1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.46.0.  By combining all the individual C code files into this
4** single large file, the entire code can be compiled as a single translation
5** unit.  This allows many compilers to do optimizations that would not be
6** possible if the files were compiled separately.  Performance improvements
7** of 5% or more are commonly seen when SQLite is compiled as a single
8** translation unit.
9**
10** This file is all you need to compile SQLite.  To use SQLite in other
11** programs, you need this file and the "sqlite3.h" header file that defines
12** the programming interface to the SQLite library.  (If you do not have
13** the "sqlite3.h" header file at hand, you will find a copy embedded within
14** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15** of the embedded sqlite3.h header file.) Additional code files may be needed
16** if you want a wrapper to interface SQLite with your choice of programming
17** language. The code for the "sqlite3" command-line shell is also in a
18** separate file. This file contains only code for the core SQLite library.
19**
20** The content in this amalgamation comes from Fossil check-in
21** 96c92aba00c8375bc32fafcdf12429c58bd8.
22*/
23#define SQLITE_CORE 1
24#define SQLITE_AMALGAMATION 1
25#ifndef SQLITE_PRIVATE
26# define SQLITE_PRIVATE static
27#endif
28/************** Begin file sqliteInt.h ***************************************/
29/*
30** 2001 September 15
31**
32** The author disclaims copyright to this source code.  In place of
33** a legal notice, here is a blessing:
34**
35**    May you do good and not evil.
36**    May you find forgiveness for yourself and forgive others.
37**    May you share freely, never taking more than you give.
38**
39*************************************************************************
40** Internal interface definitions for SQLite.
41**
42*/
43#ifndef SQLITEINT_H
44#define SQLITEINT_H
45
46/* Special Comments:
47**
48** Some comments have special meaning to the tools that measure test
49** coverage:
50**
51**    NO_TEST                     - The branches on this line are not
52**                                  measured by branch coverage.  This is
53**                                  used on lines of code that actually
54**                                  implement parts of coverage testing.
55**
56**    OPTIMIZATION-IF-TRUE        - This branch is allowed to always be false
57**                                  and the correct answer is still obtained,
58**                                  though perhaps more slowly.
59**
60**    OPTIMIZATION-IF-FALSE       - This branch is allowed to always be true
61**                                  and the correct answer is still obtained,
62**                                  though perhaps more slowly.
63**
64**    PREVENTS-HARMLESS-OVERREAD  - This branch prevents a buffer overread
65**                                  that would be harmless and undetectable
66**                                  if it did occur.
67**
68** In all cases, the special comment must be enclosed in the usual
69** slash-asterisk...asterisk-slash comment marks, with no spaces between the
70** asterisks and the comment text.
71*/
72
73/*
74** Make sure the Tcl calling convention macro is defined.  This macro is
75** only used by test code and Tcl integration code.
76*/
77#ifndef SQLITE_TCLAPI
78#  define SQLITE_TCLAPI
79#endif
80
81/*
82** Include the header file used to customize the compiler options for MSVC.
83** This should be done first so that it can successfully prevent spurious
84** compiler warnings due to subsequent content in this file and other files
85** that are included by this file.
86*/
87/************** Include msvc.h in the middle of sqliteInt.h ******************/
88/************** Begin file msvc.h ********************************************/
89/*
90** 2015 January 12
91**
92** The author disclaims copyright to this source code.  In place of
93** a legal notice, here is a blessing:
94**
95**    May you do good and not evil.
96**    May you find forgiveness for yourself and forgive others.
97**    May you share freely, never taking more than you give.
98**
99******************************************************************************
100**
101** This file contains code that is specific to MSVC.
102*/
103#ifndef SQLITE_MSVC_H
104#define SQLITE_MSVC_H
105
106#if defined(_MSC_VER)
107#pragma warning(disable : 4054)
108#pragma warning(disable : 4055)
109#pragma warning(disable : 4100)
110#pragma warning(disable : 4127)
111#pragma warning(disable : 4130)
112#pragma warning(disable : 4152)
113#pragma warning(disable : 4189)
114#pragma warning(disable : 4206)
115#pragma warning(disable : 4210)
116#pragma warning(disable : 4232)
117#pragma warning(disable : 4244)
118#pragma warning(disable : 4305)
119#pragma warning(disable : 4306)
120#pragma warning(disable : 4702)
121#pragma warning(disable : 4706)
122#endif /* defined(_MSC_VER) */
123
124#if defined(_MSC_VER) && !defined(_WIN64)
125#undef SQLITE_4_BYTE_ALIGNED_MALLOC
126#define SQLITE_4_BYTE_ALIGNED_MALLOC
127#endif /* defined(_MSC_VER) && !defined(_WIN64) */
128
129#if !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800
130#define HAVE_LOG2 0
131#endif /* !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800 */
132
133#endif /* SQLITE_MSVC_H */
134
135/************** End of msvc.h ************************************************/
136/************** Continuing where we left off in sqliteInt.h ******************/
137
138/*
139** Special setup for VxWorks
140*/
141/************** Include vxworks.h in the middle of sqliteInt.h ***************/
142/************** Begin file vxworks.h *****************************************/
143/*
144** 2015-03-02
145**
146** The author disclaims copyright to this source code.  In place of
147** a legal notice, here is a blessing:
148**
149**    May you do good and not evil.
150**    May you find forgiveness for yourself and forgive others.
151**    May you share freely, never taking more than you give.
152**
153******************************************************************************
154**
155** This file contains code that is specific to Wind River's VxWorks
156*/
157#if defined(__RTP__) || defined(_WRS_KERNEL)
158/* This is VxWorks.  Set up things specially for that OS
159*/
160#include <vxWorks.h>
161#include <pthread.h>  /* amalgamator: dontcache */
162#define OS_VXWORKS 1
163#define SQLITE_OS_OTHER 0
164#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
165#define SQLITE_OMIT_LOAD_EXTENSION 1
166#define SQLITE_ENABLE_LOCKING_STYLE 0
167#define HAVE_UTIME 1
168#else
169/* This is not VxWorks. */
170#define OS_VXWORKS 0
171#define HAVE_FCHOWN 1
172#define HAVE_READLINK 1
173#define HAVE_LSTAT 1
174#endif /* defined(_WRS_KERNEL) */
175
176/************** End of vxworks.h *********************************************/
177/************** Continuing where we left off in sqliteInt.h ******************/
178
179/*
180** These #defines should enable >2GB file support on POSIX if the
181** underlying operating system supports it.  If the OS lacks
182** large file support, or if the OS is windows, these should be no-ops.
183**
184** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
185** system #includes.  Hence, this block of code must be the very first
186** code in all source files.
187**
188** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
189** on the compiler command line.  This is necessary if you are compiling
190** on a recent machine (ex: Red Hat 7.2) but you want your code to work
191** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
192** without this option, LFS is enable.  But LFS does not exist in the kernel
193** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
194** portability you should omit LFS.
195**
196** The previous paragraph was written in 2005.  (This paragraph is written
197** on 2008-11-28.) These days, all Linux kernels support large files, so
198** you should probably leave LFS enabled.  But some embedded platforms might
199** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
200**
201** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
202*/
203#ifndef SQLITE_DISABLE_LFS
204# define _LARGE_FILE       1
205# ifndef _FILE_OFFSET_BITS
206#   define _FILE_OFFSET_BITS 64
207# endif
208# define _LARGEFILE_SOURCE 1
209#endif
210
211/* The GCC_VERSION and MSVC_VERSION macros are used to
212** conditionally include optimizations for each of these compilers.  A
213** value of 0 means that compiler is not being used.  The
214** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
215** optimizations, and hence set all compiler macros to 0
216**
217** There was once also a CLANG_VERSION macro.  However, we learn that the
218** version numbers in clang are for "marketing" only and are inconsistent
219** and unreliable.  Fortunately, all versions of clang also recognize the
220** gcc version numbers and have reasonable settings for gcc version numbers,
221** so the GCC_VERSION macro will be set to a correct non-zero value even
222** when compiling with clang.
223*/
224#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
225# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
226#else
227# define GCC_VERSION 0
228#endif
229#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
230# define MSVC_VERSION _MSC_VER
231#else
232# define MSVC_VERSION 0
233#endif
234
235/*
236** Some C99 functions in "math.h" are only present for MSVC when its version
237** is associated with Visual Studio 2013 or higher.
238*/
239#ifndef SQLITE_HAVE_C99_MATH_FUNCS
240# if MSVC_VERSION==0 || MSVC_VERSION>=1800
241#  define SQLITE_HAVE_C99_MATH_FUNCS (1)
242# else
243#  define SQLITE_HAVE_C99_MATH_FUNCS (0)
244# endif
245#endif
246
247/* Needed for various definitions... */
248#if defined(__GNUC__) && !defined(_GNU_SOURCE)
249# define _GNU_SOURCE
250#endif
251
252#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
253# define _BSD_SOURCE
254#endif
255
256/*
257** Macro to disable warnings about missing "break" at the end of a "case".
258*/
259#if GCC_VERSION>=7000000
260# define deliberate_fall_through __attribute__((fallthrough));
261#else
262# define deliberate_fall_through
263#endif
264
265/*
266** For MinGW, check to see if we can include the header file containing its
267** version information, among other things.  Normally, this internal MinGW
268** header file would [only] be included automatically by other MinGW header
269** files; however, the contained version information is now required by this
270** header file to work around binary compatibility issues (see below) and
271** this is the only known way to reliably obtain it.  This entire #if block
272** would be completely unnecessary if there was any other way of detecting
273** MinGW via their preprocessor (e.g. if they customized their GCC to define
274** some MinGW-specific macros).  When compiling for MinGW, either the
275** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
276** defined; otherwise, detection of conditions specific to MinGW will be
277** disabled.
278*/
279#if defined(_HAVE_MINGW_H)
280# include "mingw.h"
281#elif defined(_HAVE__MINGW_H)
282# include "_mingw.h"
283#endif
284
285/*
286** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
287** define is required to maintain binary compatibility with the MSVC runtime
288** library in use (e.g. for Windows XP).
289*/
290#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
291    defined(_WIN32) && !defined(_WIN64) && \
292    defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
293    defined(__MSVCRT__)
294# define _USE_32BIT_TIME_T
295#endif
296
297/* Optionally #include a user-defined header, whereby compilation options
298** may be set prior to where they take effect, but after platform setup.
299** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
300** file.
301*/
302#ifdef SQLITE_CUSTOM_INCLUDE
303# define INC_STRINGIFY_(f) #f
304# define INC_STRINGIFY(f) INC_STRINGIFY_(f)
305# include INC_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
306#endif
307
308/* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
309** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
310** MinGW.
311*/
312/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
313/************** Begin file sqlite3.h *****************************************/
314/*
315** 2001-09-15
316**
317** The author disclaims copyright to this source code.  In place of
318** a legal notice, here is a blessing:
319**
320**    May you do good and not evil.
321**    May you find forgiveness for yourself and forgive others.
322**    May you share freely, never taking more than you give.
323**
324*************************************************************************
325** This header file defines the interface that the SQLite library
326** presents to client programs.  If a C-function, structure, datatype,
327** or constant definition does not appear in this file, then it is
328** not a published API of SQLite, is subject to change without
329** notice, and should not be referenced by programs that use SQLite.
330**
331** Some of the definitions that are in this file are marked as
332** "experimental".  Experimental interfaces are normally new
333** features recently added to SQLite.  We do not anticipate changes
334** to experimental interfaces but reserve the right to make minor changes
335** if experience from use "in the wild" suggest such changes are prudent.
336**
337** The official C-language API documentation for SQLite is derived
338** from comments in this file.  This file is the authoritative source
339** on how SQLite interfaces are supposed to operate.
340**
341** The name of this file under configuration management is "sqlite.h.in".
342** The makefile makes some minor changes to this file (such as inserting
343** the version number) and changes its name to "sqlite3.h" as
344** part of the build process.
345*/
346#ifndef SQLITE3_H
347#define SQLITE3_H
348#include <stdarg.h>     /* Needed for the definition of va_list */
349
350/*
351** Make sure we can call this stuff from C++.
352*/
353#if 0
354extern "C" {
355#endif
356
357
358/*
359** Facilitate override of interface linkage and calling conventions.
360** Be aware that these macros may not be used within this particular
361** translation of the amalgamation and its associated header file.
362**
363** The SQLITE_EXTERN and SQLITE_API macros are used to instruct the
364** compiler that the target identifier should have external linkage.
365**
366** The SQLITE_CDECL macro is used to set the calling convention for
367** public functions that accept a variable number of arguments.
368**
369** The SQLITE_APICALL macro is used to set the calling convention for
370** public functions that accept a fixed number of arguments.
371**
372** The SQLITE_STDCALL macro is no longer used and is now deprecated.
373**
374** The SQLITE_CALLBACK macro is used to set the calling convention for
375** function pointers.
376**
377** The SQLITE_SYSAPI macro is used to set the calling convention for
378** functions provided by the operating system.
379**
380** Currently, the SQLITE_CDECL, SQLITE_APICALL, SQLITE_CALLBACK, and
381** SQLITE_SYSAPI macros are used only when building for environments
382** that require non-default calling conventions.
383*/
384#ifndef SQLITE_EXTERN
385# define SQLITE_EXTERN extern
386#endif
387#ifndef SQLITE_API
388# define SQLITE_API
389#endif
390#ifndef SQLITE_CDECL
391# define SQLITE_CDECL
392#endif
393#ifndef SQLITE_APICALL
394# define SQLITE_APICALL
395#endif
396#ifndef SQLITE_STDCALL
397# define SQLITE_STDCALL SQLITE_APICALL
398#endif
399#ifndef SQLITE_CALLBACK
400# define SQLITE_CALLBACK
401#endif
402#ifndef SQLITE_SYSAPI
403# define SQLITE_SYSAPI
404#endif
405
406/*
407** These no-op macros are used in front of interfaces to mark those
408** interfaces as either deprecated or experimental.  New applications
409** should not use deprecated interfaces - they are supported for backwards
410** compatibility only.  Application writers should be aware that
411** experimental interfaces are subject to change in point releases.
412**
413** These macros used to resolve to various kinds of compiler magic that
414** would generate warning messages when they were used.  But that
415** compiler magic ended up generating such a flurry of bug reports
416** that we have taken it all out and gone back to using simple
417** noop macros.
418*/
419#define SQLITE_DEPRECATED
420#define SQLITE_EXPERIMENTAL
421
422/*
423** Ensure these symbols were not defined by some previous header file.
424*/
425#ifdef SQLITE_VERSION
426# undef SQLITE_VERSION
427#endif
428#ifdef SQLITE_VERSION_NUMBER
429# undef SQLITE_VERSION_NUMBER
430#endif
431
432/*
433** CAPI3REF: Compile-Time Library Version Numbers
434**
435** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
436** evaluates to a string literal that is the SQLite version in the
437** format "X.Y.Z" where X is the major version number (always 3 for
438** SQLite3) and Y is the minor version number and Z is the release number.)^
439** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
440** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
441** numbers used in [SQLITE_VERSION].)^
442** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
443** be larger than the release from which it is derived.  Either Y will
444** be held constant and Z will be incremented or else Y will be incremented
445** and Z will be reset to zero.
446**
447** Since [version 3.6.18] ([dateof:3.6.18]),
448** SQLite source code has been stored in the
449** <a href="http://www.fossil-scm.org/">Fossil configuration management
450** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
451** a string which identifies a particular check-in of SQLite
452** within its configuration management system.  ^The SQLITE_SOURCE_ID
453** string contains the date and time of the check-in (UTC) and a SHA1
454** or SHA3-256 hash of the entire source tree.  If the source code has
455** been edited in any way since it was last checked in, then the last
456** four hexadecimal digits of the hash may be modified.
457**
458** See also: [sqlite3_libversion()],
459** [sqlite3_libversion_number()], [sqlite3_sourceid()],
460** [sqlite_version()] and [sqlite_source_id()].
461*/
462#define SQLITE_VERSION        "3.46.0"
463#define SQLITE_VERSION_NUMBER 3046000
464#define SQLITE_SOURCE_ID      "2024-05-23 13:25:27 96c92aba00c8375bc32fafcdf12429c58bd8aabfcadab6683e35bbb9cdebf19e"
465
466/*
467** CAPI3REF: Run-Time Library Version Numbers
468** KEYWORDS: sqlite3_version sqlite3_sourceid
469**
470** These interfaces provide the same information as the [SQLITE_VERSION],
471** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
472** but are associated with the library instead of the header file.  ^(Cautious
473** programmers might include assert() statements in their application to
474** verify that values returned by these interfaces match the macros in
475** the header, and thus ensure that the application is
476** compiled with matching library and header files.
477**
478** <blockquote><pre>
479** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
480** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
481** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
482** </pre></blockquote>)^
483**
484** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
485** macro.  ^The sqlite3_libversion() function returns a pointer to the
486** to the sqlite3_version[] string constant.  The sqlite3_libversion()
487** function is provided for use in DLLs since DLL users usually do not have
488** direct access to string constants within the DLL.  ^The
489** sqlite3_libversion_number() function returns an integer equal to
490** [SQLITE_VERSION_NUMBER].  ^(The sqlite3_sourceid() function returns
491** a pointer to a string constant whose value is the same as the
492** [SQLITE_SOURCE_ID] C preprocessor macro.  Except if SQLite is built
493** using an edited copy of [the amalgamation], then the last four characters
494** of the hash might be different from [SQLITE_SOURCE_ID].)^
495**
496** See also: [sqlite_version()] and [sqlite_source_id()].
497*/
498SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
499SQLITE_API const char *sqlite3_libversion(void);
500SQLITE_API const char *sqlite3_sourceid(void);
501SQLITE_API int sqlite3_libversion_number(void);
502
503/*
504** CAPI3REF: Run-Time Library Compilation Options Diagnostics
505**
506** ^The sqlite3_compileoption_used() function returns 0 or 1
507** indicating whether the specified option was defined at
508** compile time.  ^The SQLITE_ prefix may be omitted from the
509** option name passed to sqlite3_compileoption_used().
510**
511** ^The sqlite3_compileoption_get() function allows iterating
512** over the list of options that were defined at compile time by
513** returning the N-th compile time option string.  ^If N is out of range,
514** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
515** prefix is omitted from any strings returned by
516** sqlite3_compileoption_get().
517**
518** ^Support for the diagnostic functions sqlite3_compileoption_used()
519** and sqlite3_compileoption_get() may be omitted by specifying the
520** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
521**
522** See also: SQL functions [sqlite_compileoption_used()] and
523** [sqlite_compileoption_get()] and the [compile_options pragma].
524*/
525#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
526SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
527SQLITE_API const char *sqlite3_compileoption_get(int N);
528#else
529# define sqlite3_compileoption_used(X) 0
530# define sqlite3_compileoption_get(X)  ((void*)0)
531#endif
532
533/*
534** CAPI3REF: Test To See If The Library Is Threadsafe
535**
536** ^The sqlite3_threadsafe() function returns zero if and only if
537** SQLite was compiled with mutexing code omitted due to the
538** [SQLITE_THREADSAFE] compile-time option being set to 0.
539**
540** SQLite can be compiled with or without mutexes.  When
541** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
542** are enabled and SQLite is threadsafe.  When the
543** [SQLITE_THREADSAFE] macro is 0,
544** the mutexes are omitted.  Without the mutexes, it is not safe
545** to use SQLite concurrently from more than one thread.
546**
547** Enabling mutexes incurs a measurable performance penalty.
548** So if speed is of utmost importance, it makes sense to disable
549** the mutexes.  But for maximum safety, mutexes should be enabled.
550** ^The default behavior is for mutexes to be enabled.
551**
552** This interface can be used by an application to make sure that the
553** version of SQLite that it is linking against was compiled with
554** the desired setting of the [SQLITE_THREADSAFE] macro.
555**
556** This interface only reports on the compile-time mutex setting
557** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
558** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
559** can be fully or partially disabled using a call to [sqlite3_config()]
560** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
561** or [SQLITE_CONFIG_SERIALIZED].  ^(The return value of the
562** sqlite3_threadsafe() function shows only the compile-time setting of
563** thread safety, not any run-time changes to that setting made by
564** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
565** is unchanged by calls to sqlite3_config().)^
566**
567** See the [threading mode] documentation for additional information.
568*/
569SQLITE_API int sqlite3_threadsafe(void);
570
571/*
572** CAPI3REF: Database Connection Handle
573** KEYWORDS: {database connection} {database connections}
574**
575** Each open SQLite database is represented by a pointer to an instance of
576** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
577** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
578** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
579** and [sqlite3_close_v2()] are its destructors.  There are many other
580** interfaces (such as
581** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
582** [sqlite3_busy_timeout()] to name but three) that are methods on an
583** sqlite3 object.
584*/
585typedef struct sqlite3 sqlite3;
586
587/*
588** CAPI3REF: 64-Bit Integer Types
589** KEYWORDS: sqlite_int64 sqlite_uint64
590**
591** Because there is no cross-platform way to specify 64-bit integer types
592** SQLite includes typedefs for 64-bit signed and unsigned integers.
593**
594** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
595** The sqlite_int64 and sqlite_uint64 types are supported for backwards
596** compatibility only.
597**
598** ^The sqlite3_int64 and sqlite_int64 types can store integer values
599** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
600** sqlite3_uint64 and sqlite_uint64 types can store integer values
601** between 0 and +18446744073709551615 inclusive.
602*/
603#ifdef SQLITE_INT64_TYPE
604  typedef SQLITE_INT64_TYPE sqlite_int64;
605# ifdef SQLITE_UINT64_TYPE
606    typedef SQLITE_UINT64_TYPE sqlite_uint64;
607# else
608    typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
609# endif
610#elif defined(_MSC_VER) || defined(__BORLANDC__)
611  typedef __int64 sqlite_int64;
612  typedef unsigned __int64 sqlite_uint64;
613#else
614  typedef long long int sqlite_int64;
615  typedef unsigned long long int sqlite_uint64;
616#endif
617typedef sqlite_int64 sqlite3_int64;
618typedef sqlite_uint64 sqlite3_uint64;
619
620/*
621** If compiling for a processor that lacks floating point support,
622** substitute integer for floating-point.
623*/
624#ifdef SQLITE_OMIT_FLOATING_POINT
625# define double sqlite3_int64
626#endif
627
628/*
629** CAPI3REF: Closing A Database Connection
630** DESTRUCTOR: sqlite3
631**
632** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
633** for the [sqlite3] object.
634** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
635** the [sqlite3] object is successfully destroyed and all associated
636** resources are deallocated.
637**
638** Ideally, applications should [sqlite3_finalize | finalize] all
639** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and
640** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
641** with the [sqlite3] object prior to attempting to close the object.
642** ^If the database connection is associated with unfinalized prepared
643** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then
644** sqlite3_close() will leave the database connection open and return
645** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared
646** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,
647** it returns [SQLITE_OK] regardless, but instead of deallocating the database
648** connection immediately, it marks the database connection as an unusable
649** "zombie" and makes arrangements to automatically deallocate the database
650** connection after all prepared statements are finalized, all BLOB handles
651** are closed, and all backups have finished. The sqlite3_close_v2() interface
652** is intended for use with host languages that are garbage collected, and
653** where the order in which destructors are called is arbitrary.
654**
655** ^If an [sqlite3] object is destroyed while a transaction is open,
656** the transaction is automatically rolled back.
657**
658** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
659** must be either a NULL
660** pointer or an [sqlite3] object pointer obtained
661** from [sqlite3_open()], [sqlite3_open16()], or
662** [sqlite3_open_v2()], and not previously closed.
663** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
664** argument is a harmless no-op.
665*/
666SQLITE_API int sqlite3_close(sqlite3*);
667SQLITE_API int sqlite3_close_v2(sqlite3*);
668
669/*
670** The type for a callback function.
671** This is legacy and deprecated.  It is included for historical
672** compatibility and is not documented.
673*/
674typedef int (*sqlite3_callback)(void*,int,char**, char**);
675
676/*
677** CAPI3REF: One-Step Query Execution Interface
678** METHOD: sqlite3
679**
680** The sqlite3_exec() interface is a convenience wrapper around
681** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
682** that allows an application to run multiple statements of SQL
683** without having to use a lot of C code.
684**
685** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
686** semicolon-separate SQL statements passed into its 2nd argument,
687** in the context of the [database connection] passed in as its 1st
688** argument.  ^If the callback function of the 3rd argument to
689** sqlite3_exec() is not NULL, then it is invoked for each result row
690** coming out of the evaluated SQL statements.  ^The 4th argument to
691** sqlite3_exec() is relayed through to the 1st argument of each
692** callback invocation.  ^If the callback pointer to sqlite3_exec()
693** is NULL, then no callback is ever invoked and result rows are
694** ignored.
695**
696** ^If an error occurs while evaluating the SQL statements passed into
697** sqlite3_exec(), then execution of the current statement stops and
698** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
699** is not NULL then any error message is written into memory obtained
700** from [sqlite3_malloc()] and passed back through the 5th parameter.
701** To avoid memory leaks, the application should invoke [sqlite3_free()]
702** on error message strings returned through the 5th parameter of
703** sqlite3_exec() after the error message string is no longer needed.
704** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
705** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
706** NULL before returning.
707**
708** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
709** routine returns SQLITE_ABORT without invoking the callback again and
710** without running any subsequent SQL statements.
711**
712** ^The 2nd argument to the sqlite3_exec() callback function is the
713** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
714** callback is an array of pointers to strings obtained as if from
715** [sqlite3_column_text()], one for each column.  ^If an element of a
716** result row is NULL then the corresponding string pointer for the
717** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
718** sqlite3_exec() callback is an array of pointers to strings where each
719** entry represents the name of corresponding result column as obtained
720** from [sqlite3_column_name()].
721**
722** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
723** to an empty string, or a pointer that contains only whitespace and/or
724** SQL comments, then no SQL statements are evaluated and the database
725** is not changed.
726**
727** Restrictions:
728**
729** <ul>
730** <li> The application must ensure that the 1st parameter to sqlite3_exec()
731**      is a valid and open [database connection].
732** <li> The application must not close the [database connection] specified by
733**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
734** <li> The application must not modify the SQL statement text passed into
735**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
736** <li> The application must not dereference the arrays or string pointers
737**       passed as the 3rd and 4th callback parameters after it returns.
738** </ul>
739*/
740SQLITE_API int sqlite3_exec(
741  sqlite3*,                                  /* An open database */
742  const char *sql,                           /* SQL to be evaluated */
743  int (*callback)(void*,int,char**,char**),  /* Callback function */
744  void *,                                    /* 1st argument to callback */
745  char **errmsg                              /* Error msg written here */
746);
747
748/*
749** CAPI3REF: Result Codes
750** KEYWORDS: {result code definitions}
751**
752** Many SQLite functions return an integer result code from the set shown
753** here in order to indicate success or failure.
754**
755** New error codes may be added in future versions of SQLite.
756**
757** See also: [extended result code definitions]
758*/
759#define SQLITE_OK           0   /* Successful result */
760/* beginning-of-error-codes */
761#define SQLITE_ERROR        1   /* Generic error */
762#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
763#define SQLITE_PERM         3   /* Access permission denied */
764#define SQLITE_ABORT        4   /* Callback routine requested an abort */
765#define SQLITE_BUSY         5   /* The database file is locked */
766#define SQLITE_LOCKED       6   /* A table in the database is locked */
767#define SQLITE_NOMEM        7   /* A malloc() failed */
768#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
769#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
770#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
771#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
772#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
773#define SQLITE_FULL        13   /* Insertion failed because database is full */
774#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
775#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
776#define SQLITE_EMPTY       16   /* Internal use only */
777#define SQLITE_SCHEMA      17   /* The database schema changed */
778#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
779#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
780#define SQLITE_MISMATCH    20   /* Data type mismatch */
781#define SQLITE_MISUSE      21   /* Library used incorrectly */
782#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
783#define SQLITE_AUTH        23   /* Authorization denied */
784#define SQLITE_FORMAT      24   /* Not used */
785#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
786#define SQLITE_NOTADB      26   /* File opened that is not a database file */
787#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
788#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
789#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
790#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
791/* end-of-error-codes */
792
793/*
794** CAPI3REF: Extended Result Codes
795** KEYWORDS: {extended result code definitions}
796**
797** In its default configuration, SQLite API routines return one of 30 integer
798** [result codes].  However, experience has shown that many of
799** these result codes are too coarse-grained.  They do not provide as
800** much information about problems as programmers might like.  In an effort to
801** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
802** and later) include
803** support for additional result codes that provide more detailed information
804** about errors. These [extended result codes] are enabled or disabled
805** on a per database connection basis using the
806** [sqlite3_extended_result_codes()] API.  Or, the extended code for
807** the most recent error can be obtained using
808** [sqlite3_extended_errcode()].
809*/
810#define SQLITE_ERROR_MISSING_COLLSEQ   (SQLITE_ERROR | (1<<8))
811#define SQLITE_ERROR_RETRY             (SQLITE_ERROR | (2<<8))
812#define SQLITE_ERROR_SNAPSHOT          (SQLITE_ERROR | (3<<8))
813#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
814#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
815#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
816#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
817#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
818#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
819#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
820#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
821#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
822#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
823#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
824#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
825#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
826#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
827#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
828#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
829#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
830#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
831#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
832#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
833#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
834#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
835#define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
836#define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
837#define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
838#define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
839#define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))
840#define SQLITE_IOERR_AUTH              (SQLITE_IOERR | (28<<8))
841#define SQLITE_IOERR_BEGIN_ATOMIC      (SQLITE_IOERR | (29<<8))
842#define SQLITE_IOERR_COMMIT_ATOMIC     (SQLITE_IOERR | (30<<8))
843#define SQLITE_IOERR_ROLLBACK_ATOMIC   (SQLITE_IOERR | (31<<8))
844#define SQLITE_IOERR_DATA              (SQLITE_IOERR | (32<<8))
845#define SQLITE_IOERR_CORRUPTFS         (SQLITE_IOERR | (33<<8))
846#define SQLITE_IOERR_IN_PAGE           (SQLITE_IOERR | (34<<8))
847#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
848#define SQLITE_LOCKED_VTAB             (SQLITE_LOCKED |  (2<<8))
849#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
850#define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
851#define SQLITE_BUSY_TIMEOUT            (SQLITE_BUSY   |  (3<<8))
852#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
853#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
854#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
855#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
856#define SQLITE_CANTOPEN_DIRTYWAL       (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
857#define SQLITE_CANTOPEN_SYMLINK        (SQLITE_CANTOPEN | (6<<8))
858#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
859#define SQLITE_CORRUPT_SEQUENCE        (SQLITE_CORRUPT | (2<<8))
860#define SQLITE_CORRUPT_INDEX           (SQLITE_CORRUPT | (3<<8))
861#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
862#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
863#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
864#define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
865#define SQLITE_READONLY_CANTINIT       (SQLITE_READONLY | (5<<8))
866#define SQLITE_READONLY_DIRECTORY      (SQLITE_READONLY | (6<<8))
867#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
868#define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
869#define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
870#define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
871#define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
872#define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
873#define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
874#define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
875#define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
876#define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
877#define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
878#define SQLITE_CONSTRAINT_PINNED       (SQLITE_CONSTRAINT |(11<<8))
879#define SQLITE_CONSTRAINT_DATATYPE     (SQLITE_CONSTRAINT |(12<<8))
880#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
881#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
882#define SQLITE_NOTICE_RBU              (SQLITE_NOTICE | (3<<8))
883#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
884#define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
885#define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
886#define SQLITE_OK_SYMLINK              (SQLITE_OK | (2<<8)) /* internal use only */
887
888/*
889** CAPI3REF: Flags For File Open Operations
890**
891** These bit values are intended for use in the
892** 3rd parameter to the [sqlite3_open_v2()] interface and
893** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
894**
895** Only those flags marked as "Ok for sqlite3_open_v2()" may be
896** used as the third argument to the [sqlite3_open_v2()] interface.
897** The other flags have historically been ignored by sqlite3_open_v2(),
898** though future versions of SQLite might change so that an error is
899** raised if any of the disallowed bits are passed into sqlite3_open_v2().
900** Applications should not depend on the historical behavior.
901**
902** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into
903** [sqlite3_open_v2()] does *not* cause the underlying database file
904** to be opened using O_EXCL.  Passing SQLITE_OPEN_EXCLUSIVE into
905** [sqlite3_open_v2()] has historically be a no-op and might become an
906** error in future versions of SQLite.
907*/
908#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
909#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
910#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
911#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
912#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
913#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
914#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
915#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
916#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
917#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
918#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
919#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
920#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
921#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
922#define SQLITE_OPEN_SUPER_JOURNAL    0x00004000  /* VFS only */
923#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
924#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
925#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
926#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
927#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
928#define SQLITE_OPEN_NOFOLLOW         0x01000000  /* Ok for sqlite3_open_v2() */
929#define SQLITE_OPEN_EXRESCODE        0x02000000  /* Extended result codes */
930
931/* Reserved:                         0x00F00000 */
932/* Legacy compatibility: */
933#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
934
935
936/*
937** CAPI3REF: Device Characteristics
938**
939** The xDeviceCharacteristics method of the [sqlite3_io_methods]
940** object returns an integer which is a vector of these
941** bit values expressing I/O characteristics of the mass storage
942** device that holds the file that the [sqlite3_io_methods]
943** refers to.
944**
945** The SQLITE_IOCAP_ATOMIC property means that all writes of
946** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
947** mean that writes of blocks that are nnn bytes in size and
948** are aligned to an address which is an integer multiple of
949** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
950** that when data is appended to a file, the data is appended
951** first then the size of the file is extended, never the other
952** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
953** information is written to disk in the same order as calls
954** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
955** after reboot following a crash or power loss, the only bytes in a
956** file that were written at the application level might have changed
957** and that adjacent bytes, even bytes within the same sector are
958** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
959** flag indicates that a file cannot be deleted when open.  The
960** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
961** read-only media and cannot be changed even by processes with
962** elevated privileges.
963**
964** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
965** filesystem supports doing multiple write operations atomically when those
966** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
967** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
968*/
969#define SQLITE_IOCAP_ATOMIC                 0x00000001
970#define SQLITE_IOCAP_ATOMIC512              0x00000002
971#define SQLITE_IOCAP_ATOMIC1K               0x00000004
972#define SQLITE_IOCAP_ATOMIC2K               0x00000008
973#define SQLITE_IOCAP_ATOMIC4K               0x00000010
974#define SQLITE_IOCAP_ATOMIC8K               0x00000020
975#define SQLITE_IOCAP_ATOMIC16K              0x00000040
976#define SQLITE_IOCAP_ATOMIC32K              0x00000080
977#define SQLITE_IOCAP_ATOMIC64K              0x00000100
978#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
979#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
980#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
981#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
982#define SQLITE_IOCAP_IMMUTABLE              0x00002000
983#define SQLITE_IOCAP_BATCH_ATOMIC           0x00004000
984
985/*
986** CAPI3REF: File Locking Levels
987**
988** SQLite uses one of these integer values as the second
989** argument to calls it makes to the xLock() and xUnlock() methods
990** of an [sqlite3_io_methods] object.  These values are ordered from
991** lest restrictive to most restrictive.
992**
993** The argument to xLock() is always SHARED or higher.  The argument to
994** xUnlock is either SHARED or NONE.
995*/
996#define SQLITE_LOCK_NONE          0       /* xUnlock() only */
997#define SQLITE_LOCK_SHARED        1       /* xLock() or xUnlock() */
998#define SQLITE_LOCK_RESERVED      2       /* xLock() only */
999#define SQLITE_LOCK_PENDING       3       /* xLock() only */
1000#define SQLITE_LOCK_EXCLUSIVE     4       /* xLock() only */
1001
1002/*
1003** CAPI3REF: Synchronization Type Flags
1004**
1005** When SQLite invokes the xSync() method of an
1006** [sqlite3_io_methods] object it uses a combination of
1007** these integer values as the second argument.
1008**
1009** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1010** sync operation only needs to flush data to mass storage.  Inode
1011** information need not be flushed. If the lower four bits of the flag
1012** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1013** If the lower four bits equal SQLITE_SYNC_FULL, that means
1014** to use Mac OS X style fullsync instead of fsync().
1015**
1016** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1017** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1018** settings.  The [synchronous pragma] determines when calls to the
1019** xSync VFS method occur and applies uniformly across all platforms.
1020** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1021** energetic or rigorous or forceful the sync operations are and
1022** only make a difference on Mac OSX for the default SQLite code.
1023** (Third-party VFS implementations might also make the distinction
1024** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1025** operating systems natively supported by SQLite, only Mac OSX
1026** cares about the difference.)
1027*/
1028#define SQLITE_SYNC_NORMAL        0x00002
1029#define SQLITE_SYNC_FULL          0x00003
1030#define SQLITE_SYNC_DATAONLY      0x00010
1031
1032/*
1033** CAPI3REF: OS Interface Open File Handle
1034**
1035** An [sqlite3_file] object represents an open file in the
1036** [sqlite3_vfs | OS interface layer].  Individual OS interface
1037** implementations will
1038** want to subclass this object by appending additional fields
1039** for their own use.  The pMethods entry is a pointer to an
1040** [sqlite3_io_methods] object that defines methods for performing
1041** I/O operations on the open file.
1042*/
1043typedef struct sqlite3_file sqlite3_file;
1044struct sqlite3_file {
1045  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1046};
1047
1048/*
1049** CAPI3REF: OS Interface File Virtual Methods Object
1050**
1051** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1052** [sqlite3_file] object (or, more commonly, a subclass of the
1053** [sqlite3_file] object) with a pointer to an instance of this object.
1054** This object defines the methods used to perform various operations
1055** against the open file represented by the [sqlite3_file] object.
1056**
1057** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1058** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1059** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
1060** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1061** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1062** to NULL.
1063**
1064** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1065** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1066** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1067** flag may be ORed in to indicate that only the data of the file
1068** and not its inode needs to be synced.
1069**
1070** The integer values to xLock() and xUnlock() are one of
1071** <ul>
1072** <li> [SQLITE_LOCK_NONE],
1073** <li> [SQLITE_LOCK_SHARED],
1074** <li> [SQLITE_LOCK_RESERVED],
1075** <li> [SQLITE_LOCK_PENDING], or
1076** <li> [SQLITE_LOCK_EXCLUSIVE].
1077** </ul>
1078** xLock() upgrades the database file lock.  In other words, xLock() moves the
1079** database file lock in the direction NONE toward EXCLUSIVE. The argument to
1080** xLock() is always one of SHARED, RESERVED, PENDING, or EXCLUSIVE, never
1081** SQLITE_LOCK_NONE.  If the database file lock is already at or above the
1082** requested lock, then the call to xLock() is a no-op.
1083** xUnlock() downgrades the database file lock to either SHARED or NONE.
1084** If the lock is already at or below the requested lock state, then the call
1085** to xUnlock() is a no-op.
1086** The xCheckReservedLock() method checks whether any database connection,
1087** either in this process or in some other process, is holding a RESERVED,
1088** PENDING, or EXCLUSIVE lock on the file.  It returns true
1089** if such a lock exists and false otherwise.
1090**
1091** The xFileControl() method is a generic interface that allows custom
1092** VFS implementations to directly control an open file using the
1093** [sqlite3_file_control()] interface.  The second "op" argument is an
1094** integer opcode.  The third argument is a generic pointer intended to
1095** point to a structure that may contain arguments or space in which to
1096** write return values.  Potential uses for xFileControl() might be
1097** functions to enable blocking locks with timeouts, to change the
1098** locking strategy (for example to use dot-file locks), to inquire
1099** about the status of a lock, or to break stale locks.  The SQLite
1100** core reserves all opcodes less than 100 for its own use.
1101** A [file control opcodes | list of opcodes] less than 100 is available.
1102** Applications that define a custom xFileControl method should use opcodes
1103** greater than 100 to avoid conflicts.  VFS implementations should
1104** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1105** recognize.
1106**
1107** The xSectorSize() method returns the sector size of the
1108** device that underlies the file.  The sector size is the
1109** minimum write that can be performed without disturbing
1110** other bytes in the file.  The xDeviceCharacteristics()
1111** method returns a bit vector describing behaviors of the
1112** underlying device:
1113**
1114** <ul>
1115** <li> [SQLITE_IOCAP_ATOMIC]
1116** <li> [SQLITE_IOCAP_ATOMIC512]
1117** <li> [SQLITE_IOCAP_ATOMIC1K]
1118** <li> [SQLITE_IOCAP_ATOMIC2K]
1119** <li> [SQLITE_IOCAP_ATOMIC4K]
1120** <li> [SQLITE_IOCAP_ATOMIC8K]
1121** <li> [SQLITE_IOCAP_ATOMIC16K]
1122** <li> [SQLITE_IOCAP_ATOMIC32K]
1123** <li> [SQLITE_IOCAP_ATOMIC64K]
1124** <li> [SQLITE_IOCAP_SAFE_APPEND]
1125** <li> [SQLITE_IOCAP_SEQUENTIAL]
1126** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
1127** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
1128** <li> [SQLITE_IOCAP_IMMUTABLE]
1129** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
1130** </ul>
1131**
1132** The SQLITE_IOCAP_ATOMIC property means that all writes of
1133** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1134** mean that writes of blocks that are nnn bytes in size and
1135** are aligned to an address which is an integer multiple of
1136** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1137** that when data is appended to a file, the data is appended
1138** first then the size of the file is extended, never the other
1139** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1140** information is written to disk in the same order as calls
1141** to xWrite().
1142**
1143** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1144** in the unread portions of the buffer with zeros.  A VFS that
1145** fails to zero-fill short reads might seem to work.  However,
1146** failure to zero-fill short reads will eventually lead to
1147** database corruption.
1148*/
1149typedef struct sqlite3_io_methods sqlite3_io_methods;
1150struct sqlite3_io_methods {
1151  int iVersion;
1152  int (*xClose)(sqlite3_file*);
1153  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1154  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1155  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1156  int (*xSync)(sqlite3_file*, int flags);
1157  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1158  int (*xLock)(sqlite3_file*, int);
1159  int (*xUnlock)(sqlite3_file*, int);
1160  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1161  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1162  int (*xSectorSize)(sqlite3_file*);
1163  int (*xDeviceCharacteristics)(sqlite3_file*);
1164  /* Methods above are valid for version 1 */
1165  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1166  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1167  void (*xShmBarrier)(sqlite3_file*);
1168  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1169  /* Methods above are valid for version 2 */
1170  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1171  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1172  /* Methods above are valid for version 3 */
1173  /* Additional methods may be added in future releases */
1174};
1175
1176/*
1177** CAPI3REF: Standard File Control Opcodes
1178** KEYWORDS: {file control opcodes} {file control opcode}
1179**
1180** These integer constants are opcodes for the xFileControl method
1181** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1182** interface.
1183**
1184** <ul>
1185** <li>[[SQLITE_FCNTL_LOCKSTATE]]
1186** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1187** opcode causes the xFileControl method to write the current state of
1188** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1189** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1190** into an integer that the pArg argument points to.
1191** This capability is only available if SQLite is compiled with [SQLITE_DEBUG].
1192**
1193** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1194** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1195** layer a hint of how large the database file will grow to be during the
1196** current transaction.  This hint is not guaranteed to be accurate but it
1197** is often close.  The underlying VFS might choose to preallocate database
1198** file space based on this hint in order to help writes to the database
1199** file run faster.
1200**
1201** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]
1202** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
1203** implements [sqlite3_deserialize()] to set an upper bound on the size
1204** of the in-memory database.  The argument is a pointer to a [sqlite3_int64].
1205** If the integer pointed to is negative, then it is filled in with the
1206** current limit.  Otherwise the limit is set to the larger of the value
1207** of the integer pointed to and the current database size.  The integer
1208** pointed to is set to the new limit.
1209**
1210** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1211** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1212** extends and truncates the database file in chunks of a size specified
1213** by the user. The fourth argument to [sqlite3_file_control()] should
1214** point to an integer (type int) containing the new chunk-size to use
1215** for the nominated database. Allocating database file space in large
1216** chunks (say 1MB at a time), may reduce file-system fragmentation and
1217** improve performance on some systems.
1218**
1219** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1220** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1221** to the [sqlite3_file] object associated with a particular database
1222** connection.  See also [SQLITE_FCNTL_JOURNAL_POINTER].
1223**
1224** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1225** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1226** to the [sqlite3_file] object associated with the journal file (either
1227** the [rollback journal] or the [write-ahead log]) for a particular database
1228** connection.  See also [SQLITE_FCNTL_FILE_POINTER].
1229**
1230** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1231** No longer in use.
1232**
1233** <li>[[SQLITE_FCNTL_SYNC]]
1234** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1235** sent to the VFS immediately before the xSync method is invoked on a
1236** database file descriptor. Or, if the xSync method is not invoked
1237** because the user has configured SQLite with
1238** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1239** of the xSync method. In most cases, the pointer argument passed with
1240** this file-control is NULL. However, if the database file is being synced
1241** as part of a multi-database commit, the argument points to a nul-terminated
1242** string containing the transactions super-journal file name. VFSes that
1243** do not need this signal should silently ignore this opcode. Applications
1244** should not call [sqlite3_file_control()] with this opcode as doing so may
1245** disrupt the operation of the specialized VFSes that do require it.
1246**
1247** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1248** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1249** and sent to the VFS after a transaction has been committed immediately
1250** but before the database is unlocked. VFSes that do not need this signal
1251** should silently ignore this opcode. Applications should not call
1252** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1253** operation of the specialized VFSes that do require it.
1254**
1255** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1256** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1257** retry counts and intervals for certain disk I/O operations for the
1258** windows [VFS] in order to provide robustness in the presence of
1259** anti-virus programs.  By default, the windows VFS will retry file read,
1260** file write, and file delete operations up to 10 times, with a delay
1261** of 25 milliseconds before the first retry and with the delay increasing
1262** by an additional 25 milliseconds with each subsequent retry.  This
1263** opcode allows these two values (10 retries and 25 milliseconds of delay)
1264** to be adjusted.  The values are changed for all database connections
1265** within the same process.  The argument is a pointer to an array of two
1266** integers where the first integer is the new retry count and the second
1267** integer is the delay.  If either integer is negative, then the setting
1268** is not changed but instead the prior value of that setting is written
1269** into the array entry, allowing the current retry settings to be
1270** interrogated.  The zDbName parameter is ignored.
1271**
1272** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1273** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1274** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1275** write ahead log ([WAL file]) and shared memory
1276** files used for transaction control
1277** are automatically deleted when the latest connection to the database
1278** closes.  Setting persistent WAL mode causes those files to persist after
1279** close.  Persisting the files is useful when other processes that do not
1280** have write permission on the directory containing the database file want
1281** to read the database file, as the WAL and shared memory files must exist
1282** in order for the database to be readable.  The fourth parameter to
1283** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1284** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1285** WAL mode.  If the integer is -1, then it is overwritten with the current
1286** WAL persistence setting.
1287**
1288** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1289** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1290** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1291** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1292** xDeviceCharacteristics methods. The fourth parameter to
1293** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1294** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1295** mode.  If the integer is -1, then it is overwritten with the current
1296** zero-damage mode setting.
1297**
1298** <li>[[SQLITE_FCNTL_OVERWRITE]]
1299** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1300** a write transaction to indicate that, unless it is rolled back for some
1301** reason, the entire database file will be overwritten by the current
1302** transaction. This is used by VACUUM operations.
1303**
1304** <li>[[SQLITE_FCNTL_VFSNAME]]
1305** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1306** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1307** final bottom-level VFS are written into memory obtained from
1308** [sqlite3_malloc()] and the result is stored in the char* variable
1309** that the fourth parameter of [sqlite3_file_control()] points to.
1310** The caller is responsible for freeing the memory when done.  As with
1311** all file-control actions, there is no guarantee that this will actually
1312** do anything.  Callers should initialize the char* variable to a NULL
1313** pointer in case this file-control is not implemented.  This file-control
1314** is intended for diagnostic use only.
1315**
1316** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1317** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1318** [VFSes] currently in use.  ^(The argument X in
1319** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1320** of type "[sqlite3_vfs] **".  This opcodes will set *X
1321** to a pointer to the top-level VFS.)^
1322** ^When there are multiple VFS shims in the stack, this opcode finds the
1323** upper-most shim only.
1324**
1325** <li>[[SQLITE_FCNTL_PRAGMA]]
1326** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1327** file control is sent to the open [sqlite3_file] object corresponding
1328** to the database file to which the pragma statement refers. ^The argument
1329** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1330** pointers to strings (char**) in which the second element of the array
1331** is the name of the pragma and the third element is the argument to the
1332** pragma or NULL if the pragma has no argument.  ^The handler for an
1333** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1334** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1335** or the equivalent and that string will become the result of the pragma or
1336** the error message if the pragma fails. ^If the
1337** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1338** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1339** file control returns [SQLITE_OK], then the parser assumes that the
1340** VFS has handled the PRAGMA itself and the parser generates a no-op
1341** prepared statement if result string is NULL, or that returns a copy
1342** of the result string if the string is non-NULL.
1343** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1344** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1345** that the VFS encountered an error while handling the [PRAGMA] and the
1346** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1347** file control occurs at the beginning of pragma statement analysis and so
1348** it is able to override built-in [PRAGMA] statements.
1349**
1350** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1351** ^The [SQLITE_FCNTL_BUSYHANDLER]
1352** file-control may be invoked by SQLite on the database file handle
1353** shortly after it is opened in order to provide a custom VFS with access
1354** to the connection's busy-handler callback. The argument is of type (void**)
1355** - an array of two (void *) values. The first (void *) actually points
1356** to a function of type (int (*)(void *)). In order to invoke the connection's
1357** busy-handler, this function should be invoked with the second (void *) in
1358** the array as the only argument. If it returns non-zero, then the operation
1359** should be retried. If it returns zero, the custom VFS should abandon the
1360** current operation.
1361**
1362** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1363** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1364** to have SQLite generate a
1365** temporary filename using the same algorithm that is followed to generate
1366** temporary filenames for TEMP tables and other internal uses.  The
1367** argument should be a char** which will be filled with the filename
1368** written into memory obtained from [sqlite3_malloc()].  The caller should
1369** invoke [sqlite3_free()] on the result to avoid a memory leak.
1370**
1371** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1372** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1373** maximum number of bytes that will be used for memory-mapped I/O.
1374** The argument is a pointer to a value of type sqlite3_int64 that
1375** is an advisory maximum number of bytes in the file to memory map.  The
1376** pointer is overwritten with the old value.  The limit is not changed if
1377** the value originally pointed to is negative, and so the current limit
1378** can be queried by passing in a pointer to a negative number.  This
1379** file-control is used internally to implement [PRAGMA mmap_size].
1380**
1381** <li>[[SQLITE_FCNTL_TRACE]]
1382** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1383** to the VFS about what the higher layers of the SQLite stack are doing.
1384** This file control is used by some VFS activity tracing [shims].
1385** The argument is a zero-terminated string.  Higher layers in the
1386** SQLite stack may generate instances of this file control if
1387** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1388**
1389** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1390** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1391** pointer to an integer and it writes a boolean into that integer depending
1392** on whether or not the file has been renamed, moved, or deleted since it
1393** was first opened.
1394**
1395** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
1396** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
1397** underlying native file handle associated with a file handle.  This file
1398** control interprets its argument as a pointer to a native file handle and
1399** writes the resulting value there.
1400**
1401** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1402** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
1403** opcode causes the xFileControl method to swap the file handle with the one
1404** pointed to by the pArg argument.  This capability is used during testing
1405** and only needs to be supported when SQLITE_TEST is defined.
1406**
1407** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1408** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1409** be advantageous to block on the next WAL lock if the lock is not immediately
1410** available.  The WAL subsystem issues this signal during rare
1411** circumstances in order to fix a problem with priority inversion.
1412** Applications should <em>not</em> use this file-control.
1413**
1414** <li>[[SQLITE_FCNTL_ZIPVFS]]
1415** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
1416** VFS should return SQLITE_NOTFOUND for this opcode.
1417**
1418** <li>[[SQLITE_FCNTL_RBU]]
1419** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
1420** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for
1421** this opcode.
1422**
1423** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
1424** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
1425** the file descriptor is placed in "batch write mode", which
1426** means all subsequent write operations will be deferred and done
1427** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].  Systems
1428** that do not support batch atomic writes will return SQLITE_NOTFOUND.
1429** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
1430** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
1431** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
1432** no VFS interface calls on the same [sqlite3_file] file descriptor
1433** except for calls to the xWrite method and the xFileControl method
1434** with [SQLITE_FCNTL_SIZE_HINT].
1435**
1436** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
1437** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
1438** operations since the previous successful call to
1439** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
1440** This file control returns [SQLITE_OK] if and only if the writes were
1441** all performed successfully and have been committed to persistent storage.
1442** ^Regardless of whether or not it is successful, this file control takes
1443** the file descriptor out of batch write mode so that all subsequent
1444** write operations are independent.
1445** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
1446** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
1447**
1448** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
1449** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
1450** operations since the previous successful call to
1451** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
1452** ^This file control takes the file descriptor out of batch write mode
1453** so that all subsequent write operations are independent.
1454** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
1455** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
1456**
1457** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
1458** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS
1459** to block for up to M milliseconds before failing when attempting to
1460** obtain a file lock using the xLock or xShmLock methods of the VFS.
1461** The parameter is a pointer to a 32-bit signed integer that contains
1462** the value that M is to be set to. Before returning, the 32-bit signed
1463** integer is overwritten with the previous value of M.
1464**
1465** <li>[[SQLITE_FCNTL_DATA_VERSION]]
1466** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
1467** a database file.  The argument is a pointer to a 32-bit unsigned integer.
1468** The "data version" for the pager is written into the pointer.  The
1469** "data version" changes whenever any change occurs to the corresponding
1470** database file, either through SQL statements on the same database
1471** connection or through transactions committed by separate database
1472** connections possibly in other processes. The [sqlite3_total_changes()]
1473** interface can be used to find if any database on the connection has changed,
1474** but that interface responds to changes on TEMP as well as MAIN and does
1475** not provide a mechanism to detect changes to MAIN only.  Also, the
1476** [sqlite3_total_changes()] interface responds to internal changes only and
1477** omits changes made by other database connections.  The
1478** [PRAGMA data_version] command provides a mechanism to detect changes to
1479** a single attached database that occur due to other database connections,
1480** but omits changes implemented by the database connection on which it is
1481** called.  This file control is the only mechanism to detect changes that
1482** happen either internally or externally and that are associated with
1483** a particular attached database.
1484**
1485** <li>[[SQLITE_FCNTL_CKPT_START]]
1486** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint
1487** in wal mode before the client starts to copy pages from the wal
1488** file to the database file.
1489**
1490** <li>[[SQLITE_FCNTL_CKPT_DONE]]
1491** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint
1492** in wal mode after the client has finished copying pages from the wal
1493** file to the database file, but before the *-shm file is updated to
1494** record the fact that the pages have been checkpointed.
1495**
1496** <li>[[SQLITE_FCNTL_EXTERNAL_READER]]
1497** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect
1498** whether or not there is a database client in another process with a wal-mode
1499** transaction open on the database or not. It is only available on unix.The
1500** (void*) argument passed with this file-control should be a pointer to a
1501** value of type (int). The integer value is set to 1 if the database is a wal
1502** mode database and there exists at least one client in another process that
1503** currently has an SQL transaction open on the database. It is set to 0 if
1504** the database is not a wal-mode db, or if there is no such connection in any
1505** other process. This opcode cannot be used to detect transactions opened
1506** by clients within the current process, only within other processes.
1507**
1508** <li>[[SQLITE_FCNTL_CKSM_FILE]]
1509** The [SQLITE_FCNTL_CKSM_FILE] opcode is for use internally by the
1510** [checksum VFS shim] only.
1511**
1512** <li>[[SQLITE_FCNTL_RESET_CACHE]]
1513** If there is currently no transaction open on the database, and the
1514** database is not a temp db, then the [SQLITE_FCNTL_RESET_CACHE] file-control
1515** purges the contents of the in-memory page cache. If there is an open
1516** transaction, or if the db is a temp-db, this opcode is a no-op, not an error.
1517** </ul>
1518*/
1519#define SQLITE_FCNTL_LOCKSTATE               1
1520#define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
1521#define SQLITE_FCNTL_SET_LOCKPROXYFILE       3
1522#define SQLITE_FCNTL_LAST_ERRNO              4
1523#define SQLITE_FCNTL_SIZE_HINT               5
1524#define SQLITE_FCNTL_CHUNK_SIZE              6
1525#define SQLITE_FCNTL_FILE_POINTER            7
1526#define SQLITE_FCNTL_SYNC_OMITTED            8
1527#define SQLITE_FCNTL_WIN32_AV_RETRY          9
1528#define SQLITE_FCNTL_PERSIST_WAL            10
1529#define SQLITE_FCNTL_OVERWRITE              11
1530#define SQLITE_FCNTL_VFSNAME                12
1531#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1532#define SQLITE_FCNTL_PRAGMA                 14
1533#define SQLITE_FCNTL_BUSYHANDLER            15
1534#define SQLITE_FCNTL_TEMPFILENAME           16
1535#define SQLITE_FCNTL_MMAP_SIZE              18
1536#define SQLITE_FCNTL_TRACE                  19
1537#define SQLITE_FCNTL_HAS_MOVED              20
1538#define SQLITE_FCNTL_SYNC                   21
1539#define SQLITE_FCNTL_COMMIT_PHASETWO        22
1540#define SQLITE_FCNTL_WIN32_SET_HANDLE       23
1541#define SQLITE_FCNTL_WAL_BLOCK              24
1542#define SQLITE_FCNTL_ZIPVFS                 25
1543#define SQLITE_FCNTL_RBU                    26
1544#define SQLITE_FCNTL_VFS_POINTER            27
1545#define SQLITE_FCNTL_JOURNAL_POINTER        28
1546#define SQLITE_FCNTL_WIN32_GET_HANDLE       29
1547#define SQLITE_FCNTL_PDB                    30
1548#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE     31
1549#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE    32
1550#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE  33
1551#define SQLITE_FCNTL_LOCK_TIMEOUT           34
1552#define SQLITE_FCNTL_DATA_VERSION           35
1553#define SQLITE_FCNTL_SIZE_LIMIT             36
1554#define SQLITE_FCNTL_CKPT_DONE              37
1555#define SQLITE_FCNTL_RESERVE_BYTES          38
1556#define SQLITE_FCNTL_CKPT_START             39
1557#define SQLITE_FCNTL_EXTERNAL_READER        40
1558#define SQLITE_FCNTL_CKSM_FILE              41
1559#define SQLITE_FCNTL_RESET_CACHE            42
1560
1561/* deprecated names */
1562#define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
1563#define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE
1564#define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO
1565
1566
1567/*
1568** CAPI3REF: Mutex Handle
1569**
1570** The mutex module within SQLite defines [sqlite3_mutex] to be an
1571** abstract type for a mutex object.  The SQLite core never looks
1572** at the internal representation of an [sqlite3_mutex].  It only
1573** deals with pointers to the [sqlite3_mutex] object.
1574**
1575** Mutexes are created using [sqlite3_mutex_alloc()].
1576*/
1577typedef struct sqlite3_mutex sqlite3_mutex;
1578
1579/*
1580** CAPI3REF: Loadable Extension Thunk
1581**
1582** A pointer to the opaque sqlite3_api_routines structure is passed as
1583** the third parameter to entry points of [loadable extensions].  This
1584** structure must be typedefed in order to work around compiler warnings
1585** on some platforms.
1586*/
1587typedef struct sqlite3_api_routines sqlite3_api_routines;
1588
1589/*
1590** CAPI3REF: File Name
1591**
1592** Type [sqlite3_filename] is used by SQLite to pass filenames to the
1593** xOpen method of a [VFS]. It may be cast to (const char*) and treated
1594** as a normal, nul-terminated, UTF-8 buffer containing the filename, but
1595** may also be passed to special APIs such as:
1596**
1597** <ul>
1598** <li>  sqlite3_filename_database()
1599** <li>  sqlite3_filename_journal()
1600** <li>  sqlite3_filename_wal()
1601** <li>  sqlite3_uri_parameter()
1602** <li>  sqlite3_uri_boolean()
1603** <li>  sqlite3_uri_int64()
1604** <li>  sqlite3_uri_key()
1605** </ul>
1606*/
1607typedef const char *sqlite3_filename;
1608
1609/*
1610** CAPI3REF: OS Interface Object
1611**
1612** An instance of the sqlite3_vfs object defines the interface between
1613** the SQLite core and the underlying operating system.  The "vfs"
1614** in the name of the object stands for "virtual file system".  See
1615** the [VFS | VFS documentation] for further information.
1616**
1617** The VFS interface is sometimes extended by adding new methods onto
1618** the end.  Each time such an extension occurs, the iVersion field
1619** is incremented.  The iVersion value started out as 1 in
1620** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
1621** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
1622** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6].  Additional fields
1623** may be appended to the sqlite3_vfs object and the iVersion value
1624** may increase again in future versions of SQLite.
1625** Note that due to an oversight, the structure
1626** of the sqlite3_vfs object changed in the transition from
1627** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
1628** and yet the iVersion field was not increased.
1629**
1630** The szOsFile field is the size of the subclassed [sqlite3_file]
1631** structure used by this VFS.  mxPathname is the maximum length of
1632** a pathname in this VFS.
1633**
1634** Registered sqlite3_vfs objects are kept on a linked list formed by
1635** the pNext pointer.  The [sqlite3_vfs_register()]
1636** and [sqlite3_vfs_unregister()] interfaces manage this list
1637** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1638** searches the list.  Neither the application code nor the VFS
1639** implementation should use the pNext pointer.
1640**
1641** The pNext field is the only field in the sqlite3_vfs
1642** structure that SQLite will ever modify.  SQLite will only access
1643** or modify this field while holding a particular static mutex.
1644** The application should never modify anything within the sqlite3_vfs
1645** object once the object has been registered.
1646**
1647** The zName field holds the name of the VFS module.  The name must
1648** be unique across all VFS modules.
1649**
1650** [[sqlite3_vfs.xOpen]]
1651** ^SQLite guarantees that the zFilename parameter to xOpen
1652** is either a NULL pointer or string obtained
1653** from xFullPathname() with an optional suffix added.
1654** ^If a suffix is added to the zFilename parameter, it will
1655** consist of a single "-" character followed by no more than
1656** 11 alphanumeric and/or "-" characters.
1657** ^SQLite further guarantees that
1658** the string will be valid and unchanged until xClose() is
1659** called. Because of the previous sentence,
1660** the [sqlite3_file] can safely store a pointer to the
1661** filename if it needs to remember the filename for some reason.
1662** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1663** must invent its own temporary name for the file.  ^Whenever the
1664** xFilename parameter is NULL it will also be the case that the
1665** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1666**
1667** The flags argument to xOpen() includes all bits set in
1668** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1669** or [sqlite3_open16()] is used, then flags includes at least
1670** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1671** If xOpen() opens a file read-only then it sets *pOutFlags to
1672** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1673**
1674** ^(SQLite will also add one of the following flags to the xOpen()
1675** call, depending on the object being opened:
1676**
1677** <ul>
1678** <li>  [SQLITE_OPEN_MAIN_DB]
1679** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1680** <li>  [SQLITE_OPEN_TEMP_DB]
1681** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1682** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1683** <li>  [SQLITE_OPEN_SUBJOURNAL]
1684** <li>  [SQLITE_OPEN_SUPER_JOURNAL]
1685** <li>  [SQLITE_OPEN_WAL]
1686** </ul>)^
1687**
1688** The file I/O implementation can use the object type flags to
1689** change the way it deals with files.  For example, an application
1690** that does not care about crash recovery or rollback might make
1691** the open of a journal file a no-op.  Writes to this journal would
1692** also be no-ops, and any attempt to read the journal would return
1693** SQLITE_IOERR.  Or the implementation might recognize that a database
1694** file will be doing page-aligned sector reads and writes in a random
1695** order and set up its I/O subsystem accordingly.
1696**
1697** SQLite might also add one of the following flags to the xOpen method:
1698**
1699** <ul>
1700** <li> [SQLITE_OPEN_DELETEONCLOSE]
1701** <li> [SQLITE_OPEN_EXCLUSIVE]
1702** </ul>
1703**
1704** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1705** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1706** will be set for TEMP databases and their journals, transient
1707** databases, and subjournals.
1708**
1709** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1710** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1711** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1712** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1713** SQLITE_OPEN_CREATE, is used to indicate that file should always
1714** be created, and that it is an error if it already exists.
1715** It is <i>not</i> used to indicate the file should be opened
1716** for exclusive access.
1717**
1718** ^At least szOsFile bytes of memory are allocated by SQLite
1719** to hold the [sqlite3_file] structure passed as the third
1720** argument to xOpen.  The xOpen method does not have to
1721** allocate the structure; it should just fill it in.  Note that
1722** the xOpen method must set the sqlite3_file.pMethods to either
1723** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1724** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1725** element will be valid after xOpen returns regardless of the success
1726** or failure of the xOpen call.
1727**
1728** [[sqlite3_vfs.xAccess]]
1729** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1730** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1731** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1732** to test whether a file is at least readable.  The SQLITE_ACCESS_READ
1733** flag is never actually used and is not implemented in the built-in
1734** VFSes of SQLite.  The file is named by the second argument and can be a
1735** directory. The xAccess method returns [SQLITE_OK] on success or some
1736** non-zero error code if there is an I/O error or if the name of
1737** the file given in the second argument is illegal.  If SQLITE_OK
1738** is returned, then non-zero or zero is written into *pResOut to indicate
1739** whether or not the file is accessible.
1740**
1741** ^SQLite will always allocate at least mxPathname+1 bytes for the
1742** output buffer xFullPathname.  The exact size of the output buffer
1743** is also passed as a parameter to both  methods. If the output buffer
1744** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1745** handled as a fatal error by SQLite, vfs implementations should endeavor
1746** to prevent this by setting mxPathname to a sufficiently large value.
1747**
1748** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1749** interfaces are not strictly a part of the filesystem, but they are
1750** included in the VFS structure for completeness.
1751** The xRandomness() function attempts to return nBytes bytes
1752** of good-quality randomness into zOut.  The return value is
1753** the actual number of bytes of randomness obtained.
1754** The xSleep() method causes the calling thread to sleep for at
1755** least the number of microseconds given.  ^The xCurrentTime()
1756** method returns a Julian Day Number for the current date and time as
1757** a floating point value.
1758** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1759** Day Number multiplied by 86400000 (the number of milliseconds in
1760** a 24-hour day).
1761** ^SQLite will use the xCurrentTimeInt64() method to get the current
1762** date and time if that method is available (if iVersion is 2 or
1763** greater and the function pointer is not NULL) and will fall back
1764** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1765**
1766** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1767** are not used by the SQLite core.  These optional interfaces are provided
1768** by some VFSes to facilitate testing of the VFS code. By overriding
1769** system calls with functions under its control, a test program can
1770** simulate faults and error conditions that would otherwise be difficult
1771** or impossible to induce.  The set of system calls that can be overridden
1772** varies from one VFS to another, and from one version of the same VFS to the
1773** next.  Applications that use these interfaces must be prepared for any
1774** or all of these interfaces to be NULL or for their behavior to change
1775** from one release to the next.  Applications must not attempt to access
1776** any of these methods if the iVersion of the VFS is less than 3.
1777*/
1778typedef struct sqlite3_vfs sqlite3_vfs;
1779typedef void (*sqlite3_syscall_ptr)(void);
1780struct sqlite3_vfs {
1781  int iVersion;            /* Structure version number (currently 3) */
1782  int szOsFile;            /* Size of subclassed sqlite3_file */
1783  int mxPathname;          /* Maximum file pathname length */
1784  sqlite3_vfs *pNext;      /* Next registered VFS */
1785  const char *zName;       /* Name of this virtual file system */
1786  void *pAppData;          /* Pointer to application-specific data */
1787  int (*xOpen)(sqlite3_vfs*, sqlite3_filename zName, sqlite3_file*,
1788               int flags, int *pOutFlags);
1789  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1790  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1791  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1792  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1793  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1794  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1795  void (*xDlClose)(sqlite3_vfs*, void*);
1796  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1797  int (*xSleep)(sqlite3_vfs*, int microseconds);
1798  int (*xCurrentTime)(sqlite3_vfs*, double*);
1799  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1800  /*
1801  ** The methods above are in version 1 of the sqlite_vfs object
1802  ** definition.  Those that follow are added in version 2 or later
1803  */
1804  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1805  /*
1806  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1807  ** Those below are for version 3 and greater.
1808  */
1809  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1810  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1811  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1812  /*
1813  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1814  ** New fields may be appended in future versions.  The iVersion
1815  ** value will increment whenever this happens.
1816  */
1817};
1818
1819/*
1820** CAPI3REF: Flags for the xAccess VFS method
1821**
1822** These integer constants can be used as the third parameter to
1823** the xAccess method of an [sqlite3_vfs] object.  They determine
1824** what kind of permissions the xAccess method is looking for.
1825** With SQLITE_ACCESS_EXISTS, the xAccess method
1826** simply checks whether the file exists.
1827** With SQLITE_ACCESS_READWRITE, the xAccess method
1828** checks whether the named directory is both readable and writable
1829** (in other words, if files can be added, removed, and renamed within
1830** the directory).
1831** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1832** [temp_store_directory pragma], though this could change in a future
1833** release of SQLite.
1834** With SQLITE_ACCESS_READ, the xAccess method
1835** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1836** currently unused, though it might be used in a future release of
1837** SQLite.
1838*/
1839#define SQLITE_ACCESS_EXISTS    0
1840#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1841#define SQLITE_ACCESS_READ      2   /* Unused */
1842
1843/*
1844** CAPI3REF: Flags for the xShmLock VFS method
1845**
1846** These integer constants define the various locking operations
1847** allowed by the xShmLock method of [sqlite3_io_methods].  The
1848** following are the only legal combinations of flags to the
1849** xShmLock method:
1850**
1851** <ul>
1852** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1853** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1854** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1855** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1856** </ul>
1857**
1858** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1859** was given on the corresponding lock.
1860**
1861** The xShmLock method can transition between unlocked and SHARED or
1862** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1863** and EXCLUSIVE.
1864*/
1865#define SQLITE_SHM_UNLOCK       1
1866#define SQLITE_SHM_LOCK         2
1867#define SQLITE_SHM_SHARED       4
1868#define SQLITE_SHM_EXCLUSIVE    8
1869
1870/*
1871** CAPI3REF: Maximum xShmLock index
1872**
1873** The xShmLock method on [sqlite3_io_methods] may use values
1874** between 0 and this upper bound as its "offset" argument.
1875** The SQLite core will never attempt to acquire or release a
1876** lock outside of this range
1877*/
1878#define SQLITE_SHM_NLOCK        8
1879
1880
1881/*
1882** CAPI3REF: Initialize The SQLite Library
1883**
1884** ^The sqlite3_initialize() routine initializes the
1885** SQLite library.  ^The sqlite3_shutdown() routine
1886** deallocates any resources that were allocated by sqlite3_initialize().
1887** These routines are designed to aid in process initialization and
1888** shutdown on embedded systems.  Workstation applications using
1889** SQLite normally do not need to invoke either of these routines.
1890**
1891** A call to sqlite3_initialize() is an "effective" call if it is
1892** the first time sqlite3_initialize() is invoked during the lifetime of
1893** the process, or if it is the first time sqlite3_initialize() is invoked
1894** following a call to sqlite3_shutdown().  ^(Only an effective call
1895** of sqlite3_initialize() does any initialization.  All other calls
1896** are harmless no-ops.)^
1897**
1898** A call to sqlite3_shutdown() is an "effective" call if it is the first
1899** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1900** an effective call to sqlite3_shutdown() does any deinitialization.
1901** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1902**
1903** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1904** is not.  The sqlite3_shutdown() interface must only be called from a
1905** single thread.  All open [database connections] must be closed and all
1906** other SQLite resources must be deallocated prior to invoking
1907** sqlite3_shutdown().
1908**
1909** Among other things, ^sqlite3_initialize() will invoke
1910** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1911** will invoke sqlite3_os_end().
1912**
1913** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1914** ^If for some reason, sqlite3_initialize() is unable to initialize
1915** the library (perhaps it is unable to allocate a needed resource such
1916** as a mutex) it returns an [error code] other than [SQLITE_OK].
1917**
1918** ^The sqlite3_initialize() routine is called internally by many other
1919** SQLite interfaces so that an application usually does not need to
1920** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1921** calls sqlite3_initialize() so the SQLite library will be automatically
1922** initialized when [sqlite3_open()] is called if it has not be initialized
1923** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1924** compile-time option, then the automatic calls to sqlite3_initialize()
1925** are omitted and the application must call sqlite3_initialize() directly
1926** prior to using any other SQLite interface.  For maximum portability,
1927** it is recommended that applications always invoke sqlite3_initialize()
1928** directly prior to using any other SQLite interface.  Future releases
1929** of SQLite may require this.  In other words, the behavior exhibited
1930** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1931** default behavior in some future release of SQLite.
1932**
1933** The sqlite3_os_init() routine does operating-system specific
1934** initialization of the SQLite library.  The sqlite3_os_end()
1935** routine undoes the effect of sqlite3_os_init().  Typical tasks
1936** performed by these routines include allocation or deallocation
1937** of static resources, initialization of global variables,
1938** setting up a default [sqlite3_vfs] module, or setting up
1939** a default configuration using [sqlite3_config()].
1940**
1941** The application should never invoke either sqlite3_os_init()
1942** or sqlite3_os_end() directly.  The application should only invoke
1943** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1944** interface is called automatically by sqlite3_initialize() and
1945** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1946** implementations for sqlite3_os_init() and sqlite3_os_end()
1947** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1948** When [custom builds | built for other platforms]
1949** (using the [SQLITE_OS_OTHER=1] compile-time
1950** option) the application must supply a suitable implementation for
1951** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1952** implementation of sqlite3_os_init() or sqlite3_os_end()
1953** must return [SQLITE_OK] on success and some other [error code] upon
1954** failure.
1955*/
1956SQLITE_API int sqlite3_initialize(void);
1957SQLITE_API int sqlite3_shutdown(void);
1958SQLITE_API int sqlite3_os_init(void);
1959SQLITE_API int sqlite3_os_end(void);
1960
1961/*
1962** CAPI3REF: Configuring The SQLite Library
1963**
1964** The sqlite3_config() interface is used to make global configuration
1965** changes to SQLite in order to tune SQLite to the specific needs of
1966** the application.  The default configuration is recommended for most
1967** applications and so this routine is usually not necessary.  It is
1968** provided to support rare applications with unusual needs.
1969**
1970** <b>The sqlite3_config() interface is not threadsafe. The application
1971** must ensure that no other SQLite interfaces are invoked by other
1972** threads while sqlite3_config() is running.</b>
1973**
1974** The first argument to sqlite3_config() is an integer
1975** [configuration option] that determines
1976** what property of SQLite is to be configured.  Subsequent arguments
1977** vary depending on the [configuration option]
1978** in the first argument.
1979**
1980** For most configuration options, the sqlite3_config() interface
1981** may only be invoked prior to library initialization using
1982** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1983** The exceptional configuration options that may be invoked at any time
1984** are called "anytime configuration options".
1985** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1986** [sqlite3_shutdown()] with a first argument that is not an anytime
1987** configuration option, then the sqlite3_config() call will return SQLITE_MISUSE.
1988** Note, however, that ^sqlite3_config() can be called as part of the
1989** implementation of an application-defined [sqlite3_os_init()].
1990**
1991** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1992** ^If the option is unknown or SQLite is unable to set the option
1993** then this routine returns a non-zero [error code].
1994*/
1995SQLITE_API int sqlite3_config(int, ...);
1996
1997/*
1998** CAPI3REF: Configure database connections
1999** METHOD: sqlite3
2000**
2001** The sqlite3_db_config() interface is used to make configuration
2002** changes to a [database connection].  The interface is similar to
2003** [sqlite3_config()] except that the changes apply to a single
2004** [database connection] (specified in the first argument).
2005**
2006** The second argument to sqlite3_db_config(D,V,...)  is the
2007** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
2008** that indicates what aspect of the [database connection] is being configured.
2009** Subsequent arguments vary depending on the configuration verb.
2010**
2011** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
2012** the call is considered successful.
2013*/
2014SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
2015
2016/*
2017** CAPI3REF: Memory Allocation Routines
2018**
2019** An instance of this object defines the interface between SQLite
2020** and low-level memory allocation routines.
2021**
2022** This object is used in only one place in the SQLite interface.
2023** A pointer to an instance of this object is the argument to
2024** [sqlite3_config()] when the configuration option is
2025** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
2026** By creating an instance of this object
2027** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
2028** during configuration, an application can specify an alternative
2029** memory allocation subsystem for SQLite to use for all of its
2030** dynamic memory needs.
2031**
2032** Note that SQLite comes with several [built-in memory allocators]
2033** that are perfectly adequate for the overwhelming majority of applications
2034** and that this object is only useful to a tiny minority of applications
2035** with specialized memory allocation requirements.  This object is
2036** also used during testing of SQLite in order to specify an alternative
2037** memory allocator that simulates memory out-of-memory conditions in
2038** order to verify that SQLite recovers gracefully from such
2039** conditions.
2040**
2041** The xMalloc, xRealloc, and xFree methods must work like the
2042** malloc(), realloc() and free() functions from the standard C library.
2043** ^SQLite guarantees that the second argument to
2044** xRealloc is always a value returned by a prior call to xRoundup.
2045**
2046** xSize should return the allocated size of a memory allocation
2047** previously obtained from xMalloc or xRealloc.  The allocated size
2048** is always at least as big as the requested size but may be larger.
2049**
2050** The xRoundup method returns what would be the allocated size of
2051** a memory allocation given a particular requested size.  Most memory
2052** allocators round up memory allocations at least to the next multiple
2053** of 8.  Some allocators round up to a larger multiple or to a power of 2.
2054** Every memory allocation request coming in through [sqlite3_malloc()]
2055** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
2056** that causes the corresponding memory allocation to fail.
2057**
2058** The xInit method initializes the memory allocator.  For example,
2059** it might allocate any required mutexes or initialize internal data
2060** structures.  The xShutdown method is invoked (indirectly) by
2061** [sqlite3_shutdown()] and should deallocate any resources acquired
2062** by xInit.  The pAppData pointer is used as the only parameter to
2063** xInit and xShutdown.
2064**
2065** SQLite holds the [SQLITE_MUTEX_STATIC_MAIN] mutex when it invokes
2066** the xInit method, so the xInit method need not be threadsafe.  The
2067** xShutdown method is only called from [sqlite3_shutdown()] so it does
2068** not need to be threadsafe either.  For all other methods, SQLite
2069** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
2070** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
2071** it is by default) and so the methods are automatically serialized.
2072** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
2073** methods must be threadsafe or else make their own arrangements for
2074** serialization.
2075**
2076** SQLite will never invoke xInit() more than once without an intervening
2077** call to xShutdown().
2078*/
2079typedef struct sqlite3_mem_methods sqlite3_mem_methods;
2080struct sqlite3_mem_methods {
2081  void *(*xMalloc)(int);         /* Memory allocation function */
2082  void (*xFree)(void*);          /* Free a prior allocation */
2083  void *(*xRealloc)(void*,int);  /* Resize an allocation */
2084  int (*xSize)(void*);           /* Return the size of an allocation */
2085  int (*xRoundup)(int);          /* Round up request size to allocation size */
2086  int (*xInit)(void*);           /* Initialize the memory allocator */
2087  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
2088  void *pAppData;                /* Argument to xInit() and xShutdown() */
2089};
2090
2091/*
2092** CAPI3REF: Configuration Options
2093** KEYWORDS: {configuration option}
2094**
2095** These constants are the available integer configuration options that
2096** can be passed as the first argument to the [sqlite3_config()] interface.
2097**
2098** Most of the configuration options for sqlite3_config()
2099** will only work if invoked prior to [sqlite3_initialize()] or after
2100** [sqlite3_shutdown()].  The few exceptions to this rule are called
2101** "anytime configuration options".
2102** ^Calling [sqlite3_config()] with a first argument that is not an
2103** anytime configuration option in between calls to [sqlite3_initialize()] and
2104** [sqlite3_shutdown()] is a no-op that returns SQLITE_MISUSE.
2105**
2106** The set of anytime configuration options can change (by insertions
2107** and/or deletions) from one release of SQLite to the next.
2108** As of SQLite version 3.42.0, the complete set of anytime configuration
2109** options is:
2110** <ul>
2111** <li> SQLITE_CONFIG_LOG
2112** <li> SQLITE_CONFIG_PCACHE_HDRSZ
2113** </ul>
2114**
2115** New configuration options may be added in future releases of SQLite.
2116** Existing configuration options might be discontinued.  Applications
2117** should check the return code from [sqlite3_config()] to make sure that
2118** the call worked.  The [sqlite3_config()] interface will return a
2119** non-zero [error code] if a discontinued or unsupported configuration option
2120** is invoked.
2121**
2122** <dl>
2123** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
2124** <dd>There are no arguments to this option.  ^This option sets the
2125** [threading mode] to Single-thread.  In other words, it disables
2126** all mutexing and puts SQLite into a mode where it can only be used
2127** by a single thread.   ^If SQLite is compiled with
2128** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2129** it is not possible to change the [threading mode] from its default
2130** value of Single-thread and so [sqlite3_config()] will return
2131** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
2132** configuration option.</dd>
2133**
2134** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
2135** <dd>There are no arguments to this option.  ^This option sets the
2136** [threading mode] to Multi-thread.  In other words, it disables
2137** mutexing on [database connection] and [prepared statement] objects.
2138** The application is responsible for serializing access to
2139** [database connections] and [prepared statements].  But other mutexes
2140** are enabled so that SQLite will be safe to use in a multi-threaded
2141** environment as long as no two threads attempt to use the same
2142** [database connection] at the same time.  ^If SQLite is compiled with
2143** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2144** it is not possible to set the Multi-thread [threading mode] and
2145** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2146** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
2147**
2148** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
2149** <dd>There are no arguments to this option.  ^This option sets the
2150** [threading mode] to Serialized. In other words, this option enables
2151** all mutexes including the recursive
2152** mutexes on [database connection] and [prepared statement] objects.
2153** In this mode (which is the default when SQLite is compiled with
2154** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
2155** to [database connections] and [prepared statements] so that the
2156** application is free to use the same [database connection] or the
2157** same [prepared statement] in different threads at the same time.
2158** ^If SQLite is compiled with
2159** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2160** it is not possible to set the Serialized [threading mode] and
2161** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2162** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
2163**
2164** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
2165** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
2166** a pointer to an instance of the [sqlite3_mem_methods] structure.
2167** The argument specifies
2168** alternative low-level memory allocation routines to be used in place of
2169** the memory allocation routines built into SQLite.)^ ^SQLite makes
2170** its own private copy of the content of the [sqlite3_mem_methods] structure
2171** before the [sqlite3_config()] call returns.</dd>
2172**
2173** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
2174** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
2175** is a pointer to an instance of the [sqlite3_mem_methods] structure.
2176** The [sqlite3_mem_methods]
2177** structure is filled with the currently defined memory allocation routines.)^
2178** This option can be used to overload the default memory allocation
2179** routines with a wrapper that simulations memory allocation failure or
2180** tracks memory usage, for example. </dd>
2181**
2182** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
2183** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
2184** type int, interpreted as a boolean, which if true provides a hint to
2185** SQLite that it should avoid large memory allocations if possible.
2186** SQLite will run faster if it is free to make large memory allocations,
2187** but some application might prefer to run slower in exchange for
2188** guarantees about memory fragmentation that are possible if large
2189** allocations are avoided.  This hint is normally off.
2190** </dd>
2191**
2192** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
2193** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
2194** interpreted as a boolean, which enables or disables the collection of
2195** memory allocation statistics. ^(When memory allocation statistics are
2196** disabled, the following SQLite interfaces become non-operational:
2197**   <ul>
2198**   <li> [sqlite3_hard_heap_limit64()]
2199**   <li> [sqlite3_memory_used()]
2200**   <li> [sqlite3_memory_highwater()]
2201**   <li> [sqlite3_soft_heap_limit64()]
2202**   <li> [sqlite3_status64()]
2203**   </ul>)^
2204** ^Memory allocation statistics are enabled by default unless SQLite is
2205** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
2206** allocation statistics are disabled by default.
2207** </dd>
2208**
2209** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
2210** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
2211** </dd>
2212**
2213** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
2214** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
2215** that SQLite can use for the database page cache with the default page
2216** cache implementation.
2217** This configuration option is a no-op if an application-defined page
2218** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
2219** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
2220** 8-byte aligned memory (pMem), the size of each page cache line (sz),
2221** and the number of cache lines (N).
2222** The sz argument should be the size of the largest database page
2223** (a power of two between 512 and 65536) plus some extra bytes for each
2224** page header.  ^The number of extra bytes needed by the page header
2225** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
2226** ^It is harmless, apart from the wasted memory,
2227** for the sz parameter to be larger than necessary.  The pMem
2228** argument must be either a NULL pointer or a pointer to an 8-byte
2229** aligned block of memory of at least sz*N bytes, otherwise
2230** subsequent behavior is undefined.
2231** ^When pMem is not NULL, SQLite will strive to use the memory provided
2232** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
2233** a page cache line is larger than sz bytes or if all of the pMem buffer
2234** is exhausted.
2235** ^If pMem is NULL and N is non-zero, then each database connection
2236** does an initial bulk allocation for page cache memory
2237** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
2238** of -1024*N bytes if N is negative, . ^If additional
2239** page cache memory is needed beyond what is provided by the initial
2240** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
2241** additional cache line. </dd>
2242**
2243** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2244** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
2245** that SQLite will use for all of its dynamic memory allocation needs
2246** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
2247** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
2248** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
2249** [SQLITE_ERROR] if invoked otherwise.
2250** ^There are three arguments to SQLITE_CONFIG_HEAP:
2251** An 8-byte aligned pointer to the memory,
2252** the number of bytes in the memory buffer, and the minimum allocation size.
2253** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2254** to using its default memory allocator (the system malloc() implementation),
2255** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
2256** memory pointer is not NULL then the alternative memory
2257** allocator is engaged to handle all of SQLites memory allocation needs.
2258** The first pointer (the memory pointer) must be aligned to an 8-byte
2259** boundary or subsequent behavior of SQLite will be undefined.
2260** The minimum allocation size is capped at 2**12. Reasonable values
2261** for the minimum allocation size are 2**5 through 2**8.</dd>
2262**
2263** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2264** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
2265** pointer to an instance of the [sqlite3_mutex_methods] structure.
2266** The argument specifies alternative low-level mutex routines to be used
2267** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of
2268** the content of the [sqlite3_mutex_methods] structure before the call to
2269** [sqlite3_config()] returns. ^If SQLite is compiled with
2270** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2271** the entire mutexing subsystem is omitted from the build and hence calls to
2272** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2273** return [SQLITE_ERROR].</dd>
2274**
2275** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2276** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
2277** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The
2278** [sqlite3_mutex_methods]
2279** structure is filled with the currently defined mutex routines.)^
2280** This option can be used to overload the default mutex allocation
2281** routines with a wrapper used to track mutex usage for performance
2282** profiling or testing, for example.   ^If SQLite is compiled with
2283** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2284** the entire mutexing subsystem is omitted from the build and hence calls to
2285** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2286** return [SQLITE_ERROR].</dd>
2287**
2288** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2289** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
2290** the default size of lookaside memory on each [database connection].
2291** The first argument is the
2292** size of each lookaside buffer slot and the second is the number of
2293** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE
2294** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2295** option to [sqlite3_db_config()] can be used to change the lookaside
2296** configuration on individual connections.)^ </dd>
2297**
2298** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2299** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
2300** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies
2301** the interface to a custom page cache implementation.)^
2302** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
2303**
2304** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2305** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
2306** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of
2307** the current page cache implementation into that object.)^ </dd>
2308**
2309** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2310** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
2311** global [error log].
2312** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2313** function with a call signature of void(*)(void*,int,const char*),
2314** and a pointer to void. ^If the function pointer is not NULL, it is
2315** invoked by [sqlite3_log()] to process each logging event.  ^If the
2316** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2317** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2318** passed through as the first parameter to the application-defined logger
2319** function whenever that function is invoked.  ^The second parameter to
2320** the logger function is a copy of the first parameter to the corresponding
2321** [sqlite3_log()] call and is intended to be a [result code] or an
2322** [extended result code].  ^The third parameter passed to the logger is
2323** log message after formatting via [sqlite3_snprintf()].
2324** The SQLite logging interface is not reentrant; the logger function
2325** supplied by the application must not invoke any SQLite interface.
2326** In a multi-threaded application, the application-defined logger
2327** function must be threadsafe. </dd>
2328**
2329** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2330** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
2331** If non-zero, then URI handling is globally enabled. If the parameter is zero,
2332** then URI handling is globally disabled.)^ ^If URI handling is globally
2333** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
2334** [sqlite3_open16()] or
2335** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2336** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2337** connection is opened. ^If it is globally disabled, filenames are
2338** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2339** database connection is opened. ^(By default, URI handling is globally
2340** disabled. The default value may be changed by compiling with the
2341** [SQLITE_USE_URI] symbol defined.)^
2342**
2343** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2344** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
2345** argument which is interpreted as a boolean in order to enable or disable
2346** the use of covering indices for full table scans in the query optimizer.
2347** ^The default setting is determined
2348** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2349** if that compile-time option is omitted.
2350** The ability to disable the use of covering indices for full table scans
2351** is because some incorrectly coded legacy applications might malfunction
2352** when the optimization is enabled.  Providing the ability to
2353** disable the optimization allows the older, buggy application code to work
2354** without change even with newer versions of SQLite.
2355**
2356** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2357** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2358** <dd> These options are obsolete and should not be used by new code.
2359** They are retained for backwards compatibility but are now no-ops.
2360** </dd>
2361**
2362** [[SQLITE_CONFIG_SQLLOG]]
2363** <dt>SQLITE_CONFIG_SQLLOG
2364** <dd>This option is only available if sqlite is compiled with the
2365** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2366** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2367** The second should be of type (void*). The callback is invoked by the library
2368** in three separate circumstances, identified by the value passed as the
2369** fourth parameter. If the fourth parameter is 0, then the database connection
2370** passed as the second argument has just been opened. The third argument
2371** points to a buffer containing the name of the main database file. If the
2372** fourth parameter is 1, then the SQL statement that the third parameter
2373** points to has just been executed. Or, if the fourth parameter is 2, then
2374** the connection being passed as the second parameter is being closed. The
2375** third parameter is passed NULL In this case.  An example of using this
2376** configuration option can be seen in the "test_sqllog.c" source file in
2377** the canonical SQLite source tree.</dd>
2378**
2379** [[SQLITE_CONFIG_MMAP_SIZE]]
2380** <dt>SQLITE_CONFIG_MMAP_SIZE
2381** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2382** that are the default mmap size limit (the default setting for
2383** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2384** ^The default setting can be overridden by each database connection using
2385** either the [PRAGMA mmap_size] command, or by using the
2386** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
2387** will be silently truncated if necessary so that it does not exceed the
2388** compile-time maximum mmap size set by the
2389** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2390** ^If either argument to this option is negative, then that argument is
2391** changed to its compile-time default.
2392**
2393** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
2394** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
2395** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
2396** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2397** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2398** that specifies the maximum size of the created heap.
2399**
2400** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
2401** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
2402** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
2403** is a pointer to an integer and writes into that integer the number of extra
2404** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
2405** The amount of extra space required can change depending on the compiler,
2406** target platform, and SQLite version.
2407**
2408** [[SQLITE_CONFIG_PMASZ]]
2409** <dt>SQLITE_CONFIG_PMASZ
2410** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
2411** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2412** sorter to that integer.  The default minimum PMA Size is set by the
2413** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched
2414** to help with sort operations when multithreaded sorting
2415** is enabled (using the [PRAGMA threads] command) and the amount of content
2416** to be sorted exceeds the page size times the minimum of the
2417** [PRAGMA cache_size] setting and this value.
2418**
2419** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
2420** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
2421** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
2422** becomes the [statement journal] spill-to-disk threshold.
2423** [Statement journals] are held in memory until their size (in bytes)
2424** exceeds this threshold, at which point they are written to disk.
2425** Or if the threshold is -1, statement journals are always held
2426** exclusively in memory.
2427** Since many statement journals never become large, setting the spill
2428** threshold to a value such as 64KiB can greatly reduce the amount of
2429** I/O required to support statement rollback.
2430** The default value for this setting is controlled by the
2431** [SQLITE_STMTJRNL_SPILL] compile-time option.
2432**
2433** [[SQLITE_CONFIG_SORTERREF_SIZE]]
2434** <dt>SQLITE_CONFIG_SORTERREF_SIZE
2435** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter
2436** of type (int) - the new value of the sorter-reference size threshold.
2437** Usually, when SQLite uses an external sort to order records according
2438** to an ORDER BY clause, all fields required by the caller are present in the
2439** sorted records. However, if SQLite determines based on the declared type
2440** of a table column that its values are likely to be very large - larger
2441** than the configured sorter-reference size threshold - then a reference
2442** is stored in each sorted record and the required column values loaded
2443** from the database as records are returned in sorted order. The default
2444** value for this option is to never use this optimization. Specifying a
2445** negative value for this option restores the default behavior.
2446** This option is only available if SQLite is compiled with the
2447** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
2448**
2449** [[SQLITE_CONFIG_MEMDB_MAXSIZE]]
2450** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE
2451** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter
2452** [sqlite3_int64] parameter which is the default maximum size for an in-memory
2453** database created using [sqlite3_deserialize()].  This default maximum
2454** size can be adjusted up or down for individual databases using the
2455** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control].  If this
2456** configuration setting is never used, then the default maximum is determined
2457** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option.  If that
2458** compile-time option is not set, then the default maximum is 1073741824.
2459**
2460** [[SQLITE_CONFIG_ROWID_IN_VIEW]]
2461** <dt>SQLITE_CONFIG_ROWID_IN_VIEW
2462** <dd>The SQLITE_CONFIG_ROWID_IN_VIEW option enables or disables the ability
2463** for VIEWs to have a ROWID.  The capability can only be enabled if SQLite is
2464** compiled with -DSQLITE_ALLOW_ROWID_IN_VIEW, in which case the capability
2465** defaults to on.  This configuration option queries the current setting or
2466** changes the setting to off or on.  The argument is a pointer to an integer.
2467** If that integer initially holds a value of 1, then the ability for VIEWs to
2468** have ROWIDs is activated.  If the integer initially holds zero, then the
2469** ability is deactivated.  Any other initial value for the integer leaves the
2470** setting unchanged.  After changes, if any, the integer is written with
2471** a 1 or 0, if the ability for VIEWs to have ROWIDs is on or off.  If SQLite
2472** is compiled without -DSQLITE_ALLOW_ROWID_IN_VIEW (which is the usual and
2473** recommended case) then the integer is always filled with zero, regardless
2474** if its initial value.
2475** </dl>
2476*/
2477#define SQLITE_CONFIG_SINGLETHREAD         1  /* nil */
2478#define SQLITE_CONFIG_MULTITHREAD          2  /* nil */
2479#define SQLITE_CONFIG_SERIALIZED           3  /* nil */
2480#define SQLITE_CONFIG_MALLOC               4  /* sqlite3_mem_methods* */
2481#define SQLITE_CONFIG_GETMALLOC            5  /* sqlite3_mem_methods* */
2482#define SQLITE_CONFIG_SCRATCH              6  /* No longer used */
2483#define SQLITE_CONFIG_PAGECACHE            7  /* void*, int sz, int N */
2484#define SQLITE_CONFIG_HEAP                 8  /* void*, int nByte, int min */
2485#define SQLITE_CONFIG_MEMSTATUS            9  /* boolean */
2486#define SQLITE_CONFIG_MUTEX               10  /* sqlite3_mutex_methods* */
2487#define SQLITE_CONFIG_GETMUTEX            11  /* sqlite3_mutex_methods* */
2488/* previously SQLITE_CONFIG_CHUNKALLOC    12 which is now unused. */
2489#define SQLITE_CONFIG_LOOKASIDE           13  /* int int */
2490#define SQLITE_CONFIG_PCACHE              14  /* no-op */
2491#define SQLITE_CONFIG_GETPCACHE           15  /* no-op */
2492#define SQLITE_CONFIG_LOG                 16  /* xFunc, void* */
2493#define SQLITE_CONFIG_URI                 17  /* int */
2494#define SQLITE_CONFIG_PCACHE2             18  /* sqlite3_pcache_methods2* */
2495#define SQLITE_CONFIG_GETPCACHE2          19  /* sqlite3_pcache_methods2* */
2496#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
2497#define SQLITE_CONFIG_SQLLOG              21  /* xSqllog, void* */
2498#define SQLITE_CONFIG_MMAP_SIZE           22  /* sqlite3_int64, sqlite3_int64 */
2499#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
2500#define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
2501#define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
2502#define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */
2503#define SQLITE_CONFIG_SMALL_MALLOC        27  /* boolean */
2504#define SQLITE_CONFIG_SORTERREF_SIZE      28  /* int nByte */
2505#define SQLITE_CONFIG_MEMDB_MAXSIZE       29  /* sqlite3_int64 */
2506#define SQLITE_CONFIG_ROWID_IN_VIEW       30  /* int* */
2507
2508/*
2509** CAPI3REF: Database Connection Configuration Options
2510**
2511** These constants are the available integer configuration options that
2512** can be passed as the second argument to the [sqlite3_db_config()] interface.
2513**
2514** New configuration options may be added in future releases of SQLite.
2515** Existing configuration options might be discontinued.  Applications
2516** should check the return code from [sqlite3_db_config()] to make sure that
2517** the call worked.  ^The [sqlite3_db_config()] interface will return a
2518** non-zero [error code] if a discontinued or unsupported configuration option
2519** is invoked.
2520**
2521** <dl>
2522** [[SQLITE_DBCONFIG_LOOKASIDE]]
2523** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2524** <dd> ^This option takes three additional arguments that determine the
2525** [lookaside memory allocator] configuration for the [database connection].
2526** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2527** pointer to a memory buffer to use for lookaside memory.
2528** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2529** may be NULL in which case SQLite will allocate the
2530** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2531** size of each lookaside buffer slot.  ^The third argument is the number of
2532** slots.  The size of the buffer in the first argument must be greater than
2533** or equal to the product of the second and third arguments.  The buffer
2534** must be aligned to an 8-byte boundary.  ^If the second argument to
2535** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2536** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2537** configuration for a database connection can only be changed when that
2538** connection is not currently using lookaside memory, or in other words
2539** when the "current value" returned by
2540** [sqlite3_db_status](D,[SQLITE_DBSTATUS_LOOKASIDE_USED],...) is zero.
2541** Any attempt to change the lookaside memory configuration when lookaside
2542** memory is in use leaves the configuration unchanged and returns
2543** [SQLITE_BUSY].)^</dd>
2544**
2545** [[SQLITE_DBCONFIG_ENABLE_FKEY]]
2546** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2547** <dd> ^This option is used to enable or disable the enforcement of
2548** [foreign key constraints].  There should be two additional arguments.
2549** The first argument is an integer which is 0 to disable FK enforcement,
2550** positive to enable FK enforcement or negative to leave FK enforcement
2551** unchanged.  The second parameter is a pointer to an integer into which
2552** is written 0 or 1 to indicate whether FK enforcement is off or on
2553** following this call.  The second parameter may be a NULL pointer, in
2554** which case the FK enforcement setting is not reported back. </dd>
2555**
2556** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]
2557** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2558** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2559** There should be two additional arguments.
2560** The first argument is an integer which is 0 to disable triggers,
2561** positive to enable triggers or negative to leave the setting unchanged.
2562** The second parameter is a pointer to an integer into which
2563** is written 0 or 1 to indicate whether triggers are disabled or enabled
2564** following this call.  The second parameter may be a NULL pointer, in
2565** which case the trigger setting is not reported back.
2566**
2567** <p>Originally this option disabled all triggers.  ^(However, since
2568** SQLite version 3.35.0, TEMP triggers are still allowed even if
2569** this option is off.  So, in other words, this option now only disables
2570** triggers in the main database schema or in the schemas of ATTACH-ed
2571** databases.)^ </dd>
2572**
2573** [[SQLITE_DBCONFIG_ENABLE_VIEW]]
2574** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt>
2575** <dd> ^This option is used to enable or disable [CREATE VIEW | views].
2576** There should be two additional arguments.
2577** The first argument is an integer which is 0 to disable views,
2578** positive to enable views or negative to leave the setting unchanged.
2579** The second parameter is a pointer to an integer into which
2580** is written 0 or 1 to indicate whether views are disabled or enabled
2581** following this call.  The second parameter may be a NULL pointer, in
2582** which case the view setting is not reported back.
2583**
2584** <p>Originally this option disabled all views.  ^(However, since
2585** SQLite version 3.35.0, TEMP views are still allowed even if
2586** this option is off.  So, in other words, this option now only disables
2587** views in the main database schema or in the schemas of ATTACH-ed
2588** databases.)^ </dd>
2589**
2590** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
2591** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
2592** <dd> ^This option is used to enable or disable the
2593** [fts3_tokenizer()] function which is part of the
2594** [FTS3] full-text search engine extension.
2595** There should be two additional arguments.
2596** The first argument is an integer which is 0 to disable fts3_tokenizer() or
2597** positive to enable fts3_tokenizer() or negative to leave the setting
2598** unchanged.
2599** The second parameter is a pointer to an integer into which
2600** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
2601** following this call.  The second parameter may be a NULL pointer, in
2602** which case the new setting is not reported back. </dd>
2603**
2604** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]
2605** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
2606** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
2607** interface independently of the [load_extension()] SQL function.
2608** The [sqlite3_enable_load_extension()] API enables or disables both the
2609** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
2610** There should be two additional arguments.
2611** When the first argument to this interface is 1, then only the C-API is
2612** enabled and the SQL function remains disabled.  If the first argument to
2613** this interface is 0, then both the C-API and the SQL function are disabled.
2614** If the first argument is -1, then no changes are made to state of either the
2615** C-API or the SQL function.
2616** The second parameter is a pointer to an integer into which
2617** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
2618** is disabled or enabled following this call.  The second parameter may
2619** be a NULL pointer, in which case the new setting is not reported back.
2620** </dd>
2621**
2622** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
2623** <dd> ^This option is used to change the name of the "main" database
2624** schema.  ^The sole argument is a pointer to a constant UTF8 string
2625** which will become the new schema name in place of "main".  ^SQLite
2626** does not make a copy of the new main schema name string, so the application
2627** must ensure that the argument passed into this DBCONFIG option is unchanged
2628** until after the database connection closes.
2629** </dd>
2630**
2631** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]]
2632** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
2633** <dd> Usually, when a database in wal mode is closed or detached from a
2634** database handle, SQLite checks if this will mean that there are now no
2635** connections at all to the database. If so, it performs a checkpoint
2636** operation before closing the connection. This option may be used to
2637** override this behavior. The first parameter passed to this operation
2638** is an integer - positive to disable checkpoints-on-close, or zero (the
2639** default) to enable them, and negative to leave the setting unchanged.
2640** The second parameter is a pointer to an integer
2641** into which is written 0 or 1 to indicate whether checkpoints-on-close
2642** have been disabled - 0 if they are not disabled, 1 if they are.
2643** </dd>
2644**
2645** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
2646** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
2647** the [query planner stability guarantee] (QPSG).  When the QPSG is active,
2648** a single SQL query statement will always use the same algorithm regardless
2649** of values of [bound parameters].)^ The QPSG disables some query optimizations
2650** that look at the values of bound parameters, which can make some queries
2651** slower.  But the QPSG has the advantage of more predictable behavior.  With
2652** the QPSG active, SQLite will always use the same query plan in the field as
2653** was used during testing in the lab.
2654** The first argument to this setting is an integer which is 0 to disable
2655** the QPSG, positive to enable QPSG, or negative to leave the setting
2656** unchanged. The second parameter is a pointer to an integer into which
2657** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
2658** following this call.
2659** </dd>
2660**
2661** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
2662** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
2663** include output for any operations performed by trigger programs. This
2664** option is used to set or clear (the default) a flag that governs this
2665** behavior. The first parameter passed to this operation is an integer -
2666** positive to enable output for trigger programs, or zero to disable it,
2667** or negative to leave the setting unchanged.
2668** The second parameter is a pointer to an integer into which is written
2669** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
2670** it is not disabled, 1 if it is.
2671** </dd>
2672**
2673** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
2674** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
2675** [VACUUM] in order to reset a database back to an empty database
2676** with no schema and no content. The following process works even for
2677** a badly corrupted database file:
2678** <ol>
2679** <li> If the database connection is newly opened, make sure it has read the
2680**      database schema by preparing then discarding some query against the
2681**      database, or calling sqlite3_table_column_metadata(), ignoring any
2682**      errors.  This step is only necessary if the application desires to keep
2683**      the database in WAL mode after the reset if it was in WAL mode before
2684**      the reset.
2685** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
2686** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
2687** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
2688** </ol>
2689** Because resetting a database is destructive and irreversible, the
2690** process requires the use of this obscure API and multiple steps to
2691** help ensure that it does not happen by accident. Because this
2692** feature must be capable of resetting corrupt databases, and
2693** shutting down virtual tables may require access to that corrupt
2694** storage, the library must abandon any installed virtual tables
2695** without calling their xDestroy() methods.
2696**
2697** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>
2698** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
2699** "defensive" flag for a database connection.  When the defensive
2700** flag is enabled, language features that allow ordinary SQL to
2701** deliberately corrupt the database file are disabled.  The disabled
2702** features include but are not limited to the following:
2703** <ul>
2704** <li> The [PRAGMA writable_schema=ON] statement.
2705** <li> The [PRAGMA journal_mode=OFF] statement.
2706** <li> The [PRAGMA schema_version=N] statement.
2707** <li> Writes to the [sqlite_dbpage] virtual table.
2708** <li> Direct writes to [shadow tables].
2709** </ul>
2710** </dd>
2711**
2712** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt>
2713** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the
2714** "writable_schema" flag. This has the same effect and is logically equivalent
2715** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].
2716** The first argument to this setting is an integer which is 0 to disable
2717** the writable_schema, positive to enable writable_schema, or negative to
2718** leave the setting unchanged. The second parameter is a pointer to an
2719** integer into which is written 0 or 1 to indicate whether the writable_schema
2720** is enabled or disabled following this call.
2721** </dd>
2722**
2723** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]]
2724** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt>
2725** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates
2726** the legacy behavior of the [ALTER TABLE RENAME] command such it
2727** behaves as it did prior to [version 3.24.0] (2018-06-04).  See the
2728** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for
2729** additional information. This feature can also be turned on and off
2730** using the [PRAGMA legacy_alter_table] statement.
2731** </dd>
2732**
2733** [[SQLITE_DBCONFIG_DQS_DML]]
2734** <dt>SQLITE_DBCONFIG_DQS_DML</dt>
2735** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
2736** the legacy [double-quoted string literal] misfeature for DML statements
2737** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
2738** default value of this setting is determined by the [-DSQLITE_DQS]
2739** compile-time option.
2740** </dd>
2741**
2742** [[SQLITE_DBCONFIG_DQS_DDL]]
2743** <dt>SQLITE_DBCONFIG_DQS_DDL</dt>
2744** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates
2745** the legacy [double-quoted string literal] misfeature for DDL statements,
2746** such as CREATE TABLE and CREATE INDEX. The
2747** default value of this setting is determined by the [-DSQLITE_DQS]
2748** compile-time option.
2749** </dd>
2750**
2751** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]
2752** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</dt>
2753** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to
2754** assume that database schemas are untainted by malicious content.
2755** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite
2756** takes additional defensive steps to protect the application from harm
2757** including:
2758** <ul>
2759** <li> Prohibit the use of SQL functions inside triggers, views,
2760** CHECK constraints, DEFAULT clauses, expression indexes,
2761** partial indexes, or generated columns
2762** unless those functions are tagged with [SQLITE_INNOCUOUS].
2763** <li> Prohibit the use of virtual tables inside of triggers or views
2764** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].
2765** </ul>
2766** This setting defaults to "on" for legacy compatibility, however
2767** all applications are advised to turn it off if possible. This setting
2768** can also be controlled using the [PRAGMA trusted_schema] statement.
2769** </dd>
2770**
2771** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]
2772** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</dt>
2773** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates
2774** the legacy file format flag.  When activated, this flag causes all newly
2775** created database file to have a schema format version number (the 4-byte
2776** integer found at offset 44 into the database header) of 1.  This in turn
2777** means that the resulting database file will be readable and writable by
2778** any SQLite version back to 3.0.0 ([dateof:3.0.0]).  Without this setting,
2779** newly created databases are generally not understandable by SQLite versions
2780** prior to 3.3.0 ([dateof:3.3.0]).  As these words are written, there
2781** is now scarcely any need to generate database files that are compatible
2782** all the way back to version 3.0.0, and so this setting is of little
2783** practical use, but is provided so that SQLite can continue to claim the
2784** ability to generate new database files that are compatible with  version
2785** 3.0.0.
2786** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,
2787** the [VACUUM] command will fail with an obscure error when attempting to
2788** process a table with generated columns and a descending index.  This is
2789** not considered a bug since SQLite versions 3.3.0 and earlier do not support
2790** either generated columns or descending indexes.
2791** </dd>
2792**
2793** [[SQLITE_DBCONFIG_STMT_SCANSTATUS]]
2794** <dt>SQLITE_DBCONFIG_STMT_SCANSTATUS</dt>
2795** <dd>The SQLITE_DBCONFIG_STMT_SCANSTATUS option is only useful in
2796** SQLITE_ENABLE_STMT_SCANSTATUS builds. In this case, it sets or clears
2797** a flag that enables collection of the sqlite3_stmt_scanstatus_v2()
2798** statistics. For statistics to be collected, the flag must be set on
2799** the database handle both when the SQL statement is prepared and when it
2800** is stepped. The flag is set (collection of statistics is enabled)
2801** by default.  This option takes two arguments: an integer and a pointer to
2802** an integer..  The first argument is 1, 0, or -1 to enable, disable, or
2803** leave unchanged the statement scanstatus option.  If the second argument
2804** is not NULL, then the value of the statement scanstatus setting after
2805** processing the first argument is written into the integer that the second
2806** argument points to.
2807** </dd>
2808**
2809** [[SQLITE_DBCONFIG_REVERSE_SCANORDER]]
2810** <dt>SQLITE_DBCONFIG_REVERSE_SCANORDER</dt>
2811** <dd>The SQLITE_DBCONFIG_REVERSE_SCANORDER option changes the default order
2812** in which tables and indexes are scanned so that the scans start at the end
2813** and work toward the beginning rather than starting at the beginning and
2814** working toward the end. Setting SQLITE_DBCONFIG_REVERSE_SCANORDER is the
2815** same as setting [PRAGMA reverse_unordered_selects].  This option takes
2816** two arguments which are an integer and a pointer to an integer.  The first
2817** argument is 1, 0, or -1 to enable, disable, or leave unchanged the
2818** reverse scan order flag, respectively.  If the second argument is not NULL,
2819** then 0 or 1 is written into the integer that the second argument points to
2820** depending on if the reverse scan order flag is set after processing the
2821** first argument.
2822** </dd>
2823**
2824** </dl>
2825*/
2826#define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
2827#define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
2828#define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
2829#define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
2830#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
2831#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
2832#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */
2833#define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */
2834#define SQLITE_DBCONFIG_TRIGGER_EQP           1008 /* int int* */
2835#define SQLITE_DBCONFIG_RESET_DATABASE        1009 /* int int* */
2836#define SQLITE_DBCONFIG_DEFENSIVE             1010 /* int int* */
2837#define SQLITE_DBCONFIG_WRITABLE_SCHEMA       1011 /* int int* */
2838#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    1012 /* int int* */
2839#define SQLITE_DBCONFIG_DQS_DML               1013 /* int int* */
2840#define SQLITE_DBCONFIG_DQS_DDL               1014 /* int int* */
2841#define SQLITE_DBCONFIG_ENABLE_VIEW           1015 /* int int* */
2842#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    1016 /* int int* */
2843#define SQLITE_DBCONFIG_TRUSTED_SCHEMA        1017 /* int int* */
2844#define SQLITE_DBCONFIG_STMT_SCANSTATUS       1018 /* int int* */
2845#define SQLITE_DBCONFIG_REVERSE_SCANORDER     1019 /* int int* */
2846#define SQLITE_DBCONFIG_MAX                   1019 /* Largest DBCONFIG */
2847
2848/*
2849** CAPI3REF: Enable Or Disable Extended Result Codes
2850** METHOD: sqlite3
2851**
2852** ^The sqlite3_extended_result_codes() routine enables or disables the
2853** [extended result codes] feature of SQLite. ^The extended result
2854** codes are disabled by default for historical compatibility.
2855*/
2856SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2857
2858/*
2859** CAPI3REF: Last Insert Rowid
2860** METHOD: sqlite3
2861**
2862** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
2863** has a unique 64-bit signed
2864** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2865** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2866** names are not also used by explicitly declared columns. ^If
2867** the table has a column of type [INTEGER PRIMARY KEY] then that column
2868** is another alias for the rowid.
2869**
2870** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
2871** the most recent successful [INSERT] into a rowid table or [virtual table]
2872** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
2873** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
2874** on the database connection D, then sqlite3_last_insert_rowid(D) returns
2875** zero.
2876**
2877** As well as being set automatically as rows are inserted into database
2878** tables, the value returned by this function may be set explicitly by
2879** [sqlite3_set_last_insert_rowid()]
2880**
2881** Some virtual table implementations may INSERT rows into rowid tables as
2882** part of committing a transaction (e.g. to flush data accumulated in memory
2883** to disk). In this case subsequent calls to this function return the rowid
2884** associated with these internal INSERT operations, which leads to
2885** unintuitive results. Virtual table implementations that do write to rowid
2886** tables in this way can avoid this problem by restoring the original
2887** rowid value using [sqlite3_set_last_insert_rowid()] before returning
2888** control to the user.
2889**
2890** ^(If an [INSERT] occurs within a trigger then this routine will
2891** return the [rowid] of the inserted row as long as the trigger is
2892** running. Once the trigger program ends, the value returned
2893** by this routine reverts to what it was before the trigger was fired.)^
2894**
2895** ^An [INSERT] that fails due to a constraint violation is not a
2896** successful [INSERT] and does not change the value returned by this
2897** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2898** and INSERT OR ABORT make no changes to the return value of this
2899** routine when their insertion fails.  ^(When INSERT OR REPLACE
2900** encounters a constraint violation, it does not fail.  The
2901** INSERT continues to completion after deleting rows that caused
2902** the constraint problem so INSERT OR REPLACE will always change
2903** the return value of this interface.)^
2904**
2905** ^For the purposes of this routine, an [INSERT] is considered to
2906** be successful even if it is subsequently rolled back.
2907**
2908** This function is accessible to SQL statements via the
2909** [last_insert_rowid() SQL function].
2910**
2911** If a separate thread performs a new [INSERT] on the same
2912** database connection while the [sqlite3_last_insert_rowid()]
2913** function is running and thus changes the last insert [rowid],
2914** then the value returned by [sqlite3_last_insert_rowid()] is
2915** unpredictable and might not equal either the old or the new
2916** last insert [rowid].
2917*/
2918SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2919
2920/*
2921** CAPI3REF: Set the Last Insert Rowid value.
2922** METHOD: sqlite3
2923**
2924** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
2925** set the value returned by calling sqlite3_last_insert_rowid(D) to R
2926** without inserting a row into the database.
2927*/
2928SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
2929
2930/*
2931** CAPI3REF: Count The Number Of Rows Modified
2932** METHOD: sqlite3
2933**
2934** ^These functions return the number of rows modified, inserted or
2935** deleted by the most recently completed INSERT, UPDATE or DELETE
2936** statement on the database connection specified by the only parameter.
2937** The two functions are identical except for the type of the return value
2938** and that if the number of rows modified by the most recent INSERT, UPDATE
2939** or DELETE is greater than the maximum value supported by type "int", then
2940** the return value of sqlite3_changes() is undefined. ^Executing any other
2941** type of SQL statement does not modify the value returned by these functions.
2942**
2943** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
2944** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
2945** [foreign key actions] or [REPLACE] constraint resolution are not counted.
2946**
2947** Changes to a view that are intercepted by
2948** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
2949** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
2950** DELETE statement run on a view is always zero. Only changes made to real
2951** tables are counted.
2952**
2953** Things are more complicated if the sqlite3_changes() function is
2954** executed while a trigger program is running. This may happen if the
2955** program uses the [changes() SQL function], or if some other callback
2956** function invokes sqlite3_changes() directly. Essentially:
2957**
2958** <ul>
2959**   <li> ^(Before entering a trigger program the value returned by
2960**        sqlite3_changes() function is saved. After the trigger program
2961**        has finished, the original value is restored.)^
2962**
2963**   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
2964**        statement sets the value returned by sqlite3_changes()
2965**        upon completion as normal. Of course, this value will not include
2966**        any changes performed by sub-triggers, as the sqlite3_changes()
2967**        value will be saved and restored after each sub-trigger has run.)^
2968** </ul>
2969**
2970** ^This means that if the changes() SQL function (or similar) is used
2971** by the first INSERT, UPDATE or DELETE statement within a trigger, it
2972** returns the value as set when the calling statement began executing.
2973** ^If it is used by the second or subsequent such statement within a trigger
2974** program, the value returned reflects the number of rows modified by the
2975** previous INSERT, UPDATE or DELETE statement within the same trigger.
2976**
2977** If a separate thread makes changes on the same database connection
2978** while [sqlite3_changes()] is running then the value returned
2979** is unpredictable and not meaningful.
2980**
2981** See also:
2982** <ul>
2983** <li> the [sqlite3_total_changes()] interface
2984** <li> the [count_changes pragma]
2985** <li> the [changes() SQL function]
2986** <li> the [data_version pragma]
2987** </ul>
2988*/
2989SQLITE_API int sqlite3_changes(sqlite3*);
2990SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3*);
2991
2992/*
2993** CAPI3REF: Total Number Of Rows Modified
2994** METHOD: sqlite3
2995**
2996** ^These functions return the total number of rows inserted, modified or
2997** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
2998** since the database connection was opened, including those executed as
2999** part of trigger programs. The two functions are identical except for the
3000** type of the return value and that if the number of rows modified by the
3001** connection exceeds the maximum value supported by type "int", then
3002** the return value of sqlite3_total_changes() is undefined. ^Executing
3003** any other type of SQL statement does not affect the value returned by
3004** sqlite3_total_changes().
3005**
3006** ^Changes made as part of [foreign key actions] are included in the
3007** count, but those made as part of REPLACE constraint resolution are
3008** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
3009** are not counted.
3010**
3011** The [sqlite3_total_changes(D)] interface only reports the number
3012** of rows that changed due to SQL statement run against database
3013** connection D.  Any changes by other database connections are ignored.
3014** To detect changes against a database file from other database
3015** connections use the [PRAGMA data_version] command or the
3016** [SQLITE_FCNTL_DATA_VERSION] [file control].
3017**
3018** If a separate thread makes changes on the same database connection
3019** while [sqlite3_total_changes()] is running then the value
3020** returned is unpredictable and not meaningful.
3021**
3022** See also:
3023** <ul>
3024** <li> the [sqlite3_changes()] interface
3025** <li> the [count_changes pragma]
3026** <li> the [changes() SQL function]
3027** <li> the [data_version pragma]
3028** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]
3029** </ul>
3030*/
3031SQLITE_API int sqlite3_total_changes(sqlite3*);
3032SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3*);
3033
3034/*
3035** CAPI3REF: Interrupt A Long-Running Query
3036** METHOD: sqlite3
3037**
3038** ^This function causes any pending database operation to abort and
3039** return at its earliest opportunity. This routine is typically
3040** called in response to a user action such as pressing "Cancel"
3041** or Ctrl-C where the user wants a long query operation to halt
3042** immediately.
3043**
3044** ^It is safe to call this routine from a thread different from the
3045** thread that is currently running the database operation.  But it
3046** is not safe to call this routine with a [database connection] that
3047** is closed or might close before sqlite3_interrupt() returns.
3048**
3049** ^If an SQL operation is very nearly finished at the time when
3050** sqlite3_interrupt() is called, then it might not have an opportunity
3051** to be interrupted and might continue to completion.
3052**
3053** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
3054** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
3055** that is inside an explicit transaction, then the entire transaction
3056** will be rolled back automatically.
3057**
3058** ^The sqlite3_interrupt(D) call is in effect until all currently running
3059** SQL statements on [database connection] D complete.  ^Any new SQL statements
3060** that are started after the sqlite3_interrupt() call and before the
3061** running statement count reaches zero are interrupted as if they had been
3062** running prior to the sqlite3_interrupt() call.  ^New SQL statements
3063** that are started after the running statement count reaches zero are
3064** not effected by the sqlite3_interrupt().
3065** ^A call to sqlite3_interrupt(D) that occurs when there are no running
3066** SQL statements is a no-op and has no effect on SQL statements
3067** that are started after the sqlite3_interrupt() call returns.
3068**
3069** ^The [sqlite3_is_interrupted(D)] interface can be used to determine whether
3070** or not an interrupt is currently in effect for [database connection] D.
3071** It returns 1 if an interrupt is currently in effect, or 0 otherwise.
3072*/
3073SQLITE_API void sqlite3_interrupt(sqlite3*);
3074SQLITE_API int sqlite3_is_interrupted(sqlite3*);
3075
3076/*
3077** CAPI3REF: Determine If An SQL Statement Is Complete
3078**
3079** These routines are useful during command-line input to determine if the
3080** currently entered text seems to form a complete SQL statement or
3081** if additional input is needed before sending the text into
3082** SQLite for parsing.  ^These routines return 1 if the input string
3083** appears to be a complete SQL statement.  ^A statement is judged to be
3084** complete if it ends with a semicolon token and is not a prefix of a
3085** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
3086** string literals or quoted identifier names or comments are not
3087** independent tokens (they are part of the token in which they are
3088** embedded) and thus do not count as a statement terminator.  ^Whitespace
3089** and comments that follow the final semicolon are ignored.
3090**
3091** ^These routines return 0 if the statement is incomplete.  ^If a
3092** memory allocation fails, then SQLITE_NOMEM is returned.
3093**
3094** ^These routines do not parse the SQL statements thus
3095** will not detect syntactically incorrect SQL.
3096**
3097** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
3098** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
3099** automatically by sqlite3_complete16().  If that initialization fails,
3100** then the return value from sqlite3_complete16() will be non-zero
3101** regardless of whether or not the input SQL is complete.)^
3102**
3103** The input to [sqlite3_complete()] must be a zero-terminated
3104** UTF-8 string.
3105**
3106** The input to [sqlite3_complete16()] must be a zero-terminated
3107** UTF-16 string in native byte order.
3108*/
3109SQLITE_API int sqlite3_complete(const char *sql);
3110SQLITE_API int sqlite3_complete16(const void *sql);
3111
3112/*
3113** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
3114** KEYWORDS: {busy-handler callback} {busy handler}
3115** METHOD: sqlite3
3116**
3117** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
3118** that might be invoked with argument P whenever
3119** an attempt is made to access a database table associated with
3120** [database connection] D when another thread
3121** or process has the table locked.
3122** The sqlite3_busy_handler() interface is used to implement
3123** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
3124**
3125** ^If the busy callback is NULL, then [SQLITE_BUSY]
3126** is returned immediately upon encountering the lock.  ^If the busy callback
3127** is not NULL, then the callback might be invoked with two arguments.
3128**
3129** ^The first argument to the busy handler is a copy of the void* pointer which
3130** is the third argument to sqlite3_busy_handler().  ^The second argument to
3131** the busy handler callback is the number of times that the busy handler has
3132** been invoked previously for the same locking event.  ^If the
3133** busy callback returns 0, then no additional attempts are made to
3134** access the database and [SQLITE_BUSY] is returned
3135** to the application.
3136** ^If the callback returns non-zero, then another attempt
3137** is made to access the database and the cycle repeats.
3138**
3139** The presence of a busy handler does not guarantee that it will be invoked
3140** when there is lock contention. ^If SQLite determines that invoking the busy
3141** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
3142** to the application instead of invoking the
3143** busy handler.
3144** Consider a scenario where one process is holding a read lock that
3145** it is trying to promote to a reserved lock and
3146** a second process is holding a reserved lock that it is trying
3147** to promote to an exclusive lock.  The first process cannot proceed
3148** because it is blocked by the second and the second process cannot
3149** proceed because it is blocked by the first.  If both processes
3150** invoke the busy handlers, neither will make any progress.  Therefore,
3151** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
3152** will induce the first process to release its read lock and allow
3153** the second process to proceed.
3154**
3155** ^The default busy callback is NULL.
3156**
3157** ^(There can only be a single busy handler defined for each
3158** [database connection].  Setting a new busy handler clears any
3159** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
3160** or evaluating [PRAGMA busy_timeout=N] will change the
3161** busy handler and thus clear any previously set busy handler.
3162**
3163** The busy callback should not take any actions which modify the
3164** database connection that invoked the busy handler.  In other words,
3165** the busy handler is not reentrant.  Any such actions
3166** result in undefined behavior.
3167**
3168** A busy handler must not close the database connection
3169** or [prepared statement] that invoked the busy handler.
3170*/
3171SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
3172
3173/*
3174** CAPI3REF: Set A Busy Timeout
3175** METHOD: sqlite3
3176**
3177** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
3178** for a specified amount of time when a table is locked.  ^The handler
3179** will sleep multiple times until at least "ms" milliseconds of sleeping
3180** have accumulated.  ^After at least "ms" milliseconds of sleeping,
3181** the handler returns 0 which causes [sqlite3_step()] to return
3182** [SQLITE_BUSY].
3183**
3184** ^Calling this routine with an argument less than or equal to zero
3185** turns off all busy handlers.
3186**
3187** ^(There can only be a single busy handler for a particular
3188** [database connection] at any given moment.  If another busy handler
3189** was defined  (using [sqlite3_busy_handler()]) prior to calling
3190** this routine, that other busy handler is cleared.)^
3191**
3192** See also:  [PRAGMA busy_timeout]
3193*/
3194SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
3195
3196/*
3197** CAPI3REF: Convenience Routines For Running Queries
3198** METHOD: sqlite3
3199**
3200** This is a legacy interface that is preserved for backwards compatibility.
3201** Use of this interface is not recommended.
3202**
3203** Definition: A <b>result table</b> is memory data structure created by the
3204** [sqlite3_get_table()] interface.  A result table records the
3205** complete query results from one or more queries.
3206**
3207** The table conceptually has a number of rows and columns.  But
3208** these numbers are not part of the result table itself.  These
3209** numbers are obtained separately.  Let N be the number of rows
3210** and M be the number of columns.
3211**
3212** A result table is an array of pointers to zero-terminated UTF-8 strings.
3213** There are (N+1)*M elements in the array.  The first M pointers point
3214** to zero-terminated strings that  contain the names of the columns.
3215** The remaining entries all point to query results.  NULL values result
3216** in NULL pointers.  All other values are in their UTF-8 zero-terminated
3217** string representation as returned by [sqlite3_column_text()].
3218**
3219** A result table might consist of one or more memory allocations.
3220** It is not safe to pass a result table directly to [sqlite3_free()].
3221** A result table should be deallocated using [sqlite3_free_table()].
3222**
3223** ^(As an example of the result table format, suppose a query result
3224** is as follows:
3225**
3226** <blockquote><pre>
3227**        Name        | Age
3228**        -----------------------
3229**        Alice       | 43
3230**        Bob         | 28
3231**        Cindy       | 21
3232** </pre></blockquote>
3233**
3234** There are two columns (M==2) and three rows (N==3).  Thus the
3235** result table has 8 entries.  Suppose the result table is stored
3236** in an array named azResult.  Then azResult holds this content:
3237**
3238** <blockquote><pre>
3239**        azResult&#91;0] = "Name";
3240**        azResult&#91;1] = "Age";
3241**        azResult&#91;2] = "Alice";
3242**        azResult&#91;3] = "43";
3243**        azResult&#91;4] = "Bob";
3244**        azResult&#91;5] = "28";
3245**        azResult&#91;6] = "Cindy";
3246**        azResult&#91;7] = "21";
3247** </pre></blockquote>)^
3248**
3249** ^The sqlite3_get_table() function evaluates one or more
3250** semicolon-separated SQL statements in the zero-terminated UTF-8
3251** string of its 2nd parameter and returns a result table to the
3252** pointer given in its 3rd parameter.
3253**
3254** After the application has finished with the result from sqlite3_get_table(),
3255** it must pass the result table pointer to sqlite3_free_table() in order to
3256** release the memory that was malloced.  Because of the way the
3257** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
3258** function must not try to call [sqlite3_free()] directly.  Only
3259** [sqlite3_free_table()] is able to release the memory properly and safely.
3260**
3261** The sqlite3_get_table() interface is implemented as a wrapper around
3262** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
3263** to any internal data structures of SQLite.  It uses only the public
3264** interface defined here.  As a consequence, errors that occur in the
3265** wrapper layer outside of the internal [sqlite3_exec()] call are not
3266** reflected in subsequent calls to [sqlite3_errcode()] or
3267** [sqlite3_errmsg()].
3268*/
3269SQLITE_API int sqlite3_get_table(
3270  sqlite3 *db,          /* An open database */
3271  const char *zSql,     /* SQL to be evaluated */
3272  char ***pazResult,    /* Results of the query */
3273  int *pnRow,           /* Number of result rows written here */
3274  int *pnColumn,        /* Number of result columns written here */
3275  char **pzErrmsg       /* Error msg written here */
3276);
3277SQLITE_API void sqlite3_free_table(char **result);
3278
3279/*
3280** CAPI3REF: Formatted String Printing Functions
3281**
3282** These routines are work-alikes of the "printf()" family of functions
3283** from the standard C library.
3284** These routines understand most of the common formatting options from
3285** the standard library printf()
3286** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
3287** See the [built-in printf()] documentation for details.
3288**
3289** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
3290** results into memory obtained from [sqlite3_malloc64()].
3291** The strings returned by these two routines should be
3292** released by [sqlite3_free()].  ^Both routines return a
3293** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough
3294** memory to hold the resulting string.
3295**
3296** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
3297** the standard C library.  The result is written into the
3298** buffer supplied as the second parameter whose size is given by
3299** the first parameter. Note that the order of the
3300** first two parameters is reversed from snprintf().)^  This is an
3301** historical accident that cannot be fixed without breaking
3302** backwards compatibility.  ^(Note also that sqlite3_snprintf()
3303** returns a pointer to its buffer instead of the number of
3304** characters actually written into the buffer.)^  We admit that
3305** the number of characters written would be a more useful return
3306** value but we cannot change the implementation of sqlite3_snprintf()
3307** now without breaking compatibility.
3308**
3309** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
3310** guarantees that the buffer is always zero-terminated.  ^The first
3311** parameter "n" is the total size of the buffer, including space for
3312** the zero terminator.  So the longest string that can be completely
3313** written will be n-1 characters.
3314**
3315** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
3316**
3317** See also:  [built-in printf()], [printf() SQL function]
3318*/
3319SQLITE_API char *sqlite3_mprintf(const char*,...);
3320SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
3321SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
3322SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
3323
3324/*
3325** CAPI3REF: Memory Allocation Subsystem
3326**
3327** The SQLite core uses these three routines for all of its own
3328** internal memory allocation needs. "Core" in the previous sentence
3329** does not include operating-system specific [VFS] implementation.  The
3330** Windows VFS uses native malloc() and free() for some operations.
3331**
3332** ^The sqlite3_malloc() routine returns a pointer to a block
3333** of memory at least N bytes in length, where N is the parameter.
3334** ^If sqlite3_malloc() is unable to obtain sufficient free
3335** memory, it returns a NULL pointer.  ^If the parameter N to
3336** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
3337** a NULL pointer.
3338**
3339** ^The sqlite3_malloc64(N) routine works just like
3340** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
3341** of a signed 32-bit integer.
3342**
3343** ^Calling sqlite3_free() with a pointer previously returned
3344** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
3345** that it might be reused.  ^The sqlite3_free() routine is
3346** a no-op if is called with a NULL pointer.  Passing a NULL pointer
3347** to sqlite3_free() is harmless.  After being freed, memory
3348** should neither be read nor written.  Even reading previously freed
3349** memory might result in a segmentation fault or other severe error.
3350** Memory corruption, a segmentation fault, or other severe error
3351** might result if sqlite3_free() is called with a non-NULL pointer that
3352** was not obtained from sqlite3_malloc() or sqlite3_realloc().
3353**
3354** ^The sqlite3_realloc(X,N) interface attempts to resize a
3355** prior memory allocation X to be at least N bytes.
3356** ^If the X parameter to sqlite3_realloc(X,N)
3357** is a NULL pointer then its behavior is identical to calling
3358** sqlite3_malloc(N).
3359** ^If the N parameter to sqlite3_realloc(X,N) is zero or
3360** negative then the behavior is exactly the same as calling
3361** sqlite3_free(X).
3362** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
3363** of at least N bytes in size or NULL if insufficient memory is available.
3364** ^If M is the size of the prior allocation, then min(N,M) bytes
3365** of the prior allocation are copied into the beginning of buffer returned
3366** by sqlite3_realloc(X,N) and the prior allocation is freed.
3367** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
3368** prior allocation is not freed.
3369**
3370** ^The sqlite3_realloc64(X,N) interfaces works the same as
3371** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
3372** of a 32-bit signed integer.
3373**
3374** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
3375** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
3376** sqlite3_msize(X) returns the size of that memory allocation in bytes.
3377** ^The value returned by sqlite3_msize(X) might be larger than the number
3378** of bytes requested when X was allocated.  ^If X is a NULL pointer then
3379** sqlite3_msize(X) returns zero.  If X points to something that is not
3380** the beginning of memory allocation, or if it points to a formerly
3381** valid memory allocation that has now been freed, then the behavior
3382** of sqlite3_msize(X) is undefined and possibly harmful.
3383**
3384** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
3385** sqlite3_malloc64(), and sqlite3_realloc64()
3386** is always aligned to at least an 8 byte boundary, or to a
3387** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
3388** option is used.
3389**
3390** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
3391** must be either NULL or else pointers obtained from a prior
3392** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
3393** not yet been released.
3394**
3395** The application must not read or write any part of
3396** a block of memory after it has been released using
3397** [sqlite3_free()] or [sqlite3_realloc()].
3398*/
3399SQLITE_API void *sqlite3_malloc(int);
3400SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
3401SQLITE_API void *sqlite3_realloc(void*, int);
3402SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
3403SQLITE_API void sqlite3_free(void*);
3404SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
3405
3406/*
3407** CAPI3REF: Memory Allocator Statistics
3408**
3409** SQLite provides these two interfaces for reporting on the status
3410** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
3411** routines, which form the built-in memory allocation subsystem.
3412**
3413** ^The [sqlite3_memory_used()] routine returns the number of bytes
3414** of memory currently outstanding (malloced but not freed).
3415** ^The [sqlite3_memory_highwater()] routine returns the maximum
3416** value of [sqlite3_memory_used()] since the high-water mark
3417** was last reset.  ^The values returned by [sqlite3_memory_used()] and
3418** [sqlite3_memory_highwater()] include any overhead
3419** added by SQLite in its implementation of [sqlite3_malloc()],
3420** but not overhead added by the any underlying system library
3421** routines that [sqlite3_malloc()] may call.
3422**
3423** ^The memory high-water mark is reset to the current value of
3424** [sqlite3_memory_used()] if and only if the parameter to
3425** [sqlite3_memory_highwater()] is true.  ^The value returned
3426** by [sqlite3_memory_highwater(1)] is the high-water mark
3427** prior to the reset.
3428*/
3429SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
3430SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
3431
3432/*
3433** CAPI3REF: Pseudo-Random Number Generator
3434**
3435** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
3436** select random [ROWID | ROWIDs] when inserting new records into a table that
3437** already uses the largest possible [ROWID].  The PRNG is also used for
3438** the built-in random() and randomblob() SQL functions.  This interface allows
3439** applications to access the same PRNG for other purposes.
3440**
3441** ^A call to this routine stores N bytes of randomness into buffer P.
3442** ^The P parameter can be a NULL pointer.
3443**
3444** ^If this routine has not been previously called or if the previous
3445** call had N less than one or a NULL pointer for P, then the PRNG is
3446** seeded using randomness obtained from the xRandomness method of
3447** the default [sqlite3_vfs] object.
3448** ^If the previous call to this routine had an N of 1 or more and a
3449** non-NULL P then the pseudo-randomness is generated
3450** internally and without recourse to the [sqlite3_vfs] xRandomness
3451** method.
3452*/
3453SQLITE_API void sqlite3_randomness(int N, void *P);
3454
3455/*
3456** CAPI3REF: Compile-Time Authorization Callbacks
3457** METHOD: sqlite3
3458** KEYWORDS: {authorizer callback}
3459**
3460** ^This routine registers an authorizer callback with a particular
3461** [database connection], supplied in the first argument.
3462** ^The authorizer callback is invoked as SQL statements are being compiled
3463** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
3464** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
3465** and [sqlite3_prepare16_v3()].  ^At various
3466** points during the compilation process, as logic is being created
3467** to perform various actions, the authorizer callback is invoked to
3468** see if those actions are allowed.  ^The authorizer callback should
3469** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
3470** specific action but allow the SQL statement to continue to be
3471** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
3472** rejected with an error.  ^If the authorizer callback returns
3473** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
3474** then the [sqlite3_prepare_v2()] or equivalent call that triggered
3475** the authorizer will fail with an error message.
3476**
3477** When the callback returns [SQLITE_OK], that means the operation
3478** requested is ok.  ^When the callback returns [SQLITE_DENY], the
3479** [sqlite3_prepare_v2()] or equivalent call that triggered the
3480** authorizer will fail with an error message explaining that
3481** access is denied.
3482**
3483** ^The first parameter to the authorizer callback is a copy of the third
3484** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
3485** to the callback is an integer [SQLITE_COPY | action code] that specifies
3486** the particular action to be authorized. ^The third through sixth parameters
3487** to the callback are either NULL pointers or zero-terminated strings
3488** that contain additional details about the action to be authorized.
3489** Applications must always be prepared to encounter a NULL pointer in any
3490** of the third through the sixth parameters of the authorization callback.
3491**
3492** ^If the action code is [SQLITE_READ]
3493** and the callback returns [SQLITE_IGNORE] then the
3494** [prepared statement] statement is constructed to substitute
3495** a NULL value in place of the table column that would have
3496** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
3497** return can be used to deny an untrusted user access to individual
3498** columns of a table.
3499** ^When a table is referenced by a [SELECT] but no column values are
3500** extracted from that table (for example in a query like
3501** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
3502** is invoked once for that table with a column name that is an empty string.
3503** ^If the action code is [SQLITE_DELETE] and the callback returns
3504** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
3505** [truncate optimization] is disabled and all rows are deleted individually.
3506**
3507** An authorizer is used when [sqlite3_prepare | preparing]
3508** SQL statements from an untrusted source, to ensure that the SQL statements
3509** do not try to access data they are not allowed to see, or that they do not
3510** try to execute malicious statements that damage the database.  For
3511** example, an application may allow a user to enter arbitrary
3512** SQL queries for evaluation by a database.  But the application does
3513** not want the user to be able to make arbitrary changes to the
3514** database.  An authorizer could then be put in place while the
3515** user-entered SQL is being [sqlite3_prepare | prepared] that
3516** disallows everything except [SELECT] statements.
3517**
3518** Applications that need to process SQL from untrusted sources
3519** might also consider lowering resource limits using [sqlite3_limit()]
3520** and limiting database size using the [max_page_count] [PRAGMA]
3521** in addition to using an authorizer.
3522**
3523** ^(Only a single authorizer can be in place on a database connection
3524** at a time.  Each call to sqlite3_set_authorizer overrides the
3525** previous call.)^  ^Disable the authorizer by installing a NULL callback.
3526** The authorizer is disabled by default.
3527**
3528** The authorizer callback must not do anything that will modify
3529** the database connection that invoked the authorizer callback.
3530** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3531** database connections for the meaning of "modify" in this paragraph.
3532**
3533** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3534** statement might be re-prepared during [sqlite3_step()] due to a
3535** schema change.  Hence, the application should ensure that the
3536** correct authorizer callback remains in place during the [sqlite3_step()].
3537**
3538** ^Note that the authorizer callback is invoked only during
3539** [sqlite3_prepare()] or its variants.  Authorization is not
3540** performed during statement evaluation in [sqlite3_step()], unless
3541** as stated in the previous paragraph, sqlite3_step() invokes
3542** sqlite3_prepare_v2() to reprepare a statement after a schema change.
3543*/
3544SQLITE_API int sqlite3_set_authorizer(
3545  sqlite3*,
3546  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
3547  void *pUserData
3548);
3549
3550/*
3551** CAPI3REF: Authorizer Return Codes
3552**
3553** The [sqlite3_set_authorizer | authorizer callback function] must
3554** return either [SQLITE_OK] or one of these two constants in order
3555** to signal SQLite whether or not the action is permitted.  See the
3556** [sqlite3_set_authorizer | authorizer documentation] for additional
3557** information.
3558**
3559** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
3560** returned from the [sqlite3_vtab_on_conflict()] interface.
3561*/
3562#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
3563#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
3564
3565/*
3566** CAPI3REF: Authorizer Action Codes
3567**
3568** The [sqlite3_set_authorizer()] interface registers a callback function
3569** that is invoked to authorize certain SQL statement actions.  The
3570** second parameter to the callback is an integer code that specifies
3571** what action is being authorized.  These are the integer action codes that
3572** the authorizer callback may be passed.
3573**
3574** These action code values signify what kind of operation is to be
3575** authorized.  The 3rd and 4th parameters to the authorization
3576** callback function will be parameters or NULL depending on which of these
3577** codes is used as the second parameter.  ^(The 5th parameter to the
3578** authorizer callback is the name of the database ("main", "temp",
3579** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
3580** is the name of the inner-most trigger or view that is responsible for
3581** the access attempt or NULL if this access attempt is directly from
3582** top-level SQL code.
3583*/
3584/******************************************* 3rd ************ 4th ***********/
3585#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
3586#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
3587#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
3588#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
3589#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
3590#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
3591#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
3592#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
3593#define SQLITE_DELETE                9   /* Table Name      NULL            */
3594#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
3595#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
3596#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
3597#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
3598#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
3599#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
3600#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
3601#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
3602#define SQLITE_INSERT               18   /* Table Name      NULL            */
3603#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
3604#define SQLITE_READ                 20   /* Table Name      Column Name     */
3605#define SQLITE_SELECT               21   /* NULL            NULL            */
3606#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
3607#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
3608#define SQLITE_ATTACH               24   /* Filename        NULL            */
3609#define SQLITE_DETACH               25   /* Database Name   NULL            */
3610#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
3611#define SQLITE_REINDEX              27   /* Index Name      NULL            */
3612#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
3613#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
3614#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
3615#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
3616#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
3617#define SQLITE_COPY                  0   /* No longer used */
3618#define SQLITE_RECURSIVE            33   /* NULL            NULL            */
3619
3620/*
3621** CAPI3REF: Deprecated Tracing And Profiling Functions
3622** DEPRECATED
3623**
3624** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
3625** instead of the routines described here.
3626**
3627** These routines register callback functions that can be used for
3628** tracing and profiling the execution of SQL statements.
3629**
3630** ^The callback function registered by sqlite3_trace() is invoked at
3631** various times when an SQL statement is being run by [sqlite3_step()].
3632** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3633** SQL statement text as the statement first begins executing.
3634** ^(Additional sqlite3_trace() callbacks might occur
3635** as each triggered subprogram is entered.  The callbacks for triggers
3636** contain a UTF-8 SQL comment that identifies the trigger.)^
3637**
3638** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3639** the length of [bound parameter] expansion in the output of sqlite3_trace().
3640**
3641** ^The callback function registered by sqlite3_profile() is invoked
3642** as each SQL statement finishes.  ^The profile callback contains
3643** the original statement text and an estimate of wall-clock time
3644** of how long that statement took to run.  ^The profile callback
3645** time is in units of nanoseconds, however the current implementation
3646** is only capable of millisecond resolution so the six least significant
3647** digits in the time are meaningless.  Future versions of SQLite
3648** might provide greater resolution on the profiler callback.  Invoking
3649** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the
3650** profile callback.
3651*/
3652SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
3653   void(*xTrace)(void*,const char*), void*);
3654SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
3655   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3656
3657/*
3658** CAPI3REF: SQL Trace Event Codes
3659** KEYWORDS: SQLITE_TRACE
3660**
3661** These constants identify classes of events that can be monitored
3662** using the [sqlite3_trace_v2()] tracing logic.  The M argument
3663** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
3664** the following constants.  ^The first argument to the trace callback
3665** is one of the following constants.
3666**
3667** New tracing constants may be added in future releases.
3668**
3669** ^A trace callback has four arguments: xCallback(T,C,P,X).
3670** ^The T argument is one of the integer type codes above.
3671** ^The C argument is a copy of the context pointer passed in as the
3672** fourth argument to [sqlite3_trace_v2()].
3673** The P and X arguments are pointers whose meanings depend on T.
3674**
3675** <dl>
3676** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
3677** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
3678** first begins running and possibly at other times during the
3679** execution of the prepared statement, such as at the start of each
3680** trigger subprogram. ^The P argument is a pointer to the
3681** [prepared statement]. ^The X argument is a pointer to a string which
3682** is the unexpanded SQL text of the prepared statement or an SQL comment
3683** that indicates the invocation of a trigger.  ^The callback can compute
3684** the same text that would have been returned by the legacy [sqlite3_trace()]
3685** interface by using the X argument when X begins with "--" and invoking
3686** [sqlite3_expanded_sql(P)] otherwise.
3687**
3688** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
3689** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
3690** information as is provided by the [sqlite3_profile()] callback.
3691** ^The P argument is a pointer to the [prepared statement] and the
3692** X argument points to a 64-bit integer which is approximately
3693** the number of nanoseconds that the prepared statement took to run.
3694** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
3695**
3696** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
3697** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
3698** statement generates a single row of result.
3699** ^The P argument is a pointer to the [prepared statement] and the
3700** X argument is unused.
3701**
3702** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
3703** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
3704** connection closes.
3705** ^The P argument is a pointer to the [database connection] object
3706** and the X argument is unused.
3707** </dl>
3708*/
3709#define SQLITE_TRACE_STMT       0x01
3710#define SQLITE_TRACE_PROFILE    0x02
3711#define SQLITE_TRACE_ROW        0x04
3712#define SQLITE_TRACE_CLOSE      0x08
3713
3714/*
3715** CAPI3REF: SQL Trace Hook
3716** METHOD: sqlite3
3717**
3718** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
3719** function X against [database connection] D, using property mask M
3720** and context pointer P.  ^If the X callback is
3721** NULL or if the M mask is zero, then tracing is disabled.  The
3722** M argument should be the bitwise OR-ed combination of
3723** zero or more [SQLITE_TRACE] constants.
3724**
3725** ^Each call to either sqlite3_trace(D,X,P) or sqlite3_trace_v2(D,M,X,P)
3726** overrides (cancels) all prior calls to sqlite3_trace(D,X,P) or
3727** sqlite3_trace_v2(D,M,X,P) for the [database connection] D.  Each
3728** database connection may have at most one trace callback.
3729**
3730** ^The X callback is invoked whenever any of the events identified by
3731** mask M occur.  ^The integer return value from the callback is currently
3732** ignored, though this may change in future releases.  Callback
3733** implementations should return zero to ensure future compatibility.
3734**
3735** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
3736** ^The T argument is one of the [SQLITE_TRACE]
3737** constants to indicate why the callback was invoked.
3738** ^The C argument is a copy of the context pointer.
3739** The P and X arguments are pointers whose meanings depend on T.
3740**
3741** The sqlite3_trace_v2() interface is intended to replace the legacy
3742** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
3743** are deprecated.
3744*/
3745SQLITE_API int sqlite3_trace_v2(
3746  sqlite3*,
3747  unsigned uMask,
3748  int(*xCallback)(unsigned,void*,void*,void*),
3749  void *pCtx
3750);
3751
3752/*
3753** CAPI3REF: Query Progress Callbacks
3754** METHOD: sqlite3
3755**
3756** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3757** function X to be invoked periodically during long running calls to
3758** [sqlite3_step()] and [sqlite3_prepare()] and similar for
3759** database connection D.  An example use for this
3760** interface is to keep a GUI updated during a large query.
3761**
3762** ^The parameter P is passed through as the only parameter to the
3763** callback function X.  ^The parameter N is the approximate number of
3764** [virtual machine instructions] that are evaluated between successive
3765** invocations of the callback X.  ^If N is less than one then the progress
3766** handler is disabled.
3767**
3768** ^Only a single progress handler may be defined at one time per
3769** [database connection]; setting a new progress handler cancels the
3770** old one.  ^Setting parameter X to NULL disables the progress handler.
3771** ^The progress handler is also disabled by setting N to a value less
3772** than 1.
3773**
3774** ^If the progress callback returns non-zero, the operation is
3775** interrupted.  This feature can be used to implement a
3776** "Cancel" button on a GUI progress dialog box.
3777**
3778** The progress handler callback must not do anything that will modify
3779** the database connection that invoked the progress handler.
3780** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3781** database connections for the meaning of "modify" in this paragraph.
3782**
3783** The progress handler callback would originally only be invoked from the
3784** bytecode engine.  It still might be invoked during [sqlite3_prepare()]
3785** and similar because those routines might force a reparse of the schema
3786** which involves running the bytecode engine.  However, beginning with
3787** SQLite version 3.41.0, the progress handler callback might also be
3788** invoked directly from [sqlite3_prepare()] while analyzing and generating
3789** code for complex queries.
3790*/
3791SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3792
3793/*
3794** CAPI3REF: Opening A New Database Connection
3795** CONSTRUCTOR: sqlite3
3796**
3797** ^These routines open an SQLite database file as specified by the
3798** filename argument. ^The filename argument is interpreted as UTF-8 for
3799** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3800** order for sqlite3_open16(). ^(A [database connection] handle is usually
3801** returned in *ppDb, even if an error occurs.  The only exception is that
3802** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3803** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3804** object.)^ ^(If the database is opened (and/or created) successfully, then
3805** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
3806** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3807** an English language description of the error following a failure of any
3808** of the sqlite3_open() routines.
3809**
3810** ^The default encoding will be UTF-8 for databases created using
3811** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases
3812** created using sqlite3_open16() will be UTF-16 in the native byte order.
3813**
3814** Whether or not an error occurs when it is opened, resources
3815** associated with the [database connection] handle should be released by
3816** passing it to [sqlite3_close()] when it is no longer required.
3817**
3818** The sqlite3_open_v2() interface works like sqlite3_open()
3819** except that it accepts two additional parameters for additional control
3820** over the new database connection.  ^(The flags parameter to
3821** sqlite3_open_v2() must include, at a minimum, one of the following
3822** three flag combinations:)^
3823**
3824** <dl>
3825** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3826** <dd>The database is opened in read-only mode.  If the database does
3827** not already exist, an error is returned.</dd>)^
3828**
3829** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3830** <dd>The database is opened for reading and writing if possible, or
3831** reading only if the file is write protected by the operating
3832** system.  In either case the database must already exist, otherwise
3833** an error is returned.  For historical reasons, if opening in
3834** read-write mode fails due to OS-level permissions, an attempt is
3835** made to open it in read-only mode. [sqlite3_db_readonly()] can be
3836** used to determine whether the database is actually
3837** read-write.</dd>)^
3838**
3839** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3840** <dd>The database is opened for reading and writing, and is created if
3841** it does not already exist. This is the behavior that is always used for
3842** sqlite3_open() and sqlite3_open16().</dd>)^
3843** </dl>
3844**
3845** In addition to the required flags, the following optional flags are
3846** also supported:
3847**
3848** <dl>
3849** ^(<dt>[SQLITE_OPEN_URI]</dt>
3850** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^
3851**
3852** ^(<dt>[SQLITE_OPEN_MEMORY]</dt>
3853** <dd>The database will be opened as an in-memory database.  The database
3854** is named by the "filename" argument for the purposes of cache-sharing,
3855** if shared cache mode is enabled, but the "filename" is otherwise ignored.
3856** </dd>)^
3857**
3858** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt>
3859** <dd>The new database connection will use the "multi-thread"
3860** [threading mode].)^  This means that separate threads are allowed
3861** to use SQLite at the same time, as long as each thread is using
3862** a different [database connection].
3863**
3864** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt>
3865** <dd>The new database connection will use the "serialized"
3866** [threading mode].)^  This means the multiple threads can safely
3867** attempt to use the same database connection at the same time.
3868** (Mutexes will block any actual concurrency, but in this mode
3869** there is no harm in trying.)
3870**
3871** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt>
3872** <dd>The database is opened [shared cache] enabled, overriding
3873** the default shared cache setting provided by
3874** [sqlite3_enable_shared_cache()].)^
3875** The [use of shared cache mode is discouraged] and hence shared cache
3876** capabilities may be omitted from many builds of SQLite.  In such cases,
3877** this option is a no-op.
3878**
3879** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>
3880** <dd>The database is opened [shared cache] disabled, overriding
3881** the default shared cache setting provided by
3882** [sqlite3_enable_shared_cache()].)^
3883**
3884** [[OPEN_EXRESCODE]] ^(<dt>[SQLITE_OPEN_EXRESCODE]</dt>
3885** <dd>The database connection comes up in "extended result code mode".
3886** In other words, the database behaves has if
3887** [sqlite3_extended_result_codes(db,1)] where called on the database
3888** connection as soon as the connection is created. In addition to setting
3889** the extended result code mode, this flag also causes [sqlite3_open_v2()]
3890** to return an extended result code.</dd>
3891**
3892** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
3893** <dd>The database filename is not allowed to contain a symbolic link</dd>
3894** </dl>)^
3895**
3896** If the 3rd parameter to sqlite3_open_v2() is not one of the
3897** required combinations shown above optionally combined with other
3898** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3899** then the behavior is undefined.  Historic versions of SQLite
3900** have silently ignored surplus bits in the flags parameter to
3901** sqlite3_open_v2(), however that behavior might not be carried through
3902** into future versions of SQLite and so applications should not rely
3903** upon it.  Note in particular that the SQLITE_OPEN_EXCLUSIVE flag is a no-op
3904** for sqlite3_open_v2().  The SQLITE_OPEN_EXCLUSIVE does *not* cause
3905** the open to fail if the database already exists.  The SQLITE_OPEN_EXCLUSIVE
3906** flag is intended for use by the [sqlite3_vfs|VFS interface] only, and not
3907** by sqlite3_open_v2().
3908**
3909** ^The fourth parameter to sqlite3_open_v2() is the name of the
3910** [sqlite3_vfs] object that defines the operating system interface that
3911** the new database connection should use.  ^If the fourth parameter is
3912** a NULL pointer then the default [sqlite3_vfs] object is used.
3913**
3914** ^If the filename is ":memory:", then a private, temporary in-memory database
3915** is created for the connection.  ^This in-memory database will vanish when
3916** the database connection is closed.  Future versions of SQLite might
3917** make use of additional special filenames that begin with the ":" character.
3918** It is recommended that when a database filename actually does begin with
3919** a ":" character you should prefix the filename with a pathname such as
3920** "./" to avoid ambiguity.
3921**
3922** ^If the filename is an empty string, then a private, temporary
3923** on-disk database will be created.  ^This private database will be
3924** automatically deleted as soon as the database connection is closed.
3925**
3926** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3927**
3928** ^If [URI filename] interpretation is enabled, and the filename argument
3929** begins with "file:", then the filename is interpreted as a URI. ^URI
3930** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3931** set in the third argument to sqlite3_open_v2(), or if it has
3932** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3933** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3934** URI filename interpretation is turned off
3935** by default, but future releases of SQLite might enable URI filename
3936** interpretation by default.  See "[URI filenames]" for additional
3937** information.
3938**
3939** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3940** authority, then it must be either an empty string or the string
3941** "localhost". ^If the authority is not an empty string or "localhost", an
3942** error is returned to the caller. ^The fragment component of a URI, if
3943** present, is ignored.
3944**
3945** ^SQLite uses the path component of the URI as the name of the disk file
3946** which contains the database. ^If the path begins with a '/' character,
3947** then it is interpreted as an absolute path. ^If the path does not begin
3948** with a '/' (meaning that the authority section is omitted from the URI)
3949** then the path is interpreted as a relative path.
3950** ^(On windows, the first component of an absolute path
3951** is a drive specification (e.g. "C:").)^
3952**
3953** [[core URI query parameters]]
3954** The query component of a URI may contain parameters that are interpreted
3955** either by SQLite itself, or by a [VFS | custom VFS implementation].
3956** SQLite and its built-in [VFSes] interpret the
3957** following query parameters:
3958**
3959** <ul>
3960**   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3961**     a VFS object that provides the operating system interface that should
3962**     be used to access the database file on disk. ^If this option is set to
3963**     an empty string the default VFS object is used. ^Specifying an unknown
3964**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3965**     present, then the VFS specified by the option takes precedence over
3966**     the value passed as the fourth parameter to sqlite3_open_v2().
3967**
3968**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3969**     "rwc", or "memory". Attempting to set it to any other value is
3970**     an error)^.
3971**     ^If "ro" is specified, then the database is opened for read-only
3972**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3973**     third argument to sqlite3_open_v2(). ^If the mode option is set to
3974**     "rw", then the database is opened for read-write (but not create)
3975**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3976**     been set. ^Value "rwc" is equivalent to setting both
3977**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
3978**     set to "memory" then a pure [in-memory database] that never reads
3979**     or writes from disk is used. ^It is an error to specify a value for
3980**     the mode parameter that is less restrictive than that specified by
3981**     the flags passed in the third parameter to sqlite3_open_v2().
3982**
3983**   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3984**     "private". ^Setting it to "shared" is equivalent to setting the
3985**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3986**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3987**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3988**     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3989**     a URI filename, its value overrides any behavior requested by setting
3990**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3991**
3992**  <li> <b>psow</b>: ^The psow parameter indicates whether or not the
3993**     [powersafe overwrite] property does or does not apply to the
3994**     storage media on which the database file resides.
3995**
3996**  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
3997**     which if set disables file locking in rollback journal modes.  This
3998**     is useful for accessing a database on a filesystem that does not
3999**     support locking.  Caution:  Database corruption might result if two
4000**     or more processes write to the same database and any one of those
4001**     processes uses nolock=1.
4002**
4003**  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
4004**     parameter that indicates that the database file is stored on
4005**     read-only media.  ^When immutable is set, SQLite assumes that the
4006**     database file cannot be changed, even by a process with higher
4007**     privilege, and so the database is opened read-only and all locking
4008**     and change detection is disabled.  Caution: Setting the immutable
4009**     property on a database file that does in fact change can result
4010**     in incorrect query results and/or [SQLITE_CORRUPT] errors.
4011**     See also: [SQLITE_IOCAP_IMMUTABLE].
4012**
4013** </ul>
4014**
4015** ^Specifying an unknown parameter in the query component of a URI is not an
4016** error.  Future versions of SQLite might understand additional query
4017** parameters.  See "[query parameters with special meaning to SQLite]" for
4018** additional information.
4019**
4020** [[URI filename examples]] <h3>URI filename examples</h3>
4021**
4022** <table border="1" align=center cellpadding=5>
4023** <tr><th> URI filenames <th> Results
4024** <tr><td> file:data.db <td>
4025**          Open the file "data.db" in the current directory.
4026** <tr><td> file:/home/fred/data.db<br>
4027**          file:///home/fred/data.db <br>
4028**          file://localhost/home/fred/data.db <br> <td>
4029**          Open the database file "/home/fred/data.db".
4030** <tr><td> file://darkstar/home/fred/data.db <td>
4031**          An error. "darkstar" is not a recognized authority.
4032** <tr><td style="white-space:nowrap">
4033**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
4034**     <td> Windows only: Open the file "data.db" on fred's desktop on drive
4035**          C:. Note that the %20 escaping in this example is not strictly
4036**          necessary - space characters can be used literally
4037**          in URI filenames.
4038** <tr><td> file:data.db?mode=ro&cache=private <td>
4039**          Open file "data.db" in the current directory for read-only access.
4040**          Regardless of whether or not shared-cache mode is enabled by
4041**          default, use a private cache.
4042** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
4043**          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
4044**          that uses dot-files in place of posix advisory locking.
4045** <tr><td> file:data.db?mode=readonly <td>
4046**          An error. "readonly" is not a valid option for the "mode" parameter.
4047**          Use "ro" instead:  "file:data.db?mode=ro".
4048** </table>
4049**
4050** ^URI hexadecimal escape sequences (%HH) are supported within the path and
4051** query components of a URI. A hexadecimal escape sequence consists of a
4052** percent sign - "%" - followed by exactly two hexadecimal digits
4053** specifying an octet value. ^Before the path or query components of a
4054** URI filename are interpreted, they are encoded using UTF-8 and all
4055** hexadecimal escape sequences replaced by a single byte containing the
4056** corresponding octet. If this process generates an invalid UTF-8 encoding,
4057** the results are undefined.
4058**
4059** <b>Note to Windows users:</b>  The encoding used for the filename argument
4060** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
4061** codepage is currently defined.  Filenames containing international
4062** characters must be converted to UTF-8 prior to passing them into
4063** sqlite3_open() or sqlite3_open_v2().
4064**
4065** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
4066** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
4067** features that require the use of temporary files may fail.
4068**
4069** See also: [sqlite3_temp_directory]
4070*/
4071SQLITE_API int sqlite3_open(
4072  const char *filename,   /* Database filename (UTF-8) */
4073  sqlite3 **ppDb          /* OUT: SQLite db handle */
4074);
4075SQLITE_API int sqlite3_open16(
4076  const void *filename,   /* Database filename (UTF-16) */
4077  sqlite3 **ppDb          /* OUT: SQLite db handle */
4078);
4079SQLITE_API int sqlite3_open_v2(
4080  const char *filename,   /* Database filename (UTF-8) */
4081  sqlite3 **ppDb,         /* OUT: SQLite db handle */
4082  int flags,              /* Flags */
4083  const char *zVfs        /* Name of VFS module to use */
4084);
4085
4086/*
4087** CAPI3REF: Obtain Values For URI Parameters
4088**
4089** These are utility routines, useful to [VFS|custom VFS implementations],
4090** that check if a database file was a URI that contained a specific query
4091** parameter, and if so obtains the value of that query parameter.
4092**
4093** The first parameter to these interfaces (hereafter referred to
4094** as F) must be one of:
4095** <ul>
4096** <li> A database filename pointer created by the SQLite core and
4097** passed into the xOpen() method of a VFS implementation, or
4098** <li> A filename obtained from [sqlite3_db_filename()], or
4099** <li> A new filename constructed using [sqlite3_create_filename()].
4100** </ul>
4101** If the F parameter is not one of the above, then the behavior is
4102** undefined and probably undesirable.  Older versions of SQLite were
4103** more tolerant of invalid F parameters than newer versions.
4104**
4105** If F is a suitable filename (as described in the previous paragraph)
4106** and if P is the name of the query parameter, then
4107** sqlite3_uri_parameter(F,P) returns the value of the P
4108** parameter if it exists or a NULL pointer if P does not appear as a
4109** query parameter on F.  If P is a query parameter of F and it
4110** has no explicit value, then sqlite3_uri_parameter(F,P) returns
4111** a pointer to an empty string.
4112**
4113** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
4114** parameter and returns true (1) or false (0) according to the value
4115** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
4116** value of query parameter P is one of "yes", "true", or "on" in any
4117** case or if the value begins with a non-zero number.  The
4118** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
4119** query parameter P is one of "no", "false", or "off" in any case or
4120** if the value begins with a numeric zero.  If P is not a query
4121** parameter on F or if the value of P does not match any of the
4122** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
4123**
4124** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
4125** 64-bit signed integer and returns that integer, or D if P does not
4126** exist.  If the value of P is something other than an integer, then
4127** zero is returned.
4128**
4129** The sqlite3_uri_key(F,N) returns a pointer to the name (not
4130** the value) of the N-th query parameter for filename F, or a NULL
4131** pointer if N is less than zero or greater than the number of query
4132** parameters minus 1.  The N value is zero-based so N should be 0 to obtain
4133** the name of the first query parameter, 1 for the second parameter, and
4134** so forth.
4135**
4136** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
4137** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
4138** is not a database file pathname pointer that the SQLite core passed
4139** into the xOpen VFS method, then the behavior of this routine is undefined
4140** and probably undesirable.
4141**
4142** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F
4143** parameter can also be the name of a rollback journal file or WAL file
4144** in addition to the main database file.  Prior to version 3.31.0, these
4145** routines would only work if F was the name of the main database file.
4146** When the F parameter is the name of the rollback journal or WAL file,
4147** it has access to all the same query parameters as were found on the
4148** main database file.
4149**
4150** See the [URI filename] documentation for additional information.
4151*/
4152SQLITE_API const char *sqlite3_uri_parameter(sqlite3_filename z, const char *zParam);
4153SQLITE_API int sqlite3_uri_boolean(sqlite3_filename z, const char *zParam, int bDefault);
4154SQLITE_API sqlite3_int64 sqlite3_uri_int64(sqlite3_filename, const char*, sqlite3_int64);
4155SQLITE_API const char *sqlite3_uri_key(sqlite3_filename z, int N);
4156
4157/*
4158** CAPI3REF:  Translate filenames
4159**
4160** These routines are available to [VFS|custom VFS implementations] for
4161** translating filenames between the main database file, the journal file,
4162** and the WAL file.
4163**
4164** If F is the name of an sqlite database file, journal file, or WAL file
4165** passed by the SQLite core into the VFS, then sqlite3_filename_database(F)
4166** returns the name of the corresponding database file.
4167**
4168** If F is the name of an sqlite database file, journal file, or WAL file
4169** passed by the SQLite core into the VFS, or if F is a database filename
4170** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F)
4171** returns the name of the corresponding rollback journal file.
4172**
4173** If F is the name of an sqlite database file, journal file, or WAL file
4174** that was passed by the SQLite core into the VFS, or if F is a database
4175** filename obtained from [sqlite3_db_filename()], then
4176** sqlite3_filename_wal(F) returns the name of the corresponding
4177** WAL file.
4178**
4179** In all of the above, if F is not the name of a database, journal or WAL
4180** filename passed into the VFS from the SQLite core and F is not the
4181** return value from [sqlite3_db_filename()], then the result is
4182** undefined and is likely a memory access violation.
4183*/
4184SQLITE_API const char *sqlite3_filename_database(sqlite3_filename);
4185SQLITE_API const char *sqlite3_filename_journal(sqlite3_filename);
4186SQLITE_API const char *sqlite3_filename_wal(sqlite3_filename);
4187
4188/*
4189** CAPI3REF:  Database File Corresponding To A Journal
4190**
4191** ^If X is the name of a rollback or WAL-mode journal file that is
4192** passed into the xOpen method of [sqlite3_vfs], then
4193** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file]
4194** object that represents the main database file.
4195**
4196** This routine is intended for use in custom [VFS] implementations
4197** only.  It is not a general-purpose interface.
4198** The argument sqlite3_file_object(X) must be a filename pointer that
4199** has been passed into [sqlite3_vfs].xOpen method where the
4200** flags parameter to xOpen contains one of the bits
4201** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL].  Any other use
4202** of this routine results in undefined and probably undesirable
4203** behavior.
4204*/
4205SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*);
4206
4207/*
4208** CAPI3REF: Create and Destroy VFS Filenames
4209**
4210** These interfaces are provided for use by [VFS shim] implementations and
4211** are not useful outside of that context.
4212**
4213** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of
4214** database filename D with corresponding journal file J and WAL file W and
4215** with N URI parameters key/values pairs in the array P.  The result from
4216** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that
4217** is safe to pass to routines like:
4218** <ul>
4219** <li> [sqlite3_uri_parameter()],
4220** <li> [sqlite3_uri_boolean()],
4221** <li> [sqlite3_uri_int64()],
4222** <li> [sqlite3_uri_key()],
4223** <li> [sqlite3_filename_database()],
4224** <li> [sqlite3_filename_journal()], or
4225** <li> [sqlite3_filename_wal()].
4226** </ul>
4227** If a memory allocation error occurs, sqlite3_create_filename() might
4228** return a NULL pointer.  The memory obtained from sqlite3_create_filename(X)
4229** must be released by a corresponding call to sqlite3_free_filename(Y).
4230**
4231** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array
4232** of 2*N pointers to strings.  Each pair of pointers in this array corresponds
4233** to a key and value for a query parameter.  The P parameter may be a NULL
4234** pointer if N is zero.  None of the 2*N pointers in the P array may be
4235** NULL pointers and key pointers should not be empty strings.
4236** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may
4237** be NULL pointers, though they can be empty strings.
4238**
4239** The sqlite3_free_filename(Y) routine releases a memory allocation
4240** previously obtained from sqlite3_create_filename().  Invoking
4241** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.
4242**
4243** If the Y parameter to sqlite3_free_filename(Y) is anything other
4244** than a NULL pointer or a pointer previously acquired from
4245** sqlite3_create_filename(), then bad things such as heap
4246** corruption or segfaults may occur. The value Y should not be
4247** used again after sqlite3_free_filename(Y) has been called.  This means
4248** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y,
4249** then the corresponding [sqlite3_module.xClose() method should also be
4250** invoked prior to calling sqlite3_free_filename(Y).
4251*/
4252SQLITE_API sqlite3_filename sqlite3_create_filename(
4253  const char *zDatabase,
4254  const char *zJournal,
4255  const char *zWal,
4256  int nParam,
4257  const char **azParam
4258);
4259SQLITE_API void sqlite3_free_filename(sqlite3_filename);
4260
4261/*
4262** CAPI3REF: Error Codes And Messages
4263** METHOD: sqlite3
4264**
4265** ^If the most recent sqlite3_* API call associated with
4266** [database connection] D failed, then the sqlite3_errcode(D) interface
4267** returns the numeric [result code] or [extended result code] for that
4268** API call.
4269** ^The sqlite3_extended_errcode()
4270** interface is the same except that it always returns the
4271** [extended result code] even when extended result codes are
4272** disabled.
4273**
4274** The values returned by sqlite3_errcode() and/or
4275** sqlite3_extended_errcode() might change with each API call.
4276** Except, there are some interfaces that are guaranteed to never
4277** change the value of the error code.  The error-code preserving
4278** interfaces include the following:
4279**
4280** <ul>
4281** <li> sqlite3_errcode()
4282** <li> sqlite3_extended_errcode()
4283** <li> sqlite3_errmsg()
4284** <li> sqlite3_errmsg16()
4285** <li> sqlite3_error_offset()
4286** </ul>
4287**
4288** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
4289** text that describes the error, as either UTF-8 or UTF-16 respectively,
4290** or NULL if no error message is available.
4291** (See how SQLite handles [invalid UTF] for exceptions to this rule.)
4292** ^(Memory to hold the error message string is managed internally.
4293** The application does not need to worry about freeing the result.
4294** However, the error string might be overwritten or deallocated by
4295** subsequent calls to other SQLite interface functions.)^
4296**
4297** ^The sqlite3_errstr(E) interface returns the English-language text
4298** that describes the [result code] E, as UTF-8, or NULL if E is not an
4299** result code for which a text error message is available.
4300** ^(Memory to hold the error message string is managed internally
4301** and must not be freed by the application)^.
4302**
4303** ^If the most recent error references a specific token in the input
4304** SQL, the sqlite3_error_offset() interface returns the byte offset
4305** of the start of that token.  ^The byte offset returned by
4306** sqlite3_error_offset() assumes that the input SQL is UTF8.
4307** ^If the most recent error does not reference a specific token in the input
4308** SQL, then the sqlite3_error_offset() function returns -1.
4309**
4310** When the serialized [threading mode] is in use, it might be the
4311** case that a second error occurs on a separate thread in between
4312** the time of the first error and the call to these interfaces.
4313** When that happens, the second error will be reported since these
4314** interfaces always report the most recent result.  To avoid
4315** this, each thread can obtain exclusive use of the [database connection] D
4316** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
4317** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
4318** all calls to the interfaces listed here are completed.
4319**
4320** If an interface fails with SQLITE_MISUSE, that means the interface
4321** was invoked incorrectly by the application.  In that case, the
4322** error code and message may or may not be set.
4323*/
4324SQLITE_API int sqlite3_errcode(sqlite3 *db);
4325SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
4326SQLITE_API const char *sqlite3_errmsg(sqlite3*);
4327SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
4328SQLITE_API const char *sqlite3_errstr(int);
4329SQLITE_API int sqlite3_error_offset(sqlite3 *db);
4330
4331/*
4332** CAPI3REF: Prepared Statement Object
4333** KEYWORDS: {prepared statement} {prepared statements}
4334**
4335** An instance of this object represents a single SQL statement that
4336** has been compiled into binary form and is ready to be evaluated.
4337**
4338** Think of each SQL statement as a separate computer program.  The
4339** original SQL text is source code.  A prepared statement object
4340** is the compiled object code.  All SQL must be converted into a
4341** prepared statement before it can be run.
4342**
4343** The life-cycle of a prepared statement object usually goes like this:
4344**
4345** <ol>
4346** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
4347** <li> Bind values to [parameters] using the sqlite3_bind_*()
4348**      interfaces.
4349** <li> Run the SQL by calling [sqlite3_step()] one or more times.
4350** <li> Reset the prepared statement using [sqlite3_reset()] then go back
4351**      to step 2.  Do this zero or more times.
4352** <li> Destroy the object using [sqlite3_finalize()].
4353** </ol>
4354*/
4355typedef struct sqlite3_stmt sqlite3_stmt;
4356
4357/*
4358** CAPI3REF: Run-time Limits
4359** METHOD: sqlite3
4360**
4361** ^(This interface allows the size of various constructs to be limited
4362** on a connection by connection basis.  The first parameter is the
4363** [database connection] whose limit is to be set or queried.  The
4364** second parameter is one of the [limit categories] that define a
4365** class of constructs to be size limited.  The third parameter is the
4366** new limit for that construct.)^
4367**
4368** ^If the new limit is a negative number, the limit is unchanged.
4369** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
4370** [limits | hard upper bound]
4371** set at compile-time by a C preprocessor macro called
4372** [limits | SQLITE_MAX_<i>NAME</i>].
4373** (The "_LIMIT_" in the name is changed to "_MAX_".))^
4374** ^Attempts to increase a limit above its hard upper bound are
4375** silently truncated to the hard upper bound.
4376**
4377** ^Regardless of whether or not the limit was changed, the
4378** [sqlite3_limit()] interface returns the prior value of the limit.
4379** ^Hence, to find the current value of a limit without changing it,
4380** simply invoke this interface with the third parameter set to -1.
4381**
4382** Run-time limits are intended for use in applications that manage
4383** both their own internal database and also databases that are controlled
4384** by untrusted external sources.  An example application might be a
4385** web browser that has its own databases for storing history and
4386** separate databases controlled by JavaScript applications downloaded
4387** off the Internet.  The internal databases can be given the
4388** large, default limits.  Databases managed by external sources can
4389** be given much smaller limits designed to prevent a denial of service
4390** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
4391** interface to further control untrusted SQL.  The size of the database
4392** created by an untrusted script can be contained using the
4393** [max_page_count] [PRAGMA].
4394**
4395** New run-time limit categories may be added in future releases.
4396*/
4397SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
4398
4399/*
4400** CAPI3REF: Run-Time Limit Categories
4401** KEYWORDS: {limit category} {*limit categories}
4402**
4403** These constants define various performance limits
4404** that can be lowered at run-time using [sqlite3_limit()].
4405** The synopsis of the meanings of the various limits is shown below.
4406** Additional information is available at [limits | Limits in SQLite].
4407**
4408** <dl>
4409** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
4410** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
4411**
4412** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
4413** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
4414**
4415** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
4416** <dd>The maximum number of columns in a table definition or in the
4417** result set of a [SELECT] or the maximum number of columns in an index
4418** or in an ORDER BY or GROUP BY clause.</dd>)^
4419**
4420** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
4421** <dd>The maximum depth of the parse tree on any expression.</dd>)^
4422**
4423** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
4424** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
4425**
4426** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
4427** <dd>The maximum number of instructions in a virtual machine program
4428** used to implement an SQL statement.  If [sqlite3_prepare_v2()] or
4429** the equivalent tries to allocate space for more than this many opcodes
4430** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
4431**
4432** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
4433** <dd>The maximum number of arguments on a function.</dd>)^
4434**
4435** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
4436** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
4437**
4438** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
4439** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
4440** <dd>The maximum length of the pattern argument to the [LIKE] or
4441** [GLOB] operators.</dd>)^
4442**
4443** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
4444** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
4445** <dd>The maximum index number of any [parameter] in an SQL statement.)^
4446**
4447** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
4448** <dd>The maximum depth of recursion for triggers.</dd>)^
4449**
4450** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
4451** <dd>The maximum number of auxiliary worker threads that a single
4452** [prepared statement] may start.</dd>)^
4453** </dl>
4454*/
4455#define SQLITE_LIMIT_LENGTH                    0
4456#define SQLITE_LIMIT_SQL_LENGTH                1
4457#define SQLITE_LIMIT_COLUMN                    2
4458#define SQLITE_LIMIT_EXPR_DEPTH                3
4459#define SQLITE_LIMIT_COMPOUND_SELECT           4
4460#define SQLITE_LIMIT_VDBE_OP                   5
4461#define SQLITE_LIMIT_FUNCTION_ARG              6
4462#define SQLITE_LIMIT_ATTACHED                  7
4463#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
4464#define SQLITE_LIMIT_VARIABLE_NUMBER           9
4465#define SQLITE_LIMIT_TRIGGER_DEPTH            10
4466#define SQLITE_LIMIT_WORKER_THREADS           11
4467
4468/*
4469** CAPI3REF: Prepare Flags
4470**
4471** These constants define various flags that can be passed into
4472** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
4473** [sqlite3_prepare16_v3()] interfaces.
4474**
4475** New flags may be added in future releases of SQLite.
4476**
4477** <dl>
4478** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
4479** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
4480** that the prepared statement will be retained for a long time and
4481** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
4482** and [sqlite3_prepare16_v3()] assume that the prepared statement will
4483** be used just once or at most a few times and then destroyed using
4484** [sqlite3_finalize()] relatively soon. The current implementation acts
4485** on this hint by avoiding the use of [lookaside memory] so as not to
4486** deplete the limited store of lookaside memory. Future versions of
4487** SQLite may act on this hint differently.
4488**
4489** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt>
4490** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used
4491** to be required for any prepared statement that wanted to use the
4492** [sqlite3_normalized_sql()] interface.  However, the
4493** [sqlite3_normalized_sql()] interface is now available to all
4494** prepared statements, regardless of whether or not they use this
4495** flag.
4496**
4497** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt>
4498** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler
4499** to return an error (error code SQLITE_ERROR) if the statement uses
4500** any virtual tables.
4501** </dl>
4502*/
4503#define SQLITE_PREPARE_PERSISTENT              0x01
4504#define SQLITE_PREPARE_NORMALIZE               0x02
4505#define SQLITE_PREPARE_NO_VTAB                 0x04
4506
4507/*
4508** CAPI3REF: Compiling An SQL Statement
4509** KEYWORDS: {SQL statement compiler}
4510** METHOD: sqlite3
4511** CONSTRUCTOR: sqlite3_stmt
4512**
4513** To execute an SQL statement, it must first be compiled into a byte-code
4514** program using one of these routines.  Or, in other words, these routines
4515** are constructors for the [prepared statement] object.
4516**
4517** The preferred routine to use is [sqlite3_prepare_v2()].  The
4518** [sqlite3_prepare()] interface is legacy and should be avoided.
4519** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
4520** for special purposes.
4521**
4522** The use of the UTF-8 interfaces is preferred, as SQLite currently
4523** does all parsing using UTF-8.  The UTF-16 interfaces are provided
4524** as a convenience.  The UTF-16 interfaces work by converting the
4525** input text into UTF-8, then invoking the corresponding UTF-8 interface.
4526**
4527** The first argument, "db", is a [database connection] obtained from a
4528** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
4529** [sqlite3_open16()].  The database connection must not have been closed.
4530**
4531** The second argument, "zSql", is the statement to be compiled, encoded
4532** as either UTF-8 or UTF-16.  The sqlite3_prepare(), sqlite3_prepare_v2(),
4533** and sqlite3_prepare_v3()
4534** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
4535** and sqlite3_prepare16_v3() use UTF-16.
4536**
4537** ^If the nByte argument is negative, then zSql is read up to the
4538** first zero terminator. ^If nByte is positive, then it is the
4539** number of bytes read from zSql.  ^If nByte is zero, then no prepared
4540** statement is generated.
4541** If the caller knows that the supplied string is nul-terminated, then
4542** there is a small performance advantage to passing an nByte parameter that
4543** is the number of bytes in the input string <i>including</i>
4544** the nul-terminator.
4545**
4546** ^If pzTail is not NULL then *pzTail is made to point to the first byte
4547** past the end of the first SQL statement in zSql.  These routines only
4548** compile the first statement in zSql, so *pzTail is left pointing to
4549** what remains uncompiled.
4550**
4551** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
4552** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
4553** to NULL.  ^If the input text contains no SQL (if the input is an empty
4554** string or a comment) then *ppStmt is set to NULL.
4555** The calling procedure is responsible for deleting the compiled
4556** SQL statement using [sqlite3_finalize()] after it has finished with it.
4557** ppStmt may not be NULL.
4558**
4559** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
4560** otherwise an [error code] is returned.
4561**
4562** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
4563** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
4564** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
4565** are retained for backwards compatibility, but their use is discouraged.
4566** ^In the "vX" interfaces, the prepared statement
4567** that is returned (the [sqlite3_stmt] object) contains a copy of the
4568** original SQL text. This causes the [sqlite3_step()] interface to
4569** behave differently in three ways:
4570**
4571** <ol>
4572** <li>
4573** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
4574** always used to do, [sqlite3_step()] will automatically recompile the SQL
4575** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
4576** retries will occur before sqlite3_step() gives up and returns an error.
4577** </li>
4578**
4579** <li>
4580** ^When an error occurs, [sqlite3_step()] will return one of the detailed
4581** [error codes] or [extended error codes].  ^The legacy behavior was that
4582** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
4583** and the application would have to make a second call to [sqlite3_reset()]
4584** in order to find the underlying cause of the problem. With the "v2" prepare
4585** interfaces, the underlying reason for the error is returned immediately.
4586** </li>
4587**
4588** <li>
4589** ^If the specific value bound to a [parameter | host parameter] in the
4590** WHERE clause might influence the choice of query plan for a statement,
4591** then the statement will be automatically recompiled, as if there had been
4592** a schema change, on the first [sqlite3_step()] call following any change
4593** to the [sqlite3_bind_text | bindings] of that [parameter].
4594** ^The specific value of a WHERE-clause [parameter] might influence the
4595** choice of query plan if the parameter is the left-hand side of a [LIKE]
4596** or [GLOB] operator or if the parameter is compared to an indexed column
4597** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled.
4598** </li>
4599** </ol>
4600**
4601** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
4602** the extra prepFlags parameter, which is a bit array consisting of zero or
4603** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags.  ^The
4604** sqlite3_prepare_v2() interface works exactly the same as
4605** sqlite3_prepare_v3() with a zero prepFlags parameter.
4606*/
4607SQLITE_API int sqlite3_prepare(
4608  sqlite3 *db,            /* Database handle */
4609  const char *zSql,       /* SQL statement, UTF-8 encoded */
4610  int nByte,              /* Maximum length of zSql in bytes. */
4611  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
4612  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
4613);
4614SQLITE_API int sqlite3_prepare_v2(
4615  sqlite3 *db,            /* Database handle */
4616  const char *zSql,       /* SQL statement, UTF-8 encoded */
4617  int nByte,              /* Maximum length of zSql in bytes. */
4618  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
4619  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
4620);
4621SQLITE_API int sqlite3_prepare_v3(
4622  sqlite3 *db,            /* Database handle */
4623  const char *zSql,       /* SQL statement, UTF-8 encoded */
4624  int nByte,              /* Maximum length of zSql in bytes. */
4625  unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
4626  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
4627  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
4628);
4629SQLITE_API int sqlite3_prepare16(
4630  sqlite3 *db,            /* Database handle */
4631  const void *zSql,       /* SQL statement, UTF-16 encoded */
4632  int nByte,              /* Maximum length of zSql in bytes. */
4633  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
4634  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
4635);
4636SQLITE_API int sqlite3_prepare16_v2(
4637  sqlite3 *db,            /* Database handle */
4638  const void *zSql,       /* SQL statement, UTF-16 encoded */
4639  int nByte,              /* Maximum length of zSql in bytes. */
4640  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
4641  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
4642);
4643SQLITE_API int sqlite3_prepare16_v3(
4644  sqlite3 *db,            /* Database handle */
4645  const void *zSql,       /* SQL statement, UTF-16 encoded */
4646  int nByte,              /* Maximum length of zSql in bytes. */
4647  unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
4648  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
4649  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
4650);
4651
4652/*
4653** CAPI3REF: Retrieving Statement SQL
4654** METHOD: sqlite3_stmt
4655**
4656** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
4657** SQL text used to create [prepared statement] P if P was
4658** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
4659** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
4660** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
4661** string containing the SQL text of prepared statement P with
4662** [bound parameters] expanded.
4663** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
4664** string containing the normalized SQL text of prepared statement P.  The
4665** semantics used to normalize a SQL statement are unspecified and subject
4666** to change.  At a minimum, literal values will be replaced with suitable
4667** placeholders.
4668**
4669** ^(For example, if a prepared statement is created using the SQL
4670** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
4671** and parameter :xyz is unbound, then sqlite3_sql() will return
4672** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
4673** will return "SELECT 2345,NULL".)^
4674**
4675** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
4676** is available to hold the result, or if the result would exceed the
4677** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
4678**
4679** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
4680** bound parameter expansions.  ^The [SQLITE_OMIT_TRACE] compile-time
4681** option causes sqlite3_expanded_sql() to always return NULL.
4682**
4683** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)
4684** are managed by SQLite and are automatically freed when the prepared
4685** statement is finalized.
4686** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
4687** is obtained from [sqlite3_malloc()] and must be freed by the application
4688** by passing it to [sqlite3_free()].
4689**
4690** ^The sqlite3_normalized_sql() interface is only available if
4691** the [SQLITE_ENABLE_NORMALIZE] compile-time option is defined.
4692*/
4693SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
4694SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
4695#ifdef SQLITE_ENABLE_NORMALIZE
4696SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
4697#endif
4698
4699/*
4700** CAPI3REF: Determine If An SQL Statement Writes The Database
4701** METHOD: sqlite3_stmt
4702**
4703** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
4704** and only if the [prepared statement] X makes no direct changes to
4705** the content of the database file.
4706**
4707** Note that [application-defined SQL functions] or
4708** [virtual tables] might change the database indirectly as a side effect.
4709** ^(For example, if an application defines a function "eval()" that
4710** calls [sqlite3_exec()], then the following SQL statement would
4711** change the database file through side-effects:
4712**
4713** <blockquote><pre>
4714**    SELECT eval('DELETE FROM t1') FROM t2;
4715** </pre></blockquote>
4716**
4717** But because the [SELECT] statement does not change the database file
4718** directly, sqlite3_stmt_readonly() would still return true.)^
4719**
4720** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
4721** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
4722** since the statements themselves do not actually modify the database but
4723** rather they control the timing of when other statements modify the
4724** database.  ^The [ATTACH] and [DETACH] statements also cause
4725** sqlite3_stmt_readonly() to return true since, while those statements
4726** change the configuration of a database connection, they do not make
4727** changes to the content of the database files on disk.
4728** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
4729** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
4730** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
4731** sqlite3_stmt_readonly() returns false for those commands.
4732**
4733** ^This routine returns false if there is any possibility that the
4734** statement might change the database file.  ^A false return does
4735** not guarantee that the statement will change the database file.
4736** ^For example, an UPDATE statement might have a WHERE clause that
4737** makes it a no-op, but the sqlite3_stmt_readonly() result would still
4738** be false.  ^Similarly, a CREATE TABLE IF NOT EXISTS statement is a
4739** read-only no-op if the table already exists, but
4740** sqlite3_stmt_readonly() still returns false for such a statement.
4741**
4742** ^If prepared statement X is an [EXPLAIN] or [EXPLAIN QUERY PLAN]
4743** statement, then sqlite3_stmt_readonly(X) returns the same value as
4744** if the EXPLAIN or EXPLAIN QUERY PLAN prefix were omitted.
4745*/
4746SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
4747
4748/*
4749** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement
4750** METHOD: sqlite3_stmt
4751**
4752** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the
4753** prepared statement S is an EXPLAIN statement, or 2 if the
4754** statement S is an EXPLAIN QUERY PLAN.
4755** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is
4756** an ordinary statement or a NULL pointer.
4757*/
4758SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);
4759
4760/*
4761** CAPI3REF: Change The EXPLAIN Setting For A Prepared Statement
4762** METHOD: sqlite3_stmt
4763**
4764** The sqlite3_stmt_explain(S,E) interface changes the EXPLAIN
4765** setting for [prepared statement] S.  If E is zero, then S becomes
4766** a normal prepared statement.  If E is 1, then S behaves as if
4767** its SQL text began with "[EXPLAIN]".  If E is 2, then S behaves as if
4768** its SQL text began with "[EXPLAIN QUERY PLAN]".
4769**
4770** Calling sqlite3_stmt_explain(S,E) might cause S to be reprepared.
4771** SQLite tries to avoid a reprepare, but a reprepare might be necessary
4772** on the first transition into EXPLAIN or EXPLAIN QUERY PLAN mode.
4773**
4774** Because of the potential need to reprepare, a call to
4775** sqlite3_stmt_explain(S,E) will fail with SQLITE_ERROR if S cannot be
4776** reprepared because it was created using [sqlite3_prepare()] instead of
4777** the newer [sqlite3_prepare_v2()] or [sqlite3_prepare_v3()] interfaces and
4778** hence has no saved SQL text with which to reprepare.
4779**
4780** Changing the explain setting for a prepared statement does not change
4781** the original SQL text for the statement.  Hence, if the SQL text originally
4782** began with EXPLAIN or EXPLAIN QUERY PLAN, but sqlite3_stmt_explain(S,0)
4783** is called to convert the statement into an ordinary statement, the EXPLAIN
4784** or EXPLAIN QUERY PLAN keywords will still appear in the sqlite3_sql(S)
4785** output, even though the statement now acts like a normal SQL statement.
4786**
4787** This routine returns SQLITE_OK if the explain mode is successfully
4788** changed, or an error code if the explain mode could not be changed.
4789** The explain mode cannot be changed while a statement is active.
4790** Hence, it is good practice to call [sqlite3_reset(S)]
4791** immediately prior to calling sqlite3_stmt_explain(S,E).
4792*/
4793SQLITE_API int sqlite3_stmt_explain(sqlite3_stmt *pStmt, int eMode);
4794
4795/*
4796** CAPI3REF: Determine If A Prepared Statement Has Been Reset
4797** METHOD: sqlite3_stmt
4798**
4799** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
4800** [prepared statement] S has been stepped at least once using
4801** [sqlite3_step(S)] but has neither run to completion (returned
4802** [SQLITE_DONE] from [sqlite3_step(S)]) nor
4803** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
4804** interface returns false if S is a NULL pointer.  If S is not a
4805** NULL pointer and is not a pointer to a valid [prepared statement]
4806** object, then the behavior is undefined and probably undesirable.
4807**
4808** This interface can be used in combination [sqlite3_next_stmt()]
4809** to locate all prepared statements associated with a database
4810** connection that are in need of being reset.  This can be used,
4811** for example, in diagnostic routines to search for prepared
4812** statements that are holding a transaction open.
4813*/
4814SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
4815
4816/*
4817** CAPI3REF: Dynamically Typed Value Object
4818** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
4819**
4820** SQLite uses the sqlite3_value object to represent all values
4821** that can be stored in a database table. SQLite uses dynamic typing
4822** for the values it stores.  ^Values stored in sqlite3_value objects
4823** can be integers, floating point values, strings, BLOBs, or NULL.
4824**
4825** An sqlite3_value object may be either "protected" or "unprotected".
4826** Some interfaces require a protected sqlite3_value.  Other interfaces
4827** will accept either a protected or an unprotected sqlite3_value.
4828** Every interface that accepts sqlite3_value arguments specifies
4829** whether or not it requires a protected sqlite3_value.  The
4830** [sqlite3_value_dup()] interface can be used to construct a new
4831** protected sqlite3_value from an unprotected sqlite3_value.
4832**
4833** The terms "protected" and "unprotected" refer to whether or not
4834** a mutex is held.  An internal mutex is held for a protected
4835** sqlite3_value object but no mutex is held for an unprotected
4836** sqlite3_value object.  If SQLite is compiled to be single-threaded
4837** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
4838** or if SQLite is run in one of reduced mutex modes
4839** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
4840** then there is no distinction between protected and unprotected
4841** sqlite3_value objects and they can be used interchangeably.  However,
4842** for maximum code portability it is recommended that applications
4843** still make the distinction between protected and unprotected
4844** sqlite3_value objects even when not strictly required.
4845**
4846** ^The sqlite3_value objects that are passed as parameters into the
4847** implementation of [application-defined SQL functions] are protected.
4848** ^The sqlite3_value objects returned by [sqlite3_vtab_rhs_value()]
4849** are protected.
4850** ^The sqlite3_value object returned by
4851** [sqlite3_column_value()] is unprotected.
4852** Unprotected sqlite3_value objects may only be used as arguments
4853** to [sqlite3_result_value()], [sqlite3_bind_value()], and
4854** [sqlite3_value_dup()].
4855** The [sqlite3_value_blob | sqlite3_value_type()] family of
4856** interfaces require protected sqlite3_value objects.
4857*/
4858typedef struct sqlite3_value sqlite3_value;
4859
4860/*
4861** CAPI3REF: SQL Function Context Object
4862**
4863** The context in which an SQL function executes is stored in an
4864** sqlite3_context object.  ^A pointer to an sqlite3_context object
4865** is always first parameter to [application-defined SQL functions].
4866** The application-defined SQL function implementation will pass this
4867** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
4868** [sqlite3_aggregate_context()], [sqlite3_user_data()],
4869** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
4870** and/or [sqlite3_set_auxdata()].
4871*/
4872typedef struct sqlite3_context sqlite3_context;
4873
4874/*
4875** CAPI3REF: Binding Values To Prepared Statements
4876** KEYWORDS: {host parameter} {host parameters} {host parameter name}
4877** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
4878** METHOD: sqlite3_stmt
4879**
4880** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
4881** literals may be replaced by a [parameter] that matches one of following
4882** templates:
4883**
4884** <ul>
4885** <li>  ?
4886** <li>  ?NNN
4887** <li>  :VVV
4888** <li>  @VVV
4889** <li>  $VVV
4890** </ul>
4891**
4892** In the templates above, NNN represents an integer literal,
4893** and VVV represents an alphanumeric identifier.)^  ^The values of these
4894** parameters (also called "host parameter names" or "SQL parameters")
4895** can be set using the sqlite3_bind_*() routines defined here.
4896**
4897** ^The first argument to the sqlite3_bind_*() routines is always
4898** a pointer to the [sqlite3_stmt] object returned from
4899** [sqlite3_prepare_v2()] or its variants.
4900**
4901** ^The second argument is the index of the SQL parameter to be set.
4902** ^The leftmost SQL parameter has an index of 1.  ^When the same named
4903** SQL parameter is used more than once, second and subsequent
4904** occurrences have the same index as the first occurrence.
4905** ^The index for named parameters can be looked up using the
4906** [sqlite3_bind_parameter_index()] API if desired.  ^The index
4907** for "?NNN" parameters is the value of NNN.
4908** ^The NNN value must be between 1 and the [sqlite3_limit()]
4909** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 32766).
4910**
4911** ^The third argument is the value to bind to the parameter.
4912** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
4913** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
4914** is ignored and the end result is the same as sqlite3_bind_null().
4915** ^If the third parameter to sqlite3_bind_text() is not NULL, then
4916** it should be a pointer to well-formed UTF8 text.
4917** ^If the third parameter to sqlite3_bind_text16() is not NULL, then
4918** it should be a pointer to well-formed UTF16 text.
4919** ^If the third parameter to sqlite3_bind_text64() is not NULL, then
4920** it should be a pointer to a well-formed unicode string that is
4921** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16
4922** otherwise.
4923**
4924** [[byte-order determination rules]] ^The byte-order of
4925** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)
4926** found in first character, which is removed, or in the absence of a BOM
4927** the byte order is the native byte order of the host
4928** machine for sqlite3_bind_text16() or the byte order specified in
4929** the 6th parameter for sqlite3_bind_text64().)^
4930** ^If UTF16 input text contains invalid unicode
4931** characters, then SQLite might change those invalid characters
4932** into the unicode replacement character: U+FFFD.
4933**
4934** ^(In those routines that have a fourth argument, its value is the
4935** number of bytes in the parameter.  To be clear: the value is the
4936** number of <u>bytes</u> in the value, not the number of characters.)^
4937** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
4938** is negative, then the length of the string is
4939** the number of bytes up to the first zero terminator.
4940** If the fourth parameter to sqlite3_bind_blob() is negative, then
4941** the behavior is undefined.
4942** If a non-negative fourth parameter is provided to sqlite3_bind_text()
4943** or sqlite3_bind_text16() or sqlite3_bind_text64() then
4944** that parameter must be the byte offset
4945** where the NUL terminator would occur assuming the string were NUL
4946** terminated.  If any NUL characters occurs at byte offsets less than
4947** the value of the fourth parameter then the resulting string value will
4948** contain embedded NULs.  The result of expressions involving strings
4949** with embedded NULs is undefined.
4950**
4951** ^The fifth argument to the BLOB and string binding interfaces controls
4952** or indicates the lifetime of the object referenced by the third parameter.
4953** These three options exist:
4954** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished
4955** with it may be passed. ^It is called to dispose of the BLOB or string even
4956** if the call to the bind API fails, except the destructor is not called if
4957** the third parameter is a NULL pointer or the fourth parameter is negative.
4958** ^ (2) The special constant, [SQLITE_STATIC], may be passed to indicate that
4959** the application remains responsible for disposing of the object. ^In this
4960** case, the object and the provided pointer to it must remain valid until
4961** either the prepared statement is finalized or the same SQL parameter is
4962** bound to something else, whichever occurs sooner.
4963** ^ (3) The constant, [SQLITE_TRANSIENT], may be passed to indicate that the
4964** object is to be copied prior to the return from sqlite3_bind_*(). ^The
4965** object and pointer to it must remain valid until then. ^SQLite will then
4966** manage the lifetime of its private copy.
4967**
4968** ^The sixth argument to sqlite3_bind_text64() must be one of
4969** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
4970** to specify the encoding of the text in the third parameter.  If
4971** the sixth argument to sqlite3_bind_text64() is not one of the
4972** allowed values shown above, or if the text encoding is different
4973** from the encoding specified by the sixth parameter, then the behavior
4974** is undefined.
4975**
4976** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
4977** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
4978** (just an integer to hold its size) while it is being processed.
4979** Zeroblobs are intended to serve as placeholders for BLOBs whose
4980** content is later written using
4981** [sqlite3_blob_open | incremental BLOB I/O] routines.
4982** ^A negative value for the zeroblob results in a zero-length BLOB.
4983**
4984** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
4985** [prepared statement] S to have an SQL value of NULL, but to also be
4986** associated with the pointer P of type T.  ^D is either a NULL pointer or
4987** a pointer to a destructor function for P. ^SQLite will invoke the
4988** destructor D with a single argument of P when it is finished using
4989** P.  The T parameter should be a static string, preferably a string
4990** literal. The sqlite3_bind_pointer() routine is part of the
4991** [pointer passing interface] added for SQLite 3.20.0.
4992**
4993** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
4994** for the [prepared statement] or with a prepared statement for which
4995** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
4996** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
4997** routine is passed a [prepared statement] that has been finalized, the
4998** result is undefined and probably harmful.
4999**
5000** ^Bindings are not cleared by the [sqlite3_reset()] routine.
5001** ^Unbound parameters are interpreted as NULL.
5002**
5003** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
5004** [error code] if anything goes wrong.
5005** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
5006** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
5007** [SQLITE_MAX_LENGTH].
5008** ^[SQLITE_RANGE] is returned if the parameter
5009** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
5010**
5011** See also: [sqlite3_bind_parameter_count()],
5012** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
5013*/
5014SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
5015SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
5016                        void(*)(void*));
5017SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
5018SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
5019SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
5020SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
5021SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
5022SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
5023SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
5024                         void(*)(void*), unsigned char encoding);
5025SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
5026SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
5027SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
5028SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
5029
5030/*
5031** CAPI3REF: Number Of SQL Parameters
5032** METHOD: sqlite3_stmt
5033**
5034** ^This routine can be used to find the number of [SQL parameters]
5035** in a [prepared statement].  SQL parameters are tokens of the
5036** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
5037** placeholders for values that are [sqlite3_bind_blob | bound]
5038** to the parameters at a later time.
5039**
5040** ^(This routine actually returns the index of the largest (rightmost)
5041** parameter. For all forms except ?NNN, this will correspond to the
5042** number of unique parameters.  If parameters of the ?NNN form are used,
5043** there may be gaps in the list.)^
5044**
5045** See also: [sqlite3_bind_blob|sqlite3_bind()],
5046** [sqlite3_bind_parameter_name()], and
5047** [sqlite3_bind_parameter_index()].
5048*/
5049SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
5050
5051/*
5052** CAPI3REF: Name Of A Host Parameter
5053** METHOD: sqlite3_stmt
5054**
5055** ^The sqlite3_bind_parameter_name(P,N) interface returns
5056** the name of the N-th [SQL parameter] in the [prepared statement] P.
5057** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
5058** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
5059** respectively.
5060** In other words, the initial ":" or "$" or "@" or "?"
5061** is included as part of the name.)^
5062** ^Parameters of the form "?" without a following integer have no name
5063** and are referred to as "nameless" or "anonymous parameters".
5064**
5065** ^The first host parameter has an index of 1, not 0.
5066**
5067** ^If the value N is out of range or if the N-th parameter is
5068** nameless, then NULL is returned.  ^The returned string is
5069** always in UTF-8 encoding even if the named parameter was
5070** originally specified as UTF-16 in [sqlite3_prepare16()],
5071** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
5072**
5073** See also: [sqlite3_bind_blob|sqlite3_bind()],
5074** [sqlite3_bind_parameter_count()], and
5075** [sqlite3_bind_parameter_index()].
5076*/
5077SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
5078
5079/*
5080** CAPI3REF: Index Of A Parameter With A Given Name
5081** METHOD: sqlite3_stmt
5082**
5083** ^Return the index of an SQL parameter given its name.  ^The
5084** index value returned is suitable for use as the second
5085** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
5086** is returned if no matching parameter is found.  ^The parameter
5087** name must be given in UTF-8 even if the original statement
5088** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
5089** [sqlite3_prepare16_v3()].
5090**
5091** See also: [sqlite3_bind_blob|sqlite3_bind()],
5092** [sqlite3_bind_parameter_count()], and
5093** [sqlite3_bind_parameter_name()].
5094*/
5095SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
5096
5097/*
5098** CAPI3REF: Reset All Bindings On A Prepared Statement
5099** METHOD: sqlite3_stmt
5100**
5101** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
5102** the [sqlite3_bind_blob | bindings] on a [prepared statement].
5103** ^Use this routine to reset all host parameters to NULL.
5104*/
5105SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
5106
5107/*
5108** CAPI3REF: Number Of Columns In A Result Set
5109** METHOD: sqlite3_stmt
5110**
5111** ^Return the number of columns in the result set returned by the
5112** [prepared statement]. ^If this routine returns 0, that means the
5113** [prepared statement] returns no data (for example an [UPDATE]).
5114** ^However, just because this routine returns a positive number does not
5115** mean that one or more rows of data will be returned.  ^A SELECT statement
5116** will always have a positive sqlite3_column_count() but depending on the
5117** WHERE clause constraints and the table content, it might return no rows.
5118**
5119** See also: [sqlite3_data_count()]
5120*/
5121SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
5122
5123/*
5124** CAPI3REF: Column Names In A Result Set
5125** METHOD: sqlite3_stmt
5126**
5127** ^These routines return the name assigned to a particular column
5128** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
5129** interface returns a pointer to a zero-terminated UTF-8 string
5130** and sqlite3_column_name16() returns a pointer to a zero-terminated
5131** UTF-16 string.  ^The first parameter is the [prepared statement]
5132** that implements the [SELECT] statement. ^The second parameter is the
5133** column number.  ^The leftmost column is number 0.
5134**
5135** ^The returned string pointer is valid until either the [prepared statement]
5136** is destroyed by [sqlite3_finalize()] or until the statement is automatically
5137** reprepared by the first call to [sqlite3_step()] for a particular run
5138** or until the next call to
5139** sqlite3_column_name() or sqlite3_column_name16() on the same column.
5140**
5141** ^If sqlite3_malloc() fails during the processing of either routine
5142** (for example during a conversion from UTF-8 to UTF-16) then a
5143** NULL pointer is returned.
5144**
5145** ^The name of a result column is the value of the "AS" clause for
5146** that column, if there is an AS clause.  If there is no AS clause
5147** then the name of the column is unspecified and may change from
5148** one release of SQLite to the next.
5149*/
5150SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
5151SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
5152
5153/*
5154** CAPI3REF: Source Of Data In A Query Result
5155** METHOD: sqlite3_stmt
5156**
5157** ^These routines provide a means to determine the database, table, and
5158** table column that is the origin of a particular result column in
5159** [SELECT] statement.
5160** ^The name of the database or table or column can be returned as
5161** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
5162** the database name, the _table_ routines return the table name, and
5163** the origin_ routines return the column name.
5164** ^The returned string is valid until the [prepared statement] is destroyed
5165** using [sqlite3_finalize()] or until the statement is automatically
5166** reprepared by the first call to [sqlite3_step()] for a particular run
5167** or until the same information is requested
5168** again in a different encoding.
5169**
5170** ^The names returned are the original un-aliased names of the
5171** database, table, and column.
5172**
5173** ^The first argument to these interfaces is a [prepared statement].
5174** ^These functions return information about the Nth result column returned by
5175** the statement, where N is the second function argument.
5176** ^The left-most column is column 0 for these routines.
5177**
5178** ^If the Nth column returned by the statement is an expression or
5179** subquery and is not a column value, then all of these functions return
5180** NULL.  ^These routines might also return NULL if a memory allocation error
5181** occurs.  ^Otherwise, they return the name of the attached database, table,
5182** or column that query result column was extracted from.
5183**
5184** ^As with all other SQLite APIs, those whose names end with "16" return
5185** UTF-16 encoded strings and the other functions return UTF-8.
5186**
5187** ^These APIs are only available if the library was compiled with the
5188** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
5189**
5190** If two or more threads call one or more
5191** [sqlite3_column_database_name | column metadata interfaces]
5192** for the same [prepared statement] and result column
5193** at the same time then the results are undefined.
5194*/
5195SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
5196SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
5197SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
5198SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
5199SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
5200SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
5201
5202/*
5203** CAPI3REF: Declared Datatype Of A Query Result
5204** METHOD: sqlite3_stmt
5205**
5206** ^(The first parameter is a [prepared statement].
5207** If this statement is a [SELECT] statement and the Nth column of the
5208** returned result set of that [SELECT] is a table column (not an
5209** expression or subquery) then the declared type of the table
5210** column is returned.)^  ^If the Nth column of the result set is an
5211** expression or subquery, then a NULL pointer is returned.
5212** ^The returned string is always UTF-8 encoded.
5213**
5214** ^(For example, given the database schema:
5215**
5216** CREATE TABLE t1(c1 VARIANT);
5217**
5218** and the following statement to be compiled:
5219**
5220** SELECT c1 + 1, c1 FROM t1;
5221**
5222** this routine would return the string "VARIANT" for the second result
5223** column (i==1), and a NULL pointer for the first result column (i==0).)^
5224**
5225** ^SQLite uses dynamic run-time typing.  ^So just because a column
5226** is declared to contain a particular type does not mean that the
5227** data stored in that column is of the declared type.  SQLite is
5228** strongly typed, but the typing is dynamic not static.  ^Type
5229** is associated with individual values, not with the containers
5230** used to hold those values.
5231*/
5232SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
5233SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
5234
5235/*
5236** CAPI3REF: Evaluate An SQL Statement
5237** METHOD: sqlite3_stmt
5238**
5239** After a [prepared statement] has been prepared using any of
5240** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
5241** or [sqlite3_prepare16_v3()] or one of the legacy
5242** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
5243** must be called one or more times to evaluate the statement.
5244**
5245** The details of the behavior of the sqlite3_step() interface depend
5246** on whether the statement was prepared using the newer "vX" interfaces
5247** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
5248** [sqlite3_prepare16_v2()] or the older legacy
5249** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
5250** new "vX" interface is recommended for new applications but the legacy
5251** interface will continue to be supported.
5252**
5253** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
5254** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
5255** ^With the "v2" interface, any of the other [result codes] or
5256** [extended result codes] might be returned as well.
5257**
5258** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
5259** database locks it needs to do its job.  ^If the statement is a [COMMIT]
5260** or occurs outside of an explicit transaction, then you can retry the
5261** statement.  If the statement is not a [COMMIT] and occurs within an
5262** explicit transaction then you should rollback the transaction before
5263** continuing.
5264**
5265** ^[SQLITE_DONE] means that the statement has finished executing
5266** successfully.  sqlite3_step() should not be called again on this virtual
5267** machine without first calling [sqlite3_reset()] to reset the virtual
5268** machine back to its initial state.
5269**
5270** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
5271** is returned each time a new row of data is ready for processing by the
5272** caller. The values may be accessed using the [column access functions].
5273** sqlite3_step() is called again to retrieve the next row of data.
5274**
5275** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
5276** violation) has occurred.  sqlite3_step() should not be called again on
5277** the VM. More information may be found by calling [sqlite3_errmsg()].
5278** ^With the legacy interface, a more specific error code (for example,
5279** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
5280** can be obtained by calling [sqlite3_reset()] on the
5281** [prepared statement].  ^In the "v2" interface,
5282** the more specific error code is returned directly by sqlite3_step().
5283**
5284** [SQLITE_MISUSE] means that the this routine was called inappropriately.
5285** Perhaps it was called on a [prepared statement] that has
5286** already been [sqlite3_finalize | finalized] or on one that had
5287** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
5288** be the case that the same database connection is being used by two or
5289** more threads at the same moment in time.
5290**
5291** For all versions of SQLite up to and including 3.6.23.1, a call to
5292** [sqlite3_reset()] was required after sqlite3_step() returned anything
5293** other than [SQLITE_ROW] before any subsequent invocation of
5294** sqlite3_step().  Failure to reset the prepared statement using
5295** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
5296** sqlite3_step().  But after [version 3.6.23.1] ([dateof:3.6.23.1],
5297** sqlite3_step() began
5298** calling [sqlite3_reset()] automatically in this circumstance rather
5299** than returning [SQLITE_MISUSE].  This is not considered a compatibility
5300** break because any application that ever receives an SQLITE_MISUSE error
5301** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
5302** can be used to restore the legacy behavior.
5303**
5304** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
5305** API always returns a generic error code, [SQLITE_ERROR], following any
5306** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
5307** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
5308** specific [error codes] that better describes the error.
5309** We admit that this is a goofy design.  The problem has been fixed
5310** with the "v2" interface.  If you prepare all of your SQL statements
5311** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
5312** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
5313** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
5314** then the more specific [error codes] are returned directly
5315** by sqlite3_step().  The use of the "vX" interfaces is recommended.
5316*/
5317SQLITE_API int sqlite3_step(sqlite3_stmt*);
5318
5319/*
5320** CAPI3REF: Number of columns in a result set
5321** METHOD: sqlite3_stmt
5322**
5323** ^The sqlite3_data_count(P) interface returns the number of columns in the
5324** current row of the result set of [prepared statement] P.
5325** ^If prepared statement P does not have results ready to return
5326** (via calls to the [sqlite3_column_int | sqlite3_column()] family of
5327** interfaces) then sqlite3_data_count(P) returns 0.
5328** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
5329** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
5330** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
5331** will return non-zero if previous call to [sqlite3_step](P) returned
5332** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
5333** where it always returns zero since each step of that multi-step
5334** pragma returns 0 columns of data.
5335**
5336** See also: [sqlite3_column_count()]
5337*/
5338SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
5339
5340/*
5341** CAPI3REF: Fundamental Datatypes
5342** KEYWORDS: SQLITE_TEXT
5343**
5344** ^(Every value in SQLite has one of five fundamental datatypes:
5345**
5346** <ul>
5347** <li> 64-bit signed integer
5348** <li> 64-bit IEEE floating point number
5349** <li> string
5350** <li> BLOB
5351** <li> NULL
5352** </ul>)^
5353**
5354** These constants are codes for each of those types.
5355**
5356** Note that the SQLITE_TEXT constant was also used in SQLite version 2
5357** for a completely different meaning.  Software that links against both
5358** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
5359** SQLITE_TEXT.
5360*/
5361#define SQLITE_INTEGER  1
5362#define SQLITE_FLOAT    2
5363#define SQLITE_BLOB     4
5364#define SQLITE_NULL     5
5365#ifdef SQLITE_TEXT
5366# undef SQLITE_TEXT
5367#else
5368# define SQLITE_TEXT     3
5369#endif
5370#define SQLITE3_TEXT     3
5371
5372/*
5373** CAPI3REF: Result Values From A Query
5374** KEYWORDS: {column access functions}
5375** METHOD: sqlite3_stmt
5376**
5377** <b>Summary:</b>
5378** <blockquote><table border=0 cellpadding=0 cellspacing=0>
5379** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
5380** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
5381** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
5382** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
5383** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
5384** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
5385** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
5386** [sqlite3_value|unprotected sqlite3_value] object.
5387** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
5388** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
5389** or a UTF-8 TEXT result in bytes
5390** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
5391** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
5392** TEXT in bytes
5393** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
5394** datatype of the result
5395** </table></blockquote>
5396**
5397** <b>Details:</b>
5398**
5399** ^These routines return information about a single column of the current
5400** result row of a query.  ^In every case the first argument is a pointer
5401** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
5402** that was returned from [sqlite3_prepare_v2()] or one of its variants)
5403** and the second argument is the index of the column for which information
5404** should be returned. ^The leftmost column of the result set has the index 0.
5405** ^The number of columns in the result can be determined using
5406** [sqlite3_column_count()].
5407**
5408** If the SQL statement does not currently point to a valid row, or if the
5409** column index is out of range, the result is undefined.
5410** These routines may only be called when the most recent call to
5411** [sqlite3_step()] has returned [SQLITE_ROW] and neither
5412** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
5413** If any of these routines are called after [sqlite3_reset()] or
5414** [sqlite3_finalize()] or after [sqlite3_step()] has returned
5415** something other than [SQLITE_ROW], the results are undefined.
5416** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
5417** are called from a different thread while any of these routines
5418** are pending, then the results are undefined.
5419**
5420** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
5421** each return the value of a result column in a specific data format.  If
5422** the result column is not initially in the requested format (for example,
5423** if the query returns an integer but the sqlite3_column_text() interface
5424** is used to extract the value) then an automatic type conversion is performed.
5425**
5426** ^The sqlite3_column_type() routine returns the
5427** [SQLITE_INTEGER | datatype code] for the initial data type
5428** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
5429** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
5430** The return value of sqlite3_column_type() can be used to decide which
5431** of the first six interface should be used to extract the column value.
5432** The value returned by sqlite3_column_type() is only meaningful if no
5433** automatic type conversions have occurred for the value in question.
5434** After a type conversion, the result of calling sqlite3_column_type()
5435** is undefined, though harmless.  Future
5436** versions of SQLite may change the behavior of sqlite3_column_type()
5437** following a type conversion.
5438**
5439** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
5440** or sqlite3_column_bytes16() interfaces can be used to determine the size
5441** of that BLOB or string.
5442**
5443** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
5444** routine returns the number of bytes in that BLOB or string.
5445** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
5446** the string to UTF-8 and then returns the number of bytes.
5447** ^If the result is a numeric value then sqlite3_column_bytes() uses
5448** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
5449** the number of bytes in that string.
5450** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
5451**
5452** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
5453** routine returns the number of bytes in that BLOB or string.
5454** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
5455** the string to UTF-16 and then returns the number of bytes.
5456** ^If the result is a numeric value then sqlite3_column_bytes16() uses
5457** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
5458** the number of bytes in that string.
5459** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
5460**
5461** ^The values returned by [sqlite3_column_bytes()] and
5462** [sqlite3_column_bytes16()] do not include the zero terminators at the end
5463** of the string.  ^For clarity: the values returned by
5464** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
5465** bytes in the string, not the number of characters.
5466**
5467** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
5468** even empty strings, are always zero-terminated.  ^The return
5469** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
5470**
5471** ^Strings returned by sqlite3_column_text16() always have the endianness
5472** which is native to the platform, regardless of the text encoding set
5473** for the database.
5474**
5475** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
5476** [unprotected sqlite3_value] object.  In a multithreaded environment,
5477** an unprotected sqlite3_value object may only be used safely with
5478** [sqlite3_bind_value()] and [sqlite3_result_value()].
5479** If the [unprotected sqlite3_value] object returned by
5480** [sqlite3_column_value()] is used in any other way, including calls
5481** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
5482** or [sqlite3_value_bytes()], the behavior is not threadsafe.
5483** Hence, the sqlite3_column_value() interface
5484** is normally only useful within the implementation of
5485** [application-defined SQL functions] or [virtual tables], not within
5486** top-level application code.
5487**
5488** These routines may attempt to convert the datatype of the result.
5489** ^For example, if the internal representation is FLOAT and a text result
5490** is requested, [sqlite3_snprintf()] is used internally to perform the
5491** conversion automatically.  ^(The following table details the conversions
5492** that are applied:
5493**
5494** <blockquote>
5495** <table border="1">
5496** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
5497**
5498** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
5499** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
5500** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
5501** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
5502** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
5503** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
5504** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
5505** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
5506** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
5507** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
5508** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
5509** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
5510** <tr><td>  TEXT    <td>   BLOB    <td> No change
5511** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
5512** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
5513** <tr><td>  BLOB    <td>   TEXT    <td> [CAST] to TEXT, ensure zero terminator
5514** </table>
5515** </blockquote>)^
5516**
5517** Note that when type conversions occur, pointers returned by prior
5518** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
5519** sqlite3_column_text16() may be invalidated.
5520** Type conversions and pointer invalidations might occur
5521** in the following cases:
5522**
5523** <ul>
5524** <li> The initial content is a BLOB and sqlite3_column_text() or
5525**      sqlite3_column_text16() is called.  A zero-terminator might
5526**      need to be added to the string.</li>
5527** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
5528**      sqlite3_column_text16() is called.  The content must be converted
5529**      to UTF-16.</li>
5530** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
5531**      sqlite3_column_text() is called.  The content must be converted
5532**      to UTF-8.</li>
5533** </ul>
5534**
5535** ^Conversions between UTF-16be and UTF-16le are always done in place and do
5536** not invalidate a prior pointer, though of course the content of the buffer
5537** that the prior pointer references will have been modified.  Other kinds
5538** of conversion are done in place when it is possible, but sometimes they
5539** are not possible and in those cases prior pointers are invalidated.
5540**
5541** The safest policy is to invoke these routines
5542** in one of the following ways:
5543**
5544** <ul>
5545**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
5546**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
5547**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
5548** </ul>
5549**
5550** In other words, you should call sqlite3_column_text(),
5551** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
5552** into the desired format, then invoke sqlite3_column_bytes() or
5553** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
5554** to sqlite3_column_text() or sqlite3_column_blob() with calls to
5555** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
5556** with calls to sqlite3_column_bytes().
5557**
5558** ^The pointers returned are valid until a type conversion occurs as
5559** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
5560** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
5561** and BLOBs is freed automatically.  Do not pass the pointers returned
5562** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
5563** [sqlite3_free()].
5564**
5565** As long as the input parameters are correct, these routines will only
5566** fail if an out-of-memory error occurs during a format conversion.
5567** Only the following subset of interfaces are subject to out-of-memory
5568** errors:
5569**
5570** <ul>
5571** <li> sqlite3_column_blob()
5572** <li> sqlite3_column_text()
5573** <li> sqlite3_column_text16()
5574** <li> sqlite3_column_bytes()
5575** <li> sqlite3_column_bytes16()
5576** </ul>
5577**
5578** If an out-of-memory error occurs, then the return value from these
5579** routines is the same as if the column had contained an SQL NULL value.
5580** Valid SQL NULL returns can be distinguished from out-of-memory errors
5581** by invoking the [sqlite3_errcode()] immediately after the suspect
5582** return value is obtained and before any
5583** other SQLite interface is called on the same [database connection].
5584*/
5585SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
5586SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
5587SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
5588SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
5589SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
5590SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
5591SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
5592SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
5593SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
5594SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
5595
5596/*
5597** CAPI3REF: Destroy A Prepared Statement Object
5598** DESTRUCTOR: sqlite3_stmt
5599**
5600** ^The sqlite3_finalize() function is called to delete a [prepared statement].
5601** ^If the most recent evaluation of the statement encountered no errors
5602** or if the statement is never been evaluated, then sqlite3_finalize() returns
5603** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
5604** sqlite3_finalize(S) returns the appropriate [error code] or
5605** [extended error code].
5606**
5607** ^The sqlite3_finalize(S) routine can be called at any point during
5608** the life cycle of [prepared statement] S:
5609** before statement S is ever evaluated, after
5610** one or more calls to [sqlite3_reset()], or after any call
5611** to [sqlite3_step()] regardless of whether or not the statement has
5612** completed execution.
5613**
5614** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
5615**
5616** The application must finalize every [prepared statement] in order to avoid
5617** resource leaks.  It is a grievous error for the application to try to use
5618** a prepared statement after it has been finalized.  Any use of a prepared
5619** statement after it has been finalized can result in undefined and
5620** undesirable behavior such as segfaults and heap corruption.
5621*/
5622SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
5623
5624/*
5625** CAPI3REF: Reset A Prepared Statement Object
5626** METHOD: sqlite3_stmt
5627**
5628** The sqlite3_reset() function is called to reset a [prepared statement]
5629** object back to its initial state, ready to be re-executed.
5630** ^Any SQL statement variables that had values bound to them using
5631** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
5632** Use [sqlite3_clear_bindings()] to reset the bindings.
5633**
5634** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
5635** back to the beginning of its program.
5636**
5637** ^The return code from [sqlite3_reset(S)] indicates whether or not
5638** the previous evaluation of prepared statement S completed successfully.
5639** ^If [sqlite3_step(S)] has never before been called on S or if
5640** [sqlite3_step(S)] has not been called since the previous call
5641** to [sqlite3_reset(S)], then [sqlite3_reset(S)] will return
5642** [SQLITE_OK].
5643**
5644** ^If the most recent call to [sqlite3_step(S)] for the
5645** [prepared statement] S indicated an error, then
5646** [sqlite3_reset(S)] returns an appropriate [error code].
5647** ^The [sqlite3_reset(S)] interface might also return an [error code]
5648** if there were no prior errors but the process of resetting
5649** the prepared statement caused a new error. ^For example, if an
5650** [INSERT] statement with a [RETURNING] clause is only stepped one time,
5651** that one call to [sqlite3_step(S)] might return SQLITE_ROW but
5652** the overall statement might still fail and the [sqlite3_reset(S)] call
5653** might return SQLITE_BUSY if locking constraints prevent the
5654** database change from committing.  Therefore, it is important that
5655** applications check the return code from [sqlite3_reset(S)] even if
5656** no prior call to [sqlite3_step(S)] indicated a problem.
5657**
5658** ^The [sqlite3_reset(S)] interface does not change the values
5659** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
5660*/
5661SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
5662
5663
5664/*
5665** CAPI3REF: Create Or Redefine SQL Functions
5666** KEYWORDS: {function creation routines}
5667** METHOD: sqlite3
5668**
5669** ^These functions (collectively known as "function creation routines")
5670** are used to add SQL functions or aggregates or to redefine the behavior
5671** of existing SQL functions or aggregates. The only differences between
5672** the three "sqlite3_create_function*" routines are the text encoding
5673** expected for the second parameter (the name of the function being
5674** created) and the presence or absence of a destructor callback for
5675** the application data pointer. Function sqlite3_create_window_function()
5676** is similar, but allows the user to supply the extra callback functions
5677** needed by [aggregate window functions].
5678**
5679** ^The first parameter is the [database connection] to which the SQL
5680** function is to be added.  ^If an application uses more than one database
5681** connection then application-defined SQL functions must be added
5682** to each database connection separately.
5683**
5684** ^The second parameter is the name of the SQL function to be created or
5685** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
5686** representation, exclusive of the zero-terminator.  ^Note that the name
5687** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
5688** ^Any attempt to create a function with a longer name
5689** will result in [SQLITE_MISUSE] being returned.
5690**
5691** ^The third parameter (nArg)
5692** is the number of arguments that the SQL function or
5693** aggregate takes. ^If this parameter is -1, then the SQL function or
5694** aggregate may take any number of arguments between 0 and the limit
5695** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
5696** parameter is less than -1 or greater than 127 then the behavior is
5697** undefined.
5698**
5699** ^The fourth parameter, eTextRep, specifies what
5700** [SQLITE_UTF8 | text encoding] this SQL function prefers for
5701** its parameters.  The application should set this parameter to
5702** [SQLITE_UTF16LE] if the function implementation invokes
5703** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
5704** implementation invokes [sqlite3_value_text16be()] on an input, or
5705** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
5706** otherwise.  ^The same SQL function may be registered multiple times using
5707** different preferred text encodings, with different implementations for
5708** each encoding.
5709** ^When multiple implementations of the same function are available, SQLite
5710** will pick the one that involves the least amount of data conversion.
5711**
5712** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
5713** to signal that the function will always return the same result given
5714** the same inputs within a single SQL statement.  Most SQL functions are
5715** deterministic.  The built-in [random()] SQL function is an example of a
5716** function that is not deterministic.  The SQLite query planner is able to
5717** perform additional optimizations on deterministic functions, so use
5718** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
5719**
5720** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY]
5721** flag, which if present prevents the function from being invoked from
5722** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,
5723** index expressions, or the WHERE clause of partial indexes.
5724**
5725** For best security, the [SQLITE_DIRECTONLY] flag is recommended for
5726** all application-defined SQL functions that do not need to be
5727** used inside of triggers, view, CHECK constraints, or other elements of
5728** the database schema.  This flags is especially recommended for SQL
5729** functions that have side effects or reveal internal application state.
5730** Without this flag, an attacker might be able to modify the schema of
5731** a database file to include invocations of the function with parameters
5732** chosen by the attacker, which the application will then execute when
5733** the database file is opened and read.
5734**
5735** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
5736** function can gain access to this pointer using [sqlite3_user_data()].)^
5737**
5738** ^The sixth, seventh and eighth parameters passed to the three
5739** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are
5740** pointers to C-language functions that implement the SQL function or
5741** aggregate. ^A scalar SQL function requires an implementation of the xFunc
5742** callback only; NULL pointers must be passed as the xStep and xFinal
5743** parameters. ^An aggregate SQL function requires an implementation of xStep
5744** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
5745** SQL function or aggregate, pass NULL pointers for all three function
5746** callbacks.
5747**
5748** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue
5749** and xInverse) passed to sqlite3_create_window_function are pointers to
5750** C-language callbacks that implement the new function. xStep and xFinal
5751** must both be non-NULL. xValue and xInverse may either both be NULL, in
5752** which case a regular aggregate function is created, or must both be
5753** non-NULL, in which case the new function may be used as either an aggregate
5754** or aggregate window function. More details regarding the implementation
5755** of aggregate window functions are
5756** [user-defined window functions|available here].
5757**
5758** ^(If the final parameter to sqlite3_create_function_v2() or
5759** sqlite3_create_window_function() is not NULL, then it is destructor for
5760** the application data pointer. The destructor is invoked when the function
5761** is deleted, either by being overloaded or when the database connection
5762** closes.)^ ^The destructor is also invoked if the call to
5763** sqlite3_create_function_v2() fails.  ^When the destructor callback is
5764** invoked, it is passed a single argument which is a copy of the application
5765** data pointer which was the fifth parameter to sqlite3_create_function_v2().
5766**
5767** ^It is permitted to register multiple implementations of the same
5768** functions with the same name but with either differing numbers of
5769** arguments or differing preferred text encodings.  ^SQLite will use
5770** the implementation that most closely matches the way in which the
5771** SQL function is used.  ^A function implementation with a non-negative
5772** nArg parameter is a better match than a function implementation with
5773** a negative nArg.  ^A function where the preferred text encoding
5774** matches the database encoding is a better
5775** match than a function where the encoding is different.
5776** ^A function where the encoding difference is between UTF16le and UTF16be
5777** is a closer match than a function where the encoding difference is
5778** between UTF8 and UTF16.
5779**
5780** ^Built-in functions may be overloaded by new application-defined functions.
5781**
5782** ^An application-defined function is permitted to call other
5783** SQLite interfaces.  However, such calls must not
5784** close the database connection nor finalize or reset the prepared
5785** statement in which the function is running.
5786*/
5787SQLITE_API int sqlite3_create_function(
5788  sqlite3 *db,
5789  const char *zFunctionName,
5790  int nArg,
5791  int eTextRep,
5792  void *pApp,
5793  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
5794  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5795  void (*xFinal)(sqlite3_context*)
5796);
5797SQLITE_API int sqlite3_create_function16(
5798  sqlite3 *db,
5799  const void *zFunctionName,
5800  int nArg,
5801  int eTextRep,
5802  void *pApp,
5803  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
5804  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5805  void (*xFinal)(sqlite3_context*)
5806);
5807SQLITE_API int sqlite3_create_function_v2(
5808  sqlite3 *db,
5809  const char *zFunctionName,
5810  int nArg,
5811  int eTextRep,
5812  void *pApp,
5813  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
5814  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5815  void (*xFinal)(sqlite3_context*),
5816  void(*xDestroy)(void*)
5817);
5818SQLITE_API int sqlite3_create_window_function(
5819  sqlite3 *db,
5820  const char *zFunctionName,
5821  int nArg,
5822  int eTextRep,
5823  void *pApp,
5824  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5825  void (*xFinal)(sqlite3_context*),
5826  void (*xValue)(sqlite3_context*),
5827  void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
5828  void(*xDestroy)(void*)
5829);
5830
5831/*
5832** CAPI3REF: Text Encodings
5833**
5834** These constant define integer codes that represent the various
5835** text encodings supported by SQLite.
5836*/
5837#define SQLITE_UTF8           1    /* IMP: R-37514-35566 */
5838#define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */
5839#define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */
5840#define SQLITE_UTF16          4    /* Use native byte order */
5841#define SQLITE_ANY            5    /* Deprecated */
5842#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
5843
5844/*
5845** CAPI3REF: Function Flags
5846**
5847** These constants may be ORed together with the
5848** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
5849** to [sqlite3_create_function()], [sqlite3_create_function16()], or
5850** [sqlite3_create_function_v2()].
5851**
5852** <dl>
5853** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd>
5854** The SQLITE_DETERMINISTIC flag means that the new function always gives
5855** the same output when the input parameters are the same.
5856** The [abs|abs() function] is deterministic, for example, but
5857** [randomblob|randomblob()] is not.  Functions must
5858** be deterministic in order to be used in certain contexts such as
5859** with the WHERE clause of [partial indexes] or in [generated columns].
5860** SQLite might also optimize deterministic functions by factoring them
5861** out of inner loops.
5862** </dd>
5863**
5864** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd>
5865** The SQLITE_DIRECTONLY flag means that the function may only be invoked
5866** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in
5867** schema structures such as [CHECK constraints], [DEFAULT clauses],
5868** [expression indexes], [partial indexes], or [generated columns].
5869** <p>
5870** The SQLITE_DIRECTONLY flag is recommended for any
5871** [application-defined SQL function]
5872** that has side-effects or that could potentially leak sensitive information.
5873** This will prevent attacks in which an application is tricked
5874** into using a database file that has had its schema surreptitiously
5875** modified to invoke the application-defined function in ways that are
5876** harmful.
5877** <p>
5878** Some people say it is good practice to set SQLITE_DIRECTONLY on all
5879** [application-defined SQL functions], regardless of whether or not they
5880** are security sensitive, as doing so prevents those functions from being used
5881** inside of the database schema, and thus ensures that the database
5882** can be inspected and modified using generic tools (such as the [CLI])
5883** that do not have access to the application-defined functions.
5884** </dd>
5885**
5886** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd>
5887** The SQLITE_INNOCUOUS flag means that the function is unlikely
5888** to cause problems even if misused.  An innocuous function should have
5889** no side effects and should not depend on any values other than its
5890** input parameters. The [abs|abs() function] is an example of an
5891** innocuous function.
5892** The [load_extension() SQL function] is not innocuous because of its
5893** side effects.
5894** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not
5895** exactly the same.  The [random|random() function] is an example of a
5896** function that is innocuous but not deterministic.
5897** <p>Some heightened security settings
5898** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF])
5899** disable the use of SQL functions inside views and triggers and in
5900** schema structures such as [CHECK constraints], [DEFAULT clauses],
5901** [expression indexes], [partial indexes], and [generated columns] unless
5902** the function is tagged with SQLITE_INNOCUOUS.  Most built-in functions
5903** are innocuous.  Developers are advised to avoid using the
5904** SQLITE_INNOCUOUS flag for application-defined functions unless the
5905** function has been carefully audited and found to be free of potentially
5906** security-adverse side-effects and information-leaks.
5907** </dd>
5908**
5909** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>
5910** The SQLITE_SUBTYPE flag indicates to SQLite that a function might call
5911** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
5912** This flag instructs SQLite to omit some corner-case optimizations that
5913** might disrupt the operation of the [sqlite3_value_subtype()] function,
5914** causing it to return zero rather than the correct subtype().
5915** SQL functions that invokes [sqlite3_value_subtype()] should have this
5916** property.  If the SQLITE_SUBTYPE property is omitted, then the return
5917** value from [sqlite3_value_subtype()] might sometimes be zero even though
5918** a non-zero subtype was specified by the function argument expression.
5919**
5920** [[SQLITE_RESULT_SUBTYPE]] <dt>SQLITE_RESULT_SUBTYPE</dt><dd>
5921** The SQLITE_RESULT_SUBTYPE flag indicates to SQLite that a function might call
5922** [sqlite3_result_subtype()] to cause a sub-type to be associated with its
5923** result.
5924** Every function that invokes [sqlite3_result_subtype()] should have this
5925** property.  If it does not, then the call to [sqlite3_result_subtype()]
5926** might become a no-op if the function is used as term in an
5927** [expression index].  On the other hand, SQL functions that never invoke
5928** [sqlite3_result_subtype()] should avoid setting this property, as the
5929** purpose of this property is to disable certain optimizations that are
5930** incompatible with subtypes.
5931** </dd>
5932** </dl>
5933*/
5934#define SQLITE_DETERMINISTIC    0x000000800
5935#define SQLITE_DIRECTONLY       0x000080000
5936#define SQLITE_SUBTYPE          0x000100000
5937#define SQLITE_INNOCUOUS        0x000200000
5938#define SQLITE_RESULT_SUBTYPE   0x001000000
5939
5940/*
5941** CAPI3REF: Deprecated Functions
5942** DEPRECATED
5943**
5944** These functions are [deprecated].  In order to maintain
5945** backwards compatibility with older code, these functions continue
5946** to be supported.  However, new applications should avoid
5947** the use of these functions.  To encourage programmers to avoid
5948** these functions, we will not explain what they do.
5949*/
5950#ifndef SQLITE_OMIT_DEPRECATED
5951SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
5952SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
5953SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
5954SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
5955SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
5956SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
5957                      void*,sqlite3_int64);
5958#endif
5959
5960/*
5961** CAPI3REF: Obtaining SQL Values
5962** METHOD: sqlite3_value
5963**
5964** <b>Summary:</b>
5965** <blockquote><table border=0 cellpadding=0 cellspacing=0>
5966** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
5967** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
5968** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
5969** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
5970** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
5971** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
5972** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
5973** the native byteorder
5974** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
5975** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
5976** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
5977** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
5978** or a UTF-8 TEXT in bytes
5979** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
5980** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
5981** TEXT in bytes
5982** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
5983** datatype of the value
5984** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
5985** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
5986** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>
5987** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE
5988** against a virtual table.
5989** <tr><td><b>sqlite3_value_frombind&nbsp;&nbsp;</b>
5990** <td>&rarr;&nbsp;&nbsp;<td>True if value originated from a [bound parameter]
5991** </table></blockquote>
5992**
5993** <b>Details:</b>
5994**
5995** These routines extract type, size, and content information from
5996** [protected sqlite3_value] objects.  Protected sqlite3_value objects
5997** are used to pass parameter information into the functions that
5998** implement [application-defined SQL functions] and [virtual tables].
5999**
6000** These routines work only with [protected sqlite3_value] objects.
6001** Any attempt to use these routines on an [unprotected sqlite3_value]
6002** is not threadsafe.
6003**
6004** ^These routines work just like the corresponding [column access functions]
6005** except that these routines take a single [protected sqlite3_value] object
6006** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
6007**
6008** ^The sqlite3_value_text16() interface extracts a UTF-16 string
6009** in the native byte-order of the host machine.  ^The
6010** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
6011** extract UTF-16 strings as big-endian and little-endian respectively.
6012**
6013** ^If [sqlite3_value] object V was initialized
6014** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
6015** and if X and Y are strings that compare equal according to strcmp(X,Y),
6016** then sqlite3_value_pointer(V,Y) will return the pointer P.  ^Otherwise,
6017** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
6018** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
6019**
6020** ^(The sqlite3_value_type(V) interface returns the
6021** [SQLITE_INTEGER | datatype code] for the initial datatype of the
6022** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
6023** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
6024** Other interfaces might change the datatype for an sqlite3_value object.
6025** For example, if the datatype is initially SQLITE_INTEGER and
6026** sqlite3_value_text(V) is called to extract a text value for that
6027** integer, then subsequent calls to sqlite3_value_type(V) might return
6028** SQLITE_TEXT.  Whether or not a persistent internal datatype conversion
6029** occurs is undefined and may change from one release of SQLite to the next.
6030**
6031** ^(The sqlite3_value_numeric_type() interface attempts to apply
6032** numeric affinity to the value.  This means that an attempt is
6033** made to convert the value to an integer or floating point.  If
6034** such a conversion is possible without loss of information (in other
6035** words, if the value is a string that looks like a number)
6036** then the conversion is performed.  Otherwise no conversion occurs.
6037** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
6038**
6039** ^Within the [xUpdate] method of a [virtual table], the
6040** sqlite3_value_nochange(X) interface returns true if and only if
6041** the column corresponding to X is unchanged by the UPDATE operation
6042** that the xUpdate method call was invoked to implement and if
6043** and the prior [xColumn] method call that was invoked to extracted
6044** the value for that column returned without setting a result (probably
6045** because it queried [sqlite3_vtab_nochange()] and found that the column
6046** was unchanging).  ^Within an [xUpdate] method, any value for which
6047** sqlite3_value_nochange(X) is true will in all other respects appear
6048** to be a NULL value.  If sqlite3_value_nochange(X) is invoked anywhere other
6049** than within an [xUpdate] method call for an UPDATE statement, then
6050** the return value is arbitrary and meaningless.
6051**
6052** ^The sqlite3_value_frombind(X) interface returns non-zero if the
6053** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]
6054** interfaces.  ^If X comes from an SQL literal value, or a table column,
6055** or an expression, then sqlite3_value_frombind(X) returns zero.
6056**
6057** Please pay particular attention to the fact that the pointer returned
6058** from [sqlite3_value_blob()], [sqlite3_value_text()], or
6059** [sqlite3_value_text16()] can be invalidated by a subsequent call to
6060** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
6061** or [sqlite3_value_text16()].
6062**
6063** These routines must be called from the same thread as
6064** the SQL function that supplied the [sqlite3_value*] parameters.
6065**
6066** As long as the input parameter is correct, these routines can only
6067** fail if an out-of-memory error occurs during a format conversion.
6068** Only the following subset of interfaces are subject to out-of-memory
6069** errors:
6070**
6071** <ul>
6072** <li> sqlite3_value_blob()
6073** <li> sqlite3_value_text()
6074** <li> sqlite3_value_text16()
6075** <li> sqlite3_value_text16le()
6076** <li> sqlite3_value_text16be()
6077** <li> sqlite3_value_bytes()
6078** <li> sqlite3_value_bytes16()
6079** </ul>
6080**
6081** If an out-of-memory error occurs, then the return value from these
6082** routines is the same as if the column had contained an SQL NULL value.
6083** Valid SQL NULL returns can be distinguished from out-of-memory errors
6084** by invoking the [sqlite3_errcode()] immediately after the suspect
6085** return value is obtained and before any
6086** other SQLite interface is called on the same [database connection].
6087*/
6088SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
6089SQLITE_API double sqlite3_value_double(sqlite3_value*);
6090SQLITE_API int sqlite3_value_int(sqlite3_value*);
6091SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
6092SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
6093SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
6094SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
6095SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
6096SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
6097SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
6098SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
6099SQLITE_API int sqlite3_value_type(sqlite3_value*);
6100SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
6101SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
6102SQLITE_API int sqlite3_value_frombind(sqlite3_value*);
6103
6104/*
6105** CAPI3REF: Report the internal text encoding state of an sqlite3_value object
6106** METHOD: sqlite3_value
6107**
6108** ^(The sqlite3_value_encoding(X) interface returns one of [SQLITE_UTF8],
6109** [SQLITE_UTF16BE], or [SQLITE_UTF16LE] according to the current text encoding
6110** of the value X, assuming that X has type TEXT.)^  If sqlite3_value_type(X)
6111** returns something other than SQLITE_TEXT, then the return value from
6112** sqlite3_value_encoding(X) is meaningless.  ^Calls to
6113** [sqlite3_value_text(X)], [sqlite3_value_text16(X)], [sqlite3_value_text16be(X)],
6114** [sqlite3_value_text16le(X)], [sqlite3_value_bytes(X)], or
6115** [sqlite3_value_bytes16(X)] might change the encoding of the value X and
6116** thus change the return from subsequent calls to sqlite3_value_encoding(X).
6117**
6118** This routine is intended for used by applications that test and validate
6119** the SQLite implementation.  This routine is inquiring about the opaque
6120** internal state of an [sqlite3_value] object.  Ordinary applications should
6121** not need to know what the internal state of an sqlite3_value object is and
6122** hence should not need to use this interface.
6123*/
6124SQLITE_API int sqlite3_value_encoding(sqlite3_value*);
6125
6126/*
6127** CAPI3REF: Finding The Subtype Of SQL Values
6128** METHOD: sqlite3_value
6129**
6130** The sqlite3_value_subtype(V) function returns the subtype for
6131** an [application-defined SQL function] argument V.  The subtype
6132** information can be used to pass a limited amount of context from
6133** one SQL function to another.  Use the [sqlite3_result_subtype()]
6134** routine to set the subtype for the return value of an SQL function.
6135**
6136** Every [application-defined SQL function] that invoke this interface
6137** should include the [SQLITE_SUBTYPE] property in the text
6138** encoding argument when the function is [sqlite3_create_function|registered].
6139** If the [SQLITE_SUBTYPE] property is omitted, then sqlite3_value_subtype()
6140** might return zero instead of the upstream subtype in some corner cases.
6141*/
6142SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
6143
6144/*
6145** CAPI3REF: Copy And Free SQL Values
6146** METHOD: sqlite3_value
6147**
6148** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
6149** object D and returns a pointer to that copy.  ^The [sqlite3_value] returned
6150** is a [protected sqlite3_value] object even if the input is not.
6151** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
6152** memory allocation fails. ^If V is a [pointer value], then the result
6153** of sqlite3_value_dup(V) is a NULL value.
6154**
6155** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
6156** previously obtained from [sqlite3_value_dup()].  ^If V is a NULL pointer
6157** then sqlite3_value_free(V) is a harmless no-op.
6158*/
6159SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
6160SQLITE_API void sqlite3_value_free(sqlite3_value*);
6161
6162/*
6163** CAPI3REF: Obtain Aggregate Function Context
6164** METHOD: sqlite3_context
6165**
6166** Implementations of aggregate SQL functions use this
6167** routine to allocate memory for storing their state.
6168**
6169** ^The first time the sqlite3_aggregate_context(C,N) routine is called
6170** for a particular aggregate function, SQLite allocates
6171** N bytes of memory, zeroes out that memory, and returns a pointer
6172** to the new memory. ^On second and subsequent calls to
6173** sqlite3_aggregate_context() for the same aggregate function instance,
6174** the same buffer is returned.  Sqlite3_aggregate_context() is normally
6175** called once for each invocation of the xStep callback and then one
6176** last time when the xFinal callback is invoked.  ^(When no rows match
6177** an aggregate query, the xStep() callback of the aggregate function
6178** implementation is never called and xFinal() is called exactly once.
6179** In those cases, sqlite3_aggregate_context() might be called for the
6180** first time from within xFinal().)^
6181**
6182** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
6183** when first called if N is less than or equal to zero or if a memory
6184** allocation error occurs.
6185**
6186** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
6187** determined by the N parameter on first successful call.  Changing the
6188** value of N in any subsequent call to sqlite3_aggregate_context() within
6189** the same aggregate function instance will not resize the memory
6190** allocation.)^  Within the xFinal callback, it is customary to set
6191** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
6192** pointless memory allocations occur.
6193**
6194** ^SQLite automatically frees the memory allocated by
6195** sqlite3_aggregate_context() when the aggregate query concludes.
6196**
6197** The first parameter must be a copy of the
6198** [sqlite3_context | SQL function context] that is the first parameter
6199** to the xStep or xFinal callback routine that implements the aggregate
6200** function.
6201**
6202** This routine must be called from the same thread in which
6203** the aggregate SQL function is running.
6204*/
6205SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
6206
6207/*
6208** CAPI3REF: User Data For Functions
6209** METHOD: sqlite3_context
6210**
6211** ^The sqlite3_user_data() interface returns a copy of
6212** the pointer that was the pUserData parameter (the 5th parameter)
6213** of the [sqlite3_create_function()]
6214** and [sqlite3_create_function16()] routines that originally
6215** registered the application defined function.
6216**
6217** This routine must be called from the same thread in which
6218** the application-defined function is running.
6219*/
6220SQLITE_API void *sqlite3_user_data(sqlite3_context*);
6221
6222/*
6223** CAPI3REF: Database Connection For Functions
6224** METHOD: sqlite3_context
6225**
6226** ^The sqlite3_context_db_handle() interface returns a copy of
6227** the pointer to the [database connection] (the 1st parameter)
6228** of the [sqlite3_create_function()]
6229** and [sqlite3_create_function16()] routines that originally
6230** registered the application defined function.
6231*/
6232SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
6233
6234/*
6235** CAPI3REF: Function Auxiliary Data
6236** METHOD: sqlite3_context
6237**
6238** These functions may be used by (non-aggregate) SQL functions to
6239** associate auxiliary data with argument values. If the same argument
6240** value is passed to multiple invocations of the same SQL function during
6241** query execution, under some circumstances the associated auxiliary data
6242** might be preserved.  An example of where this might be useful is in a
6243** regular-expression matching function. The compiled version of the regular
6244** expression can be stored as auxiliary data associated with the pattern string.
6245** Then as long as the pattern string remains the same,
6246** the compiled regular expression can be reused on multiple
6247** invocations of the same function.
6248**
6249** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the auxiliary data
6250** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
6251** value to the application-defined function.  ^N is zero for the left-most
6252** function argument.  ^If there is no auxiliary data
6253** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
6254** returns a NULL pointer.
6255**
6256** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as auxiliary data for the
6257** N-th argument of the application-defined function.  ^Subsequent
6258** calls to sqlite3_get_auxdata(C,N) return P from the most recent
6259** sqlite3_set_auxdata(C,N,P,X) call if the auxiliary data is still valid or
6260** NULL if the auxiliary data has been discarded.
6261** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
6262** SQLite will invoke the destructor function X with parameter P exactly
6263** once, when the auxiliary data is discarded.
6264** SQLite is free to discard the auxiliary data at any time, including: <ul>
6265** <li> ^(when the corresponding function parameter changes)^, or
6266** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
6267**      SQL statement)^, or
6268** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
6269**       parameter)^, or
6270** <li> ^(during the original sqlite3_set_auxdata() call when a memory
6271**      allocation error occurs.)^
6272** <li> ^(during the original sqlite3_set_auxdata() call if the function
6273**      is evaluated during query planning instead of during query execution,
6274**      as sometimes happens with [SQLITE_ENABLE_STAT4].)^ </ul>
6275**
6276** Note the last two bullets in particular.  The destructor X in
6277** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
6278** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
6279** should be called near the end of the function implementation and the
6280** function implementation should not make any use of P after
6281** sqlite3_set_auxdata() has been called.  Furthermore, a call to
6282** sqlite3_get_auxdata() that occurs immediately after a corresponding call
6283** to sqlite3_set_auxdata() might still return NULL if an out-of-memory
6284** condition occurred during the sqlite3_set_auxdata() call or if the
6285** function is being evaluated during query planning rather than during
6286** query execution.
6287**
6288** ^(In practice, auxiliary data is preserved between function calls for
6289** function parameters that are compile-time constants, including literal
6290** values and [parameters] and expressions composed from the same.)^
6291**
6292** The value of the N parameter to these interfaces should be non-negative.
6293** Future enhancements may make use of negative N values to define new
6294** kinds of function caching behavior.
6295**
6296** These routines must be called from the same thread in which
6297** the SQL function is running.
6298**
6299** See also: [sqlite3_get_clientdata()] and [sqlite3_set_clientdata()].
6300*/
6301SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
6302SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
6303
6304/*
6305** CAPI3REF: Database Connection Client Data
6306** METHOD: sqlite3
6307**
6308** These functions are used to associate one or more named pointers
6309** with a [database connection].
6310** A call to sqlite3_set_clientdata(D,N,P,X) causes the pointer P
6311** to be attached to [database connection] D using name N.  Subsequent
6312** calls to sqlite3_get_clientdata(D,N) will return a copy of pointer P
6313** or a NULL pointer if there were no prior calls to
6314** sqlite3_set_clientdata() with the same values of D and N.
6315** Names are compared using strcmp() and are thus case sensitive.
6316**
6317** If P and X are both non-NULL, then the destructor X is invoked with
6318** argument P on the first of the following occurrences:
6319** <ul>
6320** <li> An out-of-memory error occurs during the call to
6321**      sqlite3_set_clientdata() which attempts to register pointer P.
6322** <li> A subsequent call to sqlite3_set_clientdata(D,N,P,X) is made
6323**      with the same D and N parameters.
6324** <li> The database connection closes.  SQLite does not make any guarantees
6325**      about the order in which destructors are called, only that all
6326**      destructors will be called exactly once at some point during the
6327**      database connection closing process.
6328** </ul>
6329**
6330** SQLite does not do anything with client data other than invoke
6331** destructors on the client data at the appropriate time.  The intended
6332** use for client data is to provide a mechanism for wrapper libraries
6333** to store additional information about an SQLite database connection.
6334**
6335** There is no limit (other than available memory) on the number of different
6336** client data pointers (with different names) that can be attached to a
6337** single database connection.  However, the implementation is optimized
6338** for the case of having only one or two different client data names.
6339** Applications and wrapper libraries are discouraged from using more than
6340** one client data name each.
6341**
6342** There is no way to enumerate the client data pointers
6343** associated with a database connection.  The N parameter can be thought
6344** of as a secret key such that only code that knows the secret key is able
6345** to access the associated data.
6346**
6347** Security Warning:  These interfaces should not be exposed in scripting
6348** languages or in other circumstances where it might be possible for an
6349** an attacker to invoke them.  Any agent that can invoke these interfaces
6350** can probably also take control of the process.
6351**
6352** Database connection client data is only available for SQLite
6353** version 3.44.0 ([dateof:3.44.0]) and later.
6354**
6355** See also: [sqlite3_set_auxdata()] and [sqlite3_get_auxdata()].
6356*/
6357SQLITE_API void *sqlite3_get_clientdata(sqlite3*,const char*);
6358SQLITE_API int sqlite3_set_clientdata(sqlite3*, const char*, void*, void(*)(void*));
6359
6360/*
6361** CAPI3REF: Constants Defining Special Destructor Behavior
6362**
6363** These are special values for the destructor that is passed in as the
6364** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
6365** argument is SQLITE_STATIC, it means that the content pointer is constant
6366** and will never change.  It does not need to be destroyed.  ^The
6367** SQLITE_TRANSIENT value means that the content will likely change in
6368** the near future and that SQLite should make its own private copy of
6369** the content before returning.
6370**
6371** The typedef is necessary to work around problems in certain
6372** C++ compilers.
6373*/
6374typedef void (*sqlite3_destructor_type)(void*);
6375#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
6376#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
6377
6378/*
6379** CAPI3REF: Setting The Result Of An SQL Function
6380** METHOD: sqlite3_context
6381**
6382** These routines are used by the xFunc or xFinal callbacks that
6383** implement SQL functions and aggregates.  See
6384** [sqlite3_create_function()] and [sqlite3_create_function16()]
6385** for additional information.
6386**
6387** These functions work very much like the [parameter binding] family of
6388** functions used to bind values to host parameters in prepared statements.
6389** Refer to the [SQL parameter] documentation for additional information.
6390**
6391** ^The sqlite3_result_blob() interface sets the result from
6392** an application-defined function to be the BLOB whose content is pointed
6393** to by the second parameter and which is N bytes long where N is the
6394** third parameter.
6395**
6396** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
6397** interfaces set the result of the application-defined function to be
6398** a BLOB containing all zero bytes and N bytes in size.
6399**
6400** ^The sqlite3_result_double() interface sets the result from
6401** an application-defined function to be a floating point value specified
6402** by its 2nd argument.
6403**
6404** ^The sqlite3_result_error() and sqlite3_result_error16() functions
6405** cause the implemented SQL function to throw an exception.
6406** ^SQLite uses the string pointed to by the
6407** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
6408** as the text of an error message.  ^SQLite interprets the error
6409** message string from sqlite3_result_error() as UTF-8. ^SQLite
6410** interprets the string from sqlite3_result_error16() as UTF-16 using
6411** the same [byte-order determination rules] as [sqlite3_bind_text16()].
6412** ^If the third parameter to sqlite3_result_error()
6413** or sqlite3_result_error16() is negative then SQLite takes as the error
6414** message all text up through the first zero character.
6415** ^If the third parameter to sqlite3_result_error() or
6416** sqlite3_result_error16() is non-negative then SQLite takes that many
6417** bytes (not characters) from the 2nd parameter as the error message.
6418** ^The sqlite3_result_error() and sqlite3_result_error16()
6419** routines make a private copy of the error message text before
6420** they return.  Hence, the calling function can deallocate or
6421** modify the text after they return without harm.
6422** ^The sqlite3_result_error_code() function changes the error code
6423** returned by SQLite as a result of an error in a function.  ^By default,
6424** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
6425** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
6426**
6427** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
6428** error indicating that a string or BLOB is too long to represent.
6429**
6430** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
6431** error indicating that a memory allocation failed.
6432**
6433** ^The sqlite3_result_int() interface sets the return value
6434** of the application-defined function to be the 32-bit signed integer
6435** value given in the 2nd argument.
6436** ^The sqlite3_result_int64() interface sets the return value
6437** of the application-defined function to be the 64-bit signed integer
6438** value given in the 2nd argument.
6439**
6440** ^The sqlite3_result_null() interface sets the return value
6441** of the application-defined function to be NULL.
6442**
6443** ^The sqlite3_result_text(), sqlite3_result_text16(),
6444** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
6445** set the return value of the application-defined function to be
6446** a text string which is represented as UTF-8, UTF-16 native byte order,
6447** UTF-16 little endian, or UTF-16 big endian, respectively.
6448** ^The sqlite3_result_text64() interface sets the return value of an
6449** application-defined function to be a text string in an encoding
6450** specified by the fifth (and last) parameter, which must be one
6451** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
6452** ^SQLite takes the text result from the application from
6453** the 2nd parameter of the sqlite3_result_text* interfaces.
6454** ^If the 3rd parameter to any of the sqlite3_result_text* interfaces
6455** other than sqlite3_result_text64() is negative, then SQLite computes
6456** the string length itself by searching the 2nd parameter for the first
6457** zero character.
6458** ^If the 3rd parameter to the sqlite3_result_text* interfaces
6459** is non-negative, then as many bytes (not characters) of the text
6460** pointed to by the 2nd parameter are taken as the application-defined
6461** function result.  If the 3rd parameter is non-negative, then it
6462** must be the byte offset into the string where the NUL terminator would
6463** appear if the string where NUL terminated.  If any NUL characters occur
6464** in the string at a byte offset that is less than the value of the 3rd
6465** parameter, then the resulting string will contain embedded NULs and the
6466** result of expressions operating on strings with embedded NULs is undefined.
6467** ^If the 4th parameter to the sqlite3_result_text* interfaces
6468** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
6469** function as the destructor on the text or BLOB result when it has
6470** finished using that result.
6471** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
6472** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
6473** assumes that the text or BLOB result is in constant space and does not
6474** copy the content of the parameter nor call a destructor on the content
6475** when it has finished using that result.
6476** ^If the 4th parameter to the sqlite3_result_text* interfaces
6477** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
6478** then SQLite makes a copy of the result into space obtained
6479** from [sqlite3_malloc()] before it returns.
6480**
6481** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and
6482** sqlite3_result_text16be() routines, and for sqlite3_result_text64()
6483** when the encoding is not UTF8, if the input UTF16 begins with a
6484** byte-order mark (BOM, U+FEFF) then the BOM is removed from the
6485** string and the rest of the string is interpreted according to the
6486** byte-order specified by the BOM.  ^The byte-order specified by
6487** the BOM at the beginning of the text overrides the byte-order
6488** specified by the interface procedure.  ^So, for example, if
6489** sqlite3_result_text16le() is invoked with text that begins
6490** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the
6491** first two bytes of input are skipped and the remaining input
6492** is interpreted as UTF16BE text.
6493**
6494** ^For UTF16 input text to the sqlite3_result_text16(),
6495** sqlite3_result_text16be(), sqlite3_result_text16le(), and
6496** sqlite3_result_text64() routines, if the text contains invalid
6497** UTF16 characters, the invalid characters might be converted
6498** into the unicode replacement character, U+FFFD.
6499**
6500** ^The sqlite3_result_value() interface sets the result of
6501** the application-defined function to be a copy of the
6502** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
6503** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
6504** so that the [sqlite3_value] specified in the parameter may change or
6505** be deallocated after sqlite3_result_value() returns without harm.
6506** ^A [protected sqlite3_value] object may always be used where an
6507** [unprotected sqlite3_value] object is required, so either
6508** kind of [sqlite3_value] object can be used with this interface.
6509**
6510** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
6511** SQL NULL value, just like [sqlite3_result_null(C)], except that it
6512** also associates the host-language pointer P or type T with that
6513** NULL value such that the pointer can be retrieved within an
6514** [application-defined SQL function] using [sqlite3_value_pointer()].
6515** ^If the D parameter is not NULL, then it is a pointer to a destructor
6516** for the P parameter.  ^SQLite invokes D with P as its only argument
6517** when SQLite is finished with P.  The T parameter should be a static
6518** string and preferably a string literal. The sqlite3_result_pointer()
6519** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
6520**
6521** If these routines are called from within the different thread
6522** than the one containing the application-defined function that received
6523** the [sqlite3_context] pointer, the results are undefined.
6524*/
6525SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
6526SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
6527                           sqlite3_uint64,void(*)(void*));
6528SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
6529SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
6530SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
6531SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
6532SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
6533SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
6534SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
6535SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
6536SQLITE_API void sqlite3_result_null(sqlite3_context*);
6537SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
6538SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
6539                           void(*)(void*), unsigned char encoding);
6540SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
6541SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
6542SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
6543SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
6544SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
6545SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
6546SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
6547
6548
6549/*
6550** CAPI3REF: Setting The Subtype Of An SQL Function
6551** METHOD: sqlite3_context
6552**
6553** The sqlite3_result_subtype(C,T) function causes the subtype of
6554** the result from the [application-defined SQL function] with
6555** [sqlite3_context] C to be the value T.  Only the lower 8 bits
6556** of the subtype T are preserved in current versions of SQLite;
6557** higher order bits are discarded.
6558** The number of subtype bytes preserved by SQLite might increase
6559** in future releases of SQLite.
6560**
6561** Every [application-defined SQL function] that invokes this interface
6562** should include the [SQLITE_RESULT_SUBTYPE] property in its
6563** text encoding argument when the SQL function is
6564** [sqlite3_create_function|registered].  If the [SQLITE_RESULT_SUBTYPE]
6565** property is omitted from the function that invokes sqlite3_result_subtype(),
6566** then in some cases the sqlite3_result_subtype() might fail to set
6567** the result subtype.
6568**
6569** If SQLite is compiled with -DSQLITE_STRICT_SUBTYPE=1, then any
6570** SQL function that invokes the sqlite3_result_subtype() interface
6571** and that does not have the SQLITE_RESULT_SUBTYPE property will raise
6572** an error.  Future versions of SQLite might enable -DSQLITE_STRICT_SUBTYPE=1
6573** by default.
6574*/
6575SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
6576
6577/*
6578** CAPI3REF: Define New Collating Sequences
6579** METHOD: sqlite3
6580**
6581** ^These functions add, remove, or modify a [collation] associated
6582** with the [database connection] specified as the first argument.
6583**
6584** ^The name of the collation is a UTF-8 string
6585** for sqlite3_create_collation() and sqlite3_create_collation_v2()
6586** and a UTF-16 string in native byte order for sqlite3_create_collation16().
6587** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
6588** considered to be the same name.
6589**
6590** ^(The third argument (eTextRep) must be one of the constants:
6591** <ul>
6592** <li> [SQLITE_UTF8],
6593** <li> [SQLITE_UTF16LE],
6594** <li> [SQLITE_UTF16BE],
6595** <li> [SQLITE_UTF16], or
6596** <li> [SQLITE_UTF16_ALIGNED].
6597** </ul>)^
6598** ^The eTextRep argument determines the encoding of strings passed
6599** to the collating function callback, xCompare.
6600** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
6601** force strings to be UTF16 with native byte order.
6602** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
6603** on an even byte address.
6604**
6605** ^The fourth argument, pArg, is an application data pointer that is passed
6606** through as the first argument to the collating function callback.
6607**
6608** ^The fifth argument, xCompare, is a pointer to the collating function.
6609** ^Multiple collating functions can be registered using the same name but
6610** with different eTextRep parameters and SQLite will use whichever
6611** function requires the least amount of data transformation.
6612** ^If the xCompare argument is NULL then the collating function is
6613** deleted.  ^When all collating functions having the same name are deleted,
6614** that collation is no longer usable.
6615**
6616** ^The collating function callback is invoked with a copy of the pArg
6617** application data pointer and with two strings in the encoding specified
6618** by the eTextRep argument.  The two integer parameters to the collating
6619** function callback are the length of the two strings, in bytes. The collating
6620** function must return an integer that is negative, zero, or positive
6621** if the first string is less than, equal to, or greater than the second,
6622** respectively.  A collating function must always return the same answer
6623** given the same inputs.  If two or more collating functions are registered
6624** to the same collation name (using different eTextRep values) then all
6625** must give an equivalent answer when invoked with equivalent strings.
6626** The collating function must obey the following properties for all
6627** strings A, B, and C:
6628**
6629** <ol>
6630** <li> If A==B then B==A.
6631** <li> If A==B and B==C then A==C.
6632** <li> If A&lt;B THEN B&gt;A.
6633** <li> If A&lt;B and B&lt;C then A&lt;C.
6634** </ol>
6635**
6636** If a collating function fails any of the above constraints and that
6637** collating function is registered and used, then the behavior of SQLite
6638** is undefined.
6639**
6640** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
6641** with the addition that the xDestroy callback is invoked on pArg when
6642** the collating function is deleted.
6643** ^Collating functions are deleted when they are overridden by later
6644** calls to the collation creation functions or when the
6645** [database connection] is closed using [sqlite3_close()].
6646**
6647** ^The xDestroy callback is <u>not</u> called if the
6648** sqlite3_create_collation_v2() function fails.  Applications that invoke
6649** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
6650** check the return code and dispose of the application data pointer
6651** themselves rather than expecting SQLite to deal with it for them.
6652** This is different from every other SQLite interface.  The inconsistency
6653** is unfortunate but cannot be changed without breaking backwards
6654** compatibility.
6655**
6656** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
6657*/
6658SQLITE_API int sqlite3_create_collation(
6659  sqlite3*,
6660  const char *zName,
6661  int eTextRep,
6662  void *pArg,
6663  int(*xCompare)(void*,int,const void*,int,const void*)
6664);
6665SQLITE_API int sqlite3_create_collation_v2(
6666  sqlite3*,
6667  const char *zName,
6668  int eTextRep,
6669  void *pArg,
6670  int(*xCompare)(void*,int,const void*,int,const void*),
6671  void(*xDestroy)(void*)
6672);
6673SQLITE_API int sqlite3_create_collation16(
6674  sqlite3*,
6675  const void *zName,
6676  int eTextRep,
6677  void *pArg,
6678  int(*xCompare)(void*,int,const void*,int,const void*)
6679);
6680
6681/*
6682** CAPI3REF: Collation Needed Callbacks
6683** METHOD: sqlite3
6684**
6685** ^To avoid having to register all collation sequences before a database
6686** can be used, a single callback function may be registered with the
6687** [database connection] to be invoked whenever an undefined collation
6688** sequence is required.
6689**
6690** ^If the function is registered using the sqlite3_collation_needed() API,
6691** then it is passed the names of undefined collation sequences as strings
6692** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
6693** the names are passed as UTF-16 in machine native byte order.
6694** ^A call to either function replaces the existing collation-needed callback.
6695**
6696** ^(When the callback is invoked, the first argument passed is a copy
6697** of the second argument to sqlite3_collation_needed() or
6698** sqlite3_collation_needed16().  The second argument is the database
6699** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
6700** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
6701** sequence function required.  The fourth parameter is the name of the
6702** required collation sequence.)^
6703**
6704** The callback function should register the desired collation using
6705** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
6706** [sqlite3_create_collation_v2()].
6707*/
6708SQLITE_API int sqlite3_collation_needed(
6709  sqlite3*,
6710  void*,
6711  void(*)(void*,sqlite3*,int eTextRep,const char*)
6712);
6713SQLITE_API int sqlite3_collation_needed16(
6714  sqlite3*,
6715  void*,
6716  void(*)(void*,sqlite3*,int eTextRep,const void*)
6717);
6718
6719#ifdef SQLITE_ENABLE_CEROD
6720/*
6721** Specify the activation key for a CEROD database.  Unless
6722** activated, none of the CEROD routines will work.
6723*/
6724SQLITE_API void sqlite3_activate_cerod(
6725  const char *zPassPhrase        /* Activation phrase */
6726);
6727#endif
6728
6729/*
6730** CAPI3REF: Suspend Execution For A Short Time
6731**
6732** The sqlite3_sleep() function causes the current thread to suspend execution
6733** for at least a number of milliseconds specified in its parameter.
6734**
6735** If the operating system does not support sleep requests with
6736** millisecond time resolution, then the time will be rounded up to
6737** the nearest second. The number of milliseconds of sleep actually
6738** requested from the operating system is returned.
6739**
6740** ^SQLite implements this interface by calling the xSleep()
6741** method of the default [sqlite3_vfs] object.  If the xSleep() method
6742** of the default VFS is not implemented correctly, or not implemented at
6743** all, then the behavior of sqlite3_sleep() may deviate from the description
6744** in the previous paragraphs.
6745**
6746** If a negative argument is passed to sqlite3_sleep() the results vary by
6747** VFS and operating system.  Some system treat a negative argument as an
6748** instruction to sleep forever.  Others understand it to mean do not sleep
6749** at all. ^In SQLite version 3.42.0 and later, a negative
6750** argument passed into sqlite3_sleep() is changed to zero before it is relayed
6751** down into the xSleep method of the VFS.
6752*/
6753SQLITE_API int sqlite3_sleep(int);
6754
6755/*
6756** CAPI3REF: Name Of The Folder Holding Temporary Files
6757**
6758** ^(If this global variable is made to point to a string which is
6759** the name of a folder (a.k.a. directory), then all temporary files
6760** created by SQLite when using a built-in [sqlite3_vfs | VFS]
6761** will be placed in that directory.)^  ^If this variable
6762** is a NULL pointer, then SQLite performs a search for an appropriate
6763** temporary file directory.
6764**
6765** Applications are strongly discouraged from using this global variable.
6766** It is required to set a temporary folder on Windows Runtime (WinRT).
6767** But for all other platforms, it is highly recommended that applications
6768** neither read nor write this variable.  This global variable is a relic
6769** that exists for backwards compatibility of legacy applications and should
6770** be avoided in new projects.
6771**
6772** It is not safe to read or modify this variable in more than one
6773** thread at a time.  It is not safe to read or modify this variable
6774** if a [database connection] is being used at the same time in a separate
6775** thread.
6776** It is intended that this variable be set once
6777** as part of process initialization and before any SQLite interface
6778** routines have been called and that this variable remain unchanged
6779** thereafter.
6780**
6781** ^The [temp_store_directory pragma] may modify this variable and cause
6782** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
6783** the [temp_store_directory pragma] always assumes that any string
6784** that this variable points to is held in memory obtained from
6785** [sqlite3_malloc] and the pragma may attempt to free that memory
6786** using [sqlite3_free].
6787** Hence, if this variable is modified directly, either it should be
6788** made NULL or made to point to memory obtained from [sqlite3_malloc]
6789** or else the use of the [temp_store_directory pragma] should be avoided.
6790** Except when requested by the [temp_store_directory pragma], SQLite
6791** does not free the memory that sqlite3_temp_directory points to.  If
6792** the application wants that memory to be freed, it must do
6793** so itself, taking care to only do so after all [database connection]
6794** objects have been destroyed.
6795**
6796** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
6797** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
6798** features that require the use of temporary files may fail.  Here is an
6799** example of how to do this using C++ with the Windows Runtime:
6800**
6801** <blockquote><pre>
6802** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
6803** &nbsp;     TemporaryFolder->Path->Data();
6804** char zPathBuf&#91;MAX_PATH + 1&#93;;
6805** memset(zPathBuf, 0, sizeof(zPathBuf));
6806** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
6807** &nbsp;     NULL, NULL);
6808** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
6809** </pre></blockquote>
6810*/
6811SQLITE_API char *sqlite3_temp_directory;
6812
6813/*
6814** CAPI3REF: Name Of The Folder Holding Database Files
6815**
6816** ^(If this global variable is made to point to a string which is
6817** the name of a folder (a.k.a. directory), then all database files
6818** specified with a relative pathname and created or accessed by
6819** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
6820** to be relative to that directory.)^ ^If this variable is a NULL
6821** pointer, then SQLite assumes that all database files specified
6822** with a relative pathname are relative to the current directory
6823** for the process.  Only the windows VFS makes use of this global
6824** variable; it is ignored by the unix VFS.
6825**
6826** Changing the value of this variable while a database connection is
6827** open can result in a corrupt database.
6828**
6829** It is not safe to read or modify this variable in more than one
6830** thread at a time.  It is not safe to read or modify this variable
6831** if a [database connection] is being used at the same time in a separate
6832** thread.
6833** It is intended that this variable be set once
6834** as part of process initialization and before any SQLite interface
6835** routines have been called and that this variable remain unchanged
6836** thereafter.
6837**
6838** ^The [data_store_directory pragma] may modify this variable and cause
6839** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
6840** the [data_store_directory pragma] always assumes that any string
6841** that this variable points to is held in memory obtained from
6842** [sqlite3_malloc] and the pragma may attempt to free that memory
6843** using [sqlite3_free].
6844** Hence, if this variable is modified directly, either it should be
6845** made NULL or made to point to memory obtained from [sqlite3_malloc]
6846** or else the use of the [data_store_directory pragma] should be avoided.
6847*/
6848SQLITE_API char *sqlite3_data_directory;
6849
6850/*
6851** CAPI3REF: Win32 Specific Interface
6852**
6853** These interfaces are available only on Windows.  The
6854** [sqlite3_win32_set_directory] interface is used to set the value associated
6855** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
6856** zValue, depending on the value of the type parameter.  The zValue parameter
6857** should be NULL to cause the previous value to be freed via [sqlite3_free];
6858** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
6859** prior to being used.  The [sqlite3_win32_set_directory] interface returns
6860** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
6861** or [SQLITE_NOMEM] if memory could not be allocated.  The value of the
6862** [sqlite3_data_directory] variable is intended to act as a replacement for
6863** the current directory on the sub-platforms of Win32 where that concept is
6864** not present, e.g. WinRT and UWP.  The [sqlite3_win32_set_directory8] and
6865** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
6866** sqlite3_win32_set_directory interface except the string parameter must be
6867** UTF-8 or UTF-16, respectively.
6868*/
6869SQLITE_API int sqlite3_win32_set_directory(
6870  unsigned long type, /* Identifier for directory being set or reset */
6871  void *zValue        /* New value for directory being set or reset */
6872);
6873SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
6874SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
6875
6876/*
6877** CAPI3REF: Win32 Directory Types
6878**
6879** These macros are only available on Windows.  They define the allowed values
6880** for the type argument to the [sqlite3_win32_set_directory] interface.
6881*/
6882#define SQLITE_WIN32_DATA_DIRECTORY_TYPE  1
6883#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE  2
6884
6885/*
6886** CAPI3REF: Test For Auto-Commit Mode
6887** KEYWORDS: {autocommit mode}
6888** METHOD: sqlite3
6889**
6890** ^The sqlite3_get_autocommit() interface returns non-zero or
6891** zero if the given database connection is or is not in autocommit mode,
6892** respectively.  ^Autocommit mode is on by default.
6893** ^Autocommit mode is disabled by a [BEGIN] statement.
6894** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
6895**
6896** If certain kinds of errors occur on a statement within a multi-statement
6897** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
6898** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
6899** transaction might be rolled back automatically.  The only way to
6900** find out whether SQLite automatically rolled back the transaction after
6901** an error is to use this function.
6902**
6903** If another thread changes the autocommit status of the database
6904** connection while this routine is running, then the return value
6905** is undefined.
6906*/
6907SQLITE_API int sqlite3_get_autocommit(sqlite3*);
6908
6909/*
6910** CAPI3REF: Find The Database Handle Of A Prepared Statement
6911** METHOD: sqlite3_stmt
6912**
6913** ^The sqlite3_db_handle interface returns the [database connection] handle
6914** to which a [prepared statement] belongs.  ^The [database connection]
6915** returned by sqlite3_db_handle is the same [database connection]
6916** that was the first argument
6917** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
6918** create the statement in the first place.
6919*/
6920SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
6921
6922/*
6923** CAPI3REF: Return The Schema Name For A Database Connection
6924** METHOD: sqlite3
6925**
6926** ^The sqlite3_db_name(D,N) interface returns a pointer to the schema name
6927** for the N-th database on database connection D, or a NULL pointer of N is
6928** out of range.  An N value of 0 means the main database file.  An N of 1 is
6929** the "temp" schema.  Larger values of N correspond to various ATTACH-ed
6930** databases.
6931**
6932** Space to hold the string that is returned by sqlite3_db_name() is managed
6933** by SQLite itself.  The string might be deallocated by any operation that
6934** changes the schema, including [ATTACH] or [DETACH] or calls to
6935** [sqlite3_serialize()] or [sqlite3_deserialize()], even operations that
6936** occur on a different thread.  Applications that need to
6937** remember the string long-term should make their own copy.  Applications that
6938** are accessing the same database connection simultaneously on multiple
6939** threads should mutex-protect calls to this API and should make their own
6940** private copy of the result prior to releasing the mutex.
6941*/
6942SQLITE_API const char *sqlite3_db_name(sqlite3 *db, int N);
6943
6944/*
6945** CAPI3REF: Return The Filename For A Database Connection
6946** METHOD: sqlite3
6947**
6948** ^The sqlite3_db_filename(D,N) interface returns a pointer to the filename
6949** associated with database N of connection D.
6950** ^If there is no attached database N on the database
6951** connection D, or if database N is a temporary or in-memory database, then
6952** this function will return either a NULL pointer or an empty string.
6953**
6954** ^The string value returned by this routine is owned and managed by
6955** the database connection.  ^The value will be valid until the database N
6956** is [DETACH]-ed or until the database connection closes.
6957**
6958** ^The filename returned by this function is the output of the
6959** xFullPathname method of the [VFS].  ^In other words, the filename
6960** will be an absolute pathname, even if the filename used
6961** to open the database originally was a URI or relative pathname.
6962**
6963** If the filename pointer returned by this routine is not NULL, then it
6964** can be used as the filename input parameter to these routines:
6965** <ul>
6966** <li> [sqlite3_uri_parameter()]
6967** <li> [sqlite3_uri_boolean()]
6968** <li> [sqlite3_uri_int64()]
6969** <li> [sqlite3_filename_database()]
6970** <li> [sqlite3_filename_journal()]
6971** <li> [sqlite3_filename_wal()]
6972** </ul>
6973*/
6974SQLITE_API sqlite3_filename sqlite3_db_filename(sqlite3 *db, const char *zDbName);
6975
6976/*
6977** CAPI3REF: Determine if a database is read-only
6978** METHOD: sqlite3
6979**
6980** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
6981** of connection D is read-only, 0 if it is read/write, or -1 if N is not
6982** the name of a database on connection D.
6983*/
6984SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
6985
6986/*
6987** CAPI3REF: Determine the transaction state of a database
6988** METHOD: sqlite3
6989**
6990** ^The sqlite3_txn_state(D,S) interface returns the current
6991** [transaction state] of schema S in database connection D.  ^If S is NULL,
6992** then the highest transaction state of any schema on database connection D
6993** is returned.  Transaction states are (in order of lowest to highest):
6994** <ol>
6995** <li value="0"> SQLITE_TXN_NONE
6996** <li value="1"> SQLITE_TXN_READ
6997** <li value="2"> SQLITE_TXN_WRITE
6998** </ol>
6999** ^If the S argument to sqlite3_txn_state(D,S) is not the name of
7000** a valid schema, then -1 is returned.
7001*/
7002SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);
7003
7004/*
7005** CAPI3REF: Allowed return values from sqlite3_txn_state()
7006** KEYWORDS: {transaction state}
7007**
7008** These constants define the current transaction state of a database file.
7009** ^The [sqlite3_txn_state(D,S)] interface returns one of these
7010** constants in order to describe the transaction state of schema S
7011** in [database connection] D.
7012**
7013** <dl>
7014** [[SQLITE_TXN_NONE]] <dt>SQLITE_TXN_NONE</dt>
7015** <dd>The SQLITE_TXN_NONE state means that no transaction is currently
7016** pending.</dd>
7017**
7018** [[SQLITE_TXN_READ]] <dt>SQLITE_TXN_READ</dt>
7019** <dd>The SQLITE_TXN_READ state means that the database is currently
7020** in a read transaction.  Content has been read from the database file
7021** but nothing in the database file has changed.  The transaction state
7022** will advanced to SQLITE_TXN_WRITE if any changes occur and there are
7023** no other conflicting concurrent write transactions.  The transaction
7024** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or
7025** [COMMIT].</dd>
7026**
7027** [[SQLITE_TXN_WRITE]] <dt>SQLITE_TXN_WRITE</dt>
7028** <dd>The SQLITE_TXN_WRITE state means that the database is currently
7029** in a write transaction.  Content has been written to the database file
7030** but has not yet committed.  The transaction state will change to
7031** to SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd>
7032*/
7033#define SQLITE_TXN_NONE  0
7034#define SQLITE_TXN_READ  1
7035#define SQLITE_TXN_WRITE 2
7036
7037/*
7038** CAPI3REF: Find the next prepared statement
7039** METHOD: sqlite3
7040**
7041** ^This interface returns a pointer to the next [prepared statement] after
7042** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
7043** then this interface returns a pointer to the first prepared statement
7044** associated with the database connection pDb.  ^If no prepared statement
7045** satisfies the conditions of this routine, it returns NULL.
7046**
7047** The [database connection] pointer D in a call to
7048** [sqlite3_next_stmt(D,S)] must refer to an open database
7049** connection and in particular must not be a NULL pointer.
7050*/
7051SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
7052
7053/*
7054** CAPI3REF: Commit And Rollback Notification Callbacks
7055** METHOD: sqlite3
7056**
7057** ^The sqlite3_commit_hook() interface registers a callback
7058** function to be invoked whenever a transaction is [COMMIT | committed].
7059** ^Any callback set by a previous call to sqlite3_commit_hook()
7060** for the same database connection is overridden.
7061** ^The sqlite3_rollback_hook() interface registers a callback
7062** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
7063** ^Any callback set by a previous call to sqlite3_rollback_hook()
7064** for the same database connection is overridden.
7065** ^The pArg argument is passed through to the callback.
7066** ^If the callback on a commit hook function returns non-zero,
7067** then the commit is converted into a rollback.
7068**
7069** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
7070** return the P argument from the previous call of the same function
7071** on the same [database connection] D, or NULL for
7072** the first call for each function on D.
7073**
7074** The commit and rollback hook callbacks are not reentrant.
7075** The callback implementation must not do anything that will modify
7076** the database connection that invoked the callback.  Any actions
7077** to modify the database connection must be deferred until after the
7078** completion of the [sqlite3_step()] call that triggered the commit
7079** or rollback hook in the first place.
7080** Note that running any other SQL statements, including SELECT statements,
7081** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
7082** the database connections for the meaning of "modify" in this paragraph.
7083**
7084** ^Registering a NULL function disables the callback.
7085**
7086** ^When the commit hook callback routine returns zero, the [COMMIT]
7087** operation is allowed to continue normally.  ^If the commit hook
7088** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
7089** ^The rollback hook is invoked on a rollback that results from a commit
7090** hook returning non-zero, just as it would be with any other rollback.
7091**
7092** ^For the purposes of this API, a transaction is said to have been
7093** rolled back if an explicit "ROLLBACK" statement is executed, or
7094** an error or constraint causes an implicit rollback to occur.
7095** ^The rollback callback is not invoked if a transaction is
7096** automatically rolled back because the database connection is closed.
7097**
7098** See also the [sqlite3_update_hook()] interface.
7099*/
7100SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
7101SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
7102
7103/*
7104** CAPI3REF: Autovacuum Compaction Amount Callback
7105** METHOD: sqlite3
7106**
7107** ^The sqlite3_autovacuum_pages(D,C,P,X) interface registers a callback
7108** function C that is invoked prior to each autovacuum of the database
7109** file.  ^The callback is passed a copy of the generic data pointer (P),
7110** the schema-name of the attached database that is being autovacuumed,
7111** the size of the database file in pages, the number of free pages,
7112** and the number of bytes per page, respectively.  The callback should
7113** return the number of free pages that should be removed by the
7114** autovacuum.  ^If the callback returns zero, then no autovacuum happens.
7115** ^If the value returned is greater than or equal to the number of
7116** free pages, then a complete autovacuum happens.
7117**
7118** <p>^If there are multiple ATTACH-ed database files that are being
7119** modified as part of a transaction commit, then the autovacuum pages
7120** callback is invoked separately for each file.
7121**
7122** <p><b>The callback is not reentrant.</b> The callback function should
7123** not attempt to invoke any other SQLite interface.  If it does, bad
7124** things may happen, including segmentation faults and corrupt database
7125** files.  The callback function should be a simple function that
7126** does some arithmetic on its input parameters and returns a result.
7127**
7128** ^The X parameter to sqlite3_autovacuum_pages(D,C,P,X) is an optional
7129** destructor for the P parameter.  ^If X is not NULL, then X(P) is
7130** invoked whenever the database connection closes or when the callback
7131** is overwritten by another invocation of sqlite3_autovacuum_pages().
7132**
7133** <p>^There is only one autovacuum pages callback per database connection.
7134** ^Each call to the sqlite3_autovacuum_pages() interface overrides all
7135** previous invocations for that database connection.  ^If the callback
7136** argument (C) to sqlite3_autovacuum_pages(D,C,P,X) is a NULL pointer,
7137** then the autovacuum steps callback is canceled.  The return value
7138** from sqlite3_autovacuum_pages() is normally SQLITE_OK, but might
7139** be some other error code if something goes wrong.  The current
7140** implementation will only return SQLITE_OK or SQLITE_MISUSE, but other
7141** return codes might be added in future releases.
7142**
7143** <p>If no autovacuum pages callback is specified (the usual case) or
7144** a NULL pointer is provided for the callback,
7145** then the default behavior is to vacuum all free pages.  So, in other
7146** words, the default behavior is the same as if the callback function
7147** were something like this:
7148**
7149** <blockquote><pre>
7150** &nbsp;   unsigned int demonstration_autovac_pages_callback(
7151** &nbsp;     void *pClientData,
7152** &nbsp;     const char *zSchema,
7153** &nbsp;     unsigned int nDbPage,
7154** &nbsp;     unsigned int nFreePage,
7155** &nbsp;     unsigned int nBytePerPage
7156** &nbsp;   ){
7157** &nbsp;     return nFreePage;
7158** &nbsp;   }
7159** </pre></blockquote>
7160*/
7161SQLITE_API int sqlite3_autovacuum_pages(
7162  sqlite3 *db,
7163  unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int),
7164  void*,
7165  void(*)(void*)
7166);
7167
7168
7169/*
7170** CAPI3REF: Data Change Notification Callbacks
7171** METHOD: sqlite3
7172**
7173** ^The sqlite3_update_hook() interface registers a callback function
7174** with the [database connection] identified by the first argument
7175** to be invoked whenever a row is updated, inserted or deleted in
7176** a [rowid table].
7177** ^Any callback set by a previous call to this function
7178** for the same database connection is overridden.
7179**
7180** ^The second argument is a pointer to the function to invoke when a
7181** row is updated, inserted or deleted in a rowid table.
7182** ^The first argument to the callback is a copy of the third argument
7183** to sqlite3_update_hook().
7184** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
7185** or [SQLITE_UPDATE], depending on the operation that caused the callback
7186** to be invoked.
7187** ^The third and fourth arguments to the callback contain pointers to the
7188** database and table name containing the affected row.
7189** ^The final callback parameter is the [rowid] of the row.
7190** ^In the case of an update, this is the [rowid] after the update takes place.
7191**
7192** ^(The update hook is not invoked when internal system tables are
7193** modified (i.e. sqlite_sequence).)^
7194** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
7195**
7196** ^In the current implementation, the update hook
7197** is not invoked when conflicting rows are deleted because of an
7198** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
7199** invoked when rows are deleted using the [truncate optimization].
7200** The exceptions defined in this paragraph might change in a future
7201** release of SQLite.
7202**
7203** Whether the update hook is invoked before or after the
7204** corresponding change is currently unspecified and may differ
7205** depending on the type of change. Do not rely on the order of the
7206** hook call with regards to the final result of the operation which
7207** triggers the hook.
7208**
7209** The update hook implementation must not do anything that will modify
7210** the database connection that invoked the update hook.  Any actions
7211** to modify the database connection must be deferred until after the
7212** completion of the [sqlite3_step()] call that triggered the update hook.
7213** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
7214** database connections for the meaning of "modify" in this paragraph.
7215**
7216** ^The sqlite3_update_hook(D,C,P) function
7217** returns the P argument from the previous call
7218** on the same [database connection] D, or NULL for
7219** the first call on D.
7220**
7221** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
7222** and [sqlite3_preupdate_hook()] interfaces.
7223*/
7224SQLITE_API void *sqlite3_update_hook(
7225  sqlite3*,
7226  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
7227  void*
7228);
7229
7230/*
7231** CAPI3REF: Enable Or Disable Shared Pager Cache
7232**
7233** ^(This routine enables or disables the sharing of the database cache
7234** and schema data structures between [database connection | connections]
7235** to the same database. Sharing is enabled if the argument is true
7236** and disabled if the argument is false.)^
7237**
7238** This interface is omitted if SQLite is compiled with
7239** [-DSQLITE_OMIT_SHARED_CACHE].  The [-DSQLITE_OMIT_SHARED_CACHE]
7240** compile-time option is recommended because the
7241** [use of shared cache mode is discouraged].
7242**
7243** ^Cache sharing is enabled and disabled for an entire process.
7244** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
7245** In prior versions of SQLite,
7246** sharing was enabled or disabled for each thread separately.
7247**
7248** ^(The cache sharing mode set by this interface effects all subsequent
7249** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
7250** Existing database connections continue to use the sharing mode
7251** that was in effect at the time they were opened.)^
7252**
7253** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
7254** successfully.  An [error code] is returned otherwise.)^
7255**
7256** ^Shared cache is disabled by default. It is recommended that it stay
7257** that way.  In other words, do not use this routine.  This interface
7258** continues to be provided for historical compatibility, but its use is
7259** discouraged.  Any use of shared cache is discouraged.  If shared cache
7260** must be used, it is recommended that shared cache only be enabled for
7261** individual database connections using the [sqlite3_open_v2()] interface
7262** with the [SQLITE_OPEN_SHAREDCACHE] flag.
7263**
7264** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
7265** and will always return SQLITE_MISUSE. On those systems,
7266** shared cache mode should be enabled per-database connection via
7267** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
7268**
7269** This interface is threadsafe on processors where writing a
7270** 32-bit integer is atomic.
7271**
7272** See Also:  [SQLite Shared-Cache Mode]
7273*/
7274SQLITE_API int sqlite3_enable_shared_cache(int);
7275
7276/*
7277** CAPI3REF: Attempt To Free Heap Memory
7278**
7279** ^The sqlite3_release_memory() interface attempts to free N bytes
7280** of heap memory by deallocating non-essential memory allocations
7281** held by the database library.   Memory used to cache database
7282** pages to improve performance is an example of non-essential memory.
7283** ^sqlite3_release_memory() returns the number of bytes actually freed,
7284** which might be more or less than the amount requested.
7285** ^The sqlite3_release_memory() routine is a no-op returning zero
7286** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
7287**
7288** See also: [sqlite3_db_release_memory()]
7289*/
7290SQLITE_API int sqlite3_release_memory(int);
7291
7292/*
7293** CAPI3REF: Free Memory Used By A Database Connection
7294** METHOD: sqlite3
7295**
7296** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
7297** memory as possible from database connection D. Unlike the
7298** [sqlite3_release_memory()] interface, this interface is in effect even
7299** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
7300** omitted.
7301**
7302** See also: [sqlite3_release_memory()]
7303*/
7304SQLITE_API int sqlite3_db_release_memory(sqlite3*);
7305
7306/*
7307** CAPI3REF: Impose A Limit On Heap Size
7308**
7309** These interfaces impose limits on the amount of heap memory that will be
7310** by all database connections within a single process.
7311**
7312** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
7313** soft limit on the amount of heap memory that may be allocated by SQLite.
7314** ^SQLite strives to keep heap memory utilization below the soft heap
7315** limit by reducing the number of pages held in the page cache
7316** as heap memory usages approaches the limit.
7317** ^The soft heap limit is "soft" because even though SQLite strives to stay
7318** below the limit, it will exceed the limit rather than generate
7319** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
7320** is advisory only.
7321**
7322** ^The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of
7323** N bytes on the amount of memory that will be allocated.  ^The
7324** sqlite3_hard_heap_limit64(N) interface is similar to
7325** sqlite3_soft_heap_limit64(N) except that memory allocations will fail
7326** when the hard heap limit is reached.
7327**
7328** ^The return value from both sqlite3_soft_heap_limit64() and
7329** sqlite3_hard_heap_limit64() is the size of
7330** the heap limit prior to the call, or negative in the case of an
7331** error.  ^If the argument N is negative
7332** then no change is made to the heap limit.  Hence, the current
7333** size of heap limits can be determined by invoking
7334** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).
7335**
7336** ^Setting the heap limits to zero disables the heap limiter mechanism.
7337**
7338** ^The soft heap limit may not be greater than the hard heap limit.
7339** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N)
7340** is invoked with a value of N that is greater than the hard heap limit,
7341** the soft heap limit is set to the value of the hard heap limit.
7342** ^The soft heap limit is automatically enabled whenever the hard heap
7343** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and
7344** the soft heap limit is outside the range of 1..N, then the soft heap
7345** limit is set to N.  ^Invoking sqlite3_soft_heap_limit64(0) when the
7346** hard heap limit is enabled makes the soft heap limit equal to the
7347** hard heap limit.
7348**
7349** The memory allocation limits can also be adjusted using
7350** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit].
7351**
7352** ^(The heap limits are not enforced in the current implementation
7353** if one or more of following conditions are true:
7354**
7355** <ul>
7356** <li> The limit value is set to zero.
7357** <li> Memory accounting is disabled using a combination of the
7358**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
7359**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
7360** <li> An alternative page cache implementation is specified using
7361**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
7362** <li> The page cache allocates from its own memory pool supplied
7363**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
7364**      from the heap.
7365** </ul>)^
7366**
7367** The circumstances under which SQLite will enforce the heap limits may
7368** changes in future releases of SQLite.
7369*/
7370SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
7371SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N);
7372
7373/*
7374** CAPI3REF: Deprecated Soft Heap Limit Interface
7375** DEPRECATED
7376**
7377** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
7378** interface.  This routine is provided for historical compatibility
7379** only.  All new applications should use the
7380** [sqlite3_soft_heap_limit64()] interface rather than this one.
7381*/
7382SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
7383
7384
7385/*
7386** CAPI3REF: Extract Metadata About A Column Of A Table
7387** METHOD: sqlite3
7388**
7389** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
7390** information about column C of table T in database D
7391** on [database connection] X.)^  ^The sqlite3_table_column_metadata()
7392** interface returns SQLITE_OK and fills in the non-NULL pointers in
7393** the final five arguments with appropriate values if the specified
7394** column exists.  ^The sqlite3_table_column_metadata() interface returns
7395** SQLITE_ERROR if the specified column does not exist.
7396** ^If the column-name parameter to sqlite3_table_column_metadata() is a
7397** NULL pointer, then this routine simply checks for the existence of the
7398** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
7399** does not.  If the table name parameter T in a call to
7400** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
7401** undefined behavior.
7402**
7403** ^The column is identified by the second, third and fourth parameters to
7404** this function. ^(The second parameter is either the name of the database
7405** (i.e. "main", "temp", or an attached database) containing the specified
7406** table or NULL.)^ ^If it is NULL, then all attached databases are searched
7407** for the table using the same algorithm used by the database engine to
7408** resolve unqualified table references.
7409**
7410** ^The third and fourth parameters to this function are the table and column
7411** name of the desired column, respectively.
7412**
7413** ^Metadata is returned by writing to the memory locations passed as the 5th
7414** and subsequent parameters to this function. ^Any of these arguments may be
7415** NULL, in which case the corresponding element of metadata is omitted.
7416**
7417** ^(<blockquote>
7418** <table border="1">
7419** <tr><th> Parameter <th> Output<br>Type <th>  Description
7420**
7421** <tr><td> 5th <td> const char* <td> Data type
7422** <tr><td> 6th <td> const char* <td> Name of default collation sequence
7423** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
7424** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
7425** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
7426** </table>
7427** </blockquote>)^
7428**
7429** ^The memory pointed to by the character pointers returned for the
7430** declaration type and collation sequence is valid until the next
7431** call to any SQLite API function.
7432**
7433** ^If the specified table is actually a view, an [error code] is returned.
7434**
7435** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
7436** is not a [WITHOUT ROWID] table and an
7437** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
7438** parameters are set for the explicitly declared column. ^(If there is no
7439** [INTEGER PRIMARY KEY] column, then the outputs
7440** for the [rowid] are set as follows:
7441**
7442** <pre>
7443**     data type: "INTEGER"
7444**     collation sequence: "BINARY"
7445**     not null: 0
7446**     primary key: 1
7447**     auto increment: 0
7448** </pre>)^
7449**
7450** ^This function causes all database schemas to be read from disk and
7451** parsed, if that has not already been done, and returns an error if
7452** any errors are encountered while loading the schema.
7453*/
7454SQLITE_API int sqlite3_table_column_metadata(
7455  sqlite3 *db,                /* Connection handle */
7456  const char *zDbName,        /* Database name or NULL */
7457  const char *zTableName,     /* Table name */
7458  const char *zColumnName,    /* Column name */
7459  char const **pzDataType,    /* OUTPUT: Declared data type */
7460  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
7461  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
7462  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
7463  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
7464);
7465
7466/*
7467** CAPI3REF: Load An Extension
7468** METHOD: sqlite3
7469**
7470** ^This interface loads an SQLite extension library from the named file.
7471**
7472** ^The sqlite3_load_extension() interface attempts to load an
7473** [SQLite extension] library contained in the file zFile.  If
7474** the file cannot be loaded directly, attempts are made to load
7475** with various operating-system specific extensions added.
7476** So for example, if "samplelib" cannot be loaded, then names like
7477** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
7478** be tried also.
7479**
7480** ^The entry point is zProc.
7481** ^(zProc may be 0, in which case SQLite will try to come up with an
7482** entry point name on its own.  It first tries "sqlite3_extension_init".
7483** If that does not work, it constructs a name "sqlite3_X_init" where the
7484** X is consists of the lower-case equivalent of all ASCII alphabetic
7485** characters in the filename from the last "/" to the first following
7486** "." and omitting any initial "lib".)^
7487** ^The sqlite3_load_extension() interface returns
7488** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
7489** ^If an error occurs and pzErrMsg is not 0, then the
7490** [sqlite3_load_extension()] interface shall attempt to
7491** fill *pzErrMsg with error message text stored in memory
7492** obtained from [sqlite3_malloc()]. The calling function
7493** should free this memory by calling [sqlite3_free()].
7494**
7495** ^Extension loading must be enabled using
7496** [sqlite3_enable_load_extension()] or
7497** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
7498** prior to calling this API,
7499** otherwise an error will be returned.
7500**
7501** <b>Security warning:</b> It is recommended that the
7502** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
7503** interface.  The use of the [sqlite3_enable_load_extension()] interface
7504** should be avoided.  This will keep the SQL function [load_extension()]
7505** disabled and prevent SQL injections from giving attackers
7506** access to extension loading capabilities.
7507**
7508** See also the [load_extension() SQL function].
7509*/
7510SQLITE_API int sqlite3_load_extension(
7511  sqlite3 *db,          /* Load the extension into this database connection */
7512  const char *zFile,    /* Name of the shared library containing extension */
7513  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
7514  char **pzErrMsg       /* Put error message here if not 0 */
7515);
7516
7517/*
7518** CAPI3REF: Enable Or Disable Extension Loading
7519** METHOD: sqlite3
7520**
7521** ^So as not to open security holes in older applications that are
7522** unprepared to deal with [extension loading], and as a means of disabling
7523** [extension loading] while evaluating user-entered SQL, the following API
7524** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
7525**
7526** ^Extension loading is off by default.
7527** ^Call the sqlite3_enable_load_extension() routine with onoff==1
7528** to turn extension loading on and call it with onoff==0 to turn
7529** it back off again.
7530**
7531** ^This interface enables or disables both the C-API
7532** [sqlite3_load_extension()] and the SQL function [load_extension()].
7533** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
7534** to enable or disable only the C-API.)^
7535**
7536** <b>Security warning:</b> It is recommended that extension loading
7537** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
7538** rather than this interface, so the [load_extension()] SQL function
7539** remains disabled. This will prevent SQL injections from giving attackers
7540** access to extension loading capabilities.
7541*/
7542SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
7543
7544/*
7545** CAPI3REF: Automatically Load Statically Linked Extensions
7546**
7547** ^This interface causes the xEntryPoint() function to be invoked for
7548** each new [database connection] that is created.  The idea here is that
7549** xEntryPoint() is the entry point for a statically linked [SQLite extension]
7550** that is to be automatically loaded into all new database connections.
7551**
7552** ^(Even though the function prototype shows that xEntryPoint() takes
7553** no arguments and returns void, SQLite invokes xEntryPoint() with three
7554** arguments and expects an integer result as if the signature of the
7555** entry point where as follows:
7556**
7557** <blockquote><pre>
7558** &nbsp;  int xEntryPoint(
7559** &nbsp;    sqlite3 *db,
7560** &nbsp;    const char **pzErrMsg,
7561** &nbsp;    const struct sqlite3_api_routines *pThunk
7562** &nbsp;  );
7563** </pre></blockquote>)^
7564**
7565** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
7566** point to an appropriate error message (obtained from [sqlite3_mprintf()])
7567** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
7568** is NULL before calling the xEntryPoint().  ^SQLite will invoke
7569** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
7570** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
7571** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
7572**
7573** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
7574** on the list of automatic extensions is a harmless no-op. ^No entry point
7575** will be called more than once for each database connection that is opened.
7576**
7577** See also: [sqlite3_reset_auto_extension()]
7578** and [sqlite3_cancel_auto_extension()]
7579*/
7580SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
7581
7582/*
7583** CAPI3REF: Cancel Automatic Extension Loading
7584**
7585** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
7586** initialization routine X that was registered using a prior call to
7587** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
7588** routine returns 1 if initialization routine X was successfully
7589** unregistered and it returns 0 if X was not on the list of initialization
7590** routines.
7591*/
7592SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
7593
7594/*
7595** CAPI3REF: Reset Automatic Extension Loading
7596**
7597** ^This interface disables all automatic extensions previously
7598** registered using [sqlite3_auto_extension()].
7599*/
7600SQLITE_API void sqlite3_reset_auto_extension(void);
7601
7602/*
7603** Structures used by the virtual table interface
7604*/
7605typedef struct sqlite3_vtab sqlite3_vtab;
7606typedef struct sqlite3_index_info sqlite3_index_info;
7607typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
7608typedef struct sqlite3_module sqlite3_module;
7609
7610/*
7611** CAPI3REF: Virtual Table Object
7612** KEYWORDS: sqlite3_module {virtual table module}
7613**
7614** This structure, sometimes called a "virtual table module",
7615** defines the implementation of a [virtual table].
7616** This structure consists mostly of methods for the module.
7617**
7618** ^A virtual table module is created by filling in a persistent
7619** instance of this structure and passing a pointer to that instance
7620** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
7621** ^The registration remains valid until it is replaced by a different
7622** module or until the [database connection] closes.  The content
7623** of this structure must not change while it is registered with
7624** any database connection.
7625*/
7626struct sqlite3_module {
7627  int iVersion;
7628  int (*xCreate)(sqlite3*, void *pAux,
7629               int argc, const char *const*argv,
7630               sqlite3_vtab **ppVTab, char**);
7631  int (*xConnect)(sqlite3*, void *pAux,
7632               int argc, const char *const*argv,
7633               sqlite3_vtab **ppVTab, char**);
7634  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
7635  int (*xDisconnect)(sqlite3_vtab *pVTab);
7636  int (*xDestroy)(sqlite3_vtab *pVTab);
7637  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
7638  int (*xClose)(sqlite3_vtab_cursor*);
7639  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
7640                int argc, sqlite3_value **argv);
7641  int (*xNext)(sqlite3_vtab_cursor*);
7642  int (*xEof)(sqlite3_vtab_cursor*);
7643  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
7644  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
7645  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
7646  int (*xBegin)(sqlite3_vtab *pVTab);
7647  int (*xSync)(sqlite3_vtab *pVTab);
7648  int (*xCommit)(sqlite3_vtab *pVTab);
7649  int (*xRollback)(sqlite3_vtab *pVTab);
7650  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
7651                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
7652                       void **ppArg);
7653  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
7654  /* The methods above are in version 1 of the sqlite_module object. Those
7655  ** below are for version 2 and greater. */
7656  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
7657  int (*xRelease)(sqlite3_vtab *pVTab, int);
7658  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
7659  /* The methods above are in versions 1 and 2 of the sqlite_module object.
7660  ** Those below are for version 3 and greater. */
7661  int (*xShadowName)(const char*);
7662  /* The methods above are in versions 1 through 3 of the sqlite_module object.
7663  ** Those below are for version 4 and greater. */
7664  int (*xIntegrity)(sqlite3_vtab *pVTab, const char *zSchema,
7665                    const char *zTabName, int mFlags, char **pzErr);
7666};
7667
7668/*
7669** CAPI3REF: Virtual Table Indexing Information
7670** KEYWORDS: sqlite3_index_info
7671**
7672** The sqlite3_index_info structure and its substructures is used as part
7673** of the [virtual table] interface to
7674** pass information into and receive the reply from the [xBestIndex]
7675** method of a [virtual table module].  The fields under **Inputs** are the
7676** inputs to xBestIndex and are read-only.  xBestIndex inserts its
7677** results into the **Outputs** fields.
7678**
7679** ^(The aConstraint[] array records WHERE clause constraints of the form:
7680**
7681** <blockquote>column OP expr</blockquote>
7682**
7683** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
7684** stored in aConstraint[].op using one of the
7685** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
7686** ^(The index of the column is stored in
7687** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
7688** expr on the right-hand side can be evaluated (and thus the constraint
7689** is usable) and false if it cannot.)^
7690**
7691** ^The optimizer automatically inverts terms of the form "expr OP column"
7692** and makes other simplifications to the WHERE clause in an attempt to
7693** get as many WHERE clause terms into the form shown above as possible.
7694** ^The aConstraint[] array only reports WHERE clause terms that are
7695** relevant to the particular virtual table being queried.
7696**
7697** ^Information about the ORDER BY clause is stored in aOrderBy[].
7698** ^Each term of aOrderBy records a column of the ORDER BY clause.
7699**
7700** The colUsed field indicates which columns of the virtual table may be
7701** required by the current scan. Virtual table columns are numbered from
7702** zero in the order in which they appear within the CREATE TABLE statement
7703** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
7704** the corresponding bit is set within the colUsed mask if the column may be
7705** required by SQLite. If the table has at least 64 columns and any column
7706** to the right of the first 63 is required, then bit 63 of colUsed is also
7707** set. In other words, column iCol may be required if the expression
7708** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
7709** non-zero.
7710**
7711** The [xBestIndex] method must fill aConstraintUsage[] with information
7712** about what parameters to pass to xFilter.  ^If argvIndex>0 then
7713** the right-hand side of the corresponding aConstraint[] is evaluated
7714** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
7715** is true, then the constraint is assumed to be fully handled by the
7716** virtual table and might not be checked again by the byte code.)^ ^(The
7717** aConstraintUsage[].omit flag is an optimization hint. When the omit flag
7718** is left in its default setting of false, the constraint will always be
7719** checked separately in byte code.  If the omit flag is change to true, then
7720** the constraint may or may not be checked in byte code.  In other words,
7721** when the omit flag is true there is no guarantee that the constraint will
7722** not be checked again using byte code.)^
7723**
7724** ^The idxNum and idxStr values are recorded and passed into the
7725** [xFilter] method.
7726** ^[sqlite3_free()] is used to free idxStr if and only if
7727** needToFreeIdxStr is true.
7728**
7729** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
7730** the correct order to satisfy the ORDER BY clause so that no separate
7731** sorting step is required.
7732**
7733** ^The estimatedCost value is an estimate of the cost of a particular
7734** strategy. A cost of N indicates that the cost of the strategy is similar
7735** to a linear scan of an SQLite table with N rows. A cost of log(N)
7736** indicates that the expense of the operation is similar to that of a
7737** binary search on a unique indexed field of an SQLite table with N rows.
7738**
7739** ^The estimatedRows value is an estimate of the number of rows that
7740** will be returned by the strategy.
7741**
7742** The xBestIndex method may optionally populate the idxFlags field with a
7743** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
7744** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
7745** assumes that the strategy may visit at most one row.
7746**
7747** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
7748** SQLite also assumes that if a call to the xUpdate() method is made as
7749** part of the same statement to delete or update a virtual table row and the
7750** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
7751** any database changes. In other words, if the xUpdate() returns
7752** SQLITE_CONSTRAINT, the database contents must be exactly as they were
7753** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
7754** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
7755** the xUpdate method are automatically rolled back by SQLite.
7756**
7757** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
7758** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
7759** If a virtual table extension is
7760** used with an SQLite version earlier than 3.8.2, the results of attempting
7761** to read or write the estimatedRows field are undefined (but are likely
7762** to include crashing the application). The estimatedRows field should
7763** therefore only be used if [sqlite3_libversion_number()] returns a
7764** value greater than or equal to 3008002. Similarly, the idxFlags field
7765** was added for [version 3.9.0] ([dateof:3.9.0]).
7766** It may therefore only be used if
7767** sqlite3_libversion_number() returns a value greater than or equal to
7768** 3009000.
7769*/
7770struct sqlite3_index_info {
7771  /* Inputs */
7772  int nConstraint;           /* Number of entries in aConstraint */
7773  struct sqlite3_index_constraint {
7774     int iColumn;              /* Column constrained.  -1 for ROWID */
7775     unsigned char op;         /* Constraint operator */
7776     unsigned char usable;     /* True if this constraint is usable */
7777     int iTermOffset;          /* Used internally - xBestIndex should ignore */
7778  } *aConstraint;            /* Table of WHERE clause constraints */
7779  int nOrderBy;              /* Number of terms in the ORDER BY clause */
7780  struct sqlite3_index_orderby {
7781     int iColumn;              /* Column number */
7782     unsigned char desc;       /* True for DESC.  False for ASC. */
7783  } *aOrderBy;               /* The ORDER BY clause */
7784  /* Outputs */
7785  struct sqlite3_index_constraint_usage {
7786    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
7787    unsigned char omit;      /* Do not code a test for this constraint */
7788  } *aConstraintUsage;
7789  int idxNum;                /* Number used to identify the index */
7790  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
7791  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
7792  int orderByConsumed;       /* True if output is already ordered */
7793  double estimatedCost;           /* Estimated cost of using this index */
7794  /* Fields below are only available in SQLite 3.8.2 and later */
7795  sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
7796  /* Fields below are only available in SQLite 3.9.0 and later */
7797  int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */
7798  /* Fields below are only available in SQLite 3.10.0 and later */
7799  sqlite3_uint64 colUsed;    /* Input: Mask of columns used by statement */
7800};
7801
7802/*
7803** CAPI3REF: Virtual Table Scan Flags
7804**
7805** Virtual table implementations are allowed to set the
7806** [sqlite3_index_info].idxFlags field to some combination of
7807** these bits.
7808*/
7809#define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */
7810
7811/*
7812** CAPI3REF: Virtual Table Constraint Operator Codes
7813**
7814** These macros define the allowed values for the
7815** [sqlite3_index_info].aConstraint[].op field.  Each value represents
7816** an operator that is part of a constraint term in the WHERE clause of
7817** a query that uses a [virtual table].
7818**
7819** ^The left-hand operand of the operator is given by the corresponding
7820** aConstraint[].iColumn field.  ^An iColumn of -1 indicates the left-hand
7821** operand is the rowid.
7822** The SQLITE_INDEX_CONSTRAINT_LIMIT and SQLITE_INDEX_CONSTRAINT_OFFSET
7823** operators have no left-hand operand, and so for those operators the
7824** corresponding aConstraint[].iColumn is meaningless and should not be
7825** used.
7826**
7827** All operator values from SQLITE_INDEX_CONSTRAINT_FUNCTION through
7828** value 255 are reserved to represent functions that are overloaded
7829** by the [xFindFunction|xFindFunction method] of the virtual table
7830** implementation.
7831**
7832** The right-hand operands for each constraint might be accessible using
7833** the [sqlite3_vtab_rhs_value()] interface.  Usually the right-hand
7834** operand is only available if it appears as a single constant literal
7835** in the input SQL.  If the right-hand operand is another column or an
7836** expression (even a constant expression) or a parameter, then the
7837** sqlite3_vtab_rhs_value() probably will not be able to extract it.
7838** ^The SQLITE_INDEX_CONSTRAINT_ISNULL and
7839** SQLITE_INDEX_CONSTRAINT_ISNOTNULL operators have no right-hand operand
7840** and hence calls to sqlite3_vtab_rhs_value() for those operators will
7841** always return SQLITE_NOTFOUND.
7842**
7843** The collating sequence to be used for comparison can be found using
7844** the [sqlite3_vtab_collation()] interface.  For most real-world virtual
7845** tables, the collating sequence of constraints does not matter (for example
7846** because the constraints are numeric) and so the sqlite3_vtab_collation()
7847** interface is not commonly needed.
7848*/
7849#define SQLITE_INDEX_CONSTRAINT_EQ          2
7850#define SQLITE_INDEX_CONSTRAINT_GT          4
7851#define SQLITE_INDEX_CONSTRAINT_LE          8
7852#define SQLITE_INDEX_CONSTRAINT_LT         16
7853#define SQLITE_INDEX_CONSTRAINT_GE         32
7854#define SQLITE_INDEX_CONSTRAINT_MATCH      64
7855#define SQLITE_INDEX_CONSTRAINT_LIKE       65
7856#define SQLITE_INDEX_CONSTRAINT_GLOB       66
7857#define SQLITE_INDEX_CONSTRAINT_REGEXP     67
7858#define SQLITE_INDEX_CONSTRAINT_NE         68
7859#define SQLITE_INDEX_CONSTRAINT_ISNOT      69
7860#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL  70
7861#define SQLITE_INDEX_CONSTRAINT_ISNULL     71
7862#define SQLITE_INDEX_CONSTRAINT_IS         72
7863#define SQLITE_INDEX_CONSTRAINT_LIMIT      73
7864#define SQLITE_INDEX_CONSTRAINT_OFFSET     74
7865#define SQLITE_INDEX_CONSTRAINT_FUNCTION  150
7866
7867/*
7868** CAPI3REF: Register A Virtual Table Implementation
7869** METHOD: sqlite3
7870**
7871** ^These routines are used to register a new [virtual table module] name.
7872** ^Module names must be registered before
7873** creating a new [virtual table] using the module and before using a
7874** preexisting [virtual table] for the module.
7875**
7876** ^The module name is registered on the [database connection] specified
7877** by the first parameter.  ^The name of the module is given by the
7878** second parameter.  ^The third parameter is a pointer to
7879** the implementation of the [virtual table module].   ^The fourth
7880** parameter is an arbitrary client data pointer that is passed through
7881** into the [xCreate] and [xConnect] methods of the virtual table module
7882** when a new virtual table is be being created or reinitialized.
7883**
7884** ^The sqlite3_create_module_v2() interface has a fifth parameter which
7885** is a pointer to a destructor for the pClientData.  ^SQLite will
7886** invoke the destructor function (if it is not NULL) when SQLite
7887** no longer needs the pClientData pointer.  ^The destructor will also
7888** be invoked if the call to sqlite3_create_module_v2() fails.
7889** ^The sqlite3_create_module()
7890** interface is equivalent to sqlite3_create_module_v2() with a NULL
7891** destructor.
7892**
7893** ^If the third parameter (the pointer to the sqlite3_module object) is
7894** NULL then no new module is created and any existing modules with the
7895** same name are dropped.
7896**
7897** See also: [sqlite3_drop_modules()]
7898*/
7899SQLITE_API int sqlite3_create_module(
7900  sqlite3 *db,               /* SQLite connection to register module with */
7901  const char *zName,         /* Name of the module */
7902  const sqlite3_module *p,   /* Methods for the module */
7903  void *pClientData          /* Client data for xCreate/xConnect */
7904);
7905SQLITE_API int sqlite3_create_module_v2(
7906  sqlite3 *db,               /* SQLite connection to register module with */
7907  const char *zName,         /* Name of the module */
7908  const sqlite3_module *p,   /* Methods for the module */
7909  void *pClientData,         /* Client data for xCreate/xConnect */
7910  void(*xDestroy)(void*)     /* Module destructor function */
7911);
7912
7913/*
7914** CAPI3REF: Remove Unnecessary Virtual Table Implementations
7915** METHOD: sqlite3
7916**
7917** ^The sqlite3_drop_modules(D,L) interface removes all virtual
7918** table modules from database connection D except those named on list L.
7919** The L parameter must be either NULL or a pointer to an array of pointers
7920** to strings where the array is terminated by a single NULL pointer.
7921** ^If the L parameter is NULL, then all virtual table modules are removed.
7922**
7923** See also: [sqlite3_create_module()]
7924*/
7925SQLITE_API int sqlite3_drop_modules(
7926  sqlite3 *db,                /* Remove modules from this connection */
7927  const char **azKeep         /* Except, do not remove the ones named here */
7928);
7929
7930/*
7931** CAPI3REF: Virtual Table Instance Object
7932** KEYWORDS: sqlite3_vtab
7933**
7934** Every [virtual table module] implementation uses a subclass
7935** of this object to describe a particular instance
7936** of the [virtual table].  Each subclass will
7937** be tailored to the specific needs of the module implementation.
7938** The purpose of this superclass is to define certain fields that are
7939** common to all module implementations.
7940**
7941** ^Virtual tables methods can set an error message by assigning a
7942** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
7943** take care that any prior string is freed by a call to [sqlite3_free()]
7944** prior to assigning a new string to zErrMsg.  ^After the error message
7945** is delivered up to the client application, the string will be automatically
7946** freed by sqlite3_free() and the zErrMsg field will be zeroed.
7947*/
7948struct sqlite3_vtab {
7949  const sqlite3_module *pModule;  /* The module for this virtual table */
7950  int nRef;                       /* Number of open cursors */
7951  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
7952  /* Virtual table implementations will typically add additional fields */
7953};
7954
7955/*
7956** CAPI3REF: Virtual Table Cursor Object
7957** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
7958**
7959** Every [virtual table module] implementation uses a subclass of the
7960** following structure to describe cursors that point into the
7961** [virtual table] and are used
7962** to loop through the virtual table.  Cursors are created using the
7963** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
7964** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
7965** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
7966** of the module.  Each module implementation will define
7967** the content of a cursor structure to suit its own needs.
7968**
7969** This superclass exists in order to define fields of the cursor that
7970** are common to all implementations.
7971*/
7972struct sqlite3_vtab_cursor {
7973  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
7974  /* Virtual table implementations will typically add additional fields */
7975};
7976
7977/*
7978** CAPI3REF: Declare The Schema Of A Virtual Table
7979**
7980** ^The [xCreate] and [xConnect] methods of a
7981** [virtual table module] call this interface
7982** to declare the format (the names and datatypes of the columns) of
7983** the virtual tables they implement.
7984*/
7985SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
7986
7987/*
7988** CAPI3REF: Overload A Function For A Virtual Table
7989** METHOD: sqlite3
7990**
7991** ^(Virtual tables can provide alternative implementations of functions
7992** using the [xFindFunction] method of the [virtual table module].
7993** But global versions of those functions
7994** must exist in order to be overloaded.)^
7995**
7996** ^(This API makes sure a global version of a function with a particular
7997** name and number of parameters exists.  If no such function exists
7998** before this API is called, a new function is created.)^  ^The implementation
7999** of the new function always causes an exception to be thrown.  So
8000** the new function is not good for anything by itself.  Its only
8001** purpose is to be a placeholder function that can be overloaded
8002** by a [virtual table].
8003*/
8004SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
8005
8006/*
8007** CAPI3REF: A Handle To An Open BLOB
8008** KEYWORDS: {BLOB handle} {BLOB handles}
8009**
8010** An instance of this object represents an open BLOB on which
8011** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
8012** ^Objects of this type are created by [sqlite3_blob_open()]
8013** and destroyed by [sqlite3_blob_close()].
8014** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
8015** can be used to read or write small subsections of the BLOB.
8016** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
8017*/
8018typedef struct sqlite3_blob sqlite3_blob;
8019
8020/*
8021** CAPI3REF: Open A BLOB For Incremental I/O
8022** METHOD: sqlite3
8023** CONSTRUCTOR: sqlite3_blob
8024**
8025** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
8026** in row iRow, column zColumn, table zTable in database zDb;
8027** in other words, the same BLOB that would be selected by:
8028**
8029** <pre>
8030**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
8031** </pre>)^
8032**
8033** ^(Parameter zDb is not the filename that contains the database, but
8034** rather the symbolic name of the database. For attached databases, this is
8035** the name that appears after the AS keyword in the [ATTACH] statement.
8036** For the main database file, the database name is "main". For TEMP
8037** tables, the database name is "temp".)^
8038**
8039** ^If the flags parameter is non-zero, then the BLOB is opened for read
8040** and write access. ^If the flags parameter is zero, the BLOB is opened for
8041** read-only access.
8042**
8043** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
8044** in *ppBlob. Otherwise an [error code] is returned and, unless the error
8045** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
8046** the API is not misused, it is always safe to call [sqlite3_blob_close()]
8047** on *ppBlob after this function it returns.
8048**
8049** This function fails with SQLITE_ERROR if any of the following are true:
8050** <ul>
8051**   <li> ^(Database zDb does not exist)^,
8052**   <li> ^(Table zTable does not exist within database zDb)^,
8053**   <li> ^(Table zTable is a WITHOUT ROWID table)^,
8054**   <li> ^(Column zColumn does not exist)^,
8055**   <li> ^(Row iRow is not present in the table)^,
8056**   <li> ^(The specified column of row iRow contains a value that is not
8057**         a TEXT or BLOB value)^,
8058**   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
8059**         constraint and the blob is being opened for read/write access)^,
8060**   <li> ^([foreign key constraints | Foreign key constraints] are enabled,
8061**         column zColumn is part of a [child key] definition and the blob is
8062**         being opened for read/write access)^.
8063** </ul>
8064**
8065** ^Unless it returns SQLITE_MISUSE, this function sets the
8066** [database connection] error code and message accessible via
8067** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
8068**
8069** A BLOB referenced by sqlite3_blob_open() may be read using the
8070** [sqlite3_blob_read()] interface and modified by using
8071** [sqlite3_blob_write()].  The [BLOB handle] can be moved to a
8072** different row of the same table using the [sqlite3_blob_reopen()]
8073** interface.  However, the column, table, or database of a [BLOB handle]
8074** cannot be changed after the [BLOB handle] is opened.
8075**
8076** ^(If the row that a BLOB handle points to is modified by an
8077** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
8078** then the BLOB handle is marked as "expired".
8079** This is true if any column of the row is changed, even a column
8080** other than the one the BLOB handle is open on.)^
8081** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
8082** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
8083** ^(Changes written into a BLOB prior to the BLOB expiring are not
8084** rolled back by the expiration of the BLOB.  Such changes will eventually
8085** commit if the transaction continues to completion.)^
8086**
8087** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
8088** the opened blob.  ^The size of a blob may not be changed by this
8089** interface.  Use the [UPDATE] SQL command to change the size of a
8090** blob.
8091**
8092** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
8093** and the built-in [zeroblob] SQL function may be used to create a
8094** zero-filled blob to read or write using the incremental-blob interface.
8095**
8096** To avoid a resource leak, every open [BLOB handle] should eventually
8097** be released by a call to [sqlite3_blob_close()].
8098**
8099** See also: [sqlite3_blob_close()],
8100** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
8101** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
8102*/
8103SQLITE_API int sqlite3_blob_open(
8104  sqlite3*,
8105  const char *zDb,
8106  const char *zTable,
8107  const char *zColumn,
8108  sqlite3_int64 iRow,
8109  int flags,
8110  sqlite3_blob **ppBlob
8111);
8112
8113/*
8114** CAPI3REF: Move a BLOB Handle to a New Row
8115** METHOD: sqlite3_blob
8116**
8117** ^This function is used to move an existing [BLOB handle] so that it points
8118** to a different row of the same database table. ^The new row is identified
8119** by the rowid value passed as the second argument. Only the row can be
8120** changed. ^The database, table and column on which the blob handle is open
8121** remain the same. Moving an existing [BLOB handle] to a new row is
8122** faster than closing the existing handle and opening a new one.
8123**
8124** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
8125** it must exist and there must be either a blob or text value stored in
8126** the nominated column.)^ ^If the new row is not present in the table, or if
8127** it does not contain a blob or text value, or if another error occurs, an
8128** SQLite error code is returned and the blob handle is considered aborted.
8129** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
8130** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
8131** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
8132** always returns zero.
8133**
8134** ^This function sets the database handle error code and message.
8135*/
8136SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
8137
8138/*
8139** CAPI3REF: Close A BLOB Handle
8140** DESTRUCTOR: sqlite3_blob
8141**
8142** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
8143** unconditionally.  Even if this routine returns an error code, the
8144** handle is still closed.)^
8145**
8146** ^If the blob handle being closed was opened for read-write access, and if
8147** the database is in auto-commit mode and there are no other open read-write
8148** blob handles or active write statements, the current transaction is
8149** committed. ^If an error occurs while committing the transaction, an error
8150** code is returned and the transaction rolled back.
8151**
8152** Calling this function with an argument that is not a NULL pointer or an
8153** open blob handle results in undefined behavior. ^Calling this routine
8154** with a null pointer (such as would be returned by a failed call to
8155** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
8156** is passed a valid open blob handle, the values returned by the
8157** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
8158*/
8159SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
8160
8161/*
8162** CAPI3REF: Return The Size Of An Open BLOB
8163** METHOD: sqlite3_blob
8164**
8165** ^Returns the size in bytes of the BLOB accessible via the
8166** successfully opened [BLOB handle] in its only argument.  ^The
8167** incremental blob I/O routines can only read or overwriting existing
8168** blob content; they cannot change the size of a blob.
8169**
8170** This routine only works on a [BLOB handle] which has been created
8171** by a prior successful call to [sqlite3_blob_open()] and which has not
8172** been closed by [sqlite3_blob_close()].  Passing any other pointer in
8173** to this routine results in undefined and probably undesirable behavior.
8174*/
8175SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
8176
8177/*
8178** CAPI3REF: Read Data From A BLOB Incrementally
8179** METHOD: sqlite3_blob
8180**
8181** ^(This function is used to read data from an open [BLOB handle] into a
8182** caller-supplied buffer. N bytes of data are copied into buffer Z
8183** from the open BLOB, starting at offset iOffset.)^
8184**
8185** ^If offset iOffset is less than N bytes from the end of the BLOB,
8186** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
8187** less than zero, [SQLITE_ERROR] is returned and no data is read.
8188** ^The size of the blob (and hence the maximum value of N+iOffset)
8189** can be determined using the [sqlite3_blob_bytes()] interface.
8190**
8191** ^An attempt to read from an expired [BLOB handle] fails with an
8192** error code of [SQLITE_ABORT].
8193**
8194** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
8195** Otherwise, an [error code] or an [extended error code] is returned.)^
8196**
8197** This routine only works on a [BLOB handle] which has been created
8198** by a prior successful call to [sqlite3_blob_open()] and which has not
8199** been closed by [sqlite3_blob_close()].  Passing any other pointer in
8200** to this routine results in undefined and probably undesirable behavior.
8201**
8202** See also: [sqlite3_blob_write()].
8203*/
8204SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
8205
8206/*
8207** CAPI3REF: Write Data Into A BLOB Incrementally
8208** METHOD: sqlite3_blob
8209**
8210** ^(This function is used to write data into an open [BLOB handle] from a
8211** caller-supplied buffer. N bytes of data are copied from the buffer Z
8212** into the open BLOB, starting at offset iOffset.)^
8213**
8214** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
8215** Otherwise, an  [error code] or an [extended error code] is returned.)^
8216** ^Unless SQLITE_MISUSE is returned, this function sets the
8217** [database connection] error code and message accessible via
8218** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
8219**
8220** ^If the [BLOB handle] passed as the first argument was not opened for
8221** writing (the flags parameter to [sqlite3_blob_open()] was zero),
8222** this function returns [SQLITE_READONLY].
8223**
8224** This function may only modify the contents of the BLOB; it is
8225** not possible to increase the size of a BLOB using this API.
8226** ^If offset iOffset is less than N bytes from the end of the BLOB,
8227** [SQLITE_ERROR] is returned and no data is written. The size of the
8228** BLOB (and hence the maximum value of N+iOffset) can be determined
8229** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
8230** than zero [SQLITE_ERROR] is returned and no data is written.
8231**
8232** ^An attempt to write to an expired [BLOB handle] fails with an
8233** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
8234** before the [BLOB handle] expired are not rolled back by the
8235** expiration of the handle, though of course those changes might
8236** have been overwritten by the statement that expired the BLOB handle
8237** or by other independent statements.
8238**
8239** This routine only works on a [BLOB handle] which has been created
8240** by a prior successful call to [sqlite3_blob_open()] and which has not
8241** been closed by [sqlite3_blob_close()].  Passing any other pointer in
8242** to this routine results in undefined and probably undesirable behavior.
8243**
8244** See also: [sqlite3_blob_read()].
8245*/
8246SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
8247
8248/*
8249** CAPI3REF: Virtual File System Objects
8250**
8251** A virtual filesystem (VFS) is an [sqlite3_vfs] object
8252** that SQLite uses to interact
8253** with the underlying operating system.  Most SQLite builds come with a
8254** single default VFS that is appropriate for the host computer.
8255** New VFSes can be registered and existing VFSes can be unregistered.
8256** The following interfaces are provided.
8257**
8258** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
8259** ^Names are case sensitive.
8260** ^Names are zero-terminated UTF-8 strings.
8261** ^If there is no match, a NULL pointer is returned.
8262** ^If zVfsName is NULL then the default VFS is returned.
8263**
8264** ^New VFSes are registered with sqlite3_vfs_register().
8265** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
8266** ^The same VFS can be registered multiple times without injury.
8267** ^To make an existing VFS into the default VFS, register it again
8268** with the makeDflt flag set.  If two different VFSes with the
8269** same name are registered, the behavior is undefined.  If a
8270** VFS is registered with a name that is NULL or an empty string,
8271** then the behavior is undefined.
8272**
8273** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
8274** ^(If the default VFS is unregistered, another VFS is chosen as
8275** the default.  The choice for the new VFS is arbitrary.)^
8276*/
8277SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
8278SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
8279SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
8280
8281/*
8282** CAPI3REF: Mutexes
8283**
8284** The SQLite core uses these routines for thread
8285** synchronization. Though they are intended for internal
8286** use by SQLite, code that links against SQLite is
8287** permitted to use any of these routines.
8288**
8289** The SQLite source code contains multiple implementations
8290** of these mutex routines.  An appropriate implementation
8291** is selected automatically at compile-time.  The following
8292** implementations are available in the SQLite core:
8293**
8294** <ul>
8295** <li>   SQLITE_MUTEX_PTHREADS
8296** <li>   SQLITE_MUTEX_W32
8297** <li>   SQLITE_MUTEX_NOOP
8298** </ul>
8299**
8300** The SQLITE_MUTEX_NOOP implementation is a set of routines
8301** that does no real locking and is appropriate for use in
8302** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and
8303** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
8304** and Windows.
8305**
8306** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
8307** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
8308** implementation is included with the library. In this case the
8309** application must supply a custom mutex implementation using the
8310** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
8311** before calling sqlite3_initialize() or any other public sqlite3_
8312** function that calls sqlite3_initialize().
8313**
8314** ^The sqlite3_mutex_alloc() routine allocates a new
8315** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
8316** routine returns NULL if it is unable to allocate the requested
8317** mutex.  The argument to sqlite3_mutex_alloc() must one of these
8318** integer constants:
8319**
8320** <ul>
8321** <li>  SQLITE_MUTEX_FAST
8322** <li>  SQLITE_MUTEX_RECURSIVE
8323** <li>  SQLITE_MUTEX_STATIC_MAIN
8324** <li>  SQLITE_MUTEX_STATIC_MEM
8325** <li>  SQLITE_MUTEX_STATIC_OPEN
8326** <li>  SQLITE_MUTEX_STATIC_PRNG
8327** <li>  SQLITE_MUTEX_STATIC_LRU
8328** <li>  SQLITE_MUTEX_STATIC_PMEM
8329** <li>  SQLITE_MUTEX_STATIC_APP1
8330** <li>  SQLITE_MUTEX_STATIC_APP2
8331** <li>  SQLITE_MUTEX_STATIC_APP3
8332** <li>  SQLITE_MUTEX_STATIC_VFS1
8333** <li>  SQLITE_MUTEX_STATIC_VFS2
8334** <li>  SQLITE_MUTEX_STATIC_VFS3
8335** </ul>
8336**
8337** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
8338** cause sqlite3_mutex_alloc() to create
8339** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
8340** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
8341** The mutex implementation does not need to make a distinction
8342** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
8343** not want to.  SQLite will only request a recursive mutex in
8344** cases where it really needs one.  If a faster non-recursive mutex
8345** implementation is available on the host platform, the mutex subsystem
8346** might return such a mutex in response to SQLITE_MUTEX_FAST.
8347**
8348** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
8349** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
8350** a pointer to a static preexisting mutex.  ^Nine static mutexes are
8351** used by the current version of SQLite.  Future versions of SQLite
8352** may add additional static mutexes.  Static mutexes are for internal
8353** use by SQLite only.  Applications that use SQLite mutexes should
8354** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
8355** SQLITE_MUTEX_RECURSIVE.
8356**
8357** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
8358** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
8359** returns a different mutex on every call.  ^For the static
8360** mutex types, the same mutex is returned on every call that has
8361** the same type number.
8362**
8363** ^The sqlite3_mutex_free() routine deallocates a previously
8364** allocated dynamic mutex.  Attempting to deallocate a static
8365** mutex results in undefined behavior.
8366**
8367** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
8368** to enter a mutex.  ^If another thread is already within the mutex,
8369** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
8370** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
8371** upon successful entry.  ^(Mutexes created using
8372** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
8373** In such cases, the
8374** mutex must be exited an equal number of times before another thread
8375** can enter.)^  If the same thread tries to enter any mutex other
8376** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
8377**
8378** ^(Some systems (for example, Windows 95) do not support the operation
8379** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
8380** will always return SQLITE_BUSY. In most cases the SQLite core only uses
8381** sqlite3_mutex_try() as an optimization, so this is acceptable
8382** behavior. The exceptions are unix builds that set the
8383** SQLITE_ENABLE_SETLK_TIMEOUT build option. In that case a working
8384** sqlite3_mutex_try() is required.)^
8385**
8386** ^The sqlite3_mutex_leave() routine exits a mutex that was
8387** previously entered by the same thread.   The behavior
8388** is undefined if the mutex is not currently entered by the
8389** calling thread or is not currently allocated.
8390**
8391** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(),
8392** sqlite3_mutex_leave(), or sqlite3_mutex_free() is a NULL pointer,
8393** then any of the four routines behaves as a no-op.
8394**
8395** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
8396*/
8397SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
8398SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
8399SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
8400SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
8401SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
8402
8403/*
8404** CAPI3REF: Mutex Methods Object
8405**
8406** An instance of this structure defines the low-level routines
8407** used to allocate and use mutexes.
8408**
8409** Usually, the default mutex implementations provided by SQLite are
8410** sufficient, however the application has the option of substituting a custom
8411** implementation for specialized deployments or systems for which SQLite
8412** does not provide a suitable implementation. In this case, the application
8413** creates and populates an instance of this structure to pass
8414** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
8415** Additionally, an instance of this structure can be used as an
8416** output variable when querying the system for the current mutex
8417** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
8418**
8419** ^The xMutexInit method defined by this structure is invoked as
8420** part of system initialization by the sqlite3_initialize() function.
8421** ^The xMutexInit routine is called by SQLite exactly once for each
8422** effective call to [sqlite3_initialize()].
8423**
8424** ^The xMutexEnd method defined by this structure is invoked as
8425** part of system shutdown by the sqlite3_shutdown() function. The
8426** implementation of this method is expected to release all outstanding
8427** resources obtained by the mutex methods implementation, especially
8428** those obtained by the xMutexInit method.  ^The xMutexEnd()
8429** interface is invoked exactly once for each call to [sqlite3_shutdown()].
8430**
8431** ^(The remaining seven methods defined by this structure (xMutexAlloc,
8432** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
8433** xMutexNotheld) implement the following interfaces (respectively):
8434**
8435** <ul>
8436**   <li>  [sqlite3_mutex_alloc()] </li>
8437**   <li>  [sqlite3_mutex_free()] </li>
8438**   <li>  [sqlite3_mutex_enter()] </li>
8439**   <li>  [sqlite3_mutex_try()] </li>
8440**   <li>  [sqlite3_mutex_leave()] </li>
8441**   <li>  [sqlite3_mutex_held()] </li>
8442**   <li>  [sqlite3_mutex_notheld()] </li>
8443** </ul>)^
8444**
8445** The only difference is that the public sqlite3_XXX functions enumerated
8446** above silently ignore any invocations that pass a NULL pointer instead
8447** of a valid mutex handle. The implementations of the methods defined
8448** by this structure are not required to handle this case. The results
8449** of passing a NULL pointer instead of a valid mutex handle are undefined
8450** (i.e. it is acceptable to provide an implementation that segfaults if
8451** it is passed a NULL pointer).
8452**
8453** The xMutexInit() method must be threadsafe.  It must be harmless to
8454** invoke xMutexInit() multiple times within the same process and without
8455** intervening calls to xMutexEnd().  Second and subsequent calls to
8456** xMutexInit() must be no-ops.
8457**
8458** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
8459** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory
8460** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
8461** memory allocation for a fast or recursive mutex.
8462**
8463** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
8464** called, but only if the prior call to xMutexInit returned SQLITE_OK.
8465** If xMutexInit fails in any way, it is expected to clean up after itself
8466** prior to returning.
8467*/
8468typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
8469struct sqlite3_mutex_methods {
8470  int (*xMutexInit)(void);
8471  int (*xMutexEnd)(void);
8472  sqlite3_mutex *(*xMutexAlloc)(int);
8473  void (*xMutexFree)(sqlite3_mutex *);
8474  void (*xMutexEnter)(sqlite3_mutex *);
8475  int (*xMutexTry)(sqlite3_mutex *);
8476  void (*xMutexLeave)(sqlite3_mutex *);
8477  int (*xMutexHeld)(sqlite3_mutex *);
8478  int (*xMutexNotheld)(sqlite3_mutex *);
8479};
8480
8481/*
8482** CAPI3REF: Mutex Verification Routines
8483**
8484** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
8485** are intended for use inside assert() statements.  The SQLite core
8486** never uses these routines except inside an assert() and applications
8487** are advised to follow the lead of the core.  The SQLite core only
8488** provides implementations for these routines when it is compiled
8489** with the SQLITE_DEBUG flag.  External mutex implementations
8490** are only required to provide these routines if SQLITE_DEBUG is
8491** defined and if NDEBUG is not defined.
8492**
8493** These routines should return true if the mutex in their argument
8494** is held or not held, respectively, by the calling thread.
8495**
8496** The implementation is not required to provide versions of these
8497** routines that actually work. If the implementation does not provide working
8498** versions of these routines, it should at least provide stubs that always
8499** return true so that one does not get spurious assertion failures.
8500**
8501** If the argument to sqlite3_mutex_held() is a NULL pointer then
8502** the routine should return 1.   This seems counter-intuitive since
8503** clearly the mutex cannot be held if it does not exist.  But
8504** the reason the mutex does not exist is because the build is not
8505** using mutexes.  And we do not want the assert() containing the
8506** call to sqlite3_mutex_held() to fail, so a non-zero return is
8507** the appropriate thing to do.  The sqlite3_mutex_notheld()
8508** interface should also return 1 when given a NULL pointer.
8509*/
8510#ifndef NDEBUG
8511SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
8512SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
8513#endif
8514
8515/*
8516** CAPI3REF: Mutex Types
8517**
8518** The [sqlite3_mutex_alloc()] interface takes a single argument
8519** which is one of these integer constants.
8520**
8521** The set of static mutexes may change from one SQLite release to the
8522** next.  Applications that override the built-in mutex logic must be
8523** prepared to accommodate additional static mutexes.
8524*/
8525#define SQLITE_MUTEX_FAST             0
8526#define SQLITE_MUTEX_RECURSIVE        1
8527#define SQLITE_MUTEX_STATIC_MAIN      2
8528#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
8529#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
8530#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
8531#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_randomness() */
8532#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
8533#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
8534#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
8535#define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */
8536#define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */
8537#define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */
8538#define SQLITE_MUTEX_STATIC_VFS1     11  /* For use by built-in VFS */
8539#define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */
8540#define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */
8541
8542/* Legacy compatibility: */
8543#define SQLITE_MUTEX_STATIC_MASTER    2
8544
8545
8546/*
8547** CAPI3REF: Retrieve the mutex for a database connection
8548** METHOD: sqlite3
8549**
8550** ^This interface returns a pointer the [sqlite3_mutex] object that
8551** serializes access to the [database connection] given in the argument
8552** when the [threading mode] is Serialized.
8553** ^If the [threading mode] is Single-thread or Multi-thread then this
8554** routine returns a NULL pointer.
8555*/
8556SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
8557
8558/*
8559** CAPI3REF: Low-Level Control Of Database Files
8560** METHOD: sqlite3
8561** KEYWORDS: {file control}
8562**
8563** ^The [sqlite3_file_control()] interface makes a direct call to the
8564** xFileControl method for the [sqlite3_io_methods] object associated
8565** with a particular database identified by the second argument. ^The
8566** name of the database is "main" for the main database or "temp" for the
8567** TEMP database, or the name that appears after the AS keyword for
8568** databases that are added using the [ATTACH] SQL command.
8569** ^A NULL pointer can be used in place of "main" to refer to the
8570** main database file.
8571** ^The third and fourth parameters to this routine
8572** are passed directly through to the second and third parameters of
8573** the xFileControl method.  ^The return value of the xFileControl
8574** method becomes the return value of this routine.
8575**
8576** A few opcodes for [sqlite3_file_control()] are handled directly
8577** by the SQLite core and never invoke the
8578** sqlite3_io_methods.xFileControl method.
8579** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
8580** a pointer to the underlying [sqlite3_file] object to be written into
8581** the space pointed to by the 4th parameter.  The
8582** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns
8583** the [sqlite3_file] object associated with the journal file instead of
8584** the main database.  The [SQLITE_FCNTL_VFS_POINTER] opcode returns
8585** a pointer to the underlying [sqlite3_vfs] object for the file.
8586** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter
8587** from the pager.
8588**
8589** ^If the second parameter (zDbName) does not match the name of any
8590** open database file, then SQLITE_ERROR is returned.  ^This error
8591** code is not remembered and will not be recalled by [sqlite3_errcode()]
8592** or [sqlite3_errmsg()].  The underlying xFileControl method might
8593** also return SQLITE_ERROR.  There is no way to distinguish between
8594** an incorrect zDbName and an SQLITE_ERROR return from the underlying
8595** xFileControl method.
8596**
8597** See also: [file control opcodes]
8598*/
8599SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
8600
8601/*
8602** CAPI3REF: Testing Interface
8603**
8604** ^The sqlite3_test_control() interface is used to read out internal
8605** state of SQLite and to inject faults into SQLite for testing
8606** purposes.  ^The first parameter is an operation code that determines
8607** the number, meaning, and operation of all subsequent parameters.
8608**
8609** This interface is not for use by applications.  It exists solely
8610** for verifying the correct operation of the SQLite library.  Depending
8611** on how the SQLite library is compiled, this interface might not exist.
8612**
8613** The details of the operation codes, their meanings, the parameters
8614** they take, and what they do are all subject to change without notice.
8615** Unlike most of the SQLite API, this function is not guaranteed to
8616** operate consistently from one release to the next.
8617*/
8618SQLITE_API int sqlite3_test_control(int op, ...);
8619
8620/*
8621** CAPI3REF: Testing Interface Operation Codes
8622**
8623** These constants are the valid operation code parameters used
8624** as the first argument to [sqlite3_test_control()].
8625**
8626** These parameters and their meanings are subject to change
8627** without notice.  These values are for testing purposes only.
8628** Applications should not use any of these parameters or the
8629** [sqlite3_test_control()] interface.
8630*/
8631#define SQLITE_TESTCTRL_FIRST                    5
8632#define SQLITE_TESTCTRL_PRNG_SAVE                5
8633#define SQLITE_TESTCTRL_PRNG_RESTORE             6
8634#define SQLITE_TESTCTRL_PRNG_RESET               7  /* NOT USED */
8635#define SQLITE_TESTCTRL_FK_NO_ACTION             7
8636#define SQLITE_TESTCTRL_BITVEC_TEST              8
8637#define SQLITE_TESTCTRL_FAULT_INSTALL            9
8638#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
8639#define SQLITE_TESTCTRL_PENDING_BYTE            11
8640#define SQLITE_TESTCTRL_ASSERT                  12
8641#define SQLITE_TESTCTRL_ALWAYS                  13
8642#define SQLITE_TESTCTRL_RESERVE                 14  /* NOT USED */
8643#define SQLITE_TESTCTRL_JSON_SELFCHECK          14
8644#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
8645#define SQLITE_TESTCTRL_ISKEYWORD               16  /* NOT USED */
8646#define SQLITE_TESTCTRL_SCRATCHMALLOC           17  /* NOT USED */
8647#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS      17
8648#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
8649#define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */
8650#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD    19
8651#define SQLITE_TESTCTRL_NEVER_CORRUPT           20
8652#define SQLITE_TESTCTRL_VDBE_COVERAGE           21
8653#define SQLITE_TESTCTRL_BYTEORDER               22
8654#define SQLITE_TESTCTRL_ISINIT                  23
8655#define SQLITE_TESTCTRL_SORTER_MMAP             24
8656#define SQLITE_TESTCTRL_IMPOSTER                25
8657#define SQLITE_TESTCTRL_PARSER_COVERAGE         26
8658#define SQLITE_TESTCTRL_RESULT_INTREAL          27
8659#define SQLITE_TESTCTRL_PRNG_SEED               28
8660#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     29
8661#define SQLITE_TESTCTRL_SEEK_COUNT              30
8662#define SQLITE_TESTCTRL_TRACEFLAGS              31
8663#define SQLITE_TESTCTRL_TUNE                    32
8664#define SQLITE_TESTCTRL_LOGEST                  33
8665#define SQLITE_TESTCTRL_USELONGDOUBLE           34
8666#define SQLITE_TESTCTRL_LAST                    34  /* Largest TESTCTRL */
8667
8668/*
8669** CAPI3REF: SQL Keyword Checking
8670**
8671** These routines provide access to the set of SQL language keywords
8672** recognized by SQLite.  Applications can uses these routines to determine
8673** whether or not a specific identifier needs to be escaped (for example,
8674** by enclosing in double-quotes) so as not to confuse the parser.
8675**
8676** The sqlite3_keyword_count() interface returns the number of distinct
8677** keywords understood by SQLite.
8678**
8679** The sqlite3_keyword_name(N,Z,L) interface finds the 0-based N-th keyword and
8680** makes *Z point to that keyword expressed as UTF8 and writes the number
8681** of bytes in the keyword into *L.  The string that *Z points to is not
8682** zero-terminated.  The sqlite3_keyword_name(N,Z,L) routine returns
8683** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z
8684** or L are NULL or invalid pointers then calls to
8685** sqlite3_keyword_name(N,Z,L) result in undefined behavior.
8686**
8687** The sqlite3_keyword_check(Z,L) interface checks to see whether or not
8688** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
8689** if it is and zero if not.
8690**
8691** The parser used by SQLite is forgiving.  It is often possible to use
8692** a keyword as an identifier as long as such use does not result in a
8693** parsing ambiguity.  For example, the statement
8694** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
8695** creates a new table named "BEGIN" with three columns named
8696** "REPLACE", "PRAGMA", and "END".  Nevertheless, best practice is to avoid
8697** using keywords as identifiers.  Common techniques used to avoid keyword
8698** name collisions include:
8699** <ul>
8700** <li> Put all identifier names inside double-quotes.  This is the official
8701**      SQL way to escape identifier names.
8702** <li> Put identifier names inside &#91;...&#93;.  This is not standard SQL,
8703**      but it is what SQL Server does and so lots of programmers use this
8704**      technique.
8705** <li> Begin every identifier with the letter "Z" as no SQL keywords start
8706**      with "Z".
8707** <li> Include a digit somewhere in every identifier name.
8708** </ul>
8709**
8710** Note that the number of keywords understood by SQLite can depend on
8711** compile-time options.  For example, "VACUUM" is not a keyword if
8712** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option.  Also,
8713** new keywords may be added to future releases of SQLite.
8714*/
8715SQLITE_API int sqlite3_keyword_count(void);
8716SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
8717SQLITE_API int sqlite3_keyword_check(const char*,int);
8718
8719/*
8720** CAPI3REF: Dynamic String Object
8721** KEYWORDS: {dynamic string}
8722**
8723** An instance of the sqlite3_str object contains a dynamically-sized
8724** string under construction.
8725**
8726** The lifecycle of an sqlite3_str object is as follows:
8727** <ol>
8728** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
8729** <li> ^Text is appended to the sqlite3_str object using various
8730** methods, such as [sqlite3_str_appendf()].
8731** <li> ^The sqlite3_str object is destroyed and the string it created
8732** is returned using the [sqlite3_str_finish()] interface.
8733** </ol>
8734*/
8735typedef struct sqlite3_str sqlite3_str;
8736
8737/*
8738** CAPI3REF: Create A New Dynamic String Object
8739** CONSTRUCTOR: sqlite3_str
8740**
8741** ^The [sqlite3_str_new(D)] interface allocates and initializes
8742** a new [sqlite3_str] object.  To avoid memory leaks, the object returned by
8743** [sqlite3_str_new()] must be freed by a subsequent call to
8744** [sqlite3_str_finish(X)].
8745**
8746** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
8747** valid [sqlite3_str] object, though in the event of an out-of-memory
8748** error the returned object might be a special singleton that will
8749** silently reject new text, always return SQLITE_NOMEM from
8750** [sqlite3_str_errcode()], always return 0 for
8751** [sqlite3_str_length()], and always return NULL from
8752** [sqlite3_str_finish(X)].  It is always safe to use the value
8753** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
8754** to any of the other [sqlite3_str] methods.
8755**
8756** The D parameter to [sqlite3_str_new(D)] may be NULL.  If the
8757** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
8758** length of the string contained in the [sqlite3_str] object will be
8759** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
8760** of [SQLITE_MAX_LENGTH].
8761*/
8762SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
8763
8764/*
8765** CAPI3REF: Finalize A Dynamic String
8766** DESTRUCTOR: sqlite3_str
8767**
8768** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
8769** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
8770** that contains the constructed string.  The calling application should
8771** pass the returned value to [sqlite3_free()] to avoid a memory leak.
8772** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
8773** errors were encountered during construction of the string.  ^The
8774** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
8775** string in [sqlite3_str] object X is zero bytes long.
8776*/
8777SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
8778
8779/*
8780** CAPI3REF: Add Content To A Dynamic String
8781** METHOD: sqlite3_str
8782**
8783** These interfaces add content to an sqlite3_str object previously obtained
8784** from [sqlite3_str_new()].
8785**
8786** ^The [sqlite3_str_appendf(X,F,...)] and
8787** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
8788** functionality of SQLite to append formatted text onto the end of
8789** [sqlite3_str] object X.
8790**
8791** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
8792** onto the end of the [sqlite3_str] object X.  N must be non-negative.
8793** S must contain at least N non-zero bytes of content.  To append a
8794** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
8795** method instead.
8796**
8797** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
8798** zero-terminated string S onto the end of [sqlite3_str] object X.
8799**
8800** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
8801** single-byte character C onto the end of [sqlite3_str] object X.
8802** ^This method can be used, for example, to add whitespace indentation.
8803**
8804** ^The [sqlite3_str_reset(X)] method resets the string under construction
8805** inside [sqlite3_str] object X back to zero bytes in length.
8806**
8807** These methods do not return a result code.  ^If an error occurs, that fact
8808** is recorded in the [sqlite3_str] object and can be recovered by a
8809** subsequent call to [sqlite3_str_errcode(X)].
8810*/
8811SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
8812SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
8813SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
8814SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
8815SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
8816SQLITE_API void sqlite3_str_reset(sqlite3_str*);
8817
8818/*
8819** CAPI3REF: Status Of A Dynamic String
8820** METHOD: sqlite3_str
8821**
8822** These interfaces return the current status of an [sqlite3_str] object.
8823**
8824** ^If any prior errors have occurred while constructing the dynamic string
8825** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
8826** an appropriate error code.  ^The [sqlite3_str_errcode(X)] method returns
8827** [SQLITE_NOMEM] following any out-of-memory error, or
8828** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
8829** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
8830**
8831** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
8832** of the dynamic string under construction in [sqlite3_str] object X.
8833** ^The length returned by [sqlite3_str_length(X)] does not include the
8834** zero-termination byte.
8835**
8836** ^The [sqlite3_str_value(X)] method returns a pointer to the current
8837** content of the dynamic string under construction in X.  The value
8838** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
8839** and might be freed or altered by any subsequent method on the same
8840** [sqlite3_str] object.  Applications must not used the pointer returned
8841** [sqlite3_str_value(X)] after any subsequent method call on the same
8842** object.  ^Applications may change the content of the string returned
8843** by [sqlite3_str_value(X)] as long as they do not write into any bytes
8844** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
8845** write any byte after any subsequent sqlite3_str method call.
8846*/
8847SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
8848SQLITE_API int sqlite3_str_length(sqlite3_str*);
8849SQLITE_API char *sqlite3_str_value(sqlite3_str*);
8850
8851/*
8852** CAPI3REF: SQLite Runtime Status
8853**
8854** ^These interfaces are used to retrieve runtime status information
8855** about the performance of SQLite, and optionally to reset various
8856** highwater marks.  ^The first argument is an integer code for
8857** the specific parameter to measure.  ^(Recognized integer codes
8858** are of the form [status parameters | SQLITE_STATUS_...].)^
8859** ^The current value of the parameter is returned into *pCurrent.
8860** ^The highest recorded value is returned in *pHighwater.  ^If the
8861** resetFlag is true, then the highest record value is reset after
8862** *pHighwater is written.  ^(Some parameters do not record the highest
8863** value.  For those parameters
8864** nothing is written into *pHighwater and the resetFlag is ignored.)^
8865** ^(Other parameters record only the highwater mark and not the current
8866** value.  For these latter parameters nothing is written into *pCurrent.)^
8867**
8868** ^The sqlite3_status() and sqlite3_status64() routines return
8869** SQLITE_OK on success and a non-zero [error code] on failure.
8870**
8871** If either the current value or the highwater mark is too large to
8872** be represented by a 32-bit integer, then the values returned by
8873** sqlite3_status() are undefined.
8874**
8875** See also: [sqlite3_db_status()]
8876*/
8877SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
8878SQLITE_API int sqlite3_status64(
8879  int op,
8880  sqlite3_int64 *pCurrent,
8881  sqlite3_int64 *pHighwater,
8882  int resetFlag
8883);
8884
8885
8886/*
8887** CAPI3REF: Status Parameters
8888** KEYWORDS: {status parameters}
8889**
8890** These integer constants designate various run-time status parameters
8891** that can be returned by [sqlite3_status()].
8892**
8893** <dl>
8894** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
8895** <dd>This parameter is the current amount of memory checked out
8896** using [sqlite3_malloc()], either directly or indirectly.  The
8897** figure includes calls made to [sqlite3_malloc()] by the application
8898** and internal memory usage by the SQLite library.  Auxiliary page-cache
8899** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
8900** this parameter.  The amount returned is the sum of the allocation
8901** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
8902**
8903** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
8904** <dd>This parameter records the largest memory allocation request
8905** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
8906** internal equivalents).  Only the value returned in the
8907** *pHighwater parameter to [sqlite3_status()] is of interest.
8908** The value written into the *pCurrent parameter is undefined.</dd>)^
8909**
8910** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
8911** <dd>This parameter records the number of separate memory allocations
8912** currently checked out.</dd>)^
8913**
8914** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
8915** <dd>This parameter returns the number of pages used out of the
8916** [pagecache memory allocator] that was configured using
8917** [SQLITE_CONFIG_PAGECACHE].  The
8918** value returned is in pages, not in bytes.</dd>)^
8919**
8920** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
8921** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
8922** <dd>This parameter returns the number of bytes of page cache
8923** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
8924** buffer and where forced to overflow to [sqlite3_malloc()].  The
8925** returned value includes allocations that overflowed because they
8926** where too large (they were larger than the "sz" parameter to
8927** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
8928** no space was left in the page cache.</dd>)^
8929**
8930** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
8931** <dd>This parameter records the largest memory allocation request
8932** handed to the [pagecache memory allocator].  Only the value returned in the
8933** *pHighwater parameter to [sqlite3_status()] is of interest.
8934** The value written into the *pCurrent parameter is undefined.</dd>)^
8935**
8936** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
8937** <dd>No longer used.</dd>
8938**
8939** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
8940** <dd>No longer used.</dd>
8941**
8942** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
8943** <dd>No longer used.</dd>
8944**
8945** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
8946** <dd>The *pHighwater parameter records the deepest parser stack.
8947** The *pCurrent value is undefined.  The *pHighwater value is only
8948** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
8949** </dl>
8950**
8951** New status parameters may be added from time to time.
8952*/
8953#define SQLITE_STATUS_MEMORY_USED          0
8954#define SQLITE_STATUS_PAGECACHE_USED       1
8955#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
8956#define SQLITE_STATUS_SCRATCH_USED         3  /* NOT USED */
8957#define SQLITE_STATUS_SCRATCH_OVERFLOW     4  /* NOT USED */
8958#define SQLITE_STATUS_MALLOC_SIZE          5
8959#define SQLITE_STATUS_PARSER_STACK         6
8960#define SQLITE_STATUS_PAGECACHE_SIZE       7
8961#define SQLITE_STATUS_SCRATCH_SIZE         8  /* NOT USED */
8962#define SQLITE_STATUS_MALLOC_COUNT         9
8963
8964/*
8965** CAPI3REF: Database Connection Status
8966** METHOD: sqlite3
8967**
8968** ^This interface is used to retrieve runtime status information
8969** about a single [database connection].  ^The first argument is the
8970** database connection object to be interrogated.  ^The second argument
8971** is an integer constant, taken from the set of
8972** [SQLITE_DBSTATUS options], that
8973** determines the parameter to interrogate.  The set of
8974** [SQLITE_DBSTATUS options] is likely
8975** to grow in future releases of SQLite.
8976**
8977** ^The current value of the requested parameter is written into *pCur
8978** and the highest instantaneous value is written into *pHiwtr.  ^If
8979** the resetFlg is true, then the highest instantaneous value is
8980** reset back down to the current value.
8981**
8982** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
8983** non-zero [error code] on failure.
8984**
8985** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
8986*/
8987SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
8988
8989/*
8990** CAPI3REF: Status Parameters for database connections
8991** KEYWORDS: {SQLITE_DBSTATUS options}
8992**
8993** These constants are the available integer "verbs" that can be passed as
8994** the second argument to the [sqlite3_db_status()] interface.
8995**
8996** New verbs may be added in future releases of SQLite. Existing verbs
8997** might be discontinued. Applications should check the return code from
8998** [sqlite3_db_status()] to make sure that the call worked.
8999** The [sqlite3_db_status()] interface will return a non-zero error code
9000** if a discontinued or unsupported verb is invoked.
9001**
9002** <dl>
9003** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
9004** <dd>This parameter returns the number of lookaside memory slots currently
9005** checked out.</dd>)^
9006**
9007** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
9008** <dd>This parameter returns the number of malloc attempts that were
9009** satisfied using lookaside memory. Only the high-water value is meaningful;
9010** the current value is always zero.)^
9011**
9012** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
9013** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
9014** <dd>This parameter returns the number malloc attempts that might have
9015** been satisfied using lookaside memory but failed due to the amount of
9016** memory requested being larger than the lookaside slot size.
9017** Only the high-water value is meaningful;
9018** the current value is always zero.)^
9019**
9020** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
9021** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
9022** <dd>This parameter returns the number malloc attempts that might have
9023** been satisfied using lookaside memory but failed due to all lookaside
9024** memory already being in use.
9025** Only the high-water value is meaningful;
9026** the current value is always zero.)^
9027**
9028** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
9029** <dd>This parameter returns the approximate number of bytes of heap
9030** memory used by all pager caches associated with the database connection.)^
9031** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
9032**
9033** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
9034** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
9035** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
9036** pager cache is shared between two or more connections the bytes of heap
9037** memory used by that pager cache is divided evenly between the attached
9038** connections.)^  In other words, if none of the pager caches associated
9039** with the database connection are shared, this request returns the same
9040** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
9041** shared, the value returned by this call will be smaller than that returned
9042** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
9043** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
9044**
9045** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
9046** <dd>This parameter returns the approximate number of bytes of heap
9047** memory used to store the schema for all databases associated
9048** with the connection - main, temp, and any [ATTACH]-ed databases.)^
9049** ^The full amount of memory used by the schemas is reported, even if the
9050** schema memory is shared with other database connections due to
9051** [shared cache mode] being enabled.
9052** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
9053**
9054** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
9055** <dd>This parameter returns the approximate number of bytes of heap
9056** and lookaside memory used by all prepared statements associated with
9057** the database connection.)^
9058** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
9059** </dd>
9060**
9061** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
9062** <dd>This parameter returns the number of pager cache hits that have
9063** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
9064** is always 0.
9065** </dd>
9066**
9067** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
9068** <dd>This parameter returns the number of pager cache misses that have
9069** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
9070** is always 0.
9071** </dd>
9072**
9073** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
9074** <dd>This parameter returns the number of dirty cache entries that have
9075** been written to disk. Specifically, the number of pages written to the
9076** wal file in wal mode databases, or the number of pages written to the
9077** database file in rollback mode databases. Any pages written as part of
9078** transaction rollback or database recovery operations are not included.
9079** If an IO or other error occurs while writing a page to disk, the effect
9080** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
9081** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
9082** </dd>
9083**
9084** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>
9085** <dd>This parameter returns the number of dirty cache entries that have
9086** been written to disk in the middle of a transaction due to the page
9087** cache overflowing. Transactions are more efficient if they are written
9088** to disk all at once. When pages spill mid-transaction, that introduces
9089** additional overhead. This parameter can be used help identify
9090** inefficiencies that can be resolved by increasing the cache size.
9091** </dd>
9092**
9093** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
9094** <dd>This parameter returns zero for the current value if and only if
9095** all foreign key constraints (deferred or immediate) have been
9096** resolved.)^  ^The highwater mark is always 0.
9097** </dd>
9098** </dl>
9099*/
9100#define SQLITE_DBSTATUS_LOOKASIDE_USED       0
9101#define SQLITE_DBSTATUS_CACHE_USED           1
9102#define SQLITE_DBSTATUS_SCHEMA_USED          2
9103#define SQLITE_DBSTATUS_STMT_USED            3
9104#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
9105#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
9106#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
9107#define SQLITE_DBSTATUS_CACHE_HIT            7
9108#define SQLITE_DBSTATUS_CACHE_MISS           8
9109#define SQLITE_DBSTATUS_CACHE_WRITE          9
9110#define SQLITE_DBSTATUS_DEFERRED_FKS        10
9111#define SQLITE_DBSTATUS_CACHE_USED_SHARED   11
9112#define SQLITE_DBSTATUS_CACHE_SPILL         12
9113#define SQLITE_DBSTATUS_MAX                 12   /* Largest defined DBSTATUS */
9114
9115
9116/*
9117** CAPI3REF: Prepared Statement Status
9118** METHOD: sqlite3_stmt
9119**
9120** ^(Each prepared statement maintains various
9121** [SQLITE_STMTSTATUS counters] that measure the number
9122** of times it has performed specific operations.)^  These counters can
9123** be used to monitor the performance characteristics of the prepared
9124** statements.  For example, if the number of table steps greatly exceeds
9125** the number of table searches or result rows, that would tend to indicate
9126** that the prepared statement is using a full table scan rather than
9127** an index.
9128**
9129** ^(This interface is used to retrieve and reset counter values from
9130** a [prepared statement].  The first argument is the prepared statement
9131** object to be interrogated.  The second argument
9132** is an integer code for a specific [SQLITE_STMTSTATUS counter]
9133** to be interrogated.)^
9134** ^The current value of the requested counter is returned.
9135** ^If the resetFlg is true, then the counter is reset to zero after this
9136** interface call returns.
9137**
9138** See also: [sqlite3_status()] and [sqlite3_db_status()].
9139*/
9140SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
9141
9142/*
9143** CAPI3REF: Status Parameters for prepared statements
9144** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
9145**
9146** These preprocessor macros define integer codes that name counter
9147** values associated with the [sqlite3_stmt_status()] interface.
9148** The meanings of the various counters are as follows:
9149**
9150** <dl>
9151** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
9152** <dd>^This is the number of times that SQLite has stepped forward in
9153** a table as part of a full table scan.  Large numbers for this counter
9154** may indicate opportunities for performance improvement through
9155** careful use of indices.</dd>
9156**
9157** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
9158** <dd>^This is the number of sort operations that have occurred.
9159** A non-zero value in this counter may indicate an opportunity to
9160** improvement performance through careful use of indices.</dd>
9161**
9162** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
9163** <dd>^This is the number of rows inserted into transient indices that
9164** were created automatically in order to help joins run faster.
9165** A non-zero value in this counter may indicate an opportunity to
9166** improvement performance by adding permanent indices that do not
9167** need to be reinitialized each time the statement is run.</dd>
9168**
9169** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
9170** <dd>^This is the number of virtual machine operations executed
9171** by the prepared statement if that number is less than or equal
9172** to 2147483647.  The number of virtual machine operations can be
9173** used as a proxy for the total work done by the prepared statement.
9174** If the number of virtual machine operations exceeds 2147483647
9175** then the value returned by this statement status code is undefined.
9176**
9177** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
9178** <dd>^This is the number of times that the prepare statement has been
9179** automatically regenerated due to schema changes or changes to
9180** [bound parameters] that might affect the query plan.
9181**
9182** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
9183** <dd>^This is the number of times that the prepared statement has
9184** been run.  A single "run" for the purposes of this counter is one
9185** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
9186** The counter is incremented on the first [sqlite3_step()] call of each
9187** cycle.
9188**
9189** [[SQLITE_STMTSTATUS_FILTER_MISS]]
9190** [[SQLITE_STMTSTATUS_FILTER HIT]]
9191** <dt>SQLITE_STMTSTATUS_FILTER_HIT<br>
9192** SQLITE_STMTSTATUS_FILTER_MISS</dt>
9193** <dd>^SQLITE_STMTSTATUS_FILTER_HIT is the number of times that a join
9194** step was bypassed because a Bloom filter returned not-found.  The
9195** corresponding SQLITE_STMTSTATUS_FILTER_MISS value is the number of
9196** times that the Bloom filter returned a find, and thus the join step
9197** had to be processed as normal.
9198**
9199** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
9200** <dd>^This is the approximate number of bytes of heap memory
9201** used to store the prepared statement.  ^This value is not actually
9202** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
9203** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
9204** </dd>
9205** </dl>
9206*/
9207#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
9208#define SQLITE_STMTSTATUS_SORT              2
9209#define SQLITE_STMTSTATUS_AUTOINDEX         3
9210#define SQLITE_STMTSTATUS_VM_STEP           4
9211#define SQLITE_STMTSTATUS_REPREPARE         5
9212#define SQLITE_STMTSTATUS_RUN               6
9213#define SQLITE_STMTSTATUS_FILTER_MISS       7
9214#define SQLITE_STMTSTATUS_FILTER_HIT        8
9215#define SQLITE_STMTSTATUS_MEMUSED           99
9216
9217/*
9218** CAPI3REF: Custom Page Cache Object
9219**
9220** The sqlite3_pcache type is opaque.  It is implemented by
9221** the pluggable module.  The SQLite core has no knowledge of
9222** its size or internal structure and never deals with the
9223** sqlite3_pcache object except by holding and passing pointers
9224** to the object.
9225**
9226** See [sqlite3_pcache_methods2] for additional information.
9227*/
9228typedef struct sqlite3_pcache sqlite3_pcache;
9229
9230/*
9231** CAPI3REF: Custom Page Cache Object
9232**
9233** The sqlite3_pcache_page object represents a single page in the
9234** page cache.  The page cache will allocate instances of this
9235** object.  Various methods of the page cache use pointers to instances
9236** of this object as parameters or as their return value.
9237**
9238** See [sqlite3_pcache_methods2] for additional information.
9239*/
9240typedef struct sqlite3_pcache_page sqlite3_pcache_page;
9241struct sqlite3_pcache_page {
9242  void *pBuf;        /* The content of the page */
9243  void *pExtra;      /* Extra information associated with the page */
9244};
9245
9246/*
9247** CAPI3REF: Application Defined Page Cache.
9248** KEYWORDS: {page cache}
9249**
9250** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
9251** register an alternative page cache implementation by passing in an
9252** instance of the sqlite3_pcache_methods2 structure.)^
9253** In many applications, most of the heap memory allocated by
9254** SQLite is used for the page cache.
9255** By implementing a
9256** custom page cache using this API, an application can better control
9257** the amount of memory consumed by SQLite, the way in which
9258** that memory is allocated and released, and the policies used to
9259** determine exactly which parts of a database file are cached and for
9260** how long.
9261**
9262** The alternative page cache mechanism is an
9263** extreme measure that is only needed by the most demanding applications.
9264** The built-in page cache is recommended for most uses.
9265**
9266** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
9267** internal buffer by SQLite within the call to [sqlite3_config].  Hence
9268** the application may discard the parameter after the call to
9269** [sqlite3_config()] returns.)^
9270**
9271** [[the xInit() page cache method]]
9272** ^(The xInit() method is called once for each effective
9273** call to [sqlite3_initialize()])^
9274** (usually only once during the lifetime of the process). ^(The xInit()
9275** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
9276** The intent of the xInit() method is to set up global data structures
9277** required by the custom page cache implementation.
9278** ^(If the xInit() method is NULL, then the
9279** built-in default page cache is used instead of the application defined
9280** page cache.)^
9281**
9282** [[the xShutdown() page cache method]]
9283** ^The xShutdown() method is called by [sqlite3_shutdown()].
9284** It can be used to clean up
9285** any outstanding resources before process shutdown, if required.
9286** ^The xShutdown() method may be NULL.
9287**
9288** ^SQLite automatically serializes calls to the xInit method,
9289** so the xInit method need not be threadsafe.  ^The
9290** xShutdown method is only called from [sqlite3_shutdown()] so it does
9291** not need to be threadsafe either.  All other methods must be threadsafe
9292** in multithreaded applications.
9293**
9294** ^SQLite will never invoke xInit() more than once without an intervening
9295** call to xShutdown().
9296**
9297** [[the xCreate() page cache methods]]
9298** ^SQLite invokes the xCreate() method to construct a new cache instance.
9299** SQLite will typically create one cache instance for each open database file,
9300** though this is not guaranteed. ^The
9301** first parameter, szPage, is the size in bytes of the pages that must
9302** be allocated by the cache.  ^szPage will always a power of two.  ^The
9303** second parameter szExtra is a number of bytes of extra storage
9304** associated with each page cache entry.  ^The szExtra parameter will
9305** a number less than 250.  SQLite will use the
9306** extra szExtra bytes on each page to store metadata about the underlying
9307** database page on disk.  The value passed into szExtra depends
9308** on the SQLite version, the target platform, and how SQLite was compiled.
9309** ^The third argument to xCreate(), bPurgeable, is true if the cache being
9310** created will be used to cache database pages of a file stored on disk, or
9311** false if it is used for an in-memory database. The cache implementation
9312** does not have to do anything special based with the value of bPurgeable;
9313** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
9314** never invoke xUnpin() except to deliberately delete a page.
9315** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
9316** false will always have the "discard" flag set to true.
9317** ^Hence, a cache created with bPurgeable false will
9318** never contain any unpinned pages.
9319**
9320** [[the xCachesize() page cache method]]
9321** ^(The xCachesize() method may be called at any time by SQLite to set the
9322** suggested maximum cache-size (number of pages stored by) the cache
9323** instance passed as the first argument. This is the value configured using
9324** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
9325** parameter, the implementation is not required to do anything with this
9326** value; it is advisory only.
9327**
9328** [[the xPagecount() page cache methods]]
9329** The xPagecount() method must return the number of pages currently
9330** stored in the cache, both pinned and unpinned.
9331**
9332** [[the xFetch() page cache methods]]
9333** The xFetch() method locates a page in the cache and returns a pointer to
9334** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
9335** The pBuf element of the returned sqlite3_pcache_page object will be a
9336** pointer to a buffer of szPage bytes used to store the content of a
9337** single database page.  The pExtra element of sqlite3_pcache_page will be
9338** a pointer to the szExtra bytes of extra storage that SQLite has requested
9339** for each entry in the page cache.
9340**
9341** The page to be fetched is determined by the key. ^The minimum key value
9342** is 1.  After it has been retrieved using xFetch, the page is considered
9343** to be "pinned".
9344**
9345** If the requested page is already in the page cache, then the page cache
9346** implementation must return a pointer to the page buffer with its content
9347** intact.  If the requested page is not already in the cache, then the
9348** cache implementation should use the value of the createFlag
9349** parameter to help it determined what action to take:
9350**
9351** <table border=1 width=85% align=center>
9352** <tr><th> createFlag <th> Behavior when page is not already in cache
9353** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
9354** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
9355**                 Otherwise return NULL.
9356** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
9357**                 NULL if allocating a new page is effectively impossible.
9358** </table>
9359**
9360** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
9361** will only use a createFlag of 2 after a prior call with a createFlag of 1
9362** failed.)^  In between the xFetch() calls, SQLite may
9363** attempt to unpin one or more cache pages by spilling the content of
9364** pinned pages to disk and synching the operating system disk cache.
9365**
9366** [[the xUnpin() page cache method]]
9367** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
9368** as its second argument.  If the third parameter, discard, is non-zero,
9369** then the page must be evicted from the cache.
9370** ^If the discard parameter is
9371** zero, then the page may be discarded or retained at the discretion of
9372** page cache implementation. ^The page cache implementation
9373** may choose to evict unpinned pages at any time.
9374**
9375** The cache must not perform any reference counting. A single
9376** call to xUnpin() unpins the page regardless of the number of prior calls
9377** to xFetch().
9378**
9379** [[the xRekey() page cache methods]]
9380** The xRekey() method is used to change the key value associated with the
9381** page passed as the second argument. If the cache
9382** previously contains an entry associated with newKey, it must be
9383** discarded. ^Any prior cache entry associated with newKey is guaranteed not
9384** to be pinned.
9385**
9386** When SQLite calls the xTruncate() method, the cache must discard all
9387** existing cache entries with page numbers (keys) greater than or equal
9388** to the value of the iLimit parameter passed to xTruncate(). If any
9389** of these pages are pinned, they are implicitly unpinned, meaning that
9390** they can be safely discarded.
9391**
9392** [[the xDestroy() page cache method]]
9393** ^The xDestroy() method is used to delete a cache allocated by xCreate().
9394** All resources associated with the specified cache should be freed. ^After
9395** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
9396** handle invalid, and will not use it with any other sqlite3_pcache_methods2
9397** functions.
9398**
9399** [[the xShrink() page cache method]]
9400** ^SQLite invokes the xShrink() method when it wants the page cache to
9401** free up as much of heap memory as possible.  The page cache implementation
9402** is not obligated to free any memory, but well-behaved implementations should
9403** do their best.
9404*/
9405typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
9406struct sqlite3_pcache_methods2 {
9407  int iVersion;
9408  void *pArg;
9409  int (*xInit)(void*);
9410  void (*xShutdown)(void*);
9411  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
9412  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
9413  int (*xPagecount)(sqlite3_pcache*);
9414  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
9415  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
9416  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
9417      unsigned oldKey, unsigned newKey);
9418  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
9419  void (*xDestroy)(sqlite3_pcache*);
9420  void (*xShrink)(sqlite3_pcache*);
9421};
9422
9423/*
9424** This is the obsolete pcache_methods object that has now been replaced
9425** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
9426** retained in the header file for backwards compatibility only.
9427*/
9428typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
9429struct sqlite3_pcache_methods {
9430  void *pArg;
9431  int (*xInit)(void*);
9432  void (*xShutdown)(void*);
9433  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
9434  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
9435  int (*xPagecount)(sqlite3_pcache*);
9436  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
9437  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
9438  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
9439  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
9440  void (*xDestroy)(sqlite3_pcache*);
9441};
9442
9443
9444/*
9445** CAPI3REF: Online Backup Object
9446**
9447** The sqlite3_backup object records state information about an ongoing
9448** online backup operation.  ^The sqlite3_backup object is created by
9449** a call to [sqlite3_backup_init()] and is destroyed by a call to
9450** [sqlite3_backup_finish()].
9451**
9452** See Also: [Using the SQLite Online Backup API]
9453*/
9454typedef struct sqlite3_backup sqlite3_backup;
9455
9456/*
9457** CAPI3REF: Online Backup API.
9458**
9459** The backup API copies the content of one database into another.
9460** It is useful either for creating backups of databases or
9461** for copying in-memory databases to or from persistent files.
9462**
9463** See Also: [Using the SQLite Online Backup API]
9464**
9465** ^SQLite holds a write transaction open on the destination database file
9466** for the duration of the backup operation.
9467** ^The source database is read-locked only while it is being read;
9468** it is not locked continuously for the entire backup operation.
9469** ^Thus, the backup may be performed on a live source database without
9470** preventing other database connections from
9471** reading or writing to the source database while the backup is underway.
9472**
9473** ^(To perform a backup operation:
9474**   <ol>
9475**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
9476**         backup,
9477**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
9478**         the data between the two databases, and finally
9479**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
9480**         associated with the backup operation.
9481**   </ol>)^
9482** There should be exactly one call to sqlite3_backup_finish() for each
9483** successful call to sqlite3_backup_init().
9484**
9485** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
9486**
9487** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
9488** [database connection] associated with the destination database
9489** and the database name, respectively.
9490** ^The database name is "main" for the main database, "temp" for the
9491** temporary database, or the name specified after the AS keyword in
9492** an [ATTACH] statement for an attached database.
9493** ^The S and M arguments passed to
9494** sqlite3_backup_init(D,N,S,M) identify the [database connection]
9495** and database name of the source database, respectively.
9496** ^The source and destination [database connections] (parameters S and D)
9497** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
9498** an error.
9499**
9500** ^A call to sqlite3_backup_init() will fail, returning NULL, if
9501** there is already a read or read-write transaction open on the
9502** destination database.
9503**
9504** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
9505** returned and an error code and error message are stored in the
9506** destination [database connection] D.
9507** ^The error code and message for the failed call to sqlite3_backup_init()
9508** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
9509** [sqlite3_errmsg16()] functions.
9510** ^A successful call to sqlite3_backup_init() returns a pointer to an
9511** [sqlite3_backup] object.
9512** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
9513** sqlite3_backup_finish() functions to perform the specified backup
9514** operation.
9515**
9516** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
9517**
9518** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
9519** the source and destination databases specified by [sqlite3_backup] object B.
9520** ^If N is negative, all remaining source pages are copied.
9521** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
9522** are still more pages to be copied, then the function returns [SQLITE_OK].
9523** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
9524** from source to destination, then it returns [SQLITE_DONE].
9525** ^If an error occurs while running sqlite3_backup_step(B,N),
9526** then an [error code] is returned. ^As well as [SQLITE_OK] and
9527** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
9528** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
9529** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
9530**
9531** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
9532** <ol>
9533** <li> the destination database was opened read-only, or
9534** <li> the destination database is using write-ahead-log journaling
9535** and the destination and source page sizes differ, or
9536** <li> the destination database is an in-memory database and the
9537** destination and source page sizes differ.
9538** </ol>)^
9539**
9540** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
9541** the [sqlite3_busy_handler | busy-handler function]
9542** is invoked (if one is specified). ^If the
9543** busy-handler returns non-zero before the lock is available, then
9544** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
9545** sqlite3_backup_step() can be retried later. ^If the source
9546** [database connection]
9547** is being used to write to the source database when sqlite3_backup_step()
9548** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
9549** case the call to sqlite3_backup_step() can be retried later on. ^(If
9550** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
9551** [SQLITE_READONLY] is returned, then
9552** there is no point in retrying the call to sqlite3_backup_step(). These
9553** errors are considered fatal.)^  The application must accept
9554** that the backup operation has failed and pass the backup operation handle
9555** to the sqlite3_backup_finish() to release associated resources.
9556**
9557** ^The first call to sqlite3_backup_step() obtains an exclusive lock
9558** on the destination file. ^The exclusive lock is not released until either
9559** sqlite3_backup_finish() is called or the backup operation is complete
9560** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
9561** sqlite3_backup_step() obtains a [shared lock] on the source database that
9562** lasts for the duration of the sqlite3_backup_step() call.
9563** ^Because the source database is not locked between calls to
9564** sqlite3_backup_step(), the source database may be modified mid-way
9565** through the backup process.  ^If the source database is modified by an
9566** external process or via a database connection other than the one being
9567** used by the backup operation, then the backup will be automatically
9568** restarted by the next call to sqlite3_backup_step(). ^If the source
9569** database is modified by the using the same database connection as is used
9570** by the backup operation, then the backup database is automatically
9571** updated at the same time.
9572**
9573** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
9574**
9575** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
9576** application wishes to abandon the backup operation, the application
9577** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
9578** ^The sqlite3_backup_finish() interfaces releases all
9579** resources associated with the [sqlite3_backup] object.
9580** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
9581** active write-transaction on the destination database is rolled back.
9582** The [sqlite3_backup] object is invalid
9583** and may not be used following a call to sqlite3_backup_finish().
9584**
9585** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
9586** sqlite3_backup_step() errors occurred, regardless or whether or not
9587** sqlite3_backup_step() completed.
9588** ^If an out-of-memory condition or IO error occurred during any prior
9589** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
9590** sqlite3_backup_finish() returns the corresponding [error code].
9591**
9592** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
9593** is not a permanent error and does not affect the return value of
9594** sqlite3_backup_finish().
9595**
9596** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
9597** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
9598**
9599** ^The sqlite3_backup_remaining() routine returns the number of pages still
9600** to be backed up at the conclusion of the most recent sqlite3_backup_step().
9601** ^The sqlite3_backup_pagecount() routine returns the total number of pages
9602** in the source database at the conclusion of the most recent
9603** sqlite3_backup_step().
9604** ^(The values returned by these functions are only updated by
9605** sqlite3_backup_step(). If the source database is modified in a way that
9606** changes the size of the source database or the number of pages remaining,
9607** those changes are not reflected in the output of sqlite3_backup_pagecount()
9608** and sqlite3_backup_remaining() until after the next
9609** sqlite3_backup_step().)^
9610**
9611** <b>Concurrent Usage of Database Handles</b>
9612**
9613** ^The source [database connection] may be used by the application for other
9614** purposes while a backup operation is underway or being initialized.
9615** ^If SQLite is compiled and configured to support threadsafe database
9616** connections, then the source database connection may be used concurrently
9617** from within other threads.
9618**
9619** However, the application must guarantee that the destination
9620** [database connection] is not passed to any other API (by any thread) after
9621** sqlite3_backup_init() is called and before the corresponding call to
9622** sqlite3_backup_finish().  SQLite does not currently check to see
9623** if the application incorrectly accesses the destination [database connection]
9624** and so no error code is reported, but the operations may malfunction
9625** nevertheless.  Use of the destination database connection while a
9626** backup is in progress might also cause a mutex deadlock.
9627**
9628** If running in [shared cache mode], the application must
9629** guarantee that the shared cache used by the destination database
9630** is not accessed while the backup is running. In practice this means
9631** that the application must guarantee that the disk file being
9632** backed up to is not accessed by any connection within the process,
9633** not just the specific connection that was passed to sqlite3_backup_init().
9634**
9635** The [sqlite3_backup] object itself is partially threadsafe. Multiple
9636** threads may safely make multiple concurrent calls to sqlite3_backup_step().
9637** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
9638** APIs are not strictly speaking threadsafe. If they are invoked at the
9639** same time as another thread is invoking sqlite3_backup_step() it is
9640** possible that they return invalid values.
9641*/
9642SQLITE_API sqlite3_backup *sqlite3_backup_init(
9643  sqlite3 *pDest,                        /* Destination database handle */
9644  const char *zDestName,                 /* Destination database name */
9645  sqlite3 *pSource,                      /* Source database handle */
9646  const char *zSourceName                /* Source database name */
9647);
9648SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
9649SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
9650SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
9651SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
9652
9653/*
9654** CAPI3REF: Unlock Notification
9655** METHOD: sqlite3
9656**
9657** ^When running in shared-cache mode, a database operation may fail with
9658** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
9659** individual tables within the shared-cache cannot be obtained. See
9660** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
9661** ^This API may be used to register a callback that SQLite will invoke
9662** when the connection currently holding the required lock relinquishes it.
9663** ^This API is only available if the library was compiled with the
9664** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
9665**
9666** See Also: [Using the SQLite Unlock Notification Feature].
9667**
9668** ^Shared-cache locks are released when a database connection concludes
9669** its current transaction, either by committing it or rolling it back.
9670**
9671** ^When a connection (known as the blocked connection) fails to obtain a
9672** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
9673** identity of the database connection (the blocking connection) that
9674** has locked the required resource is stored internally. ^After an
9675** application receives an SQLITE_LOCKED error, it may call the
9676** sqlite3_unlock_notify() method with the blocked connection handle as
9677** the first argument to register for a callback that will be invoked
9678** when the blocking connections current transaction is concluded. ^The
9679** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
9680** call that concludes the blocking connection's transaction.
9681**
9682** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
9683** there is a chance that the blocking connection will have already
9684** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
9685** If this happens, then the specified callback is invoked immediately,
9686** from within the call to sqlite3_unlock_notify().)^
9687**
9688** ^If the blocked connection is attempting to obtain a write-lock on a
9689** shared-cache table, and more than one other connection currently holds
9690** a read-lock on the same table, then SQLite arbitrarily selects one of
9691** the other connections to use as the blocking connection.
9692**
9693** ^(There may be at most one unlock-notify callback registered by a
9694** blocked connection. If sqlite3_unlock_notify() is called when the
9695** blocked connection already has a registered unlock-notify callback,
9696** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
9697** called with a NULL pointer as its second argument, then any existing
9698** unlock-notify callback is canceled. ^The blocked connections
9699** unlock-notify callback may also be canceled by closing the blocked
9700** connection using [sqlite3_close()].
9701**
9702** The unlock-notify callback is not reentrant. If an application invokes
9703** any sqlite3_xxx API functions from within an unlock-notify callback, a
9704** crash or deadlock may be the result.
9705**
9706** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
9707** returns SQLITE_OK.
9708**
9709** <b>Callback Invocation Details</b>
9710**
9711** When an unlock-notify callback is registered, the application provides a
9712** single void* pointer that is passed to the callback when it is invoked.
9713** However, the signature of the callback function allows SQLite to pass
9714** it an array of void* context pointers. The first argument passed to
9715** an unlock-notify callback is a pointer to an array of void* pointers,
9716** and the second is the number of entries in the array.
9717**
9718** When a blocking connection's transaction is concluded, there may be
9719** more than one blocked connection that has registered for an unlock-notify
9720** callback. ^If two or more such blocked connections have specified the
9721** same callback function, then instead of invoking the callback function
9722** multiple times, it is invoked once with the set of void* context pointers
9723** specified by the blocked connections bundled together into an array.
9724** This gives the application an opportunity to prioritize any actions
9725** related to the set of unblocked database connections.
9726**
9727** <b>Deadlock Detection</b>
9728**
9729** Assuming that after registering for an unlock-notify callback a
9730** database waits for the callback to be issued before taking any further
9731** action (a reasonable assumption), then using this API may cause the
9732** application to deadlock. For example, if connection X is waiting for
9733** connection Y's transaction to be concluded, and similarly connection
9734** Y is waiting on connection X's transaction, then neither connection
9735** will proceed and the system may remain deadlocked indefinitely.
9736**
9737** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
9738** detection. ^If a given call to sqlite3_unlock_notify() would put the
9739** system in a deadlocked state, then SQLITE_LOCKED is returned and no
9740** unlock-notify callback is registered. The system is said to be in
9741** a deadlocked state if connection A has registered for an unlock-notify
9742** callback on the conclusion of connection B's transaction, and connection
9743** B has itself registered for an unlock-notify callback when connection
9744** A's transaction is concluded. ^Indirect deadlock is also detected, so
9745** the system is also considered to be deadlocked if connection B has
9746** registered for an unlock-notify callback on the conclusion of connection
9747** C's transaction, where connection C is waiting on connection A. ^Any
9748** number of levels of indirection are allowed.
9749**
9750** <b>The "DROP TABLE" Exception</b>
9751**
9752** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
9753** always appropriate to call sqlite3_unlock_notify(). There is however,
9754** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
9755** SQLite checks if there are any currently executing SELECT statements
9756** that belong to the same connection. If there are, SQLITE_LOCKED is
9757** returned. In this case there is no "blocking connection", so invoking
9758** sqlite3_unlock_notify() results in the unlock-notify callback being
9759** invoked immediately. If the application then re-attempts the "DROP TABLE"
9760** or "DROP INDEX" query, an infinite loop might be the result.
9761**
9762** One way around this problem is to check the extended error code returned
9763** by an sqlite3_step() call. ^(If there is a blocking connection, then the
9764** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
9765** the special "DROP TABLE/INDEX" case, the extended error code is just
9766** SQLITE_LOCKED.)^
9767*/
9768SQLITE_API int sqlite3_unlock_notify(
9769  sqlite3 *pBlocked,                          /* Waiting connection */
9770  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
9771  void *pNotifyArg                            /* Argument to pass to xNotify */
9772);
9773
9774
9775/*
9776** CAPI3REF: String Comparison
9777**
9778** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
9779** and extensions to compare the contents of two buffers containing UTF-8
9780** strings in a case-independent fashion, using the same definition of "case
9781** independence" that SQLite uses internally when comparing identifiers.
9782*/
9783SQLITE_API int sqlite3_stricmp(const char *, const char *);
9784SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
9785
9786/*
9787** CAPI3REF: String Globbing
9788*
9789** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
9790** string X matches the [GLOB] pattern P.
9791** ^The definition of [GLOB] pattern matching used in
9792** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
9793** SQL dialect understood by SQLite.  ^The [sqlite3_strglob(P,X)] function
9794** is case sensitive.
9795**
9796** Note that this routine returns zero on a match and non-zero if the strings
9797** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
9798**
9799** See also: [sqlite3_strlike()].
9800*/
9801SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
9802
9803/*
9804** CAPI3REF: String LIKE Matching
9805*
9806** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
9807** string X matches the [LIKE] pattern P with escape character E.
9808** ^The definition of [LIKE] pattern matching used in
9809** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
9810** operator in the SQL dialect understood by SQLite.  ^For "X LIKE P" without
9811** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
9812** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
9813** insensitive - equivalent upper and lower case ASCII characters match
9814** one another.
9815**
9816** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
9817** only ASCII characters are case folded.
9818**
9819** Note that this routine returns zero on a match and non-zero if the strings
9820** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
9821**
9822** See also: [sqlite3_strglob()].
9823*/
9824SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
9825
9826/*
9827** CAPI3REF: Error Logging Interface
9828**
9829** ^The [sqlite3_log()] interface writes a message into the [error log]
9830** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
9831** ^If logging is enabled, the zFormat string and subsequent arguments are
9832** used with [sqlite3_snprintf()] to generate the final output string.
9833**
9834** The sqlite3_log() interface is intended for use by extensions such as
9835** virtual tables, collating functions, and SQL functions.  While there is
9836** nothing to prevent an application from calling sqlite3_log(), doing so
9837** is considered bad form.
9838**
9839** The zFormat string must not be NULL.
9840**
9841** To avoid deadlocks and other threading problems, the sqlite3_log() routine
9842** will not use dynamically allocated memory.  The log message is stored in
9843** a fixed-length buffer on the stack.  If the log message is longer than
9844** a few hundred characters, it will be truncated to the length of the
9845** buffer.
9846*/
9847SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
9848
9849/*
9850** CAPI3REF: Write-Ahead Log Commit Hook
9851** METHOD: sqlite3
9852**
9853** ^The [sqlite3_wal_hook()] function is used to register a callback that
9854** is invoked each time data is committed to a database in wal mode.
9855**
9856** ^(The callback is invoked by SQLite after the commit has taken place and
9857** the associated write-lock on the database released)^, so the implementation
9858** may read, write or [checkpoint] the database as required.
9859**
9860** ^The first parameter passed to the callback function when it is invoked
9861** is a copy of the third parameter passed to sqlite3_wal_hook() when
9862** registering the callback. ^The second is a copy of the database handle.
9863** ^The third parameter is the name of the database that was written to -
9864** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
9865** is the number of pages currently in the write-ahead log file,
9866** including those that were just committed.
9867**
9868** The callback function should normally return [SQLITE_OK].  ^If an error
9869** code is returned, that error will propagate back up through the
9870** SQLite code base to cause the statement that provoked the callback
9871** to report an error, though the commit will have still occurred. If the
9872** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
9873** that does not correspond to any valid SQLite error code, the results
9874** are undefined.
9875**
9876** A single database handle may have at most a single write-ahead log callback
9877** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
9878** previously registered write-ahead log callback. ^The return value is
9879** a copy of the third parameter from the previous call, if any, or 0.
9880** ^Note that the [sqlite3_wal_autocheckpoint()] interface and the
9881** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
9882** overwrite any prior [sqlite3_wal_hook()] settings.
9883*/
9884SQLITE_API void *sqlite3_wal_hook(
9885  sqlite3*,
9886  int(*)(void *,sqlite3*,const char*,int),
9887  void*
9888);
9889
9890/*
9891** CAPI3REF: Configure an auto-checkpoint
9892** METHOD: sqlite3
9893**
9894** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
9895** [sqlite3_wal_hook()] that causes any database on [database connection] D
9896** to automatically [checkpoint]
9897** after committing a transaction if there are N or
9898** more frames in the [write-ahead log] file.  ^Passing zero or
9899** a negative value as the nFrame parameter disables automatic
9900** checkpoints entirely.
9901**
9902** ^The callback registered by this function replaces any existing callback
9903** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
9904** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
9905** configured by this function.
9906**
9907** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
9908** from SQL.
9909**
9910** ^Checkpoints initiated by this mechanism are
9911** [sqlite3_wal_checkpoint_v2|PASSIVE].
9912**
9913** ^Every new [database connection] defaults to having the auto-checkpoint
9914** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
9915** pages.  The use of this interface
9916** is only necessary if the default setting is found to be suboptimal
9917** for a particular application.
9918*/
9919SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
9920
9921/*
9922** CAPI3REF: Checkpoint a database
9923** METHOD: sqlite3
9924**
9925** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
9926** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
9927**
9928** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
9929** [write-ahead log] for database X on [database connection] D to be
9930** transferred into the database file and for the write-ahead log to
9931** be reset.  See the [checkpointing] documentation for addition
9932** information.
9933**
9934** This interface used to be the only way to cause a checkpoint to
9935** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
9936** interface was added.  This interface is retained for backwards
9937** compatibility and as a convenience for applications that need to manually
9938** start a callback but which do not need the full power (and corresponding
9939** complication) of [sqlite3_wal_checkpoint_v2()].
9940*/
9941SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
9942
9943/*
9944** CAPI3REF: Checkpoint a database
9945** METHOD: sqlite3
9946**
9947** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
9948** operation on database X of [database connection] D in mode M.  Status
9949** information is written back into integers pointed to by L and C.)^
9950** ^(The M parameter must be a valid [checkpoint mode]:)^
9951**
9952** <dl>
9953** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
9954**   ^Checkpoint as many frames as possible without waiting for any database
9955**   readers or writers to finish, then sync the database file if all frames
9956**   in the log were checkpointed. ^The [busy-handler callback]
9957**   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
9958**   ^On the other hand, passive mode might leave the checkpoint unfinished
9959**   if there are concurrent readers or writers.
9960**
9961** <dt>SQLITE_CHECKPOINT_FULL<dd>
9962**   ^This mode blocks (it invokes the
9963**   [sqlite3_busy_handler|busy-handler callback]) until there is no
9964**   database writer and all readers are reading from the most recent database
9965**   snapshot. ^It then checkpoints all frames in the log file and syncs the
9966**   database file. ^This mode blocks new database writers while it is pending,
9967**   but new database readers are allowed to continue unimpeded.
9968**
9969** <dt>SQLITE_CHECKPOINT_RESTART<dd>
9970**   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
9971**   that after checkpointing the log file it blocks (calls the
9972**   [busy-handler callback])
9973**   until all readers are reading from the database file only. ^This ensures
9974**   that the next writer will restart the log file from the beginning.
9975**   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
9976**   database writer attempts while it is pending, but does not impede readers.
9977**
9978** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
9979**   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
9980**   addition that it also truncates the log file to zero bytes just prior
9981**   to a successful return.
9982** </dl>
9983**
9984** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
9985** the log file or to -1 if the checkpoint could not run because
9986** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
9987** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
9988** log file (including any that were already checkpointed before the function
9989** was called) or to -1 if the checkpoint could not run due to an error or
9990** because the database is not in WAL mode. ^Note that upon successful
9991** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
9992** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
9993**
9994** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
9995** any other process is running a checkpoint operation at the same time, the
9996** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
9997** busy-handler configured, it will not be invoked in this case.
9998**
9999** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
10000** exclusive "writer" lock on the database file. ^If the writer lock cannot be
10001** obtained immediately, and a busy-handler is configured, it is invoked and
10002** the writer lock retried until either the busy-handler returns 0 or the lock
10003** is successfully obtained. ^The busy-handler is also invoked while waiting for
10004** database readers as described above. ^If the busy-handler returns 0 before
10005** the writer lock is obtained or while waiting for database readers, the
10006** checkpoint operation proceeds from that point in the same way as
10007** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
10008** without blocking any further. ^SQLITE_BUSY is returned in this case.
10009**
10010** ^If parameter zDb is NULL or points to a zero length string, then the
10011** specified operation is attempted on all WAL databases [attached] to
10012** [database connection] db.  In this case the
10013** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
10014** an SQLITE_BUSY error is encountered when processing one or more of the
10015** attached WAL databases, the operation is still attempted on any remaining
10016** attached databases and SQLITE_BUSY is returned at the end. ^If any other
10017** error occurs while processing an attached database, processing is abandoned
10018** and the error code is returned to the caller immediately. ^If no error
10019** (SQLITE_BUSY or otherwise) is encountered while processing the attached
10020** databases, SQLITE_OK is returned.
10021**
10022** ^If database zDb is the name of an attached database that is not in WAL
10023** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
10024** zDb is not NULL (or a zero length string) and is not the name of any
10025** attached database, SQLITE_ERROR is returned to the caller.
10026**
10027** ^Unless it returns SQLITE_MISUSE,
10028** the sqlite3_wal_checkpoint_v2() interface
10029** sets the error information that is queried by
10030** [sqlite3_errcode()] and [sqlite3_errmsg()].
10031**
10032** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
10033** from SQL.
10034*/
10035SQLITE_API int sqlite3_wal_checkpoint_v2(
10036  sqlite3 *db,                    /* Database handle */
10037  const char *zDb,                /* Name of attached database (or NULL) */
10038  int eMode,                      /* SQLITE_CHECKPOINT_* value */
10039  int *pnLog,                     /* OUT: Size of WAL log in frames */
10040  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
10041);
10042
10043/*
10044** CAPI3REF: Checkpoint Mode Values
10045** KEYWORDS: {checkpoint mode}
10046**
10047** These constants define all valid values for the "checkpoint mode" passed
10048** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
10049** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
10050** meaning of each of these checkpoint modes.
10051*/
10052#define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */
10053#define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */
10054#define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for readers */
10055#define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */
10056
10057/*
10058** CAPI3REF: Virtual Table Interface Configuration
10059**
10060** This function may be called by either the [xConnect] or [xCreate] method
10061** of a [virtual table] implementation to configure
10062** various facets of the virtual table interface.
10063**
10064** If this interface is invoked outside the context of an xConnect or
10065** xCreate virtual table method then the behavior is undefined.
10066**
10067** In the call sqlite3_vtab_config(D,C,...) the D parameter is the
10068** [database connection] in which the virtual table is being created and
10069** which is passed in as the first argument to the [xConnect] or [xCreate]
10070** method that is invoking sqlite3_vtab_config().  The C parameter is one
10071** of the [virtual table configuration options].  The presence and meaning
10072** of parameters after C depend on which [virtual table configuration option]
10073** is used.
10074*/
10075SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
10076
10077/*
10078** CAPI3REF: Virtual Table Configuration Options
10079** KEYWORDS: {virtual table configuration options}
10080** KEYWORDS: {virtual table configuration option}
10081**
10082** These macros define the various options to the
10083** [sqlite3_vtab_config()] interface that [virtual table] implementations
10084** can use to customize and optimize their behavior.
10085**
10086** <dl>
10087** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]
10088** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt>
10089** <dd>Calls of the form
10090** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
10091** where X is an integer.  If X is zero, then the [virtual table] whose
10092** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
10093** support constraints.  In this configuration (which is the default) if
10094** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
10095** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
10096** specified as part of the users SQL statement, regardless of the actual
10097** ON CONFLICT mode specified.
10098**
10099** If X is non-zero, then the virtual table implementation guarantees
10100** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
10101** any modifications to internal or persistent data structures have been made.
10102** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
10103** is able to roll back a statement or database transaction, and abandon
10104** or continue processing the current SQL statement as appropriate.
10105** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
10106** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
10107** had been ABORT.
10108**
10109** Virtual table implementations that are required to handle OR REPLACE
10110** must do so within the [xUpdate] method. If a call to the
10111** [sqlite3_vtab_on_conflict()] function indicates that the current ON
10112** CONFLICT policy is REPLACE, the virtual table implementation should
10113** silently replace the appropriate rows within the xUpdate callback and
10114** return SQLITE_OK. Or, if this is not possible, it may return
10115** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
10116** constraint handling.
10117** </dd>
10118**
10119** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt>
10120** <dd>Calls of the form
10121** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the
10122** the [xConnect] or [xCreate] methods of a [virtual table] implementation
10123** prohibits that virtual table from being used from within triggers and
10124** views.
10125** </dd>
10126**
10127** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>
10128** <dd>Calls of the form
10129** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the
10130** the [xConnect] or [xCreate] methods of a [virtual table] implementation
10131** identify that virtual table as being safe to use from within triggers
10132** and views.  Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the
10133** virtual table can do no serious harm even if it is controlled by a
10134** malicious hacker.  Developers should avoid setting the SQLITE_VTAB_INNOCUOUS
10135** flag unless absolutely necessary.
10136** </dd>
10137**
10138** [[SQLITE_VTAB_USES_ALL_SCHEMAS]]<dt>SQLITE_VTAB_USES_ALL_SCHEMAS</dt>
10139** <dd>Calls of the form
10140** [sqlite3_vtab_config](db,SQLITE_VTAB_USES_ALL_SCHEMA) from within the
10141** the [xConnect] or [xCreate] methods of a [virtual table] implementation
10142** instruct the query planner to begin at least a read transaction on
10143** all schemas ("main", "temp", and any ATTACH-ed databases) whenever the
10144** virtual table is used.
10145** </dd>
10146** </dl>
10147*/
10148#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
10149#define SQLITE_VTAB_INNOCUOUS          2
10150#define SQLITE_VTAB_DIRECTONLY         3
10151#define SQLITE_VTAB_USES_ALL_SCHEMAS   4
10152
10153/*
10154** CAPI3REF: Determine The Virtual Table Conflict Policy
10155**
10156** This function may only be called from within a call to the [xUpdate] method
10157** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
10158** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
10159** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
10160** of the SQL statement that triggered the call to the [xUpdate] method of the
10161** [virtual table].
10162*/
10163SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
10164
10165/*
10166** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
10167**
10168** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
10169** method of a [virtual table], then it might return true if the
10170** column is being fetched as part of an UPDATE operation during which the
10171** column value will not change.  The virtual table implementation can use
10172** this hint as permission to substitute a return value that is less
10173** expensive to compute and that the corresponding
10174** [xUpdate] method understands as a "no-change" value.
10175**
10176** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
10177** the column is not changed by the UPDATE statement, then the xColumn
10178** method can optionally return without setting a result, without calling
10179** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
10180** In that case, [sqlite3_value_nochange(X)] will return true for the
10181** same column in the [xUpdate] method.
10182**
10183** The sqlite3_vtab_nochange() routine is an optimization.  Virtual table
10184** implementations should continue to give a correct answer even if the
10185** sqlite3_vtab_nochange() interface were to always return false.  In the
10186** current implementation, the sqlite3_vtab_nochange() interface does always
10187** returns false for the enhanced [UPDATE FROM] statement.
10188*/
10189SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
10190
10191/*
10192** CAPI3REF: Determine The Collation For a Virtual Table Constraint
10193** METHOD: sqlite3_index_info
10194**
10195** This function may only be called from within a call to the [xBestIndex]
10196** method of a [virtual table].  This function returns a pointer to a string
10197** that is the name of the appropriate collation sequence to use for text
10198** comparisons on the constraint identified by its arguments.
10199**
10200** The first argument must be the pointer to the [sqlite3_index_info] object
10201** that is the first parameter to the xBestIndex() method. The second argument
10202** must be an index into the aConstraint[] array belonging to the
10203** sqlite3_index_info structure passed to xBestIndex.
10204**
10205** Important:
10206** The first parameter must be the same pointer that is passed into the
10207** xBestMethod() method.  The first parameter may not be a pointer to a
10208** different [sqlite3_index_info] object, even an exact copy.
10209**
10210** The return value is computed as follows:
10211**
10212** <ol>
10213** <li><p> If the constraint comes from a WHERE clause expression that contains
10214**         a [COLLATE operator], then the name of the collation specified by
10215**         that COLLATE operator is returned.
10216** <li><p> If there is no COLLATE operator, but the column that is the subject
10217**         of the constraint specifies an alternative collating sequence via
10218**         a [COLLATE clause] on the column definition within the CREATE TABLE
10219**         statement that was passed into [sqlite3_declare_vtab()], then the
10220**         name of that alternative collating sequence is returned.
10221** <li><p> Otherwise, "BINARY" is returned.
10222** </ol>
10223*/
10224SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
10225
10226/*
10227** CAPI3REF: Determine if a virtual table query is DISTINCT
10228** METHOD: sqlite3_index_info
10229**
10230** This API may only be used from within an [xBestIndex|xBestIndex method]
10231** of a [virtual table] implementation. The result of calling this
10232** interface from outside of xBestIndex() is undefined and probably harmful.
10233**
10234** ^The sqlite3_vtab_distinct() interface returns an integer between 0 and
10235** 3.  The integer returned by sqlite3_vtab_distinct()
10236** gives the virtual table additional information about how the query
10237** planner wants the output to be ordered. As long as the virtual table
10238** can meet the ordering requirements of the query planner, it may set
10239** the "orderByConsumed" flag.
10240**
10241** <ol><li value="0"><p>
10242** ^If the sqlite3_vtab_distinct() interface returns 0, that means
10243** that the query planner needs the virtual table to return all rows in the
10244** sort order defined by the "nOrderBy" and "aOrderBy" fields of the
10245** [sqlite3_index_info] object.  This is the default expectation.  If the
10246** virtual table outputs all rows in sorted order, then it is always safe for
10247** the xBestIndex method to set the "orderByConsumed" flag, regardless of
10248** the return value from sqlite3_vtab_distinct().
10249** <li value="1"><p>
10250** ^(If the sqlite3_vtab_distinct() interface returns 1, that means
10251** that the query planner does not need the rows to be returned in sorted order
10252** as long as all rows with the same values in all columns identified by the
10253** "aOrderBy" field are adjacent.)^  This mode is used when the query planner
10254** is doing a GROUP BY.
10255** <li value="2"><p>
10256** ^(If the sqlite3_vtab_distinct() interface returns 2, that means
10257** that the query planner does not need the rows returned in any particular
10258** order, as long as rows with the same values in all columns identified
10259** by "aOrderBy" are adjacent.)^  ^(Furthermore, when two or more rows
10260** contain the same values for all columns identified by "colUsed", all but
10261** one such row may optionally be omitted from the result.)^
10262** The virtual table is not required to omit rows that are duplicates
10263** over the "colUsed" columns, but if the virtual table can do that without
10264** too much extra effort, it could potentially help the query to run faster.
10265** This mode is used for a DISTINCT query.
10266** <li value="3"><p>
10267** ^(If the sqlite3_vtab_distinct() interface returns 3, that means the
10268** virtual table must return rows in the order defined by "aOrderBy" as
10269** if the sqlite3_vtab_distinct() interface had returned 0.  However if
10270** two or more rows in the result have the same values for all columns
10271** identified by "colUsed", then all but one such row may optionally be
10272** omitted.)^  Like when the return value is 2, the virtual table
10273** is not required to omit rows that are duplicates over the "colUsed"
10274** columns, but if the virtual table can do that without
10275** too much extra effort, it could potentially help the query to run faster.
10276** This mode is used for queries
10277** that have both DISTINCT and ORDER BY clauses.
10278** </ol>
10279**
10280** <p>The following table summarizes the conditions under which the
10281** virtual table is allowed to set the "orderByConsumed" flag based on
10282** the value returned by sqlite3_vtab_distinct().  This table is a
10283** restatement of the previous four paragraphs:
10284**
10285** <table border=1 cellspacing=0 cellpadding=10 width="90%">
10286** <tr>
10287** <td valign="top">sqlite3_vtab_distinct() return value
10288** <td valign="top">Rows are returned in aOrderBy order
10289** <td valign="top">Rows with the same value in all aOrderBy columns are adjacent
10290** <td valign="top">Duplicates over all colUsed columns may be omitted
10291** <tr><td>0<td>yes<td>yes<td>no
10292** <tr><td>1<td>no<td>yes<td>no
10293** <tr><td>2<td>no<td>yes<td>yes
10294** <tr><td>3<td>yes<td>yes<td>yes
10295** </table>
10296**
10297** ^For the purposes of comparing virtual table output values to see if the
10298** values are same value for sorting purposes, two NULL values are considered
10299** to be the same.  In other words, the comparison operator is "IS"
10300** (or "IS NOT DISTINCT FROM") and not "==".
10301**
10302** If a virtual table implementation is unable to meet the requirements
10303** specified above, then it must not set the "orderByConsumed" flag in the
10304** [sqlite3_index_info] object or an incorrect answer may result.
10305**
10306** ^A virtual table implementation is always free to return rows in any order
10307** it wants, as long as the "orderByConsumed" flag is not set.  ^When the
10308** the "orderByConsumed" flag is unset, the query planner will add extra
10309** [bytecode] to ensure that the final results returned by the SQL query are
10310** ordered correctly.  The use of the "orderByConsumed" flag and the
10311** sqlite3_vtab_distinct() interface is merely an optimization.  ^Careful
10312** use of the sqlite3_vtab_distinct() interface and the "orderByConsumed"
10313** flag might help queries against a virtual table to run faster.  Being
10314** overly aggressive and setting the "orderByConsumed" flag when it is not
10315** valid to do so, on the other hand, might cause SQLite to return incorrect
10316** results.
10317*/
10318SQLITE_API int sqlite3_vtab_distinct(sqlite3_index_info*);
10319
10320/*
10321** CAPI3REF: Identify and handle IN constraints in xBestIndex
10322**
10323** This interface may only be used from within an
10324** [xBestIndex|xBestIndex() method] of a [virtual table] implementation.
10325** The result of invoking this interface from any other context is
10326** undefined and probably harmful.
10327**
10328** ^(A constraint on a virtual table of the form
10329** "[IN operator|column IN (...)]" is
10330** communicated to the xBestIndex method as a
10331** [SQLITE_INDEX_CONSTRAINT_EQ] constraint.)^  If xBestIndex wants to use
10332** this constraint, it must set the corresponding
10333** aConstraintUsage[].argvIndex to a positive integer.  ^(Then, under
10334** the usual mode of handling IN operators, SQLite generates [bytecode]
10335** that invokes the [xFilter|xFilter() method] once for each value
10336** on the right-hand side of the IN operator.)^  Thus the virtual table
10337** only sees a single value from the right-hand side of the IN operator
10338** at a time.
10339**
10340** In some cases, however, it would be advantageous for the virtual
10341** table to see all values on the right-hand of the IN operator all at
10342** once.  The sqlite3_vtab_in() interfaces facilitates this in two ways:
10343**
10344** <ol>
10345** <li><p>
10346**   ^A call to sqlite3_vtab_in(P,N,-1) will return true (non-zero)
10347**   if and only if the [sqlite3_index_info|P->aConstraint][N] constraint
10348**   is an [IN operator] that can be processed all at once.  ^In other words,
10349**   sqlite3_vtab_in() with -1 in the third argument is a mechanism
10350**   by which the virtual table can ask SQLite if all-at-once processing
10351**   of the IN operator is even possible.
10352**
10353** <li><p>
10354**   ^A call to sqlite3_vtab_in(P,N,F) with F==1 or F==0 indicates
10355**   to SQLite that the virtual table does or does not want to process
10356**   the IN operator all-at-once, respectively.  ^Thus when the third
10357**   parameter (F) is non-negative, this interface is the mechanism by
10358**   which the virtual table tells SQLite how it wants to process the
10359**   IN operator.
10360** </ol>
10361**
10362** ^The sqlite3_vtab_in(P,N,F) interface can be invoked multiple times
10363** within the same xBestIndex method call.  ^For any given P,N pair,
10364** the return value from sqlite3_vtab_in(P,N,F) will always be the same
10365** within the same xBestIndex call.  ^If the interface returns true
10366** (non-zero), that means that the constraint is an IN operator
10367** that can be processed all-at-once.  ^If the constraint is not an IN
10368** operator or cannot be processed all-at-once, then the interface returns
10369** false.
10370**
10371** ^(All-at-once processing of the IN operator is selected if both of the
10372** following conditions are met:
10373**
10374** <ol>
10375** <li><p> The P->aConstraintUsage[N].argvIndex value is set to a positive
10376** integer.  This is how the virtual table tells SQLite that it wants to
10377** use the N-th constraint.
10378**
10379** <li><p> The last call to sqlite3_vtab_in(P,N,F) for which F was
10380** non-negative had F>=1.
10381** </ol>)^
10382**
10383** ^If either or both of the conditions above are false, then SQLite uses
10384** the traditional one-at-a-time processing strategy for the IN constraint.
10385** ^If both conditions are true, then the argvIndex-th parameter to the
10386** xFilter method will be an [sqlite3_value] that appears to be NULL,
10387** but which can be passed to [sqlite3_vtab_in_first()] and
10388** [sqlite3_vtab_in_next()] to find all values on the right-hand side
10389** of the IN constraint.
10390*/
10391SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle);
10392
10393/*
10394** CAPI3REF: Find all elements on the right-hand side of an IN constraint.
10395**
10396** These interfaces are only useful from within the
10397** [xFilter|xFilter() method] of a [virtual table] implementation.
10398** The result of invoking these interfaces from any other context
10399** is undefined and probably harmful.
10400**
10401** The X parameter in a call to sqlite3_vtab_in_first(X,P) or
10402** sqlite3_vtab_in_next(X,P) should be one of the parameters to the
10403** xFilter method which invokes these routines, and specifically
10404** a parameter that was previously selected for all-at-once IN constraint
10405** processing use the [sqlite3_vtab_in()] interface in the
10406** [xBestIndex|xBestIndex method].  ^(If the X parameter is not
10407** an xFilter argument that was selected for all-at-once IN constraint
10408** processing, then these routines return [SQLITE_ERROR].)^
10409**
10410** ^(Use these routines to access all values on the right-hand side
10411** of the IN constraint using code like the following:
10412**
10413** <blockquote><pre>
10414** &nbsp;  for(rc=sqlite3_vtab_in_first(pList, &pVal);
10415** &nbsp;      rc==SQLITE_OK && pVal;
10416** &nbsp;      rc=sqlite3_vtab_in_next(pList, &pVal)
10417** &nbsp;  ){
10418** &nbsp;    // do something with pVal
10419** &nbsp;  }
10420** &nbsp;  if( rc!=SQLITE_OK ){
10421** &nbsp;    // an error has occurred
10422** &nbsp;  }
10423** </pre></blockquote>)^
10424**
10425** ^On success, the sqlite3_vtab_in_first(X,P) and sqlite3_vtab_in_next(X,P)
10426** routines return SQLITE_OK and set *P to point to the first or next value
10427** on the RHS of the IN constraint.  ^If there are no more values on the
10428** right hand side of the IN constraint, then *P is set to NULL and these
10429** routines return [SQLITE_DONE].  ^The return value might be
10430** some other value, such as SQLITE_NOMEM, in the event of a malfunction.
10431**
10432** The *ppOut values returned by these routines are only valid until the
10433** next call to either of these routines or until the end of the xFilter
10434** method from which these routines were called.  If the virtual table
10435** implementation needs to retain the *ppOut values for longer, it must make
10436** copies.  The *ppOut values are [protected sqlite3_value|protected].
10437*/
10438SQLITE_API int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut);
10439SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut);
10440
10441/*
10442** CAPI3REF: Constraint values in xBestIndex()
10443** METHOD: sqlite3_index_info
10444**
10445** This API may only be used from within the [xBestIndex|xBestIndex method]
10446** of a [virtual table] implementation. The result of calling this interface
10447** from outside of an xBestIndex method are undefined and probably harmful.
10448**
10449** ^When the sqlite3_vtab_rhs_value(P,J,V) interface is invoked from within
10450** the [xBestIndex] method of a [virtual table] implementation, with P being
10451** a copy of the [sqlite3_index_info] object pointer passed into xBestIndex and
10452** J being a 0-based index into P->aConstraint[], then this routine
10453** attempts to set *V to the value of the right-hand operand of
10454** that constraint if the right-hand operand is known.  ^If the
10455** right-hand operand is not known, then *V is set to a NULL pointer.
10456** ^The sqlite3_vtab_rhs_value(P,J,V) interface returns SQLITE_OK if
10457** and only if *V is set to a value.  ^The sqlite3_vtab_rhs_value(P,J,V)
10458** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th
10459** constraint is not available.  ^The sqlite3_vtab_rhs_value() interface
10460** can return an result code other than SQLITE_OK or SQLITE_NOTFOUND if
10461** something goes wrong.
10462**
10463** The sqlite3_vtab_rhs_value() interface is usually only successful if
10464** the right-hand operand of a constraint is a literal value in the original
10465** SQL statement.  If the right-hand operand is an expression or a reference
10466** to some other column or a [host parameter], then sqlite3_vtab_rhs_value()
10467** will probably return [SQLITE_NOTFOUND].
10468**
10469** ^(Some constraints, such as [SQLITE_INDEX_CONSTRAINT_ISNULL] and
10470** [SQLITE_INDEX_CONSTRAINT_ISNOTNULL], have no right-hand operand.  For such
10471** constraints, sqlite3_vtab_rhs_value() always returns SQLITE_NOTFOUND.)^
10472**
10473** ^The [sqlite3_value] object returned in *V is a protected sqlite3_value
10474** and remains valid for the duration of the xBestIndex method call.
10475** ^When xBestIndex returns, the sqlite3_value object returned by
10476** sqlite3_vtab_rhs_value() is automatically deallocated.
10477**
10478** The "_rhs_" in the name of this routine is an abbreviation for
10479** "Right-Hand Side".
10480*/
10481SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **ppVal);
10482
10483/*
10484** CAPI3REF: Conflict resolution modes
10485** KEYWORDS: {conflict resolution mode}
10486**
10487** These constants are returned by [sqlite3_vtab_on_conflict()] to
10488** inform a [virtual table] implementation what the [ON CONFLICT] mode
10489** is for the SQL statement being evaluated.
10490**
10491** Note that the [SQLITE_IGNORE] constant is also used as a potential
10492** return value from the [sqlite3_set_authorizer()] callback and that
10493** [SQLITE_ABORT] is also a [result code].
10494*/
10495#define SQLITE_ROLLBACK 1
10496/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
10497#define SQLITE_FAIL     3
10498/* #define SQLITE_ABORT 4  // Also an error code */
10499#define SQLITE_REPLACE  5
10500
10501/*
10502** CAPI3REF: Prepared Statement Scan Status Opcodes
10503** KEYWORDS: {scanstatus options}
10504**
10505** The following constants can be used for the T parameter to the
10506** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a
10507** different metric for sqlite3_stmt_scanstatus() to return.
10508**
10509** When the value returned to V is a string, space to hold that string is
10510** managed by the prepared statement S and will be automatically freed when
10511** S is finalized.
10512**
10513** Not all values are available for all query elements. When a value is
10514** not available, the output variable is set to -1 if the value is numeric,
10515** or to NULL if it is a string (SQLITE_SCANSTAT_NAME).
10516**
10517** <dl>
10518** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
10519** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be
10520** set to the total number of times that the X-th loop has run.</dd>
10521**
10522** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
10523** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be set
10524** to the total number of rows examined by all iterations of the X-th loop.</dd>
10525**
10526** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
10527** <dd>^The "double" variable pointed to by the V parameter will be set to the
10528** query planner's estimate for the average number of rows output from each
10529** iteration of the X-th loop.  If the query planner's estimates was accurate,
10530** then this value will approximate the quotient NVISIT/NLOOP and the
10531** product of this value for all prior loops with the same SELECTID will
10532** be the NLOOP value for the current loop.
10533**
10534** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
10535** <dd>^The "const char *" variable pointed to by the V parameter will be set
10536** to a zero-terminated UTF-8 string containing the name of the index or table
10537** used for the X-th loop.
10538**
10539** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
10540** <dd>^The "const char *" variable pointed to by the V parameter will be set
10541** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
10542** description for the X-th loop.
10543**
10544** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECTID</dt>
10545** <dd>^The "int" variable pointed to by the V parameter will be set to the
10546** id for the X-th query plan element. The id value is unique within the
10547** statement. The select-id is the same value as is output in the first
10548** column of an [EXPLAIN QUERY PLAN] query.
10549**
10550** [[SQLITE_SCANSTAT_PARENTID]] <dt>SQLITE_SCANSTAT_PARENTID</dt>
10551** <dd>The "int" variable pointed to by the V parameter will be set to the
10552** the id of the parent of the current query element, if applicable, or
10553** to zero if the query element has no parent. This is the same value as
10554** returned in the second column of an [EXPLAIN QUERY PLAN] query.
10555**
10556** [[SQLITE_SCANSTAT_NCYCLE]] <dt>SQLITE_SCANSTAT_NCYCLE</dt>
10557** <dd>The sqlite3_int64 output value is set to the number of cycles,
10558** according to the processor time-stamp counter, that elapsed while the
10559** query element was being processed. This value is not available for
10560** all query elements - if it is unavailable the output variable is
10561** set to -1.
10562** </dl>
10563*/
10564#define SQLITE_SCANSTAT_NLOOP    0
10565#define SQLITE_SCANSTAT_NVISIT   1
10566#define SQLITE_SCANSTAT_EST      2
10567#define SQLITE_SCANSTAT_NAME     3
10568#define SQLITE_SCANSTAT_EXPLAIN  4
10569#define SQLITE_SCANSTAT_SELECTID 5
10570#define SQLITE_SCANSTAT_PARENTID 6
10571#define SQLITE_SCANSTAT_NCYCLE   7
10572
10573/*
10574** CAPI3REF: Prepared Statement Scan Status
10575** METHOD: sqlite3_stmt
10576**
10577** These interfaces return information about the predicted and measured
10578** performance for pStmt.  Advanced applications can use this
10579** interface to compare the predicted and the measured performance and
10580** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
10581**
10582** Since this interface is expected to be rarely used, it is only
10583** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
10584** compile-time option.
10585**
10586** The "iScanStatusOp" parameter determines which status information to return.
10587** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
10588** of this interface is undefined. ^The requested measurement is written into
10589** a variable pointed to by the "pOut" parameter.
10590**
10591** The "flags" parameter must be passed a mask of flags. At present only
10592** one flag is defined - SQLITE_SCANSTAT_COMPLEX. If SQLITE_SCANSTAT_COMPLEX
10593** is specified, then status information is available for all elements
10594** of a query plan that are reported by "EXPLAIN QUERY PLAN" output. If
10595** SQLITE_SCANSTAT_COMPLEX is not specified, then only query plan elements
10596** that correspond to query loops (the "SCAN..." and "SEARCH..." elements of
10597** the EXPLAIN QUERY PLAN output) are available. Invoking API
10598** sqlite3_stmt_scanstatus() is equivalent to calling
10599** sqlite3_stmt_scanstatus_v2() with a zeroed flags parameter.
10600**
10601** Parameter "idx" identifies the specific query element to retrieve statistics
10602** for. Query elements are numbered starting from zero. A value of -1 may be
10603** to query for statistics regarding the entire query. ^If idx is out of range
10604** - less than -1 or greater than or equal to the total number of query
10605** elements used to implement the statement - a non-zero value is returned and
10606** the variable that pOut points to is unchanged.
10607**
10608** See also: [sqlite3_stmt_scanstatus_reset()]
10609*/
10610SQLITE_API int sqlite3_stmt_scanstatus(
10611  sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */
10612  int idx,                  /* Index of loop to report on */
10613  int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
10614  void *pOut                /* Result written here */
10615);
10616SQLITE_API int sqlite3_stmt_scanstatus_v2(
10617  sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */
10618  int idx,                  /* Index of loop to report on */
10619  int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
10620  int flags,                /* Mask of flags defined below */
10621  void *pOut                /* Result written here */
10622);
10623
10624/*
10625** CAPI3REF: Prepared Statement Scan Status
10626** KEYWORDS: {scan status flags}
10627*/
10628#define SQLITE_SCANSTAT_COMPLEX 0x0001
10629
10630/*
10631** CAPI3REF: Zero Scan-Status Counters
10632** METHOD: sqlite3_stmt
10633**
10634** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
10635**
10636** This API is only available if the library is built with pre-processor
10637** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
10638*/
10639SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
10640
10641/*
10642** CAPI3REF: Flush caches to disk mid-transaction
10643** METHOD: sqlite3
10644**
10645** ^If a write-transaction is open on [database connection] D when the
10646** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
10647** pages in the pager-cache that are not currently in use are written out
10648** to disk. A dirty page may be in use if a database cursor created by an
10649** active SQL statement is reading from it, or if it is page 1 of a database
10650** file (page 1 is always "in use").  ^The [sqlite3_db_cacheflush(D)]
10651** interface flushes caches for all schemas - "main", "temp", and
10652** any [attached] databases.
10653**
10654** ^If this function needs to obtain extra database locks before dirty pages
10655** can be flushed to disk, it does so. ^If those locks cannot be obtained
10656** immediately and there is a busy-handler callback configured, it is invoked
10657** in the usual manner. ^If the required lock still cannot be obtained, then
10658** the database is skipped and an attempt made to flush any dirty pages
10659** belonging to the next (if any) database. ^If any databases are skipped
10660** because locks cannot be obtained, but no other error occurs, this
10661** function returns SQLITE_BUSY.
10662**
10663** ^If any other error occurs while flushing dirty pages to disk (for
10664** example an IO error or out-of-memory condition), then processing is
10665** abandoned and an SQLite [error code] is returned to the caller immediately.
10666**
10667** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
10668**
10669** ^This function does not set the database handle error code or message
10670** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
10671*/
10672SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
10673
10674/*
10675** CAPI3REF: The pre-update hook.
10676** METHOD: sqlite3
10677**
10678** ^These interfaces are only available if SQLite is compiled using the
10679** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
10680**
10681** ^The [sqlite3_preupdate_hook()] interface registers a callback function
10682** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
10683** on a database table.
10684** ^At most one preupdate hook may be registered at a time on a single
10685** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
10686** the previous setting.
10687** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
10688** with a NULL pointer as the second parameter.
10689** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
10690** the first parameter to callbacks.
10691**
10692** ^The preupdate hook only fires for changes to real database tables; the
10693** preupdate hook is not invoked for changes to [virtual tables] or to
10694** system tables like sqlite_sequence or sqlite_stat1.
10695**
10696** ^The second parameter to the preupdate callback is a pointer to
10697** the [database connection] that registered the preupdate hook.
10698** ^The third parameter to the preupdate callback is one of the constants
10699** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
10700** kind of update operation that is about to occur.
10701** ^(The fourth parameter to the preupdate callback is the name of the
10702** database within the database connection that is being modified.  This
10703** will be "main" for the main database or "temp" for TEMP tables or
10704** the name given after the AS keyword in the [ATTACH] statement for attached
10705** databases.)^
10706** ^The fifth parameter to the preupdate callback is the name of the
10707** table that is being modified.
10708**
10709** For an UPDATE or DELETE operation on a [rowid table], the sixth
10710** parameter passed to the preupdate callback is the initial [rowid] of the
10711** row being modified or deleted. For an INSERT operation on a rowid table,
10712** or any operation on a WITHOUT ROWID table, the value of the sixth
10713** parameter is undefined. For an INSERT or UPDATE on a rowid table the
10714** seventh parameter is the final rowid value of the row being inserted
10715** or updated. The value of the seventh parameter passed to the callback
10716** function is not defined for operations on WITHOUT ROWID tables, or for
10717** DELETE operations on rowid tables.
10718**
10719** ^The sqlite3_preupdate_hook(D,C,P) function returns the P argument from
10720** the previous call on the same [database connection] D, or NULL for
10721** the first call on D.
10722**
10723** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
10724** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
10725** provide additional information about a preupdate event. These routines
10726** may only be called from within a preupdate callback.  Invoking any of
10727** these routines from outside of a preupdate callback or with a
10728** [database connection] pointer that is different from the one supplied
10729** to the preupdate callback results in undefined and probably undesirable
10730** behavior.
10731**
10732** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
10733** in the row that is being inserted, updated, or deleted.
10734**
10735** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
10736** a [protected sqlite3_value] that contains the value of the Nth column of
10737** the table row before it is updated.  The N parameter must be between 0
10738** and one less than the number of columns or the behavior will be
10739** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
10740** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
10741** behavior is undefined.  The [sqlite3_value] that P points to
10742** will be destroyed when the preupdate callback returns.
10743**
10744** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
10745** a [protected sqlite3_value] that contains the value of the Nth column of
10746** the table row after it is updated.  The N parameter must be between 0
10747** and one less than the number of columns or the behavior will be
10748** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
10749** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
10750** behavior is undefined.  The [sqlite3_value] that P points to
10751** will be destroyed when the preupdate callback returns.
10752**
10753** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
10754** callback was invoked as a result of a direct insert, update, or delete
10755** operation; or 1 for inserts, updates, or deletes invoked by top-level
10756** triggers; or 2 for changes resulting from triggers called by top-level
10757** triggers; and so forth.
10758**
10759** When the [sqlite3_blob_write()] API is used to update a blob column,
10760** the pre-update hook is invoked with SQLITE_DELETE. This is because the
10761** in this case the new values are not available. In this case, when a
10762** callback made with op==SQLITE_DELETE is actually a write using the
10763** sqlite3_blob_write() API, the [sqlite3_preupdate_blobwrite()] returns
10764** the index of the column being written. In other cases, where the
10765** pre-update hook is being invoked for some other reason, including a
10766** regular DELETE, sqlite3_preupdate_blobwrite() returns -1.
10767**
10768** See also:  [sqlite3_update_hook()]
10769*/
10770#if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
10771SQLITE_API void *sqlite3_preupdate_hook(
10772  sqlite3 *db,
10773  void(*xPreUpdate)(
10774    void *pCtx,                   /* Copy of third arg to preupdate_hook() */
10775    sqlite3 *db,                  /* Database handle */
10776    int op,                       /* SQLITE_UPDATE, DELETE or INSERT */
10777    char const *zDb,              /* Database name */
10778    char const *zName,            /* Table name */
10779    sqlite3_int64 iKey1,          /* Rowid of row about to be deleted/updated */
10780    sqlite3_int64 iKey2           /* New rowid value (for a rowid UPDATE) */
10781  ),
10782  void*
10783);
10784SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
10785SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
10786SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
10787SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
10788SQLITE_API int sqlite3_preupdate_blobwrite(sqlite3 *);
10789#endif
10790
10791/*
10792** CAPI3REF: Low-level system error code
10793** METHOD: sqlite3
10794**
10795** ^Attempt to return the underlying operating system error code or error
10796** number that caused the most recent I/O error or failure to open a file.
10797** The return value is OS-dependent.  For example, on unix systems, after
10798** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
10799** called to get back the underlying "errno" that caused the problem, such
10800** as ENOSPC, EAUTH, EISDIR, and so forth.
10801*/
10802SQLITE_API int sqlite3_system_errno(sqlite3*);
10803
10804/*
10805** CAPI3REF: Database Snapshot
10806** KEYWORDS: {snapshot} {sqlite3_snapshot}
10807**
10808** An instance of the snapshot object records the state of a [WAL mode]
10809** database for some specific point in history.
10810**
10811** In [WAL mode], multiple [database connections] that are open on the
10812** same database file can each be reading a different historical version
10813** of the database file.  When a [database connection] begins a read
10814** transaction, that connection sees an unchanging copy of the database
10815** as it existed for the point in time when the transaction first started.
10816** Subsequent changes to the database from other connections are not seen
10817** by the reader until a new read transaction is started.
10818**
10819** The sqlite3_snapshot object records state information about an historical
10820** version of the database file so that it is possible to later open a new read
10821** transaction that sees that historical version of the database rather than
10822** the most recent version.
10823*/
10824typedef struct sqlite3_snapshot {
10825  unsigned char hidden[48];
10826} sqlite3_snapshot;
10827
10828/*
10829** CAPI3REF: Record A Database Snapshot
10830** CONSTRUCTOR: sqlite3_snapshot
10831**
10832** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
10833** new [sqlite3_snapshot] object that records the current state of
10834** schema S in database connection D.  ^On success, the
10835** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
10836** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
10837** If there is not already a read-transaction open on schema S when
10838** this function is called, one is opened automatically.
10839**
10840** The following must be true for this function to succeed. If any of
10841** the following statements are false when sqlite3_snapshot_get() is
10842** called, SQLITE_ERROR is returned. The final value of *P is undefined
10843** in this case.
10844**
10845** <ul>
10846**   <li> The database handle must not be in [autocommit mode].
10847**
10848**   <li> Schema S of [database connection] D must be a [WAL mode] database.
10849**
10850**   <li> There must not be a write transaction open on schema S of database
10851**        connection D.
10852**
10853**   <li> One or more transactions must have been written to the current wal
10854**        file since it was created on disk (by any connection). This means
10855**        that a snapshot cannot be taken on a wal mode database with no wal
10856**        file immediately after it is first opened. At least one transaction
10857**        must be written to it first.
10858** </ul>
10859**
10860** This function may also return SQLITE_NOMEM.  If it is called with the
10861** database handle in autocommit mode but fails for some other reason,
10862** whether or not a read transaction is opened on schema S is undefined.
10863**
10864** The [sqlite3_snapshot] object returned from a successful call to
10865** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
10866** to avoid a memory leak.
10867**
10868** The [sqlite3_snapshot_get()] interface is only available when the
10869** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
10870*/
10871SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
10872  sqlite3 *db,
10873  const char *zSchema,
10874  sqlite3_snapshot **ppSnapshot
10875);
10876
10877/*
10878** CAPI3REF: Start a read transaction on an historical snapshot
10879** METHOD: sqlite3_snapshot
10880**
10881** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read
10882** transaction or upgrades an existing one for schema S of
10883** [database connection] D such that the read transaction refers to
10884** historical [snapshot] P, rather than the most recent change to the
10885** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK
10886** on success or an appropriate [error code] if it fails.
10887**
10888** ^In order to succeed, the database connection must not be in
10889** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there
10890** is already a read transaction open on schema S, then the database handle
10891** must have no active statements (SELECT statements that have been passed
10892** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()).
10893** SQLITE_ERROR is returned if either of these conditions is violated, or
10894** if schema S does not exist, or if the snapshot object is invalid.
10895**
10896** ^A call to sqlite3_snapshot_open() will fail to open if the specified
10897** snapshot has been overwritten by a [checkpoint]. In this case
10898** SQLITE_ERROR_SNAPSHOT is returned.
10899**
10900** If there is already a read transaction open when this function is
10901** invoked, then the same read transaction remains open (on the same
10902** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT
10903** is returned. If another error code - for example SQLITE_PROTOCOL or an
10904** SQLITE_IOERR error code - is returned, then the final state of the
10905** read transaction is undefined. If SQLITE_OK is returned, then the
10906** read transaction is now open on database snapshot P.
10907**
10908** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
10909** database connection D does not know that the database file for
10910** schema S is in [WAL mode].  A database connection might not know
10911** that the database file is in [WAL mode] if there has been no prior
10912** I/O on that database connection, or if the database entered [WAL mode]
10913** after the most recent I/O on the database connection.)^
10914** (Hint: Run "[PRAGMA application_id]" against a newly opened
10915** database connection in order to make it ready to use snapshots.)
10916**
10917** The [sqlite3_snapshot_open()] interface is only available when the
10918** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
10919*/
10920SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
10921  sqlite3 *db,
10922  const char *zSchema,
10923  sqlite3_snapshot *pSnapshot
10924);
10925
10926/*
10927** CAPI3REF: Destroy a snapshot
10928** DESTRUCTOR: sqlite3_snapshot
10929**
10930** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
10931** The application must eventually free every [sqlite3_snapshot] object
10932** using this routine to avoid a memory leak.
10933**
10934** The [sqlite3_snapshot_free()] interface is only available when the
10935** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
10936*/
10937SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
10938
10939/*
10940** CAPI3REF: Compare the ages of two snapshot handles.
10941** METHOD: sqlite3_snapshot
10942**
10943** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
10944** of two valid snapshot handles.
10945**
10946** If the two snapshot handles are not associated with the same database
10947** file, the result of the comparison is undefined.
10948**
10949** Additionally, the result of the comparison is only valid if both of the
10950** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
10951** last time the wal file was deleted. The wal file is deleted when the
10952** database is changed back to rollback mode or when the number of database
10953** clients drops to zero. If either snapshot handle was obtained before the
10954** wal file was last deleted, the value returned by this function
10955** is undefined.
10956**
10957** Otherwise, this API returns a negative value if P1 refers to an older
10958** snapshot than P2, zero if the two handles refer to the same database
10959** snapshot, and a positive value if P1 is a newer snapshot than P2.
10960**
10961** This interface is only available if SQLite is compiled with the
10962** [SQLITE_ENABLE_SNAPSHOT] option.
10963*/
10964SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
10965  sqlite3_snapshot *p1,
10966  sqlite3_snapshot *p2
10967);
10968
10969/*
10970** CAPI3REF: Recover snapshots from a wal file
10971** METHOD: sqlite3_snapshot
10972**
10973** If a [WAL file] remains on disk after all database connections close
10974** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]
10975** or because the last process to have the database opened exited without
10976** calling [sqlite3_close()]) and a new connection is subsequently opened
10977** on that database and [WAL file], the [sqlite3_snapshot_open()] interface
10978** will only be able to open the last transaction added to the WAL file
10979** even though the WAL file contains other valid transactions.
10980**
10981** This function attempts to scan the WAL file associated with database zDb
10982** of database handle db and make all valid snapshots available to
10983** sqlite3_snapshot_open(). It is an error if there is already a read
10984** transaction open on the database, or if the database is not a WAL mode
10985** database.
10986**
10987** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
10988**
10989** This interface is only available if SQLite is compiled with the
10990** [SQLITE_ENABLE_SNAPSHOT] option.
10991*/
10992SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
10993
10994/*
10995** CAPI3REF: Serialize a database
10996**
10997** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory
10998** that is a serialization of the S database on [database connection] D.
10999** If P is not a NULL pointer, then the size of the database in bytes
11000** is written into *P.
11001**
11002** For an ordinary on-disk database file, the serialization is just a
11003** copy of the disk file.  For an in-memory database or a "TEMP" database,
11004** the serialization is the same sequence of bytes which would be written
11005** to disk if that database where backed up to disk.
11006**
11007** The usual case is that sqlite3_serialize() copies the serialization of
11008** the database into memory obtained from [sqlite3_malloc64()] and returns
11009** a pointer to that memory.  The caller is responsible for freeing the
11010** returned value to avoid a memory leak.  However, if the F argument
11011** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
11012** are made, and the sqlite3_serialize() function will return a pointer
11013** to the contiguous memory representation of the database that SQLite
11014** is currently using for that database, or NULL if the no such contiguous
11015** memory representation of the database exists.  A contiguous memory
11016** representation of the database will usually only exist if there has
11017** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
11018** values of D and S.
11019** The size of the database is written into *P even if the
11020** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
11021** of the database exists.
11022**
11023** After the call, if the SQLITE_SERIALIZE_NOCOPY bit had been set,
11024** the returned buffer content will remain accessible and unchanged
11025** until either the next write operation on the connection or when
11026** the connection is closed, and applications must not modify the
11027** buffer. If the bit had been clear, the returned buffer will not
11028** be accessed by SQLite after the call.
11029**
11030** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
11031** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
11032** allocation error occurs.
11033**
11034** This interface is omitted if SQLite is compiled with the
11035** [SQLITE_OMIT_DESERIALIZE] option.
11036*/
11037SQLITE_API unsigned char *sqlite3_serialize(
11038  sqlite3 *db,           /* The database connection */
11039  const char *zSchema,   /* Which DB to serialize. ex: "main", "temp", ... */
11040  sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
11041  unsigned int mFlags    /* Zero or more SQLITE_SERIALIZE_* flags */
11042);
11043
11044/*
11045** CAPI3REF: Flags for sqlite3_serialize
11046**
11047** Zero or more of the following constants can be OR-ed together for
11048** the F argument to [sqlite3_serialize(D,S,P,F)].
11049**
11050** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return
11051** a pointer to contiguous in-memory database that it is currently using,
11052** without making a copy of the database.  If SQLite is not currently using
11053** a contiguous in-memory database, then this option causes
11054** [sqlite3_serialize()] to return a NULL pointer.  SQLite will only be
11055** using a contiguous in-memory database if it has been initialized by a
11056** prior call to [sqlite3_deserialize()].
11057*/
11058#define SQLITE_SERIALIZE_NOCOPY 0x001   /* Do no memory allocations */
11059
11060/*
11061** CAPI3REF: Deserialize a database
11062**
11063** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
11064** [database connection] D to disconnect from database S and then
11065** reopen S as an in-memory database based on the serialization contained
11066** in P.  The serialized database P is N bytes in size.  M is the size of
11067** the buffer P, which might be larger than N.  If M is larger than N, and
11068** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
11069** permitted to add content to the in-memory database as long as the total
11070** size does not exceed M bytes.
11071**
11072** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
11073** invoke sqlite3_free() on the serialization buffer when the database
11074** connection closes.  If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
11075** SQLite will try to increase the buffer size using sqlite3_realloc64()
11076** if writes on the database cause it to grow larger than M bytes.
11077**
11078** Applications must not modify the buffer P or invalidate it before
11079** the database connection D is closed.
11080**
11081** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
11082** database is currently in a read transaction or is involved in a backup
11083** operation.
11084**
11085** It is not possible to deserialized into the TEMP database.  If the
11086** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the
11087** function returns SQLITE_ERROR.
11088**
11089** The deserialized database should not be in [WAL mode].  If the database
11090** is in WAL mode, then any attempt to use the database file will result
11091** in an [SQLITE_CANTOPEN] error.  The application can set the
11092** [file format version numbers] (bytes 18 and 19) of the input database P
11093** to 0x01 prior to invoking sqlite3_deserialize(D,S,P,N,M,F) to force the
11094** database file into rollback mode and work around this limitation.
11095**
11096** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
11097** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
11098** [sqlite3_free()] is invoked on argument P prior to returning.
11099**
11100** This interface is omitted if SQLite is compiled with the
11101** [SQLITE_OMIT_DESERIALIZE] option.
11102*/
11103SQLITE_API int sqlite3_deserialize(
11104  sqlite3 *db,            /* The database connection */
11105  const char *zSchema,    /* Which DB to reopen with the deserialization */
11106  unsigned char *pData,   /* The serialized database content */
11107  sqlite3_int64 szDb,     /* Number bytes in the deserialization */
11108  sqlite3_int64 szBuf,    /* Total size of buffer pData[] */
11109  unsigned mFlags         /* Zero or more SQLITE_DESERIALIZE_* flags */
11110);
11111
11112/*
11113** CAPI3REF: Flags for sqlite3_deserialize()
11114**
11115** The following are allowed values for 6th argument (the F argument) to
11116** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.
11117**
11118** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
11119** in the P argument is held in memory obtained from [sqlite3_malloc64()]
11120** and that SQLite should take ownership of this memory and automatically
11121** free it when it has finished using it.  Without this flag, the caller
11122** is responsible for freeing any dynamically allocated memory.
11123**
11124** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
11125** grow the size of the database using calls to [sqlite3_realloc64()].  This
11126** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
11127** Without this flag, the deserialized database cannot increase in size beyond
11128** the number of bytes specified by the M parameter.
11129**
11130** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
11131** should be treated as read-only.
11132*/
11133#define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */
11134#define SQLITE_DESERIALIZE_RESIZEABLE  2 /* Resize using sqlite3_realloc64() */
11135#define SQLITE_DESERIALIZE_READONLY    4 /* Database is read-only */
11136
11137/*
11138** Undo the hack that converts floating point types to integer for
11139** builds on processors without floating point support.
11140*/
11141#ifdef SQLITE_OMIT_FLOATING_POINT
11142# undef double
11143#endif
11144
11145#if defined(__wasi__)
11146# undef SQLITE_WASI
11147# define SQLITE_WASI 1
11148# undef SQLITE_OMIT_WAL
11149# define SQLITE_OMIT_WAL 1/* because it requires shared memory APIs */
11150# ifndef SQLITE_OMIT_LOAD_EXTENSION
11151#  define SQLITE_OMIT_LOAD_EXTENSION
11152# endif
11153# ifndef SQLITE_THREADSAFE
11154#  define SQLITE_THREADSAFE 0
11155# endif
11156#endif
11157
11158#if 0
11159}  /* End of the 'extern "C"' block */
11160#endif
11161#endif /* SQLITE3_H */
11162
11163/******** Begin file sqlite3rtree.h *********/
11164/*
11165** 2010 August 30
11166**
11167** The author disclaims copyright to this source code.  In place of
11168** a legal notice, here is a blessing:
11169**
11170**    May you do good and not evil.
11171**    May you find forgiveness for yourself and forgive others.
11172**    May you share freely, never taking more than you give.
11173**
11174*************************************************************************
11175*/
11176
11177#ifndef _SQLITE3RTREE_H_
11178#define _SQLITE3RTREE_H_
11179
11180
11181#if 0
11182extern "C" {
11183#endif
11184
11185typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
11186typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
11187
11188/* The double-precision datatype used by RTree depends on the
11189** SQLITE_RTREE_INT_ONLY compile-time option.
11190*/
11191#ifdef SQLITE_RTREE_INT_ONLY
11192  typedef sqlite3_int64 sqlite3_rtree_dbl;
11193#else
11194  typedef double sqlite3_rtree_dbl;
11195#endif
11196
11197/*
11198** Register a geometry callback named zGeom that can be used as part of an
11199** R-Tree geometry query as follows:
11200**
11201**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
11202*/
11203SQLITE_API int sqlite3_rtree_geometry_callback(
11204  sqlite3 *db,
11205  const char *zGeom,
11206  int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
11207  void *pContext
11208);
11209
11210
11211/*
11212** A pointer to a structure of the following type is passed as the first
11213** argument to callbacks registered using rtree_geometry_callback().
11214*/
11215struct sqlite3_rtree_geometry {
11216  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
11217  int nParam;                     /* Size of array aParam[] */
11218  sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
11219  void *pUser;                    /* Callback implementation user data */
11220  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
11221};
11222
11223/*
11224** Register a 2nd-generation geometry callback named zScore that can be
11225** used as part of an R-Tree geometry query as follows:
11226**
11227**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
11228*/
11229SQLITE_API int sqlite3_rtree_query_callback(
11230  sqlite3 *db,
11231  const char *zQueryFunc,
11232  int (*xQueryFunc)(sqlite3_rtree_query_info*),
11233  void *pContext,
11234  void (*xDestructor)(void*)
11235);
11236
11237
11238/*
11239** A pointer to a structure of the following type is passed as the
11240** argument to scored geometry callback registered using
11241** sqlite3_rtree_query_callback().
11242**
11243** Note that the first 5 fields of this structure are identical to
11244** sqlite3_rtree_geometry.  This structure is a subclass of
11245** sqlite3_rtree_geometry.
11246*/
11247struct sqlite3_rtree_query_info {
11248  void *pContext;                   /* pContext from when function registered */
11249  int nParam;                       /* Number of function parameters */
11250  sqlite3_rtree_dbl *aParam;        /* value of function parameters */
11251  void *pUser;                      /* callback can use this, if desired */
11252  void (*xDelUser)(void*);          /* function to free pUser */
11253  sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
11254  unsigned int *anQueue;            /* Number of pending entries in the queue */
11255  int nCoord;                       /* Number of coordinates */
11256  int iLevel;                       /* Level of current node or entry */
11257  int mxLevel;                      /* The largest iLevel value in the tree */
11258  sqlite3_int64 iRowid;             /* Rowid for current entry */
11259  sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
11260  int eParentWithin;                /* Visibility of parent node */
11261  int eWithin;                      /* OUT: Visibility */
11262  sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
11263  /* The following fields are only available in 3.8.11 and later */
11264  sqlite3_value **apSqlParam;       /* Original SQL values of parameters */
11265};
11266
11267/*
11268** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
11269*/
11270#define NOT_WITHIN       0   /* Object completely outside of query region */
11271#define PARTLY_WITHIN    1   /* Object partially overlaps query region */
11272#define FULLY_WITHIN     2   /* Object fully contained within query region */
11273
11274
11275#if 0
11276}  /* end of the 'extern "C"' block */
11277#endif
11278
11279#endif  /* ifndef _SQLITE3RTREE_H_ */
11280
11281/******** End of sqlite3rtree.h *********/
11282/******** Begin file sqlite3session.h *********/
11283
11284#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
11285#define __SQLITESESSION_H_ 1
11286
11287/*
11288** Make sure we can call this stuff from C++.
11289*/
11290#if 0
11291extern "C" {
11292#endif
11293
11294
11295/*
11296** CAPI3REF: Session Object Handle
11297**
11298** An instance of this object is a [session] that can be used to
11299** record changes to a database.
11300*/
11301typedef struct sqlite3_session sqlite3_session;
11302
11303/*
11304** CAPI3REF: Changeset Iterator Handle
11305**
11306** An instance of this object acts as a cursor for iterating
11307** over the elements of a [changeset] or [patchset].
11308*/
11309typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
11310
11311/*
11312** CAPI3REF: Create A New Session Object
11313** CONSTRUCTOR: sqlite3_session
11314**
11315** Create a new session object attached to database handle db. If successful,
11316** a pointer to the new object is written to *ppSession and SQLITE_OK is
11317** returned. If an error occurs, *ppSession is set to NULL and an SQLite
11318** error code (e.g. SQLITE_NOMEM) is returned.
11319**
11320** It is possible to create multiple session objects attached to a single
11321** database handle.
11322**
11323** Session objects created using this function should be deleted using the
11324** [sqlite3session_delete()] function before the database handle that they
11325** are attached to is itself closed. If the database handle is closed before
11326** the session object is deleted, then the results of calling any session
11327** module function, including [sqlite3session_delete()] on the session object
11328** are undefined.
11329**
11330** Because the session module uses the [sqlite3_preupdate_hook()] API, it
11331** is not possible for an application to register a pre-update hook on a
11332** database handle that has one or more session objects attached. Nor is
11333** it possible to create a session object attached to a database handle for
11334** which a pre-update hook is already defined. The results of attempting
11335** either of these things are undefined.
11336**
11337** The session object will be used to create changesets for tables in
11338** database zDb, where zDb is either "main", or "temp", or the name of an
11339** attached database. It is not an error if database zDb is not attached
11340** to the database when the session object is created.
11341*/
11342SQLITE_API int sqlite3session_create(
11343  sqlite3 *db,                    /* Database handle */
11344  const char *zDb,                /* Name of db (e.g. "main") */
11345  sqlite3_session **ppSession     /* OUT: New session object */
11346);
11347
11348/*
11349** CAPI3REF: Delete A Session Object
11350** DESTRUCTOR: sqlite3_session
11351**
11352** Delete a session object previously allocated using
11353** [sqlite3session_create()]. Once a session object has been deleted, the
11354** results of attempting to use pSession with any other session module
11355** function are undefined.
11356**
11357** Session objects must be deleted before the database handle to which they
11358** are attached is closed. Refer to the documentation for
11359** [sqlite3session_create()] for details.
11360*/
11361SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
11362
11363/*
11364** CAPI3REF: Configure a Session Object
11365** METHOD: sqlite3_session
11366**
11367** This method is used to configure a session object after it has been
11368** created. At present the only valid values for the second parameter are
11369** [SQLITE_SESSION_OBJCONFIG_SIZE] and [SQLITE_SESSION_OBJCONFIG_ROWID].
11370**
11371*/
11372SQLITE_API int sqlite3session_object_config(sqlite3_session*, int op, void *pArg);
11373
11374/*
11375** CAPI3REF: Options for sqlite3session_object_config
11376**
11377** The following values may passed as the the 2nd parameter to
11378** sqlite3session_object_config().
11379**
11380** <dt>SQLITE_SESSION_OBJCONFIG_SIZE <dd>
11381**   This option is used to set, clear or query the flag that enables
11382**   the [sqlite3session_changeset_size()] API. Because it imposes some
11383**   computational overhead, this API is disabled by default. Argument
11384**   pArg must point to a value of type (int). If the value is initially
11385**   0, then the sqlite3session_changeset_size() API is disabled. If it
11386**   is greater than 0, then the same API is enabled. Or, if the initial
11387**   value is less than zero, no change is made. In all cases the (int)
11388**   variable is set to 1 if the sqlite3session_changeset_size() API is
11389**   enabled following the current call, or 0 otherwise.
11390**
11391**   It is an error (SQLITE_MISUSE) to attempt to modify this setting after
11392**   the first table has been attached to the session object.
11393**
11394** <dt>SQLITE_SESSION_OBJCONFIG_ROWID <dd>
11395**   This option is used to set, clear or query the flag that enables
11396**   collection of data for tables with no explicit PRIMARY KEY.
11397**
11398**   Normally, tables with no explicit PRIMARY KEY are simply ignored
11399**   by the sessions module. However, if this flag is set, it behaves
11400**   as if such tables have a column "_rowid_ INTEGER PRIMARY KEY" inserted
11401**   as their leftmost columns.
11402**
11403**   It is an error (SQLITE_MISUSE) to attempt to modify this setting after
11404**   the first table has been attached to the session object.
11405*/
11406#define SQLITE_SESSION_OBJCONFIG_SIZE  1
11407#define SQLITE_SESSION_OBJCONFIG_ROWID 2
11408
11409/*
11410** CAPI3REF: Enable Or Disable A Session Object
11411** METHOD: sqlite3_session
11412**
11413** Enable or disable the recording of changes by a session object. When
11414** enabled, a session object records changes made to the database. When
11415** disabled - it does not. A newly created session object is enabled.
11416** Refer to the documentation for [sqlite3session_changeset()] for further
11417** details regarding how enabling and disabling a session object affects
11418** the eventual changesets.
11419**
11420** Passing zero to this function disables the session. Passing a value
11421** greater than zero enables it. Passing a value less than zero is a
11422** no-op, and may be used to query the current state of the session.
11423**
11424** The return value indicates the final state of the session object: 0 if
11425** the session is disabled, or 1 if it is enabled.
11426*/
11427SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
11428
11429/*
11430** CAPI3REF: Set Or Clear the Indirect Change Flag
11431** METHOD: sqlite3_session
11432**
11433** Each change recorded by a session object is marked as either direct or
11434** indirect. A change is marked as indirect if either:
11435**
11436** <ul>
11437**   <li> The session object "indirect" flag is set when the change is
11438**        made, or
11439**   <li> The change is made by an SQL trigger or foreign key action
11440**        instead of directly as a result of a users SQL statement.
11441** </ul>
11442**
11443** If a single row is affected by more than one operation within a session,
11444** then the change is considered indirect if all operations meet the criteria
11445** for an indirect change above, or direct otherwise.
11446**
11447** This function is used to set, clear or query the session object indirect
11448** flag.  If the second argument passed to this function is zero, then the
11449** indirect flag is cleared. If it is greater than zero, the indirect flag
11450** is set. Passing a value less than zero does not modify the current value
11451** of the indirect flag, and may be used to query the current state of the
11452** indirect flag for the specified session object.
11453**
11454** The return value indicates the final state of the indirect flag: 0 if
11455** it is clear, or 1 if it is set.
11456*/
11457SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
11458
11459/*
11460** CAPI3REF: Attach A Table To A Session Object
11461** METHOD: sqlite3_session
11462**
11463** If argument zTab is not NULL, then it is the name of a table to attach
11464** to the session object passed as the first argument. All subsequent changes
11465** made to the table while the session object is enabled will be recorded. See
11466** documentation for [sqlite3session_changeset()] for further details.
11467**
11468** Or, if argument zTab is NULL, then changes are recorded for all tables
11469** in the database. If additional tables are added to the database (by
11470** executing "CREATE TABLE" statements) after this call is made, changes for
11471** the new tables are also recorded.
11472**
11473** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
11474** defined as part of their CREATE TABLE statement. It does not matter if the
11475** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
11476** KEY may consist of a single column, or may be a composite key.
11477**
11478** It is not an error if the named table does not exist in the database. Nor
11479** is it an error if the named table does not have a PRIMARY KEY. However,
11480** no changes will be recorded in either of these scenarios.
11481**
11482** Changes are not recorded for individual rows that have NULL values stored
11483** in one or more of their PRIMARY KEY columns.
11484**
11485** SQLITE_OK is returned if the call completes without error. Or, if an error
11486** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
11487**
11488** <h3>Special sqlite_stat1 Handling</h3>
11489**
11490** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
11491** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
11492**  <pre>
11493**  &nbsp;     CREATE TABLE sqlite_stat1(tbl,idx,stat)
11494**  </pre>
11495**
11496** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
11497** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
11498** are recorded for rows for which (idx IS NULL) is true. However, for such
11499** rows a zero-length blob (SQL value X'') is stored in the changeset or
11500** patchset instead of a NULL value. This allows such changesets to be
11501** manipulated by legacy implementations of sqlite3changeset_invert(),
11502** concat() and similar.
11503**
11504** The sqlite3changeset_apply() function automatically converts the
11505** zero-length blob back to a NULL value when updating the sqlite_stat1
11506** table. However, if the application calls sqlite3changeset_new(),
11507** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
11508** iterator directly (including on a changeset iterator passed to a
11509** conflict-handler callback) then the X'' value is returned. The application
11510** must translate X'' to NULL itself if required.
11511**
11512** Legacy (older than 3.22.0) versions of the sessions module cannot capture
11513** changes made to the sqlite_stat1 table. Legacy versions of the
11514** sqlite3changeset_apply() function silently ignore any modifications to the
11515** sqlite_stat1 table that are part of a changeset or patchset.
11516*/
11517SQLITE_API int sqlite3session_attach(
11518  sqlite3_session *pSession,      /* Session object */
11519  const char *zTab                /* Table name */
11520);
11521
11522/*
11523** CAPI3REF: Set a table filter on a Session Object.
11524** METHOD: sqlite3_session
11525**
11526** The second argument (xFilter) is the "filter callback". For changes to rows
11527** in tables that are not attached to the Session object, the filter is called
11528** to determine whether changes to the table's rows should be tracked or not.
11529** If xFilter returns 0, changes are not tracked. Note that once a table is
11530** attached, xFilter will not be called again.
11531*/
11532SQLITE_API void sqlite3session_table_filter(
11533  sqlite3_session *pSession,      /* Session object */
11534  int(*xFilter)(
11535    void *pCtx,                   /* Copy of third arg to _filter_table() */
11536    const char *zTab              /* Table name */
11537  ),
11538  void *pCtx                      /* First argument passed to xFilter */
11539);
11540
11541/*
11542** CAPI3REF: Generate A Changeset From A Session Object
11543** METHOD: sqlite3_session
11544**
11545** Obtain a changeset containing changes to the tables attached to the
11546** session object passed as the first argument. If successful,
11547** set *ppChangeset to point to a buffer containing the changeset
11548** and *pnChangeset to the size of the changeset in bytes before returning
11549** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
11550** zero and return an SQLite error code.
11551**
11552** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
11553** each representing a change to a single row of an attached table. An INSERT
11554** change contains the values of each field of a new database row. A DELETE
11555** contains the original values of each field of a deleted database row. An
11556** UPDATE change contains the original values of each field of an updated
11557** database row along with the updated values for each updated non-primary-key
11558** column. It is not possible for an UPDATE change to represent a change that
11559** modifies the values of primary key columns. If such a change is made, it
11560** is represented in a changeset as a DELETE followed by an INSERT.
11561**
11562** Changes are not recorded for rows that have NULL values stored in one or
11563** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
11564** no corresponding change is present in the changesets returned by this
11565** function. If an existing row with one or more NULL values stored in
11566** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
11567** only an INSERT is appears in the changeset. Similarly, if an existing row
11568** with non-NULL PRIMARY KEY values is updated so that one or more of its
11569** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
11570** DELETE change only.
11571**
11572** The contents of a changeset may be traversed using an iterator created
11573** using the [sqlite3changeset_start()] API. A changeset may be applied to
11574** a database with a compatible schema using the [sqlite3changeset_apply()]
11575** API.
11576**
11577** Within a changeset generated by this function, all changes related to a
11578** single table are grouped together. In other words, when iterating through
11579** a changeset or when applying a changeset to a database, all changes related
11580** to a single table are processed before moving on to the next table. Tables
11581** are sorted in the same order in which they were attached (or auto-attached)
11582** to the sqlite3_session object. The order in which the changes related to
11583** a single table are stored is undefined.
11584**
11585** Following a successful call to this function, it is the responsibility of
11586** the caller to eventually free the buffer that *ppChangeset points to using
11587** [sqlite3_free()].
11588**
11589** <h3>Changeset Generation</h3>
11590**
11591** Once a table has been attached to a session object, the session object
11592** records the primary key values of all new rows inserted into the table.
11593** It also records the original primary key and other column values of any
11594** deleted or updated rows. For each unique primary key value, data is only
11595** recorded once - the first time a row with said primary key is inserted,
11596** updated or deleted in the lifetime of the session.
11597**
11598** There is one exception to the previous paragraph: when a row is inserted,
11599** updated or deleted, if one or more of its primary key columns contain a
11600** NULL value, no record of the change is made.
11601**
11602** The session object therefore accumulates two types of records - those
11603** that consist of primary key values only (created when the user inserts
11604** a new record) and those that consist of the primary key values and the
11605** original values of other table columns (created when the users deletes
11606** or updates a record).
11607**
11608** When this function is called, the requested changeset is created using
11609** both the accumulated records and the current contents of the database
11610** file. Specifically:
11611**
11612** <ul>
11613**   <li> For each record generated by an insert, the database is queried
11614**        for a row with a matching primary key. If one is found, an INSERT
11615**        change is added to the changeset. If no such row is found, no change
11616**        is added to the changeset.
11617**
11618**   <li> For each record generated by an update or delete, the database is
11619**        queried for a row with a matching primary key. If such a row is
11620**        found and one or more of the non-primary key fields have been
11621**        modified from their original values, an UPDATE change is added to
11622**        the changeset. Or, if no such row is found in the table, a DELETE
11623**        change is added to the changeset. If there is a row with a matching
11624**        primary key in the database, but all fields contain their original
11625**        values, no change is added to the changeset.
11626** </ul>
11627**
11628** This means, amongst other things, that if a row is inserted and then later
11629** deleted while a session object is active, neither the insert nor the delete
11630** will be present in the changeset. Or if a row is deleted and then later a
11631** row with the same primary key values inserted while a session object is
11632** active, the resulting changeset will contain an UPDATE change instead of
11633** a DELETE and an INSERT.
11634**
11635** When a session object is disabled (see the [sqlite3session_enable()] API),
11636** it does not accumulate records when rows are inserted, updated or deleted.
11637** This may appear to have some counter-intuitive effects if a single row
11638** is written to more than once during a session. For example, if a row
11639** is inserted while a session object is enabled, then later deleted while
11640** the same session object is disabled, no INSERT record will appear in the
11641** changeset, even though the delete took place while the session was disabled.
11642** Or, if one field of a row is updated while a session is disabled, and
11643** another field of the same row is updated while the session is enabled, the
11644** resulting changeset will contain an UPDATE change that updates both fields.
11645*/
11646SQLITE_API int sqlite3session_changeset(
11647  sqlite3_session *pSession,      /* Session object */
11648  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
11649  void **ppChangeset              /* OUT: Buffer containing changeset */
11650);
11651
11652/*
11653** CAPI3REF: Return An Upper-limit For The Size Of The Changeset
11654** METHOD: sqlite3_session
11655**
11656** By default, this function always returns 0. For it to return
11657** a useful result, the sqlite3_session object must have been configured
11658** to enable this API using sqlite3session_object_config() with the
11659** SQLITE_SESSION_OBJCONFIG_SIZE verb.
11660**
11661** When enabled, this function returns an upper limit, in bytes, for the size
11662** of the changeset that might be produced if sqlite3session_changeset() were
11663** called. The final changeset size might be equal to or smaller than the
11664** size in bytes returned by this function.
11665*/
11666SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession);
11667
11668/*
11669** CAPI3REF: Load The Difference Between Tables Into A Session
11670** METHOD: sqlite3_session
11671**
11672** If it is not already attached to the session object passed as the first
11673** argument, this function attaches table zTbl in the same manner as the
11674** [sqlite3session_attach()] function. If zTbl does not exist, or if it
11675** does not have a primary key, this function is a no-op (but does not return
11676** an error).
11677**
11678** Argument zFromDb must be the name of a database ("main", "temp" etc.)
11679** attached to the same database handle as the session object that contains
11680** a table compatible with the table attached to the session by this function.
11681** A table is considered compatible if it:
11682**
11683** <ul>
11684**   <li> Has the same name,
11685**   <li> Has the same set of columns declared in the same order, and
11686**   <li> Has the same PRIMARY KEY definition.
11687** </ul>
11688**
11689** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
11690** are compatible but do not have any PRIMARY KEY columns, it is not an error
11691** but no changes are added to the session object. As with other session
11692** APIs, tables without PRIMARY KEYs are simply ignored.
11693**
11694** This function adds a set of changes to the session object that could be
11695** used to update the table in database zFrom (call this the "from-table")
11696** so that its content is the same as the table attached to the session
11697** object (call this the "to-table"). Specifically:
11698**
11699** <ul>
11700**   <li> For each row (primary key) that exists in the to-table but not in
11701**     the from-table, an INSERT record is added to the session object.
11702**
11703**   <li> For each row (primary key) that exists in the to-table but not in
11704**     the from-table, a DELETE record is added to the session object.
11705**
11706**   <li> For each row (primary key) that exists in both tables, but features
11707**     different non-PK values in each, an UPDATE record is added to the
11708**     session.
11709** </ul>
11710**
11711** To clarify, if this function is called and then a changeset constructed
11712** using [sqlite3session_changeset()], then after applying that changeset to
11713** database zFrom the contents of the two compatible tables would be
11714** identical.
11715**
11716** It an error if database zFrom does not exist or does not contain the
11717** required compatible table.
11718**
11719** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite
11720** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
11721** may be set to point to a buffer containing an English language error
11722** message. It is the responsibility of the caller to free this buffer using
11723** sqlite3_free().
11724*/
11725SQLITE_API int sqlite3session_diff(
11726  sqlite3_session *pSession,
11727  const char *zFromDb,
11728  const char *zTbl,
11729  char **pzErrMsg
11730);
11731
11732
11733/*
11734** CAPI3REF: Generate A Patchset From A Session Object
11735** METHOD: sqlite3_session
11736**
11737** The differences between a patchset and a changeset are that:
11738**
11739** <ul>
11740**   <li> DELETE records consist of the primary key fields only. The
11741**        original values of other fields are omitted.
11742**   <li> The original values of any modified fields are omitted from
11743**        UPDATE records.
11744** </ul>
11745**
11746** A patchset blob may be used with up to date versions of all
11747** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
11748** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
11749** attempting to use a patchset blob with old versions of the
11750** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
11751**
11752** Because the non-primary key "old.*" fields are omitted, no
11753** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
11754** is passed to the sqlite3changeset_apply() API. Other conflict types work
11755** in the same way as for changesets.
11756**
11757** Changes within a patchset are ordered in the same way as for changesets
11758** generated by the sqlite3session_changeset() function (i.e. all changes for
11759** a single table are grouped together, tables appear in the order in which
11760** they were attached to the session object).
11761*/
11762SQLITE_API int sqlite3session_patchset(
11763  sqlite3_session *pSession,      /* Session object */
11764  int *pnPatchset,                /* OUT: Size of buffer at *ppPatchset */
11765  void **ppPatchset               /* OUT: Buffer containing patchset */
11766);
11767
11768/*
11769** CAPI3REF: Test if a changeset has recorded any changes.
11770**
11771** Return non-zero if no changes to attached tables have been recorded by
11772** the session object passed as the first argument. Otherwise, if one or
11773** more changes have been recorded, return zero.
11774**
11775** Even if this function returns zero, it is possible that calling
11776** [sqlite3session_changeset()] on the session handle may still return a
11777** changeset that contains no changes. This can happen when a row in
11778** an attached table is modified and then later on the original values
11779** are restored. However, if this function returns non-zero, then it is
11780** guaranteed that a call to sqlite3session_changeset() will return a
11781** changeset containing zero changes.
11782*/
11783SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
11784
11785/*
11786** CAPI3REF: Query for the amount of heap memory used by a session object.
11787**
11788** This API returns the total amount of heap memory in bytes currently
11789** used by the session object passed as the only argument.
11790*/
11791SQLITE_API sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession);
11792
11793/*
11794** CAPI3REF: Create An Iterator To Traverse A Changeset
11795** CONSTRUCTOR: sqlite3_changeset_iter
11796**
11797** Create an iterator used to iterate through the contents of a changeset.
11798** If successful, *pp is set to point to the iterator handle and SQLITE_OK
11799** is returned. Otherwise, if an error occurs, *pp is set to zero and an
11800** SQLite error code is returned.
11801**
11802** The following functions can be used to advance and query a changeset
11803** iterator created by this function:
11804**
11805** <ul>
11806**   <li> [sqlite3changeset_next()]
11807**   <li> [sqlite3changeset_op()]
11808**   <li> [sqlite3changeset_new()]
11809**   <li> [sqlite3changeset_old()]
11810** </ul>
11811**
11812** It is the responsibility of the caller to eventually destroy the iterator
11813** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
11814** changeset (pChangeset) must remain valid until after the iterator is
11815** destroyed.
11816**
11817** Assuming the changeset blob was created by one of the
11818** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
11819** [sqlite3changeset_invert()] functions, all changes within the changeset
11820** that apply to a single table are grouped together. This means that when
11821** an application iterates through a changeset using an iterator created by
11822** this function, all changes that relate to a single table are visited
11823** consecutively. There is no chance that the iterator will visit a change
11824** the applies to table X, then one for table Y, and then later on visit
11825** another change for table X.
11826**
11827** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
11828** may be modified by passing a combination of
11829** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.
11830**
11831** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>
11832** and therefore subject to change.
11833*/
11834SQLITE_API int sqlite3changeset_start(
11835  sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */
11836  int nChangeset,                 /* Size of changeset blob in bytes */
11837  void *pChangeset                /* Pointer to blob containing changeset */
11838);
11839SQLITE_API int sqlite3changeset_start_v2(
11840  sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */
11841  int nChangeset,                 /* Size of changeset blob in bytes */
11842  void *pChangeset,               /* Pointer to blob containing changeset */
11843  int flags                       /* SESSION_CHANGESETSTART_* flags */
11844);
11845
11846/*
11847** CAPI3REF: Flags for sqlite3changeset_start_v2
11848**
11849** The following flags may passed via the 4th parameter to
11850** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:
11851**
11852** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
11853**   Invert the changeset while iterating through it. This is equivalent to
11854**   inverting a changeset using sqlite3changeset_invert() before applying it.
11855**   It is an error to specify this flag with a patchset.
11856*/
11857#define SQLITE_CHANGESETSTART_INVERT        0x0002
11858
11859
11860/*
11861** CAPI3REF: Advance A Changeset Iterator
11862** METHOD: sqlite3_changeset_iter
11863**
11864** This function may only be used with iterators created by the function
11865** [sqlite3changeset_start()]. If it is called on an iterator passed to
11866** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
11867** is returned and the call has no effect.
11868**
11869** Immediately after an iterator is created by sqlite3changeset_start(), it
11870** does not point to any change in the changeset. Assuming the changeset
11871** is not empty, the first call to this function advances the iterator to
11872** point to the first change in the changeset. Each subsequent call advances
11873** the iterator to point to the next change in the changeset (if any). If
11874** no error occurs and the iterator points to a valid change after a call
11875** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
11876** Otherwise, if all changes in the changeset have already been visited,
11877** SQLITE_DONE is returned.
11878**
11879** If an error occurs, an SQLite error code is returned. Possible error
11880** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
11881** SQLITE_NOMEM.
11882*/
11883SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
11884
11885/*
11886** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
11887** METHOD: sqlite3_changeset_iter
11888**
11889** The pIter argument passed to this function may either be an iterator
11890** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
11891** created by [sqlite3changeset_start()]. In the latter case, the most recent
11892** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
11893** is not the case, this function returns [SQLITE_MISUSE].
11894**
11895** Arguments pOp, pnCol and pzTab may not be NULL. Upon return, three
11896** outputs are set through these pointers:
11897**
11898** *pOp is set to one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
11899** depending on the type of change that the iterator currently points to;
11900**
11901** *pnCol is set to the number of columns in the table affected by the change; and
11902**
11903** *pzTab is set to point to a nul-terminated utf-8 encoded string containing
11904** the name of the table affected by the current change. The buffer remains
11905** valid until either sqlite3changeset_next() is called on the iterator
11906** or until the conflict-handler function returns.
11907**
11908** If pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
11909** is an indirect change, or false (0) otherwise. See the documentation for
11910** [sqlite3session_indirect()] for a description of direct and indirect
11911** changes.
11912**
11913** If no error occurs, SQLITE_OK is returned. If an error does occur, an
11914** SQLite error code is returned. The values of the output variables may not
11915** be trusted in this case.
11916*/
11917SQLITE_API int sqlite3changeset_op(
11918  sqlite3_changeset_iter *pIter,  /* Iterator object */
11919  const char **pzTab,             /* OUT: Pointer to table name */
11920  int *pnCol,                     /* OUT: Number of columns in table */
11921  int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
11922  int *pbIndirect                 /* OUT: True for an 'indirect' change */
11923);
11924
11925/*
11926** CAPI3REF: Obtain The Primary Key Definition Of A Table
11927** METHOD: sqlite3_changeset_iter
11928**
11929** For each modified table, a changeset includes the following:
11930**
11931** <ul>
11932**   <li> The number of columns in the table, and
11933**   <li> Which of those columns make up the tables PRIMARY KEY.
11934** </ul>
11935**
11936** This function is used to find which columns comprise the PRIMARY KEY of
11937** the table modified by the change that iterator pIter currently points to.
11938** If successful, *pabPK is set to point to an array of nCol entries, where
11939** nCol is the number of columns in the table. Elements of *pabPK are set to
11940** 0x01 if the corresponding column is part of the tables primary key, or
11941** 0x00 if it is not.
11942**
11943** If argument pnCol is not NULL, then *pnCol is set to the number of columns
11944** in the table.
11945**
11946** If this function is called when the iterator does not point to a valid
11947** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
11948** SQLITE_OK is returned and the output variables populated as described
11949** above.
11950*/
11951SQLITE_API int sqlite3changeset_pk(
11952  sqlite3_changeset_iter *pIter,  /* Iterator object */
11953  unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
11954  int *pnCol                      /* OUT: Number of entries in output array */
11955);
11956
11957/*
11958** CAPI3REF: Obtain old.* Values From A Changeset Iterator
11959** METHOD: sqlite3_changeset_iter
11960**
11961** The pIter argument passed to this function may either be an iterator
11962** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
11963** created by [sqlite3changeset_start()]. In the latter case, the most recent
11964** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
11965** Furthermore, it may only be called if the type of change that the iterator
11966** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
11967** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
11968**
11969** Argument iVal must be greater than or equal to 0, and less than the number
11970** of columns in the table affected by the current change. Otherwise,
11971** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
11972**
11973** If successful, this function sets *ppValue to point to a protected
11974** sqlite3_value object containing the iVal'th value from the vector of
11975** original row values stored as part of the UPDATE or DELETE change and
11976** returns SQLITE_OK. The name of the function comes from the fact that this
11977** is similar to the "old.*" columns available to update or delete triggers.
11978**
11979** If some other error occurs (e.g. an OOM condition), an SQLite error code
11980** is returned and *ppValue is set to NULL.
11981*/
11982SQLITE_API int sqlite3changeset_old(
11983  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
11984  int iVal,                       /* Column number */
11985  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
11986);
11987
11988/*
11989** CAPI3REF: Obtain new.* Values From A Changeset Iterator
11990** METHOD: sqlite3_changeset_iter
11991**
11992** The pIter argument passed to this function may either be an iterator
11993** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
11994** created by [sqlite3changeset_start()]. In the latter case, the most recent
11995** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
11996** Furthermore, it may only be called if the type of change that the iterator
11997** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
11998** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
11999**
12000** Argument iVal must be greater than or equal to 0, and less than the number
12001** of columns in the table affected by the current change. Otherwise,
12002** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
12003**
12004** If successful, this function sets *ppValue to point to a protected
12005** sqlite3_value object containing the iVal'th value from the vector of
12006** new row values stored as part of the UPDATE or INSERT change and
12007** returns SQLITE_OK. If the change is an UPDATE and does not include
12008** a new value for the requested column, *ppValue is set to NULL and
12009** SQLITE_OK returned. The name of the function comes from the fact that
12010** this is similar to the "new.*" columns available to update or delete
12011** triggers.
12012**
12013** If some other error occurs (e.g. an OOM condition), an SQLite error code
12014** is returned and *ppValue is set to NULL.
12015*/
12016SQLITE_API int sqlite3changeset_new(
12017  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
12018  int iVal,                       /* Column number */
12019  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
12020);
12021
12022/*
12023** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
12024** METHOD: sqlite3_changeset_iter
12025**
12026** This function should only be used with iterator objects passed to a
12027** conflict-handler callback by [sqlite3changeset_apply()] with either
12028** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
12029** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
12030** is set to NULL.
12031**
12032** Argument iVal must be greater than or equal to 0, and less than the number
12033** of columns in the table affected by the current change. Otherwise,
12034** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
12035**
12036** If successful, this function sets *ppValue to point to a protected
12037** sqlite3_value object containing the iVal'th value from the
12038** "conflicting row" associated with the current conflict-handler callback
12039** and returns SQLITE_OK.
12040**
12041** If some other error occurs (e.g. an OOM condition), an SQLite error code
12042** is returned and *ppValue is set to NULL.
12043*/
12044SQLITE_API int sqlite3changeset_conflict(
12045  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
12046  int iVal,                       /* Column number */
12047  sqlite3_value **ppValue         /* OUT: Value from conflicting row */
12048);
12049
12050/*
12051** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
12052** METHOD: sqlite3_changeset_iter
12053**
12054** This function may only be called with an iterator passed to an
12055** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
12056** it sets the output variable to the total number of known foreign key
12057** violations in the destination database and returns SQLITE_OK.
12058**
12059** In all other cases this function returns SQLITE_MISUSE.
12060*/
12061SQLITE_API int sqlite3changeset_fk_conflicts(
12062  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
12063  int *pnOut                      /* OUT: Number of FK violations */
12064);
12065
12066
12067/*
12068** CAPI3REF: Finalize A Changeset Iterator
12069** METHOD: sqlite3_changeset_iter
12070**
12071** This function is used to finalize an iterator allocated with
12072** [sqlite3changeset_start()].
12073**
12074** This function should only be called on iterators created using the
12075** [sqlite3changeset_start()] function. If an application calls this
12076** function with an iterator passed to a conflict-handler by
12077** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
12078** call has no effect.
12079**
12080** If an error was encountered within a call to an sqlite3changeset_xxx()
12081** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
12082** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
12083** to that error is returned by this function. Otherwise, SQLITE_OK is
12084** returned. This is to allow the following pattern (pseudo-code):
12085**
12086** <pre>
12087**   sqlite3changeset_start();
12088**   while( SQLITE_ROW==sqlite3changeset_next() ){
12089**     // Do something with change.
12090**   }
12091**   rc = sqlite3changeset_finalize();
12092**   if( rc!=SQLITE_OK ){
12093**     // An error has occurred
12094**   }
12095** </pre>
12096*/
12097SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
12098
12099/*
12100** CAPI3REF: Invert A Changeset
12101**
12102** This function is used to "invert" a changeset object. Applying an inverted
12103** changeset to a database reverses the effects of applying the uninverted
12104** changeset. Specifically:
12105**
12106** <ul>
12107**   <li> Each DELETE change is changed to an INSERT, and
12108**   <li> Each INSERT change is changed to a DELETE, and
12109**   <li> For each UPDATE change, the old.* and new.* values are exchanged.
12110** </ul>
12111**
12112** This function does not change the order in which changes appear within
12113** the changeset. It merely reverses the sense of each individual change.
12114**
12115** If successful, a pointer to a buffer containing the inverted changeset
12116** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
12117** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
12118** zeroed and an SQLite error code returned.
12119**
12120** It is the responsibility of the caller to eventually call sqlite3_free()
12121** on the *ppOut pointer to free the buffer allocation following a successful
12122** call to this function.
12123**
12124** WARNING/TODO: This function currently assumes that the input is a valid
12125** changeset. If it is not, the results are undefined.
12126*/
12127SQLITE_API int sqlite3changeset_invert(
12128  int nIn, const void *pIn,       /* Input changeset */
12129  int *pnOut, void **ppOut        /* OUT: Inverse of input */
12130);
12131
12132/*
12133** CAPI3REF: Concatenate Two Changeset Objects
12134**
12135** This function is used to concatenate two changesets, A and B, into a
12136** single changeset. The result is a changeset equivalent to applying
12137** changeset A followed by changeset B.
12138**
12139** This function combines the two input changesets using an
12140** sqlite3_changegroup object. Calling it produces similar results as the
12141** following code fragment:
12142**
12143** <pre>
12144**   sqlite3_changegroup *pGrp;
12145**   rc = sqlite3_changegroup_new(&pGrp);
12146**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
12147**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
12148**   if( rc==SQLITE_OK ){
12149**     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
12150**   }else{
12151**     *ppOut = 0;
12152**     *pnOut = 0;
12153**   }
12154** </pre>
12155**
12156** Refer to the sqlite3_changegroup documentation below for details.
12157*/
12158SQLITE_API int sqlite3changeset_concat(
12159  int nA,                         /* Number of bytes in buffer pA */
12160  void *pA,                       /* Pointer to buffer containing changeset A */
12161  int nB,                         /* Number of bytes in buffer pB */
12162  void *pB,                       /* Pointer to buffer containing changeset B */
12163  int *pnOut,                     /* OUT: Number of bytes in output changeset */
12164  void **ppOut                    /* OUT: Buffer containing output changeset */
12165);
12166
12167
12168/*
12169** CAPI3REF: Upgrade the Schema of a Changeset/Patchset
12170*/
12171SQLITE_API int sqlite3changeset_upgrade(
12172  sqlite3 *db,
12173  const char *zDb,
12174  int nIn, const void *pIn,       /* Input changeset */
12175  int *pnOut, void **ppOut        /* OUT: Inverse of input */
12176);
12177
12178
12179
12180/*
12181** CAPI3REF: Changegroup Handle
12182**
12183** A changegroup is an object used to combine two or more
12184** [changesets] or [patchsets]
12185*/
12186typedef struct sqlite3_changegroup sqlite3_changegroup;
12187
12188/*
12189** CAPI3REF: Create A New Changegroup Object
12190** CONSTRUCTOR: sqlite3_changegroup
12191**
12192** An sqlite3_changegroup object is used to combine two or more changesets
12193** (or patchsets) into a single changeset (or patchset). A single changegroup
12194** object may combine changesets or patchsets, but not both. The output is
12195** always in the same format as the input.
12196**
12197** If successful, this function returns SQLITE_OK and populates (*pp) with
12198** a pointer to a new sqlite3_changegroup object before returning. The caller
12199** should eventually free the returned object using a call to
12200** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
12201** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
12202**
12203** The usual usage pattern for an sqlite3_changegroup object is as follows:
12204**
12205** <ul>
12206**   <li> It is created using a call to sqlite3changegroup_new().
12207**
12208**   <li> Zero or more changesets (or patchsets) are added to the object
12209**        by calling sqlite3changegroup_add().
12210**
12211**   <li> The result of combining all input changesets together is obtained
12212**        by the application via a call to sqlite3changegroup_output().
12213**
12214**   <li> The object is deleted using a call to sqlite3changegroup_delete().
12215** </ul>
12216**
12217** Any number of calls to add() and output() may be made between the calls to
12218** new() and delete(), and in any order.
12219**
12220** As well as the regular sqlite3changegroup_add() and
12221** sqlite3changegroup_output() functions, also available are the streaming
12222** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
12223*/
12224SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
12225
12226/*
12227** CAPI3REF: Add a Schema to a Changegroup
12228** METHOD: sqlite3_changegroup_schema
12229**
12230** This method may be used to optionally enforce the rule that the changesets
12231** added to the changegroup handle must match the schema of database zDb
12232** ("main", "temp", or the name of an attached database). If
12233** sqlite3changegroup_add() is called to add a changeset that is not compatible
12234** with the configured schema, SQLITE_SCHEMA is returned and the changegroup
12235** object is left in an undefined state.
12236**
12237** A changeset schema is considered compatible with the database schema in
12238** the same way as for sqlite3changeset_apply(). Specifically, for each
12239** table in the changeset, there exists a database table with:
12240**
12241** <ul>
12242**   <li> The name identified by the changeset, and
12243**   <li> at least as many columns as recorded in the changeset, and
12244**   <li> the primary key columns in the same position as recorded in
12245**        the changeset.
12246** </ul>
12247**
12248** The output of the changegroup object always has the same schema as the
12249** database nominated using this function. In cases where changesets passed
12250** to sqlite3changegroup_add() have fewer columns than the corresponding table
12251** in the database schema, these are filled in using the default column
12252** values from the database schema. This makes it possible to combined
12253** changesets that have different numbers of columns for a single table
12254** within a changegroup, provided that they are otherwise compatible.
12255*/
12256SQLITE_API int sqlite3changegroup_schema(sqlite3_changegroup*, sqlite3*, const char *zDb);
12257
12258/*
12259** CAPI3REF: Add A Changeset To A Changegroup
12260** METHOD: sqlite3_changegroup
12261**
12262** Add all changes within the changeset (or patchset) in buffer pData (size
12263** nData bytes) to the changegroup.
12264**
12265** If the buffer contains a patchset, then all prior calls to this function
12266** on the same changegroup object must also have specified patchsets. Or, if
12267** the buffer contains a changeset, so must have the earlier calls to this
12268** function. Otherwise, SQLITE_ERROR is returned and no changes are added
12269** to the changegroup.
12270**
12271** Rows within the changeset and changegroup are identified by the values in
12272** their PRIMARY KEY columns. A change in the changeset is considered to
12273** apply to the same row as a change already present in the changegroup if
12274** the two rows have the same primary key.
12275**
12276** Changes to rows that do not already appear in the changegroup are
12277** simply copied into it. Or, if both the new changeset and the changegroup
12278** contain changes that apply to a single row, the final contents of the
12279** changegroup depends on the type of each change, as follows:
12280**
12281** <table border=1 style="margin-left:8ex;margin-right:8ex">
12282**   <tr><th style="white-space:pre">Existing Change  </th>
12283**       <th style="white-space:pre">New Change       </th>
12284**       <th>Output Change
12285**   <tr><td>INSERT <td>INSERT <td>
12286**       The new change is ignored. This case does not occur if the new
12287**       changeset was recorded immediately after the changesets already
12288**       added to the changegroup.
12289**   <tr><td>INSERT <td>UPDATE <td>
12290**       The INSERT change remains in the changegroup. The values in the
12291**       INSERT change are modified as if the row was inserted by the
12292**       existing change and then updated according to the new change.
12293**   <tr><td>INSERT <td>DELETE <td>
12294**       The existing INSERT is removed from the changegroup. The DELETE is
12295**       not added.
12296**   <tr><td>UPDATE <td>INSERT <td>
12297**       The new change is ignored. This case does not occur if the new
12298**       changeset was recorded immediately after the changesets already
12299**       added to the changegroup.
12300**   <tr><td>UPDATE <td>UPDATE <td>
12301**       The existing UPDATE remains within the changegroup. It is amended
12302**       so that the accompanying values are as if the row was updated once
12303**       by the existing change and then again by the new change.
12304**   <tr><td>UPDATE <td>DELETE <td>
12305**       The existing UPDATE is replaced by the new DELETE within the
12306**       changegroup.
12307**   <tr><td>DELETE <td>INSERT <td>
12308**       If one or more of the column values in the row inserted by the
12309**       new change differ from those in the row deleted by the existing
12310**       change, the existing DELETE is replaced by an UPDATE within the
12311**       changegroup. Otherwise, if the inserted row is exactly the same
12312**       as the deleted row, the existing DELETE is simply discarded.
12313**   <tr><td>DELETE <td>UPDATE <td>
12314**       The new change is ignored. This case does not occur if the new
12315**       changeset was recorded immediately after the changesets already
12316**       added to the changegroup.
12317**   <tr><td>DELETE <td>DELETE <td>
12318**       The new change is ignored. This case does not occur if the new
12319**       changeset was recorded immediately after the changesets already
12320**       added to the changegroup.
12321** </table>
12322**
12323** If the new changeset contains changes to a table that is already present
12324** in the changegroup, then the number of columns and the position of the
12325** primary key columns for the table must be consistent. If this is not the
12326** case, this function fails with SQLITE_SCHEMA. Except, if the changegroup
12327** object has been configured with a database schema using the
12328** sqlite3changegroup_schema() API, then it is possible to combine changesets
12329** with different numbers of columns for a single table, provided that
12330** they are otherwise compatible.
12331**
12332** If the input changeset appears to be corrupt and the corruption is
12333** detected, SQLITE_CORRUPT is returned. Or, if an out-of-memory condition
12334** occurs during processing, this function returns SQLITE_NOMEM.
12335**
12336** In all cases, if an error occurs the state of the final contents of the
12337** changegroup is undefined. If no error occurs, SQLITE_OK is returned.
12338*/
12339SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
12340
12341/*
12342** CAPI3REF: Add A Single Change To A Changegroup
12343** METHOD: sqlite3_changegroup
12344**
12345** This function adds the single change currently indicated by the iterator
12346** passed as the second argument to the changegroup object. The rules for
12347** adding the change are just as described for [sqlite3changegroup_add()].
12348**
12349** If the change is successfully added to the changegroup, SQLITE_OK is
12350** returned. Otherwise, an SQLite error code is returned.
12351**
12352** The iterator must point to a valid entry when this function is called.
12353** If it does not, SQLITE_ERROR is returned and no change is added to the
12354** changegroup. Additionally, the iterator must not have been opened with
12355** the SQLITE_CHANGESETAPPLY_INVERT flag. In this case SQLITE_ERROR is also
12356** returned.
12357*/
12358SQLITE_API int sqlite3changegroup_add_change(
12359  sqlite3_changegroup*,
12360  sqlite3_changeset_iter*
12361);
12362
12363
12364
12365/*
12366** CAPI3REF: Obtain A Composite Changeset From A Changegroup
12367** METHOD: sqlite3_changegroup
12368**
12369** Obtain a buffer containing a changeset (or patchset) representing the
12370** current contents of the changegroup. If the inputs to the changegroup
12371** were themselves changesets, the output is a changeset. Or, if the
12372** inputs were patchsets, the output is also a patchset.
12373**
12374** As with the output of the sqlite3session_changeset() and
12375** sqlite3session_patchset() functions, all changes related to a single
12376** table are grouped together in the output of this function. Tables appear
12377** in the same order as for the very first changeset added to the changegroup.
12378** If the second or subsequent changesets added to the changegroup contain
12379** changes for tables that do not appear in the first changeset, they are
12380** appended onto the end of the output changeset, again in the order in
12381** which they are first encountered.
12382**
12383** If an error occurs, an SQLite error code is returned and the output
12384** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
12385** is returned and the output variables are set to the size of and a
12386** pointer to the output buffer, respectively. In this case it is the
12387** responsibility of the caller to eventually free the buffer using a
12388** call to sqlite3_free().
12389*/
12390SQLITE_API int sqlite3changegroup_output(
12391  sqlite3_changegroup*,
12392  int *pnData,                    /* OUT: Size of output buffer in bytes */
12393  void **ppData                   /* OUT: Pointer to output buffer */
12394);
12395
12396/*
12397** CAPI3REF: Delete A Changegroup Object
12398** DESTRUCTOR: sqlite3_changegroup
12399*/
12400SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
12401
12402/*
12403** CAPI3REF: Apply A Changeset To A Database
12404**
12405** Apply a changeset or patchset to a database. These functions attempt to
12406** update the "main" database attached to handle db with the changes found in
12407** the changeset passed via the second and third arguments.
12408**
12409** The fourth argument (xFilter) passed to these functions is the "filter
12410** callback". If it is not NULL, then for each table affected by at least one
12411** change in the changeset, the filter callback is invoked with
12412** the table name as the second argument, and a copy of the context pointer
12413** passed as the sixth argument as the first. If the "filter callback"
12414** returns zero, then no attempt is made to apply any changes to the table.
12415** Otherwise, if the return value is non-zero or the xFilter argument to
12416** is NULL, all changes related to the table are attempted.
12417**
12418** For each table that is not excluded by the filter callback, this function
12419** tests that the target database contains a compatible table. A table is
12420** considered compatible if all of the following are true:
12421**
12422** <ul>
12423**   <li> The table has the same name as the name recorded in the
12424**        changeset, and
12425**   <li> The table has at least as many columns as recorded in the
12426**        changeset, and
12427**   <li> The table has primary key columns in the same position as
12428**        recorded in the changeset.
12429** </ul>
12430**
12431** If there is no compatible table, it is not an error, but none of the
12432** changes associated with the table are applied. A warning message is issued
12433** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
12434** one such warning is issued for each table in the changeset.
12435**
12436** For each change for which there is a compatible table, an attempt is made
12437** to modify the table contents according to the UPDATE, INSERT or DELETE
12438** change. If a change cannot be applied cleanly, the conflict handler
12439** function passed as the fifth argument to sqlite3changeset_apply() may be
12440** invoked. A description of exactly when the conflict handler is invoked for
12441** each type of change is below.
12442**
12443** Unlike the xFilter argument, xConflict may not be passed NULL. The results
12444** of passing anything other than a valid function pointer as the xConflict
12445** argument are undefined.
12446**
12447** Each time the conflict handler function is invoked, it must return one
12448** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
12449** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
12450** if the second argument passed to the conflict handler is either
12451** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
12452** returns an illegal value, any changes already made are rolled back and
12453** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
12454** actions are taken by sqlite3changeset_apply() depending on the value
12455** returned by each invocation of the conflict-handler function. Refer to
12456** the documentation for the three
12457** [SQLITE_CHANGESET_OMIT|available return values] for details.
12458**
12459** <dl>
12460** <dt>DELETE Changes<dd>
12461**   For each DELETE change, the function checks if the target database
12462**   contains a row with the same primary key value (or values) as the
12463**   original row values stored in the changeset. If it does, and the values
12464**   stored in all non-primary key columns also match the values stored in
12465**   the changeset the row is deleted from the target database.
12466**
12467**   If a row with matching primary key values is found, but one or more of
12468**   the non-primary key fields contains a value different from the original
12469**   row value stored in the changeset, the conflict-handler function is
12470**   invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
12471**   database table has more columns than are recorded in the changeset,
12472**   only the values of those non-primary key fields are compared against
12473**   the current database contents - any trailing database table columns
12474**   are ignored.
12475**
12476**   If no row with matching primary key values is found in the database,
12477**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
12478**   passed as the second argument.
12479**
12480**   If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
12481**   (which can only happen if a foreign key constraint is violated), the
12482**   conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
12483**   passed as the second argument. This includes the case where the DELETE
12484**   operation is attempted because an earlier call to the conflict handler
12485**   function returned [SQLITE_CHANGESET_REPLACE].
12486**
12487** <dt>INSERT Changes<dd>
12488**   For each INSERT change, an attempt is made to insert the new row into
12489**   the database. If the changeset row contains fewer fields than the
12490**   database table, the trailing fields are populated with their default
12491**   values.
12492**
12493**   If the attempt to insert the row fails because the database already
12494**   contains a row with the same primary key values, the conflict handler
12495**   function is invoked with the second argument set to
12496**   [SQLITE_CHANGESET_CONFLICT].
12497**
12498**   If the attempt to insert the row fails because of some other constraint
12499**   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
12500**   invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
12501**   This includes the case where the INSERT operation is re-attempted because
12502**   an earlier call to the conflict handler function returned
12503**   [SQLITE_CHANGESET_REPLACE].
12504**
12505** <dt>UPDATE Changes<dd>
12506**   For each UPDATE change, the function checks if the target database
12507**   contains a row with the same primary key value (or values) as the
12508**   original row values stored in the changeset. If it does, and the values
12509**   stored in all modified non-primary key columns also match the values
12510**   stored in the changeset the row is updated within the target database.
12511**
12512**   If a row with matching primary key values is found, but one or more of
12513**   the modified non-primary key fields contains a value different from an
12514**   original row value stored in the changeset, the conflict-handler function
12515**   is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
12516**   UPDATE changes only contain values for non-primary key fields that are
12517**   to be modified, only those fields need to match the original values to
12518**   avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
12519**
12520**   If no row with matching primary key values is found in the database,
12521**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
12522**   passed as the second argument.
12523**
12524**   If the UPDATE operation is attempted, but SQLite returns
12525**   SQLITE_CONSTRAINT, the conflict-handler function is invoked with
12526**   [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
12527**   This includes the case where the UPDATE operation is attempted after
12528**   an earlier call to the conflict handler function returned
12529**   [SQLITE_CHANGESET_REPLACE].
12530** </dl>
12531**
12532** It is safe to execute SQL statements, including those that write to the
12533** table that the callback related to, from within the xConflict callback.
12534** This can be used to further customize the application's conflict
12535** resolution strategy.
12536**
12537** All changes made by these functions are enclosed in a savepoint transaction.
12538** If any other error (aside from a constraint failure when attempting to
12539** write to the target database) occurs, then the savepoint transaction is
12540** rolled back, restoring the target database to its original state, and an
12541** SQLite error code returned.
12542**
12543** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
12544** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
12545** may set (*ppRebase) to point to a "rebase" that may be used with the
12546** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
12547** is set to the size of the buffer in bytes. It is the responsibility of the
12548** caller to eventually free any such buffer using sqlite3_free(). The buffer
12549** is only allocated and populated if one or more conflicts were encountered
12550** while applying the patchset. See comments surrounding the sqlite3_rebaser
12551** APIs for further details.
12552**
12553** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent
12554** may be modified by passing a combination of
12555** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.
12556**
12557** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>
12558** and therefore subject to change.
12559*/
12560SQLITE_API int sqlite3changeset_apply(
12561  sqlite3 *db,                    /* Apply change to "main" db of this handle */
12562  int nChangeset,                 /* Size of changeset in bytes */
12563  void *pChangeset,               /* Changeset blob */
12564  int(*xFilter)(
12565    void *pCtx,                   /* Copy of sixth arg to _apply() */
12566    const char *zTab              /* Table name */
12567  ),
12568  int(*xConflict)(
12569    void *pCtx,                   /* Copy of sixth arg to _apply() */
12570    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
12571    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
12572  ),
12573  void *pCtx                      /* First argument passed to xConflict */
12574);
12575SQLITE_API int sqlite3changeset_apply_v2(
12576  sqlite3 *db,                    /* Apply change to "main" db of this handle */
12577  int nChangeset,                 /* Size of changeset in bytes */
12578  void *pChangeset,               /* Changeset blob */
12579  int(*xFilter)(
12580    void *pCtx,                   /* Copy of sixth arg to _apply() */
12581    const char *zTab              /* Table name */
12582  ),
12583  int(*xConflict)(
12584    void *pCtx,                   /* Copy of sixth arg to _apply() */
12585    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
12586    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
12587  ),
12588  void *pCtx,                     /* First argument passed to xConflict */
12589  void **ppRebase, int *pnRebase, /* OUT: Rebase data */
12590  int flags                       /* SESSION_CHANGESETAPPLY_* flags */
12591);
12592
12593/*
12594** CAPI3REF: Flags for sqlite3changeset_apply_v2
12595**
12596** The following flags may passed via the 9th parameter to
12597** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
12598**
12599** <dl>
12600** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>
12601**   Usually, the sessions module encloses all operations performed by
12602**   a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
12603**   SAVEPOINT is committed if the changeset or patchset is successfully
12604**   applied, or rolled back if an error occurs. Specifying this flag
12605**   causes the sessions module to omit this savepoint. In this case, if the
12606**   caller has an open transaction or savepoint when apply_v2() is called,
12607**   it may revert the partially applied changeset by rolling it back.
12608**
12609** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
12610**   Invert the changeset before applying it. This is equivalent to inverting
12611**   a changeset using sqlite3changeset_invert() before applying it. It is
12612**   an error to specify this flag with a patchset.
12613**
12614** <dt>SQLITE_CHANGESETAPPLY_IGNORENOOP <dd>
12615**   Do not invoke the conflict handler callback for any changes that
12616**   would not actually modify the database even if they were applied.
12617**   Specifically, this means that the conflict handler is not invoked
12618**   for:
12619**    <ul>
12620**    <li>a delete change if the row being deleted cannot be found,
12621**    <li>an update change if the modified fields are already set to
12622**        their new values in the conflicting row, or
12623**    <li>an insert change if all fields of the conflicting row match
12624**        the row being inserted.
12625**    </ul>
12626**
12627** <dt>SQLITE_CHANGESETAPPLY_FKNOACTION <dd>
12628**   If this flag it set, then all foreign key constraints in the target
12629**   database behave as if they were declared with "ON UPDATE NO ACTION ON
12630**   DELETE NO ACTION", even if they are actually CASCADE, RESTRICT, SET NULL
12631**   or SET DEFAULT.
12632*/
12633#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x0001
12634#define SQLITE_CHANGESETAPPLY_INVERT        0x0002
12635#define SQLITE_CHANGESETAPPLY_IGNORENOOP    0x0004
12636#define SQLITE_CHANGESETAPPLY_FKNOACTION    0x0008
12637
12638/*
12639** CAPI3REF: Constants Passed To The Conflict Handler
12640**
12641** Values that may be passed as the second argument to a conflict-handler.
12642**
12643** <dl>
12644** <dt>SQLITE_CHANGESET_DATA<dd>
12645**   The conflict handler is invoked with CHANGESET_DATA as the second argument
12646**   when processing a DELETE or UPDATE change if a row with the required
12647**   PRIMARY KEY fields is present in the database, but one or more other
12648**   (non primary-key) fields modified by the update do not contain the
12649**   expected "before" values.
12650**
12651**   The conflicting row, in this case, is the database row with the matching
12652**   primary key.
12653**
12654** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
12655**   The conflict handler is invoked with CHANGESET_NOTFOUND as the second
12656**   argument when processing a DELETE or UPDATE change if a row with the
12657**   required PRIMARY KEY fields is not present in the database.
12658**
12659**   There is no conflicting row in this case. The results of invoking the
12660**   sqlite3changeset_conflict() API are undefined.
12661**
12662** <dt>SQLITE_CHANGESET_CONFLICT<dd>
12663**   CHANGESET_CONFLICT is passed as the second argument to the conflict
12664**   handler while processing an INSERT change if the operation would result
12665**   in duplicate primary key values.
12666**
12667**   The conflicting row in this case is the database row with the matching
12668**   primary key.
12669**
12670** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
12671**   If foreign key handling is enabled, and applying a changeset leaves the
12672**   database in a state containing foreign key violations, the conflict
12673**   handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
12674**   exactly once before the changeset is committed. If the conflict handler
12675**   returns CHANGESET_OMIT, the changes, including those that caused the
12676**   foreign key constraint violation, are committed. Or, if it returns
12677**   CHANGESET_ABORT, the changeset is rolled back.
12678**
12679**   No current or conflicting row information is provided. The only function
12680**   it is possible to call on the supplied sqlite3_changeset_iter handle
12681**   is sqlite3changeset_fk_conflicts().
12682**
12683** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
12684**   If any other constraint violation occurs while applying a change (i.e.
12685**   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
12686**   invoked with CHANGESET_CONSTRAINT as the second argument.
12687**
12688**   There is no conflicting row in this case. The results of invoking the
12689**   sqlite3changeset_conflict() API are undefined.
12690**
12691** </dl>
12692*/
12693#define SQLITE_CHANGESET_DATA        1
12694#define SQLITE_CHANGESET_NOTFOUND    2
12695#define SQLITE_CHANGESET_CONFLICT    3
12696#define SQLITE_CHANGESET_CONSTRAINT  4
12697#define SQLITE_CHANGESET_FOREIGN_KEY 5
12698
12699/*
12700** CAPI3REF: Constants Returned By The Conflict Handler
12701**
12702** A conflict handler callback must return one of the following three values.
12703**
12704** <dl>
12705** <dt>SQLITE_CHANGESET_OMIT<dd>
12706**   If a conflict handler returns this value no special action is taken. The
12707**   change that caused the conflict is not applied. The session module
12708**   continues to the next change in the changeset.
12709**
12710** <dt>SQLITE_CHANGESET_REPLACE<dd>
12711**   This value may only be returned if the second argument to the conflict
12712**   handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
12713**   is not the case, any changes applied so far are rolled back and the
12714**   call to sqlite3changeset_apply() returns SQLITE_MISUSE.
12715**
12716**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
12717**   handler, then the conflicting row is either updated or deleted, depending
12718**   on the type of change.
12719**
12720**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
12721**   handler, then the conflicting row is removed from the database and a
12722**   second attempt to apply the change is made. If this second attempt fails,
12723**   the original row is restored to the database before continuing.
12724**
12725** <dt>SQLITE_CHANGESET_ABORT<dd>
12726**   If this value is returned, any changes applied so far are rolled back
12727**   and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
12728** </dl>
12729*/
12730#define SQLITE_CHANGESET_OMIT       0
12731#define SQLITE_CHANGESET_REPLACE    1
12732#define SQLITE_CHANGESET_ABORT      2
12733
12734/*
12735** CAPI3REF: Rebasing changesets
12736** EXPERIMENTAL
12737**
12738** Suppose there is a site hosting a database in state S0. And that
12739** modifications are made that move that database to state S1 and a
12740** changeset recorded (the "local" changeset). Then, a changeset based
12741** on S0 is received from another site (the "remote" changeset) and
12742** applied to the database. The database is then in state
12743** (S1+"remote"), where the exact state depends on any conflict
12744** resolution decisions (OMIT or REPLACE) made while applying "remote".
12745** Rebasing a changeset is to update it to take those conflict
12746** resolution decisions into account, so that the same conflicts
12747** do not have to be resolved elsewhere in the network.
12748**
12749** For example, if both the local and remote changesets contain an
12750** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
12751**
12752**   local:  INSERT INTO t1 VALUES(1, 'v1');
12753**   remote: INSERT INTO t1 VALUES(1, 'v2');
12754**
12755** and the conflict resolution is REPLACE, then the INSERT change is
12756** removed from the local changeset (it was overridden). Or, if the
12757** conflict resolution was "OMIT", then the local changeset is modified
12758** to instead contain:
12759**
12760**           UPDATE t1 SET b = 'v2' WHERE a=1;
12761**
12762** Changes within the local changeset are rebased as follows:
12763**
12764** <dl>
12765** <dt>Local INSERT<dd>
12766**   This may only conflict with a remote INSERT. If the conflict
12767**   resolution was OMIT, then add an UPDATE change to the rebased
12768**   changeset. Or, if the conflict resolution was REPLACE, add
12769**   nothing to the rebased changeset.
12770**
12771** <dt>Local DELETE<dd>
12772**   This may conflict with a remote UPDATE or DELETE. In both cases the
12773**   only possible resolution is OMIT. If the remote operation was a
12774**   DELETE, then add no change to the rebased changeset. If the remote
12775**   operation was an UPDATE, then the old.* fields of change are updated
12776**   to reflect the new.* values in the UPDATE.
12777**
12778** <dt>Local UPDATE<dd>
12779**   This may conflict with a remote UPDATE or DELETE. If it conflicts
12780**   with a DELETE, and the conflict resolution was OMIT, then the update
12781**   is changed into an INSERT. Any undefined values in the new.* record
12782**   from the update change are filled in using the old.* values from
12783**   the conflicting DELETE. Or, if the conflict resolution was REPLACE,
12784**   the UPDATE change is simply omitted from the rebased changeset.
12785**
12786**   If conflict is with a remote UPDATE and the resolution is OMIT, then
12787**   the old.* values are rebased using the new.* values in the remote
12788**   change. Or, if the resolution is REPLACE, then the change is copied
12789**   into the rebased changeset with updates to columns also updated by
12790**   the conflicting remote UPDATE removed. If this means no columns would
12791**   be updated, the change is omitted.
12792** </dl>
12793**
12794** A local change may be rebased against multiple remote changes
12795** simultaneously. If a single key is modified by multiple remote
12796** changesets, they are combined as follows before the local changeset
12797** is rebased:
12798**
12799** <ul>
12800**    <li> If there has been one or more REPLACE resolutions on a
12801**         key, it is rebased according to a REPLACE.
12802**
12803**    <li> If there have been no REPLACE resolutions on a key, then
12804**         the local changeset is rebased according to the most recent
12805**         of the OMIT resolutions.
12806** </ul>
12807**
12808** Note that conflict resolutions from multiple remote changesets are
12809** combined on a per-field basis, not per-row. This means that in the
12810** case of multiple remote UPDATE operations, some fields of a single
12811** local change may be rebased for REPLACE while others are rebased for
12812** OMIT.
12813**
12814** In order to rebase a local changeset, the remote changeset must first
12815** be applied to the local database using sqlite3changeset_apply_v2() and
12816** the buffer of rebase information captured. Then:
12817**
12818** <ol>
12819**   <li> An sqlite3_rebaser object is created by calling
12820**        sqlite3rebaser_create().
12821**   <li> The new object is configured with the rebase buffer obtained from
12822**        sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
12823**        If the local changeset is to be rebased against multiple remote
12824**        changesets, then sqlite3rebaser_configure() should be called
12825**        multiple times, in the same order that the multiple
12826**        sqlite3changeset_apply_v2() calls were made.
12827**   <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().
12828**   <li> The sqlite3_rebaser object is deleted by calling
12829**        sqlite3rebaser_delete().
12830** </ol>
12831*/
12832typedef struct sqlite3_rebaser sqlite3_rebaser;
12833
12834/*
12835** CAPI3REF: Create a changeset rebaser object.
12836** EXPERIMENTAL
12837**
12838** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
12839** point to the new object and return SQLITE_OK. Otherwise, if an error
12840** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
12841** to NULL.
12842*/
12843SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
12844
12845/*
12846** CAPI3REF: Configure a changeset rebaser object.
12847** EXPERIMENTAL
12848**
12849** Configure the changeset rebaser object to rebase changesets according
12850** to the conflict resolutions described by buffer pRebase (size nRebase
12851** bytes), which must have been obtained from a previous call to
12852** sqlite3changeset_apply_v2().
12853*/
12854SQLITE_API int sqlite3rebaser_configure(
12855  sqlite3_rebaser*,
12856  int nRebase, const void *pRebase
12857);
12858
12859/*
12860** CAPI3REF: Rebase a changeset
12861** EXPERIMENTAL
12862**
12863** Argument pIn must point to a buffer containing a changeset nIn bytes
12864** in size. This function allocates and populates a buffer with a copy
12865** of the changeset rebased according to the configuration of the
12866** rebaser object passed as the first argument. If successful, (*ppOut)
12867** is set to point to the new buffer containing the rebased changeset and
12868** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
12869** responsibility of the caller to eventually free the new buffer using
12870** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
12871** are set to zero and an SQLite error code returned.
12872*/
12873SQLITE_API int sqlite3rebaser_rebase(
12874  sqlite3_rebaser*,
12875  int nIn, const void *pIn,
12876  int *pnOut, void **ppOut
12877);
12878
12879/*
12880** CAPI3REF: Delete a changeset rebaser object.
12881** EXPERIMENTAL
12882**
12883** Delete the changeset rebaser object and all associated resources. There
12884** should be one call to this function for each successful invocation
12885** of sqlite3rebaser_create().
12886*/
12887SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
12888
12889/*
12890** CAPI3REF: Streaming Versions of API functions.
12891**
12892** The six streaming API xxx_strm() functions serve similar purposes to the
12893** corresponding non-streaming API functions:
12894**
12895** <table border=1 style="margin-left:8ex;margin-right:8ex">
12896**   <tr><th>Streaming function<th>Non-streaming equivalent</th>
12897**   <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
12898**   <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]
12899**   <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
12900**   <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
12901**   <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
12902**   <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
12903**   <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
12904** </table>
12905**
12906** Non-streaming functions that accept changesets (or patchsets) as input
12907** require that the entire changeset be stored in a single buffer in memory.
12908** Similarly, those that return a changeset or patchset do so by returning
12909** a pointer to a single large buffer allocated using sqlite3_malloc().
12910** Normally this is convenient. However, if an application running in a
12911** low-memory environment is required to handle very large changesets, the
12912** large contiguous memory allocations required can become onerous.
12913**
12914** In order to avoid this problem, instead of a single large buffer, input
12915** is passed to a streaming API functions by way of a callback function that
12916** the sessions module invokes to incrementally request input data as it is
12917** required. In all cases, a pair of API function parameters such as
12918**
12919**  <pre>
12920**  &nbsp;     int nChangeset,
12921**  &nbsp;     void *pChangeset,
12922**  </pre>
12923**
12924** Is replaced by:
12925**
12926**  <pre>
12927**  &nbsp;     int (*xInput)(void *pIn, void *pData, int *pnData),
12928**  &nbsp;     void *pIn,
12929**  </pre>
12930**
12931** Each time the xInput callback is invoked by the sessions module, the first
12932** argument passed is a copy of the supplied pIn context pointer. The second
12933** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
12934** error occurs the xInput method should copy up to (*pnData) bytes of data
12935** into the buffer and set (*pnData) to the actual number of bytes copied
12936** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
12937** should be set to zero to indicate this. Or, if an error occurs, an SQLite
12938** error code should be returned. In all cases, if an xInput callback returns
12939** an error, all processing is abandoned and the streaming API function
12940** returns a copy of the error code to the caller.
12941**
12942** In the case of sqlite3changeset_start_strm(), the xInput callback may be
12943** invoked by the sessions module at any point during the lifetime of the
12944** iterator. If such an xInput callback returns an error, the iterator enters
12945** an error state, whereby all subsequent calls to iterator functions
12946** immediately fail with the same error code as returned by xInput.
12947**
12948** Similarly, streaming API functions that return changesets (or patchsets)
12949** return them in chunks by way of a callback function instead of via a
12950** pointer to a single large buffer. In this case, a pair of parameters such
12951** as:
12952**
12953**  <pre>
12954**  &nbsp;     int *pnChangeset,
12955**  &nbsp;     void **ppChangeset,
12956**  </pre>
12957**
12958** Is replaced by:
12959**
12960**  <pre>
12961**  &nbsp;     int (*xOutput)(void *pOut, const void *pData, int nData),
12962**  &nbsp;     void *pOut
12963**  </pre>
12964**
12965** The xOutput callback is invoked zero or more times to return data to
12966** the application. The first parameter passed to each call is a copy of the
12967** pOut pointer supplied by the application. The second parameter, pData,
12968** points to a buffer nData bytes in size containing the chunk of output
12969** data being returned. If the xOutput callback successfully processes the
12970** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
12971** it should return some other SQLite error code. In this case processing
12972** is immediately abandoned and the streaming API function returns a copy
12973** of the xOutput error code to the application.
12974**
12975** The sessions module never invokes an xOutput callback with the third
12976** parameter set to a value less than or equal to zero. Other than this,
12977** no guarantees are made as to the size of the chunks of data returned.
12978*/
12979SQLITE_API int sqlite3changeset_apply_strm(
12980  sqlite3 *db,                    /* Apply change to "main" db of this handle */
12981  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
12982  void *pIn,                                          /* First arg for xInput */
12983  int(*xFilter)(
12984    void *pCtx,                   /* Copy of sixth arg to _apply() */
12985    const char *zTab              /* Table name */
12986  ),
12987  int(*xConflict)(
12988    void *pCtx,                   /* Copy of sixth arg to _apply() */
12989    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
12990    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
12991  ),
12992  void *pCtx                      /* First argument passed to xConflict */
12993);
12994SQLITE_API int sqlite3changeset_apply_v2_strm(
12995  sqlite3 *db,                    /* Apply change to "main" db of this handle */
12996  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
12997  void *pIn,                                          /* First arg for xInput */
12998  int(*xFilter)(
12999    void *pCtx,                   /* Copy of sixth arg to _apply() */
13000    const char *zTab              /* Table name */
13001  ),
13002  int(*xConflict)(
13003    void *pCtx,                   /* Copy of sixth arg to _apply() */
13004    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
13005    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
13006  ),
13007  void *pCtx,                     /* First argument passed to xConflict */
13008  void **ppRebase, int *pnRebase,
13009  int flags
13010);
13011SQLITE_API int sqlite3changeset_concat_strm(
13012  int (*xInputA)(void *pIn, void *pData, int *pnData),
13013  void *pInA,
13014  int (*xInputB)(void *pIn, void *pData, int *pnData),
13015  void *pInB,
13016  int (*xOutput)(void *pOut, const void *pData, int nData),
13017  void *pOut
13018);
13019SQLITE_API int sqlite3changeset_invert_strm(
13020  int (*xInput)(void *pIn, void *pData, int *pnData),
13021  void *pIn,
13022  int (*xOutput)(void *pOut, const void *pData, int nData),
13023  void *pOut
13024);
13025SQLITE_API int sqlite3changeset_start_strm(
13026  sqlite3_changeset_iter **pp,
13027  int (*xInput)(void *pIn, void *pData, int *pnData),
13028  void *pIn
13029);
13030SQLITE_API int sqlite3changeset_start_v2_strm(
13031  sqlite3_changeset_iter **pp,
13032  int (*xInput)(void *pIn, void *pData, int *pnData),
13033  void *pIn,
13034  int flags
13035);
13036SQLITE_API int sqlite3session_changeset_strm(
13037  sqlite3_session *pSession,
13038  int (*xOutput)(void *pOut, const void *pData, int nData),
13039  void *pOut
13040);
13041SQLITE_API int sqlite3session_patchset_strm(
13042  sqlite3_session *pSession,
13043  int (*xOutput)(void *pOut, const void *pData, int nData),
13044  void *pOut
13045);
13046SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
13047    int (*xInput)(void *pIn, void *pData, int *pnData),
13048    void *pIn
13049);
13050SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
13051    int (*xOutput)(void *pOut, const void *pData, int nData),
13052    void *pOut
13053);
13054SQLITE_API int sqlite3rebaser_rebase_strm(
13055  sqlite3_rebaser *pRebaser,
13056  int (*xInput)(void *pIn, void *pData, int *pnData),
13057  void *pIn,
13058  int (*xOutput)(void *pOut, const void *pData, int nData),
13059  void *pOut
13060);
13061
13062/*
13063** CAPI3REF: Configure global parameters
13064**
13065** The sqlite3session_config() interface is used to make global configuration
13066** changes to the sessions module in order to tune it to the specific needs
13067** of the application.
13068**
13069** The sqlite3session_config() interface is not threadsafe. If it is invoked
13070** while any other thread is inside any other sessions method then the
13071** results are undefined. Furthermore, if it is invoked after any sessions
13072** related objects have been created, the results are also undefined.
13073**
13074** The first argument to the sqlite3session_config() function must be one
13075** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The
13076** interpretation of the (void*) value passed as the second parameter and
13077** the effect of calling this function depends on the value of the first
13078** parameter.
13079**
13080** <dl>
13081** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>
13082**    By default, the sessions module streaming interfaces attempt to input
13083**    and output data in approximately 1 KiB chunks. This operand may be used
13084**    to set and query the value of this configuration setting. The pointer
13085**    passed as the second argument must point to a value of type (int).
13086**    If this value is greater than 0, it is used as the new streaming data
13087**    chunk size for both input and output. Before returning, the (int) value
13088**    pointed to by pArg is set to the final value of the streaming interface
13089**    chunk size.
13090** </dl>
13091**
13092** This function returns SQLITE_OK if successful, or an SQLite error code
13093** otherwise.
13094*/
13095SQLITE_API int sqlite3session_config(int op, void *pArg);
13096
13097/*
13098** CAPI3REF: Values for sqlite3session_config().
13099*/
13100#define SQLITE_SESSION_CONFIG_STRMSIZE 1
13101
13102/*
13103** Make sure we can call this stuff from C++.
13104*/
13105#if 0
13106}
13107#endif
13108
13109#endif  /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
13110
13111/******** End of sqlite3session.h *********/
13112/******** Begin file fts5.h *********/
13113/*
13114** 2014 May 31
13115**
13116** The author disclaims copyright to this source code.  In place of
13117** a legal notice, here is a blessing:
13118**
13119**    May you do good and not evil.
13120**    May you find forgiveness for yourself and forgive others.
13121**    May you share freely, never taking more than you give.
13122**
13123******************************************************************************
13124**
13125** Interfaces to extend FTS5. Using the interfaces defined in this file,
13126** FTS5 may be extended with:
13127**
13128**     * custom tokenizers, and
13129**     * custom auxiliary functions.
13130*/
13131
13132
13133#ifndef _FTS5_H
13134#define _FTS5_H
13135
13136
13137#if 0
13138extern "C" {
13139#endif
13140
13141/*************************************************************************
13142** CUSTOM AUXILIARY FUNCTIONS
13143**
13144** Virtual table implementations may overload SQL functions by implementing
13145** the sqlite3_module.xFindFunction() method.
13146*/
13147
13148typedef struct Fts5ExtensionApi Fts5ExtensionApi;
13149typedef struct Fts5Context Fts5Context;
13150typedef struct Fts5PhraseIter Fts5PhraseIter;
13151
13152typedef void (*fts5_extension_function)(
13153  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
13154  Fts5Context *pFts,              /* First arg to pass to pApi functions */
13155  sqlite3_context *pCtx,          /* Context for returning result/error */
13156  int nVal,                       /* Number of values in apVal[] array */
13157  sqlite3_value **apVal           /* Array of trailing arguments */
13158);
13159
13160struct Fts5PhraseIter {
13161  const unsigned char *a;
13162  const unsigned char *b;
13163};
13164
13165/*
13166** EXTENSION API FUNCTIONS
13167**
13168** xUserData(pFts):
13169**   Return a copy of the pUserData pointer passed to the xCreateFunction()
13170**   API when the extension function was registered.
13171**
13172** xColumnTotalSize(pFts, iCol, pnToken):
13173**   If parameter iCol is less than zero, set output variable *pnToken
13174**   to the total number of tokens in the FTS5 table. Or, if iCol is
13175**   non-negative but less than the number of columns in the table, return
13176**   the total number of tokens in column iCol, considering all rows in
13177**   the FTS5 table.
13178**
13179**   If parameter iCol is greater than or equal to the number of columns
13180**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
13181**   an OOM condition or IO error), an appropriate SQLite error code is
13182**   returned.
13183**
13184** xColumnCount(pFts):
13185**   Return the number of columns in the table.
13186**
13187** xColumnSize(pFts, iCol, pnToken):
13188**   If parameter iCol is less than zero, set output variable *pnToken
13189**   to the total number of tokens in the current row. Or, if iCol is
13190**   non-negative but less than the number of columns in the table, set
13191**   *pnToken to the number of tokens in column iCol of the current row.
13192**
13193**   If parameter iCol is greater than or equal to the number of columns
13194**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
13195**   an OOM condition or IO error), an appropriate SQLite error code is
13196**   returned.
13197**
13198**   This function may be quite inefficient if used with an FTS5 table
13199**   created with the "columnsize=0" option.
13200**
13201** xColumnText:
13202**   If parameter iCol is less than zero, or greater than or equal to the
13203**   number of columns in the table, SQLITE_RANGE is returned.
13204**
13205**   Otherwise, this function attempts to retrieve the text of column iCol of
13206**   the current document. If successful, (*pz) is set to point to a buffer
13207**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
13208**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
13209**   if an error occurs, an SQLite error code is returned and the final values
13210**   of (*pz) and (*pn) are undefined.
13211**
13212** xPhraseCount:
13213**   Returns the number of phrases in the current query expression.
13214**
13215** xPhraseSize:
13216**   If parameter iCol is less than zero, or greater than or equal to the
13217**   number of phrases in the current query, as returned by xPhraseCount,
13218**   0 is returned. Otherwise, this function returns the number of tokens in
13219**   phrase iPhrase of the query. Phrases are numbered starting from zero.
13220**
13221** xInstCount:
13222**   Set *pnInst to the total number of occurrences of all phrases within
13223**   the query within the current row. Return SQLITE_OK if successful, or
13224**   an error code (i.e. SQLITE_NOMEM) if an error occurs.
13225**
13226**   This API can be quite slow if used with an FTS5 table created with the
13227**   "detail=none" or "detail=column" option. If the FTS5 table is created
13228**   with either "detail=none" or "detail=column" and "content=" option
13229**   (i.e. if it is a contentless table), then this API always returns 0.
13230**
13231** xInst:
13232**   Query for the details of phrase match iIdx within the current row.
13233**   Phrase matches are numbered starting from zero, so the iIdx argument
13234**   should be greater than or equal to zero and smaller than the value
13235**   output by xInstCount(). If iIdx is less than zero or greater than
13236**   or equal to the value returned by xInstCount(), SQLITE_RANGE is returned.
13237**
13238**   Otherwise, output parameter *piPhrase is set to the phrase number, *piCol
13239**   to the column in which it occurs and *piOff the token offset of the
13240**   first token of the phrase. SQLITE_OK is returned if successful, or an
13241**   error code (i.e. SQLITE_NOMEM) if an error occurs.
13242**
13243**   This API can be quite slow if used with an FTS5 table created with the
13244**   "detail=none" or "detail=column" option.
13245**
13246** xRowid:
13247**   Returns the rowid of the current row.
13248**
13249** xTokenize:
13250**   Tokenize text using the tokenizer belonging to the FTS5 table.
13251**
13252** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
13253**   This API function is used to query the FTS table for phrase iPhrase
13254**   of the current query. Specifically, a query equivalent to:
13255**
13256**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
13257**
13258**   with $p set to a phrase equivalent to the phrase iPhrase of the
13259**   current query is executed. Any column filter that applies to
13260**   phrase iPhrase of the current query is included in $p. For each
13261**   row visited, the callback function passed as the fourth argument
13262**   is invoked. The context and API objects passed to the callback
13263**   function may be used to access the properties of each matched row.
13264**   Invoking Api.xUserData() returns a copy of the pointer passed as
13265**   the third argument to pUserData.
13266**
13267**   If parameter iPhrase is less than zero, or greater than or equal to
13268**   the number of phrases in the query, as returned by xPhraseCount(),
13269**   this function returns SQLITE_RANGE.
13270**
13271**   If the callback function returns any value other than SQLITE_OK, the
13272**   query is abandoned and the xQueryPhrase function returns immediately.
13273**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
13274**   Otherwise, the error code is propagated upwards.
13275**
13276**   If the query runs to completion without incident, SQLITE_OK is returned.
13277**   Or, if some error occurs before the query completes or is aborted by
13278**   the callback, an SQLite error code is returned.
13279**
13280**
13281** xSetAuxdata(pFts5, pAux, xDelete)
13282**
13283**   Save the pointer passed as the second argument as the extension function's
13284**   "auxiliary data". The pointer may then be retrieved by the current or any
13285**   future invocation of the same fts5 extension function made as part of
13286**   the same MATCH query using the xGetAuxdata() API.
13287**
13288**   Each extension function is allocated a single auxiliary data slot for
13289**   each FTS query (MATCH expression). If the extension function is invoked
13290**   more than once for a single FTS query, then all invocations share a
13291**   single auxiliary data context.
13292**
13293**   If there is already an auxiliary data pointer when this function is
13294**   invoked, then it is replaced by the new pointer. If an xDelete callback
13295**   was specified along with the original pointer, it is invoked at this
13296**   point.
13297**
13298**   The xDelete callback, if one is specified, is also invoked on the
13299**   auxiliary data pointer after the FTS5 query has finished.
13300**
13301**   If an error (e.g. an OOM condition) occurs within this function,
13302**   the auxiliary data is set to NULL and an error code returned. If the
13303**   xDelete parameter was not NULL, it is invoked on the auxiliary data
13304**   pointer before returning.
13305**
13306**
13307** xGetAuxdata(pFts5, bClear)
13308**
13309**   Returns the current auxiliary data pointer for the fts5 extension
13310**   function. See the xSetAuxdata() method for details.
13311**
13312**   If the bClear argument is non-zero, then the auxiliary data is cleared
13313**   (set to NULL) before this function returns. In this case the xDelete,
13314**   if any, is not invoked.
13315**
13316**
13317** xRowCount(pFts5, pnRow)
13318**
13319**   This function is used to retrieve the total number of rows in the table.
13320**   In other words, the same value that would be returned by:
13321**
13322**        SELECT count(*) FROM ftstable;
13323**
13324** xPhraseFirst()
13325**   This function is used, along with type Fts5PhraseIter and the xPhraseNext
13326**   method, to iterate through all instances of a single query phrase within
13327**   the current row. This is the same information as is accessible via the
13328**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
13329**   to use, this API may be faster under some circumstances. To iterate
13330**   through instances of phrase iPhrase, use the following code:
13331**
13332**       Fts5PhraseIter iter;
13333**       int iCol, iOff;
13334**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
13335**           iCol>=0;
13336**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
13337**       ){
13338**         // An instance of phrase iPhrase at offset iOff of column iCol
13339**       }
13340**
13341**   The Fts5PhraseIter structure is defined above. Applications should not
13342**   modify this structure directly - it should only be used as shown above
13343**   with the xPhraseFirst() and xPhraseNext() API methods (and by
13344**   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
13345**
13346**   This API can be quite slow if used with an FTS5 table created with the
13347**   "detail=none" or "detail=column" option. If the FTS5 table is created
13348**   with either "detail=none" or "detail=column" and "content=" option
13349**   (i.e. if it is a contentless table), then this API always iterates
13350**   through an empty set (all calls to xPhraseFirst() set iCol to -1).
13351**
13352** xPhraseNext()
13353**   See xPhraseFirst above.
13354**
13355** xPhraseFirstColumn()
13356**   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
13357**   and xPhraseNext() APIs described above. The difference is that instead
13358**   of iterating through all instances of a phrase in the current row, these
13359**   APIs are used to iterate through the set of columns in the current row
13360**   that contain one or more instances of a specified phrase. For example:
13361**
13362**       Fts5PhraseIter iter;
13363**       int iCol;
13364**       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
13365**           iCol>=0;
13366**           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
13367**       ){
13368**         // Column iCol contains at least one instance of phrase iPhrase
13369**       }
13370**
13371**   This API can be quite slow if used with an FTS5 table created with the
13372**   "detail=none" option. If the FTS5 table is created with either
13373**   "detail=none" "content=" option (i.e. if it is a contentless table),
13374**   then this API always iterates through an empty set (all calls to
13375**   xPhraseFirstColumn() set iCol to -1).
13376**
13377**   The information accessed using this API and its companion
13378**   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
13379**   (or xInst/xInstCount). The chief advantage of this API is that it is
13380**   significantly more efficient than those alternatives when used with
13381**   "detail=column" tables.
13382**
13383** xPhraseNextColumn()
13384**   See xPhraseFirstColumn above.
13385**
13386** xQueryToken(pFts5, iPhrase, iToken, ppToken, pnToken)
13387**   This is used to access token iToken of phrase iPhrase of the current
13388**   query. Before returning, output parameter *ppToken is set to point
13389**   to a buffer containing the requested token, and *pnToken to the
13390**   size of this buffer in bytes.
13391**
13392**   If iPhrase or iToken are less than zero, or if iPhrase is greater than
13393**   or equal to the number of phrases in the query as reported by
13394**   xPhraseCount(), or if iToken is equal to or greater than the number of
13395**   tokens in the phrase, SQLITE_RANGE is returned and *ppToken and *pnToken
13396     are both zeroed.
13397**
13398**   The output text is not a copy of the query text that specified the
13399**   token. It is the output of the tokenizer module. For tokendata=1
13400**   tables, this includes any embedded 0x00 and trailing data.
13401**
13402** xInstToken(pFts5, iIdx, iToken, ppToken, pnToken)
13403**   This is used to access token iToken of phrase hit iIdx within the
13404**   current row. If iIdx is less than zero or greater than or equal to the
13405**   value returned by xInstCount(), SQLITE_RANGE is returned.  Otherwise,
13406**   output variable (*ppToken) is set to point to a buffer containing the
13407**   matching document token, and (*pnToken) to the size of that buffer in
13408**   bytes. This API is not available if the specified token matches a
13409**   prefix query term. In that case both output variables are always set
13410**   to 0.
13411**
13412**   The output text is not a copy of the document text that was tokenized.
13413**   It is the output of the tokenizer module. For tokendata=1 tables, this
13414**   includes any embedded 0x00 and trailing data.
13415**
13416**   This API can be quite slow if used with an FTS5 table created with the
13417**   "detail=none" or "detail=column" option.
13418*/
13419struct Fts5ExtensionApi {
13420  int iVersion;                   /* Currently always set to 3 */
13421
13422  void *(*xUserData)(Fts5Context*);
13423
13424  int (*xColumnCount)(Fts5Context*);
13425  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
13426  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
13427
13428  int (*xTokenize)(Fts5Context*,
13429    const char *pText, int nText, /* Text to tokenize */
13430    void *pCtx,                   /* Context passed to xToken() */
13431    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
13432  );
13433
13434  int (*xPhraseCount)(Fts5Context*);
13435  int (*xPhraseSize)(Fts5Context*, int iPhrase);
13436
13437  int (*xInstCount)(Fts5Context*, int *pnInst);
13438  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
13439
13440  sqlite3_int64 (*xRowid)(Fts5Context*);
13441  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
13442  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
13443
13444  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
13445    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
13446  );
13447  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
13448  void *(*xGetAuxdata)(Fts5Context*, int bClear);
13449
13450  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
13451  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
13452
13453  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
13454  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
13455
13456  /* Below this point are iVersion>=3 only */
13457  int (*xQueryToken)(Fts5Context*,
13458      int iPhrase, int iToken,
13459      const char **ppToken, int *pnToken
13460  );
13461  int (*xInstToken)(Fts5Context*, int iIdx, int iToken, const char**, int*);
13462};
13463
13464/*
13465** CUSTOM AUXILIARY FUNCTIONS
13466*************************************************************************/
13467
13468/*************************************************************************
13469** CUSTOM TOKENIZERS
13470**
13471** Applications may also register custom tokenizer types. A tokenizer
13472** is registered by providing fts5 with a populated instance of the
13473** following structure. All structure methods must be defined, setting
13474** any member of the fts5_tokenizer struct to NULL leads to undefined
13475** behaviour. The structure methods are expected to function as follows:
13476**
13477** xCreate:
13478**   This function is used to allocate and initialize a tokenizer instance.
13479**   A tokenizer instance is required to actually tokenize text.
13480**
13481**   The first argument passed to this function is a copy of the (void*)
13482**   pointer provided by the application when the fts5_tokenizer object
13483**   was registered with FTS5 (the third argument to xCreateTokenizer()).
13484**   The second and third arguments are an array of nul-terminated strings
13485**   containing the tokenizer arguments, if any, specified following the
13486**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
13487**   to create the FTS5 table.
13488**
13489**   The final argument is an output variable. If successful, (*ppOut)
13490**   should be set to point to the new tokenizer handle and SQLITE_OK
13491**   returned. If an error occurs, some value other than SQLITE_OK should
13492**   be returned. In this case, fts5 assumes that the final value of *ppOut
13493**   is undefined.
13494**
13495** xDelete:
13496**   This function is invoked to delete a tokenizer handle previously
13497**   allocated using xCreate(). Fts5 guarantees that this function will
13498**   be invoked exactly once for each successful call to xCreate().
13499**
13500** xTokenize:
13501**   This function is expected to tokenize the nText byte string indicated
13502**   by argument pText. pText may or may not be nul-terminated. The first
13503**   argument passed to this function is a pointer to an Fts5Tokenizer object
13504**   returned by an earlier call to xCreate().
13505**
13506**   The second argument indicates the reason that FTS5 is requesting
13507**   tokenization of the supplied text. This is always one of the following
13508**   four values:
13509**
13510**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
13511**            or removed from the FTS table. The tokenizer is being invoked to
13512**            determine the set of tokens to add to (or delete from) the
13513**            FTS index.
13514**
13515**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
13516**            against the FTS index. The tokenizer is being called to tokenize
13517**            a bareword or quoted string specified as part of the query.
13518**
13519**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
13520**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
13521**            followed by a "*" character, indicating that the last token
13522**            returned by the tokenizer will be treated as a token prefix.
13523**
13524**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
13525**            satisfy an fts5_api.xTokenize() request made by an auxiliary
13526**            function. Or an fts5_api.xColumnSize() request made by the same
13527**            on a columnsize=0 database.
13528**   </ul>
13529**
13530**   For each token in the input string, the supplied callback xToken() must
13531**   be invoked. The first argument to it should be a copy of the pointer
13532**   passed as the second argument to xTokenize(). The third and fourth
13533**   arguments are a pointer to a buffer containing the token text, and the
13534**   size of the token in bytes. The 4th and 5th arguments are the byte offsets
13535**   of the first byte of and first byte immediately following the text from
13536**   which the token is derived within the input.
13537**
13538**   The second argument passed to the xToken() callback ("tflags") should
13539**   normally be set to 0. The exception is if the tokenizer supports
13540**   synonyms. In this case see the discussion below for details.
13541**
13542**   FTS5 assumes the xToken() callback is invoked for each token in the
13543**   order that they occur within the input text.
13544**
13545**   If an xToken() callback returns any value other than SQLITE_OK, then
13546**   the tokenization should be abandoned and the xTokenize() method should
13547**   immediately return a copy of the xToken() return value. Or, if the
13548**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
13549**   if an error occurs with the xTokenize() implementation itself, it
13550**   may abandon the tokenization and return any error code other than
13551**   SQLITE_OK or SQLITE_DONE.
13552**
13553** SYNONYM SUPPORT
13554**
13555**   Custom tokenizers may also support synonyms. Consider a case in which a
13556**   user wishes to query for a phrase such as "first place". Using the
13557**   built-in tokenizers, the FTS5 query 'first + place' will match instances
13558**   of "first place" within the document set, but not alternative forms
13559**   such as "1st place". In some applications, it would be better to match
13560**   all instances of "first place" or "1st place" regardless of which form
13561**   the user specified in the MATCH query text.
13562**
13563**   There are several ways to approach this in FTS5:
13564**
13565**   <ol><li> By mapping all synonyms to a single token. In this case, using
13566**            the above example, this means that the tokenizer returns the
13567**            same token for inputs "first" and "1st". Say that token is in
13568**            fact "first", so that when the user inserts the document "I won
13569**            1st place" entries are added to the index for tokens "i", "won",
13570**            "first" and "place". If the user then queries for '1st + place',
13571**            the tokenizer substitutes "first" for "1st" and the query works
13572**            as expected.
13573**
13574**       <li> By querying the index for all synonyms of each query term
13575**            separately. In this case, when tokenizing query text, the
13576**            tokenizer may provide multiple synonyms for a single term
13577**            within the document. FTS5 then queries the index for each
13578**            synonym individually. For example, faced with the query:
13579**
13580**   <codeblock>
13581**     ... MATCH 'first place'</codeblock>
13582**
13583**            the tokenizer offers both "1st" and "first" as synonyms for the
13584**            first token in the MATCH query and FTS5 effectively runs a query
13585**            similar to:
13586**
13587**   <codeblock>
13588**     ... MATCH '(first OR 1st) place'</codeblock>
13589**
13590**            except that, for the purposes of auxiliary functions, the query
13591**            still appears to contain just two phrases - "(first OR 1st)"
13592**            being treated as a single phrase.
13593**
13594**       <li> By adding multiple synonyms for a single term to the FTS index.
13595**            Using this method, when tokenizing document text, the tokenizer
13596**            provides multiple synonyms for each token. So that when a
13597**            document such as "I won first place" is tokenized, entries are
13598**            added to the FTS index for "i", "won", "first", "1st" and
13599**            "place".
13600**
13601**            This way, even if the tokenizer does not provide synonyms
13602**            when tokenizing query text (it should not - to do so would be
13603**            inefficient), it doesn't matter if the user queries for
13604**            'first + place' or '1st + place', as there are entries in the
13605**            FTS index corresponding to both forms of the first token.
13606**   </ol>
13607**
13608**   Whether it is parsing document or query text, any call to xToken that
13609**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
13610**   is considered to supply a synonym for the previous token. For example,
13611**   when parsing the document "I won first place", a tokenizer that supports
13612**   synonyms would call xToken() 5 times, as follows:
13613**
13614**   <codeblock>
13615**       xToken(pCtx, 0, "i",                      1,  0,  1);
13616**       xToken(pCtx, 0, "won",                    3,  2,  5);
13617**       xToken(pCtx, 0, "first",                  5,  6, 11);
13618**       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
13619**       xToken(pCtx, 0, "place",                  5, 12, 17);
13620**</codeblock>
13621**
13622**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
13623**   xToken() is called. Multiple synonyms may be specified for a single token
13624**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
13625**   There is no limit to the number of synonyms that may be provided for a
13626**   single token.
13627**
13628**   In many cases, method (1) above is the best approach. It does not add
13629**   extra data to the FTS index or require FTS5 to query for multiple terms,
13630**   so it is efficient in terms of disk space and query speed. However, it
13631**   does not support prefix queries very well. If, as suggested above, the
13632**   token "first" is substituted for "1st" by the tokenizer, then the query:
13633**
13634**   <codeblock>
13635**     ... MATCH '1s*'</codeblock>
13636**
13637**   will not match documents that contain the token "1st" (as the tokenizer
13638**   will probably not map "1s" to any prefix of "first").
13639**
13640**   For full prefix support, method (3) may be preferred. In this case,
13641**   because the index contains entries for both "first" and "1st", prefix
13642**   queries such as 'fi*' or '1s*' will match correctly. However, because
13643**   extra entries are added to the FTS index, this method uses more space
13644**   within the database.
13645**
13646**   Method (2) offers a midpoint between (1) and (3). Using this method,
13647**   a query such as '1s*' will match documents that contain the literal
13648**   token "1st", but not "first" (assuming the tokenizer is not able to
13649**   provide synonyms for prefixes). However, a non-prefix query like '1st'
13650**   will match against "1st" and "first". This method does not require
13651**   extra disk space, as no extra entries are added to the FTS index.
13652**   On the other hand, it may require more CPU cycles to run MATCH queries,
13653**   as separate queries of the FTS index are required for each synonym.
13654**
13655**   When using methods (2) or (3), it is important that the tokenizer only
13656**   provide synonyms when tokenizing document text (method (3)) or query
13657**   text (method (2)), not both. Doing so will not cause any errors, but is
13658**   inefficient.
13659*/
13660typedef struct Fts5Tokenizer Fts5Tokenizer;
13661typedef struct fts5_tokenizer fts5_tokenizer;
13662struct fts5_tokenizer {
13663  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
13664  void (*xDelete)(Fts5Tokenizer*);
13665  int (*xTokenize)(Fts5Tokenizer*,
13666      void *pCtx,
13667      int flags,            /* Mask of FTS5_TOKENIZE_* flags */
13668      const char *pText, int nText,
13669      int (*xToken)(
13670        void *pCtx,         /* Copy of 2nd argument to xTokenize() */
13671        int tflags,         /* Mask of FTS5_TOKEN_* flags */
13672        const char *pToken, /* Pointer to buffer containing token */
13673        int nToken,         /* Size of token in bytes */
13674        int iStart,         /* Byte offset of token within input text */
13675        int iEnd            /* Byte offset of end of token within input text */
13676      )
13677  );
13678};
13679
13680/* Flags that may be passed as the third argument to xTokenize() */
13681#define FTS5_TOKENIZE_QUERY     0x0001
13682#define FTS5_TOKENIZE_PREFIX    0x0002
13683#define FTS5_TOKENIZE_DOCUMENT  0x0004
13684#define FTS5_TOKENIZE_AUX       0x0008
13685
13686/* Flags that may be passed by the tokenizer implementation back to FTS5
13687** as the third argument to the supplied xToken callback. */
13688#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
13689
13690/*
13691** END OF CUSTOM TOKENIZERS
13692*************************************************************************/
13693
13694/*************************************************************************
13695** FTS5 EXTENSION REGISTRATION API
13696*/
13697typedef struct fts5_api fts5_api;
13698struct fts5_api {
13699  int iVersion;                   /* Currently always set to 2 */
13700
13701  /* Create a new tokenizer */
13702  int (*xCreateTokenizer)(
13703    fts5_api *pApi,
13704    const char *zName,
13705    void *pUserData,
13706    fts5_tokenizer *pTokenizer,
13707    void (*xDestroy)(void*)
13708  );
13709
13710  /* Find an existing tokenizer */
13711  int (*xFindTokenizer)(
13712    fts5_api *pApi,
13713    const char *zName,
13714    void **ppUserData,
13715    fts5_tokenizer *pTokenizer
13716  );
13717
13718  /* Create a new auxiliary function */
13719  int (*xCreateFunction)(
13720    fts5_api *pApi,
13721    const char *zName,
13722    void *pUserData,
13723    fts5_extension_function xFunction,
13724    void (*xDestroy)(void*)
13725  );
13726};
13727
13728/*
13729** END OF REGISTRATION API
13730*************************************************************************/
13731
13732#if 0
13733}  /* end of the 'extern "C"' block */
13734#endif
13735
13736#endif /* _FTS5_H */
13737
13738/******** End of fts5.h *********/
13739
13740/************** End of sqlite3.h *********************************************/
13741/************** Continuing where we left off in sqliteInt.h ******************/
13742
13743/*
13744** Reuse the STATIC_LRU for mutex access to sqlite3_temp_directory.
13745*/
13746#define SQLITE_MUTEX_STATIC_TEMPDIR SQLITE_MUTEX_STATIC_VFS1
13747
13748/*
13749** Include the configuration header output by 'configure' if we're using the
13750** autoconf-based build
13751*/
13752#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
13753#include "sqlite_cfg.h"
13754#define SQLITECONFIG_H 1
13755#endif
13756
13757/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
13758/************** Begin file sqliteLimit.h *************************************/
13759/*
13760** 2007 May 7
13761**
13762** The author disclaims copyright to this source code.  In place of
13763** a legal notice, here is a blessing:
13764**
13765**    May you do good and not evil.
13766**    May you find forgiveness for yourself and forgive others.
13767**    May you share freely, never taking more than you give.
13768**
13769*************************************************************************
13770**
13771** This file defines various limits of what SQLite can process.
13772*/
13773
13774/*
13775** The maximum length of a TEXT or BLOB in bytes.   This also
13776** limits the size of a row in a table or index.
13777**
13778** The hard limit is the ability of a 32-bit signed integer
13779** to count the size: 2^31-1 or 2147483647.
13780*/
13781#ifndef SQLITE_MAX_LENGTH
13782# define SQLITE_MAX_LENGTH 1000000000
13783#endif
13784
13785/*
13786** This is the maximum number of
13787**
13788**    * Columns in a table
13789**    * Columns in an index
13790**    * Columns in a view
13791**    * Terms in the SET clause of an UPDATE statement
13792**    * Terms in the result set of a SELECT statement
13793**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
13794**    * Terms in the VALUES clause of an INSERT statement
13795**
13796** The hard upper limit here is 32676.  Most database people will
13797** tell you that in a well-normalized database, you usually should
13798** not have more than a dozen or so columns in any table.  And if
13799** that is the case, there is no point in having more than a few
13800** dozen values in any of the other situations described above.
13801*/
13802#ifndef SQLITE_MAX_COLUMN
13803# define SQLITE_MAX_COLUMN 2000
13804#endif
13805
13806/*
13807** The maximum length of a single SQL statement in bytes.
13808**
13809** It used to be the case that setting this value to zero would
13810** turn the limit off.  That is no longer true.  It is not possible
13811** to turn this limit off.
13812*/
13813#ifndef SQLITE_MAX_SQL_LENGTH
13814# define SQLITE_MAX_SQL_LENGTH 1000000000
13815#endif
13816
13817/*
13818** The maximum depth of an expression tree. This is limited to
13819** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
13820** want to place more severe limits on the complexity of an
13821** expression. A value of 0 means that there is no limit.
13822*/
13823#ifndef SQLITE_MAX_EXPR_DEPTH
13824# define SQLITE_MAX_EXPR_DEPTH 1000
13825#endif
13826
13827/*
13828** The maximum number of terms in a compound SELECT statement.
13829** The code generator for compound SELECT statements does one
13830** level of recursion for each term.  A stack overflow can result
13831** if the number of terms is too large.  In practice, most SQL
13832** never has more than 3 or 4 terms.  Use a value of 0 to disable
13833** any limit on the number of terms in a compound SELECT.
13834*/
13835#ifndef SQLITE_MAX_COMPOUND_SELECT
13836# define SQLITE_MAX_COMPOUND_SELECT 500
13837#endif
13838
13839/*
13840** The maximum number of opcodes in a VDBE program.
13841** Not currently enforced.
13842*/
13843#ifndef SQLITE_MAX_VDBE_OP
13844# define SQLITE_MAX_VDBE_OP 250000000
13845#endif
13846
13847/*
13848** The maximum number of arguments to an SQL function.
13849*/
13850#ifndef SQLITE_MAX_FUNCTION_ARG
13851# define SQLITE_MAX_FUNCTION_ARG 127
13852#endif
13853
13854/*
13855** The suggested maximum number of in-memory pages to use for
13856** the main database table and for temporary tables.
13857**
13858** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
13859** which means the cache size is limited to 2048000 bytes of memory.
13860** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
13861** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
13862*/
13863#ifndef SQLITE_DEFAULT_CACHE_SIZE
13864# define SQLITE_DEFAULT_CACHE_SIZE  -2000
13865#endif
13866
13867/*
13868** The default number of frames to accumulate in the log file before
13869** checkpointing the database in WAL mode.
13870*/
13871#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
13872# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
13873#endif
13874
13875/*
13876** The maximum number of attached databases.  This must be between 0
13877** and 125.  The upper bound of 125 is because the attached databases are
13878** counted using a signed 8-bit integer which has a maximum value of 127
13879** and we have to allow 2 extra counts for the "main" and "temp" databases.
13880*/
13881#ifndef SQLITE_MAX_ATTACHED
13882# define SQLITE_MAX_ATTACHED 10
13883#endif
13884
13885
13886/*
13887** The maximum value of a ?nnn wildcard that the parser will accept.
13888** If the value exceeds 32767 then extra space is required for the Expr
13889** structure.  But otherwise, we believe that the number can be as large
13890** as a signed 32-bit integer can hold.
13891*/
13892#ifndef SQLITE_MAX_VARIABLE_NUMBER
13893# define SQLITE_MAX_VARIABLE_NUMBER 32766
13894#endif
13895
13896/* Maximum page size.  The upper bound on this value is 65536.  This a limit
13897** imposed by the use of 16-bit offsets within each page.
13898**
13899** Earlier versions of SQLite allowed the user to change this value at
13900** compile time. This is no longer permitted, on the grounds that it creates
13901** a library that is technically incompatible with an SQLite library
13902** compiled with a different limit. If a process operating on a database
13903** with a page-size of 65536 bytes crashes, then an instance of SQLite
13904** compiled with the default page-size limit will not be able to rollback
13905** the aborted transaction. This could lead to database corruption.
13906*/
13907#ifdef SQLITE_MAX_PAGE_SIZE
13908# undef SQLITE_MAX_PAGE_SIZE
13909#endif
13910#define SQLITE_MAX_PAGE_SIZE 65536
13911
13912
13913/*
13914** The default size of a database page.
13915*/
13916#ifndef SQLITE_DEFAULT_PAGE_SIZE
13917# define SQLITE_DEFAULT_PAGE_SIZE 4096
13918#endif
13919#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
13920# undef SQLITE_DEFAULT_PAGE_SIZE
13921# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
13922#endif
13923
13924/*
13925** Ordinarily, if no value is explicitly provided, SQLite creates databases
13926** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
13927** device characteristics (sector-size and atomic write() support),
13928** SQLite may choose a larger value. This constant is the maximum value
13929** SQLite will choose on its own.
13930*/
13931#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
13932# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
13933#endif
13934#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
13935# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
13936# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
13937#endif
13938
13939
13940/*
13941** Maximum number of pages in one database file.
13942**
13943** This is really just the default value for the max_page_count pragma.
13944** This value can be lowered (or raised) at run-time using that the
13945** max_page_count macro.
13946*/
13947#ifndef SQLITE_MAX_PAGE_COUNT
13948# define SQLITE_MAX_PAGE_COUNT 0xfffffffe /* 4294967294 */
13949#endif
13950
13951/*
13952** Maximum length (in bytes) of the pattern in a LIKE or GLOB
13953** operator.
13954*/
13955#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
13956# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
13957#endif
13958
13959/*
13960** Maximum depth of recursion for triggers.
13961**
13962** A value of 1 means that a trigger program will not be able to itself
13963** fire any triggers. A value of 0 means that no trigger programs at all
13964** may be executed.
13965*/
13966#ifndef SQLITE_MAX_TRIGGER_DEPTH
13967# define SQLITE_MAX_TRIGGER_DEPTH 1000
13968#endif
13969
13970/************** End of sqliteLimit.h *****************************************/
13971/************** Continuing where we left off in sqliteInt.h ******************/
13972
13973/* Disable nuisance warnings on Borland compilers */
13974#if defined(__BORLANDC__)
13975#pragma warn -rch /* unreachable code */
13976#pragma warn -ccc /* Condition is always true or false */
13977#pragma warn -aus /* Assigned value is never used */
13978#pragma warn -csu /* Comparing signed and unsigned */
13979#pragma warn -spa /* Suspicious pointer arithmetic */
13980#endif
13981
13982/*
13983** A few places in the code require atomic load/store of aligned
13984** integer values.
13985*/
13986#ifndef __has_extension
13987# define __has_extension(x) 0     /* compatibility with non-clang compilers */
13988#endif
13989#if GCC_VERSION>=4007000 || __has_extension(c_atomic)
13990# define SQLITE_ATOMIC_INTRINSICS 1
13991# define AtomicLoad(PTR)       __atomic_load_n((PTR),__ATOMIC_RELAXED)
13992# define AtomicStore(PTR,VAL)  __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
13993#else
13994# define SQLITE_ATOMIC_INTRINSICS 0
13995# define AtomicLoad(PTR)       (*(PTR))
13996# define AtomicStore(PTR,VAL)  (*(PTR) = (VAL))
13997#endif
13998
13999/*
14000** Include standard header files as necessary
14001*/
14002#ifdef HAVE_STDINT_H
14003#include <stdint.h>
14004#endif
14005#ifdef HAVE_INTTYPES_H
14006#include <inttypes.h>
14007#endif
14008
14009/*
14010** The following macros are used to cast pointers to integers and
14011** integers to pointers.  The way you do this varies from one compiler
14012** to the next, so we have developed the following set of #if statements
14013** to generate appropriate macros for a wide range of compilers.
14014**
14015** The correct "ANSI" way to do this is to use the intptr_t type.
14016** Unfortunately, that typedef is not available on all compilers, or
14017** if it is available, it requires an #include of specific headers
14018** that vary from one machine to the next.
14019**
14020** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
14021** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
14022** So we have to define the macros in different ways depending on the
14023** compiler.
14024*/
14025#if defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
14026# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
14027# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
14028#elif defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
14029# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
14030# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
14031#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
14032# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
14033# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
14034#else                          /* Generates a warning - but it always works */
14035# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
14036# define SQLITE_PTR_TO_INT(X)  ((int)(X))
14037#endif
14038
14039/*
14040** Macros to hint to the compiler that a function should or should not be
14041** inlined.
14042*/
14043#if defined(__GNUC__)
14044#  define SQLITE_NOINLINE  __attribute__((noinline))
14045#  define SQLITE_INLINE    __attribute__((always_inline)) inline
14046#elif defined(_MSC_VER) && _MSC_VER>=1310
14047#  define SQLITE_NOINLINE  __declspec(noinline)
14048#  define SQLITE_INLINE    __forceinline
14049#else
14050#  define SQLITE_NOINLINE
14051#  define SQLITE_INLINE
14052#endif
14053#if defined(SQLITE_COVERAGE_TEST) || defined(__STRICT_ANSI__)
14054# undef SQLITE_INLINE
14055# define SQLITE_INLINE
14056#endif
14057
14058/*
14059** Make sure that the compiler intrinsics we desire are enabled when
14060** compiling with an appropriate version of MSVC unless prevented by
14061** the SQLITE_DISABLE_INTRINSIC define.
14062*/
14063#if !defined(SQLITE_DISABLE_INTRINSIC)
14064#  if defined(_MSC_VER) && _MSC_VER>=1400
14065#    if !defined(_WIN32_WCE)
14066#      include <intrin.h>
14067#      pragma intrinsic(_byteswap_ushort)
14068#      pragma intrinsic(_byteswap_ulong)
14069#      pragma intrinsic(_byteswap_uint64)
14070#      pragma intrinsic(_ReadWriteBarrier)
14071#    else
14072#      include <cmnintrin.h>
14073#    endif
14074#  endif
14075#endif
14076
14077/*
14078** Enable SQLITE_USE_SEH by default on MSVC builds.  Only omit
14079** SEH support if the -DSQLITE_OMIT_SEH option is given.
14080*/
14081#if defined(_MSC_VER) && !defined(SQLITE_OMIT_SEH)
14082# define SQLITE_USE_SEH 1
14083#else
14084# undef SQLITE_USE_SEH
14085#endif
14086
14087/*
14088** Enable SQLITE_DIRECT_OVERFLOW_READ, unless the build explicitly
14089** disables it using -DSQLITE_DIRECT_OVERFLOW_READ=0
14090*/
14091#if defined(SQLITE_DIRECT_OVERFLOW_READ) && SQLITE_DIRECT_OVERFLOW_READ+1==1
14092  /* Disable if -DSQLITE_DIRECT_OVERFLOW_READ=0 */
14093# undef SQLITE_DIRECT_OVERFLOW_READ
14094#else
14095  /* In all other cases, enable */
14096# define SQLITE_DIRECT_OVERFLOW_READ 1
14097#endif
14098
14099
14100/*
14101** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
14102** 0 means mutexes are permanently disable and the library is never
14103** threadsafe.  1 means the library is serialized which is the highest
14104** level of threadsafety.  2 means the library is multithreaded - multiple
14105** threads can use SQLite as long as no two threads try to use the same
14106** database connection at the same time.
14107**
14108** Older versions of SQLite used an optional THREADSAFE macro.
14109** We support that for legacy.
14110**
14111** To ensure that the correct value of "THREADSAFE" is reported when querying
14112** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
14113** logic is partially replicated in ctime.c. If it is updated here, it should
14114** also be updated there.
14115*/
14116#if !defined(SQLITE_THREADSAFE)
14117# if defined(THREADSAFE)
14118#   define SQLITE_THREADSAFE THREADSAFE
14119# else
14120#   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
14121# endif
14122#endif
14123
14124/*
14125** Powersafe overwrite is on by default.  But can be turned off using
14126** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
14127*/
14128#ifndef SQLITE_POWERSAFE_OVERWRITE
14129# define SQLITE_POWERSAFE_OVERWRITE 1
14130#endif
14131
14132/*
14133** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
14134** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
14135** which case memory allocation statistics are disabled by default.
14136*/
14137#if !defined(SQLITE_DEFAULT_MEMSTATUS)
14138# define SQLITE_DEFAULT_MEMSTATUS 1
14139#endif
14140
14141/*
14142** Exactly one of the following macros must be defined in order to
14143** specify which memory allocation subsystem to use.
14144**
14145**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
14146**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
14147**     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
14148**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
14149**
14150** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
14151** assert() macro is enabled, each call into the Win32 native heap subsystem
14152** will cause HeapValidate to be called.  If heap validation should fail, an
14153** assertion will be triggered.
14154**
14155** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
14156** the default.
14157*/
14158#if defined(SQLITE_SYSTEM_MALLOC) \
14159  + defined(SQLITE_WIN32_MALLOC) \
14160  + defined(SQLITE_ZERO_MALLOC) \
14161  + defined(SQLITE_MEMDEBUG)>1
14162# error "Two or more of the following compile-time configuration options\
14163 are defined but at most one is allowed:\
14164 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
14165 SQLITE_ZERO_MALLOC"
14166#endif
14167#if defined(SQLITE_SYSTEM_MALLOC) \
14168  + defined(SQLITE_WIN32_MALLOC) \
14169  + defined(SQLITE_ZERO_MALLOC) \
14170  + defined(SQLITE_MEMDEBUG)==0
14171# define SQLITE_SYSTEM_MALLOC 1
14172#endif
14173
14174/*
14175** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
14176** sizes of memory allocations below this value where possible.
14177*/
14178#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
14179# define SQLITE_MALLOC_SOFT_LIMIT 1024
14180#endif
14181
14182/*
14183** We need to define _XOPEN_SOURCE as follows in order to enable
14184** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
14185** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
14186** it.
14187*/
14188#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
14189#  define _XOPEN_SOURCE 600
14190#endif
14191
14192/*
14193** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
14194** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
14195** make it true by defining or undefining NDEBUG.
14196**
14197** Setting NDEBUG makes the code smaller and faster by disabling the
14198** assert() statements in the code.  So we want the default action
14199** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
14200** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
14201** feature.
14202*/
14203#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
14204# define NDEBUG 1
14205#endif
14206#if defined(NDEBUG) && defined(SQLITE_DEBUG)
14207# undef NDEBUG
14208#endif
14209
14210/*
14211** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
14212*/
14213#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
14214# define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
14215#endif
14216
14217/*
14218** The testcase() macro is used to aid in coverage testing.  When
14219** doing coverage testing, the condition inside the argument to
14220** testcase() must be evaluated both true and false in order to
14221** get full branch coverage.  The testcase() macro is inserted
14222** to help ensure adequate test coverage in places where simple
14223** condition/decision coverage is inadequate.  For example, testcase()
14224** can be used to make sure boundary values are tested.  For
14225** bitmask tests, testcase() can be used to make sure each bit
14226** is significant and used at least once.  On switch statements
14227** where multiple cases go to the same block of code, testcase()
14228** can insure that all cases are evaluated.
14229*/
14230#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
14231# ifndef SQLITE_AMALGAMATION
14232    extern unsigned int sqlite3CoverageCounter;
14233# endif
14234# define testcase(X)  if( X ){ sqlite3CoverageCounter += (unsigned)__LINE__; }
14235#else
14236# define testcase(X)
14237#endif
14238
14239/*
14240** The TESTONLY macro is used to enclose variable declarations or
14241** other bits of code that are needed to support the arguments
14242** within testcase() and assert() macros.
14243*/
14244#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
14245# define TESTONLY(X)  X
14246#else
14247# define TESTONLY(X)
14248#endif
14249
14250/*
14251** Sometimes we need a small amount of code such as a variable initialization
14252** to setup for a later assert() statement.  We do not want this code to
14253** appear when assert() is disabled.  The following macro is therefore
14254** used to contain that setup code.  The "VVA" acronym stands for
14255** "Verification, Validation, and Accreditation".  In other words, the
14256** code within VVA_ONLY() will only run during verification processes.
14257*/
14258#ifndef NDEBUG
14259# define VVA_ONLY(X)  X
14260#else
14261# define VVA_ONLY(X)
14262#endif
14263
14264/*
14265** Disable ALWAYS() and NEVER() (make them pass-throughs) for coverage
14266** and mutation testing
14267*/
14268#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
14269# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS  1
14270#endif
14271
14272/*
14273** The ALWAYS and NEVER macros surround boolean expressions which
14274** are intended to always be true or false, respectively.  Such
14275** expressions could be omitted from the code completely.  But they
14276** are included in a few cases in order to enhance the resilience
14277** of SQLite to unexpected behavior - to make the code "self-healing"
14278** or "ductile" rather than being "brittle" and crashing at the first
14279** hint of unplanned behavior.
14280**
14281** In other words, ALWAYS and NEVER are added for defensive code.
14282**
14283** When doing coverage testing ALWAYS and NEVER are hard-coded to
14284** be true and false so that the unreachable code they specify will
14285** not be counted as untested code.
14286*/
14287#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
14288# define ALWAYS(X)      (1)
14289# define NEVER(X)       (0)
14290#elif !defined(NDEBUG)
14291# define ALWAYS(X)      ((X)?1:(assert(0),0))
14292# define NEVER(X)       ((X)?(assert(0),1):0)
14293#else
14294# define ALWAYS(X)      (X)
14295# define NEVER(X)       (X)
14296#endif
14297
14298/*
14299** Some conditionals are optimizations only.  In other words, if the
14300** conditionals are replaced with a constant 1 (true) or 0 (false) then
14301** the correct answer is still obtained, though perhaps not as quickly.
14302**
14303** The following macros mark these optimizations conditionals.
14304*/
14305#if defined(SQLITE_MUTATION_TEST)
14306# define OK_IF_ALWAYS_TRUE(X)  (1)
14307# define OK_IF_ALWAYS_FALSE(X) (0)
14308#else
14309# define OK_IF_ALWAYS_TRUE(X)  (X)
14310# define OK_IF_ALWAYS_FALSE(X) (X)
14311#endif
14312
14313/*
14314** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
14315** defined.  We need to defend against those failures when testing with
14316** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
14317** during a normal build.  The following macro can be used to disable tests
14318** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
14319*/
14320#if defined(SQLITE_TEST_REALLOC_STRESS)
14321# define ONLY_IF_REALLOC_STRESS(X)  (X)
14322#elif !defined(NDEBUG)
14323# define ONLY_IF_REALLOC_STRESS(X)  ((X)?(assert(0),1):0)
14324#else
14325# define ONLY_IF_REALLOC_STRESS(X)  (0)
14326#endif
14327
14328/*
14329** Declarations used for tracing the operating system interfaces.
14330*/
14331#if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
14332    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
14333  extern int sqlite3OSTrace;
14334# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
14335# define SQLITE_HAVE_OS_TRACE
14336#else
14337# define OSTRACE(X)
14338# undef  SQLITE_HAVE_OS_TRACE
14339#endif
14340
14341/*
14342** Is the sqlite3ErrName() function needed in the build?  Currently,
14343** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
14344** OSTRACE is enabled), and by several "test*.c" files (which are
14345** compiled using SQLITE_TEST).
14346*/
14347#if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
14348    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
14349# define SQLITE_NEED_ERR_NAME
14350#else
14351# undef  SQLITE_NEED_ERR_NAME
14352#endif
14353
14354/*
14355** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
14356*/
14357#ifdef SQLITE_OMIT_EXPLAIN
14358# undef SQLITE_ENABLE_EXPLAIN_COMMENTS
14359#endif
14360
14361/*
14362** SQLITE_OMIT_VIRTUALTABLE implies SQLITE_OMIT_ALTERTABLE
14363*/
14364#if defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_ALTERTABLE)
14365# define SQLITE_OMIT_ALTERTABLE
14366#endif
14367
14368#define SQLITE_DIGIT_SEPARATOR '_'
14369
14370/*
14371** Return true (non-zero) if the input is an integer that is too large
14372** to fit in 32-bits.  This macro is used inside of various testcase()
14373** macros to verify that we have tested SQLite for large-file support.
14374*/
14375#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
14376
14377/*
14378** The macro unlikely() is a hint that surrounds a boolean
14379** expression that is usually false.  Macro likely() surrounds
14380** a boolean expression that is usually true.  These hints could,
14381** in theory, be used by the compiler to generate better code, but
14382** currently they are just comments for human readers.
14383*/
14384#define likely(X)    (X)
14385#define unlikely(X)  (X)
14386
14387/************** Include hash.h in the middle of sqliteInt.h ******************/
14388/************** Begin file hash.h ********************************************/
14389/*
14390** 2001 September 22
14391**
14392** The author disclaims copyright to this source code.  In place of
14393** a legal notice, here is a blessing:
14394**
14395**    May you do good and not evil.
14396**    May you find forgiveness for yourself and forgive others.
14397**    May you share freely, never taking more than you give.
14398**
14399*************************************************************************
14400** This is the header file for the generic hash-table implementation
14401** used in SQLite.
14402*/
14403#ifndef SQLITE_HASH_H
14404#define SQLITE_HASH_H
14405
14406/* Forward declarations of structures. */
14407typedef struct Hash Hash;
14408typedef struct HashElem HashElem;
14409
14410/* A complete hash table is an instance of the following structure.
14411** The internals of this structure are intended to be opaque -- client
14412** code should not attempt to access or modify the fields of this structure
14413** directly.  Change this structure only by using the routines below.
14414** However, some of the "procedures" and "functions" for modifying and
14415** accessing this structure are really macros, so we can't really make
14416** this structure opaque.
14417**
14418** All elements of the hash table are on a single doubly-linked list.
14419** Hash.first points to the head of this list.
14420**
14421** There are Hash.htsize buckets.  Each bucket points to a spot in
14422** the global doubly-linked list.  The contents of the bucket are the
14423** element pointed to plus the next _ht.count-1 elements in the list.
14424**
14425** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
14426** by a linear search of the global list.  For small tables, the
14427** Hash.ht table is never allocated because if there are few elements
14428** in the table, it is faster to do a linear search than to manage
14429** the hash table.
14430*/
14431struct Hash {
14432  unsigned int htsize;      /* Number of buckets in the hash table */
14433  unsigned int count;       /* Number of entries in this table */
14434  HashElem *first;          /* The first element of the array */
14435  struct _ht {              /* the hash table */
14436    unsigned int count;        /* Number of entries with this hash */
14437    HashElem *chain;           /* Pointer to first entry with this hash */
14438  } *ht;
14439};
14440
14441/* Each element in the hash table is an instance of the following
14442** structure.  All elements are stored on a single doubly-linked list.
14443**
14444** Again, this structure is intended to be opaque, but it can't really
14445** be opaque because it is used by macros.
14446*/
14447struct HashElem {
14448  HashElem *next, *prev;       /* Next and previous elements in the table */
14449  void *data;                  /* Data associated with this element */
14450  const char *pKey;            /* Key associated with this element */
14451};
14452
14453/*
14454** Access routines.  To delete, insert a NULL pointer.
14455*/
14456SQLITE_PRIVATE void sqlite3HashInit(Hash*);
14457SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
14458SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
14459SQLITE_PRIVATE void sqlite3HashClear(Hash*);
14460
14461/*
14462** Macros for looping over all elements of a hash table.  The idiom is
14463** like this:
14464**
14465**   Hash h;
14466**   HashElem *p;
14467**   ...
14468**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
14469**     SomeStructure *pData = sqliteHashData(p);
14470**     // do something with pData
14471**   }
14472*/
14473#define sqliteHashFirst(H)  ((H)->first)
14474#define sqliteHashNext(E)   ((E)->next)
14475#define sqliteHashData(E)   ((E)->data)
14476/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
14477/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
14478
14479/*
14480** Number of entries in a hash table
14481*/
14482#define sqliteHashCount(H)  ((H)->count)
14483
14484#endif /* SQLITE_HASH_H */
14485
14486/************** End of hash.h ************************************************/
14487/************** Continuing where we left off in sqliteInt.h ******************/
14488/************** Include parse.h in the middle of sqliteInt.h *****************/
14489/************** Begin file parse.h *******************************************/
14490#define TK_SEMI                             1
14491#define TK_EXPLAIN                          2
14492#define TK_QUERY                            3
14493#define TK_PLAN                             4
14494#define TK_BEGIN                            5
14495#define TK_TRANSACTION                      6
14496#define TK_DEFERRED                         7
14497#define TK_IMMEDIATE                        8
14498#define TK_EXCLUSIVE                        9
14499#define TK_COMMIT                          10
14500#define TK_END                             11
14501#define TK_ROLLBACK                        12
14502#define TK_SAVEPOINT                       13
14503#define TK_RELEASE                         14
14504#define TK_TO                              15
14505#define TK_TABLE                           16
14506#define TK_CREATE                          17
14507#define TK_IF                              18
14508#define TK_NOT                             19
14509#define TK_EXISTS                          20
14510#define TK_TEMP                            21
14511#define TK_LP                              22
14512#define TK_RP                              23
14513#define TK_AS                              24
14514#define TK_COMMA                           25
14515#define TK_WITHOUT                         26
14516#define TK_ABORT                           27
14517#define TK_ACTION                          28
14518#define TK_AFTER                           29
14519#define TK_ANALYZE                         30
14520#define TK_ASC                             31
14521#define TK_ATTACH                          32
14522#define TK_BEFORE                          33
14523#define TK_BY                              34
14524#define TK_CASCADE                         35
14525#define TK_CAST                            36
14526#define TK_CONFLICT                        37
14527#define TK_DATABASE                        38
14528#define TK_DESC                            39
14529#define TK_DETACH                          40
14530#define TK_EACH                            41
14531#define TK_FAIL                            42
14532#define TK_OR                              43
14533#define TK_AND                             44
14534#define TK_IS                              45
14535#define TK_MATCH                           46
14536#define TK_LIKE_KW                         47
14537#define TK_BETWEEN                         48
14538#define TK_IN                              49
14539#define TK_ISNULL                          50
14540#define TK_NOTNULL                         51
14541#define TK_NE                              52
14542#define TK_EQ                              53
14543#define TK_GT                              54
14544#define TK_LE                              55
14545#define TK_LT                              56
14546#define TK_GE                              57
14547#define TK_ESCAPE                          58
14548#define TK_ID                              59
14549#define TK_COLUMNKW                        60
14550#define TK_DO                              61
14551#define TK_FOR                             62
14552#define TK_IGNORE                          63
14553#define TK_INITIALLY                       64
14554#define TK_INSTEAD                         65
14555#define TK_NO                              66
14556#define TK_KEY                             67
14557#define TK_OF                              68
14558#define TK_OFFSET                          69
14559#define TK_PRAGMA                          70
14560#define TK_RAISE                           71
14561#define TK_RECURSIVE                       72
14562#define TK_REPLACE                         73
14563#define TK_RESTRICT                        74
14564#define TK_ROW                             75
14565#define TK_ROWS                            76
14566#define TK_TRIGGER                         77
14567#define TK_VACUUM                          78
14568#define TK_VIEW                            79
14569#define TK_VIRTUAL                         80
14570#define TK_WITH                            81
14571#define TK_NULLS                           82
14572#define TK_FIRST                           83
14573#define TK_LAST                            84
14574#define TK_CURRENT                         85
14575#define TK_FOLLOWING                       86
14576#define TK_PARTITION                       87
14577#define TK_PRECEDING                       88
14578#define TK_RANGE                           89
14579#define TK_UNBOUNDED                       90
14580#define TK_EXCLUDE                         91
14581#define TK_GROUPS                          92
14582#define TK_OTHERS                          93
14583#define TK_TIES                            94
14584#define TK_GENERATED                       95
14585#define TK_ALWAYS                          96
14586#define TK_MATERIALIZED                    97
14587#define TK_REINDEX                         98
14588#define TK_RENAME                          99
14589#define TK_CTIME_KW                       100
14590#define TK_ANY                            101
14591#define TK_BITAND                         102
14592#define TK_BITOR                          103
14593#define TK_LSHIFT                         104
14594#define TK_RSHIFT                         105
14595#define TK_PLUS                           106
14596#define TK_MINUS                          107
14597#define TK_STAR                           108
14598#define TK_SLASH                          109
14599#define TK_REM                            110
14600#define TK_CONCAT                         111
14601#define TK_PTR                            112
14602#define TK_COLLATE                        113
14603#define TK_BITNOT                         114
14604#define TK_ON                             115
14605#define TK_INDEXED                        116
14606#define TK_STRING                         117
14607#define TK_JOIN_KW                        118
14608#define TK_CONSTRAINT                     119
14609#define TK_DEFAULT                        120
14610#define TK_NULL                           121
14611#define TK_PRIMARY                        122
14612#define TK_UNIQUE                         123
14613#define TK_CHECK                          124
14614#define TK_REFERENCES                     125
14615#define TK_AUTOINCR                       126
14616#define TK_INSERT                         127
14617#define TK_DELETE                         128
14618#define TK_UPDATE                         129
14619#define TK_SET                            130
14620#define TK_DEFERRABLE                     131
14621#define TK_FOREIGN                        132
14622#define TK_DROP                           133
14623#define TK_UNION                          134
14624#define TK_ALL                            135
14625#define TK_EXCEPT                         136
14626#define TK_INTERSECT                      137
14627#define TK_SELECT                         138
14628#define TK_VALUES                         139
14629#define TK_DISTINCT                       140
14630#define TK_DOT                            141
14631#define TK_FROM                           142
14632#define TK_JOIN                           143
14633#define TK_USING                          144
14634#define TK_ORDER                          145
14635#define TK_GROUP                          146
14636#define TK_HAVING                         147
14637#define TK_LIMIT                          148
14638#define TK_WHERE                          149
14639#define TK_RETURNING                      150
14640#define TK_INTO                           151
14641#define TK_NOTHING                        152
14642#define TK_FLOAT                          153
14643#define TK_BLOB                           154
14644#define TK_INTEGER                        155
14645#define TK_VARIABLE                       156
14646#define TK_CASE                           157
14647#define TK_WHEN                           158
14648#define TK_THEN                           159
14649#define TK_ELSE                           160
14650#define TK_INDEX                          161
14651#define TK_ALTER                          162
14652#define TK_ADD                            163
14653#define TK_WINDOW                         164
14654#define TK_OVER                           165
14655#define TK_FILTER                         166
14656#define TK_COLUMN                         167
14657#define TK_AGG_FUNCTION                   168
14658#define TK_AGG_COLUMN                     169
14659#define TK_TRUEFALSE                      170
14660#define TK_ISNOT                          171
14661#define TK_FUNCTION                       172
14662#define TK_UPLUS                          173
14663#define TK_UMINUS                         174
14664#define TK_TRUTH                          175
14665#define TK_REGISTER                       176
14666#define TK_VECTOR                         177
14667#define TK_SELECT_COLUMN                  178
14668#define TK_IF_NULL_ROW                    179
14669#define TK_ASTERISK                       180
14670#define TK_SPAN                           181
14671#define TK_ERROR                          182
14672#define TK_QNUMBER                        183
14673#define TK_SPACE                          184
14674#define TK_ILLEGAL                        185
14675
14676/************** End of parse.h ***********************************************/
14677/************** Continuing where we left off in sqliteInt.h ******************/
14678#include <stdio.h>
14679#include <stdlib.h>
14680#include <string.h>
14681#include <assert.h>
14682#include <stddef.h>
14683
14684/*
14685** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
14686** This allows better measurements of where memcpy() is used when running
14687** cachegrind.  But this macro version of memcpy() is very slow so it
14688** should not be used in production.  This is a performance measurement
14689** hack only.
14690*/
14691#ifdef SQLITE_INLINE_MEMCPY
14692# define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
14693                        int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
14694#endif
14695
14696/*
14697** If compiling for a processor that lacks floating point support,
14698** substitute integer for floating-point
14699*/
14700#ifdef SQLITE_OMIT_FLOATING_POINT
14701# define double sqlite_int64
14702# define float sqlite_int64
14703# define LONGDOUBLE_TYPE sqlite_int64
14704# ifndef SQLITE_BIG_DBL
14705#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
14706# endif
14707# define SQLITE_OMIT_DATETIME_FUNCS 1
14708# define SQLITE_OMIT_TRACE 1
14709# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
14710# undef SQLITE_HAVE_ISNAN
14711#endif
14712#ifndef SQLITE_BIG_DBL
14713# define SQLITE_BIG_DBL (1e99)
14714#endif
14715
14716/*
14717** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
14718** afterward. Having this macro allows us to cause the C compiler
14719** to omit code used by TEMP tables without messy #ifndef statements.
14720*/
14721#ifdef SQLITE_OMIT_TEMPDB
14722#define OMIT_TEMPDB 1
14723#else
14724#define OMIT_TEMPDB 0
14725#endif
14726
14727/*
14728** The "file format" number is an integer that is incremented whenever
14729** the VDBE-level file format changes.  The following macros define the
14730** the default file format for new databases and the maximum file format
14731** that the library can read.
14732*/
14733#define SQLITE_MAX_FILE_FORMAT 4
14734#ifndef SQLITE_DEFAULT_FILE_FORMAT
14735# define SQLITE_DEFAULT_FILE_FORMAT 4
14736#endif
14737
14738/*
14739** Determine whether triggers are recursive by default.  This can be
14740** changed at run-time using a pragma.
14741*/
14742#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
14743# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
14744#endif
14745
14746/*
14747** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
14748** on the command-line
14749*/
14750#ifndef SQLITE_TEMP_STORE
14751# define SQLITE_TEMP_STORE 1
14752#endif
14753
14754/*
14755** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
14756** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
14757** to zero.
14758*/
14759#if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
14760# undef SQLITE_MAX_WORKER_THREADS
14761# define SQLITE_MAX_WORKER_THREADS 0
14762#endif
14763#ifndef SQLITE_MAX_WORKER_THREADS
14764# define SQLITE_MAX_WORKER_THREADS 8
14765#endif
14766#ifndef SQLITE_DEFAULT_WORKER_THREADS
14767# define SQLITE_DEFAULT_WORKER_THREADS 0
14768#endif
14769#if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
14770# undef SQLITE_MAX_WORKER_THREADS
14771# define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
14772#endif
14773
14774/*
14775** The default initial allocation for the pagecache when using separate
14776** pagecaches for each database connection.  A positive number is the
14777** number of pages.  A negative number N translations means that a buffer
14778** of -1024*N bytes is allocated and used for as many pages as it will hold.
14779**
14780** The default value of "20" was chosen to minimize the run-time of the
14781** speedtest1 test program with options: --shrink-memory --reprepare
14782*/
14783#ifndef SQLITE_DEFAULT_PCACHE_INITSZ
14784# define SQLITE_DEFAULT_PCACHE_INITSZ 20
14785#endif
14786
14787/*
14788** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.
14789*/
14790#ifndef SQLITE_DEFAULT_SORTERREF_SIZE
14791# define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff
14792#endif
14793
14794/*
14795** The compile-time options SQLITE_MMAP_READWRITE and
14796** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
14797** You must choose one or the other (or neither) but not both.
14798*/
14799#if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
14800#error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
14801#endif
14802
14803/*
14804** GCC does not define the offsetof() macro so we'll have to do it
14805** ourselves.
14806*/
14807#ifndef offsetof
14808#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
14809#endif
14810
14811/*
14812** Macros to compute minimum and maximum of two numbers.
14813*/
14814#ifndef MIN
14815# define MIN(A,B) ((A)<(B)?(A):(B))
14816#endif
14817#ifndef MAX
14818# define MAX(A,B) ((A)>(B)?(A):(B))
14819#endif
14820
14821/*
14822** Swap two objects of type TYPE.
14823*/
14824#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
14825
14826/*
14827** Check to see if this machine uses EBCDIC.  (Yes, believe it or
14828** not, there are still machines out there that use EBCDIC.)
14829*/
14830#if 'A' == '\301'
14831# define SQLITE_EBCDIC 1
14832#else
14833# define SQLITE_ASCII 1
14834#endif
14835
14836/*
14837** Integers of known sizes.  These typedefs might change for architectures
14838** where the sizes very.  Preprocessor macros are available so that the
14839** types can be conveniently redefined at compile-type.  Like this:
14840**
14841**         cc '-DUINTPTR_TYPE=long long int' ...
14842*/
14843#ifndef UINT32_TYPE
14844# ifdef HAVE_UINT32_T
14845#  define UINT32_TYPE uint32_t
14846# else
14847#  define UINT32_TYPE unsigned int
14848# endif
14849#endif
14850#ifndef UINT16_TYPE
14851# ifdef HAVE_UINT16_T
14852#  define UINT16_TYPE uint16_t
14853# else
14854#  define UINT16_TYPE unsigned short int
14855# endif
14856#endif
14857#ifndef INT16_TYPE
14858# ifdef HAVE_INT16_T
14859#  define INT16_TYPE int16_t
14860# else
14861#  define INT16_TYPE short int
14862# endif
14863#endif
14864#ifndef UINT8_TYPE
14865# ifdef HAVE_UINT8_T
14866#  define UINT8_TYPE uint8_t
14867# else
14868#  define UINT8_TYPE unsigned char
14869# endif
14870#endif
14871#ifndef INT8_TYPE
14872# ifdef HAVE_INT8_T
14873#  define INT8_TYPE int8_t
14874# else
14875#  define INT8_TYPE signed char
14876# endif
14877#endif
14878#ifndef LONGDOUBLE_TYPE
14879# define LONGDOUBLE_TYPE long double
14880#endif
14881typedef sqlite_int64 i64;          /* 8-byte signed integer */
14882typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
14883typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
14884typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
14885typedef INT16_TYPE i16;            /* 2-byte signed integer */
14886typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
14887typedef INT8_TYPE i8;              /* 1-byte signed integer */
14888
14889/*
14890** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
14891** that can be stored in a u32 without loss of data.  The value
14892** is 0x00000000ffffffff.  But because of quirks of some compilers, we
14893** have to specify the value in the less intuitive manner shown:
14894*/
14895#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
14896
14897/*
14898** The datatype used to store estimates of the number of rows in a
14899** table or index.
14900*/
14901typedef u64 tRowcnt;
14902
14903/*
14904** Estimated quantities used for query planning are stored as 16-bit
14905** logarithms.  For quantity X, the value stored is 10*log2(X).  This
14906** gives a possible range of values of approximately 1.0e986 to 1e-986.
14907** But the allowed values are "grainy".  Not every value is representable.
14908** For example, quantities 16 and 17 are both represented by a LogEst
14909** of 40.  However, since LogEst quantities are suppose to be estimates,
14910** not exact values, this imprecision is not a problem.
14911**
14912** "LogEst" is short for "Logarithmic Estimate".
14913**
14914** Examples:
14915**      1 -> 0              20 -> 43          10000 -> 132
14916**      2 -> 10             25 -> 46          25000 -> 146
14917**      3 -> 16            100 -> 66        1000000 -> 199
14918**      4 -> 20           1000 -> 99        1048576 -> 200
14919**     10 -> 33           1024 -> 100    4294967296 -> 320
14920**
14921** The LogEst can be negative to indicate fractional values.
14922** Examples:
14923**
14924**    0.5 -> -10           0.1 -> -33        0.0625 -> -40
14925*/
14926typedef INT16_TYPE LogEst;
14927
14928/*
14929** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
14930*/
14931#ifndef SQLITE_PTRSIZE
14932# if defined(__SIZEOF_POINTER__)
14933#   define SQLITE_PTRSIZE __SIZEOF_POINTER__
14934# elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
14935       defined(_M_ARM)   || defined(__arm__)    || defined(__x86)   ||    \
14936      (defined(__APPLE__) && defined(__ppc__)) ||                         \
14937      (defined(__TOS_AIX__) && !defined(__64BIT__))
14938#   define SQLITE_PTRSIZE 4
14939# else
14940#   define SQLITE_PTRSIZE 8
14941# endif
14942#endif
14943
14944/* The uptr type is an unsigned integer large enough to hold a pointer
14945*/
14946#if defined(HAVE_STDINT_H)
14947  typedef uintptr_t uptr;
14948#elif SQLITE_PTRSIZE==4
14949  typedef u32 uptr;
14950#else
14951  typedef u64 uptr;
14952#endif
14953
14954/*
14955** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
14956** something between S (inclusive) and E (exclusive).
14957**
14958** In other words, S is a buffer and E is a pointer to the first byte after
14959** the end of buffer S.  This macro returns true if P points to something
14960** contained within the buffer S.
14961*/
14962#define SQLITE_WITHIN(P,S,E)   (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
14963
14964/*
14965** P is one byte past the end of a large buffer. Return true if a span of bytes
14966** between S..E crosses the end of that buffer.  In other words, return true
14967** if the sub-buffer S..E-1 overflows the buffer whose last byte is P-1.
14968**
14969** S is the start of the span.  E is one byte past the end of end of span.
14970**
14971**                        P
14972**     |-----------------|                FALSE
14973**               |-------|
14974**               S        E
14975**
14976**                        P
14977**     |-----------------|
14978**                    |-------|           TRUE
14979**                    S        E
14980**
14981**                        P
14982**     |-----------------|
14983**                        |-------|       FALSE
14984**                        S        E
14985*/
14986#define SQLITE_OVERFLOW(P,S,E) (((uptr)(S)<(uptr)(P))&&((uptr)(E)>(uptr)(P)))
14987
14988/*
14989** Macros to determine whether the machine is big or little endian,
14990** and whether or not that determination is run-time or compile-time.
14991**
14992** For best performance, an attempt is made to guess at the byte-order
14993** using C-preprocessor macros.  If that is unsuccessful, or if
14994** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
14995** at run-time.
14996**
14997** If you are building SQLite on some obscure platform for which the
14998** following ifdef magic does not work, you can always include either:
14999**
15000**    -DSQLITE_BYTEORDER=1234
15001**
15002** or
15003**
15004**    -DSQLITE_BYTEORDER=4321
15005**
15006** to cause the build to work for little-endian or big-endian processors,
15007** respectively.
15008*/
15009#ifndef SQLITE_BYTEORDER  /* Replicate changes at tag-20230904a */
15010# if defined(__BYTE_ORDER__) && __BYTE_ORDER__==__ORDER_BIG_ENDIAN__
15011#   define SQLITE_BYTEORDER 4321
15012# elif defined(__BYTE_ORDER__) && __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__
15013#   define SQLITE_BYTEORDER 1234
15014# elif defined(__BIG_ENDIAN__) && __BIG_ENDIAN__==1
15015#   define SQLITE_BYTEORDER 4321
15016# elif defined(i386)    || defined(__i386__)      || defined(_M_IX86) ||    \
15017     defined(__x86_64)  || defined(__x86_64__)    || defined(_M_X64)  ||    \
15018     defined(_M_AMD64)  || defined(_M_ARM)        || defined(__x86)   ||    \
15019     defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
15020#   define SQLITE_BYTEORDER 1234
15021# elif defined(sparc)   || defined(__ARMEB__)     || defined(__AARCH64EB__)
15022#   define SQLITE_BYTEORDER 4321
15023# else
15024#   define SQLITE_BYTEORDER 0
15025# endif
15026#endif
15027#if SQLITE_BYTEORDER==4321
15028# define SQLITE_BIGENDIAN    1
15029# define SQLITE_LITTLEENDIAN 0
15030# define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
15031#elif SQLITE_BYTEORDER==1234
15032# define SQLITE_BIGENDIAN    0
15033# define SQLITE_LITTLEENDIAN 1
15034# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
15035#else
15036# ifdef SQLITE_AMALGAMATION
15037  const int sqlite3one = 1;
15038# else
15039  extern const int sqlite3one;
15040# endif
15041# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
15042# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
15043# define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
15044#endif
15045
15046/*
15047** Constants for the largest and smallest possible 64-bit signed integers.
15048** These macros are designed to work correctly on both 32-bit and 64-bit
15049** compilers.
15050*/
15051#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
15052#define LARGEST_UINT64 (0xffffffff|(((u64)0xffffffff)<<32))
15053#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
15054
15055/*
15056** Round up a number to the next larger multiple of 8.  This is used
15057** to force 8-byte alignment on 64-bit architectures.
15058**
15059** ROUND8() always does the rounding, for any argument.
15060**
15061** ROUND8P() assumes that the argument is already an integer number of
15062** pointers in size, and so it is a no-op on systems where the pointer
15063** size is 8.
15064*/
15065#define ROUND8(x)     (((x)+7)&~7)
15066#if SQLITE_PTRSIZE==8
15067# define ROUND8P(x)   (x)
15068#else
15069# define ROUND8P(x)   (((x)+7)&~7)
15070#endif
15071
15072/*
15073** Round down to the nearest multiple of 8
15074*/
15075#define ROUNDDOWN8(x) ((x)&~7)
15076
15077/*
15078** Assert that the pointer X is aligned to an 8-byte boundary.  This
15079** macro is used only within assert() to verify that the code gets
15080** all alignment restrictions correct.
15081**
15082** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
15083** underlying malloc() implementation might return us 4-byte aligned
15084** pointers.  In that case, only verify 4-byte alignment.
15085*/
15086#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
15087# define EIGHT_BYTE_ALIGNMENT(X)   ((((uptr)(X) - (uptr)0)&3)==0)
15088#else
15089# define EIGHT_BYTE_ALIGNMENT(X)   ((((uptr)(X) - (uptr)0)&7)==0)
15090#endif
15091
15092/*
15093** Disable MMAP on platforms where it is known to not work
15094*/
15095#if defined(__OpenBSD__) || defined(__QNXNTO__)
15096# undef SQLITE_MAX_MMAP_SIZE
15097# define SQLITE_MAX_MMAP_SIZE 0
15098#endif
15099
15100/*
15101** Default maximum size of memory used by memory-mapped I/O in the VFS
15102*/
15103#ifdef __APPLE__
15104# include <TargetConditionals.h>
15105#endif
15106#ifndef SQLITE_MAX_MMAP_SIZE
15107# if defined(__linux__) \
15108  || defined(_WIN32) \
15109  || (defined(__APPLE__) && defined(__MACH__)) \
15110  || defined(__sun) \
15111  || defined(__FreeBSD__) \
15112  || defined(__DragonFly__)
15113#   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
15114# else
15115#   define SQLITE_MAX_MMAP_SIZE 0
15116# endif
15117#endif
15118
15119/*
15120** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
15121** default MMAP_SIZE is specified at compile-time, make sure that it does
15122** not exceed the maximum mmap size.
15123*/
15124#ifndef SQLITE_DEFAULT_MMAP_SIZE
15125# define SQLITE_DEFAULT_MMAP_SIZE 0
15126#endif
15127#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
15128# undef SQLITE_DEFAULT_MMAP_SIZE
15129# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
15130#endif
15131
15132/*
15133** TREETRACE_ENABLED will be either 1 or 0 depending on whether or not
15134** the Abstract Syntax Tree tracing logic is turned on.
15135*/
15136#if !defined(SQLITE_AMALGAMATION)
15137SQLITE_PRIVATE u32 sqlite3TreeTrace;
15138#endif
15139#if defined(SQLITE_DEBUG) \
15140    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_SELECTTRACE) \
15141                             || defined(SQLITE_ENABLE_TREETRACE))
15142# define TREETRACE_ENABLED 1
15143# define TREETRACE(K,P,S,X)  \
15144  if(sqlite3TreeTrace&(K))   \
15145    sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
15146    sqlite3DebugPrintf X
15147#else
15148# define TREETRACE(K,P,S,X)
15149# define TREETRACE_ENABLED 0
15150#endif
15151
15152/* TREETRACE flag meanings:
15153**
15154**   0x00000001     Beginning and end of SELECT processing
15155**   0x00000002     WHERE clause processing
15156**   0x00000004     Query flattener
15157**   0x00000008     Result-set wildcard expansion
15158**   0x00000010     Query name resolution
15159**   0x00000020     Aggregate analysis
15160**   0x00000040     Window functions
15161**   0x00000080     Generated column names
15162**   0x00000100     Move HAVING terms into WHERE
15163**   0x00000200     Count-of-view optimization
15164**   0x00000400     Compound SELECT processing
15165**   0x00000800     Drop superfluous ORDER BY
15166**   0x00001000     LEFT JOIN simplifies to JOIN
15167**   0x00002000     Constant propagation
15168**   0x00004000     Push-down optimization
15169**   0x00008000     After all FROM-clause analysis
15170**   0x00010000     Beginning of DELETE/INSERT/UPDATE processing
15171**   0x00020000     Transform DISTINCT into GROUP BY
15172**   0x00040000     SELECT tree dump after all code has been generated
15173**   0x00080000     NOT NULL strength reduction
15174*/
15175
15176/*
15177** Macros for "wheretrace"
15178*/
15179SQLITE_PRIVATE u32 sqlite3WhereTrace;
15180#if defined(SQLITE_DEBUG) \
15181    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
15182# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
15183# define WHERETRACE_ENABLED 1
15184#else
15185# define WHERETRACE(K,X)
15186#endif
15187
15188/*
15189** Bits for the sqlite3WhereTrace mask:
15190**
15191** (---any--)   Top-level block structure
15192** 0x-------F   High-level debug messages
15193** 0x----FFF-   More detail
15194** 0xFFFF----   Low-level debug messages
15195**
15196** 0x00000001   Code generation
15197** 0x00000002   Solver
15198** 0x00000004   Solver costs
15199** 0x00000008   WhereLoop inserts
15200**
15201** 0x00000010   Display sqlite3_index_info xBestIndex calls
15202** 0x00000020   Range an equality scan metrics
15203** 0x00000040   IN operator decisions
15204** 0x00000080   WhereLoop cost adjustments
15205** 0x00000100
15206** 0x00000200   Covering index decisions
15207** 0x00000400   OR optimization
15208** 0x00000800   Index scanner
15209** 0x00001000   More details associated with code generation
15210** 0x00002000
15211** 0x00004000   Show all WHERE terms at key points
15212** 0x00008000   Show the full SELECT statement at key places
15213**
15214** 0x00010000   Show more detail when printing WHERE terms
15215** 0x00020000   Show WHERE terms returned from whereScanNext()
15216*/
15217
15218
15219/*
15220** An instance of the following structure is used to store the busy-handler
15221** callback for a given sqlite handle.
15222**
15223** The sqlite.busyHandler member of the sqlite struct contains the busy
15224** callback for the database handle. Each pager opened via the sqlite
15225** handle is passed a pointer to sqlite.busyHandler. The busy-handler
15226** callback is currently invoked only from within pager.c.
15227*/
15228typedef struct BusyHandler BusyHandler;
15229struct BusyHandler {
15230  int (*xBusyHandler)(void *,int);  /* The busy callback */
15231  void *pBusyArg;                   /* First arg to busy callback */
15232  int nBusy;                        /* Incremented with each busy call */
15233};
15234
15235/*
15236** Name of table that holds the database schema.
15237**
15238** The PREFERRED names are used wherever possible.  But LEGACY is also
15239** used for backwards compatibility.
15240**
15241**  1.  Queries can use either the PREFERRED or the LEGACY names
15242**  2.  The sqlite3_set_authorizer() callback uses the LEGACY name
15243**  3.  The PRAGMA table_list statement uses the PREFERRED name
15244**
15245** The LEGACY names are stored in the internal symbol hash table
15246** in support of (2).  Names are translated using sqlite3PreferredTableName()
15247** for (3).  The sqlite3FindTable() function takes care of translating
15248** names for (1).
15249**
15250** Note that "sqlite_temp_schema" can also be called "temp.sqlite_schema".
15251*/
15252#define LEGACY_SCHEMA_TABLE          "sqlite_master"
15253#define LEGACY_TEMP_SCHEMA_TABLE     "sqlite_temp_master"
15254#define PREFERRED_SCHEMA_TABLE       "sqlite_schema"
15255#define PREFERRED_TEMP_SCHEMA_TABLE  "sqlite_temp_schema"
15256
15257
15258/*
15259** The root-page of the schema table.
15260*/
15261#define SCHEMA_ROOT    1
15262
15263/*
15264** The name of the schema table.  The name is different for TEMP.
15265*/
15266#define SCHEMA_TABLE(x) \
15267    ((!OMIT_TEMPDB)&&(x==1)?LEGACY_TEMP_SCHEMA_TABLE:LEGACY_SCHEMA_TABLE)
15268
15269/*
15270** A convenience macro that returns the number of elements in
15271** an array.
15272*/
15273#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
15274
15275/*
15276** Determine if the argument is a power of two
15277*/
15278#define IsPowerOfTwo(X) (((X)&((X)-1))==0)
15279
15280/*
15281** The following value as a destructor means to use sqlite3DbFree().
15282** The sqlite3DbFree() routine requires two parameters instead of the
15283** one parameter that destructors normally want.  So we have to introduce
15284** this magic value that the code knows to handle differently.  Any
15285** pointer will work here as long as it is distinct from SQLITE_STATIC
15286** and SQLITE_TRANSIENT.
15287*/
15288#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3OomClear)
15289
15290/*
15291** When SQLITE_OMIT_WSD is defined, it means that the target platform does
15292** not support Writable Static Data (WSD) such as global and static variables.
15293** All variables must either be on the stack or dynamically allocated from
15294** the heap.  When WSD is unsupported, the variable declarations scattered
15295** throughout the SQLite code must become constants instead.  The SQLITE_WSD
15296** macro is used for this purpose.  And instead of referencing the variable
15297** directly, we use its constant as a key to lookup the run-time allocated
15298** buffer that holds real variable.  The constant is also the initializer
15299** for the run-time allocated buffer.
15300**
15301** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
15302** macros become no-ops and have zero performance impact.
15303*/
15304#ifdef SQLITE_OMIT_WSD
15305  #define SQLITE_WSD const
15306  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
15307  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
15308SQLITE_API int sqlite3_wsd_init(int N, int J);
15309SQLITE_API void *sqlite3_wsd_find(void *K, int L);
15310#else
15311  #define SQLITE_WSD
15312  #define GLOBAL(t,v) v
15313  #define sqlite3GlobalConfig sqlite3Config
15314#endif
15315
15316/*
15317** The following macros are used to suppress compiler warnings and to
15318** make it clear to human readers when a function parameter is deliberately
15319** left unused within the body of a function. This usually happens when
15320** a function is called via a function pointer. For example the
15321** implementation of an SQL aggregate step callback may not use the
15322** parameter indicating the number of arguments passed to the aggregate,
15323** if it knows that this is enforced elsewhere.
15324**
15325** When a function parameter is not used at all within the body of a function,
15326** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
15327** However, these macros may also be used to suppress warnings related to
15328** parameters that may or may not be used depending on compilation options.
15329** For example those parameters only used in assert() statements. In these
15330** cases the parameters are named as per the usual conventions.
15331*/
15332#define UNUSED_PARAMETER(x) (void)(x)
15333#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
15334
15335/*
15336** Forward references to structures
15337*/
15338typedef struct AggInfo AggInfo;
15339typedef struct AuthContext AuthContext;
15340typedef struct AutoincInfo AutoincInfo;
15341typedef struct Bitvec Bitvec;
15342typedef struct CollSeq CollSeq;
15343typedef struct Column Column;
15344typedef struct Cte Cte;
15345typedef struct CteUse CteUse;
15346typedef struct Db Db;
15347typedef struct DbClientData DbClientData;
15348typedef struct DbFixer DbFixer;
15349typedef struct Schema Schema;
15350typedef struct Expr Expr;
15351typedef struct ExprList ExprList;
15352typedef struct FKey FKey;
15353typedef struct FpDecode FpDecode;
15354typedef struct FuncDestructor FuncDestructor;
15355typedef struct FuncDef FuncDef;
15356typedef struct FuncDefHash FuncDefHash;
15357typedef struct IdList IdList;
15358typedef struct Index Index;
15359typedef struct IndexedExpr IndexedExpr;
15360typedef struct IndexSample IndexSample;
15361typedef struct KeyClass KeyClass;
15362typedef struct KeyInfo KeyInfo;
15363typedef struct Lookaside Lookaside;
15364typedef struct LookasideSlot LookasideSlot;
15365typedef struct Module Module;
15366typedef struct NameContext NameContext;
15367typedef struct OnOrUsing OnOrUsing;
15368typedef struct Parse Parse;
15369typedef struct ParseCleanup ParseCleanup;
15370typedef struct PreUpdate PreUpdate;
15371typedef struct PrintfArguments PrintfArguments;
15372typedef struct RCStr RCStr;
15373typedef struct RenameToken RenameToken;
15374typedef struct Returning Returning;
15375typedef struct RowSet RowSet;
15376typedef struct Savepoint Savepoint;
15377typedef struct Select Select;
15378typedef struct SQLiteThread SQLiteThread;
15379typedef struct SelectDest SelectDest;
15380typedef struct SrcItem SrcItem;
15381typedef struct SrcList SrcList;
15382typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
15383typedef struct Table Table;
15384typedef struct TableLock TableLock;
15385typedef struct Token Token;
15386typedef struct TreeView TreeView;
15387typedef struct Trigger Trigger;
15388typedef struct TriggerPrg TriggerPrg;
15389typedef struct TriggerStep TriggerStep;
15390typedef struct UnpackedRecord UnpackedRecord;
15391typedef struct Upsert Upsert;
15392typedef struct VTable VTable;
15393typedef struct VtabCtx VtabCtx;
15394typedef struct Walker Walker;
15395typedef struct WhereInfo WhereInfo;
15396typedef struct Window Window;
15397typedef struct With With;
15398
15399
15400/*
15401** The bitmask datatype defined below is used for various optimizations.
15402**
15403** Changing this from a 64-bit to a 32-bit type limits the number of
15404** tables in a join to 32 instead of 64.  But it also reduces the size
15405** of the library by 738 bytes on ix86.
15406*/
15407#ifdef SQLITE_BITMASK_TYPE
15408  typedef SQLITE_BITMASK_TYPE Bitmask;
15409#else
15410  typedef u64 Bitmask;
15411#endif
15412
15413/*
15414** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
15415*/
15416#define BMS  ((int)(sizeof(Bitmask)*8))
15417
15418/*
15419** A bit in a Bitmask
15420*/
15421#define MASKBIT(n)    (((Bitmask)1)<<(n))
15422#define MASKBIT64(n)  (((u64)1)<<(n))
15423#define MASKBIT32(n)  (((unsigned int)1)<<(n))
15424#define SMASKBIT32(n) ((n)<=31?((unsigned int)1)<<(n):0)
15425#define ALLBITS       ((Bitmask)-1)
15426#define TOPBIT        (((Bitmask)1)<<(BMS-1))
15427
15428/* A VList object records a mapping between parameters/variables/wildcards
15429** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
15430** variable number associated with that parameter.  See the format description
15431** on the sqlite3VListAdd() routine for more information.  A VList is really
15432** just an array of integers.
15433*/
15434typedef int VList;
15435
15436/*
15437** Defer sourcing vdbe.h and btree.h until after the "u8" and
15438** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
15439** pointer types (i.e. FuncDef) defined above.
15440*/
15441/************** Include os.h in the middle of sqliteInt.h ********************/
15442/************** Begin file os.h **********************************************/
15443/*
15444** 2001 September 16
15445**
15446** The author disclaims copyright to this source code.  In place of
15447** a legal notice, here is a blessing:
15448**
15449**    May you do good and not evil.
15450**    May you find forgiveness for yourself and forgive others.
15451**    May you share freely, never taking more than you give.
15452**
15453******************************************************************************
15454**
15455** This header file (together with is companion C source-code file
15456** "os.c") attempt to abstract the underlying operating system so that
15457** the SQLite library will work on both POSIX and windows systems.
15458**
15459** This header file is #include-ed by sqliteInt.h and thus ends up
15460** being included by every source file.
15461*/
15462#ifndef _SQLITE_OS_H_
15463#define _SQLITE_OS_H_
15464
15465/*
15466** Attempt to automatically detect the operating system and setup the
15467** necessary pre-processor macros for it.
15468*/
15469/************** Include os_setup.h in the middle of os.h *********************/
15470/************** Begin file os_setup.h ****************************************/
15471/*
15472** 2013 November 25
15473**
15474** The author disclaims copyright to this source code.  In place of
15475** a legal notice, here is a blessing:
15476**
15477**    May you do good and not evil.
15478**    May you find forgiveness for yourself and forgive others.
15479**    May you share freely, never taking more than you give.
15480**
15481******************************************************************************
15482**
15483** This file contains pre-processor directives related to operating system
15484** detection and/or setup.
15485*/
15486#ifndef SQLITE_OS_SETUP_H
15487#define SQLITE_OS_SETUP_H
15488
15489/*
15490** Figure out if we are dealing with Unix, Windows, or some other operating
15491** system.
15492**
15493** After the following block of preprocess macros, all of
15494**
15495**    SQLITE_OS_KV
15496**    SQLITE_OS_OTHER
15497**    SQLITE_OS_UNIX
15498**    SQLITE_OS_WIN
15499**
15500** will defined to either 1 or 0. One of them will be 1. The others will be 0.
15501** If none of the macros are initially defined, then select either
15502** SQLITE_OS_UNIX or SQLITE_OS_WIN depending on the target platform.
15503**
15504** If SQLITE_OS_OTHER=1 is specified at compile-time, then the application
15505** must provide its own VFS implementation together with sqlite3_os_init()
15506** and sqlite3_os_end() routines.
15507*/
15508#if !defined(SQLITE_OS_KV) && !defined(SQLITE_OS_OTHER) && \
15509       !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_WIN)
15510#  if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
15511          defined(__MINGW32__) || defined(__BORLANDC__)
15512#    define SQLITE_OS_WIN 1
15513#    define SQLITE_OS_UNIX 0
15514#  else
15515#    define SQLITE_OS_WIN 0
15516#    define SQLITE_OS_UNIX 1
15517#  endif
15518#endif
15519#if SQLITE_OS_OTHER+1>1
15520#  undef SQLITE_OS_KV
15521#  define SQLITE_OS_KV 0
15522#  undef SQLITE_OS_UNIX
15523#  define SQLITE_OS_UNIX 0
15524#  undef SQLITE_OS_WIN
15525#  define SQLITE_OS_WIN 0
15526#endif
15527#if SQLITE_OS_KV+1>1
15528#  undef SQLITE_OS_OTHER
15529#  define SQLITE_OS_OTHER 0
15530#  undef SQLITE_OS_UNIX
15531#  define SQLITE_OS_UNIX 0
15532#  undef SQLITE_OS_WIN
15533#  define SQLITE_OS_WIN 0
15534#  define SQLITE_OMIT_LOAD_EXTENSION 1
15535#  define SQLITE_OMIT_WAL 1
15536#  define SQLITE_OMIT_DEPRECATED 1
15537#  undef SQLITE_TEMP_STORE
15538#  define SQLITE_TEMP_STORE 3  /* Always use memory for temporary storage */
15539#  define SQLITE_DQS 0
15540#  define SQLITE_OMIT_SHARED_CACHE 1
15541#  define SQLITE_OMIT_AUTOINIT 1
15542#endif
15543#if SQLITE_OS_UNIX+1>1
15544#  undef SQLITE_OS_KV
15545#  define SQLITE_OS_KV 0
15546#  undef SQLITE_OS_OTHER
15547#  define SQLITE_OS_OTHER 0
15548#  undef SQLITE_OS_WIN
15549#  define SQLITE_OS_WIN 0
15550#endif
15551#if SQLITE_OS_WIN+1>1
15552#  undef SQLITE_OS_KV
15553#  define SQLITE_OS_KV 0
15554#  undef SQLITE_OS_OTHER
15555#  define SQLITE_OS_OTHER 0
15556#  undef SQLITE_OS_UNIX
15557#  define SQLITE_OS_UNIX 0
15558#endif
15559
15560
15561#endif /* SQLITE_OS_SETUP_H */
15562
15563/************** End of os_setup.h ********************************************/
15564/************** Continuing where we left off in os.h *************************/
15565
15566/* If the SET_FULLSYNC macro is not defined above, then make it
15567** a no-op
15568*/
15569#ifndef SET_FULLSYNC
15570# define SET_FULLSYNC(x,y)
15571#endif
15572
15573/* Maximum pathname length.  Note: FILENAME_MAX defined by stdio.h
15574*/
15575#ifndef SQLITE_MAX_PATHLEN
15576# define SQLITE_MAX_PATHLEN FILENAME_MAX
15577#endif
15578
15579/* Maximum number of symlinks that will be resolved while trying to
15580** expand a filename in xFullPathname() in the VFS.
15581*/
15582#ifndef SQLITE_MAX_SYMLINK
15583# define SQLITE_MAX_SYMLINK 200
15584#endif
15585
15586/*
15587** The default size of a disk sector
15588*/
15589#ifndef SQLITE_DEFAULT_SECTOR_SIZE
15590# define SQLITE_DEFAULT_SECTOR_SIZE 4096
15591#endif
15592
15593/*
15594** Temporary files are named starting with this prefix followed by 16 random
15595** alphanumeric characters, and no file extension. They are stored in the
15596** OS's standard temporary file directory, and are deleted prior to exit.
15597** If sqlite is being embedded in another program, you may wish to change the
15598** prefix to reflect your program's name, so that if your program exits
15599** prematurely, old temporary files can be easily identified. This can be done
15600** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
15601**
15602** 2006-10-31:  The default prefix used to be "sqlite_".  But then
15603** Mcafee started using SQLite in their anti-virus product and it
15604** started putting files with the "sqlite" name in the c:/temp folder.
15605** This annoyed many windows users.  Those users would then do a
15606** Google search for "sqlite", find the telephone numbers of the
15607** developers and call to wake them up at night and complain.
15608** For this reason, the default name prefix is changed to be "sqlite"
15609** spelled backwards.  So the temp files are still identified, but
15610** anybody smart enough to figure out the code is also likely smart
15611** enough to know that calling the developer will not help get rid
15612** of the file.
15613*/
15614#ifndef SQLITE_TEMP_FILE_PREFIX
15615# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
15616#endif
15617
15618/*
15619** The following values may be passed as the second argument to
15620** sqlite3OsLock(). The various locks exhibit the following semantics:
15621**
15622** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
15623** RESERVED:  A single process may hold a RESERVED lock on a file at
15624**            any time. Other processes may hold and obtain new SHARED locks.
15625** PENDING:   A single process may hold a PENDING lock on a file at
15626**            any one time. Existing SHARED locks may persist, but no new
15627**            SHARED locks may be obtained by other processes.
15628** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
15629**
15630** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
15631** process that requests an EXCLUSIVE lock may actually obtain a PENDING
15632** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
15633** sqlite3OsLock().
15634*/
15635#define NO_LOCK         0
15636#define SHARED_LOCK     1
15637#define RESERVED_LOCK   2
15638#define PENDING_LOCK    3
15639#define EXCLUSIVE_LOCK  4
15640
15641/*
15642** File Locking Notes:  (Mostly about windows but also some info for Unix)
15643**
15644** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
15645** those functions are not available.  So we use only LockFile() and
15646** UnlockFile().
15647**
15648** LockFile() prevents not just writing but also reading by other processes.
15649** A SHARED_LOCK is obtained by locking a single randomly-chosen
15650** byte out of a specific range of bytes. The lock byte is obtained at
15651** random so two separate readers can probably access the file at the
15652** same time, unless they are unlucky and choose the same lock byte.
15653** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
15654** There can only be one writer.  A RESERVED_LOCK is obtained by locking
15655** a single byte of the file that is designated as the reserved lock byte.
15656** A PENDING_LOCK is obtained by locking a designated byte different from
15657** the RESERVED_LOCK byte.
15658**
15659** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
15660** which means we can use reader/writer locks.  When reader/writer locks
15661** are used, the lock is placed on the same range of bytes that is used
15662** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
15663** will support two or more Win95 readers or two or more WinNT readers.
15664** But a single Win95 reader will lock out all WinNT readers and a single
15665** WinNT reader will lock out all other Win95 readers.
15666**
15667** The following #defines specify the range of bytes used for locking.
15668** SHARED_SIZE is the number of bytes available in the pool from which
15669** a random byte is selected for a shared lock.  The pool of bytes for
15670** shared locks begins at SHARED_FIRST.
15671**
15672** The same locking strategy and
15673** byte ranges are used for Unix.  This leaves open the possibility of having
15674** clients on win95, winNT, and unix all talking to the same shared file
15675** and all locking correctly.  To do so would require that samba (or whatever
15676** tool is being used for file sharing) implements locks correctly between
15677** windows and unix.  I'm guessing that isn't likely to happen, but by
15678** using the same locking range we are at least open to the possibility.
15679**
15680** Locking in windows is manditory.  For this reason, we cannot store
15681** actual data in the bytes used for locking.  The pager never allocates
15682** the pages involved in locking therefore.  SHARED_SIZE is selected so
15683** that all locks will fit on a single page even at the minimum page size.
15684** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
15685** is set high so that we don't have to allocate an unused page except
15686** for very large databases.  But one should test the page skipping logic
15687** by setting PENDING_BYTE low and running the entire regression suite.
15688**
15689** Changing the value of PENDING_BYTE results in a subtly incompatible
15690** file format.  Depending on how it is changed, you might not notice
15691** the incompatibility right away, even running a full regression test.
15692** The default location of PENDING_BYTE is the first byte past the
15693** 1GB boundary.
15694**
15695*/
15696#ifdef SQLITE_OMIT_WSD
15697# define PENDING_BYTE     (0x40000000)
15698#else
15699# define PENDING_BYTE      sqlite3PendingByte
15700#endif
15701#define RESERVED_BYTE     (PENDING_BYTE+1)
15702#define SHARED_FIRST      (PENDING_BYTE+2)
15703#define SHARED_SIZE       510
15704
15705/*
15706** Wrapper around OS specific sqlite3_os_init() function.
15707*/
15708SQLITE_PRIVATE int sqlite3OsInit(void);
15709
15710/*
15711** Functions for accessing sqlite3_file methods
15712*/
15713SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
15714SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
15715SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
15716SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
15717SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
15718SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
15719SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
15720SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
15721SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
15722SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
15723SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
15724#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
15725SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
15726SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
15727#ifndef SQLITE_OMIT_WAL
15728SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
15729SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
15730SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
15731SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
15732#endif /* SQLITE_OMIT_WAL */
15733SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
15734SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
15735
15736
15737/*
15738** Functions for accessing sqlite3_vfs methods
15739*/
15740SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
15741SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
15742SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
15743SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
15744#ifndef SQLITE_OMIT_LOAD_EXTENSION
15745SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
15746SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
15747SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
15748SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
15749#endif /* SQLITE_OMIT_LOAD_EXTENSION */
15750SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
15751SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
15752SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
15753SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
15754
15755/*
15756** Convenience functions for opening and closing files using
15757** sqlite3_malloc() to obtain space for the file-handle structure.
15758*/
15759SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
15760SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
15761
15762#endif /* _SQLITE_OS_H_ */
15763
15764/************** End of os.h **************************************************/
15765/************** Continuing where we left off in sqliteInt.h ******************/
15766/************** Include pager.h in the middle of sqliteInt.h *****************/
15767/************** Begin file pager.h *******************************************/
15768/*
15769** 2001 September 15
15770**
15771** The author disclaims copyright to this source code.  In place of
15772** a legal notice, here is a blessing:
15773**
15774**    May you do good and not evil.
15775**    May you find forgiveness for yourself and forgive others.
15776**    May you share freely, never taking more than you give.
15777**
15778*************************************************************************
15779** This header file defines the interface that the sqlite page cache
15780** subsystem.  The page cache subsystem reads and writes a file a page
15781** at a time and provides a journal for rollback.
15782*/
15783
15784#ifndef SQLITE_PAGER_H
15785#define SQLITE_PAGER_H
15786
15787/*
15788** Default maximum size for persistent journal files. A negative
15789** value means no limit. This value may be overridden using the
15790** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
15791*/
15792#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
15793  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
15794#endif
15795
15796/*
15797** The type used to represent a page number.  The first page in a file
15798** is called page 1.  0 is used to represent "not a page".
15799*/
15800typedef u32 Pgno;
15801
15802/*
15803** Each open file is managed by a separate instance of the "Pager" structure.
15804*/
15805typedef struct Pager Pager;
15806
15807/*
15808** Handle type for pages.
15809*/
15810typedef struct PgHdr DbPage;
15811
15812/*
15813** Page number PAGER_SJ_PGNO is never used in an SQLite database (it is
15814** reserved for working around a windows/posix incompatibility). It is
15815** used in the journal to signify that the remainder of the journal file
15816** is devoted to storing a super-journal name - there are no more pages to
15817** roll back. See comments for function writeSuperJournal() in pager.c
15818** for details.
15819*/
15820#define PAGER_SJ_PGNO_COMPUTED(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
15821#define PAGER_SJ_PGNO(x)          ((x)->lckPgno)
15822
15823/*
15824** Allowed values for the flags parameter to sqlite3PagerOpen().
15825**
15826** NOTE: These values must match the corresponding BTREE_ values in btree.h.
15827*/
15828#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
15829#define PAGER_MEMORY        0x0002    /* In-memory database */
15830
15831/*
15832** Valid values for the second argument to sqlite3PagerLockingMode().
15833*/
15834#define PAGER_LOCKINGMODE_QUERY      -1
15835#define PAGER_LOCKINGMODE_NORMAL      0
15836#define PAGER_LOCKINGMODE_EXCLUSIVE   1
15837
15838/*
15839** Numeric constants that encode the journalmode.
15840**
15841** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
15842** are exposed in the API via the "PRAGMA journal_mode" command and
15843** therefore cannot be changed without a compatibility break.
15844*/
15845#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
15846#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
15847#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
15848#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
15849#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
15850#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
15851#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
15852
15853/*
15854** Flags that make up the mask passed to sqlite3PagerGet().
15855*/
15856#define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
15857#define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
15858
15859/*
15860** Flags for sqlite3PagerSetFlags()
15861**
15862** Value constraints (enforced via assert()):
15863**    PAGER_FULLFSYNC      == SQLITE_FullFSync
15864**    PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
15865**    PAGER_CACHE_SPILL    == SQLITE_CacheSpill
15866*/
15867#define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
15868#define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
15869#define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
15870#define PAGER_SYNCHRONOUS_EXTRA     0x04  /* PRAGMA synchronous=EXTRA */
15871#define PAGER_SYNCHRONOUS_MASK      0x07  /* Mask for four values above */
15872#define PAGER_FULLFSYNC             0x08  /* PRAGMA fullfsync=ON */
15873#define PAGER_CKPT_FULLFSYNC        0x10  /* PRAGMA checkpoint_fullfsync=ON */
15874#define PAGER_CACHESPILL            0x20  /* PRAGMA cache_spill=ON */
15875#define PAGER_FLAGS_MASK            0x38  /* All above except SYNCHRONOUS */
15876
15877/*
15878** The remainder of this file contains the declarations of the functions
15879** that make up the Pager sub-system API. See source code comments for
15880** a detailed description of each routine.
15881*/
15882
15883/* Open and close a Pager connection. */
15884SQLITE_PRIVATE int sqlite3PagerOpen(
15885  sqlite3_vfs*,
15886  Pager **ppPager,
15887  const char*,
15888  int,
15889  int,
15890  int,
15891  void(*)(DbPage*)
15892);
15893SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
15894SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
15895
15896/* Functions used to configure a Pager object. */
15897SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
15898SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
15899SQLITE_PRIVATE Pgno sqlite3PagerMaxPageCount(Pager*, Pgno);
15900SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
15901SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
15902SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
15903SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
15904SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
15905SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
15906SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
15907SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
15908SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
15909SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
15910SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
15911SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
15912
15913/* Functions used to obtain and release page references. */
15914SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
15915SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
15916SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
15917SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
15918SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
15919SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
15920
15921/* Operations on page references. */
15922SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
15923SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
15924SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
15925SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
15926SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
15927SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
15928
15929/* Functions used to manage pager transactions and savepoints. */
15930SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
15931SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
15932SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zSuper, int);
15933SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
15934SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zSuper);
15935SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
15936SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
15937SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
15938SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
15939SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
15940
15941#ifndef SQLITE_OMIT_WAL
15942SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
15943SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
15944SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
15945SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
15946SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
15947# ifdef SQLITE_ENABLE_SNAPSHOT
15948SQLITE_PRIVATE   int sqlite3PagerSnapshotGet(Pager*, sqlite3_snapshot **ppSnapshot);
15949SQLITE_PRIVATE   int sqlite3PagerSnapshotOpen(Pager*, sqlite3_snapshot *pSnapshot);
15950SQLITE_PRIVATE   int sqlite3PagerSnapshotRecover(Pager *pPager);
15951SQLITE_PRIVATE   int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
15952SQLITE_PRIVATE   void sqlite3PagerSnapshotUnlock(Pager *pPager);
15953# endif
15954#endif
15955
15956#if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_ENABLE_SETLK_TIMEOUT)
15957SQLITE_PRIVATE   int sqlite3PagerWalWriteLock(Pager*, int);
15958SQLITE_PRIVATE   void sqlite3PagerWalDb(Pager*, sqlite3*);
15959#else
15960# define sqlite3PagerWalWriteLock(y,z) SQLITE_OK
15961# define sqlite3PagerWalDb(x,y)
15962#endif
15963
15964#ifdef SQLITE_DIRECT_OVERFLOW_READ
15965SQLITE_PRIVATE   int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);
15966#endif
15967
15968#ifdef SQLITE_ENABLE_ZIPVFS
15969SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
15970#endif
15971
15972/* Functions used to query pager state and configuration. */
15973SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
15974SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
15975#ifdef SQLITE_DEBUG
15976SQLITE_PRIVATE   int sqlite3PagerRefcount(Pager*);
15977#endif
15978SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
15979SQLITE_PRIVATE const char *sqlite3PagerFilename(const Pager*, int);
15980SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
15981SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
15982SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
15983SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
15984SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
15985SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
15986SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, u64*);
15987SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
15988SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
15989
15990/* Functions used to truncate the database file. */
15991SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
15992
15993SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
15994
15995/* Functions to support testing and debugging. */
15996#if !defined(NDEBUG) || defined(SQLITE_TEST)
15997SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
15998SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
15999#endif
16000#ifdef SQLITE_TEST
16001SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
16002SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
16003  void disable_simulated_io_errors(void);
16004  void enable_simulated_io_errors(void);
16005#else
16006# define disable_simulated_io_errors()
16007# define enable_simulated_io_errors()
16008#endif
16009
16010#if defined(SQLITE_USE_SEH) && !defined(SQLITE_OMIT_WAL)
16011SQLITE_PRIVATE int sqlite3PagerWalSystemErrno(Pager*);
16012#endif
16013
16014#endif /* SQLITE_PAGER_H */
16015
16016/************** End of pager.h ***********************************************/
16017/************** Continuing where we left off in sqliteInt.h ******************/
16018/************** Include btree.h in the middle of sqliteInt.h *****************/
16019/************** Begin file btree.h *******************************************/
16020/*
16021** 2001 September 15
16022**
16023** The author disclaims copyright to this source code.  In place of
16024** a legal notice, here is a blessing:
16025**
16026**    May you do good and not evil.
16027**    May you find forgiveness for yourself and forgive others.
16028**    May you share freely, never taking more than you give.
16029**
16030*************************************************************************
16031** This header file defines the interface that the sqlite B-Tree file
16032** subsystem.  See comments in the source code for a detailed description
16033** of what each interface routine does.
16034*/
16035#ifndef SQLITE_BTREE_H
16036#define SQLITE_BTREE_H
16037
16038/* TODO: This definition is just included so other modules compile. It
16039** needs to be revisited.
16040*/
16041#define SQLITE_N_BTREE_META 16
16042
16043/*
16044** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
16045** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
16046*/
16047#ifndef SQLITE_DEFAULT_AUTOVACUUM
16048  #define SQLITE_DEFAULT_AUTOVACUUM 0
16049#endif
16050
16051#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
16052#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
16053#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
16054
16055/*
16056** Forward declarations of structure
16057*/
16058typedef struct Btree Btree;
16059typedef struct BtCursor BtCursor;
16060typedef struct BtShared BtShared;
16061typedef struct BtreePayload BtreePayload;
16062
16063
16064SQLITE_PRIVATE int sqlite3BtreeOpen(
16065  sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
16066  const char *zFilename,   /* Name of database file to open */
16067  sqlite3 *db,             /* Associated database connection */
16068  Btree **ppBtree,         /* Return open Btree* here */
16069  int flags,               /* Flags */
16070  int vfsFlags             /* Flags passed through to VFS open */
16071);
16072
16073/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
16074** following values.
16075**
16076** NOTE:  These values must match the corresponding PAGER_ values in
16077** pager.h.
16078*/
16079#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
16080#define BTREE_MEMORY        2  /* This is an in-memory DB */
16081#define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
16082#define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
16083
16084SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
16085SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
16086SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
16087#if SQLITE_MAX_MMAP_SIZE>0
16088SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
16089#endif
16090SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
16091SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
16092SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
16093SQLITE_PRIVATE Pgno sqlite3BtreeMaxPageCount(Btree*,Pgno);
16094SQLITE_PRIVATE Pgno sqlite3BtreeLastPage(Btree*);
16095SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
16096SQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(Btree*);
16097SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
16098SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
16099SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
16100SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int,int*);
16101SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char*);
16102SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
16103SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
16104SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
16105SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
16106SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, Pgno*, int flags);
16107SQLITE_PRIVATE int sqlite3BtreeTxnState(Btree*);
16108SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
16109
16110SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
16111SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
16112#ifndef SQLITE_OMIT_SHARED_CACHE
16113SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
16114#endif
16115
16116/* Savepoints are named, nestable SQL transactions mostly implemented */
16117/* in vdbe.c and pager.c See https://sqlite.org/lang_savepoint.html */
16118SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
16119
16120/* "Checkpoint" only refers to WAL. See https://sqlite.org/wal.html#ckpt */
16121#ifndef SQLITE_OMIT_WAL
16122SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
16123#endif
16124
16125SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
16126SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
16127SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
16128
16129SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
16130
16131/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
16132** of the flags shown below.
16133**
16134** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
16135** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
16136** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
16137** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
16138** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
16139** indices.)
16140*/
16141#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
16142#define BTREE_BLOBKEY    2    /* Table has keys only - no data */
16143
16144SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
16145SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, i64*);
16146SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
16147SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
16148
16149SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
16150SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
16151
16152SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
16153
16154/*
16155** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
16156** should be one of the following values. The integer values are assigned
16157** to constants so that the offset of the corresponding field in an
16158** SQLite database header may be found using the following formula:
16159**
16160**   offset = 36 + (idx * 4)
16161**
16162** For example, the free-page-count field is located at byte offset 36 of
16163** the database file header. The incr-vacuum-flag field is located at
16164** byte offset 64 (== 36+4*7).
16165**
16166** The BTREE_DATA_VERSION value is not really a value stored in the header.
16167** It is a read-only number computed by the pager.  But we merge it with
16168** the header value access routines since its access pattern is the same.
16169** Call it a "virtual meta value".
16170*/
16171#define BTREE_FREE_PAGE_COUNT     0
16172#define BTREE_SCHEMA_VERSION      1
16173#define BTREE_FILE_FORMAT         2
16174#define BTREE_DEFAULT_CACHE_SIZE  3
16175#define BTREE_LARGEST_ROOT_PAGE   4
16176#define BTREE_TEXT_ENCODING       5
16177#define BTREE_USER_VERSION        6
16178#define BTREE_INCR_VACUUM         7
16179#define BTREE_APPLICATION_ID      8
16180#define BTREE_DATA_VERSION        15  /* A virtual meta-value */
16181
16182/*
16183** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
16184** interface.
16185**
16186** BTREE_HINT_RANGE  (arguments: Expr*, Mem*)
16187**
16188**     The first argument is an Expr* (which is guaranteed to be constant for
16189**     the lifetime of the cursor) that defines constraints on which rows
16190**     might be fetched with this cursor.  The Expr* tree may contain
16191**     TK_REGISTER nodes that refer to values stored in the array of registers
16192**     passed as the second parameter.  In other words, if Expr.op==TK_REGISTER
16193**     then the value of the node is the value in Mem[pExpr.iTable].  Any
16194**     TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
16195**     column of the b-tree of the cursor.  The Expr tree will not contain
16196**     any function calls nor subqueries nor references to b-trees other than
16197**     the cursor being hinted.
16198**
16199**     The design of the _RANGE hint is aid b-tree implementations that try
16200**     to prefetch content from remote machines - to provide those
16201**     implementations with limits on what needs to be prefetched and thereby
16202**     reduce network bandwidth.
16203**
16204** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
16205** standard SQLite.  The other hints are provided for extensions that use
16206** the SQLite parser and code generator but substitute their own storage
16207** engine.
16208*/
16209#define BTREE_HINT_RANGE 0       /* Range constraints on queries */
16210
16211/*
16212** Values that may be OR'd together to form the argument to the
16213** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
16214**
16215** The BTREE_BULKLOAD flag is set on index cursors when the index is going
16216** to be filled with content that is already in sorted order.
16217**
16218** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
16219** OP_SeekLE opcodes for a range search, but where the range of entries
16220** selected will all have the same key.  In other words, the cursor will
16221** be used only for equality key searches.
16222**
16223*/
16224#define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */
16225#define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */
16226
16227/*
16228** Flags passed as the third argument to sqlite3BtreeCursor().
16229**
16230** For read-only cursors the wrFlag argument is always zero. For read-write
16231** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
16232** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
16233** only be used by SQLite for the following:
16234**
16235**   * to seek to and then delete specific entries, and/or
16236**
16237**   * to read values that will be used to create keys that other
16238**     BTREE_FORDELETE cursors will seek to and delete.
16239**
16240** The BTREE_FORDELETE flag is an optimization hint.  It is not used by
16241** by this, the native b-tree engine of SQLite, but it is available to
16242** alternative storage engines that might be substituted in place of this
16243** b-tree system.  For alternative storage engines in which a delete of
16244** the main table row automatically deletes corresponding index rows,
16245** the FORDELETE flag hint allows those alternative storage engines to
16246** skip a lot of work.  Namely:  FORDELETE cursors may treat all SEEK
16247** and DELETE operations as no-ops, and any READ operation against a
16248** FORDELETE cursor may return a null row: 0x01 0x00.
16249*/
16250#define BTREE_WRCSR     0x00000004     /* read-write cursor */
16251#define BTREE_FORDELETE 0x00000008     /* Cursor is for seek/delete only */
16252
16253SQLITE_PRIVATE int sqlite3BtreeCursor(
16254  Btree*,                              /* BTree containing table to open */
16255  Pgno iTable,                         /* Index of root page */
16256  int wrFlag,                          /* 1 for writing.  0 for read-only */
16257  struct KeyInfo*,                     /* First argument to compare function */
16258  BtCursor *pCursor                    /* Space to write cursor structure */
16259);
16260SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
16261SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
16262SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
16263SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
16264#ifdef SQLITE_ENABLE_CURSOR_HINTS
16265SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
16266#endif
16267
16268SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
16269SQLITE_PRIVATE int sqlite3BtreeTableMoveto(
16270  BtCursor*,
16271  i64 intKey,
16272  int bias,
16273  int *pRes
16274);
16275SQLITE_PRIVATE int sqlite3BtreeIndexMoveto(
16276  BtCursor*,
16277  UnpackedRecord *pUnKey,
16278  int *pRes
16279);
16280SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
16281SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
16282SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
16283
16284/* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
16285#define BTREE_SAVEPOSITION 0x02  /* Leave cursor pointing at NEXT or PREV */
16286#define BTREE_AUXDELETE    0x04  /* not the primary delete operation */
16287#define BTREE_APPEND       0x08  /* Insert is likely an append */
16288#define BTREE_PREFORMAT    0x80  /* Inserted data is a preformated cell */
16289
16290/* An instance of the BtreePayload object describes the content of a single
16291** entry in either an index or table btree.
16292**
16293** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
16294** an arbitrary key and no data.  These btrees have pKey,nKey set to the
16295** key and the pData,nData,nZero fields are uninitialized.  The aMem,nMem
16296** fields give an array of Mem objects that are a decomposition of the key.
16297** The nMem field might be zero, indicating that no decomposition is available.
16298**
16299** Table btrees (used for rowid tables) contain an integer rowid used as
16300** the key and passed in the nKey field.  The pKey field is zero.
16301** pData,nData hold the content of the new entry.  nZero extra zero bytes
16302** are appended to the end of the content when constructing the entry.
16303** The aMem,nMem fields are uninitialized for table btrees.
16304**
16305** Field usage summary:
16306**
16307**               Table BTrees                   Index Btrees
16308**
16309**   pKey        always NULL                    encoded key
16310**   nKey        the ROWID                      length of pKey
16311**   pData       data                           not used
16312**   aMem        not used                       decomposed key value
16313**   nMem        not used                       entries in aMem
16314**   nData       length of pData                not used
16315**   nZero       extra zeros after pData        not used
16316**
16317** This object is used to pass information into sqlite3BtreeInsert().  The
16318** same information used to be passed as five separate parameters.  But placing
16319** the information into this object helps to keep the interface more
16320** organized and understandable, and it also helps the resulting code to
16321** run a little faster by using fewer registers for parameter passing.
16322*/
16323struct BtreePayload {
16324  const void *pKey;       /* Key content for indexes.  NULL for tables */
16325  sqlite3_int64 nKey;     /* Size of pKey for indexes.  PRIMARY KEY for tabs */
16326  const void *pData;      /* Data for tables. */
16327  sqlite3_value *aMem;    /* First of nMem value in the unpacked pKey */
16328  u16 nMem;               /* Number of aMem[] value.  Might be zero */
16329  int nData;              /* Size of pData.  0 if none. */
16330  int nZero;              /* Extra zero data appended after pData,nData */
16331};
16332
16333SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
16334                       int flags, int seekResult);
16335SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
16336SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
16337SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
16338SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
16339SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
16340SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
16341SQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor*);
16342SQLITE_PRIVATE void sqlite3BtreeCursorUnpin(BtCursor*);
16343SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);
16344SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
16345SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
16346SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
16347SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor*);
16348
16349SQLITE_PRIVATE int sqlite3BtreeIntegrityCheck(
16350  sqlite3 *db,  /* Database connection that is running the check */
16351  Btree *p,     /* The btree to be checked */
16352  Pgno *aRoot,  /* An array of root pages numbers for individual trees */
16353  sqlite3_value *aCnt,  /* OUT: entry counts for each btree in aRoot[] */
16354  int nRoot,    /* Number of entries in aRoot[] */
16355  int mxErr,    /* Stop reporting errors after this many */
16356  int *pnErr,   /* OUT: Write number of errors seen to this variable */
16357  char **pzOut  /* OUT: Write the error message string here */
16358);
16359SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
16360SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
16361
16362#ifndef SQLITE_OMIT_INCRBLOB
16363SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
16364SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
16365SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
16366#endif
16367SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
16368SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
16369SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
16370SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
16371SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
16372
16373#ifdef SQLITE_DEBUG
16374SQLITE_PRIVATE sqlite3_uint64 sqlite3BtreeSeekCount(Btree*);
16375#else
16376# define sqlite3BtreeSeekCount(X) 0
16377#endif
16378
16379#ifndef NDEBUG
16380SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
16381#endif
16382SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
16383
16384SQLITE_PRIVATE int sqlite3BtreeCount(sqlite3*, BtCursor*, i64*);
16385
16386#ifdef SQLITE_TEST
16387SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
16388SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
16389#endif
16390
16391#ifndef SQLITE_OMIT_WAL
16392SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
16393#endif
16394
16395SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor*, BtCursor*, i64);
16396
16397SQLITE_PRIVATE void sqlite3BtreeClearCache(Btree*);
16398
16399/*
16400** If we are not using shared cache, then there is no need to
16401** use mutexes to access the BtShared structures.  So make the
16402** Enter and Leave procedures no-ops.
16403*/
16404#ifndef SQLITE_OMIT_SHARED_CACHE
16405SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
16406SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
16407SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
16408SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
16409SQLITE_PRIVATE   int sqlite3BtreeConnectionCount(Btree*);
16410#else
16411# define sqlite3BtreeEnter(X)
16412# define sqlite3BtreeEnterAll(X)
16413# define sqlite3BtreeSharable(X) 0
16414# define sqlite3BtreeEnterCursor(X)
16415# define sqlite3BtreeConnectionCount(X) 1
16416#endif
16417
16418#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
16419SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
16420SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
16421SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
16422#ifndef NDEBUG
16423  /* These routines are used inside assert() statements only. */
16424SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
16425SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
16426SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
16427#endif
16428#else
16429
16430# define sqlite3BtreeLeave(X)
16431# define sqlite3BtreeLeaveCursor(X)
16432# define sqlite3BtreeLeaveAll(X)
16433
16434# define sqlite3BtreeHoldsMutex(X) 1
16435# define sqlite3BtreeHoldsAllMutexes(X) 1
16436# define sqlite3SchemaMutexHeld(X,Y,Z) 1
16437#endif
16438
16439
16440#endif /* SQLITE_BTREE_H */
16441
16442/************** End of btree.h ***********************************************/
16443/************** Continuing where we left off in sqliteInt.h ******************/
16444/************** Include vdbe.h in the middle of sqliteInt.h ******************/
16445/************** Begin file vdbe.h ********************************************/
16446/*
16447** 2001 September 15
16448**
16449** The author disclaims copyright to this source code.  In place of
16450** a legal notice, here is a blessing:
16451**
16452**    May you do good and not evil.
16453**    May you find forgiveness for yourself and forgive others.
16454**    May you share freely, never taking more than you give.
16455**
16456*************************************************************************
16457** Header file for the Virtual DataBase Engine (VDBE)
16458**
16459** This header defines the interface to the virtual database engine
16460** or VDBE.  The VDBE implements an abstract machine that runs a
16461** simple program to access and modify the underlying database.
16462*/
16463#ifndef SQLITE_VDBE_H
16464#define SQLITE_VDBE_H
16465/* #include <stdio.h> */
16466
16467/*
16468** A single VDBE is an opaque structure named "Vdbe".  Only routines
16469** in the source file sqliteVdbe.c are allowed to see the insides
16470** of this structure.
16471*/
16472typedef struct Vdbe Vdbe;
16473
16474/*
16475** The names of the following types declared in vdbeInt.h are required
16476** for the VdbeOp definition.
16477*/
16478typedef struct sqlite3_value Mem;
16479typedef struct SubProgram SubProgram;
16480
16481/*
16482** A single instruction of the virtual machine has an opcode
16483** and as many as three operands.  The instruction is recorded
16484** as an instance of the following structure:
16485*/
16486struct VdbeOp {
16487  u8 opcode;          /* What operation to perform */
16488  signed char p4type; /* One of the P4_xxx constants for p4 */
16489  u16 p5;             /* Fifth parameter is an unsigned 16-bit integer */
16490  int p1;             /* First operand */
16491  int p2;             /* Second parameter (often the jump destination) */
16492  int p3;             /* The third parameter */
16493  union p4union {     /* fourth parameter */
16494    int i;                 /* Integer value if p4type==P4_INT32 */
16495    void *p;               /* Generic pointer */
16496    char *z;               /* Pointer to data for string (char array) types */
16497    i64 *pI64;             /* Used when p4type is P4_INT64 */
16498    double *pReal;         /* Used when p4type is P4_REAL */
16499    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
16500    sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
16501    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
16502    Mem *pMem;             /* Used when p4type is P4_MEM */
16503    VTable *pVtab;         /* Used when p4type is P4_VTAB */
16504    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
16505    u32 *ai;               /* Used when p4type is P4_INTARRAY */
16506    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
16507    Table *pTab;           /* Used when p4type is P4_TABLE */
16508#ifdef SQLITE_ENABLE_CURSOR_HINTS
16509    Expr *pExpr;           /* Used when p4type is P4_EXPR */
16510#endif
16511  } p4;
16512#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
16513  char *zComment;          /* Comment to improve readability */
16514#endif
16515#ifdef SQLITE_VDBE_COVERAGE
16516  u32 iSrcLine;            /* Source-code line that generated this opcode
16517                           ** with flags in the upper 8 bits */
16518#endif
16519#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
16520  u64 nExec;
16521  u64 nCycle;
16522#endif
16523};
16524typedef struct VdbeOp VdbeOp;
16525
16526
16527/*
16528** A sub-routine used to implement a trigger program.
16529*/
16530struct SubProgram {
16531  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
16532  int nOp;                      /* Elements in aOp[] */
16533  int nMem;                     /* Number of memory cells required */
16534  int nCsr;                     /* Number of cursors required */
16535  u8 *aOnce;                    /* Array of OP_Once flags */
16536  void *token;                  /* id that may be used to recursive triggers */
16537  SubProgram *pNext;            /* Next sub-program already visited */
16538};
16539
16540/*
16541** A smaller version of VdbeOp used for the VdbeAddOpList() function because
16542** it takes up less space.
16543*/
16544struct VdbeOpList {
16545  u8 opcode;          /* What operation to perform */
16546  signed char p1;     /* First operand */
16547  signed char p2;     /* Second parameter (often the jump destination) */
16548  signed char p3;     /* Third parameter */
16549};
16550typedef struct VdbeOpList VdbeOpList;
16551
16552/*
16553** Allowed values of VdbeOp.p4type
16554*/
16555#define P4_NOTUSED      0   /* The P4 parameter is not used */
16556#define P4_TRANSIENT    0   /* P4 is a pointer to a transient string */
16557#define P4_STATIC     (-1)  /* Pointer to a static string */
16558#define P4_COLLSEQ    (-2)  /* P4 is a pointer to a CollSeq structure */
16559#define P4_INT32      (-3)  /* P4 is a 32-bit signed integer */
16560#define P4_SUBPROGRAM (-4)  /* P4 is a pointer to a SubProgram structure */
16561#define P4_TABLE      (-5)  /* P4 is a pointer to a Table structure */
16562/* Above do not own any resources.  Must free those below */
16563#define P4_FREE_IF_LE (-6)
16564#define P4_DYNAMIC    (-6)  /* Pointer to memory from sqliteMalloc() */
16565#define P4_FUNCDEF    (-7)  /* P4 is a pointer to a FuncDef structure */
16566#define P4_KEYINFO    (-8)  /* P4 is a pointer to a KeyInfo structure */
16567#define P4_EXPR       (-9) /* P4 is a pointer to an Expr tree */
16568#define P4_MEM        (-10) /* P4 is a pointer to a Mem*    structure */
16569#define P4_VTAB       (-11) /* P4 is a pointer to an sqlite3_vtab structure */
16570#define P4_REAL       (-12) /* P4 is a 64-bit floating point value */
16571#define P4_INT64      (-13) /* P4 is a 64-bit signed integer */
16572#define P4_INTARRAY   (-14) /* P4 is a vector of 32-bit integers */
16573#define P4_FUNCCTX    (-15) /* P4 is a pointer to an sqlite3_context object */
16574#define P4_TABLEREF   (-16) /* Like P4_TABLE, but reference counted */
16575
16576/* Error message codes for OP_Halt */
16577#define P5_ConstraintNotNull 1
16578#define P5_ConstraintUnique  2
16579#define P5_ConstraintCheck   3
16580#define P5_ConstraintFK      4
16581
16582/*
16583** The Vdbe.aColName array contains 5n Mem structures, where n is the
16584** number of columns of data returned by the statement.
16585*/
16586#define COLNAME_NAME     0
16587#define COLNAME_DECLTYPE 1
16588#define COLNAME_DATABASE 2
16589#define COLNAME_TABLE    3
16590#define COLNAME_COLUMN   4
16591#ifdef SQLITE_ENABLE_COLUMN_METADATA
16592# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
16593#else
16594# ifdef SQLITE_OMIT_DECLTYPE
16595#   define COLNAME_N      1      /* Store only the name */
16596# else
16597#   define COLNAME_N      2      /* Store the name and decltype */
16598# endif
16599#endif
16600
16601/*
16602** The following macro converts a label returned by sqlite3VdbeMakeLabel()
16603** into an index into the Parse.aLabel[] array that contains the resolved
16604** address of that label.
16605*/
16606#define ADDR(X)  (~(X))
16607
16608/*
16609** The makefile scans the vdbe.c source file and creates the "opcodes.h"
16610** header file that defines a number for each opcode used by the VDBE.
16611*/
16612/************** Include opcodes.h in the middle of vdbe.h ********************/
16613/************** Begin file opcodes.h *****************************************/
16614/* Automatically generated.  Do not edit */
16615/* See the tool/mkopcodeh.tcl script for details */
16616#define OP_Savepoint       0
16617#define OP_AutoCommit      1
16618#define OP_Transaction     2
16619#define OP_Checkpoint      3
16620#define OP_JournalMode     4
16621#define OP_Vacuum          5
16622#define OP_VFilter         6 /* jump, synopsis: iplan=r[P3] zplan='P4'     */
16623#define OP_VUpdate         7 /* synopsis: data=r[P3@P2]                    */
16624#define OP_Init            8 /* jump0, synopsis: Start at P2               */
16625#define OP_Goto            9 /* jump                                       */
16626#define OP_Gosub          10 /* jump                                       */
16627#define OP_InitCoroutine  11 /* jump0                                      */
16628#define OP_Yield          12 /* jump0                                      */
16629#define OP_MustBeInt      13 /* jump0                                      */
16630#define OP_Jump           14 /* jump                                       */
16631#define OP_Once           15 /* jump                                       */
16632#define OP_If             16 /* jump                                       */
16633#define OP_IfNot          17 /* jump                                       */
16634#define OP_IsType         18 /* jump, synopsis: if typeof(P1.P3) in P5 goto P2 */
16635#define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
16636#define OP_IfNullRow      20 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
16637#define OP_SeekLT         21 /* jump0, synopsis: key=r[P3@P4]              */
16638#define OP_SeekLE         22 /* jump0, synopsis: key=r[P3@P4]              */
16639#define OP_SeekGE         23 /* jump0, synopsis: key=r[P3@P4]              */
16640#define OP_SeekGT         24 /* jump0, synopsis: key=r[P3@P4]              */
16641#define OP_IfNotOpen      25 /* jump, synopsis: if( !csr[P1] ) goto P2     */
16642#define OP_IfNoHope       26 /* jump, synopsis: key=r[P3@P4]               */
16643#define OP_NoConflict     27 /* jump, synopsis: key=r[P3@P4]               */
16644#define OP_NotFound       28 /* jump, synopsis: key=r[P3@P4]               */
16645#define OP_Found          29 /* jump, synopsis: key=r[P3@P4]               */
16646#define OP_SeekRowid      30 /* jump0, synopsis: intkey=r[P3]              */
16647#define OP_NotExists      31 /* jump, synopsis: intkey=r[P3]               */
16648#define OP_Last           32 /* jump0                                      */
16649#define OP_IfSizeBetween  33 /* jump                                       */
16650#define OP_SorterSort     34 /* jump                                       */
16651#define OP_Sort           35 /* jump                                       */
16652#define OP_Rewind         36 /* jump0                                      */
16653#define OP_SorterNext     37 /* jump                                       */
16654#define OP_Prev           38 /* jump                                       */
16655#define OP_Next           39 /* jump                                       */
16656#define OP_IdxLE          40 /* jump, synopsis: key=r[P3@P4]               */
16657#define OP_IdxGT          41 /* jump, synopsis: key=r[P3@P4]               */
16658#define OP_IdxLT          42 /* jump, synopsis: key=r[P3@P4]               */
16659#define OP_Or             43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
16660#define OP_And            44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
16661#define OP_IdxGE          45 /* jump, synopsis: key=r[P3@P4]               */
16662#define OP_RowSetRead     46 /* jump, synopsis: r[P3]=rowset(P1)           */
16663#define OP_RowSetTest     47 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
16664#define OP_Program        48 /* jump0                                      */
16665#define OP_FkIfZero       49 /* jump, synopsis: if fkctr[P1]==0 goto P2    */
16666#define OP_IsNull         50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
16667#define OP_NotNull        51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
16668#define OP_Ne             52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
16669#define OP_Eq             53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
16670#define OP_Gt             54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
16671#define OP_Le             55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
16672#define OP_Lt             56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
16673#define OP_Ge             57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
16674#define OP_ElseEq         58 /* jump, same as TK_ESCAPE                    */
16675#define OP_IfPos          59 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
16676#define OP_IfNotZero      60 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
16677#define OP_DecrJumpZero   61 /* jump, synopsis: if (--r[P1])==0 goto P2    */
16678#define OP_IncrVacuum     62 /* jump                                       */
16679#define OP_VNext          63 /* jump                                       */
16680#define OP_Filter         64 /* jump, synopsis: if key(P3@P4) not in filter(P1) goto P2 */
16681#define OP_PureFunc       65 /* synopsis: r[P3]=func(r[P2@NP])             */
16682#define OP_Function       66 /* synopsis: r[P3]=func(r[P2@NP])             */
16683#define OP_Return         67
16684#define OP_EndCoroutine   68
16685#define OP_HaltIfNull     69 /* synopsis: if r[P3]=null halt               */
16686#define OP_Halt           70
16687#define OP_Integer        71 /* synopsis: r[P2]=P1                         */
16688#define OP_Int64          72 /* synopsis: r[P2]=P4                         */
16689#define OP_String         73 /* synopsis: r[P2]='P4' (len=P1)              */
16690#define OP_BeginSubrtn    74 /* synopsis: r[P2]=NULL                       */
16691#define OP_Null           75 /* synopsis: r[P2..P3]=NULL                   */
16692#define OP_SoftNull       76 /* synopsis: r[P1]=NULL                       */
16693#define OP_Blob           77 /* synopsis: r[P2]=P4 (len=P1)                */
16694#define OP_Variable       78 /* synopsis: r[P2]=parameter(P1)              */
16695#define OP_Move           79 /* synopsis: r[P2@P3]=r[P1@P3]                */
16696#define OP_Copy           80 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
16697#define OP_SCopy          81 /* synopsis: r[P2]=r[P1]                      */
16698#define OP_IntCopy        82 /* synopsis: r[P2]=r[P1]                      */
16699#define OP_FkCheck        83
16700#define OP_ResultRow      84 /* synopsis: output=r[P1@P2]                  */
16701#define OP_CollSeq        85
16702#define OP_AddImm         86 /* synopsis: r[P1]=r[P1]+P2                   */
16703#define OP_RealAffinity   87
16704#define OP_Cast           88 /* synopsis: affinity(r[P1])                  */
16705#define OP_Permutation    89
16706#define OP_Compare        90 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
16707#define OP_IsTrue         91 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
16708#define OP_ZeroOrNull     92 /* synopsis: r[P2] = 0 OR NULL                */
16709#define OP_Offset         93 /* synopsis: r[P3] = sqlite_offset(P1)        */
16710#define OP_Column         94 /* synopsis: r[P3]=PX cursor P1 column P2     */
16711#define OP_TypeCheck      95 /* synopsis: typecheck(r[P1@P2])              */
16712#define OP_Affinity       96 /* synopsis: affinity(r[P1@P2])               */
16713#define OP_MakeRecord     97 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
16714#define OP_Count          98 /* synopsis: r[P2]=count()                    */
16715#define OP_ReadCookie     99
16716#define OP_SetCookie     100
16717#define OP_ReopenIdx     101 /* synopsis: root=P2 iDb=P3                   */
16718#define OP_BitAnd        102 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
16719#define OP_BitOr         103 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
16720#define OP_ShiftLeft     104 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
16721#define OP_ShiftRight    105 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
16722#define OP_Add           106 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
16723#define OP_Subtract      107 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
16724#define OP_Multiply      108 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
16725#define OP_Divide        109 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
16726#define OP_Remainder     110 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
16727#define OP_Concat        111 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
16728#define OP_OpenRead      112 /* synopsis: root=P2 iDb=P3                   */
16729#define OP_OpenWrite     113 /* synopsis: root=P2 iDb=P3                   */
16730#define OP_BitNot        114 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
16731#define OP_OpenDup       115
16732#define OP_OpenAutoindex 116 /* synopsis: nColumn=P2                       */
16733#define OP_String8       117 /* same as TK_STRING, synopsis: r[P2]='P4'    */
16734#define OP_OpenEphemeral 118 /* synopsis: nColumn=P2                       */
16735#define OP_SorterOpen    119
16736#define OP_SequenceTest  120 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
16737#define OP_OpenPseudo    121 /* synopsis: P3 columns in r[P2]              */
16738#define OP_Close         122
16739#define OP_ColumnsUsed   123
16740#define OP_SeekScan      124 /* synopsis: Scan-ahead up to P1 rows         */
16741#define OP_SeekHit       125 /* synopsis: set P2<=seekHit<=P3              */
16742#define OP_Sequence      126 /* synopsis: r[P2]=cursor[P1].ctr++           */
16743#define OP_NewRowid      127 /* synopsis: r[P2]=rowid                      */
16744#define OP_Insert        128 /* synopsis: intkey=r[P3] data=r[P2]          */
16745#define OP_RowCell       129
16746#define OP_Delete        130
16747#define OP_ResetCount    131
16748#define OP_SorterCompare 132 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
16749#define OP_SorterData    133 /* synopsis: r[P2]=data                       */
16750#define OP_RowData       134 /* synopsis: r[P2]=data                       */
16751#define OP_Rowid         135 /* synopsis: r[P2]=PX rowid of P1             */
16752#define OP_NullRow       136
16753#define OP_SeekEnd       137
16754#define OP_IdxInsert     138 /* synopsis: key=r[P2]                        */
16755#define OP_SorterInsert  139 /* synopsis: key=r[P2]                        */
16756#define OP_IdxDelete     140 /* synopsis: key=r[P2@P3]                     */
16757#define OP_DeferredSeek  141 /* synopsis: Move P3 to P1.rowid if needed    */
16758#define OP_IdxRowid      142 /* synopsis: r[P2]=rowid                      */
16759#define OP_FinishSeek    143
16760#define OP_Destroy       144
16761#define OP_Clear         145
16762#define OP_ResetSorter   146
16763#define OP_CreateBtree   147 /* synopsis: r[P2]=root iDb=P1 flags=P3       */
16764#define OP_SqlExec       148
16765#define OP_ParseSchema   149
16766#define OP_LoadAnalysis  150
16767#define OP_DropTable     151
16768#define OP_DropIndex     152
16769#define OP_Real          153 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
16770#define OP_DropTrigger   154
16771#define OP_IntegrityCk   155
16772#define OP_RowSetAdd     156 /* synopsis: rowset(P1)=r[P2]                 */
16773#define OP_Param         157
16774#define OP_FkCounter     158 /* synopsis: fkctr[P1]+=P2                    */
16775#define OP_MemMax        159 /* synopsis: r[P1]=max(r[P1],r[P2])           */
16776#define OP_OffsetLimit   160 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
16777#define OP_AggInverse    161 /* synopsis: accum=r[P3] inverse(r[P2@P5])    */
16778#define OP_AggStep       162 /* synopsis: accum=r[P3] step(r[P2@P5])       */
16779#define OP_AggStep1      163 /* synopsis: accum=r[P3] step(r[P2@P5])       */
16780#define OP_AggValue      164 /* synopsis: r[P3]=value N=P2                 */
16781#define OP_AggFinal      165 /* synopsis: accum=r[P1] N=P2                 */
16782#define OP_Expire        166
16783#define OP_CursorLock    167
16784#define OP_CursorUnlock  168
16785#define OP_TableLock     169 /* synopsis: iDb=P1 root=P2 write=P3          */
16786#define OP_VBegin        170
16787#define OP_VCreate       171
16788#define OP_VDestroy      172
16789#define OP_VOpen         173
16790#define OP_VCheck        174
16791#define OP_VInitIn       175 /* synopsis: r[P2]=ValueList(P1,P3)           */
16792#define OP_VColumn       176 /* synopsis: r[P3]=vcolumn(P2)                */
16793#define OP_VRename       177
16794#define OP_Pagecount     178
16795#define OP_MaxPgcnt      179
16796#define OP_ClrSubtype    180 /* synopsis: r[P1].subtype = 0                */
16797#define OP_GetSubtype    181 /* synopsis: r[P2] = r[P1].subtype            */
16798#define OP_SetSubtype    182 /* synopsis: r[P2].subtype = r[P1]            */
16799#define OP_FilterAdd     183 /* synopsis: filter(P1) += key(P3@P4)         */
16800#define OP_Trace         184
16801#define OP_CursorHint    185
16802#define OP_ReleaseReg    186 /* synopsis: release r[P1@P2] mask P3         */
16803#define OP_Noop          187
16804#define OP_Explain       188
16805#define OP_Abortable     189
16806
16807/* Properties such as "out2" or "jump" that are specified in
16808** comments following the "case" for each opcode in the vdbe.c
16809** are encoded into bitvectors as follows:
16810*/
16811#define OPFLG_JUMP        0x01  /* jump:  P2 holds jmp target */
16812#define OPFLG_IN1         0x02  /* in1:   P1 is an input */
16813#define OPFLG_IN2         0x04  /* in2:   P2 is an input */
16814#define OPFLG_IN3         0x08  /* in3:   P3 is an input */
16815#define OPFLG_OUT2        0x10  /* out2:  P2 is an output */
16816#define OPFLG_OUT3        0x20  /* out3:  P3 is an output */
16817#define OPFLG_NCYCLE      0x40  /* ncycle:Cycles count against P1 */
16818#define OPFLG_JUMP0       0x80  /* jump0:  P2 might be zero */
16819#define OPFLG_INITIALIZER {\
16820/*   0 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x41, 0x00,\
16821/*   8 */ 0x81, 0x01, 0x01, 0x81, 0x83, 0x83, 0x01, 0x01,\
16822/*  16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0xc9, 0xc9, 0xc9,\
16823/*  24 */ 0xc9, 0x01, 0x49, 0x49, 0x49, 0x49, 0xc9, 0x49,\
16824/*  32 */ 0xc1, 0x01, 0x41, 0x41, 0xc1, 0x01, 0x41, 0x41,\
16825/*  40 */ 0x41, 0x41, 0x41, 0x26, 0x26, 0x41, 0x23, 0x0b,\
16826/*  48 */ 0x81, 0x01, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
16827/*  56 */ 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x03, 0x01, 0x41,\
16828/*  64 */ 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10,\
16829/*  72 */ 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10, 0x00,\
16830/*  80 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x02, 0x02,\
16831/*  88 */ 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20, 0x40, 0x00,\
16832/*  96 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x26, 0x26,\
16833/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\
16834/* 112 */ 0x40, 0x00, 0x12, 0x40, 0x40, 0x10, 0x40, 0x00,\
16835/* 120 */ 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x10, 0x10,\
16836/* 128 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x50,\
16837/* 136 */ 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50, 0x40,\
16838/* 144 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
16839/* 152 */ 0x00, 0x10, 0x00, 0x00, 0x06, 0x10, 0x00, 0x04,\
16840/* 160 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
16841/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50,\
16842/* 176 */ 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12, 0x00,\
16843/* 184 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}
16844
16845/* The resolve3P2Values() routine is able to run faster if it knows
16846** the value of the largest JUMP opcode.  The smaller the maximum
16847** JUMP opcode the better, so the mkopcodeh.tcl script that
16848** generated this include file strives to group all JUMP opcodes
16849** together near the beginning of the list.
16850*/
16851#define SQLITE_MX_JUMP_OPCODE  64  /* Maximum JUMP opcode */
16852
16853/************** End of opcodes.h *********************************************/
16854/************** Continuing where we left off in vdbe.h ***********************/
16855
16856/*
16857** Additional non-public SQLITE_PREPARE_* flags
16858*/
16859#define SQLITE_PREPARE_SAVESQL  0x80  /* Preserve SQL text */
16860#define SQLITE_PREPARE_MASK     0x0f  /* Mask of public flags */
16861
16862/*
16863** Prototypes for the VDBE interface.  See comments on the implementation
16864** for a description of what each of these routines does.
16865*/
16866SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
16867SQLITE_PRIVATE Parse *sqlite3VdbeParser(Vdbe*);
16868SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
16869SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
16870SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
16871SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
16872SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
16873SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
16874SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
16875SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
16876SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
16877SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
16878SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(Parse*,int,int,int,int,const FuncDef*,int);
16879SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
16880#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
16881SQLITE_PRIVATE   void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
16882SQLITE_PRIVATE   void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
16883#else
16884# define sqlite3VdbeVerifyNoMallocRequired(A,B)
16885# define sqlite3VdbeVerifyNoResultRow(A)
16886#endif
16887#if defined(SQLITE_DEBUG)
16888SQLITE_PRIVATE   void sqlite3VdbeVerifyAbortable(Vdbe *p, int);
16889SQLITE_PRIVATE   void sqlite3VdbeNoJumpsOutsideSubrtn(Vdbe*,int,int,int);
16890#else
16891# define sqlite3VdbeVerifyAbortable(A,B)
16892# define sqlite3VdbeNoJumpsOutsideSubrtn(A,B,C,D)
16893#endif
16894SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);
16895#ifndef SQLITE_OMIT_EXPLAIN
16896SQLITE_PRIVATE   int sqlite3VdbeExplain(Parse*,u8,const char*,...);
16897SQLITE_PRIVATE   void sqlite3VdbeExplainPop(Parse*);
16898SQLITE_PRIVATE   int sqlite3VdbeExplainParent(Parse*);
16899# define ExplainQueryPlan(P)        sqlite3VdbeExplain P
16900# ifdef SQLITE_ENABLE_STMT_SCANSTATUS
16901#  define ExplainQueryPlan2(V,P)     (V = sqlite3VdbeExplain P)
16902# else
16903#  define ExplainQueryPlan2(V,P)     ExplainQueryPlan(P)
16904# endif
16905# define ExplainQueryPlanPop(P)     sqlite3VdbeExplainPop(P)
16906# define ExplainQueryPlanParent(P)  sqlite3VdbeExplainParent(P)
16907#else
16908# define ExplainQueryPlan(P)
16909# define ExplainQueryPlan2(V,P)
16910# define ExplainQueryPlanPop(P)
16911# define ExplainQueryPlanParent(P) 0
16912# define sqlite3ExplainBreakpoint(A,B) /*no-op*/
16913#endif
16914#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN)
16915SQLITE_PRIVATE   void sqlite3ExplainBreakpoint(const char*,const char*);
16916#else
16917# define sqlite3ExplainBreakpoint(A,B) /*no-op*/
16918#endif
16919SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*, int, char*, u16);
16920SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, int addr, u8);
16921SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
16922SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
16923SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
16924SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
16925SQLITE_PRIVATE void sqlite3VdbeTypeofColumn(Vdbe*, int);
16926SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
16927SQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe*, int addr);
16928SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
16929SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
16930#ifdef SQLITE_DEBUG
16931SQLITE_PRIVATE   void sqlite3VdbeReleaseRegisters(Parse*,int addr, int n, u32 mask, int);
16932#else
16933# define sqlite3VdbeReleaseRegisters(P,A,N,M,F)
16934#endif
16935SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
16936SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
16937SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
16938SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
16939SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
16940SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetLastOp(Vdbe*);
16941SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse*);
16942SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
16943SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
16944SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
16945SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
16946SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
16947SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
16948SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
16949#ifdef SQLITE_DEBUG
16950SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
16951#endif
16952SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
16953SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
16954SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
16955SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
16956SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
16957SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
16958SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
16959SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
16960SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
16961#ifdef SQLITE_ENABLE_NORMALIZE
16962SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3*,Vdbe*,const char*);
16963SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*);
16964#endif
16965SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
16966SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
16967SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
16968SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
16969#ifndef SQLITE_OMIT_TRACE
16970SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
16971#endif
16972SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
16973SQLITE_PRIVATE int sqlite3BlobCompare(const Mem*, const Mem*);
16974
16975SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
16976SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
16977SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
16978SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
16979
16980typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
16981SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
16982
16983SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
16984SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe*);
16985
16986SQLITE_PRIVATE void sqlite3MemSetArrayInt64(sqlite3_value *aMem, int iIdx, i64 val);
16987
16988SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
16989#ifdef SQLITE_ENABLE_BYTECODE_VTAB
16990SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3*);
16991#endif
16992
16993/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
16994** each VDBE opcode.
16995**
16996** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
16997** comments in VDBE programs that show key decision points in the code
16998** generator.
16999*/
17000#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
17001SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
17002# define VdbeComment(X)  sqlite3VdbeComment X
17003SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
17004# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
17005# ifdef SQLITE_ENABLE_MODULE_COMMENTS
17006#   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
17007# else
17008#   define VdbeModuleComment(X)
17009# endif
17010#else
17011# define VdbeComment(X)
17012# define VdbeNoopComment(X)
17013# define VdbeModuleComment(X)
17014#endif
17015
17016/*
17017** The VdbeCoverage macros are used to set a coverage testing point
17018** for VDBE branch instructions.  The coverage testing points are line
17019** numbers in the sqlite3.c source file.  VDBE branch coverage testing
17020** only works with an amalgamation build.  That's ok since a VDBE branch
17021** coverage build designed for testing the test suite only.  No application
17022** should ever ship with VDBE branch coverage measuring turned on.
17023**
17024**    VdbeCoverage(v)                  // Mark the previously coded instruction
17025**                                     // as a branch
17026**
17027**    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
17028**
17029**    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
17030**
17031**    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
17032**
17033**    VdbeCoverageNeverNull(v)         // Previous three-way branch is only
17034**                                     // taken on the first two ways.  The
17035**                                     // NULL option is not possible
17036**
17037**    VdbeCoverageEqNe(v)              // Previous OP_Jump is only interested
17038**                                     // in distinguishing equal and not-equal.
17039**
17040** Every VDBE branch operation must be tagged with one of the macros above.
17041** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
17042** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
17043** routine in vdbe.c, alerting the developer to the missed tag.
17044**
17045** During testing, the test application will invoke
17046** sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback
17047** routine that is invoked as each bytecode branch is taken.  The callback
17048** contains the sqlite3.c source line number of the VdbeCoverage macro and
17049** flags to indicate whether or not the branch was taken.  The test application
17050** is responsible for keeping track of this and reporting byte-code branches
17051** that are never taken.
17052**
17053** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the
17054** vdbe.c source file for additional information.
17055*/
17056#ifdef SQLITE_VDBE_COVERAGE
17057SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
17058# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
17059# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
17060# define VdbeCoverageAlwaysTaken(v) \
17061         sqlite3VdbeSetLineNumber(v,__LINE__|0x5000000);
17062# define VdbeCoverageNeverTaken(v) \
17063         sqlite3VdbeSetLineNumber(v,__LINE__|0x6000000);
17064# define VdbeCoverageNeverNull(v) \
17065         sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
17066# define VdbeCoverageNeverNullIf(v,x) \
17067         if(x)sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
17068# define VdbeCoverageEqNe(v) \
17069         sqlite3VdbeSetLineNumber(v,__LINE__|0x8000000);
17070# define VDBE_OFFSET_LINENO(x) (__LINE__+x)
17071#else
17072# define VdbeCoverage(v)
17073# define VdbeCoverageIf(v,x)
17074# define VdbeCoverageAlwaysTaken(v)
17075# define VdbeCoverageNeverTaken(v)
17076# define VdbeCoverageNeverNull(v)
17077# define VdbeCoverageNeverNullIf(v,x)
17078# define VdbeCoverageEqNe(v)
17079# define VDBE_OFFSET_LINENO(x) 0
17080#endif
17081
17082#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
17083SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
17084SQLITE_PRIVATE void sqlite3VdbeScanStatusRange(Vdbe*, int, int, int);
17085SQLITE_PRIVATE void sqlite3VdbeScanStatusCounters(Vdbe*, int, int, int);
17086#else
17087# define sqlite3VdbeScanStatus(a,b,c,d,e,f)
17088# define sqlite3VdbeScanStatusRange(a,b,c,d)
17089# define sqlite3VdbeScanStatusCounters(a,b,c,d)
17090#endif
17091
17092#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
17093SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);
17094#endif
17095
17096#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
17097SQLITE_PRIVATE int sqlite3CursorRangeHintExprCheck(Walker *pWalker, Expr *pExpr);
17098#endif
17099
17100#endif /* SQLITE_VDBE_H */
17101
17102/************** End of vdbe.h ************************************************/
17103/************** Continuing where we left off in sqliteInt.h ******************/
17104/************** Include pcache.h in the middle of sqliteInt.h ****************/
17105/************** Begin file pcache.h ******************************************/
17106/*
17107** 2008 August 05
17108**
17109** The author disclaims copyright to this source code.  In place of
17110** a legal notice, here is a blessing:
17111**
17112**    May you do good and not evil.
17113**    May you find forgiveness for yourself and forgive others.
17114**    May you share freely, never taking more than you give.
17115**
17116*************************************************************************
17117** This header file defines the interface that the sqlite page cache
17118** subsystem.
17119*/
17120
17121#ifndef _PCACHE_H_
17122
17123typedef struct PgHdr PgHdr;
17124typedef struct PCache PCache;
17125
17126/*
17127** Every page in the cache is controlled by an instance of the following
17128** structure.
17129*/
17130struct PgHdr {
17131  sqlite3_pcache_page *pPage;    /* Pcache object page handle */
17132  void *pData;                   /* Page data */
17133  void *pExtra;                  /* Extra content */
17134  PCache *pCache;                /* PRIVATE: Cache that owns this page */
17135  PgHdr *pDirty;                 /* Transient list of dirty sorted by pgno */
17136  Pager *pPager;                 /* The pager this page is part of */
17137  Pgno pgno;                     /* Page number for this page */
17138#ifdef SQLITE_CHECK_PAGES
17139  u32 pageHash;                  /* Hash of page content */
17140#endif
17141  u16 flags;                     /* PGHDR flags defined below */
17142
17143  /**********************************************************************
17144  ** Elements above, except pCache, are public.  All that follow are
17145  ** private to pcache.c and should not be accessed by other modules.
17146  ** pCache is grouped with the public elements for efficiency.
17147  */
17148  i64 nRef;                      /* Number of users of this page */
17149  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
17150  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
17151                          /* NB: pDirtyNext and pDirtyPrev are undefined if the
17152                          ** PgHdr object is not dirty */
17153};
17154
17155/* Bit values for PgHdr.flags */
17156#define PGHDR_CLEAN           0x001  /* Page not on the PCache.pDirty list */
17157#define PGHDR_DIRTY           0x002  /* Page is on the PCache.pDirty list */
17158#define PGHDR_WRITEABLE       0x004  /* Journaled and ready to modify */
17159#define PGHDR_NEED_SYNC       0x008  /* Fsync the rollback journal before
17160                                     ** writing this page to the database */
17161#define PGHDR_DONT_WRITE      0x010  /* Do not write content to disk */
17162#define PGHDR_MMAP            0x020  /* This is an mmap page object */
17163
17164#define PGHDR_WAL_APPEND      0x040  /* Appended to wal file */
17165
17166/* Initialize and shutdown the page cache subsystem */
17167SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
17168SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
17169
17170/* Page cache buffer management:
17171** These routines implement SQLITE_CONFIG_PAGECACHE.
17172*/
17173SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
17174
17175/* Create a new pager cache.
17176** Under memory stress, invoke xStress to try to make pages clean.
17177** Only clean and unpinned pages can be reclaimed.
17178*/
17179SQLITE_PRIVATE int sqlite3PcacheOpen(
17180  int szPage,                    /* Size of every page */
17181  int szExtra,                   /* Extra space associated with each page */
17182  int bPurgeable,                /* True if pages are on backing store */
17183  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
17184  void *pStress,                 /* Argument to xStress */
17185  PCache *pToInit                /* Preallocated space for the PCache */
17186);
17187
17188/* Modify the page-size after the cache has been created. */
17189SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
17190
17191/* Return the size in bytes of a PCache object.  Used to preallocate
17192** storage space.
17193*/
17194SQLITE_PRIVATE int sqlite3PcacheSize(void);
17195
17196/* One release per successful fetch.  Page is pinned until released.
17197** Reference counted.
17198*/
17199SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
17200SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
17201SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
17202SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
17203
17204SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
17205SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
17206SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
17207SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
17208SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
17209
17210/* Change a page number.  Used by incr-vacuum. */
17211SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
17212
17213/* Remove all pages with pgno>x.  Reset the cache if x==0 */
17214SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
17215
17216/* Get a list of all dirty pages in the cache, sorted by page number */
17217SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
17218
17219/* Reset and close the cache object */
17220SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
17221
17222/* Clear flags from pages of the page cache */
17223SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
17224
17225/* Discard the contents of the cache */
17226SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
17227
17228/* Return the total number of outstanding page references */
17229SQLITE_PRIVATE i64 sqlite3PcacheRefCount(PCache*);
17230
17231/* Increment the reference count of an existing page */
17232SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
17233
17234SQLITE_PRIVATE i64 sqlite3PcachePageRefcount(PgHdr*);
17235
17236/* Return the total number of pages stored in the cache */
17237SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
17238
17239#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
17240/* Iterate through all dirty pages currently stored in the cache. This
17241** interface is only available if SQLITE_CHECK_PAGES is defined when the
17242** library is built.
17243*/
17244SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
17245#endif
17246
17247#if defined(SQLITE_DEBUG)
17248/* Check invariants on a PgHdr object */
17249SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
17250#endif
17251
17252/* Set and get the suggested cache-size for the specified pager-cache.
17253**
17254** If no global maximum is configured, then the system attempts to limit
17255** the total number of pages cached by purgeable pager-caches to the sum
17256** of the suggested cache-sizes.
17257*/
17258SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
17259#ifdef SQLITE_TEST
17260SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
17261#endif
17262
17263/* Set or get the suggested spill-size for the specified pager-cache.
17264**
17265** The spill-size is the minimum number of pages in cache before the cache
17266** will attempt to spill dirty pages by calling xStress.
17267*/
17268SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
17269
17270/* Free up as much memory as possible from the page cache */
17271SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
17272
17273#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17274/* Try to return memory used by the pcache module to the main memory heap */
17275SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
17276#endif
17277
17278#ifdef SQLITE_TEST
17279SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
17280#endif
17281
17282SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
17283
17284/* Return the header size */
17285SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
17286SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
17287
17288/* Number of dirty pages as a percentage of the configured cache size */
17289SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
17290
17291#ifdef SQLITE_DIRECT_OVERFLOW_READ
17292SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
17293#endif
17294
17295#endif /* _PCACHE_H_ */
17296
17297/************** End of pcache.h **********************************************/
17298/************** Continuing where we left off in sqliteInt.h ******************/
17299/************** Include mutex.h in the middle of sqliteInt.h *****************/
17300/************** Begin file mutex.h *******************************************/
17301/*
17302** 2007 August 28
17303**
17304** The author disclaims copyright to this source code.  In place of
17305** a legal notice, here is a blessing:
17306**
17307**    May you do good and not evil.
17308**    May you find forgiveness for yourself and forgive others.
17309**    May you share freely, never taking more than you give.
17310**
17311*************************************************************************
17312**
17313** This file contains the common header for all mutex implementations.
17314** The sqliteInt.h header #includes this file so that it is available
17315** to all source files.  We break it out in an effort to keep the code
17316** better organized.
17317**
17318** NOTE:  source files should *not* #include this header file directly.
17319** Source files should #include the sqliteInt.h file and let that file
17320** include this one indirectly.
17321*/
17322
17323
17324/*
17325** Figure out what version of the code to use.  The choices are
17326**
17327**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
17328**                             mutexes implementation cannot be overridden
17329**                             at start-time.
17330**
17331**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
17332**                             mutual exclusion is provided.  But this
17333**                             implementation can be overridden at
17334**                             start-time.
17335**
17336**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
17337**
17338**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
17339*/
17340#if !SQLITE_THREADSAFE
17341# define SQLITE_MUTEX_OMIT
17342#endif
17343#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
17344#  if SQLITE_OS_UNIX
17345#    define SQLITE_MUTEX_PTHREADS
17346#  elif SQLITE_OS_WIN
17347#    define SQLITE_MUTEX_W32
17348#  else
17349#    define SQLITE_MUTEX_NOOP
17350#  endif
17351#endif
17352
17353#ifdef SQLITE_MUTEX_OMIT
17354/*
17355** If this is a no-op implementation, implement everything as macros.
17356*/
17357#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
17358#define sqlite3_mutex_free(X)
17359#define sqlite3_mutex_enter(X)
17360#define sqlite3_mutex_try(X)      SQLITE_OK
17361#define sqlite3_mutex_leave(X)
17362#define sqlite3_mutex_held(X)     ((void)(X),1)
17363#define sqlite3_mutex_notheld(X)  ((void)(X),1)
17364#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
17365#define sqlite3MutexInit()        SQLITE_OK
17366#define sqlite3MutexEnd()
17367#define MUTEX_LOGIC(X)
17368#else
17369#define MUTEX_LOGIC(X)            X
17370SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
17371#endif /* defined(SQLITE_MUTEX_OMIT) */
17372
17373/************** End of mutex.h ***********************************************/
17374/************** Continuing where we left off in sqliteInt.h ******************/
17375
17376/* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
17377** synchronous setting to EXTRA.  It is no longer supported.
17378*/
17379#ifdef SQLITE_EXTRA_DURABLE
17380# warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
17381# define SQLITE_DEFAULT_SYNCHRONOUS 3
17382#endif
17383
17384/*
17385** Default synchronous levels.
17386**
17387** Note that (for historical reasons) the PAGER_SYNCHRONOUS_* macros differ
17388** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
17389**
17390**           PAGER_SYNCHRONOUS       DEFAULT_SYNCHRONOUS
17391**   OFF           1                         0
17392**   NORMAL        2                         1
17393**   FULL          3                         2
17394**   EXTRA         4                         3
17395**
17396** The "PRAGMA synchronous" statement also uses the zero-based numbers.
17397** In other words, the zero-based numbers are used for all external interfaces
17398** and the one-based values are used internally.
17399*/
17400#ifndef SQLITE_DEFAULT_SYNCHRONOUS
17401# define SQLITE_DEFAULT_SYNCHRONOUS 2
17402#endif
17403#ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
17404# define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
17405#endif
17406
17407/*
17408** Each database file to be accessed by the system is an instance
17409** of the following structure.  There are normally two of these structures
17410** in the sqlite.aDb[] array.  aDb[0] is the main database file and
17411** aDb[1] is the database file used to hold temporary tables.  Additional
17412** databases may be attached.
17413*/
17414struct Db {
17415  char *zDbSName;      /* Name of this database. (schema name, not filename) */
17416  Btree *pBt;          /* The B*Tree structure for this database file */
17417  u8 safety_level;     /* How aggressive at syncing data to disk */
17418  u8 bSyncSet;         /* True if "PRAGMA synchronous=N" has been run */
17419  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
17420};
17421
17422/*
17423** An instance of the following structure stores a database schema.
17424**
17425** Most Schema objects are associated with a Btree.  The exception is
17426** the Schema for the TEMP database (sqlite3.aDb[1]) which is free-standing.
17427** In shared cache mode, a single Schema object can be shared by multiple
17428** Btrees that refer to the same underlying BtShared object.
17429**
17430** Schema objects are automatically deallocated when the last Btree that
17431** references them is destroyed.   The TEMP Schema is manually freed by
17432** sqlite3_close().
17433*
17434** A thread must be holding a mutex on the corresponding Btree in order
17435** to access Schema content.  This implies that the thread must also be
17436** holding a mutex on the sqlite3 connection pointer that owns the Btree.
17437** For a TEMP Schema, only the connection mutex is required.
17438*/
17439struct Schema {
17440  int schema_cookie;   /* Database schema version number for this file */
17441  int iGeneration;     /* Generation counter.  Incremented with each change */
17442  Hash tblHash;        /* All tables indexed by name */
17443  Hash idxHash;        /* All (named) indices indexed by name */
17444  Hash trigHash;       /* All triggers indexed by name */
17445  Hash fkeyHash;       /* All foreign keys by referenced table name */
17446  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
17447  u8 file_format;      /* Schema format version for this file */
17448  u8 enc;              /* Text encoding used by this database */
17449  u16 schemaFlags;     /* Flags associated with this schema */
17450  int cache_size;      /* Number of pages to use in the cache */
17451};
17452
17453/*
17454** These macros can be used to test, set, or clear bits in the
17455** Db.pSchema->flags field.
17456*/
17457#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
17458#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
17459#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
17460#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
17461
17462/*
17463** Allowed values for the DB.pSchema->flags field.
17464**
17465** The DB_SchemaLoaded flag is set after the database schema has been
17466** read into internal hash tables.
17467**
17468** DB_UnresetViews means that one or more views have column names that
17469** have been filled out.  If the schema changes, these column names might
17470** changes and so the view will need to be reset.
17471*/
17472#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
17473#define DB_UnresetViews    0x0002  /* Some views have defined column names */
17474#define DB_ResetWanted     0x0008  /* Reset the schema when nSchemaLock==0 */
17475
17476/*
17477** The number of different kinds of things that can be limited
17478** using the sqlite3_limit() interface.
17479*/
17480#define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
17481
17482/*
17483** Lookaside malloc is a set of fixed-size buffers that can be used
17484** to satisfy small transient memory allocation requests for objects
17485** associated with a particular database connection.  The use of
17486** lookaside malloc provides a significant performance enhancement
17487** (approx 10%) by avoiding numerous malloc/free requests while parsing
17488** SQL statements.
17489**
17490** The Lookaside structure holds configuration information about the
17491** lookaside malloc subsystem.  Each available memory allocation in
17492** the lookaside subsystem is stored on a linked list of LookasideSlot
17493** objects.
17494**
17495** Lookaside allocations are only allowed for objects that are associated
17496** with a particular database connection.  Hence, schema information cannot
17497** be stored in lookaside because in shared cache mode the schema information
17498** is shared by multiple database connections.  Therefore, while parsing
17499** schema information, the Lookaside.bEnabled flag is cleared so that
17500** lookaside allocations are not used to construct the schema objects.
17501**
17502** New lookaside allocations are only allowed if bDisable==0.  When
17503** bDisable is greater than zero, sz is set to zero which effectively
17504** disables lookaside without adding a new test for the bDisable flag
17505** in a performance-critical path.  sz should be set by to szTrue whenever
17506** bDisable changes back to zero.
17507**
17508** Lookaside buffers are initially held on the pInit list.  As they are
17509** used and freed, they are added back to the pFree list.  New allocations
17510** come off of pFree first, then pInit as a fallback.  This dual-list
17511** allows use to compute a high-water mark - the maximum number of allocations
17512** outstanding at any point in the past - by subtracting the number of
17513** allocations on the pInit list from the total number of allocations.
17514**
17515** Enhancement on 2019-12-12:  Two-size-lookaside
17516** The default lookaside configuration is 100 slots of 1200 bytes each.
17517** The larger slot sizes are important for performance, but they waste
17518** a lot of space, as most lookaside allocations are less than 128 bytes.
17519** The two-size-lookaside enhancement breaks up the lookaside allocation
17520** into two pools:  One of 128-byte slots and the other of the default size
17521** (1200-byte) slots.   Allocations are filled from the small-pool first,
17522** failing over to the full-size pool if that does not work.  Thus more
17523** lookaside slots are available while also using less memory.
17524** This enhancement can be omitted by compiling with
17525** SQLITE_OMIT_TWOSIZE_LOOKASIDE.
17526*/
17527struct Lookaside {
17528  u32 bDisable;           /* Only operate the lookaside when zero */
17529  u16 sz;                 /* Size of each buffer in bytes */
17530  u16 szTrue;             /* True value of sz, even if disabled */
17531  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
17532  u32 nSlot;              /* Number of lookaside slots allocated */
17533  u32 anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
17534  LookasideSlot *pInit;   /* List of buffers not previously used */
17535  LookasideSlot *pFree;   /* List of available buffers */
17536#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
17537  LookasideSlot *pSmallInit; /* List of small buffers not previously used */
17538  LookasideSlot *pSmallFree; /* List of available small buffers */
17539  void *pMiddle;          /* First byte past end of full-size buffers and
17540                          ** the first byte of LOOKASIDE_SMALL buffers */
17541#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
17542  void *pStart;           /* First byte of available memory space */
17543  void *pEnd;             /* First byte past end of available space */
17544  void *pTrueEnd;         /* True value of pEnd, when db->pnBytesFreed!=0 */
17545};
17546struct LookasideSlot {
17547  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
17548};
17549
17550#define DisableLookaside  db->lookaside.bDisable++;db->lookaside.sz=0
17551#define EnableLookaside   db->lookaside.bDisable--;\
17552   db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue
17553
17554/* Size of the smaller allocations in two-size lookaside */
17555#ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
17556#  define LOOKASIDE_SMALL           0
17557#else
17558#  define LOOKASIDE_SMALL         128
17559#endif
17560
17561/*
17562** A hash table for built-in function definitions.  (Application-defined
17563** functions use a regular table table from hash.h.)
17564**
17565** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
17566** Collisions are on the FuncDef.u.pHash chain.  Use the SQLITE_FUNC_HASH()
17567** macro to compute a hash on the function name.
17568*/
17569#define SQLITE_FUNC_HASH_SZ 23
17570struct FuncDefHash {
17571  FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */
17572};
17573#define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)
17574
17575#if defined(SQLITE_USER_AUTHENTICATION)
17576# warning  "The SQLITE_USER_AUTHENTICATION extension is deprecated. \
17577 See ext/userauth/user-auth.txt for details."
17578#endif
17579#ifdef SQLITE_USER_AUTHENTICATION
17580/*
17581** Information held in the "sqlite3" database connection object and used
17582** to manage user authentication.
17583*/
17584typedef struct sqlite3_userauth sqlite3_userauth;
17585struct sqlite3_userauth {
17586  u8 authLevel;                 /* Current authentication level */
17587  int nAuthPW;                  /* Size of the zAuthPW in bytes */
17588  char *zAuthPW;                /* Password used to authenticate */
17589  char *zAuthUser;              /* User name used to authenticate */
17590};
17591
17592/* Allowed values for sqlite3_userauth.authLevel */
17593#define UAUTH_Unknown     0     /* Authentication not yet checked */
17594#define UAUTH_Fail        1     /* User authentication failed */
17595#define UAUTH_User        2     /* Authenticated as a normal user */
17596#define UAUTH_Admin       3     /* Authenticated as an administrator */
17597
17598/* Functions used only by user authorization logic */
17599SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
17600SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
17601SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
17602SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
17603
17604#endif /* SQLITE_USER_AUTHENTICATION */
17605
17606/*
17607** typedef for the authorization callback function.
17608*/
17609#ifdef SQLITE_USER_AUTHENTICATION
17610  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
17611                               const char*, const char*);
17612#else
17613  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
17614                               const char*);
17615#endif
17616
17617#ifndef SQLITE_OMIT_DEPRECATED
17618/* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
17619** in the style of sqlite3_trace()
17620*/
17621#define SQLITE_TRACE_LEGACY          0x40     /* Use the legacy xTrace */
17622#define SQLITE_TRACE_XPROFILE        0x80     /* Use the legacy xProfile */
17623#else
17624#define SQLITE_TRACE_LEGACY          0
17625#define SQLITE_TRACE_XPROFILE        0
17626#endif /* SQLITE_OMIT_DEPRECATED */
17627#define SQLITE_TRACE_NONLEGACY_MASK  0x0f     /* Normal flags */
17628
17629/*
17630** Maximum number of sqlite3.aDb[] entries.  This is the number of attached
17631** databases plus 2 for "main" and "temp".
17632*/
17633#define SQLITE_MAX_DB (SQLITE_MAX_ATTACHED+2)
17634
17635/*
17636** Each database connection is an instance of the following structure.
17637*/
17638struct sqlite3 {
17639  sqlite3_vfs *pVfs;            /* OS Interface */
17640  struct Vdbe *pVdbe;           /* List of active virtual machines */
17641  CollSeq *pDfltColl;           /* BINARY collseq for the database encoding */
17642  sqlite3_mutex *mutex;         /* Connection mutex */
17643  Db *aDb;                      /* All backends */
17644  int nDb;                      /* Number of backends currently in use */
17645  u32 mDbFlags;                 /* flags recording internal state */
17646  u64 flags;                    /* flags settable by pragmas. See below */
17647  i64 lastRowid;                /* ROWID of most recent insert (see above) */
17648  i64 szMmap;                   /* Default mmap_size setting */
17649  u32 nSchemaLock;              /* Do not reset the schema when non-zero */
17650  unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
17651  int errCode;                  /* Most recent error code (SQLITE_*) */
17652  int errByteOffset;            /* Byte offset of error in SQL statement */
17653  int errMask;                  /* & result codes with this before returning */
17654  int iSysErrno;                /* Errno value from last system error */
17655  u32 dbOptFlags;               /* Flags to enable/disable optimizations */
17656  u8 enc;                       /* Text encoding */
17657  u8 autoCommit;                /* The auto-commit flag. */
17658  u8 temp_store;                /* 1: file 2: memory 0: default */
17659  u8 mallocFailed;              /* True if we have seen a malloc failure */
17660  u8 bBenignMalloc;             /* Do not require OOMs if true */
17661  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
17662  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
17663  u8 suppressErr;               /* Do not issue error messages if true */
17664  u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
17665  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
17666  u8 mTrace;                    /* zero or more SQLITE_TRACE flags */
17667  u8 noSharedCache;             /* True if no shared-cache backends */
17668  u8 nSqlExec;                  /* Number of pending OP_SqlExec opcodes */
17669  u8 eOpenState;                /* Current condition of the connection */
17670  int nextPagesize;             /* Pagesize after VACUUM if >0 */
17671  i64 nChange;                  /* Value returned by sqlite3_changes() */
17672  i64 nTotalChange;             /* Value returned by sqlite3_total_changes() */
17673  int aLimit[SQLITE_N_LIMIT];   /* Limits */
17674  int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
17675  struct sqlite3InitInfo {      /* Information used during initialization */
17676    Pgno newTnum;               /* Rootpage of table being initialized */
17677    u8 iDb;                     /* Which db file is being initialized */
17678    u8 busy;                    /* TRUE if currently initializing */
17679    unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
17680    unsigned imposterTable : 1; /* Building an imposter table */
17681    unsigned reopenMemdb : 1;   /* ATTACH is really a reopen using MemDB */
17682    const char **azInit;        /* "type", "name", and "tbl_name" columns */
17683  } init;
17684  int nVdbeActive;              /* Number of VDBEs currently running */
17685  int nVdbeRead;                /* Number of active VDBEs that read or write */
17686  int nVdbeWrite;               /* Number of active VDBEs that read and write */
17687  int nVdbeExec;                /* Number of nested calls to VdbeExec() */
17688  int nVDestroy;                /* Number of active OP_VDestroy operations */
17689  int nExtension;               /* Number of loaded extensions */
17690  void **aExtension;            /* Array of shared library handles */
17691  union {
17692    void (*xLegacy)(void*,const char*);   /* mTrace==SQLITE_TRACE_LEGACY */
17693    int (*xV2)(u32,void*,void*,void*);    /* All other mTrace values */
17694  } trace;
17695  void *pTraceArg;                        /* Argument to the trace function */
17696#ifndef SQLITE_OMIT_DEPRECATED
17697  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
17698  void *pProfileArg;                        /* Argument to profile function */
17699#endif
17700  void *pCommitArg;                 /* Argument to xCommitCallback() */
17701  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
17702  void *pRollbackArg;               /* Argument to xRollbackCallback() */
17703  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
17704  void *pUpdateArg;
17705  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
17706  void *pAutovacPagesArg;           /* Client argument to autovac_pages */
17707  void (*xAutovacDestr)(void*);     /* Destructor for pAutovacPAgesArg */
17708  unsigned int (*xAutovacPages)(void*,const char*,u32,u32,u32);
17709  Parse *pParse;                /* Current parse */
17710#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
17711  void *pPreUpdateArg;          /* First argument to xPreUpdateCallback */
17712  void (*xPreUpdateCallback)(   /* Registered using sqlite3_preupdate_hook() */
17713    void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
17714  );
17715  PreUpdate *pPreUpdate;        /* Context for active pre-update callback */
17716#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
17717#ifndef SQLITE_OMIT_WAL
17718  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
17719  void *pWalArg;
17720#endif
17721  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
17722  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
17723  void *pCollNeededArg;
17724  sqlite3_value *pErr;          /* Most recent error message */
17725  union {
17726    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
17727    double notUsed1;            /* Spacer */
17728  } u1;
17729  Lookaside lookaside;          /* Lookaside malloc configuration */
17730#ifndef SQLITE_OMIT_AUTHORIZATION
17731  sqlite3_xauth xAuth;          /* Access authorization function */
17732  void *pAuthArg;               /* 1st argument to the access auth function */
17733#endif
17734#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
17735  int (*xProgress)(void *);     /* The progress callback */
17736  void *pProgressArg;           /* Argument to the progress callback */
17737  unsigned nProgressOps;        /* Number of opcodes for progress callback */
17738#endif
17739#ifndef SQLITE_OMIT_VIRTUALTABLE
17740  int nVTrans;                  /* Allocated size of aVTrans */
17741  Hash aModule;                 /* populated by sqlite3_create_module() */
17742  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
17743  VTable **aVTrans;             /* Virtual tables with open transactions */
17744  VTable *pDisconnect;          /* Disconnect these in next sqlite3_prepare() */
17745#endif
17746  Hash aFunc;                   /* Hash table of connection functions */
17747  Hash aCollSeq;                /* All collating sequences */
17748  BusyHandler busyHandler;      /* Busy callback */
17749  Db aDbStatic[2];              /* Static space for the 2 default backends */
17750  Savepoint *pSavepoint;        /* List of active savepoints */
17751  int nAnalysisLimit;           /* Number of index rows to ANALYZE */
17752  int busyTimeout;              /* Busy handler timeout, in msec */
17753  int nSavepoint;               /* Number of non-transaction savepoints */
17754  int nStatement;               /* Number of nested statement-transactions  */
17755  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
17756  i64 nDeferredImmCons;         /* Net deferred immediate constraints */
17757  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
17758  DbClientData *pDbData;        /* sqlite3_set_clientdata() content */
17759#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
17760  /* The following variables are all protected by the STATIC_MAIN
17761  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
17762  **
17763  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
17764  ** unlock so that it can proceed.
17765  **
17766  ** When X.pBlockingConnection==Y, that means that something that X tried
17767  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
17768  ** held by Y.
17769  */
17770  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
17771  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
17772  void *pUnlockArg;                     /* Argument to xUnlockNotify */
17773  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
17774  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
17775#endif
17776#ifdef SQLITE_USER_AUTHENTICATION
17777  sqlite3_userauth auth;        /* User authentication information */
17778#endif
17779};
17780
17781/*
17782** A macro to discover the encoding of a database.
17783*/
17784#define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
17785#define ENC(db)        ((db)->enc)
17786
17787/*
17788** A u64 constant where the lower 32 bits are all zeros.  Only the
17789** upper 32 bits are included in the argument.  Necessary because some
17790** C-compilers still do not accept LL integer literals.
17791*/
17792#define HI(X)  ((u64)(X)<<32)
17793
17794/*
17795** Possible values for the sqlite3.flags.
17796**
17797** Value constraints (enforced via assert()):
17798**      SQLITE_FullFSync     == PAGER_FULLFSYNC
17799**      SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
17800**      SQLITE_CacheSpill    == PAGER_CACHE_SPILL
17801*/
17802#define SQLITE_WriteSchema    0x00000001  /* OK to update SQLITE_SCHEMA */
17803#define SQLITE_LegacyFileFmt  0x00000002  /* Create new databases in format 1 */
17804#define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
17805#define SQLITE_FullFSync      0x00000008  /* Use full fsync on the backend */
17806#define SQLITE_CkptFullFSync  0x00000010  /* Use full fsync for checkpoint */
17807#define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */
17808#define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
17809#define SQLITE_TrustedSchema  0x00000080  /* Allow unsafe functions and
17810                                          ** vtabs in the schema definition */
17811#define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
17812                                          /*   result set is empty */
17813#define SQLITE_IgnoreChecks   0x00000200  /* Do not enforce check constraints */
17814#define SQLITE_StmtScanStatus 0x00000400  /* Enable stmt_scanstats() counters */
17815#define SQLITE_NoCkptOnClose  0x00000800  /* No checkpoint on close()/DETACH */
17816#define SQLITE_ReverseOrder   0x00001000  /* Reverse unordered SELECTs */
17817#define SQLITE_RecTriggers    0x00002000  /* Enable recursive triggers */
17818#define SQLITE_ForeignKeys    0x00004000  /* Enforce foreign key constraints  */
17819#define SQLITE_AutoIndex      0x00008000  /* Enable automatic indexes */
17820#define SQLITE_LoadExtension  0x00010000  /* Enable load_extension */
17821#define SQLITE_LoadExtFunc    0x00020000  /* Enable load_extension() SQL func */
17822#define SQLITE_EnableTrigger  0x00040000  /* True to enable triggers */
17823#define SQLITE_DeferFKs       0x00080000  /* Defer all FK constraints */
17824#define SQLITE_QueryOnly      0x00100000  /* Disable database changes */
17825#define SQLITE_CellSizeCk     0x00200000  /* Check btree cell sizes on load */
17826#define SQLITE_Fts3Tokenizer  0x00400000  /* Enable fts3_tokenizer(2) */
17827#define SQLITE_EnableQPSG     0x00800000  /* Query Planner Stability Guarantee*/
17828#define SQLITE_TriggerEQP     0x01000000  /* Show trigger EXPLAIN QUERY PLAN */
17829#define SQLITE_ResetDatabase  0x02000000  /* Reset the database */
17830#define SQLITE_LegacyAlter    0x04000000  /* Legacy ALTER TABLE behaviour */
17831#define SQLITE_NoSchemaError  0x08000000  /* Do not report schema parse errors*/
17832#define SQLITE_Defensive      0x10000000  /* Input SQL is likely hostile */
17833#define SQLITE_DqsDDL         0x20000000  /* dbl-quoted strings allowed in DDL*/
17834#define SQLITE_DqsDML         0x40000000  /* dbl-quoted strings allowed in DML*/
17835#define SQLITE_EnableView     0x80000000  /* Enable the use of views */
17836#define SQLITE_CountRows      HI(0x00001) /* Count rows changed by INSERT, */
17837                                          /*   DELETE, or UPDATE and return */
17838                                          /*   the count using a callback. */
17839#define SQLITE_CorruptRdOnly  HI(0x00002) /* Prohibit writes due to error */
17840#define SQLITE_ReadUncommit   HI(0x00004) /* READ UNCOMMITTED in shared-cache */
17841#define SQLITE_FkNoAction     HI(0x00008) /* Treat all FK as NO ACTION */
17842
17843/* Flags used only if debugging */
17844#ifdef SQLITE_DEBUG
17845#define SQLITE_SqlTrace       HI(0x0100000) /* Debug print SQL as it executes */
17846#define SQLITE_VdbeListing    HI(0x0200000) /* Debug listings of VDBE progs */
17847#define SQLITE_VdbeTrace      HI(0x0400000) /* True to trace VDBE execution */
17848#define SQLITE_VdbeAddopTrace HI(0x0800000) /* Trace sqlite3VdbeAddOp() calls */
17849#define SQLITE_VdbeEQP        HI(0x1000000) /* Debug EXPLAIN QUERY PLAN */
17850#define SQLITE_ParserTrace    HI(0x2000000) /* PRAGMA parser_trace=ON */
17851#endif
17852
17853/*
17854** Allowed values for sqlite3.mDbFlags
17855*/
17856#define DBFLAG_SchemaChange   0x0001  /* Uncommitted Hash table changes */
17857#define DBFLAG_PreferBuiltin  0x0002  /* Preference to built-in funcs */
17858#define DBFLAG_Vacuum         0x0004  /* Currently in a VACUUM */
17859#define DBFLAG_VacuumInto     0x0008  /* Currently running VACUUM INTO */
17860#define DBFLAG_SchemaKnownOk  0x0010  /* Schema is known to be valid */
17861#define DBFLAG_InternalFunc   0x0020  /* Allow use of internal functions */
17862#define DBFLAG_EncodingFixed  0x0040  /* No longer possible to change enc. */
17863
17864/*
17865** Bits of the sqlite3.dbOptFlags field that are used by the
17866** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
17867** selectively disable various optimizations.
17868*/
17869#define SQLITE_QueryFlattener 0x00000001 /* Query flattening */
17870#define SQLITE_WindowFunc     0x00000002 /* Use xInverse for window functions */
17871#define SQLITE_GroupByOrder   0x00000004 /* GROUPBY cover of ORDERBY */
17872#define SQLITE_FactorOutConst 0x00000008 /* Constant factoring */
17873#define SQLITE_DistinctOpt    0x00000010 /* DISTINCT using indexes */
17874#define SQLITE_CoverIdxScan   0x00000020 /* Covering index scans */
17875#define SQLITE_OrderByIdxJoin 0x00000040 /* ORDER BY of joins via index */
17876#define SQLITE_Transitive     0x00000080 /* Transitive constraints */
17877#define SQLITE_OmitNoopJoin   0x00000100 /* Omit unused tables in joins */
17878#define SQLITE_CountOfView    0x00000200 /* The count-of-view optimization */
17879#define SQLITE_CursorHints    0x00000400 /* Add OP_CursorHint opcodes */
17880#define SQLITE_Stat4          0x00000800 /* Use STAT4 data */
17881   /* TH3 expects this value  ^^^^^^^^^^ to be 0x0000800. Don't change it */
17882#define SQLITE_PushDown       0x00001000 /* WHERE-clause push-down opt */
17883#define SQLITE_SimplifyJoin   0x00002000 /* Convert LEFT JOIN to JOIN */
17884#define SQLITE_SkipScan       0x00004000 /* Skip-scans */
17885#define SQLITE_PropagateConst 0x00008000 /* The constant propagation opt */
17886#define SQLITE_MinMaxOpt      0x00010000 /* The min/max optimization */
17887#define SQLITE_SeekScan       0x00020000 /* The OP_SeekScan optimization */
17888#define SQLITE_OmitOrderBy    0x00040000 /* Omit pointless ORDER BY */
17889   /* TH3 expects this value  ^^^^^^^^^^ to be 0x40000. Coordinate any change */
17890#define SQLITE_BloomFilter    0x00080000 /* Use a Bloom filter on searches */
17891#define SQLITE_BloomPulldown  0x00100000 /* Run Bloom filters early */
17892#define SQLITE_BalancedMerge  0x00200000 /* Balance multi-way merges */
17893#define SQLITE_ReleaseReg     0x00400000 /* Use OP_ReleaseReg for testing */
17894#define SQLITE_FlttnUnionAll  0x00800000 /* Disable the UNION ALL flattener */
17895   /* TH3 expects this value  ^^^^^^^^^^ See flatten04.test */
17896#define SQLITE_IndexedExpr    0x01000000 /* Pull exprs from index when able */
17897#define SQLITE_Coroutines     0x02000000 /* Co-routines for subqueries */
17898#define SQLITE_NullUnusedCols 0x04000000 /* NULL unused columns in subqueries */
17899#define SQLITE_OnePass        0x08000000 /* Single-pass DELETE and UPDATE */
17900#define SQLITE_AllOpts        0xffffffff /* All optimizations */
17901
17902/*
17903** Macros for testing whether or not optimizations are enabled or disabled.
17904*/
17905#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
17906#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
17907
17908/*
17909** Return true if it OK to factor constant expressions into the initialization
17910** code. The argument is a Parse object for the code generator.
17911*/
17912#define ConstFactorOk(P) ((P)->okConstFactor)
17913
17914/* Possible values for the sqlite3.eOpenState field.
17915** The numbers are randomly selected such that a minimum of three bits must
17916** change to convert any number to another or to zero
17917*/
17918#define SQLITE_STATE_OPEN     0x76  /* Database is open */
17919#define SQLITE_STATE_CLOSED   0xce  /* Database is closed */
17920#define SQLITE_STATE_SICK     0xba  /* Error and awaiting close */
17921#define SQLITE_STATE_BUSY     0x6d  /* Database currently in use */
17922#define SQLITE_STATE_ERROR    0xd5  /* An SQLITE_MISUSE error occurred */
17923#define SQLITE_STATE_ZOMBIE   0xa7  /* Close with last statement close */
17924
17925/*
17926** Each SQL function is defined by an instance of the following
17927** structure.  For global built-in functions (ex: substr(), max(), count())
17928** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
17929** For per-connection application-defined functions, a pointer to this
17930** structure is held in the db->aHash hash table.
17931**
17932** The u.pHash field is used by the global built-ins.  The u.pDestructor
17933** field is used by per-connection app-def functions.
17934*/
17935struct FuncDef {
17936  i8 nArg;             /* Number of arguments.  -1 means unlimited */
17937  u32 funcFlags;       /* Some combination of SQLITE_FUNC_* */
17938  void *pUserData;     /* User data parameter */
17939  FuncDef *pNext;      /* Next function with same name */
17940  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
17941  void (*xFinalize)(sqlite3_context*);                  /* Agg finalizer */
17942  void (*xValue)(sqlite3_context*);                     /* Current agg value */
17943  void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
17944  const char *zName;   /* SQL name of the function. */
17945  union {
17946    FuncDef *pHash;      /* Next with a different name but the same hash */
17947    FuncDestructor *pDestructor;   /* Reference counted destructor function */
17948  } u; /* pHash if SQLITE_FUNC_BUILTIN, pDestructor otherwise */
17949};
17950
17951/*
17952** This structure encapsulates a user-function destructor callback (as
17953** configured using create_function_v2()) and a reference counter. When
17954** create_function_v2() is called to create a function with a destructor,
17955** a single object of this type is allocated. FuncDestructor.nRef is set to
17956** the number of FuncDef objects created (either 1 or 3, depending on whether
17957** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
17958** member of each of the new FuncDef objects is set to point to the allocated
17959** FuncDestructor.
17960**
17961** Thereafter, when one of the FuncDef objects is deleted, the reference
17962** count on this object is decremented. When it reaches 0, the destructor
17963** is invoked and the FuncDestructor structure freed.
17964*/
17965struct FuncDestructor {
17966  int nRef;
17967  void (*xDestroy)(void *);
17968  void *pUserData;
17969};
17970
17971/*
17972** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
17973** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  And
17974** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC.  There
17975** are assert() statements in the code to verify this.
17976**
17977** Value constraints (enforced via assert()):
17978**     SQLITE_FUNC_MINMAX      ==  NC_MinMaxAgg      == SF_MinMaxAgg
17979**     SQLITE_FUNC_ANYORDER    ==  NC_OrderAgg       == SF_OrderByReqd
17980**     SQLITE_FUNC_LENGTH      ==  OPFLAG_LENGTHARG
17981**     SQLITE_FUNC_TYPEOF      ==  OPFLAG_TYPEOFARG
17982**     SQLITE_FUNC_BYTELEN     ==  OPFLAG_BYTELENARG
17983**     SQLITE_FUNC_CONSTANT    ==  SQLITE_DETERMINISTIC from the API
17984**     SQLITE_FUNC_DIRECT      ==  SQLITE_DIRECTONLY from the API
17985**     SQLITE_FUNC_UNSAFE      ==  SQLITE_INNOCUOUS  -- opposite meanings!!!
17986**     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API
17987**
17988** Note that even though SQLITE_FUNC_UNSAFE and SQLITE_INNOCUOUS have the
17989** same bit value, their meanings are inverted.  SQLITE_FUNC_UNSAFE is
17990** used internally and if set means that the function has side effects.
17991** SQLITE_INNOCUOUS is used by application code and means "not unsafe".
17992** See multiple instances of tag-20230109-1.
17993*/
17994#define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
17995#define SQLITE_FUNC_LIKE     0x0004 /* Candidate for the LIKE optimization */
17996#define SQLITE_FUNC_CASE     0x0008 /* Case-sensitive LIKE-type function */
17997#define SQLITE_FUNC_EPHEM    0x0010 /* Ephemeral.  Delete with VDBE */
17998#define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
17999#define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */
18000#define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */
18001#define SQLITE_FUNC_BYTELEN  0x00c0 /* Built-in octet_length() function */
18002#define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */
18003/*                           0x0200 -- available for reuse */
18004#define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
18005#define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
18006#define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */
18007#define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
18008                                    ** single query - might change over time */
18009#define SQLITE_FUNC_TEST     0x4000 /* Built-in testing functions */
18010#define SQLITE_FUNC_RUNONLY  0x8000 /* Cannot be used by valueFromFunction */
18011#define SQLITE_FUNC_WINDOW   0x00010000 /* Built-in window-only function */
18012#define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
18013#define SQLITE_FUNC_DIRECT   0x00080000 /* Not for use in TRIGGERs or VIEWs */
18014/* SQLITE_SUBTYPE            0x00100000 // Consumer of subtypes */
18015#define SQLITE_FUNC_UNSAFE   0x00200000 /* Function has side effects */
18016#define SQLITE_FUNC_INLINE   0x00400000 /* Functions implemented in-line */
18017#define SQLITE_FUNC_BUILTIN  0x00800000 /* This is a built-in function */
18018/*  SQLITE_RESULT_SUBTYPE    0x01000000 // Generator of subtypes */
18019#define SQLITE_FUNC_ANYORDER 0x08000000 /* count/min/max aggregate */
18020
18021/* Identifier numbers for each in-line function */
18022#define INLINEFUNC_coalesce             0
18023#define INLINEFUNC_implies_nonnull_row  1
18024#define INLINEFUNC_expr_implies_expr    2
18025#define INLINEFUNC_expr_compare         3
18026#define INLINEFUNC_affinity             4
18027#define INLINEFUNC_iif                  5
18028#define INLINEFUNC_sqlite_offset        6
18029#define INLINEFUNC_unlikely            99  /* Default case */
18030
18031/*
18032** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
18033** used to create the initializers for the FuncDef structures.
18034**
18035**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
18036**     Used to create a scalar function definition of a function zName
18037**     implemented by C function xFunc that accepts nArg arguments. The
18038**     value passed as iArg is cast to a (void*) and made available
18039**     as the user-data (sqlite3_user_data()) for the function. If
18040**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
18041**
18042**   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
18043**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
18044**
18045**   SFUNCTION(zName, nArg, iArg, bNC, xFunc)
18046**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
18047**     adds the SQLITE_DIRECTONLY flag.
18048**
18049**   INLINE_FUNC(zName, nArg, iFuncId, mFlags)
18050**     zName is the name of a function that is implemented by in-line
18051**     byte code rather than by the usual callbacks. The iFuncId
18052**     parameter determines the function id.  The mFlags parameter is
18053**     optional SQLITE_FUNC_ flags for this function.
18054**
18055**   TEST_FUNC(zName, nArg, iFuncId, mFlags)
18056**     zName is the name of a test-only function implemented by in-line
18057**     byte code rather than by the usual callbacks. The iFuncId
18058**     parameter determines the function id.  The mFlags parameter is
18059**     optional SQLITE_FUNC_ flags for this function.
18060**
18061**   DFUNCTION(zName, nArg, iArg, bNC, xFunc)
18062**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
18063**     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions
18064**     and functions like sqlite_version() that can change, but not during
18065**     a single query.  The iArg is ignored.  The user-data is always set
18066**     to a NULL pointer.  The bNC parameter is not used.
18067**
18068**   MFUNCTION(zName, nArg, xPtr, xFunc)
18069**     For math-library functions.  xPtr is an arbitrary pointer.
18070**
18071**   PURE_DATE(zName, nArg, iArg, bNC, xFunc)
18072**     Used for "pure" date/time functions, this macro is like DFUNCTION
18073**     except that it does set the SQLITE_FUNC_CONSTANT flags.  iArg is
18074**     ignored and the user-data for these functions is set to an
18075**     arbitrary non-NULL pointer.  The bNC parameter is not used.
18076**
18077**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
18078**     Used to create an aggregate function definition implemented by
18079**     the C functions xStep and xFinal. The first four parameters
18080**     are interpreted in the same way as the first 4 parameters to
18081**     FUNCTION().
18082**
18083**   WAGGREGATE(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
18084**     Used to create an aggregate function definition implemented by
18085**     the C functions xStep and xFinal. The first four parameters
18086**     are interpreted in the same way as the first 4 parameters to
18087**     FUNCTION().
18088**
18089**   LIKEFUNC(zName, nArg, pArg, flags)
18090**     Used to create a scalar function definition of a function zName
18091**     that accepts nArg arguments and is implemented by a call to C
18092**     function likeFunc. Argument pArg is cast to a (void *) and made
18093**     available as the function user-data (sqlite3_user_data()). The
18094**     FuncDef.flags variable is set to the value passed as the flags
18095**     parameter.
18096*/
18097#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
18098  {nArg, SQLITE_FUNC_BUILTIN|\
18099   SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
18100   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
18101#define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
18102  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
18103   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
18104#define SFUNCTION(zName, nArg, iArg, bNC, xFunc) \
18105  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \
18106   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
18107#define MFUNCTION(zName, nArg, xPtr, xFunc) \
18108  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8, \
18109   xPtr, 0, xFunc, 0, 0, 0, #zName, {0} }
18110#define JFUNCTION(zName, nArg, bUseCache, bWS, bRS, bJsonB, iArg, xFunc) \
18111  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_DETERMINISTIC|SQLITE_FUNC_CONSTANT|\
18112   SQLITE_UTF8|((bUseCache)*SQLITE_FUNC_RUNONLY)|\
18113   ((bRS)*SQLITE_SUBTYPE)|((bWS)*SQLITE_RESULT_SUBTYPE), \
18114   SQLITE_INT_TO_PTR(iArg|((bJsonB)*JSON_BLOB)),0,xFunc,0, 0, 0, #zName, {0} }
18115#define INLINE_FUNC(zName, nArg, iArg, mFlags) \
18116  {nArg, SQLITE_FUNC_BUILTIN|\
18117   SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
18118   SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
18119#define TEST_FUNC(zName, nArg, iArg, mFlags) \
18120  {nArg, SQLITE_FUNC_BUILTIN|\
18121         SQLITE_UTF8|SQLITE_FUNC_INTERNAL|SQLITE_FUNC_TEST| \
18122         SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
18123   SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
18124#define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
18125  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
18126   0, 0, xFunc, 0, 0, 0, #zName, {0} }
18127#define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
18128  {nArg, SQLITE_FUNC_BUILTIN|\
18129         SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
18130   (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }
18131#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
18132  {nArg, SQLITE_FUNC_BUILTIN|\
18133   SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
18134   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
18135#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
18136  {nArg, SQLITE_FUNC_BUILTIN|\
18137   SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
18138   pArg, 0, xFunc, 0, 0, 0, #zName, }
18139#define LIKEFUNC(zName, nArg, arg, flags) \
18140  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
18141   (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
18142#define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
18143  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
18144   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
18145#define INTERNAL_FUNCTION(zName, nArg, xFunc) \
18146  {nArg, SQLITE_FUNC_BUILTIN|\
18147   SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
18148   0, 0, xFunc, 0, 0, 0, #zName, {0} }
18149
18150
18151/*
18152** All current savepoints are stored in a linked list starting at
18153** sqlite3.pSavepoint. The first element in the list is the most recently
18154** opened savepoint. Savepoints are added to the list by the vdbe
18155** OP_Savepoint instruction.
18156*/
18157struct Savepoint {
18158  char *zName;                        /* Savepoint name (nul-terminated) */
18159  i64 nDeferredCons;                  /* Number of deferred fk violations */
18160  i64 nDeferredImmCons;               /* Number of deferred imm fk. */
18161  Savepoint *pNext;                   /* Parent savepoint (if any) */
18162};
18163
18164/*
18165** The following are used as the second parameter to sqlite3Savepoint(),
18166** and as the P1 argument to the OP_Savepoint instruction.
18167*/
18168#define SAVEPOINT_BEGIN      0
18169#define SAVEPOINT_RELEASE    1
18170#define SAVEPOINT_ROLLBACK   2
18171
18172
18173/*
18174** Each SQLite module (virtual table definition) is defined by an
18175** instance of the following structure, stored in the sqlite3.aModule
18176** hash table.
18177*/
18178struct Module {
18179  const sqlite3_module *pModule;       /* Callback pointers */
18180  const char *zName;                   /* Name passed to create_module() */
18181  int nRefModule;                      /* Number of pointers to this object */
18182  void *pAux;                          /* pAux passed to create_module() */
18183  void (*xDestroy)(void *);            /* Module destructor function */
18184  Table *pEpoTab;                      /* Eponymous table for this module */
18185};
18186
18187/*
18188** Information about each column of an SQL table is held in an instance
18189** of the Column structure, in the Table.aCol[] array.
18190**
18191** Definitions:
18192**
18193**   "table column index"     This is the index of the column in the
18194**                            Table.aCol[] array, and also the index of
18195**                            the column in the original CREATE TABLE stmt.
18196**
18197**   "storage column index"   This is the index of the column in the
18198**                            record BLOB generated by the OP_MakeRecord
18199**                            opcode.  The storage column index is less than
18200**                            or equal to the table column index.  It is
18201**                            equal if and only if there are no VIRTUAL
18202**                            columns to the left.
18203**
18204** Notes on zCnName:
18205** The zCnName field stores the name of the column, the datatype of the
18206** column, and the collating sequence for the column, in that order, all in
18207** a single allocation.  Each string is 0x00 terminated.  The datatype
18208** is only included if the COLFLAG_HASTYPE bit of colFlags is set and the
18209** collating sequence name is only included if the COLFLAG_HASCOLL bit is
18210** set.
18211*/
18212struct Column {
18213  char *zCnName;        /* Name of this column */
18214  unsigned notNull :4;  /* An OE_ code for handling a NOT NULL constraint */
18215  unsigned eCType :4;   /* One of the standard types */
18216  char affinity;        /* One of the SQLITE_AFF_... values */
18217  u8 szEst;             /* Est size of value in this column. sizeof(INT)==1 */
18218  u8 hName;             /* Column name hash for faster lookup */
18219  u16 iDflt;            /* 1-based index of DEFAULT.  0 means "none" */
18220  u16 colFlags;         /* Boolean properties.  See COLFLAG_ defines below */
18221};
18222
18223/* Allowed values for Column.eCType.
18224**
18225** Values must match entries in the global constant arrays
18226** sqlite3StdTypeLen[] and sqlite3StdType[].  Each value is one more
18227** than the offset into these arrays for the corresponding name.
18228** Adjust the SQLITE_N_STDTYPE value if adding or removing entries.
18229*/
18230#define COLTYPE_CUSTOM      0   /* Type appended to zName */
18231#define COLTYPE_ANY         1
18232#define COLTYPE_BLOB        2
18233#define COLTYPE_INT         3
18234#define COLTYPE_INTEGER     4
18235#define COLTYPE_REAL        5
18236#define COLTYPE_TEXT        6
18237#define SQLITE_N_STDTYPE    6  /* Number of standard types */
18238
18239/* Allowed values for Column.colFlags.
18240**
18241** Constraints:
18242**         TF_HasVirtual == COLFLAG_VIRTUAL
18243**         TF_HasStored  == COLFLAG_STORED
18244**         TF_HasHidden  == COLFLAG_HIDDEN
18245*/
18246#define COLFLAG_PRIMKEY   0x0001   /* Column is part of the primary key */
18247#define COLFLAG_HIDDEN    0x0002   /* A hidden column in a virtual table */
18248#define COLFLAG_HASTYPE   0x0004   /* Type name follows column name */
18249#define COLFLAG_UNIQUE    0x0008   /* Column def contains "UNIQUE" or "PK" */
18250#define COLFLAG_SORTERREF 0x0010   /* Use sorter-refs with this column */
18251#define COLFLAG_VIRTUAL   0x0020   /* GENERATED ALWAYS AS ... VIRTUAL */
18252#define COLFLAG_STORED    0x0040   /* GENERATED ALWAYS AS ... STORED */
18253#define COLFLAG_NOTAVAIL  0x0080   /* STORED column not yet calculated */
18254#define COLFLAG_BUSY      0x0100   /* Blocks recursion on GENERATED columns */
18255#define COLFLAG_HASCOLL   0x0200   /* Has collating sequence name in zCnName */
18256#define COLFLAG_NOEXPAND  0x0400   /* Omit this column when expanding "*" */
18257#define COLFLAG_GENERATED 0x0060   /* Combo: _STORED, _VIRTUAL */
18258#define COLFLAG_NOINSERT  0x0062   /* Combo: _HIDDEN, _STORED, _VIRTUAL */
18259
18260/*
18261** A "Collating Sequence" is defined by an instance of the following
18262** structure. Conceptually, a collating sequence consists of a name and
18263** a comparison routine that defines the order of that sequence.
18264**
18265** If CollSeq.xCmp is NULL, it means that the
18266** collating sequence is undefined.  Indices built on an undefined
18267** collating sequence may not be read or written.
18268*/
18269struct CollSeq {
18270  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
18271  u8 enc;               /* Text encoding handled by xCmp() */
18272  void *pUser;          /* First argument to xCmp() */
18273  int (*xCmp)(void*,int, const void*, int, const void*);
18274  void (*xDel)(void*);  /* Destructor for pUser */
18275};
18276
18277/*
18278** A sort order can be either ASC or DESC.
18279*/
18280#define SQLITE_SO_ASC       0  /* Sort in ascending order */
18281#define SQLITE_SO_DESC      1  /* Sort in ascending order */
18282#define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
18283
18284/*
18285** Column affinity types.
18286**
18287** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
18288** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
18289** the speed a little by numbering the values consecutively.
18290**
18291** But rather than start with 0 or 1, we begin with 'A'.  That way,
18292** when multiple affinity types are concatenated into a string and
18293** used as the P4 operand, they will be more readable.
18294**
18295** Note also that the numeric types are grouped together so that testing
18296** for a numeric type is a single comparison.  And the BLOB type is first.
18297*/
18298#define SQLITE_AFF_NONE     0x40  /* '@' */
18299#define SQLITE_AFF_BLOB     0x41  /* 'A' */
18300#define SQLITE_AFF_TEXT     0x42  /* 'B' */
18301#define SQLITE_AFF_NUMERIC  0x43  /* 'C' */
18302#define SQLITE_AFF_INTEGER  0x44  /* 'D' */
18303#define SQLITE_AFF_REAL     0x45  /* 'E' */
18304#define SQLITE_AFF_FLEXNUM  0x46  /* 'F' */
18305
18306#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
18307
18308/*
18309** The SQLITE_AFF_MASK values masks off the significant bits of an
18310** affinity value.
18311*/
18312#define SQLITE_AFF_MASK     0x47
18313
18314/*
18315** Additional bit values that can be ORed with an affinity without
18316** changing the affinity.
18317**
18318** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
18319** It causes an assert() to fire if either operand to a comparison
18320** operator is NULL.  It is added to certain comparison operators to
18321** prove that the operands are always NOT NULL.
18322*/
18323#define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
18324#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
18325#define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
18326
18327/*
18328** An object of this type is created for each virtual table present in
18329** the database schema.
18330**
18331** If the database schema is shared, then there is one instance of this
18332** structure for each database connection (sqlite3*) that uses the shared
18333** schema. This is because each database connection requires its own unique
18334** instance of the sqlite3_vtab* handle used to access the virtual table
18335** implementation. sqlite3_vtab* handles can not be shared between
18336** database connections, even when the rest of the in-memory database
18337** schema is shared, as the implementation often stores the database
18338** connection handle passed to it via the xConnect() or xCreate() method
18339** during initialization internally. This database connection handle may
18340** then be used by the virtual table implementation to access real tables
18341** within the database. So that they appear as part of the callers
18342** transaction, these accesses need to be made via the same database
18343** connection as that used to execute SQL operations on the virtual table.
18344**
18345** All VTable objects that correspond to a single table in a shared
18346** database schema are initially stored in a linked-list pointed to by
18347** the Table.pVTable member variable of the corresponding Table object.
18348** When an sqlite3_prepare() operation is required to access the virtual
18349** table, it searches the list for the VTable that corresponds to the
18350** database connection doing the preparing so as to use the correct
18351** sqlite3_vtab* handle in the compiled query.
18352**
18353** When an in-memory Table object is deleted (for example when the
18354** schema is being reloaded for some reason), the VTable objects are not
18355** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
18356** immediately. Instead, they are moved from the Table.pVTable list to
18357** another linked list headed by the sqlite3.pDisconnect member of the
18358** corresponding sqlite3 structure. They are then deleted/xDisconnected
18359** next time a statement is prepared using said sqlite3*. This is done
18360** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
18361** Refer to comments above function sqlite3VtabUnlockList() for an
18362** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
18363** list without holding the corresponding sqlite3.mutex mutex.
18364**
18365** The memory for objects of this type is always allocated by
18366** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
18367** the first argument.
18368*/
18369struct VTable {
18370  sqlite3 *db;              /* Database connection associated with this table */
18371  Module *pMod;             /* Pointer to module implementation */
18372  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
18373  int nRef;                 /* Number of pointers to this structure */
18374  u8 bConstraint;           /* True if constraints are supported */
18375  u8 bAllSchemas;           /* True if might use any attached schema */
18376  u8 eVtabRisk;             /* Riskiness of allowing hacker access */
18377  int iSavepoint;           /* Depth of the SAVEPOINT stack */
18378  VTable *pNext;            /* Next in linked list (see above) */
18379};
18380
18381/* Allowed values for VTable.eVtabRisk
18382*/
18383#define SQLITE_VTABRISK_Low          0
18384#define SQLITE_VTABRISK_Normal       1
18385#define SQLITE_VTABRISK_High         2
18386
18387/*
18388** The schema for each SQL table, virtual table, and view is represented
18389** in memory by an instance of the following structure.
18390*/
18391struct Table {
18392  char *zName;         /* Name of the table or view */
18393  Column *aCol;        /* Information about each column */
18394  Index *pIndex;       /* List of SQL indexes on this table. */
18395  char *zColAff;       /* String defining the affinity of each column */
18396  ExprList *pCheck;    /* All CHECK constraints */
18397                       /*   ... also used as column name list in a VIEW */
18398  Pgno tnum;           /* Root BTree page for this table */
18399  u32 nTabRef;         /* Number of pointers to this Table */
18400  u32 tabFlags;        /* Mask of TF_* values */
18401  i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */
18402  i16 nCol;            /* Number of columns in this table */
18403  i16 nNVCol;          /* Number of columns that are not VIRTUAL */
18404  LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
18405  LogEst szTabRow;     /* Estimated size of each table row in bytes */
18406#ifdef SQLITE_ENABLE_COSTMULT
18407  LogEst costMult;     /* Cost multiplier for using this table */
18408#endif
18409  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
18410  u8 eTabType;         /* 0: normal, 1: virtual, 2: view */
18411  union {
18412    struct {             /* Used by ordinary tables: */
18413      int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
18414      FKey *pFKey;         /* Linked list of all foreign keys in this table */
18415      ExprList *pDfltList; /* DEFAULT clauses on various columns.
18416                           ** Or the AS clause for generated columns. */
18417    } tab;
18418    struct {             /* Used by views: */
18419      Select *pSelect;     /* View definition */
18420    } view;
18421    struct {             /* Used by virtual tables only: */
18422      int nArg;            /* Number of arguments to the module */
18423      char **azArg;        /* 0: module 1: schema 2: vtab name 3...: args */
18424      VTable *p;           /* List of VTable objects. */
18425    } vtab;
18426  } u;
18427  Trigger *pTrigger;   /* List of triggers on this object */
18428  Schema *pSchema;     /* Schema that contains this table */
18429};
18430
18431/*
18432** Allowed values for Table.tabFlags.
18433**
18434** TF_OOOHidden applies to tables or view that have hidden columns that are
18435** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING
18436** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,
18437** the TF_OOOHidden attribute would apply in this case.  Such tables require
18438** special handling during INSERT processing. The "OOO" means "Out Of Order".
18439**
18440** Constraints:
18441**
18442**         TF_HasVirtual == COLFLAG_VIRTUAL
18443**         TF_HasStored  == COLFLAG_STORED
18444**         TF_HasHidden  == COLFLAG_HIDDEN
18445*/
18446#define TF_Readonly       0x00000001 /* Read-only system table */
18447#define TF_HasHidden      0x00000002 /* Has one or more hidden columns */
18448#define TF_HasPrimaryKey  0x00000004 /* Table has a primary key */
18449#define TF_Autoincrement  0x00000008 /* Integer primary key is autoincrement */
18450#define TF_HasStat1       0x00000010 /* nRowLogEst set from sqlite_stat1 */
18451#define TF_HasVirtual     0x00000020 /* Has one or more VIRTUAL columns */
18452#define TF_HasStored      0x00000040 /* Has one or more STORED columns */
18453#define TF_HasGenerated   0x00000060 /* Combo: HasVirtual + HasStored */
18454#define TF_WithoutRowid   0x00000080 /* No rowid.  PRIMARY KEY is the key */
18455#define TF_MaybeReanalyze 0x00000100 /* Maybe run ANALYZE on this table */
18456#define TF_NoVisibleRowid 0x00000200 /* No user-visible "rowid" column */
18457#define TF_OOOHidden      0x00000400 /* Out-of-Order hidden columns */
18458#define TF_HasNotNull     0x00000800 /* Contains NOT NULL constraints */
18459#define TF_Shadow         0x00001000 /* True for a shadow table */
18460#define TF_HasStat4       0x00002000 /* STAT4 info available for this table */
18461#define TF_Ephemeral      0x00004000 /* An ephemeral table */
18462#define TF_Eponymous      0x00008000 /* An eponymous virtual table */
18463#define TF_Strict         0x00010000 /* STRICT mode */
18464
18465/*
18466** Allowed values for Table.eTabType
18467*/
18468#define TABTYP_NORM      0     /* Ordinary table */
18469#define TABTYP_VTAB      1     /* Virtual table */
18470#define TABTYP_VIEW      2     /* A view */
18471
18472#define IsView(X)           ((X)->eTabType==TABTYP_VIEW)
18473#define IsOrdinaryTable(X)  ((X)->eTabType==TABTYP_NORM)
18474
18475/*
18476** Test to see whether or not a table is a virtual table.  This is
18477** done as a macro so that it will be optimized out when virtual
18478** table support is omitted from the build.
18479*/
18480#ifndef SQLITE_OMIT_VIRTUALTABLE
18481#  define IsVirtual(X)      ((X)->eTabType==TABTYP_VTAB)
18482#  define ExprIsVtab(X)  \
18483   ((X)->op==TK_COLUMN && (X)->y.pTab->eTabType==TABTYP_VTAB)
18484#else
18485#  define IsVirtual(X)      0
18486#  define ExprIsVtab(X)     0
18487#endif
18488
18489/*
18490** Macros to determine if a column is hidden.  IsOrdinaryHiddenColumn()
18491** only works for non-virtual tables (ordinary tables and views) and is
18492** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined.  The
18493** IsHiddenColumn() macro is general purpose.
18494*/
18495#if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
18496#  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
18497#  define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
18498#elif !defined(SQLITE_OMIT_VIRTUALTABLE)
18499#  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
18500#  define IsOrdinaryHiddenColumn(X) 0
18501#else
18502#  define IsHiddenColumn(X)         0
18503#  define IsOrdinaryHiddenColumn(X) 0
18504#endif
18505
18506
18507/* Does the table have a rowid */
18508#define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
18509#define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
18510
18511/* Macro is true if the SQLITE_ALLOW_ROWID_IN_VIEW (mis-)feature is
18512** available.  By default, this macro is false
18513*/
18514#ifndef SQLITE_ALLOW_ROWID_IN_VIEW
18515# define ViewCanHaveRowid     0
18516#else
18517# define ViewCanHaveRowid     (sqlite3Config.mNoVisibleRowid==0)
18518#endif
18519
18520/*
18521** Each foreign key constraint is an instance of the following structure.
18522**
18523** A foreign key is associated with two tables.  The "from" table is
18524** the table that contains the REFERENCES clause that creates the foreign
18525** key.  The "to" table is the table that is named in the REFERENCES clause.
18526** Consider this example:
18527**
18528**     CREATE TABLE ex1(
18529**       a INTEGER PRIMARY KEY,
18530**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
18531**     );
18532**
18533** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
18534** Equivalent names:
18535**
18536**     from-table == child-table
18537**       to-table == parent-table
18538**
18539** Each REFERENCES clause generates an instance of the following structure
18540** which is attached to the from-table.  The to-table need not exist when
18541** the from-table is created.  The existence of the to-table is not checked.
18542**
18543** The list of all parents for child Table X is held at X.pFKey.
18544**
18545** A list of all children for a table named Z (which might not even exist)
18546** is held in Schema.fkeyHash with a hash key of Z.
18547*/
18548struct FKey {
18549  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
18550  FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
18551  char *zTo;        /* Name of table that the key points to (aka: Parent) */
18552  FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
18553  FKey *pPrevTo;    /* Previous with the same zTo */
18554  int nCol;         /* Number of columns in this key */
18555  /* EV: R-30323-21917 */
18556  u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
18557  u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
18558  Trigger *apTrigger[2];/* Triggers for aAction[] actions */
18559  struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
18560    int iFrom;            /* Index of column in pFrom */
18561    char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
18562  } aCol[1];            /* One entry for each of nCol columns */
18563};
18564
18565/*
18566** SQLite supports many different ways to resolve a constraint
18567** error.  ROLLBACK processing means that a constraint violation
18568** causes the operation in process to fail and for the current transaction
18569** to be rolled back.  ABORT processing means the operation in process
18570** fails and any prior changes from that one operation are backed out,
18571** but the transaction is not rolled back.  FAIL processing means that
18572** the operation in progress stops and returns an error code.  But prior
18573** changes due to the same operation are not backed out and no rollback
18574** occurs.  IGNORE means that the particular row that caused the constraint
18575** error is not inserted or updated.  Processing continues and no error
18576** is returned.  REPLACE means that preexisting database rows that caused
18577** a UNIQUE constraint violation are removed so that the new insert or
18578** update can proceed.  Processing continues and no error is reported.
18579** UPDATE applies to insert operations only and means that the insert
18580** is omitted and the DO UPDATE clause of an upsert is run instead.
18581**
18582** RESTRICT, SETNULL, SETDFLT, and CASCADE actions apply only to foreign keys.
18583** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
18584** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
18585** key is set to NULL.  SETDFLT means that the foreign key is set
18586** to its default value.  CASCADE means that a DELETE or UPDATE of the
18587** referenced table row is propagated into the row that holds the
18588** foreign key.
18589**
18590** The OE_Default value is a place holder that means to use whatever
18591** conflict resolution algorithm is required from context.
18592**
18593** The following symbolic values are used to record which type
18594** of conflict resolution action to take.
18595*/
18596#define OE_None     0   /* There is no constraint to check */
18597#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
18598#define OE_Abort    2   /* Back out changes but do no rollback transaction */
18599#define OE_Fail     3   /* Stop the operation but leave all prior changes */
18600#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
18601#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
18602#define OE_Update   6   /* Process as a DO UPDATE in an upsert */
18603#define OE_Restrict 7   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
18604#define OE_SetNull  8   /* Set the foreign key value to NULL */
18605#define OE_SetDflt  9   /* Set the foreign key value to its default */
18606#define OE_Cascade  10  /* Cascade the changes */
18607#define OE_Default  11  /* Do whatever the default action is */
18608
18609
18610/*
18611** An instance of the following structure is passed as the first
18612** argument to sqlite3VdbeKeyCompare and is used to control the
18613** comparison of the two index keys.
18614**
18615** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
18616** are nField slots for the columns of an index then one extra slot
18617** for the rowid at the end.
18618*/
18619struct KeyInfo {
18620  u32 nRef;           /* Number of references to this KeyInfo object */
18621  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
18622  u16 nKeyField;      /* Number of key columns in the index */
18623  u16 nAllField;      /* Total columns, including key plus others */
18624  sqlite3 *db;        /* The database connection */
18625  u8 *aSortFlags;     /* Sort order for each column. */
18626  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
18627};
18628
18629/*
18630** Allowed bit values for entries in the KeyInfo.aSortFlags[] array.
18631*/
18632#define KEYINFO_ORDER_DESC    0x01    /* DESC sort order */
18633#define KEYINFO_ORDER_BIGNULL 0x02    /* NULL is larger than any other value */
18634
18635/*
18636** This object holds a record which has been parsed out into individual
18637** fields, for the purposes of doing a comparison.
18638**
18639** A record is an object that contains one or more fields of data.
18640** Records are used to store the content of a table row and to store
18641** the key of an index.  A blob encoding of a record is created by
18642** the OP_MakeRecord opcode of the VDBE and is disassembled by the
18643** OP_Column opcode.
18644**
18645** An instance of this object serves as a "key" for doing a search on
18646** an index b+tree. The goal of the search is to find the entry that
18647** is closed to the key described by this object.  This object might hold
18648** just a prefix of the key.  The number of fields is given by
18649** pKeyInfo->nField.
18650**
18651** The r1 and r2 fields are the values to return if this key is less than
18652** or greater than a key in the btree, respectively.  These are normally
18653** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
18654** is in DESC order.
18655**
18656** The key comparison functions actually return default_rc when they find
18657** an equals comparison.  default_rc can be -1, 0, or +1.  If there are
18658** multiple entries in the b-tree with the same key (when only looking
18659** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
18660** cause the search to find the last match, or +1 to cause the search to
18661** find the first match.
18662**
18663** The key comparison functions will set eqSeen to true if they ever
18664** get and equal results when comparing this structure to a b-tree record.
18665** When default_rc!=0, the search might end up on the record immediately
18666** before the first match or immediately after the last match.  The
18667** eqSeen field will indicate whether or not an exact match exists in the
18668** b-tree.
18669*/
18670struct UnpackedRecord {
18671  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
18672  Mem *aMem;          /* Values */
18673  union {
18674    char *z;            /* Cache of aMem[0].z for vdbeRecordCompareString() */
18675    i64 i;              /* Cache of aMem[0].u.i for vdbeRecordCompareInt() */
18676  } u;
18677  int n;              /* Cache of aMem[0].n used by vdbeRecordCompareString() */
18678  u16 nField;         /* Number of entries in apMem[] */
18679  i8 default_rc;      /* Comparison result if keys are equal */
18680  u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
18681  i8 r1;              /* Value to return if (lhs < rhs) */
18682  i8 r2;              /* Value to return if (lhs > rhs) */
18683  u8 eqSeen;          /* True if an equality comparison has been seen */
18684};
18685
18686
18687/*
18688** Each SQL index is represented in memory by an
18689** instance of the following structure.
18690**
18691** The columns of the table that are to be indexed are described
18692** by the aiColumn[] field of this structure.  For example, suppose
18693** we have the following table and index:
18694**
18695**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
18696**     CREATE INDEX Ex2 ON Ex1(c3,c1);
18697**
18698** In the Table structure describing Ex1, nCol==3 because there are
18699** three columns in the table.  In the Index structure describing
18700** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
18701** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
18702** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
18703** The second column to be indexed (c1) has an index of 0 in
18704** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
18705**
18706** The Index.onError field determines whether or not the indexed columns
18707** must be unique and what to do if they are not.  When Index.onError=OE_None,
18708** it means this is not a unique index.  Otherwise it is a unique index
18709** and the value of Index.onError indicates which conflict resolution
18710** algorithm to employ when an attempt is made to insert a non-unique
18711** element.
18712**
18713** The colNotIdxed bitmask is used in combination with SrcItem.colUsed
18714** for a fast test to see if an index can serve as a covering index.
18715** colNotIdxed has a 1 bit for every column of the original table that
18716** is *not* available in the index.  Thus the expression
18717** "colUsed & colNotIdxed" will be non-zero if the index is not a
18718** covering index.  The most significant bit of of colNotIdxed will always
18719** be true (note-20221022-a).  If a column beyond the 63rd column of the
18720** table is used, the "colUsed & colNotIdxed" test will always be non-zero
18721** and we have to assume either that the index is not covering, or use
18722** an alternative (slower) algorithm to determine whether or not
18723** the index is covering.
18724**
18725** While parsing a CREATE TABLE or CREATE INDEX statement in order to
18726** generate VDBE code (as opposed to parsing one read from an sqlite_schema
18727** table as part of parsing an existing database schema), transient instances
18728** of this structure may be created. In this case the Index.tnum variable is
18729** used to store the address of a VDBE instruction, not a database page
18730** number (it cannot - the database page is not allocated until the VDBE
18731** program is executed). See convertToWithoutRowidTable() for details.
18732*/
18733struct Index {
18734  char *zName;             /* Name of this index */
18735  i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
18736  LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
18737  Table *pTable;           /* The SQL table being indexed */
18738  char *zColAff;           /* String defining the affinity of each column */
18739  Index *pNext;            /* The next index associated with the same table */
18740  Schema *pSchema;         /* Schema containing this index */
18741  u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
18742  const char **azColl;     /* Array of collation sequence names for index */
18743  Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
18744  ExprList *aColExpr;      /* Column expressions */
18745  Pgno tnum;               /* DB Page containing root of this index */
18746  LogEst szIdxRow;         /* Estimated average row size in bytes */
18747  u16 nKeyCol;             /* Number of columns forming the key */
18748  u16 nColumn;             /* Number of columns stored in the index */
18749  u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
18750  unsigned idxType:2;      /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */
18751  unsigned bUnordered:1;   /* Use this index for == or IN queries only */
18752  unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
18753  unsigned isResized:1;    /* True if resizeIndexObject() has been called */
18754  unsigned isCovering:1;   /* True if this is a covering index */
18755  unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */
18756  unsigned hasStat1:1;     /* aiRowLogEst values come from sqlite_stat1 */
18757  unsigned bLowQual:1;     /* sqlite_stat1 says this is a low-quality index */
18758  unsigned bNoQuery:1;     /* Do not use this index to optimize queries */
18759  unsigned bAscKeyBug:1;   /* True if the bba7b69f9849b5bf bug applies */
18760  unsigned bHasVCol:1;     /* Index references one or more VIRTUAL columns */
18761  unsigned bHasExpr:1;     /* Index contains an expression, either a literal
18762                           ** expression, or a reference to a VIRTUAL column */
18763#ifdef SQLITE_ENABLE_STAT4
18764  int nSample;             /* Number of elements in aSample[] */
18765  int mxSample;            /* Number of slots allocated to aSample[] */
18766  int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
18767  tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
18768  IndexSample *aSample;    /* Samples of the left-most key */
18769  tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
18770  tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
18771#endif
18772  Bitmask colNotIdxed;     /* Unindexed columns in pTab */
18773};
18774
18775/*
18776** Allowed values for Index.idxType
18777*/
18778#define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
18779#define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
18780#define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
18781#define SQLITE_IDXTYPE_IPK         3   /* INTEGER PRIMARY KEY index */
18782
18783/* Return true if index X is a PRIMARY KEY index */
18784#define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
18785
18786/* Return true if index X is a UNIQUE index */
18787#define IsUniqueIndex(X)      ((X)->onError!=OE_None)
18788
18789/* The Index.aiColumn[] values are normally positive integer.  But
18790** there are some negative values that have special meaning:
18791*/
18792#define XN_ROWID     (-1)     /* Indexed column is the rowid */
18793#define XN_EXPR      (-2)     /* Indexed column is an expression */
18794
18795/*
18796** Each sample stored in the sqlite_stat4 table is represented in memory
18797** using a structure of this type.  See documentation at the top of the
18798** analyze.c source file for additional information.
18799*/
18800struct IndexSample {
18801  void *p;          /* Pointer to sampled record */
18802  int n;            /* Size of record in bytes */
18803  tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
18804  tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
18805  tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
18806};
18807
18808/*
18809** Possible values to use within the flags argument to sqlite3GetToken().
18810*/
18811#define SQLITE_TOKEN_QUOTED    0x1 /* Token is a quoted identifier. */
18812#define SQLITE_TOKEN_KEYWORD   0x2 /* Token is a keyword. */
18813
18814/*
18815** Each token coming out of the lexer is an instance of
18816** this structure.  Tokens are also used as part of an expression.
18817**
18818** The memory that "z" points to is owned by other objects.  Take care
18819** that the owner of the "z" string does not deallocate the string before
18820** the Token goes out of scope!  Very often, the "z" points to some place
18821** in the middle of the Parse.zSql text.  But it might also point to a
18822** static string.
18823*/
18824struct Token {
18825  const char *z;     /* Text of the token.  Not NULL-terminated! */
18826  unsigned int n;    /* Number of characters in this token */
18827};
18828
18829/*
18830** An instance of this structure contains information needed to generate
18831** code for a SELECT that contains aggregate functions.
18832**
18833** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
18834** pointer to this structure.  The Expr.iAgg field is the index in
18835** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
18836** code for that node.
18837**
18838** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
18839** original Select structure that describes the SELECT statement.  These
18840** fields do not need to be freed when deallocating the AggInfo structure.
18841*/
18842struct AggInfo {
18843  u8 directMode;          /* Direct rendering mode means take data directly
18844                          ** from source tables rather than from accumulators */
18845  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
18846                          ** than the source table */
18847  u16 nSortingColumn;     /* Number of columns in the sorting index */
18848  int sortingIdx;         /* Cursor number of the sorting index */
18849  int sortingIdxPTab;     /* Cursor number of pseudo-table */
18850  int iFirstReg;          /* First register in range for aCol[] and aFunc[] */
18851  ExprList *pGroupBy;     /* The group by clause */
18852  struct AggInfo_col {    /* For each column used in source tables */
18853    Table *pTab;             /* Source table */
18854    Expr *pCExpr;            /* The original expression */
18855    int iTable;              /* Cursor number of the source table */
18856    i16 iColumn;             /* Column number within the source table */
18857    i16 iSorterColumn;       /* Column number in the sorting index */
18858  } *aCol;
18859  int nColumn;            /* Number of used entries in aCol[] */
18860  int nAccumulator;       /* Number of columns that show through to the output.
18861                          ** Additional columns are used only as parameters to
18862                          ** aggregate functions */
18863  struct AggInfo_func {   /* For each aggregate function */
18864    Expr *pFExpr;            /* Expression encoding the function */
18865    FuncDef *pFunc;          /* The aggregate function implementation */
18866    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
18867    int iDistAddr;           /* Address of OP_OpenEphemeral */
18868    int iOBTab;              /* Ephemeral table to implement ORDER BY */
18869    u8 bOBPayload;           /* iOBTab has payload columns separate from key */
18870    u8 bOBUnique;            /* Enforce uniqueness on iOBTab keys */
18871    u8 bUseSubtype;          /* Transfer subtype info through sorter */
18872  } *aFunc;
18873  int nFunc;              /* Number of entries in aFunc[] */
18874  u32 selId;              /* Select to which this AggInfo belongs */
18875#ifdef SQLITE_DEBUG
18876  Select *pSelect;        /* SELECT statement that this AggInfo supports */
18877#endif
18878};
18879
18880/*
18881** Macros to compute aCol[] and aFunc[] register numbers.
18882**
18883** These macros should not be used prior to the call to
18884** assignAggregateRegisters() that computes the value of pAggInfo->iFirstReg.
18885** The assert()s that are part of this macro verify that constraint.
18886*/
18887#define AggInfoColumnReg(A,I)  (assert((A)->iFirstReg),(A)->iFirstReg+(I))
18888#define AggInfoFuncReg(A,I)    \
18889                      (assert((A)->iFirstReg),(A)->iFirstReg+(A)->nColumn+(I))
18890
18891/*
18892** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
18893** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
18894** than 32767 we have to make it 32-bit.  16-bit is preferred because
18895** it uses less memory in the Expr object, which is a big memory user
18896** in systems with lots of prepared statements.  And few applications
18897** need more than about 10 or 20 variables.  But some extreme users want
18898** to have prepared statements with over 32766 variables, and for them
18899** the option is available (at compile-time).
18900*/
18901#if SQLITE_MAX_VARIABLE_NUMBER<32767
18902typedef i16 ynVar;
18903#else
18904typedef int ynVar;
18905#endif
18906
18907/*
18908** Each node of an expression in the parse tree is an instance
18909** of this structure.
18910**
18911** Expr.op is the opcode. The integer parser token codes are reused
18912** as opcodes here. For example, the parser defines TK_GE to be an integer
18913** code representing the ">=" operator. This same integer code is reused
18914** to represent the greater-than-or-equal-to operator in the expression
18915** tree.
18916**
18917** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
18918** or TK_STRING), then Expr.u.zToken contains the text of the SQL literal. If
18919** the expression is a variable (TK_VARIABLE), then Expr.u.zToken contains the
18920** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
18921** then Expr.u.zToken contains the name of the function.
18922**
18923** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
18924** binary operator. Either or both may be NULL.
18925**
18926** Expr.x.pList is a list of arguments if the expression is an SQL function,
18927** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
18928** Expr.x.pSelect is used if the expression is a sub-select or an expression of
18929** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
18930** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
18931** valid.
18932**
18933** An expression of the form ID or ID.ID refers to a column in a table.
18934** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
18935** the integer cursor number of a VDBE cursor pointing to that table and
18936** Expr.iColumn is the column number for the specific column.  If the
18937** expression is used as a result in an aggregate SELECT, then the
18938** value is also stored in the Expr.iAgg column in the aggregate so that
18939** it can be accessed after all aggregates are computed.
18940**
18941** If the expression is an unbound variable marker (a question mark
18942** character '?' in the original SQL) then the Expr.iTable holds the index
18943** number for that variable.
18944**
18945** If the expression is a subquery then Expr.iColumn holds an integer
18946** register number containing the result of the subquery.  If the
18947** subquery gives a constant result, then iTable is -1.  If the subquery
18948** gives a different answer at different times during statement processing
18949** then iTable is the address of a subroutine that computes the subquery.
18950**
18951** If the Expr is of type OP_Column, and the table it is selecting from
18952** is a disk table or the "old.*" pseudo-table, then pTab points to the
18953** corresponding table definition.
18954**
18955** ALLOCATION NOTES:
18956**
18957** Expr objects can use a lot of memory space in database schema.  To
18958** help reduce memory requirements, sometimes an Expr object will be
18959** truncated.  And to reduce the number of memory allocations, sometimes
18960** two or more Expr objects will be stored in a single memory allocation,
18961** together with Expr.u.zToken strings.
18962**
18963** If the EP_Reduced and EP_TokenOnly flags are set when
18964** an Expr object is truncated.  When EP_Reduced is set, then all
18965** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
18966** are contained within the same memory allocation.  Note, however, that
18967** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
18968** allocated, regardless of whether or not EP_Reduced is set.
18969*/
18970struct Expr {
18971  u8 op;                 /* Operation performed by this node */
18972  char affExpr;          /* affinity, or RAISE type */
18973  u8 op2;                /* TK_REGISTER/TK_TRUTH: original value of Expr.op
18974                         ** TK_COLUMN: the value of p5 for OP_Column
18975                         ** TK_AGG_FUNCTION: nesting depth
18976                         ** TK_FUNCTION: NC_SelfRef flag if needs OP_PureFunc */
18977#ifdef SQLITE_DEBUG
18978  u8 vvaFlags;           /* Verification flags. */
18979#endif
18980  u32 flags;             /* Various flags.  EP_* See below */
18981  union {
18982    char *zToken;          /* Token value. Zero terminated and dequoted */
18983    int iValue;            /* Non-negative integer value if EP_IntValue */
18984  } u;
18985
18986  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
18987  ** space is allocated for the fields below this point. An attempt to
18988  ** access them will result in a segfault or malfunction.
18989  *********************************************************************/
18990
18991  Expr *pLeft;           /* Left subnode */
18992  Expr *pRight;          /* Right subnode */
18993  union {
18994    ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
18995    Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
18996  } x;
18997
18998  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
18999  ** space is allocated for the fields below this point. An attempt to
19000  ** access them will result in a segfault or malfunction.
19001  *********************************************************************/
19002
19003#if SQLITE_MAX_EXPR_DEPTH>0
19004  int nHeight;           /* Height of the tree headed by this node */
19005#endif
19006  int iTable;            /* TK_COLUMN: cursor number of table holding column
19007                         ** TK_REGISTER: register number
19008                         ** TK_TRIGGER: 1 -> new, 0 -> old
19009                         ** EP_Unlikely:  134217728 times likelihood
19010                         ** TK_IN: ephemeral table holding RHS
19011                         ** TK_SELECT_COLUMN: Number of columns on the LHS
19012                         ** TK_SELECT: 1st register of result vector */
19013  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
19014                         ** TK_VARIABLE: variable number (always >= 1).
19015                         ** TK_SELECT_COLUMN: column of the result vector */
19016  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
19017  union {
19018    int iJoin;             /* If EP_OuterON or EP_InnerON, the right table */
19019    int iOfst;             /* else: start of token from start of statement */
19020  } w;
19021  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
19022  union {
19023    Table *pTab;           /* TK_COLUMN: Table containing column. Can be NULL
19024                           ** for a column of an index on an expression */
19025    Window *pWin;          /* EP_WinFunc: Window/Filter defn for a function */
19026    struct {               /* TK_IN, TK_SELECT, and TK_EXISTS */
19027      int iAddr;             /* Subroutine entry address */
19028      int regReturn;         /* Register used to hold return address */
19029    } sub;
19030  } y;
19031};
19032
19033/* The following are the meanings of bits in the Expr.flags field.
19034** Value restrictions:
19035**
19036**          EP_Agg == NC_HasAgg == SF_HasAgg
19037**          EP_Win == NC_HasWin
19038*/
19039#define EP_OuterON    0x000001 /* Originates in ON/USING clause of outer join */
19040#define EP_InnerON    0x000002 /* Originates in ON/USING of an inner join */
19041#define EP_Distinct   0x000004 /* Aggregate function with DISTINCT keyword */
19042#define EP_HasFunc    0x000008 /* Contains one or more functions of any kind */
19043#define EP_Agg        0x000010 /* Contains one or more aggregate functions */
19044#define EP_FixedCol   0x000020 /* TK_Column with a known fixed value */
19045#define EP_VarSelect  0x000040 /* pSelect is correlated, not constant */
19046#define EP_DblQuoted  0x000080 /* token.z was originally in "..." */
19047#define EP_InfixFunc  0x000100 /* True for an infix function: LIKE, GLOB, etc */
19048#define EP_Collate    0x000200 /* Tree contains a TK_COLLATE operator */
19049#define EP_Commuted   0x000400 /* Comparison operator has been commuted */
19050#define EP_IntValue   0x000800 /* Integer value contained in u.iValue */
19051#define EP_xIsSelect  0x001000 /* x.pSelect is valid (otherwise x.pList is) */
19052#define EP_Skip       0x002000 /* Operator does not contribute to affinity */
19053#define EP_Reduced    0x004000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
19054#define EP_Win        0x008000 /* Contains window functions */
19055#define EP_TokenOnly  0x010000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
19056#define EP_FullSize   0x020000 /* Expr structure must remain full sized */
19057#define EP_IfNullRow  0x040000 /* The TK_IF_NULL_ROW opcode */
19058#define EP_Unlikely   0x080000 /* unlikely() or likelihood() function */
19059#define EP_ConstFunc  0x100000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
19060#define EP_CanBeNull  0x200000 /* Can be null despite NOT NULL constraint */
19061#define EP_Subquery   0x400000 /* Tree contains a TK_SELECT operator */
19062#define EP_Leaf       0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
19063#define EP_WinFunc   0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
19064#define EP_Subrtn    0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
19065#define EP_Quoted    0x4000000 /* TK_ID was originally quoted */
19066#define EP_Static    0x8000000 /* Held in memory not obtained from malloc() */
19067#define EP_IsTrue   0x10000000 /* Always has boolean value of TRUE */
19068#define EP_IsFalse  0x20000000 /* Always has boolean value of FALSE */
19069#define EP_FromDDL  0x40000000 /* Originates from sqlite_schema */
19070               /*   0x80000000 // Available */
19071
19072/* The EP_Propagate mask is a set of properties that automatically propagate
19073** upwards into parent nodes.
19074*/
19075#define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
19076
19077/* Macros can be used to test, set, or clear bits in the
19078** Expr.flags field.
19079*/
19080#define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
19081#define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
19082#define ExprSetProperty(E,P)     (E)->flags|=(P)
19083#define ExprClearProperty(E,P)   (E)->flags&=~(P)
19084#define ExprAlwaysTrue(E)   (((E)->flags&(EP_OuterON|EP_IsTrue))==EP_IsTrue)
19085#define ExprAlwaysFalse(E)  (((E)->flags&(EP_OuterON|EP_IsFalse))==EP_IsFalse)
19086#define ExprIsFullSize(E)   (((E)->flags&(EP_Reduced|EP_TokenOnly))==0)
19087
19088/* Macros used to ensure that the correct members of unions are accessed
19089** in Expr.
19090*/
19091#define ExprUseUToken(E)    (((E)->flags&EP_IntValue)==0)
19092#define ExprUseUValue(E)    (((E)->flags&EP_IntValue)!=0)
19093#define ExprUseWOfst(E)     (((E)->flags&(EP_InnerON|EP_OuterON))==0)
19094#define ExprUseWJoin(E)     (((E)->flags&(EP_InnerON|EP_OuterON))!=0)
19095#define ExprUseXList(E)     (((E)->flags&EP_xIsSelect)==0)
19096#define ExprUseXSelect(E)   (((E)->flags&EP_xIsSelect)!=0)
19097#define ExprUseYTab(E)      (((E)->flags&(EP_WinFunc|EP_Subrtn))==0)
19098#define ExprUseYWin(E)      (((E)->flags&EP_WinFunc)!=0)
19099#define ExprUseYSub(E)      (((E)->flags&EP_Subrtn)!=0)
19100
19101/* Flags for use with Expr.vvaFlags
19102*/
19103#define EP_NoReduce   0x01  /* Cannot EXPRDUP_REDUCE this Expr */
19104#define EP_Immutable  0x02  /* Do not change this Expr node */
19105
19106/* The ExprSetVVAProperty() macro is used for Verification, Validation,
19107** and Accreditation only.  It works like ExprSetProperty() during VVA
19108** processes but is a no-op for delivery.
19109*/
19110#ifdef SQLITE_DEBUG
19111# define ExprSetVVAProperty(E,P)   (E)->vvaFlags|=(P)
19112# define ExprHasVVAProperty(E,P)   (((E)->vvaFlags&(P))!=0)
19113# define ExprClearVVAProperties(E) (E)->vvaFlags = 0
19114#else
19115# define ExprSetVVAProperty(E,P)
19116# define ExprHasVVAProperty(E,P)   0
19117# define ExprClearVVAProperties(E)
19118#endif
19119
19120/*
19121** Macros to determine the number of bytes required by a normal Expr
19122** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
19123** and an Expr struct with the EP_TokenOnly flag set.
19124*/
19125#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
19126#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
19127#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
19128
19129/*
19130** Flags passed to the sqlite3ExprDup() function. See the header comment
19131** above sqlite3ExprDup() for details.
19132*/
19133#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
19134
19135/*
19136** True if the expression passed as an argument was a function with
19137** an OVER() clause (a window function).
19138*/
19139#ifdef SQLITE_OMIT_WINDOWFUNC
19140# define IsWindowFunc(p) 0
19141#else
19142# define IsWindowFunc(p) ( \
19143    ExprHasProperty((p), EP_WinFunc) && p->y.pWin->eFrmType!=TK_FILTER \
19144 )
19145#endif
19146
19147/*
19148** A list of expressions.  Each expression may optionally have a
19149** name.  An expr/name combination can be used in several ways, such
19150** as the list of "expr AS ID" fields following a "SELECT" or in the
19151** list of "ID = expr" items in an UPDATE.  A list of expressions can
19152** also be used as the argument to a function, in which case the a.zName
19153** field is not used.
19154**
19155** In order to try to keep memory usage down, the Expr.a.zEName field
19156** is used for multiple purposes:
19157**
19158**     eEName          Usage
19159**    ----------       -------------------------
19160**    ENAME_NAME       (1) the AS of result set column
19161**                     (2) COLUMN= of an UPDATE
19162**
19163**    ENAME_TAB        DB.TABLE.NAME used to resolve names
19164**                     of subqueries
19165**
19166**    ENAME_SPAN       Text of the original result set
19167**                     expression.
19168*/
19169struct ExprList {
19170  int nExpr;             /* Number of expressions on the list */
19171  int nAlloc;            /* Number of a[] slots allocated */
19172  struct ExprList_item { /* For each expression in the list */
19173    Expr *pExpr;            /* The parse tree for this expression */
19174    char *zEName;           /* Token associated with this expression */
19175    struct {
19176      u8 sortFlags;           /* Mask of KEYINFO_ORDER_* flags */
19177      unsigned eEName :2;     /* Meaning of zEName */
19178      unsigned done :1;       /* Indicates when processing is finished */
19179      unsigned reusable :1;   /* Constant expression is reusable */
19180      unsigned bSorterRef :1; /* Defer evaluation until after sorting */
19181      unsigned bNulls :1;     /* True if explicit "NULLS FIRST/LAST" */
19182      unsigned bUsed :1;      /* This column used in a SF_NestedFrom subquery */
19183      unsigned bUsingTerm:1;  /* Term from the USING clause of a NestedFrom */
19184      unsigned bNoExpand: 1;  /* Term is an auxiliary in NestedFrom and should
19185                              ** not be expanded by "*" in parent queries */
19186    } fg;
19187    union {
19188      struct {             /* Used by any ExprList other than Parse.pConsExpr */
19189        u16 iOrderByCol;      /* For ORDER BY, column number in result set */
19190        u16 iAlias;           /* Index into Parse.aAlias[] for zName */
19191      } x;
19192      int iConstExprReg;   /* Register in which Expr value is cached. Used only
19193                           ** by Parse.pConstExpr */
19194    } u;
19195  } a[1];                  /* One slot for each expression in the list */
19196};
19197
19198/*
19199** Allowed values for Expr.a.eEName
19200*/
19201#define ENAME_NAME  0       /* The AS clause of a result set */
19202#define ENAME_SPAN  1       /* Complete text of the result set expression */
19203#define ENAME_TAB   2       /* "DB.TABLE.NAME" for the result set */
19204#define ENAME_ROWID 3       /* "DB.TABLE._rowid_" for * expansion of rowid */
19205
19206/*
19207** An instance of this structure can hold a simple list of identifiers,
19208** such as the list "a,b,c" in the following statements:
19209**
19210**      INSERT INTO t(a,b,c) VALUES ...;
19211**      CREATE INDEX idx ON t(a,b,c);
19212**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
19213**
19214** The IdList.a.idx field is used when the IdList represents the list of
19215** column names after a table name in an INSERT statement.  In the statement
19216**
19217**     INSERT INTO t(a,b,c) ...
19218**
19219** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
19220*/
19221struct IdList {
19222  int nId;         /* Number of identifiers on the list */
19223  u8 eU4;          /* Which element of a.u4 is valid */
19224  struct IdList_item {
19225    char *zName;      /* Name of the identifier */
19226    union {
19227      int idx;          /* Index in some Table.aCol[] of a column named zName */
19228      Expr *pExpr;      /* Expr to implement a USING variable -- NOT USED */
19229    } u4;
19230  } a[1];
19231};
19232
19233/*
19234** Allowed values for IdList.eType, which determines which value of the a.u4
19235** is valid.
19236*/
19237#define EU4_NONE   0   /* Does not use IdList.a.u4 */
19238#define EU4_IDX    1   /* Uses IdList.a.u4.idx */
19239#define EU4_EXPR   2   /* Uses IdList.a.u4.pExpr -- NOT CURRENTLY USED */
19240
19241/*
19242** The SrcItem object represents a single term in the FROM clause of a query.
19243** The SrcList object is mostly an array of SrcItems.
19244**
19245** The jointype starts out showing the join type between the current table
19246** and the next table on the list.  The parser builds the list this way.
19247** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
19248** jointype expresses the join between the table and the previous table.
19249**
19250** In the colUsed field, the high-order bit (bit 63) is set if the table
19251** contains more than 63 columns and the 64-th or later column is used.
19252**
19253** Union member validity:
19254**
19255**    u1.zIndexedBy      fg.isIndexedBy && !fg.isTabFunc
19256**    u1.pFuncArg        fg.isTabFunc   && !fg.isIndexedBy
19257**    u1.nRow            !fg.isTabFunc  && !fg.isIndexedBy
19258**
19259**    u2.pIBIndex        fg.isIndexedBy && !fg.isCte
19260**    u2.pCteUse         fg.isCte       && !fg.isIndexedBy
19261*/
19262struct SrcItem {
19263  Schema *pSchema;  /* Schema to which this item is fixed */
19264  char *zDatabase;  /* Name of database holding this table */
19265  char *zName;      /* Name of the table */
19266  char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
19267  Table *pTab;      /* An SQL table corresponding to zName */
19268  Select *pSelect;  /* A SELECT statement used in place of a table name */
19269  int addrFillSub;  /* Address of subroutine to manifest a subquery */
19270  int regReturn;    /* Register holding return address of addrFillSub */
19271  int regResult;    /* Registers holding results of a co-routine */
19272  struct {
19273    u8 jointype;      /* Type of join between this table and the previous */
19274    unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
19275    unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
19276    unsigned isTabFunc :1;     /* True if table-valued-function syntax */
19277    unsigned isCorrelated :1;  /* True if sub-query is correlated */
19278    unsigned isMaterialized:1; /* This is a materialized view */
19279    unsigned viaCoroutine :1;  /* Implemented as a co-routine */
19280    unsigned isRecursive :1;   /* True for recursive reference in WITH */
19281    unsigned fromDDL :1;       /* Comes from sqlite_schema */
19282    unsigned isCte :1;         /* This is a CTE */
19283    unsigned notCte :1;        /* This item may not match a CTE */
19284    unsigned isUsing :1;       /* u3.pUsing is valid */
19285    unsigned isOn :1;          /* u3.pOn was once valid and non-NULL */
19286    unsigned isSynthUsing :1;  /* u3.pUsing is synthesized from NATURAL */
19287    unsigned isNestedFrom :1;  /* pSelect is a SF_NestedFrom subquery */
19288    unsigned rowidUsed :1;     /* The ROWID of this table is referenced */
19289  } fg;
19290  int iCursor;      /* The VDBE cursor number used to access this table */
19291  union {
19292    Expr *pOn;        /* fg.isUsing==0 =>  The ON clause of a join */
19293    IdList *pUsing;   /* fg.isUsing==1 =>  The USING clause of a join */
19294  } u3;
19295  Bitmask colUsed;  /* Bit N set if column N used. Details above for N>62 */
19296  union {
19297    char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
19298    ExprList *pFuncArg;  /* Arguments to table-valued-function */
19299    u32 nRow;            /* Number of rows in a VALUES clause */
19300  } u1;
19301  union {
19302    Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */
19303    CteUse *pCteUse;  /* CTE Usage info when fg.isCte is true */
19304  } u2;
19305};
19306
19307/*
19308** The OnOrUsing object represents either an ON clause or a USING clause.
19309** It can never be both at the same time, but it can be neither.
19310*/
19311struct OnOrUsing {
19312  Expr *pOn;         /* The ON clause of a join */
19313  IdList *pUsing;    /* The USING clause of a join */
19314};
19315
19316/*
19317** This object represents one or more tables that are the source of
19318** content for an SQL statement.  For example, a single SrcList object
19319** is used to hold the FROM clause of a SELECT statement.  SrcList also
19320** represents the target tables for DELETE, INSERT, and UPDATE statements.
19321**
19322*/
19323struct SrcList {
19324  int nSrc;        /* Number of tables or subqueries in the FROM clause */
19325  u32 nAlloc;      /* Number of entries allocated in a[] below */
19326  SrcItem a[1];    /* One entry for each identifier on the list */
19327};
19328
19329/*
19330** Permitted values of the SrcList.a.jointype field
19331*/
19332#define JT_INNER     0x01    /* Any kind of inner or cross join */
19333#define JT_CROSS     0x02    /* Explicit use of the CROSS keyword */
19334#define JT_NATURAL   0x04    /* True for a "natural" join */
19335#define JT_LEFT      0x08    /* Left outer join */
19336#define JT_RIGHT     0x10    /* Right outer join */
19337#define JT_OUTER     0x20    /* The "OUTER" keyword is present */
19338#define JT_LTORJ     0x40    /* One of the LEFT operands of a RIGHT JOIN
19339                             ** Mnemonic: Left Table Of Right Join */
19340#define JT_ERROR     0x80    /* unknown or unsupported join type */
19341
19342/*
19343** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
19344** and the WhereInfo.wctrlFlags member.
19345**
19346** Value constraints (enforced via assert()):
19347**     WHERE_USE_LIMIT  == SF_FixedLimit
19348*/
19349#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
19350#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
19351#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
19352#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
19353#define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
19354#define WHERE_DUPLICATES_OK    0x0010 /* Ok to return a row more than once */
19355#define WHERE_OR_SUBCLAUSE     0x0020 /* Processing a sub-WHERE as part of
19356                                      ** the OR optimization  */
19357#define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */
19358#define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
19359#define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
19360#define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
19361#define WHERE_AGG_DISTINCT     0x0400 /* Query is "SELECT agg(DISTINCT ...)" */
19362#define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
19363#define WHERE_RIGHT_JOIN       0x1000 /* Processing a RIGHT JOIN */
19364                        /*     0x2000    not currently used */
19365#define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */
19366                        /*     0x8000    not currently used */
19367
19368/* Allowed return values from sqlite3WhereIsDistinct()
19369*/
19370#define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
19371#define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
19372#define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
19373#define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
19374
19375/*
19376** A NameContext defines a context in which to resolve table and column
19377** names.  The context consists of a list of tables (the pSrcList) field and
19378** a list of named expression (pEList).  The named expression list may
19379** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
19380** to the table being operated on by INSERT, UPDATE, or DELETE.  The
19381** pEList corresponds to the result set of a SELECT and is NULL for
19382** other statements.
19383**
19384** NameContexts can be nested.  When resolving names, the inner-most
19385** context is searched first.  If no match is found, the next outer
19386** context is checked.  If there is still no match, the next context
19387** is checked.  This process continues until either a match is found
19388** or all contexts are check.  When a match is found, the nRef member of
19389** the context containing the match is incremented.
19390**
19391** Each subquery gets a new NameContext.  The pNext field points to the
19392** NameContext in the parent query.  Thus the process of scanning the
19393** NameContext list corresponds to searching through successively outer
19394** subqueries looking for a match.
19395*/
19396struct NameContext {
19397  Parse *pParse;       /* The parser */
19398  SrcList *pSrcList;   /* One or more tables used to resolve names */
19399  union {
19400    ExprList *pEList;    /* Optional list of result-set columns */
19401    AggInfo *pAggInfo;   /* Information about aggregates at this level */
19402    Upsert *pUpsert;     /* ON CONFLICT clause information from an upsert */
19403    int iBaseReg;        /* For TK_REGISTER when parsing RETURNING */
19404  } uNC;
19405  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
19406  int nRef;            /* Number of names resolved by this context */
19407  int nNcErr;          /* Number of errors encountered while resolving names */
19408  int ncFlags;         /* Zero or more NC_* flags defined below */
19409  u32 nNestedSelect;   /* Number of nested selects using this NC */
19410  Select *pWinSelect;  /* SELECT statement for any window functions */
19411};
19412
19413/*
19414** Allowed values for the NameContext, ncFlags field.
19415**
19416** Value constraints (all checked via assert()):
19417**    NC_HasAgg    == SF_HasAgg       == EP_Agg
19418**    NC_MinMaxAgg == SF_MinMaxAgg    == SQLITE_FUNC_MINMAX
19419**    NC_OrderAgg  == SF_OrderByReqd  == SQLITE_FUNC_ANYORDER
19420**    NC_HasWin    == EP_Win
19421**
19422*/
19423#define NC_AllowAgg  0x000001 /* Aggregate functions are allowed here */
19424#define NC_PartIdx   0x000002 /* True if resolving a partial index WHERE */
19425#define NC_IsCheck   0x000004 /* True if resolving a CHECK constraint */
19426#define NC_GenCol    0x000008 /* True for a GENERATED ALWAYS AS clause */
19427#define NC_HasAgg    0x000010 /* One or more aggregate functions seen */
19428#define NC_IdxExpr   0x000020 /* True if resolving columns of CREATE INDEX */
19429#define NC_SelfRef   0x00002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
19430#define NC_Subquery  0x000040 /* A subquery has been seen */
19431#define NC_UEList    0x000080 /* True if uNC.pEList is used */
19432#define NC_UAggInfo  0x000100 /* True if uNC.pAggInfo is used */
19433#define NC_UUpsert   0x000200 /* True if uNC.pUpsert is used */
19434#define NC_UBaseReg  0x000400 /* True if uNC.iBaseReg is used */
19435#define NC_MinMaxAgg 0x001000 /* min/max aggregates seen.  See note above */
19436#define NC_Complex   0x002000 /* True if a function or subquery seen */
19437#define NC_AllowWin  0x004000 /* Window functions are allowed here */
19438#define NC_HasWin    0x008000 /* One or more window functions seen */
19439#define NC_IsDDL     0x010000 /* Resolving names in a CREATE statement */
19440#define NC_InAggFunc 0x020000 /* True if analyzing arguments to an agg func */
19441#define NC_FromDDL   0x040000 /* SQL text comes from sqlite_schema */
19442#define NC_NoSelect  0x080000 /* Do not descend into sub-selects */
19443#define NC_Where     0x100000 /* Processing WHERE clause of a SELECT */
19444#define NC_OrderAgg 0x8000000 /* Has an aggregate other than count/min/max */
19445
19446/*
19447** An instance of the following object describes a single ON CONFLICT
19448** clause in an upsert.
19449**
19450** The pUpsertTarget field is only set if the ON CONFLICT clause includes
19451** conflict-target clause.  (In "ON CONFLICT(a,b)" the "(a,b)" is the
19452** conflict-target clause.)  The pUpsertTargetWhere is the optional
19453** WHERE clause used to identify partial unique indexes.
19454**
19455** pUpsertSet is the list of column=expr terms of the UPDATE statement.
19456** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING.  The
19457** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
19458** WHERE clause is omitted.
19459*/
19460struct Upsert {
19461  ExprList *pUpsertTarget;  /* Optional description of conflict target */
19462  Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
19463  ExprList *pUpsertSet;     /* The SET clause from an ON CONFLICT UPDATE */
19464  Expr *pUpsertWhere;       /* WHERE clause for the ON CONFLICT UPDATE */
19465  Upsert *pNextUpsert;      /* Next ON CONFLICT clause in the list */
19466  u8 isDoUpdate;            /* True for DO UPDATE.  False for DO NOTHING */
19467  u8 isDup;                 /* True if 2nd or later with same pUpsertIdx */
19468  /* Above this point is the parse tree for the ON CONFLICT clauses.
19469  ** The next group of fields stores intermediate data. */
19470  void *pToFree;            /* Free memory when deleting the Upsert object */
19471  /* All fields above are owned by the Upsert object and must be freed
19472  ** when the Upsert is destroyed.  The fields below are used to transfer
19473  ** information from the INSERT processing down into the UPDATE processing
19474  ** while generating code.  The fields below are owned by the INSERT
19475  ** statement and will be freed by INSERT processing. */
19476  Index *pUpsertIdx;        /* UNIQUE constraint specified by pUpsertTarget */
19477  SrcList *pUpsertSrc;      /* Table to be updated */
19478  int regData;              /* First register holding array of VALUES */
19479  int iDataCur;             /* Index of the data cursor */
19480  int iIdxCur;              /* Index of the first index cursor */
19481};
19482
19483/*
19484** An instance of the following structure contains all information
19485** needed to generate code for a single SELECT statement.
19486**
19487** See the header comment on the computeLimitRegisters() routine for a
19488** detailed description of the meaning of the iLimit and iOffset fields.
19489**
19490** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
19491** These addresses must be stored so that we can go back and fill in
19492** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
19493** the number of columns in P2 can be computed at the same time
19494** as the OP_OpenEphm instruction is coded because not
19495** enough information about the compound query is known at that point.
19496** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
19497** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
19498** sequences for the ORDER BY clause.
19499*/
19500struct Select {
19501  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
19502  LogEst nSelectRow;     /* Estimated number of result rows */
19503  u32 selFlags;          /* Various SF_* values */
19504  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
19505  u32 selId;             /* Unique identifier number for this SELECT */
19506  int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
19507  ExprList *pEList;      /* The fields of the result */
19508  SrcList *pSrc;         /* The FROM clause */
19509  Expr *pWhere;          /* The WHERE clause */
19510  ExprList *pGroupBy;    /* The GROUP BY clause */
19511  Expr *pHaving;         /* The HAVING clause */
19512  ExprList *pOrderBy;    /* The ORDER BY clause */
19513  Select *pPrior;        /* Prior select in a compound select statement */
19514  Select *pNext;         /* Next select to the left in a compound */
19515  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
19516  With *pWith;           /* WITH clause attached to this select. Or NULL. */
19517#ifndef SQLITE_OMIT_WINDOWFUNC
19518  Window *pWin;          /* List of window functions */
19519  Window *pWinDefn;      /* List of named window definitions */
19520#endif
19521};
19522
19523/*
19524** Allowed values for Select.selFlags.  The "SF" prefix stands for
19525** "Select Flag".
19526**
19527** Value constraints (all checked via assert())
19528**     SF_HasAgg      == NC_HasAgg
19529**     SF_MinMaxAgg   == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX
19530**     SF_OrderByReqd == NC_OrderAgg      == SQLITE_FUNC_ANYORDER
19531**     SF_FixedLimit  == WHERE_USE_LIMIT
19532*/
19533#define SF_Distinct      0x0000001 /* Output should be DISTINCT */
19534#define SF_All           0x0000002 /* Includes the ALL keyword */
19535#define SF_Resolved      0x0000004 /* Identifiers have been resolved */
19536#define SF_Aggregate     0x0000008 /* Contains agg functions or a GROUP BY */
19537#define SF_HasAgg        0x0000010 /* Contains aggregate functions */
19538#define SF_UsesEphemeral 0x0000020 /* Uses the OpenEphemeral opcode */
19539#define SF_Expanded      0x0000040 /* sqlite3SelectExpand() called on this */
19540#define SF_HasTypeInfo   0x0000080 /* FROM subqueries have Table metadata */
19541#define SF_Compound      0x0000100 /* Part of a compound query */
19542#define SF_Values        0x0000200 /* Synthesized from VALUES clause */
19543#define SF_MultiValue    0x0000400 /* Single VALUES term with multiple rows */
19544#define SF_NestedFrom    0x0000800 /* Part of a parenthesized FROM clause */
19545#define SF_MinMaxAgg     0x0001000 /* Aggregate containing min() or max() */
19546#define SF_Recursive     0x0002000 /* The recursive part of a recursive CTE */
19547#define SF_FixedLimit    0x0004000 /* nSelectRow set by a constant LIMIT */
19548#define SF_MaybeConvert  0x0008000 /* Need convertCompoundSelectToSubquery() */
19549#define SF_Converted     0x0010000 /* By convertCompoundSelectToSubquery() */
19550#define SF_IncludeHidden 0x0020000 /* Include hidden columns in output */
19551#define SF_ComplexResult 0x0040000 /* Result contains subquery or function */
19552#define SF_WhereBegin    0x0080000 /* Really a WhereBegin() call.  Debug Only */
19553#define SF_WinRewrite    0x0100000 /* Window function rewrite accomplished */
19554#define SF_View          0x0200000 /* SELECT statement is a view */
19555#define SF_NoopOrderBy   0x0400000 /* ORDER BY is ignored for this query */
19556#define SF_UFSrcCheck    0x0800000 /* Check pSrc as required by UPDATE...FROM */
19557#define SF_PushDown      0x1000000 /* Modified by WHERE-clause push-down opt */
19558#define SF_MultiPart     0x2000000 /* Has multiple incompatible PARTITIONs */
19559#define SF_CopyCte       0x4000000 /* SELECT statement is a copy of a CTE */
19560#define SF_OrderByReqd   0x8000000 /* The ORDER BY clause may not be omitted */
19561#define SF_UpdateFrom   0x10000000 /* Query originates with UPDATE FROM */
19562#define SF_Correlated   0x20000000 /* True if references the outer context */
19563
19564/* True if S exists and has SF_NestedFrom */
19565#define IsNestedFrom(S) ((S)!=0 && ((S)->selFlags&SF_NestedFrom)!=0)
19566
19567/*
19568** The results of a SELECT can be distributed in several ways, as defined
19569** by one of the following macros.  The "SRT" prefix means "SELECT Result
19570** Type".
19571**
19572**     SRT_Union       Store results as a key in a temporary index
19573**                     identified by pDest->iSDParm.
19574**
19575**     SRT_Except      Remove results from the temporary index pDest->iSDParm.
19576**
19577**     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
19578**                     set is not empty.
19579**
19580**     SRT_Discard     Throw the results away.  This is used by SELECT
19581**                     statements within triggers whose only purpose is
19582**                     the side-effects of functions.
19583**
19584**     SRT_Output      Generate a row of output (using the OP_ResultRow
19585**                     opcode) for each row in the result set.
19586**
19587**     SRT_Mem         Only valid if the result is a single column.
19588**                     Store the first column of the first result row
19589**                     in register pDest->iSDParm then abandon the rest
19590**                     of the query.  This destination implies "LIMIT 1".
19591**
19592**     SRT_Set         The result must be a single column.  Store each
19593**                     row of result as the key in table pDest->iSDParm.
19594**                     Apply the affinity pDest->affSdst before storing
19595**                     results.  Used to implement "IN (SELECT ...)".
19596**
19597**     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
19598**                     the result there. The cursor is left open after
19599**                     returning.  This is like SRT_Table except that
19600**                     this destination uses OP_OpenEphemeral to create
19601**                     the table first.
19602**
19603**     SRT_Coroutine   Generate a co-routine that returns a new row of
19604**                     results each time it is invoked.  The entry point
19605**                     of the co-routine is stored in register pDest->iSDParm
19606**                     and the result row is stored in pDest->nDest registers
19607**                     starting with pDest->iSdst.
19608**
19609**     SRT_Table       Store results in temporary table pDest->iSDParm.
19610**     SRT_Fifo        This is like SRT_EphemTab except that the table
19611**                     is assumed to already be open.  SRT_Fifo has
19612**                     the additional property of being able to ignore
19613**                     the ORDER BY clause.
19614**
19615**     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
19616**                     But also use temporary table pDest->iSDParm+1 as
19617**                     a record of all prior results and ignore any duplicate
19618**                     rows.  Name means:  "Distinct Fifo".
19619**
19620**     SRT_Queue       Store results in priority queue pDest->iSDParm (really
19621**                     an index).  Append a sequence number so that all entries
19622**                     are distinct.
19623**
19624**     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
19625**                     the same record has never been stored before.  The
19626**                     index at pDest->iSDParm+1 hold all prior stores.
19627**
19628**     SRT_Upfrom      Store results in the temporary table already opened by
19629**                     pDest->iSDParm. If (pDest->iSDParm<0), then the temp
19630**                     table is an intkey table - in this case the first
19631**                     column returned by the SELECT is used as the integer
19632**                     key. If (pDest->iSDParm>0), then the table is an index
19633**                     table. (pDest->iSDParm) is the number of key columns in
19634**                     each index record in this case.
19635*/
19636#define SRT_Union        1  /* Store result as keys in an index */
19637#define SRT_Except       2  /* Remove result from a UNION index */
19638#define SRT_Exists       3  /* Store 1 if the result is not empty */
19639#define SRT_Discard      4  /* Do not save the results anywhere */
19640#define SRT_DistFifo     5  /* Like SRT_Fifo, but unique results only */
19641#define SRT_DistQueue    6  /* Like SRT_Queue, but unique results only */
19642
19643/* The DISTINCT clause is ignored for all of the above.  Not that
19644** IgnorableDistinct() implies IgnorableOrderby() */
19645#define IgnorableDistinct(X) ((X->eDest)<=SRT_DistQueue)
19646
19647#define SRT_Queue        7  /* Store result in an queue */
19648#define SRT_Fifo         8  /* Store result as data with an automatic rowid */
19649
19650/* The ORDER BY clause is ignored for all of the above */
19651#define IgnorableOrderby(X) ((X->eDest)<=SRT_Fifo)
19652
19653#define SRT_Output       9  /* Output each row of result */
19654#define SRT_Mem         10  /* Store result in a memory cell */
19655#define SRT_Set         11  /* Store results as keys in an index */
19656#define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
19657#define SRT_Coroutine   13  /* Generate a single row of result */
19658#define SRT_Table       14  /* Store result as data with an automatic rowid */
19659#define SRT_Upfrom      15  /* Store result as data with rowid */
19660
19661/*
19662** An instance of this object describes where to put of the results of
19663** a SELECT statement.
19664*/
19665struct SelectDest {
19666  u8 eDest;            /* How to dispose of the results.  One of SRT_* above. */
19667  int iSDParm;         /* A parameter used by the eDest disposal method */
19668  int iSDParm2;        /* A second parameter for the eDest disposal method */
19669  int iSdst;           /* Base register where results are written */
19670  int nSdst;           /* Number of registers allocated */
19671  char *zAffSdst;      /* Affinity used for SRT_Set */
19672  ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
19673};
19674
19675/*
19676** During code generation of statements that do inserts into AUTOINCREMENT
19677** tables, the following information is attached to the Table.u.autoInc.p
19678** pointer of each autoincrement table to record some side information that
19679** the code generator needs.  We have to keep per-table autoincrement
19680** information in case inserts are done within triggers.  Triggers do not
19681** normally coordinate their activities, but we do need to coordinate the
19682** loading and saving of autoincrement information.
19683*/
19684struct AutoincInfo {
19685  AutoincInfo *pNext;   /* Next info block in a list of them all */
19686  Table *pTab;          /* Table this info block refers to */
19687  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
19688  int regCtr;           /* Memory register holding the rowid counter */
19689};
19690
19691/*
19692** At least one instance of the following structure is created for each
19693** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
19694** statement. All such objects are stored in the linked list headed at
19695** Parse.pTriggerPrg and deleted once statement compilation has been
19696** completed.
19697**
19698** A Vdbe sub-program that implements the body and WHEN clause of trigger
19699** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
19700** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
19701** The Parse.pTriggerPrg list never contains two entries with the same
19702** values for both pTrigger and orconf.
19703**
19704** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
19705** accessed (or set to 0 for triggers fired as a result of INSERT
19706** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
19707** a mask of new.* columns used by the program.
19708*/
19709struct TriggerPrg {
19710  Trigger *pTrigger;      /* Trigger this program was coded from */
19711  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
19712  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
19713  int orconf;             /* Default ON CONFLICT policy */
19714  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
19715};
19716
19717/*
19718** The yDbMask datatype for the bitmask of all attached databases.
19719*/
19720#if SQLITE_MAX_ATTACHED>30
19721  typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
19722# define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
19723# define DbMaskZero(M)      memset((M),0,sizeof(M))
19724# define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
19725# define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
19726# define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
19727#else
19728  typedef unsigned int yDbMask;
19729# define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
19730# define DbMaskZero(M)      ((M)=0)
19731# define DbMaskSet(M,I)     ((M)|=(((yDbMask)1)<<(I)))
19732# define DbMaskAllZero(M)   ((M)==0)
19733# define DbMaskNonZero(M)   ((M)!=0)
19734#endif
19735
19736/*
19737** For each index X that has as one of its arguments either an expression
19738** or the name of a virtual generated column, and if X is in scope such that
19739** the value of the expression can simply be read from the index, then
19740** there is an instance of this object on the Parse.pIdxExpr list.
19741**
19742** During code generation, while generating code to evaluate expressions,
19743** this list is consulted and if a matching expression is found, the value
19744** is read from the index rather than being recomputed.
19745*/
19746struct IndexedExpr {
19747  Expr *pExpr;            /* The expression contained in the index */
19748  int iDataCur;           /* The data cursor associated with the index */
19749  int iIdxCur;            /* The index cursor */
19750  int iIdxCol;            /* The index column that contains value of pExpr */
19751  u8 bMaybeNullRow;       /* True if we need an OP_IfNullRow check */
19752  u8 aff;                 /* Affinity of the pExpr expression */
19753  IndexedExpr *pIENext;   /* Next in a list of all indexed expressions */
19754#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
19755  const char *zIdxName;   /* Name of index, used only for bytecode comments */
19756#endif
19757};
19758
19759/*
19760** An instance of the ParseCleanup object specifies an operation that
19761** should be performed after parsing to deallocation resources obtained
19762** during the parse and which are no longer needed.
19763*/
19764struct ParseCleanup {
19765  ParseCleanup *pNext;               /* Next cleanup task */
19766  void *pPtr;                        /* Pointer to object to deallocate */
19767  void (*xCleanup)(sqlite3*,void*);  /* Deallocation routine */
19768};
19769
19770/*
19771** An SQL parser context.  A copy of this structure is passed through
19772** the parser and down into all the parser action routine in order to
19773** carry around information that is global to the entire parse.
19774**
19775** The structure is divided into two parts.  When the parser and code
19776** generate call themselves recursively, the first part of the structure
19777** is constant but the second part is reset at the beginning and end of
19778** each recursion.
19779**
19780** The nTableLock and aTableLock variables are only used if the shared-cache
19781** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
19782** used to store the set of table-locks required by the statement being
19783** compiled. Function sqlite3TableLock() is used to add entries to the
19784** list.
19785*/
19786struct Parse {
19787  sqlite3 *db;         /* The main database structure */
19788  char *zErrMsg;       /* An error message */
19789  Vdbe *pVdbe;         /* An engine for executing database bytecode */
19790  int rc;              /* Return code from execution */
19791  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
19792  u8 checkSchema;      /* Causes schema cookie check after an error */
19793  u8 nested;           /* Number of nested calls to the parser/code generator */
19794  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
19795  u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
19796  u8 mayAbort;         /* True if statement may throw an ABORT exception */
19797  u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
19798  u8 okConstFactor;    /* OK to factor out constants */
19799  u8 disableLookaside; /* Number of times lookaside has been disabled */
19800  u8 prepFlags;        /* SQLITE_PREPARE_* flags */
19801  u8 withinRJSubrtn;   /* Nesting level for RIGHT JOIN body subroutines */
19802  u8 bHasWith;         /* True if statement contains WITH */
19803#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
19804  u8 earlyCleanup;     /* OOM inside sqlite3ParserAddCleanup() */
19805#endif
19806#ifdef SQLITE_DEBUG
19807  u8 ifNotExists;      /* Might be true if IF NOT EXISTS.  Assert()s only */
19808#endif
19809  int nRangeReg;       /* Size of the temporary register block */
19810  int iRangeReg;       /* First register in temporary register block */
19811  int nErr;            /* Number of errors seen */
19812  int nTab;            /* Number of previously allocated VDBE cursors */
19813  int nMem;            /* Number of memory cells used so far */
19814  int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */
19815  int iSelfTab;        /* Table associated with an index on expr, or negative
19816                       ** of the base register during check-constraint eval */
19817  int nLabel;          /* The *negative* of the number of labels used */
19818  int nLabelAlloc;     /* Number of slots in aLabel */
19819  int *aLabel;         /* Space to hold the labels */
19820  ExprList *pConstExpr;/* Constant expressions */
19821  IndexedExpr *pIdxEpr;/* List of expressions used by active indexes */
19822  IndexedExpr *pIdxPartExpr; /* Exprs constrained by index WHERE clauses */
19823  Token constraintName;/* Name of the constraint currently being parsed */
19824  yDbMask writeMask;   /* Start a write transaction on these databases */
19825  yDbMask cookieMask;  /* Bitmask of schema verified databases */
19826  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
19827  int regRoot;         /* Register holding root page number for new objects */
19828  int nMaxArg;         /* Max args passed to user function by sub-program */
19829  int nSelect;         /* Number of SELECT stmts. Counter for Select.selId */
19830#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
19831  u32 nProgressSteps;  /* xProgress steps taken during sqlite3_prepare() */
19832#endif
19833#ifndef SQLITE_OMIT_SHARED_CACHE
19834  int nTableLock;        /* Number of locks in aTableLock */
19835  TableLock *aTableLock; /* Required table locks for shared-cache mode */
19836#endif
19837  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
19838  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
19839  Table *pTriggerTab;  /* Table triggers are being coded for */
19840  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
19841  ParseCleanup *pCleanup;   /* List of cleanup operations to run after parse */
19842  union {
19843    int addrCrTab;         /* Address of OP_CreateBtree on CREATE TABLE */
19844    Returning *pReturning; /* The RETURNING clause */
19845  } u1;
19846  u32 oldmask;         /* Mask of old.* columns referenced */
19847  u32 newmask;         /* Mask of new.* columns referenced */
19848  LogEst nQueryLoop;   /* Est number of iterations of a query (10*log2(N)) */
19849  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
19850  u8 bReturning;       /* Coding a RETURNING trigger */
19851  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
19852  u8 disableTriggers;  /* True to disable triggers */
19853
19854  /**************************************************************************
19855  ** Fields above must be initialized to zero.  The fields that follow,
19856  ** down to the beginning of the recursive section, do not need to be
19857  ** initialized as they will be set before being used.  The boundary is
19858  ** determined by offsetof(Parse,aTempReg).
19859  **************************************************************************/
19860
19861  int aTempReg[8];        /* Holding area for temporary registers */
19862  Parse *pOuterParse;     /* Outer Parse object when nested */
19863  Token sNameToken;       /* Token with unqualified schema object name */
19864
19865  /************************************************************************
19866  ** Above is constant between recursions.  Below is reset before and after
19867  ** each recursion.  The boundary between these two regions is determined
19868  ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
19869  ** first field in the recursive region.
19870  ************************************************************************/
19871
19872  Token sLastToken;       /* The last token parsed */
19873  ynVar nVar;               /* Number of '?' variables seen in the SQL so far */
19874  u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
19875  u8 explain;               /* True if the EXPLAIN flag is found on the query */
19876  u8 eParseMode;            /* PARSE_MODE_XXX constant */
19877#ifndef SQLITE_OMIT_VIRTUALTABLE
19878  int nVtabLock;            /* Number of virtual tables to lock */
19879#endif
19880  int nHeight;              /* Expression tree height of current sub-select */
19881#ifndef SQLITE_OMIT_EXPLAIN
19882  int addrExplain;          /* Address of current OP_Explain opcode */
19883#endif
19884  VList *pVList;            /* Mapping between variable names and numbers */
19885  Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
19886  const char *zTail;        /* All SQL text past the last semicolon parsed */
19887  Table *pNewTable;         /* A table being constructed by CREATE TABLE */
19888  Index *pNewIndex;         /* An index being constructed by CREATE INDEX.
19889                            ** Also used to hold redundant UNIQUE constraints
19890                            ** during a RENAME COLUMN */
19891  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
19892  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
19893#ifndef SQLITE_OMIT_VIRTUALTABLE
19894  Token sArg;               /* Complete text of a module argument */
19895  Table **apVtabLock;       /* Pointer to virtual tables needing locking */
19896#endif
19897  With *pWith;              /* Current WITH clause, or NULL */
19898#ifndef SQLITE_OMIT_ALTERTABLE
19899  RenameToken *pRename;     /* Tokens subject to renaming by ALTER TABLE */
19900#endif
19901};
19902
19903/* Allowed values for Parse.eParseMode
19904*/
19905#define PARSE_MODE_NORMAL        0
19906#define PARSE_MODE_DECLARE_VTAB  1
19907#define PARSE_MODE_RENAME        2
19908#define PARSE_MODE_UNMAP         3
19909
19910/*
19911** Sizes and pointers of various parts of the Parse object.
19912*/
19913#define PARSE_HDR(X)  (((char*)(X))+offsetof(Parse,zErrMsg))
19914#define PARSE_HDR_SZ (offsetof(Parse,aTempReg)-offsetof(Parse,zErrMsg)) /* Recursive part w/o aColCache*/
19915#define PARSE_RECURSE_SZ offsetof(Parse,sLastToken)    /* Recursive part */
19916#define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
19917#define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ)  /* Pointer to tail */
19918
19919/*
19920** Return true if currently inside an sqlite3_declare_vtab() call.
19921*/
19922#ifdef SQLITE_OMIT_VIRTUALTABLE
19923  #define IN_DECLARE_VTAB 0
19924#else
19925  #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)
19926#endif
19927
19928#if defined(SQLITE_OMIT_ALTERTABLE)
19929  #define IN_RENAME_OBJECT 0
19930#else
19931  #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME)
19932#endif
19933
19934#if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)
19935  #define IN_SPECIAL_PARSE 0
19936#else
19937  #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)
19938#endif
19939
19940/*
19941** An instance of the following structure can be declared on a stack and used
19942** to save the Parse.zAuthContext value so that it can be restored later.
19943*/
19944struct AuthContext {
19945  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
19946  Parse *pParse;              /* The Parse structure */
19947};
19948
19949/*
19950** Bitfield flags for P5 value in various opcodes.
19951**
19952** Value constraints (enforced via assert()):
19953**    OPFLAG_LENGTHARG    == SQLITE_FUNC_LENGTH
19954**    OPFLAG_TYPEOFARG    == SQLITE_FUNC_TYPEOF
19955**    OPFLAG_BULKCSR      == BTREE_BULKLOAD
19956**    OPFLAG_SEEKEQ       == BTREE_SEEK_EQ
19957**    OPFLAG_FORDELETE    == BTREE_FORDELETE
19958**    OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
19959**    OPFLAG_AUXDELETE    == BTREE_AUXDELETE
19960*/
19961#define OPFLAG_NCHANGE       0x01    /* OP_Insert: Set to update db->nChange */
19962                                     /* Also used in P2 (not P5) of OP_Delete */
19963#define OPFLAG_NOCHNG        0x01    /* OP_VColumn nochange for UPDATE */
19964#define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
19965#define OPFLAG_LASTROWID     0x20    /* Set to update db->lastRowid */
19966#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
19967#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
19968#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
19969#define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */
19970#define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
19971#define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
19972#define OPFLAG_BYTELENARG    0xc0    /* OP_Column only for octet_length() */
19973#define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
19974#define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */
19975#define OPFLAG_FORDELETE     0x08    /* OP_Open should use BTREE_FORDELETE */
19976#define OPFLAG_P2ISREG       0x10    /* P2 to OP_Open** is a register number */
19977#define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
19978#define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete/Insert: save cursor pos */
19979#define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */
19980#define OPFLAG_NOCHNG_MAGIC  0x6d    /* OP_MakeRecord: serialtype 10 is ok */
19981#define OPFLAG_PREFORMAT     0x80    /* OP_Insert uses preformatted cell */
19982
19983/*
19984** Each trigger present in the database schema is stored as an instance of
19985** struct Trigger.
19986**
19987** Pointers to instances of struct Trigger are stored in two ways.
19988** 1. In the "trigHash" hash table (part of the sqlite3* that represents the
19989**    database). This allows Trigger structures to be retrieved by name.
19990** 2. All triggers associated with a single table form a linked list, using the
19991**    pNext member of struct Trigger. A pointer to the first element of the
19992**    linked list is stored as the "pTrigger" member of the associated
19993**    struct Table.
19994**
19995** The "step_list" member points to the first element of a linked list
19996** containing the SQL statements specified as the trigger program.
19997*/
19998struct Trigger {
19999  char *zName;            /* The name of the trigger                        */
20000  char *table;            /* The table or view to which the trigger applies */
20001  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
20002  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
20003  u8 bReturning;          /* This trigger implements a RETURNING clause */
20004  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
20005  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
20006                             the <column-list> is stored here */
20007  Schema *pSchema;        /* Schema containing the trigger */
20008  Schema *pTabSchema;     /* Schema containing the table */
20009  TriggerStep *step_list; /* Link list of trigger program steps             */
20010  Trigger *pNext;         /* Next trigger associated with the table */
20011};
20012
20013/*
20014** A trigger is either a BEFORE or an AFTER trigger.  The following constants
20015** determine which.
20016**
20017** If there are multiple triggers, you might of some BEFORE and some AFTER.
20018** In that cases, the constants below can be ORed together.
20019*/
20020#define TRIGGER_BEFORE  1
20021#define TRIGGER_AFTER   2
20022
20023/*
20024** An instance of struct TriggerStep is used to store a single SQL statement
20025** that is a part of a trigger-program.
20026**
20027** Instances of struct TriggerStep are stored in a singly linked list (linked
20028** using the "pNext" member) referenced by the "step_list" member of the
20029** associated struct Trigger instance. The first element of the linked list is
20030** the first step of the trigger-program.
20031**
20032** The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
20033** "SELECT" statement. The meanings of the other members is determined by the
20034** value of "op" as follows:
20035**
20036** (op == TK_INSERT)
20037** orconf    -> stores the ON CONFLICT algorithm
20038** pSelect   -> The content to be inserted - either a SELECT statement or
20039**              a VALUES clause.
20040** zTarget   -> Dequoted name of the table to insert into.
20041** pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
20042**              statement, then this stores the column-names to be
20043**              inserted into.
20044** pUpsert   -> The ON CONFLICT clauses for an Upsert
20045**
20046** (op == TK_DELETE)
20047** zTarget   -> Dequoted name of the table to delete from.
20048** pWhere    -> The WHERE clause of the DELETE statement if one is specified.
20049**              Otherwise NULL.
20050**
20051** (op == TK_UPDATE)
20052** zTarget   -> Dequoted name of the table to update.
20053** pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
20054**              Otherwise NULL.
20055** pExprList -> A list of the columns to update and the expressions to update
20056**              them to. See sqlite3Update() documentation of "pChanges"
20057**              argument.
20058**
20059** (op == TK_SELECT)
20060** pSelect   -> The SELECT statement
20061**
20062** (op == TK_RETURNING)
20063** pExprList -> The list of expressions that follow the RETURNING keyword.
20064**
20065*/
20066struct TriggerStep {
20067  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT,
20068                       ** or TK_RETURNING */
20069  u8 orconf;           /* OE_Rollback etc. */
20070  Trigger *pTrig;      /* The trigger that this step is a part of */
20071  Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
20072  char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
20073  SrcList *pFrom;      /* FROM clause for UPDATE statement (if any) */
20074  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
20075  ExprList *pExprList; /* SET clause for UPDATE, or RETURNING clause */
20076  IdList *pIdList;     /* Column names for INSERT */
20077  Upsert *pUpsert;     /* Upsert clauses on an INSERT */
20078  char *zSpan;         /* Original SQL text of this command */
20079  TriggerStep *pNext;  /* Next in the link-list */
20080  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
20081};
20082
20083/*
20084** Information about a RETURNING clause
20085*/
20086struct Returning {
20087  Parse *pParse;        /* The parse that includes the RETURNING clause */
20088  ExprList *pReturnEL;  /* List of expressions to return */
20089  Trigger retTrig;      /* The transient trigger that implements RETURNING */
20090  TriggerStep retTStep; /* The trigger step */
20091  int iRetCur;          /* Transient table holding RETURNING results */
20092  int nRetCol;          /* Number of in pReturnEL after expansion */
20093  int iRetReg;          /* Register array for holding a row of RETURNING */
20094  char zName[40];       /* Name of trigger: "sqlite_returning_%p" */
20095};
20096
20097/*
20098** An objected used to accumulate the text of a string where we
20099** do not necessarily know how big the string will be in the end.
20100*/
20101struct sqlite3_str {
20102  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
20103  char *zText;         /* The string collected so far */
20104  u32  nAlloc;         /* Amount of space allocated in zText */
20105  u32  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */
20106  u32  nChar;          /* Length of the string so far */
20107  u8   accError;       /* SQLITE_NOMEM or SQLITE_TOOBIG */
20108  u8   printfFlags;    /* SQLITE_PRINTF flags below */
20109};
20110#define SQLITE_PRINTF_INTERNAL 0x01  /* Internal-use-only converters allowed */
20111#define SQLITE_PRINTF_SQLFUNC  0x02  /* SQL function arguments to VXPrintf */
20112#define SQLITE_PRINTF_MALLOCED 0x04  /* True if xText is allocated space */
20113
20114#define isMalloced(X)  (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
20115
20116/*
20117** The following object is the header for an "RCStr" or "reference-counted
20118** string".  An RCStr is passed around and used like any other char*
20119** that has been dynamically allocated.  The important interface
20120** differences:
20121**
20122**   1.  RCStr strings are reference counted.  They are deallocated
20123**       when the reference count reaches zero.
20124**
20125**   2.  Use sqlite3RCStrUnref() to free an RCStr string rather than
20126**       sqlite3_free()
20127**
20128**   3.  Make a (read-only) copy of a read-only RCStr string using
20129**       sqlite3RCStrRef().
20130**
20131** "String" is in the name, but an RCStr object can also be used to hold
20132** binary data.
20133*/
20134struct RCStr {
20135  u64 nRCRef;            /* Number of references */
20136  /* Total structure size should be a multiple of 8 bytes for alignment */
20137};
20138
20139/*
20140** A pointer to this structure is used to communicate information
20141** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
20142*/
20143typedef struct {
20144  sqlite3 *db;        /* The database being initialized */
20145  char **pzErrMsg;    /* Error message stored here */
20146  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
20147  int rc;             /* Result code stored here */
20148  u32 mInitFlags;     /* Flags controlling error messages */
20149  u32 nInitRow;       /* Number of rows processed */
20150  Pgno mxPage;        /* Maximum page number.  0 for no limit. */
20151} InitData;
20152
20153/*
20154** Allowed values for mInitFlags
20155*/
20156#define INITFLAG_AlterMask     0x0003  /* Types of ALTER */
20157#define INITFLAG_AlterRename   0x0001  /* Reparse after a RENAME */
20158#define INITFLAG_AlterDrop     0x0002  /* Reparse after a DROP COLUMN */
20159#define INITFLAG_AlterAdd      0x0003  /* Reparse after an ADD COLUMN */
20160
20161/* Tuning parameters are set using SQLITE_TESTCTRL_TUNE and are controlled
20162** on debug-builds of the CLI using ".testctrl tune ID VALUE".  Tuning
20163** parameters are for temporary use during development, to help find
20164** optimal values for parameters in the query planner.  The should not
20165** be used on trunk check-ins.  They are a temporary mechanism available
20166** for transient development builds only.
20167**
20168** Tuning parameters are numbered starting with 1.
20169*/
20170#define SQLITE_NTUNE  6             /* Should be zero for all trunk check-ins */
20171#ifdef SQLITE_DEBUG
20172# define Tuning(X)  (sqlite3Config.aTune[(X)-1])
20173#else
20174# define Tuning(X)  0
20175#endif
20176
20177/*
20178** Structure containing global configuration data for the SQLite library.
20179**
20180** This structure also contains some state information.
20181*/
20182struct Sqlite3Config {
20183  int bMemstat;                     /* True to enable memory status */
20184  u8 bCoreMutex;                    /* True to enable core mutexing */
20185  u8 bFullMutex;                    /* True to enable full mutexing */
20186  u8 bOpenUri;                      /* True to interpret filenames as URIs */
20187  u8 bUseCis;                       /* Use covering indices for full-scans */
20188  u8 bSmallMalloc;                  /* Avoid large memory allocations if true */
20189  u8 bExtraSchemaChecks;            /* Verify type,name,tbl_name in schema */
20190  u8 bUseLongDouble;                /* Make use of long double */
20191#ifdef SQLITE_DEBUG
20192  u8 bJsonSelfcheck;                /* Double-check JSON parsing */
20193#endif
20194  int mxStrlen;                     /* Maximum string length */
20195  int neverCorrupt;                 /* Database is always well-formed */
20196  int szLookaside;                  /* Default lookaside buffer size */
20197  int nLookaside;                   /* Default lookaside buffer count */
20198  int nStmtSpill;                   /* Stmt-journal spill-to-disk threshold */
20199  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
20200  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
20201  sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
20202  void *pHeap;                      /* Heap storage space */
20203  int nHeap;                        /* Size of pHeap[] */
20204  int mnReq, mxReq;                 /* Min and max heap requests sizes */
20205  sqlite3_int64 szMmap;             /* mmap() space per open file */
20206  sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
20207  void *pPage;                      /* Page cache memory */
20208  int szPage;                       /* Size of each page in pPage[] */
20209  int nPage;                        /* Number of pages in pPage[] */
20210  int mxParserStack;                /* maximum depth of the parser stack */
20211  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
20212  u32 szPma;                        /* Maximum Sorter PMA size */
20213  /* The above might be initialized to non-zero.  The following need to always
20214  ** initially be zero, however. */
20215  int isInit;                       /* True after initialization has finished */
20216  int inProgress;                   /* True while initialization in progress */
20217  int isMutexInit;                  /* True after mutexes are initialized */
20218  int isMallocInit;                 /* True after malloc is initialized */
20219  int isPCacheInit;                 /* True after malloc is initialized */
20220  int nRefInitMutex;                /* Number of users of pInitMutex */
20221  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
20222  void (*xLog)(void*,int,const char*); /* Function for logging */
20223  void *pLogArg;                       /* First argument to xLog() */
20224#ifdef SQLITE_ENABLE_SQLLOG
20225  void(*xSqllog)(void*,sqlite3*,const char*, int);
20226  void *pSqllogArg;
20227#endif
20228#ifdef SQLITE_VDBE_COVERAGE
20229  /* The following callback (if not NULL) is invoked on every VDBE branch
20230  ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
20231  */
20232  void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx);  /* Callback */
20233  void *pVdbeBranchArg;                                     /* 1st argument */
20234#endif
20235#ifndef SQLITE_OMIT_DESERIALIZE
20236  sqlite3_int64 mxMemdbSize;        /* Default max memdb size */
20237#endif
20238#ifndef SQLITE_UNTESTABLE
20239  int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
20240#endif
20241#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
20242  u32 mNoVisibleRowid;              /* TF_NoVisibleRowid if the ROWID_IN_VIEW
20243                                    ** feature is disabled.  0 if rowids can
20244                                    ** occur in views. */
20245#endif
20246  int bLocaltimeFault;              /* True to fail localtime() calls */
20247  int (*xAltLocaltime)(const void*,void*); /* Alternative localtime() routine */
20248  int iOnceResetThreshold;          /* When to reset OP_Once counters */
20249  u32 szSorterRef;                  /* Min size in bytes to use sorter-refs */
20250  unsigned int iPrngSeed;           /* Alternative fixed seed for the PRNG */
20251  /* vvvv--- must be last ---vvv */
20252#ifdef SQLITE_DEBUG
20253  sqlite3_int64 aTune[SQLITE_NTUNE]; /* Tuning parameters */
20254#endif
20255};
20256
20257/*
20258** This macro is used inside of assert() statements to indicate that
20259** the assert is only valid on a well-formed database.  Instead of:
20260**
20261**     assert( X );
20262**
20263** One writes:
20264**
20265**     assert( X || CORRUPT_DB );
20266**
20267** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
20268** that the database is definitely corrupt, only that it might be corrupt.
20269** For most test cases, CORRUPT_DB is set to false using a special
20270** sqlite3_test_control().  This enables assert() statements to prove
20271** things that are always true for well-formed databases.
20272*/
20273#define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
20274
20275/*
20276** Context pointer passed down through the tree-walk.
20277*/
20278struct Walker {
20279  Parse *pParse;                            /* Parser context.  */
20280  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
20281  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
20282  void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
20283  int walkerDepth;                          /* Number of subqueries */
20284  u16 eCode;                                /* A small processing code */
20285  u16 mWFlags;                              /* Use-dependent flags */
20286  union {                                   /* Extra data for callback */
20287    NameContext *pNC;                         /* Naming context */
20288    int n;                                    /* A counter */
20289    int iCur;                                 /* A cursor number */
20290    SrcList *pSrcList;                        /* FROM clause */
20291    struct CCurHint *pCCurHint;               /* Used by codeCursorHint() */
20292    struct RefSrcList *pRefSrcList;           /* sqlite3ReferencesSrcList() */
20293    int *aiCol;                               /* array of column indexes */
20294    struct IdxCover *pIdxCover;               /* Check for index coverage */
20295    ExprList *pGroupBy;                       /* GROUP BY clause */
20296    Select *pSelect;                          /* HAVING to WHERE clause ctx */
20297    struct WindowRewrite *pRewrite;           /* Window rewrite context */
20298    struct WhereConst *pConst;                /* WHERE clause constants */
20299    struct RenameCtx *pRename;                /* RENAME COLUMN context */
20300    struct Table *pTab;                       /* Table of generated column */
20301    struct CoveringIndexCheck *pCovIdxCk;     /* Check for covering index */
20302    SrcItem *pSrcItem;                        /* A single FROM clause item */
20303    DbFixer *pFix;                            /* See sqlite3FixSelect() */
20304    Mem *aMem;                                /* See sqlite3BtreeCursorHint() */
20305  } u;
20306};
20307
20308/*
20309** The following structure contains information used by the sqliteFix...
20310** routines as they walk the parse tree to make database references
20311** explicit.
20312*/
20313struct DbFixer {
20314  Parse *pParse;      /* The parsing context.  Error messages written here */
20315  Walker w;           /* Walker object */
20316  Schema *pSchema;    /* Fix items to this schema */
20317  u8 bTemp;           /* True for TEMP schema entries */
20318  const char *zDb;    /* Make sure all objects are contained in this database */
20319  const char *zType;  /* Type of the container - used for error messages */
20320  const Token *pName; /* Name of the container - used for error messages */
20321};
20322
20323/* Forward declarations */
20324SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
20325SQLITE_PRIVATE int sqlite3WalkExprNN(Walker*, Expr*);
20326SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
20327SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
20328SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
20329SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
20330SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
20331SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
20332SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
20333SQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker*,Select*);
20334SQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker*,Select*);
20335SQLITE_PRIVATE void sqlite3WalkWinDefnDummyCallback(Walker*,Select*);
20336
20337#ifdef SQLITE_DEBUG
20338SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
20339#endif
20340
20341#ifndef SQLITE_OMIT_CTE
20342SQLITE_PRIVATE void sqlite3SelectPopWith(Walker*, Select*);
20343#else
20344# define sqlite3SelectPopWith 0
20345#endif
20346
20347/*
20348** Return code from the parse-tree walking primitives and their
20349** callbacks.
20350*/
20351#define WRC_Continue    0   /* Continue down into children */
20352#define WRC_Prune       1   /* Omit children but continue walking siblings */
20353#define WRC_Abort       2   /* Abandon the tree walk */
20354
20355/*
20356** A single common table expression
20357*/
20358struct Cte {
20359  char *zName;            /* Name of this CTE */
20360  ExprList *pCols;        /* List of explicit column names, or NULL */
20361  Select *pSelect;        /* The definition of this CTE */
20362  const char *zCteErr;    /* Error message for circular references */
20363  CteUse *pUse;           /* Usage information for this CTE */
20364  u8 eM10d;               /* The MATERIALIZED flag */
20365};
20366
20367/*
20368** Allowed values for the materialized flag (eM10d):
20369*/
20370#define M10d_Yes       0  /* AS MATERIALIZED */
20371#define M10d_Any       1  /* Not specified.  Query planner's choice */
20372#define M10d_No        2  /* AS NOT MATERIALIZED */
20373
20374/*
20375** An instance of the With object represents a WITH clause containing
20376** one or more CTEs (common table expressions).
20377*/
20378struct With {
20379  int nCte;               /* Number of CTEs in the WITH clause */
20380  int bView;              /* Belongs to the outermost Select of a view */
20381  With *pOuter;           /* Containing WITH clause, or NULL */
20382  Cte a[1];               /* For each CTE in the WITH clause.... */
20383};
20384
20385/*
20386** The Cte object is not guaranteed to persist for the entire duration
20387** of code generation.  (The query flattener or other parser tree
20388** edits might delete it.)  The following object records information
20389** about each Common Table Expression that must be preserved for the
20390** duration of the parse.
20391**
20392** The CteUse objects are freed using sqlite3ParserAddCleanup() rather
20393** than sqlite3SelectDelete(), which is what enables them to persist
20394** until the end of code generation.
20395*/
20396struct CteUse {
20397  int nUse;              /* Number of users of this CTE */
20398  int addrM9e;           /* Start of subroutine to compute materialization */
20399  int regRtn;            /* Return address register for addrM9e subroutine */
20400  int iCur;              /* Ephemeral table holding the materialization */
20401  LogEst nRowEst;        /* Estimated number of rows in the table */
20402  u8 eM10d;              /* The MATERIALIZED flag */
20403};
20404
20405
20406/* Client data associated with sqlite3_set_clientdata() and
20407** sqlite3_get_clientdata().
20408*/
20409struct DbClientData {
20410  DbClientData *pNext;        /* Next in a linked list */
20411  void *pData;                /* The data */
20412  void (*xDestructor)(void*); /* Destructor.  Might be NULL */
20413  char zName[1];              /* Name of this client data. MUST BE LAST */
20414};
20415
20416#ifdef SQLITE_DEBUG
20417/*
20418** An instance of the TreeView object is used for printing the content of
20419** data structures on sqlite3DebugPrintf() using a tree-like view.
20420*/
20421struct TreeView {
20422  int iLevel;             /* Which level of the tree we are on */
20423  u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
20424};
20425#endif /* SQLITE_DEBUG */
20426
20427/*
20428** This object is used in various ways, most (but not all) related to window
20429** functions.
20430**
20431**   (1) A single instance of this structure is attached to the
20432**       the Expr.y.pWin field for each window function in an expression tree.
20433**       This object holds the information contained in the OVER clause,
20434**       plus additional fields used during code generation.
20435**
20436**   (2) All window functions in a single SELECT form a linked-list
20437**       attached to Select.pWin.  The Window.pFunc and Window.pExpr
20438**       fields point back to the expression that is the window function.
20439**
20440**   (3) The terms of the WINDOW clause of a SELECT are instances of this
20441**       object on a linked list attached to Select.pWinDefn.
20442**
20443**   (4) For an aggregate function with a FILTER clause, an instance
20444**       of this object is stored in Expr.y.pWin with eFrmType set to
20445**       TK_FILTER. In this case the only field used is Window.pFilter.
20446**
20447** The uses (1) and (2) are really the same Window object that just happens
20448** to be accessible in two different ways.  Use case (3) are separate objects.
20449*/
20450struct Window {
20451  char *zName;            /* Name of window (may be NULL) */
20452  char *zBase;            /* Name of base window for chaining (may be NULL) */
20453  ExprList *pPartition;   /* PARTITION BY clause */
20454  ExprList *pOrderBy;     /* ORDER BY clause */
20455  u8 eFrmType;            /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */
20456  u8 eStart;              /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
20457  u8 eEnd;                /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
20458  u8 bImplicitFrame;      /* True if frame was implicitly specified */
20459  u8 eExclude;            /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */
20460  Expr *pStart;           /* Expression for "<expr> PRECEDING" */
20461  Expr *pEnd;             /* Expression for "<expr> FOLLOWING" */
20462  Window **ppThis;        /* Pointer to this object in Select.pWin list */
20463  Window *pNextWin;       /* Next window function belonging to this SELECT */
20464  Expr *pFilter;          /* The FILTER expression */
20465  FuncDef *pWFunc;        /* The function */
20466  int iEphCsr;            /* Partition buffer or Peer buffer */
20467  int regAccum;           /* Accumulator */
20468  int regResult;          /* Interim result */
20469  int csrApp;             /* Function cursor (used by min/max) */
20470  int regApp;             /* Function register (also used by min/max) */
20471  int regPart;            /* Array of registers for PARTITION BY values */
20472  Expr *pOwner;           /* Expression object this window is attached to */
20473  int nBufferCol;         /* Number of columns in buffer table */
20474  int iArgCol;            /* Offset of first argument for this function */
20475  int regOne;             /* Register containing constant value 1 */
20476  int regStartRowid;
20477  int regEndRowid;
20478  u8 bExprArgs;           /* Defer evaluation of window function arguments
20479                          ** due to the SQLITE_SUBTYPE flag */
20480};
20481
20482SQLITE_PRIVATE Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList *pRow);
20483SQLITE_PRIVATE void sqlite3MultiValuesEnd(Parse *pParse, Select *pVal);
20484
20485#ifndef SQLITE_OMIT_WINDOWFUNC
20486SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3*, Window*);
20487SQLITE_PRIVATE void sqlite3WindowUnlinkFromSelect(Window*);
20488SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p);
20489SQLITE_PRIVATE Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8);
20490SQLITE_PRIVATE void sqlite3WindowAttach(Parse*, Expr*, Window*);
20491SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin);
20492SQLITE_PRIVATE int sqlite3WindowCompare(const Parse*, const Window*, const Window*, int);
20493SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Select*);
20494SQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
20495SQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);
20496SQLITE_PRIVATE void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);
20497SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);
20498SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p);
20499SQLITE_PRIVATE void sqlite3WindowFunctions(void);
20500SQLITE_PRIVATE void sqlite3WindowChain(Parse*, Window*, Window*);
20501SQLITE_PRIVATE Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*);
20502#else
20503# define sqlite3WindowDelete(a,b)
20504# define sqlite3WindowFunctions()
20505# define sqlite3WindowAttach(a,b,c)
20506#endif
20507
20508/*
20509** Assuming zIn points to the first byte of a UTF-8 character,
20510** advance zIn to point to the first byte of the next UTF-8 character.
20511*/
20512#define SQLITE_SKIP_UTF8(zIn) {                        \
20513  if( (*(zIn++))>=0xc0 ){                              \
20514    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
20515  }                                                    \
20516}
20517
20518/*
20519** The SQLITE_*_BKPT macros are substitutes for the error codes with
20520** the same name but without the _BKPT suffix.  These macros invoke
20521** routines that report the line-number on which the error originated
20522** using sqlite3_log().  The routines also provide a convenient place
20523** to set a debugger breakpoint.
20524*/
20525SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);
20526SQLITE_PRIVATE int sqlite3CorruptError(int);
20527SQLITE_PRIVATE int sqlite3MisuseError(int);
20528SQLITE_PRIVATE int sqlite3CantopenError(int);
20529#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
20530#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
20531#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
20532#ifdef SQLITE_DEBUG
20533SQLITE_PRIVATE   int sqlite3NomemError(int);
20534SQLITE_PRIVATE   int sqlite3IoerrnomemError(int);
20535# define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
20536# define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
20537#else
20538# define SQLITE_NOMEM_BKPT SQLITE_NOMEM
20539# define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
20540#endif
20541#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
20542SQLITE_PRIVATE   int sqlite3CorruptPgnoError(int,Pgno);
20543# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
20544#else
20545# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
20546#endif
20547
20548/*
20549** FTS3 and FTS4 both require virtual table support
20550*/
20551#if defined(SQLITE_OMIT_VIRTUALTABLE)
20552# undef SQLITE_ENABLE_FTS3
20553# undef SQLITE_ENABLE_FTS4
20554#endif
20555
20556/*
20557** FTS4 is really an extension for FTS3.  It is enabled using the
20558** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
20559** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
20560*/
20561#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
20562# define SQLITE_ENABLE_FTS3 1
20563#endif
20564
20565/*
20566** The ctype.h header is needed for non-ASCII systems.  It is also
20567** needed by FTS3 when FTS3 is included in the amalgamation.
20568*/
20569#if !defined(SQLITE_ASCII) || \
20570    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
20571# include <ctype.h>
20572#endif
20573
20574/*
20575** The following macros mimic the standard library functions toupper(),
20576** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
20577** sqlite versions only work for ASCII characters, regardless of locale.
20578*/
20579#ifdef SQLITE_ASCII
20580# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
20581# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
20582# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
20583# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
20584# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
20585# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
20586# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
20587# define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
20588# define sqlite3JsonId1(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x42)
20589# define sqlite3JsonId2(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x46)
20590#else
20591# define sqlite3Toupper(x)   toupper((unsigned char)(x))
20592# define sqlite3Isspace(x)   isspace((unsigned char)(x))
20593# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
20594# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
20595# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
20596# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
20597# define sqlite3Tolower(x)   tolower((unsigned char)(x))
20598# define sqlite3Isquote(x)   ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
20599# define sqlite3JsonId1(x)   (sqlite3IsIdChar(x)&&(x)<'0')
20600# define sqlite3JsonId2(x)   sqlite3IsIdChar(x)
20601#endif
20602SQLITE_PRIVATE int sqlite3IsIdChar(u8);
20603
20604/*
20605** Internal function prototypes
20606*/
20607SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
20608SQLITE_PRIVATE int sqlite3Strlen30(const char*);
20609#define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)
20610SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
20611#define sqlite3StrNICmp sqlite3_strnicmp
20612
20613SQLITE_PRIVATE int sqlite3MallocInit(void);
20614SQLITE_PRIVATE void sqlite3MallocEnd(void);
20615SQLITE_PRIVATE void *sqlite3Malloc(u64);
20616SQLITE_PRIVATE void *sqlite3MallocZero(u64);
20617SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
20618SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
20619SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
20620SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
20621SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
20622SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
20623SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
20624SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
20625SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
20626SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
20627SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
20628SQLITE_PRIVATE void sqlite3DbNNFreeNN(sqlite3*, void*);
20629SQLITE_PRIVATE int sqlite3MallocSize(const void*);
20630SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, const void*);
20631SQLITE_PRIVATE void *sqlite3PageMalloc(int);
20632SQLITE_PRIVATE void sqlite3PageFree(void*);
20633SQLITE_PRIVATE void sqlite3MemSetDefault(void);
20634#ifndef SQLITE_UNTESTABLE
20635SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
20636#endif
20637SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
20638
20639/*
20640** On systems with ample stack space and that support alloca(), make
20641** use of alloca() to obtain space for large automatic objects.  By default,
20642** obtain space from malloc().
20643**
20644** The alloca() routine never returns NULL.  This will cause code paths
20645** that deal with sqlite3StackAlloc() failures to be unreachable.
20646*/
20647#ifdef SQLITE_USE_ALLOCA
20648# define sqlite3StackAllocRaw(D,N)   alloca(N)
20649# define sqlite3StackAllocRawNN(D,N) alloca(N)
20650# define sqlite3StackFree(D,P)
20651# define sqlite3StackFreeNN(D,P)
20652#else
20653# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
20654# define sqlite3StackAllocRawNN(D,N) sqlite3DbMallocRawNN(D,N)
20655# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
20656# define sqlite3StackFreeNN(D,P)     sqlite3DbFreeNN(D,P)
20657#endif
20658
20659/* Do not allow both MEMSYS5 and MEMSYS3 to be defined together.  If they
20660** are, disable MEMSYS3
20661*/
20662#ifdef SQLITE_ENABLE_MEMSYS5
20663SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
20664#undef SQLITE_ENABLE_MEMSYS3
20665#endif
20666#ifdef SQLITE_ENABLE_MEMSYS3
20667SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
20668#endif
20669
20670
20671#ifndef SQLITE_MUTEX_OMIT
20672SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
20673SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
20674SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
20675SQLITE_PRIVATE   int sqlite3MutexInit(void);
20676SQLITE_PRIVATE   int sqlite3MutexEnd(void);
20677#endif
20678#if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
20679SQLITE_PRIVATE   void sqlite3MemoryBarrier(void);
20680#else
20681# define sqlite3MemoryBarrier()
20682#endif
20683
20684SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
20685SQLITE_PRIVATE void sqlite3StatusUp(int, int);
20686SQLITE_PRIVATE void sqlite3StatusDown(int, int);
20687SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
20688SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
20689
20690/* Access to mutexes used by sqlite3_status() */
20691SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
20692SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
20693
20694#if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
20695SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);
20696#else
20697# define sqlite3MutexWarnOnContention(x)
20698#endif
20699
20700#ifndef SQLITE_OMIT_FLOATING_POINT
20701# define EXP754 (((u64)0x7ff)<<52)
20702# define MAN754 ((((u64)1)<<52)-1)
20703# define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0)
20704# define IsOvfl(X) (((X)&EXP754)==EXP754)
20705SQLITE_PRIVATE   int sqlite3IsNaN(double);
20706SQLITE_PRIVATE   int sqlite3IsOverflow(double);
20707#else
20708# define IsNaN(X)             0
20709# define sqlite3IsNaN(X)      0
20710# define sqlite3IsOVerflow(X) 0
20711#endif
20712
20713/*
20714** An instance of the following structure holds information about SQL
20715** functions arguments that are the parameters to the printf() function.
20716*/
20717struct PrintfArguments {
20718  int nArg;                /* Total number of arguments */
20719  int nUsed;               /* Number of arguments used so far */
20720  sqlite3_value **apArg;   /* The argument values */
20721};
20722
20723/*
20724** An instance of this object receives the decoding of a floating point
20725** value into an approximate decimal representation.
20726*/
20727struct FpDecode {
20728  char sign;           /* '+' or '-' */
20729  char isSpecial;      /* 1: Infinity  2: NaN */
20730  int n;               /* Significant digits in the decode */
20731  int iDP;             /* Location of the decimal point */
20732  char *z;             /* Start of significant digits */
20733  char zBuf[24];       /* Storage for significant digits */
20734};
20735
20736SQLITE_PRIVATE void sqlite3FpDecode(FpDecode*,double,int,int);
20737SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
20738SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
20739#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
20740SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
20741#endif
20742#if defined(SQLITE_TEST)
20743SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
20744#endif
20745
20746#if defined(SQLITE_DEBUG)
20747SQLITE_PRIVATE   void sqlite3TreeViewLine(TreeView*, const char *zFormat, ...);
20748SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
20749SQLITE_PRIVATE   void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
20750SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
20751SQLITE_PRIVATE   void sqlite3TreeViewBareIdList(TreeView*, const IdList*, const char*);
20752SQLITE_PRIVATE   void sqlite3TreeViewIdList(TreeView*, const IdList*, u8, const char*);
20753SQLITE_PRIVATE   void sqlite3TreeViewColumnList(TreeView*, const Column*, int, u8);
20754SQLITE_PRIVATE   void sqlite3TreeViewSrcList(TreeView*, const SrcList*);
20755SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
20756SQLITE_PRIVATE   void sqlite3TreeViewWith(TreeView*, const With*, u8);
20757SQLITE_PRIVATE   void sqlite3TreeViewUpsert(TreeView*, const Upsert*, u8);
20758#if TREETRACE_ENABLED
20759SQLITE_PRIVATE   void sqlite3TreeViewDelete(const With*, const SrcList*, const Expr*,
20760                             const ExprList*,const Expr*, const Trigger*);
20761SQLITE_PRIVATE   void sqlite3TreeViewInsert(const With*, const SrcList*,
20762                             const IdList*, const Select*, const ExprList*,
20763                             int, const Upsert*, const Trigger*);
20764SQLITE_PRIVATE   void sqlite3TreeViewUpdate(const With*, const SrcList*, const ExprList*,
20765                             const Expr*, int, const ExprList*, const Expr*,
20766                             const Upsert*, const Trigger*);
20767#endif
20768#ifndef SQLITE_OMIT_TRIGGER
20769SQLITE_PRIVATE   void sqlite3TreeViewTriggerStep(TreeView*, const TriggerStep*, u8, u8);
20770SQLITE_PRIVATE   void sqlite3TreeViewTrigger(TreeView*, const Trigger*, u8, u8);
20771#endif
20772#ifndef SQLITE_OMIT_WINDOWFUNC
20773SQLITE_PRIVATE   void sqlite3TreeViewWindow(TreeView*, const Window*, u8);
20774SQLITE_PRIVATE   void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);
20775#endif
20776SQLITE_PRIVATE   void sqlite3ShowExpr(const Expr*);
20777SQLITE_PRIVATE   void sqlite3ShowExprList(const ExprList*);
20778SQLITE_PRIVATE   void sqlite3ShowIdList(const IdList*);
20779SQLITE_PRIVATE   void sqlite3ShowSrcList(const SrcList*);
20780SQLITE_PRIVATE   void sqlite3ShowSelect(const Select*);
20781SQLITE_PRIVATE   void sqlite3ShowWith(const With*);
20782SQLITE_PRIVATE   void sqlite3ShowUpsert(const Upsert*);
20783#ifndef SQLITE_OMIT_TRIGGER
20784SQLITE_PRIVATE   void sqlite3ShowTriggerStep(const TriggerStep*);
20785SQLITE_PRIVATE   void sqlite3ShowTriggerStepList(const TriggerStep*);
20786SQLITE_PRIVATE   void sqlite3ShowTrigger(const Trigger*);
20787SQLITE_PRIVATE   void sqlite3ShowTriggerList(const Trigger*);
20788#endif
20789#ifndef SQLITE_OMIT_WINDOWFUNC
20790SQLITE_PRIVATE   void sqlite3ShowWindow(const Window*);
20791SQLITE_PRIVATE   void sqlite3ShowWinFunc(const Window*);
20792#endif
20793#endif
20794
20795SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
20796SQLITE_PRIVATE void sqlite3ProgressCheck(Parse*);
20797SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
20798SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3*,int);
20799SQLITE_PRIVATE void sqlite3Dequote(char*);
20800SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);
20801SQLITE_PRIVATE void sqlite3DequoteToken(Token*);
20802SQLITE_PRIVATE void sqlite3DequoteNumber(Parse*, Expr*);
20803SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
20804SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
20805SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*);
20806SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
20807SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
20808SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
20809SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
20810SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
20811SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
20812SQLITE_PRIVATE void sqlite3TouchRegister(Parse*,int);
20813#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
20814SQLITE_PRIVATE int sqlite3FirstAvailableRegister(Parse*,int);
20815#endif
20816#ifdef SQLITE_DEBUG
20817SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
20818#endif
20819SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
20820SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
20821SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
20822SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
20823SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
20824SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*);
20825SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr*);
20826SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, const Token*, int);
20827SQLITE_PRIVATE void sqlite3ExprAddFunctionOrderBy(Parse*,Expr*,ExprList*);
20828SQLITE_PRIVATE void sqlite3ExprOrderByAggregateError(Parse*,Expr*);
20829SQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,const Expr*,const FuncDef*);
20830SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
20831SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
20832SQLITE_PRIVATE void sqlite3ExprDeleteGeneric(sqlite3*,void*);
20833SQLITE_PRIVATE int sqlite3ExprDeferredDelete(Parse*, Expr*);
20834SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
20835SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
20836SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
20837SQLITE_PRIVATE Select *sqlite3ExprListToValues(Parse*, int, ExprList*);
20838SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int,int);
20839SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,const Token*,int);
20840SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
20841SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
20842SQLITE_PRIVATE void sqlite3ExprListDeleteGeneric(sqlite3*,void*);
20843SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
20844SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index*);
20845SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
20846SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
20847SQLITE_PRIVATE int sqlite3InitOne(sqlite3*, int, char**, u32);
20848SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
20849#ifndef SQLITE_OMIT_VIRTUALTABLE
20850SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
20851#endif
20852SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
20853SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
20854SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
20855SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
20856SQLITE_PRIVATE void sqlite3ColumnSetExpr(Parse*,Table*,Column*,Expr*);
20857SQLITE_PRIVATE Expr *sqlite3ColumnExpr(Table*,Column*);
20858SQLITE_PRIVATE void sqlite3ColumnSetColl(sqlite3*,Column*,const char*zColl);
20859SQLITE_PRIVATE const char *sqlite3ColumnColl(Column*);
20860SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
20861SQLITE_PRIVATE void sqlite3GenerateColumnNames(Parse *pParse, Select *pSelect);
20862SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
20863SQLITE_PRIVATE void sqlite3SubqueryColumnTypes(Parse*,Table*,Select*,char);
20864SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*,char);
20865SQLITE_PRIVATE void sqlite3OpenSchemaTable(Parse *, int);
20866SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
20867SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index*, i16);
20868#ifdef SQLITE_OMIT_GENERATED_COLUMNS
20869# define sqlite3TableColumnToStorage(T,X) (X)  /* No-op pass-through */
20870# define sqlite3StorageColumnToTable(T,X) (X)  /* No-op pass-through */
20871#else
20872SQLITE_PRIVATE   i16 sqlite3TableColumnToStorage(Table*, i16);
20873SQLITE_PRIVATE   i16 sqlite3StorageColumnToTable(Table*, i16);
20874#endif
20875SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
20876#if SQLITE_ENABLE_HIDDEN_COLUMNS
20877SQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);
20878#else
20879# define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
20880#endif
20881SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token,Token);
20882SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
20883SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
20884SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*, const char*, const char*);
20885SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
20886SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
20887SQLITE_PRIVATE void sqlite3AddGenerated(Parse*,Expr*,Token*);
20888SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u32,Select*);
20889SQLITE_PRIVATE void sqlite3AddReturning(Parse*,ExprList*);
20890SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
20891                    sqlite3_vfs**,char**,char **);
20892#define sqlite3CodecQueryParameters(A,B,C) 0
20893SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
20894
20895#ifdef SQLITE_UNTESTABLE
20896# define sqlite3FaultSim(X) SQLITE_OK
20897#else
20898SQLITE_PRIVATE   int sqlite3FaultSim(int);
20899#endif
20900
20901SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
20902SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
20903SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
20904SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
20905SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
20906SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
20907SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
20908#ifndef SQLITE_UNTESTABLE
20909SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
20910#endif
20911
20912SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*);
20913SQLITE_PRIVATE void sqlite3RowSetDelete(void*);
20914SQLITE_PRIVATE void sqlite3RowSetClear(void*);
20915SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
20916SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
20917SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
20918
20919SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
20920
20921#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
20922SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
20923#else
20924# define sqlite3ViewGetColumnNames(A,B) 0
20925#endif
20926
20927#if SQLITE_MAX_ATTACHED>30
20928SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);
20929#endif
20930SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
20931SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
20932SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
20933SQLITE_PRIVATE void sqlite3DeleteTableGeneric(sqlite3*, void*);
20934SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3*, Index*);
20935#ifndef SQLITE_OMIT_AUTOINCREMENT
20936SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
20937SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
20938#else
20939# define sqlite3AutoincrementBegin(X)
20940# define sqlite3AutoincrementEnd(X)
20941#endif
20942SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
20943#ifndef SQLITE_OMIT_GENERATED_COLUMNS
20944SQLITE_PRIVATE   void sqlite3ComputeGeneratedColumns(Parse*, int, Table*);
20945#endif
20946SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
20947SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);
20948SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
20949SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);
20950SQLITE_PRIVATE SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2);
20951SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);
20952SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
20953                                      Token*, Select*, OnOrUsing*);
20954SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
20955SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
20956SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, SrcItem *);
20957SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(Parse*,SrcList*);
20958SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
20959SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
20960SQLITE_PRIVATE void sqlite3ClearOnOrUsing(sqlite3*, OnOrUsing*);
20961SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
20962SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
20963SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
20964                          Expr*, int, int, u8);
20965SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
20966SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
20967SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
20968                         Expr*,ExprList*,u32,Expr*);
20969SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
20970SQLITE_PRIVATE void sqlite3SelectDeleteGeneric(sqlite3*,void*);
20971SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
20972SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, Trigger*);
20973SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
20974#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
20975SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
20976#endif
20977SQLITE_PRIVATE void sqlite3CodeChangeCount(Vdbe*,int,const char*);
20978SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
20979SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
20980                   Upsert*);
20981SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,
20982                             ExprList*,Select*,u16,int);
20983SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
20984SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
20985SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
20986SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
20987SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);
20988SQLITE_PRIVATE void sqlite3WhereMinMaxOptEarlyOut(Vdbe*,WhereInfo*);
20989SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
20990SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
20991SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
20992SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
20993#define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */
20994#define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
20995#define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
20996SQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo*);
20997SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
20998SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
20999SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
21000SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
21001SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
21002#ifndef SQLITE_OMIT_GENERATED_COLUMNS
21003SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Table*, Column*, int);
21004#endif
21005SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
21006SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
21007SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int);
21008SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
21009SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
21010SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
21011#define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
21012#define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
21013#define SQLITE_ECEL_REF      0x04  /* Use ExprList.u.x.iOrderByCol */
21014#define SQLITE_ECEL_OMITREF  0x08  /* Omit if ExprList.u.x.iOrderByCol */
21015SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
21016SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
21017SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
21018SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
21019#define LOCATE_VIEW    0x01
21020#define LOCATE_NOERR   0x02
21021SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
21022SQLITE_PRIVATE const char *sqlite3PreferredTableName(const char*);
21023SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,SrcItem *);
21024SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
21025SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
21026SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
21027SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*,Expr*);
21028SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);
21029SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, const Token*);
21030SQLITE_PRIVATE int sqlite3ExprCompare(const Parse*,const Expr*,const Expr*, int);
21031SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*,Expr*,int);
21032SQLITE_PRIVATE int sqlite3ExprListCompare(const ExprList*,const ExprList*, int);
21033SQLITE_PRIVATE int sqlite3ExprImpliesExpr(const Parse*,const Expr*,const Expr*, int);
21034SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int,int);
21035SQLITE_PRIVATE void sqlite3AggInfoPersistWalkerInit(Walker*,Parse*);
21036SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
21037SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
21038SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
21039SQLITE_PRIVATE int sqlite3ReferencesSrcList(Parse*, Expr*, SrcList*);
21040SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
21041#ifndef SQLITE_UNTESTABLE
21042SQLITE_PRIVATE void sqlite3PrngSaveState(void);
21043SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
21044#endif
21045SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
21046SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
21047SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
21048SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
21049SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
21050SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
21051SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
21052SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
21053SQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char*);
21054SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
21055SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
21056SQLITE_PRIVATE int sqlite3ExprIsConstant(Parse*,Expr*);
21057SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
21058SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
21059SQLITE_PRIVATE int sqlite3ExprIsSingleTableConstraint(Expr*,const SrcList*,int,int);
21060#ifdef SQLITE_ENABLE_CURSOR_HINTS
21061SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
21062#endif
21063SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr*, int*);
21064SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
21065SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
21066SQLITE_PRIVATE int sqlite3IsRowid(const char*);
21067SQLITE_PRIVATE const char *sqlite3RowidAlias(Table *pTab);
21068SQLITE_PRIVATE void sqlite3GenerateRowDelete(
21069    Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
21070SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
21071SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
21072SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
21073SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);
21074SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
21075                                     u8,u8,int,int*,int*,Upsert*);
21076#ifdef SQLITE_ENABLE_NULL_TRIM
21077SQLITE_PRIVATE   void sqlite3SetMakeRecordP5(Vdbe*,Table*);
21078#else
21079# define sqlite3SetMakeRecordP5(A,B)
21080#endif
21081SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
21082SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
21083SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
21084SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
21085SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
21086SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
21087SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
21088SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
21089SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,const Expr*,int);
21090SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,const ExprList*,int);
21091SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,const SrcList*,int);
21092SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,const IdList*);
21093SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,const Select*,int);
21094SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(int,const char*);
21095SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
21096SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
21097SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum*,sqlite3_value*);
21098SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
21099SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
21100SQLITE_PRIVATE void sqlite3RegisterJsonFunctions(void);
21101SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
21102#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
21103SQLITE_PRIVATE   int sqlite3JsonTableFunctions(sqlite3*);
21104#endif
21105SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
21106SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
21107SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
21108SQLITE_PRIVATE With *sqlite3WithDup(sqlite3 *db, With *p);
21109
21110#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
21111SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
21112#endif
21113
21114#ifndef SQLITE_OMIT_TRIGGER
21115SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
21116                           Expr*,int, int);
21117SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
21118SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
21119SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
21120SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
21121SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
21122SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
21123                            int, int, int);
21124SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
21125  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
21126SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
21127SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
21128                                        const char*,const char*);
21129SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,
21130                                        Select*,u8,Upsert*,
21131                                        const char*,const char*);
21132SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,SrcList*,ExprList*,
21133                                        Expr*, u8, const char*,const char*);
21134SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,
21135                                        const char*,const char*);
21136SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
21137SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
21138SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
21139SQLITE_PRIVATE   SrcList *sqlite3TriggerStepSrc(Parse*, TriggerStep*);
21140# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
21141# define sqlite3IsToplevel(p) ((p)->pToplevel==0)
21142#else
21143# define sqlite3TriggersExist(B,C,D,E,F) 0
21144# define sqlite3DeleteTrigger(A,B)
21145# define sqlite3DropTriggerPtr(A,B)
21146# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
21147# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
21148# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
21149# define sqlite3TriggerList(X, Y) 0
21150# define sqlite3ParseToplevel(p) p
21151# define sqlite3IsToplevel(p) 1
21152# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
21153# define sqlite3TriggerStepSrc(A,B) 0
21154#endif
21155
21156SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
21157SQLITE_PRIVATE int sqlite3ColumnIndex(Table *pTab, const char *zCol);
21158SQLITE_PRIVATE void sqlite3SrcItemColumnUsed(SrcItem*,int);
21159SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr*,int,u32);
21160SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
21161SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
21162#ifndef SQLITE_OMIT_AUTHORIZATION
21163SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
21164SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
21165SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
21166SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
21167SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
21168#else
21169# define sqlite3AuthRead(a,b,c,d)
21170# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
21171# define sqlite3AuthContextPush(a,b,c)
21172# define sqlite3AuthContextPop(a)  ((void)(a))
21173#endif
21174SQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName);
21175SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
21176SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
21177SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
21178SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
21179SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
21180SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
21181SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
21182
21183SQLITE_PRIVATE int sqlite3RealSameAsInt(double,sqlite3_int64);
21184SQLITE_PRIVATE i64 sqlite3RealToI64(double);
21185SQLITE_PRIVATE int sqlite3Int64ToText(i64,char*);
21186SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
21187SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
21188SQLITE_PRIVATE int sqlite3GetUInt32(const char*, u32*);
21189SQLITE_PRIVATE int sqlite3Atoi(const char*);
21190#ifndef SQLITE_OMIT_UTF16
21191SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
21192#endif
21193SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
21194SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
21195SQLITE_PRIVATE int sqlite3Utf8ReadLimited(const u8*, int, u32*);
21196SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
21197SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
21198SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
21199SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
21200SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
21201SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
21202SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
21203
21204/*
21205** Routines to read and write variable-length integers.  These used to
21206** be defined locally, but now we use the varint routines in the util.c
21207** file.
21208*/
21209SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
21210SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
21211SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
21212SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
21213
21214/*
21215** The common case is for a varint to be a single byte.  They following
21216** macros handle the common case without a procedure call, but then call
21217** the procedure for larger varints.
21218*/
21219#define getVarint32(A,B)  \
21220  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
21221#define getVarint32NR(A,B) \
21222  B=(u32)*(A);if(B>=0x80)sqlite3GetVarint32((A),(u32*)&(B))
21223#define putVarint32(A,B)  \
21224  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
21225  sqlite3PutVarint((A),(B)))
21226#define getVarint    sqlite3GetVarint
21227#define putVarint    sqlite3PutVarint
21228
21229
21230SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
21231SQLITE_PRIVATE char *sqlite3TableAffinityStr(sqlite3*,const Table*);
21232SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
21233SQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2);
21234SQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity);
21235SQLITE_PRIVATE char sqlite3TableColumnAffinity(const Table*,int);
21236SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr);
21237SQLITE_PRIVATE int sqlite3ExprDataType(const Expr *pExpr);
21238SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
21239SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
21240SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
21241SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
21242SQLITE_PRIVATE void sqlite3ErrorClear(sqlite3*);
21243SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
21244#if !defined(SQLITE_OMIT_BLOB_LITERAL)
21245SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
21246#endif
21247SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
21248SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
21249
21250#if defined(SQLITE_NEED_ERR_NAME)
21251SQLITE_PRIVATE const char *sqlite3ErrName(int);
21252#endif
21253
21254#ifndef SQLITE_OMIT_DESERIALIZE
21255SQLITE_PRIVATE int sqlite3MemdbInit(void);
21256SQLITE_PRIVATE int sqlite3IsMemdb(const sqlite3_vfs*);
21257#else
21258# define sqlite3IsMemdb(X) 0
21259#endif
21260
21261SQLITE_PRIVATE const char *sqlite3ErrStr(int);
21262SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
21263SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
21264SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq*);
21265SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
21266SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8);
21267SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr);
21268SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr);
21269SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const Expr*);
21270SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(const Parse *pParse, Expr*, const Token*, int);
21271SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(const Parse*,Expr*,const char*);
21272SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
21273SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr*);
21274SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
21275SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
21276SQLITE_PRIVATE int sqlite3CheckObjectName(Parse*, const char*,const char*,const char*);
21277SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, i64);
21278SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
21279SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
21280SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
21281SQLITE_PRIVATE int sqlite3AbsInt32(int);
21282#ifdef SQLITE_ENABLE_8_3_NAMES
21283SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
21284#else
21285# define sqlite3FileSuffix3(X,Y)
21286#endif
21287SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
21288
21289SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
21290SQLITE_PRIVATE int sqlite3ValueIsOfClass(const sqlite3_value*, void(*)(void*));
21291SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
21292SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
21293                        void(*)(void*));
21294SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
21295SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
21296#ifndef SQLITE_UNTESTABLE
21297SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context*);
21298#endif
21299SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
21300#ifndef SQLITE_OMIT_UTF16
21301SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
21302#endif
21303SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, const Expr *, u8, u8, sqlite3_value **);
21304SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
21305#ifndef SQLITE_AMALGAMATION
21306SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
21307SQLITE_PRIVATE const char sqlite3StrBINARY[];
21308SQLITE_PRIVATE const unsigned char sqlite3StdTypeLen[];
21309SQLITE_PRIVATE const char sqlite3StdTypeAffinity[];
21310SQLITE_PRIVATE const char *sqlite3StdType[];
21311SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
21312SQLITE_PRIVATE const unsigned char *sqlite3aLTb;
21313SQLITE_PRIVATE const unsigned char *sqlite3aEQb;
21314SQLITE_PRIVATE const unsigned char *sqlite3aGTb;
21315SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
21316SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
21317SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
21318#ifndef SQLITE_OMIT_WSD
21319SQLITE_PRIVATE int sqlite3PendingByte;
21320#endif
21321#endif /* SQLITE_AMALGAMATION */
21322#ifdef VDBE_PROFILE
21323SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;
21324#endif
21325SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, Pgno, Pgno);
21326SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
21327SQLITE_PRIVATE void sqlite3AlterFunctions(void);
21328SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
21329SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);
21330SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
21331SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
21332SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);
21333SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int);
21334SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);
21335SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
21336SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, SrcItem*);
21337SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
21338SQLITE_PRIVATE int sqlite3MatchEName(
21339  const struct ExprList_item*,
21340  const char*,
21341  const char*,
21342  const char*,
21343  int*
21344);
21345SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr*);
21346SQLITE_PRIVATE u8 sqlite3StrIHash(const char*);
21347SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
21348SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
21349SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
21350SQLITE_PRIVATE int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
21351SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
21352SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
21353SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
21354SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
21355SQLITE_PRIVATE void sqlite3AlterDropColumn(Parse*, SrcList*, const Token*);
21356SQLITE_PRIVATE const void *sqlite3RenameTokenMap(Parse*, const void*, const Token*);
21357SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse*, const void *pTo, const void *pFrom);
21358SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse*, Expr*);
21359SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
21360SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
21361SQLITE_PRIVATE char sqlite3AffinityType(const char*, Column*);
21362SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
21363SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
21364SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
21365SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
21366SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
21367SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
21368SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
21369SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
21370SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
21371SQLITE_PRIVATE void sqlite3SchemaClear(void *);
21372SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
21373SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
21374SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
21375SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
21376SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
21377SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
21378SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);
21379SQLITE_PRIVATE const char *sqlite3SelectOpName(int);
21380SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse*, ExprList*);
21381
21382#ifdef SQLITE_DEBUG
21383SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
21384#endif
21385SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
21386  void (*)(sqlite3_context*,int,sqlite3_value **),
21387  void (*)(sqlite3_context*,int,sqlite3_value **),
21388  void (*)(sqlite3_context*),
21389  void (*)(sqlite3_context*),
21390  void (*)(sqlite3_context*,int,sqlite3_value **),
21391  FuncDestructor *pDestructor
21392);
21393SQLITE_PRIVATE void sqlite3NoopDestructor(void*);
21394SQLITE_PRIVATE void *sqlite3OomFault(sqlite3*);
21395SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
21396SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
21397SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
21398
21399SQLITE_PRIVATE char *sqlite3RCStrRef(char*);
21400SQLITE_PRIVATE void sqlite3RCStrUnref(void*);
21401SQLITE_PRIVATE char *sqlite3RCStrNew(u64);
21402SQLITE_PRIVATE char *sqlite3RCStrResize(char*,u64);
21403
21404SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
21405SQLITE_PRIVATE int sqlite3StrAccumEnlarge(StrAccum*, i64);
21406SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
21407SQLITE_PRIVATE void sqlite3StrAccumSetError(StrAccum*, u8);
21408SQLITE_PRIVATE void sqlite3ResultStrAccum(sqlite3_context*,StrAccum*);
21409SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
21410SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
21411SQLITE_PRIVATE void sqlite3RecordErrorByteOffset(sqlite3*,const char*);
21412SQLITE_PRIVATE void sqlite3RecordErrorOffsetOfExpr(sqlite3*,const Expr*);
21413
21414SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
21415SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
21416
21417#ifndef SQLITE_OMIT_SUBQUERY
21418SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
21419#else
21420# define sqlite3ExprCheckIN(x,y) SQLITE_OK
21421#endif
21422
21423#ifdef SQLITE_ENABLE_STAT4
21424SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
21425    Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
21426SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
21427SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
21428SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
21429SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
21430#endif
21431
21432/*
21433** The interface to the LEMON-generated parser
21434*/
21435#ifndef SQLITE_AMALGAMATION
21436SQLITE_PRIVATE   void *sqlite3ParserAlloc(void*(*)(u64), Parse*);
21437SQLITE_PRIVATE   void sqlite3ParserFree(void*, void(*)(void*));
21438#endif
21439SQLITE_PRIVATE void sqlite3Parser(void*, int, Token);
21440SQLITE_PRIVATE int sqlite3ParserFallback(int);
21441#ifdef YYTRACKMAXSTACKDEPTH
21442SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
21443#endif
21444
21445SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
21446#ifndef SQLITE_OMIT_LOAD_EXTENSION
21447SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
21448#else
21449# define sqlite3CloseExtensions(X)
21450#endif
21451
21452#ifndef SQLITE_OMIT_SHARED_CACHE
21453SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, Pgno, u8, const char *);
21454#else
21455  #define sqlite3TableLock(v,w,x,y,z)
21456#endif
21457
21458#ifdef SQLITE_TEST
21459SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
21460#endif
21461
21462#ifdef SQLITE_OMIT_VIRTUALTABLE
21463#  define sqlite3VtabClear(D,T)
21464#  define sqlite3VtabSync(X,Y) SQLITE_OK
21465#  define sqlite3VtabRollback(X)
21466#  define sqlite3VtabCommit(X)
21467#  define sqlite3VtabInSync(db) 0
21468#  define sqlite3VtabLock(X)
21469#  define sqlite3VtabUnlock(X)
21470#  define sqlite3VtabModuleUnref(D,X)
21471#  define sqlite3VtabUnlockList(X)
21472#  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
21473#  define sqlite3GetVTable(X,Y)  ((VTable*)0)
21474#else
21475SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
21476SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
21477SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
21478SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
21479SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
21480SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
21481SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
21482SQLITE_PRIVATE    void sqlite3VtabModuleUnref(sqlite3*,Module*);
21483SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
21484SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
21485SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
21486SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
21487SQLITE_PRIVATE    Module *sqlite3VtabCreateModule(
21488     sqlite3*,
21489     const char*,
21490     const sqlite3_module*,
21491     void*,
21492     void(*)(void*)
21493   );
21494#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
21495#endif
21496SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db);
21497#ifndef SQLITE_OMIT_VIRTUALTABLE
21498SQLITE_PRIVATE   int sqlite3ShadowTableName(sqlite3 *db, const char *zName);
21499SQLITE_PRIVATE   int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);
21500SQLITE_PRIVATE   void sqlite3MarkAllShadowTablesOf(sqlite3*, Table*);
21501#else
21502# define sqlite3ShadowTableName(A,B) 0
21503# define sqlite3IsShadowTableOf(A,B,C) 0
21504# define sqlite3MarkAllShadowTablesOf(A,B)
21505#endif
21506SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
21507SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
21508SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
21509SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
21510SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
21511SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
21512SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
21513SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
21514SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
21515SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
21516SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
21517
21518SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
21519SQLITE_PRIVATE void sqlite3VtabUsesAllSchemas(Parse*);
21520SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
21521SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
21522SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
21523SQLITE_PRIVATE void sqlite3ParseObjectInit(Parse*,sqlite3*);
21524SQLITE_PRIVATE void sqlite3ParseObjectReset(Parse*);
21525SQLITE_PRIVATE void *sqlite3ParserAddCleanup(Parse*,void(*)(sqlite3*,void*),void*);
21526#ifdef SQLITE_ENABLE_NORMALIZE
21527SQLITE_PRIVATE char *sqlite3Normalize(Vdbe*, const char*);
21528#endif
21529SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
21530SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
21531SQLITE_PRIVATE CollSeq *sqlite3ExprCompareCollSeq(Parse*,const Expr*);
21532SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, const Expr*, const Expr*);
21533SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
21534SQLITE_PRIVATE const char *sqlite3JournalModename(int);
21535#ifndef SQLITE_OMIT_WAL
21536SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
21537SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
21538#endif
21539#ifndef SQLITE_OMIT_CTE
21540SQLITE_PRIVATE   Cte *sqlite3CteNew(Parse*,Token*,ExprList*,Select*,u8);
21541SQLITE_PRIVATE   void sqlite3CteDelete(sqlite3*,Cte*);
21542SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Cte*);
21543SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
21544SQLITE_PRIVATE   void sqlite3WithDeleteGeneric(sqlite3*,void*);
21545SQLITE_PRIVATE   With *sqlite3WithPush(Parse*, With*, u8);
21546#else
21547# define sqlite3CteNew(P,T,E,S)   ((void*)0)
21548# define sqlite3CteDelete(D,C)
21549# define sqlite3CteWithAdd(P,W,C) ((void*)0)
21550# define sqlite3WithDelete(x,y)
21551# define sqlite3WithPush(x,y,z) ((void*)0)
21552#endif
21553#ifndef SQLITE_OMIT_UPSERT
21554SQLITE_PRIVATE   Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*,Upsert*);
21555SQLITE_PRIVATE   void sqlite3UpsertDelete(sqlite3*,Upsert*);
21556SQLITE_PRIVATE   Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
21557SQLITE_PRIVATE   int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*,Upsert*);
21558SQLITE_PRIVATE   void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
21559SQLITE_PRIVATE   Upsert *sqlite3UpsertOfIndex(Upsert*,Index*);
21560SQLITE_PRIVATE   int sqlite3UpsertNextIsIPK(Upsert*);
21561#else
21562#define sqlite3UpsertNew(u,v,w,x,y,z) ((Upsert*)0)
21563#define sqlite3UpsertDelete(x,y)
21564#define sqlite3UpsertDup(x,y)         ((Upsert*)0)
21565#define sqlite3UpsertOfIndex(x,y)     ((Upsert*)0)
21566#define sqlite3UpsertNextIsIPK(x)     0
21567#endif
21568
21569
21570/* Declarations for functions in fkey.c. All of these are replaced by
21571** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
21572** key functionality is available. If OMIT_TRIGGER is defined but
21573** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
21574** this case foreign keys are parsed, but no other functionality is
21575** provided (enforcement of FK constraints requires the triggers sub-system).
21576*/
21577#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
21578SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
21579SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
21580SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
21581SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
21582SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
21583SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
21584SQLITE_PRIVATE   void sqlite3FkClearTriggerCache(sqlite3*,int);
21585#else
21586  #define sqlite3FkActions(a,b,c,d,e,f)
21587  #define sqlite3FkCheck(a,b,c,d,e,f)
21588  #define sqlite3FkDropTable(a,b,c)
21589  #define sqlite3FkOldmask(a,b)         0
21590  #define sqlite3FkRequired(a,b,c,d)    0
21591  #define sqlite3FkReferences(a)        0
21592  #define sqlite3FkClearTriggerCache(a,b)
21593#endif
21594#ifndef SQLITE_OMIT_FOREIGN_KEY
21595SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
21596SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
21597#else
21598  #define sqlite3FkDelete(a,b)
21599  #define sqlite3FkLocateIndex(a,b,c,d,e)
21600#endif
21601
21602
21603/*
21604** Available fault injectors.  Should be numbered beginning with 0.
21605*/
21606#define SQLITE_FAULTINJECTOR_MALLOC     0
21607#define SQLITE_FAULTINJECTOR_COUNT      1
21608
21609/*
21610** The interface to the code in fault.c used for identifying "benign"
21611** malloc failures. This is only present if SQLITE_UNTESTABLE
21612** is not defined.
21613*/
21614#ifndef SQLITE_UNTESTABLE
21615SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
21616SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
21617#else
21618  #define sqlite3BeginBenignMalloc()
21619  #define sqlite3EndBenignMalloc()
21620#endif
21621
21622/*
21623** Allowed return values from sqlite3FindInIndex()
21624*/
21625#define IN_INDEX_ROWID        1   /* Search the rowid of the table */
21626#define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
21627#define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
21628#define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
21629#define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
21630/*
21631** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
21632*/
21633#define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
21634#define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
21635#define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
21636SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*);
21637
21638SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
21639SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
21640#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
21641 || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
21642SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
21643#endif
21644
21645SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
21646SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
21647
21648SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
21649#if SQLITE_MAX_EXPR_DEPTH>0
21650SQLITE_PRIVATE   int sqlite3SelectExprHeight(const Select *);
21651SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
21652#else
21653  #define sqlite3SelectExprHeight(x) 0
21654  #define sqlite3ExprCheckHeight(x,y)
21655#endif
21656SQLITE_PRIVATE void sqlite3ExprSetErrorOffset(Expr*,int);
21657
21658SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
21659SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
21660
21661#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
21662SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
21663SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
21664SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
21665#else
21666  #define sqlite3ConnectionBlocked(x,y)
21667  #define sqlite3ConnectionUnlocked(x)
21668  #define sqlite3ConnectionClosed(x)
21669#endif
21670
21671#ifdef SQLITE_DEBUG
21672SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
21673#endif
21674#if defined(YYCOVERAGE)
21675SQLITE_PRIVATE   int sqlite3ParserCoverage(FILE*);
21676#endif
21677
21678/*
21679** If the SQLITE_ENABLE IOTRACE exists then the global variable
21680** sqlite3IoTrace is a pointer to a printf-like routine used to
21681** print I/O tracing messages.
21682*/
21683#ifdef SQLITE_ENABLE_IOTRACE
21684# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
21685SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
21686SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
21687#else
21688# define IOTRACE(A)
21689# define sqlite3VdbeIOTraceSql(X)
21690#endif
21691
21692/*
21693** These routines are available for the mem2.c debugging memory allocator
21694** only.  They are used to verify that different "types" of memory
21695** allocations are properly tracked by the system.
21696**
21697** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
21698** the MEMTYPE_* macros defined below.  The type must be a bitmask with
21699** a single bit set.
21700**
21701** sqlite3MemdebugHasType() returns true if any of the bits in its second
21702** argument match the type set by the previous sqlite3MemdebugSetType().
21703** sqlite3MemdebugHasType() is intended for use inside assert() statements.
21704**
21705** sqlite3MemdebugNoType() returns true if none of the bits in its second
21706** argument match the type set by the previous sqlite3MemdebugSetType().
21707**
21708** Perhaps the most important point is the difference between MEMTYPE_HEAP
21709** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
21710** it might have been allocated by lookaside, except the allocation was
21711** too large or lookaside was already full.  It is important to verify
21712** that allocations that might have been satisfied by lookaside are not
21713** passed back to non-lookaside free() routines.  Asserts such as the
21714** example above are placed on the non-lookaside free() routines to verify
21715** this constraint.
21716**
21717** All of this is no-op for a production build.  It only comes into
21718** play when the SQLITE_MEMDEBUG compile-time option is used.
21719*/
21720#ifdef SQLITE_MEMDEBUG
21721SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
21722SQLITE_PRIVATE   int sqlite3MemdebugHasType(const void*,u8);
21723SQLITE_PRIVATE   int sqlite3MemdebugNoType(const void*,u8);
21724#else
21725# define sqlite3MemdebugSetType(X,Y)  /* no-op */
21726# define sqlite3MemdebugHasType(X,Y)  1
21727# define sqlite3MemdebugNoType(X,Y)   1
21728#endif
21729#define MEMTYPE_HEAP       0x01  /* General heap allocations */
21730#define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
21731#define MEMTYPE_PCACHE     0x04  /* Page cache allocations */
21732
21733/*
21734** Threading interface
21735*/
21736#if SQLITE_MAX_WORKER_THREADS>0
21737SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
21738SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
21739#endif
21740
21741#if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
21742SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
21743#endif
21744#if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
21745SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
21746#endif
21747
21748SQLITE_PRIVATE int sqlite3ExprVectorSize(const Expr *pExpr);
21749SQLITE_PRIVATE int sqlite3ExprIsVector(const Expr *pExpr);
21750SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
21751SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int,int);
21752SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
21753
21754#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
21755SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
21756#endif
21757
21758#if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
21759SQLITE_PRIVATE int sqlite3KvvfsInit(void);
21760#endif
21761
21762#if defined(VDBE_PROFILE) \
21763 || defined(SQLITE_PERFORMANCE_TRACE) \
21764 || defined(SQLITE_ENABLE_STMT_SCANSTATUS)
21765SQLITE_PRIVATE sqlite3_uint64 sqlite3Hwtime(void);
21766#endif
21767
21768#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
21769# define IS_STMT_SCANSTATUS(db) (db->flags & SQLITE_StmtScanStatus)
21770#else
21771# define IS_STMT_SCANSTATUS(db) 0
21772#endif
21773
21774#endif /* SQLITEINT_H */
21775
21776/************** End of sqliteInt.h *******************************************/
21777/************** Begin file os_common.h ***************************************/
21778/*
21779** 2004 May 22
21780**
21781** The author disclaims copyright to this source code.  In place of
21782** a legal notice, here is a blessing:
21783**
21784**    May you do good and not evil.
21785**    May you find forgiveness for yourself and forgive others.
21786**    May you share freely, never taking more than you give.
21787**
21788******************************************************************************
21789**
21790** This file contains macros and a little bit of code that is common to
21791** all of the platform-specific files (os_*.c) and is #included into those
21792** files.
21793**
21794** This file should be #included by the os_*.c files only.  It is not a
21795** general purpose header file.
21796*/
21797#ifndef _OS_COMMON_H_
21798#define _OS_COMMON_H_
21799
21800/*
21801** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21802** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21803** switch.  The following code should catch this problem at compile-time.
21804*/
21805#ifdef MEMORY_DEBUG
21806# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21807#endif
21808
21809/*
21810** Macros for performance tracing.  Normally turned off.  Only works
21811** on i486 hardware.
21812*/
21813#ifdef SQLITE_PERFORMANCE_TRACE
21814
21815static sqlite_uint64 g_start;
21816static sqlite_uint64 g_elapsed;
21817#define TIMER_START       g_start=sqlite3Hwtime()
21818#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21819#define TIMER_ELAPSED     g_elapsed
21820#else
21821#define TIMER_START
21822#define TIMER_END
21823#define TIMER_ELAPSED     ((sqlite_uint64)0)
21824#endif
21825
21826/*
21827** If we compile with the SQLITE_TEST macro set, then the following block
21828** of code will give us the ability to simulate a disk I/O error.  This
21829** is used for testing the I/O recovery logic.
21830*/
21831#if defined(SQLITE_TEST)
21832SQLITE_API extern int sqlite3_io_error_hit;
21833SQLITE_API extern int sqlite3_io_error_hardhit;
21834SQLITE_API extern int sqlite3_io_error_pending;
21835SQLITE_API extern int sqlite3_io_error_persist;
21836SQLITE_API extern int sqlite3_io_error_benign;
21837SQLITE_API extern int sqlite3_diskfull_pending;
21838SQLITE_API extern int sqlite3_diskfull;
21839#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21840#define SimulateIOError(CODE)  \
21841  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21842       || sqlite3_io_error_pending-- == 1 )  \
21843              { local_ioerr(); CODE; }
21844static void local_ioerr(){
21845  IOTRACE(("IOERR\n"));
21846  sqlite3_io_error_hit++;
21847  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21848}
21849#define SimulateDiskfullError(CODE) \
21850   if( sqlite3_diskfull_pending ){ \
21851     if( sqlite3_diskfull_pending == 1 ){ \
21852       local_ioerr(); \
21853       sqlite3_diskfull = 1; \
21854       sqlite3_io_error_hit = 1; \
21855       CODE; \
21856     }else{ \
21857       sqlite3_diskfull_pending--; \
21858     } \
21859   }
21860#else
21861#define SimulateIOErrorBenign(X)
21862#define SimulateIOError(A)
21863#define SimulateDiskfullError(A)
21864#endif /* defined(SQLITE_TEST) */
21865
21866/*
21867** When testing, keep a count of the number of open files.
21868*/
21869#if defined(SQLITE_TEST)
21870SQLITE_API extern int sqlite3_open_file_count;
21871#define OpenCounter(X)  sqlite3_open_file_count+=(X)
21872#else
21873#define OpenCounter(X)
21874#endif /* defined(SQLITE_TEST) */
21875
21876#endif /* !defined(_OS_COMMON_H_) */
21877
21878/************** End of os_common.h *******************************************/
21879/************** Begin file ctime.c *******************************************/
21880/* DO NOT EDIT!
21881** This file is automatically generated by the script in the canonical
21882** SQLite source tree at tool/mkctimec.tcl.
21883**
21884** To modify this header, edit any of the various lists in that script
21885** which specify categories of generated conditionals in this file.
21886*/
21887
21888/*
21889** 2010 February 23
21890**
21891** The author disclaims copyright to this source code.  In place of
21892** a legal notice, here is a blessing:
21893**
21894**    May you do good and not evil.
21895**    May you find forgiveness for yourself and forgive others.
21896**    May you share freely, never taking more than you give.
21897**
21898*************************************************************************
21899**
21900** This file implements routines used to report what compile-time options
21901** SQLite was built with.
21902*/
21903#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */
21904
21905/*
21906** Include the configuration header output by 'configure' if we're using the
21907** autoconf-based build
21908*/
21909#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
21910/* #include "sqlite_cfg.h" */
21911#define SQLITECONFIG_H 1
21912#endif
21913
21914/* These macros are provided to "stringify" the value of the define
21915** for those options in which the value is meaningful. */
21916#define CTIMEOPT_VAL_(opt) #opt
21917#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
21918
21919/* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This
21920** option requires a separate macro because legal values contain a single
21921** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */
21922#define CTIMEOPT_VAL2_(opt1,opt2) #opt1 "," #opt2
21923#define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt)
21924/* #include "sqliteInt.h" */
21925
21926/*
21927** An array of names of all compile-time options.  This array should
21928** be sorted A-Z.
21929**
21930** This array looks large, but in a typical installation actually uses
21931** only a handful of compile-time options, so most times this array is usually
21932** rather short and uses little memory space.
21933*/
21934static const char * const sqlite3azCompileOpt[] = {
21935
21936#ifdef SQLITE_32BIT_ROWID
21937  "32BIT_ROWID",
21938#endif
21939#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
21940  "4_BYTE_ALIGNED_MALLOC",
21941#endif
21942#ifdef SQLITE_ALLOW_COVERING_INDEX_SCAN
21943# if SQLITE_ALLOW_COVERING_INDEX_SCAN != 1
21944  "ALLOW_COVERING_INDEX_SCAN=" CTIMEOPT_VAL(SQLITE_ALLOW_COVERING_INDEX_SCAN),
21945# endif
21946#endif
21947#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
21948  "ALLOW_ROWID_IN_VIEW",
21949#endif
21950#ifdef SQLITE_ALLOW_URI_AUTHORITY
21951  "ALLOW_URI_AUTHORITY",
21952#endif
21953#ifdef SQLITE_ATOMIC_INTRINSICS
21954  "ATOMIC_INTRINSICS=" CTIMEOPT_VAL(SQLITE_ATOMIC_INTRINSICS),
21955#endif
21956#ifdef SQLITE_BITMASK_TYPE
21957  "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
21958#endif
21959#ifdef SQLITE_BUG_COMPATIBLE_20160819
21960  "BUG_COMPATIBLE_20160819",
21961#endif
21962#ifdef SQLITE_CASE_SENSITIVE_LIKE
21963  "CASE_SENSITIVE_LIKE",
21964#endif
21965#ifdef SQLITE_CHECK_PAGES
21966  "CHECK_PAGES",
21967#endif
21968#if defined(__clang__) && defined(__clang_major__)
21969  "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
21970                    CTIMEOPT_VAL(__clang_minor__) "."
21971                    CTIMEOPT_VAL(__clang_patchlevel__),
21972#elif defined(_MSC_VER)
21973  "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
21974#elif defined(__GNUC__) && defined(__VERSION__)
21975  "COMPILER=gcc-" __VERSION__,
21976#endif
21977#ifdef SQLITE_COVERAGE_TEST
21978  "COVERAGE_TEST",
21979#endif
21980#ifdef SQLITE_DEBUG
21981  "DEBUG",
21982#endif
21983#ifdef SQLITE_DEFAULT_AUTOMATIC_INDEX
21984  "DEFAULT_AUTOMATIC_INDEX",
21985#endif
21986#ifdef SQLITE_DEFAULT_AUTOVACUUM
21987  "DEFAULT_AUTOVACUUM",
21988#endif
21989#ifdef SQLITE_DEFAULT_CACHE_SIZE
21990  "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
21991#endif
21992#ifdef SQLITE_DEFAULT_CKPTFULLFSYNC
21993  "DEFAULT_CKPTFULLFSYNC",
21994#endif
21995#ifdef SQLITE_DEFAULT_FILE_FORMAT
21996  "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
21997#endif
21998#ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
21999  "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
22000#endif
22001#ifdef SQLITE_DEFAULT_FOREIGN_KEYS
22002  "DEFAULT_FOREIGN_KEYS",
22003#endif
22004#ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
22005  "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
22006#endif
22007#ifdef SQLITE_DEFAULT_LOCKING_MODE
22008  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
22009#endif
22010#ifdef SQLITE_DEFAULT_LOOKASIDE
22011  "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE),
22012#endif
22013#ifdef SQLITE_DEFAULT_MEMSTATUS
22014# if SQLITE_DEFAULT_MEMSTATUS != 1
22015  "DEFAULT_MEMSTATUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_MEMSTATUS),
22016# endif
22017#endif
22018#ifdef SQLITE_DEFAULT_MMAP_SIZE
22019  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
22020#endif
22021#ifdef SQLITE_DEFAULT_PAGE_SIZE
22022  "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
22023#endif
22024#ifdef SQLITE_DEFAULT_PCACHE_INITSZ
22025  "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
22026#endif
22027#ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
22028  "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
22029#endif
22030#ifdef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
22031  "DEFAULT_RECURSIVE_TRIGGERS",
22032#endif
22033#ifdef SQLITE_DEFAULT_ROWEST
22034  "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
22035#endif
22036#ifdef SQLITE_DEFAULT_SECTOR_SIZE
22037  "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
22038#endif
22039#ifdef SQLITE_DEFAULT_SYNCHRONOUS
22040  "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
22041#endif
22042#ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
22043  "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
22044#endif
22045#ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
22046  "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
22047#endif
22048#ifdef SQLITE_DEFAULT_WORKER_THREADS
22049  "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
22050#endif
22051#ifdef SQLITE_DIRECT_OVERFLOW_READ
22052  "DIRECT_OVERFLOW_READ",
22053#endif
22054#ifdef SQLITE_DISABLE_DIRSYNC
22055  "DISABLE_DIRSYNC",
22056#endif
22057#ifdef SQLITE_DISABLE_FTS3_UNICODE
22058  "DISABLE_FTS3_UNICODE",
22059#endif
22060#ifdef SQLITE_DISABLE_FTS4_DEFERRED
22061  "DISABLE_FTS4_DEFERRED",
22062#endif
22063#ifdef SQLITE_DISABLE_INTRINSIC
22064  "DISABLE_INTRINSIC",
22065#endif
22066#ifdef SQLITE_DISABLE_LFS
22067  "DISABLE_LFS",
22068#endif
22069#ifdef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
22070  "DISABLE_PAGECACHE_OVERFLOW_STATS",
22071#endif
22072#ifdef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
22073  "DISABLE_SKIPAHEAD_DISTINCT",
22074#endif
22075#ifdef SQLITE_DQS
22076  "DQS=" CTIMEOPT_VAL(SQLITE_DQS),
22077#endif
22078#ifdef SQLITE_ENABLE_8_3_NAMES
22079  "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
22080#endif
22081#ifdef SQLITE_ENABLE_API_ARMOR
22082  "ENABLE_API_ARMOR",
22083#endif
22084#ifdef SQLITE_ENABLE_ATOMIC_WRITE
22085  "ENABLE_ATOMIC_WRITE",
22086#endif
22087#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
22088  "ENABLE_BATCH_ATOMIC_WRITE",
22089#endif
22090#ifdef SQLITE_ENABLE_BYTECODE_VTAB
22091  "ENABLE_BYTECODE_VTAB",
22092#endif
22093#ifdef SQLITE_ENABLE_CEROD
22094  "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),
22095#endif
22096#ifdef SQLITE_ENABLE_COLUMN_METADATA
22097  "ENABLE_COLUMN_METADATA",
22098#endif
22099#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
22100  "ENABLE_COLUMN_USED_MASK",
22101#endif
22102#ifdef SQLITE_ENABLE_COSTMULT
22103  "ENABLE_COSTMULT",
22104#endif
22105#ifdef SQLITE_ENABLE_CURSOR_HINTS
22106  "ENABLE_CURSOR_HINTS",
22107#endif
22108#ifdef SQLITE_ENABLE_DBPAGE_VTAB
22109  "ENABLE_DBPAGE_VTAB",
22110#endif
22111#ifdef SQLITE_ENABLE_DBSTAT_VTAB
22112  "ENABLE_DBSTAT_VTAB",
22113#endif
22114#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
22115  "ENABLE_EXPENSIVE_ASSERT",
22116#endif
22117#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
22118  "ENABLE_EXPLAIN_COMMENTS",
22119#endif
22120#ifdef SQLITE_ENABLE_FTS3
22121  "ENABLE_FTS3",
22122#endif
22123#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
22124  "ENABLE_FTS3_PARENTHESIS",
22125#endif
22126#ifdef SQLITE_ENABLE_FTS3_TOKENIZER
22127  "ENABLE_FTS3_TOKENIZER",
22128#endif
22129#ifdef SQLITE_ENABLE_FTS4
22130  "ENABLE_FTS4",
22131#endif
22132#ifdef SQLITE_ENABLE_FTS5
22133  "ENABLE_FTS5",
22134#endif
22135#ifdef SQLITE_ENABLE_GEOPOLY
22136  "ENABLE_GEOPOLY",
22137#endif
22138#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
22139  "ENABLE_HIDDEN_COLUMNS",
22140#endif
22141#ifdef SQLITE_ENABLE_ICU
22142  "ENABLE_ICU",
22143#endif
22144#ifdef SQLITE_ENABLE_IOTRACE
22145  "ENABLE_IOTRACE",
22146#endif
22147#ifdef SQLITE_ENABLE_LOAD_EXTENSION
22148  "ENABLE_LOAD_EXTENSION",
22149#endif
22150#ifdef SQLITE_ENABLE_LOCKING_STYLE
22151  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
22152#endif
22153#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
22154  "ENABLE_MATH_FUNCTIONS",
22155#endif
22156#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
22157  "ENABLE_MEMORY_MANAGEMENT",
22158#endif
22159#ifdef SQLITE_ENABLE_MEMSYS3
22160  "ENABLE_MEMSYS3",
22161#endif
22162#ifdef SQLITE_ENABLE_MEMSYS5
22163  "ENABLE_MEMSYS5",
22164#endif
22165#ifdef SQLITE_ENABLE_MULTIPLEX
22166  "ENABLE_MULTIPLEX",
22167#endif
22168#ifdef SQLITE_ENABLE_NORMALIZE
22169  "ENABLE_NORMALIZE",
22170#endif
22171#ifdef SQLITE_ENABLE_NULL_TRIM
22172  "ENABLE_NULL_TRIM",
22173#endif
22174#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
22175  "ENABLE_OFFSET_SQL_FUNC",
22176#endif
22177#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
22178  "ENABLE_OVERSIZE_CELL_CHECK",
22179#endif
22180#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
22181  "ENABLE_PREUPDATE_HOOK",
22182#endif
22183#ifdef SQLITE_ENABLE_QPSG
22184  "ENABLE_QPSG",
22185#endif
22186#ifdef SQLITE_ENABLE_RBU
22187  "ENABLE_RBU",
22188#endif
22189#ifdef SQLITE_ENABLE_RTREE
22190  "ENABLE_RTREE",
22191#endif
22192#ifdef SQLITE_ENABLE_SESSION
22193  "ENABLE_SESSION",
22194#endif
22195#ifdef SQLITE_ENABLE_SNAPSHOT
22196  "ENABLE_SNAPSHOT",
22197#endif
22198#ifdef SQLITE_ENABLE_SORTER_REFERENCES
22199  "ENABLE_SORTER_REFERENCES",
22200#endif
22201#ifdef SQLITE_ENABLE_SQLLOG
22202  "ENABLE_SQLLOG",
22203#endif
22204#ifdef SQLITE_ENABLE_STAT4
22205  "ENABLE_STAT4",
22206#endif
22207#ifdef SQLITE_ENABLE_STMTVTAB
22208  "ENABLE_STMTVTAB",
22209#endif
22210#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
22211  "ENABLE_STMT_SCANSTATUS",
22212#endif
22213#ifdef SQLITE_ENABLE_TREETRACE
22214  "ENABLE_TREETRACE",
22215#endif
22216#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
22217  "ENABLE_UNKNOWN_SQL_FUNCTION",
22218#endif
22219#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
22220  "ENABLE_UNLOCK_NOTIFY",
22221#endif
22222#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
22223  "ENABLE_UPDATE_DELETE_LIMIT",
22224#endif
22225#ifdef SQLITE_ENABLE_URI_00_ERROR
22226  "ENABLE_URI_00_ERROR",
22227#endif
22228#ifdef SQLITE_ENABLE_VFSTRACE
22229  "ENABLE_VFSTRACE",
22230#endif
22231#ifdef SQLITE_ENABLE_WHERETRACE
22232  "ENABLE_WHERETRACE",
22233#endif
22234#ifdef SQLITE_ENABLE_ZIPVFS
22235  "ENABLE_ZIPVFS",
22236#endif
22237#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
22238  "EXPLAIN_ESTIMATED_ROWS",
22239#endif
22240#ifdef SQLITE_EXTRA_AUTOEXT
22241  "EXTRA_AUTOEXT=" CTIMEOPT_VAL(SQLITE_EXTRA_AUTOEXT),
22242#endif
22243#ifdef SQLITE_EXTRA_IFNULLROW
22244  "EXTRA_IFNULLROW",
22245#endif
22246#ifdef SQLITE_EXTRA_INIT
22247  "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
22248#endif
22249#ifdef SQLITE_EXTRA_SHUTDOWN
22250  "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
22251#endif
22252#ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
22253  "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
22254#endif
22255#ifdef SQLITE_FTS5_ENABLE_TEST_MI
22256  "FTS5_ENABLE_TEST_MI",
22257#endif
22258#ifdef SQLITE_FTS5_NO_WITHOUT_ROWID
22259  "FTS5_NO_WITHOUT_ROWID",
22260#endif
22261#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
22262  "HAVE_ISNAN",
22263#endif
22264#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22265# if SQLITE_HOMEGROWN_RECURSIVE_MUTEX != 1
22266  "HOMEGROWN_RECURSIVE_MUTEX=" CTIMEOPT_VAL(SQLITE_HOMEGROWN_RECURSIVE_MUTEX),
22267# endif
22268#endif
22269#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
22270  "IGNORE_AFP_LOCK_ERRORS",
22271#endif
22272#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
22273  "IGNORE_FLOCK_LOCK_ERRORS",
22274#endif
22275#ifdef SQLITE_INLINE_MEMCPY
22276  "INLINE_MEMCPY",
22277#endif
22278#ifdef SQLITE_INT64_TYPE
22279  "INT64_TYPE",
22280#endif
22281#ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
22282  "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
22283#endif
22284#ifdef SQLITE_LEGACY_JSON_VALID
22285  "LEGACY_JSON_VALID",
22286#endif
22287#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
22288  "LIKE_DOESNT_MATCH_BLOBS",
22289#endif
22290#ifdef SQLITE_LOCK_TRACE
22291  "LOCK_TRACE",
22292#endif
22293#ifdef SQLITE_LOG_CACHE_SPILL
22294  "LOG_CACHE_SPILL",
22295#endif
22296#ifdef SQLITE_MALLOC_SOFT_LIMIT
22297  "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
22298#endif
22299#ifdef SQLITE_MAX_ATTACHED
22300  "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
22301#endif
22302#ifdef SQLITE_MAX_COLUMN
22303  "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
22304#endif
22305#ifdef SQLITE_MAX_COMPOUND_SELECT
22306  "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
22307#endif
22308#ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
22309  "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
22310#endif
22311#ifdef SQLITE_MAX_EXPR_DEPTH
22312  "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
22313#endif
22314#ifdef SQLITE_MAX_FUNCTION_ARG
22315  "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
22316#endif
22317#ifdef SQLITE_MAX_LENGTH
22318  "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
22319#endif
22320#ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
22321  "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
22322#endif
22323#ifdef SQLITE_MAX_MEMORY
22324  "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
22325#endif
22326#ifdef SQLITE_MAX_MMAP_SIZE
22327  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
22328#endif
22329#ifdef SQLITE_MAX_MMAP_SIZE_
22330  "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
22331#endif
22332#ifdef SQLITE_MAX_PAGE_COUNT
22333  "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
22334#endif
22335#ifdef SQLITE_MAX_PAGE_SIZE
22336  "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
22337#endif
22338#ifdef SQLITE_MAX_SCHEMA_RETRY
22339  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
22340#endif
22341#ifdef SQLITE_MAX_SQL_LENGTH
22342  "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
22343#endif
22344#ifdef SQLITE_MAX_TRIGGER_DEPTH
22345  "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
22346#endif
22347#ifdef SQLITE_MAX_VARIABLE_NUMBER
22348  "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
22349#endif
22350#ifdef SQLITE_MAX_VDBE_OP
22351  "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
22352#endif
22353#ifdef SQLITE_MAX_WORKER_THREADS
22354  "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
22355#endif
22356#ifdef SQLITE_MEMDEBUG
22357  "MEMDEBUG",
22358#endif
22359#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
22360  "MIXED_ENDIAN_64BIT_FLOAT",
22361#endif
22362#ifdef SQLITE_MMAP_READWRITE
22363  "MMAP_READWRITE",
22364#endif
22365#ifdef SQLITE_MUTEX_NOOP
22366  "MUTEX_NOOP",
22367#endif
22368#ifdef SQLITE_MUTEX_OMIT
22369  "MUTEX_OMIT",
22370#endif
22371#ifdef SQLITE_MUTEX_PTHREADS
22372  "MUTEX_PTHREADS",
22373#endif
22374#ifdef SQLITE_MUTEX_W32
22375  "MUTEX_W32",
22376#endif
22377#ifdef SQLITE_NEED_ERR_NAME
22378  "NEED_ERR_NAME",
22379#endif
22380#ifdef SQLITE_NO_SYNC
22381  "NO_SYNC",
22382#endif
22383#ifdef SQLITE_OMIT_ALTERTABLE
22384  "OMIT_ALTERTABLE",
22385#endif
22386#ifdef SQLITE_OMIT_ANALYZE
22387  "OMIT_ANALYZE",
22388#endif
22389#ifdef SQLITE_OMIT_ATTACH
22390  "OMIT_ATTACH",
22391#endif
22392#ifdef SQLITE_OMIT_AUTHORIZATION
22393  "OMIT_AUTHORIZATION",
22394#endif
22395#ifdef SQLITE_OMIT_AUTOINCREMENT
22396  "OMIT_AUTOINCREMENT",
22397#endif
22398#ifdef SQLITE_OMIT_AUTOINIT
22399  "OMIT_AUTOINIT",
22400#endif
22401#ifdef SQLITE_OMIT_AUTOMATIC_INDEX
22402  "OMIT_AUTOMATIC_INDEX",
22403#endif
22404#ifdef SQLITE_OMIT_AUTORESET
22405  "OMIT_AUTORESET",
22406#endif
22407#ifdef SQLITE_OMIT_AUTOVACUUM
22408  "OMIT_AUTOVACUUM",
22409#endif
22410#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
22411  "OMIT_BETWEEN_OPTIMIZATION",
22412#endif
22413#ifdef SQLITE_OMIT_BLOB_LITERAL
22414  "OMIT_BLOB_LITERAL",
22415#endif
22416#ifdef SQLITE_OMIT_CAST
22417  "OMIT_CAST",
22418#endif
22419#ifdef SQLITE_OMIT_CHECK
22420  "OMIT_CHECK",
22421#endif
22422#ifdef SQLITE_OMIT_COMPLETE
22423  "OMIT_COMPLETE",
22424#endif
22425#ifdef SQLITE_OMIT_COMPOUND_SELECT
22426  "OMIT_COMPOUND_SELECT",
22427#endif
22428#ifdef SQLITE_OMIT_CONFLICT_CLAUSE
22429  "OMIT_CONFLICT_CLAUSE",
22430#endif
22431#ifdef SQLITE_OMIT_CTE
22432  "OMIT_CTE",
22433#endif
22434#if defined(SQLITE_OMIT_DATETIME_FUNCS) || defined(SQLITE_OMIT_FLOATING_POINT)
22435  "OMIT_DATETIME_FUNCS",
22436#endif
22437#ifdef SQLITE_OMIT_DECLTYPE
22438  "OMIT_DECLTYPE",
22439#endif
22440#ifdef SQLITE_OMIT_DEPRECATED
22441  "OMIT_DEPRECATED",
22442#endif
22443#ifdef SQLITE_OMIT_DESERIALIZE
22444  "OMIT_DESERIALIZE",
22445#endif
22446#ifdef SQLITE_OMIT_DISKIO
22447  "OMIT_DISKIO",
22448#endif
22449#ifdef SQLITE_OMIT_EXPLAIN
22450  "OMIT_EXPLAIN",
22451#endif
22452#ifdef SQLITE_OMIT_FLAG_PRAGMAS
22453  "OMIT_FLAG_PRAGMAS",
22454#endif
22455#ifdef SQLITE_OMIT_FLOATING_POINT
22456  "OMIT_FLOATING_POINT",
22457#endif
22458#ifdef SQLITE_OMIT_FOREIGN_KEY
22459  "OMIT_FOREIGN_KEY",
22460#endif
22461#ifdef SQLITE_OMIT_GET_TABLE
22462  "OMIT_GET_TABLE",
22463#endif
22464#ifdef SQLITE_OMIT_HEX_INTEGER
22465  "OMIT_HEX_INTEGER",
22466#endif
22467#ifdef SQLITE_OMIT_INCRBLOB
22468  "OMIT_INCRBLOB",
22469#endif
22470#ifdef SQLITE_OMIT_INTEGRITY_CHECK
22471  "OMIT_INTEGRITY_CHECK",
22472#endif
22473#ifdef SQLITE_OMIT_INTROSPECTION_PRAGMAS
22474  "OMIT_INTROSPECTION_PRAGMAS",
22475#endif
22476#ifdef SQLITE_OMIT_JSON
22477  "OMIT_JSON",
22478#endif
22479#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
22480  "OMIT_LIKE_OPTIMIZATION",
22481#endif
22482#ifdef SQLITE_OMIT_LOAD_EXTENSION
22483  "OMIT_LOAD_EXTENSION",
22484#endif
22485#ifdef SQLITE_OMIT_LOCALTIME
22486  "OMIT_LOCALTIME",
22487#endif
22488#ifdef SQLITE_OMIT_LOOKASIDE
22489  "OMIT_LOOKASIDE",
22490#endif
22491#ifdef SQLITE_OMIT_MEMORYDB
22492  "OMIT_MEMORYDB",
22493#endif
22494#ifdef SQLITE_OMIT_OR_OPTIMIZATION
22495  "OMIT_OR_OPTIMIZATION",
22496#endif
22497#ifdef SQLITE_OMIT_PAGER_PRAGMAS
22498  "OMIT_PAGER_PRAGMAS",
22499#endif
22500#ifdef SQLITE_OMIT_PARSER_TRACE
22501  "OMIT_PARSER_TRACE",
22502#endif
22503#ifdef SQLITE_OMIT_POPEN
22504  "OMIT_POPEN",
22505#endif
22506#ifdef SQLITE_OMIT_PRAGMA
22507  "OMIT_PRAGMA",
22508#endif
22509#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
22510  "OMIT_PROGRESS_CALLBACK",
22511#endif
22512#ifdef SQLITE_OMIT_QUICKBALANCE
22513  "OMIT_QUICKBALANCE",
22514#endif
22515#ifdef SQLITE_OMIT_REINDEX
22516  "OMIT_REINDEX",
22517#endif
22518#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
22519  "OMIT_SCHEMA_PRAGMAS",
22520#endif
22521#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
22522  "OMIT_SCHEMA_VERSION_PRAGMAS",
22523#endif
22524#ifdef SQLITE_OMIT_SEH
22525  "OMIT_SEH",
22526#endif
22527#ifdef SQLITE_OMIT_SHARED_CACHE
22528  "OMIT_SHARED_CACHE",
22529#endif
22530#ifdef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
22531  "OMIT_SHUTDOWN_DIRECTORIES",
22532#endif
22533#ifdef SQLITE_OMIT_SUBQUERY
22534  "OMIT_SUBQUERY",
22535#endif
22536#ifdef SQLITE_OMIT_TCL_VARIABLE
22537  "OMIT_TCL_VARIABLE",
22538#endif
22539#ifdef SQLITE_OMIT_TEMPDB
22540  "OMIT_TEMPDB",
22541#endif
22542#ifdef SQLITE_OMIT_TEST_CONTROL
22543  "OMIT_TEST_CONTROL",
22544#endif
22545#ifdef SQLITE_OMIT_TRACE
22546# if SQLITE_OMIT_TRACE != 1
22547  "OMIT_TRACE=" CTIMEOPT_VAL(SQLITE_OMIT_TRACE),
22548# endif
22549#endif
22550#ifdef SQLITE_OMIT_TRIGGER
22551  "OMIT_TRIGGER",
22552#endif
22553#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
22554  "OMIT_TRUNCATE_OPTIMIZATION",
22555#endif
22556#ifdef SQLITE_OMIT_UTF16
22557  "OMIT_UTF16",
22558#endif
22559#ifdef SQLITE_OMIT_VACUUM
22560  "OMIT_VACUUM",
22561#endif
22562#ifdef SQLITE_OMIT_VIEW
22563  "OMIT_VIEW",
22564#endif
22565#ifdef SQLITE_OMIT_VIRTUALTABLE
22566  "OMIT_VIRTUALTABLE",
22567#endif
22568#ifdef SQLITE_OMIT_WAL
22569  "OMIT_WAL",
22570#endif
22571#ifdef SQLITE_OMIT_WSD
22572  "OMIT_WSD",
22573#endif
22574#ifdef SQLITE_OMIT_XFER_OPT
22575  "OMIT_XFER_OPT",
22576#endif
22577#ifdef SQLITE_PERFORMANCE_TRACE
22578  "PERFORMANCE_TRACE",
22579#endif
22580#ifdef SQLITE_POWERSAFE_OVERWRITE
22581# if SQLITE_POWERSAFE_OVERWRITE != 1
22582  "POWERSAFE_OVERWRITE=" CTIMEOPT_VAL(SQLITE_POWERSAFE_OVERWRITE),
22583# endif
22584#endif
22585#ifdef SQLITE_PREFER_PROXY_LOCKING
22586  "PREFER_PROXY_LOCKING",
22587#endif
22588#ifdef SQLITE_PROXY_DEBUG
22589  "PROXY_DEBUG",
22590#endif
22591#ifdef SQLITE_REVERSE_UNORDERED_SELECTS
22592  "REVERSE_UNORDERED_SELECTS",
22593#endif
22594#ifdef SQLITE_RTREE_INT_ONLY
22595  "RTREE_INT_ONLY",
22596#endif
22597#ifdef SQLITE_SECURE_DELETE
22598  "SECURE_DELETE",
22599#endif
22600#ifdef SQLITE_SMALL_STACK
22601  "SMALL_STACK",
22602#endif
22603#ifdef SQLITE_SORTER_PMASZ
22604  "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
22605#endif
22606#ifdef SQLITE_SOUNDEX
22607  "SOUNDEX",
22608#endif
22609#ifdef SQLITE_STAT4_SAMPLES
22610  "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
22611#endif
22612#ifdef SQLITE_STMTJRNL_SPILL
22613  "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
22614#endif
22615#ifdef SQLITE_SUBSTR_COMPATIBILITY
22616  "SUBSTR_COMPATIBILITY",
22617#endif
22618#if (!defined(SQLITE_WIN32_MALLOC) \
22619     && !defined(SQLITE_ZERO_MALLOC) \
22620     && !defined(SQLITE_MEMDEBUG) \
22621    ) || defined(SQLITE_SYSTEM_MALLOC)
22622  "SYSTEM_MALLOC",
22623#endif
22624#ifdef SQLITE_TCL
22625  "TCL",
22626#endif
22627#ifdef SQLITE_TEMP_STORE
22628  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
22629#endif
22630#ifdef SQLITE_TEST
22631  "TEST",
22632#endif
22633#if defined(SQLITE_THREADSAFE)
22634  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
22635#elif defined(THREADSAFE)
22636  "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
22637#else
22638  "THREADSAFE=1",
22639#endif
22640#ifdef SQLITE_UNLINK_AFTER_CLOSE
22641  "UNLINK_AFTER_CLOSE",
22642#endif
22643#ifdef SQLITE_UNTESTABLE
22644  "UNTESTABLE",
22645#endif
22646#ifdef SQLITE_USER_AUTHENTICATION
22647  "USER_AUTHENTICATION",
22648#endif
22649#ifdef SQLITE_USE_ALLOCA
22650  "USE_ALLOCA",
22651#endif
22652#ifdef SQLITE_USE_FCNTL_TRACE
22653  "USE_FCNTL_TRACE",
22654#endif
22655#ifdef SQLITE_USE_URI
22656  "USE_URI",
22657#endif
22658#ifdef SQLITE_VDBE_COVERAGE
22659  "VDBE_COVERAGE",
22660#endif
22661#ifdef SQLITE_WIN32_MALLOC
22662  "WIN32_MALLOC",
22663#endif
22664#ifdef SQLITE_ZERO_MALLOC
22665  "ZERO_MALLOC",
22666#endif
22667
22668} ;
22669
22670SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
22671  *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
22672  return (const char**)sqlite3azCompileOpt;
22673}
22674
22675#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
22676
22677/************** End of ctime.c ***********************************************/
22678/************** Begin file global.c ******************************************/
22679/*
22680** 2008 June 13
22681**
22682** The author disclaims copyright to this source code.  In place of
22683** a legal notice, here is a blessing:
22684**
22685**    May you do good and not evil.
22686**    May you find forgiveness for yourself and forgive others.
22687**    May you share freely, never taking more than you give.
22688**
22689*************************************************************************
22690**
22691** This file contains definitions of global variables and constants.
22692*/
22693/* #include "sqliteInt.h" */
22694
22695/* An array to map all upper-case characters into their corresponding
22696** lower-case character.
22697**
22698** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
22699** handle case conversions for the UTF character set since the tables
22700** involved are nearly as big or bigger than SQLite itself.
22701*/
22702SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
22703#ifdef SQLITE_ASCII
22704      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
22705     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
22706     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
22707     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
22708    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
22709    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
22710    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
22711    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
22712    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
22713    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
22714    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
22715    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
22716    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
22717    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
22718    252,253,254,255,
22719#endif
22720#ifdef SQLITE_EBCDIC
22721      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
22722     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
22723     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
22724     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
22725     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
22726     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
22727     96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
22728    112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
22729    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
22730    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
22731    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
22732    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
22733    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
22734    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
22735    224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
22736    240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
22737#endif
22738/* All of the upper-to-lower conversion data is above.  The following
22739** 18 integers are completely unrelated.  They are appended to the
22740** sqlite3UpperToLower[] array to avoid UBSAN warnings.  Here's what is
22741** going on:
22742**
22743** The SQL comparison operators (<>, =, >, <=, <, and >=) are implemented
22744** by invoking sqlite3MemCompare(A,B) which compares values A and B and
22745** returns negative, zero, or positive if A is less then, equal to, or
22746** greater than B, respectively.  Then the true false results is found by
22747** consulting sqlite3aLTb[opcode], sqlite3aEQb[opcode], or
22748** sqlite3aGTb[opcode] depending on whether the result of compare(A,B)
22749** is negative, zero, or positive, where opcode is the specific opcode.
22750** The only works because the comparison opcodes are consecutive and in
22751** this order: NE EQ GT LE LT GE.  Various assert()s throughout the code
22752** ensure that is the case.
22753**
22754** These elements must be appended to another array.  Otherwise the
22755** index (here shown as [256-OP_Ne]) would be out-of-bounds and thus
22756** be undefined behavior.  That's goofy, but the C-standards people thought
22757** it was a good idea, so here we are.
22758*/
22759/* NE  EQ  GT  LE  LT  GE  */
22760   1,  0,  0,  1,  1,  0,  /* aLTb[]: Use when compare(A,B) less than zero */
22761   0,  1,  0,  1,  0,  1,  /* aEQb[]: Use when compare(A,B) equals zero */
22762   1,  0,  1,  0,  0,  1   /* aGTb[]: Use when compare(A,B) greater than zero*/
22763};
22764SQLITE_PRIVATE const unsigned char *sqlite3aLTb = &sqlite3UpperToLower[256-OP_Ne];
22765SQLITE_PRIVATE const unsigned char *sqlite3aEQb = &sqlite3UpperToLower[256+6-OP_Ne];
22766SQLITE_PRIVATE const unsigned char *sqlite3aGTb = &sqlite3UpperToLower[256+12-OP_Ne];
22767
22768/*
22769** The following 256 byte lookup table is used to support SQLites built-in
22770** equivalents to the following standard library functions:
22771**
22772**   isspace()                        0x01
22773**   isalpha()                        0x02
22774**   isdigit()                        0x04
22775**   isalnum()                        0x06
22776**   isxdigit()                       0x08
22777**   toupper()                        0x20
22778**   SQLite identifier character      0x40   $, _, or non-ascii
22779**   Quote character                  0x80
22780**
22781** Bit 0x20 is set if the mapped character requires translation to upper
22782** case. i.e. if the character is a lower-case ASCII character.
22783** If x is a lower-case ASCII character, then its upper-case equivalent
22784** is (x - 0x20). Therefore toupper() can be implemented as:
22785**
22786**   (x & ~(map[x]&0x20))
22787**
22788** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
22789** array. tolower() is used more often than toupper() by SQLite.
22790**
22791** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
22792** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
22793** non-ASCII UTF character. Hence the test for whether or not a character is
22794** part of an identifier is 0x46.
22795*/
22796SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
22797  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
22798  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
22799  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
22800  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
22801  0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80,  /* 20..27     !"#$%&' */
22802  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
22803  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
22804  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
22805
22806  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
22807  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
22808  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
22809  0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
22810  0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
22811  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
22812  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
22813  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
22814
22815  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
22816  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
22817  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
22818  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
22819  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
22820  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
22821  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
22822  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
22823
22824  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
22825  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
22826  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
22827  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
22828  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
22829  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
22830  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
22831  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
22832};
22833
22834/* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
22835** compatibility for legacy applications, the URI filename capability is
22836** disabled by default.
22837**
22838** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
22839** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
22840**
22841** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
22842** disabled. The default value may be changed by compiling with the
22843** SQLITE_USE_URI symbol defined.
22844*/
22845#ifndef SQLITE_USE_URI
22846# define SQLITE_USE_URI 0
22847#endif
22848
22849/* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
22850** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
22851** that compile-time option is omitted.
22852*/
22853#if !defined(SQLITE_ALLOW_COVERING_INDEX_SCAN)
22854# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
22855#else
22856# if !SQLITE_ALLOW_COVERING_INDEX_SCAN
22857#   error "Compile-time disabling of covering index scan using the\
22858 -DSQLITE_ALLOW_COVERING_INDEX_SCAN=0 option is deprecated.\
22859 Contact SQLite developers if this is a problem for you, and\
22860 delete this #error macro to continue with your build."
22861# endif
22862#endif
22863
22864/* The minimum PMA size is set to this value multiplied by the database
22865** page size in bytes.
22866*/
22867#ifndef SQLITE_SORTER_PMASZ
22868# define SQLITE_SORTER_PMASZ 250
22869#endif
22870
22871/* Statement journals spill to disk when their size exceeds the following
22872** threshold (in bytes). 0 means that statement journals are created and
22873** written to disk immediately (the default behavior for SQLite versions
22874** before 3.12.0).  -1 means always keep the entire statement journal in
22875** memory.  (The statement journal is also always held entirely in memory
22876** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
22877** setting.)
22878*/
22879#ifndef SQLITE_STMTJRNL_SPILL
22880# define SQLITE_STMTJRNL_SPILL (64*1024)
22881#endif
22882
22883/*
22884** The default lookaside-configuration, the format "SZ,N".  SZ is the
22885** number of bytes in each lookaside slot (should be a multiple of 8)
22886** and N is the number of slots.  The lookaside-configuration can be
22887** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
22888** or at run-time for an individual database connection using
22889** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
22890**
22891** With the two-size-lookaside enhancement, less lookaside is required.
22892** The default configuration of 1200,40 actually provides 30 1200-byte slots
22893** and 93 128-byte slots, which is more lookaside than is available
22894** using the older 1200,100 configuration without two-size-lookaside.
22895*/
22896#ifndef SQLITE_DEFAULT_LOOKASIDE
22897# ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
22898#   define SQLITE_DEFAULT_LOOKASIDE 1200,100  /* 120KB of memory */
22899# else
22900#   define SQLITE_DEFAULT_LOOKASIDE 1200,40   /* 48KB of memory */
22901# endif
22902#endif
22903
22904
22905/* The default maximum size of an in-memory database created using
22906** sqlite3_deserialize()
22907*/
22908#ifndef SQLITE_MEMDB_DEFAULT_MAXSIZE
22909# define SQLITE_MEMDB_DEFAULT_MAXSIZE 1073741824
22910#endif
22911
22912/*
22913** The following singleton contains the global configuration for
22914** the SQLite library.
22915*/
22916SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
22917   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
22918   1,                         /* bCoreMutex */
22919   SQLITE_THREADSAFE==1,      /* bFullMutex */
22920   SQLITE_USE_URI,            /* bOpenUri */
22921   SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
22922   0,                         /* bSmallMalloc */
22923   1,                         /* bExtraSchemaChecks */
22924   sizeof(LONGDOUBLE_TYPE)>8, /* bUseLongDouble */
22925#ifdef SQLITE_DEBUG
22926   0,                         /* bJsonSelfcheck */
22927#endif
22928   0x7ffffffe,                /* mxStrlen */
22929   0,                         /* neverCorrupt */
22930   SQLITE_DEFAULT_LOOKASIDE,  /* szLookaside, nLookaside */
22931   SQLITE_STMTJRNL_SPILL,     /* nStmtSpill */
22932   {0,0,0,0,0,0,0,0},         /* m */
22933   {0,0,0,0,0,0,0,0,0},       /* mutex */
22934   {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
22935   (void*)0,                  /* pHeap */
22936   0,                         /* nHeap */
22937   0, 0,                      /* mnHeap, mxHeap */
22938   SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
22939   SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
22940   (void*)0,                  /* pPage */
22941   0,                         /* szPage */
22942   SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
22943   0,                         /* mxParserStack */
22944   0,                         /* sharedCacheEnabled */
22945   SQLITE_SORTER_PMASZ,       /* szPma */
22946   /* All the rest should always be initialized to zero */
22947   0,                         /* isInit */
22948   0,                         /* inProgress */
22949   0,                         /* isMutexInit */
22950   0,                         /* isMallocInit */
22951   0,                         /* isPCacheInit */
22952   0,                         /* nRefInitMutex */
22953   0,                         /* pInitMutex */
22954   0,                         /* xLog */
22955   0,                         /* pLogArg */
22956#ifdef SQLITE_ENABLE_SQLLOG
22957   0,                         /* xSqllog */
22958   0,                         /* pSqllogArg */
22959#endif
22960#ifdef SQLITE_VDBE_COVERAGE
22961   0,                         /* xVdbeBranch */
22962   0,                         /* pVbeBranchArg */
22963#endif
22964#ifndef SQLITE_OMIT_DESERIALIZE
22965   SQLITE_MEMDB_DEFAULT_MAXSIZE,   /* mxMemdbSize */
22966#endif
22967#ifndef SQLITE_UNTESTABLE
22968   0,                         /* xTestCallback */
22969#endif
22970#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
22971   0,                         /* mNoVisibleRowid.  0 == allow rowid-in-view */
22972#endif
22973   0,                         /* bLocaltimeFault */
22974   0,                         /* xAltLocaltime */
22975   0x7ffffffe,                /* iOnceResetThreshold */
22976   SQLITE_DEFAULT_SORTERREF_SIZE,   /* szSorterRef */
22977   0,                         /* iPrngSeed */
22978#ifdef SQLITE_DEBUG
22979   {0,0,0,0,0,0},             /* aTune */
22980#endif
22981};
22982
22983/*
22984** Hash table for global functions - functions common to all
22985** database connections.  After initialization, this table is
22986** read-only.
22987*/
22988SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
22989
22990#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
22991/*
22992** Counter used for coverage testing.  Does not come into play for
22993** release builds.
22994**
22995** Access to this global variable is not mutex protected.  This might
22996** result in TSAN warnings.  But as the variable does not exist in
22997** release builds, that should not be a concern.
22998*/
22999SQLITE_PRIVATE unsigned int sqlite3CoverageCounter;
23000#endif /* SQLITE_COVERAGE_TEST || SQLITE_DEBUG */
23001
23002#ifdef VDBE_PROFILE
23003/*
23004** The following performance counter can be used in place of
23005** sqlite3Hwtime() for profiling.  This is a no-op on standard builds.
23006*/
23007SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt = 0;
23008#endif
23009
23010/*
23011** The value of the "pending" byte must be 0x40000000 (1 byte past the
23012** 1-gibabyte boundary) in a compatible database.  SQLite never uses
23013** the database page that contains the pending byte.  It never attempts
23014** to read or write that page.  The pending byte page is set aside
23015** for use by the VFS layers as space for managing file locks.
23016**
23017** During testing, it is often desirable to move the pending byte to
23018** a different position in the file.  This allows code that has to
23019** deal with the pending byte to run on files that are much smaller
23020** than 1 GiB.  The sqlite3_test_control() interface can be used to
23021** move the pending byte.
23022**
23023** IMPORTANT:  Changing the pending byte to any value other than
23024** 0x40000000 results in an incompatible database file format!
23025** Changing the pending byte during operation will result in undefined
23026** and incorrect behavior.
23027*/
23028#ifndef SQLITE_OMIT_WSD
23029SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
23030#endif
23031
23032/*
23033** Tracing flags set by SQLITE_TESTCTRL_TRACEFLAGS.
23034*/
23035SQLITE_PRIVATE u32 sqlite3TreeTrace = 0;
23036SQLITE_PRIVATE u32 sqlite3WhereTrace = 0;
23037
23038/* #include "opcodes.h" */
23039/*
23040** Properties of opcodes.  The OPFLG_INITIALIZER macro is
23041** created by mkopcodeh.awk during compilation.  Data is obtained
23042** from the comments following the "case OP_xxxx:" statements in
23043** the vdbe.c file.
23044*/
23045SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
23046
23047/*
23048** Name of the default collating sequence
23049*/
23050SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
23051
23052/*
23053** Standard typenames.  These names must match the COLTYPE_* definitions.
23054** Adjust the SQLITE_N_STDTYPE value if adding or removing entries.
23055**
23056**    sqlite3StdType[]            The actual names of the datatypes.
23057**
23058**    sqlite3StdTypeLen[]         The length (in bytes) of each entry
23059**                                in sqlite3StdType[].
23060**
23061**    sqlite3StdTypeAffinity[]    The affinity associated with each entry
23062**                                in sqlite3StdType[].
23063*/
23064SQLITE_PRIVATE const unsigned char sqlite3StdTypeLen[] = { 3, 4, 3, 7, 4, 4 };
23065SQLITE_PRIVATE const char sqlite3StdTypeAffinity[] = {
23066  SQLITE_AFF_NUMERIC,
23067  SQLITE_AFF_BLOB,
23068  SQLITE_AFF_INTEGER,
23069  SQLITE_AFF_INTEGER,
23070  SQLITE_AFF_REAL,
23071  SQLITE_AFF_TEXT
23072};
23073SQLITE_PRIVATE const char *sqlite3StdType[] = {
23074  "ANY",
23075  "BLOB",
23076  "INT",
23077  "INTEGER",
23078  "REAL",
23079  "TEXT"
23080};
23081
23082/************** End of global.c **********************************************/
23083/************** Begin file status.c ******************************************/
23084/*
23085** 2008 June 18
23086**
23087** The author disclaims copyright to this source code.  In place of
23088** a legal notice, here is a blessing:
23089**
23090**    May you do good and not evil.
23091**    May you find forgiveness for yourself and forgive others.
23092**    May you share freely, never taking more than you give.
23093**
23094*************************************************************************
23095**
23096** This module implements the sqlite3_status() interface and related
23097** functionality.
23098*/
23099/* #include "sqliteInt.h" */
23100/************** Include vdbeInt.h in the middle of status.c ******************/
23101/************** Begin file vdbeInt.h *****************************************/
23102/*
23103** 2003 September 6
23104**
23105** The author disclaims copyright to this source code.  In place of
23106** a legal notice, here is a blessing:
23107**
23108**    May you do good and not evil.
23109**    May you find forgiveness for yourself and forgive others.
23110**    May you share freely, never taking more than you give.
23111**
23112*************************************************************************
23113** This is the header file for information that is private to the
23114** VDBE.  This information used to all be at the top of the single
23115** source code file "vdbe.c".  When that file became too big (over
23116** 6000 lines long) it was split up into several smaller files and
23117** this header information was factored out.
23118*/
23119#ifndef SQLITE_VDBEINT_H
23120#define SQLITE_VDBEINT_H
23121
23122/*
23123** The maximum number of times that a statement will try to reparse
23124** itself before giving up and returning SQLITE_SCHEMA.
23125*/
23126#ifndef SQLITE_MAX_SCHEMA_RETRY
23127# define SQLITE_MAX_SCHEMA_RETRY 50
23128#endif
23129
23130/*
23131** VDBE_DISPLAY_P4 is true or false depending on whether or not the
23132** "explain" P4 display logic is enabled.
23133*/
23134#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
23135     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) \
23136     || defined(SQLITE_ENABLE_BYTECODE_VTAB)
23137# define VDBE_DISPLAY_P4 1
23138#else
23139# define VDBE_DISPLAY_P4 0
23140#endif
23141
23142/*
23143** SQL is translated into a sequence of instructions to be
23144** executed by a virtual machine.  Each instruction is an instance
23145** of the following structure.
23146*/
23147typedef struct VdbeOp Op;
23148
23149/*
23150** Boolean values
23151*/
23152typedef unsigned Bool;
23153
23154/* Opaque type used by code in vdbesort.c */
23155typedef struct VdbeSorter VdbeSorter;
23156
23157/* Elements of the linked list at Vdbe.pAuxData */
23158typedef struct AuxData AuxData;
23159
23160/* A cache of large TEXT or BLOB values in a VdbeCursor */
23161typedef struct VdbeTxtBlbCache VdbeTxtBlbCache;
23162
23163/* Types of VDBE cursors */
23164#define CURTYPE_BTREE       0
23165#define CURTYPE_SORTER      1
23166#define CURTYPE_VTAB        2
23167#define CURTYPE_PSEUDO      3
23168
23169/*
23170** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
23171**
23172**      * A b-tree cursor
23173**          -  In the main database or in an ephemeral database
23174**          -  On either an index or a table
23175**      * A sorter
23176**      * A virtual table
23177**      * A one-row "pseudotable" stored in a single register
23178*/
23179typedef struct VdbeCursor VdbeCursor;
23180struct VdbeCursor {
23181  u8 eCurType;            /* One of the CURTYPE_* values above */
23182  i8 iDb;                 /* Index of cursor database in db->aDb[] */
23183  u8 nullRow;             /* True if pointing to a row with no data */
23184  u8 deferredMoveto;      /* A call to sqlite3BtreeMoveto() is needed */
23185  u8 isTable;             /* True for rowid tables.  False for indexes */
23186#ifdef SQLITE_DEBUG
23187  u8 seekOp;              /* Most recent seek operation on this cursor */
23188  u8 wrFlag;              /* The wrFlag argument to sqlite3BtreeCursor() */
23189#endif
23190  Bool isEphemeral:1;     /* True for an ephemeral table */
23191  Bool useRandomRowid:1;  /* Generate new record numbers semi-randomly */
23192  Bool isOrdered:1;       /* True if the table is not BTREE_UNORDERED */
23193  Bool noReuse:1;         /* OpenEphemeral may not reuse this cursor */
23194  Bool colCache:1;        /* pCache pointer is initialized and non-NULL */
23195  u16 seekHit;            /* See the OP_SeekHit and OP_IfNoHope opcodes */
23196  union {                 /* pBtx for isEphermeral.  pAltMap otherwise */
23197    Btree *pBtx;            /* Separate file holding temporary table */
23198    u32 *aAltMap;           /* Mapping from table to index column numbers */
23199  } ub;
23200  i64 seqCount;           /* Sequence counter */
23201
23202  /* Cached OP_Column parse information is only valid if cacheStatus matches
23203  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
23204  ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
23205  ** the cache is out of date. */
23206  u32 cacheStatus;        /* Cache is valid if this matches Vdbe.cacheCtr */
23207  int seekResult;         /* Result of previous sqlite3BtreeMoveto() or 0
23208                          ** if there have been no prior seeks on the cursor. */
23209  /* seekResult does not distinguish between "no seeks have ever occurred
23210  ** on this cursor" and "the most recent seek was an exact match".
23211  ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
23212
23213  /* When a new VdbeCursor is allocated, only the fields above are zeroed.
23214  ** The fields that follow are uninitialized, and must be individually
23215  ** initialized prior to first use. */
23216  VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
23217  union {
23218    BtCursor *pCursor;          /* CURTYPE_BTREE or _PSEUDO.  Btree cursor */
23219    sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB.              Vtab cursor */
23220    VdbeSorter *pSorter;        /* CURTYPE_SORTER.            Sorter object */
23221  } uc;
23222  KeyInfo *pKeyInfo;      /* Info about index keys needed by index cursors */
23223  u32 iHdrOffset;         /* Offset to next unparsed byte of the header */
23224  Pgno pgnoRoot;          /* Root page of the open btree cursor */
23225  i16 nField;             /* Number of fields in the header */
23226  u16 nHdrParsed;         /* Number of header fields parsed so far */
23227  i64 movetoTarget;       /* Argument to the deferred sqlite3BtreeMoveto() */
23228  u32 *aOffset;           /* Pointer to aType[nField] */
23229  const u8 *aRow;         /* Data for the current row, if all on one page */
23230  u32 payloadSize;        /* Total number of bytes in the record */
23231  u32 szRow;              /* Byte available in aRow */
23232#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
23233  u64 maskUsed;           /* Mask of columns used by this cursor */
23234#endif
23235  VdbeTxtBlbCache *pCache; /* Cache of large TEXT or BLOB values */
23236
23237  /* 2*nField extra array elements allocated for aType[], beyond the one
23238  ** static element declared in the structure.  nField total array slots for
23239  ** aType[] and nField+1 array slots for aOffset[] */
23240  u32 aType[1];           /* Type values record decode.  MUST BE LAST */
23241};
23242
23243/* Return true if P is a null-only cursor
23244*/
23245#define IsNullCursor(P) \
23246  ((P)->eCurType==CURTYPE_PSEUDO && (P)->nullRow && (P)->seekResult==0)
23247
23248/*
23249** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
23250*/
23251#define CACHE_STALE 0
23252
23253/*
23254** Large TEXT or BLOB values can be slow to load, so we want to avoid
23255** loading them more than once.  For that reason, large TEXT and BLOB values
23256** can be stored in a cache defined by this object, and attached to the
23257** VdbeCursor using the pCache field.
23258*/
23259struct VdbeTxtBlbCache {
23260  char *pCValue;        /* A RCStr buffer to hold the value */
23261  i64 iOffset;          /* File offset of the row being cached */
23262  int iCol;             /* Column for which the cache is valid */
23263  u32 cacheStatus;      /* Vdbe.cacheCtr value */
23264  u32 colCacheCtr;      /* Column cache counter */
23265};
23266
23267/*
23268** When a sub-program is executed (OP_Program), a structure of this type
23269** is allocated to store the current value of the program counter, as
23270** well as the current memory cell array and various other frame specific
23271** values stored in the Vdbe struct. When the sub-program is finished,
23272** these values are copied back to the Vdbe from the VdbeFrame structure,
23273** restoring the state of the VM to as it was before the sub-program
23274** began executing.
23275**
23276** The memory for a VdbeFrame object is allocated and managed by a memory
23277** cell in the parent (calling) frame. When the memory cell is deleted or
23278** overwritten, the VdbeFrame object is not freed immediately. Instead, it
23279** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
23280** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
23281** this instead of deleting the VdbeFrame immediately is to avoid recursive
23282** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
23283** child frame are released.
23284**
23285** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
23286** set to NULL if the currently executing frame is the main program.
23287*/
23288typedef struct VdbeFrame VdbeFrame;
23289struct VdbeFrame {
23290  Vdbe *v;                /* VM this frame belongs to */
23291  VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
23292  Op *aOp;                /* Program instructions for parent frame */
23293  Mem *aMem;              /* Array of memory cells for parent frame */
23294  VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
23295  u8 *aOnce;              /* Bitmask used by OP_Once */
23296  void *token;            /* Copy of SubProgram.token */
23297  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
23298  AuxData *pAuxData;      /* Linked list of auxdata allocations */
23299#if SQLITE_DEBUG
23300  u32 iFrameMagic;        /* magic number for sanity checking */
23301#endif
23302  int nCursor;            /* Number of entries in apCsr */
23303  int pc;                 /* Program Counter in parent (calling) frame */
23304  int nOp;                /* Size of aOp array */
23305  int nMem;               /* Number of entries in aMem */
23306  int nChildMem;          /* Number of memory cells for child frame */
23307  int nChildCsr;          /* Number of cursors for child frame */
23308  i64 nChange;            /* Statement changes (Vdbe.nChange)     */
23309  i64 nDbChange;          /* Value of db->nChange */
23310};
23311
23312/* Magic number for sanity checking on VdbeFrame objects */
23313#define SQLITE_FRAME_MAGIC 0x879fb71e
23314
23315/*
23316** Return a pointer to the array of registers allocated for use
23317** by a VdbeFrame.
23318*/
23319#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
23320
23321/*
23322** Internally, the vdbe manipulates nearly all SQL values as Mem
23323** structures. Each Mem struct may cache multiple representations (string,
23324** integer etc.) of the same value.
23325*/
23326struct sqlite3_value {
23327  union MemValue {
23328    double r;           /* Real value used when MEM_Real is set in flags */
23329    i64 i;              /* Integer value used when MEM_Int is set in flags */
23330    int nZero;          /* Extra zero bytes when MEM_Zero and MEM_Blob set */
23331    const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
23332    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
23333  } u;
23334  char *z;            /* String or BLOB value */
23335  int n;              /* Number of characters in string value, excluding '\0' */
23336  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
23337  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
23338  u8  eSubtype;       /* Subtype for this value */
23339  /* ShallowCopy only needs to copy the information above */
23340  sqlite3 *db;        /* The associated database connection */
23341  int szMalloc;       /* Size of the zMalloc allocation */
23342  u32 uTemp;          /* Transient storage for serial_type in OP_MakeRecord */
23343  char *zMalloc;      /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
23344  void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
23345#ifdef SQLITE_DEBUG
23346  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
23347  u16 mScopyFlags;    /* flags value immediately after the shallow copy */
23348#endif
23349};
23350
23351/*
23352** Size of struct Mem not including the Mem.zMalloc member or anything that
23353** follows.
23354*/
23355#define MEMCELLSIZE offsetof(Mem,db)
23356
23357/* One or more of the following flags are set to indicate the
23358** representations of the value stored in the Mem struct.
23359**
23360**  *  MEM_Null                An SQL NULL value
23361**
23362**  *  MEM_Null|MEM_Zero       An SQL NULL with the virtual table
23363**                             UPDATE no-change flag set
23364**
23365**  *  MEM_Null|MEM_Term|      An SQL NULL, but also contains a
23366**        MEM_Subtype          pointer accessible using
23367**                             sqlite3_value_pointer().
23368**
23369**  *  MEM_Null|MEM_Cleared    Special SQL NULL that compares non-equal
23370**                             to other NULLs even using the IS operator.
23371**
23372**  *  MEM_Str                 A string, stored in Mem.z with
23373**                             length Mem.n.  Zero-terminated if
23374**                             MEM_Term is set.  This flag is
23375**                             incompatible with MEM_Blob and
23376**                             MEM_Null, but can appear with MEM_Int,
23377**                             MEM_Real, and MEM_IntReal.
23378**
23379**  *  MEM_Blob                A blob, stored in Mem.z length Mem.n.
23380**                             Incompatible with MEM_Str, MEM_Null,
23381**                             MEM_Int, MEM_Real, and MEM_IntReal.
23382**
23383**  *  MEM_Blob|MEM_Zero       A blob in Mem.z of length Mem.n plus
23384**                             MEM.u.i extra 0x00 bytes at the end.
23385**
23386**  *  MEM_Int                 Integer stored in Mem.u.i.
23387**
23388**  *  MEM_Real                Real stored in Mem.u.r.
23389**
23390**  *  MEM_IntReal             Real stored as an integer in Mem.u.i.
23391**
23392** If the MEM_Null flag is set, then the value is an SQL NULL value.
23393** For a pointer type created using sqlite3_bind_pointer() or
23394** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
23395**
23396** If the MEM_Str flag is set then Mem.z points at a string representation.
23397** Usually this is encoded in the same unicode encoding as the main
23398** database (see below for exceptions). If the MEM_Term flag is also
23399** set, then the string is nul terminated. The MEM_Int and MEM_Real
23400** flags may coexist with the MEM_Str flag.
23401*/
23402#define MEM_Undefined 0x0000   /* Value is undefined */
23403#define MEM_Null      0x0001   /* Value is NULL (or a pointer) */
23404#define MEM_Str       0x0002   /* Value is a string */
23405#define MEM_Int       0x0004   /* Value is an integer */
23406#define MEM_Real      0x0008   /* Value is a real number */
23407#define MEM_Blob      0x0010   /* Value is a BLOB */
23408#define MEM_IntReal   0x0020   /* MEM_Int that stringifies like MEM_Real */
23409#define MEM_AffMask   0x003f   /* Mask of affinity bits */
23410
23411/* Extra bits that modify the meanings of the core datatypes above
23412*/
23413#define MEM_FromBind  0x0040   /* Value originates from sqlite3_bind() */
23414 /*                   0x0080   // Available */
23415#define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
23416#define MEM_Term      0x0200   /* String in Mem.z is zero terminated */
23417#define MEM_Zero      0x0400   /* Mem.i contains count of 0s appended to blob */
23418#define MEM_Subtype   0x0800   /* Mem.eSubtype is valid */
23419#define MEM_TypeMask  0x0dbf   /* Mask of type bits */
23420
23421/* Bits that determine the storage for Mem.z for a string or blob or
23422** aggregate accumulator.
23423*/
23424#define MEM_Dyn       0x1000   /* Need to call Mem.xDel() on Mem.z */
23425#define MEM_Static    0x2000   /* Mem.z points to a static string */
23426#define MEM_Ephem     0x4000   /* Mem.z points to an ephemeral string */
23427#define MEM_Agg       0x8000   /* Mem.z points to an agg function context */
23428
23429/* Return TRUE if Mem X contains dynamically allocated content - anything
23430** that needs to be deallocated to avoid a leak.
23431*/
23432#define VdbeMemDynamic(X)  \
23433  (((X)->flags&(MEM_Agg|MEM_Dyn))!=0)
23434
23435/*
23436** Clear any existing type flags from a Mem and replace them with f
23437*/
23438#define MemSetTypeFlag(p, f) \
23439   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
23440
23441/*
23442** True if Mem X is a NULL-nochng type.
23443*/
23444#define MemNullNochng(X) \
23445  (((X)->flags&MEM_TypeMask)==(MEM_Null|MEM_Zero) \
23446    && (X)->n==0 && (X)->u.nZero==0)
23447
23448/*
23449** Return true if a memory cell has been initialized and is valid.
23450** is for use inside assert() statements only.
23451**
23452** A Memory cell is initialized if at least one of the
23453** MEM_Null, MEM_Str, MEM_Int, MEM_Real, MEM_Blob, or MEM_IntReal bits
23454** is set.  It is "undefined" if all those bits are zero.
23455*/
23456#ifdef SQLITE_DEBUG
23457#define memIsValid(M)  ((M)->flags & MEM_AffMask)!=0
23458#endif
23459
23460/*
23461** Each auxiliary data pointer stored by a user defined function
23462** implementation calling sqlite3_set_auxdata() is stored in an instance
23463** of this structure. All such structures associated with a single VM
23464** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
23465** when the VM is halted (if not before).
23466*/
23467struct AuxData {
23468  int iAuxOp;                     /* Instruction number of OP_Function opcode */
23469  int iAuxArg;                    /* Index of function argument. */
23470  void *pAux;                     /* Aux data pointer */
23471  void (*xDeleteAux)(void*);      /* Destructor for the aux data */
23472  AuxData *pNextAux;              /* Next element in list */
23473};
23474
23475/*
23476** The "context" argument for an installable function.  A pointer to an
23477** instance of this structure is the first argument to the routines used
23478** implement the SQL functions.
23479**
23480** There is a typedef for this structure in sqlite.h.  So all routines,
23481** even the public interface to SQLite, can use a pointer to this structure.
23482** But this file is the only place where the internal details of this
23483** structure are known.
23484**
23485** This structure is defined inside of vdbeInt.h because it uses substructures
23486** (Mem) which are only defined there.
23487*/
23488struct sqlite3_context {
23489  Mem *pOut;              /* The return value is stored here */
23490  FuncDef *pFunc;         /* Pointer to function information */
23491  Mem *pMem;              /* Memory cell used to store aggregate context */
23492  Vdbe *pVdbe;            /* The VM that owns this context */
23493  int iOp;                /* Instruction number of OP_Function */
23494  int isError;            /* Error code returned by the function. */
23495  u8 enc;                 /* Encoding to use for results */
23496  u8 skipFlag;            /* Skip accumulator loading if true */
23497  u8 argc;                /* Number of arguments */
23498  sqlite3_value *argv[1]; /* Argument set */
23499};
23500
23501/* A bitfield type for use inside of structures.  Always follow with :N where
23502** N is the number of bits.
23503*/
23504typedef unsigned bft;  /* Bit Field Type */
23505
23506/* The ScanStatus object holds a single value for the
23507** sqlite3_stmt_scanstatus() interface.
23508**
23509** aAddrRange[]:
23510**   This array is used by ScanStatus elements associated with EQP
23511**   notes that make an SQLITE_SCANSTAT_NCYCLE value available. It is
23512**   an array of up to 3 ranges of VM addresses for which the Vdbe.anCycle[]
23513**   values should be summed to calculate the NCYCLE value. Each pair of
23514**   integer addresses is a start and end address (both inclusive) for a range
23515**   instructions. A start value of 0 indicates an empty range.
23516*/
23517typedef struct ScanStatus ScanStatus;
23518struct ScanStatus {
23519  int addrExplain;                /* OP_Explain for loop */
23520  int aAddrRange[6];
23521  int addrLoop;                   /* Address of "loops" counter */
23522  int addrVisit;                  /* Address of "rows visited" counter */
23523  int iSelectID;                  /* The "Select-ID" for this loop */
23524  LogEst nEst;                    /* Estimated output rows per loop */
23525  char *zName;                    /* Name of table or index */
23526};
23527
23528/* The DblquoteStr object holds the text of a double-quoted
23529** string for a prepared statement.  A linked list of these objects
23530** is constructed during statement parsing and is held on Vdbe.pDblStr.
23531** When computing a normalized SQL statement for an SQL statement, that
23532** list is consulted for each double-quoted identifier to see if the
23533** identifier should really be a string literal.
23534*/
23535typedef struct DblquoteStr DblquoteStr;
23536struct DblquoteStr {
23537  DblquoteStr *pNextStr;   /* Next string literal in the list */
23538  char z[8];               /* Dequoted value for the string */
23539};
23540
23541/*
23542** An instance of the virtual machine.  This structure contains the complete
23543** state of the virtual machine.
23544**
23545** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
23546** is really a pointer to an instance of this structure.
23547*/
23548struct Vdbe {
23549  sqlite3 *db;            /* The database connection that owns this statement */
23550  Vdbe **ppVPrev,*pVNext; /* Linked list of VDBEs with the same Vdbe.db */
23551  Parse *pParse;          /* Parsing context used to create this Vdbe */
23552  ynVar nVar;             /* Number of entries in aVar[] */
23553  int nMem;               /* Number of memory locations currently allocated */
23554  int nCursor;            /* Number of slots in apCsr[] */
23555  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
23556  int pc;                 /* The program counter */
23557  int rc;                 /* Value to return */
23558  i64 nChange;            /* Number of db changes made since last reset */
23559  int iStatement;         /* Statement number (or 0 if has no opened stmt) */
23560  i64 iCurrentTime;       /* Value of julianday('now') for this statement */
23561  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
23562  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
23563  i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
23564  Mem *aMem;              /* The memory locations */
23565  Mem **apArg;            /* Arguments to currently executing user function */
23566  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
23567  Mem *aVar;              /* Values for the OP_Variable opcode. */
23568
23569  /* When allocating a new Vdbe object, all of the fields below should be
23570  ** initialized to zero or NULL */
23571
23572  Op *aOp;                /* Space to hold the virtual machine's program */
23573  int nOp;                /* Number of instructions in the program */
23574  int nOpAlloc;           /* Slots allocated for aOp[] */
23575  Mem *aColName;          /* Column names to return */
23576  Mem *pResultRow;        /* Current output row */
23577  char *zErrMsg;          /* Error message written here */
23578  VList *pVList;          /* Name of variables */
23579#ifndef SQLITE_OMIT_TRACE
23580  i64 startTime;          /* Time when query started - used for profiling */
23581#endif
23582#ifdef SQLITE_DEBUG
23583  int rcApp;              /* errcode set by sqlite3_result_error_code() */
23584  u32 nWrite;             /* Number of write operations that have occurred */
23585#endif
23586  u16 nResColumn;         /* Number of columns in one row of the result set */
23587  u16 nResAlloc;          /* Column slots allocated to aColName[] */
23588  u8 errorAction;         /* Recovery action to do in case of an error */
23589  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
23590  u8 prepFlags;           /* SQLITE_PREPARE_* flags */
23591  u8 eVdbeState;          /* On of the VDBE_*_STATE values */
23592  bft expired:2;          /* 1: recompile VM immediately  2: when convenient */
23593  bft explain:2;          /* 0: normal, 1: EXPLAIN, 2: EXPLAIN QUERY PLAN */
23594  bft changeCntOn:1;      /* True to update the change-counter */
23595  bft usesStmtJournal:1;  /* True if uses a statement journal */
23596  bft readOnly:1;         /* True for statements that do not write */
23597  bft bIsReader:1;        /* True for statements that read */
23598  bft haveEqpOps:1;       /* Bytecode supports EXPLAIN QUERY PLAN */
23599  yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
23600  yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
23601  u32 aCounter[9];        /* Counters used by sqlite3_stmt_status() */
23602  char *zSql;             /* Text of the SQL statement that generated this */
23603#ifdef SQLITE_ENABLE_NORMALIZE
23604  char *zNormSql;         /* Normalization of the associated SQL statement */
23605  DblquoteStr *pDblStr;   /* List of double-quoted string literals */
23606#endif
23607  void *pFree;            /* Free this when deleting the vdbe */
23608  VdbeFrame *pFrame;      /* Parent frame */
23609  VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
23610  int nFrame;             /* Number of frames in pFrame list */
23611  u32 expmask;            /* Binding to these vars invalidates VM */
23612  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
23613  AuxData *pAuxData;      /* Linked list of auxdata allocations */
23614#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
23615  int nScan;              /* Entries in aScan[] */
23616  ScanStatus *aScan;      /* Scan definitions for sqlite3_stmt_scanstatus() */
23617#endif
23618};
23619
23620/*
23621** The following are allowed values for Vdbe.eVdbeState
23622*/
23623#define VDBE_INIT_STATE     0   /* Prepared statement under construction */
23624#define VDBE_READY_STATE    1   /* Ready to run but not yet started */
23625#define VDBE_RUN_STATE      2   /* Run in progress */
23626#define VDBE_HALT_STATE     3   /* Finished.  Need reset() or finalize() */
23627
23628/*
23629** Structure used to store the context required by the
23630** sqlite3_preupdate_*() API functions.
23631*/
23632struct PreUpdate {
23633  Vdbe *v;
23634  VdbeCursor *pCsr;               /* Cursor to read old values from */
23635  int op;                         /* One of SQLITE_INSERT, UPDATE, DELETE */
23636  u8 *aRecord;                    /* old.* database record */
23637  KeyInfo keyinfo;
23638  UnpackedRecord *pUnpacked;      /* Unpacked version of aRecord[] */
23639  UnpackedRecord *pNewUnpacked;   /* Unpacked version of new.* record */
23640  int iNewReg;                    /* Register for new.* values */
23641  int iBlobWrite;                 /* Value returned by preupdate_blobwrite() */
23642  i64 iKey1;                      /* First key value passed to hook */
23643  i64 iKey2;                      /* Second key value passed to hook */
23644  Mem *aNew;                      /* Array of new.* values */
23645  Table *pTab;                    /* Schema object being updated */
23646  Index *pPk;                     /* PK index if pTab is WITHOUT ROWID */
23647};
23648
23649/*
23650** An instance of this object is used to pass an vector of values into
23651** OP_VFilter, the xFilter method of a virtual table.  The vector is the
23652** set of values on the right-hand side of an IN constraint.
23653**
23654** The value as passed into xFilter is an sqlite3_value with a "pointer"
23655** type, such as is generated by sqlite3_result_pointer() and read by
23656** sqlite3_value_pointer.  Such values have MEM_Term|MEM_Subtype|MEM_Null
23657** and a subtype of 'p'.  The sqlite3_vtab_in_first() and _next() interfaces
23658** know how to use this object to step through all the values in the
23659** right operand of the IN constraint.
23660*/
23661typedef struct ValueList ValueList;
23662struct ValueList {
23663  BtCursor *pCsr;          /* An ephemeral table holding all values */
23664  sqlite3_value *pOut;     /* Register to hold each decoded output value */
23665};
23666
23667/* Size of content associated with serial types that fit into a
23668** single-byte varint.
23669*/
23670#ifndef SQLITE_AMALGAMATION
23671SQLITE_PRIVATE const u8 sqlite3SmallTypeSizes[];
23672#endif
23673
23674/*
23675** Function prototypes
23676*/
23677SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
23678SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
23679SQLITE_PRIVATE void sqlite3VdbeFreeCursorNN(Vdbe*,VdbeCursor*);
23680void sqliteVdbePopStack(Vdbe*,int);
23681SQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeHandleMovedCursor(VdbeCursor *p);
23682SQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor*);
23683SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
23684SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
23685SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
23686#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
23687SQLITE_PRIVATE   u64 sqlite3FloatSwap(u64 in);
23688# define swapMixedEndianFloat(X)  X = sqlite3FloatSwap(X)
23689#else
23690# define swapMixedEndianFloat(X)
23691#endif
23692SQLITE_PRIVATE void sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
23693SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
23694
23695int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
23696SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
23697SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
23698SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
23699#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)
23700SQLITE_PRIVATE int sqlite3VdbeNextOpcode(Vdbe*,Mem*,int,int*,int*,Op**);
23701SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3*,Op*);
23702#endif
23703#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
23704SQLITE_PRIVATE char *sqlite3VdbeDisplayComment(sqlite3*,const Op*,const char*);
23705#endif
23706#if !defined(SQLITE_OMIT_EXPLAIN)
23707SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
23708#endif
23709SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
23710SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
23711SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
23712SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
23713SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
23714SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
23715SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
23716SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, i64, u8, void(*)(void*));
23717SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
23718#ifdef SQLITE_OMIT_FLOATING_POINT
23719# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
23720#else
23721SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
23722#endif
23723SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
23724SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
23725SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
23726#ifndef SQLITE_OMIT_INCRBLOB
23727SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
23728#else
23729SQLITE_PRIVATE int sqlite3VdbeMemSetZeroBlob(Mem*,int);
23730#endif
23731#ifdef SQLITE_DEBUG
23732SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem*);
23733#endif
23734SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem*);
23735SQLITE_PRIVATE void sqlite3VdbeMemZeroTerminateIfAble(Mem*);
23736SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
23737SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
23738SQLITE_PRIVATE int sqlite3IntFloatCompare(i64,double);
23739SQLITE_PRIVATE i64 sqlite3VdbeIntValue(const Mem*);
23740SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
23741SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
23742SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);
23743SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
23744SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
23745SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
23746SQLITE_PRIVATE int sqlite3VdbeMemCast(Mem*,u8,u8);
23747SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
23748SQLITE_PRIVATE int sqlite3VdbeMemFromBtreeZeroOffset(BtCursor*,u32,Mem*);
23749SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
23750SQLITE_PRIVATE void sqlite3VdbeMemReleaseMalloc(Mem*p);
23751SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
23752#ifndef SQLITE_OMIT_WINDOWFUNC
23753SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*);
23754#endif
23755#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)
23756SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
23757#endif
23758SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
23759SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
23760SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
23761#ifdef SQLITE_DEBUG
23762SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame*);
23763#endif
23764SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void*);      /* Destructor on Mem */
23765SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */
23766SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
23767#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
23768SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
23769    Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int,int);
23770#endif
23771SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
23772
23773SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
23774SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
23775SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
23776SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
23777SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
23778SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
23779SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
23780SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
23781
23782SQLITE_PRIVATE void sqlite3VdbeValueListFree(void*);
23783
23784#ifdef SQLITE_DEBUG
23785SQLITE_PRIVATE   void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*);
23786SQLITE_PRIVATE   void sqlite3VdbeAssertAbortable(Vdbe*);
23787#else
23788# define sqlite3VdbeIncrWriteCounter(V,C)
23789# define sqlite3VdbeAssertAbortable(V)
23790#endif
23791
23792#if !defined(SQLITE_OMIT_SHARED_CACHE)
23793SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
23794#else
23795# define sqlite3VdbeEnter(X)
23796#endif
23797
23798#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
23799SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
23800#else
23801# define sqlite3VdbeLeave(X)
23802#endif
23803
23804#ifdef SQLITE_DEBUG
23805SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
23806SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
23807#endif
23808
23809#ifndef SQLITE_OMIT_FOREIGN_KEY
23810SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
23811#else
23812# define sqlite3VdbeCheckFk(p,i) 0
23813#endif
23814
23815#ifdef SQLITE_DEBUG
23816SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
23817SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr);
23818#endif
23819#ifndef SQLITE_OMIT_UTF16
23820SQLITE_PRIVATE   int sqlite3VdbeMemTranslate(Mem*, u8);
23821SQLITE_PRIVATE   int sqlite3VdbeMemHandleBom(Mem *pMem);
23822#endif
23823
23824#ifndef SQLITE_OMIT_INCRBLOB
23825SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
23826  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
23827#else
23828  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
23829  #define ExpandBlob(P) SQLITE_OK
23830#endif
23831
23832#endif /* !defined(SQLITE_VDBEINT_H) */
23833
23834/************** End of vdbeInt.h *********************************************/
23835/************** Continuing where we left off in status.c *********************/
23836
23837/*
23838** Variables in which to record status information.
23839*/
23840#if SQLITE_PTRSIZE>4
23841typedef sqlite3_int64 sqlite3StatValueType;
23842#else
23843typedef u32 sqlite3StatValueType;
23844#endif
23845typedef struct sqlite3StatType sqlite3StatType;
23846static SQLITE_WSD struct sqlite3StatType {
23847  sqlite3StatValueType nowValue[10];  /* Current value */
23848  sqlite3StatValueType mxValue[10];   /* Maximum value */
23849} sqlite3Stat = { {0,}, {0,} };
23850
23851/*
23852** Elements of sqlite3Stat[] are protected by either the memory allocator
23853** mutex, or by the pcache1 mutex.  The following array determines which.
23854*/
23855static const char statMutex[] = {
23856  0,  /* SQLITE_STATUS_MEMORY_USED */
23857  1,  /* SQLITE_STATUS_PAGECACHE_USED */
23858  1,  /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
23859  0,  /* SQLITE_STATUS_SCRATCH_USED */
23860  0,  /* SQLITE_STATUS_SCRATCH_OVERFLOW */
23861  0,  /* SQLITE_STATUS_MALLOC_SIZE */
23862  0,  /* SQLITE_STATUS_PARSER_STACK */
23863  1,  /* SQLITE_STATUS_PAGECACHE_SIZE */
23864  0,  /* SQLITE_STATUS_SCRATCH_SIZE */
23865  0,  /* SQLITE_STATUS_MALLOC_COUNT */
23866};
23867
23868
23869/* The "wsdStat" macro will resolve to the status information
23870** state vector.  If writable static data is unsupported on the target,
23871** we have to locate the state vector at run-time.  In the more common
23872** case where writable static data is supported, wsdStat can refer directly
23873** to the "sqlite3Stat" state vector declared above.
23874*/
23875#ifdef SQLITE_OMIT_WSD
23876# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
23877# define wsdStat x[0]
23878#else
23879# define wsdStatInit
23880# define wsdStat sqlite3Stat
23881#endif
23882
23883/*
23884** Return the current value of a status parameter.  The caller must
23885** be holding the appropriate mutex.
23886*/
23887SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
23888  wsdStatInit;
23889  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
23890  assert( op>=0 && op<ArraySize(statMutex) );
23891  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
23892                                           : sqlite3MallocMutex()) );
23893  return wsdStat.nowValue[op];
23894}
23895
23896/*
23897** Add N to the value of a status record.  The caller must hold the
23898** appropriate mutex.  (Locking is checked by assert()).
23899**
23900** The StatusUp() routine can accept positive or negative values for N.
23901** The value of N is added to the current status value and the high-water
23902** mark is adjusted if necessary.
23903**
23904** The StatusDown() routine lowers the current value by N.  The highwater
23905** mark is unchanged.  N must be non-negative for StatusDown().
23906*/
23907SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
23908  wsdStatInit;
23909  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
23910  assert( op>=0 && op<ArraySize(statMutex) );
23911  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
23912                                           : sqlite3MallocMutex()) );
23913  wsdStat.nowValue[op] += N;
23914  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
23915    wsdStat.mxValue[op] = wsdStat.nowValue[op];
23916  }
23917}
23918SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
23919  wsdStatInit;
23920  assert( N>=0 );
23921  assert( op>=0 && op<ArraySize(statMutex) );
23922  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
23923                                           : sqlite3MallocMutex()) );
23924  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
23925  wsdStat.nowValue[op] -= N;
23926}
23927
23928/*
23929** Adjust the highwater mark if necessary.
23930** The caller must hold the appropriate mutex.
23931*/
23932SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
23933  sqlite3StatValueType newValue;
23934  wsdStatInit;
23935  assert( X>=0 );
23936  newValue = (sqlite3StatValueType)X;
23937  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
23938  assert( op>=0 && op<ArraySize(statMutex) );
23939  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
23940                                           : sqlite3MallocMutex()) );
23941  assert( op==SQLITE_STATUS_MALLOC_SIZE
23942          || op==SQLITE_STATUS_PAGECACHE_SIZE
23943          || op==SQLITE_STATUS_PARSER_STACK );
23944  if( newValue>wsdStat.mxValue[op] ){
23945    wsdStat.mxValue[op] = newValue;
23946  }
23947}
23948
23949/*
23950** Query status information.
23951*/
23952SQLITE_API int sqlite3_status64(
23953  int op,
23954  sqlite3_int64 *pCurrent,
23955  sqlite3_int64 *pHighwater,
23956  int resetFlag
23957){
23958  sqlite3_mutex *pMutex;
23959  wsdStatInit;
23960  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
23961    return SQLITE_MISUSE_BKPT;
23962  }
23963#ifdef SQLITE_ENABLE_API_ARMOR
23964  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
23965#endif
23966  pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
23967  sqlite3_mutex_enter(pMutex);
23968  *pCurrent = wsdStat.nowValue[op];
23969  *pHighwater = wsdStat.mxValue[op];
23970  if( resetFlag ){
23971    wsdStat.mxValue[op] = wsdStat.nowValue[op];
23972  }
23973  sqlite3_mutex_leave(pMutex);
23974  (void)pMutex;  /* Prevent warning when SQLITE_THREADSAFE=0 */
23975  return SQLITE_OK;
23976}
23977SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
23978  sqlite3_int64 iCur = 0, iHwtr = 0;
23979  int rc;
23980#ifdef SQLITE_ENABLE_API_ARMOR
23981  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
23982#endif
23983  rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
23984  if( rc==0 ){
23985    *pCurrent = (int)iCur;
23986    *pHighwater = (int)iHwtr;
23987  }
23988  return rc;
23989}
23990
23991/*
23992** Return the number of LookasideSlot elements on the linked list
23993*/
23994static u32 countLookasideSlots(LookasideSlot *p){
23995  u32 cnt = 0;
23996  while( p ){
23997    p = p->pNext;
23998    cnt++;
23999  }
24000  return cnt;
24001}
24002
24003/*
24004** Count the number of slots of lookaside memory that are outstanding
24005*/
24006SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
24007  u32 nInit = countLookasideSlots(db->lookaside.pInit);
24008  u32 nFree = countLookasideSlots(db->lookaside.pFree);
24009#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
24010  nInit += countLookasideSlots(db->lookaside.pSmallInit);
24011  nFree += countLookasideSlots(db->lookaside.pSmallFree);
24012#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
24013  if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
24014  return db->lookaside.nSlot - (nInit+nFree);
24015}
24016
24017/*
24018** Query status information for a single database connection
24019*/
24020SQLITE_API int sqlite3_db_status(
24021  sqlite3 *db,          /* The database connection whose status is desired */
24022  int op,               /* Status verb */
24023  int *pCurrent,        /* Write current value here */
24024  int *pHighwater,      /* Write high-water mark here */
24025  int resetFlag         /* Reset high-water mark if true */
24026){
24027  int rc = SQLITE_OK;   /* Return code */
24028#ifdef SQLITE_ENABLE_API_ARMOR
24029  if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
24030    return SQLITE_MISUSE_BKPT;
24031  }
24032#endif
24033  sqlite3_mutex_enter(db->mutex);
24034  switch( op ){
24035    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
24036      *pCurrent = sqlite3LookasideUsed(db, pHighwater);
24037      if( resetFlag ){
24038        LookasideSlot *p = db->lookaside.pFree;
24039        if( p ){
24040          while( p->pNext ) p = p->pNext;
24041          p->pNext = db->lookaside.pInit;
24042          db->lookaside.pInit = db->lookaside.pFree;
24043          db->lookaside.pFree = 0;
24044        }
24045#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
24046        p = db->lookaside.pSmallFree;
24047        if( p ){
24048          while( p->pNext ) p = p->pNext;
24049          p->pNext = db->lookaside.pSmallInit;
24050          db->lookaside.pSmallInit = db->lookaside.pSmallFree;
24051          db->lookaside.pSmallFree = 0;
24052        }
24053#endif
24054      }
24055      break;
24056    }
24057
24058    case SQLITE_DBSTATUS_LOOKASIDE_HIT:
24059    case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
24060    case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
24061      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
24062      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
24063      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
24064      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
24065      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
24066      *pCurrent = 0;
24067      *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
24068      if( resetFlag ){
24069        db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
24070      }
24071      break;
24072    }
24073
24074    /*
24075    ** Return an approximation for the amount of memory currently used
24076    ** by all pagers associated with the given database connection.  The
24077    ** highwater mark is meaningless and is returned as zero.
24078    */
24079    case SQLITE_DBSTATUS_CACHE_USED_SHARED:
24080    case SQLITE_DBSTATUS_CACHE_USED: {
24081      int totalUsed = 0;
24082      int i;
24083      sqlite3BtreeEnterAll(db);
24084      for(i=0; i<db->nDb; i++){
24085        Btree *pBt = db->aDb[i].pBt;
24086        if( pBt ){
24087          Pager *pPager = sqlite3BtreePager(pBt);
24088          int nByte = sqlite3PagerMemUsed(pPager);
24089          if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
24090            nByte = nByte / sqlite3BtreeConnectionCount(pBt);
24091          }
24092          totalUsed += nByte;
24093        }
24094      }
24095      sqlite3BtreeLeaveAll(db);
24096      *pCurrent = totalUsed;
24097      *pHighwater = 0;
24098      break;
24099    }
24100
24101    /*
24102    ** *pCurrent gets an accurate estimate of the amount of memory used
24103    ** to store the schema for all databases (main, temp, and any ATTACHed
24104    ** databases.  *pHighwater is set to zero.
24105    */
24106    case SQLITE_DBSTATUS_SCHEMA_USED: {
24107      int i;                      /* Used to iterate through schemas */
24108      int nByte = 0;              /* Used to accumulate return value */
24109
24110      sqlite3BtreeEnterAll(db);
24111      db->pnBytesFreed = &nByte;
24112      assert( db->lookaside.pEnd==db->lookaside.pTrueEnd );
24113      db->lookaside.pEnd = db->lookaside.pStart;
24114      for(i=0; i<db->nDb; i++){
24115        Schema *pSchema = db->aDb[i].pSchema;
24116        if( ALWAYS(pSchema!=0) ){
24117          HashElem *p;
24118
24119          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
24120              pSchema->tblHash.count
24121            + pSchema->trigHash.count
24122            + pSchema->idxHash.count
24123            + pSchema->fkeyHash.count
24124          );
24125          nByte += sqlite3_msize(pSchema->tblHash.ht);
24126          nByte += sqlite3_msize(pSchema->trigHash.ht);
24127          nByte += sqlite3_msize(pSchema->idxHash.ht);
24128          nByte += sqlite3_msize(pSchema->fkeyHash.ht);
24129
24130          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
24131            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
24132          }
24133          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
24134            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
24135          }
24136        }
24137      }
24138      db->pnBytesFreed = 0;
24139      db->lookaside.pEnd = db->lookaside.pTrueEnd;
24140      sqlite3BtreeLeaveAll(db);
24141
24142      *pHighwater = 0;
24143      *pCurrent = nByte;
24144      break;
24145    }
24146
24147    /*
24148    ** *pCurrent gets an accurate estimate of the amount of memory used
24149    ** to store all prepared statements.
24150    ** *pHighwater is set to zero.
24151    */
24152    case SQLITE_DBSTATUS_STMT_USED: {
24153      struct Vdbe *pVdbe;         /* Used to iterate through VMs */
24154      int nByte = 0;              /* Used to accumulate return value */
24155
24156      db->pnBytesFreed = &nByte;
24157      assert( db->lookaside.pEnd==db->lookaside.pTrueEnd );
24158      db->lookaside.pEnd = db->lookaside.pStart;
24159      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pVNext){
24160        sqlite3VdbeDelete(pVdbe);
24161      }
24162      db->lookaside.pEnd = db->lookaside.pTrueEnd;
24163      db->pnBytesFreed = 0;
24164
24165      *pHighwater = 0;  /* IMP: R-64479-57858 */
24166      *pCurrent = nByte;
24167
24168      break;
24169    }
24170
24171    /*
24172    ** Set *pCurrent to the total cache hits or misses encountered by all
24173    ** pagers the database handle is connected to. *pHighwater is always set
24174    ** to zero.
24175    */
24176    case SQLITE_DBSTATUS_CACHE_SPILL:
24177      op = SQLITE_DBSTATUS_CACHE_WRITE+1;
24178      /* no break */ deliberate_fall_through
24179    case SQLITE_DBSTATUS_CACHE_HIT:
24180    case SQLITE_DBSTATUS_CACHE_MISS:
24181    case SQLITE_DBSTATUS_CACHE_WRITE:{
24182      int i;
24183      u64 nRet = 0;
24184      assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
24185      assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
24186
24187      for(i=0; i<db->nDb; i++){
24188        if( db->aDb[i].pBt ){
24189          Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
24190          sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
24191        }
24192      }
24193      *pHighwater = 0; /* IMP: R-42420-56072 */
24194                       /* IMP: R-54100-20147 */
24195                       /* IMP: R-29431-39229 */
24196      *pCurrent = (int)nRet & 0x7fffffff;
24197      break;
24198    }
24199
24200    /* Set *pCurrent to non-zero if there are unresolved deferred foreign
24201    ** key constraints.  Set *pCurrent to zero if all foreign key constraints
24202    ** have been satisfied.  The *pHighwater is always set to zero.
24203    */
24204    case SQLITE_DBSTATUS_DEFERRED_FKS: {
24205      *pHighwater = 0;  /* IMP: R-11967-56545 */
24206      *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
24207      break;
24208    }
24209
24210    default: {
24211      rc = SQLITE_ERROR;
24212    }
24213  }
24214  sqlite3_mutex_leave(db->mutex);
24215  return rc;
24216}
24217
24218/************** End of status.c **********************************************/
24219/************** Begin file date.c ********************************************/
24220/*
24221** 2003 October 31
24222**
24223** The author disclaims copyright to this source code.  In place of
24224** a legal notice, here is a blessing:
24225**
24226**    May you do good and not evil.
24227**    May you find forgiveness for yourself and forgive others.
24228**    May you share freely, never taking more than you give.
24229**
24230*************************************************************************
24231** This file contains the C functions that implement date and time
24232** functions for SQLite.
24233**
24234** There is only one exported symbol in this file - the function
24235** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
24236** All other code has file scope.
24237**
24238** SQLite processes all times and dates as julian day numbers.  The
24239** dates and times are stored as the number of days since noon
24240** in Greenwich on November 24, 4714 B.C. according to the Gregorian
24241** calendar system.
24242**
24243** 1970-01-01 00:00:00 is JD 2440587.5
24244** 2000-01-01 00:00:00 is JD 2451544.5
24245**
24246** This implementation requires years to be expressed as a 4-digit number
24247** which means that only dates between 0000-01-01 and 9999-12-31 can
24248** be represented, even though julian day numbers allow a much wider
24249** range of dates.
24250**
24251** The Gregorian calendar system is used for all dates and times,
24252** even those that predate the Gregorian calendar.  Historians usually
24253** use the julian calendar for dates prior to 1582-10-15 and for some
24254** dates afterwards, depending on locale.  Beware of this difference.
24255**
24256** The conversion algorithms are implemented based on descriptions
24257** in the following text:
24258**
24259**      Jean Meeus
24260**      Astronomical Algorithms, 2nd Edition, 1998
24261**      ISBN 0-943396-61-1
24262**      Willmann-Bell, Inc
24263**      Richmond, Virginia (USA)
24264*/
24265/* #include "sqliteInt.h" */
24266/* #include <stdlib.h> */
24267/* #include <assert.h> */
24268#include <time.h>
24269
24270#ifndef SQLITE_OMIT_DATETIME_FUNCS
24271
24272/*
24273** The MSVC CRT on Windows CE may not have a localtime() function.
24274** So declare a substitute.  The substitute function itself is
24275** defined in "os_win.c".
24276*/
24277#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
24278    (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
24279struct tm *__cdecl localtime(const time_t *);
24280#endif
24281
24282/*
24283** A structure for holding a single date and time.
24284*/
24285typedef struct DateTime DateTime;
24286struct DateTime {
24287  sqlite3_int64 iJD;  /* The julian day number times 86400000 */
24288  int Y, M, D;        /* Year, month, and day */
24289  int h, m;           /* Hour and minutes */
24290  int tz;             /* Timezone offset in minutes */
24291  double s;           /* Seconds */
24292  char validJD;       /* True (1) if iJD is valid */
24293  char validYMD;      /* True (1) if Y,M,D are valid */
24294  char validHMS;      /* True (1) if h,m,s are valid */
24295  char nFloor;            /* Days to implement "floor" */
24296  unsigned rawS      : 1; /* Raw numeric value stored in s */
24297  unsigned isError   : 1; /* An overflow has occurred */
24298  unsigned useSubsec : 1; /* Display subsecond precision */
24299  unsigned isUtc     : 1; /* Time is known to be UTC */
24300  unsigned isLocal   : 1; /* Time is known to be localtime */
24301};
24302
24303
24304/*
24305** Convert zDate into one or more integers according to the conversion
24306** specifier zFormat.
24307**
24308** zFormat[] contains 4 characters for each integer converted, except for
24309** the last integer which is specified by three characters.  The meaning
24310** of a four-character format specifiers ABCD is:
24311**
24312**    A:   number of digits to convert.  Always "2" or "4".
24313**    B:   minimum value.  Always "0" or "1".
24314**    C:   maximum value, decoded as:
24315**           a:  12
24316**           b:  14
24317**           c:  24
24318**           d:  31
24319**           e:  59
24320**           f:  9999
24321**    D:   the separator character, or \000 to indicate this is the
24322**         last number to convert.
24323**
24324** Example:  To translate an ISO-8601 date YYYY-MM-DD, the format would
24325** be "40f-21a-20c".  The "40f-" indicates the 4-digit year followed by "-".
24326** The "21a-" indicates the 2-digit month followed by "-".  The "20c" indicates
24327** the 2-digit day which is the last integer in the set.
24328**
24329** The function returns the number of successful conversions.
24330*/
24331static int getDigits(const char *zDate, const char *zFormat, ...){
24332  /* The aMx[] array translates the 3rd character of each format
24333  ** spec into a max size:    a   b   c   d   e      f */
24334  static const u16 aMx[] = { 12, 14, 24, 31, 59, 14712 };
24335  va_list ap;
24336  int cnt = 0;
24337  char nextC;
24338  va_start(ap, zFormat);
24339  do{
24340    char N = zFormat[0] - '0';
24341    char min = zFormat[1] - '0';
24342    int val = 0;
24343    u16 max;
24344
24345    assert( zFormat[2]>='a' && zFormat[2]<='f' );
24346    max = aMx[zFormat[2] - 'a'];
24347    nextC = zFormat[3];
24348    val = 0;
24349    while( N-- ){
24350      if( !sqlite3Isdigit(*zDate) ){
24351        goto end_getDigits;
24352      }
24353      val = val*10 + *zDate - '0';
24354      zDate++;
24355    }
24356    if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
24357      goto end_getDigits;
24358    }
24359    *va_arg(ap,int*) = val;
24360    zDate++;
24361    cnt++;
24362    zFormat += 4;
24363  }while( nextC );
24364end_getDigits:
24365  va_end(ap);
24366  return cnt;
24367}
24368
24369/*
24370** Parse a timezone extension on the end of a date-time.
24371** The extension is of the form:
24372**
24373**        (+/-)HH:MM
24374**
24375** Or the "zulu" notation:
24376**
24377**        Z
24378**
24379** If the parse is successful, write the number of minutes
24380** of change in p->tz and return 0.  If a parser error occurs,
24381** return non-zero.
24382**
24383** A missing specifier is not considered an error.
24384*/
24385static int parseTimezone(const char *zDate, DateTime *p){
24386  int sgn = 0;
24387  int nHr, nMn;
24388  int c;
24389  while( sqlite3Isspace(*zDate) ){ zDate++; }
24390  p->tz = 0;
24391  c = *zDate;
24392  if( c=='-' ){
24393    sgn = -1;
24394  }else if( c=='+' ){
24395    sgn = +1;
24396  }else if( c=='Z' || c=='z' ){
24397    zDate++;
24398    p->isLocal = 0;
24399    p->isUtc = 1;
24400    goto zulu_time;
24401  }else{
24402    return c!=0;
24403  }
24404  zDate++;
24405  if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
24406    return 1;
24407  }
24408  zDate += 5;
24409  p->tz = sgn*(nMn + nHr*60);
24410zulu_time:
24411  while( sqlite3Isspace(*zDate) ){ zDate++; }
24412  return *zDate!=0;
24413}
24414
24415/*
24416** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
24417** The HH, MM, and SS must each be exactly 2 digits.  The
24418** fractional seconds FFFF can be one or more digits.
24419**
24420** Return 1 if there is a parsing error and 0 on success.
24421*/
24422static int parseHhMmSs(const char *zDate, DateTime *p){
24423  int h, m, s;
24424  double ms = 0.0;
24425  if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
24426    return 1;
24427  }
24428  zDate += 5;
24429  if( *zDate==':' ){
24430    zDate++;
24431    if( getDigits(zDate, "20e", &s)!=1 ){
24432      return 1;
24433    }
24434    zDate += 2;
24435    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
24436      double rScale = 1.0;
24437      zDate++;
24438      while( sqlite3Isdigit(*zDate) ){
24439        ms = ms*10.0 + *zDate - '0';
24440        rScale *= 10.0;
24441        zDate++;
24442      }
24443      ms /= rScale;
24444    }
24445  }else{
24446    s = 0;
24447  }
24448  p->validJD = 0;
24449  p->rawS = 0;
24450  p->validHMS = 1;
24451  p->h = h;
24452  p->m = m;
24453  p->s = s + ms;
24454  if( parseTimezone(zDate, p) ) return 1;
24455  return 0;
24456}
24457
24458/*
24459** Put the DateTime object into its error state.
24460*/
24461static void datetimeError(DateTime *p){
24462  memset(p, 0, sizeof(*p));
24463  p->isError = 1;
24464}
24465
24466/*
24467** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
24468** that the YYYY-MM-DD is according to the Gregorian calendar.
24469**
24470** Reference:  Meeus page 61
24471*/
24472static void computeJD(DateTime *p){
24473  int Y, M, D, A, B, X1, X2;
24474
24475  if( p->validJD ) return;
24476  if( p->validYMD ){
24477    Y = p->Y;
24478    M = p->M;
24479    D = p->D;
24480  }else{
24481    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
24482    M = 1;
24483    D = 1;
24484  }
24485  if( Y<-4713 || Y>9999 || p->rawS ){
24486    datetimeError(p);
24487    return;
24488  }
24489  if( M<=2 ){
24490    Y--;
24491    M += 12;
24492  }
24493  A = Y/100;
24494  B = 2 - A + (A/4);
24495  X1 = 36525*(Y+4716)/100;
24496  X2 = 306001*(M+1)/10000;
24497  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
24498  p->validJD = 1;
24499  if( p->validHMS ){
24500    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000 + 0.5);
24501    if( p->tz ){
24502      p->iJD -= p->tz*60000;
24503      p->validYMD = 0;
24504      p->validHMS = 0;
24505      p->tz = 0;
24506      p->isUtc = 1;
24507      p->isLocal = 0;
24508    }
24509  }
24510}
24511
24512/*
24513** Given the YYYY-MM-DD information current in p, determine if there
24514** is day-of-month overflow and set nFloor to the number of days that
24515** would need to be subtracted from the date in order to bring the
24516** date back to the end of the month.
24517*/
24518static void computeFloor(DateTime *p){
24519  assert( p->validYMD || p->isError );
24520  assert( p->D>=0 && p->D<=31 );
24521  assert( p->M>=0 && p->M<=12 );
24522  if( p->D<=28 ){
24523    p->nFloor = 0;
24524  }else if( (1<<p->M) & 0x15aa ){
24525    p->nFloor = 0;
24526  }else if( p->M!=2 ){
24527    p->nFloor = (p->D==31);
24528  }else if( p->Y%4!=0 || (p->Y%100==0 && p->Y%400!=0) ){
24529    p->nFloor = p->D - 28;
24530  }else{
24531    p->nFloor = p->D - 29;
24532  }
24533}
24534
24535/*
24536** Parse dates of the form
24537**
24538**     YYYY-MM-DD HH:MM:SS.FFF
24539**     YYYY-MM-DD HH:MM:SS
24540**     YYYY-MM-DD HH:MM
24541**     YYYY-MM-DD
24542**
24543** Write the result into the DateTime structure and return 0
24544** on success and 1 if the input string is not a well-formed
24545** date.
24546*/
24547static int parseYyyyMmDd(const char *zDate, DateTime *p){
24548  int Y, M, D, neg;
24549
24550  if( zDate[0]=='-' ){
24551    zDate++;
24552    neg = 1;
24553  }else{
24554    neg = 0;
24555  }
24556  if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
24557    return 1;
24558  }
24559  zDate += 10;
24560  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
24561  if( parseHhMmSs(zDate, p)==0 ){
24562    /* We got the time */
24563  }else if( *zDate==0 ){
24564    p->validHMS = 0;
24565  }else{
24566    return 1;
24567  }
24568  p->validJD = 0;
24569  p->validYMD = 1;
24570  p->Y = neg ? -Y : Y;
24571  p->M = M;
24572  p->D = D;
24573  computeFloor(p);
24574  if( p->tz ){
24575    computeJD(p);
24576  }
24577  return 0;
24578}
24579
24580
24581static void clearYMD_HMS_TZ(DateTime *p);  /* Forward declaration */
24582
24583/*
24584** Set the time to the current time reported by the VFS.
24585**
24586** Return the number of errors.
24587*/
24588static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
24589  p->iJD = sqlite3StmtCurrentTime(context);
24590  if( p->iJD>0 ){
24591    p->validJD = 1;
24592    p->isUtc = 1;
24593    p->isLocal = 0;
24594    clearYMD_HMS_TZ(p);
24595    return 0;
24596  }else{
24597    return 1;
24598  }
24599}
24600
24601/*
24602** Input "r" is a numeric quantity which might be a julian day number,
24603** or the number of seconds since 1970.  If the value if r is within
24604** range of a julian day number, install it as such and set validJD.
24605** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
24606*/
24607static void setRawDateNumber(DateTime *p, double r){
24608  p->s = r;
24609  p->rawS = 1;
24610  if( r>=0.0 && r<5373484.5 ){
24611    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
24612    p->validJD = 1;
24613  }
24614}
24615
24616/*
24617** Attempt to parse the given string into a julian day number.  Return
24618** the number of errors.
24619**
24620** The following are acceptable forms for the input string:
24621**
24622**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
24623**      DDDD.DD
24624**      now
24625**
24626** In the first form, the +/-HH:MM is always optional.  The fractional
24627** seconds extension (the ".FFF") is optional.  The seconds portion
24628** (":SS.FFF") is option.  The year and date can be omitted as long
24629** as there is a time string.  The time string can be omitted as long
24630** as there is a year and date.
24631*/
24632static int parseDateOrTime(
24633  sqlite3_context *context,
24634  const char *zDate,
24635  DateTime *p
24636){
24637  double r;
24638  if( parseYyyyMmDd(zDate,p)==0 ){
24639    return 0;
24640  }else if( parseHhMmSs(zDate, p)==0 ){
24641    return 0;
24642  }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
24643    return setDateTimeToCurrent(context, p);
24644  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8)>0 ){
24645    setRawDateNumber(p, r);
24646    return 0;
24647  }else if( (sqlite3StrICmp(zDate,"subsec")==0
24648             || sqlite3StrICmp(zDate,"subsecond")==0)
24649           && sqlite3NotPureFunc(context) ){
24650    p->useSubsec = 1;
24651    return setDateTimeToCurrent(context, p);
24652  }
24653  return 1;
24654}
24655
24656/* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
24657** Multiplying this by 86400000 gives 464269060799999 as the maximum value
24658** for DateTime.iJD.
24659**
24660** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
24661** such a large integer literal, so we have to encode it.
24662*/
24663#define INT_464269060799999  ((((i64)0x1a640)<<32)|0x1072fdff)
24664
24665/*
24666** Return TRUE if the given julian day number is within range.
24667**
24668** The input is the JulianDay times 86400000.
24669*/
24670static int validJulianDay(sqlite3_int64 iJD){
24671  return iJD>=0 && iJD<=INT_464269060799999;
24672}
24673
24674/*
24675** Compute the Year, Month, and Day from the julian day number.
24676*/
24677static void computeYMD(DateTime *p){
24678  int Z, A, B, C, D, E, X1;
24679  if( p->validYMD ) return;
24680  if( !p->validJD ){
24681    p->Y = 2000;
24682    p->M = 1;
24683    p->D = 1;
24684  }else if( !validJulianDay(p->iJD) ){
24685    datetimeError(p);
24686    return;
24687  }else{
24688    Z = (int)((p->iJD + 43200000)/86400000);
24689    A = (int)((Z - 1867216.25)/36524.25);
24690    A = Z + 1 + A - (A/4);
24691    B = A + 1524;
24692    C = (int)((B - 122.1)/365.25);
24693    D = (36525*(C&32767))/100;
24694    E = (int)((B-D)/30.6001);
24695    X1 = (int)(30.6001*E);
24696    p->D = B - D - X1;
24697    p->M = E<14 ? E-1 : E-13;
24698    p->Y = p->M>2 ? C - 4716 : C - 4715;
24699  }
24700  p->validYMD = 1;
24701}
24702
24703/*
24704** Compute the Hour, Minute, and Seconds from the julian day number.
24705*/
24706static void computeHMS(DateTime *p){
24707  int day_ms, day_min; /* milliseconds, minutes into the day */
24708  if( p->validHMS ) return;
24709  computeJD(p);
24710  day_ms = (int)((p->iJD + 43200000) % 86400000);
24711  p->s = (day_ms % 60000)/1000.0;
24712  day_min = day_ms/60000;
24713  p->m = day_min % 60;
24714  p->h = day_min / 60;
24715  p->rawS = 0;
24716  p->validHMS = 1;
24717}
24718
24719/*
24720** Compute both YMD and HMS
24721*/
24722static void computeYMD_HMS(DateTime *p){
24723  computeYMD(p);
24724  computeHMS(p);
24725}
24726
24727/*
24728** Clear the YMD and HMS and the TZ
24729*/
24730static void clearYMD_HMS_TZ(DateTime *p){
24731  p->validYMD = 0;
24732  p->validHMS = 0;
24733  p->tz = 0;
24734}
24735
24736#ifndef SQLITE_OMIT_LOCALTIME
24737/*
24738** On recent Windows platforms, the localtime_s() function is available
24739** as part of the "Secure CRT". It is essentially equivalent to
24740** localtime_r() available under most POSIX platforms, except that the
24741** order of the parameters is reversed.
24742**
24743** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
24744**
24745** If the user has not indicated to use localtime_r() or localtime_s()
24746** already, check for an MSVC build environment that provides
24747** localtime_s().
24748*/
24749#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
24750    && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
24751#undef  HAVE_LOCALTIME_S
24752#define HAVE_LOCALTIME_S 1
24753#endif
24754
24755/*
24756** The following routine implements the rough equivalent of localtime_r()
24757** using whatever operating-system specific localtime facility that
24758** is available.  This routine returns 0 on success and
24759** non-zero on any kind of error.
24760**
24761** If the sqlite3GlobalConfig.bLocaltimeFault variable is non-zero then this
24762** routine will always fail.  If bLocaltimeFault is nonzero and
24763** sqlite3GlobalConfig.xAltLocaltime is not NULL, then xAltLocaltime() is
24764** invoked in place of the OS-defined localtime() function.
24765**
24766** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
24767** library function localtime_r() is used to assist in the calculation of
24768** local time.
24769*/
24770static int osLocaltime(time_t *t, struct tm *pTm){
24771  int rc;
24772#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
24773  struct tm *pX;
24774#if SQLITE_THREADSAFE>0
24775  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
24776#endif
24777  sqlite3_mutex_enter(mutex);
24778  pX = localtime(t);
24779#ifndef SQLITE_UNTESTABLE
24780  if( sqlite3GlobalConfig.bLocaltimeFault ){
24781    if( sqlite3GlobalConfig.xAltLocaltime!=0
24782     && 0==sqlite3GlobalConfig.xAltLocaltime((const void*)t,(void*)pTm)
24783    ){
24784      pX = pTm;
24785    }else{
24786      pX = 0;
24787    }
24788  }
24789#endif
24790  if( pX ) *pTm = *pX;
24791#if SQLITE_THREADSAFE>0
24792  sqlite3_mutex_leave(mutex);
24793#endif
24794  rc = pX==0;
24795#else
24796#ifndef SQLITE_UNTESTABLE
24797  if( sqlite3GlobalConfig.bLocaltimeFault ){
24798    if( sqlite3GlobalConfig.xAltLocaltime!=0 ){
24799      return sqlite3GlobalConfig.xAltLocaltime((const void*)t,(void*)pTm);
24800    }else{
24801      return 1;
24802    }
24803  }
24804#endif
24805#if HAVE_LOCALTIME_R
24806  rc = localtime_r(t, pTm)==0;
24807#else
24808  rc = localtime_s(pTm, t);
24809#endif /* HAVE_LOCALTIME_R */
24810#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
24811  return rc;
24812}
24813#endif /* SQLITE_OMIT_LOCALTIME */
24814
24815
24816#ifndef SQLITE_OMIT_LOCALTIME
24817/*
24818** Assuming the input DateTime is UTC, move it to its localtime equivalent.
24819*/
24820static int toLocaltime(
24821  DateTime *p,                   /* Date at which to calculate offset */
24822  sqlite3_context *pCtx          /* Write error here if one occurs */
24823){
24824  time_t t;
24825  struct tm sLocal;
24826  int iYearDiff;
24827
24828  /* Initialize the contents of sLocal to avoid a compiler warning. */
24829  memset(&sLocal, 0, sizeof(sLocal));
24830
24831  computeJD(p);
24832  if( p->iJD<2108667600*(i64)100000 /* 1970-01-01 */
24833   || p->iJD>2130141456*(i64)100000 /* 2038-01-18 */
24834  ){
24835    /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
24836    ** works for years between 1970 and 2037. For dates outside this range,
24837    ** SQLite attempts to map the year into an equivalent year within this
24838    ** range, do the calculation, then map the year back.
24839    */
24840    DateTime x = *p;
24841    computeYMD_HMS(&x);
24842    iYearDiff = (2000 + x.Y%4) - x.Y;
24843    x.Y += iYearDiff;
24844    x.validJD = 0;
24845    computeJD(&x);
24846    t = (time_t)(x.iJD/1000 -  21086676*(i64)10000);
24847  }else{
24848    iYearDiff = 0;
24849    t = (time_t)(p->iJD/1000 -  21086676*(i64)10000);
24850  }
24851  if( osLocaltime(&t, &sLocal) ){
24852    sqlite3_result_error(pCtx, "local time unavailable", -1);
24853    return SQLITE_ERROR;
24854  }
24855  p->Y = sLocal.tm_year + 1900 - iYearDiff;
24856  p->M = sLocal.tm_mon + 1;
24857  p->D = sLocal.tm_mday;
24858  p->h = sLocal.tm_hour;
24859  p->m = sLocal.tm_min;
24860  p->s = sLocal.tm_sec + (p->iJD%1000)*0.001;
24861  p->validYMD = 1;
24862  p->validHMS = 1;
24863  p->validJD = 0;
24864  p->rawS = 0;
24865  p->tz = 0;
24866  p->isError = 0;
24867  return SQLITE_OK;
24868}
24869#endif /* SQLITE_OMIT_LOCALTIME */
24870
24871/*
24872** The following table defines various date transformations of the form
24873**
24874**            'NNN days'
24875**
24876** Where NNN is an arbitrary floating-point number and "days" can be one
24877** of several units of time.
24878*/
24879static const struct {
24880  u8 nName;           /* Length of the name */
24881  char zName[7];      /* Name of the transformation */
24882  float rLimit;       /* Maximum NNN value for this transform */
24883  float rXform;       /* Constant used for this transform */
24884} aXformType[] = {
24885  /* 0 */ { 6, "second",   4.6427e+14,         1.0  },
24886  /* 1 */ { 6, "minute",   7.7379e+12,        60.0  },
24887  /* 2 */ { 4, "hour",     1.2897e+11,      3600.0  },
24888  /* 3 */ { 3, "day",      5373485.0,      86400.0  },
24889  /* 4 */ { 5, "month",    176546.0,  30.0*86400.0  },
24890  /* 5 */ { 4, "year",     14713.0,  365.0*86400.0  },
24891};
24892
24893/*
24894** If the DateTime p is raw number, try to figure out if it is
24895** a julian day number of a unix timestamp.  Set the p value
24896** appropriately.
24897*/
24898static void autoAdjustDate(DateTime *p){
24899  if( !p->rawS || p->validJD ){
24900    p->rawS = 0;
24901  }else if( p->s>=-21086676*(i64)10000        /* -4713-11-24 12:00:00 */
24902         && p->s<=(25340230*(i64)10000)+799   /*  9999-12-31 23:59:59 */
24903  ){
24904    double r = p->s*1000.0 + 210866760000000.0;
24905    clearYMD_HMS_TZ(p);
24906    p->iJD = (sqlite3_int64)(r + 0.5);
24907    p->validJD = 1;
24908    p->rawS = 0;
24909  }
24910}
24911
24912/*
24913** Process a modifier to a date-time stamp.  The modifiers are
24914** as follows:
24915**
24916**     NNN days
24917**     NNN hours
24918**     NNN minutes
24919**     NNN.NNNN seconds
24920**     NNN months
24921**     NNN years
24922**     +/-YYYY-MM-DD HH:MM:SS.SSS
24923**     ceiling
24924**     floor
24925**     start of month
24926**     start of year
24927**     start of week
24928**     start of day
24929**     weekday N
24930**     unixepoch
24931**     auto
24932**     localtime
24933**     utc
24934**     subsec
24935**     subsecond
24936**
24937** Return 0 on success and 1 if there is any kind of error. If the error
24938** is in a system call (i.e. localtime()), then an error message is written
24939** to context pCtx. If the error is an unrecognized modifier, no error is
24940** written to pCtx.
24941*/
24942static int parseModifier(
24943  sqlite3_context *pCtx,      /* Function context */
24944  const char *z,              /* The text of the modifier */
24945  int n,                      /* Length of zMod in bytes */
24946  DateTime *p,                /* The date/time value to be modified */
24947  int idx                     /* Parameter index of the modifier */
24948){
24949  int rc = 1;
24950  double r;
24951  switch(sqlite3UpperToLower[(u8)z[0]] ){
24952    case 'a': {
24953      /*
24954      **    auto
24955      **
24956      ** If rawS is available, then interpret as a julian day number, or
24957      ** a unix timestamp, depending on its magnitude.
24958      */
24959      if( sqlite3_stricmp(z, "auto")==0 ){
24960        if( idx>1 ) return 1; /* IMP: R-33611-57934 */
24961        autoAdjustDate(p);
24962        rc = 0;
24963      }
24964      break;
24965    }
24966    case 'c': {
24967      /*
24968      **    ceiling
24969      **
24970      ** Resolve day-of-month overflow by rolling forward into the next
24971      ** month.  As this is the default action, this modifier is really
24972      ** a no-op that is only included for symmetry.  See "floor".
24973      */
24974      if( sqlite3_stricmp(z, "ceiling")==0 ){
24975        computeJD(p);
24976        clearYMD_HMS_TZ(p);
24977        rc = 0;
24978        p->nFloor = 0;
24979      }
24980      break;
24981    }
24982    case 'f': {
24983      /*
24984      **    floor
24985      **
24986      ** Resolve day-of-month overflow by rolling back to the end of the
24987      ** previous month.
24988      */
24989      if( sqlite3_stricmp(z, "floor")==0 ){
24990        computeJD(p);
24991        p->iJD -= p->nFloor*86400000;
24992        clearYMD_HMS_TZ(p);
24993        rc = 0;
24994      }
24995      break;
24996    }
24997    case 'j': {
24998      /*
24999      **    julianday
25000      **
25001      ** Always interpret the prior number as a julian-day value.  If this
25002      ** is not the first modifier, or if the prior argument is not a numeric
25003      ** value in the allowed range of julian day numbers understood by
25004      ** SQLite (0..5373484.5) then the result will be NULL.
25005      */
25006      if( sqlite3_stricmp(z, "julianday")==0 ){
25007        if( idx>1 ) return 1;  /* IMP: R-31176-64601 */
25008        if( p->validJD && p->rawS ){
25009          rc = 0;
25010          p->rawS = 0;
25011        }
25012      }
25013      break;
25014    }
25015#ifndef SQLITE_OMIT_LOCALTIME
25016    case 'l': {
25017      /*    localtime
25018      **
25019      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
25020      ** show local time.
25021      */
25022      if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
25023        rc = p->isLocal ? SQLITE_OK : toLocaltime(p, pCtx);
25024        p->isUtc = 0;
25025        p->isLocal = 1;
25026      }
25027      break;
25028    }
25029#endif
25030    case 'u': {
25031      /*
25032      **    unixepoch
25033      **
25034      ** Treat the current value of p->s as the number of
25035      ** seconds since 1970.  Convert to a real julian day number.
25036      */
25037      if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
25038        if( idx>1 ) return 1;  /* IMP: R-49255-55373 */
25039        r = p->s*1000.0 + 210866760000000.0;
25040        if( r>=0.0 && r<464269060800000.0 ){
25041          clearYMD_HMS_TZ(p);
25042          p->iJD = (sqlite3_int64)(r + 0.5);
25043          p->validJD = 1;
25044          p->rawS = 0;
25045          rc = 0;
25046        }
25047      }
25048#ifndef SQLITE_OMIT_LOCALTIME
25049      else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
25050        if( p->isUtc==0 ){
25051          i64 iOrigJD;              /* Original localtime */
25052          i64 iGuess;               /* Guess at the corresponding utc time */
25053          int cnt = 0;              /* Safety to prevent infinite loop */
25054          i64 iErr;                 /* Guess is off by this much */
25055
25056          computeJD(p);
25057          iGuess = iOrigJD = p->iJD;
25058          iErr = 0;
25059          do{
25060            DateTime new;
25061            memset(&new, 0, sizeof(new));
25062            iGuess -= iErr;
25063            new.iJD = iGuess;
25064            new.validJD = 1;
25065            rc = toLocaltime(&new, pCtx);
25066            if( rc ) return rc;
25067            computeJD(&new);
25068            iErr = new.iJD - iOrigJD;
25069          }while( iErr && cnt++<3 );
25070          memset(p, 0, sizeof(*p));
25071          p->iJD = iGuess;
25072          p->validJD = 1;
25073          p->isUtc = 1;
25074          p->isLocal = 0;
25075        }
25076        rc = SQLITE_OK;
25077      }
25078#endif
25079      break;
25080    }
25081    case 'w': {
25082      /*
25083      **    weekday N
25084      **
25085      ** Move the date to the same time on the next occurrence of
25086      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
25087      ** date is already on the appropriate weekday, this is a no-op.
25088      */
25089      if( sqlite3_strnicmp(z, "weekday ", 8)==0
25090               && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)>0
25091               && r>=0.0 && r<7.0 && (n=(int)r)==r ){
25092        sqlite3_int64 Z;
25093        computeYMD_HMS(p);
25094        p->tz = 0;
25095        p->validJD = 0;
25096        computeJD(p);
25097        Z = ((p->iJD + 129600000)/86400000) % 7;
25098        if( Z>n ) Z -= 7;
25099        p->iJD += (n - Z)*86400000;
25100        clearYMD_HMS_TZ(p);
25101        rc = 0;
25102      }
25103      break;
25104    }
25105    case 's': {
25106      /*
25107      **    start of TTTTT
25108      **
25109      ** Move the date backwards to the beginning of the current day,
25110      ** or month or year.
25111      **
25112      **    subsecond
25113      **    subsec
25114      **
25115      ** Show subsecond precision in the output of datetime() and
25116      ** unixepoch() and strftime('%s').
25117      */
25118      if( sqlite3_strnicmp(z, "start of ", 9)!=0 ){
25119        if( sqlite3_stricmp(z, "subsec")==0
25120         || sqlite3_stricmp(z, "subsecond")==0
25121        ){
25122          p->useSubsec = 1;
25123          rc = 0;
25124        }
25125        break;
25126      }
25127      if( !p->validJD && !p->validYMD && !p->validHMS ) break;
25128      z += 9;
25129      computeYMD(p);
25130      p->validHMS = 1;
25131      p->h = p->m = 0;
25132      p->s = 0.0;
25133      p->rawS = 0;
25134      p->tz = 0;
25135      p->validJD = 0;
25136      if( sqlite3_stricmp(z,"month")==0 ){
25137        p->D = 1;
25138        rc = 0;
25139      }else if( sqlite3_stricmp(z,"year")==0 ){
25140        p->M = 1;
25141        p->D = 1;
25142        rc = 0;
25143      }else if( sqlite3_stricmp(z,"day")==0 ){
25144        rc = 0;
25145      }
25146      break;
25147    }
25148    case '+':
25149    case '-':
25150    case '0':
25151    case '1':
25152    case '2':
25153    case '3':
25154    case '4':
25155    case '5':
25156    case '6':
25157    case '7':
25158    case '8':
25159    case '9': {
25160      double rRounder;
25161      int i;
25162      int Y,M,D,h,m,x;
25163      const char *z2 = z;
25164      char z0 = z[0];
25165      for(n=1; z[n]; n++){
25166        if( z[n]==':' ) break;
25167        if( sqlite3Isspace(z[n]) ) break;
25168        if( z[n]=='-' ){
25169          if( n==5 && getDigits(&z[1], "40f", &Y)==1 ) break;
25170          if( n==6 && getDigits(&z[1], "50f", &Y)==1 ) break;
25171        }
25172      }
25173      if( sqlite3AtoF(z, &r, n, SQLITE_UTF8)<=0 ){
25174        assert( rc==1 );
25175        break;
25176      }
25177      if( z[n]=='-' ){
25178        /* A modifier of the form (+|-)YYYY-MM-DD adds or subtracts the
25179        ** specified number of years, months, and days.  MM is limited to
25180        ** the range 0-11 and DD is limited to 0-30.
25181        */
25182        if( z0!='+' && z0!='-' ) break;  /* Must start with +/- */
25183        if( n==5 ){
25184          if( getDigits(&z[1], "40f-20a-20d", &Y, &M, &D)!=3 ) break;
25185        }else{
25186          assert( n==6 );
25187          if( getDigits(&z[1], "50f-20a-20d", &Y, &M, &D)!=3 ) break;
25188          z++;
25189        }
25190        if( M>=12 ) break;                   /* M range 0..11 */
25191        if( D>=31 ) break;                   /* D range 0..30 */
25192        computeYMD_HMS(p);
25193        p->validJD = 0;
25194        if( z0=='-' ){
25195          p->Y -= Y;
25196          p->M -= M;
25197          D = -D;
25198        }else{
25199          p->Y += Y;
25200          p->M += M;
25201        }
25202        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
25203        p->Y += x;
25204        p->M -= x*12;
25205        computeFloor(p);
25206        computeJD(p);
25207        p->validHMS = 0;
25208        p->validYMD = 0;
25209        p->iJD += (i64)D*86400000;
25210        if( z[11]==0 ){
25211          rc = 0;
25212          break;
25213        }
25214        if( sqlite3Isspace(z[11])
25215         && getDigits(&z[12], "20c:20e", &h, &m)==2
25216        ){
25217          z2 = &z[12];
25218          n = 2;
25219        }else{
25220          break;
25221        }
25222      }
25223      if( z2[n]==':' ){
25224        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
25225        ** specified number of hours, minutes, seconds, and fractional seconds
25226        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
25227        ** omitted.
25228        */
25229
25230        DateTime tx;
25231        sqlite3_int64 day;
25232        if( !sqlite3Isdigit(*z2) ) z2++;
25233        memset(&tx, 0, sizeof(tx));
25234        if( parseHhMmSs(z2, &tx) ) break;
25235        computeJD(&tx);
25236        tx.iJD -= 43200000;
25237        day = tx.iJD/86400000;
25238        tx.iJD -= day*86400000;
25239        if( z0=='-' ) tx.iJD = -tx.iJD;
25240        computeJD(p);
25241        clearYMD_HMS_TZ(p);
25242        p->iJD += tx.iJD;
25243        rc = 0;
25244        break;
25245      }
25246
25247      /* If control reaches this point, it means the transformation is
25248      ** one of the forms like "+NNN days".  */
25249      z += n;
25250      while( sqlite3Isspace(*z) ) z++;
25251      n = sqlite3Strlen30(z);
25252      if( n<3 || n>10 ) break;
25253      if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
25254      computeJD(p);
25255      assert( rc==1 );
25256      rRounder = r<0 ? -0.5 : +0.5;
25257      p->nFloor = 0;
25258      for(i=0; i<ArraySize(aXformType); i++){
25259        if( aXformType[i].nName==n
25260         && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
25261         && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
25262        ){
25263          switch( i ){
25264            case 4: { /* Special processing to add months */
25265              assert( strcmp(aXformType[4].zName,"month")==0 );
25266              computeYMD_HMS(p);
25267              p->M += (int)r;
25268              x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
25269              p->Y += x;
25270              p->M -= x*12;
25271              computeFloor(p);
25272              p->validJD = 0;
25273              r -= (int)r;
25274              break;
25275            }
25276            case 5: { /* Special processing to add years */
25277              int y = (int)r;
25278              assert( strcmp(aXformType[5].zName,"year")==0 );
25279              computeYMD_HMS(p);
25280              assert( p->M>=0 && p->M<=12 );
25281              p->Y += y;
25282              computeFloor(p);
25283              p->validJD = 0;
25284              r -= (int)r;
25285              break;
25286            }
25287          }
25288          computeJD(p);
25289          p->iJD += (sqlite3_int64)(r*1000.0*aXformType[i].rXform + rRounder);
25290          rc = 0;
25291          break;
25292        }
25293      }
25294      clearYMD_HMS_TZ(p);
25295      break;
25296    }
25297    default: {
25298      break;
25299    }
25300  }
25301  return rc;
25302}
25303
25304/*
25305** Process time function arguments.  argv[0] is a date-time stamp.
25306** argv[1] and following are modifiers.  Parse them all and write
25307** the resulting time into the DateTime structure p.  Return 0
25308** on success and 1 if there are any errors.
25309**
25310** If there are zero parameters (if even argv[0] is undefined)
25311** then assume a default value of "now" for argv[0].
25312*/
25313static int isDate(
25314  sqlite3_context *context,
25315  int argc,
25316  sqlite3_value **argv,
25317  DateTime *p
25318){
25319  int i, n;
25320  const unsigned char *z;
25321  int eType;
25322  memset(p, 0, sizeof(*p));
25323  if( argc==0 ){
25324    if( !sqlite3NotPureFunc(context) ) return 1;
25325    return setDateTimeToCurrent(context, p);
25326  }
25327  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
25328                   || eType==SQLITE_INTEGER ){
25329    setRawDateNumber(p, sqlite3_value_double(argv[0]));
25330  }else{
25331    z = sqlite3_value_text(argv[0]);
25332    if( !z || parseDateOrTime(context, (char*)z, p) ){
25333      return 1;
25334    }
25335  }
25336  for(i=1; i<argc; i++){
25337    z = sqlite3_value_text(argv[i]);
25338    n = sqlite3_value_bytes(argv[i]);
25339    if( z==0 || parseModifier(context, (char*)z, n, p, i) ) return 1;
25340  }
25341  computeJD(p);
25342  if( p->isError || !validJulianDay(p->iJD) ) return 1;
25343  if( argc==1 && p->validYMD && p->D>28 ){
25344    /* Make sure a YYYY-MM-DD is normalized.
25345    ** Example: 2023-02-31 -> 2023-03-03 */
25346    assert( p->validJD );
25347    p->validYMD = 0;
25348  }
25349  return 0;
25350}
25351
25352
25353/*
25354** The following routines implement the various date and time functions
25355** of SQLite.
25356*/
25357
25358/*
25359**    julianday( TIMESTRING, MOD, MOD, ...)
25360**
25361** Return the julian day number of the date specified in the arguments
25362*/
25363static void juliandayFunc(
25364  sqlite3_context *context,
25365  int argc,
25366  sqlite3_value **argv
25367){
25368  DateTime x;
25369  if( isDate(context, argc, argv, &x)==0 ){
25370    computeJD(&x);
25371    sqlite3_result_double(context, x.iJD/86400000.0);
25372  }
25373}
25374
25375/*
25376**    unixepoch( TIMESTRING, MOD, MOD, ...)
25377**
25378** Return the number of seconds (including fractional seconds) since
25379** the unix epoch of 1970-01-01 00:00:00 GMT.
25380*/
25381static void unixepochFunc(
25382  sqlite3_context *context,
25383  int argc,
25384  sqlite3_value **argv
25385){
25386  DateTime x;
25387  if( isDate(context, argc, argv, &x)==0 ){
25388    computeJD(&x);
25389    if( x.useSubsec ){
25390      sqlite3_result_double(context, (x.iJD - 21086676*(i64)10000000)/1000.0);
25391    }else{
25392      sqlite3_result_int64(context, x.iJD/1000 - 21086676*(i64)10000);
25393    }
25394  }
25395}
25396
25397/*
25398**    datetime( TIMESTRING, MOD, MOD, ...)
25399**
25400** Return YYYY-MM-DD HH:MM:SS
25401*/
25402static void datetimeFunc(
25403  sqlite3_context *context,
25404  int argc,
25405  sqlite3_value **argv
25406){
25407  DateTime x;
25408  if( isDate(context, argc, argv, &x)==0 ){
25409    int Y, s, n;
25410    char zBuf[32];
25411    computeYMD_HMS(&x);
25412    Y = x.Y;
25413    if( Y<0 ) Y = -Y;
25414    zBuf[1] = '0' + (Y/1000)%10;
25415    zBuf[2] = '0' + (Y/100)%10;
25416    zBuf[3] = '0' + (Y/10)%10;
25417    zBuf[4] = '0' + (Y)%10;
25418    zBuf[5] = '-';
25419    zBuf[6] = '0' + (x.M/10)%10;
25420    zBuf[7] = '0' + (x.M)%10;
25421    zBuf[8] = '-';
25422    zBuf[9] = '0' + (x.D/10)%10;
25423    zBuf[10] = '0' + (x.D)%10;
25424    zBuf[11] = ' ';
25425    zBuf[12] = '0' + (x.h/10)%10;
25426    zBuf[13] = '0' + (x.h)%10;
25427    zBuf[14] = ':';
25428    zBuf[15] = '0' + (x.m/10)%10;
25429    zBuf[16] = '0' + (x.m)%10;
25430    zBuf[17] = ':';
25431    if( x.useSubsec ){
25432      s = (int)(1000.0*x.s + 0.5);
25433      zBuf[18] = '0' + (s/10000)%10;
25434      zBuf[19] = '0' + (s/1000)%10;
25435      zBuf[20] = '.';
25436      zBuf[21] = '0' + (s/100)%10;
25437      zBuf[22] = '0' + (s/10)%10;
25438      zBuf[23] = '0' + (s)%10;
25439      zBuf[24] = 0;
25440      n = 24;
25441    }else{
25442      s = (int)x.s;
25443      zBuf[18] = '0' + (s/10)%10;
25444      zBuf[19] = '0' + (s)%10;
25445      zBuf[20] = 0;
25446      n = 20;
25447    }
25448    if( x.Y<0 ){
25449      zBuf[0] = '-';
25450      sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT);
25451    }else{
25452      sqlite3_result_text(context, &zBuf[1], n-1, SQLITE_TRANSIENT);
25453    }
25454  }
25455}
25456
25457/*
25458**    time( TIMESTRING, MOD, MOD, ...)
25459**
25460** Return HH:MM:SS
25461*/
25462static void timeFunc(
25463  sqlite3_context *context,
25464  int argc,
25465  sqlite3_value **argv
25466){
25467  DateTime x;
25468  if( isDate(context, argc, argv, &x)==0 ){
25469    int s, n;
25470    char zBuf[16];
25471    computeHMS(&x);
25472    zBuf[0] = '0' + (x.h/10)%10;
25473    zBuf[1] = '0' + (x.h)%10;
25474    zBuf[2] = ':';
25475    zBuf[3] = '0' + (x.m/10)%10;
25476    zBuf[4] = '0' + (x.m)%10;
25477    zBuf[5] = ':';
25478    if( x.useSubsec ){
25479      s = (int)(1000.0*x.s + 0.5);
25480      zBuf[6] = '0' + (s/10000)%10;
25481      zBuf[7] = '0' + (s/1000)%10;
25482      zBuf[8] = '.';
25483      zBuf[9] = '0' + (s/100)%10;
25484      zBuf[10] = '0' + (s/10)%10;
25485      zBuf[11] = '0' + (s)%10;
25486      zBuf[12] = 0;
25487      n = 12;
25488    }else{
25489      s = (int)x.s;
25490      zBuf[6] = '0' + (s/10)%10;
25491      zBuf[7] = '0' + (s)%10;
25492      zBuf[8] = 0;
25493      n = 8;
25494    }
25495    sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT);
25496  }
25497}
25498
25499/*
25500**    date( TIMESTRING, MOD, MOD, ...)
25501**
25502** Return YYYY-MM-DD
25503*/
25504static void dateFunc(
25505  sqlite3_context *context,
25506  int argc,
25507  sqlite3_value **argv
25508){
25509  DateTime x;
25510  if( isDate(context, argc, argv, &x)==0 ){
25511    int Y;
25512    char zBuf[16];
25513    computeYMD(&x);
25514    Y = x.Y;
25515    if( Y<0 ) Y = -Y;
25516    zBuf[1] = '0' + (Y/1000)%10;
25517    zBuf[2] = '0' + (Y/100)%10;
25518    zBuf[3] = '0' + (Y/10)%10;
25519    zBuf[4] = '0' + (Y)%10;
25520    zBuf[5] = '-';
25521    zBuf[6] = '0' + (x.M/10)%10;
25522    zBuf[7] = '0' + (x.M)%10;
25523    zBuf[8] = '-';
25524    zBuf[9] = '0' + (x.D/10)%10;
25525    zBuf[10] = '0' + (x.D)%10;
25526    zBuf[11] = 0;
25527    if( x.Y<0 ){
25528      zBuf[0] = '-';
25529      sqlite3_result_text(context, zBuf, 11, SQLITE_TRANSIENT);
25530    }else{
25531      sqlite3_result_text(context, &zBuf[1], 10, SQLITE_TRANSIENT);
25532    }
25533  }
25534}
25535
25536/*
25537** Compute the number of days after the most recent January 1.
25538**
25539** In other words, compute the zero-based day number for the
25540** current year:
25541**
25542**   Jan01 = 0,  Jan02 = 1, ..., Jan31 = 30, Feb01 = 31, ...
25543**   Dec31 = 364 or 365.
25544*/
25545static int daysAfterJan01(DateTime *pDate){
25546  DateTime jan01 = *pDate;
25547  assert( jan01.validYMD );
25548  assert( jan01.validHMS );
25549  assert( pDate->validJD );
25550  jan01.validJD = 0;
25551  jan01.M = 1;
25552  jan01.D = 1;
25553  computeJD(&jan01);
25554  return (int)((pDate->iJD-jan01.iJD+43200000)/86400000);
25555}
25556
25557/*
25558** Return the number of days after the most recent Monday.
25559**
25560** In other words, return the day of the week according
25561** to this code:
25562**
25563**   0=Monday, 1=Tuesday, 2=Wednesday, ..., 6=Sunday.
25564*/
25565static int daysAfterMonday(DateTime *pDate){
25566  assert( pDate->validJD );
25567  return (int)((pDate->iJD+43200000)/86400000) % 7;
25568}
25569
25570/*
25571** Return the number of days after the most recent Sunday.
25572**
25573** In other words, return the day of the week according
25574** to this code:
25575**
25576**   0=Sunday, 1=Monday, 2=Tues, ..., 6=Saturday
25577*/
25578static int daysAfterSunday(DateTime *pDate){
25579  assert( pDate->validJD );
25580  return (int)((pDate->iJD+129600000)/86400000) % 7;
25581}
25582
25583/*
25584**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
25585**
25586** Return a string described by FORMAT.  Conversions as follows:
25587**
25588**   %d  day of month  01-31
25589**   %e  day of month  1-31
25590**   %f  ** fractional seconds  SS.SSS
25591**   %F  ISO date.  YYYY-MM-DD
25592**   %G  ISO year corresponding to %V 0000-9999.
25593**   %g  2-digit ISO year corresponding to %V 00-99
25594**   %H  hour 00-24
25595**   %k  hour  0-24  (leading zero converted to space)
25596**   %I  hour 01-12
25597**   %j  day of year 001-366
25598**   %J  ** julian day number
25599**   %l  hour  1-12  (leading zero converted to space)
25600**   %m  month 01-12
25601**   %M  minute 00-59
25602**   %p  "am" or "pm"
25603**   %P  "AM" or "PM"
25604**   %R  time as HH:MM
25605**   %s  seconds since 1970-01-01
25606**   %S  seconds 00-59
25607**   %T  time as HH:MM:SS
25608**   %u  day of week 1-7  Monday==1, Sunday==7
25609**   %w  day of week 0-6  Sunday==0, Monday==1
25610**   %U  week of year 00-53  (First Sunday is start of week 01)
25611**   %V  week of year 01-53  (First week containing Thursday is week 01)
25612**   %W  week of year 00-53  (First Monday is start of week 01)
25613**   %Y  year 0000-9999
25614**   %%  %
25615*/
25616static void strftimeFunc(
25617  sqlite3_context *context,
25618  int argc,
25619  sqlite3_value **argv
25620){
25621  DateTime x;
25622  size_t i,j;
25623  sqlite3 *db;
25624  const char *zFmt;
25625  sqlite3_str sRes;
25626
25627
25628  if( argc==0 ) return;
25629  zFmt = (const char*)sqlite3_value_text(argv[0]);
25630  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
25631  db = sqlite3_context_db_handle(context);
25632  sqlite3StrAccumInit(&sRes, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
25633
25634  computeJD(&x);
25635  computeYMD_HMS(&x);
25636  for(i=j=0; zFmt[i]; i++){
25637    char cf;
25638    if( zFmt[i]!='%' ) continue;
25639    if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j));
25640    i++;
25641    j = i + 1;
25642    cf = zFmt[i];
25643    switch( cf ){
25644      case 'd':  /* Fall thru */
25645      case 'e': {
25646        sqlite3_str_appendf(&sRes, cf=='d' ? "%02d" : "%2d", x.D);
25647        break;
25648      }
25649      case 'f': {  /* Fractional seconds.  (Non-standard) */
25650        double s = x.s;
25651        if( s>59.999 ) s = 59.999;
25652        sqlite3_str_appendf(&sRes, "%06.3f", s);
25653        break;
25654      }
25655      case 'F': {
25656        sqlite3_str_appendf(&sRes, "%04d-%02d-%02d", x.Y, x.M, x.D);
25657        break;
25658      }
25659      case 'G': /* Fall thru */
25660      case 'g': {
25661        DateTime y = x;
25662        assert( y.validJD );
25663        /* Move y so that it is the Thursday in the same week as x */
25664        y.iJD += (3 - daysAfterMonday(&x))*86400000;
25665        y.validYMD = 0;
25666        computeYMD(&y);
25667        if( cf=='g' ){
25668          sqlite3_str_appendf(&sRes, "%02d", y.Y%100);
25669        }else{
25670          sqlite3_str_appendf(&sRes, "%04d", y.Y);
25671        }
25672        break;
25673      }
25674      case 'H':
25675      case 'k': {
25676        sqlite3_str_appendf(&sRes, cf=='H' ? "%02d" : "%2d", x.h);
25677        break;
25678      }
25679      case 'I': /* Fall thru */
25680      case 'l': {
25681        int h = x.h;
25682        if( h>12 ) h -= 12;
25683        if( h==0 ) h = 12;
25684        sqlite3_str_appendf(&sRes, cf=='I' ? "%02d" : "%2d", h);
25685        break;
25686      }
25687      case 'j': {  /* Day of year.  Jan01==1, Jan02==2, and so forth */
25688        sqlite3_str_appendf(&sRes,"%03d",daysAfterJan01(&x)+1);
25689        break;
25690      }
25691      case 'J': {  /* Julian day number.  (Non-standard) */
25692        sqlite3_str_appendf(&sRes,"%.16g",x.iJD/86400000.0);
25693        break;
25694      }
25695      case 'm': {
25696        sqlite3_str_appendf(&sRes,"%02d",x.M);
25697        break;
25698      }
25699      case 'M': {
25700        sqlite3_str_appendf(&sRes,"%02d",x.m);
25701        break;
25702      }
25703      case 'p': /* Fall thru */
25704      case 'P': {
25705        if( x.h>=12 ){
25706          sqlite3_str_append(&sRes, cf=='p' ? "PM" : "pm", 2);
25707        }else{
25708          sqlite3_str_append(&sRes, cf=='p' ? "AM" : "am", 2);
25709        }
25710        break;
25711      }
25712      case 'R': {
25713        sqlite3_str_appendf(&sRes, "%02d:%02d", x.h, x.m);
25714        break;
25715      }
25716      case 's': {
25717        if( x.useSubsec ){
25718          sqlite3_str_appendf(&sRes,"%.3f",
25719                (x.iJD - 21086676*(i64)10000000)/1000.0);
25720        }else{
25721          i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
25722          sqlite3_str_appendf(&sRes,"%lld",iS);
25723        }
25724        break;
25725      }
25726      case 'S': {
25727        sqlite3_str_appendf(&sRes,"%02d",(int)x.s);
25728        break;
25729      }
25730      case 'T': {
25731        sqlite3_str_appendf(&sRes,"%02d:%02d:%02d", x.h, x.m, (int)x.s);
25732        break;
25733      }
25734      case 'u':    /* Day of week.  1 to 7.  Monday==1, Sunday==7 */
25735      case 'w': {  /* Day of week.  0 to 6.  Sunday==0, Monday==1 */
25736        char c = (char)daysAfterSunday(&x) + '0';
25737        if( c=='0' && cf=='u' ) c = '7';
25738        sqlite3_str_appendchar(&sRes, 1, c);
25739        break;
25740      }
25741      case 'U': {  /* Week num. 00-53. First Sun of the year is week 01 */
25742        sqlite3_str_appendf(&sRes,"%02d",
25743              (daysAfterJan01(&x)-daysAfterSunday(&x)+7)/7);
25744        break;
25745      }
25746      case 'V': {  /* Week num. 01-53. First week with a Thur is week 01 */
25747        DateTime y = x;
25748        /* Adjust y so that is the Thursday in the same week as x */
25749        assert( y.validJD );
25750        y.iJD += (3 - daysAfterMonday(&x))*86400000;
25751        y.validYMD = 0;
25752        computeYMD(&y);
25753        sqlite3_str_appendf(&sRes,"%02d", daysAfterJan01(&y)/7+1);
25754        break;
25755      }
25756      case 'W': {  /* Week num. 00-53. First Mon of the year is week 01 */
25757        sqlite3_str_appendf(&sRes,"%02d",
25758           (daysAfterJan01(&x)-daysAfterMonday(&x)+7)/7);
25759        break;
25760      }
25761      case 'Y': {
25762        sqlite3_str_appendf(&sRes,"%04d",x.Y);
25763        break;
25764      }
25765      case '%': {
25766        sqlite3_str_appendchar(&sRes, 1, '%');
25767        break;
25768      }
25769      default: {
25770        sqlite3_str_reset(&sRes);
25771        return;
25772      }
25773    }
25774  }
25775  if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j));
25776  sqlite3ResultStrAccum(context, &sRes);
25777}
25778
25779/*
25780** current_time()
25781**
25782** This function returns the same value as time('now').
25783*/
25784static void ctimeFunc(
25785  sqlite3_context *context,
25786  int NotUsed,
25787  sqlite3_value **NotUsed2
25788){
25789  UNUSED_PARAMETER2(NotUsed, NotUsed2);
25790  timeFunc(context, 0, 0);
25791}
25792
25793/*
25794** current_date()
25795**
25796** This function returns the same value as date('now').
25797*/
25798static void cdateFunc(
25799  sqlite3_context *context,
25800  int NotUsed,
25801  sqlite3_value **NotUsed2
25802){
25803  UNUSED_PARAMETER2(NotUsed, NotUsed2);
25804  dateFunc(context, 0, 0);
25805}
25806
25807/*
25808** timediff(DATE1, DATE2)
25809**
25810** Return the amount of time that must be added to DATE2 in order to
25811** convert it into DATE2.  The time difference format is:
25812**
25813**     +YYYY-MM-DD HH:MM:SS.SSS
25814**
25815** The initial "+" becomes "-" if DATE1 occurs before DATE2.  For
25816** date/time values A and B, the following invariant should hold:
25817**
25818**     datetime(A) == (datetime(B, timediff(A,B))
25819**
25820** Both DATE arguments must be either a julian day number, or an
25821** ISO-8601 string.  The unix timestamps are not supported by this
25822** routine.
25823*/
25824static void timediffFunc(
25825  sqlite3_context *context,
25826  int NotUsed1,
25827  sqlite3_value **argv
25828){
25829  char sign;
25830  int Y, M;
25831  DateTime d1, d2;
25832  sqlite3_str sRes;
25833  UNUSED_PARAMETER(NotUsed1);
25834  if( isDate(context, 1, &argv[0], &d1) ) return;
25835  if( isDate(context, 1, &argv[1], &d2) ) return;
25836  computeYMD_HMS(&d1);
25837  computeYMD_HMS(&d2);
25838  if( d1.iJD>=d2.iJD ){
25839    sign = '+';
25840    Y = d1.Y - d2.Y;
25841    if( Y ){
25842      d2.Y = d1.Y;
25843      d2.validJD = 0;
25844      computeJD(&d2);
25845    }
25846    M = d1.M - d2.M;
25847    if( M<0 ){
25848      Y--;
25849      M += 12;
25850    }
25851    if( M!=0 ){
25852      d2.M = d1.M;
25853      d2.validJD = 0;
25854      computeJD(&d2);
25855    }
25856    while( d1.iJD<d2.iJD ){
25857      M--;
25858      if( M<0 ){
25859        M = 11;
25860        Y--;
25861      }
25862      d2.M--;
25863      if( d2.M<1 ){
25864        d2.M = 12;
25865        d2.Y--;
25866      }
25867      d2.validJD = 0;
25868      computeJD(&d2);
25869    }
25870    d1.iJD -= d2.iJD;
25871    d1.iJD += (u64)1486995408 * (u64)100000;
25872  }else /* d1<d2 */{
25873    sign = '-';
25874    Y = d2.Y - d1.Y;
25875    if( Y ){
25876      d2.Y = d1.Y;
25877      d2.validJD = 0;
25878      computeJD(&d2);
25879    }
25880    M = d2.M - d1.M;
25881    if( M<0 ){
25882      Y--;
25883      M += 12;
25884    }
25885    if( M!=0 ){
25886      d2.M = d1.M;
25887      d2.validJD = 0;
25888      computeJD(&d2);
25889    }
25890    while( d1.iJD>d2.iJD ){
25891      M--;
25892      if( M<0 ){
25893        M = 11;
25894        Y--;
25895      }
25896      d2.M++;
25897      if( d2.M>12 ){
25898        d2.M = 1;
25899        d2.Y++;
25900      }
25901      d2.validJD = 0;
25902      computeJD(&d2);
25903    }
25904    d1.iJD = d2.iJD - d1.iJD;
25905    d1.iJD += (u64)1486995408 * (u64)100000;
25906  }
25907  clearYMD_HMS_TZ(&d1);
25908  computeYMD_HMS(&d1);
25909  sqlite3StrAccumInit(&sRes, 0, 0, 0, 100);
25910  sqlite3_str_appendf(&sRes, "%c%04d-%02d-%02d %02d:%02d:%06.3f",
25911       sign, Y, M, d1.D-1, d1.h, d1.m, d1.s);
25912  sqlite3ResultStrAccum(context, &sRes);
25913}
25914
25915
25916/*
25917** current_timestamp()
25918**
25919** This function returns the same value as datetime('now').
25920*/
25921static void ctimestampFunc(
25922  sqlite3_context *context,
25923  int NotUsed,
25924  sqlite3_value **NotUsed2
25925){
25926  UNUSED_PARAMETER2(NotUsed, NotUsed2);
25927  datetimeFunc(context, 0, 0);
25928}
25929#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
25930
25931#ifdef SQLITE_OMIT_DATETIME_FUNCS
25932/*
25933** If the library is compiled to omit the full-scale date and time
25934** handling (to get a smaller binary), the following minimal version
25935** of the functions current_time(), current_date() and current_timestamp()
25936** are included instead. This is to support column declarations that
25937** include "DEFAULT CURRENT_TIME" etc.
25938**
25939** This function uses the C-library functions time(), gmtime()
25940** and strftime(). The format string to pass to strftime() is supplied
25941** as the user-data for the function.
25942*/
25943static void currentTimeFunc(
25944  sqlite3_context *context,
25945  int argc,
25946  sqlite3_value **argv
25947){
25948  time_t t;
25949  char *zFormat = (char *)sqlite3_user_data(context);
25950  sqlite3_int64 iT;
25951  struct tm *pTm;
25952  struct tm sNow;
25953  char zBuf[20];
25954
25955  UNUSED_PARAMETER(argc);
25956  UNUSED_PARAMETER(argv);
25957
25958  iT = sqlite3StmtCurrentTime(context);
25959  if( iT<=0 ) return;
25960  t = iT/1000 - 10000*(sqlite3_int64)21086676;
25961#if HAVE_GMTIME_R
25962  pTm = gmtime_r(&t, &sNow);
25963#else
25964  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
25965  pTm = gmtime(&t);
25966  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
25967  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
25968#endif
25969  if( pTm ){
25970    strftime(zBuf, 20, zFormat, &sNow);
25971    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
25972  }
25973}
25974#endif
25975
25976#if !defined(SQLITE_OMIT_DATETIME_FUNCS) && defined(SQLITE_DEBUG)
25977/*
25978**   datedebug(...)
25979**
25980** This routine returns JSON that describes the internal DateTime object.
25981** Used for debugging and testing only.  Subject to change.
25982*/
25983static void datedebugFunc(
25984  sqlite3_context *context,
25985  int argc,
25986  sqlite3_value **argv
25987){
25988  DateTime x;
25989  if( isDate(context, argc, argv, &x)==0 ){
25990    char *zJson;
25991    zJson = sqlite3_mprintf(
25992      "{iJD:%lld,Y:%d,M:%d,D:%d,h:%d,m:%d,tz:%d,"
25993      "s:%.3f,validJD:%d,validYMS:%d,validHMS:%d,"
25994      "nFloor:%d,rawS:%d,isError:%d,useSubsec:%d,"
25995      "isUtc:%d,isLocal:%d}",
25996      x.iJD, x.Y, x.M, x.D, x.h, x.m, x.tz,
25997      x.s, x.validJD, x.validYMD, x.validHMS,
25998      x.nFloor, x.rawS, x.isError, x.useSubsec,
25999      x.isUtc, x.isLocal);
26000    sqlite3_result_text(context, zJson, -1, sqlite3_free);
26001  }
26002}
26003#endif /* !SQLITE_OMIT_DATETIME_FUNCS && SQLITE_DEBUG */
26004
26005
26006/*
26007** This function registered all of the above C functions as SQL
26008** functions.  This should be the only routine in this file with
26009** external linkage.
26010*/
26011SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
26012  static FuncDef aDateTimeFuncs[] = {
26013#ifndef SQLITE_OMIT_DATETIME_FUNCS
26014    PURE_DATE(julianday,        -1, 0, 0, juliandayFunc ),
26015    PURE_DATE(unixepoch,        -1, 0, 0, unixepochFunc ),
26016    PURE_DATE(date,             -1, 0, 0, dateFunc      ),
26017    PURE_DATE(time,             -1, 0, 0, timeFunc      ),
26018    PURE_DATE(datetime,         -1, 0, 0, datetimeFunc  ),
26019    PURE_DATE(strftime,         -1, 0, 0, strftimeFunc  ),
26020    PURE_DATE(timediff,          2, 0, 0, timediffFunc  ),
26021#ifdef SQLITE_DEBUG
26022    PURE_DATE(datedebug,        -1, 0, 0, datedebugFunc ),
26023#endif
26024    DFUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
26025    DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
26026    DFUNCTION(current_date,      0, 0, 0, cdateFunc     ),
26027#else
26028    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
26029    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
26030    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
26031#endif
26032  };
26033  sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
26034}
26035
26036/************** End of date.c ************************************************/
26037/************** Begin file os.c **********************************************/
26038/*
26039** 2005 November 29
26040**
26041** The author disclaims copyright to this source code.  In place of
26042** a legal notice, here is a blessing:
26043**
26044**    May you do good and not evil.
26045**    May you find forgiveness for yourself and forgive others.
26046**    May you share freely, never taking more than you give.
26047**
26048******************************************************************************
26049**
26050** This file contains OS interface code that is common to all
26051** architectures.
26052*/
26053/* #include "sqliteInt.h" */
26054
26055/*
26056** If we compile with the SQLITE_TEST macro set, then the following block
26057** of code will give us the ability to simulate a disk I/O error.  This
26058** is used for testing the I/O recovery logic.
26059*/
26060#if defined(SQLITE_TEST)
26061SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
26062SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
26063SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
26064SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
26065SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
26066SQLITE_API int sqlite3_diskfull_pending = 0;
26067SQLITE_API int sqlite3_diskfull = 0;
26068#endif /* defined(SQLITE_TEST) */
26069
26070/*
26071** When testing, also keep a count of the number of open files.
26072*/
26073#if defined(SQLITE_TEST)
26074SQLITE_API int sqlite3_open_file_count = 0;
26075#endif /* defined(SQLITE_TEST) */
26076
26077/*
26078** The default SQLite sqlite3_vfs implementations do not allocate
26079** memory (actually, os_unix.c allocates a small amount of memory
26080** from within OsOpen()), but some third-party implementations may.
26081** So we test the effects of a malloc() failing and the sqlite3OsXXX()
26082** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
26083**
26084** The following functions are instrumented for malloc() failure
26085** testing:
26086**
26087**     sqlite3OsRead()
26088**     sqlite3OsWrite()
26089**     sqlite3OsSync()
26090**     sqlite3OsFileSize()
26091**     sqlite3OsLock()
26092**     sqlite3OsCheckReservedLock()
26093**     sqlite3OsFileControl()
26094**     sqlite3OsShmMap()
26095**     sqlite3OsOpen()
26096**     sqlite3OsDelete()
26097**     sqlite3OsAccess()
26098**     sqlite3OsFullPathname()
26099**
26100*/
26101#if defined(SQLITE_TEST)
26102SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
26103  #define DO_OS_MALLOC_TEST(x)                                       \
26104  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
26105    void *pTstAlloc = sqlite3Malloc(10);                             \
26106    if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT;                  \
26107    sqlite3_free(pTstAlloc);                                         \
26108  }
26109#else
26110  #define DO_OS_MALLOC_TEST(x)
26111#endif
26112
26113/*
26114** The following routines are convenience wrappers around methods
26115** of the sqlite3_file object.  This is mostly just syntactic sugar. All
26116** of this would be completely automatic if SQLite were coded using
26117** C++ instead of plain old C.
26118*/
26119SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
26120  if( pId->pMethods ){
26121    pId->pMethods->xClose(pId);
26122    pId->pMethods = 0;
26123  }
26124}
26125SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
26126  DO_OS_MALLOC_TEST(id);
26127  return id->pMethods->xRead(id, pBuf, amt, offset);
26128}
26129SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
26130  DO_OS_MALLOC_TEST(id);
26131  return id->pMethods->xWrite(id, pBuf, amt, offset);
26132}
26133SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
26134  return id->pMethods->xTruncate(id, size);
26135}
26136SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
26137  DO_OS_MALLOC_TEST(id);
26138  return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
26139}
26140SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
26141  DO_OS_MALLOC_TEST(id);
26142  return id->pMethods->xFileSize(id, pSize);
26143}
26144SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
26145  DO_OS_MALLOC_TEST(id);
26146  assert( lockType>=SQLITE_LOCK_SHARED && lockType<=SQLITE_LOCK_EXCLUSIVE );
26147  return id->pMethods->xLock(id, lockType);
26148}
26149SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
26150  assert( lockType==SQLITE_LOCK_NONE || lockType==SQLITE_LOCK_SHARED );
26151  return id->pMethods->xUnlock(id, lockType);
26152}
26153SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
26154  DO_OS_MALLOC_TEST(id);
26155  return id->pMethods->xCheckReservedLock(id, pResOut);
26156}
26157
26158/*
26159** Use sqlite3OsFileControl() when we are doing something that might fail
26160** and we need to know about the failures.  Use sqlite3OsFileControlHint()
26161** when simply tossing information over the wall to the VFS and we do not
26162** really care if the VFS receives and understands the information since it
26163** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
26164** routine has no return value since the return value would be meaningless.
26165*/
26166SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
26167  if( id->pMethods==0 ) return SQLITE_NOTFOUND;
26168#ifdef SQLITE_TEST
26169  if( op!=SQLITE_FCNTL_COMMIT_PHASETWO
26170   && op!=SQLITE_FCNTL_LOCK_TIMEOUT
26171   && op!=SQLITE_FCNTL_CKPT_DONE
26172   && op!=SQLITE_FCNTL_CKPT_START
26173  ){
26174    /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
26175    ** is using a regular VFS, it is called after the corresponding
26176    ** transaction has been committed. Injecting a fault at this point
26177    ** confuses the test scripts - the COMMIT command returns SQLITE_NOMEM
26178    ** but the transaction is committed anyway.
26179    **
26180    ** The core must call OsFileControl() though, not OsFileControlHint(),
26181    ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
26182    ** means the commit really has failed and an error should be returned
26183    ** to the user.
26184    **
26185    ** The CKPT_DONE and CKPT_START file-controls are write-only signals
26186    ** to the cksumvfs.  Their return code is meaningless and is ignored
26187    ** by the SQLite core, so there is no point in simulating OOMs for them.
26188    */
26189    DO_OS_MALLOC_TEST(id);
26190  }
26191#endif
26192  return id->pMethods->xFileControl(id, op, pArg);
26193}
26194SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
26195  if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
26196}
26197
26198SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
26199  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
26200  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
26201}
26202SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
26203  if( NEVER(id->pMethods==0) ) return 0;
26204  return id->pMethods->xDeviceCharacteristics(id);
26205}
26206#ifndef SQLITE_OMIT_WAL
26207SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
26208  return id->pMethods->xShmLock(id, offset, n, flags);
26209}
26210SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
26211  id->pMethods->xShmBarrier(id);
26212}
26213SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
26214  return id->pMethods->xShmUnmap(id, deleteFlag);
26215}
26216SQLITE_PRIVATE int sqlite3OsShmMap(
26217  sqlite3_file *id,               /* Database file handle */
26218  int iPage,
26219  int pgsz,
26220  int bExtend,                    /* True to extend file if necessary */
26221  void volatile **pp              /* OUT: Pointer to mapping */
26222){
26223  DO_OS_MALLOC_TEST(id);
26224  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
26225}
26226#endif /* SQLITE_OMIT_WAL */
26227
26228#if SQLITE_MAX_MMAP_SIZE>0
26229/* The real implementation of xFetch and xUnfetch */
26230SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
26231  DO_OS_MALLOC_TEST(id);
26232  return id->pMethods->xFetch(id, iOff, iAmt, pp);
26233}
26234SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
26235  return id->pMethods->xUnfetch(id, iOff, p);
26236}
26237#else
26238/* No-op stubs to use when memory-mapped I/O is disabled */
26239SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
26240  *pp = 0;
26241  return SQLITE_OK;
26242}
26243SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
26244  return SQLITE_OK;
26245}
26246#endif
26247
26248/*
26249** The next group of routines are convenience wrappers around the
26250** VFS methods.
26251*/
26252SQLITE_PRIVATE int sqlite3OsOpen(
26253  sqlite3_vfs *pVfs,
26254  const char *zPath,
26255  sqlite3_file *pFile,
26256  int flags,
26257  int *pFlagsOut
26258){
26259  int rc;
26260  DO_OS_MALLOC_TEST(0);
26261  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
26262  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
26263  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
26264  ** reaching the VFS. */
26265  assert( zPath || (flags & SQLITE_OPEN_EXCLUSIVE) );
26266  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x1087f7f, pFlagsOut);
26267  assert( rc==SQLITE_OK || pFile->pMethods==0 );
26268  return rc;
26269}
26270SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
26271  DO_OS_MALLOC_TEST(0);
26272  assert( dirSync==0 || dirSync==1 );
26273  return pVfs->xDelete!=0 ? pVfs->xDelete(pVfs, zPath, dirSync) : SQLITE_OK;
26274}
26275SQLITE_PRIVATE int sqlite3OsAccess(
26276  sqlite3_vfs *pVfs,
26277  const char *zPath,
26278  int flags,
26279  int *pResOut
26280){
26281  DO_OS_MALLOC_TEST(0);
26282  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
26283}
26284SQLITE_PRIVATE int sqlite3OsFullPathname(
26285  sqlite3_vfs *pVfs,
26286  const char *zPath,
26287  int nPathOut,
26288  char *zPathOut
26289){
26290  DO_OS_MALLOC_TEST(0);
26291  zPathOut[0] = 0;
26292  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
26293}
26294#ifndef SQLITE_OMIT_LOAD_EXTENSION
26295SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
26296  assert( zPath!=0 );
26297  assert( strlen(zPath)<=SQLITE_MAX_PATHLEN );  /* tag-20210611-1 */
26298  return pVfs->xDlOpen(pVfs, zPath);
26299}
26300SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
26301  pVfs->xDlError(pVfs, nByte, zBufOut);
26302}
26303SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
26304  return pVfs->xDlSym(pVfs, pHdle, zSym);
26305}
26306SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
26307  pVfs->xDlClose(pVfs, pHandle);
26308}
26309#endif /* SQLITE_OMIT_LOAD_EXTENSION */
26310SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
26311  if( sqlite3Config.iPrngSeed ){
26312    memset(zBufOut, 0, nByte);
26313    if( ALWAYS(nByte>(signed)sizeof(unsigned)) ) nByte = sizeof(unsigned int);
26314    memcpy(zBufOut, &sqlite3Config.iPrngSeed, nByte);
26315    return SQLITE_OK;
26316  }else{
26317    return pVfs->xRandomness(pVfs, nByte, zBufOut);
26318  }
26319
26320}
26321SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
26322  return pVfs->xSleep(pVfs, nMicro);
26323}
26324SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
26325  return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
26326}
26327SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
26328  int rc;
26329  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
26330  ** method to get the current date and time if that method is available
26331  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
26332  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
26333  ** unavailable.
26334  */
26335  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
26336    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
26337  }else{
26338    double r;
26339    rc = pVfs->xCurrentTime(pVfs, &r);
26340    *pTimeOut = (sqlite3_int64)(r*86400000.0);
26341  }
26342  return rc;
26343}
26344
26345SQLITE_PRIVATE int sqlite3OsOpenMalloc(
26346  sqlite3_vfs *pVfs,
26347  const char *zFile,
26348  sqlite3_file **ppFile,
26349  int flags,
26350  int *pOutFlags
26351){
26352  int rc;
26353  sqlite3_file *pFile;
26354  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
26355  if( pFile ){
26356    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
26357    if( rc!=SQLITE_OK ){
26358      sqlite3_free(pFile);
26359      *ppFile = 0;
26360    }else{
26361      *ppFile = pFile;
26362    }
26363  }else{
26364    *ppFile = 0;
26365    rc = SQLITE_NOMEM_BKPT;
26366  }
26367  assert( *ppFile!=0 || rc!=SQLITE_OK );
26368  return rc;
26369}
26370SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
26371  assert( pFile );
26372  sqlite3OsClose(pFile);
26373  sqlite3_free(pFile);
26374}
26375
26376/*
26377** This function is a wrapper around the OS specific implementation of
26378** sqlite3_os_init(). The purpose of the wrapper is to provide the
26379** ability to simulate a malloc failure, so that the handling of an
26380** error in sqlite3_os_init() by the upper layers can be tested.
26381*/
26382SQLITE_PRIVATE int sqlite3OsInit(void){
26383  void *p = sqlite3_malloc(10);
26384  if( p==0 ) return SQLITE_NOMEM_BKPT;
26385  sqlite3_free(p);
26386  return sqlite3_os_init();
26387}
26388
26389/*
26390** The list of all registered VFS implementations.
26391*/
26392static sqlite3_vfs * SQLITE_WSD vfsList = 0;
26393#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
26394
26395/*
26396** Locate a VFS by name.  If no name is given, simply return the
26397** first VFS on the list.
26398*/
26399SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
26400  sqlite3_vfs *pVfs = 0;
26401#if SQLITE_THREADSAFE
26402  sqlite3_mutex *mutex;
26403#endif
26404#ifndef SQLITE_OMIT_AUTOINIT
26405  int rc = sqlite3_initialize();
26406  if( rc ) return 0;
26407#endif
26408#if SQLITE_THREADSAFE
26409  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
26410#endif
26411  sqlite3_mutex_enter(mutex);
26412  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
26413    if( zVfs==0 ) break;
26414    if( strcmp(zVfs, pVfs->zName)==0 ) break;
26415  }
26416  sqlite3_mutex_leave(mutex);
26417  return pVfs;
26418}
26419
26420/*
26421** Unlink a VFS from the linked list
26422*/
26423static void vfsUnlink(sqlite3_vfs *pVfs){
26424  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN)) );
26425  if( pVfs==0 ){
26426    /* No-op */
26427  }else if( vfsList==pVfs ){
26428    vfsList = pVfs->pNext;
26429  }else if( vfsList ){
26430    sqlite3_vfs *p = vfsList;
26431    while( p->pNext && p->pNext!=pVfs ){
26432      p = p->pNext;
26433    }
26434    if( p->pNext==pVfs ){
26435      p->pNext = pVfs->pNext;
26436    }
26437  }
26438}
26439
26440/*
26441** Register a VFS with the system.  It is harmless to register the same
26442** VFS multiple times.  The new VFS becomes the default if makeDflt is
26443** true.
26444*/
26445SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
26446  MUTEX_LOGIC(sqlite3_mutex *mutex;)
26447#ifndef SQLITE_OMIT_AUTOINIT
26448  int rc = sqlite3_initialize();
26449  if( rc ) return rc;
26450#endif
26451#ifdef SQLITE_ENABLE_API_ARMOR
26452  if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
26453#endif
26454
26455  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
26456  sqlite3_mutex_enter(mutex);
26457  vfsUnlink(pVfs);
26458  if( makeDflt || vfsList==0 ){
26459    pVfs->pNext = vfsList;
26460    vfsList = pVfs;
26461  }else{
26462    pVfs->pNext = vfsList->pNext;
26463    vfsList->pNext = pVfs;
26464  }
26465  assert(vfsList);
26466  sqlite3_mutex_leave(mutex);
26467  return SQLITE_OK;
26468}
26469
26470/*
26471** Unregister a VFS so that it is no longer accessible.
26472*/
26473SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
26474  MUTEX_LOGIC(sqlite3_mutex *mutex;)
26475#ifndef SQLITE_OMIT_AUTOINIT
26476  int rc = sqlite3_initialize();
26477  if( rc ) return rc;
26478#endif
26479  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
26480  sqlite3_mutex_enter(mutex);
26481  vfsUnlink(pVfs);
26482  sqlite3_mutex_leave(mutex);
26483  return SQLITE_OK;
26484}
26485
26486/************** End of os.c **************************************************/
26487/************** Begin file fault.c *******************************************/
26488/*
26489** 2008 Jan 22
26490**
26491** The author disclaims copyright to this source code.  In place of
26492** a legal notice, here is a blessing:
26493**
26494**    May you do good and not evil.
26495**    May you find forgiveness for yourself and forgive others.
26496**    May you share freely, never taking more than you give.
26497**
26498*************************************************************************
26499**
26500** This file contains code to support the concept of "benign"
26501** malloc failures (when the xMalloc() or xRealloc() method of the
26502** sqlite3_mem_methods structure fails to allocate a block of memory
26503** and returns 0).
26504**
26505** Most malloc failures are non-benign. After they occur, SQLite
26506** abandons the current operation and returns an error code (usually
26507** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
26508** fatal. For example, if a malloc fails while resizing a hash table, this
26509** is completely recoverable simply by not carrying out the resize. The
26510** hash table will continue to function normally.  So a malloc failure
26511** during a hash table resize is a benign fault.
26512*/
26513
26514/* #include "sqliteInt.h" */
26515
26516#ifndef SQLITE_UNTESTABLE
26517
26518/*
26519** Global variables.
26520*/
26521typedef struct BenignMallocHooks BenignMallocHooks;
26522static SQLITE_WSD struct BenignMallocHooks {
26523  void (*xBenignBegin)(void);
26524  void (*xBenignEnd)(void);
26525} sqlite3Hooks = { 0, 0 };
26526
26527/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
26528** structure.  If writable static data is unsupported on the target,
26529** we have to locate the state vector at run-time.  In the more common
26530** case where writable static data is supported, wsdHooks can refer directly
26531** to the "sqlite3Hooks" state vector declared above.
26532*/
26533#ifdef SQLITE_OMIT_WSD
26534# define wsdHooksInit \
26535  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
26536# define wsdHooks x[0]
26537#else
26538# define wsdHooksInit
26539# define wsdHooks sqlite3Hooks
26540#endif
26541
26542
26543/*
26544** Register hooks to call when sqlite3BeginBenignMalloc() and
26545** sqlite3EndBenignMalloc() are called, respectively.
26546*/
26547SQLITE_PRIVATE void sqlite3BenignMallocHooks(
26548  void (*xBenignBegin)(void),
26549  void (*xBenignEnd)(void)
26550){
26551  wsdHooksInit;
26552  wsdHooks.xBenignBegin = xBenignBegin;
26553  wsdHooks.xBenignEnd = xBenignEnd;
26554}
26555
26556/*
26557** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
26558** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
26559** indicates that subsequent malloc failures are non-benign.
26560*/
26561SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
26562  wsdHooksInit;
26563  if( wsdHooks.xBenignBegin ){
26564    wsdHooks.xBenignBegin();
26565  }
26566}
26567SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
26568  wsdHooksInit;
26569  if( wsdHooks.xBenignEnd ){
26570    wsdHooks.xBenignEnd();
26571  }
26572}
26573
26574#endif   /* #ifndef SQLITE_UNTESTABLE */
26575
26576/************** End of fault.c ***********************************************/
26577/************** Begin file mem0.c ********************************************/
26578/*
26579** 2008 October 28
26580**
26581** The author disclaims copyright to this source code.  In place of
26582** a legal notice, here is a blessing:
26583**
26584**    May you do good and not evil.
26585**    May you find forgiveness for yourself and forgive others.
26586**    May you share freely, never taking more than you give.
26587**
26588*************************************************************************
26589**
26590** This file contains a no-op memory allocation drivers for use when
26591** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
26592** here always fail.  SQLite will not operate with these drivers.  These
26593** are merely placeholders.  Real drivers must be substituted using
26594** sqlite3_config() before SQLite will operate.
26595*/
26596/* #include "sqliteInt.h" */
26597
26598/*
26599** This version of the memory allocator is the default.  It is
26600** used when no other memory allocator is specified using compile-time
26601** macros.
26602*/
26603#ifdef SQLITE_ZERO_MALLOC
26604
26605/*
26606** No-op versions of all memory allocation routines
26607*/
26608static void *sqlite3MemMalloc(int nByte){ return 0; }
26609static void sqlite3MemFree(void *pPrior){ return; }
26610static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
26611static int sqlite3MemSize(void *pPrior){ return 0; }
26612static int sqlite3MemRoundup(int n){ return n; }
26613static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
26614static void sqlite3MemShutdown(void *NotUsed){ return; }
26615
26616/*
26617** This routine is the only routine in this file with external linkage.
26618**
26619** Populate the low-level memory allocation function pointers in
26620** sqlite3GlobalConfig.m with pointers to the routines in this file.
26621*/
26622SQLITE_PRIVATE void sqlite3MemSetDefault(void){
26623  static const sqlite3_mem_methods defaultMethods = {
26624     sqlite3MemMalloc,
26625     sqlite3MemFree,
26626     sqlite3MemRealloc,
26627     sqlite3MemSize,
26628     sqlite3MemRoundup,
26629     sqlite3MemInit,
26630     sqlite3MemShutdown,
26631     0
26632  };
26633  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
26634}
26635
26636#endif /* SQLITE_ZERO_MALLOC */
26637
26638/************** End of mem0.c ************************************************/
26639/************** Begin file mem1.c ********************************************/
26640/*
26641** 2007 August 14
26642**
26643** The author disclaims copyright to this source code.  In place of
26644** a legal notice, here is a blessing:
26645**
26646**    May you do good and not evil.
26647**    May you find forgiveness for yourself and forgive others.
26648**    May you share freely, never taking more than you give.
26649**
26650*************************************************************************
26651**
26652** This file contains low-level memory allocation drivers for when
26653** SQLite will use the standard C-library malloc/realloc/free interface
26654** to obtain the memory it needs.
26655**
26656** This file contains implementations of the low-level memory allocation
26657** routines specified in the sqlite3_mem_methods object.  The content of
26658** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
26659** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
26660** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
26661** default configuration is to use memory allocation routines in this
26662** file.
26663**
26664** C-preprocessor macro summary:
26665**
26666**    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
26667**                                the malloc_usable_size() interface exists
26668**                                on the target platform.  Or, this symbol
26669**                                can be set manually, if desired.
26670**                                If an equivalent interface exists by
26671**                                a different name, using a separate -D
26672**                                option to rename it.
26673**
26674**    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
26675**                                memory allocator.  Set this symbol to enable
26676**                                building on older macs.
26677**
26678**    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
26679**                                _msize() on windows systems.  This might
26680**                                be necessary when compiling for Delphi,
26681**                                for example.
26682*/
26683/* #include "sqliteInt.h" */
26684
26685/*
26686** This version of the memory allocator is the default.  It is
26687** used when no other memory allocator is specified using compile-time
26688** macros.
26689*/
26690#ifdef SQLITE_SYSTEM_MALLOC
26691#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
26692
26693/*
26694** Use the zone allocator available on apple products unless the
26695** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
26696*/
26697#include <sys/sysctl.h>
26698#include <malloc/malloc.h>
26699#ifdef SQLITE_MIGHT_BE_SINGLE_CORE
26700#include <libkern/OSAtomic.h>
26701#endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
26702static malloc_zone_t* _sqliteZone_;
26703#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
26704#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
26705#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
26706#define SQLITE_MALLOCSIZE(x) \
26707        (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
26708
26709#else /* if not __APPLE__ */
26710
26711/*
26712** Use standard C library malloc and free on non-Apple systems.
26713** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
26714*/
26715#define SQLITE_MALLOC(x)             malloc(x)
26716#define SQLITE_FREE(x)               free(x)
26717#define SQLITE_REALLOC(x,y)          realloc((x),(y))
26718
26719/*
26720** The malloc.h header file is needed for malloc_usable_size() function
26721** on some systems (e.g. Linux).
26722*/
26723#if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
26724#  define SQLITE_USE_MALLOC_H 1
26725#  define SQLITE_USE_MALLOC_USABLE_SIZE 1
26726/*
26727** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
26728** use of _msize() is automatic, but can be disabled by compiling with
26729** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
26730** the malloc.h header file.
26731*/
26732#elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
26733#  define SQLITE_USE_MALLOC_H
26734#  define SQLITE_USE_MSIZE
26735#endif
26736
26737/*
26738** Include the malloc.h header file, if necessary.  Also set define macro
26739** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
26740** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
26741** The memory size function can always be overridden manually by defining
26742** the macro SQLITE_MALLOCSIZE to the desired function name.
26743*/
26744#if defined(SQLITE_USE_MALLOC_H)
26745#  include <malloc.h>
26746#  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
26747#    if !defined(SQLITE_MALLOCSIZE)
26748#      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
26749#    endif
26750#  elif defined(SQLITE_USE_MSIZE)
26751#    if !defined(SQLITE_MALLOCSIZE)
26752#      define SQLITE_MALLOCSIZE      _msize
26753#    endif
26754#  endif
26755#endif /* defined(SQLITE_USE_MALLOC_H) */
26756
26757#endif /* __APPLE__ or not __APPLE__ */
26758
26759/*
26760** Like malloc(), but remember the size of the allocation
26761** so that we can find it later using sqlite3MemSize().
26762**
26763** For this low-level routine, we are guaranteed that nByte>0 because
26764** cases of nByte<=0 will be intercepted and dealt with by higher level
26765** routines.
26766*/
26767static void *sqlite3MemMalloc(int nByte){
26768#ifdef SQLITE_MALLOCSIZE
26769  void *p;
26770  testcase( ROUND8(nByte)==nByte );
26771  p = SQLITE_MALLOC( nByte );
26772  if( p==0 ){
26773    testcase( sqlite3GlobalConfig.xLog!=0 );
26774    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
26775  }
26776  return p;
26777#else
26778  sqlite3_int64 *p;
26779  assert( nByte>0 );
26780  testcase( ROUND8(nByte)!=nByte );
26781  p = SQLITE_MALLOC( nByte+8 );
26782  if( p ){
26783    p[0] = nByte;
26784    p++;
26785  }else{
26786    testcase( sqlite3GlobalConfig.xLog!=0 );
26787    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
26788  }
26789  return (void *)p;
26790#endif
26791}
26792
26793/*
26794** Like free() but works for allocations obtained from sqlite3MemMalloc()
26795** or sqlite3MemRealloc().
26796**
26797** For this low-level routine, we already know that pPrior!=0 since
26798** cases where pPrior==0 will have been intercepted and dealt with
26799** by higher-level routines.
26800*/
26801static void sqlite3MemFree(void *pPrior){
26802#ifdef SQLITE_MALLOCSIZE
26803  SQLITE_FREE(pPrior);
26804#else
26805  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
26806  assert( pPrior!=0 );
26807  p--;
26808  SQLITE_FREE(p);
26809#endif
26810}
26811
26812/*
26813** Report the allocated size of a prior return from xMalloc()
26814** or xRealloc().
26815*/
26816static int sqlite3MemSize(void *pPrior){
26817#ifdef SQLITE_MALLOCSIZE
26818  assert( pPrior!=0 );
26819  return (int)SQLITE_MALLOCSIZE(pPrior);
26820#else
26821  sqlite3_int64 *p;
26822  assert( pPrior!=0 );
26823  p = (sqlite3_int64*)pPrior;
26824  p--;
26825  return (int)p[0];
26826#endif
26827}
26828
26829/*
26830** Like realloc().  Resize an allocation previously obtained from
26831** sqlite3MemMalloc().
26832**
26833** For this low-level interface, we know that pPrior!=0.  Cases where
26834** pPrior==0 while have been intercepted by higher-level routine and
26835** redirected to xMalloc.  Similarly, we know that nByte>0 because
26836** cases where nByte<=0 will have been intercepted by higher-level
26837** routines and redirected to xFree.
26838*/
26839static void *sqlite3MemRealloc(void *pPrior, int nByte){
26840#ifdef SQLITE_MALLOCSIZE
26841  void *p = SQLITE_REALLOC(pPrior, nByte);
26842  if( p==0 ){
26843    testcase( sqlite3GlobalConfig.xLog!=0 );
26844    sqlite3_log(SQLITE_NOMEM,
26845      "failed memory resize %u to %u bytes",
26846      SQLITE_MALLOCSIZE(pPrior), nByte);
26847  }
26848  return p;
26849#else
26850  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
26851  assert( pPrior!=0 && nByte>0 );
26852  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
26853  p--;
26854  p = SQLITE_REALLOC(p, nByte+8 );
26855  if( p ){
26856    p[0] = nByte;
26857    p++;
26858  }else{
26859    testcase( sqlite3GlobalConfig.xLog!=0 );
26860    sqlite3_log(SQLITE_NOMEM,
26861      "failed memory resize %u to %u bytes",
26862      sqlite3MemSize(pPrior), nByte);
26863  }
26864  return (void*)p;
26865#endif
26866}
26867
26868/*
26869** Round up a request size to the next valid allocation size.
26870*/
26871static int sqlite3MemRoundup(int n){
26872  return ROUND8(n);
26873}
26874
26875/*
26876** Initialize this module.
26877*/
26878static int sqlite3MemInit(void *NotUsed){
26879#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
26880  int cpuCount;
26881  size_t len;
26882  if( _sqliteZone_ ){
26883    return SQLITE_OK;
26884  }
26885  len = sizeof(cpuCount);
26886  /* One usually wants to use hw.activecpu for MT decisions, but not here */
26887  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
26888  if( cpuCount>1 ){
26889    /* defer MT decisions to system malloc */
26890    _sqliteZone_ = malloc_default_zone();
26891  }else{
26892    /* only 1 core, use our own zone to contention over global locks,
26893    ** e.g. we have our own dedicated locks */
26894    _sqliteZone_ = malloc_create_zone(4096, 0);
26895    malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
26896  }
26897#endif /*  defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
26898  UNUSED_PARAMETER(NotUsed);
26899  return SQLITE_OK;
26900}
26901
26902/*
26903** Deinitialize this module.
26904*/
26905static void sqlite3MemShutdown(void *NotUsed){
26906  UNUSED_PARAMETER(NotUsed);
26907  return;
26908}
26909
26910/*
26911** This routine is the only routine in this file with external linkage.
26912**
26913** Populate the low-level memory allocation function pointers in
26914** sqlite3GlobalConfig.m with pointers to the routines in this file.
26915*/
26916SQLITE_PRIVATE void sqlite3MemSetDefault(void){
26917  static const sqlite3_mem_methods defaultMethods = {
26918     sqlite3MemMalloc,
26919     sqlite3MemFree,
26920     sqlite3MemRealloc,
26921     sqlite3MemSize,
26922     sqlite3MemRoundup,
26923     sqlite3MemInit,
26924     sqlite3MemShutdown,
26925     0
26926  };
26927  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
26928}
26929
26930#endif /* SQLITE_SYSTEM_MALLOC */
26931
26932/************** End of mem1.c ************************************************/
26933/************** Begin file mem2.c ********************************************/
26934/*
26935** 2007 August 15
26936**
26937** The author disclaims copyright to this source code.  In place of
26938** a legal notice, here is a blessing:
26939**
26940**    May you do good and not evil.
26941**    May you find forgiveness for yourself and forgive others.
26942**    May you share freely, never taking more than you give.
26943**
26944*************************************************************************
26945**
26946** This file contains low-level memory allocation drivers for when
26947** SQLite will use the standard C-library malloc/realloc/free interface
26948** to obtain the memory it needs while adding lots of additional debugging
26949** information to each allocation in order to help detect and fix memory
26950** leaks and memory usage errors.
26951**
26952** This file contains implementations of the low-level memory allocation
26953** routines specified in the sqlite3_mem_methods object.
26954*/
26955/* #include "sqliteInt.h" */
26956
26957/*
26958** This version of the memory allocator is used only if the
26959** SQLITE_MEMDEBUG macro is defined
26960*/
26961#ifdef SQLITE_MEMDEBUG
26962
26963/*
26964** The backtrace functionality is only available with GLIBC
26965*/
26966#ifdef __GLIBC__
26967  extern int backtrace(void**,int);
26968  extern void backtrace_symbols_fd(void*const*,int,int);
26969#else
26970# define backtrace(A,B) 1
26971# define backtrace_symbols_fd(A,B,C)
26972#endif
26973/* #include <stdio.h> */
26974
26975/*
26976** Each memory allocation looks like this:
26977**
26978**  ------------------------------------------------------------------------
26979**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
26980**  ------------------------------------------------------------------------
26981**
26982** The application code sees only a pointer to the allocation.  We have
26983** to back up from the allocation pointer to find the MemBlockHdr.  The
26984** MemBlockHdr tells us the size of the allocation and the number of
26985** backtrace pointers.  There is also a guard word at the end of the
26986** MemBlockHdr.
26987*/
26988struct MemBlockHdr {
26989  i64 iSize;                          /* Size of this allocation */
26990  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
26991  char nBacktrace;                    /* Number of backtraces on this alloc */
26992  char nBacktraceSlots;               /* Available backtrace slots */
26993  u8 nTitle;                          /* Bytes of title; includes '\0' */
26994  u8 eType;                           /* Allocation type code */
26995  int iForeGuard;                     /* Guard word for sanity */
26996};
26997
26998/*
26999** Guard words
27000*/
27001#define FOREGUARD 0x80F5E153
27002#define REARGUARD 0xE4676B53
27003
27004/*
27005** Number of malloc size increments to track.
27006*/
27007#define NCSIZE  1000
27008
27009/*
27010** All of the static variables used by this module are collected
27011** into a single structure named "mem".  This is to keep the
27012** static variables organized and to reduce namespace pollution
27013** when this module is combined with other in the amalgamation.
27014*/
27015static struct {
27016
27017  /*
27018  ** Mutex to control access to the memory allocation subsystem.
27019  */
27020  sqlite3_mutex *mutex;
27021
27022  /*
27023  ** Head and tail of a linked list of all outstanding allocations
27024  */
27025  struct MemBlockHdr *pFirst;
27026  struct MemBlockHdr *pLast;
27027
27028  /*
27029  ** The number of levels of backtrace to save in new allocations.
27030  */
27031  int nBacktrace;
27032  void (*xBacktrace)(int, int, void **);
27033
27034  /*
27035  ** Title text to insert in front of each block
27036  */
27037  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
27038  char zTitle[100];  /* The title text */
27039
27040  /*
27041  ** sqlite3MallocDisallow() increments the following counter.
27042  ** sqlite3MallocAllow() decrements it.
27043  */
27044  int disallow; /* Do not allow memory allocation */
27045
27046  /*
27047  ** Gather statistics on the sizes of memory allocations.
27048  ** nAlloc[i] is the number of allocation attempts of i*8
27049  ** bytes.  i==NCSIZE is the number of allocation attempts for
27050  ** sizes more than NCSIZE*8 bytes.
27051  */
27052  int nAlloc[NCSIZE];      /* Total number of allocations */
27053  int nCurrent[NCSIZE];    /* Current number of allocations */
27054  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
27055
27056} mem;
27057
27058
27059/*
27060** Adjust memory usage statistics
27061*/
27062static void adjustStats(int iSize, int increment){
27063  int i = ROUND8(iSize)/8;
27064  if( i>NCSIZE-1 ){
27065    i = NCSIZE - 1;
27066  }
27067  if( increment>0 ){
27068    mem.nAlloc[i]++;
27069    mem.nCurrent[i]++;
27070    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
27071      mem.mxCurrent[i] = mem.nCurrent[i];
27072    }
27073  }else{
27074    mem.nCurrent[i]--;
27075    assert( mem.nCurrent[i]>=0 );
27076  }
27077}
27078
27079/*
27080** Given an allocation, find the MemBlockHdr for that allocation.
27081**
27082** This routine checks the guards at either end of the allocation and
27083** if they are incorrect it asserts.
27084*/
27085static struct MemBlockHdr *sqlite3MemsysGetHeader(const void *pAllocation){
27086  struct MemBlockHdr *p;
27087  int *pInt;
27088  u8 *pU8;
27089  int nReserve;
27090
27091  p = (struct MemBlockHdr*)pAllocation;
27092  p--;
27093  assert( p->iForeGuard==(int)FOREGUARD );
27094  nReserve = ROUND8(p->iSize);
27095  pInt = (int*)pAllocation;
27096  pU8 = (u8*)pAllocation;
27097  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
27098  /* This checks any of the "extra" bytes allocated due
27099  ** to rounding up to an 8 byte boundary to ensure
27100  ** they haven't been overwritten.
27101  */
27102  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
27103  return p;
27104}
27105
27106/*
27107** Return the number of bytes currently allocated at address p.
27108*/
27109static int sqlite3MemSize(void *p){
27110  struct MemBlockHdr *pHdr;
27111  if( !p ){
27112    return 0;
27113  }
27114  pHdr = sqlite3MemsysGetHeader(p);
27115  return (int)pHdr->iSize;
27116}
27117
27118/*
27119** Initialize the memory allocation subsystem.
27120*/
27121static int sqlite3MemInit(void *NotUsed){
27122  UNUSED_PARAMETER(NotUsed);
27123  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
27124  if( !sqlite3GlobalConfig.bMemstat ){
27125    /* If memory status is enabled, then the malloc.c wrapper will already
27126    ** hold the STATIC_MEM mutex when the routines here are invoked. */
27127    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
27128  }
27129  return SQLITE_OK;
27130}
27131
27132/*
27133** Deinitialize the memory allocation subsystem.
27134*/
27135static void sqlite3MemShutdown(void *NotUsed){
27136  UNUSED_PARAMETER(NotUsed);
27137  mem.mutex = 0;
27138}
27139
27140/*
27141** Round up a request size to the next valid allocation size.
27142*/
27143static int sqlite3MemRoundup(int n){
27144  return ROUND8(n);
27145}
27146
27147/*
27148** Fill a buffer with pseudo-random bytes.  This is used to preset
27149** the content of a new memory allocation to unpredictable values and
27150** to clear the content of a freed allocation to unpredictable values.
27151*/
27152static void randomFill(char *pBuf, int nByte){
27153  unsigned int x, y, r;
27154  x = SQLITE_PTR_TO_INT(pBuf);
27155  y = nByte | 1;
27156  while( nByte >= 4 ){
27157    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
27158    y = y*1103515245 + 12345;
27159    r = x ^ y;
27160    *(int*)pBuf = r;
27161    pBuf += 4;
27162    nByte -= 4;
27163  }
27164  while( nByte-- > 0 ){
27165    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
27166    y = y*1103515245 + 12345;
27167    r = x ^ y;
27168    *(pBuf++) = r & 0xff;
27169  }
27170}
27171
27172/*
27173** Allocate nByte bytes of memory.
27174*/
27175static void *sqlite3MemMalloc(int nByte){
27176  struct MemBlockHdr *pHdr;
27177  void **pBt;
27178  char *z;
27179  int *pInt;
27180  void *p = 0;
27181  int totalSize;
27182  int nReserve;
27183  sqlite3_mutex_enter(mem.mutex);
27184  assert( mem.disallow==0 );
27185  nReserve = ROUND8(nByte);
27186  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
27187               mem.nBacktrace*sizeof(void*) + mem.nTitle;
27188  p = malloc(totalSize);
27189  if( p ){
27190    z = p;
27191    pBt = (void**)&z[mem.nTitle];
27192    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
27193    pHdr->pNext = 0;
27194    pHdr->pPrev = mem.pLast;
27195    if( mem.pLast ){
27196      mem.pLast->pNext = pHdr;
27197    }else{
27198      mem.pFirst = pHdr;
27199    }
27200    mem.pLast = pHdr;
27201    pHdr->iForeGuard = FOREGUARD;
27202    pHdr->eType = MEMTYPE_HEAP;
27203    pHdr->nBacktraceSlots = mem.nBacktrace;
27204    pHdr->nTitle = mem.nTitle;
27205    if( mem.nBacktrace ){
27206      void *aAddr[40];
27207      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
27208      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
27209      assert(pBt[0]);
27210      if( mem.xBacktrace ){
27211        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
27212      }
27213    }else{
27214      pHdr->nBacktrace = 0;
27215    }
27216    if( mem.nTitle ){
27217      memcpy(z, mem.zTitle, mem.nTitle);
27218    }
27219    pHdr->iSize = nByte;
27220    adjustStats(nByte, +1);
27221    pInt = (int*)&pHdr[1];
27222    pInt[nReserve/sizeof(int)] = REARGUARD;
27223    randomFill((char*)pInt, nByte);
27224    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
27225    p = (void*)pInt;
27226  }
27227  sqlite3_mutex_leave(mem.mutex);
27228  return p;
27229}
27230
27231/*
27232** Free memory.
27233*/
27234static void sqlite3MemFree(void *pPrior){
27235  struct MemBlockHdr *pHdr;
27236  void **pBt;
27237  char *z;
27238  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
27239       || mem.mutex!=0 );
27240  pHdr = sqlite3MemsysGetHeader(pPrior);
27241  pBt = (void**)pHdr;
27242  pBt -= pHdr->nBacktraceSlots;
27243  sqlite3_mutex_enter(mem.mutex);
27244  if( pHdr->pPrev ){
27245    assert( pHdr->pPrev->pNext==pHdr );
27246    pHdr->pPrev->pNext = pHdr->pNext;
27247  }else{
27248    assert( mem.pFirst==pHdr );
27249    mem.pFirst = pHdr->pNext;
27250  }
27251  if( pHdr->pNext ){
27252    assert( pHdr->pNext->pPrev==pHdr );
27253    pHdr->pNext->pPrev = pHdr->pPrev;
27254  }else{
27255    assert( mem.pLast==pHdr );
27256    mem.pLast = pHdr->pPrev;
27257  }
27258  z = (char*)pBt;
27259  z -= pHdr->nTitle;
27260  adjustStats((int)pHdr->iSize, -1);
27261  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
27262                (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
27263  free(z);
27264  sqlite3_mutex_leave(mem.mutex);
27265}
27266
27267/*
27268** Change the size of an existing memory allocation.
27269**
27270** For this debugging implementation, we *always* make a copy of the
27271** allocation into a new place in memory.  In this way, if the
27272** higher level code is using pointer to the old allocation, it is
27273** much more likely to break and we are much more liking to find
27274** the error.
27275*/
27276static void *sqlite3MemRealloc(void *pPrior, int nByte){
27277  struct MemBlockHdr *pOldHdr;
27278  void *pNew;
27279  assert( mem.disallow==0 );
27280  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
27281  pOldHdr = sqlite3MemsysGetHeader(pPrior);
27282  pNew = sqlite3MemMalloc(nByte);
27283  if( pNew ){
27284    memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
27285    if( nByte>pOldHdr->iSize ){
27286      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
27287    }
27288    sqlite3MemFree(pPrior);
27289  }
27290  return pNew;
27291}
27292
27293/*
27294** Populate the low-level memory allocation function pointers in
27295** sqlite3GlobalConfig.m with pointers to the routines in this file.
27296*/
27297SQLITE_PRIVATE void sqlite3MemSetDefault(void){
27298  static const sqlite3_mem_methods defaultMethods = {
27299     sqlite3MemMalloc,
27300     sqlite3MemFree,
27301     sqlite3MemRealloc,
27302     sqlite3MemSize,
27303     sqlite3MemRoundup,
27304     sqlite3MemInit,
27305     sqlite3MemShutdown,
27306     0
27307  };
27308  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
27309}
27310
27311/*
27312** Set the "type" of an allocation.
27313*/
27314SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
27315  if( p && sqlite3GlobalConfig.m.xFree==sqlite3MemFree ){
27316    struct MemBlockHdr *pHdr;
27317    pHdr = sqlite3MemsysGetHeader(p);
27318    assert( pHdr->iForeGuard==FOREGUARD );
27319    pHdr->eType = eType;
27320  }
27321}
27322
27323/*
27324** Return TRUE if the mask of type in eType matches the type of the
27325** allocation p.  Also return true if p==NULL.
27326**
27327** This routine is designed for use within an assert() statement, to
27328** verify the type of an allocation.  For example:
27329**
27330**     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
27331*/
27332SQLITE_PRIVATE int sqlite3MemdebugHasType(const void *p, u8 eType){
27333  int rc = 1;
27334  if( p && sqlite3GlobalConfig.m.xFree==sqlite3MemFree ){
27335    struct MemBlockHdr *pHdr;
27336    pHdr = sqlite3MemsysGetHeader(p);
27337    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
27338    if( (pHdr->eType&eType)==0 ){
27339      rc = 0;
27340    }
27341  }
27342  return rc;
27343}
27344
27345/*
27346** Return TRUE if the mask of type in eType matches no bits of the type of the
27347** allocation p.  Also return true if p==NULL.
27348**
27349** This routine is designed for use within an assert() statement, to
27350** verify the type of an allocation.  For example:
27351**
27352**     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
27353*/
27354SQLITE_PRIVATE int sqlite3MemdebugNoType(const void *p, u8 eType){
27355  int rc = 1;
27356  if( p && sqlite3GlobalConfig.m.xFree==sqlite3MemFree ){
27357    struct MemBlockHdr *pHdr;
27358    pHdr = sqlite3MemsysGetHeader(p);
27359    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
27360    if( (pHdr->eType&eType)!=0 ){
27361      rc = 0;
27362    }
27363  }
27364  return rc;
27365}
27366
27367/*
27368** Set the number of backtrace levels kept for each allocation.
27369** A value of zero turns off backtracing.  The number is always rounded
27370** up to a multiple of 2.
27371*/
27372SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
27373  if( depth<0 ){ depth = 0; }
27374  if( depth>20 ){ depth = 20; }
27375  depth = (depth+1)&0xfe;
27376  mem.nBacktrace = depth;
27377}
27378
27379SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
27380  mem.xBacktrace = xBacktrace;
27381}
27382
27383/*
27384** Set the title string for subsequent allocations.
27385*/
27386SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
27387  unsigned int n = sqlite3Strlen30(zTitle) + 1;
27388  sqlite3_mutex_enter(mem.mutex);
27389  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
27390  memcpy(mem.zTitle, zTitle, n);
27391  mem.zTitle[n] = 0;
27392  mem.nTitle = ROUND8(n);
27393  sqlite3_mutex_leave(mem.mutex);
27394}
27395
27396SQLITE_PRIVATE void sqlite3MemdebugSync(){
27397  struct MemBlockHdr *pHdr;
27398  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
27399    void **pBt = (void**)pHdr;
27400    pBt -= pHdr->nBacktraceSlots;
27401    mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
27402  }
27403}
27404
27405/*
27406** Open the file indicated and write a log of all unfreed memory
27407** allocations into that log.
27408*/
27409SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
27410  FILE *out;
27411  struct MemBlockHdr *pHdr;
27412  void **pBt;
27413  int i;
27414  out = fopen(zFilename, "w");
27415  if( out==0 ){
27416    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
27417                    zFilename);
27418    return;
27419  }
27420  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
27421    char *z = (char*)pHdr;
27422    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
27423    fprintf(out, "**** %lld bytes at %p from %s ****\n",
27424            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
27425    if( pHdr->nBacktrace ){
27426      fflush(out);
27427      pBt = (void**)pHdr;
27428      pBt -= pHdr->nBacktraceSlots;
27429      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
27430      fprintf(out, "\n");
27431    }
27432  }
27433  fprintf(out, "COUNTS:\n");
27434  for(i=0; i<NCSIZE-1; i++){
27435    if( mem.nAlloc[i] ){
27436      fprintf(out, "   %5d: %10d %10d %10d\n",
27437            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
27438    }
27439  }
27440  if( mem.nAlloc[NCSIZE-1] ){
27441    fprintf(out, "   %5d: %10d %10d %10d\n",
27442             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
27443             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
27444  }
27445  fclose(out);
27446}
27447
27448/*
27449** Return the number of times sqlite3MemMalloc() has been called.
27450*/
27451SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
27452  int i;
27453  int nTotal = 0;
27454  for(i=0; i<NCSIZE; i++){
27455    nTotal += mem.nAlloc[i];
27456  }
27457  return nTotal;
27458}
27459
27460
27461#endif /* SQLITE_MEMDEBUG */
27462
27463/************** End of mem2.c ************************************************/
27464/************** Begin file mem3.c ********************************************/
27465/*
27466** 2007 October 14
27467**
27468** The author disclaims copyright to this source code.  In place of
27469** a legal notice, here is a blessing:
27470**
27471**    May you do good and not evil.
27472**    May you find forgiveness for yourself and forgive others.
27473**    May you share freely, never taking more than you give.
27474**
27475*************************************************************************
27476** This file contains the C functions that implement a memory
27477** allocation subsystem for use by SQLite.
27478**
27479** This version of the memory allocation subsystem omits all
27480** use of malloc(). The SQLite user supplies a block of memory
27481** before calling sqlite3_initialize() from which allocations
27482** are made and returned by the xMalloc() and xRealloc()
27483** implementations. Once sqlite3_initialize() has been called,
27484** the amount of memory available to SQLite is fixed and cannot
27485** be changed.
27486**
27487** This version of the memory allocation subsystem is included
27488** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
27489*/
27490/* #include "sqliteInt.h" */
27491
27492/*
27493** This version of the memory allocator is only built into the library
27494** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
27495** mean that the library will use a memory-pool by default, just that
27496** it is available. The mempool allocator is activated by calling
27497** sqlite3_config().
27498*/
27499#ifdef SQLITE_ENABLE_MEMSYS3
27500
27501/*
27502** Maximum size (in Mem3Blocks) of a "small" chunk.
27503*/
27504#define MX_SMALL 10
27505
27506
27507/*
27508** Number of freelist hash slots
27509*/
27510#define N_HASH  61
27511
27512/*
27513** A memory allocation (also called a "chunk") consists of two or
27514** more blocks where each block is 8 bytes.  The first 8 bytes are
27515** a header that is not returned to the user.
27516**
27517** A chunk is two or more blocks that is either checked out or
27518** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
27519** size of the allocation in blocks if the allocation is free.
27520** The u.hdr.size4x&1 bit is true if the chunk is checked out and
27521** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
27522** is true if the previous chunk is checked out and false if the
27523** previous chunk is free.  The u.hdr.prevSize field is the size of
27524** the previous chunk in blocks if the previous chunk is on the
27525** freelist. If the previous chunk is checked out, then
27526** u.hdr.prevSize can be part of the data for that chunk and should
27527** not be read or written.
27528**
27529** We often identify a chunk by its index in mem3.aPool[].  When
27530** this is done, the chunk index refers to the second block of
27531** the chunk.  In this way, the first chunk has an index of 1.
27532** A chunk index of 0 means "no such chunk" and is the equivalent
27533** of a NULL pointer.
27534**
27535** The second block of free chunks is of the form u.list.  The
27536** two fields form a double-linked list of chunks of related sizes.
27537** Pointers to the head of the list are stored in mem3.aiSmall[]
27538** for smaller chunks and mem3.aiHash[] for larger chunks.
27539**
27540** The second block of a chunk is user data if the chunk is checked
27541** out.  If a chunk is checked out, the user data may extend into
27542** the u.hdr.prevSize value of the following chunk.
27543*/
27544typedef struct Mem3Block Mem3Block;
27545struct Mem3Block {
27546  union {
27547    struct {
27548      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
27549      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
27550    } hdr;
27551    struct {
27552      u32 next;       /* Index in mem3.aPool[] of next free chunk */
27553      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
27554    } list;
27555  } u;
27556};
27557
27558/*
27559** All of the static variables used by this module are collected
27560** into a single structure named "mem3".  This is to keep the
27561** static variables organized and to reduce namespace pollution
27562** when this module is combined with other in the amalgamation.
27563*/
27564static SQLITE_WSD struct Mem3Global {
27565  /*
27566  ** Memory available for allocation. nPool is the size of the array
27567  ** (in Mem3Blocks) pointed to by aPool less 2.
27568  */
27569  u32 nPool;
27570  Mem3Block *aPool;
27571
27572  /*
27573  ** True if we are evaluating an out-of-memory callback.
27574  */
27575  int alarmBusy;
27576
27577  /*
27578  ** Mutex to control access to the memory allocation subsystem.
27579  */
27580  sqlite3_mutex *mutex;
27581
27582  /*
27583  ** The minimum amount of free space that we have seen.
27584  */
27585  u32 mnKeyBlk;
27586
27587  /*
27588  ** iKeyBlk is the index of the key chunk.  Most new allocations
27589  ** occur off of this chunk.  szKeyBlk is the size (in Mem3Blocks)
27590  ** of the current key chunk.  iKeyBlk is 0 if there is no key chunk.
27591  ** The key chunk is not in either the aiHash[] or aiSmall[].
27592  */
27593  u32 iKeyBlk;
27594  u32 szKeyBlk;
27595
27596  /*
27597  ** Array of lists of free blocks according to the block size
27598  ** for smaller chunks, or a hash on the block size for larger
27599  ** chunks.
27600  */
27601  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
27602  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
27603} mem3 = { 97535575 };
27604
27605#define mem3 GLOBAL(struct Mem3Global, mem3)
27606
27607/*
27608** Unlink the chunk at mem3.aPool[i] from list it is currently
27609** on.  *pRoot is the list that i is a member of.
27610*/
27611static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
27612  u32 next = mem3.aPool[i].u.list.next;
27613  u32 prev = mem3.aPool[i].u.list.prev;
27614  assert( sqlite3_mutex_held(mem3.mutex) );
27615  if( prev==0 ){
27616    *pRoot = next;
27617  }else{
27618    mem3.aPool[prev].u.list.next = next;
27619  }
27620  if( next ){
27621    mem3.aPool[next].u.list.prev = prev;
27622  }
27623  mem3.aPool[i].u.list.next = 0;
27624  mem3.aPool[i].u.list.prev = 0;
27625}
27626
27627/*
27628** Unlink the chunk at index i from
27629** whatever list is currently a member of.
27630*/
27631static void memsys3Unlink(u32 i){
27632  u32 size, hash;
27633  assert( sqlite3_mutex_held(mem3.mutex) );
27634  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
27635  assert( i>=1 );
27636  size = mem3.aPool[i-1].u.hdr.size4x/4;
27637  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
27638  assert( size>=2 );
27639  if( size <= MX_SMALL ){
27640    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
27641  }else{
27642    hash = size % N_HASH;
27643    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
27644  }
27645}
27646
27647/*
27648** Link the chunk at mem3.aPool[i] so that is on the list rooted
27649** at *pRoot.
27650*/
27651static void memsys3LinkIntoList(u32 i, u32 *pRoot){
27652  assert( sqlite3_mutex_held(mem3.mutex) );
27653  mem3.aPool[i].u.list.next = *pRoot;
27654  mem3.aPool[i].u.list.prev = 0;
27655  if( *pRoot ){
27656    mem3.aPool[*pRoot].u.list.prev = i;
27657  }
27658  *pRoot = i;
27659}
27660
27661/*
27662** Link the chunk at index i into either the appropriate
27663** small chunk list, or into the large chunk hash table.
27664*/
27665static void memsys3Link(u32 i){
27666  u32 size, hash;
27667  assert( sqlite3_mutex_held(mem3.mutex) );
27668  assert( i>=1 );
27669  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
27670  size = mem3.aPool[i-1].u.hdr.size4x/4;
27671  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
27672  assert( size>=2 );
27673  if( size <= MX_SMALL ){
27674    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
27675  }else{
27676    hash = size % N_HASH;
27677    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
27678  }
27679}
27680
27681/*
27682** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
27683** will already be held (obtained by code in malloc.c) if
27684** sqlite3GlobalConfig.bMemStat is true.
27685*/
27686static void memsys3Enter(void){
27687  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
27688    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
27689  }
27690  sqlite3_mutex_enter(mem3.mutex);
27691}
27692static void memsys3Leave(void){
27693  sqlite3_mutex_leave(mem3.mutex);
27694}
27695
27696/*
27697** Called when we are unable to satisfy an allocation of nBytes.
27698*/
27699static void memsys3OutOfMemory(int nByte){
27700  if( !mem3.alarmBusy ){
27701    mem3.alarmBusy = 1;
27702    assert( sqlite3_mutex_held(mem3.mutex) );
27703    sqlite3_mutex_leave(mem3.mutex);
27704    sqlite3_release_memory(nByte);
27705    sqlite3_mutex_enter(mem3.mutex);
27706    mem3.alarmBusy = 0;
27707  }
27708}
27709
27710
27711/*
27712** Chunk i is a free chunk that has been unlinked.  Adjust its
27713** size parameters for check-out and return a pointer to the
27714** user portion of the chunk.
27715*/
27716static void *memsys3Checkout(u32 i, u32 nBlock){
27717  u32 x;
27718  assert( sqlite3_mutex_held(mem3.mutex) );
27719  assert( i>=1 );
27720  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
27721  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
27722  x = mem3.aPool[i-1].u.hdr.size4x;
27723  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
27724  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
27725  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
27726  return &mem3.aPool[i];
27727}
27728
27729/*
27730** Carve a piece off of the end of the mem3.iKeyBlk free chunk.
27731** Return a pointer to the new allocation.  Or, if the key chunk
27732** is not large enough, return 0.
27733*/
27734static void *memsys3FromKeyBlk(u32 nBlock){
27735  assert( sqlite3_mutex_held(mem3.mutex) );
27736  assert( mem3.szKeyBlk>=nBlock );
27737  if( nBlock>=mem3.szKeyBlk-1 ){
27738    /* Use the entire key chunk */
27739    void *p = memsys3Checkout(mem3.iKeyBlk, mem3.szKeyBlk);
27740    mem3.iKeyBlk = 0;
27741    mem3.szKeyBlk = 0;
27742    mem3.mnKeyBlk = 0;
27743    return p;
27744  }else{
27745    /* Split the key block.  Return the tail. */
27746    u32 newi, x;
27747    newi = mem3.iKeyBlk + mem3.szKeyBlk - nBlock;
27748    assert( newi > mem3.iKeyBlk+1 );
27749    mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = nBlock;
27750    mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x |= 2;
27751    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
27752    mem3.szKeyBlk -= nBlock;
27753    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szKeyBlk;
27754    x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
27755    mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
27756    if( mem3.szKeyBlk < mem3.mnKeyBlk ){
27757      mem3.mnKeyBlk = mem3.szKeyBlk;
27758    }
27759    return (void*)&mem3.aPool[newi];
27760  }
27761}
27762
27763/*
27764** *pRoot is the head of a list of free chunks of the same size
27765** or same size hash.  In other words, *pRoot is an entry in either
27766** mem3.aiSmall[] or mem3.aiHash[].
27767**
27768** This routine examines all entries on the given list and tries
27769** to coalesce each entries with adjacent free chunks.
27770**
27771** If it sees a chunk that is larger than mem3.iKeyBlk, it replaces
27772** the current mem3.iKeyBlk with the new larger chunk.  In order for
27773** this mem3.iKeyBlk replacement to work, the key chunk must be
27774** linked into the hash tables.  That is not the normal state of
27775** affairs, of course.  The calling routine must link the key
27776** chunk before invoking this routine, then must unlink the (possibly
27777** changed) key chunk once this routine has finished.
27778*/
27779static void memsys3Merge(u32 *pRoot){
27780  u32 iNext, prev, size, i, x;
27781
27782  assert( sqlite3_mutex_held(mem3.mutex) );
27783  for(i=*pRoot; i>0; i=iNext){
27784    iNext = mem3.aPool[i].u.list.next;
27785    size = mem3.aPool[i-1].u.hdr.size4x;
27786    assert( (size&1)==0 );
27787    if( (size&2)==0 ){
27788      memsys3UnlinkFromList(i, pRoot);
27789      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
27790      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
27791      if( prev==iNext ){
27792        iNext = mem3.aPool[prev].u.list.next;
27793      }
27794      memsys3Unlink(prev);
27795      size = i + size/4 - prev;
27796      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
27797      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
27798      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
27799      memsys3Link(prev);
27800      i = prev;
27801    }else{
27802      size /= 4;
27803    }
27804    if( size>mem3.szKeyBlk ){
27805      mem3.iKeyBlk = i;
27806      mem3.szKeyBlk = size;
27807    }
27808  }
27809}
27810
27811/*
27812** Return a block of memory of at least nBytes in size.
27813** Return NULL if unable.
27814**
27815** This function assumes that the necessary mutexes, if any, are
27816** already held by the caller. Hence "Unsafe".
27817*/
27818static void *memsys3MallocUnsafe(int nByte){
27819  u32 i;
27820  u32 nBlock;
27821  u32 toFree;
27822
27823  assert( sqlite3_mutex_held(mem3.mutex) );
27824  assert( sizeof(Mem3Block)==8 );
27825  if( nByte<=12 ){
27826    nBlock = 2;
27827  }else{
27828    nBlock = (nByte + 11)/8;
27829  }
27830  assert( nBlock>=2 );
27831
27832  /* STEP 1:
27833  ** Look for an entry of the correct size in either the small
27834  ** chunk table or in the large chunk hash table.  This is
27835  ** successful most of the time (about 9 times out of 10).
27836  */
27837  if( nBlock <= MX_SMALL ){
27838    i = mem3.aiSmall[nBlock-2];
27839    if( i>0 ){
27840      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
27841      return memsys3Checkout(i, nBlock);
27842    }
27843  }else{
27844    int hash = nBlock % N_HASH;
27845    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
27846      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
27847        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
27848        return memsys3Checkout(i, nBlock);
27849      }
27850    }
27851  }
27852
27853  /* STEP 2:
27854  ** Try to satisfy the allocation by carving a piece off of the end
27855  ** of the key chunk.  This step usually works if step 1 fails.
27856  */
27857  if( mem3.szKeyBlk>=nBlock ){
27858    return memsys3FromKeyBlk(nBlock);
27859  }
27860
27861
27862  /* STEP 3:
27863  ** Loop through the entire memory pool.  Coalesce adjacent free
27864  ** chunks.  Recompute the key chunk as the largest free chunk.
27865  ** Then try again to satisfy the allocation by carving a piece off
27866  ** of the end of the key chunk.  This step happens very
27867  ** rarely (we hope!)
27868  */
27869  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
27870    memsys3OutOfMemory(toFree);
27871    if( mem3.iKeyBlk ){
27872      memsys3Link(mem3.iKeyBlk);
27873      mem3.iKeyBlk = 0;
27874      mem3.szKeyBlk = 0;
27875    }
27876    for(i=0; i<N_HASH; i++){
27877      memsys3Merge(&mem3.aiHash[i]);
27878    }
27879    for(i=0; i<MX_SMALL-1; i++){
27880      memsys3Merge(&mem3.aiSmall[i]);
27881    }
27882    if( mem3.szKeyBlk ){
27883      memsys3Unlink(mem3.iKeyBlk);
27884      if( mem3.szKeyBlk>=nBlock ){
27885        return memsys3FromKeyBlk(nBlock);
27886      }
27887    }
27888  }
27889
27890  /* If none of the above worked, then we fail. */
27891  return 0;
27892}
27893
27894/*
27895** Free an outstanding memory allocation.
27896**
27897** This function assumes that the necessary mutexes, if any, are
27898** already held by the caller. Hence "Unsafe".
27899*/
27900static void memsys3FreeUnsafe(void *pOld){
27901  Mem3Block *p = (Mem3Block*)pOld;
27902  int i;
27903  u32 size, x;
27904  assert( sqlite3_mutex_held(mem3.mutex) );
27905  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
27906  i = p - mem3.aPool;
27907  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
27908  size = mem3.aPool[i-1].u.hdr.size4x/4;
27909  assert( i+size<=mem3.nPool+1 );
27910  mem3.aPool[i-1].u.hdr.size4x &= ~1;
27911  mem3.aPool[i+size-1].u.hdr.prevSize = size;
27912  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
27913  memsys3Link(i);
27914
27915  /* Try to expand the key using the newly freed chunk */
27916  if( mem3.iKeyBlk ){
27917    while( (mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x&2)==0 ){
27918      size = mem3.aPool[mem3.iKeyBlk-1].u.hdr.prevSize;
27919      mem3.iKeyBlk -= size;
27920      mem3.szKeyBlk += size;
27921      memsys3Unlink(mem3.iKeyBlk);
27922      x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
27923      mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
27924      mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk;
27925    }
27926    x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
27927    while( (mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x&1)==0 ){
27928      memsys3Unlink(mem3.iKeyBlk+mem3.szKeyBlk);
27929      mem3.szKeyBlk += mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x/4;
27930      mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
27931      mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk;
27932    }
27933  }
27934}
27935
27936/*
27937** Return the size of an outstanding allocation, in bytes.  The
27938** size returned omits the 8-byte header overhead.  This only
27939** works for chunks that are currently checked out.
27940*/
27941static int memsys3Size(void *p){
27942  Mem3Block *pBlock;
27943  assert( p!=0 );
27944  pBlock = (Mem3Block*)p;
27945  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
27946  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
27947}
27948
27949/*
27950** Round up a request size to the next valid allocation size.
27951*/
27952static int memsys3Roundup(int n){
27953  if( n<=12 ){
27954    return 12;
27955  }else{
27956    return ((n+11)&~7) - 4;
27957  }
27958}
27959
27960/*
27961** Allocate nBytes of memory.
27962*/
27963static void *memsys3Malloc(int nBytes){
27964  sqlite3_int64 *p;
27965  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
27966  memsys3Enter();
27967  p = memsys3MallocUnsafe(nBytes);
27968  memsys3Leave();
27969  return (void*)p;
27970}
27971
27972/*
27973** Free memory.
27974*/
27975static void memsys3Free(void *pPrior){
27976  assert( pPrior );
27977  memsys3Enter();
27978  memsys3FreeUnsafe(pPrior);
27979  memsys3Leave();
27980}
27981
27982/*
27983** Change the size of an existing memory allocation
27984*/
27985static void *memsys3Realloc(void *pPrior, int nBytes){
27986  int nOld;
27987  void *p;
27988  if( pPrior==0 ){
27989    return sqlite3_malloc(nBytes);
27990  }
27991  if( nBytes<=0 ){
27992    sqlite3_free(pPrior);
27993    return 0;
27994  }
27995  nOld = memsys3Size(pPrior);
27996  if( nBytes<=nOld && nBytes>=nOld-128 ){
27997    return pPrior;
27998  }
27999  memsys3Enter();
28000  p = memsys3MallocUnsafe(nBytes);
28001  if( p ){
28002    if( nOld<nBytes ){
28003      memcpy(p, pPrior, nOld);
28004    }else{
28005      memcpy(p, pPrior, nBytes);
28006    }
28007    memsys3FreeUnsafe(pPrior);
28008  }
28009  memsys3Leave();
28010  return p;
28011}
28012
28013/*
28014** Initialize this module.
28015*/
28016static int memsys3Init(void *NotUsed){
28017  UNUSED_PARAMETER(NotUsed);
28018  if( !sqlite3GlobalConfig.pHeap ){
28019    return SQLITE_ERROR;
28020  }
28021
28022  /* Store a pointer to the memory block in global structure mem3. */
28023  assert( sizeof(Mem3Block)==8 );
28024  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
28025  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
28026
28027  /* Initialize the key block. */
28028  mem3.szKeyBlk = mem3.nPool;
28029  mem3.mnKeyBlk = mem3.szKeyBlk;
28030  mem3.iKeyBlk = 1;
28031  mem3.aPool[0].u.hdr.size4x = (mem3.szKeyBlk<<2) + 2;
28032  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
28033  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
28034
28035  return SQLITE_OK;
28036}
28037
28038/*
28039** Deinitialize this module.
28040*/
28041static void memsys3Shutdown(void *NotUsed){
28042  UNUSED_PARAMETER(NotUsed);
28043  mem3.mutex = 0;
28044  return;
28045}
28046
28047
28048
28049/*
28050** Open the file indicated and write a log of all unfreed memory
28051** allocations into that log.
28052*/
28053SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
28054#ifdef SQLITE_DEBUG
28055  FILE *out;
28056  u32 i, j;
28057  u32 size;
28058  if( zFilename==0 || zFilename[0]==0 ){
28059    out = stdout;
28060  }else{
28061    out = fopen(zFilename, "w");
28062    if( out==0 ){
28063      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
28064                      zFilename);
28065      return;
28066    }
28067  }
28068  memsys3Enter();
28069  fprintf(out, "CHUNKS:\n");
28070  for(i=1; i<=mem3.nPool; i+=size/4){
28071    size = mem3.aPool[i-1].u.hdr.size4x;
28072    if( size/4<=1 ){
28073      fprintf(out, "%p size error\n", &mem3.aPool[i]);
28074      assert( 0 );
28075      break;
28076    }
28077    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
28078      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
28079      assert( 0 );
28080      break;
28081    }
28082    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
28083      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
28084      assert( 0 );
28085      break;
28086    }
28087    if( size&1 ){
28088      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
28089    }else{
28090      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
28091                  i==mem3.iKeyBlk ? " **key**" : "");
28092    }
28093  }
28094  for(i=0; i<MX_SMALL-1; i++){
28095    if( mem3.aiSmall[i]==0 ) continue;
28096    fprintf(out, "small(%2d):", i);
28097    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
28098      fprintf(out, " %p(%d)", &mem3.aPool[j],
28099              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
28100    }
28101    fprintf(out, "\n");
28102  }
28103  for(i=0; i<N_HASH; i++){
28104    if( mem3.aiHash[i]==0 ) continue;
28105    fprintf(out, "hash(%2d):", i);
28106    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
28107      fprintf(out, " %p(%d)", &mem3.aPool[j],
28108              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
28109    }
28110    fprintf(out, "\n");
28111  }
28112  fprintf(out, "key=%d\n", mem3.iKeyBlk);
28113  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szKeyBlk*8);
28114  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnKeyBlk*8);
28115  sqlite3_mutex_leave(mem3.mutex);
28116  if( out==stdout ){
28117    fflush(stdout);
28118  }else{
28119    fclose(out);
28120  }
28121#else
28122  UNUSED_PARAMETER(zFilename);
28123#endif
28124}
28125
28126/*
28127** This routine is the only routine in this file with external
28128** linkage.
28129**
28130** Populate the low-level memory allocation function pointers in
28131** sqlite3GlobalConfig.m with pointers to the routines in this file. The
28132** arguments specify the block of memory to manage.
28133**
28134** This routine is only called by sqlite3_config(), and therefore
28135** is not required to be threadsafe (it is not).
28136*/
28137SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
28138  static const sqlite3_mem_methods mempoolMethods = {
28139     memsys3Malloc,
28140     memsys3Free,
28141     memsys3Realloc,
28142     memsys3Size,
28143     memsys3Roundup,
28144     memsys3Init,
28145     memsys3Shutdown,
28146     0
28147  };
28148  return &mempoolMethods;
28149}
28150
28151#endif /* SQLITE_ENABLE_MEMSYS3 */
28152
28153/************** End of mem3.c ************************************************/
28154/************** Begin file mem5.c ********************************************/
28155/*
28156** 2007 October 14
28157**
28158** The author disclaims copyright to this source code.  In place of
28159** a legal notice, here is a blessing:
28160**
28161**    May you do good and not evil.
28162**    May you find forgiveness for yourself and forgive others.
28163**    May you share freely, never taking more than you give.
28164**
28165*************************************************************************
28166** This file contains the C functions that implement a memory
28167** allocation subsystem for use by SQLite.
28168**
28169** This version of the memory allocation subsystem omits all
28170** use of malloc(). The application gives SQLite a block of memory
28171** before calling sqlite3_initialize() from which allocations
28172** are made and returned by the xMalloc() and xRealloc()
28173** implementations. Once sqlite3_initialize() has been called,
28174** the amount of memory available to SQLite is fixed and cannot
28175** be changed.
28176**
28177** This version of the memory allocation subsystem is included
28178** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
28179**
28180** This memory allocator uses the following algorithm:
28181**
28182**   1.  All memory allocation sizes are rounded up to a power of 2.
28183**
28184**   2.  If two adjacent free blocks are the halves of a larger block,
28185**       then the two blocks are coalesced into the single larger block.
28186**
28187**   3.  New memory is allocated from the first available free block.
28188**
28189** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
28190** Concerning Dynamic Storage Allocation". Journal of the Association for
28191** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
28192**
28193** Let n be the size of the largest allocation divided by the minimum
28194** allocation size (after rounding all sizes up to a power of 2.)  Let M
28195** be the maximum amount of memory ever outstanding at one time.  Let
28196** N be the total amount of memory available for allocation.  Robson
28197** proved that this memory allocator will never breakdown due to
28198** fragmentation as long as the following constraint holds:
28199**
28200**      N >=  M*(1 + log2(n)/2) - n + 1
28201**
28202** The sqlite3_status() logic tracks the maximum values of n and M so
28203** that an application can, at any time, verify this constraint.
28204*/
28205/* #include "sqliteInt.h" */
28206
28207/*
28208** This version of the memory allocator is used only when
28209** SQLITE_ENABLE_MEMSYS5 is defined.
28210*/
28211#ifdef SQLITE_ENABLE_MEMSYS5
28212
28213/*
28214** A minimum allocation is an instance of the following structure.
28215** Larger allocations are an array of these structures where the
28216** size of the array is a power of 2.
28217**
28218** The size of this object must be a power of two.  That fact is
28219** verified in memsys5Init().
28220*/
28221typedef struct Mem5Link Mem5Link;
28222struct Mem5Link {
28223  int next;       /* Index of next free chunk */
28224  int prev;       /* Index of previous free chunk */
28225};
28226
28227/*
28228** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
28229** mem5.szAtom is always at least 8 and 32-bit integers are used,
28230** it is not actually possible to reach this limit.
28231*/
28232#define LOGMAX 30
28233
28234/*
28235** Masks used for mem5.aCtrl[] elements.
28236*/
28237#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
28238#define CTRL_FREE     0x20    /* True if not checked out */
28239
28240/*
28241** All of the static variables used by this module are collected
28242** into a single structure named "mem5".  This is to keep the
28243** static variables organized and to reduce namespace pollution
28244** when this module is combined with other in the amalgamation.
28245*/
28246static SQLITE_WSD struct Mem5Global {
28247  /*
28248  ** Memory available for allocation
28249  */
28250  int szAtom;      /* Smallest possible allocation in bytes */
28251  int nBlock;      /* Number of szAtom sized blocks in zPool */
28252  u8 *zPool;       /* Memory available to be allocated */
28253
28254  /*
28255  ** Mutex to control access to the memory allocation subsystem.
28256  */
28257  sqlite3_mutex *mutex;
28258
28259#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
28260  /*
28261  ** Performance statistics
28262  */
28263  u64 nAlloc;         /* Total number of calls to malloc */
28264  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
28265  u64 totalExcess;    /* Total internal fragmentation */
28266  u32 currentOut;     /* Current checkout, including internal fragmentation */
28267  u32 currentCount;   /* Current number of distinct checkouts */
28268  u32 maxOut;         /* Maximum instantaneous currentOut */
28269  u32 maxCount;       /* Maximum instantaneous currentCount */
28270  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
28271#endif
28272
28273  /*
28274  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
28275  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
28276  ** aiFreelist[2] holds free blocks of size szAtom*4.  And so forth.
28277  */
28278  int aiFreelist[LOGMAX+1];
28279
28280  /*
28281  ** Space for tracking which blocks are checked out and the size
28282  ** of each block.  One byte per block.
28283  */
28284  u8 *aCtrl;
28285
28286} mem5;
28287
28288/*
28289** Access the static variable through a macro for SQLITE_OMIT_WSD.
28290*/
28291#define mem5 GLOBAL(struct Mem5Global, mem5)
28292
28293/*
28294** Assuming mem5.zPool is divided up into an array of Mem5Link
28295** structures, return a pointer to the idx-th such link.
28296*/
28297#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
28298
28299/*
28300** Unlink the chunk at mem5.aPool[i] from list it is currently
28301** on.  It should be found on mem5.aiFreelist[iLogsize].
28302*/
28303static void memsys5Unlink(int i, int iLogsize){
28304  int next, prev;
28305  assert( i>=0 && i<mem5.nBlock );
28306  assert( iLogsize>=0 && iLogsize<=LOGMAX );
28307  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
28308
28309  next = MEM5LINK(i)->next;
28310  prev = MEM5LINK(i)->prev;
28311  if( prev<0 ){
28312    mem5.aiFreelist[iLogsize] = next;
28313  }else{
28314    MEM5LINK(prev)->next = next;
28315  }
28316  if( next>=0 ){
28317    MEM5LINK(next)->prev = prev;
28318  }
28319}
28320
28321/*
28322** Link the chunk at mem5.aPool[i] so that is on the iLogsize
28323** free list.
28324*/
28325static void memsys5Link(int i, int iLogsize){
28326  int x;
28327  assert( sqlite3_mutex_held(mem5.mutex) );
28328  assert( i>=0 && i<mem5.nBlock );
28329  assert( iLogsize>=0 && iLogsize<=LOGMAX );
28330  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
28331
28332  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
28333  MEM5LINK(i)->prev = -1;
28334  if( x>=0 ){
28335    assert( x<mem5.nBlock );
28336    MEM5LINK(x)->prev = i;
28337  }
28338  mem5.aiFreelist[iLogsize] = i;
28339}
28340
28341/*
28342** Obtain or release the mutex needed to access global data structures.
28343*/
28344static void memsys5Enter(void){
28345  sqlite3_mutex_enter(mem5.mutex);
28346}
28347static void memsys5Leave(void){
28348  sqlite3_mutex_leave(mem5.mutex);
28349}
28350
28351/*
28352** Return the size of an outstanding allocation, in bytes.
28353** This only works for chunks that are currently checked out.
28354*/
28355static int memsys5Size(void *p){
28356  int iSize, i;
28357  assert( p!=0 );
28358  i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
28359  assert( i>=0 && i<mem5.nBlock );
28360  iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
28361  return iSize;
28362}
28363
28364/*
28365** Return a block of memory of at least nBytes in size.
28366** Return NULL if unable.  Return NULL if nBytes==0.
28367**
28368** The caller guarantees that nByte is positive.
28369**
28370** The caller has obtained a mutex prior to invoking this
28371** routine so there is never any chance that two or more
28372** threads can be in this routine at the same time.
28373*/
28374static void *memsys5MallocUnsafe(int nByte){
28375  int i;           /* Index of a mem5.aPool[] slot */
28376  int iBin;        /* Index into mem5.aiFreelist[] */
28377  int iFullSz;     /* Size of allocation rounded up to power of 2 */
28378  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
28379
28380  /* nByte must be a positive */
28381  assert( nByte>0 );
28382
28383  /* No more than 1GiB per allocation */
28384  if( nByte > 0x40000000 ) return 0;
28385
28386#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
28387  /* Keep track of the maximum allocation request.  Even unfulfilled
28388  ** requests are counted */
28389  if( (u32)nByte>mem5.maxRequest ){
28390    mem5.maxRequest = nByte;
28391  }
28392#endif
28393
28394
28395  /* Round nByte up to the next valid power of two */
28396  for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
28397
28398  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
28399  ** block.  If not, then split a block of the next larger power of
28400  ** two in order to create a new free block of size iLogsize.
28401  */
28402  for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
28403  if( iBin>LOGMAX ){
28404    testcase( sqlite3GlobalConfig.xLog!=0 );
28405    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
28406    return 0;
28407  }
28408  i = mem5.aiFreelist[iBin];
28409  memsys5Unlink(i, iBin);
28410  while( iBin>iLogsize ){
28411    int newSize;
28412
28413    iBin--;
28414    newSize = 1 << iBin;
28415    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
28416    memsys5Link(i+newSize, iBin);
28417  }
28418  mem5.aCtrl[i] = iLogsize;
28419
28420#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
28421  /* Update allocator performance statistics. */
28422  mem5.nAlloc++;
28423  mem5.totalAlloc += iFullSz;
28424  mem5.totalExcess += iFullSz - nByte;
28425  mem5.currentCount++;
28426  mem5.currentOut += iFullSz;
28427  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
28428  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
28429#endif
28430
28431#ifdef SQLITE_DEBUG
28432  /* Make sure the allocated memory does not assume that it is set to zero
28433  ** or retains a value from a previous allocation */
28434  memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
28435#endif
28436
28437  /* Return a pointer to the allocated memory. */
28438  return (void*)&mem5.zPool[i*mem5.szAtom];
28439}
28440
28441/*
28442** Free an outstanding memory allocation.
28443*/
28444static void memsys5FreeUnsafe(void *pOld){
28445  u32 size, iLogsize;
28446  int iBlock;
28447
28448  /* Set iBlock to the index of the block pointed to by pOld in
28449  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
28450  */
28451  iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
28452
28453  /* Check that the pointer pOld points to a valid, non-free block. */
28454  assert( iBlock>=0 && iBlock<mem5.nBlock );
28455  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
28456  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
28457
28458  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
28459  size = 1<<iLogsize;
28460  assert( iBlock+size-1<(u32)mem5.nBlock );
28461
28462  mem5.aCtrl[iBlock] |= CTRL_FREE;
28463  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
28464
28465#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
28466  assert( mem5.currentCount>0 );
28467  assert( mem5.currentOut>=(size*mem5.szAtom) );
28468  mem5.currentCount--;
28469  mem5.currentOut -= size*mem5.szAtom;
28470  assert( mem5.currentOut>0 || mem5.currentCount==0 );
28471  assert( mem5.currentCount>0 || mem5.currentOut==0 );
28472#endif
28473
28474  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
28475  while( ALWAYS(iLogsize<LOGMAX) ){
28476    int iBuddy;
28477    if( (iBlock>>iLogsize) & 1 ){
28478      iBuddy = iBlock - size;
28479      assert( iBuddy>=0 );
28480    }else{
28481      iBuddy = iBlock + size;
28482      if( iBuddy>=mem5.nBlock ) break;
28483    }
28484    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
28485    memsys5Unlink(iBuddy, iLogsize);
28486    iLogsize++;
28487    if( iBuddy<iBlock ){
28488      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
28489      mem5.aCtrl[iBlock] = 0;
28490      iBlock = iBuddy;
28491    }else{
28492      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
28493      mem5.aCtrl[iBuddy] = 0;
28494    }
28495    size *= 2;
28496  }
28497
28498#ifdef SQLITE_DEBUG
28499  /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
28500  ** not used after being freed */
28501  memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
28502#endif
28503
28504  memsys5Link(iBlock, iLogsize);
28505}
28506
28507/*
28508** Allocate nBytes of memory.
28509*/
28510static void *memsys5Malloc(int nBytes){
28511  sqlite3_int64 *p = 0;
28512  if( nBytes>0 ){
28513    memsys5Enter();
28514    p = memsys5MallocUnsafe(nBytes);
28515    memsys5Leave();
28516  }
28517  return (void*)p;
28518}
28519
28520/*
28521** Free memory.
28522**
28523** The outer layer memory allocator prevents this routine from
28524** being called with pPrior==0.
28525*/
28526static void memsys5Free(void *pPrior){
28527  assert( pPrior!=0 );
28528  memsys5Enter();
28529  memsys5FreeUnsafe(pPrior);
28530  memsys5Leave();
28531}
28532
28533/*
28534** Change the size of an existing memory allocation.
28535**
28536** The outer layer memory allocator prevents this routine from
28537** being called with pPrior==0.
28538**
28539** nBytes is always a value obtained from a prior call to
28540** memsys5Round().  Hence nBytes is always a non-negative power
28541** of two.  If nBytes==0 that means that an oversize allocation
28542** (an allocation larger than 0x40000000) was requested and this
28543** routine should return 0 without freeing pPrior.
28544*/
28545static void *memsys5Realloc(void *pPrior, int nBytes){
28546  int nOld;
28547  void *p;
28548  assert( pPrior!=0 );
28549  assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
28550  assert( nBytes>=0 );
28551  if( nBytes==0 ){
28552    return 0;
28553  }
28554  nOld = memsys5Size(pPrior);
28555  if( nBytes<=nOld ){
28556    return pPrior;
28557  }
28558  p = memsys5Malloc(nBytes);
28559  if( p ){
28560    memcpy(p, pPrior, nOld);
28561    memsys5Free(pPrior);
28562  }
28563  return p;
28564}
28565
28566/*
28567** Round up a request size to the next valid allocation size.  If
28568** the allocation is too large to be handled by this allocation system,
28569** return 0.
28570**
28571** All allocations must be a power of two and must be expressed by a
28572** 32-bit signed integer.  Hence the largest allocation is 0x40000000
28573** or 1073741824 bytes.
28574*/
28575static int memsys5Roundup(int n){
28576  int iFullSz;
28577  if( n<=mem5.szAtom*2 ){
28578    if( n<=mem5.szAtom ) return mem5.szAtom;
28579    return mem5.szAtom*2;
28580  }
28581  if( n>0x10000000 ){
28582    if( n>0x40000000 ) return 0;
28583    if( n>0x20000000 ) return 0x40000000;
28584    return 0x20000000;
28585  }
28586  for(iFullSz=mem5.szAtom*8; iFullSz<n; iFullSz *= 4);
28587  if( (iFullSz/2)>=(i64)n ) return iFullSz/2;
28588  return iFullSz;
28589}
28590
28591/*
28592** Return the ceiling of the logarithm base 2 of iValue.
28593**
28594** Examples:   memsys5Log(1) -> 0
28595**             memsys5Log(2) -> 1
28596**             memsys5Log(4) -> 2
28597**             memsys5Log(5) -> 3
28598**             memsys5Log(8) -> 3
28599**             memsys5Log(9) -> 4
28600*/
28601static int memsys5Log(int iValue){
28602  int iLog;
28603  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
28604  return iLog;
28605}
28606
28607/*
28608** Initialize the memory allocator.
28609**
28610** This routine is not threadsafe.  The caller must be holding a mutex
28611** to prevent multiple threads from entering at the same time.
28612*/
28613static int memsys5Init(void *NotUsed){
28614  int ii;            /* Loop counter */
28615  int nByte;         /* Number of bytes of memory available to this allocator */
28616  u8 *zByte;         /* Memory usable by this allocator */
28617  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
28618  int iOffset;       /* An offset into mem5.aCtrl[] */
28619
28620  UNUSED_PARAMETER(NotUsed);
28621
28622  /* For the purposes of this routine, disable the mutex */
28623  mem5.mutex = 0;
28624
28625  /* The size of a Mem5Link object must be a power of two.  Verify that
28626  ** this is case.
28627  */
28628  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
28629
28630  nByte = sqlite3GlobalConfig.nHeap;
28631  zByte = (u8*)sqlite3GlobalConfig.pHeap;
28632  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
28633
28634  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
28635  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
28636  mem5.szAtom = (1<<nMinLog);
28637  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
28638    mem5.szAtom = mem5.szAtom << 1;
28639  }
28640
28641  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
28642  mem5.zPool = zByte;
28643  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
28644
28645  for(ii=0; ii<=LOGMAX; ii++){
28646    mem5.aiFreelist[ii] = -1;
28647  }
28648
28649  iOffset = 0;
28650  for(ii=LOGMAX; ii>=0; ii--){
28651    int nAlloc = (1<<ii);
28652    if( (iOffset+nAlloc)<=mem5.nBlock ){
28653      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
28654      memsys5Link(iOffset, ii);
28655      iOffset += nAlloc;
28656    }
28657    assert((iOffset+nAlloc)>mem5.nBlock);
28658  }
28659
28660  /* If a mutex is required for normal operation, allocate one */
28661  if( sqlite3GlobalConfig.bMemstat==0 ){
28662    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
28663  }
28664
28665  return SQLITE_OK;
28666}
28667
28668/*
28669** Deinitialize this module.
28670*/
28671static void memsys5Shutdown(void *NotUsed){
28672  UNUSED_PARAMETER(NotUsed);
28673  mem5.mutex = 0;
28674  return;
28675}
28676
28677#ifdef SQLITE_TEST
28678/*
28679** Open the file indicated and write a log of all unfreed memory
28680** allocations into that log.
28681*/
28682SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
28683  FILE *out;
28684  int i, j, n;
28685  int nMinLog;
28686
28687  if( zFilename==0 || zFilename[0]==0 ){
28688    out = stdout;
28689  }else{
28690    out = fopen(zFilename, "w");
28691    if( out==0 ){
28692      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
28693                      zFilename);
28694      return;
28695    }
28696  }
28697  memsys5Enter();
28698  nMinLog = memsys5Log(mem5.szAtom);
28699  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
28700    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
28701    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
28702  }
28703  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
28704  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
28705  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
28706  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
28707  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
28708  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
28709  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
28710  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
28711  memsys5Leave();
28712  if( out==stdout ){
28713    fflush(stdout);
28714  }else{
28715    fclose(out);
28716  }
28717}
28718#endif
28719
28720/*
28721** This routine is the only routine in this file with external
28722** linkage. It returns a pointer to a static sqlite3_mem_methods
28723** struct populated with the memsys5 methods.
28724*/
28725SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
28726  static const sqlite3_mem_methods memsys5Methods = {
28727     memsys5Malloc,
28728     memsys5Free,
28729     memsys5Realloc,
28730     memsys5Size,
28731     memsys5Roundup,
28732     memsys5Init,
28733     memsys5Shutdown,
28734     0
28735  };
28736  return &memsys5Methods;
28737}
28738
28739#endif /* SQLITE_ENABLE_MEMSYS5 */
28740
28741/************** End of mem5.c ************************************************/
28742/************** Begin file mutex.c *******************************************/
28743/*
28744** 2007 August 14
28745**
28746** The author disclaims copyright to this source code.  In place of
28747** a legal notice, here is a blessing:
28748**
28749**    May you do good and not evil.
28750**    May you find forgiveness for yourself and forgive others.
28751**    May you share freely, never taking more than you give.
28752**
28753*************************************************************************
28754** This file contains the C functions that implement mutexes.
28755**
28756** This file contains code that is common across all mutex implementations.
28757*/
28758/* #include "sqliteInt.h" */
28759
28760#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
28761/*
28762** For debugging purposes, record when the mutex subsystem is initialized
28763** and uninitialized so that we can assert() if there is an attempt to
28764** allocate a mutex while the system is uninitialized.
28765*/
28766static SQLITE_WSD int mutexIsInit = 0;
28767#endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
28768
28769
28770#ifndef SQLITE_MUTEX_OMIT
28771
28772#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
28773/*
28774** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains
28775** the implementation of a wrapper around the system default mutex
28776** implementation (sqlite3DefaultMutex()).
28777**
28778** Most calls are passed directly through to the underlying default
28779** mutex implementation. Except, if a mutex is configured by calling
28780** sqlite3MutexWarnOnContention() on it, then if contention is ever
28781** encountered within xMutexEnter() a warning is emitted via sqlite3_log().
28782**
28783** This type of mutex is used as the database handle mutex when testing
28784** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.
28785*/
28786
28787/*
28788** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS
28789** is defined. Variable CheckMutex.mutex is a pointer to the real mutex
28790** allocated by the system mutex implementation. Variable iType is usually set
28791** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
28792** or one of the static mutex identifiers. Or, if this is a recursive mutex
28793** that has been configured using sqlite3MutexWarnOnContention(), it is
28794** set to SQLITE_MUTEX_WARNONCONTENTION.
28795*/
28796typedef struct CheckMutex CheckMutex;
28797struct CheckMutex {
28798  int iType;
28799  sqlite3_mutex *mutex;
28800};
28801
28802#define SQLITE_MUTEX_WARNONCONTENTION  (-1)
28803
28804/*
28805** Pointer to real mutex methods object used by the CheckMutex
28806** implementation. Set by checkMutexInit().
28807*/
28808static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;
28809
28810#ifdef SQLITE_DEBUG
28811static int checkMutexHeld(sqlite3_mutex *p){
28812  return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);
28813}
28814static int checkMutexNotheld(sqlite3_mutex *p){
28815  return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
28816}
28817#endif
28818
28819/*
28820** Initialize and deinitialize the mutex subsystem.
28821*/
28822static int checkMutexInit(void){
28823  pGlobalMutexMethods = sqlite3DefaultMutex();
28824  return SQLITE_OK;
28825}
28826static int checkMutexEnd(void){
28827  pGlobalMutexMethods = 0;
28828  return SQLITE_OK;
28829}
28830
28831/*
28832** Allocate a mutex.
28833*/
28834static sqlite3_mutex *checkMutexAlloc(int iType){
28835  static CheckMutex staticMutexes[] = {
28836    {2, 0}, {3, 0}, {4, 0}, {5, 0},
28837    {6, 0}, {7, 0}, {8, 0}, {9, 0},
28838    {10, 0}, {11, 0}, {12, 0}, {13, 0}
28839  };
28840  CheckMutex *p = 0;
28841
28842  assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 );
28843  if( iType<2 ){
28844    p = sqlite3MallocZero(sizeof(CheckMutex));
28845    if( p==0 ) return 0;
28846    p->iType = iType;
28847  }else{
28848#ifdef SQLITE_ENABLE_API_ARMOR
28849    if( iType-2>=ArraySize(staticMutexes) ){
28850      (void)SQLITE_MISUSE_BKPT;
28851      return 0;
28852    }
28853#endif
28854    p = &staticMutexes[iType-2];
28855  }
28856
28857  if( p->mutex==0 ){
28858    p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);
28859    if( p->mutex==0 ){
28860      if( iType<2 ){
28861        sqlite3_free(p);
28862      }
28863      p = 0;
28864    }
28865  }
28866
28867  return (sqlite3_mutex*)p;
28868}
28869
28870/*
28871** Free a mutex.
28872*/
28873static void checkMutexFree(sqlite3_mutex *p){
28874  assert( SQLITE_MUTEX_RECURSIVE<2 );
28875  assert( SQLITE_MUTEX_FAST<2 );
28876  assert( SQLITE_MUTEX_WARNONCONTENTION<2 );
28877
28878#ifdef SQLITE_ENABLE_API_ARMOR
28879  if( ((CheckMutex*)p)->iType<2 )
28880#endif
28881  {
28882    CheckMutex *pCheck = (CheckMutex*)p;
28883    pGlobalMutexMethods->xMutexFree(pCheck->mutex);
28884    sqlite3_free(pCheck);
28885  }
28886#ifdef SQLITE_ENABLE_API_ARMOR
28887  else{
28888    (void)SQLITE_MISUSE_BKPT;
28889  }
28890#endif
28891}
28892
28893/*
28894** Enter the mutex.
28895*/
28896static void checkMutexEnter(sqlite3_mutex *p){
28897  CheckMutex *pCheck = (CheckMutex*)p;
28898  if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){
28899    if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
28900      return;
28901    }
28902    sqlite3_log(SQLITE_MISUSE,
28903        "illegal multi-threaded access to database connection"
28904    );
28905  }
28906  pGlobalMutexMethods->xMutexEnter(pCheck->mutex);
28907}
28908
28909/*
28910** Enter the mutex (do not block).
28911*/
28912static int checkMutexTry(sqlite3_mutex *p){
28913  CheckMutex *pCheck = (CheckMutex*)p;
28914  return pGlobalMutexMethods->xMutexTry(pCheck->mutex);
28915}
28916
28917/*
28918** Leave the mutex.
28919*/
28920static void checkMutexLeave(sqlite3_mutex *p){
28921  CheckMutex *pCheck = (CheckMutex*)p;
28922  pGlobalMutexMethods->xMutexLeave(pCheck->mutex);
28923}
28924
28925sqlite3_mutex_methods const *multiThreadedCheckMutex(void){
28926  static const sqlite3_mutex_methods sMutex = {
28927    checkMutexInit,
28928    checkMutexEnd,
28929    checkMutexAlloc,
28930    checkMutexFree,
28931    checkMutexEnter,
28932    checkMutexTry,
28933    checkMutexLeave,
28934#ifdef SQLITE_DEBUG
28935    checkMutexHeld,
28936    checkMutexNotheld
28937#else
28938    0,
28939    0
28940#endif
28941  };
28942  return &sMutex;
28943}
28944
28945/*
28946** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as
28947** one on which there should be no contention.
28948*/
28949SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){
28950  if( sqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){
28951    CheckMutex *pCheck = (CheckMutex*)p;
28952    assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );
28953    pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;
28954  }
28955}
28956#endif   /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */
28957
28958/*
28959** Initialize the mutex system.
28960*/
28961SQLITE_PRIVATE int sqlite3MutexInit(void){
28962  int rc = SQLITE_OK;
28963  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
28964    /* If the xMutexAlloc method has not been set, then the user did not
28965    ** install a mutex implementation via sqlite3_config() prior to
28966    ** sqlite3_initialize() being called. This block copies pointers to
28967    ** the default implementation into the sqlite3GlobalConfig structure.
28968    */
28969    sqlite3_mutex_methods const *pFrom;
28970    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
28971
28972    if( sqlite3GlobalConfig.bCoreMutex ){
28973#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
28974      pFrom = multiThreadedCheckMutex();
28975#else
28976      pFrom = sqlite3DefaultMutex();
28977#endif
28978    }else{
28979      pFrom = sqlite3NoopMutex();
28980    }
28981    pTo->xMutexInit = pFrom->xMutexInit;
28982    pTo->xMutexEnd = pFrom->xMutexEnd;
28983    pTo->xMutexFree = pFrom->xMutexFree;
28984    pTo->xMutexEnter = pFrom->xMutexEnter;
28985    pTo->xMutexTry = pFrom->xMutexTry;
28986    pTo->xMutexLeave = pFrom->xMutexLeave;
28987    pTo->xMutexHeld = pFrom->xMutexHeld;
28988    pTo->xMutexNotheld = pFrom->xMutexNotheld;
28989    sqlite3MemoryBarrier();
28990    pTo->xMutexAlloc = pFrom->xMutexAlloc;
28991  }
28992  assert( sqlite3GlobalConfig.mutex.xMutexInit );
28993  rc = sqlite3GlobalConfig.mutex.xMutexInit();
28994
28995#ifdef SQLITE_DEBUG
28996  GLOBAL(int, mutexIsInit) = 1;
28997#endif
28998
28999  sqlite3MemoryBarrier();
29000  return rc;
29001}
29002
29003/*
29004** Shutdown the mutex system. This call frees resources allocated by
29005** sqlite3MutexInit().
29006*/
29007SQLITE_PRIVATE int sqlite3MutexEnd(void){
29008  int rc = SQLITE_OK;
29009  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
29010    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
29011  }
29012
29013#ifdef SQLITE_DEBUG
29014  GLOBAL(int, mutexIsInit) = 0;
29015#endif
29016
29017  return rc;
29018}
29019
29020/*
29021** Retrieve a pointer to a static mutex or allocate a new dynamic one.
29022*/
29023SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
29024#ifndef SQLITE_OMIT_AUTOINIT
29025  if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
29026  if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
29027#endif
29028  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
29029  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
29030}
29031
29032SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
29033  if( !sqlite3GlobalConfig.bCoreMutex ){
29034    return 0;
29035  }
29036  assert( GLOBAL(int, mutexIsInit) );
29037  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
29038  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
29039}
29040
29041/*
29042** Free a dynamic mutex.
29043*/
29044SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
29045  if( p ){
29046    assert( sqlite3GlobalConfig.mutex.xMutexFree );
29047    sqlite3GlobalConfig.mutex.xMutexFree(p);
29048  }
29049}
29050
29051/*
29052** Obtain the mutex p. If some other thread already has the mutex, block
29053** until it can be obtained.
29054*/
29055SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
29056  if( p ){
29057    assert( sqlite3GlobalConfig.mutex.xMutexEnter );
29058    sqlite3GlobalConfig.mutex.xMutexEnter(p);
29059  }
29060}
29061
29062/*
29063** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
29064** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
29065*/
29066SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
29067  int rc = SQLITE_OK;
29068  if( p ){
29069    assert( sqlite3GlobalConfig.mutex.xMutexTry );
29070    return sqlite3GlobalConfig.mutex.xMutexTry(p);
29071  }
29072  return rc;
29073}
29074
29075/*
29076** The sqlite3_mutex_leave() routine exits a mutex that was previously
29077** entered by the same thread.  The behavior is undefined if the mutex
29078** is not currently entered. If a NULL pointer is passed as an argument
29079** this function is a no-op.
29080*/
29081SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
29082  if( p ){
29083    assert( sqlite3GlobalConfig.mutex.xMutexLeave );
29084    sqlite3GlobalConfig.mutex.xMutexLeave(p);
29085  }
29086}
29087
29088#ifndef NDEBUG
29089/*
29090** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
29091** intended for use inside assert() statements.
29092*/
29093SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
29094  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
29095  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
29096}
29097SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
29098  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
29099  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
29100}
29101#endif
29102
29103#endif /* !defined(SQLITE_MUTEX_OMIT) */
29104
29105/************** End of mutex.c ***********************************************/
29106/************** Begin file mutex_noop.c **************************************/
29107/*
29108** 2008 October 07
29109**
29110** The author disclaims copyright to this source code.  In place of
29111** a legal notice, here is a blessing:
29112**
29113**    May you do good and not evil.
29114**    May you find forgiveness for yourself and forgive others.
29115**    May you share freely, never taking more than you give.
29116**
29117*************************************************************************
29118** This file contains the C functions that implement mutexes.
29119**
29120** This implementation in this file does not provide any mutual
29121** exclusion and is thus suitable for use only in applications
29122** that use SQLite in a single thread.  The routines defined
29123** here are place-holders.  Applications can substitute working
29124** mutex routines at start-time using the
29125**
29126**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
29127**
29128** interface.
29129**
29130** If compiled with SQLITE_DEBUG, then additional logic is inserted
29131** that does error checking on mutexes to make sure they are being
29132** called correctly.
29133*/
29134/* #include "sqliteInt.h" */
29135
29136#ifndef SQLITE_MUTEX_OMIT
29137
29138#ifndef SQLITE_DEBUG
29139/*
29140** Stub routines for all mutex methods.
29141**
29142** This routines provide no mutual exclusion or error checking.
29143*/
29144static int noopMutexInit(void){ return SQLITE_OK; }
29145static int noopMutexEnd(void){ return SQLITE_OK; }
29146static sqlite3_mutex *noopMutexAlloc(int id){
29147  UNUSED_PARAMETER(id);
29148  return (sqlite3_mutex*)8;
29149}
29150static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
29151static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
29152static int noopMutexTry(sqlite3_mutex *p){
29153  UNUSED_PARAMETER(p);
29154  return SQLITE_OK;
29155}
29156static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
29157
29158SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
29159  static const sqlite3_mutex_methods sMutex = {
29160    noopMutexInit,
29161    noopMutexEnd,
29162    noopMutexAlloc,
29163    noopMutexFree,
29164    noopMutexEnter,
29165    noopMutexTry,
29166    noopMutexLeave,
29167
29168    0,
29169    0,
29170  };
29171
29172  return &sMutex;
29173}
29174#endif /* !SQLITE_DEBUG */
29175
29176#ifdef SQLITE_DEBUG
29177/*
29178** In this implementation, error checking is provided for testing
29179** and debugging purposes.  The mutexes still do not provide any
29180** mutual exclusion.
29181*/
29182
29183/*
29184** The mutex object
29185*/
29186typedef struct sqlite3_debug_mutex {
29187  int id;     /* The mutex type */
29188  int cnt;    /* Number of entries without a matching leave */
29189} sqlite3_debug_mutex;
29190
29191/*
29192** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
29193** intended for use inside assert() statements.
29194*/
29195static int debugMutexHeld(sqlite3_mutex *pX){
29196  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
29197  return p==0 || p->cnt>0;
29198}
29199static int debugMutexNotheld(sqlite3_mutex *pX){
29200  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
29201  return p==0 || p->cnt==0;
29202}
29203
29204/*
29205** Initialize and deinitialize the mutex subsystem.
29206*/
29207static int debugMutexInit(void){ return SQLITE_OK; }
29208static int debugMutexEnd(void){ return SQLITE_OK; }
29209
29210/*
29211** The sqlite3_mutex_alloc() routine allocates a new
29212** mutex and returns a pointer to it.  If it returns NULL
29213** that means that a mutex could not be allocated.
29214*/
29215static sqlite3_mutex *debugMutexAlloc(int id){
29216  static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
29217  sqlite3_debug_mutex *pNew = 0;
29218  switch( id ){
29219    case SQLITE_MUTEX_FAST:
29220    case SQLITE_MUTEX_RECURSIVE: {
29221      pNew = sqlite3Malloc(sizeof(*pNew));
29222      if( pNew ){
29223        pNew->id = id;
29224        pNew->cnt = 0;
29225      }
29226      break;
29227    }
29228    default: {
29229#ifdef SQLITE_ENABLE_API_ARMOR
29230      if( id-2<0 || id-2>=ArraySize(aStatic) ){
29231        (void)SQLITE_MISUSE_BKPT;
29232        return 0;
29233      }
29234#endif
29235      pNew = &aStatic[id-2];
29236      pNew->id = id;
29237      break;
29238    }
29239  }
29240  return (sqlite3_mutex*)pNew;
29241}
29242
29243/*
29244** This routine deallocates a previously allocated mutex.
29245*/
29246static void debugMutexFree(sqlite3_mutex *pX){
29247  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
29248  assert( p->cnt==0 );
29249  if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
29250    sqlite3_free(p);
29251  }else{
29252#ifdef SQLITE_ENABLE_API_ARMOR
29253    (void)SQLITE_MISUSE_BKPT;
29254#endif
29255  }
29256}
29257
29258/*
29259** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
29260** to enter a mutex.  If another thread is already within the mutex,
29261** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
29262** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
29263** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
29264** be entered multiple times by the same thread.  In such cases the,
29265** mutex must be exited an equal number of times before another thread
29266** can enter.  If the same thread tries to enter any other kind of mutex
29267** more than once, the behavior is undefined.
29268*/
29269static void debugMutexEnter(sqlite3_mutex *pX){
29270  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
29271  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
29272  p->cnt++;
29273}
29274static int debugMutexTry(sqlite3_mutex *pX){
29275  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
29276  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
29277  p->cnt++;
29278  return SQLITE_OK;
29279}
29280
29281/*
29282** The sqlite3_mutex_leave() routine exits a mutex that was
29283** previously entered by the same thread.  The behavior
29284** is undefined if the mutex is not currently entered or
29285** is not currently allocated.  SQLite will never do either.
29286*/
29287static void debugMutexLeave(sqlite3_mutex *pX){
29288  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
29289  assert( debugMutexHeld(pX) );
29290  p->cnt--;
29291  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
29292}
29293
29294SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
29295  static const sqlite3_mutex_methods sMutex = {
29296    debugMutexInit,
29297    debugMutexEnd,
29298    debugMutexAlloc,
29299    debugMutexFree,
29300    debugMutexEnter,
29301    debugMutexTry,
29302    debugMutexLeave,
29303
29304    debugMutexHeld,
29305    debugMutexNotheld
29306  };
29307
29308  return &sMutex;
29309}
29310#endif /* SQLITE_DEBUG */
29311
29312/*
29313** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
29314** is used regardless of the run-time threadsafety setting.
29315*/
29316#ifdef SQLITE_MUTEX_NOOP
29317SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
29318  return sqlite3NoopMutex();
29319}
29320#endif /* defined(SQLITE_MUTEX_NOOP) */
29321#endif /* !defined(SQLITE_MUTEX_OMIT) */
29322
29323/************** End of mutex_noop.c ******************************************/
29324/************** Begin file mutex_unix.c **************************************/
29325/*
29326** 2007 August 28
29327**
29328** The author disclaims copyright to this source code.  In place of
29329** a legal notice, here is a blessing:
29330**
29331**    May you do good and not evil.
29332**    May you find forgiveness for yourself and forgive others.
29333**    May you share freely, never taking more than you give.
29334**
29335*************************************************************************
29336** This file contains the C functions that implement mutexes for pthreads
29337*/
29338/* #include "sqliteInt.h" */
29339
29340/*
29341** The code in this file is only used if we are compiling threadsafe
29342** under unix with pthreads.
29343**
29344** Note that this implementation requires a version of pthreads that
29345** supports recursive mutexes.
29346*/
29347#ifdef SQLITE_MUTEX_PTHREADS
29348
29349#include <pthread.h>
29350
29351/*
29352** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
29353** are necessary under two conditions:  (1) Debug builds and (2) using
29354** home-grown mutexes.  Encapsulate these conditions into a single #define.
29355*/
29356#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
29357# define SQLITE_MUTEX_NREF 1
29358#else
29359# define SQLITE_MUTEX_NREF 0
29360#endif
29361
29362/*
29363** Each recursive mutex is an instance of the following structure.
29364*/
29365struct sqlite3_mutex {
29366  pthread_mutex_t mutex;     /* Mutex controlling the lock */
29367#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
29368  int id;                    /* Mutex type */
29369#endif
29370#if SQLITE_MUTEX_NREF
29371  volatile int nRef;         /* Number of entrances */
29372  volatile pthread_t owner;  /* Thread that is within this mutex */
29373  int trace;                 /* True to trace changes */
29374#endif
29375};
29376#if SQLITE_MUTEX_NREF
29377# define SQLITE3_MUTEX_INITIALIZER(id) \
29378     {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0}
29379#elif defined(SQLITE_ENABLE_API_ARMOR)
29380# define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id }
29381#else
29382#define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER }
29383#endif
29384
29385/*
29386** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
29387** intended for use only inside assert() statements.  On some platforms,
29388** there might be race conditions that can cause these routines to
29389** deliver incorrect results.  In particular, if pthread_equal() is
29390** not an atomic operation, then these routines might delivery
29391** incorrect results.  On most platforms, pthread_equal() is a
29392** comparison of two integers and is therefore atomic.  But we are
29393** told that HPUX is not such a platform.  If so, then these routines
29394** will not always work correctly on HPUX.
29395**
29396** On those platforms where pthread_equal() is not atomic, SQLite
29397** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
29398** make sure no assert() statements are evaluated and hence these
29399** routines are never called.
29400*/
29401#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
29402static int pthreadMutexHeld(sqlite3_mutex *p){
29403  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
29404}
29405static int pthreadMutexNotheld(sqlite3_mutex *p){
29406  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
29407}
29408#endif
29409
29410/*
29411** Try to provide a memory barrier operation, needed for initialization
29412** and also for the implementation of xShmBarrier in the VFS in cases
29413** where SQLite is compiled without mutexes.
29414*/
29415SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
29416#if defined(SQLITE_MEMORY_BARRIER)
29417  SQLITE_MEMORY_BARRIER;
29418#elif defined(__GNUC__) && GCC_VERSION>=4001000
29419  __sync_synchronize();
29420#endif
29421}
29422
29423/*
29424** Initialize and deinitialize the mutex subsystem.
29425*/
29426static int pthreadMutexInit(void){ return SQLITE_OK; }
29427static int pthreadMutexEnd(void){ return SQLITE_OK; }
29428
29429/*
29430** The sqlite3_mutex_alloc() routine allocates a new
29431** mutex and returns a pointer to it.  If it returns NULL
29432** that means that a mutex could not be allocated.  SQLite
29433** will unwind its stack and return an error.  The argument
29434** to sqlite3_mutex_alloc() is one of these integer constants:
29435**
29436** <ul>
29437** <li>  SQLITE_MUTEX_FAST
29438** <li>  SQLITE_MUTEX_RECURSIVE
29439** <li>  SQLITE_MUTEX_STATIC_MAIN
29440** <li>  SQLITE_MUTEX_STATIC_MEM
29441** <li>  SQLITE_MUTEX_STATIC_OPEN
29442** <li>  SQLITE_MUTEX_STATIC_PRNG
29443** <li>  SQLITE_MUTEX_STATIC_LRU
29444** <li>  SQLITE_MUTEX_STATIC_PMEM
29445** <li>  SQLITE_MUTEX_STATIC_APP1
29446** <li>  SQLITE_MUTEX_STATIC_APP2
29447** <li>  SQLITE_MUTEX_STATIC_APP3
29448** <li>  SQLITE_MUTEX_STATIC_VFS1
29449** <li>  SQLITE_MUTEX_STATIC_VFS2
29450** <li>  SQLITE_MUTEX_STATIC_VFS3
29451** </ul>
29452**
29453** The first two constants cause sqlite3_mutex_alloc() to create
29454** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
29455** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
29456** The mutex implementation does not need to make a distinction
29457** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
29458** not want to.  But SQLite will only request a recursive mutex in
29459** cases where it really needs one.  If a faster non-recursive mutex
29460** implementation is available on the host platform, the mutex subsystem
29461** might return such a mutex in response to SQLITE_MUTEX_FAST.
29462**
29463** The other allowed parameters to sqlite3_mutex_alloc() each return
29464** a pointer to a static preexisting mutex.  Six static mutexes are
29465** used by the current version of SQLite.  Future versions of SQLite
29466** may add additional static mutexes.  Static mutexes are for internal
29467** use by SQLite only.  Applications that use SQLite mutexes should
29468** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
29469** SQLITE_MUTEX_RECURSIVE.
29470**
29471** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
29472** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
29473** returns a different mutex on every call.  But for the static
29474** mutex types, the same mutex is returned on every call that has
29475** the same type number.
29476*/
29477static sqlite3_mutex *pthreadMutexAlloc(int iType){
29478  static sqlite3_mutex staticMutexes[] = {
29479    SQLITE3_MUTEX_INITIALIZER(2),
29480    SQLITE3_MUTEX_INITIALIZER(3),
29481    SQLITE3_MUTEX_INITIALIZER(4),
29482    SQLITE3_MUTEX_INITIALIZER(5),
29483    SQLITE3_MUTEX_INITIALIZER(6),
29484    SQLITE3_MUTEX_INITIALIZER(7),
29485    SQLITE3_MUTEX_INITIALIZER(8),
29486    SQLITE3_MUTEX_INITIALIZER(9),
29487    SQLITE3_MUTEX_INITIALIZER(10),
29488    SQLITE3_MUTEX_INITIALIZER(11),
29489    SQLITE3_MUTEX_INITIALIZER(12),
29490    SQLITE3_MUTEX_INITIALIZER(13)
29491  };
29492  sqlite3_mutex *p;
29493  switch( iType ){
29494    case SQLITE_MUTEX_RECURSIVE: {
29495      p = sqlite3MallocZero( sizeof(*p) );
29496      if( p ){
29497#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
29498        /* If recursive mutexes are not available, we will have to
29499        ** build our own.  See below. */
29500        pthread_mutex_init(&p->mutex, 0);
29501#else
29502        /* Use a recursive mutex if it is available */
29503        pthread_mutexattr_t recursiveAttr;
29504        pthread_mutexattr_init(&recursiveAttr);
29505        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
29506        pthread_mutex_init(&p->mutex, &recursiveAttr);
29507        pthread_mutexattr_destroy(&recursiveAttr);
29508#endif
29509#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
29510        p->id = SQLITE_MUTEX_RECURSIVE;
29511#endif
29512      }
29513      break;
29514    }
29515    case SQLITE_MUTEX_FAST: {
29516      p = sqlite3MallocZero( sizeof(*p) );
29517      if( p ){
29518        pthread_mutex_init(&p->mutex, 0);
29519#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
29520        p->id = SQLITE_MUTEX_FAST;
29521#endif
29522      }
29523      break;
29524    }
29525    default: {
29526#ifdef SQLITE_ENABLE_API_ARMOR
29527      if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
29528        (void)SQLITE_MISUSE_BKPT;
29529        return 0;
29530      }
29531#endif
29532      p = &staticMutexes[iType-2];
29533      break;
29534    }
29535  }
29536#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
29537  assert( p==0 || p->id==iType );
29538#endif
29539  return p;
29540}
29541
29542
29543/*
29544** This routine deallocates a previously
29545** allocated mutex.  SQLite is careful to deallocate every
29546** mutex that it allocates.
29547*/
29548static void pthreadMutexFree(sqlite3_mutex *p){
29549  assert( p->nRef==0 );
29550#ifdef SQLITE_ENABLE_API_ARMOR
29551  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
29552#endif
29553  {
29554    pthread_mutex_destroy(&p->mutex);
29555    sqlite3_free(p);
29556  }
29557#ifdef SQLITE_ENABLE_API_ARMOR
29558  else{
29559    (void)SQLITE_MISUSE_BKPT;
29560  }
29561#endif
29562}
29563
29564/*
29565** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
29566** to enter a mutex.  If another thread is already within the mutex,
29567** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
29568** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
29569** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
29570** be entered multiple times by the same thread.  In such cases the,
29571** mutex must be exited an equal number of times before another thread
29572** can enter.  If the same thread tries to enter any other kind of mutex
29573** more than once, the behavior is undefined.
29574*/
29575static void pthreadMutexEnter(sqlite3_mutex *p){
29576  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
29577
29578#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
29579  /* If recursive mutexes are not available, then we have to grow
29580  ** our own.  This implementation assumes that pthread_equal()
29581  ** is atomic - that it cannot be deceived into thinking self
29582  ** and p->owner are equal if p->owner changes between two values
29583  ** that are not equal to self while the comparison is taking place.
29584  ** This implementation also assumes a coherent cache - that
29585  ** separate processes cannot read different values from the same
29586  ** address at the same time.  If either of these two conditions
29587  ** are not met, then the mutexes will fail and problems will result.
29588  */
29589  {
29590    pthread_t self = pthread_self();
29591    if( p->nRef>0 && pthread_equal(p->owner, self) ){
29592      p->nRef++;
29593    }else{
29594      pthread_mutex_lock(&p->mutex);
29595      assert( p->nRef==0 );
29596      p->owner = self;
29597      p->nRef = 1;
29598    }
29599  }
29600#else
29601  /* Use the built-in recursive mutexes if they are available.
29602  */
29603  pthread_mutex_lock(&p->mutex);
29604#if SQLITE_MUTEX_NREF
29605  assert( p->nRef>0 || p->owner==0 );
29606  p->owner = pthread_self();
29607  p->nRef++;
29608#endif
29609#endif
29610
29611#ifdef SQLITE_DEBUG
29612  if( p->trace ){
29613    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
29614  }
29615#endif
29616}
29617static int pthreadMutexTry(sqlite3_mutex *p){
29618  int rc;
29619  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
29620
29621#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
29622  /* If recursive mutexes are not available, then we have to grow
29623  ** our own.  This implementation assumes that pthread_equal()
29624  ** is atomic - that it cannot be deceived into thinking self
29625  ** and p->owner are equal if p->owner changes between two values
29626  ** that are not equal to self while the comparison is taking place.
29627  ** This implementation also assumes a coherent cache - that
29628  ** separate processes cannot read different values from the same
29629  ** address at the same time.  If either of these two conditions
29630  ** are not met, then the mutexes will fail and problems will result.
29631  */
29632  {
29633    pthread_t self = pthread_self();
29634    if( p->nRef>0 && pthread_equal(p->owner, self) ){
29635      p->nRef++;
29636      rc = SQLITE_OK;
29637    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
29638      assert( p->nRef==0 );
29639      p->owner = self;
29640      p->nRef = 1;
29641      rc = SQLITE_OK;
29642    }else{
29643      rc = SQLITE_BUSY;
29644    }
29645  }
29646#else
29647  /* Use the built-in recursive mutexes if they are available.
29648  */
29649  if( pthread_mutex_trylock(&p->mutex)==0 ){
29650#if SQLITE_MUTEX_NREF
29651    p->owner = pthread_self();
29652    p->nRef++;
29653#endif
29654    rc = SQLITE_OK;
29655  }else{
29656    rc = SQLITE_BUSY;
29657  }
29658#endif
29659
29660#ifdef SQLITE_DEBUG
29661  if( rc==SQLITE_OK && p->trace ){
29662    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
29663  }
29664#endif
29665  return rc;
29666}
29667
29668/*
29669** The sqlite3_mutex_leave() routine exits a mutex that was
29670** previously entered by the same thread.  The behavior
29671** is undefined if the mutex is not currently entered or
29672** is not currently allocated.  SQLite will never do either.
29673*/
29674static void pthreadMutexLeave(sqlite3_mutex *p){
29675  assert( pthreadMutexHeld(p) );
29676#if SQLITE_MUTEX_NREF
29677  p->nRef--;
29678  if( p->nRef==0 ) p->owner = 0;
29679#endif
29680  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
29681
29682#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
29683  if( p->nRef==0 ){
29684    pthread_mutex_unlock(&p->mutex);
29685  }
29686#else
29687  pthread_mutex_unlock(&p->mutex);
29688#endif
29689
29690#ifdef SQLITE_DEBUG
29691  if( p->trace ){
29692    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
29693  }
29694#endif
29695}
29696
29697SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
29698  static const sqlite3_mutex_methods sMutex = {
29699    pthreadMutexInit,
29700    pthreadMutexEnd,
29701    pthreadMutexAlloc,
29702    pthreadMutexFree,
29703    pthreadMutexEnter,
29704    pthreadMutexTry,
29705    pthreadMutexLeave,
29706#ifdef SQLITE_DEBUG
29707    pthreadMutexHeld,
29708    pthreadMutexNotheld
29709#else
29710    0,
29711    0
29712#endif
29713  };
29714
29715  return &sMutex;
29716}
29717
29718#endif /* SQLITE_MUTEX_PTHREADS */
29719
29720/************** End of mutex_unix.c ******************************************/
29721/************** Begin file mutex_w32.c ***************************************/
29722/*
29723** 2007 August 14
29724**
29725** The author disclaims copyright to this source code.  In place of
29726** a legal notice, here is a blessing:
29727**
29728**    May you do good and not evil.
29729**    May you find forgiveness for yourself and forgive others.
29730**    May you share freely, never taking more than you give.
29731**
29732*************************************************************************
29733** This file contains the C functions that implement mutexes for Win32.
29734*/
29735/* #include "sqliteInt.h" */
29736
29737#if SQLITE_OS_WIN
29738/*
29739** Include code that is common to all os_*.c files
29740*/
29741/* #include "os_common.h" */
29742
29743/*
29744** Include the header file for the Windows VFS.
29745*/
29746/************** Include os_win.h in the middle of mutex_w32.c ****************/
29747/************** Begin file os_win.h ******************************************/
29748/*
29749** 2013 November 25
29750**
29751** The author disclaims copyright to this source code.  In place of
29752** a legal notice, here is a blessing:
29753**
29754**    May you do good and not evil.
29755**    May you find forgiveness for yourself and forgive others.
29756**    May you share freely, never taking more than you give.
29757**
29758******************************************************************************
29759**
29760** This file contains code that is specific to Windows.
29761*/
29762#ifndef SQLITE_OS_WIN_H
29763#define SQLITE_OS_WIN_H
29764
29765/*
29766** Include the primary Windows SDK header file.
29767*/
29768#include "windows.h"
29769
29770#ifdef __CYGWIN__
29771# include <sys/cygwin.h>
29772# include <errno.h> /* amalgamator: dontcache */
29773#endif
29774
29775/*
29776** Determine if we are dealing with Windows NT.
29777**
29778** We ought to be able to determine if we are compiling for Windows 9x or
29779** Windows NT using the _WIN32_WINNT macro as follows:
29780**
29781** #if defined(_WIN32_WINNT)
29782** # define SQLITE_OS_WINNT 1
29783** #else
29784** # define SQLITE_OS_WINNT 0
29785** #endif
29786**
29787** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
29788** it ought to, so the above test does not work.  We'll just assume that
29789** everything is Windows NT unless the programmer explicitly says otherwise
29790** by setting SQLITE_OS_WINNT to 0.
29791*/
29792#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
29793# define SQLITE_OS_WINNT 1
29794#endif
29795
29796/*
29797** Determine if we are dealing with Windows CE - which has a much reduced
29798** API.
29799*/
29800#if defined(_WIN32_WCE)
29801# define SQLITE_OS_WINCE 1
29802#else
29803# define SQLITE_OS_WINCE 0
29804#endif
29805
29806/*
29807** Determine if we are dealing with WinRT, which provides only a subset of
29808** the full Win32 API.
29809*/
29810#if !defined(SQLITE_OS_WINRT)
29811# define SQLITE_OS_WINRT 0
29812#endif
29813
29814/*
29815** For WinCE, some API function parameters do not appear to be declared as
29816** volatile.
29817*/
29818#if SQLITE_OS_WINCE
29819# define SQLITE_WIN32_VOLATILE
29820#else
29821# define SQLITE_WIN32_VOLATILE volatile
29822#endif
29823
29824/*
29825** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
29826** functions are not available (e.g. those not using MSVC, Cygwin, etc).
29827*/
29828#if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
29829    SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
29830# define SQLITE_OS_WIN_THREADS 1
29831#else
29832# define SQLITE_OS_WIN_THREADS 0
29833#endif
29834
29835#endif /* SQLITE_OS_WIN_H */
29836
29837/************** End of os_win.h **********************************************/
29838/************** Continuing where we left off in mutex_w32.c ******************/
29839#endif
29840
29841/*
29842** The code in this file is only used if we are compiling multithreaded
29843** on a Win32 system.
29844*/
29845#ifdef SQLITE_MUTEX_W32
29846
29847/*
29848** Each recursive mutex is an instance of the following structure.
29849*/
29850struct sqlite3_mutex {
29851  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
29852  int id;                    /* Mutex type */
29853#ifdef SQLITE_DEBUG
29854  volatile int nRef;         /* Number of entrances */
29855  volatile DWORD owner;      /* Thread holding this mutex */
29856  volatile LONG trace;       /* True to trace changes */
29857#endif
29858};
29859
29860/*
29861** These are the initializer values used when declaring a "static" mutex
29862** on Win32.  It should be noted that all mutexes require initialization
29863** on the Win32 platform.
29864*/
29865#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
29866
29867#ifdef SQLITE_DEBUG
29868#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \
29869                                    0L, (DWORD)0, 0 }
29870#else
29871#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id }
29872#endif
29873
29874#ifdef SQLITE_DEBUG
29875/*
29876** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
29877** intended for use only inside assert() statements.
29878*/
29879static int winMutexHeld(sqlite3_mutex *p){
29880  return p->nRef!=0 && p->owner==GetCurrentThreadId();
29881}
29882
29883static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
29884  return p->nRef==0 || p->owner!=tid;
29885}
29886
29887static int winMutexNotheld(sqlite3_mutex *p){
29888  DWORD tid = GetCurrentThreadId();
29889  return winMutexNotheld2(p, tid);
29890}
29891#endif
29892
29893/*
29894** Try to provide a memory barrier operation, needed for initialization
29895** and also for the xShmBarrier method of the VFS in cases when SQLite is
29896** compiled without mutexes (SQLITE_THREADSAFE=0).
29897*/
29898SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
29899#if defined(SQLITE_MEMORY_BARRIER)
29900  SQLITE_MEMORY_BARRIER;
29901#elif defined(__GNUC__)
29902  __sync_synchronize();
29903#elif MSVC_VERSION>=1400
29904  _ReadWriteBarrier();
29905#elif defined(MemoryBarrier)
29906  MemoryBarrier();
29907#endif
29908}
29909
29910/*
29911** Initialize and deinitialize the mutex subsystem.
29912*/
29913static sqlite3_mutex winMutex_staticMutexes[] = {
29914  SQLITE3_MUTEX_INITIALIZER(2),
29915  SQLITE3_MUTEX_INITIALIZER(3),
29916  SQLITE3_MUTEX_INITIALIZER(4),
29917  SQLITE3_MUTEX_INITIALIZER(5),
29918  SQLITE3_MUTEX_INITIALIZER(6),
29919  SQLITE3_MUTEX_INITIALIZER(7),
29920  SQLITE3_MUTEX_INITIALIZER(8),
29921  SQLITE3_MUTEX_INITIALIZER(9),
29922  SQLITE3_MUTEX_INITIALIZER(10),
29923  SQLITE3_MUTEX_INITIALIZER(11),
29924  SQLITE3_MUTEX_INITIALIZER(12),
29925  SQLITE3_MUTEX_INITIALIZER(13)
29926};
29927
29928static int winMutex_isInit = 0;
29929static int winMutex_isNt = -1; /* <0 means "need to query" */
29930
29931/* As the winMutexInit() and winMutexEnd() functions are called as part
29932** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
29933** "interlocked" magic used here is probably not strictly necessary.
29934*/
29935static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
29936
29937SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
29938SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
29939
29940static int winMutexInit(void){
29941  /* The first to increment to 1 does actual initialization */
29942  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
29943    int i;
29944    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
29945#if SQLITE_OS_WINRT
29946      InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
29947#else
29948      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
29949#endif
29950    }
29951    winMutex_isInit = 1;
29952  }else{
29953    /* Another thread is (in the process of) initializing the static
29954    ** mutexes */
29955    while( !winMutex_isInit ){
29956      sqlite3_win32_sleep(1);
29957    }
29958  }
29959  return SQLITE_OK;
29960}
29961
29962static int winMutexEnd(void){
29963  /* The first to decrement to 0 does actual shutdown
29964  ** (which should be the last to shutdown.) */
29965  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
29966    if( winMutex_isInit==1 ){
29967      int i;
29968      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
29969        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
29970      }
29971      winMutex_isInit = 0;
29972    }
29973  }
29974  return SQLITE_OK;
29975}
29976
29977/*
29978** The sqlite3_mutex_alloc() routine allocates a new
29979** mutex and returns a pointer to it.  If it returns NULL
29980** that means that a mutex could not be allocated.  SQLite
29981** will unwind its stack and return an error.  The argument
29982** to sqlite3_mutex_alloc() is one of these integer constants:
29983**
29984** <ul>
29985** <li>  SQLITE_MUTEX_FAST
29986** <li>  SQLITE_MUTEX_RECURSIVE
29987** <li>  SQLITE_MUTEX_STATIC_MAIN
29988** <li>  SQLITE_MUTEX_STATIC_MEM
29989** <li>  SQLITE_MUTEX_STATIC_OPEN
29990** <li>  SQLITE_MUTEX_STATIC_PRNG
29991** <li>  SQLITE_MUTEX_STATIC_LRU
29992** <li>  SQLITE_MUTEX_STATIC_PMEM
29993** <li>  SQLITE_MUTEX_STATIC_APP1
29994** <li>  SQLITE_MUTEX_STATIC_APP2
29995** <li>  SQLITE_MUTEX_STATIC_APP3
29996** <li>  SQLITE_MUTEX_STATIC_VFS1
29997** <li>  SQLITE_MUTEX_STATIC_VFS2
29998** <li>  SQLITE_MUTEX_STATIC_VFS3
29999** </ul>
30000**
30001** The first two constants cause sqlite3_mutex_alloc() to create
30002** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
30003** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
30004** The mutex implementation does not need to make a distinction
30005** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
30006** not want to.  But SQLite will only request a recursive mutex in
30007** cases where it really needs one.  If a faster non-recursive mutex
30008** implementation is available on the host platform, the mutex subsystem
30009** might return such a mutex in response to SQLITE_MUTEX_FAST.
30010**
30011** The other allowed parameters to sqlite3_mutex_alloc() each return
30012** a pointer to a static preexisting mutex.  Six static mutexes are
30013** used by the current version of SQLite.  Future versions of SQLite
30014** may add additional static mutexes.  Static mutexes are for internal
30015** use by SQLite only.  Applications that use SQLite mutexes should
30016** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
30017** SQLITE_MUTEX_RECURSIVE.
30018**
30019** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
30020** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
30021** returns a different mutex on every call.  But for the static
30022** mutex types, the same mutex is returned on every call that has
30023** the same type number.
30024*/
30025static sqlite3_mutex *winMutexAlloc(int iType){
30026  sqlite3_mutex *p;
30027
30028  switch( iType ){
30029    case SQLITE_MUTEX_FAST:
30030    case SQLITE_MUTEX_RECURSIVE: {
30031      p = sqlite3MallocZero( sizeof(*p) );
30032      if( p ){
30033        p->id = iType;
30034#ifdef SQLITE_DEBUG
30035#ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
30036        p->trace = 1;
30037#endif
30038#endif
30039#if SQLITE_OS_WINRT
30040        InitializeCriticalSectionEx(&p->mutex, 0, 0);
30041#else
30042        InitializeCriticalSection(&p->mutex);
30043#endif
30044      }
30045      break;
30046    }
30047    default: {
30048#ifdef SQLITE_ENABLE_API_ARMOR
30049      if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
30050        (void)SQLITE_MISUSE_BKPT;
30051        return 0;
30052      }
30053#endif
30054      p = &winMutex_staticMutexes[iType-2];
30055#ifdef SQLITE_DEBUG
30056#ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
30057      InterlockedCompareExchange(&p->trace, 1, 0);
30058#endif
30059#endif
30060      break;
30061    }
30062  }
30063  assert( p==0 || p->id==iType );
30064  return p;
30065}
30066
30067
30068/*
30069** This routine deallocates a previously
30070** allocated mutex.  SQLite is careful to deallocate every
30071** mutex that it allocates.
30072*/
30073static void winMutexFree(sqlite3_mutex *p){
30074  assert( p );
30075  assert( p->nRef==0 && p->owner==0 );
30076  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
30077    DeleteCriticalSection(&p->mutex);
30078    sqlite3_free(p);
30079  }else{
30080#ifdef SQLITE_ENABLE_API_ARMOR
30081    (void)SQLITE_MISUSE_BKPT;
30082#endif
30083  }
30084}
30085
30086/*
30087** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
30088** to enter a mutex.  If another thread is already within the mutex,
30089** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
30090** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
30091** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
30092** be entered multiple times by the same thread.  In such cases the,
30093** mutex must be exited an equal number of times before another thread
30094** can enter.  If the same thread tries to enter any other kind of mutex
30095** more than once, the behavior is undefined.
30096*/
30097static void winMutexEnter(sqlite3_mutex *p){
30098#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
30099  DWORD tid = GetCurrentThreadId();
30100#endif
30101#ifdef SQLITE_DEBUG
30102  assert( p );
30103  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
30104#else
30105  assert( p );
30106#endif
30107  assert( winMutex_isInit==1 );
30108  EnterCriticalSection(&p->mutex);
30109#ifdef SQLITE_DEBUG
30110  assert( p->nRef>0 || p->owner==0 );
30111  p->owner = tid;
30112  p->nRef++;
30113  if( p->trace ){
30114    OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
30115             tid, p->id, p, p->trace, p->nRef));
30116  }
30117#endif
30118}
30119
30120static int winMutexTry(sqlite3_mutex *p){
30121#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
30122  DWORD tid = GetCurrentThreadId();
30123#endif
30124  int rc = SQLITE_BUSY;
30125  assert( p );
30126  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
30127  /*
30128  ** The sqlite3_mutex_try() routine is very rarely used, and when it
30129  ** is used it is merely an optimization.  So it is OK for it to always
30130  ** fail.
30131  **
30132  ** The TryEnterCriticalSection() interface is only available on WinNT.
30133  ** And some windows compilers complain if you try to use it without
30134  ** first doing some #defines that prevent SQLite from building on Win98.
30135  ** For that reason, we will omit this optimization for now.  See
30136  ** ticket #2685.
30137  */
30138#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
30139  assert( winMutex_isInit==1 );
30140  assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
30141  if( winMutex_isNt<0 ){
30142    winMutex_isNt = sqlite3_win32_is_nt();
30143  }
30144  assert( winMutex_isNt==0 || winMutex_isNt==1 );
30145  if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
30146#ifdef SQLITE_DEBUG
30147    p->owner = tid;
30148    p->nRef++;
30149#endif
30150    rc = SQLITE_OK;
30151  }
30152#else
30153  UNUSED_PARAMETER(p);
30154#endif
30155#ifdef SQLITE_DEBUG
30156  if( p->trace ){
30157    OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
30158             tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
30159  }
30160#endif
30161  return rc;
30162}
30163
30164/*
30165** The sqlite3_mutex_leave() routine exits a mutex that was
30166** previously entered by the same thread.  The behavior
30167** is undefined if the mutex is not currently entered or
30168** is not currently allocated.  SQLite will never do either.
30169*/
30170static void winMutexLeave(sqlite3_mutex *p){
30171#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
30172  DWORD tid = GetCurrentThreadId();
30173#endif
30174  assert( p );
30175#ifdef SQLITE_DEBUG
30176  assert( p->nRef>0 );
30177  assert( p->owner==tid );
30178  p->nRef--;
30179  if( p->nRef==0 ) p->owner = 0;
30180  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
30181#endif
30182  assert( winMutex_isInit==1 );
30183  LeaveCriticalSection(&p->mutex);
30184#ifdef SQLITE_DEBUG
30185  if( p->trace ){
30186    OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
30187             tid, p->id, p, p->trace, p->nRef));
30188  }
30189#endif
30190}
30191
30192SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
30193  static const sqlite3_mutex_methods sMutex = {
30194    winMutexInit,
30195    winMutexEnd,
30196    winMutexAlloc,
30197    winMutexFree,
30198    winMutexEnter,
30199    winMutexTry,
30200    winMutexLeave,
30201#ifdef SQLITE_DEBUG
30202    winMutexHeld,
30203    winMutexNotheld
30204#else
30205    0,
30206    0
30207#endif
30208  };
30209  return &sMutex;
30210}
30211
30212#endif /* SQLITE_MUTEX_W32 */
30213
30214/************** End of mutex_w32.c *******************************************/
30215/************** Begin file malloc.c ******************************************/
30216/*
30217** 2001 September 15
30218**
30219** The author disclaims copyright to this source code.  In place of
30220** a legal notice, here is a blessing:
30221**
30222**    May you do good and not evil.
30223**    May you find forgiveness for yourself and forgive others.
30224**    May you share freely, never taking more than you give.
30225**
30226*************************************************************************
30227**
30228** Memory allocation functions used throughout sqlite.
30229*/
30230/* #include "sqliteInt.h" */
30231/* #include <stdarg.h> */
30232
30233/*
30234** Attempt to release up to n bytes of non-essential memory currently
30235** held by SQLite. An example of non-essential memory is memory used to
30236** cache database pages that are not currently in use.
30237*/
30238SQLITE_API int sqlite3_release_memory(int n){
30239#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
30240  return sqlite3PcacheReleaseMemory(n);
30241#else
30242  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
30243  ** is a no-op returning zero if SQLite is not compiled with
30244  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
30245  UNUSED_PARAMETER(n);
30246  return 0;
30247#endif
30248}
30249
30250/*
30251** Default value of the hard heap limit.  0 means "no limit".
30252*/
30253#ifndef SQLITE_MAX_MEMORY
30254# define SQLITE_MAX_MEMORY 0
30255#endif
30256
30257/*
30258** State information local to the memory allocation subsystem.
30259*/
30260static SQLITE_WSD struct Mem0Global {
30261  sqlite3_mutex *mutex;         /* Mutex to serialize access */
30262  sqlite3_int64 alarmThreshold; /* The soft heap limit */
30263  sqlite3_int64 hardLimit;      /* The hard upper bound on memory */
30264
30265  /*
30266  ** True if heap is nearly "full" where "full" is defined by the
30267  ** sqlite3_soft_heap_limit() setting.
30268  */
30269  int nearlyFull;
30270} mem0 = { 0, SQLITE_MAX_MEMORY, SQLITE_MAX_MEMORY, 0 };
30271
30272#define mem0 GLOBAL(struct Mem0Global, mem0)
30273
30274/*
30275** Return the memory allocator mutex. sqlite3_status() needs it.
30276*/
30277SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
30278  return mem0.mutex;
30279}
30280
30281#ifndef SQLITE_OMIT_DEPRECATED
30282/*
30283** Deprecated external interface.  It used to set an alarm callback
30284** that was invoked when memory usage grew too large.  Now it is a
30285** no-op.
30286*/
30287SQLITE_API int sqlite3_memory_alarm(
30288  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
30289  void *pArg,
30290  sqlite3_int64 iThreshold
30291){
30292  (void)xCallback;
30293  (void)pArg;
30294  (void)iThreshold;
30295  return SQLITE_OK;
30296}
30297#endif
30298
30299/*
30300** Set the soft heap-size limit for the library.  An argument of
30301** zero disables the limit.  A negative argument is a no-op used to
30302** obtain the return value.
30303**
30304** The return value is the value of the heap limit just before this
30305** interface was called.
30306**
30307** If the hard heap limit is enabled, then the soft heap limit cannot
30308** be disabled nor raised above the hard heap limit.
30309*/
30310SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
30311  sqlite3_int64 priorLimit;
30312  sqlite3_int64 excess;
30313  sqlite3_int64 nUsed;
30314#ifndef SQLITE_OMIT_AUTOINIT
30315  int rc = sqlite3_initialize();
30316  if( rc ) return -1;
30317#endif
30318  sqlite3_mutex_enter(mem0.mutex);
30319  priorLimit = mem0.alarmThreshold;
30320  if( n<0 ){
30321    sqlite3_mutex_leave(mem0.mutex);
30322    return priorLimit;
30323  }
30324  if( mem0.hardLimit>0 && (n>mem0.hardLimit || n==0) ){
30325    n = mem0.hardLimit;
30326  }
30327  mem0.alarmThreshold = n;
30328  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
30329  AtomicStore(&mem0.nearlyFull, n>0 && n<=nUsed);
30330  sqlite3_mutex_leave(mem0.mutex);
30331  excess = sqlite3_memory_used() - n;
30332  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
30333  return priorLimit;
30334}
30335SQLITE_API void sqlite3_soft_heap_limit(int n){
30336  if( n<0 ) n = 0;
30337  sqlite3_soft_heap_limit64(n);
30338}
30339
30340/*
30341** Set the hard heap-size limit for the library. An argument of zero
30342** disables the hard heap limit.  A negative argument is a no-op used
30343** to obtain the return value without affecting the hard heap limit.
30344**
30345** The return value is the value of the hard heap limit just prior to
30346** calling this interface.
30347**
30348** Setting the hard heap limit will also activate the soft heap limit
30349** and constrain the soft heap limit to be no more than the hard heap
30350** limit.
30351*/
30352SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 n){
30353  sqlite3_int64 priorLimit;
30354#ifndef SQLITE_OMIT_AUTOINIT
30355  int rc = sqlite3_initialize();
30356  if( rc ) return -1;
30357#endif
30358  sqlite3_mutex_enter(mem0.mutex);
30359  priorLimit = mem0.hardLimit;
30360  if( n>=0 ){
30361    mem0.hardLimit = n;
30362    if( n<mem0.alarmThreshold || mem0.alarmThreshold==0 ){
30363      mem0.alarmThreshold = n;
30364    }
30365  }
30366  sqlite3_mutex_leave(mem0.mutex);
30367  return priorLimit;
30368}
30369
30370
30371/*
30372** Initialize the memory allocation subsystem.
30373*/
30374SQLITE_PRIVATE int sqlite3MallocInit(void){
30375  int rc;
30376  if( sqlite3GlobalConfig.m.xMalloc==0 ){
30377    sqlite3MemSetDefault();
30378  }
30379  mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
30380  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
30381      || sqlite3GlobalConfig.nPage<=0 ){
30382    sqlite3GlobalConfig.pPage = 0;
30383    sqlite3GlobalConfig.szPage = 0;
30384  }
30385  rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
30386  if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
30387  return rc;
30388}
30389
30390/*
30391** Return true if the heap is currently under memory pressure - in other
30392** words if the amount of heap used is close to the limit set by
30393** sqlite3_soft_heap_limit().
30394*/
30395SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
30396  return AtomicLoad(&mem0.nearlyFull);
30397}
30398
30399/*
30400** Deinitialize the memory allocation subsystem.
30401*/
30402SQLITE_PRIVATE void sqlite3MallocEnd(void){
30403  if( sqlite3GlobalConfig.m.xShutdown ){
30404    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
30405  }
30406  memset(&mem0, 0, sizeof(mem0));
30407}
30408
30409/*
30410** Return the amount of memory currently checked out.
30411*/
30412SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
30413  sqlite3_int64 res, mx;
30414  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
30415  return res;
30416}
30417
30418/*
30419** Return the maximum amount of memory that has ever been
30420** checked out since either the beginning of this process
30421** or since the most recent reset.
30422*/
30423SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
30424  sqlite3_int64 res, mx;
30425  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
30426  return mx;
30427}
30428
30429/*
30430** Trigger the alarm
30431*/
30432static void sqlite3MallocAlarm(int nByte){
30433  if( mem0.alarmThreshold<=0 ) return;
30434  sqlite3_mutex_leave(mem0.mutex);
30435  sqlite3_release_memory(nByte);
30436  sqlite3_mutex_enter(mem0.mutex);
30437}
30438
30439#ifdef SQLITE_DEBUG
30440/*
30441** This routine is called whenever an out-of-memory condition is seen,
30442** It's only purpose to to serve as a breakpoint for gdb or similar
30443** code debuggers when working on out-of-memory conditions, for example
30444** caused by PRAGMA hard_heap_limit=N.
30445*/
30446static SQLITE_NOINLINE void test_oom_breakpoint(u64 n){
30447  static u64 nOomFault = 0;
30448  nOomFault += n;
30449  /* The assert() is never reached in a human lifetime.  It  is here mostly
30450  ** to prevent code optimizers from optimizing out this function. */
30451  assert( (nOomFault>>32) < 0xffffffff );
30452}
30453#else
30454# define test_oom_breakpoint(X)   /* No-op for production builds */
30455#endif
30456
30457/*
30458** Do a memory allocation with statistics and alarms.  Assume the
30459** lock is already held.
30460*/
30461static void mallocWithAlarm(int n, void **pp){
30462  void *p;
30463  int nFull;
30464  assert( sqlite3_mutex_held(mem0.mutex) );
30465  assert( n>0 );
30466
30467  /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
30468  ** implementation of malloc_good_size(), which must be called in debug
30469  ** mode and specifically when the DMD "Dark Matter Detector" is enabled
30470  ** or else a crash results.  Hence, do not attempt to optimize out the
30471  ** following xRoundup() call. */
30472  nFull = sqlite3GlobalConfig.m.xRoundup(n);
30473
30474  sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
30475  if( mem0.alarmThreshold>0 ){
30476    sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
30477    if( nUsed >= mem0.alarmThreshold - nFull ){
30478      AtomicStore(&mem0.nearlyFull, 1);
30479      sqlite3MallocAlarm(nFull);
30480      if( mem0.hardLimit ){
30481        nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
30482        if( nUsed >= mem0.hardLimit - nFull ){
30483          test_oom_breakpoint(1);
30484          *pp = 0;
30485          return;
30486        }
30487      }
30488    }else{
30489      AtomicStore(&mem0.nearlyFull, 0);
30490    }
30491  }
30492  p = sqlite3GlobalConfig.m.xMalloc(nFull);
30493#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
30494  if( p==0 && mem0.alarmThreshold>0 ){
30495    sqlite3MallocAlarm(nFull);
30496    p = sqlite3GlobalConfig.m.xMalloc(nFull);
30497  }
30498#endif
30499  if( p ){
30500    nFull = sqlite3MallocSize(p);
30501    sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
30502    sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
30503  }
30504  *pp = p;
30505}
30506
30507/*
30508** Maximum size of any single memory allocation.
30509**
30510** This is not a limit on the total amount of memory used.  This is
30511** a limit on the size parameter to sqlite3_malloc() and sqlite3_realloc().
30512**
30513** The upper bound is slightly less than 2GiB:  0x7ffffeff == 2,147,483,391
30514** This provides a 256-byte safety margin for defense against 32-bit
30515** signed integer overflow bugs when computing memory allocation sizes.
30516** Paranoid applications might want to reduce the maximum allocation size
30517** further for an even larger safety margin.  0x3fffffff or 0x0fffffff
30518** or even smaller would be reasonable upper bounds on the size of a memory
30519** allocations for most applications.
30520*/
30521#ifndef SQLITE_MAX_ALLOCATION_SIZE
30522# define SQLITE_MAX_ALLOCATION_SIZE  2147483391
30523#endif
30524#if SQLITE_MAX_ALLOCATION_SIZE>2147483391
30525# error Maximum size for SQLITE_MAX_ALLOCATION_SIZE is 2147483391
30526#endif
30527
30528/*
30529** Allocate memory.  This routine is like sqlite3_malloc() except that it
30530** assumes the memory subsystem has already been initialized.
30531*/
30532SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
30533  void *p;
30534  if( n==0 || n>SQLITE_MAX_ALLOCATION_SIZE ){
30535    p = 0;
30536  }else if( sqlite3GlobalConfig.bMemstat ){
30537    sqlite3_mutex_enter(mem0.mutex);
30538    mallocWithAlarm((int)n, &p);
30539    sqlite3_mutex_leave(mem0.mutex);
30540  }else{
30541    p = sqlite3GlobalConfig.m.xMalloc((int)n);
30542  }
30543  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
30544  return p;
30545}
30546
30547/*
30548** This version of the memory allocation is for use by the application.
30549** First make sure the memory subsystem is initialized, then do the
30550** allocation.
30551*/
30552SQLITE_API void *sqlite3_malloc(int n){
30553#ifndef SQLITE_OMIT_AUTOINIT
30554  if( sqlite3_initialize() ) return 0;
30555#endif
30556  return n<=0 ? 0 : sqlite3Malloc(n);
30557}
30558SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
30559#ifndef SQLITE_OMIT_AUTOINIT
30560  if( sqlite3_initialize() ) return 0;
30561#endif
30562  return sqlite3Malloc(n);
30563}
30564
30565/*
30566** TRUE if p is a lookaside memory allocation from db
30567*/
30568#ifndef SQLITE_OMIT_LOOKASIDE
30569static int isLookaside(sqlite3 *db, const void *p){
30570  return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pTrueEnd);
30571}
30572#else
30573#define isLookaside(A,B) 0
30574#endif
30575
30576/*
30577** Return the size of a memory allocation previously obtained from
30578** sqlite3Malloc() or sqlite3_malloc().
30579*/
30580SQLITE_PRIVATE int sqlite3MallocSize(const void *p){
30581  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
30582  return sqlite3GlobalConfig.m.xSize((void*)p);
30583}
30584static int lookasideMallocSize(sqlite3 *db, const void *p){
30585#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
30586  return p<db->lookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL;
30587#else
30588  return db->lookaside.szTrue;
30589#endif
30590}
30591SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, const void *p){
30592  assert( p!=0 );
30593#ifdef SQLITE_DEBUG
30594  if( db==0 ){
30595    assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
30596    assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
30597  }else if( !isLookaside(db,p) ){
30598    assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
30599    assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
30600  }
30601#endif
30602  if( db ){
30603    if( ((uptr)p)<(uptr)(db->lookaside.pTrueEnd) ){
30604#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
30605      if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
30606        assert( sqlite3_mutex_held(db->mutex) );
30607        return LOOKASIDE_SMALL;
30608      }
30609#endif
30610      if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
30611        assert( sqlite3_mutex_held(db->mutex) );
30612        return db->lookaside.szTrue;
30613      }
30614    }
30615  }
30616  return sqlite3GlobalConfig.m.xSize((void*)p);
30617}
30618SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
30619  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
30620  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
30621  return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
30622}
30623
30624/*
30625** Free memory previously obtained from sqlite3Malloc().
30626*/
30627SQLITE_API void sqlite3_free(void *p){
30628  if( p==0 ) return;  /* IMP: R-49053-54554 */
30629  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
30630  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
30631  if( sqlite3GlobalConfig.bMemstat ){
30632    sqlite3_mutex_enter(mem0.mutex);
30633    sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
30634    sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
30635    sqlite3GlobalConfig.m.xFree(p);
30636    sqlite3_mutex_leave(mem0.mutex);
30637  }else{
30638    sqlite3GlobalConfig.m.xFree(p);
30639  }
30640}
30641
30642/*
30643** Add the size of memory allocation "p" to the count in
30644** *db->pnBytesFreed.
30645*/
30646static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
30647  *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
30648}
30649
30650/*
30651** Free memory that might be associated with a particular database
30652** connection.  Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
30653** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
30654*/
30655SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
30656  assert( db==0 || sqlite3_mutex_held(db->mutex) );
30657  assert( p!=0 );
30658  if( db ){
30659    if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
30660#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
30661      if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
30662        LookasideSlot *pBuf = (LookasideSlot*)p;
30663        assert( db->pnBytesFreed==0 );
30664#ifdef SQLITE_DEBUG
30665        memset(p, 0xaa, LOOKASIDE_SMALL);  /* Trash freed content */
30666#endif
30667        pBuf->pNext = db->lookaside.pSmallFree;
30668        db->lookaside.pSmallFree = pBuf;
30669        return;
30670      }
30671#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
30672      if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
30673        LookasideSlot *pBuf = (LookasideSlot*)p;
30674        assert( db->pnBytesFreed==0 );
30675#ifdef SQLITE_DEBUG
30676        memset(p, 0xaa, db->lookaside.szTrue);  /* Trash freed content */
30677#endif
30678        pBuf->pNext = db->lookaside.pFree;
30679        db->lookaside.pFree = pBuf;
30680        return;
30681      }
30682    }
30683    if( db->pnBytesFreed ){
30684      measureAllocationSize(db, p);
30685      return;
30686    }
30687  }
30688  assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
30689  assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
30690  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
30691  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
30692  sqlite3_free(p);
30693}
30694SQLITE_PRIVATE void sqlite3DbNNFreeNN(sqlite3 *db, void *p){
30695  assert( db!=0 );
30696  assert( sqlite3_mutex_held(db->mutex) );
30697  assert( p!=0 );
30698  if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
30699#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
30700    if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
30701      LookasideSlot *pBuf = (LookasideSlot*)p;
30702      assert( db->pnBytesFreed==0 );
30703#ifdef SQLITE_DEBUG
30704      memset(p, 0xaa, LOOKASIDE_SMALL);  /* Trash freed content */
30705#endif
30706      pBuf->pNext = db->lookaside.pSmallFree;
30707      db->lookaside.pSmallFree = pBuf;
30708      return;
30709    }
30710#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
30711    if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
30712      LookasideSlot *pBuf = (LookasideSlot*)p;
30713      assert( db->pnBytesFreed==0 );
30714#ifdef SQLITE_DEBUG
30715      memset(p, 0xaa, db->lookaside.szTrue);  /* Trash freed content */
30716#endif
30717      pBuf->pNext = db->lookaside.pFree;
30718      db->lookaside.pFree = pBuf;
30719      return;
30720    }
30721  }
30722  if( db->pnBytesFreed ){
30723    measureAllocationSize(db, p);
30724    return;
30725  }
30726  assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
30727  assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
30728  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
30729  sqlite3_free(p);
30730}
30731SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
30732  assert( db==0 || sqlite3_mutex_held(db->mutex) );
30733  if( p ) sqlite3DbFreeNN(db, p);
30734}
30735
30736/*
30737** Change the size of an existing memory allocation
30738*/
30739SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
30740  int nOld, nNew, nDiff;
30741  void *pNew;
30742  assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
30743  assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
30744  if( pOld==0 ){
30745    return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
30746  }
30747  if( nBytes==0 ){
30748    sqlite3_free(pOld); /* IMP: R-26507-47431 */
30749    return 0;
30750  }
30751  if( nBytes>=0x7fffff00 ){
30752    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
30753    return 0;
30754  }
30755  nOld = sqlite3MallocSize(pOld);
30756  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
30757  ** argument to xRealloc is always a value returned by a prior call to
30758  ** xRoundup. */
30759  nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
30760  if( nOld==nNew ){
30761    pNew = pOld;
30762  }else if( sqlite3GlobalConfig.bMemstat ){
30763    sqlite3_int64 nUsed;
30764    sqlite3_mutex_enter(mem0.mutex);
30765    sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
30766    nDiff = nNew - nOld;
30767    if( nDiff>0 && (nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)) >=
30768          mem0.alarmThreshold-nDiff ){
30769      sqlite3MallocAlarm(nDiff);
30770      if( mem0.hardLimit>0 && nUsed >= mem0.hardLimit - nDiff ){
30771        sqlite3_mutex_leave(mem0.mutex);
30772        test_oom_breakpoint(1);
30773        return 0;
30774      }
30775    }
30776    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
30777#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
30778    if( pNew==0 && mem0.alarmThreshold>0 ){
30779      sqlite3MallocAlarm((int)nBytes);
30780      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
30781    }
30782#endif
30783    if( pNew ){
30784      nNew = sqlite3MallocSize(pNew);
30785      sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
30786    }
30787    sqlite3_mutex_leave(mem0.mutex);
30788  }else{
30789    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
30790  }
30791  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
30792  return pNew;
30793}
30794
30795/*
30796** The public interface to sqlite3Realloc.  Make sure that the memory
30797** subsystem is initialized prior to invoking sqliteRealloc.
30798*/
30799SQLITE_API void *sqlite3_realloc(void *pOld, int n){
30800#ifndef SQLITE_OMIT_AUTOINIT
30801  if( sqlite3_initialize() ) return 0;
30802#endif
30803  if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
30804  return sqlite3Realloc(pOld, n);
30805}
30806SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
30807#ifndef SQLITE_OMIT_AUTOINIT
30808  if( sqlite3_initialize() ) return 0;
30809#endif
30810  return sqlite3Realloc(pOld, n);
30811}
30812
30813
30814/*
30815** Allocate and zero memory.
30816*/
30817SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
30818  void *p = sqlite3Malloc(n);
30819  if( p ){
30820    memset(p, 0, (size_t)n);
30821  }
30822  return p;
30823}
30824
30825/*
30826** Allocate and zero memory.  If the allocation fails, make
30827** the mallocFailed flag in the connection pointer.
30828*/
30829SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
30830  void *p;
30831  testcase( db==0 );
30832  p = sqlite3DbMallocRaw(db, n);
30833  if( p ) memset(p, 0, (size_t)n);
30834  return p;
30835}
30836
30837
30838/* Finish the work of sqlite3DbMallocRawNN for the unusual and
30839** slower case when the allocation cannot be fulfilled using lookaside.
30840*/
30841static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
30842  void *p;
30843  assert( db!=0 );
30844  p = sqlite3Malloc(n);
30845  if( !p ) sqlite3OomFault(db);
30846  sqlite3MemdebugSetType(p,
30847         (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
30848  return p;
30849}
30850
30851/*
30852** Allocate memory, either lookaside (if possible) or heap.
30853** If the allocation fails, set the mallocFailed flag in
30854** the connection pointer.
30855**
30856** If db!=0 and db->mallocFailed is true (indicating a prior malloc
30857** failure on the same database connection) then always return 0.
30858** Hence for a particular database connection, once malloc starts
30859** failing, it fails consistently until mallocFailed is reset.
30860** This is an important assumption.  There are many places in the
30861** code that do things like this:
30862**
30863**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
30864**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
30865**         if( b ) a[10] = 9;
30866**
30867** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
30868** that all prior mallocs (ex: "a") worked too.
30869**
30870** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
30871** not a NULL pointer.
30872*/
30873SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
30874  void *p;
30875  if( db ) return sqlite3DbMallocRawNN(db, n);
30876  p = sqlite3Malloc(n);
30877  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
30878  return p;
30879}
30880SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
30881#ifndef SQLITE_OMIT_LOOKASIDE
30882  LookasideSlot *pBuf;
30883  assert( db!=0 );
30884  assert( sqlite3_mutex_held(db->mutex) );
30885  assert( db->pnBytesFreed==0 );
30886  if( n>db->lookaside.sz ){
30887    if( !db->lookaside.bDisable ){
30888      db->lookaside.anStat[1]++;
30889    }else if( db->mallocFailed ){
30890      return 0;
30891    }
30892    return dbMallocRawFinish(db, n);
30893  }
30894#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
30895  if( n<=LOOKASIDE_SMALL ){
30896    if( (pBuf = db->lookaside.pSmallFree)!=0 ){
30897      db->lookaside.pSmallFree = pBuf->pNext;
30898      db->lookaside.anStat[0]++;
30899      return (void*)pBuf;
30900    }else if( (pBuf = db->lookaside.pSmallInit)!=0 ){
30901      db->lookaside.pSmallInit = pBuf->pNext;
30902      db->lookaside.anStat[0]++;
30903      return (void*)pBuf;
30904    }
30905  }
30906#endif
30907  if( (pBuf = db->lookaside.pFree)!=0 ){
30908    db->lookaside.pFree = pBuf->pNext;
30909    db->lookaside.anStat[0]++;
30910    return (void*)pBuf;
30911  }else if( (pBuf = db->lookaside.pInit)!=0 ){
30912    db->lookaside.pInit = pBuf->pNext;
30913    db->lookaside.anStat[0]++;
30914    return (void*)pBuf;
30915  }else{
30916    db->lookaside.anStat[2]++;
30917  }
30918#else
30919  assert( db!=0 );
30920  assert( sqlite3_mutex_held(db->mutex) );
30921  assert( db->pnBytesFreed==0 );
30922  if( db->mallocFailed ){
30923    return 0;
30924  }
30925#endif
30926  return dbMallocRawFinish(db, n);
30927}
30928
30929/* Forward declaration */
30930static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
30931
30932/*
30933** Resize the block of memory pointed to by p to n bytes. If the
30934** resize fails, set the mallocFailed flag in the connection object.
30935*/
30936SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
30937  assert( db!=0 );
30938  if( p==0 ) return sqlite3DbMallocRawNN(db, n);
30939  assert( sqlite3_mutex_held(db->mutex) );
30940  if( ((uptr)p)<(uptr)db->lookaside.pEnd ){
30941#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
30942    if( ((uptr)p)>=(uptr)db->lookaside.pMiddle ){
30943      if( n<=LOOKASIDE_SMALL ) return p;
30944    }else
30945#endif
30946    if( ((uptr)p)>=(uptr)db->lookaside.pStart ){
30947      if( n<=db->lookaside.szTrue ) return p;
30948    }
30949  }
30950  return dbReallocFinish(db, p, n);
30951}
30952static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
30953  void *pNew = 0;
30954  assert( db!=0 );
30955  assert( p!=0 );
30956  if( db->mallocFailed==0 ){
30957    if( isLookaside(db, p) ){
30958      pNew = sqlite3DbMallocRawNN(db, n);
30959      if( pNew ){
30960        memcpy(pNew, p, lookasideMallocSize(db, p));
30961        sqlite3DbFree(db, p);
30962      }
30963    }else{
30964      assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
30965      assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
30966      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
30967      pNew = sqlite3Realloc(p, n);
30968      if( !pNew ){
30969        sqlite3OomFault(db);
30970      }
30971      sqlite3MemdebugSetType(pNew,
30972            (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
30973    }
30974  }
30975  return pNew;
30976}
30977
30978/*
30979** Attempt to reallocate p.  If the reallocation fails, then free p
30980** and set the mallocFailed flag in the database connection.
30981*/
30982SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
30983  void *pNew;
30984  pNew = sqlite3DbRealloc(db, p, n);
30985  if( !pNew ){
30986    sqlite3DbFree(db, p);
30987  }
30988  return pNew;
30989}
30990
30991/*
30992** Make a copy of a string in memory obtained from sqliteMalloc(). These
30993** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
30994** is because when memory debugging is turned on, these two functions are
30995** called via macros that record the current file and line number in the
30996** ThreadData structure.
30997*/
30998SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
30999  char *zNew;
31000  size_t n;
31001  if( z==0 ){
31002    return 0;
31003  }
31004  n = strlen(z) + 1;
31005  zNew = sqlite3DbMallocRaw(db, n);
31006  if( zNew ){
31007    memcpy(zNew, z, n);
31008  }
31009  return zNew;
31010}
31011SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
31012  char *zNew;
31013  assert( db!=0 );
31014  assert( z!=0 || n==0 );
31015  assert( (n&0x7fffffff)==n );
31016  zNew = z ? sqlite3DbMallocRawNN(db, n+1) : 0;
31017  if( zNew ){
31018    memcpy(zNew, z, (size_t)n);
31019    zNew[n] = 0;
31020  }
31021  return zNew;
31022}
31023
31024/*
31025** The text between zStart and zEnd represents a phrase within a larger
31026** SQL statement.  Make a copy of this phrase in space obtained form
31027** sqlite3DbMalloc().  Omit leading and trailing whitespace.
31028*/
31029SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
31030  int n;
31031#ifdef SQLITE_DEBUG
31032  /* Because of the way the parser works, the span is guaranteed to contain
31033  ** at least one non-space character */
31034  for(n=0; sqlite3Isspace(zStart[n]); n++){ assert( &zStart[n]<zEnd ); }
31035#endif
31036  while( sqlite3Isspace(zStart[0]) ) zStart++;
31037  n = (int)(zEnd - zStart);
31038  while( sqlite3Isspace(zStart[n-1]) ) n--;
31039  return sqlite3DbStrNDup(db, zStart, n);
31040}
31041
31042/*
31043** Free any prior content in *pz and replace it with a copy of zNew.
31044*/
31045SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
31046  char *z = sqlite3DbStrDup(db, zNew);
31047  sqlite3DbFree(db, *pz);
31048  *pz = z;
31049}
31050
31051/*
31052** Call this routine to record the fact that an OOM (out-of-memory) error
31053** has happened.  This routine will set db->mallocFailed, and also
31054** temporarily disable the lookaside memory allocator and interrupt
31055** any running VDBEs.
31056**
31057** Always return a NULL pointer so that this routine can be invoked using
31058**
31059**      return sqlite3OomFault(db);
31060**
31061** and thereby avoid unnecessary stack frame allocations for the overwhelmingly
31062** common case where no OOM occurs.
31063*/
31064SQLITE_PRIVATE void *sqlite3OomFault(sqlite3 *db){
31065  if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
31066    db->mallocFailed = 1;
31067    if( db->nVdbeExec>0 ){
31068      AtomicStore(&db->u1.isInterrupted, 1);
31069    }
31070    DisableLookaside;
31071    if( db->pParse ){
31072      Parse *pParse;
31073      sqlite3ErrorMsg(db->pParse, "out of memory");
31074      db->pParse->rc = SQLITE_NOMEM_BKPT;
31075      for(pParse=db->pParse->pOuterParse; pParse; pParse = pParse->pOuterParse){
31076        pParse->nErr++;
31077        pParse->rc = SQLITE_NOMEM;
31078      }
31079    }
31080  }
31081  return 0;
31082}
31083
31084/*
31085** This routine reactivates the memory allocator and clears the
31086** db->mallocFailed flag as necessary.
31087**
31088** The memory allocator is not restarted if there are running
31089** VDBEs.
31090*/
31091SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
31092  if( db->mallocFailed && db->nVdbeExec==0 ){
31093    db->mallocFailed = 0;
31094    AtomicStore(&db->u1.isInterrupted, 0);
31095    assert( db->lookaside.bDisable>0 );
31096    EnableLookaside;
31097  }
31098}
31099
31100/*
31101** Take actions at the end of an API call to deal with error codes.
31102*/
31103static SQLITE_NOINLINE int apiHandleError(sqlite3 *db, int rc){
31104  if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
31105    sqlite3OomClear(db);
31106    sqlite3Error(db, SQLITE_NOMEM);
31107    return SQLITE_NOMEM_BKPT;
31108  }
31109  return rc & db->errMask;
31110}
31111
31112/*
31113** This function must be called before exiting any API function (i.e.
31114** returning control to the user) that has called sqlite3_malloc or
31115** sqlite3_realloc.
31116**
31117** The returned value is normally a copy of the second argument to this
31118** function. However, if a malloc() failure has occurred since the previous
31119** invocation SQLITE_NOMEM is returned instead.
31120**
31121** If an OOM as occurred, then the connection error-code (the value
31122** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
31123*/
31124SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
31125  /* If the db handle must hold the connection handle mutex here.
31126  ** Otherwise the read (and possible write) of db->mallocFailed
31127  ** is unsafe, as is the call to sqlite3Error().
31128  */
31129  assert( db!=0 );
31130  assert( sqlite3_mutex_held(db->mutex) );
31131  if( db->mallocFailed || rc ){
31132    return apiHandleError(db, rc);
31133  }
31134  return 0;
31135}
31136
31137/************** End of malloc.c **********************************************/
31138/************** Begin file printf.c ******************************************/
31139/*
31140** The "printf" code that follows dates from the 1980's.  It is in
31141** the public domain.
31142**
31143**************************************************************************
31144**
31145** This file contains code for a set of "printf"-like routines.  These
31146** routines format strings much like the printf() from the standard C
31147** library, though the implementation here has enhancements to support
31148** SQLite.
31149*/
31150/* #include "sqliteInt.h" */
31151
31152/*
31153** Conversion types fall into various categories as defined by the
31154** following enumeration.
31155*/
31156#define etRADIX       0 /* non-decimal integer types.  %x %o */
31157#define etFLOAT       1 /* Floating point.  %f */
31158#define etEXP         2 /* Exponentional notation. %e and %E */
31159#define etGENERIC     3 /* Floating or exponential, depending on exponent. %g */
31160#define etSIZE        4 /* Return number of characters processed so far. %n */
31161#define etSTRING      5 /* Strings. %s */
31162#define etDYNSTRING   6 /* Dynamically allocated strings. %z */
31163#define etPERCENT     7 /* Percent symbol. %% */
31164#define etCHARX       8 /* Characters. %c */
31165/* The rest are extensions, not normally found in printf() */
31166#define etSQLESCAPE   9 /* Strings with '\'' doubled.  %q */
31167#define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
31168                          NULL pointers replaced by SQL NULL.  %Q */
31169#define etTOKEN      11 /* a pointer to a Token structure */
31170#define etSRCITEM    12 /* a pointer to a SrcItem */
31171#define etPOINTER    13 /* The %p conversion */
31172#define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
31173#define etORDINAL    15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
31174#define etDECIMAL    16 /* %d or %u, but not %x, %o */
31175
31176#define etINVALID    17 /* Any unrecognized conversion type */
31177
31178
31179/*
31180** An "etByte" is an 8-bit unsigned value.
31181*/
31182typedef unsigned char etByte;
31183
31184/*
31185** Each builtin conversion character (ex: the 'd' in "%d") is described
31186** by an instance of the following structure
31187*/
31188typedef struct et_info {   /* Information about each format field */
31189  char fmttype;            /* The format field code letter */
31190  etByte base;             /* The base for radix conversion */
31191  etByte flags;            /* One or more of FLAG_ constants below */
31192  etByte type;             /* Conversion paradigm */
31193  etByte charset;          /* Offset into aDigits[] of the digits string */
31194  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
31195} et_info;
31196
31197/*
31198** Allowed values for et_info.flags
31199*/
31200#define FLAG_SIGNED    1     /* True if the value to convert is signed */
31201#define FLAG_STRING    4     /* Allow infinite precision */
31202
31203
31204/*
31205** The following table is searched linearly, so it is good to put the
31206** most frequently used conversion types first.
31207*/
31208static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
31209static const char aPrefix[] = "-x0\000X0";
31210static const et_info fmtinfo[] = {
31211  {  'd', 10, 1, etDECIMAL,    0,  0 },
31212  {  's',  0, 4, etSTRING,     0,  0 },
31213  {  'g',  0, 1, etGENERIC,    30, 0 },
31214  {  'z',  0, 4, etDYNSTRING,  0,  0 },
31215  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
31216  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
31217  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
31218  {  'c',  0, 0, etCHARX,      0,  0 },
31219  {  'o',  8, 0, etRADIX,      0,  2 },
31220  {  'u', 10, 0, etDECIMAL,    0,  0 },
31221  {  'x', 16, 0, etRADIX,      16, 1 },
31222  {  'X', 16, 0, etRADIX,      0,  4 },
31223#ifndef SQLITE_OMIT_FLOATING_POINT
31224  {  'f',  0, 1, etFLOAT,      0,  0 },
31225  {  'e',  0, 1, etEXP,        30, 0 },
31226  {  'E',  0, 1, etEXP,        14, 0 },
31227  {  'G',  0, 1, etGENERIC,    14, 0 },
31228#endif
31229  {  'i', 10, 1, etDECIMAL,    0,  0 },
31230  {  'n',  0, 0, etSIZE,       0,  0 },
31231  {  '%',  0, 0, etPERCENT,    0,  0 },
31232  {  'p', 16, 0, etPOINTER,    0,  1 },
31233
31234  /* All the rest are undocumented and are for internal use only */
31235  {  'T',  0, 0, etTOKEN,      0,  0 },
31236  {  'S',  0, 0, etSRCITEM,    0,  0 },
31237  {  'r', 10, 1, etORDINAL,    0,  0 },
31238};
31239
31240/* Notes:
31241**
31242**    %S    Takes a pointer to SrcItem.  Shows name or database.name
31243**    %!S   Like %S but prefer the zName over the zAlias
31244*/
31245
31246/*
31247** Set the StrAccum object to an error mode.
31248*/
31249SQLITE_PRIVATE void sqlite3StrAccumSetError(StrAccum *p, u8 eError){
31250  assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
31251  p->accError = eError;
31252  if( p->mxAlloc ) sqlite3_str_reset(p);
31253  if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);
31254}
31255
31256/*
31257** Extra argument values from a PrintfArguments object
31258*/
31259static sqlite3_int64 getIntArg(PrintfArguments *p){
31260  if( p->nArg<=p->nUsed ) return 0;
31261  return sqlite3_value_int64(p->apArg[p->nUsed++]);
31262}
31263static double getDoubleArg(PrintfArguments *p){
31264  if( p->nArg<=p->nUsed ) return 0.0;
31265  return sqlite3_value_double(p->apArg[p->nUsed++]);
31266}
31267static char *getTextArg(PrintfArguments *p){
31268  if( p->nArg<=p->nUsed ) return 0;
31269  return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
31270}
31271
31272/*
31273** Allocate memory for a temporary buffer needed for printf rendering.
31274**
31275** If the requested size of the temp buffer is larger than the size
31276** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
31277** Do the size check before the memory allocation to prevent rogue
31278** SQL from requesting large allocations using the precision or width
31279** field of the printf() function.
31280*/
31281static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
31282  char *z;
31283  if( pAccum->accError ) return 0;
31284  if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
31285    sqlite3StrAccumSetError(pAccum, SQLITE_TOOBIG);
31286    return 0;
31287  }
31288  z = sqlite3DbMallocRaw(pAccum->db, n);
31289  if( z==0 ){
31290    sqlite3StrAccumSetError(pAccum, SQLITE_NOMEM);
31291  }
31292  return z;
31293}
31294
31295/*
31296** On machines with a small stack size, you can redefine the
31297** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
31298*/
31299#ifndef SQLITE_PRINT_BUF_SIZE
31300# define SQLITE_PRINT_BUF_SIZE 70
31301#endif
31302#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
31303
31304/*
31305** Hard limit on the precision of floating-point conversions.
31306*/
31307#ifndef SQLITE_PRINTF_PRECISION_LIMIT
31308# define SQLITE_FP_PRECISION_LIMIT 100000000
31309#endif
31310
31311/*
31312** Render a string given by "fmt" into the StrAccum object.
31313*/
31314SQLITE_API void sqlite3_str_vappendf(
31315  sqlite3_str *pAccum,       /* Accumulate results here */
31316  const char *fmt,           /* Format string */
31317  va_list ap                 /* arguments */
31318){
31319  int c;                     /* Next character in the format string */
31320  char *bufpt;               /* Pointer to the conversion buffer */
31321  int precision;             /* Precision of the current field */
31322  int length;                /* Length of the field */
31323  int idx;                   /* A general purpose loop counter */
31324  int width;                 /* Width of the current field */
31325  etByte flag_leftjustify;   /* True if "-" flag is present */
31326  etByte flag_prefix;        /* '+' or ' ' or 0 for prefix */
31327  etByte flag_alternateform; /* True if "#" flag is present */
31328  etByte flag_altform2;      /* True if "!" flag is present */
31329  etByte flag_zeropad;       /* True if field width constant starts with zero */
31330  etByte flag_long;          /* 1 for the "l" flag, 2 for "ll", 0 by default */
31331  etByte done;               /* Loop termination flag */
31332  etByte cThousand;          /* Thousands separator for %d and %u */
31333  etByte xtype = etINVALID;  /* Conversion paradigm */
31334  u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
31335  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
31336  sqlite_uint64 longvalue;   /* Value for integer types */
31337  double realvalue;          /* Value for real types */
31338  const et_info *infop;      /* Pointer to the appropriate info structure */
31339  char *zOut;                /* Rendering buffer */
31340  int nOut;                  /* Size of the rendering buffer */
31341  char *zExtra = 0;          /* Malloced memory used by some conversion */
31342  int exp, e2;               /* exponent of real numbers */
31343  etByte flag_dp;            /* True if decimal point should be shown */
31344  etByte flag_rtz;           /* True if trailing zeros should be removed */
31345
31346  PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
31347  char buf[etBUFSIZE];       /* Conversion buffer */
31348
31349  /* pAccum never starts out with an empty buffer that was obtained from
31350  ** malloc().  This precondition is required by the mprintf("%z...")
31351  ** optimization. */
31352  assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
31353
31354  bufpt = 0;
31355  if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
31356    pArgList = va_arg(ap, PrintfArguments*);
31357    bArgList = 1;
31358  }else{
31359    bArgList = 0;
31360  }
31361  for(; (c=(*fmt))!=0; ++fmt){
31362    if( c!='%' ){
31363      bufpt = (char *)fmt;
31364#if HAVE_STRCHRNUL
31365      fmt = strchrnul(fmt, '%');
31366#else
31367      do{ fmt++; }while( *fmt && *fmt != '%' );
31368#endif
31369      sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
31370      if( *fmt==0 ) break;
31371    }
31372    if( (c=(*++fmt))==0 ){
31373      sqlite3_str_append(pAccum, "%", 1);
31374      break;
31375    }
31376    /* Find out what flags are present */
31377    flag_leftjustify = flag_prefix = cThousand =
31378     flag_alternateform = flag_altform2 = flag_zeropad = 0;
31379    done = 0;
31380    width = 0;
31381    flag_long = 0;
31382    precision = -1;
31383    do{
31384      switch( c ){
31385        case '-':   flag_leftjustify = 1;     break;
31386        case '+':   flag_prefix = '+';        break;
31387        case ' ':   flag_prefix = ' ';        break;
31388        case '#':   flag_alternateform = 1;   break;
31389        case '!':   flag_altform2 = 1;        break;
31390        case '0':   flag_zeropad = 1;         break;
31391        case ',':   cThousand = ',';          break;
31392        default:    done = 1;                 break;
31393        case 'l': {
31394          flag_long = 1;
31395          c = *++fmt;
31396          if( c=='l' ){
31397            c = *++fmt;
31398            flag_long = 2;
31399          }
31400          done = 1;
31401          break;
31402        }
31403        case '1': case '2': case '3': case '4': case '5':
31404        case '6': case '7': case '8': case '9': {
31405          unsigned wx = c - '0';
31406          while( (c = *++fmt)>='0' && c<='9' ){
31407            wx = wx*10 + c - '0';
31408          }
31409          testcase( wx>0x7fffffff );
31410          width = wx & 0x7fffffff;
31411#ifdef SQLITE_PRINTF_PRECISION_LIMIT
31412          if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
31413            width = SQLITE_PRINTF_PRECISION_LIMIT;
31414          }
31415#endif
31416          if( c!='.' && c!='l' ){
31417            done = 1;
31418          }else{
31419            fmt--;
31420          }
31421          break;
31422        }
31423        case '*': {
31424          if( bArgList ){
31425            width = (int)getIntArg(pArgList);
31426          }else{
31427            width = va_arg(ap,int);
31428          }
31429          if( width<0 ){
31430            flag_leftjustify = 1;
31431            width = width >= -2147483647 ? -width : 0;
31432          }
31433#ifdef SQLITE_PRINTF_PRECISION_LIMIT
31434          if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
31435            width = SQLITE_PRINTF_PRECISION_LIMIT;
31436          }
31437#endif
31438          if( (c = fmt[1])!='.' && c!='l' ){
31439            c = *++fmt;
31440            done = 1;
31441          }
31442          break;
31443        }
31444        case '.': {
31445          c = *++fmt;
31446          if( c=='*' ){
31447            if( bArgList ){
31448              precision = (int)getIntArg(pArgList);
31449            }else{
31450              precision = va_arg(ap,int);
31451            }
31452            if( precision<0 ){
31453              precision = precision >= -2147483647 ? -precision : -1;
31454            }
31455            c = *++fmt;
31456          }else{
31457            unsigned px = 0;
31458            while( c>='0' && c<='9' ){
31459              px = px*10 + c - '0';
31460              c = *++fmt;
31461            }
31462            testcase( px>0x7fffffff );
31463            precision = px & 0x7fffffff;
31464          }
31465#ifdef SQLITE_PRINTF_PRECISION_LIMIT
31466          if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
31467            precision = SQLITE_PRINTF_PRECISION_LIMIT;
31468          }
31469#endif
31470          if( c=='l' ){
31471            --fmt;
31472          }else{
31473            done = 1;
31474          }
31475          break;
31476        }
31477      }
31478    }while( !done && (c=(*++fmt))!=0 );
31479
31480    /* Fetch the info entry for the field */
31481    infop = &fmtinfo[0];
31482    xtype = etINVALID;
31483    for(idx=0; idx<ArraySize(fmtinfo); idx++){
31484      if( c==fmtinfo[idx].fmttype ){
31485        infop = &fmtinfo[idx];
31486        xtype = infop->type;
31487        break;
31488      }
31489    }
31490
31491    /*
31492    ** At this point, variables are initialized as follows:
31493    **
31494    **   flag_alternateform          TRUE if a '#' is present.
31495    **   flag_altform2               TRUE if a '!' is present.
31496    **   flag_prefix                 '+' or ' ' or zero
31497    **   flag_leftjustify            TRUE if a '-' is present or if the
31498    **                               field width was negative.
31499    **   flag_zeropad                TRUE if the width began with 0.
31500    **   flag_long                   1 for "l", 2 for "ll"
31501    **   width                       The specified field width.  This is
31502    **                               always non-negative.  Zero is the default.
31503    **   precision                   The specified precision.  The default
31504    **                               is -1.
31505    **   xtype                       The class of the conversion.
31506    **   infop                       Pointer to the appropriate info struct.
31507    */
31508    assert( width>=0 );
31509    assert( precision>=(-1) );
31510    switch( xtype ){
31511      case etPOINTER:
31512        flag_long = sizeof(char*)==sizeof(i64) ? 2 :
31513                     sizeof(char*)==sizeof(long int) ? 1 : 0;
31514        /* no break */ deliberate_fall_through
31515      case etORDINAL:
31516      case etRADIX:
31517        cThousand = 0;
31518        /* no break */ deliberate_fall_through
31519      case etDECIMAL:
31520        if( infop->flags & FLAG_SIGNED ){
31521          i64 v;
31522          if( bArgList ){
31523            v = getIntArg(pArgList);
31524          }else if( flag_long ){
31525            if( flag_long==2 ){
31526              v = va_arg(ap,i64) ;
31527            }else{
31528              v = va_arg(ap,long int);
31529            }
31530          }else{
31531            v = va_arg(ap,int);
31532          }
31533          if( v<0 ){
31534            testcase( v==SMALLEST_INT64 );
31535            testcase( v==(-1) );
31536            longvalue = ~v;
31537            longvalue++;
31538            prefix = '-';
31539          }else{
31540            longvalue = v;
31541            prefix = flag_prefix;
31542          }
31543        }else{
31544          if( bArgList ){
31545            longvalue = (u64)getIntArg(pArgList);
31546          }else if( flag_long ){
31547            if( flag_long==2 ){
31548              longvalue = va_arg(ap,u64);
31549            }else{
31550              longvalue = va_arg(ap,unsigned long int);
31551            }
31552          }else{
31553            longvalue = va_arg(ap,unsigned int);
31554          }
31555          prefix = 0;
31556        }
31557        if( longvalue==0 ) flag_alternateform = 0;
31558        if( flag_zeropad && precision<width-(prefix!=0) ){
31559          precision = width-(prefix!=0);
31560        }
31561        if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
31562          nOut = etBUFSIZE;
31563          zOut = buf;
31564        }else{
31565          u64 n;
31566          n = (u64)precision + 10;
31567          if( cThousand ) n += precision/3;
31568          zOut = zExtra = printfTempBuf(pAccum, n);
31569          if( zOut==0 ) return;
31570          nOut = (int)n;
31571        }
31572        bufpt = &zOut[nOut-1];
31573        if( xtype==etORDINAL ){
31574          static const char zOrd[] = "thstndrd";
31575          int x = (int)(longvalue % 10);
31576          if( x>=4 || (longvalue/10)%10==1 ){
31577            x = 0;
31578          }
31579          *(--bufpt) = zOrd[x*2+1];
31580          *(--bufpt) = zOrd[x*2];
31581        }
31582        {
31583          const char *cset = &aDigits[infop->charset];
31584          u8 base = infop->base;
31585          do{                                           /* Convert to ascii */
31586            *(--bufpt) = cset[longvalue%base];
31587            longvalue = longvalue/base;
31588          }while( longvalue>0 );
31589        }
31590        length = (int)(&zOut[nOut-1]-bufpt);
31591        while( precision>length ){
31592          *(--bufpt) = '0';                             /* Zero pad */
31593          length++;
31594        }
31595        if( cThousand ){
31596          int nn = (length - 1)/3;  /* Number of "," to insert */
31597          int ix = (length - 1)%3 + 1;
31598          bufpt -= nn;
31599          for(idx=0; nn>0; idx++){
31600            bufpt[idx] = bufpt[idx+nn];
31601            ix--;
31602            if( ix==0 ){
31603              bufpt[++idx] = cThousand;
31604              nn--;
31605              ix = 3;
31606            }
31607          }
31608        }
31609        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
31610        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
31611          const char *pre;
31612          char x;
31613          pre = &aPrefix[infop->prefix];
31614          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
31615        }
31616        length = (int)(&zOut[nOut-1]-bufpt);
31617        break;
31618      case etFLOAT:
31619      case etEXP:
31620      case etGENERIC: {
31621        FpDecode s;
31622        int iRound;
31623        int j;
31624
31625        if( bArgList ){
31626          realvalue = getDoubleArg(pArgList);
31627        }else{
31628          realvalue = va_arg(ap,double);
31629        }
31630        if( precision<0 ) precision = 6;         /* Set default precision */
31631#ifdef SQLITE_FP_PRECISION_LIMIT
31632        if( precision>SQLITE_FP_PRECISION_LIMIT ){
31633          precision = SQLITE_FP_PRECISION_LIMIT;
31634        }
31635#endif
31636        if( xtype==etFLOAT ){
31637          iRound = -precision;
31638        }else if( xtype==etGENERIC ){
31639          if( precision==0 ) precision = 1;
31640          iRound = precision;
31641        }else{
31642          iRound = precision+1;
31643        }
31644        sqlite3FpDecode(&s, realvalue, iRound, flag_altform2 ? 26 : 16);
31645        if( s.isSpecial ){
31646          if( s.isSpecial==2 ){
31647            bufpt = flag_zeropad ? "null" : "NaN";
31648            length = sqlite3Strlen30(bufpt);
31649            break;
31650          }else if( flag_zeropad ){
31651            s.z[0] = '9';
31652            s.iDP = 1000;
31653            s.n = 1;
31654          }else{
31655            memcpy(buf, "-Inf", 5);
31656            bufpt = buf;
31657            if( s.sign=='-' ){
31658              /* no-op */
31659            }else if( flag_prefix ){
31660              buf[0] = flag_prefix;
31661            }else{
31662              bufpt++;
31663            }
31664            length = sqlite3Strlen30(bufpt);
31665            break;
31666          }
31667        }
31668        if( s.sign=='-' ){
31669          prefix = '-';
31670        }else{
31671          prefix = flag_prefix;
31672        }
31673
31674        exp = s.iDP-1;
31675
31676        /*
31677        ** If the field type is etGENERIC, then convert to either etEXP
31678        ** or etFLOAT, as appropriate.
31679        */
31680        if( xtype==etGENERIC ){
31681          assert( precision>0 );
31682          precision--;
31683          flag_rtz = !flag_alternateform;
31684          if( exp<-4 || exp>precision ){
31685            xtype = etEXP;
31686          }else{
31687            precision = precision - exp;
31688            xtype = etFLOAT;
31689          }
31690        }else{
31691          flag_rtz = flag_altform2;
31692        }
31693        if( xtype==etEXP ){
31694          e2 = 0;
31695        }else{
31696          e2 = s.iDP - 1;
31697        }
31698        bufpt = buf;
31699        {
31700          i64 szBufNeeded;           /* Size of a temporary buffer needed */
31701          szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
31702          if( cThousand && e2>0 ) szBufNeeded += (e2+2)/3;
31703          if( szBufNeeded > etBUFSIZE ){
31704            bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
31705            if( bufpt==0 ) return;
31706          }
31707        }
31708        zOut = bufpt;
31709        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
31710        /* The sign in front of the number */
31711        if( prefix ){
31712          *(bufpt++) = prefix;
31713        }
31714        /* Digits prior to the decimal point */
31715        j = 0;
31716        if( e2<0 ){
31717          *(bufpt++) = '0';
31718        }else{
31719          for(; e2>=0; e2--){
31720            *(bufpt++) = j<s.n ? s.z[j++] : '0';
31721            if( cThousand && (e2%3)==0 && e2>1 ) *(bufpt++) = ',';
31722          }
31723        }
31724        /* The decimal point */
31725        if( flag_dp ){
31726          *(bufpt++) = '.';
31727        }
31728        /* "0" digits after the decimal point but before the first
31729        ** significant digit of the number */
31730        for(e2++; e2<0 && precision>0; precision--, e2++){
31731          *(bufpt++) = '0';
31732        }
31733        /* Significant digits after the decimal point */
31734        while( (precision--)>0 ){
31735          *(bufpt++) = j<s.n ? s.z[j++] : '0';
31736        }
31737        /* Remove trailing zeros and the "." if no digits follow the "." */
31738        if( flag_rtz && flag_dp ){
31739          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
31740          assert( bufpt>zOut );
31741          if( bufpt[-1]=='.' ){
31742            if( flag_altform2 ){
31743              *(bufpt++) = '0';
31744            }else{
31745              *(--bufpt) = 0;
31746            }
31747          }
31748        }
31749        /* Add the "eNNN" suffix */
31750        if( xtype==etEXP ){
31751          exp = s.iDP - 1;
31752          *(bufpt++) = aDigits[infop->charset];
31753          if( exp<0 ){
31754            *(bufpt++) = '-'; exp = -exp;
31755          }else{
31756            *(bufpt++) = '+';
31757          }
31758          if( exp>=100 ){
31759            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
31760            exp %= 100;
31761          }
31762          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
31763          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
31764        }
31765        *bufpt = 0;
31766
31767        /* The converted number is in buf[] and zero terminated. Output it.
31768        ** Note that the number is in the usual order, not reversed as with
31769        ** integer conversions. */
31770        length = (int)(bufpt-zOut);
31771        bufpt = zOut;
31772
31773        /* Special case:  Add leading zeros if the flag_zeropad flag is
31774        ** set and we are not left justified */
31775        if( flag_zeropad && !flag_leftjustify && length < width){
31776          int i;
31777          int nPad = width - length;
31778          for(i=width; i>=nPad; i--){
31779            bufpt[i] = bufpt[i-nPad];
31780          }
31781          i = prefix!=0;
31782          while( nPad-- ) bufpt[i++] = '0';
31783          length = width;
31784        }
31785        break;
31786      }
31787      case etSIZE:
31788        if( !bArgList ){
31789          *(va_arg(ap,int*)) = pAccum->nChar;
31790        }
31791        length = width = 0;
31792        break;
31793      case etPERCENT:
31794        buf[0] = '%';
31795        bufpt = buf;
31796        length = 1;
31797        break;
31798      case etCHARX:
31799        if( bArgList ){
31800          bufpt = getTextArg(pArgList);
31801          length = 1;
31802          if( bufpt ){
31803            buf[0] = c = *(bufpt++);
31804            if( (c&0xc0)==0xc0 ){
31805              while( length<4 && (bufpt[0]&0xc0)==0x80 ){
31806                buf[length++] = *(bufpt++);
31807              }
31808            }
31809          }else{
31810            buf[0] = 0;
31811          }
31812        }else{
31813          unsigned int ch = va_arg(ap,unsigned int);
31814          if( ch<0x00080 ){
31815            buf[0] = ch & 0xff;
31816            length = 1;
31817          }else if( ch<0x00800 ){
31818            buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
31819            buf[1] = 0x80 + (u8)(ch & 0x3f);
31820            length = 2;
31821          }else if( ch<0x10000 ){
31822            buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
31823            buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
31824            buf[2] = 0x80 + (u8)(ch & 0x3f);
31825            length = 3;
31826          }else{
31827            buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
31828            buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
31829            buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
31830            buf[3] = 0x80 + (u8)(ch & 0x3f);
31831            length = 4;
31832          }
31833        }
31834        if( precision>1 ){
31835          i64 nPrior = 1;
31836          width -= precision-1;
31837          if( width>1 && !flag_leftjustify ){
31838            sqlite3_str_appendchar(pAccum, width-1, ' ');
31839            width = 0;
31840          }
31841          sqlite3_str_append(pAccum, buf, length);
31842          precision--;
31843          while( precision > 1 ){
31844            i64 nCopyBytes;
31845            if( nPrior > precision-1 ) nPrior = precision - 1;
31846            nCopyBytes = length*nPrior;
31847            if( nCopyBytes + pAccum->nChar >= pAccum->nAlloc ){
31848              sqlite3StrAccumEnlarge(pAccum, nCopyBytes);
31849            }
31850            if( pAccum->accError ) break;
31851            sqlite3_str_append(pAccum,
31852                 &pAccum->zText[pAccum->nChar-nCopyBytes], nCopyBytes);
31853            precision -= nPrior;
31854            nPrior *= 2;
31855          }
31856        }
31857        bufpt = buf;
31858        flag_altform2 = 1;
31859        goto adjust_width_for_utf8;
31860      case etSTRING:
31861      case etDYNSTRING:
31862        if( bArgList ){
31863          bufpt = getTextArg(pArgList);
31864          xtype = etSTRING;
31865        }else{
31866          bufpt = va_arg(ap,char*);
31867        }
31868        if( bufpt==0 ){
31869          bufpt = "";
31870        }else if( xtype==etDYNSTRING ){
31871          if( pAccum->nChar==0
31872           && pAccum->mxAlloc
31873           && width==0
31874           && precision<0
31875           && pAccum->accError==0
31876          ){
31877            /* Special optimization for sqlite3_mprintf("%z..."):
31878            ** Extend an existing memory allocation rather than creating
31879            ** a new one. */
31880            assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
31881            pAccum->zText = bufpt;
31882            pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
31883            pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
31884            pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
31885            length = 0;
31886            break;
31887          }
31888          zExtra = bufpt;
31889        }
31890        if( precision>=0 ){
31891          if( flag_altform2 ){
31892            /* Set length to the number of bytes needed in order to display
31893            ** precision characters */
31894            unsigned char *z = (unsigned char*)bufpt;
31895            while( precision-- > 0 && z[0] ){
31896              SQLITE_SKIP_UTF8(z);
31897            }
31898            length = (int)(z - (unsigned char*)bufpt);
31899          }else{
31900            for(length=0; length<precision && bufpt[length]; length++){}
31901          }
31902        }else{
31903          length = 0x7fffffff & (int)strlen(bufpt);
31904        }
31905      adjust_width_for_utf8:
31906        if( flag_altform2 && width>0 ){
31907          /* Adjust width to account for extra bytes in UTF-8 characters */
31908          int ii = length - 1;
31909          while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
31910        }
31911        break;
31912      case etSQLESCAPE:           /* %q: Escape ' characters */
31913      case etSQLESCAPE2:          /* %Q: Escape ' and enclose in '...' */
31914      case etSQLESCAPE3: {        /* %w: Escape " characters */
31915        i64 i, j, k, n;
31916        int needQuote, isnull;
31917        char ch;
31918        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
31919        char *escarg;
31920
31921        if( bArgList ){
31922          escarg = getTextArg(pArgList);
31923        }else{
31924          escarg = va_arg(ap,char*);
31925        }
31926        isnull = escarg==0;
31927        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
31928        /* For %q, %Q, and %w, the precision is the number of bytes (or
31929        ** characters if the ! flags is present) to use from the input.
31930        ** Because of the extra quoting characters inserted, the number
31931        ** of output characters may be larger than the precision.
31932        */
31933        k = precision;
31934        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
31935          if( ch==q )  n++;
31936          if( flag_altform2 && (ch&0xc0)==0xc0 ){
31937            while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
31938          }
31939        }
31940        needQuote = !isnull && xtype==etSQLESCAPE2;
31941        n += i + 3;
31942        if( n>etBUFSIZE ){
31943          bufpt = zExtra = printfTempBuf(pAccum, n);
31944          if( bufpt==0 ) return;
31945        }else{
31946          bufpt = buf;
31947        }
31948        j = 0;
31949        if( needQuote ) bufpt[j++] = q;
31950        k = i;
31951        for(i=0; i<k; i++){
31952          bufpt[j++] = ch = escarg[i];
31953          if( ch==q ) bufpt[j++] = ch;
31954        }
31955        if( needQuote ) bufpt[j++] = q;
31956        bufpt[j] = 0;
31957        length = j;
31958        goto adjust_width_for_utf8;
31959      }
31960      case etTOKEN: {
31961        if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
31962        if( flag_alternateform ){
31963          /* %#T means an Expr pointer that uses Expr.u.zToken */
31964          Expr *pExpr = va_arg(ap,Expr*);
31965          if( ALWAYS(pExpr) && ALWAYS(!ExprHasProperty(pExpr,EP_IntValue)) ){
31966            sqlite3_str_appendall(pAccum, (const char*)pExpr->u.zToken);
31967            sqlite3RecordErrorOffsetOfExpr(pAccum->db, pExpr);
31968          }
31969        }else{
31970          /* %T means a Token pointer */
31971          Token *pToken = va_arg(ap, Token*);
31972          assert( bArgList==0 );
31973          if( pToken && pToken->n ){
31974            sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
31975            sqlite3RecordErrorByteOffset(pAccum->db, pToken->z);
31976          }
31977        }
31978        length = width = 0;
31979        break;
31980      }
31981      case etSRCITEM: {
31982        SrcItem *pItem;
31983        if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
31984        pItem = va_arg(ap, SrcItem*);
31985        assert( bArgList==0 );
31986        if( pItem->zAlias && !flag_altform2 ){
31987          sqlite3_str_appendall(pAccum, pItem->zAlias);
31988        }else if( pItem->zName ){
31989          if( pItem->zDatabase ){
31990            sqlite3_str_appendall(pAccum, pItem->zDatabase);
31991            sqlite3_str_append(pAccum, ".", 1);
31992          }
31993          sqlite3_str_appendall(pAccum, pItem->zName);
31994        }else if( pItem->zAlias ){
31995          sqlite3_str_appendall(pAccum, pItem->zAlias);
31996        }else{
31997          Select *pSel = pItem->pSelect;
31998          assert( pSel!=0 ); /* Because of tag-20240424-1 */
31999          if( pSel->selFlags & SF_NestedFrom ){
32000            sqlite3_str_appendf(pAccum, "(join-%u)", pSel->selId);
32001          }else if( pSel->selFlags & SF_MultiValue ){
32002            assert( !pItem->fg.isTabFunc && !pItem->fg.isIndexedBy );
32003            sqlite3_str_appendf(pAccum, "%u-ROW VALUES CLAUSE",
32004                                pItem->u1.nRow);
32005          }else{
32006            sqlite3_str_appendf(pAccum, "(subquery-%u)", pSel->selId);
32007          }
32008        }
32009        length = width = 0;
32010        break;
32011      }
32012      default: {
32013        assert( xtype==etINVALID );
32014        return;
32015      }
32016    }/* End switch over the format type */
32017    /*
32018    ** The text of the conversion is pointed to by "bufpt" and is
32019    ** "length" characters long.  The field width is "width".  Do
32020    ** the output.  Both length and width are in bytes, not characters,
32021    ** at this point.  If the "!" flag was present on string conversions
32022    ** indicating that width and precision should be expressed in characters,
32023    ** then the values have been translated prior to reaching this point.
32024    */
32025    width -= length;
32026    if( width>0 ){
32027      if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
32028      sqlite3_str_append(pAccum, bufpt, length);
32029      if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
32030    }else{
32031      sqlite3_str_append(pAccum, bufpt, length);
32032    }
32033
32034    if( zExtra ){
32035      sqlite3DbFree(pAccum->db, zExtra);
32036      zExtra = 0;
32037    }
32038  }/* End for loop over the format string */
32039} /* End of function */
32040
32041
32042/*
32043** The z string points to the first character of a token that is
32044** associated with an error.  If db does not already have an error
32045** byte offset recorded, try to compute the error byte offset for
32046** z and set the error byte offset in db.
32047*/
32048SQLITE_PRIVATE void sqlite3RecordErrorByteOffset(sqlite3 *db, const char *z){
32049  const Parse *pParse;
32050  const char *zText;
32051  const char *zEnd;
32052  assert( z!=0 );
32053  if( NEVER(db==0) ) return;
32054  if( db->errByteOffset!=(-2) ) return;
32055  pParse = db->pParse;
32056  if( NEVER(pParse==0) ) return;
32057  zText =pParse->zTail;
32058  if( NEVER(zText==0) ) return;
32059  zEnd = &zText[strlen(zText)];
32060  if( SQLITE_WITHIN(z,zText,zEnd) ){
32061    db->errByteOffset = (int)(z-zText);
32062  }
32063}
32064
32065/*
32066** If pExpr has a byte offset for the start of a token, record that as
32067** as the error offset.
32068*/
32069SQLITE_PRIVATE void sqlite3RecordErrorOffsetOfExpr(sqlite3 *db, const Expr *pExpr){
32070  while( pExpr
32071     && (ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) || pExpr->w.iOfst<=0)
32072  ){
32073    pExpr = pExpr->pLeft;
32074  }
32075  if( pExpr==0 ) return;
32076  db->errByteOffset = pExpr->w.iOfst;
32077}
32078
32079/*
32080** Enlarge the memory allocation on a StrAccum object so that it is
32081** able to accept at least N more bytes of text.
32082**
32083** Return the number of bytes of text that StrAccum is able to accept
32084** after the attempted enlargement.  The value returned might be zero.
32085*/
32086SQLITE_PRIVATE int sqlite3StrAccumEnlarge(StrAccum *p, i64 N){
32087  char *zNew;
32088  assert( p->nChar+N >= p->nAlloc ); /* Only called if really needed */
32089  if( p->accError ){
32090    testcase(p->accError==SQLITE_TOOBIG);
32091    testcase(p->accError==SQLITE_NOMEM);
32092    return 0;
32093  }
32094  if( p->mxAlloc==0 ){
32095    sqlite3StrAccumSetError(p, SQLITE_TOOBIG);
32096    return p->nAlloc - p->nChar - 1;
32097  }else{
32098    char *zOld = isMalloced(p) ? p->zText : 0;
32099    i64 szNew = p->nChar + N + 1;
32100    if( szNew+p->nChar<=p->mxAlloc ){
32101      /* Force exponential buffer size growth as long as it does not overflow,
32102      ** to avoid having to call this routine too often */
32103      szNew += p->nChar;
32104    }
32105    if( szNew > p->mxAlloc ){
32106      sqlite3_str_reset(p);
32107      sqlite3StrAccumSetError(p, SQLITE_TOOBIG);
32108      return 0;
32109    }else{
32110      p->nAlloc = (int)szNew;
32111    }
32112    if( p->db ){
32113      zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
32114    }else{
32115      zNew = sqlite3Realloc(zOld, p->nAlloc);
32116    }
32117    if( zNew ){
32118      assert( p->zText!=0 || p->nChar==0 );
32119      if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
32120      p->zText = zNew;
32121      p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
32122      p->printfFlags |= SQLITE_PRINTF_MALLOCED;
32123    }else{
32124      sqlite3_str_reset(p);
32125      sqlite3StrAccumSetError(p, SQLITE_NOMEM);
32126      return 0;
32127    }
32128  }
32129  assert( N>=0 && N<=0x7fffffff );
32130  return (int)N;
32131}
32132
32133/*
32134** Append N copies of character c to the given string buffer.
32135*/
32136SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
32137  testcase( p->nChar + (i64)N > 0x7fffffff );
32138  if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
32139    return;
32140  }
32141  while( (N--)>0 ) p->zText[p->nChar++] = c;
32142}
32143
32144/*
32145** The StrAccum "p" is not large enough to accept N new bytes of z[].
32146** So enlarge if first, then do the append.
32147**
32148** This is a helper routine to sqlite3_str_append() that does special-case
32149** work (enlarging the buffer) using tail recursion, so that the
32150** sqlite3_str_append() routine can use fast calling semantics.
32151*/
32152static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
32153  N = sqlite3StrAccumEnlarge(p, N);
32154  if( N>0 ){
32155    memcpy(&p->zText[p->nChar], z, N);
32156    p->nChar += N;
32157  }
32158}
32159
32160/*
32161** Append N bytes of text from z to the StrAccum object.  Increase the
32162** size of the memory allocation for StrAccum if necessary.
32163*/
32164SQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
32165  assert( z!=0 || N==0 );
32166  assert( p->zText!=0 || p->nChar==0 || p->accError );
32167  assert( N>=0 );
32168  assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
32169  if( p->nChar+N >= p->nAlloc ){
32170    enlargeAndAppend(p,z,N);
32171  }else if( N ){
32172    assert( p->zText );
32173    p->nChar += N;
32174    memcpy(&p->zText[p->nChar-N], z, N);
32175  }
32176}
32177
32178/*
32179** Append the complete text of zero-terminated string z[] to the p string.
32180*/
32181SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
32182  sqlite3_str_append(p, z, sqlite3Strlen30(z));
32183}
32184
32185
32186/*
32187** Finish off a string by making sure it is zero-terminated.
32188** Return a pointer to the resulting string.  Return a NULL
32189** pointer if any kind of error was encountered.
32190*/
32191static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
32192  char *zText;
32193  assert( p->mxAlloc>0 && !isMalloced(p) );
32194  zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
32195  if( zText ){
32196    memcpy(zText, p->zText, p->nChar+1);
32197    p->printfFlags |= SQLITE_PRINTF_MALLOCED;
32198  }else{
32199    sqlite3StrAccumSetError(p, SQLITE_NOMEM);
32200  }
32201  p->zText = zText;
32202  return zText;
32203}
32204SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
32205  if( p->zText ){
32206    p->zText[p->nChar] = 0;
32207    if( p->mxAlloc>0 && !isMalloced(p) ){
32208      return strAccumFinishRealloc(p);
32209    }
32210  }
32211  return p->zText;
32212}
32213
32214/*
32215** Use the content of the StrAccum passed as the second argument
32216** as the result of an SQL function.
32217*/
32218SQLITE_PRIVATE void sqlite3ResultStrAccum(sqlite3_context *pCtx, StrAccum *p){
32219  if( p->accError ){
32220    sqlite3_result_error_code(pCtx, p->accError);
32221    sqlite3_str_reset(p);
32222  }else if( isMalloced(p) ){
32223    sqlite3_result_text(pCtx, p->zText, p->nChar, SQLITE_DYNAMIC);
32224  }else{
32225    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
32226    sqlite3_str_reset(p);
32227  }
32228}
32229
32230/*
32231** This singleton is an sqlite3_str object that is returned if
32232** sqlite3_malloc() fails to provide space for a real one.  This
32233** sqlite3_str object accepts no new text and always returns
32234** an SQLITE_NOMEM error.
32235*/
32236static sqlite3_str sqlite3OomStr = {
32237   0, 0, 0, 0, 0, SQLITE_NOMEM, 0
32238};
32239
32240/* Finalize a string created using sqlite3_str_new().
32241*/
32242SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
32243  char *z;
32244  if( p!=0 && p!=&sqlite3OomStr ){
32245    z = sqlite3StrAccumFinish(p);
32246    sqlite3_free(p);
32247  }else{
32248    z = 0;
32249  }
32250  return z;
32251}
32252
32253/* Return any error code associated with p */
32254SQLITE_API int sqlite3_str_errcode(sqlite3_str *p){
32255  return p ? p->accError : SQLITE_NOMEM;
32256}
32257
32258/* Return the current length of p in bytes */
32259SQLITE_API int sqlite3_str_length(sqlite3_str *p){
32260  return p ? p->nChar : 0;
32261}
32262
32263/* Return the current value for p */
32264SQLITE_API char *sqlite3_str_value(sqlite3_str *p){
32265  if( p==0 || p->nChar==0 ) return 0;
32266  p->zText[p->nChar] = 0;
32267  return p->zText;
32268}
32269
32270/*
32271** Reset an StrAccum string.  Reclaim all malloced memory.
32272*/
32273SQLITE_API void sqlite3_str_reset(StrAccum *p){
32274  if( isMalloced(p) ){
32275    sqlite3DbFree(p->db, p->zText);
32276    p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
32277  }
32278  p->nAlloc = 0;
32279  p->nChar = 0;
32280  p->zText = 0;
32281}
32282
32283/*
32284** Initialize a string accumulator.
32285**
32286** p:     The accumulator to be initialized.
32287** db:    Pointer to a database connection.  May be NULL.  Lookaside
32288**        memory is used if not NULL. db->mallocFailed is set appropriately
32289**        when not NULL.
32290** zBase: An initial buffer.  May be NULL in which case the initial buffer
32291**        is malloced.
32292** n:     Size of zBase in bytes.  If total space requirements never exceed
32293**        n then no memory allocations ever occur.
32294** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
32295**        allocations will ever occur.
32296*/
32297SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
32298  p->zText = zBase;
32299  p->db = db;
32300  p->nAlloc = n;
32301  p->mxAlloc = mx;
32302  p->nChar = 0;
32303  p->accError = 0;
32304  p->printfFlags = 0;
32305}
32306
32307/* Allocate and initialize a new dynamic string object */
32308SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){
32309  sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
32310  if( p ){
32311    sqlite3StrAccumInit(p, 0, 0, 0,
32312            db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
32313  }else{
32314    p = &sqlite3OomStr;
32315  }
32316  return p;
32317}
32318
32319/*
32320** Print into memory obtained from sqliteMalloc().  Use the internal
32321** %-conversion extensions.
32322*/
32323SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
32324  char *z;
32325  char zBase[SQLITE_PRINT_BUF_SIZE];
32326  StrAccum acc;
32327  assert( db!=0 );
32328  sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
32329                      db->aLimit[SQLITE_LIMIT_LENGTH]);
32330  acc.printfFlags = SQLITE_PRINTF_INTERNAL;
32331  sqlite3_str_vappendf(&acc, zFormat, ap);
32332  z = sqlite3StrAccumFinish(&acc);
32333  if( acc.accError==SQLITE_NOMEM ){
32334    sqlite3OomFault(db);
32335  }
32336  return z;
32337}
32338
32339/*
32340** Print into memory obtained from sqliteMalloc().  Use the internal
32341** %-conversion extensions.
32342*/
32343SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
32344  va_list ap;
32345  char *z;
32346  va_start(ap, zFormat);
32347  z = sqlite3VMPrintf(db, zFormat, ap);
32348  va_end(ap);
32349  return z;
32350}
32351
32352/*
32353** Print into memory obtained from sqlite3_malloc().  Omit the internal
32354** %-conversion extensions.
32355*/
32356SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
32357  char *z;
32358  char zBase[SQLITE_PRINT_BUF_SIZE];
32359  StrAccum acc;
32360
32361#ifdef SQLITE_ENABLE_API_ARMOR
32362  if( zFormat==0 ){
32363    (void)SQLITE_MISUSE_BKPT;
32364    return 0;
32365  }
32366#endif
32367#ifndef SQLITE_OMIT_AUTOINIT
32368  if( sqlite3_initialize() ) return 0;
32369#endif
32370  sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
32371  sqlite3_str_vappendf(&acc, zFormat, ap);
32372  z = sqlite3StrAccumFinish(&acc);
32373  return z;
32374}
32375
32376/*
32377** Print into memory obtained from sqlite3_malloc()().  Omit the internal
32378** %-conversion extensions.
32379*/
32380SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
32381  va_list ap;
32382  char *z;
32383#ifndef SQLITE_OMIT_AUTOINIT
32384  if( sqlite3_initialize() ) return 0;
32385#endif
32386  va_start(ap, zFormat);
32387  z = sqlite3_vmprintf(zFormat, ap);
32388  va_end(ap);
32389  return z;
32390}
32391
32392/*
32393** sqlite3_snprintf() works like snprintf() except that it ignores the
32394** current locale settings.  This is important for SQLite because we
32395** are not able to use a "," as the decimal point in place of "." as
32396** specified by some locales.
32397**
32398** Oops:  The first two arguments of sqlite3_snprintf() are backwards
32399** from the snprintf() standard.  Unfortunately, it is too late to change
32400** this without breaking compatibility, so we just have to live with the
32401** mistake.
32402**
32403** sqlite3_vsnprintf() is the varargs version.
32404*/
32405SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
32406  StrAccum acc;
32407  if( n<=0 ) return zBuf;
32408#ifdef SQLITE_ENABLE_API_ARMOR
32409  if( zBuf==0 || zFormat==0 ) {
32410    (void)SQLITE_MISUSE_BKPT;
32411    if( zBuf ) zBuf[0] = 0;
32412    return zBuf;
32413  }
32414#endif
32415  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
32416  sqlite3_str_vappendf(&acc, zFormat, ap);
32417  zBuf[acc.nChar] = 0;
32418  return zBuf;
32419}
32420SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
32421  StrAccum acc;
32422  va_list ap;
32423  if( n<=0 ) return zBuf;
32424#ifdef SQLITE_ENABLE_API_ARMOR
32425  if( zBuf==0 || zFormat==0 ) {
32426    (void)SQLITE_MISUSE_BKPT;
32427    if( zBuf ) zBuf[0] = 0;
32428    return zBuf;
32429  }
32430#endif
32431  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
32432  va_start(ap,zFormat);
32433  sqlite3_str_vappendf(&acc, zFormat, ap);
32434  va_end(ap);
32435  zBuf[acc.nChar] = 0;
32436  return zBuf;
32437}
32438
32439/*
32440** This is the routine that actually formats the sqlite3_log() message.
32441** We house it in a separate routine from sqlite3_log() to avoid using
32442** stack space on small-stack systems when logging is disabled.
32443**
32444** sqlite3_log() must render into a static buffer.  It cannot dynamically
32445** allocate memory because it might be called while the memory allocator
32446** mutex is held.
32447**
32448** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
32449** certain format characters (%q) or for very large precisions or widths.
32450** Care must be taken that any sqlite3_log() calls that occur while the
32451** memory mutex is held do not use these mechanisms.
32452*/
32453static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
32454  StrAccum acc;                          /* String accumulator */
32455  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
32456
32457  sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
32458  sqlite3_str_vappendf(&acc, zFormat, ap);
32459  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
32460                           sqlite3StrAccumFinish(&acc));
32461}
32462
32463/*
32464** Format and write a message to the log if logging is enabled.
32465*/
32466SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
32467  va_list ap;                             /* Vararg list */
32468  if( sqlite3GlobalConfig.xLog ){
32469    va_start(ap, zFormat);
32470    renderLogMsg(iErrCode, zFormat, ap);
32471    va_end(ap);
32472  }
32473}
32474
32475#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
32476/*
32477** A version of printf() that understands %lld.  Used for debugging.
32478** The printf() built into some versions of windows does not understand %lld
32479** and segfaults if you give it a long long int.
32480*/
32481SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
32482  va_list ap;
32483  StrAccum acc;
32484  char zBuf[SQLITE_PRINT_BUF_SIZE*10];
32485  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
32486  va_start(ap,zFormat);
32487  sqlite3_str_vappendf(&acc, zFormat, ap);
32488  va_end(ap);
32489  sqlite3StrAccumFinish(&acc);
32490#ifdef SQLITE_OS_TRACE_PROC
32491  {
32492    extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
32493    SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
32494  }
32495#else
32496  fprintf(stdout,"%s", zBuf);
32497  fflush(stdout);
32498#endif
32499}
32500#endif
32501
32502
32503/*
32504** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
32505** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
32506*/
32507SQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
32508  va_list ap;
32509  va_start(ap,zFormat);
32510  sqlite3_str_vappendf(p, zFormat, ap);
32511  va_end(ap);
32512}
32513
32514
32515/*****************************************************************************
32516** Reference counted string/blob storage
32517*****************************************************************************/
32518
32519/*
32520** Increase the reference count of the string by one.
32521**
32522** The input parameter is returned.
32523*/
32524SQLITE_PRIVATE char *sqlite3RCStrRef(char *z){
32525  RCStr *p = (RCStr*)z;
32526  assert( p!=0 );
32527  p--;
32528  p->nRCRef++;
32529  return z;
32530}
32531
32532/*
32533** Decrease the reference count by one.  Free the string when the
32534** reference count reaches zero.
32535*/
32536SQLITE_PRIVATE void sqlite3RCStrUnref(void *z){
32537  RCStr *p = (RCStr*)z;
32538  assert( p!=0 );
32539  p--;
32540  assert( p->nRCRef>0 );
32541  if( p->nRCRef>=2 ){
32542    p->nRCRef--;
32543  }else{
32544    sqlite3_free(p);
32545  }
32546}
32547
32548/*
32549** Create a new string that is capable of holding N bytes of text, not counting
32550** the zero byte at the end.  The string is uninitialized.
32551**
32552** The reference count is initially 1.  Call sqlite3RCStrUnref() to free the
32553** newly allocated string.
32554**
32555** This routine returns 0 on an OOM.
32556*/
32557SQLITE_PRIVATE char *sqlite3RCStrNew(u64 N){
32558  RCStr *p = sqlite3_malloc64( N + sizeof(*p) + 1 );
32559  if( p==0 ) return 0;
32560  p->nRCRef = 1;
32561  return (char*)&p[1];
32562}
32563
32564/*
32565** Change the size of the string so that it is able to hold N bytes.
32566** The string might be reallocated, so return the new allocation.
32567*/
32568SQLITE_PRIVATE char *sqlite3RCStrResize(char *z, u64 N){
32569  RCStr *p = (RCStr*)z;
32570  RCStr *pNew;
32571  assert( p!=0 );
32572  p--;
32573  assert( p->nRCRef==1 );
32574  pNew = sqlite3_realloc64(p, N+sizeof(RCStr)+1);
32575  if( pNew==0 ){
32576    sqlite3_free(p);
32577    return 0;
32578  }else{
32579    return (char*)&pNew[1];
32580  }
32581}
32582
32583/************** End of printf.c **********************************************/
32584/************** Begin file treeview.c ****************************************/
32585/*
32586** 2015-06-08
32587**
32588** The author disclaims copyright to this source code.  In place of
32589** a legal notice, here is a blessing:
32590**
32591**    May you do good and not evil.
32592**    May you find forgiveness for yourself and forgive others.
32593**    May you share freely, never taking more than you give.
32594**
32595*************************************************************************
32596**
32597** This file contains C code to implement the TreeView debugging routines.
32598** These routines print a parse tree to standard output for debugging and
32599** analysis.
32600**
32601** The interfaces in this file is only available when compiling
32602** with SQLITE_DEBUG.
32603*/
32604/* #include "sqliteInt.h" */
32605#ifdef SQLITE_DEBUG
32606
32607/*
32608** Add a new subitem to the tree.  The moreToFollow flag indicates that this
32609** is not the last item in the tree.
32610*/
32611static void sqlite3TreeViewPush(TreeView **pp, u8 moreToFollow){
32612  TreeView *p = *pp;
32613  if( p==0 ){
32614    *pp = p = sqlite3_malloc64( sizeof(*p) );
32615    if( p==0 ) return;
32616    memset(p, 0, sizeof(*p));
32617  }else{
32618    p->iLevel++;
32619  }
32620  assert( moreToFollow==0 || moreToFollow==1 );
32621  if( p->iLevel<(int)sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
32622}
32623
32624/*
32625** Finished with one layer of the tree
32626*/
32627static void sqlite3TreeViewPop(TreeView **pp){
32628  TreeView *p = *pp;
32629  if( p==0 ) return;
32630  p->iLevel--;
32631  if( p->iLevel<0 ){
32632    sqlite3_free(p);
32633    *pp = 0;
32634  }
32635}
32636
32637/*
32638** Generate a single line of output for the tree, with a prefix that contains
32639** all the appropriate tree lines
32640*/
32641SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
32642  va_list ap;
32643  int i;
32644  StrAccum acc;
32645  char zBuf[1000];
32646  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
32647  if( p ){
32648    for(i=0; i<p->iLevel && i<(int)sizeof(p->bLine)-1; i++){
32649      sqlite3_str_append(&acc, p->bLine[i] ? "|   " : "    ", 4);
32650    }
32651    sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
32652  }
32653  if( zFormat!=0 ){
32654    va_start(ap, zFormat);
32655    sqlite3_str_vappendf(&acc, zFormat, ap);
32656    va_end(ap);
32657    assert( acc.nChar>0 || acc.accError );
32658    sqlite3_str_append(&acc, "\n", 1);
32659  }
32660  sqlite3StrAccumFinish(&acc);
32661  fprintf(stdout,"%s", zBuf);
32662  fflush(stdout);
32663}
32664
32665/*
32666** Shorthand for starting a new tree item that consists of a single label
32667*/
32668static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
32669  sqlite3TreeViewPush(&p, moreFollows);
32670  sqlite3TreeViewLine(p, "%s", zLabel);
32671}
32672
32673/*
32674** Show a list of Column objects in tree format.
32675*/
32676SQLITE_PRIVATE void sqlite3TreeViewColumnList(
32677  TreeView *pView,
32678  const Column *aCol,
32679  int nCol,
32680  u8 moreToFollow
32681){
32682  int i;
32683  sqlite3TreeViewPush(&pView, moreToFollow);
32684  sqlite3TreeViewLine(pView, "COLUMNS");
32685  for(i=0; i<nCol; i++){
32686    u16 flg = aCol[i].colFlags;
32687    int colMoreToFollow = i<(nCol - 1);
32688    sqlite3TreeViewPush(&pView, colMoreToFollow);
32689    sqlite3TreeViewLine(pView, 0);
32690    printf(" %s", aCol[i].zCnName);
32691    switch( aCol[i].eCType ){
32692      case COLTYPE_ANY:      printf(" ANY");        break;
32693      case COLTYPE_BLOB:     printf(" BLOB");       break;
32694      case COLTYPE_INT:      printf(" INT");        break;
32695      case COLTYPE_INTEGER:  printf(" INTEGER");    break;
32696      case COLTYPE_REAL:     printf(" REAL");       break;
32697      case COLTYPE_TEXT:     printf(" TEXT");       break;
32698      case COLTYPE_CUSTOM: {
32699        if( flg & COLFLAG_HASTYPE ){
32700          const char *z = aCol[i].zCnName;
32701          z += strlen(z)+1;
32702          printf(" X-%s", z);
32703          break;
32704        }
32705      }
32706    }
32707    if( flg & COLFLAG_PRIMKEY ) printf(" PRIMARY KEY");
32708    if( flg & COLFLAG_HIDDEN ) printf(" HIDDEN");
32709#ifdef COLFLAG_NOEXPAND
32710    if( flg & COLFLAG_NOEXPAND ) printf(" NO-EXPAND");
32711#endif
32712    if( flg ) printf(" flags=%04x", flg);
32713    printf("\n");
32714    fflush(stdout);
32715    sqlite3TreeViewPop(&pView);
32716  }
32717  sqlite3TreeViewPop(&pView);
32718}
32719
32720/*
32721** Generate a human-readable description of a WITH clause.
32722*/
32723SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
32724  int i;
32725  if( pWith==0 ) return;
32726  if( pWith->nCte==0 ) return;
32727  if( pWith->pOuter ){
32728    sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
32729  }else{
32730    sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
32731  }
32732  if( pWith->nCte>0 ){
32733    sqlite3TreeViewPush(&pView, moreToFollow);
32734    for(i=0; i<pWith->nCte; i++){
32735      StrAccum x;
32736      char zLine[1000];
32737      const struct Cte *pCte = &pWith->a[i];
32738      sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
32739      sqlite3_str_appendf(&x, "%s", pCte->zName);
32740      if( pCte->pCols && pCte->pCols->nExpr>0 ){
32741        char cSep = '(';
32742        int j;
32743        for(j=0; j<pCte->pCols->nExpr; j++){
32744          sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zEName);
32745          cSep = ',';
32746        }
32747        sqlite3_str_appendf(&x, ")");
32748      }
32749      if( pCte->eM10d!=M10d_Any ){
32750        sqlite3_str_appendf(&x, " %sMATERIALIZED",
32751           pCte->eM10d==M10d_No ? "NOT " : "");
32752      }
32753      if( pCte->pUse ){
32754        sqlite3_str_appendf(&x, " (pUse=0x%p, nUse=%d)", pCte->pUse,
32755                 pCte->pUse->nUse);
32756      }
32757      sqlite3StrAccumFinish(&x);
32758      sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
32759      sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
32760      sqlite3TreeViewPop(&pView);
32761    }
32762    sqlite3TreeViewPop(&pView);
32763  }
32764}
32765
32766/*
32767** Generate a human-readable description of a SrcList object.
32768*/
32769SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){
32770  int i;
32771  if( pSrc==0 ) return;
32772  for(i=0; i<pSrc->nSrc; i++){
32773    const SrcItem *pItem = &pSrc->a[i];
32774    StrAccum x;
32775    int n = 0;
32776    char zLine[1000];
32777    sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
32778    x.printfFlags |= SQLITE_PRINTF_INTERNAL;
32779    sqlite3_str_appendf(&x, "{%d:*} %!S", pItem->iCursor, pItem);
32780    if( pItem->pTab ){
32781      sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p used=%llx%s",
32782           pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab,
32783           pItem->colUsed,
32784           pItem->fg.rowidUsed ? "+rowid" : "");
32785    }
32786    if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))==(JT_LEFT|JT_RIGHT) ){
32787      sqlite3_str_appendf(&x, " FULL-OUTER-JOIN");
32788    }else if( pItem->fg.jointype & JT_LEFT ){
32789      sqlite3_str_appendf(&x, " LEFT-JOIN");
32790    }else if( pItem->fg.jointype & JT_RIGHT ){
32791      sqlite3_str_appendf(&x, " RIGHT-JOIN");
32792    }else if( pItem->fg.jointype & JT_CROSS ){
32793      sqlite3_str_appendf(&x, " CROSS-JOIN");
32794    }
32795    if( pItem->fg.jointype & JT_LTORJ ){
32796      sqlite3_str_appendf(&x, " LTORJ");
32797    }
32798    if( pItem->fg.fromDDL ){
32799      sqlite3_str_appendf(&x, " DDL");
32800    }
32801    if( pItem->fg.isCte ){
32802      sqlite3_str_appendf(&x, " CteUse=0x%p", pItem->u2.pCteUse);
32803    }
32804    if( pItem->fg.isOn || (pItem->fg.isUsing==0 && pItem->u3.pOn!=0) ){
32805      sqlite3_str_appendf(&x, " ON");
32806    }
32807    if( pItem->fg.isTabFunc )      sqlite3_str_appendf(&x, " isTabFunc");
32808    if( pItem->fg.isCorrelated )   sqlite3_str_appendf(&x, " isCorrelated");
32809    if( pItem->fg.isMaterialized ) sqlite3_str_appendf(&x, " isMaterialized");
32810    if( pItem->fg.viaCoroutine )   sqlite3_str_appendf(&x, " viaCoroutine");
32811    if( pItem->fg.notCte )         sqlite3_str_appendf(&x, " notCte");
32812    if( pItem->fg.isNestedFrom )   sqlite3_str_appendf(&x, " isNestedFrom");
32813
32814    sqlite3StrAccumFinish(&x);
32815    sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1);
32816    n = 0;
32817    if( pItem->pSelect ) n++;
32818    if( pItem->fg.isTabFunc ) n++;
32819    if( pItem->fg.isUsing ) n++;
32820    if( pItem->fg.isUsing ){
32821      sqlite3TreeViewIdList(pView, pItem->u3.pUsing, (--n)>0, "USING");
32822    }
32823    if( pItem->pSelect ){
32824      sqlite3TreeViewPush(&pView, i+1<pSrc->nSrc);
32825      if( pItem->pTab ){
32826        Table *pTab = pItem->pTab;
32827        sqlite3TreeViewColumnList(pView, pTab->aCol, pTab->nCol, 1);
32828      }
32829      assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
32830      sqlite3TreeViewSelect(pView, pItem->pSelect, (--n)>0);
32831      sqlite3TreeViewPop(&pView);
32832    }
32833    if( pItem->fg.isTabFunc ){
32834      sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
32835    }
32836    sqlite3TreeViewPop(&pView);
32837  }
32838}
32839
32840/*
32841** Generate a human-readable description of a Select object.
32842*/
32843SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
32844  int n = 0;
32845  int cnt = 0;
32846  if( p==0 ){
32847    sqlite3TreeViewLine(pView, "nil-SELECT");
32848    return;
32849  }
32850  sqlite3TreeViewPush(&pView, moreToFollow);
32851  if( p->pWith ){
32852    sqlite3TreeViewWith(pView, p->pWith, 1);
32853    cnt = 1;
32854    sqlite3TreeViewPush(&pView, 1);
32855  }
32856  do{
32857    if( p->selFlags & SF_WhereBegin ){
32858      sqlite3TreeViewLine(pView, "sqlite3WhereBegin()");
32859    }else{
32860      sqlite3TreeViewLine(pView,
32861        "SELECT%s%s (%u/%p) selFlags=0x%x nSelectRow=%d",
32862        ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
32863        ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""),
32864        p->selId, p, p->selFlags,
32865        (int)p->nSelectRow
32866      );
32867    }
32868    if( cnt++ ) sqlite3TreeViewPop(&pView);
32869    if( p->pPrior ){
32870      n = 1000;
32871    }else{
32872      n = 0;
32873      if( p->pSrc && p->pSrc->nSrc ) n++;
32874      if( p->pWhere ) n++;
32875      if( p->pGroupBy ) n++;
32876      if( p->pHaving ) n++;
32877      if( p->pOrderBy ) n++;
32878      if( p->pLimit ) n++;
32879#ifndef SQLITE_OMIT_WINDOWFUNC
32880      if( p->pWin ) n++;
32881      if( p->pWinDefn ) n++;
32882#endif
32883    }
32884    if( p->pEList ){
32885      sqlite3TreeViewExprList(pView, p->pEList, n>0, "result-set");
32886    }
32887    n--;
32888#ifndef SQLITE_OMIT_WINDOWFUNC
32889    if( p->pWin ){
32890      Window *pX;
32891      sqlite3TreeViewPush(&pView, (n--)>0);
32892      sqlite3TreeViewLine(pView, "window-functions");
32893      for(pX=p->pWin; pX; pX=pX->pNextWin){
32894        sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0);
32895      }
32896      sqlite3TreeViewPop(&pView);
32897    }
32898#endif
32899    if( p->pSrc && p->pSrc->nSrc ){
32900      sqlite3TreeViewPush(&pView, (n--)>0);
32901      sqlite3TreeViewLine(pView, "FROM");
32902      sqlite3TreeViewSrcList(pView, p->pSrc);
32903      sqlite3TreeViewPop(&pView);
32904    }
32905    if( p->pWhere ){
32906      sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
32907      sqlite3TreeViewExpr(pView, p->pWhere, 0);
32908      sqlite3TreeViewPop(&pView);
32909    }
32910    if( p->pGroupBy ){
32911      sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
32912    }
32913    if( p->pHaving ){
32914      sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
32915      sqlite3TreeViewExpr(pView, p->pHaving, 0);
32916      sqlite3TreeViewPop(&pView);
32917    }
32918#ifndef SQLITE_OMIT_WINDOWFUNC
32919    if( p->pWinDefn ){
32920      Window *pX;
32921      sqlite3TreeViewItem(pView, "WINDOW", (n--)>0);
32922      for(pX=p->pWinDefn; pX; pX=pX->pNextWin){
32923        sqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0);
32924      }
32925      sqlite3TreeViewPop(&pView);
32926    }
32927#endif
32928    if( p->pOrderBy ){
32929      sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
32930    }
32931    if( p->pLimit ){
32932      sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
32933      sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
32934      if( p->pLimit->pRight ){
32935        sqlite3TreeViewItem(pView, "OFFSET", 0);
32936        sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
32937        sqlite3TreeViewPop(&pView);
32938      }
32939      sqlite3TreeViewPop(&pView);
32940    }
32941    if( p->pPrior ){
32942      const char *zOp = "UNION";
32943      switch( p->op ){
32944        case TK_ALL:         zOp = "UNION ALL";  break;
32945        case TK_INTERSECT:   zOp = "INTERSECT";  break;
32946        case TK_EXCEPT:      zOp = "EXCEPT";     break;
32947      }
32948      sqlite3TreeViewItem(pView, zOp, 1);
32949    }
32950    p = p->pPrior;
32951  }while( p!=0 );
32952  sqlite3TreeViewPop(&pView);
32953}
32954
32955#ifndef SQLITE_OMIT_WINDOWFUNC
32956/*
32957** Generate a description of starting or stopping bounds
32958*/
32959SQLITE_PRIVATE void sqlite3TreeViewBound(
32960  TreeView *pView,        /* View context */
32961  u8 eBound,              /* UNBOUNDED, CURRENT, PRECEDING, FOLLOWING */
32962  Expr *pExpr,            /* Value for PRECEDING or FOLLOWING */
32963  u8 moreToFollow         /* True if more to follow */
32964){
32965  switch( eBound ){
32966    case TK_UNBOUNDED: {
32967      sqlite3TreeViewItem(pView, "UNBOUNDED", moreToFollow);
32968      sqlite3TreeViewPop(&pView);
32969      break;
32970    }
32971    case TK_CURRENT: {
32972      sqlite3TreeViewItem(pView, "CURRENT", moreToFollow);
32973      sqlite3TreeViewPop(&pView);
32974      break;
32975    }
32976    case TK_PRECEDING: {
32977      sqlite3TreeViewItem(pView, "PRECEDING", moreToFollow);
32978      sqlite3TreeViewExpr(pView, pExpr, 0);
32979      sqlite3TreeViewPop(&pView);
32980      break;
32981    }
32982    case TK_FOLLOWING: {
32983      sqlite3TreeViewItem(pView, "FOLLOWING", moreToFollow);
32984      sqlite3TreeViewExpr(pView, pExpr, 0);
32985      sqlite3TreeViewPop(&pView);
32986      break;
32987    }
32988  }
32989}
32990#endif /* SQLITE_OMIT_WINDOWFUNC */
32991
32992#ifndef SQLITE_OMIT_WINDOWFUNC
32993/*
32994** Generate a human-readable explanation for a Window object
32995*/
32996SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u8 more){
32997  int nElement = 0;
32998  if( pWin==0 ) return;
32999  if( pWin->pFilter ){
33000    sqlite3TreeViewItem(pView, "FILTER", 1);
33001    sqlite3TreeViewExpr(pView, pWin->pFilter, 0);
33002    sqlite3TreeViewPop(&pView);
33003    if( pWin->eFrmType==TK_FILTER ) return;
33004  }
33005  sqlite3TreeViewPush(&pView, more);
33006  if( pWin->zName ){
33007    sqlite3TreeViewLine(pView, "OVER %s (%p)", pWin->zName, pWin);
33008  }else{
33009    sqlite3TreeViewLine(pView, "OVER (%p)", pWin);
33010  }
33011  if( pWin->zBase )    nElement++;
33012  if( pWin->pOrderBy ) nElement++;
33013  if( pWin->eFrmType!=0 && pWin->eFrmType!=TK_FILTER ) nElement++;
33014  if( pWin->eExclude ) nElement++;
33015  if( pWin->zBase ){
33016    sqlite3TreeViewPush(&pView, (--nElement)>0);
33017    sqlite3TreeViewLine(pView, "window: %s", pWin->zBase);
33018    sqlite3TreeViewPop(&pView);
33019  }
33020  if( pWin->pPartition ){
33021    sqlite3TreeViewExprList(pView, pWin->pPartition, nElement>0,"PARTITION-BY");
33022  }
33023  if( pWin->pOrderBy ){
33024    sqlite3TreeViewExprList(pView, pWin->pOrderBy, (--nElement)>0, "ORDER-BY");
33025  }
33026  if( pWin->eFrmType!=0 && pWin->eFrmType!=TK_FILTER ){
33027    char zBuf[30];
33028    const char *zFrmType = "ROWS";
33029    if( pWin->eFrmType==TK_RANGE ) zFrmType = "RANGE";
33030    if( pWin->eFrmType==TK_GROUPS ) zFrmType = "GROUPS";
33031    sqlite3_snprintf(sizeof(zBuf),zBuf,"%s%s",zFrmType,
33032        pWin->bImplicitFrame ? " (implied)" : "");
33033    sqlite3TreeViewItem(pView, zBuf, (--nElement)>0);
33034    sqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1);
33035    sqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0);
33036    sqlite3TreeViewPop(&pView);
33037  }
33038  if( pWin->eExclude ){
33039    char zBuf[30];
33040    const char *zExclude;
33041    switch( pWin->eExclude ){
33042      case TK_NO:      zExclude = "NO OTHERS";   break;
33043      case TK_CURRENT: zExclude = "CURRENT ROW"; break;
33044      case TK_GROUP:   zExclude = "GROUP";       break;
33045      case TK_TIES:    zExclude = "TIES";        break;
33046      default:
33047        sqlite3_snprintf(sizeof(zBuf),zBuf,"invalid(%d)", pWin->eExclude);
33048        zExclude = zBuf;
33049        break;
33050    }
33051    sqlite3TreeViewPush(&pView, 0);
33052    sqlite3TreeViewLine(pView, "EXCLUDE %s", zExclude);
33053    sqlite3TreeViewPop(&pView);
33054  }
33055  sqlite3TreeViewPop(&pView);
33056}
33057#endif /* SQLITE_OMIT_WINDOWFUNC */
33058
33059#ifndef SQLITE_OMIT_WINDOWFUNC
33060/*
33061** Generate a human-readable explanation for a Window Function object
33062*/
33063SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView *pView, const Window *pWin, u8 more){
33064  if( pWin==0 ) return;
33065  sqlite3TreeViewPush(&pView, more);
33066  sqlite3TreeViewLine(pView, "WINFUNC %s(%d)",
33067                       pWin->pWFunc->zName, pWin->pWFunc->nArg);
33068  sqlite3TreeViewWindow(pView, pWin, 0);
33069  sqlite3TreeViewPop(&pView);
33070}
33071#endif /* SQLITE_OMIT_WINDOWFUNC */
33072
33073/*
33074** Generate a human-readable explanation of an expression tree.
33075*/
33076SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
33077  const char *zBinOp = 0;   /* Binary operator */
33078  const char *zUniOp = 0;   /* Unary operator */
33079  char zFlgs[200];
33080  sqlite3TreeViewPush(&pView, moreToFollow);
33081  if( pExpr==0 ){
33082    sqlite3TreeViewLine(pView, "nil");
33083    sqlite3TreeViewPop(&pView);
33084    return;
33085  }
33086  if( pExpr->flags || pExpr->affExpr || pExpr->vvaFlags || pExpr->pAggInfo ){
33087    StrAccum x;
33088    sqlite3StrAccumInit(&x, 0, zFlgs, sizeof(zFlgs), 0);
33089    sqlite3_str_appendf(&x, " fg.af=%x.%c",
33090      pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n');
33091    if( ExprHasProperty(pExpr, EP_OuterON) ){
33092      sqlite3_str_appendf(&x, " outer.iJoin=%d", pExpr->w.iJoin);
33093    }
33094    if( ExprHasProperty(pExpr, EP_InnerON) ){
33095      sqlite3_str_appendf(&x, " inner.iJoin=%d", pExpr->w.iJoin);
33096    }
33097    if( ExprHasProperty(pExpr, EP_FromDDL) ){
33098      sqlite3_str_appendf(&x, " DDL");
33099    }
33100    if( ExprHasVVAProperty(pExpr, EP_Immutable) ){
33101      sqlite3_str_appendf(&x, " IMMUTABLE");
33102    }
33103    if( pExpr->pAggInfo!=0 ){
33104      sqlite3_str_appendf(&x, " agg-column[%d]", pExpr->iAgg);
33105    }
33106    sqlite3StrAccumFinish(&x);
33107  }else{
33108    zFlgs[0] = 0;
33109  }
33110  switch( pExpr->op ){
33111    case TK_AGG_COLUMN: {
33112      sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
33113            pExpr->iTable, pExpr->iColumn, zFlgs);
33114      break;
33115    }
33116    case TK_COLUMN: {
33117      if( pExpr->iTable<0 ){
33118        /* This only happens when coding check constraints */
33119        char zOp2[16];
33120        if( pExpr->op2 ){
33121          sqlite3_snprintf(sizeof(zOp2),zOp2," op2=0x%02x",pExpr->op2);
33122        }else{
33123          zOp2[0] = 0;
33124        }
33125        sqlite3TreeViewLine(pView, "COLUMN(%d)%s%s",
33126                                    pExpr->iColumn, zFlgs, zOp2);
33127      }else{
33128        assert( ExprUseYTab(pExpr) );
33129        sqlite3TreeViewLine(pView, "{%d:%d} pTab=%p%s",
33130                        pExpr->iTable, pExpr->iColumn,
33131                        pExpr->y.pTab, zFlgs);
33132      }
33133      if( ExprHasProperty(pExpr, EP_FixedCol) ){
33134        sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
33135      }
33136      break;
33137    }
33138    case TK_INTEGER: {
33139      if( pExpr->flags & EP_IntValue ){
33140        sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
33141      }else{
33142        sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
33143      }
33144      break;
33145    }
33146#ifndef SQLITE_OMIT_FLOATING_POINT
33147    case TK_FLOAT: {
33148      assert( !ExprHasProperty(pExpr, EP_IntValue) );
33149      sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
33150      break;
33151    }
33152#endif
33153    case TK_STRING: {
33154      assert( !ExprHasProperty(pExpr, EP_IntValue) );
33155      sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
33156      break;
33157    }
33158    case TK_NULL: {
33159      sqlite3TreeViewLine(pView,"NULL");
33160      break;
33161    }
33162    case TK_TRUEFALSE: {
33163      sqlite3TreeViewLine(pView,"%s%s",
33164         sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE", zFlgs);
33165      break;
33166    }
33167#ifndef SQLITE_OMIT_BLOB_LITERAL
33168    case TK_BLOB: {
33169      assert( !ExprHasProperty(pExpr, EP_IntValue) );
33170      sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
33171      break;
33172    }
33173#endif
33174    case TK_VARIABLE: {
33175      assert( !ExprHasProperty(pExpr, EP_IntValue) );
33176      sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
33177                          pExpr->u.zToken, pExpr->iColumn);
33178      break;
33179    }
33180    case TK_REGISTER: {
33181      sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
33182      break;
33183    }
33184    case TK_ID: {
33185      assert( !ExprHasProperty(pExpr, EP_IntValue) );
33186      sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
33187      break;
33188    }
33189#ifndef SQLITE_OMIT_CAST
33190    case TK_CAST: {
33191      /* Expressions of the form:   CAST(pLeft AS token) */
33192      assert( !ExprHasProperty(pExpr, EP_IntValue) );
33193      sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
33194      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
33195      break;
33196    }
33197#endif /* SQLITE_OMIT_CAST */
33198    case TK_LT:      zBinOp = "LT";     break;
33199    case TK_LE:      zBinOp = "LE";     break;
33200    case TK_GT:      zBinOp = "GT";     break;
33201    case TK_GE:      zBinOp = "GE";     break;
33202    case TK_NE:      zBinOp = "NE";     break;
33203    case TK_EQ:      zBinOp = "EQ";     break;
33204    case TK_IS:      zBinOp = "IS";     break;
33205    case TK_ISNOT:   zBinOp = "ISNOT";  break;
33206    case TK_AND:     zBinOp = "AND";    break;
33207    case TK_OR:      zBinOp = "OR";     break;
33208    case TK_PLUS:    zBinOp = "ADD";    break;
33209    case TK_STAR:    zBinOp = "MUL";    break;
33210    case TK_MINUS:   zBinOp = "SUB";    break;
33211    case TK_REM:     zBinOp = "REM";    break;
33212    case TK_BITAND:  zBinOp = "BITAND"; break;
33213    case TK_BITOR:   zBinOp = "BITOR";  break;
33214    case TK_SLASH:   zBinOp = "DIV";    break;
33215    case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
33216    case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
33217    case TK_CONCAT:  zBinOp = "CONCAT"; break;
33218    case TK_DOT:     zBinOp = "DOT";    break;
33219    case TK_LIMIT:   zBinOp = "LIMIT";  break;
33220
33221    case TK_UMINUS:  zUniOp = "UMINUS"; break;
33222    case TK_UPLUS:   zUniOp = "UPLUS";  break;
33223    case TK_BITNOT:  zUniOp = "BITNOT"; break;
33224    case TK_NOT:     zUniOp = "NOT";    break;
33225    case TK_ISNULL:  zUniOp = "ISNULL"; break;
33226    case TK_NOTNULL: zUniOp = "NOTNULL"; break;
33227
33228    case TK_TRUTH: {
33229      int x;
33230      const char *azOp[] = {
33231         "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE"
33232      };
33233      assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT );
33234      assert( pExpr->pRight );
33235      assert( sqlite3ExprSkipCollateAndLikely(pExpr->pRight)->op
33236                  == TK_TRUEFALSE );
33237      x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight);
33238      zUniOp = azOp[x];
33239      break;
33240    }
33241
33242    case TK_SPAN: {
33243      assert( !ExprHasProperty(pExpr, EP_IntValue) );
33244      sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
33245      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
33246      break;
33247    }
33248
33249    case TK_COLLATE: {
33250      /* COLLATE operators without the EP_Collate flag are intended to
33251      ** emulate collation associated with a table column.  These show
33252      ** up in the treeview output as "SOFT-COLLATE".  Explicit COLLATE
33253      ** operators that appear in the original SQL always have the
33254      ** EP_Collate bit set and appear in treeview output as just "COLLATE" */
33255      assert( !ExprHasProperty(pExpr, EP_IntValue) );
33256      sqlite3TreeViewLine(pView, "%sCOLLATE %Q%s",
33257        !ExprHasProperty(pExpr, EP_Collate) ? "SOFT-" : "",
33258        pExpr->u.zToken, zFlgs);
33259      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
33260      break;
33261    }
33262
33263    case TK_AGG_FUNCTION:
33264    case TK_FUNCTION: {
33265      ExprList *pFarg;       /* List of function arguments */
33266      Window *pWin;
33267      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
33268        pFarg = 0;
33269        pWin = 0;
33270      }else{
33271        assert( ExprUseXList(pExpr) );
33272        pFarg = pExpr->x.pList;
33273#ifndef SQLITE_OMIT_WINDOWFUNC
33274        pWin = IsWindowFunc(pExpr) ? pExpr->y.pWin : 0;
33275#else
33276        pWin = 0;
33277#endif
33278      }
33279      assert( !ExprHasProperty(pExpr, EP_IntValue) );
33280      if( pExpr->op==TK_AGG_FUNCTION ){
33281        sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q%s agg=%d[%d]/%p",
33282                             pExpr->op2, pExpr->u.zToken, zFlgs,
33283                             pExpr->pAggInfo ? pExpr->pAggInfo->selId : 0,
33284                             pExpr->iAgg, pExpr->pAggInfo);
33285      }else if( pExpr->op2!=0 ){
33286        const char *zOp2;
33287        char zBuf[8];
33288        sqlite3_snprintf(sizeof(zBuf),zBuf,"0x%02x",pExpr->op2);
33289        zOp2 = zBuf;
33290        if( pExpr->op2==NC_IsCheck ) zOp2 = "NC_IsCheck";
33291        if( pExpr->op2==NC_IdxExpr ) zOp2 = "NC_IdxExpr";
33292        if( pExpr->op2==NC_PartIdx ) zOp2 = "NC_PartIdx";
33293        if( pExpr->op2==NC_GenCol ) zOp2 = "NC_GenCol";
33294        sqlite3TreeViewLine(pView, "FUNCTION %Q%s op2=%s",
33295                            pExpr->u.zToken, zFlgs, zOp2);
33296      }else{
33297        sqlite3TreeViewLine(pView, "FUNCTION %Q%s", pExpr->u.zToken, zFlgs);
33298      }
33299      if( pFarg ){
33300        sqlite3TreeViewExprList(pView, pFarg, pWin!=0 || pExpr->pLeft, 0);
33301        if( pExpr->pLeft ){
33302          Expr *pOB = pExpr->pLeft;
33303          assert( pOB->op==TK_ORDER );
33304          assert( ExprUseXList(pOB) );
33305          sqlite3TreeViewExprList(pView, pOB->x.pList, pWin!=0, "ORDERBY");
33306        }
33307      }
33308#ifndef SQLITE_OMIT_WINDOWFUNC
33309      if( pWin ){
33310        sqlite3TreeViewWindow(pView, pWin, 0);
33311      }
33312#endif
33313      break;
33314    }
33315    case TK_ORDER: {
33316      sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, "ORDERBY");
33317      break;
33318    }
33319#ifndef SQLITE_OMIT_SUBQUERY
33320    case TK_EXISTS: {
33321      assert( ExprUseXSelect(pExpr) );
33322      sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
33323      sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
33324      break;
33325    }
33326    case TK_SELECT: {
33327      assert( ExprUseXSelect(pExpr) );
33328      sqlite3TreeViewLine(pView, "subquery-expr flags=0x%x", pExpr->flags);
33329      sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
33330      break;
33331    }
33332    case TK_IN: {
33333      sqlite3_str *pStr = sqlite3_str_new(0);
33334      char *z;
33335      sqlite3_str_appendf(pStr, "IN flags=0x%x", pExpr->flags);
33336      if( pExpr->iTable ) sqlite3_str_appendf(pStr, " iTable=%d",pExpr->iTable);
33337      if( ExprHasProperty(pExpr, EP_Subrtn) ){
33338        sqlite3_str_appendf(pStr, " subrtn(%d,%d)",
33339            pExpr->y.sub.regReturn, pExpr->y.sub.iAddr);
33340      }
33341      z = sqlite3_str_finish(pStr);
33342      sqlite3TreeViewLine(pView, z);
33343      sqlite3_free(z);
33344      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
33345      if( ExprUseXSelect(pExpr) ){
33346        sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
33347      }else{
33348        sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
33349      }
33350      break;
33351    }
33352#endif /* SQLITE_OMIT_SUBQUERY */
33353
33354    /*
33355    **    x BETWEEN y AND z
33356    **
33357    ** This is equivalent to
33358    **
33359    **    x>=y AND x<=z
33360    **
33361    ** X is stored in pExpr->pLeft.
33362    ** Y is stored in pExpr->pList->a[0].pExpr.
33363    ** Z is stored in pExpr->pList->a[1].pExpr.
33364    */
33365    case TK_BETWEEN: {
33366      const Expr *pX, *pY, *pZ;
33367      pX = pExpr->pLeft;
33368      assert( ExprUseXList(pExpr) );
33369      assert( pExpr->x.pList->nExpr==2 );
33370      pY = pExpr->x.pList->a[0].pExpr;
33371      pZ = pExpr->x.pList->a[1].pExpr;
33372      sqlite3TreeViewLine(pView, "BETWEEN%s", zFlgs);
33373      sqlite3TreeViewExpr(pView, pX, 1);
33374      sqlite3TreeViewExpr(pView, pY, 1);
33375      sqlite3TreeViewExpr(pView, pZ, 0);
33376      break;
33377    }
33378    case TK_TRIGGER: {
33379      /* If the opcode is TK_TRIGGER, then the expression is a reference
33380      ** to a column in the new.* or old.* pseudo-tables available to
33381      ** trigger programs. In this case Expr.iTable is set to 1 for the
33382      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
33383      ** is set to the column of the pseudo-table to read, or to -1 to
33384      ** read the rowid field.
33385      */
33386      sqlite3TreeViewLine(pView, "%s(%d)",
33387          pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
33388      break;
33389    }
33390    case TK_CASE: {
33391      sqlite3TreeViewLine(pView, "CASE");
33392      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
33393      assert( ExprUseXList(pExpr) );
33394      sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
33395      break;
33396    }
33397#ifndef SQLITE_OMIT_TRIGGER
33398    case TK_RAISE: {
33399      const char *zType = "unk";
33400      switch( pExpr->affExpr ){
33401        case OE_Rollback:   zType = "rollback";  break;
33402        case OE_Abort:      zType = "abort";     break;
33403        case OE_Fail:       zType = "fail";      break;
33404        case OE_Ignore:     zType = "ignore";    break;
33405      }
33406      assert( !ExprHasProperty(pExpr, EP_IntValue) );
33407      sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
33408      break;
33409    }
33410#endif
33411    case TK_MATCH: {
33412      sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
33413                          pExpr->iTable, pExpr->iColumn, zFlgs);
33414      sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
33415      break;
33416    }
33417    case TK_VECTOR: {
33418      char *z = sqlite3_mprintf("VECTOR%s",zFlgs);
33419      assert( ExprUseXList(pExpr) );
33420      sqlite3TreeViewBareExprList(pView, pExpr->x.pList, z);
33421      sqlite3_free(z);
33422      break;
33423    }
33424    case TK_SELECT_COLUMN: {
33425      sqlite3TreeViewLine(pView, "SELECT-COLUMN %d of [0..%d]%s",
33426              pExpr->iColumn, pExpr->iTable-1,
33427              pExpr->pRight==pExpr->pLeft ? " (SELECT-owner)" : "");
33428      assert( ExprUseXSelect(pExpr->pLeft) );
33429      sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
33430      break;
33431    }
33432    case TK_IF_NULL_ROW: {
33433      sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
33434      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
33435      break;
33436    }
33437    case TK_ERROR: {
33438      Expr tmp;
33439      sqlite3TreeViewLine(pView, "ERROR");
33440      tmp = *pExpr;
33441      tmp.op = pExpr->op2;
33442      sqlite3TreeViewExpr(pView, &tmp, 0);
33443      break;
33444    }
33445    case TK_ROW: {
33446      if( pExpr->iColumn<=0 ){
33447        sqlite3TreeViewLine(pView, "First FROM table rowid");
33448      }else{
33449        sqlite3TreeViewLine(pView, "First FROM table column %d",
33450            pExpr->iColumn-1);
33451      }
33452      break;
33453    }
33454    default: {
33455      sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
33456      break;
33457    }
33458  }
33459  if( zBinOp ){
33460    sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
33461    sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
33462    sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
33463  }else if( zUniOp ){
33464    sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
33465   sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
33466  }
33467  sqlite3TreeViewPop(&pView);
33468}
33469
33470
33471/*
33472** Generate a human-readable explanation of an expression list.
33473*/
33474SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
33475  TreeView *pView,
33476  const ExprList *pList,
33477  const char *zLabel
33478){
33479  if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
33480  if( pList==0 ){
33481    sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
33482  }else{
33483    int i;
33484    sqlite3TreeViewLine(pView, "%s", zLabel);
33485    for(i=0; i<pList->nExpr; i++){
33486      int j = pList->a[i].u.x.iOrderByCol;
33487      char *zName = pList->a[i].zEName;
33488      int moreToFollow = i<pList->nExpr - 1;
33489      if( j || zName ){
33490        sqlite3TreeViewPush(&pView, moreToFollow);
33491        moreToFollow = 0;
33492        sqlite3TreeViewLine(pView, 0);
33493        if( zName ){
33494          switch( pList->a[i].fg.eEName ){
33495            default:
33496              fprintf(stdout, "AS %s ", zName);
33497              break;
33498            case ENAME_TAB:
33499              fprintf(stdout, "TABLE-ALIAS-NAME(\"%s\") ", zName);
33500              if( pList->a[i].fg.bUsed ) fprintf(stdout, "(used) ");
33501              if( pList->a[i].fg.bUsingTerm ) fprintf(stdout, "(USING-term) ");
33502              if( pList->a[i].fg.bNoExpand ) fprintf(stdout, "(NoExpand) ");
33503              break;
33504            case ENAME_SPAN:
33505              fprintf(stdout, "SPAN(\"%s\") ", zName);
33506              break;
33507          }
33508        }
33509        if( j ){
33510          fprintf(stdout, "iOrderByCol=%d", j);
33511        }
33512        fprintf(stdout, "\n");
33513        fflush(stdout);
33514      }
33515      sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow);
33516      if( j || zName ){
33517        sqlite3TreeViewPop(&pView);
33518      }
33519    }
33520  }
33521}
33522SQLITE_PRIVATE void sqlite3TreeViewExprList(
33523  TreeView *pView,
33524  const ExprList *pList,
33525  u8 moreToFollow,
33526  const char *zLabel
33527){
33528  sqlite3TreeViewPush(&pView, moreToFollow);
33529  sqlite3TreeViewBareExprList(pView, pList, zLabel);
33530  sqlite3TreeViewPop(&pView);
33531}
33532
33533/*
33534** Generate a human-readable explanation of an id-list.
33535*/
33536SQLITE_PRIVATE void sqlite3TreeViewBareIdList(
33537  TreeView *pView,
33538  const IdList *pList,
33539  const char *zLabel
33540){
33541  if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
33542  if( pList==0 ){
33543    sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
33544  }else{
33545    int i;
33546    sqlite3TreeViewLine(pView, "%s", zLabel);
33547    for(i=0; i<pList->nId; i++){
33548      char *zName = pList->a[i].zName;
33549      int moreToFollow = i<pList->nId - 1;
33550      if( zName==0 ) zName = "(null)";
33551      sqlite3TreeViewPush(&pView, moreToFollow);
33552      sqlite3TreeViewLine(pView, 0);
33553      if( pList->eU4==EU4_NONE ){
33554        fprintf(stdout, "%s\n", zName);
33555      }else if( pList->eU4==EU4_IDX ){
33556        fprintf(stdout, "%s (%d)\n", zName, pList->a[i].u4.idx);
33557      }else{
33558        assert( pList->eU4==EU4_EXPR );
33559        if( pList->a[i].u4.pExpr==0 ){
33560          fprintf(stdout, "%s (pExpr=NULL)\n", zName);
33561        }else{
33562          fprintf(stdout, "%s\n", zName);
33563          sqlite3TreeViewPush(&pView, i<pList->nId-1);
33564          sqlite3TreeViewExpr(pView, pList->a[i].u4.pExpr, 0);
33565          sqlite3TreeViewPop(&pView);
33566        }
33567      }
33568      sqlite3TreeViewPop(&pView);
33569    }
33570  }
33571}
33572SQLITE_PRIVATE void sqlite3TreeViewIdList(
33573  TreeView *pView,
33574  const IdList *pList,
33575  u8 moreToFollow,
33576  const char *zLabel
33577){
33578  sqlite3TreeViewPush(&pView, moreToFollow);
33579  sqlite3TreeViewBareIdList(pView, pList, zLabel);
33580  sqlite3TreeViewPop(&pView);
33581}
33582
33583/*
33584** Generate a human-readable explanation of a list of Upsert objects
33585*/
33586SQLITE_PRIVATE void sqlite3TreeViewUpsert(
33587  TreeView *pView,
33588  const Upsert *pUpsert,
33589  u8 moreToFollow
33590){
33591  if( pUpsert==0 ) return;
33592  sqlite3TreeViewPush(&pView, moreToFollow);
33593  while( pUpsert ){
33594    int n;
33595    sqlite3TreeViewPush(&pView, pUpsert->pNextUpsert!=0 || moreToFollow);
33596    sqlite3TreeViewLine(pView, "ON CONFLICT DO %s",
33597         pUpsert->isDoUpdate ? "UPDATE" : "NOTHING");
33598    n = (pUpsert->pUpsertSet!=0) + (pUpsert->pUpsertWhere!=0);
33599    sqlite3TreeViewExprList(pView, pUpsert->pUpsertTarget, (n--)>0, "TARGET");
33600    sqlite3TreeViewExprList(pView, pUpsert->pUpsertSet, (n--)>0, "SET");
33601    if( pUpsert->pUpsertWhere ){
33602      sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
33603      sqlite3TreeViewExpr(pView, pUpsert->pUpsertWhere, 0);
33604      sqlite3TreeViewPop(&pView);
33605    }
33606    sqlite3TreeViewPop(&pView);
33607    pUpsert = pUpsert->pNextUpsert;
33608  }
33609  sqlite3TreeViewPop(&pView);
33610}
33611
33612#if TREETRACE_ENABLED
33613/*
33614** Generate a human-readable diagram of the data structure that go
33615** into generating an DELETE statement.
33616*/
33617SQLITE_PRIVATE void sqlite3TreeViewDelete(
33618  const With *pWith,
33619  const SrcList *pTabList,
33620  const Expr *pWhere,
33621  const ExprList *pOrderBy,
33622  const Expr *pLimit,
33623  const Trigger *pTrigger
33624){
33625  int n = 0;
33626  TreeView *pView = 0;
33627  sqlite3TreeViewPush(&pView, 0);
33628  sqlite3TreeViewLine(pView, "DELETE");
33629  if( pWith ) n++;
33630  if( pTabList ) n++;
33631  if( pWhere ) n++;
33632  if( pOrderBy ) n++;
33633  if( pLimit ) n++;
33634  if( pTrigger ) n++;
33635  if( pWith ){
33636    sqlite3TreeViewPush(&pView, (--n)>0);
33637    sqlite3TreeViewWith(pView, pWith, 0);
33638    sqlite3TreeViewPop(&pView);
33639  }
33640  if( pTabList ){
33641    sqlite3TreeViewPush(&pView, (--n)>0);
33642    sqlite3TreeViewLine(pView, "FROM");
33643    sqlite3TreeViewSrcList(pView, pTabList);
33644    sqlite3TreeViewPop(&pView);
33645  }
33646  if( pWhere ){
33647    sqlite3TreeViewPush(&pView, (--n)>0);
33648    sqlite3TreeViewLine(pView, "WHERE");
33649    sqlite3TreeViewExpr(pView, pWhere, 0);
33650    sqlite3TreeViewPop(&pView);
33651  }
33652  if( pOrderBy ){
33653    sqlite3TreeViewExprList(pView, pOrderBy, (--n)>0, "ORDER-BY");
33654  }
33655  if( pLimit ){
33656    sqlite3TreeViewPush(&pView, (--n)>0);
33657    sqlite3TreeViewLine(pView, "LIMIT");
33658    sqlite3TreeViewExpr(pView, pLimit, 0);
33659    sqlite3TreeViewPop(&pView);
33660  }
33661  if( pTrigger ){
33662    sqlite3TreeViewTrigger(pView, pTrigger, (--n)>0, 1);
33663  }
33664  sqlite3TreeViewPop(&pView);
33665}
33666#endif /* TREETRACE_ENABLED */
33667
33668#if TREETRACE_ENABLED
33669/*
33670** Generate a human-readable diagram of the data structure that go
33671** into generating an INSERT statement.
33672*/
33673SQLITE_PRIVATE void sqlite3TreeViewInsert(
33674  const With *pWith,
33675  const SrcList *pTabList,
33676  const IdList *pColumnList,
33677  const Select *pSelect,
33678  const ExprList *pExprList,
33679  int onError,
33680  const Upsert *pUpsert,
33681  const Trigger *pTrigger
33682){
33683  TreeView *pView = 0;
33684  int n = 0;
33685  const char *zLabel = "INSERT";
33686  switch( onError ){
33687    case OE_Replace:  zLabel = "REPLACE";             break;
33688    case OE_Ignore:   zLabel = "INSERT OR IGNORE";    break;
33689    case OE_Rollback: zLabel = "INSERT OR ROLLBACK";  break;
33690    case OE_Abort:    zLabel = "INSERT OR ABORT";     break;
33691    case OE_Fail:     zLabel = "INSERT OR FAIL";      break;
33692  }
33693  sqlite3TreeViewPush(&pView, 0);
33694  sqlite3TreeViewLine(pView, zLabel);
33695  if( pWith ) n++;
33696  if( pTabList ) n++;
33697  if( pColumnList ) n++;
33698  if( pSelect ) n++;
33699  if( pExprList ) n++;
33700  if( pUpsert ) n++;
33701  if( pTrigger ) n++;
33702  if( pWith ){
33703    sqlite3TreeViewPush(&pView, (--n)>0);
33704    sqlite3TreeViewWith(pView, pWith, 0);
33705    sqlite3TreeViewPop(&pView);
33706  }
33707  if( pTabList ){
33708    sqlite3TreeViewPush(&pView, (--n)>0);
33709    sqlite3TreeViewLine(pView, "INTO");
33710    sqlite3TreeViewSrcList(pView, pTabList);
33711    sqlite3TreeViewPop(&pView);
33712  }
33713  if( pColumnList ){
33714    sqlite3TreeViewIdList(pView, pColumnList, (--n)>0, "COLUMNS");
33715  }
33716  if( pSelect ){
33717    sqlite3TreeViewPush(&pView, (--n)>0);
33718    sqlite3TreeViewLine(pView, "DATA-SOURCE");
33719    sqlite3TreeViewSelect(pView, pSelect, 0);
33720    sqlite3TreeViewPop(&pView);
33721  }
33722  if( pExprList ){
33723    sqlite3TreeViewExprList(pView, pExprList, (--n)>0, "VALUES");
33724  }
33725  if( pUpsert ){
33726    sqlite3TreeViewPush(&pView, (--n)>0);
33727    sqlite3TreeViewLine(pView, "UPSERT");
33728    sqlite3TreeViewUpsert(pView, pUpsert, 0);
33729    sqlite3TreeViewPop(&pView);
33730  }
33731  if( pTrigger ){
33732    sqlite3TreeViewTrigger(pView, pTrigger, (--n)>0, 1);
33733  }
33734  sqlite3TreeViewPop(&pView);
33735}
33736#endif /* TREETRACE_ENABLED */
33737
33738#if TREETRACE_ENABLED
33739/*
33740** Generate a human-readable diagram of the data structure that go
33741** into generating an UPDATE statement.
33742*/
33743SQLITE_PRIVATE void sqlite3TreeViewUpdate(
33744  const With *pWith,
33745  const SrcList *pTabList,
33746  const ExprList *pChanges,
33747  const Expr *pWhere,
33748  int onError,
33749  const ExprList *pOrderBy,
33750  const Expr *pLimit,
33751  const Upsert *pUpsert,
33752  const Trigger *pTrigger
33753){
33754  int n = 0;
33755  TreeView *pView = 0;
33756  const char *zLabel = "UPDATE";
33757  switch( onError ){
33758    case OE_Replace:  zLabel = "UPDATE OR REPLACE";   break;
33759    case OE_Ignore:   zLabel = "UPDATE OR IGNORE";    break;
33760    case OE_Rollback: zLabel = "UPDATE OR ROLLBACK";  break;
33761    case OE_Abort:    zLabel = "UPDATE OR ABORT";     break;
33762    case OE_Fail:     zLabel = "UPDATE OR FAIL";      break;
33763  }
33764  sqlite3TreeViewPush(&pView, 0);
33765  sqlite3TreeViewLine(pView, zLabel);
33766  if( pWith ) n++;
33767  if( pTabList ) n++;
33768  if( pChanges ) n++;
33769  if( pWhere ) n++;
33770  if( pOrderBy ) n++;
33771  if( pLimit ) n++;
33772  if( pUpsert ) n++;
33773  if( pTrigger ) n++;
33774  if( pWith ){
33775    sqlite3TreeViewPush(&pView, (--n)>0);
33776    sqlite3TreeViewWith(pView, pWith, 0);
33777    sqlite3TreeViewPop(&pView);
33778  }
33779  if( pTabList ){
33780    sqlite3TreeViewPush(&pView, (--n)>0);
33781    sqlite3TreeViewLine(pView, "FROM");
33782    sqlite3TreeViewSrcList(pView, pTabList);
33783    sqlite3TreeViewPop(&pView);
33784  }
33785  if( pChanges ){
33786    sqlite3TreeViewExprList(pView, pChanges, (--n)>0, "SET");
33787  }
33788  if( pWhere ){
33789    sqlite3TreeViewPush(&pView, (--n)>0);
33790    sqlite3TreeViewLine(pView, "WHERE");
33791    sqlite3TreeViewExpr(pView, pWhere, 0);
33792    sqlite3TreeViewPop(&pView);
33793  }
33794  if( pOrderBy ){
33795    sqlite3TreeViewExprList(pView, pOrderBy, (--n)>0, "ORDER-BY");
33796  }
33797  if( pLimit ){
33798    sqlite3TreeViewPush(&pView, (--n)>0);
33799    sqlite3TreeViewLine(pView, "LIMIT");
33800    sqlite3TreeViewExpr(pView, pLimit, 0);
33801    sqlite3TreeViewPop(&pView);
33802  }
33803  if( pUpsert ){
33804    sqlite3TreeViewPush(&pView, (--n)>0);
33805    sqlite3TreeViewLine(pView, "UPSERT");
33806    sqlite3TreeViewUpsert(pView, pUpsert, 0);
33807    sqlite3TreeViewPop(&pView);
33808  }
33809  if( pTrigger ){
33810    sqlite3TreeViewTrigger(pView, pTrigger, (--n)>0, 1);
33811  }
33812  sqlite3TreeViewPop(&pView);
33813}
33814#endif /* TREETRACE_ENABLED */
33815
33816#ifndef SQLITE_OMIT_TRIGGER
33817/*
33818** Show a human-readable graph of a TriggerStep
33819*/
33820SQLITE_PRIVATE void sqlite3TreeViewTriggerStep(
33821  TreeView *pView,
33822  const TriggerStep *pStep,
33823  u8 moreToFollow,
33824  u8 showFullList
33825){
33826  int cnt = 0;
33827  if( pStep==0 ) return;
33828  sqlite3TreeViewPush(&pView,
33829      moreToFollow || (showFullList && pStep->pNext!=0));
33830  do{
33831    if( cnt++ && pStep->pNext==0 ){
33832      sqlite3TreeViewPop(&pView);
33833      sqlite3TreeViewPush(&pView, 0);
33834    }
33835    sqlite3TreeViewLine(pView, "%s", pStep->zSpan ? pStep->zSpan : "RETURNING");
33836  }while( showFullList && (pStep = pStep->pNext)!=0 );
33837  sqlite3TreeViewPop(&pView);
33838}
33839
33840/*
33841** Show a human-readable graph of a Trigger
33842*/
33843SQLITE_PRIVATE void sqlite3TreeViewTrigger(
33844  TreeView *pView,
33845  const Trigger *pTrigger,
33846  u8 moreToFollow,
33847  u8 showFullList
33848){
33849  int cnt = 0;
33850  if( pTrigger==0 ) return;
33851  sqlite3TreeViewPush(&pView,
33852     moreToFollow || (showFullList && pTrigger->pNext!=0));
33853  do{
33854    if( cnt++ && pTrigger->pNext==0 ){
33855      sqlite3TreeViewPop(&pView);
33856      sqlite3TreeViewPush(&pView, 0);
33857    }
33858    sqlite3TreeViewLine(pView, "TRIGGER %s", pTrigger->zName);
33859    sqlite3TreeViewPush(&pView, 0);
33860    sqlite3TreeViewTriggerStep(pView, pTrigger->step_list, 0, 1);
33861    sqlite3TreeViewPop(&pView);
33862  }while( showFullList && (pTrigger = pTrigger->pNext)!=0 );
33863  sqlite3TreeViewPop(&pView);
33864}
33865#endif /* SQLITE_OMIT_TRIGGER */
33866
33867
33868/*
33869** These simplified versions of the tree-view routines omit unnecessary
33870** parameters.  These variants are intended to be used from a symbolic
33871** debugger, such as "gdb", during interactive debugging sessions.
33872**
33873** This routines are given external linkage so that they will always be
33874** accessible to the debugging, and to avoid warnings about unused
33875** functions.  But these routines only exist in debugging builds, so they
33876** do not contaminate the interface.
33877*/
33878SQLITE_PRIVATE void sqlite3ShowExpr(const Expr *p){ sqlite3TreeViewExpr(0,p,0); }
33879SQLITE_PRIVATE void sqlite3ShowExprList(const ExprList *p){ sqlite3TreeViewExprList(0,p,0,0);}
33880SQLITE_PRIVATE void sqlite3ShowIdList(const IdList *p){ sqlite3TreeViewIdList(0,p,0,0); }
33881SQLITE_PRIVATE void sqlite3ShowSrcList(const SrcList *p){ sqlite3TreeViewSrcList(0,p); }
33882SQLITE_PRIVATE void sqlite3ShowSelect(const Select *p){ sqlite3TreeViewSelect(0,p,0); }
33883SQLITE_PRIVATE void sqlite3ShowWith(const With *p){ sqlite3TreeViewWith(0,p,0); }
33884SQLITE_PRIVATE void sqlite3ShowUpsert(const Upsert *p){ sqlite3TreeViewUpsert(0,p,0); }
33885#ifndef SQLITE_OMIT_TRIGGER
33886SQLITE_PRIVATE void sqlite3ShowTriggerStep(const TriggerStep *p){
33887  sqlite3TreeViewTriggerStep(0,p,0,0);
33888}
33889SQLITE_PRIVATE void sqlite3ShowTriggerStepList(const TriggerStep *p){
33890  sqlite3TreeViewTriggerStep(0,p,0,1);
33891}
33892SQLITE_PRIVATE void sqlite3ShowTrigger(const Trigger *p){ sqlite3TreeViewTrigger(0,p,0,0); }
33893SQLITE_PRIVATE void sqlite3ShowTriggerList(const Trigger *p){ sqlite3TreeViewTrigger(0,p,0,1);}
33894#endif
33895#ifndef SQLITE_OMIT_WINDOWFUNC
33896SQLITE_PRIVATE void sqlite3ShowWindow(const Window *p){ sqlite3TreeViewWindow(0,p,0); }
33897SQLITE_PRIVATE void sqlite3ShowWinFunc(const Window *p){ sqlite3TreeViewWinFunc(0,p,0); }
33898#endif
33899
33900#endif /* SQLITE_DEBUG */
33901
33902/************** End of treeview.c ********************************************/
33903/************** Begin file random.c ******************************************/
33904/*
33905** 2001 September 15
33906**
33907** The author disclaims copyright to this source code.  In place of
33908** a legal notice, here is a blessing:
33909**
33910**    May you do good and not evil.
33911**    May you find forgiveness for yourself and forgive others.
33912**    May you share freely, never taking more than you give.
33913**
33914*************************************************************************
33915** This file contains code to implement a pseudo-random number
33916** generator (PRNG) for SQLite.
33917**
33918** Random numbers are used by some of the database backends in order
33919** to generate random integer keys for tables or random filenames.
33920*/
33921/* #include "sqliteInt.h" */
33922
33923
33924/* All threads share a single random number generator.
33925** This structure is the current state of the generator.
33926*/
33927static SQLITE_WSD struct sqlite3PrngType {
33928  u32 s[16];                 /* 64 bytes of chacha20 state */
33929  u8 out[64];                /* Output bytes */
33930  u8 n;                      /* Output bytes remaining */
33931} sqlite3Prng;
33932
33933
33934/* The RFC-7539 ChaCha20 block function
33935*/
33936#define ROTL(a,b) (((a) << (b)) | ((a) >> (32 - (b))))
33937#define QR(a, b, c, d) ( \
33938    a += b, d ^= a, d = ROTL(d,16), \
33939    c += d, b ^= c, b = ROTL(b,12), \
33940    a += b, d ^= a, d = ROTL(d, 8), \
33941    c += d, b ^= c, b = ROTL(b, 7))
33942static void chacha_block(u32 *out, const u32 *in){
33943  int i;
33944  u32 x[16];
33945  memcpy(x, in, 64);
33946  for(i=0; i<10; i++){
33947    QR(x[0], x[4], x[ 8], x[12]);
33948    QR(x[1], x[5], x[ 9], x[13]);
33949    QR(x[2], x[6], x[10], x[14]);
33950    QR(x[3], x[7], x[11], x[15]);
33951    QR(x[0], x[5], x[10], x[15]);
33952    QR(x[1], x[6], x[11], x[12]);
33953    QR(x[2], x[7], x[ 8], x[13]);
33954    QR(x[3], x[4], x[ 9], x[14]);
33955  }
33956  for(i=0; i<16; i++) out[i] = x[i]+in[i];
33957}
33958
33959/*
33960** Return N random bytes.
33961*/
33962SQLITE_API void sqlite3_randomness(int N, void *pBuf){
33963  unsigned char *zBuf = pBuf;
33964
33965  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
33966  ** state vector.  If writable static data is unsupported on the target,
33967  ** we have to locate the state vector at run-time.  In the more common
33968  ** case where writable static data is supported, wsdPrng can refer directly
33969  ** to the "sqlite3Prng" state vector declared above.
33970  */
33971#ifdef SQLITE_OMIT_WSD
33972  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
33973# define wsdPrng p[0]
33974#else
33975# define wsdPrng sqlite3Prng
33976#endif
33977
33978#if SQLITE_THREADSAFE
33979  sqlite3_mutex *mutex;
33980#endif
33981
33982#ifndef SQLITE_OMIT_AUTOINIT
33983  if( sqlite3_initialize() ) return;
33984#endif
33985
33986#if SQLITE_THREADSAFE
33987  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
33988#endif
33989
33990  sqlite3_mutex_enter(mutex);
33991  if( N<=0 || pBuf==0 ){
33992    wsdPrng.s[0] = 0;
33993    sqlite3_mutex_leave(mutex);
33994    return;
33995  }
33996
33997  /* Initialize the state of the random number generator once,
33998  ** the first time this routine is called.
33999  */
34000  if( wsdPrng.s[0]==0 ){
34001    sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
34002    static const u32 chacha20_init[] = {
34003      0x61707865, 0x3320646e, 0x79622d32, 0x6b206574
34004    };
34005    memcpy(&wsdPrng.s[0], chacha20_init, 16);
34006    if( NEVER(pVfs==0) ){
34007      memset(&wsdPrng.s[4], 0, 44);
34008    }else{
34009      sqlite3OsRandomness(pVfs, 44, (char*)&wsdPrng.s[4]);
34010    }
34011    wsdPrng.s[15] = wsdPrng.s[12];
34012    wsdPrng.s[12] = 0;
34013    wsdPrng.n = 0;
34014  }
34015
34016  assert( N>0 );
34017  while( 1 /* exit by break */ ){
34018    if( N<=wsdPrng.n ){
34019      memcpy(zBuf, &wsdPrng.out[wsdPrng.n-N], N);
34020      wsdPrng.n -= N;
34021      break;
34022    }
34023    if( wsdPrng.n>0 ){
34024      memcpy(zBuf, wsdPrng.out, wsdPrng.n);
34025      N -= wsdPrng.n;
34026      zBuf += wsdPrng.n;
34027    }
34028    wsdPrng.s[12]++;
34029    chacha_block((u32*)wsdPrng.out, wsdPrng.s);
34030    wsdPrng.n = 64;
34031  }
34032  sqlite3_mutex_leave(mutex);
34033}
34034
34035#ifndef SQLITE_UNTESTABLE
34036/*
34037** For testing purposes, we sometimes want to preserve the state of
34038** PRNG and restore the PRNG to its saved state at a later time, or
34039** to reset the PRNG to its initial state.  These routines accomplish
34040** those tasks.
34041**
34042** The sqlite3_test_control() interface calls these routines to
34043** control the PRNG.
34044*/
34045static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
34046SQLITE_PRIVATE void sqlite3PrngSaveState(void){
34047  memcpy(
34048    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
34049    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
34050    sizeof(sqlite3Prng)
34051  );
34052}
34053SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
34054  memcpy(
34055    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
34056    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
34057    sizeof(sqlite3Prng)
34058  );
34059}
34060#endif /* SQLITE_UNTESTABLE */
34061
34062/************** End of random.c **********************************************/
34063/************** Begin file threads.c *****************************************/
34064/*
34065** 2012 July 21
34066**
34067** The author disclaims copyright to this source code.  In place of
34068** a legal notice, here is a blessing:
34069**
34070**    May you do good and not evil.
34071**    May you find forgiveness for yourself and forgive others.
34072**    May you share freely, never taking more than you give.
34073**
34074******************************************************************************
34075**
34076** This file presents a simple cross-platform threading interface for
34077** use internally by SQLite.
34078**
34079** A "thread" can be created using sqlite3ThreadCreate().  This thread
34080** runs independently of its creator until it is joined using
34081** sqlite3ThreadJoin(), at which point it terminates.
34082**
34083** Threads do not have to be real.  It could be that the work of the
34084** "thread" is done by the main thread at either the sqlite3ThreadCreate()
34085** or sqlite3ThreadJoin() call.  This is, in fact, what happens in
34086** single threaded systems.  Nothing in SQLite requires multiple threads.
34087** This interface exists so that applications that want to take advantage
34088** of multiple cores can do so, while also allowing applications to stay
34089** single-threaded if desired.
34090*/
34091/* #include "sqliteInt.h" */
34092#if SQLITE_OS_WIN
34093/* #  include "os_win.h" */
34094#endif
34095
34096#if SQLITE_MAX_WORKER_THREADS>0
34097
34098/********************************* Unix Pthreads ****************************/
34099#if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
34100
34101#define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
34102/* #include <pthread.h> */
34103
34104/* A running thread */
34105struct SQLiteThread {
34106  pthread_t tid;                 /* Thread ID */
34107  int done;                      /* Set to true when thread finishes */
34108  void *pOut;                    /* Result returned by the thread */
34109  void *(*xTask)(void*);         /* The thread routine */
34110  void *pIn;                     /* Argument to the thread */
34111};
34112
34113/* Create a new thread */
34114SQLITE_PRIVATE int sqlite3ThreadCreate(
34115  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
34116  void *(*xTask)(void*),    /* Routine to run in a separate thread */
34117  void *pIn                 /* Argument passed into xTask() */
34118){
34119  SQLiteThread *p;
34120  int rc;
34121
34122  assert( ppThread!=0 );
34123  assert( xTask!=0 );
34124  /* This routine is never used in single-threaded mode */
34125  assert( sqlite3GlobalConfig.bCoreMutex!=0 );
34126
34127  *ppThread = 0;
34128  p = sqlite3Malloc(sizeof(*p));
34129  if( p==0 ) return SQLITE_NOMEM_BKPT;
34130  memset(p, 0, sizeof(*p));
34131  p->xTask = xTask;
34132  p->pIn = pIn;
34133  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
34134  ** function that returns SQLITE_ERROR when passed the argument 200, that
34135  ** forces worker threads to run sequentially and deterministically
34136  ** for testing purposes. */
34137  if( sqlite3FaultSim(200) ){
34138    rc = 1;
34139  }else{
34140    rc = pthread_create(&p->tid, 0, xTask, pIn);
34141  }
34142  if( rc ){
34143    p->done = 1;
34144    p->pOut = xTask(pIn);
34145  }
34146  *ppThread = p;
34147  return SQLITE_OK;
34148}
34149
34150/* Get the results of the thread */
34151SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
34152  int rc;
34153
34154  assert( ppOut!=0 );
34155  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
34156  if( p->done ){
34157    *ppOut = p->pOut;
34158    rc = SQLITE_OK;
34159  }else{
34160    rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
34161  }
34162  sqlite3_free(p);
34163  return rc;
34164}
34165
34166#endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
34167/******************************** End Unix Pthreads *************************/
34168
34169
34170/********************************* Win32 Threads ****************************/
34171#if SQLITE_OS_WIN_THREADS
34172
34173#define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
34174#include <process.h>
34175
34176/* A running thread */
34177struct SQLiteThread {
34178  void *tid;               /* The thread handle */
34179  unsigned id;             /* The thread identifier */
34180  void *(*xTask)(void*);   /* The routine to run as a thread */
34181  void *pIn;               /* Argument to xTask */
34182  void *pResult;           /* Result of xTask */
34183};
34184
34185/* Thread procedure Win32 compatibility shim */
34186static unsigned __stdcall sqlite3ThreadProc(
34187  void *pArg  /* IN: Pointer to the SQLiteThread structure */
34188){
34189  SQLiteThread *p = (SQLiteThread *)pArg;
34190
34191  assert( p!=0 );
34192#if 0
34193  /*
34194  ** This assert appears to trigger spuriously on certain
34195  ** versions of Windows, possibly due to _beginthreadex()
34196  ** and/or CreateThread() not fully setting their thread
34197  ** ID parameter before starting the thread.
34198  */
34199  assert( p->id==GetCurrentThreadId() );
34200#endif
34201  assert( p->xTask!=0 );
34202  p->pResult = p->xTask(p->pIn);
34203
34204  _endthreadex(0);
34205  return 0; /* NOT REACHED */
34206}
34207
34208/* Create a new thread */
34209SQLITE_PRIVATE int sqlite3ThreadCreate(
34210  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
34211  void *(*xTask)(void*),    /* Routine to run in a separate thread */
34212  void *pIn                 /* Argument passed into xTask() */
34213){
34214  SQLiteThread *p;
34215
34216  assert( ppThread!=0 );
34217  assert( xTask!=0 );
34218  *ppThread = 0;
34219  p = sqlite3Malloc(sizeof(*p));
34220  if( p==0 ) return SQLITE_NOMEM_BKPT;
34221  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
34222  ** function that returns SQLITE_ERROR when passed the argument 200, that
34223  ** forces worker threads to run sequentially and deterministically
34224  ** (via the sqlite3FaultSim() term of the conditional) for testing
34225  ** purposes. */
34226  if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
34227    memset(p, 0, sizeof(*p));
34228  }else{
34229    p->xTask = xTask;
34230    p->pIn = pIn;
34231    p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
34232    if( p->tid==0 ){
34233      memset(p, 0, sizeof(*p));
34234    }
34235  }
34236  if( p->xTask==0 ){
34237    p->id = GetCurrentThreadId();
34238    p->pResult = xTask(pIn);
34239  }
34240  *ppThread = p;
34241  return SQLITE_OK;
34242}
34243
34244SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
34245
34246/* Get the results of the thread */
34247SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
34248  DWORD rc;
34249  BOOL bRc;
34250
34251  assert( ppOut!=0 );
34252  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
34253  if( p->xTask==0 ){
34254    /* assert( p->id==GetCurrentThreadId() ); */
34255    rc = WAIT_OBJECT_0;
34256    assert( p->tid==0 );
34257  }else{
34258    assert( p->id!=0 && p->id!=GetCurrentThreadId() );
34259    rc = sqlite3Win32Wait((HANDLE)p->tid);
34260    assert( rc!=WAIT_IO_COMPLETION );
34261    bRc = CloseHandle((HANDLE)p->tid);
34262    assert( bRc );
34263  }
34264  if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
34265  sqlite3_free(p);
34266  return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
34267}
34268
34269#endif /* SQLITE_OS_WIN_THREADS */
34270/******************************** End Win32 Threads *************************/
34271
34272
34273/********************************* Single-Threaded **************************/
34274#ifndef SQLITE_THREADS_IMPLEMENTED
34275/*
34276** This implementation does not actually create a new thread.  It does the
34277** work of the thread in the main thread, when either the thread is created
34278** or when it is joined
34279*/
34280
34281/* A running thread */
34282struct SQLiteThread {
34283  void *(*xTask)(void*);   /* The routine to run as a thread */
34284  void *pIn;               /* Argument to xTask */
34285  void *pResult;           /* Result of xTask */
34286};
34287
34288/* Create a new thread */
34289SQLITE_PRIVATE int sqlite3ThreadCreate(
34290  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
34291  void *(*xTask)(void*),    /* Routine to run in a separate thread */
34292  void *pIn                 /* Argument passed into xTask() */
34293){
34294  SQLiteThread *p;
34295
34296  assert( ppThread!=0 );
34297  assert( xTask!=0 );
34298  *ppThread = 0;
34299  p = sqlite3Malloc(sizeof(*p));
34300  if( p==0 ) return SQLITE_NOMEM_BKPT;
34301  if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
34302    p->xTask = xTask;
34303    p->pIn = pIn;
34304  }else{
34305    p->xTask = 0;
34306    p->pResult = xTask(pIn);
34307  }
34308  *ppThread = p;
34309  return SQLITE_OK;
34310}
34311
34312/* Get the results of the thread */
34313SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
34314
34315  assert( ppOut!=0 );
34316  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
34317  if( p->xTask ){
34318    *ppOut = p->xTask(p->pIn);
34319  }else{
34320    *ppOut = p->pResult;
34321  }
34322  sqlite3_free(p);
34323
34324#if defined(SQLITE_TEST)
34325  {
34326    void *pTstAlloc = sqlite3Malloc(10);
34327    if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
34328    sqlite3_free(pTstAlloc);
34329  }
34330#endif
34331
34332  return SQLITE_OK;
34333}
34334
34335#endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
34336/****************************** End Single-Threaded *************************/
34337#endif /* SQLITE_MAX_WORKER_THREADS>0 */
34338
34339/************** End of threads.c *********************************************/
34340/************** Begin file utf.c *********************************************/
34341/*
34342** 2004 April 13
34343**
34344** The author disclaims copyright to this source code.  In place of
34345** a legal notice, here is a blessing:
34346**
34347**    May you do good and not evil.
34348**    May you find forgiveness for yourself and forgive others.
34349**    May you share freely, never taking more than you give.
34350**
34351*************************************************************************
34352** This file contains routines used to translate between UTF-8,
34353** UTF-16, UTF-16BE, and UTF-16LE.
34354**
34355** Notes on UTF-8:
34356**
34357**   Byte-0    Byte-1    Byte-2    Byte-3    Value
34358**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
34359**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
34360**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
34361**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
34362**
34363**
34364** Notes on UTF-16:  (with wwww+1==uuuuu)
34365**
34366**      Word-0               Word-1          Value
34367**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
34368**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
34369**
34370**
34371** BOM or Byte Order Mark:
34372**     0xff 0xfe   little-endian utf-16 follows
34373**     0xfe 0xff   big-endian utf-16 follows
34374**
34375*/
34376/* #include "sqliteInt.h" */
34377/* #include <assert.h> */
34378/* #include "vdbeInt.h" */
34379
34380#if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
34381/*
34382** The following constant value is used by the SQLITE_BIGENDIAN and
34383** SQLITE_LITTLEENDIAN macros.
34384*/
34385SQLITE_PRIVATE const int sqlite3one = 1;
34386#endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
34387
34388/*
34389** This lookup table is used to help decode the first byte of
34390** a multi-byte UTF8 character.
34391*/
34392static const unsigned char sqlite3Utf8Trans1[] = {
34393  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
34394  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
34395  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
34396  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
34397  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
34398  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
34399  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
34400  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
34401};
34402
34403
34404#define WRITE_UTF8(zOut, c) {                          \
34405  if( c<0x00080 ){                                     \
34406    *zOut++ = (u8)(c&0xFF);                            \
34407  }                                                    \
34408  else if( c<0x00800 ){                                \
34409    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
34410    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
34411  }                                                    \
34412  else if( c<0x10000 ){                                \
34413    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
34414    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
34415    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
34416  }else{                                               \
34417    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
34418    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
34419    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
34420    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
34421  }                                                    \
34422}
34423
34424#define WRITE_UTF16LE(zOut, c) {                                    \
34425  if( c<=0xFFFF ){                                                  \
34426    *zOut++ = (u8)(c&0x00FF);                                       \
34427    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
34428  }else{                                                            \
34429    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
34430    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
34431    *zOut++ = (u8)(c&0x00FF);                                       \
34432    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
34433  }                                                                 \
34434}
34435
34436#define WRITE_UTF16BE(zOut, c) {                                    \
34437  if( c<=0xFFFF ){                                                  \
34438    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
34439    *zOut++ = (u8)(c&0x00FF);                                       \
34440  }else{                                                            \
34441    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
34442    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
34443    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
34444    *zOut++ = (u8)(c&0x00FF);                                       \
34445  }                                                                 \
34446}
34447
34448/*
34449** Translate a single UTF-8 character.  Return the unicode value.
34450**
34451** During translation, assume that the byte that zTerm points
34452** is a 0x00.
34453**
34454** Write a pointer to the next unread byte back into *pzNext.
34455**
34456** Notes On Invalid UTF-8:
34457**
34458**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
34459**     be encoded as a multi-byte character.  Any multi-byte character that
34460**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
34461**
34462**  *  This routine never allows a UTF16 surrogate value to be encoded.
34463**     If a multi-byte character attempts to encode a value between
34464**     0xd800 and 0xe000 then it is rendered as 0xfffd.
34465**
34466**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
34467**     byte of a character are interpreted as single-byte characters
34468**     and rendered as themselves even though they are technically
34469**     invalid characters.
34470**
34471**  *  This routine accepts over-length UTF8 encodings
34472**     for unicode values 0x80 and greater.  It does not change over-length
34473**     encodings to 0xfffd as some systems recommend.
34474*/
34475#define READ_UTF8(zIn, zTerm, c)                           \
34476  c = *(zIn++);                                            \
34477  if( c>=0xc0 ){                                           \
34478    c = sqlite3Utf8Trans1[c-0xc0];                         \
34479    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
34480      c = (c<<6) + (0x3f & *(zIn++));                      \
34481    }                                                      \
34482    if( c<0x80                                             \
34483        || (c&0xFFFFF800)==0xD800                          \
34484        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
34485  }
34486SQLITE_PRIVATE u32 sqlite3Utf8Read(
34487  const unsigned char **pz    /* Pointer to string from which to read char */
34488){
34489  unsigned int c;
34490
34491  /* Same as READ_UTF8() above but without the zTerm parameter.
34492  ** For this routine, we assume the UTF8 string is always zero-terminated.
34493  */
34494  c = *((*pz)++);
34495  if( c>=0xc0 ){
34496    c = sqlite3Utf8Trans1[c-0xc0];
34497    while( (*(*pz) & 0xc0)==0x80 ){
34498      c = (c<<6) + (0x3f & *((*pz)++));
34499    }
34500    if( c<0x80
34501        || (c&0xFFFFF800)==0xD800
34502        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
34503  }
34504  return c;
34505}
34506
34507/*
34508** Read a single UTF8 character out of buffer z[], but reading no
34509** more than n characters from the buffer.  z[] is not zero-terminated.
34510**
34511** Return the number of bytes used to construct the character.
34512**
34513** Invalid UTF8 might generate a strange result.  No effort is made
34514** to detect invalid UTF8.
34515**
34516** At most 4 bytes will be read out of z[].  The return value will always
34517** be between 1 and 4.
34518*/
34519SQLITE_PRIVATE int sqlite3Utf8ReadLimited(
34520  const u8 *z,
34521  int n,
34522  u32 *piOut
34523){
34524  u32 c;
34525  int i = 1;
34526  assert( n>0 );
34527  c = z[0];
34528  if( c>=0xc0 ){
34529    c = sqlite3Utf8Trans1[c-0xc0];
34530    if( n>4 ) n = 4;
34531    while( i<n && (z[i] & 0xc0)==0x80 ){
34532      c = (c<<6) + (0x3f & z[i]);
34533      i++;
34534    }
34535  }
34536  *piOut = c;
34537  return i;
34538}
34539
34540
34541/*
34542** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
34543** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
34544*/
34545/* #define TRANSLATE_TRACE 1 */
34546
34547#ifndef SQLITE_OMIT_UTF16
34548/*
34549** This routine transforms the internal text encoding used by pMem to
34550** desiredEnc. It is an error if the string is already of the desired
34551** encoding, or if *pMem does not contain a string value.
34552*/
34553SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
34554  sqlite3_int64 len;          /* Maximum length of output string in bytes */
34555  unsigned char *zOut;        /* Output buffer */
34556  unsigned char *zIn;         /* Input iterator */
34557  unsigned char *zTerm;       /* End of input */
34558  unsigned char *z;           /* Output iterator */
34559  unsigned int c;
34560
34561  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
34562  assert( pMem->flags&MEM_Str );
34563  assert( pMem->enc!=desiredEnc );
34564  assert( pMem->enc!=0 );
34565  assert( pMem->n>=0 );
34566
34567#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
34568  {
34569    StrAccum acc;
34570    char zBuf[1000];
34571    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
34572    sqlite3VdbeMemPrettyPrint(pMem, &acc);
34573    fprintf(stderr, "INPUT:  %s\n", sqlite3StrAccumFinish(&acc));
34574  }
34575#endif
34576
34577  /* If the translation is between UTF-16 little and big endian, then
34578  ** all that is required is to swap the byte order. This case is handled
34579  ** differently from the others.
34580  */
34581  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
34582    u8 temp;
34583    int rc;
34584    rc = sqlite3VdbeMemMakeWriteable(pMem);
34585    if( rc!=SQLITE_OK ){
34586      assert( rc==SQLITE_NOMEM );
34587      return SQLITE_NOMEM_BKPT;
34588    }
34589    zIn = (u8*)pMem->z;
34590    zTerm = &zIn[pMem->n&~1];
34591    while( zIn<zTerm ){
34592      temp = *zIn;
34593      *zIn = *(zIn+1);
34594      zIn++;
34595      *zIn++ = temp;
34596    }
34597    pMem->enc = desiredEnc;
34598    goto translate_out;
34599  }
34600
34601  /* Set len to the maximum number of bytes required in the output buffer. */
34602  if( desiredEnc==SQLITE_UTF8 ){
34603    /* When converting from UTF-16, the maximum growth results from
34604    ** translating a 2-byte character to a 4-byte UTF-8 character.
34605    ** A single byte is required for the output string
34606    ** nul-terminator.
34607    */
34608    pMem->n &= ~1;
34609    len = 2 * (sqlite3_int64)pMem->n + 1;
34610  }else{
34611    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
34612    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
34613    ** character. Two bytes are required in the output buffer for the
34614    ** nul-terminator.
34615    */
34616    len = 2 * (sqlite3_int64)pMem->n + 2;
34617  }
34618
34619  /* Set zIn to point at the start of the input buffer and zTerm to point 1
34620  ** byte past the end.
34621  **
34622  ** Variable zOut is set to point at the output buffer, space obtained
34623  ** from sqlite3_malloc().
34624  */
34625  zIn = (u8*)pMem->z;
34626  zTerm = &zIn[pMem->n];
34627  zOut = sqlite3DbMallocRaw(pMem->db, len);
34628  if( !zOut ){
34629    return SQLITE_NOMEM_BKPT;
34630  }
34631  z = zOut;
34632
34633  if( pMem->enc==SQLITE_UTF8 ){
34634    if( desiredEnc==SQLITE_UTF16LE ){
34635      /* UTF-8 -> UTF-16 Little-endian */
34636      while( zIn<zTerm ){
34637        READ_UTF8(zIn, zTerm, c);
34638        WRITE_UTF16LE(z, c);
34639      }
34640    }else{
34641      assert( desiredEnc==SQLITE_UTF16BE );
34642      /* UTF-8 -> UTF-16 Big-endian */
34643      while( zIn<zTerm ){
34644        READ_UTF8(zIn, zTerm, c);
34645        WRITE_UTF16BE(z, c);
34646      }
34647    }
34648    pMem->n = (int)(z - zOut);
34649    *z++ = 0;
34650  }else{
34651    assert( desiredEnc==SQLITE_UTF8 );
34652    if( pMem->enc==SQLITE_UTF16LE ){
34653      /* UTF-16 Little-endian -> UTF-8 */
34654      while( zIn<zTerm ){
34655        c = *(zIn++);
34656        c += (*(zIn++))<<8;
34657        if( c>=0xd800 && c<0xe000 ){
34658#ifdef SQLITE_REPLACE_INVALID_UTF
34659          if( c>=0xdc00 || zIn>=zTerm ){
34660            c = 0xfffd;
34661          }else{
34662            int c2 = *(zIn++);
34663            c2 += (*(zIn++))<<8;
34664            if( c2<0xdc00 || c2>=0xe000 ){
34665              zIn -= 2;
34666              c = 0xfffd;
34667            }else{
34668              c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;
34669            }
34670          }
34671#else
34672          if( zIn<zTerm ){
34673            int c2 = (*zIn++);
34674            c2 += ((*zIn++)<<8);
34675            c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);
34676          }
34677#endif
34678        }
34679        WRITE_UTF8(z, c);
34680      }
34681    }else{
34682      /* UTF-16 Big-endian -> UTF-8 */
34683      while( zIn<zTerm ){
34684        c = (*(zIn++))<<8;
34685        c += *(zIn++);
34686        if( c>=0xd800 && c<0xe000 ){
34687#ifdef SQLITE_REPLACE_INVALID_UTF
34688          if( c>=0xdc00 || zIn>=zTerm ){
34689            c = 0xfffd;
34690          }else{
34691            int c2 = (*(zIn++))<<8;
34692            c2 += *(zIn++);
34693            if( c2<0xdc00 || c2>=0xe000 ){
34694              zIn -= 2;
34695              c = 0xfffd;
34696            }else{
34697              c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;
34698            }
34699          }
34700#else
34701          if( zIn<zTerm ){
34702            int c2 = ((*zIn++)<<8);
34703            c2 += (*zIn++);
34704            c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);
34705          }
34706#endif
34707        }
34708        WRITE_UTF8(z, c);
34709      }
34710    }
34711    pMem->n = (int)(z - zOut);
34712  }
34713  *z = 0;
34714  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
34715
34716  c = MEM_Str|MEM_Term|(pMem->flags&(MEM_AffMask|MEM_Subtype));
34717  sqlite3VdbeMemRelease(pMem);
34718  pMem->flags = c;
34719  pMem->enc = desiredEnc;
34720  pMem->z = (char*)zOut;
34721  pMem->zMalloc = pMem->z;
34722  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
34723
34724translate_out:
34725#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
34726  {
34727    StrAccum acc;
34728    char zBuf[1000];
34729    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
34730    sqlite3VdbeMemPrettyPrint(pMem, &acc);
34731    fprintf(stderr, "OUTPUT: %s\n", sqlite3StrAccumFinish(&acc));
34732  }
34733#endif
34734  return SQLITE_OK;
34735}
34736#endif /* SQLITE_OMIT_UTF16 */
34737
34738#ifndef SQLITE_OMIT_UTF16
34739/*
34740** This routine checks for a byte-order mark at the beginning of the
34741** UTF-16 string stored in *pMem. If one is present, it is removed and
34742** the encoding of the Mem adjusted. This routine does not do any
34743** byte-swapping, it just sets Mem.enc appropriately.
34744**
34745** The allocation (static, dynamic etc.) and encoding of the Mem may be
34746** changed by this function.
34747*/
34748SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
34749  int rc = SQLITE_OK;
34750  u8 bom = 0;
34751
34752  assert( pMem->n>=0 );
34753  if( pMem->n>1 ){
34754    u8 b1 = *(u8 *)pMem->z;
34755    u8 b2 = *(((u8 *)pMem->z) + 1);
34756    if( b1==0xFE && b2==0xFF ){
34757      bom = SQLITE_UTF16BE;
34758    }
34759    if( b1==0xFF && b2==0xFE ){
34760      bom = SQLITE_UTF16LE;
34761    }
34762  }
34763
34764  if( bom ){
34765    rc = sqlite3VdbeMemMakeWriteable(pMem);
34766    if( rc==SQLITE_OK ){
34767      pMem->n -= 2;
34768      memmove(pMem->z, &pMem->z[2], pMem->n);
34769      pMem->z[pMem->n] = '\0';
34770      pMem->z[pMem->n+1] = '\0';
34771      pMem->flags |= MEM_Term;
34772      pMem->enc = bom;
34773    }
34774  }
34775  return rc;
34776}
34777#endif /* SQLITE_OMIT_UTF16 */
34778
34779/*
34780** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
34781** return the number of unicode characters in pZ up to (but not including)
34782** the first 0x00 byte. If nByte is not less than zero, return the
34783** number of unicode characters in the first nByte of pZ (or up to
34784** the first 0x00, whichever comes first).
34785*/
34786SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
34787  int r = 0;
34788  const u8 *z = (const u8*)zIn;
34789  const u8 *zTerm;
34790  if( nByte>=0 ){
34791    zTerm = &z[nByte];
34792  }else{
34793    zTerm = (const u8*)(-1);
34794  }
34795  assert( z<=zTerm );
34796  while( *z!=0 && z<zTerm ){
34797    SQLITE_SKIP_UTF8(z);
34798    r++;
34799  }
34800  return r;
34801}
34802
34803/* This test function is not currently used by the automated test-suite.
34804** Hence it is only available in debug builds.
34805*/
34806#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
34807/*
34808** Translate UTF-8 to UTF-8.
34809**
34810** This has the effect of making sure that the string is well-formed
34811** UTF-8.  Miscoded characters are removed.
34812**
34813** The translation is done in-place and aborted if the output
34814** overruns the input.
34815*/
34816SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
34817  unsigned char *zOut = zIn;
34818  unsigned char *zStart = zIn;
34819  u32 c;
34820
34821  while( zIn[0] && zOut<=zIn ){
34822    c = sqlite3Utf8Read((const u8**)&zIn);
34823    if( c!=0xfffd ){
34824      WRITE_UTF8(zOut, c);
34825    }
34826  }
34827  *zOut = 0;
34828  return (int)(zOut - zStart);
34829}
34830#endif
34831
34832#ifndef SQLITE_OMIT_UTF16
34833/*
34834** Convert a UTF-16 string in the native encoding into a UTF-8 string.
34835** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
34836** be freed by the calling function.
34837**
34838** NULL is returned if there is an allocation error.
34839*/
34840SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
34841  Mem m;
34842  memset(&m, 0, sizeof(m));
34843  m.db = db;
34844  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
34845  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
34846  if( db->mallocFailed ){
34847    sqlite3VdbeMemRelease(&m);
34848    m.z = 0;
34849  }
34850  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
34851  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
34852  assert( m.z || db->mallocFailed );
34853  return m.z;
34854}
34855
34856/*
34857** zIn is a UTF-16 encoded unicode string at least nChar characters long.
34858** Return the number of bytes in the first nChar unicode characters
34859** in pZ.  nChar must be non-negative.
34860*/
34861SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
34862  int c;
34863  unsigned char const *z = zIn;
34864  int n = 0;
34865
34866  if( SQLITE_UTF16NATIVE==SQLITE_UTF16LE ) z++;
34867  while( n<nChar ){
34868    c = z[0];
34869    z += 2;
34870    if( c>=0xd8 && c<0xdc && z[0]>=0xdc && z[0]<0xe0 ) z += 2;
34871    n++;
34872  }
34873  return (int)(z-(unsigned char const *)zIn)
34874              - (SQLITE_UTF16NATIVE==SQLITE_UTF16LE);
34875}
34876
34877#if defined(SQLITE_TEST)
34878/*
34879** This routine is called from the TCL test function "translate_selftest".
34880** It checks that the primitives for serializing and deserializing
34881** characters in each encoding are inverses of each other.
34882*/
34883SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
34884  unsigned int i, t;
34885  unsigned char zBuf[20];
34886  unsigned char *z;
34887  int n;
34888  unsigned int c;
34889
34890  for(i=0; i<0x00110000; i++){
34891    z = zBuf;
34892    WRITE_UTF8(z, i);
34893    n = (int)(z-zBuf);
34894    assert( n>0 && n<=4 );
34895    z[0] = 0;
34896    z = zBuf;
34897    c = sqlite3Utf8Read((const u8**)&z);
34898    t = i;
34899    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
34900    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
34901    assert( c==t );
34902    assert( (z-zBuf)==n );
34903  }
34904}
34905#endif /* SQLITE_TEST */
34906#endif /* SQLITE_OMIT_UTF16 */
34907
34908/************** End of utf.c *************************************************/
34909/************** Begin file util.c ********************************************/
34910/*
34911** 2001 September 15
34912**
34913** The author disclaims copyright to this source code.  In place of
34914** a legal notice, here is a blessing:
34915**
34916**    May you do good and not evil.
34917**    May you find forgiveness for yourself and forgive others.
34918**    May you share freely, never taking more than you give.
34919**
34920*************************************************************************
34921** Utility functions used throughout sqlite.
34922**
34923** This file contains functions for allocating memory, comparing
34924** strings, and stuff like that.
34925**
34926*/
34927/* #include "sqliteInt.h" */
34928/* #include <stdarg.h> */
34929#ifndef SQLITE_OMIT_FLOATING_POINT
34930#include <math.h>
34931#endif
34932
34933/*
34934** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
34935** or to bypass normal error detection during testing in order to let
34936** execute proceed further downstream.
34937**
34938** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0).  The
34939** sqlite3FaultSim() function only returns non-zero during testing.
34940**
34941** During testing, if the test harness has set a fault-sim callback using
34942** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then
34943** each call to sqlite3FaultSim() is relayed to that application-supplied
34944** callback and the integer return value form the application-supplied
34945** callback is returned by sqlite3FaultSim().
34946**
34947** The integer argument to sqlite3FaultSim() is a code to identify which
34948** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()
34949** should have a unique code.  To prevent legacy testing applications from
34950** breaking, the codes should not be changed or reused.
34951*/
34952#ifndef SQLITE_UNTESTABLE
34953SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
34954  int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
34955  return xCallback ? xCallback(iTest) : SQLITE_OK;
34956}
34957#endif
34958
34959#ifndef SQLITE_OMIT_FLOATING_POINT
34960/*
34961** Return true if the floating point value is Not a Number (NaN).
34962**
34963** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
34964** Otherwise, we have our own implementation that works on most systems.
34965*/
34966SQLITE_PRIVATE int sqlite3IsNaN(double x){
34967  int rc;   /* The value return */
34968#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
34969  u64 y;
34970  memcpy(&y,&x,sizeof(y));
34971  rc = IsNaN(y);
34972#else
34973  rc = isnan(x);
34974#endif /* HAVE_ISNAN */
34975  testcase( rc );
34976  return rc;
34977}
34978#endif /* SQLITE_OMIT_FLOATING_POINT */
34979
34980#ifndef SQLITE_OMIT_FLOATING_POINT
34981/*
34982** Return true if the floating point value is NaN or +Inf or -Inf.
34983*/
34984SQLITE_PRIVATE int sqlite3IsOverflow(double x){
34985  int rc;   /* The value return */
34986  u64 y;
34987  memcpy(&y,&x,sizeof(y));
34988  rc = IsOvfl(y);
34989  return rc;
34990}
34991#endif /* SQLITE_OMIT_FLOATING_POINT */
34992
34993/*
34994** Compute a string length that is limited to what can be stored in
34995** lower 30 bits of a 32-bit signed integer.
34996**
34997** The value returned will never be negative.  Nor will it ever be greater
34998** than the actual length of the string.  For very long strings (greater
34999** than 1GiB) the value returned might be less than the true string length.
35000*/
35001SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
35002  if( z==0 ) return 0;
35003  return 0x3fffffff & (int)strlen(z);
35004}
35005
35006/*
35007** Return the declared type of a column.  Or return zDflt if the column
35008** has no declared type.
35009**
35010** The column type is an extra string stored after the zero-terminator on
35011** the column name if and only if the COLFLAG_HASTYPE flag is set.
35012*/
35013SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
35014  if( pCol->colFlags & COLFLAG_HASTYPE ){
35015    return pCol->zCnName + strlen(pCol->zCnName) + 1;
35016  }else if( pCol->eCType ){
35017    assert( pCol->eCType<=SQLITE_N_STDTYPE );
35018    return (char*)sqlite3StdType[pCol->eCType-1];
35019  }else{
35020    return zDflt;
35021  }
35022}
35023
35024/*
35025** Helper function for sqlite3Error() - called rarely.  Broken out into
35026** a separate routine to avoid unnecessary register saves on entry to
35027** sqlite3Error().
35028*/
35029static SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){
35030  if( db->pErr ) sqlite3ValueSetNull(db->pErr);
35031  sqlite3SystemError(db, err_code);
35032}
35033
35034/*
35035** Set the current error code to err_code and clear any prior error message.
35036** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
35037** that would be appropriate.
35038*/
35039SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
35040  assert( db!=0 );
35041  db->errCode = err_code;
35042  if( err_code || db->pErr ){
35043    sqlite3ErrorFinish(db, err_code);
35044  }else{
35045    db->errByteOffset = -1;
35046  }
35047}
35048
35049/*
35050** The equivalent of sqlite3Error(db, SQLITE_OK).  Clear the error state
35051** and error message.
35052*/
35053SQLITE_PRIVATE void sqlite3ErrorClear(sqlite3 *db){
35054  assert( db!=0 );
35055  db->errCode = SQLITE_OK;
35056  db->errByteOffset = -1;
35057  if( db->pErr ) sqlite3ValueSetNull(db->pErr);
35058}
35059
35060/*
35061** Load the sqlite3.iSysErrno field if that is an appropriate thing
35062** to do based on the SQLite error code in rc.
35063*/
35064SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
35065  if( rc==SQLITE_IOERR_NOMEM ) return;
35066#if defined(SQLITE_USE_SEH) && !defined(SQLITE_OMIT_WAL)
35067  if( rc==SQLITE_IOERR_IN_PAGE ){
35068    int ii;
35069    int iErr;
35070    sqlite3BtreeEnterAll(db);
35071    for(ii=0; ii<db->nDb; ii++){
35072      if( db->aDb[ii].pBt ){
35073        iErr = sqlite3PagerWalSystemErrno(sqlite3BtreePager(db->aDb[ii].pBt));
35074        if( iErr ){
35075          db->iSysErrno = iErr;
35076        }
35077      }
35078    }
35079    sqlite3BtreeLeaveAll(db);
35080    return;
35081  }
35082#endif
35083  rc &= 0xff;
35084  if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
35085    db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
35086  }
35087}
35088
35089/*
35090** Set the most recent error code and error string for the sqlite
35091** handle "db". The error code is set to "err_code".
35092**
35093** If it is not NULL, string zFormat specifies the format of the
35094** error string.  zFormat and any string tokens that follow it are
35095** assumed to be encoded in UTF-8.
35096**
35097** To clear the most recent error for sqlite handle "db", sqlite3Error
35098** should be called with err_code set to SQLITE_OK and zFormat set
35099** to NULL.
35100*/
35101SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
35102  assert( db!=0 );
35103  db->errCode = err_code;
35104  sqlite3SystemError(db, err_code);
35105  if( zFormat==0 ){
35106    sqlite3Error(db, err_code);
35107  }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
35108    char *z;
35109    va_list ap;
35110    va_start(ap, zFormat);
35111    z = sqlite3VMPrintf(db, zFormat, ap);
35112    va_end(ap);
35113    sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
35114  }
35115}
35116
35117/*
35118** Check for interrupts and invoke progress callback.
35119*/
35120SQLITE_PRIVATE void sqlite3ProgressCheck(Parse *p){
35121  sqlite3 *db = p->db;
35122  if( AtomicLoad(&db->u1.isInterrupted) ){
35123    p->nErr++;
35124    p->rc = SQLITE_INTERRUPT;
35125  }
35126#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
35127  if( db->xProgress ){
35128    if( p->rc==SQLITE_INTERRUPT ){
35129      p->nProgressSteps = 0;
35130    }else if( (++p->nProgressSteps)>=db->nProgressOps ){
35131      if( db->xProgress(db->pProgressArg) ){
35132        p->nErr++;
35133        p->rc = SQLITE_INTERRUPT;
35134      }
35135      p->nProgressSteps = 0;
35136    }
35137  }
35138#endif
35139}
35140
35141/*
35142** Add an error message to pParse->zErrMsg and increment pParse->nErr.
35143**
35144** This function should be used to report any error that occurs while
35145** compiling an SQL statement (i.e. within sqlite3_prepare()). The
35146** last thing the sqlite3_prepare() function does is copy the error
35147** stored by this function into the database handle using sqlite3Error().
35148** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
35149** during statement execution (sqlite3_step() etc.).
35150*/
35151SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
35152  char *zMsg;
35153  va_list ap;
35154  sqlite3 *db = pParse->db;
35155  assert( db!=0 );
35156  assert( db->pParse==pParse || db->pParse->pToplevel==pParse );
35157  db->errByteOffset = -2;
35158  va_start(ap, zFormat);
35159  zMsg = sqlite3VMPrintf(db, zFormat, ap);
35160  va_end(ap);
35161  if( db->errByteOffset<-1 ) db->errByteOffset = -1;
35162  if( db->suppressErr ){
35163    sqlite3DbFree(db, zMsg);
35164    if( db->mallocFailed ){
35165      pParse->nErr++;
35166      pParse->rc = SQLITE_NOMEM;
35167    }
35168  }else{
35169    pParse->nErr++;
35170    sqlite3DbFree(db, pParse->zErrMsg);
35171    pParse->zErrMsg = zMsg;
35172    pParse->rc = SQLITE_ERROR;
35173    pParse->pWith = 0;
35174  }
35175}
35176
35177/*
35178** If database connection db is currently parsing SQL, then transfer
35179** error code errCode to that parser if the parser has not already
35180** encountered some other kind of error.
35181*/
35182SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3 *db, int errCode){
35183  Parse *pParse;
35184  if( db==0 || (pParse = db->pParse)==0 ) return errCode;
35185  pParse->rc = errCode;
35186  pParse->nErr++;
35187  return errCode;
35188}
35189
35190/*
35191** Convert an SQL-style quoted string into a normal string by removing
35192** the quote characters.  The conversion is done in-place.  If the
35193** input does not begin with a quote character, then this routine
35194** is a no-op.
35195**
35196** The input string must be zero-terminated.  A new zero-terminator
35197** is added to the dequoted string.
35198**
35199** The return value is -1 if no dequoting occurs or the length of the
35200** dequoted string, exclusive of the zero terminator, if dequoting does
35201** occur.
35202**
35203** 2002-02-14: This routine is extended to remove MS-Access style
35204** brackets from around identifiers.  For example:  "[a-b-c]" becomes
35205** "a-b-c".
35206*/
35207SQLITE_PRIVATE void sqlite3Dequote(char *z){
35208  char quote;
35209  int i, j;
35210  if( z==0 ) return;
35211  quote = z[0];
35212  if( !sqlite3Isquote(quote) ) return;
35213  if( quote=='[' ) quote = ']';
35214  for(i=1, j=0;; i++){
35215    assert( z[i] );
35216    if( z[i]==quote ){
35217      if( z[i+1]==quote ){
35218        z[j++] = quote;
35219        i++;
35220      }else{
35221        break;
35222      }
35223    }else{
35224      z[j++] = z[i];
35225    }
35226  }
35227  z[j] = 0;
35228}
35229SQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){
35230  assert( !ExprHasProperty(p, EP_IntValue) );
35231  assert( sqlite3Isquote(p->u.zToken[0]) );
35232  p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
35233  sqlite3Dequote(p->u.zToken);
35234}
35235
35236/*
35237** Expression p is a QNUMBER (quoted number). Dequote the value in p->u.zToken
35238** and set the type to INTEGER or FLOAT. "Quoted" integers or floats are those
35239** that contain '_' characters that must be removed before further processing.
35240*/
35241SQLITE_PRIVATE void sqlite3DequoteNumber(Parse *pParse, Expr *p){
35242  assert( p!=0 || pParse->db->mallocFailed );
35243  if( p ){
35244    const char *pIn = p->u.zToken;
35245    char *pOut = p->u.zToken;
35246    int bHex = (pIn[0]=='0' && (pIn[1]=='x' || pIn[1]=='X'));
35247    int iValue;
35248    assert( p->op==TK_QNUMBER );
35249    p->op = TK_INTEGER;
35250    do {
35251      if( *pIn!=SQLITE_DIGIT_SEPARATOR ){
35252        *pOut++ = *pIn;
35253        if( *pIn=='e' || *pIn=='E' || *pIn=='.' ) p->op = TK_FLOAT;
35254      }else{
35255        if( (bHex==0 && (!sqlite3Isdigit(pIn[-1]) || !sqlite3Isdigit(pIn[1])))
35256         || (bHex==1 && (!sqlite3Isxdigit(pIn[-1]) || !sqlite3Isxdigit(pIn[1])))
35257        ){
35258          sqlite3ErrorMsg(pParse, "unrecognized token: \"%s\"", p->u.zToken);
35259        }
35260      }
35261    }while( *pIn++ );
35262    if( bHex ) p->op = TK_INTEGER;
35263
35264    /* tag-20240227-a: If after dequoting, the number is an integer that
35265    ** fits in 32 bits, then it must be converted into EP_IntValue.  Other
35266    ** parts of the code expect this.  See also tag-20240227-b. */
35267    if( p->op==TK_INTEGER && sqlite3GetInt32(p->u.zToken, &iValue) ){
35268      p->u.iValue = iValue;
35269      p->flags |= EP_IntValue;
35270    }
35271  }
35272}
35273
35274/*
35275** If the input token p is quoted, try to adjust the token to remove
35276** the quotes.  This is not always possible:
35277**
35278**     "abc"     ->   abc
35279**     "ab""cd"  ->   (not possible because of the interior "")
35280**
35281** Remove the quotes if possible.  This is a optimization.  The overall
35282** system should still return the correct answer even if this routine
35283** is always a no-op.
35284*/
35285SQLITE_PRIVATE void sqlite3DequoteToken(Token *p){
35286  unsigned int i;
35287  if( p->n<2 ) return;
35288  if( !sqlite3Isquote(p->z[0]) ) return;
35289  for(i=1; i<p->n-1; i++){
35290    if( sqlite3Isquote(p->z[i]) ) return;
35291  }
35292  p->n -= 2;
35293  p->z++;
35294}
35295
35296/*
35297** Generate a Token object from a string
35298*/
35299SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
35300  p->z = z;
35301  p->n = sqlite3Strlen30(z);
35302}
35303
35304/* Convenient short-hand */
35305#define UpperToLower sqlite3UpperToLower
35306
35307/*
35308** Some systems have stricmp().  Others have strcasecmp().  Because
35309** there is no consistency, we will define our own.
35310**
35311** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
35312** sqlite3_strnicmp() APIs allow applications and extensions to compare
35313** the contents of two buffers containing UTF-8 strings in a
35314** case-independent fashion, using the same definition of "case
35315** independence" that SQLite uses internally when comparing identifiers.
35316*/
35317SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
35318  if( zLeft==0 ){
35319    return zRight ? -1 : 0;
35320  }else if( zRight==0 ){
35321    return 1;
35322  }
35323  return sqlite3StrICmp(zLeft, zRight);
35324}
35325SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
35326  unsigned char *a, *b;
35327  int c, x;
35328  a = (unsigned char *)zLeft;
35329  b = (unsigned char *)zRight;
35330  for(;;){
35331    c = *a;
35332    x = *b;
35333    if( c==x ){
35334      if( c==0 ) break;
35335    }else{
35336      c = (int)UpperToLower[c] - (int)UpperToLower[x];
35337      if( c ) break;
35338    }
35339    a++;
35340    b++;
35341  }
35342  return c;
35343}
35344SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
35345  register unsigned char *a, *b;
35346  if( zLeft==0 ){
35347    return zRight ? -1 : 0;
35348  }else if( zRight==0 ){
35349    return 1;
35350  }
35351  a = (unsigned char *)zLeft;
35352  b = (unsigned char *)zRight;
35353  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
35354  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
35355}
35356
35357/*
35358** Compute an 8-bit hash on a string that is insensitive to case differences
35359*/
35360SQLITE_PRIVATE u8 sqlite3StrIHash(const char *z){
35361  u8 h = 0;
35362  if( z==0 ) return 0;
35363  while( z[0] ){
35364    h += UpperToLower[(unsigned char)z[0]];
35365    z++;
35366  }
35367  return h;
35368}
35369
35370/* Double-Double multiplication.  (x[0],x[1]) *= (y,yy)
35371**
35372** Reference:
35373**   T. J. Dekker, "A Floating-Point Technique for Extending the
35374**   Available Precision".  1971-07-26.
35375*/
35376static void dekkerMul2(volatile double *x, double y, double yy){
35377  /*
35378  ** The "volatile" keywords on parameter x[] and on local variables
35379  ** below are needed force intermediate results to be truncated to
35380  ** binary64 rather than be carried around in an extended-precision
35381  ** format.  The truncation is necessary for the Dekker algorithm to
35382  ** work.  Intel x86 floating point might omit the truncation without
35383  ** the use of volatile.
35384  */
35385  volatile double tx, ty, p, q, c, cc;
35386  double hx, hy;
35387  u64 m;
35388  memcpy(&m, (void*)&x[0], 8);
35389  m &= 0xfffffffffc000000LL;
35390  memcpy(&hx, &m, 8);
35391  tx = x[0] - hx;
35392  memcpy(&m, &y, 8);
35393  m &= 0xfffffffffc000000LL;
35394  memcpy(&hy, &m, 8);
35395  ty = y - hy;
35396  p = hx*hy;
35397  q = hx*ty + tx*hy;
35398  c = p+q;
35399  cc = p - c + q + tx*ty;
35400  cc = x[0]*yy + x[1]*y + cc;
35401  x[0] = c + cc;
35402  x[1] = c - x[0];
35403  x[1] += cc;
35404}
35405
35406/*
35407** The string z[] is an text representation of a real number.
35408** Convert this string to a double and write it into *pResult.
35409**
35410** The string z[] is length bytes in length (bytes, not characters) and
35411** uses the encoding enc.  The string is not necessarily zero-terminated.
35412**
35413** Return TRUE if the result is a valid real number (or integer) and FALSE
35414** if the string is empty or contains extraneous text.  More specifically
35415** return
35416**      1          =>  The input string is a pure integer
35417**      2 or more  =>  The input has a decimal point or eNNN clause
35418**      0 or less  =>  The input string is not a valid number
35419**     -1          =>  Not a valid number, but has a valid prefix which
35420**                     includes a decimal point and/or an eNNN clause
35421**
35422** Valid numbers are in one of these formats:
35423**
35424**    [+-]digits[E[+-]digits]
35425**    [+-]digits.[digits][E[+-]digits]
35426**    [+-].digits[E[+-]digits]
35427**
35428** Leading and trailing whitespace is ignored for the purpose of determining
35429** validity.
35430**
35431** If some prefix of the input string is a valid number, this routine
35432** returns FALSE but it still converts the prefix and writes the result
35433** into *pResult.
35434*/
35435#if defined(_MSC_VER)
35436#pragma warning(disable : 4756)
35437#endif
35438SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
35439#ifndef SQLITE_OMIT_FLOATING_POINT
35440  int incr;
35441  const char *zEnd;
35442  /* sign * significand * (10 ^ (esign * exponent)) */
35443  int sign = 1;    /* sign of significand */
35444  u64 s = 0;       /* significand */
35445  int d = 0;       /* adjust exponent for shifting decimal point */
35446  int esign = 1;   /* sign of exponent */
35447  int e = 0;       /* exponent */
35448  int eValid = 1;  /* True exponent is either not used or is well-formed */
35449  int nDigit = 0;  /* Number of digits processed */
35450  int eType = 1;   /* 1: pure integer,  2+: fractional  -1 or less: bad UTF16 */
35451
35452  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
35453  *pResult = 0.0;   /* Default return value, in case of an error */
35454  if( length==0 ) return 0;
35455
35456  if( enc==SQLITE_UTF8 ){
35457    incr = 1;
35458    zEnd = z + length;
35459  }else{
35460    int i;
35461    incr = 2;
35462    length &= ~1;
35463    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
35464    testcase( enc==SQLITE_UTF16LE );
35465    testcase( enc==SQLITE_UTF16BE );
35466    for(i=3-enc; i<length && z[i]==0; i+=2){}
35467    if( i<length ) eType = -100;
35468    zEnd = &z[i^1];
35469    z += (enc&1);
35470  }
35471
35472  /* skip leading spaces */
35473  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
35474  if( z>=zEnd ) return 0;
35475
35476  /* get sign of significand */
35477  if( *z=='-' ){
35478    sign = -1;
35479    z+=incr;
35480  }else if( *z=='+' ){
35481    z+=incr;
35482  }
35483
35484  /* copy max significant digits to significand */
35485  while( z<zEnd && sqlite3Isdigit(*z) ){
35486    s = s*10 + (*z - '0');
35487    z+=incr; nDigit++;
35488    if( s>=((LARGEST_UINT64-9)/10) ){
35489      /* skip non-significant significand digits
35490      ** (increase exponent by d to shift decimal left) */
35491      while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; d++; }
35492    }
35493  }
35494  if( z>=zEnd ) goto do_atof_calc;
35495
35496  /* if decimal point is present */
35497  if( *z=='.' ){
35498    z+=incr;
35499    eType++;
35500    /* copy digits from after decimal to significand
35501    ** (decrease exponent by d to shift decimal right) */
35502    while( z<zEnd && sqlite3Isdigit(*z) ){
35503      if( s<((LARGEST_UINT64-9)/10) ){
35504        s = s*10 + (*z - '0');
35505        d--;
35506        nDigit++;
35507      }
35508      z+=incr;
35509    }
35510  }
35511  if( z>=zEnd ) goto do_atof_calc;
35512
35513  /* if exponent is present */
35514  if( *z=='e' || *z=='E' ){
35515    z+=incr;
35516    eValid = 0;
35517    eType++;
35518
35519    /* This branch is needed to avoid a (harmless) buffer overread.  The
35520    ** special comment alerts the mutation tester that the correct answer
35521    ** is obtained even if the branch is omitted */
35522    if( z>=zEnd ) goto do_atof_calc;              /*PREVENTS-HARMLESS-OVERREAD*/
35523
35524    /* get sign of exponent */
35525    if( *z=='-' ){
35526      esign = -1;
35527      z+=incr;
35528    }else if( *z=='+' ){
35529      z+=incr;
35530    }
35531    /* copy digits to exponent */
35532    while( z<zEnd && sqlite3Isdigit(*z) ){
35533      e = e<10000 ? (e*10 + (*z - '0')) : 10000;
35534      z+=incr;
35535      eValid = 1;
35536    }
35537  }
35538
35539  /* skip trailing spaces */
35540  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
35541
35542do_atof_calc:
35543  /* Zero is a special case */
35544  if( s==0 ){
35545    *pResult = sign<0 ? -0.0 : +0.0;
35546    goto atof_return;
35547  }
35548
35549  /* adjust exponent by d, and update sign */
35550  e = (e*esign) + d;
35551
35552  /* Try to adjust the exponent to make it smaller */
35553  while( e>0 && s<(LARGEST_UINT64/10) ){
35554    s *= 10;
35555    e--;
35556  }
35557  while( e<0 && (s%10)==0 ){
35558    s /= 10;
35559    e++;
35560  }
35561
35562  if( e==0 ){
35563    *pResult = s;
35564  }else if( sqlite3Config.bUseLongDouble ){
35565    LONGDOUBLE_TYPE r = (LONGDOUBLE_TYPE)s;
35566    if( e>0 ){
35567      while( e>=100  ){ e-=100; r *= 1.0e+100L; }
35568      while( e>=10   ){ e-=10;  r *= 1.0e+10L;  }
35569      while( e>=1    ){ e-=1;   r *= 1.0e+01L;  }
35570    }else{
35571      while( e<=-100 ){ e+=100; r *= 1.0e-100L; }
35572      while( e<=-10  ){ e+=10;  r *= 1.0e-10L;  }
35573      while( e<=-1   ){ e+=1;   r *= 1.0e-01L;  }
35574    }
35575    assert( r>=0.0 );
35576    if( r>+1.7976931348623157081452742373e+308L ){
35577#ifdef INFINITY
35578      *pResult = +INFINITY;
35579#else
35580      *pResult = 1.0e308*10.0;
35581#endif
35582    }else{
35583      *pResult = (double)r;
35584    }
35585  }else{
35586    double rr[2];
35587    u64 s2;
35588    rr[0] = (double)s;
35589    s2 = (u64)rr[0];
35590#if defined(_MSC_VER) && _MSC_VER<1700
35591    if( s2==0x8000000000000000LL ){ s2 = 2*(u64)(0.5*rr[0]); }
35592#endif
35593    rr[1] = s>=s2 ? (double)(s - s2) : -(double)(s2 - s);
35594    if( e>0 ){
35595      while( e>=100  ){
35596        e -= 100;
35597        dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83);
35598      }
35599      while( e>=10   ){
35600        e -= 10;
35601        dekkerMul2(rr, 1.0e+10, 0.0);
35602      }
35603      while( e>=1    ){
35604        e -= 1;
35605        dekkerMul2(rr, 1.0e+01, 0.0);
35606      }
35607    }else{
35608      while( e<=-100 ){
35609        e += 100;
35610        dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117);
35611      }
35612      while( e<=-10  ){
35613        e += 10;
35614        dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27);
35615      }
35616      while( e<=-1   ){
35617        e += 1;
35618        dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18);
35619      }
35620    }
35621    *pResult = rr[0]+rr[1];
35622    if( sqlite3IsNaN(*pResult) ) *pResult = 1e300*1e300;
35623  }
35624  if( sign<0 ) *pResult = -*pResult;
35625  assert( !sqlite3IsNaN(*pResult) );
35626
35627atof_return:
35628  /* return true if number and no extra non-whitespace characters after */
35629  if( z==zEnd && nDigit>0 && eValid && eType>0 ){
35630    return eType;
35631  }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){
35632    return -1;
35633  }else{
35634    return 0;
35635  }
35636#else
35637  return !sqlite3Atoi64(z, pResult, length, enc);
35638#endif /* SQLITE_OMIT_FLOATING_POINT */
35639}
35640#if defined(_MSC_VER)
35641#pragma warning(default : 4756)
35642#endif
35643
35644/*
35645** Render an signed 64-bit integer as text.  Store the result in zOut[] and
35646** return the length of the string that was stored, in bytes.  The value
35647** returned does not include the zero terminator at the end of the output
35648** string.
35649**
35650** The caller must ensure that zOut[] is at least 21 bytes in size.
35651*/
35652SQLITE_PRIVATE int sqlite3Int64ToText(i64 v, char *zOut){
35653  int i;
35654  u64 x;
35655  char zTemp[22];
35656  if( v<0 ){
35657    x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v;
35658  }else{
35659    x = v;
35660  }
35661  i = sizeof(zTemp)-2;
35662  zTemp[sizeof(zTemp)-1] = 0;
35663  while( 1 /*exit-by-break*/ ){
35664    zTemp[i] = (x%10) + '0';
35665    x = x/10;
35666    if( x==0 ) break;
35667    i--;
35668  };
35669  if( v<0 ) zTemp[--i] = '-';
35670  memcpy(zOut, &zTemp[i], sizeof(zTemp)-i);
35671  return sizeof(zTemp)-1-i;
35672}
35673
35674/*
35675** Compare the 19-character string zNum against the text representation
35676** value 2^63:  9223372036854775808.  Return negative, zero, or positive
35677** if zNum is less than, equal to, or greater than the string.
35678** Note that zNum must contain exactly 19 characters.
35679**
35680** Unlike memcmp() this routine is guaranteed to return the difference
35681** in the values of the last digit if the only difference is in the
35682** last digit.  So, for example,
35683**
35684**      compare2pow63("9223372036854775800", 1)
35685**
35686** will return -8.
35687*/
35688static int compare2pow63(const char *zNum, int incr){
35689  int c = 0;
35690  int i;
35691                    /* 012345678901234567 */
35692  const char *pow63 = "922337203685477580";
35693  for(i=0; c==0 && i<18; i++){
35694    c = (zNum[i*incr]-pow63[i])*10;
35695  }
35696  if( c==0 ){
35697    c = zNum[18*incr] - '8';
35698    testcase( c==(-1) );
35699    testcase( c==0 );
35700    testcase( c==(+1) );
35701  }
35702  return c;
35703}
35704
35705/*
35706** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
35707** routine does *not* accept hexadecimal notation.
35708**
35709** Returns:
35710**
35711**    -1    Not even a prefix of the input text looks like an integer
35712**     0    Successful transformation.  Fits in a 64-bit signed integer.
35713**     1    Excess non-space text after the integer value
35714**     2    Integer too large for a 64-bit signed integer or is malformed
35715**     3    Special case of 9223372036854775808
35716**
35717** length is the number of bytes in the string (bytes, not characters).
35718** The string is not necessarily zero-terminated.  The encoding is
35719** given by enc.
35720*/
35721SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
35722  int incr;
35723  u64 u = 0;
35724  int neg = 0; /* assume positive */
35725  int i;
35726  int c = 0;
35727  int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
35728  int rc;          /* Baseline return code */
35729  const char *zStart;
35730  const char *zEnd = zNum + length;
35731  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
35732  if( enc==SQLITE_UTF8 ){
35733    incr = 1;
35734  }else{
35735    incr = 2;
35736    length &= ~1;
35737    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
35738    for(i=3-enc; i<length && zNum[i]==0; i+=2){}
35739    nonNum = i<length;
35740    zEnd = &zNum[i^1];
35741    zNum += (enc&1);
35742  }
35743  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
35744  if( zNum<zEnd ){
35745    if( *zNum=='-' ){
35746      neg = 1;
35747      zNum+=incr;
35748    }else if( *zNum=='+' ){
35749      zNum+=incr;
35750    }
35751  }
35752  zStart = zNum;
35753  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
35754  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
35755    u = u*10 + c - '0';
35756  }
35757  testcase( i==18*incr );
35758  testcase( i==19*incr );
35759  testcase( i==20*incr );
35760  if( u>LARGEST_INT64 ){
35761    /* This test and assignment is needed only to suppress UB warnings
35762    ** from clang and -fsanitize=undefined.  This test and assignment make
35763    ** the code a little larger and slower, and no harm comes from omitting
35764    ** them, but we must appease the undefined-behavior pharisees. */
35765    *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
35766  }else if( neg ){
35767    *pNum = -(i64)u;
35768  }else{
35769    *pNum = (i64)u;
35770  }
35771  rc = 0;
35772  if( i==0 && zStart==zNum ){    /* No digits */
35773    rc = -1;
35774  }else if( nonNum ){            /* UTF16 with high-order bytes non-zero */
35775    rc = 1;
35776  }else if( &zNum[i]<zEnd ){     /* Extra bytes at the end */
35777    int jj = i;
35778    do{
35779      if( !sqlite3Isspace(zNum[jj]) ){
35780        rc = 1;          /* Extra non-space text after the integer */
35781        break;
35782      }
35783      jj += incr;
35784    }while( &zNum[jj]<zEnd );
35785  }
35786  if( i<19*incr ){
35787    /* Less than 19 digits, so we know that it fits in 64 bits */
35788    assert( u<=LARGEST_INT64 );
35789    return rc;
35790  }else{
35791    /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
35792    c = i>19*incr ? 1 : compare2pow63(zNum, incr);
35793    if( c<0 ){
35794      /* zNum is less than 9223372036854775808 so it fits */
35795      assert( u<=LARGEST_INT64 );
35796      return rc;
35797    }else{
35798      *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
35799      if( c>0 ){
35800        /* zNum is greater than 9223372036854775808 so it overflows */
35801        return 2;
35802      }else{
35803        /* zNum is exactly 9223372036854775808.  Fits if negative.  The
35804        ** special case 2 overflow if positive */
35805        assert( u-1==LARGEST_INT64 );
35806        return neg ? rc : 3;
35807      }
35808    }
35809  }
35810}
35811
35812/*
35813** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
35814** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
35815** whereas sqlite3Atoi64() does not.
35816**
35817** Returns:
35818**
35819**     0    Successful transformation.  Fits in a 64-bit signed integer.
35820**     1    Excess text after the integer value
35821**     2    Integer too large for a 64-bit signed integer or is malformed
35822**     3    Special case of 9223372036854775808
35823*/
35824SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
35825#ifndef SQLITE_OMIT_HEX_INTEGER
35826  if( z[0]=='0'
35827   && (z[1]=='x' || z[1]=='X')
35828  ){
35829    u64 u = 0;
35830    int i, k;
35831    for(i=2; z[i]=='0'; i++){}
35832    for(k=i; sqlite3Isxdigit(z[k]); k++){
35833      u = u*16 + sqlite3HexToInt(z[k]);
35834    }
35835    memcpy(pOut, &u, 8);
35836    if( k-i>16 ) return 2;
35837    if( z[k]!=0 ) return 1;
35838    return 0;
35839  }else
35840#endif /* SQLITE_OMIT_HEX_INTEGER */
35841  {
35842    int n = (int)(0x3fffffff&strspn(z,"+- \n\t0123456789"));
35843    if( z[n] ) n++;
35844    return sqlite3Atoi64(z, pOut, n, SQLITE_UTF8);
35845  }
35846}
35847
35848/*
35849** If zNum represents an integer that will fit in 32-bits, then set
35850** *pValue to that integer and return true.  Otherwise return false.
35851**
35852** This routine accepts both decimal and hexadecimal notation for integers.
35853**
35854** Any non-numeric characters that following zNum are ignored.
35855** This is different from sqlite3Atoi64() which requires the
35856** input number to be zero-terminated.
35857*/
35858SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
35859  sqlite_int64 v = 0;
35860  int i, c;
35861  int neg = 0;
35862  if( zNum[0]=='-' ){
35863    neg = 1;
35864    zNum++;
35865  }else if( zNum[0]=='+' ){
35866    zNum++;
35867  }
35868#ifndef SQLITE_OMIT_HEX_INTEGER
35869  else if( zNum[0]=='0'
35870        && (zNum[1]=='x' || zNum[1]=='X')
35871        && sqlite3Isxdigit(zNum[2])
35872  ){
35873    u32 u = 0;
35874    zNum += 2;
35875    while( zNum[0]=='0' ) zNum++;
35876    for(i=0; i<8 && sqlite3Isxdigit(zNum[i]); i++){
35877      u = u*16 + sqlite3HexToInt(zNum[i]);
35878    }
35879    if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
35880      memcpy(pValue, &u, 4);
35881      return 1;
35882    }else{
35883      return 0;
35884    }
35885  }
35886#endif
35887  if( !sqlite3Isdigit(zNum[0]) ) return 0;
35888  while( zNum[0]=='0' ) zNum++;
35889  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
35890    v = v*10 + c;
35891  }
35892
35893  /* The longest decimal representation of a 32 bit integer is 10 digits:
35894  **
35895  **             1234567890
35896  **     2^31 -> 2147483648
35897  */
35898  testcase( i==10 );
35899  if( i>10 ){
35900    return 0;
35901  }
35902  testcase( v-neg==2147483647 );
35903  if( v-neg>2147483647 ){
35904    return 0;
35905  }
35906  if( neg ){
35907    v = -v;
35908  }
35909  *pValue = (int)v;
35910  return 1;
35911}
35912
35913/*
35914** Return a 32-bit integer value extracted from a string.  If the
35915** string is not an integer, just return 0.
35916*/
35917SQLITE_PRIVATE int sqlite3Atoi(const char *z){
35918  int x = 0;
35919  sqlite3GetInt32(z, &x);
35920  return x;
35921}
35922
35923/*
35924** Decode a floating-point value into an approximate decimal
35925** representation.
35926**
35927** Round the decimal representation to n significant digits if
35928** n is positive.  Or round to -n signficant digits after the
35929** decimal point if n is negative.  No rounding is performed if
35930** n is zero.
35931**
35932** The significant digits of the decimal representation are
35933** stored in p->z[] which is a often (but not always) a pointer
35934** into the middle of p->zBuf[].  There are p->n significant digits.
35935** The p->z[] array is *not* zero-terminated.
35936*/
35937SQLITE_PRIVATE void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRound){
35938  int i;
35939  u64 v;
35940  int e, exp = 0;
35941  p->isSpecial = 0;
35942  p->z = p->zBuf;
35943
35944  /* Convert negative numbers to positive.  Deal with Infinity, 0.0, and
35945  ** NaN. */
35946  if( r<0.0 ){
35947    p->sign = '-';
35948    r = -r;
35949  }else if( r==0.0 ){
35950    p->sign = '+';
35951    p->n = 1;
35952    p->iDP = 1;
35953    p->z = "0";
35954    return;
35955  }else{
35956    p->sign = '+';
35957  }
35958  memcpy(&v,&r,8);
35959  e = v>>52;
35960  if( (e&0x7ff)==0x7ff ){
35961    p->isSpecial = 1 + (v!=0x7ff0000000000000LL);
35962    p->n = 0;
35963    p->iDP = 0;
35964    return;
35965  }
35966
35967  /* Multiply r by powers of ten until it lands somewhere in between
35968  ** 1.0e+19 and 1.0e+17.
35969  */
35970  if( sqlite3Config.bUseLongDouble ){
35971    LONGDOUBLE_TYPE rr = r;
35972    if( rr>=1.0e+19 ){
35973      while( rr>=1.0e+119L ){ exp+=100; rr *= 1.0e-100L; }
35974      while( rr>=1.0e+29L  ){ exp+=10;  rr *= 1.0e-10L;  }
35975      while( rr>=1.0e+19L  ){ exp++;    rr *= 1.0e-1L;   }
35976    }else{
35977      while( rr<1.0e-97L   ){ exp-=100; rr *= 1.0e+100L; }
35978      while( rr<1.0e+07L   ){ exp-=10;  rr *= 1.0e+10L;  }
35979      while( rr<1.0e+17L   ){ exp--;    rr *= 1.0e+1L;   }
35980    }
35981    v = (u64)rr;
35982  }else{
35983    /* If high-precision floating point is not available using "long double",
35984    ** then use Dekker-style double-double computation to increase the
35985    ** precision.
35986    **
35987    ** The error terms on constants like 1.0e+100 computed using the
35988    ** decimal extension, for example as follows:
35989    **
35990    **   SELECT decimal_exp(decimal_sub('1.0e+100',decimal(1.0e+100)));
35991    */
35992    double rr[2];
35993    rr[0] = r;
35994    rr[1] = 0.0;
35995    if( rr[0]>9.223372036854774784e+18 ){
35996      while( rr[0]>9.223372036854774784e+118 ){
35997        exp += 100;
35998        dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117);
35999      }
36000      while( rr[0]>9.223372036854774784e+28 ){
36001        exp += 10;
36002        dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27);
36003      }
36004      while( rr[0]>9.223372036854774784e+18 ){
36005        exp += 1;
36006        dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18);
36007      }
36008    }else{
36009      while( rr[0]<9.223372036854774784e-83  ){
36010        exp -= 100;
36011        dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83);
36012      }
36013      while( rr[0]<9.223372036854774784e+07  ){
36014        exp -= 10;
36015        dekkerMul2(rr, 1.0e+10, 0.0);
36016      }
36017      while( rr[0]<9.22337203685477478e+17  ){
36018        exp -= 1;
36019        dekkerMul2(rr, 1.0e+01, 0.0);
36020      }
36021    }
36022    v = rr[1]<0.0 ? (u64)rr[0]-(u64)(-rr[1]) : (u64)rr[0]+(u64)rr[1];
36023  }
36024
36025
36026  /* Extract significant digits. */
36027  i = sizeof(p->zBuf)-1;
36028  assert( v>0 );
36029  while( v ){  p->zBuf[i--] = (v%10) + '0'; v /= 10; }
36030  assert( i>=0 && i<sizeof(p->zBuf)-1 );
36031  p->n = sizeof(p->zBuf) - 1 - i;
36032  assert( p->n>0 );
36033  assert( p->n<sizeof(p->zBuf) );
36034  p->iDP = p->n + exp;
36035  if( iRound<=0 ){
36036    iRound = p->iDP - iRound;
36037    if( iRound==0 && p->zBuf[i+1]>='5' ){
36038      iRound = 1;
36039      p->zBuf[i--] = '0';
36040      p->n++;
36041      p->iDP++;
36042    }
36043  }
36044  if( iRound>0 && (iRound<p->n || p->n>mxRound) ){
36045    char *z = &p->zBuf[i+1];
36046    if( iRound>mxRound ) iRound = mxRound;
36047    p->n = iRound;
36048    if( z[iRound]>='5' ){
36049      int j = iRound-1;
36050      while( 1 /*exit-by-break*/ ){
36051        z[j]++;
36052        if( z[j]<='9' ) break;
36053        z[j] = '0';
36054        if( j==0 ){
36055          p->z[i--] = '1';
36056          p->n++;
36057          p->iDP++;
36058          break;
36059        }else{
36060          j--;
36061        }
36062      }
36063    }
36064  }
36065  p->z = &p->zBuf[i+1];
36066  assert( i+p->n < sizeof(p->zBuf) );
36067  while( ALWAYS(p->n>0) && p->z[p->n-1]=='0' ){ p->n--; }
36068}
36069
36070/*
36071** Try to convert z into an unsigned 32-bit integer.  Return true on
36072** success and false if there is an error.
36073**
36074** Only decimal notation is accepted.
36075*/
36076SQLITE_PRIVATE int sqlite3GetUInt32(const char *z, u32 *pI){
36077  u64 v = 0;
36078  int i;
36079  for(i=0; sqlite3Isdigit(z[i]); i++){
36080    v = v*10 + z[i] - '0';
36081    if( v>4294967296LL ){ *pI = 0; return 0; }
36082  }
36083  if( i==0 || z[i]!=0 ){ *pI = 0; return 0; }
36084  *pI = (u32)v;
36085  return 1;
36086}
36087
36088/*
36089** The variable-length integer encoding is as follows:
36090**
36091** KEY:
36092**         A = 0xxxxxxx    7 bits of data and one flag bit
36093**         B = 1xxxxxxx    7 bits of data and one flag bit
36094**         C = xxxxxxxx    8 bits of data
36095**
36096**  7 bits - A
36097** 14 bits - BA
36098** 21 bits - BBA
36099** 28 bits - BBBA
36100** 35 bits - BBBBA
36101** 42 bits - BBBBBA
36102** 49 bits - BBBBBBA
36103** 56 bits - BBBBBBBA
36104** 64 bits - BBBBBBBBC
36105*/
36106
36107/*
36108** Write a 64-bit variable-length integer to memory starting at p[0].
36109** The length of data write will be between 1 and 9 bytes.  The number
36110** of bytes written is returned.
36111**
36112** A variable-length integer consists of the lower 7 bits of each byte
36113** for all bytes that have the 8th bit set and one byte with the 8th
36114** bit clear.  Except, if we get to the 9th byte, it stores the full
36115** 8 bits and is the last byte.
36116*/
36117static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
36118  int i, j, n;
36119  u8 buf[10];
36120  if( v & (((u64)0xff000000)<<32) ){
36121    p[8] = (u8)v;
36122    v >>= 8;
36123    for(i=7; i>=0; i--){
36124      p[i] = (u8)((v & 0x7f) | 0x80);
36125      v >>= 7;
36126    }
36127    return 9;
36128  }
36129  n = 0;
36130  do{
36131    buf[n++] = (u8)((v & 0x7f) | 0x80);
36132    v >>= 7;
36133  }while( v!=0 );
36134  buf[0] &= 0x7f;
36135  assert( n<=9 );
36136  for(i=0, j=n-1; j>=0; j--, i++){
36137    p[i] = buf[j];
36138  }
36139  return n;
36140}
36141SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
36142  if( v<=0x7f ){
36143    p[0] = v&0x7f;
36144    return 1;
36145  }
36146  if( v<=0x3fff ){
36147    p[0] = ((v>>7)&0x7f)|0x80;
36148    p[1] = v&0x7f;
36149    return 2;
36150  }
36151  return putVarint64(p,v);
36152}
36153
36154/*
36155** Bitmasks used by sqlite3GetVarint().  These precomputed constants
36156** are defined here rather than simply putting the constant expressions
36157** inline in order to work around bugs in the RVT compiler.
36158**
36159** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
36160**
36161** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
36162*/
36163#define SLOT_2_0     0x001fc07f
36164#define SLOT_4_2_0   0xf01fc07f
36165
36166
36167/*
36168** Read a 64-bit variable-length integer from memory starting at p[0].
36169** Return the number of bytes read.  The value is stored in *v.
36170*/
36171SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
36172  u32 a,b,s;
36173
36174  if( ((signed char*)p)[0]>=0 ){
36175    *v = *p;
36176    return 1;
36177  }
36178  if( ((signed char*)p)[1]>=0 ){
36179    *v = ((u32)(p[0]&0x7f)<<7) | p[1];
36180    return 2;
36181  }
36182
36183  /* Verify that constants are precomputed correctly */
36184  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
36185  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
36186
36187  a = ((u32)p[0])<<14;
36188  b = p[1];
36189  p += 2;
36190  a |= *p;
36191  /* a: p0<<14 | p2 (unmasked) */
36192  if (!(a&0x80))
36193  {
36194    a &= SLOT_2_0;
36195    b &= 0x7f;
36196    b = b<<7;
36197    a |= b;
36198    *v = a;
36199    return 3;
36200  }
36201
36202  /* CSE1 from below */
36203  a &= SLOT_2_0;
36204  p++;
36205  b = b<<14;
36206  b |= *p;
36207  /* b: p1<<14 | p3 (unmasked) */
36208  if (!(b&0x80))
36209  {
36210    b &= SLOT_2_0;
36211    /* moved CSE1 up */
36212    /* a &= (0x7f<<14)|(0x7f); */
36213    a = a<<7;
36214    a |= b;
36215    *v = a;
36216    return 4;
36217  }
36218
36219  /* a: p0<<14 | p2 (masked) */
36220  /* b: p1<<14 | p3 (unmasked) */
36221  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
36222  /* moved CSE1 up */
36223  /* a &= (0x7f<<14)|(0x7f); */
36224  b &= SLOT_2_0;
36225  s = a;
36226  /* s: p0<<14 | p2 (masked) */
36227
36228  p++;
36229  a = a<<14;
36230  a |= *p;
36231  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
36232  if (!(a&0x80))
36233  {
36234    /* we can skip these cause they were (effectively) done above
36235    ** while calculating s */
36236    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
36237    /* b &= (0x7f<<14)|(0x7f); */
36238    b = b<<7;
36239    a |= b;
36240    s = s>>18;
36241    *v = ((u64)s)<<32 | a;
36242    return 5;
36243  }
36244
36245  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
36246  s = s<<7;
36247  s |= b;
36248  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
36249
36250  p++;
36251  b = b<<14;
36252  b |= *p;
36253  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
36254  if (!(b&0x80))
36255  {
36256    /* we can skip this cause it was (effectively) done above in calc'ing s */
36257    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
36258    a &= SLOT_2_0;
36259    a = a<<7;
36260    a |= b;
36261    s = s>>18;
36262    *v = ((u64)s)<<32 | a;
36263    return 6;
36264  }
36265
36266  p++;
36267  a = a<<14;
36268  a |= *p;
36269  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
36270  if (!(a&0x80))
36271  {
36272    a &= SLOT_4_2_0;
36273    b &= SLOT_2_0;
36274    b = b<<7;
36275    a |= b;
36276    s = s>>11;
36277    *v = ((u64)s)<<32 | a;
36278    return 7;
36279  }
36280
36281  /* CSE2 from below */
36282  a &= SLOT_2_0;
36283  p++;
36284  b = b<<14;
36285  b |= *p;
36286  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
36287  if (!(b&0x80))
36288  {
36289    b &= SLOT_4_2_0;
36290    /* moved CSE2 up */
36291    /* a &= (0x7f<<14)|(0x7f); */
36292    a = a<<7;
36293    a |= b;
36294    s = s>>4;
36295    *v = ((u64)s)<<32 | a;
36296    return 8;
36297  }
36298
36299  p++;
36300  a = a<<15;
36301  a |= *p;
36302  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
36303
36304  /* moved CSE2 up */
36305  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
36306  b &= SLOT_2_0;
36307  b = b<<8;
36308  a |= b;
36309
36310  s = s<<4;
36311  b = p[-4];
36312  b &= 0x7f;
36313  b = b>>3;
36314  s |= b;
36315
36316  *v = ((u64)s)<<32 | a;
36317
36318  return 9;
36319}
36320
36321/*
36322** Read a 32-bit variable-length integer from memory starting at p[0].
36323** Return the number of bytes read.  The value is stored in *v.
36324**
36325** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
36326** integer, then set *v to 0xffffffff.
36327**
36328** A MACRO version, getVarint32, is provided which inlines the
36329** single-byte case.  All code should use the MACRO version as
36330** this function assumes the single-byte case has already been handled.
36331*/
36332SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
36333  u64 v64;
36334  u8 n;
36335
36336  /* Assume that the single-byte case has already been handled by
36337  ** the getVarint32() macro */
36338  assert( (p[0] & 0x80)!=0 );
36339
36340  if( (p[1] & 0x80)==0 ){
36341    /* This is the two-byte case */
36342    *v = ((p[0]&0x7f)<<7) | p[1];
36343    return 2;
36344  }
36345  if( (p[2] & 0x80)==0 ){
36346    /* This is the three-byte case */
36347    *v = ((p[0]&0x7f)<<14) | ((p[1]&0x7f)<<7) | p[2];
36348    return 3;
36349  }
36350  /* four or more bytes */
36351  n = sqlite3GetVarint(p, &v64);
36352  assert( n>3 && n<=9 );
36353  if( (v64 & SQLITE_MAX_U32)!=v64 ){
36354    *v = 0xffffffff;
36355  }else{
36356    *v = (u32)v64;
36357  }
36358  return n;
36359}
36360
36361/*
36362** Return the number of bytes that will be needed to store the given
36363** 64-bit integer.
36364*/
36365SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
36366  int i;
36367  for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
36368  return i;
36369}
36370
36371
36372/*
36373** Read or write a four-byte big-endian integer value.
36374*/
36375SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
36376#if SQLITE_BYTEORDER==4321
36377  u32 x;
36378  memcpy(&x,p,4);
36379  return x;
36380#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
36381  u32 x;
36382  memcpy(&x,p,4);
36383  return __builtin_bswap32(x);
36384#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
36385  u32 x;
36386  memcpy(&x,p,4);
36387  return _byteswap_ulong(x);
36388#else
36389  testcase( p[0]&0x80 );
36390  return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
36391#endif
36392}
36393SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
36394#if SQLITE_BYTEORDER==4321
36395  memcpy(p,&v,4);
36396#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
36397  u32 x = __builtin_bswap32(v);
36398  memcpy(p,&x,4);
36399#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
36400  u32 x = _byteswap_ulong(v);
36401  memcpy(p,&x,4);
36402#else
36403  p[0] = (u8)(v>>24);
36404  p[1] = (u8)(v>>16);
36405  p[2] = (u8)(v>>8);
36406  p[3] = (u8)v;
36407#endif
36408}
36409
36410
36411
36412/*
36413** Translate a single byte of Hex into an integer.
36414** This routine only works if h really is a valid hexadecimal
36415** character:  0..9a..fA..F
36416*/
36417SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
36418  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
36419#ifdef SQLITE_ASCII
36420  h += 9*(1&(h>>6));
36421#endif
36422#ifdef SQLITE_EBCDIC
36423  h += 9*(1&~(h>>4));
36424#endif
36425  return (u8)(h & 0xf);
36426}
36427
36428#if !defined(SQLITE_OMIT_BLOB_LITERAL)
36429/*
36430** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
36431** value.  Return a pointer to its binary value.  Space to hold the
36432** binary value has been obtained from malloc and must be freed by
36433** the calling routine.
36434*/
36435SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
36436  char *zBlob;
36437  int i;
36438
36439  zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
36440  n--;
36441  if( zBlob ){
36442    for(i=0; i<n; i+=2){
36443      zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
36444    }
36445    zBlob[i/2] = 0;
36446  }
36447  return zBlob;
36448}
36449#endif /* !SQLITE_OMIT_BLOB_LITERAL */
36450
36451/*
36452** Log an error that is an API call on a connection pointer that should
36453** not have been used.  The "type" of connection pointer is given as the
36454** argument.  The zType is a word like "NULL" or "closed" or "invalid".
36455*/
36456static void logBadConnection(const char *zType){
36457  sqlite3_log(SQLITE_MISUSE,
36458     "API call with %s database connection pointer",
36459     zType
36460  );
36461}
36462
36463/*
36464** Check to make sure we have a valid db pointer.  This test is not
36465** foolproof but it does provide some measure of protection against
36466** misuse of the interface such as passing in db pointers that are
36467** NULL or which have been previously closed.  If this routine returns
36468** 1 it means that the db pointer is valid and 0 if it should not be
36469** dereferenced for any reason.  The calling function should invoke
36470** SQLITE_MISUSE immediately.
36471**
36472** sqlite3SafetyCheckOk() requires that the db pointer be valid for
36473** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
36474** open properly and is not fit for general use but which can be
36475** used as an argument to sqlite3_errmsg() or sqlite3_close().
36476*/
36477SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
36478  u8 eOpenState;
36479  if( db==0 ){
36480    logBadConnection("NULL");
36481    return 0;
36482  }
36483  eOpenState = db->eOpenState;
36484  if( eOpenState!=SQLITE_STATE_OPEN ){
36485    if( sqlite3SafetyCheckSickOrOk(db) ){
36486      testcase( sqlite3GlobalConfig.xLog!=0 );
36487      logBadConnection("unopened");
36488    }
36489    return 0;
36490  }else{
36491    return 1;
36492  }
36493}
36494SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
36495  u8 eOpenState;
36496  eOpenState = db->eOpenState;
36497  if( eOpenState!=SQLITE_STATE_SICK &&
36498      eOpenState!=SQLITE_STATE_OPEN &&
36499      eOpenState!=SQLITE_STATE_BUSY ){
36500    testcase( sqlite3GlobalConfig.xLog!=0 );
36501    logBadConnection("invalid");
36502    return 0;
36503  }else{
36504    return 1;
36505  }
36506}
36507
36508/*
36509** Attempt to add, subtract, or multiply the 64-bit signed value iB against
36510** the other 64-bit signed integer at *pA and store the result in *pA.
36511** Return 0 on success.  Or if the operation would have resulted in an
36512** overflow, leave *pA unchanged and return 1.
36513*/
36514SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
36515#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
36516  return __builtin_add_overflow(*pA, iB, pA);
36517#else
36518  i64 iA = *pA;
36519  testcase( iA==0 ); testcase( iA==1 );
36520  testcase( iB==-1 ); testcase( iB==0 );
36521  if( iB>=0 ){
36522    testcase( iA>0 && LARGEST_INT64 - iA == iB );
36523    testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
36524    if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
36525  }else{
36526    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
36527    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
36528    if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
36529  }
36530  *pA += iB;
36531  return 0;
36532#endif
36533}
36534SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
36535#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
36536  return __builtin_sub_overflow(*pA, iB, pA);
36537#else
36538  testcase( iB==SMALLEST_INT64+1 );
36539  if( iB==SMALLEST_INT64 ){
36540    testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
36541    if( (*pA)>=0 ) return 1;
36542    *pA -= iB;
36543    return 0;
36544  }else{
36545    return sqlite3AddInt64(pA, -iB);
36546  }
36547#endif
36548}
36549SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
36550#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
36551  return __builtin_mul_overflow(*pA, iB, pA);
36552#else
36553  i64 iA = *pA;
36554  if( iB>0 ){
36555    if( iA>LARGEST_INT64/iB ) return 1;
36556    if( iA<SMALLEST_INT64/iB ) return 1;
36557  }else if( iB<0 ){
36558    if( iA>0 ){
36559      if( iB<SMALLEST_INT64/iA ) return 1;
36560    }else if( iA<0 ){
36561      if( iB==SMALLEST_INT64 ) return 1;
36562      if( iA==SMALLEST_INT64 ) return 1;
36563      if( -iA>LARGEST_INT64/-iB ) return 1;
36564    }
36565  }
36566  *pA = iA*iB;
36567  return 0;
36568#endif
36569}
36570
36571/*
36572** Compute the absolute value of a 32-bit signed integer, of possible.  Or
36573** if the integer has a value of -2147483648, return +2147483647
36574*/
36575SQLITE_PRIVATE int sqlite3AbsInt32(int x){
36576  if( x>=0 ) return x;
36577  if( x==(int)0x80000000 ) return 0x7fffffff;
36578  return -x;
36579}
36580
36581#ifdef SQLITE_ENABLE_8_3_NAMES
36582/*
36583** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
36584** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
36585** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
36586** three characters, then shorten the suffix on z[] to be the last three
36587** characters of the original suffix.
36588**
36589** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
36590** do the suffix shortening regardless of URI parameter.
36591**
36592** Examples:
36593**
36594**     test.db-journal    =>   test.nal
36595**     test.db-wal        =>   test.wal
36596**     test.db-shm        =>   test.shm
36597**     test.db-mj7f3319fa =>   test.9fa
36598*/
36599SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
36600#if SQLITE_ENABLE_8_3_NAMES<2
36601  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
36602#endif
36603  {
36604    int i, sz;
36605    sz = sqlite3Strlen30(z);
36606    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
36607    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
36608  }
36609}
36610#endif
36611
36612/*
36613** Find (an approximate) sum of two LogEst values.  This computation is
36614** not a simple "+" operator because LogEst is stored as a logarithmic
36615** value.
36616**
36617*/
36618SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
36619  static const unsigned char x[] = {
36620     10, 10,                         /* 0,1 */
36621      9, 9,                          /* 2,3 */
36622      8, 8,                          /* 4,5 */
36623      7, 7, 7,                       /* 6,7,8 */
36624      6, 6, 6,                       /* 9,10,11 */
36625      5, 5, 5,                       /* 12-14 */
36626      4, 4, 4, 4,                    /* 15-18 */
36627      3, 3, 3, 3, 3, 3,              /* 19-24 */
36628      2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
36629  };
36630  if( a>=b ){
36631    if( a>b+49 ) return a;
36632    if( a>b+31 ) return a+1;
36633    return a+x[a-b];
36634  }else{
36635    if( b>a+49 ) return b;
36636    if( b>a+31 ) return b+1;
36637    return b+x[b-a];
36638  }
36639}
36640
36641/*
36642** Convert an integer into a LogEst.  In other words, compute an
36643** approximation for 10*log2(x).
36644*/
36645SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
36646  static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
36647  LogEst y = 40;
36648  if( x<8 ){
36649    if( x<2 ) return 0;
36650    while( x<8 ){  y -= 10; x <<= 1; }
36651  }else{
36652#if GCC_VERSION>=5004000
36653    int i = 60 - __builtin_clzll(x);
36654    y += i*10;
36655    x >>= i;
36656#else
36657    while( x>255 ){ y += 40; x >>= 4; }  /*OPTIMIZATION-IF-TRUE*/
36658    while( x>15 ){  y += 10; x >>= 1; }
36659#endif
36660  }
36661  return a[x&7] + y - 10;
36662}
36663
36664/*
36665** Convert a double into a LogEst
36666** In other words, compute an approximation for 10*log2(x).
36667*/
36668SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
36669  u64 a;
36670  LogEst e;
36671  assert( sizeof(x)==8 && sizeof(a)==8 );
36672  if( x<=1 ) return 0;
36673  if( x<=2000000000 ) return sqlite3LogEst((u64)x);
36674  memcpy(&a, &x, 8);
36675  e = (a>>52) - 1022;
36676  return e*10;
36677}
36678
36679/*
36680** Convert a LogEst into an integer.
36681*/
36682SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
36683  u64 n;
36684  n = x%10;
36685  x /= 10;
36686  if( n>=5 ) n -= 2;
36687  else if( n>=1 ) n -= 1;
36688  if( x>60 ) return (u64)LARGEST_INT64;
36689  return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
36690}
36691
36692/*
36693** Add a new name/number pair to a VList.  This might require that the
36694** VList object be reallocated, so return the new VList.  If an OOM
36695** error occurs, the original VList returned and the
36696** db->mallocFailed flag is set.
36697**
36698** A VList is really just an array of integers.  To destroy a VList,
36699** simply pass it to sqlite3DbFree().
36700**
36701** The first integer is the number of integers allocated for the whole
36702** VList.  The second integer is the number of integers actually used.
36703** Each name/number pair is encoded by subsequent groups of 3 or more
36704** integers.
36705**
36706** Each name/number pair starts with two integers which are the numeric
36707** value for the pair and the size of the name/number pair, respectively.
36708** The text name overlays one or more following integers.  The text name
36709** is always zero-terminated.
36710**
36711** Conceptually:
36712**
36713**    struct VList {
36714**      int nAlloc;   // Number of allocated slots
36715**      int nUsed;    // Number of used slots
36716**      struct VListEntry {
36717**        int iValue;    // Value for this entry
36718**        int nSlot;     // Slots used by this entry
36719**        // ... variable name goes here
36720**      } a[0];
36721**    }
36722**
36723** During code generation, pointers to the variable names within the
36724** VList are taken.  When that happens, nAlloc is set to zero as an
36725** indication that the VList may never again be enlarged, since the
36726** accompanying realloc() would invalidate the pointers.
36727*/
36728SQLITE_PRIVATE VList *sqlite3VListAdd(
36729  sqlite3 *db,           /* The database connection used for malloc() */
36730  VList *pIn,            /* The input VList.  Might be NULL */
36731  const char *zName,     /* Name of symbol to add */
36732  int nName,             /* Bytes of text in zName */
36733  int iVal               /* Value to associate with zName */
36734){
36735  int nInt;              /* number of sizeof(int) objects needed for zName */
36736  char *z;               /* Pointer to where zName will be stored */
36737  int i;                 /* Index in pIn[] where zName is stored */
36738
36739  nInt = nName/4 + 3;
36740  assert( pIn==0 || pIn[0]>=3 );  /* Verify ok to add new elements */
36741  if( pIn==0 || pIn[1]+nInt > pIn[0] ){
36742    /* Enlarge the allocation */
36743    sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt;
36744    VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
36745    if( pOut==0 ) return pIn;
36746    if( pIn==0 ) pOut[1] = 2;
36747    pIn = pOut;
36748    pIn[0] = nAlloc;
36749  }
36750  i = pIn[1];
36751  pIn[i] = iVal;
36752  pIn[i+1] = nInt;
36753  z = (char*)&pIn[i+2];
36754  pIn[1] = i+nInt;
36755  assert( pIn[1]<=pIn[0] );
36756  memcpy(z, zName, nName);
36757  z[nName] = 0;
36758  return pIn;
36759}
36760
36761/*
36762** Return a pointer to the name of a variable in the given VList that
36763** has the value iVal.  Or return a NULL if there is no such variable in
36764** the list
36765*/
36766SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
36767  int i, mx;
36768  if( pIn==0 ) return 0;
36769  mx = pIn[1];
36770  i = 2;
36771  do{
36772    if( pIn[i]==iVal ) return (char*)&pIn[i+2];
36773    i += pIn[i+1];
36774  }while( i<mx );
36775  return 0;
36776}
36777
36778/*
36779** Return the number of the variable named zName, if it is in VList.
36780** or return 0 if there is no such variable.
36781*/
36782SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
36783  int i, mx;
36784  if( pIn==0 ) return 0;
36785  mx = pIn[1];
36786  i = 2;
36787  do{
36788    const char *z = (const char*)&pIn[i+2];
36789    if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
36790    i += pIn[i+1];
36791  }while( i<mx );
36792  return 0;
36793}
36794
36795/*
36796** High-resolution hardware timer used for debugging and testing only.
36797*/
36798#if defined(VDBE_PROFILE)  \
36799 || defined(SQLITE_PERFORMANCE_TRACE) \
36800 || defined(SQLITE_ENABLE_STMT_SCANSTATUS)
36801/************** Include hwtime.h in the middle of util.c *********************/
36802/************** Begin file hwtime.h ******************************************/
36803/*
36804** 2008 May 27
36805**
36806** The author disclaims copyright to this source code.  In place of
36807** a legal notice, here is a blessing:
36808**
36809**    May you do good and not evil.
36810**    May you find forgiveness for yourself and forgive others.
36811**    May you share freely, never taking more than you give.
36812**
36813******************************************************************************
36814**
36815** This file contains inline asm code for retrieving "high-performance"
36816** counters for x86 and x86_64 class CPUs.
36817*/
36818#ifndef SQLITE_HWTIME_H
36819#define SQLITE_HWTIME_H
36820
36821/*
36822** The following routine only works on Pentium-class (or newer) processors.
36823** It uses the RDTSC opcode to read the cycle count value out of the
36824** processor and returns that value.  This can be used for high-res
36825** profiling.
36826*/
36827#if !defined(__STRICT_ANSI__) && \
36828    (defined(__GNUC__) || defined(_MSC_VER)) && \
36829    (defined(i386) || defined(__i386__) || defined(_M_IX86))
36830
36831  #if defined(__GNUC__)
36832
36833  __inline__ sqlite_uint64 sqlite3Hwtime(void){
36834     unsigned int lo, hi;
36835     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
36836     return (sqlite_uint64)hi << 32 | lo;
36837  }
36838
36839  #elif defined(_MSC_VER)
36840
36841  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
36842     __asm {
36843        rdtsc
36844        ret       ; return value at EDX:EAX
36845     }
36846  }
36847
36848  #endif
36849
36850#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
36851
36852  __inline__ sqlite_uint64 sqlite3Hwtime(void){
36853     unsigned int lo, hi;
36854     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
36855     return (sqlite_uint64)hi << 32 | lo;
36856  }
36857
36858#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
36859
36860  __inline__ sqlite_uint64 sqlite3Hwtime(void){
36861      unsigned long long retval;
36862      unsigned long junk;
36863      __asm__ __volatile__ ("\n\
36864          1:      mftbu   %1\n\
36865                  mftb    %L0\n\
36866                  mftbu   %0\n\
36867                  cmpw    %0,%1\n\
36868                  bne     1b"
36869                  : "=r" (retval), "=r" (junk));
36870      return retval;
36871  }
36872
36873#else
36874
36875  /*
36876  ** asm() is needed for hardware timing support.  Without asm(),
36877  ** disable the sqlite3Hwtime() routine.
36878  **
36879  ** sqlite3Hwtime() is only used for some obscure debugging
36880  ** and analysis configurations, not in any deliverable, so this
36881  ** should not be a great loss.
36882  */
36883SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
36884
36885#endif
36886
36887#endif /* !defined(SQLITE_HWTIME_H) */
36888
36889/************** End of hwtime.h **********************************************/
36890/************** Continuing where we left off in util.c ***********************/
36891#endif
36892
36893/************** End of util.c ************************************************/
36894/************** Begin file hash.c ********************************************/
36895/*
36896** 2001 September 22
36897**
36898** The author disclaims copyright to this source code.  In place of
36899** a legal notice, here is a blessing:
36900**
36901**    May you do good and not evil.
36902**    May you find forgiveness for yourself and forgive others.
36903**    May you share freely, never taking more than you give.
36904**
36905*************************************************************************
36906** This is the implementation of generic hash-tables
36907** used in SQLite.
36908*/
36909/* #include "sqliteInt.h" */
36910/* #include <assert.h> */
36911
36912/* Turn bulk memory into a hash table object by initializing the
36913** fields of the Hash structure.
36914**
36915** "pNew" is a pointer to the hash table that is to be initialized.
36916*/
36917SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
36918  assert( pNew!=0 );
36919  pNew->first = 0;
36920  pNew->count = 0;
36921  pNew->htsize = 0;
36922  pNew->ht = 0;
36923}
36924
36925/* Remove all entries from a hash table.  Reclaim all memory.
36926** Call this routine to delete a hash table or to reset a hash table
36927** to the empty state.
36928*/
36929SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
36930  HashElem *elem;         /* For looping over all elements of the table */
36931
36932  assert( pH!=0 );
36933  elem = pH->first;
36934  pH->first = 0;
36935  sqlite3_free(pH->ht);
36936  pH->ht = 0;
36937  pH->htsize = 0;
36938  while( elem ){
36939    HashElem *next_elem = elem->next;
36940    sqlite3_free(elem);
36941    elem = next_elem;
36942  }
36943  pH->count = 0;
36944}
36945
36946/*
36947** The hashing function.
36948*/
36949static unsigned int strHash(const char *z){
36950  unsigned int h = 0;
36951  unsigned char c;
36952  while( (c = (unsigned char)*z++)!=0 ){     /*OPTIMIZATION-IF-TRUE*/
36953    /* Knuth multiplicative hashing.  (Sorting & Searching, p. 510).
36954    ** 0x9e3779b1 is 2654435761 which is the closest prime number to
36955    ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
36956    h += sqlite3UpperToLower[c];
36957    h *= 0x9e3779b1;
36958  }
36959  return h;
36960}
36961
36962
36963/* Link pNew element into the hash table pH.  If pEntry!=0 then also
36964** insert pNew into the pEntry hash bucket.
36965*/
36966static void insertElement(
36967  Hash *pH,              /* The complete hash table */
36968  struct _ht *pEntry,    /* The entry into which pNew is inserted */
36969  HashElem *pNew         /* The element to be inserted */
36970){
36971  HashElem *pHead;       /* First element already in pEntry */
36972  if( pEntry ){
36973    pHead = pEntry->count ? pEntry->chain : 0;
36974    pEntry->count++;
36975    pEntry->chain = pNew;
36976  }else{
36977    pHead = 0;
36978  }
36979  if( pHead ){
36980    pNew->next = pHead;
36981    pNew->prev = pHead->prev;
36982    if( pHead->prev ){ pHead->prev->next = pNew; }
36983    else             { pH->first = pNew; }
36984    pHead->prev = pNew;
36985  }else{
36986    pNew->next = pH->first;
36987    if( pH->first ){ pH->first->prev = pNew; }
36988    pNew->prev = 0;
36989    pH->first = pNew;
36990  }
36991}
36992
36993
36994/* Resize the hash table so that it contains "new_size" buckets.
36995**
36996** The hash table might fail to resize if sqlite3_malloc() fails or
36997** if the new size is the same as the prior size.
36998** Return TRUE if the resize occurs and false if not.
36999*/
37000static int rehash(Hash *pH, unsigned int new_size){
37001  struct _ht *new_ht;            /* The new hash table */
37002  HashElem *elem, *next_elem;    /* For looping over existing elements */
37003
37004#if SQLITE_MALLOC_SOFT_LIMIT>0
37005  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
37006    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
37007  }
37008  if( new_size==pH->htsize ) return 0;
37009#endif
37010
37011  /* The inability to allocates space for a larger hash table is
37012  ** a performance hit but it is not a fatal error.  So mark the
37013  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
37014  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
37015  ** only zeroes the requested number of bytes whereas this module will
37016  ** use the actual amount of space allocated for the hash table (which
37017  ** may be larger than the requested amount).
37018  */
37019  sqlite3BeginBenignMalloc();
37020  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
37021  sqlite3EndBenignMalloc();
37022
37023  if( new_ht==0 ) return 0;
37024  sqlite3_free(pH->ht);
37025  pH->ht = new_ht;
37026  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
37027  memset(new_ht, 0, new_size*sizeof(struct _ht));
37028  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
37029    unsigned int h = strHash(elem->pKey) % new_size;
37030    next_elem = elem->next;
37031    insertElement(pH, &new_ht[h], elem);
37032  }
37033  return 1;
37034}
37035
37036/* This function (for internal use only) locates an element in an
37037** hash table that matches the given key.  If no element is found,
37038** a pointer to a static null element with HashElem.data==0 is returned.
37039** If pH is not NULL, then the hash for this key is written to *pH.
37040*/
37041static HashElem *findElementWithHash(
37042  const Hash *pH,     /* The pH to be searched */
37043  const char *pKey,   /* The key we are searching for */
37044  unsigned int *pHash /* Write the hash value here */
37045){
37046  HashElem *elem;                /* Used to loop thru the element list */
37047  unsigned int count;            /* Number of elements left to test */
37048  unsigned int h;                /* The computed hash */
37049  static HashElem nullElement = { 0, 0, 0, 0 };
37050
37051  if( pH->ht ){   /*OPTIMIZATION-IF-TRUE*/
37052    struct _ht *pEntry;
37053    h = strHash(pKey) % pH->htsize;
37054    pEntry = &pH->ht[h];
37055    elem = pEntry->chain;
37056    count = pEntry->count;
37057  }else{
37058    h = 0;
37059    elem = pH->first;
37060    count = pH->count;
37061  }
37062  if( pHash ) *pHash = h;
37063  while( count ){
37064    assert( elem!=0 );
37065    if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
37066      return elem;
37067    }
37068    elem = elem->next;
37069    count--;
37070  }
37071  return &nullElement;
37072}
37073
37074/* Remove a single entry from the hash table given a pointer to that
37075** element and a hash on the element's key.
37076*/
37077static void removeElementGivenHash(
37078  Hash *pH,         /* The pH containing "elem" */
37079  HashElem* elem,   /* The element to be removed from the pH */
37080  unsigned int h    /* Hash value for the element */
37081){
37082  struct _ht *pEntry;
37083  if( elem->prev ){
37084    elem->prev->next = elem->next;
37085  }else{
37086    pH->first = elem->next;
37087  }
37088  if( elem->next ){
37089    elem->next->prev = elem->prev;
37090  }
37091  if( pH->ht ){
37092    pEntry = &pH->ht[h];
37093    if( pEntry->chain==elem ){
37094      pEntry->chain = elem->next;
37095    }
37096    assert( pEntry->count>0 );
37097    pEntry->count--;
37098  }
37099  sqlite3_free( elem );
37100  pH->count--;
37101  if( pH->count==0 ){
37102    assert( pH->first==0 );
37103    assert( pH->count==0 );
37104    sqlite3HashClear(pH);
37105  }
37106}
37107
37108/* Attempt to locate an element of the hash table pH with a key
37109** that matches pKey.  Return the data for this element if it is
37110** found, or NULL if there is no match.
37111*/
37112SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
37113  assert( pH!=0 );
37114  assert( pKey!=0 );
37115  return findElementWithHash(pH, pKey, 0)->data;
37116}
37117
37118/* Insert an element into the hash table pH.  The key is pKey
37119** and the data is "data".
37120**
37121** If no element exists with a matching key, then a new
37122** element is created and NULL is returned.
37123**
37124** If another element already exists with the same key, then the
37125** new data replaces the old data and the old data is returned.
37126** The key is not copied in this instance.  If a malloc fails, then
37127** the new data is returned and the hash table is unchanged.
37128**
37129** If the "data" parameter to this function is NULL, then the
37130** element corresponding to "key" is removed from the hash table.
37131*/
37132SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
37133  unsigned int h;       /* the hash of the key modulo hash table size */
37134  HashElem *elem;       /* Used to loop thru the element list */
37135  HashElem *new_elem;   /* New element added to the pH */
37136
37137  assert( pH!=0 );
37138  assert( pKey!=0 );
37139  elem = findElementWithHash(pH,pKey,&h);
37140  if( elem->data ){
37141    void *old_data = elem->data;
37142    if( data==0 ){
37143      removeElementGivenHash(pH,elem,h);
37144    }else{
37145      elem->data = data;
37146      elem->pKey = pKey;
37147    }
37148    return old_data;
37149  }
37150  if( data==0 ) return 0;
37151  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
37152  if( new_elem==0 ) return data;
37153  new_elem->pKey = pKey;
37154  new_elem->data = data;
37155  pH->count++;
37156  if( pH->count>=10 && pH->count > 2*pH->htsize ){
37157    if( rehash(pH, pH->count*2) ){
37158      assert( pH->htsize>0 );
37159      h = strHash(pKey) % pH->htsize;
37160    }
37161  }
37162  insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
37163  return 0;
37164}
37165
37166/************** End of hash.c ************************************************/
37167/************** Begin file opcodes.c *****************************************/
37168/* Automatically generated.  Do not edit */
37169/* See the tool/mkopcodec.tcl script for details. */
37170#if !defined(SQLITE_OMIT_EXPLAIN) \
37171 || defined(VDBE_PROFILE) \
37172 || defined(SQLITE_DEBUG)
37173#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
37174# define OpHelp(X) "\0" X
37175#else
37176# define OpHelp(X)
37177#endif
37178SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
37179 static const char *const azName[] = {
37180    /*   0 */ "Savepoint"        OpHelp(""),
37181    /*   1 */ "AutoCommit"       OpHelp(""),
37182    /*   2 */ "Transaction"      OpHelp(""),
37183    /*   3 */ "Checkpoint"       OpHelp(""),
37184    /*   4 */ "JournalMode"      OpHelp(""),
37185    /*   5 */ "Vacuum"           OpHelp(""),
37186    /*   6 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
37187    /*   7 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
37188    /*   8 */ "Init"             OpHelp("Start at P2"),
37189    /*   9 */ "Goto"             OpHelp(""),
37190    /*  10 */ "Gosub"            OpHelp(""),
37191    /*  11 */ "InitCoroutine"    OpHelp(""),
37192    /*  12 */ "Yield"            OpHelp(""),
37193    /*  13 */ "MustBeInt"        OpHelp(""),
37194    /*  14 */ "Jump"             OpHelp(""),
37195    /*  15 */ "Once"             OpHelp(""),
37196    /*  16 */ "If"               OpHelp(""),
37197    /*  17 */ "IfNot"            OpHelp(""),
37198    /*  18 */ "IsType"           OpHelp("if typeof(P1.P3) in P5 goto P2"),
37199    /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
37200    /*  20 */ "IfNullRow"        OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
37201    /*  21 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
37202    /*  22 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
37203    /*  23 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
37204    /*  24 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
37205    /*  25 */ "IfNotOpen"        OpHelp("if( !csr[P1] ) goto P2"),
37206    /*  26 */ "IfNoHope"         OpHelp("key=r[P3@P4]"),
37207    /*  27 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
37208    /*  28 */ "NotFound"         OpHelp("key=r[P3@P4]"),
37209    /*  29 */ "Found"            OpHelp("key=r[P3@P4]"),
37210    /*  30 */ "SeekRowid"        OpHelp("intkey=r[P3]"),
37211    /*  31 */ "NotExists"        OpHelp("intkey=r[P3]"),
37212    /*  32 */ "Last"             OpHelp(""),
37213    /*  33 */ "IfSizeBetween"    OpHelp(""),
37214    /*  34 */ "SorterSort"       OpHelp(""),
37215    /*  35 */ "Sort"             OpHelp(""),
37216    /*  36 */ "Rewind"           OpHelp(""),
37217    /*  37 */ "SorterNext"       OpHelp(""),
37218    /*  38 */ "Prev"             OpHelp(""),
37219    /*  39 */ "Next"             OpHelp(""),
37220    /*  40 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
37221    /*  41 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
37222    /*  42 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
37223    /*  43 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
37224    /*  44 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
37225    /*  45 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
37226    /*  46 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
37227    /*  47 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
37228    /*  48 */ "Program"          OpHelp(""),
37229    /*  49 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
37230    /*  50 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
37231    /*  51 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
37232    /*  52 */ "Ne"               OpHelp("IF r[P3]!=r[P1]"),
37233    /*  53 */ "Eq"               OpHelp("IF r[P3]==r[P1]"),
37234    /*  54 */ "Gt"               OpHelp("IF r[P3]>r[P1]"),
37235    /*  55 */ "Le"               OpHelp("IF r[P3]<=r[P1]"),
37236    /*  56 */ "Lt"               OpHelp("IF r[P3]<r[P1]"),
37237    /*  57 */ "Ge"               OpHelp("IF r[P3]>=r[P1]"),
37238    /*  58 */ "ElseEq"           OpHelp(""),
37239    /*  59 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
37240    /*  60 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
37241    /*  61 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
37242    /*  62 */ "IncrVacuum"       OpHelp(""),
37243    /*  63 */ "VNext"            OpHelp(""),
37244    /*  64 */ "Filter"           OpHelp("if key(P3@P4) not in filter(P1) goto P2"),
37245    /*  65 */ "PureFunc"         OpHelp("r[P3]=func(r[P2@NP])"),
37246    /*  66 */ "Function"         OpHelp("r[P3]=func(r[P2@NP])"),
37247    /*  67 */ "Return"           OpHelp(""),
37248    /*  68 */ "EndCoroutine"     OpHelp(""),
37249    /*  69 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
37250    /*  70 */ "Halt"             OpHelp(""),
37251    /*  71 */ "Integer"          OpHelp("r[P2]=P1"),
37252    /*  72 */ "Int64"            OpHelp("r[P2]=P4"),
37253    /*  73 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
37254    /*  74 */ "BeginSubrtn"      OpHelp("r[P2]=NULL"),
37255    /*  75 */ "Null"             OpHelp("r[P2..P3]=NULL"),
37256    /*  76 */ "SoftNull"         OpHelp("r[P1]=NULL"),
37257    /*  77 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
37258    /*  78 */ "Variable"         OpHelp("r[P2]=parameter(P1)"),
37259    /*  79 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
37260    /*  80 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
37261    /*  81 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
37262    /*  82 */ "IntCopy"          OpHelp("r[P2]=r[P1]"),
37263    /*  83 */ "FkCheck"          OpHelp(""),
37264    /*  84 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
37265    /*  85 */ "CollSeq"          OpHelp(""),
37266    /*  86 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
37267    /*  87 */ "RealAffinity"     OpHelp(""),
37268    /*  88 */ "Cast"             OpHelp("affinity(r[P1])"),
37269    /*  89 */ "Permutation"      OpHelp(""),
37270    /*  90 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
37271    /*  91 */ "IsTrue"           OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
37272    /*  92 */ "ZeroOrNull"       OpHelp("r[P2] = 0 OR NULL"),
37273    /*  93 */ "Offset"           OpHelp("r[P3] = sqlite_offset(P1)"),
37274    /*  94 */ "Column"           OpHelp("r[P3]=PX cursor P1 column P2"),
37275    /*  95 */ "TypeCheck"        OpHelp("typecheck(r[P1@P2])"),
37276    /*  96 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
37277    /*  97 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
37278    /*  98 */ "Count"            OpHelp("r[P2]=count()"),
37279    /*  99 */ "ReadCookie"       OpHelp(""),
37280    /* 100 */ "SetCookie"        OpHelp(""),
37281    /* 101 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
37282    /* 102 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
37283    /* 103 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
37284    /* 104 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
37285    /* 105 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
37286    /* 106 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
37287    /* 107 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
37288    /* 108 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
37289    /* 109 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
37290    /* 110 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
37291    /* 111 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
37292    /* 112 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
37293    /* 113 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
37294    /* 114 */ "BitNot"           OpHelp("r[P2]= ~r[P1]"),
37295    /* 115 */ "OpenDup"          OpHelp(""),
37296    /* 116 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
37297    /* 117 */ "String8"          OpHelp("r[P2]='P4'"),
37298    /* 118 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
37299    /* 119 */ "SorterOpen"       OpHelp(""),
37300    /* 120 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
37301    /* 121 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
37302    /* 122 */ "Close"            OpHelp(""),
37303    /* 123 */ "ColumnsUsed"      OpHelp(""),
37304    /* 124 */ "SeekScan"         OpHelp("Scan-ahead up to P1 rows"),
37305    /* 125 */ "SeekHit"          OpHelp("set P2<=seekHit<=P3"),
37306    /* 126 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
37307    /* 127 */ "NewRowid"         OpHelp("r[P2]=rowid"),
37308    /* 128 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
37309    /* 129 */ "RowCell"          OpHelp(""),
37310    /* 130 */ "Delete"           OpHelp(""),
37311    /* 131 */ "ResetCount"       OpHelp(""),
37312    /* 132 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
37313    /* 133 */ "SorterData"       OpHelp("r[P2]=data"),
37314    /* 134 */ "RowData"          OpHelp("r[P2]=data"),
37315    /* 135 */ "Rowid"            OpHelp("r[P2]=PX rowid of P1"),
37316    /* 136 */ "NullRow"          OpHelp(""),
37317    /* 137 */ "SeekEnd"          OpHelp(""),
37318    /* 138 */ "IdxInsert"        OpHelp("key=r[P2]"),
37319    /* 139 */ "SorterInsert"     OpHelp("key=r[P2]"),
37320    /* 140 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
37321    /* 141 */ "DeferredSeek"     OpHelp("Move P3 to P1.rowid if needed"),
37322    /* 142 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
37323    /* 143 */ "FinishSeek"       OpHelp(""),
37324    /* 144 */ "Destroy"          OpHelp(""),
37325    /* 145 */ "Clear"            OpHelp(""),
37326    /* 146 */ "ResetSorter"      OpHelp(""),
37327    /* 147 */ "CreateBtree"      OpHelp("r[P2]=root iDb=P1 flags=P3"),
37328    /* 148 */ "SqlExec"          OpHelp(""),
37329    /* 149 */ "ParseSchema"      OpHelp(""),
37330    /* 150 */ "LoadAnalysis"     OpHelp(""),
37331    /* 151 */ "DropTable"        OpHelp(""),
37332    /* 152 */ "DropIndex"        OpHelp(""),
37333    /* 153 */ "Real"             OpHelp("r[P2]=P4"),
37334    /* 154 */ "DropTrigger"      OpHelp(""),
37335    /* 155 */ "IntegrityCk"      OpHelp(""),
37336    /* 156 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
37337    /* 157 */ "Param"            OpHelp(""),
37338    /* 158 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
37339    /* 159 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
37340    /* 160 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
37341    /* 161 */ "AggInverse"       OpHelp("accum=r[P3] inverse(r[P2@P5])"),
37342    /* 162 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
37343    /* 163 */ "AggStep1"         OpHelp("accum=r[P3] step(r[P2@P5])"),
37344    /* 164 */ "AggValue"         OpHelp("r[P3]=value N=P2"),
37345    /* 165 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
37346    /* 166 */ "Expire"           OpHelp(""),
37347    /* 167 */ "CursorLock"       OpHelp(""),
37348    /* 168 */ "CursorUnlock"     OpHelp(""),
37349    /* 169 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
37350    /* 170 */ "VBegin"           OpHelp(""),
37351    /* 171 */ "VCreate"          OpHelp(""),
37352    /* 172 */ "VDestroy"         OpHelp(""),
37353    /* 173 */ "VOpen"            OpHelp(""),
37354    /* 174 */ "VCheck"           OpHelp(""),
37355    /* 175 */ "VInitIn"          OpHelp("r[P2]=ValueList(P1,P3)"),
37356    /* 176 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
37357    /* 177 */ "VRename"          OpHelp(""),
37358    /* 178 */ "Pagecount"        OpHelp(""),
37359    /* 179 */ "MaxPgcnt"         OpHelp(""),
37360    /* 180 */ "ClrSubtype"       OpHelp("r[P1].subtype = 0"),
37361    /* 181 */ "GetSubtype"       OpHelp("r[P2] = r[P1].subtype"),
37362    /* 182 */ "SetSubtype"       OpHelp("r[P2].subtype = r[P1]"),
37363    /* 183 */ "FilterAdd"        OpHelp("filter(P1) += key(P3@P4)"),
37364    /* 184 */ "Trace"            OpHelp(""),
37365    /* 185 */ "CursorHint"       OpHelp(""),
37366    /* 186 */ "ReleaseReg"       OpHelp("release r[P1@P2] mask P3"),
37367    /* 187 */ "Noop"             OpHelp(""),
37368    /* 188 */ "Explain"          OpHelp(""),
37369    /* 189 */ "Abortable"        OpHelp(""),
37370  };
37371  return azName[i];
37372}
37373#endif
37374
37375/************** End of opcodes.c *********************************************/
37376/************** Begin file os_kv.c *******************************************/
37377/*
37378** 2022-09-06
37379**
37380** The author disclaims copyright to this source code.  In place of
37381** a legal notice, here is a blessing:
37382**
37383**    May you do good and not evil.
37384**    May you find forgiveness for yourself and forgive others.
37385**    May you share freely, never taking more than you give.
37386**
37387******************************************************************************
37388**
37389** This file contains an experimental VFS layer that operates on a
37390** Key/Value storage engine where both keys and values must be pure
37391** text.
37392*/
37393/* #include <sqliteInt.h> */
37394#if SQLITE_OS_KV || (SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL))
37395
37396/*****************************************************************************
37397** Debugging logic
37398*/
37399
37400/* SQLITE_KV_TRACE() is used for tracing calls to kvstorage routines. */
37401#if 0
37402#define SQLITE_KV_TRACE(X)  printf X
37403#else
37404#define SQLITE_KV_TRACE(X)
37405#endif
37406
37407/* SQLITE_KV_LOG() is used for tracing calls to the VFS interface */
37408#if 0
37409#define SQLITE_KV_LOG(X)  printf X
37410#else
37411#define SQLITE_KV_LOG(X)
37412#endif
37413
37414
37415/*
37416** Forward declaration of objects used by this VFS implementation
37417*/
37418typedef struct KVVfsFile KVVfsFile;
37419
37420/* A single open file.  There are only two files represented by this
37421** VFS - the database and the rollback journal.
37422*/
37423struct KVVfsFile {
37424  sqlite3_file base;              /* IO methods */
37425  const char *zClass;             /* Storage class */
37426  int isJournal;                  /* True if this is a journal file */
37427  unsigned int nJrnl;             /* Space allocated for aJrnl[] */
37428  char *aJrnl;                    /* Journal content */
37429  int szPage;                     /* Last known page size */
37430  sqlite3_int64 szDb;             /* Database file size.  -1 means unknown */
37431  char *aData;                    /* Buffer to hold page data */
37432};
37433#define SQLITE_KVOS_SZ 133073
37434
37435/*
37436** Methods for KVVfsFile
37437*/
37438static int kvvfsClose(sqlite3_file*);
37439static int kvvfsReadDb(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
37440static int kvvfsReadJrnl(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
37441static int kvvfsWriteDb(sqlite3_file*,const void*,int iAmt, sqlite3_int64);
37442static int kvvfsWriteJrnl(sqlite3_file*,const void*,int iAmt, sqlite3_int64);
37443static int kvvfsTruncateDb(sqlite3_file*, sqlite3_int64 size);
37444static int kvvfsTruncateJrnl(sqlite3_file*, sqlite3_int64 size);
37445static int kvvfsSyncDb(sqlite3_file*, int flags);
37446static int kvvfsSyncJrnl(sqlite3_file*, int flags);
37447static int kvvfsFileSizeDb(sqlite3_file*, sqlite3_int64 *pSize);
37448static int kvvfsFileSizeJrnl(sqlite3_file*, sqlite3_int64 *pSize);
37449static int kvvfsLock(sqlite3_file*, int);
37450static int kvvfsUnlock(sqlite3_file*, int);
37451static int kvvfsCheckReservedLock(sqlite3_file*, int *pResOut);
37452static int kvvfsFileControlDb(sqlite3_file*, int op, void *pArg);
37453static int kvvfsFileControlJrnl(sqlite3_file*, int op, void *pArg);
37454static int kvvfsSectorSize(sqlite3_file*);
37455static int kvvfsDeviceCharacteristics(sqlite3_file*);
37456
37457/*
37458** Methods for sqlite3_vfs
37459*/
37460static int kvvfsOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
37461static int kvvfsDelete(sqlite3_vfs*, const char *zName, int syncDir);
37462static int kvvfsAccess(sqlite3_vfs*, const char *zName, int flags, int *);
37463static int kvvfsFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
37464static void *kvvfsDlOpen(sqlite3_vfs*, const char *zFilename);
37465static int kvvfsRandomness(sqlite3_vfs*, int nByte, char *zOut);
37466static int kvvfsSleep(sqlite3_vfs*, int microseconds);
37467static int kvvfsCurrentTime(sqlite3_vfs*, double*);
37468static int kvvfsCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
37469
37470static sqlite3_vfs sqlite3OsKvvfsObject = {
37471  1,                              /* iVersion */
37472  sizeof(KVVfsFile),              /* szOsFile */
37473  1024,                           /* mxPathname */
37474  0,                              /* pNext */
37475  "kvvfs",                        /* zName */
37476  0,                              /* pAppData */
37477  kvvfsOpen,                      /* xOpen */
37478  kvvfsDelete,                    /* xDelete */
37479  kvvfsAccess,                    /* xAccess */
37480  kvvfsFullPathname,              /* xFullPathname */
37481  kvvfsDlOpen,                    /* xDlOpen */
37482  0,                              /* xDlError */
37483  0,                              /* xDlSym */
37484  0,                              /* xDlClose */
37485  kvvfsRandomness,                /* xRandomness */
37486  kvvfsSleep,                     /* xSleep */
37487  kvvfsCurrentTime,               /* xCurrentTime */
37488  0,                              /* xGetLastError */
37489  kvvfsCurrentTimeInt64           /* xCurrentTimeInt64 */
37490};
37491
37492/* Methods for sqlite3_file objects referencing a database file
37493*/
37494static sqlite3_io_methods kvvfs_db_io_methods = {
37495  1,                              /* iVersion */
37496  kvvfsClose,                     /* xClose */
37497  kvvfsReadDb,                    /* xRead */
37498  kvvfsWriteDb,                   /* xWrite */
37499  kvvfsTruncateDb,                /* xTruncate */
37500  kvvfsSyncDb,                    /* xSync */
37501  kvvfsFileSizeDb,                /* xFileSize */
37502  kvvfsLock,                      /* xLock */
37503  kvvfsUnlock,                    /* xUnlock */
37504  kvvfsCheckReservedLock,         /* xCheckReservedLock */
37505  kvvfsFileControlDb,             /* xFileControl */
37506  kvvfsSectorSize,                /* xSectorSize */
37507  kvvfsDeviceCharacteristics,     /* xDeviceCharacteristics */
37508  0,                              /* xShmMap */
37509  0,                              /* xShmLock */
37510  0,                              /* xShmBarrier */
37511  0,                              /* xShmUnmap */
37512  0,                              /* xFetch */
37513  0                               /* xUnfetch */
37514};
37515
37516/* Methods for sqlite3_file objects referencing a rollback journal
37517*/
37518static sqlite3_io_methods kvvfs_jrnl_io_methods = {
37519  1,                              /* iVersion */
37520  kvvfsClose,                     /* xClose */
37521  kvvfsReadJrnl,                  /* xRead */
37522  kvvfsWriteJrnl,                 /* xWrite */
37523  kvvfsTruncateJrnl,              /* xTruncate */
37524  kvvfsSyncJrnl,                  /* xSync */
37525  kvvfsFileSizeJrnl,              /* xFileSize */
37526  kvvfsLock,                      /* xLock */
37527  kvvfsUnlock,                    /* xUnlock */
37528  kvvfsCheckReservedLock,         /* xCheckReservedLock */
37529  kvvfsFileControlJrnl,           /* xFileControl */
37530  kvvfsSectorSize,                /* xSectorSize */
37531  kvvfsDeviceCharacteristics,     /* xDeviceCharacteristics */
37532  0,                              /* xShmMap */
37533  0,                              /* xShmLock */
37534  0,                              /* xShmBarrier */
37535  0,                              /* xShmUnmap */
37536  0,                              /* xFetch */
37537  0                               /* xUnfetch */
37538};
37539
37540/****** Storage subsystem **************************************************/
37541#include <sys/types.h>
37542#include <sys/stat.h>
37543#include <unistd.h>
37544
37545/* Forward declarations for the low-level storage engine
37546*/
37547static int kvstorageWrite(const char*, const char *zKey, const char *zData);
37548static int kvstorageDelete(const char*, const char *zKey);
37549static int kvstorageRead(const char*, const char *zKey, char *zBuf, int nBuf);
37550#define KVSTORAGE_KEY_SZ  32
37551
37552/* Expand the key name with an appropriate prefix and put the result
37553** zKeyOut[].  The zKeyOut[] buffer is assumed to hold at least
37554** KVSTORAGE_KEY_SZ bytes.
37555*/
37556static void kvstorageMakeKey(
37557  const char *zClass,
37558  const char *zKeyIn,
37559  char *zKeyOut
37560){
37561  sqlite3_snprintf(KVSTORAGE_KEY_SZ, zKeyOut, "kvvfs-%s-%s", zClass, zKeyIn);
37562}
37563
37564/* Write content into a key.  zClass is the particular namespace of the
37565** underlying key/value store to use - either "local" or "session".
37566**
37567** Both zKey and zData are zero-terminated pure text strings.
37568**
37569** Return the number of errors.
37570*/
37571static int kvstorageWrite(
37572  const char *zClass,
37573  const char *zKey,
37574  const char *zData
37575){
37576  FILE *fd;
37577  char zXKey[KVSTORAGE_KEY_SZ];
37578  kvstorageMakeKey(zClass, zKey, zXKey);
37579  fd = fopen(zXKey, "wb");
37580  if( fd ){
37581    SQLITE_KV_TRACE(("KVVFS-WRITE  %-15s (%d) %.50s%s\n", zXKey,
37582                 (int)strlen(zData), zData,
37583                 strlen(zData)>50 ? "..." : ""));
37584    fputs(zData, fd);
37585    fclose(fd);
37586    return 0;
37587  }else{
37588    return 1;
37589  }
37590}
37591
37592/* Delete a key (with its corresponding data) from the key/value
37593** namespace given by zClass.  If the key does not previously exist,
37594** this routine is a no-op.
37595*/
37596static int kvstorageDelete(const char *zClass, const char *zKey){
37597  char zXKey[KVSTORAGE_KEY_SZ];
37598  kvstorageMakeKey(zClass, zKey, zXKey);
37599  unlink(zXKey);
37600  SQLITE_KV_TRACE(("KVVFS-DELETE %-15s\n", zXKey));
37601  return 0;
37602}
37603
37604/* Read the value associated with a zKey from the key/value namespace given
37605** by zClass and put the text data associated with that key in the first
37606** nBuf bytes of zBuf[].  The value might be truncated if zBuf is not large
37607** enough to hold it all.  The value put into zBuf must always be zero
37608** terminated, even if it gets truncated because nBuf is not large enough.
37609**
37610** Return the total number of bytes in the data, without truncation, and
37611** not counting the final zero terminator.   Return -1 if the key does
37612** not exist.
37613**
37614** If nBuf<=0 then this routine simply returns the size of the data without
37615** actually reading it.
37616*/
37617static int kvstorageRead(
37618  const char *zClass,
37619  const char *zKey,
37620  char *zBuf,
37621  int nBuf
37622){
37623  FILE *fd;
37624  struct stat buf;
37625  char zXKey[KVSTORAGE_KEY_SZ];
37626  kvstorageMakeKey(zClass, zKey, zXKey);
37627  if( access(zXKey, R_OK)!=0
37628   || stat(zXKey, &buf)!=0
37629   || !S_ISREG(buf.st_mode)
37630  ){
37631    SQLITE_KV_TRACE(("KVVFS-READ   %-15s (-1)\n", zXKey));
37632    return -1;
37633  }
37634  if( nBuf<=0 ){
37635    return (int)buf.st_size;
37636  }else if( nBuf==1 ){
37637    zBuf[0] = 0;
37638    SQLITE_KV_TRACE(("KVVFS-READ   %-15s (%d)\n", zXKey,
37639                 (int)buf.st_size));
37640    return (int)buf.st_size;
37641  }
37642  if( nBuf > buf.st_size + 1 ){
37643    nBuf = buf.st_size + 1;
37644  }
37645  fd = fopen(zXKey, "rb");
37646  if( fd==0 ){
37647    SQLITE_KV_TRACE(("KVVFS-READ   %-15s (-1)\n", zXKey));
37648    return -1;
37649  }else{
37650    sqlite3_int64 n = fread(zBuf, 1, nBuf-1, fd);
37651    fclose(fd);
37652    zBuf[n] = 0;
37653    SQLITE_KV_TRACE(("KVVFS-READ   %-15s (%lld) %.50s%s\n", zXKey,
37654                 n, zBuf, n>50 ? "..." : ""));
37655    return (int)n;
37656  }
37657}
37658
37659/*
37660** An internal level of indirection which enables us to replace the
37661** kvvfs i/o methods with JavaScript implementations in WASM builds.
37662** Maintenance reminder: if this struct changes in any way, the JSON
37663** rendering of its structure must be updated in
37664** sqlite3_wasm_enum_json(). There are no binary compatibility
37665** concerns, so it does not need an iVersion member. This file is
37666** necessarily always compiled together with sqlite3_wasm_enum_json(),
37667** and JS code dynamically creates the mapping of members based on
37668** that JSON description.
37669*/
37670typedef struct sqlite3_kvvfs_methods sqlite3_kvvfs_methods;
37671struct sqlite3_kvvfs_methods {
37672  int (*xRead)(const char *zClass, const char *zKey, char *zBuf, int nBuf);
37673  int (*xWrite)(const char *zClass, const char *zKey, const char *zData);
37674  int (*xDelete)(const char *zClass, const char *zKey);
37675  const int nKeySize;
37676};
37677
37678/*
37679** This object holds the kvvfs I/O methods which may be swapped out
37680** for JavaScript-side implementations in WASM builds. In such builds
37681** it cannot be const, but in native builds it should be so that
37682** the compiler can hopefully optimize this level of indirection out.
37683** That said, kvvfs is intended primarily for use in WASM builds.
37684**
37685** Note that this is not explicitly flagged as static because the
37686** amalgamation build will tag it with SQLITE_PRIVATE.
37687*/
37688#ifndef SQLITE_WASM
37689const
37690#endif
37691SQLITE_PRIVATE sqlite3_kvvfs_methods sqlite3KvvfsMethods = {
37692kvstorageRead,
37693kvstorageWrite,
37694kvstorageDelete,
37695KVSTORAGE_KEY_SZ
37696};
37697
37698/****** Utility subroutines ************************************************/
37699
37700/*
37701** Encode binary into the text encoded used to persist on disk.
37702** The output text is stored in aOut[], which must be at least
37703** nData+1 bytes in length.
37704**
37705** Return the actual length of the encoded text, not counting the
37706** zero terminator at the end.
37707**
37708** Encoding format
37709** ---------------
37710**
37711**   *  Non-zero bytes are encoded as upper-case hexadecimal
37712**
37713**   *  A sequence of one or more zero-bytes that are not at the
37714**      beginning of the buffer are encoded as a little-endian
37715**      base-26 number using a..z.  "a" means 0.  "b" means 1,
37716**      "z" means 25.  "ab" means 26.  "ac" means 52.  And so forth.
37717**
37718**   *  Because there is no overlap between the encoding characters
37719**      of hexadecimal and base-26 numbers, it is always clear where
37720**      one stops and the next begins.
37721*/
37722static int kvvfsEncode(const char *aData, int nData, char *aOut){
37723  int i, j;
37724  const unsigned char *a = (const unsigned char*)aData;
37725  for(i=j=0; i<nData; i++){
37726    unsigned char c = a[i];
37727    if( c!=0 ){
37728      aOut[j++] = "0123456789ABCDEF"[c>>4];
37729      aOut[j++] = "0123456789ABCDEF"[c&0xf];
37730    }else{
37731      /* A sequence of 1 or more zeros is stored as a little-endian
37732      ** base-26 number using a..z as the digits. So one zero is "b".
37733      ** Two zeros is "c". 25 zeros is "z", 26 zeros is "ab", 27 is "bb",
37734      ** and so forth.
37735      */
37736      int k;
37737      for(k=1; i+k<nData && a[i+k]==0; k++){}
37738      i += k-1;
37739      while( k>0 ){
37740        aOut[j++] = 'a'+(k%26);
37741        k /= 26;
37742      }
37743    }
37744  }
37745  aOut[j] = 0;
37746  return j;
37747}
37748
37749static const signed char kvvfsHexValue[256] = {
37750  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37751  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37752  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37753   0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,
37754  -1, 10, 11, 12, 13, 14, 15, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37755  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37756  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37757  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37758
37759  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37760  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37761  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37762  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37763  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37764  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37765  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
37766  -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1
37767};
37768
37769/*
37770** Decode the text encoding back to binary.  The binary content is
37771** written into pOut, which must be at least nOut bytes in length.
37772**
37773** The return value is the number of bytes actually written into aOut[].
37774*/
37775static int kvvfsDecode(const char *a, char *aOut, int nOut){
37776  int i, j;
37777  int c;
37778  const unsigned char *aIn = (const unsigned char*)a;
37779  i = 0;
37780  j = 0;
37781  while( 1 ){
37782    c = kvvfsHexValue[aIn[i]];
37783    if( c<0 ){
37784      int n = 0;
37785      int mult = 1;
37786      c = aIn[i];
37787      if( c==0 ) break;
37788      while( c>='a' && c<='z' ){
37789        n += (c - 'a')*mult;
37790        mult *= 26;
37791        c = aIn[++i];
37792      }
37793      if( j+n>nOut ) return -1;
37794      memset(&aOut[j], 0, n);
37795      j += n;
37796      if( c==0 || mult==1 ) break; /* progress stalled if mult==1 */
37797    }else{
37798      aOut[j] = c<<4;
37799      c = kvvfsHexValue[aIn[++i]];
37800      if( c<0 ) break;
37801      aOut[j++] += c;
37802      i++;
37803    }
37804  }
37805  return j;
37806}
37807
37808/*
37809** Decode a complete journal file.  Allocate space in pFile->aJrnl
37810** and store the decoding there.  Or leave pFile->aJrnl set to NULL
37811** if an error is encountered.
37812**
37813** The first few characters of the text encoding will be a little-endian
37814** base-26 number (digits a..z) that is the total number of bytes
37815** in the decoded journal file image.  This base-26 number is followed
37816** by a single space, then the encoding of the journal.  The space
37817** separator is required to act as a terminator for the base-26 number.
37818*/
37819static void kvvfsDecodeJournal(
37820  KVVfsFile *pFile,      /* Store decoding in pFile->aJrnl */
37821  const char *zTxt,      /* Text encoding.  Zero-terminated */
37822  int nTxt               /* Bytes in zTxt, excluding zero terminator */
37823){
37824  unsigned int n = 0;
37825  int c, i, mult;
37826  i = 0;
37827  mult = 1;
37828  while( (c = zTxt[i++])>='a' && c<='z' ){
37829    n += (zTxt[i] - 'a')*mult;
37830    mult *= 26;
37831  }
37832  sqlite3_free(pFile->aJrnl);
37833  pFile->aJrnl = sqlite3_malloc64( n );
37834  if( pFile->aJrnl==0 ){
37835    pFile->nJrnl = 0;
37836    return;
37837  }
37838  pFile->nJrnl = n;
37839  n = kvvfsDecode(zTxt+i, pFile->aJrnl, pFile->nJrnl);
37840  if( n<pFile->nJrnl ){
37841    sqlite3_free(pFile->aJrnl);
37842    pFile->aJrnl = 0;
37843    pFile->nJrnl = 0;
37844  }
37845}
37846
37847/*
37848** Read or write the "sz" element, containing the database file size.
37849*/
37850static sqlite3_int64 kvvfsReadFileSize(KVVfsFile *pFile){
37851  char zData[50];
37852  zData[0] = 0;
37853  sqlite3KvvfsMethods.xRead(pFile->zClass, "sz", zData, sizeof(zData)-1);
37854  return strtoll(zData, 0, 0);
37855}
37856static int kvvfsWriteFileSize(KVVfsFile *pFile, sqlite3_int64 sz){
37857  char zData[50];
37858  sqlite3_snprintf(sizeof(zData), zData, "%lld", sz);
37859  return sqlite3KvvfsMethods.xWrite(pFile->zClass, "sz", zData);
37860}
37861
37862/****** sqlite3_io_methods methods ******************************************/
37863
37864/*
37865** Close an kvvfs-file.
37866*/
37867static int kvvfsClose(sqlite3_file *pProtoFile){
37868  KVVfsFile *pFile = (KVVfsFile *)pProtoFile;
37869
37870  SQLITE_KV_LOG(("xClose %s %s\n", pFile->zClass,
37871             pFile->isJournal ? "journal" : "db"));
37872  sqlite3_free(pFile->aJrnl);
37873  sqlite3_free(pFile->aData);
37874  return SQLITE_OK;
37875}
37876
37877/*
37878** Read from the -journal file.
37879*/
37880static int kvvfsReadJrnl(
37881  sqlite3_file *pProtoFile,
37882  void *zBuf,
37883  int iAmt,
37884  sqlite_int64 iOfst
37885){
37886  KVVfsFile *pFile = (KVVfsFile*)pProtoFile;
37887  assert( pFile->isJournal );
37888  SQLITE_KV_LOG(("xRead('%s-journal',%d,%lld)\n", pFile->zClass, iAmt, iOfst));
37889  if( pFile->aJrnl==0 ){
37890    int szTxt = kvstorageRead(pFile->zClass, "jrnl", 0, 0);
37891    char *aTxt;
37892    if( szTxt<=4 ){
37893      return SQLITE_IOERR;
37894    }
37895    aTxt = sqlite3_malloc64( szTxt+1 );
37896    if( aTxt==0 ) return SQLITE_NOMEM;
37897    kvstorageRead(pFile->zClass, "jrnl", aTxt, szTxt+1);
37898    kvvfsDecodeJournal(pFile, aTxt, szTxt);
37899    sqlite3_free(aTxt);
37900    if( pFile->aJrnl==0 ) return SQLITE_IOERR;
37901  }
37902  if( iOfst+iAmt>pFile->nJrnl ){
37903    return SQLITE_IOERR_SHORT_READ;
37904  }
37905  memcpy(zBuf, pFile->aJrnl+iOfst, iAmt);
37906  return SQLITE_OK;
37907}
37908
37909/*
37910** Read from the database file.
37911*/
37912static int kvvfsReadDb(
37913  sqlite3_file *pProtoFile,
37914  void *zBuf,
37915  int iAmt,
37916  sqlite_int64 iOfst
37917){
37918  KVVfsFile *pFile = (KVVfsFile*)pProtoFile;
37919  unsigned int pgno;
37920  int got, n;
37921  char zKey[30];
37922  char *aData = pFile->aData;
37923  assert( iOfst>=0 );
37924  assert( iAmt>=0 );
37925  SQLITE_KV_LOG(("xRead('%s-db',%d,%lld)\n", pFile->zClass, iAmt, iOfst));
37926  if( iOfst+iAmt>=512 ){
37927    if( (iOfst % iAmt)!=0 ){
37928      return SQLITE_IOERR_READ;
37929    }
37930    if( (iAmt & (iAmt-1))!=0 || iAmt<512 || iAmt>65536 ){
37931      return SQLITE_IOERR_READ;
37932    }
37933    pFile->szPage = iAmt;
37934    pgno = 1 + iOfst/iAmt;
37935  }else{
37936    pgno = 1;
37937  }
37938  sqlite3_snprintf(sizeof(zKey), zKey, "%u", pgno);
37939  got = sqlite3KvvfsMethods.xRead(pFile->zClass, zKey,
37940                                  aData, SQLITE_KVOS_SZ-1);
37941  if( got<0 ){
37942    n = 0;
37943  }else{
37944    aData[got] = 0;
37945    if( iOfst+iAmt<512 ){
37946      int k = iOfst+iAmt;
37947      aData[k*2] = 0;
37948      n = kvvfsDecode(aData, &aData[2000], SQLITE_KVOS_SZ-2000);
37949      if( n>=iOfst+iAmt ){
37950        memcpy(zBuf, &aData[2000+iOfst], iAmt);
37951        n = iAmt;
37952      }else{
37953        n = 0;
37954      }
37955    }else{
37956      n = kvvfsDecode(aData, zBuf, iAmt);
37957    }
37958  }
37959  if( n<iAmt ){
37960    memset(zBuf+n, 0, iAmt-n);
37961    return SQLITE_IOERR_SHORT_READ;
37962  }
37963  return SQLITE_OK;
37964}
37965
37966
37967/*
37968** Write into the -journal file.
37969*/
37970static int kvvfsWriteJrnl(
37971  sqlite3_file *pProtoFile,
37972  const void *zBuf,
37973  int iAmt,
37974  sqlite_int64 iOfst
37975){
37976  KVVfsFile *pFile = (KVVfsFile*)pProtoFile;
37977  sqlite3_int64 iEnd = iOfst+iAmt;
37978  SQLITE_KV_LOG(("xWrite('%s-journal',%d,%lld)\n", pFile->zClass, iAmt, iOfst));
37979  if( iEnd>=0x10000000 ) return SQLITE_FULL;
37980  if( pFile->aJrnl==0 || pFile->nJrnl<iEnd ){
37981    char *aNew = sqlite3_realloc(pFile->aJrnl, iEnd);
37982    if( aNew==0 ){
37983      return SQLITE_IOERR_NOMEM;
37984    }
37985    pFile->aJrnl = aNew;
37986    if( pFile->nJrnl<iOfst ){
37987      memset(pFile->aJrnl+pFile->nJrnl, 0, iOfst-pFile->nJrnl);
37988    }
37989    pFile->nJrnl = iEnd;
37990  }
37991  memcpy(pFile->aJrnl+iOfst, zBuf, iAmt);
37992  return SQLITE_OK;
37993}
37994
37995/*
37996** Write into the database file.
37997*/
37998static int kvvfsWriteDb(
37999  sqlite3_file *pProtoFile,
38000  const void *zBuf,
38001  int iAmt,
38002  sqlite_int64 iOfst
38003){
38004  KVVfsFile *pFile = (KVVfsFile*)pProtoFile;
38005  unsigned int pgno;
38006  char zKey[30];
38007  char *aData = pFile->aData;
38008  SQLITE_KV_LOG(("xWrite('%s-db',%d,%lld)\n", pFile->zClass, iAmt, iOfst));
38009  assert( iAmt>=512 && iAmt<=65536 );
38010  assert( (iAmt & (iAmt-1))==0 );
38011  assert( pFile->szPage<0 || pFile->szPage==iAmt );
38012  pFile->szPage = iAmt;
38013  pgno = 1 + iOfst/iAmt;
38014  sqlite3_snprintf(sizeof(zKey), zKey, "%u", pgno);
38015  kvvfsEncode(zBuf, iAmt, aData);
38016  if( sqlite3KvvfsMethods.xWrite(pFile->zClass, zKey, aData) ){
38017    return SQLITE_IOERR;
38018  }
38019  if( iOfst+iAmt > pFile->szDb ){
38020    pFile->szDb = iOfst + iAmt;
38021  }
38022  return SQLITE_OK;
38023}
38024
38025/*
38026** Truncate an kvvfs-file.
38027*/
38028static int kvvfsTruncateJrnl(sqlite3_file *pProtoFile, sqlite_int64 size){
38029  KVVfsFile *pFile = (KVVfsFile *)pProtoFile;
38030  SQLITE_KV_LOG(("xTruncate('%s-journal',%lld)\n", pFile->zClass, size));
38031  assert( size==0 );
38032  sqlite3KvvfsMethods.xDelete(pFile->zClass, "jrnl");
38033  sqlite3_free(pFile->aJrnl);
38034  pFile->aJrnl = 0;
38035  pFile->nJrnl = 0;
38036  return SQLITE_OK;
38037}
38038static int kvvfsTruncateDb(sqlite3_file *pProtoFile, sqlite_int64 size){
38039  KVVfsFile *pFile = (KVVfsFile *)pProtoFile;
38040  if( pFile->szDb>size
38041   && pFile->szPage>0
38042   && (size % pFile->szPage)==0
38043  ){
38044    char zKey[50];
38045    unsigned int pgno, pgnoMax;
38046    SQLITE_KV_LOG(("xTruncate('%s-db',%lld)\n", pFile->zClass, size));
38047    pgno = 1 + size/pFile->szPage;
38048    pgnoMax = 2 + pFile->szDb/pFile->szPage;
38049    while( pgno<=pgnoMax ){
38050      sqlite3_snprintf(sizeof(zKey), zKey, "%u", pgno);
38051      sqlite3KvvfsMethods.xDelete(pFile->zClass, zKey);
38052      pgno++;
38053    }
38054    pFile->szDb = size;
38055    return kvvfsWriteFileSize(pFile, size) ? SQLITE_IOERR : SQLITE_OK;
38056  }
38057  return SQLITE_IOERR;
38058}
38059
38060/*
38061** Sync an kvvfs-file.
38062*/
38063static int kvvfsSyncJrnl(sqlite3_file *pProtoFile, int flags){
38064  int i, n;
38065  KVVfsFile *pFile = (KVVfsFile *)pProtoFile;
38066  char *zOut;
38067  SQLITE_KV_LOG(("xSync('%s-journal')\n", pFile->zClass));
38068  if( pFile->nJrnl<=0 ){
38069    return kvvfsTruncateJrnl(pProtoFile, 0);
38070  }
38071  zOut = sqlite3_malloc64( pFile->nJrnl*2 + 50 );
38072  if( zOut==0 ){
38073    return SQLITE_IOERR_NOMEM;
38074  }
38075  n = pFile->nJrnl;
38076  i = 0;
38077  do{
38078    zOut[i++] = 'a' + (n%26);
38079    n /= 26;
38080  }while( n>0 );
38081  zOut[i++] = ' ';
38082  kvvfsEncode(pFile->aJrnl, pFile->nJrnl, &zOut[i]);
38083  i = sqlite3KvvfsMethods.xWrite(pFile->zClass, "jrnl", zOut);
38084  sqlite3_free(zOut);
38085  return i ? SQLITE_IOERR : SQLITE_OK;
38086}
38087static int kvvfsSyncDb(sqlite3_file *pProtoFile, int flags){
38088  return SQLITE_OK;
38089}
38090
38091/*
38092** Return the current file-size of an kvvfs-file.
38093*/
38094static int kvvfsFileSizeJrnl(sqlite3_file *pProtoFile, sqlite_int64 *pSize){
38095  KVVfsFile *pFile = (KVVfsFile *)pProtoFile;
38096  SQLITE_KV_LOG(("xFileSize('%s-journal')\n", pFile->zClass));
38097  *pSize = pFile->nJrnl;
38098  return SQLITE_OK;
38099}
38100static int kvvfsFileSizeDb(sqlite3_file *pProtoFile, sqlite_int64 *pSize){
38101  KVVfsFile *pFile = (KVVfsFile *)pProtoFile;
38102  SQLITE_KV_LOG(("xFileSize('%s-db')\n", pFile->zClass));
38103  if( pFile->szDb>=0 ){
38104    *pSize = pFile->szDb;
38105  }else{
38106    *pSize = kvvfsReadFileSize(pFile);
38107  }
38108  return SQLITE_OK;
38109}
38110
38111/*
38112** Lock an kvvfs-file.
38113*/
38114static int kvvfsLock(sqlite3_file *pProtoFile, int eLock){
38115  KVVfsFile *pFile = (KVVfsFile *)pProtoFile;
38116  assert( !pFile->isJournal );
38117  SQLITE_KV_LOG(("xLock(%s,%d)\n", pFile->zClass, eLock));
38118
38119  if( eLock!=SQLITE_LOCK_NONE ){
38120    pFile->szDb = kvvfsReadFileSize(pFile);
38121  }
38122  return SQLITE_OK;
38123}
38124
38125/*
38126** Unlock an kvvfs-file.
38127*/
38128static int kvvfsUnlock(sqlite3_file *pProtoFile, int eLock){
38129  KVVfsFile *pFile = (KVVfsFile *)pProtoFile;
38130  assert( !pFile->isJournal );
38131  SQLITE_KV_LOG(("xUnlock(%s,%d)\n", pFile->zClass, eLock));
38132  if( eLock==SQLITE_LOCK_NONE ){
38133    pFile->szDb = -1;
38134  }
38135  return SQLITE_OK;
38136}
38137
38138/*
38139** Check if another file-handle holds a RESERVED lock on an kvvfs-file.
38140*/
38141static int kvvfsCheckReservedLock(sqlite3_file *pProtoFile, int *pResOut){
38142  SQLITE_KV_LOG(("xCheckReservedLock\n"));
38143  *pResOut = 0;
38144  return SQLITE_OK;
38145}
38146
38147/*
38148** File control method. For custom operations on an kvvfs-file.
38149*/
38150static int kvvfsFileControlJrnl(sqlite3_file *pProtoFile, int op, void *pArg){
38151  SQLITE_KV_LOG(("xFileControl(%d) on journal\n", op));
38152  return SQLITE_NOTFOUND;
38153}
38154static int kvvfsFileControlDb(sqlite3_file *pProtoFile, int op, void *pArg){
38155  SQLITE_KV_LOG(("xFileControl(%d) on database\n", op));
38156  if( op==SQLITE_FCNTL_SYNC ){
38157    KVVfsFile *pFile = (KVVfsFile *)pProtoFile;
38158    int rc = SQLITE_OK;
38159    SQLITE_KV_LOG(("xSync('%s-db')\n", pFile->zClass));
38160    if( pFile->szDb>0 && 0!=kvvfsWriteFileSize(pFile, pFile->szDb) ){
38161      rc = SQLITE_IOERR;
38162    }
38163    return rc;
38164  }
38165  return SQLITE_NOTFOUND;
38166}
38167
38168/*
38169** Return the sector-size in bytes for an kvvfs-file.
38170*/
38171static int kvvfsSectorSize(sqlite3_file *pFile){
38172  return 512;
38173}
38174
38175/*
38176** Return the device characteristic flags supported by an kvvfs-file.
38177*/
38178static int kvvfsDeviceCharacteristics(sqlite3_file *pProtoFile){
38179  return 0;
38180}
38181
38182/****** sqlite3_vfs methods *************************************************/
38183
38184/*
38185** Open an kvvfs file handle.
38186*/
38187static int kvvfsOpen(
38188  sqlite3_vfs *pProtoVfs,
38189  const char *zName,
38190  sqlite3_file *pProtoFile,
38191  int flags,
38192  int *pOutFlags
38193){
38194  KVVfsFile *pFile = (KVVfsFile*)pProtoFile;
38195  if( zName==0 ) zName = "";
38196  SQLITE_KV_LOG(("xOpen(\"%s\")\n", zName));
38197  if( strcmp(zName, "local")==0
38198   || strcmp(zName, "session")==0
38199  ){
38200    pFile->isJournal = 0;
38201    pFile->base.pMethods = &kvvfs_db_io_methods;
38202  }else
38203  if( strcmp(zName, "local-journal")==0
38204   || strcmp(zName, "session-journal")==0
38205  ){
38206    pFile->isJournal = 1;
38207    pFile->base.pMethods = &kvvfs_jrnl_io_methods;
38208  }else{
38209    return SQLITE_CANTOPEN;
38210  }
38211  if( zName[0]=='s' ){
38212    pFile->zClass = "session";
38213  }else{
38214    pFile->zClass = "local";
38215  }
38216  pFile->aData = sqlite3_malloc64(SQLITE_KVOS_SZ);
38217  if( pFile->aData==0 ){
38218    return SQLITE_NOMEM;
38219  }
38220  pFile->aJrnl = 0;
38221  pFile->nJrnl = 0;
38222  pFile->szPage = -1;
38223  pFile->szDb = -1;
38224  return SQLITE_OK;
38225}
38226
38227/*
38228** Delete the file located at zPath. If the dirSync argument is true,
38229** ensure the file-system modifications are synced to disk before
38230** returning.
38231*/
38232static int kvvfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
38233  if( strcmp(zPath, "local-journal")==0 ){
38234    sqlite3KvvfsMethods.xDelete("local", "jrnl");
38235  }else
38236  if( strcmp(zPath, "session-journal")==0 ){
38237    sqlite3KvvfsMethods.xDelete("session", "jrnl");
38238  }
38239  return SQLITE_OK;
38240}
38241
38242/*
38243** Test for access permissions. Return true if the requested permission
38244** is available, or false otherwise.
38245*/
38246static int kvvfsAccess(
38247  sqlite3_vfs *pProtoVfs,
38248  const char *zPath,
38249  int flags,
38250  int *pResOut
38251){
38252  SQLITE_KV_LOG(("xAccess(\"%s\")\n", zPath));
38253  if( strcmp(zPath, "local-journal")==0 ){
38254    *pResOut = sqlite3KvvfsMethods.xRead("local", "jrnl", 0, 0)>0;
38255  }else
38256  if( strcmp(zPath, "session-journal")==0 ){
38257    *pResOut = sqlite3KvvfsMethods.xRead("session", "jrnl", 0, 0)>0;
38258  }else
38259  if( strcmp(zPath, "local")==0 ){
38260    *pResOut = sqlite3KvvfsMethods.xRead("local", "sz", 0, 0)>0;
38261  }else
38262  if( strcmp(zPath, "session")==0 ){
38263    *pResOut = sqlite3KvvfsMethods.xRead("session", "sz", 0, 0)>0;
38264  }else
38265  {
38266    *pResOut = 0;
38267  }
38268  SQLITE_KV_LOG(("xAccess returns %d\n",*pResOut));
38269  return SQLITE_OK;
38270}
38271
38272/*
38273** Populate buffer zOut with the full canonical pathname corresponding
38274** to the pathname in zPath. zOut is guaranteed to point to a buffer
38275** of at least (INST_MAX_PATHNAME+1) bytes.
38276*/
38277static int kvvfsFullPathname(
38278  sqlite3_vfs *pVfs,
38279  const char *zPath,
38280  int nOut,
38281  char *zOut
38282){
38283  size_t nPath;
38284#ifdef SQLITE_OS_KV_ALWAYS_LOCAL
38285  zPath = "local";
38286#endif
38287  nPath = strlen(zPath);
38288  SQLITE_KV_LOG(("xFullPathname(\"%s\")\n", zPath));
38289  if( nOut<nPath+1 ) nPath = nOut - 1;
38290  memcpy(zOut, zPath, nPath);
38291  zOut[nPath] = 0;
38292  return SQLITE_OK;
38293}
38294
38295/*
38296** Open the dynamic library located at zPath and return a handle.
38297*/
38298static void *kvvfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
38299  return 0;
38300}
38301
38302/*
38303** Populate the buffer pointed to by zBufOut with nByte bytes of
38304** random data.
38305*/
38306static int kvvfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
38307  memset(zBufOut, 0, nByte);
38308  return nByte;
38309}
38310
38311/*
38312** Sleep for nMicro microseconds. Return the number of microseconds
38313** actually slept.
38314*/
38315static int kvvfsSleep(sqlite3_vfs *pVfs, int nMicro){
38316  return SQLITE_OK;
38317}
38318
38319/*
38320** Return the current time as a Julian Day number in *pTimeOut.
38321*/
38322static int kvvfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
38323  sqlite3_int64 i = 0;
38324  int rc;
38325  rc = kvvfsCurrentTimeInt64(0, &i);
38326  *pTimeOut = i/86400000.0;
38327  return rc;
38328}
38329#include <sys/time.h>
38330static int kvvfsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
38331  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
38332  struct timeval sNow;
38333  (void)gettimeofday(&sNow, 0);  /* Cannot fail given valid arguments */
38334  *pTimeOut = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
38335  return SQLITE_OK;
38336}
38337#endif /* SQLITE_OS_KV || SQLITE_OS_UNIX */
38338
38339#if SQLITE_OS_KV
38340/*
38341** This routine is called initialize the KV-vfs as the default VFS.
38342*/
38343SQLITE_API int sqlite3_os_init(void){
38344  return sqlite3_vfs_register(&sqlite3OsKvvfsObject, 1);
38345}
38346SQLITE_API int sqlite3_os_end(void){
38347  return SQLITE_OK;
38348}
38349#endif /* SQLITE_OS_KV */
38350
38351#if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
38352SQLITE_PRIVATE int sqlite3KvvfsInit(void){
38353  return sqlite3_vfs_register(&sqlite3OsKvvfsObject, 0);
38354}
38355#endif
38356
38357/************** End of os_kv.c ***********************************************/
38358/************** Begin file os_unix.c *****************************************/
38359/*
38360** 2004 May 22
38361**
38362** The author disclaims copyright to this source code.  In place of
38363** a legal notice, here is a blessing:
38364**
38365**    May you do good and not evil.
38366**    May you find forgiveness for yourself and forgive others.
38367**    May you share freely, never taking more than you give.
38368**
38369******************************************************************************
38370**
38371** This file contains the VFS implementation for unix-like operating systems
38372** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
38373**
38374** There are actually several different VFS implementations in this file.
38375** The differences are in the way that file locking is done.  The default
38376** implementation uses Posix Advisory Locks.  Alternative implementations
38377** use flock(), dot-files, various proprietary locking schemas, or simply
38378** skip locking all together.
38379**
38380** This source file is organized into divisions where the logic for various
38381** subfunctions is contained within the appropriate division.  PLEASE
38382** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
38383** in the correct division and should be clearly labelled.
38384**
38385** The layout of divisions is as follows:
38386**
38387**   *  General-purpose declarations and utility functions.
38388**   *  Unique file ID logic used by VxWorks.
38389**   *  Various locking primitive implementations (all except proxy locking):
38390**      + for Posix Advisory Locks
38391**      + for no-op locks
38392**      + for dot-file locks
38393**      + for flock() locking
38394**      + for named semaphore locks (VxWorks only)
38395**      + for AFP filesystem locks (MacOSX only)
38396**   *  sqlite3_file methods not associated with locking.
38397**   *  Definitions of sqlite3_io_methods objects for all locking
38398**      methods plus "finder" functions for each locking method.
38399**   *  sqlite3_vfs method implementations.
38400**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
38401**   *  Definitions of sqlite3_vfs objects for all locking methods
38402**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
38403*/
38404/* #include "sqliteInt.h" */
38405#if SQLITE_OS_UNIX              /* This file is used on unix only */
38406
38407/*
38408** There are various methods for file locking used for concurrency
38409** control:
38410**
38411**   1. POSIX locking (the default),
38412**   2. No locking,
38413**   3. Dot-file locking,
38414**   4. flock() locking,
38415**   5. AFP locking (OSX only),
38416**   6. Named POSIX semaphores (VXWorks only),
38417**   7. proxy locking. (OSX only)
38418**
38419** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
38420** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
38421** selection of the appropriate locking style based on the filesystem
38422** where the database is located.
38423*/
38424#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
38425#  if defined(__APPLE__)
38426#    define SQLITE_ENABLE_LOCKING_STYLE 1
38427#  else
38428#    define SQLITE_ENABLE_LOCKING_STYLE 0
38429#  endif
38430#endif
38431
38432/* Use pread() and pwrite() if they are available */
38433#if defined(__APPLE__) || defined(__linux__)
38434# define HAVE_PREAD 1
38435# define HAVE_PWRITE 1
38436#endif
38437#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
38438# undef USE_PREAD
38439# define USE_PREAD64 1
38440#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
38441# undef USE_PREAD64
38442# define USE_PREAD 1
38443#endif
38444
38445/*
38446** standard include files.
38447*/
38448#include <sys/types.h>   /* amalgamator: keep */
38449#include <sys/stat.h>    /* amalgamator: keep */
38450#include <fcntl.h>
38451#include <sys/ioctl.h>
38452#include <unistd.h>      /* amalgamator: keep */
38453/* #include <time.h> */
38454#include <sys/time.h>    /* amalgamator: keep */
38455#include <errno.h>
38456#if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \
38457  && !defined(SQLITE_WASI)
38458# include <sys/mman.h>
38459#endif
38460
38461#if SQLITE_ENABLE_LOCKING_STYLE
38462/* # include <sys/ioctl.h> */
38463# include <sys/file.h>
38464# include <sys/param.h>
38465#endif /* SQLITE_ENABLE_LOCKING_STYLE */
38466
38467/*
38468** Try to determine if gethostuuid() is available based on standard
38469** macros.  This might sometimes compute the wrong value for some
38470** obscure platforms.  For those cases, simply compile with one of
38471** the following:
38472**
38473**    -DHAVE_GETHOSTUUID=0
38474**    -DHAVE_GETHOSTUUID=1
38475**
38476** None if this matters except when building on Apple products with
38477** -DSQLITE_ENABLE_LOCKING_STYLE.
38478*/
38479#ifndef HAVE_GETHOSTUUID
38480# define HAVE_GETHOSTUUID 0
38481# if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
38482                            (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
38483#    if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
38484        && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))\
38485        && (!defined(TARGET_OS_MACCATALYST) || (TARGET_OS_MACCATALYST==0))
38486#      undef HAVE_GETHOSTUUID
38487#      define HAVE_GETHOSTUUID 1
38488#    else
38489#      warning "gethostuuid() is disabled."
38490#    endif
38491#  endif
38492#endif
38493
38494
38495#if OS_VXWORKS
38496/* # include <sys/ioctl.h> */
38497# include <semaphore.h>
38498# include <limits.h>
38499#endif /* OS_VXWORKS */
38500
38501#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
38502# include <sys/mount.h>
38503#endif
38504
38505#ifdef HAVE_UTIME
38506# include <utime.h>
38507#endif
38508
38509/*
38510** Allowed values of unixFile.fsFlags
38511*/
38512#define SQLITE_FSFLAGS_IS_MSDOS     0x1
38513
38514/*
38515** If we are to be thread-safe, include the pthreads header.
38516*/
38517#if SQLITE_THREADSAFE
38518/* # include <pthread.h> */
38519#endif
38520
38521/*
38522** Default permissions when creating a new file
38523*/
38524#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
38525# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
38526#endif
38527
38528/*
38529** Default permissions when creating auto proxy dir
38530*/
38531#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
38532# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
38533#endif
38534
38535/*
38536** Maximum supported path-length.
38537*/
38538#define MAX_PATHNAME 512
38539
38540/*
38541** Maximum supported symbolic links
38542*/
38543#define SQLITE_MAX_SYMLINKS 100
38544
38545/*
38546** Remove and stub certain info for WASI (WebAssembly System
38547** Interface) builds.
38548*/
38549#ifdef SQLITE_WASI
38550# undef HAVE_FCHMOD
38551# undef HAVE_FCHOWN
38552# undef HAVE_MREMAP
38553# define HAVE_MREMAP 0
38554# ifndef SQLITE_DEFAULT_UNIX_VFS
38555#  define SQLITE_DEFAULT_UNIX_VFS "unix-dotfile"
38556   /* ^^^ should SQLITE_DEFAULT_UNIX_VFS be "unix-none"? */
38557# endif
38558# ifndef F_RDLCK
38559#  define F_RDLCK 0
38560#  define F_WRLCK 1
38561#  define F_UNLCK 2
38562#  if __LONG_MAX == 0x7fffffffL
38563#   define F_GETLK 12
38564#   define F_SETLK 13
38565#   define F_SETLKW 14
38566#  else
38567#   define F_GETLK 5
38568#   define F_SETLK 6
38569#   define F_SETLKW 7
38570#  endif
38571# endif
38572#else /* !SQLITE_WASI */
38573# ifndef HAVE_FCHMOD
38574#  define HAVE_FCHMOD
38575# endif
38576#endif /* SQLITE_WASI */
38577
38578#ifdef SQLITE_WASI
38579# define osGetpid(X) (pid_t)1
38580#else
38581/* Always cast the getpid() return type for compatibility with
38582** kernel modules in VxWorks. */
38583# define osGetpid(X) (pid_t)getpid()
38584#endif
38585
38586/*
38587** Only set the lastErrno if the error code is a real error and not
38588** a normal expected return code of SQLITE_BUSY or SQLITE_OK
38589*/
38590#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
38591
38592/* Forward references */
38593typedef struct unixShm unixShm;               /* Connection shared memory */
38594typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
38595typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
38596typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
38597
38598/*
38599** Sometimes, after a file handle is closed by SQLite, the file descriptor
38600** cannot be closed immediately. In these cases, instances of the following
38601** structure are used to store the file descriptor while waiting for an
38602** opportunity to either close or reuse it.
38603*/
38604struct UnixUnusedFd {
38605  int fd;                   /* File descriptor to close */
38606  int flags;                /* Flags this file descriptor was opened with */
38607  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
38608};
38609
38610/*
38611** The unixFile structure is subclass of sqlite3_file specific to the unix
38612** VFS implementations.
38613*/
38614typedef struct unixFile unixFile;
38615struct unixFile {
38616  sqlite3_io_methods const *pMethod;  /* Always the first entry */
38617  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
38618  unixInodeInfo *pInode;              /* Info about locks on this inode */
38619  int h;                              /* The file descriptor */
38620  unsigned char eFileLock;            /* The type of lock held on this fd */
38621  unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
38622  int lastErrno;                      /* The unix errno from last I/O error */
38623  void *lockingContext;               /* Locking style specific state */
38624  UnixUnusedFd *pPreallocatedUnused;  /* Pre-allocated UnixUnusedFd */
38625  const char *zPath;                  /* Name of the file */
38626  unixShm *pShm;                      /* Shared memory segment information */
38627  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
38628#if SQLITE_MAX_MMAP_SIZE>0
38629  int nFetchOut;                      /* Number of outstanding xFetch refs */
38630  sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
38631  sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
38632  sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
38633  void *pMapRegion;                   /* Memory mapped region */
38634#endif
38635  int sectorSize;                     /* Device sector size */
38636  int deviceCharacteristics;          /* Precomputed device characteristics */
38637#if SQLITE_ENABLE_LOCKING_STYLE
38638  int openFlags;                      /* The flags specified at open() */
38639#endif
38640#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
38641  unsigned fsFlags;                   /* cached details from statfs() */
38642#endif
38643#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
38644  unsigned iBusyTimeout;              /* Wait this many millisec on locks */
38645#endif
38646#if OS_VXWORKS
38647  struct vxworksFileId *pId;          /* Unique file ID */
38648#endif
38649#ifdef SQLITE_DEBUG
38650  /* The next group of variables are used to track whether or not the
38651  ** transaction counter in bytes 24-27 of database files are updated
38652  ** whenever any part of the database changes.  An assertion fault will
38653  ** occur if a file is updated without also updating the transaction
38654  ** counter.  This test is made to avoid new problems similar to the
38655  ** one described by ticket #3584.
38656  */
38657  unsigned char transCntrChng;   /* True if the transaction counter changed */
38658  unsigned char dbUpdate;        /* True if any part of database file changed */
38659  unsigned char inNormalWrite;   /* True if in a normal write operation */
38660
38661#endif
38662
38663#ifdef SQLITE_TEST
38664  /* In test mode, increase the size of this structure a bit so that
38665  ** it is larger than the struct CrashFile defined in test6.c.
38666  */
38667  char aPadding[32];
38668#endif
38669};
38670
38671/* This variable holds the process id (pid) from when the xRandomness()
38672** method was called.  If xOpen() is called from a different process id,
38673** indicating that a fork() has occurred, the PRNG will be reset.
38674*/
38675static pid_t randomnessPid = 0;
38676
38677/*
38678** Allowed values for the unixFile.ctrlFlags bitmask:
38679*/
38680#define UNIXFILE_EXCL        0x01     /* Connections from one process only */
38681#define UNIXFILE_RDONLY      0x02     /* Connection is read only */
38682#define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
38683#ifndef SQLITE_DISABLE_DIRSYNC
38684# define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
38685#else
38686# define UNIXFILE_DIRSYNC    0x00
38687#endif
38688#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
38689#define UNIXFILE_DELETE      0x20     /* Delete on close */
38690#define UNIXFILE_URI         0x40     /* Filename might have query parameters */
38691#define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
38692
38693/*
38694** Include code that is common to all os_*.c files
38695*/
38696/* #include "os_common.h" */
38697
38698/*
38699** Define various macros that are missing from some systems.
38700*/
38701#ifndef O_LARGEFILE
38702# define O_LARGEFILE 0
38703#endif
38704#ifdef SQLITE_DISABLE_LFS
38705# undef O_LARGEFILE
38706# define O_LARGEFILE 0
38707#endif
38708#ifndef O_NOFOLLOW
38709# define O_NOFOLLOW 0
38710#endif
38711#ifndef O_BINARY
38712# define O_BINARY 0
38713#endif
38714
38715/*
38716** The threadid macro resolves to the thread-id or to 0.  Used for
38717** testing and debugging only.
38718*/
38719#if SQLITE_THREADSAFE
38720#define threadid pthread_self()
38721#else
38722#define threadid 0
38723#endif
38724
38725/*
38726** HAVE_MREMAP defaults to true on Linux and false everywhere else.
38727*/
38728#if !defined(HAVE_MREMAP)
38729# if defined(__linux__) && defined(_GNU_SOURCE)
38730#  define HAVE_MREMAP 1
38731# else
38732#  define HAVE_MREMAP 0
38733# endif
38734#endif
38735
38736/*
38737** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
38738** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
38739*/
38740#ifdef __ANDROID__
38741# define lseek lseek64
38742#endif
38743
38744#ifdef __linux__
38745/*
38746** Linux-specific IOCTL magic numbers used for controlling F2FS
38747*/
38748#define F2FS_IOCTL_MAGIC        0xf5
38749#define F2FS_IOC_START_ATOMIC_WRITE     _IO(F2FS_IOCTL_MAGIC, 1)
38750#define F2FS_IOC_COMMIT_ATOMIC_WRITE    _IO(F2FS_IOCTL_MAGIC, 2)
38751#define F2FS_IOC_START_VOLATILE_WRITE   _IO(F2FS_IOCTL_MAGIC, 3)
38752#define F2FS_IOC_ABORT_VOLATILE_WRITE   _IO(F2FS_IOCTL_MAGIC, 5)
38753#define F2FS_IOC_GET_FEATURES           _IOR(F2FS_IOCTL_MAGIC, 12, u32)
38754#define F2FS_FEATURE_ATOMIC_WRITE 0x0004
38755#endif /* __linux__ */
38756
38757
38758/*
38759** Different Unix systems declare open() in different ways.  Same use
38760** open(const char*,int,mode_t).  Others use open(const char*,int,...).
38761** The difference is important when using a pointer to the function.
38762**
38763** The safest way to deal with the problem is to always use this wrapper
38764** which always has the same well-defined interface.
38765*/
38766static int posixOpen(const char *zFile, int flags, int mode){
38767  return open(zFile, flags, mode);
38768}
38769
38770/* Forward reference */
38771static int openDirectory(const char*, int*);
38772static int unixGetpagesize(void);
38773
38774/*
38775** Many system calls are accessed through pointer-to-functions so that
38776** they may be overridden at runtime to facilitate fault injection during
38777** testing and sandboxing.  The following array holds the names and pointers
38778** to all overrideable system calls.
38779*/
38780static struct unix_syscall {
38781  const char *zName;            /* Name of the system call */
38782  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
38783  sqlite3_syscall_ptr pDefault; /* Default value */
38784} aSyscall[] = {
38785  { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
38786#define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
38787
38788  { "close",        (sqlite3_syscall_ptr)close,      0  },
38789#define osClose     ((int(*)(int))aSyscall[1].pCurrent)
38790
38791  { "access",       (sqlite3_syscall_ptr)access,     0  },
38792#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
38793
38794  { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
38795#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
38796
38797  { "stat",         (sqlite3_syscall_ptr)stat,       0  },
38798#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
38799
38800/*
38801** The DJGPP compiler environment looks mostly like Unix, but it
38802** lacks the fcntl() system call.  So redefine fcntl() to be something
38803** that always succeeds.  This means that locking does not occur under
38804** DJGPP.  But it is DOS - what did you expect?
38805*/
38806#ifdef __DJGPP__
38807  { "fstat",        0,                 0  },
38808#define osFstat(a,b,c)    0
38809#else
38810  { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
38811#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
38812#endif
38813
38814  { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
38815#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
38816
38817  { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
38818#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
38819
38820  { "read",         (sqlite3_syscall_ptr)read,       0  },
38821#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
38822
38823#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
38824  { "pread",        (sqlite3_syscall_ptr)pread,      0  },
38825#else
38826  { "pread",        (sqlite3_syscall_ptr)0,          0  },
38827#endif
38828#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
38829
38830#if defined(USE_PREAD64)
38831  { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
38832#else
38833  { "pread64",      (sqlite3_syscall_ptr)0,          0  },
38834#endif
38835#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
38836
38837  { "write",        (sqlite3_syscall_ptr)write,      0  },
38838#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
38839
38840#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
38841  { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
38842#else
38843  { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
38844#endif
38845#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
38846                    aSyscall[12].pCurrent)
38847
38848#if defined(USE_PREAD64)
38849  { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
38850#else
38851  { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
38852#endif
38853#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\
38854                    aSyscall[13].pCurrent)
38855
38856#if defined(HAVE_FCHMOD)
38857  { "fchmod",       (sqlite3_syscall_ptr)fchmod,          0  },
38858#else
38859  { "fchmod",       (sqlite3_syscall_ptr)0,               0  },
38860#endif
38861#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
38862
38863#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
38864  { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
38865#else
38866  { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
38867#endif
38868#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
38869
38870  { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
38871#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
38872
38873  { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
38874#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
38875
38876  { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
38877#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
38878
38879  { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
38880#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
38881
38882#if defined(HAVE_FCHOWN)
38883  { "fchown",       (sqlite3_syscall_ptr)fchown,          0 },
38884#else
38885  { "fchown",       (sqlite3_syscall_ptr)0,               0 },
38886#endif
38887#define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
38888
38889#if defined(HAVE_FCHOWN)
38890  { "geteuid",      (sqlite3_syscall_ptr)geteuid,         0 },
38891#else
38892  { "geteuid",      (sqlite3_syscall_ptr)0,               0 },
38893#endif
38894#define osGeteuid   ((uid_t(*)(void))aSyscall[21].pCurrent)
38895
38896#if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \
38897  && !defined(SQLITE_WASI)
38898  { "mmap",         (sqlite3_syscall_ptr)mmap,            0 },
38899#else
38900  { "mmap",         (sqlite3_syscall_ptr)0,               0 },
38901#endif
38902#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
38903
38904#if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \
38905  && !defined(SQLITE_WASI)
38906  { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
38907#else
38908  { "munmap",       (sqlite3_syscall_ptr)0,               0 },
38909#endif
38910#define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
38911
38912#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
38913  { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
38914#else
38915  { "mremap",       (sqlite3_syscall_ptr)0,               0 },
38916#endif
38917#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
38918
38919#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
38920  { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
38921#else
38922  { "getpagesize",  (sqlite3_syscall_ptr)0,               0 },
38923#endif
38924#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
38925
38926#if defined(HAVE_READLINK)
38927  { "readlink",     (sqlite3_syscall_ptr)readlink,        0 },
38928#else
38929  { "readlink",     (sqlite3_syscall_ptr)0,               0 },
38930#endif
38931#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
38932
38933#if defined(HAVE_LSTAT)
38934  { "lstat",         (sqlite3_syscall_ptr)lstat,          0 },
38935#else
38936  { "lstat",         (sqlite3_syscall_ptr)0,              0 },
38937#endif
38938#define osLstat      ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
38939
38940#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
38941# ifdef __ANDROID__
38942  { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
38943#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
38944# else
38945  { "ioctl",         (sqlite3_syscall_ptr)ioctl,          0 },
38946#define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent)
38947# endif
38948#else
38949  { "ioctl",         (sqlite3_syscall_ptr)0,              0 },
38950#endif
38951
38952}; /* End of the overrideable system calls */
38953
38954
38955/*
38956** On some systems, calls to fchown() will trigger a message in a security
38957** log if they come from non-root processes.  So avoid calling fchown() if
38958** we are not running as root.
38959*/
38960static int robustFchown(int fd, uid_t uid, gid_t gid){
38961#if defined(HAVE_FCHOWN)
38962  return osGeteuid() ? 0 : osFchown(fd,uid,gid);
38963#else
38964  return 0;
38965#endif
38966}
38967
38968/*
38969** This is the xSetSystemCall() method of sqlite3_vfs for all of the
38970** "unix" VFSes.  Return SQLITE_OK upon successfully updating the
38971** system call pointer, or SQLITE_NOTFOUND if there is no configurable
38972** system call named zName.
38973*/
38974static int unixSetSystemCall(
38975  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
38976  const char *zName,            /* Name of system call to override */
38977  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
38978){
38979  unsigned int i;
38980  int rc = SQLITE_NOTFOUND;
38981
38982  UNUSED_PARAMETER(pNotUsed);
38983  if( zName==0 ){
38984    /* If no zName is given, restore all system calls to their default
38985    ** settings and return NULL
38986    */
38987    rc = SQLITE_OK;
38988    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38989      if( aSyscall[i].pDefault ){
38990        aSyscall[i].pCurrent = aSyscall[i].pDefault;
38991      }
38992    }
38993  }else{
38994    /* If zName is specified, operate on only the one system call
38995    ** specified.
38996    */
38997    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38998      if( strcmp(zName, aSyscall[i].zName)==0 ){
38999        if( aSyscall[i].pDefault==0 ){
39000          aSyscall[i].pDefault = aSyscall[i].pCurrent;
39001        }
39002        rc = SQLITE_OK;
39003        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
39004        aSyscall[i].pCurrent = pNewFunc;
39005        break;
39006      }
39007    }
39008  }
39009  return rc;
39010}
39011
39012/*
39013** Return the value of a system call.  Return NULL if zName is not a
39014** recognized system call name.  NULL is also returned if the system call
39015** is currently undefined.
39016*/
39017static sqlite3_syscall_ptr unixGetSystemCall(
39018  sqlite3_vfs *pNotUsed,
39019  const char *zName
39020){
39021  unsigned int i;
39022
39023  UNUSED_PARAMETER(pNotUsed);
39024  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
39025    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
39026  }
39027  return 0;
39028}
39029
39030/*
39031** Return the name of the first system call after zName.  If zName==NULL
39032** then return the name of the first system call.  Return NULL if zName
39033** is the last system call or if zName is not the name of a valid
39034** system call.
39035*/
39036static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
39037  int i = -1;
39038
39039  UNUSED_PARAMETER(p);
39040  if( zName ){
39041    for(i=0; i<ArraySize(aSyscall)-1; i++){
39042      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
39043    }
39044  }
39045  for(i++; i<ArraySize(aSyscall); i++){
39046    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
39047  }
39048  return 0;
39049}
39050
39051/*
39052** Do not accept any file descriptor less than this value, in order to avoid
39053** opening database file using file descriptors that are commonly used for
39054** standard input, output, and error.
39055*/
39056#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
39057# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
39058#endif
39059
39060/*
39061** Invoke open().  Do so multiple times, until it either succeeds or
39062** fails for some reason other than EINTR.
39063**
39064** If the file creation mode "m" is 0 then set it to the default for
39065** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
39066** 0644) as modified by the system umask.  If m is not 0, then
39067** make the file creation mode be exactly m ignoring the umask.
39068**
39069** The m parameter will be non-zero only when creating -wal, -journal,
39070** and -shm files.  We want those files to have *exactly* the same
39071** permissions as their original database, unadulterated by the umask.
39072** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
39073** transaction crashes and leaves behind hot journals, then any
39074** process that is able to write to the database will also be able to
39075** recover the hot journals.
39076*/
39077static int robust_open(const char *z, int f, mode_t m){
39078  int fd;
39079  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
39080  while(1){
39081#if defined(O_CLOEXEC)
39082    fd = osOpen(z,f|O_CLOEXEC,m2);
39083#else
39084    fd = osOpen(z,f,m2);
39085#endif
39086    if( fd<0 ){
39087      if( errno==EINTR ) continue;
39088      break;
39089    }
39090    if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
39091    if( (f & (O_EXCL|O_CREAT))==(O_EXCL|O_CREAT) ){
39092      (void)osUnlink(z);
39093    }
39094    osClose(fd);
39095    sqlite3_log(SQLITE_WARNING,
39096                "attempt to open \"%s\" as file descriptor %d", z, fd);
39097    fd = -1;
39098    if( osOpen("/dev/null", O_RDONLY, m)<0 ) break;
39099  }
39100  if( fd>=0 ){
39101    if( m!=0 ){
39102      struct stat statbuf;
39103      if( osFstat(fd, &statbuf)==0
39104       && statbuf.st_size==0
39105       && (statbuf.st_mode&0777)!=m
39106      ){
39107        osFchmod(fd, m);
39108      }
39109    }
39110#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
39111    osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
39112#endif
39113  }
39114  return fd;
39115}
39116
39117/*
39118** Helper functions to obtain and relinquish the global mutex. The
39119** global mutex is used to protect the unixInodeInfo and
39120** vxworksFileId objects used by this file, all of which may be
39121** shared by multiple threads.
39122**
39123** Function unixMutexHeld() is used to assert() that the global mutex
39124** is held when required. This function is only used as part of assert()
39125** statements. e.g.
39126**
39127**   unixEnterMutex()
39128**     assert( unixMutexHeld() );
39129**   unixEnterLeave()
39130**
39131** To prevent deadlock, the global unixBigLock must must be acquired
39132** before the unixInodeInfo.pLockMutex mutex, if both are held.  It is
39133** OK to get the pLockMutex without holding unixBigLock first, but if
39134** that happens, the unixBigLock mutex must not be acquired until after
39135** pLockMutex is released.
39136**
39137**      OK:     enter(unixBigLock),  enter(pLockInfo)
39138**      OK:     enter(unixBigLock)
39139**      OK:     enter(pLockInfo)
39140**   ERROR:     enter(pLockInfo), enter(unixBigLock)
39141*/
39142static sqlite3_mutex *unixBigLock = 0;
39143static void unixEnterMutex(void){
39144  assert( sqlite3_mutex_notheld(unixBigLock) );  /* Not a recursive mutex */
39145  sqlite3_mutex_enter(unixBigLock);
39146}
39147static void unixLeaveMutex(void){
39148  assert( sqlite3_mutex_held(unixBigLock) );
39149  sqlite3_mutex_leave(unixBigLock);
39150}
39151#ifdef SQLITE_DEBUG
39152static int unixMutexHeld(void) {
39153  return sqlite3_mutex_held(unixBigLock);
39154}
39155#endif
39156
39157
39158#ifdef SQLITE_HAVE_OS_TRACE
39159/*
39160** Helper function for printing out trace information from debugging
39161** binaries. This returns the string representation of the supplied
39162** integer lock-type.
39163*/
39164static const char *azFileLock(int eFileLock){
39165  switch( eFileLock ){
39166    case NO_LOCK: return "NONE";
39167    case SHARED_LOCK: return "SHARED";
39168    case RESERVED_LOCK: return "RESERVED";
39169    case PENDING_LOCK: return "PENDING";
39170    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
39171  }
39172  return "ERROR";
39173}
39174#endif
39175
39176#ifdef SQLITE_LOCK_TRACE
39177/*
39178** Print out information about all locking operations.
39179**
39180** This routine is used for troubleshooting locks on multithreaded
39181** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
39182** command-line option on the compiler.  This code is normally
39183** turned off.
39184*/
39185static int lockTrace(int fd, int op, struct flock *p){
39186  char *zOpName, *zType;
39187  int s;
39188  int savedErrno;
39189  if( op==F_GETLK ){
39190    zOpName = "GETLK";
39191  }else if( op==F_SETLK ){
39192    zOpName = "SETLK";
39193  }else{
39194    s = osFcntl(fd, op, p);
39195    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
39196    return s;
39197  }
39198  if( p->l_type==F_RDLCK ){
39199    zType = "RDLCK";
39200  }else if( p->l_type==F_WRLCK ){
39201    zType = "WRLCK";
39202  }else if( p->l_type==F_UNLCK ){
39203    zType = "UNLCK";
39204  }else{
39205    assert( 0 );
39206  }
39207  assert( p->l_whence==SEEK_SET );
39208  s = osFcntl(fd, op, p);
39209  savedErrno = errno;
39210  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
39211     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
39212     (int)p->l_pid, s);
39213  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
39214    struct flock l2;
39215    l2 = *p;
39216    osFcntl(fd, F_GETLK, &l2);
39217    if( l2.l_type==F_RDLCK ){
39218      zType = "RDLCK";
39219    }else if( l2.l_type==F_WRLCK ){
39220      zType = "WRLCK";
39221    }else if( l2.l_type==F_UNLCK ){
39222      zType = "UNLCK";
39223    }else{
39224      assert( 0 );
39225    }
39226    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
39227       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
39228  }
39229  errno = savedErrno;
39230  return s;
39231}
39232#undef osFcntl
39233#define osFcntl lockTrace
39234#endif /* SQLITE_LOCK_TRACE */
39235
39236/*
39237** Retry ftruncate() calls that fail due to EINTR
39238**
39239** All calls to ftruncate() within this file should be made through
39240** this wrapper.  On the Android platform, bypassing the logic below
39241** could lead to a corrupt database.
39242*/
39243static int robust_ftruncate(int h, sqlite3_int64 sz){
39244  int rc;
39245#ifdef __ANDROID__
39246  /* On Android, ftruncate() always uses 32-bit offsets, even if
39247  ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
39248  ** truncate a file to any size larger than 2GiB. Silently ignore any
39249  ** such attempts.  */
39250  if( sz>(sqlite3_int64)0x7FFFFFFF ){
39251    rc = SQLITE_OK;
39252  }else
39253#endif
39254  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
39255  return rc;
39256}
39257
39258/*
39259** This routine translates a standard POSIX errno code into something
39260** useful to the clients of the sqlite3 functions.  Specifically, it is
39261** intended to translate a variety of "try again" errors into SQLITE_BUSY
39262** and a variety of "please close the file descriptor NOW" errors into
39263** SQLITE_IOERR
39264**
39265** Errors during initialization of locks, or file system support for locks,
39266** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
39267*/
39268static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
39269  assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
39270          (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
39271          (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
39272          (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
39273  switch (posixError) {
39274  case EACCES:
39275  case EAGAIN:
39276  case ETIMEDOUT:
39277  case EBUSY:
39278  case EINTR:
39279  case ENOLCK:
39280    /* random NFS retry error, unless during file system support
39281     * introspection, in which it actually means what it says */
39282    return SQLITE_BUSY;
39283
39284  case EPERM:
39285    return SQLITE_PERM;
39286
39287  default:
39288    return sqliteIOErr;
39289  }
39290}
39291
39292
39293/******************************************************************************
39294****************** Begin Unique File ID Utility Used By VxWorks ***************
39295**
39296** On most versions of unix, we can get a unique ID for a file by concatenating
39297** the device number and the inode number.  But this does not work on VxWorks.
39298** On VxWorks, a unique file id must be based on the canonical filename.
39299**
39300** A pointer to an instance of the following structure can be used as a
39301** unique file ID in VxWorks.  Each instance of this structure contains
39302** a copy of the canonical filename.  There is also a reference count.
39303** The structure is reclaimed when the number of pointers to it drops to
39304** zero.
39305**
39306** There are never very many files open at one time and lookups are not
39307** a performance-critical path, so it is sufficient to put these
39308** structures on a linked list.
39309*/
39310struct vxworksFileId {
39311  struct vxworksFileId *pNext;  /* Next in a list of them all */
39312  int nRef;                     /* Number of references to this one */
39313  int nName;                    /* Length of the zCanonicalName[] string */
39314  char *zCanonicalName;         /* Canonical filename */
39315};
39316
39317#if OS_VXWORKS
39318/*
39319** All unique filenames are held on a linked list headed by this
39320** variable:
39321*/
39322static struct vxworksFileId *vxworksFileList = 0;
39323
39324/*
39325** Simplify a filename into its canonical form
39326** by making the following changes:
39327**
39328**  * removing any trailing and duplicate /
39329**  * convert /./ into just /
39330**  * convert /A/../ where A is any simple name into just /
39331**
39332** Changes are made in-place.  Return the new name length.
39333**
39334** The original filename is in z[0..n-1].  Return the number of
39335** characters in the simplified name.
39336*/
39337static int vxworksSimplifyName(char *z, int n){
39338  int i, j;
39339  while( n>1 && z[n-1]=='/' ){ n--; }
39340  for(i=j=0; i<n; i++){
39341    if( z[i]=='/' ){
39342      if( z[i+1]=='/' ) continue;
39343      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
39344        i += 1;
39345        continue;
39346      }
39347      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
39348        while( j>0 && z[j-1]!='/' ){ j--; }
39349        if( j>0 ){ j--; }
39350        i += 2;
39351        continue;
39352      }
39353    }
39354    z[j++] = z[i];
39355  }
39356  z[j] = 0;
39357  return j;
39358}
39359
39360/*
39361** Find a unique file ID for the given absolute pathname.  Return
39362** a pointer to the vxworksFileId object.  This pointer is the unique
39363** file ID.
39364**
39365** The nRef field of the vxworksFileId object is incremented before
39366** the object is returned.  A new vxworksFileId object is created
39367** and added to the global list if necessary.
39368**
39369** If a memory allocation error occurs, return NULL.
39370*/
39371static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
39372  struct vxworksFileId *pNew;         /* search key and new file ID */
39373  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
39374  int n;                              /* Length of zAbsoluteName string */
39375
39376  assert( zAbsoluteName[0]=='/' );
39377  n = (int)strlen(zAbsoluteName);
39378  pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
39379  if( pNew==0 ) return 0;
39380  pNew->zCanonicalName = (char*)&pNew[1];
39381  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
39382  n = vxworksSimplifyName(pNew->zCanonicalName, n);
39383
39384  /* Search for an existing entry that matching the canonical name.
39385  ** If found, increment the reference count and return a pointer to
39386  ** the existing file ID.
39387  */
39388  unixEnterMutex();
39389  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
39390    if( pCandidate->nName==n
39391     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
39392    ){
39393       sqlite3_free(pNew);
39394       pCandidate->nRef++;
39395       unixLeaveMutex();
39396       return pCandidate;
39397    }
39398  }
39399
39400  /* No match was found.  We will make a new file ID */
39401  pNew->nRef = 1;
39402  pNew->nName = n;
39403  pNew->pNext = vxworksFileList;
39404  vxworksFileList = pNew;
39405  unixLeaveMutex();
39406  return pNew;
39407}
39408
39409/*
39410** Decrement the reference count on a vxworksFileId object.  Free
39411** the object when the reference count reaches zero.
39412*/
39413static void vxworksReleaseFileId(struct vxworksFileId *pId){
39414  unixEnterMutex();
39415  assert( pId->nRef>0 );
39416  pId->nRef--;
39417  if( pId->nRef==0 ){
39418    struct vxworksFileId **pp;
39419    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
39420    assert( *pp==pId );
39421    *pp = pId->pNext;
39422    sqlite3_free(pId);
39423  }
39424  unixLeaveMutex();
39425}
39426#endif /* OS_VXWORKS */
39427/*************** End of Unique File ID Utility Used By VxWorks ****************
39428******************************************************************************/
39429
39430
39431/******************************************************************************
39432*************************** Posix Advisory Locking ****************************
39433**
39434** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
39435** section 6.5.2.2 lines 483 through 490 specify that when a process
39436** sets or clears a lock, that operation overrides any prior locks set
39437** by the same process.  It does not explicitly say so, but this implies
39438** that it overrides locks set by the same process using a different
39439** file descriptor.  Consider this test case:
39440**
39441**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
39442**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
39443**
39444** Suppose ./file1 and ./file2 are really the same file (because
39445** one is a hard or symbolic link to the other) then if you set
39446** an exclusive lock on fd1, then try to get an exclusive lock
39447** on fd2, it works.  I would have expected the second lock to
39448** fail since there was already a lock on the file due to fd1.
39449** But not so.  Since both locks came from the same process, the
39450** second overrides the first, even though they were on different
39451** file descriptors opened on different file names.
39452**
39453** This means that we cannot use POSIX locks to synchronize file access
39454** among competing threads of the same process.  POSIX locks will work fine
39455** to synchronize access for threads in separate processes, but not
39456** threads within the same process.
39457**
39458** To work around the problem, SQLite has to manage file locks internally
39459** on its own.  Whenever a new database is opened, we have to find the
39460** specific inode of the database file (the inode is determined by the
39461** st_dev and st_ino fields of the stat structure that fstat() fills in)
39462** and check for locks already existing on that inode.  When locks are
39463** created or removed, we have to look at our own internal record of the
39464** locks to see if another thread has previously set a lock on that same
39465** inode.
39466**
39467** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
39468** For VxWorks, we have to use the alternative unique ID system based on
39469** canonical filename and implemented in the previous division.)
39470**
39471** The sqlite3_file structure for POSIX is no longer just an integer file
39472** descriptor.  It is now a structure that holds the integer file
39473** descriptor and a pointer to a structure that describes the internal
39474** locks on the corresponding inode.  There is one locking structure
39475** per inode, so if the same inode is opened twice, both unixFile structures
39476** point to the same locking structure.  The locking structure keeps
39477** a reference count (so we will know when to delete it) and a "cnt"
39478** field that tells us its internal lock status.  cnt==0 means the
39479** file is unlocked.  cnt==-1 means the file has an exclusive lock.
39480** cnt>0 means there are cnt shared locks on the file.
39481**
39482** Any attempt to lock or unlock a file first checks the locking
39483** structure.  The fcntl() system call is only invoked to set a
39484** POSIX lock if the internal lock structure transitions between
39485** a locked and an unlocked state.
39486**
39487** But wait:  there are yet more problems with POSIX advisory locks.
39488**
39489** If you close a file descriptor that points to a file that has locks,
39490** all locks on that file that are owned by the current process are
39491** released.  To work around this problem, each unixInodeInfo object
39492** maintains a count of the number of pending locks on the inode.
39493** When an attempt is made to close an unixFile, if there are
39494** other unixFile open on the same inode that are holding locks, the call
39495** to close() the file descriptor is deferred until all of the locks clear.
39496** The unixInodeInfo structure keeps a list of file descriptors that need to
39497** be closed and that list is walked (and cleared) when the last lock
39498** clears.
39499**
39500** Yet another problem:  LinuxThreads do not play well with posix locks.
39501**
39502** Many older versions of linux use the LinuxThreads library which is
39503** not posix compliant.  Under LinuxThreads, a lock created by thread
39504** A cannot be modified or overridden by a different thread B.
39505** Only thread A can modify the lock.  Locking behavior is correct
39506** if the application uses the newer Native Posix Thread Library (NPTL)
39507** on linux - with NPTL a lock created by thread A can override locks
39508** in thread B.  But there is no way to know at compile-time which
39509** threading library is being used.  So there is no way to know at
39510** compile-time whether or not thread A can override locks on thread B.
39511** One has to do a run-time check to discover the behavior of the
39512** current process.
39513**
39514** SQLite used to support LinuxThreads.  But support for LinuxThreads
39515** was dropped beginning with version 3.7.0.  SQLite will still work with
39516** LinuxThreads provided that (1) there is no more than one connection
39517** per database file in the same process and (2) database connections
39518** do not move across threads.
39519*/
39520
39521/*
39522** An instance of the following structure serves as the key used
39523** to locate a particular unixInodeInfo object.
39524*/
39525struct unixFileId {
39526  dev_t dev;                  /* Device number */
39527#if OS_VXWORKS
39528  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
39529#else
39530  /* We are told that some versions of Android contain a bug that
39531  ** sizes ino_t at only 32-bits instead of 64-bits. (See
39532  ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
39533  ** To work around this, always allocate 64-bits for the inode number.
39534  ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
39535  ** but that should not be a big deal. */
39536  /* WAS:  ino_t ino;   */
39537  u64 ino;                   /* Inode number */
39538#endif
39539};
39540
39541/*
39542** An instance of the following structure is allocated for each open
39543** inode.
39544**
39545** A single inode can have multiple file descriptors, so each unixFile
39546** structure contains a pointer to an instance of this object and this
39547** object keeps a count of the number of unixFile pointing to it.
39548**
39549** Mutex rules:
39550**
39551**  (1) Only the pLockMutex mutex must be held in order to read or write
39552**      any of the locking fields:
39553**          nShared, nLock, eFileLock, bProcessLock, pUnused
39554**
39555**  (2) When nRef>0, then the following fields are unchanging and can
39556**      be read (but not written) without holding any mutex:
39557**          fileId, pLockMutex
39558**
39559**  (3) With the exceptions above, all the fields may only be read
39560**      or written while holding the global unixBigLock mutex.
39561**
39562** Deadlock prevention:  The global unixBigLock mutex may not
39563** be acquired while holding the pLockMutex mutex.  If both unixBigLock
39564** and pLockMutex are needed, then unixBigLock must be acquired first.
39565*/
39566struct unixInodeInfo {
39567  struct unixFileId fileId;       /* The lookup key */
39568  sqlite3_mutex *pLockMutex;      /* Hold this mutex for... */
39569  int nShared;                      /* Number of SHARED locks held */
39570  int nLock;                        /* Number of outstanding file locks */
39571  unsigned char eFileLock;          /* One of SHARED_LOCK, RESERVED_LOCK etc. */
39572  unsigned char bProcessLock;       /* An exclusive process lock is held */
39573  UnixUnusedFd *pUnused;            /* Unused file descriptors to close */
39574  int nRef;                       /* Number of pointers to this structure */
39575  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
39576  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
39577  unixInodeInfo *pPrev;           /*    .... doubly linked */
39578#if SQLITE_ENABLE_LOCKING_STYLE
39579  unsigned long long sharedByte;  /* for AFP simulated shared lock */
39580#endif
39581#if OS_VXWORKS
39582  sem_t *pSem;                    /* Named POSIX semaphore */
39583  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
39584#endif
39585};
39586
39587/*
39588** A lists of all unixInodeInfo objects.
39589**
39590** Must hold unixBigLock in order to read or write this variable.
39591*/
39592static unixInodeInfo *inodeList = 0;  /* All unixInodeInfo objects */
39593
39594#ifdef SQLITE_DEBUG
39595/*
39596** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
39597** This routine is used only within assert() to help verify correct mutex
39598** usage.
39599*/
39600int unixFileMutexHeld(unixFile *pFile){
39601  assert( pFile->pInode );
39602  return sqlite3_mutex_held(pFile->pInode->pLockMutex);
39603}
39604int unixFileMutexNotheld(unixFile *pFile){
39605  assert( pFile->pInode );
39606  return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
39607}
39608#endif
39609
39610/*
39611**
39612** This function - unixLogErrorAtLine(), is only ever called via the macro
39613** unixLogError().
39614**
39615** It is invoked after an error occurs in an OS function and errno has been
39616** set. It logs a message using sqlite3_log() containing the current value of
39617** errno and, if possible, the human-readable equivalent from strerror() or
39618** strerror_r().
39619**
39620** The first argument passed to the macro should be the error code that
39621** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
39622** The two subsequent arguments should be the name of the OS function that
39623** failed (e.g. "unlink", "open") and the associated file-system path,
39624** if any.
39625*/
39626#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
39627static int unixLogErrorAtLine(
39628  int errcode,                    /* SQLite error code */
39629  const char *zFunc,              /* Name of OS function that failed */
39630  const char *zPath,              /* File path associated with error */
39631  int iLine                       /* Source line number where error occurred */
39632){
39633  char *zErr;                     /* Message from strerror() or equivalent */
39634  int iErrno = errno;             /* Saved syscall error number */
39635
39636  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
39637  ** the strerror() function to obtain the human-readable error message
39638  ** equivalent to errno. Otherwise, use strerror_r().
39639  */
39640#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
39641  char aErr[80];
39642  memset(aErr, 0, sizeof(aErr));
39643  zErr = aErr;
39644
39645  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
39646  ** assume that the system provides the GNU version of strerror_r() that
39647  ** returns a pointer to a buffer containing the error message. That pointer
39648  ** may point to aErr[], or it may point to some static storage somewhere.
39649  ** Otherwise, assume that the system provides the POSIX version of
39650  ** strerror_r(), which always writes an error message into aErr[].
39651  **
39652  ** If the code incorrectly assumes that it is the POSIX version that is
39653  ** available, the error message will often be an empty string. Not a
39654  ** huge problem. Incorrectly concluding that the GNU version is available
39655  ** could lead to a segfault though.
39656  **
39657  ** Forum post 3f13857fa4062301 reports that the Android SDK may use
39658  ** int-type return, depending on its version.
39659  */
39660#if (defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)) \
39661  && !defined(ANDROID) && !defined(__ANDROID__)
39662  zErr =
39663# endif
39664  strerror_r(iErrno, aErr, sizeof(aErr)-1);
39665
39666#elif SQLITE_THREADSAFE
39667  /* This is a threadsafe build, but strerror_r() is not available. */
39668  zErr = "";
39669#else
39670  /* Non-threadsafe build, use strerror(). */
39671  zErr = strerror(iErrno);
39672#endif
39673
39674  if( zPath==0 ) zPath = "";
39675  sqlite3_log(errcode,
39676      "os_unix.c:%d: (%d) %s(%s) - %s",
39677      iLine, iErrno, zFunc, zPath, zErr
39678  );
39679
39680  return errcode;
39681}
39682
39683/*
39684** Close a file descriptor.
39685**
39686** We assume that close() almost always works, since it is only in a
39687** very sick application or on a very sick platform that it might fail.
39688** If it does fail, simply leak the file descriptor, but do log the
39689** error.
39690**
39691** Note that it is not safe to retry close() after EINTR since the
39692** file descriptor might have already been reused by another thread.
39693** So we don't even try to recover from an EINTR.  Just log the error
39694** and move on.
39695*/
39696static void robust_close(unixFile *pFile, int h, int lineno){
39697  if( osClose(h) ){
39698    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
39699                       pFile ? pFile->zPath : 0, lineno);
39700  }
39701}
39702
39703/*
39704** Set the pFile->lastErrno.  Do this in a subroutine as that provides
39705** a convenient place to set a breakpoint.
39706*/
39707static void storeLastErrno(unixFile *pFile, int error){
39708  pFile->lastErrno = error;
39709}
39710
39711/*
39712** Close all file descriptors accumulated in the unixInodeInfo->pUnused list.
39713*/
39714static void closePendingFds(unixFile *pFile){
39715  unixInodeInfo *pInode = pFile->pInode;
39716  UnixUnusedFd *p;
39717  UnixUnusedFd *pNext;
39718  assert( unixFileMutexHeld(pFile) );
39719  for(p=pInode->pUnused; p; p=pNext){
39720    pNext = p->pNext;
39721    robust_close(pFile, p->fd, __LINE__);
39722    sqlite3_free(p);
39723  }
39724  pInode->pUnused = 0;
39725}
39726
39727/*
39728** Release a unixInodeInfo structure previously allocated by findInodeInfo().
39729**
39730** The global mutex must be held when this routine is called, but the mutex
39731** on the inode being deleted must NOT be held.
39732*/
39733static void releaseInodeInfo(unixFile *pFile){
39734  unixInodeInfo *pInode = pFile->pInode;
39735  assert( unixMutexHeld() );
39736  assert( unixFileMutexNotheld(pFile) );
39737  if( ALWAYS(pInode) ){
39738    pInode->nRef--;
39739    if( pInode->nRef==0 ){
39740      assert( pInode->pShmNode==0 );
39741      sqlite3_mutex_enter(pInode->pLockMutex);
39742      closePendingFds(pFile);
39743      sqlite3_mutex_leave(pInode->pLockMutex);
39744      if( pInode->pPrev ){
39745        assert( pInode->pPrev->pNext==pInode );
39746        pInode->pPrev->pNext = pInode->pNext;
39747      }else{
39748        assert( inodeList==pInode );
39749        inodeList = pInode->pNext;
39750      }
39751      if( pInode->pNext ){
39752        assert( pInode->pNext->pPrev==pInode );
39753        pInode->pNext->pPrev = pInode->pPrev;
39754      }
39755      sqlite3_mutex_free(pInode->pLockMutex);
39756      sqlite3_free(pInode);
39757    }
39758  }
39759}
39760
39761/*
39762** Given a file descriptor, locate the unixInodeInfo object that
39763** describes that file descriptor.  Create a new one if necessary.  The
39764** return value might be uninitialized if an error occurs.
39765**
39766** The global mutex must held when calling this routine.
39767**
39768** Return an appropriate error code.
39769*/
39770static int findInodeInfo(
39771  unixFile *pFile,               /* Unix file with file desc used in the key */
39772  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
39773){
39774  int rc;                        /* System call return code */
39775  int fd;                        /* The file descriptor for pFile */
39776  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
39777  struct stat statbuf;           /* Low-level file information */
39778  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
39779
39780  assert( unixMutexHeld() );
39781
39782  /* Get low-level information about the file that we can used to
39783  ** create a unique name for the file.
39784  */
39785  fd = pFile->h;
39786  rc = osFstat(fd, &statbuf);
39787  if( rc!=0 ){
39788    storeLastErrno(pFile, errno);
39789#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
39790    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
39791#endif
39792    return SQLITE_IOERR;
39793  }
39794
39795#ifdef __APPLE__
39796  /* On OS X on an msdos filesystem, the inode number is reported
39797  ** incorrectly for zero-size files.  See ticket #3260.  To work
39798  ** around this problem (we consider it a bug in OS X, not SQLite)
39799  ** we always increase the file size to 1 by writing a single byte
39800  ** prior to accessing the inode number.  The one byte written is
39801  ** an ASCII 'S' character which also happens to be the first byte
39802  ** in the header of every SQLite database.  In this way, if there
39803  ** is a race condition such that another thread has already populated
39804  ** the first page of the database, no damage is done.
39805  */
39806  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
39807    do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
39808    if( rc!=1 ){
39809      storeLastErrno(pFile, errno);
39810      return SQLITE_IOERR;
39811    }
39812    rc = osFstat(fd, &statbuf);
39813    if( rc!=0 ){
39814      storeLastErrno(pFile, errno);
39815      return SQLITE_IOERR;
39816    }
39817  }
39818#endif
39819
39820  memset(&fileId, 0, sizeof(fileId));
39821  fileId.dev = statbuf.st_dev;
39822#if OS_VXWORKS
39823  fileId.pId = pFile->pId;
39824#else
39825  fileId.ino = (u64)statbuf.st_ino;
39826#endif
39827  assert( unixMutexHeld() );
39828  pInode = inodeList;
39829  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
39830    pInode = pInode->pNext;
39831  }
39832  if( pInode==0 ){
39833    pInode = sqlite3_malloc64( sizeof(*pInode) );
39834    if( pInode==0 ){
39835      return SQLITE_NOMEM_BKPT;
39836    }
39837    memset(pInode, 0, sizeof(*pInode));
39838    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
39839    if( sqlite3GlobalConfig.bCoreMutex ){
39840      pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
39841      if( pInode->pLockMutex==0 ){
39842        sqlite3_free(pInode);
39843        return SQLITE_NOMEM_BKPT;
39844      }
39845    }
39846    pInode->nRef = 1;
39847    assert( unixMutexHeld() );
39848    pInode->pNext = inodeList;
39849    pInode->pPrev = 0;
39850    if( inodeList ) inodeList->pPrev = pInode;
39851    inodeList = pInode;
39852  }else{
39853    pInode->nRef++;
39854  }
39855  *ppInode = pInode;
39856  return SQLITE_OK;
39857}
39858
39859/*
39860** Return TRUE if pFile has been renamed or unlinked since it was first opened.
39861*/
39862static int fileHasMoved(unixFile *pFile){
39863#if OS_VXWORKS
39864  return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
39865#else
39866  struct stat buf;
39867  return pFile->pInode!=0 &&
39868      (osStat(pFile->zPath, &buf)!=0
39869         || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
39870#endif
39871}
39872
39873
39874/*
39875** Check a unixFile that is a database.  Verify the following:
39876**
39877** (1) There is exactly one hard link on the file
39878** (2) The file is not a symbolic link
39879** (3) The file has not been renamed or unlinked
39880**
39881** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
39882*/
39883static void verifyDbFile(unixFile *pFile){
39884  struct stat buf;
39885  int rc;
39886
39887  /* These verifications occurs for the main database only */
39888  if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
39889
39890  rc = osFstat(pFile->h, &buf);
39891  if( rc!=0 ){
39892    sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
39893    return;
39894  }
39895  if( buf.st_nlink==0 ){
39896    sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
39897    return;
39898  }
39899  if( buf.st_nlink>1 ){
39900    sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
39901    return;
39902  }
39903  if( fileHasMoved(pFile) ){
39904    sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
39905    return;
39906  }
39907}
39908
39909
39910/*
39911** This routine checks if there is a RESERVED lock held on the specified
39912** file by this or any other process. If such a lock is held, set *pResOut
39913** to a non-zero value otherwise *pResOut is set to zero.  The return value
39914** is set to SQLITE_OK unless an I/O error occurs during lock checking.
39915*/
39916static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
39917  int rc = SQLITE_OK;
39918  int reserved = 0;
39919  unixFile *pFile = (unixFile*)id;
39920
39921  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
39922
39923  assert( pFile );
39924  assert( pFile->eFileLock<=SHARED_LOCK );
39925  sqlite3_mutex_enter(pFile->pInode->pLockMutex);
39926
39927  /* Check if a thread in this process holds such a lock */
39928  if( pFile->pInode->eFileLock>SHARED_LOCK ){
39929    reserved = 1;
39930  }
39931
39932  /* Otherwise see if some other process holds it.
39933  */
39934#ifndef __DJGPP__
39935  if( !reserved && !pFile->pInode->bProcessLock ){
39936    struct flock lock;
39937    lock.l_whence = SEEK_SET;
39938    lock.l_start = RESERVED_BYTE;
39939    lock.l_len = 1;
39940    lock.l_type = F_WRLCK;
39941    if( osFcntl(pFile->h, F_GETLK, &lock) ){
39942      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
39943      storeLastErrno(pFile, errno);
39944    } else if( lock.l_type!=F_UNLCK ){
39945      reserved = 1;
39946    }
39947  }
39948#endif
39949
39950  sqlite3_mutex_leave(pFile->pInode->pLockMutex);
39951  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
39952
39953  *pResOut = reserved;
39954  return rc;
39955}
39956
39957/* Forward declaration*/
39958static int unixSleep(sqlite3_vfs*,int);
39959
39960/*
39961** Set a posix-advisory-lock.
39962**
39963** There are two versions of this routine.  If compiled with
39964** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
39965** which is a pointer to a unixFile.  If the unixFile->iBusyTimeout
39966** value is set, then it is the number of milliseconds to wait before
39967** failing the lock.  The iBusyTimeout value is always reset back to
39968** zero on each call.
39969**
39970** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
39971** attempt to set the lock.
39972*/
39973#ifndef SQLITE_ENABLE_SETLK_TIMEOUT
39974# define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
39975#else
39976static int osSetPosixAdvisoryLock(
39977  int h,                /* The file descriptor on which to take the lock */
39978  struct flock *pLock,  /* The description of the lock */
39979  unixFile *pFile       /* Structure holding timeout value */
39980){
39981  int tm = pFile->iBusyTimeout;
39982  int rc = osFcntl(h,F_SETLK,pLock);
39983  while( rc<0 && tm>0 ){
39984    /* On systems that support some kind of blocking file lock with a timeout,
39985    ** make appropriate changes here to invoke that blocking file lock.  On
39986    ** generic posix, however, there is no such API.  So we simply try the
39987    ** lock once every millisecond until either the timeout expires, or until
39988    ** the lock is obtained. */
39989    unixSleep(0,1000);
39990    rc = osFcntl(h,F_SETLK,pLock);
39991    tm--;
39992  }
39993  return rc;
39994}
39995#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
39996
39997
39998/*
39999** Attempt to set a system-lock on the file pFile.  The lock is
40000** described by pLock.
40001**
40002** If the pFile was opened read/write from unix-excl, then the only lock
40003** ever obtained is an exclusive lock, and it is obtained exactly once
40004** the first time any lock is attempted.  All subsequent system locking
40005** operations become no-ops.  Locking operations still happen internally,
40006** in order to coordinate access between separate database connections
40007** within this process, but all of that is handled in memory and the
40008** operating system does not participate.
40009**
40010** This function is a pass-through to fcntl(F_SETLK) if pFile is using
40011** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
40012** and is read-only.
40013**
40014** Zero is returned if the call completes successfully, or -1 if a call
40015** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
40016*/
40017static int unixFileLock(unixFile *pFile, struct flock *pLock){
40018  int rc;
40019  unixInodeInfo *pInode = pFile->pInode;
40020  assert( pInode!=0 );
40021  assert( sqlite3_mutex_held(pInode->pLockMutex) );
40022  if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
40023    if( pInode->bProcessLock==0 ){
40024      struct flock lock;
40025      assert( pInode->nLock==0 );
40026      lock.l_whence = SEEK_SET;
40027      lock.l_start = SHARED_FIRST;
40028      lock.l_len = SHARED_SIZE;
40029      lock.l_type = F_WRLCK;
40030      rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
40031      if( rc<0 ) return rc;
40032      pInode->bProcessLock = 1;
40033      pInode->nLock++;
40034    }else{
40035      rc = 0;
40036    }
40037  }else{
40038    rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
40039  }
40040  return rc;
40041}
40042
40043/*
40044** Lock the file with the lock specified by parameter eFileLock - one
40045** of the following:
40046**
40047**     (1) SHARED_LOCK
40048**     (2) RESERVED_LOCK
40049**     (3) PENDING_LOCK
40050**     (4) EXCLUSIVE_LOCK
40051**
40052** Sometimes when requesting one lock state, additional lock states
40053** are inserted in between.  The locking might fail on one of the later
40054** transitions leaving the lock state different from what it started but
40055** still short of its goal.  The following chart shows the allowed
40056** transitions and the inserted intermediate states:
40057**
40058**    UNLOCKED -> SHARED
40059**    SHARED -> RESERVED
40060**    SHARED -> EXCLUSIVE
40061**    RESERVED -> (PENDING) -> EXCLUSIVE
40062**    PENDING -> EXCLUSIVE
40063**
40064** This routine will only increase a lock.  Use the sqlite3OsUnlock()
40065** routine to lower a locking level.
40066*/
40067static int unixLock(sqlite3_file *id, int eFileLock){
40068  /* The following describes the implementation of the various locks and
40069  ** lock transitions in terms of the POSIX advisory shared and exclusive
40070  ** lock primitives (called read-locks and write-locks below, to avoid
40071  ** confusion with SQLite lock names). The algorithms are complicated
40072  ** slightly in order to be compatible with Windows95 systems simultaneously
40073  ** accessing the same database file, in case that is ever required.
40074  **
40075  ** Symbols defined in os.h identify the 'pending byte' and the 'reserved
40076  ** byte', each single bytes at well known offsets, and the 'shared byte
40077  ** range', a range of 510 bytes at a well known offset.
40078  **
40079  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
40080  ** byte'.  If this is successful, 'shared byte range' is read-locked
40081  ** and the lock on the 'pending byte' released.  (Legacy note:  When
40082  ** SQLite was first developed, Windows95 systems were still very common,
40083  ** and Windows95 lacks a shared-lock capability.  So on Windows95, a
40084  ** single randomly selected by from the 'shared byte range' is locked.
40085  ** Windows95 is now pretty much extinct, but this work-around for the
40086  ** lack of shared-locks on Windows95 lives on, for backwards
40087  ** compatibility.)
40088  **
40089  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
40090  ** A RESERVED lock is implemented by grabbing a write-lock on the
40091  ** 'reserved byte'.
40092  **
40093  ** An EXCLUSIVE lock may only be requested after either a SHARED or
40094  ** RESERVED lock is held. An EXCLUSIVE lock is implemented by obtaining
40095  ** a write-lock on the entire 'shared byte range'. Since all other locks
40096  ** require a read-lock on one of the bytes within this range, this ensures
40097  ** that no other locks are held on the database.
40098  **
40099  ** If a process that holds a RESERVED lock requests an EXCLUSIVE, then
40100  ** a PENDING lock is obtained first. A PENDING lock is implemented by
40101  ** obtaining a write-lock on the 'pending byte'. This ensures that no new
40102  ** SHARED locks can be obtained, but existing SHARED locks are allowed to
40103  ** persist. If the call to this function fails to obtain the EXCLUSIVE
40104  ** lock in this case, it holds the PENDING lock instead. The client may
40105  ** then re-attempt the EXCLUSIVE lock later on, after existing SHARED
40106  ** locks have cleared.
40107  */
40108  int rc = SQLITE_OK;
40109  unixFile *pFile = (unixFile*)id;
40110  unixInodeInfo *pInode;
40111  struct flock lock;
40112  int tErrno = 0;
40113
40114  assert( pFile );
40115  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
40116      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
40117      azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
40118      osGetpid(0)));
40119
40120  /* If there is already a lock of this type or more restrictive on the
40121  ** unixFile, do nothing. Don't use the end_lock: exit path, as
40122  ** unixEnterMutex() hasn't been called yet.
40123  */
40124  if( pFile->eFileLock>=eFileLock ){
40125    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
40126            azFileLock(eFileLock)));
40127    return SQLITE_OK;
40128  }
40129
40130  /* Make sure the locking sequence is correct.
40131  **  (1) We never move from unlocked to anything higher than shared lock.
40132  **  (2) SQLite never explicitly requests a pending lock.
40133  **  (3) A shared lock is always held when a reserve lock is requested.
40134  */
40135  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
40136  assert( eFileLock!=PENDING_LOCK );
40137  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
40138
40139  /* This mutex is needed because pFile->pInode is shared across threads
40140  */
40141  pInode = pFile->pInode;
40142  sqlite3_mutex_enter(pInode->pLockMutex);
40143
40144  /* If some thread using this PID has a lock via a different unixFile*
40145  ** handle that precludes the requested lock, return BUSY.
40146  */
40147  if( (pFile->eFileLock!=pInode->eFileLock &&
40148          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
40149  ){
40150    rc = SQLITE_BUSY;
40151    goto end_lock;
40152  }
40153
40154  /* If a SHARED lock is requested, and some thread using this PID already
40155  ** has a SHARED or RESERVED lock, then increment reference counts and
40156  ** return SQLITE_OK.
40157  */
40158  if( eFileLock==SHARED_LOCK &&
40159      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
40160    assert( eFileLock==SHARED_LOCK );
40161    assert( pFile->eFileLock==0 );
40162    assert( pInode->nShared>0 );
40163    pFile->eFileLock = SHARED_LOCK;
40164    pInode->nShared++;
40165    pInode->nLock++;
40166    goto end_lock;
40167  }
40168
40169
40170  /* A PENDING lock is needed before acquiring a SHARED lock and before
40171  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
40172  ** be released.
40173  */
40174  lock.l_len = 1L;
40175  lock.l_whence = SEEK_SET;
40176  if( eFileLock==SHARED_LOCK
40177   || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock==RESERVED_LOCK)
40178  ){
40179    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
40180    lock.l_start = PENDING_BYTE;
40181    if( unixFileLock(pFile, &lock) ){
40182      tErrno = errno;
40183      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
40184      if( rc!=SQLITE_BUSY ){
40185        storeLastErrno(pFile, tErrno);
40186      }
40187      goto end_lock;
40188    }else if( eFileLock==EXCLUSIVE_LOCK ){
40189      pFile->eFileLock = PENDING_LOCK;
40190      pInode->eFileLock = PENDING_LOCK;
40191    }
40192  }
40193
40194
40195  /* If control gets to this point, then actually go ahead and make
40196  ** operating system calls for the specified lock.
40197  */
40198  if( eFileLock==SHARED_LOCK ){
40199    assert( pInode->nShared==0 );
40200    assert( pInode->eFileLock==0 );
40201    assert( rc==SQLITE_OK );
40202
40203    /* Now get the read-lock */
40204    lock.l_start = SHARED_FIRST;
40205    lock.l_len = SHARED_SIZE;
40206    if( unixFileLock(pFile, &lock) ){
40207      tErrno = errno;
40208      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
40209    }
40210
40211    /* Drop the temporary PENDING lock */
40212    lock.l_start = PENDING_BYTE;
40213    lock.l_len = 1L;
40214    lock.l_type = F_UNLCK;
40215    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
40216      /* This could happen with a network mount */
40217      tErrno = errno;
40218      rc = SQLITE_IOERR_UNLOCK;
40219    }
40220
40221    if( rc ){
40222      if( rc!=SQLITE_BUSY ){
40223        storeLastErrno(pFile, tErrno);
40224      }
40225      goto end_lock;
40226    }else{
40227      pFile->eFileLock = SHARED_LOCK;
40228      pInode->nLock++;
40229      pInode->nShared = 1;
40230    }
40231  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
40232    /* We are trying for an exclusive lock but another thread in this
40233    ** same process is still holding a shared lock. */
40234    rc = SQLITE_BUSY;
40235  }else{
40236    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
40237    ** assumed that there is a SHARED or greater lock on the file
40238    ** already.
40239    */
40240    assert( 0!=pFile->eFileLock );
40241    lock.l_type = F_WRLCK;
40242
40243    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
40244    if( eFileLock==RESERVED_LOCK ){
40245      lock.l_start = RESERVED_BYTE;
40246      lock.l_len = 1L;
40247    }else{
40248      lock.l_start = SHARED_FIRST;
40249      lock.l_len = SHARED_SIZE;
40250    }
40251
40252    if( unixFileLock(pFile, &lock) ){
40253      tErrno = errno;
40254      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
40255      if( rc!=SQLITE_BUSY ){
40256        storeLastErrno(pFile, tErrno);
40257      }
40258    }
40259  }
40260
40261
40262#ifdef SQLITE_DEBUG
40263  /* Set up the transaction-counter change checking flags when
40264  ** transitioning from a SHARED to a RESERVED lock.  The change
40265  ** from SHARED to RESERVED marks the beginning of a normal
40266  ** write operation (not a hot journal rollback).
40267  */
40268  if( rc==SQLITE_OK
40269   && pFile->eFileLock<=SHARED_LOCK
40270   && eFileLock==RESERVED_LOCK
40271  ){
40272    pFile->transCntrChng = 0;
40273    pFile->dbUpdate = 0;
40274    pFile->inNormalWrite = 1;
40275  }
40276#endif
40277
40278  if( rc==SQLITE_OK ){
40279    pFile->eFileLock = eFileLock;
40280    pInode->eFileLock = eFileLock;
40281  }
40282
40283end_lock:
40284  sqlite3_mutex_leave(pInode->pLockMutex);
40285  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
40286      rc==SQLITE_OK ? "ok" : "failed"));
40287  return rc;
40288}
40289
40290/*
40291** Add the file descriptor used by file handle pFile to the corresponding
40292** pUnused list.
40293*/
40294static void setPendingFd(unixFile *pFile){
40295  unixInodeInfo *pInode = pFile->pInode;
40296  UnixUnusedFd *p = pFile->pPreallocatedUnused;
40297  assert( unixFileMutexHeld(pFile) );
40298  p->pNext = pInode->pUnused;
40299  pInode->pUnused = p;
40300  pFile->h = -1;
40301  pFile->pPreallocatedUnused = 0;
40302}
40303
40304/*
40305** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
40306** must be either NO_LOCK or SHARED_LOCK.
40307**
40308** If the locking level of the file descriptor is already at or below
40309** the requested locking level, this routine is a no-op.
40310**
40311** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
40312** the byte range is divided into 2 parts and the first part is unlocked then
40313** set to a read lock, then the other part is simply unlocked.  This works
40314** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
40315** remove the write lock on a region when a read lock is set.
40316*/
40317static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
40318  unixFile *pFile = (unixFile*)id;
40319  unixInodeInfo *pInode;
40320  struct flock lock;
40321  int rc = SQLITE_OK;
40322
40323  assert( pFile );
40324  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
40325      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
40326      osGetpid(0)));
40327
40328  assert( eFileLock<=SHARED_LOCK );
40329  if( pFile->eFileLock<=eFileLock ){
40330    return SQLITE_OK;
40331  }
40332  pInode = pFile->pInode;
40333  sqlite3_mutex_enter(pInode->pLockMutex);
40334  assert( pInode->nShared!=0 );
40335  if( pFile->eFileLock>SHARED_LOCK ){
40336    assert( pInode->eFileLock==pFile->eFileLock );
40337
40338#ifdef SQLITE_DEBUG
40339    /* When reducing a lock such that other processes can start
40340    ** reading the database file again, make sure that the
40341    ** transaction counter was updated if any part of the database
40342    ** file changed.  If the transaction counter is not updated,
40343    ** other connections to the same file might not realize that
40344    ** the file has changed and hence might not know to flush their
40345    ** cache.  The use of a stale cache can lead to database corruption.
40346    */
40347    pFile->inNormalWrite = 0;
40348#endif
40349
40350    /* downgrading to a shared lock on NFS involves clearing the write lock
40351    ** before establishing the readlock - to avoid a race condition we downgrade
40352    ** the lock in 2 blocks, so that part of the range will be covered by a
40353    ** write lock until the rest is covered by a read lock:
40354    **  1:   [WWWWW]
40355    **  2:   [....W]
40356    **  3:   [RRRRW]
40357    **  4:   [RRRR.]
40358    */
40359    if( eFileLock==SHARED_LOCK ){
40360#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
40361      (void)handleNFSUnlock;
40362      assert( handleNFSUnlock==0 );
40363#endif
40364#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
40365      if( handleNFSUnlock ){
40366        int tErrno;               /* Error code from system call errors */
40367        off_t divSize = SHARED_SIZE - 1;
40368
40369        lock.l_type = F_UNLCK;
40370        lock.l_whence = SEEK_SET;
40371        lock.l_start = SHARED_FIRST;
40372        lock.l_len = divSize;
40373        if( unixFileLock(pFile, &lock)==(-1) ){
40374          tErrno = errno;
40375          rc = SQLITE_IOERR_UNLOCK;
40376          storeLastErrno(pFile, tErrno);
40377          goto end_unlock;
40378        }
40379        lock.l_type = F_RDLCK;
40380        lock.l_whence = SEEK_SET;
40381        lock.l_start = SHARED_FIRST;
40382        lock.l_len = divSize;
40383        if( unixFileLock(pFile, &lock)==(-1) ){
40384          tErrno = errno;
40385          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
40386          if( IS_LOCK_ERROR(rc) ){
40387            storeLastErrno(pFile, tErrno);
40388          }
40389          goto end_unlock;
40390        }
40391        lock.l_type = F_UNLCK;
40392        lock.l_whence = SEEK_SET;
40393        lock.l_start = SHARED_FIRST+divSize;
40394        lock.l_len = SHARED_SIZE-divSize;
40395        if( unixFileLock(pFile, &lock)==(-1) ){
40396          tErrno = errno;
40397          rc = SQLITE_IOERR_UNLOCK;
40398          storeLastErrno(pFile, tErrno);
40399          goto end_unlock;
40400        }
40401      }else
40402#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
40403      {
40404        lock.l_type = F_RDLCK;
40405        lock.l_whence = SEEK_SET;
40406        lock.l_start = SHARED_FIRST;
40407        lock.l_len = SHARED_SIZE;
40408        if( unixFileLock(pFile, &lock) ){
40409          /* In theory, the call to unixFileLock() cannot fail because another
40410          ** process is holding an incompatible lock. If it does, this
40411          ** indicates that the other process is not following the locking
40412          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
40413          ** SQLITE_BUSY would confuse the upper layer (in practice it causes
40414          ** an assert to fail). */
40415          rc = SQLITE_IOERR_RDLOCK;
40416          storeLastErrno(pFile, errno);
40417          goto end_unlock;
40418        }
40419      }
40420    }
40421    lock.l_type = F_UNLCK;
40422    lock.l_whence = SEEK_SET;
40423    lock.l_start = PENDING_BYTE;
40424    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
40425    if( unixFileLock(pFile, &lock)==0 ){
40426      pInode->eFileLock = SHARED_LOCK;
40427    }else{
40428      rc = SQLITE_IOERR_UNLOCK;
40429      storeLastErrno(pFile, errno);
40430      goto end_unlock;
40431    }
40432  }
40433  if( eFileLock==NO_LOCK ){
40434    /* Decrement the shared lock counter.  Release the lock using an
40435    ** OS call only when all threads in this same process have released
40436    ** the lock.
40437    */
40438    pInode->nShared--;
40439    if( pInode->nShared==0 ){
40440      lock.l_type = F_UNLCK;
40441      lock.l_whence = SEEK_SET;
40442      lock.l_start = lock.l_len = 0L;
40443      if( unixFileLock(pFile, &lock)==0 ){
40444        pInode->eFileLock = NO_LOCK;
40445      }else{
40446        rc = SQLITE_IOERR_UNLOCK;
40447        storeLastErrno(pFile, errno);
40448        pInode->eFileLock = NO_LOCK;
40449        pFile->eFileLock = NO_LOCK;
40450      }
40451    }
40452
40453    /* Decrement the count of locks against this same file.  When the
40454    ** count reaches zero, close any other file descriptors whose close
40455    ** was deferred because of outstanding locks.
40456    */
40457    pInode->nLock--;
40458    assert( pInode->nLock>=0 );
40459    if( pInode->nLock==0 ) closePendingFds(pFile);
40460  }
40461
40462end_unlock:
40463  sqlite3_mutex_leave(pInode->pLockMutex);
40464  if( rc==SQLITE_OK ){
40465    pFile->eFileLock = eFileLock;
40466  }
40467  return rc;
40468}
40469
40470/*
40471** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
40472** must be either NO_LOCK or SHARED_LOCK.
40473**
40474** If the locking level of the file descriptor is already at or below
40475** the requested locking level, this routine is a no-op.
40476*/
40477static int unixUnlock(sqlite3_file *id, int eFileLock){
40478#if SQLITE_MAX_MMAP_SIZE>0
40479  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
40480#endif
40481  return posixUnlock(id, eFileLock, 0);
40482}
40483
40484#if SQLITE_MAX_MMAP_SIZE>0
40485static int unixMapfile(unixFile *pFd, i64 nByte);
40486static void unixUnmapfile(unixFile *pFd);
40487#endif
40488
40489/*
40490** This function performs the parts of the "close file" operation
40491** common to all locking schemes. It closes the directory and file
40492** handles, if they are valid, and sets all fields of the unixFile
40493** structure to 0.
40494**
40495** It is *not* necessary to hold the mutex when this routine is called,
40496** even on VxWorks.  A mutex will be acquired on VxWorks by the
40497** vxworksReleaseFileId() routine.
40498*/
40499static int closeUnixFile(sqlite3_file *id){
40500  unixFile *pFile = (unixFile*)id;
40501#if SQLITE_MAX_MMAP_SIZE>0
40502  unixUnmapfile(pFile);
40503#endif
40504  if( pFile->h>=0 ){
40505    robust_close(pFile, pFile->h, __LINE__);
40506    pFile->h = -1;
40507  }
40508#if OS_VXWORKS
40509  if( pFile->pId ){
40510    if( pFile->ctrlFlags & UNIXFILE_DELETE ){
40511      osUnlink(pFile->pId->zCanonicalName);
40512    }
40513    vxworksReleaseFileId(pFile->pId);
40514    pFile->pId = 0;
40515  }
40516#endif
40517#ifdef SQLITE_UNLINK_AFTER_CLOSE
40518  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
40519    osUnlink(pFile->zPath);
40520    sqlite3_free(*(char**)&pFile->zPath);
40521    pFile->zPath = 0;
40522  }
40523#endif
40524  OSTRACE(("CLOSE   %-3d\n", pFile->h));
40525  OpenCounter(-1);
40526  sqlite3_free(pFile->pPreallocatedUnused);
40527  memset(pFile, 0, sizeof(unixFile));
40528  return SQLITE_OK;
40529}
40530
40531/*
40532** Close a file.
40533*/
40534static int unixClose(sqlite3_file *id){
40535  int rc = SQLITE_OK;
40536  unixFile *pFile = (unixFile *)id;
40537  unixInodeInfo *pInode = pFile->pInode;
40538
40539  assert( pInode!=0 );
40540  verifyDbFile(pFile);
40541  unixUnlock(id, NO_LOCK);
40542  assert( unixFileMutexNotheld(pFile) );
40543  unixEnterMutex();
40544
40545  /* unixFile.pInode is always valid here. Otherwise, a different close
40546  ** routine (e.g. nolockClose()) would be called instead.
40547  */
40548  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
40549  sqlite3_mutex_enter(pInode->pLockMutex);
40550  if( pInode->nLock ){
40551    /* If there are outstanding locks, do not actually close the file just
40552    ** yet because that would clear those locks.  Instead, add the file
40553    ** descriptor to pInode->pUnused list.  It will be automatically closed
40554    ** when the last lock is cleared.
40555    */
40556    setPendingFd(pFile);
40557  }
40558  sqlite3_mutex_leave(pInode->pLockMutex);
40559  releaseInodeInfo(pFile);
40560  assert( pFile->pShm==0 );
40561  rc = closeUnixFile(id);
40562  unixLeaveMutex();
40563  return rc;
40564}
40565
40566/************** End of the posix advisory lock implementation *****************
40567******************************************************************************/
40568
40569/******************************************************************************
40570****************************** No-op Locking **********************************
40571**
40572** Of the various locking implementations available, this is by far the
40573** simplest:  locking is ignored.  No attempt is made to lock the database
40574** file for reading or writing.
40575**
40576** This locking mode is appropriate for use on read-only databases
40577** (ex: databases that are burned into CD-ROM, for example.)  It can
40578** also be used if the application employs some external mechanism to
40579** prevent simultaneous access of the same database by two or more
40580** database connections.  But there is a serious risk of database
40581** corruption if this locking mode is used in situations where multiple
40582** database connections are accessing the same database file at the same
40583** time and one or more of those connections are writing.
40584*/
40585
40586static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
40587  UNUSED_PARAMETER(NotUsed);
40588  *pResOut = 0;
40589  return SQLITE_OK;
40590}
40591static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
40592  UNUSED_PARAMETER2(NotUsed, NotUsed2);
40593  return SQLITE_OK;
40594}
40595static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
40596  UNUSED_PARAMETER2(NotUsed, NotUsed2);
40597  return SQLITE_OK;
40598}
40599
40600/*
40601** Close the file.
40602*/
40603static int nolockClose(sqlite3_file *id) {
40604  return closeUnixFile(id);
40605}
40606
40607/******************* End of the no-op lock implementation *********************
40608******************************************************************************/
40609
40610/******************************************************************************
40611************************* Begin dot-file Locking ******************************
40612**
40613** The dotfile locking implementation uses the existence of separate lock
40614** files (really a directory) to control access to the database.  This works
40615** on just about every filesystem imaginable.  But there are serious downsides:
40616**
40617**    (1)  There is zero concurrency.  A single reader blocks all other
40618**         connections from reading or writing the database.
40619**
40620**    (2)  An application crash or power loss can leave stale lock files
40621**         sitting around that need to be cleared manually.
40622**
40623** Nevertheless, a dotlock is an appropriate locking mode for use if no
40624** other locking strategy is available.
40625**
40626** Dotfile locking works by creating a subdirectory in the same directory as
40627** the database and with the same name but with a ".lock" extension added.
40628** The existence of a lock directory implies an EXCLUSIVE lock.  All other
40629** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
40630*/
40631
40632/*
40633** The file suffix added to the data base filename in order to create the
40634** lock directory.
40635*/
40636#define DOTLOCK_SUFFIX ".lock"
40637
40638/*
40639** This routine checks if there is a RESERVED lock held on the specified
40640** file by this or any other process. If such a lock is held, set *pResOut
40641** to a non-zero value otherwise *pResOut is set to zero.  The return value
40642** is set to SQLITE_OK unless an I/O error occurs during lock checking.
40643**
40644** In dotfile locking, either a lock exists or it does not.  So in this
40645** variation of CheckReservedLock(), *pResOut is set to true if any lock
40646** is held on the file and false if the file is unlocked.
40647*/
40648static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
40649  int rc = SQLITE_OK;
40650  int reserved = 0;
40651  unixFile *pFile = (unixFile*)id;
40652
40653  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
40654
40655  assert( pFile );
40656  reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
40657  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
40658  *pResOut = reserved;
40659  return rc;
40660}
40661
40662/*
40663** Lock the file with the lock specified by parameter eFileLock - one
40664** of the following:
40665**
40666**     (1) SHARED_LOCK
40667**     (2) RESERVED_LOCK
40668**     (3) PENDING_LOCK
40669**     (4) EXCLUSIVE_LOCK
40670**
40671** Sometimes when requesting one lock state, additional lock states
40672** are inserted in between.  The locking might fail on one of the later
40673** transitions leaving the lock state different from what it started but
40674** still short of its goal.  The following chart shows the allowed
40675** transitions and the inserted intermediate states:
40676**
40677**    UNLOCKED -> SHARED
40678**    SHARED -> RESERVED
40679**    SHARED -> (PENDING) -> EXCLUSIVE
40680**    RESERVED -> (PENDING) -> EXCLUSIVE
40681**    PENDING -> EXCLUSIVE
40682**
40683** This routine will only increase a lock.  Use the sqlite3OsUnlock()
40684** routine to lower a locking level.
40685**
40686** With dotfile locking, we really only support state (4): EXCLUSIVE.
40687** But we track the other locking levels internally.
40688*/
40689static int dotlockLock(sqlite3_file *id, int eFileLock) {
40690  unixFile *pFile = (unixFile*)id;
40691  char *zLockFile = (char *)pFile->lockingContext;
40692  int rc = SQLITE_OK;
40693
40694
40695  /* If we have any lock, then the lock file already exists.  All we have
40696  ** to do is adjust our internal record of the lock level.
40697  */
40698  if( pFile->eFileLock > NO_LOCK ){
40699    pFile->eFileLock = eFileLock;
40700    /* Always update the timestamp on the old file */
40701#ifdef HAVE_UTIME
40702    utime(zLockFile, NULL);
40703#else
40704    utimes(zLockFile, NULL);
40705#endif
40706    return SQLITE_OK;
40707  }
40708
40709  /* grab an exclusive lock */
40710  rc = osMkdir(zLockFile, 0777);
40711  if( rc<0 ){
40712    /* failed to open/create the lock directory */
40713    int tErrno = errno;
40714    if( EEXIST == tErrno ){
40715      rc = SQLITE_BUSY;
40716    } else {
40717      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
40718      if( rc!=SQLITE_BUSY ){
40719        storeLastErrno(pFile, tErrno);
40720      }
40721    }
40722    return rc;
40723  }
40724
40725  /* got it, set the type and return ok */
40726  pFile->eFileLock = eFileLock;
40727  return rc;
40728}
40729
40730/*
40731** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
40732** must be either NO_LOCK or SHARED_LOCK.
40733**
40734** If the locking level of the file descriptor is already at or below
40735** the requested locking level, this routine is a no-op.
40736**
40737** When the locking level reaches NO_LOCK, delete the lock file.
40738*/
40739static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
40740  unixFile *pFile = (unixFile*)id;
40741  char *zLockFile = (char *)pFile->lockingContext;
40742  int rc;
40743
40744  assert( pFile );
40745  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
40746           pFile->eFileLock, osGetpid(0)));
40747  assert( eFileLock<=SHARED_LOCK );
40748
40749  /* no-op if possible */
40750  if( pFile->eFileLock==eFileLock ){
40751    return SQLITE_OK;
40752  }
40753
40754  /* To downgrade to shared, simply update our internal notion of the
40755  ** lock state.  No need to mess with the file on disk.
40756  */
40757  if( eFileLock==SHARED_LOCK ){
40758    pFile->eFileLock = SHARED_LOCK;
40759    return SQLITE_OK;
40760  }
40761
40762  /* To fully unlock the database, delete the lock file */
40763  assert( eFileLock==NO_LOCK );
40764  rc = osRmdir(zLockFile);
40765  if( rc<0 ){
40766    int tErrno = errno;
40767    if( tErrno==ENOENT ){
40768      rc = SQLITE_OK;
40769    }else{
40770      rc = SQLITE_IOERR_UNLOCK;
40771      storeLastErrno(pFile, tErrno);
40772    }
40773    return rc;
40774  }
40775  pFile->eFileLock = NO_LOCK;
40776  return SQLITE_OK;
40777}
40778
40779/*
40780** Close a file.  Make sure the lock has been released before closing.
40781*/
40782static int dotlockClose(sqlite3_file *id) {
40783  unixFile *pFile = (unixFile*)id;
40784  assert( id!=0 );
40785  dotlockUnlock(id, NO_LOCK);
40786  sqlite3_free(pFile->lockingContext);
40787  return closeUnixFile(id);
40788}
40789/****************** End of the dot-file lock implementation *******************
40790******************************************************************************/
40791
40792/******************************************************************************
40793************************** Begin flock Locking ********************************
40794**
40795** Use the flock() system call to do file locking.
40796**
40797** flock() locking is like dot-file locking in that the various
40798** fine-grain locking levels supported by SQLite are collapsed into
40799** a single exclusive lock.  In other words, SHARED, RESERVED, and
40800** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
40801** still works when you do this, but concurrency is reduced since
40802** only a single process can be reading the database at a time.
40803**
40804** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
40805*/
40806#if SQLITE_ENABLE_LOCKING_STYLE
40807
40808/*
40809** Retry flock() calls that fail with EINTR
40810*/
40811#ifdef EINTR
40812static int robust_flock(int fd, int op){
40813  int rc;
40814  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
40815  return rc;
40816}
40817#else
40818# define robust_flock(a,b) flock(a,b)
40819#endif
40820
40821
40822/*
40823** This routine checks if there is a RESERVED lock held on the specified
40824** file by this or any other process. If such a lock is held, set *pResOut
40825** to a non-zero value otherwise *pResOut is set to zero.  The return value
40826** is set to SQLITE_OK unless an I/O error occurs during lock checking.
40827*/
40828static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
40829  int rc = SQLITE_OK;
40830  int reserved = 0;
40831  unixFile *pFile = (unixFile*)id;
40832
40833  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
40834
40835  assert( pFile );
40836
40837  /* Check if a thread in this process holds such a lock */
40838  if( pFile->eFileLock>SHARED_LOCK ){
40839    reserved = 1;
40840  }
40841
40842  /* Otherwise see if some other process holds it. */
40843  if( !reserved ){
40844    /* attempt to get the lock */
40845    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
40846    if( !lrc ){
40847      /* got the lock, unlock it */
40848      lrc = robust_flock(pFile->h, LOCK_UN);
40849      if ( lrc ) {
40850        int tErrno = errno;
40851        /* unlock failed with an error */
40852        lrc = SQLITE_IOERR_UNLOCK;
40853        storeLastErrno(pFile, tErrno);
40854        rc = lrc;
40855      }
40856    } else {
40857      int tErrno = errno;
40858      reserved = 1;
40859      /* someone else might have it reserved */
40860      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
40861      if( IS_LOCK_ERROR(lrc) ){
40862        storeLastErrno(pFile, tErrno);
40863        rc = lrc;
40864      }
40865    }
40866  }
40867  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
40868
40869#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
40870  if( (rc & 0xff) == SQLITE_IOERR ){
40871    rc = SQLITE_OK;
40872    reserved=1;
40873  }
40874#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
40875  *pResOut = reserved;
40876  return rc;
40877}
40878
40879/*
40880** Lock the file with the lock specified by parameter eFileLock - one
40881** of the following:
40882**
40883**     (1) SHARED_LOCK
40884**     (2) RESERVED_LOCK
40885**     (3) PENDING_LOCK
40886**     (4) EXCLUSIVE_LOCK
40887**
40888** Sometimes when requesting one lock state, additional lock states
40889** are inserted in between.  The locking might fail on one of the later
40890** transitions leaving the lock state different from what it started but
40891** still short of its goal.  The following chart shows the allowed
40892** transitions and the inserted intermediate states:
40893**
40894**    UNLOCKED -> SHARED
40895**    SHARED -> RESERVED
40896**    SHARED -> (PENDING) -> EXCLUSIVE
40897**    RESERVED -> (PENDING) -> EXCLUSIVE
40898**    PENDING -> EXCLUSIVE
40899**
40900** flock() only really support EXCLUSIVE locks.  We track intermediate
40901** lock states in the sqlite3_file structure, but all locks SHARED or
40902** above are really EXCLUSIVE locks and exclude all other processes from
40903** access the file.
40904**
40905** This routine will only increase a lock.  Use the sqlite3OsUnlock()
40906** routine to lower a locking level.
40907*/
40908static int flockLock(sqlite3_file *id, int eFileLock) {
40909  int rc = SQLITE_OK;
40910  unixFile *pFile = (unixFile*)id;
40911
40912  assert( pFile );
40913
40914  /* if we already have a lock, it is exclusive.
40915  ** Just adjust level and punt on outta here. */
40916  if (pFile->eFileLock > NO_LOCK) {
40917    pFile->eFileLock = eFileLock;
40918    return SQLITE_OK;
40919  }
40920
40921  /* grab an exclusive lock */
40922
40923  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
40924    int tErrno = errno;
40925    /* didn't get, must be busy */
40926    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
40927    if( IS_LOCK_ERROR(rc) ){
40928      storeLastErrno(pFile, tErrno);
40929    }
40930  } else {
40931    /* got it, set the type and return ok */
40932    pFile->eFileLock = eFileLock;
40933  }
40934  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
40935           rc==SQLITE_OK ? "ok" : "failed"));
40936#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
40937  if( (rc & 0xff) == SQLITE_IOERR ){
40938    rc = SQLITE_BUSY;
40939  }
40940#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
40941  return rc;
40942}
40943
40944
40945/*
40946** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
40947** must be either NO_LOCK or SHARED_LOCK.
40948**
40949** If the locking level of the file descriptor is already at or below
40950** the requested locking level, this routine is a no-op.
40951*/
40952static int flockUnlock(sqlite3_file *id, int eFileLock) {
40953  unixFile *pFile = (unixFile*)id;
40954
40955  assert( pFile );
40956  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
40957           pFile->eFileLock, osGetpid(0)));
40958  assert( eFileLock<=SHARED_LOCK );
40959
40960  /* no-op if possible */
40961  if( pFile->eFileLock==eFileLock ){
40962    return SQLITE_OK;
40963  }
40964
40965  /* shared can just be set because we always have an exclusive */
40966  if (eFileLock==SHARED_LOCK) {
40967    pFile->eFileLock = eFileLock;
40968    return SQLITE_OK;
40969  }
40970
40971  /* no, really, unlock. */
40972  if( robust_flock(pFile->h, LOCK_UN) ){
40973#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
40974    return SQLITE_OK;
40975#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
40976    return SQLITE_IOERR_UNLOCK;
40977  }else{
40978    pFile->eFileLock = NO_LOCK;
40979    return SQLITE_OK;
40980  }
40981}
40982
40983/*
40984** Close a file.
40985*/
40986static int flockClose(sqlite3_file *id) {
40987  assert( id!=0 );
40988  flockUnlock(id, NO_LOCK);
40989  return closeUnixFile(id);
40990}
40991
40992#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
40993
40994/******************* End of the flock lock implementation *********************
40995******************************************************************************/
40996
40997/******************************************************************************
40998************************ Begin Named Semaphore Locking ************************
40999**
41000** Named semaphore locking is only supported on VxWorks.
41001**
41002** Semaphore locking is like dot-lock and flock in that it really only
41003** supports EXCLUSIVE locking.  Only a single process can read or write
41004** the database file at a time.  This reduces potential concurrency, but
41005** makes the lock implementation much easier.
41006*/
41007#if OS_VXWORKS
41008
41009/*
41010** This routine checks if there is a RESERVED lock held on the specified
41011** file by this or any other process. If such a lock is held, set *pResOut
41012** to a non-zero value otherwise *pResOut is set to zero.  The return value
41013** is set to SQLITE_OK unless an I/O error occurs during lock checking.
41014*/
41015static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
41016  int rc = SQLITE_OK;
41017  int reserved = 0;
41018  unixFile *pFile = (unixFile*)id;
41019
41020  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
41021
41022  assert( pFile );
41023
41024  /* Check if a thread in this process holds such a lock */
41025  if( pFile->eFileLock>SHARED_LOCK ){
41026    reserved = 1;
41027  }
41028
41029  /* Otherwise see if some other process holds it. */
41030  if( !reserved ){
41031    sem_t *pSem = pFile->pInode->pSem;
41032
41033    if( sem_trywait(pSem)==-1 ){
41034      int tErrno = errno;
41035      if( EAGAIN != tErrno ){
41036        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
41037        storeLastErrno(pFile, tErrno);
41038      } else {
41039        /* someone else has the lock when we are in NO_LOCK */
41040        reserved = (pFile->eFileLock < SHARED_LOCK);
41041      }
41042    }else{
41043      /* we could have it if we want it */
41044      sem_post(pSem);
41045    }
41046  }
41047  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
41048
41049  *pResOut = reserved;
41050  return rc;
41051}
41052
41053/*
41054** Lock the file with the lock specified by parameter eFileLock - one
41055** of the following:
41056**
41057**     (1) SHARED_LOCK
41058**     (2) RESERVED_LOCK
41059**     (3) PENDING_LOCK
41060**     (4) EXCLUSIVE_LOCK
41061**
41062** Sometimes when requesting one lock state, additional lock states
41063** are inserted in between.  The locking might fail on one of the later
41064** transitions leaving the lock state different from what it started but
41065** still short of its goal.  The following chart shows the allowed
41066** transitions and the inserted intermediate states:
41067**
41068**    UNLOCKED -> SHARED
41069**    SHARED -> RESERVED
41070**    SHARED -> (PENDING) -> EXCLUSIVE
41071**    RESERVED -> (PENDING) -> EXCLUSIVE
41072**    PENDING -> EXCLUSIVE
41073**
41074** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
41075** lock states in the sqlite3_file structure, but all locks SHARED or
41076** above are really EXCLUSIVE locks and exclude all other processes from
41077** access the file.
41078**
41079** This routine will only increase a lock.  Use the sqlite3OsUnlock()
41080** routine to lower a locking level.
41081*/
41082static int semXLock(sqlite3_file *id, int eFileLock) {
41083  unixFile *pFile = (unixFile*)id;
41084  sem_t *pSem = pFile->pInode->pSem;
41085  int rc = SQLITE_OK;
41086
41087  /* if we already have a lock, it is exclusive.
41088  ** Just adjust level and punt on outta here. */
41089  if (pFile->eFileLock > NO_LOCK) {
41090    pFile->eFileLock = eFileLock;
41091    rc = SQLITE_OK;
41092    goto sem_end_lock;
41093  }
41094
41095  /* lock semaphore now but bail out when already locked. */
41096  if( sem_trywait(pSem)==-1 ){
41097    rc = SQLITE_BUSY;
41098    goto sem_end_lock;
41099  }
41100
41101  /* got it, set the type and return ok */
41102  pFile->eFileLock = eFileLock;
41103
41104 sem_end_lock:
41105  return rc;
41106}
41107
41108/*
41109** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
41110** must be either NO_LOCK or SHARED_LOCK.
41111**
41112** If the locking level of the file descriptor is already at or below
41113** the requested locking level, this routine is a no-op.
41114*/
41115static int semXUnlock(sqlite3_file *id, int eFileLock) {
41116  unixFile *pFile = (unixFile*)id;
41117  sem_t *pSem = pFile->pInode->pSem;
41118
41119  assert( pFile );
41120  assert( pSem );
41121  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
41122           pFile->eFileLock, osGetpid(0)));
41123  assert( eFileLock<=SHARED_LOCK );
41124
41125  /* no-op if possible */
41126  if( pFile->eFileLock==eFileLock ){
41127    return SQLITE_OK;
41128  }
41129
41130  /* shared can just be set because we always have an exclusive */
41131  if (eFileLock==SHARED_LOCK) {
41132    pFile->eFileLock = eFileLock;
41133    return SQLITE_OK;
41134  }
41135
41136  /* no, really unlock. */
41137  if ( sem_post(pSem)==-1 ) {
41138    int rc, tErrno = errno;
41139    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
41140    if( IS_LOCK_ERROR(rc) ){
41141      storeLastErrno(pFile, tErrno);
41142    }
41143    return rc;
41144  }
41145  pFile->eFileLock = NO_LOCK;
41146  return SQLITE_OK;
41147}
41148
41149/*
41150 ** Close a file.
41151 */
41152static int semXClose(sqlite3_file *id) {
41153  if( id ){
41154    unixFile *pFile = (unixFile*)id;
41155    semXUnlock(id, NO_LOCK);
41156    assert( pFile );
41157    assert( unixFileMutexNotheld(pFile) );
41158    unixEnterMutex();
41159    releaseInodeInfo(pFile);
41160    unixLeaveMutex();
41161    closeUnixFile(id);
41162  }
41163  return SQLITE_OK;
41164}
41165
41166#endif /* OS_VXWORKS */
41167/*
41168** Named semaphore locking is only available on VxWorks.
41169**
41170*************** End of the named semaphore lock implementation ****************
41171******************************************************************************/
41172
41173
41174/******************************************************************************
41175*************************** Begin AFP Locking *********************************
41176**
41177** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
41178** on Apple Macintosh computers - both OS9 and OSX.
41179**
41180** Third-party implementations of AFP are available.  But this code here
41181** only works on OSX.
41182*/
41183
41184#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
41185/*
41186** The afpLockingContext structure contains all afp lock specific state
41187*/
41188typedef struct afpLockingContext afpLockingContext;
41189struct afpLockingContext {
41190  int reserved;
41191  const char *dbPath;             /* Name of the open file */
41192};
41193
41194struct ByteRangeLockPB2
41195{
41196  unsigned long long offset;        /* offset to first byte to lock */
41197  unsigned long long length;        /* nbr of bytes to lock */
41198  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
41199  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
41200  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
41201  int fd;                           /* file desc to assoc this lock with */
41202};
41203
41204#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
41205
41206/*
41207** This is a utility for setting or clearing a bit-range lock on an
41208** AFP filesystem.
41209**
41210** Return SQLITE_OK on success, SQLITE_BUSY on failure.
41211*/
41212static int afpSetLock(
41213  const char *path,              /* Name of the file to be locked or unlocked */
41214  unixFile *pFile,               /* Open file descriptor on path */
41215  unsigned long long offset,     /* First byte to be locked */
41216  unsigned long long length,     /* Number of bytes to lock */
41217  int setLockFlag                /* True to set lock.  False to clear lock */
41218){
41219  struct ByteRangeLockPB2 pb;
41220  int err;
41221
41222  pb.unLockFlag = setLockFlag ? 0 : 1;
41223  pb.startEndFlag = 0;
41224  pb.offset = offset;
41225  pb.length = length;
41226  pb.fd = pFile->h;
41227
41228  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
41229    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
41230    offset, length));
41231  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
41232  if ( err==-1 ) {
41233    int rc;
41234    int tErrno = errno;
41235    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
41236             path, tErrno, strerror(tErrno)));
41237#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
41238    rc = SQLITE_BUSY;
41239#else
41240    rc = sqliteErrorFromPosixError(tErrno,
41241                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
41242#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
41243    if( IS_LOCK_ERROR(rc) ){
41244      storeLastErrno(pFile, tErrno);
41245    }
41246    return rc;
41247  } else {
41248    return SQLITE_OK;
41249  }
41250}
41251
41252/*
41253** This routine checks if there is a RESERVED lock held on the specified
41254** file by this or any other process. If such a lock is held, set *pResOut
41255** to a non-zero value otherwise *pResOut is set to zero.  The return value
41256** is set to SQLITE_OK unless an I/O error occurs during lock checking.
41257*/
41258static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
41259  int rc = SQLITE_OK;
41260  int reserved = 0;
41261  unixFile *pFile = (unixFile*)id;
41262  afpLockingContext *context;
41263
41264  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
41265
41266  assert( pFile );
41267  context = (afpLockingContext *) pFile->lockingContext;
41268  if( context->reserved ){
41269    *pResOut = 1;
41270    return SQLITE_OK;
41271  }
41272  sqlite3_mutex_enter(pFile->pInode->pLockMutex);
41273  /* Check if a thread in this process holds such a lock */
41274  if( pFile->pInode->eFileLock>SHARED_LOCK ){
41275    reserved = 1;
41276  }
41277
41278  /* Otherwise see if some other process holds it.
41279   */
41280  if( !reserved ){
41281    /* lock the RESERVED byte */
41282    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
41283    if( SQLITE_OK==lrc ){
41284      /* if we succeeded in taking the reserved lock, unlock it to restore
41285      ** the original state */
41286      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
41287    } else {
41288      /* if we failed to get the lock then someone else must have it */
41289      reserved = 1;
41290    }
41291    if( IS_LOCK_ERROR(lrc) ){
41292      rc=lrc;
41293    }
41294  }
41295
41296  sqlite3_mutex_leave(pFile->pInode->pLockMutex);
41297  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
41298
41299  *pResOut = reserved;
41300  return rc;
41301}
41302
41303/*
41304** Lock the file with the lock specified by parameter eFileLock - one
41305** of the following:
41306**
41307**     (1) SHARED_LOCK
41308**     (2) RESERVED_LOCK
41309**     (3) PENDING_LOCK
41310**     (4) EXCLUSIVE_LOCK
41311**
41312** Sometimes when requesting one lock state, additional lock states
41313** are inserted in between.  The locking might fail on one of the later
41314** transitions leaving the lock state different from what it started but
41315** still short of its goal.  The following chart shows the allowed
41316** transitions and the inserted intermediate states:
41317**
41318**    UNLOCKED -> SHARED
41319**    SHARED -> RESERVED
41320**    SHARED -> (PENDING) -> EXCLUSIVE
41321**    RESERVED -> (PENDING) -> EXCLUSIVE
41322**    PENDING -> EXCLUSIVE
41323**
41324** This routine will only increase a lock.  Use the sqlite3OsUnlock()
41325** routine to lower a locking level.
41326*/
41327static int afpLock(sqlite3_file *id, int eFileLock){
41328  int rc = SQLITE_OK;
41329  unixFile *pFile = (unixFile*)id;
41330  unixInodeInfo *pInode = pFile->pInode;
41331  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
41332
41333  assert( pFile );
41334  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
41335           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
41336           azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
41337
41338  /* If there is already a lock of this type or more restrictive on the
41339  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
41340  ** unixEnterMutex() hasn't been called yet.
41341  */
41342  if( pFile->eFileLock>=eFileLock ){
41343    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
41344           azFileLock(eFileLock)));
41345    return SQLITE_OK;
41346  }
41347
41348  /* Make sure the locking sequence is correct
41349  **  (1) We never move from unlocked to anything higher than shared lock.
41350  **  (2) SQLite never explicitly requests a pending lock.
41351  **  (3) A shared lock is always held when a reserve lock is requested.
41352  */
41353  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
41354  assert( eFileLock!=PENDING_LOCK );
41355  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
41356
41357  /* This mutex is needed because pFile->pInode is shared across threads
41358  */
41359  pInode = pFile->pInode;
41360  sqlite3_mutex_enter(pInode->pLockMutex);
41361
41362  /* If some thread using this PID has a lock via a different unixFile*
41363  ** handle that precludes the requested lock, return BUSY.
41364  */
41365  if( (pFile->eFileLock!=pInode->eFileLock &&
41366       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
41367     ){
41368    rc = SQLITE_BUSY;
41369    goto afp_end_lock;
41370  }
41371
41372  /* If a SHARED lock is requested, and some thread using this PID already
41373  ** has a SHARED or RESERVED lock, then increment reference counts and
41374  ** return SQLITE_OK.
41375  */
41376  if( eFileLock==SHARED_LOCK &&
41377     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
41378    assert( eFileLock==SHARED_LOCK );
41379    assert( pFile->eFileLock==0 );
41380    assert( pInode->nShared>0 );
41381    pFile->eFileLock = SHARED_LOCK;
41382    pInode->nShared++;
41383    pInode->nLock++;
41384    goto afp_end_lock;
41385  }
41386
41387  /* A PENDING lock is needed before acquiring a SHARED lock and before
41388  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
41389  ** be released.
41390  */
41391  if( eFileLock==SHARED_LOCK
41392      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
41393  ){
41394    int failed;
41395    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
41396    if (failed) {
41397      rc = failed;
41398      goto afp_end_lock;
41399    }
41400  }
41401
41402  /* If control gets to this point, then actually go ahead and make
41403  ** operating system calls for the specified lock.
41404  */
41405  if( eFileLock==SHARED_LOCK ){
41406    int lrc1, lrc2, lrc1Errno = 0;
41407    long lk, mask;
41408
41409    assert( pInode->nShared==0 );
41410    assert( pInode->eFileLock==0 );
41411
41412    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
41413    /* Now get the read-lock SHARED_LOCK */
41414    /* note that the quality of the randomness doesn't matter that much */
41415    lk = random();
41416    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
41417    lrc1 = afpSetLock(context->dbPath, pFile,
41418          SHARED_FIRST+pInode->sharedByte, 1, 1);
41419    if( IS_LOCK_ERROR(lrc1) ){
41420      lrc1Errno = pFile->lastErrno;
41421    }
41422    /* Drop the temporary PENDING lock */
41423    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
41424
41425    if( IS_LOCK_ERROR(lrc1) ) {
41426      storeLastErrno(pFile, lrc1Errno);
41427      rc = lrc1;
41428      goto afp_end_lock;
41429    } else if( IS_LOCK_ERROR(lrc2) ){
41430      rc = lrc2;
41431      goto afp_end_lock;
41432    } else if( lrc1 != SQLITE_OK ) {
41433      rc = lrc1;
41434    } else {
41435      pFile->eFileLock = SHARED_LOCK;
41436      pInode->nLock++;
41437      pInode->nShared = 1;
41438    }
41439  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
41440    /* We are trying for an exclusive lock but another thread in this
41441     ** same process is still holding a shared lock. */
41442    rc = SQLITE_BUSY;
41443  }else{
41444    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
41445    ** assumed that there is a SHARED or greater lock on the file
41446    ** already.
41447    */
41448    int failed = 0;
41449    assert( 0!=pFile->eFileLock );
41450    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
41451        /* Acquire a RESERVED lock */
41452        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
41453      if( !failed ){
41454        context->reserved = 1;
41455      }
41456    }
41457    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
41458      /* Acquire an EXCLUSIVE lock */
41459
41460      /* Remove the shared lock before trying the range.  we'll need to
41461      ** reestablish the shared lock if we can't get the  afpUnlock
41462      */
41463      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
41464                         pInode->sharedByte, 1, 0)) ){
41465        int failed2 = SQLITE_OK;
41466        /* now attempt to get the exclusive lock range */
41467        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
41468                               SHARED_SIZE, 1);
41469        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
41470                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
41471          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
41472          ** a critical I/O error
41473          */
41474          rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
41475               SQLITE_IOERR_LOCK;
41476          goto afp_end_lock;
41477        }
41478      }else{
41479        rc = failed;
41480      }
41481    }
41482    if( failed ){
41483      rc = failed;
41484    }
41485  }
41486
41487  if( rc==SQLITE_OK ){
41488    pFile->eFileLock = eFileLock;
41489    pInode->eFileLock = eFileLock;
41490  }else if( eFileLock==EXCLUSIVE_LOCK ){
41491    pFile->eFileLock = PENDING_LOCK;
41492    pInode->eFileLock = PENDING_LOCK;
41493  }
41494
41495afp_end_lock:
41496  sqlite3_mutex_leave(pInode->pLockMutex);
41497  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
41498         rc==SQLITE_OK ? "ok" : "failed"));
41499  return rc;
41500}
41501
41502/*
41503** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
41504** must be either NO_LOCK or SHARED_LOCK.
41505**
41506** If the locking level of the file descriptor is already at or below
41507** the requested locking level, this routine is a no-op.
41508*/
41509static int afpUnlock(sqlite3_file *id, int eFileLock) {
41510  int rc = SQLITE_OK;
41511  unixFile *pFile = (unixFile*)id;
41512  unixInodeInfo *pInode;
41513  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
41514  int skipShared = 0;
41515
41516  assert( pFile );
41517  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
41518           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
41519           osGetpid(0)));
41520
41521  assert( eFileLock<=SHARED_LOCK );
41522  if( pFile->eFileLock<=eFileLock ){
41523    return SQLITE_OK;
41524  }
41525  pInode = pFile->pInode;
41526  sqlite3_mutex_enter(pInode->pLockMutex);
41527  assert( pInode->nShared!=0 );
41528  if( pFile->eFileLock>SHARED_LOCK ){
41529    assert( pInode->eFileLock==pFile->eFileLock );
41530
41531#ifdef SQLITE_DEBUG
41532    /* When reducing a lock such that other processes can start
41533    ** reading the database file again, make sure that the
41534    ** transaction counter was updated if any part of the database
41535    ** file changed.  If the transaction counter is not updated,
41536    ** other connections to the same file might not realize that
41537    ** the file has changed and hence might not know to flush their
41538    ** cache.  The use of a stale cache can lead to database corruption.
41539    */
41540    assert( pFile->inNormalWrite==0
41541           || pFile->dbUpdate==0
41542           || pFile->transCntrChng==1 );
41543    pFile->inNormalWrite = 0;
41544#endif
41545
41546    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
41547      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
41548      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
41549        /* only re-establish the shared lock if necessary */
41550        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
41551        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
41552      } else {
41553        skipShared = 1;
41554      }
41555    }
41556    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
41557      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
41558    }
41559    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
41560      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
41561      if( !rc ){
41562        context->reserved = 0;
41563      }
41564    }
41565    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
41566      pInode->eFileLock = SHARED_LOCK;
41567    }
41568  }
41569  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
41570
41571    /* Decrement the shared lock counter.  Release the lock using an
41572    ** OS call only when all threads in this same process have released
41573    ** the lock.
41574    */
41575    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
41576    pInode->nShared--;
41577    if( pInode->nShared==0 ){
41578      if( !skipShared ){
41579        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
41580      }
41581      if( !rc ){
41582        pInode->eFileLock = NO_LOCK;
41583        pFile->eFileLock = NO_LOCK;
41584      }
41585    }
41586    if( rc==SQLITE_OK ){
41587      pInode->nLock--;
41588      assert( pInode->nLock>=0 );
41589      if( pInode->nLock==0 ) closePendingFds(pFile);
41590    }
41591  }
41592
41593  sqlite3_mutex_leave(pInode->pLockMutex);
41594  if( rc==SQLITE_OK ){
41595    pFile->eFileLock = eFileLock;
41596  }
41597  return rc;
41598}
41599
41600/*
41601** Close a file & cleanup AFP specific locking context
41602*/
41603static int afpClose(sqlite3_file *id) {
41604  int rc = SQLITE_OK;
41605  unixFile *pFile = (unixFile*)id;
41606  assert( id!=0 );
41607  afpUnlock(id, NO_LOCK);
41608  assert( unixFileMutexNotheld(pFile) );
41609  unixEnterMutex();
41610  if( pFile->pInode ){
41611    unixInodeInfo *pInode = pFile->pInode;
41612    sqlite3_mutex_enter(pInode->pLockMutex);
41613    if( pInode->nLock ){
41614      /* If there are outstanding locks, do not actually close the file just
41615      ** yet because that would clear those locks.  Instead, add the file
41616      ** descriptor to pInode->aPending.  It will be automatically closed when
41617      ** the last lock is cleared.
41618      */
41619      setPendingFd(pFile);
41620    }
41621    sqlite3_mutex_leave(pInode->pLockMutex);
41622  }
41623  releaseInodeInfo(pFile);
41624  sqlite3_free(pFile->lockingContext);
41625  rc = closeUnixFile(id);
41626  unixLeaveMutex();
41627  return rc;
41628}
41629
41630#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
41631/*
41632** The code above is the AFP lock implementation.  The code is specific
41633** to MacOSX and does not work on other unix platforms.  No alternative
41634** is available.  If you don't compile for a mac, then the "unix-afp"
41635** VFS is not available.
41636**
41637********************* End of the AFP lock implementation **********************
41638******************************************************************************/
41639
41640/******************************************************************************
41641*************************** Begin NFS Locking ********************************/
41642
41643#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
41644/*
41645 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
41646 ** must be either NO_LOCK or SHARED_LOCK.
41647 **
41648 ** If the locking level of the file descriptor is already at or below
41649 ** the requested locking level, this routine is a no-op.
41650 */
41651static int nfsUnlock(sqlite3_file *id, int eFileLock){
41652  return posixUnlock(id, eFileLock, 1);
41653}
41654
41655#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
41656/*
41657** The code above is the NFS lock implementation.  The code is specific
41658** to MacOSX and does not work on other unix platforms.  No alternative
41659** is available.
41660**
41661********************* End of the NFS lock implementation **********************
41662******************************************************************************/
41663
41664/******************************************************************************
41665**************** Non-locking sqlite3_file methods *****************************
41666**
41667** The next division contains implementations for all methods of the
41668** sqlite3_file object other than the locking methods.  The locking
41669** methods were defined in divisions above (one locking method per
41670** division).  Those methods that are common to all locking modes
41671** are gather together into this division.
41672*/
41673
41674/*
41675** Seek to the offset passed as the second argument, then read cnt
41676** bytes into pBuf. Return the number of bytes actually read.
41677**
41678** To avoid stomping the errno value on a failed read the lastErrno value
41679** is set before returning.
41680*/
41681static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
41682  int got;
41683  int prior = 0;
41684#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
41685  i64 newOffset;
41686#endif
41687  TIMER_START;
41688  assert( cnt==(cnt&0x1ffff) );
41689  assert( id->h>2 );
41690  do{
41691#if defined(USE_PREAD)
41692    got = osPread(id->h, pBuf, cnt, offset);
41693    SimulateIOError( got = -1 );
41694#elif defined(USE_PREAD64)
41695    got = osPread64(id->h, pBuf, cnt, offset);
41696    SimulateIOError( got = -1 );
41697#else
41698    newOffset = lseek(id->h, offset, SEEK_SET);
41699    SimulateIOError( newOffset = -1 );
41700    if( newOffset<0 ){
41701      storeLastErrno((unixFile*)id, errno);
41702      return -1;
41703    }
41704    got = osRead(id->h, pBuf, cnt);
41705#endif
41706    if( got==cnt ) break;
41707    if( got<0 ){
41708      if( errno==EINTR ){ got = 1; continue; }
41709      prior = 0;
41710      storeLastErrno((unixFile*)id,  errno);
41711      break;
41712    }else if( got>0 ){
41713      cnt -= got;
41714      offset += got;
41715      prior += got;
41716      pBuf = (void*)(got + (char*)pBuf);
41717    }
41718  }while( got>0 );
41719  TIMER_END;
41720  OSTRACE(("READ    %-3d %5d %7lld %llu\n",
41721            id->h, got+prior, offset-prior, TIMER_ELAPSED));
41722  return got+prior;
41723}
41724
41725/*
41726** Read data from a file into a buffer.  Return SQLITE_OK if all
41727** bytes were read successfully and SQLITE_IOERR if anything goes
41728** wrong.
41729*/
41730static int unixRead(
41731  sqlite3_file *id,
41732  void *pBuf,
41733  int amt,
41734  sqlite3_int64 offset
41735){
41736  unixFile *pFile = (unixFile *)id;
41737  int got;
41738  assert( id );
41739  assert( offset>=0 );
41740  assert( amt>0 );
41741
41742  /* If this is a database file (not a journal, super-journal or temp
41743  ** file), the bytes in the locking range should never be read or written. */
41744#if 0
41745  assert( pFile->pPreallocatedUnused==0
41746       || offset>=PENDING_BYTE+512
41747       || offset+amt<=PENDING_BYTE
41748  );
41749#endif
41750
41751#if SQLITE_MAX_MMAP_SIZE>0
41752  /* Deal with as much of this read request as possible by transferring
41753  ** data from the memory mapping using memcpy().  */
41754  if( offset<pFile->mmapSize ){
41755    if( offset+amt <= pFile->mmapSize ){
41756      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
41757      return SQLITE_OK;
41758    }else{
41759      int nCopy = pFile->mmapSize - offset;
41760      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
41761      pBuf = &((u8 *)pBuf)[nCopy];
41762      amt -= nCopy;
41763      offset += nCopy;
41764    }
41765  }
41766#endif
41767
41768  got = seekAndRead(pFile, offset, pBuf, amt);
41769  if( got==amt ){
41770    return SQLITE_OK;
41771  }else if( got<0 ){
41772    /* pFile->lastErrno has been set by seekAndRead().
41773    ** Usually we return SQLITE_IOERR_READ here, though for some
41774    ** kinds of errors we return SQLITE_IOERR_CORRUPTFS.  The
41775    ** SQLITE_IOERR_CORRUPTFS will be converted into SQLITE_CORRUPT
41776    ** prior to returning to the application by the sqlite3ApiExit()
41777    ** routine.
41778    */
41779    switch( pFile->lastErrno ){
41780      case ERANGE:
41781      case EIO:
41782#ifdef ENXIO
41783      case ENXIO:
41784#endif
41785#ifdef EDEVERR
41786      case EDEVERR:
41787#endif
41788        return SQLITE_IOERR_CORRUPTFS;
41789    }
41790    return SQLITE_IOERR_READ;
41791  }else{
41792    storeLastErrno(pFile, 0);   /* not a system error */
41793    /* Unread parts of the buffer must be zero-filled */
41794    memset(&((char*)pBuf)[got], 0, amt-got);
41795    return SQLITE_IOERR_SHORT_READ;
41796  }
41797}
41798
41799/*
41800** Attempt to seek the file-descriptor passed as the first argument to
41801** absolute offset iOff, then attempt to write nBuf bytes of data from
41802** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
41803** return the actual number of bytes written (which may be less than
41804** nBuf).
41805*/
41806static int seekAndWriteFd(
41807  int fd,                         /* File descriptor to write to */
41808  i64 iOff,                       /* File offset to begin writing at */
41809  const void *pBuf,               /* Copy data from this buffer to the file */
41810  int nBuf,                       /* Size of buffer pBuf in bytes */
41811  int *piErrno                    /* OUT: Error number if error occurs */
41812){
41813  int rc = 0;                     /* Value returned by system call */
41814
41815  assert( nBuf==(nBuf&0x1ffff) );
41816  assert( fd>2 );
41817  assert( piErrno!=0 );
41818  nBuf &= 0x1ffff;
41819  TIMER_START;
41820
41821#if defined(USE_PREAD)
41822  do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
41823#elif defined(USE_PREAD64)
41824  do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
41825#else
41826  do{
41827    i64 iSeek = lseek(fd, iOff, SEEK_SET);
41828    SimulateIOError( iSeek = -1 );
41829    if( iSeek<0 ){
41830      rc = -1;
41831      break;
41832    }
41833    rc = osWrite(fd, pBuf, nBuf);
41834  }while( rc<0 && errno==EINTR );
41835#endif
41836
41837  TIMER_END;
41838  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
41839
41840  if( rc<0 ) *piErrno = errno;
41841  return rc;
41842}
41843
41844
41845/*
41846** Seek to the offset in id->offset then read cnt bytes into pBuf.
41847** Return the number of bytes actually read.  Update the offset.
41848**
41849** To avoid stomping the errno value on a failed write the lastErrno value
41850** is set before returning.
41851*/
41852static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
41853  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
41854}
41855
41856
41857/*
41858** Write data from a buffer into a file.  Return SQLITE_OK on success
41859** or some other error code on failure.
41860*/
41861static int unixWrite(
41862  sqlite3_file *id,
41863  const void *pBuf,
41864  int amt,
41865  sqlite3_int64 offset
41866){
41867  unixFile *pFile = (unixFile*)id;
41868  int wrote = 0;
41869  assert( id );
41870  assert( amt>0 );
41871
41872  /* If this is a database file (not a journal, super-journal or temp
41873  ** file), the bytes in the locking range should never be read or written. */
41874#if 0
41875  assert( pFile->pPreallocatedUnused==0
41876       || offset>=PENDING_BYTE+512
41877       || offset+amt<=PENDING_BYTE
41878  );
41879#endif
41880
41881#ifdef SQLITE_DEBUG
41882  /* If we are doing a normal write to a database file (as opposed to
41883  ** doing a hot-journal rollback or a write to some file other than a
41884  ** normal database file) then record the fact that the database
41885  ** has changed.  If the transaction counter is modified, record that
41886  ** fact too.
41887  */
41888  if( pFile->inNormalWrite ){
41889    pFile->dbUpdate = 1;  /* The database has been modified */
41890    if( offset<=24 && offset+amt>=27 ){
41891      int rc;
41892      char oldCntr[4];
41893      SimulateIOErrorBenign(1);
41894      rc = seekAndRead(pFile, 24, oldCntr, 4);
41895      SimulateIOErrorBenign(0);
41896      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
41897        pFile->transCntrChng = 1;  /* The transaction counter has changed */
41898      }
41899    }
41900  }
41901#endif
41902
41903#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
41904  /* Deal with as much of this write request as possible by transferring
41905  ** data from the memory mapping using memcpy().  */
41906  if( offset<pFile->mmapSize ){
41907    if( offset+amt <= pFile->mmapSize ){
41908      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
41909      return SQLITE_OK;
41910    }else{
41911      int nCopy = pFile->mmapSize - offset;
41912      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
41913      pBuf = &((u8 *)pBuf)[nCopy];
41914      amt -= nCopy;
41915      offset += nCopy;
41916    }
41917  }
41918#endif
41919
41920  while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
41921    amt -= wrote;
41922    offset += wrote;
41923    pBuf = &((char*)pBuf)[wrote];
41924  }
41925  SimulateIOError(( wrote=(-1), amt=1 ));
41926  SimulateDiskfullError(( wrote=0, amt=1 ));
41927
41928  if( amt>wrote ){
41929    if( wrote<0 && pFile->lastErrno!=ENOSPC ){
41930      /* lastErrno set by seekAndWrite */
41931      return SQLITE_IOERR_WRITE;
41932    }else{
41933      storeLastErrno(pFile, 0); /* not a system error */
41934      return SQLITE_FULL;
41935    }
41936  }
41937
41938  return SQLITE_OK;
41939}
41940
41941#ifdef SQLITE_TEST
41942/*
41943** Count the number of fullsyncs and normal syncs.  This is used to test
41944** that syncs and fullsyncs are occurring at the right times.
41945*/
41946SQLITE_API int sqlite3_sync_count = 0;
41947SQLITE_API int sqlite3_fullsync_count = 0;
41948#endif
41949
41950/*
41951** We do not trust systems to provide a working fdatasync().  Some do.
41952** Others do no.  To be safe, we will stick with the (slightly slower)
41953** fsync(). If you know that your system does support fdatasync() correctly,
41954** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
41955*/
41956#if !defined(fdatasync) && !HAVE_FDATASYNC
41957# define fdatasync fsync
41958#endif
41959
41960/*
41961** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
41962** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
41963** only available on Mac OS X.  But that could change.
41964*/
41965#ifdef F_FULLFSYNC
41966# define HAVE_FULLFSYNC 1
41967#else
41968# define HAVE_FULLFSYNC 0
41969#endif
41970
41971
41972/*
41973** The fsync() system call does not work as advertised on many
41974** unix systems.  The following procedure is an attempt to make
41975** it work better.
41976**
41977** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
41978** for testing when we want to run through the test suite quickly.
41979** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
41980** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
41981** or power failure will likely corrupt the database file.
41982**
41983** SQLite sets the dataOnly flag if the size of the file is unchanged.
41984** The idea behind dataOnly is that it should only write the file content
41985** to disk, not the inode.  We only set dataOnly if the file size is
41986** unchanged since the file size is part of the inode.  However,
41987** Ted Ts'o tells us that fdatasync() will also write the inode if the
41988** file size has changed.  The only real difference between fdatasync()
41989** and fsync(), Ted tells us, is that fdatasync() will not flush the
41990** inode if the mtime or owner or other inode attributes have changed.
41991** We only care about the file size, not the other file attributes, so
41992** as far as SQLite is concerned, an fdatasync() is always adequate.
41993** So, we always use fdatasync() if it is available, regardless of
41994** the value of the dataOnly flag.
41995*/
41996static int full_fsync(int fd, int fullSync, int dataOnly){
41997  int rc;
41998
41999  /* The following "ifdef/elif/else/" block has the same structure as
42000  ** the one below. It is replicated here solely to avoid cluttering
42001  ** up the real code with the UNUSED_PARAMETER() macros.
42002  */
42003#ifdef SQLITE_NO_SYNC
42004  UNUSED_PARAMETER(fd);
42005  UNUSED_PARAMETER(fullSync);
42006  UNUSED_PARAMETER(dataOnly);
42007#elif HAVE_FULLFSYNC
42008  UNUSED_PARAMETER(dataOnly);
42009#else
42010  UNUSED_PARAMETER(fullSync);
42011  UNUSED_PARAMETER(dataOnly);
42012#endif
42013
42014  /* Record the number of times that we do a normal fsync() and
42015  ** FULLSYNC.  This is used during testing to verify that this procedure
42016  ** gets called with the correct arguments.
42017  */
42018#ifdef SQLITE_TEST
42019  if( fullSync ) sqlite3_fullsync_count++;
42020  sqlite3_sync_count++;
42021#endif
42022
42023  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
42024  ** no-op.  But go ahead and call fstat() to validate the file
42025  ** descriptor as we need a method to provoke a failure during
42026  ** coverage testing.
42027  */
42028#ifdef SQLITE_NO_SYNC
42029  {
42030    struct stat buf;
42031    rc = osFstat(fd, &buf);
42032  }
42033#elif HAVE_FULLFSYNC
42034  if( fullSync ){
42035    rc = osFcntl(fd, F_FULLFSYNC, 0);
42036  }else{
42037    rc = 1;
42038  }
42039  /* If the FULLFSYNC failed, fall back to attempting an fsync().
42040  ** It shouldn't be possible for fullfsync to fail on the local
42041  ** file system (on OSX), so failure indicates that FULLFSYNC
42042  ** isn't supported for this file system. So, attempt an fsync
42043  ** and (for now) ignore the overhead of a superfluous fcntl call.
42044  ** It'd be better to detect fullfsync support once and avoid
42045  ** the fcntl call every time sync is called.
42046  */
42047  if( rc ) rc = fsync(fd);
42048
42049#elif defined(__APPLE__)
42050  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
42051  ** so currently we default to the macro that redefines fdatasync to fsync
42052  */
42053  rc = fsync(fd);
42054#else
42055  rc = fdatasync(fd);
42056#if OS_VXWORKS
42057  if( rc==-1 && errno==ENOTSUP ){
42058    rc = fsync(fd);
42059  }
42060#endif /* OS_VXWORKS */
42061#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
42062
42063  if( OS_VXWORKS && rc!= -1 ){
42064    rc = 0;
42065  }
42066  return rc;
42067}
42068
42069/*
42070** Open a file descriptor to the directory containing file zFilename.
42071** If successful, *pFd is set to the opened file descriptor and
42072** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
42073** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
42074** value.
42075**
42076** The directory file descriptor is used for only one thing - to
42077** fsync() a directory to make sure file creation and deletion events
42078** are flushed to disk.  Such fsyncs are not needed on newer
42079** journaling filesystems, but are required on older filesystems.
42080**
42081** This routine can be overridden using the xSetSysCall interface.
42082** The ability to override this routine was added in support of the
42083** chromium sandbox.  Opening a directory is a security risk (we are
42084** told) so making it overrideable allows the chromium sandbox to
42085** replace this routine with a harmless no-op.  To make this routine
42086** a no-op, replace it with a stub that returns SQLITE_OK but leaves
42087** *pFd set to a negative number.
42088**
42089** If SQLITE_OK is returned, the caller is responsible for closing
42090** the file descriptor *pFd using close().
42091*/
42092static int openDirectory(const char *zFilename, int *pFd){
42093  int ii;
42094  int fd = -1;
42095  char zDirname[MAX_PATHNAME+1];
42096
42097  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
42098  for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
42099  if( ii>0 ){
42100    zDirname[ii] = '\0';
42101  }else{
42102    if( zDirname[0]!='/' ) zDirname[0] = '.';
42103    zDirname[1] = 0;
42104  }
42105  fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
42106  if( fd>=0 ){
42107    OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
42108  }
42109  *pFd = fd;
42110  if( fd>=0 ) return SQLITE_OK;
42111  return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
42112}
42113
42114/*
42115** Make sure all writes to a particular file are committed to disk.
42116**
42117** If dataOnly==0 then both the file itself and its metadata (file
42118** size, access time, etc) are synced.  If dataOnly!=0 then only the
42119** file data is synced.
42120**
42121** Under Unix, also make sure that the directory entry for the file
42122** has been created by fsync-ing the directory that contains the file.
42123** If we do not do this and we encounter a power failure, the directory
42124** entry for the journal might not exist after we reboot.  The next
42125** SQLite to access the file will not know that the journal exists (because
42126** the directory entry for the journal was never created) and the transaction
42127** will not roll back - possibly leading to database corruption.
42128*/
42129static int unixSync(sqlite3_file *id, int flags){
42130  int rc;
42131  unixFile *pFile = (unixFile*)id;
42132
42133  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
42134  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
42135
42136  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
42137  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
42138      || (flags&0x0F)==SQLITE_SYNC_FULL
42139  );
42140
42141  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
42142  ** line is to test that doing so does not cause any problems.
42143  */
42144  SimulateDiskfullError( return SQLITE_FULL );
42145
42146  assert( pFile );
42147  OSTRACE(("SYNC    %-3d\n", pFile->h));
42148  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
42149  SimulateIOError( rc=1 );
42150  if( rc ){
42151    storeLastErrno(pFile, errno);
42152    return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
42153  }
42154
42155  /* Also fsync the directory containing the file if the DIRSYNC flag
42156  ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
42157  ** are unable to fsync a directory, so ignore errors on the fsync.
42158  */
42159  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
42160    int dirfd;
42161    OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
42162            HAVE_FULLFSYNC, isFullsync));
42163    rc = osOpenDirectory(pFile->zPath, &dirfd);
42164    if( rc==SQLITE_OK ){
42165      full_fsync(dirfd, 0, 0);
42166      robust_close(pFile, dirfd, __LINE__);
42167    }else{
42168      assert( rc==SQLITE_CANTOPEN );
42169      rc = SQLITE_OK;
42170    }
42171    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
42172  }
42173  return rc;
42174}
42175
42176/*
42177** Truncate an open file to a specified size
42178*/
42179static int unixTruncate(sqlite3_file *id, i64 nByte){
42180  unixFile *pFile = (unixFile *)id;
42181  int rc;
42182  assert( pFile );
42183  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
42184
42185  /* If the user has configured a chunk-size for this file, truncate the
42186  ** file so that it consists of an integer number of chunks (i.e. the
42187  ** actual file size after the operation may be larger than the requested
42188  ** size).
42189  */
42190  if( pFile->szChunk>0 ){
42191    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
42192  }
42193
42194  rc = robust_ftruncate(pFile->h, nByte);
42195  if( rc ){
42196    storeLastErrno(pFile, errno);
42197    return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
42198  }else{
42199#ifdef SQLITE_DEBUG
42200    /* If we are doing a normal write to a database file (as opposed to
42201    ** doing a hot-journal rollback or a write to some file other than a
42202    ** normal database file) and we truncate the file to zero length,
42203    ** that effectively updates the change counter.  This might happen
42204    ** when restoring a database using the backup API from a zero-length
42205    ** source.
42206    */
42207    if( pFile->inNormalWrite && nByte==0 ){
42208      pFile->transCntrChng = 1;
42209    }
42210#endif
42211
42212#if SQLITE_MAX_MMAP_SIZE>0
42213    /* If the file was just truncated to a size smaller than the currently
42214    ** mapped region, reduce the effective mapping size as well. SQLite will
42215    ** use read() and write() to access data beyond this point from now on.
42216    */
42217    if( nByte<pFile->mmapSize ){
42218      pFile->mmapSize = nByte;
42219    }
42220#endif
42221
42222    return SQLITE_OK;
42223  }
42224}
42225
42226/*
42227** Determine the current size of a file in bytes
42228*/
42229static int unixFileSize(sqlite3_file *id, i64 *pSize){
42230  int rc;
42231  struct stat buf;
42232  assert( id );
42233  rc = osFstat(((unixFile*)id)->h, &buf);
42234  SimulateIOError( rc=1 );
42235  if( rc!=0 ){
42236    storeLastErrno((unixFile*)id, errno);
42237    return SQLITE_IOERR_FSTAT;
42238  }
42239  *pSize = buf.st_size;
42240
42241  /* When opening a zero-size database, the findInodeInfo() procedure
42242  ** writes a single byte into that file in order to work around a bug
42243  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
42244  ** layers, we need to report this file size as zero even though it is
42245  ** really 1.   Ticket #3260.
42246  */
42247  if( *pSize==1 ) *pSize = 0;
42248
42249
42250  return SQLITE_OK;
42251}
42252
42253#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
42254/*
42255** Handler for proxy-locking file-control verbs.  Defined below in the
42256** proxying locking division.
42257*/
42258static int proxyFileControl(sqlite3_file*,int,void*);
42259#endif
42260
42261/*
42262** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
42263** file-control operation.  Enlarge the database to nBytes in size
42264** (rounded up to the next chunk-size).  If the database is already
42265** nBytes or larger, this routine is a no-op.
42266*/
42267static int fcntlSizeHint(unixFile *pFile, i64 nByte){
42268  if( pFile->szChunk>0 ){
42269    i64 nSize;                    /* Required file size */
42270    struct stat buf;              /* Used to hold return values of fstat() */
42271
42272    if( osFstat(pFile->h, &buf) ){
42273      return SQLITE_IOERR_FSTAT;
42274    }
42275
42276    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
42277    if( nSize>(i64)buf.st_size ){
42278
42279#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
42280      /* The code below is handling the return value of osFallocate()
42281      ** correctly. posix_fallocate() is defined to "returns zero on success,
42282      ** or an error number on  failure". See the manpage for details. */
42283      int err;
42284      do{
42285        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
42286      }while( err==EINTR );
42287      if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
42288#else
42289      /* If the OS does not have posix_fallocate(), fake it. Write a
42290      ** single byte to the last byte in each block that falls entirely
42291      ** within the extended region. Then, if required, a single byte
42292      ** at offset (nSize-1), to set the size of the file correctly.
42293      ** This is a similar technique to that used by glibc on systems
42294      ** that do not have a real fallocate() call.
42295      */
42296      int nBlk = buf.st_blksize;  /* File-system block size */
42297      int nWrite = 0;             /* Number of bytes written by seekAndWrite */
42298      i64 iWrite;                 /* Next offset to write to */
42299
42300      iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
42301      assert( iWrite>=buf.st_size );
42302      assert( ((iWrite+1)%nBlk)==0 );
42303      for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
42304        if( iWrite>=nSize ) iWrite = nSize - 1;
42305        nWrite = seekAndWrite(pFile, iWrite, "", 1);
42306        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
42307      }
42308#endif
42309    }
42310  }
42311
42312#if SQLITE_MAX_MMAP_SIZE>0
42313  if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
42314    int rc;
42315    if( pFile->szChunk<=0 ){
42316      if( robust_ftruncate(pFile->h, nByte) ){
42317        storeLastErrno(pFile, errno);
42318        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
42319      }
42320    }
42321
42322    rc = unixMapfile(pFile, nByte);
42323    return rc;
42324  }
42325#endif
42326
42327  return SQLITE_OK;
42328}
42329
42330/*
42331** If *pArg is initially negative then this is a query.  Set *pArg to
42332** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
42333**
42334** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
42335*/
42336static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
42337  if( *pArg<0 ){
42338    *pArg = (pFile->ctrlFlags & mask)!=0;
42339  }else if( (*pArg)==0 ){
42340    pFile->ctrlFlags &= ~mask;
42341  }else{
42342    pFile->ctrlFlags |= mask;
42343  }
42344}
42345
42346/* Forward declaration */
42347static int unixGetTempname(int nBuf, char *zBuf);
42348#ifndef SQLITE_OMIT_WAL
42349 static int unixFcntlExternalReader(unixFile*, int*);
42350#endif
42351
42352/*
42353** Information and control of an open file handle.
42354*/
42355static int unixFileControl(sqlite3_file *id, int op, void *pArg){
42356  unixFile *pFile = (unixFile*)id;
42357  switch( op ){
42358#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
42359    case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
42360      int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
42361      return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
42362    }
42363    case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
42364      int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
42365      return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
42366    }
42367    case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
42368      int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
42369      return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
42370    }
42371#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
42372
42373    case SQLITE_FCNTL_LOCKSTATE: {
42374      *(int*)pArg = pFile->eFileLock;
42375      return SQLITE_OK;
42376    }
42377    case SQLITE_FCNTL_LAST_ERRNO: {
42378      *(int*)pArg = pFile->lastErrno;
42379      return SQLITE_OK;
42380    }
42381    case SQLITE_FCNTL_CHUNK_SIZE: {
42382      pFile->szChunk = *(int *)pArg;
42383      return SQLITE_OK;
42384    }
42385    case SQLITE_FCNTL_SIZE_HINT: {
42386      int rc;
42387      SimulateIOErrorBenign(1);
42388      rc = fcntlSizeHint(pFile, *(i64 *)pArg);
42389      SimulateIOErrorBenign(0);
42390      return rc;
42391    }
42392    case SQLITE_FCNTL_PERSIST_WAL: {
42393      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
42394      return SQLITE_OK;
42395    }
42396    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
42397      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
42398      return SQLITE_OK;
42399    }
42400    case SQLITE_FCNTL_VFSNAME: {
42401      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
42402      return SQLITE_OK;
42403    }
42404    case SQLITE_FCNTL_TEMPFILENAME: {
42405      char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
42406      if( zTFile ){
42407        unixGetTempname(pFile->pVfs->mxPathname, zTFile);
42408        *(char**)pArg = zTFile;
42409      }
42410      return SQLITE_OK;
42411    }
42412    case SQLITE_FCNTL_HAS_MOVED: {
42413      *(int*)pArg = fileHasMoved(pFile);
42414      return SQLITE_OK;
42415    }
42416#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42417    case SQLITE_FCNTL_LOCK_TIMEOUT: {
42418      int iOld = pFile->iBusyTimeout;
42419#if SQLITE_ENABLE_SETLK_TIMEOUT==1
42420      pFile->iBusyTimeout = *(int*)pArg;
42421#elif SQLITE_ENABLE_SETLK_TIMEOUT==2
42422      pFile->iBusyTimeout = !!(*(int*)pArg);
42423#else
42424# error "SQLITE_ENABLE_SETLK_TIMEOUT must be set to 1 or 2"
42425#endif
42426      *(int*)pArg = iOld;
42427      return SQLITE_OK;
42428    }
42429#endif
42430#if SQLITE_MAX_MMAP_SIZE>0
42431    case SQLITE_FCNTL_MMAP_SIZE: {
42432      i64 newLimit = *(i64*)pArg;
42433      int rc = SQLITE_OK;
42434      if( newLimit>sqlite3GlobalConfig.mxMmap ){
42435        newLimit = sqlite3GlobalConfig.mxMmap;
42436      }
42437
42438      /* The value of newLimit may be eventually cast to (size_t) and passed
42439      ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
42440      ** 64-bit type. */
42441      if( newLimit>0 && sizeof(size_t)<8 ){
42442        newLimit = (newLimit & 0x7FFFFFFF);
42443      }
42444
42445      *(i64*)pArg = pFile->mmapSizeMax;
42446      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
42447        pFile->mmapSizeMax = newLimit;
42448        if( pFile->mmapSize>0 ){
42449          unixUnmapfile(pFile);
42450          rc = unixMapfile(pFile, -1);
42451        }
42452      }
42453      return rc;
42454    }
42455#endif
42456#ifdef SQLITE_DEBUG
42457    /* The pager calls this method to signal that it has done
42458    ** a rollback and that the database is therefore unchanged and
42459    ** it hence it is OK for the transaction change counter to be
42460    ** unchanged.
42461    */
42462    case SQLITE_FCNTL_DB_UNCHANGED: {
42463      ((unixFile*)id)->dbUpdate = 0;
42464      return SQLITE_OK;
42465    }
42466#endif
42467#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
42468    case SQLITE_FCNTL_SET_LOCKPROXYFILE:
42469    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
42470      return proxyFileControl(id,op,pArg);
42471    }
42472#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
42473
42474    case SQLITE_FCNTL_EXTERNAL_READER: {
42475#ifndef SQLITE_OMIT_WAL
42476      return unixFcntlExternalReader((unixFile*)id, (int*)pArg);
42477#else
42478      *(int*)pArg = 0;
42479      return SQLITE_OK;
42480#endif
42481    }
42482  }
42483  return SQLITE_NOTFOUND;
42484}
42485
42486/*
42487** If pFd->sectorSize is non-zero when this function is called, it is a
42488** no-op. Otherwise, the values of pFd->sectorSize and
42489** pFd->deviceCharacteristics are set according to the file-system
42490** characteristics.
42491**
42492** There are two versions of this function. One for QNX and one for all
42493** other systems.
42494*/
42495#ifndef __QNXNTO__
42496static void setDeviceCharacteristics(unixFile *pFd){
42497  assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
42498  if( pFd->sectorSize==0 ){
42499#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
42500    int res;
42501    u32 f = 0;
42502
42503    /* Check for support for F2FS atomic batch writes. */
42504    res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
42505    if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
42506      pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
42507    }
42508#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
42509
42510    /* Set the POWERSAFE_OVERWRITE flag if requested. */
42511    if( pFd->ctrlFlags & UNIXFILE_PSOW ){
42512      pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
42513    }
42514
42515    pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
42516  }
42517}
42518#else
42519#include <sys/dcmd_blk.h>
42520#include <sys/statvfs.h>
42521static void setDeviceCharacteristics(unixFile *pFile){
42522  if( pFile->sectorSize == 0 ){
42523    struct statvfs fsInfo;
42524
42525    /* Set defaults for non-supported filesystems */
42526    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
42527    pFile->deviceCharacteristics = 0;
42528    if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
42529      return;
42530    }
42531
42532    if( !strcmp(fsInfo.f_basetype, "tmp") ) {
42533      pFile->sectorSize = fsInfo.f_bsize;
42534      pFile->deviceCharacteristics =
42535        SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
42536        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
42537                                      ** the write succeeds */
42538        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
42539                                      ** so it is ordered */
42540        0;
42541    }else if( strstr(fsInfo.f_basetype, "etfs") ){
42542      pFile->sectorSize = fsInfo.f_bsize;
42543      pFile->deviceCharacteristics =
42544        /* etfs cluster size writes are atomic */
42545        (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
42546        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
42547                                      ** the write succeeds */
42548        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
42549                                      ** so it is ordered */
42550        0;
42551    }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
42552      pFile->sectorSize = fsInfo.f_bsize;
42553      pFile->deviceCharacteristics =
42554        SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
42555        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
42556                                      ** the write succeeds */
42557        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
42558                                      ** so it is ordered */
42559        0;
42560    }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
42561      pFile->sectorSize = fsInfo.f_bsize;
42562      pFile->deviceCharacteristics =
42563        /* full bitset of atomics from max sector size and smaller */
42564        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
42565        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
42566                                      ** so it is ordered */
42567        0;
42568    }else if( strstr(fsInfo.f_basetype, "dos") ){
42569      pFile->sectorSize = fsInfo.f_bsize;
42570      pFile->deviceCharacteristics =
42571        /* full bitset of atomics from max sector size and smaller */
42572        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
42573        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
42574                                      ** so it is ordered */
42575        0;
42576    }else{
42577      pFile->deviceCharacteristics =
42578        SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
42579        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
42580                                      ** the write succeeds */
42581        0;
42582    }
42583  }
42584  /* Last chance verification.  If the sector size isn't a multiple of 512
42585  ** then it isn't valid.*/
42586  if( pFile->sectorSize % 512 != 0 ){
42587    pFile->deviceCharacteristics = 0;
42588    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
42589  }
42590}
42591#endif
42592
42593/*
42594** Return the sector size in bytes of the underlying block device for
42595** the specified file. This is almost always 512 bytes, but may be
42596** larger for some devices.
42597**
42598** SQLite code assumes this function cannot fail. It also assumes that
42599** if two files are created in the same file-system directory (i.e.
42600** a database and its journal file) that the sector size will be the
42601** same for both.
42602*/
42603static int unixSectorSize(sqlite3_file *id){
42604  unixFile *pFd = (unixFile*)id;
42605  setDeviceCharacteristics(pFd);
42606  return pFd->sectorSize;
42607}
42608
42609/*
42610** Return the device characteristics for the file.
42611**
42612** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
42613** However, that choice is controversial since technically the underlying
42614** file system does not always provide powersafe overwrites.  (In other
42615** words, after a power-loss event, parts of the file that were never
42616** written might end up being altered.)  However, non-PSOW behavior is very,
42617** very rare.  And asserting PSOW makes a large reduction in the amount
42618** of required I/O for journaling, since a lot of padding is eliminated.
42619**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
42620** available to turn it off and URI query parameter available to turn it off.
42621*/
42622static int unixDeviceCharacteristics(sqlite3_file *id){
42623  unixFile *pFd = (unixFile*)id;
42624  setDeviceCharacteristics(pFd);
42625  return pFd->deviceCharacteristics;
42626}
42627
42628#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
42629
42630/*
42631** Return the system page size.
42632**
42633** This function should not be called directly by other code in this file.
42634** Instead, it should be called via macro osGetpagesize().
42635*/
42636static int unixGetpagesize(void){
42637#if OS_VXWORKS
42638  return 1024;
42639#elif defined(_BSD_SOURCE)
42640  return getpagesize();
42641#else
42642  return (int)sysconf(_SC_PAGESIZE);
42643#endif
42644}
42645
42646#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
42647
42648#ifndef SQLITE_OMIT_WAL
42649
42650/*
42651** Object used to represent an shared memory buffer.
42652**
42653** When multiple threads all reference the same wal-index, each thread
42654** has its own unixShm object, but they all point to a single instance
42655** of this unixShmNode object.  In other words, each wal-index is opened
42656** only once per process.
42657**
42658** Each unixShmNode object is connected to a single unixInodeInfo object.
42659** We could coalesce this object into unixInodeInfo, but that would mean
42660** every open file that does not use shared memory (in other words, most
42661** open files) would have to carry around this extra information.  So
42662** the unixInodeInfo object contains a pointer to this unixShmNode object
42663** and the unixShmNode object is created only when needed.
42664**
42665** unixMutexHeld() must be true when creating or destroying
42666** this object or while reading or writing the following fields:
42667**
42668**      nRef
42669**
42670** The following fields are read-only after the object is created:
42671**
42672**      hShm
42673**      zFilename
42674**
42675** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
42676** unixMutexHeld() is true when reading or writing any other field
42677** in this structure.
42678**
42679** aLock[SQLITE_SHM_NLOCK]:
42680**   This array records the various locks held by clients on each of the
42681**   SQLITE_SHM_NLOCK slots. If the aLock[] entry is set to 0, then no
42682**   locks are held by the process on this slot. If it is set to -1, then
42683**   some client holds an EXCLUSIVE lock on the locking slot. If the aLock[]
42684**   value is set to a positive value, then it is the number of shared
42685**   locks currently held on the slot.
42686**
42687** aMutex[SQLITE_SHM_NLOCK]:
42688**   Normally, when SQLITE_ENABLE_SETLK_TIMEOUT is not defined, mutex
42689**   pShmMutex is used to protect the aLock[] array and the right to
42690**   call fcntl() on unixShmNode.hShm to obtain or release locks.
42691**
42692**   If SQLITE_ENABLE_SETLK_TIMEOUT is defined though, we use an array
42693**   of mutexes - one for each locking slot. To read or write locking
42694**   slot aLock[iSlot], the caller must hold the corresponding mutex
42695**   aMutex[iSlot]. Similarly, to call fcntl() to obtain or release a
42696**   lock corresponding to slot iSlot, mutex aMutex[iSlot] must be held.
42697*/
42698struct unixShmNode {
42699  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
42700  sqlite3_mutex *pShmMutex;  /* Mutex to access this object */
42701  char *zFilename;           /* Name of the mmapped file */
42702  int hShm;                  /* Open file descriptor */
42703  int szRegion;              /* Size of shared-memory regions */
42704  u16 nRegion;               /* Size of array apRegion */
42705  u8 isReadonly;             /* True if read-only */
42706  u8 isUnlocked;             /* True if no DMS lock held */
42707  char **apRegion;           /* Array of mapped shared-memory regions */
42708  int nRef;                  /* Number of unixShm objects pointing to this */
42709  unixShm *pFirst;           /* All unixShm objects pointing to this */
42710#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42711  sqlite3_mutex *aMutex[SQLITE_SHM_NLOCK];
42712#endif
42713  int aLock[SQLITE_SHM_NLOCK];  /* # shared locks on slot, -1==excl lock */
42714#ifdef SQLITE_DEBUG
42715  u8 nextShmId;              /* Next available unixShm.id value */
42716#endif
42717};
42718
42719/*
42720** Structure used internally by this VFS to record the state of an
42721** open shared memory connection.
42722**
42723** The following fields are initialized when this object is created and
42724** are read-only thereafter:
42725**
42726**    unixShm.pShmNode
42727**    unixShm.id
42728**
42729** All other fields are read/write.  The unixShm.pShmNode->pShmMutex must
42730** be held while accessing any read/write fields.
42731*/
42732struct unixShm {
42733  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
42734  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
42735  u8 hasMutex;               /* True if holding the unixShmNode->pShmMutex */
42736  u8 id;                     /* Id of this connection within its unixShmNode */
42737  u16 sharedMask;            /* Mask of shared locks held */
42738  u16 exclMask;              /* Mask of exclusive locks held */
42739};
42740
42741/*
42742** Constants used for locking
42743*/
42744#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
42745#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
42746
42747/*
42748** Use F_GETLK to check whether or not there are any readers with open
42749** wal-mode transactions in other processes on database file pFile. If
42750** no error occurs, return SQLITE_OK and set (*piOut) to 1 if there are
42751** such transactions, or 0 otherwise. If an error occurs, return an
42752** SQLite error code. The final value of *piOut is undefined in this
42753** case.
42754*/
42755static int unixFcntlExternalReader(unixFile *pFile, int *piOut){
42756  int rc = SQLITE_OK;
42757  *piOut = 0;
42758  if( pFile->pShm){
42759    unixShmNode *pShmNode = pFile->pShm->pShmNode;
42760    struct flock f;
42761
42762    memset(&f, 0, sizeof(f));
42763    f.l_type = F_WRLCK;
42764    f.l_whence = SEEK_SET;
42765    f.l_start = UNIX_SHM_BASE + 3;
42766    f.l_len = SQLITE_SHM_NLOCK - 3;
42767
42768    sqlite3_mutex_enter(pShmNode->pShmMutex);
42769    if( osFcntl(pShmNode->hShm, F_GETLK, &f)<0 ){
42770      rc = SQLITE_IOERR_LOCK;
42771    }else{
42772      *piOut = (f.l_type!=F_UNLCK);
42773    }
42774    sqlite3_mutex_leave(pShmNode->pShmMutex);
42775  }
42776
42777  return rc;
42778}
42779
42780
42781/*
42782** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
42783**
42784** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
42785** otherwise.
42786*/
42787static int unixShmSystemLock(
42788  unixFile *pFile,       /* Open connection to the WAL file */
42789  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
42790  int ofst,              /* First byte of the locking range */
42791  int n                  /* Number of bytes to lock */
42792){
42793  unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
42794  struct flock f;        /* The posix advisory locking structure */
42795  int rc = SQLITE_OK;    /* Result code form fcntl() */
42796
42797  pShmNode = pFile->pInode->pShmNode;
42798
42799  /* Assert that the parameters are within expected range and that the
42800  ** correct mutex or mutexes are held. */
42801  assert( pShmNode->nRef>=0 );
42802  assert( (ofst==UNIX_SHM_DMS && n==1)
42803       || (ofst>=UNIX_SHM_BASE && ofst+n<=(UNIX_SHM_BASE+SQLITE_SHM_NLOCK))
42804  );
42805  if( ofst==UNIX_SHM_DMS ){
42806    assert( pShmNode->nRef>0 || unixMutexHeld() );
42807    assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
42808  }else{
42809#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42810    int ii;
42811    for(ii=ofst-UNIX_SHM_BASE; ii<ofst-UNIX_SHM_BASE+n; ii++){
42812      assert( sqlite3_mutex_held(pShmNode->aMutex[ii]) );
42813    }
42814#else
42815    assert( sqlite3_mutex_held(pShmNode->pShmMutex) );
42816    assert( pShmNode->nRef>0 );
42817#endif
42818  }
42819
42820  /* Shared locks never span more than one byte */
42821  assert( n==1 || lockType!=F_RDLCK );
42822
42823  /* Locks are within range */
42824  assert( n>=1 && n<=SQLITE_SHM_NLOCK );
42825  assert( ofst>=UNIX_SHM_BASE && ofst<=(UNIX_SHM_DMS+SQLITE_SHM_NLOCK) );
42826
42827  if( pShmNode->hShm>=0 ){
42828    int res;
42829    /* Initialize the locking parameters */
42830    f.l_type = lockType;
42831    f.l_whence = SEEK_SET;
42832    f.l_start = ofst;
42833    f.l_len = n;
42834    res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
42835    if( res==-1 ){
42836#if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && SQLITE_ENABLE_SETLK_TIMEOUT==1
42837      rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);
42838#else
42839      rc = SQLITE_BUSY;
42840#endif
42841    }
42842  }
42843
42844  /* Do debug tracing */
42845#ifdef SQLITE_DEBUG
42846  OSTRACE(("SHM-LOCK "));
42847  if( rc==SQLITE_OK ){
42848    if( lockType==F_UNLCK ){
42849      OSTRACE(("unlock %d..%d ok\n", ofst, ofst+n-1));
42850    }else if( lockType==F_RDLCK ){
42851      OSTRACE(("read-lock %d..%d ok\n", ofst, ofst+n-1));
42852    }else{
42853      assert( lockType==F_WRLCK );
42854      OSTRACE(("write-lock %d..%d ok\n", ofst, ofst+n-1));
42855    }
42856  }else{
42857    if( lockType==F_UNLCK ){
42858      OSTRACE(("unlock %d..%d failed\n", ofst, ofst+n-1));
42859    }else if( lockType==F_RDLCK ){
42860      OSTRACE(("read-lock %d..%d failed\n", ofst, ofst+n-1));
42861    }else{
42862      assert( lockType==F_WRLCK );
42863      OSTRACE(("write-lock %d..%d failed\n", ofst, ofst+n-1));
42864    }
42865  }
42866#endif
42867
42868  return rc;
42869}
42870
42871/*
42872** Return the minimum number of 32KB shm regions that should be mapped at
42873** a time, assuming that each mapping must be an integer multiple of the
42874** current system page-size.
42875**
42876** Usually, this is 1. The exception seems to be systems that are configured
42877** to use 64KB pages - in this case each mapping must cover at least two
42878** shm regions.
42879*/
42880static int unixShmRegionPerMap(void){
42881  int shmsz = 32*1024;            /* SHM region size */
42882  int pgsz = osGetpagesize();   /* System page size */
42883  assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
42884  if( pgsz<shmsz ) return 1;
42885  return pgsz/shmsz;
42886}
42887
42888/*
42889** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
42890**
42891** This is not a VFS shared-memory method; it is a utility function called
42892** by VFS shared-memory methods.
42893*/
42894static void unixShmPurge(unixFile *pFd){
42895  unixShmNode *p = pFd->pInode->pShmNode;
42896  assert( unixMutexHeld() );
42897  if( p && ALWAYS(p->nRef==0) ){
42898    int nShmPerMap = unixShmRegionPerMap();
42899    int i;
42900    assert( p->pInode==pFd->pInode );
42901    sqlite3_mutex_free(p->pShmMutex);
42902#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42903    for(i=0; i<SQLITE_SHM_NLOCK; i++){
42904      sqlite3_mutex_free(p->aMutex[i]);
42905    }
42906#endif
42907    for(i=0; i<p->nRegion; i+=nShmPerMap){
42908      if( p->hShm>=0 ){
42909        osMunmap(p->apRegion[i], p->szRegion);
42910      }else{
42911        sqlite3_free(p->apRegion[i]);
42912      }
42913    }
42914    sqlite3_free(p->apRegion);
42915    if( p->hShm>=0 ){
42916      robust_close(pFd, p->hShm, __LINE__);
42917      p->hShm = -1;
42918    }
42919    p->pInode->pShmNode = 0;
42920    sqlite3_free(p);
42921  }
42922}
42923
42924/*
42925** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
42926** take it now. Return SQLITE_OK if successful, or an SQLite error
42927** code otherwise.
42928**
42929** If the DMS cannot be locked because this is a readonly_shm=1
42930** connection and no other process already holds a lock, return
42931** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
42932*/
42933static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
42934  struct flock lock;
42935  int rc = SQLITE_OK;
42936
42937  /* Use F_GETLK to determine the locks other processes are holding
42938  ** on the DMS byte. If it indicates that another process is holding
42939  ** a SHARED lock, then this process may also take a SHARED lock
42940  ** and proceed with opening the *-shm file.
42941  **
42942  ** Or, if no other process is holding any lock, then this process
42943  ** is the first to open it. In this case take an EXCLUSIVE lock on the
42944  ** DMS byte and truncate the *-shm file to zero bytes in size. Then
42945  ** downgrade to a SHARED lock on the DMS byte.
42946  **
42947  ** If another process is holding an EXCLUSIVE lock on the DMS byte,
42948  ** return SQLITE_BUSY to the caller (it will try again). An earlier
42949  ** version of this code attempted the SHARED lock at this point. But
42950  ** this introduced a subtle race condition: if the process holding
42951  ** EXCLUSIVE failed just before truncating the *-shm file, then this
42952  ** process might open and use the *-shm file without truncating it.
42953  ** And if the *-shm file has been corrupted by a power failure or
42954  ** system crash, the database itself may also become corrupt.  */
42955  lock.l_whence = SEEK_SET;
42956  lock.l_start = UNIX_SHM_DMS;
42957  lock.l_len = 1;
42958  lock.l_type = F_WRLCK;
42959  if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
42960    rc = SQLITE_IOERR_LOCK;
42961  }else if( lock.l_type==F_UNLCK ){
42962    if( pShmNode->isReadonly ){
42963      pShmNode->isUnlocked = 1;
42964      rc = SQLITE_READONLY_CANTINIT;
42965    }else{
42966#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42967      /* Do not use a blocking lock here. If the lock cannot be obtained
42968      ** immediately, it means some other connection is truncating the
42969      ** *-shm file. And after it has done so, it will not release its
42970      ** lock, but only downgrade it to a shared lock. So no point in
42971      ** blocking here. The call below to obtain the shared DMS lock may
42972      ** use a blocking lock. */
42973      int iSaveTimeout = pDbFd->iBusyTimeout;
42974      pDbFd->iBusyTimeout = 0;
42975#endif
42976      rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
42977#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42978      pDbFd->iBusyTimeout = iSaveTimeout;
42979#endif
42980      /* The first connection to attach must truncate the -shm file.  We
42981      ** truncate to 3 bytes (an arbitrary small number, less than the
42982      ** -shm header size) rather than 0 as a system debugging aid, to
42983      ** help detect if a -shm file truncation is legitimate or is the work
42984      ** or a rogue process. */
42985      if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
42986        rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
42987      }
42988    }
42989  }else if( lock.l_type==F_WRLCK ){
42990    rc = SQLITE_BUSY;
42991  }
42992
42993  if( rc==SQLITE_OK ){
42994    assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
42995    rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
42996  }
42997  return rc;
42998}
42999
43000/*
43001** Open a shared-memory area associated with open database file pDbFd.
43002** This particular implementation uses mmapped files.
43003**
43004** The file used to implement shared-memory is in the same directory
43005** as the open database file and has the same name as the open database
43006** file with the "-shm" suffix added.  For example, if the database file
43007** is "/home/user1/config.db" then the file that is created and mmapped
43008** for shared memory will be called "/home/user1/config.db-shm".
43009**
43010** Another approach to is to use files in /dev/shm or /dev/tmp or an
43011** some other tmpfs mount. But if a file in a different directory
43012** from the database file is used, then differing access permissions
43013** or a chroot() might cause two different processes on the same
43014** database to end up using different files for shared memory -
43015** meaning that their memory would not really be shared - resulting
43016** in database corruption.  Nevertheless, this tmpfs file usage
43017** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
43018** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
43019** option results in an incompatible build of SQLite;  builds of SQLite
43020** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
43021** same database file at the same time, database corruption will likely
43022** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
43023** "unsupported" and may go away in a future SQLite release.
43024**
43025** When opening a new shared-memory file, if no other instances of that
43026** file are currently open, in this process or in other processes, then
43027** the file must be truncated to zero length or have its header cleared.
43028**
43029** If the original database file (pDbFd) is using the "unix-excl" VFS
43030** that means that an exclusive lock is held on the database file and
43031** that no other processes are able to read or write the database.  In
43032** that case, we do not really need shared memory.  No shared memory
43033** file is created.  The shared memory will be simulated with heap memory.
43034*/
43035static int unixOpenSharedMemory(unixFile *pDbFd){
43036  struct unixShm *p = 0;          /* The connection to be opened */
43037  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
43038  int rc = SQLITE_OK;             /* Result code */
43039  unixInodeInfo *pInode;          /* The inode of fd */
43040  char *zShm;             /* Name of the file used for SHM */
43041  int nShmFilename;               /* Size of the SHM filename in bytes */
43042
43043  /* Allocate space for the new unixShm object. */
43044  p = sqlite3_malloc64( sizeof(*p) );
43045  if( p==0 ) return SQLITE_NOMEM_BKPT;
43046  memset(p, 0, sizeof(*p));
43047  assert( pDbFd->pShm==0 );
43048
43049  /* Check to see if a unixShmNode object already exists. Reuse an existing
43050  ** one if present. Create a new one if necessary.
43051  */
43052  assert( unixFileMutexNotheld(pDbFd) );
43053  unixEnterMutex();
43054  pInode = pDbFd->pInode;
43055  pShmNode = pInode->pShmNode;
43056  if( pShmNode==0 ){
43057    struct stat sStat;                 /* fstat() info for database file */
43058#ifndef SQLITE_SHM_DIRECTORY
43059    const char *zBasePath = pDbFd->zPath;
43060#endif
43061
43062    /* Call fstat() to figure out the permissions on the database file. If
43063    ** a new *-shm file is created, an attempt will be made to create it
43064    ** with the same permissions.
43065    */
43066    if( osFstat(pDbFd->h, &sStat) ){
43067      rc = SQLITE_IOERR_FSTAT;
43068      goto shm_open_err;
43069    }
43070
43071#ifdef SQLITE_SHM_DIRECTORY
43072    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
43073#else
43074    nShmFilename = 6 + (int)strlen(zBasePath);
43075#endif
43076    pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
43077    if( pShmNode==0 ){
43078      rc = SQLITE_NOMEM_BKPT;
43079      goto shm_open_err;
43080    }
43081    memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
43082    zShm = pShmNode->zFilename = (char*)&pShmNode[1];
43083#ifdef SQLITE_SHM_DIRECTORY
43084    sqlite3_snprintf(nShmFilename, zShm,
43085                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
43086                     (u32)sStat.st_ino, (u32)sStat.st_dev);
43087#else
43088    sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
43089    sqlite3FileSuffix3(pDbFd->zPath, zShm);
43090#endif
43091    pShmNode->hShm = -1;
43092    pDbFd->pInode->pShmNode = pShmNode;
43093    pShmNode->pInode = pDbFd->pInode;
43094    if( sqlite3GlobalConfig.bCoreMutex ){
43095      pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
43096      if( pShmNode->pShmMutex==0 ){
43097        rc = SQLITE_NOMEM_BKPT;
43098        goto shm_open_err;
43099      }
43100#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
43101      {
43102        int ii;
43103        for(ii=0; ii<SQLITE_SHM_NLOCK; ii++){
43104          pShmNode->aMutex[ii] = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
43105          if( pShmNode->aMutex[ii]==0 ){
43106            rc = SQLITE_NOMEM_BKPT;
43107            goto shm_open_err;
43108          }
43109        }
43110      }
43111#endif
43112    }
43113
43114    if( pInode->bProcessLock==0 ){
43115      if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
43116        pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
43117                                     (sStat.st_mode&0777));
43118      }
43119      if( pShmNode->hShm<0 ){
43120        pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,
43121                                     (sStat.st_mode&0777));
43122        if( pShmNode->hShm<0 ){
43123          rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
43124          goto shm_open_err;
43125        }
43126        pShmNode->isReadonly = 1;
43127      }
43128
43129      /* If this process is running as root, make sure that the SHM file
43130      ** is owned by the same user that owns the original database.  Otherwise,
43131      ** the original owner will not be able to connect.
43132      */
43133      robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
43134
43135      rc = unixLockSharedMemory(pDbFd, pShmNode);
43136      if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
43137    }
43138  }
43139
43140  /* Make the new connection a child of the unixShmNode */
43141  p->pShmNode = pShmNode;
43142#ifdef SQLITE_DEBUG
43143  p->id = pShmNode->nextShmId++;
43144#endif
43145  pShmNode->nRef++;
43146  pDbFd->pShm = p;
43147  unixLeaveMutex();
43148
43149  /* The reference count on pShmNode has already been incremented under
43150  ** the cover of the unixEnterMutex() mutex and the pointer from the
43151  ** new (struct unixShm) object to the pShmNode has been set. All that is
43152  ** left to do is to link the new object into the linked list starting
43153  ** at pShmNode->pFirst. This must be done while holding the
43154  ** pShmNode->pShmMutex.
43155  */
43156  sqlite3_mutex_enter(pShmNode->pShmMutex);
43157  p->pNext = pShmNode->pFirst;
43158  pShmNode->pFirst = p;
43159  sqlite3_mutex_leave(pShmNode->pShmMutex);
43160  return rc;
43161
43162  /* Jump here on any error */
43163shm_open_err:
43164  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
43165  sqlite3_free(p);
43166  unixLeaveMutex();
43167  return rc;
43168}
43169
43170/*
43171** This function is called to obtain a pointer to region iRegion of the
43172** shared-memory associated with the database file fd. Shared-memory regions
43173** are numbered starting from zero. Each shared-memory region is szRegion
43174** bytes in size.
43175**
43176** If an error occurs, an error code is returned and *pp is set to NULL.
43177**
43178** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
43179** region has not been allocated (by any client, including one running in a
43180** separate process), then *pp is set to NULL and SQLITE_OK returned. If
43181** bExtend is non-zero and the requested shared-memory region has not yet
43182** been allocated, it is allocated by this function.
43183**
43184** If the shared-memory region has already been allocated or is allocated by
43185** this call as described above, then it is mapped into this processes
43186** address space (if it is not already), *pp is set to point to the mapped
43187** memory and SQLITE_OK returned.
43188*/
43189static int unixShmMap(
43190  sqlite3_file *fd,               /* Handle open on database file */
43191  int iRegion,                    /* Region to retrieve */
43192  int szRegion,                   /* Size of regions */
43193  int bExtend,                    /* True to extend file if necessary */
43194  void volatile **pp              /* OUT: Mapped memory */
43195){
43196  unixFile *pDbFd = (unixFile*)fd;
43197  unixShm *p;
43198  unixShmNode *pShmNode;
43199  int rc = SQLITE_OK;
43200  int nShmPerMap = unixShmRegionPerMap();
43201  int nReqRegion;
43202
43203  /* If the shared-memory file has not yet been opened, open it now. */
43204  if( pDbFd->pShm==0 ){
43205    rc = unixOpenSharedMemory(pDbFd);
43206    if( rc!=SQLITE_OK ) return rc;
43207  }
43208
43209  p = pDbFd->pShm;
43210  pShmNode = p->pShmNode;
43211  sqlite3_mutex_enter(pShmNode->pShmMutex);
43212  if( pShmNode->isUnlocked ){
43213    rc = unixLockSharedMemory(pDbFd, pShmNode);
43214    if( rc!=SQLITE_OK ) goto shmpage_out;
43215    pShmNode->isUnlocked = 0;
43216  }
43217  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
43218  assert( pShmNode->pInode==pDbFd->pInode );
43219  assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
43220  assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
43221
43222  /* Minimum number of regions required to be mapped. */
43223  nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
43224
43225  if( pShmNode->nRegion<nReqRegion ){
43226    char **apNew;                      /* New apRegion[] array */
43227    int nByte = nReqRegion*szRegion;   /* Minimum required file size */
43228    struct stat sStat;                 /* Used by fstat() */
43229
43230    pShmNode->szRegion = szRegion;
43231
43232    if( pShmNode->hShm>=0 ){
43233      /* The requested region is not mapped into this processes address space.
43234      ** Check to see if it has been allocated (i.e. if the wal-index file is
43235      ** large enough to contain the requested region).
43236      */
43237      if( osFstat(pShmNode->hShm, &sStat) ){
43238        rc = SQLITE_IOERR_SHMSIZE;
43239        goto shmpage_out;
43240      }
43241
43242      if( sStat.st_size<nByte ){
43243        /* The requested memory region does not exist. If bExtend is set to
43244        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
43245        */
43246        if( !bExtend ){
43247          goto shmpage_out;
43248        }
43249
43250        /* Alternatively, if bExtend is true, extend the file. Do this by
43251        ** writing a single byte to the end of each (OS) page being
43252        ** allocated or extended. Technically, we need only write to the
43253        ** last page in order to extend the file. But writing to all new
43254        ** pages forces the OS to allocate them immediately, which reduces
43255        ** the chances of SIGBUS while accessing the mapped region later on.
43256        */
43257        else{
43258          static const int pgsz = 4096;
43259          int iPg;
43260
43261          /* Write to the last byte of each newly allocated or extended page */
43262          assert( (nByte % pgsz)==0 );
43263          for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
43264            int x = 0;
43265            if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
43266              const char *zFile = pShmNode->zFilename;
43267              rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
43268              goto shmpage_out;
43269            }
43270          }
43271        }
43272      }
43273    }
43274
43275    /* Map the requested memory region into this processes address space. */
43276    apNew = (char **)sqlite3_realloc(
43277        pShmNode->apRegion, nReqRegion*sizeof(char *)
43278    );
43279    if( !apNew ){
43280      rc = SQLITE_IOERR_NOMEM_BKPT;
43281      goto shmpage_out;
43282    }
43283    pShmNode->apRegion = apNew;
43284    while( pShmNode->nRegion<nReqRegion ){
43285      int nMap = szRegion*nShmPerMap;
43286      int i;
43287      void *pMem;
43288      if( pShmNode->hShm>=0 ){
43289        pMem = osMmap(0, nMap,
43290            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
43291            MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
43292        );
43293        if( pMem==MAP_FAILED ){
43294          rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
43295          goto shmpage_out;
43296        }
43297      }else{
43298        pMem = sqlite3_malloc64(nMap);
43299        if( pMem==0 ){
43300          rc = SQLITE_NOMEM_BKPT;
43301          goto shmpage_out;
43302        }
43303        memset(pMem, 0, nMap);
43304      }
43305
43306      for(i=0; i<nShmPerMap; i++){
43307        pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
43308      }
43309      pShmNode->nRegion += nShmPerMap;
43310    }
43311  }
43312
43313shmpage_out:
43314  if( pShmNode->nRegion>iRegion ){
43315    *pp = pShmNode->apRegion[iRegion];
43316  }else{
43317    *pp = 0;
43318  }
43319  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
43320  sqlite3_mutex_leave(pShmNode->pShmMutex);
43321  return rc;
43322}
43323
43324/*
43325** Check that the pShmNode->aLock[] array comports with the locking bitmasks
43326** held by each client. Return true if it does, or false otherwise. This
43327** is to be used in an assert(). e.g.
43328**
43329**     assert( assertLockingArrayOk(pShmNode) );
43330*/
43331#ifdef SQLITE_DEBUG
43332static int assertLockingArrayOk(unixShmNode *pShmNode){
43333#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
43334  return 1;
43335#else
43336  unixShm *pX;
43337  int aLock[SQLITE_SHM_NLOCK];
43338
43339  memset(aLock, 0, sizeof(aLock));
43340  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
43341    int i;
43342    for(i=0; i<SQLITE_SHM_NLOCK; i++){
43343      if( pX->exclMask & (1<<i) ){
43344        assert( aLock[i]==0 );
43345        aLock[i] = -1;
43346      }else if( pX->sharedMask & (1<<i) ){
43347        assert( aLock[i]>=0 );
43348        aLock[i]++;
43349      }
43350    }
43351  }
43352
43353  assert( 0==memcmp(pShmNode->aLock, aLock, sizeof(aLock)) );
43354  return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0);
43355#endif
43356}
43357#endif
43358
43359/*
43360** Change the lock state for a shared-memory segment.
43361**
43362** Note that the relationship between SHARED and EXCLUSIVE locks is a little
43363** different here than in posix.  In xShmLock(), one can go from unlocked
43364** to shared and back or from unlocked to exclusive and back.  But one may
43365** not go from shared to exclusive or from exclusive to shared.
43366*/
43367static int unixShmLock(
43368  sqlite3_file *fd,          /* Database file holding the shared memory */
43369  int ofst,                  /* First lock to acquire or release */
43370  int n,                     /* Number of locks to acquire or release */
43371  int flags                  /* What to do with the lock */
43372){
43373  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
43374  unixShm *p;                           /* The shared memory being locked */
43375  unixShmNode *pShmNode;                /* The underlying file iNode */
43376  int rc = SQLITE_OK;                   /* Result code */
43377  u16 mask = (1<<(ofst+n)) - (1<<ofst); /* Mask of locks to take or release */
43378  int *aLock;
43379
43380  p = pDbFd->pShm;
43381  if( p==0 ) return SQLITE_IOERR_SHMLOCK;
43382  pShmNode = p->pShmNode;
43383  if( NEVER(pShmNode==0) ) return SQLITE_IOERR_SHMLOCK;
43384  aLock = pShmNode->aLock;
43385
43386  assert( pShmNode==pDbFd->pInode->pShmNode );
43387  assert( pShmNode->pInode==pDbFd->pInode );
43388  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
43389  assert( n>=1 );
43390  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
43391       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
43392       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
43393       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
43394  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
43395  assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
43396  assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
43397
43398  /* Check that, if this to be a blocking lock, no locks that occur later
43399  ** in the following list than the lock being obtained are already held:
43400  **
43401  **   1. Checkpointer lock (ofst==1).
43402  **   2. Write lock (ofst==0).
43403  **   3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
43404  **
43405  ** In other words, if this is a blocking lock, none of the locks that
43406  ** occur later in the above list than the lock being obtained may be
43407  ** held.
43408  **
43409  ** It is not permitted to block on the RECOVER lock.
43410  */
43411#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
43412  {
43413    u16 lockMask = (p->exclMask|p->sharedMask);
43414    assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
43415          (ofst!=2)                                   /* not RECOVER */
43416       && (ofst!=1 || lockMask==0 || lockMask==2)
43417       && (ofst!=0 || lockMask<3)
43418       && (ofst<3  || lockMask<(1<<ofst))
43419    ));
43420  }
43421#endif
43422
43423  /* Check if there is any work to do. There are three cases:
43424  **
43425  **    a) An unlock operation where there are locks to unlock,
43426  **    b) An shared lock where the requested lock is not already held
43427  **    c) An exclusive lock where the requested lock is not already held
43428  **
43429  ** The SQLite core never requests an exclusive lock that it already holds.
43430  ** This is assert()ed below.
43431  */
43432  assert( flags!=(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK)
43433       || 0==(p->exclMask & mask)
43434  );
43435  if( ((flags & SQLITE_SHM_UNLOCK) && ((p->exclMask|p->sharedMask) & mask))
43436   || (flags==(SQLITE_SHM_SHARED|SQLITE_SHM_LOCK) && 0==(p->sharedMask & mask))
43437   || (flags==(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK))
43438  ){
43439
43440    /* Take the required mutexes. In SETLK_TIMEOUT mode (blocking locks), if
43441    ** this is an attempt on an exclusive lock use sqlite3_mutex_try(). If any
43442    ** other thread is holding this mutex, then it is either holding or about
43443    ** to hold a lock exclusive to the one being requested, and we may
43444    ** therefore return SQLITE_BUSY to the caller.
43445    **
43446    ** Doing this prevents some deadlock scenarios. For example, thread 1 may
43447    ** be a checkpointer blocked waiting on the WRITER lock. And thread 2
43448    ** may be a normal SQL client upgrading to a write transaction. In this
43449    ** case thread 2 does a non-blocking request for the WRITER lock. But -
43450    ** if it were to use sqlite3_mutex_enter() then it would effectively
43451    ** become a (doomed) blocking request, as thread 2 would block until thread
43452    ** 1 obtained WRITER and released the mutex. Since thread 2 already holds
43453    ** a lock on a read-locking slot at this point, this breaks the
43454    ** anti-deadlock rules (see above).  */
43455#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
43456    int iMutex;
43457    for(iMutex=ofst; iMutex<ofst+n; iMutex++){
43458      if( flags==(SQLITE_SHM_LOCK|SQLITE_SHM_EXCLUSIVE) ){
43459        rc = sqlite3_mutex_try(pShmNode->aMutex[iMutex]);
43460        if( rc!=SQLITE_OK ) goto leave_shmnode_mutexes;
43461      }else{
43462        sqlite3_mutex_enter(pShmNode->aMutex[iMutex]);
43463      }
43464    }
43465#else
43466    sqlite3_mutex_enter(pShmNode->pShmMutex);
43467#endif
43468
43469    if( ALWAYS(rc==SQLITE_OK) ){
43470      if( flags & SQLITE_SHM_UNLOCK ){
43471        /* Case (a) - unlock.  */
43472        int bUnlock = 1;
43473        assert( (p->exclMask & p->sharedMask)==0 );
43474        assert( !(flags & SQLITE_SHM_EXCLUSIVE) || (p->exclMask & mask)==mask );
43475        assert( !(flags & SQLITE_SHM_SHARED) || (p->sharedMask & mask)==mask );
43476
43477        /* If this is a SHARED lock being unlocked, it is possible that other
43478        ** clients within this process are holding the same SHARED lock. In
43479        ** this case, set bUnlock to 0 so that the posix lock is not removed
43480        ** from the file-descriptor below.  */
43481        if( flags & SQLITE_SHM_SHARED ){
43482          assert( n==1 );
43483          assert( aLock[ofst]>=1 );
43484          if( aLock[ofst]>1 ){
43485            bUnlock = 0;
43486            aLock[ofst]--;
43487            p->sharedMask &= ~mask;
43488          }
43489        }
43490
43491        if( bUnlock ){
43492          rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
43493          if( rc==SQLITE_OK ){
43494            memset(&aLock[ofst], 0, sizeof(int)*n);
43495            p->sharedMask &= ~mask;
43496            p->exclMask &= ~mask;
43497          }
43498        }
43499      }else if( flags & SQLITE_SHM_SHARED ){
43500        /* Case (b) - a shared lock.  */
43501
43502        if( aLock[ofst]<0 ){
43503          /* An exclusive lock is held by some other connection. BUSY. */
43504          rc = SQLITE_BUSY;
43505        }else if( aLock[ofst]==0 ){
43506          rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
43507        }
43508
43509        /* Get the local shared locks */
43510        if( rc==SQLITE_OK ){
43511          p->sharedMask |= mask;
43512          aLock[ofst]++;
43513        }
43514      }else{
43515        /* Case (c) - an exclusive lock.  */
43516        int ii;
43517
43518        assert( flags==(SQLITE_SHM_LOCK|SQLITE_SHM_EXCLUSIVE) );
43519        assert( (p->sharedMask & mask)==0 );
43520        assert( (p->exclMask & mask)==0 );
43521
43522        /* Make sure no sibling connections hold locks that will block this
43523        ** lock.  If any do, return SQLITE_BUSY right away.  */
43524        for(ii=ofst; ii<ofst+n; ii++){
43525          if( aLock[ii] ){
43526            rc = SQLITE_BUSY;
43527            break;
43528          }
43529        }
43530
43531        /* Get the exclusive locks at the system level. Then if successful
43532        ** also update the in-memory values. */
43533        if( rc==SQLITE_OK ){
43534          rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
43535          if( rc==SQLITE_OK ){
43536            p->exclMask |= mask;
43537            for(ii=ofst; ii<ofst+n; ii++){
43538              aLock[ii] = -1;
43539            }
43540          }
43541        }
43542      }
43543      assert( assertLockingArrayOk(pShmNode) );
43544    }
43545
43546    /* Drop the mutexes acquired above. */
43547#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
43548  leave_shmnode_mutexes:
43549    for(iMutex--; iMutex>=ofst; iMutex--){
43550      sqlite3_mutex_leave(pShmNode->aMutex[iMutex]);
43551    }
43552#else
43553    sqlite3_mutex_leave(pShmNode->pShmMutex);
43554#endif
43555  }
43556
43557  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
43558           p->id, osGetpid(0), p->sharedMask, p->exclMask));
43559  return rc;
43560}
43561
43562/*
43563** Implement a memory barrier or memory fence on shared memory.
43564**
43565** All loads and stores begun before the barrier must complete before
43566** any load or store begun after the barrier.
43567*/
43568static void unixShmBarrier(
43569  sqlite3_file *fd                /* Database file holding the shared memory */
43570){
43571  UNUSED_PARAMETER(fd);
43572  sqlite3MemoryBarrier();         /* compiler-defined memory barrier */
43573  assert( fd->pMethods->xLock==nolockLock
43574       || unixFileMutexNotheld((unixFile*)fd)
43575  );
43576  unixEnterMutex();               /* Also mutex, for redundancy */
43577  unixLeaveMutex();
43578}
43579
43580/*
43581** Close a connection to shared-memory.  Delete the underlying
43582** storage if deleteFlag is true.
43583**
43584** If there is no shared memory associated with the connection then this
43585** routine is a harmless no-op.
43586*/
43587static int unixShmUnmap(
43588  sqlite3_file *fd,               /* The underlying database file */
43589  int deleteFlag                  /* Delete shared-memory if true */
43590){
43591  unixShm *p;                     /* The connection to be closed */
43592  unixShmNode *pShmNode;          /* The underlying shared-memory file */
43593  unixShm **pp;                   /* For looping over sibling connections */
43594  unixFile *pDbFd;                /* The underlying database file */
43595
43596  pDbFd = (unixFile*)fd;
43597  p = pDbFd->pShm;
43598  if( p==0 ) return SQLITE_OK;
43599  pShmNode = p->pShmNode;
43600
43601  assert( pShmNode==pDbFd->pInode->pShmNode );
43602  assert( pShmNode->pInode==pDbFd->pInode );
43603
43604  /* Remove connection p from the set of connections associated
43605  ** with pShmNode */
43606  sqlite3_mutex_enter(pShmNode->pShmMutex);
43607  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
43608  *pp = p->pNext;
43609
43610  /* Free the connection p */
43611  sqlite3_free(p);
43612  pDbFd->pShm = 0;
43613  sqlite3_mutex_leave(pShmNode->pShmMutex);
43614
43615  /* If pShmNode->nRef has reached 0, then close the underlying
43616  ** shared-memory file, too */
43617  assert( unixFileMutexNotheld(pDbFd) );
43618  unixEnterMutex();
43619  assert( pShmNode->nRef>0 );
43620  pShmNode->nRef--;
43621  if( pShmNode->nRef==0 ){
43622    if( deleteFlag && pShmNode->hShm>=0 ){
43623      osUnlink(pShmNode->zFilename);
43624    }
43625    unixShmPurge(pDbFd);
43626  }
43627  unixLeaveMutex();
43628
43629  return SQLITE_OK;
43630}
43631
43632
43633#else
43634# define unixShmMap     0
43635# define unixShmLock    0
43636# define unixShmBarrier 0
43637# define unixShmUnmap   0
43638#endif /* #ifndef SQLITE_OMIT_WAL */
43639
43640#if SQLITE_MAX_MMAP_SIZE>0
43641/*
43642** If it is currently memory mapped, unmap file pFd.
43643*/
43644static void unixUnmapfile(unixFile *pFd){
43645  assert( pFd->nFetchOut==0 );
43646  if( pFd->pMapRegion ){
43647    osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
43648    pFd->pMapRegion = 0;
43649    pFd->mmapSize = 0;
43650    pFd->mmapSizeActual = 0;
43651  }
43652}
43653
43654/*
43655** Attempt to set the size of the memory mapping maintained by file
43656** descriptor pFd to nNew bytes. Any existing mapping is discarded.
43657**
43658** If successful, this function sets the following variables:
43659**
43660**       unixFile.pMapRegion
43661**       unixFile.mmapSize
43662**       unixFile.mmapSizeActual
43663**
43664** If unsuccessful, an error message is logged via sqlite3_log() and
43665** the three variables above are zeroed. In this case SQLite should
43666** continue accessing the database using the xRead() and xWrite()
43667** methods.
43668*/
43669static void unixRemapfile(
43670  unixFile *pFd,                  /* File descriptor object */
43671  i64 nNew                        /* Required mapping size */
43672){
43673  const char *zErr = "mmap";
43674  int h = pFd->h;                      /* File descriptor open on db file */
43675  u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
43676  i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
43677  u8 *pNew = 0;                        /* Location of new mapping */
43678  int flags = PROT_READ;               /* Flags to pass to mmap() */
43679
43680  assert( pFd->nFetchOut==0 );
43681  assert( nNew>pFd->mmapSize );
43682  assert( nNew<=pFd->mmapSizeMax );
43683  assert( nNew>0 );
43684  assert( pFd->mmapSizeActual>=pFd->mmapSize );
43685  assert( MAP_FAILED!=0 );
43686
43687#ifdef SQLITE_MMAP_READWRITE
43688  if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
43689#endif
43690
43691  if( pOrig ){
43692#if HAVE_MREMAP
43693    i64 nReuse = pFd->mmapSize;
43694#else
43695    const int szSyspage = osGetpagesize();
43696    i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
43697#endif
43698    u8 *pReq = &pOrig[nReuse];
43699
43700    /* Unmap any pages of the existing mapping that cannot be reused. */
43701    if( nReuse!=nOrig ){
43702      osMunmap(pReq, nOrig-nReuse);
43703    }
43704
43705#if HAVE_MREMAP
43706    pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
43707    zErr = "mremap";
43708#else
43709    pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
43710    if( pNew!=MAP_FAILED ){
43711      if( pNew!=pReq ){
43712        osMunmap(pNew, nNew - nReuse);
43713        pNew = 0;
43714      }else{
43715        pNew = pOrig;
43716      }
43717    }
43718#endif
43719
43720    /* The attempt to extend the existing mapping failed. Free it. */
43721    if( pNew==MAP_FAILED || pNew==0 ){
43722      osMunmap(pOrig, nReuse);
43723    }
43724  }
43725
43726  /* If pNew is still NULL, try to create an entirely new mapping. */
43727  if( pNew==0 ){
43728    pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
43729  }
43730
43731  if( pNew==MAP_FAILED ){
43732    pNew = 0;
43733    nNew = 0;
43734    unixLogError(SQLITE_OK, zErr, pFd->zPath);
43735
43736    /* If the mmap() above failed, assume that all subsequent mmap() calls
43737    ** will probably fail too. Fall back to using xRead/xWrite exclusively
43738    ** in this case.  */
43739    pFd->mmapSizeMax = 0;
43740  }
43741  pFd->pMapRegion = (void *)pNew;
43742  pFd->mmapSize = pFd->mmapSizeActual = nNew;
43743}
43744
43745/*
43746** Memory map or remap the file opened by file-descriptor pFd (if the file
43747** is already mapped, the existing mapping is replaced by the new). Or, if
43748** there already exists a mapping for this file, and there are still
43749** outstanding xFetch() references to it, this function is a no-op.
43750**
43751** If parameter nByte is non-negative, then it is the requested size of
43752** the mapping to create. Otherwise, if nByte is less than zero, then the
43753** requested size is the size of the file on disk. The actual size of the
43754** created mapping is either the requested size or the value configured
43755** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
43756**
43757** SQLITE_OK is returned if no error occurs (even if the mapping is not
43758** recreated as a result of outstanding references) or an SQLite error
43759** code otherwise.
43760*/
43761static int unixMapfile(unixFile *pFd, i64 nMap){
43762  assert( nMap>=0 || pFd->nFetchOut==0 );
43763  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
43764  if( pFd->nFetchOut>0 ) return SQLITE_OK;
43765
43766  if( nMap<0 ){
43767    struct stat statbuf;          /* Low-level file information */
43768    if( osFstat(pFd->h, &statbuf) ){
43769      return SQLITE_IOERR_FSTAT;
43770    }
43771    nMap = statbuf.st_size;
43772  }
43773  if( nMap>pFd->mmapSizeMax ){
43774    nMap = pFd->mmapSizeMax;
43775  }
43776
43777  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
43778  if( nMap!=pFd->mmapSize ){
43779    unixRemapfile(pFd, nMap);
43780  }
43781
43782  return SQLITE_OK;
43783}
43784#endif /* SQLITE_MAX_MMAP_SIZE>0 */
43785
43786/*
43787** If possible, return a pointer to a mapping of file fd starting at offset
43788** iOff. The mapping must be valid for at least nAmt bytes.
43789**
43790** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
43791** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
43792** Finally, if an error does occur, return an SQLite error code. The final
43793** value of *pp is undefined in this case.
43794**
43795** If this function does return a pointer, the caller must eventually
43796** release the reference by calling unixUnfetch().
43797*/
43798static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
43799#if SQLITE_MAX_MMAP_SIZE>0
43800  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
43801#endif
43802  *pp = 0;
43803
43804#if SQLITE_MAX_MMAP_SIZE>0
43805  if( pFd->mmapSizeMax>0 ){
43806    /* Ensure that there is always at least a 256 byte buffer of addressable
43807    ** memory following the returned page. If the database is corrupt,
43808    ** SQLite may overread the page slightly (in practice only a few bytes,
43809    ** but 256 is safe, round, number).  */
43810    const int nEofBuffer = 256;
43811    if( pFd->pMapRegion==0 ){
43812      int rc = unixMapfile(pFd, -1);
43813      if( rc!=SQLITE_OK ) return rc;
43814    }
43815    if( pFd->mmapSize >= (iOff+nAmt+nEofBuffer) ){
43816      *pp = &((u8 *)pFd->pMapRegion)[iOff];
43817      pFd->nFetchOut++;
43818    }
43819  }
43820#endif
43821  return SQLITE_OK;
43822}
43823
43824/*
43825** If the third argument is non-NULL, then this function releases a
43826** reference obtained by an earlier call to unixFetch(). The second
43827** argument passed to this function must be the same as the corresponding
43828** argument that was passed to the unixFetch() invocation.
43829**
43830** Or, if the third argument is NULL, then this function is being called
43831** to inform the VFS layer that, according to POSIX, any existing mapping
43832** may now be invalid and should be unmapped.
43833*/
43834static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
43835#if SQLITE_MAX_MMAP_SIZE>0
43836  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
43837  UNUSED_PARAMETER(iOff);
43838
43839  /* If p==0 (unmap the entire file) then there must be no outstanding
43840  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
43841  ** then there must be at least one outstanding.  */
43842  assert( (p==0)==(pFd->nFetchOut==0) );
43843
43844  /* If p!=0, it must match the iOff value. */
43845  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
43846
43847  if( p ){
43848    pFd->nFetchOut--;
43849  }else{
43850    unixUnmapfile(pFd);
43851  }
43852
43853  assert( pFd->nFetchOut>=0 );
43854#else
43855  UNUSED_PARAMETER(fd);
43856  UNUSED_PARAMETER(p);
43857  UNUSED_PARAMETER(iOff);
43858#endif
43859  return SQLITE_OK;
43860}
43861
43862/*
43863** Here ends the implementation of all sqlite3_file methods.
43864**
43865********************** End sqlite3_file Methods *******************************
43866******************************************************************************/
43867
43868/*
43869** This division contains definitions of sqlite3_io_methods objects that
43870** implement various file locking strategies.  It also contains definitions
43871** of "finder" functions.  A finder-function is used to locate the appropriate
43872** sqlite3_io_methods object for a particular database file.  The pAppData
43873** field of the sqlite3_vfs VFS objects are initialized to be pointers to
43874** the correct finder-function for that VFS.
43875**
43876** Most finder functions return a pointer to a fixed sqlite3_io_methods
43877** object.  The only interesting finder-function is autolockIoFinder, which
43878** looks at the filesystem type and tries to guess the best locking
43879** strategy from that.
43880**
43881** For finder-function F, two objects are created:
43882**
43883**    (1) The real finder-function named "FImpt()".
43884**
43885**    (2) A constant pointer to this function named just "F".
43886**
43887**
43888** A pointer to the F pointer is used as the pAppData value for VFS
43889** objects.  We have to do this instead of letting pAppData point
43890** directly at the finder-function since C90 rules prevent a void*
43891** from be cast into a function pointer.
43892**
43893**
43894** Each instance of this macro generates two objects:
43895**
43896**   *  A constant sqlite3_io_methods object call METHOD that has locking
43897**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
43898**
43899**   *  An I/O method finder function called FINDER that returns a pointer
43900**      to the METHOD object in the previous bullet.
43901*/
43902#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)     \
43903static const sqlite3_io_methods METHOD = {                                   \
43904   VERSION,                    /* iVersion */                                \
43905   CLOSE,                      /* xClose */                                  \
43906   unixRead,                   /* xRead */                                   \
43907   unixWrite,                  /* xWrite */                                  \
43908   unixTruncate,               /* xTruncate */                               \
43909   unixSync,                   /* xSync */                                   \
43910   unixFileSize,               /* xFileSize */                               \
43911   LOCK,                       /* xLock */                                   \
43912   UNLOCK,                     /* xUnlock */                                 \
43913   CKLOCK,                     /* xCheckReservedLock */                      \
43914   unixFileControl,            /* xFileControl */                            \
43915   unixSectorSize,             /* xSectorSize */                             \
43916   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
43917   SHMMAP,                     /* xShmMap */                                 \
43918   unixShmLock,                /* xShmLock */                                \
43919   unixShmBarrier,             /* xShmBarrier */                             \
43920   unixShmUnmap,               /* xShmUnmap */                               \
43921   unixFetch,                  /* xFetch */                                  \
43922   unixUnfetch,                /* xUnfetch */                                \
43923};                                                                           \
43924static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
43925  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
43926  return &METHOD;                                                            \
43927}                                                                            \
43928static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
43929    = FINDER##Impl;
43930
43931/*
43932** Here are all of the sqlite3_io_methods objects for each of the
43933** locking strategies.  Functions that return pointers to these methods
43934** are also created.
43935*/
43936IOMETHODS(
43937  posixIoFinder,            /* Finder function name */
43938  posixIoMethods,           /* sqlite3_io_methods object name */
43939  3,                        /* shared memory and mmap are enabled */
43940  unixClose,                /* xClose method */
43941  unixLock,                 /* xLock method */
43942  unixUnlock,               /* xUnlock method */
43943  unixCheckReservedLock,    /* xCheckReservedLock method */
43944  unixShmMap                /* xShmMap method */
43945)
43946IOMETHODS(
43947  nolockIoFinder,           /* Finder function name */
43948  nolockIoMethods,          /* sqlite3_io_methods object name */
43949  3,                        /* shared memory and mmap are enabled */
43950  nolockClose,              /* xClose method */
43951  nolockLock,               /* xLock method */
43952  nolockUnlock,             /* xUnlock method */
43953  nolockCheckReservedLock,  /* xCheckReservedLock method */
43954  0                         /* xShmMap method */
43955)
43956IOMETHODS(
43957  dotlockIoFinder,          /* Finder function name */
43958  dotlockIoMethods,         /* sqlite3_io_methods object name */
43959  1,                        /* shared memory is disabled */
43960  dotlockClose,             /* xClose method */
43961  dotlockLock,              /* xLock method */
43962  dotlockUnlock,            /* xUnlock method */
43963  dotlockCheckReservedLock, /* xCheckReservedLock method */
43964  0                         /* xShmMap method */
43965)
43966
43967#if SQLITE_ENABLE_LOCKING_STYLE
43968IOMETHODS(
43969  flockIoFinder,            /* Finder function name */
43970  flockIoMethods,           /* sqlite3_io_methods object name */
43971  1,                        /* shared memory is disabled */
43972  flockClose,               /* xClose method */
43973  flockLock,                /* xLock method */
43974  flockUnlock,              /* xUnlock method */
43975  flockCheckReservedLock,   /* xCheckReservedLock method */
43976  0                         /* xShmMap method */
43977)
43978#endif
43979
43980#if OS_VXWORKS
43981IOMETHODS(
43982  semIoFinder,              /* Finder function name */
43983  semIoMethods,             /* sqlite3_io_methods object name */
43984  1,                        /* shared memory is disabled */
43985  semXClose,                /* xClose method */
43986  semXLock,                 /* xLock method */
43987  semXUnlock,               /* xUnlock method */
43988  semXCheckReservedLock,    /* xCheckReservedLock method */
43989  0                         /* xShmMap method */
43990)
43991#endif
43992
43993#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
43994IOMETHODS(
43995  afpIoFinder,              /* Finder function name */
43996  afpIoMethods,             /* sqlite3_io_methods object name */
43997  1,                        /* shared memory is disabled */
43998  afpClose,                 /* xClose method */
43999  afpLock,                  /* xLock method */
44000  afpUnlock,                /* xUnlock method */
44001  afpCheckReservedLock,     /* xCheckReservedLock method */
44002  0                         /* xShmMap method */
44003)
44004#endif
44005
44006/*
44007** The proxy locking method is a "super-method" in the sense that it
44008** opens secondary file descriptors for the conch and lock files and
44009** it uses proxy, dot-file, AFP, and flock() locking methods on those
44010** secondary files.  For this reason, the division that implements
44011** proxy locking is located much further down in the file.  But we need
44012** to go ahead and define the sqlite3_io_methods and finder function
44013** for proxy locking here.  So we forward declare the I/O methods.
44014*/
44015#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
44016static int proxyClose(sqlite3_file*);
44017static int proxyLock(sqlite3_file*, int);
44018static int proxyUnlock(sqlite3_file*, int);
44019static int proxyCheckReservedLock(sqlite3_file*, int*);
44020IOMETHODS(
44021  proxyIoFinder,            /* Finder function name */
44022  proxyIoMethods,           /* sqlite3_io_methods object name */
44023  1,                        /* shared memory is disabled */
44024  proxyClose,               /* xClose method */
44025  proxyLock,                /* xLock method */
44026  proxyUnlock,              /* xUnlock method */
44027  proxyCheckReservedLock,   /* xCheckReservedLock method */
44028  0                         /* xShmMap method */
44029)
44030#endif
44031
44032/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
44033#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
44034IOMETHODS(
44035  nfsIoFinder,               /* Finder function name */
44036  nfsIoMethods,              /* sqlite3_io_methods object name */
44037  1,                         /* shared memory is disabled */
44038  unixClose,                 /* xClose method */
44039  unixLock,                  /* xLock method */
44040  nfsUnlock,                 /* xUnlock method */
44041  unixCheckReservedLock,     /* xCheckReservedLock method */
44042  0                          /* xShmMap method */
44043)
44044#endif
44045
44046#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
44047/*
44048** This "finder" function attempts to determine the best locking strategy
44049** for the database file "filePath".  It then returns the sqlite3_io_methods
44050** object that implements that strategy.
44051**
44052** This is for MacOSX only.
44053*/
44054static const sqlite3_io_methods *autolockIoFinderImpl(
44055  const char *filePath,    /* name of the database file */
44056  unixFile *pNew           /* open file object for the database file */
44057){
44058  static const struct Mapping {
44059    const char *zFilesystem;              /* Filesystem type name */
44060    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
44061  } aMap[] = {
44062    { "hfs",    &posixIoMethods },
44063    { "ufs",    &posixIoMethods },
44064    { "afpfs",  &afpIoMethods },
44065    { "smbfs",  &afpIoMethods },
44066    { "webdav", &nolockIoMethods },
44067    { 0, 0 }
44068  };
44069  int i;
44070  struct statfs fsInfo;
44071  struct flock lockInfo;
44072
44073  if( !filePath ){
44074    /* If filePath==NULL that means we are dealing with a transient file
44075    ** that does not need to be locked. */
44076    return &nolockIoMethods;
44077  }
44078  if( statfs(filePath, &fsInfo) != -1 ){
44079    if( fsInfo.f_flags & MNT_RDONLY ){
44080      return &nolockIoMethods;
44081    }
44082    for(i=0; aMap[i].zFilesystem; i++){
44083      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
44084        return aMap[i].pMethods;
44085      }
44086    }
44087  }
44088
44089  /* Default case. Handles, amongst others, "nfs".
44090  ** Test byte-range lock using fcntl(). If the call succeeds,
44091  ** assume that the file-system supports POSIX style locks.
44092  */
44093  lockInfo.l_len = 1;
44094  lockInfo.l_start = 0;
44095  lockInfo.l_whence = SEEK_SET;
44096  lockInfo.l_type = F_RDLCK;
44097  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
44098    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
44099      return &nfsIoMethods;
44100    } else {
44101      return &posixIoMethods;
44102    }
44103  }else{
44104    return &dotlockIoMethods;
44105  }
44106}
44107static const sqlite3_io_methods
44108  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
44109
44110#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
44111
44112#if OS_VXWORKS
44113/*
44114** This "finder" function for VxWorks checks to see if posix advisory
44115** locking works.  If it does, then that is what is used.  If it does not
44116** work, then fallback to named semaphore locking.
44117*/
44118static const sqlite3_io_methods *vxworksIoFinderImpl(
44119  const char *filePath,    /* name of the database file */
44120  unixFile *pNew           /* the open file object */
44121){
44122  struct flock lockInfo;
44123
44124  if( !filePath ){
44125    /* If filePath==NULL that means we are dealing with a transient file
44126    ** that does not need to be locked. */
44127    return &nolockIoMethods;
44128  }
44129
44130  /* Test if fcntl() is supported and use POSIX style locks.
44131  ** Otherwise fall back to the named semaphore method.
44132  */
44133  lockInfo.l_len = 1;
44134  lockInfo.l_start = 0;
44135  lockInfo.l_whence = SEEK_SET;
44136  lockInfo.l_type = F_RDLCK;
44137  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
44138    return &posixIoMethods;
44139  }else{
44140    return &semIoMethods;
44141  }
44142}
44143static const sqlite3_io_methods
44144  *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
44145
44146#endif /* OS_VXWORKS */
44147
44148/*
44149** An abstract type for a pointer to an IO method finder function:
44150*/
44151typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
44152
44153
44154/****************************************************************************
44155**************************** sqlite3_vfs methods ****************************
44156**
44157** This division contains the implementation of methods on the
44158** sqlite3_vfs object.
44159*/
44160
44161/*
44162** Initialize the contents of the unixFile structure pointed to by pId.
44163*/
44164static int fillInUnixFile(
44165  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
44166  int h,                  /* Open file descriptor of file being opened */
44167  sqlite3_file *pId,      /* Write to the unixFile structure here */
44168  const char *zFilename,  /* Name of the file being opened */
44169  int ctrlFlags           /* Zero or more UNIXFILE_* values */
44170){
44171  const sqlite3_io_methods *pLockingStyle;
44172  unixFile *pNew = (unixFile *)pId;
44173  int rc = SQLITE_OK;
44174
44175  assert( pNew->pInode==NULL );
44176
44177  /* No locking occurs in temporary files */
44178  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
44179
44180  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
44181  pNew->h = h;
44182  pNew->pVfs = pVfs;
44183  pNew->zPath = zFilename;
44184  pNew->ctrlFlags = (u8)ctrlFlags;
44185#if SQLITE_MAX_MMAP_SIZE>0
44186  pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
44187#endif
44188  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
44189                           "psow", SQLITE_POWERSAFE_OVERWRITE) ){
44190    pNew->ctrlFlags |= UNIXFILE_PSOW;
44191  }
44192  if( strcmp(pVfs->zName,"unix-excl")==0 ){
44193    pNew->ctrlFlags |= UNIXFILE_EXCL;
44194  }
44195
44196#if OS_VXWORKS
44197  pNew->pId = vxworksFindFileId(zFilename);
44198  if( pNew->pId==0 ){
44199    ctrlFlags |= UNIXFILE_NOLOCK;
44200    rc = SQLITE_NOMEM_BKPT;
44201  }
44202#endif
44203
44204  if( ctrlFlags & UNIXFILE_NOLOCK ){
44205    pLockingStyle = &nolockIoMethods;
44206  }else{
44207    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
44208#if SQLITE_ENABLE_LOCKING_STYLE
44209    /* Cache zFilename in the locking context (AFP and dotlock override) for
44210    ** proxyLock activation is possible (remote proxy is based on db name)
44211    ** zFilename remains valid until file is closed, to support */
44212    pNew->lockingContext = (void*)zFilename;
44213#endif
44214  }
44215
44216  if( pLockingStyle == &posixIoMethods
44217#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
44218    || pLockingStyle == &nfsIoMethods
44219#endif
44220  ){
44221    unixEnterMutex();
44222    rc = findInodeInfo(pNew, &pNew->pInode);
44223    if( rc!=SQLITE_OK ){
44224      /* If an error occurred in findInodeInfo(), close the file descriptor
44225      ** immediately, before releasing the mutex. findInodeInfo() may fail
44226      ** in two scenarios:
44227      **
44228      **   (a) A call to fstat() failed.
44229      **   (b) A malloc failed.
44230      **
44231      ** Scenario (b) may only occur if the process is holding no other
44232      ** file descriptors open on the same file. If there were other file
44233      ** descriptors on this file, then no malloc would be required by
44234      ** findInodeInfo(). If this is the case, it is quite safe to close
44235      ** handle h - as it is guaranteed that no posix locks will be released
44236      ** by doing so.
44237      **
44238      ** If scenario (a) caused the error then things are not so safe. The
44239      ** implicit assumption here is that if fstat() fails, things are in
44240      ** such bad shape that dropping a lock or two doesn't matter much.
44241      */
44242      robust_close(pNew, h, __LINE__);
44243      h = -1;
44244    }
44245    unixLeaveMutex();
44246  }
44247
44248#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
44249  else if( pLockingStyle == &afpIoMethods ){
44250    /* AFP locking uses the file path so it needs to be included in
44251    ** the afpLockingContext.
44252    */
44253    afpLockingContext *pCtx;
44254    pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
44255    if( pCtx==0 ){
44256      rc = SQLITE_NOMEM_BKPT;
44257    }else{
44258      /* NB: zFilename exists and remains valid until the file is closed
44259      ** according to requirement F11141.  So we do not need to make a
44260      ** copy of the filename. */
44261      pCtx->dbPath = zFilename;
44262      pCtx->reserved = 0;
44263      srandomdev();
44264      unixEnterMutex();
44265      rc = findInodeInfo(pNew, &pNew->pInode);
44266      if( rc!=SQLITE_OK ){
44267        sqlite3_free(pNew->lockingContext);
44268        robust_close(pNew, h, __LINE__);
44269        h = -1;
44270      }
44271      unixLeaveMutex();
44272    }
44273  }
44274#endif
44275
44276  else if( pLockingStyle == &dotlockIoMethods ){
44277    /* Dotfile locking uses the file path so it needs to be included in
44278    ** the dotlockLockingContext
44279    */
44280    char *zLockFile;
44281    int nFilename;
44282    assert( zFilename!=0 );
44283    nFilename = (int)strlen(zFilename) + 6;
44284    zLockFile = (char *)sqlite3_malloc64(nFilename);
44285    if( zLockFile==0 ){
44286      rc = SQLITE_NOMEM_BKPT;
44287    }else{
44288      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
44289    }
44290    pNew->lockingContext = zLockFile;
44291  }
44292
44293#if OS_VXWORKS
44294  else if( pLockingStyle == &semIoMethods ){
44295    /* Named semaphore locking uses the file path so it needs to be
44296    ** included in the semLockingContext
44297    */
44298    unixEnterMutex();
44299    rc = findInodeInfo(pNew, &pNew->pInode);
44300    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
44301      char *zSemName = pNew->pInode->aSemName;
44302      int n;
44303      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
44304                       pNew->pId->zCanonicalName);
44305      for( n=1; zSemName[n]; n++ )
44306        if( zSemName[n]=='/' ) zSemName[n] = '_';
44307      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
44308      if( pNew->pInode->pSem == SEM_FAILED ){
44309        rc = SQLITE_NOMEM_BKPT;
44310        pNew->pInode->aSemName[0] = '\0';
44311      }
44312    }
44313    unixLeaveMutex();
44314  }
44315#endif
44316
44317  storeLastErrno(pNew, 0);
44318#if OS_VXWORKS
44319  if( rc!=SQLITE_OK ){
44320    if( h>=0 ) robust_close(pNew, h, __LINE__);
44321    h = -1;
44322    osUnlink(zFilename);
44323    pNew->ctrlFlags |= UNIXFILE_DELETE;
44324  }
44325#endif
44326  if( rc!=SQLITE_OK ){
44327    if( h>=0 ) robust_close(pNew, h, __LINE__);
44328  }else{
44329    pId->pMethods = pLockingStyle;
44330    OpenCounter(+1);
44331    verifyDbFile(pNew);
44332  }
44333  return rc;
44334}
44335
44336/*
44337** Directories to consider for temp files.
44338*/
44339static const char *azTempDirs[] = {
44340  0,
44341  0,
44342  "/var/tmp",
44343  "/usr/tmp",
44344  "/tmp",
44345  "."
44346};
44347
44348/*
44349** Initialize first two members of azTempDirs[] array.
44350*/
44351static void unixTempFileInit(void){
44352  azTempDirs[0] = getenv("SQLITE_TMPDIR");
44353  azTempDirs[1] = getenv("TMPDIR");
44354}
44355
44356/*
44357** Return the name of a directory in which to put temporary files.
44358** If no suitable temporary file directory can be found, return NULL.
44359*/
44360static const char *unixTempFileDir(void){
44361  unsigned int i = 0;
44362  struct stat buf;
44363  const char *zDir = sqlite3_temp_directory;
44364
44365  while(1){
44366    if( zDir!=0
44367     && osStat(zDir, &buf)==0
44368     && S_ISDIR(buf.st_mode)
44369     && osAccess(zDir, 03)==0
44370    ){
44371      return zDir;
44372    }
44373    if( i>=sizeof(azTempDirs)/sizeof(azTempDirs[0]) ) break;
44374    zDir = azTempDirs[i++];
44375  }
44376  return 0;
44377}
44378
44379/*
44380** Create a temporary file name in zBuf.  zBuf must be allocated
44381** by the calling process and must be big enough to hold at least
44382** pVfs->mxPathname bytes.
44383*/
44384static int unixGetTempname(int nBuf, char *zBuf){
44385  const char *zDir;
44386  int iLimit = 0;
44387  int rc = SQLITE_OK;
44388
44389  /* It's odd to simulate an io-error here, but really this is just
44390  ** using the io-error infrastructure to test that SQLite handles this
44391  ** function failing.
44392  */
44393  zBuf[0] = 0;
44394  SimulateIOError( return SQLITE_IOERR );
44395
44396  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
44397  zDir = unixTempFileDir();
44398  if( zDir==0 ){
44399    rc = SQLITE_IOERR_GETTEMPPATH;
44400  }else{
44401    do{
44402      u64 r;
44403      sqlite3_randomness(sizeof(r), &r);
44404      assert( nBuf>2 );
44405      zBuf[nBuf-2] = 0;
44406      sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
44407                       zDir, r, 0);
44408      if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ){
44409        rc = SQLITE_ERROR;
44410        break;
44411      }
44412    }while( osAccess(zBuf,0)==0 );
44413  }
44414  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
44415  return rc;
44416}
44417
44418#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
44419/*
44420** Routine to transform a unixFile into a proxy-locking unixFile.
44421** Implementation in the proxy-lock division, but used by unixOpen()
44422** if SQLITE_PREFER_PROXY_LOCKING is defined.
44423*/
44424static int proxyTransformUnixFile(unixFile*, const char*);
44425#endif
44426
44427/*
44428** Search for an unused file descriptor that was opened on the database
44429** file (not a journal or super-journal file) identified by pathname
44430** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
44431** argument to this function.
44432**
44433** Such a file descriptor may exist if a database connection was closed
44434** but the associated file descriptor could not be closed because some
44435** other file descriptor open on the same file is holding a file-lock.
44436** Refer to comments in the unixClose() function and the lengthy comment
44437** describing "Posix Advisory Locking" at the start of this file for
44438** further details. Also, ticket #4018.
44439**
44440** If a suitable file descriptor is found, then it is returned. If no
44441** such file descriptor is located, -1 is returned.
44442*/
44443static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
44444  UnixUnusedFd *pUnused = 0;
44445
44446  /* Do not search for an unused file descriptor on vxworks. Not because
44447  ** vxworks would not benefit from the change (it might, we're not sure),
44448  ** but because no way to test it is currently available. It is better
44449  ** not to risk breaking vxworks support for the sake of such an obscure
44450  ** feature.  */
44451#if !OS_VXWORKS
44452  struct stat sStat;                   /* Results of stat() call */
44453
44454  unixEnterMutex();
44455
44456  /* A stat() call may fail for various reasons. If this happens, it is
44457  ** almost certain that an open() call on the same path will also fail.
44458  ** For this reason, if an error occurs in the stat() call here, it is
44459  ** ignored and -1 is returned. The caller will try to open a new file
44460  ** descriptor on the same path, fail, and return an error to SQLite.
44461  **
44462  ** Even if a subsequent open() call does succeed, the consequences of
44463  ** not searching for a reusable file descriptor are not dire.  */
44464  if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
44465    unixInodeInfo *pInode;
44466
44467    pInode = inodeList;
44468    while( pInode && (pInode->fileId.dev!=sStat.st_dev
44469                     || pInode->fileId.ino!=(u64)sStat.st_ino) ){
44470       pInode = pInode->pNext;
44471    }
44472    if( pInode ){
44473      UnixUnusedFd **pp;
44474      assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
44475      sqlite3_mutex_enter(pInode->pLockMutex);
44476      flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
44477      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
44478      pUnused = *pp;
44479      if( pUnused ){
44480        *pp = pUnused->pNext;
44481      }
44482      sqlite3_mutex_leave(pInode->pLockMutex);
44483    }
44484  }
44485  unixLeaveMutex();
44486#endif    /* if !OS_VXWORKS */
44487  return pUnused;
44488}
44489
44490/*
44491** Find the mode, uid and gid of file zFile.
44492*/
44493static int getFileMode(
44494  const char *zFile,              /* File name */
44495  mode_t *pMode,                  /* OUT: Permissions of zFile */
44496  uid_t *pUid,                    /* OUT: uid of zFile. */
44497  gid_t *pGid                     /* OUT: gid of zFile. */
44498){
44499  struct stat sStat;              /* Output of stat() on database file */
44500  int rc = SQLITE_OK;
44501  if( 0==osStat(zFile, &sStat) ){
44502    *pMode = sStat.st_mode & 0777;
44503    *pUid = sStat.st_uid;
44504    *pGid = sStat.st_gid;
44505  }else{
44506    rc = SQLITE_IOERR_FSTAT;
44507  }
44508  return rc;
44509}
44510
44511/*
44512** This function is called by unixOpen() to determine the unix permissions
44513** to create new files with. If no error occurs, then SQLITE_OK is returned
44514** and a value suitable for passing as the third argument to open(2) is
44515** written to *pMode. If an IO error occurs, an SQLite error code is
44516** returned and the value of *pMode is not modified.
44517**
44518** In most cases, this routine sets *pMode to 0, which will become
44519** an indication to robust_open() to create the file using
44520** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
44521** But if the file being opened is a WAL or regular journal file, then
44522** this function queries the file-system for the permissions on the
44523** corresponding database file and sets *pMode to this value. Whenever
44524** possible, WAL and journal files are created using the same permissions
44525** as the associated database file.
44526**
44527** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
44528** original filename is unavailable.  But 8_3_NAMES is only used for
44529** FAT filesystems and permissions do not matter there, so just use
44530** the default permissions.  In 8_3_NAMES mode, leave *pMode set to zero.
44531*/
44532static int findCreateFileMode(
44533  const char *zPath,              /* Path of file (possibly) being created */
44534  int flags,                      /* Flags passed as 4th argument to xOpen() */
44535  mode_t *pMode,                  /* OUT: Permissions to open file with */
44536  uid_t *pUid,                    /* OUT: uid to set on the file */
44537  gid_t *pGid                     /* OUT: gid to set on the file */
44538){
44539  int rc = SQLITE_OK;             /* Return Code */
44540  *pMode = 0;
44541  *pUid = 0;
44542  *pGid = 0;
44543  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
44544    char zDb[MAX_PATHNAME+1];     /* Database file path */
44545    int nDb;                      /* Number of valid bytes in zDb */
44546
44547    /* zPath is a path to a WAL or journal file. The following block derives
44548    ** the path to the associated database file from zPath. This block handles
44549    ** the following naming conventions:
44550    **
44551    **   "<path to db>-journal"
44552    **   "<path to db>-wal"
44553    **   "<path to db>-journalNN"
44554    **   "<path to db>-walNN"
44555    **
44556    ** where NN is a decimal number. The NN naming schemes are
44557    ** used by the test_multiplex.c module.
44558    **
44559    ** In normal operation, the journal file name will always contain
44560    ** a '-' character.  However in 8+3 filename mode, or if a corrupt
44561    ** rollback journal specifies a super-journal with a goofy name, then
44562    ** the '-' might be missing or the '-' might be the first character in
44563    ** the filename.  In that case, just return SQLITE_OK with *pMode==0.
44564    */
44565    nDb = sqlite3Strlen30(zPath) - 1;
44566    while( nDb>0 && zPath[nDb]!='.' ){
44567      if( zPath[nDb]=='-' ){
44568        memcpy(zDb, zPath, nDb);
44569        zDb[nDb] = '\0';
44570        rc = getFileMode(zDb, pMode, pUid, pGid);
44571        break;
44572      }
44573      nDb--;
44574    }
44575  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
44576    *pMode = 0600;
44577  }else if( flags & SQLITE_OPEN_URI ){
44578    /* If this is a main database file and the file was opened using a URI
44579    ** filename, check for the "modeof" parameter. If present, interpret
44580    ** its value as a filename and try to copy the mode, uid and gid from
44581    ** that file.  */
44582    const char *z = sqlite3_uri_parameter(zPath, "modeof");
44583    if( z ){
44584      rc = getFileMode(z, pMode, pUid, pGid);
44585    }
44586  }
44587  return rc;
44588}
44589
44590/*
44591** Open the file zPath.
44592**
44593** Previously, the SQLite OS layer used three functions in place of this
44594** one:
44595**
44596**     sqlite3OsOpenReadWrite();
44597**     sqlite3OsOpenReadOnly();
44598**     sqlite3OsOpenExclusive();
44599**
44600** These calls correspond to the following combinations of flags:
44601**
44602**     ReadWrite() ->     (READWRITE | CREATE)
44603**     ReadOnly()  ->     (READONLY)
44604**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
44605**
44606** The old OpenExclusive() accepted a boolean argument - "delFlag". If
44607** true, the file was configured to be automatically deleted when the
44608** file handle closed. To achieve the same effect using this new
44609** interface, add the DELETEONCLOSE flag to those specified above for
44610** OpenExclusive().
44611*/
44612static int unixOpen(
44613  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
44614  const char *zPath,           /* Pathname of file to be opened */
44615  sqlite3_file *pFile,         /* The file descriptor to be filled in */
44616  int flags,                   /* Input flags to control the opening */
44617  int *pOutFlags               /* Output flags returned to SQLite core */
44618){
44619  unixFile *p = (unixFile *)pFile;
44620  int fd = -1;                   /* File descriptor returned by open() */
44621  int openFlags = 0;             /* Flags to pass to open() */
44622  int eType = flags&0x0FFF00;  /* Type of file to open */
44623  int noLock;                    /* True to omit locking primitives */
44624  int rc = SQLITE_OK;            /* Function Return Code */
44625  int ctrlFlags = 0;             /* UNIXFILE_* flags */
44626
44627  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
44628  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
44629  int isCreate     = (flags & SQLITE_OPEN_CREATE);
44630  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
44631  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
44632#if SQLITE_ENABLE_LOCKING_STYLE
44633  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
44634#endif
44635#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
44636  struct statfs fsInfo;
44637#endif
44638
44639  /* If creating a super- or main-file journal, this function will open
44640  ** a file-descriptor on the directory too. The first time unixSync()
44641  ** is called the directory file descriptor will be fsync()ed and close()d.
44642  */
44643  int isNewJrnl = (isCreate && (
44644        eType==SQLITE_OPEN_SUPER_JOURNAL
44645     || eType==SQLITE_OPEN_MAIN_JOURNAL
44646     || eType==SQLITE_OPEN_WAL
44647  ));
44648
44649  /* If argument zPath is a NULL pointer, this function is required to open
44650  ** a temporary file. Use this buffer to store the file name in.
44651  */
44652  char zTmpname[MAX_PATHNAME+2];
44653  const char *zName = zPath;
44654
44655  /* Check the following statements are true:
44656  **
44657  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
44658  **   (b) if CREATE is set, then READWRITE must also be set, and
44659  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
44660  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
44661  */
44662  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
44663  assert(isCreate==0 || isReadWrite);
44664  assert(isExclusive==0 || isCreate);
44665  assert(isDelete==0 || isCreate);
44666
44667  /* The main DB, main journal, WAL file and super-journal are never
44668  ** automatically deleted. Nor are they ever temporary files.  */
44669  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
44670  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
44671  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL );
44672  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
44673
44674  /* Assert that the upper layer has set one of the "file-type" flags. */
44675  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
44676       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
44677       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_SUPER_JOURNAL
44678       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
44679  );
44680
44681  /* Detect a pid change and reset the PRNG.  There is a race condition
44682  ** here such that two or more threads all trying to open databases at
44683  ** the same instant might all reset the PRNG.  But multiple resets
44684  ** are harmless.
44685  */
44686  if( randomnessPid!=osGetpid(0) ){
44687    randomnessPid = osGetpid(0);
44688    sqlite3_randomness(0,0);
44689  }
44690  memset(p, 0, sizeof(unixFile));
44691
44692#ifdef SQLITE_ASSERT_NO_FILES
44693  /* Applications that never read or write a persistent disk files */
44694  assert( zName==0 );
44695#endif
44696
44697  if( eType==SQLITE_OPEN_MAIN_DB ){
44698    UnixUnusedFd *pUnused;
44699    pUnused = findReusableFd(zName, flags);
44700    if( pUnused ){
44701      fd = pUnused->fd;
44702    }else{
44703      pUnused = sqlite3_malloc64(sizeof(*pUnused));
44704      if( !pUnused ){
44705        return SQLITE_NOMEM_BKPT;
44706      }
44707    }
44708    p->pPreallocatedUnused = pUnused;
44709
44710    /* Database filenames are double-zero terminated if they are not
44711    ** URIs with parameters.  Hence, they can always be passed into
44712    ** sqlite3_uri_parameter(). */
44713    assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
44714
44715  }else if( !zName ){
44716    /* If zName is NULL, the upper layer is requesting a temp file. */
44717    assert(isDelete && !isNewJrnl);
44718    rc = unixGetTempname(pVfs->mxPathname, zTmpname);
44719    if( rc!=SQLITE_OK ){
44720      return rc;
44721    }
44722    zName = zTmpname;
44723
44724    /* Generated temporary filenames are always double-zero terminated
44725    ** for use by sqlite3_uri_parameter(). */
44726    assert( zName[strlen(zName)+1]==0 );
44727  }
44728
44729  /* Determine the value of the flags parameter passed to POSIX function
44730  ** open(). These must be calculated even if open() is not called, as
44731  ** they may be stored as part of the file handle and used by the
44732  ** 'conch file' locking functions later on.  */
44733  if( isReadonly )  openFlags |= O_RDONLY;
44734  if( isReadWrite ) openFlags |= O_RDWR;
44735  if( isCreate )    openFlags |= O_CREAT;
44736  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
44737  openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW);
44738
44739  if( fd<0 ){
44740    mode_t openMode;              /* Permissions to create file with */
44741    uid_t uid;                    /* Userid for the file */
44742    gid_t gid;                    /* Groupid for the file */
44743    rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
44744    if( rc!=SQLITE_OK ){
44745      assert( !p->pPreallocatedUnused );
44746      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
44747      return rc;
44748    }
44749    fd = robust_open(zName, openFlags, openMode);
44750    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
44751    assert( !isExclusive || (openFlags & O_CREAT)!=0 );
44752    if( fd<0 ){
44753      if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
44754        /* If unable to create a journal because the directory is not
44755        ** writable, change the error code to indicate that. */
44756        rc = SQLITE_READONLY_DIRECTORY;
44757      }else if( errno!=EISDIR && isReadWrite ){
44758        /* Failed to open the file for read/write access. Try read-only. */
44759        UnixUnusedFd *pReadonly = 0;
44760        flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
44761        openFlags &= ~(O_RDWR|O_CREAT);
44762        flags |= SQLITE_OPEN_READONLY;
44763        openFlags |= O_RDONLY;
44764        isReadonly = 1;
44765        pReadonly = findReusableFd(zName, flags);
44766        if( pReadonly ){
44767          fd = pReadonly->fd;
44768          sqlite3_free(pReadonly);
44769        }else{
44770          fd = robust_open(zName, openFlags, openMode);
44771        }
44772      }
44773    }
44774    if( fd<0 ){
44775      int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
44776      if( rc==SQLITE_OK ) rc = rc2;
44777      goto open_finished;
44778    }
44779
44780    /* The owner of the rollback journal or WAL file should always be the
44781    ** same as the owner of the database file.  Try to ensure that this is
44782    ** the case.  The chown() system call will be a no-op if the current
44783    ** process lacks root privileges, be we should at least try.  Without
44784    ** this step, if a root process opens a database file, it can leave
44785    ** behinds a journal/WAL that is owned by root and hence make the
44786    ** database inaccessible to unprivileged processes.
44787    **
44788    ** If openMode==0, then that means uid and gid are not set correctly
44789    ** (probably because SQLite is configured to use 8+3 filename mode) and
44790    ** in that case we do not want to attempt the chown().
44791    */
44792    if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){
44793      robustFchown(fd, uid, gid);
44794    }
44795  }
44796  assert( fd>=0 );
44797  if( pOutFlags ){
44798    *pOutFlags = flags;
44799  }
44800
44801  if( p->pPreallocatedUnused ){
44802    p->pPreallocatedUnused->fd = fd;
44803    p->pPreallocatedUnused->flags =
44804                          flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
44805  }
44806
44807  if( isDelete ){
44808#if OS_VXWORKS
44809    zPath = zName;
44810#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
44811    zPath = sqlite3_mprintf("%s", zName);
44812    if( zPath==0 ){
44813      robust_close(p, fd, __LINE__);
44814      return SQLITE_NOMEM_BKPT;
44815    }
44816#else
44817    osUnlink(zName);
44818#endif
44819  }
44820#if SQLITE_ENABLE_LOCKING_STYLE
44821  else{
44822    p->openFlags = openFlags;
44823  }
44824#endif
44825
44826#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
44827  if( fstatfs(fd, &fsInfo) == -1 ){
44828    storeLastErrno(p, errno);
44829    robust_close(p, fd, __LINE__);
44830    return SQLITE_IOERR_ACCESS;
44831  }
44832  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
44833    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
44834  }
44835  if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
44836    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
44837  }
44838#endif
44839
44840  /* Set up appropriate ctrlFlags */
44841  if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
44842  if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
44843  noLock = eType!=SQLITE_OPEN_MAIN_DB;
44844  if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
44845  if( isNewJrnl )               ctrlFlags |= UNIXFILE_DIRSYNC;
44846  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
44847
44848#if SQLITE_ENABLE_LOCKING_STYLE
44849#if SQLITE_PREFER_PROXY_LOCKING
44850  isAutoProxy = 1;
44851#endif
44852  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
44853    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
44854    int useProxy = 0;
44855
44856    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
44857    ** never use proxy, NULL means use proxy for non-local files only.  */
44858    if( envforce!=NULL ){
44859      useProxy = atoi(envforce)>0;
44860    }else{
44861      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
44862    }
44863    if( useProxy ){
44864      rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
44865      if( rc==SQLITE_OK ){
44866        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
44867        if( rc!=SQLITE_OK ){
44868          /* Use unixClose to clean up the resources added in fillInUnixFile
44869          ** and clear all the structure's references.  Specifically,
44870          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
44871          */
44872          unixClose(pFile);
44873          return rc;
44874        }
44875      }
44876      goto open_finished;
44877    }
44878  }
44879#endif
44880
44881  assert( zPath==0 || zPath[0]=='/'
44882      || eType==SQLITE_OPEN_SUPER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
44883  );
44884  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
44885
44886open_finished:
44887  if( rc!=SQLITE_OK ){
44888    sqlite3_free(p->pPreallocatedUnused);
44889  }
44890  return rc;
44891}
44892
44893
44894/*
44895** Delete the file at zPath. If the dirSync argument is true, fsync()
44896** the directory after deleting the file.
44897*/
44898static int unixDelete(
44899  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
44900  const char *zPath,        /* Name of file to be deleted */
44901  int dirSync               /* If true, fsync() directory after deleting file */
44902){
44903  int rc = SQLITE_OK;
44904  UNUSED_PARAMETER(NotUsed);
44905  SimulateIOError(return SQLITE_IOERR_DELETE);
44906  if( osUnlink(zPath)==(-1) ){
44907    if( errno==ENOENT
44908#if OS_VXWORKS
44909        || osAccess(zPath,0)!=0
44910#endif
44911    ){
44912      rc = SQLITE_IOERR_DELETE_NOENT;
44913    }else{
44914      rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
44915    }
44916    return rc;
44917  }
44918#ifndef SQLITE_DISABLE_DIRSYNC
44919  if( (dirSync & 1)!=0 ){
44920    int fd;
44921    rc = osOpenDirectory(zPath, &fd);
44922    if( rc==SQLITE_OK ){
44923      if( full_fsync(fd,0,0) ){
44924        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
44925      }
44926      robust_close(0, fd, __LINE__);
44927    }else{
44928      assert( rc==SQLITE_CANTOPEN );
44929      rc = SQLITE_OK;
44930    }
44931  }
44932#endif
44933  return rc;
44934}
44935
44936/*
44937** Test the existence of or access permissions of file zPath. The
44938** test performed depends on the value of flags:
44939**
44940**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
44941**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
44942**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
44943**
44944** Otherwise return 0.
44945*/
44946static int unixAccess(
44947  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
44948  const char *zPath,      /* Path of the file to examine */
44949  int flags,              /* What do we want to learn about the zPath file? */
44950  int *pResOut            /* Write result boolean here */
44951){
44952  UNUSED_PARAMETER(NotUsed);
44953  SimulateIOError( return SQLITE_IOERR_ACCESS; );
44954  assert( pResOut!=0 );
44955
44956  /* The spec says there are three possible values for flags.  But only
44957  ** two of them are actually used */
44958  assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
44959
44960  if( flags==SQLITE_ACCESS_EXISTS ){
44961    struct stat buf;
44962    *pResOut = 0==osStat(zPath, &buf) &&
44963                (!S_ISREG(buf.st_mode) || buf.st_size>0);
44964  }else{
44965    *pResOut = osAccess(zPath, W_OK|R_OK)==0;
44966  }
44967  return SQLITE_OK;
44968}
44969
44970/*
44971** A pathname under construction
44972*/
44973typedef struct DbPath DbPath;
44974struct DbPath {
44975  int rc;           /* Non-zero following any error */
44976  int nSymlink;     /* Number of symlinks resolved */
44977  char *zOut;       /* Write the pathname here */
44978  int nOut;         /* Bytes of space available to zOut[] */
44979  int nUsed;        /* Bytes of zOut[] currently being used */
44980};
44981
44982/* Forward reference */
44983static void appendAllPathElements(DbPath*,const char*);
44984
44985/*
44986** Append a single path element to the DbPath under construction
44987*/
44988static void appendOnePathElement(
44989  DbPath *pPath,       /* Path under construction, to which to append zName */
44990  const char *zName,   /* Name to append to pPath.  Not zero-terminated */
44991  int nName            /* Number of significant bytes in zName */
44992){
44993  assert( nName>0 );
44994  assert( zName!=0 );
44995  if( zName[0]=='.' ){
44996    if( nName==1 ) return;
44997    if( zName[1]=='.' && nName==2 ){
44998      if( pPath->nUsed>1 ){
44999        assert( pPath->zOut[0]=='/' );
45000        while( pPath->zOut[--pPath->nUsed]!='/' ){}
45001      }
45002      return;
45003    }
45004  }
45005  if( pPath->nUsed + nName + 2 >= pPath->nOut ){
45006    pPath->rc = SQLITE_ERROR;
45007    return;
45008  }
45009  pPath->zOut[pPath->nUsed++] = '/';
45010  memcpy(&pPath->zOut[pPath->nUsed], zName, nName);
45011  pPath->nUsed += nName;
45012#if defined(HAVE_READLINK) && defined(HAVE_LSTAT)
45013  if( pPath->rc==SQLITE_OK ){
45014    const char *zIn;
45015    struct stat buf;
45016    pPath->zOut[pPath->nUsed] = 0;
45017    zIn = pPath->zOut;
45018    if( osLstat(zIn, &buf)!=0 ){
45019      if( errno!=ENOENT ){
45020        pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
45021      }
45022    }else if( S_ISLNK(buf.st_mode) ){
45023      ssize_t got;
45024      char zLnk[SQLITE_MAX_PATHLEN+2];
45025      if( pPath->nSymlink++ > SQLITE_MAX_SYMLINK ){
45026        pPath->rc = SQLITE_CANTOPEN_BKPT;
45027        return;
45028      }
45029      got = osReadlink(zIn, zLnk, sizeof(zLnk)-2);
45030      if( got<=0 || got>=(ssize_t)sizeof(zLnk)-2 ){
45031        pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
45032        return;
45033      }
45034      zLnk[got] = 0;
45035      if( zLnk[0]=='/' ){
45036        pPath->nUsed = 0;
45037      }else{
45038        pPath->nUsed -= nName + 1;
45039      }
45040      appendAllPathElements(pPath, zLnk);
45041    }
45042  }
45043#endif
45044}
45045
45046/*
45047** Append all path elements in zPath to the DbPath under construction.
45048*/
45049static void appendAllPathElements(
45050  DbPath *pPath,       /* Path under construction, to which to append zName */
45051  const char *zPath    /* Path to append to pPath.  Is zero-terminated */
45052){
45053  int i = 0;
45054  int j = 0;
45055  do{
45056    while( zPath[i] && zPath[i]!='/' ){ i++; }
45057    if( i>j ){
45058      appendOnePathElement(pPath, &zPath[j], i-j);
45059    }
45060    j = i+1;
45061  }while( zPath[i++] );
45062}
45063
45064/*
45065** Turn a relative pathname into a full pathname. The relative path
45066** is stored as a nul-terminated string in the buffer pointed to by
45067** zPath.
45068**
45069** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
45070** (in this case, MAX_PATHNAME bytes). The full-path is written to
45071** this buffer before returning.
45072*/
45073static int unixFullPathname(
45074  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
45075  const char *zPath,            /* Possibly relative input path */
45076  int nOut,                     /* Size of output buffer in bytes */
45077  char *zOut                    /* Output buffer */
45078){
45079  DbPath path;
45080  UNUSED_PARAMETER(pVfs);
45081  path.rc = 0;
45082  path.nUsed = 0;
45083  path.nSymlink = 0;
45084  path.nOut = nOut;
45085  path.zOut = zOut;
45086  if( zPath[0]!='/' ){
45087    char zPwd[SQLITE_MAX_PATHLEN+2];
45088    if( osGetcwd(zPwd, sizeof(zPwd)-2)==0 ){
45089      return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
45090    }
45091    appendAllPathElements(&path, zPwd);
45092  }
45093  appendAllPathElements(&path, zPath);
45094  zOut[path.nUsed] = 0;
45095  if( path.rc || path.nUsed<2 ) return SQLITE_CANTOPEN_BKPT;
45096  if( path.nSymlink ) return SQLITE_OK_SYMLINK;
45097  return SQLITE_OK;
45098}
45099
45100#ifndef SQLITE_OMIT_LOAD_EXTENSION
45101/*
45102** Interfaces for opening a shared library, finding entry points
45103** within the shared library, and closing the shared library.
45104*/
45105#include <dlfcn.h>
45106static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
45107  UNUSED_PARAMETER(NotUsed);
45108  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
45109}
45110
45111/*
45112** SQLite calls this function immediately after a call to unixDlSym() or
45113** unixDlOpen() fails (returns a null pointer). If a more detailed error
45114** message is available, it is written to zBufOut. If no error message
45115** is available, zBufOut is left unmodified and SQLite uses a default
45116** error message.
45117*/
45118static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
45119  const char *zErr;
45120  UNUSED_PARAMETER(NotUsed);
45121  unixEnterMutex();
45122  zErr = dlerror();
45123  if( zErr ){
45124    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
45125  }
45126  unixLeaveMutex();
45127}
45128static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
45129  /*
45130  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
45131  ** cast into a pointer to a function.  And yet the library dlsym() routine
45132  ** returns a void* which is really a pointer to a function.  So how do we
45133  ** use dlsym() with -pedantic-errors?
45134  **
45135  ** Variable x below is defined to be a pointer to a function taking
45136  ** parameters void* and const char* and returning a pointer to a function.
45137  ** We initialize x by assigning it a pointer to the dlsym() function.
45138  ** (That assignment requires a cast.)  Then we call the function that
45139  ** x points to.
45140  **
45141  ** This work-around is unlikely to work correctly on any system where
45142  ** you really cannot cast a function pointer into void*.  But then, on the
45143  ** other hand, dlsym() will not work on such a system either, so we have
45144  ** not really lost anything.
45145  */
45146  void (*(*x)(void*,const char*))(void);
45147  UNUSED_PARAMETER(NotUsed);
45148  x = (void(*(*)(void*,const char*))(void))dlsym;
45149  return (*x)(p, zSym);
45150}
45151static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
45152  UNUSED_PARAMETER(NotUsed);
45153  dlclose(pHandle);
45154}
45155#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
45156  #define unixDlOpen  0
45157  #define unixDlError 0
45158  #define unixDlSym   0
45159  #define unixDlClose 0
45160#endif
45161
45162/*
45163** Write nBuf bytes of random data to the supplied buffer zBuf.
45164*/
45165static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
45166  UNUSED_PARAMETER(NotUsed);
45167  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
45168
45169  /* We have to initialize zBuf to prevent valgrind from reporting
45170  ** errors.  The reports issued by valgrind are incorrect - we would
45171  ** prefer that the randomness be increased by making use of the
45172  ** uninitialized space in zBuf - but valgrind errors tend to worry
45173  ** some users.  Rather than argue, it seems easier just to initialize
45174  ** the whole array and silence valgrind, even if that means less randomness
45175  ** in the random seed.
45176  **
45177  ** When testing, initializing zBuf[] to zero is all we do.  That means
45178  ** that we always use the same random number sequence.  This makes the
45179  ** tests repeatable.
45180  */
45181  memset(zBuf, 0, nBuf);
45182  randomnessPid = osGetpid(0);
45183#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
45184  {
45185    int fd, got;
45186    fd = robust_open("/dev/urandom", O_RDONLY, 0);
45187    if( fd<0 ){
45188      time_t t;
45189      time(&t);
45190      memcpy(zBuf, &t, sizeof(t));
45191      memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
45192      assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
45193      nBuf = sizeof(t) + sizeof(randomnessPid);
45194    }else{
45195      do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
45196      robust_close(0, fd, __LINE__);
45197    }
45198  }
45199#endif
45200  return nBuf;
45201}
45202
45203
45204/*
45205** Sleep for a little while.  Return the amount of time slept.
45206** The argument is the number of microseconds we want to sleep.
45207** The return value is the number of microseconds of sleep actually
45208** requested from the underlying operating system, a number which
45209** might be greater than or equal to the argument, but not less
45210** than the argument.
45211*/
45212static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
45213#if !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP+0
45214  struct timespec sp;
45215  sp.tv_sec = microseconds / 1000000;
45216  sp.tv_nsec = (microseconds % 1000000) * 1000;
45217
45218  /* Almost all modern unix systems support nanosleep().  But if you are
45219  ** compiling for one of the rare exceptions, you can use
45220  ** -DHAVE_NANOSLEEP=0 (perhaps in conjuction with -DHAVE_USLEEP if
45221  ** usleep() is available) in order to bypass the use of nanosleep() */
45222  nanosleep(&sp, NULL);
45223
45224  UNUSED_PARAMETER(NotUsed);
45225  return microseconds;
45226#elif defined(HAVE_USLEEP) && HAVE_USLEEP
45227  if( microseconds>=1000000 ) sleep(microseconds/1000000);
45228  if( microseconds%1000000 ) usleep(microseconds%1000000);
45229  UNUSED_PARAMETER(NotUsed);
45230  return microseconds;
45231#else
45232  int seconds = (microseconds+999999)/1000000;
45233  sleep(seconds);
45234  UNUSED_PARAMETER(NotUsed);
45235  return seconds*1000000;
45236#endif
45237}
45238
45239/*
45240** The following variable, if set to a non-zero value, is interpreted as
45241** the number of seconds since 1970 and is used to set the result of
45242** sqlite3OsCurrentTime() during testing.
45243*/
45244#ifdef SQLITE_TEST
45245SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
45246#endif
45247
45248/*
45249** Find the current time (in Universal Coordinated Time).  Write into *piNow
45250** the current time and date as a Julian Day number times 86_400_000.  In
45251** other words, write into *piNow the number of milliseconds since the Julian
45252** epoch of noon in Greenwich on November 24, 4714 B.C according to the
45253** proleptic Gregorian calendar.
45254**
45255** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
45256** cannot be found.
45257*/
45258static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
45259  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
45260  int rc = SQLITE_OK;
45261#if defined(NO_GETTOD)
45262  time_t t;
45263  time(&t);
45264  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
45265#elif OS_VXWORKS
45266  struct timespec sNow;
45267  clock_gettime(CLOCK_REALTIME, &sNow);
45268  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
45269#else
45270  struct timeval sNow;
45271  (void)gettimeofday(&sNow, 0);  /* Cannot fail given valid arguments */
45272  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
45273#endif
45274
45275#ifdef SQLITE_TEST
45276  if( sqlite3_current_time ){
45277    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
45278  }
45279#endif
45280  UNUSED_PARAMETER(NotUsed);
45281  return rc;
45282}
45283
45284#ifndef SQLITE_OMIT_DEPRECATED
45285/*
45286** Find the current time (in Universal Coordinated Time).  Write the
45287** current time and date as a Julian Day number into *prNow and
45288** return 0.  Return 1 if the time and date cannot be found.
45289*/
45290static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
45291  sqlite3_int64 i = 0;
45292  int rc;
45293  UNUSED_PARAMETER(NotUsed);
45294  rc = unixCurrentTimeInt64(0, &i);
45295  *prNow = i/86400000.0;
45296  return rc;
45297}
45298#else
45299# define unixCurrentTime 0
45300#endif
45301
45302/*
45303** The xGetLastError() method is designed to return a better
45304** low-level error message when operating-system problems come up
45305** during SQLite operation.  Only the integer return code is currently
45306** used.
45307*/
45308static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
45309  UNUSED_PARAMETER(NotUsed);
45310  UNUSED_PARAMETER(NotUsed2);
45311  UNUSED_PARAMETER(NotUsed3);
45312  return errno;
45313}
45314
45315
45316/*
45317************************ End of sqlite3_vfs methods ***************************
45318******************************************************************************/
45319
45320/******************************************************************************
45321************************** Begin Proxy Locking ********************************
45322**
45323** Proxy locking is a "uber-locking-method" in this sense:  It uses the
45324** other locking methods on secondary lock files.  Proxy locking is a
45325** meta-layer over top of the primitive locking implemented above.  For
45326** this reason, the division that implements of proxy locking is deferred
45327** until late in the file (here) after all of the other I/O methods have
45328** been defined - so that the primitive locking methods are available
45329** as services to help with the implementation of proxy locking.
45330**
45331****
45332**
45333** The default locking schemes in SQLite use byte-range locks on the
45334** database file to coordinate safe, concurrent access by multiple readers
45335** and writers [http://sqlite.org/lockingv3.html].  The five file locking
45336** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
45337** as POSIX read & write locks over fixed set of locations (via fsctl),
45338** on AFP and SMB only exclusive byte-range locks are available via fsctl
45339** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
45340** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
45341** address in the shared range is taken for a SHARED lock, the entire
45342** shared range is taken for an EXCLUSIVE lock):
45343**
45344**      PENDING_BYTE        0x40000000
45345**      RESERVED_BYTE       0x40000001
45346**      SHARED_RANGE        0x40000002 -> 0x40000200
45347**
45348** This works well on the local file system, but shows a nearly 100x
45349** slowdown in read performance on AFP because the AFP client disables
45350** the read cache when byte-range locks are present.  Enabling the read
45351** cache exposes a cache coherency problem that is present on all OS X
45352** supported network file systems.  NFS and AFP both observe the
45353** close-to-open semantics for ensuring cache coherency
45354** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
45355** address the requirements for concurrent database access by multiple
45356** readers and writers
45357** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
45358**
45359** To address the performance and cache coherency issues, proxy file locking
45360** changes the way database access is controlled by limiting access to a
45361** single host at a time and moving file locks off of the database file
45362** and onto a proxy file on the local file system.
45363**
45364**
45365** Using proxy locks
45366** -----------------
45367**
45368** C APIs
45369**
45370**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
45371**                       <proxy_path> | ":auto:");
45372**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
45373**                       &<proxy_path>);
45374**
45375**
45376** SQL pragmas
45377**
45378**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
45379**  PRAGMA [database.]lock_proxy_file
45380**
45381** Specifying ":auto:" means that if there is a conch file with a matching
45382** host ID in it, the proxy path in the conch file will be used, otherwise
45383** a proxy path based on the user's temp dir
45384** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
45385** actual proxy file name is generated from the name and path of the
45386** database file.  For example:
45387**
45388**       For database path "/Users/me/foo.db"
45389**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
45390**
45391** Once a lock proxy is configured for a database connection, it can not
45392** be removed, however it may be switched to a different proxy path via
45393** the above APIs (assuming the conch file is not being held by another
45394** connection or process).
45395**
45396**
45397** How proxy locking works
45398** -----------------------
45399**
45400** Proxy file locking relies primarily on two new supporting files:
45401**
45402**   *  conch file to limit access to the database file to a single host
45403**      at a time
45404**
45405**   *  proxy file to act as a proxy for the advisory locks normally
45406**      taken on the database
45407**
45408** The conch file - to use a proxy file, sqlite must first "hold the conch"
45409** by taking an sqlite-style shared lock on the conch file, reading the
45410** contents and comparing the host's unique host ID (see below) and lock
45411** proxy path against the values stored in the conch.  The conch file is
45412** stored in the same directory as the database file and the file name
45413** is patterned after the database file name as ".<databasename>-conch".
45414** If the conch file does not exist, or its contents do not match the
45415** host ID and/or proxy path, then the lock is escalated to an exclusive
45416** lock and the conch file contents is updated with the host ID and proxy
45417** path and the lock is downgraded to a shared lock again.  If the conch
45418** is held by another process (with a shared lock), the exclusive lock
45419** will fail and SQLITE_BUSY is returned.
45420**
45421** The proxy file - a single-byte file used for all advisory file locks
45422** normally taken on the database file.   This allows for safe sharing
45423** of the database file for multiple readers and writers on the same
45424** host (the conch ensures that they all use the same local lock file).
45425**
45426** Requesting the lock proxy does not immediately take the conch, it is
45427** only taken when the first request to lock database file is made.
45428** This matches the semantics of the traditional locking behavior, where
45429** opening a connection to a database file does not take a lock on it.
45430** The shared lock and an open file descriptor are maintained until
45431** the connection to the database is closed.
45432**
45433** The proxy file and the lock file are never deleted so they only need
45434** to be created the first time they are used.
45435**
45436** Configuration options
45437** ---------------------
45438**
45439**  SQLITE_PREFER_PROXY_LOCKING
45440**
45441**       Database files accessed on non-local file systems are
45442**       automatically configured for proxy locking, lock files are
45443**       named automatically using the same logic as
45444**       PRAGMA lock_proxy_file=":auto:"
45445**
45446**  SQLITE_PROXY_DEBUG
45447**
45448**       Enables the logging of error messages during host id file
45449**       retrieval and creation
45450**
45451**  LOCKPROXYDIR
45452**
45453**       Overrides the default directory used for lock proxy files that
45454**       are named automatically via the ":auto:" setting
45455**
45456**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
45457**
45458**       Permissions to use when creating a directory for storing the
45459**       lock proxy files, only used when LOCKPROXYDIR is not set.
45460**
45461**
45462** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
45463** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
45464** force proxy locking to be used for every database file opened, and 0
45465** will force automatic proxy locking to be disabled for all database
45466** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
45467** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
45468*/
45469
45470/*
45471** Proxy locking is only available on MacOSX
45472*/
45473#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
45474
45475/*
45476** The proxyLockingContext has the path and file structures for the remote
45477** and local proxy files in it
45478*/
45479typedef struct proxyLockingContext proxyLockingContext;
45480struct proxyLockingContext {
45481  unixFile *conchFile;         /* Open conch file */
45482  char *conchFilePath;         /* Name of the conch file */
45483  unixFile *lockProxy;         /* Open proxy lock file */
45484  char *lockProxyPath;         /* Name of the proxy lock file */
45485  char *dbPath;                /* Name of the open file */
45486  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
45487  int nFails;                  /* Number of conch taking failures */
45488  void *oldLockingContext;     /* Original lockingcontext to restore on close */
45489  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
45490};
45491
45492/*
45493** The proxy lock file path for the database at dbPath is written into lPath,
45494** which must point to valid, writable memory large enough for a maxLen length
45495** file path.
45496*/
45497static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
45498  int len;
45499  int dbLen;
45500  int i;
45501
45502#ifdef LOCKPROXYDIR
45503  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
45504#else
45505# ifdef _CS_DARWIN_USER_TEMP_DIR
45506  {
45507    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
45508      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
45509               lPath, errno, osGetpid(0)));
45510      return SQLITE_IOERR_LOCK;
45511    }
45512    len = strlcat(lPath, "sqliteplocks", maxLen);
45513  }
45514# else
45515  len = strlcpy(lPath, "/tmp/", maxLen);
45516# endif
45517#endif
45518
45519  if( lPath[len-1]!='/' ){
45520    len = strlcat(lPath, "/", maxLen);
45521  }
45522
45523  /* transform the db path to a unique cache name */
45524  dbLen = (int)strlen(dbPath);
45525  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
45526    char c = dbPath[i];
45527    lPath[i+len] = (c=='/')?'_':c;
45528  }
45529  lPath[i+len]='\0';
45530  strlcat(lPath, ":auto:", maxLen);
45531  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
45532  return SQLITE_OK;
45533}
45534
45535/*
45536 ** Creates the lock file and any missing directories in lockPath
45537 */
45538static int proxyCreateLockPath(const char *lockPath){
45539  int i, len;
45540  char buf[MAXPATHLEN];
45541  int start = 0;
45542
45543  assert(lockPath!=NULL);
45544  /* try to create all the intermediate directories */
45545  len = (int)strlen(lockPath);
45546  buf[0] = lockPath[0];
45547  for( i=1; i<len; i++ ){
45548    if( lockPath[i] == '/' && (i - start > 0) ){
45549      /* only mkdir if leaf dir != "." or "/" or ".." */
45550      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
45551         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
45552        buf[i]='\0';
45553        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
45554          int err=errno;
45555          if( err!=EEXIST ) {
45556            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
45557                     "'%s' proxy lock path=%s pid=%d\n",
45558                     buf, strerror(err), lockPath, osGetpid(0)));
45559            return err;
45560          }
45561        }
45562      }
45563      start=i+1;
45564    }
45565    buf[i] = lockPath[i];
45566  }
45567  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
45568  return 0;
45569}
45570
45571/*
45572** Create a new VFS file descriptor (stored in memory obtained from
45573** sqlite3_malloc) and open the file named "path" in the file descriptor.
45574**
45575** The caller is responsible not only for closing the file descriptor
45576** but also for freeing the memory associated with the file descriptor.
45577*/
45578static int proxyCreateUnixFile(
45579    const char *path,        /* path for the new unixFile */
45580    unixFile **ppFile,       /* unixFile created and returned by ref */
45581    int islockfile           /* if non zero missing dirs will be created */
45582) {
45583  int fd = -1;
45584  unixFile *pNew;
45585  int rc = SQLITE_OK;
45586  int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW;
45587  sqlite3_vfs dummyVfs;
45588  int terrno = 0;
45589  UnixUnusedFd *pUnused = NULL;
45590
45591  /* 1. first try to open/create the file
45592  ** 2. if that fails, and this is a lock file (not-conch), try creating
45593  ** the parent directories and then try again.
45594  ** 3. if that fails, try to open the file read-only
45595  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
45596  */
45597  pUnused = findReusableFd(path, openFlags);
45598  if( pUnused ){
45599    fd = pUnused->fd;
45600  }else{
45601    pUnused = sqlite3_malloc64(sizeof(*pUnused));
45602    if( !pUnused ){
45603      return SQLITE_NOMEM_BKPT;
45604    }
45605  }
45606  if( fd<0 ){
45607    fd = robust_open(path, openFlags, 0);
45608    terrno = errno;
45609    if( fd<0 && errno==ENOENT && islockfile ){
45610      if( proxyCreateLockPath(path) == SQLITE_OK ){
45611        fd = robust_open(path, openFlags, 0);
45612      }
45613    }
45614  }
45615  if( fd<0 ){
45616    openFlags = O_RDONLY | O_NOFOLLOW;
45617    fd = robust_open(path, openFlags, 0);
45618    terrno = errno;
45619  }
45620  if( fd<0 ){
45621    if( islockfile ){
45622      return SQLITE_BUSY;
45623    }
45624    switch (terrno) {
45625      case EACCES:
45626        return SQLITE_PERM;
45627      case EIO:
45628        return SQLITE_IOERR_LOCK; /* even though it is the conch */
45629      default:
45630        return SQLITE_CANTOPEN_BKPT;
45631    }
45632  }
45633
45634  pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
45635  if( pNew==NULL ){
45636    rc = SQLITE_NOMEM_BKPT;
45637    goto end_create_proxy;
45638  }
45639  memset(pNew, 0, sizeof(unixFile));
45640  pNew->openFlags = openFlags;
45641  memset(&dummyVfs, 0, sizeof(dummyVfs));
45642  dummyVfs.pAppData = (void*)&autolockIoFinder;
45643  dummyVfs.zName = "dummy";
45644  pUnused->fd = fd;
45645  pUnused->flags = openFlags;
45646  pNew->pPreallocatedUnused = pUnused;
45647
45648  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
45649  if( rc==SQLITE_OK ){
45650    *ppFile = pNew;
45651    return SQLITE_OK;
45652  }
45653end_create_proxy:
45654  robust_close(pNew, fd, __LINE__);
45655  sqlite3_free(pNew);
45656  sqlite3_free(pUnused);
45657  return rc;
45658}
45659
45660#ifdef SQLITE_TEST
45661/* simulate multiple hosts by creating unique hostid file paths */
45662SQLITE_API int sqlite3_hostid_num = 0;
45663#endif
45664
45665#define PROXY_HOSTIDLEN    16  /* conch file host id length */
45666
45667#if HAVE_GETHOSTUUID
45668/* Not always defined in the headers as it ought to be */
45669extern int gethostuuid(uuid_t id, const struct timespec *wait);
45670#endif
45671
45672/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
45673** bytes of writable memory.
45674*/
45675static int proxyGetHostID(unsigned char *pHostID, int *pError){
45676  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
45677  memset(pHostID, 0, PROXY_HOSTIDLEN);
45678#if HAVE_GETHOSTUUID
45679  {
45680    struct timespec timeout = {1, 0}; /* 1 sec timeout */
45681    if( gethostuuid(pHostID, &timeout) ){
45682      int err = errno;
45683      if( pError ){
45684        *pError = err;
45685      }
45686      return SQLITE_IOERR;
45687    }
45688  }
45689#else
45690  UNUSED_PARAMETER(pError);
45691#endif
45692#ifdef SQLITE_TEST
45693  /* simulate multiple hosts by creating unique hostid file paths */
45694  if( sqlite3_hostid_num != 0){
45695    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
45696  }
45697#endif
45698
45699  return SQLITE_OK;
45700}
45701
45702/* The conch file contains the header, host id and lock file path
45703 */
45704#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
45705#define PROXY_HEADERLEN    1   /* conch file header length */
45706#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
45707#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
45708
45709/*
45710** Takes an open conch file, copies the contents to a new path and then moves
45711** it back.  The newly created file's file descriptor is assigned to the
45712** conch file structure and finally the original conch file descriptor is
45713** closed.  Returns zero if successful.
45714*/
45715static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
45716  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
45717  unixFile *conchFile = pCtx->conchFile;
45718  char tPath[MAXPATHLEN];
45719  char buf[PROXY_MAXCONCHLEN];
45720  char *cPath = pCtx->conchFilePath;
45721  size_t readLen = 0;
45722  size_t pathLen = 0;
45723  char errmsg[64] = "";
45724  int fd = -1;
45725  int rc = -1;
45726  UNUSED_PARAMETER(myHostID);
45727
45728  /* create a new path by replace the trailing '-conch' with '-break' */
45729  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
45730  if( pathLen>MAXPATHLEN || pathLen<6 ||
45731     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
45732    sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
45733    goto end_breaklock;
45734  }
45735  /* read the conch content */
45736  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
45737  if( readLen<PROXY_PATHINDEX ){
45738    sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
45739    goto end_breaklock;
45740  }
45741  /* write it out to the temporary break file */
45742  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0);
45743  if( fd<0 ){
45744    sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
45745    goto end_breaklock;
45746  }
45747  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
45748    sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
45749    goto end_breaklock;
45750  }
45751  if( rename(tPath, cPath) ){
45752    sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
45753    goto end_breaklock;
45754  }
45755  rc = 0;
45756  fprintf(stderr, "broke stale lock on %s\n", cPath);
45757  robust_close(pFile, conchFile->h, __LINE__);
45758  conchFile->h = fd;
45759  conchFile->openFlags = O_RDWR | O_CREAT;
45760
45761end_breaklock:
45762  if( rc ){
45763    if( fd>=0 ){
45764      osUnlink(tPath);
45765      robust_close(pFile, fd, __LINE__);
45766    }
45767    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
45768  }
45769  return rc;
45770}
45771
45772/* Take the requested lock on the conch file and break a stale lock if the
45773** host id matches.
45774*/
45775static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
45776  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
45777  unixFile *conchFile = pCtx->conchFile;
45778  int rc = SQLITE_OK;
45779  int nTries = 0;
45780  struct timespec conchModTime;
45781
45782  memset(&conchModTime, 0, sizeof(conchModTime));
45783  do {
45784    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
45785    nTries ++;
45786    if( rc==SQLITE_BUSY ){
45787      /* If the lock failed (busy):
45788       * 1st try: get the mod time of the conch, wait 0.5s and try again.
45789       * 2nd try: fail if the mod time changed or host id is different, wait
45790       *           10 sec and try again
45791       * 3rd try: break the lock unless the mod time has changed.
45792       */
45793      struct stat buf;
45794      if( osFstat(conchFile->h, &buf) ){
45795        storeLastErrno(pFile, errno);
45796        return SQLITE_IOERR_LOCK;
45797      }
45798
45799      if( nTries==1 ){
45800        conchModTime = buf.st_mtimespec;
45801        unixSleep(0,500000); /* wait 0.5 sec and try the lock again*/
45802        continue;
45803      }
45804
45805      assert( nTries>1 );
45806      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
45807         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
45808        return SQLITE_BUSY;
45809      }
45810
45811      if( nTries==2 ){
45812        char tBuf[PROXY_MAXCONCHLEN];
45813        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
45814        if( len<0 ){
45815          storeLastErrno(pFile, errno);
45816          return SQLITE_IOERR_LOCK;
45817        }
45818        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
45819          /* don't break the lock if the host id doesn't match */
45820          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
45821            return SQLITE_BUSY;
45822          }
45823        }else{
45824          /* don't break the lock on short read or a version mismatch */
45825          return SQLITE_BUSY;
45826        }
45827        unixSleep(0,10000000); /* wait 10 sec and try the lock again */
45828        continue;
45829      }
45830
45831      assert( nTries==3 );
45832      if( 0==proxyBreakConchLock(pFile, myHostID) ){
45833        rc = SQLITE_OK;
45834        if( lockType==EXCLUSIVE_LOCK ){
45835          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
45836        }
45837        if( !rc ){
45838          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
45839        }
45840      }
45841    }
45842  } while( rc==SQLITE_BUSY && nTries<3 );
45843
45844  return rc;
45845}
45846
45847/* Takes the conch by taking a shared lock and read the contents conch, if
45848** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
45849** lockPath means that the lockPath in the conch file will be used if the
45850** host IDs match, or a new lock path will be generated automatically
45851** and written to the conch file.
45852*/
45853static int proxyTakeConch(unixFile *pFile){
45854  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
45855
45856  if( pCtx->conchHeld!=0 ){
45857    return SQLITE_OK;
45858  }else{
45859    unixFile *conchFile = pCtx->conchFile;
45860    uuid_t myHostID;
45861    int pError = 0;
45862    char readBuf[PROXY_MAXCONCHLEN];
45863    char lockPath[MAXPATHLEN];
45864    char *tempLockPath = NULL;
45865    int rc = SQLITE_OK;
45866    int createConch = 0;
45867    int hostIdMatch = 0;
45868    int readLen = 0;
45869    int tryOldLockPath = 0;
45870    int forceNewLockPath = 0;
45871
45872    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
45873             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
45874             osGetpid(0)));
45875
45876    rc = proxyGetHostID(myHostID, &pError);
45877    if( (rc&0xff)==SQLITE_IOERR ){
45878      storeLastErrno(pFile, pError);
45879      goto end_takeconch;
45880    }
45881    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
45882    if( rc!=SQLITE_OK ){
45883      goto end_takeconch;
45884    }
45885    /* read the existing conch file */
45886    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
45887    if( readLen<0 ){
45888      /* I/O error: lastErrno set by seekAndRead */
45889      storeLastErrno(pFile, conchFile->lastErrno);
45890      rc = SQLITE_IOERR_READ;
45891      goto end_takeconch;
45892    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
45893             readBuf[0]!=(char)PROXY_CONCHVERSION ){
45894      /* a short read or version format mismatch means we need to create a new
45895      ** conch file.
45896      */
45897      createConch = 1;
45898    }
45899    /* if the host id matches and the lock path already exists in the conch
45900    ** we'll try to use the path there, if we can't open that path, we'll
45901    ** retry with a new auto-generated path
45902    */
45903    do { /* in case we need to try again for an :auto: named lock file */
45904
45905      if( !createConch && !forceNewLockPath ){
45906        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
45907                                  PROXY_HOSTIDLEN);
45908        /* if the conch has data compare the contents */
45909        if( !pCtx->lockProxyPath ){
45910          /* for auto-named local lock file, just check the host ID and we'll
45911           ** use the local lock file path that's already in there
45912           */
45913          if( hostIdMatch ){
45914            size_t pathLen = (readLen - PROXY_PATHINDEX);
45915
45916            if( pathLen>=MAXPATHLEN ){
45917              pathLen=MAXPATHLEN-1;
45918            }
45919            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
45920            lockPath[pathLen] = 0;
45921            tempLockPath = lockPath;
45922            tryOldLockPath = 1;
45923            /* create a copy of the lock path if the conch is taken */
45924            goto end_takeconch;
45925          }
45926        }else if( hostIdMatch
45927               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
45928                           readLen-PROXY_PATHINDEX)
45929        ){
45930          /* conch host and lock path match */
45931          goto end_takeconch;
45932        }
45933      }
45934
45935      /* if the conch isn't writable and doesn't match, we can't take it */
45936      if( (conchFile->openFlags&O_RDWR) == 0 ){
45937        rc = SQLITE_BUSY;
45938        goto end_takeconch;
45939      }
45940
45941      /* either the conch didn't match or we need to create a new one */
45942      if( !pCtx->lockProxyPath ){
45943        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
45944        tempLockPath = lockPath;
45945        /* create a copy of the lock path _only_ if the conch is taken */
45946      }
45947
45948      /* update conch with host and path (this will fail if other process
45949      ** has a shared lock already), if the host id matches, use the big
45950      ** stick.
45951      */
45952      futimes(conchFile->h, NULL);
45953      if( hostIdMatch && !createConch ){
45954        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
45955          /* We are trying for an exclusive lock but another thread in this
45956           ** same process is still holding a shared lock. */
45957          rc = SQLITE_BUSY;
45958        } else {
45959          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
45960        }
45961      }else{
45962        rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
45963      }
45964      if( rc==SQLITE_OK ){
45965        char writeBuffer[PROXY_MAXCONCHLEN];
45966        int writeSize = 0;
45967
45968        writeBuffer[0] = (char)PROXY_CONCHVERSION;
45969        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
45970        if( pCtx->lockProxyPath!=NULL ){
45971          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
45972                  MAXPATHLEN);
45973        }else{
45974          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
45975        }
45976        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
45977        robust_ftruncate(conchFile->h, writeSize);
45978        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
45979        full_fsync(conchFile->h,0,0);
45980        /* If we created a new conch file (not just updated the contents of a
45981         ** valid conch file), try to match the permissions of the database
45982         */
45983        if( rc==SQLITE_OK && createConch ){
45984          struct stat buf;
45985          int err = osFstat(pFile->h, &buf);
45986          if( err==0 ){
45987            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
45988                                        S_IROTH|S_IWOTH);
45989            /* try to match the database file R/W permissions, ignore failure */
45990#ifndef SQLITE_PROXY_DEBUG
45991            osFchmod(conchFile->h, cmode);
45992#else
45993            do{
45994              rc = osFchmod(conchFile->h, cmode);
45995            }while( rc==(-1) && errno==EINTR );
45996            if( rc!=0 ){
45997              int code = errno;
45998              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
45999                      cmode, code, strerror(code));
46000            } else {
46001              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
46002            }
46003          }else{
46004            int code = errno;
46005            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
46006                    err, code, strerror(code));
46007#endif
46008          }
46009        }
46010      }
46011      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
46012
46013    end_takeconch:
46014      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
46015      if( rc==SQLITE_OK && pFile->openFlags ){
46016        int fd;
46017        if( pFile->h>=0 ){
46018          robust_close(pFile, pFile->h, __LINE__);
46019        }
46020        pFile->h = -1;
46021        fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
46022        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
46023        if( fd>=0 ){
46024          pFile->h = fd;
46025        }else{
46026          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
46027           during locking */
46028        }
46029      }
46030      if( rc==SQLITE_OK && !pCtx->lockProxy ){
46031        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
46032        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
46033        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
46034          /* we couldn't create the proxy lock file with the old lock file path
46035           ** so try again via auto-naming
46036           */
46037          forceNewLockPath = 1;
46038          tryOldLockPath = 0;
46039          continue; /* go back to the do {} while start point, try again */
46040        }
46041      }
46042      if( rc==SQLITE_OK ){
46043        /* Need to make a copy of path if we extracted the value
46044         ** from the conch file or the path was allocated on the stack
46045         */
46046        if( tempLockPath ){
46047          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
46048          if( !pCtx->lockProxyPath ){
46049            rc = SQLITE_NOMEM_BKPT;
46050          }
46051        }
46052      }
46053      if( rc==SQLITE_OK ){
46054        pCtx->conchHeld = 1;
46055
46056        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
46057          afpLockingContext *afpCtx;
46058          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
46059          afpCtx->dbPath = pCtx->lockProxyPath;
46060        }
46061      } else {
46062        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
46063      }
46064      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
46065               rc==SQLITE_OK?"ok":"failed"));
46066      return rc;
46067    } while (1); /* in case we need to retry the :auto: lock file -
46068                 ** we should never get here except via the 'continue' call. */
46069  }
46070}
46071
46072/*
46073** If pFile holds a lock on a conch file, then release that lock.
46074*/
46075static int proxyReleaseConch(unixFile *pFile){
46076  int rc = SQLITE_OK;         /* Subroutine return code */
46077  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
46078  unixFile *conchFile;        /* Name of the conch file */
46079
46080  pCtx = (proxyLockingContext *)pFile->lockingContext;
46081  conchFile = pCtx->conchFile;
46082  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
46083           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
46084           osGetpid(0)));
46085  if( pCtx->conchHeld>0 ){
46086    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
46087  }
46088  pCtx->conchHeld = 0;
46089  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
46090           (rc==SQLITE_OK ? "ok" : "failed")));
46091  return rc;
46092}
46093
46094/*
46095** Given the name of a database file, compute the name of its conch file.
46096** Store the conch filename in memory obtained from sqlite3_malloc64().
46097** Make *pConchPath point to the new name.  Return SQLITE_OK on success
46098** or SQLITE_NOMEM if unable to obtain memory.
46099**
46100** The caller is responsible for ensuring that the allocated memory
46101** space is eventually freed.
46102**
46103** *pConchPath is set to NULL if a memory allocation error occurs.
46104*/
46105static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
46106  int i;                        /* Loop counter */
46107  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
46108  char *conchPath;              /* buffer in which to construct conch name */
46109
46110  /* Allocate space for the conch filename and initialize the name to
46111  ** the name of the original database file. */
46112  *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
46113  if( conchPath==0 ){
46114    return SQLITE_NOMEM_BKPT;
46115  }
46116  memcpy(conchPath, dbPath, len+1);
46117
46118  /* now insert a "." before the last / character */
46119  for( i=(len-1); i>=0; i-- ){
46120    if( conchPath[i]=='/' ){
46121      i++;
46122      break;
46123    }
46124  }
46125  conchPath[i]='.';
46126  while ( i<len ){
46127    conchPath[i+1]=dbPath[i];
46128    i++;
46129  }
46130
46131  /* append the "-conch" suffix to the file */
46132  memcpy(&conchPath[i+1], "-conch", 7);
46133  assert( (int)strlen(conchPath) == len+7 );
46134
46135  return SQLITE_OK;
46136}
46137
46138
46139/* Takes a fully configured proxy locking-style unix file and switches
46140** the local lock file path
46141*/
46142static int switchLockProxyPath(unixFile *pFile, const char *path) {
46143  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
46144  char *oldPath = pCtx->lockProxyPath;
46145  int rc = SQLITE_OK;
46146
46147  if( pFile->eFileLock!=NO_LOCK ){
46148    return SQLITE_BUSY;
46149  }
46150
46151  /* nothing to do if the path is NULL, :auto: or matches the existing path */
46152  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
46153    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
46154    return SQLITE_OK;
46155  }else{
46156    unixFile *lockProxy = pCtx->lockProxy;
46157    pCtx->lockProxy=NULL;
46158    pCtx->conchHeld = 0;
46159    if( lockProxy!=NULL ){
46160      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
46161      if( rc ) return rc;
46162      sqlite3_free(lockProxy);
46163    }
46164    sqlite3_free(oldPath);
46165    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
46166  }
46167
46168  return rc;
46169}
46170
46171/*
46172** pFile is a file that has been opened by a prior xOpen call.  dbPath
46173** is a string buffer at least MAXPATHLEN+1 characters in size.
46174**
46175** This routine find the filename associated with pFile and writes it
46176** int dbPath.
46177*/
46178static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
46179#if defined(__APPLE__)
46180  if( pFile->pMethod == &afpIoMethods ){
46181    /* afp style keeps a reference to the db path in the filePath field
46182    ** of the struct */
46183    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
46184    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
46185            MAXPATHLEN);
46186  } else
46187#endif
46188  if( pFile->pMethod == &dotlockIoMethods ){
46189    /* dot lock style uses the locking context to store the dot lock
46190    ** file path */
46191    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
46192    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
46193  }else{
46194    /* all other styles use the locking context to store the db file path */
46195    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
46196    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
46197  }
46198  return SQLITE_OK;
46199}
46200
46201/*
46202** Takes an already filled in unix file and alters it so all file locking
46203** will be performed on the local proxy lock file.  The following fields
46204** are preserved in the locking context so that they can be restored and
46205** the unix structure properly cleaned up at close time:
46206**  ->lockingContext
46207**  ->pMethod
46208*/
46209static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
46210  proxyLockingContext *pCtx;
46211  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
46212  char *lockPath=NULL;
46213  int rc = SQLITE_OK;
46214
46215  if( pFile->eFileLock!=NO_LOCK ){
46216    return SQLITE_BUSY;
46217  }
46218  proxyGetDbPathForUnixFile(pFile, dbPath);
46219  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
46220    lockPath=NULL;
46221  }else{
46222    lockPath=(char *)path;
46223  }
46224
46225  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
46226           (lockPath ? lockPath : ":auto:"), osGetpid(0)));
46227
46228  pCtx = sqlite3_malloc64( sizeof(*pCtx) );
46229  if( pCtx==0 ){
46230    return SQLITE_NOMEM_BKPT;
46231  }
46232  memset(pCtx, 0, sizeof(*pCtx));
46233
46234  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
46235  if( rc==SQLITE_OK ){
46236    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
46237    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
46238      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
46239      ** (c) the file system is read-only, then enable no-locking access.
46240      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
46241      ** that openFlags will have only one of O_RDONLY or O_RDWR.
46242      */
46243      struct statfs fsInfo;
46244      struct stat conchInfo;
46245      int goLockless = 0;
46246
46247      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
46248        int err = errno;
46249        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
46250          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
46251        }
46252      }
46253      if( goLockless ){
46254        pCtx->conchHeld = -1; /* read only FS/ lockless */
46255        rc = SQLITE_OK;
46256      }
46257    }
46258  }
46259  if( rc==SQLITE_OK && lockPath ){
46260    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
46261  }
46262
46263  if( rc==SQLITE_OK ){
46264    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
46265    if( pCtx->dbPath==NULL ){
46266      rc = SQLITE_NOMEM_BKPT;
46267    }
46268  }
46269  if( rc==SQLITE_OK ){
46270    /* all memory is allocated, proxys are created and assigned,
46271    ** switch the locking context and pMethod then return.
46272    */
46273    pCtx->oldLockingContext = pFile->lockingContext;
46274    pFile->lockingContext = pCtx;
46275    pCtx->pOldMethod = pFile->pMethod;
46276    pFile->pMethod = &proxyIoMethods;
46277  }else{
46278    if( pCtx->conchFile ){
46279      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
46280      sqlite3_free(pCtx->conchFile);
46281    }
46282    sqlite3DbFree(0, pCtx->lockProxyPath);
46283    sqlite3_free(pCtx->conchFilePath);
46284    sqlite3_free(pCtx);
46285  }
46286  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
46287           (rc==SQLITE_OK ? "ok" : "failed")));
46288  return rc;
46289}
46290
46291
46292/*
46293** This routine handles sqlite3_file_control() calls that are specific
46294** to proxy locking.
46295*/
46296static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
46297  switch( op ){
46298    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
46299      unixFile *pFile = (unixFile*)id;
46300      if( pFile->pMethod == &proxyIoMethods ){
46301        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
46302        proxyTakeConch(pFile);
46303        if( pCtx->lockProxyPath ){
46304          *(const char **)pArg = pCtx->lockProxyPath;
46305        }else{
46306          *(const char **)pArg = ":auto: (not held)";
46307        }
46308      } else {
46309        *(const char **)pArg = NULL;
46310      }
46311      return SQLITE_OK;
46312    }
46313    case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
46314      unixFile *pFile = (unixFile*)id;
46315      int rc = SQLITE_OK;
46316      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
46317      if( pArg==NULL || (const char *)pArg==0 ){
46318        if( isProxyStyle ){
46319          /* turn off proxy locking - not supported.  If support is added for
46320          ** switching proxy locking mode off then it will need to fail if
46321          ** the journal mode is WAL mode.
46322          */
46323          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
46324        }else{
46325          /* turn off proxy locking - already off - NOOP */
46326          rc = SQLITE_OK;
46327        }
46328      }else{
46329        const char *proxyPath = (const char *)pArg;
46330        if( isProxyStyle ){
46331          proxyLockingContext *pCtx =
46332            (proxyLockingContext*)pFile->lockingContext;
46333          if( !strcmp(pArg, ":auto:")
46334           || (pCtx->lockProxyPath &&
46335               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
46336          ){
46337            rc = SQLITE_OK;
46338          }else{
46339            rc = switchLockProxyPath(pFile, proxyPath);
46340          }
46341        }else{
46342          /* turn on proxy file locking */
46343          rc = proxyTransformUnixFile(pFile, proxyPath);
46344        }
46345      }
46346      return rc;
46347    }
46348    default: {
46349      assert( 0 );  /* The call assures that only valid opcodes are sent */
46350    }
46351  }
46352  /*NOTREACHED*/ assert(0);
46353  return SQLITE_ERROR;
46354}
46355
46356/*
46357** Within this division (the proxying locking implementation) the procedures
46358** above this point are all utilities.  The lock-related methods of the
46359** proxy-locking sqlite3_io_method object follow.
46360*/
46361
46362
46363/*
46364** This routine checks if there is a RESERVED lock held on the specified
46365** file by this or any other process. If such a lock is held, set *pResOut
46366** to a non-zero value otherwise *pResOut is set to zero.  The return value
46367** is set to SQLITE_OK unless an I/O error occurs during lock checking.
46368*/
46369static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
46370  unixFile *pFile = (unixFile*)id;
46371  int rc = proxyTakeConch(pFile);
46372  if( rc==SQLITE_OK ){
46373    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
46374    if( pCtx->conchHeld>0 ){
46375      unixFile *proxy = pCtx->lockProxy;
46376      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
46377    }else{ /* conchHeld < 0 is lockless */
46378      pResOut=0;
46379    }
46380  }
46381  return rc;
46382}
46383
46384/*
46385** Lock the file with the lock specified by parameter eFileLock - one
46386** of the following:
46387**
46388**     (1) SHARED_LOCK
46389**     (2) RESERVED_LOCK
46390**     (3) PENDING_LOCK
46391**     (4) EXCLUSIVE_LOCK
46392**
46393** Sometimes when requesting one lock state, additional lock states
46394** are inserted in between.  The locking might fail on one of the later
46395** transitions leaving the lock state different from what it started but
46396** still short of its goal.  The following chart shows the allowed
46397** transitions and the inserted intermediate states:
46398**
46399**    UNLOCKED -> SHARED
46400**    SHARED -> RESERVED
46401**    SHARED -> (PENDING) -> EXCLUSIVE
46402**    RESERVED -> (PENDING) -> EXCLUSIVE
46403**    PENDING -> EXCLUSIVE
46404**
46405** This routine will only increase a lock.  Use the sqlite3OsUnlock()
46406** routine to lower a locking level.
46407*/
46408static int proxyLock(sqlite3_file *id, int eFileLock) {
46409  unixFile *pFile = (unixFile*)id;
46410  int rc = proxyTakeConch(pFile);
46411  if( rc==SQLITE_OK ){
46412    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
46413    if( pCtx->conchHeld>0 ){
46414      unixFile *proxy = pCtx->lockProxy;
46415      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
46416      pFile->eFileLock = proxy->eFileLock;
46417    }else{
46418      /* conchHeld < 0 is lockless */
46419    }
46420  }
46421  return rc;
46422}
46423
46424
46425/*
46426** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
46427** must be either NO_LOCK or SHARED_LOCK.
46428**
46429** If the locking level of the file descriptor is already at or below
46430** the requested locking level, this routine is a no-op.
46431*/
46432static int proxyUnlock(sqlite3_file *id, int eFileLock) {
46433  unixFile *pFile = (unixFile*)id;
46434  int rc = proxyTakeConch(pFile);
46435  if( rc==SQLITE_OK ){
46436    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
46437    if( pCtx->conchHeld>0 ){
46438      unixFile *proxy = pCtx->lockProxy;
46439      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
46440      pFile->eFileLock = proxy->eFileLock;
46441    }else{
46442      /* conchHeld < 0 is lockless */
46443    }
46444  }
46445  return rc;
46446}
46447
46448/*
46449** Close a file that uses proxy locks.
46450*/
46451static int proxyClose(sqlite3_file *id) {
46452  if( ALWAYS(id) ){
46453    unixFile *pFile = (unixFile*)id;
46454    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
46455    unixFile *lockProxy = pCtx->lockProxy;
46456    unixFile *conchFile = pCtx->conchFile;
46457    int rc = SQLITE_OK;
46458
46459    if( lockProxy ){
46460      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
46461      if( rc ) return rc;
46462      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
46463      if( rc ) return rc;
46464      sqlite3_free(lockProxy);
46465      pCtx->lockProxy = 0;
46466    }
46467    if( conchFile ){
46468      if( pCtx->conchHeld ){
46469        rc = proxyReleaseConch(pFile);
46470        if( rc ) return rc;
46471      }
46472      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
46473      if( rc ) return rc;
46474      sqlite3_free(conchFile);
46475    }
46476    sqlite3DbFree(0, pCtx->lockProxyPath);
46477    sqlite3_free(pCtx->conchFilePath);
46478    sqlite3DbFree(0, pCtx->dbPath);
46479    /* restore the original locking context and pMethod then close it */
46480    pFile->lockingContext = pCtx->oldLockingContext;
46481    pFile->pMethod = pCtx->pOldMethod;
46482    sqlite3_free(pCtx);
46483    return pFile->pMethod->xClose(id);
46484  }
46485  return SQLITE_OK;
46486}
46487
46488
46489
46490#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
46491/*
46492** The proxy locking style is intended for use with AFP filesystems.
46493** And since AFP is only supported on MacOSX, the proxy locking is also
46494** restricted to MacOSX.
46495**
46496**
46497******************* End of the proxy lock implementation **********************
46498******************************************************************************/
46499
46500/*
46501** Initialize the operating system interface.
46502**
46503** This routine registers all VFS implementations for unix-like operating
46504** systems.  This routine, and the sqlite3_os_end() routine that follows,
46505** should be the only routines in this file that are visible from other
46506** files.
46507**
46508** This routine is called once during SQLite initialization and by a
46509** single thread.  The memory allocation and mutex subsystems have not
46510** necessarily been initialized when this routine is called, and so they
46511** should not be used.
46512*/
46513SQLITE_API int sqlite3_os_init(void){
46514  /*
46515  ** The following macro defines an initializer for an sqlite3_vfs object.
46516  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
46517  ** to the "finder" function.  (pAppData is a pointer to a pointer because
46518  ** silly C90 rules prohibit a void* from being cast to a function pointer
46519  ** and so we have to go through the intermediate pointer to avoid problems
46520  ** when compiling with -pedantic-errors on GCC.)
46521  **
46522  ** The FINDER parameter to this macro is the name of the pointer to the
46523  ** finder-function.  The finder-function returns a pointer to the
46524  ** sqlite_io_methods object that implements the desired locking
46525  ** behaviors.  See the division above that contains the IOMETHODS
46526  ** macro for addition information on finder-functions.
46527  **
46528  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
46529  ** object.  But the "autolockIoFinder" available on MacOSX does a little
46530  ** more than that; it looks at the filesystem type that hosts the
46531  ** database file and tries to choose an locking method appropriate for
46532  ** that filesystem time.
46533  */
46534  #define UNIXVFS(VFSNAME, FINDER) {                        \
46535    3,                    /* iVersion */                    \
46536    sizeof(unixFile),     /* szOsFile */                    \
46537    MAX_PATHNAME,         /* mxPathname */                  \
46538    0,                    /* pNext */                       \
46539    VFSNAME,              /* zName */                       \
46540    (void*)&FINDER,       /* pAppData */                    \
46541    unixOpen,             /* xOpen */                       \
46542    unixDelete,           /* xDelete */                     \
46543    unixAccess,           /* xAccess */                     \
46544    unixFullPathname,     /* xFullPathname */               \
46545    unixDlOpen,           /* xDlOpen */                     \
46546    unixDlError,          /* xDlError */                    \
46547    unixDlSym,            /* xDlSym */                      \
46548    unixDlClose,          /* xDlClose */                    \
46549    unixRandomness,       /* xRandomness */                 \
46550    unixSleep,            /* xSleep */                      \
46551    unixCurrentTime,      /* xCurrentTime */                \
46552    unixGetLastError,     /* xGetLastError */               \
46553    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
46554    unixSetSystemCall,    /* xSetSystemCall */              \
46555    unixGetSystemCall,    /* xGetSystemCall */              \
46556    unixNextSystemCall,   /* xNextSystemCall */             \
46557  }
46558
46559  /*
46560  ** All default VFSes for unix are contained in the following array.
46561  **
46562  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
46563  ** by the SQLite core when the VFS is registered.  So the following
46564  ** array cannot be const.
46565  */
46566  static sqlite3_vfs aVfs[] = {
46567#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
46568    UNIXVFS("unix",          autolockIoFinder ),
46569#elif OS_VXWORKS
46570    UNIXVFS("unix",          vxworksIoFinder ),
46571#else
46572    UNIXVFS("unix",          posixIoFinder ),
46573#endif
46574    UNIXVFS("unix-none",     nolockIoFinder ),
46575    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
46576    UNIXVFS("unix-excl",     posixIoFinder ),
46577#if OS_VXWORKS
46578    UNIXVFS("unix-namedsem", semIoFinder ),
46579#endif
46580#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
46581    UNIXVFS("unix-posix",    posixIoFinder ),
46582#endif
46583#if SQLITE_ENABLE_LOCKING_STYLE
46584    UNIXVFS("unix-flock",    flockIoFinder ),
46585#endif
46586#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
46587    UNIXVFS("unix-afp",      afpIoFinder ),
46588    UNIXVFS("unix-nfs",      nfsIoFinder ),
46589    UNIXVFS("unix-proxy",    proxyIoFinder ),
46590#endif
46591  };
46592  unsigned int i;          /* Loop counter */
46593
46594  /* Double-check that the aSyscall[] array has been constructed
46595  ** correctly.  See ticket [bb3a86e890c8e96ab] */
46596  assert( ArraySize(aSyscall)==29 );
46597
46598  /* Register all VFSes defined in the aVfs[] array */
46599  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
46600#ifdef SQLITE_DEFAULT_UNIX_VFS
46601    sqlite3_vfs_register(&aVfs[i],
46602           0==strcmp(aVfs[i].zName,SQLITE_DEFAULT_UNIX_VFS));
46603#else
46604    sqlite3_vfs_register(&aVfs[i], i==0);
46605#endif
46606  }
46607#ifdef SQLITE_OS_KV_OPTIONAL
46608  sqlite3KvvfsInit();
46609#endif
46610  unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
46611
46612#ifndef SQLITE_OMIT_WAL
46613  /* Validate lock assumptions */
46614  assert( SQLITE_SHM_NLOCK==8 );  /* Number of available locks */
46615  assert( UNIX_SHM_BASE==120  );  /* Start of locking area */
46616  /* Locks:
46617  **    WRITE       UNIX_SHM_BASE      120
46618  **    CKPT        UNIX_SHM_BASE+1    121
46619  **    RECOVER     UNIX_SHM_BASE+2    122
46620  **    READ-0      UNIX_SHM_BASE+3    123
46621  **    READ-1      UNIX_SHM_BASE+4    124
46622  **    READ-2      UNIX_SHM_BASE+5    125
46623  **    READ-3      UNIX_SHM_BASE+6    126
46624  **    READ-4      UNIX_SHM_BASE+7    127
46625  **    DMS         UNIX_SHM_BASE+8    128
46626  */
46627  assert( UNIX_SHM_DMS==128   );  /* Byte offset of the deadman-switch */
46628#endif
46629
46630  /* Initialize temp file dir array. */
46631  unixTempFileInit();
46632
46633  return SQLITE_OK;
46634}
46635
46636/*
46637** Shutdown the operating system interface.
46638**
46639** Some operating systems might need to do some cleanup in this routine,
46640** to release dynamically allocated objects.  But not on unix.
46641** This routine is a no-op for unix.
46642*/
46643SQLITE_API int sqlite3_os_end(void){
46644  unixBigLock = 0;
46645  return SQLITE_OK;
46646}
46647
46648#endif /* SQLITE_OS_UNIX */
46649
46650/************** End of os_unix.c *********************************************/
46651/************** Begin file os_win.c ******************************************/
46652/*
46653** 2004 May 22
46654**
46655** The author disclaims copyright to this source code.  In place of
46656** a legal notice, here is a blessing:
46657**
46658**    May you do good and not evil.
46659**    May you find forgiveness for yourself and forgive others.
46660**    May you share freely, never taking more than you give.
46661**
46662******************************************************************************
46663**
46664** This file contains code that is specific to Windows.
46665*/
46666/* #include "sqliteInt.h" */
46667#if SQLITE_OS_WIN               /* This file is used for Windows only */
46668
46669/*
46670** Include code that is common to all os_*.c files
46671*/
46672/* #include "os_common.h" */
46673
46674/*
46675** Include the header file for the Windows VFS.
46676*/
46677/* #include "os_win.h" */
46678
46679/*
46680** Compiling and using WAL mode requires several APIs that are only
46681** available in Windows platforms based on the NT kernel.
46682*/
46683#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
46684#  error "WAL mode requires support from the Windows NT kernel, compile\
46685 with SQLITE_OMIT_WAL."
46686#endif
46687
46688#if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
46689#  error "Memory mapped files require support from the Windows NT kernel,\
46690 compile with SQLITE_MAX_MMAP_SIZE=0."
46691#endif
46692
46693/*
46694** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
46695** based on the sub-platform)?
46696*/
46697#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
46698#  define SQLITE_WIN32_HAS_ANSI
46699#endif
46700
46701/*
46702** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
46703** based on the sub-platform)?
46704*/
46705#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
46706    !defined(SQLITE_WIN32_NO_WIDE)
46707#  define SQLITE_WIN32_HAS_WIDE
46708#endif
46709
46710/*
46711** Make sure at least one set of Win32 APIs is available.
46712*/
46713#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
46714#  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
46715 must be defined."
46716#endif
46717
46718/*
46719** Define the required Windows SDK version constants if they are not
46720** already available.
46721*/
46722#ifndef NTDDI_WIN8
46723#  define NTDDI_WIN8                        0x06020000
46724#endif
46725
46726#ifndef NTDDI_WINBLUE
46727#  define NTDDI_WINBLUE                     0x06030000
46728#endif
46729
46730#ifndef NTDDI_WINTHRESHOLD
46731#  define NTDDI_WINTHRESHOLD                0x06040000
46732#endif
46733
46734/*
46735** Check to see if the GetVersionEx[AW] functions are deprecated on the
46736** target system.  GetVersionEx was first deprecated in Win8.1.
46737*/
46738#ifndef SQLITE_WIN32_GETVERSIONEX
46739#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
46740#    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
46741#  else
46742#    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
46743#  endif
46744#endif
46745
46746/*
46747** Check to see if the CreateFileMappingA function is supported on the
46748** target system.  It is unavailable when using "mincore.lib" on Win10.
46749** When compiling for Windows 10, always assume "mincore.lib" is in use.
46750*/
46751#ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
46752#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
46753#    define SQLITE_WIN32_CREATEFILEMAPPINGA   0
46754#  else
46755#    define SQLITE_WIN32_CREATEFILEMAPPINGA   1
46756#  endif
46757#endif
46758
46759/*
46760** This constant should already be defined (in the "WinDef.h" SDK file).
46761*/
46762#ifndef MAX_PATH
46763#  define MAX_PATH                      (260)
46764#endif
46765
46766/*
46767** Maximum pathname length (in chars) for Win32.  This should normally be
46768** MAX_PATH.
46769*/
46770#ifndef SQLITE_WIN32_MAX_PATH_CHARS
46771#  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
46772#endif
46773
46774/*
46775** This constant should already be defined (in the "WinNT.h" SDK file).
46776*/
46777#ifndef UNICODE_STRING_MAX_CHARS
46778#  define UNICODE_STRING_MAX_CHARS      (32767)
46779#endif
46780
46781/*
46782** Maximum pathname length (in chars) for WinNT.  This should normally be
46783** UNICODE_STRING_MAX_CHARS.
46784*/
46785#ifndef SQLITE_WINNT_MAX_PATH_CHARS
46786#  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
46787#endif
46788
46789/*
46790** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
46791** characters, so we allocate 4 bytes per character assuming worst-case of
46792** 4-bytes-per-character for UTF8.
46793*/
46794#ifndef SQLITE_WIN32_MAX_PATH_BYTES
46795#  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
46796#endif
46797
46798/*
46799** Maximum pathname length (in bytes) for WinNT.  This should normally be
46800** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
46801*/
46802#ifndef SQLITE_WINNT_MAX_PATH_BYTES
46803#  define SQLITE_WINNT_MAX_PATH_BYTES   \
46804                            (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
46805#endif
46806
46807/*
46808** Maximum error message length (in chars) for WinRT.
46809*/
46810#ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
46811#  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
46812#endif
46813
46814/*
46815** Returns non-zero if the character should be treated as a directory
46816** separator.
46817*/
46818#ifndef winIsDirSep
46819#  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
46820#endif
46821
46822/*
46823** This macro is used when a local variable is set to a value that is
46824** [sometimes] not used by the code (e.g. via conditional compilation).
46825*/
46826#ifndef UNUSED_VARIABLE_VALUE
46827#  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
46828#endif
46829
46830/*
46831** Returns the character that should be used as the directory separator.
46832*/
46833#ifndef winGetDirSep
46834#  define winGetDirSep()                '\\'
46835#endif
46836
46837/*
46838** Do we need to manually define the Win32 file mapping APIs for use with WAL
46839** mode or memory mapped files (e.g. these APIs are available in the Windows
46840** CE SDK; however, they are not present in the header file)?
46841*/
46842#if SQLITE_WIN32_FILEMAPPING_API && \
46843        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
46844/*
46845** Two of the file mapping APIs are different under WinRT.  Figure out which
46846** set we need.
46847*/
46848#if SQLITE_OS_WINRT
46849WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
46850        LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
46851
46852WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
46853#else
46854#if defined(SQLITE_WIN32_HAS_ANSI)
46855WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
46856        DWORD, DWORD, DWORD, LPCSTR);
46857#endif /* defined(SQLITE_WIN32_HAS_ANSI) */
46858
46859#if defined(SQLITE_WIN32_HAS_WIDE)
46860WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
46861        DWORD, DWORD, DWORD, LPCWSTR);
46862#endif /* defined(SQLITE_WIN32_HAS_WIDE) */
46863
46864WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
46865#endif /* SQLITE_OS_WINRT */
46866
46867/*
46868** These file mapping APIs are common to both Win32 and WinRT.
46869*/
46870
46871WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
46872WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
46873#endif /* SQLITE_WIN32_FILEMAPPING_API */
46874
46875/*
46876** Some Microsoft compilers lack this definition.
46877*/
46878#ifndef INVALID_FILE_ATTRIBUTES
46879# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
46880#endif
46881
46882#ifndef FILE_FLAG_MASK
46883# define FILE_FLAG_MASK          (0xFF3C0000)
46884#endif
46885
46886#ifndef FILE_ATTRIBUTE_MASK
46887# define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
46888#endif
46889
46890#ifndef SQLITE_OMIT_WAL
46891/* Forward references to structures used for WAL */
46892typedef struct winShm winShm;           /* A connection to shared-memory */
46893typedef struct winShmNode winShmNode;   /* A region of shared-memory */
46894#endif
46895
46896/*
46897** WinCE lacks native support for file locking so we have to fake it
46898** with some code of our own.
46899*/
46900#if SQLITE_OS_WINCE
46901typedef struct winceLock {
46902  int nReaders;       /* Number of reader locks obtained */
46903  BOOL bPending;      /* Indicates a pending lock has been obtained */
46904  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
46905  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
46906} winceLock;
46907#endif
46908
46909/*
46910** The winFile structure is a subclass of sqlite3_file* specific to the win32
46911** portability layer.
46912*/
46913typedef struct winFile winFile;
46914struct winFile {
46915  const sqlite3_io_methods *pMethod; /*** Must be first ***/
46916  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
46917  HANDLE h;               /* Handle for accessing the file */
46918  u8 locktype;            /* Type of lock currently held on this file */
46919  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
46920  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
46921  DWORD lastErrno;        /* The Windows errno from the last I/O error */
46922#ifndef SQLITE_OMIT_WAL
46923  winShm *pShm;           /* Instance of shared memory on this file */
46924#endif
46925  const char *zPath;      /* Full pathname of this file */
46926  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
46927#if SQLITE_OS_WINCE
46928  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
46929  HANDLE hMutex;          /* Mutex used to control access to shared lock */
46930  HANDLE hShared;         /* Shared memory segment used for locking */
46931  winceLock local;        /* Locks obtained by this instance of winFile */
46932  winceLock *shared;      /* Global shared lock memory for the file  */
46933#endif
46934#if SQLITE_MAX_MMAP_SIZE>0
46935  int nFetchOut;                /* Number of outstanding xFetch references */
46936  HANDLE hMap;                  /* Handle for accessing memory mapping */
46937  void *pMapRegion;             /* Area memory mapped */
46938  sqlite3_int64 mmapSize;       /* Size of mapped region */
46939  sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
46940#endif
46941};
46942
46943/*
46944** The winVfsAppData structure is used for the pAppData member for all of the
46945** Win32 VFS variants.
46946*/
46947typedef struct winVfsAppData winVfsAppData;
46948struct winVfsAppData {
46949  const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
46950  void *pAppData;                    /* The extra pAppData, if any. */
46951  BOOL bNoLock;                      /* Non-zero if locking is disabled. */
46952};
46953
46954/*
46955** Allowed values for winFile.ctrlFlags
46956*/
46957#define WINFILE_RDONLY          0x02   /* Connection is read only */
46958#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
46959#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
46960
46961/*
46962 * The size of the buffer used by sqlite3_win32_write_debug().
46963 */
46964#ifndef SQLITE_WIN32_DBG_BUF_SIZE
46965#  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
46966#endif
46967
46968/*
46969 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
46970 * various Win32 API heap functions instead of our own.
46971 */
46972#ifdef SQLITE_WIN32_MALLOC
46973
46974/*
46975 * If this is non-zero, an isolated heap will be created by the native Win32
46976 * allocator subsystem; otherwise, the default process heap will be used.  This
46977 * setting has no effect when compiling for WinRT.  By default, this is enabled
46978 * and an isolated heap will be created to store all allocated data.
46979 *
46980 ******************************************************************************
46981 * WARNING: It is important to note that when this setting is non-zero and the
46982 *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
46983 *          function), all data that was allocated using the isolated heap will
46984 *          be freed immediately and any attempt to access any of that freed
46985 *          data will almost certainly result in an immediate access violation.
46986 ******************************************************************************
46987 */
46988#ifndef SQLITE_WIN32_HEAP_CREATE
46989#  define SQLITE_WIN32_HEAP_CREATE        (TRUE)
46990#endif
46991
46992/*
46993 * This is the maximum possible initial size of the Win32-specific heap, in
46994 * bytes.
46995 */
46996#ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
46997#  define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
46998#endif
46999
47000/*
47001 * This is the extra space for the initial size of the Win32-specific heap,
47002 * in bytes.  This value may be zero.
47003 */
47004#ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
47005#  define SQLITE_WIN32_HEAP_INIT_EXTRA  (4194304)
47006#endif
47007
47008/*
47009 * Calculate the maximum legal cache size, in pages, based on the maximum
47010 * possible initial heap size and the default page size, setting aside the
47011 * needed extra space.
47012 */
47013#ifndef SQLITE_WIN32_MAX_CACHE_SIZE
47014#  define SQLITE_WIN32_MAX_CACHE_SIZE   (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
47015                                          (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
47016                                         (SQLITE_DEFAULT_PAGE_SIZE))
47017#endif
47018
47019/*
47020 * This is cache size used in the calculation of the initial size of the
47021 * Win32-specific heap.  It cannot be negative.
47022 */
47023#ifndef SQLITE_WIN32_CACHE_SIZE
47024#  if SQLITE_DEFAULT_CACHE_SIZE>=0
47025#    define SQLITE_WIN32_CACHE_SIZE     (SQLITE_DEFAULT_CACHE_SIZE)
47026#  else
47027#    define SQLITE_WIN32_CACHE_SIZE     (-(SQLITE_DEFAULT_CACHE_SIZE))
47028#  endif
47029#endif
47030
47031/*
47032 * Make sure that the calculated cache size, in pages, cannot cause the
47033 * initial size of the Win32-specific heap to exceed the maximum amount
47034 * of memory that can be specified in the call to HeapCreate.
47035 */
47036#if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
47037#  undef SQLITE_WIN32_CACHE_SIZE
47038#  define SQLITE_WIN32_CACHE_SIZE       (2000)
47039#endif
47040
47041/*
47042 * The initial size of the Win32-specific heap.  This value may be zero.
47043 */
47044#ifndef SQLITE_WIN32_HEAP_INIT_SIZE
47045#  define SQLITE_WIN32_HEAP_INIT_SIZE   ((SQLITE_WIN32_CACHE_SIZE) * \
47046                                         (SQLITE_DEFAULT_PAGE_SIZE) + \
47047                                         (SQLITE_WIN32_HEAP_INIT_EXTRA))
47048#endif
47049
47050/*
47051 * The maximum size of the Win32-specific heap.  This value may be zero.
47052 */
47053#ifndef SQLITE_WIN32_HEAP_MAX_SIZE
47054#  define SQLITE_WIN32_HEAP_MAX_SIZE    (0)
47055#endif
47056
47057/*
47058 * The extra flags to use in calls to the Win32 heap APIs.  This value may be
47059 * zero for the default behavior.
47060 */
47061#ifndef SQLITE_WIN32_HEAP_FLAGS
47062#  define SQLITE_WIN32_HEAP_FLAGS       (0)
47063#endif
47064
47065
47066/*
47067** The winMemData structure stores information required by the Win32-specific
47068** sqlite3_mem_methods implementation.
47069*/
47070typedef struct winMemData winMemData;
47071struct winMemData {
47072#ifndef NDEBUG
47073  u32 magic1;   /* Magic number to detect structure corruption. */
47074#endif
47075  HANDLE hHeap; /* The handle to our heap. */
47076  BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
47077#ifndef NDEBUG
47078  u32 magic2;   /* Magic number to detect structure corruption. */
47079#endif
47080};
47081
47082#ifndef NDEBUG
47083#define WINMEM_MAGIC1     0x42b2830b
47084#define WINMEM_MAGIC2     0xbd4d7cf4
47085#endif
47086
47087static struct winMemData win_mem_data = {
47088#ifndef NDEBUG
47089  WINMEM_MAGIC1,
47090#endif
47091  NULL, FALSE
47092#ifndef NDEBUG
47093  ,WINMEM_MAGIC2
47094#endif
47095};
47096
47097#ifndef NDEBUG
47098#define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
47099#define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
47100#define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
47101#else
47102#define winMemAssertMagic()
47103#endif
47104
47105#define winMemGetDataPtr()  &win_mem_data
47106#define winMemGetHeap()     win_mem_data.hHeap
47107#define winMemGetOwned()    win_mem_data.bOwned
47108
47109static void *winMemMalloc(int nBytes);
47110static void winMemFree(void *pPrior);
47111static void *winMemRealloc(void *pPrior, int nBytes);
47112static int winMemSize(void *p);
47113static int winMemRoundup(int n);
47114static int winMemInit(void *pAppData);
47115static void winMemShutdown(void *pAppData);
47116
47117SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
47118#endif /* SQLITE_WIN32_MALLOC */
47119
47120/*
47121** The following variable is (normally) set once and never changes
47122** thereafter.  It records whether the operating system is Win9x
47123** or WinNT.
47124**
47125** 0:   Operating system unknown.
47126** 1:   Operating system is Win9x.
47127** 2:   Operating system is WinNT.
47128**
47129** In order to facilitate testing on a WinNT system, the test fixture
47130** can manually set this value to 1 to emulate Win98 behavior.
47131*/
47132#ifdef SQLITE_TEST
47133SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
47134#else
47135static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
47136#endif
47137
47138#ifndef SYSCALL
47139#  define SYSCALL sqlite3_syscall_ptr
47140#endif
47141
47142/*
47143** This function is not available on Windows CE or WinRT.
47144 */
47145
47146#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
47147#  define osAreFileApisANSI()       1
47148#endif
47149
47150/*
47151** Many system calls are accessed through pointer-to-functions so that
47152** they may be overridden at runtime to facilitate fault injection during
47153** testing and sandboxing.  The following array holds the names and pointers
47154** to all overrideable system calls.
47155*/
47156static struct win_syscall {
47157  const char *zName;            /* Name of the system call */
47158  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
47159  sqlite3_syscall_ptr pDefault; /* Default value */
47160} aSyscall[] = {
47161#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
47162  { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
47163#else
47164  { "AreFileApisANSI",         (SYSCALL)0,                       0 },
47165#endif
47166
47167#ifndef osAreFileApisANSI
47168#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
47169#endif
47170
47171#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
47172  { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
47173#else
47174  { "CharLowerW",              (SYSCALL)0,                       0 },
47175#endif
47176
47177#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
47178
47179#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
47180  { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
47181#else
47182  { "CharUpperW",              (SYSCALL)0,                       0 },
47183#endif
47184
47185#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
47186
47187  { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
47188
47189#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
47190
47191#if defined(SQLITE_WIN32_HAS_ANSI)
47192  { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
47193#else
47194  { "CreateFileA",             (SYSCALL)0,                       0 },
47195#endif
47196
47197#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
47198        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
47199
47200#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
47201  { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
47202#else
47203  { "CreateFileW",             (SYSCALL)0,                       0 },
47204#endif
47205
47206#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
47207        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
47208
47209#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
47210        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
47211        SQLITE_WIN32_CREATEFILEMAPPINGA
47212  { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
47213#else
47214  { "CreateFileMappingA",      (SYSCALL)0,                       0 },
47215#endif
47216
47217#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
47218        DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
47219
47220#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
47221        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
47222  { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
47223#else
47224  { "CreateFileMappingW",      (SYSCALL)0,                       0 },
47225#endif
47226
47227#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
47228        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
47229
47230#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
47231  { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
47232#else
47233  { "CreateMutexW",            (SYSCALL)0,                       0 },
47234#endif
47235
47236#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
47237        LPCWSTR))aSyscall[8].pCurrent)
47238
47239#if defined(SQLITE_WIN32_HAS_ANSI)
47240  { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
47241#else
47242  { "DeleteFileA",             (SYSCALL)0,                       0 },
47243#endif
47244
47245#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
47246
47247#if defined(SQLITE_WIN32_HAS_WIDE)
47248  { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
47249#else
47250  { "DeleteFileW",             (SYSCALL)0,                       0 },
47251#endif
47252
47253#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
47254
47255#if SQLITE_OS_WINCE
47256  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
47257#else
47258  { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
47259#endif
47260
47261#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
47262        LPFILETIME))aSyscall[11].pCurrent)
47263
47264#if SQLITE_OS_WINCE
47265  { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
47266#else
47267  { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
47268#endif
47269
47270#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
47271        LPSYSTEMTIME))aSyscall[12].pCurrent)
47272
47273  { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
47274
47275#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
47276
47277#if defined(SQLITE_WIN32_HAS_ANSI)
47278  { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
47279#else
47280  { "FormatMessageA",          (SYSCALL)0,                       0 },
47281#endif
47282
47283#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
47284        DWORD,va_list*))aSyscall[14].pCurrent)
47285
47286#if defined(SQLITE_WIN32_HAS_WIDE)
47287  { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
47288#else
47289  { "FormatMessageW",          (SYSCALL)0,                       0 },
47290#endif
47291
47292#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
47293        DWORD,va_list*))aSyscall[15].pCurrent)
47294
47295#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
47296  { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
47297#else
47298  { "FreeLibrary",             (SYSCALL)0,                       0 },
47299#endif
47300
47301#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
47302
47303  { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
47304
47305#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
47306
47307#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
47308  { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
47309#else
47310  { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
47311#endif
47312
47313#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
47314        LPDWORD))aSyscall[18].pCurrent)
47315
47316#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
47317  { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
47318#else
47319  { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
47320#endif
47321
47322#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
47323        LPDWORD))aSyscall[19].pCurrent)
47324
47325#if defined(SQLITE_WIN32_HAS_ANSI)
47326  { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
47327#else
47328  { "GetFileAttributesA",      (SYSCALL)0,                       0 },
47329#endif
47330
47331#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
47332
47333#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
47334  { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
47335#else
47336  { "GetFileAttributesW",      (SYSCALL)0,                       0 },
47337#endif
47338
47339#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
47340
47341#if defined(SQLITE_WIN32_HAS_WIDE)
47342  { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
47343#else
47344  { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
47345#endif
47346
47347#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
47348        LPVOID))aSyscall[22].pCurrent)
47349
47350#if !SQLITE_OS_WINRT
47351  { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
47352#else
47353  { "GetFileSize",             (SYSCALL)0,                       0 },
47354#endif
47355
47356#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
47357
47358#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
47359  { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
47360#else
47361  { "GetFullPathNameA",        (SYSCALL)0,                       0 },
47362#endif
47363
47364#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
47365        LPSTR*))aSyscall[24].pCurrent)
47366
47367#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
47368  { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
47369#else
47370  { "GetFullPathNameW",        (SYSCALL)0,                       0 },
47371#endif
47372
47373#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
47374        LPWSTR*))aSyscall[25].pCurrent)
47375
47376  { "GetLastError",            (SYSCALL)GetLastError,            0 },
47377
47378#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
47379
47380#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
47381#if SQLITE_OS_WINCE
47382  /* The GetProcAddressA() routine is only available on Windows CE. */
47383  { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
47384#else
47385  /* All other Windows platforms expect GetProcAddress() to take
47386  ** an ANSI string regardless of the _UNICODE setting */
47387  { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
47388#endif
47389#else
47390  { "GetProcAddressA",         (SYSCALL)0,                       0 },
47391#endif
47392
47393#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
47394        LPCSTR))aSyscall[27].pCurrent)
47395
47396#if !SQLITE_OS_WINRT
47397  { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
47398#else
47399  { "GetSystemInfo",           (SYSCALL)0,                       0 },
47400#endif
47401
47402#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
47403
47404  { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
47405
47406#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
47407
47408#if !SQLITE_OS_WINCE
47409  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
47410#else
47411  { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
47412#endif
47413
47414#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
47415        LPFILETIME))aSyscall[30].pCurrent)
47416
47417#if defined(SQLITE_WIN32_HAS_ANSI)
47418  { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
47419#else
47420  { "GetTempPathA",            (SYSCALL)0,                       0 },
47421#endif
47422
47423#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
47424
47425#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
47426  { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
47427#else
47428  { "GetTempPathW",            (SYSCALL)0,                       0 },
47429#endif
47430
47431#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
47432
47433#if !SQLITE_OS_WINRT
47434  { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
47435#else
47436  { "GetTickCount",            (SYSCALL)0,                       0 },
47437#endif
47438
47439#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
47440
47441#if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
47442  { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
47443#else
47444  { "GetVersionExA",           (SYSCALL)0,                       0 },
47445#endif
47446
47447#define osGetVersionExA ((BOOL(WINAPI*)( \
47448        LPOSVERSIONINFOA))aSyscall[34].pCurrent)
47449
47450#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
47451        SQLITE_WIN32_GETVERSIONEX
47452  { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
47453#else
47454  { "GetVersionExW",           (SYSCALL)0,                       0 },
47455#endif
47456
47457#define osGetVersionExW ((BOOL(WINAPI*)( \
47458        LPOSVERSIONINFOW))aSyscall[35].pCurrent)
47459
47460  { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
47461
47462#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
47463        SIZE_T))aSyscall[36].pCurrent)
47464
47465#if !SQLITE_OS_WINRT
47466  { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
47467#else
47468  { "HeapCreate",              (SYSCALL)0,                       0 },
47469#endif
47470
47471#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
47472        SIZE_T))aSyscall[37].pCurrent)
47473
47474#if !SQLITE_OS_WINRT
47475  { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
47476#else
47477  { "HeapDestroy",             (SYSCALL)0,                       0 },
47478#endif
47479
47480#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
47481
47482  { "HeapFree",                (SYSCALL)HeapFree,                0 },
47483
47484#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
47485
47486  { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
47487
47488#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
47489        SIZE_T))aSyscall[40].pCurrent)
47490
47491  { "HeapSize",                (SYSCALL)HeapSize,                0 },
47492
47493#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
47494        LPCVOID))aSyscall[41].pCurrent)
47495
47496#if !SQLITE_OS_WINRT
47497  { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
47498#else
47499  { "HeapValidate",            (SYSCALL)0,                       0 },
47500#endif
47501
47502#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
47503        LPCVOID))aSyscall[42].pCurrent)
47504
47505#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
47506  { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
47507#else
47508  { "HeapCompact",             (SYSCALL)0,                       0 },
47509#endif
47510
47511#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
47512
47513#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
47514  { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
47515#else
47516  { "LoadLibraryA",            (SYSCALL)0,                       0 },
47517#endif
47518
47519#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
47520
47521#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
47522        !defined(SQLITE_OMIT_LOAD_EXTENSION)
47523  { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
47524#else
47525  { "LoadLibraryW",            (SYSCALL)0,                       0 },
47526#endif
47527
47528#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
47529
47530#if !SQLITE_OS_WINRT
47531  { "LocalFree",               (SYSCALL)LocalFree,               0 },
47532#else
47533  { "LocalFree",               (SYSCALL)0,                       0 },
47534#endif
47535
47536#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
47537
47538#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
47539  { "LockFile",                (SYSCALL)LockFile,                0 },
47540#else
47541  { "LockFile",                (SYSCALL)0,                       0 },
47542#endif
47543
47544#ifndef osLockFile
47545#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
47546        DWORD))aSyscall[47].pCurrent)
47547#endif
47548
47549#if !SQLITE_OS_WINCE
47550  { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
47551#else
47552  { "LockFileEx",              (SYSCALL)0,                       0 },
47553#endif
47554
47555#ifndef osLockFileEx
47556#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
47557        LPOVERLAPPED))aSyscall[48].pCurrent)
47558#endif
47559
47560#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
47561        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
47562  { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
47563#else
47564  { "MapViewOfFile",           (SYSCALL)0,                       0 },
47565#endif
47566
47567#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
47568        SIZE_T))aSyscall[49].pCurrent)
47569
47570  { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
47571
47572#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
47573        int))aSyscall[50].pCurrent)
47574
47575  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
47576
47577#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
47578        LARGE_INTEGER*))aSyscall[51].pCurrent)
47579
47580  { "ReadFile",                (SYSCALL)ReadFile,                0 },
47581
47582#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
47583        LPOVERLAPPED))aSyscall[52].pCurrent)
47584
47585  { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
47586
47587#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
47588
47589#if !SQLITE_OS_WINRT
47590  { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
47591#else
47592  { "SetFilePointer",          (SYSCALL)0,                       0 },
47593#endif
47594
47595#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
47596        DWORD))aSyscall[54].pCurrent)
47597
47598#if !SQLITE_OS_WINRT
47599  { "Sleep",                   (SYSCALL)Sleep,                   0 },
47600#else
47601  { "Sleep",                   (SYSCALL)0,                       0 },
47602#endif
47603
47604#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
47605
47606  { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
47607
47608#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
47609        LPFILETIME))aSyscall[56].pCurrent)
47610
47611#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
47612  { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
47613#else
47614  { "UnlockFile",              (SYSCALL)0,                       0 },
47615#endif
47616
47617#ifndef osUnlockFile
47618#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
47619        DWORD))aSyscall[57].pCurrent)
47620#endif
47621
47622#if !SQLITE_OS_WINCE
47623  { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
47624#else
47625  { "UnlockFileEx",            (SYSCALL)0,                       0 },
47626#endif
47627
47628#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
47629        LPOVERLAPPED))aSyscall[58].pCurrent)
47630
47631#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
47632  { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
47633#else
47634  { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
47635#endif
47636
47637#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
47638
47639  { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
47640
47641#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
47642        LPCSTR,LPBOOL))aSyscall[60].pCurrent)
47643
47644  { "WriteFile",               (SYSCALL)WriteFile,               0 },
47645
47646#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
47647        LPOVERLAPPED))aSyscall[61].pCurrent)
47648
47649#if SQLITE_OS_WINRT
47650  { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
47651#else
47652  { "CreateEventExW",          (SYSCALL)0,                       0 },
47653#endif
47654
47655#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
47656        DWORD,DWORD))aSyscall[62].pCurrent)
47657
47658#if !SQLITE_OS_WINRT
47659  { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
47660#else
47661  { "WaitForSingleObject",     (SYSCALL)0,                       0 },
47662#endif
47663
47664#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
47665        DWORD))aSyscall[63].pCurrent)
47666
47667#if !SQLITE_OS_WINCE
47668  { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
47669#else
47670  { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
47671#endif
47672
47673#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
47674        BOOL))aSyscall[64].pCurrent)
47675
47676#if SQLITE_OS_WINRT
47677  { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
47678#else
47679  { "SetFilePointerEx",        (SYSCALL)0,                       0 },
47680#endif
47681
47682#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
47683        PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
47684
47685#if SQLITE_OS_WINRT
47686  { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
47687#else
47688  { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
47689#endif
47690
47691#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
47692        FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
47693
47694#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
47695  { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
47696#else
47697  { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
47698#endif
47699
47700#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
47701        SIZE_T))aSyscall[67].pCurrent)
47702
47703#if SQLITE_OS_WINRT
47704  { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
47705#else
47706  { "CreateFile2",             (SYSCALL)0,                       0 },
47707#endif
47708
47709#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
47710        LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
47711
47712#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
47713  { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
47714#else
47715  { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
47716#endif
47717
47718#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
47719        DWORD))aSyscall[69].pCurrent)
47720
47721#if SQLITE_OS_WINRT
47722  { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
47723#else
47724  { "GetTickCount64",          (SYSCALL)0,                       0 },
47725#endif
47726
47727#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
47728
47729#if SQLITE_OS_WINRT
47730  { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
47731#else
47732  { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
47733#endif
47734
47735#define osGetNativeSystemInfo ((VOID(WINAPI*)( \
47736        LPSYSTEM_INFO))aSyscall[71].pCurrent)
47737
47738#if defined(SQLITE_WIN32_HAS_ANSI)
47739  { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
47740#else
47741  { "OutputDebugStringA",      (SYSCALL)0,                       0 },
47742#endif
47743
47744#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
47745
47746#if defined(SQLITE_WIN32_HAS_WIDE)
47747  { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
47748#else
47749  { "OutputDebugStringW",      (SYSCALL)0,                       0 },
47750#endif
47751
47752#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
47753
47754  { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
47755
47756#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
47757
47758#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
47759  { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
47760#else
47761  { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
47762#endif
47763
47764#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
47765        LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
47766
47767/*
47768** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
47769**       is really just a macro that uses a compiler intrinsic (e.g. x64).
47770**       So do not try to make this is into a redefinable interface.
47771*/
47772#if defined(InterlockedCompareExchange)
47773  { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
47774
47775#define osInterlockedCompareExchange InterlockedCompareExchange
47776#else
47777  { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
47778
47779#define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
47780        SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
47781#endif /* defined(InterlockedCompareExchange) */
47782
47783#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
47784  { "UuidCreate",               (SYSCALL)UuidCreate,             0 },
47785#else
47786  { "UuidCreate",               (SYSCALL)0,                      0 },
47787#endif
47788
47789#define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
47790
47791#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
47792  { "UuidCreateSequential",     (SYSCALL)UuidCreateSequential,   0 },
47793#else
47794  { "UuidCreateSequential",     (SYSCALL)0,                      0 },
47795#endif
47796
47797#define osUuidCreateSequential \
47798        ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
47799
47800#if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
47801  { "FlushViewOfFile",          (SYSCALL)FlushViewOfFile,        0 },
47802#else
47803  { "FlushViewOfFile",          (SYSCALL)0,                      0 },
47804#endif
47805
47806#define osFlushViewOfFile \
47807        ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
47808
47809}; /* End of the overrideable system calls */
47810
47811/*
47812** This is the xSetSystemCall() method of sqlite3_vfs for all of the
47813** "win32" VFSes.  Return SQLITE_OK upon successfully updating the
47814** system call pointer, or SQLITE_NOTFOUND if there is no configurable
47815** system call named zName.
47816*/
47817static int winSetSystemCall(
47818  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
47819  const char *zName,            /* Name of system call to override */
47820  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
47821){
47822  unsigned int i;
47823  int rc = SQLITE_NOTFOUND;
47824
47825  UNUSED_PARAMETER(pNotUsed);
47826  if( zName==0 ){
47827    /* If no zName is given, restore all system calls to their default
47828    ** settings and return NULL
47829    */
47830    rc = SQLITE_OK;
47831    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
47832      if( aSyscall[i].pDefault ){
47833        aSyscall[i].pCurrent = aSyscall[i].pDefault;
47834      }
47835    }
47836  }else{
47837    /* If zName is specified, operate on only the one system call
47838    ** specified.
47839    */
47840    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
47841      if( strcmp(zName, aSyscall[i].zName)==0 ){
47842        if( aSyscall[i].pDefault==0 ){
47843          aSyscall[i].pDefault = aSyscall[i].pCurrent;
47844        }
47845        rc = SQLITE_OK;
47846        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
47847        aSyscall[i].pCurrent = pNewFunc;
47848        break;
47849      }
47850    }
47851  }
47852  return rc;
47853}
47854
47855/*
47856** Return the value of a system call.  Return NULL if zName is not a
47857** recognized system call name.  NULL is also returned if the system call
47858** is currently undefined.
47859*/
47860static sqlite3_syscall_ptr winGetSystemCall(
47861  sqlite3_vfs *pNotUsed,
47862  const char *zName
47863){
47864  unsigned int i;
47865
47866  UNUSED_PARAMETER(pNotUsed);
47867  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
47868    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
47869  }
47870  return 0;
47871}
47872
47873/*
47874** Return the name of the first system call after zName.  If zName==NULL
47875** then return the name of the first system call.  Return NULL if zName
47876** is the last system call or if zName is not the name of a valid
47877** system call.
47878*/
47879static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
47880  int i = -1;
47881
47882  UNUSED_PARAMETER(p);
47883  if( zName ){
47884    for(i=0; i<ArraySize(aSyscall)-1; i++){
47885      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
47886    }
47887  }
47888  for(i++; i<ArraySize(aSyscall); i++){
47889    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
47890  }
47891  return 0;
47892}
47893
47894#ifdef SQLITE_WIN32_MALLOC
47895/*
47896** If a Win32 native heap has been configured, this function will attempt to
47897** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
47898** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
47899** "pnLargest" argument, if non-zero, will be used to return the size of the
47900** largest committed free block in the heap, in bytes.
47901*/
47902SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
47903  int rc = SQLITE_OK;
47904  UINT nLargest = 0;
47905  HANDLE hHeap;
47906
47907  winMemAssertMagic();
47908  hHeap = winMemGetHeap();
47909  assert( hHeap!=0 );
47910  assert( hHeap!=INVALID_HANDLE_VALUE );
47911#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
47912  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
47913#endif
47914#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
47915  if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
47916    DWORD lastErrno = osGetLastError();
47917    if( lastErrno==NO_ERROR ){
47918      sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
47919                  (void*)hHeap);
47920      rc = SQLITE_NOMEM_BKPT;
47921    }else{
47922      sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
47923                  osGetLastError(), (void*)hHeap);
47924      rc = SQLITE_ERROR;
47925    }
47926  }
47927#else
47928  sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
47929              (void*)hHeap);
47930  rc = SQLITE_NOTFOUND;
47931#endif
47932  if( pnLargest ) *pnLargest = nLargest;
47933  return rc;
47934}
47935
47936/*
47937** If a Win32 native heap has been configured, this function will attempt to
47938** destroy and recreate it.  If the Win32 native heap is not isolated and/or
47939** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
47940** be returned and no changes will be made to the Win32 native heap.
47941*/
47942SQLITE_API int sqlite3_win32_reset_heap(){
47943  int rc;
47944  MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */
47945  MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
47946  MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
47947  MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
47948  sqlite3_mutex_enter(pMainMtx);
47949  sqlite3_mutex_enter(pMem);
47950  winMemAssertMagic();
47951  if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
47952    /*
47953    ** At this point, there should be no outstanding memory allocations on
47954    ** the heap.  Also, since both the main and memsys locks are currently
47955    ** being held by us, no other function (i.e. from another thread) should
47956    ** be able to even access the heap.  Attempt to destroy and recreate our
47957    ** isolated Win32 native heap now.
47958    */
47959    assert( winMemGetHeap()!=NULL );
47960    assert( winMemGetOwned() );
47961    assert( sqlite3_memory_used()==0 );
47962    winMemShutdown(winMemGetDataPtr());
47963    assert( winMemGetHeap()==NULL );
47964    assert( !winMemGetOwned() );
47965    assert( sqlite3_memory_used()==0 );
47966    rc = winMemInit(winMemGetDataPtr());
47967    assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
47968    assert( rc!=SQLITE_OK || winMemGetOwned() );
47969    assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
47970  }else{
47971    /*
47972    ** The Win32 native heap cannot be modified because it may be in use.
47973    */
47974    rc = SQLITE_BUSY;
47975  }
47976  sqlite3_mutex_leave(pMem);
47977  sqlite3_mutex_leave(pMainMtx);
47978  return rc;
47979}
47980#endif /* SQLITE_WIN32_MALLOC */
47981
47982/*
47983** This function outputs the specified (ANSI) string to the Win32 debugger
47984** (if available).
47985*/
47986
47987SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
47988  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
47989  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
47990  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
47991  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
47992#ifdef SQLITE_ENABLE_API_ARMOR
47993  if( !zBuf ){
47994    (void)SQLITE_MISUSE_BKPT;
47995    return;
47996  }
47997#endif
47998#if defined(SQLITE_WIN32_HAS_ANSI)
47999  if( nMin>0 ){
48000    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
48001    memcpy(zDbgBuf, zBuf, nMin);
48002    osOutputDebugStringA(zDbgBuf);
48003  }else{
48004    osOutputDebugStringA(zBuf);
48005  }
48006#elif defined(SQLITE_WIN32_HAS_WIDE)
48007  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
48008  if ( osMultiByteToWideChar(
48009          osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
48010          nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
48011    return;
48012  }
48013  osOutputDebugStringW((LPCWSTR)zDbgBuf);
48014#else
48015  if( nMin>0 ){
48016    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
48017    memcpy(zDbgBuf, zBuf, nMin);
48018    fprintf(stderr, "%s", zDbgBuf);
48019  }else{
48020    fprintf(stderr, "%s", zBuf);
48021  }
48022#endif
48023}
48024
48025/*
48026** The following routine suspends the current thread for at least ms
48027** milliseconds.  This is equivalent to the Win32 Sleep() interface.
48028*/
48029#if SQLITE_OS_WINRT
48030static HANDLE sleepObj = NULL;
48031#endif
48032
48033SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
48034#if SQLITE_OS_WINRT
48035  if ( sleepObj==NULL ){
48036    sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
48037                                SYNCHRONIZE);
48038  }
48039  assert( sleepObj!=NULL );
48040  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
48041#else
48042  osSleep(milliseconds);
48043#endif
48044}
48045
48046#if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
48047        SQLITE_THREADSAFE>0
48048SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
48049  DWORD rc;
48050  while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
48051                                       TRUE))==WAIT_IO_COMPLETION ){}
48052  return rc;
48053}
48054#endif
48055
48056/*
48057** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
48058** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
48059**
48060** Here is an interesting observation:  Win95, Win98, and WinME lack
48061** the LockFileEx() API.  But we can still statically link against that
48062** API as long as we don't call it when running Win95/98/ME.  A call to
48063** this routine is used to determine if the host is Win95/98/ME or
48064** WinNT/2K/XP so that we will know whether or not we can safely call
48065** the LockFileEx() API.
48066*/
48067
48068#if !SQLITE_WIN32_GETVERSIONEX
48069# define osIsNT()  (1)
48070#elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
48071# define osIsNT()  (1)
48072#elif !defined(SQLITE_WIN32_HAS_WIDE)
48073# define osIsNT()  (0)
48074#else
48075# define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
48076#endif
48077
48078/*
48079** This function determines if the machine is running a version of Windows
48080** based on the NT kernel.
48081*/
48082SQLITE_API int sqlite3_win32_is_nt(void){
48083#if SQLITE_OS_WINRT
48084  /*
48085  ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
48086  **       kernel.
48087  */
48088  return 1;
48089#elif SQLITE_WIN32_GETVERSIONEX
48090  if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
48091#if defined(SQLITE_WIN32_HAS_ANSI)
48092    OSVERSIONINFOA sInfo;
48093    sInfo.dwOSVersionInfoSize = sizeof(sInfo);
48094    osGetVersionExA(&sInfo);
48095    osInterlockedCompareExchange(&sqlite3_os_type,
48096        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
48097#elif defined(SQLITE_WIN32_HAS_WIDE)
48098    OSVERSIONINFOW sInfo;
48099    sInfo.dwOSVersionInfoSize = sizeof(sInfo);
48100    osGetVersionExW(&sInfo);
48101    osInterlockedCompareExchange(&sqlite3_os_type,
48102        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
48103#endif
48104  }
48105  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
48106#elif SQLITE_TEST
48107  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
48108#else
48109  /*
48110  ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
48111  **       deprecated are always assumed to be based on the NT kernel.
48112  */
48113  return 1;
48114#endif
48115}
48116
48117#ifdef SQLITE_WIN32_MALLOC
48118/*
48119** Allocate nBytes of memory.
48120*/
48121static void *winMemMalloc(int nBytes){
48122  HANDLE hHeap;
48123  void *p;
48124
48125  winMemAssertMagic();
48126  hHeap = winMemGetHeap();
48127  assert( hHeap!=0 );
48128  assert( hHeap!=INVALID_HANDLE_VALUE );
48129#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
48130  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
48131#endif
48132  assert( nBytes>=0 );
48133  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
48134  if( !p ){
48135    sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
48136                nBytes, osGetLastError(), (void*)hHeap);
48137  }
48138  return p;
48139}
48140
48141/*
48142** Free memory.
48143*/
48144static void winMemFree(void *pPrior){
48145  HANDLE hHeap;
48146
48147  winMemAssertMagic();
48148  hHeap = winMemGetHeap();
48149  assert( hHeap!=0 );
48150  assert( hHeap!=INVALID_HANDLE_VALUE );
48151#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
48152  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
48153#endif
48154  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
48155  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
48156    sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
48157                pPrior, osGetLastError(), (void*)hHeap);
48158  }
48159}
48160
48161/*
48162** Change the size of an existing memory allocation
48163*/
48164static void *winMemRealloc(void *pPrior, int nBytes){
48165  HANDLE hHeap;
48166  void *p;
48167
48168  winMemAssertMagic();
48169  hHeap = winMemGetHeap();
48170  assert( hHeap!=0 );
48171  assert( hHeap!=INVALID_HANDLE_VALUE );
48172#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
48173  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
48174#endif
48175  assert( nBytes>=0 );
48176  if( !pPrior ){
48177    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
48178  }else{
48179    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
48180  }
48181  if( !p ){
48182    sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
48183                pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
48184                (void*)hHeap);
48185  }
48186  return p;
48187}
48188
48189/*
48190** Return the size of an outstanding allocation, in bytes.
48191*/
48192static int winMemSize(void *p){
48193  HANDLE hHeap;
48194  SIZE_T n;
48195
48196  winMemAssertMagic();
48197  hHeap = winMemGetHeap();
48198  assert( hHeap!=0 );
48199  assert( hHeap!=INVALID_HANDLE_VALUE );
48200#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
48201  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
48202#endif
48203  if( !p ) return 0;
48204  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
48205  if( n==(SIZE_T)-1 ){
48206    sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
48207                p, osGetLastError(), (void*)hHeap);
48208    return 0;
48209  }
48210  return (int)n;
48211}
48212
48213/*
48214** Round up a request size to the next valid allocation size.
48215*/
48216static int winMemRoundup(int n){
48217  return n;
48218}
48219
48220/*
48221** Initialize this module.
48222*/
48223static int winMemInit(void *pAppData){
48224  winMemData *pWinMemData = (winMemData *)pAppData;
48225
48226  if( !pWinMemData ) return SQLITE_ERROR;
48227  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
48228  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
48229
48230#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
48231  if( !pWinMemData->hHeap ){
48232    DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
48233    DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
48234    if( dwMaximumSize==0 ){
48235      dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
48236    }else if( dwInitialSize>dwMaximumSize ){
48237      dwInitialSize = dwMaximumSize;
48238    }
48239    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
48240                                      dwInitialSize, dwMaximumSize);
48241    if( !pWinMemData->hHeap ){
48242      sqlite3_log(SQLITE_NOMEM,
48243          "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
48244          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
48245          dwMaximumSize);
48246      return SQLITE_NOMEM_BKPT;
48247    }
48248    pWinMemData->bOwned = TRUE;
48249    assert( pWinMemData->bOwned );
48250  }
48251#else
48252  pWinMemData->hHeap = osGetProcessHeap();
48253  if( !pWinMemData->hHeap ){
48254    sqlite3_log(SQLITE_NOMEM,
48255        "failed to GetProcessHeap (%lu)", osGetLastError());
48256    return SQLITE_NOMEM_BKPT;
48257  }
48258  pWinMemData->bOwned = FALSE;
48259  assert( !pWinMemData->bOwned );
48260#endif
48261  assert( pWinMemData->hHeap!=0 );
48262  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
48263#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
48264  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
48265#endif
48266  return SQLITE_OK;
48267}
48268
48269/*
48270** Deinitialize this module.
48271*/
48272static void winMemShutdown(void *pAppData){
48273  winMemData *pWinMemData = (winMemData *)pAppData;
48274
48275  if( !pWinMemData ) return;
48276  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
48277  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
48278
48279  if( pWinMemData->hHeap ){
48280    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
48281#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
48282    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
48283#endif
48284    if( pWinMemData->bOwned ){
48285      if( !osHeapDestroy(pWinMemData->hHeap) ){
48286        sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
48287                    osGetLastError(), (void*)pWinMemData->hHeap);
48288      }
48289      pWinMemData->bOwned = FALSE;
48290    }
48291    pWinMemData->hHeap = NULL;
48292  }
48293}
48294
48295/*
48296** Populate the low-level memory allocation function pointers in
48297** sqlite3GlobalConfig.m with pointers to the routines in this file. The
48298** arguments specify the block of memory to manage.
48299**
48300** This routine is only called by sqlite3_config(), and therefore
48301** is not required to be threadsafe (it is not).
48302*/
48303SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
48304  static const sqlite3_mem_methods winMemMethods = {
48305    winMemMalloc,
48306    winMemFree,
48307    winMemRealloc,
48308    winMemSize,
48309    winMemRoundup,
48310    winMemInit,
48311    winMemShutdown,
48312    &win_mem_data
48313  };
48314  return &winMemMethods;
48315}
48316
48317SQLITE_PRIVATE void sqlite3MemSetDefault(void){
48318  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
48319}
48320#endif /* SQLITE_WIN32_MALLOC */
48321
48322/*
48323** Convert a UTF-8 string to Microsoft Unicode.
48324**
48325** Space to hold the returned string is obtained from sqlite3_malloc().
48326*/
48327static LPWSTR winUtf8ToUnicode(const char *zText){
48328  int nChar;
48329  LPWSTR zWideText;
48330
48331  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
48332  if( nChar==0 ){
48333    return 0;
48334  }
48335  zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
48336  if( zWideText==0 ){
48337    return 0;
48338  }
48339  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
48340                                nChar);
48341  if( nChar==0 ){
48342    sqlite3_free(zWideText);
48343    zWideText = 0;
48344  }
48345  return zWideText;
48346}
48347
48348/*
48349** Convert a Microsoft Unicode string to UTF-8.
48350**
48351** Space to hold the returned string is obtained from sqlite3_malloc().
48352*/
48353static char *winUnicodeToUtf8(LPCWSTR zWideText){
48354  int nByte;
48355  char *zText;
48356
48357  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
48358  if( nByte == 0 ){
48359    return 0;
48360  }
48361  zText = sqlite3MallocZero( nByte );
48362  if( zText==0 ){
48363    return 0;
48364  }
48365  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
48366                                0, 0);
48367  if( nByte == 0 ){
48368    sqlite3_free(zText);
48369    zText = 0;
48370  }
48371  return zText;
48372}
48373
48374/*
48375** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
48376** code page.
48377**
48378** Space to hold the returned string is obtained from sqlite3_malloc().
48379*/
48380static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
48381  int nByte;
48382  LPWSTR zMbcsText;
48383  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
48384
48385  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
48386                                0)*sizeof(WCHAR);
48387  if( nByte==0 ){
48388    return 0;
48389  }
48390  zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
48391  if( zMbcsText==0 ){
48392    return 0;
48393  }
48394  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
48395                                nByte);
48396  if( nByte==0 ){
48397    sqlite3_free(zMbcsText);
48398    zMbcsText = 0;
48399  }
48400  return zMbcsText;
48401}
48402
48403/*
48404** Convert a Microsoft Unicode string to a multi-byte character string,
48405** using the ANSI or OEM code page.
48406**
48407** Space to hold the returned string is obtained from sqlite3_malloc().
48408*/
48409static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
48410  int nByte;
48411  char *zText;
48412  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
48413
48414  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
48415  if( nByte == 0 ){
48416    return 0;
48417  }
48418  zText = sqlite3MallocZero( nByte );
48419  if( zText==0 ){
48420    return 0;
48421  }
48422  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
48423                                nByte, 0, 0);
48424  if( nByte == 0 ){
48425    sqlite3_free(zText);
48426    zText = 0;
48427  }
48428  return zText;
48429}
48430
48431/*
48432** Convert a multi-byte character string to UTF-8.
48433**
48434** Space to hold the returned string is obtained from sqlite3_malloc().
48435*/
48436static char *winMbcsToUtf8(const char *zText, int useAnsi){
48437  char *zTextUtf8;
48438  LPWSTR zTmpWide;
48439
48440  zTmpWide = winMbcsToUnicode(zText, useAnsi);
48441  if( zTmpWide==0 ){
48442    return 0;
48443  }
48444  zTextUtf8 = winUnicodeToUtf8(zTmpWide);
48445  sqlite3_free(zTmpWide);
48446  return zTextUtf8;
48447}
48448
48449/*
48450** Convert a UTF-8 string to a multi-byte character string.
48451**
48452** Space to hold the returned string is obtained from sqlite3_malloc().
48453*/
48454static char *winUtf8ToMbcs(const char *zText, int useAnsi){
48455  char *zTextMbcs;
48456  LPWSTR zTmpWide;
48457
48458  zTmpWide = winUtf8ToUnicode(zText);
48459  if( zTmpWide==0 ){
48460    return 0;
48461  }
48462  zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
48463  sqlite3_free(zTmpWide);
48464  return zTextMbcs;
48465}
48466
48467/*
48468** This is a public wrapper for the winUtf8ToUnicode() function.
48469*/
48470SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
48471#ifdef SQLITE_ENABLE_API_ARMOR
48472  if( !zText ){
48473    (void)SQLITE_MISUSE_BKPT;
48474    return 0;
48475  }
48476#endif
48477#ifndef SQLITE_OMIT_AUTOINIT
48478  if( sqlite3_initialize() ) return 0;
48479#endif
48480  return winUtf8ToUnicode(zText);
48481}
48482
48483/*
48484** This is a public wrapper for the winUnicodeToUtf8() function.
48485*/
48486SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
48487#ifdef SQLITE_ENABLE_API_ARMOR
48488  if( !zWideText ){
48489    (void)SQLITE_MISUSE_BKPT;
48490    return 0;
48491  }
48492#endif
48493#ifndef SQLITE_OMIT_AUTOINIT
48494  if( sqlite3_initialize() ) return 0;
48495#endif
48496  return winUnicodeToUtf8(zWideText);
48497}
48498
48499/*
48500** This is a public wrapper for the winMbcsToUtf8() function.
48501*/
48502SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
48503#ifdef SQLITE_ENABLE_API_ARMOR
48504  if( !zText ){
48505    (void)SQLITE_MISUSE_BKPT;
48506    return 0;
48507  }
48508#endif
48509#ifndef SQLITE_OMIT_AUTOINIT
48510  if( sqlite3_initialize() ) return 0;
48511#endif
48512  return winMbcsToUtf8(zText, osAreFileApisANSI());
48513}
48514
48515/*
48516** This is a public wrapper for the winMbcsToUtf8() function.
48517*/
48518SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
48519#ifdef SQLITE_ENABLE_API_ARMOR
48520  if( !zText ){
48521    (void)SQLITE_MISUSE_BKPT;
48522    return 0;
48523  }
48524#endif
48525#ifndef SQLITE_OMIT_AUTOINIT
48526  if( sqlite3_initialize() ) return 0;
48527#endif
48528  return winMbcsToUtf8(zText, useAnsi);
48529}
48530
48531/*
48532** This is a public wrapper for the winUtf8ToMbcs() function.
48533*/
48534SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
48535#ifdef SQLITE_ENABLE_API_ARMOR
48536  if( !zText ){
48537    (void)SQLITE_MISUSE_BKPT;
48538    return 0;
48539  }
48540#endif
48541#ifndef SQLITE_OMIT_AUTOINIT
48542  if( sqlite3_initialize() ) return 0;
48543#endif
48544  return winUtf8ToMbcs(zText, osAreFileApisANSI());
48545}
48546
48547/*
48548** This is a public wrapper for the winUtf8ToMbcs() function.
48549*/
48550SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
48551#ifdef SQLITE_ENABLE_API_ARMOR
48552  if( !zText ){
48553    (void)SQLITE_MISUSE_BKPT;
48554    return 0;
48555  }
48556#endif
48557#ifndef SQLITE_OMIT_AUTOINIT
48558  if( sqlite3_initialize() ) return 0;
48559#endif
48560  return winUtf8ToMbcs(zText, useAnsi);
48561}
48562
48563/*
48564** This function is the same as sqlite3_win32_set_directory (below); however,
48565** it accepts a UTF-8 string.
48566*/
48567SQLITE_API int sqlite3_win32_set_directory8(
48568  unsigned long type, /* Identifier for directory being set or reset */
48569  const char *zValue  /* New value for directory being set or reset */
48570){
48571  char **ppDirectory = 0;
48572  int rc;
48573#ifndef SQLITE_OMIT_AUTOINIT
48574  rc = sqlite3_initialize();
48575  if( rc ) return rc;
48576#endif
48577  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
48578  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
48579    ppDirectory = &sqlite3_data_directory;
48580  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
48581    ppDirectory = &sqlite3_temp_directory;
48582  }
48583  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
48584          || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
48585  );
48586  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
48587  if( ppDirectory ){
48588    char *zCopy = 0;
48589    if( zValue && zValue[0] ){
48590      zCopy = sqlite3_mprintf("%s", zValue);
48591      if ( zCopy==0 ){
48592        rc = SQLITE_NOMEM_BKPT;
48593        goto set_directory8_done;
48594      }
48595    }
48596    sqlite3_free(*ppDirectory);
48597    *ppDirectory = zCopy;
48598    rc = SQLITE_OK;
48599  }else{
48600    rc = SQLITE_ERROR;
48601  }
48602set_directory8_done:
48603  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
48604  return rc;
48605}
48606
48607/*
48608** This function is the same as sqlite3_win32_set_directory (below); however,
48609** it accepts a UTF-16 string.
48610*/
48611SQLITE_API int sqlite3_win32_set_directory16(
48612  unsigned long type, /* Identifier for directory being set or reset */
48613  const void *zValue  /* New value for directory being set or reset */
48614){
48615  int rc;
48616  char *zUtf8 = 0;
48617  if( zValue ){
48618    zUtf8 = sqlite3_win32_unicode_to_utf8(zValue);
48619    if( zUtf8==0 ) return SQLITE_NOMEM_BKPT;
48620  }
48621  rc = sqlite3_win32_set_directory8(type, zUtf8);
48622  if( zUtf8 ) sqlite3_free(zUtf8);
48623  return rc;
48624}
48625
48626/*
48627** This function sets the data directory or the temporary directory based on
48628** the provided arguments.  The type argument must be 1 in order to set the
48629** data directory or 2 in order to set the temporary directory.  The zValue
48630** argument is the name of the directory to use.  The return value will be
48631** SQLITE_OK if successful.
48632*/
48633SQLITE_API int sqlite3_win32_set_directory(
48634  unsigned long type, /* Identifier for directory being set or reset */
48635  void *zValue        /* New value for directory being set or reset */
48636){
48637  return sqlite3_win32_set_directory16(type, zValue);
48638}
48639
48640/*
48641** The return value of winGetLastErrorMsg
48642** is zero if the error message fits in the buffer, or non-zero
48643** otherwise (if the message was truncated).
48644*/
48645static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
48646  /* FormatMessage returns 0 on failure.  Otherwise it
48647  ** returns the number of TCHARs written to the output
48648  ** buffer, excluding the terminating null char.
48649  */
48650  DWORD dwLen = 0;
48651  char *zOut = 0;
48652
48653  if( osIsNT() ){
48654#if SQLITE_OS_WINRT
48655    WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
48656    dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
48657                             FORMAT_MESSAGE_IGNORE_INSERTS,
48658                             NULL,
48659                             lastErrno,
48660                             0,
48661                             zTempWide,
48662                             SQLITE_WIN32_MAX_ERRMSG_CHARS,
48663                             0);
48664#else
48665    LPWSTR zTempWide = NULL;
48666    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
48667                             FORMAT_MESSAGE_FROM_SYSTEM |
48668                             FORMAT_MESSAGE_IGNORE_INSERTS,
48669                             NULL,
48670                             lastErrno,
48671                             0,
48672                             (LPWSTR) &zTempWide,
48673                             0,
48674                             0);
48675#endif
48676    if( dwLen > 0 ){
48677      /* allocate a buffer and convert to UTF8 */
48678      sqlite3BeginBenignMalloc();
48679      zOut = winUnicodeToUtf8(zTempWide);
48680      sqlite3EndBenignMalloc();
48681#if !SQLITE_OS_WINRT
48682      /* free the system buffer allocated by FormatMessage */
48683      osLocalFree(zTempWide);
48684#endif
48685    }
48686  }
48687#ifdef SQLITE_WIN32_HAS_ANSI
48688  else{
48689    char *zTemp = NULL;
48690    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
48691                             FORMAT_MESSAGE_FROM_SYSTEM |
48692                             FORMAT_MESSAGE_IGNORE_INSERTS,
48693                             NULL,
48694                             lastErrno,
48695                             0,
48696                             (LPSTR) &zTemp,
48697                             0,
48698                             0);
48699    if( dwLen > 0 ){
48700      /* allocate a buffer and convert to UTF8 */
48701      sqlite3BeginBenignMalloc();
48702      zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
48703      sqlite3EndBenignMalloc();
48704      /* free the system buffer allocated by FormatMessage */
48705      osLocalFree(zTemp);
48706    }
48707  }
48708#endif
48709  if( 0 == dwLen ){
48710    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
48711  }else{
48712    /* copy a maximum of nBuf chars to output buffer */
48713    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
48714    /* free the UTF8 buffer */
48715    sqlite3_free(zOut);
48716  }
48717  return 0;
48718}
48719
48720/*
48721**
48722** This function - winLogErrorAtLine() - is only ever called via the macro
48723** winLogError().
48724**
48725** This routine is invoked after an error occurs in an OS function.
48726** It logs a message using sqlite3_log() containing the current value of
48727** error code and, if possible, the human-readable equivalent from
48728** FormatMessage.
48729**
48730** The first argument passed to the macro should be the error code that
48731** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
48732** The two subsequent arguments should be the name of the OS function that
48733** failed and the associated file-system path, if any.
48734*/
48735#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
48736static int winLogErrorAtLine(
48737  int errcode,                    /* SQLite error code */
48738  DWORD lastErrno,                /* Win32 last error */
48739  const char *zFunc,              /* Name of OS function that failed */
48740  const char *zPath,              /* File path associated with error */
48741  int iLine                       /* Source line number where error occurred */
48742){
48743  char zMsg[500];                 /* Human readable error text */
48744  int i;                          /* Loop counter */
48745
48746  zMsg[0] = 0;
48747  winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
48748  assert( errcode!=SQLITE_OK );
48749  if( zPath==0 ) zPath = "";
48750  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
48751  zMsg[i] = 0;
48752  sqlite3_log(errcode,
48753      "os_win.c:%d: (%lu) %s(%s) - %s",
48754      iLine, lastErrno, zFunc, zPath, zMsg
48755  );
48756
48757  return errcode;
48758}
48759
48760/*
48761** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
48762** will be retried following a locking error - probably caused by
48763** antivirus software.  Also the initial delay before the first retry.
48764** The delay increases linearly with each retry.
48765*/
48766#ifndef SQLITE_WIN32_IOERR_RETRY
48767# define SQLITE_WIN32_IOERR_RETRY 10
48768#endif
48769#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
48770# define SQLITE_WIN32_IOERR_RETRY_DELAY 25
48771#endif
48772static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
48773static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
48774
48775/*
48776** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
48777** error code obtained via GetLastError() is eligible to be retried.  It
48778** must accept the error code DWORD as its only argument and should return
48779** non-zero if the error code is transient in nature and the operation
48780** responsible for generating the original error might succeed upon being
48781** retried.  The argument to this macro should be a variable.
48782**
48783** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
48784** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
48785** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
48786** may be used to include additional error codes in the set that should
48787** result in the failing I/O operation being retried by the caller.  If
48788** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
48789** identical to those of the "winIoerrCanRetry1" macro.
48790*/
48791#if !defined(winIoerrCanRetry1)
48792#define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
48793                              ((a)==ERROR_SHARING_VIOLATION)    || \
48794                              ((a)==ERROR_LOCK_VIOLATION)       || \
48795                              ((a)==ERROR_DEV_NOT_EXIST)        || \
48796                              ((a)==ERROR_NETNAME_DELETED)      || \
48797                              ((a)==ERROR_SEM_TIMEOUT)          || \
48798                              ((a)==ERROR_NETWORK_UNREACHABLE))
48799#endif
48800
48801/*
48802** If a ReadFile() or WriteFile() error occurs, invoke this routine
48803** to see if it should be retried.  Return TRUE to retry.  Return FALSE
48804** to give up with an error.
48805*/
48806static int winRetryIoerr(int *pnRetry, DWORD *pError){
48807  DWORD e = osGetLastError();
48808  if( *pnRetry>=winIoerrRetry ){
48809    if( pError ){
48810      *pError = e;
48811    }
48812    return 0;
48813  }
48814  if( winIoerrCanRetry1(e) ){
48815    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
48816    ++*pnRetry;
48817    return 1;
48818  }
48819#if defined(winIoerrCanRetry2)
48820  else if( winIoerrCanRetry2(e) ){
48821    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
48822    ++*pnRetry;
48823    return 1;
48824  }
48825#endif
48826  if( pError ){
48827    *pError = e;
48828  }
48829  return 0;
48830}
48831
48832/*
48833** Log a I/O error retry episode.
48834*/
48835static void winLogIoerr(int nRetry, int lineno){
48836  if( nRetry ){
48837    sqlite3_log(SQLITE_NOTICE,
48838      "delayed %dms for lock/sharing conflict at line %d",
48839      winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
48840    );
48841  }
48842}
48843
48844/*
48845** This #if does not rely on the SQLITE_OS_WINCE define because the
48846** corresponding section in "date.c" cannot use it.
48847*/
48848#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
48849    (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
48850/*
48851** The MSVC CRT on Windows CE may not have a localtime() function.
48852** So define a substitute.
48853*/
48854/* #  include <time.h> */
48855struct tm *__cdecl localtime(const time_t *t)
48856{
48857  static struct tm y;
48858  FILETIME uTm, lTm;
48859  SYSTEMTIME pTm;
48860  sqlite3_int64 t64;
48861  t64 = *t;
48862  t64 = (t64 + 11644473600)*10000000;
48863  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
48864  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
48865  osFileTimeToLocalFileTime(&uTm,&lTm);
48866  osFileTimeToSystemTime(&lTm,&pTm);
48867  y.tm_year = pTm.wYear - 1900;
48868  y.tm_mon = pTm.wMonth - 1;
48869  y.tm_wday = pTm.wDayOfWeek;
48870  y.tm_mday = pTm.wDay;
48871  y.tm_hour = pTm.wHour;
48872  y.tm_min = pTm.wMinute;
48873  y.tm_sec = pTm.wSecond;
48874  return &y;
48875}
48876#endif
48877
48878#if SQLITE_OS_WINCE
48879/*************************************************************************
48880** This section contains code for WinCE only.
48881*/
48882#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
48883
48884/*
48885** Acquire a lock on the handle h
48886*/
48887static void winceMutexAcquire(HANDLE h){
48888   DWORD dwErr;
48889   do {
48890     dwErr = osWaitForSingleObject(h, INFINITE);
48891   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
48892}
48893/*
48894** Release a lock acquired by winceMutexAcquire()
48895*/
48896#define winceMutexRelease(h) ReleaseMutex(h)
48897
48898/*
48899** Create the mutex and shared memory used for locking in the file
48900** descriptor pFile
48901*/
48902static int winceCreateLock(const char *zFilename, winFile *pFile){
48903  LPWSTR zTok;
48904  LPWSTR zName;
48905  DWORD lastErrno;
48906  BOOL bLogged = FALSE;
48907  BOOL bInit = TRUE;
48908
48909  zName = winUtf8ToUnicode(zFilename);
48910  if( zName==0 ){
48911    /* out of memory */
48912    return SQLITE_IOERR_NOMEM_BKPT;
48913  }
48914
48915  /* Initialize the local lockdata */
48916  memset(&pFile->local, 0, sizeof(pFile->local));
48917
48918  /* Replace the backslashes from the filename and lowercase it
48919  ** to derive a mutex name. */
48920  zTok = osCharLowerW(zName);
48921  for (;*zTok;zTok++){
48922    if (*zTok == '\\') *zTok = '_';
48923  }
48924
48925  /* Create/open the named mutex */
48926  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
48927  if (!pFile->hMutex){
48928    pFile->lastErrno = osGetLastError();
48929    sqlite3_free(zName);
48930    return winLogError(SQLITE_IOERR, pFile->lastErrno,
48931                       "winceCreateLock1", zFilename);
48932  }
48933
48934  /* Acquire the mutex before continuing */
48935  winceMutexAcquire(pFile->hMutex);
48936
48937  /* Since the names of named mutexes, semaphores, file mappings etc are
48938  ** case-sensitive, take advantage of that by uppercasing the mutex name
48939  ** and using that as the shared filemapping name.
48940  */
48941  osCharUpperW(zName);
48942  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
48943                                        PAGE_READWRITE, 0, sizeof(winceLock),
48944                                        zName);
48945
48946  /* Set a flag that indicates we're the first to create the memory so it
48947  ** must be zero-initialized */
48948  lastErrno = osGetLastError();
48949  if (lastErrno == ERROR_ALREADY_EXISTS){
48950    bInit = FALSE;
48951  }
48952
48953  sqlite3_free(zName);
48954
48955  /* If we succeeded in making the shared memory handle, map it. */
48956  if( pFile->hShared ){
48957    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
48958             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
48959    /* If mapping failed, close the shared memory handle and erase it */
48960    if( !pFile->shared ){
48961      pFile->lastErrno = osGetLastError();
48962      winLogError(SQLITE_IOERR, pFile->lastErrno,
48963                  "winceCreateLock2", zFilename);
48964      bLogged = TRUE;
48965      osCloseHandle(pFile->hShared);
48966      pFile->hShared = NULL;
48967    }
48968  }
48969
48970  /* If shared memory could not be created, then close the mutex and fail */
48971  if( pFile->hShared==NULL ){
48972    if( !bLogged ){
48973      pFile->lastErrno = lastErrno;
48974      winLogError(SQLITE_IOERR, pFile->lastErrno,
48975                  "winceCreateLock3", zFilename);
48976      bLogged = TRUE;
48977    }
48978    winceMutexRelease(pFile->hMutex);
48979    osCloseHandle(pFile->hMutex);
48980    pFile->hMutex = NULL;
48981    return SQLITE_IOERR;
48982  }
48983
48984  /* Initialize the shared memory if we're supposed to */
48985  if( bInit ){
48986    memset(pFile->shared, 0, sizeof(winceLock));
48987  }
48988
48989  winceMutexRelease(pFile->hMutex);
48990  return SQLITE_OK;
48991}
48992
48993/*
48994** Destroy the part of winFile that deals with wince locks
48995*/
48996static void winceDestroyLock(winFile *pFile){
48997  if (pFile->hMutex){
48998    /* Acquire the mutex */
48999    winceMutexAcquire(pFile->hMutex);
49000
49001    /* The following blocks should probably assert in debug mode, but they
49002       are to cleanup in case any locks remained open */
49003    if (pFile->local.nReaders){
49004      pFile->shared->nReaders --;
49005    }
49006    if (pFile->local.bReserved){
49007      pFile->shared->bReserved = FALSE;
49008    }
49009    if (pFile->local.bPending){
49010      pFile->shared->bPending = FALSE;
49011    }
49012    if (pFile->local.bExclusive){
49013      pFile->shared->bExclusive = FALSE;
49014    }
49015
49016    /* De-reference and close our copy of the shared memory handle */
49017    osUnmapViewOfFile(pFile->shared);
49018    osCloseHandle(pFile->hShared);
49019
49020    /* Done with the mutex */
49021    winceMutexRelease(pFile->hMutex);
49022    osCloseHandle(pFile->hMutex);
49023    pFile->hMutex = NULL;
49024  }
49025}
49026
49027/*
49028** An implementation of the LockFile() API of Windows for CE
49029*/
49030static BOOL winceLockFile(
49031  LPHANDLE phFile,
49032  DWORD dwFileOffsetLow,
49033  DWORD dwFileOffsetHigh,
49034  DWORD nNumberOfBytesToLockLow,
49035  DWORD nNumberOfBytesToLockHigh
49036){
49037  winFile *pFile = HANDLE_TO_WINFILE(phFile);
49038  BOOL bReturn = FALSE;
49039
49040  UNUSED_PARAMETER(dwFileOffsetHigh);
49041  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
49042
49043  if (!pFile->hMutex) return TRUE;
49044  winceMutexAcquire(pFile->hMutex);
49045
49046  /* Wanting an exclusive lock? */
49047  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
49048       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
49049    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
49050       pFile->shared->bExclusive = TRUE;
49051       pFile->local.bExclusive = TRUE;
49052       bReturn = TRUE;
49053    }
49054  }
49055
49056  /* Want a read-only lock? */
49057  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
49058           nNumberOfBytesToLockLow == 1){
49059    if (pFile->shared->bExclusive == 0){
49060      pFile->local.nReaders ++;
49061      if (pFile->local.nReaders == 1){
49062        pFile->shared->nReaders ++;
49063      }
49064      bReturn = TRUE;
49065    }
49066  }
49067
49068  /* Want a pending lock? */
49069  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
49070           && nNumberOfBytesToLockLow == 1){
49071    /* If no pending lock has been acquired, then acquire it */
49072    if (pFile->shared->bPending == 0) {
49073      pFile->shared->bPending = TRUE;
49074      pFile->local.bPending = TRUE;
49075      bReturn = TRUE;
49076    }
49077  }
49078
49079  /* Want a reserved lock? */
49080  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
49081           && nNumberOfBytesToLockLow == 1){
49082    if (pFile->shared->bReserved == 0) {
49083      pFile->shared->bReserved = TRUE;
49084      pFile->local.bReserved = TRUE;
49085      bReturn = TRUE;
49086    }
49087  }
49088
49089  winceMutexRelease(pFile->hMutex);
49090  return bReturn;
49091}
49092
49093/*
49094** An implementation of the UnlockFile API of Windows for CE
49095*/
49096static BOOL winceUnlockFile(
49097  LPHANDLE phFile,
49098  DWORD dwFileOffsetLow,
49099  DWORD dwFileOffsetHigh,
49100  DWORD nNumberOfBytesToUnlockLow,
49101  DWORD nNumberOfBytesToUnlockHigh
49102){
49103  winFile *pFile = HANDLE_TO_WINFILE(phFile);
49104  BOOL bReturn = FALSE;
49105
49106  UNUSED_PARAMETER(dwFileOffsetHigh);
49107  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
49108
49109  if (!pFile->hMutex) return TRUE;
49110  winceMutexAcquire(pFile->hMutex);
49111
49112  /* Releasing a reader lock or an exclusive lock */
49113  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
49114    /* Did we have an exclusive lock? */
49115    if (pFile->local.bExclusive){
49116      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
49117      pFile->local.bExclusive = FALSE;
49118      pFile->shared->bExclusive = FALSE;
49119      bReturn = TRUE;
49120    }
49121
49122    /* Did we just have a reader lock? */
49123    else if (pFile->local.nReaders){
49124      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
49125             || nNumberOfBytesToUnlockLow == 1);
49126      pFile->local.nReaders --;
49127      if (pFile->local.nReaders == 0)
49128      {
49129        pFile->shared->nReaders --;
49130      }
49131      bReturn = TRUE;
49132    }
49133  }
49134
49135  /* Releasing a pending lock */
49136  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
49137           && nNumberOfBytesToUnlockLow == 1){
49138    if (pFile->local.bPending){
49139      pFile->local.bPending = FALSE;
49140      pFile->shared->bPending = FALSE;
49141      bReturn = TRUE;
49142    }
49143  }
49144  /* Releasing a reserved lock */
49145  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
49146           && nNumberOfBytesToUnlockLow == 1){
49147    if (pFile->local.bReserved) {
49148      pFile->local.bReserved = FALSE;
49149      pFile->shared->bReserved = FALSE;
49150      bReturn = TRUE;
49151    }
49152  }
49153
49154  winceMutexRelease(pFile->hMutex);
49155  return bReturn;
49156}
49157/*
49158** End of the special code for wince
49159*****************************************************************************/
49160#endif /* SQLITE_OS_WINCE */
49161
49162/*
49163** Lock a file region.
49164*/
49165static BOOL winLockFile(
49166  LPHANDLE phFile,
49167  DWORD flags,
49168  DWORD offsetLow,
49169  DWORD offsetHigh,
49170  DWORD numBytesLow,
49171  DWORD numBytesHigh
49172){
49173#if SQLITE_OS_WINCE
49174  /*
49175  ** NOTE: Windows CE is handled differently here due its lack of the Win32
49176  **       API LockFile.
49177  */
49178  return winceLockFile(phFile, offsetLow, offsetHigh,
49179                       numBytesLow, numBytesHigh);
49180#else
49181  if( osIsNT() ){
49182    OVERLAPPED ovlp;
49183    memset(&ovlp, 0, sizeof(OVERLAPPED));
49184    ovlp.Offset = offsetLow;
49185    ovlp.OffsetHigh = offsetHigh;
49186    return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
49187  }else{
49188    return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
49189                      numBytesHigh);
49190  }
49191#endif
49192}
49193
49194/*
49195** Unlock a file region.
49196 */
49197static BOOL winUnlockFile(
49198  LPHANDLE phFile,
49199  DWORD offsetLow,
49200  DWORD offsetHigh,
49201  DWORD numBytesLow,
49202  DWORD numBytesHigh
49203){
49204#if SQLITE_OS_WINCE
49205  /*
49206  ** NOTE: Windows CE is handled differently here due its lack of the Win32
49207  **       API UnlockFile.
49208  */
49209  return winceUnlockFile(phFile, offsetLow, offsetHigh,
49210                         numBytesLow, numBytesHigh);
49211#else
49212  if( osIsNT() ){
49213    OVERLAPPED ovlp;
49214    memset(&ovlp, 0, sizeof(OVERLAPPED));
49215    ovlp.Offset = offsetLow;
49216    ovlp.OffsetHigh = offsetHigh;
49217    return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
49218  }else{
49219    return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
49220                        numBytesHigh);
49221  }
49222#endif
49223}
49224
49225/*****************************************************************************
49226** The next group of routines implement the I/O methods specified
49227** by the sqlite3_io_methods object.
49228******************************************************************************/
49229
49230/*
49231** Some Microsoft compilers lack this definition.
49232*/
49233#ifndef INVALID_SET_FILE_POINTER
49234# define INVALID_SET_FILE_POINTER ((DWORD)-1)
49235#endif
49236
49237/*
49238** Move the current position of the file handle passed as the first
49239** argument to offset iOffset within the file. If successful, return 0.
49240** Otherwise, set pFile->lastErrno and return non-zero.
49241*/
49242static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
49243#if !SQLITE_OS_WINRT
49244  LONG upperBits;                 /* Most sig. 32 bits of new offset */
49245  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
49246  DWORD dwRet;                    /* Value returned by SetFilePointer() */
49247  DWORD lastErrno;                /* Value returned by GetLastError() */
49248
49249  OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
49250
49251  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
49252  lowerBits = (LONG)(iOffset & 0xffffffff);
49253
49254  /* API oddity: If successful, SetFilePointer() returns a dword
49255  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
49256  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
49257  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
49258  ** whether an error has actually occurred, it is also necessary to call
49259  ** GetLastError().
49260  */
49261  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
49262
49263  if( (dwRet==INVALID_SET_FILE_POINTER
49264      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
49265    pFile->lastErrno = lastErrno;
49266    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
49267                "winSeekFile", pFile->zPath);
49268    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
49269    return 1;
49270  }
49271
49272  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
49273  return 0;
49274#else
49275  /*
49276  ** Same as above, except that this implementation works for WinRT.
49277  */
49278
49279  LARGE_INTEGER x;                /* The new offset */
49280  BOOL bRet;                      /* Value returned by SetFilePointerEx() */
49281
49282  x.QuadPart = iOffset;
49283  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
49284
49285  if(!bRet){
49286    pFile->lastErrno = osGetLastError();
49287    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
49288                "winSeekFile", pFile->zPath);
49289    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
49290    return 1;
49291  }
49292
49293  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
49294  return 0;
49295#endif
49296}
49297
49298#if SQLITE_MAX_MMAP_SIZE>0
49299/* Forward references to VFS helper methods used for memory mapped files */
49300static int winMapfile(winFile*, sqlite3_int64);
49301static int winUnmapfile(winFile*);
49302#endif
49303
49304/*
49305** Close a file.
49306**
49307** It is reported that an attempt to close a handle might sometimes
49308** fail.  This is a very unreasonable result, but Windows is notorious
49309** for being unreasonable so I do not doubt that it might happen.  If
49310** the close fails, we pause for 100 milliseconds and try again.  As
49311** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
49312** giving up and returning an error.
49313*/
49314#define MX_CLOSE_ATTEMPT 3
49315static int winClose(sqlite3_file *id){
49316  int rc, cnt = 0;
49317  winFile *pFile = (winFile*)id;
49318
49319  assert( id!=0 );
49320#ifndef SQLITE_OMIT_WAL
49321  assert( pFile->pShm==0 );
49322#endif
49323  assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
49324  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
49325           osGetCurrentProcessId(), pFile, pFile->h));
49326
49327#if SQLITE_MAX_MMAP_SIZE>0
49328  winUnmapfile(pFile);
49329#endif
49330
49331  do{
49332    rc = osCloseHandle(pFile->h);
49333    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
49334  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
49335#if SQLITE_OS_WINCE
49336#define WINCE_DELETION_ATTEMPTS 3
49337  {
49338    winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
49339    if( pAppData==NULL || !pAppData->bNoLock ){
49340      winceDestroyLock(pFile);
49341    }
49342  }
49343  if( pFile->zDeleteOnClose ){
49344    int cnt = 0;
49345    while(
49346           osDeleteFileW(pFile->zDeleteOnClose)==0
49347        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
49348        && cnt++ < WINCE_DELETION_ATTEMPTS
49349    ){
49350       sqlite3_win32_sleep(100);  /* Wait a little before trying again */
49351    }
49352    sqlite3_free(pFile->zDeleteOnClose);
49353  }
49354#endif
49355  if( rc ){
49356    pFile->h = NULL;
49357  }
49358  OpenCounter(-1);
49359  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
49360           osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
49361  return rc ? SQLITE_OK
49362            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
49363                          "winClose", pFile->zPath);
49364}
49365
49366/*
49367** Read data from a file into a buffer.  Return SQLITE_OK if all
49368** bytes were read successfully and SQLITE_IOERR if anything goes
49369** wrong.
49370*/
49371static int winRead(
49372  sqlite3_file *id,          /* File to read from */
49373  void *pBuf,                /* Write content into this buffer */
49374  int amt,                   /* Number of bytes to read */
49375  sqlite3_int64 offset       /* Begin reading at this offset */
49376){
49377#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
49378  OVERLAPPED overlapped;          /* The offset for ReadFile. */
49379#endif
49380  winFile *pFile = (winFile*)id;  /* file handle */
49381  DWORD nRead;                    /* Number of bytes actually read from file */
49382  int nRetry = 0;                 /* Number of retrys */
49383
49384  assert( id!=0 );
49385  assert( amt>0 );
49386  assert( offset>=0 );
49387  SimulateIOError(return SQLITE_IOERR_READ);
49388  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
49389           "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
49390           pFile->h, pBuf, amt, offset, pFile->locktype));
49391
49392#if SQLITE_MAX_MMAP_SIZE>0
49393  /* Deal with as much of this read request as possible by transferring
49394  ** data from the memory mapping using memcpy().  */
49395  if( offset<pFile->mmapSize ){
49396    if( offset+amt <= pFile->mmapSize ){
49397      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
49398      OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
49399               osGetCurrentProcessId(), pFile, pFile->h));
49400      return SQLITE_OK;
49401    }else{
49402      int nCopy = (int)(pFile->mmapSize - offset);
49403      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
49404      pBuf = &((u8 *)pBuf)[nCopy];
49405      amt -= nCopy;
49406      offset += nCopy;
49407    }
49408  }
49409#endif
49410
49411#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
49412  if( winSeekFile(pFile, offset) ){
49413    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
49414             osGetCurrentProcessId(), pFile, pFile->h));
49415    return SQLITE_FULL;
49416  }
49417  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
49418#else
49419  memset(&overlapped, 0, sizeof(OVERLAPPED));
49420  overlapped.Offset = (LONG)(offset & 0xffffffff);
49421  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
49422  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
49423         osGetLastError()!=ERROR_HANDLE_EOF ){
49424#endif
49425    DWORD lastErrno;
49426    if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
49427    pFile->lastErrno = lastErrno;
49428    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
49429             osGetCurrentProcessId(), pFile, pFile->h));
49430    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
49431                       "winRead", pFile->zPath);
49432  }
49433  winLogIoerr(nRetry, __LINE__);
49434  if( nRead<(DWORD)amt ){
49435    /* Unread parts of the buffer must be zero-filled */
49436    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
49437    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
49438             osGetCurrentProcessId(), pFile, pFile->h));
49439    return SQLITE_IOERR_SHORT_READ;
49440  }
49441
49442  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
49443           osGetCurrentProcessId(), pFile, pFile->h));
49444  return SQLITE_OK;
49445}
49446
49447/*
49448** Write data from a buffer into a file.  Return SQLITE_OK on success
49449** or some other error code on failure.
49450*/
49451static int winWrite(
49452  sqlite3_file *id,               /* File to write into */
49453  const void *pBuf,               /* The bytes to be written */
49454  int amt,                        /* Number of bytes to write */
49455  sqlite3_int64 offset            /* Offset into the file to begin writing at */
49456){
49457  int rc = 0;                     /* True if error has occurred, else false */
49458  winFile *pFile = (winFile*)id;  /* File handle */
49459  int nRetry = 0;                 /* Number of retries */
49460
49461  assert( amt>0 );
49462  assert( pFile );
49463  SimulateIOError(return SQLITE_IOERR_WRITE);
49464  SimulateDiskfullError(return SQLITE_FULL);
49465
49466  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
49467           "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
49468           pFile->h, pBuf, amt, offset, pFile->locktype));
49469
49470#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
49471  /* Deal with as much of this write request as possible by transferring
49472  ** data from the memory mapping using memcpy().  */
49473  if( offset<pFile->mmapSize ){
49474    if( offset+amt <= pFile->mmapSize ){
49475      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
49476      OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
49477               osGetCurrentProcessId(), pFile, pFile->h));
49478      return SQLITE_OK;
49479    }else{
49480      int nCopy = (int)(pFile->mmapSize - offset);
49481      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
49482      pBuf = &((u8 *)pBuf)[nCopy];
49483      amt -= nCopy;
49484      offset += nCopy;
49485    }
49486  }
49487#endif
49488
49489#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
49490  rc = winSeekFile(pFile, offset);
49491  if( rc==0 ){
49492#else
49493  {
49494#endif
49495#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
49496    OVERLAPPED overlapped;        /* The offset for WriteFile. */
49497#endif
49498    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
49499    int nRem = amt;               /* Number of bytes yet to be written */
49500    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
49501    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
49502
49503#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
49504    memset(&overlapped, 0, sizeof(OVERLAPPED));
49505    overlapped.Offset = (LONG)(offset & 0xffffffff);
49506    overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
49507#endif
49508
49509    while( nRem>0 ){
49510#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
49511      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
49512#else
49513      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
49514#endif
49515        if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
49516        break;
49517      }
49518      assert( nWrite==0 || nWrite<=(DWORD)nRem );
49519      if( nWrite==0 || nWrite>(DWORD)nRem ){
49520        lastErrno = osGetLastError();
49521        break;
49522      }
49523#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
49524      offset += nWrite;
49525      overlapped.Offset = (LONG)(offset & 0xffffffff);
49526      overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
49527#endif
49528      aRem += nWrite;
49529      nRem -= nWrite;
49530    }
49531    if( nRem>0 ){
49532      pFile->lastErrno = lastErrno;
49533      rc = 1;
49534    }
49535  }
49536
49537  if( rc ){
49538    if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
49539       || ( pFile->lastErrno==ERROR_DISK_FULL )){
49540      OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
49541               osGetCurrentProcessId(), pFile, pFile->h));
49542      return winLogError(SQLITE_FULL, pFile->lastErrno,
49543                         "winWrite1", pFile->zPath);
49544    }
49545    OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
49546             osGetCurrentProcessId(), pFile, pFile->h));
49547    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
49548                       "winWrite2", pFile->zPath);
49549  }else{
49550    winLogIoerr(nRetry, __LINE__);
49551  }
49552  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
49553           osGetCurrentProcessId(), pFile, pFile->h));
49554  return SQLITE_OK;
49555}
49556
49557/*
49558** Truncate an open file to a specified size
49559*/
49560static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
49561  winFile *pFile = (winFile*)id;  /* File handle object */
49562  int rc = SQLITE_OK;             /* Return code for this function */
49563  DWORD lastErrno;
49564#if SQLITE_MAX_MMAP_SIZE>0
49565  sqlite3_int64 oldMmapSize;
49566  if( pFile->nFetchOut>0 ){
49567    /* File truncation is a no-op if there are outstanding memory mapped
49568    ** pages.  This is because truncating the file means temporarily unmapping
49569    ** the file, and that might delete memory out from under existing cursors.
49570    **
49571    ** This can result in incremental vacuum not truncating the file,
49572    ** if there is an active read cursor when the incremental vacuum occurs.
49573    ** No real harm comes of this - the database file is not corrupted,
49574    ** though some folks might complain that the file is bigger than it
49575    ** needs to be.
49576    **
49577    ** The only feasible work-around is to defer the truncation until after
49578    ** all references to memory-mapped content are closed.  That is doable,
49579    ** but involves adding a few branches in the common write code path which
49580    ** could slow down normal operations slightly.  Hence, we have decided for
49581    ** now to simply make transactions a no-op if there are pending reads.  We
49582    ** can maybe revisit this decision in the future.
49583    */
49584    return SQLITE_OK;
49585  }
49586#endif
49587
49588  assert( pFile );
49589  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
49590  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
49591           osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
49592
49593  /* If the user has configured a chunk-size for this file, truncate the
49594  ** file so that it consists of an integer number of chunks (i.e. the
49595  ** actual file size after the operation may be larger than the requested
49596  ** size).
49597  */
49598  if( pFile->szChunk>0 ){
49599    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
49600  }
49601
49602#if SQLITE_MAX_MMAP_SIZE>0
49603  if( pFile->pMapRegion ){
49604    oldMmapSize = pFile->mmapSize;
49605  }else{
49606    oldMmapSize = 0;
49607  }
49608  winUnmapfile(pFile);
49609#endif
49610
49611  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
49612  if( winSeekFile(pFile, nByte) ){
49613    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
49614                     "winTruncate1", pFile->zPath);
49615  }else if( 0==osSetEndOfFile(pFile->h) &&
49616            ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
49617    pFile->lastErrno = lastErrno;
49618    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
49619                     "winTruncate2", pFile->zPath);
49620  }
49621
49622#if SQLITE_MAX_MMAP_SIZE>0
49623  if( rc==SQLITE_OK && oldMmapSize>0 ){
49624    if( oldMmapSize>nByte ){
49625      winMapfile(pFile, -1);
49626    }else{
49627      winMapfile(pFile, oldMmapSize);
49628    }
49629  }
49630#endif
49631
49632  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
49633           osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
49634  return rc;
49635}
49636
49637#ifdef SQLITE_TEST
49638/*
49639** Count the number of fullsyncs and normal syncs.  This is used to test
49640** that syncs and fullsyncs are occurring at the right times.
49641*/
49642SQLITE_API int sqlite3_sync_count = 0;
49643SQLITE_API int sqlite3_fullsync_count = 0;
49644#endif
49645
49646/*
49647** Make sure all writes to a particular file are committed to disk.
49648*/
49649static int winSync(sqlite3_file *id, int flags){
49650#ifndef SQLITE_NO_SYNC
49651  /*
49652  ** Used only when SQLITE_NO_SYNC is not defined.
49653   */
49654  BOOL rc;
49655#endif
49656#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
49657    defined(SQLITE_HAVE_OS_TRACE)
49658  /*
49659  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
49660  ** OSTRACE() macros.
49661   */
49662  winFile *pFile = (winFile*)id;
49663#else
49664  UNUSED_PARAMETER(id);
49665#endif
49666
49667  assert( pFile );
49668  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
49669  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
49670      || (flags&0x0F)==SQLITE_SYNC_FULL
49671  );
49672
49673  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
49674  ** line is to test that doing so does not cause any problems.
49675  */
49676  SimulateDiskfullError( return SQLITE_FULL );
49677
49678  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
49679           osGetCurrentProcessId(), pFile, pFile->h, flags,
49680           pFile->locktype));
49681
49682#ifndef SQLITE_TEST
49683  UNUSED_PARAMETER(flags);
49684#else
49685  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
49686    sqlite3_fullsync_count++;
49687  }
49688  sqlite3_sync_count++;
49689#endif
49690
49691  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
49692  ** no-op
49693  */
49694#ifdef SQLITE_NO_SYNC
49695  OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
49696           osGetCurrentProcessId(), pFile, pFile->h));
49697  return SQLITE_OK;
49698#else
49699#if SQLITE_MAX_MMAP_SIZE>0
49700  if( pFile->pMapRegion ){
49701    if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
49702      OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
49703               "rc=SQLITE_OK\n", osGetCurrentProcessId(),
49704               pFile, pFile->pMapRegion));
49705    }else{
49706      pFile->lastErrno = osGetLastError();
49707      OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
49708               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
49709               pFile, pFile->pMapRegion));
49710      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
49711                         "winSync1", pFile->zPath);
49712    }
49713  }
49714#endif
49715  rc = osFlushFileBuffers(pFile->h);
49716  SimulateIOError( rc=FALSE );
49717  if( rc ){
49718    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
49719             osGetCurrentProcessId(), pFile, pFile->h));
49720    return SQLITE_OK;
49721  }else{
49722    pFile->lastErrno = osGetLastError();
49723    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
49724             osGetCurrentProcessId(), pFile, pFile->h));
49725    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
49726                       "winSync2", pFile->zPath);
49727  }
49728#endif
49729}
49730
49731/*
49732** Determine the current size of a file in bytes
49733*/
49734static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
49735  winFile *pFile = (winFile*)id;
49736  int rc = SQLITE_OK;
49737
49738  assert( id!=0 );
49739  assert( pSize!=0 );
49740  SimulateIOError(return SQLITE_IOERR_FSTAT);
49741  OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
49742
49743#if SQLITE_OS_WINRT
49744  {
49745    FILE_STANDARD_INFO info;
49746    if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
49747                                     &info, sizeof(info)) ){
49748      *pSize = info.EndOfFile.QuadPart;
49749    }else{
49750      pFile->lastErrno = osGetLastError();
49751      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
49752                       "winFileSize", pFile->zPath);
49753    }
49754  }
49755#else
49756  {
49757    DWORD upperBits;
49758    DWORD lowerBits;
49759    DWORD lastErrno;
49760
49761    lowerBits = osGetFileSize(pFile->h, &upperBits);
49762    *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
49763    if(   (lowerBits == INVALID_FILE_SIZE)
49764       && ((lastErrno = osGetLastError())!=NO_ERROR) ){
49765      pFile->lastErrno = lastErrno;
49766      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
49767                       "winFileSize", pFile->zPath);
49768    }
49769  }
49770#endif
49771  OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
49772           pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
49773  return rc;
49774}
49775
49776/*
49777** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
49778*/
49779#ifndef LOCKFILE_FAIL_IMMEDIATELY
49780# define LOCKFILE_FAIL_IMMEDIATELY 1
49781#endif
49782
49783#ifndef LOCKFILE_EXCLUSIVE_LOCK
49784# define LOCKFILE_EXCLUSIVE_LOCK 2
49785#endif
49786
49787/*
49788** Historically, SQLite has used both the LockFile and LockFileEx functions.
49789** When the LockFile function was used, it was always expected to fail
49790** immediately if the lock could not be obtained.  Also, it always expected to
49791** obtain an exclusive lock.  These flags are used with the LockFileEx function
49792** and reflect those expectations; therefore, they should not be changed.
49793*/
49794#ifndef SQLITE_LOCKFILE_FLAGS
49795# define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
49796                                  LOCKFILE_EXCLUSIVE_LOCK)
49797#endif
49798
49799/*
49800** Currently, SQLite never calls the LockFileEx function without wanting the
49801** call to fail immediately if the lock cannot be obtained.
49802*/
49803#ifndef SQLITE_LOCKFILEEX_FLAGS
49804# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
49805#endif
49806
49807/*
49808** Acquire a reader lock.
49809** Different API routines are called depending on whether or not this
49810** is Win9x or WinNT.
49811*/
49812static int winGetReadLock(winFile *pFile){
49813  int res;
49814  OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
49815  if( osIsNT() ){
49816#if SQLITE_OS_WINCE
49817    /*
49818    ** NOTE: Windows CE is handled differently here due its lack of the Win32
49819    **       API LockFileEx.
49820    */
49821    res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
49822#else
49823    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
49824                      SHARED_SIZE, 0);
49825#endif
49826  }
49827#ifdef SQLITE_WIN32_HAS_ANSI
49828  else{
49829    int lk;
49830    sqlite3_randomness(sizeof(lk), &lk);
49831    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
49832    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
49833                      SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
49834  }
49835#endif
49836  if( res == 0 ){
49837    pFile->lastErrno = osGetLastError();
49838    /* No need to log a failure to lock */
49839  }
49840  OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
49841  return res;
49842}
49843
49844/*
49845** Undo a readlock
49846*/
49847static int winUnlockReadLock(winFile *pFile){
49848  int res;
49849  DWORD lastErrno;
49850  OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
49851  if( osIsNT() ){
49852    res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
49853  }
49854#ifdef SQLITE_WIN32_HAS_ANSI
49855  else{
49856    res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
49857  }
49858#endif
49859  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
49860    pFile->lastErrno = lastErrno;
49861    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
49862                "winUnlockReadLock", pFile->zPath);
49863  }
49864  OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
49865  return res;
49866}
49867
49868/*
49869** Lock the file with the lock specified by parameter locktype - one
49870** of the following:
49871**
49872**     (1) SHARED_LOCK
49873**     (2) RESERVED_LOCK
49874**     (3) PENDING_LOCK
49875**     (4) EXCLUSIVE_LOCK
49876**
49877** Sometimes when requesting one lock state, additional lock states
49878** are inserted in between.  The locking might fail on one of the later
49879** transitions leaving the lock state different from what it started but
49880** still short of its goal.  The following chart shows the allowed
49881** transitions and the inserted intermediate states:
49882**
49883**    UNLOCKED -> SHARED
49884**    SHARED -> RESERVED
49885**    SHARED -> (PENDING) -> EXCLUSIVE
49886**    RESERVED -> (PENDING) -> EXCLUSIVE
49887**    PENDING -> EXCLUSIVE
49888**
49889** This routine will only increase a lock.  The winUnlock() routine
49890** erases all locks at once and returns us immediately to locking level 0.
49891** It is not possible to lower the locking level one step at a time.  You
49892** must go straight to locking level 0.
49893*/
49894static int winLock(sqlite3_file *id, int locktype){
49895  int rc = SQLITE_OK;    /* Return code from subroutines */
49896  int res = 1;           /* Result of a Windows lock call */
49897  int newLocktype;       /* Set pFile->locktype to this value before exiting */
49898  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
49899  winFile *pFile = (winFile*)id;
49900  DWORD lastErrno = NO_ERROR;
49901
49902  assert( id!=0 );
49903  OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
49904           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
49905
49906  /* If there is already a lock of this type or more restrictive on the
49907  ** OsFile, do nothing. Don't use the end_lock: exit path, as
49908  ** sqlite3OsEnterMutex() hasn't been called yet.
49909  */
49910  if( pFile->locktype>=locktype ){
49911    OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
49912    return SQLITE_OK;
49913  }
49914
49915  /* Do not allow any kind of write-lock on a read-only database
49916  */
49917  if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
49918    return SQLITE_IOERR_LOCK;
49919  }
49920
49921  /* Make sure the locking sequence is correct
49922  */
49923  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
49924  assert( locktype!=PENDING_LOCK );
49925  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
49926
49927  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
49928  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
49929  ** the PENDING_LOCK byte is temporary.
49930  */
49931  newLocktype = pFile->locktype;
49932  if( pFile->locktype==NO_LOCK
49933   || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
49934  ){
49935    int cnt = 3;
49936    while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
49937                                         PENDING_BYTE, 0, 1, 0))==0 ){
49938      /* Try 3 times to get the pending lock.  This is needed to work
49939      ** around problems caused by indexing and/or anti-virus software on
49940      ** Windows systems.
49941      ** If you are using this code as a model for alternative VFSes, do not
49942      ** copy this retry logic.  It is a hack intended for Windows only.
49943      */
49944      lastErrno = osGetLastError();
49945      OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
49946               pFile->h, cnt, res));
49947      if( lastErrno==ERROR_INVALID_HANDLE ){
49948        pFile->lastErrno = lastErrno;
49949        rc = SQLITE_IOERR_LOCK;
49950        OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
49951                 pFile->h, cnt, sqlite3ErrName(rc)));
49952        return rc;
49953      }
49954      if( cnt ) sqlite3_win32_sleep(1);
49955    }
49956    gotPendingLock = res;
49957    if( !res ){
49958      lastErrno = osGetLastError();
49959    }
49960  }
49961
49962  /* Acquire a shared lock
49963  */
49964  if( locktype==SHARED_LOCK && res ){
49965    assert( pFile->locktype==NO_LOCK );
49966    res = winGetReadLock(pFile);
49967    if( res ){
49968      newLocktype = SHARED_LOCK;
49969    }else{
49970      lastErrno = osGetLastError();
49971    }
49972  }
49973
49974  /* Acquire a RESERVED lock
49975  */
49976  if( locktype==RESERVED_LOCK && res ){
49977    assert( pFile->locktype==SHARED_LOCK );
49978    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
49979    if( res ){
49980      newLocktype = RESERVED_LOCK;
49981    }else{
49982      lastErrno = osGetLastError();
49983    }
49984  }
49985
49986  /* Acquire a PENDING lock
49987  */
49988  if( locktype==EXCLUSIVE_LOCK && res ){
49989    newLocktype = PENDING_LOCK;
49990    gotPendingLock = 0;
49991  }
49992
49993  /* Acquire an EXCLUSIVE lock
49994  */
49995  if( locktype==EXCLUSIVE_LOCK && res ){
49996    assert( pFile->locktype>=SHARED_LOCK );
49997    (void)winUnlockReadLock(pFile);
49998    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
49999                      SHARED_SIZE, 0);
50000    if( res ){
50001      newLocktype = EXCLUSIVE_LOCK;
50002    }else{
50003      lastErrno = osGetLastError();
50004      winGetReadLock(pFile);
50005    }
50006  }
50007
50008  /* If we are holding a PENDING lock that ought to be released, then
50009  ** release it now.
50010  */
50011  if( gotPendingLock && locktype==SHARED_LOCK ){
50012    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
50013  }
50014
50015  /* Update the state of the lock has held in the file descriptor then
50016  ** return the appropriate result code.
50017  */
50018  if( res ){
50019    rc = SQLITE_OK;
50020  }else{
50021    pFile->lastErrno = lastErrno;
50022    rc = SQLITE_BUSY;
50023    OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
50024             pFile->h, locktype, newLocktype));
50025  }
50026  pFile->locktype = (u8)newLocktype;
50027  OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
50028           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
50029  return rc;
50030}
50031
50032/*
50033** This routine checks if there is a RESERVED lock held on the specified
50034** file by this or any other process. If such a lock is held, return
50035** non-zero, otherwise zero.
50036*/
50037static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
50038  int res;
50039  winFile *pFile = (winFile*)id;
50040
50041  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
50042  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
50043
50044  assert( id!=0 );
50045  if( pFile->locktype>=RESERVED_LOCK ){
50046    res = 1;
50047    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
50048  }else{
50049    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
50050    if( res ){
50051      winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
50052    }
50053    res = !res;
50054    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
50055  }
50056  *pResOut = res;
50057  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
50058           pFile->h, pResOut, *pResOut));
50059  return SQLITE_OK;
50060}
50061
50062/*
50063** Lower the locking level on file descriptor id to locktype.  locktype
50064** must be either NO_LOCK or SHARED_LOCK.
50065**
50066** If the locking level of the file descriptor is already at or below
50067** the requested locking level, this routine is a no-op.
50068**
50069** It is not possible for this routine to fail if the second argument
50070** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
50071** might return SQLITE_IOERR;
50072*/
50073static int winUnlock(sqlite3_file *id, int locktype){
50074  int type;
50075  winFile *pFile = (winFile*)id;
50076  int rc = SQLITE_OK;
50077  assert( pFile!=0 );
50078  assert( locktype<=SHARED_LOCK );
50079  OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
50080           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
50081  type = pFile->locktype;
50082  if( type>=EXCLUSIVE_LOCK ){
50083    winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
50084    if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
50085      /* This should never happen.  We should always be able to
50086      ** reacquire the read lock */
50087      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
50088                       "winUnlock", pFile->zPath);
50089    }
50090  }
50091  if( type>=RESERVED_LOCK ){
50092    winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
50093  }
50094  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
50095    winUnlockReadLock(pFile);
50096  }
50097  if( type>=PENDING_LOCK ){
50098    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
50099  }
50100  pFile->locktype = (u8)locktype;
50101  OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
50102           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
50103  return rc;
50104}
50105
50106/******************************************************************************
50107****************************** No-op Locking **********************************
50108**
50109** Of the various locking implementations available, this is by far the
50110** simplest:  locking is ignored.  No attempt is made to lock the database
50111** file for reading or writing.
50112**
50113** This locking mode is appropriate for use on read-only databases
50114** (ex: databases that are burned into CD-ROM, for example.)  It can
50115** also be used if the application employs some external mechanism to
50116** prevent simultaneous access of the same database by two or more
50117** database connections.  But there is a serious risk of database
50118** corruption if this locking mode is used in situations where multiple
50119** database connections are accessing the same database file at the same
50120** time and one or more of those connections are writing.
50121*/
50122
50123static int winNolockLock(sqlite3_file *id, int locktype){
50124  UNUSED_PARAMETER(id);
50125  UNUSED_PARAMETER(locktype);
50126  return SQLITE_OK;
50127}
50128
50129static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
50130  UNUSED_PARAMETER(id);
50131  UNUSED_PARAMETER(pResOut);
50132  return SQLITE_OK;
50133}
50134
50135static int winNolockUnlock(sqlite3_file *id, int locktype){
50136  UNUSED_PARAMETER(id);
50137  UNUSED_PARAMETER(locktype);
50138  return SQLITE_OK;
50139}
50140
50141/******************* End of the no-op lock implementation *********************
50142******************************************************************************/
50143
50144/*
50145** If *pArg is initially negative then this is a query.  Set *pArg to
50146** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
50147**
50148** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
50149*/
50150static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
50151  if( *pArg<0 ){
50152    *pArg = (pFile->ctrlFlags & mask)!=0;
50153  }else if( (*pArg)==0 ){
50154    pFile->ctrlFlags &= ~mask;
50155  }else{
50156    pFile->ctrlFlags |= mask;
50157  }
50158}
50159
50160/* Forward references to VFS helper methods used for temporary files */
50161static int winGetTempname(sqlite3_vfs *, char **);
50162static int winIsDir(const void *);
50163static BOOL winIsLongPathPrefix(const char *);
50164static BOOL winIsDriveLetterAndColon(const char *);
50165
50166/*
50167** Control and query of the open file handle.
50168*/
50169static int winFileControl(sqlite3_file *id, int op, void *pArg){
50170  winFile *pFile = (winFile*)id;
50171  OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
50172  switch( op ){
50173    case SQLITE_FCNTL_LOCKSTATE: {
50174      *(int*)pArg = pFile->locktype;
50175      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50176      return SQLITE_OK;
50177    }
50178    case SQLITE_FCNTL_LAST_ERRNO: {
50179      *(int*)pArg = (int)pFile->lastErrno;
50180      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50181      return SQLITE_OK;
50182    }
50183    case SQLITE_FCNTL_CHUNK_SIZE: {
50184      pFile->szChunk = *(int *)pArg;
50185      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50186      return SQLITE_OK;
50187    }
50188    case SQLITE_FCNTL_SIZE_HINT: {
50189      if( pFile->szChunk>0 ){
50190        sqlite3_int64 oldSz;
50191        int rc = winFileSize(id, &oldSz);
50192        if( rc==SQLITE_OK ){
50193          sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
50194          if( newSz>oldSz ){
50195            SimulateIOErrorBenign(1);
50196            rc = winTruncate(id, newSz);
50197            SimulateIOErrorBenign(0);
50198          }
50199        }
50200        OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
50201        return rc;
50202      }
50203      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50204      return SQLITE_OK;
50205    }
50206    case SQLITE_FCNTL_PERSIST_WAL: {
50207      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
50208      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50209      return SQLITE_OK;
50210    }
50211    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
50212      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
50213      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50214      return SQLITE_OK;
50215    }
50216    case SQLITE_FCNTL_VFSNAME: {
50217      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
50218      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50219      return SQLITE_OK;
50220    }
50221    case SQLITE_FCNTL_WIN32_AV_RETRY: {
50222      int *a = (int*)pArg;
50223      if( a[0]>0 ){
50224        winIoerrRetry = a[0];
50225      }else{
50226        a[0] = winIoerrRetry;
50227      }
50228      if( a[1]>0 ){
50229        winIoerrRetryDelay = a[1];
50230      }else{
50231        a[1] = winIoerrRetryDelay;
50232      }
50233      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50234      return SQLITE_OK;
50235    }
50236    case SQLITE_FCNTL_WIN32_GET_HANDLE: {
50237      LPHANDLE phFile = (LPHANDLE)pArg;
50238      *phFile = pFile->h;
50239      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50240      return SQLITE_OK;
50241    }
50242#ifdef SQLITE_TEST
50243    case SQLITE_FCNTL_WIN32_SET_HANDLE: {
50244      LPHANDLE phFile = (LPHANDLE)pArg;
50245      HANDLE hOldFile = pFile->h;
50246      pFile->h = *phFile;
50247      *phFile = hOldFile;
50248      OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
50249               hOldFile, pFile->h));
50250      return SQLITE_OK;
50251    }
50252#endif
50253    case SQLITE_FCNTL_TEMPFILENAME: {
50254      char *zTFile = 0;
50255      int rc = winGetTempname(pFile->pVfs, &zTFile);
50256      if( rc==SQLITE_OK ){
50257        *(char**)pArg = zTFile;
50258      }
50259      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
50260      return rc;
50261    }
50262#if SQLITE_MAX_MMAP_SIZE>0
50263    case SQLITE_FCNTL_MMAP_SIZE: {
50264      i64 newLimit = *(i64*)pArg;
50265      int rc = SQLITE_OK;
50266      if( newLimit>sqlite3GlobalConfig.mxMmap ){
50267        newLimit = sqlite3GlobalConfig.mxMmap;
50268      }
50269
50270      /* The value of newLimit may be eventually cast to (SIZE_T) and passed
50271      ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
50272      ** least a 64-bit type. */
50273      if( newLimit>0 && sizeof(SIZE_T)<8 ){
50274        newLimit = (newLimit & 0x7FFFFFFF);
50275      }
50276
50277      *(i64*)pArg = pFile->mmapSizeMax;
50278      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
50279        pFile->mmapSizeMax = newLimit;
50280        if( pFile->mmapSize>0 ){
50281          winUnmapfile(pFile);
50282          rc = winMapfile(pFile, -1);
50283        }
50284      }
50285      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
50286      return rc;
50287    }
50288#endif
50289  }
50290  OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
50291  return SQLITE_NOTFOUND;
50292}
50293
50294/*
50295** Return the sector size in bytes of the underlying block device for
50296** the specified file. This is almost always 512 bytes, but may be
50297** larger for some devices.
50298**
50299** SQLite code assumes this function cannot fail. It also assumes that
50300** if two files are created in the same file-system directory (i.e.
50301** a database and its journal file) that the sector size will be the
50302** same for both.
50303*/
50304static int winSectorSize(sqlite3_file *id){
50305  (void)id;
50306  return SQLITE_DEFAULT_SECTOR_SIZE;
50307}
50308
50309/*
50310** Return a vector of device characteristics.
50311*/
50312static int winDeviceCharacteristics(sqlite3_file *id){
50313  winFile *p = (winFile*)id;
50314  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
50315         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
50316}
50317
50318/*
50319** Windows will only let you create file view mappings
50320** on allocation size granularity boundaries.
50321** During sqlite3_os_init() we do a GetSystemInfo()
50322** to get the granularity size.
50323*/
50324static SYSTEM_INFO winSysInfo;
50325
50326#ifndef SQLITE_OMIT_WAL
50327
50328/*
50329** Helper functions to obtain and relinquish the global mutex. The
50330** global mutex is used to protect the winLockInfo objects used by
50331** this file, all of which may be shared by multiple threads.
50332**
50333** Function winShmMutexHeld() is used to assert() that the global mutex
50334** is held when required. This function is only used as part of assert()
50335** statements. e.g.
50336**
50337**   winShmEnterMutex()
50338**     assert( winShmMutexHeld() );
50339**   winShmLeaveMutex()
50340*/
50341static sqlite3_mutex *winBigLock = 0;
50342static void winShmEnterMutex(void){
50343  sqlite3_mutex_enter(winBigLock);
50344}
50345static void winShmLeaveMutex(void){
50346  sqlite3_mutex_leave(winBigLock);
50347}
50348#ifndef NDEBUG
50349static int winShmMutexHeld(void) {
50350  return sqlite3_mutex_held(winBigLock);
50351}
50352#endif
50353
50354/*
50355** Object used to represent a single file opened and mmapped to provide
50356** shared memory.  When multiple threads all reference the same
50357** log-summary, each thread has its own winFile object, but they all
50358** point to a single instance of this object.  In other words, each
50359** log-summary is opened only once per process.
50360**
50361** winShmMutexHeld() must be true when creating or destroying
50362** this object or while reading or writing the following fields:
50363**
50364**      nRef
50365**      pNext
50366**
50367** The following fields are read-only after the object is created:
50368**
50369**      fid
50370**      zFilename
50371**
50372** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
50373** winShmMutexHeld() is true when reading or writing any other field
50374** in this structure.
50375**
50376*/
50377struct winShmNode {
50378  sqlite3_mutex *mutex;      /* Mutex to access this object */
50379  char *zFilename;           /* Name of the file */
50380  winFile hFile;             /* File handle from winOpen */
50381
50382  int szRegion;              /* Size of shared-memory regions */
50383  int nRegion;               /* Size of array apRegion */
50384  u8 isReadonly;             /* True if read-only */
50385  u8 isUnlocked;             /* True if no DMS lock held */
50386
50387  struct ShmRegion {
50388    HANDLE hMap;             /* File handle from CreateFileMapping */
50389    void *pMap;
50390  } *aRegion;
50391  DWORD lastErrno;           /* The Windows errno from the last I/O error */
50392
50393  int nRef;                  /* Number of winShm objects pointing to this */
50394  winShm *pFirst;            /* All winShm objects pointing to this */
50395  winShmNode *pNext;         /* Next in list of all winShmNode objects */
50396#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
50397  u8 nextShmId;              /* Next available winShm.id value */
50398#endif
50399};
50400
50401/*
50402** A global array of all winShmNode objects.
50403**
50404** The winShmMutexHeld() must be true while reading or writing this list.
50405*/
50406static winShmNode *winShmNodeList = 0;
50407
50408/*
50409** Structure used internally by this VFS to record the state of an
50410** open shared memory connection.
50411**
50412** The following fields are initialized when this object is created and
50413** are read-only thereafter:
50414**
50415**    winShm.pShmNode
50416**    winShm.id
50417**
50418** All other fields are read/write.  The winShm.pShmNode->mutex must be held
50419** while accessing any read/write fields.
50420*/
50421struct winShm {
50422  winShmNode *pShmNode;      /* The underlying winShmNode object */
50423  winShm *pNext;             /* Next winShm with the same winShmNode */
50424  u8 hasMutex;               /* True if holding the winShmNode mutex */
50425  u16 sharedMask;            /* Mask of shared locks held */
50426  u16 exclMask;              /* Mask of exclusive locks held */
50427#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
50428  u8 id;                     /* Id of this connection with its winShmNode */
50429#endif
50430};
50431
50432/*
50433** Constants used for locking
50434*/
50435#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
50436#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
50437
50438/*
50439** Apply advisory locks for all n bytes beginning at ofst.
50440*/
50441#define WINSHM_UNLCK  1
50442#define WINSHM_RDLCK  2
50443#define WINSHM_WRLCK  3
50444static int winShmSystemLock(
50445  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
50446  int lockType,         /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
50447  int ofst,             /* Offset to first byte to be locked/unlocked */
50448  int nByte             /* Number of bytes to lock or unlock */
50449){
50450  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
50451
50452  /* Access to the winShmNode object is serialized by the caller */
50453  assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
50454
50455  OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
50456           pFile->hFile.h, lockType, ofst, nByte));
50457
50458  /* Release/Acquire the system-level lock */
50459  if( lockType==WINSHM_UNLCK ){
50460    rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
50461  }else{
50462    /* Initialize the locking parameters */
50463    DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
50464    if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
50465    rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
50466  }
50467
50468  if( rc!= 0 ){
50469    rc = SQLITE_OK;
50470  }else{
50471    pFile->lastErrno =  osGetLastError();
50472    rc = SQLITE_BUSY;
50473  }
50474
50475  OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
50476           pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
50477           "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
50478
50479  return rc;
50480}
50481
50482/* Forward references to VFS methods */
50483static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
50484static int winDelete(sqlite3_vfs *,const char*,int);
50485
50486/*
50487** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
50488**
50489** This is not a VFS shared-memory method; it is a utility function called
50490** by VFS shared-memory methods.
50491*/
50492static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
50493  winShmNode **pp;
50494  winShmNode *p;
50495  assert( winShmMutexHeld() );
50496  OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
50497           osGetCurrentProcessId(), deleteFlag));
50498  pp = &winShmNodeList;
50499  while( (p = *pp)!=0 ){
50500    if( p->nRef==0 ){
50501      int i;
50502      if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
50503      for(i=0; i<p->nRegion; i++){
50504        BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
50505        OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
50506                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
50507        UNUSED_VARIABLE_VALUE(bRc);
50508        bRc = osCloseHandle(p->aRegion[i].hMap);
50509        OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
50510                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
50511        UNUSED_VARIABLE_VALUE(bRc);
50512      }
50513      if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
50514        SimulateIOErrorBenign(1);
50515        winClose((sqlite3_file *)&p->hFile);
50516        SimulateIOErrorBenign(0);
50517      }
50518      if( deleteFlag ){
50519        SimulateIOErrorBenign(1);
50520        sqlite3BeginBenignMalloc();
50521        winDelete(pVfs, p->zFilename, 0);
50522        sqlite3EndBenignMalloc();
50523        SimulateIOErrorBenign(0);
50524      }
50525      *pp = p->pNext;
50526      sqlite3_free(p->aRegion);
50527      sqlite3_free(p);
50528    }else{
50529      pp = &p->pNext;
50530    }
50531  }
50532}
50533
50534/*
50535** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
50536** take it now. Return SQLITE_OK if successful, or an SQLite error
50537** code otherwise.
50538**
50539** If the DMS cannot be locked because this is a readonly_shm=1
50540** connection and no other process already holds a lock, return
50541** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
50542*/
50543static int winLockSharedMemory(winShmNode *pShmNode){
50544  int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
50545
50546  if( rc==SQLITE_OK ){
50547    if( pShmNode->isReadonly ){
50548      pShmNode->isUnlocked = 1;
50549      winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
50550      return SQLITE_READONLY_CANTINIT;
50551    }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
50552      winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
50553      return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
50554                         "winLockSharedMemory", pShmNode->zFilename);
50555    }
50556  }
50557
50558  if( rc==SQLITE_OK ){
50559    winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
50560  }
50561
50562  return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
50563}
50564
50565/*
50566** Open the shared-memory area associated with database file pDbFd.
50567**
50568** When opening a new shared-memory file, if no other instances of that
50569** file are currently open, in this process or in other processes, then
50570** the file must be truncated to zero length or have its header cleared.
50571*/
50572static int winOpenSharedMemory(winFile *pDbFd){
50573  struct winShm *p;                  /* The connection to be opened */
50574  winShmNode *pShmNode = 0;          /* The underlying mmapped file */
50575  int rc = SQLITE_OK;                /* Result code */
50576  winShmNode *pNew;                  /* Newly allocated winShmNode */
50577  int nName;                         /* Size of zName in bytes */
50578
50579  assert( pDbFd->pShm==0 );    /* Not previously opened */
50580
50581  /* Allocate space for the new sqlite3_shm object.  Also speculatively
50582  ** allocate space for a new winShmNode and filename.
50583  */
50584  p = sqlite3MallocZero( sizeof(*p) );
50585  if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
50586  nName = sqlite3Strlen30(pDbFd->zPath);
50587  pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
50588  if( pNew==0 ){
50589    sqlite3_free(p);
50590    return SQLITE_IOERR_NOMEM_BKPT;
50591  }
50592  pNew->zFilename = (char*)&pNew[1];
50593  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
50594  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
50595
50596  /* Look to see if there is an existing winShmNode that can be used.
50597  ** If no matching winShmNode currently exists, create a new one.
50598  */
50599  winShmEnterMutex();
50600  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
50601    /* TBD need to come up with better match here.  Perhaps
50602    ** use FILE_ID_BOTH_DIR_INFO Structure.
50603    */
50604    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
50605  }
50606  if( pShmNode ){
50607    sqlite3_free(pNew);
50608  }else{
50609    int inFlags = SQLITE_OPEN_WAL;
50610    int outFlags = 0;
50611
50612    pShmNode = pNew;
50613    pNew = 0;
50614    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
50615    pShmNode->pNext = winShmNodeList;
50616    winShmNodeList = pShmNode;
50617
50618    if( sqlite3GlobalConfig.bCoreMutex ){
50619      pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
50620      if( pShmNode->mutex==0 ){
50621        rc = SQLITE_IOERR_NOMEM_BKPT;
50622        goto shm_open_err;
50623      }
50624    }
50625
50626    if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
50627      inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
50628    }else{
50629      inFlags |= SQLITE_OPEN_READONLY;
50630    }
50631    rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
50632                 (sqlite3_file*)&pShmNode->hFile,
50633                 inFlags, &outFlags);
50634    if( rc!=SQLITE_OK ){
50635      rc = winLogError(rc, osGetLastError(), "winOpenShm",
50636                       pShmNode->zFilename);
50637      goto shm_open_err;
50638    }
50639    if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
50640
50641    rc = winLockSharedMemory(pShmNode);
50642    if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
50643  }
50644
50645  /* Make the new connection a child of the winShmNode */
50646  p->pShmNode = pShmNode;
50647#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
50648  p->id = pShmNode->nextShmId++;
50649#endif
50650  pShmNode->nRef++;
50651  pDbFd->pShm = p;
50652  winShmLeaveMutex();
50653
50654  /* The reference count on pShmNode has already been incremented under
50655  ** the cover of the winShmEnterMutex() mutex and the pointer from the
50656  ** new (struct winShm) object to the pShmNode has been set. All that is
50657  ** left to do is to link the new object into the linked list starting
50658  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
50659  ** mutex.
50660  */
50661  sqlite3_mutex_enter(pShmNode->mutex);
50662  p->pNext = pShmNode->pFirst;
50663  pShmNode->pFirst = p;
50664  sqlite3_mutex_leave(pShmNode->mutex);
50665  return rc;
50666
50667  /* Jump here on any error */
50668shm_open_err:
50669  winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
50670  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
50671  sqlite3_free(p);
50672  sqlite3_free(pNew);
50673  winShmLeaveMutex();
50674  return rc;
50675}
50676
50677/*
50678** Close a connection to shared-memory.  Delete the underlying
50679** storage if deleteFlag is true.
50680*/
50681static int winShmUnmap(
50682  sqlite3_file *fd,          /* Database holding shared memory */
50683  int deleteFlag             /* Delete after closing if true */
50684){
50685  winFile *pDbFd;       /* Database holding shared-memory */
50686  winShm *p;            /* The connection to be closed */
50687  winShmNode *pShmNode; /* The underlying shared-memory file */
50688  winShm **pp;          /* For looping over sibling connections */
50689
50690  pDbFd = (winFile*)fd;
50691  p = pDbFd->pShm;
50692  if( p==0 ) return SQLITE_OK;
50693  pShmNode = p->pShmNode;
50694
50695  /* Remove connection p from the set of connections associated
50696  ** with pShmNode */
50697  sqlite3_mutex_enter(pShmNode->mutex);
50698  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
50699  *pp = p->pNext;
50700
50701  /* Free the connection p */
50702  sqlite3_free(p);
50703  pDbFd->pShm = 0;
50704  sqlite3_mutex_leave(pShmNode->mutex);
50705
50706  /* If pShmNode->nRef has reached 0, then close the underlying
50707  ** shared-memory file, too */
50708  winShmEnterMutex();
50709  assert( pShmNode->nRef>0 );
50710  pShmNode->nRef--;
50711  if( pShmNode->nRef==0 ){
50712    winShmPurge(pDbFd->pVfs, deleteFlag);
50713  }
50714  winShmLeaveMutex();
50715
50716  return SQLITE_OK;
50717}
50718
50719/*
50720** Change the lock state for a shared-memory segment.
50721*/
50722static int winShmLock(
50723  sqlite3_file *fd,          /* Database file holding the shared memory */
50724  int ofst,                  /* First lock to acquire or release */
50725  int n,                     /* Number of locks to acquire or release */
50726  int flags                  /* What to do with the lock */
50727){
50728  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
50729  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
50730  winShm *pX;                           /* For looping over all siblings */
50731  winShmNode *pShmNode;
50732  int rc = SQLITE_OK;                   /* Result code */
50733  u16 mask;                             /* Mask of locks to take or release */
50734
50735  if( p==0 ) return SQLITE_IOERR_SHMLOCK;
50736  pShmNode = p->pShmNode;
50737  if( NEVER(pShmNode==0) ) return SQLITE_IOERR_SHMLOCK;
50738
50739  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
50740  assert( n>=1 );
50741  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
50742       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
50743       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
50744       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
50745  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
50746
50747  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
50748  assert( n>1 || mask==(1<<ofst) );
50749  sqlite3_mutex_enter(pShmNode->mutex);
50750  if( flags & SQLITE_SHM_UNLOCK ){
50751    u16 allMask = 0; /* Mask of locks held by siblings */
50752
50753    /* See if any siblings hold this same lock */
50754    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
50755      if( pX==p ) continue;
50756      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
50757      allMask |= pX->sharedMask;
50758    }
50759
50760    /* Unlock the system-level locks */
50761    if( (mask & allMask)==0 ){
50762      rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
50763    }else{
50764      rc = SQLITE_OK;
50765    }
50766
50767    /* Undo the local locks */
50768    if( rc==SQLITE_OK ){
50769      p->exclMask &= ~mask;
50770      p->sharedMask &= ~mask;
50771    }
50772  }else if( flags & SQLITE_SHM_SHARED ){
50773    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
50774
50775    /* Find out which shared locks are already held by sibling connections.
50776    ** If any sibling already holds an exclusive lock, go ahead and return
50777    ** SQLITE_BUSY.
50778    */
50779    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
50780      if( (pX->exclMask & mask)!=0 ){
50781        rc = SQLITE_BUSY;
50782        break;
50783      }
50784      allShared |= pX->sharedMask;
50785    }
50786
50787    /* Get shared locks at the system level, if necessary */
50788    if( rc==SQLITE_OK ){
50789      if( (allShared & mask)==0 ){
50790        rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
50791      }else{
50792        rc = SQLITE_OK;
50793      }
50794    }
50795
50796    /* Get the local shared locks */
50797    if( rc==SQLITE_OK ){
50798      p->sharedMask |= mask;
50799    }
50800  }else{
50801    /* Make sure no sibling connections hold locks that will block this
50802    ** lock.  If any do, return SQLITE_BUSY right away.
50803    */
50804    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
50805      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
50806        rc = SQLITE_BUSY;
50807        break;
50808      }
50809    }
50810
50811    /* Get the exclusive locks at the system level.  Then if successful
50812    ** also mark the local connection as being locked.
50813    */
50814    if( rc==SQLITE_OK ){
50815      rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
50816      if( rc==SQLITE_OK ){
50817        assert( (p->sharedMask & mask)==0 );
50818        p->exclMask |= mask;
50819      }
50820    }
50821  }
50822  sqlite3_mutex_leave(pShmNode->mutex);
50823  OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
50824           osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
50825           sqlite3ErrName(rc)));
50826  return rc;
50827}
50828
50829/*
50830** Implement a memory barrier or memory fence on shared memory.
50831**
50832** All loads and stores begun before the barrier must complete before
50833** any load or store begun after the barrier.
50834*/
50835static void winShmBarrier(
50836  sqlite3_file *fd          /* Database holding the shared memory */
50837){
50838  UNUSED_PARAMETER(fd);
50839  sqlite3MemoryBarrier();   /* compiler-defined memory barrier */
50840  winShmEnterMutex();       /* Also mutex, for redundancy */
50841  winShmLeaveMutex();
50842}
50843
50844/*
50845** This function is called to obtain a pointer to region iRegion of the
50846** shared-memory associated with the database file fd. Shared-memory regions
50847** are numbered starting from zero. Each shared-memory region is szRegion
50848** bytes in size.
50849**
50850** If an error occurs, an error code is returned and *pp is set to NULL.
50851**
50852** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
50853** region has not been allocated (by any client, including one running in a
50854** separate process), then *pp is set to NULL and SQLITE_OK returned. If
50855** isWrite is non-zero and the requested shared-memory region has not yet
50856** been allocated, it is allocated by this function.
50857**
50858** If the shared-memory region has already been allocated or is allocated by
50859** this call as described above, then it is mapped into this processes
50860** address space (if it is not already), *pp is set to point to the mapped
50861** memory and SQLITE_OK returned.
50862*/
50863static int winShmMap(
50864  sqlite3_file *fd,               /* Handle open on database file */
50865  int iRegion,                    /* Region to retrieve */
50866  int szRegion,                   /* Size of regions */
50867  int isWrite,                    /* True to extend file if necessary */
50868  void volatile **pp              /* OUT: Mapped memory */
50869){
50870  winFile *pDbFd = (winFile*)fd;
50871  winShm *pShm = pDbFd->pShm;
50872  winShmNode *pShmNode;
50873  DWORD protect = PAGE_READWRITE;
50874  DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
50875  int rc = SQLITE_OK;
50876
50877  if( !pShm ){
50878    rc = winOpenSharedMemory(pDbFd);
50879    if( rc!=SQLITE_OK ) return rc;
50880    pShm = pDbFd->pShm;
50881    assert( pShm!=0 );
50882  }
50883  pShmNode = pShm->pShmNode;
50884
50885  sqlite3_mutex_enter(pShmNode->mutex);
50886  if( pShmNode->isUnlocked ){
50887    rc = winLockSharedMemory(pShmNode);
50888    if( rc!=SQLITE_OK ) goto shmpage_out;
50889    pShmNode->isUnlocked = 0;
50890  }
50891  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
50892
50893  if( pShmNode->nRegion<=iRegion ){
50894    struct ShmRegion *apNew;           /* New aRegion[] array */
50895    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
50896    sqlite3_int64 sz;                  /* Current size of wal-index file */
50897
50898    pShmNode->szRegion = szRegion;
50899
50900    /* The requested region is not mapped into this processes address space.
50901    ** Check to see if it has been allocated (i.e. if the wal-index file is
50902    ** large enough to contain the requested region).
50903    */
50904    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
50905    if( rc!=SQLITE_OK ){
50906      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
50907                       "winShmMap1", pDbFd->zPath);
50908      goto shmpage_out;
50909    }
50910
50911    if( sz<nByte ){
50912      /* The requested memory region does not exist. If isWrite is set to
50913      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
50914      **
50915      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
50916      ** the requested memory region.
50917      */
50918      if( !isWrite ) goto shmpage_out;
50919      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
50920      if( rc!=SQLITE_OK ){
50921        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
50922                         "winShmMap2", pDbFd->zPath);
50923        goto shmpage_out;
50924      }
50925    }
50926
50927    /* Map the requested memory region into this processes address space. */
50928    apNew = (struct ShmRegion *)sqlite3_realloc64(
50929        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
50930    );
50931    if( !apNew ){
50932      rc = SQLITE_IOERR_NOMEM_BKPT;
50933      goto shmpage_out;
50934    }
50935    pShmNode->aRegion = apNew;
50936
50937    if( pShmNode->isReadonly ){
50938      protect = PAGE_READONLY;
50939      flags = FILE_MAP_READ;
50940    }
50941
50942    while( pShmNode->nRegion<=iRegion ){
50943      HANDLE hMap = NULL;         /* file-mapping handle */
50944      void *pMap = 0;             /* Mapped memory region */
50945
50946#if SQLITE_OS_WINRT
50947      hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
50948          NULL, protect, nByte, NULL
50949      );
50950#elif defined(SQLITE_WIN32_HAS_WIDE)
50951      hMap = osCreateFileMappingW(pShmNode->hFile.h,
50952          NULL, protect, 0, nByte, NULL
50953      );
50954#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
50955      hMap = osCreateFileMappingA(pShmNode->hFile.h,
50956          NULL, protect, 0, nByte, NULL
50957      );
50958#endif
50959      OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
50960               osGetCurrentProcessId(), pShmNode->nRegion, nByte,
50961               hMap ? "ok" : "failed"));
50962      if( hMap ){
50963        int iOffset = pShmNode->nRegion*szRegion;
50964        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
50965#if SQLITE_OS_WINRT
50966        pMap = osMapViewOfFileFromApp(hMap, flags,
50967            iOffset - iOffsetShift, szRegion + iOffsetShift
50968        );
50969#else
50970        pMap = osMapViewOfFile(hMap, flags,
50971            0, iOffset - iOffsetShift, szRegion + iOffsetShift
50972        );
50973#endif
50974        OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
50975                 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
50976                 szRegion, pMap ? "ok" : "failed"));
50977      }
50978      if( !pMap ){
50979        pShmNode->lastErrno = osGetLastError();
50980        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
50981                         "winShmMap3", pDbFd->zPath);
50982        if( hMap ) osCloseHandle(hMap);
50983        goto shmpage_out;
50984      }
50985
50986      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
50987      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
50988      pShmNode->nRegion++;
50989    }
50990  }
50991
50992shmpage_out:
50993  if( pShmNode->nRegion>iRegion ){
50994    int iOffset = iRegion*szRegion;
50995    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
50996    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
50997    *pp = (void *)&p[iOffsetShift];
50998  }else{
50999    *pp = 0;
51000  }
51001  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
51002  sqlite3_mutex_leave(pShmNode->mutex);
51003  return rc;
51004}
51005
51006#else
51007# define winShmMap     0
51008# define winShmLock    0
51009# define winShmBarrier 0
51010# define winShmUnmap   0
51011#endif /* #ifndef SQLITE_OMIT_WAL */
51012
51013/*
51014** Cleans up the mapped region of the specified file, if any.
51015*/
51016#if SQLITE_MAX_MMAP_SIZE>0
51017static int winUnmapfile(winFile *pFile){
51018  assert( pFile!=0 );
51019  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
51020           "mmapSize=%lld, mmapSizeMax=%lld\n",
51021           osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
51022           pFile->mmapSize, pFile->mmapSizeMax));
51023  if( pFile->pMapRegion ){
51024    if( !osUnmapViewOfFile(pFile->pMapRegion) ){
51025      pFile->lastErrno = osGetLastError();
51026      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
51027               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
51028               pFile->pMapRegion));
51029      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
51030                         "winUnmapfile1", pFile->zPath);
51031    }
51032    pFile->pMapRegion = 0;
51033    pFile->mmapSize = 0;
51034  }
51035  if( pFile->hMap!=NULL ){
51036    if( !osCloseHandle(pFile->hMap) ){
51037      pFile->lastErrno = osGetLastError();
51038      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
51039               osGetCurrentProcessId(), pFile, pFile->hMap));
51040      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
51041                         "winUnmapfile2", pFile->zPath);
51042    }
51043    pFile->hMap = NULL;
51044  }
51045  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
51046           osGetCurrentProcessId(), pFile));
51047  return SQLITE_OK;
51048}
51049
51050/*
51051** Memory map or remap the file opened by file-descriptor pFd (if the file
51052** is already mapped, the existing mapping is replaced by the new). Or, if
51053** there already exists a mapping for this file, and there are still
51054** outstanding xFetch() references to it, this function is a no-op.
51055**
51056** If parameter nByte is non-negative, then it is the requested size of
51057** the mapping to create. Otherwise, if nByte is less than zero, then the
51058** requested size is the size of the file on disk. The actual size of the
51059** created mapping is either the requested size or the value configured
51060** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
51061**
51062** SQLITE_OK is returned if no error occurs (even if the mapping is not
51063** recreated as a result of outstanding references) or an SQLite error
51064** code otherwise.
51065*/
51066static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
51067  sqlite3_int64 nMap = nByte;
51068  int rc;
51069
51070  assert( nMap>=0 || pFd->nFetchOut==0 );
51071  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
51072           osGetCurrentProcessId(), pFd, nByte));
51073
51074  if( pFd->nFetchOut>0 ) return SQLITE_OK;
51075
51076  if( nMap<0 ){
51077    rc = winFileSize((sqlite3_file*)pFd, &nMap);
51078    if( rc ){
51079      OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
51080               osGetCurrentProcessId(), pFd));
51081      return SQLITE_IOERR_FSTAT;
51082    }
51083  }
51084  if( nMap>pFd->mmapSizeMax ){
51085    nMap = pFd->mmapSizeMax;
51086  }
51087  nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
51088
51089  if( nMap==0 && pFd->mmapSize>0 ){
51090    winUnmapfile(pFd);
51091  }
51092  if( nMap!=pFd->mmapSize ){
51093    void *pNew = 0;
51094    DWORD protect = PAGE_READONLY;
51095    DWORD flags = FILE_MAP_READ;
51096
51097    winUnmapfile(pFd);
51098#ifdef SQLITE_MMAP_READWRITE
51099    if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
51100      protect = PAGE_READWRITE;
51101      flags |= FILE_MAP_WRITE;
51102    }
51103#endif
51104#if SQLITE_OS_WINRT
51105    pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
51106#elif defined(SQLITE_WIN32_HAS_WIDE)
51107    pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
51108                                (DWORD)((nMap>>32) & 0xffffffff),
51109                                (DWORD)(nMap & 0xffffffff), NULL);
51110#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
51111    pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
51112                                (DWORD)((nMap>>32) & 0xffffffff),
51113                                (DWORD)(nMap & 0xffffffff), NULL);
51114#endif
51115    if( pFd->hMap==NULL ){
51116      pFd->lastErrno = osGetLastError();
51117      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
51118                       "winMapfile1", pFd->zPath);
51119      /* Log the error, but continue normal operation using xRead/xWrite */
51120      OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
51121               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
51122      return SQLITE_OK;
51123    }
51124    assert( (nMap % winSysInfo.dwPageSize)==0 );
51125    assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
51126#if SQLITE_OS_WINRT
51127    pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
51128#else
51129    pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
51130#endif
51131    if( pNew==NULL ){
51132      osCloseHandle(pFd->hMap);
51133      pFd->hMap = NULL;
51134      pFd->lastErrno = osGetLastError();
51135      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
51136                       "winMapfile2", pFd->zPath);
51137      /* Log the error, but continue normal operation using xRead/xWrite */
51138      OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
51139               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
51140      return SQLITE_OK;
51141    }
51142    pFd->pMapRegion = pNew;
51143    pFd->mmapSize = nMap;
51144  }
51145
51146  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
51147           osGetCurrentProcessId(), pFd));
51148  return SQLITE_OK;
51149}
51150#endif /* SQLITE_MAX_MMAP_SIZE>0 */
51151
51152/*
51153** If possible, return a pointer to a mapping of file fd starting at offset
51154** iOff. The mapping must be valid for at least nAmt bytes.
51155**
51156** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
51157** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
51158** Finally, if an error does occur, return an SQLite error code. The final
51159** value of *pp is undefined in this case.
51160**
51161** If this function does return a pointer, the caller must eventually
51162** release the reference by calling winUnfetch().
51163*/
51164static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
51165#if SQLITE_MAX_MMAP_SIZE>0
51166  winFile *pFd = (winFile*)fd;   /* The underlying database file */
51167#endif
51168  *pp = 0;
51169
51170  OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
51171           osGetCurrentProcessId(), fd, iOff, nAmt, pp));
51172
51173#if SQLITE_MAX_MMAP_SIZE>0
51174  if( pFd->mmapSizeMax>0 ){
51175    /* Ensure that there is always at least a 256 byte buffer of addressable
51176    ** memory following the returned page. If the database is corrupt,
51177    ** SQLite may overread the page slightly (in practice only a few bytes,
51178    ** but 256 is safe, round, number).  */
51179    const int nEofBuffer = 256;
51180    if( pFd->pMapRegion==0 ){
51181      int rc = winMapfile(pFd, -1);
51182      if( rc!=SQLITE_OK ){
51183        OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
51184                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
51185        return rc;
51186      }
51187    }
51188    if( pFd->mmapSize >= (iOff+nAmt+nEofBuffer) ){
51189      assert( pFd->pMapRegion!=0 );
51190      *pp = &((u8 *)pFd->pMapRegion)[iOff];
51191      pFd->nFetchOut++;
51192    }
51193  }
51194#endif
51195
51196  OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
51197           osGetCurrentProcessId(), fd, pp, *pp));
51198  return SQLITE_OK;
51199}
51200
51201/*
51202** If the third argument is non-NULL, then this function releases a
51203** reference obtained by an earlier call to winFetch(). The second
51204** argument passed to this function must be the same as the corresponding
51205** argument that was passed to the winFetch() invocation.
51206**
51207** Or, if the third argument is NULL, then this function is being called
51208** to inform the VFS layer that, according to POSIX, any existing mapping
51209** may now be invalid and should be unmapped.
51210*/
51211static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
51212#if SQLITE_MAX_MMAP_SIZE>0
51213  winFile *pFd = (winFile*)fd;   /* The underlying database file */
51214
51215  /* If p==0 (unmap the entire file) then there must be no outstanding
51216  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
51217  ** then there must be at least one outstanding.  */
51218  assert( (p==0)==(pFd->nFetchOut==0) );
51219
51220  /* If p!=0, it must match the iOff value. */
51221  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
51222
51223  OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
51224           osGetCurrentProcessId(), pFd, iOff, p));
51225
51226  if( p ){
51227    pFd->nFetchOut--;
51228  }else{
51229    /* FIXME:  If Windows truly always prevents truncating or deleting a
51230    ** file while a mapping is held, then the following winUnmapfile() call
51231    ** is unnecessary can be omitted - potentially improving
51232    ** performance.  */
51233    winUnmapfile(pFd);
51234  }
51235
51236  assert( pFd->nFetchOut>=0 );
51237#endif
51238
51239  OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
51240           osGetCurrentProcessId(), fd));
51241  return SQLITE_OK;
51242}
51243
51244/*
51245** Here ends the implementation of all sqlite3_file methods.
51246**
51247********************** End sqlite3_file Methods *******************************
51248******************************************************************************/
51249
51250/*
51251** This vector defines all the methods that can operate on an
51252** sqlite3_file for win32.
51253*/
51254static const sqlite3_io_methods winIoMethod = {
51255  3,                              /* iVersion */
51256  winClose,                       /* xClose */
51257  winRead,                        /* xRead */
51258  winWrite,                       /* xWrite */
51259  winTruncate,                    /* xTruncate */
51260  winSync,                        /* xSync */
51261  winFileSize,                    /* xFileSize */
51262  winLock,                        /* xLock */
51263  winUnlock,                      /* xUnlock */
51264  winCheckReservedLock,           /* xCheckReservedLock */
51265  winFileControl,                 /* xFileControl */
51266  winSectorSize,                  /* xSectorSize */
51267  winDeviceCharacteristics,       /* xDeviceCharacteristics */
51268  winShmMap,                      /* xShmMap */
51269  winShmLock,                     /* xShmLock */
51270  winShmBarrier,                  /* xShmBarrier */
51271  winShmUnmap,                    /* xShmUnmap */
51272  winFetch,                       /* xFetch */
51273  winUnfetch                      /* xUnfetch */
51274};
51275
51276/*
51277** This vector defines all the methods that can operate on an
51278** sqlite3_file for win32 without performing any locking.
51279*/
51280static const sqlite3_io_methods winIoNolockMethod = {
51281  3,                              /* iVersion */
51282  winClose,                       /* xClose */
51283  winRead,                        /* xRead */
51284  winWrite,                       /* xWrite */
51285  winTruncate,                    /* xTruncate */
51286  winSync,                        /* xSync */
51287  winFileSize,                    /* xFileSize */
51288  winNolockLock,                  /* xLock */
51289  winNolockUnlock,                /* xUnlock */
51290  winNolockCheckReservedLock,     /* xCheckReservedLock */
51291  winFileControl,                 /* xFileControl */
51292  winSectorSize,                  /* xSectorSize */
51293  winDeviceCharacteristics,       /* xDeviceCharacteristics */
51294  winShmMap,                      /* xShmMap */
51295  winShmLock,                     /* xShmLock */
51296  winShmBarrier,                  /* xShmBarrier */
51297  winShmUnmap,                    /* xShmUnmap */
51298  winFetch,                       /* xFetch */
51299  winUnfetch                      /* xUnfetch */
51300};
51301
51302static winVfsAppData winAppData = {
51303  &winIoMethod,       /* pMethod */
51304  0,                  /* pAppData */
51305  0                   /* bNoLock */
51306};
51307
51308static winVfsAppData winNolockAppData = {
51309  &winIoNolockMethod, /* pMethod */
51310  0,                  /* pAppData */
51311  1                   /* bNoLock */
51312};
51313
51314/****************************************************************************
51315**************************** sqlite3_vfs methods ****************************
51316**
51317** This division contains the implementation of methods on the
51318** sqlite3_vfs object.
51319*/
51320
51321#if defined(__CYGWIN__)
51322/*
51323** Convert a filename from whatever the underlying operating system
51324** supports for filenames into UTF-8.  Space to hold the result is
51325** obtained from malloc and must be freed by the calling function.
51326*/
51327static char *winConvertToUtf8Filename(const void *zFilename){
51328  char *zConverted = 0;
51329  if( osIsNT() ){
51330    zConverted = winUnicodeToUtf8(zFilename);
51331  }
51332#ifdef SQLITE_WIN32_HAS_ANSI
51333  else{
51334    zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
51335  }
51336#endif
51337  /* caller will handle out of memory */
51338  return zConverted;
51339}
51340#endif
51341
51342/*
51343** Convert a UTF-8 filename into whatever form the underlying
51344** operating system wants filenames in.  Space to hold the result
51345** is obtained from malloc and must be freed by the calling
51346** function.
51347*/
51348static void *winConvertFromUtf8Filename(const char *zFilename){
51349  void *zConverted = 0;
51350  if( osIsNT() ){
51351    zConverted = winUtf8ToUnicode(zFilename);
51352  }
51353#ifdef SQLITE_WIN32_HAS_ANSI
51354  else{
51355    zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
51356  }
51357#endif
51358  /* caller will handle out of memory */
51359  return zConverted;
51360}
51361
51362/*
51363** This function returns non-zero if the specified UTF-8 string buffer
51364** ends with a directory separator character or one was successfully
51365** added to it.
51366*/
51367static int winMakeEndInDirSep(int nBuf, char *zBuf){
51368  if( zBuf ){
51369    int nLen = sqlite3Strlen30(zBuf);
51370    if( nLen>0 ){
51371      if( winIsDirSep(zBuf[nLen-1]) ){
51372        return 1;
51373      }else if( nLen+1<nBuf ){
51374        zBuf[nLen] = winGetDirSep();
51375        zBuf[nLen+1] = '\0';
51376        return 1;
51377      }
51378    }
51379  }
51380  return 0;
51381}
51382
51383/*
51384** If sqlite3_temp_directory is defined, take the mutex and return true.
51385**
51386** If sqlite3_temp_directory is NULL (undefined), omit the mutex and
51387** return false.
51388*/
51389static int winTempDirDefined(void){
51390  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
51391  if( sqlite3_temp_directory!=0 ) return 1;
51392  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
51393  return 0;
51394}
51395
51396/*
51397** Create a temporary file name and store the resulting pointer into pzBuf.
51398** The pointer returned in pzBuf must be freed via sqlite3_free().
51399*/
51400static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
51401  static char zChars[] =
51402    "abcdefghijklmnopqrstuvwxyz"
51403    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
51404    "0123456789";
51405  size_t i, j;
51406  DWORD pid;
51407  int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
51408  int nMax, nBuf, nDir, nLen;
51409  char *zBuf;
51410
51411  /* It's odd to simulate an io-error here, but really this is just
51412  ** using the io-error infrastructure to test that SQLite handles this
51413  ** function failing.
51414  */
51415  SimulateIOError( return SQLITE_IOERR );
51416
51417  /* Allocate a temporary buffer to store the fully qualified file
51418  ** name for the temporary file.  If this fails, we cannot continue.
51419  */
51420  nMax = pVfs->mxPathname; nBuf = nMax + 2;
51421  zBuf = sqlite3MallocZero( nBuf );
51422  if( !zBuf ){
51423    OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
51424    return SQLITE_IOERR_NOMEM_BKPT;
51425  }
51426
51427  /* Figure out the effective temporary directory.  First, check if one
51428  ** has been explicitly set by the application; otherwise, use the one
51429  ** configured by the operating system.
51430  */
51431  nDir = nMax - (nPre + 15);
51432  assert( nDir>0 );
51433  if( winTempDirDefined() ){
51434    int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
51435    if( nDirLen>0 ){
51436      if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
51437        nDirLen++;
51438      }
51439      if( nDirLen>nDir ){
51440        sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
51441        sqlite3_free(zBuf);
51442        OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
51443        return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
51444      }
51445      sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
51446    }
51447    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
51448  }
51449
51450#if defined(__CYGWIN__)
51451  else{
51452    static const char *azDirs[] = {
51453       0, /* getenv("SQLITE_TMPDIR") */
51454       0, /* getenv("TMPDIR") */
51455       0, /* getenv("TMP") */
51456       0, /* getenv("TEMP") */
51457       0, /* getenv("USERPROFILE") */
51458       "/var/tmp",
51459       "/usr/tmp",
51460       "/tmp",
51461       ".",
51462       0        /* List terminator */
51463    };
51464    unsigned int i;
51465    const char *zDir = 0;
51466
51467    if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
51468    if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
51469    if( !azDirs[2] ) azDirs[2] = getenv("TMP");
51470    if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
51471    if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
51472    for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
51473      void *zConverted;
51474      if( zDir==0 ) continue;
51475      /* If the path starts with a drive letter followed by the colon
51476      ** character, assume it is already a native Win32 path; otherwise,
51477      ** it must be converted to a native Win32 path via the Cygwin API
51478      ** prior to using it.
51479      */
51480      if( winIsDriveLetterAndColon(zDir) ){
51481        zConverted = winConvertFromUtf8Filename(zDir);
51482        if( !zConverted ){
51483          sqlite3_free(zBuf);
51484          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
51485          return SQLITE_IOERR_NOMEM_BKPT;
51486        }
51487        if( winIsDir(zConverted) ){
51488          sqlite3_snprintf(nMax, zBuf, "%s", zDir);
51489          sqlite3_free(zConverted);
51490          break;
51491        }
51492        sqlite3_free(zConverted);
51493      }else{
51494        zConverted = sqlite3MallocZero( nMax+1 );
51495        if( !zConverted ){
51496          sqlite3_free(zBuf);
51497          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
51498          return SQLITE_IOERR_NOMEM_BKPT;
51499        }
51500        if( cygwin_conv_path(
51501                osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
51502                zConverted, nMax+1)<0 ){
51503          sqlite3_free(zConverted);
51504          sqlite3_free(zBuf);
51505          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
51506          return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
51507                             "winGetTempname2", zDir);
51508        }
51509        if( winIsDir(zConverted) ){
51510          /* At this point, we know the candidate directory exists and should
51511          ** be used.  However, we may need to convert the string containing
51512          ** its name into UTF-8 (i.e. if it is UTF-16 right now).
51513          */
51514          char *zUtf8 = winConvertToUtf8Filename(zConverted);
51515          if( !zUtf8 ){
51516            sqlite3_free(zConverted);
51517            sqlite3_free(zBuf);
51518            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
51519            return SQLITE_IOERR_NOMEM_BKPT;
51520          }
51521          sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
51522          sqlite3_free(zUtf8);
51523          sqlite3_free(zConverted);
51524          break;
51525        }
51526        sqlite3_free(zConverted);
51527      }
51528    }
51529  }
51530#elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
51531  else if( osIsNT() ){
51532    char *zMulti;
51533    LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
51534    if( !zWidePath ){
51535      sqlite3_free(zBuf);
51536      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
51537      return SQLITE_IOERR_NOMEM_BKPT;
51538    }
51539    if( osGetTempPathW(nMax, zWidePath)==0 ){
51540      sqlite3_free(zWidePath);
51541      sqlite3_free(zBuf);
51542      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
51543      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
51544                         "winGetTempname2", 0);
51545    }
51546    zMulti = winUnicodeToUtf8(zWidePath);
51547    if( zMulti ){
51548      sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
51549      sqlite3_free(zMulti);
51550      sqlite3_free(zWidePath);
51551    }else{
51552      sqlite3_free(zWidePath);
51553      sqlite3_free(zBuf);
51554      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
51555      return SQLITE_IOERR_NOMEM_BKPT;
51556    }
51557  }
51558#ifdef SQLITE_WIN32_HAS_ANSI
51559  else{
51560    char *zUtf8;
51561    char *zMbcsPath = sqlite3MallocZero( nMax );
51562    if( !zMbcsPath ){
51563      sqlite3_free(zBuf);
51564      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
51565      return SQLITE_IOERR_NOMEM_BKPT;
51566    }
51567    if( osGetTempPathA(nMax, zMbcsPath)==0 ){
51568      sqlite3_free(zBuf);
51569      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
51570      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
51571                         "winGetTempname3", 0);
51572    }
51573    zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
51574    if( zUtf8 ){
51575      sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
51576      sqlite3_free(zUtf8);
51577    }else{
51578      sqlite3_free(zBuf);
51579      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
51580      return SQLITE_IOERR_NOMEM_BKPT;
51581    }
51582  }
51583#endif /* SQLITE_WIN32_HAS_ANSI */
51584#endif /* !SQLITE_OS_WINRT */
51585
51586  /*
51587  ** Check to make sure the temporary directory ends with an appropriate
51588  ** separator.  If it does not and there is not enough space left to add
51589  ** one, fail.
51590  */
51591  if( !winMakeEndInDirSep(nDir+1, zBuf) ){
51592    sqlite3_free(zBuf);
51593    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
51594    return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
51595  }
51596
51597  /*
51598  ** Check that the output buffer is large enough for the temporary file
51599  ** name in the following format:
51600  **
51601  **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
51602  **
51603  ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
51604  ** account for the space used by the 15 character random suffix and the
51605  ** two trailing NUL characters.  The final directory separator character
51606  ** has already added if it was not already present.
51607  */
51608  nLen = sqlite3Strlen30(zBuf);
51609  if( (nLen + nPre + 17) > nBuf ){
51610    sqlite3_free(zBuf);
51611    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
51612    return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
51613  }
51614
51615  sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
51616
51617  j = sqlite3Strlen30(zBuf);
51618  sqlite3_randomness(15, &zBuf[j]);
51619  pid = osGetCurrentProcessId();
51620  for(i=0; i<15; i++, j++){
51621    zBuf[j] += pid & 0xff;
51622    pid >>= 8;
51623    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
51624  }
51625  zBuf[j] = 0;
51626  zBuf[j+1] = 0;
51627  *pzBuf = zBuf;
51628
51629  OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
51630  return SQLITE_OK;
51631}
51632
51633/*
51634** Return TRUE if the named file is really a directory.  Return false if
51635** it is something other than a directory, or if there is any kind of memory
51636** allocation failure.
51637*/
51638static int winIsDir(const void *zConverted){
51639  DWORD attr;
51640  int rc = 0;
51641  DWORD lastErrno;
51642
51643  if( osIsNT() ){
51644    int cnt = 0;
51645    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
51646    memset(&sAttrData, 0, sizeof(sAttrData));
51647    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
51648                             GetFileExInfoStandard,
51649                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
51650    if( !rc ){
51651      return 0; /* Invalid name? */
51652    }
51653    attr = sAttrData.dwFileAttributes;
51654#if SQLITE_OS_WINCE==0
51655  }else{
51656    attr = osGetFileAttributesA((char*)zConverted);
51657#endif
51658  }
51659  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
51660}
51661
51662/* forward reference */
51663static int winAccess(
51664  sqlite3_vfs *pVfs,         /* Not used on win32 */
51665  const char *zFilename,     /* Name of file to check */
51666  int flags,                 /* Type of test to make on this file */
51667  int *pResOut               /* OUT: Result */
51668);
51669
51670/*
51671** Open a file.
51672*/
51673static int winOpen(
51674  sqlite3_vfs *pVfs,        /* Used to get maximum path length and AppData */
51675  const char *zName,        /* Name of the file (UTF-8) */
51676  sqlite3_file *id,         /* Write the SQLite file handle here */
51677  int flags,                /* Open mode flags */
51678  int *pOutFlags            /* Status return flags */
51679){
51680  HANDLE h;
51681  DWORD lastErrno = 0;
51682  DWORD dwDesiredAccess;
51683  DWORD dwShareMode;
51684  DWORD dwCreationDisposition;
51685  DWORD dwFlagsAndAttributes = 0;
51686#if SQLITE_OS_WINCE
51687  int isTemp = 0;
51688#endif
51689  winVfsAppData *pAppData;
51690  winFile *pFile = (winFile*)id;
51691  void *zConverted;              /* Filename in OS encoding */
51692  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
51693  int cnt = 0;
51694
51695  /* If argument zPath is a NULL pointer, this function is required to open
51696  ** a temporary file. Use this buffer to store the file name in.
51697  */
51698  char *zTmpname = 0; /* For temporary filename, if necessary. */
51699
51700  int rc = SQLITE_OK;            /* Function Return Code */
51701#if !defined(NDEBUG) || SQLITE_OS_WINCE
51702  int eType = flags&0xFFFFFF00;  /* Type of file to open */
51703#endif
51704
51705  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
51706  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
51707  int isCreate     = (flags & SQLITE_OPEN_CREATE);
51708  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
51709  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
51710
51711#ifndef NDEBUG
51712  int isOpenJournal = (isCreate && (
51713        eType==SQLITE_OPEN_SUPER_JOURNAL
51714     || eType==SQLITE_OPEN_MAIN_JOURNAL
51715     || eType==SQLITE_OPEN_WAL
51716  ));
51717#endif
51718
51719  OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
51720           zUtf8Name, id, flags, pOutFlags));
51721
51722  /* Check the following statements are true:
51723  **
51724  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
51725  **   (b) if CREATE is set, then READWRITE must also be set, and
51726  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
51727  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
51728  */
51729  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
51730  assert(isCreate==0 || isReadWrite);
51731  assert(isExclusive==0 || isCreate);
51732  assert(isDelete==0 || isCreate);
51733
51734  /* The main DB, main journal, WAL file and super-journal are never
51735  ** automatically deleted. Nor are they ever temporary files.  */
51736  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
51737  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
51738  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL );
51739  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
51740
51741  /* Assert that the upper layer has set one of the "file-type" flags. */
51742  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
51743       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
51744       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_SUPER_JOURNAL
51745       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
51746  );
51747
51748  assert( pFile!=0 );
51749  memset(pFile, 0, sizeof(winFile));
51750  pFile->h = INVALID_HANDLE_VALUE;
51751
51752#if SQLITE_OS_WINRT
51753  if( !zUtf8Name && !sqlite3_temp_directory ){
51754    sqlite3_log(SQLITE_ERROR,
51755        "sqlite3_temp_directory variable should be set for WinRT");
51756  }
51757#endif
51758
51759  /* If the second argument to this function is NULL, generate a
51760  ** temporary file name to use
51761  */
51762  if( !zUtf8Name ){
51763    assert( isDelete && !isOpenJournal );
51764    rc = winGetTempname(pVfs, &zTmpname);
51765    if( rc!=SQLITE_OK ){
51766      OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
51767      return rc;
51768    }
51769    zUtf8Name = zTmpname;
51770  }
51771
51772  /* Database filenames are double-zero terminated if they are not
51773  ** URIs with parameters.  Hence, they can always be passed into
51774  ** sqlite3_uri_parameter().
51775  */
51776  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
51777       zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
51778
51779  /* Convert the filename to the system encoding. */
51780  zConverted = winConvertFromUtf8Filename(zUtf8Name);
51781  if( zConverted==0 ){
51782    sqlite3_free(zTmpname);
51783    OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
51784    return SQLITE_IOERR_NOMEM_BKPT;
51785  }
51786
51787  if( winIsDir(zConverted) ){
51788    sqlite3_free(zConverted);
51789    sqlite3_free(zTmpname);
51790    OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
51791    return SQLITE_CANTOPEN_ISDIR;
51792  }
51793
51794  if( isReadWrite ){
51795    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
51796  }else{
51797    dwDesiredAccess = GENERIC_READ;
51798  }
51799
51800  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
51801  ** created. SQLite doesn't use it to indicate "exclusive access"
51802  ** as it is usually understood.
51803  */
51804  if( isExclusive ){
51805    /* Creates a new file, only if it does not already exist. */
51806    /* If the file exists, it fails. */
51807    dwCreationDisposition = CREATE_NEW;
51808  }else if( isCreate ){
51809    /* Open existing file, or create if it doesn't exist */
51810    dwCreationDisposition = OPEN_ALWAYS;
51811  }else{
51812    /* Opens a file, only if it exists. */
51813    dwCreationDisposition = OPEN_EXISTING;
51814  }
51815
51816  if( 0==sqlite3_uri_boolean(zName, "exclusive", 0) ){
51817    dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
51818  }else{
51819    dwShareMode = 0;
51820  }
51821
51822  if( isDelete ){
51823#if SQLITE_OS_WINCE
51824    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
51825    isTemp = 1;
51826#else
51827    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
51828                               | FILE_ATTRIBUTE_HIDDEN
51829                               | FILE_FLAG_DELETE_ON_CLOSE;
51830#endif
51831  }else{
51832    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
51833  }
51834  /* Reports from the internet are that performance is always
51835  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
51836#if SQLITE_OS_WINCE
51837  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
51838#endif
51839
51840  if( osIsNT() ){
51841#if SQLITE_OS_WINRT
51842    CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
51843    extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
51844    extendedParameters.dwFileAttributes =
51845            dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
51846    extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
51847    extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
51848    extendedParameters.lpSecurityAttributes = NULL;
51849    extendedParameters.hTemplateFile = NULL;
51850    do{
51851      h = osCreateFile2((LPCWSTR)zConverted,
51852                        dwDesiredAccess,
51853                        dwShareMode,
51854                        dwCreationDisposition,
51855                        &extendedParameters);
51856      if( h!=INVALID_HANDLE_VALUE ) break;
51857      if( isReadWrite ){
51858        int rc2, isRO = 0;
51859        sqlite3BeginBenignMalloc();
51860        rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO);
51861        sqlite3EndBenignMalloc();
51862        if( rc2==SQLITE_OK && isRO ) break;
51863      }
51864    }while( winRetryIoerr(&cnt, &lastErrno) );
51865#else
51866    do{
51867      h = osCreateFileW((LPCWSTR)zConverted,
51868                        dwDesiredAccess,
51869                        dwShareMode, NULL,
51870                        dwCreationDisposition,
51871                        dwFlagsAndAttributes,
51872                        NULL);
51873      if( h!=INVALID_HANDLE_VALUE ) break;
51874      if( isReadWrite ){
51875        int rc2, isRO = 0;
51876        sqlite3BeginBenignMalloc();
51877        rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO);
51878        sqlite3EndBenignMalloc();
51879        if( rc2==SQLITE_OK && isRO ) break;
51880      }
51881    }while( winRetryIoerr(&cnt, &lastErrno) );
51882#endif
51883  }
51884#ifdef SQLITE_WIN32_HAS_ANSI
51885  else{
51886    do{
51887      h = osCreateFileA((LPCSTR)zConverted,
51888                        dwDesiredAccess,
51889                        dwShareMode, NULL,
51890                        dwCreationDisposition,
51891                        dwFlagsAndAttributes,
51892                        NULL);
51893      if( h!=INVALID_HANDLE_VALUE ) break;
51894      if( isReadWrite ){
51895        int rc2, isRO = 0;
51896        sqlite3BeginBenignMalloc();
51897        rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO);
51898        sqlite3EndBenignMalloc();
51899        if( rc2==SQLITE_OK && isRO ) break;
51900      }
51901    }while( winRetryIoerr(&cnt, &lastErrno) );
51902  }
51903#endif
51904  winLogIoerr(cnt, __LINE__);
51905
51906  OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
51907           dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
51908
51909  if( h==INVALID_HANDLE_VALUE ){
51910    sqlite3_free(zConverted);
51911    sqlite3_free(zTmpname);
51912    if( isReadWrite && !isExclusive ){
51913      return winOpen(pVfs, zName, id,
51914         ((flags|SQLITE_OPEN_READONLY) &
51915                     ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
51916         pOutFlags);
51917    }else{
51918      pFile->lastErrno = lastErrno;
51919      winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
51920      return SQLITE_CANTOPEN_BKPT;
51921    }
51922  }
51923
51924  if( pOutFlags ){
51925    if( isReadWrite ){
51926      *pOutFlags = SQLITE_OPEN_READWRITE;
51927    }else{
51928      *pOutFlags = SQLITE_OPEN_READONLY;
51929    }
51930  }
51931
51932  OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
51933           "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
51934           *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
51935
51936  pAppData = (winVfsAppData*)pVfs->pAppData;
51937
51938#if SQLITE_OS_WINCE
51939  {
51940    if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
51941         && ((pAppData==NULL) || !pAppData->bNoLock)
51942         && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
51943    ){
51944      osCloseHandle(h);
51945      sqlite3_free(zConverted);
51946      sqlite3_free(zTmpname);
51947      OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
51948      return rc;
51949    }
51950  }
51951  if( isTemp ){
51952    pFile->zDeleteOnClose = zConverted;
51953  }else
51954#endif
51955  {
51956    sqlite3_free(zConverted);
51957  }
51958
51959  sqlite3_free(zTmpname);
51960  id->pMethods = pAppData ? pAppData->pMethod : &winIoMethod;
51961  pFile->pVfs = pVfs;
51962  pFile->h = h;
51963  if( isReadonly ){
51964    pFile->ctrlFlags |= WINFILE_RDONLY;
51965  }
51966  if( (flags & SQLITE_OPEN_MAIN_DB)
51967   && sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE)
51968  ){
51969    pFile->ctrlFlags |= WINFILE_PSOW;
51970  }
51971  pFile->lastErrno = NO_ERROR;
51972  pFile->zPath = zName;
51973#if SQLITE_MAX_MMAP_SIZE>0
51974  pFile->hMap = NULL;
51975  pFile->pMapRegion = 0;
51976  pFile->mmapSize = 0;
51977  pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
51978#endif
51979
51980  OpenCounter(+1);
51981  return rc;
51982}
51983
51984/*
51985** Delete the named file.
51986**
51987** Note that Windows does not allow a file to be deleted if some other
51988** process has it open.  Sometimes a virus scanner or indexing program
51989** will open a journal file shortly after it is created in order to do
51990** whatever it does.  While this other process is holding the
51991** file open, we will be unable to delete it.  To work around this
51992** problem, we delay 100 milliseconds and try to delete again.  Up
51993** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
51994** up and returning an error.
51995*/
51996static int winDelete(
51997  sqlite3_vfs *pVfs,          /* Not used on win32 */
51998  const char *zFilename,      /* Name of file to delete */
51999  int syncDir                 /* Not used on win32 */
52000){
52001  int cnt = 0;
52002  int rc;
52003  DWORD attr;
52004  DWORD lastErrno = 0;
52005  void *zConverted;
52006  UNUSED_PARAMETER(pVfs);
52007  UNUSED_PARAMETER(syncDir);
52008
52009  SimulateIOError(return SQLITE_IOERR_DELETE);
52010  OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
52011
52012  zConverted = winConvertFromUtf8Filename(zFilename);
52013  if( zConverted==0 ){
52014    OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
52015    return SQLITE_IOERR_NOMEM_BKPT;
52016  }
52017  if( osIsNT() ){
52018    do {
52019#if SQLITE_OS_WINRT
52020      WIN32_FILE_ATTRIBUTE_DATA sAttrData;
52021      memset(&sAttrData, 0, sizeof(sAttrData));
52022      if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
52023                                  &sAttrData) ){
52024        attr = sAttrData.dwFileAttributes;
52025      }else{
52026        lastErrno = osGetLastError();
52027        if( lastErrno==ERROR_FILE_NOT_FOUND
52028         || lastErrno==ERROR_PATH_NOT_FOUND ){
52029          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
52030        }else{
52031          rc = SQLITE_ERROR;
52032        }
52033        break;
52034      }
52035#else
52036      attr = osGetFileAttributesW(zConverted);
52037#endif
52038      if ( attr==INVALID_FILE_ATTRIBUTES ){
52039        lastErrno = osGetLastError();
52040        if( lastErrno==ERROR_FILE_NOT_FOUND
52041         || lastErrno==ERROR_PATH_NOT_FOUND ){
52042          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
52043        }else{
52044          rc = SQLITE_ERROR;
52045        }
52046        break;
52047      }
52048      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
52049        rc = SQLITE_ERROR; /* Files only. */
52050        break;
52051      }
52052      if ( osDeleteFileW(zConverted) ){
52053        rc = SQLITE_OK; /* Deleted OK. */
52054        break;
52055      }
52056      if ( !winRetryIoerr(&cnt, &lastErrno) ){
52057        rc = SQLITE_ERROR; /* No more retries. */
52058        break;
52059      }
52060    } while(1);
52061  }
52062#ifdef SQLITE_WIN32_HAS_ANSI
52063  else{
52064    do {
52065      attr = osGetFileAttributesA(zConverted);
52066      if ( attr==INVALID_FILE_ATTRIBUTES ){
52067        lastErrno = osGetLastError();
52068        if( lastErrno==ERROR_FILE_NOT_FOUND
52069         || lastErrno==ERROR_PATH_NOT_FOUND ){
52070          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
52071        }else{
52072          rc = SQLITE_ERROR;
52073        }
52074        break;
52075      }
52076      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
52077        rc = SQLITE_ERROR; /* Files only. */
52078        break;
52079      }
52080      if ( osDeleteFileA(zConverted) ){
52081        rc = SQLITE_OK; /* Deleted OK. */
52082        break;
52083      }
52084      if ( !winRetryIoerr(&cnt, &lastErrno) ){
52085        rc = SQLITE_ERROR; /* No more retries. */
52086        break;
52087      }
52088    } while(1);
52089  }
52090#endif
52091  if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
52092    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
52093  }else{
52094    winLogIoerr(cnt, __LINE__);
52095  }
52096  sqlite3_free(zConverted);
52097  OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
52098  return rc;
52099}
52100
52101/*
52102** Check the existence and status of a file.
52103*/
52104static int winAccess(
52105  sqlite3_vfs *pVfs,         /* Not used on win32 */
52106  const char *zFilename,     /* Name of file to check */
52107  int flags,                 /* Type of test to make on this file */
52108  int *pResOut               /* OUT: Result */
52109){
52110  DWORD attr;
52111  int rc = 0;
52112  DWORD lastErrno = 0;
52113  void *zConverted;
52114  UNUSED_PARAMETER(pVfs);
52115
52116  SimulateIOError( return SQLITE_IOERR_ACCESS; );
52117  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
52118           zFilename, flags, pResOut));
52119
52120  if( zFilename==0 ){
52121    *pResOut = 0;
52122    OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
52123             zFilename, pResOut, *pResOut));
52124    return SQLITE_OK;
52125  }
52126
52127  zConverted = winConvertFromUtf8Filename(zFilename);
52128  if( zConverted==0 ){
52129    OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
52130    return SQLITE_IOERR_NOMEM_BKPT;
52131  }
52132  if( osIsNT() ){
52133    int cnt = 0;
52134    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
52135    memset(&sAttrData, 0, sizeof(sAttrData));
52136    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
52137                             GetFileExInfoStandard,
52138                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
52139    if( rc ){
52140      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
52141      ** as if it does not exist.
52142      */
52143      if(    flags==SQLITE_ACCESS_EXISTS
52144          && sAttrData.nFileSizeHigh==0
52145          && sAttrData.nFileSizeLow==0 ){
52146        attr = INVALID_FILE_ATTRIBUTES;
52147      }else{
52148        attr = sAttrData.dwFileAttributes;
52149      }
52150    }else{
52151      winLogIoerr(cnt, __LINE__);
52152      if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
52153        sqlite3_free(zConverted);
52154        return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
52155                           zFilename);
52156      }else{
52157        attr = INVALID_FILE_ATTRIBUTES;
52158      }
52159    }
52160  }
52161#ifdef SQLITE_WIN32_HAS_ANSI
52162  else{
52163    attr = osGetFileAttributesA((char*)zConverted);
52164  }
52165#endif
52166  sqlite3_free(zConverted);
52167  switch( flags ){
52168    case SQLITE_ACCESS_READ:
52169    case SQLITE_ACCESS_EXISTS:
52170      rc = attr!=INVALID_FILE_ATTRIBUTES;
52171      break;
52172    case SQLITE_ACCESS_READWRITE:
52173      rc = attr!=INVALID_FILE_ATTRIBUTES &&
52174             (attr & FILE_ATTRIBUTE_READONLY)==0;
52175      break;
52176    default:
52177      assert(!"Invalid flags argument");
52178  }
52179  *pResOut = rc;
52180  OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
52181           zFilename, pResOut, *pResOut));
52182  return SQLITE_OK;
52183}
52184
52185/*
52186** Returns non-zero if the specified path name starts with the "long path"
52187** prefix.
52188*/
52189static BOOL winIsLongPathPrefix(
52190  const char *zPathname
52191){
52192  return ( zPathname[0]=='\\' && zPathname[1]=='\\'
52193        && zPathname[2]=='?'  && zPathname[3]=='\\' );
52194}
52195
52196/*
52197** Returns non-zero if the specified path name starts with a drive letter
52198** followed by a colon character.
52199*/
52200static BOOL winIsDriveLetterAndColon(
52201  const char *zPathname
52202){
52203  return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
52204}
52205
52206/*
52207** Returns non-zero if the specified path name should be used verbatim.  If
52208** non-zero is returned from this function, the calling function must simply
52209** use the provided path name verbatim -OR- resolve it into a full path name
52210** using the GetFullPathName Win32 API function (if available).
52211*/
52212static BOOL winIsVerbatimPathname(
52213  const char *zPathname
52214){
52215  /*
52216  ** If the path name starts with a forward slash or a backslash, it is either
52217  ** a legal UNC name, a volume relative path, or an absolute path name in the
52218  ** "Unix" format on Windows.  There is no easy way to differentiate between
52219  ** the final two cases; therefore, we return the safer return value of TRUE
52220  ** so that callers of this function will simply use it verbatim.
52221  */
52222  if ( winIsDirSep(zPathname[0]) ){
52223    return TRUE;
52224  }
52225
52226  /*
52227  ** If the path name starts with a letter and a colon it is either a volume
52228  ** relative path or an absolute path.  Callers of this function must not
52229  ** attempt to treat it as a relative path name (i.e. they should simply use
52230  ** it verbatim).
52231  */
52232  if ( winIsDriveLetterAndColon(zPathname) ){
52233    return TRUE;
52234  }
52235
52236  /*
52237  ** If we get to this point, the path name should almost certainly be a purely
52238  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
52239  */
52240  return FALSE;
52241}
52242
52243/*
52244** Turn a relative pathname into a full pathname.  Write the full
52245** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
52246** bytes in size.
52247*/
52248static int winFullPathnameNoMutex(
52249  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
52250  const char *zRelative,        /* Possibly relative input path */
52251  int nFull,                    /* Size of output buffer in bytes */
52252  char *zFull                   /* Output buffer */
52253){
52254#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
52255  DWORD nByte;
52256  void *zConverted;
52257  char *zOut;
52258#endif
52259
52260  /* If this path name begins with "/X:" or "\\?\", where "X" is any
52261  ** alphabetic character, discard the initial "/" from the pathname.
52262  */
52263  if( zRelative[0]=='/' && (winIsDriveLetterAndColon(zRelative+1)
52264       || winIsLongPathPrefix(zRelative+1)) ){
52265    zRelative++;
52266  }
52267
52268#if defined(__CYGWIN__)
52269  SimulateIOError( return SQLITE_ERROR );
52270  UNUSED_PARAMETER(nFull);
52271  assert( nFull>=pVfs->mxPathname );
52272  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
52273    /*
52274    ** NOTE: We are dealing with a relative path name and the data
52275    **       directory has been set.  Therefore, use it as the basis
52276    **       for converting the relative path name to an absolute
52277    **       one by prepending the data directory and a slash.
52278    */
52279    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
52280    if( !zOut ){
52281      return SQLITE_IOERR_NOMEM_BKPT;
52282    }
52283    if( cygwin_conv_path(
52284            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
52285            CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
52286      sqlite3_free(zOut);
52287      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
52288                         "winFullPathname1", zRelative);
52289    }else{
52290      char *zUtf8 = winConvertToUtf8Filename(zOut);
52291      if( !zUtf8 ){
52292        sqlite3_free(zOut);
52293        return SQLITE_IOERR_NOMEM_BKPT;
52294      }
52295      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
52296                       sqlite3_data_directory, winGetDirSep(), zUtf8);
52297      sqlite3_free(zUtf8);
52298      sqlite3_free(zOut);
52299    }
52300  }else{
52301    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
52302    if( !zOut ){
52303      return SQLITE_IOERR_NOMEM_BKPT;
52304    }
52305    if( cygwin_conv_path(
52306            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
52307            zRelative, zOut, pVfs->mxPathname+1)<0 ){
52308      sqlite3_free(zOut);
52309      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
52310                         "winFullPathname2", zRelative);
52311    }else{
52312      char *zUtf8 = winConvertToUtf8Filename(zOut);
52313      if( !zUtf8 ){
52314        sqlite3_free(zOut);
52315        return SQLITE_IOERR_NOMEM_BKPT;
52316      }
52317      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
52318      sqlite3_free(zUtf8);
52319      sqlite3_free(zOut);
52320    }
52321  }
52322  return SQLITE_OK;
52323#endif
52324
52325#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
52326  SimulateIOError( return SQLITE_ERROR );
52327  /* WinCE has no concept of a relative pathname, or so I am told. */
52328  /* WinRT has no way to convert a relative path to an absolute one. */
52329  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
52330    /*
52331    ** NOTE: We are dealing with a relative path name and the data
52332    **       directory has been set.  Therefore, use it as the basis
52333    **       for converting the relative path name to an absolute
52334    **       one by prepending the data directory and a backslash.
52335    */
52336    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
52337                     sqlite3_data_directory, winGetDirSep(), zRelative);
52338  }else{
52339    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
52340  }
52341  return SQLITE_OK;
52342#endif
52343
52344#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
52345  /* It's odd to simulate an io-error here, but really this is just
52346  ** using the io-error infrastructure to test that SQLite handles this
52347  ** function failing. This function could fail if, for example, the
52348  ** current working directory has been unlinked.
52349  */
52350  SimulateIOError( return SQLITE_ERROR );
52351  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
52352    /*
52353    ** NOTE: We are dealing with a relative path name and the data
52354    **       directory has been set.  Therefore, use it as the basis
52355    **       for converting the relative path name to an absolute
52356    **       one by prepending the data directory and a backslash.
52357    */
52358    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
52359                     sqlite3_data_directory, winGetDirSep(), zRelative);
52360    return SQLITE_OK;
52361  }
52362  zConverted = winConvertFromUtf8Filename(zRelative);
52363  if( zConverted==0 ){
52364    return SQLITE_IOERR_NOMEM_BKPT;
52365  }
52366  if( osIsNT() ){
52367    LPWSTR zTemp;
52368    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
52369    if( nByte==0 ){
52370      sqlite3_free(zConverted);
52371      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
52372                         "winFullPathname1", zRelative);
52373    }
52374    nByte += 3;
52375    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
52376    if( zTemp==0 ){
52377      sqlite3_free(zConverted);
52378      return SQLITE_IOERR_NOMEM_BKPT;
52379    }
52380    nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
52381    if( nByte==0 ){
52382      sqlite3_free(zConverted);
52383      sqlite3_free(zTemp);
52384      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
52385                         "winFullPathname2", zRelative);
52386    }
52387    sqlite3_free(zConverted);
52388    zOut = winUnicodeToUtf8(zTemp);
52389    sqlite3_free(zTemp);
52390  }
52391#ifdef SQLITE_WIN32_HAS_ANSI
52392  else{
52393    char *zTemp;
52394    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
52395    if( nByte==0 ){
52396      sqlite3_free(zConverted);
52397      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
52398                         "winFullPathname3", zRelative);
52399    }
52400    nByte += 3;
52401    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
52402    if( zTemp==0 ){
52403      sqlite3_free(zConverted);
52404      return SQLITE_IOERR_NOMEM_BKPT;
52405    }
52406    nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
52407    if( nByte==0 ){
52408      sqlite3_free(zConverted);
52409      sqlite3_free(zTemp);
52410      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
52411                         "winFullPathname4", zRelative);
52412    }
52413    sqlite3_free(zConverted);
52414    zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
52415    sqlite3_free(zTemp);
52416  }
52417#endif
52418  if( zOut ){
52419    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
52420    sqlite3_free(zOut);
52421    return SQLITE_OK;
52422  }else{
52423    return SQLITE_IOERR_NOMEM_BKPT;
52424  }
52425#endif
52426}
52427static int winFullPathname(
52428  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
52429  const char *zRelative,        /* Possibly relative input path */
52430  int nFull,                    /* Size of output buffer in bytes */
52431  char *zFull                   /* Output buffer */
52432){
52433  int rc;
52434  MUTEX_LOGIC( sqlite3_mutex *pMutex; )
52435  MUTEX_LOGIC( pMutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR); )
52436  sqlite3_mutex_enter(pMutex);
52437  rc = winFullPathnameNoMutex(pVfs, zRelative, nFull, zFull);
52438  sqlite3_mutex_leave(pMutex);
52439  return rc;
52440}
52441
52442#ifndef SQLITE_OMIT_LOAD_EXTENSION
52443/*
52444** Interfaces for opening a shared library, finding entry points
52445** within the shared library, and closing the shared library.
52446*/
52447static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
52448  HANDLE h;
52449#if defined(__CYGWIN__)
52450  int nFull = pVfs->mxPathname+1;
52451  char *zFull = sqlite3MallocZero( nFull );
52452  void *zConverted = 0;
52453  if( zFull==0 ){
52454    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
52455    return 0;
52456  }
52457  if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
52458    sqlite3_free(zFull);
52459    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
52460    return 0;
52461  }
52462  zConverted = winConvertFromUtf8Filename(zFull);
52463  sqlite3_free(zFull);
52464#else
52465  void *zConverted = winConvertFromUtf8Filename(zFilename);
52466  UNUSED_PARAMETER(pVfs);
52467#endif
52468  if( zConverted==0 ){
52469    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
52470    return 0;
52471  }
52472  if( osIsNT() ){
52473#if SQLITE_OS_WINRT
52474    h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
52475#else
52476    h = osLoadLibraryW((LPCWSTR)zConverted);
52477#endif
52478  }
52479#ifdef SQLITE_WIN32_HAS_ANSI
52480  else{
52481    h = osLoadLibraryA((char*)zConverted);
52482  }
52483#endif
52484  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
52485  sqlite3_free(zConverted);
52486  return (void*)h;
52487}
52488static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
52489  UNUSED_PARAMETER(pVfs);
52490  winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
52491}
52492static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
52493  FARPROC proc;
52494  UNUSED_PARAMETER(pVfs);
52495  proc = osGetProcAddressA((HANDLE)pH, zSym);
52496  OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
52497           (void*)pH, zSym, (void*)proc));
52498  return (void(*)(void))proc;
52499}
52500static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
52501  UNUSED_PARAMETER(pVfs);
52502  osFreeLibrary((HANDLE)pHandle);
52503  OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
52504}
52505#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
52506  #define winDlOpen  0
52507  #define winDlError 0
52508  #define winDlSym   0
52509  #define winDlClose 0
52510#endif
52511
52512/* State information for the randomness gatherer. */
52513typedef struct EntropyGatherer EntropyGatherer;
52514struct EntropyGatherer {
52515  unsigned char *a;   /* Gather entropy into this buffer */
52516  int na;             /* Size of a[] in bytes */
52517  int i;              /* XOR next input into a[i] */
52518  int nXor;           /* Number of XOR operations done */
52519};
52520
52521#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
52522/* Mix sz bytes of entropy into p. */
52523static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
52524  int j, k;
52525  for(j=0, k=p->i; j<sz; j++){
52526    p->a[k++] ^= x[j];
52527    if( k>=p->na ) k = 0;
52528  }
52529  p->i = k;
52530  p->nXor += sz;
52531}
52532#endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
52533
52534/*
52535** Write up to nBuf bytes of randomness into zBuf.
52536*/
52537static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
52538#if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
52539  UNUSED_PARAMETER(pVfs);
52540  memset(zBuf, 0, nBuf);
52541  return nBuf;
52542#else
52543  EntropyGatherer e;
52544  UNUSED_PARAMETER(pVfs);
52545  memset(zBuf, 0, nBuf);
52546  e.a = (unsigned char*)zBuf;
52547  e.na = nBuf;
52548  e.nXor = 0;
52549  e.i = 0;
52550  {
52551    SYSTEMTIME x;
52552    osGetSystemTime(&x);
52553    xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
52554  }
52555  {
52556    DWORD pid = osGetCurrentProcessId();
52557    xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
52558  }
52559#if SQLITE_OS_WINRT
52560  {
52561    ULONGLONG cnt = osGetTickCount64();
52562    xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
52563  }
52564#else
52565  {
52566    DWORD cnt = osGetTickCount();
52567    xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
52568  }
52569#endif /* SQLITE_OS_WINRT */
52570  {
52571    LARGE_INTEGER i;
52572    osQueryPerformanceCounter(&i);
52573    xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
52574  }
52575#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
52576  {
52577    UUID id;
52578    memset(&id, 0, sizeof(UUID));
52579    osUuidCreate(&id);
52580    xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
52581    memset(&id, 0, sizeof(UUID));
52582    osUuidCreateSequential(&id);
52583    xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
52584  }
52585#endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
52586  return e.nXor>nBuf ? nBuf : e.nXor;
52587#endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
52588}
52589
52590
52591/*
52592** Sleep for a little while.  Return the amount of time slept.
52593*/
52594static int winSleep(sqlite3_vfs *pVfs, int microsec){
52595  sqlite3_win32_sleep((microsec+999)/1000);
52596  UNUSED_PARAMETER(pVfs);
52597  return ((microsec+999)/1000)*1000;
52598}
52599
52600/*
52601** The following variable, if set to a non-zero value, is interpreted as
52602** the number of seconds since 1970 and is used to set the result of
52603** sqlite3OsCurrentTime() during testing.
52604*/
52605#ifdef SQLITE_TEST
52606SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
52607#endif
52608
52609/*
52610** Find the current time (in Universal Coordinated Time).  Write into *piNow
52611** the current time and date as a Julian Day number times 86_400_000.  In
52612** other words, write into *piNow the number of milliseconds since the Julian
52613** epoch of noon in Greenwich on November 24, 4714 B.C according to the
52614** proleptic Gregorian calendar.
52615**
52616** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
52617** cannot be found.
52618*/
52619static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
52620  /* FILETIME structure is a 64-bit value representing the number of
52621     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
52622  */
52623  FILETIME ft;
52624  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
52625#ifdef SQLITE_TEST
52626  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
52627#endif
52628  /* 2^32 - to avoid use of LL and warnings in gcc */
52629  static const sqlite3_int64 max32BitValue =
52630      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
52631      (sqlite3_int64)294967296;
52632
52633#if SQLITE_OS_WINCE
52634  SYSTEMTIME time;
52635  osGetSystemTime(&time);
52636  /* if SystemTimeToFileTime() fails, it returns zero. */
52637  if (!osSystemTimeToFileTime(&time,&ft)){
52638    return SQLITE_ERROR;
52639  }
52640#else
52641  osGetSystemTimeAsFileTime( &ft );
52642#endif
52643
52644  *piNow = winFiletimeEpoch +
52645            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
52646               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
52647
52648#ifdef SQLITE_TEST
52649  if( sqlite3_current_time ){
52650    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
52651  }
52652#endif
52653  UNUSED_PARAMETER(pVfs);
52654  return SQLITE_OK;
52655}
52656
52657/*
52658** Find the current time (in Universal Coordinated Time).  Write the
52659** current time and date as a Julian Day number into *prNow and
52660** return 0.  Return 1 if the time and date cannot be found.
52661*/
52662static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
52663  int rc;
52664  sqlite3_int64 i;
52665  rc = winCurrentTimeInt64(pVfs, &i);
52666  if( !rc ){
52667    *prNow = i/86400000.0;
52668  }
52669  return rc;
52670}
52671
52672/*
52673** The idea is that this function works like a combination of
52674** GetLastError() and FormatMessage() on Windows (or errno and
52675** strerror_r() on Unix). After an error is returned by an OS
52676** function, SQLite calls this function with zBuf pointing to
52677** a buffer of nBuf bytes. The OS layer should populate the
52678** buffer with a nul-terminated UTF-8 encoded error message
52679** describing the last IO error to have occurred within the calling
52680** thread.
52681**
52682** If the error message is too large for the supplied buffer,
52683** it should be truncated. The return value of xGetLastError
52684** is zero if the error message fits in the buffer, or non-zero
52685** otherwise (if the message was truncated). If non-zero is returned,
52686** then it is not necessary to include the nul-terminator character
52687** in the output buffer.
52688**
52689** Not supplying an error message will have no adverse effect
52690** on SQLite. It is fine to have an implementation that never
52691** returns an error message:
52692**
52693**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
52694**     assert(zBuf[0]=='\0');
52695**     return 0;
52696**   }
52697**
52698** However if an error message is supplied, it will be incorporated
52699** by sqlite into the error message available to the user using
52700** sqlite3_errmsg(), possibly making IO errors easier to debug.
52701*/
52702static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
52703  DWORD e = osGetLastError();
52704  UNUSED_PARAMETER(pVfs);
52705  if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
52706  return e;
52707}
52708
52709/*
52710** Initialize and deinitialize the operating system interface.
52711*/
52712SQLITE_API int sqlite3_os_init(void){
52713  static sqlite3_vfs winVfs = {
52714    3,                     /* iVersion */
52715    sizeof(winFile),       /* szOsFile */
52716    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
52717    0,                     /* pNext */
52718    "win32",               /* zName */
52719    &winAppData,           /* pAppData */
52720    winOpen,               /* xOpen */
52721    winDelete,             /* xDelete */
52722    winAccess,             /* xAccess */
52723    winFullPathname,       /* xFullPathname */
52724    winDlOpen,             /* xDlOpen */
52725    winDlError,            /* xDlError */
52726    winDlSym,              /* xDlSym */
52727    winDlClose,            /* xDlClose */
52728    winRandomness,         /* xRandomness */
52729    winSleep,              /* xSleep */
52730    winCurrentTime,        /* xCurrentTime */
52731    winGetLastError,       /* xGetLastError */
52732    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
52733    winSetSystemCall,      /* xSetSystemCall */
52734    winGetSystemCall,      /* xGetSystemCall */
52735    winNextSystemCall,     /* xNextSystemCall */
52736  };
52737#if defined(SQLITE_WIN32_HAS_WIDE)
52738  static sqlite3_vfs winLongPathVfs = {
52739    3,                     /* iVersion */
52740    sizeof(winFile),       /* szOsFile */
52741    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
52742    0,                     /* pNext */
52743    "win32-longpath",      /* zName */
52744    &winAppData,           /* pAppData */
52745    winOpen,               /* xOpen */
52746    winDelete,             /* xDelete */
52747    winAccess,             /* xAccess */
52748    winFullPathname,       /* xFullPathname */
52749    winDlOpen,             /* xDlOpen */
52750    winDlError,            /* xDlError */
52751    winDlSym,              /* xDlSym */
52752    winDlClose,            /* xDlClose */
52753    winRandomness,         /* xRandomness */
52754    winSleep,              /* xSleep */
52755    winCurrentTime,        /* xCurrentTime */
52756    winGetLastError,       /* xGetLastError */
52757    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
52758    winSetSystemCall,      /* xSetSystemCall */
52759    winGetSystemCall,      /* xGetSystemCall */
52760    winNextSystemCall,     /* xNextSystemCall */
52761  };
52762#endif
52763  static sqlite3_vfs winNolockVfs = {
52764    3,                     /* iVersion */
52765    sizeof(winFile),       /* szOsFile */
52766    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
52767    0,                     /* pNext */
52768    "win32-none",          /* zName */
52769    &winNolockAppData,     /* pAppData */
52770    winOpen,               /* xOpen */
52771    winDelete,             /* xDelete */
52772    winAccess,             /* xAccess */
52773    winFullPathname,       /* xFullPathname */
52774    winDlOpen,             /* xDlOpen */
52775    winDlError,            /* xDlError */
52776    winDlSym,              /* xDlSym */
52777    winDlClose,            /* xDlClose */
52778    winRandomness,         /* xRandomness */
52779    winSleep,              /* xSleep */
52780    winCurrentTime,        /* xCurrentTime */
52781    winGetLastError,       /* xGetLastError */
52782    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
52783    winSetSystemCall,      /* xSetSystemCall */
52784    winGetSystemCall,      /* xGetSystemCall */
52785    winNextSystemCall,     /* xNextSystemCall */
52786  };
52787#if defined(SQLITE_WIN32_HAS_WIDE)
52788  static sqlite3_vfs winLongPathNolockVfs = {
52789    3,                     /* iVersion */
52790    sizeof(winFile),       /* szOsFile */
52791    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
52792    0,                     /* pNext */
52793    "win32-longpath-none", /* zName */
52794    &winNolockAppData,     /* pAppData */
52795    winOpen,               /* xOpen */
52796    winDelete,             /* xDelete */
52797    winAccess,             /* xAccess */
52798    winFullPathname,       /* xFullPathname */
52799    winDlOpen,             /* xDlOpen */
52800    winDlError,            /* xDlError */
52801    winDlSym,              /* xDlSym */
52802    winDlClose,            /* xDlClose */
52803    winRandomness,         /* xRandomness */
52804    winSleep,              /* xSleep */
52805    winCurrentTime,        /* xCurrentTime */
52806    winGetLastError,       /* xGetLastError */
52807    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
52808    winSetSystemCall,      /* xSetSystemCall */
52809    winGetSystemCall,      /* xGetSystemCall */
52810    winNextSystemCall,     /* xNextSystemCall */
52811  };
52812#endif
52813
52814  /* Double-check that the aSyscall[] array has been constructed
52815  ** correctly.  See ticket [bb3a86e890c8e96ab] */
52816  assert( ArraySize(aSyscall)==80 );
52817
52818  /* get memory map allocation granularity */
52819  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
52820#if SQLITE_OS_WINRT
52821  osGetNativeSystemInfo(&winSysInfo);
52822#else
52823  osGetSystemInfo(&winSysInfo);
52824#endif
52825  assert( winSysInfo.dwAllocationGranularity>0 );
52826  assert( winSysInfo.dwPageSize>0 );
52827
52828  sqlite3_vfs_register(&winVfs, 1);
52829
52830#if defined(SQLITE_WIN32_HAS_WIDE)
52831  sqlite3_vfs_register(&winLongPathVfs, 0);
52832#endif
52833
52834  sqlite3_vfs_register(&winNolockVfs, 0);
52835
52836#if defined(SQLITE_WIN32_HAS_WIDE)
52837  sqlite3_vfs_register(&winLongPathNolockVfs, 0);
52838#endif
52839
52840#ifndef SQLITE_OMIT_WAL
52841  winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
52842#endif
52843
52844  return SQLITE_OK;
52845}
52846
52847SQLITE_API int sqlite3_os_end(void){
52848#if SQLITE_OS_WINRT
52849  if( sleepObj!=NULL ){
52850    osCloseHandle(sleepObj);
52851    sleepObj = NULL;
52852  }
52853#endif
52854
52855#ifndef SQLITE_OMIT_WAL
52856  winBigLock = 0;
52857#endif
52858
52859  return SQLITE_OK;
52860}
52861
52862#endif /* SQLITE_OS_WIN */
52863
52864/************** End of os_win.c **********************************************/
52865/************** Begin file memdb.c *******************************************/
52866/*
52867** 2016-09-07
52868**
52869** The author disclaims copyright to this source code.  In place of
52870** a legal notice, here is a blessing:
52871**
52872**    May you do good and not evil.
52873**    May you find forgiveness for yourself and forgive others.
52874**    May you share freely, never taking more than you give.
52875**
52876******************************************************************************
52877**
52878** This file implements an in-memory VFS. A database is held as a contiguous
52879** block of memory.
52880**
52881** This file also implements interface sqlite3_serialize() and
52882** sqlite3_deserialize().
52883*/
52884/* #include "sqliteInt.h" */
52885#ifndef SQLITE_OMIT_DESERIALIZE
52886
52887/*
52888** Forward declaration of objects used by this utility
52889*/
52890typedef struct sqlite3_vfs MemVfs;
52891typedef struct MemFile MemFile;
52892typedef struct MemStore MemStore;
52893
52894/* Access to a lower-level VFS that (might) implement dynamic loading,
52895** access to randomness, etc.
52896*/
52897#define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
52898
52899/* Storage for a memdb file.
52900**
52901** An memdb object can be shared or separate.  Shared memdb objects can be
52902** used by more than one database connection.  Mutexes are used by shared
52903** memdb objects to coordinate access.  Separate memdb objects are only
52904** connected to a single database connection and do not require additional
52905** mutexes.
52906**
52907** Shared memdb objects have .zFName!=0 and .pMutex!=0.  They are created
52908** using "file:/name?vfs=memdb".  The first character of the name must be
52909** "/" or else the object will be a separate memdb object.  All shared
52910** memdb objects are stored in memdb_g.apMemStore[] in an arbitrary order.
52911**
52912** Separate memdb objects are created using a name that does not begin
52913** with "/" or using sqlite3_deserialize().
52914**
52915** Access rules for shared MemStore objects:
52916**
52917**   *  .zFName is initialized when the object is created and afterwards
52918**      is unchanged until the object is destroyed.  So it can be accessed
52919**      at any time as long as we know the object is not being destroyed,
52920**      which means while either the SQLITE_MUTEX_STATIC_VFS1 or
52921**      .pMutex is held or the object is not part of memdb_g.apMemStore[].
52922**
52923**   *  Can .pMutex can only be changed while holding the
52924**      SQLITE_MUTEX_STATIC_VFS1 mutex or while the object is not part
52925**      of memdb_g.apMemStore[].
52926**
52927**   *  Other fields can only be changed while holding the .pMutex mutex
52928**      or when the .nRef is less than zero and the object is not part of
52929**      memdb_g.apMemStore[].
52930**
52931**   *  The .aData pointer has the added requirement that it can can only
52932**      be changed (for resizing) when nMmap is zero.
52933**
52934*/
52935struct MemStore {
52936  sqlite3_int64 sz;               /* Size of the file */
52937  sqlite3_int64 szAlloc;          /* Space allocated to aData */
52938  sqlite3_int64 szMax;            /* Maximum allowed size of the file */
52939  unsigned char *aData;           /* content of the file */
52940  sqlite3_mutex *pMutex;          /* Used by shared stores only */
52941  int nMmap;                      /* Number of memory mapped pages */
52942  unsigned mFlags;                /* Flags */
52943  int nRdLock;                    /* Number of readers */
52944  int nWrLock;                    /* Number of writers.  (Always 0 or 1) */
52945  int nRef;                       /* Number of users of this MemStore */
52946  char *zFName;                   /* The filename for shared stores */
52947};
52948
52949/* An open file */
52950struct MemFile {
52951  sqlite3_file base;              /* IO methods */
52952  MemStore *pStore;               /* The storage */
52953  int eLock;                      /* Most recent lock against this file */
52954};
52955
52956/*
52957** File-scope variables for holding the memdb files that are accessible
52958** to multiple database connections in separate threads.
52959**
52960** Must hold SQLITE_MUTEX_STATIC_VFS1 to access any part of this object.
52961*/
52962static struct MemFS {
52963  int nMemStore;                  /* Number of shared MemStore objects */
52964  MemStore **apMemStore;          /* Array of all shared MemStore objects */
52965} memdb_g;
52966
52967/*
52968** Methods for MemFile
52969*/
52970static int memdbClose(sqlite3_file*);
52971static int memdbRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
52972static int memdbWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
52973static int memdbTruncate(sqlite3_file*, sqlite3_int64 size);
52974static int memdbSync(sqlite3_file*, int flags);
52975static int memdbFileSize(sqlite3_file*, sqlite3_int64 *pSize);
52976static int memdbLock(sqlite3_file*, int);
52977static int memdbUnlock(sqlite3_file*, int);
52978/* static int memdbCheckReservedLock(sqlite3_file*, int *pResOut);// not used */
52979static int memdbFileControl(sqlite3_file*, int op, void *pArg);
52980/* static int memdbSectorSize(sqlite3_file*); // not used */
52981static int memdbDeviceCharacteristics(sqlite3_file*);
52982static int memdbFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
52983static int memdbUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
52984
52985/*
52986** Methods for MemVfs
52987*/
52988static int memdbOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
52989/* static int memdbDelete(sqlite3_vfs*, const char *zName, int syncDir); */
52990static int memdbAccess(sqlite3_vfs*, const char *zName, int flags, int *);
52991static int memdbFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
52992static void *memdbDlOpen(sqlite3_vfs*, const char *zFilename);
52993static void memdbDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
52994static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
52995static void memdbDlClose(sqlite3_vfs*, void*);
52996static int memdbRandomness(sqlite3_vfs*, int nByte, char *zOut);
52997static int memdbSleep(sqlite3_vfs*, int microseconds);
52998/* static int memdbCurrentTime(sqlite3_vfs*, double*); */
52999static int memdbGetLastError(sqlite3_vfs*, int, char *);
53000static int memdbCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
53001
53002static sqlite3_vfs memdb_vfs = {
53003  2,                           /* iVersion */
53004  0,                           /* szOsFile (set when registered) */
53005  1024,                        /* mxPathname */
53006  0,                           /* pNext */
53007  "memdb",                     /* zName */
53008  0,                           /* pAppData (set when registered) */
53009  memdbOpen,                   /* xOpen */
53010  0, /* memdbDelete, */        /* xDelete */
53011  memdbAccess,                 /* xAccess */
53012  memdbFullPathname,           /* xFullPathname */
53013  memdbDlOpen,                 /* xDlOpen */
53014  memdbDlError,                /* xDlError */
53015  memdbDlSym,                  /* xDlSym */
53016  memdbDlClose,                /* xDlClose */
53017  memdbRandomness,             /* xRandomness */
53018  memdbSleep,                  /* xSleep */
53019  0, /* memdbCurrentTime, */   /* xCurrentTime */
53020  memdbGetLastError,           /* xGetLastError */
53021  memdbCurrentTimeInt64,       /* xCurrentTimeInt64 */
53022  0,                           /* xSetSystemCall */
53023  0,                           /* xGetSystemCall */
53024  0,                           /* xNextSystemCall */
53025};
53026
53027static const sqlite3_io_methods memdb_io_methods = {
53028  3,                              /* iVersion */
53029  memdbClose,                      /* xClose */
53030  memdbRead,                       /* xRead */
53031  memdbWrite,                      /* xWrite */
53032  memdbTruncate,                   /* xTruncate */
53033  memdbSync,                       /* xSync */
53034  memdbFileSize,                   /* xFileSize */
53035  memdbLock,                       /* xLock */
53036  memdbUnlock,                     /* xUnlock */
53037  0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */
53038  memdbFileControl,                /* xFileControl */
53039  0, /* memdbSectorSize,*/         /* xSectorSize */
53040  memdbDeviceCharacteristics,      /* xDeviceCharacteristics */
53041  0,                               /* xShmMap */
53042  0,                               /* xShmLock */
53043  0,                               /* xShmBarrier */
53044  0,                               /* xShmUnmap */
53045  memdbFetch,                      /* xFetch */
53046  memdbUnfetch                     /* xUnfetch */
53047};
53048
53049/*
53050** Enter/leave the mutex on a MemStore
53051*/
53052#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
53053static void memdbEnter(MemStore *p){
53054  UNUSED_PARAMETER(p);
53055}
53056static void memdbLeave(MemStore *p){
53057  UNUSED_PARAMETER(p);
53058}
53059#else
53060static void memdbEnter(MemStore *p){
53061  sqlite3_mutex_enter(p->pMutex);
53062}
53063static void memdbLeave(MemStore *p){
53064  sqlite3_mutex_leave(p->pMutex);
53065}
53066#endif
53067
53068
53069
53070/*
53071** Close an memdb-file.
53072** Free the underlying MemStore object when its refcount drops to zero
53073** or less.
53074*/
53075static int memdbClose(sqlite3_file *pFile){
53076  MemStore *p = ((MemFile*)pFile)->pStore;
53077  if( p->zFName ){
53078    int i;
53079#ifndef SQLITE_MUTEX_OMIT
53080    sqlite3_mutex *pVfsMutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
53081#endif
53082    sqlite3_mutex_enter(pVfsMutex);
53083    for(i=0; ALWAYS(i<memdb_g.nMemStore); i++){
53084      if( memdb_g.apMemStore[i]==p ){
53085        memdbEnter(p);
53086        if( p->nRef==1 ){
53087          memdb_g.apMemStore[i] = memdb_g.apMemStore[--memdb_g.nMemStore];
53088          if( memdb_g.nMemStore==0 ){
53089            sqlite3_free(memdb_g.apMemStore);
53090            memdb_g.apMemStore = 0;
53091          }
53092        }
53093        break;
53094      }
53095    }
53096    sqlite3_mutex_leave(pVfsMutex);
53097  }else{
53098    memdbEnter(p);
53099  }
53100  p->nRef--;
53101  if( p->nRef<=0 ){
53102    if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ){
53103      sqlite3_free(p->aData);
53104    }
53105    memdbLeave(p);
53106    sqlite3_mutex_free(p->pMutex);
53107    sqlite3_free(p);
53108  }else{
53109    memdbLeave(p);
53110  }
53111  return SQLITE_OK;
53112}
53113
53114/*
53115** Read data from an memdb-file.
53116*/
53117static int memdbRead(
53118  sqlite3_file *pFile,
53119  void *zBuf,
53120  int iAmt,
53121  sqlite_int64 iOfst
53122){
53123  MemStore *p = ((MemFile*)pFile)->pStore;
53124  memdbEnter(p);
53125  if( iOfst+iAmt>p->sz ){
53126    memset(zBuf, 0, iAmt);
53127    if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);
53128    memdbLeave(p);
53129    return SQLITE_IOERR_SHORT_READ;
53130  }
53131  memcpy(zBuf, p->aData+iOfst, iAmt);
53132  memdbLeave(p);
53133  return SQLITE_OK;
53134}
53135
53136/*
53137** Try to enlarge the memory allocation to hold at least sz bytes
53138*/
53139static int memdbEnlarge(MemStore *p, sqlite3_int64 newSz){
53140  unsigned char *pNew;
53141  if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || NEVER(p->nMmap>0) ){
53142    return SQLITE_FULL;
53143  }
53144  if( newSz>p->szMax ){
53145    return SQLITE_FULL;
53146  }
53147  newSz *= 2;
53148  if( newSz>p->szMax ) newSz = p->szMax;
53149  pNew = sqlite3Realloc(p->aData, newSz);
53150  if( pNew==0 ) return SQLITE_IOERR_NOMEM;
53151  p->aData = pNew;
53152  p->szAlloc = newSz;
53153  return SQLITE_OK;
53154}
53155
53156/*
53157** Write data to an memdb-file.
53158*/
53159static int memdbWrite(
53160  sqlite3_file *pFile,
53161  const void *z,
53162  int iAmt,
53163  sqlite_int64 iOfst
53164){
53165  MemStore *p = ((MemFile*)pFile)->pStore;
53166  memdbEnter(p);
53167  if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY) ){
53168    /* Can't happen: memdbLock() will return SQLITE_READONLY before
53169    ** reaching this point */
53170    memdbLeave(p);
53171    return SQLITE_IOERR_WRITE;
53172  }
53173  if( iOfst+iAmt>p->sz ){
53174    int rc;
53175    if( iOfst+iAmt>p->szAlloc
53176     && (rc = memdbEnlarge(p, iOfst+iAmt))!=SQLITE_OK
53177    ){
53178      memdbLeave(p);
53179      return rc;
53180    }
53181    if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);
53182    p->sz = iOfst+iAmt;
53183  }
53184  memcpy(p->aData+iOfst, z, iAmt);
53185  memdbLeave(p);
53186  return SQLITE_OK;
53187}
53188
53189/*
53190** Truncate an memdb-file.
53191**
53192** In rollback mode (which is always the case for memdb, as it does not
53193** support WAL mode) the truncate() method is only used to reduce
53194** the size of a file, never to increase the size.
53195*/
53196static int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){
53197  MemStore *p = ((MemFile*)pFile)->pStore;
53198  int rc = SQLITE_OK;
53199  memdbEnter(p);
53200  if( size>p->sz ){
53201    /* This can only happen with a corrupt wal mode db */
53202    rc = SQLITE_CORRUPT;
53203  }else{
53204    p->sz = size;
53205  }
53206  memdbLeave(p);
53207  return rc;
53208}
53209
53210/*
53211** Sync an memdb-file.
53212*/
53213static int memdbSync(sqlite3_file *pFile, int flags){
53214  UNUSED_PARAMETER(pFile);
53215  UNUSED_PARAMETER(flags);
53216  return SQLITE_OK;
53217}
53218
53219/*
53220** Return the current file-size of an memdb-file.
53221*/
53222static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
53223  MemStore *p = ((MemFile*)pFile)->pStore;
53224  memdbEnter(p);
53225  *pSize = p->sz;
53226  memdbLeave(p);
53227  return SQLITE_OK;
53228}
53229
53230/*
53231** Lock an memdb-file.
53232*/
53233static int memdbLock(sqlite3_file *pFile, int eLock){
53234  MemFile *pThis = (MemFile*)pFile;
53235  MemStore *p = pThis->pStore;
53236  int rc = SQLITE_OK;
53237  if( eLock<=pThis->eLock ) return SQLITE_OK;
53238  memdbEnter(p);
53239
53240  assert( p->nWrLock==0 || p->nWrLock==1 );
53241  assert( pThis->eLock<=SQLITE_LOCK_SHARED || p->nWrLock==1 );
53242  assert( pThis->eLock==SQLITE_LOCK_NONE || p->nRdLock>=1 );
53243
53244  if( eLock>SQLITE_LOCK_SHARED && (p->mFlags & SQLITE_DESERIALIZE_READONLY) ){
53245    rc = SQLITE_READONLY;
53246  }else{
53247    switch( eLock ){
53248      case SQLITE_LOCK_SHARED: {
53249        assert( pThis->eLock==SQLITE_LOCK_NONE );
53250        if( p->nWrLock>0 ){
53251          rc = SQLITE_BUSY;
53252        }else{
53253          p->nRdLock++;
53254        }
53255        break;
53256      };
53257
53258      case SQLITE_LOCK_RESERVED:
53259      case SQLITE_LOCK_PENDING: {
53260        assert( pThis->eLock>=SQLITE_LOCK_SHARED );
53261        if( ALWAYS(pThis->eLock==SQLITE_LOCK_SHARED) ){
53262          if( p->nWrLock>0 ){
53263            rc = SQLITE_BUSY;
53264          }else{
53265            p->nWrLock = 1;
53266          }
53267        }
53268        break;
53269      }
53270
53271      default: {
53272        assert(  eLock==SQLITE_LOCK_EXCLUSIVE );
53273        assert( pThis->eLock>=SQLITE_LOCK_SHARED );
53274        if( p->nRdLock>1 ){
53275          rc = SQLITE_BUSY;
53276        }else if( pThis->eLock==SQLITE_LOCK_SHARED ){
53277          p->nWrLock = 1;
53278        }
53279        break;
53280      }
53281    }
53282  }
53283  if( rc==SQLITE_OK ) pThis->eLock = eLock;
53284  memdbLeave(p);
53285  return rc;
53286}
53287
53288/*
53289** Unlock an memdb-file.
53290*/
53291static int memdbUnlock(sqlite3_file *pFile, int eLock){
53292  MemFile *pThis = (MemFile*)pFile;
53293  MemStore *p = pThis->pStore;
53294  if( eLock>=pThis->eLock ) return SQLITE_OK;
53295  memdbEnter(p);
53296
53297  assert( eLock==SQLITE_LOCK_SHARED || eLock==SQLITE_LOCK_NONE );
53298  if( eLock==SQLITE_LOCK_SHARED ){
53299    if( ALWAYS(pThis->eLock>SQLITE_LOCK_SHARED) ){
53300      p->nWrLock--;
53301    }
53302  }else{
53303    if( pThis->eLock>SQLITE_LOCK_SHARED ){
53304      p->nWrLock--;
53305    }
53306    p->nRdLock--;
53307  }
53308
53309  pThis->eLock = eLock;
53310  memdbLeave(p);
53311  return SQLITE_OK;
53312}
53313
53314#if 0
53315/*
53316** This interface is only used for crash recovery, which does not
53317** occur on an in-memory database.
53318*/
53319static int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){
53320  *pResOut = 0;
53321  return SQLITE_OK;
53322}
53323#endif
53324
53325
53326/*
53327** File control method. For custom operations on an memdb-file.
53328*/
53329static int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){
53330  MemStore *p = ((MemFile*)pFile)->pStore;
53331  int rc = SQLITE_NOTFOUND;
53332  memdbEnter(p);
53333  if( op==SQLITE_FCNTL_VFSNAME ){
53334    *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz);
53335    rc = SQLITE_OK;
53336  }
53337  if( op==SQLITE_FCNTL_SIZE_LIMIT ){
53338    sqlite3_int64 iLimit = *(sqlite3_int64*)pArg;
53339    if( iLimit<p->sz ){
53340      if( iLimit<0 ){
53341        iLimit = p->szMax;
53342      }else{
53343        iLimit = p->sz;
53344      }
53345    }
53346    p->szMax = iLimit;
53347    *(sqlite3_int64*)pArg = iLimit;
53348    rc = SQLITE_OK;
53349  }
53350  memdbLeave(p);
53351  return rc;
53352}
53353
53354#if 0  /* Not used because of SQLITE_IOCAP_POWERSAFE_OVERWRITE */
53355/*
53356** Return the sector-size in bytes for an memdb-file.
53357*/
53358static int memdbSectorSize(sqlite3_file *pFile){
53359  return 1024;
53360}
53361#endif
53362
53363/*
53364** Return the device characteristic flags supported by an memdb-file.
53365*/
53366static int memdbDeviceCharacteristics(sqlite3_file *pFile){
53367  UNUSED_PARAMETER(pFile);
53368  return SQLITE_IOCAP_ATOMIC |
53369         SQLITE_IOCAP_POWERSAFE_OVERWRITE |
53370         SQLITE_IOCAP_SAFE_APPEND |
53371         SQLITE_IOCAP_SEQUENTIAL;
53372}
53373
53374/* Fetch a page of a memory-mapped file */
53375static int memdbFetch(
53376  sqlite3_file *pFile,
53377  sqlite3_int64 iOfst,
53378  int iAmt,
53379  void **pp
53380){
53381  MemStore *p = ((MemFile*)pFile)->pStore;
53382  memdbEnter(p);
53383  if( iOfst+iAmt>p->sz || (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)!=0 ){
53384    *pp = 0;
53385  }else{
53386    p->nMmap++;
53387    *pp = (void*)(p->aData + iOfst);
53388  }
53389  memdbLeave(p);
53390  return SQLITE_OK;
53391}
53392
53393/* Release a memory-mapped page */
53394static int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
53395  MemStore *p = ((MemFile*)pFile)->pStore;
53396  UNUSED_PARAMETER(iOfst);
53397  UNUSED_PARAMETER(pPage);
53398  memdbEnter(p);
53399  p->nMmap--;
53400  memdbLeave(p);
53401  return SQLITE_OK;
53402}
53403
53404/*
53405** Open an mem file handle.
53406*/
53407static int memdbOpen(
53408  sqlite3_vfs *pVfs,
53409  const char *zName,
53410  sqlite3_file *pFd,
53411  int flags,
53412  int *pOutFlags
53413){
53414  MemFile *pFile = (MemFile*)pFd;
53415  MemStore *p = 0;
53416  int szName;
53417  UNUSED_PARAMETER(pVfs);
53418
53419  memset(pFile, 0, sizeof(*pFile));
53420  szName = sqlite3Strlen30(zName);
53421  if( szName>1 && (zName[0]=='/' || zName[0]=='\\') ){
53422    int i;
53423#ifndef SQLITE_MUTEX_OMIT
53424    sqlite3_mutex *pVfsMutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
53425#endif
53426    sqlite3_mutex_enter(pVfsMutex);
53427    for(i=0; i<memdb_g.nMemStore; i++){
53428      if( strcmp(memdb_g.apMemStore[i]->zFName,zName)==0 ){
53429        p = memdb_g.apMemStore[i];
53430        break;
53431      }
53432    }
53433    if( p==0 ){
53434      MemStore **apNew;
53435      p = sqlite3Malloc( sizeof(*p) + szName + 3 );
53436      if( p==0 ){
53437        sqlite3_mutex_leave(pVfsMutex);
53438        return SQLITE_NOMEM;
53439      }
53440      apNew = sqlite3Realloc(memdb_g.apMemStore,
53441                             sizeof(apNew[0])*(memdb_g.nMemStore+1) );
53442      if( apNew==0 ){
53443        sqlite3_free(p);
53444        sqlite3_mutex_leave(pVfsMutex);
53445        return SQLITE_NOMEM;
53446      }
53447      apNew[memdb_g.nMemStore++] = p;
53448      memdb_g.apMemStore = apNew;
53449      memset(p, 0, sizeof(*p));
53450      p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE|SQLITE_DESERIALIZE_FREEONCLOSE;
53451      p->szMax = sqlite3GlobalConfig.mxMemdbSize;
53452      p->zFName = (char*)&p[1];
53453      memcpy(p->zFName, zName, szName+1);
53454      p->pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
53455      if( p->pMutex==0 ){
53456        memdb_g.nMemStore--;
53457        sqlite3_free(p);
53458        sqlite3_mutex_leave(pVfsMutex);
53459        return SQLITE_NOMEM;
53460      }
53461      p->nRef = 1;
53462      memdbEnter(p);
53463    }else{
53464      memdbEnter(p);
53465      p->nRef++;
53466    }
53467    sqlite3_mutex_leave(pVfsMutex);
53468  }else{
53469    p = sqlite3Malloc( sizeof(*p) );
53470    if( p==0 ){
53471      return SQLITE_NOMEM;
53472    }
53473    memset(p, 0, sizeof(*p));
53474    p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
53475    p->szMax = sqlite3GlobalConfig.mxMemdbSize;
53476  }
53477  pFile->pStore = p;
53478  if( pOutFlags!=0 ){
53479    *pOutFlags = flags | SQLITE_OPEN_MEMORY;
53480  }
53481  pFd->pMethods = &memdb_io_methods;
53482  memdbLeave(p);
53483  return SQLITE_OK;
53484}
53485
53486#if 0 /* Only used to delete rollback journals, super-journals, and WAL
53487      ** files, none of which exist in memdb.  So this routine is never used */
53488/*
53489** Delete the file located at zPath. If the dirSync argument is true,
53490** ensure the file-system modifications are synced to disk before
53491** returning.
53492*/
53493static int memdbDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
53494  return SQLITE_IOERR_DELETE;
53495}
53496#endif
53497
53498/*
53499** Test for access permissions. Return true if the requested permission
53500** is available, or false otherwise.
53501**
53502** With memdb, no files ever exist on disk.  So always return false.
53503*/
53504static int memdbAccess(
53505  sqlite3_vfs *pVfs,
53506  const char *zPath,
53507  int flags,
53508  int *pResOut
53509){
53510  UNUSED_PARAMETER(pVfs);
53511  UNUSED_PARAMETER(zPath);
53512  UNUSED_PARAMETER(flags);
53513  *pResOut = 0;
53514  return SQLITE_OK;
53515}
53516
53517/*
53518** Populate buffer zOut with the full canonical pathname corresponding
53519** to the pathname in zPath. zOut is guaranteed to point to a buffer
53520** of at least (INST_MAX_PATHNAME+1) bytes.
53521*/
53522static int memdbFullPathname(
53523  sqlite3_vfs *pVfs,
53524  const char *zPath,
53525  int nOut,
53526  char *zOut
53527){
53528  UNUSED_PARAMETER(pVfs);
53529  sqlite3_snprintf(nOut, zOut, "%s", zPath);
53530  return SQLITE_OK;
53531}
53532
53533/*
53534** Open the dynamic library located at zPath and return a handle.
53535*/
53536static void *memdbDlOpen(sqlite3_vfs *pVfs, const char *zPath){
53537  return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
53538}
53539
53540/*
53541** Populate the buffer zErrMsg (size nByte bytes) with a human readable
53542** utf-8 string describing the most recent error encountered associated
53543** with dynamic libraries.
53544*/
53545static void memdbDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
53546  ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
53547}
53548
53549/*
53550** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
53551*/
53552static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
53553  return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
53554}
53555
53556/*
53557** Close the dynamic library handle pHandle.
53558*/
53559static void memdbDlClose(sqlite3_vfs *pVfs, void *pHandle){
53560  ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
53561}
53562
53563/*
53564** Populate the buffer pointed to by zBufOut with nByte bytes of
53565** random data.
53566*/
53567static int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
53568  return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
53569}
53570
53571/*
53572** Sleep for nMicro microseconds. Return the number of microseconds
53573** actually slept.
53574*/
53575static int memdbSleep(sqlite3_vfs *pVfs, int nMicro){
53576  return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
53577}
53578
53579#if 0  /* Never used.  Modern cores only call xCurrentTimeInt64() */
53580/*
53581** Return the current time as a Julian Day number in *pTimeOut.
53582*/
53583static int memdbCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
53584  return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
53585}
53586#endif
53587
53588static int memdbGetLastError(sqlite3_vfs *pVfs, int a, char *b){
53589  return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
53590}
53591static int memdbCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
53592  return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
53593}
53594
53595/*
53596** Translate a database connection pointer and schema name into a
53597** MemFile pointer.
53598*/
53599static MemFile *memdbFromDbSchema(sqlite3 *db, const char *zSchema){
53600  MemFile *p = 0;
53601  MemStore *pStore;
53602  int rc = sqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER, &p);
53603  if( rc ) return 0;
53604  if( p->base.pMethods!=&memdb_io_methods ) return 0;
53605  pStore = p->pStore;
53606  memdbEnter(pStore);
53607  if( pStore->zFName!=0 ) p = 0;
53608  memdbLeave(pStore);
53609  return p;
53610}
53611
53612/*
53613** Return the serialization of a database
53614*/
53615SQLITE_API unsigned char *sqlite3_serialize(
53616  sqlite3 *db,              /* The database connection */
53617  const char *zSchema,      /* Which database within the connection */
53618  sqlite3_int64 *piSize,    /* Write size here, if not NULL */
53619  unsigned int mFlags       /* Maybe SQLITE_SERIALIZE_NOCOPY */
53620){
53621  MemFile *p;
53622  int iDb;
53623  Btree *pBt;
53624  sqlite3_int64 sz;
53625  int szPage = 0;
53626  sqlite3_stmt *pStmt = 0;
53627  unsigned char *pOut;
53628  char *zSql;
53629  int rc;
53630
53631#ifdef SQLITE_ENABLE_API_ARMOR
53632  if( !sqlite3SafetyCheckOk(db) ){
53633    (void)SQLITE_MISUSE_BKPT;
53634    return 0;
53635  }
53636#endif
53637
53638  if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
53639  p = memdbFromDbSchema(db, zSchema);
53640  iDb = sqlite3FindDbName(db, zSchema);
53641  if( piSize ) *piSize = -1;
53642  if( iDb<0 ) return 0;
53643  if( p ){
53644    MemStore *pStore = p->pStore;
53645    assert( pStore->pMutex==0 );
53646    if( piSize ) *piSize = pStore->sz;
53647    if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
53648      pOut = pStore->aData;
53649    }else{
53650      pOut = sqlite3_malloc64( pStore->sz );
53651      if( pOut ) memcpy(pOut, pStore->aData, pStore->sz);
53652    }
53653    return pOut;
53654  }
53655  pBt = db->aDb[iDb].pBt;
53656  if( pBt==0 ) return 0;
53657  szPage = sqlite3BtreeGetPageSize(pBt);
53658  zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema);
53659  rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
53660  sqlite3_free(zSql);
53661  if( rc ) return 0;
53662  rc = sqlite3_step(pStmt);
53663  if( rc!=SQLITE_ROW ){
53664    pOut = 0;
53665  }else{
53666    sz = sqlite3_column_int64(pStmt, 0)*szPage;
53667    if( sz==0 ){
53668      sqlite3_reset(pStmt);
53669      sqlite3_exec(db, "BEGIN IMMEDIATE; COMMIT;", 0, 0, 0);
53670      rc = sqlite3_step(pStmt);
53671      if( rc==SQLITE_ROW ){
53672        sz = sqlite3_column_int64(pStmt, 0)*szPage;
53673      }
53674    }
53675    if( piSize ) *piSize = sz;
53676    if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
53677      pOut = 0;
53678    }else{
53679      pOut = sqlite3_malloc64( sz );
53680      if( pOut ){
53681        int nPage = sqlite3_column_int(pStmt, 0);
53682        Pager *pPager = sqlite3BtreePager(pBt);
53683        int pgno;
53684        for(pgno=1; pgno<=nPage; pgno++){
53685          DbPage *pPage = 0;
53686          unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1);
53687          rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pPage, 0);
53688          if( rc==SQLITE_OK ){
53689            memcpy(pTo, sqlite3PagerGetData(pPage), szPage);
53690          }else{
53691            memset(pTo, 0, szPage);
53692          }
53693          sqlite3PagerUnref(pPage);
53694        }
53695      }
53696    }
53697  }
53698  sqlite3_finalize(pStmt);
53699  return pOut;
53700}
53701
53702/* Convert zSchema to a MemDB and initialize its content.
53703*/
53704SQLITE_API int sqlite3_deserialize(
53705  sqlite3 *db,            /* The database connection */
53706  const char *zSchema,    /* Which DB to reopen with the deserialization */
53707  unsigned char *pData,   /* The serialized database content */
53708  sqlite3_int64 szDb,     /* Number bytes in the deserialization */
53709  sqlite3_int64 szBuf,    /* Total size of buffer pData[] */
53710  unsigned mFlags         /* Zero or more SQLITE_DESERIALIZE_* flags */
53711){
53712  MemFile *p;
53713  char *zSql;
53714  sqlite3_stmt *pStmt = 0;
53715  int rc;
53716  int iDb;
53717
53718#ifdef SQLITE_ENABLE_API_ARMOR
53719  if( !sqlite3SafetyCheckOk(db) ){
53720    return SQLITE_MISUSE_BKPT;
53721  }
53722  if( szDb<0 ) return SQLITE_MISUSE_BKPT;
53723  if( szBuf<0 ) return SQLITE_MISUSE_BKPT;
53724#endif
53725
53726  sqlite3_mutex_enter(db->mutex);
53727  if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
53728  iDb = sqlite3FindDbName(db, zSchema);
53729  testcase( iDb==1 );
53730  if( iDb<2 && iDb!=0 ){
53731    rc = SQLITE_ERROR;
53732    goto end_deserialize;
53733  }
53734  zSql = sqlite3_mprintf("ATTACH x AS %Q", zSchema);
53735  if( zSql==0 ){
53736    rc = SQLITE_NOMEM;
53737  }else{
53738    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
53739    sqlite3_free(zSql);
53740  }
53741  if( rc ) goto end_deserialize;
53742  db->init.iDb = (u8)iDb;
53743  db->init.reopenMemdb = 1;
53744  rc = sqlite3_step(pStmt);
53745  db->init.reopenMemdb = 0;
53746  if( rc!=SQLITE_DONE ){
53747    rc = SQLITE_ERROR;
53748    goto end_deserialize;
53749  }
53750  p = memdbFromDbSchema(db, zSchema);
53751  if( p==0 ){
53752    rc = SQLITE_ERROR;
53753  }else{
53754    MemStore *pStore = p->pStore;
53755    pStore->aData = pData;
53756    pData = 0;
53757    pStore->sz = szDb;
53758    pStore->szAlloc = szBuf;
53759    pStore->szMax = szBuf;
53760    if( pStore->szMax<sqlite3GlobalConfig.mxMemdbSize ){
53761      pStore->szMax = sqlite3GlobalConfig.mxMemdbSize;
53762    }
53763    pStore->mFlags = mFlags;
53764    rc = SQLITE_OK;
53765  }
53766
53767end_deserialize:
53768  sqlite3_finalize(pStmt);
53769  if( pData && (mFlags & SQLITE_DESERIALIZE_FREEONCLOSE)!=0 ){
53770    sqlite3_free(pData);
53771  }
53772  sqlite3_mutex_leave(db->mutex);
53773  return rc;
53774}
53775
53776/*
53777** Return true if the VFS is the memvfs.
53778*/
53779SQLITE_PRIVATE int sqlite3IsMemdb(const sqlite3_vfs *pVfs){
53780  return pVfs==&memdb_vfs;
53781}
53782
53783/*
53784** This routine is called when the extension is loaded.
53785** Register the new VFS.
53786*/
53787SQLITE_PRIVATE int sqlite3MemdbInit(void){
53788  sqlite3_vfs *pLower = sqlite3_vfs_find(0);
53789  unsigned int sz;
53790  if( NEVER(pLower==0) ) return SQLITE_ERROR;
53791  sz = pLower->szOsFile;
53792  memdb_vfs.pAppData = pLower;
53793  /* The following conditional can only be true when compiled for
53794  ** Windows x86 and SQLITE_MAX_MMAP_SIZE=0.  We always leave
53795  ** it in, to be safe, but it is marked as NO_TEST since there
53796  ** is no way to reach it under most builds. */
53797  if( sz<sizeof(MemFile) ) sz = sizeof(MemFile); /*NO_TEST*/
53798  memdb_vfs.szOsFile = sz;
53799  return sqlite3_vfs_register(&memdb_vfs, 0);
53800}
53801#endif /* SQLITE_OMIT_DESERIALIZE */
53802
53803/************** End of memdb.c ***********************************************/
53804/************** Begin file bitvec.c ******************************************/
53805/*
53806** 2008 February 16
53807**
53808** The author disclaims copyright to this source code.  In place of
53809** a legal notice, here is a blessing:
53810**
53811**    May you do good and not evil.
53812**    May you find forgiveness for yourself and forgive others.
53813**    May you share freely, never taking more than you give.
53814**
53815*************************************************************************
53816** This file implements an object that represents a fixed-length
53817** bitmap.  Bits are numbered starting with 1.
53818**
53819** A bitmap is used to record which pages of a database file have been
53820** journalled during a transaction, or which pages have the "dont-write"
53821** property.  Usually only a few pages are meet either condition.
53822** So the bitmap is usually sparse and has low cardinality.
53823** But sometimes (for example when during a DROP of a large table) most
53824** or all of the pages in a database can get journalled.  In those cases,
53825** the bitmap becomes dense with high cardinality.  The algorithm needs
53826** to handle both cases well.
53827**
53828** The size of the bitmap is fixed when the object is created.
53829**
53830** All bits are clear when the bitmap is created.  Individual bits
53831** may be set or cleared one at a time.
53832**
53833** Test operations are about 100 times more common that set operations.
53834** Clear operations are exceedingly rare.  There are usually between
53835** 5 and 500 set operations per Bitvec object, though the number of sets can
53836** sometimes grow into tens of thousands or larger.  The size of the
53837** Bitvec object is the number of pages in the database file at the
53838** start of a transaction, and is thus usually less than a few thousand,
53839** but can be as large as 2 billion for a really big database.
53840*/
53841/* #include "sqliteInt.h" */
53842
53843/* Size of the Bitvec structure in bytes. */
53844#define BITVEC_SZ        512
53845
53846/* Round the union size down to the nearest pointer boundary, since that's how
53847** it will be aligned within the Bitvec struct. */
53848#define BITVEC_USIZE \
53849    (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
53850
53851/* Type of the array "element" for the bitmap representation.
53852** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
53853** Setting this to the "natural word" size of your CPU may improve
53854** performance. */
53855#define BITVEC_TELEM     u8
53856/* Size, in bits, of the bitmap element. */
53857#define BITVEC_SZELEM    8
53858/* Number of elements in a bitmap array. */
53859#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
53860/* Number of bits in the bitmap array. */
53861#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
53862
53863/* Number of u32 values in hash table. */
53864#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
53865/* Maximum number of entries in hash table before
53866** sub-dividing and re-hashing. */
53867#define BITVEC_MXHASH    (BITVEC_NINT/2)
53868/* Hashing function for the aHash representation.
53869** Empirical testing showed that the *37 multiplier
53870** (an arbitrary prime)in the hash function provided
53871** no fewer collisions than the no-op *1. */
53872#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
53873
53874#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
53875
53876
53877/*
53878** A bitmap is an instance of the following structure.
53879**
53880** This bitmap records the existence of zero or more bits
53881** with values between 1 and iSize, inclusive.
53882**
53883** There are three possible representations of the bitmap.
53884** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
53885** bitmap.  The least significant bit is bit 1.
53886**
53887** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
53888** a hash table that will hold up to BITVEC_MXHASH distinct values.
53889**
53890** Otherwise, the value i is redirected into one of BITVEC_NPTR
53891** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
53892** handles up to iDivisor separate values of i.  apSub[0] holds
53893** values between 1 and iDivisor.  apSub[1] holds values between
53894** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
53895** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
53896** to hold deal with values between 1 and iDivisor.
53897*/
53898struct Bitvec {
53899  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
53900  u32 nSet;       /* Number of bits that are set - only valid for aHash
53901                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
53902                  ** this would be 125. */
53903  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
53904                  /* Should >=0 for apSub element. */
53905                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
53906                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
53907  union {
53908    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
53909    u32 aHash[BITVEC_NINT];      /* Hash table representation */
53910    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
53911  } u;
53912};
53913
53914/*
53915** Create a new bitmap object able to handle bits between 0 and iSize,
53916** inclusive.  Return a pointer to the new object.  Return NULL if
53917** malloc fails.
53918*/
53919SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
53920  Bitvec *p;
53921  assert( sizeof(*p)==BITVEC_SZ );
53922  p = sqlite3MallocZero( sizeof(*p) );
53923  if( p ){
53924    p->iSize = iSize;
53925  }
53926  return p;
53927}
53928
53929/*
53930** Check to see if the i-th bit is set.  Return true or false.
53931** If p is NULL (if the bitmap has not been created) or if
53932** i is out of range, then return false.
53933*/
53934SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
53935  assert( p!=0 );
53936  i--;
53937  if( i>=p->iSize ) return 0;
53938  while( p->iDivisor ){
53939    u32 bin = i/p->iDivisor;
53940    i = i%p->iDivisor;
53941    p = p->u.apSub[bin];
53942    if (!p) {
53943      return 0;
53944    }
53945  }
53946  if( p->iSize<=BITVEC_NBIT ){
53947    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
53948  } else{
53949    u32 h = BITVEC_HASH(i++);
53950    while( p->u.aHash[h] ){
53951      if( p->u.aHash[h]==i ) return 1;
53952      h = (h+1) % BITVEC_NINT;
53953    }
53954    return 0;
53955  }
53956}
53957SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
53958  return p!=0 && sqlite3BitvecTestNotNull(p,i);
53959}
53960
53961/*
53962** Set the i-th bit.  Return 0 on success and an error code if
53963** anything goes wrong.
53964**
53965** This routine might cause sub-bitmaps to be allocated.  Failing
53966** to get the memory needed to hold the sub-bitmap is the only
53967** that can go wrong with an insert, assuming p and i are valid.
53968**
53969** The calling function must ensure that p is a valid Bitvec object
53970** and that the value for "i" is within range of the Bitvec object.
53971** Otherwise the behavior is undefined.
53972*/
53973SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
53974  u32 h;
53975  if( p==0 ) return SQLITE_OK;
53976  assert( i>0 );
53977  assert( i<=p->iSize );
53978  i--;
53979  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
53980    u32 bin = i/p->iDivisor;
53981    i = i%p->iDivisor;
53982    if( p->u.apSub[bin]==0 ){
53983      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
53984      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
53985    }
53986    p = p->u.apSub[bin];
53987  }
53988  if( p->iSize<=BITVEC_NBIT ){
53989    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
53990    return SQLITE_OK;
53991  }
53992  h = BITVEC_HASH(i++);
53993  /* if there wasn't a hash collision, and this doesn't */
53994  /* completely fill the hash, then just add it without */
53995  /* worrying about sub-dividing and re-hashing. */
53996  if( !p->u.aHash[h] ){
53997    if (p->nSet<(BITVEC_NINT-1)) {
53998      goto bitvec_set_end;
53999    } else {
54000      goto bitvec_set_rehash;
54001    }
54002  }
54003  /* there was a collision, check to see if it's already */
54004  /* in hash, if not, try to find a spot for it */
54005  do {
54006    if( p->u.aHash[h]==i ) return SQLITE_OK;
54007    h++;
54008    if( h>=BITVEC_NINT ) h = 0;
54009  } while( p->u.aHash[h] );
54010  /* we didn't find it in the hash.  h points to the first */
54011  /* available free spot. check to see if this is going to */
54012  /* make our hash too "full".  */
54013bitvec_set_rehash:
54014  if( p->nSet>=BITVEC_MXHASH ){
54015    unsigned int j;
54016    int rc;
54017    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
54018    if( aiValues==0 ){
54019      return SQLITE_NOMEM_BKPT;
54020    }else{
54021      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
54022      memset(p->u.apSub, 0, sizeof(p->u.apSub));
54023      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
54024      rc = sqlite3BitvecSet(p, i);
54025      for(j=0; j<BITVEC_NINT; j++){
54026        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
54027      }
54028      sqlite3StackFree(0, aiValues);
54029      return rc;
54030    }
54031  }
54032bitvec_set_end:
54033  p->nSet++;
54034  p->u.aHash[h] = i;
54035  return SQLITE_OK;
54036}
54037
54038/*
54039** Clear the i-th bit.
54040**
54041** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
54042** that BitvecClear can use to rebuilt its hash table.
54043*/
54044SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
54045  if( p==0 ) return;
54046  assert( i>0 );
54047  i--;
54048  while( p->iDivisor ){
54049    u32 bin = i/p->iDivisor;
54050    i = i%p->iDivisor;
54051    p = p->u.apSub[bin];
54052    if (!p) {
54053      return;
54054    }
54055  }
54056  if( p->iSize<=BITVEC_NBIT ){
54057    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
54058  }else{
54059    unsigned int j;
54060    u32 *aiValues = pBuf;
54061    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
54062    memset(p->u.aHash, 0, sizeof(p->u.aHash));
54063    p->nSet = 0;
54064    for(j=0; j<BITVEC_NINT; j++){
54065      if( aiValues[j] && aiValues[j]!=(i+1) ){
54066        u32 h = BITVEC_HASH(aiValues[j]-1);
54067        p->nSet++;
54068        while( p->u.aHash[h] ){
54069          h++;
54070          if( h>=BITVEC_NINT ) h = 0;
54071        }
54072        p->u.aHash[h] = aiValues[j];
54073      }
54074    }
54075  }
54076}
54077
54078/*
54079** Destroy a bitmap object.  Reclaim all memory used.
54080*/
54081SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
54082  if( p==0 ) return;
54083  if( p->iDivisor ){
54084    unsigned int i;
54085    for(i=0; i<BITVEC_NPTR; i++){
54086      sqlite3BitvecDestroy(p->u.apSub[i]);
54087    }
54088  }
54089  sqlite3_free(p);
54090}
54091
54092/*
54093** Return the value of the iSize parameter specified when Bitvec *p
54094** was created.
54095*/
54096SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
54097  return p->iSize;
54098}
54099
54100#ifndef SQLITE_UNTESTABLE
54101/*
54102** Let V[] be an array of unsigned characters sufficient to hold
54103** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
54104** Then the following macros can be used to set, clear, or test
54105** individual bits within V.
54106*/
54107#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
54108#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
54109#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
54110
54111/*
54112** This routine runs an extensive test of the Bitvec code.
54113**
54114** The input is an array of integers that acts as a program
54115** to test the Bitvec.  The integers are opcodes followed
54116** by 0, 1, or 3 operands, depending on the opcode.  Another
54117** opcode follows immediately after the last operand.
54118**
54119** There are 6 opcodes numbered from 0 through 5.  0 is the
54120** "halt" opcode and causes the test to end.
54121**
54122**    0          Halt and return the number of errors
54123**    1 N S X    Set N bits beginning with S and incrementing by X
54124**    2 N S X    Clear N bits beginning with S and incrementing by X
54125**    3 N        Set N randomly chosen bits
54126**    4 N        Clear N randomly chosen bits
54127**    5 N S X    Set N bits from S increment X in array only, not in bitvec
54128**
54129** The opcodes 1 through 4 perform set and clear operations are performed
54130** on both a Bitvec object and on a linear array of bits obtained from malloc.
54131** Opcode 5 works on the linear array only, not on the Bitvec.
54132** Opcode 5 is used to deliberately induce a fault in order to
54133** confirm that error detection works.
54134**
54135** At the conclusion of the test the linear array is compared
54136** against the Bitvec object.  If there are any differences,
54137** an error is returned.  If they are the same, zero is returned.
54138**
54139** If a memory allocation error occurs, return -1.
54140*/
54141SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
54142  Bitvec *pBitvec = 0;
54143  unsigned char *pV = 0;
54144  int rc = -1;
54145  int i, nx, pc, op;
54146  void *pTmpSpace;
54147
54148  /* Allocate the Bitvec to be tested and a linear array of
54149  ** bits to act as the reference */
54150  pBitvec = sqlite3BitvecCreate( sz );
54151  pV = sqlite3MallocZero( (sz+7)/8 + 1 );
54152  pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
54153  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
54154
54155  /* NULL pBitvec tests */
54156  sqlite3BitvecSet(0, 1);
54157  sqlite3BitvecClear(0, 1, pTmpSpace);
54158
54159  /* Run the program */
54160  pc = i = 0;
54161  while( (op = aOp[pc])!=0 ){
54162    switch( op ){
54163      case 1:
54164      case 2:
54165      case 5: {
54166        nx = 4;
54167        i = aOp[pc+2] - 1;
54168        aOp[pc+2] += aOp[pc+3];
54169        break;
54170      }
54171      case 3:
54172      case 4:
54173      default: {
54174        nx = 2;
54175        sqlite3_randomness(sizeof(i), &i);
54176        break;
54177      }
54178    }
54179    if( (--aOp[pc+1]) > 0 ) nx = 0;
54180    pc += nx;
54181    i = (i & 0x7fffffff)%sz;
54182    if( (op & 1)!=0 ){
54183      SETBIT(pV, (i+1));
54184      if( op!=5 ){
54185        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
54186      }
54187    }else{
54188      CLEARBIT(pV, (i+1));
54189      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
54190    }
54191  }
54192
54193  /* Test to make sure the linear array exactly matches the
54194  ** Bitvec object.  Start with the assumption that they do
54195  ** match (rc==0).  Change rc to non-zero if a discrepancy
54196  ** is found.
54197  */
54198  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
54199          + sqlite3BitvecTest(pBitvec, 0)
54200          + (sqlite3BitvecSize(pBitvec) - sz);
54201  for(i=1; i<=sz; i++){
54202    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
54203      rc = i;
54204      break;
54205    }
54206  }
54207
54208  /* Free allocated structure */
54209bitvec_end:
54210  sqlite3_free(pTmpSpace);
54211  sqlite3_free(pV);
54212  sqlite3BitvecDestroy(pBitvec);
54213  return rc;
54214}
54215#endif /* SQLITE_UNTESTABLE */
54216
54217/************** End of bitvec.c **********************************************/
54218/************** Begin file pcache.c ******************************************/
54219/*
54220** 2008 August 05
54221**
54222** The author disclaims copyright to this source code.  In place of
54223** a legal notice, here is a blessing:
54224**
54225**    May you do good and not evil.
54226**    May you find forgiveness for yourself and forgive others.
54227**    May you share freely, never taking more than you give.
54228**
54229*************************************************************************
54230** This file implements that page cache.
54231*/
54232/* #include "sqliteInt.h" */
54233
54234/*
54235** A complete page cache is an instance of this structure.  Every
54236** entry in the cache holds a single page of the database file.  The
54237** btree layer only operates on the cached copy of the database pages.
54238**
54239** A page cache entry is "clean" if it exactly matches what is currently
54240** on disk.  A page is "dirty" if it has been modified and needs to be
54241** persisted to disk.
54242**
54243** pDirty, pDirtyTail, pSynced:
54244**   All dirty pages are linked into the doubly linked list using
54245**   PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
54246**   such that p was added to the list more recently than p->pDirtyNext.
54247**   PCache.pDirty points to the first (newest) element in the list and
54248**   pDirtyTail to the last (oldest).
54249**
54250**   The PCache.pSynced variable is used to optimize searching for a dirty
54251**   page to eject from the cache mid-transaction. It is better to eject
54252**   a page that does not require a journal sync than one that does.
54253**   Therefore, pSynced is maintained so that it *almost* always points
54254**   to either the oldest page in the pDirty/pDirtyTail list that has a
54255**   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
54256**   (so that the right page to eject can be found by following pDirtyPrev
54257**   pointers).
54258*/
54259struct PCache {
54260  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
54261  PgHdr *pSynced;                     /* Last synced page in dirty page list */
54262  i64 nRefSum;                        /* Sum of ref counts over all pages */
54263  int szCache;                        /* Configured cache size */
54264  int szSpill;                        /* Size before spilling occurs */
54265  int szPage;                         /* Size of every page in this cache */
54266  int szExtra;                        /* Size of extra space for each page */
54267  u8 bPurgeable;                      /* True if pages are on backing store */
54268  u8 eCreate;                         /* eCreate value for for xFetch() */
54269  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
54270  void *pStress;                      /* Argument to xStress */
54271  sqlite3_pcache *pCache;             /* Pluggable cache module */
54272};
54273
54274/********************************** Test and Debug Logic **********************/
54275/*
54276** Debug tracing macros.  Enable by by changing the "0" to "1" and
54277** recompiling.
54278**
54279** When sqlite3PcacheTrace is 1, single line trace messages are issued.
54280** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
54281** is displayed for many operations, resulting in a lot of output.
54282*/
54283#if defined(SQLITE_DEBUG) && 0
54284  int sqlite3PcacheTrace = 2;       /* 0: off  1: simple  2: cache dumps */
54285  int sqlite3PcacheMxDump = 9999;   /* Max cache entries for pcacheDump() */
54286# define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
54287  static void pcachePageTrace(int i, sqlite3_pcache_page *pLower){
54288    PgHdr *pPg;
54289    unsigned char *a;
54290    int j;
54291    if( pLower==0 ){
54292      printf("%3d: NULL\n", i);
54293    }else{
54294      pPg = (PgHdr*)pLower->pExtra;
54295      printf("%3d: nRef %2lld flgs %02x data ", i, pPg->nRef, pPg->flags);
54296      a = (unsigned char *)pLower->pBuf;
54297      for(j=0; j<12; j++) printf("%02x", a[j]);
54298      printf(" ptr %p\n", pPg);
54299    }
54300  }
54301  static void pcacheDump(PCache *pCache){
54302    int N;
54303    int i;
54304    sqlite3_pcache_page *pLower;
54305
54306    if( sqlite3PcacheTrace<2 ) return;
54307    if( pCache->pCache==0 ) return;
54308    N = sqlite3PcachePagecount(pCache);
54309    if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
54310    for(i=1; i<=N; i++){
54311       pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
54312       pcachePageTrace(i, pLower);
54313       if( pLower && ((PgHdr*)pLower)->pPage==0 ){
54314         sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
54315       }
54316    }
54317  }
54318#else
54319# define pcacheTrace(X)
54320# define pcachePageTrace(PGNO, X)
54321# define pcacheDump(X)
54322#endif
54323
54324/*
54325** Return 1 if pPg is on the dirty list for pCache.  Return 0 if not.
54326** This routine runs inside of assert() statements only.
54327*/
54328#if defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
54329static int pageOnDirtyList(PCache *pCache, PgHdr *pPg){
54330  PgHdr *p;
54331  for(p=pCache->pDirty; p; p=p->pDirtyNext){
54332    if( p==pPg ) return 1;
54333  }
54334  return 0;
54335}
54336static int pageNotOnDirtyList(PCache *pCache, PgHdr *pPg){
54337  PgHdr *p;
54338  for(p=pCache->pDirty; p; p=p->pDirtyNext){
54339    if( p==pPg ) return 0;
54340  }
54341  return 1;
54342}
54343#else
54344# define pageOnDirtyList(A,B)    1
54345# define pageNotOnDirtyList(A,B) 1
54346#endif
54347
54348/*
54349** Check invariants on a PgHdr entry.  Return true if everything is OK.
54350** Return false if any invariant is violated.
54351**
54352** This routine is for use inside of assert() statements only.  For
54353** example:
54354**
54355**          assert( sqlite3PcachePageSanity(pPg) );
54356*/
54357#ifdef SQLITE_DEBUG
54358SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
54359  PCache *pCache;
54360  assert( pPg!=0 );
54361  assert( pPg->pgno>0 || pPg->pPager==0 );    /* Page number is 1 or more */
54362  pCache = pPg->pCache;
54363  assert( pCache!=0 );      /* Every page has an associated PCache */
54364  if( pPg->flags & PGHDR_CLEAN ){
54365    assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
54366    assert( pageNotOnDirtyList(pCache, pPg) );/* CLEAN pages not on dirtylist */
54367  }else{
54368    assert( (pPg->flags & PGHDR_DIRTY)!=0 );/* If not CLEAN must be DIRTY */
54369    assert( pPg->pDirtyNext==0 || pPg->pDirtyNext->pDirtyPrev==pPg );
54370    assert( pPg->pDirtyPrev==0 || pPg->pDirtyPrev->pDirtyNext==pPg );
54371    assert( pPg->pDirtyPrev!=0 || pCache->pDirty==pPg );
54372    assert( pageOnDirtyList(pCache, pPg) );
54373  }
54374  /* WRITEABLE pages must also be DIRTY */
54375  if( pPg->flags & PGHDR_WRITEABLE ){
54376    assert( pPg->flags & PGHDR_DIRTY );     /* WRITEABLE implies DIRTY */
54377  }
54378  /* NEED_SYNC can be set independently of WRITEABLE.  This can happen,
54379  ** for example, when using the sqlite3PagerDontWrite() optimization:
54380  **    (1)  Page X is journalled, and gets WRITEABLE and NEED_SEEK.
54381  **    (2)  Page X moved to freelist, WRITEABLE is cleared
54382  **    (3)  Page X reused, WRITEABLE is set again
54383  ** If NEED_SYNC had been cleared in step 2, then it would not be reset
54384  ** in step 3, and page might be written into the database without first
54385  ** syncing the rollback journal, which might cause corruption on a power
54386  ** loss.
54387  **
54388  ** Another example is when the database page size is smaller than the
54389  ** disk sector size.  When any page of a sector is journalled, all pages
54390  ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
54391  ** in case they are later modified, since all pages in the same sector
54392  ** must be journalled and synced before any of those pages can be safely
54393  ** written.
54394  */
54395  return 1;
54396}
54397#endif /* SQLITE_DEBUG */
54398
54399
54400/********************************** Linked List Management ********************/
54401
54402/* Allowed values for second argument to pcacheManageDirtyList() */
54403#define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
54404#define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
54405#define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
54406
54407/*
54408** Manage pPage's participation on the dirty list.  Bits of the addRemove
54409** argument determines what operation to do.  The 0x01 bit means first
54410** remove pPage from the dirty list.  The 0x02 means add pPage back to
54411** the dirty list.  Doing both moves pPage to the front of the dirty list.
54412*/
54413static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
54414  PCache *p = pPage->pCache;
54415
54416  pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
54417                addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
54418                pPage->pgno));
54419  if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
54420    assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
54421    assert( pPage->pDirtyPrev || pPage==p->pDirty );
54422
54423    /* Update the PCache1.pSynced variable if necessary. */
54424    if( p->pSynced==pPage ){
54425      p->pSynced = pPage->pDirtyPrev;
54426    }
54427
54428    if( pPage->pDirtyNext ){
54429      pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
54430    }else{
54431      assert( pPage==p->pDirtyTail );
54432      p->pDirtyTail = pPage->pDirtyPrev;
54433    }
54434    if( pPage->pDirtyPrev ){
54435      pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
54436    }else{
54437      /* If there are now no dirty pages in the cache, set eCreate to 2.
54438      ** This is an optimization that allows sqlite3PcacheFetch() to skip
54439      ** searching for a dirty page to eject from the cache when it might
54440      ** otherwise have to.  */
54441      assert( pPage==p->pDirty );
54442      p->pDirty = pPage->pDirtyNext;
54443      assert( p->bPurgeable || p->eCreate==2 );
54444      if( p->pDirty==0 ){         /*OPTIMIZATION-IF-TRUE*/
54445        assert( p->bPurgeable==0 || p->eCreate==1 );
54446        p->eCreate = 2;
54447      }
54448    }
54449  }
54450  if( addRemove & PCACHE_DIRTYLIST_ADD ){
54451    pPage->pDirtyPrev = 0;
54452    pPage->pDirtyNext = p->pDirty;
54453    if( pPage->pDirtyNext ){
54454      assert( pPage->pDirtyNext->pDirtyPrev==0 );
54455      pPage->pDirtyNext->pDirtyPrev = pPage;
54456    }else{
54457      p->pDirtyTail = pPage;
54458      if( p->bPurgeable ){
54459        assert( p->eCreate==2 );
54460        p->eCreate = 1;
54461      }
54462    }
54463    p->pDirty = pPage;
54464
54465    /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
54466    ** pSynced to point to it. Checking the NEED_SYNC flag is an
54467    ** optimization, as if pSynced points to a page with the NEED_SYNC
54468    ** flag set sqlite3PcacheFetchStress() searches through all newer
54469    ** entries of the dirty-list for a page with NEED_SYNC clear anyway.  */
54470    if( !p->pSynced
54471     && 0==(pPage->flags&PGHDR_NEED_SYNC)   /*OPTIMIZATION-IF-FALSE*/
54472    ){
54473      p->pSynced = pPage;
54474    }
54475  }
54476  pcacheDump(p);
54477}
54478
54479/*
54480** Wrapper around the pluggable caches xUnpin method. If the cache is
54481** being used for an in-memory database, this function is a no-op.
54482*/
54483static void pcacheUnpin(PgHdr *p){
54484  if( p->pCache->bPurgeable ){
54485    pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
54486    sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
54487    pcacheDump(p->pCache);
54488  }
54489}
54490
54491/*
54492** Compute the number of pages of cache requested.   p->szCache is the
54493** cache size requested by the "PRAGMA cache_size" statement.
54494*/
54495static int numberOfCachePages(PCache *p){
54496  if( p->szCache>=0 ){
54497    /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
54498    ** suggested cache size is set to N. */
54499    return p->szCache;
54500  }else{
54501    i64 n;
54502    /* IMPLEMENTATION-OF: R-59858-46238 If the argument N is negative, then the
54503    ** number of cache pages is adjusted to be a number of pages that would
54504    ** use approximately abs(N*1024) bytes of memory based on the current
54505    ** page size. */
54506    n = ((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
54507    if( n>1000000000 ) n = 1000000000;
54508    return (int)n;
54509  }
54510}
54511
54512/*************************************************** General Interfaces ******
54513**
54514** Initialize and shutdown the page cache subsystem. Neither of these
54515** functions are threadsafe.
54516*/
54517SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
54518  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
54519    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
54520    ** built-in default page cache is used instead of the application defined
54521    ** page cache. */
54522    sqlite3PCacheSetDefault();
54523    assert( sqlite3GlobalConfig.pcache2.xInit!=0 );
54524  }
54525  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
54526}
54527SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
54528  if( sqlite3GlobalConfig.pcache2.xShutdown ){
54529    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
54530    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
54531  }
54532}
54533
54534/*
54535** Return the size in bytes of a PCache object.
54536*/
54537SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
54538
54539/*
54540** Create a new PCache object. Storage space to hold the object
54541** has already been allocated and is passed in as the p pointer.
54542** The caller discovers how much space needs to be allocated by
54543** calling sqlite3PcacheSize().
54544**
54545** szExtra is some extra space allocated for each page.  The first
54546** 8 bytes of the extra space will be zeroed as the page is allocated,
54547** but remaining content will be uninitialized.  Though it is opaque
54548** to this module, the extra space really ends up being the MemPage
54549** structure in the pager.
54550*/
54551SQLITE_PRIVATE int sqlite3PcacheOpen(
54552  int szPage,                  /* Size of every page */
54553  int szExtra,                 /* Extra space associated with each page */
54554  int bPurgeable,              /* True if pages are on backing store */
54555  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
54556  void *pStress,               /* Argument to xStress */
54557  PCache *p                    /* Preallocated space for the PCache */
54558){
54559  memset(p, 0, sizeof(PCache));
54560  p->szPage = 1;
54561  p->szExtra = szExtra;
54562  assert( szExtra>=8 );  /* First 8 bytes will be zeroed */
54563  p->bPurgeable = bPurgeable;
54564  p->eCreate = 2;
54565  p->xStress = xStress;
54566  p->pStress = pStress;
54567  p->szCache = 100;
54568  p->szSpill = 1;
54569  pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
54570  return sqlite3PcacheSetPageSize(p, szPage);
54571}
54572
54573/*
54574** Change the page size for PCache object. The caller must ensure that there
54575** are no outstanding page references when this function is called.
54576*/
54577SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
54578  assert( pCache->nRefSum==0 && pCache->pDirty==0 );
54579  if( pCache->szPage ){
54580    sqlite3_pcache *pNew;
54581    pNew = sqlite3GlobalConfig.pcache2.xCreate(
54582                szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
54583                pCache->bPurgeable
54584    );
54585    if( pNew==0 ) return SQLITE_NOMEM_BKPT;
54586    sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
54587    if( pCache->pCache ){
54588      sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
54589    }
54590    pCache->pCache = pNew;
54591    pCache->szPage = szPage;
54592    pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
54593  }
54594  return SQLITE_OK;
54595}
54596
54597/*
54598** Try to obtain a page from the cache.
54599**
54600** This routine returns a pointer to an sqlite3_pcache_page object if
54601** such an object is already in cache, or if a new one is created.
54602** This routine returns a NULL pointer if the object was not in cache
54603** and could not be created.
54604**
54605** The createFlags should be 0 to check for existing pages and should
54606** be 3 (not 1, but 3) to try to create a new page.
54607**
54608** If the createFlag is 0, then NULL is always returned if the page
54609** is not already in the cache.  If createFlag is 1, then a new page
54610** is created only if that can be done without spilling dirty pages
54611** and without exceeding the cache size limit.
54612**
54613** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
54614** initialize the sqlite3_pcache_page object and convert it into a
54615** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
54616** routines are split this way for performance reasons. When separated
54617** they can both (usually) operate without having to push values to
54618** the stack on entry and pop them back off on exit, which saves a
54619** lot of pushing and popping.
54620*/
54621SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
54622  PCache *pCache,       /* Obtain the page from this cache */
54623  Pgno pgno,            /* Page number to obtain */
54624  int createFlag        /* If true, create page if it does not exist already */
54625){
54626  int eCreate;
54627  sqlite3_pcache_page *pRes;
54628
54629  assert( pCache!=0 );
54630  assert( pCache->pCache!=0 );
54631  assert( createFlag==3 || createFlag==0 );
54632  assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
54633
54634  /* eCreate defines what to do if the page does not exist.
54635  **    0     Do not allocate a new page.  (createFlag==0)
54636  **    1     Allocate a new page if doing so is inexpensive.
54637  **          (createFlag==1 AND bPurgeable AND pDirty)
54638  **    2     Allocate a new page even it doing so is difficult.
54639  **          (createFlag==1 AND !(bPurgeable AND pDirty)
54640  */
54641  eCreate = createFlag & pCache->eCreate;
54642  assert( eCreate==0 || eCreate==1 || eCreate==2 );
54643  assert( createFlag==0 || pCache->eCreate==eCreate );
54644  assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
54645  pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
54646  pcacheTrace(("%p.FETCH %d%s (result: %p) ",pCache,pgno,
54647               createFlag?" create":"",pRes));
54648  pcachePageTrace(pgno, pRes);
54649  return pRes;
54650}
54651
54652/*
54653** If the sqlite3PcacheFetch() routine is unable to allocate a new
54654** page because no clean pages are available for reuse and the cache
54655** size limit has been reached, then this routine can be invoked to
54656** try harder to allocate a page.  This routine might invoke the stress
54657** callback to spill dirty pages to the journal.  It will then try to
54658** allocate the new page and will only fail to allocate a new page on
54659** an OOM error.
54660**
54661** This routine should be invoked only after sqlite3PcacheFetch() fails.
54662*/
54663SQLITE_PRIVATE int sqlite3PcacheFetchStress(
54664  PCache *pCache,                 /* Obtain the page from this cache */
54665  Pgno pgno,                      /* Page number to obtain */
54666  sqlite3_pcache_page **ppPage    /* Write result here */
54667){
54668  PgHdr *pPg;
54669  if( pCache->eCreate==2 ) return 0;
54670
54671  if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
54672    /* Find a dirty page to write-out and recycle. First try to find a
54673    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
54674    ** cleared), but if that is not possible settle for any other
54675    ** unreferenced dirty page.
54676    **
54677    ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
54678    ** flag is currently referenced, then the following may leave pSynced
54679    ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
54680    ** cleared). This is Ok, as pSynced is just an optimization.  */
54681    for(pPg=pCache->pSynced;
54682        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
54683        pPg=pPg->pDirtyPrev
54684    );
54685    pCache->pSynced = pPg;
54686    if( !pPg ){
54687      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
54688    }
54689    if( pPg ){
54690      int rc;
54691#ifdef SQLITE_LOG_CACHE_SPILL
54692      sqlite3_log(SQLITE_FULL,
54693                  "spill page %d making room for %d - cache used: %d/%d",
54694                  pPg->pgno, pgno,
54695                  sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),
54696                numberOfCachePages(pCache));
54697#endif
54698      pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
54699      rc = pCache->xStress(pCache->pStress, pPg);
54700      pcacheDump(pCache);
54701      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
54702        return rc;
54703      }
54704    }
54705  }
54706  *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
54707  return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
54708}
54709
54710/*
54711** This is a helper routine for sqlite3PcacheFetchFinish()
54712**
54713** In the uncommon case where the page being fetched has not been
54714** initialized, this routine is invoked to do the initialization.
54715** This routine is broken out into a separate function since it
54716** requires extra stack manipulation that can be avoided in the common
54717** case.
54718*/
54719static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
54720  PCache *pCache,             /* Obtain the page from this cache */
54721  Pgno pgno,                  /* Page number obtained */
54722  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
54723){
54724  PgHdr *pPgHdr;
54725  assert( pPage!=0 );
54726  pPgHdr = (PgHdr*)pPage->pExtra;
54727  assert( pPgHdr->pPage==0 );
54728  memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
54729  pPgHdr->pPage = pPage;
54730  pPgHdr->pData = pPage->pBuf;
54731  pPgHdr->pExtra = (void *)&pPgHdr[1];
54732  memset(pPgHdr->pExtra, 0, 8);
54733  pPgHdr->pCache = pCache;
54734  pPgHdr->pgno = pgno;
54735  pPgHdr->flags = PGHDR_CLEAN;
54736  return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
54737}
54738
54739/*
54740** This routine converts the sqlite3_pcache_page object returned by
54741** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
54742** must be called after sqlite3PcacheFetch() in order to get a usable
54743** result.
54744*/
54745SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
54746  PCache *pCache,             /* Obtain the page from this cache */
54747  Pgno pgno,                  /* Page number obtained */
54748  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
54749){
54750  PgHdr *pPgHdr;
54751
54752  assert( pPage!=0 );
54753  pPgHdr = (PgHdr *)pPage->pExtra;
54754
54755  if( !pPgHdr->pPage ){
54756    return pcacheFetchFinishWithInit(pCache, pgno, pPage);
54757  }
54758  pCache->nRefSum++;
54759  pPgHdr->nRef++;
54760  assert( sqlite3PcachePageSanity(pPgHdr) );
54761  return pPgHdr;
54762}
54763
54764/*
54765** Decrement the reference count on a page. If the page is clean and the
54766** reference count drops to 0, then it is made eligible for recycling.
54767*/
54768SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
54769  assert( p->nRef>0 );
54770  p->pCache->nRefSum--;
54771  if( (--p->nRef)==0 ){
54772    if( p->flags&PGHDR_CLEAN ){
54773      pcacheUnpin(p);
54774    }else{
54775      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
54776      assert( sqlite3PcachePageSanity(p) );
54777    }
54778  }
54779}
54780
54781/*
54782** Increase the reference count of a supplied page by 1.
54783*/
54784SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
54785  assert(p->nRef>0);
54786  assert( sqlite3PcachePageSanity(p) );
54787  p->nRef++;
54788  p->pCache->nRefSum++;
54789}
54790
54791/*
54792** Drop a page from the cache. There must be exactly one reference to the
54793** page. This function deletes that reference, so after it returns the
54794** page pointed to by p is invalid.
54795*/
54796SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
54797  assert( p->nRef==1 );
54798  assert( sqlite3PcachePageSanity(p) );
54799  if( p->flags&PGHDR_DIRTY ){
54800    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
54801  }
54802  p->pCache->nRefSum--;
54803  sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
54804}
54805
54806/*
54807** Make sure the page is marked as dirty. If it isn't dirty already,
54808** make it so.
54809*/
54810SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
54811  assert( p->nRef>0 );
54812  assert( sqlite3PcachePageSanity(p) );
54813  if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){    /*OPTIMIZATION-IF-FALSE*/
54814    p->flags &= ~PGHDR_DONT_WRITE;
54815    if( p->flags & PGHDR_CLEAN ){
54816      p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
54817      pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
54818      assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
54819      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
54820      assert( sqlite3PcachePageSanity(p) );
54821    }
54822    assert( sqlite3PcachePageSanity(p) );
54823  }
54824}
54825
54826/*
54827** Make sure the page is marked as clean. If it isn't clean already,
54828** make it so.
54829*/
54830SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
54831  assert( sqlite3PcachePageSanity(p) );
54832  assert( (p->flags & PGHDR_DIRTY)!=0 );
54833  assert( (p->flags & PGHDR_CLEAN)==0 );
54834  pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
54835  p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
54836  p->flags |= PGHDR_CLEAN;
54837  pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
54838  assert( sqlite3PcachePageSanity(p) );
54839  if( p->nRef==0 ){
54840    pcacheUnpin(p);
54841  }
54842}
54843
54844/*
54845** Make every page in the cache clean.
54846*/
54847SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
54848  PgHdr *p;
54849  pcacheTrace(("%p.CLEAN-ALL\n",pCache));
54850  while( (p = pCache->pDirty)!=0 ){
54851    sqlite3PcacheMakeClean(p);
54852  }
54853}
54854
54855/*
54856** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
54857*/
54858SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
54859  PgHdr *p;
54860  pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
54861  for(p=pCache->pDirty; p; p=p->pDirtyNext){
54862    p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
54863  }
54864  pCache->pSynced = pCache->pDirtyTail;
54865}
54866
54867/*
54868** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
54869*/
54870SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
54871  PgHdr *p;
54872  for(p=pCache->pDirty; p; p=p->pDirtyNext){
54873    p->flags &= ~PGHDR_NEED_SYNC;
54874  }
54875  pCache->pSynced = pCache->pDirtyTail;
54876}
54877
54878/*
54879** Change the page number of page p to newPgno.
54880*/
54881SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
54882  PCache *pCache = p->pCache;
54883  sqlite3_pcache_page *pOther;
54884  assert( p->nRef>0 );
54885  assert( newPgno>0 );
54886  assert( sqlite3PcachePageSanity(p) );
54887  pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
54888  pOther = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, newPgno, 0);
54889  if( pOther ){
54890    PgHdr *pXPage = (PgHdr*)pOther->pExtra;
54891    assert( pXPage->nRef==0 );
54892    pXPage->nRef++;
54893    pCache->nRefSum++;
54894    sqlite3PcacheDrop(pXPage);
54895  }
54896  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
54897  p->pgno = newPgno;
54898  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
54899    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
54900    assert( sqlite3PcachePageSanity(p) );
54901  }
54902}
54903
54904/*
54905** Drop every cache entry whose page number is greater than "pgno". The
54906** caller must ensure that there are no outstanding references to any pages
54907** other than page 1 with a page number greater than pgno.
54908**
54909** If there is a reference to page 1 and the pgno parameter passed to this
54910** function is 0, then the data area associated with page 1 is zeroed, but
54911** the page object is not dropped.
54912*/
54913SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
54914  if( pCache->pCache ){
54915    PgHdr *p;
54916    PgHdr *pNext;
54917    pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
54918    for(p=pCache->pDirty; p; p=pNext){
54919      pNext = p->pDirtyNext;
54920      /* This routine never gets call with a positive pgno except right
54921      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
54922      ** it must be that pgno==0.
54923      */
54924      assert( p->pgno>0 );
54925      if( p->pgno>pgno ){
54926        assert( p->flags&PGHDR_DIRTY );
54927        sqlite3PcacheMakeClean(p);
54928      }
54929    }
54930    if( pgno==0 && pCache->nRefSum ){
54931      sqlite3_pcache_page *pPage1;
54932      pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
54933      if( ALWAYS(pPage1) ){  /* Page 1 is always available in cache, because
54934                             ** pCache->nRefSum>0 */
54935        memset(pPage1->pBuf, 0, pCache->szPage);
54936        pgno = 1;
54937      }
54938    }
54939    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
54940  }
54941}
54942
54943/*
54944** Close a cache.
54945*/
54946SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
54947  assert( pCache->pCache!=0 );
54948  pcacheTrace(("%p.CLOSE\n",pCache));
54949  sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
54950}
54951
54952/*
54953** Discard the contents of the cache.
54954*/
54955SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
54956  sqlite3PcacheTruncate(pCache, 0);
54957}
54958
54959/*
54960** Merge two lists of pages connected by pDirty and in pgno order.
54961** Do not bother fixing the pDirtyPrev pointers.
54962*/
54963static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
54964  PgHdr result, *pTail;
54965  pTail = &result;
54966  assert( pA!=0 && pB!=0 );
54967  for(;;){
54968    if( pA->pgno<pB->pgno ){
54969      pTail->pDirty = pA;
54970      pTail = pA;
54971      pA = pA->pDirty;
54972      if( pA==0 ){
54973        pTail->pDirty = pB;
54974        break;
54975      }
54976    }else{
54977      pTail->pDirty = pB;
54978      pTail = pB;
54979      pB = pB->pDirty;
54980      if( pB==0 ){
54981        pTail->pDirty = pA;
54982        break;
54983      }
54984    }
54985  }
54986  return result.pDirty;
54987}
54988
54989/*
54990** Sort the list of pages in ascending order by pgno.  Pages are
54991** connected by pDirty pointers.  The pDirtyPrev pointers are
54992** corrupted by this sort.
54993**
54994** Since there cannot be more than 2^31 distinct pages in a database,
54995** there cannot be more than 31 buckets required by the merge sorter.
54996** One extra bucket is added to catch overflow in case something
54997** ever changes to make the previous sentence incorrect.
54998*/
54999#define N_SORT_BUCKET  32
55000static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
55001  PgHdr *a[N_SORT_BUCKET], *p;
55002  int i;
55003  memset(a, 0, sizeof(a));
55004  while( pIn ){
55005    p = pIn;
55006    pIn = p->pDirty;
55007    p->pDirty = 0;
55008    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
55009      if( a[i]==0 ){
55010        a[i] = p;
55011        break;
55012      }else{
55013        p = pcacheMergeDirtyList(a[i], p);
55014        a[i] = 0;
55015      }
55016    }
55017    if( NEVER(i==N_SORT_BUCKET-1) ){
55018      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
55019      ** the input list.  But that is impossible.
55020      */
55021      a[i] = pcacheMergeDirtyList(a[i], p);
55022    }
55023  }
55024  p = a[0];
55025  for(i=1; i<N_SORT_BUCKET; i++){
55026    if( a[i]==0 ) continue;
55027    p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
55028  }
55029  return p;
55030}
55031
55032/*
55033** Return a list of all dirty pages in the cache, sorted by page number.
55034*/
55035SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
55036  PgHdr *p;
55037  for(p=pCache->pDirty; p; p=p->pDirtyNext){
55038    p->pDirty = p->pDirtyNext;
55039  }
55040  return pcacheSortDirtyList(pCache->pDirty);
55041}
55042
55043/*
55044** Return the total number of references to all pages held by the cache.
55045**
55046** This is not the total number of pages referenced, but the sum of the
55047** reference count for all pages.
55048*/
55049SQLITE_PRIVATE i64 sqlite3PcacheRefCount(PCache *pCache){
55050  return pCache->nRefSum;
55051}
55052
55053/*
55054** Return the number of references to the page supplied as an argument.
55055*/
55056SQLITE_PRIVATE i64 sqlite3PcachePageRefcount(PgHdr *p){
55057  return p->nRef;
55058}
55059
55060/*
55061** Return the total number of pages in the cache.
55062*/
55063SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
55064  assert( pCache->pCache!=0 );
55065  return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
55066}
55067
55068#ifdef SQLITE_TEST
55069/*
55070** Get the suggested cache-size value.
55071*/
55072SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
55073  return numberOfCachePages(pCache);
55074}
55075#endif
55076
55077/*
55078** Set the suggested cache-size value.
55079*/
55080SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
55081  assert( pCache->pCache!=0 );
55082  pCache->szCache = mxPage;
55083  sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
55084                                         numberOfCachePages(pCache));
55085}
55086
55087/*
55088** Set the suggested cache-spill value.  Make no changes if if the
55089** argument is zero.  Return the effective cache-spill size, which will
55090** be the larger of the szSpill and szCache.
55091*/
55092SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
55093  int res;
55094  assert( p->pCache!=0 );
55095  if( mxPage ){
55096    if( mxPage<0 ){
55097      mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
55098    }
55099    p->szSpill = mxPage;
55100  }
55101  res = numberOfCachePages(p);
55102  if( res<p->szSpill ) res = p->szSpill;
55103  return res;
55104}
55105
55106/*
55107** Free up as much memory as possible from the page cache.
55108*/
55109SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
55110  assert( pCache->pCache!=0 );
55111  sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
55112}
55113
55114/*
55115** Return the size of the header added by this middleware layer
55116** in the page-cache hierarchy.
55117*/
55118SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
55119
55120/*
55121** Return the number of dirty pages currently in the cache, as a percentage
55122** of the configured cache size.
55123*/
55124SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
55125  PgHdr *pDirty;
55126  int nDirty = 0;
55127  int nCache = numberOfCachePages(pCache);
55128  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
55129  return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
55130}
55131
55132#ifdef SQLITE_DIRECT_OVERFLOW_READ
55133/*
55134** Return true if there are one or more dirty pages in the cache. Else false.
55135*/
55136SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache){
55137  return (pCache->pDirty!=0);
55138}
55139#endif
55140
55141#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
55142/*
55143** For all dirty pages currently in the cache, invoke the specified
55144** callback. This is only used if the SQLITE_CHECK_PAGES macro is
55145** defined.
55146*/
55147SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
55148  PgHdr *pDirty;
55149  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
55150    xIter(pDirty);
55151  }
55152}
55153#endif
55154
55155/************** End of pcache.c **********************************************/
55156/************** Begin file pcache1.c *****************************************/
55157/*
55158** 2008 November 05
55159**
55160** The author disclaims copyright to this source code.  In place of
55161** a legal notice, here is a blessing:
55162**
55163**    May you do good and not evil.
55164**    May you find forgiveness for yourself and forgive others.
55165**    May you share freely, never taking more than you give.
55166**
55167*************************************************************************
55168**
55169** This file implements the default page cache implementation (the
55170** sqlite3_pcache interface). It also contains part of the implementation
55171** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
55172** If the default page cache implementation is overridden, then neither of
55173** these two features are available.
55174**
55175** A Page cache line looks like this:
55176**
55177**  -------------------------------------------------------------
55178**  |  database page content   |  PgHdr1  |  MemPage  |  PgHdr  |
55179**  -------------------------------------------------------------
55180**
55181** The database page content is up front (so that buffer overreads tend to
55182** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions).   MemPage
55183** is the extension added by the btree.c module containing information such
55184** as the database page number and how that database page is used.  PgHdr
55185** is added by the pcache.c layer and contains information used to keep track
55186** of which pages are "dirty".  PgHdr1 is an extension added by this
55187** module (pcache1.c).  The PgHdr1 header is a subclass of sqlite3_pcache_page.
55188** PgHdr1 contains information needed to look up a page by its page number.
55189** The superclass sqlite3_pcache_page.pBuf points to the start of the
55190** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
55191**
55192** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
55193** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size).  The
55194** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
55195** size can vary according to architecture, compile-time options, and
55196** SQLite library version number.
55197**
55198** Historical note:  It used to be that if the SQLITE_PCACHE_SEPARATE_HEADER
55199** was defined, then the page content would be held in a separate memory
55200** allocation from the PgHdr1.  This was intended to avoid clownshoe memory
55201** allocations.  However, the btree layer needs a small (16-byte) overrun
55202** area after the page content buffer.  The header serves as that overrun
55203** area.  Therefore SQLITE_PCACHE_SEPARATE_HEADER was discontinued to avoid
55204** any possibility of a memory error.
55205**
55206** This module tracks pointers to PgHdr1 objects.  Only pcache.c communicates
55207** with this module.  Information is passed back and forth as PgHdr1 pointers.
55208**
55209** The pcache.c and pager.c modules deal pointers to PgHdr objects.
55210** The btree.c module deals with pointers to MemPage objects.
55211**
55212** SOURCE OF PAGE CACHE MEMORY:
55213**
55214** Memory for a page might come from any of three sources:
55215**
55216**    (1)  The general-purpose memory allocator - sqlite3Malloc()
55217**    (2)  Global page-cache memory provided using sqlite3_config() with
55218**         SQLITE_CONFIG_PAGECACHE.
55219**    (3)  PCache-local bulk allocation.
55220**
55221** The third case is a chunk of heap memory (defaulting to 100 pages worth)
55222** that is allocated when the page cache is created.  The size of the local
55223** bulk allocation can be adjusted using
55224**
55225**     sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
55226**
55227** If N is positive, then N pages worth of memory are allocated using a single
55228** sqlite3Malloc() call and that memory is used for the first N pages allocated.
55229** Or if N is negative, then -1024*N bytes of memory are allocated and used
55230** for as many pages as can be accommodated.
55231**
55232** Only one of (2) or (3) can be used.  Once the memory available to (2) or
55233** (3) is exhausted, subsequent allocations fail over to the general-purpose
55234** memory allocator (1).
55235**
55236** Earlier versions of SQLite used only methods (1) and (2).  But experiments
55237** show that method (3) with N==100 provides about a 5% performance boost for
55238** common workloads.
55239*/
55240/* #include "sqliteInt.h" */
55241
55242typedef struct PCache1 PCache1;
55243typedef struct PgHdr1 PgHdr1;
55244typedef struct PgFreeslot PgFreeslot;
55245typedef struct PGroup PGroup;
55246
55247/*
55248** Each cache entry is represented by an instance of the following
55249** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
55250** directly before this structure and is used to cache the page content.
55251**
55252** When reading a corrupt database file, it is possible that SQLite might
55253** read a few bytes (no more than 16 bytes) past the end of the page buffer.
55254** It will only read past the end of the page buffer, never write.  This
55255** object is positioned immediately after the page buffer to serve as an
55256** overrun area, so that overreads are harmless.
55257**
55258** Variables isBulkLocal and isAnchor were once type "u8". That works,
55259** but causes a 2-byte gap in the structure for most architectures (since
55260** pointers must be either 4 or 8-byte aligned). As this structure is located
55261** in memory directly after the associated page data, if the database is
55262** corrupt, code at the b-tree layer may overread the page buffer and
55263** read part of this structure before the corruption is detected. This
55264** can cause a valgrind error if the uninitialized gap is accessed. Using u16
55265** ensures there is no such gap, and therefore no bytes of uninitialized
55266** memory in the structure.
55267**
55268** The pLruNext and pLruPrev pointers form a double-linked circular list
55269** of all pages that are unpinned.  The PGroup.lru element (which should be
55270** the only element on the list with PgHdr1.isAnchor set to 1) forms the
55271** beginning and the end of the list.
55272*/
55273struct PgHdr1 {
55274  sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
55275  unsigned int iKey;        /* Key value (page number) */
55276  u16 isBulkLocal;          /* This page from bulk local storage */
55277  u16 isAnchor;             /* This is the PGroup.lru element */
55278  PgHdr1 *pNext;            /* Next in hash table chain */
55279  PCache1 *pCache;          /* Cache that currently owns this page */
55280  PgHdr1 *pLruNext;         /* Next in circular LRU list of unpinned pages */
55281  PgHdr1 *pLruPrev;         /* Previous in LRU list of unpinned pages */
55282                            /* NB: pLruPrev is only valid if pLruNext!=0 */
55283};
55284
55285/*
55286** A page is pinned if it is not on the LRU list.  To be "pinned" means
55287** that the page is in active use and must not be deallocated.
55288*/
55289#define PAGE_IS_PINNED(p)    ((p)->pLruNext==0)
55290#define PAGE_IS_UNPINNED(p)  ((p)->pLruNext!=0)
55291
55292/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
55293** of one or more PCaches that are able to recycle each other's unpinned
55294** pages when they are under memory pressure.  A PGroup is an instance of
55295** the following object.
55296**
55297** This page cache implementation works in one of two modes:
55298**
55299**   (1)  Every PCache is the sole member of its own PGroup.  There is
55300**        one PGroup per PCache.
55301**
55302**   (2)  There is a single global PGroup that all PCaches are a member
55303**        of.
55304**
55305** Mode 1 uses more memory (since PCache instances are not able to rob
55306** unused pages from other PCaches) but it also operates without a mutex,
55307** and is therefore often faster.  Mode 2 requires a mutex in order to be
55308** threadsafe, but recycles pages more efficiently.
55309**
55310** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
55311** PGroup which is the pcache1.grp global variable and its mutex is
55312** SQLITE_MUTEX_STATIC_LRU.
55313*/
55314struct PGroup {
55315  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
55316  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
55317  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
55318  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
55319  unsigned int nPurgeable;       /* Number of purgeable pages allocated */
55320  PgHdr1 lru;                    /* The beginning and end of the LRU list */
55321};
55322
55323/* Each page cache is an instance of the following object.  Every
55324** open database file (including each in-memory database and each
55325** temporary or transient database) has a single page cache which
55326** is an instance of this object.
55327**
55328** Pointers to structures of this type are cast and returned as
55329** opaque sqlite3_pcache* handles.
55330*/
55331struct PCache1 {
55332  /* Cache configuration parameters. Page size (szPage) and the purgeable
55333  ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
55334  ** cache is created and are never changed thereafter. nMax may be
55335  ** modified at any time by a call to the pcache1Cachesize() method.
55336  ** The PGroup mutex must be held when accessing nMax.
55337  */
55338  PGroup *pGroup;                     /* PGroup this cache belongs to */
55339  unsigned int *pnPurgeable;          /* Pointer to pGroup->nPurgeable */
55340  int szPage;                         /* Size of database content section */
55341  int szExtra;                        /* sizeof(MemPage)+sizeof(PgHdr) */
55342  int szAlloc;                        /* Total size of one pcache line */
55343  int bPurgeable;                     /* True if cache is purgeable */
55344  unsigned int nMin;                  /* Minimum number of pages reserved */
55345  unsigned int nMax;                  /* Configured "cache_size" value */
55346  unsigned int n90pct;                /* nMax*9/10 */
55347  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
55348  unsigned int nPurgeableDummy;       /* pnPurgeable points here when not used*/
55349
55350  /* Hash table of all pages. The following variables may only be accessed
55351  ** when the accessor is holding the PGroup mutex.
55352  */
55353  unsigned int nRecyclable;           /* Number of pages in the LRU list */
55354  unsigned int nPage;                 /* Total number of pages in apHash */
55355  unsigned int nHash;                 /* Number of slots in apHash[] */
55356  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
55357  PgHdr1 *pFree;                      /* List of unused pcache-local pages */
55358  void *pBulk;                        /* Bulk memory used by pcache-local */
55359};
55360
55361/*
55362** Free slots in the allocator used to divide up the global page cache
55363** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
55364*/
55365struct PgFreeslot {
55366  PgFreeslot *pNext;  /* Next free slot */
55367};
55368
55369/*
55370** Global data used by this cache.
55371*/
55372static SQLITE_WSD struct PCacheGlobal {
55373  PGroup grp;                    /* The global PGroup for mode (2) */
55374
55375  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
55376  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
55377  ** fixed at sqlite3_initialize() time and do not require mutex protection.
55378  ** The nFreeSlot and pFree values do require mutex protection.
55379  */
55380  int isInit;                    /* True if initialized */
55381  int separateCache;             /* Use a new PGroup for each PCache */
55382  int nInitPage;                 /* Initial bulk allocation size */
55383  int szSlot;                    /* Size of each free slot */
55384  int nSlot;                     /* The number of pcache slots */
55385  int nReserve;                  /* Try to keep nFreeSlot above this */
55386  void *pStart, *pEnd;           /* Bounds of global page cache memory */
55387  /* Above requires no mutex.  Use mutex below for variable that follow. */
55388  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
55389  PgFreeslot *pFree;             /* Free page blocks */
55390  int nFreeSlot;                 /* Number of unused pcache slots */
55391  /* The following value requires a mutex to change.  We skip the mutex on
55392  ** reading because (1) most platforms read a 32-bit integer atomically and
55393  ** (2) even if an incorrect value is read, no great harm is done since this
55394  ** is really just an optimization. */
55395  int bUnderPressure;            /* True if low on PAGECACHE memory */
55396} pcache1_g;
55397
55398/*
55399** All code in this file should access the global structure above via the
55400** alias "pcache1". This ensures that the WSD emulation is used when
55401** compiling for systems that do not support real WSD.
55402*/
55403#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
55404
55405/*
55406** Macros to enter and leave the PCache LRU mutex.
55407*/
55408#if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
55409# define pcache1EnterMutex(X)  assert((X)->mutex==0)
55410# define pcache1LeaveMutex(X)  assert((X)->mutex==0)
55411# define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
55412#else
55413# define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
55414# define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
55415# define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
55416#endif
55417
55418/******************************************************************************/
55419/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
55420
55421
55422/*
55423** This function is called during initialization if a static buffer is
55424** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
55425** verb to sqlite3_config(). Parameter pBuf points to an allocation large
55426** enough to contain 'n' buffers of 'sz' bytes each.
55427**
55428** This routine is called from sqlite3_initialize() and so it is guaranteed
55429** to be serialized already.  There is no need for further mutexing.
55430*/
55431SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
55432  if( pcache1.isInit ){
55433    PgFreeslot *p;
55434    if( pBuf==0 ) sz = n = 0;
55435    if( n==0 ) sz = 0;
55436    sz = ROUNDDOWN8(sz);
55437    pcache1.szSlot = sz;
55438    pcache1.nSlot = pcache1.nFreeSlot = n;
55439    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
55440    pcache1.pStart = pBuf;
55441    pcache1.pFree = 0;
55442    pcache1.bUnderPressure = 0;
55443    while( n-- ){
55444      p = (PgFreeslot*)pBuf;
55445      p->pNext = pcache1.pFree;
55446      pcache1.pFree = p;
55447      pBuf = (void*)&((char*)pBuf)[sz];
55448    }
55449    pcache1.pEnd = pBuf;
55450  }
55451}
55452
55453/*
55454** Try to initialize the pCache->pFree and pCache->pBulk fields.  Return
55455** true if pCache->pFree ends up containing one or more free pages.
55456*/
55457static int pcache1InitBulk(PCache1 *pCache){
55458  i64 szBulk;
55459  char *zBulk;
55460  if( pcache1.nInitPage==0 ) return 0;
55461  /* Do not bother with a bulk allocation if the cache size very small */
55462  if( pCache->nMax<3 ) return 0;
55463  sqlite3BeginBenignMalloc();
55464  if( pcache1.nInitPage>0 ){
55465    szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
55466  }else{
55467    szBulk = -1024 * (i64)pcache1.nInitPage;
55468  }
55469  if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
55470    szBulk = pCache->szAlloc*(i64)pCache->nMax;
55471  }
55472  zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
55473  sqlite3EndBenignMalloc();
55474  if( zBulk ){
55475    int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
55476    do{
55477      PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
55478      pX->page.pBuf = zBulk;
55479      pX->page.pExtra = &pX[1];
55480      pX->isBulkLocal = 1;
55481      pX->isAnchor = 0;
55482      pX->pNext = pCache->pFree;
55483      pX->pLruPrev = 0;           /* Initializing this saves a valgrind error */
55484      pCache->pFree = pX;
55485      zBulk += pCache->szAlloc;
55486    }while( --nBulk );
55487  }
55488  return pCache->pFree!=0;
55489}
55490
55491/*
55492** Malloc function used within this file to allocate space from the buffer
55493** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
55494** such buffer exists or there is no space left in it, this function falls
55495** back to sqlite3Malloc().
55496**
55497** Multiple threads can run this routine at the same time.  Global variables
55498** in pcache1 need to be protected via mutex.
55499*/
55500static void *pcache1Alloc(int nByte){
55501  void *p = 0;
55502  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
55503  if( nByte<=pcache1.szSlot ){
55504    sqlite3_mutex_enter(pcache1.mutex);
55505    p = (PgHdr1 *)pcache1.pFree;
55506    if( p ){
55507      pcache1.pFree = pcache1.pFree->pNext;
55508      pcache1.nFreeSlot--;
55509      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
55510      assert( pcache1.nFreeSlot>=0 );
55511      sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
55512      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
55513    }
55514    sqlite3_mutex_leave(pcache1.mutex);
55515  }
55516  if( p==0 ){
55517    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
55518    ** it from sqlite3Malloc instead.
55519    */
55520    p = sqlite3Malloc(nByte);
55521#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
55522    if( p ){
55523      int sz = sqlite3MallocSize(p);
55524      sqlite3_mutex_enter(pcache1.mutex);
55525      sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
55526      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
55527      sqlite3_mutex_leave(pcache1.mutex);
55528    }
55529#endif
55530    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
55531  }
55532  return p;
55533}
55534
55535/*
55536** Free an allocated buffer obtained from pcache1Alloc().
55537*/
55538static void pcache1Free(void *p){
55539  if( p==0 ) return;
55540  if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
55541    PgFreeslot *pSlot;
55542    sqlite3_mutex_enter(pcache1.mutex);
55543    sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
55544    pSlot = (PgFreeslot*)p;
55545    pSlot->pNext = pcache1.pFree;
55546    pcache1.pFree = pSlot;
55547    pcache1.nFreeSlot++;
55548    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
55549    assert( pcache1.nFreeSlot<=pcache1.nSlot );
55550    sqlite3_mutex_leave(pcache1.mutex);
55551  }else{
55552    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
55553    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
55554#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
55555    {
55556      int nFreed = 0;
55557      nFreed = sqlite3MallocSize(p);
55558      sqlite3_mutex_enter(pcache1.mutex);
55559      sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
55560      sqlite3_mutex_leave(pcache1.mutex);
55561    }
55562#endif
55563    sqlite3_free(p);
55564  }
55565}
55566
55567#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
55568/*
55569** Return the size of a pcache allocation
55570*/
55571static int pcache1MemSize(void *p){
55572  if( p>=pcache1.pStart && p<pcache1.pEnd ){
55573    return pcache1.szSlot;
55574  }else{
55575    int iSize;
55576    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
55577    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
55578    iSize = sqlite3MallocSize(p);
55579    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
55580    return iSize;
55581  }
55582}
55583#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
55584
55585/*
55586** Allocate a new page object initially associated with cache pCache.
55587*/
55588static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
55589  PgHdr1 *p = 0;
55590  void *pPg;
55591
55592  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
55593  if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
55594    assert( pCache->pFree!=0 );
55595    p = pCache->pFree;
55596    pCache->pFree = p->pNext;
55597    p->pNext = 0;
55598  }else{
55599#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
55600    /* The group mutex must be released before pcache1Alloc() is called. This
55601    ** is because it might call sqlite3_release_memory(), which assumes that
55602    ** this mutex is not held. */
55603    assert( pcache1.separateCache==0 );
55604    assert( pCache->pGroup==&pcache1.grp );
55605    pcache1LeaveMutex(pCache->pGroup);
55606#endif
55607    if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
55608    pPg = pcache1Alloc(pCache->szAlloc);
55609    if( benignMalloc ){ sqlite3EndBenignMalloc(); }
55610#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
55611    pcache1EnterMutex(pCache->pGroup);
55612#endif
55613    if( pPg==0 ) return 0;
55614    p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
55615    p->page.pBuf = pPg;
55616    p->page.pExtra = &p[1];
55617    p->isBulkLocal = 0;
55618    p->isAnchor = 0;
55619    p->pLruPrev = 0;           /* Initializing this saves a valgrind error */
55620  }
55621  (*pCache->pnPurgeable)++;
55622  return p;
55623}
55624
55625/*
55626** Free a page object allocated by pcache1AllocPage().
55627*/
55628static void pcache1FreePage(PgHdr1 *p){
55629  PCache1 *pCache;
55630  assert( p!=0 );
55631  pCache = p->pCache;
55632  assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
55633  if( p->isBulkLocal ){
55634    p->pNext = pCache->pFree;
55635    pCache->pFree = p;
55636  }else{
55637    pcache1Free(p->page.pBuf);
55638  }
55639  (*pCache->pnPurgeable)--;
55640}
55641
55642/*
55643** Malloc function used by SQLite to obtain space from the buffer configured
55644** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
55645** exists, this function falls back to sqlite3Malloc().
55646*/
55647SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
55648  assert( sz<=65536+8 ); /* These allocations are never very large */
55649  return pcache1Alloc(sz);
55650}
55651
55652/*
55653** Free an allocated buffer obtained from sqlite3PageMalloc().
55654*/
55655SQLITE_PRIVATE void sqlite3PageFree(void *p){
55656  pcache1Free(p);
55657}
55658
55659
55660/*
55661** Return true if it desirable to avoid allocating a new page cache
55662** entry.
55663**
55664** If memory was allocated specifically to the page cache using
55665** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
55666** it is desirable to avoid allocating a new page cache entry because
55667** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
55668** for all page cache needs and we should not need to spill the
55669** allocation onto the heap.
55670**
55671** Or, the heap is used for all page cache memory but the heap is
55672** under memory pressure, then again it is desirable to avoid
55673** allocating a new page cache entry in order to avoid stressing
55674** the heap even further.
55675*/
55676static int pcache1UnderMemoryPressure(PCache1 *pCache){
55677  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
55678    return pcache1.bUnderPressure;
55679  }else{
55680    return sqlite3HeapNearlyFull();
55681  }
55682}
55683
55684/******************************************************************************/
55685/******** General Implementation Functions ************************************/
55686
55687/*
55688** This function is used to resize the hash table used by the cache passed
55689** as the first argument.
55690**
55691** The PCache mutex must be held when this function is called.
55692*/
55693static void pcache1ResizeHash(PCache1 *p){
55694  PgHdr1 **apNew;
55695  unsigned int nNew;
55696  unsigned int i;
55697
55698  assert( sqlite3_mutex_held(p->pGroup->mutex) );
55699
55700  nNew = p->nHash*2;
55701  if( nNew<256 ){
55702    nNew = 256;
55703  }
55704
55705  pcache1LeaveMutex(p->pGroup);
55706  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
55707  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
55708  if( p->nHash ){ sqlite3EndBenignMalloc(); }
55709  pcache1EnterMutex(p->pGroup);
55710  if( apNew ){
55711    for(i=0; i<p->nHash; i++){
55712      PgHdr1 *pPage;
55713      PgHdr1 *pNext = p->apHash[i];
55714      while( (pPage = pNext)!=0 ){
55715        unsigned int h = pPage->iKey % nNew;
55716        pNext = pPage->pNext;
55717        pPage->pNext = apNew[h];
55718        apNew[h] = pPage;
55719      }
55720    }
55721    sqlite3_free(p->apHash);
55722    p->apHash = apNew;
55723    p->nHash = nNew;
55724  }
55725}
55726
55727/*
55728** This function is used internally to remove the page pPage from the
55729** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
55730** LRU list, then this function is a no-op.
55731**
55732** The PGroup mutex must be held when this function is called.
55733*/
55734static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
55735  assert( pPage!=0 );
55736  assert( PAGE_IS_UNPINNED(pPage) );
55737  assert( pPage->pLruNext );
55738  assert( pPage->pLruPrev );
55739  assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
55740  pPage->pLruPrev->pLruNext = pPage->pLruNext;
55741  pPage->pLruNext->pLruPrev = pPage->pLruPrev;
55742  pPage->pLruNext = 0;
55743  /* pPage->pLruPrev = 0;
55744  ** No need to clear pLruPrev as it is never accessed if pLruNext is 0 */
55745  assert( pPage->isAnchor==0 );
55746  assert( pPage->pCache->pGroup->lru.isAnchor==1 );
55747  pPage->pCache->nRecyclable--;
55748  return pPage;
55749}
55750
55751
55752/*
55753** Remove the page supplied as an argument from the hash table
55754** (PCache1.apHash structure) that it is currently stored in.
55755** Also free the page if freePage is true.
55756**
55757** The PGroup mutex must be held when this function is called.
55758*/
55759static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
55760  unsigned int h;
55761  PCache1 *pCache = pPage->pCache;
55762  PgHdr1 **pp;
55763
55764  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
55765  h = pPage->iKey % pCache->nHash;
55766  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
55767  *pp = (*pp)->pNext;
55768
55769  pCache->nPage--;
55770  if( freeFlag ) pcache1FreePage(pPage);
55771}
55772
55773/*
55774** If there are currently more than nMaxPage pages allocated, try
55775** to recycle pages to reduce the number allocated to nMaxPage.
55776*/
55777static void pcache1EnforceMaxPage(PCache1 *pCache){
55778  PGroup *pGroup = pCache->pGroup;
55779  PgHdr1 *p;
55780  assert( sqlite3_mutex_held(pGroup->mutex) );
55781  while( pGroup->nPurgeable>pGroup->nMaxPage
55782      && (p=pGroup->lru.pLruPrev)->isAnchor==0
55783  ){
55784    assert( p->pCache->pGroup==pGroup );
55785    assert( PAGE_IS_UNPINNED(p) );
55786    pcache1PinPage(p);
55787    pcache1RemoveFromHash(p, 1);
55788  }
55789  if( pCache->nPage==0 && pCache->pBulk ){
55790    sqlite3_free(pCache->pBulk);
55791    pCache->pBulk = pCache->pFree = 0;
55792  }
55793}
55794
55795/*
55796** Discard all pages from cache pCache with a page number (key value)
55797** greater than or equal to iLimit. Any pinned pages that meet this
55798** criteria are unpinned before they are discarded.
55799**
55800** The PCache mutex must be held when this function is called.
55801*/
55802static void pcache1TruncateUnsafe(
55803  PCache1 *pCache,             /* The cache to truncate */
55804  unsigned int iLimit          /* Drop pages with this pgno or larger */
55805){
55806  TESTONLY( int nPage = 0; )  /* To assert pCache->nPage is correct */
55807  unsigned int h, iStop;
55808  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
55809  assert( pCache->iMaxKey >= iLimit );
55810  assert( pCache->nHash > 0 );
55811  if( pCache->iMaxKey - iLimit < pCache->nHash ){
55812    /* If we are just shaving the last few pages off the end of the
55813    ** cache, then there is no point in scanning the entire hash table.
55814    ** Only scan those hash slots that might contain pages that need to
55815    ** be removed. */
55816    h = iLimit % pCache->nHash;
55817    iStop = pCache->iMaxKey % pCache->nHash;
55818    TESTONLY( nPage = -10; )  /* Disable the pCache->nPage validity check */
55819  }else{
55820    /* This is the general case where many pages are being removed.
55821    ** It is necessary to scan the entire hash table */
55822    h = pCache->nHash/2;
55823    iStop = h - 1;
55824  }
55825  for(;;){
55826    PgHdr1 **pp;
55827    PgHdr1 *pPage;
55828    assert( h<pCache->nHash );
55829    pp = &pCache->apHash[h];
55830    while( (pPage = *pp)!=0 ){
55831      if( pPage->iKey>=iLimit ){
55832        pCache->nPage--;
55833        *pp = pPage->pNext;
55834        if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
55835        pcache1FreePage(pPage);
55836      }else{
55837        pp = &pPage->pNext;
55838        TESTONLY( if( nPage>=0 ) nPage++; )
55839      }
55840    }
55841    if( h==iStop ) break;
55842    h = (h+1) % pCache->nHash;
55843  }
55844  assert( nPage<0 || pCache->nPage==(unsigned)nPage );
55845}
55846
55847/******************************************************************************/
55848/******** sqlite3_pcache Methods **********************************************/
55849
55850/*
55851** Implementation of the sqlite3_pcache.xInit method.
55852*/
55853static int pcache1Init(void *NotUsed){
55854  UNUSED_PARAMETER(NotUsed);
55855  assert( pcache1.isInit==0 );
55856  memset(&pcache1, 0, sizeof(pcache1));
55857
55858
55859  /*
55860  ** The pcache1.separateCache variable is true if each PCache has its own
55861  ** private PGroup (mode-1).  pcache1.separateCache is false if the single
55862  ** PGroup in pcache1.grp is used for all page caches (mode-2).
55863  **
55864  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
55865  **
55866  **   *  Use a unified cache in single-threaded applications that have
55867  **      configured a start-time buffer for use as page-cache memory using
55868  **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
55869  **      pBuf argument.
55870  **
55871  **   *  Otherwise use separate caches (mode-1)
55872  */
55873#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
55874  pcache1.separateCache = 0;
55875#elif SQLITE_THREADSAFE
55876  pcache1.separateCache = sqlite3GlobalConfig.pPage==0
55877                          || sqlite3GlobalConfig.bCoreMutex>0;
55878#else
55879  pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
55880#endif
55881
55882#if SQLITE_THREADSAFE
55883  if( sqlite3GlobalConfig.bCoreMutex ){
55884    pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
55885    pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
55886  }
55887#endif
55888  if( pcache1.separateCache
55889   && sqlite3GlobalConfig.nPage!=0
55890   && sqlite3GlobalConfig.pPage==0
55891  ){
55892    pcache1.nInitPage = sqlite3GlobalConfig.nPage;
55893  }else{
55894    pcache1.nInitPage = 0;
55895  }
55896  pcache1.grp.mxPinned = 10;
55897  pcache1.isInit = 1;
55898  return SQLITE_OK;
55899}
55900
55901/*
55902** Implementation of the sqlite3_pcache.xShutdown method.
55903** Note that the static mutex allocated in xInit does
55904** not need to be freed.
55905*/
55906static void pcache1Shutdown(void *NotUsed){
55907  UNUSED_PARAMETER(NotUsed);
55908  assert( pcache1.isInit!=0 );
55909  memset(&pcache1, 0, sizeof(pcache1));
55910}
55911
55912/* forward declaration */
55913static void pcache1Destroy(sqlite3_pcache *p);
55914
55915/*
55916** Implementation of the sqlite3_pcache.xCreate method.
55917**
55918** Allocate a new cache.
55919*/
55920static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
55921  PCache1 *pCache;      /* The newly created page cache */
55922  PGroup *pGroup;       /* The group the new page cache will belong to */
55923  int sz;               /* Bytes of memory required to allocate the new cache */
55924
55925  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
55926  assert( szExtra < 300 );
55927
55928  sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
55929  pCache = (PCache1 *)sqlite3MallocZero(sz);
55930  if( pCache ){
55931    if( pcache1.separateCache ){
55932      pGroup = (PGroup*)&pCache[1];
55933      pGroup->mxPinned = 10;
55934    }else{
55935      pGroup = &pcache1.grp;
55936    }
55937    pcache1EnterMutex(pGroup);
55938    if( pGroup->lru.isAnchor==0 ){
55939      pGroup->lru.isAnchor = 1;
55940      pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
55941    }
55942    pCache->pGroup = pGroup;
55943    pCache->szPage = szPage;
55944    pCache->szExtra = szExtra;
55945    pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
55946    pCache->bPurgeable = (bPurgeable ? 1 : 0);
55947    pcache1ResizeHash(pCache);
55948    if( bPurgeable ){
55949      pCache->nMin = 10;
55950      pGroup->nMinPage += pCache->nMin;
55951      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
55952      pCache->pnPurgeable = &pGroup->nPurgeable;
55953    }else{
55954      pCache->pnPurgeable = &pCache->nPurgeableDummy;
55955    }
55956    pcache1LeaveMutex(pGroup);
55957    if( pCache->nHash==0 ){
55958      pcache1Destroy((sqlite3_pcache*)pCache);
55959      pCache = 0;
55960    }
55961  }
55962  return (sqlite3_pcache *)pCache;
55963}
55964
55965/*
55966** Implementation of the sqlite3_pcache.xCachesize method.
55967**
55968** Configure the cache_size limit for a cache.
55969*/
55970static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
55971  PCache1 *pCache = (PCache1 *)p;
55972  u32 n;
55973  assert( nMax>=0 );
55974  if( pCache->bPurgeable ){
55975    PGroup *pGroup = pCache->pGroup;
55976    pcache1EnterMutex(pGroup);
55977    n = (u32)nMax;
55978    if( n > 0x7fff0000 - pGroup->nMaxPage + pCache->nMax ){
55979      n = 0x7fff0000 - pGroup->nMaxPage + pCache->nMax;
55980    }
55981    pGroup->nMaxPage += (n - pCache->nMax);
55982    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
55983    pCache->nMax = n;
55984    pCache->n90pct = pCache->nMax*9/10;
55985    pcache1EnforceMaxPage(pCache);
55986    pcache1LeaveMutex(pGroup);
55987  }
55988}
55989
55990/*
55991** Implementation of the sqlite3_pcache.xShrink method.
55992**
55993** Free up as much memory as possible.
55994*/
55995static void pcache1Shrink(sqlite3_pcache *p){
55996  PCache1 *pCache = (PCache1*)p;
55997  if( pCache->bPurgeable ){
55998    PGroup *pGroup = pCache->pGroup;
55999    unsigned int savedMaxPage;
56000    pcache1EnterMutex(pGroup);
56001    savedMaxPage = pGroup->nMaxPage;
56002    pGroup->nMaxPage = 0;
56003    pcache1EnforceMaxPage(pCache);
56004    pGroup->nMaxPage = savedMaxPage;
56005    pcache1LeaveMutex(pGroup);
56006  }
56007}
56008
56009/*
56010** Implementation of the sqlite3_pcache.xPagecount method.
56011*/
56012static int pcache1Pagecount(sqlite3_pcache *p){
56013  int n;
56014  PCache1 *pCache = (PCache1*)p;
56015  pcache1EnterMutex(pCache->pGroup);
56016  n = pCache->nPage;
56017  pcache1LeaveMutex(pCache->pGroup);
56018  return n;
56019}
56020
56021
56022/*
56023** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
56024** in the header of the pcache1Fetch() procedure.
56025**
56026** This steps are broken out into a separate procedure because they are
56027** usually not needed, and by avoiding the stack initialization required
56028** for these steps, the main pcache1Fetch() procedure can run faster.
56029*/
56030static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
56031  PCache1 *pCache,
56032  unsigned int iKey,
56033  int createFlag
56034){
56035  unsigned int nPinned;
56036  PGroup *pGroup = pCache->pGroup;
56037  PgHdr1 *pPage = 0;
56038
56039  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
56040  assert( pCache->nPage >= pCache->nRecyclable );
56041  nPinned = pCache->nPage - pCache->nRecyclable;
56042  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
56043  assert( pCache->n90pct == pCache->nMax*9/10 );
56044  if( createFlag==1 && (
56045        nPinned>=pGroup->mxPinned
56046     || nPinned>=pCache->n90pct
56047     || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
56048  )){
56049    return 0;
56050  }
56051
56052  if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
56053  assert( pCache->nHash>0 && pCache->apHash );
56054
56055  /* Step 4. Try to recycle a page. */
56056  if( pCache->bPurgeable
56057   && !pGroup->lru.pLruPrev->isAnchor
56058   && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
56059  ){
56060    PCache1 *pOther;
56061    pPage = pGroup->lru.pLruPrev;
56062    assert( PAGE_IS_UNPINNED(pPage) );
56063    pcache1RemoveFromHash(pPage, 0);
56064    pcache1PinPage(pPage);
56065    pOther = pPage->pCache;
56066    if( pOther->szAlloc != pCache->szAlloc ){
56067      pcache1FreePage(pPage);
56068      pPage = 0;
56069    }else{
56070      pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
56071    }
56072  }
56073
56074  /* Step 5. If a usable page buffer has still not been found,
56075  ** attempt to allocate a new one.
56076  */
56077  if( !pPage ){
56078    pPage = pcache1AllocPage(pCache, createFlag==1);
56079  }
56080
56081  if( pPage ){
56082    unsigned int h = iKey % pCache->nHash;
56083    pCache->nPage++;
56084    pPage->iKey = iKey;
56085    pPage->pNext = pCache->apHash[h];
56086    pPage->pCache = pCache;
56087    pPage->pLruNext = 0;
56088    /* pPage->pLruPrev = 0;
56089    ** No need to clear pLruPrev since it is not accessed when pLruNext==0 */
56090    *(void **)pPage->page.pExtra = 0;
56091    pCache->apHash[h] = pPage;
56092    if( iKey>pCache->iMaxKey ){
56093      pCache->iMaxKey = iKey;
56094    }
56095  }
56096  return pPage;
56097}
56098
56099/*
56100** Implementation of the sqlite3_pcache.xFetch method.
56101**
56102** Fetch a page by key value.
56103**
56104** Whether or not a new page may be allocated by this function depends on
56105** the value of the createFlag argument.  0 means do not allocate a new
56106** page.  1 means allocate a new page if space is easily available.  2
56107** means to try really hard to allocate a new page.
56108**
56109** For a non-purgeable cache (a cache used as the storage for an in-memory
56110** database) there is really no difference between createFlag 1 and 2.  So
56111** the calling function (pcache.c) will never have a createFlag of 1 on
56112** a non-purgeable cache.
56113**
56114** There are three different approaches to obtaining space for a page,
56115** depending on the value of parameter createFlag (which may be 0, 1 or 2).
56116**
56117**   1. Regardless of the value of createFlag, the cache is searched for a
56118**      copy of the requested page. If one is found, it is returned.
56119**
56120**   2. If createFlag==0 and the page is not already in the cache, NULL is
56121**      returned.
56122**
56123**   3. If createFlag is 1, and the page is not already in the cache, then
56124**      return NULL (do not allocate a new page) if any of the following
56125**      conditions are true:
56126**
56127**       (a) the number of pages pinned by the cache is greater than
56128**           PCache1.nMax, or
56129**
56130**       (b) the number of pages pinned by the cache is greater than
56131**           the sum of nMax for all purgeable caches, less the sum of
56132**           nMin for all other purgeable caches, or
56133**
56134**   4. If none of the first three conditions apply and the cache is marked
56135**      as purgeable, and if one of the following is true:
56136**
56137**       (a) The number of pages allocated for the cache is already
56138**           PCache1.nMax, or
56139**
56140**       (b) The number of pages allocated for all purgeable caches is
56141**           already equal to or greater than the sum of nMax for all
56142**           purgeable caches,
56143**
56144**       (c) The system is under memory pressure and wants to avoid
56145**           unnecessary pages cache entry allocations
56146**
56147**      then attempt to recycle a page from the LRU list. If it is the right
56148**      size, return the recycled buffer. Otherwise, free the buffer and
56149**      proceed to step 5.
56150**
56151**   5. Otherwise, allocate and return a new page buffer.
56152**
56153** There are two versions of this routine.  pcache1FetchWithMutex() is
56154** the general case.  pcache1FetchNoMutex() is a faster implementation for
56155** the common case where pGroup->mutex is NULL.  The pcache1Fetch() wrapper
56156** invokes the appropriate routine.
56157*/
56158static PgHdr1 *pcache1FetchNoMutex(
56159  sqlite3_pcache *p,
56160  unsigned int iKey,
56161  int createFlag
56162){
56163  PCache1 *pCache = (PCache1 *)p;
56164  PgHdr1 *pPage = 0;
56165
56166  /* Step 1: Search the hash table for an existing entry. */
56167  pPage = pCache->apHash[iKey % pCache->nHash];
56168  while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
56169
56170  /* Step 2: If the page was found in the hash table, then return it.
56171  ** If the page was not in the hash table and createFlag is 0, abort.
56172  ** Otherwise (page not in hash and createFlag!=0) continue with
56173  ** subsequent steps to try to create the page. */
56174  if( pPage ){
56175    if( PAGE_IS_UNPINNED(pPage) ){
56176      return pcache1PinPage(pPage);
56177    }else{
56178      return pPage;
56179    }
56180  }else if( createFlag ){
56181    /* Steps 3, 4, and 5 implemented by this subroutine */
56182    return pcache1FetchStage2(pCache, iKey, createFlag);
56183  }else{
56184    return 0;
56185  }
56186}
56187#if PCACHE1_MIGHT_USE_GROUP_MUTEX
56188static PgHdr1 *pcache1FetchWithMutex(
56189  sqlite3_pcache *p,
56190  unsigned int iKey,
56191  int createFlag
56192){
56193  PCache1 *pCache = (PCache1 *)p;
56194  PgHdr1 *pPage;
56195
56196  pcache1EnterMutex(pCache->pGroup);
56197  pPage = pcache1FetchNoMutex(p, iKey, createFlag);
56198  assert( pPage==0 || pCache->iMaxKey>=iKey );
56199  pcache1LeaveMutex(pCache->pGroup);
56200  return pPage;
56201}
56202#endif
56203static sqlite3_pcache_page *pcache1Fetch(
56204  sqlite3_pcache *p,
56205  unsigned int iKey,
56206  int createFlag
56207){
56208#if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
56209  PCache1 *pCache = (PCache1 *)p;
56210#endif
56211
56212  assert( offsetof(PgHdr1,page)==0 );
56213  assert( pCache->bPurgeable || createFlag!=1 );
56214  assert( pCache->bPurgeable || pCache->nMin==0 );
56215  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
56216  assert( pCache->nMin==0 || pCache->bPurgeable );
56217  assert( pCache->nHash>0 );
56218#if PCACHE1_MIGHT_USE_GROUP_MUTEX
56219  if( pCache->pGroup->mutex ){
56220    return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
56221  }else
56222#endif
56223  {
56224    return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
56225  }
56226}
56227
56228
56229/*
56230** Implementation of the sqlite3_pcache.xUnpin method.
56231**
56232** Mark a page as unpinned (eligible for asynchronous recycling).
56233*/
56234static void pcache1Unpin(
56235  sqlite3_pcache *p,
56236  sqlite3_pcache_page *pPg,
56237  int reuseUnlikely
56238){
56239  PCache1 *pCache = (PCache1 *)p;
56240  PgHdr1 *pPage = (PgHdr1 *)pPg;
56241  PGroup *pGroup = pCache->pGroup;
56242
56243  assert( pPage->pCache==pCache );
56244  pcache1EnterMutex(pGroup);
56245
56246  /* It is an error to call this function if the page is already
56247  ** part of the PGroup LRU list.
56248  */
56249  assert( pPage->pLruNext==0 );
56250  assert( PAGE_IS_PINNED(pPage) );
56251
56252  if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
56253    pcache1RemoveFromHash(pPage, 1);
56254  }else{
56255    /* Add the page to the PGroup LRU list. */
56256    PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
56257    pPage->pLruPrev = &pGroup->lru;
56258    (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
56259    *ppFirst = pPage;
56260    pCache->nRecyclable++;
56261  }
56262
56263  pcache1LeaveMutex(pCache->pGroup);
56264}
56265
56266/*
56267** Implementation of the sqlite3_pcache.xRekey method.
56268*/
56269static void pcache1Rekey(
56270  sqlite3_pcache *p,
56271  sqlite3_pcache_page *pPg,
56272  unsigned int iOld,
56273  unsigned int iNew
56274){
56275  PCache1 *pCache = (PCache1 *)p;
56276  PgHdr1 *pPage = (PgHdr1 *)pPg;
56277  PgHdr1 **pp;
56278  unsigned int hOld, hNew;
56279  assert( pPage->iKey==iOld );
56280  assert( pPage->pCache==pCache );
56281  assert( iOld!=iNew );               /* The page number really is changing */
56282
56283  pcache1EnterMutex(pCache->pGroup);
56284
56285  assert( pcache1FetchNoMutex(p, iOld, 0)==pPage ); /* pPg really is iOld */
56286  hOld = iOld%pCache->nHash;
56287  pp = &pCache->apHash[hOld];
56288  while( (*pp)!=pPage ){
56289    pp = &(*pp)->pNext;
56290  }
56291  *pp = pPage->pNext;
56292
56293  assert( pcache1FetchNoMutex(p, iNew, 0)==0 ); /* iNew not in cache */
56294  hNew = iNew%pCache->nHash;
56295  pPage->iKey = iNew;
56296  pPage->pNext = pCache->apHash[hNew];
56297  pCache->apHash[hNew] = pPage;
56298  if( iNew>pCache->iMaxKey ){
56299    pCache->iMaxKey = iNew;
56300  }
56301
56302  pcache1LeaveMutex(pCache->pGroup);
56303}
56304
56305/*
56306** Implementation of the sqlite3_pcache.xTruncate method.
56307**
56308** Discard all unpinned pages in the cache with a page number equal to
56309** or greater than parameter iLimit. Any pinned pages with a page number
56310** equal to or greater than iLimit are implicitly unpinned.
56311*/
56312static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
56313  PCache1 *pCache = (PCache1 *)p;
56314  pcache1EnterMutex(pCache->pGroup);
56315  if( iLimit<=pCache->iMaxKey ){
56316    pcache1TruncateUnsafe(pCache, iLimit);
56317    pCache->iMaxKey = iLimit-1;
56318  }
56319  pcache1LeaveMutex(pCache->pGroup);
56320}
56321
56322/*
56323** Implementation of the sqlite3_pcache.xDestroy method.
56324**
56325** Destroy a cache allocated using pcache1Create().
56326*/
56327static void pcache1Destroy(sqlite3_pcache *p){
56328  PCache1 *pCache = (PCache1 *)p;
56329  PGroup *pGroup = pCache->pGroup;
56330  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
56331  pcache1EnterMutex(pGroup);
56332  if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
56333  assert( pGroup->nMaxPage >= pCache->nMax );
56334  pGroup->nMaxPage -= pCache->nMax;
56335  assert( pGroup->nMinPage >= pCache->nMin );
56336  pGroup->nMinPage -= pCache->nMin;
56337  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
56338  pcache1EnforceMaxPage(pCache);
56339  pcache1LeaveMutex(pGroup);
56340  sqlite3_free(pCache->pBulk);
56341  sqlite3_free(pCache->apHash);
56342  sqlite3_free(pCache);
56343}
56344
56345/*
56346** This function is called during initialization (sqlite3_initialize()) to
56347** install the default pluggable cache module, assuming the user has not
56348** already provided an alternative.
56349*/
56350SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
56351  static const sqlite3_pcache_methods2 defaultMethods = {
56352    1,                       /* iVersion */
56353    0,                       /* pArg */
56354    pcache1Init,             /* xInit */
56355    pcache1Shutdown,         /* xShutdown */
56356    pcache1Create,           /* xCreate */
56357    pcache1Cachesize,        /* xCachesize */
56358    pcache1Pagecount,        /* xPagecount */
56359    pcache1Fetch,            /* xFetch */
56360    pcache1Unpin,            /* xUnpin */
56361    pcache1Rekey,            /* xRekey */
56362    pcache1Truncate,         /* xTruncate */
56363    pcache1Destroy,          /* xDestroy */
56364    pcache1Shrink            /* xShrink */
56365  };
56366  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
56367}
56368
56369/*
56370** Return the size of the header on each page of this PCACHE implementation.
56371*/
56372SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
56373
56374/*
56375** Return the global mutex used by this PCACHE implementation.  The
56376** sqlite3_status() routine needs access to this mutex.
56377*/
56378SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
56379  return pcache1.mutex;
56380}
56381
56382#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
56383/*
56384** This function is called to free superfluous dynamically allocated memory
56385** held by the pager system. Memory in use by any SQLite pager allocated
56386** by the current thread may be sqlite3_free()ed.
56387**
56388** nReq is the number of bytes of memory required. Once this much has
56389** been released, the function returns. The return value is the total number
56390** of bytes of memory released.
56391*/
56392SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
56393  int nFree = 0;
56394  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
56395  assert( sqlite3_mutex_notheld(pcache1.mutex) );
56396  if( sqlite3GlobalConfig.pPage==0 ){
56397    PgHdr1 *p;
56398    pcache1EnterMutex(&pcache1.grp);
56399    while( (nReq<0 || nFree<nReq)
56400       &&  (p=pcache1.grp.lru.pLruPrev)!=0
56401       &&  p->isAnchor==0
56402    ){
56403      nFree += pcache1MemSize(p->page.pBuf);
56404      assert( PAGE_IS_UNPINNED(p) );
56405      pcache1PinPage(p);
56406      pcache1RemoveFromHash(p, 1);
56407    }
56408    pcache1LeaveMutex(&pcache1.grp);
56409  }
56410  return nFree;
56411}
56412#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
56413
56414#ifdef SQLITE_TEST
56415/*
56416** This function is used by test procedures to inspect the internal state
56417** of the global cache.
56418*/
56419SQLITE_PRIVATE void sqlite3PcacheStats(
56420  int *pnCurrent,      /* OUT: Total number of pages cached */
56421  int *pnMax,          /* OUT: Global maximum cache size */
56422  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
56423  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
56424){
56425  PgHdr1 *p;
56426  int nRecyclable = 0;
56427  for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
56428    assert( PAGE_IS_UNPINNED(p) );
56429    nRecyclable++;
56430  }
56431  *pnCurrent = pcache1.grp.nPurgeable;
56432  *pnMax = (int)pcache1.grp.nMaxPage;
56433  *pnMin = (int)pcache1.grp.nMinPage;
56434  *pnRecyclable = nRecyclable;
56435}
56436#endif
56437
56438/************** End of pcache1.c *********************************************/
56439/************** Begin file rowset.c ******************************************/
56440/*
56441** 2008 December 3
56442**
56443** The author disclaims copyright to this source code.  In place of
56444** a legal notice, here is a blessing:
56445**
56446**    May you do good and not evil.
56447**    May you find forgiveness for yourself and forgive others.
56448**    May you share freely, never taking more than you give.
56449**
56450*************************************************************************
56451**
56452** This module implements an object we call a "RowSet".
56453**
56454** The RowSet object is a collection of rowids.  Rowids
56455** are inserted into the RowSet in an arbitrary order.  Inserts
56456** can be intermixed with tests to see if a given rowid has been
56457** previously inserted into the RowSet.
56458**
56459** After all inserts are finished, it is possible to extract the
56460** elements of the RowSet in sorted order.  Once this extraction
56461** process has started, no new elements may be inserted.
56462**
56463** Hence, the primitive operations for a RowSet are:
56464**
56465**    CREATE
56466**    INSERT
56467**    TEST
56468**    SMALLEST
56469**    DESTROY
56470**
56471** The CREATE and DESTROY primitives are the constructor and destructor,
56472** obviously.  The INSERT primitive adds a new element to the RowSet.
56473** TEST checks to see if an element is already in the RowSet.  SMALLEST
56474** extracts the least value from the RowSet.
56475**
56476** The INSERT primitive might allocate additional memory.  Memory is
56477** allocated in chunks so most INSERTs do no allocation.  There is an
56478** upper bound on the size of allocated memory.  No memory is freed
56479** until DESTROY.
56480**
56481** The TEST primitive includes a "batch" number.  The TEST primitive
56482** will only see elements that were inserted before the last change
56483** in the batch number.  In other words, if an INSERT occurs between
56484** two TESTs where the TESTs have the same batch number, then the
56485** value added by the INSERT will not be visible to the second TEST.
56486** The initial batch number is zero, so if the very first TEST contains
56487** a non-zero batch number, it will see all prior INSERTs.
56488**
56489** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
56490** that is attempted.
56491**
56492** The cost of an INSERT is roughly constant.  (Sometimes new memory
56493** has to be allocated on an INSERT.)  The cost of a TEST with a new
56494** batch number is O(NlogN) where N is the number of elements in the RowSet.
56495** The cost of a TEST using the same batch number is O(logN).  The cost
56496** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
56497** primitives are constant time.  The cost of DESTROY is O(N).
56498**
56499** TEST and SMALLEST may not be used by the same RowSet.  This used to
56500** be possible, but the feature was not used, so it was removed in order
56501** to simplify the code.
56502*/
56503/* #include "sqliteInt.h" */
56504
56505
56506/*
56507** Target size for allocation chunks.
56508*/
56509#define ROWSET_ALLOCATION_SIZE 1024
56510
56511/*
56512** The number of rowset entries per allocation chunk.
56513*/
56514#define ROWSET_ENTRY_PER_CHUNK  \
56515                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
56516
56517/*
56518** Each entry in a RowSet is an instance of the following object.
56519**
56520** This same object is reused to store a linked list of trees of RowSetEntry
56521** objects.  In that alternative use, pRight points to the next entry
56522** in the list, pLeft points to the tree, and v is unused.  The
56523** RowSet.pForest value points to the head of this forest list.
56524*/
56525struct RowSetEntry {
56526  i64 v;                        /* ROWID value for this entry */
56527  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
56528  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
56529};
56530
56531/*
56532** RowSetEntry objects are allocated in large chunks (instances of the
56533** following structure) to reduce memory allocation overhead.  The
56534** chunks are kept on a linked list so that they can be deallocated
56535** when the RowSet is destroyed.
56536*/
56537struct RowSetChunk {
56538  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
56539  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
56540};
56541
56542/*
56543** A RowSet in an instance of the following structure.
56544**
56545** A typedef of this structure if found in sqliteInt.h.
56546*/
56547struct RowSet {
56548  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
56549  sqlite3 *db;                   /* The database connection */
56550  struct RowSetEntry *pEntry;    /* List of entries using pRight */
56551  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
56552  struct RowSetEntry *pFresh;    /* Source of new entry objects */
56553  struct RowSetEntry *pForest;   /* List of binary trees of entries */
56554  u16 nFresh;                    /* Number of objects on pFresh */
56555  u16 rsFlags;                   /* Various flags */
56556  int iBatch;                    /* Current insert batch */
56557};
56558
56559/*
56560** Allowed values for RowSet.rsFlags
56561*/
56562#define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
56563#define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
56564
56565/*
56566** Allocate a RowSet object.  Return NULL if a memory allocation
56567** error occurs.
56568*/
56569SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db){
56570  RowSet *p = sqlite3DbMallocRawNN(db, sizeof(*p));
56571  if( p ){
56572    int N = sqlite3DbMallocSize(db, p);
56573    p->pChunk = 0;
56574    p->db = db;
56575    p->pEntry = 0;
56576    p->pLast = 0;
56577    p->pForest = 0;
56578    p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
56579    p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
56580    p->rsFlags = ROWSET_SORTED;
56581    p->iBatch = 0;
56582  }
56583  return p;
56584}
56585
56586/*
56587** Deallocate all chunks from a RowSet.  This frees all memory that
56588** the RowSet has allocated over its lifetime.  This routine is
56589** the destructor for the RowSet.
56590*/
56591SQLITE_PRIVATE void sqlite3RowSetClear(void *pArg){
56592  RowSet *p = (RowSet*)pArg;
56593  struct RowSetChunk *pChunk, *pNextChunk;
56594  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
56595    pNextChunk = pChunk->pNextChunk;
56596    sqlite3DbFree(p->db, pChunk);
56597  }
56598  p->pChunk = 0;
56599  p->nFresh = 0;
56600  p->pEntry = 0;
56601  p->pLast = 0;
56602  p->pForest = 0;
56603  p->rsFlags = ROWSET_SORTED;
56604}
56605
56606/*
56607** Deallocate all chunks from a RowSet.  This frees all memory that
56608** the RowSet has allocated over its lifetime.  This routine is
56609** the destructor for the RowSet.
56610*/
56611SQLITE_PRIVATE void sqlite3RowSetDelete(void *pArg){
56612  sqlite3RowSetClear(pArg);
56613  sqlite3DbFree(((RowSet*)pArg)->db, pArg);
56614}
56615
56616/*
56617** Allocate a new RowSetEntry object that is associated with the
56618** given RowSet.  Return a pointer to the new and completely uninitialized
56619** object.
56620**
56621** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
56622** routine returns NULL.
56623*/
56624static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
56625  assert( p!=0 );
56626  if( p->nFresh==0 ){  /*OPTIMIZATION-IF-FALSE*/
56627    /* We could allocate a fresh RowSetEntry each time one is needed, but it
56628    ** is more efficient to pull a preallocated entry from the pool */
56629    struct RowSetChunk *pNew;
56630    pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
56631    if( pNew==0 ){
56632      return 0;
56633    }
56634    pNew->pNextChunk = p->pChunk;
56635    p->pChunk = pNew;
56636    p->pFresh = pNew->aEntry;
56637    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
56638  }
56639  p->nFresh--;
56640  return p->pFresh++;
56641}
56642
56643/*
56644** Insert a new value into a RowSet.
56645**
56646** The mallocFailed flag of the database connection is set if a
56647** memory allocation fails.
56648*/
56649SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
56650  struct RowSetEntry *pEntry;  /* The new entry */
56651  struct RowSetEntry *pLast;   /* The last prior entry */
56652
56653  /* This routine is never called after sqlite3RowSetNext() */
56654  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
56655
56656  pEntry = rowSetEntryAlloc(p);
56657  if( pEntry==0 ) return;
56658  pEntry->v = rowid;
56659  pEntry->pRight = 0;
56660  pLast = p->pLast;
56661  if( pLast ){
56662    if( rowid<=pLast->v ){  /*OPTIMIZATION-IF-FALSE*/
56663      /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
56664      ** where possible */
56665      p->rsFlags &= ~ROWSET_SORTED;
56666    }
56667    pLast->pRight = pEntry;
56668  }else{
56669    p->pEntry = pEntry;
56670  }
56671  p->pLast = pEntry;
56672}
56673
56674/*
56675** Merge two lists of RowSetEntry objects.  Remove duplicates.
56676**
56677** The input lists are connected via pRight pointers and are
56678** assumed to each already be in sorted order.
56679*/
56680static struct RowSetEntry *rowSetEntryMerge(
56681  struct RowSetEntry *pA,    /* First sorted list to be merged */
56682  struct RowSetEntry *pB     /* Second sorted list to be merged */
56683){
56684  struct RowSetEntry head;
56685  struct RowSetEntry *pTail;
56686
56687  pTail = &head;
56688  assert( pA!=0 && pB!=0 );
56689  for(;;){
56690    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
56691    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
56692    if( pA->v<=pB->v ){
56693      if( pA->v<pB->v ) pTail = pTail->pRight = pA;
56694      pA = pA->pRight;
56695      if( pA==0 ){
56696        pTail->pRight = pB;
56697        break;
56698      }
56699    }else{
56700      pTail = pTail->pRight = pB;
56701      pB = pB->pRight;
56702      if( pB==0 ){
56703        pTail->pRight = pA;
56704        break;
56705      }
56706    }
56707  }
56708  return head.pRight;
56709}
56710
56711/*
56712** Sort all elements on the list of RowSetEntry objects into order of
56713** increasing v.
56714*/
56715static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
56716  unsigned int i;
56717  struct RowSetEntry *pNext, *aBucket[40];
56718
56719  memset(aBucket, 0, sizeof(aBucket));
56720  while( pIn ){
56721    pNext = pIn->pRight;
56722    pIn->pRight = 0;
56723    for(i=0; aBucket[i]; i++){
56724      pIn = rowSetEntryMerge(aBucket[i], pIn);
56725      aBucket[i] = 0;
56726    }
56727    aBucket[i] = pIn;
56728    pIn = pNext;
56729  }
56730  pIn = aBucket[0];
56731  for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
56732    if( aBucket[i]==0 ) continue;
56733    pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
56734  }
56735  return pIn;
56736}
56737
56738
56739/*
56740** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
56741** Convert this tree into a linked list connected by the pRight pointers
56742** and return pointers to the first and last elements of the new list.
56743*/
56744static void rowSetTreeToList(
56745  struct RowSetEntry *pIn,         /* Root of the input tree */
56746  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
56747  struct RowSetEntry **ppLast      /* Write tail of the output list here */
56748){
56749  assert( pIn!=0 );
56750  if( pIn->pLeft ){
56751    struct RowSetEntry *p;
56752    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
56753    p->pRight = pIn;
56754  }else{
56755    *ppFirst = pIn;
56756  }
56757  if( pIn->pRight ){
56758    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
56759  }else{
56760    *ppLast = pIn;
56761  }
56762  assert( (*ppLast)->pRight==0 );
56763}
56764
56765
56766/*
56767** Convert a sorted list of elements (connected by pRight) into a binary
56768** tree with depth of iDepth.  A depth of 1 means the tree contains a single
56769** node taken from the head of *ppList.  A depth of 2 means a tree with
56770** three nodes.  And so forth.
56771**
56772** Use as many entries from the input list as required and update the
56773** *ppList to point to the unused elements of the list.  If the input
56774** list contains too few elements, then construct an incomplete tree
56775** and leave *ppList set to NULL.
56776**
56777** Return a pointer to the root of the constructed binary tree.
56778*/
56779static struct RowSetEntry *rowSetNDeepTree(
56780  struct RowSetEntry **ppList,
56781  int iDepth
56782){
56783  struct RowSetEntry *p;         /* Root of the new tree */
56784  struct RowSetEntry *pLeft;     /* Left subtree */
56785  if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
56786    /* Prevent unnecessary deep recursion when we run out of entries */
56787    return 0;
56788  }
56789  if( iDepth>1 ){   /*OPTIMIZATION-IF-TRUE*/
56790    /* This branch causes a *balanced* tree to be generated.  A valid tree
56791    ** is still generated without this branch, but the tree is wildly
56792    ** unbalanced and inefficient. */
56793    pLeft = rowSetNDeepTree(ppList, iDepth-1);
56794    p = *ppList;
56795    if( p==0 ){     /*OPTIMIZATION-IF-FALSE*/
56796      /* It is safe to always return here, but the resulting tree
56797      ** would be unbalanced */
56798      return pLeft;
56799    }
56800    p->pLeft = pLeft;
56801    *ppList = p->pRight;
56802    p->pRight = rowSetNDeepTree(ppList, iDepth-1);
56803  }else{
56804    p = *ppList;
56805    *ppList = p->pRight;
56806    p->pLeft = p->pRight = 0;
56807  }
56808  return p;
56809}
56810
56811/*
56812** Convert a sorted list of elements into a binary tree. Make the tree
56813** as deep as it needs to be in order to contain the entire list.
56814*/
56815static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
56816  int iDepth;           /* Depth of the tree so far */
56817  struct RowSetEntry *p;       /* Current tree root */
56818  struct RowSetEntry *pLeft;   /* Left subtree */
56819
56820  assert( pList!=0 );
56821  p = pList;
56822  pList = p->pRight;
56823  p->pLeft = p->pRight = 0;
56824  for(iDepth=1; pList; iDepth++){
56825    pLeft = p;
56826    p = pList;
56827    pList = p->pRight;
56828    p->pLeft = pLeft;
56829    p->pRight = rowSetNDeepTree(&pList, iDepth);
56830  }
56831  return p;
56832}
56833
56834/*
56835** Extract the smallest element from the RowSet.
56836** Write the element into *pRowid.  Return 1 on success.  Return
56837** 0 if the RowSet is already empty.
56838**
56839** After this routine has been called, the sqlite3RowSetInsert()
56840** routine may not be called again.
56841**
56842** This routine may not be called after sqlite3RowSetTest() has
56843** been used.  Older versions of RowSet allowed that, but as the
56844** capability was not used by the code generator, it was removed
56845** for code economy.
56846*/
56847SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
56848  assert( p!=0 );
56849  assert( p->pForest==0 );  /* Cannot be used with sqlite3RowSetText() */
56850
56851  /* Merge the forest into a single sorted list on first call */
56852  if( (p->rsFlags & ROWSET_NEXT)==0 ){  /*OPTIMIZATION-IF-FALSE*/
56853    if( (p->rsFlags & ROWSET_SORTED)==0 ){  /*OPTIMIZATION-IF-FALSE*/
56854      p->pEntry = rowSetEntrySort(p->pEntry);
56855    }
56856    p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
56857  }
56858
56859  /* Return the next entry on the list */
56860  if( p->pEntry ){
56861    *pRowid = p->pEntry->v;
56862    p->pEntry = p->pEntry->pRight;
56863    if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
56864      /* Free memory immediately, rather than waiting on sqlite3_finalize() */
56865      sqlite3RowSetClear(p);
56866    }
56867    return 1;
56868  }else{
56869    return 0;
56870  }
56871}
56872
56873/*
56874** Check to see if element iRowid was inserted into the rowset as
56875** part of any insert batch prior to iBatch.  Return 1 or 0.
56876**
56877** If this is the first test of a new batch and if there exist entries
56878** on pRowSet->pEntry, then sort those entries into the forest at
56879** pRowSet->pForest so that they can be tested.
56880*/
56881SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
56882  struct RowSetEntry *p, *pTree;
56883
56884  /* This routine is never called after sqlite3RowSetNext() */
56885  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
56886
56887  /* Sort entries into the forest on the first test of a new batch.
56888  ** To save unnecessary work, only do this when the batch number changes.
56889  */
56890  if( iBatch!=pRowSet->iBatch ){  /*OPTIMIZATION-IF-FALSE*/
56891    p = pRowSet->pEntry;
56892    if( p ){
56893      struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
56894      if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
56895        /* Only sort the current set of entries if they need it */
56896        p = rowSetEntrySort(p);
56897      }
56898      for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
56899        ppPrevTree = &pTree->pRight;
56900        if( pTree->pLeft==0 ){
56901          pTree->pLeft = rowSetListToTree(p);
56902          break;
56903        }else{
56904          struct RowSetEntry *pAux, *pTail;
56905          rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
56906          pTree->pLeft = 0;
56907          p = rowSetEntryMerge(pAux, p);
56908        }
56909      }
56910      if( pTree==0 ){
56911        *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
56912        if( pTree ){
56913          pTree->v = 0;
56914          pTree->pRight = 0;
56915          pTree->pLeft = rowSetListToTree(p);
56916        }
56917      }
56918      pRowSet->pEntry = 0;
56919      pRowSet->pLast = 0;
56920      pRowSet->rsFlags |= ROWSET_SORTED;
56921    }
56922    pRowSet->iBatch = iBatch;
56923  }
56924
56925  /* Test to see if the iRowid value appears anywhere in the forest.
56926  ** Return 1 if it does and 0 if not.
56927  */
56928  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
56929    p = pTree->pLeft;
56930    while( p ){
56931      if( p->v<iRowid ){
56932        p = p->pRight;
56933      }else if( p->v>iRowid ){
56934        p = p->pLeft;
56935      }else{
56936        return 1;
56937      }
56938    }
56939  }
56940  return 0;
56941}
56942
56943/************** End of rowset.c **********************************************/
56944/************** Begin file pager.c *******************************************/
56945/*
56946** 2001 September 15
56947**
56948** The author disclaims copyright to this source code.  In place of
56949** a legal notice, here is a blessing:
56950**
56951**    May you do good and not evil.
56952**    May you find forgiveness for yourself and forgive others.
56953**    May you share freely, never taking more than you give.
56954**
56955*************************************************************************
56956** This is the implementation of the page cache subsystem or "pager".
56957**
56958** The pager is used to access a database disk file.  It implements
56959** atomic commit and rollback through the use of a journal file that
56960** is separate from the database file.  The pager also implements file
56961** locking to prevent two processes from writing the same database
56962** file simultaneously, or one process from reading the database while
56963** another is writing.
56964*/
56965#ifndef SQLITE_OMIT_DISKIO
56966/* #include "sqliteInt.h" */
56967/************** Include wal.h in the middle of pager.c ***********************/
56968/************** Begin file wal.h *********************************************/
56969/*
56970** 2010 February 1
56971**
56972** The author disclaims copyright to this source code.  In place of
56973** a legal notice, here is a blessing:
56974**
56975**    May you do good and not evil.
56976**    May you find forgiveness for yourself and forgive others.
56977**    May you share freely, never taking more than you give.
56978**
56979*************************************************************************
56980** This header file defines the interface to the write-ahead logging
56981** system. Refer to the comments below and the header comment attached to
56982** the implementation of each function in log.c for further details.
56983*/
56984
56985#ifndef SQLITE_WAL_H
56986#define SQLITE_WAL_H
56987
56988/* #include "sqliteInt.h" */
56989
56990/* Macros for extracting appropriate sync flags for either transaction
56991** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
56992*/
56993#define WAL_SYNC_FLAGS(X)   ((X)&0x03)
56994#define CKPT_SYNC_FLAGS(X)  (((X)>>2)&0x03)
56995
56996#ifdef SQLITE_OMIT_WAL
56997# define sqlite3WalOpen(x,y,z)                   0
56998# define sqlite3WalLimit(x,y)
56999# define sqlite3WalClose(v,w,x,y,z)              0
57000# define sqlite3WalBeginReadTransaction(y,z)     0
57001# define sqlite3WalEndReadTransaction(z)
57002# define sqlite3WalDbsize(y)                     0
57003# define sqlite3WalBeginWriteTransaction(y)      0
57004# define sqlite3WalEndWriteTransaction(x)        0
57005# define sqlite3WalUndo(x,y,z)                   0
57006# define sqlite3WalSavepoint(y,z)
57007# define sqlite3WalSavepointUndo(y,z)            0
57008# define sqlite3WalFrames(u,v,w,x,y,z)           0
57009# define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
57010# define sqlite3WalCallback(z)                   0
57011# define sqlite3WalExclusiveMode(y,z)            0
57012# define sqlite3WalHeapMemory(z)                 0
57013# define sqlite3WalFramesize(z)                  0
57014# define sqlite3WalFindFrame(x,y,z)              0
57015# define sqlite3WalFile(x)                       0
57016# undef SQLITE_USE_SEH
57017#else
57018
57019#define WAL_SAVEPOINT_NDATA 4
57020
57021/* Connection to a write-ahead log (WAL) file.
57022** There is one object of this type for each pager.
57023*/
57024typedef struct Wal Wal;
57025
57026/* Open and close a connection to a write-ahead log. */
57027SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
57028SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
57029
57030/* Set the limiting size of a WAL file. */
57031SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
57032
57033/* Used by readers to open (lock) and close (unlock) a snapshot.  A
57034** snapshot is like a read-transaction.  It is the state of the database
57035** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
57036** preserves the current state even if the other threads or processes
57037** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
57038** transaction and releases the lock.
57039*/
57040SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
57041SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
57042
57043/* Read a page from the write-ahead log, if it is present. */
57044SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
57045SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
57046
57047/* If the WAL is not empty, return the size of the database. */
57048SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
57049
57050/* Obtain or release the WRITER lock. */
57051SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
57052SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
57053
57054/* Undo any frames written (but not committed) to the log */
57055SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
57056
57057/* Return an integer that records the current (uncommitted) write
57058** position in the WAL */
57059SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
57060
57061/* Move the write position of the WAL back to iFrame.  Called in
57062** response to a ROLLBACK TO command. */
57063SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
57064
57065/* Write a frame or frames to the log. */
57066SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
57067
57068/* Copy pages from the log to the database file */
57069SQLITE_PRIVATE int sqlite3WalCheckpoint(
57070  Wal *pWal,                      /* Write-ahead log connection */
57071  sqlite3 *db,                    /* Check this handle's interrupt flag */
57072  int eMode,                      /* One of PASSIVE, FULL and RESTART */
57073  int (*xBusy)(void*),            /* Function to call when busy */
57074  void *pBusyArg,                 /* Context argument for xBusyHandler */
57075  int sync_flags,                 /* Flags to sync db file with (or 0) */
57076  int nBuf,                       /* Size of buffer nBuf */
57077  u8 *zBuf,                       /* Temporary buffer to use */
57078  int *pnLog,                     /* OUT: Number of frames in WAL */
57079  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
57080);
57081
57082/* Return the value to pass to a sqlite3_wal_hook callback, the
57083** number of frames in the WAL at the point of the last commit since
57084** sqlite3WalCallback() was called.  If no commits have occurred since
57085** the last call, then return 0.
57086*/
57087SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
57088
57089/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
57090** by the pager layer on the database file.
57091*/
57092SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
57093
57094/* Return true if the argument is non-NULL and the WAL module is using
57095** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
57096** WAL module is using shared-memory, return false.
57097*/
57098SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
57099
57100#ifdef SQLITE_ENABLE_SNAPSHOT
57101SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
57102SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
57103SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
57104SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot);
57105SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal);
57106#endif
57107
57108#ifdef SQLITE_ENABLE_ZIPVFS
57109/* If the WAL file is not empty, return the number of bytes of content
57110** stored in each frame (i.e. the db page-size when the WAL was created).
57111*/
57112SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
57113#endif
57114
57115/* Return the sqlite3_file object for the WAL file */
57116SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
57117
57118#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
57119SQLITE_PRIVATE int sqlite3WalWriteLock(Wal *pWal, int bLock);
57120SQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db);
57121#endif
57122
57123#ifdef SQLITE_USE_SEH
57124SQLITE_PRIVATE int sqlite3WalSystemErrno(Wal*);
57125#endif
57126
57127#endif /* ifndef SQLITE_OMIT_WAL */
57128#endif /* SQLITE_WAL_H */
57129
57130/************** End of wal.h *************************************************/
57131/************** Continuing where we left off in pager.c **********************/
57132
57133
57134/******************* NOTES ON THE DESIGN OF THE PAGER ************************
57135**
57136** This comment block describes invariants that hold when using a rollback
57137** journal.  These invariants do not apply for journal_mode=WAL,
57138** journal_mode=MEMORY, or journal_mode=OFF.
57139**
57140** Within this comment block, a page is deemed to have been synced
57141** automatically as soon as it is written when PRAGMA synchronous=OFF.
57142** Otherwise, the page is not synced until the xSync method of the VFS
57143** is called successfully on the file containing the page.
57144**
57145** Definition:  A page of the database file is said to be "overwriteable" if
57146** one or more of the following are true about the page:
57147**
57148**     (a)  The original content of the page as it was at the beginning of
57149**          the transaction has been written into the rollback journal and
57150**          synced.
57151**
57152**     (b)  The page was a freelist leaf page at the start of the transaction.
57153**
57154**     (c)  The page number is greater than the largest page that existed in
57155**          the database file at the start of the transaction.
57156**
57157** (1) A page of the database file is never overwritten unless one of the
57158**     following are true:
57159**
57160**     (a) The page and all other pages on the same sector are overwriteable.
57161**
57162**     (b) The atomic page write optimization is enabled, and the entire
57163**         transaction other than the update of the transaction sequence
57164**         number consists of a single page change.
57165**
57166** (2) The content of a page written into the rollback journal exactly matches
57167**     both the content in the database when the rollback journal was written
57168**     and the content in the database at the beginning of the current
57169**     transaction.
57170**
57171** (3) Writes to the database file are an integer multiple of the page size
57172**     in length and are aligned on a page boundary.
57173**
57174** (4) Reads from the database file are either aligned on a page boundary and
57175**     an integer multiple of the page size in length or are taken from the
57176**     first 100 bytes of the database file.
57177**
57178** (5) All writes to the database file are synced prior to the rollback journal
57179**     being deleted, truncated, or zeroed.
57180**
57181** (6) If a super-journal file is used, then all writes to the database file
57182**     are synced prior to the super-journal being deleted.
57183**
57184** Definition: Two databases (or the same database at two points it time)
57185** are said to be "logically equivalent" if they give the same answer to
57186** all queries.  Note in particular the content of freelist leaf
57187** pages can be changed arbitrarily without affecting the logical equivalence
57188** of the database.
57189**
57190** (7) At any time, if any subset, including the empty set and the total set,
57191**     of the unsynced changes to a rollback journal are removed and the
57192**     journal is rolled back, the resulting database file will be logically
57193**     equivalent to the database file at the beginning of the transaction.
57194**
57195** (8) When a transaction is rolled back, the xTruncate method of the VFS
57196**     is called to restore the database file to the same size it was at
57197**     the beginning of the transaction.  (In some VFSes, the xTruncate
57198**     method is a no-op, but that does not change the fact the SQLite will
57199**     invoke it.)
57200**
57201** (9) Whenever the database file is modified, at least one bit in the range
57202**     of bytes from 24 through 39 inclusive will be changed prior to releasing
57203**     the EXCLUSIVE lock, thus signaling other connections on the same
57204**     database to flush their caches.
57205**
57206** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
57207**      than one billion transactions.
57208**
57209** (11) A database file is well-formed at the beginning and at the conclusion
57210**      of every transaction.
57211**
57212** (12) An EXCLUSIVE lock is held on the database file when writing to
57213**      the database file.
57214**
57215** (13) A SHARED lock is held on the database file while reading any
57216**      content out of the database file.
57217**
57218******************************************************************************/
57219
57220/*
57221** Macros for troubleshooting.  Normally turned off
57222*/
57223#if 0
57224int sqlite3PagerTrace=1;  /* True to enable tracing */
57225#define sqlite3DebugPrintf printf
57226#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
57227#else
57228#define PAGERTRACE(X)
57229#endif
57230
57231/*
57232** The following two macros are used within the PAGERTRACE() macros above
57233** to print out file-descriptors.
57234**
57235** PAGERID() takes a pointer to a Pager struct as its argument. The
57236** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
57237** struct as its argument.
57238*/
57239#define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
57240#define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
57241
57242/*
57243** The Pager.eState variable stores the current 'state' of a pager. A
57244** pager may be in any one of the seven states shown in the following
57245** state diagram.
57246**
57247**                            OPEN <------+------+
57248**                              |         |      |
57249**                              V         |      |
57250**               +---------> READER-------+      |
57251**               |              |                |
57252**               |              V                |
57253**               |<-------WRITER_LOCKED------> ERROR
57254**               |              |                ^
57255**               |              V                |
57256**               |<------WRITER_CACHEMOD-------->|
57257**               |              |                |
57258**               |              V                |
57259**               |<-------WRITER_DBMOD---------->|
57260**               |              |                |
57261**               |              V                |
57262**               +<------WRITER_FINISHED-------->+
57263**
57264**
57265** List of state transitions and the C [function] that performs each:
57266**
57267**   OPEN              -> READER              [sqlite3PagerSharedLock]
57268**   READER            -> OPEN                [pager_unlock]
57269**
57270**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
57271**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
57272**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
57273**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
57274**   WRITER_***        -> READER              [pager_end_transaction]
57275**
57276**   WRITER_***        -> ERROR               [pager_error]
57277**   ERROR             -> OPEN                [pager_unlock]
57278**
57279**
57280**  OPEN:
57281**
57282**    The pager starts up in this state. Nothing is guaranteed in this
57283**    state - the file may or may not be locked and the database size is
57284**    unknown. The database may not be read or written.
57285**
57286**    * No read or write transaction is active.
57287**    * Any lock, or no lock at all, may be held on the database file.
57288**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
57289**
57290**  READER:
57291**
57292**    In this state all the requirements for reading the database in
57293**    rollback (non-WAL) mode are met. Unless the pager is (or recently
57294**    was) in exclusive-locking mode, a user-level read transaction is
57295**    open. The database size is known in this state.
57296**
57297**    A connection running with locking_mode=normal enters this state when
57298**    it opens a read-transaction on the database and returns to state
57299**    OPEN after the read-transaction is completed. However a connection
57300**    running in locking_mode=exclusive (including temp databases) remains in
57301**    this state even after the read-transaction is closed. The only way
57302**    a locking_mode=exclusive connection can transition from READER to OPEN
57303**    is via the ERROR state (see below).
57304**
57305**    * A read transaction may be active (but a write-transaction cannot).
57306**    * A SHARED or greater lock is held on the database file.
57307**    * The dbSize variable may be trusted (even if a user-level read
57308**      transaction is not active). The dbOrigSize and dbFileSize variables
57309**      may not be trusted at this point.
57310**    * If the database is a WAL database, then the WAL connection is open.
57311**    * Even if a read-transaction is not open, it is guaranteed that
57312**      there is no hot-journal in the file-system.
57313**
57314**  WRITER_LOCKED:
57315**
57316**    The pager moves to this state from READER when a write-transaction
57317**    is first opened on the database. In WRITER_LOCKED state, all locks
57318**    required to start a write-transaction are held, but no actual
57319**    modifications to the cache or database have taken place.
57320**
57321**    In rollback mode, a RESERVED or (if the transaction was opened with
57322**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
57323**    moving to this state, but the journal file is not written to or opened
57324**    to in this state. If the transaction is committed or rolled back while
57325**    in WRITER_LOCKED state, all that is required is to unlock the database
57326**    file.
57327**
57328**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
57329**    If the connection is running with locking_mode=exclusive, an attempt
57330**    is made to obtain an EXCLUSIVE lock on the database file.
57331**
57332**    * A write transaction is active.
57333**    * If the connection is open in rollback-mode, a RESERVED or greater
57334**      lock is held on the database file.
57335**    * If the connection is open in WAL-mode, a WAL write transaction
57336**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
57337**      called).
57338**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
57339**    * The contents of the pager cache have not been modified.
57340**    * The journal file may or may not be open.
57341**    * Nothing (not even the first header) has been written to the journal.
57342**
57343**  WRITER_CACHEMOD:
57344**
57345**    A pager moves from WRITER_LOCKED state to this state when a page is
57346**    first modified by the upper layer. In rollback mode the journal file
57347**    is opened (if it is not already open) and a header written to the
57348**    start of it. The database file on disk has not been modified.
57349**
57350**    * A write transaction is active.
57351**    * A RESERVED or greater lock is held on the database file.
57352**    * The journal file is open and the first header has been written
57353**      to it, but the header has not been synced to disk.
57354**    * The contents of the page cache have been modified.
57355**
57356**  WRITER_DBMOD:
57357**
57358**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
57359**    when it modifies the contents of the database file. WAL connections
57360**    never enter this state (since they do not modify the database file,
57361**    just the log file).
57362**
57363**    * A write transaction is active.
57364**    * An EXCLUSIVE or greater lock is held on the database file.
57365**    * The journal file is open and the first header has been written
57366**      and synced to disk.
57367**    * The contents of the page cache have been modified (and possibly
57368**      written to disk).
57369**
57370**  WRITER_FINISHED:
57371**
57372**    It is not possible for a WAL connection to enter this state.
57373**
57374**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
57375**    state after the entire transaction has been successfully written into the
57376**    database file. In this state the transaction may be committed simply
57377**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
57378**    not possible to modify the database further. At this point, the upper
57379**    layer must either commit or rollback the transaction.
57380**
57381**    * A write transaction is active.
57382**    * An EXCLUSIVE or greater lock is held on the database file.
57383**    * All writing and syncing of journal and database data has finished.
57384**      If no error occurred, all that remains is to finalize the journal to
57385**      commit the transaction. If an error did occur, the caller will need
57386**      to rollback the transaction.
57387**
57388**  ERROR:
57389**
57390**    The ERROR state is entered when an IO or disk-full error (including
57391**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
57392**    difficult to be sure that the in-memory pager state (cache contents,
57393**    db size etc.) are consistent with the contents of the file-system.
57394**
57395**    Temporary pager files may enter the ERROR state, but in-memory pagers
57396**    cannot.
57397**
57398**    For example, if an IO error occurs while performing a rollback,
57399**    the contents of the page-cache may be left in an inconsistent state.
57400**    At this point it would be dangerous to change back to READER state
57401**    (as usually happens after a rollback). Any subsequent readers might
57402**    report database corruption (due to the inconsistent cache), and if
57403**    they upgrade to writers, they may inadvertently corrupt the database
57404**    file. To avoid this hazard, the pager switches into the ERROR state
57405**    instead of READER following such an error.
57406**
57407**    Once it has entered the ERROR state, any attempt to use the pager
57408**    to read or write data returns an error. Eventually, once all
57409**    outstanding transactions have been abandoned, the pager is able to
57410**    transition back to OPEN state, discarding the contents of the
57411**    page-cache and any other in-memory state at the same time. Everything
57412**    is reloaded from disk (and, if necessary, hot-journal rollback performed)
57413**    when a read-transaction is next opened on the pager (transitioning
57414**    the pager into READER state). At that point the system has recovered
57415**    from the error.
57416**
57417**    Specifically, the pager jumps into the ERROR state if:
57418**
57419**      1. An error occurs while attempting a rollback. This happens in
57420**         function sqlite3PagerRollback().
57421**
57422**      2. An error occurs while attempting to finalize a journal file
57423**         following a commit in function sqlite3PagerCommitPhaseTwo().
57424**
57425**      3. An error occurs while attempting to write to the journal or
57426**         database file in function pagerStress() in order to free up
57427**         memory.
57428**
57429**    In other cases, the error is returned to the b-tree layer. The b-tree
57430**    layer then attempts a rollback operation. If the error condition
57431**    persists, the pager enters the ERROR state via condition (1) above.
57432**
57433**    Condition (3) is necessary because it can be triggered by a read-only
57434**    statement executed within a transaction. In this case, if the error
57435**    code were simply returned to the user, the b-tree layer would not
57436**    automatically attempt a rollback, as it assumes that an error in a
57437**    read-only statement cannot leave the pager in an internally inconsistent
57438**    state.
57439**
57440**    * The Pager.errCode variable is set to something other than SQLITE_OK.
57441**    * There are one or more outstanding references to pages (after the
57442**      last reference is dropped the pager should move back to OPEN state).
57443**    * The pager is not an in-memory pager.
57444**
57445**
57446** Notes:
57447**
57448**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
57449**     connection is open in WAL mode. A WAL connection is always in one
57450**     of the first four states.
57451**
57452**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
57453**     state. There are two exceptions: immediately after exclusive-mode has
57454**     been turned on (and before any read or write transactions are
57455**     executed), and when the pager is leaving the "error state".
57456**
57457**   * See also: assert_pager_state().
57458*/
57459#define PAGER_OPEN                  0
57460#define PAGER_READER                1
57461#define PAGER_WRITER_LOCKED         2
57462#define PAGER_WRITER_CACHEMOD       3
57463#define PAGER_WRITER_DBMOD          4
57464#define PAGER_WRITER_FINISHED       5
57465#define PAGER_ERROR                 6
57466
57467/*
57468** The Pager.eLock variable is almost always set to one of the
57469** following locking-states, according to the lock currently held on
57470** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
57471** This variable is kept up to date as locks are taken and released by
57472** the pagerLockDb() and pagerUnlockDb() wrappers.
57473**
57474** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
57475** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
57476** the operation was successful. In these circumstances pagerLockDb() and
57477** pagerUnlockDb() take a conservative approach - eLock is always updated
57478** when unlocking the file, and only updated when locking the file if the
57479** VFS call is successful. This way, the Pager.eLock variable may be set
57480** to a less exclusive (lower) value than the lock that is actually held
57481** at the system level, but it is never set to a more exclusive value.
57482**
57483** This is usually safe. If an xUnlock fails or appears to fail, there may
57484** be a few redundant xLock() calls or a lock may be held for longer than
57485** required, but nothing really goes wrong.
57486**
57487** The exception is when the database file is unlocked as the pager moves
57488** from ERROR to OPEN state. At this point there may be a hot-journal file
57489** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
57490** transition, by the same pager or any other). If the call to xUnlock()
57491** fails at this point and the pager is left holding an EXCLUSIVE lock, this
57492** can confuse the call to xCheckReservedLock() call made later as part
57493** of hot-journal detection.
57494**
57495** xCheckReservedLock() is defined as returning true "if there is a RESERVED
57496** lock held by this process or any others". So xCheckReservedLock may
57497** return true because the caller itself is holding an EXCLUSIVE lock (but
57498** doesn't know it because of a previous error in xUnlock). If this happens
57499** a hot-journal may be mistaken for a journal being created by an active
57500** transaction in another process, causing SQLite to read from the database
57501** without rolling it back.
57502**
57503** To work around this, if a call to xUnlock() fails when unlocking the
57504** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
57505** is only changed back to a real locking state after a successful call
57506** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
57507** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
57508** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
57509** lock on the database file before attempting to roll it back. See function
57510** PagerSharedLock() for more detail.
57511**
57512** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
57513** PAGER_OPEN state.
57514*/
57515#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
57516
57517/*
57518** The maximum allowed sector size. 64KiB. If the xSectorsize() method
57519** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
57520** This could conceivably cause corruption following a power failure on
57521** such a system. This is currently an undocumented limit.
57522*/
57523#define MAX_SECTOR_SIZE 0x10000
57524
57525
57526/*
57527** An instance of the following structure is allocated for each active
57528** savepoint and statement transaction in the system. All such structures
57529** are stored in the Pager.aSavepoint[] array, which is allocated and
57530** resized using sqlite3Realloc().
57531**
57532** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
57533** set to 0. If a journal-header is written into the main journal while
57534** the savepoint is active, then iHdrOffset is set to the byte offset
57535** immediately following the last journal record written into the main
57536** journal before the journal-header. This is required during savepoint
57537** rollback (see pagerPlaybackSavepoint()).
57538*/
57539typedef struct PagerSavepoint PagerSavepoint;
57540struct PagerSavepoint {
57541  i64 iOffset;                 /* Starting offset in main journal */
57542  i64 iHdrOffset;              /* See above */
57543  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
57544  Pgno nOrig;                  /* Original number of pages in file */
57545  Pgno iSubRec;                /* Index of first record in sub-journal */
57546  int bTruncateOnRelease;      /* If stmt journal may be truncated on RELEASE */
57547#ifndef SQLITE_OMIT_WAL
57548  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
57549#endif
57550};
57551
57552/*
57553** Bits of the Pager.doNotSpill flag.  See further description below.
57554*/
57555#define SPILLFLAG_OFF         0x01 /* Never spill cache.  Set via pragma */
57556#define SPILLFLAG_ROLLBACK    0x02 /* Current rolling back, so do not spill */
57557#define SPILLFLAG_NOSYNC      0x04 /* Spill is ok, but do not sync */
57558
57559/*
57560** An open page cache is an instance of struct Pager. A description of
57561** some of the more important member variables follows:
57562**
57563** eState
57564**
57565**   The current 'state' of the pager object. See the comment and state
57566**   diagram above for a description of the pager state.
57567**
57568** eLock
57569**
57570**   For a real on-disk database, the current lock held on the database file -
57571**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
57572**
57573**   For a temporary or in-memory database (neither of which require any
57574**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
57575**   databases always have Pager.exclusiveMode==1, this tricks the pager
57576**   logic into thinking that it already has all the locks it will ever
57577**   need (and no reason to release them).
57578**
57579**   In some (obscure) circumstances, this variable may also be set to
57580**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
57581**   details.
57582**
57583** changeCountDone
57584**
57585**   This boolean variable is used to make sure that the change-counter
57586**   (the 4-byte header field at byte offset 24 of the database file) is
57587**   not updated more often than necessary.
57588**
57589**   It is set to true when the change-counter field is updated, which
57590**   can only happen if an exclusive lock is held on the database file.
57591**   It is cleared (set to false) whenever an exclusive lock is
57592**   relinquished on the database file. Each time a transaction is committed,
57593**   The changeCountDone flag is inspected. If it is true, the work of
57594**   updating the change-counter is omitted for the current transaction.
57595**
57596**   This mechanism means that when running in exclusive mode, a connection
57597**   need only update the change-counter once, for the first transaction
57598**   committed.
57599**
57600** setSuper
57601**
57602**   When PagerCommitPhaseOne() is called to commit a transaction, it may
57603**   (or may not) specify a super-journal name to be written into the
57604**   journal file before it is synced to disk.
57605**
57606**   Whether or not a journal file contains a super-journal pointer affects
57607**   the way in which the journal file is finalized after the transaction is
57608**   committed or rolled back when running in "journal_mode=PERSIST" mode.
57609**   If a journal file does not contain a super-journal pointer, it is
57610**   finalized by overwriting the first journal header with zeroes. If
57611**   it does contain a super-journal pointer the journal file is finalized
57612**   by truncating it to zero bytes, just as if the connection were
57613**   running in "journal_mode=truncate" mode.
57614**
57615**   Journal files that contain super-journal pointers cannot be finalized
57616**   simply by overwriting the first journal-header with zeroes, as the
57617**   super-journal pointer could interfere with hot-journal rollback of any
57618**   subsequently interrupted transaction that reuses the journal file.
57619**
57620**   The flag is cleared as soon as the journal file is finalized (either
57621**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
57622**   journal file from being successfully finalized, the setSuper flag
57623**   is cleared anyway (and the pager will move to ERROR state).
57624**
57625** doNotSpill
57626**
57627**   This variables control the behavior of cache-spills  (calls made by
57628**   the pcache module to the pagerStress() routine to write cached data
57629**   to the file-system in order to free up memory).
57630**
57631**   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
57632**   writing to the database from pagerStress() is disabled altogether.
57633**   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
57634**   comes up during savepoint rollback that requires the pcache module
57635**   to allocate a new page to prevent the journal file from being written
57636**   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
57637**   case is a user preference.
57638**
57639**   If the SPILLFLAG_NOSYNC bit is set, writing to the database from
57640**   pagerStress() is permitted, but syncing the journal file is not.
57641**   This flag is set by sqlite3PagerWrite() when the file-system sector-size
57642**   is larger than the database page-size in order to prevent a journal sync
57643**   from happening in between the journalling of two pages on the same sector.
57644**
57645** subjInMemory
57646**
57647**   This is a boolean variable. If true, then any required sub-journal
57648**   is opened as an in-memory journal file. If false, then in-memory
57649**   sub-journals are only used for in-memory pager files.
57650**
57651**   This variable is updated by the upper layer each time a new
57652**   write-transaction is opened.
57653**
57654** dbSize, dbOrigSize, dbFileSize
57655**
57656**   Variable dbSize is set to the number of pages in the database file.
57657**   It is valid in PAGER_READER and higher states (all states except for
57658**   OPEN and ERROR).
57659**
57660**   dbSize is set based on the size of the database file, which may be
57661**   larger than the size of the database (the value stored at offset
57662**   28 of the database header by the btree). If the size of the file
57663**   is not an integer multiple of the page-size, the value stored in
57664**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
57665**   Except, any file that is greater than 0 bytes in size is considered
57666**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
57667**   to dbSize==1).
57668**
57669**   During a write-transaction, if pages with page-numbers greater than
57670**   dbSize are modified in the cache, dbSize is updated accordingly.
57671**   Similarly, if the database is truncated using PagerTruncateImage(),
57672**   dbSize is updated.
57673**
57674**   Variables dbOrigSize and dbFileSize are valid in states
57675**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
57676**   variable at the start of the transaction. It is used during rollback,
57677**   and to determine whether or not pages need to be journalled before
57678**   being modified.
57679**
57680**   Throughout a write-transaction, dbFileSize contains the size of
57681**   the file on disk in pages. It is set to a copy of dbSize when the
57682**   write-transaction is first opened, and updated when VFS calls are made
57683**   to write or truncate the database file on disk.
57684**
57685**   The only reason the dbFileSize variable is required is to suppress
57686**   unnecessary calls to xTruncate() after committing a transaction. If,
57687**   when a transaction is committed, the dbFileSize variable indicates
57688**   that the database file is larger than the database image (Pager.dbSize),
57689**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
57690**   to measure the database file on disk, and then truncates it if required.
57691**   dbFileSize is not used when rolling back a transaction. In this case
57692**   pager_truncate() is called unconditionally (which means there may be
57693**   a call to xFilesize() that is not strictly required). In either case,
57694**   pager_truncate() may cause the file to become smaller or larger.
57695**
57696** dbHintSize
57697**
57698**   The dbHintSize variable is used to limit the number of calls made to
57699**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
57700**
57701**   dbHintSize is set to a copy of the dbSize variable when a
57702**   write-transaction is opened (at the same time as dbFileSize and
57703**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
57704**   dbHintSize is increased to the number of pages that correspond to the
57705**   size-hint passed to the method call. See pager_write_pagelist() for
57706**   details.
57707**
57708** errCode
57709**
57710**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
57711**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
57712**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
57713**   sub-codes.
57714**
57715** syncFlags, walSyncFlags
57716**
57717**   syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
57718**   syncFlags is used for rollback mode.  walSyncFlags is used for WAL mode
57719**   and contains the flags used to sync the checkpoint operations in the
57720**   lower two bits, and sync flags used for transaction commits in the WAL
57721**   file in bits 0x04 and 0x08.  In other words, to get the correct sync flags
57722**   for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
57723**   sync flags for transaction commit, use ((walSyncFlags>>2)&0x03).  Note
57724**   that with synchronous=NORMAL in WAL mode, transaction commit is not synced
57725**   meaning that the 0x04 and 0x08 bits are both zero.
57726*/
57727struct Pager {
57728  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
57729  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
57730  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
57731  u8 useJournal;              /* Use a rollback journal on this file */
57732  u8 noSync;                  /* Do not sync the journal if true */
57733  u8 fullSync;                /* Do extra syncs of the journal for robustness */
57734  u8 extraSync;               /* sync directory after journal delete */
57735  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
57736  u8 walSyncFlags;            /* See description above */
57737  u8 tempFile;                /* zFilename is a temporary or immutable file */
57738  u8 noLock;                  /* Do not lock (except in WAL mode) */
57739  u8 readOnly;                /* True for a read-only database */
57740  u8 memDb;                   /* True to inhibit all file I/O */
57741  u8 memVfs;                  /* VFS-implemented memory database */
57742
57743  /**************************************************************************
57744  ** The following block contains those class members that change during
57745  ** routine operation.  Class members not in this block are either fixed
57746  ** when the pager is first created or else only change when there is a
57747  ** significant mode change (such as changing the page_size, locking_mode,
57748  ** or the journal_mode).  From another view, these class members describe
57749  ** the "state" of the pager, while other class members describe the
57750  ** "configuration" of the pager.
57751  */
57752  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
57753  u8 eLock;                   /* Current lock held on database file */
57754  u8 changeCountDone;         /* Set after incrementing the change-counter */
57755  u8 setSuper;                /* Super-jrnl name is written into jrnl */
57756  u8 doNotSpill;              /* Do not spill the cache when non-zero */
57757  u8 subjInMemory;            /* True to use in-memory sub-journals */
57758  u8 bUseFetch;               /* True to use xFetch() */
57759  u8 hasHeldSharedLock;       /* True if a shared lock has ever been held */
57760  Pgno dbSize;                /* Number of pages in the database */
57761  Pgno dbOrigSize;            /* dbSize before the current transaction */
57762  Pgno dbFileSize;            /* Number of pages in the database file */
57763  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
57764  int errCode;                /* One of several kinds of errors */
57765  int nRec;                   /* Pages journalled since last j-header written */
57766  u32 cksumInit;              /* Quasi-random value added to every checksum */
57767  u32 nSubRec;                /* Number of records written to sub-journal */
57768  Bitvec *pInJournal;         /* One bit for each page in the database file */
57769  sqlite3_file *fd;           /* File descriptor for database */
57770  sqlite3_file *jfd;          /* File descriptor for main journal */
57771  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
57772  i64 journalOff;             /* Current write offset in the journal file */
57773  i64 journalHdr;             /* Byte offset to previous journal header */
57774  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
57775  PagerSavepoint *aSavepoint; /* Array of active savepoints */
57776  int nSavepoint;             /* Number of elements in aSavepoint[] */
57777  u32 iDataVersion;           /* Changes whenever database content changes */
57778  char dbFileVers[16];        /* Changes whenever database file changes */
57779
57780  int nMmapOut;               /* Number of mmap pages currently outstanding */
57781  sqlite3_int64 szMmap;       /* Desired maximum mmap size */
57782  PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
57783  /*
57784  ** End of the routinely-changing class members
57785  ***************************************************************************/
57786
57787  u16 nExtra;                 /* Add this many bytes to each in-memory page */
57788  i16 nReserve;               /* Number of unused bytes at end of each page */
57789  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
57790  u32 sectorSize;             /* Assumed sector size during rollback */
57791  Pgno mxPgno;                /* Maximum allowed size of the database */
57792  Pgno lckPgno;               /* Page number for the locking page */
57793  i64 pageSize;               /* Number of bytes in a page */
57794  i64 journalSizeLimit;       /* Size limit for persistent journal files */
57795  char *zFilename;            /* Name of the database file */
57796  char *zJournal;             /* Name of the journal file */
57797  int (*xBusyHandler)(void*); /* Function to call when busy */
57798  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
57799  u32 aStat[4];               /* Total cache hits, misses, writes, spills */
57800#ifdef SQLITE_TEST
57801  int nRead;                  /* Database pages read */
57802#endif
57803  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
57804  int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
57805  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
57806  PCache *pPCache;            /* Pointer to page cache object */
57807#ifndef SQLITE_OMIT_WAL
57808  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
57809  char *zWal;                 /* File name for write-ahead log */
57810#endif
57811};
57812
57813/*
57814** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
57815** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
57816** or CACHE_WRITE to sqlite3_db_status().
57817*/
57818#define PAGER_STAT_HIT   0
57819#define PAGER_STAT_MISS  1
57820#define PAGER_STAT_WRITE 2
57821#define PAGER_STAT_SPILL 3
57822
57823/*
57824** The following global variables hold counters used for
57825** testing purposes only.  These variables do not exist in
57826** a non-testing build.  These variables are not thread-safe.
57827*/
57828#ifdef SQLITE_TEST
57829SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
57830SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
57831SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
57832# define PAGER_INCR(v)  v++
57833#else
57834# define PAGER_INCR(v)
57835#endif
57836
57837
57838
57839/*
57840** Journal files begin with the following magic string.  The data
57841** was obtained from /dev/random.  It is used only as a sanity check.
57842**
57843** Since version 2.8.0, the journal format contains additional sanity
57844** checking information.  If the power fails while the journal is being
57845** written, semi-random garbage data might appear in the journal
57846** file after power is restored.  If an attempt is then made
57847** to roll the journal back, the database could be corrupted.  The additional
57848** sanity checking data is an attempt to discover the garbage in the
57849** journal and ignore it.
57850**
57851** The sanity checking information for the new journal format consists
57852** of a 32-bit checksum on each page of data.  The checksum covers both
57853** the page number and the pPager->pageSize bytes of data for the page.
57854** This cksum is initialized to a 32-bit random value that appears in the
57855** journal file right after the header.  The random initializer is important,
57856** because garbage data that appears at the end of a journal is likely
57857** data that was once in other files that have now been deleted.  If the
57858** garbage data came from an obsolete journal file, the checksums might
57859** be correct.  But by initializing the checksum to random value which
57860** is different for every journal, we minimize that risk.
57861*/
57862static const unsigned char aJournalMagic[] = {
57863  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
57864};
57865
57866/*
57867** The size of the of each page record in the journal is given by
57868** the following macro.
57869*/
57870#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
57871
57872/*
57873** The journal header size for this pager. This is usually the same
57874** size as a single disk sector. See also setSectorSize().
57875*/
57876#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
57877
57878/*
57879** The macro MEMDB is true if we are dealing with an in-memory database.
57880** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
57881** the value of MEMDB will be a constant and the compiler will optimize
57882** out code that would never execute.
57883*/
57884#ifdef SQLITE_OMIT_MEMORYDB
57885# define MEMDB 0
57886#else
57887# define MEMDB pPager->memDb
57888#endif
57889
57890/*
57891** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
57892** interfaces to access the database using memory-mapped I/O.
57893*/
57894#if SQLITE_MAX_MMAP_SIZE>0
57895# define USEFETCH(x) ((x)->bUseFetch)
57896#else
57897# define USEFETCH(x) 0
57898#endif
57899
57900/*
57901** The argument to this macro is a file descriptor (type sqlite3_file*).
57902** Return 0 if it is not open, or non-zero (but not 1) if it is.
57903**
57904** This is so that expressions can be written as:
57905**
57906**   if( isOpen(pPager->jfd) ){ ...
57907**
57908** instead of
57909**
57910**   if( pPager->jfd->pMethods ){ ...
57911*/
57912#define isOpen(pFd) ((pFd)->pMethods!=0)
57913
57914#ifdef SQLITE_DIRECT_OVERFLOW_READ
57915/*
57916** Return true if page pgno can be read directly from the database file
57917** by the b-tree layer. This is the case if:
57918**
57919**   * the database file is open,
57920**   * there are no dirty pages in the cache, and
57921**   * the desired page is not currently in the wal file.
57922*/
57923SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){
57924  if( pPager->fd->pMethods==0 ) return 0;
57925  if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0;
57926#ifndef SQLITE_OMIT_WAL
57927  if( pPager->pWal ){
57928    u32 iRead = 0;
57929    (void)sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
57930    return iRead==0;
57931  }
57932#endif
57933  return 1;
57934}
57935#endif
57936
57937#ifndef SQLITE_OMIT_WAL
57938# define pagerUseWal(x) ((x)->pWal!=0)
57939#else
57940# define pagerUseWal(x) 0
57941# define pagerRollbackWal(x) 0
57942# define pagerWalFrames(v,w,x,y) 0
57943# define pagerOpenWalIfPresent(z) SQLITE_OK
57944# define pagerBeginReadTransaction(z) SQLITE_OK
57945#endif
57946
57947#ifndef NDEBUG
57948/*
57949** Usage:
57950**
57951**   assert( assert_pager_state(pPager) );
57952**
57953** This function runs many asserts to try to find inconsistencies in
57954** the internal state of the Pager object.
57955*/
57956static int assert_pager_state(Pager *p){
57957  Pager *pPager = p;
57958
57959  /* State must be valid. */
57960  assert( p->eState==PAGER_OPEN
57961       || p->eState==PAGER_READER
57962       || p->eState==PAGER_WRITER_LOCKED
57963       || p->eState==PAGER_WRITER_CACHEMOD
57964       || p->eState==PAGER_WRITER_DBMOD
57965       || p->eState==PAGER_WRITER_FINISHED
57966       || p->eState==PAGER_ERROR
57967  );
57968
57969  /* Regardless of the current state, a temp-file connection always behaves
57970  ** as if it has an exclusive lock on the database file. It never updates
57971  ** the change-counter field, so the changeCountDone flag is always set.
57972  */
57973  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
57974  assert( p->tempFile==0 || pPager->changeCountDone );
57975
57976  /* If the useJournal flag is clear, the journal-mode must be "OFF".
57977  ** And if the journal-mode is "OFF", the journal file must not be open.
57978  */
57979  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
57980  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
57981
57982  /* Check that MEMDB implies noSync. And an in-memory journal. Since
57983  ** this means an in-memory pager performs no IO at all, it cannot encounter
57984  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
57985  ** a journal file. (although the in-memory journal implementation may
57986  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
57987  ** is therefore not possible for an in-memory pager to enter the ERROR
57988  ** state.
57989  */
57990  if( MEMDB ){
57991    assert( !isOpen(p->fd) );
57992    assert( p->noSync );
57993    assert( p->journalMode==PAGER_JOURNALMODE_OFF
57994         || p->journalMode==PAGER_JOURNALMODE_MEMORY
57995    );
57996    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
57997    assert( pagerUseWal(p)==0 );
57998  }
57999
58000  /* If changeCountDone is set, a RESERVED lock or greater must be held
58001  ** on the file.
58002  */
58003  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
58004  assert( p->eLock!=PENDING_LOCK );
58005
58006  switch( p->eState ){
58007    case PAGER_OPEN:
58008      assert( !MEMDB );
58009      assert( pPager->errCode==SQLITE_OK );
58010      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
58011      break;
58012
58013    case PAGER_READER:
58014      assert( pPager->errCode==SQLITE_OK );
58015      assert( p->eLock!=UNKNOWN_LOCK );
58016      assert( p->eLock>=SHARED_LOCK );
58017      break;
58018
58019    case PAGER_WRITER_LOCKED:
58020      assert( p->eLock!=UNKNOWN_LOCK );
58021      assert( pPager->errCode==SQLITE_OK );
58022      if( !pagerUseWal(pPager) ){
58023        assert( p->eLock>=RESERVED_LOCK );
58024      }
58025      assert( pPager->dbSize==pPager->dbOrigSize );
58026      assert( pPager->dbOrigSize==pPager->dbFileSize );
58027      assert( pPager->dbOrigSize==pPager->dbHintSize );
58028      assert( pPager->setSuper==0 );
58029      break;
58030
58031    case PAGER_WRITER_CACHEMOD:
58032      assert( p->eLock!=UNKNOWN_LOCK );
58033      assert( pPager->errCode==SQLITE_OK );
58034      if( !pagerUseWal(pPager) ){
58035        /* It is possible that if journal_mode=wal here that neither the
58036        ** journal file nor the WAL file are open. This happens during
58037        ** a rollback transaction that switches from journal_mode=off
58038        ** to journal_mode=wal.
58039        */
58040        assert( p->eLock>=RESERVED_LOCK );
58041        assert( isOpen(p->jfd)
58042             || p->journalMode==PAGER_JOURNALMODE_OFF
58043             || p->journalMode==PAGER_JOURNALMODE_WAL
58044        );
58045      }
58046      assert( pPager->dbOrigSize==pPager->dbFileSize );
58047      assert( pPager->dbOrigSize==pPager->dbHintSize );
58048      break;
58049
58050    case PAGER_WRITER_DBMOD:
58051      assert( p->eLock==EXCLUSIVE_LOCK );
58052      assert( pPager->errCode==SQLITE_OK );
58053      assert( !pagerUseWal(pPager) );
58054      assert( p->eLock>=EXCLUSIVE_LOCK );
58055      assert( isOpen(p->jfd)
58056           || p->journalMode==PAGER_JOURNALMODE_OFF
58057           || p->journalMode==PAGER_JOURNALMODE_WAL
58058           || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
58059      );
58060      assert( pPager->dbOrigSize<=pPager->dbHintSize );
58061      break;
58062
58063    case PAGER_WRITER_FINISHED:
58064      assert( p->eLock==EXCLUSIVE_LOCK );
58065      assert( pPager->errCode==SQLITE_OK );
58066      assert( !pagerUseWal(pPager) );
58067      assert( isOpen(p->jfd)
58068           || p->journalMode==PAGER_JOURNALMODE_OFF
58069           || p->journalMode==PAGER_JOURNALMODE_WAL
58070           || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
58071      );
58072      break;
58073
58074    case PAGER_ERROR:
58075      /* There must be at least one outstanding reference to the pager if
58076      ** in ERROR state. Otherwise the pager should have already dropped
58077      ** back to OPEN state.
58078      */
58079      assert( pPager->errCode!=SQLITE_OK );
58080      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
58081      break;
58082  }
58083
58084  return 1;
58085}
58086#endif /* ifndef NDEBUG */
58087
58088#ifdef SQLITE_DEBUG
58089/*
58090** Return a pointer to a human readable string in a static buffer
58091** containing the state of the Pager object passed as an argument. This
58092** is intended to be used within debuggers. For example, as an alternative
58093** to "print *pPager" in gdb:
58094**
58095** (gdb) printf "%s", print_pager_state(pPager)
58096**
58097** This routine has external linkage in order to suppress compiler warnings
58098** about an unused function.  It is enclosed within SQLITE_DEBUG and so does
58099** not appear in normal builds.
58100*/
58101char *print_pager_state(Pager *p){
58102  static char zRet[1024];
58103
58104  sqlite3_snprintf(1024, zRet,
58105      "Filename:      %s\n"
58106      "State:         %s errCode=%d\n"
58107      "Lock:          %s\n"
58108      "Locking mode:  locking_mode=%s\n"
58109      "Journal mode:  journal_mode=%s\n"
58110      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
58111      "Journal:       journalOff=%lld journalHdr=%lld\n"
58112      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
58113      , p->zFilename
58114      , p->eState==PAGER_OPEN            ? "OPEN" :
58115        p->eState==PAGER_READER          ? "READER" :
58116        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
58117        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
58118        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
58119        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
58120        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
58121      , (int)p->errCode
58122      , p->eLock==NO_LOCK         ? "NO_LOCK" :
58123        p->eLock==RESERVED_LOCK   ? "RESERVED" :
58124        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
58125        p->eLock==SHARED_LOCK     ? "SHARED" :
58126        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
58127      , p->exclusiveMode ? "exclusive" : "normal"
58128      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
58129        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
58130        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
58131        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
58132        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
58133        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
58134      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
58135      , p->journalOff, p->journalHdr
58136      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
58137  );
58138
58139  return zRet;
58140}
58141#endif
58142
58143/* Forward references to the various page getters */
58144static int getPageNormal(Pager*,Pgno,DbPage**,int);
58145static int getPageError(Pager*,Pgno,DbPage**,int);
58146#if SQLITE_MAX_MMAP_SIZE>0
58147static int getPageMMap(Pager*,Pgno,DbPage**,int);
58148#endif
58149
58150/*
58151** Set the Pager.xGet method for the appropriate routine used to fetch
58152** content from the pager.
58153*/
58154static void setGetterMethod(Pager *pPager){
58155  if( pPager->errCode ){
58156    pPager->xGet = getPageError;
58157#if SQLITE_MAX_MMAP_SIZE>0
58158  }else if( USEFETCH(pPager) ){
58159    pPager->xGet = getPageMMap;
58160#endif /* SQLITE_MAX_MMAP_SIZE>0 */
58161  }else{
58162    pPager->xGet = getPageNormal;
58163  }
58164}
58165
58166/*
58167** Return true if it is necessary to write page *pPg into the sub-journal.
58168** A page needs to be written into the sub-journal if there exists one
58169** or more open savepoints for which:
58170**
58171**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
58172**   * The bit corresponding to the page-number is not set in
58173**     PagerSavepoint.pInSavepoint.
58174*/
58175static int subjRequiresPage(PgHdr *pPg){
58176  Pager *pPager = pPg->pPager;
58177  PagerSavepoint *p;
58178  Pgno pgno = pPg->pgno;
58179  int i;
58180  for(i=0; i<pPager->nSavepoint; i++){
58181    p = &pPager->aSavepoint[i];
58182    if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
58183      for(i=i+1; i<pPager->nSavepoint; i++){
58184        pPager->aSavepoint[i].bTruncateOnRelease = 0;
58185      }
58186      return 1;
58187    }
58188  }
58189  return 0;
58190}
58191
58192#ifdef SQLITE_DEBUG
58193/*
58194** Return true if the page is already in the journal file.
58195*/
58196static int pageInJournal(Pager *pPager, PgHdr *pPg){
58197  return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
58198}
58199#endif
58200
58201/*
58202** Read a 32-bit integer from the given file descriptor.  Store the integer
58203** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
58204** error code is something goes wrong.
58205**
58206** All values are stored on disk as big-endian.
58207*/
58208static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
58209  unsigned char ac[4];
58210  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
58211  if( rc==SQLITE_OK ){
58212    *pRes = sqlite3Get4byte(ac);
58213  }
58214  return rc;
58215}
58216
58217/*
58218** Write a 32-bit integer into a string buffer in big-endian byte order.
58219*/
58220#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
58221
58222
58223/*
58224** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
58225** on success or an error code is something goes wrong.
58226*/
58227static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
58228  char ac[4];
58229  put32bits(ac, val);
58230  return sqlite3OsWrite(fd, ac, 4, offset);
58231}
58232
58233/*
58234** Unlock the database file to level eLock, which must be either NO_LOCK
58235** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
58236** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
58237**
58238** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
58239** called, do not modify it. See the comment above the #define of
58240** UNKNOWN_LOCK for an explanation of this.
58241*/
58242static int pagerUnlockDb(Pager *pPager, int eLock){
58243  int rc = SQLITE_OK;
58244
58245  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
58246  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
58247  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
58248  if( isOpen(pPager->fd) ){
58249    assert( pPager->eLock>=eLock );
58250    rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
58251    if( pPager->eLock!=UNKNOWN_LOCK ){
58252      pPager->eLock = (u8)eLock;
58253    }
58254    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
58255  }
58256  pPager->changeCountDone = pPager->tempFile; /* ticket fb3b3024ea238d5c */
58257  return rc;
58258}
58259
58260/*
58261** Lock the database file to level eLock, which must be either SHARED_LOCK,
58262** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
58263** Pager.eLock variable to the new locking state.
58264**
58265** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
58266** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
58267** See the comment above the #define of UNKNOWN_LOCK for an explanation
58268** of this.
58269*/
58270static int pagerLockDb(Pager *pPager, int eLock){
58271  int rc = SQLITE_OK;
58272
58273  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
58274  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
58275    rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
58276    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
58277      pPager->eLock = (u8)eLock;
58278      IOTRACE(("LOCK %p %d\n", pPager, eLock))
58279    }
58280  }
58281  return rc;
58282}
58283
58284/*
58285** This function determines whether or not the atomic-write or
58286** atomic-batch-write optimizations can be used with this pager. The
58287** atomic-write optimization can be used if:
58288**
58289**  (a) the value returned by OsDeviceCharacteristics() indicates that
58290**      a database page may be written atomically, and
58291**  (b) the value returned by OsSectorSize() is less than or equal
58292**      to the page size.
58293**
58294** If it can be used, then the value returned is the size of the journal
58295** file when it contains rollback data for exactly one page.
58296**
58297** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
58298** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
58299** returned in this case.
58300**
58301** If neither optimization can be used, 0 is returned.
58302*/
58303static int jrnlBufferSize(Pager *pPager){
58304  assert( !MEMDB );
58305
58306#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
58307 || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
58308  int dc;                           /* Device characteristics */
58309
58310  assert( isOpen(pPager->fd) );
58311  dc = sqlite3OsDeviceCharacteristics(pPager->fd);
58312#else
58313  UNUSED_PARAMETER(pPager);
58314#endif
58315
58316#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
58317  if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){
58318    return -1;
58319  }
58320#endif
58321
58322#ifdef SQLITE_ENABLE_ATOMIC_WRITE
58323  {
58324    int nSector = pPager->sectorSize;
58325    int szPage = pPager->pageSize;
58326
58327    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
58328    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
58329    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
58330      return 0;
58331    }
58332  }
58333
58334  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
58335#endif
58336
58337  return 0;
58338}
58339
58340/*
58341** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
58342** on the cache using a hash function.  This is used for testing
58343** and debugging only.
58344*/
58345#ifdef SQLITE_CHECK_PAGES
58346/*
58347** Return a 32-bit hash of the page data for pPage.
58348*/
58349static u32 pager_datahash(int nByte, unsigned char *pData){
58350  u32 hash = 0;
58351  int i;
58352  for(i=0; i<nByte; i++){
58353    hash = (hash*1039) + pData[i];
58354  }
58355  return hash;
58356}
58357static u32 pager_pagehash(PgHdr *pPage){
58358  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
58359}
58360static void pager_set_pagehash(PgHdr *pPage){
58361  pPage->pageHash = pager_pagehash(pPage);
58362}
58363
58364/*
58365** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
58366** is defined, and NDEBUG is not defined, an assert() statement checks
58367** that the page is either dirty or still matches the calculated page-hash.
58368*/
58369#define CHECK_PAGE(x) checkPage(x)
58370static void checkPage(PgHdr *pPg){
58371  Pager *pPager = pPg->pPager;
58372  assert( pPager->eState!=PAGER_ERROR );
58373  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
58374}
58375
58376#else
58377#define pager_datahash(X,Y)  0
58378#define pager_pagehash(X)  0
58379#define pager_set_pagehash(X)
58380#define CHECK_PAGE(x)
58381#endif  /* SQLITE_CHECK_PAGES */
58382
58383/*
58384** When this is called the journal file for pager pPager must be open.
58385** This function attempts to read a super-journal file name from the
58386** end of the file and, if successful, copies it into memory supplied
58387** by the caller. See comments above writeSuperJournal() for the format
58388** used to store a super-journal file name at the end of a journal file.
58389**
58390** zSuper must point to a buffer of at least nSuper bytes allocated by
58391** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
58392** enough space to write the super-journal name). If the super-journal
58393** name in the journal is longer than nSuper bytes (including a
58394** nul-terminator), then this is handled as if no super-journal name
58395** were present in the journal.
58396**
58397** If a super-journal file name is present at the end of the journal
58398** file, then it is copied into the buffer pointed to by zSuper. A
58399** nul-terminator byte is appended to the buffer following the
58400** super-journal file name.
58401**
58402** If it is determined that no super-journal file name is present
58403** zSuper[0] is set to 0 and SQLITE_OK returned.
58404**
58405** If an error occurs while reading from the journal file, an SQLite
58406** error code is returned.
58407*/
58408static int readSuperJournal(sqlite3_file *pJrnl, char *zSuper, u32 nSuper){
58409  int rc;                    /* Return code */
58410  u32 len;                   /* Length in bytes of super-journal name */
58411  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
58412  u32 cksum;                 /* MJ checksum value read from journal */
58413  u32 u;                     /* Unsigned loop counter */
58414  unsigned char aMagic[8];   /* A buffer to hold the magic header */
58415  zSuper[0] = '\0';
58416
58417  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
58418   || szJ<16
58419   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
58420   || len>=nSuper
58421   || len>szJ-16
58422   || len==0
58423   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
58424   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
58425   || memcmp(aMagic, aJournalMagic, 8)
58426   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zSuper, len, szJ-16-len))
58427  ){
58428    return rc;
58429  }
58430
58431  /* See if the checksum matches the super-journal name */
58432  for(u=0; u<len; u++){
58433    cksum -= zSuper[u];
58434  }
58435  if( cksum ){
58436    /* If the checksum doesn't add up, then one or more of the disk sectors
58437    ** containing the super-journal filename is corrupted. This means
58438    ** definitely roll back, so just return SQLITE_OK and report a (nul)
58439    ** super-journal filename.
58440    */
58441    len = 0;
58442  }
58443  zSuper[len] = '\0';
58444  zSuper[len+1] = '\0';
58445
58446  return SQLITE_OK;
58447}
58448
58449/*
58450** Return the offset of the sector boundary at or immediately
58451** following the value in pPager->journalOff, assuming a sector
58452** size of pPager->sectorSize bytes.
58453**
58454** i.e for a sector size of 512:
58455**
58456**   Pager.journalOff          Return value
58457**   ---------------------------------------
58458**   0                         0
58459**   512                       512
58460**   100                       512
58461**   2000                      2048
58462**
58463*/
58464static i64 journalHdrOffset(Pager *pPager){
58465  i64 offset = 0;
58466  i64 c = pPager->journalOff;
58467  if( c ){
58468    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
58469  }
58470  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
58471  assert( offset>=c );
58472  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
58473  return offset;
58474}
58475
58476/*
58477** The journal file must be open when this function is called.
58478**
58479** This function is a no-op if the journal file has not been written to
58480** within the current transaction (i.e. if Pager.journalOff==0).
58481**
58482** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
58483** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
58484** zero the 28-byte header at the start of the journal file. In either case,
58485** if the pager is not in no-sync mode, sync the journal file immediately
58486** after writing or truncating it.
58487**
58488** If Pager.journalSizeLimit is set to a positive, non-zero value, and
58489** following the truncation or zeroing described above the size of the
58490** journal file in bytes is larger than this value, then truncate the
58491** journal file to Pager.journalSizeLimit bytes. The journal file does
58492** not need to be synced following this operation.
58493**
58494** If an IO error occurs, abandon processing and return the IO error code.
58495** Otherwise, return SQLITE_OK.
58496*/
58497static int zeroJournalHdr(Pager *pPager, int doTruncate){
58498  int rc = SQLITE_OK;                               /* Return code */
58499  assert( isOpen(pPager->jfd) );
58500  assert( !sqlite3JournalIsInMemory(pPager->jfd) );
58501  if( pPager->journalOff ){
58502    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
58503
58504    IOTRACE(("JZEROHDR %p\n", pPager))
58505    if( doTruncate || iLimit==0 ){
58506      rc = sqlite3OsTruncate(pPager->jfd, 0);
58507    }else{
58508      static const char zeroHdr[28] = {0};
58509      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
58510    }
58511    if( rc==SQLITE_OK && !pPager->noSync ){
58512      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
58513    }
58514
58515    /* At this point the transaction is committed but the write lock
58516    ** is still held on the file. If there is a size limit configured for
58517    ** the persistent journal and the journal file currently consumes more
58518    ** space than that limit allows for, truncate it now. There is no need
58519    ** to sync the file following this operation.
58520    */
58521    if( rc==SQLITE_OK && iLimit>0 ){
58522      i64 sz;
58523      rc = sqlite3OsFileSize(pPager->jfd, &sz);
58524      if( rc==SQLITE_OK && sz>iLimit ){
58525        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
58526      }
58527    }
58528  }
58529  return rc;
58530}
58531
58532/*
58533** The journal file must be open when this routine is called. A journal
58534** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
58535** current location.
58536**
58537** The format for the journal header is as follows:
58538** - 8 bytes: Magic identifying journal format.
58539** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
58540** - 4 bytes: Random number used for page hash.
58541** - 4 bytes: Initial database page count.
58542** - 4 bytes: Sector size used by the process that wrote this journal.
58543** - 4 bytes: Database page size.
58544**
58545** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
58546*/
58547static int writeJournalHdr(Pager *pPager){
58548  int rc = SQLITE_OK;                 /* Return code */
58549  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
58550  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
58551  u32 nWrite;                         /* Bytes of header sector written */
58552  int ii;                             /* Loop counter */
58553
58554  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
58555
58556  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
58557    nHeader = JOURNAL_HDR_SZ(pPager);
58558  }
58559
58560  /* If there are active savepoints and any of them were created
58561  ** since the most recent journal header was written, update the
58562  ** PagerSavepoint.iHdrOffset fields now.
58563  */
58564  for(ii=0; ii<pPager->nSavepoint; ii++){
58565    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
58566      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
58567    }
58568  }
58569
58570  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
58571
58572  /*
58573  ** Write the nRec Field - the number of page records that follow this
58574  ** journal header. Normally, zero is written to this value at this time.
58575  ** After the records are added to the journal (and the journal synced,
58576  ** if in full-sync mode), the zero is overwritten with the true number
58577  ** of records (see syncJournal()).
58578  **
58579  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
58580  ** reading the journal this value tells SQLite to assume that the
58581  ** rest of the journal file contains valid page records. This assumption
58582  ** is dangerous, as if a failure occurred whilst writing to the journal
58583  ** file it may contain some garbage data. There are two scenarios
58584  ** where this risk can be ignored:
58585  **
58586  **   * When the pager is in no-sync mode. Corruption can follow a
58587  **     power failure in this case anyway.
58588  **
58589  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
58590  **     that garbage data is never appended to the journal file.
58591  */
58592  assert( isOpen(pPager->fd) || pPager->noSync );
58593  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
58594   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
58595  ){
58596    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
58597    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
58598  }else{
58599    memset(zHeader, 0, sizeof(aJournalMagic)+4);
58600  }
58601
58602
58603
58604  /* The random check-hash initializer */
58605  if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
58606    sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
58607  }
58608#ifdef SQLITE_DEBUG
58609  else{
58610    /* The Pager.cksumInit variable is usually randomized above to protect
58611    ** against there being existing records in the journal file. This is
58612    ** dangerous, as following a crash they may be mistaken for records
58613    ** written by the current transaction and rolled back into the database
58614    ** file, causing corruption. The following assert statements verify
58615    ** that this is not required in "journal_mode=memory" mode, as in that
58616    ** case the journal file is always 0 bytes in size at this point.
58617    ** It is advantageous to avoid the sqlite3_randomness() call if possible
58618    ** as it takes the global PRNG mutex.  */
58619    i64 sz = 0;
58620    sqlite3OsFileSize(pPager->jfd, &sz);
58621    assert( sz==0 );
58622    assert( pPager->journalOff==journalHdrOffset(pPager) );
58623    assert( sqlite3JournalIsInMemory(pPager->jfd) );
58624  }
58625#endif
58626  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
58627
58628  /* The initial database size */
58629  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
58630  /* The assumed sector size for this process */
58631  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
58632
58633  /* The page size */
58634  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
58635
58636  /* Initializing the tail of the buffer is not necessary.  Everything
58637  ** works find if the following memset() is omitted.  But initializing
58638  ** the memory prevents valgrind from complaining, so we are willing to
58639  ** take the performance hit.
58640  */
58641  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
58642         nHeader-(sizeof(aJournalMagic)+20));
58643
58644  /* In theory, it is only necessary to write the 28 bytes that the
58645  ** journal header consumes to the journal file here. Then increment the
58646  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
58647  ** record is written to the following sector (leaving a gap in the file
58648  ** that will be implicitly filled in by the OS).
58649  **
58650  ** However it has been discovered that on some systems this pattern can
58651  ** be significantly slower than contiguously writing data to the file,
58652  ** even if that means explicitly writing data to the block of
58653  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
58654  ** is done.
58655  **
58656  ** The loop is required here in case the sector-size is larger than the
58657  ** database page size. Since the zHeader buffer is only Pager.pageSize
58658  ** bytes in size, more than one call to sqlite3OsWrite() may be required
58659  ** to populate the entire journal header sector.
58660  */
58661  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
58662    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
58663    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
58664    assert( pPager->journalHdr <= pPager->journalOff );
58665    pPager->journalOff += nHeader;
58666  }
58667
58668  return rc;
58669}
58670
58671/*
58672** The journal file must be open when this is called. A journal header file
58673** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
58674** file. The current location in the journal file is given by
58675** pPager->journalOff. See comments above function writeJournalHdr() for
58676** a description of the journal header format.
58677**
58678** If the header is read successfully, *pNRec is set to the number of
58679** page records following this header and *pDbSize is set to the size of the
58680** database before the transaction began, in pages. Also, pPager->cksumInit
58681** is set to the value read from the journal header. SQLITE_OK is returned
58682** in this case.
58683**
58684** If the journal header file appears to be corrupted, SQLITE_DONE is
58685** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
58686** cannot be read from the journal file an error code is returned.
58687*/
58688static int readJournalHdr(
58689  Pager *pPager,               /* Pager object */
58690  int isHot,
58691  i64 journalSize,             /* Size of the open journal file in bytes */
58692  u32 *pNRec,                  /* OUT: Value read from the nRec field */
58693  u32 *pDbSize                 /* OUT: Value of original database size field */
58694){
58695  int rc;                      /* Return code */
58696  unsigned char aMagic[8];     /* A buffer to hold the magic header */
58697  i64 iHdrOff;                 /* Offset of journal header being read */
58698
58699  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
58700
58701  /* Advance Pager.journalOff to the start of the next sector. If the
58702  ** journal file is too small for there to be a header stored at this
58703  ** point, return SQLITE_DONE.
58704  */
58705  pPager->journalOff = journalHdrOffset(pPager);
58706  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
58707    return SQLITE_DONE;
58708  }
58709  iHdrOff = pPager->journalOff;
58710
58711  /* Read in the first 8 bytes of the journal header. If they do not match
58712  ** the  magic string found at the start of each journal header, return
58713  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
58714  ** proceed.
58715  */
58716  if( isHot || iHdrOff!=pPager->journalHdr ){
58717    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
58718    if( rc ){
58719      return rc;
58720    }
58721    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
58722      return SQLITE_DONE;
58723    }
58724  }
58725
58726  /* Read the first three 32-bit fields of the journal header: The nRec
58727  ** field, the checksum-initializer and the database size at the start
58728  ** of the transaction. Return an error code if anything goes wrong.
58729  */
58730  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
58731   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
58732   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
58733  ){
58734    return rc;
58735  }
58736
58737  if( pPager->journalOff==0 ){
58738    u32 iPageSize;               /* Page-size field of journal header */
58739    u32 iSectorSize;             /* Sector-size field of journal header */
58740
58741    /* Read the page-size and sector-size journal header fields. */
58742    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
58743     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
58744    ){
58745      return rc;
58746    }
58747
58748    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
58749    ** journal header to zero. In this case, assume that the Pager.pageSize
58750    ** variable is already set to the correct page size.
58751    */
58752    if( iPageSize==0 ){
58753      iPageSize = pPager->pageSize;
58754    }
58755
58756    /* Check that the values read from the page-size and sector-size fields
58757    ** are within range. To be 'in range', both values need to be a power
58758    ** of two greater than or equal to 512 or 32, and not greater than their
58759    ** respective compile time maximum limits.
58760    */
58761    if( iPageSize<512                  || iSectorSize<32
58762     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
58763     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
58764    ){
58765      /* If the either the page-size or sector-size in the journal-header is
58766      ** invalid, then the process that wrote the journal-header must have
58767      ** crashed before the header was synced. In this case stop reading
58768      ** the journal file here.
58769      */
58770      return SQLITE_DONE;
58771    }
58772
58773    /* Update the page-size to match the value read from the journal.
58774    ** Use a testcase() macro to make sure that malloc failure within
58775    ** PagerSetPagesize() is tested.
58776    */
58777    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
58778    testcase( rc!=SQLITE_OK );
58779
58780    /* Update the assumed sector-size to match the value used by
58781    ** the process that created this journal. If this journal was
58782    ** created by a process other than this one, then this routine
58783    ** is being called from within pager_playback(). The local value
58784    ** of Pager.sectorSize is restored at the end of that routine.
58785    */
58786    pPager->sectorSize = iSectorSize;
58787  }
58788
58789  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
58790  return rc;
58791}
58792
58793
58794/*
58795** Write the supplied super-journal name into the journal file for pager
58796** pPager at the current location. The super-journal name must be the last
58797** thing written to a journal file. If the pager is in full-sync mode, the
58798** journal file descriptor is advanced to the next sector boundary before
58799** anything is written. The format is:
58800**
58801**   + 4 bytes: PAGER_SJ_PGNO.
58802**   + N bytes: super-journal filename in utf-8.
58803**   + 4 bytes: N (length of super-journal name in bytes, no nul-terminator).
58804**   + 4 bytes: super-journal name checksum.
58805**   + 8 bytes: aJournalMagic[].
58806**
58807** The super-journal page checksum is the sum of the bytes in the super-journal
58808** name, where each byte is interpreted as a signed 8-bit integer.
58809**
58810** If zSuper is a NULL pointer (occurs for a single database transaction),
58811** this call is a no-op.
58812*/
58813static int writeSuperJournal(Pager *pPager, const char *zSuper){
58814  int rc;                          /* Return code */
58815  int nSuper;                      /* Length of string zSuper */
58816  i64 iHdrOff;                     /* Offset of header in journal file */
58817  i64 jrnlSize;                    /* Size of journal file on disk */
58818  u32 cksum = 0;                   /* Checksum of string zSuper */
58819
58820  assert( pPager->setSuper==0 );
58821  assert( !pagerUseWal(pPager) );
58822
58823  if( !zSuper
58824   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
58825   || !isOpen(pPager->jfd)
58826  ){
58827    return SQLITE_OK;
58828  }
58829  pPager->setSuper = 1;
58830  assert( pPager->journalHdr <= pPager->journalOff );
58831
58832  /* Calculate the length in bytes and the checksum of zSuper */
58833  for(nSuper=0; zSuper[nSuper]; nSuper++){
58834    cksum += zSuper[nSuper];
58835  }
58836
58837  /* If in full-sync mode, advance to the next disk sector before writing
58838  ** the super-journal name. This is in case the previous page written to
58839  ** the journal has already been synced.
58840  */
58841  if( pPager->fullSync ){
58842    pPager->journalOff = journalHdrOffset(pPager);
58843  }
58844  iHdrOff = pPager->journalOff;
58845
58846  /* Write the super-journal data to the end of the journal file. If
58847  ** an error occurs, return the error code to the caller.
58848  */
58849  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_SJ_PGNO(pPager))))
58850   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zSuper, nSuper, iHdrOff+4)))
58851   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper, nSuper)))
58852   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper+4, cksum)))
58853   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
58854                                 iHdrOff+4+nSuper+8)))
58855  ){
58856    return rc;
58857  }
58858  pPager->journalOff += (nSuper+20);
58859
58860  /* If the pager is in persistent-journal mode, then the physical
58861  ** journal-file may extend past the end of the super-journal name
58862  ** and 8 bytes of magic data just written to the file. This is
58863  ** dangerous because the code to rollback a hot-journal file
58864  ** will not be able to find the super-journal name to determine
58865  ** whether or not the journal is hot.
58866  **
58867  ** Easiest thing to do in this scenario is to truncate the journal
58868  ** file to the required size.
58869  */
58870  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
58871   && jrnlSize>pPager->journalOff
58872  ){
58873    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
58874  }
58875  return rc;
58876}
58877
58878/*
58879** Discard the entire contents of the in-memory page-cache.
58880*/
58881static void pager_reset(Pager *pPager){
58882  pPager->iDataVersion++;
58883  sqlite3BackupRestart(pPager->pBackup);
58884  sqlite3PcacheClear(pPager->pPCache);
58885}
58886
58887/*
58888** Return the pPager->iDataVersion value
58889*/
58890SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
58891  return pPager->iDataVersion;
58892}
58893
58894/*
58895** Free all structures in the Pager.aSavepoint[] array and set both
58896** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
58897** if it is open and the pager is not in exclusive mode.
58898*/
58899static void releaseAllSavepoints(Pager *pPager){
58900  int ii;               /* Iterator for looping through Pager.aSavepoint */
58901  for(ii=0; ii<pPager->nSavepoint; ii++){
58902    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
58903  }
58904  if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
58905    sqlite3OsClose(pPager->sjfd);
58906  }
58907  sqlite3_free(pPager->aSavepoint);
58908  pPager->aSavepoint = 0;
58909  pPager->nSavepoint = 0;
58910  pPager->nSubRec = 0;
58911}
58912
58913/*
58914** Set the bit number pgno in the PagerSavepoint.pInSavepoint
58915** bitvecs of all open savepoints. Return SQLITE_OK if successful
58916** or SQLITE_NOMEM if a malloc failure occurs.
58917*/
58918static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
58919  int ii;                   /* Loop counter */
58920  int rc = SQLITE_OK;       /* Result code */
58921
58922  for(ii=0; ii<pPager->nSavepoint; ii++){
58923    PagerSavepoint *p = &pPager->aSavepoint[ii];
58924    if( pgno<=p->nOrig ){
58925      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
58926      testcase( rc==SQLITE_NOMEM );
58927      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
58928    }
58929  }
58930  return rc;
58931}
58932
58933/*
58934** This function is a no-op if the pager is in exclusive mode and not
58935** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
58936** state.
58937**
58938** If the pager is not in exclusive-access mode, the database file is
58939** completely unlocked. If the file is unlocked and the file-system does
58940** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
58941** closed (if it is open).
58942**
58943** If the pager is in ERROR state when this function is called, the
58944** contents of the pager cache are discarded before switching back to
58945** the OPEN state. Regardless of whether the pager is in exclusive-mode
58946** or not, any journal file left in the file-system will be treated
58947** as a hot-journal and rolled back the next time a read-transaction
58948** is opened (by this or by any other connection).
58949*/
58950static void pager_unlock(Pager *pPager){
58951
58952  assert( pPager->eState==PAGER_READER
58953       || pPager->eState==PAGER_OPEN
58954       || pPager->eState==PAGER_ERROR
58955  );
58956
58957  sqlite3BitvecDestroy(pPager->pInJournal);
58958  pPager->pInJournal = 0;
58959  releaseAllSavepoints(pPager);
58960
58961  if( pagerUseWal(pPager) ){
58962    assert( !isOpen(pPager->jfd) );
58963    sqlite3WalEndReadTransaction(pPager->pWal);
58964    pPager->eState = PAGER_OPEN;
58965  }else if( !pPager->exclusiveMode ){
58966    int rc;                       /* Error code returned by pagerUnlockDb() */
58967    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
58968
58969    /* If the operating system support deletion of open files, then
58970    ** close the journal file when dropping the database lock.  Otherwise
58971    ** another connection with journal_mode=delete might delete the file
58972    ** out from under us.
58973    */
58974    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
58975    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
58976    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
58977    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
58978    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
58979    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
58980    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
58981     || 1!=(pPager->journalMode & 5)
58982    ){
58983      sqlite3OsClose(pPager->jfd);
58984    }
58985
58986    /* If the pager is in the ERROR state and the call to unlock the database
58987    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
58988    ** above the #define for UNKNOWN_LOCK for an explanation of why this
58989    ** is necessary.
58990    */
58991    rc = pagerUnlockDb(pPager, NO_LOCK);
58992    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
58993      pPager->eLock = UNKNOWN_LOCK;
58994    }
58995
58996    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
58997    ** without clearing the error code. This is intentional - the error
58998    ** code is cleared and the cache reset in the block below.
58999    */
59000    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
59001    pPager->eState = PAGER_OPEN;
59002  }
59003
59004  /* If Pager.errCode is set, the contents of the pager cache cannot be
59005  ** trusted. Now that there are no outstanding references to the pager,
59006  ** it can safely move back to PAGER_OPEN state. This happens in both
59007  ** normal and exclusive-locking mode.
59008  */
59009  assert( pPager->errCode==SQLITE_OK || !MEMDB );
59010  if( pPager->errCode ){
59011    if( pPager->tempFile==0 ){
59012      pager_reset(pPager);
59013      pPager->changeCountDone = 0;
59014      pPager->eState = PAGER_OPEN;
59015    }else{
59016      pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
59017    }
59018    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
59019    pPager->errCode = SQLITE_OK;
59020    setGetterMethod(pPager);
59021  }
59022
59023  pPager->journalOff = 0;
59024  pPager->journalHdr = 0;
59025  pPager->setSuper = 0;
59026}
59027
59028/*
59029** This function is called whenever an IOERR or FULL error that requires
59030** the pager to transition into the ERROR state may have occurred.
59031** The first argument is a pointer to the pager structure, the second
59032** the error-code about to be returned by a pager API function. The
59033** value returned is a copy of the second argument to this function.
59034**
59035** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
59036** IOERR sub-codes, the pager enters the ERROR state and the error code
59037** is stored in Pager.errCode. While the pager remains in the ERROR state,
59038** all major API calls on the Pager will immediately return Pager.errCode.
59039**
59040** The ERROR state indicates that the contents of the pager-cache
59041** cannot be trusted. This state can be cleared by completely discarding
59042** the contents of the pager-cache. If a transaction was active when
59043** the persistent error occurred, then the rollback journal may need
59044** to be replayed to restore the contents of the database file (as if
59045** it were a hot-journal).
59046*/
59047static int pager_error(Pager *pPager, int rc){
59048  int rc2 = rc & 0xff;
59049  assert( rc==SQLITE_OK || !MEMDB );
59050  assert(
59051       pPager->errCode==SQLITE_FULL ||
59052       pPager->errCode==SQLITE_OK ||
59053       (pPager->errCode & 0xff)==SQLITE_IOERR
59054  );
59055  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
59056    pPager->errCode = rc;
59057    pPager->eState = PAGER_ERROR;
59058    setGetterMethod(pPager);
59059  }
59060  return rc;
59061}
59062
59063static int pager_truncate(Pager *pPager, Pgno nPage);
59064
59065/*
59066** The write transaction open on pPager is being committed (bCommit==1)
59067** or rolled back (bCommit==0).
59068**
59069** Return TRUE if and only if all dirty pages should be flushed to disk.
59070**
59071** Rules:
59072**
59073**   *  For non-TEMP databases, always sync to disk.  This is necessary
59074**      for transactions to be durable.
59075**
59076**   *  Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
59077**      file has been created already (via a spill on pagerStress()) and
59078**      when the number of dirty pages in memory exceeds 25% of the total
59079**      cache size.
59080*/
59081static int pagerFlushOnCommit(Pager *pPager, int bCommit){
59082  if( pPager->tempFile==0 ) return 1;
59083  if( !bCommit ) return 0;
59084  if( !isOpen(pPager->fd) ) return 0;
59085  return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
59086}
59087
59088/*
59089** This routine ends a transaction. A transaction is usually ended by
59090** either a COMMIT or a ROLLBACK operation. This routine may be called
59091** after rollback of a hot-journal, or if an error occurs while opening
59092** the journal file or writing the very first journal-header of a
59093** database transaction.
59094**
59095** This routine is never called in PAGER_ERROR state. If it is called
59096** in PAGER_NONE or PAGER_SHARED state and the lock held is less
59097** exclusive than a RESERVED lock, it is a no-op.
59098**
59099** Otherwise, any active savepoints are released.
59100**
59101** If the journal file is open, then it is "finalized". Once a journal
59102** file has been finalized it is not possible to use it to roll back a
59103** transaction. Nor will it be considered to be a hot-journal by this
59104** or any other database connection. Exactly how a journal is finalized
59105** depends on whether or not the pager is running in exclusive mode and
59106** the current journal-mode (Pager.journalMode value), as follows:
59107**
59108**   journalMode==MEMORY
59109**     Journal file descriptor is simply closed. This destroys an
59110**     in-memory journal.
59111**
59112**   journalMode==TRUNCATE
59113**     Journal file is truncated to zero bytes in size.
59114**
59115**   journalMode==PERSIST
59116**     The first 28 bytes of the journal file are zeroed. This invalidates
59117**     the first journal header in the file, and hence the entire journal
59118**     file. An invalid journal file cannot be rolled back.
59119**
59120**   journalMode==DELETE
59121**     The journal file is closed and deleted using sqlite3OsDelete().
59122**
59123**     If the pager is running in exclusive mode, this method of finalizing
59124**     the journal file is never used. Instead, if the journalMode is
59125**     DELETE and the pager is in exclusive mode, the method described under
59126**     journalMode==PERSIST is used instead.
59127**
59128** After the journal is finalized, the pager moves to PAGER_READER state.
59129** If running in non-exclusive rollback mode, the lock on the file is
59130** downgraded to a SHARED_LOCK.
59131**
59132** SQLITE_OK is returned if no error occurs. If an error occurs during
59133** any of the IO operations to finalize the journal file or unlock the
59134** database then the IO error code is returned to the user. If the
59135** operation to finalize the journal file fails, then the code still
59136** tries to unlock the database file if not in exclusive mode. If the
59137** unlock operation fails as well, then the first error code related
59138** to the first error encountered (the journal finalization one) is
59139** returned.
59140*/
59141static int pager_end_transaction(Pager *pPager, int hasSuper, int bCommit){
59142  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
59143  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
59144
59145  /* Do nothing if the pager does not have an open write transaction
59146  ** or at least a RESERVED lock. This function may be called when there
59147  ** is no write-transaction active but a RESERVED or greater lock is
59148  ** held under two circumstances:
59149  **
59150  **   1. After a successful hot-journal rollback, it is called with
59151  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
59152  **
59153  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
59154  **      lock switches back to locking_mode=normal and then executes a
59155  **      read-transaction, this function is called with eState==PAGER_READER
59156  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
59157  */
59158  assert( assert_pager_state(pPager) );
59159  assert( pPager->eState!=PAGER_ERROR );
59160  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
59161    return SQLITE_OK;
59162  }
59163
59164  releaseAllSavepoints(pPager);
59165  assert( isOpen(pPager->jfd) || pPager->pInJournal==0
59166      || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
59167  );
59168  if( isOpen(pPager->jfd) ){
59169    assert( !pagerUseWal(pPager) );
59170
59171    /* Finalize the journal file. */
59172    if( sqlite3JournalIsInMemory(pPager->jfd) ){
59173      /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
59174      sqlite3OsClose(pPager->jfd);
59175    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
59176      if( pPager->journalOff==0 ){
59177        rc = SQLITE_OK;
59178      }else{
59179        rc = sqlite3OsTruncate(pPager->jfd, 0);
59180        if( rc==SQLITE_OK && pPager->fullSync ){
59181          /* Make sure the new file size is written into the inode right away.
59182          ** Otherwise the journal might resurrect following a power loss and
59183          ** cause the last transaction to roll back.  See
59184          ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
59185          */
59186          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
59187        }
59188      }
59189      pPager->journalOff = 0;
59190    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
59191      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
59192    ){
59193      rc = zeroJournalHdr(pPager, hasSuper||pPager->tempFile);
59194      pPager->journalOff = 0;
59195    }else{
59196      /* This branch may be executed with Pager.journalMode==MEMORY if
59197      ** a hot-journal was just rolled back. In this case the journal
59198      ** file should be closed and deleted. If this connection writes to
59199      ** the database file, it will do so using an in-memory journal.
59200      */
59201      int bDelete = !pPager->tempFile;
59202      assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
59203      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
59204           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
59205           || pPager->journalMode==PAGER_JOURNALMODE_WAL
59206      );
59207      sqlite3OsClose(pPager->jfd);
59208      if( bDelete ){
59209        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
59210      }
59211    }
59212  }
59213
59214#ifdef SQLITE_CHECK_PAGES
59215  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
59216  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
59217    PgHdr *p = sqlite3PagerLookup(pPager, 1);
59218    if( p ){
59219      p->pageHash = 0;
59220      sqlite3PagerUnrefNotNull(p);
59221    }
59222  }
59223#endif
59224
59225  sqlite3BitvecDestroy(pPager->pInJournal);
59226  pPager->pInJournal = 0;
59227  pPager->nRec = 0;
59228  if( rc==SQLITE_OK ){
59229    if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
59230      sqlite3PcacheCleanAll(pPager->pPCache);
59231    }else{
59232      sqlite3PcacheClearWritable(pPager->pPCache);
59233    }
59234    sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
59235  }
59236
59237  if( pagerUseWal(pPager) ){
59238    /* Drop the WAL write-lock, if any. Also, if the connection was in
59239    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
59240    ** lock held on the database file.
59241    */
59242    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
59243    assert( rc2==SQLITE_OK );
59244  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
59245    /* This branch is taken when committing a transaction in rollback-journal
59246    ** mode if the database file on disk is larger than the database image.
59247    ** At this point the journal has been finalized and the transaction
59248    ** successfully committed, but the EXCLUSIVE lock is still held on the
59249    ** file. So it is safe to truncate the database file to its minimum
59250    ** required size.  */
59251    assert( pPager->eLock==EXCLUSIVE_LOCK );
59252    rc = pager_truncate(pPager, pPager->dbSize);
59253  }
59254
59255  if( rc==SQLITE_OK && bCommit ){
59256    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
59257    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
59258  }
59259
59260  if( !pPager->exclusiveMode
59261   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
59262  ){
59263    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
59264  }
59265  pPager->eState = PAGER_READER;
59266  pPager->setSuper = 0;
59267
59268  return (rc==SQLITE_OK?rc2:rc);
59269}
59270
59271/* Forward reference */
59272static int pager_playback(Pager *pPager, int isHot);
59273
59274/*
59275** Execute a rollback if a transaction is active and unlock the
59276** database file.
59277**
59278** If the pager has already entered the ERROR state, do not attempt
59279** the rollback at this time. Instead, pager_unlock() is called. The
59280** call to pager_unlock() will discard all in-memory pages, unlock
59281** the database file and move the pager back to OPEN state. If this
59282** means that there is a hot-journal left in the file-system, the next
59283** connection to obtain a shared lock on the pager (which may be this one)
59284** will roll it back.
59285**
59286** If the pager has not already entered the ERROR state, but an IO or
59287** malloc error occurs during a rollback, then this will itself cause
59288** the pager to enter the ERROR state. Which will be cleared by the
59289** call to pager_unlock(), as described above.
59290*/
59291static void pagerUnlockAndRollback(Pager *pPager){
59292  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
59293    assert( assert_pager_state(pPager) );
59294    if( pPager->eState>=PAGER_WRITER_LOCKED ){
59295      sqlite3BeginBenignMalloc();
59296      sqlite3PagerRollback(pPager);
59297      sqlite3EndBenignMalloc();
59298    }else if( !pPager->exclusiveMode ){
59299      assert( pPager->eState==PAGER_READER );
59300      pager_end_transaction(pPager, 0, 0);
59301    }
59302  }else if( pPager->eState==PAGER_ERROR
59303         && pPager->journalMode==PAGER_JOURNALMODE_MEMORY
59304         && isOpen(pPager->jfd)
59305  ){
59306    /* Special case for a ROLLBACK due to I/O error with an in-memory
59307    ** journal:  We have to rollback immediately, before the journal is
59308    ** closed, because once it is closed, all content is forgotten. */
59309    int errCode = pPager->errCode;
59310    u8 eLock = pPager->eLock;
59311    pPager->eState = PAGER_OPEN;
59312    pPager->errCode = SQLITE_OK;
59313    pPager->eLock = EXCLUSIVE_LOCK;
59314    pager_playback(pPager, 1);
59315    pPager->errCode = errCode;
59316    pPager->eLock = eLock;
59317  }
59318  pager_unlock(pPager);
59319}
59320
59321/*
59322** Parameter aData must point to a buffer of pPager->pageSize bytes
59323** of data. Compute and return a checksum based on the contents of the
59324** page of data and the current value of pPager->cksumInit.
59325**
59326** This is not a real checksum. It is really just the sum of the
59327** random initial value (pPager->cksumInit) and every 200th byte
59328** of the page data, starting with byte offset (pPager->pageSize%200).
59329** Each byte is interpreted as an 8-bit unsigned integer.
59330**
59331** Changing the formula used to compute this checksum results in an
59332** incompatible journal file format.
59333**
59334** If journal corruption occurs due to a power failure, the most likely
59335** scenario is that one end or the other of the record will be changed.
59336** It is much less likely that the two ends of the journal record will be
59337** correct and the middle be corrupt.  Thus, this "checksum" scheme,
59338** though fast and simple, catches the mostly likely kind of corruption.
59339*/
59340static u32 pager_cksum(Pager *pPager, const u8 *aData){
59341  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
59342  int i = pPager->pageSize-200;          /* Loop counter */
59343  while( i>0 ){
59344    cksum += aData[i];
59345    i -= 200;
59346  }
59347  return cksum;
59348}
59349
59350/*
59351** Read a single page from either the journal file (if isMainJrnl==1) or
59352** from the sub-journal (if isMainJrnl==0) and playback that page.
59353** The page begins at offset *pOffset into the file. The *pOffset
59354** value is increased to the start of the next page in the journal.
59355**
59356** The main rollback journal uses checksums - the statement journal does
59357** not.
59358**
59359** If the page number of the page record read from the (sub-)journal file
59360** is greater than the current value of Pager.dbSize, then playback is
59361** skipped and SQLITE_OK is returned.
59362**
59363** If pDone is not NULL, then it is a record of pages that have already
59364** been played back.  If the page at *pOffset has already been played back
59365** (if the corresponding pDone bit is set) then skip the playback.
59366** Make sure the pDone bit corresponding to the *pOffset page is set
59367** prior to returning.
59368**
59369** If the page record is successfully read from the (sub-)journal file
59370** and played back, then SQLITE_OK is returned. If an IO error occurs
59371** while reading the record from the (sub-)journal file or while writing
59372** to the database file, then the IO error code is returned. If data
59373** is successfully read from the (sub-)journal file but appears to be
59374** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
59375** two circumstances:
59376**
59377**   * If the record page-number is illegal (0 or PAGER_SJ_PGNO), or
59378**   * If the record is being rolled back from the main journal file
59379**     and the checksum field does not match the record content.
59380**
59381** Neither of these two scenarios are possible during a savepoint rollback.
59382**
59383** If this is a savepoint rollback, then memory may have to be dynamically
59384** allocated by this function. If this is the case and an allocation fails,
59385** SQLITE_NOMEM is returned.
59386*/
59387static int pager_playback_one_page(
59388  Pager *pPager,                /* The pager being played back */
59389  i64 *pOffset,                 /* Offset of record to playback */
59390  Bitvec *pDone,                /* Bitvec of pages already played back */
59391  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
59392  int isSavepnt                 /* True for a savepoint rollback */
59393){
59394  int rc;
59395  PgHdr *pPg;                   /* An existing page in the cache */
59396  Pgno pgno;                    /* The page number of a page in journal */
59397  u32 cksum;                    /* Checksum used for sanity checking */
59398  char *aData;                  /* Temporary storage for the page */
59399  sqlite3_file *jfd;            /* The file descriptor for the journal file */
59400  int isSynced;                 /* True if journal page is synced */
59401
59402  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
59403  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
59404  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
59405  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
59406
59407  aData = pPager->pTmpSpace;
59408  assert( aData );         /* Temp storage must have already been allocated */
59409  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
59410
59411  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
59412  ** or savepoint rollback done at the request of the caller) or this is
59413  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
59414  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
59415  ** only reads from the main journal, not the sub-journal.
59416  */
59417  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
59418       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
59419  );
59420  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
59421
59422  /* Read the page number and page data from the journal or sub-journal
59423  ** file. Return an error code to the caller if an IO error occurs.
59424  */
59425  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
59426  rc = read32bits(jfd, *pOffset, &pgno);
59427  if( rc!=SQLITE_OK ) return rc;
59428  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
59429  if( rc!=SQLITE_OK ) return rc;
59430  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
59431
59432  /* Sanity checking on the page.  This is more important that I originally
59433  ** thought.  If a power failure occurs while the journal is being written,
59434  ** it could cause invalid data to be written into the journal.  We need to
59435  ** detect this invalid data (with high probability) and ignore it.
59436  */
59437  if( pgno==0 || pgno==PAGER_SJ_PGNO(pPager) ){
59438    assert( !isSavepnt );
59439    return SQLITE_DONE;
59440  }
59441  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
59442    return SQLITE_OK;
59443  }
59444  if( isMainJrnl ){
59445    rc = read32bits(jfd, (*pOffset)-4, &cksum);
59446    if( rc ) return rc;
59447    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
59448      return SQLITE_DONE;
59449    }
59450  }
59451
59452  /* If this page has already been played back before during the current
59453  ** rollback, then don't bother to play it back again.
59454  */
59455  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
59456    return rc;
59457  }
59458
59459  /* When playing back page 1, restore the nReserve setting
59460  */
59461  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
59462    pPager->nReserve = ((u8*)aData)[20];
59463  }
59464
59465  /* If the pager is in CACHEMOD state, then there must be a copy of this
59466  ** page in the pager cache. In this case just update the pager cache,
59467  ** not the database file. The page is left marked dirty in this case.
59468  **
59469  ** An exception to the above rule: If the database is in no-sync mode
59470  ** and a page is moved during an incremental vacuum then the page may
59471  ** not be in the pager cache. Later: if a malloc() or IO error occurs
59472  ** during a Movepage() call, then the page may not be in the cache
59473  ** either. So the condition described in the above paragraph is not
59474  ** assert()able.
59475  **
59476  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
59477  ** pager cache if it exists and the main file. The page is then marked
59478  ** not dirty. Since this code is only executed in PAGER_OPEN state for
59479  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
59480  ** if the pager is in OPEN state.
59481  **
59482  ** Ticket #1171:  The statement journal might contain page content that is
59483  ** different from the page content at the start of the transaction.
59484  ** This occurs when a page is changed prior to the start of a statement
59485  ** then changed again within the statement.  When rolling back such a
59486  ** statement we must not write to the original database unless we know
59487  ** for certain that original page contents are synced into the main rollback
59488  ** journal.  Otherwise, a power loss might leave modified data in the
59489  ** database file without an entry in the rollback journal that can
59490  ** restore the database to its original form.  Two conditions must be
59491  ** met before writing to the database files. (1) the database must be
59492  ** locked.  (2) we know that the original page content is fully synced
59493  ** in the main journal either because the page is not in cache or else
59494  ** the page is marked as needSync==0.
59495  **
59496  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
59497  ** is possible to fail a statement on a database that does not yet exist.
59498  ** Do not attempt to write if database file has never been opened.
59499  */
59500  if( pagerUseWal(pPager) ){
59501    pPg = 0;
59502  }else{
59503    pPg = sqlite3PagerLookup(pPager, pgno);
59504  }
59505  assert( pPg || !MEMDB );
59506  assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
59507  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
59508           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
59509           (isMainJrnl?"main-journal":"sub-journal")
59510  ));
59511  if( isMainJrnl ){
59512    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
59513  }else{
59514    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
59515  }
59516  if( isOpen(pPager->fd)
59517   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
59518   && isSynced
59519  ){
59520    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
59521    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
59522    assert( !pagerUseWal(pPager) );
59523
59524    /* Write the data read from the journal back into the database file.
59525    ** This is usually safe even for an encrypted database - as the data
59526    ** was encrypted before it was written to the journal file. The exception
59527    ** is if the data was just read from an in-memory sub-journal. In that
59528    ** case it must be encrypted here before it is copied into the database
59529    ** file.  */
59530    rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
59531
59532    if( pgno>pPager->dbFileSize ){
59533      pPager->dbFileSize = pgno;
59534    }
59535    if( pPager->pBackup ){
59536      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
59537    }
59538  }else if( !isMainJrnl && pPg==0 ){
59539    /* If this is a rollback of a savepoint and data was not written to
59540    ** the database and the page is not in-memory, there is a potential
59541    ** problem. When the page is next fetched by the b-tree layer, it
59542    ** will be read from the database file, which may or may not be
59543    ** current.
59544    **
59545    ** There are a couple of different ways this can happen. All are quite
59546    ** obscure. When running in synchronous mode, this can only happen
59547    ** if the page is on the free-list at the start of the transaction, then
59548    ** populated, then moved using sqlite3PagerMovepage().
59549    **
59550    ** The solution is to add an in-memory page to the cache containing
59551    ** the data just read from the sub-journal. Mark the page as dirty
59552    ** and if the pager requires a journal-sync, then mark the page as
59553    ** requiring a journal-sync before it is written.
59554    */
59555    assert( isSavepnt );
59556    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
59557    pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
59558    rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
59559    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
59560    pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
59561    if( rc!=SQLITE_OK ) return rc;
59562    sqlite3PcacheMakeDirty(pPg);
59563  }
59564  if( pPg ){
59565    /* No page should ever be explicitly rolled back that is in use, except
59566    ** for page 1 which is held in use in order to keep the lock on the
59567    ** database active. However such a page may be rolled back as a result
59568    ** of an internal error resulting in an automatic call to
59569    ** sqlite3PagerRollback().
59570    */
59571    void *pData;
59572    pData = pPg->pData;
59573    memcpy(pData, (u8*)aData, pPager->pageSize);
59574    pPager->xReiniter(pPg);
59575    /* It used to be that sqlite3PcacheMakeClean(pPg) was called here.  But
59576    ** that call was dangerous and had no detectable benefit since the cache
59577    ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
59578    ** has been removed. */
59579    pager_set_pagehash(pPg);
59580
59581    /* If this was page 1, then restore the value of Pager.dbFileVers.
59582    ** Do this before any decoding. */
59583    if( pgno==1 ){
59584      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
59585    }
59586    sqlite3PcacheRelease(pPg);
59587  }
59588  return rc;
59589}
59590
59591/*
59592** Parameter zSuper is the name of a super-journal file. A single journal
59593** file that referred to the super-journal file has just been rolled back.
59594** This routine checks if it is possible to delete the super-journal file,
59595** and does so if it is.
59596**
59597** Argument zSuper may point to Pager.pTmpSpace. So that buffer is not
59598** available for use within this function.
59599**
59600** When a super-journal file is created, it is populated with the names
59601** of all of its child journals, one after another, formatted as utf-8
59602** encoded text. The end of each child journal file is marked with a
59603** nul-terminator byte (0x00). i.e. the entire contents of a super-journal
59604** file for a transaction involving two databases might be:
59605**
59606**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
59607**
59608** A super-journal file may only be deleted once all of its child
59609** journals have been rolled back.
59610**
59611** This function reads the contents of the super-journal file into
59612** memory and loops through each of the child journal names. For
59613** each child journal, it checks if:
59614**
59615**   * if the child journal exists, and if so
59616**   * if the child journal contains a reference to super-journal
59617**     file zSuper
59618**
59619** If a child journal can be found that matches both of the criteria
59620** above, this function returns without doing anything. Otherwise, if
59621** no such child journal can be found, file zSuper is deleted from
59622** the file-system using sqlite3OsDelete().
59623**
59624** If an IO error within this function, an error code is returned. This
59625** function allocates memory by calling sqlite3Malloc(). If an allocation
59626** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
59627** occur, SQLITE_OK is returned.
59628**
59629** TODO: This function allocates a single block of memory to load
59630** the entire contents of the super-journal file. This could be
59631** a couple of kilobytes or so - potentially larger than the page
59632** size.
59633*/
59634static int pager_delsuper(Pager *pPager, const char *zSuper){
59635  sqlite3_vfs *pVfs = pPager->pVfs;
59636  int rc;                   /* Return code */
59637  sqlite3_file *pSuper;     /* Malloc'd super-journal file descriptor */
59638  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
59639  char *zSuperJournal = 0;  /* Contents of super-journal file */
59640  i64 nSuperJournal;        /* Size of super-journal file */
59641  char *zJournal;           /* Pointer to one journal within MJ file */
59642  char *zSuperPtr;          /* Space to hold super-journal filename */
59643  char *zFree = 0;          /* Free this buffer */
59644  int nSuperPtr;            /* Amount of space allocated to zSuperPtr[] */
59645
59646  /* Allocate space for both the pJournal and pSuper file descriptors.
59647  ** If successful, open the super-journal file for reading.
59648  */
59649  pSuper = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
59650  if( !pSuper ){
59651    rc = SQLITE_NOMEM_BKPT;
59652    pJournal = 0;
59653  }else{
59654    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL);
59655    rc = sqlite3OsOpen(pVfs, zSuper, pSuper, flags, 0);
59656    pJournal = (sqlite3_file *)(((u8 *)pSuper) + pVfs->szOsFile);
59657  }
59658  if( rc!=SQLITE_OK ) goto delsuper_out;
59659
59660  /* Load the entire super-journal file into space obtained from
59661  ** sqlite3_malloc() and pointed to by zSuperJournal.   Also obtain
59662  ** sufficient space (in zSuperPtr) to hold the names of super-journal
59663  ** files extracted from regular rollback-journals.
59664  */
59665  rc = sqlite3OsFileSize(pSuper, &nSuperJournal);
59666  if( rc!=SQLITE_OK ) goto delsuper_out;
59667  nSuperPtr = pVfs->mxPathname+1;
59668  zFree = sqlite3Malloc(4 + nSuperJournal + nSuperPtr + 2);
59669  if( !zFree ){
59670    rc = SQLITE_NOMEM_BKPT;
59671    goto delsuper_out;
59672  }
59673  zFree[0] = zFree[1] = zFree[2] = zFree[3] = 0;
59674  zSuperJournal = &zFree[4];
59675  zSuperPtr = &zSuperJournal[nSuperJournal+2];
59676  rc = sqlite3OsRead(pSuper, zSuperJournal, (int)nSuperJournal, 0);
59677  if( rc!=SQLITE_OK ) goto delsuper_out;
59678  zSuperJournal[nSuperJournal] = 0;
59679  zSuperJournal[nSuperJournal+1] = 0;
59680
59681  zJournal = zSuperJournal;
59682  while( (zJournal-zSuperJournal)<nSuperJournal ){
59683    int exists;
59684    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
59685    if( rc!=SQLITE_OK ){
59686      goto delsuper_out;
59687    }
59688    if( exists ){
59689      /* One of the journals pointed to by the super-journal exists.
59690      ** Open it and check if it points at the super-journal. If
59691      ** so, return without deleting the super-journal file.
59692      ** NB:  zJournal is really a MAIN_JOURNAL.  But call it a
59693      ** SUPER_JOURNAL here so that the VFS will not send the zJournal
59694      ** name into sqlite3_database_file_object().
59695      */
59696      int c;
59697      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL);
59698      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
59699      if( rc!=SQLITE_OK ){
59700        goto delsuper_out;
59701      }
59702
59703      rc = readSuperJournal(pJournal, zSuperPtr, nSuperPtr);
59704      sqlite3OsClose(pJournal);
59705      if( rc!=SQLITE_OK ){
59706        goto delsuper_out;
59707      }
59708
59709      c = zSuperPtr[0]!=0 && strcmp(zSuperPtr, zSuper)==0;
59710      if( c ){
59711        /* We have a match. Do not delete the super-journal file. */
59712        goto delsuper_out;
59713      }
59714    }
59715    zJournal += (sqlite3Strlen30(zJournal)+1);
59716  }
59717
59718  sqlite3OsClose(pSuper);
59719  rc = sqlite3OsDelete(pVfs, zSuper, 0);
59720
59721delsuper_out:
59722  sqlite3_free(zFree);
59723  if( pSuper ){
59724    sqlite3OsClose(pSuper);
59725    assert( !isOpen(pJournal) );
59726    sqlite3_free(pSuper);
59727  }
59728  return rc;
59729}
59730
59731
59732/*
59733** This function is used to change the actual size of the database
59734** file in the file-system. This only happens when committing a transaction,
59735** or rolling back a transaction (including rolling back a hot-journal).
59736**
59737** If the main database file is not open, or the pager is not in either
59738** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
59739** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
59740** If the file on disk is currently larger than nPage pages, then use the VFS
59741** xTruncate() method to truncate it.
59742**
59743** Or, it might be the case that the file on disk is smaller than
59744** nPage pages. Some operating system implementations can get confused if
59745** you try to truncate a file to some size that is larger than it
59746** currently is, so detect this case and write a single zero byte to
59747** the end of the new file instead.
59748**
59749** If successful, return SQLITE_OK. If an IO error occurs while modifying
59750** the database file, return the error code to the caller.
59751*/
59752static int pager_truncate(Pager *pPager, Pgno nPage){
59753  int rc = SQLITE_OK;
59754  assert( pPager->eState!=PAGER_ERROR );
59755  assert( pPager->eState!=PAGER_READER );
59756  PAGERTRACE(("Truncate %d npage %u\n", PAGERID(pPager), nPage));
59757
59758
59759  if( isOpen(pPager->fd)
59760   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
59761  ){
59762    i64 currentSize, newSize;
59763    int szPage = pPager->pageSize;
59764    assert( pPager->eLock==EXCLUSIVE_LOCK );
59765    /* TODO: Is it safe to use Pager.dbFileSize here? */
59766    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
59767    newSize = szPage*(i64)nPage;
59768    if( rc==SQLITE_OK && currentSize!=newSize ){
59769      if( currentSize>newSize ){
59770        rc = sqlite3OsTruncate(pPager->fd, newSize);
59771      }else if( (currentSize+szPage)<=newSize ){
59772        char *pTmp = pPager->pTmpSpace;
59773        memset(pTmp, 0, szPage);
59774        testcase( (newSize-szPage) == currentSize );
59775        testcase( (newSize-szPage) >  currentSize );
59776        sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &newSize);
59777        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
59778      }
59779      if( rc==SQLITE_OK ){
59780        pPager->dbFileSize = nPage;
59781      }
59782    }
59783  }
59784  return rc;
59785}
59786
59787/*
59788** Return a sanitized version of the sector-size of OS file pFile. The
59789** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
59790*/
59791SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
59792  int iRet = sqlite3OsSectorSize(pFile);
59793  if( iRet<32 ){
59794    iRet = 512;
59795  }else if( iRet>MAX_SECTOR_SIZE ){
59796    assert( MAX_SECTOR_SIZE>=512 );
59797    iRet = MAX_SECTOR_SIZE;
59798  }
59799  return iRet;
59800}
59801
59802/*
59803** Set the value of the Pager.sectorSize variable for the given
59804** pager based on the value returned by the xSectorSize method
59805** of the open database file. The sector size will be used
59806** to determine the size and alignment of journal header and
59807** super-journal pointers within created journal files.
59808**
59809** For temporary files the effective sector size is always 512 bytes.
59810**
59811** Otherwise, for non-temporary files, the effective sector size is
59812** the value returned by the xSectorSize() method rounded up to 32 if
59813** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
59814** is greater than MAX_SECTOR_SIZE.
59815**
59816** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
59817** the effective sector size to its minimum value (512).  The purpose of
59818** pPager->sectorSize is to define the "blast radius" of bytes that
59819** might change if a crash occurs while writing to a single byte in
59820** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
59821** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
59822** size.  For backwards compatibility of the rollback journal file format,
59823** we cannot reduce the effective sector size below 512.
59824*/
59825static void setSectorSize(Pager *pPager){
59826  assert( isOpen(pPager->fd) || pPager->tempFile );
59827
59828  if( pPager->tempFile
59829   || (sqlite3OsDeviceCharacteristics(pPager->fd) &
59830              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
59831  ){
59832    /* Sector size doesn't matter for temporary files. Also, the file
59833    ** may not have been opened yet, in which case the OsSectorSize()
59834    ** call will segfault. */
59835    pPager->sectorSize = 512;
59836  }else{
59837    pPager->sectorSize = sqlite3SectorSize(pPager->fd);
59838  }
59839}
59840
59841/*
59842** Playback the journal and thus restore the database file to
59843** the state it was in before we started making changes.
59844**
59845** The journal file format is as follows:
59846**
59847**  (1)  8 byte prefix.  A copy of aJournalMagic[].
59848**  (2)  4 byte big-endian integer which is the number of valid page records
59849**       in the journal.  If this value is 0xffffffff, then compute the
59850**       number of page records from the journal size.
59851**  (3)  4 byte big-endian integer which is the initial value for the
59852**       sanity checksum.
59853**  (4)  4 byte integer which is the number of pages to truncate the
59854**       database to during a rollback.
59855**  (5)  4 byte big-endian integer which is the sector size.  The header
59856**       is this many bytes in size.
59857**  (6)  4 byte big-endian integer which is the page size.
59858**  (7)  zero padding out to the next sector size.
59859**  (8)  Zero or more pages instances, each as follows:
59860**        +  4 byte page number.
59861**        +  pPager->pageSize bytes of data.
59862**        +  4 byte checksum
59863**
59864** When we speak of the journal header, we mean the first 7 items above.
59865** Each entry in the journal is an instance of the 8th item.
59866**
59867** Call the value from the second bullet "nRec".  nRec is the number of
59868** valid page entries in the journal.  In most cases, you can compute the
59869** value of nRec from the size of the journal file.  But if a power
59870** failure occurred while the journal was being written, it could be the
59871** case that the size of the journal file had already been increased but
59872** the extra entries had not yet made it safely to disk.  In such a case,
59873** the value of nRec computed from the file size would be too large.  For
59874** that reason, we always use the nRec value in the header.
59875**
59876** If the nRec value is 0xffffffff it means that nRec should be computed
59877** from the file size.  This value is used when the user selects the
59878** no-sync option for the journal.  A power failure could lead to corruption
59879** in this case.  But for things like temporary table (which will be
59880** deleted when the power is restored) we don't care.
59881**
59882** If the file opened as the journal file is not a well-formed
59883** journal file then all pages up to the first corrupted page are rolled
59884** back (or no pages if the journal header is corrupted). The journal file
59885** is then deleted and SQLITE_OK returned, just as if no corruption had
59886** been encountered.
59887**
59888** If an I/O or malloc() error occurs, the journal-file is not deleted
59889** and an error code is returned.
59890**
59891** The isHot parameter indicates that we are trying to rollback a journal
59892** that might be a hot journal.  Or, it could be that the journal is
59893** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
59894** If the journal really is hot, reset the pager cache prior rolling
59895** back any content.  If the journal is merely persistent, no reset is
59896** needed.
59897*/
59898static int pager_playback(Pager *pPager, int isHot){
59899  sqlite3_vfs *pVfs = pPager->pVfs;
59900  i64 szJ;                 /* Size of the journal file in bytes */
59901  u32 nRec;                /* Number of Records in the journal */
59902  u32 u;                   /* Unsigned loop counter */
59903  Pgno mxPg = 0;           /* Size of the original file in pages */
59904  int rc;                  /* Result code of a subroutine */
59905  int res = 1;             /* Value returned by sqlite3OsAccess() */
59906  char *zSuper = 0;        /* Name of super-journal file if any */
59907  int needPagerReset;      /* True to reset page prior to first page rollback */
59908  int nPlayback = 0;       /* Total number of pages restored from journal */
59909  u32 savedPageSize = pPager->pageSize;
59910
59911  /* Figure out how many records are in the journal.  Abort early if
59912  ** the journal is empty.
59913  */
59914  assert( isOpen(pPager->jfd) );
59915  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
59916  if( rc!=SQLITE_OK ){
59917    goto end_playback;
59918  }
59919
59920  /* Read the super-journal name from the journal, if it is present.
59921  ** If a super-journal file name is specified, but the file is not
59922  ** present on disk, then the journal is not hot and does not need to be
59923  ** played back.
59924  **
59925  ** TODO: Technically the following is an error because it assumes that
59926  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
59927  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
59928  ** mxPathname is 512, which is the same as the minimum allowable value
59929  ** for pageSize.
59930  */
59931  zSuper = pPager->pTmpSpace;
59932  rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1);
59933  if( rc==SQLITE_OK && zSuper[0] ){
59934    rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
59935  }
59936  zSuper = 0;
59937  if( rc!=SQLITE_OK || !res ){
59938    goto end_playback;
59939  }
59940  pPager->journalOff = 0;
59941  needPagerReset = isHot;
59942
59943  /* This loop terminates either when a readJournalHdr() or
59944  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
59945  ** occurs.
59946  */
59947  while( 1 ){
59948    /* Read the next journal header from the journal file.  If there are
59949    ** not enough bytes left in the journal file for a complete header, or
59950    ** it is corrupted, then a process must have failed while writing it.
59951    ** This indicates nothing more needs to be rolled back.
59952    */
59953    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
59954    if( rc!=SQLITE_OK ){
59955      if( rc==SQLITE_DONE ){
59956        rc = SQLITE_OK;
59957      }
59958      goto end_playback;
59959    }
59960
59961    /* If nRec is 0xffffffff, then this journal was created by a process
59962    ** working in no-sync mode. This means that the rest of the journal
59963    ** file consists of pages, there are no more journal headers. Compute
59964    ** the value of nRec based on this assumption.
59965    */
59966    if( nRec==0xffffffff ){
59967      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
59968      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
59969    }
59970
59971    /* If nRec is 0 and this rollback is of a transaction created by this
59972    ** process and if this is the final header in the journal, then it means
59973    ** that this part of the journal was being filled but has not yet been
59974    ** synced to disk.  Compute the number of pages based on the remaining
59975    ** size of the file.
59976    **
59977    ** The third term of the test was added to fix ticket #2565.
59978    ** When rolling back a hot journal, nRec==0 always means that the next
59979    ** chunk of the journal contains zero pages to be rolled back.  But
59980    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
59981    ** the journal, it means that the journal might contain additional
59982    ** pages that need to be rolled back and that the number of pages
59983    ** should be computed based on the journal file size.
59984    */
59985    if( nRec==0 && !isHot &&
59986        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
59987      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
59988    }
59989
59990    /* If this is the first header read from the journal, truncate the
59991    ** database file back to its original size.
59992    */
59993    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
59994      rc = pager_truncate(pPager, mxPg);
59995      if( rc!=SQLITE_OK ){
59996        goto end_playback;
59997      }
59998      pPager->dbSize = mxPg;
59999      if( pPager->mxPgno<mxPg ){
60000        pPager->mxPgno = mxPg;
60001      }
60002    }
60003
60004    /* Copy original pages out of the journal and back into the
60005    ** database file and/or page cache.
60006    */
60007    for(u=0; u<nRec; u++){
60008      if( needPagerReset ){
60009        pager_reset(pPager);
60010        needPagerReset = 0;
60011      }
60012      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
60013      if( rc==SQLITE_OK ){
60014        nPlayback++;
60015      }else{
60016        if( rc==SQLITE_DONE ){
60017          pPager->journalOff = szJ;
60018          break;
60019        }else if( rc==SQLITE_IOERR_SHORT_READ ){
60020          /* If the journal has been truncated, simply stop reading and
60021          ** processing the journal. This might happen if the journal was
60022          ** not completely written and synced prior to a crash.  In that
60023          ** case, the database should have never been written in the
60024          ** first place so it is OK to simply abandon the rollback. */
60025          rc = SQLITE_OK;
60026          goto end_playback;
60027        }else{
60028          /* If we are unable to rollback, quit and return the error
60029          ** code.  This will cause the pager to enter the error state
60030          ** so that no further harm will be done.  Perhaps the next
60031          ** process to come along will be able to rollback the database.
60032          */
60033          goto end_playback;
60034        }
60035      }
60036    }
60037  }
60038  /*NOTREACHED*/
60039  assert( 0 );
60040
60041end_playback:
60042  if( rc==SQLITE_OK ){
60043    rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
60044  }
60045  /* Following a rollback, the database file should be back in its original
60046  ** state prior to the start of the transaction, so invoke the
60047  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
60048  ** assertion that the transaction counter was modified.
60049  */
60050#ifdef SQLITE_DEBUG
60051  sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
60052#endif
60053
60054  /* If this playback is happening automatically as a result of an IO or
60055  ** malloc error that occurred after the change-counter was updated but
60056  ** before the transaction was committed, then the change-counter
60057  ** modification may just have been reverted. If this happens in exclusive
60058  ** mode, then subsequent transactions performed by the connection will not
60059  ** update the change-counter at all. This may lead to cache inconsistency
60060  ** problems for other processes at some point in the future. So, just
60061  ** in case this has happened, clear the changeCountDone flag now.
60062  */
60063  pPager->changeCountDone = pPager->tempFile;
60064
60065  if( rc==SQLITE_OK ){
60066    /* Leave 4 bytes of space before the super-journal filename in memory.
60067    ** This is because it may end up being passed to sqlite3OsOpen(), in
60068    ** which case it requires 4 0x00 bytes in memory immediately before
60069    ** the filename. */
60070    zSuper = &pPager->pTmpSpace[4];
60071    rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1);
60072    testcase( rc!=SQLITE_OK );
60073  }
60074  if( rc==SQLITE_OK
60075   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
60076  ){
60077    rc = sqlite3PagerSync(pPager, 0);
60078  }
60079  if( rc==SQLITE_OK ){
60080    rc = pager_end_transaction(pPager, zSuper[0]!='\0', 0);
60081    testcase( rc!=SQLITE_OK );
60082  }
60083  if( rc==SQLITE_OK && zSuper[0] && res ){
60084    /* If there was a super-journal and this routine will return success,
60085    ** see if it is possible to delete the super-journal.
60086    */
60087    assert( zSuper==&pPager->pTmpSpace[4] );
60088    memset(pPager->pTmpSpace, 0, 4);
60089    rc = pager_delsuper(pPager, zSuper);
60090    testcase( rc!=SQLITE_OK );
60091  }
60092  if( isHot && nPlayback ){
60093    sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
60094                nPlayback, pPager->zJournal);
60095  }
60096
60097  /* The Pager.sectorSize variable may have been updated while rolling
60098  ** back a journal created by a process with a different sector size
60099  ** value. Reset it to the correct value for this process.
60100  */
60101  setSectorSize(pPager);
60102  return rc;
60103}
60104
60105
60106/*
60107** Read the content for page pPg out of the database file (or out of
60108** the WAL if that is where the most recent copy if found) into
60109** pPg->pData. A shared lock or greater must be held on the database
60110** file before this function is called.
60111**
60112** If page 1 is read, then the value of Pager.dbFileVers[] is set to
60113** the value read from the database file.
60114**
60115** If an IO error occurs, then the IO error is returned to the caller.
60116** Otherwise, SQLITE_OK is returned.
60117*/
60118static int readDbPage(PgHdr *pPg){
60119  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
60120  int rc = SQLITE_OK;          /* Return code */
60121
60122#ifndef SQLITE_OMIT_WAL
60123  u32 iFrame = 0;              /* Frame of WAL containing pgno */
60124
60125  assert( pPager->eState>=PAGER_READER && !MEMDB );
60126  assert( isOpen(pPager->fd) );
60127
60128  if( pagerUseWal(pPager) ){
60129    rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
60130    if( rc ) return rc;
60131  }
60132  if( iFrame ){
60133    rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
60134  }else
60135#endif
60136  {
60137    i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
60138    rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
60139    if( rc==SQLITE_IOERR_SHORT_READ ){
60140      rc = SQLITE_OK;
60141    }
60142  }
60143
60144  if( pPg->pgno==1 ){
60145    if( rc ){
60146      /* If the read is unsuccessful, set the dbFileVers[] to something
60147      ** that will never be a valid file version.  dbFileVers[] is a copy
60148      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
60149      ** zero or the size of the database in page. Bytes 32..35 and 35..39
60150      ** should be page numbers which are never 0xffffffff.  So filling
60151      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
60152      **
60153      ** For an encrypted database, the situation is more complex:  bytes
60154      ** 24..39 of the database are white noise.  But the probability of
60155      ** white noise equaling 16 bytes of 0xff is vanishingly small so
60156      ** we should still be ok.
60157      */
60158      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
60159    }else{
60160      u8 *dbFileVers = &((u8*)pPg->pData)[24];
60161      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
60162    }
60163  }
60164  PAGER_INCR(sqlite3_pager_readdb_count);
60165  PAGER_INCR(pPager->nRead);
60166  IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
60167  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
60168               PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
60169
60170  return rc;
60171}
60172
60173/*
60174** Update the value of the change-counter at offsets 24 and 92 in
60175** the header and the sqlite version number at offset 96.
60176**
60177** This is an unconditional update.  See also the pager_incr_changecounter()
60178** routine which only updates the change-counter if the update is actually
60179** needed, as determined by the pPager->changeCountDone state variable.
60180*/
60181static void pager_write_changecounter(PgHdr *pPg){
60182  u32 change_counter;
60183  if( NEVER(pPg==0) ) return;
60184
60185  /* Increment the value just read and write it back to byte 24. */
60186  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
60187  put32bits(((char*)pPg->pData)+24, change_counter);
60188
60189  /* Also store the SQLite version number in bytes 96..99 and in
60190  ** bytes 92..95 store the change counter for which the version number
60191  ** is valid. */
60192  put32bits(((char*)pPg->pData)+92, change_counter);
60193  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
60194}
60195
60196#ifndef SQLITE_OMIT_WAL
60197/*
60198** This function is invoked once for each page that has already been
60199** written into the log file when a WAL transaction is rolled back.
60200** Parameter iPg is the page number of said page. The pCtx argument
60201** is actually a pointer to the Pager structure.
60202**
60203** If page iPg is present in the cache, and has no outstanding references,
60204** it is discarded. Otherwise, if there are one or more outstanding
60205** references, the page content is reloaded from the database. If the
60206** attempt to reload content from the database is required and fails,
60207** return an SQLite error code. Otherwise, SQLITE_OK.
60208*/
60209static int pagerUndoCallback(void *pCtx, Pgno iPg){
60210  int rc = SQLITE_OK;
60211  Pager *pPager = (Pager *)pCtx;
60212  PgHdr *pPg;
60213
60214  assert( pagerUseWal(pPager) );
60215  pPg = sqlite3PagerLookup(pPager, iPg);
60216  if( pPg ){
60217    if( sqlite3PcachePageRefcount(pPg)==1 ){
60218      sqlite3PcacheDrop(pPg);
60219    }else{
60220      rc = readDbPage(pPg);
60221      if( rc==SQLITE_OK ){
60222        pPager->xReiniter(pPg);
60223      }
60224      sqlite3PagerUnrefNotNull(pPg);
60225    }
60226  }
60227
60228  /* Normally, if a transaction is rolled back, any backup processes are
60229  ** updated as data is copied out of the rollback journal and into the
60230  ** database. This is not generally possible with a WAL database, as
60231  ** rollback involves simply truncating the log file. Therefore, if one
60232  ** or more frames have already been written to the log (and therefore
60233  ** also copied into the backup databases) as part of this transaction,
60234  ** the backups must be restarted.
60235  */
60236  sqlite3BackupRestart(pPager->pBackup);
60237
60238  return rc;
60239}
60240
60241/*
60242** This function is called to rollback a transaction on a WAL database.
60243*/
60244static int pagerRollbackWal(Pager *pPager){
60245  int rc;                         /* Return Code */
60246  PgHdr *pList;                   /* List of dirty pages to revert */
60247
60248  /* For all pages in the cache that are currently dirty or have already
60249  ** been written (but not committed) to the log file, do one of the
60250  ** following:
60251  **
60252  **   + Discard the cached page (if refcount==0), or
60253  **   + Reload page content from the database (if refcount>0).
60254  */
60255  pPager->dbSize = pPager->dbOrigSize;
60256  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
60257  pList = sqlite3PcacheDirtyList(pPager->pPCache);
60258  while( pList && rc==SQLITE_OK ){
60259    PgHdr *pNext = pList->pDirty;
60260    rc = pagerUndoCallback((void *)pPager, pList->pgno);
60261    pList = pNext;
60262  }
60263
60264  return rc;
60265}
60266
60267/*
60268** This function is a wrapper around sqlite3WalFrames(). As well as logging
60269** the contents of the list of pages headed by pList (connected by pDirty),
60270** this function notifies any active backup processes that the pages have
60271** changed.
60272**
60273** The list of pages passed into this routine is always sorted by page number.
60274** Hence, if page 1 appears anywhere on the list, it will be the first page.
60275*/
60276static int pagerWalFrames(
60277  Pager *pPager,                  /* Pager object */
60278  PgHdr *pList,                   /* List of frames to log */
60279  Pgno nTruncate,                 /* Database size after this commit */
60280  int isCommit                    /* True if this is a commit */
60281){
60282  int rc;                         /* Return code */
60283  int nList;                      /* Number of pages in pList */
60284  PgHdr *p;                       /* For looping over pages */
60285
60286  assert( pPager->pWal );
60287  assert( pList );
60288#ifdef SQLITE_DEBUG
60289  /* Verify that the page list is in ascending order */
60290  for(p=pList; p && p->pDirty; p=p->pDirty){
60291    assert( p->pgno < p->pDirty->pgno );
60292  }
60293#endif
60294
60295  assert( pList->pDirty==0 || isCommit );
60296  if( isCommit ){
60297    /* If a WAL transaction is being committed, there is no point in writing
60298    ** any pages with page numbers greater than nTruncate into the WAL file.
60299    ** They will never be read by any client. So remove them from the pDirty
60300    ** list here. */
60301    PgHdr **ppNext = &pList;
60302    nList = 0;
60303    for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
60304      if( p->pgno<=nTruncate ){
60305        ppNext = &p->pDirty;
60306        nList++;
60307      }
60308    }
60309    assert( pList );
60310  }else{
60311    nList = 1;
60312  }
60313  pPager->aStat[PAGER_STAT_WRITE] += nList;
60314
60315  if( pList->pgno==1 ) pager_write_changecounter(pList);
60316  rc = sqlite3WalFrames(pPager->pWal,
60317      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
60318  );
60319  if( rc==SQLITE_OK && pPager->pBackup ){
60320    for(p=pList; p; p=p->pDirty){
60321      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
60322    }
60323  }
60324
60325#ifdef SQLITE_CHECK_PAGES
60326  pList = sqlite3PcacheDirtyList(pPager->pPCache);
60327  for(p=pList; p; p=p->pDirty){
60328    pager_set_pagehash(p);
60329  }
60330#endif
60331
60332  return rc;
60333}
60334
60335/*
60336** Begin a read transaction on the WAL.
60337**
60338** This routine used to be called "pagerOpenSnapshot()" because it essentially
60339** makes a snapshot of the database at the current point in time and preserves
60340** that snapshot for use by the reader in spite of concurrently changes by
60341** other writers or checkpointers.
60342*/
60343static int pagerBeginReadTransaction(Pager *pPager){
60344  int rc;                         /* Return code */
60345  int changed = 0;                /* True if cache must be reset */
60346
60347  assert( pagerUseWal(pPager) );
60348  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
60349
60350  /* sqlite3WalEndReadTransaction() was not called for the previous
60351  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
60352  ** are in locking_mode=NORMAL and EndRead() was previously called,
60353  ** the duplicate call is harmless.
60354  */
60355  sqlite3WalEndReadTransaction(pPager->pWal);
60356
60357  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
60358  if( rc!=SQLITE_OK || changed ){
60359    pager_reset(pPager);
60360    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
60361  }
60362
60363  return rc;
60364}
60365#endif
60366
60367/*
60368** This function is called as part of the transition from PAGER_OPEN
60369** to PAGER_READER state to determine the size of the database file
60370** in pages (assuming the page size currently stored in Pager.pageSize).
60371**
60372** If no error occurs, SQLITE_OK is returned and the size of the database
60373** in pages is stored in *pnPage. Otherwise, an error code (perhaps
60374** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
60375*/
60376static int pagerPagecount(Pager *pPager, Pgno *pnPage){
60377  Pgno nPage;                     /* Value to return via *pnPage */
60378
60379  /* Query the WAL sub-system for the database size. The WalDbsize()
60380  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
60381  ** if the database size is not available. The database size is not
60382  ** available from the WAL sub-system if the log file is empty or
60383  ** contains no valid committed transactions.
60384  */
60385  assert( pPager->eState==PAGER_OPEN );
60386  assert( pPager->eLock>=SHARED_LOCK );
60387  assert( isOpen(pPager->fd) );
60388  assert( pPager->tempFile==0 );
60389  nPage = sqlite3WalDbsize(pPager->pWal);
60390
60391  /* If the number of pages in the database is not available from the
60392  ** WAL sub-system, determine the page count based on the size of
60393  ** the database file.  If the size of the database file is not an
60394  ** integer multiple of the page-size, round up the result.
60395  */
60396  if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
60397    i64 n = 0;                    /* Size of db file in bytes */
60398    int rc = sqlite3OsFileSize(pPager->fd, &n);
60399    if( rc!=SQLITE_OK ){
60400      return rc;
60401    }
60402    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
60403  }
60404
60405  /* If the current number of pages in the file is greater than the
60406  ** configured maximum pager number, increase the allowed limit so
60407  ** that the file can be read.
60408  */
60409  if( nPage>pPager->mxPgno ){
60410    pPager->mxPgno = (Pgno)nPage;
60411  }
60412
60413  *pnPage = nPage;
60414  return SQLITE_OK;
60415}
60416
60417#ifndef SQLITE_OMIT_WAL
60418/*
60419** Check if the *-wal file that corresponds to the database opened by pPager
60420** exists if the database is not empty, or verify that the *-wal file does
60421** not exist (by deleting it) if the database file is empty.
60422**
60423** If the database is not empty and the *-wal file exists, open the pager
60424** in WAL mode.  If the database is empty or if no *-wal file exists and
60425** if no error occurs, make sure Pager.journalMode is not set to
60426** PAGER_JOURNALMODE_WAL.
60427**
60428** Return SQLITE_OK or an error code.
60429**
60430** The caller must hold a SHARED lock on the database file to call this
60431** function. Because an EXCLUSIVE lock on the db file is required to delete
60432** a WAL on a none-empty database, this ensures there is no race condition
60433** between the xAccess() below and an xDelete() being executed by some
60434** other connection.
60435*/
60436static int pagerOpenWalIfPresent(Pager *pPager){
60437  int rc = SQLITE_OK;
60438  assert( pPager->eState==PAGER_OPEN );
60439  assert( pPager->eLock>=SHARED_LOCK );
60440
60441  if( !pPager->tempFile ){
60442    int isWal;                    /* True if WAL file exists */
60443    rc = sqlite3OsAccess(
60444        pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
60445    );
60446    if( rc==SQLITE_OK ){
60447      if( isWal ){
60448        Pgno nPage;                   /* Size of the database file */
60449
60450        rc = pagerPagecount(pPager, &nPage);
60451        if( rc ) return rc;
60452        if( nPage==0 ){
60453          rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
60454        }else{
60455          testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
60456          rc = sqlite3PagerOpenWal(pPager, 0);
60457        }
60458      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
60459        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
60460      }
60461    }
60462  }
60463  return rc;
60464}
60465#endif
60466
60467/*
60468** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
60469** the entire super-journal file. The case pSavepoint==NULL occurs when
60470** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
60471** savepoint.
60472**
60473** When pSavepoint is not NULL (meaning a non-transaction savepoint is
60474** being rolled back), then the rollback consists of up to three stages,
60475** performed in the order specified:
60476**
60477**   * Pages are played back from the main journal starting at byte
60478**     offset PagerSavepoint.iOffset and continuing to
60479**     PagerSavepoint.iHdrOffset, or to the end of the main journal
60480**     file if PagerSavepoint.iHdrOffset is zero.
60481**
60482**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
60483**     back starting from the journal header immediately following
60484**     PagerSavepoint.iHdrOffset to the end of the main journal file.
60485**
60486**   * Pages are then played back from the sub-journal file, starting
60487**     with the PagerSavepoint.iSubRec and continuing to the end of
60488**     the journal file.
60489**
60490** Throughout the rollback process, each time a page is rolled back, the
60491** corresponding bit is set in a bitvec structure (variable pDone in the
60492** implementation below). This is used to ensure that a page is only
60493** rolled back the first time it is encountered in either journal.
60494**
60495** If pSavepoint is NULL, then pages are only played back from the main
60496** journal file. There is no need for a bitvec in this case.
60497**
60498** In either case, before playback commences the Pager.dbSize variable
60499** is reset to the value that it held at the start of the savepoint
60500** (or transaction). No page with a page-number greater than this value
60501** is played back. If one is encountered it is simply skipped.
60502*/
60503static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
60504  i64 szJ;                 /* Effective size of the main journal */
60505  i64 iHdrOff;             /* End of first segment of main-journal records */
60506  int rc = SQLITE_OK;      /* Return code */
60507  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
60508
60509  assert( pPager->eState!=PAGER_ERROR );
60510  assert( pPager->eState>=PAGER_WRITER_LOCKED );
60511
60512  /* Allocate a bitvec to use to store the set of pages rolled back */
60513  if( pSavepoint ){
60514    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
60515    if( !pDone ){
60516      return SQLITE_NOMEM_BKPT;
60517    }
60518  }
60519
60520  /* Set the database size back to the value it was before the savepoint
60521  ** being reverted was opened.
60522  */
60523  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
60524  pPager->changeCountDone = pPager->tempFile;
60525
60526  if( !pSavepoint && pagerUseWal(pPager) ){
60527    return pagerRollbackWal(pPager);
60528  }
60529
60530  /* Use pPager->journalOff as the effective size of the main rollback
60531  ** journal.  The actual file might be larger than this in
60532  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
60533  ** past pPager->journalOff is off-limits to us.
60534  */
60535  szJ = pPager->journalOff;
60536  assert( pagerUseWal(pPager)==0 || szJ==0 );
60537
60538  /* Begin by rolling back records from the main journal starting at
60539  ** PagerSavepoint.iOffset and continuing to the next journal header.
60540  ** There might be records in the main journal that have a page number
60541  ** greater than the current database size (pPager->dbSize) but those
60542  ** will be skipped automatically.  Pages are added to pDone as they
60543  ** are played back.
60544  */
60545  if( pSavepoint && !pagerUseWal(pPager) ){
60546    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
60547    pPager->journalOff = pSavepoint->iOffset;
60548    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
60549      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
60550    }
60551    assert( rc!=SQLITE_DONE );
60552  }else{
60553    pPager->journalOff = 0;
60554  }
60555
60556  /* Continue rolling back records out of the main journal starting at
60557  ** the first journal header seen and continuing until the effective end
60558  ** of the main journal file.  Continue to skip out-of-range pages and
60559  ** continue adding pages rolled back to pDone.
60560  */
60561  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
60562    u32 ii;            /* Loop counter */
60563    u32 nJRec = 0;     /* Number of Journal Records */
60564    u32 dummy;
60565    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
60566    assert( rc!=SQLITE_DONE );
60567
60568    /*
60569    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
60570    ** test is related to ticket #2565.  See the discussion in the
60571    ** pager_playback() function for additional information.
60572    */
60573    if( nJRec==0
60574     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
60575    ){
60576      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
60577    }
60578    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
60579      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
60580    }
60581    assert( rc!=SQLITE_DONE );
60582  }
60583  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
60584
60585  /* Finally,  rollback pages from the sub-journal.  Page that were
60586  ** previously rolled back out of the main journal (and are hence in pDone)
60587  ** will be skipped.  Out-of-range pages are also skipped.
60588  */
60589  if( pSavepoint ){
60590    u32 ii;            /* Loop counter */
60591    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
60592
60593    if( pagerUseWal(pPager) ){
60594      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
60595    }
60596    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
60597      assert( offset==(i64)ii*(4+pPager->pageSize) );
60598      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
60599    }
60600    assert( rc!=SQLITE_DONE );
60601  }
60602
60603  sqlite3BitvecDestroy(pDone);
60604  if( rc==SQLITE_OK ){
60605    pPager->journalOff = szJ;
60606  }
60607
60608  return rc;
60609}
60610
60611/*
60612** Change the maximum number of in-memory pages that are allowed
60613** before attempting to recycle clean and unused pages.
60614*/
60615SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
60616  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
60617}
60618
60619/*
60620** Change the maximum number of in-memory pages that are allowed
60621** before attempting to spill pages to journal.
60622*/
60623SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
60624  return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
60625}
60626
60627/*
60628** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
60629*/
60630static void pagerFixMaplimit(Pager *pPager){
60631#if SQLITE_MAX_MMAP_SIZE>0
60632  sqlite3_file *fd = pPager->fd;
60633  if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
60634    sqlite3_int64 sz;
60635    sz = pPager->szMmap;
60636    pPager->bUseFetch = (sz>0);
60637    setGetterMethod(pPager);
60638    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
60639  }
60640#endif
60641}
60642
60643/*
60644** Change the maximum size of any memory mapping made of the database file.
60645*/
60646SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
60647  pPager->szMmap = szMmap;
60648  pagerFixMaplimit(pPager);
60649}
60650
60651/*
60652** Free as much memory as possible from the pager.
60653*/
60654SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
60655  sqlite3PcacheShrink(pPager->pPCache);
60656}
60657
60658/*
60659** Adjust settings of the pager to those specified in the pgFlags parameter.
60660**
60661** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
60662** of the database to damage due to OS crashes or power failures by
60663** changing the number of syncs()s when writing the journals.
60664** There are four levels:
60665**
60666**    OFF       sqlite3OsSync() is never called.  This is the default
60667**              for temporary and transient files.
60668**
60669**    NORMAL    The journal is synced once before writes begin on the
60670**              database.  This is normally adequate protection, but
60671**              it is theoretically possible, though very unlikely,
60672**              that an inopertune power failure could leave the journal
60673**              in a state which would cause damage to the database
60674**              when it is rolled back.
60675**
60676**    FULL      The journal is synced twice before writes begin on the
60677**              database (with some additional information - the nRec field
60678**              of the journal header - being written in between the two
60679**              syncs).  If we assume that writing a
60680**              single disk sector is atomic, then this mode provides
60681**              assurance that the journal will not be corrupted to the
60682**              point of causing damage to the database during rollback.
60683**
60684**    EXTRA     This is like FULL except that is also syncs the directory
60685**              that contains the rollback journal after the rollback
60686**              journal is unlinked.
60687**
60688** The above is for a rollback-journal mode.  For WAL mode, OFF continues
60689** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
60690** prior to the start of checkpoint and that the database file is synced
60691** at the conclusion of the checkpoint if the entire content of the WAL
60692** was written back into the database.  But no sync operations occur for
60693** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
60694** file is synced following each commit operation, in addition to the
60695** syncs associated with NORMAL.  There is no difference between FULL
60696** and EXTRA for WAL mode.
60697**
60698** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
60699** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
60700** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
60701** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
60702** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
60703** synchronous=FULL versus synchronous=NORMAL setting determines when
60704** the xSync primitive is called and is relevant to all platforms.
60705**
60706** Numeric values associated with these states are OFF==1, NORMAL=2,
60707** and FULL=3.
60708*/
60709SQLITE_PRIVATE void sqlite3PagerSetFlags(
60710  Pager *pPager,        /* The pager to set safety level for */
60711  unsigned pgFlags      /* Various flags */
60712){
60713  unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
60714  if( pPager->tempFile ){
60715    pPager->noSync = 1;
60716    pPager->fullSync = 0;
60717    pPager->extraSync = 0;
60718  }else{
60719    pPager->noSync =  level==PAGER_SYNCHRONOUS_OFF ?1:0;
60720    pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
60721    pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
60722  }
60723  if( pPager->noSync ){
60724    pPager->syncFlags = 0;
60725  }else if( pgFlags & PAGER_FULLFSYNC ){
60726    pPager->syncFlags = SQLITE_SYNC_FULL;
60727  }else{
60728    pPager->syncFlags = SQLITE_SYNC_NORMAL;
60729  }
60730  pPager->walSyncFlags = (pPager->syncFlags<<2);
60731  if( pPager->fullSync ){
60732    pPager->walSyncFlags |= pPager->syncFlags;
60733  }
60734  if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
60735    pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
60736  }
60737  if( pgFlags & PAGER_CACHESPILL ){
60738    pPager->doNotSpill &= ~SPILLFLAG_OFF;
60739  }else{
60740    pPager->doNotSpill |= SPILLFLAG_OFF;
60741  }
60742}
60743
60744/*
60745** The following global variable is incremented whenever the library
60746** attempts to open a temporary file.  This information is used for
60747** testing and analysis only.
60748*/
60749#ifdef SQLITE_TEST
60750SQLITE_API int sqlite3_opentemp_count = 0;
60751#endif
60752
60753/*
60754** Open a temporary file.
60755**
60756** Write the file descriptor into *pFile. Return SQLITE_OK on success
60757** or some other error code if we fail. The OS will automatically
60758** delete the temporary file when it is closed.
60759**
60760** The flags passed to the VFS layer xOpen() call are those specified
60761** by parameter vfsFlags ORed with the following:
60762**
60763**     SQLITE_OPEN_READWRITE
60764**     SQLITE_OPEN_CREATE
60765**     SQLITE_OPEN_EXCLUSIVE
60766**     SQLITE_OPEN_DELETEONCLOSE
60767*/
60768static int pagerOpentemp(
60769  Pager *pPager,        /* The pager object */
60770  sqlite3_file *pFile,  /* Write the file descriptor here */
60771  int vfsFlags          /* Flags passed through to the VFS */
60772){
60773  int rc;               /* Return code */
60774
60775#ifdef SQLITE_TEST
60776  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
60777#endif
60778
60779  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
60780            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
60781  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
60782  assert( rc!=SQLITE_OK || isOpen(pFile) );
60783  return rc;
60784}
60785
60786/*
60787** Set the busy handler function.
60788**
60789** The pager invokes the busy-handler if sqlite3OsLock() returns
60790** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
60791** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
60792** lock. It does *not* invoke the busy handler when upgrading from
60793** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
60794** (which occurs during hot-journal rollback). Summary:
60795**
60796**   Transition                        | Invokes xBusyHandler
60797**   --------------------------------------------------------
60798**   NO_LOCK       -> SHARED_LOCK      | Yes
60799**   SHARED_LOCK   -> RESERVED_LOCK    | No
60800**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
60801**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
60802**
60803** If the busy-handler callback returns non-zero, the lock is
60804** retried. If it returns zero, then the SQLITE_BUSY error is
60805** returned to the caller of the pager API function.
60806*/
60807SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(
60808  Pager *pPager,                       /* Pager object */
60809  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
60810  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
60811){
60812  void **ap;
60813  pPager->xBusyHandler = xBusyHandler;
60814  pPager->pBusyHandlerArg = pBusyHandlerArg;
60815  ap = (void **)&pPager->xBusyHandler;
60816  assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
60817  assert( ap[1]==pBusyHandlerArg );
60818  sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
60819}
60820
60821/*
60822** Change the page size used by the Pager object. The new page size
60823** is passed in *pPageSize.
60824**
60825** If the pager is in the error state when this function is called, it
60826** is a no-op. The value returned is the error state error code (i.e.
60827** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
60828**
60829** Otherwise, if all of the following are true:
60830**
60831**   * the new page size (value of *pPageSize) is valid (a power
60832**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
60833**
60834**   * there are no outstanding page references, and
60835**
60836**   * the database is either not an in-memory database or it is
60837**     an in-memory database that currently consists of zero pages.
60838**
60839** then the pager object page size is set to *pPageSize.
60840**
60841** If the page size is changed, then this function uses sqlite3PagerMalloc()
60842** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
60843** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
60844** In all other cases, SQLITE_OK is returned.
60845**
60846** If the page size is not changed, either because one of the enumerated
60847** conditions above is not true, the pager was in error state when this
60848** function was called, or because the memory allocation attempt failed,
60849** then *pPageSize is set to the old, retained page size before returning.
60850*/
60851SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
60852  int rc = SQLITE_OK;
60853
60854  /* It is not possible to do a full assert_pager_state() here, as this
60855  ** function may be called from within PagerOpen(), before the state
60856  ** of the Pager object is internally consistent.
60857  **
60858  ** At one point this function returned an error if the pager was in
60859  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
60860  ** there is at least one outstanding page reference, this function
60861  ** is a no-op for that case anyhow.
60862  */
60863
60864  u32 pageSize = *pPageSize;
60865  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
60866  if( (pPager->memDb==0 || pPager->dbSize==0)
60867   && sqlite3PcacheRefCount(pPager->pPCache)==0
60868   && pageSize && pageSize!=(u32)pPager->pageSize
60869  ){
60870    char *pNew = NULL;             /* New temp space */
60871    i64 nByte = 0;
60872
60873    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
60874      rc = sqlite3OsFileSize(pPager->fd, &nByte);
60875    }
60876    if( rc==SQLITE_OK ){
60877      /* 8 bytes of zeroed overrun space is sufficient so that the b-tree
60878      * cell header parser will never run off the end of the allocation */
60879      pNew = (char *)sqlite3PageMalloc(pageSize+8);
60880      if( !pNew ){
60881        rc = SQLITE_NOMEM_BKPT;
60882      }else{
60883        memset(pNew+pageSize, 0, 8);
60884      }
60885    }
60886
60887    if( rc==SQLITE_OK ){
60888      pager_reset(pPager);
60889      rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
60890    }
60891    if( rc==SQLITE_OK ){
60892      sqlite3PageFree(pPager->pTmpSpace);
60893      pPager->pTmpSpace = pNew;
60894      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
60895      pPager->pageSize = pageSize;
60896      pPager->lckPgno = (Pgno)(PENDING_BYTE/pageSize) + 1;
60897    }else{
60898      sqlite3PageFree(pNew);
60899    }
60900  }
60901
60902  *pPageSize = pPager->pageSize;
60903  if( rc==SQLITE_OK ){
60904    if( nReserve<0 ) nReserve = pPager->nReserve;
60905    assert( nReserve>=0 && nReserve<1000 );
60906    pPager->nReserve = (i16)nReserve;
60907    pagerFixMaplimit(pPager);
60908  }
60909  return rc;
60910}
60911
60912/*
60913** Return a pointer to the "temporary page" buffer held internally
60914** by the pager.  This is a buffer that is big enough to hold the
60915** entire content of a database page.  This buffer is used internally
60916** during rollback and will be overwritten whenever a rollback
60917** occurs.  But other modules are free to use it too, as long as
60918** no rollbacks are happening.
60919*/
60920SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
60921  return pPager->pTmpSpace;
60922}
60923
60924/*
60925** Attempt to set the maximum database page count if mxPage is positive.
60926** Make no changes if mxPage is zero or negative.  And never reduce the
60927** maximum page count below the current size of the database.
60928**
60929** Regardless of mxPage, return the current maximum page count.
60930*/
60931SQLITE_PRIVATE Pgno sqlite3PagerMaxPageCount(Pager *pPager, Pgno mxPage){
60932  if( mxPage>0 ){
60933    pPager->mxPgno = mxPage;
60934  }
60935  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
60936  /* assert( pPager->mxPgno>=pPager->dbSize ); */
60937  /* OP_MaxPgcnt ensures that the parameter passed to this function is not
60938  ** less than the total number of valid pages in the database. But this
60939  ** may be less than Pager.dbSize, and so the assert() above is not valid */
60940  return pPager->mxPgno;
60941}
60942
60943/*
60944** The following set of routines are used to disable the simulated
60945** I/O error mechanism.  These routines are used to avoid simulated
60946** errors in places where we do not care about errors.
60947**
60948** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
60949** and generate no code.
60950*/
60951#ifdef SQLITE_TEST
60952SQLITE_API extern int sqlite3_io_error_pending;
60953SQLITE_API extern int sqlite3_io_error_hit;
60954static int saved_cnt;
60955void disable_simulated_io_errors(void){
60956  saved_cnt = sqlite3_io_error_pending;
60957  sqlite3_io_error_pending = -1;
60958}
60959void enable_simulated_io_errors(void){
60960  sqlite3_io_error_pending = saved_cnt;
60961}
60962#else
60963# define disable_simulated_io_errors()
60964# define enable_simulated_io_errors()
60965#endif
60966
60967/*
60968** Read the first N bytes from the beginning of the file into memory
60969** that pDest points to.
60970**
60971** If the pager was opened on a transient file (zFilename==""), or
60972** opened on a file less than N bytes in size, the output buffer is
60973** zeroed and SQLITE_OK returned. The rationale for this is that this
60974** function is used to read database headers, and a new transient or
60975** zero sized database has a header than consists entirely of zeroes.
60976**
60977** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
60978** the error code is returned to the caller and the contents of the
60979** output buffer undefined.
60980*/
60981SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
60982  int rc = SQLITE_OK;
60983  memset(pDest, 0, N);
60984  assert( isOpen(pPager->fd) || pPager->tempFile );
60985
60986  /* This routine is only called by btree immediately after creating
60987  ** the Pager object.  There has not been an opportunity to transition
60988  ** to WAL mode yet.
60989  */
60990  assert( !pagerUseWal(pPager) );
60991
60992  if( isOpen(pPager->fd) ){
60993    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
60994    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
60995    if( rc==SQLITE_IOERR_SHORT_READ ){
60996      rc = SQLITE_OK;
60997    }
60998  }
60999  return rc;
61000}
61001
61002/*
61003** This function may only be called when a read-transaction is open on
61004** the pager. It returns the total number of pages in the database.
61005**
61006** However, if the file is between 1 and <page-size> bytes in size, then
61007** this is considered a 1 page file.
61008*/
61009SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
61010  assert( pPager->eState>=PAGER_READER );
61011  assert( pPager->eState!=PAGER_WRITER_FINISHED );
61012  *pnPage = (int)pPager->dbSize;
61013}
61014
61015
61016/*
61017** Try to obtain a lock of type locktype on the database file. If
61018** a similar or greater lock is already held, this function is a no-op
61019** (returning SQLITE_OK immediately).
61020**
61021** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
61022** the busy callback if the lock is currently not available. Repeat
61023** until the busy callback returns false or until the attempt to
61024** obtain the lock succeeds.
61025**
61026** Return SQLITE_OK on success and an error code if we cannot obtain
61027** the lock. If the lock is obtained successfully, set the Pager.state
61028** variable to locktype before returning.
61029*/
61030static int pager_wait_on_lock(Pager *pPager, int locktype){
61031  int rc;                              /* Return code */
61032
61033  /* Check that this is either a no-op (because the requested lock is
61034  ** already held), or one of the transitions that the busy-handler
61035  ** may be invoked during, according to the comment above
61036  ** sqlite3PagerSetBusyhandler().
61037  */
61038  assert( (pPager->eLock>=locktype)
61039       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
61040       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
61041  );
61042
61043  do {
61044    rc = pagerLockDb(pPager, locktype);
61045  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
61046  return rc;
61047}
61048
61049/*
61050** Function assertTruncateConstraint(pPager) checks that one of the
61051** following is true for all dirty pages currently in the page-cache:
61052**
61053**   a) The page number is less than or equal to the size of the
61054**      current database image, in pages, OR
61055**
61056**   b) if the page content were written at this time, it would not
61057**      be necessary to write the current content out to the sub-journal.
61058**
61059** If the condition asserted by this function were not true, and the
61060** dirty page were to be discarded from the cache via the pagerStress()
61061** routine, pagerStress() would not write the current page content to
61062** the database file. If a savepoint transaction were rolled back after
61063** this happened, the correct behavior would be to restore the current
61064** content of the page. However, since this content is not present in either
61065** the database file or the portion of the rollback journal and
61066** sub-journal rolled back the content could not be restored and the
61067** database image would become corrupt. It is therefore fortunate that
61068** this circumstance cannot arise.
61069*/
61070#if defined(SQLITE_DEBUG)
61071static void assertTruncateConstraintCb(PgHdr *pPg){
61072  Pager *pPager = pPg->pPager;
61073  assert( pPg->flags&PGHDR_DIRTY );
61074  if( pPg->pgno>pPager->dbSize ){      /* if (a) is false */
61075    Pgno pgno = pPg->pgno;
61076    int i;
61077    for(i=0; i<pPg->pPager->nSavepoint; i++){
61078      PagerSavepoint *p = &pPager->aSavepoint[i];
61079      assert( p->nOrig<pgno || sqlite3BitvecTestNotNull(p->pInSavepoint,pgno) );
61080    }
61081  }
61082}
61083static void assertTruncateConstraint(Pager *pPager){
61084  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
61085}
61086#else
61087# define assertTruncateConstraint(pPager)
61088#endif
61089
61090/*
61091** Truncate the in-memory database file image to nPage pages. This
61092** function does not actually modify the database file on disk. It
61093** just sets the internal state of the pager object so that the
61094** truncation will be done when the current transaction is committed.
61095**
61096** This function is only called right before committing a transaction.
61097** Once this function has been called, the transaction must either be
61098** rolled back or committed. It is not safe to call this function and
61099** then continue writing to the database.
61100*/
61101SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
61102  assert( pPager->dbSize>=nPage || CORRUPT_DB );
61103  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
61104  pPager->dbSize = nPage;
61105
61106  /* At one point the code here called assertTruncateConstraint() to
61107  ** ensure that all pages being truncated away by this operation are,
61108  ** if one or more savepoints are open, present in the savepoint
61109  ** journal so that they can be restored if the savepoint is rolled
61110  ** back. This is no longer necessary as this function is now only
61111  ** called right before committing a transaction. So although the
61112  ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
61113  ** they cannot be rolled back. So the assertTruncateConstraint() call
61114  ** is no longer correct. */
61115}
61116
61117
61118/*
61119** This function is called before attempting a hot-journal rollback. It
61120** syncs the journal file to disk, then sets pPager->journalHdr to the
61121** size of the journal file so that the pager_playback() routine knows
61122** that the entire journal file has been synced.
61123**
61124** Syncing a hot-journal to disk before attempting to roll it back ensures
61125** that if a power-failure occurs during the rollback, the process that
61126** attempts rollback following system recovery sees the same journal
61127** content as this process.
61128**
61129** If everything goes as planned, SQLITE_OK is returned. Otherwise,
61130** an SQLite error code.
61131*/
61132static int pagerSyncHotJournal(Pager *pPager){
61133  int rc = SQLITE_OK;
61134  if( !pPager->noSync ){
61135    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
61136  }
61137  if( rc==SQLITE_OK ){
61138    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
61139  }
61140  return rc;
61141}
61142
61143#if SQLITE_MAX_MMAP_SIZE>0
61144/*
61145** Obtain a reference to a memory mapped page object for page number pgno.
61146** The new object will use the pointer pData, obtained from xFetch().
61147** If successful, set *ppPage to point to the new page reference
61148** and return SQLITE_OK. Otherwise, return an SQLite error code and set
61149** *ppPage to zero.
61150**
61151** Page references obtained by calling this function should be released
61152** by calling pagerReleaseMapPage().
61153*/
61154static int pagerAcquireMapPage(
61155  Pager *pPager,                  /* Pager object */
61156  Pgno pgno,                      /* Page number */
61157  void *pData,                    /* xFetch()'d data for this page */
61158  PgHdr **ppPage                  /* OUT: Acquired page object */
61159){
61160  PgHdr *p;                       /* Memory mapped page to return */
61161
61162  if( pPager->pMmapFreelist ){
61163    *ppPage = p = pPager->pMmapFreelist;
61164    pPager->pMmapFreelist = p->pDirty;
61165    p->pDirty = 0;
61166    assert( pPager->nExtra>=8 );
61167    memset(p->pExtra, 0, 8);
61168  }else{
61169    *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
61170    if( p==0 ){
61171      sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
61172      return SQLITE_NOMEM_BKPT;
61173    }
61174    p->pExtra = (void *)&p[1];
61175    p->flags = PGHDR_MMAP;
61176    p->nRef = 1;
61177    p->pPager = pPager;
61178  }
61179
61180  assert( p->pExtra==(void *)&p[1] );
61181  assert( p->pPage==0 );
61182  assert( p->flags==PGHDR_MMAP );
61183  assert( p->pPager==pPager );
61184  assert( p->nRef==1 );
61185
61186  p->pgno = pgno;
61187  p->pData = pData;
61188  pPager->nMmapOut++;
61189
61190  return SQLITE_OK;
61191}
61192#endif
61193
61194/*
61195** Release a reference to page pPg. pPg must have been returned by an
61196** earlier call to pagerAcquireMapPage().
61197*/
61198static void pagerReleaseMapPage(PgHdr *pPg){
61199  Pager *pPager = pPg->pPager;
61200  pPager->nMmapOut--;
61201  pPg->pDirty = pPager->pMmapFreelist;
61202  pPager->pMmapFreelist = pPg;
61203
61204  assert( pPager->fd->pMethods->iVersion>=3 );
61205  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
61206}
61207
61208/*
61209** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
61210*/
61211static void pagerFreeMapHdrs(Pager *pPager){
61212  PgHdr *p;
61213  PgHdr *pNext;
61214  for(p=pPager->pMmapFreelist; p; p=pNext){
61215    pNext = p->pDirty;
61216    sqlite3_free(p);
61217  }
61218}
61219
61220/* Verify that the database file has not be deleted or renamed out from
61221** under the pager.  Return SQLITE_OK if the database is still where it ought
61222** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
61223** code from sqlite3OsAccess()) if the database has gone missing.
61224*/
61225static int databaseIsUnmoved(Pager *pPager){
61226  int bHasMoved = 0;
61227  int rc;
61228
61229  if( pPager->tempFile ) return SQLITE_OK;
61230  if( pPager->dbSize==0 ) return SQLITE_OK;
61231  assert( pPager->zFilename && pPager->zFilename[0] );
61232  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
61233  if( rc==SQLITE_NOTFOUND ){
61234    /* If the HAS_MOVED file-control is unimplemented, assume that the file
61235    ** has not been moved.  That is the historical behavior of SQLite: prior to
61236    ** version 3.8.3, it never checked */
61237    rc = SQLITE_OK;
61238  }else if( rc==SQLITE_OK && bHasMoved ){
61239    rc = SQLITE_READONLY_DBMOVED;
61240  }
61241  return rc;
61242}
61243
61244
61245/*
61246** Shutdown the page cache.  Free all memory and close all files.
61247**
61248** If a transaction was in progress when this routine is called, that
61249** transaction is rolled back.  All outstanding pages are invalidated
61250** and their memory is freed.  Any attempt to use a page associated
61251** with this page cache after this function returns will likely
61252** result in a coredump.
61253**
61254** This function always succeeds. If a transaction is active an attempt
61255** is made to roll it back. If an error occurs during the rollback
61256** a hot journal may be left in the filesystem but no error is returned
61257** to the caller.
61258*/
61259SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
61260  u8 *pTmp = (u8*)pPager->pTmpSpace;
61261  assert( db || pagerUseWal(pPager)==0 );
61262  assert( assert_pager_state(pPager) );
61263  disable_simulated_io_errors();
61264  sqlite3BeginBenignMalloc();
61265  pagerFreeMapHdrs(pPager);
61266  /* pPager->errCode = 0; */
61267  pPager->exclusiveMode = 0;
61268#ifndef SQLITE_OMIT_WAL
61269  {
61270    u8 *a = 0;
61271    assert( db || pPager->pWal==0 );
61272    if( db && 0==(db->flags & SQLITE_NoCkptOnClose)
61273     && SQLITE_OK==databaseIsUnmoved(pPager)
61274    ){
61275      a = pTmp;
61276    }
61277    sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a);
61278    pPager->pWal = 0;
61279  }
61280#endif
61281  pager_reset(pPager);
61282  if( MEMDB ){
61283    pager_unlock(pPager);
61284  }else{
61285    /* If it is open, sync the journal file before calling UnlockAndRollback.
61286    ** If this is not done, then an unsynced portion of the open journal
61287    ** file may be played back into the database. If a power failure occurs
61288    ** while this is happening, the database could become corrupt.
61289    **
61290    ** If an error occurs while trying to sync the journal, shift the pager
61291    ** into the ERROR state. This causes UnlockAndRollback to unlock the
61292    ** database and close the journal file without attempting to roll it
61293    ** back or finalize it. The next database user will have to do hot-journal
61294    ** rollback before accessing the database file.
61295    */
61296    if( isOpen(pPager->jfd) ){
61297      pager_error(pPager, pagerSyncHotJournal(pPager));
61298    }
61299    pagerUnlockAndRollback(pPager);
61300  }
61301  sqlite3EndBenignMalloc();
61302  enable_simulated_io_errors();
61303  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
61304  IOTRACE(("CLOSE %p\n", pPager))
61305  sqlite3OsClose(pPager->jfd);
61306  sqlite3OsClose(pPager->fd);
61307  sqlite3PageFree(pTmp);
61308  sqlite3PcacheClose(pPager->pPCache);
61309  assert( !pPager->aSavepoint && !pPager->pInJournal );
61310  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
61311
61312  sqlite3_free(pPager);
61313  return SQLITE_OK;
61314}
61315
61316#if !defined(NDEBUG) || defined(SQLITE_TEST)
61317/*
61318** Return the page number for page pPg.
61319*/
61320SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
61321  return pPg->pgno;
61322}
61323#endif
61324
61325/*
61326** Increment the reference count for page pPg.
61327*/
61328SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
61329  sqlite3PcacheRef(pPg);
61330}
61331
61332/*
61333** Sync the journal. In other words, make sure all the pages that have
61334** been written to the journal have actually reached the surface of the
61335** disk and can be restored in the event of a hot-journal rollback.
61336**
61337** If the Pager.noSync flag is set, then this function is a no-op.
61338** Otherwise, the actions required depend on the journal-mode and the
61339** device characteristics of the file-system, as follows:
61340**
61341**   * If the journal file is an in-memory journal file, no action need
61342**     be taken.
61343**
61344**   * Otherwise, if the device does not support the SAFE_APPEND property,
61345**     then the nRec field of the most recently written journal header
61346**     is updated to contain the number of journal records that have
61347**     been written following it. If the pager is operating in full-sync
61348**     mode, then the journal file is synced before this field is updated.
61349**
61350**   * If the device does not support the SEQUENTIAL property, then
61351**     journal file is synced.
61352**
61353** Or, in pseudo-code:
61354**
61355**   if( NOT <in-memory journal> ){
61356**     if( NOT SAFE_APPEND ){
61357**       if( <full-sync mode> ) xSync(<journal file>);
61358**       <update nRec field>
61359**     }
61360**     if( NOT SEQUENTIAL ) xSync(<journal file>);
61361**   }
61362**
61363** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
61364** page currently held in memory before returning SQLITE_OK. If an IO
61365** error is encountered, then the IO error code is returned to the caller.
61366*/
61367static int syncJournal(Pager *pPager, int newHdr){
61368  int rc;                         /* Return code */
61369
61370  assert( pPager->eState==PAGER_WRITER_CACHEMOD
61371       || pPager->eState==PAGER_WRITER_DBMOD
61372  );
61373  assert( assert_pager_state(pPager) );
61374  assert( !pagerUseWal(pPager) );
61375
61376  rc = sqlite3PagerExclusiveLock(pPager);
61377  if( rc!=SQLITE_OK ) return rc;
61378
61379  if( !pPager->noSync ){
61380    assert( !pPager->tempFile );
61381    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
61382      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
61383      assert( isOpen(pPager->jfd) );
61384
61385      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
61386        /* This block deals with an obscure problem. If the last connection
61387        ** that wrote to this database was operating in persistent-journal
61388        ** mode, then the journal file may at this point actually be larger
61389        ** than Pager.journalOff bytes. If the next thing in the journal
61390        ** file happens to be a journal-header (written as part of the
61391        ** previous connection's transaction), and a crash or power-failure
61392        ** occurs after nRec is updated but before this connection writes
61393        ** anything else to the journal file (or commits/rolls back its
61394        ** transaction), then SQLite may become confused when doing the
61395        ** hot-journal rollback following recovery. It may roll back all
61396        ** of this connections data, then proceed to rolling back the old,
61397        ** out-of-date data that follows it. Database corruption.
61398        **
61399        ** To work around this, if the journal file does appear to contain
61400        ** a valid header following Pager.journalOff, then write a 0x00
61401        ** byte to the start of it to prevent it from being recognized.
61402        **
61403        ** Variable iNextHdrOffset is set to the offset at which this
61404        ** problematic header will occur, if it exists. aMagic is used
61405        ** as a temporary buffer to inspect the first couple of bytes of
61406        ** the potential journal header.
61407        */
61408        i64 iNextHdrOffset;
61409        u8 aMagic[8];
61410        u8 zHeader[sizeof(aJournalMagic)+4];
61411
61412        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
61413        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
61414
61415        iNextHdrOffset = journalHdrOffset(pPager);
61416        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
61417        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
61418          static const u8 zerobyte = 0;
61419          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
61420        }
61421        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
61422          return rc;
61423        }
61424
61425        /* Write the nRec value into the journal file header. If in
61426        ** full-synchronous mode, sync the journal first. This ensures that
61427        ** all data has really hit the disk before nRec is updated to mark
61428        ** it as a candidate for rollback.
61429        **
61430        ** This is not required if the persistent media supports the
61431        ** SAFE_APPEND property. Because in this case it is not possible
61432        ** for garbage data to be appended to the file, the nRec field
61433        ** is populated with 0xFFFFFFFF when the journal header is written
61434        ** and never needs to be updated.
61435        */
61436        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
61437          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
61438          IOTRACE(("JSYNC %p\n", pPager))
61439          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
61440          if( rc!=SQLITE_OK ) return rc;
61441        }
61442        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
61443        rc = sqlite3OsWrite(
61444            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
61445        );
61446        if( rc!=SQLITE_OK ) return rc;
61447      }
61448      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
61449        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
61450        IOTRACE(("JSYNC %p\n", pPager))
61451        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
61452          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
61453        );
61454        if( rc!=SQLITE_OK ) return rc;
61455      }
61456
61457      pPager->journalHdr = pPager->journalOff;
61458      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
61459        pPager->nRec = 0;
61460        rc = writeJournalHdr(pPager);
61461        if( rc!=SQLITE_OK ) return rc;
61462      }
61463    }else{
61464      pPager->journalHdr = pPager->journalOff;
61465    }
61466  }
61467
61468  /* Unless the pager is in noSync mode, the journal file was just
61469  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
61470  ** all pages.
61471  */
61472  sqlite3PcacheClearSyncFlags(pPager->pPCache);
61473  pPager->eState = PAGER_WRITER_DBMOD;
61474  assert( assert_pager_state(pPager) );
61475  return SQLITE_OK;
61476}
61477
61478/*
61479** The argument is the first in a linked list of dirty pages connected
61480** by the PgHdr.pDirty pointer. This function writes each one of the
61481** in-memory pages in the list to the database file. The argument may
61482** be NULL, representing an empty list. In this case this function is
61483** a no-op.
61484**
61485** The pager must hold at least a RESERVED lock when this function
61486** is called. Before writing anything to the database file, this lock
61487** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
61488** SQLITE_BUSY is returned and no data is written to the database file.
61489**
61490** If the pager is a temp-file pager and the actual file-system file
61491** is not yet open, it is created and opened before any data is
61492** written out.
61493**
61494** Once the lock has been upgraded and, if necessary, the file opened,
61495** the pages are written out to the database file in list order. Writing
61496** a page is skipped if it meets either of the following criteria:
61497**
61498**   * The page number is greater than Pager.dbSize, or
61499**   * The PGHDR_DONT_WRITE flag is set on the page.
61500**
61501** If writing out a page causes the database file to grow, Pager.dbFileSize
61502** is updated accordingly. If page 1 is written out, then the value cached
61503** in Pager.dbFileVers[] is updated to match the new value stored in
61504** the database file.
61505**
61506** If everything is successful, SQLITE_OK is returned. If an IO error
61507** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
61508** be obtained, SQLITE_BUSY is returned.
61509*/
61510static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
61511  int rc = SQLITE_OK;                  /* Return code */
61512
61513  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
61514  assert( !pagerUseWal(pPager) );
61515  assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
61516  assert( pPager->eLock==EXCLUSIVE_LOCK );
61517  assert( isOpen(pPager->fd) || pList->pDirty==0 );
61518
61519  /* If the file is a temp-file has not yet been opened, open it now. It
61520  ** is not possible for rc to be other than SQLITE_OK if this branch
61521  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
61522  */
61523  if( !isOpen(pPager->fd) ){
61524    assert( pPager->tempFile && rc==SQLITE_OK );
61525    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
61526  }
61527
61528  /* Before the first write, give the VFS a hint of what the final
61529  ** file size will be.
61530  */
61531  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
61532  if( rc==SQLITE_OK
61533   && pPager->dbHintSize<pPager->dbSize
61534   && (pList->pDirty || pList->pgno>pPager->dbHintSize)
61535  ){
61536    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
61537    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
61538    pPager->dbHintSize = pPager->dbSize;
61539  }
61540
61541  while( rc==SQLITE_OK && pList ){
61542    Pgno pgno = pList->pgno;
61543
61544    /* If there are dirty pages in the page cache with page numbers greater
61545    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
61546    ** make the file smaller (presumably by auto-vacuum code). Do not write
61547    ** any such pages to the file.
61548    **
61549    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
61550    ** set (set by sqlite3PagerDontWrite()).
61551    */
61552    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
61553      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
61554      char *pData;                                   /* Data to write */
61555
61556      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
61557      if( pList->pgno==1 ) pager_write_changecounter(pList);
61558
61559      pData = pList->pData;
61560
61561      /* Write out the page data. */
61562      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
61563
61564      /* If page 1 was just written, update Pager.dbFileVers to match
61565      ** the value now stored in the database file. If writing this
61566      ** page caused the database file to grow, update dbFileSize.
61567      */
61568      if( pgno==1 ){
61569        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
61570      }
61571      if( pgno>pPager->dbFileSize ){
61572        pPager->dbFileSize = pgno;
61573      }
61574      pPager->aStat[PAGER_STAT_WRITE]++;
61575
61576      /* Update any backup objects copying the contents of this pager. */
61577      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
61578
61579      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
61580                   PAGERID(pPager), pgno, pager_pagehash(pList)));
61581      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
61582      PAGER_INCR(sqlite3_pager_writedb_count);
61583    }else{
61584      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
61585    }
61586    pager_set_pagehash(pList);
61587    pList = pList->pDirty;
61588  }
61589
61590  return rc;
61591}
61592
61593/*
61594** Ensure that the sub-journal file is open. If it is already open, this
61595** function is a no-op.
61596**
61597** SQLITE_OK is returned if everything goes according to plan. An
61598** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
61599** fails.
61600*/
61601static int openSubJournal(Pager *pPager){
61602  int rc = SQLITE_OK;
61603  if( !isOpen(pPager->sjfd) ){
61604    const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
61605      | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
61606      | SQLITE_OPEN_DELETEONCLOSE;
61607    int nStmtSpill = sqlite3Config.nStmtSpill;
61608    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
61609      nStmtSpill = -1;
61610    }
61611    rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
61612  }
61613  return rc;
61614}
61615
61616/*
61617** Append a record of the current state of page pPg to the sub-journal.
61618**
61619** If successful, set the bit corresponding to pPg->pgno in the bitvecs
61620** for all open savepoints before returning.
61621**
61622** This function returns SQLITE_OK if everything is successful, an IO
61623** error code if the attempt to write to the sub-journal fails, or
61624** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
61625** bitvec.
61626*/
61627static int subjournalPage(PgHdr *pPg){
61628  int rc = SQLITE_OK;
61629  Pager *pPager = pPg->pPager;
61630  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
61631
61632    /* Open the sub-journal, if it has not already been opened */
61633    assert( pPager->useJournal );
61634    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
61635    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
61636    assert( pagerUseWal(pPager)
61637         || pageInJournal(pPager, pPg)
61638         || pPg->pgno>pPager->dbOrigSize
61639    );
61640    rc = openSubJournal(pPager);
61641
61642    /* If the sub-journal was opened successfully (or was already open),
61643    ** write the journal record into the file.  */
61644    if( rc==SQLITE_OK ){
61645      void *pData = pPg->pData;
61646      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
61647      char *pData2;
61648      pData2 = pData;
61649      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
61650      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
61651      if( rc==SQLITE_OK ){
61652        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
61653      }
61654    }
61655  }
61656  if( rc==SQLITE_OK ){
61657    pPager->nSubRec++;
61658    assert( pPager->nSavepoint>0 );
61659    rc = addToSavepointBitvecs(pPager, pPg->pgno);
61660  }
61661  return rc;
61662}
61663static int subjournalPageIfRequired(PgHdr *pPg){
61664  if( subjRequiresPage(pPg) ){
61665    return subjournalPage(pPg);
61666  }else{
61667    return SQLITE_OK;
61668  }
61669}
61670
61671/*
61672** This function is called by the pcache layer when it has reached some
61673** soft memory limit. The first argument is a pointer to a Pager object
61674** (cast as a void*). The pager is always 'purgeable' (not an in-memory
61675** database). The second argument is a reference to a page that is
61676** currently dirty but has no outstanding references. The page
61677** is always associated with the Pager object passed as the first
61678** argument.
61679**
61680** The job of this function is to make pPg clean by writing its contents
61681** out to the database file, if possible. This may involve syncing the
61682** journal file.
61683**
61684** If successful, sqlite3PcacheMakeClean() is called on the page and
61685** SQLITE_OK returned. If an IO error occurs while trying to make the
61686** page clean, the IO error code is returned. If the page cannot be
61687** made clean for some other reason, but no error occurs, then SQLITE_OK
61688** is returned by sqlite3PcacheMakeClean() is not called.
61689*/
61690static int pagerStress(void *p, PgHdr *pPg){
61691  Pager *pPager = (Pager *)p;
61692  int rc = SQLITE_OK;
61693
61694  assert( pPg->pPager==pPager );
61695  assert( pPg->flags&PGHDR_DIRTY );
61696
61697  /* The doNotSpill NOSYNC bit is set during times when doing a sync of
61698  ** journal (and adding a new header) is not allowed.  This occurs
61699  ** during calls to sqlite3PagerWrite() while trying to journal multiple
61700  ** pages belonging to the same sector.
61701  **
61702  ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
61703  ** regardless of whether or not a sync is required.  This is set during
61704  ** a rollback or by user request, respectively.
61705  **
61706  ** Spilling is also prohibited when in an error state since that could
61707  ** lead to database corruption.   In the current implementation it
61708  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
61709  ** while in the error state, hence it is impossible for this routine to
61710  ** be called in the error state.  Nevertheless, we include a NEVER()
61711  ** test for the error state as a safeguard against future changes.
61712  */
61713  if( NEVER(pPager->errCode) ) return SQLITE_OK;
61714  testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
61715  testcase( pPager->doNotSpill & SPILLFLAG_OFF );
61716  testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
61717  if( pPager->doNotSpill
61718   && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
61719      || (pPg->flags & PGHDR_NEED_SYNC)!=0)
61720  ){
61721    return SQLITE_OK;
61722  }
61723
61724  pPager->aStat[PAGER_STAT_SPILL]++;
61725  pPg->pDirty = 0;
61726  if( pagerUseWal(pPager) ){
61727    /* Write a single frame for this page to the log. */
61728    rc = subjournalPageIfRequired(pPg);
61729    if( rc==SQLITE_OK ){
61730      rc = pagerWalFrames(pPager, pPg, 0, 0);
61731    }
61732  }else{
61733
61734#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
61735    if( pPager->tempFile==0 ){
61736      rc = sqlite3JournalCreate(pPager->jfd);
61737      if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
61738    }
61739#endif
61740
61741    /* Sync the journal file if required. */
61742    if( pPg->flags&PGHDR_NEED_SYNC
61743     || pPager->eState==PAGER_WRITER_CACHEMOD
61744    ){
61745      rc = syncJournal(pPager, 1);
61746    }
61747
61748    /* Write the contents of the page out to the database file. */
61749    if( rc==SQLITE_OK ){
61750      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
61751      rc = pager_write_pagelist(pPager, pPg);
61752    }
61753  }
61754
61755  /* Mark the page as clean. */
61756  if( rc==SQLITE_OK ){
61757    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
61758    sqlite3PcacheMakeClean(pPg);
61759  }
61760
61761  return pager_error(pPager, rc);
61762}
61763
61764/*
61765** Flush all unreferenced dirty pages to disk.
61766*/
61767SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
61768  int rc = pPager->errCode;
61769  if( !MEMDB ){
61770    PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
61771    assert( assert_pager_state(pPager) );
61772    while( rc==SQLITE_OK && pList ){
61773      PgHdr *pNext = pList->pDirty;
61774      if( pList->nRef==0 ){
61775        rc = pagerStress((void*)pPager, pList);
61776      }
61777      pList = pNext;
61778    }
61779  }
61780
61781  return rc;
61782}
61783
61784/*
61785** Allocate and initialize a new Pager object and put a pointer to it
61786** in *ppPager. The pager should eventually be freed by passing it
61787** to sqlite3PagerClose().
61788**
61789** The zFilename argument is the path to the database file to open.
61790** If zFilename is NULL then a randomly-named temporary file is created
61791** and used as the file to be cached. Temporary files are be deleted
61792** automatically when they are closed. If zFilename is ":memory:" then
61793** all information is held in cache. It is never written to disk.
61794** This can be used to implement an in-memory database.
61795**
61796** The nExtra parameter specifies the number of bytes of space allocated
61797** along with each page reference. This space is available to the user
61798** via the sqlite3PagerGetExtra() API.  When a new page is allocated, the
61799** first 8 bytes of this space are zeroed but the remainder is uninitialized.
61800** (The extra space is used by btree as the MemPage object.)
61801**
61802** The flags argument is used to specify properties that affect the
61803** operation of the pager. It should be passed some bitwise combination
61804** of the PAGER_* flags.
61805**
61806** The vfsFlags parameter is a bitmask to pass to the flags parameter
61807** of the xOpen() method of the supplied VFS when opening files.
61808**
61809** If the pager object is allocated and the specified file opened
61810** successfully, SQLITE_OK is returned and *ppPager set to point to
61811** the new pager object. If an error occurs, *ppPager is set to NULL
61812** and error code returned. This function may return SQLITE_NOMEM
61813** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
61814** various SQLITE_IO_XXX errors.
61815*/
61816SQLITE_PRIVATE int sqlite3PagerOpen(
61817  sqlite3_vfs *pVfs,       /* The virtual file system to use */
61818  Pager **ppPager,         /* OUT: Return the Pager structure here */
61819  const char *zFilename,   /* Name of the database file to open */
61820  int nExtra,              /* Extra bytes append to each in-memory page */
61821  int flags,               /* flags controlling this file */
61822  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
61823  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
61824){
61825  u8 *pPtr;
61826  Pager *pPager = 0;       /* Pager object to allocate and return */
61827  int rc = SQLITE_OK;      /* Return code */
61828  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
61829  int memDb = 0;           /* True if this is an in-memory file */
61830  int memJM = 0;           /* Memory journal mode */
61831  int readOnly = 0;        /* True if this is a read-only file */
61832  int journalFileSize;     /* Bytes to allocate for each journal fd */
61833  char *zPathname = 0;     /* Full path to database file */
61834  int nPathname = 0;       /* Number of bytes in zPathname */
61835  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
61836  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
61837  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
61838  const char *zUri = 0;    /* URI args to copy */
61839  int nUriByte = 1;        /* Number of bytes of URI args at *zUri */
61840
61841  /* Figure out how much space is required for each journal file-handle
61842  ** (there are two of them, the main journal and the sub-journal).  */
61843  journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
61844
61845  /* Set the output variable to NULL in case an error occurs. */
61846  *ppPager = 0;
61847
61848#ifndef SQLITE_OMIT_MEMORYDB
61849  if( flags & PAGER_MEMORY ){
61850    memDb = 1;
61851    if( zFilename && zFilename[0] ){
61852      zPathname = sqlite3DbStrDup(0, zFilename);
61853      if( zPathname==0  ) return SQLITE_NOMEM_BKPT;
61854      nPathname = sqlite3Strlen30(zPathname);
61855      zFilename = 0;
61856    }
61857  }
61858#endif
61859
61860  /* Compute and store the full pathname in an allocated buffer pointed
61861  ** to by zPathname, length nPathname. Or, if this is a temporary file,
61862  ** leave both nPathname and zPathname set to 0.
61863  */
61864  if( zFilename && zFilename[0] ){
61865    const char *z;
61866    nPathname = pVfs->mxPathname+1;
61867    zPathname = sqlite3DbMallocRaw(0, nPathname*2);
61868    if( zPathname==0 ){
61869      return SQLITE_NOMEM_BKPT;
61870    }
61871    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
61872    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
61873    if( rc!=SQLITE_OK ){
61874      if( rc==SQLITE_OK_SYMLINK ){
61875        if( vfsFlags & SQLITE_OPEN_NOFOLLOW ){
61876          rc = SQLITE_CANTOPEN_SYMLINK;
61877        }else{
61878          rc = SQLITE_OK;
61879        }
61880      }
61881    }
61882    nPathname = sqlite3Strlen30(zPathname);
61883    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
61884    while( *z ){
61885      z += strlen(z)+1;
61886      z += strlen(z)+1;
61887    }
61888    nUriByte = (int)(&z[1] - zUri);
61889    assert( nUriByte>=1 );
61890    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
61891      /* This branch is taken when the journal path required by
61892      ** the database being opened will be more than pVfs->mxPathname
61893      ** bytes in length. This means the database cannot be opened,
61894      ** as it will not be possible to open the journal file or even
61895      ** check for a hot-journal before reading.
61896      */
61897      rc = SQLITE_CANTOPEN_BKPT;
61898    }
61899    if( rc!=SQLITE_OK ){
61900      sqlite3DbFree(0, zPathname);
61901      return rc;
61902    }
61903  }
61904
61905  /* Allocate memory for the Pager structure, PCache object, the
61906  ** three file descriptors, the database file name and the journal
61907  ** file name. The layout in memory is as follows:
61908  **
61909  **     Pager object                    (sizeof(Pager) bytes)
61910  **     PCache object                   (sqlite3PcacheSize() bytes)
61911  **     Database file handle            (pVfs->szOsFile bytes)
61912  **     Sub-journal file handle         (journalFileSize bytes)
61913  **     Main journal file handle        (journalFileSize bytes)
61914  **     Ptr back to the Pager           (sizeof(Pager*) bytes)
61915  **     \0\0\0\0 database prefix        (4 bytes)
61916  **     Database file name              (nPathname+1 bytes)
61917  **     URI query parameters            (nUriByte bytes)
61918  **     Journal filename                (nPathname+8+1 bytes)
61919  **     WAL filename                    (nPathname+4+1 bytes)
61920  **     \0\0\0 terminator               (3 bytes)
61921  **
61922  ** Some 3rd-party software, over which we have no control, depends on
61923  ** the specific order of the filenames and the \0 separators between them
61924  ** so that it can (for example) find the database filename given the WAL
61925  ** filename without using the sqlite3_filename_database() API.  This is a
61926  ** misuse of SQLite and a bug in the 3rd-party software, but the 3rd-party
61927  ** software is in widespread use, so we try to avoid changing the filename
61928  ** order and formatting if possible.  In particular, the details of the
61929  ** filename format expected by 3rd-party software should be as follows:
61930  **
61931  **   - Main Database Path
61932  **   - \0
61933  **   - Multiple URI components consisting of:
61934  **     - Key
61935  **     - \0
61936  **     - Value
61937  **     - \0
61938  **   - \0
61939  **   - Journal Path
61940  **   - \0
61941  **   - WAL Path (zWALName)
61942  **   - \0
61943  **
61944  ** The sqlite3_create_filename() interface and the databaseFilename() utility
61945  ** that is used by sqlite3_filename_database() and kin also depend on the
61946  ** specific formatting and order of the various filenames, so if the format
61947  ** changes here, be sure to change it there as well.
61948  */
61949  assert( SQLITE_PTRSIZE==sizeof(Pager*) );
61950  pPtr = (u8 *)sqlite3MallocZero(
61951    ROUND8(sizeof(*pPager)) +            /* Pager structure */
61952    ROUND8(pcacheSize) +                 /* PCache object */
61953    ROUND8(pVfs->szOsFile) +             /* The main db file */
61954    journalFileSize * 2 +                /* The two journal files */
61955    SQLITE_PTRSIZE +                     /* Space to hold a pointer */
61956    4 +                                  /* Database prefix */
61957    nPathname + 1 +                      /* database filename */
61958    nUriByte +                           /* query parameters */
61959    nPathname + 8 + 1 +                  /* Journal filename */
61960#ifndef SQLITE_OMIT_WAL
61961    nPathname + 4 + 1 +                  /* WAL filename */
61962#endif
61963    3                                    /* Terminator */
61964  );
61965  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
61966  if( !pPtr ){
61967    sqlite3DbFree(0, zPathname);
61968    return SQLITE_NOMEM_BKPT;
61969  }
61970  pPager = (Pager*)pPtr;                  pPtr += ROUND8(sizeof(*pPager));
61971  pPager->pPCache = (PCache*)pPtr;        pPtr += ROUND8(pcacheSize);
61972  pPager->fd = (sqlite3_file*)pPtr;       pPtr += ROUND8(pVfs->szOsFile);
61973  pPager->sjfd = (sqlite3_file*)pPtr;     pPtr += journalFileSize;
61974  pPager->jfd =  (sqlite3_file*)pPtr;     pPtr += journalFileSize;
61975  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
61976  memcpy(pPtr, &pPager, SQLITE_PTRSIZE);  pPtr += SQLITE_PTRSIZE;
61977
61978  /* Fill in the Pager.zFilename and pPager.zQueryParam fields */
61979                                          pPtr += 4;  /* Skip zero prefix */
61980  pPager->zFilename = (char*)pPtr;
61981  if( nPathname>0 ){
61982    memcpy(pPtr, zPathname, nPathname);   pPtr += nPathname + 1;
61983    if( zUri ){
61984      memcpy(pPtr, zUri, nUriByte);       pPtr += nUriByte;
61985    }else{
61986                                          pPtr++;
61987    }
61988  }
61989
61990
61991  /* Fill in Pager.zJournal */
61992  if( nPathname>0 ){
61993    pPager->zJournal = (char*)pPtr;
61994    memcpy(pPtr, zPathname, nPathname);   pPtr += nPathname;
61995    memcpy(pPtr, "-journal",8);           pPtr += 8 + 1;
61996#ifdef SQLITE_ENABLE_8_3_NAMES
61997    sqlite3FileSuffix3(zFilename,pPager->zJournal);
61998    pPtr = (u8*)(pPager->zJournal + sqlite3Strlen30(pPager->zJournal)+1);
61999#endif
62000  }else{
62001    pPager->zJournal = 0;
62002  }
62003
62004#ifndef SQLITE_OMIT_WAL
62005  /* Fill in Pager.zWal */
62006  if( nPathname>0 ){
62007    pPager->zWal = (char*)pPtr;
62008    memcpy(pPtr, zPathname, nPathname);   pPtr += nPathname;
62009    memcpy(pPtr, "-wal", 4);              pPtr += 4 + 1;
62010#ifdef SQLITE_ENABLE_8_3_NAMES
62011    sqlite3FileSuffix3(zFilename, pPager->zWal);
62012    pPtr = (u8*)(pPager->zWal + sqlite3Strlen30(pPager->zWal)+1);
62013#endif
62014  }else{
62015    pPager->zWal = 0;
62016  }
62017#endif
62018  (void)pPtr;  /* Suppress warning about unused pPtr value */
62019
62020  if( nPathname ) sqlite3DbFree(0, zPathname);
62021  pPager->pVfs = pVfs;
62022  pPager->vfsFlags = vfsFlags;
62023
62024  /* Open the pager file.
62025  */
62026  if( zFilename && zFilename[0] ){
62027    int fout = 0;                    /* VFS flags returned by xOpen() */
62028    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
62029    assert( !memDb );
62030    pPager->memVfs = memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
62031    readOnly = (fout&SQLITE_OPEN_READONLY)!=0;
62032
62033    /* If the file was successfully opened for read/write access,
62034    ** choose a default page size in case we have to create the
62035    ** database file. The default page size is the maximum of:
62036    **
62037    **    + SQLITE_DEFAULT_PAGE_SIZE,
62038    **    + The value returned by sqlite3OsSectorSize()
62039    **    + The largest page size that can be written atomically.
62040    */
62041    if( rc==SQLITE_OK ){
62042      int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
62043      if( !readOnly ){
62044        setSectorSize(pPager);
62045        assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
62046        if( szPageDflt<pPager->sectorSize ){
62047          if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
62048            szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
62049          }else{
62050            szPageDflt = (u32)pPager->sectorSize;
62051          }
62052        }
62053#ifdef SQLITE_ENABLE_ATOMIC_WRITE
62054        {
62055          int ii;
62056          assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
62057          assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
62058          assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
62059          for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
62060            if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
62061              szPageDflt = ii;
62062            }
62063          }
62064        }
62065#endif
62066      }
62067      pPager->noLock = sqlite3_uri_boolean(pPager->zFilename, "nolock", 0);
62068      if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
62069       || sqlite3_uri_boolean(pPager->zFilename, "immutable", 0) ){
62070          vfsFlags |= SQLITE_OPEN_READONLY;
62071          goto act_like_temp_file;
62072      }
62073    }
62074  }else{
62075    /* If a temporary file is requested, it is not opened immediately.
62076    ** In this case we accept the default page size and delay actually
62077    ** opening the file until the first call to OsWrite().
62078    **
62079    ** This branch is also run for an in-memory database. An in-memory
62080    ** database is the same as a temp-file that is never written out to
62081    ** disk and uses an in-memory rollback journal.
62082    **
62083    ** This branch also runs for files marked as immutable.
62084    */
62085act_like_temp_file:
62086    tempFile = 1;
62087    pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
62088    pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE mode */
62089    pPager->noLock = 1;                /* Do no locking */
62090    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
62091  }
62092
62093  /* The following call to PagerSetPagesize() serves to set the value of
62094  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
62095  */
62096  if( rc==SQLITE_OK ){
62097    assert( pPager->memDb==0 );
62098    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
62099    testcase( rc!=SQLITE_OK );
62100  }
62101
62102  /* Initialize the PCache object. */
62103  if( rc==SQLITE_OK ){
62104    nExtra = ROUND8(nExtra);
62105    assert( nExtra>=8 && nExtra<1000 );
62106    rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
62107                       !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
62108  }
62109
62110  /* If an error occurred above, free the  Pager structure and close the file.
62111  */
62112  if( rc!=SQLITE_OK ){
62113    sqlite3OsClose(pPager->fd);
62114    sqlite3PageFree(pPager->pTmpSpace);
62115    sqlite3_free(pPager);
62116    return rc;
62117  }
62118
62119  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
62120  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
62121
62122  pPager->useJournal = (u8)useJournal;
62123  /* pPager->stmtOpen = 0; */
62124  /* pPager->stmtInUse = 0; */
62125  /* pPager->nRef = 0; */
62126  /* pPager->stmtSize = 0; */
62127  /* pPager->stmtJSize = 0; */
62128  /* pPager->nPage = 0; */
62129  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
62130  /* pPager->state = PAGER_UNLOCK; */
62131  /* pPager->errMask = 0; */
62132  pPager->tempFile = (u8)tempFile;
62133  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
62134          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
62135  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
62136  pPager->exclusiveMode = (u8)tempFile;
62137  pPager->changeCountDone = pPager->tempFile;
62138  pPager->memDb = (u8)memDb;
62139  pPager->readOnly = (u8)readOnly;
62140  assert( useJournal || pPager->tempFile );
62141  sqlite3PagerSetFlags(pPager, (SQLITE_DEFAULT_SYNCHRONOUS+1)|PAGER_CACHESPILL);
62142  /* pPager->pFirst = 0; */
62143  /* pPager->pFirstSynced = 0; */
62144  /* pPager->pLast = 0; */
62145  pPager->nExtra = (u16)nExtra;
62146  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
62147  assert( isOpen(pPager->fd) || tempFile );
62148  setSectorSize(pPager);
62149  if( !useJournal ){
62150    pPager->journalMode = PAGER_JOURNALMODE_OFF;
62151  }else if( memDb || memJM ){
62152    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
62153  }
62154  /* pPager->xBusyHandler = 0; */
62155  /* pPager->pBusyHandlerArg = 0; */
62156  pPager->xReiniter = xReinit;
62157  setGetterMethod(pPager);
62158  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
62159  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
62160
62161  *ppPager = pPager;
62162  return SQLITE_OK;
62163}
62164
62165/*
62166** Return the sqlite3_file for the main database given the name
62167** of the corresponding WAL or Journal name as passed into
62168** xOpen.
62169*/
62170SQLITE_API sqlite3_file *sqlite3_database_file_object(const char *zName){
62171  Pager *pPager;
62172  const char *p;
62173  while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
62174    zName--;
62175  }
62176  p = zName - 4 - sizeof(Pager*);
62177  assert( EIGHT_BYTE_ALIGNMENT(p) );
62178  pPager = *(Pager**)p;
62179  return pPager->fd;
62180}
62181
62182
62183/*
62184** This function is called after transitioning from PAGER_UNLOCK to
62185** PAGER_SHARED state. It tests if there is a hot journal present in
62186** the file-system for the given pager. A hot journal is one that
62187** needs to be played back. According to this function, a hot-journal
62188** file exists if the following criteria are met:
62189**
62190**   * The journal file exists in the file system, and
62191**   * No process holds a RESERVED or greater lock on the database file, and
62192**   * The database file itself is greater than 0 bytes in size, and
62193**   * The first byte of the journal file exists and is not 0x00.
62194**
62195** If the current size of the database file is 0 but a journal file
62196** exists, that is probably an old journal left over from a prior
62197** database with the same name. In this case the journal file is
62198** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
62199** is returned.
62200**
62201** This routine does not check if there is a super-journal filename
62202** at the end of the file. If there is, and that super-journal file
62203** does not exist, then the journal file is not really hot. In this
62204** case this routine will return a false-positive. The pager_playback()
62205** routine will discover that the journal file is not really hot and
62206** will not roll it back.
62207**
62208** If a hot-journal file is found to exist, *pExists is set to 1 and
62209** SQLITE_OK returned. If no hot-journal file is present, *pExists is
62210** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
62211** to determine whether or not a hot-journal file exists, the IO error
62212** code is returned and the value of *pExists is undefined.
62213*/
62214static int hasHotJournal(Pager *pPager, int *pExists){
62215  sqlite3_vfs * const pVfs = pPager->pVfs;
62216  int rc = SQLITE_OK;           /* Return code */
62217  int exists = 1;               /* True if a journal file is present */
62218  int jrnlOpen = !!isOpen(pPager->jfd);
62219
62220  assert( pPager->useJournal );
62221  assert( isOpen(pPager->fd) );
62222  assert( pPager->eState==PAGER_OPEN );
62223
62224  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
62225    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
62226  ));
62227
62228  *pExists = 0;
62229  if( !jrnlOpen ){
62230    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
62231  }
62232  if( rc==SQLITE_OK && exists ){
62233    int locked = 0;             /* True if some process holds a RESERVED lock */
62234
62235    /* Race condition here:  Another process might have been holding the
62236    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
62237    ** call above, but then delete the journal and drop the lock before
62238    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
62239    ** is the case, this routine might think there is a hot journal when
62240    ** in fact there is none.  This results in a false-positive which will
62241    ** be dealt with by the playback routine.  Ticket #3883.
62242    */
62243    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
62244    if( rc==SQLITE_OK && !locked ){
62245      Pgno nPage;                 /* Number of pages in database file */
62246
62247      assert( pPager->tempFile==0 );
62248      rc = pagerPagecount(pPager, &nPage);
62249      if( rc==SQLITE_OK ){
62250        /* If the database is zero pages in size, that means that either (1) the
62251        ** journal is a remnant from a prior database with the same name where
62252        ** the database file but not the journal was deleted, or (2) the initial
62253        ** transaction that populates a new database is being rolled back.
62254        ** In either case, the journal file can be deleted.  However, take care
62255        ** not to delete the journal file if it is already open due to
62256        ** journal_mode=PERSIST.
62257        */
62258        if( nPage==0 && !jrnlOpen ){
62259          sqlite3BeginBenignMalloc();
62260          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
62261            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
62262            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
62263          }
62264          sqlite3EndBenignMalloc();
62265        }else{
62266          /* The journal file exists and no other connection has a reserved
62267          ** or greater lock on the database file. Now check that there is
62268          ** at least one non-zero bytes at the start of the journal file.
62269          ** If there is, then we consider this journal to be hot. If not,
62270          ** it can be ignored.
62271          */
62272          if( !jrnlOpen ){
62273            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
62274            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
62275          }
62276          if( rc==SQLITE_OK ){
62277            u8 first = 0;
62278            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
62279            if( rc==SQLITE_IOERR_SHORT_READ ){
62280              rc = SQLITE_OK;
62281            }
62282            if( !jrnlOpen ){
62283              sqlite3OsClose(pPager->jfd);
62284            }
62285            *pExists = (first!=0);
62286          }else if( rc==SQLITE_CANTOPEN ){
62287            /* If we cannot open the rollback journal file in order to see if
62288            ** it has a zero header, that might be due to an I/O error, or
62289            ** it might be due to the race condition described above and in
62290            ** ticket #3883.  Either way, assume that the journal is hot.
62291            ** This might be a false positive.  But if it is, then the
62292            ** automatic journal playback and recovery mechanism will deal
62293            ** with it under an EXCLUSIVE lock where we do not need to
62294            ** worry so much with race conditions.
62295            */
62296            *pExists = 1;
62297            rc = SQLITE_OK;
62298          }
62299        }
62300      }
62301    }
62302  }
62303
62304  return rc;
62305}
62306
62307/*
62308** This function is called to obtain a shared lock on the database file.
62309** It is illegal to call sqlite3PagerGet() until after this function
62310** has been successfully called. If a shared-lock is already held when
62311** this function is called, it is a no-op.
62312**
62313** The following operations are also performed by this function.
62314**
62315**   1) If the pager is currently in PAGER_OPEN state (no lock held
62316**      on the database file), then an attempt is made to obtain a
62317**      SHARED lock on the database file. Immediately after obtaining
62318**      the SHARED lock, the file-system is checked for a hot-journal,
62319**      which is played back if present. Following any hot-journal
62320**      rollback, the contents of the cache are validated by checking
62321**      the 'change-counter' field of the database file header and
62322**      discarded if they are found to be invalid.
62323**
62324**   2) If the pager is running in exclusive-mode, and there are currently
62325**      no outstanding references to any pages, and is in the error state,
62326**      then an attempt is made to clear the error state by discarding
62327**      the contents of the page cache and rolling back any open journal
62328**      file.
62329**
62330** If everything is successful, SQLITE_OK is returned. If an IO error
62331** occurs while locking the database, checking for a hot-journal file or
62332** rolling back a journal file, the IO error code is returned.
62333*/
62334SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
62335  int rc = SQLITE_OK;                /* Return code */
62336
62337  /* This routine is only called from b-tree and only when there are no
62338  ** outstanding pages. This implies that the pager state should either
62339  ** be OPEN or READER. READER is only possible if the pager is or was in
62340  ** exclusive access mode.  */
62341  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
62342  assert( assert_pager_state(pPager) );
62343  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
62344  assert( pPager->errCode==SQLITE_OK );
62345
62346  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
62347    int bHotJournal = 1;          /* True if there exists a hot journal-file */
62348
62349    assert( !MEMDB );
62350    assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
62351
62352    rc = pager_wait_on_lock(pPager, SHARED_LOCK);
62353    if( rc!=SQLITE_OK ){
62354      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
62355      goto failed;
62356    }
62357
62358    /* If a journal file exists, and there is no RESERVED lock on the
62359    ** database file, then it either needs to be played back or deleted.
62360    */
62361    if( pPager->eLock<=SHARED_LOCK ){
62362      rc = hasHotJournal(pPager, &bHotJournal);
62363    }
62364    if( rc!=SQLITE_OK ){
62365      goto failed;
62366    }
62367    if( bHotJournal ){
62368      if( pPager->readOnly ){
62369        rc = SQLITE_READONLY_ROLLBACK;
62370        goto failed;
62371      }
62372
62373      /* Get an EXCLUSIVE lock on the database file. At this point it is
62374      ** important that a RESERVED lock is not obtained on the way to the
62375      ** EXCLUSIVE lock. If it were, another process might open the
62376      ** database file, detect the RESERVED lock, and conclude that the
62377      ** database is safe to read while this process is still rolling the
62378      ** hot-journal back.
62379      **
62380      ** Because the intermediate RESERVED lock is not requested, any
62381      ** other process attempting to access the database file will get to
62382      ** this point in the code and fail to obtain its own EXCLUSIVE lock
62383      ** on the database file.
62384      **
62385      ** Unless the pager is in locking_mode=exclusive mode, the lock is
62386      ** downgraded to SHARED_LOCK before this function returns.
62387      */
62388      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
62389      if( rc!=SQLITE_OK ){
62390        goto failed;
62391      }
62392
62393      /* If it is not already open and the file exists on disk, open the
62394      ** journal for read/write access. Write access is required because
62395      ** in exclusive-access mode the file descriptor will be kept open
62396      ** and possibly used for a transaction later on. Also, write-access
62397      ** is usually required to finalize the journal in journal_mode=persist
62398      ** mode (and also for journal_mode=truncate on some systems).
62399      **
62400      ** If the journal does not exist, it usually means that some
62401      ** other connection managed to get in and roll it back before
62402      ** this connection obtained the exclusive lock above. Or, it
62403      ** may mean that the pager was in the error-state when this
62404      ** function was called and the journal file does not exist.
62405      */
62406      if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
62407        sqlite3_vfs * const pVfs = pPager->pVfs;
62408        int bExists;              /* True if journal file exists */
62409        rc = sqlite3OsAccess(
62410            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
62411        if( rc==SQLITE_OK && bExists ){
62412          int fout = 0;
62413          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
62414          assert( !pPager->tempFile );
62415          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
62416          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
62417          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
62418            rc = SQLITE_CANTOPEN_BKPT;
62419            sqlite3OsClose(pPager->jfd);
62420          }
62421        }
62422      }
62423
62424      /* Playback and delete the journal.  Drop the database write
62425      ** lock and reacquire the read lock. Purge the cache before
62426      ** playing back the hot-journal so that we don't end up with
62427      ** an inconsistent cache.  Sync the hot journal before playing
62428      ** it back since the process that crashed and left the hot journal
62429      ** probably did not sync it and we are required to always sync
62430      ** the journal before playing it back.
62431      */
62432      if( isOpen(pPager->jfd) ){
62433        assert( rc==SQLITE_OK );
62434        rc = pagerSyncHotJournal(pPager);
62435        if( rc==SQLITE_OK ){
62436          rc = pager_playback(pPager, !pPager->tempFile);
62437          pPager->eState = PAGER_OPEN;
62438        }
62439      }else if( !pPager->exclusiveMode ){
62440        pagerUnlockDb(pPager, SHARED_LOCK);
62441      }
62442
62443      if( rc!=SQLITE_OK ){
62444        /* This branch is taken if an error occurs while trying to open
62445        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
62446        ** pager_unlock() routine will be called before returning to unlock
62447        ** the file. If the unlock attempt fails, then Pager.eLock must be
62448        ** set to UNKNOWN_LOCK (see the comment above the #define for
62449        ** UNKNOWN_LOCK above for an explanation).
62450        **
62451        ** In order to get pager_unlock() to do this, set Pager.eState to
62452        ** PAGER_ERROR now. This is not actually counted as a transition
62453        ** to ERROR state in the state diagram at the top of this file,
62454        ** since we know that the same call to pager_unlock() will very
62455        ** shortly transition the pager object to the OPEN state. Calling
62456        ** assert_pager_state() would fail now, as it should not be possible
62457        ** to be in ERROR state when there are zero outstanding page
62458        ** references.
62459        */
62460        pager_error(pPager, rc);
62461        goto failed;
62462      }
62463
62464      assert( pPager->eState==PAGER_OPEN );
62465      assert( (pPager->eLock==SHARED_LOCK)
62466           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
62467      );
62468    }
62469
62470    if( !pPager->tempFile && pPager->hasHeldSharedLock ){
62471      /* The shared-lock has just been acquired then check to
62472      ** see if the database has been modified.  If the database has changed,
62473      ** flush the cache.  The hasHeldSharedLock flag prevents this from
62474      ** occurring on the very first access to a file, in order to save a
62475      ** single unnecessary sqlite3OsRead() call at the start-up.
62476      **
62477      ** Database changes are detected by looking at 15 bytes beginning
62478      ** at offset 24 into the file.  The first 4 of these 16 bytes are
62479      ** a 32-bit counter that is incremented with each change.  The
62480      ** other bytes change randomly with each file change when
62481      ** a codec is in use.
62482      **
62483      ** There is a vanishingly small chance that a change will not be
62484      ** detected.  The chance of an undetected change is so small that
62485      ** it can be neglected.
62486      */
62487      char dbFileVers[sizeof(pPager->dbFileVers)];
62488
62489      IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
62490      rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
62491      if( rc!=SQLITE_OK ){
62492        if( rc!=SQLITE_IOERR_SHORT_READ ){
62493          goto failed;
62494        }
62495        memset(dbFileVers, 0, sizeof(dbFileVers));
62496      }
62497
62498      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
62499        pager_reset(pPager);
62500
62501        /* Unmap the database file. It is possible that external processes
62502        ** may have truncated the database file and then extended it back
62503        ** to its original size while this process was not holding a lock.
62504        ** In this case there may exist a Pager.pMap mapping that appears
62505        ** to be the right size but is not actually valid. Avoid this
62506        ** possibility by unmapping the db here. */
62507        if( USEFETCH(pPager) ){
62508          sqlite3OsUnfetch(pPager->fd, 0, 0);
62509        }
62510      }
62511    }
62512
62513    /* If there is a WAL file in the file-system, open this database in WAL
62514    ** mode. Otherwise, the following function call is a no-op.
62515    */
62516    rc = pagerOpenWalIfPresent(pPager);
62517#ifndef SQLITE_OMIT_WAL
62518    assert( pPager->pWal==0 || rc==SQLITE_OK );
62519#endif
62520  }
62521
62522  if( pagerUseWal(pPager) ){
62523    assert( rc==SQLITE_OK );
62524    rc = pagerBeginReadTransaction(pPager);
62525  }
62526
62527  if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
62528    rc = pagerPagecount(pPager, &pPager->dbSize);
62529  }
62530
62531 failed:
62532  if( rc!=SQLITE_OK ){
62533    assert( !MEMDB );
62534    pager_unlock(pPager);
62535    assert( pPager->eState==PAGER_OPEN );
62536  }else{
62537    pPager->eState = PAGER_READER;
62538    pPager->hasHeldSharedLock = 1;
62539  }
62540  return rc;
62541}
62542
62543/*
62544** If the reference count has reached zero, rollback any active
62545** transaction and unlock the pager.
62546**
62547** Except, in locking_mode=EXCLUSIVE when there is nothing to in
62548** the rollback journal, the unlock is not performed and there is
62549** nothing to rollback, so this routine is a no-op.
62550*/
62551static void pagerUnlockIfUnused(Pager *pPager){
62552  if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
62553    assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
62554    pagerUnlockAndRollback(pPager);
62555  }
62556}
62557
62558/*
62559** The page getter methods each try to acquire a reference to a
62560** page with page number pgno. If the requested reference is
62561** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
62562**
62563** There are different implementations of the getter method depending
62564** on the current state of the pager.
62565**
62566**     getPageNormal()         --  The normal getter
62567**     getPageError()          --  Used if the pager is in an error state
62568**     getPageMmap()           --  Used if memory-mapped I/O is enabled
62569**
62570** If the requested page is already in the cache, it is returned.
62571** Otherwise, a new page object is allocated and populated with data
62572** read from the database file. In some cases, the pcache module may
62573** choose not to allocate a new page object and may reuse an existing
62574** object with no outstanding references.
62575**
62576** The extra data appended to a page is always initialized to zeros the
62577** first time a page is loaded into memory. If the page requested is
62578** already in the cache when this function is called, then the extra
62579** data is left as it was when the page object was last used.
62580**
62581** If the database image is smaller than the requested page or if
62582** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
62583** requested page is not already stored in the cache, then no
62584** actual disk read occurs. In this case the memory image of the
62585** page is initialized to all zeros.
62586**
62587** If PAGER_GET_NOCONTENT is true, it means that we do not care about
62588** the contents of the page. This occurs in two scenarios:
62589**
62590**   a) When reading a free-list leaf page from the database, and
62591**
62592**   b) When a savepoint is being rolled back and we need to load
62593**      a new page into the cache to be filled with the data read
62594**      from the savepoint journal.
62595**
62596** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
62597** of being read from the database. Additionally, the bits corresponding
62598** to pgno in Pager.pInJournal (bitvec of pages already written to the
62599** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
62600** savepoints are set. This means if the page is made writable at any
62601** point in the future, using a call to sqlite3PagerWrite(), its contents
62602** will not be journaled. This saves IO.
62603**
62604** The acquisition might fail for several reasons.  In all cases,
62605** an appropriate error code is returned and *ppPage is set to NULL.
62606**
62607** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
62608** to find a page in the in-memory cache first.  If the page is not already
62609** in memory, this routine goes to disk to read it in whereas Lookup()
62610** just returns 0.  This routine acquires a read-lock the first time it
62611** has to go to disk, and could also playback an old journal if necessary.
62612** Since Lookup() never goes to disk, it never has to deal with locks
62613** or journal files.
62614*/
62615static int getPageNormal(
62616  Pager *pPager,      /* The pager open on the database file */
62617  Pgno pgno,          /* Page number to fetch */
62618  DbPage **ppPage,    /* Write a pointer to the page here */
62619  int flags           /* PAGER_GET_XXX flags */
62620){
62621  int rc = SQLITE_OK;
62622  PgHdr *pPg;
62623  u8 noContent;                   /* True if PAGER_GET_NOCONTENT is set */
62624  sqlite3_pcache_page *pBase;
62625
62626  assert( pPager->errCode==SQLITE_OK );
62627  assert( pPager->eState>=PAGER_READER );
62628  assert( assert_pager_state(pPager) );
62629  assert( pPager->hasHeldSharedLock==1 );
62630
62631  if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
62632  pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
62633  if( pBase==0 ){
62634    pPg = 0;
62635    rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
62636    if( rc!=SQLITE_OK ) goto pager_acquire_err;
62637    if( pBase==0 ){
62638      rc = SQLITE_NOMEM_BKPT;
62639      goto pager_acquire_err;
62640    }
62641  }
62642  pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
62643  assert( pPg==(*ppPage) );
62644  assert( pPg->pgno==pgno );
62645  assert( pPg->pPager==pPager || pPg->pPager==0 );
62646
62647  noContent = (flags & PAGER_GET_NOCONTENT)!=0;
62648  if( pPg->pPager && !noContent ){
62649    /* In this case the pcache already contains an initialized copy of
62650    ** the page. Return without further ado.  */
62651    assert( pgno!=PAGER_SJ_PGNO(pPager) );
62652    pPager->aStat[PAGER_STAT_HIT]++;
62653    return SQLITE_OK;
62654
62655  }else{
62656    /* The pager cache has created a new page. Its content needs to
62657    ** be initialized. But first some error checks:
62658    **
62659    ** (*) obsolete.  Was: maximum page number is 2^31
62660    ** (2) Never try to fetch the locking page
62661    */
62662    if( pgno==PAGER_SJ_PGNO(pPager) ){
62663      rc = SQLITE_CORRUPT_BKPT;
62664      goto pager_acquire_err;
62665    }
62666
62667    pPg->pPager = pPager;
62668
62669    assert( !isOpen(pPager->fd) || !MEMDB );
62670    if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
62671      if( pgno>pPager->mxPgno ){
62672        rc = SQLITE_FULL;
62673        if( pgno<=pPager->dbSize ){
62674          sqlite3PcacheRelease(pPg);
62675          pPg = 0;
62676        }
62677        goto pager_acquire_err;
62678      }
62679      if( noContent ){
62680        /* Failure to set the bits in the InJournal bit-vectors is benign.
62681        ** It merely means that we might do some extra work to journal a
62682        ** page that does not need to be journaled.  Nevertheless, be sure
62683        ** to test the case where a malloc error occurs while trying to set
62684        ** a bit in a bit vector.
62685        */
62686        sqlite3BeginBenignMalloc();
62687        if( pgno<=pPager->dbOrigSize ){
62688          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
62689          testcase( rc==SQLITE_NOMEM );
62690        }
62691        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
62692        testcase( rc==SQLITE_NOMEM );
62693        sqlite3EndBenignMalloc();
62694      }
62695      memset(pPg->pData, 0, pPager->pageSize);
62696      IOTRACE(("ZERO %p %d\n", pPager, pgno));
62697    }else{
62698      assert( pPg->pPager==pPager );
62699      pPager->aStat[PAGER_STAT_MISS]++;
62700      rc = readDbPage(pPg);
62701      if( rc!=SQLITE_OK ){
62702        goto pager_acquire_err;
62703      }
62704    }
62705    pager_set_pagehash(pPg);
62706  }
62707  return SQLITE_OK;
62708
62709pager_acquire_err:
62710  assert( rc!=SQLITE_OK );
62711  if( pPg ){
62712    sqlite3PcacheDrop(pPg);
62713  }
62714  pagerUnlockIfUnused(pPager);
62715  *ppPage = 0;
62716  return rc;
62717}
62718
62719#if SQLITE_MAX_MMAP_SIZE>0
62720/* The page getter for when memory-mapped I/O is enabled */
62721static int getPageMMap(
62722  Pager *pPager,      /* The pager open on the database file */
62723  Pgno pgno,          /* Page number to fetch */
62724  DbPage **ppPage,    /* Write a pointer to the page here */
62725  int flags           /* PAGER_GET_XXX flags */
62726){
62727  int rc = SQLITE_OK;
62728  PgHdr *pPg = 0;
62729  u32 iFrame = 0;                 /* Frame to read from WAL file */
62730
62731  /* It is acceptable to use a read-only (mmap) page for any page except
62732  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
62733  ** flag was specified by the caller. And so long as the db is not a
62734  ** temporary or in-memory database.  */
62735  const int bMmapOk = (pgno>1
62736   && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
62737  );
62738
62739  assert( USEFETCH(pPager) );
62740
62741  /* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
62742  ** allows the compiler optimizer to reuse the results of the "pgno>1"
62743  ** test in the previous statement, and avoid testing pgno==0 in the
62744  ** common case where pgno is large. */
62745  if( pgno<=1 && pgno==0 ){
62746    return SQLITE_CORRUPT_BKPT;
62747  }
62748  assert( pPager->eState>=PAGER_READER );
62749  assert( assert_pager_state(pPager) );
62750  assert( pPager->hasHeldSharedLock==1 );
62751  assert( pPager->errCode==SQLITE_OK );
62752
62753  if( bMmapOk && pagerUseWal(pPager) ){
62754    rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
62755    if( rc!=SQLITE_OK ){
62756      *ppPage = 0;
62757      return rc;
62758    }
62759  }
62760  if( bMmapOk && iFrame==0 ){
62761    void *pData = 0;
62762    rc = sqlite3OsFetch(pPager->fd,
62763        (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
62764    );
62765    if( rc==SQLITE_OK && pData ){
62766      if( pPager->eState>PAGER_READER || pPager->tempFile ){
62767        pPg = sqlite3PagerLookup(pPager, pgno);
62768      }
62769      if( pPg==0 ){
62770        rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
62771      }else{
62772        sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
62773      }
62774      if( pPg ){
62775        assert( rc==SQLITE_OK );
62776        *ppPage = pPg;
62777        return SQLITE_OK;
62778      }
62779    }
62780    if( rc!=SQLITE_OK ){
62781      *ppPage = 0;
62782      return rc;
62783    }
62784  }
62785  return getPageNormal(pPager, pgno, ppPage, flags);
62786}
62787#endif /* SQLITE_MAX_MMAP_SIZE>0 */
62788
62789/* The page getter method for when the pager is an error state */
62790static int getPageError(
62791  Pager *pPager,      /* The pager open on the database file */
62792  Pgno pgno,          /* Page number to fetch */
62793  DbPage **ppPage,    /* Write a pointer to the page here */
62794  int flags           /* PAGER_GET_XXX flags */
62795){
62796  UNUSED_PARAMETER(pgno);
62797  UNUSED_PARAMETER(flags);
62798  assert( pPager->errCode!=SQLITE_OK );
62799  *ppPage = 0;
62800  return pPager->errCode;
62801}
62802
62803
62804/* Dispatch all page fetch requests to the appropriate getter method.
62805*/
62806SQLITE_PRIVATE int sqlite3PagerGet(
62807  Pager *pPager,      /* The pager open on the database file */
62808  Pgno pgno,          /* Page number to fetch */
62809  DbPage **ppPage,    /* Write a pointer to the page here */
62810  int flags           /* PAGER_GET_XXX flags */
62811){
62812#if 0   /* Trace page fetch by setting to 1 */
62813  int rc;
62814  printf("PAGE %u\n", pgno);
62815  fflush(stdout);
62816  rc = pPager->xGet(pPager, pgno, ppPage, flags);
62817  if( rc ){
62818    printf("PAGE %u failed with 0x%02x\n", pgno, rc);
62819    fflush(stdout);
62820  }
62821  return rc;
62822#else
62823  /* Normal, high-speed version of sqlite3PagerGet() */
62824  return pPager->xGet(pPager, pgno, ppPage, flags);
62825#endif
62826}
62827
62828/*
62829** Acquire a page if it is already in the in-memory cache.  Do
62830** not read the page from disk.  Return a pointer to the page,
62831** or 0 if the page is not in cache.
62832**
62833** See also sqlite3PagerGet().  The difference between this routine
62834** and sqlite3PagerGet() is that _get() will go to the disk and read
62835** in the page if the page is not already in cache.  This routine
62836** returns NULL if the page is not in cache or if a disk I/O error
62837** has ever happened.
62838*/
62839SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
62840  sqlite3_pcache_page *pPage;
62841  assert( pPager!=0 );
62842  assert( pgno!=0 );
62843  assert( pPager->pPCache!=0 );
62844  pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
62845  assert( pPage==0 || pPager->hasHeldSharedLock );
62846  if( pPage==0 ) return 0;
62847  return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
62848}
62849
62850/*
62851** Release a page reference.
62852**
62853** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be used
62854** if we know that the page being released is not the last reference to page1.
62855** The btree layer always holds page1 open until the end, so these first
62856** two routines can be used to release any page other than BtShared.pPage1.
62857** The assert() at tag-20230419-2 proves that this constraint is always
62858** honored.
62859**
62860** Use sqlite3PagerUnrefPageOne() to release page1.  This latter routine
62861** checks the total number of outstanding pages and if the number of
62862** pages reaches zero it drops the database lock.
62863*/
62864SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
62865  TESTONLY( Pager *pPager = pPg->pPager; )
62866  assert( pPg!=0 );
62867  if( pPg->flags & PGHDR_MMAP ){
62868    assert( pPg->pgno!=1 );  /* Page1 is never memory mapped */
62869    pagerReleaseMapPage(pPg);
62870  }else{
62871    sqlite3PcacheRelease(pPg);
62872  }
62873  /* Do not use this routine to release the last reference to page1 */
62874  assert( sqlite3PcacheRefCount(pPager->pPCache)>0 ); /* tag-20230419-2 */
62875}
62876SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
62877  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
62878}
62879SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
62880  Pager *pPager;
62881  assert( pPg!=0 );
62882  assert( pPg->pgno==1 );
62883  assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
62884  pPager = pPg->pPager;
62885  sqlite3PcacheRelease(pPg);
62886  pagerUnlockIfUnused(pPager);
62887}
62888
62889/*
62890** This function is called at the start of every write transaction.
62891** There must already be a RESERVED or EXCLUSIVE lock on the database
62892** file when this routine is called.
62893**
62894** Open the journal file for pager pPager and write a journal header
62895** to the start of it. If there are active savepoints, open the sub-journal
62896** as well. This function is only used when the journal file is being
62897** opened to write a rollback log for a transaction. It is not used
62898** when opening a hot journal file to roll it back.
62899**
62900** If the journal file is already open (as it may be in exclusive mode),
62901** then this function just writes a journal header to the start of the
62902** already open file.
62903**
62904** Whether or not the journal file is opened by this function, the
62905** Pager.pInJournal bitvec structure is allocated.
62906**
62907** Return SQLITE_OK if everything is successful. Otherwise, return
62908** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
62909** an IO error code if opening or writing the journal file fails.
62910*/
62911static int pager_open_journal(Pager *pPager){
62912  int rc = SQLITE_OK;                        /* Return code */
62913  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
62914
62915  assert( pPager->eState==PAGER_WRITER_LOCKED );
62916  assert( assert_pager_state(pPager) );
62917  assert( pPager->pInJournal==0 );
62918
62919  /* If already in the error state, this function is a no-op.  But on
62920  ** the other hand, this routine is never called if we are already in
62921  ** an error state. */
62922  if( NEVER(pPager->errCode) ) return pPager->errCode;
62923
62924  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
62925    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
62926    if( pPager->pInJournal==0 ){
62927      return SQLITE_NOMEM_BKPT;
62928    }
62929
62930    /* Open the journal file if it is not already open. */
62931    if( !isOpen(pPager->jfd) ){
62932      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
62933        sqlite3MemJournalOpen(pPager->jfd);
62934      }else{
62935        int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
62936        int nSpill;
62937
62938        if( pPager->tempFile ){
62939          flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
62940          flags |= SQLITE_OPEN_EXCLUSIVE;
62941          nSpill = sqlite3Config.nStmtSpill;
62942        }else{
62943          flags |= SQLITE_OPEN_MAIN_JOURNAL;
62944          nSpill = jrnlBufferSize(pPager);
62945        }
62946
62947        /* Verify that the database still has the same name as it did when
62948        ** it was originally opened. */
62949        rc = databaseIsUnmoved(pPager);
62950        if( rc==SQLITE_OK ){
62951          rc = sqlite3JournalOpen (
62952              pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
62953          );
62954        }
62955      }
62956      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
62957    }
62958
62959
62960    /* Write the first journal header to the journal file and open
62961    ** the sub-journal if necessary.
62962    */
62963    if( rc==SQLITE_OK ){
62964      /* TODO: Check if all of these are really required. */
62965      pPager->nRec = 0;
62966      pPager->journalOff = 0;
62967      pPager->setSuper = 0;
62968      pPager->journalHdr = 0;
62969      rc = writeJournalHdr(pPager);
62970    }
62971  }
62972
62973  if( rc!=SQLITE_OK ){
62974    sqlite3BitvecDestroy(pPager->pInJournal);
62975    pPager->pInJournal = 0;
62976    pPager->journalOff = 0;
62977  }else{
62978    assert( pPager->eState==PAGER_WRITER_LOCKED );
62979    pPager->eState = PAGER_WRITER_CACHEMOD;
62980  }
62981
62982  return rc;
62983}
62984
62985/*
62986** Begin a write-transaction on the specified pager object. If a
62987** write-transaction has already been opened, this function is a no-op.
62988**
62989** If the exFlag argument is false, then acquire at least a RESERVED
62990** lock on the database file. If exFlag is true, then acquire at least
62991** an EXCLUSIVE lock. If such a lock is already held, no locking
62992** functions need be called.
62993**
62994** If the subjInMemory argument is non-zero, then any sub-journal opened
62995** within this transaction will be opened as an in-memory file. This
62996** has no effect if the sub-journal is already opened (as it may be when
62997** running in exclusive mode) or if the transaction does not require a
62998** sub-journal. If the subjInMemory argument is zero, then any required
62999** sub-journal is implemented in-memory if pPager is an in-memory database,
63000** or using a temporary file otherwise.
63001*/
63002SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
63003  int rc = SQLITE_OK;
63004
63005  if( pPager->errCode ) return pPager->errCode;
63006  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
63007  pPager->subjInMemory = (u8)subjInMemory;
63008
63009  if( pPager->eState==PAGER_READER ){
63010    assert( pPager->pInJournal==0 );
63011
63012    if( pagerUseWal(pPager) ){
63013      /* If the pager is configured to use locking_mode=exclusive, and an
63014      ** exclusive lock on the database is not already held, obtain it now.
63015      */
63016      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
63017        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
63018        if( rc!=SQLITE_OK ){
63019          return rc;
63020        }
63021        (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
63022      }
63023
63024      /* Grab the write lock on the log file. If successful, upgrade to
63025      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
63026      ** The busy-handler is not invoked if another connection already
63027      ** holds the write-lock. If possible, the upper layer will call it.
63028      */
63029      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
63030    }else{
63031      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
63032      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
63033      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
63034      ** lock, but not when obtaining the RESERVED lock.
63035      */
63036      rc = pagerLockDb(pPager, RESERVED_LOCK);
63037      if( rc==SQLITE_OK && exFlag ){
63038        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
63039      }
63040    }
63041
63042    if( rc==SQLITE_OK ){
63043      /* Change to WRITER_LOCKED state.
63044      **
63045      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
63046      ** when it has an open transaction, but never to DBMOD or FINISHED.
63047      ** This is because in those states the code to roll back savepoint
63048      ** transactions may copy data from the sub-journal into the database
63049      ** file as well as into the page cache. Which would be incorrect in
63050      ** WAL mode.
63051      */
63052      pPager->eState = PAGER_WRITER_LOCKED;
63053      pPager->dbHintSize = pPager->dbSize;
63054      pPager->dbFileSize = pPager->dbSize;
63055      pPager->dbOrigSize = pPager->dbSize;
63056      pPager->journalOff = 0;
63057    }
63058
63059    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
63060    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
63061    assert( assert_pager_state(pPager) );
63062  }
63063
63064  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
63065  return rc;
63066}
63067
63068/*
63069** Write page pPg onto the end of the rollback journal.
63070*/
63071static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
63072  Pager *pPager = pPg->pPager;
63073  int rc;
63074  u32 cksum;
63075  char *pData2;
63076  i64 iOff = pPager->journalOff;
63077
63078  /* We should never write to the journal file the page that
63079  ** contains the database locks.  The following assert verifies
63080  ** that we do not. */
63081  assert( pPg->pgno!=PAGER_SJ_PGNO(pPager) );
63082
63083  assert( pPager->journalHdr<=pPager->journalOff );
63084  pData2 = pPg->pData;
63085  cksum = pager_cksum(pPager, (u8*)pData2);
63086
63087  /* Even if an IO or diskfull error occurs while journalling the
63088  ** page in the block above, set the need-sync flag for the page.
63089  ** Otherwise, when the transaction is rolled back, the logic in
63090  ** playback_one_page() will think that the page needs to be restored
63091  ** in the database file. And if an IO error occurs while doing so,
63092  ** then corruption may follow.
63093  */
63094  pPg->flags |= PGHDR_NEED_SYNC;
63095
63096  rc = write32bits(pPager->jfd, iOff, pPg->pgno);
63097  if( rc!=SQLITE_OK ) return rc;
63098  rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
63099  if( rc!=SQLITE_OK ) return rc;
63100  rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
63101  if( rc!=SQLITE_OK ) return rc;
63102
63103  IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
63104           pPager->journalOff, pPager->pageSize));
63105  PAGER_INCR(sqlite3_pager_writej_count);
63106  PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
63107       PAGERID(pPager), pPg->pgno,
63108       ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
63109
63110  pPager->journalOff += 8 + pPager->pageSize;
63111  pPager->nRec++;
63112  assert( pPager->pInJournal!=0 );
63113  rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
63114  testcase( rc==SQLITE_NOMEM );
63115  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
63116  rc |= addToSavepointBitvecs(pPager, pPg->pgno);
63117  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
63118  return rc;
63119}
63120
63121/*
63122** Mark a single data page as writeable. The page is written into the
63123** main journal or sub-journal as required. If the page is written into
63124** one of the journals, the corresponding bit is set in the
63125** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
63126** of any open savepoints as appropriate.
63127*/
63128static int pager_write(PgHdr *pPg){
63129  Pager *pPager = pPg->pPager;
63130  int rc = SQLITE_OK;
63131
63132  /* This routine is not called unless a write-transaction has already
63133  ** been started. The journal file may or may not be open at this point.
63134  ** It is never called in the ERROR state.
63135  */
63136  assert( pPager->eState==PAGER_WRITER_LOCKED
63137       || pPager->eState==PAGER_WRITER_CACHEMOD
63138       || pPager->eState==PAGER_WRITER_DBMOD
63139  );
63140  assert( assert_pager_state(pPager) );
63141  assert( pPager->errCode==0 );
63142  assert( pPager->readOnly==0 );
63143  CHECK_PAGE(pPg);
63144
63145  /* The journal file needs to be opened. Higher level routines have already
63146  ** obtained the necessary locks to begin the write-transaction, but the
63147  ** rollback journal might not yet be open. Open it now if this is the case.
63148  **
63149  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
63150  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
63151  ** an error might occur and the pager would end up in WRITER_LOCKED state
63152  ** with pages marked as dirty in the cache.
63153  */
63154  if( pPager->eState==PAGER_WRITER_LOCKED ){
63155    rc = pager_open_journal(pPager);
63156    if( rc!=SQLITE_OK ) return rc;
63157  }
63158  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
63159  assert( assert_pager_state(pPager) );
63160
63161  /* Mark the page that is about to be modified as dirty. */
63162  sqlite3PcacheMakeDirty(pPg);
63163
63164  /* If a rollback journal is in use, them make sure the page that is about
63165  ** to change is in the rollback journal, or if the page is a new page off
63166  ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
63167  */
63168  assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
63169  if( pPager->pInJournal!=0
63170   && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
63171  ){
63172    assert( pagerUseWal(pPager)==0 );
63173    if( pPg->pgno<=pPager->dbOrigSize ){
63174      rc = pagerAddPageToRollbackJournal(pPg);
63175      if( rc!=SQLITE_OK ){
63176        return rc;
63177      }
63178    }else{
63179      if( pPager->eState!=PAGER_WRITER_DBMOD ){
63180        pPg->flags |= PGHDR_NEED_SYNC;
63181      }
63182      PAGERTRACE(("APPEND %d page %d needSync=%d\n",
63183              PAGERID(pPager), pPg->pgno,
63184             ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
63185    }
63186  }
63187
63188  /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
63189  ** and before writing the page into the rollback journal.  Wait until now,
63190  ** after the page has been successfully journalled, before setting the
63191  ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
63192  */
63193  pPg->flags |= PGHDR_WRITEABLE;
63194
63195  /* If the statement journal is open and the page is not in it,
63196  ** then write the page into the statement journal.
63197  */
63198  if( pPager->nSavepoint>0 ){
63199    rc = subjournalPageIfRequired(pPg);
63200  }
63201
63202  /* Update the database size and return. */
63203  if( pPager->dbSize<pPg->pgno ){
63204    pPager->dbSize = pPg->pgno;
63205  }
63206  return rc;
63207}
63208
63209/*
63210** This is a variant of sqlite3PagerWrite() that runs when the sector size
63211** is larger than the page size.  SQLite makes the (reasonable) assumption that
63212** all bytes of a sector are written together by hardware.  Hence, all bytes of
63213** a sector need to be journalled in case of a power loss in the middle of
63214** a write.
63215**
63216** Usually, the sector size is less than or equal to the page size, in which
63217** case pages can be individually written.  This routine only runs in the
63218** exceptional case where the page size is smaller than the sector size.
63219*/
63220static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
63221  int rc = SQLITE_OK;          /* Return code */
63222  Pgno nPageCount;             /* Total number of pages in database file */
63223  Pgno pg1;                    /* First page of the sector pPg is located on. */
63224  int nPage = 0;               /* Number of pages starting at pg1 to journal */
63225  int ii;                      /* Loop counter */
63226  int needSync = 0;            /* True if any page has PGHDR_NEED_SYNC */
63227  Pager *pPager = pPg->pPager; /* The pager that owns pPg */
63228  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
63229
63230  /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
63231  ** a journal header to be written between the pages journaled by
63232  ** this function.
63233  */
63234  assert( !MEMDB );
63235  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
63236  pPager->doNotSpill |= SPILLFLAG_NOSYNC;
63237
63238  /* This trick assumes that both the page-size and sector-size are
63239  ** an integer power of 2. It sets variable pg1 to the identifier
63240  ** of the first page of the sector pPg is located on.
63241  */
63242  pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
63243
63244  nPageCount = pPager->dbSize;
63245  if( pPg->pgno>nPageCount ){
63246    nPage = (pPg->pgno - pg1)+1;
63247  }else if( (pg1+nPagePerSector-1)>nPageCount ){
63248    nPage = nPageCount+1-pg1;
63249  }else{
63250    nPage = nPagePerSector;
63251  }
63252  assert(nPage>0);
63253  assert(pg1<=pPg->pgno);
63254  assert((pg1+nPage)>pPg->pgno);
63255
63256  for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
63257    Pgno pg = pg1+ii;
63258    PgHdr *pPage;
63259    if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
63260      if( pg!=PAGER_SJ_PGNO(pPager) ){
63261        rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
63262        if( rc==SQLITE_OK ){
63263          rc = pager_write(pPage);
63264          if( pPage->flags&PGHDR_NEED_SYNC ){
63265            needSync = 1;
63266          }
63267          sqlite3PagerUnrefNotNull(pPage);
63268        }
63269      }
63270    }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
63271      if( pPage->flags&PGHDR_NEED_SYNC ){
63272        needSync = 1;
63273      }
63274      sqlite3PagerUnrefNotNull(pPage);
63275    }
63276  }
63277
63278  /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
63279  ** starting at pg1, then it needs to be set for all of them. Because
63280  ** writing to any of these nPage pages may damage the others, the
63281  ** journal file must contain sync()ed copies of all of them
63282  ** before any of them can be written out to the database file.
63283  */
63284  if( rc==SQLITE_OK && needSync ){
63285    assert( !MEMDB );
63286    for(ii=0; ii<nPage; ii++){
63287      PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
63288      if( pPage ){
63289        pPage->flags |= PGHDR_NEED_SYNC;
63290        sqlite3PagerUnrefNotNull(pPage);
63291      }
63292    }
63293  }
63294
63295  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
63296  pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
63297  return rc;
63298}
63299
63300/*
63301** Mark a data page as writeable. This routine must be called before
63302** making changes to a page. The caller must check the return value
63303** of this function and be careful not to change any page data unless
63304** this routine returns SQLITE_OK.
63305**
63306** The difference between this function and pager_write() is that this
63307** function also deals with the special case where 2 or more pages
63308** fit on a single disk sector. In this case all co-resident pages
63309** must have been written to the journal file before returning.
63310**
63311** If an error occurs, SQLITE_NOMEM or an IO error code is returned
63312** as appropriate. Otherwise, SQLITE_OK.
63313*/
63314SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
63315  Pager *pPager = pPg->pPager;
63316  assert( (pPg->flags & PGHDR_MMAP)==0 );
63317  assert( pPager->eState>=PAGER_WRITER_LOCKED );
63318  assert( assert_pager_state(pPager) );
63319  if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
63320    if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
63321    return SQLITE_OK;
63322  }else if( pPager->errCode ){
63323    return pPager->errCode;
63324  }else if( pPager->sectorSize > (u32)pPager->pageSize ){
63325    assert( pPager->tempFile==0 );
63326    return pagerWriteLargeSector(pPg);
63327  }else{
63328    return pager_write(pPg);
63329  }
63330}
63331
63332/*
63333** Return TRUE if the page given in the argument was previously passed
63334** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
63335** to change the content of the page.
63336*/
63337#ifndef NDEBUG
63338SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
63339  return pPg->flags & PGHDR_WRITEABLE;
63340}
63341#endif
63342
63343/*
63344** A call to this routine tells the pager that it is not necessary to
63345** write the information on page pPg back to the disk, even though
63346** that page might be marked as dirty.  This happens, for example, when
63347** the page has been added as a leaf of the freelist and so its
63348** content no longer matters.
63349**
63350** The overlying software layer calls this routine when all of the data
63351** on the given page is unused. The pager marks the page as clean so
63352** that it does not get written to disk.
63353**
63354** Tests show that this optimization can quadruple the speed of large
63355** DELETE operations.
63356**
63357** This optimization cannot be used with a temp-file, as the page may
63358** have been dirty at the start of the transaction. In that case, if
63359** memory pressure forces page pPg out of the cache, the data does need
63360** to be written out to disk so that it may be read back in if the
63361** current transaction is rolled back.
63362*/
63363SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
63364  Pager *pPager = pPg->pPager;
63365  if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
63366    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
63367    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
63368    pPg->flags |= PGHDR_DONT_WRITE;
63369    pPg->flags &= ~PGHDR_WRITEABLE;
63370    testcase( pPg->flags & PGHDR_NEED_SYNC );
63371    pager_set_pagehash(pPg);
63372  }
63373}
63374
63375/*
63376** This routine is called to increment the value of the database file
63377** change-counter, stored as a 4-byte big-endian integer starting at
63378** byte offset 24 of the pager file.  The secondary change counter at
63379** 92 is also updated, as is the SQLite version number at offset 96.
63380**
63381** But this only happens if the pPager->changeCountDone flag is false.
63382** To avoid excess churning of page 1, the update only happens once.
63383** See also the pager_write_changecounter() routine that does an
63384** unconditional update of the change counters.
63385**
63386** If the isDirectMode flag is zero, then this is done by calling
63387** sqlite3PagerWrite() on page 1, then modifying the contents of the
63388** page data. In this case the file will be updated when the current
63389** transaction is committed.
63390**
63391** The isDirectMode flag may only be non-zero if the library was compiled
63392** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
63393** if isDirect is non-zero, then the database file is updated directly
63394** by writing an updated version of page 1 using a call to the
63395** sqlite3OsWrite() function.
63396*/
63397static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
63398  int rc = SQLITE_OK;
63399
63400  assert( pPager->eState==PAGER_WRITER_CACHEMOD
63401       || pPager->eState==PAGER_WRITER_DBMOD
63402  );
63403  assert( assert_pager_state(pPager) );
63404
63405  /* Declare and initialize constant integer 'isDirect'. If the
63406  ** atomic-write optimization is enabled in this build, then isDirect
63407  ** is initialized to the value passed as the isDirectMode parameter
63408  ** to this function. Otherwise, it is always set to zero.
63409  **
63410  ** The idea is that if the atomic-write optimization is not
63411  ** enabled at compile time, the compiler can omit the tests of
63412  ** 'isDirect' below, as well as the block enclosed in the
63413  ** "if( isDirect )" condition.
63414  */
63415#ifndef SQLITE_ENABLE_ATOMIC_WRITE
63416# define DIRECT_MODE 0
63417  assert( isDirectMode==0 );
63418  UNUSED_PARAMETER(isDirectMode);
63419#else
63420# define DIRECT_MODE isDirectMode
63421#endif
63422
63423  if( !pPager->changeCountDone && pPager->dbSize>0 ){
63424    PgHdr *pPgHdr;                /* Reference to page 1 */
63425
63426    assert( !pPager->tempFile && isOpen(pPager->fd) );
63427
63428    /* Open page 1 of the file for writing. */
63429    rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
63430    assert( pPgHdr==0 || rc==SQLITE_OK );
63431
63432    /* If page one was fetched successfully, and this function is not
63433    ** operating in direct-mode, make page 1 writable.  When not in
63434    ** direct mode, page 1 is always held in cache and hence the PagerGet()
63435    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
63436    */
63437    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
63438      rc = sqlite3PagerWrite(pPgHdr);
63439    }
63440
63441    if( rc==SQLITE_OK ){
63442      /* Actually do the update of the change counter */
63443      pager_write_changecounter(pPgHdr);
63444
63445      /* If running in direct mode, write the contents of page 1 to the file. */
63446      if( DIRECT_MODE ){
63447        const void *zBuf;
63448        assert( pPager->dbFileSize>0 );
63449        zBuf = pPgHdr->pData;
63450        if( rc==SQLITE_OK ){
63451          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
63452          pPager->aStat[PAGER_STAT_WRITE]++;
63453        }
63454        if( rc==SQLITE_OK ){
63455          /* Update the pager's copy of the change-counter. Otherwise, the
63456          ** next time a read transaction is opened the cache will be
63457          ** flushed (as the change-counter values will not match).  */
63458          const void *pCopy = (const void *)&((const char *)zBuf)[24];
63459          memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
63460          pPager->changeCountDone = 1;
63461        }
63462      }else{
63463        pPager->changeCountDone = 1;
63464      }
63465    }
63466
63467    /* Release the page reference. */
63468    sqlite3PagerUnref(pPgHdr);
63469  }
63470  return rc;
63471}
63472
63473/*
63474** Sync the database file to disk. This is a no-op for in-memory databases
63475** or pages with the Pager.noSync flag set.
63476**
63477** If successful, or if called on a pager for which it is a no-op, this
63478** function returns SQLITE_OK. Otherwise, an IO error code is returned.
63479*/
63480SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zSuper){
63481  int rc = SQLITE_OK;
63482  void *pArg = (void*)zSuper;
63483  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
63484  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
63485  if( rc==SQLITE_OK && !pPager->noSync ){
63486    assert( !MEMDB );
63487    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
63488  }
63489  return rc;
63490}
63491
63492/*
63493** This function may only be called while a write-transaction is active in
63494** rollback. If the connection is in WAL mode, this call is a no-op.
63495** Otherwise, if the connection does not already have an EXCLUSIVE lock on
63496** the database file, an attempt is made to obtain one.
63497**
63498** If the EXCLUSIVE lock is already held or the attempt to obtain it is
63499** successful, or the connection is in WAL mode, SQLITE_OK is returned.
63500** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
63501** returned.
63502*/
63503SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
63504  int rc = pPager->errCode;
63505  assert( assert_pager_state(pPager) );
63506  if( rc==SQLITE_OK ){
63507    assert( pPager->eState==PAGER_WRITER_CACHEMOD
63508         || pPager->eState==PAGER_WRITER_DBMOD
63509         || pPager->eState==PAGER_WRITER_LOCKED
63510    );
63511    assert( assert_pager_state(pPager) );
63512    if( 0==pagerUseWal(pPager) ){
63513      rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
63514    }
63515  }
63516  return rc;
63517}
63518
63519/*
63520** Sync the database file for the pager pPager. zSuper points to the name
63521** of a super-journal file that should be written into the individual
63522** journal file. zSuper may be NULL, which is interpreted as no
63523** super-journal (a single database transaction).
63524**
63525** This routine ensures that:
63526**
63527**   * The database file change-counter is updated,
63528**   * the journal is synced (unless the atomic-write optimization is used),
63529**   * all dirty pages are written to the database file,
63530**   * the database file is truncated (if required), and
63531**   * the database file synced.
63532**
63533** The only thing that remains to commit the transaction is to finalize
63534** (delete, truncate or zero the first part of) the journal file (or
63535** delete the super-journal file if specified).
63536**
63537** Note that if zSuper==NULL, this does not overwrite a previous value
63538** passed to an sqlite3PagerCommitPhaseOne() call.
63539**
63540** If the final parameter - noSync - is true, then the database file itself
63541** is not synced. The caller must call sqlite3PagerSync() directly to
63542** sync the database file before calling CommitPhaseTwo() to delete the
63543** journal file in this case.
63544*/
63545SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
63546  Pager *pPager,                  /* Pager object */
63547  const char *zSuper,            /* If not NULL, the super-journal name */
63548  int noSync                      /* True to omit the xSync on the db file */
63549){
63550  int rc = SQLITE_OK;             /* Return code */
63551
63552  assert( pPager->eState==PAGER_WRITER_LOCKED
63553       || pPager->eState==PAGER_WRITER_CACHEMOD
63554       || pPager->eState==PAGER_WRITER_DBMOD
63555       || pPager->eState==PAGER_ERROR
63556  );
63557  assert( assert_pager_state(pPager) );
63558
63559  /* If a prior error occurred, report that error again. */
63560  if( NEVER(pPager->errCode) ) return pPager->errCode;
63561
63562  /* Provide the ability to easily simulate an I/O error during testing */
63563  if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
63564
63565  PAGERTRACE(("DATABASE SYNC: File=%s zSuper=%s nSize=%d\n",
63566      pPager->zFilename, zSuper, pPager->dbSize));
63567
63568  /* If no database changes have been made, return early. */
63569  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
63570
63571  assert( MEMDB==0 || pPager->tempFile );
63572  assert( isOpen(pPager->fd) || pPager->tempFile );
63573  if( 0==pagerFlushOnCommit(pPager, 1) ){
63574    /* If this is an in-memory db, or no pages have been written to, or this
63575    ** function has already been called, it is mostly a no-op.  However, any
63576    ** backup in progress needs to be restarted.  */
63577    sqlite3BackupRestart(pPager->pBackup);
63578  }else{
63579    PgHdr *pList;
63580    if( pagerUseWal(pPager) ){
63581      PgHdr *pPageOne = 0;
63582      pList = sqlite3PcacheDirtyList(pPager->pPCache);
63583      if( pList==0 ){
63584        /* Must have at least one page for the WAL commit flag.
63585        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
63586        rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
63587        pList = pPageOne;
63588        pList->pDirty = 0;
63589      }
63590      assert( rc==SQLITE_OK );
63591      if( ALWAYS(pList) ){
63592        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
63593      }
63594      sqlite3PagerUnref(pPageOne);
63595      if( rc==SQLITE_OK ){
63596        sqlite3PcacheCleanAll(pPager->pPCache);
63597      }
63598    }else{
63599      /* The bBatch boolean is true if the batch-atomic-write commit method
63600      ** should be used.  No rollback journal is created if batch-atomic-write
63601      ** is enabled.
63602      */
63603#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
63604      sqlite3_file *fd = pPager->fd;
63605      int bBatch = zSuper==0    /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
63606        && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
63607        && !pPager->noSync
63608        && sqlite3JournalIsInMemory(pPager->jfd);
63609#else
63610#     define bBatch 0
63611#endif
63612
63613#ifdef SQLITE_ENABLE_ATOMIC_WRITE
63614      /* The following block updates the change-counter. Exactly how it
63615      ** does this depends on whether or not the atomic-update optimization
63616      ** was enabled at compile time, and if this transaction meets the
63617      ** runtime criteria to use the operation:
63618      **
63619      **    * The file-system supports the atomic-write property for
63620      **      blocks of size page-size, and
63621      **    * This commit is not part of a multi-file transaction, and
63622      **    * Exactly one page has been modified and store in the journal file.
63623      **
63624      ** If the optimization was not enabled at compile time, then the
63625      ** pager_incr_changecounter() function is called to update the change
63626      ** counter in 'indirect-mode'. If the optimization is compiled in but
63627      ** is not applicable to this transaction, call sqlite3JournalCreate()
63628      ** to make sure the journal file has actually been created, then call
63629      ** pager_incr_changecounter() to update the change-counter in indirect
63630      ** mode.
63631      **
63632      ** Otherwise, if the optimization is both enabled and applicable,
63633      ** then call pager_incr_changecounter() to update the change-counter
63634      ** in 'direct' mode. In this case the journal file will never be
63635      ** created for this transaction.
63636      */
63637      if( bBatch==0 ){
63638        PgHdr *pPg;
63639        assert( isOpen(pPager->jfd)
63640            || pPager->journalMode==PAGER_JOURNALMODE_OFF
63641            || pPager->journalMode==PAGER_JOURNALMODE_WAL
63642            );
63643        if( !zSuper && isOpen(pPager->jfd)
63644         && pPager->journalOff==jrnlBufferSize(pPager)
63645         && pPager->dbSize>=pPager->dbOrigSize
63646         && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
63647        ){
63648          /* Update the db file change counter via the direct-write method. The
63649          ** following call will modify the in-memory representation of page 1
63650          ** to include the updated change counter and then write page 1
63651          ** directly to the database file. Because of the atomic-write
63652          ** property of the host file-system, this is safe.
63653          */
63654          rc = pager_incr_changecounter(pPager, 1);
63655        }else{
63656          rc = sqlite3JournalCreate(pPager->jfd);
63657          if( rc==SQLITE_OK ){
63658            rc = pager_incr_changecounter(pPager, 0);
63659          }
63660        }
63661      }
63662#else  /* SQLITE_ENABLE_ATOMIC_WRITE */
63663#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
63664      if( zSuper ){
63665        rc = sqlite3JournalCreate(pPager->jfd);
63666        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
63667        assert( bBatch==0 );
63668      }
63669#endif
63670      rc = pager_incr_changecounter(pPager, 0);
63671#endif /* !SQLITE_ENABLE_ATOMIC_WRITE */
63672      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
63673
63674      /* Write the super-journal name into the journal file. If a
63675      ** super-journal file name has already been written to the journal file,
63676      ** or if zSuper is NULL (no super-journal), then this call is a no-op.
63677      */
63678      rc = writeSuperJournal(pPager, zSuper);
63679      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
63680
63681      /* Sync the journal file and write all dirty pages to the database.
63682      ** If the atomic-update optimization is being used, this sync will not
63683      ** create the journal file or perform any real IO.
63684      **
63685      ** Because the change-counter page was just modified, unless the
63686      ** atomic-update optimization is used it is almost certain that the
63687      ** journal requires a sync here. However, in locking_mode=exclusive
63688      ** on a system under memory pressure it is just possible that this is
63689      ** not the case. In this case it is likely enough that the redundant
63690      ** xSync() call will be changed to a no-op by the OS anyhow.
63691      */
63692      rc = syncJournal(pPager, 0);
63693      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
63694
63695      pList = sqlite3PcacheDirtyList(pPager->pPCache);
63696#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
63697      if( bBatch ){
63698        rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
63699        if( rc==SQLITE_OK ){
63700          rc = pager_write_pagelist(pPager, pList);
63701          if( rc==SQLITE_OK && pPager->dbSize>pPager->dbFileSize ){
63702            char *pTmp = pPager->pTmpSpace;
63703            int szPage = (int)pPager->pageSize;
63704            memset(pTmp, 0, szPage);
63705            rc = sqlite3OsWrite(pPager->fd, pTmp, szPage,
63706                      ((i64)pPager->dbSize*pPager->pageSize)-szPage);
63707          }
63708          if( rc==SQLITE_OK ){
63709            rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
63710          }
63711          if( rc!=SQLITE_OK ){
63712            sqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
63713          }
63714        }
63715
63716        if( (rc&0xFF)==SQLITE_IOERR && rc!=SQLITE_IOERR_NOMEM ){
63717          rc = sqlite3JournalCreate(pPager->jfd);
63718          if( rc!=SQLITE_OK ){
63719            sqlite3OsClose(pPager->jfd);
63720            goto commit_phase_one_exit;
63721          }
63722          bBatch = 0;
63723        }else{
63724          sqlite3OsClose(pPager->jfd);
63725        }
63726      }
63727#endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
63728
63729      if( bBatch==0 ){
63730        rc = pager_write_pagelist(pPager, pList);
63731      }
63732      if( rc!=SQLITE_OK ){
63733        assert( rc!=SQLITE_IOERR_BLOCKED );
63734        goto commit_phase_one_exit;
63735      }
63736      sqlite3PcacheCleanAll(pPager->pPCache);
63737
63738      /* If the file on disk is smaller than the database image, use
63739      ** pager_truncate to grow the file here. This can happen if the database
63740      ** image was extended as part of the current transaction and then the
63741      ** last page in the db image moved to the free-list. In this case the
63742      ** last page is never written out to disk, leaving the database file
63743      ** undersized. Fix this now if it is the case.  */
63744      if( pPager->dbSize>pPager->dbFileSize ){
63745        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_SJ_PGNO(pPager));
63746        assert( pPager->eState==PAGER_WRITER_DBMOD );
63747        rc = pager_truncate(pPager, nNew);
63748        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
63749      }
63750
63751      /* Finally, sync the database file. */
63752      if( !noSync ){
63753        rc = sqlite3PagerSync(pPager, zSuper);
63754      }
63755      IOTRACE(("DBSYNC %p\n", pPager))
63756    }
63757  }
63758
63759commit_phase_one_exit:
63760  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
63761    pPager->eState = PAGER_WRITER_FINISHED;
63762  }
63763  return rc;
63764}
63765
63766
63767/*
63768** When this function is called, the database file has been completely
63769** updated to reflect the changes made by the current transaction and
63770** synced to disk. The journal file still exists in the file-system
63771** though, and if a failure occurs at this point it will eventually
63772** be used as a hot-journal and the current transaction rolled back.
63773**
63774** This function finalizes the journal file, either by deleting,
63775** truncating or partially zeroing it, so that it cannot be used
63776** for hot-journal rollback. Once this is done the transaction is
63777** irrevocably committed.
63778**
63779** If an error occurs, an IO error code is returned and the pager
63780** moves into the error state. Otherwise, SQLITE_OK is returned.
63781*/
63782SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
63783  int rc = SQLITE_OK;                  /* Return code */
63784
63785  /* This routine should not be called if a prior error has occurred.
63786  ** But if (due to a coding error elsewhere in the system) it does get
63787  ** called, just return the same error code without doing anything. */
63788  if( NEVER(pPager->errCode) ) return pPager->errCode;
63789  pPager->iDataVersion++;
63790
63791  assert( pPager->eState==PAGER_WRITER_LOCKED
63792       || pPager->eState==PAGER_WRITER_FINISHED
63793       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
63794  );
63795  assert( assert_pager_state(pPager) );
63796
63797  /* An optimization. If the database was not actually modified during
63798  ** this transaction, the pager is running in exclusive-mode and is
63799  ** using persistent journals, then this function is a no-op.
63800  **
63801  ** The start of the journal file currently contains a single journal
63802  ** header with the nRec field set to 0. If such a journal is used as
63803  ** a hot-journal during hot-journal rollback, 0 changes will be made
63804  ** to the database file. So there is no need to zero the journal
63805  ** header. Since the pager is in exclusive mode, there is no need
63806  ** to drop any locks either.
63807  */
63808  if( pPager->eState==PAGER_WRITER_LOCKED
63809   && pPager->exclusiveMode
63810   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
63811  ){
63812    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
63813    pPager->eState = PAGER_READER;
63814    return SQLITE_OK;
63815  }
63816
63817  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
63818  rc = pager_end_transaction(pPager, pPager->setSuper, 1);
63819  return pager_error(pPager, rc);
63820}
63821
63822/*
63823** If a write transaction is open, then all changes made within the
63824** transaction are reverted and the current write-transaction is closed.
63825** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
63826** state if an error occurs.
63827**
63828** If the pager is already in PAGER_ERROR state when this function is called,
63829** it returns Pager.errCode immediately. No work is performed in this case.
63830**
63831** Otherwise, in rollback mode, this function performs two functions:
63832**
63833**   1) It rolls back the journal file, restoring all database file and
63834**      in-memory cache pages to the state they were in when the transaction
63835**      was opened, and
63836**
63837**   2) It finalizes the journal file, so that it is not used for hot
63838**      rollback at any point in the future.
63839**
63840** Finalization of the journal file (task 2) is only performed if the
63841** rollback is successful.
63842**
63843** In WAL mode, all cache-entries containing data modified within the
63844** current transaction are either expelled from the cache or reverted to
63845** their pre-transaction state by re-reading data from the database or
63846** WAL files. The WAL transaction is then closed.
63847*/
63848SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
63849  int rc = SQLITE_OK;                  /* Return code */
63850  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
63851
63852  /* PagerRollback() is a no-op if called in READER or OPEN state. If
63853  ** the pager is already in the ERROR state, the rollback is not
63854  ** attempted here. Instead, the error code is returned to the caller.
63855  */
63856  assert( assert_pager_state(pPager) );
63857  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
63858  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
63859
63860  if( pagerUseWal(pPager) ){
63861    int rc2;
63862    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
63863    rc2 = pager_end_transaction(pPager, pPager->setSuper, 0);
63864    if( rc==SQLITE_OK ) rc = rc2;
63865  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
63866    int eState = pPager->eState;
63867    rc = pager_end_transaction(pPager, 0, 0);
63868    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
63869      /* This can happen using journal_mode=off. Move the pager to the error
63870      ** state to indicate that the contents of the cache may not be trusted.
63871      ** Any active readers will get SQLITE_ABORT.
63872      */
63873      pPager->errCode = SQLITE_ABORT;
63874      pPager->eState = PAGER_ERROR;
63875      setGetterMethod(pPager);
63876      return rc;
63877    }
63878  }else{
63879    rc = pager_playback(pPager, 0);
63880  }
63881
63882  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
63883  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
63884          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
63885          || rc==SQLITE_CANTOPEN
63886  );
63887
63888  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
63889  ** cache. So call pager_error() on the way out to make any error persistent.
63890  */
63891  return pager_error(pPager, rc);
63892}
63893
63894/*
63895** Return TRUE if the database file is opened read-only.  Return FALSE
63896** if the database is (in theory) writable.
63897*/
63898SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
63899  return pPager->readOnly;
63900}
63901
63902#ifdef SQLITE_DEBUG
63903/*
63904** Return the sum of the reference counts for all pages held by pPager.
63905*/
63906SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
63907  return sqlite3PcacheRefCount(pPager->pPCache);
63908}
63909#endif
63910
63911/*
63912** Return the approximate number of bytes of memory currently
63913** used by the pager and its associated cache.
63914*/
63915SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
63916  int perPageSize = pPager->pageSize + pPager->nExtra
63917    + (int)(sizeof(PgHdr) + 5*sizeof(void*));
63918  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
63919           + sqlite3MallocSize(pPager)
63920           + pPager->pageSize;
63921}
63922
63923/*
63924** Return the number of references to the specified page.
63925*/
63926SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
63927  return sqlite3PcachePageRefcount(pPage);
63928}
63929
63930#ifdef SQLITE_TEST
63931/*
63932** This routine is used for testing and analysis only.
63933*/
63934SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
63935  static int a[11];
63936  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
63937  a[1] = sqlite3PcachePagecount(pPager->pPCache);
63938  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
63939  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
63940  a[4] = pPager->eState;
63941  a[5] = pPager->errCode;
63942  a[6] = (int)pPager->aStat[PAGER_STAT_HIT] & 0x7fffffff;
63943  a[7] = (int)pPager->aStat[PAGER_STAT_MISS] & 0x7fffffff;
63944  a[8] = 0;  /* Used to be pPager->nOvfl */
63945  a[9] = pPager->nRead;
63946  a[10] = (int)pPager->aStat[PAGER_STAT_WRITE] & 0x7fffffff;
63947  return a;
63948}
63949#endif
63950
63951/*
63952** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE,
63953** or _WRITE+1.  The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation
63954** of SQLITE_DBSTATUS_CACHE_SPILL.  The _SPILL case is not contiguous because
63955** it was added later.
63956**
63957** Before returning, *pnVal is incremented by the
63958** current cache hit or miss count, according to the value of eStat. If the
63959** reset parameter is non-zero, the cache hit or miss count is zeroed before
63960** returning.
63961*/
63962SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, u64 *pnVal){
63963
63964  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
63965       || eStat==SQLITE_DBSTATUS_CACHE_MISS
63966       || eStat==SQLITE_DBSTATUS_CACHE_WRITE
63967       || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1
63968  );
63969
63970  assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
63971  assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
63972  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1
63973           && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 );
63974
63975  eStat -= SQLITE_DBSTATUS_CACHE_HIT;
63976  *pnVal += pPager->aStat[eStat];
63977  if( reset ){
63978    pPager->aStat[eStat] = 0;
63979  }
63980}
63981
63982/*
63983** Return true if this is an in-memory or temp-file backed pager.
63984*/
63985SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
63986  return pPager->tempFile || pPager->memVfs;
63987}
63988
63989/*
63990** Check that there are at least nSavepoint savepoints open. If there are
63991** currently less than nSavepoints open, then open one or more savepoints
63992** to make up the difference. If the number of savepoints is already
63993** equal to nSavepoint, then this function is a no-op.
63994**
63995** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
63996** occurs while opening the sub-journal file, then an IO error code is
63997** returned. Otherwise, SQLITE_OK.
63998*/
63999static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
64000  int rc = SQLITE_OK;                       /* Return code */
64001  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
64002  int ii;                                   /* Iterator variable */
64003  PagerSavepoint *aNew;                     /* New Pager.aSavepoint array */
64004
64005  assert( pPager->eState>=PAGER_WRITER_LOCKED );
64006  assert( assert_pager_state(pPager) );
64007  assert( nSavepoint>nCurrent && pPager->useJournal );
64008
64009  /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
64010  ** if the allocation fails. Otherwise, zero the new portion in case a
64011  ** malloc failure occurs while populating it in the for(...) loop below.
64012  */
64013  aNew = (PagerSavepoint *)sqlite3Realloc(
64014      pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
64015  );
64016  if( !aNew ){
64017    return SQLITE_NOMEM_BKPT;
64018  }
64019  memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
64020  pPager->aSavepoint = aNew;
64021
64022  /* Populate the PagerSavepoint structures just allocated. */
64023  for(ii=nCurrent; ii<nSavepoint; ii++){
64024    aNew[ii].nOrig = pPager->dbSize;
64025    if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
64026      aNew[ii].iOffset = pPager->journalOff;
64027    }else{
64028      aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
64029    }
64030    aNew[ii].iSubRec = pPager->nSubRec;
64031    aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
64032    aNew[ii].bTruncateOnRelease = 1;
64033    if( !aNew[ii].pInSavepoint ){
64034      return SQLITE_NOMEM_BKPT;
64035    }
64036    if( pagerUseWal(pPager) ){
64037      sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
64038    }
64039    pPager->nSavepoint = ii+1;
64040  }
64041  assert( pPager->nSavepoint==nSavepoint );
64042  assertTruncateConstraint(pPager);
64043  return rc;
64044}
64045SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
64046  assert( pPager->eState>=PAGER_WRITER_LOCKED );
64047  assert( assert_pager_state(pPager) );
64048
64049  if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
64050    return pagerOpenSavepoint(pPager, nSavepoint);
64051  }else{
64052    return SQLITE_OK;
64053  }
64054}
64055
64056
64057/*
64058** This function is called to rollback or release (commit) a savepoint.
64059** The savepoint to release or rollback need not be the most recently
64060** created savepoint.
64061**
64062** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
64063** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
64064** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
64065** that have occurred since the specified savepoint was created.
64066**
64067** The savepoint to rollback or release is identified by parameter
64068** iSavepoint. A value of 0 means to operate on the outermost savepoint
64069** (the first created). A value of (Pager.nSavepoint-1) means operate
64070** on the most recently created savepoint. If iSavepoint is greater than
64071** (Pager.nSavepoint-1), then this function is a no-op.
64072**
64073** If a negative value is passed to this function, then the current
64074** transaction is rolled back. This is different to calling
64075** sqlite3PagerRollback() because this function does not terminate
64076** the transaction or unlock the database, it just restores the
64077** contents of the database to its original state.
64078**
64079** In any case, all savepoints with an index greater than iSavepoint
64080** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
64081** then savepoint iSavepoint is also destroyed.
64082**
64083** This function may return SQLITE_NOMEM if a memory allocation fails,
64084** or an IO error code if an IO error occurs while rolling back a
64085** savepoint. If no errors occur, SQLITE_OK is returned.
64086*/
64087SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
64088  int rc = pPager->errCode;
64089
64090#ifdef SQLITE_ENABLE_ZIPVFS
64091  if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
64092#endif
64093
64094  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
64095  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
64096
64097  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
64098    int ii;            /* Iterator variable */
64099    int nNew;          /* Number of remaining savepoints after this op. */
64100
64101    /* Figure out how many savepoints will still be active after this
64102    ** operation. Store this value in nNew. Then free resources associated
64103    ** with any savepoints that are destroyed by this operation.
64104    */
64105    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
64106    for(ii=nNew; ii<pPager->nSavepoint; ii++){
64107      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
64108    }
64109    pPager->nSavepoint = nNew;
64110
64111    /* Truncate the sub-journal so that it only includes the parts
64112    ** that are still in use. */
64113    if( op==SAVEPOINT_RELEASE ){
64114      PagerSavepoint *pRel = &pPager->aSavepoint[nNew];
64115      if( pRel->bTruncateOnRelease && isOpen(pPager->sjfd) ){
64116        /* Only truncate if it is an in-memory sub-journal. */
64117        if( sqlite3JournalIsInMemory(pPager->sjfd) ){
64118          i64 sz = (pPager->pageSize+4)*(i64)pRel->iSubRec;
64119          rc = sqlite3OsTruncate(pPager->sjfd, sz);
64120          assert( rc==SQLITE_OK );
64121        }
64122        pPager->nSubRec = pRel->iSubRec;
64123      }
64124    }
64125    /* Else this is a rollback operation, playback the specified savepoint.
64126    ** If this is a temp-file, it is possible that the journal file has
64127    ** not yet been opened. In this case there have been no changes to
64128    ** the database file, so the playback operation can be skipped.
64129    */
64130    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
64131      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
64132      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
64133      assert(rc!=SQLITE_DONE);
64134    }
64135
64136#ifdef SQLITE_ENABLE_ZIPVFS
64137    /* If the cache has been modified but the savepoint cannot be rolled
64138    ** back journal_mode=off, put the pager in the error state. This way,
64139    ** if the VFS used by this pager includes ZipVFS, the entire transaction
64140    ** can be rolled back at the ZipVFS level.  */
64141    else if(
64142        pPager->journalMode==PAGER_JOURNALMODE_OFF
64143     && pPager->eState>=PAGER_WRITER_CACHEMOD
64144    ){
64145      pPager->errCode = SQLITE_ABORT;
64146      pPager->eState = PAGER_ERROR;
64147      setGetterMethod(pPager);
64148    }
64149#endif
64150  }
64151
64152  return rc;
64153}
64154
64155/*
64156** Return the full pathname of the database file.
64157**
64158** Except, if the pager is in-memory only, then return an empty string if
64159** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
64160** used to report the filename to the user, for compatibility with legacy
64161** behavior.  But when the Btree needs to know the filename for matching to
64162** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
64163** participate in shared-cache.
64164**
64165** The return value to this routine is always safe to use with
64166** sqlite3_uri_parameter() and sqlite3_filename_database() and friends.
64167*/
64168SQLITE_PRIVATE const char *sqlite3PagerFilename(const Pager *pPager, int nullIfMemDb){
64169  static const char zFake[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
64170  if( nullIfMemDb && (pPager->memDb || sqlite3IsMemdb(pPager->pVfs)) ){
64171    return &zFake[4];
64172  }else{
64173    return pPager->zFilename;
64174  }
64175}
64176
64177/*
64178** Return the VFS structure for the pager.
64179*/
64180SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
64181  return pPager->pVfs;
64182}
64183
64184/*
64185** Return the file handle for the database file associated
64186** with the pager.  This might return NULL if the file has
64187** not yet been opened.
64188*/
64189SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
64190  return pPager->fd;
64191}
64192
64193/*
64194** Return the file handle for the journal file (if it exists).
64195** This will be either the rollback journal or the WAL file.
64196*/
64197SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
64198#ifdef SQLITE_OMIT_WAL
64199  return pPager->jfd;
64200#else
64201  return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
64202#endif
64203}
64204
64205/*
64206** Return the full pathname of the journal file.
64207*/
64208SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
64209  return pPager->zJournal;
64210}
64211
64212#ifndef SQLITE_OMIT_AUTOVACUUM
64213/*
64214** Move the page pPg to location pgno in the file.
64215**
64216** There must be no references to the page previously located at
64217** pgno (which we call pPgOld) though that page is allowed to be
64218** in cache.  If the page previously located at pgno is not already
64219** in the rollback journal, it is not put there by by this routine.
64220**
64221** References to the page pPg remain valid. Updating any
64222** meta-data associated with pPg (i.e. data stored in the nExtra bytes
64223** allocated along with the page) is the responsibility of the caller.
64224**
64225** A transaction must be active when this routine is called. It used to be
64226** required that a statement transaction was not active, but this restriction
64227** has been removed (CREATE INDEX needs to move a page when a statement
64228** transaction is active).
64229**
64230** If the fourth argument, isCommit, is non-zero, then this page is being
64231** moved as part of a database reorganization just before the transaction
64232** is being committed. In this case, it is guaranteed that the database page
64233** pPg refers to will not be written to again within this transaction.
64234**
64235** This function may return SQLITE_NOMEM or an IO error code if an error
64236** occurs. Otherwise, it returns SQLITE_OK.
64237*/
64238SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
64239  PgHdr *pPgOld;               /* The page being overwritten. */
64240  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
64241  int rc;                      /* Return code */
64242  Pgno origPgno;               /* The original page number */
64243
64244  assert( pPg->nRef>0 );
64245  assert( pPager->eState==PAGER_WRITER_CACHEMOD
64246       || pPager->eState==PAGER_WRITER_DBMOD
64247  );
64248  assert( assert_pager_state(pPager) );
64249
64250  /* In order to be able to rollback, an in-memory database must journal
64251  ** the page we are moving from.
64252  */
64253  assert( pPager->tempFile || !MEMDB );
64254  if( pPager->tempFile ){
64255    rc = sqlite3PagerWrite(pPg);
64256    if( rc ) return rc;
64257  }
64258
64259  /* If the page being moved is dirty and has not been saved by the latest
64260  ** savepoint, then save the current contents of the page into the
64261  ** sub-journal now. This is required to handle the following scenario:
64262  **
64263  **   BEGIN;
64264  **     <journal page X, then modify it in memory>
64265  **     SAVEPOINT one;
64266  **       <Move page X to location Y>
64267  **     ROLLBACK TO one;
64268  **
64269  ** If page X were not written to the sub-journal here, it would not
64270  ** be possible to restore its contents when the "ROLLBACK TO one"
64271  ** statement were is processed.
64272  **
64273  ** subjournalPage() may need to allocate space to store pPg->pgno into
64274  ** one or more savepoint bitvecs. This is the reason this function
64275  ** may return SQLITE_NOMEM.
64276  */
64277  if( (pPg->flags & PGHDR_DIRTY)!=0
64278   && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
64279  ){
64280    return rc;
64281  }
64282
64283  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
64284      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
64285  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
64286
64287  /* If the journal needs to be sync()ed before page pPg->pgno can
64288  ** be written to, store pPg->pgno in local variable needSyncPgno.
64289  **
64290  ** If the isCommit flag is set, there is no need to remember that
64291  ** the journal needs to be sync()ed before database page pPg->pgno
64292  ** can be written to. The caller has already promised not to write to it.
64293  */
64294  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
64295    needSyncPgno = pPg->pgno;
64296    assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
64297            pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
64298    assert( pPg->flags&PGHDR_DIRTY );
64299  }
64300
64301  /* If the cache contains a page with page-number pgno, remove it
64302  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
64303  ** page pgno before the 'move' operation, it needs to be retained
64304  ** for the page moved there.
64305  */
64306  pPg->flags &= ~PGHDR_NEED_SYNC;
64307  pPgOld = sqlite3PagerLookup(pPager, pgno);
64308  assert( !pPgOld || pPgOld->nRef==1 || CORRUPT_DB );
64309  if( pPgOld ){
64310    if( NEVER(pPgOld->nRef>1) ){
64311      sqlite3PagerUnrefNotNull(pPgOld);
64312      return SQLITE_CORRUPT_BKPT;
64313    }
64314    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
64315    if( pPager->tempFile ){
64316      /* Do not discard pages from an in-memory database since we might
64317      ** need to rollback later.  Just move the page out of the way. */
64318      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
64319    }else{
64320      sqlite3PcacheDrop(pPgOld);
64321    }
64322  }
64323
64324  origPgno = pPg->pgno;
64325  sqlite3PcacheMove(pPg, pgno);
64326  sqlite3PcacheMakeDirty(pPg);
64327
64328  /* For an in-memory database, make sure the original page continues
64329  ** to exist, in case the transaction needs to roll back.  Use pPgOld
64330  ** as the original page since it has already been allocated.
64331  */
64332  if( pPager->tempFile && pPgOld ){
64333    sqlite3PcacheMove(pPgOld, origPgno);
64334    sqlite3PagerUnrefNotNull(pPgOld);
64335  }
64336
64337  if( needSyncPgno ){
64338    /* If needSyncPgno is non-zero, then the journal file needs to be
64339    ** sync()ed before any data is written to database file page needSyncPgno.
64340    ** Currently, no such page exists in the page-cache and the
64341    ** "is journaled" bitvec flag has been set. This needs to be remedied by
64342    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
64343    ** flag.
64344    **
64345    ** If the attempt to load the page into the page-cache fails, (due
64346    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
64347    ** array. Otherwise, if the page is loaded and written again in
64348    ** this transaction, it may be written to the database file before
64349    ** it is synced into the journal file. This way, it may end up in
64350    ** the journal file twice, but that is not a problem.
64351    */
64352    PgHdr *pPgHdr;
64353    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
64354    if( rc!=SQLITE_OK ){
64355      if( needSyncPgno<=pPager->dbOrigSize ){
64356        assert( pPager->pTmpSpace!=0 );
64357        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
64358      }
64359      return rc;
64360    }
64361    pPgHdr->flags |= PGHDR_NEED_SYNC;
64362    sqlite3PcacheMakeDirty(pPgHdr);
64363    sqlite3PagerUnrefNotNull(pPgHdr);
64364  }
64365
64366  return SQLITE_OK;
64367}
64368#endif
64369
64370/*
64371** The page handle passed as the first argument refers to a dirty page
64372** with a page number other than iNew. This function changes the page's
64373** page number to iNew and sets the value of the PgHdr.flags field to
64374** the value passed as the third parameter.
64375*/
64376SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
64377  assert( pPg->pgno!=iNew );
64378  pPg->flags = flags;
64379  sqlite3PcacheMove(pPg, iNew);
64380}
64381
64382/*
64383** Return a pointer to the data for the specified page.
64384*/
64385SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
64386  assert( pPg->nRef>0 || pPg->pPager->memDb );
64387  return pPg->pData;
64388}
64389
64390/*
64391** Return a pointer to the Pager.nExtra bytes of "extra" space
64392** allocated along with the specified page.
64393*/
64394SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
64395  return pPg->pExtra;
64396}
64397
64398/*
64399** Get/set the locking-mode for this pager. Parameter eMode must be one
64400** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
64401** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
64402** the locking-mode is set to the value specified.
64403**
64404** The returned value is either PAGER_LOCKINGMODE_NORMAL or
64405** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
64406** locking-mode.
64407*/
64408SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
64409  assert( eMode==PAGER_LOCKINGMODE_QUERY
64410            || eMode==PAGER_LOCKINGMODE_NORMAL
64411            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
64412  assert( PAGER_LOCKINGMODE_QUERY<0 );
64413  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
64414  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
64415  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
64416    pPager->exclusiveMode = (u8)eMode;
64417  }
64418  return (int)pPager->exclusiveMode;
64419}
64420
64421/*
64422** Set the journal-mode for this pager. Parameter eMode must be one of:
64423**
64424**    PAGER_JOURNALMODE_DELETE
64425**    PAGER_JOURNALMODE_TRUNCATE
64426**    PAGER_JOURNALMODE_PERSIST
64427**    PAGER_JOURNALMODE_OFF
64428**    PAGER_JOURNALMODE_MEMORY
64429**    PAGER_JOURNALMODE_WAL
64430**
64431** The journalmode is set to the value specified if the change is allowed.
64432** The change may be disallowed for the following reasons:
64433**
64434**   *  An in-memory database can only have its journal_mode set to _OFF
64435**      or _MEMORY.
64436**
64437**   *  Temporary databases cannot have _WAL journalmode.
64438**
64439** The returned indicate the current (possibly updated) journal-mode.
64440*/
64441SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
64442  u8 eOld = pPager->journalMode;    /* Prior journalmode */
64443
64444  /* The eMode parameter is always valid */
64445  assert(      eMode==PAGER_JOURNALMODE_DELETE    /* 0 */
64446            || eMode==PAGER_JOURNALMODE_PERSIST   /* 1 */
64447            || eMode==PAGER_JOURNALMODE_OFF       /* 2 */
64448            || eMode==PAGER_JOURNALMODE_TRUNCATE  /* 3 */
64449            || eMode==PAGER_JOURNALMODE_MEMORY    /* 4 */
64450            || eMode==PAGER_JOURNALMODE_WAL       /* 5 */ );
64451
64452  /* This routine is only called from the OP_JournalMode opcode, and
64453  ** the logic there will never allow a temporary file to be changed
64454  ** to WAL mode.
64455  */
64456  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
64457
64458  /* Do allow the journalmode of an in-memory database to be set to
64459  ** anything other than MEMORY or OFF
64460  */
64461  if( MEMDB ){
64462    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
64463    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
64464      eMode = eOld;
64465    }
64466  }
64467
64468  if( eMode!=eOld ){
64469
64470    /* Change the journal mode. */
64471    assert( pPager->eState!=PAGER_ERROR );
64472    pPager->journalMode = (u8)eMode;
64473
64474    /* When transitioning from TRUNCATE or PERSIST to any other journal
64475    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
64476    ** delete the journal file.
64477    */
64478    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
64479    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
64480    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
64481    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
64482    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
64483    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
64484
64485    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
64486    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
64487      /* In this case we would like to delete the journal file. If it is
64488      ** not possible, then that is not a problem. Deleting the journal file
64489      ** here is an optimization only.
64490      **
64491      ** Before deleting the journal file, obtain a RESERVED lock on the
64492      ** database file. This ensures that the journal file is not deleted
64493      ** while it is in use by some other client.
64494      */
64495      sqlite3OsClose(pPager->jfd);
64496      if( pPager->eLock>=RESERVED_LOCK ){
64497        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
64498      }else{
64499        int rc = SQLITE_OK;
64500        int state = pPager->eState;
64501        assert( state==PAGER_OPEN || state==PAGER_READER );
64502        if( state==PAGER_OPEN ){
64503          rc = sqlite3PagerSharedLock(pPager);
64504        }
64505        if( pPager->eState==PAGER_READER ){
64506          assert( rc==SQLITE_OK );
64507          rc = pagerLockDb(pPager, RESERVED_LOCK);
64508        }
64509        if( rc==SQLITE_OK ){
64510          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
64511        }
64512        if( rc==SQLITE_OK && state==PAGER_READER ){
64513          pagerUnlockDb(pPager, SHARED_LOCK);
64514        }else if( state==PAGER_OPEN ){
64515          pager_unlock(pPager);
64516        }
64517        assert( state==pPager->eState );
64518      }
64519    }else if( eMode==PAGER_JOURNALMODE_OFF || eMode==PAGER_JOURNALMODE_MEMORY ){
64520      sqlite3OsClose(pPager->jfd);
64521    }
64522  }
64523
64524  /* Return the new journal mode */
64525  return (int)pPager->journalMode;
64526}
64527
64528/*
64529** Return the current journal mode.
64530*/
64531SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
64532  return (int)pPager->journalMode;
64533}
64534
64535/*
64536** Return TRUE if the pager is in a state where it is OK to change the
64537** journalmode.  Journalmode changes can only happen when the database
64538** is unmodified.
64539*/
64540SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
64541  assert( assert_pager_state(pPager) );
64542  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
64543  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
64544  return 1;
64545}
64546
64547/*
64548** Get/set the size-limit used for persistent journal files.
64549**
64550** Setting the size limit to -1 means no limit is enforced.
64551** An attempt to set a limit smaller than -1 is a no-op.
64552*/
64553SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
64554  if( iLimit>=-1 ){
64555    pPager->journalSizeLimit = iLimit;
64556    sqlite3WalLimit(pPager->pWal, iLimit);
64557  }
64558  return pPager->journalSizeLimit;
64559}
64560
64561/*
64562** Return a pointer to the pPager->pBackup variable. The backup module
64563** in backup.c maintains the content of this variable. This module
64564** uses it opaquely as an argument to sqlite3BackupRestart() and
64565** sqlite3BackupUpdate() only.
64566*/
64567SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
64568  return &pPager->pBackup;
64569}
64570
64571#ifndef SQLITE_OMIT_VACUUM
64572/*
64573** Unless this is an in-memory or temporary database, clear the pager cache.
64574*/
64575SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
64576  assert( MEMDB==0 || pPager->tempFile );
64577  if( pPager->tempFile==0 ) pager_reset(pPager);
64578}
64579#endif
64580
64581
64582#ifndef SQLITE_OMIT_WAL
64583/*
64584** This function is called when the user invokes "PRAGMA wal_checkpoint",
64585** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
64586** or wal_blocking_checkpoint() API functions.
64587**
64588** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
64589*/
64590SQLITE_PRIVATE int sqlite3PagerCheckpoint(
64591  Pager *pPager,                  /* Checkpoint on this pager */
64592  sqlite3 *db,                    /* Db handle used to check for interrupts */
64593  int eMode,                      /* Type of checkpoint */
64594  int *pnLog,                     /* OUT: Final number of frames in log */
64595  int *pnCkpt                     /* OUT: Final number of checkpointed frames */
64596){
64597  int rc = SQLITE_OK;
64598  if( pPager->pWal==0 && pPager->journalMode==PAGER_JOURNALMODE_WAL ){
64599    /* This only happens when a database file is zero bytes in size opened and
64600    ** then "PRAGMA journal_mode=WAL" is run and then sqlite3_wal_checkpoint()
64601    ** is invoked without any intervening transactions.  We need to start
64602    ** a transaction to initialize pWal.  The PRAGMA table_list statement is
64603    ** used for this since it starts transactions on every database file,
64604    ** including all ATTACHed databases.  This seems expensive for a single
64605    ** sqlite3_wal_checkpoint() call, but it happens very rarely.
64606    ** https://sqlite.org/forum/forumpost/fd0f19d229156939
64607    */
64608    sqlite3_exec(db, "PRAGMA table_list",0,0,0);
64609  }
64610  if( pPager->pWal ){
64611    rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
64612        (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
64613        pPager->pBusyHandlerArg,
64614        pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
64615        pnLog, pnCkpt
64616    );
64617  }
64618  return rc;
64619}
64620
64621SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
64622  return sqlite3WalCallback(pPager->pWal);
64623}
64624
64625/*
64626** Return true if the underlying VFS for the given pager supports the
64627** primitives necessary for write-ahead logging.
64628*/
64629SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
64630  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
64631  if( pPager->noLock ) return 0;
64632  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
64633}
64634
64635/*
64636** Attempt to take an exclusive lock on the database file. If a PENDING lock
64637** is obtained instead, immediately release it.
64638*/
64639static int pagerExclusiveLock(Pager *pPager){
64640  int rc;                         /* Return code */
64641  u8 eOrigLock;                   /* Original lock */
64642
64643  assert( pPager->eLock>=SHARED_LOCK );
64644  eOrigLock = pPager->eLock;
64645  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
64646  if( rc!=SQLITE_OK ){
64647    /* If the attempt to grab the exclusive lock failed, release the
64648    ** pending lock that may have been obtained instead.  */
64649    pagerUnlockDb(pPager, eOrigLock);
64650  }
64651
64652  return rc;
64653}
64654
64655/*
64656** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
64657** exclusive-locking mode when this function is called, take an EXCLUSIVE
64658** lock on the database file and use heap-memory to store the wal-index
64659** in. Otherwise, use the normal shared-memory.
64660*/
64661static int pagerOpenWal(Pager *pPager){
64662  int rc = SQLITE_OK;
64663
64664  assert( pPager->pWal==0 && pPager->tempFile==0 );
64665  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
64666
64667  /* If the pager is already in exclusive-mode, the WAL module will use
64668  ** heap-memory for the wal-index instead of the VFS shared-memory
64669  ** implementation. Take the exclusive lock now, before opening the WAL
64670  ** file, to make sure this is safe.
64671  */
64672  if( pPager->exclusiveMode ){
64673    rc = pagerExclusiveLock(pPager);
64674  }
64675
64676  /* Open the connection to the log file. If this operation fails,
64677  ** (e.g. due to malloc() failure), return an error code.
64678  */
64679  if( rc==SQLITE_OK ){
64680    rc = sqlite3WalOpen(pPager->pVfs,
64681        pPager->fd, pPager->zWal, pPager->exclusiveMode,
64682        pPager->journalSizeLimit, &pPager->pWal
64683    );
64684  }
64685  pagerFixMaplimit(pPager);
64686
64687  return rc;
64688}
64689
64690
64691/*
64692** The caller must be holding a SHARED lock on the database file to call
64693** this function.
64694**
64695** If the pager passed as the first argument is open on a real database
64696** file (not a temp file or an in-memory database), and the WAL file
64697** is not already open, make an attempt to open it now. If successful,
64698** return SQLITE_OK. If an error occurs or the VFS used by the pager does
64699** not support the xShmXXX() methods, return an error code. *pbOpen is
64700** not modified in either case.
64701**
64702** If the pager is open on a temp-file (or in-memory database), or if
64703** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
64704** without doing anything.
64705*/
64706SQLITE_PRIVATE int sqlite3PagerOpenWal(
64707  Pager *pPager,                  /* Pager object */
64708  int *pbOpen                     /* OUT: Set to true if call is a no-op */
64709){
64710  int rc = SQLITE_OK;             /* Return code */
64711
64712  assert( assert_pager_state(pPager) );
64713  assert( pPager->eState==PAGER_OPEN   || pbOpen );
64714  assert( pPager->eState==PAGER_READER || !pbOpen );
64715  assert( pbOpen==0 || *pbOpen==0 );
64716  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
64717
64718  if( !pPager->tempFile && !pPager->pWal ){
64719    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
64720
64721    /* Close any rollback journal previously open */
64722    sqlite3OsClose(pPager->jfd);
64723
64724    rc = pagerOpenWal(pPager);
64725    if( rc==SQLITE_OK ){
64726      pPager->journalMode = PAGER_JOURNALMODE_WAL;
64727      pPager->eState = PAGER_OPEN;
64728    }
64729  }else{
64730    *pbOpen = 1;
64731  }
64732
64733  return rc;
64734}
64735
64736/*
64737** This function is called to close the connection to the log file prior
64738** to switching from WAL to rollback mode.
64739**
64740** Before closing the log file, this function attempts to take an
64741** EXCLUSIVE lock on the database file. If this cannot be obtained, an
64742** error (SQLITE_BUSY) is returned and the log connection is not closed.
64743** If successful, the EXCLUSIVE lock is not released before returning.
64744*/
64745SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
64746  int rc = SQLITE_OK;
64747
64748  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
64749
64750  /* If the log file is not already open, but does exist in the file-system,
64751  ** it may need to be checkpointed before the connection can switch to
64752  ** rollback mode. Open it now so this can happen.
64753  */
64754  if( !pPager->pWal ){
64755    int logexists = 0;
64756    rc = pagerLockDb(pPager, SHARED_LOCK);
64757    if( rc==SQLITE_OK ){
64758      rc = sqlite3OsAccess(
64759          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
64760      );
64761    }
64762    if( rc==SQLITE_OK && logexists ){
64763      rc = pagerOpenWal(pPager);
64764    }
64765  }
64766
64767  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
64768  ** the database file, the log and log-summary files will be deleted.
64769  */
64770  if( rc==SQLITE_OK && pPager->pWal ){
64771    rc = pagerExclusiveLock(pPager);
64772    if( rc==SQLITE_OK ){
64773      rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
64774                           pPager->pageSize, (u8*)pPager->pTmpSpace);
64775      pPager->pWal = 0;
64776      pagerFixMaplimit(pPager);
64777      if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
64778    }
64779  }
64780  return rc;
64781}
64782
64783#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
64784/*
64785** If pager pPager is a wal-mode database not in exclusive locking mode,
64786** invoke the sqlite3WalWriteLock() function on the associated Wal object
64787** with the same db and bLock parameters as were passed to this function.
64788** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
64789*/
64790SQLITE_PRIVATE int sqlite3PagerWalWriteLock(Pager *pPager, int bLock){
64791  int rc = SQLITE_OK;
64792  if( pagerUseWal(pPager) && pPager->exclusiveMode==0 ){
64793    rc = sqlite3WalWriteLock(pPager->pWal, bLock);
64794  }
64795  return rc;
64796}
64797
64798/*
64799** Set the database handle used by the wal layer to determine if
64800** blocking locks are required.
64801*/
64802SQLITE_PRIVATE void sqlite3PagerWalDb(Pager *pPager, sqlite3 *db){
64803  if( pagerUseWal(pPager) ){
64804    sqlite3WalDb(pPager->pWal, db);
64805  }
64806}
64807#endif
64808
64809#ifdef SQLITE_ENABLE_SNAPSHOT
64810/*
64811** If this is a WAL database, obtain a snapshot handle for the snapshot
64812** currently open. Otherwise, return an error.
64813*/
64814SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
64815  int rc = SQLITE_ERROR;
64816  if( pPager->pWal ){
64817    rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
64818  }
64819  return rc;
64820}
64821
64822/*
64823** If this is a WAL database, store a pointer to pSnapshot. Next time a
64824** read transaction is opened, attempt to read from the snapshot it
64825** identifies. If this is not a WAL database, return an error.
64826*/
64827SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(
64828  Pager *pPager,
64829  sqlite3_snapshot *pSnapshot
64830){
64831  int rc = SQLITE_OK;
64832  if( pPager->pWal ){
64833    sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
64834  }else{
64835    rc = SQLITE_ERROR;
64836  }
64837  return rc;
64838}
64839
64840/*
64841** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
64842** is not a WAL database, return an error.
64843*/
64844SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
64845  int rc;
64846  if( pPager->pWal ){
64847    rc = sqlite3WalSnapshotRecover(pPager->pWal);
64848  }else{
64849    rc = SQLITE_ERROR;
64850  }
64851  return rc;
64852}
64853
64854/*
64855** The caller currently has a read transaction open on the database.
64856** If this is not a WAL database, SQLITE_ERROR is returned. Otherwise,
64857** this function takes a SHARED lock on the CHECKPOINTER slot and then
64858** checks if the snapshot passed as the second argument is still
64859** available. If so, SQLITE_OK is returned.
64860**
64861** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
64862** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
64863** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
64864** lock is released before returning.
64865*/
64866SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot){
64867  int rc;
64868  if( pPager->pWal ){
64869    rc = sqlite3WalSnapshotCheck(pPager->pWal, pSnapshot);
64870  }else{
64871    rc = SQLITE_ERROR;
64872  }
64873  return rc;
64874}
64875
64876/*
64877** Release a lock obtained by an earlier successful call to
64878** sqlite3PagerSnapshotCheck().
64879*/
64880SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager){
64881  assert( pPager->pWal );
64882  sqlite3WalSnapshotUnlock(pPager->pWal);
64883}
64884
64885#endif /* SQLITE_ENABLE_SNAPSHOT */
64886#endif /* !SQLITE_OMIT_WAL */
64887
64888#ifdef SQLITE_ENABLE_ZIPVFS
64889/*
64890** A read-lock must be held on the pager when this function is called. If
64891** the pager is in WAL mode and the WAL file currently contains one or more
64892** frames, return the size in bytes of the page images stored within the
64893** WAL frames. Otherwise, if this is not a WAL database or the WAL file
64894** is empty, return 0.
64895*/
64896SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
64897  assert( pPager->eState>=PAGER_READER );
64898  return sqlite3WalFramesize(pPager->pWal);
64899}
64900#endif
64901
64902#if defined(SQLITE_USE_SEH) && !defined(SQLITE_OMIT_WAL)
64903SQLITE_PRIVATE int sqlite3PagerWalSystemErrno(Pager *pPager){
64904  return sqlite3WalSystemErrno(pPager->pWal);
64905}
64906#endif
64907
64908#endif /* SQLITE_OMIT_DISKIO */
64909
64910/************** End of pager.c ***********************************************/
64911/************** Begin file wal.c *********************************************/
64912/*
64913** 2010 February 1
64914**
64915** The author disclaims copyright to this source code.  In place of
64916** a legal notice, here is a blessing:
64917**
64918**    May you do good and not evil.
64919**    May you find forgiveness for yourself and forgive others.
64920**    May you share freely, never taking more than you give.
64921**
64922*************************************************************************
64923**
64924** This file contains the implementation of a write-ahead log (WAL) used in
64925** "journal_mode=WAL" mode.
64926**
64927** WRITE-AHEAD LOG (WAL) FILE FORMAT
64928**
64929** A WAL file consists of a header followed by zero or more "frames".
64930** Each frame records the revised content of a single page from the
64931** database file.  All changes to the database are recorded by writing
64932** frames into the WAL.  Transactions commit when a frame is written that
64933** contains a commit marker.  A single WAL can and usually does record
64934** multiple transactions.  Periodically, the content of the WAL is
64935** transferred back into the database file in an operation called a
64936** "checkpoint".
64937**
64938** A single WAL file can be used multiple times.  In other words, the
64939** WAL can fill up with frames and then be checkpointed and then new
64940** frames can overwrite the old ones.  A WAL always grows from beginning
64941** toward the end.  Checksums and counters attached to each frame are
64942** used to determine which frames within the WAL are valid and which
64943** are leftovers from prior checkpoints.
64944**
64945** The WAL header is 32 bytes in size and consists of the following eight
64946** big-endian 32-bit unsigned integer values:
64947**
64948**     0: Magic number.  0x377f0682 or 0x377f0683
64949**     4: File format version.  Currently 3007000
64950**     8: Database page size.  Example: 1024
64951**    12: Checkpoint sequence number
64952**    16: Salt-1, random integer incremented with each checkpoint
64953**    20: Salt-2, a different random integer changing with each ckpt
64954**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
64955**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
64956**
64957** Immediately following the wal-header are zero or more frames. Each
64958** frame consists of a 24-byte frame-header followed by a <page-size> bytes
64959** of page data. The frame-header is six big-endian 32-bit unsigned
64960** integer values, as follows:
64961**
64962**     0: Page number.
64963**     4: For commit records, the size of the database image in pages
64964**        after the commit. For all other records, zero.
64965**     8: Salt-1 (copied from the header)
64966**    12: Salt-2 (copied from the header)
64967**    16: Checksum-1.
64968**    20: Checksum-2.
64969**
64970** A frame is considered valid if and only if the following conditions are
64971** true:
64972**
64973**    (1) The salt-1 and salt-2 values in the frame-header match
64974**        salt values in the wal-header
64975**
64976**    (2) The checksum values in the final 8 bytes of the frame-header
64977**        exactly match the checksum computed consecutively on the
64978**        WAL header and the first 8 bytes and the content of all frames
64979**        up to and including the current frame.
64980**
64981** The checksum is computed using 32-bit big-endian integers if the
64982** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
64983** is computed using little-endian if the magic number is 0x377f0682.
64984** The checksum values are always stored in the frame header in a
64985** big-endian format regardless of which byte order is used to compute
64986** the checksum.  The checksum is computed by interpreting the input as
64987** an even number of unsigned 32-bit integers: x[0] through x[N].  The
64988** algorithm used for the checksum is as follows:
64989**
64990**   for i from 0 to n-1 step 2:
64991**     s0 += x[i] + s1;
64992**     s1 += x[i+1] + s0;
64993**   endfor
64994**
64995** Note that s0 and s1 are both weighted checksums using fibonacci weights
64996** in reverse order (the largest fibonacci weight occurs on the first element
64997** of the sequence being summed.)  The s1 value spans all 32-bit
64998** terms of the sequence whereas s0 omits the final term.
64999**
65000** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
65001** WAL is transferred into the database, then the database is VFS.xSync-ed.
65002** The VFS.xSync operations serve as write barriers - all writes launched
65003** before the xSync must complete before any write that launches after the
65004** xSync begins.
65005**
65006** After each checkpoint, the salt-1 value is incremented and the salt-2
65007** value is randomized.  This prevents old and new frames in the WAL from
65008** being considered valid at the same time and being checkpointing together
65009** following a crash.
65010**
65011** READER ALGORITHM
65012**
65013** To read a page from the database (call it page number P), a reader
65014** first checks the WAL to see if it contains page P.  If so, then the
65015** last valid instance of page P that is a followed by a commit frame
65016** or is a commit frame itself becomes the value read.  If the WAL
65017** contains no copies of page P that are valid and which are a commit
65018** frame or are followed by a commit frame, then page P is read from
65019** the database file.
65020**
65021** To start a read transaction, the reader records the index of the last
65022** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
65023** for all subsequent read operations.  New transactions can be appended
65024** to the WAL, but as long as the reader uses its original mxFrame value
65025** and ignores the newly appended content, it will see a consistent snapshot
65026** of the database from a single point in time.  This technique allows
65027** multiple concurrent readers to view different versions of the database
65028** content simultaneously.
65029**
65030** The reader algorithm in the previous paragraphs works correctly, but
65031** because frames for page P can appear anywhere within the WAL, the
65032** reader has to scan the entire WAL looking for page P frames.  If the
65033** WAL is large (multiple megabytes is typical) that scan can be slow,
65034** and read performance suffers.  To overcome this problem, a separate
65035** data structure called the wal-index is maintained to expedite the
65036** search for frames of a particular page.
65037**
65038** WAL-INDEX FORMAT
65039**
65040** Conceptually, the wal-index is shared memory, though VFS implementations
65041** might choose to implement the wal-index using a mmapped file.  Because
65042** the wal-index is shared memory, SQLite does not support journal_mode=WAL
65043** on a network filesystem.  All users of the database must be able to
65044** share memory.
65045**
65046** In the default unix and windows implementation, the wal-index is a mmapped
65047** file whose name is the database name with a "-shm" suffix added.  For that
65048** reason, the wal-index is sometimes called the "shm" file.
65049**
65050** The wal-index is transient.  After a crash, the wal-index can (and should
65051** be) reconstructed from the original WAL file.  In fact, the VFS is required
65052** to either truncate or zero the header of the wal-index when the last
65053** connection to it closes.  Because the wal-index is transient, it can
65054** use an architecture-specific format; it does not have to be cross-platform.
65055** Hence, unlike the database and WAL file formats which store all values
65056** as big endian, the wal-index can store multi-byte values in the native
65057** byte order of the host computer.
65058**
65059** The purpose of the wal-index is to answer this question quickly:  Given
65060** a page number P and a maximum frame index M, return the index of the
65061** last frame in the wal before frame M for page P in the WAL, or return
65062** NULL if there are no frames for page P in the WAL prior to M.
65063**
65064** The wal-index consists of a header region, followed by an one or
65065** more index blocks.
65066**
65067** The wal-index header contains the total number of frames within the WAL
65068** in the mxFrame field.
65069**
65070** Each index block except for the first contains information on
65071** HASHTABLE_NPAGE frames. The first index block contains information on
65072** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
65073** HASHTABLE_NPAGE are selected so that together the wal-index header and
65074** first index block are the same size as all other index blocks in the
65075** wal-index.  The values are:
65076**
65077**   HASHTABLE_NPAGE      4096
65078**   HASHTABLE_NPAGE_ONE  4062
65079**
65080** Each index block contains two sections, a page-mapping that contains the
65081** database page number associated with each wal frame, and a hash-table
65082** that allows readers to query an index block for a specific page number.
65083** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
65084** for the first index block) 32-bit page numbers. The first entry in the
65085** first index-block contains the database page number corresponding to the
65086** first frame in the WAL file. The first entry in the second index block
65087** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
65088** the log, and so on.
65089**
65090** The last index block in a wal-index usually contains less than the full
65091** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
65092** depending on the contents of the WAL file. This does not change the
65093** allocated size of the page-mapping array - the page-mapping array merely
65094** contains unused entries.
65095**
65096** Even without using the hash table, the last frame for page P
65097** can be found by scanning the page-mapping sections of each index block
65098** starting with the last index block and moving toward the first, and
65099** within each index block, starting at the end and moving toward the
65100** beginning.  The first entry that equals P corresponds to the frame
65101** holding the content for that page.
65102**
65103** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
65104** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
65105** hash table for each page number in the mapping section, so the hash
65106** table is never more than half full.  The expected number of collisions
65107** prior to finding a match is 1.  Each entry of the hash table is an
65108** 1-based index of an entry in the mapping section of the same
65109** index block.   Let K be the 1-based index of the largest entry in
65110** the mapping section.  (For index blocks other than the last, K will
65111** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
65112** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
65113** contain a value of 0.
65114**
65115** To look for page P in the hash table, first compute a hash iKey on
65116** P as follows:
65117**
65118**      iKey = (P * 383) % HASHTABLE_NSLOT
65119**
65120** Then start scanning entries of the hash table, starting with iKey
65121** (wrapping around to the beginning when the end of the hash table is
65122** reached) until an unused hash slot is found. Let the first unused slot
65123** be at index iUnused.  (iUnused might be less than iKey if there was
65124** wrap-around.) Because the hash table is never more than half full,
65125** the search is guaranteed to eventually hit an unused entry.  Let
65126** iMax be the value between iKey and iUnused, closest to iUnused,
65127** where aHash[iMax]==P.  If there is no iMax entry (if there exists
65128** no hash slot such that aHash[i]==p) then page P is not in the
65129** current index block.  Otherwise the iMax-th mapping entry of the
65130** current index block corresponds to the last entry that references
65131** page P.
65132**
65133** A hash search begins with the last index block and moves toward the
65134** first index block, looking for entries corresponding to page P.  On
65135** average, only two or three slots in each index block need to be
65136** examined in order to either find the last entry for page P, or to
65137** establish that no such entry exists in the block.  Each index block
65138** holds over 4000 entries.  So two or three index blocks are sufficient
65139** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
65140** comparisons (on average) suffice to either locate a frame in the
65141** WAL or to establish that the frame does not exist in the WAL.  This
65142** is much faster than scanning the entire 10MB WAL.
65143**
65144** Note that entries are added in order of increasing K.  Hence, one
65145** reader might be using some value K0 and a second reader that started
65146** at a later time (after additional transactions were added to the WAL
65147** and to the wal-index) might be using a different value K1, where K1>K0.
65148** Both readers can use the same hash table and mapping section to get
65149** the correct result.  There may be entries in the hash table with
65150** K>K0 but to the first reader, those entries will appear to be unused
65151** slots in the hash table and so the first reader will get an answer as
65152** if no values greater than K0 had ever been inserted into the hash table
65153** in the first place - which is what reader one wants.  Meanwhile, the
65154** second reader using K1 will see additional values that were inserted
65155** later, which is exactly what reader two wants.
65156**
65157** When a rollback occurs, the value of K is decreased. Hash table entries
65158** that correspond to frames greater than the new K value are removed
65159** from the hash table at this point.
65160*/
65161#ifndef SQLITE_OMIT_WAL
65162
65163/* #include "wal.h" */
65164
65165/*
65166** Trace output macros
65167*/
65168#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
65169SQLITE_PRIVATE int sqlite3WalTrace = 0;
65170# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
65171#else
65172# define WALTRACE(X)
65173#endif
65174
65175/*
65176** The maximum (and only) versions of the wal and wal-index formats
65177** that may be interpreted by this version of SQLite.
65178**
65179** If a client begins recovering a WAL file and finds that (a) the checksum
65180** values in the wal-header are correct and (b) the version field is not
65181** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
65182**
65183** Similarly, if a client successfully reads a wal-index header (i.e. the
65184** checksum test is successful) and finds that the version field is not
65185** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
65186** returns SQLITE_CANTOPEN.
65187*/
65188#define WAL_MAX_VERSION      3007000
65189#define WALINDEX_MAX_VERSION 3007000
65190
65191/*
65192** Index numbers for various locking bytes.   WAL_NREADER is the number
65193** of available reader locks and should be at least 3.  The default
65194** is SQLITE_SHM_NLOCK==8 and  WAL_NREADER==5.
65195**
65196** Technically, the various VFSes are free to implement these locks however
65197** they see fit.  However, compatibility is encouraged so that VFSes can
65198** interoperate.  The standard implementation used on both unix and windows
65199** is for the index number to indicate a byte offset into the
65200** WalCkptInfo.aLock[] array in the wal-index header.  In other words, all
65201** locks are on the shm file.  The WALINDEX_LOCK_OFFSET constant (which
65202** should be 120) is the location in the shm file for the first locking
65203** byte.
65204*/
65205#define WAL_WRITE_LOCK         0
65206#define WAL_ALL_BUT_WRITE      1
65207#define WAL_CKPT_LOCK          1
65208#define WAL_RECOVER_LOCK       2
65209#define WAL_READ_LOCK(I)       (3+(I))
65210#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
65211
65212
65213/* Object declarations */
65214typedef struct WalIndexHdr WalIndexHdr;
65215typedef struct WalIterator WalIterator;
65216typedef struct WalCkptInfo WalCkptInfo;
65217
65218
65219/*
65220** The following object holds a copy of the wal-index header content.
65221**
65222** The actual header in the wal-index consists of two copies of this
65223** object followed by one instance of the WalCkptInfo object.
65224** For all versions of SQLite through 3.10.0 and probably beyond,
65225** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
65226** the total header size is 136 bytes.
65227**
65228** The szPage value can be any power of 2 between 512 and 32768, inclusive.
65229** Or it can be 1 to represent a 65536-byte page.  The latter case was
65230** added in 3.7.1 when support for 64K pages was added.
65231*/
65232struct WalIndexHdr {
65233  u32 iVersion;                   /* Wal-index version */
65234  u32 unused;                     /* Unused (padding) field */
65235  u32 iChange;                    /* Counter incremented each transaction */
65236  u8 isInit;                      /* 1 when initialized */
65237  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
65238  u16 szPage;                     /* Database page size in bytes. 1==64K */
65239  u32 mxFrame;                    /* Index of last valid frame in the WAL */
65240  u32 nPage;                      /* Size of database in pages */
65241  u32 aFrameCksum[2];             /* Checksum of last frame in log */
65242  u32 aSalt[2];                   /* Two salt values copied from WAL header */
65243  u32 aCksum[2];                  /* Checksum over all prior fields */
65244};
65245
65246/*
65247** A copy of the following object occurs in the wal-index immediately
65248** following the second copy of the WalIndexHdr.  This object stores
65249** information used by checkpoint.
65250**
65251** nBackfill is the number of frames in the WAL that have been written
65252** back into the database. (We call the act of moving content from WAL to
65253** database "backfilling".)  The nBackfill number is never greater than
65254** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
65255** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
65256** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
65257** mxFrame back to zero when the WAL is reset.
65258**
65259** nBackfillAttempted is the largest value of nBackfill that a checkpoint
65260** has attempted to achieve.  Normally nBackfill==nBackfillAtempted, however
65261** the nBackfillAttempted is set before any backfilling is done and the
65262** nBackfill is only set after all backfilling completes.  So if a checkpoint
65263** crashes, nBackfillAttempted might be larger than nBackfill.  The
65264** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
65265**
65266** The aLock[] field is a set of bytes used for locking.  These bytes should
65267** never be read or written.
65268**
65269** There is one entry in aReadMark[] for each reader lock.  If a reader
65270** holds read-lock K, then the value in aReadMark[K] is no greater than
65271** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
65272** for any aReadMark[] means that entry is unused.  aReadMark[0] is
65273** a special case; its value is never used and it exists as a place-holder
65274** to avoid having to offset aReadMark[] indexes by one.  Readers holding
65275** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
65276** directly from the database.
65277**
65278** The value of aReadMark[K] may only be changed by a thread that
65279** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
65280** aReadMark[K] cannot changed while there is a reader is using that mark
65281** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
65282**
65283** The checkpointer may only transfer frames from WAL to database where
65284** the frame numbers are less than or equal to every aReadMark[] that is
65285** in use (that is, every aReadMark[j] for which there is a corresponding
65286** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
65287** largest value and will increase an unused aReadMark[] to mxFrame if there
65288** is not already an aReadMark[] equal to mxFrame.  The exception to the
65289** previous sentence is when nBackfill equals mxFrame (meaning that everything
65290** in the WAL has been backfilled into the database) then new readers
65291** will choose aReadMark[0] which has value 0 and hence such reader will
65292** get all their all content directly from the database file and ignore
65293** the WAL.
65294**
65295** Writers normally append new frames to the end of the WAL.  However,
65296** if nBackfill equals mxFrame (meaning that all WAL content has been
65297** written back into the database) and if no readers are using the WAL
65298** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
65299** the writer will first "reset" the WAL back to the beginning and start
65300** writing new content beginning at frame 1.
65301**
65302** We assume that 32-bit loads are atomic and so no locks are needed in
65303** order to read from any aReadMark[] entries.
65304*/
65305struct WalCkptInfo {
65306  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
65307  u32 aReadMark[WAL_NREADER];     /* Reader marks */
65308  u8 aLock[SQLITE_SHM_NLOCK];     /* Reserved space for locks */
65309  u32 nBackfillAttempted;         /* WAL frames perhaps written, or maybe not */
65310  u32 notUsed0;                   /* Available for future enhancements */
65311};
65312#define READMARK_NOT_USED  0xffffffff
65313
65314/*
65315** This is a schematic view of the complete 136-byte header of the
65316** wal-index file (also known as the -shm file):
65317**
65318**      +-----------------------------+
65319**   0: | iVersion                    | \
65320**      +-----------------------------+  |
65321**   4: | (unused padding)            |  |
65322**      +-----------------------------+  |
65323**   8: | iChange                     |  |
65324**      +-------+-------+-------------+  |
65325**  12: | bInit |  bBig |   szPage    |  |
65326**      +-------+-------+-------------+  |
65327**  16: | mxFrame                     |  |  First copy of the
65328**      +-----------------------------+  |  WalIndexHdr object
65329**  20: | nPage                       |  |
65330**      +-----------------------------+  |
65331**  24: | aFrameCksum                 |  |
65332**      |                             |  |
65333**      +-----------------------------+  |
65334**  32: | aSalt                       |  |
65335**      |                             |  |
65336**      +-----------------------------+  |
65337**  40: | aCksum                      |  |
65338**      |                             | /
65339**      +-----------------------------+
65340**  48: | iVersion                    | \
65341**      +-----------------------------+  |
65342**  52: | (unused padding)            |  |
65343**      +-----------------------------+  |
65344**  56: | iChange                     |  |
65345**      +-------+-------+-------------+  |
65346**  60: | bInit |  bBig |   szPage    |  |
65347**      +-------+-------+-------------+  |  Second copy of the
65348**  64: | mxFrame                     |  |  WalIndexHdr
65349**      +-----------------------------+  |
65350**  68: | nPage                       |  |
65351**      +-----------------------------+  |
65352**  72: | aFrameCksum                 |  |
65353**      |                             |  |
65354**      +-----------------------------+  |
65355**  80: | aSalt                       |  |
65356**      |                             |  |
65357**      +-----------------------------+  |
65358**  88: | aCksum                      |  |
65359**      |                             | /
65360**      +-----------------------------+
65361**  96: | nBackfill                   |
65362**      +-----------------------------+
65363** 100: | 5 read marks                |
65364**      |                             |
65365**      |                             |
65366**      |                             |
65367**      |                             |
65368**      +-------+-------+------+------+
65369** 120: | Write | Ckpt  | Rcvr | Rd0  | \
65370**      +-------+-------+------+------+  ) 8 lock bytes
65371**      | Read1 | Read2 | Rd3  | Rd4  | /
65372**      +-------+-------+------+------+
65373** 128: | nBackfillAttempted          |
65374**      +-----------------------------+
65375** 132: | (unused padding)            |
65376**      +-----------------------------+
65377*/
65378
65379/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
65380** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
65381** only support mandatory file-locks, we do not read or write data
65382** from the region of the file on which locks are applied.
65383*/
65384#define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
65385#define WALINDEX_HDR_SIZE    (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
65386
65387/* Size of header before each frame in wal */
65388#define WAL_FRAME_HDRSIZE 24
65389
65390/* Size of write ahead log header, including checksum. */
65391#define WAL_HDRSIZE 32
65392
65393/* WAL magic value. Either this value, or the same value with the least
65394** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
65395** big-endian format in the first 4 bytes of a WAL file.
65396**
65397** If the LSB is set, then the checksums for each frame within the WAL
65398** file are calculated by treating all data as an array of 32-bit
65399** big-endian words. Otherwise, they are calculated by interpreting
65400** all data as 32-bit little-endian words.
65401*/
65402#define WAL_MAGIC 0x377f0682
65403
65404/*
65405** Return the offset of frame iFrame in the write-ahead log file,
65406** assuming a database page size of szPage bytes. The offset returned
65407** is to the start of the write-ahead log frame-header.
65408*/
65409#define walFrameOffset(iFrame, szPage) (                               \
65410  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
65411)
65412
65413/*
65414** An open write-ahead log file is represented by an instance of the
65415** following object.
65416*/
65417struct Wal {
65418  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
65419  sqlite3_file *pDbFd;       /* File handle for the database file */
65420  sqlite3_file *pWalFd;      /* File handle for WAL file */
65421  u32 iCallback;             /* Value to pass to log callback (or 0) */
65422  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
65423  int nWiData;               /* Size of array apWiData */
65424  int szFirstBlock;          /* Size of first block written to WAL file */
65425  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
65426  u32 szPage;                /* Database page size */
65427  i16 readLock;              /* Which read lock is being held.  -1 for none */
65428  u8 syncFlags;              /* Flags to use to sync header writes */
65429  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
65430  u8 writeLock;              /* True if in a write transaction */
65431  u8 ckptLock;               /* True if holding a checkpoint lock */
65432  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
65433  u8 truncateOnCommit;       /* True to truncate WAL file on commit */
65434  u8 syncHeader;             /* Fsync the WAL header if true */
65435  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
65436  u8 bShmUnreliable;         /* SHM content is read-only and unreliable */
65437  WalIndexHdr hdr;           /* Wal-index header for current transaction */
65438  u32 minFrame;              /* Ignore wal frames before this one */
65439  u32 iReCksum;              /* On commit, recalculate checksums from here */
65440  const char *zWalName;      /* Name of WAL file */
65441  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
65442#ifdef SQLITE_USE_SEH
65443  u32 lockMask;              /* Mask of locks held */
65444  void *pFree;               /* Pointer to sqlite3_free() if exception thrown */
65445  u32 *pWiValue;             /* Value to write into apWiData[iWiPg] */
65446  int iWiPg;                 /* Write pWiValue into apWiData[iWiPg] */
65447  int iSysErrno;             /* System error code following exception */
65448#endif
65449#ifdef SQLITE_DEBUG
65450  int nSehTry;               /* Number of nested SEH_TRY{} blocks */
65451  u8 lockError;              /* True if a locking error has occurred */
65452#endif
65453#ifdef SQLITE_ENABLE_SNAPSHOT
65454  WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */
65455#endif
65456#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
65457  sqlite3 *db;
65458#endif
65459};
65460
65461/*
65462** Candidate values for Wal.exclusiveMode.
65463*/
65464#define WAL_NORMAL_MODE     0
65465#define WAL_EXCLUSIVE_MODE  1
65466#define WAL_HEAPMEMORY_MODE 2
65467
65468/*
65469** Possible values for WAL.readOnly
65470*/
65471#define WAL_RDWR        0    /* Normal read/write connection */
65472#define WAL_RDONLY      1    /* The WAL file is readonly */
65473#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
65474
65475/*
65476** Each page of the wal-index mapping contains a hash-table made up of
65477** an array of HASHTABLE_NSLOT elements of the following type.
65478*/
65479typedef u16 ht_slot;
65480
65481/*
65482** This structure is used to implement an iterator that loops through
65483** all frames in the WAL in database page order. Where two or more frames
65484** correspond to the same database page, the iterator visits only the
65485** frame most recently written to the WAL (in other words, the frame with
65486** the largest index).
65487**
65488** The internals of this structure are only accessed by:
65489**
65490**   walIteratorInit() - Create a new iterator,
65491**   walIteratorNext() - Step an iterator,
65492**   walIteratorFree() - Free an iterator.
65493**
65494** This functionality is used by the checkpoint code (see walCheckpoint()).
65495*/
65496struct WalIterator {
65497  u32 iPrior;                     /* Last result returned from the iterator */
65498  int nSegment;                   /* Number of entries in aSegment[] */
65499  struct WalSegment {
65500    int iNext;                    /* Next slot in aIndex[] not yet returned */
65501    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
65502    u32 *aPgno;                   /* Array of page numbers. */
65503    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
65504    int iZero;                    /* Frame number associated with aPgno[0] */
65505  } aSegment[1];                  /* One for every 32KB page in the wal-index */
65506};
65507
65508/*
65509** Define the parameters of the hash tables in the wal-index file. There
65510** is a hash-table following every HASHTABLE_NPAGE page numbers in the
65511** wal-index.
65512**
65513** Changing any of these constants will alter the wal-index format and
65514** create incompatibilities.
65515*/
65516#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
65517#define HASHTABLE_HASH_1     383                  /* Should be prime */
65518#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
65519
65520/*
65521** The block of page numbers associated with the first hash-table in a
65522** wal-index is smaller than usual. This is so that there is a complete
65523** hash-table on each aligned 32KB page of the wal-index.
65524*/
65525#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
65526
65527/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
65528#define WALINDEX_PGSZ   (                                         \
65529    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
65530)
65531
65532/*
65533** Structured Exception Handling (SEH) is a Windows-specific technique
65534** for catching exceptions raised while accessing memory-mapped files.
65535**
65536** The -DSQLITE_USE_SEH compile-time option means to use SEH to catch and
65537** deal with system-level errors that arise during WAL -shm file processing.
65538** Without this compile-time option, any system-level faults that appear
65539** while accessing the memory-mapped -shm file will cause a process-wide
65540** signal to be deliver, which will more than likely cause the entire
65541** process to exit.
65542*/
65543#ifdef SQLITE_USE_SEH
65544#include <Windows.h>
65545
65546/* Beginning of a block of code in which an exception might occur */
65547# define SEH_TRY    __try { \
65548   assert( walAssertLockmask(pWal) && pWal->nSehTry==0 ); \
65549   VVA_ONLY(pWal->nSehTry++);
65550
65551/* The end of a block of code in which an exception might occur */
65552# define SEH_EXCEPT(X) \
65553   VVA_ONLY(pWal->nSehTry--); \
65554   assert( pWal->nSehTry==0 ); \
65555   } __except( sehExceptionFilter(pWal, GetExceptionCode(), GetExceptionInformation() ) ){ X }
65556
65557/* Simulate a memory-mapping fault in the -shm file for testing purposes */
65558# define SEH_INJECT_FAULT sehInjectFault(pWal)
65559
65560/*
65561** The second argument is the return value of GetExceptionCode() for the
65562** current exception. Return EXCEPTION_EXECUTE_HANDLER if the exception code
65563** indicates that the exception may have been caused by accessing the *-shm
65564** file mapping. Or EXCEPTION_CONTINUE_SEARCH otherwise.
65565*/
65566static int sehExceptionFilter(Wal *pWal, int eCode, EXCEPTION_POINTERS *p){
65567  VVA_ONLY(pWal->nSehTry--);
65568  if( eCode==EXCEPTION_IN_PAGE_ERROR ){
65569    if( p && p->ExceptionRecord && p->ExceptionRecord->NumberParameters>=3 ){
65570      /* From MSDN: For this type of exception, the first element of the
65571      ** ExceptionInformation[] array is a read-write flag - 0 if the exception
65572      ** was thrown while reading, 1 if while writing. The second element is
65573      ** the virtual address being accessed. The "third array element specifies
65574      ** the underlying NTSTATUS code that resulted in the exception". */
65575      pWal->iSysErrno = (int)p->ExceptionRecord->ExceptionInformation[2];
65576    }
65577    return EXCEPTION_EXECUTE_HANDLER;
65578  }
65579  return EXCEPTION_CONTINUE_SEARCH;
65580}
65581
65582/*
65583** If one is configured, invoke the xTestCallback callback with 650 as
65584** the argument. If it returns true, throw the same exception that is
65585** thrown by the system if the *-shm file mapping is accessed after it
65586** has been invalidated.
65587*/
65588static void sehInjectFault(Wal *pWal){
65589  int res;
65590  assert( pWal->nSehTry>0 );
65591
65592  res = sqlite3FaultSim(650);
65593  if( res!=0 ){
65594    ULONG_PTR aArg[3];
65595    aArg[0] = 0;
65596    aArg[1] = 0;
65597    aArg[2] = (ULONG_PTR)res;
65598    RaiseException(EXCEPTION_IN_PAGE_ERROR, 0, 3, (const ULONG_PTR*)aArg);
65599  }
65600}
65601
65602/*
65603** There are two ways to use this macro. To set a pointer to be freed
65604** if an exception is thrown:
65605**
65606**   SEH_FREE_ON_ERROR(0, pPtr);
65607**
65608** and to cancel the same:
65609**
65610**   SEH_FREE_ON_ERROR(pPtr, 0);
65611**
65612** In the first case, there must not already be a pointer registered to
65613** be freed. In the second case, pPtr must be the registered pointer.
65614*/
65615#define SEH_FREE_ON_ERROR(X,Y) \
65616  assert( (X==0 || Y==0) && pWal->pFree==X ); pWal->pFree = Y
65617
65618/*
65619** There are two ways to use this macro. To arrange for pWal->apWiData[iPg]
65620** to be set to pValue if an exception is thrown:
65621**
65622**   SEH_SET_ON_ERROR(iPg, pValue);
65623**
65624** and to cancel the same:
65625**
65626**   SEH_SET_ON_ERROR(0, 0);
65627*/
65628#define SEH_SET_ON_ERROR(X,Y)  pWal->iWiPg = X; pWal->pWiValue = Y
65629
65630#else
65631# define SEH_TRY          VVA_ONLY(pWal->nSehTry++);
65632# define SEH_EXCEPT(X)    VVA_ONLY(pWal->nSehTry--); assert( pWal->nSehTry==0 );
65633# define SEH_INJECT_FAULT assert( pWal->nSehTry>0 );
65634# define SEH_FREE_ON_ERROR(X,Y)
65635# define SEH_SET_ON_ERROR(X,Y)
65636#endif /* ifdef SQLITE_USE_SEH */
65637
65638
65639/*
65640** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
65641** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
65642** numbered from zero.
65643**
65644** If the wal-index is currently smaller the iPage pages then the size
65645** of the wal-index might be increased, but only if it is safe to do
65646** so.  It is safe to enlarge the wal-index if pWal->writeLock is true
65647** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
65648**
65649** Three possible result scenarios:
65650**
65651**   (1)  rc==SQLITE_OK    and *ppPage==Requested-Wal-Index-Page
65652**   (2)  rc>=SQLITE_ERROR and *ppPage==NULL
65653**   (3)  rc==SQLITE_OK    and *ppPage==NULL  // only if iPage==0
65654**
65655** Scenario (3) can only occur when pWal->writeLock is false and iPage==0
65656*/
65657static SQLITE_NOINLINE int walIndexPageRealloc(
65658  Wal *pWal,               /* The WAL context */
65659  int iPage,               /* The page we seek */
65660  volatile u32 **ppPage    /* Write the page pointer here */
65661){
65662  int rc = SQLITE_OK;
65663
65664  /* Enlarge the pWal->apWiData[] array if required */
65665  if( pWal->nWiData<=iPage ){
65666    sqlite3_int64 nByte = sizeof(u32*)*(iPage+1);
65667    volatile u32 **apNew;
65668    apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte);
65669    if( !apNew ){
65670      *ppPage = 0;
65671      return SQLITE_NOMEM_BKPT;
65672    }
65673    memset((void*)&apNew[pWal->nWiData], 0,
65674           sizeof(u32*)*(iPage+1-pWal->nWiData));
65675    pWal->apWiData = apNew;
65676    pWal->nWiData = iPage+1;
65677  }
65678
65679  /* Request a pointer to the required page from the VFS */
65680  assert( pWal->apWiData[iPage]==0 );
65681  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
65682    pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
65683    if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
65684  }else{
65685    rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
65686        pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
65687    );
65688    assert( pWal->apWiData[iPage]!=0
65689         || rc!=SQLITE_OK
65690         || (pWal->writeLock==0 && iPage==0) );
65691    testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
65692    if( rc==SQLITE_OK ){
65693      if( iPage>0 && sqlite3FaultSim(600) ) rc = SQLITE_NOMEM;
65694    }else if( (rc&0xff)==SQLITE_READONLY ){
65695      pWal->readOnly |= WAL_SHM_RDONLY;
65696      if( rc==SQLITE_READONLY ){
65697        rc = SQLITE_OK;
65698      }
65699    }
65700  }
65701
65702  *ppPage = pWal->apWiData[iPage];
65703  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
65704  return rc;
65705}
65706static int walIndexPage(
65707  Wal *pWal,               /* The WAL context */
65708  int iPage,               /* The page we seek */
65709  volatile u32 **ppPage    /* Write the page pointer here */
65710){
65711  SEH_INJECT_FAULT;
65712  if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
65713    return walIndexPageRealloc(pWal, iPage, ppPage);
65714  }
65715  return SQLITE_OK;
65716}
65717
65718/*
65719** Return a pointer to the WalCkptInfo structure in the wal-index.
65720*/
65721static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
65722  assert( pWal->nWiData>0 && pWal->apWiData[0] );
65723  SEH_INJECT_FAULT;
65724  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
65725}
65726
65727/*
65728** Return a pointer to the WalIndexHdr structure in the wal-index.
65729*/
65730static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
65731  assert( pWal->nWiData>0 && pWal->apWiData[0] );
65732  SEH_INJECT_FAULT;
65733  return (volatile WalIndexHdr*)pWal->apWiData[0];
65734}
65735
65736/*
65737** The argument to this macro must be of type u32. On a little-endian
65738** architecture, it returns the u32 value that results from interpreting
65739** the 4 bytes as a big-endian value. On a big-endian architecture, it
65740** returns the value that would be produced by interpreting the 4 bytes
65741** of the input value as a little-endian integer.
65742*/
65743#define BYTESWAP32(x) ( \
65744    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
65745  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
65746)
65747
65748/*
65749** Generate or extend an 8 byte checksum based on the data in
65750** array aByte[] and the initial values of aIn[0] and aIn[1] (or
65751** initial values of 0 and 0 if aIn==NULL).
65752**
65753** The checksum is written back into aOut[] before returning.
65754**
65755** nByte must be a positive multiple of 8.
65756*/
65757static void walChecksumBytes(
65758  int nativeCksum, /* True for native byte-order, false for non-native */
65759  u8 *a,           /* Content to be checksummed */
65760  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
65761  const u32 *aIn,  /* Initial checksum value input */
65762  u32 *aOut        /* OUT: Final checksum value output */
65763){
65764  u32 s1, s2;
65765  u32 *aData = (u32 *)a;
65766  u32 *aEnd = (u32 *)&a[nByte];
65767
65768  if( aIn ){
65769    s1 = aIn[0];
65770    s2 = aIn[1];
65771  }else{
65772    s1 = s2 = 0;
65773  }
65774
65775  assert( nByte>=8 );
65776  assert( (nByte&0x00000007)==0 );
65777  assert( nByte<=65536 );
65778  assert( nByte%4==0 );
65779
65780  if( !nativeCksum ){
65781    do {
65782      s1 += BYTESWAP32(aData[0]) + s2;
65783      s2 += BYTESWAP32(aData[1]) + s1;
65784      aData += 2;
65785    }while( aData<aEnd );
65786  }else if( nByte%64==0 ){
65787    do {
65788      s1 += *aData++ + s2;
65789      s2 += *aData++ + s1;
65790      s1 += *aData++ + s2;
65791      s2 += *aData++ + s1;
65792      s1 += *aData++ + s2;
65793      s2 += *aData++ + s1;
65794      s1 += *aData++ + s2;
65795      s2 += *aData++ + s1;
65796      s1 += *aData++ + s2;
65797      s2 += *aData++ + s1;
65798      s1 += *aData++ + s2;
65799      s2 += *aData++ + s1;
65800      s1 += *aData++ + s2;
65801      s2 += *aData++ + s1;
65802      s1 += *aData++ + s2;
65803      s2 += *aData++ + s1;
65804    }while( aData<aEnd );
65805  }else{
65806    do {
65807      s1 += *aData++ + s2;
65808      s2 += *aData++ + s1;
65809    }while( aData<aEnd );
65810  }
65811  assert( aData==aEnd );
65812
65813  aOut[0] = s1;
65814  aOut[1] = s2;
65815}
65816
65817/*
65818** If there is the possibility of concurrent access to the SHM file
65819** from multiple threads and/or processes, then do a memory barrier.
65820*/
65821static void walShmBarrier(Wal *pWal){
65822  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
65823    sqlite3OsShmBarrier(pWal->pDbFd);
65824  }
65825}
65826
65827/*
65828** Add the SQLITE_NO_TSAN as part of the return-type of a function
65829** definition as a hint that the function contains constructs that
65830** might give false-positive TSAN warnings.
65831**
65832** See tag-20200519-1.
65833*/
65834#if defined(__clang__) && !defined(SQLITE_NO_TSAN)
65835# define SQLITE_NO_TSAN __attribute__((no_sanitize_thread))
65836#else
65837# define SQLITE_NO_TSAN
65838#endif
65839
65840/*
65841** Write the header information in pWal->hdr into the wal-index.
65842**
65843** The checksum on pWal->hdr is updated before it is written.
65844*/
65845static SQLITE_NO_TSAN void walIndexWriteHdr(Wal *pWal){
65846  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
65847  const int nCksum = offsetof(WalIndexHdr, aCksum);
65848
65849  assert( pWal->writeLock );
65850  pWal->hdr.isInit = 1;
65851  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
65852  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
65853  /* Possible TSAN false-positive.  See tag-20200519-1 */
65854  memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
65855  walShmBarrier(pWal);
65856  memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
65857}
65858
65859/*
65860** This function encodes a single frame header and writes it to a buffer
65861** supplied by the caller. A frame-header is made up of a series of
65862** 4-byte big-endian integers, as follows:
65863**
65864**     0: Page number.
65865**     4: For commit records, the size of the database image in pages
65866**        after the commit. For all other records, zero.
65867**     8: Salt-1 (copied from the wal-header)
65868**    12: Salt-2 (copied from the wal-header)
65869**    16: Checksum-1.
65870**    20: Checksum-2.
65871*/
65872static void walEncodeFrame(
65873  Wal *pWal,                      /* The write-ahead log */
65874  u32 iPage,                      /* Database page number for frame */
65875  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
65876  u8 *aData,                      /* Pointer to page data */
65877  u8 *aFrame                      /* OUT: Write encoded frame here */
65878){
65879  int nativeCksum;                /* True for native byte-order checksums */
65880  u32 *aCksum = pWal->hdr.aFrameCksum;
65881  assert( WAL_FRAME_HDRSIZE==24 );
65882  sqlite3Put4byte(&aFrame[0], iPage);
65883  sqlite3Put4byte(&aFrame[4], nTruncate);
65884  if( pWal->iReCksum==0 ){
65885    memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
65886
65887    nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
65888    walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
65889    walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
65890
65891    sqlite3Put4byte(&aFrame[16], aCksum[0]);
65892    sqlite3Put4byte(&aFrame[20], aCksum[1]);
65893  }else{
65894    memset(&aFrame[8], 0, 16);
65895  }
65896}
65897
65898/*
65899** Check to see if the frame with header in aFrame[] and content
65900** in aData[] is valid.  If it is a valid frame, fill *piPage and
65901** *pnTruncate and return true.  Return if the frame is not valid.
65902*/
65903static int walDecodeFrame(
65904  Wal *pWal,                      /* The write-ahead log */
65905  u32 *piPage,                    /* OUT: Database page number for frame */
65906  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
65907  u8 *aData,                      /* Pointer to page data (for checksum) */
65908  u8 *aFrame                      /* Frame data */
65909){
65910  int nativeCksum;                /* True for native byte-order checksums */
65911  u32 *aCksum = pWal->hdr.aFrameCksum;
65912  u32 pgno;                       /* Page number of the frame */
65913  assert( WAL_FRAME_HDRSIZE==24 );
65914
65915  /* A frame is only valid if the salt values in the frame-header
65916  ** match the salt values in the wal-header.
65917  */
65918  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
65919    return 0;
65920  }
65921
65922  /* A frame is only valid if the page number is greater than zero.
65923  */
65924  pgno = sqlite3Get4byte(&aFrame[0]);
65925  if( pgno==0 ){
65926    return 0;
65927  }
65928
65929  /* A frame is only valid if a checksum of the WAL header,
65930  ** all prior frames, the first 16 bytes of this frame-header,
65931  ** and the frame-data matches the checksum in the last 8
65932  ** bytes of this frame-header.
65933  */
65934  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
65935  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
65936  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
65937  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
65938   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
65939  ){
65940    /* Checksum failed. */
65941    return 0;
65942  }
65943
65944  /* If we reach this point, the frame is valid.  Return the page number
65945  ** and the new database size.
65946  */
65947  *piPage = pgno;
65948  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
65949  return 1;
65950}
65951
65952
65953#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
65954/*
65955** Names of locks.  This routine is used to provide debugging output and is not
65956** a part of an ordinary build.
65957*/
65958static const char *walLockName(int lockIdx){
65959  if( lockIdx==WAL_WRITE_LOCK ){
65960    return "WRITE-LOCK";
65961  }else if( lockIdx==WAL_CKPT_LOCK ){
65962    return "CKPT-LOCK";
65963  }else if( lockIdx==WAL_RECOVER_LOCK ){
65964    return "RECOVER-LOCK";
65965  }else{
65966    static char zName[15];
65967    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
65968                     lockIdx-WAL_READ_LOCK(0));
65969    return zName;
65970  }
65971}
65972#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
65973
65974
65975/*
65976** Set or release locks on the WAL.  Locks are either shared or exclusive.
65977** A lock cannot be moved directly between shared and exclusive - it must go
65978** through the unlocked state first.
65979**
65980** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
65981*/
65982static int walLockShared(Wal *pWal, int lockIdx){
65983  int rc;
65984  if( pWal->exclusiveMode ) return SQLITE_OK;
65985  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
65986                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
65987  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
65988            walLockName(lockIdx), rc ? "failed" : "ok"));
65989  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
65990#ifdef SQLITE_USE_SEH
65991  if( rc==SQLITE_OK ) pWal->lockMask |= (1 << lockIdx);
65992#endif
65993  return rc;
65994}
65995static void walUnlockShared(Wal *pWal, int lockIdx){
65996  if( pWal->exclusiveMode ) return;
65997  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
65998                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
65999#ifdef SQLITE_USE_SEH
66000  pWal->lockMask &= ~(1 << lockIdx);
66001#endif
66002  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
66003}
66004static int walLockExclusive(Wal *pWal, int lockIdx, int n){
66005  int rc;
66006  if( pWal->exclusiveMode ) return SQLITE_OK;
66007  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
66008                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
66009  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
66010            walLockName(lockIdx), n, rc ? "failed" : "ok"));
66011  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
66012#ifdef SQLITE_USE_SEH
66013  if( rc==SQLITE_OK ){
66014    pWal->lockMask |= (((1<<n)-1) << (SQLITE_SHM_NLOCK+lockIdx));
66015  }
66016#endif
66017  return rc;
66018}
66019static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
66020  if( pWal->exclusiveMode ) return;
66021  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
66022                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
66023#ifdef SQLITE_USE_SEH
66024  pWal->lockMask &= ~(((1<<n)-1) << (SQLITE_SHM_NLOCK+lockIdx));
66025#endif
66026  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
66027             walLockName(lockIdx), n));
66028}
66029
66030/*
66031** Compute a hash on a page number.  The resulting hash value must land
66032** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
66033** the hash to the next value in the event of a collision.
66034*/
66035static int walHash(u32 iPage){
66036  assert( iPage>0 );
66037  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
66038  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
66039}
66040static int walNextHash(int iPriorHash){
66041  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
66042}
66043
66044/*
66045** An instance of the WalHashLoc object is used to describe the location
66046** of a page hash table in the wal-index.  This becomes the return value
66047** from walHashGet().
66048*/
66049typedef struct WalHashLoc WalHashLoc;
66050struct WalHashLoc {
66051  volatile ht_slot *aHash;  /* Start of the wal-index hash table */
66052  volatile u32 *aPgno;      /* aPgno[1] is the page of first frame indexed */
66053  u32 iZero;                /* One less than the frame number of first indexed*/
66054};
66055
66056/*
66057** Return pointers to the hash table and page number array stored on
66058** page iHash of the wal-index. The wal-index is broken into 32KB pages
66059** numbered starting from 0.
66060**
66061** Set output variable pLoc->aHash to point to the start of the hash table
66062** in the wal-index file. Set pLoc->iZero to one less than the frame
66063** number of the first frame indexed by this hash table. If a
66064** slot in the hash table is set to N, it refers to frame number
66065** (pLoc->iZero+N) in the log.
66066**
66067** Finally, set pLoc->aPgno so that pLoc->aPgno[0] is the page number of the
66068** first frame indexed by the hash table, frame (pLoc->iZero).
66069*/
66070static int walHashGet(
66071  Wal *pWal,                      /* WAL handle */
66072  int iHash,                      /* Find the iHash'th table */
66073  WalHashLoc *pLoc                /* OUT: Hash table location */
66074){
66075  int rc;                         /* Return code */
66076
66077  rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
66078  assert( rc==SQLITE_OK || iHash>0 );
66079
66080  if( pLoc->aPgno ){
66081    pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
66082    if( iHash==0 ){
66083      pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
66084      pLoc->iZero = 0;
66085    }else{
66086      pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
66087    }
66088  }else if( NEVER(rc==SQLITE_OK) ){
66089    rc = SQLITE_ERROR;
66090  }
66091  return rc;
66092}
66093
66094/*
66095** Return the number of the wal-index page that contains the hash-table
66096** and page-number array that contain entries corresponding to WAL frame
66097** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
66098** are numbered starting from 0.
66099*/
66100static int walFramePage(u32 iFrame){
66101  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
66102  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
66103       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
66104       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
66105       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
66106       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
66107  );
66108  assert( iHash>=0 );
66109  return iHash;
66110}
66111
66112/*
66113** Return the page number associated with frame iFrame in this WAL.
66114*/
66115static u32 walFramePgno(Wal *pWal, u32 iFrame){
66116  int iHash = walFramePage(iFrame);
66117  SEH_INJECT_FAULT;
66118  if( iHash==0 ){
66119    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
66120  }
66121  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
66122}
66123
66124/*
66125** Remove entries from the hash table that point to WAL slots greater
66126** than pWal->hdr.mxFrame.
66127**
66128** This function is called whenever pWal->hdr.mxFrame is decreased due
66129** to a rollback or savepoint.
66130**
66131** At most only the hash table containing pWal->hdr.mxFrame needs to be
66132** updated.  Any later hash tables will be automatically cleared when
66133** pWal->hdr.mxFrame advances to the point where those hash tables are
66134** actually needed.
66135*/
66136static void walCleanupHash(Wal *pWal){
66137  WalHashLoc sLoc;                /* Hash table location */
66138  int iLimit = 0;                 /* Zero values greater than this */
66139  int nByte;                      /* Number of bytes to zero in aPgno[] */
66140  int i;                          /* Used to iterate through aHash[] */
66141
66142  assert( pWal->writeLock );
66143  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
66144  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
66145  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
66146
66147  if( pWal->hdr.mxFrame==0 ) return;
66148
66149  /* Obtain pointers to the hash-table and page-number array containing
66150  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
66151  ** that the page said hash-table and array reside on is already mapped.(1)
66152  */
66153  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
66154  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
66155  i = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
66156  if( NEVER(i) ) return; /* Defense-in-depth, in case (1) above is wrong */
66157
66158  /* Zero all hash-table entries that correspond to frame numbers greater
66159  ** than pWal->hdr.mxFrame.
66160  */
66161  iLimit = pWal->hdr.mxFrame - sLoc.iZero;
66162  assert( iLimit>0 );
66163  for(i=0; i<HASHTABLE_NSLOT; i++){
66164    if( sLoc.aHash[i]>iLimit ){
66165      sLoc.aHash[i] = 0;
66166    }
66167  }
66168
66169  /* Zero the entries in the aPgno array that correspond to frames with
66170  ** frame numbers greater than pWal->hdr.mxFrame.
66171  */
66172  nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit]);
66173  assert( nByte>=0 );
66174  memset((void *)&sLoc.aPgno[iLimit], 0, nByte);
66175
66176#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
66177  /* Verify that the every entry in the mapping region is still reachable
66178  ** via the hash table even after the cleanup.
66179  */
66180  if( iLimit ){
66181    int j;           /* Loop counter */
66182    int iKey;        /* Hash key */
66183    for(j=0; j<iLimit; j++){
66184      for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){
66185        if( sLoc.aHash[iKey]==j+1 ) break;
66186      }
66187      assert( sLoc.aHash[iKey]==j+1 );
66188    }
66189  }
66190#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
66191}
66192
66193
66194/*
66195** Set an entry in the wal-index that will map database page number
66196** pPage into WAL frame iFrame.
66197*/
66198static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
66199  int rc;                         /* Return code */
66200  WalHashLoc sLoc;                /* Wal-index hash table location */
66201
66202  rc = walHashGet(pWal, walFramePage(iFrame), &sLoc);
66203
66204  /* Assuming the wal-index file was successfully mapped, populate the
66205  ** page number array and hash table entry.
66206  */
66207  if( rc==SQLITE_OK ){
66208    int iKey;                     /* Hash table key */
66209    int idx;                      /* Value to write to hash-table slot */
66210    int nCollide;                 /* Number of hash collisions */
66211
66212    idx = iFrame - sLoc.iZero;
66213    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
66214
66215    /* If this is the first entry to be added to this hash-table, zero the
66216    ** entire hash table and aPgno[] array before proceeding.
66217    */
66218    if( idx==1 ){
66219      int nByte = (int)((u8*)&sLoc.aHash[HASHTABLE_NSLOT] - (u8*)sLoc.aPgno);
66220      assert( nByte>=0 );
66221      memset((void*)sLoc.aPgno, 0, nByte);
66222    }
66223
66224    /* If the entry in aPgno[] is already set, then the previous writer
66225    ** must have exited unexpectedly in the middle of a transaction (after
66226    ** writing one or more dirty pages to the WAL to free up memory).
66227    ** Remove the remnants of that writers uncommitted transaction from
66228    ** the hash-table before writing any new entries.
66229    */
66230    if( sLoc.aPgno[idx-1] ){
66231      walCleanupHash(pWal);
66232      assert( !sLoc.aPgno[idx-1] );
66233    }
66234
66235    /* Write the aPgno[] array entry and the hash-table slot. */
66236    nCollide = idx;
66237    for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
66238      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
66239    }
66240    sLoc.aPgno[idx-1] = iPage;
66241    AtomicStore(&sLoc.aHash[iKey], (ht_slot)idx);
66242
66243#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
66244    /* Verify that the number of entries in the hash table exactly equals
66245    ** the number of entries in the mapping region.
66246    */
66247    {
66248      int i;           /* Loop counter */
66249      int nEntry = 0;  /* Number of entries in the hash table */
66250      for(i=0; i<HASHTABLE_NSLOT; i++){ if( sLoc.aHash[i] ) nEntry++; }
66251      assert( nEntry==idx );
66252    }
66253
66254    /* Verify that the every entry in the mapping region is reachable
66255    ** via the hash table.  This turns out to be a really, really expensive
66256    ** thing to check, so only do this occasionally - not on every
66257    ** iteration.
66258    */
66259    if( (idx&0x3ff)==0 ){
66260      int i;           /* Loop counter */
66261      for(i=0; i<idx; i++){
66262        for(iKey=walHash(sLoc.aPgno[i]);
66263            sLoc.aHash[iKey];
66264            iKey=walNextHash(iKey)){
66265          if( sLoc.aHash[iKey]==i+1 ) break;
66266        }
66267        assert( sLoc.aHash[iKey]==i+1 );
66268      }
66269    }
66270#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
66271  }
66272
66273  return rc;
66274}
66275
66276
66277/*
66278** Recover the wal-index by reading the write-ahead log file.
66279**
66280** This routine first tries to establish an exclusive lock on the
66281** wal-index to prevent other threads/processes from doing anything
66282** with the WAL or wal-index while recovery is running.  The
66283** WAL_RECOVER_LOCK is also held so that other threads will know
66284** that this thread is running recovery.  If unable to establish
66285** the necessary locks, this routine returns SQLITE_BUSY.
66286*/
66287static int walIndexRecover(Wal *pWal){
66288  int rc;                         /* Return Code */
66289  i64 nSize;                      /* Size of log file */
66290  u32 aFrameCksum[2] = {0, 0};
66291  int iLock;                      /* Lock offset to lock for checkpoint */
66292
66293  /* Obtain an exclusive lock on all byte in the locking range not already
66294  ** locked by the caller. The caller is guaranteed to have locked the
66295  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
66296  ** If successful, the same bytes that are locked here are unlocked before
66297  ** this function returns.
66298  */
66299  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
66300  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
66301  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
66302  assert( pWal->writeLock );
66303  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
66304  rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
66305  if( rc ){
66306    return rc;
66307  }
66308
66309  WALTRACE(("WAL%p: recovery begin...\n", pWal));
66310
66311  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
66312
66313  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
66314  if( rc!=SQLITE_OK ){
66315    goto recovery_error;
66316  }
66317
66318  if( nSize>WAL_HDRSIZE ){
66319    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
66320    u32 *aPrivate = 0;            /* Heap copy of *-shm hash being populated */
66321    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
66322    int szFrame;                  /* Number of bytes in buffer aFrame[] */
66323    u8 *aData;                    /* Pointer to data part of aFrame buffer */
66324    int szPage;                   /* Page size according to the log */
66325    u32 magic;                    /* Magic value read from WAL header */
66326    u32 version;                  /* Magic value read from WAL header */
66327    int isValid;                  /* True if this frame is valid */
66328    u32 iPg;                      /* Current 32KB wal-index page */
66329    u32 iLastFrame;               /* Last frame in wal, based on nSize alone */
66330
66331    /* Read in the WAL header. */
66332    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
66333    if( rc!=SQLITE_OK ){
66334      goto recovery_error;
66335    }
66336
66337    /* If the database page size is not a power of two, or is greater than
66338    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
66339    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
66340    ** WAL file.
66341    */
66342    magic = sqlite3Get4byte(&aBuf[0]);
66343    szPage = sqlite3Get4byte(&aBuf[8]);
66344    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
66345     || szPage&(szPage-1)
66346     || szPage>SQLITE_MAX_PAGE_SIZE
66347     || szPage<512
66348    ){
66349      goto finished;
66350    }
66351    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
66352    pWal->szPage = szPage;
66353    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
66354    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
66355
66356    /* Verify that the WAL header checksum is correct */
66357    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
66358        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
66359    );
66360    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
66361     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
66362    ){
66363      goto finished;
66364    }
66365
66366    /* Verify that the version number on the WAL format is one that
66367    ** are able to understand */
66368    version = sqlite3Get4byte(&aBuf[4]);
66369    if( version!=WAL_MAX_VERSION ){
66370      rc = SQLITE_CANTOPEN_BKPT;
66371      goto finished;
66372    }
66373
66374    /* Malloc a buffer to read frames into. */
66375    szFrame = szPage + WAL_FRAME_HDRSIZE;
66376    aFrame = (u8 *)sqlite3_malloc64(szFrame + WALINDEX_PGSZ);
66377    SEH_FREE_ON_ERROR(0, aFrame);
66378    if( !aFrame ){
66379      rc = SQLITE_NOMEM_BKPT;
66380      goto recovery_error;
66381    }
66382    aData = &aFrame[WAL_FRAME_HDRSIZE];
66383    aPrivate = (u32*)&aData[szPage];
66384
66385    /* Read all frames from the log file. */
66386    iLastFrame = (nSize - WAL_HDRSIZE) / szFrame;
66387    for(iPg=0; iPg<=(u32)walFramePage(iLastFrame); iPg++){
66388      u32 *aShare;
66389      u32 iFrame;                 /* Index of last frame read */
66390      u32 iLast = MIN(iLastFrame, HASHTABLE_NPAGE_ONE+iPg*HASHTABLE_NPAGE);
66391      u32 iFirst = 1 + (iPg==0?0:HASHTABLE_NPAGE_ONE+(iPg-1)*HASHTABLE_NPAGE);
66392      u32 nHdr, nHdr32;
66393      rc = walIndexPage(pWal, iPg, (volatile u32**)&aShare);
66394      assert( aShare!=0 || rc!=SQLITE_OK );
66395      if( aShare==0 ) break;
66396      SEH_SET_ON_ERROR(iPg, aShare);
66397      pWal->apWiData[iPg] = aPrivate;
66398
66399      for(iFrame=iFirst; iFrame<=iLast; iFrame++){
66400        i64 iOffset = walFrameOffset(iFrame, szPage);
66401        u32 pgno;                 /* Database page number for frame */
66402        u32 nTruncate;            /* dbsize field from frame header */
66403
66404        /* Read and decode the next log frame. */
66405        rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
66406        if( rc!=SQLITE_OK ) break;
66407        isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
66408        if( !isValid ) break;
66409        rc = walIndexAppend(pWal, iFrame, pgno);
66410        if( NEVER(rc!=SQLITE_OK) ) break;
66411
66412        /* If nTruncate is non-zero, this is a commit record. */
66413        if( nTruncate ){
66414          pWal->hdr.mxFrame = iFrame;
66415          pWal->hdr.nPage = nTruncate;
66416          pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
66417          testcase( szPage<=32768 );
66418          testcase( szPage>=65536 );
66419          aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
66420          aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
66421        }
66422      }
66423      pWal->apWiData[iPg] = aShare;
66424      SEH_SET_ON_ERROR(0,0);
66425      nHdr = (iPg==0 ? WALINDEX_HDR_SIZE : 0);
66426      nHdr32 = nHdr / sizeof(u32);
66427#ifndef SQLITE_SAFER_WALINDEX_RECOVERY
66428      /* Memcpy() should work fine here, on all reasonable implementations.
66429      ** Technically, memcpy() might change the destination to some
66430      ** intermediate value before setting to the final value, and that might
66431      ** cause a concurrent reader to malfunction.  Memcpy() is allowed to
66432      ** do that, according to the spec, but no memcpy() implementation that
66433      ** we know of actually does that, which is why we say that memcpy()
66434      ** is safe for this.  Memcpy() is certainly a lot faster.
66435      */
66436      memcpy(&aShare[nHdr32], &aPrivate[nHdr32], WALINDEX_PGSZ-nHdr);
66437#else
66438      /* In the event that some platform is found for which memcpy()
66439      ** changes the destination to some intermediate value before
66440      ** setting the final value, this alternative copy routine is
66441      ** provided.
66442      */
66443      {
66444        int i;
66445        for(i=nHdr32; i<WALINDEX_PGSZ/sizeof(u32); i++){
66446          if( aShare[i]!=aPrivate[i] ){
66447            /* Atomic memory operations are not required here because if
66448            ** the value needs to be changed, that means it is not being
66449            ** accessed concurrently. */
66450            aShare[i] = aPrivate[i];
66451          }
66452        }
66453      }
66454#endif
66455      SEH_INJECT_FAULT;
66456      if( iFrame<=iLast ) break;
66457    }
66458
66459    SEH_FREE_ON_ERROR(aFrame, 0);
66460    sqlite3_free(aFrame);
66461  }
66462
66463finished:
66464  if( rc==SQLITE_OK ){
66465    volatile WalCkptInfo *pInfo;
66466    int i;
66467    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
66468    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
66469    walIndexWriteHdr(pWal);
66470
66471    /* Reset the checkpoint-header. This is safe because this thread is
66472    ** currently holding locks that exclude all other writers and
66473    ** checkpointers. Then set the values of read-mark slots 1 through N.
66474    */
66475    pInfo = walCkptInfo(pWal);
66476    pInfo->nBackfill = 0;
66477    pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
66478    pInfo->aReadMark[0] = 0;
66479    for(i=1; i<WAL_NREADER; i++){
66480      rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
66481      if( rc==SQLITE_OK ){
66482        if( i==1 && pWal->hdr.mxFrame ){
66483          pInfo->aReadMark[i] = pWal->hdr.mxFrame;
66484        }else{
66485          pInfo->aReadMark[i] = READMARK_NOT_USED;
66486        }
66487        SEH_INJECT_FAULT;
66488        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
66489      }else if( rc!=SQLITE_BUSY ){
66490        goto recovery_error;
66491      }
66492    }
66493
66494    /* If more than one frame was recovered from the log file, report an
66495    ** event via sqlite3_log(). This is to help with identifying performance
66496    ** problems caused by applications routinely shutting down without
66497    ** checkpointing the log file.
66498    */
66499    if( pWal->hdr.nPage ){
66500      sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
66501          "recovered %d frames from WAL file %s",
66502          pWal->hdr.mxFrame, pWal->zWalName
66503      );
66504    }
66505  }
66506
66507recovery_error:
66508  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
66509  walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
66510  return rc;
66511}
66512
66513/*
66514** Close an open wal-index.
66515*/
66516static void walIndexClose(Wal *pWal, int isDelete){
66517  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
66518    int i;
66519    for(i=0; i<pWal->nWiData; i++){
66520      sqlite3_free((void *)pWal->apWiData[i]);
66521      pWal->apWiData[i] = 0;
66522    }
66523  }
66524  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
66525    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
66526  }
66527}
66528
66529/*
66530** Open a connection to the WAL file zWalName. The database file must
66531** already be opened on connection pDbFd. The buffer that zWalName points
66532** to must remain valid for the lifetime of the returned Wal* handle.
66533**
66534** A SHARED lock should be held on the database file when this function
66535** is called. The purpose of this SHARED lock is to prevent any other
66536** client from unlinking the WAL or wal-index file. If another process
66537** were to do this just after this client opened one of these files, the
66538** system would be badly broken.
66539**
66540** If the log file is successfully opened, SQLITE_OK is returned and
66541** *ppWal is set to point to a new WAL handle. If an error occurs,
66542** an SQLite error code is returned and *ppWal is left unmodified.
66543*/
66544SQLITE_PRIVATE int sqlite3WalOpen(
66545  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
66546  sqlite3_file *pDbFd,            /* The open database file */
66547  const char *zWalName,           /* Name of the WAL file */
66548  int bNoShm,                     /* True to run in heap-memory mode */
66549  i64 mxWalSize,                  /* Truncate WAL to this size on reset */
66550  Wal **ppWal                     /* OUT: Allocated Wal handle */
66551){
66552  int rc;                         /* Return Code */
66553  Wal *pRet;                      /* Object to allocate and return */
66554  int flags;                      /* Flags passed to OsOpen() */
66555
66556  assert( zWalName && zWalName[0] );
66557  assert( pDbFd );
66558
66559  /* Verify the values of various constants.  Any changes to the values
66560  ** of these constants would result in an incompatible on-disk format
66561  ** for the -shm file.  Any change that causes one of these asserts to
66562  ** fail is a backward compatibility problem, even if the change otherwise
66563  ** works.
66564  **
66565  ** This table also serves as a helpful cross-reference when trying to
66566  ** interpret hex dumps of the -shm file.
66567  */
66568  assert(    48 ==  sizeof(WalIndexHdr)  );
66569  assert(    40 ==  sizeof(WalCkptInfo)  );
66570  assert(   120 ==  WALINDEX_LOCK_OFFSET );
66571  assert(   136 ==  WALINDEX_HDR_SIZE    );
66572  assert(  4096 ==  HASHTABLE_NPAGE      );
66573  assert(  4062 ==  HASHTABLE_NPAGE_ONE  );
66574  assert(  8192 ==  HASHTABLE_NSLOT      );
66575  assert(   383 ==  HASHTABLE_HASH_1     );
66576  assert( 32768 ==  WALINDEX_PGSZ        );
66577  assert(     8 ==  SQLITE_SHM_NLOCK     );
66578  assert(     5 ==  WAL_NREADER          );
66579  assert(    24 ==  WAL_FRAME_HDRSIZE    );
66580  assert(    32 ==  WAL_HDRSIZE          );
66581  assert(   120 ==  WALINDEX_LOCK_OFFSET + WAL_WRITE_LOCK   );
66582  assert(   121 ==  WALINDEX_LOCK_OFFSET + WAL_CKPT_LOCK    );
66583  assert(   122 ==  WALINDEX_LOCK_OFFSET + WAL_RECOVER_LOCK );
66584  assert(   123 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(0) );
66585  assert(   124 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(1) );
66586  assert(   125 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(2) );
66587  assert(   126 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(3) );
66588  assert(   127 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(4) );
66589
66590  /* In the amalgamation, the os_unix.c and os_win.c source files come before
66591  ** this source file.  Verify that the #defines of the locking byte offsets
66592  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
66593  ** For that matter, if the lock offset ever changes from its initial design
66594  ** value of 120, we need to know that so there is an assert() to check it.
66595  */
66596#ifdef WIN_SHM_BASE
66597  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
66598#endif
66599#ifdef UNIX_SHM_BASE
66600  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
66601#endif
66602
66603
66604  /* Allocate an instance of struct Wal to return. */
66605  *ppWal = 0;
66606  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
66607  if( !pRet ){
66608    return SQLITE_NOMEM_BKPT;
66609  }
66610
66611  pRet->pVfs = pVfs;
66612  pRet->pWalFd = (sqlite3_file *)&pRet[1];
66613  pRet->pDbFd = pDbFd;
66614  pRet->readLock = -1;
66615  pRet->mxWalSize = mxWalSize;
66616  pRet->zWalName = zWalName;
66617  pRet->syncHeader = 1;
66618  pRet->padToSectorBoundary = 1;
66619  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
66620
66621  /* Open file handle on the write-ahead log file. */
66622  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
66623  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
66624  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
66625    pRet->readOnly = WAL_RDONLY;
66626  }
66627
66628  if( rc!=SQLITE_OK ){
66629    walIndexClose(pRet, 0);
66630    sqlite3OsClose(pRet->pWalFd);
66631    sqlite3_free(pRet);
66632  }else{
66633    int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
66634    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
66635    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
66636      pRet->padToSectorBoundary = 0;
66637    }
66638    *ppWal = pRet;
66639    WALTRACE(("WAL%d: opened\n", pRet));
66640  }
66641  return rc;
66642}
66643
66644/*
66645** Change the size to which the WAL file is truncated on each reset.
66646*/
66647SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
66648  if( pWal ) pWal->mxWalSize = iLimit;
66649}
66650
66651/*
66652** Find the smallest page number out of all pages held in the WAL that
66653** has not been returned by any prior invocation of this method on the
66654** same WalIterator object.   Write into *piFrame the frame index where
66655** that page was last written into the WAL.  Write into *piPage the page
66656** number.
66657**
66658** Return 0 on success.  If there are no pages in the WAL with a page
66659** number larger than *piPage, then return 1.
66660*/
66661static int walIteratorNext(
66662  WalIterator *p,               /* Iterator */
66663  u32 *piPage,                  /* OUT: The page number of the next page */
66664  u32 *piFrame                  /* OUT: Wal frame index of next page */
66665){
66666  u32 iMin;                     /* Result pgno must be greater than iMin */
66667  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
66668  int i;                        /* For looping through segments */
66669
66670  iMin = p->iPrior;
66671  assert( iMin<0xffffffff );
66672  for(i=p->nSegment-1; i>=0; i--){
66673    struct WalSegment *pSegment = &p->aSegment[i];
66674    while( pSegment->iNext<pSegment->nEntry ){
66675      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
66676      if( iPg>iMin ){
66677        if( iPg<iRet ){
66678          iRet = iPg;
66679          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
66680        }
66681        break;
66682      }
66683      pSegment->iNext++;
66684    }
66685  }
66686
66687  *piPage = p->iPrior = iRet;
66688  return (iRet==0xFFFFFFFF);
66689}
66690
66691/*
66692** This function merges two sorted lists into a single sorted list.
66693**
66694** aLeft[] and aRight[] are arrays of indices.  The sort key is
66695** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
66696** is guaranteed for all J<K:
66697**
66698**        aContent[aLeft[J]] < aContent[aLeft[K]]
66699**        aContent[aRight[J]] < aContent[aRight[K]]
66700**
66701** This routine overwrites aRight[] with a new (probably longer) sequence
66702** of indices such that the aRight[] contains every index that appears in
66703** either aLeft[] or the old aRight[] and such that the second condition
66704** above is still met.
66705**
66706** The aContent[aLeft[X]] values will be unique for all X.  And the
66707** aContent[aRight[X]] values will be unique too.  But there might be
66708** one or more combinations of X and Y such that
66709**
66710**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
66711**
66712** When that happens, omit the aLeft[X] and use the aRight[Y] index.
66713*/
66714static void walMerge(
66715  const u32 *aContent,            /* Pages in wal - keys for the sort */
66716  ht_slot *aLeft,                 /* IN: Left hand input list */
66717  int nLeft,                      /* IN: Elements in array *paLeft */
66718  ht_slot **paRight,              /* IN/OUT: Right hand input list */
66719  int *pnRight,                   /* IN/OUT: Elements in *paRight */
66720  ht_slot *aTmp                   /* Temporary buffer */
66721){
66722  int iLeft = 0;                  /* Current index in aLeft */
66723  int iRight = 0;                 /* Current index in aRight */
66724  int iOut = 0;                   /* Current index in output buffer */
66725  int nRight = *pnRight;
66726  ht_slot *aRight = *paRight;
66727
66728  assert( nLeft>0 && nRight>0 );
66729  while( iRight<nRight || iLeft<nLeft ){
66730    ht_slot logpage;
66731    Pgno dbpage;
66732
66733    if( (iLeft<nLeft)
66734     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
66735    ){
66736      logpage = aLeft[iLeft++];
66737    }else{
66738      logpage = aRight[iRight++];
66739    }
66740    dbpage = aContent[logpage];
66741
66742    aTmp[iOut++] = logpage;
66743    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
66744
66745    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
66746    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
66747  }
66748
66749  *paRight = aLeft;
66750  *pnRight = iOut;
66751  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
66752}
66753
66754/*
66755** Sort the elements in list aList using aContent[] as the sort key.
66756** Remove elements with duplicate keys, preferring to keep the
66757** larger aList[] values.
66758**
66759** The aList[] entries are indices into aContent[].  The values in
66760** aList[] are to be sorted so that for all J<K:
66761**
66762**      aContent[aList[J]] < aContent[aList[K]]
66763**
66764** For any X and Y such that
66765**
66766**      aContent[aList[X]] == aContent[aList[Y]]
66767**
66768** Keep the larger of the two values aList[X] and aList[Y] and discard
66769** the smaller.
66770*/
66771static void walMergesort(
66772  const u32 *aContent,            /* Pages in wal */
66773  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
66774  ht_slot *aList,                 /* IN/OUT: List to sort */
66775  int *pnList                     /* IN/OUT: Number of elements in aList[] */
66776){
66777  struct Sublist {
66778    int nList;                    /* Number of elements in aList */
66779    ht_slot *aList;               /* Pointer to sub-list content */
66780  };
66781
66782  const int nList = *pnList;      /* Size of input list */
66783  int nMerge = 0;                 /* Number of elements in list aMerge */
66784  ht_slot *aMerge = 0;            /* List to be merged */
66785  int iList;                      /* Index into input list */
66786  u32 iSub = 0;                   /* Index into aSub array */
66787  struct Sublist aSub[13];        /* Array of sub-lists */
66788
66789  memset(aSub, 0, sizeof(aSub));
66790  assert( nList<=HASHTABLE_NPAGE && nList>0 );
66791  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
66792
66793  for(iList=0; iList<nList; iList++){
66794    nMerge = 1;
66795    aMerge = &aList[iList];
66796    for(iSub=0; iList & (1<<iSub); iSub++){
66797      struct Sublist *p;
66798      assert( iSub<ArraySize(aSub) );
66799      p = &aSub[iSub];
66800      assert( p->aList && p->nList<=(1<<iSub) );
66801      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
66802      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
66803    }
66804    aSub[iSub].aList = aMerge;
66805    aSub[iSub].nList = nMerge;
66806  }
66807
66808  for(iSub++; iSub<ArraySize(aSub); iSub++){
66809    if( nList & (1<<iSub) ){
66810      struct Sublist *p;
66811      assert( iSub<ArraySize(aSub) );
66812      p = &aSub[iSub];
66813      assert( p->nList<=(1<<iSub) );
66814      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
66815      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
66816    }
66817  }
66818  assert( aMerge==aList );
66819  *pnList = nMerge;
66820
66821#ifdef SQLITE_DEBUG
66822  {
66823    int i;
66824    for(i=1; i<*pnList; i++){
66825      assert( aContent[aList[i]] > aContent[aList[i-1]] );
66826    }
66827  }
66828#endif
66829}
66830
66831/*
66832** Free an iterator allocated by walIteratorInit().
66833*/
66834static void walIteratorFree(WalIterator *p){
66835  sqlite3_free(p);
66836}
66837
66838/*
66839** Construct a WalInterator object that can be used to loop over all
66840** pages in the WAL following frame nBackfill in ascending order. Frames
66841** nBackfill or earlier may be included - excluding them is an optimization
66842** only. The caller must hold the checkpoint lock.
66843**
66844** On success, make *pp point to the newly allocated WalInterator object
66845** return SQLITE_OK. Otherwise, return an error code. If this routine
66846** returns an error, the value of *pp is undefined.
66847**
66848** The calling routine should invoke walIteratorFree() to destroy the
66849** WalIterator object when it has finished with it.
66850*/
66851static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
66852  WalIterator *p;                 /* Return value */
66853  int nSegment;                   /* Number of segments to merge */
66854  u32 iLast;                      /* Last frame in log */
66855  sqlite3_int64 nByte;            /* Number of bytes to allocate */
66856  int i;                          /* Iterator variable */
66857  ht_slot *aTmp;                  /* Temp space used by merge-sort */
66858  int rc = SQLITE_OK;             /* Return Code */
66859
66860  /* This routine only runs while holding the checkpoint lock. And
66861  ** it only runs if there is actually content in the log (mxFrame>0).
66862  */
66863  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
66864  iLast = pWal->hdr.mxFrame;
66865
66866  /* Allocate space for the WalIterator object. */
66867  nSegment = walFramePage(iLast) + 1;
66868  nByte = sizeof(WalIterator)
66869        + (nSegment-1)*sizeof(struct WalSegment)
66870        + iLast*sizeof(ht_slot);
66871  p = (WalIterator *)sqlite3_malloc64(nByte
66872      + sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
66873  );
66874  if( !p ){
66875    return SQLITE_NOMEM_BKPT;
66876  }
66877  memset(p, 0, nByte);
66878  p->nSegment = nSegment;
66879  aTmp = (ht_slot*)&(((u8*)p)[nByte]);
66880  SEH_FREE_ON_ERROR(0, p);
66881  for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
66882    WalHashLoc sLoc;
66883
66884    rc = walHashGet(pWal, i, &sLoc);
66885    if( rc==SQLITE_OK ){
66886      int j;                      /* Counter variable */
66887      int nEntry;                 /* Number of entries in this segment */
66888      ht_slot *aIndex;            /* Sorted index for this segment */
66889
66890      if( (i+1)==nSegment ){
66891        nEntry = (int)(iLast - sLoc.iZero);
66892      }else{
66893        nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
66894      }
66895      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
66896      sLoc.iZero++;
66897
66898      for(j=0; j<nEntry; j++){
66899        aIndex[j] = (ht_slot)j;
66900      }
66901      walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry);
66902      p->aSegment[i].iZero = sLoc.iZero;
66903      p->aSegment[i].nEntry = nEntry;
66904      p->aSegment[i].aIndex = aIndex;
66905      p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
66906    }
66907  }
66908  if( rc!=SQLITE_OK ){
66909    SEH_FREE_ON_ERROR(p, 0);
66910    walIteratorFree(p);
66911    p = 0;
66912  }
66913  *pp = p;
66914  return rc;
66915}
66916
66917#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
66918
66919
66920/*
66921** Attempt to enable blocking locks that block for nMs ms. Return 1 if
66922** blocking locks are successfully enabled, or 0 otherwise.
66923*/
66924static int walEnableBlockingMs(Wal *pWal, int nMs){
66925  int rc = sqlite3OsFileControl(
66926      pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&nMs
66927  );
66928  return (rc==SQLITE_OK);
66929}
66930
66931/*
66932** Attempt to enable blocking locks. Blocking locks are enabled only if (a)
66933** they are supported by the VFS, and (b) the database handle is configured
66934** with a busy-timeout. Return 1 if blocking locks are successfully enabled,
66935** or 0 otherwise.
66936*/
66937static int walEnableBlocking(Wal *pWal){
66938  int res = 0;
66939  if( pWal->db ){
66940    int tmout = pWal->db->busyTimeout;
66941    if( tmout ){
66942      res = walEnableBlockingMs(pWal, tmout);
66943    }
66944  }
66945  return res;
66946}
66947
66948/*
66949** Disable blocking locks.
66950*/
66951static void walDisableBlocking(Wal *pWal){
66952  int tmout = 0;
66953  sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout);
66954}
66955
66956/*
66957** If parameter bLock is true, attempt to enable blocking locks, take
66958** the WRITER lock, and then disable blocking locks. If blocking locks
66959** cannot be enabled, no attempt to obtain the WRITER lock is made. Return
66960** an SQLite error code if an error occurs, or SQLITE_OK otherwise. It is not
66961** an error if blocking locks can not be enabled.
66962**
66963** If the bLock parameter is false and the WRITER lock is held, release it.
66964*/
66965SQLITE_PRIVATE int sqlite3WalWriteLock(Wal *pWal, int bLock){
66966  int rc = SQLITE_OK;
66967  assert( pWal->readLock<0 || bLock==0 );
66968  if( bLock ){
66969    assert( pWal->db );
66970    if( walEnableBlocking(pWal) ){
66971      rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
66972      if( rc==SQLITE_OK ){
66973        pWal->writeLock = 1;
66974      }
66975      walDisableBlocking(pWal);
66976    }
66977  }else if( pWal->writeLock ){
66978    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
66979    pWal->writeLock = 0;
66980  }
66981  return rc;
66982}
66983
66984/*
66985** Set the database handle used to determine if blocking locks are required.
66986*/
66987SQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db){
66988  pWal->db = db;
66989}
66990
66991#else
66992# define walEnableBlocking(x) 0
66993# define walDisableBlocking(x)
66994# define walEnableBlockingMs(pWal, ms) 0
66995# define sqlite3WalDb(pWal, db)
66996#endif   /* ifdef SQLITE_ENABLE_SETLK_TIMEOUT */
66997
66998
66999/*
67000** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
67001** n. If the attempt fails and parameter xBusy is not NULL, then it is a
67002** busy-handler function. Invoke it and retry the lock until either the
67003** lock is successfully obtained or the busy-handler returns 0.
67004*/
67005static int walBusyLock(
67006  Wal *pWal,                      /* WAL connection */
67007  int (*xBusy)(void*),            /* Function to call when busy */
67008  void *pBusyArg,                 /* Context argument for xBusyHandler */
67009  int lockIdx,                    /* Offset of first byte to lock */
67010  int n                           /* Number of bytes to lock */
67011){
67012  int rc;
67013  do {
67014    rc = walLockExclusive(pWal, lockIdx, n);
67015  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
67016#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
67017  if( rc==SQLITE_BUSY_TIMEOUT ){
67018    walDisableBlocking(pWal);
67019    rc = SQLITE_BUSY;
67020  }
67021#endif
67022  return rc;
67023}
67024
67025/*
67026** The cache of the wal-index header must be valid to call this function.
67027** Return the page-size in bytes used by the database.
67028*/
67029static int walPagesize(Wal *pWal){
67030  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
67031}
67032
67033/*
67034** The following is guaranteed when this function is called:
67035**
67036**   a) the WRITER lock is held,
67037**   b) the entire log file has been checkpointed, and
67038**   c) any existing readers are reading exclusively from the database
67039**      file - there are no readers that may attempt to read a frame from
67040**      the log file.
67041**
67042** This function updates the shared-memory structures so that the next
67043** client to write to the database (which may be this one) does so by
67044** writing frames into the start of the log file.
67045**
67046** The value of parameter salt1 is used as the aSalt[1] value in the
67047** new wal-index header. It should be passed a pseudo-random value (i.e.
67048** one obtained from sqlite3_randomness()).
67049*/
67050static void walRestartHdr(Wal *pWal, u32 salt1){
67051  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
67052  int i;                          /* Loop counter */
67053  u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
67054  pWal->nCkpt++;
67055  pWal->hdr.mxFrame = 0;
67056  sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
67057  memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
67058  walIndexWriteHdr(pWal);
67059  AtomicStore(&pInfo->nBackfill, 0);
67060  pInfo->nBackfillAttempted = 0;
67061  pInfo->aReadMark[1] = 0;
67062  for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
67063  assert( pInfo->aReadMark[0]==0 );
67064}
67065
67066/*
67067** Copy as much content as we can from the WAL back into the database file
67068** in response to an sqlite3_wal_checkpoint() request or the equivalent.
67069**
67070** The amount of information copies from WAL to database might be limited
67071** by active readers.  This routine will never overwrite a database page
67072** that a concurrent reader might be using.
67073**
67074** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
67075** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
67076** checkpoints are always run by a background thread or background
67077** process, foreground threads will never block on a lengthy fsync call.
67078**
67079** Fsync is called on the WAL before writing content out of the WAL and
67080** into the database.  This ensures that if the new content is persistent
67081** in the WAL and can be recovered following a power-loss or hard reset.
67082**
67083** Fsync is also called on the database file if (and only if) the entire
67084** WAL content is copied into the database file.  This second fsync makes
67085** it safe to delete the WAL since the new content will persist in the
67086** database file.
67087**
67088** This routine uses and updates the nBackfill field of the wal-index header.
67089** This is the only routine that will increase the value of nBackfill.
67090** (A WAL reset or recovery will revert nBackfill to zero, but not increase
67091** its value.)
67092**
67093** The caller must be holding sufficient locks to ensure that no other
67094** checkpoint is running (in any other thread or process) at the same
67095** time.
67096*/
67097static int walCheckpoint(
67098  Wal *pWal,                      /* Wal connection */
67099  sqlite3 *db,                    /* Check for interrupts on this handle */
67100  int eMode,                      /* One of PASSIVE, FULL or RESTART */
67101  int (*xBusy)(void*),            /* Function to call when busy */
67102  void *pBusyArg,                 /* Context argument for xBusyHandler */
67103  int sync_flags,                 /* Flags for OsSync() (or 0) */
67104  u8 *zBuf                        /* Temporary buffer to use */
67105){
67106  int rc = SQLITE_OK;             /* Return code */
67107  int szPage;                     /* Database page-size */
67108  WalIterator *pIter = 0;         /* Wal iterator context */
67109  u32 iDbpage = 0;                /* Next database page to write */
67110  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
67111  u32 mxSafeFrame;                /* Max frame that can be backfilled */
67112  u32 mxPage;                     /* Max database page to write */
67113  int i;                          /* Loop counter */
67114  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
67115
67116  szPage = walPagesize(pWal);
67117  testcase( szPage<=32768 );
67118  testcase( szPage>=65536 );
67119  pInfo = walCkptInfo(pWal);
67120  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
67121
67122    /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
67123    ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
67124    assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
67125
67126    /* Compute in mxSafeFrame the index of the last frame of the WAL that is
67127    ** safe to write into the database.  Frames beyond mxSafeFrame might
67128    ** overwrite database pages that are in use by active readers and thus
67129    ** cannot be backfilled from the WAL.
67130    */
67131    mxSafeFrame = pWal->hdr.mxFrame;
67132    mxPage = pWal->hdr.nPage;
67133    for(i=1; i<WAL_NREADER; i++){
67134      u32 y = AtomicLoad(pInfo->aReadMark+i); SEH_INJECT_FAULT;
67135      if( mxSafeFrame>y ){
67136        assert( y<=pWal->hdr.mxFrame );
67137        rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
67138        if( rc==SQLITE_OK ){
67139          u32 iMark = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
67140          AtomicStore(pInfo->aReadMark+i, iMark); SEH_INJECT_FAULT;
67141          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
67142        }else if( rc==SQLITE_BUSY ){
67143          mxSafeFrame = y;
67144          xBusy = 0;
67145        }else{
67146          goto walcheckpoint_out;
67147        }
67148      }
67149    }
67150
67151    /* Allocate the iterator */
67152    if( pInfo->nBackfill<mxSafeFrame ){
67153      rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
67154      assert( rc==SQLITE_OK || pIter==0 );
67155    }
67156
67157    if( pIter
67158     && (rc = walBusyLock(pWal,xBusy,pBusyArg,WAL_READ_LOCK(0),1))==SQLITE_OK
67159    ){
67160      u32 nBackfill = pInfo->nBackfill;
67161      pInfo->nBackfillAttempted = mxSafeFrame; SEH_INJECT_FAULT;
67162
67163      /* Sync the WAL to disk */
67164      rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
67165
67166      /* If the database may grow as a result of this checkpoint, hint
67167      ** about the eventual size of the db file to the VFS layer.
67168      */
67169      if( rc==SQLITE_OK ){
67170        i64 nReq = ((i64)mxPage * szPage);
67171        i64 nSize;                    /* Current size of database file */
67172        sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0);
67173        rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
67174        if( rc==SQLITE_OK && nSize<nReq ){
67175          if( (nSize+65536+(i64)pWal->hdr.mxFrame*szPage)<nReq ){
67176            /* If the size of the final database is larger than the current
67177            ** database plus the amount of data in the wal file, plus the
67178            ** maximum size of the pending-byte page (65536 bytes), then
67179            ** must be corruption somewhere.  */
67180            rc = SQLITE_CORRUPT_BKPT;
67181          }else{
67182            sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT,&nReq);
67183          }
67184        }
67185
67186      }
67187
67188      /* Iterate through the contents of the WAL, copying data to the db file */
67189      while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
67190        i64 iOffset;
67191        assert( walFramePgno(pWal, iFrame)==iDbpage );
67192        SEH_INJECT_FAULT;
67193        if( AtomicLoad(&db->u1.isInterrupted) ){
67194          rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
67195          break;
67196        }
67197        if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
67198          continue;
67199        }
67200        iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
67201        /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
67202        rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
67203        if( rc!=SQLITE_OK ) break;
67204        iOffset = (iDbpage-1)*(i64)szPage;
67205        testcase( IS_BIG_INT(iOffset) );
67206        rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
67207        if( rc!=SQLITE_OK ) break;
67208      }
67209      sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0);
67210
67211      /* If work was actually accomplished... */
67212      if( rc==SQLITE_OK ){
67213        if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
67214          i64 szDb = pWal->hdr.nPage*(i64)szPage;
67215          testcase( IS_BIG_INT(szDb) );
67216          rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
67217          if( rc==SQLITE_OK ){
67218            rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
67219          }
67220        }
67221        if( rc==SQLITE_OK ){
67222          AtomicStore(&pInfo->nBackfill, mxSafeFrame); SEH_INJECT_FAULT;
67223        }
67224      }
67225
67226      /* Release the reader lock held while backfilling */
67227      walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
67228    }
67229
67230    if( rc==SQLITE_BUSY ){
67231      /* Reset the return code so as not to report a checkpoint failure
67232      ** just because there are active readers.  */
67233      rc = SQLITE_OK;
67234    }
67235  }
67236
67237  /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
67238  ** entire wal file has been copied into the database file, then block
67239  ** until all readers have finished using the wal file. This ensures that
67240  ** the next process to write to the database restarts the wal file.
67241  */
67242  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
67243    assert( pWal->writeLock );
67244    SEH_INJECT_FAULT;
67245    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
67246      rc = SQLITE_BUSY;
67247    }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
67248      u32 salt1;
67249      sqlite3_randomness(4, &salt1);
67250      assert( pInfo->nBackfill==pWal->hdr.mxFrame );
67251      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
67252      if( rc==SQLITE_OK ){
67253        if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
67254          /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
67255          ** SQLITE_CHECKPOINT_RESTART with the addition that it also
67256          ** truncates the log file to zero bytes just prior to a
67257          ** successful return.
67258          **
67259          ** In theory, it might be safe to do this without updating the
67260          ** wal-index header in shared memory, as all subsequent reader or
67261          ** writer clients should see that the entire log file has been
67262          ** checkpointed and behave accordingly. This seems unsafe though,
67263          ** as it would leave the system in a state where the contents of
67264          ** the wal-index header do not match the contents of the
67265          ** file-system. To avoid this, update the wal-index header to
67266          ** indicate that the log file contains zero valid frames.  */
67267          walRestartHdr(pWal, salt1);
67268          rc = sqlite3OsTruncate(pWal->pWalFd, 0);
67269        }
67270        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
67271      }
67272    }
67273  }
67274
67275 walcheckpoint_out:
67276  SEH_FREE_ON_ERROR(pIter, 0);
67277  walIteratorFree(pIter);
67278  return rc;
67279}
67280
67281/*
67282** If the WAL file is currently larger than nMax bytes in size, truncate
67283** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
67284*/
67285static void walLimitSize(Wal *pWal, i64 nMax){
67286  i64 sz;
67287  int rx;
67288  sqlite3BeginBenignMalloc();
67289  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
67290  if( rx==SQLITE_OK && (sz > nMax ) ){
67291    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
67292  }
67293  sqlite3EndBenignMalloc();
67294  if( rx ){
67295    sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
67296  }
67297}
67298
67299#ifdef SQLITE_USE_SEH
67300/*
67301** This is the "standard" exception handler used in a few places to handle
67302** an exception thrown by reading from the *-shm mapping after it has become
67303** invalid in SQLITE_USE_SEH builds. It is used as follows:
67304**
67305**   SEH_TRY { ... }
67306**   SEH_EXCEPT( rc = walHandleException(pWal); )
67307**
67308** This function does three things:
67309**
67310**   1) Determines the locks that should be held, based on the contents of
67311**      the Wal.readLock, Wal.writeLock and Wal.ckptLock variables. All other
67312**      held locks are assumed to be transient locks that would have been
67313**      released had the exception not been thrown and are dropped.
67314**
67315**   2) Frees the pointer at Wal.pFree, if any, using sqlite3_free().
67316**
67317**   3) Set pWal->apWiData[pWal->iWiPg] to pWal->pWiValue if not NULL
67318**
67319**   4) Returns SQLITE_IOERR.
67320*/
67321static int walHandleException(Wal *pWal){
67322  if( pWal->exclusiveMode==0 ){
67323    static const int S = 1;
67324    static const int E = (1<<SQLITE_SHM_NLOCK);
67325    int ii;
67326    u32 mUnlock = pWal->lockMask & ~(
67327        (pWal->readLock<0 ? 0 : (S << WAL_READ_LOCK(pWal->readLock)))
67328        | (pWal->writeLock ? (E << WAL_WRITE_LOCK) : 0)
67329        | (pWal->ckptLock ? (E << WAL_CKPT_LOCK) : 0)
67330        );
67331    for(ii=0; ii<SQLITE_SHM_NLOCK; ii++){
67332      if( (S<<ii) & mUnlock ) walUnlockShared(pWal, ii);
67333      if( (E<<ii) & mUnlock ) walUnlockExclusive(pWal, ii, 1);
67334    }
67335  }
67336  sqlite3_free(pWal->pFree);
67337  pWal->pFree = 0;
67338  if( pWal->pWiValue ){
67339    pWal->apWiData[pWal->iWiPg] = pWal->pWiValue;
67340    pWal->pWiValue = 0;
67341  }
67342  return SQLITE_IOERR_IN_PAGE;
67343}
67344
67345/*
67346** Assert that the Wal.lockMask mask, which indicates the locks held
67347** by the connenction, is consistent with the Wal.readLock, Wal.writeLock
67348** and Wal.ckptLock variables. To be used as:
67349**
67350**   assert( walAssertLockmask(pWal) );
67351*/
67352static int walAssertLockmask(Wal *pWal){
67353  if( pWal->exclusiveMode==0 ){
67354    static const int S = 1;
67355    static const int E = (1<<SQLITE_SHM_NLOCK);
67356    u32 mExpect = (
67357        (pWal->readLock<0 ? 0 : (S << WAL_READ_LOCK(pWal->readLock)))
67358      | (pWal->writeLock ? (E << WAL_WRITE_LOCK) : 0)
67359      | (pWal->ckptLock ? (E << WAL_CKPT_LOCK) : 0)
67360#ifdef SQLITE_ENABLE_SNAPSHOT
67361      | (pWal->pSnapshot ? (pWal->lockMask & (1 << WAL_CKPT_LOCK)) : 0)
67362#endif
67363    );
67364    assert( mExpect==pWal->lockMask );
67365  }
67366  return 1;
67367}
67368
67369/*
67370** Return and zero the "system error" field set when an
67371** EXCEPTION_IN_PAGE_ERROR exception is caught.
67372*/
67373SQLITE_PRIVATE int sqlite3WalSystemErrno(Wal *pWal){
67374  int iRet = 0;
67375  if( pWal ){
67376    iRet = pWal->iSysErrno;
67377    pWal->iSysErrno = 0;
67378  }
67379  return iRet;
67380}
67381
67382#else
67383# define walAssertLockmask(x) 1
67384#endif /* ifdef SQLITE_USE_SEH */
67385
67386/*
67387** Close a connection to a log file.
67388*/
67389SQLITE_PRIVATE int sqlite3WalClose(
67390  Wal *pWal,                      /* Wal to close */
67391  sqlite3 *db,                    /* For interrupt flag */
67392  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
67393  int nBuf,
67394  u8 *zBuf                        /* Buffer of at least nBuf bytes */
67395){
67396  int rc = SQLITE_OK;
67397  if( pWal ){
67398    int isDelete = 0;             /* True to unlink wal and wal-index files */
67399
67400    assert( walAssertLockmask(pWal) );
67401
67402    /* If an EXCLUSIVE lock can be obtained on the database file (using the
67403    ** ordinary, rollback-mode locking methods, this guarantees that the
67404    ** connection associated with this log file is the only connection to
67405    ** the database. In this case checkpoint the database and unlink both
67406    ** the wal and wal-index files.
67407    **
67408    ** The EXCLUSIVE lock is not released before returning.
67409    */
67410    if( zBuf!=0
67411     && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
67412    ){
67413      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
67414        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
67415      }
67416      rc = sqlite3WalCheckpoint(pWal, db,
67417          SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
67418      );
67419      if( rc==SQLITE_OK ){
67420        int bPersist = -1;
67421        sqlite3OsFileControlHint(
67422            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
67423        );
67424        if( bPersist!=1 ){
67425          /* Try to delete the WAL file if the checkpoint completed and
67426          ** fsynced (rc==SQLITE_OK) and if we are not in persistent-wal
67427          ** mode (!bPersist) */
67428          isDelete = 1;
67429        }else if( pWal->mxWalSize>=0 ){
67430          /* Try to truncate the WAL file to zero bytes if the checkpoint
67431          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
67432          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
67433          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
67434          ** to zero bytes as truncating to the journal_size_limit might
67435          ** leave a corrupt WAL file on disk. */
67436          walLimitSize(pWal, 0);
67437        }
67438      }
67439    }
67440
67441    walIndexClose(pWal, isDelete);
67442    sqlite3OsClose(pWal->pWalFd);
67443    if( isDelete ){
67444      sqlite3BeginBenignMalloc();
67445      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
67446      sqlite3EndBenignMalloc();
67447    }
67448    WALTRACE(("WAL%p: closed\n", pWal));
67449    sqlite3_free((void *)pWal->apWiData);
67450    sqlite3_free(pWal);
67451  }
67452  return rc;
67453}
67454
67455/*
67456** Try to read the wal-index header.  Return 0 on success and 1 if
67457** there is a problem.
67458**
67459** The wal-index is in shared memory.  Another thread or process might
67460** be writing the header at the same time this procedure is trying to
67461** read it, which might result in inconsistency.  A dirty read is detected
67462** by verifying that both copies of the header are the same and also by
67463** a checksum on the header.
67464**
67465** If and only if the read is consistent and the header is different from
67466** pWal->hdr, then pWal->hdr is updated to the content of the new header
67467** and *pChanged is set to 1.
67468**
67469** If the checksum cannot be verified return non-zero. If the header
67470** is read successfully and the checksum verified, return zero.
67471*/
67472static SQLITE_NO_TSAN int walIndexTryHdr(Wal *pWal, int *pChanged){
67473  u32 aCksum[2];                  /* Checksum on the header content */
67474  WalIndexHdr h1, h2;             /* Two copies of the header content */
67475  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
67476
67477  /* The first page of the wal-index must be mapped at this point. */
67478  assert( pWal->nWiData>0 && pWal->apWiData[0] );
67479
67480  /* Read the header. This might happen concurrently with a write to the
67481  ** same area of shared memory on a different CPU in a SMP,
67482  ** meaning it is possible that an inconsistent snapshot is read
67483  ** from the file. If this happens, return non-zero.
67484  **
67485  ** tag-20200519-1:
67486  ** There are two copies of the header at the beginning of the wal-index.
67487  ** When reading, read [0] first then [1].  Writes are in the reverse order.
67488  ** Memory barriers are used to prevent the compiler or the hardware from
67489  ** reordering the reads and writes.  TSAN and similar tools can sometimes
67490  ** give false-positive warnings about these accesses because the tools do not
67491  ** account for the double-read and the memory barrier. The use of mutexes
67492  ** here would be problematic as the memory being accessed is potentially
67493  ** shared among multiple processes and not all mutex implementations work
67494  ** reliably in that environment.
67495  */
67496  aHdr = walIndexHdr(pWal);
67497  memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); /* Possible TSAN false-positive */
67498  walShmBarrier(pWal);
67499  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
67500
67501  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
67502    return 1;   /* Dirty read */
67503  }
67504  if( h1.isInit==0 ){
67505    return 1;   /* Malformed header - probably all zeros */
67506  }
67507  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
67508  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
67509    return 1;   /* Checksum does not match */
67510  }
67511
67512  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
67513    *pChanged = 1;
67514    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
67515    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
67516    testcase( pWal->szPage<=32768 );
67517    testcase( pWal->szPage>=65536 );
67518  }
67519
67520  /* The header was successfully read. Return zero. */
67521  return 0;
67522}
67523
67524/*
67525** This is the value that walTryBeginRead returns when it needs to
67526** be retried.
67527*/
67528#define WAL_RETRY  (-1)
67529
67530/*
67531** Read the wal-index header from the wal-index and into pWal->hdr.
67532** If the wal-header appears to be corrupt, try to reconstruct the
67533** wal-index from the WAL before returning.
67534**
67535** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
67536** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
67537** to 0.
67538**
67539** If the wal-index header is successfully read, return SQLITE_OK.
67540** Otherwise an SQLite error code.
67541*/
67542static int walIndexReadHdr(Wal *pWal, int *pChanged){
67543  int rc;                         /* Return code */
67544  int badHdr;                     /* True if a header read failed */
67545  volatile u32 *page0;            /* Chunk of wal-index containing header */
67546
67547  /* Ensure that page 0 of the wal-index (the page that contains the
67548  ** wal-index header) is mapped. Return early if an error occurs here.
67549  */
67550  assert( pChanged );
67551  rc = walIndexPage(pWal, 0, &page0);
67552  if( rc!=SQLITE_OK ){
67553    assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */
67554    if( rc==SQLITE_READONLY_CANTINIT ){
67555      /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
67556      ** was openable but is not writable, and this thread is unable to
67557      ** confirm that another write-capable connection has the shared-memory
67558      ** open, and hence the content of the shared-memory is unreliable,
67559      ** since the shared-memory might be inconsistent with the WAL file
67560      ** and there is no writer on hand to fix it. */
67561      assert( page0==0 );
67562      assert( pWal->writeLock==0 );
67563      assert( pWal->readOnly & WAL_SHM_RDONLY );
67564      pWal->bShmUnreliable = 1;
67565      pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
67566      *pChanged = 1;
67567    }else{
67568      return rc; /* Any other non-OK return is just an error */
67569    }
67570  }else{
67571    /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
67572    ** is zero, which prevents the SHM from growing */
67573    testcase( page0!=0 );
67574  }
67575  assert( page0!=0 || pWal->writeLock==0 );
67576
67577  /* If the first page of the wal-index has been mapped, try to read the
67578  ** wal-index header immediately, without holding any lock. This usually
67579  ** works, but may fail if the wal-index header is corrupt or currently
67580  ** being modified by another thread or process.
67581  */
67582  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
67583
67584  /* If the first attempt failed, it might have been due to a race
67585  ** with a writer.  So get a WRITE lock and try again.
67586  */
67587  if( badHdr ){
67588    if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
67589      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
67590        walUnlockShared(pWal, WAL_WRITE_LOCK);
67591        rc = SQLITE_READONLY_RECOVERY;
67592      }
67593    }else{
67594      int bWriteLock = pWal->writeLock;
67595      if( bWriteLock
67596       || SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1))
67597      ){
67598        pWal->writeLock = 1;
67599        if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
67600          badHdr = walIndexTryHdr(pWal, pChanged);
67601          if( badHdr ){
67602            /* If the wal-index header is still malformed even while holding
67603            ** a WRITE lock, it can only mean that the header is corrupted and
67604            ** needs to be reconstructed.  So run recovery to do exactly that.
67605            ** Disable blocking locks first.  */
67606            walDisableBlocking(pWal);
67607            rc = walIndexRecover(pWal);
67608            *pChanged = 1;
67609          }
67610        }
67611        if( bWriteLock==0 ){
67612          pWal->writeLock = 0;
67613          walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
67614        }
67615      }
67616    }
67617  }
67618
67619  /* If the header is read successfully, check the version number to make
67620  ** sure the wal-index was not constructed with some future format that
67621  ** this version of SQLite cannot understand.
67622  */
67623  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
67624    rc = SQLITE_CANTOPEN_BKPT;
67625  }
67626  if( pWal->bShmUnreliable ){
67627    if( rc!=SQLITE_OK ){
67628      walIndexClose(pWal, 0);
67629      pWal->bShmUnreliable = 0;
67630      assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
67631      /* walIndexRecover() might have returned SHORT_READ if a concurrent
67632      ** writer truncated the WAL out from under it.  If that happens, it
67633      ** indicates that a writer has fixed the SHM file for us, so retry */
67634      if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
67635    }
67636    pWal->exclusiveMode = WAL_NORMAL_MODE;
67637  }
67638
67639  return rc;
67640}
67641
67642/*
67643** Open a transaction in a connection where the shared-memory is read-only
67644** and where we cannot verify that there is a separate write-capable connection
67645** on hand to keep the shared-memory up-to-date with the WAL file.
67646**
67647** This can happen, for example, when the shared-memory is implemented by
67648** memory-mapping a *-shm file, where a prior writer has shut down and
67649** left the *-shm file on disk, and now the present connection is trying
67650** to use that database but lacks write permission on the *-shm file.
67651** Other scenarios are also possible, depending on the VFS implementation.
67652**
67653** Precondition:
67654**
67655**    The *-wal file has been read and an appropriate wal-index has been
67656**    constructed in pWal->apWiData[] using heap memory instead of shared
67657**    memory.
67658**
67659** If this function returns SQLITE_OK, then the read transaction has
67660** been successfully opened. In this case output variable (*pChanged)
67661** is set to true before returning if the caller should discard the
67662** contents of the page cache before proceeding. Or, if it returns
67663** WAL_RETRY, then the heap memory wal-index has been discarded and
67664** the caller should retry opening the read transaction from the
67665** beginning (including attempting to map the *-shm file).
67666**
67667** If an error occurs, an SQLite error code is returned.
67668*/
67669static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
67670  i64 szWal;                      /* Size of wal file on disk in bytes */
67671  i64 iOffset;                    /* Current offset when reading wal file */
67672  u8 aBuf[WAL_HDRSIZE];           /* Buffer to load WAL header into */
67673  u8 *aFrame = 0;                 /* Malloc'd buffer to load entire frame */
67674  int szFrame;                    /* Number of bytes in buffer aFrame[] */
67675  u8 *aData;                      /* Pointer to data part of aFrame buffer */
67676  volatile void *pDummy;          /* Dummy argument for xShmMap */
67677  int rc;                         /* Return code */
67678  u32 aSaveCksum[2];              /* Saved copy of pWal->hdr.aFrameCksum */
67679
67680  assert( pWal->bShmUnreliable );
67681  assert( pWal->readOnly & WAL_SHM_RDONLY );
67682  assert( pWal->nWiData>0 && pWal->apWiData[0] );
67683
67684  /* Take WAL_READ_LOCK(0). This has the effect of preventing any
67685  ** writers from running a checkpoint, but does not stop them
67686  ** from running recovery.  */
67687  rc = walLockShared(pWal, WAL_READ_LOCK(0));
67688  if( rc!=SQLITE_OK ){
67689    if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
67690    goto begin_unreliable_shm_out;
67691  }
67692  pWal->readLock = 0;
67693
67694  /* Check to see if a separate writer has attached to the shared-memory area,
67695  ** thus making the shared-memory "reliable" again.  Do this by invoking
67696  ** the xShmMap() routine of the VFS and looking to see if the return
67697  ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
67698  **
67699  ** If the shared-memory is now "reliable" return WAL_RETRY, which will
67700  ** cause the heap-memory WAL-index to be discarded and the actual
67701  ** shared memory to be used in its place.
67702  **
67703  ** This step is important because, even though this connection is holding
67704  ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
67705  ** have already checkpointed the WAL file and, while the current
67706  ** is active, wrap the WAL and start overwriting frames that this
67707  ** process wants to use.
67708  **
67709  ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
67710  ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
67711  ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
67712  ** even if some external agent does a "chmod" to make the shared-memory
67713  ** writable by us, until sqlite3OsShmUnmap() has been called.
67714  ** This is a requirement on the VFS implementation.
67715   */
67716  rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
67717  assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
67718  if( rc!=SQLITE_READONLY_CANTINIT ){
67719    rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
67720    goto begin_unreliable_shm_out;
67721  }
67722
67723  /* We reach this point only if the real shared-memory is still unreliable.
67724  ** Assume the in-memory WAL-index substitute is correct and load it
67725  ** into pWal->hdr.
67726  */
67727  memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
67728
67729  /* Make sure some writer hasn't come in and changed the WAL file out
67730  ** from under us, then disconnected, while we were not looking.
67731  */
67732  rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
67733  if( rc!=SQLITE_OK ){
67734    goto begin_unreliable_shm_out;
67735  }
67736  if( szWal<WAL_HDRSIZE ){
67737    /* If the wal file is too small to contain a wal-header and the
67738    ** wal-index header has mxFrame==0, then it must be safe to proceed
67739    ** reading the database file only. However, the page cache cannot
67740    ** be trusted, as a read/write connection may have connected, written
67741    ** the db, run a checkpoint, truncated the wal file and disconnected
67742    ** since this client's last read transaction.  */
67743    *pChanged = 1;
67744    rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
67745    goto begin_unreliable_shm_out;
67746  }
67747
67748  /* Check the salt keys at the start of the wal file still match. */
67749  rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
67750  if( rc!=SQLITE_OK ){
67751    goto begin_unreliable_shm_out;
67752  }
67753  if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
67754    /* Some writer has wrapped the WAL file while we were not looking.
67755    ** Return WAL_RETRY which will cause the in-memory WAL-index to be
67756    ** rebuilt. */
67757    rc = WAL_RETRY;
67758    goto begin_unreliable_shm_out;
67759  }
67760
67761  /* Allocate a buffer to read frames into */
67762  assert( (pWal->szPage & (pWal->szPage-1))==0 );
67763  assert( pWal->szPage>=512 && pWal->szPage<=65536 );
67764  szFrame = pWal->szPage + WAL_FRAME_HDRSIZE;
67765  aFrame = (u8 *)sqlite3_malloc64(szFrame);
67766  if( aFrame==0 ){
67767    rc = SQLITE_NOMEM_BKPT;
67768    goto begin_unreliable_shm_out;
67769  }
67770  aData = &aFrame[WAL_FRAME_HDRSIZE];
67771
67772  /* Check to see if a complete transaction has been appended to the
67773  ** wal file since the heap-memory wal-index was created. If so, the
67774  ** heap-memory wal-index is discarded and WAL_RETRY returned to
67775  ** the caller.  */
67776  aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
67777  aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
67778  for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->szPage);
67779      iOffset+szFrame<=szWal;
67780      iOffset+=szFrame
67781  ){
67782    u32 pgno;                   /* Database page number for frame */
67783    u32 nTruncate;              /* dbsize field from frame header */
67784
67785    /* Read and decode the next log frame. */
67786    rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
67787    if( rc!=SQLITE_OK ) break;
67788    if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
67789
67790    /* If nTruncate is non-zero, then a complete transaction has been
67791    ** appended to this wal file. Set rc to WAL_RETRY and break out of
67792    ** the loop.  */
67793    if( nTruncate ){
67794      rc = WAL_RETRY;
67795      break;
67796    }
67797  }
67798  pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
67799  pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
67800
67801 begin_unreliable_shm_out:
67802  sqlite3_free(aFrame);
67803  if( rc!=SQLITE_OK ){
67804    int i;
67805    for(i=0; i<pWal->nWiData; i++){
67806      sqlite3_free((void*)pWal->apWiData[i]);
67807      pWal->apWiData[i] = 0;
67808    }
67809    pWal->bShmUnreliable = 0;
67810    sqlite3WalEndReadTransaction(pWal);
67811    *pChanged = 1;
67812  }
67813  return rc;
67814}
67815
67816/*
67817** The final argument passed to walTryBeginRead() is of type (int*). The
67818** caller should invoke walTryBeginRead as follows:
67819**
67820**   int cnt = 0;
67821**   do {
67822**     rc = walTryBeginRead(..., &cnt);
67823**   }while( rc==WAL_RETRY );
67824**
67825** The final value of "cnt" is of no use to the caller. It is used by
67826** the implementation of walTryBeginRead() as follows:
67827**
67828**   + Each time walTryBeginRead() is called, it is incremented. Once
67829**     it reaches WAL_RETRY_PROTOCOL_LIMIT - indicating that walTryBeginRead()
67830**     has many times been invoked and failed with WAL_RETRY - walTryBeginRead()
67831**     returns SQLITE_PROTOCOL.
67832**
67833**   + If SQLITE_ENABLE_SETLK_TIMEOUT is defined and walTryBeginRead() failed
67834**     because a blocking lock timed out (SQLITE_BUSY_TIMEOUT from the OS
67835**     layer), the WAL_RETRY_BLOCKED_MASK bit is set in "cnt". In this case
67836**     the next invocation of walTryBeginRead() may omit an expected call to
67837**     sqlite3OsSleep(). There has already been a delay when the previous call
67838**     waited on a lock.
67839*/
67840#define WAL_RETRY_PROTOCOL_LIMIT 100
67841#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
67842# define WAL_RETRY_BLOCKED_MASK    0x10000000
67843#else
67844# define WAL_RETRY_BLOCKED_MASK    0
67845#endif
67846
67847/*
67848** Attempt to start a read transaction.  This might fail due to a race or
67849** other transient condition.  When that happens, it returns WAL_RETRY to
67850** indicate to the caller that it is safe to retry immediately.
67851**
67852** On success return SQLITE_OK.  On a permanent failure (such an
67853** I/O error or an SQLITE_BUSY because another process is running
67854** recovery) return a positive error code.
67855**
67856** The useWal parameter is true to force the use of the WAL and disable
67857** the case where the WAL is bypassed because it has been completely
67858** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
67859** to make a copy of the wal-index header into pWal->hdr.  If the
67860** wal-index header has changed, *pChanged is set to 1 (as an indication
67861** to the caller that the local page cache is obsolete and needs to be
67862** flushed.)  When useWal==1, the wal-index header is assumed to already
67863** be loaded and the pChanged parameter is unused.
67864**
67865** The caller must set the cnt parameter to the number of prior calls to
67866** this routine during the current read attempt that returned WAL_RETRY.
67867** This routine will start taking more aggressive measures to clear the
67868** race conditions after multiple WAL_RETRY returns, and after an excessive
67869** number of errors will ultimately return SQLITE_PROTOCOL.  The
67870** SQLITE_PROTOCOL return indicates that some other process has gone rogue
67871** and is not honoring the locking protocol.  There is a vanishingly small
67872** chance that SQLITE_PROTOCOL could be returned because of a run of really
67873** bad luck when there is lots of contention for the wal-index, but that
67874** possibility is so small that it can be safely neglected, we believe.
67875**
67876** On success, this routine obtains a read lock on
67877** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
67878** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
67879** that means the Wal does not hold any read lock.  The reader must not
67880** access any database page that is modified by a WAL frame up to and
67881** including frame number aReadMark[pWal->readLock].  The reader will
67882** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
67883** Or if pWal->readLock==0, then the reader will ignore the WAL
67884** completely and get all content directly from the database file.
67885** If the useWal parameter is 1 then the WAL will never be ignored and
67886** this routine will always set pWal->readLock>0 on success.
67887** When the read transaction is completed, the caller must release the
67888** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
67889**
67890** This routine uses the nBackfill and aReadMark[] fields of the header
67891** to select a particular WAL_READ_LOCK() that strives to let the
67892** checkpoint process do as much work as possible.  This routine might
67893** update values of the aReadMark[] array in the header, but if it does
67894** so it takes care to hold an exclusive lock on the corresponding
67895** WAL_READ_LOCK() while changing values.
67896*/
67897static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int *pCnt){
67898  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
67899  u32 mxReadMark;                 /* Largest aReadMark[] value */
67900  int mxI;                        /* Index of largest aReadMark[] value */
67901  int i;                          /* Loop counter */
67902  int rc = SQLITE_OK;             /* Return code  */
67903  u32 mxFrame;                    /* Wal frame to lock to */
67904#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
67905  int nBlockTmout = 0;
67906#endif
67907
67908  assert( pWal->readLock<0 );     /* Not currently locked */
67909
67910  /* useWal may only be set for read/write connections */
67911  assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
67912
67913  /* Take steps to avoid spinning forever if there is a protocol error.
67914  **
67915  ** Circumstances that cause a RETRY should only last for the briefest
67916  ** instances of time.  No I/O or other system calls are done while the
67917  ** locks are held, so the locks should not be held for very long. But
67918  ** if we are unlucky, another process that is holding a lock might get
67919  ** paged out or take a page-fault that is time-consuming to resolve,
67920  ** during the few nanoseconds that it is holding the lock.  In that case,
67921  ** it might take longer than normal for the lock to free.
67922  **
67923  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
67924  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
67925  ** is more of a scheduler yield than an actual delay.  But on the 10th
67926  ** an subsequent retries, the delays start becoming longer and longer,
67927  ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
67928  ** The total delay time before giving up is less than 10 seconds.
67929  */
67930  (*pCnt)++;
67931  if( *pCnt>5 ){
67932    int nDelay = 1;                      /* Pause time in microseconds */
67933    int cnt = (*pCnt & ~WAL_RETRY_BLOCKED_MASK);
67934    if( cnt>WAL_RETRY_PROTOCOL_LIMIT ){
67935      VVA_ONLY( pWal->lockError = 1; )
67936      return SQLITE_PROTOCOL;
67937    }
67938    if( *pCnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
67939#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
67940    /* In SQLITE_ENABLE_SETLK_TIMEOUT builds, configure the file-descriptor
67941    ** to block for locks for approximately nDelay us. This affects three
67942    ** locks: (a) the shared lock taken on the DMS slot in os_unix.c (if
67943    ** using os_unix.c), (b) the WRITER lock taken in walIndexReadHdr() if the
67944    ** first attempted read fails, and (c) the shared lock taken on the
67945    ** read-mark.
67946    **
67947    ** If the previous call failed due to an SQLITE_BUSY_TIMEOUT error,
67948    ** then sleep for the minimum of 1us. The previous call already provided
67949    ** an extra delay while it was blocking on the lock.
67950    */
67951    nBlockTmout = (nDelay+998) / 1000;
67952    if( !useWal && walEnableBlockingMs(pWal, nBlockTmout) ){
67953      if( *pCnt & WAL_RETRY_BLOCKED_MASK ) nDelay = 1;
67954    }
67955#endif
67956    sqlite3OsSleep(pWal->pVfs, nDelay);
67957    *pCnt &= ~WAL_RETRY_BLOCKED_MASK;
67958  }
67959
67960  if( !useWal ){
67961    assert( rc==SQLITE_OK );
67962    if( pWal->bShmUnreliable==0 ){
67963      rc = walIndexReadHdr(pWal, pChanged);
67964    }
67965#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
67966    walDisableBlocking(pWal);
67967    if( rc==SQLITE_BUSY_TIMEOUT ){
67968      rc = SQLITE_BUSY;
67969      *pCnt |= WAL_RETRY_BLOCKED_MASK;
67970    }
67971#endif
67972    if( rc==SQLITE_BUSY ){
67973      /* If there is not a recovery running in another thread or process
67974      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
67975      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
67976      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
67977      ** would be technically correct.  But the race is benign since with
67978      ** WAL_RETRY this routine will be called again and will probably be
67979      ** right on the second iteration.
67980      */
67981      if( pWal->apWiData[0]==0 ){
67982        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
67983        ** We assume this is a transient condition, so return WAL_RETRY. The
67984        ** xShmMap() implementation used by the default unix and win32 VFS
67985        ** modules may return SQLITE_BUSY due to a race condition in the
67986        ** code that determines whether or not the shared-memory region
67987        ** must be zeroed before the requested page is returned.
67988        */
67989        rc = WAL_RETRY;
67990      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
67991        walUnlockShared(pWal, WAL_RECOVER_LOCK);
67992        rc = WAL_RETRY;
67993      }else if( rc==SQLITE_BUSY ){
67994        rc = SQLITE_BUSY_RECOVERY;
67995      }
67996    }
67997    if( rc!=SQLITE_OK ){
67998      return rc;
67999    }
68000    else if( pWal->bShmUnreliable ){
68001      return walBeginShmUnreliable(pWal, pChanged);
68002    }
68003  }
68004
68005  assert( pWal->nWiData>0 );
68006  assert( pWal->apWiData[0]!=0 );
68007  pInfo = walCkptInfo(pWal);
68008  SEH_INJECT_FAULT;
68009  if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame
68010#ifdef SQLITE_ENABLE_SNAPSHOT
68011   && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
68012#endif
68013  ){
68014    /* The WAL has been completely backfilled (or it is empty).
68015    ** and can be safely ignored.
68016    */
68017    rc = walLockShared(pWal, WAL_READ_LOCK(0));
68018    walShmBarrier(pWal);
68019    if( rc==SQLITE_OK ){
68020      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
68021        /* It is not safe to allow the reader to continue here if frames
68022        ** may have been appended to the log before READ_LOCK(0) was obtained.
68023        ** When holding READ_LOCK(0), the reader ignores the entire log file,
68024        ** which implies that the database file contains a trustworthy
68025        ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
68026        ** happening, this is usually correct.
68027        **
68028        ** However, if frames have been appended to the log (or if the log
68029        ** is wrapped and written for that matter) before the READ_LOCK(0)
68030        ** is obtained, that is not necessarily true. A checkpointer may
68031        ** have started to backfill the appended frames but crashed before
68032        ** it finished. Leaving a corrupt image in the database file.
68033        */
68034        walUnlockShared(pWal, WAL_READ_LOCK(0));
68035        return WAL_RETRY;
68036      }
68037      pWal->readLock = 0;
68038      return SQLITE_OK;
68039    }else if( rc!=SQLITE_BUSY ){
68040      return rc;
68041    }
68042  }
68043
68044  /* If we get this far, it means that the reader will want to use
68045  ** the WAL to get at content from recent commits.  The job now is
68046  ** to select one of the aReadMark[] entries that is closest to
68047  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
68048  */
68049  mxReadMark = 0;
68050  mxI = 0;
68051  mxFrame = pWal->hdr.mxFrame;
68052#ifdef SQLITE_ENABLE_SNAPSHOT
68053  if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
68054    mxFrame = pWal->pSnapshot->mxFrame;
68055  }
68056#endif
68057  for(i=1; i<WAL_NREADER; i++){
68058    u32 thisMark = AtomicLoad(pInfo->aReadMark+i); SEH_INJECT_FAULT;
68059    if( mxReadMark<=thisMark && thisMark<=mxFrame ){
68060      assert( thisMark!=READMARK_NOT_USED );
68061      mxReadMark = thisMark;
68062      mxI = i;
68063    }
68064  }
68065  if( (pWal->readOnly & WAL_SHM_RDONLY)==0
68066   && (mxReadMark<mxFrame || mxI==0)
68067  ){
68068    for(i=1; i<WAL_NREADER; i++){
68069      rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
68070      if( rc==SQLITE_OK ){
68071        AtomicStore(pInfo->aReadMark+i,mxFrame);
68072        mxReadMark = mxFrame;
68073        mxI = i;
68074        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
68075        break;
68076      }else if( rc!=SQLITE_BUSY ){
68077        return rc;
68078      }
68079    }
68080  }
68081  if( mxI==0 ){
68082    assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
68083    return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
68084  }
68085
68086  (void)walEnableBlockingMs(pWal, nBlockTmout);
68087  rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
68088  walDisableBlocking(pWal);
68089  if( rc ){
68090#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
68091    if( rc==SQLITE_BUSY_TIMEOUT ){
68092      *pCnt |= WAL_RETRY_BLOCKED_MASK;
68093    }
68094#else
68095    assert( rc!=SQLITE_BUSY_TIMEOUT );
68096#endif
68097    assert( (rc&0xFF)!=SQLITE_BUSY||rc==SQLITE_BUSY||rc==SQLITE_BUSY_TIMEOUT );
68098    return (rc&0xFF)==SQLITE_BUSY ? WAL_RETRY : rc;
68099  }
68100  /* Now that the read-lock has been obtained, check that neither the
68101  ** value in the aReadMark[] array or the contents of the wal-index
68102  ** header have changed.
68103  **
68104  ** It is necessary to check that the wal-index header did not change
68105  ** between the time it was read and when the shared-lock was obtained
68106  ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
68107  ** that the log file may have been wrapped by a writer, or that frames
68108  ** that occur later in the log than pWal->hdr.mxFrame may have been
68109  ** copied into the database by a checkpointer. If either of these things
68110  ** happened, then reading the database with the current value of
68111  ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
68112  ** instead.
68113  **
68114  ** Before checking that the live wal-index header has not changed
68115  ** since it was read, set Wal.minFrame to the first frame in the wal
68116  ** file that has not yet been checkpointed. This client will not need
68117  ** to read any frames earlier than minFrame from the wal file - they
68118  ** can be safely read directly from the database file.
68119  **
68120  ** Because a ShmBarrier() call is made between taking the copy of
68121  ** nBackfill and checking that the wal-header in shared-memory still
68122  ** matches the one cached in pWal->hdr, it is guaranteed that the
68123  ** checkpointer that set nBackfill was not working with a wal-index
68124  ** header newer than that cached in pWal->hdr. If it were, that could
68125  ** cause a problem. The checkpointer could omit to checkpoint
68126  ** a version of page X that lies before pWal->minFrame (call that version
68127  ** A) on the basis that there is a newer version (version B) of the same
68128  ** page later in the wal file. But if version B happens to like past
68129  ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
68130  ** that it can read version A from the database file. However, since
68131  ** we can guarantee that the checkpointer that set nBackfill could not
68132  ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
68133  */
68134  pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1; SEH_INJECT_FAULT;
68135  walShmBarrier(pWal);
68136  if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
68137   || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
68138  ){
68139    walUnlockShared(pWal, WAL_READ_LOCK(mxI));
68140    return WAL_RETRY;
68141  }else{
68142    assert( mxReadMark<=pWal->hdr.mxFrame );
68143    pWal->readLock = (i16)mxI;
68144  }
68145  return rc;
68146}
68147
68148#ifdef SQLITE_ENABLE_SNAPSHOT
68149/*
68150** This function does the work of sqlite3WalSnapshotRecover().
68151*/
68152static int walSnapshotRecover(
68153  Wal *pWal,                      /* WAL handle */
68154  void *pBuf1,                    /* Temp buffer pWal->szPage bytes in size */
68155  void *pBuf2                     /* Temp buffer pWal->szPage bytes in size */
68156){
68157  int szPage = (int)pWal->szPage;
68158  int rc;
68159  i64 szDb;                       /* Size of db file in bytes */
68160
68161  rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
68162  if( rc==SQLITE_OK ){
68163    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
68164    u32 i = pInfo->nBackfillAttempted;
68165    for(i=pInfo->nBackfillAttempted; i>AtomicLoad(&pInfo->nBackfill); i--){
68166      WalHashLoc sLoc;          /* Hash table location */
68167      u32 pgno;                 /* Page number in db file */
68168      i64 iDbOff;               /* Offset of db file entry */
68169      i64 iWalOff;              /* Offset of wal file entry */
68170
68171      rc = walHashGet(pWal, walFramePage(i), &sLoc);
68172      if( rc!=SQLITE_OK ) break;
68173      assert( i - sLoc.iZero - 1 >=0 );
68174      pgno = sLoc.aPgno[i-sLoc.iZero-1];
68175      iDbOff = (i64)(pgno-1) * szPage;
68176
68177      if( iDbOff+szPage<=szDb ){
68178        iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
68179        rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
68180
68181        if( rc==SQLITE_OK ){
68182          rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
68183        }
68184
68185        if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
68186          break;
68187        }
68188      }
68189
68190      pInfo->nBackfillAttempted = i-1;
68191    }
68192  }
68193
68194  return rc;
68195}
68196
68197/*
68198** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
68199** variable so that older snapshots can be accessed. To do this, loop
68200** through all wal frames from nBackfillAttempted to (nBackfill+1),
68201** comparing their content to the corresponding page with the database
68202** file, if any. Set nBackfillAttempted to the frame number of the
68203** first frame for which the wal file content matches the db file.
68204**
68205** This is only really safe if the file-system is such that any page
68206** writes made by earlier checkpointers were atomic operations, which
68207** is not always true. It is also possible that nBackfillAttempted
68208** may be left set to a value larger than expected, if a wal frame
68209** contains content that duplicate of an earlier version of the same
68210** page.
68211**
68212** SQLITE_OK is returned if successful, or an SQLite error code if an
68213** error occurs. It is not an error if nBackfillAttempted cannot be
68214** decreased at all.
68215*/
68216SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
68217  int rc;
68218
68219  assert( pWal->readLock>=0 );
68220  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
68221  if( rc==SQLITE_OK ){
68222    void *pBuf1 = sqlite3_malloc(pWal->szPage);
68223    void *pBuf2 = sqlite3_malloc(pWal->szPage);
68224    if( pBuf1==0 || pBuf2==0 ){
68225      rc = SQLITE_NOMEM;
68226    }else{
68227      pWal->ckptLock = 1;
68228      SEH_TRY {
68229        rc = walSnapshotRecover(pWal, pBuf1, pBuf2);
68230      }
68231      SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
68232      pWal->ckptLock = 0;
68233    }
68234
68235    sqlite3_free(pBuf1);
68236    sqlite3_free(pBuf2);
68237    walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
68238  }
68239
68240  return rc;
68241}
68242#endif /* SQLITE_ENABLE_SNAPSHOT */
68243
68244/*
68245** This function does the work of sqlite3WalBeginReadTransaction() (see
68246** below). That function simply calls this one inside an SEH_TRY{...} block.
68247*/
68248static int walBeginReadTransaction(Wal *pWal, int *pChanged){
68249  int rc;                         /* Return code */
68250  int cnt = 0;                    /* Number of TryBeginRead attempts */
68251#ifdef SQLITE_ENABLE_SNAPSHOT
68252  int ckptLock = 0;
68253  int bChanged = 0;
68254  WalIndexHdr *pSnapshot = pWal->pSnapshot;
68255#endif
68256
68257  assert( pWal->ckptLock==0 );
68258  assert( pWal->nSehTry>0 );
68259
68260#ifdef SQLITE_ENABLE_SNAPSHOT
68261  if( pSnapshot ){
68262    if( memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
68263      bChanged = 1;
68264    }
68265
68266    /* It is possible that there is a checkpointer thread running
68267    ** concurrent with this code. If this is the case, it may be that the
68268    ** checkpointer has already determined that it will checkpoint
68269    ** snapshot X, where X is later in the wal file than pSnapshot, but
68270    ** has not yet set the pInfo->nBackfillAttempted variable to indicate
68271    ** its intent. To avoid the race condition this leads to, ensure that
68272    ** there is no checkpointer process by taking a shared CKPT lock
68273    ** before checking pInfo->nBackfillAttempted.  */
68274    (void)walEnableBlocking(pWal);
68275    rc = walLockShared(pWal, WAL_CKPT_LOCK);
68276    walDisableBlocking(pWal);
68277
68278    if( rc!=SQLITE_OK ){
68279      return rc;
68280    }
68281    ckptLock = 1;
68282  }
68283#endif
68284
68285  do{
68286    rc = walTryBeginRead(pWal, pChanged, 0, &cnt);
68287  }while( rc==WAL_RETRY );
68288  testcase( (rc&0xff)==SQLITE_BUSY );
68289  testcase( (rc&0xff)==SQLITE_IOERR );
68290  testcase( rc==SQLITE_PROTOCOL );
68291  testcase( rc==SQLITE_OK );
68292
68293#ifdef SQLITE_ENABLE_SNAPSHOT
68294  if( rc==SQLITE_OK ){
68295    if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
68296      /* At this point the client has a lock on an aReadMark[] slot holding
68297      ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
68298      ** is populated with the wal-index header corresponding to the head
68299      ** of the wal file. Verify that pSnapshot is still valid before
68300      ** continuing.  Reasons why pSnapshot might no longer be valid:
68301      **
68302      **    (1)  The WAL file has been reset since the snapshot was taken.
68303      **         In this case, the salt will have changed.
68304      **
68305      **    (2)  A checkpoint as been attempted that wrote frames past
68306      **         pSnapshot->mxFrame into the database file.  Note that the
68307      **         checkpoint need not have completed for this to cause problems.
68308      */
68309      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
68310
68311      assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
68312      assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
68313
68314      /* Check that the wal file has not been wrapped. Assuming that it has
68315      ** not, also check that no checkpointer has attempted to checkpoint any
68316      ** frames beyond pSnapshot->mxFrame. If either of these conditions are
68317      ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
68318      ** with *pSnapshot and set *pChanged as appropriate for opening the
68319      ** snapshot.  */
68320      if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
68321       && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
68322      ){
68323        assert( pWal->readLock>0 );
68324        memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
68325        *pChanged = bChanged;
68326      }else{
68327        rc = SQLITE_ERROR_SNAPSHOT;
68328      }
68329
68330      /* A client using a non-current snapshot may not ignore any frames
68331      ** from the start of the wal file. This is because, for a system
68332      ** where (minFrame < iSnapshot < maxFrame), a checkpointer may
68333      ** have omitted to checkpoint a frame earlier than minFrame in
68334      ** the file because there exists a frame after iSnapshot that
68335      ** is the same database page.  */
68336      pWal->minFrame = 1;
68337
68338      if( rc!=SQLITE_OK ){
68339        sqlite3WalEndReadTransaction(pWal);
68340      }
68341    }
68342  }
68343
68344  /* Release the shared CKPT lock obtained above. */
68345  if( ckptLock ){
68346    assert( pSnapshot );
68347    walUnlockShared(pWal, WAL_CKPT_LOCK);
68348  }
68349#endif
68350  return rc;
68351}
68352
68353/*
68354** Begin a read transaction on the database.
68355**
68356** This routine used to be called sqlite3OpenSnapshot() and with good reason:
68357** it takes a snapshot of the state of the WAL and wal-index for the current
68358** instant in time.  The current thread will continue to use this snapshot.
68359** Other threads might append new content to the WAL and wal-index but
68360** that extra content is ignored by the current thread.
68361**
68362** If the database contents have changes since the previous read
68363** transaction, then *pChanged is set to 1 before returning.  The
68364** Pager layer will use this to know that its cache is stale and
68365** needs to be flushed.
68366*/
68367SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
68368  int rc;
68369  SEH_TRY {
68370    rc = walBeginReadTransaction(pWal, pChanged);
68371  }
68372  SEH_EXCEPT( rc = walHandleException(pWal); )
68373  return rc;
68374}
68375
68376/*
68377** Finish with a read transaction.  All this does is release the
68378** read-lock.
68379*/
68380SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
68381  sqlite3WalEndWriteTransaction(pWal);
68382  if( pWal->readLock>=0 ){
68383    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
68384    pWal->readLock = -1;
68385  }
68386}
68387
68388/*
68389** Search the wal file for page pgno. If found, set *piRead to the frame that
68390** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
68391** to zero.
68392**
68393** Return SQLITE_OK if successful, or an error code if an error occurs. If an
68394** error does occur, the final value of *piRead is undefined.
68395*/
68396static int walFindFrame(
68397  Wal *pWal,                      /* WAL handle */
68398  Pgno pgno,                      /* Database page number to read data for */
68399  u32 *piRead                     /* OUT: Frame number (or zero) */
68400){
68401  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
68402  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
68403  int iHash;                      /* Used to loop through N hash tables */
68404  int iMinHash;
68405
68406  /* This routine is only be called from within a read transaction. */
68407  assert( pWal->readLock>=0 || pWal->lockError );
68408
68409  /* If the "last page" field of the wal-index header snapshot is 0, then
68410  ** no data will be read from the wal under any circumstances. Return early
68411  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
68412  ** then the WAL is ignored by the reader so return early, as if the
68413  ** WAL were empty.
68414  */
68415  if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
68416    *piRead = 0;
68417    return SQLITE_OK;
68418  }
68419
68420  /* Search the hash table or tables for an entry matching page number
68421  ** pgno. Each iteration of the following for() loop searches one
68422  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
68423  **
68424  ** This code might run concurrently to the code in walIndexAppend()
68425  ** that adds entries to the wal-index (and possibly to this hash
68426  ** table). This means the value just read from the hash
68427  ** slot (aHash[iKey]) may have been added before or after the
68428  ** current read transaction was opened. Values added after the
68429  ** read transaction was opened may have been written incorrectly -
68430  ** i.e. these slots may contain garbage data. However, we assume
68431  ** that any slots written before the current read transaction was
68432  ** opened remain unmodified.
68433  **
68434  ** For the reasons above, the if(...) condition featured in the inner
68435  ** loop of the following block is more stringent that would be required
68436  ** if we had exclusive access to the hash-table:
68437  **
68438  **   (aPgno[iFrame]==pgno):
68439  **     This condition filters out normal hash-table collisions.
68440  **
68441  **   (iFrame<=iLast):
68442  **     This condition filters out entries that were added to the hash
68443  **     table after the current read-transaction had started.
68444  */
68445  iMinHash = walFramePage(pWal->minFrame);
68446  for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
68447    WalHashLoc sLoc;              /* Hash table location */
68448    int iKey;                     /* Hash slot index */
68449    int nCollide;                 /* Number of hash collisions remaining */
68450    int rc;                       /* Error code */
68451    u32 iH;
68452
68453    rc = walHashGet(pWal, iHash, &sLoc);
68454    if( rc!=SQLITE_OK ){
68455      return rc;
68456    }
68457    nCollide = HASHTABLE_NSLOT;
68458    iKey = walHash(pgno);
68459    SEH_INJECT_FAULT;
68460    while( (iH = AtomicLoad(&sLoc.aHash[iKey]))!=0 ){
68461      u32 iFrame = iH + sLoc.iZero;
68462      if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH-1]==pgno ){
68463        assert( iFrame>iRead || CORRUPT_DB );
68464        iRead = iFrame;
68465      }
68466      if( (nCollide--)==0 ){
68467        *piRead = 0;
68468        return SQLITE_CORRUPT_BKPT;
68469      }
68470      iKey = walNextHash(iKey);
68471    }
68472    if( iRead ) break;
68473  }
68474
68475#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
68476  /* If expensive assert() statements are available, do a linear search
68477  ** of the wal-index file content. Make sure the results agree with the
68478  ** result obtained using the hash indexes above.  */
68479  {
68480    u32 iRead2 = 0;
68481    u32 iTest;
68482    assert( pWal->bShmUnreliable || pWal->minFrame>0 );
68483    for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
68484      if( walFramePgno(pWal, iTest)==pgno ){
68485        iRead2 = iTest;
68486        break;
68487      }
68488    }
68489    assert( iRead==iRead2 );
68490  }
68491#endif
68492
68493  *piRead = iRead;
68494  return SQLITE_OK;
68495}
68496
68497/*
68498** Search the wal file for page pgno. If found, set *piRead to the frame that
68499** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
68500** to zero.
68501**
68502** Return SQLITE_OK if successful, or an error code if an error occurs. If an
68503** error does occur, the final value of *piRead is undefined.
68504**
68505** The difference between this function and walFindFrame() is that this
68506** function wraps walFindFrame() in an SEH_TRY{...} block.
68507*/
68508SQLITE_PRIVATE int sqlite3WalFindFrame(
68509  Wal *pWal,                      /* WAL handle */
68510  Pgno pgno,                      /* Database page number to read data for */
68511  u32 *piRead                     /* OUT: Frame number (or zero) */
68512){
68513  int rc;
68514  SEH_TRY {
68515    rc = walFindFrame(pWal, pgno, piRead);
68516  }
68517  SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
68518  return rc;
68519}
68520
68521/*
68522** Read the contents of frame iRead from the wal file into buffer pOut
68523** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
68524** error code otherwise.
68525*/
68526SQLITE_PRIVATE int sqlite3WalReadFrame(
68527  Wal *pWal,                      /* WAL handle */
68528  u32 iRead,                      /* Frame to read */
68529  int nOut,                       /* Size of buffer pOut in bytes */
68530  u8 *pOut                        /* Buffer to write page data to */
68531){
68532  int sz;
68533  i64 iOffset;
68534  sz = pWal->hdr.szPage;
68535  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
68536  testcase( sz<=32768 );
68537  testcase( sz>=65536 );
68538  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
68539  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
68540  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
68541}
68542
68543/*
68544** Return the size of the database in pages (or zero, if unknown).
68545*/
68546SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
68547  if( pWal && ALWAYS(pWal->readLock>=0) ){
68548    return pWal->hdr.nPage;
68549  }
68550  return 0;
68551}
68552
68553
68554/*
68555** This function starts a write transaction on the WAL.
68556**
68557** A read transaction must have already been started by a prior call
68558** to sqlite3WalBeginReadTransaction().
68559**
68560** If another thread or process has written into the database since
68561** the read transaction was started, then it is not possible for this
68562** thread to write as doing so would cause a fork.  So this routine
68563** returns SQLITE_BUSY in that case and no write transaction is started.
68564**
68565** There can only be a single writer active at a time.
68566*/
68567SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
68568  int rc;
68569
68570#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
68571  /* If the write-lock is already held, then it was obtained before the
68572  ** read-transaction was even opened, making this call a no-op.
68573  ** Return early. */
68574  if( pWal->writeLock ){
68575    assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) );
68576    return SQLITE_OK;
68577  }
68578#endif
68579
68580  /* Cannot start a write transaction without first holding a read
68581  ** transaction. */
68582  assert( pWal->readLock>=0 );
68583  assert( pWal->writeLock==0 && pWal->iReCksum==0 );
68584
68585  if( pWal->readOnly ){
68586    return SQLITE_READONLY;
68587  }
68588
68589  /* Only one writer allowed at a time.  Get the write lock.  Return
68590  ** SQLITE_BUSY if unable.
68591  */
68592  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
68593  if( rc ){
68594    return rc;
68595  }
68596  pWal->writeLock = 1;
68597
68598  /* If another connection has written to the database file since the
68599  ** time the read transaction on this connection was started, then
68600  ** the write is disallowed.
68601  */
68602  SEH_TRY {
68603    if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
68604      rc = SQLITE_BUSY_SNAPSHOT;
68605    }
68606  }
68607  SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
68608
68609  if( rc!=SQLITE_OK ){
68610    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
68611    pWal->writeLock = 0;
68612  }
68613  return rc;
68614}
68615
68616/*
68617** End a write transaction.  The commit has already been done.  This
68618** routine merely releases the lock.
68619*/
68620SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
68621  if( pWal->writeLock ){
68622    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
68623    pWal->writeLock = 0;
68624    pWal->iReCksum = 0;
68625    pWal->truncateOnCommit = 0;
68626  }
68627  return SQLITE_OK;
68628}
68629
68630/*
68631** If any data has been written (but not committed) to the log file, this
68632** function moves the write-pointer back to the start of the transaction.
68633**
68634** Additionally, the callback function is invoked for each frame written
68635** to the WAL since the start of the transaction. If the callback returns
68636** other than SQLITE_OK, it is not invoked again and the error code is
68637** returned to the caller.
68638**
68639** Otherwise, if the callback function does not return an error, this
68640** function returns SQLITE_OK.
68641*/
68642SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
68643  int rc = SQLITE_OK;
68644  if( ALWAYS(pWal->writeLock) ){
68645    Pgno iMax = pWal->hdr.mxFrame;
68646    Pgno iFrame;
68647
68648    SEH_TRY {
68649      /* Restore the clients cache of the wal-index header to the state it
68650      ** was in before the client began writing to the database.
68651      */
68652      memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
68653
68654      for(iFrame=pWal->hdr.mxFrame+1;
68655          ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
68656          iFrame++
68657      ){
68658        /* This call cannot fail. Unless the page for which the page number
68659        ** is passed as the second argument is (a) in the cache and
68660        ** (b) has an outstanding reference, then xUndo is either a no-op
68661        ** (if (a) is false) or simply expels the page from the cache (if (b)
68662        ** is false).
68663        **
68664        ** If the upper layer is doing a rollback, it is guaranteed that there
68665        ** are no outstanding references to any page other than page 1. And
68666        ** page 1 is never written to the log until the transaction is
68667        ** committed. As a result, the call to xUndo may not fail.
68668        */
68669        assert( walFramePgno(pWal, iFrame)!=1 );
68670        rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
68671      }
68672      if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
68673    }
68674    SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
68675  }
68676  return rc;
68677}
68678
68679/*
68680** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
68681** values. This function populates the array with values required to
68682** "rollback" the write position of the WAL handle back to the current
68683** point in the event of a savepoint rollback (via WalSavepointUndo()).
68684*/
68685SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
68686  assert( pWal->writeLock );
68687  aWalData[0] = pWal->hdr.mxFrame;
68688  aWalData[1] = pWal->hdr.aFrameCksum[0];
68689  aWalData[2] = pWal->hdr.aFrameCksum[1];
68690  aWalData[3] = pWal->nCkpt;
68691}
68692
68693/*
68694** Move the write position of the WAL back to the point identified by
68695** the values in the aWalData[] array. aWalData must point to an array
68696** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
68697** by a call to WalSavepoint().
68698*/
68699SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
68700  int rc = SQLITE_OK;
68701
68702  assert( pWal->writeLock );
68703  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
68704
68705  if( aWalData[3]!=pWal->nCkpt ){
68706    /* This savepoint was opened immediately after the write-transaction
68707    ** was started. Right after that, the writer decided to wrap around
68708    ** to the start of the log. Update the savepoint values to match.
68709    */
68710    aWalData[0] = 0;
68711    aWalData[3] = pWal->nCkpt;
68712  }
68713
68714  if( aWalData[0]<pWal->hdr.mxFrame ){
68715    pWal->hdr.mxFrame = aWalData[0];
68716    pWal->hdr.aFrameCksum[0] = aWalData[1];
68717    pWal->hdr.aFrameCksum[1] = aWalData[2];
68718    SEH_TRY {
68719      walCleanupHash(pWal);
68720    }
68721    SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
68722  }
68723
68724  return rc;
68725}
68726
68727/*
68728** This function is called just before writing a set of frames to the log
68729** file (see sqlite3WalFrames()). It checks to see if, instead of appending
68730** to the current log file, it is possible to overwrite the start of the
68731** existing log file with the new frames (i.e. "reset" the log). If so,
68732** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
68733** unchanged.
68734**
68735** SQLITE_OK is returned if no error is encountered (regardless of whether
68736** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
68737** if an error occurs.
68738*/
68739static int walRestartLog(Wal *pWal){
68740  int rc = SQLITE_OK;
68741  int cnt;
68742
68743  if( pWal->readLock==0 ){
68744    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
68745    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
68746    if( pInfo->nBackfill>0 ){
68747      u32 salt1;
68748      sqlite3_randomness(4, &salt1);
68749      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
68750      if( rc==SQLITE_OK ){
68751        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
68752        ** readers are currently using the WAL), then the transactions
68753        ** frames will overwrite the start of the existing log. Update the
68754        ** wal-index header to reflect this.
68755        **
68756        ** In theory it would be Ok to update the cache of the header only
68757        ** at this point. But updating the actual wal-index header is also
68758        ** safe and means there is no special case for sqlite3WalUndo()
68759        ** to handle if this transaction is rolled back.  */
68760        walRestartHdr(pWal, salt1);
68761        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
68762      }else if( rc!=SQLITE_BUSY ){
68763        return rc;
68764      }
68765    }
68766    walUnlockShared(pWal, WAL_READ_LOCK(0));
68767    pWal->readLock = -1;
68768    cnt = 0;
68769    do{
68770      int notUsed;
68771      rc = walTryBeginRead(pWal, &notUsed, 1, &cnt);
68772    }while( rc==WAL_RETRY );
68773    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
68774    testcase( (rc&0xff)==SQLITE_IOERR );
68775    testcase( rc==SQLITE_PROTOCOL );
68776    testcase( rc==SQLITE_OK );
68777  }
68778  return rc;
68779}
68780
68781/*
68782** Information about the current state of the WAL file and where
68783** the next fsync should occur - passed from sqlite3WalFrames() into
68784** walWriteToLog().
68785*/
68786typedef struct WalWriter {
68787  Wal *pWal;                   /* The complete WAL information */
68788  sqlite3_file *pFd;           /* The WAL file to which we write */
68789  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
68790  int syncFlags;               /* Flags for the fsync */
68791  int szPage;                  /* Size of one page */
68792} WalWriter;
68793
68794/*
68795** Write iAmt bytes of content into the WAL file beginning at iOffset.
68796** Do a sync when crossing the p->iSyncPoint boundary.
68797**
68798** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
68799** first write the part before iSyncPoint, then sync, then write the
68800** rest.
68801*/
68802static int walWriteToLog(
68803  WalWriter *p,              /* WAL to write to */
68804  void *pContent,            /* Content to be written */
68805  int iAmt,                  /* Number of bytes to write */
68806  sqlite3_int64 iOffset      /* Start writing at this offset */
68807){
68808  int rc;
68809  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
68810    int iFirstAmt = (int)(p->iSyncPoint - iOffset);
68811    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
68812    if( rc ) return rc;
68813    iOffset += iFirstAmt;
68814    iAmt -= iFirstAmt;
68815    pContent = (void*)(iFirstAmt + (char*)pContent);
68816    assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
68817    rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
68818    if( iAmt==0 || rc ) return rc;
68819  }
68820  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
68821  return rc;
68822}
68823
68824/*
68825** Write out a single frame of the WAL
68826*/
68827static int walWriteOneFrame(
68828  WalWriter *p,               /* Where to write the frame */
68829  PgHdr *pPage,               /* The page of the frame to be written */
68830  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
68831  sqlite3_int64 iOffset       /* Byte offset at which to write */
68832){
68833  int rc;                         /* Result code from subfunctions */
68834  void *pData;                    /* Data actually written */
68835  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
68836  pData = pPage->pData;
68837  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
68838  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
68839  if( rc ) return rc;
68840  /* Write the page data */
68841  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
68842  return rc;
68843}
68844
68845/*
68846** This function is called as part of committing a transaction within which
68847** one or more frames have been overwritten. It updates the checksums for
68848** all frames written to the wal file by the current transaction starting
68849** with the earliest to have been overwritten.
68850**
68851** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
68852*/
68853static int walRewriteChecksums(Wal *pWal, u32 iLast){
68854  const int szPage = pWal->szPage;/* Database page size */
68855  int rc = SQLITE_OK;             /* Return code */
68856  u8 *aBuf;                       /* Buffer to load data from wal file into */
68857  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */
68858  u32 iRead;                      /* Next frame to read from wal file */
68859  i64 iCksumOff;
68860
68861  aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
68862  if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
68863
68864  /* Find the checksum values to use as input for the recalculating the
68865  ** first checksum. If the first frame is frame 1 (implying that the current
68866  ** transaction restarted the wal file), these values must be read from the
68867  ** wal-file header. Otherwise, read them from the frame header of the
68868  ** previous frame.  */
68869  assert( pWal->iReCksum>0 );
68870  if( pWal->iReCksum==1 ){
68871    iCksumOff = 24;
68872  }else{
68873    iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
68874  }
68875  rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
68876  pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
68877  pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
68878
68879  iRead = pWal->iReCksum;
68880  pWal->iReCksum = 0;
68881  for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
68882    i64 iOff = walFrameOffset(iRead, szPage);
68883    rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
68884    if( rc==SQLITE_OK ){
68885      u32 iPgno, nDbSize;
68886      iPgno = sqlite3Get4byte(aBuf);
68887      nDbSize = sqlite3Get4byte(&aBuf[4]);
68888
68889      walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
68890      rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
68891    }
68892  }
68893
68894  sqlite3_free(aBuf);
68895  return rc;
68896}
68897
68898/*
68899** Write a set of frames to the log. The caller must hold the write-lock
68900** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
68901*/
68902static int walFrames(
68903  Wal *pWal,                      /* Wal handle to write to */
68904  int szPage,                     /* Database page-size in bytes */
68905  PgHdr *pList,                   /* List of dirty pages to write */
68906  Pgno nTruncate,                 /* Database size after this commit */
68907  int isCommit,                   /* True if this is a commit */
68908  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
68909){
68910  int rc;                         /* Used to catch return codes */
68911  u32 iFrame;                     /* Next frame address */
68912  PgHdr *p;                       /* Iterator to run through pList with. */
68913  PgHdr *pLast = 0;               /* Last frame in list */
68914  int nExtra = 0;                 /* Number of extra copies of last page */
68915  int szFrame;                    /* The size of a single frame */
68916  i64 iOffset;                    /* Next byte to write in WAL file */
68917  WalWriter w;                    /* The writer */
68918  u32 iFirst = 0;                 /* First frame that may be overwritten */
68919  WalIndexHdr *pLive;             /* Pointer to shared header */
68920
68921  assert( pList );
68922  assert( pWal->writeLock );
68923
68924  /* If this frame set completes a transaction, then nTruncate>0.  If
68925  ** nTruncate==0 then this frame set does not complete the transaction. */
68926  assert( (isCommit!=0)==(nTruncate!=0) );
68927
68928#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
68929  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
68930    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
68931              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
68932  }
68933#endif
68934
68935  pLive = (WalIndexHdr*)walIndexHdr(pWal);
68936  if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
68937    iFirst = pLive->mxFrame+1;
68938  }
68939
68940  /* See if it is possible to write these frames into the start of the
68941  ** log file, instead of appending to it at pWal->hdr.mxFrame.
68942  */
68943  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
68944    return rc;
68945  }
68946
68947  /* If this is the first frame written into the log, write the WAL
68948  ** header to the start of the WAL file. See comments at the top of
68949  ** this source file for a description of the WAL header format.
68950  */
68951  iFrame = pWal->hdr.mxFrame;
68952  if( iFrame==0 ){
68953    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
68954    u32 aCksum[2];                /* Checksum for wal-header */
68955
68956    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
68957    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
68958    sqlite3Put4byte(&aWalHdr[8], szPage);
68959    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
68960    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
68961    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
68962    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
68963    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
68964    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
68965
68966    pWal->szPage = szPage;
68967    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
68968    pWal->hdr.aFrameCksum[0] = aCksum[0];
68969    pWal->hdr.aFrameCksum[1] = aCksum[1];
68970    pWal->truncateOnCommit = 1;
68971
68972    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
68973    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
68974    if( rc!=SQLITE_OK ){
68975      return rc;
68976    }
68977
68978    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
68979    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
68980    ** an out-of-order write following a WAL restart could result in
68981    ** database corruption.  See the ticket:
68982    **
68983    **     https://sqlite.org/src/info/ff5be73dee
68984    */
68985    if( pWal->syncHeader ){
68986      rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
68987      if( rc ) return rc;
68988    }
68989  }
68990  if( (int)pWal->szPage!=szPage ){
68991    return SQLITE_CORRUPT_BKPT;  /* TH3 test case: cov1/corrupt155.test */
68992  }
68993
68994  /* Setup information needed to write frames into the WAL */
68995  w.pWal = pWal;
68996  w.pFd = pWal->pWalFd;
68997  w.iSyncPoint = 0;
68998  w.syncFlags = sync_flags;
68999  w.szPage = szPage;
69000  iOffset = walFrameOffset(iFrame+1, szPage);
69001  szFrame = szPage + WAL_FRAME_HDRSIZE;
69002
69003  /* Write all frames into the log file exactly once */
69004  for(p=pList; p; p=p->pDirty){
69005    int nDbSize;   /* 0 normally.  Positive == commit flag */
69006
69007    /* Check if this page has already been written into the wal file by
69008    ** the current transaction. If so, overwrite the existing frame and
69009    ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
69010    ** checksums must be recomputed when the transaction is committed.  */
69011    if( iFirst && (p->pDirty || isCommit==0) ){
69012      u32 iWrite = 0;
69013      VVA_ONLY(rc =) walFindFrame(pWal, p->pgno, &iWrite);
69014      assert( rc==SQLITE_OK || iWrite==0 );
69015      if( iWrite>=iFirst ){
69016        i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
69017        void *pData;
69018        if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
69019          pWal->iReCksum = iWrite;
69020        }
69021        pData = p->pData;
69022        rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
69023        if( rc ) return rc;
69024        p->flags &= ~PGHDR_WAL_APPEND;
69025        continue;
69026      }
69027    }
69028
69029    iFrame++;
69030    assert( iOffset==walFrameOffset(iFrame, szPage) );
69031    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
69032    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
69033    if( rc ) return rc;
69034    pLast = p;
69035    iOffset += szFrame;
69036    p->flags |= PGHDR_WAL_APPEND;
69037  }
69038
69039  /* Recalculate checksums within the wal file if required. */
69040  if( isCommit && pWal->iReCksum ){
69041    rc = walRewriteChecksums(pWal, iFrame);
69042    if( rc ) return rc;
69043  }
69044
69045  /* If this is the end of a transaction, then we might need to pad
69046  ** the transaction and/or sync the WAL file.
69047  **
69048  ** Padding and syncing only occur if this set of frames complete a
69049  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
69050  ** or synchronous==OFF, then no padding or syncing are needed.
69051  **
69052  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
69053  ** needed and only the sync is done.  If padding is needed, then the
69054  ** final frame is repeated (with its commit mark) until the next sector
69055  ** boundary is crossed.  Only the part of the WAL prior to the last
69056  ** sector boundary is synced; the part of the last frame that extends
69057  ** past the sector boundary is written after the sync.
69058  */
69059  if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
69060    int bSync = 1;
69061    if( pWal->padToSectorBoundary ){
69062      int sectorSize = sqlite3SectorSize(pWal->pWalFd);
69063      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
69064      bSync = (w.iSyncPoint==iOffset);
69065      testcase( bSync );
69066      while( iOffset<w.iSyncPoint ){
69067        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
69068        if( rc ) return rc;
69069        iOffset += szFrame;
69070        nExtra++;
69071        assert( pLast!=0 );
69072      }
69073    }
69074    if( bSync ){
69075      assert( rc==SQLITE_OK );
69076      rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
69077    }
69078  }
69079
69080  /* If this frame set completes the first transaction in the WAL and
69081  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
69082  ** journal size limit, if possible.
69083  */
69084  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
69085    i64 sz = pWal->mxWalSize;
69086    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
69087      sz = walFrameOffset(iFrame+nExtra+1, szPage);
69088    }
69089    walLimitSize(pWal, sz);
69090    pWal->truncateOnCommit = 0;
69091  }
69092
69093  /* Append data to the wal-index. It is not necessary to lock the
69094  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
69095  ** guarantees that there are no other writers, and no data that may
69096  ** be in use by existing readers is being overwritten.
69097  */
69098  iFrame = pWal->hdr.mxFrame;
69099  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
69100    if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
69101    iFrame++;
69102    rc = walIndexAppend(pWal, iFrame, p->pgno);
69103  }
69104  assert( pLast!=0 || nExtra==0 );
69105  while( rc==SQLITE_OK && nExtra>0 ){
69106    iFrame++;
69107    nExtra--;
69108    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
69109  }
69110
69111  if( rc==SQLITE_OK ){
69112    /* Update the private copy of the header. */
69113    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
69114    testcase( szPage<=32768 );
69115    testcase( szPage>=65536 );
69116    pWal->hdr.mxFrame = iFrame;
69117    if( isCommit ){
69118      pWal->hdr.iChange++;
69119      pWal->hdr.nPage = nTruncate;
69120    }
69121    /* If this is a commit, update the wal-index header too. */
69122    if( isCommit ){
69123      walIndexWriteHdr(pWal);
69124      pWal->iCallback = iFrame;
69125    }
69126  }
69127
69128  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
69129  return rc;
69130}
69131
69132/*
69133** Write a set of frames to the log. The caller must hold the write-lock
69134** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
69135**
69136** The difference between this function and walFrames() is that this
69137** function wraps walFrames() in an SEH_TRY{...} block.
69138*/
69139SQLITE_PRIVATE int sqlite3WalFrames(
69140  Wal *pWal,                      /* Wal handle to write to */
69141  int szPage,                     /* Database page-size in bytes */
69142  PgHdr *pList,                   /* List of dirty pages to write */
69143  Pgno nTruncate,                 /* Database size after this commit */
69144  int isCommit,                   /* True if this is a commit */
69145  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
69146){
69147  int rc;
69148  SEH_TRY {
69149    rc = walFrames(pWal, szPage, pList, nTruncate, isCommit, sync_flags);
69150  }
69151  SEH_EXCEPT( rc = walHandleException(pWal); )
69152  return rc;
69153}
69154
69155/*
69156** This routine is called to implement sqlite3_wal_checkpoint() and
69157** related interfaces.
69158**
69159** Obtain a CHECKPOINT lock and then backfill as much information as
69160** we can from WAL into the database.
69161**
69162** If parameter xBusy is not NULL, it is a pointer to a busy-handler
69163** callback. In this case this function runs a blocking checkpoint.
69164*/
69165SQLITE_PRIVATE int sqlite3WalCheckpoint(
69166  Wal *pWal,                      /* Wal connection */
69167  sqlite3 *db,                    /* Check this handle's interrupt flag */
69168  int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
69169  int (*xBusy)(void*),            /* Function to call when busy */
69170  void *pBusyArg,                 /* Context argument for xBusyHandler */
69171  int sync_flags,                 /* Flags to sync db file with (or 0) */
69172  int nBuf,                       /* Size of temporary buffer */
69173  u8 *zBuf,                       /* Temporary buffer to use */
69174  int *pnLog,                     /* OUT: Number of frames in WAL */
69175  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
69176){
69177  int rc;                         /* Return code */
69178  int isChanged = 0;              /* True if a new wal-index header is loaded */
69179  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
69180  int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
69181
69182  assert( pWal->ckptLock==0 );
69183  assert( pWal->writeLock==0 );
69184
69185  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
69186  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
69187  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
69188
69189  if( pWal->readOnly ) return SQLITE_READONLY;
69190  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
69191
69192  /* Enable blocking locks, if possible. */
69193  sqlite3WalDb(pWal, db);
69194  if( xBusy2 ) (void)walEnableBlocking(pWal);
69195
69196  /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
69197  ** "checkpoint" lock on the database file.
69198  ** EVIDENCE-OF: R-10421-19736 If any other process is running a
69199  ** checkpoint operation at the same time, the lock cannot be obtained and
69200  ** SQLITE_BUSY is returned.
69201  ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
69202  ** it will not be invoked in this case.
69203  */
69204  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
69205  testcase( rc==SQLITE_BUSY );
69206  testcase( rc!=SQLITE_OK && xBusy2!=0 );
69207  if( rc==SQLITE_OK ){
69208    pWal->ckptLock = 1;
69209
69210    /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
69211    ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
69212    ** file.
69213    **
69214    ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
69215    ** immediately, and a busy-handler is configured, it is invoked and the
69216    ** writer lock retried until either the busy-handler returns 0 or the
69217    ** lock is successfully obtained.
69218    */
69219    if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
69220      rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1);
69221      if( rc==SQLITE_OK ){
69222        pWal->writeLock = 1;
69223      }else if( rc==SQLITE_BUSY ){
69224        eMode2 = SQLITE_CHECKPOINT_PASSIVE;
69225        xBusy2 = 0;
69226        rc = SQLITE_OK;
69227      }
69228    }
69229  }
69230
69231
69232  /* Read the wal-index header. */
69233  SEH_TRY {
69234    if( rc==SQLITE_OK ){
69235      /* For a passive checkpoint, do not re-enable blocking locks after
69236      ** reading the wal-index header. A passive checkpoint should not block
69237      ** or invoke the busy handler. The only lock such a checkpoint may
69238      ** attempt to obtain is a lock on a read-slot, and it should give up
69239      ** immediately and do a partial checkpoint if it cannot obtain it. */
69240      walDisableBlocking(pWal);
69241      rc = walIndexReadHdr(pWal, &isChanged);
69242      if( eMode2!=SQLITE_CHECKPOINT_PASSIVE ) (void)walEnableBlocking(pWal);
69243      if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
69244        sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
69245      }
69246    }
69247
69248    /* Copy data from the log to the database file. */
69249    if( rc==SQLITE_OK ){
69250      if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
69251        rc = SQLITE_CORRUPT_BKPT;
69252      }else{
69253        rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags,zBuf);
69254      }
69255
69256      /* If no error occurred, set the output variables. */
69257      if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
69258        if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
69259        SEH_INJECT_FAULT;
69260        if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
69261      }
69262    }
69263  }
69264  SEH_EXCEPT( rc = walHandleException(pWal); )
69265
69266  if( isChanged ){
69267    /* If a new wal-index header was loaded before the checkpoint was
69268    ** performed, then the pager-cache associated with pWal is now
69269    ** out of date. So zero the cached wal-index header to ensure that
69270    ** next time the pager opens a snapshot on this database it knows that
69271    ** the cache needs to be reset.
69272    */
69273    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
69274  }
69275
69276  walDisableBlocking(pWal);
69277  sqlite3WalDb(pWal, 0);
69278
69279  /* Release the locks. */
69280  sqlite3WalEndWriteTransaction(pWal);
69281  if( pWal->ckptLock ){
69282    walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
69283    pWal->ckptLock = 0;
69284  }
69285  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
69286#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
69287  if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
69288#endif
69289  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
69290}
69291
69292/* Return the value to pass to a sqlite3_wal_hook callback, the
69293** number of frames in the WAL at the point of the last commit since
69294** sqlite3WalCallback() was called.  If no commits have occurred since
69295** the last call, then return 0.
69296*/
69297SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
69298  u32 ret = 0;
69299  if( pWal ){
69300    ret = pWal->iCallback;
69301    pWal->iCallback = 0;
69302  }
69303  return (int)ret;
69304}
69305
69306/*
69307** This function is called to change the WAL subsystem into or out
69308** of locking_mode=EXCLUSIVE.
69309**
69310** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
69311** into locking_mode=NORMAL.  This means that we must acquire a lock
69312** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
69313** or if the acquisition of the lock fails, then return 0.  If the
69314** transition out of exclusive-mode is successful, return 1.  This
69315** operation must occur while the pager is still holding the exclusive
69316** lock on the main database file.
69317**
69318** If op is one, then change from locking_mode=NORMAL into
69319** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
69320** be released.  Return 1 if the transition is made and 0 if the
69321** WAL is already in exclusive-locking mode - meaning that this
69322** routine is a no-op.  The pager must already hold the exclusive lock
69323** on the main database file before invoking this operation.
69324**
69325** If op is negative, then do a dry-run of the op==1 case but do
69326** not actually change anything. The pager uses this to see if it
69327** should acquire the database exclusive lock prior to invoking
69328** the op==1 case.
69329*/
69330SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
69331  int rc;
69332  assert( pWal->writeLock==0 );
69333  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
69334
69335  /* pWal->readLock is usually set, but might be -1 if there was a
69336  ** prior error while attempting to acquire are read-lock. This cannot
69337  ** happen if the connection is actually in exclusive mode (as no xShmLock
69338  ** locks are taken in this case). Nor should the pager attempt to
69339  ** upgrade to exclusive-mode following such an error.
69340  */
69341#ifndef SQLITE_USE_SEH
69342  assert( pWal->readLock>=0 || pWal->lockError );
69343#endif
69344  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
69345
69346  if( op==0 ){
69347    if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
69348      pWal->exclusiveMode = WAL_NORMAL_MODE;
69349      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
69350        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
69351      }
69352      rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
69353    }else{
69354      /* Already in locking_mode=NORMAL */
69355      rc = 0;
69356    }
69357  }else if( op>0 ){
69358    assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
69359    assert( pWal->readLock>=0 );
69360    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
69361    pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
69362    rc = 1;
69363  }else{
69364    rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
69365  }
69366  return rc;
69367}
69368
69369/*
69370** Return true if the argument is non-NULL and the WAL module is using
69371** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
69372** WAL module is using shared-memory, return false.
69373*/
69374SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
69375  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
69376}
69377
69378#ifdef SQLITE_ENABLE_SNAPSHOT
69379/* Create a snapshot object.  The content of a snapshot is opaque to
69380** every other subsystem, so the WAL module can put whatever it needs
69381** in the object.
69382*/
69383SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
69384  int rc = SQLITE_OK;
69385  WalIndexHdr *pRet;
69386  static const u32 aZero[4] = { 0, 0, 0, 0 };
69387
69388  assert( pWal->readLock>=0 && pWal->writeLock==0 );
69389
69390  if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
69391    *ppSnapshot = 0;
69392    return SQLITE_ERROR;
69393  }
69394  pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
69395  if( pRet==0 ){
69396    rc = SQLITE_NOMEM_BKPT;
69397  }else{
69398    memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
69399    *ppSnapshot = (sqlite3_snapshot*)pRet;
69400  }
69401
69402  return rc;
69403}
69404
69405/* Try to open on pSnapshot when the next read-transaction starts
69406*/
69407SQLITE_PRIVATE void sqlite3WalSnapshotOpen(
69408  Wal *pWal,
69409  sqlite3_snapshot *pSnapshot
69410){
69411  pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
69412}
69413
69414/*
69415** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
69416** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
69417*/
69418SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
69419  WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
69420  WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
69421
69422  /* aSalt[0] is a copy of the value stored in the wal file header. It
69423  ** is incremented each time the wal file is restarted.  */
69424  if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
69425  if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
69426  if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
69427  if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
69428  return 0;
69429}
69430
69431/*
69432** The caller currently has a read transaction open on the database.
69433** This function takes a SHARED lock on the CHECKPOINTER slot and then
69434** checks if the snapshot passed as the second argument is still
69435** available. If so, SQLITE_OK is returned.
69436**
69437** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
69438** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
69439** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
69440** lock is released before returning.
69441*/
69442SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){
69443  int rc;
69444  SEH_TRY {
69445    rc = walLockShared(pWal, WAL_CKPT_LOCK);
69446    if( rc==SQLITE_OK ){
69447      WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot;
69448      if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
69449       || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
69450      ){
69451        rc = SQLITE_ERROR_SNAPSHOT;
69452        walUnlockShared(pWal, WAL_CKPT_LOCK);
69453      }
69454    }
69455  }
69456  SEH_EXCEPT( rc = walHandleException(pWal); )
69457  return rc;
69458}
69459
69460/*
69461** Release a lock obtained by an earlier successful call to
69462** sqlite3WalSnapshotCheck().
69463*/
69464SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal){
69465  assert( pWal );
69466  walUnlockShared(pWal, WAL_CKPT_LOCK);
69467}
69468
69469
69470#endif /* SQLITE_ENABLE_SNAPSHOT */
69471
69472#ifdef SQLITE_ENABLE_ZIPVFS
69473/*
69474** If the argument is not NULL, it points to a Wal object that holds a
69475** read-lock. This function returns the database page-size if it is known,
69476** or zero if it is not (or if pWal is NULL).
69477*/
69478SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
69479  assert( pWal==0 || pWal->readLock>=0 );
69480  return (pWal ? pWal->szPage : 0);
69481}
69482#endif
69483
69484/* Return the sqlite3_file object for the WAL file
69485*/
69486SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
69487  return pWal->pWalFd;
69488}
69489
69490#endif /* #ifndef SQLITE_OMIT_WAL */
69491
69492/************** End of wal.c *************************************************/
69493/************** Begin file btmutex.c *****************************************/
69494/*
69495** 2007 August 27
69496**
69497** The author disclaims copyright to this source code.  In place of
69498** a legal notice, here is a blessing:
69499**
69500**    May you do good and not evil.
69501**    May you find forgiveness for yourself and forgive others.
69502**    May you share freely, never taking more than you give.
69503**
69504*************************************************************************
69505**
69506** This file contains code used to implement mutexes on Btree objects.
69507** This code really belongs in btree.c.  But btree.c is getting too
69508** big and we want to break it down some.  This packaged seemed like
69509** a good breakout.
69510*/
69511/************** Include btreeInt.h in the middle of btmutex.c ****************/
69512/************** Begin file btreeInt.h ****************************************/
69513/*
69514** 2004 April 6
69515**
69516** The author disclaims copyright to this source code.  In place of
69517** a legal notice, here is a blessing:
69518**
69519**    May you do good and not evil.
69520**    May you find forgiveness for yourself and forgive others.
69521**    May you share freely, never taking more than you give.
69522**
69523*************************************************************************
69524** This file implements an external (disk-based) database using BTrees.
69525** For a detailed discussion of BTrees, refer to
69526**
69527**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
69528**     "Sorting And Searching", pages 473-480. Addison-Wesley
69529**     Publishing Company, Reading, Massachusetts.
69530**
69531** The basic idea is that each page of the file contains N database
69532** entries and N+1 pointers to subpages.
69533**
69534**   ----------------------------------------------------------------
69535**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
69536**   ----------------------------------------------------------------
69537**
69538** All of the keys on the page that Ptr(0) points to have values less
69539** than Key(0).  All of the keys on page Ptr(1) and its subpages have
69540** values greater than Key(0) and less than Key(1).  All of the keys
69541** on Ptr(N) and its subpages have values greater than Key(N-1).  And
69542** so forth.
69543**
69544** Finding a particular key requires reading O(log(M)) pages from the
69545** disk where M is the number of entries in the tree.
69546**
69547** In this implementation, a single file can hold one or more separate
69548** BTrees.  Each BTree is identified by the index of its root page.  The
69549** key and data for any entry are combined to form the "payload".  A
69550** fixed amount of payload can be carried directly on the database
69551** page.  If the payload is larger than the preset amount then surplus
69552** bytes are stored on overflow pages.  The payload for an entry
69553** and the preceding pointer are combined to form a "Cell".  Each
69554** page has a small header which contains the Ptr(N) pointer and other
69555** information such as the size of key and data.
69556**
69557** FORMAT DETAILS
69558**
69559** The file is divided into pages.  The first page is called page 1,
69560** the second is page 2, and so forth.  A page number of zero indicates
69561** "no such page".  The page size can be any power of 2 between 512 and 65536.
69562** Each page can be either a btree page, a freelist page, an overflow
69563** page, or a pointer-map page.
69564**
69565** The first page is always a btree page.  The first 100 bytes of the first
69566** page contain a special header (the "file header") that describes the file.
69567** The format of the file header is as follows:
69568**
69569**   OFFSET   SIZE    DESCRIPTION
69570**      0      16     Header string: "SQLite format 3\000"
69571**     16       2     Page size in bytes.  (1 means 65536)
69572**     18       1     File format write version
69573**     19       1     File format read version
69574**     20       1     Bytes of unused space at the end of each page
69575**     21       1     Max embedded payload fraction (must be 64)
69576**     22       1     Min embedded payload fraction (must be 32)
69577**     23       1     Min leaf payload fraction (must be 32)
69578**     24       4     File change counter
69579**     28       4     The size of the database in pages
69580**     32       4     First freelist page
69581**     36       4     Number of freelist pages in the file
69582**     40      60     15 4-byte meta values passed to higher layers
69583**
69584**     40       4     Schema cookie
69585**     44       4     File format of schema layer
69586**     48       4     Size of page cache
69587**     52       4     Largest root-page (auto/incr_vacuum)
69588**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
69589**     60       4     User version
69590**     64       4     Incremental vacuum mode
69591**     68       4     Application-ID
69592**     72      20     unused
69593**     92       4     The version-valid-for number
69594**     96       4     SQLITE_VERSION_NUMBER
69595**
69596** All of the integer values are big-endian (most significant byte first).
69597**
69598** The file change counter is incremented when the database is changed
69599** This counter allows other processes to know when the file has changed
69600** and thus when they need to flush their cache.
69601**
69602** The max embedded payload fraction is the amount of the total usable
69603** space in a page that can be consumed by a single cell for standard
69604** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
69605** is to limit the maximum cell size so that at least 4 cells will fit
69606** on one page.  Thus the default max embedded payload fraction is 64.
69607**
69608** If the payload for a cell is larger than the max payload, then extra
69609** payload is spilled to overflow pages.  Once an overflow page is allocated,
69610** as many bytes as possible are moved into the overflow pages without letting
69611** the cell size drop below the min embedded payload fraction.
69612**
69613** The min leaf payload fraction is like the min embedded payload fraction
69614** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
69615** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
69616** not specified in the header.
69617**
69618** Each btree pages is divided into three sections:  The header, the
69619** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
69620** file header that occurs before the page header.
69621**
69622**      |----------------|
69623**      | file header    |   100 bytes.  Page 1 only.
69624**      |----------------|
69625**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
69626**      |----------------|
69627**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
69628**      | array          |   |  Grows downward
69629**      |                |   v
69630**      |----------------|
69631**      | unallocated    |
69632**      | space          |
69633**      |----------------|   ^  Grows upwards
69634**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
69635**      | area           |   |  and free space fragments.
69636**      |----------------|
69637**
69638** The page headers looks like this:
69639**
69640**   OFFSET   SIZE     DESCRIPTION
69641**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
69642**      1       2      byte offset to the first freeblock
69643**      3       2      number of cells on this page
69644**      5       2      first byte of the cell content area
69645**      7       1      number of fragmented free bytes
69646**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
69647**
69648** The flags define the format of this btree page.  The leaf flag means that
69649** this page has no children.  The zerodata flag means that this page carries
69650** only keys and no data.  The intkey flag means that the key is an integer
69651** which is stored in the key size entry of the cell header rather than in
69652** the payload area.
69653**
69654** The cell pointer array begins on the first byte after the page header.
69655** The cell pointer array contains zero or more 2-byte numbers which are
69656** offsets from the beginning of the page to the cell content in the cell
69657** content area.  The cell pointers occur in sorted order.  The system strives
69658** to keep free space after the last cell pointer so that new cells can
69659** be easily added without having to defragment the page.
69660**
69661** Cell content is stored at the very end of the page and grows toward the
69662** beginning of the page.
69663**
69664** Unused space within the cell content area is collected into a linked list of
69665** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
69666** to the first freeblock is given in the header.  Freeblocks occur in
69667** increasing order.  Because a freeblock must be at least 4 bytes in size,
69668** any group of 3 or fewer unused bytes in the cell content area cannot
69669** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
69670** a fragment.  The total number of bytes in all fragments is recorded.
69671** in the page header at offset 7.
69672**
69673**    SIZE    DESCRIPTION
69674**      2     Byte offset of the next freeblock
69675**      2     Bytes in this freeblock
69676**
69677** Cells are of variable length.  Cells are stored in the cell content area at
69678** the end of the page.  Pointers to the cells are in the cell pointer array
69679** that immediately follows the page header.  Cells is not necessarily
69680** contiguous or in order, but cell pointers are contiguous and in order.
69681**
69682** Cell content makes use of variable length integers.  A variable
69683** length integer is 1 to 9 bytes where the lower 7 bits of each
69684** byte are used.  The integer consists of all bytes that have bit 8 set and
69685** the first byte with bit 8 clear.  The most significant byte of the integer
69686** appears first.  A variable-length integer may not be more than 9 bytes long.
69687** As a special case, all 8 bits of the 9th byte are used as data.  This
69688** allows a 64-bit integer to be encoded in 9 bytes.
69689**
69690**    0x00                      becomes  0x00000000
69691**    0x7f                      becomes  0x0000007f
69692**    0x81 0x00                 becomes  0x00000080
69693**    0x82 0x00                 becomes  0x00000100
69694**    0x80 0x7f                 becomes  0x0000007f
69695**    0x81 0x91 0xd1 0xac 0x78  becomes  0x12345678
69696**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
69697**
69698** Variable length integers are used for rowids and to hold the number of
69699** bytes of key and data in a btree cell.
69700**
69701** The content of a cell looks like this:
69702**
69703**    SIZE    DESCRIPTION
69704**      4     Page number of the left child. Omitted if leaf flag is set.
69705**     var    Number of bytes of data. Omitted if the zerodata flag is set.
69706**     var    Number of bytes of key. Or the key itself if intkey flag is set.
69707**      *     Payload
69708**      4     First page of the overflow chain.  Omitted if no overflow
69709**
69710** Overflow pages form a linked list.  Each page except the last is completely
69711** filled with data (pagesize - 4 bytes).  The last page can have as little
69712** as 1 byte of data.
69713**
69714**    SIZE    DESCRIPTION
69715**      4     Page number of next overflow page
69716**      *     Data
69717**
69718** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
69719** file header points to the first in a linked list of trunk page.  Each trunk
69720** page points to multiple leaf pages.  The content of a leaf page is
69721** unspecified.  A trunk page looks like this:
69722**
69723**    SIZE    DESCRIPTION
69724**      4     Page number of next trunk page
69725**      4     Number of leaf pointers on this page
69726**      *     zero or more pages numbers of leaves
69727*/
69728/* #include "sqliteInt.h" */
69729
69730
69731/* The following value is the maximum cell size assuming a maximum page
69732** size give above.
69733*/
69734#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
69735
69736/* The maximum number of cells on a single page of the database.  This
69737** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
69738** plus 2 bytes for the index to the cell in the page header).  Such
69739** small cells will be rare, but they are possible.
69740*/
69741#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
69742
69743/* Forward declarations */
69744typedef struct MemPage MemPage;
69745typedef struct BtLock BtLock;
69746typedef struct CellInfo CellInfo;
69747
69748/*
69749** This is a magic string that appears at the beginning of every
69750** SQLite database in order to identify the file as a real database.
69751**
69752** You can change this value at compile-time by specifying a
69753** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
69754** header must be exactly 16 bytes including the zero-terminator so
69755** the string itself should be 15 characters long.  If you change
69756** the header, then your custom library will not be able to read
69757** databases generated by the standard tools and the standard tools
69758** will not be able to read databases created by your custom library.
69759*/
69760#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
69761#  define SQLITE_FILE_HEADER "SQLite format 3"
69762#endif
69763
69764/*
69765** Page type flags.  An ORed combination of these flags appear as the
69766** first byte of on-disk image of every BTree page.
69767*/
69768#define PTF_INTKEY    0x01
69769#define PTF_ZERODATA  0x02
69770#define PTF_LEAFDATA  0x04
69771#define PTF_LEAF      0x08
69772
69773/*
69774** An instance of this object stores information about each a single database
69775** page that has been loaded into memory.  The information in this object
69776** is derived from the raw on-disk page content.
69777**
69778** As each database page is loaded into memory, the pager allocates an
69779** instance of this object and zeros the first 8 bytes.  (This is the
69780** "extra" information associated with each page of the pager.)
69781**
69782** Access to all fields of this structure is controlled by the mutex
69783** stored in MemPage.pBt->mutex.
69784*/
69785struct MemPage {
69786  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
69787  u8 intKey;           /* True if table b-trees.  False for index b-trees */
69788  u8 intKeyLeaf;       /* True if the leaf of an intKey table */
69789  Pgno pgno;           /* Page number for this page */
69790  /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
69791  ** is allocated. All fields that follow must be initialized before use */
69792  u8 leaf;             /* True if a leaf page */
69793  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
69794  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
69795  u8 max1bytePayload;  /* min(maxLocal,127) */
69796  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
69797  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
69798  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
69799  u16 cellOffset;      /* Index in aData of first cell pointer */
69800  int nFree;           /* Number of free bytes on the page. -1 for unknown */
69801  u16 nCell;           /* Number of cells on this page, local and ovfl */
69802  u16 maskPage;        /* Mask for page offset */
69803  u16 aiOvfl[4];       /* Insert the i-th overflow cell before the aiOvfl-th
69804                       ** non-overflow cell */
69805  u8 *apOvfl[4];       /* Pointers to the body of overflow cells */
69806  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
69807  u8 *aData;           /* Pointer to disk image of the page data */
69808  u8 *aDataEnd;        /* One byte past the end of the entire page - not just
69809                       ** the usable space, the entire page.  Used to prevent
69810                       ** corruption-induced buffer overflow. */
69811  u8 *aCellIdx;        /* The cell index area */
69812  u8 *aDataOfst;       /* Same as aData for leaves.  aData+4 for interior */
69813  DbPage *pDbPage;     /* Pager page handle */
69814  u16 (*xCellSize)(MemPage*,u8*);             /* cellSizePtr method */
69815  void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
69816};
69817
69818/*
69819** A linked list of the following structures is stored at BtShared.pLock.
69820** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
69821** is opened on the table with root page BtShared.iTable. Locks are removed
69822** from this list when a transaction is committed or rolled back, or when
69823** a btree handle is closed.
69824*/
69825struct BtLock {
69826  Btree *pBtree;        /* Btree handle holding this lock */
69827  Pgno iTable;          /* Root page of table */
69828  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
69829  BtLock *pNext;        /* Next in BtShared.pLock list */
69830};
69831
69832/* Candidate values for BtLock.eLock */
69833#define READ_LOCK     1
69834#define WRITE_LOCK    2
69835
69836/* A Btree handle
69837**
69838** A database connection contains a pointer to an instance of
69839** this object for every database file that it has open.  This structure
69840** is opaque to the database connection.  The database connection cannot
69841** see the internals of this structure and only deals with pointers to
69842** this structure.
69843**
69844** For some database files, the same underlying database cache might be
69845** shared between multiple connections.  In that case, each connection
69846** has it own instance of this object.  But each instance of this object
69847** points to the same BtShared object.  The database cache and the
69848** schema associated with the database file are all contained within
69849** the BtShared object.
69850**
69851** All fields in this structure are accessed under sqlite3.mutex.
69852** The pBt pointer itself may not be changed while there exists cursors
69853** in the referenced BtShared that point back to this Btree since those
69854** cursors have to go through this Btree to find their BtShared and
69855** they often do so without holding sqlite3.mutex.
69856*/
69857struct Btree {
69858  sqlite3 *db;       /* The database connection holding this btree */
69859  BtShared *pBt;     /* Sharable content of this btree */
69860  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
69861  u8 sharable;       /* True if we can share pBt with another db */
69862  u8 locked;         /* True if db currently has pBt locked */
69863  u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
69864  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
69865  int nBackup;       /* Number of backup operations reading this btree */
69866  u32 iBDataVersion; /* Combines with pBt->pPager->iDataVersion */
69867  Btree *pNext;      /* List of other sharable Btrees from the same db */
69868  Btree *pPrev;      /* Back pointer of the same list */
69869#ifdef SQLITE_DEBUG
69870  u64 nSeek;         /* Calls to sqlite3BtreeMovetoUnpacked() */
69871#endif
69872#ifndef SQLITE_OMIT_SHARED_CACHE
69873  BtLock lock;       /* Object used to lock page 1 */
69874#endif
69875};
69876
69877/*
69878** Btree.inTrans may take one of the following values.
69879**
69880** If the shared-data extension is enabled, there may be multiple users
69881** of the Btree structure. At most one of these may open a write transaction,
69882** but any number may have active read transactions.
69883**
69884** These values must match SQLITE_TXN_NONE, SQLITE_TXN_READ, and
69885** SQLITE_TXN_WRITE
69886*/
69887#define TRANS_NONE  0
69888#define TRANS_READ  1
69889#define TRANS_WRITE 2
69890
69891#if TRANS_NONE!=SQLITE_TXN_NONE
69892# error wrong numeric code for no-transaction
69893#endif
69894#if TRANS_READ!=SQLITE_TXN_READ
69895# error wrong numeric code for read-transaction
69896#endif
69897#if TRANS_WRITE!=SQLITE_TXN_WRITE
69898# error wrong numeric code for write-transaction
69899#endif
69900
69901
69902/*
69903** An instance of this object represents a single database file.
69904**
69905** A single database file can be in use at the same time by two
69906** or more database connections.  When two or more connections are
69907** sharing the same database file, each connection has it own
69908** private Btree object for the file and each of those Btrees points
69909** to this one BtShared object.  BtShared.nRef is the number of
69910** connections currently sharing this database file.
69911**
69912** Fields in this structure are accessed under the BtShared.mutex
69913** mutex, except for nRef and pNext which are accessed under the
69914** global SQLITE_MUTEX_STATIC_MAIN mutex.  The pPager field
69915** may not be modified once it is initially set as long as nRef>0.
69916** The pSchema field may be set once under BtShared.mutex and
69917** thereafter is unchanged as long as nRef>0.
69918**
69919** isPending:
69920**
69921**   If a BtShared client fails to obtain a write-lock on a database
69922**   table (because there exists one or more read-locks on the table),
69923**   the shared-cache enters 'pending-lock' state and isPending is
69924**   set to true.
69925**
69926**   The shared-cache leaves the 'pending lock' state when either of
69927**   the following occur:
69928**
69929**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
69930**     2) The number of locks held by other connections drops to zero.
69931**
69932**   while in the 'pending-lock' state, no connection may start a new
69933**   transaction.
69934**
69935**   This feature is included to help prevent writer-starvation.
69936*/
69937struct BtShared {
69938  Pager *pPager;        /* The page cache */
69939  sqlite3 *db;          /* Database connection currently using this Btree */
69940  BtCursor *pCursor;    /* A list of all open cursors */
69941  MemPage *pPage1;      /* First page of the database */
69942  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
69943#ifndef SQLITE_OMIT_AUTOVACUUM
69944  u8 autoVacuum;        /* True if auto-vacuum is enabled */
69945  u8 incrVacuum;        /* True if incr-vacuum is enabled */
69946  u8 bDoTruncate;       /* True to truncate db on commit */
69947#endif
69948  u8 inTransaction;     /* Transaction state */
69949  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
69950  u8 nReserveWanted;    /* Desired number of extra bytes per page */
69951  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
69952  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
69953  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
69954  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
69955  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
69956  u32 pageSize;         /* Total number of bytes on a page */
69957  u32 usableSize;       /* Number of usable bytes on each page */
69958  int nTransaction;     /* Number of open transactions (read + write) */
69959  u32 nPage;            /* Number of pages in the database */
69960  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
69961  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
69962  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
69963  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
69964#ifndef SQLITE_OMIT_SHARED_CACHE
69965  int nRef;             /* Number of references to this structure */
69966  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
69967  BtLock *pLock;        /* List of locks held on this shared-btree struct */
69968  Btree *pWriter;       /* Btree with currently open write transaction */
69969#endif
69970  u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
69971  int nPreformatSize;   /* Size of last cell written by TransferRow() */
69972};
69973
69974/*
69975** Allowed values for BtShared.btsFlags
69976*/
69977#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
69978#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
69979#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
69980#define BTS_OVERWRITE        0x0008   /* Overwrite deleted content with zeros */
69981#define BTS_FAST_SECURE      0x000c   /* Combination of the previous two */
69982#define BTS_INITIALLY_EMPTY  0x0010   /* Database was empty at trans start */
69983#define BTS_NO_WAL           0x0020   /* Do not open write-ahead-log files */
69984#define BTS_EXCLUSIVE        0x0040   /* pWriter has an exclusive lock */
69985#define BTS_PENDING          0x0080   /* Waiting for read-locks to clear */
69986
69987/*
69988** An instance of the following structure is used to hold information
69989** about a cell.  The parseCellPtr() function fills in this structure
69990** based on information extract from the raw disk page.
69991*/
69992struct CellInfo {
69993  i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
69994  u8 *pPayload;  /* Pointer to the start of payload */
69995  u32 nPayload;  /* Bytes of payload */
69996  u16 nLocal;    /* Amount of payload held locally, not on overflow */
69997  u16 nSize;     /* Size of the cell content on the main b-tree page */
69998};
69999
70000/*
70001** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
70002** this will be declared corrupt. This value is calculated based on a
70003** maximum database size of 2^31 pages a minimum fanout of 2 for a
70004** root-node and 3 for all other internal nodes.
70005**
70006** If a tree that appears to be taller than this is encountered, it is
70007** assumed that the database is corrupt.
70008*/
70009#define BTCURSOR_MAX_DEPTH 20
70010
70011/*
70012** A cursor is a pointer to a particular entry within a particular
70013** b-tree within a database file.
70014**
70015** The entry is identified by its MemPage and the index in
70016** MemPage.aCell[] of the entry.
70017**
70018** A single database file can be shared by two more database connections,
70019** but cursors cannot be shared.  Each cursor is associated with a
70020** particular database connection identified BtCursor.pBtree.db.
70021**
70022** Fields in this structure are accessed under the BtShared.mutex
70023** found at self->pBt->mutex.
70024**
70025** skipNext meaning:
70026** The meaning of skipNext depends on the value of eState:
70027**
70028**   eState            Meaning of skipNext
70029**   VALID             skipNext is meaningless and is ignored
70030**   INVALID           skipNext is meaningless and is ignored
70031**   SKIPNEXT          sqlite3BtreeNext() is a no-op if skipNext>0 and
70032**                     sqlite3BtreePrevious() is no-op if skipNext<0.
70033**   REQUIRESEEK       restoreCursorPosition() restores the cursor to
70034**                     eState=SKIPNEXT if skipNext!=0
70035**   FAULT             skipNext holds the cursor fault error code.
70036*/
70037struct BtCursor {
70038  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
70039  u8 curFlags;              /* zero or more BTCF_* flags defined below */
70040  u8 curPagerFlags;         /* Flags to send to sqlite3PagerGet() */
70041  u8 hints;                 /* As configured by CursorSetHints() */
70042  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
70043                   ** Error code if eState==CURSOR_FAULT */
70044  Btree *pBtree;            /* The Btree to which this cursor belongs */
70045  Pgno *aOverflow;          /* Cache of overflow page locations */
70046  void *pKey;               /* Saved key that was cursor last known position */
70047  /* All fields above are zeroed when the cursor is allocated.  See
70048  ** sqlite3BtreeCursorZero().  Fields that follow must be manually
70049  ** initialized. */
70050#define BTCURSOR_FIRST_UNINIT pBt   /* Name of first uninitialized field */
70051  BtShared *pBt;            /* The BtShared this cursor points to */
70052  BtCursor *pNext;          /* Forms a linked list of all cursors */
70053  CellInfo info;            /* A parse of the cell we are pointing at */
70054  i64 nKey;                 /* Size of pKey, or last integer key */
70055  Pgno pgnoRoot;            /* The root page of this tree */
70056  i8 iPage;                 /* Index of current page in apPage */
70057  u8 curIntKey;             /* Value of apPage[0]->intKey */
70058  u16 ix;                   /* Current index for apPage[iPage] */
70059  u16 aiIdx[BTCURSOR_MAX_DEPTH-1];     /* Current index in apPage[i] */
70060  struct KeyInfo *pKeyInfo;            /* Arg passed to comparison function */
70061  MemPage *pPage;                        /* Current page */
70062  MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
70063};
70064
70065/*
70066** Legal values for BtCursor.curFlags
70067*/
70068#define BTCF_WriteFlag    0x01   /* True if a write cursor */
70069#define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
70070#define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
70071#define BTCF_AtLast       0x08   /* Cursor is pointing to the last entry */
70072#define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
70073#define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
70074#define BTCF_Pinned       0x40   /* Cursor is busy and cannot be moved */
70075
70076/*
70077** Potential values for BtCursor.eState.
70078**
70079** CURSOR_INVALID:
70080**   Cursor does not point to a valid entry. This can happen (for example)
70081**   because the table is empty or because BtreeCursorFirst() has not been
70082**   called.
70083**
70084** CURSOR_VALID:
70085**   Cursor points to a valid entry. getPayload() etc. may be called.
70086**
70087** CURSOR_SKIPNEXT:
70088**   Cursor is valid except that the Cursor.skipNext field is non-zero
70089**   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
70090**   operation should be a no-op.
70091**
70092** CURSOR_REQUIRESEEK:
70093**   The table that this cursor was opened on still exists, but has been
70094**   modified since the cursor was last used. The cursor position is saved
70095**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
70096**   this state, restoreCursorPosition() can be called to attempt to
70097**   seek the cursor to the saved position.
70098**
70099** CURSOR_FAULT:
70100**   An unrecoverable error (an I/O error or a malloc failure) has occurred
70101**   on a different connection that shares the BtShared cache with this
70102**   cursor.  The error has left the cache in an inconsistent state.
70103**   Do nothing else with this cursor.  Any attempt to use the cursor
70104**   should return the error code stored in BtCursor.skipNext
70105*/
70106#define CURSOR_VALID             0
70107#define CURSOR_INVALID           1
70108#define CURSOR_SKIPNEXT          2
70109#define CURSOR_REQUIRESEEK       3
70110#define CURSOR_FAULT             4
70111
70112/*
70113** The database page the PENDING_BYTE occupies. This page is never used.
70114*/
70115#define PENDING_BYTE_PAGE(pBt)  ((Pgno)((PENDING_BYTE/((pBt)->pageSize))+1))
70116
70117/*
70118** These macros define the location of the pointer-map entry for a
70119** database page. The first argument to each is the number of usable
70120** bytes on each page of the database (often 1024). The second is the
70121** page number to look up in the pointer map.
70122**
70123** PTRMAP_PAGENO returns the database page number of the pointer-map
70124** page that stores the required pointer. PTRMAP_PTROFFSET returns
70125** the offset of the requested map entry.
70126**
70127** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
70128** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
70129** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
70130** this test.
70131*/
70132#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
70133#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
70134#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
70135
70136/*
70137** The pointer map is a lookup table that identifies the parent page for
70138** each child page in the database file.  The parent page is the page that
70139** contains a pointer to the child.  Every page in the database contains
70140** 0 or 1 parent pages.  (In this context 'database page' refers
70141** to any page that is not part of the pointer map itself.)  Each pointer map
70142** entry consists of a single byte 'type' and a 4 byte parent page number.
70143** The PTRMAP_XXX identifiers below are the valid types.
70144**
70145** The purpose of the pointer map is to facility moving pages from one
70146** position in the file to another as part of autovacuum.  When a page
70147** is moved, the pointer in its parent must be updated to point to the
70148** new location.  The pointer map is used to locate the parent page quickly.
70149**
70150** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
70151**                  used in this case.
70152**
70153** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
70154**                  is not used in this case.
70155**
70156** PTRMAP_OVERFLOW1: The database page is the first page in a list of
70157**                   overflow pages. The page number identifies the page that
70158**                   contains the cell with a pointer to this overflow page.
70159**
70160** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
70161**                   overflow pages. The page-number identifies the previous
70162**                   page in the overflow page list.
70163**
70164** PTRMAP_BTREE: The database page is a non-root btree page. The page number
70165**               identifies the parent page in the btree.
70166*/
70167#define PTRMAP_ROOTPAGE 1
70168#define PTRMAP_FREEPAGE 2
70169#define PTRMAP_OVERFLOW1 3
70170#define PTRMAP_OVERFLOW2 4
70171#define PTRMAP_BTREE 5
70172
70173/* A bunch of assert() statements to check the transaction state variables
70174** of handle p (type Btree*) are internally consistent.
70175*/
70176#define btreeIntegrity(p) \
70177  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
70178  assert( p->pBt->inTransaction>=p->inTrans );
70179
70180
70181/*
70182** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
70183** if the database supports auto-vacuum or not. Because it is used
70184** within an expression that is an argument to another macro
70185** (sqliteMallocRaw), it is not possible to use conditional compilation.
70186** So, this macro is defined instead.
70187*/
70188#ifndef SQLITE_OMIT_AUTOVACUUM
70189#define ISAUTOVACUUM(pBt) (pBt->autoVacuum)
70190#else
70191#define ISAUTOVACUUM(pBt) 0
70192#endif
70193
70194
70195/*
70196** This structure is passed around through all the PRAGMA integrity_check
70197** checking routines in order to keep track of some global state information.
70198**
70199** The aRef[] array is allocated so that there is 1 bit for each page in
70200** the database. As the integrity-check proceeds, for each page used in
70201** the database the corresponding bit is set. This allows integrity-check to
70202** detect pages that are used twice and orphaned pages (both of which
70203** indicate corruption).
70204*/
70205typedef struct IntegrityCk IntegrityCk;
70206struct IntegrityCk {
70207  BtShared *pBt;    /* The tree being checked out */
70208  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
70209  u8 *aPgRef;       /* 1 bit per page in the db (see above) */
70210  Pgno nCkPage;     /* Pages in the database.  0 for partial check */
70211  int mxErr;        /* Stop accumulating errors when this reaches zero */
70212  int nErr;         /* Number of messages written to zErrMsg so far */
70213  int rc;           /* SQLITE_OK, SQLITE_NOMEM, or SQLITE_INTERRUPT */
70214  u32 nStep;        /* Number of steps into the integrity_check process */
70215  const char *zPfx; /* Error message prefix */
70216  Pgno v0;          /* Value for first %u substitution in zPfx (root page) */
70217  Pgno v1;          /* Value for second %u substitution in zPfx (current pg) */
70218  int v2;           /* Value for third %d substitution in zPfx */
70219  StrAccum errMsg;  /* Accumulate the error message text here */
70220  u32 *heap;        /* Min-heap used for analyzing cell coverage */
70221  sqlite3 *db;      /* Database connection running the check */
70222  i64 nRow;         /* Number of rows visited in current tree */
70223};
70224
70225/*
70226** Routines to read or write a two- and four-byte big-endian integer values.
70227*/
70228#define get2byte(x)   ((x)[0]<<8 | (x)[1])
70229#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
70230#define get4byte sqlite3Get4byte
70231#define put4byte sqlite3Put4byte
70232
70233/*
70234** get2byteAligned(), unlike get2byte(), requires that its argument point to a
70235** two-byte aligned address.  get2byteAligned() is only used for accessing the
70236** cell addresses in a btree header.
70237*/
70238#if SQLITE_BYTEORDER==4321
70239# define get2byteAligned(x)  (*(u16*)(x))
70240#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
70241# define get2byteAligned(x)  __builtin_bswap16(*(u16*)(x))
70242#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
70243# define get2byteAligned(x)  _byteswap_ushort(*(u16*)(x))
70244#else
70245# define get2byteAligned(x)  ((x)[0]<<8 | (x)[1])
70246#endif
70247
70248/************** End of btreeInt.h ********************************************/
70249/************** Continuing where we left off in btmutex.c ********************/
70250#ifndef SQLITE_OMIT_SHARED_CACHE
70251#if SQLITE_THREADSAFE
70252
70253/*
70254** Obtain the BtShared mutex associated with B-Tree handle p. Also,
70255** set BtShared.db to the database handle associated with p and the
70256** p->locked boolean to true.
70257*/
70258static void lockBtreeMutex(Btree *p){
70259  assert( p->locked==0 );
70260  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
70261  assert( sqlite3_mutex_held(p->db->mutex) );
70262
70263  sqlite3_mutex_enter(p->pBt->mutex);
70264  p->pBt->db = p->db;
70265  p->locked = 1;
70266}
70267
70268/*
70269** Release the BtShared mutex associated with B-Tree handle p and
70270** clear the p->locked boolean.
70271*/
70272static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
70273  BtShared *pBt = p->pBt;
70274  assert( p->locked==1 );
70275  assert( sqlite3_mutex_held(pBt->mutex) );
70276  assert( sqlite3_mutex_held(p->db->mutex) );
70277  assert( p->db==pBt->db );
70278
70279  sqlite3_mutex_leave(pBt->mutex);
70280  p->locked = 0;
70281}
70282
70283/* Forward reference */
70284static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
70285
70286/*
70287** Enter a mutex on the given BTree object.
70288**
70289** If the object is not sharable, then no mutex is ever required
70290** and this routine is a no-op.  The underlying mutex is non-recursive.
70291** But we keep a reference count in Btree.wantToLock so the behavior
70292** of this interface is recursive.
70293**
70294** To avoid deadlocks, multiple Btrees are locked in the same order
70295** by all database connections.  The p->pNext is a list of other
70296** Btrees belonging to the same database connection as the p Btree
70297** which need to be locked after p.  If we cannot get a lock on
70298** p, then first unlock all of the others on p->pNext, then wait
70299** for the lock to become available on p, then relock all of the
70300** subsequent Btrees that desire a lock.
70301*/
70302SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
70303  /* Some basic sanity checking on the Btree.  The list of Btrees
70304  ** connected by pNext and pPrev should be in sorted order by
70305  ** Btree.pBt value. All elements of the list should belong to
70306  ** the same connection. Only shared Btrees are on the list. */
70307  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
70308  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
70309  assert( p->pNext==0 || p->pNext->db==p->db );
70310  assert( p->pPrev==0 || p->pPrev->db==p->db );
70311  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
70312
70313  /* Check for locking consistency */
70314  assert( !p->locked || p->wantToLock>0 );
70315  assert( p->sharable || p->wantToLock==0 );
70316
70317  /* We should already hold a lock on the database connection */
70318  assert( sqlite3_mutex_held(p->db->mutex) );
70319
70320  /* Unless the database is sharable and unlocked, then BtShared.db
70321  ** should already be set correctly. */
70322  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
70323
70324  if( !p->sharable ) return;
70325  p->wantToLock++;
70326  if( p->locked ) return;
70327  btreeLockCarefully(p);
70328}
70329
70330/* This is a helper function for sqlite3BtreeLock(). By moving
70331** complex, but seldom used logic, out of sqlite3BtreeLock() and
70332** into this routine, we avoid unnecessary stack pointer changes
70333** and thus help the sqlite3BtreeLock() routine to run much faster
70334** in the common case.
70335*/
70336static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
70337  Btree *pLater;
70338
70339  /* In most cases, we should be able to acquire the lock we
70340  ** want without having to go through the ascending lock
70341  ** procedure that follows.  Just be sure not to block.
70342  */
70343  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
70344    p->pBt->db = p->db;
70345    p->locked = 1;
70346    return;
70347  }
70348
70349  /* To avoid deadlock, first release all locks with a larger
70350  ** BtShared address.  Then acquire our lock.  Then reacquire
70351  ** the other BtShared locks that we used to hold in ascending
70352  ** order.
70353  */
70354  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
70355    assert( pLater->sharable );
70356    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
70357    assert( !pLater->locked || pLater->wantToLock>0 );
70358    if( pLater->locked ){
70359      unlockBtreeMutex(pLater);
70360    }
70361  }
70362  lockBtreeMutex(p);
70363  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
70364    if( pLater->wantToLock ){
70365      lockBtreeMutex(pLater);
70366    }
70367  }
70368}
70369
70370
70371/*
70372** Exit the recursive mutex on a Btree.
70373*/
70374SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
70375  assert( sqlite3_mutex_held(p->db->mutex) );
70376  if( p->sharable ){
70377    assert( p->wantToLock>0 );
70378    p->wantToLock--;
70379    if( p->wantToLock==0 ){
70380      unlockBtreeMutex(p);
70381    }
70382  }
70383}
70384
70385#ifndef NDEBUG
70386/*
70387** Return true if the BtShared mutex is held on the btree, or if the
70388** B-Tree is not marked as sharable.
70389**
70390** This routine is used only from within assert() statements.
70391*/
70392SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
70393  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
70394  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
70395  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
70396  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
70397
70398  return (p->sharable==0 || p->locked);
70399}
70400#endif
70401
70402
70403/*
70404** Enter the mutex on every Btree associated with a database
70405** connection.  This is needed (for example) prior to parsing
70406** a statement since we will be comparing table and column names
70407** against all schemas and we do not want those schemas being
70408** reset out from under us.
70409**
70410** There is a corresponding leave-all procedures.
70411**
70412** Enter the mutexes in ascending order by BtShared pointer address
70413** to avoid the possibility of deadlock when two threads with
70414** two or more btrees in common both try to lock all their btrees
70415** at the same instant.
70416*/
70417static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
70418  int i;
70419  int skipOk = 1;
70420  Btree *p;
70421  assert( sqlite3_mutex_held(db->mutex) );
70422  for(i=0; i<db->nDb; i++){
70423    p = db->aDb[i].pBt;
70424    if( p && p->sharable ){
70425      sqlite3BtreeEnter(p);
70426      skipOk = 0;
70427    }
70428  }
70429  db->noSharedCache = skipOk;
70430}
70431SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
70432  if( db->noSharedCache==0 ) btreeEnterAll(db);
70433}
70434static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
70435  int i;
70436  Btree *p;
70437  assert( sqlite3_mutex_held(db->mutex) );
70438  for(i=0; i<db->nDb; i++){
70439    p = db->aDb[i].pBt;
70440    if( p ) sqlite3BtreeLeave(p);
70441  }
70442}
70443SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
70444  if( db->noSharedCache==0 ) btreeLeaveAll(db);
70445}
70446
70447#ifndef NDEBUG
70448/*
70449** Return true if the current thread holds the database connection
70450** mutex and all required BtShared mutexes.
70451**
70452** This routine is used inside assert() statements only.
70453*/
70454SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
70455  int i;
70456  if( !sqlite3_mutex_held(db->mutex) ){
70457    return 0;
70458  }
70459  for(i=0; i<db->nDb; i++){
70460    Btree *p;
70461    p = db->aDb[i].pBt;
70462    if( p && p->sharable &&
70463         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
70464      return 0;
70465    }
70466  }
70467  return 1;
70468}
70469#endif /* NDEBUG */
70470
70471#ifndef NDEBUG
70472/*
70473** Return true if the correct mutexes are held for accessing the
70474** db->aDb[iDb].pSchema structure.  The mutexes required for schema
70475** access are:
70476**
70477**   (1) The mutex on db
70478**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
70479**
70480** If pSchema is not NULL, then iDb is computed from pSchema and
70481** db using sqlite3SchemaToIndex().
70482*/
70483SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
70484  Btree *p;
70485  assert( db!=0 );
70486  if( db->pVfs==0 && db->nDb==0 ) return 1;
70487  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
70488  assert( iDb>=0 && iDb<db->nDb );
70489  if( !sqlite3_mutex_held(db->mutex) ) return 0;
70490  if( iDb==1 ) return 1;
70491  p = db->aDb[iDb].pBt;
70492  assert( p!=0 );
70493  return p->sharable==0 || p->locked==1;
70494}
70495#endif /* NDEBUG */
70496
70497#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
70498/*
70499** The following are special cases for mutex enter routines for use
70500** in single threaded applications that use shared cache.  Except for
70501** these two routines, all mutex operations are no-ops in that case and
70502** are null #defines in btree.h.
70503**
70504** If shared cache is disabled, then all btree mutex routines, including
70505** the ones below, are no-ops and are null #defines in btree.h.
70506*/
70507
70508SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
70509  p->pBt->db = p->db;
70510}
70511SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
70512  int i;
70513  for(i=0; i<db->nDb; i++){
70514    Btree *p = db->aDb[i].pBt;
70515    if( p ){
70516      p->pBt->db = p->db;
70517    }
70518  }
70519}
70520#endif /* if SQLITE_THREADSAFE */
70521
70522#ifndef SQLITE_OMIT_INCRBLOB
70523/*
70524** Enter a mutex on a Btree given a cursor owned by that Btree.
70525**
70526** These entry points are used by incremental I/O only. Enter() is required
70527** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
70528** the build is threadsafe. Leave() is only required by threadsafe builds.
70529*/
70530SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
70531  sqlite3BtreeEnter(pCur->pBtree);
70532}
70533# if SQLITE_THREADSAFE
70534SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
70535  sqlite3BtreeLeave(pCur->pBtree);
70536}
70537# endif
70538#endif /* ifndef SQLITE_OMIT_INCRBLOB */
70539
70540#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
70541
70542/************** End of btmutex.c *********************************************/
70543/************** Begin file btree.c *******************************************/
70544/*
70545** 2004 April 6
70546**
70547** The author disclaims copyright to this source code.  In place of
70548** a legal notice, here is a blessing:
70549**
70550**    May you do good and not evil.
70551**    May you find forgiveness for yourself and forgive others.
70552**    May you share freely, never taking more than you give.
70553**
70554*************************************************************************
70555** This file implements an external (disk-based) database using BTrees.
70556** See the header comment on "btreeInt.h" for additional information.
70557** Including a description of file format and an overview of operation.
70558*/
70559/* #include "btreeInt.h" */
70560
70561/*
70562** The header string that appears at the beginning of every
70563** SQLite database.
70564*/
70565static const char zMagicHeader[] = SQLITE_FILE_HEADER;
70566
70567/*
70568** Set this global variable to 1 to enable tracing using the TRACE
70569** macro.
70570*/
70571#if 0
70572int sqlite3BtreeTrace=1;  /* True to enable tracing */
70573# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
70574#else
70575# define TRACE(X)
70576#endif
70577
70578/*
70579** Extract a 2-byte big-endian integer from an array of unsigned bytes.
70580** But if the value is zero, make it 65536.
70581**
70582** This routine is used to extract the "offset to cell content area" value
70583** from the header of a btree page.  If the page size is 65536 and the page
70584** is empty, the offset should be 65536, but the 2-byte value stores zero.
70585** This routine makes the necessary adjustment to 65536.
70586*/
70587#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
70588
70589/*
70590** Values passed as the 5th argument to allocateBtreePage()
70591*/
70592#define BTALLOC_ANY   0           /* Allocate any page */
70593#define BTALLOC_EXACT 1           /* Allocate exact page if possible */
70594#define BTALLOC_LE    2           /* Allocate any page <= the parameter */
70595
70596/*
70597** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
70598** defined, or 0 if it is. For example:
70599**
70600**   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
70601*/
70602#ifndef SQLITE_OMIT_AUTOVACUUM
70603#define IfNotOmitAV(expr) (expr)
70604#else
70605#define IfNotOmitAV(expr) 0
70606#endif
70607
70608#ifndef SQLITE_OMIT_SHARED_CACHE
70609/*
70610** A list of BtShared objects that are eligible for participation
70611** in shared cache.  This variable has file scope during normal builds,
70612** but the test harness needs to access it so we make it global for
70613** test builds.
70614**
70615** Access to this variable is protected by SQLITE_MUTEX_STATIC_MAIN.
70616*/
70617#ifdef SQLITE_TEST
70618SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
70619#else
70620static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
70621#endif
70622#endif /* SQLITE_OMIT_SHARED_CACHE */
70623
70624#ifndef SQLITE_OMIT_SHARED_CACHE
70625/*
70626** Enable or disable the shared pager and schema features.
70627**
70628** This routine has no effect on existing database connections.
70629** The shared cache setting effects only future calls to
70630** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
70631*/
70632SQLITE_API int sqlite3_enable_shared_cache(int enable){
70633  sqlite3GlobalConfig.sharedCacheEnabled = enable;
70634  return SQLITE_OK;
70635}
70636#endif
70637
70638
70639
70640#ifdef SQLITE_OMIT_SHARED_CACHE
70641  /*
70642  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
70643  ** and clearAllSharedCacheTableLocks()
70644  ** manipulate entries in the BtShared.pLock linked list used to store
70645  ** shared-cache table level locks. If the library is compiled with the
70646  ** shared-cache feature disabled, then there is only ever one user
70647  ** of each BtShared structure and so this locking is not necessary.
70648  ** So define the lock related functions as no-ops.
70649  */
70650  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
70651  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
70652  #define clearAllSharedCacheTableLocks(a)
70653  #define downgradeAllSharedCacheTableLocks(a)
70654  #define hasSharedCacheTableLock(a,b,c,d) 1
70655  #define hasReadConflicts(a, b) 0
70656#endif
70657
70658#ifdef SQLITE_DEBUG
70659/*
70660** Return and reset the seek counter for a Btree object.
70661*/
70662SQLITE_PRIVATE sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt){
70663  u64 n =  pBt->nSeek;
70664  pBt->nSeek = 0;
70665  return n;
70666}
70667#endif
70668
70669/*
70670** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
70671** (MemPage*) as an argument. The (MemPage*) must not be NULL.
70672**
70673** If SQLITE_DEBUG is not defined, then this macro is equivalent to
70674** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
70675** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
70676** with the page number and filename associated with the (MemPage*).
70677*/
70678#ifdef SQLITE_DEBUG
70679int corruptPageError(int lineno, MemPage *p){
70680  char *zMsg;
70681  sqlite3BeginBenignMalloc();
70682  zMsg = sqlite3_mprintf("database corruption page %u of %s",
70683             p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
70684  );
70685  sqlite3EndBenignMalloc();
70686  if( zMsg ){
70687    sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
70688  }
70689  sqlite3_free(zMsg);
70690  return SQLITE_CORRUPT_BKPT;
70691}
70692# define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
70693#else
70694# define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
70695#endif
70696
70697/* Default value for SHARED_LOCK_TRACE macro if shared-cache is disabled
70698** or if the lock tracking is disabled.  This is always the value for
70699** release builds.
70700*/
70701#define SHARED_LOCK_TRACE(X,MSG,TAB,TYPE)  /*no-op*/
70702
70703#ifndef SQLITE_OMIT_SHARED_CACHE
70704
70705#if 0
70706/*  ^----  Change to 1 and recompile to enable shared-lock tracing
70707**         for debugging purposes.
70708**
70709** Print all shared-cache locks on a BtShared.  Debugging use only.
70710*/
70711static void sharedLockTrace(
70712  BtShared *pBt,
70713  const char *zMsg,
70714  int iRoot,
70715  int eLockType
70716){
70717  BtLock *pLock;
70718  if( iRoot>0 ){
70719    printf("%s-%p %u%s:", zMsg, pBt, iRoot, eLockType==READ_LOCK?"R":"W");
70720  }else{
70721    printf("%s-%p:", zMsg, pBt);
70722  }
70723  for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
70724    printf(" %p/%u%s", pLock->pBtree, pLock->iTable,
70725           pLock->eLock==READ_LOCK ? "R" : "W");
70726    while( pLock->pNext && pLock->pBtree==pLock->pNext->pBtree ){
70727      pLock = pLock->pNext;
70728      printf(",%u%s", pLock->iTable, pLock->eLock==READ_LOCK ? "R" : "W");
70729    }
70730  }
70731  printf("\n");
70732  fflush(stdout);
70733}
70734#undef SHARED_LOCK_TRACE
70735#define SHARED_LOCK_TRACE(X,MSG,TAB,TYPE)  sharedLockTrace(X,MSG,TAB,TYPE)
70736#endif /* Shared-lock tracing */
70737
70738#ifdef SQLITE_DEBUG
70739/*
70740**** This function is only used as part of an assert() statement. ***
70741**
70742** Check to see if pBtree holds the required locks to read or write to the
70743** table with root page iRoot.   Return 1 if it does and 0 if not.
70744**
70745** For example, when writing to a table with root-page iRoot via
70746** Btree connection pBtree:
70747**
70748**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
70749**
70750** When writing to an index that resides in a sharable database, the
70751** caller should have first obtained a lock specifying the root page of
70752** the corresponding table. This makes things a bit more complicated,
70753** as this module treats each table as a separate structure. To determine
70754** the table corresponding to the index being written, this
70755** function has to search through the database schema.
70756**
70757** Instead of a lock on the table/index rooted at page iRoot, the caller may
70758** hold a write-lock on the schema table (root page 1). This is also
70759** acceptable.
70760*/
70761static int hasSharedCacheTableLock(
70762  Btree *pBtree,         /* Handle that must hold lock */
70763  Pgno iRoot,            /* Root page of b-tree */
70764  int isIndex,           /* True if iRoot is the root of an index b-tree */
70765  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
70766){
70767  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
70768  Pgno iTab = 0;
70769  BtLock *pLock;
70770
70771  /* If this database is not shareable, or if the client is reading
70772  ** and has the read-uncommitted flag set, then no lock is required.
70773  ** Return true immediately.
70774  */
70775  if( (pBtree->sharable==0)
70776   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
70777  ){
70778    return 1;
70779  }
70780
70781  /* If the client is reading  or writing an index and the schema is
70782  ** not loaded, then it is too difficult to actually check to see if
70783  ** the correct locks are held.  So do not bother - just return true.
70784  ** This case does not come up very often anyhow.
70785  */
70786  if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
70787    return 1;
70788  }
70789
70790  /* Figure out the root-page that the lock should be held on. For table
70791  ** b-trees, this is just the root page of the b-tree being read or
70792  ** written. For index b-trees, it is the root page of the associated
70793  ** table.  */
70794  if( isIndex ){
70795    HashElem *p;
70796    int bSeen = 0;
70797    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
70798      Index *pIdx = (Index *)sqliteHashData(p);
70799      if( pIdx->tnum==iRoot ){
70800        if( bSeen ){
70801          /* Two or more indexes share the same root page.  There must
70802          ** be imposter tables.  So just return true.  The assert is not
70803          ** useful in that case. */
70804          return 1;
70805        }
70806        iTab = pIdx->pTable->tnum;
70807        bSeen = 1;
70808      }
70809    }
70810  }else{
70811    iTab = iRoot;
70812  }
70813
70814  SHARED_LOCK_TRACE(pBtree->pBt,"hasLock",iRoot,eLockType);
70815
70816  /* Search for the required lock. Either a write-lock on root-page iTab, a
70817  ** write-lock on the schema table, or (if the client is reading) a
70818  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
70819  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
70820    if( pLock->pBtree==pBtree
70821     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
70822     && pLock->eLock>=eLockType
70823    ){
70824      return 1;
70825    }
70826  }
70827
70828  /* Failed to find the required lock. */
70829  return 0;
70830}
70831#endif /* SQLITE_DEBUG */
70832
70833#ifdef SQLITE_DEBUG
70834/*
70835**** This function may be used as part of assert() statements only. ****
70836**
70837** Return true if it would be illegal for pBtree to write into the
70838** table or index rooted at iRoot because other shared connections are
70839** simultaneously reading that same table or index.
70840**
70841** It is illegal for pBtree to write if some other Btree object that
70842** shares the same BtShared object is currently reading or writing
70843** the iRoot table.  Except, if the other Btree object has the
70844** read-uncommitted flag set, then it is OK for the other object to
70845** have a read cursor.
70846**
70847** For example, before writing to any part of the table or index
70848** rooted at page iRoot, one should call:
70849**
70850**    assert( !hasReadConflicts(pBtree, iRoot) );
70851*/
70852static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
70853  BtCursor *p;
70854  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
70855    if( p->pgnoRoot==iRoot
70856     && p->pBtree!=pBtree
70857     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
70858    ){
70859      return 1;
70860    }
70861  }
70862  return 0;
70863}
70864#endif    /* #ifdef SQLITE_DEBUG */
70865
70866/*
70867** Query to see if Btree handle p may obtain a lock of type eLock
70868** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
70869** SQLITE_OK if the lock may be obtained (by calling
70870** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
70871*/
70872static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
70873  BtShared *pBt = p->pBt;
70874  BtLock *pIter;
70875
70876  assert( sqlite3BtreeHoldsMutex(p) );
70877  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
70878  assert( p->db!=0 );
70879  assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
70880
70881  /* If requesting a write-lock, then the Btree must have an open write
70882  ** transaction on this file. And, obviously, for this to be so there
70883  ** must be an open write transaction on the file itself.
70884  */
70885  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
70886  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
70887
70888  /* This routine is a no-op if the shared-cache is not enabled */
70889  if( !p->sharable ){
70890    return SQLITE_OK;
70891  }
70892
70893  /* If some other connection is holding an exclusive lock, the
70894  ** requested lock may not be obtained.
70895  */
70896  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
70897    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
70898    return SQLITE_LOCKED_SHAREDCACHE;
70899  }
70900
70901  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
70902    /* The condition (pIter->eLock!=eLock) in the following if(...)
70903    ** statement is a simplification of:
70904    **
70905    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
70906    **
70907    ** since we know that if eLock==WRITE_LOCK, then no other connection
70908    ** may hold a WRITE_LOCK on any table in this file (since there can
70909    ** only be a single writer).
70910    */
70911    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
70912    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
70913    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
70914      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
70915      if( eLock==WRITE_LOCK ){
70916        assert( p==pBt->pWriter );
70917        pBt->btsFlags |= BTS_PENDING;
70918      }
70919      return SQLITE_LOCKED_SHAREDCACHE;
70920    }
70921  }
70922  return SQLITE_OK;
70923}
70924#endif /* !SQLITE_OMIT_SHARED_CACHE */
70925
70926#ifndef SQLITE_OMIT_SHARED_CACHE
70927/*
70928** Add a lock on the table with root-page iTable to the shared-btree used
70929** by Btree handle p. Parameter eLock must be either READ_LOCK or
70930** WRITE_LOCK.
70931**
70932** This function assumes the following:
70933**
70934**   (a) The specified Btree object p is connected to a sharable
70935**       database (one with the BtShared.sharable flag set), and
70936**
70937**   (b) No other Btree objects hold a lock that conflicts
70938**       with the requested lock (i.e. querySharedCacheTableLock() has
70939**       already been called and returned SQLITE_OK).
70940**
70941** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
70942** is returned if a malloc attempt fails.
70943*/
70944static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
70945  BtShared *pBt = p->pBt;
70946  BtLock *pLock = 0;
70947  BtLock *pIter;
70948
70949  SHARED_LOCK_TRACE(pBt,"setLock", iTable, eLock);
70950
70951  assert( sqlite3BtreeHoldsMutex(p) );
70952  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
70953  assert( p->db!=0 );
70954
70955  /* A connection with the read-uncommitted flag set will never try to
70956  ** obtain a read-lock using this function. The only read-lock obtained
70957  ** by a connection in read-uncommitted mode is on the sqlite_schema
70958  ** table, and that lock is obtained in BtreeBeginTrans().  */
70959  assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
70960
70961  /* This function should only be called on a sharable b-tree after it
70962  ** has been determined that no other b-tree holds a conflicting lock.  */
70963  assert( p->sharable );
70964  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
70965
70966  /* First search the list for an existing lock on this table. */
70967  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
70968    if( pIter->iTable==iTable && pIter->pBtree==p ){
70969      pLock = pIter;
70970      break;
70971    }
70972  }
70973
70974  /* If the above search did not find a BtLock struct associating Btree p
70975  ** with table iTable, allocate one and link it into the list.
70976  */
70977  if( !pLock ){
70978    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
70979    if( !pLock ){
70980      return SQLITE_NOMEM_BKPT;
70981    }
70982    pLock->iTable = iTable;
70983    pLock->pBtree = p;
70984    pLock->pNext = pBt->pLock;
70985    pBt->pLock = pLock;
70986  }
70987
70988  /* Set the BtLock.eLock variable to the maximum of the current lock
70989  ** and the requested lock. This means if a write-lock was already held
70990  ** and a read-lock requested, we don't incorrectly downgrade the lock.
70991  */
70992  assert( WRITE_LOCK>READ_LOCK );
70993  if( eLock>pLock->eLock ){
70994    pLock->eLock = eLock;
70995  }
70996
70997  return SQLITE_OK;
70998}
70999#endif /* !SQLITE_OMIT_SHARED_CACHE */
71000
71001#ifndef SQLITE_OMIT_SHARED_CACHE
71002/*
71003** Release all the table locks (locks obtained via calls to
71004** the setSharedCacheTableLock() procedure) held by Btree object p.
71005**
71006** This function assumes that Btree p has an open read or write
71007** transaction. If it does not, then the BTS_PENDING flag
71008** may be incorrectly cleared.
71009*/
71010static void clearAllSharedCacheTableLocks(Btree *p){
71011  BtShared *pBt = p->pBt;
71012  BtLock **ppIter = &pBt->pLock;
71013
71014  assert( sqlite3BtreeHoldsMutex(p) );
71015  assert( p->sharable || 0==*ppIter );
71016  assert( p->inTrans>0 );
71017
71018  SHARED_LOCK_TRACE(pBt, "clearAllLocks", 0, 0);
71019
71020  while( *ppIter ){
71021    BtLock *pLock = *ppIter;
71022    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
71023    assert( pLock->pBtree->inTrans>=pLock->eLock );
71024    if( pLock->pBtree==p ){
71025      *ppIter = pLock->pNext;
71026      assert( pLock->iTable!=1 || pLock==&p->lock );
71027      if( pLock->iTable!=1 ){
71028        sqlite3_free(pLock);
71029      }
71030    }else{
71031      ppIter = &pLock->pNext;
71032    }
71033  }
71034
71035  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
71036  if( pBt->pWriter==p ){
71037    pBt->pWriter = 0;
71038    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
71039  }else if( pBt->nTransaction==2 ){
71040    /* This function is called when Btree p is concluding its
71041    ** transaction. If there currently exists a writer, and p is not
71042    ** that writer, then the number of locks held by connections other
71043    ** than the writer must be about to drop to zero. In this case
71044    ** set the BTS_PENDING flag to 0.
71045    **
71046    ** If there is not currently a writer, then BTS_PENDING must
71047    ** be zero already. So this next line is harmless in that case.
71048    */
71049    pBt->btsFlags &= ~BTS_PENDING;
71050  }
71051}
71052
71053/*
71054** This function changes all write-locks held by Btree p into read-locks.
71055*/
71056static void downgradeAllSharedCacheTableLocks(Btree *p){
71057  BtShared *pBt = p->pBt;
71058
71059  SHARED_LOCK_TRACE(pBt, "downgradeLocks", 0, 0);
71060
71061  if( pBt->pWriter==p ){
71062    BtLock *pLock;
71063    pBt->pWriter = 0;
71064    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
71065    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
71066      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
71067      pLock->eLock = READ_LOCK;
71068    }
71069  }
71070}
71071
71072#endif /* SQLITE_OMIT_SHARED_CACHE */
71073
71074static void releasePage(MemPage *pPage);         /* Forward reference */
71075static void releasePageOne(MemPage *pPage);      /* Forward reference */
71076static void releasePageNotNull(MemPage *pPage);  /* Forward reference */
71077
71078/*
71079***** This routine is used inside of assert() only ****
71080**
71081** Verify that the cursor holds the mutex on its BtShared
71082*/
71083#ifdef SQLITE_DEBUG
71084static int cursorHoldsMutex(BtCursor *p){
71085  return sqlite3_mutex_held(p->pBt->mutex);
71086}
71087
71088/* Verify that the cursor and the BtShared agree about what is the current
71089** database connetion. This is important in shared-cache mode. If the database
71090** connection pointers get out-of-sync, it is possible for routines like
71091** btreeInitPage() to reference an stale connection pointer that references a
71092** a connection that has already closed.  This routine is used inside assert()
71093** statements only and for the purpose of double-checking that the btree code
71094** does keep the database connection pointers up-to-date.
71095*/
71096static int cursorOwnsBtShared(BtCursor *p){
71097  assert( cursorHoldsMutex(p) );
71098  return (p->pBtree->db==p->pBt->db);
71099}
71100#endif
71101
71102/*
71103** Invalidate the overflow cache of the cursor passed as the first argument.
71104** on the shared btree structure pBt.
71105*/
71106#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
71107
71108/*
71109** Invalidate the overflow page-list cache for all cursors opened
71110** on the shared btree structure pBt.
71111*/
71112static void invalidateAllOverflowCache(BtShared *pBt){
71113  BtCursor *p;
71114  assert( sqlite3_mutex_held(pBt->mutex) );
71115  for(p=pBt->pCursor; p; p=p->pNext){
71116    invalidateOverflowCache(p);
71117  }
71118}
71119
71120#ifndef SQLITE_OMIT_INCRBLOB
71121/*
71122** This function is called before modifying the contents of a table
71123** to invalidate any incrblob cursors that are open on the
71124** row or one of the rows being modified.
71125**
71126** If argument isClearTable is true, then the entire contents of the
71127** table is about to be deleted. In this case invalidate all incrblob
71128** cursors open on any row within the table with root-page pgnoRoot.
71129**
71130** Otherwise, if argument isClearTable is false, then the row with
71131** rowid iRow is being replaced or deleted. In this case invalidate
71132** only those incrblob cursors open on that specific row.
71133*/
71134static void invalidateIncrblobCursors(
71135  Btree *pBtree,          /* The database file to check */
71136  Pgno pgnoRoot,          /* The table that might be changing */
71137  i64 iRow,               /* The rowid that might be changing */
71138  int isClearTable        /* True if all rows are being deleted */
71139){
71140  BtCursor *p;
71141  assert( pBtree->hasIncrblobCur );
71142  assert( sqlite3BtreeHoldsMutex(pBtree) );
71143  pBtree->hasIncrblobCur = 0;
71144  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
71145    if( (p->curFlags & BTCF_Incrblob)!=0 ){
71146      pBtree->hasIncrblobCur = 1;
71147      if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
71148        p->eState = CURSOR_INVALID;
71149      }
71150    }
71151  }
71152}
71153
71154#else
71155  /* Stub function when INCRBLOB is omitted */
71156  #define invalidateIncrblobCursors(w,x,y,z)
71157#endif /* SQLITE_OMIT_INCRBLOB */
71158
71159/*
71160** Set bit pgno of the BtShared.pHasContent bitvec. This is called
71161** when a page that previously contained data becomes a free-list leaf
71162** page.
71163**
71164** The BtShared.pHasContent bitvec exists to work around an obscure
71165** bug caused by the interaction of two useful IO optimizations surrounding
71166** free-list leaf pages:
71167**
71168**   1) When all data is deleted from a page and the page becomes
71169**      a free-list leaf page, the page is not written to the database
71170**      (as free-list leaf pages contain no meaningful data). Sometimes
71171**      such a page is not even journalled (as it will not be modified,
71172**      why bother journalling it?).
71173**
71174**   2) When a free-list leaf page is reused, its content is not read
71175**      from the database or written to the journal file (why should it
71176**      be, if it is not at all meaningful?).
71177**
71178** By themselves, these optimizations work fine and provide a handy
71179** performance boost to bulk delete or insert operations. However, if
71180** a page is moved to the free-list and then reused within the same
71181** transaction, a problem comes up. If the page is not journalled when
71182** it is moved to the free-list and it is also not journalled when it
71183** is extracted from the free-list and reused, then the original data
71184** may be lost. In the event of a rollback, it may not be possible
71185** to restore the database to its original configuration.
71186**
71187** The solution is the BtShared.pHasContent bitvec. Whenever a page is
71188** moved to become a free-list leaf page, the corresponding bit is
71189** set in the bitvec. Whenever a leaf page is extracted from the free-list,
71190** optimization 2 above is omitted if the corresponding bit is already
71191** set in BtShared.pHasContent. The contents of the bitvec are cleared
71192** at the end of every transaction.
71193*/
71194static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
71195  int rc = SQLITE_OK;
71196  if( !pBt->pHasContent ){
71197    assert( pgno<=pBt->nPage );
71198    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
71199    if( !pBt->pHasContent ){
71200      rc = SQLITE_NOMEM_BKPT;
71201    }
71202  }
71203  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
71204    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
71205  }
71206  return rc;
71207}
71208
71209/*
71210** Query the BtShared.pHasContent vector.
71211**
71212** This function is called when a free-list leaf page is removed from the
71213** free-list for reuse. It returns false if it is safe to retrieve the
71214** page from the pager layer with the 'no-content' flag set. True otherwise.
71215*/
71216static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
71217  Bitvec *p = pBt->pHasContent;
71218  return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));
71219}
71220
71221/*
71222** Clear (destroy) the BtShared.pHasContent bitvec. This should be
71223** invoked at the conclusion of each write-transaction.
71224*/
71225static void btreeClearHasContent(BtShared *pBt){
71226  sqlite3BitvecDestroy(pBt->pHasContent);
71227  pBt->pHasContent = 0;
71228}
71229
71230/*
71231** Release all of the apPage[] pages for a cursor.
71232*/
71233static void btreeReleaseAllCursorPages(BtCursor *pCur){
71234  int i;
71235  if( pCur->iPage>=0 ){
71236    for(i=0; i<pCur->iPage; i++){
71237      releasePageNotNull(pCur->apPage[i]);
71238    }
71239    releasePageNotNull(pCur->pPage);
71240    pCur->iPage = -1;
71241  }
71242}
71243
71244/*
71245** The cursor passed as the only argument must point to a valid entry
71246** when this function is called (i.e. have eState==CURSOR_VALID). This
71247** function saves the current cursor key in variables pCur->nKey and
71248** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
71249** code otherwise.
71250**
71251** If the cursor is open on an intkey table, then the integer key
71252** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
71253** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
71254** set to point to a malloced buffer pCur->nKey bytes in size containing
71255** the key.
71256*/
71257static int saveCursorKey(BtCursor *pCur){
71258  int rc = SQLITE_OK;
71259  assert( CURSOR_VALID==pCur->eState );
71260  assert( 0==pCur->pKey );
71261  assert( cursorHoldsMutex(pCur) );
71262
71263  if( pCur->curIntKey ){
71264    /* Only the rowid is required for a table btree */
71265    pCur->nKey = sqlite3BtreeIntegerKey(pCur);
71266  }else{
71267    /* For an index btree, save the complete key content. It is possible
71268    ** that the current key is corrupt. In that case, it is possible that
71269    ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
71270    ** up to the size of 1 varint plus 1 8-byte value when the cursor
71271    ** position is restored. Hence the 17 bytes of padding allocated
71272    ** below. */
71273    void *pKey;
71274    pCur->nKey = sqlite3BtreePayloadSize(pCur);
71275    pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
71276    if( pKey ){
71277      rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
71278      if( rc==SQLITE_OK ){
71279        memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
71280        pCur->pKey = pKey;
71281      }else{
71282        sqlite3_free(pKey);
71283      }
71284    }else{
71285      rc = SQLITE_NOMEM_BKPT;
71286    }
71287  }
71288  assert( !pCur->curIntKey || !pCur->pKey );
71289  return rc;
71290}
71291
71292/*
71293** Save the current cursor position in the variables BtCursor.nKey
71294** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
71295**
71296** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
71297** prior to calling this routine.
71298*/
71299static int saveCursorPosition(BtCursor *pCur){
71300  int rc;
71301
71302  assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
71303  assert( 0==pCur->pKey );
71304  assert( cursorHoldsMutex(pCur) );
71305
71306  if( pCur->curFlags & BTCF_Pinned ){
71307    return SQLITE_CONSTRAINT_PINNED;
71308  }
71309  if( pCur->eState==CURSOR_SKIPNEXT ){
71310    pCur->eState = CURSOR_VALID;
71311  }else{
71312    pCur->skipNext = 0;
71313  }
71314
71315  rc = saveCursorKey(pCur);
71316  if( rc==SQLITE_OK ){
71317    btreeReleaseAllCursorPages(pCur);
71318    pCur->eState = CURSOR_REQUIRESEEK;
71319  }
71320
71321  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
71322  return rc;
71323}
71324
71325/* Forward reference */
71326static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
71327
71328/*
71329** Save the positions of all cursors (except pExcept) that are open on
71330** the table with root-page iRoot.  "Saving the cursor position" means that
71331** the location in the btree is remembered in such a way that it can be
71332** moved back to the same spot after the btree has been modified.  This
71333** routine is called just before cursor pExcept is used to modify the
71334** table, for example in BtreeDelete() or BtreeInsert().
71335**
71336** If there are two or more cursors on the same btree, then all such
71337** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
71338** routine enforces that rule.  This routine only needs to be called in
71339** the uncommon case when pExpect has the BTCF_Multiple flag set.
71340**
71341** If pExpect!=NULL and if no other cursors are found on the same root-page,
71342** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
71343** pointless call to this routine.
71344**
71345** Implementation note:  This routine merely checks to see if any cursors
71346** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
71347** event that cursors are in need to being saved.
71348*/
71349static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
71350  BtCursor *p;
71351  assert( sqlite3_mutex_held(pBt->mutex) );
71352  assert( pExcept==0 || pExcept->pBt==pBt );
71353  for(p=pBt->pCursor; p; p=p->pNext){
71354    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
71355  }
71356  if( p ) return saveCursorsOnList(p, iRoot, pExcept);
71357  if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
71358  return SQLITE_OK;
71359}
71360
71361/* This helper routine to saveAllCursors does the actual work of saving
71362** the cursors if and when a cursor is found that actually requires saving.
71363** The common case is that no cursors need to be saved, so this routine is
71364** broken out from its caller to avoid unnecessary stack pointer movement.
71365*/
71366static int SQLITE_NOINLINE saveCursorsOnList(
71367  BtCursor *p,         /* The first cursor that needs saving */
71368  Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
71369  BtCursor *pExcept    /* Do not save this cursor */
71370){
71371  do{
71372    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
71373      if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
71374        int rc = saveCursorPosition(p);
71375        if( SQLITE_OK!=rc ){
71376          return rc;
71377        }
71378      }else{
71379        testcase( p->iPage>=0 );
71380        btreeReleaseAllCursorPages(p);
71381      }
71382    }
71383    p = p->pNext;
71384  }while( p );
71385  return SQLITE_OK;
71386}
71387
71388/*
71389** Clear the current cursor position.
71390*/
71391SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
71392  assert( cursorHoldsMutex(pCur) );
71393  sqlite3_free(pCur->pKey);
71394  pCur->pKey = 0;
71395  pCur->eState = CURSOR_INVALID;
71396}
71397
71398/*
71399** In this version of BtreeMoveto, pKey is a packed index record
71400** such as is generated by the OP_MakeRecord opcode.  Unpack the
71401** record and then call sqlite3BtreeIndexMoveto() to do the work.
71402*/
71403static int btreeMoveto(
71404  BtCursor *pCur,     /* Cursor open on the btree to be searched */
71405  const void *pKey,   /* Packed key if the btree is an index */
71406  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
71407  int bias,           /* Bias search to the high end */
71408  int *pRes           /* Write search results here */
71409){
71410  int rc;                    /* Status code */
71411  UnpackedRecord *pIdxKey;   /* Unpacked index key */
71412
71413  if( pKey ){
71414    KeyInfo *pKeyInfo = pCur->pKeyInfo;
71415    assert( nKey==(i64)(int)nKey );
71416    pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
71417    if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
71418    sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
71419    if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
71420      rc = SQLITE_CORRUPT_BKPT;
71421    }else{
71422      rc = sqlite3BtreeIndexMoveto(pCur, pIdxKey, pRes);
71423    }
71424    sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
71425  }else{
71426    pIdxKey = 0;
71427    rc = sqlite3BtreeTableMoveto(pCur, nKey, bias, pRes);
71428  }
71429  return rc;
71430}
71431
71432/*
71433** Restore the cursor to the position it was in (or as close to as possible)
71434** when saveCursorPosition() was called. Note that this call deletes the
71435** saved position info stored by saveCursorPosition(), so there can be
71436** at most one effective restoreCursorPosition() call after each
71437** saveCursorPosition().
71438*/
71439static int btreeRestoreCursorPosition(BtCursor *pCur){
71440  int rc;
71441  int skipNext = 0;
71442  assert( cursorOwnsBtShared(pCur) );
71443  assert( pCur->eState>=CURSOR_REQUIRESEEK );
71444  if( pCur->eState==CURSOR_FAULT ){
71445    return pCur->skipNext;
71446  }
71447  pCur->eState = CURSOR_INVALID;
71448  if( sqlite3FaultSim(410) ){
71449    rc = SQLITE_IOERR;
71450  }else{
71451    rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
71452  }
71453  if( rc==SQLITE_OK ){
71454    sqlite3_free(pCur->pKey);
71455    pCur->pKey = 0;
71456    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
71457    if( skipNext ) pCur->skipNext = skipNext;
71458    if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
71459      pCur->eState = CURSOR_SKIPNEXT;
71460    }
71461  }
71462  return rc;
71463}
71464
71465#define restoreCursorPosition(p) \
71466  (p->eState>=CURSOR_REQUIRESEEK ? \
71467         btreeRestoreCursorPosition(p) : \
71468         SQLITE_OK)
71469
71470/*
71471** Determine whether or not a cursor has moved from the position where
71472** it was last placed, or has been invalidated for any other reason.
71473** Cursors can move when the row they are pointing at is deleted out
71474** from under them, for example.  Cursor might also move if a btree
71475** is rebalanced.
71476**
71477** Calling this routine with a NULL cursor pointer returns false.
71478**
71479** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
71480** back to where it ought to be if this routine returns true.
71481*/
71482SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
71483  assert( EIGHT_BYTE_ALIGNMENT(pCur)
71484       || pCur==sqlite3BtreeFakeValidCursor() );
71485  assert( offsetof(BtCursor, eState)==0 );
71486  assert( sizeof(pCur->eState)==1 );
71487  return CURSOR_VALID != *(u8*)pCur;
71488}
71489
71490/*
71491** Return a pointer to a fake BtCursor object that will always answer
71492** false to the sqlite3BtreeCursorHasMoved() routine above.  The fake
71493** cursor returned must not be used with any other Btree interface.
71494*/
71495SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
71496  static u8 fakeCursor = CURSOR_VALID;
71497  assert( offsetof(BtCursor, eState)==0 );
71498  return (BtCursor*)&fakeCursor;
71499}
71500
71501/*
71502** This routine restores a cursor back to its original position after it
71503** has been moved by some outside activity (such as a btree rebalance or
71504** a row having been deleted out from under the cursor).
71505**
71506** On success, the *pDifferentRow parameter is false if the cursor is left
71507** pointing at exactly the same row.  *pDifferntRow is the row the cursor
71508** was pointing to has been deleted, forcing the cursor to point to some
71509** nearby row.
71510**
71511** This routine should only be called for a cursor that just returned
71512** TRUE from sqlite3BtreeCursorHasMoved().
71513*/
71514SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
71515  int rc;
71516
71517  assert( pCur!=0 );
71518  assert( pCur->eState!=CURSOR_VALID );
71519  rc = restoreCursorPosition(pCur);
71520  if( rc ){
71521    *pDifferentRow = 1;
71522    return rc;
71523  }
71524  if( pCur->eState!=CURSOR_VALID ){
71525    *pDifferentRow = 1;
71526  }else{
71527    *pDifferentRow = 0;
71528  }
71529  return SQLITE_OK;
71530}
71531
71532#ifdef SQLITE_ENABLE_CURSOR_HINTS
71533/*
71534** Provide hints to the cursor.  The particular hint given (and the type
71535** and number of the varargs parameters) is determined by the eHintType
71536** parameter.  See the definitions of the BTREE_HINT_* macros for details.
71537*/
71538SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
71539  /* Used only by system that substitute their own storage engine */
71540#ifdef SQLITE_DEBUG
71541  if( ALWAYS(eHintType==BTREE_HINT_RANGE) ){
71542    va_list ap;
71543    Expr *pExpr;
71544    Walker w;
71545    memset(&w, 0, sizeof(w));
71546    w.xExprCallback = sqlite3CursorRangeHintExprCheck;
71547    va_start(ap, eHintType);
71548    pExpr = va_arg(ap, Expr*);
71549    w.u.aMem = va_arg(ap, Mem*);
71550    va_end(ap);
71551    assert( pExpr!=0 );
71552    assert( w.u.aMem!=0 );
71553    sqlite3WalkExpr(&w, pExpr);
71554  }
71555#endif /* SQLITE_DEBUG */
71556}
71557#endif /* SQLITE_ENABLE_CURSOR_HINTS */
71558
71559
71560/*
71561** Provide flag hints to the cursor.
71562*/
71563SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
71564  assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
71565  pCur->hints = x;
71566}
71567
71568
71569#ifndef SQLITE_OMIT_AUTOVACUUM
71570/*
71571** Given a page number of a regular database page, return the page
71572** number for the pointer-map page that contains the entry for the
71573** input page number.
71574**
71575** Return 0 (not a valid page) for pgno==1 since there is
71576** no pointer map associated with page 1.  The integrity_check logic
71577** requires that ptrmapPageno(*,1)!=1.
71578*/
71579static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
71580  int nPagesPerMapPage;
71581  Pgno iPtrMap, ret;
71582  assert( sqlite3_mutex_held(pBt->mutex) );
71583  if( pgno<2 ) return 0;
71584  nPagesPerMapPage = (pBt->usableSize/5)+1;
71585  iPtrMap = (pgno-2)/nPagesPerMapPage;
71586  ret = (iPtrMap*nPagesPerMapPage) + 2;
71587  if( ret==PENDING_BYTE_PAGE(pBt) ){
71588    ret++;
71589  }
71590  return ret;
71591}
71592
71593/*
71594** Write an entry into the pointer map.
71595**
71596** This routine updates the pointer map entry for page number 'key'
71597** so that it maps to type 'eType' and parent page number 'pgno'.
71598**
71599** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
71600** a no-op.  If an error occurs, the appropriate error code is written
71601** into *pRC.
71602*/
71603static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
71604  DbPage *pDbPage;  /* The pointer map page */
71605  u8 *pPtrmap;      /* The pointer map data */
71606  Pgno iPtrmap;     /* The pointer map page number */
71607  int offset;       /* Offset in pointer map page */
71608  int rc;           /* Return code from subfunctions */
71609
71610  if( *pRC ) return;
71611
71612  assert( sqlite3_mutex_held(pBt->mutex) );
71613  /* The super-journal page number must never be used as a pointer map page */
71614  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
71615
71616  assert( pBt->autoVacuum );
71617  if( key==0 ){
71618    *pRC = SQLITE_CORRUPT_BKPT;
71619    return;
71620  }
71621  iPtrmap = PTRMAP_PAGENO(pBt, key);
71622  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
71623  if( rc!=SQLITE_OK ){
71624    *pRC = rc;
71625    return;
71626  }
71627  if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
71628    /* The first byte of the extra data is the MemPage.isInit byte.
71629    ** If that byte is set, it means this page is also being used
71630    ** as a btree page. */
71631    *pRC = SQLITE_CORRUPT_BKPT;
71632    goto ptrmap_exit;
71633  }
71634  offset = PTRMAP_PTROFFSET(iPtrmap, key);
71635  if( offset<0 ){
71636    *pRC = SQLITE_CORRUPT_BKPT;
71637    goto ptrmap_exit;
71638  }
71639  assert( offset <= (int)pBt->usableSize-5 );
71640  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
71641
71642  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
71643    TRACE(("PTRMAP_UPDATE: %u->(%u,%u)\n", key, eType, parent));
71644    *pRC= rc = sqlite3PagerWrite(pDbPage);
71645    if( rc==SQLITE_OK ){
71646      pPtrmap[offset] = eType;
71647      put4byte(&pPtrmap[offset+1], parent);
71648    }
71649  }
71650
71651ptrmap_exit:
71652  sqlite3PagerUnref(pDbPage);
71653}
71654
71655/*
71656** Read an entry from the pointer map.
71657**
71658** This routine retrieves the pointer map entry for page 'key', writing
71659** the type and parent page number to *pEType and *pPgno respectively.
71660** An error code is returned if something goes wrong, otherwise SQLITE_OK.
71661*/
71662static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
71663  DbPage *pDbPage;   /* The pointer map page */
71664  int iPtrmap;       /* Pointer map page index */
71665  u8 *pPtrmap;       /* Pointer map page data */
71666  int offset;        /* Offset of entry in pointer map */
71667  int rc;
71668
71669  assert( sqlite3_mutex_held(pBt->mutex) );
71670
71671  iPtrmap = PTRMAP_PAGENO(pBt, key);
71672  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
71673  if( rc!=0 ){
71674    return rc;
71675  }
71676  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
71677
71678  offset = PTRMAP_PTROFFSET(iPtrmap, key);
71679  if( offset<0 ){
71680    sqlite3PagerUnref(pDbPage);
71681    return SQLITE_CORRUPT_BKPT;
71682  }
71683  assert( offset <= (int)pBt->usableSize-5 );
71684  assert( pEType!=0 );
71685  *pEType = pPtrmap[offset];
71686  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
71687
71688  sqlite3PagerUnref(pDbPage);
71689  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
71690  return SQLITE_OK;
71691}
71692
71693#else /* if defined SQLITE_OMIT_AUTOVACUUM */
71694  #define ptrmapPut(w,x,y,z,rc)
71695  #define ptrmapGet(w,x,y,z) SQLITE_OK
71696  #define ptrmapPutOvflPtr(x, y, z, rc)
71697#endif
71698
71699/*
71700** Given a btree page and a cell index (0 means the first cell on
71701** the page, 1 means the second cell, and so forth) return a pointer
71702** to the cell content.
71703**
71704** findCellPastPtr() does the same except it skips past the initial
71705** 4-byte child pointer found on interior pages, if there is one.
71706**
71707** This routine works only for pages that do not contain overflow cells.
71708*/
71709#define findCell(P,I) \
71710  ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
71711#define findCellPastPtr(P,I) \
71712  ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
71713
71714
71715/*
71716** This is common tail processing for btreeParseCellPtr() and
71717** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
71718** on a single B-tree page.  Make necessary adjustments to the CellInfo
71719** structure.
71720*/
71721static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
71722  MemPage *pPage,         /* Page containing the cell */
71723  u8 *pCell,              /* Pointer to the cell text. */
71724  CellInfo *pInfo         /* Fill in this structure */
71725){
71726  /* If the payload will not fit completely on the local page, we have
71727  ** to decide how much to store locally and how much to spill onto
71728  ** overflow pages.  The strategy is to minimize the amount of unused
71729  ** space on overflow pages while keeping the amount of local storage
71730  ** in between minLocal and maxLocal.
71731  **
71732  ** Warning:  changing the way overflow payload is distributed in any
71733  ** way will result in an incompatible file format.
71734  */
71735  int minLocal;  /* Minimum amount of payload held locally */
71736  int maxLocal;  /* Maximum amount of payload held locally */
71737  int surplus;   /* Overflow payload available for local storage */
71738
71739  minLocal = pPage->minLocal;
71740  maxLocal = pPage->maxLocal;
71741  surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
71742  testcase( surplus==maxLocal );
71743  testcase( surplus==maxLocal+1 );
71744  if( surplus <= maxLocal ){
71745    pInfo->nLocal = (u16)surplus;
71746  }else{
71747    pInfo->nLocal = (u16)minLocal;
71748  }
71749  pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
71750}
71751
71752/*
71753** Given a record with nPayload bytes of payload stored within btree
71754** page pPage, return the number of bytes of payload stored locally.
71755*/
71756static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){
71757  int maxLocal;  /* Maximum amount of payload held locally */
71758  maxLocal = pPage->maxLocal;
71759  if( nPayload<=maxLocal ){
71760    return nPayload;
71761  }else{
71762    int minLocal;  /* Minimum amount of payload held locally */
71763    int surplus;   /* Overflow payload available for local storage */
71764    minLocal = pPage->minLocal;
71765    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4);
71766    return ( surplus <= maxLocal ) ? surplus : minLocal;
71767  }
71768}
71769
71770/*
71771** The following routines are implementations of the MemPage.xParseCell()
71772** method.
71773**
71774** Parse a cell content block and fill in the CellInfo structure.
71775**
71776** btreeParseCellPtr()        =>   table btree leaf nodes
71777** btreeParseCellNoPayload()  =>   table btree internal nodes
71778** btreeParseCellPtrIndex()   =>   index btree nodes
71779**
71780** There is also a wrapper function btreeParseCell() that works for
71781** all MemPage types and that references the cell by index rather than
71782** by pointer.
71783*/
71784static void btreeParseCellPtrNoPayload(
71785  MemPage *pPage,         /* Page containing the cell */
71786  u8 *pCell,              /* Pointer to the cell text. */
71787  CellInfo *pInfo         /* Fill in this structure */
71788){
71789  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
71790  assert( pPage->leaf==0 );
71791  assert( pPage->childPtrSize==4 );
71792#ifndef SQLITE_DEBUG
71793  UNUSED_PARAMETER(pPage);
71794#endif
71795  pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
71796  pInfo->nPayload = 0;
71797  pInfo->nLocal = 0;
71798  pInfo->pPayload = 0;
71799  return;
71800}
71801static void btreeParseCellPtr(
71802  MemPage *pPage,         /* Page containing the cell */
71803  u8 *pCell,              /* Pointer to the cell text. */
71804  CellInfo *pInfo         /* Fill in this structure */
71805){
71806  u8 *pIter;              /* For scanning through pCell */
71807  u32 nPayload;           /* Number of bytes of cell payload */
71808  u64 iKey;               /* Extracted Key value */
71809
71810  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
71811  assert( pPage->leaf==0 || pPage->leaf==1 );
71812  assert( pPage->intKeyLeaf );
71813  assert( pPage->childPtrSize==0 );
71814  pIter = pCell;
71815
71816  /* The next block of code is equivalent to:
71817  **
71818  **     pIter += getVarint32(pIter, nPayload);
71819  **
71820  ** The code is inlined to avoid a function call.
71821  */
71822  nPayload = *pIter;
71823  if( nPayload>=0x80 ){
71824    u8 *pEnd = &pIter[8];
71825    nPayload &= 0x7f;
71826    do{
71827      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
71828    }while( (*pIter)>=0x80 && pIter<pEnd );
71829  }
71830  pIter++;
71831
71832  /* The next block of code is equivalent to:
71833  **
71834  **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
71835  **
71836  ** The code is inlined and the loop is unrolled for performance.
71837  ** This routine is a high-runner.
71838  */
71839  iKey = *pIter;
71840  if( iKey>=0x80 ){
71841    u8 x;
71842    iKey = (iKey<<7) ^ (x = *++pIter);
71843    if( x>=0x80 ){
71844      iKey = (iKey<<7) ^ (x = *++pIter);
71845      if( x>=0x80 ){
71846        iKey = (iKey<<7) ^ 0x10204000 ^ (x = *++pIter);
71847        if( x>=0x80 ){
71848          iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
71849          if( x>=0x80 ){
71850            iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
71851            if( x>=0x80 ){
71852              iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
71853              if( x>=0x80 ){
71854                iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
71855                if( x>=0x80 ){
71856                  iKey = (iKey<<8) ^ 0x8000 ^ (*++pIter);
71857                }
71858              }
71859            }
71860          }
71861        }
71862      }else{
71863        iKey ^= 0x204000;
71864      }
71865    }else{
71866      iKey ^= 0x4000;
71867    }
71868  }
71869  pIter++;
71870
71871  pInfo->nKey = *(i64*)&iKey;
71872  pInfo->nPayload = nPayload;
71873  pInfo->pPayload = pIter;
71874  testcase( nPayload==pPage->maxLocal );
71875  testcase( nPayload==(u32)pPage->maxLocal+1 );
71876  if( nPayload<=pPage->maxLocal ){
71877    /* This is the (easy) common case where the entire payload fits
71878    ** on the local page.  No overflow is required.
71879    */
71880    pInfo->nSize = nPayload + (u16)(pIter - pCell);
71881    if( pInfo->nSize<4 ) pInfo->nSize = 4;
71882    pInfo->nLocal = (u16)nPayload;
71883  }else{
71884    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
71885  }
71886}
71887static void btreeParseCellPtrIndex(
71888  MemPage *pPage,         /* Page containing the cell */
71889  u8 *pCell,              /* Pointer to the cell text. */
71890  CellInfo *pInfo         /* Fill in this structure */
71891){
71892  u8 *pIter;              /* For scanning through pCell */
71893  u32 nPayload;           /* Number of bytes of cell payload */
71894
71895  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
71896  assert( pPage->leaf==0 || pPage->leaf==1 );
71897  assert( pPage->intKeyLeaf==0 );
71898  pIter = pCell + pPage->childPtrSize;
71899  nPayload = *pIter;
71900  if( nPayload>=0x80 ){
71901    u8 *pEnd = &pIter[8];
71902    nPayload &= 0x7f;
71903    do{
71904      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
71905    }while( *(pIter)>=0x80 && pIter<pEnd );
71906  }
71907  pIter++;
71908  pInfo->nKey = nPayload;
71909  pInfo->nPayload = nPayload;
71910  pInfo->pPayload = pIter;
71911  testcase( nPayload==pPage->maxLocal );
71912  testcase( nPayload==(u32)pPage->maxLocal+1 );
71913  if( nPayload<=pPage->maxLocal ){
71914    /* This is the (easy) common case where the entire payload fits
71915    ** on the local page.  No overflow is required.
71916    */
71917    pInfo->nSize = nPayload + (u16)(pIter - pCell);
71918    if( pInfo->nSize<4 ) pInfo->nSize = 4;
71919    pInfo->nLocal = (u16)nPayload;
71920  }else{
71921    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
71922  }
71923}
71924static void btreeParseCell(
71925  MemPage *pPage,         /* Page containing the cell */
71926  int iCell,              /* The cell index.  First cell is 0 */
71927  CellInfo *pInfo         /* Fill in this structure */
71928){
71929  pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
71930}
71931
71932/*
71933** The following routines are implementations of the MemPage.xCellSize
71934** method.
71935**
71936** Compute the total number of bytes that a Cell needs in the cell
71937** data area of the btree-page.  The return number includes the cell
71938** data header and the local payload, but not any overflow page or
71939** the space used by the cell pointer.
71940**
71941** cellSizePtrNoPayload()    =>   table internal nodes
71942** cellSizePtrTableLeaf()    =>   table leaf nodes
71943** cellSizePtr()             =>   index internal nodes
71944** cellSizeIdxLeaf()         =>   index leaf nodes
71945*/
71946static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
71947  u8 *pIter = pCell + 4;                   /* For looping over bytes of pCell */
71948  u8 *pEnd;                                /* End mark for a varint */
71949  u32 nSize;                               /* Size value to return */
71950
71951#ifdef SQLITE_DEBUG
71952  /* The value returned by this function should always be the same as
71953  ** the (CellInfo.nSize) value found by doing a full parse of the
71954  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
71955  ** this function verifies that this invariant is not violated. */
71956  CellInfo debuginfo;
71957  pPage->xParseCell(pPage, pCell, &debuginfo);
71958#endif
71959
71960  assert( pPage->childPtrSize==4 );
71961  nSize = *pIter;
71962  if( nSize>=0x80 ){
71963    pEnd = &pIter[8];
71964    nSize &= 0x7f;
71965    do{
71966      nSize = (nSize<<7) | (*++pIter & 0x7f);
71967    }while( *(pIter)>=0x80 && pIter<pEnd );
71968  }
71969  pIter++;
71970  testcase( nSize==pPage->maxLocal );
71971  testcase( nSize==(u32)pPage->maxLocal+1 );
71972  if( nSize<=pPage->maxLocal ){
71973    nSize += (u32)(pIter - pCell);
71974    assert( nSize>4 );
71975  }else{
71976    int minLocal = pPage->minLocal;
71977    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
71978    testcase( nSize==pPage->maxLocal );
71979    testcase( nSize==(u32)pPage->maxLocal+1 );
71980    if( nSize>pPage->maxLocal ){
71981      nSize = minLocal;
71982    }
71983    nSize += 4 + (u16)(pIter - pCell);
71984  }
71985  assert( nSize==debuginfo.nSize || CORRUPT_DB );
71986  return (u16)nSize;
71987}
71988static u16 cellSizePtrIdxLeaf(MemPage *pPage, u8 *pCell){
71989  u8 *pIter = pCell;                       /* For looping over bytes of pCell */
71990  u8 *pEnd;                                /* End mark for a varint */
71991  u32 nSize;                               /* Size value to return */
71992
71993#ifdef SQLITE_DEBUG
71994  /* The value returned by this function should always be the same as
71995  ** the (CellInfo.nSize) value found by doing a full parse of the
71996  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
71997  ** this function verifies that this invariant is not violated. */
71998  CellInfo debuginfo;
71999  pPage->xParseCell(pPage, pCell, &debuginfo);
72000#endif
72001
72002  assert( pPage->childPtrSize==0 );
72003  nSize = *pIter;
72004  if( nSize>=0x80 ){
72005    pEnd = &pIter[8];
72006    nSize &= 0x7f;
72007    do{
72008      nSize = (nSize<<7) | (*++pIter & 0x7f);
72009    }while( *(pIter)>=0x80 && pIter<pEnd );
72010  }
72011  pIter++;
72012  testcase( nSize==pPage->maxLocal );
72013  testcase( nSize==(u32)pPage->maxLocal+1 );
72014  if( nSize<=pPage->maxLocal ){
72015    nSize += (u32)(pIter - pCell);
72016    if( nSize<4 ) nSize = 4;
72017  }else{
72018    int minLocal = pPage->minLocal;
72019    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
72020    testcase( nSize==pPage->maxLocal );
72021    testcase( nSize==(u32)pPage->maxLocal+1 );
72022    if( nSize>pPage->maxLocal ){
72023      nSize = minLocal;
72024    }
72025    nSize += 4 + (u16)(pIter - pCell);
72026  }
72027  assert( nSize==debuginfo.nSize || CORRUPT_DB );
72028  return (u16)nSize;
72029}
72030static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
72031  u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
72032  u8 *pEnd;              /* End mark for a varint */
72033
72034#ifdef SQLITE_DEBUG
72035  /* The value returned by this function should always be the same as
72036  ** the (CellInfo.nSize) value found by doing a full parse of the
72037  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
72038  ** this function verifies that this invariant is not violated. */
72039  CellInfo debuginfo;
72040  pPage->xParseCell(pPage, pCell, &debuginfo);
72041#else
72042  UNUSED_PARAMETER(pPage);
72043#endif
72044
72045  assert( pPage->childPtrSize==4 );
72046  pEnd = pIter + 9;
72047  while( (*pIter++)&0x80 && pIter<pEnd );
72048  assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
72049  return (u16)(pIter - pCell);
72050}
72051static u16 cellSizePtrTableLeaf(MemPage *pPage, u8 *pCell){
72052  u8 *pIter = pCell;   /* For looping over bytes of pCell */
72053  u8 *pEnd;            /* End mark for a varint */
72054  u32 nSize;           /* Size value to return */
72055
72056#ifdef SQLITE_DEBUG
72057  /* The value returned by this function should always be the same as
72058  ** the (CellInfo.nSize) value found by doing a full parse of the
72059  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
72060  ** this function verifies that this invariant is not violated. */
72061  CellInfo debuginfo;
72062  pPage->xParseCell(pPage, pCell, &debuginfo);
72063#endif
72064
72065  nSize = *pIter;
72066  if( nSize>=0x80 ){
72067    pEnd = &pIter[8];
72068    nSize &= 0x7f;
72069    do{
72070      nSize = (nSize<<7) | (*++pIter & 0x7f);
72071    }while( *(pIter)>=0x80 && pIter<pEnd );
72072  }
72073  pIter++;
72074  /* pIter now points at the 64-bit integer key value, a variable length
72075  ** integer. The following block moves pIter to point at the first byte
72076  ** past the end of the key value. */
72077  if( (*pIter++)&0x80
72078   && (*pIter++)&0x80
72079   && (*pIter++)&0x80
72080   && (*pIter++)&0x80
72081   && (*pIter++)&0x80
72082   && (*pIter++)&0x80
72083   && (*pIter++)&0x80
72084   && (*pIter++)&0x80 ){ pIter++; }
72085  testcase( nSize==pPage->maxLocal );
72086  testcase( nSize==(u32)pPage->maxLocal+1 );
72087  if( nSize<=pPage->maxLocal ){
72088    nSize += (u32)(pIter - pCell);
72089    if( nSize<4 ) nSize = 4;
72090  }else{
72091    int minLocal = pPage->minLocal;
72092    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
72093    testcase( nSize==pPage->maxLocal );
72094    testcase( nSize==(u32)pPage->maxLocal+1 );
72095    if( nSize>pPage->maxLocal ){
72096      nSize = minLocal;
72097    }
72098    nSize += 4 + (u16)(pIter - pCell);
72099  }
72100  assert( nSize==debuginfo.nSize || CORRUPT_DB );
72101  return (u16)nSize;
72102}
72103
72104
72105#ifdef SQLITE_DEBUG
72106/* This variation on cellSizePtr() is used inside of assert() statements
72107** only. */
72108static u16 cellSize(MemPage *pPage, int iCell){
72109  return pPage->xCellSize(pPage, findCell(pPage, iCell));
72110}
72111#endif
72112
72113#ifndef SQLITE_OMIT_AUTOVACUUM
72114/*
72115** The cell pCell is currently part of page pSrc but will ultimately be part
72116** of pPage.  (pSrc and pPage are often the same.)  If pCell contains a
72117** pointer to an overflow page, insert an entry into the pointer-map for
72118** the overflow page that will be valid after pCell has been moved to pPage.
72119*/
72120static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
72121  CellInfo info;
72122  if( *pRC ) return;
72123  assert( pCell!=0 );
72124  pPage->xParseCell(pPage, pCell, &info);
72125  if( info.nLocal<info.nPayload ){
72126    Pgno ovfl;
72127    if( SQLITE_OVERFLOW(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
72128      testcase( pSrc!=pPage );
72129      *pRC = SQLITE_CORRUPT_BKPT;
72130      return;
72131    }
72132    ovfl = get4byte(&pCell[info.nSize-4]);
72133    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
72134  }
72135}
72136#endif
72137
72138
72139/*
72140** Defragment the page given. This routine reorganizes cells within the
72141** page so that there are no free-blocks on the free-block list.
72142**
72143** Parameter nMaxFrag is the maximum amount of fragmented space that may be
72144** present in the page after this routine returns.
72145**
72146** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
72147** b-tree page so that there are no freeblocks or fragment bytes, all
72148** unused bytes are contained in the unallocated space region, and all
72149** cells are packed tightly at the end of the page.
72150*/
72151static int defragmentPage(MemPage *pPage, int nMaxFrag){
72152  int i;                     /* Loop counter */
72153  int pc;                    /* Address of the i-th cell */
72154  int hdr;                   /* Offset to the page header */
72155  int size;                  /* Size of a cell */
72156  int usableSize;            /* Number of usable bytes on a page */
72157  int cellOffset;            /* Offset to the cell pointer array */
72158  int cbrk;                  /* Offset to the cell content area */
72159  int nCell;                 /* Number of cells on the page */
72160  unsigned char *data;       /* The page data */
72161  unsigned char *temp;       /* Temp area for cell content */
72162  unsigned char *src;        /* Source of content */
72163  int iCellFirst;            /* First allowable cell index */
72164  int iCellLast;             /* Last possible cell index */
72165  int iCellStart;            /* First cell offset in input */
72166
72167  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
72168  assert( pPage->pBt!=0 );
72169  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
72170  assert( pPage->nOverflow==0 );
72171  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
72172  data = pPage->aData;
72173  hdr = pPage->hdrOffset;
72174  cellOffset = pPage->cellOffset;
72175  nCell = pPage->nCell;
72176  assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
72177  iCellFirst = cellOffset + 2*nCell;
72178  usableSize = pPage->pBt->usableSize;
72179
72180  /* This block handles pages with two or fewer free blocks and nMaxFrag
72181  ** or fewer fragmented bytes. In this case it is faster to move the
72182  ** two (or one) blocks of cells using memmove() and add the required
72183  ** offsets to each pointer in the cell-pointer array than it is to
72184  ** reconstruct the entire page.  */
72185  if( (int)data[hdr+7]<=nMaxFrag ){
72186    int iFree = get2byte(&data[hdr+1]);
72187    if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
72188    if( iFree ){
72189      int iFree2 = get2byte(&data[iFree]);
72190      if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
72191      if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
72192        u8 *pEnd = &data[cellOffset + nCell*2];
72193        u8 *pAddr;
72194        int sz2 = 0;
72195        int sz = get2byte(&data[iFree+2]);
72196        int top = get2byte(&data[hdr+5]);
72197        if( top>=iFree ){
72198          return SQLITE_CORRUPT_PAGE(pPage);
72199        }
72200        if( iFree2 ){
72201          if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
72202          sz2 = get2byte(&data[iFree2+2]);
72203          if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
72204          memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
72205          sz += sz2;
72206        }else if( iFree+sz>usableSize ){
72207          return SQLITE_CORRUPT_PAGE(pPage);
72208        }
72209
72210        cbrk = top+sz;
72211        assert( cbrk+(iFree-top) <= usableSize );
72212        memmove(&data[cbrk], &data[top], iFree-top);
72213        for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
72214          pc = get2byte(pAddr);
72215          if( pc<iFree ){ put2byte(pAddr, pc+sz); }
72216          else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
72217        }
72218        goto defragment_out;
72219      }
72220    }
72221  }
72222
72223  cbrk = usableSize;
72224  iCellLast = usableSize - 4;
72225  iCellStart = get2byte(&data[hdr+5]);
72226  if( nCell>0 ){
72227    temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
72228    memcpy(temp, data, usableSize);
72229    src = temp;
72230    for(i=0; i<nCell; i++){
72231      u8 *pAddr;     /* The i-th cell pointer */
72232      pAddr = &data[cellOffset + i*2];
72233      pc = get2byte(pAddr);
72234      testcase( pc==iCellFirst );
72235      testcase( pc==iCellLast );
72236      /* These conditions have already been verified in btreeInitPage()
72237      ** if PRAGMA cell_size_check=ON.
72238      */
72239      if( pc>iCellLast ){
72240        return SQLITE_CORRUPT_PAGE(pPage);
72241      }
72242      assert( pc>=0 && pc<=iCellLast );
72243      size = pPage->xCellSize(pPage, &src[pc]);
72244      cbrk -= size;
72245      if( cbrk<iCellStart || pc+size>usableSize ){
72246        return SQLITE_CORRUPT_PAGE(pPage);
72247      }
72248      assert( cbrk+size<=usableSize && cbrk>=iCellStart );
72249      testcase( cbrk+size==usableSize );
72250      testcase( pc+size==usableSize );
72251      put2byte(pAddr, cbrk);
72252      memcpy(&data[cbrk], &src[pc], size);
72253    }
72254  }
72255  data[hdr+7] = 0;
72256
72257defragment_out:
72258  assert( pPage->nFree>=0 );
72259  if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
72260    return SQLITE_CORRUPT_PAGE(pPage);
72261  }
72262  assert( cbrk>=iCellFirst );
72263  put2byte(&data[hdr+5], cbrk);
72264  data[hdr+1] = 0;
72265  data[hdr+2] = 0;
72266  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
72267  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
72268  return SQLITE_OK;
72269}
72270
72271/*
72272** Search the free-list on page pPg for space to store a cell nByte bytes in
72273** size. If one can be found, return a pointer to the space and remove it
72274** from the free-list.
72275**
72276** If no suitable space can be found on the free-list, return NULL.
72277**
72278** This function may detect corruption within pPg.  If corruption is
72279** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
72280**
72281** Slots on the free list that are between 1 and 3 bytes larger than nByte
72282** will be ignored if adding the extra space to the fragmentation count
72283** causes the fragmentation count to exceed 60.
72284*/
72285static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
72286  const int hdr = pPg->hdrOffset;            /* Offset to page header */
72287  u8 * const aData = pPg->aData;             /* Page data */
72288  int iAddr = hdr + 1;                       /* Address of ptr to pc */
72289  u8 *pTmp = &aData[iAddr];                  /* Temporary ptr into aData[] */
72290  int pc = get2byte(pTmp);                   /* Address of a free slot */
72291  int x;                                     /* Excess size of the slot */
72292  int maxPC = pPg->pBt->usableSize - nByte;  /* Max address for a usable slot */
72293  int size;                                  /* Size of the free slot */
72294
72295  assert( pc>0 );
72296  while( pc<=maxPC ){
72297    /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
72298    ** freeblock form a big-endian integer which is the size of the freeblock
72299    ** in bytes, including the 4-byte header. */
72300    pTmp = &aData[pc+2];
72301    size = get2byte(pTmp);
72302    if( (x = size - nByte)>=0 ){
72303      testcase( x==4 );
72304      testcase( x==3 );
72305      if( x<4 ){
72306        /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
72307        ** number of bytes in fragments may not exceed 60. */
72308        if( aData[hdr+7]>57 ) return 0;
72309
72310        /* Remove the slot from the free-list. Update the number of
72311        ** fragmented bytes within the page. */
72312        memcpy(&aData[iAddr], &aData[pc], 2);
72313        aData[hdr+7] += (u8)x;
72314        return &aData[pc];
72315      }else if( x+pc > maxPC ){
72316        /* This slot extends off the end of the usable part of the page */
72317        *pRc = SQLITE_CORRUPT_PAGE(pPg);
72318        return 0;
72319      }else{
72320        /* The slot remains on the free-list. Reduce its size to account
72321        ** for the portion used by the new allocation. */
72322        put2byte(&aData[pc+2], x);
72323      }
72324      return &aData[pc + x];
72325    }
72326    iAddr = pc;
72327    pTmp = &aData[pc];
72328    pc = get2byte(pTmp);
72329    if( pc<=iAddr ){
72330      if( pc ){
72331        /* The next slot in the chain comes before the current slot */
72332        *pRc = SQLITE_CORRUPT_PAGE(pPg);
72333      }
72334      return 0;
72335    }
72336  }
72337  if( pc>maxPC+nByte-4 ){
72338    /* The free slot chain extends off the end of the page */
72339    *pRc = SQLITE_CORRUPT_PAGE(pPg);
72340  }
72341  return 0;
72342}
72343
72344/*
72345** Allocate nByte bytes of space from within the B-Tree page passed
72346** as the first argument. Write into *pIdx the index into pPage->aData[]
72347** of the first byte of allocated space. Return either SQLITE_OK or
72348** an error code (usually SQLITE_CORRUPT).
72349**
72350** The caller guarantees that there is sufficient space to make the
72351** allocation.  This routine might need to defragment in order to bring
72352** all the space together, however.  This routine will avoid using
72353** the first two bytes past the cell pointer area since presumably this
72354** allocation is being made in order to insert a new cell, so we will
72355** also end up needing a new cell pointer.
72356*/
72357static SQLITE_INLINE int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
72358  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
72359  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
72360  int top;                             /* First byte of cell content area */
72361  int rc = SQLITE_OK;                  /* Integer return code */
72362  u8 *pTmp;                            /* Temp ptr into data[] */
72363  int gap;        /* First byte of gap between cell pointers and cell content */
72364
72365  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
72366  assert( pPage->pBt );
72367  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
72368  assert( nByte>=0 );  /* Minimum cell size is 4 */
72369  assert( pPage->nFree>=nByte );
72370  assert( pPage->nOverflow==0 );
72371  assert( nByte < (int)(pPage->pBt->usableSize-8) );
72372
72373  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
72374  gap = pPage->cellOffset + 2*pPage->nCell;
72375  assert( gap<=65536 );
72376  /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
72377  ** and the reserved space is zero (the usual value for reserved space)
72378  ** then the cell content offset of an empty page wants to be 65536.
72379  ** However, that integer is too large to be stored in a 2-byte unsigned
72380  ** integer, so a value of 0 is used in its place. */
72381  pTmp = &data[hdr+5];
72382  top = get2byte(pTmp);
72383  if( gap>top ){
72384    if( top==0 && pPage->pBt->usableSize==65536 ){
72385      top = 65536;
72386    }else{
72387      return SQLITE_CORRUPT_PAGE(pPage);
72388    }
72389  }else if( top>(int)pPage->pBt->usableSize ){
72390    return SQLITE_CORRUPT_PAGE(pPage);
72391  }
72392
72393  /* If there is enough space between gap and top for one more cell pointer,
72394  ** and if the freelist is not empty, then search the
72395  ** freelist looking for a slot big enough to satisfy the request.
72396  */
72397  testcase( gap+2==top );
72398  testcase( gap+1==top );
72399  testcase( gap==top );
72400  if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
72401    u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
72402    if( pSpace ){
72403      int g2;
72404      assert( pSpace+nByte<=data+pPage->pBt->usableSize );
72405      *pIdx = g2 = (int)(pSpace-data);
72406      if( g2<=gap ){
72407        return SQLITE_CORRUPT_PAGE(pPage);
72408      }else{
72409        return SQLITE_OK;
72410      }
72411    }else if( rc ){
72412      return rc;
72413    }
72414  }
72415
72416  /* The request could not be fulfilled using a freelist slot.  Check
72417  ** to see if defragmentation is necessary.
72418  */
72419  testcase( gap+2+nByte==top );
72420  if( gap+2+nByte>top ){
72421    assert( pPage->nCell>0 || CORRUPT_DB );
72422    assert( pPage->nFree>=0 );
72423    rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
72424    if( rc ) return rc;
72425    top = get2byteNotZero(&data[hdr+5]);
72426    assert( gap+2+nByte<=top );
72427  }
72428
72429
72430  /* Allocate memory from the gap in between the cell pointer array
72431  ** and the cell content area.  The btreeComputeFreeSpace() call has already
72432  ** validated the freelist.  Given that the freelist is valid, there
72433  ** is no way that the allocation can extend off the end of the page.
72434  ** The assert() below verifies the previous sentence.
72435  */
72436  top -= nByte;
72437  put2byte(&data[hdr+5], top);
72438  assert( top+nByte <= (int)pPage->pBt->usableSize );
72439  *pIdx = top;
72440  return SQLITE_OK;
72441}
72442
72443/*
72444** Return a section of the pPage->aData to the freelist.
72445** The first byte of the new free block is pPage->aData[iStart]
72446** and the size of the block is iSize bytes.
72447**
72448** Adjacent freeblocks are coalesced.
72449**
72450** Even though the freeblock list was checked by btreeComputeFreeSpace(),
72451** that routine will not detect overlap between cells or freeblocks.  Nor
72452** does it detect cells or freeblocks that encroach into the reserved bytes
72453** at the end of the page.  So do additional corruption checks inside this
72454** routine and return SQLITE_CORRUPT if any problems are found.
72455*/
72456static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
72457  u16 iPtr;                             /* Address of ptr to next freeblock */
72458  u16 iFreeBlk;                         /* Address of the next freeblock */
72459  u8 hdr;                               /* Page header size.  0 or 100 */
72460  u8 nFrag = 0;                         /* Reduction in fragmentation */
72461  u16 iOrigSize = iSize;                /* Original value of iSize */
72462  u16 x;                                /* Offset to cell content area */
72463  u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
72464  unsigned char *data = pPage->aData;   /* Page content */
72465  u8 *pTmp;                             /* Temporary ptr into data[] */
72466
72467  assert( pPage->pBt!=0 );
72468  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
72469  assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
72470  assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
72471  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
72472  assert( iSize>=4 );   /* Minimum cell size is 4 */
72473  assert( CORRUPT_DB || iStart<=pPage->pBt->usableSize-4 );
72474
72475  /* The list of freeblocks must be in ascending order.  Find the
72476  ** spot on the list where iStart should be inserted.
72477  */
72478  hdr = pPage->hdrOffset;
72479  iPtr = hdr + 1;
72480  if( data[iPtr+1]==0 && data[iPtr]==0 ){
72481    iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
72482  }else{
72483    while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
72484      if( iFreeBlk<=iPtr ){
72485        if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
72486        return SQLITE_CORRUPT_PAGE(pPage);
72487      }
72488      iPtr = iFreeBlk;
72489    }
72490    if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
72491      return SQLITE_CORRUPT_PAGE(pPage);
72492    }
72493    assert( iFreeBlk>iPtr || iFreeBlk==0 || CORRUPT_DB );
72494
72495    /* At this point:
72496    **    iFreeBlk:   First freeblock after iStart, or zero if none
72497    **    iPtr:       The address of a pointer to iFreeBlk
72498    **
72499    ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
72500    */
72501    if( iFreeBlk && iEnd+3>=iFreeBlk ){
72502      nFrag = iFreeBlk - iEnd;
72503      if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
72504      iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
72505      if( iEnd > pPage->pBt->usableSize ){
72506        return SQLITE_CORRUPT_PAGE(pPage);
72507      }
72508      iSize = iEnd - iStart;
72509      iFreeBlk = get2byte(&data[iFreeBlk]);
72510    }
72511
72512    /* If iPtr is another freeblock (that is, if iPtr is not the freelist
72513    ** pointer in the page header) then check to see if iStart should be
72514    ** coalesced onto the end of iPtr.
72515    */
72516    if( iPtr>hdr+1 ){
72517      int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
72518      if( iPtrEnd+3>=iStart ){
72519        if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
72520        nFrag += iStart - iPtrEnd;
72521        iSize = iEnd - iPtr;
72522        iStart = iPtr;
72523      }
72524    }
72525    if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
72526    data[hdr+7] -= nFrag;
72527  }
72528  pTmp = &data[hdr+5];
72529  x = get2byte(pTmp);
72530  if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
72531    /* Overwrite deleted information with zeros when the secure_delete
72532    ** option is enabled */
72533    memset(&data[iStart], 0, iSize);
72534  }
72535  if( iStart<=x ){
72536    /* The new freeblock is at the beginning of the cell content area,
72537    ** so just extend the cell content area rather than create another
72538    ** freelist entry */
72539    if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
72540    if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
72541    put2byte(&data[hdr+1], iFreeBlk);
72542    put2byte(&data[hdr+5], iEnd);
72543  }else{
72544    /* Insert the new freeblock into the freelist */
72545    put2byte(&data[iPtr], iStart);
72546    put2byte(&data[iStart], iFreeBlk);
72547    put2byte(&data[iStart+2], iSize);
72548  }
72549  pPage->nFree += iOrigSize;
72550  return SQLITE_OK;
72551}
72552
72553/*
72554** Decode the flags byte (the first byte of the header) for a page
72555** and initialize fields of the MemPage structure accordingly.
72556**
72557** Only the following combinations are supported.  Anything different
72558** indicates a corrupt database files:
72559**
72560**         PTF_ZERODATA                             (0x02,  2)
72561**         PTF_LEAFDATA | PTF_INTKEY                (0x05,  5)
72562**         PTF_ZERODATA | PTF_LEAF                  (0x0a, 10)
72563**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF     (0x0d, 13)
72564*/
72565static int decodeFlags(MemPage *pPage, int flagByte){
72566  BtShared *pBt;     /* A copy of pPage->pBt */
72567
72568  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
72569  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
72570  pBt = pPage->pBt;
72571  pPage->max1bytePayload = pBt->max1bytePayload;
72572  if( flagByte>=(PTF_ZERODATA | PTF_LEAF) ){
72573    pPage->childPtrSize = 0;
72574    pPage->leaf = 1;
72575    if( flagByte==(PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF) ){
72576      pPage->intKeyLeaf = 1;
72577      pPage->xCellSize = cellSizePtrTableLeaf;
72578      pPage->xParseCell = btreeParseCellPtr;
72579      pPage->intKey = 1;
72580      pPage->maxLocal = pBt->maxLeaf;
72581      pPage->minLocal = pBt->minLeaf;
72582    }else if( flagByte==(PTF_ZERODATA | PTF_LEAF) ){
72583      pPage->intKey = 0;
72584      pPage->intKeyLeaf = 0;
72585      pPage->xCellSize = cellSizePtrIdxLeaf;
72586      pPage->xParseCell = btreeParseCellPtrIndex;
72587      pPage->maxLocal = pBt->maxLocal;
72588      pPage->minLocal = pBt->minLocal;
72589    }else{
72590      pPage->intKey = 0;
72591      pPage->intKeyLeaf = 0;
72592      pPage->xCellSize = cellSizePtrIdxLeaf;
72593      pPage->xParseCell = btreeParseCellPtrIndex;
72594      return SQLITE_CORRUPT_PAGE(pPage);
72595    }
72596  }else{
72597    pPage->childPtrSize = 4;
72598    pPage->leaf = 0;
72599    if( flagByte==(PTF_ZERODATA) ){
72600      pPage->intKey = 0;
72601      pPage->intKeyLeaf = 0;
72602      pPage->xCellSize = cellSizePtr;
72603      pPage->xParseCell = btreeParseCellPtrIndex;
72604      pPage->maxLocal = pBt->maxLocal;
72605      pPage->minLocal = pBt->minLocal;
72606    }else if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
72607      pPage->intKeyLeaf = 0;
72608      pPage->xCellSize = cellSizePtrNoPayload;
72609      pPage->xParseCell = btreeParseCellPtrNoPayload;
72610      pPage->intKey = 1;
72611      pPage->maxLocal = pBt->maxLeaf;
72612      pPage->minLocal = pBt->minLeaf;
72613    }else{
72614      pPage->intKey = 0;
72615      pPage->intKeyLeaf = 0;
72616      pPage->xCellSize = cellSizePtr;
72617      pPage->xParseCell = btreeParseCellPtrIndex;
72618      return SQLITE_CORRUPT_PAGE(pPage);
72619    }
72620  }
72621  return SQLITE_OK;
72622}
72623
72624/*
72625** Compute the amount of freespace on the page.  In other words, fill
72626** in the pPage->nFree field.
72627*/
72628static int btreeComputeFreeSpace(MemPage *pPage){
72629  int pc;            /* Address of a freeblock within pPage->aData[] */
72630  u8 hdr;            /* Offset to beginning of page header */
72631  u8 *data;          /* Equal to pPage->aData */
72632  int usableSize;    /* Amount of usable space on each page */
72633  int nFree;         /* Number of unused bytes on the page */
72634  int top;           /* First byte of the cell content area */
72635  int iCellFirst;    /* First allowable cell or freeblock offset */
72636  int iCellLast;     /* Last possible cell or freeblock offset */
72637
72638  assert( pPage->pBt!=0 );
72639  assert( pPage->pBt->db!=0 );
72640  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
72641  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
72642  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
72643  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
72644  assert( pPage->isInit==1 );
72645  assert( pPage->nFree<0 );
72646
72647  usableSize = pPage->pBt->usableSize;
72648  hdr = pPage->hdrOffset;
72649  data = pPage->aData;
72650  /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
72651  ** the start of the cell content area. A zero value for this integer is
72652  ** interpreted as 65536. */
72653  top = get2byteNotZero(&data[hdr+5]);
72654  iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
72655  iCellLast = usableSize - 4;
72656
72657  /* Compute the total free space on the page
72658  ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
72659  ** start of the first freeblock on the page, or is zero if there are no
72660  ** freeblocks. */
72661  pc = get2byte(&data[hdr+1]);
72662  nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
72663  if( pc>0 ){
72664    u32 next, size;
72665    if( pc<top ){
72666      /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
72667      ** always be at least one cell before the first freeblock.
72668      */
72669      return SQLITE_CORRUPT_PAGE(pPage);
72670    }
72671    while( 1 ){
72672      if( pc>iCellLast ){
72673        /* Freeblock off the end of the page */
72674        return SQLITE_CORRUPT_PAGE(pPage);
72675      }
72676      next = get2byte(&data[pc]);
72677      size = get2byte(&data[pc+2]);
72678      nFree = nFree + size;
72679      if( next<=pc+size+3 ) break;
72680      pc = next;
72681    }
72682    if( next>0 ){
72683      /* Freeblock not in ascending order */
72684      return SQLITE_CORRUPT_PAGE(pPage);
72685    }
72686    if( pc+size>(unsigned int)usableSize ){
72687      /* Last freeblock extends past page end */
72688      return SQLITE_CORRUPT_PAGE(pPage);
72689    }
72690  }
72691
72692  /* At this point, nFree contains the sum of the offset to the start
72693  ** of the cell-content area plus the number of free bytes within
72694  ** the cell-content area. If this is greater than the usable-size
72695  ** of the page, then the page must be corrupted. This check also
72696  ** serves to verify that the offset to the start of the cell-content
72697  ** area, according to the page header, lies within the page.
72698  */
72699  if( nFree>usableSize || nFree<iCellFirst ){
72700    return SQLITE_CORRUPT_PAGE(pPage);
72701  }
72702  pPage->nFree = (u16)(nFree - iCellFirst);
72703  return SQLITE_OK;
72704}
72705
72706/*
72707** Do additional sanity check after btreeInitPage() if
72708** PRAGMA cell_size_check=ON
72709*/
72710static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
72711  int iCellFirst;    /* First allowable cell or freeblock offset */
72712  int iCellLast;     /* Last possible cell or freeblock offset */
72713  int i;             /* Index into the cell pointer array */
72714  int sz;            /* Size of a cell */
72715  int pc;            /* Address of a freeblock within pPage->aData[] */
72716  u8 *data;          /* Equal to pPage->aData */
72717  int usableSize;    /* Maximum usable space on the page */
72718  int cellOffset;    /* Start of cell content area */
72719
72720  iCellFirst = pPage->cellOffset + 2*pPage->nCell;
72721  usableSize = pPage->pBt->usableSize;
72722  iCellLast = usableSize - 4;
72723  data = pPage->aData;
72724  cellOffset = pPage->cellOffset;
72725  if( !pPage->leaf ) iCellLast--;
72726  for(i=0; i<pPage->nCell; i++){
72727    pc = get2byteAligned(&data[cellOffset+i*2]);
72728    testcase( pc==iCellFirst );
72729    testcase( pc==iCellLast );
72730    if( pc<iCellFirst || pc>iCellLast ){
72731      return SQLITE_CORRUPT_PAGE(pPage);
72732    }
72733    sz = pPage->xCellSize(pPage, &data[pc]);
72734    testcase( pc+sz==usableSize );
72735    if( pc+sz>usableSize ){
72736      return SQLITE_CORRUPT_PAGE(pPage);
72737    }
72738  }
72739  return SQLITE_OK;
72740}
72741
72742/*
72743** Initialize the auxiliary information for a disk block.
72744**
72745** Return SQLITE_OK on success.  If we see that the page does
72746** not contain a well-formed database page, then return
72747** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
72748** guarantee that the page is well-formed.  It only shows that
72749** we failed to detect any corruption.
72750*/
72751static int btreeInitPage(MemPage *pPage){
72752  u8 *data;          /* Equal to pPage->aData */
72753  BtShared *pBt;        /* The main btree structure */
72754
72755  assert( pPage->pBt!=0 );
72756  assert( pPage->pBt->db!=0 );
72757  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
72758  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
72759  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
72760  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
72761  assert( pPage->isInit==0 );
72762
72763  pBt = pPage->pBt;
72764  data = pPage->aData + pPage->hdrOffset;
72765  /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
72766  ** the b-tree page type. */
72767  if( decodeFlags(pPage, data[0]) ){
72768    return SQLITE_CORRUPT_PAGE(pPage);
72769  }
72770  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
72771  pPage->maskPage = (u16)(pBt->pageSize - 1);
72772  pPage->nOverflow = 0;
72773  pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
72774  pPage->aCellIdx = data + pPage->childPtrSize + 8;
72775  pPage->aDataEnd = pPage->aData + pBt->pageSize;
72776  pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
72777  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
72778  ** number of cells on the page. */
72779  pPage->nCell = get2byte(&data[3]);
72780  if( pPage->nCell>MX_CELL(pBt) ){
72781    /* To many cells for a single page.  The page must be corrupt */
72782    return SQLITE_CORRUPT_PAGE(pPage);
72783  }
72784  testcase( pPage->nCell==MX_CELL(pBt) );
72785  /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
72786  ** possible for a root page of a table that contains no rows) then the
72787  ** offset to the cell content area will equal the page size minus the
72788  ** bytes of reserved space. */
72789  assert( pPage->nCell>0
72790       || get2byteNotZero(&data[5])==(int)pBt->usableSize
72791       || CORRUPT_DB );
72792  pPage->nFree = -1;  /* Indicate that this value is yet uncomputed */
72793  pPage->isInit = 1;
72794  if( pBt->db->flags & SQLITE_CellSizeCk ){
72795    return btreeCellSizeCheck(pPage);
72796  }
72797  return SQLITE_OK;
72798}
72799
72800/*
72801** Set up a raw page so that it looks like a database page holding
72802** no entries.
72803*/
72804static void zeroPage(MemPage *pPage, int flags){
72805  unsigned char *data = pPage->aData;
72806  BtShared *pBt = pPage->pBt;
72807  u8 hdr = pPage->hdrOffset;
72808  u16 first;
72809
72810  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno || CORRUPT_DB );
72811  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
72812  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
72813  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
72814  assert( sqlite3_mutex_held(pBt->mutex) );
72815  if( pBt->btsFlags & BTS_FAST_SECURE ){
72816    memset(&data[hdr], 0, pBt->usableSize - hdr);
72817  }
72818  data[hdr] = (char)flags;
72819  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
72820  memset(&data[hdr+1], 0, 4);
72821  data[hdr+7] = 0;
72822  put2byte(&data[hdr+5], pBt->usableSize);
72823  pPage->nFree = (u16)(pBt->usableSize - first);
72824  decodeFlags(pPage, flags);
72825  pPage->cellOffset = first;
72826  pPage->aDataEnd = &data[pBt->pageSize];
72827  pPage->aCellIdx = &data[first];
72828  pPage->aDataOfst = &data[pPage->childPtrSize];
72829  pPage->nOverflow = 0;
72830  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
72831  pPage->maskPage = (u16)(pBt->pageSize - 1);
72832  pPage->nCell = 0;
72833  pPage->isInit = 1;
72834}
72835
72836
72837/*
72838** Convert a DbPage obtained from the pager into a MemPage used by
72839** the btree layer.
72840*/
72841static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
72842  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
72843  if( pgno!=pPage->pgno ){
72844    pPage->aData = sqlite3PagerGetData(pDbPage);
72845    pPage->pDbPage = pDbPage;
72846    pPage->pBt = pBt;
72847    pPage->pgno = pgno;
72848    pPage->hdrOffset = pgno==1 ? 100 : 0;
72849  }
72850  assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
72851  return pPage;
72852}
72853
72854/*
72855** Get a page from the pager.  Initialize the MemPage.pBt and
72856** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
72857**
72858** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
72859** about the content of the page at this time.  So do not go to the disk
72860** to fetch the content.  Just fill in the content with zeros for now.
72861** If in the future we call sqlite3PagerWrite() on this page, that
72862** means we have started to be concerned about content and the disk
72863** read should occur at that point.
72864*/
72865static int btreeGetPage(
72866  BtShared *pBt,       /* The btree */
72867  Pgno pgno,           /* Number of the page to fetch */
72868  MemPage **ppPage,    /* Return the page in this parameter */
72869  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
72870){
72871  int rc;
72872  DbPage *pDbPage;
72873
72874  assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
72875  assert( sqlite3_mutex_held(pBt->mutex) );
72876  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
72877  if( rc ) return rc;
72878  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
72879  return SQLITE_OK;
72880}
72881
72882/*
72883** Retrieve a page from the pager cache. If the requested page is not
72884** already in the pager cache return NULL. Initialize the MemPage.pBt and
72885** MemPage.aData elements if needed.
72886*/
72887static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
72888  DbPage *pDbPage;
72889  assert( sqlite3_mutex_held(pBt->mutex) );
72890  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
72891  if( pDbPage ){
72892    return btreePageFromDbPage(pDbPage, pgno, pBt);
72893  }
72894  return 0;
72895}
72896
72897/*
72898** Return the size of the database file in pages. If there is any kind of
72899** error, return ((unsigned int)-1).
72900*/
72901static Pgno btreePagecount(BtShared *pBt){
72902  return pBt->nPage;
72903}
72904SQLITE_PRIVATE Pgno sqlite3BtreeLastPage(Btree *p){
72905  assert( sqlite3BtreeHoldsMutex(p) );
72906  return btreePagecount(p->pBt);
72907}
72908
72909/*
72910** Get a page from the pager and initialize it.
72911*/
72912static int getAndInitPage(
72913  BtShared *pBt,                  /* The database file */
72914  Pgno pgno,                      /* Number of the page to get */
72915  MemPage **ppPage,               /* Write the page pointer here */
72916  int bReadOnly                   /* True for a read-only page */
72917){
72918  int rc;
72919  DbPage *pDbPage;
72920  MemPage *pPage;
72921  assert( sqlite3_mutex_held(pBt->mutex) );
72922
72923  if( pgno>btreePagecount(pBt) ){
72924    *ppPage = 0;
72925    return SQLITE_CORRUPT_BKPT;
72926  }
72927  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
72928  if( rc ){
72929    *ppPage = 0;
72930    return rc;
72931  }
72932  pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
72933  if( pPage->isInit==0 ){
72934    btreePageFromDbPage(pDbPage, pgno, pBt);
72935    rc = btreeInitPage(pPage);
72936    if( rc!=SQLITE_OK ){
72937      releasePage(pPage);
72938      *ppPage = 0;
72939      return rc;
72940    }
72941  }
72942  assert( pPage->pgno==pgno || CORRUPT_DB );
72943  assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
72944  *ppPage = pPage;
72945  return SQLITE_OK;
72946}
72947
72948/*
72949** Release a MemPage.  This should be called once for each prior
72950** call to btreeGetPage.
72951**
72952** Page1 is a special case and must be released using releasePageOne().
72953*/
72954static void releasePageNotNull(MemPage *pPage){
72955  assert( pPage->aData );
72956  assert( pPage->pBt );
72957  assert( pPage->pDbPage!=0 );
72958  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
72959  assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
72960  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
72961  sqlite3PagerUnrefNotNull(pPage->pDbPage);
72962}
72963static void releasePage(MemPage *pPage){
72964  if( pPage ) releasePageNotNull(pPage);
72965}
72966static void releasePageOne(MemPage *pPage){
72967  assert( pPage!=0 );
72968  assert( pPage->aData );
72969  assert( pPage->pBt );
72970  assert( pPage->pDbPage!=0 );
72971  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
72972  assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
72973  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
72974  sqlite3PagerUnrefPageOne(pPage->pDbPage);
72975}
72976
72977/*
72978** Get an unused page.
72979**
72980** This works just like btreeGetPage() with the addition:
72981**
72982**   *  If the page is already in use for some other purpose, immediately
72983**      release it and return an SQLITE_CURRUPT error.
72984**   *  Make sure the isInit flag is clear
72985*/
72986static int btreeGetUnusedPage(
72987  BtShared *pBt,       /* The btree */
72988  Pgno pgno,           /* Number of the page to fetch */
72989  MemPage **ppPage,    /* Return the page in this parameter */
72990  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
72991){
72992  int rc = btreeGetPage(pBt, pgno, ppPage, flags);
72993  if( rc==SQLITE_OK ){
72994    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
72995      releasePage(*ppPage);
72996      *ppPage = 0;
72997      return SQLITE_CORRUPT_BKPT;
72998    }
72999    (*ppPage)->isInit = 0;
73000  }else{
73001    *ppPage = 0;
73002  }
73003  return rc;
73004}
73005
73006
73007/*
73008** During a rollback, when the pager reloads information into the cache
73009** so that the cache is restored to its original state at the start of
73010** the transaction, for each page restored this routine is called.
73011**
73012** This routine needs to reset the extra data section at the end of the
73013** page to agree with the restored data.
73014*/
73015static void pageReinit(DbPage *pData){
73016  MemPage *pPage;
73017  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
73018  assert( sqlite3PagerPageRefcount(pData)>0 );
73019  if( pPage->isInit ){
73020    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
73021    pPage->isInit = 0;
73022    if( sqlite3PagerPageRefcount(pData)>1 ){
73023      /* pPage might not be a btree page;  it might be an overflow page
73024      ** or ptrmap page or a free page.  In those cases, the following
73025      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
73026      ** But no harm is done by this.  And it is very important that
73027      ** btreeInitPage() be called on every btree page so we make
73028      ** the call for every page that comes in for re-initializing. */
73029      btreeInitPage(pPage);
73030    }
73031  }
73032}
73033
73034/*
73035** Invoke the busy handler for a btree.
73036*/
73037static int btreeInvokeBusyHandler(void *pArg){
73038  BtShared *pBt = (BtShared*)pArg;
73039  assert( pBt->db );
73040  assert( sqlite3_mutex_held(pBt->db->mutex) );
73041  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
73042}
73043
73044/*
73045** Open a database file.
73046**
73047** zFilename is the name of the database file.  If zFilename is NULL
73048** then an ephemeral database is created.  The ephemeral database might
73049** be exclusively in memory, or it might use a disk-based memory cache.
73050** Either way, the ephemeral database will be automatically deleted
73051** when sqlite3BtreeClose() is called.
73052**
73053** If zFilename is ":memory:" then an in-memory database is created
73054** that is automatically destroyed when it is closed.
73055**
73056** The "flags" parameter is a bitmask that might contain bits like
73057** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
73058**
73059** If the database is already opened in the same database connection
73060** and we are in shared cache mode, then the open will fail with an
73061** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
73062** objects in the same database connection since doing so will lead
73063** to problems with locking.
73064*/
73065SQLITE_PRIVATE int sqlite3BtreeOpen(
73066  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
73067  const char *zFilename,  /* Name of the file containing the BTree database */
73068  sqlite3 *db,            /* Associated database handle */
73069  Btree **ppBtree,        /* Pointer to new Btree object written here */
73070  int flags,              /* Options */
73071  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
73072){
73073  BtShared *pBt = 0;             /* Shared part of btree structure */
73074  Btree *p;                      /* Handle to return */
73075  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
73076  int rc = SQLITE_OK;            /* Result code from this function */
73077  u8 nReserve;                   /* Byte of unused space on each page */
73078  unsigned char zDbHeader[100];  /* Database header content */
73079
73080  /* True if opening an ephemeral, temporary database */
73081  const int isTempDb = zFilename==0 || zFilename[0]==0;
73082
73083  /* Set the variable isMemdb to true for an in-memory database, or
73084  ** false for a file-based database.
73085  */
73086#ifdef SQLITE_OMIT_MEMORYDB
73087  const int isMemdb = 0;
73088#else
73089  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
73090                       || (isTempDb && sqlite3TempInMemory(db))
73091                       || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
73092#endif
73093
73094  assert( db!=0 );
73095  assert( pVfs!=0 );
73096  assert( sqlite3_mutex_held(db->mutex) );
73097  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
73098
73099  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
73100  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
73101
73102  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
73103  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
73104
73105  if( isMemdb ){
73106    flags |= BTREE_MEMORY;
73107  }
73108  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
73109    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
73110  }
73111  p = sqlite3MallocZero(sizeof(Btree));
73112  if( !p ){
73113    return SQLITE_NOMEM_BKPT;
73114  }
73115  p->inTrans = TRANS_NONE;
73116  p->db = db;
73117#ifndef SQLITE_OMIT_SHARED_CACHE
73118  p->lock.pBtree = p;
73119  p->lock.iTable = 1;
73120#endif
73121
73122#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
73123  /*
73124  ** If this Btree is a candidate for shared cache, try to find an
73125  ** existing BtShared object that we can share with
73126  */
73127  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
73128    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
73129      int nFilename = sqlite3Strlen30(zFilename)+1;
73130      int nFullPathname = pVfs->mxPathname+1;
73131      char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
73132      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
73133
73134      p->sharable = 1;
73135      if( !zFullPathname ){
73136        sqlite3_free(p);
73137        return SQLITE_NOMEM_BKPT;
73138      }
73139      if( isMemdb ){
73140        memcpy(zFullPathname, zFilename, nFilename);
73141      }else{
73142        rc = sqlite3OsFullPathname(pVfs, zFilename,
73143                                   nFullPathname, zFullPathname);
73144        if( rc ){
73145          if( rc==SQLITE_OK_SYMLINK ){
73146            rc = SQLITE_OK;
73147          }else{
73148            sqlite3_free(zFullPathname);
73149            sqlite3_free(p);
73150            return rc;
73151          }
73152        }
73153      }
73154#if SQLITE_THREADSAFE
73155      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
73156      sqlite3_mutex_enter(mutexOpen);
73157      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
73158      sqlite3_mutex_enter(mutexShared);
73159#endif
73160      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
73161        assert( pBt->nRef>0 );
73162        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
73163                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
73164          int iDb;
73165          for(iDb=db->nDb-1; iDb>=0; iDb--){
73166            Btree *pExisting = db->aDb[iDb].pBt;
73167            if( pExisting && pExisting->pBt==pBt ){
73168              sqlite3_mutex_leave(mutexShared);
73169              sqlite3_mutex_leave(mutexOpen);
73170              sqlite3_free(zFullPathname);
73171              sqlite3_free(p);
73172              return SQLITE_CONSTRAINT;
73173            }
73174          }
73175          p->pBt = pBt;
73176          pBt->nRef++;
73177          break;
73178        }
73179      }
73180      sqlite3_mutex_leave(mutexShared);
73181      sqlite3_free(zFullPathname);
73182    }
73183#ifdef SQLITE_DEBUG
73184    else{
73185      /* In debug mode, we mark all persistent databases as sharable
73186      ** even when they are not.  This exercises the locking code and
73187      ** gives more opportunity for asserts(sqlite3_mutex_held())
73188      ** statements to find locking problems.
73189      */
73190      p->sharable = 1;
73191    }
73192#endif
73193  }
73194#endif
73195  if( pBt==0 ){
73196    /*
73197    ** The following asserts make sure that structures used by the btree are
73198    ** the right size.  This is to guard against size changes that result
73199    ** when compiling on a different architecture.
73200    */
73201    assert( sizeof(i64)==8 );
73202    assert( sizeof(u64)==8 );
73203    assert( sizeof(u32)==4 );
73204    assert( sizeof(u16)==2 );
73205    assert( sizeof(Pgno)==4 );
73206
73207    /* Suppress false-positive compiler warning from PVS-Studio */
73208    memset(&zDbHeader[16], 0, 8);
73209
73210    pBt = sqlite3MallocZero( sizeof(*pBt) );
73211    if( pBt==0 ){
73212      rc = SQLITE_NOMEM_BKPT;
73213      goto btree_open_out;
73214    }
73215    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
73216                          sizeof(MemPage), flags, vfsFlags, pageReinit);
73217    if( rc==SQLITE_OK ){
73218      sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
73219      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
73220    }
73221    if( rc!=SQLITE_OK ){
73222      goto btree_open_out;
73223    }
73224    pBt->openFlags = (u8)flags;
73225    pBt->db = db;
73226    sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
73227    p->pBt = pBt;
73228
73229    pBt->pCursor = 0;
73230    pBt->pPage1 = 0;
73231    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
73232#if defined(SQLITE_SECURE_DELETE)
73233    pBt->btsFlags |= BTS_SECURE_DELETE;
73234#elif defined(SQLITE_FAST_SECURE_DELETE)
73235    pBt->btsFlags |= BTS_OVERWRITE;
73236#endif
73237    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
73238    ** determined by the 2-byte integer located at an offset of 16 bytes from
73239    ** the beginning of the database file. */
73240    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
73241    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
73242         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
73243      pBt->pageSize = 0;
73244#ifndef SQLITE_OMIT_AUTOVACUUM
73245      /* If the magic name ":memory:" will create an in-memory database, then
73246      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
73247      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
73248      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
73249      ** regular file-name. In this case the auto-vacuum applies as per normal.
73250      */
73251      if( zFilename && !isMemdb ){
73252        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
73253        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
73254      }
73255#endif
73256      nReserve = 0;
73257    }else{
73258      /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
73259      ** determined by the one-byte unsigned integer found at an offset of 20
73260      ** into the database file header. */
73261      nReserve = zDbHeader[20];
73262      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
73263#ifndef SQLITE_OMIT_AUTOVACUUM
73264      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
73265      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
73266#endif
73267    }
73268    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
73269    if( rc ) goto btree_open_out;
73270    pBt->usableSize = pBt->pageSize - nReserve;
73271    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
73272
73273#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
73274    /* Add the new BtShared object to the linked list sharable BtShareds.
73275    */
73276    pBt->nRef = 1;
73277    if( p->sharable ){
73278      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
73279      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
73280      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
73281        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
73282        if( pBt->mutex==0 ){
73283          rc = SQLITE_NOMEM_BKPT;
73284          goto btree_open_out;
73285        }
73286      }
73287      sqlite3_mutex_enter(mutexShared);
73288      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
73289      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
73290      sqlite3_mutex_leave(mutexShared);
73291    }
73292#endif
73293  }
73294
73295#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
73296  /* If the new Btree uses a sharable pBtShared, then link the new
73297  ** Btree into the list of all sharable Btrees for the same connection.
73298  ** The list is kept in ascending order by pBt address.
73299  */
73300  if( p->sharable ){
73301    int i;
73302    Btree *pSib;
73303    for(i=0; i<db->nDb; i++){
73304      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
73305        while( pSib->pPrev ){ pSib = pSib->pPrev; }
73306        if( (uptr)p->pBt<(uptr)pSib->pBt ){
73307          p->pNext = pSib;
73308          p->pPrev = 0;
73309          pSib->pPrev = p;
73310        }else{
73311          while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
73312            pSib = pSib->pNext;
73313          }
73314          p->pNext = pSib->pNext;
73315          p->pPrev = pSib;
73316          if( p->pNext ){
73317            p->pNext->pPrev = p;
73318          }
73319          pSib->pNext = p;
73320        }
73321        break;
73322      }
73323    }
73324  }
73325#endif
73326  *ppBtree = p;
73327
73328btree_open_out:
73329  if( rc!=SQLITE_OK ){
73330    if( pBt && pBt->pPager ){
73331      sqlite3PagerClose(pBt->pPager, 0);
73332    }
73333    sqlite3_free(pBt);
73334    sqlite3_free(p);
73335    *ppBtree = 0;
73336  }else{
73337    sqlite3_file *pFile;
73338
73339    /* If the B-Tree was successfully opened, set the pager-cache size to the
73340    ** default value. Except, when opening on an existing shared pager-cache,
73341    ** do not change the pager-cache size.
73342    */
73343    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
73344      sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
73345    }
73346
73347    pFile = sqlite3PagerFile(pBt->pPager);
73348    if( pFile->pMethods ){
73349      sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
73350    }
73351  }
73352  if( mutexOpen ){
73353    assert( sqlite3_mutex_held(mutexOpen) );
73354    sqlite3_mutex_leave(mutexOpen);
73355  }
73356  assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
73357  return rc;
73358}
73359
73360/*
73361** Decrement the BtShared.nRef counter.  When it reaches zero,
73362** remove the BtShared structure from the sharing list.  Return
73363** true if the BtShared.nRef counter reaches zero and return
73364** false if it is still positive.
73365*/
73366static int removeFromSharingList(BtShared *pBt){
73367#ifndef SQLITE_OMIT_SHARED_CACHE
73368  MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
73369  BtShared *pList;
73370  int removed = 0;
73371
73372  assert( sqlite3_mutex_notheld(pBt->mutex) );
73373  MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
73374  sqlite3_mutex_enter(pMainMtx);
73375  pBt->nRef--;
73376  if( pBt->nRef<=0 ){
73377    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
73378      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
73379    }else{
73380      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
73381      while( ALWAYS(pList) && pList->pNext!=pBt ){
73382        pList=pList->pNext;
73383      }
73384      if( ALWAYS(pList) ){
73385        pList->pNext = pBt->pNext;
73386      }
73387    }
73388    if( SQLITE_THREADSAFE ){
73389      sqlite3_mutex_free(pBt->mutex);
73390    }
73391    removed = 1;
73392  }
73393  sqlite3_mutex_leave(pMainMtx);
73394  return removed;
73395#else
73396  return 1;
73397#endif
73398}
73399
73400/*
73401** Make sure pBt->pTmpSpace points to an allocation of
73402** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
73403** pointer.
73404*/
73405static SQLITE_NOINLINE int allocateTempSpace(BtShared *pBt){
73406  assert( pBt!=0 );
73407  assert( pBt->pTmpSpace==0 );
73408  /* This routine is called only by btreeCursor() when allocating the
73409  ** first write cursor for the BtShared object */
73410  assert( pBt->pCursor!=0 && (pBt->pCursor->curFlags & BTCF_WriteFlag)!=0 );
73411  pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
73412  if( pBt->pTmpSpace==0 ){
73413    BtCursor *pCur = pBt->pCursor;
73414    pBt->pCursor = pCur->pNext;  /* Unlink the cursor */
73415    memset(pCur, 0, sizeof(*pCur));
73416    return SQLITE_NOMEM_BKPT;
73417  }
73418
73419  /* One of the uses of pBt->pTmpSpace is to format cells before
73420  ** inserting them into a leaf page (function fillInCell()). If
73421  ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
73422  ** by the various routines that manipulate binary cells. Which
73423  ** can mean that fillInCell() only initializes the first 2 or 3
73424  ** bytes of pTmpSpace, but that the first 4 bytes are copied from
73425  ** it into a database page. This is not actually a problem, but it
73426  ** does cause a valgrind error when the 1 or 2 bytes of uninitialized
73427  ** data is passed to system call write(). So to avoid this error,
73428  ** zero the first 4 bytes of temp space here.
73429  **
73430  ** Also:  Provide four bytes of initialized space before the
73431  ** beginning of pTmpSpace as an area available to prepend the
73432  ** left-child pointer to the beginning of a cell.
73433  */
73434  memset(pBt->pTmpSpace, 0, 8);
73435  pBt->pTmpSpace += 4;
73436  return SQLITE_OK;
73437}
73438
73439/*
73440** Free the pBt->pTmpSpace allocation
73441*/
73442static void freeTempSpace(BtShared *pBt){
73443  if( pBt->pTmpSpace ){
73444    pBt->pTmpSpace -= 4;
73445    sqlite3PageFree(pBt->pTmpSpace);
73446    pBt->pTmpSpace = 0;
73447  }
73448}
73449
73450/*
73451** Close an open database and invalidate all cursors.
73452*/
73453SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
73454  BtShared *pBt = p->pBt;
73455
73456  /* Close all cursors opened via this handle.  */
73457  assert( sqlite3_mutex_held(p->db->mutex) );
73458  sqlite3BtreeEnter(p);
73459
73460  /* Verify that no other cursors have this Btree open */
73461#ifdef SQLITE_DEBUG
73462  {
73463    BtCursor *pCur = pBt->pCursor;
73464    while( pCur ){
73465      BtCursor *pTmp = pCur;
73466      pCur = pCur->pNext;
73467      assert( pTmp->pBtree!=p );
73468
73469    }
73470  }
73471#endif
73472
73473  /* Rollback any active transaction and free the handle structure.
73474  ** The call to sqlite3BtreeRollback() drops any table-locks held by
73475  ** this handle.
73476  */
73477  sqlite3BtreeRollback(p, SQLITE_OK, 0);
73478  sqlite3BtreeLeave(p);
73479
73480  /* If there are still other outstanding references to the shared-btree
73481  ** structure, return now. The remainder of this procedure cleans
73482  ** up the shared-btree.
73483  */
73484  assert( p->wantToLock==0 && p->locked==0 );
73485  if( !p->sharable || removeFromSharingList(pBt) ){
73486    /* The pBt is no longer on the sharing list, so we can access
73487    ** it without having to hold the mutex.
73488    **
73489    ** Clean out and delete the BtShared object.
73490    */
73491    assert( !pBt->pCursor );
73492    sqlite3PagerClose(pBt->pPager, p->db);
73493    if( pBt->xFreeSchema && pBt->pSchema ){
73494      pBt->xFreeSchema(pBt->pSchema);
73495    }
73496    sqlite3DbFree(0, pBt->pSchema);
73497    freeTempSpace(pBt);
73498    sqlite3_free(pBt);
73499  }
73500
73501#ifndef SQLITE_OMIT_SHARED_CACHE
73502  assert( p->wantToLock==0 );
73503  assert( p->locked==0 );
73504  if( p->pPrev ) p->pPrev->pNext = p->pNext;
73505  if( p->pNext ) p->pNext->pPrev = p->pPrev;
73506#endif
73507
73508  sqlite3_free(p);
73509  return SQLITE_OK;
73510}
73511
73512/*
73513** Change the "soft" limit on the number of pages in the cache.
73514** Unused and unmodified pages will be recycled when the number of
73515** pages in the cache exceeds this soft limit.  But the size of the
73516** cache is allowed to grow larger than this limit if it contains
73517** dirty pages or pages still in active use.
73518*/
73519SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
73520  BtShared *pBt = p->pBt;
73521  assert( sqlite3_mutex_held(p->db->mutex) );
73522  sqlite3BtreeEnter(p);
73523  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
73524  sqlite3BtreeLeave(p);
73525  return SQLITE_OK;
73526}
73527
73528/*
73529** Change the "spill" limit on the number of pages in the cache.
73530** If the number of pages exceeds this limit during a write transaction,
73531** the pager might attempt to "spill" pages to the journal early in
73532** order to free up memory.
73533**
73534** The value returned is the current spill size.  If zero is passed
73535** as an argument, no changes are made to the spill size setting, so
73536** using mxPage of 0 is a way to query the current spill size.
73537*/
73538SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
73539  BtShared *pBt = p->pBt;
73540  int res;
73541  assert( sqlite3_mutex_held(p->db->mutex) );
73542  sqlite3BtreeEnter(p);
73543  res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
73544  sqlite3BtreeLeave(p);
73545  return res;
73546}
73547
73548#if SQLITE_MAX_MMAP_SIZE>0
73549/*
73550** Change the limit on the amount of the database file that may be
73551** memory mapped.
73552*/
73553SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
73554  BtShared *pBt = p->pBt;
73555  assert( sqlite3_mutex_held(p->db->mutex) );
73556  sqlite3BtreeEnter(p);
73557  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
73558  sqlite3BtreeLeave(p);
73559  return SQLITE_OK;
73560}
73561#endif /* SQLITE_MAX_MMAP_SIZE>0 */
73562
73563/*
73564** Change the way data is synced to disk in order to increase or decrease
73565** how well the database resists damage due to OS crashes and power
73566** failures.  Level 1 is the same as asynchronous (no syncs() occur and
73567** there is a high probability of damage)  Level 2 is the default.  There
73568** is a very low but non-zero probability of damage.  Level 3 reduces the
73569** probability of damage to near zero but with a write performance reduction.
73570*/
73571#ifndef SQLITE_OMIT_PAGER_PRAGMAS
73572SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
73573  Btree *p,              /* The btree to set the safety level on */
73574  unsigned pgFlags       /* Various PAGER_* flags */
73575){
73576  BtShared *pBt = p->pBt;
73577  assert( sqlite3_mutex_held(p->db->mutex) );
73578  sqlite3BtreeEnter(p);
73579  sqlite3PagerSetFlags(pBt->pPager, pgFlags);
73580  sqlite3BtreeLeave(p);
73581  return SQLITE_OK;
73582}
73583#endif
73584
73585/*
73586** Change the default pages size and the number of reserved bytes per page.
73587** Or, if the page size has already been fixed, return SQLITE_READONLY
73588** without changing anything.
73589**
73590** The page size must be a power of 2 between 512 and 65536.  If the page
73591** size supplied does not meet this constraint then the page size is not
73592** changed.
73593**
73594** Page sizes are constrained to be a power of two so that the region
73595** of the database file used for locking (beginning at PENDING_BYTE,
73596** the first byte past the 1GB boundary, 0x40000000) needs to occur
73597** at the beginning of a page.
73598**
73599** If parameter nReserve is less than zero, then the number of reserved
73600** bytes per page is left unchanged.
73601**
73602** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
73603** and autovacuum mode can no longer be changed.
73604*/
73605SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
73606  int rc = SQLITE_OK;
73607  int x;
73608  BtShared *pBt = p->pBt;
73609  assert( nReserve>=0 && nReserve<=255 );
73610  sqlite3BtreeEnter(p);
73611  pBt->nReserveWanted = nReserve;
73612  x = pBt->pageSize - pBt->usableSize;
73613  if( nReserve<x ) nReserve = x;
73614  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
73615    sqlite3BtreeLeave(p);
73616    return SQLITE_READONLY;
73617  }
73618  assert( nReserve>=0 && nReserve<=255 );
73619  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
73620        ((pageSize-1)&pageSize)==0 ){
73621    assert( (pageSize & 7)==0 );
73622    assert( !pBt->pCursor );
73623    if( nReserve>32 && pageSize==512 ) pageSize = 1024;
73624    pBt->pageSize = (u32)pageSize;
73625    freeTempSpace(pBt);
73626  }
73627  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
73628  pBt->usableSize = pBt->pageSize - (u16)nReserve;
73629  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
73630  sqlite3BtreeLeave(p);
73631  return rc;
73632}
73633
73634/*
73635** Return the currently defined page size
73636*/
73637SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
73638  return p->pBt->pageSize;
73639}
73640
73641/*
73642** This function is similar to sqlite3BtreeGetReserve(), except that it
73643** may only be called if it is guaranteed that the b-tree mutex is already
73644** held.
73645**
73646** This is useful in one special case in the backup API code where it is
73647** known that the shared b-tree mutex is held, but the mutex on the
73648** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
73649** were to be called, it might collide with some other operation on the
73650** database handle that owns *p, causing undefined behavior.
73651*/
73652SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
73653  int n;
73654  assert( sqlite3_mutex_held(p->pBt->mutex) );
73655  n = p->pBt->pageSize - p->pBt->usableSize;
73656  return n;
73657}
73658
73659/*
73660** Return the number of bytes of space at the end of every page that
73661** are intentionally left unused.  This is the "reserved" space that is
73662** sometimes used by extensions.
73663**
73664** The value returned is the larger of the current reserve size and
73665** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
73666** The amount of reserve can only grow - never shrink.
73667*/
73668SQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(Btree *p){
73669  int n1, n2;
73670  sqlite3BtreeEnter(p);
73671  n1 = (int)p->pBt->nReserveWanted;
73672  n2 = sqlite3BtreeGetReserveNoMutex(p);
73673  sqlite3BtreeLeave(p);
73674  return n1>n2 ? n1 : n2;
73675}
73676
73677
73678/*
73679** Set the maximum page count for a database if mxPage is positive.
73680** No changes are made if mxPage is 0 or negative.
73681** Regardless of the value of mxPage, return the maximum page count.
73682*/
73683SQLITE_PRIVATE Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
73684  Pgno n;
73685  sqlite3BtreeEnter(p);
73686  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
73687  sqlite3BtreeLeave(p);
73688  return n;
73689}
73690
73691/*
73692** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
73693**
73694**    newFlag==0       Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
73695**    newFlag==1       BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
73696**    newFlag==2       BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
73697**    newFlag==(-1)    No changes
73698**
73699** This routine acts as a query if newFlag is less than zero
73700**
73701** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
73702** freelist leaf pages are not written back to the database.  Thus in-page
73703** deleted content is cleared, but freelist deleted content is not.
73704**
73705** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
73706** that freelist leaf pages are written back into the database, increasing
73707** the amount of disk I/O.
73708*/
73709SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
73710  int b;
73711  if( p==0 ) return 0;
73712  sqlite3BtreeEnter(p);
73713  assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
73714  assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
73715  if( newFlag>=0 ){
73716    p->pBt->btsFlags &= ~BTS_FAST_SECURE;
73717    p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
73718  }
73719  b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
73720  sqlite3BtreeLeave(p);
73721  return b;
73722}
73723
73724/*
73725** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
73726** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
73727** is disabled. The default value for the auto-vacuum property is
73728** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
73729*/
73730SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
73731#ifdef SQLITE_OMIT_AUTOVACUUM
73732  return SQLITE_READONLY;
73733#else
73734  BtShared *pBt = p->pBt;
73735  int rc = SQLITE_OK;
73736  u8 av = (u8)autoVacuum;
73737
73738  sqlite3BtreeEnter(p);
73739  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
73740    rc = SQLITE_READONLY;
73741  }else{
73742    pBt->autoVacuum = av ?1:0;
73743    pBt->incrVacuum = av==2 ?1:0;
73744  }
73745  sqlite3BtreeLeave(p);
73746  return rc;
73747#endif
73748}
73749
73750/*
73751** Return the value of the 'auto-vacuum' property. If auto-vacuum is
73752** enabled 1 is returned. Otherwise 0.
73753*/
73754SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
73755#ifdef SQLITE_OMIT_AUTOVACUUM
73756  return BTREE_AUTOVACUUM_NONE;
73757#else
73758  int rc;
73759  sqlite3BtreeEnter(p);
73760  rc = (
73761    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
73762    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
73763    BTREE_AUTOVACUUM_INCR
73764  );
73765  sqlite3BtreeLeave(p);
73766  return rc;
73767#endif
73768}
73769
73770/*
73771** If the user has not set the safety-level for this database connection
73772** using "PRAGMA synchronous", and if the safety-level is not already
73773** set to the value passed to this function as the second parameter,
73774** set it so.
73775*/
73776#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
73777    && !defined(SQLITE_OMIT_WAL)
73778static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
73779  sqlite3 *db;
73780  Db *pDb;
73781  if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
73782    while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
73783    if( pDb->bSyncSet==0
73784     && pDb->safety_level!=safety_level
73785     && pDb!=&db->aDb[1]
73786    ){
73787      pDb->safety_level = safety_level;
73788      sqlite3PagerSetFlags(pBt->pPager,
73789          pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
73790    }
73791  }
73792}
73793#else
73794# define setDefaultSyncFlag(pBt,safety_level)
73795#endif
73796
73797/* Forward declaration */
73798static int newDatabase(BtShared*);
73799
73800
73801/*
73802** Get a reference to pPage1 of the database file.  This will
73803** also acquire a readlock on that file.
73804**
73805** SQLITE_OK is returned on success.  If the file is not a
73806** well-formed database file, then SQLITE_CORRUPT is returned.
73807** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
73808** is returned if we run out of memory.
73809*/
73810static int lockBtree(BtShared *pBt){
73811  int rc;              /* Result code from subfunctions */
73812  MemPage *pPage1;     /* Page 1 of the database file */
73813  u32 nPage;           /* Number of pages in the database */
73814  u32 nPageFile = 0;   /* Number of pages in the database file */
73815
73816  assert( sqlite3_mutex_held(pBt->mutex) );
73817  assert( pBt->pPage1==0 );
73818  rc = sqlite3PagerSharedLock(pBt->pPager);
73819  if( rc!=SQLITE_OK ) return rc;
73820  rc = btreeGetPage(pBt, 1, &pPage1, 0);
73821  if( rc!=SQLITE_OK ) return rc;
73822
73823  /* Do some checking to help insure the file we opened really is
73824  ** a valid database file.
73825  */
73826  nPage = get4byte(28+(u8*)pPage1->aData);
73827  sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
73828  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
73829    nPage = nPageFile;
73830  }
73831  if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
73832    nPage = 0;
73833  }
73834  if( nPage>0 ){
73835    u32 pageSize;
73836    u32 usableSize;
73837    u8 *page1 = pPage1->aData;
73838    rc = SQLITE_NOTADB;
73839    /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
73840    ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
73841    ** 61 74 20 33 00. */
73842    if( memcmp(page1, zMagicHeader, 16)!=0 ){
73843      goto page1_init_failed;
73844    }
73845
73846#ifdef SQLITE_OMIT_WAL
73847    if( page1[18]>1 ){
73848      pBt->btsFlags |= BTS_READ_ONLY;
73849    }
73850    if( page1[19]>1 ){
73851      goto page1_init_failed;
73852    }
73853#else
73854    if( page1[18]>2 ){
73855      pBt->btsFlags |= BTS_READ_ONLY;
73856    }
73857    if( page1[19]>2 ){
73858      goto page1_init_failed;
73859    }
73860
73861    /* If the read version is set to 2, this database should be accessed
73862    ** in WAL mode. If the log is not already open, open it now. Then
73863    ** return SQLITE_OK and return without populating BtShared.pPage1.
73864    ** The caller detects this and calls this function again. This is
73865    ** required as the version of page 1 currently in the page1 buffer
73866    ** may not be the latest version - there may be a newer one in the log
73867    ** file.
73868    */
73869    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
73870      int isOpen = 0;
73871      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
73872      if( rc!=SQLITE_OK ){
73873        goto page1_init_failed;
73874      }else{
73875        setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
73876        if( isOpen==0 ){
73877          releasePageOne(pPage1);
73878          return SQLITE_OK;
73879        }
73880      }
73881      rc = SQLITE_NOTADB;
73882    }else{
73883      setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
73884    }
73885#endif
73886
73887    /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
73888    ** fractions and the leaf payload fraction values must be 64, 32, and 32.
73889    **
73890    ** The original design allowed these amounts to vary, but as of
73891    ** version 3.6.0, we require them to be fixed.
73892    */
73893    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
73894      goto page1_init_failed;
73895    }
73896    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
73897    ** determined by the 2-byte integer located at an offset of 16 bytes from
73898    ** the beginning of the database file. */
73899    pageSize = (page1[16]<<8) | (page1[17]<<16);
73900    /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
73901    ** between 512 and 65536 inclusive. */
73902    if( ((pageSize-1)&pageSize)!=0
73903     || pageSize>SQLITE_MAX_PAGE_SIZE
73904     || pageSize<=256
73905    ){
73906      goto page1_init_failed;
73907    }
73908    assert( (pageSize & 7)==0 );
73909    /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
73910    ** integer at offset 20 is the number of bytes of space at the end of
73911    ** each page to reserve for extensions.
73912    **
73913    ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
73914    ** determined by the one-byte unsigned integer found at an offset of 20
73915    ** into the database file header. */
73916    usableSize = pageSize - page1[20];
73917    if( (u32)pageSize!=pBt->pageSize ){
73918      /* After reading the first page of the database assuming a page size
73919      ** of BtShared.pageSize, we have discovered that the page-size is
73920      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
73921      ** zero and return SQLITE_OK. The caller will call this function
73922      ** again with the correct page-size.
73923      */
73924      releasePageOne(pPage1);
73925      pBt->usableSize = usableSize;
73926      pBt->pageSize = pageSize;
73927      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
73928      freeTempSpace(pBt);
73929      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
73930                                   pageSize-usableSize);
73931      return rc;
73932    }
73933    if( nPage>nPageFile ){
73934      if( sqlite3WritableSchema(pBt->db)==0 ){
73935        rc = SQLITE_CORRUPT_BKPT;
73936        goto page1_init_failed;
73937      }else{
73938        nPage = nPageFile;
73939      }
73940    }
73941    /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
73942    ** be less than 480. In other words, if the page size is 512, then the
73943    ** reserved space size cannot exceed 32. */
73944    if( usableSize<480 ){
73945      goto page1_init_failed;
73946    }
73947    pBt->btsFlags |= BTS_PAGESIZE_FIXED;
73948    pBt->pageSize = pageSize;
73949    pBt->usableSize = usableSize;
73950#ifndef SQLITE_OMIT_AUTOVACUUM
73951    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
73952    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
73953#endif
73954  }
73955
73956  /* maxLocal is the maximum amount of payload to store locally for
73957  ** a cell.  Make sure it is small enough so that at least minFanout
73958  ** cells can will fit on one page.  We assume a 10-byte page header.
73959  ** Besides the payload, the cell must store:
73960  **     2-byte pointer to the cell
73961  **     4-byte child pointer
73962  **     9-byte nKey value
73963  **     4-byte nData value
73964  **     4-byte overflow page pointer
73965  ** So a cell consists of a 2-byte pointer, a header which is as much as
73966  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
73967  ** page pointer.
73968  */
73969  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
73970  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
73971  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
73972  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
73973  if( pBt->maxLocal>127 ){
73974    pBt->max1bytePayload = 127;
73975  }else{
73976    pBt->max1bytePayload = (u8)pBt->maxLocal;
73977  }
73978  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
73979  pBt->pPage1 = pPage1;
73980  pBt->nPage = nPage;
73981  return SQLITE_OK;
73982
73983page1_init_failed:
73984  releasePageOne(pPage1);
73985  pBt->pPage1 = 0;
73986  return rc;
73987}
73988
73989#ifndef NDEBUG
73990/*
73991** Return the number of cursors open on pBt. This is for use
73992** in assert() expressions, so it is only compiled if NDEBUG is not
73993** defined.
73994**
73995** Only write cursors are counted if wrOnly is true.  If wrOnly is
73996** false then all cursors are counted.
73997**
73998** For the purposes of this routine, a cursor is any cursor that
73999** is capable of reading or writing to the database.  Cursors that
74000** have been tripped into the CURSOR_FAULT state are not counted.
74001*/
74002static int countValidCursors(BtShared *pBt, int wrOnly){
74003  BtCursor *pCur;
74004  int r = 0;
74005  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
74006    if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
74007     && pCur->eState!=CURSOR_FAULT ) r++;
74008  }
74009  return r;
74010}
74011#endif
74012
74013/*
74014** If there are no outstanding cursors and we are not in the middle
74015** of a transaction but there is a read lock on the database, then
74016** this routine unrefs the first page of the database file which
74017** has the effect of releasing the read lock.
74018**
74019** If there is a transaction in progress, this routine is a no-op.
74020*/
74021static void unlockBtreeIfUnused(BtShared *pBt){
74022  assert( sqlite3_mutex_held(pBt->mutex) );
74023  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
74024  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
74025    MemPage *pPage1 = pBt->pPage1;
74026    assert( pPage1->aData );
74027    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
74028    pBt->pPage1 = 0;
74029    releasePageOne(pPage1);
74030  }
74031}
74032
74033/*
74034** If pBt points to an empty file then convert that empty file
74035** into a new empty database by initializing the first page of
74036** the database.
74037*/
74038static int newDatabase(BtShared *pBt){
74039  MemPage *pP1;
74040  unsigned char *data;
74041  int rc;
74042
74043  assert( sqlite3_mutex_held(pBt->mutex) );
74044  if( pBt->nPage>0 ){
74045    return SQLITE_OK;
74046  }
74047  pP1 = pBt->pPage1;
74048  assert( pP1!=0 );
74049  data = pP1->aData;
74050  rc = sqlite3PagerWrite(pP1->pDbPage);
74051  if( rc ) return rc;
74052  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
74053  assert( sizeof(zMagicHeader)==16 );
74054  data[16] = (u8)((pBt->pageSize>>8)&0xff);
74055  data[17] = (u8)((pBt->pageSize>>16)&0xff);
74056  data[18] = 1;
74057  data[19] = 1;
74058  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
74059  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
74060  data[21] = 64;
74061  data[22] = 32;
74062  data[23] = 32;
74063  memset(&data[24], 0, 100-24);
74064  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
74065  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
74066#ifndef SQLITE_OMIT_AUTOVACUUM
74067  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
74068  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
74069  put4byte(&data[36 + 4*4], pBt->autoVacuum);
74070  put4byte(&data[36 + 7*4], pBt->incrVacuum);
74071#endif
74072  pBt->nPage = 1;
74073  data[31] = 1;
74074  return SQLITE_OK;
74075}
74076
74077/*
74078** Initialize the first page of the database file (creating a database
74079** consisting of a single page and no schema objects). Return SQLITE_OK
74080** if successful, or an SQLite error code otherwise.
74081*/
74082SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
74083  int rc;
74084  sqlite3BtreeEnter(p);
74085  p->pBt->nPage = 0;
74086  rc = newDatabase(p->pBt);
74087  sqlite3BtreeLeave(p);
74088  return rc;
74089}
74090
74091/*
74092** Attempt to start a new transaction. A write-transaction
74093** is started if the second argument is nonzero, otherwise a read-
74094** transaction.  If the second argument is 2 or more and exclusive
74095** transaction is started, meaning that no other process is allowed
74096** to access the database.  A preexisting transaction may not be
74097** upgraded to exclusive by calling this routine a second time - the
74098** exclusivity flag only works for a new transaction.
74099**
74100** A write-transaction must be started before attempting any
74101** changes to the database.  None of the following routines
74102** will work unless a transaction is started first:
74103**
74104**      sqlite3BtreeCreateTable()
74105**      sqlite3BtreeCreateIndex()
74106**      sqlite3BtreeClearTable()
74107**      sqlite3BtreeDropTable()
74108**      sqlite3BtreeInsert()
74109**      sqlite3BtreeDelete()
74110**      sqlite3BtreeUpdateMeta()
74111**
74112** If an initial attempt to acquire the lock fails because of lock contention
74113** and the database was previously unlocked, then invoke the busy handler
74114** if there is one.  But if there was previously a read-lock, do not
74115** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
74116** returned when there is already a read-lock in order to avoid a deadlock.
74117**
74118** Suppose there are two processes A and B.  A has a read lock and B has
74119** a reserved lock.  B tries to promote to exclusive but is blocked because
74120** of A's read lock.  A tries to promote to reserved but is blocked by B.
74121** One or the other of the two processes must give way or there can be
74122** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
74123** when A already has a read lock, we encourage A to give up and let B
74124** proceed.
74125*/
74126static SQLITE_NOINLINE int btreeBeginTrans(
74127  Btree *p,                 /* The btree in which to start the transaction */
74128  int wrflag,               /* True to start a write transaction */
74129  int *pSchemaVersion       /* Put schema version number here, if not NULL */
74130){
74131  BtShared *pBt = p->pBt;
74132  Pager *pPager = pBt->pPager;
74133  int rc = SQLITE_OK;
74134
74135  sqlite3BtreeEnter(p);
74136  btreeIntegrity(p);
74137
74138  /* If the btree is already in a write-transaction, or it
74139  ** is already in a read-transaction and a read-transaction
74140  ** is requested, this is a no-op.
74141  */
74142  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
74143    goto trans_begun;
74144  }
74145  assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
74146
74147  if( (p->db->flags & SQLITE_ResetDatabase)
74148   && sqlite3PagerIsreadonly(pPager)==0
74149  ){
74150    pBt->btsFlags &= ~BTS_READ_ONLY;
74151  }
74152
74153  /* Write transactions are not possible on a read-only database */
74154  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
74155    rc = SQLITE_READONLY;
74156    goto trans_begun;
74157  }
74158
74159#ifndef SQLITE_OMIT_SHARED_CACHE
74160  {
74161    sqlite3 *pBlock = 0;
74162    /* If another database handle has already opened a write transaction
74163    ** on this shared-btree structure and a second write transaction is
74164    ** requested, return SQLITE_LOCKED.
74165    */
74166    if( (wrflag && pBt->inTransaction==TRANS_WRITE)
74167     || (pBt->btsFlags & BTS_PENDING)!=0
74168    ){
74169      pBlock = pBt->pWriter->db;
74170    }else if( wrflag>1 ){
74171      BtLock *pIter;
74172      for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
74173        if( pIter->pBtree!=p ){
74174          pBlock = pIter->pBtree->db;
74175          break;
74176        }
74177      }
74178    }
74179    if( pBlock ){
74180      sqlite3ConnectionBlocked(p->db, pBlock);
74181      rc = SQLITE_LOCKED_SHAREDCACHE;
74182      goto trans_begun;
74183    }
74184  }
74185#endif
74186
74187  /* Any read-only or read-write transaction implies a read-lock on
74188  ** page 1. So if some other shared-cache client already has a write-lock
74189  ** on page 1, the transaction cannot be opened. */
74190  rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
74191  if( SQLITE_OK!=rc ) goto trans_begun;
74192
74193  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
74194  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
74195  do {
74196    sqlite3PagerWalDb(pPager, p->db);
74197
74198#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
74199    /* If transitioning from no transaction directly to a write transaction,
74200    ** block for the WRITER lock first if possible. */
74201    if( pBt->pPage1==0 && wrflag ){
74202      assert( pBt->inTransaction==TRANS_NONE );
74203      rc = sqlite3PagerWalWriteLock(pPager, 1);
74204      if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
74205    }
74206#endif
74207
74208    /* Call lockBtree() until either pBt->pPage1 is populated or
74209    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
74210    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
74211    ** reading page 1 it discovers that the page-size of the database
74212    ** file is not pBt->pageSize. In this case lockBtree() will update
74213    ** pBt->pageSize to the page-size of the file on disk.
74214    */
74215    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
74216
74217    if( rc==SQLITE_OK && wrflag ){
74218      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
74219        rc = SQLITE_READONLY;
74220      }else{
74221        rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
74222        if( rc==SQLITE_OK ){
74223          rc = newDatabase(pBt);
74224        }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
74225          /* if there was no transaction opened when this function was
74226          ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
74227          ** code to SQLITE_BUSY. */
74228          rc = SQLITE_BUSY;
74229        }
74230      }
74231    }
74232
74233    if( rc!=SQLITE_OK ){
74234      (void)sqlite3PagerWalWriteLock(pPager, 0);
74235      unlockBtreeIfUnused(pBt);
74236    }
74237  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
74238          btreeInvokeBusyHandler(pBt) );
74239  sqlite3PagerWalDb(pPager, 0);
74240#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
74241  if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
74242#endif
74243
74244  if( rc==SQLITE_OK ){
74245    if( p->inTrans==TRANS_NONE ){
74246      pBt->nTransaction++;
74247#ifndef SQLITE_OMIT_SHARED_CACHE
74248      if( p->sharable ){
74249        assert( p->lock.pBtree==p && p->lock.iTable==1 );
74250        p->lock.eLock = READ_LOCK;
74251        p->lock.pNext = pBt->pLock;
74252        pBt->pLock = &p->lock;
74253      }
74254#endif
74255    }
74256    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
74257    if( p->inTrans>pBt->inTransaction ){
74258      pBt->inTransaction = p->inTrans;
74259    }
74260    if( wrflag ){
74261      MemPage *pPage1 = pBt->pPage1;
74262#ifndef SQLITE_OMIT_SHARED_CACHE
74263      assert( !pBt->pWriter );
74264      pBt->pWriter = p;
74265      pBt->btsFlags &= ~BTS_EXCLUSIVE;
74266      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
74267#endif
74268
74269      /* If the db-size header field is incorrect (as it may be if an old
74270      ** client has been writing the database file), update it now. Doing
74271      ** this sooner rather than later means the database size can safely
74272      ** re-read the database size from page 1 if a savepoint or transaction
74273      ** rollback occurs within the transaction.
74274      */
74275      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
74276        rc = sqlite3PagerWrite(pPage1->pDbPage);
74277        if( rc==SQLITE_OK ){
74278          put4byte(&pPage1->aData[28], pBt->nPage);
74279        }
74280      }
74281    }
74282  }
74283
74284trans_begun:
74285  if( rc==SQLITE_OK ){
74286    if( pSchemaVersion ){
74287      *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
74288    }
74289    if( wrflag ){
74290      /* This call makes sure that the pager has the correct number of
74291      ** open savepoints. If the second parameter is greater than 0 and
74292      ** the sub-journal is not already open, then it will be opened here.
74293      */
74294      rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
74295    }
74296  }
74297
74298  btreeIntegrity(p);
74299  sqlite3BtreeLeave(p);
74300  return rc;
74301}
74302SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
74303  BtShared *pBt;
74304  if( p->sharable
74305   || p->inTrans==TRANS_NONE
74306   || (p->inTrans==TRANS_READ && wrflag!=0)
74307  ){
74308    return btreeBeginTrans(p,wrflag,pSchemaVersion);
74309  }
74310  pBt = p->pBt;
74311  if( pSchemaVersion ){
74312    *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
74313  }
74314  if( wrflag ){
74315    /* This call makes sure that the pager has the correct number of
74316    ** open savepoints. If the second parameter is greater than 0 and
74317    ** the sub-journal is not already open, then it will be opened here.
74318    */
74319    return sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
74320  }else{
74321    return SQLITE_OK;
74322  }
74323}
74324
74325#ifndef SQLITE_OMIT_AUTOVACUUM
74326
74327/*
74328** Set the pointer-map entries for all children of page pPage. Also, if
74329** pPage contains cells that point to overflow pages, set the pointer
74330** map entries for the overflow pages as well.
74331*/
74332static int setChildPtrmaps(MemPage *pPage){
74333  int i;                             /* Counter variable */
74334  int nCell;                         /* Number of cells in page pPage */
74335  int rc;                            /* Return code */
74336  BtShared *pBt = pPage->pBt;
74337  Pgno pgno = pPage->pgno;
74338
74339  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
74340  rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
74341  if( rc!=SQLITE_OK ) return rc;
74342  nCell = pPage->nCell;
74343
74344  for(i=0; i<nCell; i++){
74345    u8 *pCell = findCell(pPage, i);
74346
74347    ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
74348
74349    if( !pPage->leaf ){
74350      Pgno childPgno = get4byte(pCell);
74351      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
74352    }
74353  }
74354
74355  if( !pPage->leaf ){
74356    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
74357    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
74358  }
74359
74360  return rc;
74361}
74362
74363/*
74364** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
74365** that it points to iTo. Parameter eType describes the type of pointer to
74366** be modified, as  follows:
74367**
74368** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
74369**                   page of pPage.
74370**
74371** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
74372**                   page pointed to by one of the cells on pPage.
74373**
74374** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
74375**                   overflow page in the list.
74376*/
74377static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
74378  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
74379  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
74380  if( eType==PTRMAP_OVERFLOW2 ){
74381    /* The pointer is always the first 4 bytes of the page in this case.  */
74382    if( get4byte(pPage->aData)!=iFrom ){
74383      return SQLITE_CORRUPT_PAGE(pPage);
74384    }
74385    put4byte(pPage->aData, iTo);
74386  }else{
74387    int i;
74388    int nCell;
74389    int rc;
74390
74391    rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
74392    if( rc ) return rc;
74393    nCell = pPage->nCell;
74394
74395    for(i=0; i<nCell; i++){
74396      u8 *pCell = findCell(pPage, i);
74397      if( eType==PTRMAP_OVERFLOW1 ){
74398        CellInfo info;
74399        pPage->xParseCell(pPage, pCell, &info);
74400        if( info.nLocal<info.nPayload ){
74401          if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
74402            return SQLITE_CORRUPT_PAGE(pPage);
74403          }
74404          if( iFrom==get4byte(pCell+info.nSize-4) ){
74405            put4byte(pCell+info.nSize-4, iTo);
74406            break;
74407          }
74408        }
74409      }else{
74410        if( pCell+4 > pPage->aData+pPage->pBt->usableSize ){
74411          return SQLITE_CORRUPT_PAGE(pPage);
74412        }
74413        if( get4byte(pCell)==iFrom ){
74414          put4byte(pCell, iTo);
74415          break;
74416        }
74417      }
74418    }
74419
74420    if( i==nCell ){
74421      if( eType!=PTRMAP_BTREE ||
74422          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
74423        return SQLITE_CORRUPT_PAGE(pPage);
74424      }
74425      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
74426    }
74427  }
74428  return SQLITE_OK;
74429}
74430
74431
74432/*
74433** Move the open database page pDbPage to location iFreePage in the
74434** database. The pDbPage reference remains valid.
74435**
74436** The isCommit flag indicates that there is no need to remember that
74437** the journal needs to be sync()ed before database page pDbPage->pgno
74438** can be written to. The caller has already promised not to write to that
74439** page.
74440*/
74441static int relocatePage(
74442  BtShared *pBt,           /* Btree */
74443  MemPage *pDbPage,        /* Open page to move */
74444  u8 eType,                /* Pointer map 'type' entry for pDbPage */
74445  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
74446  Pgno iFreePage,          /* The location to move pDbPage to */
74447  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
74448){
74449  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
74450  Pgno iDbPage = pDbPage->pgno;
74451  Pager *pPager = pBt->pPager;
74452  int rc;
74453
74454  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
74455      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
74456  assert( sqlite3_mutex_held(pBt->mutex) );
74457  assert( pDbPage->pBt==pBt );
74458  if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
74459
74460  /* Move page iDbPage from its current location to page number iFreePage */
74461  TRACE(("AUTOVACUUM: Moving %u to free page %u (ptr page %u type %u)\n",
74462      iDbPage, iFreePage, iPtrPage, eType));
74463  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
74464  if( rc!=SQLITE_OK ){
74465    return rc;
74466  }
74467  pDbPage->pgno = iFreePage;
74468
74469  /* If pDbPage was a btree-page, then it may have child pages and/or cells
74470  ** that point to overflow pages. The pointer map entries for all these
74471  ** pages need to be changed.
74472  **
74473  ** If pDbPage is an overflow page, then the first 4 bytes may store a
74474  ** pointer to a subsequent overflow page. If this is the case, then
74475  ** the pointer map needs to be updated for the subsequent overflow page.
74476  */
74477  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
74478    rc = setChildPtrmaps(pDbPage);
74479    if( rc!=SQLITE_OK ){
74480      return rc;
74481    }
74482  }else{
74483    Pgno nextOvfl = get4byte(pDbPage->aData);
74484    if( nextOvfl!=0 ){
74485      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
74486      if( rc!=SQLITE_OK ){
74487        return rc;
74488      }
74489    }
74490  }
74491
74492  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
74493  ** that it points at iFreePage. Also fix the pointer map entry for
74494  ** iPtrPage.
74495  */
74496  if( eType!=PTRMAP_ROOTPAGE ){
74497    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
74498    if( rc!=SQLITE_OK ){
74499      return rc;
74500    }
74501    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
74502    if( rc!=SQLITE_OK ){
74503      releasePage(pPtrPage);
74504      return rc;
74505    }
74506    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
74507    releasePage(pPtrPage);
74508    if( rc==SQLITE_OK ){
74509      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
74510    }
74511  }
74512  return rc;
74513}
74514
74515/* Forward declaration required by incrVacuumStep(). */
74516static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
74517
74518/*
74519** Perform a single step of an incremental-vacuum. If successful, return
74520** SQLITE_OK. If there is no work to do (and therefore no point in
74521** calling this function again), return SQLITE_DONE. Or, if an error
74522** occurs, return some other error code.
74523**
74524** More specifically, this function attempts to re-organize the database so
74525** that the last page of the file currently in use is no longer in use.
74526**
74527** Parameter nFin is the number of pages that this database would contain
74528** were this function called until it returns SQLITE_DONE.
74529**
74530** If the bCommit parameter is non-zero, this function assumes that the
74531** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
74532** or an error. bCommit is passed true for an auto-vacuum-on-commit
74533** operation, or false for an incremental vacuum.
74534*/
74535static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
74536  Pgno nFreeList;           /* Number of pages still on the free-list */
74537  int rc;
74538
74539  assert( sqlite3_mutex_held(pBt->mutex) );
74540  assert( iLastPg>nFin );
74541
74542  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
74543    u8 eType;
74544    Pgno iPtrPage;
74545
74546    nFreeList = get4byte(&pBt->pPage1->aData[36]);
74547    if( nFreeList==0 ){
74548      return SQLITE_DONE;
74549    }
74550
74551    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
74552    if( rc!=SQLITE_OK ){
74553      return rc;
74554    }
74555    if( eType==PTRMAP_ROOTPAGE ){
74556      return SQLITE_CORRUPT_BKPT;
74557    }
74558
74559    if( eType==PTRMAP_FREEPAGE ){
74560      if( bCommit==0 ){
74561        /* Remove the page from the files free-list. This is not required
74562        ** if bCommit is non-zero. In that case, the free-list will be
74563        ** truncated to zero after this function returns, so it doesn't
74564        ** matter if it still contains some garbage entries.
74565        */
74566        Pgno iFreePg;
74567        MemPage *pFreePg;
74568        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
74569        if( rc!=SQLITE_OK ){
74570          return rc;
74571        }
74572        assert( iFreePg==iLastPg );
74573        releasePage(pFreePg);
74574      }
74575    } else {
74576      Pgno iFreePg;             /* Index of free page to move pLastPg to */
74577      MemPage *pLastPg;
74578      u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
74579      Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
74580
74581      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
74582      if( rc!=SQLITE_OK ){
74583        return rc;
74584      }
74585
74586      /* If bCommit is zero, this loop runs exactly once and page pLastPg
74587      ** is swapped with the first free page pulled off the free list.
74588      **
74589      ** On the other hand, if bCommit is greater than zero, then keep
74590      ** looping until a free-page located within the first nFin pages
74591      ** of the file is found.
74592      */
74593      if( bCommit==0 ){
74594        eMode = BTALLOC_LE;
74595        iNear = nFin;
74596      }
74597      do {
74598        MemPage *pFreePg;
74599        Pgno dbSize = btreePagecount(pBt);
74600        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
74601        if( rc!=SQLITE_OK ){
74602          releasePage(pLastPg);
74603          return rc;
74604        }
74605        releasePage(pFreePg);
74606        if( iFreePg>dbSize ){
74607          releasePage(pLastPg);
74608          return SQLITE_CORRUPT_BKPT;
74609        }
74610      }while( bCommit && iFreePg>nFin );
74611      assert( iFreePg<iLastPg );
74612
74613      rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
74614      releasePage(pLastPg);
74615      if( rc!=SQLITE_OK ){
74616        return rc;
74617      }
74618    }
74619  }
74620
74621  if( bCommit==0 ){
74622    do {
74623      iLastPg--;
74624    }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
74625    pBt->bDoTruncate = 1;
74626    pBt->nPage = iLastPg;
74627  }
74628  return SQLITE_OK;
74629}
74630
74631/*
74632** The database opened by the first argument is an auto-vacuum database
74633** nOrig pages in size containing nFree free pages. Return the expected
74634** size of the database in pages following an auto-vacuum operation.
74635*/
74636static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
74637  int nEntry;                     /* Number of entries on one ptrmap page */
74638  Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
74639  Pgno nFin;                      /* Return value */
74640
74641  nEntry = pBt->usableSize/5;
74642  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
74643  nFin = nOrig - nFree - nPtrmap;
74644  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
74645    nFin--;
74646  }
74647  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
74648    nFin--;
74649  }
74650
74651  return nFin;
74652}
74653
74654/*
74655** A write-transaction must be opened before calling this function.
74656** It performs a single unit of work towards an incremental vacuum.
74657**
74658** If the incremental vacuum is finished after this function has run,
74659** SQLITE_DONE is returned. If it is not finished, but no error occurred,
74660** SQLITE_OK is returned. Otherwise an SQLite error code.
74661*/
74662SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
74663  int rc;
74664  BtShared *pBt = p->pBt;
74665
74666  sqlite3BtreeEnter(p);
74667  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
74668  if( !pBt->autoVacuum ){
74669    rc = SQLITE_DONE;
74670  }else{
74671    Pgno nOrig = btreePagecount(pBt);
74672    Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
74673    Pgno nFin = finalDbSize(pBt, nOrig, nFree);
74674
74675    if( nOrig<nFin || nFree>=nOrig ){
74676      rc = SQLITE_CORRUPT_BKPT;
74677    }else if( nFree>0 ){
74678      rc = saveAllCursors(pBt, 0, 0);
74679      if( rc==SQLITE_OK ){
74680        invalidateAllOverflowCache(pBt);
74681        rc = incrVacuumStep(pBt, nFin, nOrig, 0);
74682      }
74683      if( rc==SQLITE_OK ){
74684        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
74685        put4byte(&pBt->pPage1->aData[28], pBt->nPage);
74686      }
74687    }else{
74688      rc = SQLITE_DONE;
74689    }
74690  }
74691  sqlite3BtreeLeave(p);
74692  return rc;
74693}
74694
74695/*
74696** This routine is called prior to sqlite3PagerCommit when a transaction
74697** is committed for an auto-vacuum database.
74698*/
74699static int autoVacuumCommit(Btree *p){
74700  int rc = SQLITE_OK;
74701  Pager *pPager;
74702  BtShared *pBt;
74703  sqlite3 *db;
74704  VVA_ONLY( int nRef );
74705
74706  assert( p!=0 );
74707  pBt = p->pBt;
74708  pPager = pBt->pPager;
74709  VVA_ONLY( nRef = sqlite3PagerRefcount(pPager); )
74710
74711  assert( sqlite3_mutex_held(pBt->mutex) );
74712  invalidateAllOverflowCache(pBt);
74713  assert(pBt->autoVacuum);
74714  if( !pBt->incrVacuum ){
74715    Pgno nFin;         /* Number of pages in database after autovacuuming */
74716    Pgno nFree;        /* Number of pages on the freelist initially */
74717    Pgno nVac;         /* Number of pages to vacuum */
74718    Pgno iFree;        /* The next page to be freed */
74719    Pgno nOrig;        /* Database size before freeing */
74720
74721    nOrig = btreePagecount(pBt);
74722    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
74723      /* It is not possible to create a database for which the final page
74724      ** is either a pointer-map page or the pending-byte page. If one
74725      ** is encountered, this indicates corruption.
74726      */
74727      return SQLITE_CORRUPT_BKPT;
74728    }
74729
74730    nFree = get4byte(&pBt->pPage1->aData[36]);
74731    db = p->db;
74732    if( db->xAutovacPages ){
74733      int iDb;
74734      for(iDb=0; ALWAYS(iDb<db->nDb); iDb++){
74735        if( db->aDb[iDb].pBt==p ) break;
74736      }
74737      nVac = db->xAutovacPages(
74738        db->pAutovacPagesArg,
74739        db->aDb[iDb].zDbSName,
74740        nOrig,
74741        nFree,
74742        pBt->pageSize
74743      );
74744      if( nVac>nFree ){
74745        nVac = nFree;
74746      }
74747      if( nVac==0 ){
74748        return SQLITE_OK;
74749      }
74750    }else{
74751      nVac = nFree;
74752    }
74753    nFin = finalDbSize(pBt, nOrig, nVac);
74754    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
74755    if( nFin<nOrig ){
74756      rc = saveAllCursors(pBt, 0, 0);
74757    }
74758    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
74759      rc = incrVacuumStep(pBt, nFin, iFree, nVac==nFree);
74760    }
74761    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
74762      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
74763      if( nVac==nFree ){
74764        put4byte(&pBt->pPage1->aData[32], 0);
74765        put4byte(&pBt->pPage1->aData[36], 0);
74766      }
74767      put4byte(&pBt->pPage1->aData[28], nFin);
74768      pBt->bDoTruncate = 1;
74769      pBt->nPage = nFin;
74770    }
74771    if( rc!=SQLITE_OK ){
74772      sqlite3PagerRollback(pPager);
74773    }
74774  }
74775
74776  assert( nRef>=sqlite3PagerRefcount(pPager) );
74777  return rc;
74778}
74779
74780#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
74781# define setChildPtrmaps(x) SQLITE_OK
74782#endif
74783
74784/*
74785** This routine does the first phase of a two-phase commit.  This routine
74786** causes a rollback journal to be created (if it does not already exist)
74787** and populated with enough information so that if a power loss occurs
74788** the database can be restored to its original state by playing back
74789** the journal.  Then the contents of the journal are flushed out to
74790** the disk.  After the journal is safely on oxide, the changes to the
74791** database are written into the database file and flushed to oxide.
74792** At the end of this call, the rollback journal still exists on the
74793** disk and we are still holding all locks, so the transaction has not
74794** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
74795** commit process.
74796**
74797** This call is a no-op if no write-transaction is currently active on pBt.
74798**
74799** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
74800** the name of a super-journal file that should be written into the
74801** individual journal file, or is NULL, indicating no super-journal file
74802** (single database transaction).
74803**
74804** When this is called, the super-journal should already have been
74805** created, populated with this journal pointer and synced to disk.
74806**
74807** Once this is routine has returned, the only thing required to commit
74808** the write-transaction for this database file is to delete the journal.
74809*/
74810SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
74811  int rc = SQLITE_OK;
74812  if( p->inTrans==TRANS_WRITE ){
74813    BtShared *pBt = p->pBt;
74814    sqlite3BtreeEnter(p);
74815#ifndef SQLITE_OMIT_AUTOVACUUM
74816    if( pBt->autoVacuum ){
74817      rc = autoVacuumCommit(p);
74818      if( rc!=SQLITE_OK ){
74819        sqlite3BtreeLeave(p);
74820        return rc;
74821      }
74822    }
74823    if( pBt->bDoTruncate ){
74824      sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
74825    }
74826#endif
74827    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
74828    sqlite3BtreeLeave(p);
74829  }
74830  return rc;
74831}
74832
74833/*
74834** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
74835** at the conclusion of a transaction.
74836*/
74837static void btreeEndTransaction(Btree *p){
74838  BtShared *pBt = p->pBt;
74839  sqlite3 *db = p->db;
74840  assert( sqlite3BtreeHoldsMutex(p) );
74841
74842#ifndef SQLITE_OMIT_AUTOVACUUM
74843  pBt->bDoTruncate = 0;
74844#endif
74845  if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
74846    /* If there are other active statements that belong to this database
74847    ** handle, downgrade to a read-only transaction. The other statements
74848    ** may still be reading from the database.  */
74849    downgradeAllSharedCacheTableLocks(p);
74850    p->inTrans = TRANS_READ;
74851  }else{
74852    /* If the handle had any kind of transaction open, decrement the
74853    ** transaction count of the shared btree. If the transaction count
74854    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
74855    ** call below will unlock the pager.  */
74856    if( p->inTrans!=TRANS_NONE ){
74857      clearAllSharedCacheTableLocks(p);
74858      pBt->nTransaction--;
74859      if( 0==pBt->nTransaction ){
74860        pBt->inTransaction = TRANS_NONE;
74861      }
74862    }
74863
74864    /* Set the current transaction state to TRANS_NONE and unlock the
74865    ** pager if this call closed the only read or write transaction.  */
74866    p->inTrans = TRANS_NONE;
74867    unlockBtreeIfUnused(pBt);
74868  }
74869
74870  btreeIntegrity(p);
74871}
74872
74873/*
74874** Commit the transaction currently in progress.
74875**
74876** This routine implements the second phase of a 2-phase commit.  The
74877** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
74878** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
74879** routine did all the work of writing information out to disk and flushing the
74880** contents so that they are written onto the disk platter.  All this
74881** routine has to do is delete or truncate or zero the header in the
74882** the rollback journal (which causes the transaction to commit) and
74883** drop locks.
74884**
74885** Normally, if an error occurs while the pager layer is attempting to
74886** finalize the underlying journal file, this function returns an error and
74887** the upper layer will attempt a rollback. However, if the second argument
74888** is non-zero then this b-tree transaction is part of a multi-file
74889** transaction. In this case, the transaction has already been committed
74890** (by deleting a super-journal file) and the caller will ignore this
74891** functions return code. So, even if an error occurs in the pager layer,
74892** reset the b-tree objects internal state to indicate that the write
74893** transaction has been closed. This is quite safe, as the pager will have
74894** transitioned to the error state.
74895**
74896** This will release the write lock on the database file.  If there
74897** are no active cursors, it also releases the read lock.
74898*/
74899SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
74900
74901  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
74902  sqlite3BtreeEnter(p);
74903  btreeIntegrity(p);
74904
74905  /* If the handle has a write-transaction open, commit the shared-btrees
74906  ** transaction and set the shared state to TRANS_READ.
74907  */
74908  if( p->inTrans==TRANS_WRITE ){
74909    int rc;
74910    BtShared *pBt = p->pBt;
74911    assert( pBt->inTransaction==TRANS_WRITE );
74912    assert( pBt->nTransaction>0 );
74913    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
74914    if( rc!=SQLITE_OK && bCleanup==0 ){
74915      sqlite3BtreeLeave(p);
74916      return rc;
74917    }
74918    p->iBDataVersion--;  /* Compensate for pPager->iDataVersion++; */
74919    pBt->inTransaction = TRANS_READ;
74920    btreeClearHasContent(pBt);
74921  }
74922
74923  btreeEndTransaction(p);
74924  sqlite3BtreeLeave(p);
74925  return SQLITE_OK;
74926}
74927
74928/*
74929** Do both phases of a commit.
74930*/
74931SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
74932  int rc;
74933  sqlite3BtreeEnter(p);
74934  rc = sqlite3BtreeCommitPhaseOne(p, 0);
74935  if( rc==SQLITE_OK ){
74936    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
74937  }
74938  sqlite3BtreeLeave(p);
74939  return rc;
74940}
74941
74942/*
74943** This routine sets the state to CURSOR_FAULT and the error
74944** code to errCode for every cursor on any BtShared that pBtree
74945** references.  Or if the writeOnly flag is set to 1, then only
74946** trip write cursors and leave read cursors unchanged.
74947**
74948** Every cursor is a candidate to be tripped, including cursors
74949** that belong to other database connections that happen to be
74950** sharing the cache with pBtree.
74951**
74952** This routine gets called when a rollback occurs. If the writeOnly
74953** flag is true, then only write-cursors need be tripped - read-only
74954** cursors save their current positions so that they may continue
74955** following the rollback. Or, if writeOnly is false, all cursors are
74956** tripped. In general, writeOnly is false if the transaction being
74957** rolled back modified the database schema. In this case b-tree root
74958** pages may be moved or deleted from the database altogether, making
74959** it unsafe for read cursors to continue.
74960**
74961** If the writeOnly flag is true and an error is encountered while
74962** saving the current position of a read-only cursor, all cursors,
74963** including all read-cursors are tripped.
74964**
74965** SQLITE_OK is returned if successful, or if an error occurs while
74966** saving a cursor position, an SQLite error code.
74967*/
74968SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
74969  BtCursor *p;
74970  int rc = SQLITE_OK;
74971
74972  assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
74973  if( pBtree ){
74974    sqlite3BtreeEnter(pBtree);
74975    for(p=pBtree->pBt->pCursor; p; p=p->pNext){
74976      if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
74977        if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
74978          rc = saveCursorPosition(p);
74979          if( rc!=SQLITE_OK ){
74980            (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
74981            break;
74982          }
74983        }
74984      }else{
74985        sqlite3BtreeClearCursor(p);
74986        p->eState = CURSOR_FAULT;
74987        p->skipNext = errCode;
74988      }
74989      btreeReleaseAllCursorPages(p);
74990    }
74991    sqlite3BtreeLeave(pBtree);
74992  }
74993  return rc;
74994}
74995
74996/*
74997** Set the pBt->nPage field correctly, according to the current
74998** state of the database.  Assume pBt->pPage1 is valid.
74999*/
75000static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
75001  int nPage = get4byte(&pPage1->aData[28]);
75002  testcase( nPage==0 );
75003  if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
75004  testcase( pBt->nPage!=(u32)nPage );
75005  pBt->nPage = nPage;
75006}
75007
75008/*
75009** Rollback the transaction in progress.
75010**
75011** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
75012** Only write cursors are tripped if writeOnly is true but all cursors are
75013** tripped if writeOnly is false.  Any attempt to use
75014** a tripped cursor will result in an error.
75015**
75016** This will release the write lock on the database file.  If there
75017** are no active cursors, it also releases the read lock.
75018*/
75019SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
75020  int rc;
75021  BtShared *pBt = p->pBt;
75022  MemPage *pPage1;
75023
75024  assert( writeOnly==1 || writeOnly==0 );
75025  assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
75026  sqlite3BtreeEnter(p);
75027  if( tripCode==SQLITE_OK ){
75028    rc = tripCode = saveAllCursors(pBt, 0, 0);
75029    if( rc ) writeOnly = 0;
75030  }else{
75031    rc = SQLITE_OK;
75032  }
75033  if( tripCode ){
75034    int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
75035    assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
75036    if( rc2!=SQLITE_OK ) rc = rc2;
75037  }
75038  btreeIntegrity(p);
75039
75040  if( p->inTrans==TRANS_WRITE ){
75041    int rc2;
75042
75043    assert( TRANS_WRITE==pBt->inTransaction );
75044    rc2 = sqlite3PagerRollback(pBt->pPager);
75045    if( rc2!=SQLITE_OK ){
75046      rc = rc2;
75047    }
75048
75049    /* The rollback may have destroyed the pPage1->aData value.  So
75050    ** call btreeGetPage() on page 1 again to make
75051    ** sure pPage1->aData is set correctly. */
75052    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
75053      btreeSetNPage(pBt, pPage1);
75054      releasePageOne(pPage1);
75055    }
75056    assert( countValidCursors(pBt, 1)==0 );
75057    pBt->inTransaction = TRANS_READ;
75058    btreeClearHasContent(pBt);
75059  }
75060
75061  btreeEndTransaction(p);
75062  sqlite3BtreeLeave(p);
75063  return rc;
75064}
75065
75066/*
75067** Start a statement subtransaction. The subtransaction can be rolled
75068** back independently of the main transaction. You must start a transaction
75069** before starting a subtransaction. The subtransaction is ended automatically
75070** if the main transaction commits or rolls back.
75071**
75072** Statement subtransactions are used around individual SQL statements
75073** that are contained within a BEGIN...COMMIT block.  If a constraint
75074** error occurs within the statement, the effect of that one statement
75075** can be rolled back without having to rollback the entire transaction.
75076**
75077** A statement sub-transaction is implemented as an anonymous savepoint. The
75078** value passed as the second parameter is the total number of savepoints,
75079** including the new anonymous savepoint, open on the B-Tree. i.e. if there
75080** are no active savepoints and no other statement-transactions open,
75081** iStatement is 1. This anonymous savepoint can be released or rolled back
75082** using the sqlite3BtreeSavepoint() function.
75083*/
75084SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
75085  int rc;
75086  BtShared *pBt = p->pBt;
75087  sqlite3BtreeEnter(p);
75088  assert( p->inTrans==TRANS_WRITE );
75089  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
75090  assert( iStatement>0 );
75091  assert( iStatement>p->db->nSavepoint );
75092  assert( pBt->inTransaction==TRANS_WRITE );
75093  /* At the pager level, a statement transaction is a savepoint with
75094  ** an index greater than all savepoints created explicitly using
75095  ** SQL statements. It is illegal to open, release or rollback any
75096  ** such savepoints while the statement transaction savepoint is active.
75097  */
75098  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
75099  sqlite3BtreeLeave(p);
75100  return rc;
75101}
75102
75103/*
75104** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
75105** or SAVEPOINT_RELEASE. This function either releases or rolls back the
75106** savepoint identified by parameter iSavepoint, depending on the value
75107** of op.
75108**
75109** Normally, iSavepoint is greater than or equal to zero. However, if op is
75110** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
75111** contents of the entire transaction are rolled back. This is different
75112** from a normal transaction rollback, as no locks are released and the
75113** transaction remains open.
75114*/
75115SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
75116  int rc = SQLITE_OK;
75117  if( p && p->inTrans==TRANS_WRITE ){
75118    BtShared *pBt = p->pBt;
75119    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
75120    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
75121    sqlite3BtreeEnter(p);
75122    if( op==SAVEPOINT_ROLLBACK ){
75123      rc = saveAllCursors(pBt, 0, 0);
75124    }
75125    if( rc==SQLITE_OK ){
75126      rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
75127    }
75128    if( rc==SQLITE_OK ){
75129      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
75130        pBt->nPage = 0;
75131      }
75132      rc = newDatabase(pBt);
75133      btreeSetNPage(pBt, pBt->pPage1);
75134
75135      /* pBt->nPage might be zero if the database was corrupt when
75136      ** the transaction was started. Otherwise, it must be at least 1.  */
75137      assert( CORRUPT_DB || pBt->nPage>0 );
75138    }
75139    sqlite3BtreeLeave(p);
75140  }
75141  return rc;
75142}
75143
75144/*
75145** Create a new cursor for the BTree whose root is on the page
75146** iTable. If a read-only cursor is requested, it is assumed that
75147** the caller already has at least a read-only transaction open
75148** on the database already. If a write-cursor is requested, then
75149** the caller is assumed to have an open write transaction.
75150**
75151** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
75152** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
75153** can be used for reading or for writing if other conditions for writing
75154** are also met.  These are the conditions that must be met in order
75155** for writing to be allowed:
75156**
75157** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
75158**
75159** 2:  Other database connections that share the same pager cache
75160**     but which are not in the READ_UNCOMMITTED state may not have
75161**     cursors open with wrFlag==0 on the same table.  Otherwise
75162**     the changes made by this write cursor would be visible to
75163**     the read cursors in the other database connection.
75164**
75165** 3:  The database must be writable (not on read-only media)
75166**
75167** 4:  There must be an active transaction.
75168**
75169** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
75170** is set.  If FORDELETE is set, that is a hint to the implementation that
75171** this cursor will only be used to seek to and delete entries of an index
75172** as part of a larger DELETE statement.  The FORDELETE hint is not used by
75173** this implementation.  But in a hypothetical alternative storage engine
75174** in which index entries are automatically deleted when corresponding table
75175** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
75176** operations on this cursor can be no-ops and all READ operations can
75177** return a null row (2-bytes: 0x01 0x00).
75178**
75179** No checking is done to make sure that page iTable really is the
75180** root page of a b-tree.  If it is not, then the cursor acquired
75181** will not work correctly.
75182**
75183** It is assumed that the sqlite3BtreeCursorZero() has been called
75184** on pCur to initialize the memory space prior to invoking this routine.
75185*/
75186static int btreeCursor(
75187  Btree *p,                              /* The btree */
75188  Pgno iTable,                           /* Root page of table to open */
75189  int wrFlag,                            /* 1 to write. 0 read-only */
75190  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
75191  BtCursor *pCur                         /* Space for new cursor */
75192){
75193  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
75194  BtCursor *pX;                          /* Looping over other all cursors */
75195
75196  assert( sqlite3BtreeHoldsMutex(p) );
75197  assert( wrFlag==0
75198       || wrFlag==BTREE_WRCSR
75199       || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
75200  );
75201
75202  /* The following assert statements verify that if this is a sharable
75203  ** b-tree database, the connection is holding the required table locks,
75204  ** and that no other connection has any open cursor that conflicts with
75205  ** this lock.  The iTable<1 term disables the check for corrupt schemas. */
75206  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
75207          || iTable<1 );
75208  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
75209
75210  /* Assert that the caller has opened the required transaction. */
75211  assert( p->inTrans>TRANS_NONE );
75212  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
75213  assert( pBt->pPage1 && pBt->pPage1->aData );
75214  assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
75215
75216  if( iTable<=1 ){
75217    if( iTable<1 ){
75218      return SQLITE_CORRUPT_BKPT;
75219    }else if( btreePagecount(pBt)==0 ){
75220      assert( wrFlag==0 );
75221      iTable = 0;
75222    }
75223  }
75224
75225  /* Now that no other errors can occur, finish filling in the BtCursor
75226  ** variables and link the cursor into the BtShared list.  */
75227  pCur->pgnoRoot = iTable;
75228  pCur->iPage = -1;
75229  pCur->pKeyInfo = pKeyInfo;
75230  pCur->pBtree = p;
75231  pCur->pBt = pBt;
75232  pCur->curFlags = 0;
75233  /* If there are two or more cursors on the same btree, then all such
75234  ** cursors *must* have the BTCF_Multiple flag set. */
75235  for(pX=pBt->pCursor; pX; pX=pX->pNext){
75236    if( pX->pgnoRoot==iTable ){
75237      pX->curFlags |= BTCF_Multiple;
75238      pCur->curFlags = BTCF_Multiple;
75239    }
75240  }
75241  pCur->eState = CURSOR_INVALID;
75242  pCur->pNext = pBt->pCursor;
75243  pBt->pCursor = pCur;
75244  if( wrFlag ){
75245    pCur->curFlags |= BTCF_WriteFlag;
75246    pCur->curPagerFlags = 0;
75247    if( pBt->pTmpSpace==0 ) return allocateTempSpace(pBt);
75248  }else{
75249    pCur->curPagerFlags = PAGER_GET_READONLY;
75250  }
75251  return SQLITE_OK;
75252}
75253static int btreeCursorWithLock(
75254  Btree *p,                              /* The btree */
75255  Pgno iTable,                           /* Root page of table to open */
75256  int wrFlag,                            /* 1 to write. 0 read-only */
75257  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
75258  BtCursor *pCur                         /* Space for new cursor */
75259){
75260  int rc;
75261  sqlite3BtreeEnter(p);
75262  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
75263  sqlite3BtreeLeave(p);
75264  return rc;
75265}
75266SQLITE_PRIVATE int sqlite3BtreeCursor(
75267  Btree *p,                                   /* The btree */
75268  Pgno iTable,                                /* Root page of table to open */
75269  int wrFlag,                                 /* 1 to write. 0 read-only */
75270  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
75271  BtCursor *pCur                              /* Write new cursor here */
75272){
75273  if( p->sharable ){
75274    return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
75275  }else{
75276    return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
75277  }
75278}
75279
75280/*
75281** Return the size of a BtCursor object in bytes.
75282**
75283** This interfaces is needed so that users of cursors can preallocate
75284** sufficient storage to hold a cursor.  The BtCursor object is opaque
75285** to users so they cannot do the sizeof() themselves - they must call
75286** this routine.
75287*/
75288SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
75289  return ROUND8(sizeof(BtCursor));
75290}
75291
75292/*
75293** Initialize memory that will be converted into a BtCursor object.
75294**
75295** The simple approach here would be to memset() the entire object
75296** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
75297** do not need to be zeroed and they are large, so we can save a lot
75298** of run-time by skipping the initialization of those elements.
75299*/
75300SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
75301  memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
75302}
75303
75304/*
75305** Close a cursor.  The read lock on the database file is released
75306** when the last cursor is closed.
75307*/
75308SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
75309  Btree *pBtree = pCur->pBtree;
75310  if( pBtree ){
75311    BtShared *pBt = pCur->pBt;
75312    sqlite3BtreeEnter(pBtree);
75313    assert( pBt->pCursor!=0 );
75314    if( pBt->pCursor==pCur ){
75315      pBt->pCursor = pCur->pNext;
75316    }else{
75317      BtCursor *pPrev = pBt->pCursor;
75318      do{
75319        if( pPrev->pNext==pCur ){
75320          pPrev->pNext = pCur->pNext;
75321          break;
75322        }
75323        pPrev = pPrev->pNext;
75324      }while( ALWAYS(pPrev) );
75325    }
75326    btreeReleaseAllCursorPages(pCur);
75327    unlockBtreeIfUnused(pBt);
75328    sqlite3_free(pCur->aOverflow);
75329    sqlite3_free(pCur->pKey);
75330    if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
75331      /* Since the BtShared is not sharable, there is no need to
75332      ** worry about the missing sqlite3BtreeLeave() call here.  */
75333      assert( pBtree->sharable==0 );
75334      sqlite3BtreeClose(pBtree);
75335    }else{
75336      sqlite3BtreeLeave(pBtree);
75337    }
75338    pCur->pBtree = 0;
75339  }
75340  return SQLITE_OK;
75341}
75342
75343/*
75344** Make sure the BtCursor* given in the argument has a valid
75345** BtCursor.info structure.  If it is not already valid, call
75346** btreeParseCell() to fill it in.
75347**
75348** BtCursor.info is a cache of the information in the current cell.
75349** Using this cache reduces the number of calls to btreeParseCell().
75350*/
75351#ifndef NDEBUG
75352  static int cellInfoEqual(CellInfo *a, CellInfo *b){
75353    if( a->nKey!=b->nKey ) return 0;
75354    if( a->pPayload!=b->pPayload ) return 0;
75355    if( a->nPayload!=b->nPayload ) return 0;
75356    if( a->nLocal!=b->nLocal ) return 0;
75357    if( a->nSize!=b->nSize ) return 0;
75358    return 1;
75359  }
75360  static void assertCellInfo(BtCursor *pCur){
75361    CellInfo info;
75362    memset(&info, 0, sizeof(info));
75363    btreeParseCell(pCur->pPage, pCur->ix, &info);
75364    assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
75365  }
75366#else
75367  #define assertCellInfo(x)
75368#endif
75369static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
75370  if( pCur->info.nSize==0 ){
75371    pCur->curFlags |= BTCF_ValidNKey;
75372    btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
75373  }else{
75374    assertCellInfo(pCur);
75375  }
75376}
75377
75378#ifndef NDEBUG  /* The next routine used only within assert() statements */
75379/*
75380** Return true if the given BtCursor is valid.  A valid cursor is one
75381** that is currently pointing to a row in a (non-empty) table.
75382** This is a verification routine is used only within assert() statements.
75383*/
75384SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
75385  return pCur && pCur->eState==CURSOR_VALID;
75386}
75387#endif /* NDEBUG */
75388SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
75389  assert( pCur!=0 );
75390  return pCur->eState==CURSOR_VALID;
75391}
75392
75393/*
75394** Return the value of the integer key or "rowid" for a table btree.
75395** This routine is only valid for a cursor that is pointing into a
75396** ordinary table btree.  If the cursor points to an index btree or
75397** is invalid, the result of this routine is undefined.
75398*/
75399SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
75400  assert( cursorHoldsMutex(pCur) );
75401  assert( pCur->eState==CURSOR_VALID );
75402  assert( pCur->curIntKey );
75403  getCellInfo(pCur);
75404  return pCur->info.nKey;
75405}
75406
75407/*
75408** Pin or unpin a cursor.
75409*/
75410SQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor *pCur){
75411  assert( (pCur->curFlags & BTCF_Pinned)==0 );
75412  pCur->curFlags |= BTCF_Pinned;
75413}
75414SQLITE_PRIVATE void sqlite3BtreeCursorUnpin(BtCursor *pCur){
75415  assert( (pCur->curFlags & BTCF_Pinned)!=0 );
75416  pCur->curFlags &= ~BTCF_Pinned;
75417}
75418
75419/*
75420** Return the offset into the database file for the start of the
75421** payload to which the cursor is pointing.
75422*/
75423SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor *pCur){
75424  assert( cursorHoldsMutex(pCur) );
75425  assert( pCur->eState==CURSOR_VALID );
75426  getCellInfo(pCur);
75427  return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
75428         (i64)(pCur->info.pPayload - pCur->pPage->aData);
75429}
75430
75431/*
75432** Return the number of bytes of payload for the entry that pCur is
75433** currently pointing to.  For table btrees, this will be the amount
75434** of data.  For index btrees, this will be the size of the key.
75435**
75436** The caller must guarantee that the cursor is pointing to a non-NULL
75437** valid entry.  In other words, the calling procedure must guarantee
75438** that the cursor has Cursor.eState==CURSOR_VALID.
75439*/
75440SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
75441  assert( cursorHoldsMutex(pCur) );
75442  assert( pCur->eState==CURSOR_VALID );
75443  getCellInfo(pCur);
75444  return pCur->info.nPayload;
75445}
75446
75447/*
75448** Return an upper bound on the size of any record for the table
75449** that the cursor is pointing into.
75450**
75451** This is an optimization.  Everything will still work if this
75452** routine always returns 2147483647 (which is the largest record
75453** that SQLite can handle) or more.  But returning a smaller value might
75454** prevent large memory allocations when trying to interpret a
75455** corrupt database.
75456**
75457** The current implementation merely returns the size of the underlying
75458** database file.
75459*/
75460SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
75461  assert( cursorHoldsMutex(pCur) );
75462  assert( pCur->eState==CURSOR_VALID );
75463  return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
75464}
75465
75466/*
75467** Given the page number of an overflow page in the database (parameter
75468** ovfl), this function finds the page number of the next page in the
75469** linked list of overflow pages. If possible, it uses the auto-vacuum
75470** pointer-map data instead of reading the content of page ovfl to do so.
75471**
75472** If an error occurs an SQLite error code is returned. Otherwise:
75473**
75474** The page number of the next overflow page in the linked list is
75475** written to *pPgnoNext. If page ovfl is the last page in its linked
75476** list, *pPgnoNext is set to zero.
75477**
75478** If ppPage is not NULL, and a reference to the MemPage object corresponding
75479** to page number pOvfl was obtained, then *ppPage is set to point to that
75480** reference. It is the responsibility of the caller to call releasePage()
75481** on *ppPage to free the reference. In no reference was obtained (because
75482** the pointer-map was used to obtain the value for *pPgnoNext), then
75483** *ppPage is set to zero.
75484*/
75485static int getOverflowPage(
75486  BtShared *pBt,               /* The database file */
75487  Pgno ovfl,                   /* Current overflow page number */
75488  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
75489  Pgno *pPgnoNext              /* OUT: Next overflow page number */
75490){
75491  Pgno next = 0;
75492  MemPage *pPage = 0;
75493  int rc = SQLITE_OK;
75494
75495  assert( sqlite3_mutex_held(pBt->mutex) );
75496  assert(pPgnoNext);
75497
75498#ifndef SQLITE_OMIT_AUTOVACUUM
75499  /* Try to find the next page in the overflow list using the
75500  ** autovacuum pointer-map pages. Guess that the next page in
75501  ** the overflow list is page number (ovfl+1). If that guess turns
75502  ** out to be wrong, fall back to loading the data of page
75503  ** number ovfl to determine the next page number.
75504  */
75505  if( pBt->autoVacuum ){
75506    Pgno pgno;
75507    Pgno iGuess = ovfl+1;
75508    u8 eType;
75509
75510    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
75511      iGuess++;
75512    }
75513
75514    if( iGuess<=btreePagecount(pBt) ){
75515      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
75516      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
75517        next = iGuess;
75518        rc = SQLITE_DONE;
75519      }
75520    }
75521  }
75522#endif
75523
75524  assert( next==0 || rc==SQLITE_DONE );
75525  if( rc==SQLITE_OK ){
75526    rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
75527    assert( rc==SQLITE_OK || pPage==0 );
75528    if( rc==SQLITE_OK ){
75529      next = get4byte(pPage->aData);
75530    }
75531  }
75532
75533  *pPgnoNext = next;
75534  if( ppPage ){
75535    *ppPage = pPage;
75536  }else{
75537    releasePage(pPage);
75538  }
75539  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
75540}
75541
75542/*
75543** Copy data from a buffer to a page, or from a page to a buffer.
75544**
75545** pPayload is a pointer to data stored on database page pDbPage.
75546** If argument eOp is false, then nByte bytes of data are copied
75547** from pPayload to the buffer pointed at by pBuf. If eOp is true,
75548** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
75549** of data are copied from the buffer pBuf to pPayload.
75550**
75551** SQLITE_OK is returned on success, otherwise an error code.
75552*/
75553static int copyPayload(
75554  void *pPayload,           /* Pointer to page data */
75555  void *pBuf,               /* Pointer to buffer */
75556  int nByte,                /* Number of bytes to copy */
75557  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
75558  DbPage *pDbPage           /* Page containing pPayload */
75559){
75560  if( eOp ){
75561    /* Copy data from buffer to page (a write operation) */
75562    int rc = sqlite3PagerWrite(pDbPage);
75563    if( rc!=SQLITE_OK ){
75564      return rc;
75565    }
75566    memcpy(pPayload, pBuf, nByte);
75567  }else{
75568    /* Copy data from page to buffer (a read operation) */
75569    memcpy(pBuf, pPayload, nByte);
75570  }
75571  return SQLITE_OK;
75572}
75573
75574/*
75575** This function is used to read or overwrite payload information
75576** for the entry that the pCur cursor is pointing to. The eOp
75577** argument is interpreted as follows:
75578**
75579**   0: The operation is a read. Populate the overflow cache.
75580**   1: The operation is a write. Populate the overflow cache.
75581**
75582** A total of "amt" bytes are read or written beginning at "offset".
75583** Data is read to or from the buffer pBuf.
75584**
75585** The content being read or written might appear on the main page
75586** or be scattered out on multiple overflow pages.
75587**
75588** If the current cursor entry uses one or more overflow pages
75589** this function may allocate space for and lazily populate
75590** the overflow page-list cache array (BtCursor.aOverflow).
75591** Subsequent calls use this cache to make seeking to the supplied offset
75592** more efficient.
75593**
75594** Once an overflow page-list cache has been allocated, it must be
75595** invalidated if some other cursor writes to the same table, or if
75596** the cursor is moved to a different row. Additionally, in auto-vacuum
75597** mode, the following events may invalidate an overflow page-list cache.
75598**
75599**   * An incremental vacuum,
75600**   * A commit in auto_vacuum="full" mode,
75601**   * Creating a table (may require moving an overflow page).
75602*/
75603static int accessPayload(
75604  BtCursor *pCur,      /* Cursor pointing to entry to read from */
75605  u32 offset,          /* Begin reading this far into payload */
75606  u32 amt,             /* Read this many bytes */
75607  unsigned char *pBuf, /* Write the bytes into this buffer */
75608  int eOp              /* zero to read. non-zero to write. */
75609){
75610  unsigned char *aPayload;
75611  int rc = SQLITE_OK;
75612  int iIdx = 0;
75613  MemPage *pPage = pCur->pPage;               /* Btree page of current entry */
75614  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
75615#ifdef SQLITE_DIRECT_OVERFLOW_READ
75616  unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */
75617#endif
75618
75619  assert( pPage );
75620  assert( eOp==0 || eOp==1 );
75621  assert( pCur->eState==CURSOR_VALID );
75622  if( pCur->ix>=pPage->nCell ){
75623    return SQLITE_CORRUPT_PAGE(pPage);
75624  }
75625  assert( cursorHoldsMutex(pCur) );
75626
75627  getCellInfo(pCur);
75628  aPayload = pCur->info.pPayload;
75629  assert( offset+amt <= pCur->info.nPayload );
75630
75631  assert( aPayload > pPage->aData );
75632  if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
75633    /* Trying to read or write past the end of the data is an error.  The
75634    ** conditional above is really:
75635    **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
75636    ** but is recast into its current form to avoid integer overflow problems
75637    */
75638    return SQLITE_CORRUPT_PAGE(pPage);
75639  }
75640
75641  /* Check if data must be read/written to/from the btree page itself. */
75642  if( offset<pCur->info.nLocal ){
75643    int a = amt;
75644    if( a+offset>pCur->info.nLocal ){
75645      a = pCur->info.nLocal - offset;
75646    }
75647    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
75648    offset = 0;
75649    pBuf += a;
75650    amt -= a;
75651  }else{
75652    offset -= pCur->info.nLocal;
75653  }
75654
75655
75656  if( rc==SQLITE_OK && amt>0 ){
75657    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
75658    Pgno nextPage;
75659
75660    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
75661
75662    /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
75663    **
75664    ** The aOverflow[] array is sized at one entry for each overflow page
75665    ** in the overflow chain. The page number of the first overflow page is
75666    ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
75667    ** means "not yet known" (the cache is lazily populated).
75668    */
75669    if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
75670      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
75671      if( pCur->aOverflow==0
75672       || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
75673      ){
75674        Pgno *aNew;
75675        if( sqlite3FaultSim(413) ){
75676          aNew = 0;
75677        }else{
75678          aNew = (Pgno*)sqlite3Realloc(pCur->aOverflow, nOvfl*2*sizeof(Pgno));
75679        }
75680        if( aNew==0 ){
75681          return SQLITE_NOMEM_BKPT;
75682        }else{
75683          pCur->aOverflow = aNew;
75684        }
75685      }
75686      memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
75687      pCur->curFlags |= BTCF_ValidOvfl;
75688    }else{
75689      /* Sanity check the validity of the overflow page cache */
75690      assert( pCur->aOverflow[0]==nextPage
75691           || pCur->aOverflow[0]==0
75692           || CORRUPT_DB );
75693      assert( pCur->aOverflow[0]!=0 || pCur->aOverflow[offset/ovflSize]==0 );
75694
75695      /* If the overflow page-list cache has been allocated and the
75696      ** entry for the first required overflow page is valid, skip
75697      ** directly to it.
75698      */
75699      if( pCur->aOverflow[offset/ovflSize] ){
75700        iIdx = (offset/ovflSize);
75701        nextPage = pCur->aOverflow[iIdx];
75702        offset = (offset%ovflSize);
75703      }
75704    }
75705
75706    assert( rc==SQLITE_OK && amt>0 );
75707    while( nextPage ){
75708      /* If required, populate the overflow page-list cache. */
75709      if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
75710      assert( pCur->aOverflow[iIdx]==0
75711              || pCur->aOverflow[iIdx]==nextPage
75712              || CORRUPT_DB );
75713      pCur->aOverflow[iIdx] = nextPage;
75714
75715      if( offset>=ovflSize ){
75716        /* The only reason to read this page is to obtain the page
75717        ** number for the next page in the overflow chain. The page
75718        ** data is not required. So first try to lookup the overflow
75719        ** page-list cache, if any, then fall back to the getOverflowPage()
75720        ** function.
75721        */
75722        assert( pCur->curFlags & BTCF_ValidOvfl );
75723        assert( pCur->pBtree->db==pBt->db );
75724        if( pCur->aOverflow[iIdx+1] ){
75725          nextPage = pCur->aOverflow[iIdx+1];
75726        }else{
75727          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
75728        }
75729        offset -= ovflSize;
75730      }else{
75731        /* Need to read this page properly. It contains some of the
75732        ** range of data that is being read (eOp==0) or written (eOp!=0).
75733        */
75734        int a = amt;
75735        if( a + offset > ovflSize ){
75736          a = ovflSize - offset;
75737        }
75738
75739#ifdef SQLITE_DIRECT_OVERFLOW_READ
75740        /* If all the following are true:
75741        **
75742        **   1) this is a read operation, and
75743        **   2) data is required from the start of this overflow page, and
75744        **   3) there are no dirty pages in the page-cache
75745        **   4) the database is file-backed, and
75746        **   5) the page is not in the WAL file
75747        **   6) at least 4 bytes have already been read into the output buffer
75748        **
75749        ** then data can be read directly from the database file into the
75750        ** output buffer, bypassing the page-cache altogether. This speeds
75751        ** up loading large records that span many overflow pages.
75752        */
75753        if( eOp==0                                             /* (1) */
75754         && offset==0                                          /* (2) */
75755         && sqlite3PagerDirectReadOk(pBt->pPager, nextPage)    /* (3,4,5) */
75756         && &pBuf[-4]>=pBufStart                               /* (6) */
75757        ){
75758          sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
75759          u8 aSave[4];
75760          u8 *aWrite = &pBuf[-4];
75761          assert( aWrite>=pBufStart );                         /* due to (6) */
75762          memcpy(aSave, aWrite, 4);
75763          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
75764          nextPage = get4byte(aWrite);
75765          memcpy(aWrite, aSave, 4);
75766        }else
75767#endif
75768
75769        {
75770          DbPage *pDbPage;
75771          rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
75772              (eOp==0 ? PAGER_GET_READONLY : 0)
75773          );
75774          if( rc==SQLITE_OK ){
75775            aPayload = sqlite3PagerGetData(pDbPage);
75776            nextPage = get4byte(aPayload);
75777            rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
75778            sqlite3PagerUnref(pDbPage);
75779            offset = 0;
75780          }
75781        }
75782        amt -= a;
75783        if( amt==0 ) return rc;
75784        pBuf += a;
75785      }
75786      if( rc ) break;
75787      iIdx++;
75788    }
75789  }
75790
75791  if( rc==SQLITE_OK && amt>0 ){
75792    /* Overflow chain ends prematurely */
75793    return SQLITE_CORRUPT_PAGE(pPage);
75794  }
75795  return rc;
75796}
75797
75798/*
75799** Read part of the payload for the row at which that cursor pCur is currently
75800** pointing.  "amt" bytes will be transferred into pBuf[].  The transfer
75801** begins at "offset".
75802**
75803** pCur can be pointing to either a table or an index b-tree.
75804** If pointing to a table btree, then the content section is read.  If
75805** pCur is pointing to an index b-tree then the key section is read.
75806**
75807** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
75808** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the
75809** cursor might be invalid or might need to be restored before being read.
75810**
75811** Return SQLITE_OK on success or an error code if anything goes
75812** wrong.  An error is returned if "offset+amt" is larger than
75813** the available payload.
75814*/
75815SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
75816  assert( cursorHoldsMutex(pCur) );
75817  assert( pCur->eState==CURSOR_VALID );
75818  assert( pCur->iPage>=0 && pCur->pPage );
75819  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
75820}
75821
75822/*
75823** This variant of sqlite3BtreePayload() works even if the cursor has not
75824** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()
75825** interface.
75826*/
75827#ifndef SQLITE_OMIT_INCRBLOB
75828static SQLITE_NOINLINE int accessPayloadChecked(
75829  BtCursor *pCur,
75830  u32 offset,
75831  u32 amt,
75832  void *pBuf
75833){
75834  int rc;
75835  if ( pCur->eState==CURSOR_INVALID ){
75836    return SQLITE_ABORT;
75837  }
75838  assert( cursorOwnsBtShared(pCur) );
75839  rc = btreeRestoreCursorPosition(pCur);
75840  return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
75841}
75842SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
75843  if( pCur->eState==CURSOR_VALID ){
75844    assert( cursorOwnsBtShared(pCur) );
75845    return accessPayload(pCur, offset, amt, pBuf, 0);
75846  }else{
75847    return accessPayloadChecked(pCur, offset, amt, pBuf);
75848  }
75849}
75850#endif /* SQLITE_OMIT_INCRBLOB */
75851
75852/*
75853** Return a pointer to payload information from the entry that the
75854** pCur cursor is pointing to.  The pointer is to the beginning of
75855** the key if index btrees (pPage->intKey==0) and is the data for
75856** table btrees (pPage->intKey==1). The number of bytes of available
75857** key/data is written into *pAmt.  If *pAmt==0, then the value
75858** returned will not be a valid pointer.
75859**
75860** This routine is an optimization.  It is common for the entire key
75861** and data to fit on the local page and for there to be no overflow
75862** pages.  When that is so, this routine can be used to access the
75863** key and data without making a copy.  If the key and/or data spills
75864** onto overflow pages, then accessPayload() must be used to reassemble
75865** the key/data and copy it into a preallocated buffer.
75866**
75867** The pointer returned by this routine looks directly into the cached
75868** page of the database.  The data might change or move the next time
75869** any btree routine is called.
75870*/
75871static const void *fetchPayload(
75872  BtCursor *pCur,      /* Cursor pointing to entry to read from */
75873  u32 *pAmt            /* Write the number of available bytes here */
75874){
75875  int amt;
75876  assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
75877  assert( pCur->eState==CURSOR_VALID );
75878  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
75879  assert( cursorOwnsBtShared(pCur) );
75880  assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
75881  assert( pCur->info.nSize>0 );
75882  assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
75883  assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
75884  amt = pCur->info.nLocal;
75885  if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
75886    /* There is too little space on the page for the expected amount
75887    ** of local content. Database must be corrupt. */
75888    assert( CORRUPT_DB );
75889    amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
75890  }
75891  *pAmt = (u32)amt;
75892  return (void*)pCur->info.pPayload;
75893}
75894
75895
75896/*
75897** For the entry that cursor pCur is point to, return as
75898** many bytes of the key or data as are available on the local
75899** b-tree page.  Write the number of available bytes into *pAmt.
75900**
75901** The pointer returned is ephemeral.  The key/data may move
75902** or be destroyed on the next call to any Btree routine,
75903** including calls from other threads against the same cache.
75904** Hence, a mutex on the BtShared should be held prior to calling
75905** this routine.
75906**
75907** These routines is used to get quick access to key and data
75908** in the common case where no overflow pages are used.
75909*/
75910SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
75911  return fetchPayload(pCur, pAmt);
75912}
75913
75914
75915/*
75916** Move the cursor down to a new child page.  The newPgno argument is the
75917** page number of the child page to move to.
75918**
75919** This function returns SQLITE_CORRUPT if the page-header flags field of
75920** the new child page does not match the flags field of the parent (i.e.
75921** if an intkey page appears to be the parent of a non-intkey page, or
75922** vice-versa).
75923*/
75924static int moveToChild(BtCursor *pCur, u32 newPgno){
75925  int rc;
75926  assert( cursorOwnsBtShared(pCur) );
75927  assert( pCur->eState==CURSOR_VALID );
75928  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
75929  assert( pCur->iPage>=0 );
75930  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
75931    return SQLITE_CORRUPT_BKPT;
75932  }
75933  pCur->info.nSize = 0;
75934  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
75935  pCur->aiIdx[pCur->iPage] = pCur->ix;
75936  pCur->apPage[pCur->iPage] = pCur->pPage;
75937  pCur->ix = 0;
75938  pCur->iPage++;
75939  rc = getAndInitPage(pCur->pBt, newPgno, &pCur->pPage, pCur->curPagerFlags);
75940  assert( pCur->pPage!=0 || rc!=SQLITE_OK );
75941  if( rc==SQLITE_OK
75942   && (pCur->pPage->nCell<1 || pCur->pPage->intKey!=pCur->curIntKey)
75943  ){
75944    releasePage(pCur->pPage);
75945    rc = SQLITE_CORRUPT_PGNO(newPgno);
75946  }
75947  if( rc ){
75948    pCur->pPage = pCur->apPage[--pCur->iPage];
75949  }
75950  return rc;
75951}
75952
75953#ifdef SQLITE_DEBUG
75954/*
75955** Page pParent is an internal (non-leaf) tree page. This function
75956** asserts that page number iChild is the left-child if the iIdx'th
75957** cell in page pParent. Or, if iIdx is equal to the total number of
75958** cells in pParent, that page number iChild is the right-child of
75959** the page.
75960*/
75961static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
75962  if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
75963                            ** in a corrupt database */
75964  assert( iIdx<=pParent->nCell );
75965  if( iIdx==pParent->nCell ){
75966    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
75967  }else{
75968    assert( get4byte(findCell(pParent, iIdx))==iChild );
75969  }
75970}
75971#else
75972#  define assertParentIndex(x,y,z)
75973#endif
75974
75975/*
75976** Move the cursor up to the parent page.
75977**
75978** pCur->idx is set to the cell index that contains the pointer
75979** to the page we are coming from.  If we are coming from the
75980** right-most child page then pCur->idx is set to one more than
75981** the largest cell index.
75982*/
75983static void moveToParent(BtCursor *pCur){
75984  MemPage *pLeaf;
75985  assert( cursorOwnsBtShared(pCur) );
75986  assert( pCur->eState==CURSOR_VALID );
75987  assert( pCur->iPage>0 );
75988  assert( pCur->pPage );
75989  assertParentIndex(
75990    pCur->apPage[pCur->iPage-1],
75991    pCur->aiIdx[pCur->iPage-1],
75992    pCur->pPage->pgno
75993  );
75994  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
75995  pCur->info.nSize = 0;
75996  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
75997  pCur->ix = pCur->aiIdx[pCur->iPage-1];
75998  pLeaf = pCur->pPage;
75999  pCur->pPage = pCur->apPage[--pCur->iPage];
76000  releasePageNotNull(pLeaf);
76001}
76002
76003/*
76004** Move the cursor to point to the root page of its b-tree structure.
76005**
76006** If the table has a virtual root page, then the cursor is moved to point
76007** to the virtual root page instead of the actual root page. A table has a
76008** virtual root page when the actual root page contains no cells and a
76009** single child page. This can only happen with the table rooted at page 1.
76010**
76011** If the b-tree structure is empty, the cursor state is set to
76012** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
76013** the cursor is set to point to the first cell located on the root
76014** (or virtual root) page and the cursor state is set to CURSOR_VALID.
76015**
76016** If this function returns successfully, it may be assumed that the
76017** page-header flags indicate that the [virtual] root-page is the expected
76018** kind of b-tree page (i.e. if when opening the cursor the caller did not
76019** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
76020** indicating a table b-tree, or if the caller did specify a KeyInfo
76021** structure the flags byte is set to 0x02 or 0x0A, indicating an index
76022** b-tree).
76023*/
76024static int moveToRoot(BtCursor *pCur){
76025  MemPage *pRoot;
76026  int rc = SQLITE_OK;
76027
76028  assert( cursorOwnsBtShared(pCur) );
76029  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
76030  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
76031  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
76032  assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
76033  assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
76034
76035  if( pCur->iPage>=0 ){
76036    if( pCur->iPage ){
76037      releasePageNotNull(pCur->pPage);
76038      while( --pCur->iPage ){
76039        releasePageNotNull(pCur->apPage[pCur->iPage]);
76040      }
76041      pRoot = pCur->pPage = pCur->apPage[0];
76042      goto skip_init;
76043    }
76044  }else if( pCur->pgnoRoot==0 ){
76045    pCur->eState = CURSOR_INVALID;
76046    return SQLITE_EMPTY;
76047  }else{
76048    assert( pCur->iPage==(-1) );
76049    if( pCur->eState>=CURSOR_REQUIRESEEK ){
76050      if( pCur->eState==CURSOR_FAULT ){
76051        assert( pCur->skipNext!=SQLITE_OK );
76052        return pCur->skipNext;
76053      }
76054      sqlite3BtreeClearCursor(pCur);
76055    }
76056    rc = getAndInitPage(pCur->pBt, pCur->pgnoRoot, &pCur->pPage,
76057                        pCur->curPagerFlags);
76058    if( rc!=SQLITE_OK ){
76059      pCur->eState = CURSOR_INVALID;
76060      return rc;
76061    }
76062    pCur->iPage = 0;
76063    pCur->curIntKey = pCur->pPage->intKey;
76064  }
76065  pRoot = pCur->pPage;
76066  assert( pRoot->pgno==pCur->pgnoRoot || CORRUPT_DB );
76067
76068  /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
76069  ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
76070  ** NULL, the caller expects a table b-tree. If this is not the case,
76071  ** return an SQLITE_CORRUPT error.
76072  **
76073  ** Earlier versions of SQLite assumed that this test could not fail
76074  ** if the root page was already loaded when this function was called (i.e.
76075  ** if pCur->iPage>=0). But this is not so if the database is corrupted
76076  ** in such a way that page pRoot is linked into a second b-tree table
76077  ** (or the freelist).  */
76078  assert( pRoot->intKey==1 || pRoot->intKey==0 );
76079  if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
76080    return SQLITE_CORRUPT_PAGE(pCur->pPage);
76081  }
76082
76083skip_init:
76084  pCur->ix = 0;
76085  pCur->info.nSize = 0;
76086  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
76087
76088  if( pRoot->nCell>0 ){
76089    pCur->eState = CURSOR_VALID;
76090  }else if( !pRoot->leaf ){
76091    Pgno subpage;
76092    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
76093    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
76094    pCur->eState = CURSOR_VALID;
76095    rc = moveToChild(pCur, subpage);
76096  }else{
76097    pCur->eState = CURSOR_INVALID;
76098    rc = SQLITE_EMPTY;
76099  }
76100  return rc;
76101}
76102
76103/*
76104** Move the cursor down to the left-most leaf entry beneath the
76105** entry to which it is currently pointing.
76106**
76107** The left-most leaf is the one with the smallest key - the first
76108** in ascending order.
76109*/
76110static int moveToLeftmost(BtCursor *pCur){
76111  Pgno pgno;
76112  int rc = SQLITE_OK;
76113  MemPage *pPage;
76114
76115  assert( cursorOwnsBtShared(pCur) );
76116  assert( pCur->eState==CURSOR_VALID );
76117  while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
76118    assert( pCur->ix<pPage->nCell );
76119    pgno = get4byte(findCell(pPage, pCur->ix));
76120    rc = moveToChild(pCur, pgno);
76121  }
76122  return rc;
76123}
76124
76125/*
76126** Move the cursor down to the right-most leaf entry beneath the
76127** page to which it is currently pointing.  Notice the difference
76128** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
76129** finds the left-most entry beneath the *entry* whereas moveToRightmost()
76130** finds the right-most entry beneath the *page*.
76131**
76132** The right-most entry is the one with the largest key - the last
76133** key in ascending order.
76134*/
76135static int moveToRightmost(BtCursor *pCur){
76136  Pgno pgno;
76137  int rc = SQLITE_OK;
76138  MemPage *pPage = 0;
76139
76140  assert( cursorOwnsBtShared(pCur) );
76141  assert( pCur->eState==CURSOR_VALID );
76142  while( !(pPage = pCur->pPage)->leaf ){
76143    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
76144    pCur->ix = pPage->nCell;
76145    rc = moveToChild(pCur, pgno);
76146    if( rc ) return rc;
76147  }
76148  pCur->ix = pPage->nCell-1;
76149  assert( pCur->info.nSize==0 );
76150  assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
76151  return SQLITE_OK;
76152}
76153
76154/* Move the cursor to the first entry in the table.  Return SQLITE_OK
76155** on success.  Set *pRes to 0 if the cursor actually points to something
76156** or set *pRes to 1 if the table is empty.
76157*/
76158SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
76159  int rc;
76160
76161  assert( cursorOwnsBtShared(pCur) );
76162  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
76163  rc = moveToRoot(pCur);
76164  if( rc==SQLITE_OK ){
76165    assert( pCur->pPage->nCell>0 );
76166    *pRes = 0;
76167    rc = moveToLeftmost(pCur);
76168  }else if( rc==SQLITE_EMPTY ){
76169    assert( pCur->pgnoRoot==0 || (pCur->pPage!=0 && pCur->pPage->nCell==0) );
76170    *pRes = 1;
76171    rc = SQLITE_OK;
76172  }
76173  return rc;
76174}
76175
76176#ifdef SQLITE_DEBUG
76177/* The cursors is CURSOR_VALID and has BTCF_AtLast set.  Verify that
76178** this flags are true for a consistent database.
76179**
76180** This routine is is called from within assert() statements only.
76181** It is an internal verification routine and does not appear in production
76182** builds.
76183*/
76184static int cursorIsAtLastEntry(BtCursor *pCur){
76185  int ii;
76186  for(ii=0; ii<pCur->iPage; ii++){
76187    if( pCur->aiIdx[ii]!=pCur->apPage[ii]->nCell ) return 0;
76188  }
76189  return pCur->ix==pCur->pPage->nCell-1 && pCur->pPage->leaf!=0;
76190}
76191#endif
76192
76193/* Move the cursor to the last entry in the table.  Return SQLITE_OK
76194** on success.  Set *pRes to 0 if the cursor actually points to something
76195** or set *pRes to 1 if the table is empty.
76196*/
76197static SQLITE_NOINLINE int btreeLast(BtCursor *pCur, int *pRes){
76198  int rc = moveToRoot(pCur);
76199  if( rc==SQLITE_OK ){
76200    assert( pCur->eState==CURSOR_VALID );
76201    *pRes = 0;
76202    rc = moveToRightmost(pCur);
76203    if( rc==SQLITE_OK ){
76204      pCur->curFlags |= BTCF_AtLast;
76205    }else{
76206      pCur->curFlags &= ~BTCF_AtLast;
76207    }
76208  }else if( rc==SQLITE_EMPTY ){
76209    assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
76210    *pRes = 1;
76211    rc = SQLITE_OK;
76212  }
76213  return rc;
76214}
76215SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
76216  assert( cursorOwnsBtShared(pCur) );
76217  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
76218
76219  /* If the cursor already points to the last entry, this is a no-op. */
76220  if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
76221    assert( cursorIsAtLastEntry(pCur) || CORRUPT_DB );
76222    *pRes = 0;
76223    return SQLITE_OK;
76224  }
76225  return btreeLast(pCur, pRes);
76226}
76227
76228/* Move the cursor so that it points to an entry in a table (a.k.a INTKEY)
76229** table near the key intKey.   Return a success code.
76230**
76231** If an exact match is not found, then the cursor is always
76232** left pointing at a leaf page which would hold the entry if it
76233** were present.  The cursor might point to an entry that comes
76234** before or after the key.
76235**
76236** An integer is written into *pRes which is the result of
76237** comparing the key with the entry to which the cursor is
76238** pointing.  The meaning of the integer written into
76239** *pRes is as follows:
76240**
76241**     *pRes<0      The cursor is left pointing at an entry that
76242**                  is smaller than intKey or if the table is empty
76243**                  and the cursor is therefore left point to nothing.
76244**
76245**     *pRes==0     The cursor is left pointing at an entry that
76246**                  exactly matches intKey.
76247**
76248**     *pRes>0      The cursor is left pointing at an entry that
76249**                  is larger than intKey.
76250*/
76251SQLITE_PRIVATE int sqlite3BtreeTableMoveto(
76252  BtCursor *pCur,          /* The cursor to be moved */
76253  i64 intKey,              /* The table key */
76254  int biasRight,           /* If true, bias the search to the high end */
76255  int *pRes                /* Write search results here */
76256){
76257  int rc;
76258
76259  assert( cursorOwnsBtShared(pCur) );
76260  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
76261  assert( pRes );
76262  assert( pCur->pKeyInfo==0 );
76263  assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 );
76264
76265  /* If the cursor is already positioned at the point we are trying
76266  ** to move to, then just return without doing any work */
76267  if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){
76268    if( pCur->info.nKey==intKey ){
76269      *pRes = 0;
76270      return SQLITE_OK;
76271    }
76272    if( pCur->info.nKey<intKey ){
76273      if( (pCur->curFlags & BTCF_AtLast)!=0 ){
76274        assert( cursorIsAtLastEntry(pCur) || CORRUPT_DB );
76275        *pRes = -1;
76276        return SQLITE_OK;
76277      }
76278      /* If the requested key is one more than the previous key, then
76279      ** try to get there using sqlite3BtreeNext() rather than a full
76280      ** binary search.  This is an optimization only.  The correct answer
76281      ** is still obtained without this case, only a little more slowly. */
76282      if( pCur->info.nKey+1==intKey ){
76283        *pRes = 0;
76284        rc = sqlite3BtreeNext(pCur, 0);
76285        if( rc==SQLITE_OK ){
76286          getCellInfo(pCur);
76287          if( pCur->info.nKey==intKey ){
76288            return SQLITE_OK;
76289          }
76290        }else if( rc!=SQLITE_DONE ){
76291          return rc;
76292        }
76293      }
76294    }
76295  }
76296
76297#ifdef SQLITE_DEBUG
76298  pCur->pBtree->nSeek++;   /* Performance measurement during testing */
76299#endif
76300
76301  rc = moveToRoot(pCur);
76302  if( rc ){
76303    if( rc==SQLITE_EMPTY ){
76304      assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
76305      *pRes = -1;
76306      return SQLITE_OK;
76307    }
76308    return rc;
76309  }
76310  assert( pCur->pPage );
76311  assert( pCur->pPage->isInit );
76312  assert( pCur->eState==CURSOR_VALID );
76313  assert( pCur->pPage->nCell > 0 );
76314  assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
76315  assert( pCur->curIntKey );
76316
76317  for(;;){
76318    int lwr, upr, idx, c;
76319    Pgno chldPg;
76320    MemPage *pPage = pCur->pPage;
76321    u8 *pCell;                          /* Pointer to current cell in pPage */
76322
76323    /* pPage->nCell must be greater than zero. If this is the root-page
76324    ** the cursor would have been INVALID above and this for(;;) loop
76325    ** not run. If this is not the root-page, then the moveToChild() routine
76326    ** would have already detected db corruption. Similarly, pPage must
76327    ** be the right kind (index or table) of b-tree page. Otherwise
76328    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
76329    assert( pPage->nCell>0 );
76330    assert( pPage->intKey );
76331    lwr = 0;
76332    upr = pPage->nCell-1;
76333    assert( biasRight==0 || biasRight==1 );
76334    idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
76335    for(;;){
76336      i64 nCellKey;
76337      pCell = findCellPastPtr(pPage, idx);
76338      if( pPage->intKeyLeaf ){
76339        while( 0x80 <= *(pCell++) ){
76340          if( pCell>=pPage->aDataEnd ){
76341            return SQLITE_CORRUPT_PAGE(pPage);
76342          }
76343        }
76344      }
76345      getVarint(pCell, (u64*)&nCellKey);
76346      if( nCellKey<intKey ){
76347        lwr = idx+1;
76348        if( lwr>upr ){ c = -1; break; }
76349      }else if( nCellKey>intKey ){
76350        upr = idx-1;
76351        if( lwr>upr ){ c = +1; break; }
76352      }else{
76353        assert( nCellKey==intKey );
76354        pCur->ix = (u16)idx;
76355        if( !pPage->leaf ){
76356          lwr = idx;
76357          goto moveto_table_next_layer;
76358        }else{
76359          pCur->curFlags |= BTCF_ValidNKey;
76360          pCur->info.nKey = nCellKey;
76361          pCur->info.nSize = 0;
76362          *pRes = 0;
76363          return SQLITE_OK;
76364        }
76365      }
76366      assert( lwr+upr>=0 );
76367      idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
76368    }
76369    assert( lwr==upr+1 || !pPage->leaf );
76370    assert( pPage->isInit );
76371    if( pPage->leaf ){
76372      assert( pCur->ix<pCur->pPage->nCell );
76373      pCur->ix = (u16)idx;
76374      *pRes = c;
76375      rc = SQLITE_OK;
76376      goto moveto_table_finish;
76377    }
76378moveto_table_next_layer:
76379    if( lwr>=pPage->nCell ){
76380      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
76381    }else{
76382      chldPg = get4byte(findCell(pPage, lwr));
76383    }
76384    pCur->ix = (u16)lwr;
76385    rc = moveToChild(pCur, chldPg);
76386    if( rc ) break;
76387  }
76388moveto_table_finish:
76389  pCur->info.nSize = 0;
76390  assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
76391  return rc;
76392}
76393
76394/*
76395** Compare the "idx"-th cell on the page the cursor pCur is currently
76396** pointing to to pIdxKey using xRecordCompare.  Return negative or
76397** zero if the cell is less than or equal pIdxKey.  Return positive
76398** if unknown.
76399**
76400**    Return value negative:     Cell at pCur[idx] less than pIdxKey
76401**
76402**    Return value is zero:      Cell at pCur[idx] equals pIdxKey
76403**
76404**    Return value positive:     Nothing is known about the relationship
76405**                               of the cell at pCur[idx] and pIdxKey.
76406**
76407** This routine is part of an optimization.  It is always safe to return
76408** a positive value as that will cause the optimization to be skipped.
76409*/
76410static int indexCellCompare(
76411  BtCursor *pCur,
76412  int idx,
76413  UnpackedRecord *pIdxKey,
76414  RecordCompare xRecordCompare
76415){
76416  MemPage *pPage = pCur->pPage;
76417  int c;
76418  int nCell;  /* Size of the pCell cell in bytes */
76419  u8 *pCell = findCellPastPtr(pPage, idx);
76420
76421  nCell = pCell[0];
76422  if( nCell<=pPage->max1bytePayload ){
76423    /* This branch runs if the record-size field of the cell is a
76424    ** single byte varint and the record fits entirely on the main
76425    ** b-tree page.  */
76426    testcase( pCell+nCell+1==pPage->aDataEnd );
76427    c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
76428  }else if( !(pCell[1] & 0x80)
76429    && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
76430  ){
76431    /* The record-size field is a 2 byte varint and the record
76432    ** fits entirely on the main b-tree page.  */
76433    testcase( pCell+nCell+2==pPage->aDataEnd );
76434    c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
76435  }else{
76436    /* If the record extends into overflow pages, do not attempt
76437    ** the optimization. */
76438    c = 99;
76439  }
76440  return c;
76441}
76442
76443/*
76444** Return true (non-zero) if pCur is current pointing to the last
76445** page of a table.
76446*/
76447static int cursorOnLastPage(BtCursor *pCur){
76448  int i;
76449  assert( pCur->eState==CURSOR_VALID );
76450  for(i=0; i<pCur->iPage; i++){
76451    MemPage *pPage = pCur->apPage[i];
76452    if( pCur->aiIdx[i]<pPage->nCell ) return 0;
76453  }
76454  return 1;
76455}
76456
76457/* Move the cursor so that it points to an entry in an index table
76458** near the key pIdxKey.   Return a success code.
76459**
76460** If an exact match is not found, then the cursor is always
76461** left pointing at a leaf page which would hold the entry if it
76462** were present.  The cursor might point to an entry that comes
76463** before or after the key.
76464**
76465** An integer is written into *pRes which is the result of
76466** comparing the key with the entry to which the cursor is
76467** pointing.  The meaning of the integer written into
76468** *pRes is as follows:
76469**
76470**     *pRes<0      The cursor is left pointing at an entry that
76471**                  is smaller than pIdxKey or if the table is empty
76472**                  and the cursor is therefore left point to nothing.
76473**
76474**     *pRes==0     The cursor is left pointing at an entry that
76475**                  exactly matches pIdxKey.
76476**
76477**     *pRes>0      The cursor is left pointing at an entry that
76478**                  is larger than pIdxKey.
76479**
76480** The pIdxKey->eqSeen field is set to 1 if there
76481** exists an entry in the table that exactly matches pIdxKey.
76482*/
76483SQLITE_PRIVATE int sqlite3BtreeIndexMoveto(
76484  BtCursor *pCur,          /* The cursor to be moved */
76485  UnpackedRecord *pIdxKey, /* Unpacked index key */
76486  int *pRes                /* Write search results here */
76487){
76488  int rc;
76489  RecordCompare xRecordCompare;
76490
76491  assert( cursorOwnsBtShared(pCur) );
76492  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
76493  assert( pRes );
76494  assert( pCur->pKeyInfo!=0 );
76495
76496#ifdef SQLITE_DEBUG
76497  pCur->pBtree->nSeek++;   /* Performance measurement during testing */
76498#endif
76499
76500  xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
76501  pIdxKey->errCode = 0;
76502  assert( pIdxKey->default_rc==1
76503       || pIdxKey->default_rc==0
76504       || pIdxKey->default_rc==-1
76505  );
76506
76507
76508  /* Check to see if we can skip a lot of work.  Two cases:
76509  **
76510  **    (1) If the cursor is already pointing to the very last cell
76511  **        in the table and the pIdxKey search key is greater than or
76512  **        equal to that last cell, then no movement is required.
76513  **
76514  **    (2) If the cursor is on the last page of the table and the first
76515  **        cell on that last page is less than or equal to the pIdxKey
76516  **        search key, then we can start the search on the current page
76517  **        without needing to go back to root.
76518  */
76519  if( pCur->eState==CURSOR_VALID
76520   && pCur->pPage->leaf
76521   && cursorOnLastPage(pCur)
76522  ){
76523    int c;
76524    if( pCur->ix==pCur->pPage->nCell-1
76525     && (c = indexCellCompare(pCur, pCur->ix, pIdxKey, xRecordCompare))<=0
76526     && pIdxKey->errCode==SQLITE_OK
76527    ){
76528      *pRes = c;
76529      return SQLITE_OK;  /* Cursor already pointing at the correct spot */
76530    }
76531    if( pCur->iPage>0
76532     && indexCellCompare(pCur, 0, pIdxKey, xRecordCompare)<=0
76533     && pIdxKey->errCode==SQLITE_OK
76534    ){
76535      pCur->curFlags &= ~BTCF_ValidOvfl;
76536      if( !pCur->pPage->isInit ){
76537        return SQLITE_CORRUPT_BKPT;
76538      }
76539      goto bypass_moveto_root;  /* Start search on the current page */
76540    }
76541    pIdxKey->errCode = SQLITE_OK;
76542  }
76543
76544  rc = moveToRoot(pCur);
76545  if( rc ){
76546    if( rc==SQLITE_EMPTY ){
76547      assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
76548      *pRes = -1;
76549      return SQLITE_OK;
76550    }
76551    return rc;
76552  }
76553
76554bypass_moveto_root:
76555  assert( pCur->pPage );
76556  assert( pCur->pPage->isInit );
76557  assert( pCur->eState==CURSOR_VALID );
76558  assert( pCur->pPage->nCell > 0 );
76559  assert( pCur->curIntKey==0 );
76560  assert( pIdxKey!=0 );
76561  for(;;){
76562    int lwr, upr, idx, c;
76563    Pgno chldPg;
76564    MemPage *pPage = pCur->pPage;
76565    u8 *pCell;                          /* Pointer to current cell in pPage */
76566
76567    /* pPage->nCell must be greater than zero. If this is the root-page
76568    ** the cursor would have been INVALID above and this for(;;) loop
76569    ** not run. If this is not the root-page, then the moveToChild() routine
76570    ** would have already detected db corruption. Similarly, pPage must
76571    ** be the right kind (index or table) of b-tree page. Otherwise
76572    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
76573    assert( pPage->nCell>0 );
76574    assert( pPage->intKey==0 );
76575    lwr = 0;
76576    upr = pPage->nCell-1;
76577    idx = upr>>1; /* idx = (lwr+upr)/2; */
76578    for(;;){
76579      int nCell;  /* Size of the pCell cell in bytes */
76580      pCell = findCellPastPtr(pPage, idx);
76581
76582      /* The maximum supported page-size is 65536 bytes. This means that
76583      ** the maximum number of record bytes stored on an index B-Tree
76584      ** page is less than 16384 bytes and may be stored as a 2-byte
76585      ** varint. This information is used to attempt to avoid parsing
76586      ** the entire cell by checking for the cases where the record is
76587      ** stored entirely within the b-tree page by inspecting the first
76588      ** 2 bytes of the cell.
76589      */
76590      nCell = pCell[0];
76591      if( nCell<=pPage->max1bytePayload ){
76592        /* This branch runs if the record-size field of the cell is a
76593        ** single byte varint and the record fits entirely on the main
76594        ** b-tree page.  */
76595        testcase( pCell+nCell+1==pPage->aDataEnd );
76596        c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
76597      }else if( !(pCell[1] & 0x80)
76598        && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
76599      ){
76600        /* The record-size field is a 2 byte varint and the record
76601        ** fits entirely on the main b-tree page.  */
76602        testcase( pCell+nCell+2==pPage->aDataEnd );
76603        c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
76604      }else{
76605        /* The record flows over onto one or more overflow pages. In
76606        ** this case the whole cell needs to be parsed, a buffer allocated
76607        ** and accessPayload() used to retrieve the record into the
76608        ** buffer before VdbeRecordCompare() can be called.
76609        **
76610        ** If the record is corrupt, the xRecordCompare routine may read
76611        ** up to two varints past the end of the buffer. An extra 18
76612        ** bytes of padding is allocated at the end of the buffer in
76613        ** case this happens.  */
76614        void *pCellKey;
76615        u8 * const pCellBody = pCell - pPage->childPtrSize;
76616        const int nOverrun = 18;  /* Size of the overrun padding */
76617        pPage->xParseCell(pPage, pCellBody, &pCur->info);
76618        nCell = (int)pCur->info.nKey;
76619        testcase( nCell<0 );   /* True if key size is 2^32 or more */
76620        testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
76621        testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
76622        testcase( nCell==2 );  /* Minimum legal index key size */
76623        if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
76624          rc = SQLITE_CORRUPT_PAGE(pPage);
76625          goto moveto_index_finish;
76626        }
76627        pCellKey = sqlite3Malloc( nCell+nOverrun );
76628        if( pCellKey==0 ){
76629          rc = SQLITE_NOMEM_BKPT;
76630          goto moveto_index_finish;
76631        }
76632        pCur->ix = (u16)idx;
76633        rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
76634        memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
76635        pCur->curFlags &= ~BTCF_ValidOvfl;
76636        if( rc ){
76637          sqlite3_free(pCellKey);
76638          goto moveto_index_finish;
76639        }
76640        c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
76641        sqlite3_free(pCellKey);
76642      }
76643      assert(
76644          (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
76645       && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
76646      );
76647      if( c<0 ){
76648        lwr = idx+1;
76649      }else if( c>0 ){
76650        upr = idx-1;
76651      }else{
76652        assert( c==0 );
76653        *pRes = 0;
76654        rc = SQLITE_OK;
76655        pCur->ix = (u16)idx;
76656        if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
76657        goto moveto_index_finish;
76658      }
76659      if( lwr>upr ) break;
76660      assert( lwr+upr>=0 );
76661      idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
76662    }
76663    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
76664    assert( pPage->isInit );
76665    if( pPage->leaf ){
76666      assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
76667      pCur->ix = (u16)idx;
76668      *pRes = c;
76669      rc = SQLITE_OK;
76670      goto moveto_index_finish;
76671    }
76672    if( lwr>=pPage->nCell ){
76673      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
76674    }else{
76675      chldPg = get4byte(findCell(pPage, lwr));
76676    }
76677
76678    /* This block is similar to an in-lined version of:
76679    **
76680    **    pCur->ix = (u16)lwr;
76681    **    rc = moveToChild(pCur, chldPg);
76682    **    if( rc ) break;
76683    */
76684    pCur->info.nSize = 0;
76685    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
76686    if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
76687      return SQLITE_CORRUPT_BKPT;
76688    }
76689    pCur->aiIdx[pCur->iPage] = (u16)lwr;
76690    pCur->apPage[pCur->iPage] = pCur->pPage;
76691    pCur->ix = 0;
76692    pCur->iPage++;
76693    rc = getAndInitPage(pCur->pBt, chldPg, &pCur->pPage, pCur->curPagerFlags);
76694    if( rc==SQLITE_OK
76695     && (pCur->pPage->nCell<1 || pCur->pPage->intKey!=pCur->curIntKey)
76696    ){
76697      releasePage(pCur->pPage);
76698      rc = SQLITE_CORRUPT_PGNO(chldPg);
76699    }
76700    if( rc ){
76701      pCur->pPage = pCur->apPage[--pCur->iPage];
76702      break;
76703    }
76704    /*
76705    ***** End of in-lined moveToChild() call */
76706 }
76707moveto_index_finish:
76708  pCur->info.nSize = 0;
76709  assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
76710  return rc;
76711}
76712
76713
76714/*
76715** Return TRUE if the cursor is not pointing at an entry of the table.
76716**
76717** TRUE will be returned after a call to sqlite3BtreeNext() moves
76718** past the last entry in the table or sqlite3BtreePrev() moves past
76719** the first entry.  TRUE is also returned if the table is empty.
76720*/
76721SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
76722  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
76723  ** have been deleted? This API will need to change to return an error code
76724  ** as well as the boolean result value.
76725  */
76726  return (CURSOR_VALID!=pCur->eState);
76727}
76728
76729/*
76730** Return an estimate for the number of rows in the table that pCur is
76731** pointing to.  Return a negative number if no estimate is currently
76732** available.
76733*/
76734SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
76735  i64 n;
76736  u8 i;
76737
76738  assert( cursorOwnsBtShared(pCur) );
76739  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
76740
76741  /* Currently this interface is only called by the OP_IfSizeBetween
76742  ** opcode and the OP_Count opcode with P3=1.  In either case,
76743  ** the cursor will always be valid unless the btree is empty. */
76744  if( pCur->eState!=CURSOR_VALID ) return 0;
76745  if( NEVER(pCur->pPage->leaf==0) ) return -1;
76746
76747  n = pCur->pPage->nCell;
76748  for(i=0; i<pCur->iPage; i++){
76749    n *= pCur->apPage[i]->nCell;
76750  }
76751  return n;
76752}
76753
76754/*
76755** Advance the cursor to the next entry in the database.
76756** Return value:
76757**
76758**    SQLITE_OK        success
76759**    SQLITE_DONE      cursor is already pointing at the last element
76760**    otherwise        some kind of error occurred
76761**
76762** The main entry point is sqlite3BtreeNext().  That routine is optimized
76763** for the common case of merely incrementing the cell counter BtCursor.aiIdx
76764** to the next cell on the current page.  The (slower) btreeNext() helper
76765** routine is called when it is necessary to move to a different page or
76766** to restore the cursor.
76767**
76768** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
76769** cursor corresponds to an SQL index and this routine could have been
76770** skipped if the SQL index had been a unique index.  The F argument
76771** is a hint to the implement.  SQLite btree implementation does not use
76772** this hint, but COMDB2 does.
76773*/
76774static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
76775  int rc;
76776  int idx;
76777  MemPage *pPage;
76778
76779  assert( cursorOwnsBtShared(pCur) );
76780  if( pCur->eState!=CURSOR_VALID ){
76781    assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
76782    rc = restoreCursorPosition(pCur);
76783    if( rc!=SQLITE_OK ){
76784      return rc;
76785    }
76786    if( CURSOR_INVALID==pCur->eState ){
76787      return SQLITE_DONE;
76788    }
76789    if( pCur->eState==CURSOR_SKIPNEXT ){
76790      pCur->eState = CURSOR_VALID;
76791      if( pCur->skipNext>0 ) return SQLITE_OK;
76792    }
76793  }
76794
76795  pPage = pCur->pPage;
76796  idx = ++pCur->ix;
76797  if( sqlite3FaultSim(412) ) pPage->isInit = 0;
76798  if( !pPage->isInit ){
76799    return SQLITE_CORRUPT_BKPT;
76800  }
76801
76802  if( idx>=pPage->nCell ){
76803    if( !pPage->leaf ){
76804      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
76805      if( rc ) return rc;
76806      return moveToLeftmost(pCur);
76807    }
76808    do{
76809      if( pCur->iPage==0 ){
76810        pCur->eState = CURSOR_INVALID;
76811        return SQLITE_DONE;
76812      }
76813      moveToParent(pCur);
76814      pPage = pCur->pPage;
76815    }while( pCur->ix>=pPage->nCell );
76816    if( pPage->intKey ){
76817      return sqlite3BtreeNext(pCur, 0);
76818    }else{
76819      return SQLITE_OK;
76820    }
76821  }
76822  if( pPage->leaf ){
76823    return SQLITE_OK;
76824  }else{
76825    return moveToLeftmost(pCur);
76826  }
76827}
76828SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
76829  MemPage *pPage;
76830  UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
76831  assert( cursorOwnsBtShared(pCur) );
76832  assert( flags==0 || flags==1 );
76833  pCur->info.nSize = 0;
76834  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
76835  if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
76836  pPage = pCur->pPage;
76837  if( (++pCur->ix)>=pPage->nCell ){
76838    pCur->ix--;
76839    return btreeNext(pCur);
76840  }
76841  if( pPage->leaf ){
76842    return SQLITE_OK;
76843  }else{
76844    return moveToLeftmost(pCur);
76845  }
76846}
76847
76848/*
76849** Step the cursor to the back to the previous entry in the database.
76850** Return values:
76851**
76852**     SQLITE_OK     success
76853**     SQLITE_DONE   the cursor is already on the first element of the table
76854**     otherwise     some kind of error occurred
76855**
76856** The main entry point is sqlite3BtreePrevious().  That routine is optimized
76857** for the common case of merely decrementing the cell counter BtCursor.aiIdx
76858** to the previous cell on the current page.  The (slower) btreePrevious()
76859** helper routine is called when it is necessary to move to a different page
76860** or to restore the cursor.
76861**
76862** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
76863** the cursor corresponds to an SQL index and this routine could have been
76864** skipped if the SQL index had been a unique index.  The F argument is a
76865** hint to the implement.  The native SQLite btree implementation does not
76866** use this hint, but COMDB2 does.
76867*/
76868static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
76869  int rc;
76870  MemPage *pPage;
76871
76872  assert( cursorOwnsBtShared(pCur) );
76873  assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
76874  assert( pCur->info.nSize==0 );
76875  if( pCur->eState!=CURSOR_VALID ){
76876    rc = restoreCursorPosition(pCur);
76877    if( rc!=SQLITE_OK ){
76878      return rc;
76879    }
76880    if( CURSOR_INVALID==pCur->eState ){
76881      return SQLITE_DONE;
76882    }
76883    if( CURSOR_SKIPNEXT==pCur->eState ){
76884      pCur->eState = CURSOR_VALID;
76885      if( pCur->skipNext<0 ) return SQLITE_OK;
76886    }
76887  }
76888
76889  pPage = pCur->pPage;
76890  if( sqlite3FaultSim(412) ) pPage->isInit = 0;
76891  if( !pPage->isInit ){
76892    return SQLITE_CORRUPT_BKPT;
76893  }
76894  if( !pPage->leaf ){
76895    int idx = pCur->ix;
76896    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
76897    if( rc ) return rc;
76898    rc = moveToRightmost(pCur);
76899  }else{
76900    while( pCur->ix==0 ){
76901      if( pCur->iPage==0 ){
76902        pCur->eState = CURSOR_INVALID;
76903        return SQLITE_DONE;
76904      }
76905      moveToParent(pCur);
76906    }
76907    assert( pCur->info.nSize==0 );
76908    assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
76909
76910    pCur->ix--;
76911    pPage = pCur->pPage;
76912    if( pPage->intKey && !pPage->leaf ){
76913      rc = sqlite3BtreePrevious(pCur, 0);
76914    }else{
76915      rc = SQLITE_OK;
76916    }
76917  }
76918  return rc;
76919}
76920SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
76921  assert( cursorOwnsBtShared(pCur) );
76922  assert( flags==0 || flags==1 );
76923  UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
76924  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
76925  pCur->info.nSize = 0;
76926  if( pCur->eState!=CURSOR_VALID
76927   || pCur->ix==0
76928   || pCur->pPage->leaf==0
76929  ){
76930    return btreePrevious(pCur);
76931  }
76932  pCur->ix--;
76933  return SQLITE_OK;
76934}
76935
76936/*
76937** Allocate a new page from the database file.
76938**
76939** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
76940** has already been called on the new page.)  The new page has also
76941** been referenced and the calling routine is responsible for calling
76942** sqlite3PagerUnref() on the new page when it is done.
76943**
76944** SQLITE_OK is returned on success.  Any other return value indicates
76945** an error.  *ppPage is set to NULL in the event of an error.
76946**
76947** If the "nearby" parameter is not 0, then an effort is made to
76948** locate a page close to the page number "nearby".  This can be used in an
76949** attempt to keep related pages close to each other in the database file,
76950** which in turn can make database access faster.
76951**
76952** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
76953** anywhere on the free-list, then it is guaranteed to be returned.  If
76954** eMode is BTALLOC_LT then the page returned will be less than or equal
76955** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
76956** are no restrictions on which page is returned.
76957*/
76958static int allocateBtreePage(
76959  BtShared *pBt,         /* The btree */
76960  MemPage **ppPage,      /* Store pointer to the allocated page here */
76961  Pgno *pPgno,           /* Store the page number here */
76962  Pgno nearby,           /* Search for a page near this one */
76963  u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
76964){
76965  MemPage *pPage1;
76966  int rc;
76967  u32 n;     /* Number of pages on the freelist */
76968  u32 k;     /* Number of leaves on the trunk of the freelist */
76969  MemPage *pTrunk = 0;
76970  MemPage *pPrevTrunk = 0;
76971  Pgno mxPage;     /* Total size of the database file */
76972
76973  assert( sqlite3_mutex_held(pBt->mutex) );
76974  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
76975  pPage1 = pBt->pPage1;
76976  mxPage = btreePagecount(pBt);
76977  /* EVIDENCE-OF: R-21003-45125 The 4-byte big-endian integer at offset 36
76978  ** stores the total number of pages on the freelist. */
76979  n = get4byte(&pPage1->aData[36]);
76980  testcase( n==mxPage-1 );
76981  if( n>=mxPage ){
76982    return SQLITE_CORRUPT_BKPT;
76983  }
76984  if( n>0 ){
76985    /* There are pages on the freelist.  Reuse one of those pages. */
76986    Pgno iTrunk;
76987    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
76988    u32 nSearch = 0;   /* Count of the number of search attempts */
76989
76990    /* If eMode==BTALLOC_EXACT and a query of the pointer-map
76991    ** shows that the page 'nearby' is somewhere on the free-list, then
76992    ** the entire-list will be searched for that page.
76993    */
76994#ifndef SQLITE_OMIT_AUTOVACUUM
76995    if( eMode==BTALLOC_EXACT ){
76996      if( nearby<=mxPage ){
76997        u8 eType;
76998        assert( nearby>0 );
76999        assert( pBt->autoVacuum );
77000        rc = ptrmapGet(pBt, nearby, &eType, 0);
77001        if( rc ) return rc;
77002        if( eType==PTRMAP_FREEPAGE ){
77003          searchList = 1;
77004        }
77005      }
77006    }else if( eMode==BTALLOC_LE ){
77007      searchList = 1;
77008    }
77009#endif
77010
77011    /* Decrement the free-list count by 1. Set iTrunk to the index of the
77012    ** first free-list trunk page. iPrevTrunk is initially 1.
77013    */
77014    rc = sqlite3PagerWrite(pPage1->pDbPage);
77015    if( rc ) return rc;
77016    put4byte(&pPage1->aData[36], n-1);
77017
77018    /* The code within this loop is run only once if the 'searchList' variable
77019    ** is not true. Otherwise, it runs once for each trunk-page on the
77020    ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
77021    ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
77022    */
77023    do {
77024      pPrevTrunk = pTrunk;
77025      if( pPrevTrunk ){
77026        /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
77027        ** is the page number of the next freelist trunk page in the list or
77028        ** zero if this is the last freelist trunk page. */
77029        iTrunk = get4byte(&pPrevTrunk->aData[0]);
77030      }else{
77031        /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
77032        ** stores the page number of the first page of the freelist, or zero if
77033        ** the freelist is empty. */
77034        iTrunk = get4byte(&pPage1->aData[32]);
77035      }
77036      testcase( iTrunk==mxPage );
77037      if( iTrunk>mxPage || nSearch++ > n ){
77038        rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
77039      }else{
77040        rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
77041      }
77042      if( rc ){
77043        pTrunk = 0;
77044        goto end_allocate_page;
77045      }
77046      assert( pTrunk!=0 );
77047      assert( pTrunk->aData!=0 );
77048      /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
77049      ** is the number of leaf page pointers to follow. */
77050      k = get4byte(&pTrunk->aData[4]);
77051      if( k==0 && !searchList ){
77052        /* The trunk has no leaves and the list is not being searched.
77053        ** So extract the trunk page itself and use it as the newly
77054        ** allocated page */
77055        assert( pPrevTrunk==0 );
77056        rc = sqlite3PagerWrite(pTrunk->pDbPage);
77057        if( rc ){
77058          goto end_allocate_page;
77059        }
77060        *pPgno = iTrunk;
77061        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
77062        *ppPage = pTrunk;
77063        pTrunk = 0;
77064        TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
77065      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
77066        /* Value of k is out of range.  Database corruption */
77067        rc = SQLITE_CORRUPT_PGNO(iTrunk);
77068        goto end_allocate_page;
77069#ifndef SQLITE_OMIT_AUTOVACUUM
77070      }else if( searchList
77071            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
77072      ){
77073        /* The list is being searched and this trunk page is the page
77074        ** to allocate, regardless of whether it has leaves.
77075        */
77076        *pPgno = iTrunk;
77077        *ppPage = pTrunk;
77078        searchList = 0;
77079        rc = sqlite3PagerWrite(pTrunk->pDbPage);
77080        if( rc ){
77081          goto end_allocate_page;
77082        }
77083        if( k==0 ){
77084          if( !pPrevTrunk ){
77085            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
77086          }else{
77087            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
77088            if( rc!=SQLITE_OK ){
77089              goto end_allocate_page;
77090            }
77091            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
77092          }
77093        }else{
77094          /* The trunk page is required by the caller but it contains
77095          ** pointers to free-list leaves. The first leaf becomes a trunk
77096          ** page in this case.
77097          */
77098          MemPage *pNewTrunk;
77099          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
77100          if( iNewTrunk>mxPage ){
77101            rc = SQLITE_CORRUPT_PGNO(iTrunk);
77102            goto end_allocate_page;
77103          }
77104          testcase( iNewTrunk==mxPage );
77105          rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
77106          if( rc!=SQLITE_OK ){
77107            goto end_allocate_page;
77108          }
77109          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
77110          if( rc!=SQLITE_OK ){
77111            releasePage(pNewTrunk);
77112            goto end_allocate_page;
77113          }
77114          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
77115          put4byte(&pNewTrunk->aData[4], k-1);
77116          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
77117          releasePage(pNewTrunk);
77118          if( !pPrevTrunk ){
77119            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
77120            put4byte(&pPage1->aData[32], iNewTrunk);
77121          }else{
77122            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
77123            if( rc ){
77124              goto end_allocate_page;
77125            }
77126            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
77127          }
77128        }
77129        pTrunk = 0;
77130        TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
77131#endif
77132      }else if( k>0 ){
77133        /* Extract a leaf from the trunk */
77134        u32 closest;
77135        Pgno iPage;
77136        unsigned char *aData = pTrunk->aData;
77137        if( nearby>0 ){
77138          u32 i;
77139          closest = 0;
77140          if( eMode==BTALLOC_LE ){
77141            for(i=0; i<k; i++){
77142              iPage = get4byte(&aData[8+i*4]);
77143              if( iPage<=nearby ){
77144                closest = i;
77145                break;
77146              }
77147            }
77148          }else{
77149            int dist;
77150            dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
77151            for(i=1; i<k; i++){
77152              int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
77153              if( d2<dist ){
77154                closest = i;
77155                dist = d2;
77156              }
77157            }
77158          }
77159        }else{
77160          closest = 0;
77161        }
77162
77163        iPage = get4byte(&aData[8+closest*4]);
77164        testcase( iPage==mxPage );
77165        if( iPage>mxPage || iPage<2 ){
77166          rc = SQLITE_CORRUPT_PGNO(iTrunk);
77167          goto end_allocate_page;
77168        }
77169        testcase( iPage==mxPage );
77170        if( !searchList
77171         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
77172        ){
77173          int noContent;
77174          *pPgno = iPage;
77175          TRACE(("ALLOCATE: %u was leaf %u of %u on trunk %u"
77176                 ": %u more free pages\n",
77177                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
77178          rc = sqlite3PagerWrite(pTrunk->pDbPage);
77179          if( rc ) goto end_allocate_page;
77180          if( closest<k-1 ){
77181            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
77182          }
77183          put4byte(&aData[4], k-1);
77184          noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
77185          rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
77186          if( rc==SQLITE_OK ){
77187            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
77188            if( rc!=SQLITE_OK ){
77189              releasePage(*ppPage);
77190              *ppPage = 0;
77191            }
77192          }
77193          searchList = 0;
77194        }
77195      }
77196      releasePage(pPrevTrunk);
77197      pPrevTrunk = 0;
77198    }while( searchList );
77199  }else{
77200    /* There are no pages on the freelist, so append a new page to the
77201    ** database image.
77202    **
77203    ** Normally, new pages allocated by this block can be requested from the
77204    ** pager layer with the 'no-content' flag set. This prevents the pager
77205    ** from trying to read the pages content from disk. However, if the
77206    ** current transaction has already run one or more incremental-vacuum
77207    ** steps, then the page we are about to allocate may contain content
77208    ** that is required in the event of a rollback. In this case, do
77209    ** not set the no-content flag. This causes the pager to load and journal
77210    ** the current page content before overwriting it.
77211    **
77212    ** Note that the pager will not actually attempt to load or journal
77213    ** content for any page that really does lie past the end of the database
77214    ** file on disk. So the effects of disabling the no-content optimization
77215    ** here are confined to those pages that lie between the end of the
77216    ** database image and the end of the database file.
77217    */
77218    int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
77219
77220    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
77221    if( rc ) return rc;
77222    pBt->nPage++;
77223    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
77224
77225#ifndef SQLITE_OMIT_AUTOVACUUM
77226    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
77227      /* If *pPgno refers to a pointer-map page, allocate two new pages
77228      ** at the end of the file instead of one. The first allocated page
77229      ** becomes a new pointer-map page, the second is used by the caller.
77230      */
77231      MemPage *pPg = 0;
77232      TRACE(("ALLOCATE: %u from end of file (pointer-map page)\n", pBt->nPage));
77233      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
77234      rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
77235      if( rc==SQLITE_OK ){
77236        rc = sqlite3PagerWrite(pPg->pDbPage);
77237        releasePage(pPg);
77238      }
77239      if( rc ) return rc;
77240      pBt->nPage++;
77241      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
77242    }
77243#endif
77244    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
77245    *pPgno = pBt->nPage;
77246
77247    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
77248    rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
77249    if( rc ) return rc;
77250    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
77251    if( rc!=SQLITE_OK ){
77252      releasePage(*ppPage);
77253      *ppPage = 0;
77254    }
77255    TRACE(("ALLOCATE: %u from end of file\n", *pPgno));
77256  }
77257
77258  assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
77259
77260end_allocate_page:
77261  releasePage(pTrunk);
77262  releasePage(pPrevTrunk);
77263  assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
77264  assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
77265  return rc;
77266}
77267
77268/*
77269** This function is used to add page iPage to the database file free-list.
77270** It is assumed that the page is not already a part of the free-list.
77271**
77272** The value passed as the second argument to this function is optional.
77273** If the caller happens to have a pointer to the MemPage object
77274** corresponding to page iPage handy, it may pass it as the second value.
77275** Otherwise, it may pass NULL.
77276**
77277** If a pointer to a MemPage object is passed as the second argument,
77278** its reference count is not altered by this function.
77279*/
77280static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
77281  MemPage *pTrunk = 0;                /* Free-list trunk page */
77282  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
77283  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
77284  MemPage *pPage;                     /* Page being freed. May be NULL. */
77285  int rc;                             /* Return Code */
77286  u32 nFree;                          /* Initial number of pages on free-list */
77287
77288  assert( sqlite3_mutex_held(pBt->mutex) );
77289  assert( CORRUPT_DB || iPage>1 );
77290  assert( !pMemPage || pMemPage->pgno==iPage );
77291
77292  if( iPage<2 || iPage>pBt->nPage ){
77293    return SQLITE_CORRUPT_BKPT;
77294  }
77295  if( pMemPage ){
77296    pPage = pMemPage;
77297    sqlite3PagerRef(pPage->pDbPage);
77298  }else{
77299    pPage = btreePageLookup(pBt, iPage);
77300  }
77301
77302  /* Increment the free page count on pPage1 */
77303  rc = sqlite3PagerWrite(pPage1->pDbPage);
77304  if( rc ) goto freepage_out;
77305  nFree = get4byte(&pPage1->aData[36]);
77306  put4byte(&pPage1->aData[36], nFree+1);
77307
77308  if( pBt->btsFlags & BTS_SECURE_DELETE ){
77309    /* If the secure_delete option is enabled, then
77310    ** always fully overwrite deleted information with zeros.
77311    */
77312    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
77313     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
77314    ){
77315      goto freepage_out;
77316    }
77317    memset(pPage->aData, 0, pPage->pBt->pageSize);
77318  }
77319
77320  /* If the database supports auto-vacuum, write an entry in the pointer-map
77321  ** to indicate that the page is free.
77322  */
77323  if( ISAUTOVACUUM(pBt) ){
77324    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
77325    if( rc ) goto freepage_out;
77326  }
77327
77328  /* Now manipulate the actual database free-list structure. There are two
77329  ** possibilities. If the free-list is currently empty, or if the first
77330  ** trunk page in the free-list is full, then this page will become a
77331  ** new free-list trunk page. Otherwise, it will become a leaf of the
77332  ** first trunk page in the current free-list. This block tests if it
77333  ** is possible to add the page as a new free-list leaf.
77334  */
77335  if( nFree!=0 ){
77336    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
77337
77338    iTrunk = get4byte(&pPage1->aData[32]);
77339    if( iTrunk>btreePagecount(pBt) ){
77340      rc = SQLITE_CORRUPT_BKPT;
77341      goto freepage_out;
77342    }
77343    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
77344    if( rc!=SQLITE_OK ){
77345      goto freepage_out;
77346    }
77347
77348    nLeaf = get4byte(&pTrunk->aData[4]);
77349    assert( pBt->usableSize>32 );
77350    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
77351      rc = SQLITE_CORRUPT_BKPT;
77352      goto freepage_out;
77353    }
77354    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
77355      /* In this case there is room on the trunk page to insert the page
77356      ** being freed as a new leaf.
77357      **
77358      ** Note that the trunk page is not really full until it contains
77359      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
77360      ** coded.  But due to a coding error in versions of SQLite prior to
77361      ** 3.6.0, databases with freelist trunk pages holding more than
77362      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
77363      ** to maintain backwards compatibility with older versions of SQLite,
77364      ** we will continue to restrict the number of entries to usableSize/4 - 8
77365      ** for now.  At some point in the future (once everyone has upgraded
77366      ** to 3.6.0 or later) we should consider fixing the conditional above
77367      ** to read "usableSize/4-2" instead of "usableSize/4-8".
77368      **
77369      ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
77370      ** avoid using the last six entries in the freelist trunk page array in
77371      ** order that database files created by newer versions of SQLite can be
77372      ** read by older versions of SQLite.
77373      */
77374      rc = sqlite3PagerWrite(pTrunk->pDbPage);
77375      if( rc==SQLITE_OK ){
77376        put4byte(&pTrunk->aData[4], nLeaf+1);
77377        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
77378        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
77379          sqlite3PagerDontWrite(pPage->pDbPage);
77380        }
77381        rc = btreeSetHasContent(pBt, iPage);
77382      }
77383      TRACE(("FREE-PAGE: %u leaf on trunk page %u\n",pPage->pgno,pTrunk->pgno));
77384      goto freepage_out;
77385    }
77386  }
77387
77388  /* If control flows to this point, then it was not possible to add the
77389  ** the page being freed as a leaf page of the first trunk in the free-list.
77390  ** Possibly because the free-list is empty, or possibly because the
77391  ** first trunk in the free-list is full. Either way, the page being freed
77392  ** will become the new first trunk page in the free-list.
77393  */
77394  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
77395    goto freepage_out;
77396  }
77397  rc = sqlite3PagerWrite(pPage->pDbPage);
77398  if( rc!=SQLITE_OK ){
77399    goto freepage_out;
77400  }
77401  put4byte(pPage->aData, iTrunk);
77402  put4byte(&pPage->aData[4], 0);
77403  put4byte(&pPage1->aData[32], iPage);
77404  TRACE(("FREE-PAGE: %u new trunk page replacing %u\n", pPage->pgno, iTrunk));
77405
77406freepage_out:
77407  if( pPage ){
77408    pPage->isInit = 0;
77409  }
77410  releasePage(pPage);
77411  releasePage(pTrunk);
77412  return rc;
77413}
77414static void freePage(MemPage *pPage, int *pRC){
77415  if( (*pRC)==SQLITE_OK ){
77416    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
77417  }
77418}
77419
77420/*
77421** Free the overflow pages associated with the given Cell.
77422*/
77423static SQLITE_NOINLINE int clearCellOverflow(
77424  MemPage *pPage,          /* The page that contains the Cell */
77425  unsigned char *pCell,    /* First byte of the Cell */
77426  CellInfo *pInfo          /* Size information about the cell */
77427){
77428  BtShared *pBt;
77429  Pgno ovflPgno;
77430  int rc;
77431  int nOvfl;
77432  u32 ovflPageSize;
77433
77434  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
77435  assert( pInfo->nLocal!=pInfo->nPayload );
77436  testcase( pCell + pInfo->nSize == pPage->aDataEnd );
77437  testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
77438  if( pCell + pInfo->nSize > pPage->aDataEnd ){
77439    /* Cell extends past end of page */
77440    return SQLITE_CORRUPT_PAGE(pPage);
77441  }
77442  ovflPgno = get4byte(pCell + pInfo->nSize - 4);
77443  pBt = pPage->pBt;
77444  assert( pBt->usableSize > 4 );
77445  ovflPageSize = pBt->usableSize - 4;
77446  nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
77447  assert( nOvfl>0 ||
77448    (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
77449  );
77450  while( nOvfl-- ){
77451    Pgno iNext = 0;
77452    MemPage *pOvfl = 0;
77453    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
77454      /* 0 is not a legal page number and page 1 cannot be an
77455      ** overflow page. Therefore if ovflPgno<2 or past the end of the
77456      ** file the database must be corrupt. */
77457      return SQLITE_CORRUPT_BKPT;
77458    }
77459    if( nOvfl ){
77460      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
77461      if( rc ) return rc;
77462    }
77463
77464    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
77465     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
77466    ){
77467      /* There is no reason any cursor should have an outstanding reference
77468      ** to an overflow page belonging to a cell that is being deleted/updated.
77469      ** So if there exists more than one reference to this page, then it
77470      ** must not really be an overflow page and the database must be corrupt.
77471      ** It is helpful to detect this before calling freePage2(), as
77472      ** freePage2() may zero the page contents if secure-delete mode is
77473      ** enabled. If this 'overflow' page happens to be a page that the
77474      ** caller is iterating through or using in some other way, this
77475      ** can be problematic.
77476      */
77477      rc = SQLITE_CORRUPT_BKPT;
77478    }else{
77479      rc = freePage2(pBt, pOvfl, ovflPgno);
77480    }
77481
77482    if( pOvfl ){
77483      sqlite3PagerUnref(pOvfl->pDbPage);
77484    }
77485    if( rc ) return rc;
77486    ovflPgno = iNext;
77487  }
77488  return SQLITE_OK;
77489}
77490
77491/* Call xParseCell to compute the size of a cell.  If the cell contains
77492** overflow, then invoke cellClearOverflow to clear out that overflow.
77493** Store the result code (SQLITE_OK or some error code) in rc.
77494**
77495** Implemented as macro to force inlining for performance.
77496*/
77497#define BTREE_CLEAR_CELL(rc, pPage, pCell, sInfo)   \
77498  pPage->xParseCell(pPage, pCell, &sInfo);          \
77499  if( sInfo.nLocal!=sInfo.nPayload ){               \
77500    rc = clearCellOverflow(pPage, pCell, &sInfo);   \
77501  }else{                                            \
77502    rc = SQLITE_OK;                                 \
77503  }
77504
77505
77506/*
77507** Create the byte sequence used to represent a cell on page pPage
77508** and write that byte sequence into pCell[].  Overflow pages are
77509** allocated and filled in as necessary.  The calling procedure
77510** is responsible for making sure sufficient space has been allocated
77511** for pCell[].
77512**
77513** Note that pCell does not necessary need to point to the pPage->aData
77514** area.  pCell might point to some temporary storage.  The cell will
77515** be constructed in this temporary area then copied into pPage->aData
77516** later.
77517*/
77518static int fillInCell(
77519  MemPage *pPage,                /* The page that contains the cell */
77520  unsigned char *pCell,          /* Complete text of the cell */
77521  const BtreePayload *pX,        /* Payload with which to construct the cell */
77522  int *pnSize                    /* Write cell size here */
77523){
77524  int nPayload;
77525  const u8 *pSrc;
77526  int nSrc, n, rc, mn;
77527  int spaceLeft;
77528  MemPage *pToRelease;
77529  unsigned char *pPrior;
77530  unsigned char *pPayload;
77531  BtShared *pBt;
77532  Pgno pgnoOvfl;
77533  int nHeader;
77534
77535  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
77536
77537  /* pPage is not necessarily writeable since pCell might be auxiliary
77538  ** buffer space that is separate from the pPage buffer area */
77539  assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
77540            || sqlite3PagerIswriteable(pPage->pDbPage) );
77541
77542  /* Fill in the header. */
77543  nHeader = pPage->childPtrSize;
77544  if( pPage->intKey ){
77545    nPayload = pX->nData + pX->nZero;
77546    pSrc = pX->pData;
77547    nSrc = pX->nData;
77548    assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
77549    nHeader += putVarint32(&pCell[nHeader], nPayload);
77550    nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
77551  }else{
77552    assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
77553    nSrc = nPayload = (int)pX->nKey;
77554    pSrc = pX->pKey;
77555    nHeader += putVarint32(&pCell[nHeader], nPayload);
77556  }
77557
77558  /* Fill in the payload */
77559  pPayload = &pCell[nHeader];
77560  if( nPayload<=pPage->maxLocal ){
77561    /* This is the common case where everything fits on the btree page
77562    ** and no overflow pages are required. */
77563    n = nHeader + nPayload;
77564    testcase( n==3 );
77565    testcase( n==4 );
77566    if( n<4 ){
77567      n = 4;
77568      pPayload[nPayload] = 0;
77569    }
77570    *pnSize = n;
77571    assert( nSrc<=nPayload );
77572    testcase( nSrc<nPayload );
77573    memcpy(pPayload, pSrc, nSrc);
77574    memset(pPayload+nSrc, 0, nPayload-nSrc);
77575    return SQLITE_OK;
77576  }
77577
77578  /* If we reach this point, it means that some of the content will need
77579  ** to spill onto overflow pages.
77580  */
77581  mn = pPage->minLocal;
77582  n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
77583  testcase( n==pPage->maxLocal );
77584  testcase( n==pPage->maxLocal+1 );
77585  if( n > pPage->maxLocal ) n = mn;
77586  spaceLeft = n;
77587  *pnSize = n + nHeader + 4;
77588  pPrior = &pCell[nHeader+n];
77589  pToRelease = 0;
77590  pgnoOvfl = 0;
77591  pBt = pPage->pBt;
77592
77593  /* At this point variables should be set as follows:
77594  **
77595  **   nPayload           Total payload size in bytes
77596  **   pPayload           Begin writing payload here
77597  **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
77598  **                      that means content must spill into overflow pages.
77599  **   *pnSize            Size of the local cell (not counting overflow pages)
77600  **   pPrior             Where to write the pgno of the first overflow page
77601  **
77602  ** Use a call to btreeParseCellPtr() to verify that the values above
77603  ** were computed correctly.
77604  */
77605#ifdef SQLITE_DEBUG
77606  {
77607    CellInfo info;
77608    pPage->xParseCell(pPage, pCell, &info);
77609    assert( nHeader==(int)(info.pPayload - pCell) );
77610    assert( info.nKey==pX->nKey );
77611    assert( *pnSize == info.nSize );
77612    assert( spaceLeft == info.nLocal );
77613  }
77614#endif
77615
77616  /* Write the payload into the local Cell and any extra into overflow pages */
77617  while( 1 ){
77618    n = nPayload;
77619    if( n>spaceLeft ) n = spaceLeft;
77620
77621    /* If pToRelease is not zero than pPayload points into the data area
77622    ** of pToRelease.  Make sure pToRelease is still writeable. */
77623    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
77624
77625    /* If pPayload is part of the data area of pPage, then make sure pPage
77626    ** is still writeable */
77627    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
77628            || sqlite3PagerIswriteable(pPage->pDbPage) );
77629
77630    if( nSrc>=n ){
77631      memcpy(pPayload, pSrc, n);
77632    }else if( nSrc>0 ){
77633      n = nSrc;
77634      memcpy(pPayload, pSrc, n);
77635    }else{
77636      memset(pPayload, 0, n);
77637    }
77638    nPayload -= n;
77639    if( nPayload<=0 ) break;
77640    pPayload += n;
77641    pSrc += n;
77642    nSrc -= n;
77643    spaceLeft -= n;
77644    if( spaceLeft==0 ){
77645      MemPage *pOvfl = 0;
77646#ifndef SQLITE_OMIT_AUTOVACUUM
77647      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
77648      if( pBt->autoVacuum ){
77649        do{
77650          pgnoOvfl++;
77651        } while(
77652          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
77653        );
77654      }
77655#endif
77656      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
77657#ifndef SQLITE_OMIT_AUTOVACUUM
77658      /* If the database supports auto-vacuum, and the second or subsequent
77659      ** overflow page is being allocated, add an entry to the pointer-map
77660      ** for that page now.
77661      **
77662      ** If this is the first overflow page, then write a partial entry
77663      ** to the pointer-map. If we write nothing to this pointer-map slot,
77664      ** then the optimistic overflow chain processing in clearCell()
77665      ** may misinterpret the uninitialized values and delete the
77666      ** wrong pages from the database.
77667      */
77668      if( pBt->autoVacuum && rc==SQLITE_OK ){
77669        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
77670        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
77671        if( rc ){
77672          releasePage(pOvfl);
77673        }
77674      }
77675#endif
77676      if( rc ){
77677        releasePage(pToRelease);
77678        return rc;
77679      }
77680
77681      /* If pToRelease is not zero than pPrior points into the data area
77682      ** of pToRelease.  Make sure pToRelease is still writeable. */
77683      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
77684
77685      /* If pPrior is part of the data area of pPage, then make sure pPage
77686      ** is still writeable */
77687      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
77688            || sqlite3PagerIswriteable(pPage->pDbPage) );
77689
77690      put4byte(pPrior, pgnoOvfl);
77691      releasePage(pToRelease);
77692      pToRelease = pOvfl;
77693      pPrior = pOvfl->aData;
77694      put4byte(pPrior, 0);
77695      pPayload = &pOvfl->aData[4];
77696      spaceLeft = pBt->usableSize - 4;
77697    }
77698  }
77699  releasePage(pToRelease);
77700  return SQLITE_OK;
77701}
77702
77703/*
77704** Remove the i-th cell from pPage.  This routine effects pPage only.
77705** The cell content is not freed or deallocated.  It is assumed that
77706** the cell content has been copied someplace else.  This routine just
77707** removes the reference to the cell from pPage.
77708**
77709** "sz" must be the number of bytes in the cell.
77710*/
77711static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
77712  u32 pc;         /* Offset to cell content of cell being deleted */
77713  u8 *data;       /* pPage->aData */
77714  u8 *ptr;        /* Used to move bytes around within data[] */
77715  int rc;         /* The return code */
77716  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
77717
77718  if( *pRC ) return;
77719  assert( idx>=0 );
77720  assert( idx<pPage->nCell );
77721  assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
77722  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
77723  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
77724  assert( pPage->nFree>=0 );
77725  data = pPage->aData;
77726  ptr = &pPage->aCellIdx[2*idx];
77727  assert( pPage->pBt->usableSize > (u32)(ptr-data) );
77728  pc = get2byte(ptr);
77729  hdr = pPage->hdrOffset;
77730  testcase( pc==(u32)get2byte(&data[hdr+5]) );
77731  testcase( pc+sz==pPage->pBt->usableSize );
77732  if( pc+sz > pPage->pBt->usableSize ){
77733    *pRC = SQLITE_CORRUPT_BKPT;
77734    return;
77735  }
77736  rc = freeSpace(pPage, pc, sz);
77737  if( rc ){
77738    *pRC = rc;
77739    return;
77740  }
77741  pPage->nCell--;
77742  if( pPage->nCell==0 ){
77743    memset(&data[hdr+1], 0, 4);
77744    data[hdr+7] = 0;
77745    put2byte(&data[hdr+5], pPage->pBt->usableSize);
77746    pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
77747                       - pPage->childPtrSize - 8;
77748  }else{
77749    memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
77750    put2byte(&data[hdr+3], pPage->nCell);
77751    pPage->nFree += 2;
77752  }
77753}
77754
77755/*
77756** Insert a new cell on pPage at cell index "i".  pCell points to the
77757** content of the cell.
77758**
77759** If the cell content will fit on the page, then put it there.  If it
77760** will not fit, then make a copy of the cell content into pTemp if
77761** pTemp is not null.  Regardless of pTemp, allocate a new entry
77762** in pPage->apOvfl[] and make it point to the cell content (either
77763** in pTemp or the original pCell) and also record its index.
77764** Allocating a new entry in pPage->aCell[] implies that
77765** pPage->nOverflow is incremented.
77766**
77767** The insertCellFast() routine below works exactly the same as
77768** insertCell() except that it lacks the pTemp and iChild parameters
77769** which are assumed zero.  Other than that, the two routines are the
77770** same.
77771**
77772** Fixes or enhancements to this routine should be reflected in
77773** insertCellFast()!
77774*/
77775static int insertCell(
77776  MemPage *pPage,   /* Page into which we are copying */
77777  int i,            /* New cell becomes the i-th cell of the page */
77778  u8 *pCell,        /* Content of the new cell */
77779  int sz,           /* Bytes of content in pCell */
77780  u8 *pTemp,        /* Temp storage space for pCell, if needed */
77781  Pgno iChild       /* If non-zero, replace first 4 bytes with this value */
77782){
77783  int idx = 0;      /* Where to write new cell content in data[] */
77784  int j;            /* Loop counter */
77785  u8 *data;         /* The content of the whole page */
77786  u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
77787
77788  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
77789  assert( MX_CELL(pPage->pBt)<=10921 );
77790  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
77791  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
77792  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
77793  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
77794  assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
77795  assert( pPage->nFree>=0 );
77796  assert( iChild>0 );
77797  if( pPage->nOverflow || sz+2>pPage->nFree ){
77798    if( pTemp ){
77799      memcpy(pTemp, pCell, sz);
77800      pCell = pTemp;
77801    }
77802    put4byte(pCell, iChild);
77803    j = pPage->nOverflow++;
77804    /* Comparison against ArraySize-1 since we hold back one extra slot
77805    ** as a contingency.  In other words, never need more than 3 overflow
77806    ** slots but 4 are allocated, just to be safe. */
77807    assert( j < ArraySize(pPage->apOvfl)-1 );
77808    pPage->apOvfl[j] = pCell;
77809    pPage->aiOvfl[j] = (u16)i;
77810
77811    /* When multiple overflows occur, they are always sequential and in
77812    ** sorted order.  This invariants arise because multiple overflows can
77813    ** only occur when inserting divider cells into the parent page during
77814    ** balancing, and the dividers are adjacent and sorted.
77815    */
77816    assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
77817    assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
77818  }else{
77819    int rc = sqlite3PagerWrite(pPage->pDbPage);
77820    if( NEVER(rc!=SQLITE_OK) ){
77821      return rc;
77822    }
77823    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
77824    data = pPage->aData;
77825    assert( &data[pPage->cellOffset]==pPage->aCellIdx );
77826    rc = allocateSpace(pPage, sz, &idx);
77827    if( rc ){ return rc; }
77828    /* The allocateSpace() routine guarantees the following properties
77829    ** if it returns successfully */
77830    assert( idx >= 0 );
77831    assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
77832    assert( idx+sz <= (int)pPage->pBt->usableSize );
77833    pPage->nFree -= (u16)(2 + sz);
77834    /* In a corrupt database where an entry in the cell index section of
77835    ** a btree page has a value of 3 or less, the pCell value might point
77836    ** as many as 4 bytes in front of the start of the aData buffer for
77837    ** the source page.  Make sure this does not cause problems by not
77838    ** reading the first 4 bytes */
77839    memcpy(&data[idx+4], pCell+4, sz-4);
77840    put4byte(&data[idx], iChild);
77841    pIns = pPage->aCellIdx + i*2;
77842    memmove(pIns+2, pIns, 2*(pPage->nCell - i));
77843    put2byte(pIns, idx);
77844    pPage->nCell++;
77845    /* increment the cell count */
77846    if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
77847    assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
77848#ifndef SQLITE_OMIT_AUTOVACUUM
77849    if( pPage->pBt->autoVacuum ){
77850      int rc2 = SQLITE_OK;
77851      /* The cell may contain a pointer to an overflow page. If so, write
77852      ** the entry for the overflow page into the pointer map.
77853      */
77854      ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2);
77855      if( rc2 ) return rc2;
77856    }
77857#endif
77858  }
77859  return SQLITE_OK;
77860}
77861
77862/*
77863** This variant of insertCell() assumes that the pTemp and iChild
77864** parameters are both zero.  Use this variant in sqlite3BtreeInsert()
77865** for performance improvement, and also so that this variant is only
77866** called from that one place, and is thus inlined, and thus runs must
77867** faster.
77868**
77869** Fixes or enhancements to this routine should be reflected into
77870** the insertCell() routine.
77871*/
77872static int insertCellFast(
77873  MemPage *pPage,   /* Page into which we are copying */
77874  int i,            /* New cell becomes the i-th cell of the page */
77875  u8 *pCell,        /* Content of the new cell */
77876  int sz            /* Bytes of content in pCell */
77877){
77878  int idx = 0;      /* Where to write new cell content in data[] */
77879  int j;            /* Loop counter */
77880  u8 *data;         /* The content of the whole page */
77881  u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
77882
77883  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
77884  assert( MX_CELL(pPage->pBt)<=10921 );
77885  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
77886  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
77887  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
77888  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
77889  assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
77890  assert( pPage->nFree>=0 );
77891  assert( pPage->nOverflow==0 );
77892  if( sz+2>pPage->nFree ){
77893    j = pPage->nOverflow++;
77894    /* Comparison against ArraySize-1 since we hold back one extra slot
77895    ** as a contingency.  In other words, never need more than 3 overflow
77896    ** slots but 4 are allocated, just to be safe. */
77897    assert( j < ArraySize(pPage->apOvfl)-1 );
77898    pPage->apOvfl[j] = pCell;
77899    pPage->aiOvfl[j] = (u16)i;
77900
77901    /* When multiple overflows occur, they are always sequential and in
77902    ** sorted order.  This invariants arise because multiple overflows can
77903    ** only occur when inserting divider cells into the parent page during
77904    ** balancing, and the dividers are adjacent and sorted.
77905    */
77906    assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
77907    assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
77908  }else{
77909    int rc = sqlite3PagerWrite(pPage->pDbPage);
77910    if( rc!=SQLITE_OK ){
77911      return rc;
77912    }
77913    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
77914    data = pPage->aData;
77915    assert( &data[pPage->cellOffset]==pPage->aCellIdx );
77916    rc = allocateSpace(pPage, sz, &idx);
77917    if( rc ){ return rc; }
77918    /* The allocateSpace() routine guarantees the following properties
77919    ** if it returns successfully */
77920    assert( idx >= 0 );
77921    assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
77922    assert( idx+sz <= (int)pPage->pBt->usableSize );
77923    pPage->nFree -= (u16)(2 + sz);
77924    memcpy(&data[idx], pCell, sz);
77925    pIns = pPage->aCellIdx + i*2;
77926    memmove(pIns+2, pIns, 2*(pPage->nCell - i));
77927    put2byte(pIns, idx);
77928    pPage->nCell++;
77929    /* increment the cell count */
77930    if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
77931    assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
77932#ifndef SQLITE_OMIT_AUTOVACUUM
77933    if( pPage->pBt->autoVacuum ){
77934      int rc2 = SQLITE_OK;
77935      /* The cell may contain a pointer to an overflow page. If so, write
77936      ** the entry for the overflow page into the pointer map.
77937      */
77938      ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2);
77939      if( rc2 ) return rc2;
77940    }
77941#endif
77942  }
77943  return SQLITE_OK;
77944}
77945
77946/*
77947** The following parameters determine how many adjacent pages get involved
77948** in a balancing operation.  NN is the number of neighbors on either side
77949** of the page that participate in the balancing operation.  NB is the
77950** total number of pages that participate, including the target page and
77951** NN neighbors on either side.
77952**
77953** The minimum value of NN is 1 (of course).  Increasing NN above 1
77954** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
77955** in exchange for a larger degradation in INSERT and UPDATE performance.
77956** The value of NN appears to give the best results overall.
77957**
77958** (Later:) The description above makes it seem as if these values are
77959** tunable - as if you could change them and recompile and it would all work.
77960** But that is unlikely.  NB has been 3 since the inception of SQLite and
77961** we have never tested any other value.
77962*/
77963#define NN 1             /* Number of neighbors on either side of pPage */
77964#define NB 3             /* (NN*2+1): Total pages involved in the balance */
77965
77966/*
77967** A CellArray object contains a cache of pointers and sizes for a
77968** consecutive sequence of cells that might be held on multiple pages.
77969**
77970** The cells in this array are the divider cell or cells from the pParent
77971** page plus up to three child pages.  There are a total of nCell cells.
77972**
77973** pRef is a pointer to one of the pages that contributes cells.  This is
77974** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
77975** which should be common to all pages that contribute cells to this array.
77976**
77977** apCell[] and szCell[] hold, respectively, pointers to the start of each
77978** cell and the size of each cell.  Some of the apCell[] pointers might refer
77979** to overflow cells.  In other words, some apCel[] pointers might not point
77980** to content area of the pages.
77981**
77982** A szCell[] of zero means the size of that cell has not yet been computed.
77983**
77984** The cells come from as many as four different pages:
77985**
77986**             -----------
77987**             | Parent  |
77988**             -----------
77989**            /     |     \
77990**           /      |      \
77991**  ---------   ---------   ---------
77992**  |Child-1|   |Child-2|   |Child-3|
77993**  ---------   ---------   ---------
77994**
77995** The order of cells is in the array is for an index btree is:
77996**
77997**       1.  All cells from Child-1 in order
77998**       2.  The first divider cell from Parent
77999**       3.  All cells from Child-2 in order
78000**       4.  The second divider cell from Parent
78001**       5.  All cells from Child-3 in order
78002**
78003** For a table-btree (with rowids) the items 2 and 4 are empty because
78004** content exists only in leaves and there are no divider cells.
78005**
78006** For an index btree, the apEnd[] array holds pointer to the end of page
78007** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
78008** respectively. The ixNx[] array holds the number of cells contained in
78009** each of these 5 stages, and all stages to the left.  Hence:
78010**
78011**    ixNx[0] = Number of cells in Child-1.
78012**    ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
78013**    ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
78014**    ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
78015**    ixNx[4] = Total number of cells.
78016**
78017** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
78018** are used and they point to the leaf pages only, and the ixNx value are:
78019**
78020**    ixNx[0] = Number of cells in Child-1.
78021**    ixNx[1] = Number of cells in Child-1 and Child-2.
78022**    ixNx[2] = Total number of cells.
78023**
78024** Sometimes when deleting, a child page can have zero cells.  In those
78025** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
78026** entries, shift down.  The end result is that each ixNx[] entry should
78027** be larger than the previous
78028*/
78029typedef struct CellArray CellArray;
78030struct CellArray {
78031  int nCell;              /* Number of cells in apCell[] */
78032  MemPage *pRef;          /* Reference page */
78033  u8 **apCell;            /* All cells begin balanced */
78034  u16 *szCell;            /* Local size of all cells in apCell[] */
78035  u8 *apEnd[NB*2];        /* MemPage.aDataEnd values */
78036  int ixNx[NB*2];         /* Index of at which we move to the next apEnd[] */
78037};
78038
78039/*
78040** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
78041** computed.
78042*/
78043static void populateCellCache(CellArray *p, int idx, int N){
78044  MemPage *pRef = p->pRef;
78045  u16 *szCell = p->szCell;
78046  assert( idx>=0 && idx+N<=p->nCell );
78047  while( N>0 ){
78048    assert( p->apCell[idx]!=0 );
78049    if( szCell[idx]==0 ){
78050      szCell[idx] = pRef->xCellSize(pRef, p->apCell[idx]);
78051    }else{
78052      assert( CORRUPT_DB ||
78053              szCell[idx]==pRef->xCellSize(pRef, p->apCell[idx]) );
78054    }
78055    idx++;
78056    N--;
78057  }
78058}
78059
78060/*
78061** Return the size of the Nth element of the cell array
78062*/
78063static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
78064  assert( N>=0 && N<p->nCell );
78065  assert( p->szCell[N]==0 );
78066  p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
78067  return p->szCell[N];
78068}
78069static u16 cachedCellSize(CellArray *p, int N){
78070  assert( N>=0 && N<p->nCell );
78071  if( p->szCell[N] ) return p->szCell[N];
78072  return computeCellSize(p, N);
78073}
78074
78075/*
78076** Array apCell[] contains pointers to nCell b-tree page cells. The
78077** szCell[] array contains the size in bytes of each cell. This function
78078** replaces the current contents of page pPg with the contents of the cell
78079** array.
78080**
78081** Some of the cells in apCell[] may currently be stored in pPg. This
78082** function works around problems caused by this by making a copy of any
78083** such cells before overwriting the page data.
78084**
78085** The MemPage.nFree field is invalidated by this function. It is the
78086** responsibility of the caller to set it correctly.
78087*/
78088static int rebuildPage(
78089  CellArray *pCArray,             /* Content to be added to page pPg */
78090  int iFirst,                     /* First cell in pCArray to use */
78091  int nCell,                      /* Final number of cells on page */
78092  MemPage *pPg                    /* The page to be reconstructed */
78093){
78094  const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
78095  u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
78096  const int usableSize = pPg->pBt->usableSize;
78097  u8 * const pEnd = &aData[usableSize];
78098  int i = iFirst;                 /* Which cell to copy from pCArray*/
78099  u32 j;                          /* Start of cell content area */
78100  int iEnd = i+nCell;             /* Loop terminator */
78101  u8 *pCellptr = pPg->aCellIdx;
78102  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
78103  u8 *pData;
78104  int k;                          /* Current slot in pCArray->apEnd[] */
78105  u8 *pSrcEnd;                    /* Current pCArray->apEnd[k] value */
78106
78107  assert( nCell>0 );
78108  assert( i<iEnd );
78109  j = get2byte(&aData[hdr+5]);
78110  if( j>(u32)usableSize ){ j = 0; }
78111  memcpy(&pTmp[j], &aData[j], usableSize - j);
78112
78113  for(k=0; ALWAYS(k<NB*2) && pCArray->ixNx[k]<=i; k++){}
78114  pSrcEnd = pCArray->apEnd[k];
78115
78116  pData = pEnd;
78117  while( 1/*exit by break*/ ){
78118    u8 *pCell = pCArray->apCell[i];
78119    u16 sz = pCArray->szCell[i];
78120    assert( sz>0 );
78121    if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){
78122      if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
78123      pCell = &pTmp[pCell - aData];
78124    }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
78125           && (uptr)(pCell)<(uptr)pSrcEnd
78126    ){
78127      return SQLITE_CORRUPT_BKPT;
78128    }
78129
78130    pData -= sz;
78131    put2byte(pCellptr, (pData - aData));
78132    pCellptr += 2;
78133    if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
78134    memmove(pData, pCell, sz);
78135    assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
78136    i++;
78137    if( i>=iEnd ) break;
78138    if( pCArray->ixNx[k]<=i ){
78139      k++;
78140      pSrcEnd = pCArray->apEnd[k];
78141    }
78142  }
78143
78144  /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
78145  pPg->nCell = nCell;
78146  pPg->nOverflow = 0;
78147
78148  put2byte(&aData[hdr+1], 0);
78149  put2byte(&aData[hdr+3], pPg->nCell);
78150  put2byte(&aData[hdr+5], pData - aData);
78151  aData[hdr+7] = 0x00;
78152  return SQLITE_OK;
78153}
78154
78155/*
78156** The pCArray objects contains pointers to b-tree cells and the cell sizes.
78157** This function attempts to add the cells stored in the array to page pPg.
78158** If it cannot (because the page needs to be defragmented before the cells
78159** will fit), non-zero is returned. Otherwise, if the cells are added
78160** successfully, zero is returned.
78161**
78162** Argument pCellptr points to the first entry in the cell-pointer array
78163** (part of page pPg) to populate. After cell apCell[0] is written to the
78164** page body, a 16-bit offset is written to pCellptr. And so on, for each
78165** cell in the array. It is the responsibility of the caller to ensure
78166** that it is safe to overwrite this part of the cell-pointer array.
78167**
78168** When this function is called, *ppData points to the start of the
78169** content area on page pPg. If the size of the content area is extended,
78170** *ppData is updated to point to the new start of the content area
78171** before returning.
78172**
78173** Finally, argument pBegin points to the byte immediately following the
78174** end of the space required by this page for the cell-pointer area (for
78175** all cells - not just those inserted by the current call). If the content
78176** area must be extended to before this point in order to accommodate all
78177** cells in apCell[], then the cells do not fit and non-zero is returned.
78178*/
78179static int pageInsertArray(
78180  MemPage *pPg,                   /* Page to add cells to */
78181  u8 *pBegin,                     /* End of cell-pointer array */
78182  u8 **ppData,                    /* IN/OUT: Page content-area pointer */
78183  u8 *pCellptr,                   /* Pointer to cell-pointer area */
78184  int iFirst,                     /* Index of first cell to add */
78185  int nCell,                      /* Number of cells to add to pPg */
78186  CellArray *pCArray              /* Array of cells */
78187){
78188  int i = iFirst;                 /* Loop counter - cell index to insert */
78189  u8 *aData = pPg->aData;         /* Complete page */
78190  u8 *pData = *ppData;            /* Content area.  A subset of aData[] */
78191  int iEnd = iFirst + nCell;      /* End of loop. One past last cell to ins */
78192  int k;                          /* Current slot in pCArray->apEnd[] */
78193  u8 *pEnd;                       /* Maximum extent of cell data */
78194  assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
78195  if( iEnd<=iFirst ) return 0;
78196  for(k=0; ALWAYS(k<NB*2) && pCArray->ixNx[k]<=i ; k++){}
78197  pEnd = pCArray->apEnd[k];
78198  while( 1 /*Exit by break*/ ){
78199    int sz, rc;
78200    u8 *pSlot;
78201    assert( pCArray->szCell[i]!=0 );
78202    sz = pCArray->szCell[i];
78203    if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
78204      if( (pData - pBegin)<sz ) return 1;
78205      pData -= sz;
78206      pSlot = pData;
78207    }
78208    /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
78209    ** database.  But they might for a corrupt database.  Hence use memmove()
78210    ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
78211    assert( (pSlot+sz)<=pCArray->apCell[i]
78212         || pSlot>=(pCArray->apCell[i]+sz)
78213         || CORRUPT_DB );
78214    if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
78215     && (uptr)(pCArray->apCell[i])<(uptr)pEnd
78216    ){
78217      assert( CORRUPT_DB );
78218      (void)SQLITE_CORRUPT_BKPT;
78219      return 1;
78220    }
78221    memmove(pSlot, pCArray->apCell[i], sz);
78222    put2byte(pCellptr, (pSlot - aData));
78223    pCellptr += 2;
78224    i++;
78225    if( i>=iEnd ) break;
78226    if( pCArray->ixNx[k]<=i ){
78227      k++;
78228      pEnd = pCArray->apEnd[k];
78229    }
78230  }
78231  *ppData = pData;
78232  return 0;
78233}
78234
78235/*
78236** The pCArray object contains pointers to b-tree cells and their sizes.
78237**
78238** This function adds the space associated with each cell in the array
78239** that is currently stored within the body of pPg to the pPg free-list.
78240** The cell-pointers and other fields of the page are not updated.
78241**
78242** This function returns the total number of cells added to the free-list.
78243*/
78244static int pageFreeArray(
78245  MemPage *pPg,                   /* Page to edit */
78246  int iFirst,                     /* First cell to delete */
78247  int nCell,                      /* Cells to delete */
78248  CellArray *pCArray              /* Array of cells */
78249){
78250  u8 * const aData = pPg->aData;
78251  u8 * const pEnd = &aData[pPg->pBt->usableSize];
78252  u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
78253  int nRet = 0;
78254  int i, j;
78255  int iEnd = iFirst + nCell;
78256  int nFree = 0;
78257  int aOfst[10];
78258  int aAfter[10];
78259
78260  for(i=iFirst; i<iEnd; i++){
78261    u8 *pCell = pCArray->apCell[i];
78262    if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
78263      int sz;
78264      int iAfter;
78265      int iOfst;
78266      /* No need to use cachedCellSize() here.  The sizes of all cells that
78267      ** are to be freed have already been computing while deciding which
78268      ** cells need freeing */
78269      sz = pCArray->szCell[i];  assert( sz>0 );
78270      iOfst = (u16)(pCell - aData);
78271      iAfter = iOfst+sz;
78272      for(j=0; j<nFree; j++){
78273        if( aOfst[j]==iAfter ){
78274          aOfst[j] = iOfst;
78275          break;
78276        }else if( aAfter[j]==iOfst ){
78277          aAfter[j] = iAfter;
78278          break;
78279        }
78280      }
78281      if( j>=nFree ){
78282        if( nFree>=(int)(sizeof(aOfst)/sizeof(aOfst[0])) ){
78283          for(j=0; j<nFree; j++){
78284            freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
78285          }
78286          nFree = 0;
78287        }
78288        aOfst[nFree] = iOfst;
78289        aAfter[nFree] = iAfter;
78290        if( &aData[iAfter]>pEnd ) return 0;
78291        nFree++;
78292      }
78293      nRet++;
78294    }
78295  }
78296  for(j=0; j<nFree; j++){
78297    freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
78298  }
78299  return nRet;
78300}
78301
78302/*
78303** pCArray contains pointers to and sizes of all cells in the page being
78304** balanced.  The current page, pPg, has pPg->nCell cells starting with
78305** pCArray->apCell[iOld].  After balancing, this page should hold nNew cells
78306** starting at apCell[iNew].
78307**
78308** This routine makes the necessary adjustments to pPg so that it contains
78309** the correct cells after being balanced.
78310**
78311** The pPg->nFree field is invalid when this function returns. It is the
78312** responsibility of the caller to set it correctly.
78313*/
78314static int editPage(
78315  MemPage *pPg,                   /* Edit this page */
78316  int iOld,                       /* Index of first cell currently on page */
78317  int iNew,                       /* Index of new first cell on page */
78318  int nNew,                       /* Final number of cells on page */
78319  CellArray *pCArray              /* Array of cells and sizes */
78320){
78321  u8 * const aData = pPg->aData;
78322  const int hdr = pPg->hdrOffset;
78323  u8 *pBegin = &pPg->aCellIdx[nNew * 2];
78324  int nCell = pPg->nCell;       /* Cells stored on pPg */
78325  u8 *pData;
78326  u8 *pCellptr;
78327  int i;
78328  int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
78329  int iNewEnd = iNew + nNew;
78330
78331#ifdef SQLITE_DEBUG
78332  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
78333  memcpy(pTmp, aData, pPg->pBt->usableSize);
78334#endif
78335
78336  /* Remove cells from the start and end of the page */
78337  assert( nCell>=0 );
78338  if( iOld<iNew ){
78339    int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
78340    if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
78341    memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
78342    nCell -= nShift;
78343  }
78344  if( iNewEnd < iOldEnd ){
78345    int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
78346    assert( nCell>=nTail );
78347    nCell -= nTail;
78348  }
78349
78350  pData = &aData[get2byte(&aData[hdr+5])];
78351  if( pData<pBegin ) goto editpage_fail;
78352  if( NEVER(pData>pPg->aDataEnd) ) goto editpage_fail;
78353
78354  /* Add cells to the start of the page */
78355  if( iNew<iOld ){
78356    int nAdd = MIN(nNew,iOld-iNew);
78357    assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
78358    assert( nAdd>=0 );
78359    pCellptr = pPg->aCellIdx;
78360    memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
78361    if( pageInsertArray(
78362          pPg, pBegin, &pData, pCellptr,
78363          iNew, nAdd, pCArray
78364    ) ) goto editpage_fail;
78365    nCell += nAdd;
78366  }
78367
78368  /* Add any overflow cells */
78369  for(i=0; i<pPg->nOverflow; i++){
78370    int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
78371    if( iCell>=0 && iCell<nNew ){
78372      pCellptr = &pPg->aCellIdx[iCell * 2];
78373      if( nCell>iCell ){
78374        memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
78375      }
78376      nCell++;
78377      cachedCellSize(pCArray, iCell+iNew);
78378      if( pageInsertArray(
78379            pPg, pBegin, &pData, pCellptr,
78380            iCell+iNew, 1, pCArray
78381      ) ) goto editpage_fail;
78382    }
78383  }
78384
78385  /* Append cells to the end of the page */
78386  assert( nCell>=0 );
78387  pCellptr = &pPg->aCellIdx[nCell*2];
78388  if( pageInsertArray(
78389        pPg, pBegin, &pData, pCellptr,
78390        iNew+nCell, nNew-nCell, pCArray
78391  ) ) goto editpage_fail;
78392
78393  pPg->nCell = nNew;
78394  pPg->nOverflow = 0;
78395
78396  put2byte(&aData[hdr+3], pPg->nCell);
78397  put2byte(&aData[hdr+5], pData - aData);
78398
78399#ifdef SQLITE_DEBUG
78400  for(i=0; i<nNew && !CORRUPT_DB; i++){
78401    u8 *pCell = pCArray->apCell[i+iNew];
78402    int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
78403    if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
78404      pCell = &pTmp[pCell - aData];
78405    }
78406    assert( 0==memcmp(pCell, &aData[iOff],
78407            pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
78408  }
78409#endif
78410
78411  return SQLITE_OK;
78412 editpage_fail:
78413  /* Unable to edit this page. Rebuild it from scratch instead. */
78414  if( nNew<1 ) return SQLITE_CORRUPT_BKPT;
78415  populateCellCache(pCArray, iNew, nNew);
78416  return rebuildPage(pCArray, iNew, nNew, pPg);
78417}
78418
78419
78420#ifndef SQLITE_OMIT_QUICKBALANCE
78421/*
78422** This version of balance() handles the common special case where
78423** a new entry is being inserted on the extreme right-end of the
78424** tree, in other words, when the new entry will become the largest
78425** entry in the tree.
78426**
78427** Instead of trying to balance the 3 right-most leaf pages, just add
78428** a new page to the right-hand side and put the one new entry in
78429** that page.  This leaves the right side of the tree somewhat
78430** unbalanced.  But odds are that we will be inserting new entries
78431** at the end soon afterwards so the nearly empty page will quickly
78432** fill up.  On average.
78433**
78434** pPage is the leaf page which is the right-most page in the tree.
78435** pParent is its parent.  pPage must have a single overflow entry
78436** which is also the right-most entry on the page.
78437**
78438** The pSpace buffer is used to store a temporary copy of the divider
78439** cell that will be inserted into pParent. Such a cell consists of a 4
78440** byte page number followed by a variable length integer. In other
78441** words, at most 13 bytes. Hence the pSpace buffer must be at
78442** least 13 bytes in size.
78443*/
78444static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
78445  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
78446  MemPage *pNew;                       /* Newly allocated page */
78447  int rc;                              /* Return Code */
78448  Pgno pgnoNew;                        /* Page number of pNew */
78449
78450  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
78451  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
78452  assert( pPage->nOverflow==1 );
78453
78454  if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;  /* dbfuzz001.test */
78455  assert( pPage->nFree>=0 );
78456  assert( pParent->nFree>=0 );
78457
78458  /* Allocate a new page. This page will become the right-sibling of
78459  ** pPage. Make the parent page writable, so that the new divider cell
78460  ** may be inserted. If both these operations are successful, proceed.
78461  */
78462  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
78463
78464  if( rc==SQLITE_OK ){
78465
78466    u8 *pOut = &pSpace[4];
78467    u8 *pCell = pPage->apOvfl[0];
78468    u16 szCell = pPage->xCellSize(pPage, pCell);
78469    u8 *pStop;
78470    CellArray b;
78471
78472    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
78473    assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
78474    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
78475    b.nCell = 1;
78476    b.pRef = pPage;
78477    b.apCell = &pCell;
78478    b.szCell = &szCell;
78479    b.apEnd[0] = pPage->aDataEnd;
78480    b.ixNx[0] = 2;
78481    rc = rebuildPage(&b, 0, 1, pNew);
78482    if( NEVER(rc) ){
78483      releasePage(pNew);
78484      return rc;
78485    }
78486    pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
78487
78488    /* If this is an auto-vacuum database, update the pointer map
78489    ** with entries for the new page, and any pointer from the
78490    ** cell on the page to an overflow page. If either of these
78491    ** operations fails, the return code is set, but the contents
78492    ** of the parent page are still manipulated by the code below.
78493    ** That is Ok, at this point the parent page is guaranteed to
78494    ** be marked as dirty. Returning an error code will cause a
78495    ** rollback, undoing any changes made to the parent page.
78496    */
78497    if( ISAUTOVACUUM(pBt) ){
78498      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
78499      if( szCell>pNew->minLocal ){
78500        ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
78501      }
78502    }
78503
78504    /* Create a divider cell to insert into pParent. The divider cell
78505    ** consists of a 4-byte page number (the page number of pPage) and
78506    ** a variable length key value (which must be the same value as the
78507    ** largest key on pPage).
78508    **
78509    ** To find the largest key value on pPage, first find the right-most
78510    ** cell on pPage. The first two fields of this cell are the
78511    ** record-length (a variable length integer at most 32-bits in size)
78512    ** and the key value (a variable length integer, may have any value).
78513    ** The first of the while(...) loops below skips over the record-length
78514    ** field. The second while(...) loop copies the key value from the
78515    ** cell on pPage into the pSpace buffer.
78516    */
78517    pCell = findCell(pPage, pPage->nCell-1);
78518    pStop = &pCell[9];
78519    while( (*(pCell++)&0x80) && pCell<pStop );
78520    pStop = &pCell[9];
78521    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
78522
78523    /* Insert the new divider cell into pParent. */
78524    if( rc==SQLITE_OK ){
78525      rc = insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
78526                      0, pPage->pgno);
78527    }
78528
78529    /* Set the right-child pointer of pParent to point to the new page. */
78530    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
78531
78532    /* Release the reference to the new page. */
78533    releasePage(pNew);
78534  }
78535
78536  return rc;
78537}
78538#endif /* SQLITE_OMIT_QUICKBALANCE */
78539
78540#if 0
78541/*
78542** This function does not contribute anything to the operation of SQLite.
78543** it is sometimes activated temporarily while debugging code responsible
78544** for setting pointer-map entries.
78545*/
78546static int ptrmapCheckPages(MemPage **apPage, int nPage){
78547  int i, j;
78548  for(i=0; i<nPage; i++){
78549    Pgno n;
78550    u8 e;
78551    MemPage *pPage = apPage[i];
78552    BtShared *pBt = pPage->pBt;
78553    assert( pPage->isInit );
78554
78555    for(j=0; j<pPage->nCell; j++){
78556      CellInfo info;
78557      u8 *z;
78558
78559      z = findCell(pPage, j);
78560      pPage->xParseCell(pPage, z, &info);
78561      if( info.nLocal<info.nPayload ){
78562        Pgno ovfl = get4byte(&z[info.nSize-4]);
78563        ptrmapGet(pBt, ovfl, &e, &n);
78564        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
78565      }
78566      if( !pPage->leaf ){
78567        Pgno child = get4byte(z);
78568        ptrmapGet(pBt, child, &e, &n);
78569        assert( n==pPage->pgno && e==PTRMAP_BTREE );
78570      }
78571    }
78572    if( !pPage->leaf ){
78573      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
78574      ptrmapGet(pBt, child, &e, &n);
78575      assert( n==pPage->pgno && e==PTRMAP_BTREE );
78576    }
78577  }
78578  return 1;
78579}
78580#endif
78581
78582/*
78583** This function is used to copy the contents of the b-tree node stored
78584** on page pFrom to page pTo. If page pFrom was not a leaf page, then
78585** the pointer-map entries for each child page are updated so that the
78586** parent page stored in the pointer map is page pTo. If pFrom contained
78587** any cells with overflow page pointers, then the corresponding pointer
78588** map entries are also updated so that the parent page is page pTo.
78589**
78590** If pFrom is currently carrying any overflow cells (entries in the
78591** MemPage.apOvfl[] array), they are not copied to pTo.
78592**
78593** Before returning, page pTo is reinitialized using btreeInitPage().
78594**
78595** The performance of this function is not critical. It is only used by
78596** the balance_shallower() and balance_deeper() procedures, neither of
78597** which are called often under normal circumstances.
78598*/
78599static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
78600  if( (*pRC)==SQLITE_OK ){
78601    BtShared * const pBt = pFrom->pBt;
78602    u8 * const aFrom = pFrom->aData;
78603    u8 * const aTo = pTo->aData;
78604    int const iFromHdr = pFrom->hdrOffset;
78605    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
78606    int rc;
78607    int iData;
78608
78609
78610    assert( pFrom->isInit );
78611    assert( pFrom->nFree>=iToHdr );
78612    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
78613
78614    /* Copy the b-tree node content from page pFrom to page pTo. */
78615    iData = get2byte(&aFrom[iFromHdr+5]);
78616    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
78617    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
78618
78619    /* Reinitialize page pTo so that the contents of the MemPage structure
78620    ** match the new data. The initialization of pTo can actually fail under
78621    ** fairly obscure circumstances, even though it is a copy of initialized
78622    ** page pFrom.
78623    */
78624    pTo->isInit = 0;
78625    rc = btreeInitPage(pTo);
78626    if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
78627    if( rc!=SQLITE_OK ){
78628      *pRC = rc;
78629      return;
78630    }
78631
78632    /* If this is an auto-vacuum database, update the pointer-map entries
78633    ** for any b-tree or overflow pages that pTo now contains the pointers to.
78634    */
78635    if( ISAUTOVACUUM(pBt) ){
78636      *pRC = setChildPtrmaps(pTo);
78637    }
78638  }
78639}
78640
78641/*
78642** This routine redistributes cells on the iParentIdx'th child of pParent
78643** (hereafter "the page") and up to 2 siblings so that all pages have about the
78644** same amount of free space. Usually a single sibling on either side of the
78645** page are used in the balancing, though both siblings might come from one
78646** side if the page is the first or last child of its parent. If the page
78647** has fewer than 2 siblings (something which can only happen if the page
78648** is a root page or a child of a root page) then all available siblings
78649** participate in the balancing.
78650**
78651** The number of siblings of the page might be increased or decreased by
78652** one or two in an effort to keep pages nearly full but not over full.
78653**
78654** Note that when this routine is called, some of the cells on the page
78655** might not actually be stored in MemPage.aData[]. This can happen
78656** if the page is overfull. This routine ensures that all cells allocated
78657** to the page and its siblings fit into MemPage.aData[] before returning.
78658**
78659** In the course of balancing the page and its siblings, cells may be
78660** inserted into or removed from the parent page (pParent). Doing so
78661** may cause the parent page to become overfull or underfull. If this
78662** happens, it is the responsibility of the caller to invoke the correct
78663** balancing routine to fix this problem (see the balance() routine).
78664**
78665** If this routine fails for any reason, it might leave the database
78666** in a corrupted state. So if this routine fails, the database should
78667** be rolled back.
78668**
78669** The third argument to this function, aOvflSpace, is a pointer to a
78670** buffer big enough to hold one page. If while inserting cells into the parent
78671** page (pParent) the parent page becomes overfull, this buffer is
78672** used to store the parent's overflow cells. Because this function inserts
78673** a maximum of four divider cells into the parent page, and the maximum
78674** size of a cell stored within an internal node is always less than 1/4
78675** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
78676** enough for all overflow cells.
78677**
78678** If aOvflSpace is set to a null pointer, this function returns
78679** SQLITE_NOMEM.
78680*/
78681static int balance_nonroot(
78682  MemPage *pParent,               /* Parent page of siblings being balanced */
78683  int iParentIdx,                 /* Index of "the page" in pParent */
78684  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
78685  int isRoot,                     /* True if pParent is a root-page */
78686  int bBulk                       /* True if this call is part of a bulk load */
78687){
78688  BtShared *pBt;               /* The whole database */
78689  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
78690  int nNew = 0;                /* Number of pages in apNew[] */
78691  int nOld;                    /* Number of pages in apOld[] */
78692  int i, j, k;                 /* Loop counters */
78693  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
78694  int rc = SQLITE_OK;          /* The return code */
78695  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
78696  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
78697  int usableSpace;             /* Bytes in pPage beyond the header */
78698  int pageFlags;               /* Value of pPage->aData[0] */
78699  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
78700  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
78701  int szScratch;               /* Size of scratch memory requested */
78702  MemPage *apOld[NB];          /* pPage and up to two siblings */
78703  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
78704  u8 *pRight;                  /* Location in parent of right-sibling pointer */
78705  u8 *apDiv[NB-1];             /* Divider cells in pParent */
78706  int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
78707  int cntOld[NB+2];            /* Old index in b.apCell[] */
78708  int szNew[NB+2];             /* Combined size of cells placed on i-th page */
78709  u8 *aSpace1;                 /* Space for copies of dividers cells */
78710  Pgno pgno;                   /* Temp var to store a page number in */
78711  u8 abDone[NB+2];             /* True after i'th new page is populated */
78712  Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
78713  CellArray b;                 /* Parsed information on cells being balanced */
78714
78715  memset(abDone, 0, sizeof(abDone));
78716  memset(&b, 0, sizeof(b));
78717  pBt = pParent->pBt;
78718  assert( sqlite3_mutex_held(pBt->mutex) );
78719  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
78720
78721  /* At this point pParent may have at most one overflow cell. And if
78722  ** this overflow cell is present, it must be the cell with
78723  ** index iParentIdx. This scenario comes about when this function
78724  ** is called (indirectly) from sqlite3BtreeDelete().
78725  */
78726  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
78727  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
78728
78729  if( !aOvflSpace ){
78730    return SQLITE_NOMEM_BKPT;
78731  }
78732  assert( pParent->nFree>=0 );
78733
78734  /* Find the sibling pages to balance. Also locate the cells in pParent
78735  ** that divide the siblings. An attempt is made to find NN siblings on
78736  ** either side of pPage. More siblings are taken from one side, however,
78737  ** if there are fewer than NN siblings on the other side. If pParent
78738  ** has NB or fewer children then all children of pParent are taken.
78739  **
78740  ** This loop also drops the divider cells from the parent page. This
78741  ** way, the remainder of the function does not have to deal with any
78742  ** overflow cells in the parent page, since if any existed they will
78743  ** have already been removed.
78744  */
78745  i = pParent->nOverflow + pParent->nCell;
78746  if( i<2 ){
78747    nxDiv = 0;
78748  }else{
78749    assert( bBulk==0 || bBulk==1 );
78750    if( iParentIdx==0 ){
78751      nxDiv = 0;
78752    }else if( iParentIdx==i ){
78753      nxDiv = i-2+bBulk;
78754    }else{
78755      nxDiv = iParentIdx-1;
78756    }
78757    i = 2-bBulk;
78758  }
78759  nOld = i+1;
78760  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
78761    pRight = &pParent->aData[pParent->hdrOffset+8];
78762  }else{
78763    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
78764  }
78765  pgno = get4byte(pRight);
78766  while( 1 ){
78767    if( rc==SQLITE_OK ){
78768      rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
78769    }
78770    if( rc ){
78771      memset(apOld, 0, (i+1)*sizeof(MemPage*));
78772      goto balance_cleanup;
78773    }
78774    if( apOld[i]->nFree<0 ){
78775      rc = btreeComputeFreeSpace(apOld[i]);
78776      if( rc ){
78777        memset(apOld, 0, (i)*sizeof(MemPage*));
78778        goto balance_cleanup;
78779      }
78780    }
78781    nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl);
78782    if( (i--)==0 ) break;
78783
78784    if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
78785      apDiv[i] = pParent->apOvfl[0];
78786      pgno = get4byte(apDiv[i]);
78787      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
78788      pParent->nOverflow = 0;
78789    }else{
78790      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
78791      pgno = get4byte(apDiv[i]);
78792      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
78793
78794      /* Drop the cell from the parent page. apDiv[i] still points to
78795      ** the cell within the parent, even though it has been dropped.
78796      ** This is safe because dropping a cell only overwrites the first
78797      ** four bytes of it, and this function does not need the first
78798      ** four bytes of the divider cell. So the pointer is safe to use
78799      ** later on.
78800      **
78801      ** But not if we are in secure-delete mode. In secure-delete mode,
78802      ** the dropCell() routine will overwrite the entire cell with zeroes.
78803      ** In this case, temporarily copy the cell into the aOvflSpace[]
78804      ** buffer. It will be copied out again as soon as the aSpace[] buffer
78805      ** is allocated.  */
78806      if( pBt->btsFlags & BTS_FAST_SECURE ){
78807        int iOff;
78808
78809        /* If the following if() condition is not true, the db is corrupted.
78810        ** The call to dropCell() below will detect this.  */
78811        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
78812        if( (iOff+szNew[i])<=(int)pBt->usableSize ){
78813          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
78814          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
78815        }
78816      }
78817      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
78818    }
78819  }
78820
78821  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
78822  ** alignment */
78823  nMaxCells = (nMaxCells + 3)&~3;
78824
78825  /*
78826  ** Allocate space for memory structures
78827  */
78828  szScratch =
78829       nMaxCells*sizeof(u8*)                       /* b.apCell */
78830     + nMaxCells*sizeof(u16)                       /* b.szCell */
78831     + pBt->pageSize;                              /* aSpace1 */
78832
78833  assert( szScratch<=7*(int)pBt->pageSize );
78834  b.apCell = sqlite3StackAllocRaw(0, szScratch );
78835  if( b.apCell==0 ){
78836    rc = SQLITE_NOMEM_BKPT;
78837    goto balance_cleanup;
78838  }
78839  b.szCell = (u16*)&b.apCell[nMaxCells];
78840  aSpace1 = (u8*)&b.szCell[nMaxCells];
78841  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
78842
78843  /*
78844  ** Load pointers to all cells on sibling pages and the divider cells
78845  ** into the local b.apCell[] array.  Make copies of the divider cells
78846  ** into space obtained from aSpace1[]. The divider cells have already
78847  ** been removed from pParent.
78848  **
78849  ** If the siblings are on leaf pages, then the child pointers of the
78850  ** divider cells are stripped from the cells before they are copied
78851  ** into aSpace1[].  In this way, all cells in b.apCell[] are without
78852  ** child pointers.  If siblings are not leaves, then all cell in
78853  ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
78854  ** are alike.
78855  **
78856  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
78857  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
78858  */
78859  b.pRef = apOld[0];
78860  leafCorrection = b.pRef->leaf*4;
78861  leafData = b.pRef->intKeyLeaf;
78862  for(i=0; i<nOld; i++){
78863    MemPage *pOld = apOld[i];
78864    int limit = pOld->nCell;
78865    u8 *aData = pOld->aData;
78866    u16 maskPage = pOld->maskPage;
78867    u8 *piCell = aData + pOld->cellOffset;
78868    u8 *piEnd;
78869    VVA_ONLY( int nCellAtStart = b.nCell; )
78870
78871    /* Verify that all sibling pages are of the same "type" (table-leaf,
78872    ** table-interior, index-leaf, or index-interior).
78873    */
78874    if( pOld->aData[0]!=apOld[0]->aData[0] ){
78875      rc = SQLITE_CORRUPT_PAGE(pOld);
78876      goto balance_cleanup;
78877    }
78878
78879    /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
78880    ** contains overflow cells, include them in the b.apCell[] array
78881    ** in the correct spot.
78882    **
78883    ** Note that when there are multiple overflow cells, it is always the
78884    ** case that they are sequential and adjacent.  This invariant arises
78885    ** because multiple overflows can only occurs when inserting divider
78886    ** cells into a parent on a prior balance, and divider cells are always
78887    ** adjacent and are inserted in order.  There is an assert() tagged
78888    ** with "NOTE 1" in the overflow cell insertion loop to prove this
78889    ** invariant.
78890    **
78891    ** This must be done in advance.  Once the balance starts, the cell
78892    ** offset section of the btree page will be overwritten and we will no
78893    ** long be able to find the cells if a pointer to each cell is not saved
78894    ** first.
78895    */
78896    memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
78897    if( pOld->nOverflow>0 ){
78898      if( NEVER(limit<pOld->aiOvfl[0]) ){
78899        rc = SQLITE_CORRUPT_PAGE(pOld);
78900        goto balance_cleanup;
78901      }
78902      limit = pOld->aiOvfl[0];
78903      for(j=0; j<limit; j++){
78904        b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
78905        piCell += 2;
78906        b.nCell++;
78907      }
78908      for(k=0; k<pOld->nOverflow; k++){
78909        assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
78910        b.apCell[b.nCell] = pOld->apOvfl[k];
78911        b.nCell++;
78912      }
78913    }
78914    piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
78915    while( piCell<piEnd ){
78916      assert( b.nCell<nMaxCells );
78917      b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
78918      piCell += 2;
78919      b.nCell++;
78920    }
78921    assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
78922
78923    cntOld[i] = b.nCell;
78924    if( i<nOld-1 && !leafData){
78925      u16 sz = (u16)szNew[i];
78926      u8 *pTemp;
78927      assert( b.nCell<nMaxCells );
78928      b.szCell[b.nCell] = sz;
78929      pTemp = &aSpace1[iSpace1];
78930      iSpace1 += sz;
78931      assert( sz<=pBt->maxLocal+23 );
78932      assert( iSpace1 <= (int)pBt->pageSize );
78933      memcpy(pTemp, apDiv[i], sz);
78934      b.apCell[b.nCell] = pTemp+leafCorrection;
78935      assert( leafCorrection==0 || leafCorrection==4 );
78936      b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
78937      if( !pOld->leaf ){
78938        assert( leafCorrection==0 );
78939        assert( pOld->hdrOffset==0 || CORRUPT_DB );
78940        /* The right pointer of the child page pOld becomes the left
78941        ** pointer of the divider cell */
78942        memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
78943      }else{
78944        assert( leafCorrection==4 );
78945        while( b.szCell[b.nCell]<4 ){
78946          /* Do not allow any cells smaller than 4 bytes. If a smaller cell
78947          ** does exist, pad it with 0x00 bytes. */
78948          assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
78949          assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
78950          aSpace1[iSpace1++] = 0x00;
78951          b.szCell[b.nCell]++;
78952        }
78953      }
78954      b.nCell++;
78955    }
78956  }
78957
78958  /*
78959  ** Figure out the number of pages needed to hold all b.nCell cells.
78960  ** Store this number in "k".  Also compute szNew[] which is the total
78961  ** size of all cells on the i-th page and cntNew[] which is the index
78962  ** in b.apCell[] of the cell that divides page i from page i+1.
78963  ** cntNew[k] should equal b.nCell.
78964  **
78965  ** Values computed by this block:
78966  **
78967  **           k: The total number of sibling pages
78968  **    szNew[i]: Spaced used on the i-th sibling page.
78969  **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
78970  **              the right of the i-th sibling page.
78971  ** usableSpace: Number of bytes of space available on each sibling.
78972  **
78973  */
78974  usableSpace = pBt->usableSize - 12 + leafCorrection;
78975  for(i=k=0; i<nOld; i++, k++){
78976    MemPage *p = apOld[i];
78977    b.apEnd[k] = p->aDataEnd;
78978    b.ixNx[k] = cntOld[i];
78979    if( k && b.ixNx[k]==b.ixNx[k-1] ){
78980      k--;  /* Omit b.ixNx[] entry for child pages with no cells */
78981    }
78982    if( !leafData ){
78983      k++;
78984      b.apEnd[k] = pParent->aDataEnd;
78985      b.ixNx[k] = cntOld[i]+1;
78986    }
78987    assert( p->nFree>=0 );
78988    szNew[i] = usableSpace - p->nFree;
78989    for(j=0; j<p->nOverflow; j++){
78990      szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
78991    }
78992    cntNew[i] = cntOld[i];
78993  }
78994  k = nOld;
78995  for(i=0; i<k; i++){
78996    int sz;
78997    while( szNew[i]>usableSpace ){
78998      if( i+1>=k ){
78999        k = i+2;
79000        if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
79001        szNew[k-1] = 0;
79002        cntNew[k-1] = b.nCell;
79003      }
79004      sz = 2 + cachedCellSize(&b, cntNew[i]-1);
79005      szNew[i] -= sz;
79006      if( !leafData ){
79007        if( cntNew[i]<b.nCell ){
79008          sz = 2 + cachedCellSize(&b, cntNew[i]);
79009        }else{
79010          sz = 0;
79011        }
79012      }
79013      szNew[i+1] += sz;
79014      cntNew[i]--;
79015    }
79016    while( cntNew[i]<b.nCell ){
79017      sz = 2 + cachedCellSize(&b, cntNew[i]);
79018      if( szNew[i]+sz>usableSpace ) break;
79019      szNew[i] += sz;
79020      cntNew[i]++;
79021      if( !leafData ){
79022        if( cntNew[i]<b.nCell ){
79023          sz = 2 + cachedCellSize(&b, cntNew[i]);
79024        }else{
79025          sz = 0;
79026        }
79027      }
79028      szNew[i+1] -= sz;
79029    }
79030    if( cntNew[i]>=b.nCell ){
79031      k = i+1;
79032    }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
79033      rc = SQLITE_CORRUPT_BKPT;
79034      goto balance_cleanup;
79035    }
79036  }
79037
79038  /*
79039  ** The packing computed by the previous block is biased toward the siblings
79040  ** on the left side (siblings with smaller keys). The left siblings are
79041  ** always nearly full, while the right-most sibling might be nearly empty.
79042  ** The next block of code attempts to adjust the packing of siblings to
79043  ** get a better balance.
79044  **
79045  ** This adjustment is more than an optimization.  The packing above might
79046  ** be so out of balance as to be illegal.  For example, the right-most
79047  ** sibling might be completely empty.  This adjustment is not optional.
79048  */
79049  for(i=k-1; i>0; i--){
79050    int szRight = szNew[i];  /* Size of sibling on the right */
79051    int szLeft = szNew[i-1]; /* Size of sibling on the left */
79052    int r;              /* Index of right-most cell in left sibling */
79053    int d;              /* Index of first cell to the left of right sibling */
79054
79055    r = cntNew[i-1] - 1;
79056    d = r + 1 - leafData;
79057    (void)cachedCellSize(&b, d);
79058    do{
79059      int szR, szD;
79060      assert( d<nMaxCells );
79061      assert( r<nMaxCells );
79062      szR = cachedCellSize(&b, r);
79063      szD = b.szCell[d];
79064      if( szRight!=0
79065       && (bBulk || szRight+szD+2 > szLeft-(szR+(i==k-1?0:2)))){
79066        break;
79067      }
79068      szRight += szD + 2;
79069      szLeft -= szR + 2;
79070      cntNew[i-1] = r;
79071      r--;
79072      d--;
79073    }while( r>=0 );
79074    szNew[i] = szRight;
79075    szNew[i-1] = szLeft;
79076    if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
79077      rc = SQLITE_CORRUPT_BKPT;
79078      goto balance_cleanup;
79079    }
79080  }
79081
79082  /* Sanity check:  For a non-corrupt database file one of the following
79083  ** must be true:
79084  **    (1) We found one or more cells (cntNew[0])>0), or
79085  **    (2) pPage is a virtual root page.  A virtual root page is when
79086  **        the real root page is page 1 and we are the only child of
79087  **        that page.
79088  */
79089  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
79090  TRACE(("BALANCE: old: %u(nc=%u) %u(nc=%u) %u(nc=%u)\n",
79091    apOld[0]->pgno, apOld[0]->nCell,
79092    nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
79093    nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
79094  ));
79095
79096  /*
79097  ** Allocate k new pages.  Reuse old pages where possible.
79098  */
79099  pageFlags = apOld[0]->aData[0];
79100  for(i=0; i<k; i++){
79101    MemPage *pNew;
79102    if( i<nOld ){
79103      pNew = apNew[i] = apOld[i];
79104      apOld[i] = 0;
79105      rc = sqlite3PagerWrite(pNew->pDbPage);
79106      nNew++;
79107      if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv))
79108       && rc==SQLITE_OK
79109      ){
79110        rc = SQLITE_CORRUPT_BKPT;
79111      }
79112      if( rc ) goto balance_cleanup;
79113    }else{
79114      assert( i>0 );
79115      rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
79116      if( rc ) goto balance_cleanup;
79117      zeroPage(pNew, pageFlags);
79118      apNew[i] = pNew;
79119      nNew++;
79120      cntOld[i] = b.nCell;
79121
79122      /* Set the pointer-map entry for the new sibling page. */
79123      if( ISAUTOVACUUM(pBt) ){
79124        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
79125        if( rc!=SQLITE_OK ){
79126          goto balance_cleanup;
79127        }
79128      }
79129    }
79130  }
79131
79132  /*
79133  ** Reassign page numbers so that the new pages are in ascending order.
79134  ** This helps to keep entries in the disk file in order so that a scan
79135  ** of the table is closer to a linear scan through the file. That in turn
79136  ** helps the operating system to deliver pages from the disk more rapidly.
79137  **
79138  ** An O(N*N) sort algorithm is used, but since N is never more than NB+2
79139  ** (5), that is not a performance concern.
79140  **
79141  ** When NB==3, this one optimization makes the database about 25% faster
79142  ** for large insertions and deletions.
79143  */
79144  for(i=0; i<nNew; i++){
79145    aPgno[i] = apNew[i]->pgno;
79146    assert( apNew[i]->pDbPage->flags & PGHDR_WRITEABLE );
79147    assert( apNew[i]->pDbPage->flags & PGHDR_DIRTY );
79148  }
79149  for(i=0; i<nNew-1; i++){
79150    int iB = i;
79151    for(j=i+1; j<nNew; j++){
79152      if( apNew[j]->pgno < apNew[iB]->pgno ) iB = j;
79153    }
79154
79155    /* If apNew[i] has a page number that is bigger than any of the
79156    ** subsequence apNew[i] entries, then swap apNew[i] with the subsequent
79157    ** entry that has the smallest page number (which we know to be
79158    ** entry apNew[iB]).
79159    */
79160    if( iB!=i ){
79161      Pgno pgnoA = apNew[i]->pgno;
79162      Pgno pgnoB = apNew[iB]->pgno;
79163      Pgno pgnoTemp = (PENDING_BYTE/pBt->pageSize)+1;
79164      u16 fgA = apNew[i]->pDbPage->flags;
79165      u16 fgB = apNew[iB]->pDbPage->flags;
79166      sqlite3PagerRekey(apNew[i]->pDbPage, pgnoTemp, fgB);
79167      sqlite3PagerRekey(apNew[iB]->pDbPage, pgnoA, fgA);
79168      sqlite3PagerRekey(apNew[i]->pDbPage, pgnoB, fgB);
79169      apNew[i]->pgno = pgnoB;
79170      apNew[iB]->pgno = pgnoA;
79171    }
79172  }
79173
79174  TRACE(("BALANCE: new: %u(%u nc=%u) %u(%u nc=%u) %u(%u nc=%u) "
79175         "%u(%u nc=%u) %u(%u nc=%u)\n",
79176    apNew[0]->pgno, szNew[0], cntNew[0],
79177    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
79178    nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
79179    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
79180    nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
79181    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
79182    nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
79183    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
79184    nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
79185  ));
79186
79187  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
79188  assert( nNew>=1 && nNew<=ArraySize(apNew) );
79189  assert( apNew[nNew-1]!=0 );
79190  put4byte(pRight, apNew[nNew-1]->pgno);
79191
79192  /* If the sibling pages are not leaves, ensure that the right-child pointer
79193  ** of the right-most new sibling page is set to the value that was
79194  ** originally in the same field of the right-most old sibling page. */
79195  if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
79196    MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
79197    memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
79198  }
79199
79200  /* Make any required updates to pointer map entries associated with
79201  ** cells stored on sibling pages following the balance operation. Pointer
79202  ** map entries associated with divider cells are set by the insertCell()
79203  ** routine. The associated pointer map entries are:
79204  **
79205  **   a) if the cell contains a reference to an overflow chain, the
79206  **      entry associated with the first page in the overflow chain, and
79207  **
79208  **   b) if the sibling pages are not leaves, the child page associated
79209  **      with the cell.
79210  **
79211  ** If the sibling pages are not leaves, then the pointer map entry
79212  ** associated with the right-child of each sibling may also need to be
79213  ** updated. This happens below, after the sibling pages have been
79214  ** populated, not here.
79215  */
79216  if( ISAUTOVACUUM(pBt) ){
79217    MemPage *pOld;
79218    MemPage *pNew = pOld = apNew[0];
79219    int cntOldNext = pNew->nCell + pNew->nOverflow;
79220    int iNew = 0;
79221    int iOld = 0;
79222
79223    for(i=0; i<b.nCell; i++){
79224      u8 *pCell = b.apCell[i];
79225      while( i==cntOldNext ){
79226        iOld++;
79227        assert( iOld<nNew || iOld<nOld );
79228        assert( iOld>=0 && iOld<NB );
79229        pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
79230        cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
79231      }
79232      if( i==cntNew[iNew] ){
79233        pNew = apNew[++iNew];
79234        if( !leafData ) continue;
79235      }
79236
79237      /* Cell pCell is destined for new sibling page pNew. Originally, it
79238      ** was either part of sibling page iOld (possibly an overflow cell),
79239      ** or else the divider cell to the left of sibling page iOld. So,
79240      ** if sibling page iOld had the same page number as pNew, and if
79241      ** pCell really was a part of sibling page iOld (not a divider or
79242      ** overflow cell), we can skip updating the pointer map entries.  */
79243      if( iOld>=nNew
79244       || pNew->pgno!=aPgno[iOld]
79245       || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
79246      ){
79247        if( !leafCorrection ){
79248          ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
79249        }
79250        if( cachedCellSize(&b,i)>pNew->minLocal ){
79251          ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
79252        }
79253        if( rc ) goto balance_cleanup;
79254      }
79255    }
79256  }
79257
79258  /* Insert new divider cells into pParent. */
79259  for(i=0; i<nNew-1; i++){
79260    u8 *pCell;
79261    u8 *pTemp;
79262    int sz;
79263    u8 *pSrcEnd;
79264    MemPage *pNew = apNew[i];
79265    j = cntNew[i];
79266
79267    assert( j<nMaxCells );
79268    assert( b.apCell[j]!=0 );
79269    pCell = b.apCell[j];
79270    sz = b.szCell[j] + leafCorrection;
79271    pTemp = &aOvflSpace[iOvflSpace];
79272    if( !pNew->leaf ){
79273      memcpy(&pNew->aData[8], pCell, 4);
79274    }else if( leafData ){
79275      /* If the tree is a leaf-data tree, and the siblings are leaves,
79276      ** then there is no divider cell in b.apCell[]. Instead, the divider
79277      ** cell consists of the integer key for the right-most cell of
79278      ** the sibling-page assembled above only.
79279      */
79280      CellInfo info;
79281      j--;
79282      pNew->xParseCell(pNew, b.apCell[j], &info);
79283      pCell = pTemp;
79284      sz = 4 + putVarint(&pCell[4], info.nKey);
79285      pTemp = 0;
79286    }else{
79287      pCell -= 4;
79288      /* Obscure case for non-leaf-data trees: If the cell at pCell was
79289      ** previously stored on a leaf node, and its reported size was 4
79290      ** bytes, then it may actually be smaller than this
79291      ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
79292      ** any cell). But it is important to pass the correct size to
79293      ** insertCell(), so reparse the cell now.
79294      **
79295      ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
79296      ** and WITHOUT ROWID tables with exactly one column which is the
79297      ** primary key.
79298      */
79299      if( b.szCell[j]==4 ){
79300        assert(leafCorrection==4);
79301        sz = pParent->xCellSize(pParent, pCell);
79302      }
79303    }
79304    iOvflSpace += sz;
79305    assert( sz<=pBt->maxLocal+23 );
79306    assert( iOvflSpace <= (int)pBt->pageSize );
79307    for(k=0; ALWAYS(k<NB*2) && b.ixNx[k]<=j; k++){}
79308    pSrcEnd = b.apEnd[k];
79309    if( SQLITE_OVERFLOW(pSrcEnd, pCell, pCell+sz) ){
79310      rc = SQLITE_CORRUPT_BKPT;
79311      goto balance_cleanup;
79312    }
79313    rc = insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno);
79314    if( rc!=SQLITE_OK ) goto balance_cleanup;
79315    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
79316  }
79317
79318  /* Now update the actual sibling pages. The order in which they are updated
79319  ** is important, as this code needs to avoid disrupting any page from which
79320  ** cells may still to be read. In practice, this means:
79321  **
79322  **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
79323  **      then it is not safe to update page apNew[iPg] until after
79324  **      the left-hand sibling apNew[iPg-1] has been updated.
79325  **
79326  **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
79327  **      then it is not safe to update page apNew[iPg] until after
79328  **      the right-hand sibling apNew[iPg+1] has been updated.
79329  **
79330  ** If neither of the above apply, the page is safe to update.
79331  **
79332  ** The iPg value in the following loop starts at nNew-1 goes down
79333  ** to 0, then back up to nNew-1 again, thus making two passes over
79334  ** the pages.  On the initial downward pass, only condition (1) above
79335  ** needs to be tested because (2) will always be true from the previous
79336  ** step.  On the upward pass, both conditions are always true, so the
79337  ** upwards pass simply processes pages that were missed on the downward
79338  ** pass.
79339  */
79340  for(i=1-nNew; i<nNew; i++){
79341    int iPg = i<0 ? -i : i;
79342    assert( iPg>=0 && iPg<nNew );
79343    assert( iPg>=1 || i>=0 );
79344    assert( iPg<ArraySize(cntOld) );
79345    if( abDone[iPg] ) continue;         /* Skip pages already processed */
79346    if( i>=0                            /* On the upwards pass, or... */
79347     || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
79348    ){
79349      int iNew;
79350      int iOld;
79351      int nNewCell;
79352
79353      /* Verify condition (1):  If cells are moving left, update iPg
79354      ** only after iPg-1 has already been updated. */
79355      assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
79356
79357      /* Verify condition (2):  If cells are moving right, update iPg
79358      ** only after iPg+1 has already been updated. */
79359      assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
79360
79361      if( iPg==0 ){
79362        iNew = iOld = 0;
79363        nNewCell = cntNew[0];
79364      }else{
79365        iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
79366        iNew = cntNew[iPg-1] + !leafData;
79367        nNewCell = cntNew[iPg] - iNew;
79368      }
79369
79370      rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
79371      if( rc ) goto balance_cleanup;
79372      abDone[iPg]++;
79373      apNew[iPg]->nFree = usableSpace-szNew[iPg];
79374      assert( apNew[iPg]->nOverflow==0 );
79375      assert( apNew[iPg]->nCell==nNewCell );
79376    }
79377  }
79378
79379  /* All pages have been processed exactly once */
79380  assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
79381
79382  assert( nOld>0 );
79383  assert( nNew>0 );
79384
79385  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
79386    /* The root page of the b-tree now contains no cells. The only sibling
79387    ** page is the right-child of the parent. Copy the contents of the
79388    ** child page into the parent, decreasing the overall height of the
79389    ** b-tree structure by one. This is described as the "balance-shallower"
79390    ** sub-algorithm in some documentation.
79391    **
79392    ** If this is an auto-vacuum database, the call to copyNodeContent()
79393    ** sets all pointer-map entries corresponding to database image pages
79394    ** for which the pointer is stored within the content being copied.
79395    **
79396    ** It is critical that the child page be defragmented before being
79397    ** copied into the parent, because if the parent is page 1 then it will
79398    ** by smaller than the child due to the database header, and so all the
79399    ** free space needs to be up front.
79400    */
79401    assert( nNew==1 || CORRUPT_DB );
79402    rc = defragmentPage(apNew[0], -1);
79403    testcase( rc!=SQLITE_OK );
79404    assert( apNew[0]->nFree ==
79405        (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
79406          - apNew[0]->nCell*2)
79407      || rc!=SQLITE_OK
79408    );
79409    copyNodeContent(apNew[0], pParent, &rc);
79410    freePage(apNew[0], &rc);
79411  }else if( ISAUTOVACUUM(pBt) && !leafCorrection ){
79412    /* Fix the pointer map entries associated with the right-child of each
79413    ** sibling page. All other pointer map entries have already been taken
79414    ** care of.  */
79415    for(i=0; i<nNew; i++){
79416      u32 key = get4byte(&apNew[i]->aData[8]);
79417      ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
79418    }
79419  }
79420
79421  assert( pParent->isInit );
79422  TRACE(("BALANCE: finished: old=%u new=%u cells=%u\n",
79423          nOld, nNew, b.nCell));
79424
79425  /* Free any old pages that were not reused as new pages.
79426  */
79427  for(i=nNew; i<nOld; i++){
79428    freePage(apOld[i], &rc);
79429  }
79430
79431#if 0
79432  if( ISAUTOVACUUM(pBt) && rc==SQLITE_OK && apNew[0]->isInit ){
79433    /* The ptrmapCheckPages() contains assert() statements that verify that
79434    ** all pointer map pages are set correctly. This is helpful while
79435    ** debugging. This is usually disabled because a corrupt database may
79436    ** cause an assert() statement to fail.  */
79437    ptrmapCheckPages(apNew, nNew);
79438    ptrmapCheckPages(&pParent, 1);
79439  }
79440#endif
79441
79442  /*
79443  ** Cleanup before returning.
79444  */
79445balance_cleanup:
79446  sqlite3StackFree(0, b.apCell);
79447  for(i=0; i<nOld; i++){
79448    releasePage(apOld[i]);
79449  }
79450  for(i=0; i<nNew; i++){
79451    releasePage(apNew[i]);
79452  }
79453
79454  return rc;
79455}
79456
79457
79458/*
79459** This function is called when the root page of a b-tree structure is
79460** overfull (has one or more overflow pages).
79461**
79462** A new child page is allocated and the contents of the current root
79463** page, including overflow cells, are copied into the child. The root
79464** page is then overwritten to make it an empty page with the right-child
79465** pointer pointing to the new page.
79466**
79467** Before returning, all pointer-map entries corresponding to pages
79468** that the new child-page now contains pointers to are updated. The
79469** entry corresponding to the new right-child pointer of the root
79470** page is also updated.
79471**
79472** If successful, *ppChild is set to contain a reference to the child
79473** page and SQLITE_OK is returned. In this case the caller is required
79474** to call releasePage() on *ppChild exactly once. If an error occurs,
79475** an error code is returned and *ppChild is set to 0.
79476*/
79477static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
79478  int rc;                        /* Return value from subprocedures */
79479  MemPage *pChild = 0;           /* Pointer to a new child page */
79480  Pgno pgnoChild = 0;            /* Page number of the new child page */
79481  BtShared *pBt = pRoot->pBt;    /* The BTree */
79482
79483  assert( pRoot->nOverflow>0 );
79484  assert( sqlite3_mutex_held(pBt->mutex) );
79485
79486  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
79487  ** page that will become the new right-child of pPage. Copy the contents
79488  ** of the node stored on pRoot into the new child page.
79489  */
79490  rc = sqlite3PagerWrite(pRoot->pDbPage);
79491  if( rc==SQLITE_OK ){
79492    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
79493    copyNodeContent(pRoot, pChild, &rc);
79494    if( ISAUTOVACUUM(pBt) ){
79495      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
79496    }
79497  }
79498  if( rc ){
79499    *ppChild = 0;
79500    releasePage(pChild);
79501    return rc;
79502  }
79503  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
79504  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
79505  assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
79506
79507  TRACE(("BALANCE: copy root %u into %u\n", pRoot->pgno, pChild->pgno));
79508
79509  /* Copy the overflow cells from pRoot to pChild */
79510  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
79511         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
79512  memcpy(pChild->apOvfl, pRoot->apOvfl,
79513         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
79514  pChild->nOverflow = pRoot->nOverflow;
79515
79516  /* Zero the contents of pRoot. Then install pChild as the right-child. */
79517  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
79518  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
79519
79520  *ppChild = pChild;
79521  return SQLITE_OK;
79522}
79523
79524/*
79525** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
79526** on the same B-tree as pCur.
79527**
79528** This can occur if a database is corrupt with two or more SQL tables
79529** pointing to the same b-tree.  If an insert occurs on one SQL table
79530** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
79531** table linked to the same b-tree.  If the secondary insert causes a
79532** rebalance, that can change content out from under the cursor on the
79533** first SQL table, violating invariants on the first insert.
79534*/
79535static int anotherValidCursor(BtCursor *pCur){
79536  BtCursor *pOther;
79537  for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
79538    if( pOther!=pCur
79539     && pOther->eState==CURSOR_VALID
79540     && pOther->pPage==pCur->pPage
79541    ){
79542      return SQLITE_CORRUPT_PAGE(pCur->pPage);
79543    }
79544  }
79545  return SQLITE_OK;
79546}
79547
79548/*
79549** The page that pCur currently points to has just been modified in
79550** some way. This function figures out if this modification means the
79551** tree needs to be balanced, and if so calls the appropriate balancing
79552** routine. Balancing routines are:
79553**
79554**   balance_quick()
79555**   balance_deeper()
79556**   balance_nonroot()
79557*/
79558static int balance(BtCursor *pCur){
79559  int rc = SQLITE_OK;
79560  u8 aBalanceQuickSpace[13];
79561  u8 *pFree = 0;
79562
79563  VVA_ONLY( int balance_quick_called = 0 );
79564  VVA_ONLY( int balance_deeper_called = 0 );
79565
79566  do {
79567    int iPage;
79568    MemPage *pPage = pCur->pPage;
79569
79570    if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
79571    if( pPage->nOverflow==0 && pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
79572      /* No rebalance required as long as:
79573      **   (1) There are no overflow cells
79574      **   (2) The amount of free space on the page is less than 2/3rds of
79575      **       the total usable space on the page. */
79576      break;
79577    }else if( (iPage = pCur->iPage)==0 ){
79578      if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
79579        /* The root page of the b-tree is overfull. In this case call the
79580        ** balance_deeper() function to create a new child for the root-page
79581        ** and copy the current contents of the root-page to it. The
79582        ** next iteration of the do-loop will balance the child page.
79583        */
79584        assert( balance_deeper_called==0 );
79585        VVA_ONLY( balance_deeper_called++ );
79586        rc = balance_deeper(pPage, &pCur->apPage[1]);
79587        if( rc==SQLITE_OK ){
79588          pCur->iPage = 1;
79589          pCur->ix = 0;
79590          pCur->aiIdx[0] = 0;
79591          pCur->apPage[0] = pPage;
79592          pCur->pPage = pCur->apPage[1];
79593          assert( pCur->pPage->nOverflow );
79594        }
79595      }else{
79596        break;
79597      }
79598    }else if( sqlite3PagerPageRefcount(pPage->pDbPage)>1 ){
79599      /* The page being written is not a root page, and there is currently
79600      ** more than one reference to it. This only happens if the page is one
79601      ** of its own ancestor pages. Corruption. */
79602      rc = SQLITE_CORRUPT_PAGE(pPage);
79603    }else{
79604      MemPage * const pParent = pCur->apPage[iPage-1];
79605      int const iIdx = pCur->aiIdx[iPage-1];
79606
79607      rc = sqlite3PagerWrite(pParent->pDbPage);
79608      if( rc==SQLITE_OK && pParent->nFree<0 ){
79609        rc = btreeComputeFreeSpace(pParent);
79610      }
79611      if( rc==SQLITE_OK ){
79612#ifndef SQLITE_OMIT_QUICKBALANCE
79613        if( pPage->intKeyLeaf
79614         && pPage->nOverflow==1
79615         && pPage->aiOvfl[0]==pPage->nCell
79616         && pParent->pgno!=1
79617         && pParent->nCell==iIdx
79618        ){
79619          /* Call balance_quick() to create a new sibling of pPage on which
79620          ** to store the overflow cell. balance_quick() inserts a new cell
79621          ** into pParent, which may cause pParent overflow. If this
79622          ** happens, the next iteration of the do-loop will balance pParent
79623          ** use either balance_nonroot() or balance_deeper(). Until this
79624          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
79625          ** buffer.
79626          **
79627          ** The purpose of the following assert() is to check that only a
79628          ** single call to balance_quick() is made for each call to this
79629          ** function. If this were not verified, a subtle bug involving reuse
79630          ** of the aBalanceQuickSpace[] might sneak in.
79631          */
79632          assert( balance_quick_called==0 );
79633          VVA_ONLY( balance_quick_called++ );
79634          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
79635        }else
79636#endif
79637        {
79638          /* In this case, call balance_nonroot() to redistribute cells
79639          ** between pPage and up to 2 of its sibling pages. This involves
79640          ** modifying the contents of pParent, which may cause pParent to
79641          ** become overfull or underfull. The next iteration of the do-loop
79642          ** will balance the parent page to correct this.
79643          **
79644          ** If the parent page becomes overfull, the overflow cell or cells
79645          ** are stored in the pSpace buffer allocated immediately below.
79646          ** A subsequent iteration of the do-loop will deal with this by
79647          ** calling balance_nonroot() (balance_deeper() may be called first,
79648          ** but it doesn't deal with overflow cells - just moves them to a
79649          ** different page). Once this subsequent call to balance_nonroot()
79650          ** has completed, it is safe to release the pSpace buffer used by
79651          ** the previous call, as the overflow cell data will have been
79652          ** copied either into the body of a database page or into the new
79653          ** pSpace buffer passed to the latter call to balance_nonroot().
79654          */
79655          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
79656          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
79657                               pCur->hints&BTREE_BULKLOAD);
79658          if( pFree ){
79659            /* If pFree is not NULL, it points to the pSpace buffer used
79660            ** by a previous call to balance_nonroot(). Its contents are
79661            ** now stored either on real database pages or within the
79662            ** new pSpace buffer, so it may be safely freed here. */
79663            sqlite3PageFree(pFree);
79664          }
79665
79666          /* The pSpace buffer will be freed after the next call to
79667          ** balance_nonroot(), or just before this function returns, whichever
79668          ** comes first. */
79669          pFree = pSpace;
79670        }
79671      }
79672
79673      pPage->nOverflow = 0;
79674
79675      /* The next iteration of the do-loop balances the parent page. */
79676      releasePage(pPage);
79677      pCur->iPage--;
79678      assert( pCur->iPage>=0 );
79679      pCur->pPage = pCur->apPage[pCur->iPage];
79680    }
79681  }while( rc==SQLITE_OK );
79682
79683  if( pFree ){
79684    sqlite3PageFree(pFree);
79685  }
79686  return rc;
79687}
79688
79689/* Overwrite content from pX into pDest.  Only do the write if the
79690** content is different from what is already there.
79691*/
79692static int btreeOverwriteContent(
79693  MemPage *pPage,           /* MemPage on which writing will occur */
79694  u8 *pDest,                /* Pointer to the place to start writing */
79695  const BtreePayload *pX,   /* Source of data to write */
79696  int iOffset,              /* Offset of first byte to write */
79697  int iAmt                  /* Number of bytes to be written */
79698){
79699  int nData = pX->nData - iOffset;
79700  if( nData<=0 ){
79701    /* Overwriting with zeros */
79702    int i;
79703    for(i=0; i<iAmt && pDest[i]==0; i++){}
79704    if( i<iAmt ){
79705      int rc = sqlite3PagerWrite(pPage->pDbPage);
79706      if( rc ) return rc;
79707      memset(pDest + i, 0, iAmt - i);
79708    }
79709  }else{
79710    if( nData<iAmt ){
79711      /* Mixed read data and zeros at the end.  Make a recursive call
79712      ** to write the zeros then fall through to write the real data */
79713      int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
79714                                 iAmt-nData);
79715      if( rc ) return rc;
79716      iAmt = nData;
79717    }
79718    if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
79719      int rc = sqlite3PagerWrite(pPage->pDbPage);
79720      if( rc ) return rc;
79721      /* In a corrupt database, it is possible for the source and destination
79722      ** buffers to overlap.  This is harmless since the database is already
79723      ** corrupt but it does cause valgrind and ASAN warnings.  So use
79724      ** memmove(). */
79725      memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
79726    }
79727  }
79728  return SQLITE_OK;
79729}
79730
79731/*
79732** Overwrite the cell that cursor pCur is pointing to with fresh content
79733** contained in pX.  In this variant, pCur is pointing to an overflow
79734** cell.
79735*/
79736static SQLITE_NOINLINE int btreeOverwriteOverflowCell(
79737  BtCursor *pCur,                     /* Cursor pointing to cell to overwrite */
79738  const BtreePayload *pX              /* Content to write into the cell */
79739){
79740  int iOffset;                        /* Next byte of pX->pData to write */
79741  int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
79742  int rc;                             /* Return code */
79743  MemPage *pPage = pCur->pPage;       /* Page being written */
79744  BtShared *pBt;                      /* Btree */
79745  Pgno ovflPgno;                      /* Next overflow page to write */
79746  u32 ovflPageSize;                   /* Size to write on overflow page */
79747
79748  assert( pCur->info.nLocal<nTotal );  /* pCur is an overflow cell */
79749
79750  /* Overwrite the local portion first */
79751  rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
79752                             0, pCur->info.nLocal);
79753  if( rc ) return rc;
79754
79755  /* Now overwrite the overflow pages */
79756  iOffset = pCur->info.nLocal;
79757  assert( nTotal>=0 );
79758  assert( iOffset>=0 );
79759  ovflPgno = get4byte(pCur->info.pPayload + iOffset);
79760  pBt = pPage->pBt;
79761  ovflPageSize = pBt->usableSize - 4;
79762  do{
79763    rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
79764    if( rc ) return rc;
79765    if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){
79766      rc = SQLITE_CORRUPT_PAGE(pPage);
79767    }else{
79768      if( iOffset+ovflPageSize<(u32)nTotal ){
79769        ovflPgno = get4byte(pPage->aData);
79770      }else{
79771        ovflPageSize = nTotal - iOffset;
79772      }
79773      rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
79774                                 iOffset, ovflPageSize);
79775    }
79776    sqlite3PagerUnref(pPage->pDbPage);
79777    if( rc ) return rc;
79778    iOffset += ovflPageSize;
79779  }while( iOffset<nTotal );
79780  return SQLITE_OK;
79781}
79782
79783/*
79784** Overwrite the cell that cursor pCur is pointing to with fresh content
79785** contained in pX.
79786*/
79787static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
79788  int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
79789  MemPage *pPage = pCur->pPage;       /* Page being written */
79790
79791  if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
79792   || pCur->info.pPayload < pPage->aData + pPage->cellOffset
79793  ){
79794    return SQLITE_CORRUPT_PAGE(pPage);
79795  }
79796  if( pCur->info.nLocal==nTotal ){
79797    /* The entire cell is local */
79798    return btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
79799                                 0, pCur->info.nLocal);
79800  }else{
79801    /* The cell contains overflow content */
79802    return btreeOverwriteOverflowCell(pCur, pX);
79803  }
79804}
79805
79806
79807/*
79808** Insert a new record into the BTree.  The content of the new record
79809** is described by the pX object.  The pCur cursor is used only to
79810** define what table the record should be inserted into, and is left
79811** pointing at a random location.
79812**
79813** For a table btree (used for rowid tables), only the pX.nKey value of
79814** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
79815** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
79816** hold the content of the row.
79817**
79818** For an index btree (used for indexes and WITHOUT ROWID tables), the
79819** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
79820** pX.pData,nData,nZero fields must be zero.
79821**
79822** If the seekResult parameter is non-zero, then a successful call to
79823** sqlite3BtreeIndexMoveto() to seek cursor pCur to (pKey,nKey) has already
79824** been performed.  In other words, if seekResult!=0 then the cursor
79825** is currently pointing to a cell that will be adjacent to the cell
79826** to be inserted.  If seekResult<0 then pCur points to a cell that is
79827** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
79828** that is larger than (pKey,nKey).
79829**
79830** If seekResult==0, that means pCur is pointing at some unknown location.
79831** In that case, this routine must seek the cursor to the correct insertion
79832** point for (pKey,nKey) before doing the insertion.  For index btrees,
79833** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
79834** key values and pX->aMem can be used instead of pX->pKey to avoid having
79835** to decode the key.
79836*/
79837SQLITE_PRIVATE int sqlite3BtreeInsert(
79838  BtCursor *pCur,                /* Insert data into the table of this cursor */
79839  const BtreePayload *pX,        /* Content of the row to be inserted */
79840  int flags,                     /* True if this is likely an append */
79841  int seekResult                 /* Result of prior IndexMoveto() call */
79842){
79843  int rc;
79844  int loc = seekResult;          /* -1: before desired location  +1: after */
79845  int szNew = 0;
79846  int idx;
79847  MemPage *pPage;
79848  Btree *p = pCur->pBtree;
79849  unsigned char *oldCell;
79850  unsigned char *newCell = 0;
79851
79852  assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
79853  assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
79854
79855  /* Save the positions of any other cursors open on this table.
79856  **
79857  ** In some cases, the call to btreeMoveto() below is a no-op. For
79858  ** example, when inserting data into a table with auto-generated integer
79859  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
79860  ** integer key to use. It then calls this function to actually insert the
79861  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
79862  ** that the cursor is already where it needs to be and returns without
79863  ** doing any work. To avoid thwarting these optimizations, it is important
79864  ** not to clear the cursor here.
79865  */
79866  if( pCur->curFlags & BTCF_Multiple ){
79867    rc = saveAllCursors(p->pBt, pCur->pgnoRoot, pCur);
79868    if( rc ) return rc;
79869    if( loc && pCur->iPage<0 ){
79870      /* This can only happen if the schema is corrupt such that there is more
79871      ** than one table or index with the same root page as used by the cursor.
79872      ** Which can only happen if the SQLITE_NoSchemaError flag was set when
79873      ** the schema was loaded. This cannot be asserted though, as a user might
79874      ** set the flag, load the schema, and then unset the flag.  */
79875      return SQLITE_CORRUPT_PGNO(pCur->pgnoRoot);
79876    }
79877  }
79878
79879  /* Ensure that the cursor is not in the CURSOR_FAULT state and that it
79880  ** points to a valid cell.
79881  */
79882  if( pCur->eState>=CURSOR_REQUIRESEEK ){
79883    testcase( pCur->eState==CURSOR_REQUIRESEEK );
79884    testcase( pCur->eState==CURSOR_FAULT );
79885    rc = moveToRoot(pCur);
79886    if( rc && rc!=SQLITE_EMPTY ) return rc;
79887  }
79888
79889  assert( cursorOwnsBtShared(pCur) );
79890  assert( (pCur->curFlags & BTCF_WriteFlag)!=0
79891              && p->pBt->inTransaction==TRANS_WRITE
79892              && (p->pBt->btsFlags & BTS_READ_ONLY)==0 );
79893  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
79894
79895  /* Assert that the caller has been consistent. If this cursor was opened
79896  ** expecting an index b-tree, then the caller should be inserting blob
79897  ** keys with no associated data. If the cursor was opened expecting an
79898  ** intkey table, the caller should be inserting integer keys with a
79899  ** blob of associated data.  */
79900  assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
79901
79902  if( pCur->pKeyInfo==0 ){
79903    assert( pX->pKey==0 );
79904    /* If this is an insert into a table b-tree, invalidate any incrblob
79905    ** cursors open on the row being replaced */
79906    if( p->hasIncrblobCur ){
79907      invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
79908    }
79909
79910    /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
79911    ** to a row with the same key as the new entry being inserted.
79912    */
79913#ifdef SQLITE_DEBUG
79914    if( flags & BTREE_SAVEPOSITION ){
79915      assert( pCur->curFlags & BTCF_ValidNKey );
79916      assert( pX->nKey==pCur->info.nKey );
79917      assert( loc==0 );
79918    }
79919#endif
79920
79921    /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
79922    ** that the cursor is not pointing to a row to be overwritten.
79923    ** So do a complete check.
79924    */
79925    if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
79926      /* The cursor is pointing to the entry that is to be
79927      ** overwritten */
79928      assert( pX->nData>=0 && pX->nZero>=0 );
79929      if( pCur->info.nSize!=0
79930       && pCur->info.nPayload==(u32)pX->nData+pX->nZero
79931      ){
79932        /* New entry is the same size as the old.  Do an overwrite */
79933        return btreeOverwriteCell(pCur, pX);
79934      }
79935      assert( loc==0 );
79936    }else if( loc==0 ){
79937      /* The cursor is *not* pointing to the cell to be overwritten, nor
79938      ** to an adjacent cell.  Move the cursor so that it is pointing either
79939      ** to the cell to be overwritten or an adjacent cell.
79940      */
79941      rc = sqlite3BtreeTableMoveto(pCur, pX->nKey,
79942               (flags & BTREE_APPEND)!=0, &loc);
79943      if( rc ) return rc;
79944    }
79945  }else{
79946    /* This is an index or a WITHOUT ROWID table */
79947
79948    /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
79949    ** to a row with the same key as the new entry being inserted.
79950    */
79951    assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
79952
79953    /* If the cursor is not already pointing either to the cell to be
79954    ** overwritten, or if a new cell is being inserted, if the cursor is
79955    ** not pointing to an immediately adjacent cell, then move the cursor
79956    ** so that it does.
79957    */
79958    if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
79959      if( pX->nMem ){
79960        UnpackedRecord r;
79961        r.pKeyInfo = pCur->pKeyInfo;
79962        r.aMem = pX->aMem;
79963        r.nField = pX->nMem;
79964        r.default_rc = 0;
79965        r.eqSeen = 0;
79966        rc = sqlite3BtreeIndexMoveto(pCur, &r, &loc);
79967      }else{
79968        rc = btreeMoveto(pCur, pX->pKey, pX->nKey,
79969                    (flags & BTREE_APPEND)!=0, &loc);
79970      }
79971      if( rc ) return rc;
79972    }
79973
79974    /* If the cursor is currently pointing to an entry to be overwritten
79975    ** and the new content is the same as as the old, then use the
79976    ** overwrite optimization.
79977    */
79978    if( loc==0 ){
79979      getCellInfo(pCur);
79980      if( pCur->info.nKey==pX->nKey ){
79981        BtreePayload x2;
79982        x2.pData = pX->pKey;
79983        x2.nData = pX->nKey;
79984        x2.nZero = 0;
79985        return btreeOverwriteCell(pCur, &x2);
79986      }
79987    }
79988  }
79989  assert( pCur->eState==CURSOR_VALID
79990       || (pCur->eState==CURSOR_INVALID && loc) || CORRUPT_DB );
79991
79992  pPage = pCur->pPage;
79993  assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
79994  assert( pPage->leaf || !pPage->intKey );
79995  if( pPage->nFree<0 ){
79996    if( NEVER(pCur->eState>CURSOR_INVALID) ){
79997     /* ^^^^^--- due to the moveToRoot() call above */
79998      rc = SQLITE_CORRUPT_PAGE(pPage);
79999    }else{
80000      rc = btreeComputeFreeSpace(pPage);
80001    }
80002    if( rc ) return rc;
80003  }
80004
80005  TRACE(("INSERT: table=%u nkey=%lld ndata=%u page=%u %s\n",
80006          pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
80007          loc==0 ? "overwrite" : "new entry"));
80008  assert( pPage->isInit || CORRUPT_DB );
80009  newCell = p->pBt->pTmpSpace;
80010  assert( newCell!=0 );
80011  assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT );
80012  if( flags & BTREE_PREFORMAT ){
80013    rc = SQLITE_OK;
80014    szNew = p->pBt->nPreformatSize;
80015    if( szNew<4 ){
80016      szNew = 4;
80017      newCell[3] = 0;
80018    }
80019    if( ISAUTOVACUUM(p->pBt) && szNew>pPage->maxLocal ){
80020      CellInfo info;
80021      pPage->xParseCell(pPage, newCell, &info);
80022      if( info.nPayload!=info.nLocal ){
80023        Pgno ovfl = get4byte(&newCell[szNew-4]);
80024        ptrmapPut(p->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
80025        if( NEVER(rc) ) goto end_insert;
80026      }
80027    }
80028  }else{
80029    rc = fillInCell(pPage, newCell, pX, &szNew);
80030    if( rc ) goto end_insert;
80031  }
80032  assert( szNew==pPage->xCellSize(pPage, newCell) );
80033  assert( szNew <= MX_CELL_SIZE(p->pBt) );
80034  idx = pCur->ix;
80035  pCur->info.nSize = 0;
80036  if( loc==0 ){
80037    CellInfo info;
80038    assert( idx>=0 );
80039    if( idx>=pPage->nCell ){
80040      return SQLITE_CORRUPT_PAGE(pPage);
80041    }
80042    rc = sqlite3PagerWrite(pPage->pDbPage);
80043    if( rc ){
80044      goto end_insert;
80045    }
80046    oldCell = findCell(pPage, idx);
80047    if( !pPage->leaf ){
80048      memcpy(newCell, oldCell, 4);
80049    }
80050    BTREE_CLEAR_CELL(rc, pPage, oldCell, info);
80051    testcase( pCur->curFlags & BTCF_ValidOvfl );
80052    invalidateOverflowCache(pCur);
80053    if( info.nSize==szNew && info.nLocal==info.nPayload
80054     && (!ISAUTOVACUUM(p->pBt) || szNew<pPage->minLocal)
80055    ){
80056      /* Overwrite the old cell with the new if they are the same size.
80057      ** We could also try to do this if the old cell is smaller, then add
80058      ** the leftover space to the free list.  But experiments show that
80059      ** doing that is no faster then skipping this optimization and just
80060      ** calling dropCell() and insertCell().
80061      **
80062      ** This optimization cannot be used on an autovacuum database if the
80063      ** new entry uses overflow pages, as the insertCell() call below is
80064      ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
80065      assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
80066      if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
80067        return SQLITE_CORRUPT_PAGE(pPage);
80068      }
80069      if( oldCell+szNew > pPage->aDataEnd ){
80070        return SQLITE_CORRUPT_PAGE(pPage);
80071      }
80072      memcpy(oldCell, newCell, szNew);
80073      return SQLITE_OK;
80074    }
80075    dropCell(pPage, idx, info.nSize, &rc);
80076    if( rc ) goto end_insert;
80077  }else if( loc<0 && pPage->nCell>0 ){
80078    assert( pPage->leaf );
80079    idx = ++pCur->ix;
80080    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
80081  }else{
80082    assert( pPage->leaf );
80083  }
80084  rc = insertCellFast(pPage, idx, newCell, szNew);
80085  assert( pPage->nOverflow==0 || rc==SQLITE_OK );
80086  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
80087
80088  /* If no error has occurred and pPage has an overflow cell, call balance()
80089  ** to redistribute the cells within the tree. Since balance() may move
80090  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
80091  ** variables.
80092  **
80093  ** Previous versions of SQLite called moveToRoot() to move the cursor
80094  ** back to the root page as balance() used to invalidate the contents
80095  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
80096  ** set the cursor state to "invalid". This makes common insert operations
80097  ** slightly faster.
80098  **
80099  ** There is a subtle but important optimization here too. When inserting
80100  ** multiple records into an intkey b-tree using a single cursor (as can
80101  ** happen while processing an "INSERT INTO ... SELECT" statement), it
80102  ** is advantageous to leave the cursor pointing to the last entry in
80103  ** the b-tree if possible. If the cursor is left pointing to the last
80104  ** entry in the table, and the next row inserted has an integer key
80105  ** larger than the largest existing key, it is possible to insert the
80106  ** row without seeking the cursor. This can be a big performance boost.
80107  */
80108  if( pPage->nOverflow ){
80109    assert( rc==SQLITE_OK );
80110    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
80111    rc = balance(pCur);
80112
80113    /* Must make sure nOverflow is reset to zero even if the balance()
80114    ** fails. Internal data structure corruption will result otherwise.
80115    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
80116    ** from trying to save the current position of the cursor.  */
80117    pCur->pPage->nOverflow = 0;
80118    pCur->eState = CURSOR_INVALID;
80119    if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
80120      btreeReleaseAllCursorPages(pCur);
80121      if( pCur->pKeyInfo ){
80122        assert( pCur->pKey==0 );
80123        pCur->pKey = sqlite3Malloc( pX->nKey );
80124        if( pCur->pKey==0 ){
80125          rc = SQLITE_NOMEM;
80126        }else{
80127          memcpy(pCur->pKey, pX->pKey, pX->nKey);
80128        }
80129      }
80130      pCur->eState = CURSOR_REQUIRESEEK;
80131      pCur->nKey = pX->nKey;
80132    }
80133  }
80134  assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
80135
80136end_insert:
80137  return rc;
80138}
80139
80140/*
80141** This function is used as part of copying the current row from cursor
80142** pSrc into cursor pDest. If the cursors are open on intkey tables, then
80143** parameter iKey is used as the rowid value when the record is copied
80144** into pDest. Otherwise, the record is copied verbatim.
80145**
80146** This function does not actually write the new value to cursor pDest.
80147** Instead, it creates and populates any required overflow pages and
80148** writes the data for the new cell into the BtShared.pTmpSpace buffer
80149** for the destination database. The size of the cell, in bytes, is left
80150** in BtShared.nPreformatSize. The caller completes the insertion by
80151** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
80152**
80153** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
80154*/
80155SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
80156  BtShared *pBt = pDest->pBt;
80157  u8 *aOut = pBt->pTmpSpace;    /* Pointer to next output buffer */
80158  const u8 *aIn;                /* Pointer to next input buffer */
80159  u32 nIn;                      /* Size of input buffer aIn[] */
80160  u32 nRem;                     /* Bytes of data still to copy */
80161
80162  getCellInfo(pSrc);
80163  if( pSrc->info.nPayload<0x80 ){
80164    *(aOut++) = pSrc->info.nPayload;
80165  }else{
80166    aOut += sqlite3PutVarint(aOut, pSrc->info.nPayload);
80167  }
80168  if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
80169  nIn = pSrc->info.nLocal;
80170  aIn = pSrc->info.pPayload;
80171  if( aIn+nIn>pSrc->pPage->aDataEnd ){
80172    return SQLITE_CORRUPT_PAGE(pSrc->pPage);
80173  }
80174  nRem = pSrc->info.nPayload;
80175  if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
80176    memcpy(aOut, aIn, nIn);
80177    pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
80178    return SQLITE_OK;
80179  }else{
80180    int rc = SQLITE_OK;
80181    Pager *pSrcPager = pSrc->pBt->pPager;
80182    u8 *pPgnoOut = 0;
80183    Pgno ovflIn = 0;
80184    DbPage *pPageIn = 0;
80185    MemPage *pPageOut = 0;
80186    u32 nOut;                     /* Size of output buffer aOut[] */
80187
80188    nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
80189    pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
80190    if( nOut<pSrc->info.nPayload ){
80191      pPgnoOut = &aOut[nOut];
80192      pBt->nPreformatSize += 4;
80193    }
80194
80195    if( nRem>nIn ){
80196      if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
80197        return SQLITE_CORRUPT_PAGE(pSrc->pPage);
80198      }
80199      ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
80200    }
80201
80202    do {
80203      nRem -= nOut;
80204      do{
80205        assert( nOut>0 );
80206        if( nIn>0 ){
80207          int nCopy = MIN(nOut, nIn);
80208          memcpy(aOut, aIn, nCopy);
80209          nOut -= nCopy;
80210          nIn -= nCopy;
80211          aOut += nCopy;
80212          aIn += nCopy;
80213        }
80214        if( nOut>0 ){
80215          sqlite3PagerUnref(pPageIn);
80216          pPageIn = 0;
80217          rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
80218          if( rc==SQLITE_OK ){
80219            aIn = (const u8*)sqlite3PagerGetData(pPageIn);
80220            ovflIn = get4byte(aIn);
80221            aIn += 4;
80222            nIn = pSrc->pBt->usableSize - 4;
80223          }
80224        }
80225      }while( rc==SQLITE_OK && nOut>0 );
80226
80227      if( rc==SQLITE_OK && nRem>0 && ALWAYS(pPgnoOut) ){
80228        Pgno pgnoNew;
80229        MemPage *pNew = 0;
80230        rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
80231        put4byte(pPgnoOut, pgnoNew);
80232        if( ISAUTOVACUUM(pBt) && pPageOut ){
80233          ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
80234        }
80235        releasePage(pPageOut);
80236        pPageOut = pNew;
80237        if( pPageOut ){
80238          pPgnoOut = pPageOut->aData;
80239          put4byte(pPgnoOut, 0);
80240          aOut = &pPgnoOut[4];
80241          nOut = MIN(pBt->usableSize - 4, nRem);
80242        }
80243      }
80244    }while( nRem>0 && rc==SQLITE_OK );
80245
80246    releasePage(pPageOut);
80247    sqlite3PagerUnref(pPageIn);
80248    return rc;
80249  }
80250}
80251
80252/*
80253** Delete the entry that the cursor is pointing to.
80254**
80255** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
80256** the cursor is left pointing at an arbitrary location after the delete.
80257** But if that bit is set, then the cursor is left in a state such that
80258** the next call to BtreeNext() or BtreePrev() moves it to the same row
80259** as it would have been on if the call to BtreeDelete() had been omitted.
80260**
80261** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
80262** associated with a single table entry and its indexes.  Only one of those
80263** deletes is considered the "primary" delete.  The primary delete occurs
80264** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
80265** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
80266** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
80267** but which might be used by alternative storage engines.
80268*/
80269SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
80270  Btree *p = pCur->pBtree;
80271  BtShared *pBt = p->pBt;
80272  int rc;                    /* Return code */
80273  MemPage *pPage;            /* Page to delete cell from */
80274  unsigned char *pCell;      /* Pointer to cell to delete */
80275  int iCellIdx;              /* Index of cell to delete */
80276  int iCellDepth;            /* Depth of node containing pCell */
80277  CellInfo info;             /* Size of the cell being deleted */
80278  u8 bPreserve;              /* Keep cursor valid.  2 for CURSOR_SKIPNEXT */
80279
80280  assert( cursorOwnsBtShared(pCur) );
80281  assert( pBt->inTransaction==TRANS_WRITE );
80282  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
80283  assert( pCur->curFlags & BTCF_WriteFlag );
80284  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
80285  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
80286  assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
80287  if( pCur->eState!=CURSOR_VALID ){
80288    if( pCur->eState>=CURSOR_REQUIRESEEK ){
80289      rc = btreeRestoreCursorPosition(pCur);
80290      assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
80291      if( rc || pCur->eState!=CURSOR_VALID ) return rc;
80292    }else{
80293      return SQLITE_CORRUPT_PGNO(pCur->pgnoRoot);
80294    }
80295  }
80296  assert( pCur->eState==CURSOR_VALID );
80297
80298  iCellDepth = pCur->iPage;
80299  iCellIdx = pCur->ix;
80300  pPage = pCur->pPage;
80301  if( pPage->nCell<=iCellIdx ){
80302    return SQLITE_CORRUPT_PAGE(pPage);
80303  }
80304  pCell = findCell(pPage, iCellIdx);
80305  if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
80306    return SQLITE_CORRUPT_PAGE(pPage);
80307  }
80308  if( pCell<&pPage->aCellIdx[pPage->nCell] ){
80309    return SQLITE_CORRUPT_PAGE(pPage);
80310  }
80311
80312  /* If the BTREE_SAVEPOSITION bit is on, then the cursor position must
80313  ** be preserved following this delete operation. If the current delete
80314  ** will cause a b-tree rebalance, then this is done by saving the cursor
80315  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
80316  ** returning.
80317  **
80318  ** If the current delete will not cause a rebalance, then the cursor
80319  ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
80320  ** before or after the deleted entry.
80321  **
80322  ** The bPreserve value records which path is required:
80323  **
80324  **    bPreserve==0         Not necessary to save the cursor position
80325  **    bPreserve==1         Use CURSOR_REQUIRESEEK to save the cursor position
80326  **    bPreserve==2         Cursor won't move.  Set CURSOR_SKIPNEXT.
80327  */
80328  bPreserve = (flags & BTREE_SAVEPOSITION)!=0;
80329  if( bPreserve ){
80330    if( !pPage->leaf
80331     || (pPage->nFree+pPage->xCellSize(pPage,pCell)+2) >
80332                                                   (int)(pBt->usableSize*2/3)
80333     || pPage->nCell==1  /* See dbfuzz001.test for a test case */
80334    ){
80335      /* A b-tree rebalance will be required after deleting this entry.
80336      ** Save the cursor key.  */
80337      rc = saveCursorKey(pCur);
80338      if( rc ) return rc;
80339    }else{
80340      bPreserve = 2;
80341    }
80342  }
80343
80344  /* If the page containing the entry to delete is not a leaf page, move
80345  ** the cursor to the largest entry in the tree that is smaller than
80346  ** the entry being deleted. This cell will replace the cell being deleted
80347  ** from the internal node. The 'previous' entry is used for this instead
80348  ** of the 'next' entry, as the previous entry is always a part of the
80349  ** sub-tree headed by the child page of the cell being deleted. This makes
80350  ** balancing the tree following the delete operation easier.  */
80351  if( !pPage->leaf ){
80352    rc = sqlite3BtreePrevious(pCur, 0);
80353    assert( rc!=SQLITE_DONE );
80354    if( rc ) return rc;
80355  }
80356
80357  /* Save the positions of any other cursors open on this table before
80358  ** making any modifications.  */
80359  if( pCur->curFlags & BTCF_Multiple ){
80360    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
80361    if( rc ) return rc;
80362  }
80363
80364  /* If this is a delete operation to remove a row from a table b-tree,
80365  ** invalidate any incrblob cursors open on the row being deleted.  */
80366  if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
80367    invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
80368  }
80369
80370  /* Make the page containing the entry to be deleted writable. Then free any
80371  ** overflow pages associated with the entry and finally remove the cell
80372  ** itself from within the page.  */
80373  rc = sqlite3PagerWrite(pPage->pDbPage);
80374  if( rc ) return rc;
80375  BTREE_CLEAR_CELL(rc, pPage, pCell, info);
80376  dropCell(pPage, iCellIdx, info.nSize, &rc);
80377  if( rc ) return rc;
80378
80379  /* If the cell deleted was not located on a leaf page, then the cursor
80380  ** is currently pointing to the largest entry in the sub-tree headed
80381  ** by the child-page of the cell that was just deleted from an internal
80382  ** node. The cell from the leaf node needs to be moved to the internal
80383  ** node to replace the deleted cell.  */
80384  if( !pPage->leaf ){
80385    MemPage *pLeaf = pCur->pPage;
80386    int nCell;
80387    Pgno n;
80388    unsigned char *pTmp;
80389
80390    if( pLeaf->nFree<0 ){
80391      rc = btreeComputeFreeSpace(pLeaf);
80392      if( rc ) return rc;
80393    }
80394    if( iCellDepth<pCur->iPage-1 ){
80395      n = pCur->apPage[iCellDepth+1]->pgno;
80396    }else{
80397      n = pCur->pPage->pgno;
80398    }
80399    pCell = findCell(pLeaf, pLeaf->nCell-1);
80400    if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_PAGE(pLeaf);
80401    nCell = pLeaf->xCellSize(pLeaf, pCell);
80402    assert( MX_CELL_SIZE(pBt) >= nCell );
80403    pTmp = pBt->pTmpSpace;
80404    assert( pTmp!=0 );
80405    rc = sqlite3PagerWrite(pLeaf->pDbPage);
80406    if( rc==SQLITE_OK ){
80407      rc = insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n);
80408    }
80409    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
80410    if( rc ) return rc;
80411  }
80412
80413  /* Balance the tree. If the entry deleted was located on a leaf page,
80414  ** then the cursor still points to that page. In this case the first
80415  ** call to balance() repairs the tree, and the if(...) condition is
80416  ** never true.
80417  **
80418  ** Otherwise, if the entry deleted was on an internal node page, then
80419  ** pCur is pointing to the leaf page from which a cell was removed to
80420  ** replace the cell deleted from the internal node. This is slightly
80421  ** tricky as the leaf node may be underfull, and the internal node may
80422  ** be either under or overfull. In this case run the balancing algorithm
80423  ** on the leaf node first. If the balance proceeds far enough up the
80424  ** tree that we can be sure that any problem in the internal node has
80425  ** been corrected, so be it. Otherwise, after balancing the leaf node,
80426  ** walk the cursor up the tree to the internal node and balance it as
80427  ** well.  */
80428  assert( pCur->pPage->nOverflow==0 );
80429  assert( pCur->pPage->nFree>=0 );
80430  if( pCur->pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
80431    /* Optimization: If the free space is less than 2/3rds of the page,
80432    ** then balance() will always be a no-op.  No need to invoke it. */
80433    rc = SQLITE_OK;
80434  }else{
80435    rc = balance(pCur);
80436  }
80437  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
80438    releasePageNotNull(pCur->pPage);
80439    pCur->iPage--;
80440    while( pCur->iPage>iCellDepth ){
80441      releasePage(pCur->apPage[pCur->iPage--]);
80442    }
80443    pCur->pPage = pCur->apPage[pCur->iPage];
80444    rc = balance(pCur);
80445  }
80446
80447  if( rc==SQLITE_OK ){
80448    if( bPreserve>1 ){
80449      assert( (pCur->iPage==iCellDepth || CORRUPT_DB) );
80450      assert( pPage==pCur->pPage || CORRUPT_DB );
80451      assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
80452      pCur->eState = CURSOR_SKIPNEXT;
80453      if( iCellIdx>=pPage->nCell ){
80454        pCur->skipNext = -1;
80455        pCur->ix = pPage->nCell-1;
80456      }else{
80457        pCur->skipNext = 1;
80458      }
80459    }else{
80460      rc = moveToRoot(pCur);
80461      if( bPreserve ){
80462        btreeReleaseAllCursorPages(pCur);
80463        pCur->eState = CURSOR_REQUIRESEEK;
80464      }
80465      if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
80466    }
80467  }
80468  return rc;
80469}
80470
80471/*
80472** Create a new BTree table.  Write into *piTable the page
80473** number for the root page of the new table.
80474**
80475** The type of type is determined by the flags parameter.  Only the
80476** following values of flags are currently in use.  Other values for
80477** flags might not work:
80478**
80479**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
80480**     BTREE_ZERODATA                  Used for SQL indices
80481*/
80482static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
80483  BtShared *pBt = p->pBt;
80484  MemPage *pRoot;
80485  Pgno pgnoRoot;
80486  int rc;
80487  int ptfFlags;          /* Page-type flags for the root page of new table */
80488
80489  assert( sqlite3BtreeHoldsMutex(p) );
80490  assert( pBt->inTransaction==TRANS_WRITE );
80491  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
80492
80493#ifdef SQLITE_OMIT_AUTOVACUUM
80494  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
80495  if( rc ){
80496    return rc;
80497  }
80498#else
80499  if( pBt->autoVacuum ){
80500    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
80501    MemPage *pPageMove; /* The page to move to. */
80502
80503    /* Creating a new table may probably require moving an existing database
80504    ** to make room for the new tables root page. In case this page turns
80505    ** out to be an overflow page, delete all overflow page-map caches
80506    ** held by open cursors.
80507    */
80508    invalidateAllOverflowCache(pBt);
80509
80510    /* Read the value of meta[3] from the database to determine where the
80511    ** root page of the new table should go. meta[3] is the largest root-page
80512    ** created so far, so the new root-page is (meta[3]+1).
80513    */
80514    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
80515    if( pgnoRoot>btreePagecount(pBt) ){
80516      return SQLITE_CORRUPT_PGNO(pgnoRoot);
80517    }
80518    pgnoRoot++;
80519
80520    /* The new root-page may not be allocated on a pointer-map page, or the
80521    ** PENDING_BYTE page.
80522    */
80523    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
80524        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
80525      pgnoRoot++;
80526    }
80527    assert( pgnoRoot>=3 );
80528
80529    /* Allocate a page. The page that currently resides at pgnoRoot will
80530    ** be moved to the allocated page (unless the allocated page happens
80531    ** to reside at pgnoRoot).
80532    */
80533    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
80534    if( rc!=SQLITE_OK ){
80535      return rc;
80536    }
80537
80538    if( pgnoMove!=pgnoRoot ){
80539      /* pgnoRoot is the page that will be used for the root-page of
80540      ** the new table (assuming an error did not occur). But we were
80541      ** allocated pgnoMove. If required (i.e. if it was not allocated
80542      ** by extending the file), the current page at position pgnoMove
80543      ** is already journaled.
80544      */
80545      u8 eType = 0;
80546      Pgno iPtrPage = 0;
80547
80548      /* Save the positions of any open cursors. This is required in
80549      ** case they are holding a reference to an xFetch reference
80550      ** corresponding to page pgnoRoot.  */
80551      rc = saveAllCursors(pBt, 0, 0);
80552      releasePage(pPageMove);
80553      if( rc!=SQLITE_OK ){
80554        return rc;
80555      }
80556
80557      /* Move the page currently at pgnoRoot to pgnoMove. */
80558      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
80559      if( rc!=SQLITE_OK ){
80560        return rc;
80561      }
80562      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
80563      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
80564        rc = SQLITE_CORRUPT_PGNO(pgnoRoot);
80565      }
80566      if( rc!=SQLITE_OK ){
80567        releasePage(pRoot);
80568        return rc;
80569      }
80570      assert( eType!=PTRMAP_ROOTPAGE );
80571      assert( eType!=PTRMAP_FREEPAGE );
80572      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
80573      releasePage(pRoot);
80574
80575      /* Obtain the page at pgnoRoot */
80576      if( rc!=SQLITE_OK ){
80577        return rc;
80578      }
80579      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
80580      if( rc!=SQLITE_OK ){
80581        return rc;
80582      }
80583      rc = sqlite3PagerWrite(pRoot->pDbPage);
80584      if( rc!=SQLITE_OK ){
80585        releasePage(pRoot);
80586        return rc;
80587      }
80588    }else{
80589      pRoot = pPageMove;
80590    }
80591
80592    /* Update the pointer-map and meta-data with the new root-page number. */
80593    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
80594    if( rc ){
80595      releasePage(pRoot);
80596      return rc;
80597    }
80598
80599    /* When the new root page was allocated, page 1 was made writable in
80600    ** order either to increase the database filesize, or to decrement the
80601    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
80602    */
80603    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
80604    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
80605    if( NEVER(rc) ){
80606      releasePage(pRoot);
80607      return rc;
80608    }
80609
80610  }else{
80611    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
80612    if( rc ) return rc;
80613  }
80614#endif
80615  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
80616  if( createTabFlags & BTREE_INTKEY ){
80617    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
80618  }else{
80619    ptfFlags = PTF_ZERODATA | PTF_LEAF;
80620  }
80621  zeroPage(pRoot, ptfFlags);
80622  sqlite3PagerUnref(pRoot->pDbPage);
80623  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
80624  *piTable = pgnoRoot;
80625  return SQLITE_OK;
80626}
80627SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
80628  int rc;
80629  sqlite3BtreeEnter(p);
80630  rc = btreeCreateTable(p, piTable, flags);
80631  sqlite3BtreeLeave(p);
80632  return rc;
80633}
80634
80635/*
80636** Erase the given database page and all its children.  Return
80637** the page to the freelist.
80638*/
80639static int clearDatabasePage(
80640  BtShared *pBt,           /* The BTree that contains the table */
80641  Pgno pgno,               /* Page number to clear */
80642  int freePageFlag,        /* Deallocate page if true */
80643  i64 *pnChange            /* Add number of Cells freed to this counter */
80644){
80645  MemPage *pPage;
80646  int rc;
80647  unsigned char *pCell;
80648  int i;
80649  int hdr;
80650  CellInfo info;
80651
80652  assert( sqlite3_mutex_held(pBt->mutex) );
80653  if( pgno>btreePagecount(pBt) ){
80654    return SQLITE_CORRUPT_PGNO(pgno);
80655  }
80656  rc = getAndInitPage(pBt, pgno, &pPage, 0);
80657  if( rc ) return rc;
80658  if( (pBt->openFlags & BTREE_SINGLE)==0
80659   && sqlite3PagerPageRefcount(pPage->pDbPage) != (1 + (pgno==1))
80660  ){
80661    rc = SQLITE_CORRUPT_PAGE(pPage);
80662    goto cleardatabasepage_out;
80663  }
80664  hdr = pPage->hdrOffset;
80665  for(i=0; i<pPage->nCell; i++){
80666    pCell = findCell(pPage, i);
80667    if( !pPage->leaf ){
80668      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
80669      if( rc ) goto cleardatabasepage_out;
80670    }
80671    BTREE_CLEAR_CELL(rc, pPage, pCell, info);
80672    if( rc ) goto cleardatabasepage_out;
80673  }
80674  if( !pPage->leaf ){
80675    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
80676    if( rc ) goto cleardatabasepage_out;
80677    if( pPage->intKey ) pnChange = 0;
80678  }
80679  if( pnChange ){
80680    testcase( !pPage->intKey );
80681    *pnChange += pPage->nCell;
80682  }
80683  if( freePageFlag ){
80684    freePage(pPage, &rc);
80685  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
80686    zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
80687  }
80688
80689cleardatabasepage_out:
80690  releasePage(pPage);
80691  return rc;
80692}
80693
80694/*
80695** Delete all information from a single table in the database.  iTable is
80696** the page number of the root of the table.  After this routine returns,
80697** the root page is empty, but still exists.
80698**
80699** This routine will fail with SQLITE_LOCKED if there are any open
80700** read cursors on the table.  Open write cursors are moved to the
80701** root of the table.
80702**
80703** If pnChange is not NULL, then the integer value pointed to by pnChange
80704** is incremented by the number of entries in the table.
80705*/
80706SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, i64 *pnChange){
80707  int rc;
80708  BtShared *pBt = p->pBt;
80709  sqlite3BtreeEnter(p);
80710  assert( p->inTrans==TRANS_WRITE );
80711
80712  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
80713
80714  if( SQLITE_OK==rc ){
80715    /* Invalidate all incrblob cursors open on table iTable (assuming iTable
80716    ** is the root of a table b-tree - if it is not, the following call is
80717    ** a no-op).  */
80718    if( p->hasIncrblobCur ){
80719      invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
80720    }
80721    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
80722  }
80723  sqlite3BtreeLeave(p);
80724  return rc;
80725}
80726
80727/*
80728** Delete all information from the single table that pCur is open on.
80729**
80730** This routine only work for pCur on an ephemeral table.
80731*/
80732SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
80733  return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
80734}
80735
80736/*
80737** Erase all information in a table and add the root of the table to
80738** the freelist.  Except, the root of the principle table (the one on
80739** page 1) is never added to the freelist.
80740**
80741** This routine will fail with SQLITE_LOCKED if there are any open
80742** cursors on the table.
80743**
80744** If AUTOVACUUM is enabled and the page at iTable is not the last
80745** root page in the database file, then the last root page
80746** in the database file is moved into the slot formerly occupied by
80747** iTable and that last slot formerly occupied by the last root page
80748** is added to the freelist instead of iTable.  In this say, all
80749** root pages are kept at the beginning of the database file, which
80750** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
80751** page number that used to be the last root page in the file before
80752** the move.  If no page gets moved, *piMoved is set to 0.
80753** The last root page is recorded in meta[3] and the value of
80754** meta[3] is updated by this procedure.
80755*/
80756static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
80757  int rc;
80758  MemPage *pPage = 0;
80759  BtShared *pBt = p->pBt;
80760
80761  assert( sqlite3BtreeHoldsMutex(p) );
80762  assert( p->inTrans==TRANS_WRITE );
80763  assert( iTable>=2 );
80764  if( iTable>btreePagecount(pBt) ){
80765    return SQLITE_CORRUPT_PGNO(iTable);
80766  }
80767
80768  rc = sqlite3BtreeClearTable(p, iTable, 0);
80769  if( rc ) return rc;
80770  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
80771  if( NEVER(rc) ){
80772    releasePage(pPage);
80773    return rc;
80774  }
80775
80776  *piMoved = 0;
80777
80778#ifdef SQLITE_OMIT_AUTOVACUUM
80779  freePage(pPage, &rc);
80780  releasePage(pPage);
80781#else
80782  if( pBt->autoVacuum ){
80783    Pgno maxRootPgno;
80784    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
80785
80786    if( iTable==maxRootPgno ){
80787      /* If the table being dropped is the table with the largest root-page
80788      ** number in the database, put the root page on the free list.
80789      */
80790      freePage(pPage, &rc);
80791      releasePage(pPage);
80792      if( rc!=SQLITE_OK ){
80793        return rc;
80794      }
80795    }else{
80796      /* The table being dropped does not have the largest root-page
80797      ** number in the database. So move the page that does into the
80798      ** gap left by the deleted root-page.
80799      */
80800      MemPage *pMove;
80801      releasePage(pPage);
80802      rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
80803      if( rc!=SQLITE_OK ){
80804        return rc;
80805      }
80806      rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
80807      releasePage(pMove);
80808      if( rc!=SQLITE_OK ){
80809        return rc;
80810      }
80811      pMove = 0;
80812      rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
80813      freePage(pMove, &rc);
80814      releasePage(pMove);
80815      if( rc!=SQLITE_OK ){
80816        return rc;
80817      }
80818      *piMoved = maxRootPgno;
80819    }
80820
80821    /* Set the new 'max-root-page' value in the database header. This
80822    ** is the old value less one, less one more if that happens to
80823    ** be a root-page number, less one again if that is the
80824    ** PENDING_BYTE_PAGE.
80825    */
80826    maxRootPgno--;
80827    while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
80828           || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
80829      maxRootPgno--;
80830    }
80831    assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
80832
80833    rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
80834  }else{
80835    freePage(pPage, &rc);
80836    releasePage(pPage);
80837  }
80838#endif
80839  return rc;
80840}
80841SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
80842  int rc;
80843  sqlite3BtreeEnter(p);
80844  rc = btreeDropTable(p, iTable, piMoved);
80845  sqlite3BtreeLeave(p);
80846  return rc;
80847}
80848
80849
80850/*
80851** This function may only be called if the b-tree connection already
80852** has a read or write transaction open on the database.
80853**
80854** Read the meta-information out of a database file.  Meta[0]
80855** is the number of free pages currently in the database.  Meta[1]
80856** through meta[15] are available for use by higher layers.  Meta[0]
80857** is read-only, the others are read/write.
80858**
80859** The schema layer numbers meta values differently.  At the schema
80860** layer (and the SetCookie and ReadCookie opcodes) the number of
80861** free pages is not visible.  So Cookie[0] is the same as Meta[1].
80862**
80863** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
80864** of reading the value out of the header, it instead loads the "DataVersion"
80865** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
80866** database file.  It is a number computed by the pager.  But its access
80867** pattern is the same as header meta values, and so it is convenient to
80868** read it from this routine.
80869*/
80870SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
80871  BtShared *pBt = p->pBt;
80872
80873  sqlite3BtreeEnter(p);
80874  assert( p->inTrans>TRANS_NONE );
80875  assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
80876  assert( pBt->pPage1 );
80877  assert( idx>=0 && idx<=15 );
80878
80879  if( idx==BTREE_DATA_VERSION ){
80880    *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
80881  }else{
80882    *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
80883  }
80884
80885  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
80886  ** database, mark the database as read-only.  */
80887#ifdef SQLITE_OMIT_AUTOVACUUM
80888  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
80889    pBt->btsFlags |= BTS_READ_ONLY;
80890  }
80891#endif
80892
80893  sqlite3BtreeLeave(p);
80894}
80895
80896/*
80897** Write meta-information back into the database.  Meta[0] is
80898** read-only and may not be written.
80899*/
80900SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
80901  BtShared *pBt = p->pBt;
80902  unsigned char *pP1;
80903  int rc;
80904  assert( idx>=1 && idx<=15 );
80905  sqlite3BtreeEnter(p);
80906  assert( p->inTrans==TRANS_WRITE );
80907  assert( pBt->pPage1!=0 );
80908  pP1 = pBt->pPage1->aData;
80909  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
80910  if( rc==SQLITE_OK ){
80911    put4byte(&pP1[36 + idx*4], iMeta);
80912#ifndef SQLITE_OMIT_AUTOVACUUM
80913    if( idx==BTREE_INCR_VACUUM ){
80914      assert( pBt->autoVacuum || iMeta==0 );
80915      assert( iMeta==0 || iMeta==1 );
80916      pBt->incrVacuum = (u8)iMeta;
80917    }
80918#endif
80919  }
80920  sqlite3BtreeLeave(p);
80921  return rc;
80922}
80923
80924/*
80925** The first argument, pCur, is a cursor opened on some b-tree. Count the
80926** number of entries in the b-tree and write the result to *pnEntry.
80927**
80928** SQLITE_OK is returned if the operation is successfully executed.
80929** Otherwise, if an error is encountered (i.e. an IO error or database
80930** corruption) an SQLite error code is returned.
80931*/
80932SQLITE_PRIVATE int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
80933  i64 nEntry = 0;                      /* Value to return in *pnEntry */
80934  int rc;                              /* Return code */
80935
80936  rc = moveToRoot(pCur);
80937  if( rc==SQLITE_EMPTY ){
80938    *pnEntry = 0;
80939    return SQLITE_OK;
80940  }
80941
80942  /* Unless an error occurs, the following loop runs one iteration for each
80943  ** page in the B-Tree structure (not including overflow pages).
80944  */
80945  while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
80946    int iIdx;                          /* Index of child node in parent */
80947    MemPage *pPage;                    /* Current page of the b-tree */
80948
80949    /* If this is a leaf page or the tree is not an int-key tree, then
80950    ** this page contains countable entries. Increment the entry counter
80951    ** accordingly.
80952    */
80953    pPage = pCur->pPage;
80954    if( pPage->leaf || !pPage->intKey ){
80955      nEntry += pPage->nCell;
80956    }
80957
80958    /* pPage is a leaf node. This loop navigates the cursor so that it
80959    ** points to the first interior cell that it points to the parent of
80960    ** the next page in the tree that has not yet been visited. The
80961    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
80962    ** of the page, or to the number of cells in the page if the next page
80963    ** to visit is the right-child of its parent.
80964    **
80965    ** If all pages in the tree have been visited, return SQLITE_OK to the
80966    ** caller.
80967    */
80968    if( pPage->leaf ){
80969      do {
80970        if( pCur->iPage==0 ){
80971          /* All pages of the b-tree have been visited. Return successfully. */
80972          *pnEntry = nEntry;
80973          return moveToRoot(pCur);
80974        }
80975        moveToParent(pCur);
80976      }while ( pCur->ix>=pCur->pPage->nCell );
80977
80978      pCur->ix++;
80979      pPage = pCur->pPage;
80980    }
80981
80982    /* Descend to the child node of the cell that the cursor currently
80983    ** points at. This is the right-child if (iIdx==pPage->nCell).
80984    */
80985    iIdx = pCur->ix;
80986    if( iIdx==pPage->nCell ){
80987      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
80988    }else{
80989      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
80990    }
80991  }
80992
80993  /* An error has occurred. Return an error code. */
80994  return rc;
80995}
80996
80997/*
80998** Return the pager associated with a BTree.  This routine is used for
80999** testing and debugging only.
81000*/
81001SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
81002  return p->pBt->pPager;
81003}
81004
81005#ifndef SQLITE_OMIT_INTEGRITY_CHECK
81006/*
81007** Record an OOM error during integrity_check
81008*/
81009static void checkOom(IntegrityCk *pCheck){
81010  pCheck->rc = SQLITE_NOMEM;
81011  pCheck->mxErr = 0;  /* Causes integrity_check processing to stop */
81012  if( pCheck->nErr==0 ) pCheck->nErr++;
81013}
81014
81015/*
81016** Invoke the progress handler, if appropriate.  Also check for an
81017** interrupt.
81018*/
81019static void checkProgress(IntegrityCk *pCheck){
81020  sqlite3 *db = pCheck->db;
81021  if( AtomicLoad(&db->u1.isInterrupted) ){
81022    pCheck->rc = SQLITE_INTERRUPT;
81023    pCheck->nErr++;
81024    pCheck->mxErr = 0;
81025  }
81026#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
81027  if( db->xProgress ){
81028    assert( db->nProgressOps>0 );
81029    pCheck->nStep++;
81030    if( (pCheck->nStep % db->nProgressOps)==0
81031     && db->xProgress(db->pProgressArg)
81032    ){
81033      pCheck->rc = SQLITE_INTERRUPT;
81034      pCheck->nErr++;
81035      pCheck->mxErr = 0;
81036    }
81037  }
81038#endif
81039}
81040
81041/*
81042** Append a message to the error message string.
81043*/
81044static void checkAppendMsg(
81045  IntegrityCk *pCheck,
81046  const char *zFormat,
81047  ...
81048){
81049  va_list ap;
81050  checkProgress(pCheck);
81051  if( !pCheck->mxErr ) return;
81052  pCheck->mxErr--;
81053  pCheck->nErr++;
81054  va_start(ap, zFormat);
81055  if( pCheck->errMsg.nChar ){
81056    sqlite3_str_append(&pCheck->errMsg, "\n", 1);
81057  }
81058  if( pCheck->zPfx ){
81059    sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx,
81060                        pCheck->v0, pCheck->v1, pCheck->v2);
81061  }
81062  sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
81063  va_end(ap);
81064  if( pCheck->errMsg.accError==SQLITE_NOMEM ){
81065    checkOom(pCheck);
81066  }
81067}
81068#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
81069
81070#ifndef SQLITE_OMIT_INTEGRITY_CHECK
81071
81072/*
81073** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
81074** corresponds to page iPg is already set.
81075*/
81076static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
81077  assert( pCheck->aPgRef!=0 );
81078  assert( iPg<=pCheck->nCkPage && sizeof(pCheck->aPgRef[0])==1 );
81079  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
81080}
81081
81082/*
81083** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
81084*/
81085static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
81086  assert( pCheck->aPgRef!=0 );
81087  assert( iPg<=pCheck->nCkPage && sizeof(pCheck->aPgRef[0])==1 );
81088  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
81089}
81090
81091
81092/*
81093** Add 1 to the reference count for page iPage.  If this is the second
81094** reference to the page, add an error message to pCheck->zErrMsg.
81095** Return 1 if there are 2 or more references to the page and 0 if
81096** if this is the first reference to the page.
81097**
81098** Also check that the page number is in bounds.
81099*/
81100static int checkRef(IntegrityCk *pCheck, Pgno iPage){
81101  if( iPage>pCheck->nCkPage || iPage==0 ){
81102    checkAppendMsg(pCheck, "invalid page number %u", iPage);
81103    return 1;
81104  }
81105  if( getPageReferenced(pCheck, iPage) ){
81106    checkAppendMsg(pCheck, "2nd reference to page %u", iPage);
81107    return 1;
81108  }
81109  setPageReferenced(pCheck, iPage);
81110  return 0;
81111}
81112
81113#ifndef SQLITE_OMIT_AUTOVACUUM
81114/*
81115** Check that the entry in the pointer-map for page iChild maps to
81116** page iParent, pointer type ptrType. If not, append an error message
81117** to pCheck.
81118*/
81119static void checkPtrmap(
81120  IntegrityCk *pCheck,   /* Integrity check context */
81121  Pgno iChild,           /* Child page number */
81122  u8 eType,              /* Expected pointer map type */
81123  Pgno iParent           /* Expected pointer map parent page number */
81124){
81125  int rc;
81126  u8 ePtrmapType;
81127  Pgno iPtrmapParent;
81128
81129  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
81130  if( rc!=SQLITE_OK ){
81131    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) checkOom(pCheck);
81132    checkAppendMsg(pCheck, "Failed to read ptrmap key=%u", iChild);
81133    return;
81134  }
81135
81136  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
81137    checkAppendMsg(pCheck,
81138      "Bad ptr map entry key=%u expected=(%u,%u) got=(%u,%u)",
81139      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
81140  }
81141}
81142#endif
81143
81144/*
81145** Check the integrity of the freelist or of an overflow page list.
81146** Verify that the number of pages on the list is N.
81147*/
81148static void checkList(
81149  IntegrityCk *pCheck,  /* Integrity checking context */
81150  int isFreeList,       /* True for a freelist.  False for overflow page list */
81151  Pgno iPage,           /* Page number for first page in the list */
81152  u32 N                 /* Expected number of pages in the list */
81153){
81154  int i;
81155  u32 expected = N;
81156  int nErrAtStart = pCheck->nErr;
81157  while( iPage!=0 && pCheck->mxErr ){
81158    DbPage *pOvflPage;
81159    unsigned char *pOvflData;
81160    if( checkRef(pCheck, iPage) ) break;
81161    N--;
81162    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
81163      checkAppendMsg(pCheck, "failed to get page %u", iPage);
81164      break;
81165    }
81166    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
81167    if( isFreeList ){
81168      u32 n = (u32)get4byte(&pOvflData[4]);
81169#ifndef SQLITE_OMIT_AUTOVACUUM
81170      if( pCheck->pBt->autoVacuum ){
81171        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
81172      }
81173#endif
81174      if( n>pCheck->pBt->usableSize/4-2 ){
81175        checkAppendMsg(pCheck,
81176           "freelist leaf count too big on page %u", iPage);
81177        N--;
81178      }else{
81179        for(i=0; i<(int)n; i++){
81180          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
81181#ifndef SQLITE_OMIT_AUTOVACUUM
81182          if( pCheck->pBt->autoVacuum ){
81183            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
81184          }
81185#endif
81186          checkRef(pCheck, iFreePage);
81187        }
81188        N -= n;
81189      }
81190    }
81191#ifndef SQLITE_OMIT_AUTOVACUUM
81192    else{
81193      /* If this database supports auto-vacuum and iPage is not the last
81194      ** page in this overflow list, check that the pointer-map entry for
81195      ** the following page matches iPage.
81196      */
81197      if( pCheck->pBt->autoVacuum && N>0 ){
81198        i = get4byte(pOvflData);
81199        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
81200      }
81201    }
81202#endif
81203    iPage = get4byte(pOvflData);
81204    sqlite3PagerUnref(pOvflPage);
81205  }
81206  if( N && nErrAtStart==pCheck->nErr ){
81207    checkAppendMsg(pCheck,
81208      "%s is %u but should be %u",
81209      isFreeList ? "size" : "overflow list length",
81210      expected-N, expected);
81211  }
81212}
81213#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
81214
81215/*
81216** An implementation of a min-heap.
81217**
81218** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
81219** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
81220** and aHeap[N*2+1].
81221**
81222** The heap property is this:  Every node is less than or equal to both
81223** of its daughter nodes.  A consequence of the heap property is that the
81224** root node aHeap[1] is always the minimum value currently in the heap.
81225**
81226** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
81227** the heap, preserving the heap property.  The btreeHeapPull() routine
81228** removes the root element from the heap (the minimum value in the heap)
81229** and then moves other nodes around as necessary to preserve the heap
81230** property.
81231**
81232** This heap is used for cell overlap and coverage testing.  Each u32
81233** entry represents the span of a cell or freeblock on a btree page.
81234** The upper 16 bits are the index of the first byte of a range and the
81235** lower 16 bits are the index of the last byte of that range.
81236*/
81237static void btreeHeapInsert(u32 *aHeap, u32 x){
81238  u32 j, i;
81239  assert( aHeap!=0 );
81240  i = ++aHeap[0];
81241  aHeap[i] = x;
81242  while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
81243    x = aHeap[j];
81244    aHeap[j] = aHeap[i];
81245    aHeap[i] = x;
81246    i = j;
81247  }
81248}
81249static int btreeHeapPull(u32 *aHeap, u32 *pOut){
81250  u32 j, i, x;
81251  if( (x = aHeap[0])==0 ) return 0;
81252  *pOut = aHeap[1];
81253  aHeap[1] = aHeap[x];
81254  aHeap[x] = 0xffffffff;
81255  aHeap[0]--;
81256  i = 1;
81257  while( (j = i*2)<=aHeap[0] ){
81258    if( aHeap[j]>aHeap[j+1] ) j++;
81259    if( aHeap[i]<aHeap[j] ) break;
81260    x = aHeap[i];
81261    aHeap[i] = aHeap[j];
81262    aHeap[j] = x;
81263    i = j;
81264  }
81265  return 1;
81266}
81267
81268#ifndef SQLITE_OMIT_INTEGRITY_CHECK
81269/*
81270** Do various sanity checks on a single page of a tree.  Return
81271** the tree depth.  Root pages return 0.  Parents of root pages
81272** return 1, and so forth.
81273**
81274** These checks are done:
81275**
81276**      1.  Make sure that cells and freeblocks do not overlap
81277**          but combine to completely cover the page.
81278**      2.  Make sure integer cell keys are in order.
81279**      3.  Check the integrity of overflow pages.
81280**      4.  Recursively call checkTreePage on all children.
81281**      5.  Verify that the depth of all children is the same.
81282*/
81283static int checkTreePage(
81284  IntegrityCk *pCheck,  /* Context for the sanity check */
81285  Pgno iPage,           /* Page number of the page to check */
81286  i64 *piMinKey,        /* Write minimum integer primary key here */
81287  i64 maxKey            /* Error if integer primary key greater than this */
81288){
81289  MemPage *pPage = 0;      /* The page being analyzed */
81290  int i;                   /* Loop counter */
81291  int rc;                  /* Result code from subroutine call */
81292  int depth = -1, d2;      /* Depth of a subtree */
81293  int pgno;                /* Page number */
81294  int nFrag;               /* Number of fragmented bytes on the page */
81295  int hdr;                 /* Offset to the page header */
81296  int cellStart;           /* Offset to the start of the cell pointer array */
81297  int nCell;               /* Number of cells */
81298  int doCoverageCheck = 1; /* True if cell coverage checking should be done */
81299  int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
81300                           ** False if IPK must be strictly less than maxKey */
81301  u8 *data;                /* Page content */
81302  u8 *pCell;               /* Cell content */
81303  u8 *pCellIdx;            /* Next element of the cell pointer array */
81304  BtShared *pBt;           /* The BtShared object that owns pPage */
81305  u32 pc;                  /* Address of a cell */
81306  u32 usableSize;          /* Usable size of the page */
81307  u32 contentOffset;       /* Offset to the start of the cell content area */
81308  u32 *heap = 0;           /* Min-heap used for checking cell coverage */
81309  u32 x, prev = 0;         /* Next and previous entry on the min-heap */
81310  const char *saved_zPfx = pCheck->zPfx;
81311  int saved_v1 = pCheck->v1;
81312  int saved_v2 = pCheck->v2;
81313  u8 savedIsInit = 0;
81314
81315  /* Check that the page exists
81316  */
81317  checkProgress(pCheck);
81318  if( pCheck->mxErr==0 ) goto end_of_check;
81319  pBt = pCheck->pBt;
81320  usableSize = pBt->usableSize;
81321  if( iPage==0 ) return 0;
81322  if( checkRef(pCheck, iPage) ) return 0;
81323  pCheck->zPfx = "Tree %u page %u: ";
81324  pCheck->v1 = iPage;
81325  if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
81326    checkAppendMsg(pCheck,
81327       "unable to get the page. error code=%d", rc);
81328    if( rc==SQLITE_IOERR_NOMEM ) pCheck->rc = SQLITE_NOMEM;
81329    goto end_of_check;
81330  }
81331
81332  /* Clear MemPage.isInit to make sure the corruption detection code in
81333  ** btreeInitPage() is executed.  */
81334  savedIsInit = pPage->isInit;
81335  pPage->isInit = 0;
81336  if( (rc = btreeInitPage(pPage))!=0 ){
81337    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
81338    checkAppendMsg(pCheck,
81339                   "btreeInitPage() returns error code %d", rc);
81340    goto end_of_check;
81341  }
81342  if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
81343    assert( rc==SQLITE_CORRUPT );
81344    checkAppendMsg(pCheck, "free space corruption", rc);
81345    goto end_of_check;
81346  }
81347  data = pPage->aData;
81348  hdr = pPage->hdrOffset;
81349
81350  /* Set up for cell analysis */
81351  pCheck->zPfx = "Tree %u page %u cell %u: ";
81352  contentOffset = get2byteNotZero(&data[hdr+5]);
81353  assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
81354
81355  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
81356  ** number of cells on the page. */
81357  nCell = get2byte(&data[hdr+3]);
81358  assert( pPage->nCell==nCell );
81359  if( pPage->leaf || pPage->intKey==0 ){
81360    pCheck->nRow += nCell;
81361  }
81362
81363  /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
81364  ** immediately follows the b-tree page header. */
81365  cellStart = hdr + 12 - 4*pPage->leaf;
81366  assert( pPage->aCellIdx==&data[cellStart] );
81367  pCellIdx = &data[cellStart + 2*(nCell-1)];
81368
81369  if( !pPage->leaf ){
81370    /* Analyze the right-child page of internal pages */
81371    pgno = get4byte(&data[hdr+8]);
81372#ifndef SQLITE_OMIT_AUTOVACUUM
81373    if( pBt->autoVacuum ){
81374      pCheck->zPfx = "Tree %u page %u right child: ";
81375      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
81376    }
81377#endif
81378    depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
81379    keyCanBeEqual = 0;
81380  }else{
81381    /* For leaf pages, the coverage check will occur in the same loop
81382    ** as the other cell checks, so initialize the heap.  */
81383    heap = pCheck->heap;
81384    heap[0] = 0;
81385  }
81386
81387  /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
81388  ** integer offsets to the cell contents. */
81389  for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
81390    CellInfo info;
81391
81392    /* Check cell size */
81393    pCheck->v2 = i;
81394    assert( pCellIdx==&data[cellStart + i*2] );
81395    pc = get2byteAligned(pCellIdx);
81396    pCellIdx -= 2;
81397    if( pc<contentOffset || pc>usableSize-4 ){
81398      checkAppendMsg(pCheck, "Offset %u out of range %u..%u",
81399                             pc, contentOffset, usableSize-4);
81400      doCoverageCheck = 0;
81401      continue;
81402    }
81403    pCell = &data[pc];
81404    pPage->xParseCell(pPage, pCell, &info);
81405    if( pc+info.nSize>usableSize ){
81406      checkAppendMsg(pCheck, "Extends off end of page");
81407      doCoverageCheck = 0;
81408      continue;
81409    }
81410
81411    /* Check for integer primary key out of range */
81412    if( pPage->intKey ){
81413      if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
81414        checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
81415      }
81416      maxKey = info.nKey;
81417      keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */
81418    }
81419
81420    /* Check the content overflow list */
81421    if( info.nPayload>info.nLocal ){
81422      u32 nPage;       /* Number of pages on the overflow chain */
81423      Pgno pgnoOvfl;   /* First page of the overflow chain */
81424      assert( pc + info.nSize - 4 <= usableSize );
81425      nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
81426      pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
81427#ifndef SQLITE_OMIT_AUTOVACUUM
81428      if( pBt->autoVacuum ){
81429        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
81430      }
81431#endif
81432      checkList(pCheck, 0, pgnoOvfl, nPage);
81433    }
81434
81435    if( !pPage->leaf ){
81436      /* Check sanity of left child page for internal pages */
81437      pgno = get4byte(pCell);
81438#ifndef SQLITE_OMIT_AUTOVACUUM
81439      if( pBt->autoVacuum ){
81440        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
81441      }
81442#endif
81443      d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
81444      keyCanBeEqual = 0;
81445      if( d2!=depth ){
81446        checkAppendMsg(pCheck, "Child page depth differs");
81447        depth = d2;
81448      }
81449    }else{
81450      /* Populate the coverage-checking heap for leaf pages */
81451      btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
81452    }
81453  }
81454  *piMinKey = maxKey;
81455
81456  /* Check for complete coverage of the page
81457  */
81458  pCheck->zPfx = 0;
81459  if( doCoverageCheck && pCheck->mxErr>0 ){
81460    /* For leaf pages, the min-heap has already been initialized and the
81461    ** cells have already been inserted.  But for internal pages, that has
81462    ** not yet been done, so do it now */
81463    if( !pPage->leaf ){
81464      heap = pCheck->heap;
81465      heap[0] = 0;
81466      for(i=nCell-1; i>=0; i--){
81467        u32 size;
81468        pc = get2byteAligned(&data[cellStart+i*2]);
81469        size = pPage->xCellSize(pPage, &data[pc]);
81470        btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
81471      }
81472    }
81473    assert( heap!=0 );
81474    /* Add the freeblocks to the min-heap
81475    **
81476    ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
81477    ** is the offset of the first freeblock, or zero if there are no
81478    ** freeblocks on the page.
81479    */
81480    i = get2byte(&data[hdr+1]);
81481    while( i>0 ){
81482      int size, j;
81483      assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
81484      size = get2byte(&data[i+2]);
81485      assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
81486      btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
81487      /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
81488      ** big-endian integer which is the offset in the b-tree page of the next
81489      ** freeblock in the chain, or zero if the freeblock is the last on the
81490      ** chain. */
81491      j = get2byte(&data[i]);
81492      /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
81493      ** increasing offset. */
81494      assert( j==0 || j>i+size );     /* Enforced by btreeComputeFreeSpace() */
81495      assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
81496      i = j;
81497    }
81498    /* Analyze the min-heap looking for overlap between cells and/or
81499    ** freeblocks, and counting the number of untracked bytes in nFrag.
81500    **
81501    ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
81502    ** There is an implied first entry the covers the page header, the cell
81503    ** pointer index, and the gap between the cell pointer index and the start
81504    ** of cell content.
81505    **
81506    ** The loop below pulls entries from the min-heap in order and compares
81507    ** the start_address against the previous end_address.  If there is an
81508    ** overlap, that means bytes are used multiple times.  If there is a gap,
81509    ** that gap is added to the fragmentation count.
81510    */
81511    nFrag = 0;
81512    prev = contentOffset - 1;   /* Implied first min-heap entry */
81513    while( btreeHeapPull(heap,&x) ){
81514      if( (prev&0xffff)>=(x>>16) ){
81515        checkAppendMsg(pCheck,
81516          "Multiple uses for byte %u of page %u", x>>16, iPage);
81517        break;
81518      }else{
81519        nFrag += (x>>16) - (prev&0xffff) - 1;
81520        prev = x;
81521      }
81522    }
81523    nFrag += usableSize - (prev&0xffff) - 1;
81524    /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
81525    ** is stored in the fifth field of the b-tree page header.
81526    ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
81527    ** number of fragmented free bytes within the cell content area.
81528    */
81529    if( heap[0]==0 && nFrag!=data[hdr+7] ){
81530      checkAppendMsg(pCheck,
81531          "Fragmentation of %u bytes reported as %u on page %u",
81532          nFrag, data[hdr+7], iPage);
81533    }
81534  }
81535
81536end_of_check:
81537  if( !doCoverageCheck ) pPage->isInit = savedIsInit;
81538  releasePage(pPage);
81539  pCheck->zPfx = saved_zPfx;
81540  pCheck->v1 = saved_v1;
81541  pCheck->v2 = saved_v2;
81542  return depth+1;
81543}
81544#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
81545
81546#ifndef SQLITE_OMIT_INTEGRITY_CHECK
81547/*
81548** This routine does a complete check of the given BTree file.  aRoot[] is
81549** an array of pages numbers were each page number is the root page of
81550** a table.  nRoot is the number of entries in aRoot.
81551**
81552** A read-only or read-write transaction must be opened before calling
81553** this function.
81554**
81555** Write the number of error seen in *pnErr.  Except for some memory
81556** allocation errors,  an error message held in memory obtained from
81557** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
81558** returned.  If a memory allocation error occurs, NULL is returned.
81559**
81560** If the first entry in aRoot[] is 0, that indicates that the list of
81561** root pages is incomplete.  This is a "partial integrity-check".  This
81562** happens when performing an integrity check on a single table.  The
81563** zero is skipped, of course.  But in addition, the freelist checks
81564** and the checks to make sure every page is referenced are also skipped,
81565** since obviously it is not possible to know which pages are covered by
81566** the unverified btrees.  Except, if aRoot[1] is 1, then the freelist
81567** checks are still performed.
81568*/
81569SQLITE_PRIVATE int sqlite3BtreeIntegrityCheck(
81570  sqlite3 *db,  /* Database connection that is running the check */
81571  Btree *p,     /* The btree to be checked */
81572  Pgno *aRoot,  /* An array of root pages numbers for individual trees */
81573  Mem *aCnt,    /* Memory cells to write counts for each tree to */
81574  int nRoot,    /* Number of entries in aRoot[] */
81575  int mxErr,    /* Stop reporting errors after this many */
81576  int *pnErr,   /* OUT: Write number of errors seen to this variable */
81577  char **pzOut  /* OUT: Write the error message string here */
81578){
81579  Pgno i;
81580  IntegrityCk sCheck;
81581  BtShared *pBt = p->pBt;
81582  u64 savedDbFlags = pBt->db->flags;
81583  char zErr[100];
81584  int bPartial = 0;            /* True if not checking all btrees */
81585  int bCkFreelist = 1;         /* True to scan the freelist */
81586  VVA_ONLY( int nRef );
81587
81588  assert( nRoot>0 );
81589  assert( aCnt!=0 );
81590
81591  /* aRoot[0]==0 means this is a partial check */
81592  if( aRoot[0]==0 ){
81593    assert( nRoot>1 );
81594    bPartial = 1;
81595    if( aRoot[1]!=1 ) bCkFreelist = 0;
81596  }
81597
81598  sqlite3BtreeEnter(p);
81599  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
81600  VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
81601  assert( nRef>=0 );
81602  memset(&sCheck, 0, sizeof(sCheck));
81603  sCheck.db = db;
81604  sCheck.pBt = pBt;
81605  sCheck.pPager = pBt->pPager;
81606  sCheck.nCkPage = btreePagecount(sCheck.pBt);
81607  sCheck.mxErr = mxErr;
81608  sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
81609  sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
81610  if( sCheck.nCkPage==0 ){
81611    goto integrity_ck_cleanup;
81612  }
81613
81614  sCheck.aPgRef = sqlite3MallocZero((sCheck.nCkPage / 8)+ 1);
81615  if( !sCheck.aPgRef ){
81616    checkOom(&sCheck);
81617    goto integrity_ck_cleanup;
81618  }
81619  sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
81620  if( sCheck.heap==0 ){
81621    checkOom(&sCheck);
81622    goto integrity_ck_cleanup;
81623  }
81624
81625  i = PENDING_BYTE_PAGE(pBt);
81626  if( i<=sCheck.nCkPage ) setPageReferenced(&sCheck, i);
81627
81628  /* Check the integrity of the freelist
81629  */
81630  if( bCkFreelist ){
81631    sCheck.zPfx = "Freelist: ";
81632    checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
81633              get4byte(&pBt->pPage1->aData[36]));
81634    sCheck.zPfx = 0;
81635  }
81636
81637  /* Check all the tables.
81638  */
81639#ifndef SQLITE_OMIT_AUTOVACUUM
81640  if( !bPartial ){
81641    if( pBt->autoVacuum ){
81642      Pgno mx = 0;
81643      Pgno mxInHdr;
81644      for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
81645      mxInHdr = get4byte(&pBt->pPage1->aData[52]);
81646      if( mx!=mxInHdr ){
81647        checkAppendMsg(&sCheck,
81648          "max rootpage (%u) disagrees with header (%u)",
81649          mx, mxInHdr
81650        );
81651      }
81652    }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
81653      checkAppendMsg(&sCheck,
81654        "incremental_vacuum enabled with a max rootpage of zero"
81655      );
81656    }
81657  }
81658#endif
81659  testcase( pBt->db->flags & SQLITE_CellSizeCk );
81660  pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
81661  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
81662    sCheck.nRow = 0;
81663    if( aRoot[i] ){
81664      i64 notUsed;
81665#ifndef SQLITE_OMIT_AUTOVACUUM
81666      if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
81667        checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
81668      }
81669#endif
81670      sCheck.v0 = aRoot[i];
81671      checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
81672    }
81673    sqlite3MemSetArrayInt64(aCnt, i, sCheck.nRow);
81674  }
81675  pBt->db->flags = savedDbFlags;
81676
81677  /* Make sure every page in the file is referenced
81678  */
81679  if( !bPartial ){
81680    for(i=1; i<=sCheck.nCkPage && sCheck.mxErr; i++){
81681#ifdef SQLITE_OMIT_AUTOVACUUM
81682      if( getPageReferenced(&sCheck, i)==0 ){
81683        checkAppendMsg(&sCheck, "Page %u: never used", i);
81684      }
81685#else
81686      /* If the database supports auto-vacuum, make sure no tables contain
81687      ** references to pointer-map pages.
81688      */
81689      if( getPageReferenced(&sCheck, i)==0 &&
81690         (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
81691        checkAppendMsg(&sCheck, "Page %u: never used", i);
81692      }
81693      if( getPageReferenced(&sCheck, i)!=0 &&
81694         (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
81695        checkAppendMsg(&sCheck, "Page %u: pointer map referenced", i);
81696      }
81697#endif
81698    }
81699  }
81700
81701  /* Clean  up and report errors.
81702  */
81703integrity_ck_cleanup:
81704  sqlite3PageFree(sCheck.heap);
81705  sqlite3_free(sCheck.aPgRef);
81706  *pnErr = sCheck.nErr;
81707  if( sCheck.nErr==0 ){
81708    sqlite3_str_reset(&sCheck.errMsg);
81709    *pzOut = 0;
81710  }else{
81711    *pzOut = sqlite3StrAccumFinish(&sCheck.errMsg);
81712  }
81713  /* Make sure this analysis did not leave any unref() pages. */
81714  assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
81715  sqlite3BtreeLeave(p);
81716  return sCheck.rc;
81717}
81718#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
81719
81720/*
81721** Return the full pathname of the underlying database file.  Return
81722** an empty string if the database is in-memory or a TEMP database.
81723**
81724** The pager filename is invariant as long as the pager is
81725** open so it is safe to access without the BtShared mutex.
81726*/
81727SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
81728  assert( p->pBt->pPager!=0 );
81729  return sqlite3PagerFilename(p->pBt->pPager, 1);
81730}
81731
81732/*
81733** Return the pathname of the journal file for this database. The return
81734** value of this routine is the same regardless of whether the journal file
81735** has been created or not.
81736**
81737** The pager journal filename is invariant as long as the pager is
81738** open so it is safe to access without the BtShared mutex.
81739*/
81740SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
81741  assert( p->pBt->pPager!=0 );
81742  return sqlite3PagerJournalname(p->pBt->pPager);
81743}
81744
81745/*
81746** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
81747** to describe the current transaction state of Btree p.
81748*/
81749SQLITE_PRIVATE int sqlite3BtreeTxnState(Btree *p){
81750  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
81751  return p ? p->inTrans : 0;
81752}
81753
81754#ifndef SQLITE_OMIT_WAL
81755/*
81756** Run a checkpoint on the Btree passed as the first argument.
81757**
81758** Return SQLITE_LOCKED if this or any other connection has an open
81759** transaction on the shared-cache the argument Btree is connected to.
81760**
81761** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
81762*/
81763SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
81764  int rc = SQLITE_OK;
81765  if( p ){
81766    BtShared *pBt = p->pBt;
81767    sqlite3BtreeEnter(p);
81768    if( pBt->inTransaction!=TRANS_NONE ){
81769      rc = SQLITE_LOCKED;
81770    }else{
81771      rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
81772    }
81773    sqlite3BtreeLeave(p);
81774  }
81775  return rc;
81776}
81777#endif
81778
81779/*
81780** Return true if there is currently a backup running on Btree p.
81781*/
81782SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
81783  assert( p );
81784  assert( sqlite3_mutex_held(p->db->mutex) );
81785  return p->nBackup!=0;
81786}
81787
81788/*
81789** This function returns a pointer to a blob of memory associated with
81790** a single shared-btree. The memory is used by client code for its own
81791** purposes (for example, to store a high-level schema associated with
81792** the shared-btree). The btree layer manages reference counting issues.
81793**
81794** The first time this is called on a shared-btree, nBytes bytes of memory
81795** are allocated, zeroed, and returned to the caller. For each subsequent
81796** call the nBytes parameter is ignored and a pointer to the same blob
81797** of memory returned.
81798**
81799** If the nBytes parameter is 0 and the blob of memory has not yet been
81800** allocated, a null pointer is returned. If the blob has already been
81801** allocated, it is returned as normal.
81802**
81803** Just before the shared-btree is closed, the function passed as the
81804** xFree argument when the memory allocation was made is invoked on the
81805** blob of allocated memory. The xFree function should not call sqlite3_free()
81806** on the memory, the btree layer does that.
81807*/
81808SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
81809  BtShared *pBt = p->pBt;
81810  sqlite3BtreeEnter(p);
81811  if( !pBt->pSchema && nBytes ){
81812    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
81813    pBt->xFreeSchema = xFree;
81814  }
81815  sqlite3BtreeLeave(p);
81816  return pBt->pSchema;
81817}
81818
81819/*
81820** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
81821** btree as the argument handle holds an exclusive lock on the
81822** sqlite_schema table. Otherwise SQLITE_OK.
81823*/
81824SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
81825  int rc;
81826  assert( sqlite3_mutex_held(p->db->mutex) );
81827  sqlite3BtreeEnter(p);
81828  rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
81829  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
81830  sqlite3BtreeLeave(p);
81831  return rc;
81832}
81833
81834
81835#ifndef SQLITE_OMIT_SHARED_CACHE
81836/*
81837** Obtain a lock on the table whose root page is iTab.  The
81838** lock is a write lock if isWritelock is true or a read lock
81839** if it is false.
81840*/
81841SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
81842  int rc = SQLITE_OK;
81843  assert( p->inTrans!=TRANS_NONE );
81844  if( p->sharable ){
81845    u8 lockType = READ_LOCK + isWriteLock;
81846    assert( READ_LOCK+1==WRITE_LOCK );
81847    assert( isWriteLock==0 || isWriteLock==1 );
81848
81849    sqlite3BtreeEnter(p);
81850    rc = querySharedCacheTableLock(p, iTab, lockType);
81851    if( rc==SQLITE_OK ){
81852      rc = setSharedCacheTableLock(p, iTab, lockType);
81853    }
81854    sqlite3BtreeLeave(p);
81855  }
81856  return rc;
81857}
81858#endif
81859
81860#ifndef SQLITE_OMIT_INCRBLOB
81861/*
81862** Argument pCsr must be a cursor opened for writing on an
81863** INTKEY table currently pointing at a valid table entry.
81864** This function modifies the data stored as part of that entry.
81865**
81866** Only the data content may only be modified, it is not possible to
81867** change the length of the data stored. If this function is called with
81868** parameters that attempt to write past the end of the existing data,
81869** no modifications are made and SQLITE_CORRUPT is returned.
81870*/
81871SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
81872  int rc;
81873  assert( cursorOwnsBtShared(pCsr) );
81874  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
81875  assert( pCsr->curFlags & BTCF_Incrblob );
81876
81877  rc = restoreCursorPosition(pCsr);
81878  if( rc!=SQLITE_OK ){
81879    return rc;
81880  }
81881  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
81882  if( pCsr->eState!=CURSOR_VALID ){
81883    return SQLITE_ABORT;
81884  }
81885
81886  /* Save the positions of all other cursors open on this table. This is
81887  ** required in case any of them are holding references to an xFetch
81888  ** version of the b-tree page modified by the accessPayload call below.
81889  **
81890  ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
81891  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
81892  ** saveAllCursors can only return SQLITE_OK.
81893  */
81894  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
81895  assert( rc==SQLITE_OK );
81896
81897  /* Check some assumptions:
81898  **   (a) the cursor is open for writing,
81899  **   (b) there is a read/write transaction open,
81900  **   (c) the connection holds a write-lock on the table (if required),
81901  **   (d) there are no conflicting read-locks, and
81902  **   (e) the cursor points at a valid row of an intKey table.
81903  */
81904  if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
81905    return SQLITE_READONLY;
81906  }
81907  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
81908              && pCsr->pBt->inTransaction==TRANS_WRITE );
81909  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
81910  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
81911  assert( pCsr->pPage->intKey );
81912
81913  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
81914}
81915
81916/*
81917** Mark this cursor as an incremental blob cursor.
81918*/
81919SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
81920  pCur->curFlags |= BTCF_Incrblob;
81921  pCur->pBtree->hasIncrblobCur = 1;
81922}
81923#endif
81924
81925/*
81926** Set both the "read version" (single byte at byte offset 18) and
81927** "write version" (single byte at byte offset 19) fields in the database
81928** header to iVersion.
81929*/
81930SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
81931  BtShared *pBt = pBtree->pBt;
81932  int rc;                         /* Return code */
81933
81934  assert( iVersion==1 || iVersion==2 );
81935
81936  /* If setting the version fields to 1, do not automatically open the
81937  ** WAL connection, even if the version fields are currently set to 2.
81938  */
81939  pBt->btsFlags &= ~BTS_NO_WAL;
81940  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
81941
81942  rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
81943  if( rc==SQLITE_OK ){
81944    u8 *aData = pBt->pPage1->aData;
81945    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
81946      rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
81947      if( rc==SQLITE_OK ){
81948        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
81949        if( rc==SQLITE_OK ){
81950          aData[18] = (u8)iVersion;
81951          aData[19] = (u8)iVersion;
81952        }
81953      }
81954    }
81955  }
81956
81957  pBt->btsFlags &= ~BTS_NO_WAL;
81958  return rc;
81959}
81960
81961/*
81962** Return true if the cursor has a hint specified.  This routine is
81963** only used from within assert() statements
81964*/
81965SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
81966  return (pCsr->hints & mask)!=0;
81967}
81968
81969/*
81970** Return true if the given Btree is read-only.
81971*/
81972SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
81973  return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
81974}
81975
81976/*
81977** Return the size of the header added to each page by this module.
81978*/
81979SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
81980
81981/*
81982** If no transaction is active and the database is not a temp-db, clear
81983** the in-memory pager cache.
81984*/
81985SQLITE_PRIVATE void sqlite3BtreeClearCache(Btree *p){
81986  BtShared *pBt = p->pBt;
81987  if( pBt->inTransaction==TRANS_NONE ){
81988    sqlite3PagerClearCache(pBt->pPager);
81989  }
81990}
81991
81992#if !defined(SQLITE_OMIT_SHARED_CACHE)
81993/*
81994** Return true if the Btree passed as the only argument is sharable.
81995*/
81996SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
81997  return p->sharable;
81998}
81999
82000/*
82001** Return the number of connections to the BtShared object accessed by
82002** the Btree handle passed as the only argument. For private caches
82003** this is always 1. For shared caches it may be 1 or greater.
82004*/
82005SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
82006  testcase( p->sharable );
82007  return p->pBt->nRef;
82008}
82009#endif
82010
82011/************** End of btree.c ***********************************************/
82012/************** Begin file backup.c ******************************************/
82013/*
82014** 2009 January 28
82015**
82016** The author disclaims copyright to this source code.  In place of
82017** a legal notice, here is a blessing:
82018**
82019**    May you do good and not evil.
82020**    May you find forgiveness for yourself and forgive others.
82021**    May you share freely, never taking more than you give.
82022**
82023*************************************************************************
82024** This file contains the implementation of the sqlite3_backup_XXX()
82025** API functions and the related features.
82026*/
82027/* #include "sqliteInt.h" */
82028/* #include "btreeInt.h" */
82029
82030/*
82031** Structure allocated for each backup operation.
82032*/
82033struct sqlite3_backup {
82034  sqlite3* pDestDb;        /* Destination database handle */
82035  Btree *pDest;            /* Destination b-tree file */
82036  u32 iDestSchema;         /* Original schema cookie in destination */
82037  int bDestLocked;         /* True once a write-transaction is open on pDest */
82038
82039  Pgno iNext;              /* Page number of the next source page to copy */
82040  sqlite3* pSrcDb;         /* Source database handle */
82041  Btree *pSrc;             /* Source b-tree file */
82042
82043  int rc;                  /* Backup process error code */
82044
82045  /* These two variables are set by every call to backup_step(). They are
82046  ** read by calls to backup_remaining() and backup_pagecount().
82047  */
82048  Pgno nRemaining;         /* Number of pages left to copy */
82049  Pgno nPagecount;         /* Total number of pages to copy */
82050
82051  int isAttached;          /* True once backup has been registered with pager */
82052  sqlite3_backup *pNext;   /* Next backup associated with source pager */
82053};
82054
82055/*
82056** THREAD SAFETY NOTES:
82057**
82058**   Once it has been created using backup_init(), a single sqlite3_backup
82059**   structure may be accessed via two groups of thread-safe entry points:
82060**
82061**     * Via the sqlite3_backup_XXX() API function backup_step() and
82062**       backup_finish(). Both these functions obtain the source database
82063**       handle mutex and the mutex associated with the source BtShared
82064**       structure, in that order.
82065**
82066**     * Via the BackupUpdate() and BackupRestart() functions, which are
82067**       invoked by the pager layer to report various state changes in
82068**       the page cache associated with the source database. The mutex
82069**       associated with the source database BtShared structure will always
82070**       be held when either of these functions are invoked.
82071**
82072**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
82073**   backup_pagecount() are not thread-safe functions. If they are called
82074**   while some other thread is calling backup_step() or backup_finish(),
82075**   the values returned may be invalid. There is no way for a call to
82076**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
82077**   or backup_pagecount().
82078**
82079**   Depending on the SQLite configuration, the database handles and/or
82080**   the Btree objects may have their own mutexes that require locking.
82081**   Non-sharable Btrees (in-memory databases for example), do not have
82082**   associated mutexes.
82083*/
82084
82085/*
82086** Return a pointer corresponding to database zDb (i.e. "main", "temp")
82087** in connection handle pDb. If such a database cannot be found, return
82088** a NULL pointer and write an error message to pErrorDb.
82089**
82090** If the "temp" database is requested, it may need to be opened by this
82091** function. If an error occurs while doing so, return 0 and write an
82092** error message to pErrorDb.
82093*/
82094static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
82095  int i = sqlite3FindDbName(pDb, zDb);
82096
82097  if( i==1 ){
82098    Parse sParse;
82099    int rc = 0;
82100    sqlite3ParseObjectInit(&sParse,pDb);
82101    if( sqlite3OpenTempDatabase(&sParse) ){
82102      sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
82103      rc = SQLITE_ERROR;
82104    }
82105    sqlite3DbFree(pErrorDb, sParse.zErrMsg);
82106    sqlite3ParseObjectReset(&sParse);
82107    if( rc ){
82108      return 0;
82109    }
82110  }
82111
82112  if( i<0 ){
82113    sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
82114    return 0;
82115  }
82116
82117  return pDb->aDb[i].pBt;
82118}
82119
82120/*
82121** Attempt to set the page size of the destination to match the page size
82122** of the source.
82123*/
82124static int setDestPgsz(sqlite3_backup *p){
82125  int rc;
82126  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),0,0);
82127  return rc;
82128}
82129
82130/*
82131** Check that there is no open read-transaction on the b-tree passed as the
82132** second argument. If there is not, return SQLITE_OK. Otherwise, if there
82133** is an open read-transaction, return SQLITE_ERROR and leave an error
82134** message in database handle db.
82135*/
82136static int checkReadTransaction(sqlite3 *db, Btree *p){
82137  if( sqlite3BtreeTxnState(p)!=SQLITE_TXN_NONE ){
82138    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
82139    return SQLITE_ERROR;
82140  }
82141  return SQLITE_OK;
82142}
82143
82144/*
82145** Create an sqlite3_backup process to copy the contents of zSrcDb from
82146** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
82147** a pointer to the new sqlite3_backup object.
82148**
82149** If an error occurs, NULL is returned and an error code and error message
82150** stored in database handle pDestDb.
82151*/
82152SQLITE_API sqlite3_backup *sqlite3_backup_init(
82153  sqlite3* pDestDb,                     /* Database to write to */
82154  const char *zDestDb,                  /* Name of database within pDestDb */
82155  sqlite3* pSrcDb,                      /* Database connection to read from */
82156  const char *zSrcDb                    /* Name of database within pSrcDb */
82157){
82158  sqlite3_backup *p;                    /* Value to return */
82159
82160#ifdef SQLITE_ENABLE_API_ARMOR
82161  if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
82162    (void)SQLITE_MISUSE_BKPT;
82163    return 0;
82164  }
82165#endif
82166
82167  /* Lock the source database handle. The destination database
82168  ** handle is not locked in this routine, but it is locked in
82169  ** sqlite3_backup_step(). The user is required to ensure that no
82170  ** other thread accesses the destination handle for the duration
82171  ** of the backup operation.  Any attempt to use the destination
82172  ** database connection while a backup is in progress may cause
82173  ** a malfunction or a deadlock.
82174  */
82175  sqlite3_mutex_enter(pSrcDb->mutex);
82176  sqlite3_mutex_enter(pDestDb->mutex);
82177
82178  if( pSrcDb==pDestDb ){
82179    sqlite3ErrorWithMsg(
82180        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
82181    );
82182    p = 0;
82183  }else {
82184    /* Allocate space for a new sqlite3_backup object...
82185    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
82186    ** call to sqlite3_backup_init() and is destroyed by a call to
82187    ** sqlite3_backup_finish(). */
82188    p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
82189    if( !p ){
82190      sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
82191    }
82192  }
82193
82194  /* If the allocation succeeded, populate the new object. */
82195  if( p ){
82196    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
82197    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
82198    p->pDestDb = pDestDb;
82199    p->pSrcDb = pSrcDb;
82200    p->iNext = 1;
82201    p->isAttached = 0;
82202
82203    if( 0==p->pSrc || 0==p->pDest
82204     || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
82205     ){
82206      /* One (or both) of the named databases did not exist or an OOM
82207      ** error was hit. Or there is a transaction open on the destination
82208      ** database. The error has already been written into the pDestDb
82209      ** handle. All that is left to do here is free the sqlite3_backup
82210      ** structure.  */
82211      sqlite3_free(p);
82212      p = 0;
82213    }
82214  }
82215  if( p ){
82216    p->pSrc->nBackup++;
82217  }
82218
82219  sqlite3_mutex_leave(pDestDb->mutex);
82220  sqlite3_mutex_leave(pSrcDb->mutex);
82221  return p;
82222}
82223
82224/*
82225** Argument rc is an SQLite error code. Return true if this error is
82226** considered fatal if encountered during a backup operation. All errors
82227** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
82228*/
82229static int isFatalError(int rc){
82230  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
82231}
82232
82233/*
82234** Parameter zSrcData points to a buffer containing the data for
82235** page iSrcPg from the source database. Copy this data into the
82236** destination database.
82237*/
82238static int backupOnePage(
82239  sqlite3_backup *p,              /* Backup handle */
82240  Pgno iSrcPg,                    /* Source database page to backup */
82241  const u8 *zSrcData,             /* Source database page data */
82242  int bUpdate                     /* True for an update, false otherwise */
82243){
82244  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
82245  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
82246  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
82247  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
82248  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
82249  int rc = SQLITE_OK;
82250  i64 iOff;
82251
82252  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
82253  assert( p->bDestLocked );
82254  assert( !isFatalError(p->rc) );
82255  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
82256  assert( zSrcData );
82257  assert( nSrcPgsz==nDestPgsz || sqlite3PagerIsMemdb(pDestPager)==0 );
82258
82259  /* This loop runs once for each destination page spanned by the source
82260  ** page. For each iteration, variable iOff is set to the byte offset
82261  ** of the destination page.
82262  */
82263  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
82264    DbPage *pDestPg = 0;
82265    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
82266    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
82267    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
82268     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
82269    ){
82270      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
82271      u8 *zDestData = sqlite3PagerGetData(pDestPg);
82272      u8 *zOut = &zDestData[iOff%nDestPgsz];
82273
82274      /* Copy the data from the source page into the destination page.
82275      ** Then clear the Btree layer MemPage.isInit flag. Both this module
82276      ** and the pager code use this trick (clearing the first byte
82277      ** of the page 'extra' space to invalidate the Btree layers
82278      ** cached parse of the page). MemPage.isInit is marked
82279      ** "MUST BE FIRST" for this purpose.
82280      */
82281      memcpy(zOut, zIn, nCopy);
82282      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
82283      if( iOff==0 && bUpdate==0 ){
82284        sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
82285      }
82286    }
82287    sqlite3PagerUnref(pDestPg);
82288  }
82289
82290  return rc;
82291}
82292
82293/*
82294** If pFile is currently larger than iSize bytes, then truncate it to
82295** exactly iSize bytes. If pFile is not larger than iSize bytes, then
82296** this function is a no-op.
82297**
82298** Return SQLITE_OK if everything is successful, or an SQLite error
82299** code if an error occurs.
82300*/
82301static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
82302  i64 iCurrent;
82303  int rc = sqlite3OsFileSize(pFile, &iCurrent);
82304  if( rc==SQLITE_OK && iCurrent>iSize ){
82305    rc = sqlite3OsTruncate(pFile, iSize);
82306  }
82307  return rc;
82308}
82309
82310/*
82311** Register this backup object with the associated source pager for
82312** callbacks when pages are changed or the cache invalidated.
82313*/
82314static void attachBackupObject(sqlite3_backup *p){
82315  sqlite3_backup **pp;
82316  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
82317  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
82318  p->pNext = *pp;
82319  *pp = p;
82320  p->isAttached = 1;
82321}
82322
82323/*
82324** Copy nPage pages from the source b-tree to the destination.
82325*/
82326SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
82327  int rc;
82328  int destMode;       /* Destination journal mode */
82329  int pgszSrc = 0;    /* Source page size */
82330  int pgszDest = 0;   /* Destination page size */
82331
82332#ifdef SQLITE_ENABLE_API_ARMOR
82333  if( p==0 ) return SQLITE_MISUSE_BKPT;
82334#endif
82335  sqlite3_mutex_enter(p->pSrcDb->mutex);
82336  sqlite3BtreeEnter(p->pSrc);
82337  if( p->pDestDb ){
82338    sqlite3_mutex_enter(p->pDestDb->mutex);
82339  }
82340
82341  rc = p->rc;
82342  if( !isFatalError(rc) ){
82343    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
82344    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
82345    int ii;                            /* Iterator variable */
82346    int nSrcPage = -1;                 /* Size of source db in pages */
82347    int bCloseTrans = 0;               /* True if src db requires unlocking */
82348
82349    /* If the source pager is currently in a write-transaction, return
82350    ** SQLITE_BUSY immediately.
82351    */
82352    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
82353      rc = SQLITE_BUSY;
82354    }else{
82355      rc = SQLITE_OK;
82356    }
82357
82358    /* If there is no open read-transaction on the source database, open
82359    ** one now. If a transaction is opened here, then it will be closed
82360    ** before this function exits.
82361    */
82362    if( rc==SQLITE_OK && SQLITE_TXN_NONE==sqlite3BtreeTxnState(p->pSrc) ){
82363      rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
82364      bCloseTrans = 1;
82365    }
82366
82367    /* If the destination database has not yet been locked (i.e. if this
82368    ** is the first call to backup_step() for the current backup operation),
82369    ** try to set its page size to the same as the source database. This
82370    ** is especially important on ZipVFS systems, as in that case it is
82371    ** not possible to create a database file that uses one page size by
82372    ** writing to it with another.  */
82373    if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
82374      rc = SQLITE_NOMEM;
82375    }
82376
82377    /* Lock the destination database, if it is not locked already. */
82378    if( SQLITE_OK==rc && p->bDestLocked==0
82379     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,
82380                                                (int*)&p->iDestSchema))
82381    ){
82382      p->bDestLocked = 1;
82383    }
82384
82385    /* Do not allow backup if the destination database is in WAL mode
82386    ** and the page sizes are different between source and destination */
82387    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
82388    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
82389    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
82390    if( SQLITE_OK==rc
82391     && (destMode==PAGER_JOURNALMODE_WAL || sqlite3PagerIsMemdb(pDestPager))
82392     && pgszSrc!=pgszDest
82393    ){
82394      rc = SQLITE_READONLY;
82395    }
82396
82397    /* Now that there is a read-lock on the source database, query the
82398    ** source pager for the number of pages in the database.
82399    */
82400    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
82401    assert( nSrcPage>=0 );
82402    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
82403      const Pgno iSrcPg = p->iNext;                 /* Source page number */
82404      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
82405        DbPage *pSrcPg;                             /* Source page object */
82406        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
82407        if( rc==SQLITE_OK ){
82408          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
82409          sqlite3PagerUnref(pSrcPg);
82410        }
82411      }
82412      p->iNext++;
82413    }
82414    if( rc==SQLITE_OK ){
82415      p->nPagecount = nSrcPage;
82416      p->nRemaining = nSrcPage+1-p->iNext;
82417      if( p->iNext>(Pgno)nSrcPage ){
82418        rc = SQLITE_DONE;
82419      }else if( !p->isAttached ){
82420        attachBackupObject(p);
82421      }
82422    }
82423
82424    /* Update the schema version field in the destination database. This
82425    ** is to make sure that the schema-version really does change in
82426    ** the case where the source and destination databases have the
82427    ** same schema version.
82428    */
82429    if( rc==SQLITE_DONE ){
82430      if( nSrcPage==0 ){
82431        rc = sqlite3BtreeNewDb(p->pDest);
82432        nSrcPage = 1;
82433      }
82434      if( rc==SQLITE_OK || rc==SQLITE_DONE ){
82435        rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
82436      }
82437      if( rc==SQLITE_OK ){
82438        if( p->pDestDb ){
82439          sqlite3ResetAllSchemasOfConnection(p->pDestDb);
82440        }
82441        if( destMode==PAGER_JOURNALMODE_WAL ){
82442          rc = sqlite3BtreeSetVersion(p->pDest, 2);
82443        }
82444      }
82445      if( rc==SQLITE_OK ){
82446        int nDestTruncate;
82447        /* Set nDestTruncate to the final number of pages in the destination
82448        ** database. The complication here is that the destination page
82449        ** size may be different to the source page size.
82450        **
82451        ** If the source page size is smaller than the destination page size,
82452        ** round up. In this case the call to sqlite3OsTruncate() below will
82453        ** fix the size of the file. However it is important to call
82454        ** sqlite3PagerTruncateImage() here so that any pages in the
82455        ** destination file that lie beyond the nDestTruncate page mark are
82456        ** journalled by PagerCommitPhaseOne() before they are destroyed
82457        ** by the file truncation.
82458        */
82459        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
82460        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
82461        if( pgszSrc<pgszDest ){
82462          int ratio = pgszDest/pgszSrc;
82463          nDestTruncate = (nSrcPage+ratio-1)/ratio;
82464          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
82465            nDestTruncate--;
82466          }
82467        }else{
82468          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
82469        }
82470        assert( nDestTruncate>0 );
82471
82472        if( pgszSrc<pgszDest ){
82473          /* If the source page-size is smaller than the destination page-size,
82474          ** two extra things may need to happen:
82475          **
82476          **   * The destination may need to be truncated, and
82477          **
82478          **   * Data stored on the pages immediately following the
82479          **     pending-byte page in the source database may need to be
82480          **     copied into the destination database.
82481          */
82482          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
82483          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
82484          Pgno iPg;
82485          int nDstPage;
82486          i64 iOff;
82487          i64 iEnd;
82488
82489          assert( pFile );
82490          assert( nDestTruncate==0
82491              || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
82492                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
82493             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
82494          ));
82495
82496          /* This block ensures that all data required to recreate the original
82497          ** database has been stored in the journal for pDestPager and the
82498          ** journal synced to disk. So at this point we may safely modify
82499          ** the database file in any way, knowing that if a power failure
82500          ** occurs, the original database will be reconstructed from the
82501          ** journal file.  */
82502          sqlite3PagerPagecount(pDestPager, &nDstPage);
82503          for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
82504            if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
82505              DbPage *pPg;
82506              rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
82507              if( rc==SQLITE_OK ){
82508                rc = sqlite3PagerWrite(pPg);
82509                sqlite3PagerUnref(pPg);
82510              }
82511            }
82512          }
82513          if( rc==SQLITE_OK ){
82514            rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
82515          }
82516
82517          /* Write the extra pages and truncate the database file as required */
82518          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
82519          for(
82520            iOff=PENDING_BYTE+pgszSrc;
82521            rc==SQLITE_OK && iOff<iEnd;
82522            iOff+=pgszSrc
82523          ){
82524            PgHdr *pSrcPg = 0;
82525            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
82526            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
82527            if( rc==SQLITE_OK ){
82528              u8 *zData = sqlite3PagerGetData(pSrcPg);
82529              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
82530            }
82531            sqlite3PagerUnref(pSrcPg);
82532          }
82533          if( rc==SQLITE_OK ){
82534            rc = backupTruncateFile(pFile, iSize);
82535          }
82536
82537          /* Sync the database file to disk. */
82538          if( rc==SQLITE_OK ){
82539            rc = sqlite3PagerSync(pDestPager, 0);
82540          }
82541        }else{
82542          sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
82543          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
82544        }
82545
82546        /* Finish committing the transaction to the destination database. */
82547        if( SQLITE_OK==rc
82548         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
82549        ){
82550          rc = SQLITE_DONE;
82551        }
82552      }
82553    }
82554
82555    /* If bCloseTrans is true, then this function opened a read transaction
82556    ** on the source database. Close the read transaction here. There is
82557    ** no need to check the return values of the btree methods here, as
82558    ** "committing" a read-only transaction cannot fail.
82559    */
82560    if( bCloseTrans ){
82561      TESTONLY( int rc2 );
82562      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
82563      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
82564      assert( rc2==SQLITE_OK );
82565    }
82566
82567    if( rc==SQLITE_IOERR_NOMEM ){
82568      rc = SQLITE_NOMEM_BKPT;
82569    }
82570    p->rc = rc;
82571  }
82572  if( p->pDestDb ){
82573    sqlite3_mutex_leave(p->pDestDb->mutex);
82574  }
82575  sqlite3BtreeLeave(p->pSrc);
82576  sqlite3_mutex_leave(p->pSrcDb->mutex);
82577  return rc;
82578}
82579
82580/*
82581** Release all resources associated with an sqlite3_backup* handle.
82582*/
82583SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
82584  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
82585  sqlite3 *pSrcDb;                     /* Source database connection */
82586  int rc;                              /* Value to return */
82587
82588  /* Enter the mutexes */
82589  if( p==0 ) return SQLITE_OK;
82590  pSrcDb = p->pSrcDb;
82591  sqlite3_mutex_enter(pSrcDb->mutex);
82592  sqlite3BtreeEnter(p->pSrc);
82593  if( p->pDestDb ){
82594    sqlite3_mutex_enter(p->pDestDb->mutex);
82595  }
82596
82597  /* Detach this backup from the source pager. */
82598  if( p->pDestDb ){
82599    p->pSrc->nBackup--;
82600  }
82601  if( p->isAttached ){
82602    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
82603    assert( pp!=0 );
82604    while( *pp!=p ){
82605      pp = &(*pp)->pNext;
82606      assert( pp!=0 );
82607    }
82608    *pp = p->pNext;
82609  }
82610
82611  /* If a transaction is still open on the Btree, roll it back. */
82612  sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
82613
82614  /* Set the error code of the destination database handle. */
82615  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
82616  if( p->pDestDb ){
82617    sqlite3Error(p->pDestDb, rc);
82618
82619    /* Exit the mutexes and free the backup context structure. */
82620    sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
82621  }
82622  sqlite3BtreeLeave(p->pSrc);
82623  if( p->pDestDb ){
82624    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
82625    ** call to sqlite3_backup_init() and is destroyed by a call to
82626    ** sqlite3_backup_finish(). */
82627    sqlite3_free(p);
82628  }
82629  sqlite3LeaveMutexAndCloseZombie(pSrcDb);
82630  return rc;
82631}
82632
82633/*
82634** Return the number of pages still to be backed up as of the most recent
82635** call to sqlite3_backup_step().
82636*/
82637SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
82638#ifdef SQLITE_ENABLE_API_ARMOR
82639  if( p==0 ){
82640    (void)SQLITE_MISUSE_BKPT;
82641    return 0;
82642  }
82643#endif
82644  return p->nRemaining;
82645}
82646
82647/*
82648** Return the total number of pages in the source database as of the most
82649** recent call to sqlite3_backup_step().
82650*/
82651SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
82652#ifdef SQLITE_ENABLE_API_ARMOR
82653  if( p==0 ){
82654    (void)SQLITE_MISUSE_BKPT;
82655    return 0;
82656  }
82657#endif
82658  return p->nPagecount;
82659}
82660
82661/*
82662** This function is called after the contents of page iPage of the
82663** source database have been modified. If page iPage has already been
82664** copied into the destination database, then the data written to the
82665** destination is now invalidated. The destination copy of iPage needs
82666** to be updated with the new data before the backup operation is
82667** complete.
82668**
82669** It is assumed that the mutex associated with the BtShared object
82670** corresponding to the source database is held when this function is
82671** called.
82672*/
82673static SQLITE_NOINLINE void backupUpdate(
82674  sqlite3_backup *p,
82675  Pgno iPage,
82676  const u8 *aData
82677){
82678  assert( p!=0 );
82679  do{
82680    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
82681    if( !isFatalError(p->rc) && iPage<p->iNext ){
82682      /* The backup process p has already copied page iPage. But now it
82683      ** has been modified by a transaction on the source pager. Copy
82684      ** the new data into the backup.
82685      */
82686      int rc;
82687      assert( p->pDestDb );
82688      sqlite3_mutex_enter(p->pDestDb->mutex);
82689      rc = backupOnePage(p, iPage, aData, 1);
82690      sqlite3_mutex_leave(p->pDestDb->mutex);
82691      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
82692      if( rc!=SQLITE_OK ){
82693        p->rc = rc;
82694      }
82695    }
82696  }while( (p = p->pNext)!=0 );
82697}
82698SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
82699  if( pBackup ) backupUpdate(pBackup, iPage, aData);
82700}
82701
82702/*
82703** Restart the backup process. This is called when the pager layer
82704** detects that the database has been modified by an external database
82705** connection. In this case there is no way of knowing which of the
82706** pages that have been copied into the destination database are still
82707** valid and which are not, so the entire process needs to be restarted.
82708**
82709** It is assumed that the mutex associated with the BtShared object
82710** corresponding to the source database is held when this function is
82711** called.
82712*/
82713SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
82714  sqlite3_backup *p;                   /* Iterator variable */
82715  for(p=pBackup; p; p=p->pNext){
82716    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
82717    p->iNext = 1;
82718  }
82719}
82720
82721#ifndef SQLITE_OMIT_VACUUM
82722/*
82723** Copy the complete content of pBtFrom into pBtTo.  A transaction
82724** must be active for both files.
82725**
82726** The size of file pTo may be reduced by this operation. If anything
82727** goes wrong, the transaction on pTo is rolled back. If successful, the
82728** transaction is committed before returning.
82729*/
82730SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
82731  int rc;
82732  sqlite3_file *pFd;              /* File descriptor for database pTo */
82733  sqlite3_backup b;
82734  sqlite3BtreeEnter(pTo);
82735  sqlite3BtreeEnter(pFrom);
82736
82737  assert( sqlite3BtreeTxnState(pTo)==SQLITE_TXN_WRITE );
82738  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
82739  if( pFd->pMethods ){
82740    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
82741    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
82742    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
82743    if( rc ) goto copy_finished;
82744  }
82745
82746  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
82747  ** to 0. This is used by the implementations of sqlite3_backup_step()
82748  ** and sqlite3_backup_finish() to detect that they are being called
82749  ** from this function, not directly by the user.
82750  */
82751  memset(&b, 0, sizeof(b));
82752  b.pSrcDb = pFrom->db;
82753  b.pSrc = pFrom;
82754  b.pDest = pTo;
82755  b.iNext = 1;
82756
82757  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
82758  ** file. By passing this as the number of pages to copy to
82759  ** sqlite3_backup_step(), we can guarantee that the copy finishes
82760  ** within a single call (unless an error occurs). The assert() statement
82761  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
82762  ** or an error code.  */
82763  sqlite3_backup_step(&b, 0x7FFFFFFF);
82764  assert( b.rc!=SQLITE_OK );
82765
82766  rc = sqlite3_backup_finish(&b);
82767  if( rc==SQLITE_OK ){
82768    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
82769  }else{
82770    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
82771  }
82772
82773  assert( sqlite3BtreeTxnState(pTo)!=SQLITE_TXN_WRITE );
82774copy_finished:
82775  sqlite3BtreeLeave(pFrom);
82776  sqlite3BtreeLeave(pTo);
82777  return rc;
82778}
82779#endif /* SQLITE_OMIT_VACUUM */
82780
82781/************** End of backup.c **********************************************/
82782/************** Begin file vdbemem.c *****************************************/
82783/*
82784** 2004 May 26
82785**
82786** The author disclaims copyright to this source code.  In place of
82787** a legal notice, here is a blessing:
82788**
82789**    May you do good and not evil.
82790**    May you find forgiveness for yourself and forgive others.
82791**    May you share freely, never taking more than you give.
82792**
82793*************************************************************************
82794**
82795** This file contains code use to manipulate "Mem" structure.  A "Mem"
82796** stores a single value in the VDBE.  Mem is an opaque structure visible
82797** only within the VDBE.  Interface routines refer to a Mem using the
82798** name sqlite_value
82799*/
82800/* #include "sqliteInt.h" */
82801/* #include "vdbeInt.h" */
82802
82803/* True if X is a power of two.  0 is considered a power of two here.
82804** In other words, return true if X has at most one bit set.
82805*/
82806#define ISPOWEROF2(X)  (((X)&((X)-1))==0)
82807
82808#ifdef SQLITE_DEBUG
82809/*
82810** Check invariants on a Mem object.
82811**
82812** This routine is intended for use inside of assert() statements, like
82813** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
82814*/
82815SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
82816  /* If MEM_Dyn is set then Mem.xDel!=0.
82817  ** Mem.xDel might not be initialized if MEM_Dyn is clear.
82818  */
82819  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
82820
82821  /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
82822  ** ensure that if Mem.szMalloc>0 then it is safe to do
82823  ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
82824  ** That saves a few cycles in inner loops. */
82825  assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
82826
82827  /* Cannot have more than one of MEM_Int, MEM_Real, or MEM_IntReal */
82828  assert( ISPOWEROF2(p->flags & (MEM_Int|MEM_Real|MEM_IntReal)) );
82829
82830  if( p->flags & MEM_Null ){
82831    /* Cannot be both MEM_Null and some other type */
82832    assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );
82833
82834    /* If MEM_Null is set, then either the value is a pure NULL (the usual
82835    ** case) or it is a pointer set using sqlite3_bind_pointer() or
82836    ** sqlite3_result_pointer().  If a pointer, then MEM_Term must also be
82837    ** set.
82838    */
82839    if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
82840      /* This is a pointer type.  There may be a flag to indicate what to
82841      ** do with the pointer. */
82842      assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
82843              ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
82844              ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
82845
82846      /* No other bits set */
82847      assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind
82848                           |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
82849    }else{
82850      /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
82851      ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
82852    }
82853  }else{
82854    /* The MEM_Cleared bit is only allowed on NULLs */
82855    assert( (p->flags & MEM_Cleared)==0 );
82856  }
82857
82858  /* The szMalloc field holds the correct memory allocation size */
82859  assert( p->szMalloc==0
82860       || (p->flags==MEM_Undefined
82861           && p->szMalloc<=sqlite3DbMallocSize(p->db,p->zMalloc))
82862       || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc));
82863
82864  /* If p holds a string or blob, the Mem.z must point to exactly
82865  ** one of the following:
82866  **
82867  **   (1) Memory in Mem.zMalloc and managed by the Mem object
82868  **   (2) Memory to be freed using Mem.xDel
82869  **   (3) An ephemeral string or blob
82870  **   (4) A static string or blob
82871  */
82872  if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
82873    assert(
82874      ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
82875      ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
82876      ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
82877      ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
82878    );
82879  }
82880  return 1;
82881}
82882#endif
82883
82884/*
82885** Render a Mem object which is one of MEM_Int, MEM_Real, or MEM_IntReal
82886** into a buffer.
82887*/
82888static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){
82889  StrAccum acc;
82890  assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) );
82891  assert( sz>22 );
82892  if( p->flags & MEM_Int ){
82893#if GCC_VERSION>=7000000
82894    /* Work-around for GCC bug
82895    ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96270 */
82896    i64 x;
82897    assert( (p->flags&MEM_Int)*2==sizeof(x) );
82898    memcpy(&x, (char*)&p->u, (p->flags&MEM_Int)*2);
82899    p->n = sqlite3Int64ToText(x, zBuf);
82900#else
82901    p->n = sqlite3Int64ToText(p->u.i, zBuf);
82902#endif
82903  }else{
82904    sqlite3StrAccumInit(&acc, 0, zBuf, sz, 0);
82905    sqlite3_str_appendf(&acc, "%!.15g",
82906         (p->flags & MEM_IntReal)!=0 ? (double)p->u.i : p->u.r);
82907    assert( acc.zText==zBuf && acc.mxAlloc<=0 );
82908    zBuf[acc.nChar] = 0; /* Fast version of sqlite3StrAccumFinish(&acc) */
82909    p->n = acc.nChar;
82910  }
82911}
82912
82913#ifdef SQLITE_DEBUG
82914/*
82915** Validity checks on pMem.  pMem holds a string.
82916**
82917** (1) Check that string value of pMem agrees with its integer or real value.
82918** (2) Check that the string is correctly zero terminated
82919**
82920** A single int or real value always converts to the same strings.  But
82921** many different strings can be converted into the same int or real.
82922** If a table contains a numeric value and an index is based on the
82923** corresponding string value, then it is important that the string be
82924** derived from the numeric value, not the other way around, to ensure
82925** that the index and table are consistent.  See ticket
82926** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
82927** an example.
82928**
82929** This routine looks at pMem to verify that if it has both a numeric
82930** representation and a string representation then the string rep has
82931** been derived from the numeric and not the other way around.  It returns
82932** true if everything is ok and false if there is a problem.
82933**
82934** This routine is for use inside of assert() statements only.
82935*/
82936SQLITE_PRIVATE int sqlite3VdbeMemValidStrRep(Mem *p){
82937  Mem tmp;
82938  char zBuf[100];
82939  char *z;
82940  int i, j, incr;
82941  if( (p->flags & MEM_Str)==0 ) return 1;
82942  if( p->db && p->db->mallocFailed ) return 1;
82943  if( p->flags & MEM_Term ){
82944    /* Insure that the string is properly zero-terminated.  Pay particular
82945    ** attention to the case where p->n is odd */
82946    if( p->szMalloc>0 && p->z==p->zMalloc ){
82947      assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 );
82948      assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 );
82949    }
82950    assert( p->z[p->n]==0 );
82951    assert( p->enc==SQLITE_UTF8 || p->z[(p->n+1)&~1]==0 );
82952    assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 );
82953  }
82954  if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1;
82955  memcpy(&tmp, p, sizeof(tmp));
82956  vdbeMemRenderNum(sizeof(zBuf), zBuf, &tmp);
82957  z = p->z;
82958  i = j = 0;
82959  incr = 1;
82960  if( p->enc!=SQLITE_UTF8 ){
82961    incr = 2;
82962    if( p->enc==SQLITE_UTF16BE ) z++;
82963  }
82964  while( zBuf[j] ){
82965    if( zBuf[j++]!=z[i] ) return 0;
82966    i += incr;
82967  }
82968  return 1;
82969}
82970#endif /* SQLITE_DEBUG */
82971
82972/*
82973** If pMem is an object with a valid string representation, this routine
82974** ensures the internal encoding for the string representation is
82975** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
82976**
82977** If pMem is not a string object, or the encoding of the string
82978** representation is already stored using the requested encoding, then this
82979** routine is a no-op.
82980**
82981** SQLITE_OK is returned if the conversion is successful (or not required).
82982** SQLITE_NOMEM may be returned if a malloc() fails during conversion
82983** between formats.
82984*/
82985SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
82986#ifndef SQLITE_OMIT_UTF16
82987  int rc;
82988#endif
82989  assert( pMem!=0 );
82990  assert( !sqlite3VdbeMemIsRowSet(pMem) );
82991  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
82992           || desiredEnc==SQLITE_UTF16BE );
82993  if( !(pMem->flags&MEM_Str) ){
82994    pMem->enc = desiredEnc;
82995    return SQLITE_OK;
82996  }
82997  if( pMem->enc==desiredEnc ){
82998    return SQLITE_OK;
82999  }
83000  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
83001#ifdef SQLITE_OMIT_UTF16
83002  return SQLITE_ERROR;
83003#else
83004
83005  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
83006  ** then the encoding of the value may not have changed.
83007  */
83008  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
83009  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
83010  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
83011  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
83012  return rc;
83013#endif
83014}
83015
83016/*
83017** Make sure pMem->z points to a writable allocation of at least n bytes.
83018**
83019** If the bPreserve argument is true, then copy of the content of
83020** pMem->z into the new allocation.  pMem must be either a string or
83021** blob if bPreserve is true.  If bPreserve is false, any prior content
83022** in pMem->z is discarded.
83023*/
83024SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
83025  assert( sqlite3VdbeCheckMemInvariants(pMem) );
83026  assert( !sqlite3VdbeMemIsRowSet(pMem) );
83027  testcase( pMem->db==0 );
83028
83029  /* If the bPreserve flag is set to true, then the memory cell must already
83030  ** contain a valid string or blob value.  */
83031  assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
83032  testcase( bPreserve && pMem->z==0 );
83033
83034  assert( pMem->szMalloc==0
83035       || (pMem->flags==MEM_Undefined
83036           && pMem->szMalloc<=sqlite3DbMallocSize(pMem->db,pMem->zMalloc))
83037       || pMem->szMalloc==sqlite3DbMallocSize(pMem->db,pMem->zMalloc));
83038  if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
83039    if( pMem->db ){
83040      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
83041    }else{
83042      pMem->zMalloc = sqlite3Realloc(pMem->z, n);
83043      if( pMem->zMalloc==0 ) sqlite3_free(pMem->z);
83044      pMem->z = pMem->zMalloc;
83045    }
83046    bPreserve = 0;
83047  }else{
83048    if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
83049    pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
83050  }
83051  if( pMem->zMalloc==0 ){
83052    sqlite3VdbeMemSetNull(pMem);
83053    pMem->z = 0;
83054    pMem->szMalloc = 0;
83055    return SQLITE_NOMEM_BKPT;
83056  }else{
83057    pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
83058  }
83059
83060  if( bPreserve && pMem->z ){
83061    assert( pMem->z!=pMem->zMalloc );
83062    memcpy(pMem->zMalloc, pMem->z, pMem->n);
83063  }
83064  if( (pMem->flags&MEM_Dyn)!=0 ){
83065    assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
83066    pMem->xDel((void *)(pMem->z));
83067  }
83068
83069  pMem->z = pMem->zMalloc;
83070  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
83071  return SQLITE_OK;
83072}
83073
83074/*
83075** Change the pMem->zMalloc allocation to be at least szNew bytes.
83076** If pMem->zMalloc already meets or exceeds the requested size, this
83077** routine is a no-op.
83078**
83079** Any prior string or blob content in the pMem object may be discarded.
83080** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
83081** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, MEM_IntReal,
83082** and MEM_Null values are preserved.
83083**
83084** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
83085** if unable to complete the resizing.
83086*/
83087SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
83088  assert( CORRUPT_DB || szNew>0 );
83089  assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
83090  if( pMem->szMalloc<szNew ){
83091    return sqlite3VdbeMemGrow(pMem, szNew, 0);
83092  }
83093  assert( (pMem->flags & MEM_Dyn)==0 );
83094  pMem->z = pMem->zMalloc;
83095  pMem->flags &= (MEM_Null|MEM_Int|MEM_Real|MEM_IntReal);
83096  return SQLITE_OK;
83097}
83098
83099/*
83100** If pMem is already a string, detect if it is a zero-terminated
83101** string, or make it into one if possible, and mark it as such.
83102**
83103** This is an optimization.  Correct operation continues even if
83104** this routine is a no-op.
83105*/
83106SQLITE_PRIVATE void sqlite3VdbeMemZeroTerminateIfAble(Mem *pMem){
83107  if( (pMem->flags & (MEM_Str|MEM_Term|MEM_Ephem|MEM_Static))!=MEM_Str ){
83108    /* pMem must be a string, and it cannot be an ephemeral or static string */
83109    return;
83110  }
83111  if( pMem->enc!=SQLITE_UTF8 ) return;
83112  if( NEVER(pMem->z==0) ) return;
83113  if( pMem->flags & MEM_Dyn ){
83114    if( pMem->xDel==sqlite3_free
83115     && sqlite3_msize(pMem->z) >= (u64)(pMem->n+1)
83116    ){
83117      pMem->z[pMem->n] = 0;
83118      pMem->flags |= MEM_Term;
83119      return;
83120    }
83121    if( pMem->xDel==sqlite3RCStrUnref ){
83122      /* Blindly assume that all RCStr objects are zero-terminated */
83123      pMem->flags |= MEM_Term;
83124      return;
83125    }
83126  }else if( pMem->szMalloc >= pMem->n+1 ){
83127    pMem->z[pMem->n] = 0;
83128    pMem->flags |= MEM_Term;
83129    return;
83130  }
83131}
83132
83133/*
83134** It is already known that pMem contains an unterminated string.
83135** Add the zero terminator.
83136**
83137** Three bytes of zero are added.  In this way, there is guaranteed
83138** to be a double-zero byte at an even byte boundary in order to
83139** terminate a UTF16 string, even if the initial size of the buffer
83140** is an odd number of bytes.
83141*/
83142static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
83143  if( sqlite3VdbeMemGrow(pMem, pMem->n+3, 1) ){
83144    return SQLITE_NOMEM_BKPT;
83145  }
83146  pMem->z[pMem->n] = 0;
83147  pMem->z[pMem->n+1] = 0;
83148  pMem->z[pMem->n+2] = 0;
83149  pMem->flags |= MEM_Term;
83150  return SQLITE_OK;
83151}
83152
83153/*
83154** Change pMem so that its MEM_Str or MEM_Blob value is stored in
83155** MEM.zMalloc, where it can be safely written.
83156**
83157** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
83158*/
83159SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
83160  assert( pMem!=0 );
83161  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
83162  assert( !sqlite3VdbeMemIsRowSet(pMem) );
83163  if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
83164    if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
83165    if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
83166      int rc = vdbeMemAddTerminator(pMem);
83167      if( rc ) return rc;
83168    }
83169  }
83170  pMem->flags &= ~MEM_Ephem;
83171#ifdef SQLITE_DEBUG
83172  pMem->pScopyFrom = 0;
83173#endif
83174
83175  return SQLITE_OK;
83176}
83177
83178/*
83179** If the given Mem* has a zero-filled tail, turn it into an ordinary
83180** blob stored in dynamically allocated space.
83181*/
83182#ifndef SQLITE_OMIT_INCRBLOB
83183SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
83184  int nByte;
83185  assert( pMem!=0 );
83186  assert( pMem->flags & MEM_Zero );
83187  assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) );
83188  testcase( sqlite3_value_nochange(pMem) );
83189  assert( !sqlite3VdbeMemIsRowSet(pMem) );
83190  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
83191
83192  /* Set nByte to the number of bytes required to store the expanded blob. */
83193  nByte = pMem->n + pMem->u.nZero;
83194  if( nByte<=0 ){
83195    if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK;
83196    nByte = 1;
83197  }
83198  if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
83199    return SQLITE_NOMEM_BKPT;
83200  }
83201  assert( pMem->z!=0 );
83202  assert( sqlite3DbMallocSize(pMem->db,pMem->z) >= nByte );
83203
83204  memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
83205  pMem->n += pMem->u.nZero;
83206  pMem->flags &= ~(MEM_Zero|MEM_Term);
83207  return SQLITE_OK;
83208}
83209#endif
83210
83211/*
83212** Make sure the given Mem is \u0000 terminated.
83213*/
83214SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
83215  assert( pMem!=0 );
83216  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
83217  testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
83218  testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
83219  if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
83220    return SQLITE_OK;   /* Nothing to do */
83221  }else{
83222    return vdbeMemAddTerminator(pMem);
83223  }
83224}
83225
83226/*
83227** Add MEM_Str to the set of representations for the given Mem.  This
83228** routine is only called if pMem is a number of some kind, not a NULL
83229** or a BLOB.
83230**
83231** Existing representations MEM_Int, MEM_Real, or MEM_IntReal are invalidated
83232** if bForce is true but are retained if bForce is false.
83233**
83234** A MEM_Null value will never be passed to this function. This function is
83235** used for converting values to text for returning to the user (i.e. via
83236** sqlite3_value_text()), or for ensuring that values to be used as btree
83237** keys are strings. In the former case a NULL pointer is returned the
83238** user and the latter is an internal programming error.
83239*/
83240SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
83241  const int nByte = 32;
83242
83243  assert( pMem!=0 );
83244  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
83245  assert( !(pMem->flags&MEM_Zero) );
83246  assert( !(pMem->flags&(MEM_Str|MEM_Blob)) );
83247  assert( pMem->flags&(MEM_Int|MEM_Real|MEM_IntReal) );
83248  assert( !sqlite3VdbeMemIsRowSet(pMem) );
83249  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
83250
83251
83252  if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
83253    pMem->enc = 0;
83254    return SQLITE_NOMEM_BKPT;
83255  }
83256
83257  vdbeMemRenderNum(nByte, pMem->z, pMem);
83258  assert( pMem->z!=0 );
83259  assert( pMem->n==(int)sqlite3Strlen30NN(pMem->z) );
83260  pMem->enc = SQLITE_UTF8;
83261  pMem->flags |= MEM_Str|MEM_Term;
83262  if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
83263  sqlite3VdbeChangeEncoding(pMem, enc);
83264  return SQLITE_OK;
83265}
83266
83267/*
83268** Memory cell pMem contains the context of an aggregate function.
83269** This routine calls the finalize method for that function.  The
83270** result of the aggregate is stored back into pMem.
83271**
83272** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
83273** otherwise.
83274*/
83275SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
83276  sqlite3_context ctx;
83277  Mem t;
83278  assert( pFunc!=0 );
83279  assert( pMem!=0 );
83280  assert( pMem->db!=0 );
83281  assert( pFunc->xFinalize!=0 );
83282  assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
83283  assert( sqlite3_mutex_held(pMem->db->mutex) );
83284  memset(&ctx, 0, sizeof(ctx));
83285  memset(&t, 0, sizeof(t));
83286  t.flags = MEM_Null;
83287  t.db = pMem->db;
83288  ctx.pOut = &t;
83289  ctx.pMem = pMem;
83290  ctx.pFunc = pFunc;
83291  ctx.enc = ENC(t.db);
83292  pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
83293  assert( (pMem->flags & MEM_Dyn)==0 );
83294  if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
83295  memcpy(pMem, &t, sizeof(t));
83296  return ctx.isError;
83297}
83298
83299/*
83300** Memory cell pAccum contains the context of an aggregate function.
83301** This routine calls the xValue method for that function and stores
83302** the results in memory cell pMem.
83303**
83304** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK
83305** otherwise.
83306*/
83307#ifndef SQLITE_OMIT_WINDOWFUNC
83308SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){
83309  sqlite3_context ctx;
83310  assert( pFunc!=0 );
83311  assert( pFunc->xValue!=0 );
83312  assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
83313  assert( pAccum->db!=0 );
83314  assert( sqlite3_mutex_held(pAccum->db->mutex) );
83315  memset(&ctx, 0, sizeof(ctx));
83316  sqlite3VdbeMemSetNull(pOut);
83317  ctx.pOut = pOut;
83318  ctx.pMem = pAccum;
83319  ctx.pFunc = pFunc;
83320  ctx.enc = ENC(pAccum->db);
83321  pFunc->xValue(&ctx);
83322  return ctx.isError;
83323}
83324#endif /* SQLITE_OMIT_WINDOWFUNC */
83325
83326/*
83327** If the memory cell contains a value that must be freed by
83328** invoking the external callback in Mem.xDel, then this routine
83329** will free that value.  It also sets Mem.flags to MEM_Null.
83330**
83331** This is a helper routine for sqlite3VdbeMemSetNull() and
83332** for sqlite3VdbeMemRelease().  Use those other routines as the
83333** entry point for releasing Mem resources.
83334*/
83335static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
83336  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
83337  assert( VdbeMemDynamic(p) );
83338  if( p->flags&MEM_Agg ){
83339    sqlite3VdbeMemFinalize(p, p->u.pDef);
83340    assert( (p->flags & MEM_Agg)==0 );
83341    testcase( p->flags & MEM_Dyn );
83342  }
83343  if( p->flags&MEM_Dyn ){
83344    assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
83345    p->xDel((void *)p->z);
83346  }
83347  p->flags = MEM_Null;
83348}
83349
83350/*
83351** Release memory held by the Mem p, both external memory cleared
83352** by p->xDel and memory in p->zMalloc.
83353**
83354** This is a helper routine invoked by sqlite3VdbeMemRelease() in
83355** the unusual case where there really is memory in p that needs
83356** to be freed.
83357*/
83358static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
83359  if( VdbeMemDynamic(p) ){
83360    vdbeMemClearExternAndSetNull(p);
83361  }
83362  if( p->szMalloc ){
83363    sqlite3DbFreeNN(p->db, p->zMalloc);
83364    p->szMalloc = 0;
83365  }
83366  p->z = 0;
83367}
83368
83369/*
83370** Release any memory resources held by the Mem.  Both the memory that is
83371** free by Mem.xDel and the Mem.zMalloc allocation are freed.
83372**
83373** Use this routine prior to clean up prior to abandoning a Mem, or to
83374** reset a Mem back to its minimum memory utilization.
83375**
83376** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
83377** prior to inserting new content into the Mem.
83378*/
83379SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
83380  assert( sqlite3VdbeCheckMemInvariants(p) );
83381  if( VdbeMemDynamic(p) || p->szMalloc ){
83382    vdbeMemClear(p);
83383  }
83384}
83385
83386/* Like sqlite3VdbeMemRelease() but faster for cases where we
83387** know in advance that the Mem is not MEM_Dyn or MEM_Agg.
83388*/
83389SQLITE_PRIVATE void sqlite3VdbeMemReleaseMalloc(Mem *p){
83390  assert( !VdbeMemDynamic(p) );
83391  if( p->szMalloc ) vdbeMemClear(p);
83392}
83393
83394/*
83395** Return some kind of integer value which is the best we can do
83396** at representing the value that *pMem describes as an integer.
83397** If pMem is an integer, then the value is exact.  If pMem is
83398** a floating-point then the value returned is the integer part.
83399** If pMem is a string or blob, then we make an attempt to convert
83400** it into an integer and return that.  If pMem represents an
83401** an SQL-NULL value, return 0.
83402**
83403** If pMem represents a string value, its encoding might be changed.
83404*/
83405static SQLITE_NOINLINE i64 memIntValue(const Mem *pMem){
83406  i64 value = 0;
83407  sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
83408  return value;
83409}
83410SQLITE_PRIVATE i64 sqlite3VdbeIntValue(const Mem *pMem){
83411  int flags;
83412  assert( pMem!=0 );
83413  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
83414  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
83415  flags = pMem->flags;
83416  if( flags & (MEM_Int|MEM_IntReal) ){
83417    testcase( flags & MEM_IntReal );
83418    return pMem->u.i;
83419  }else if( flags & MEM_Real ){
83420    return sqlite3RealToI64(pMem->u.r);
83421  }else if( (flags & (MEM_Str|MEM_Blob))!=0 && pMem->z!=0 ){
83422    return memIntValue(pMem);
83423  }else{
83424    return 0;
83425  }
83426}
83427
83428/*
83429** Return the best representation of pMem that we can get into a
83430** double.  If pMem is already a double or an integer, return its
83431** value.  If it is a string or blob, try to convert it to a double.
83432** If it is a NULL, return 0.0.
83433*/
83434static SQLITE_NOINLINE double memRealValue(Mem *pMem){
83435  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
83436  double val = (double)0;
83437  sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
83438  return val;
83439}
83440SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
83441  assert( pMem!=0 );
83442  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
83443  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
83444  if( pMem->flags & MEM_Real ){
83445    return pMem->u.r;
83446  }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
83447    testcase( pMem->flags & MEM_IntReal );
83448    return (double)pMem->u.i;
83449  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
83450    return memRealValue(pMem);
83451  }else{
83452    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
83453    return (double)0;
83454  }
83455}
83456
83457/*
83458** Return 1 if pMem represents true, and return 0 if pMem represents false.
83459** Return the value ifNull if pMem is NULL.
83460*/
83461SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
83462  testcase( pMem->flags & MEM_IntReal );
83463  if( pMem->flags & (MEM_Int|MEM_IntReal) ) return pMem->u.i!=0;
83464  if( pMem->flags & MEM_Null ) return ifNull;
83465  return sqlite3VdbeRealValue(pMem)!=0.0;
83466}
83467
83468/*
83469** The MEM structure is already a MEM_Real or MEM_IntReal. Try to
83470** make it a MEM_Int if we can.
83471*/
83472SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
83473  assert( pMem!=0 );
83474  assert( pMem->flags & (MEM_Real|MEM_IntReal) );
83475  assert( !sqlite3VdbeMemIsRowSet(pMem) );
83476  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
83477  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
83478
83479  if( pMem->flags & MEM_IntReal ){
83480    MemSetTypeFlag(pMem, MEM_Int);
83481  }else{
83482    i64 ix = sqlite3RealToI64(pMem->u.r);
83483
83484    /* Only mark the value as an integer if
83485    **
83486    **    (1) the round-trip conversion real->int->real is a no-op, and
83487    **    (2) The integer is neither the largest nor the smallest
83488    **        possible integer (ticket #3922)
83489    **
83490    ** The second and third terms in the following conditional enforces
83491    ** the second condition under the assumption that addition overflow causes
83492    ** values to wrap around.
83493    */
83494    if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
83495      pMem->u.i = ix;
83496      MemSetTypeFlag(pMem, MEM_Int);
83497    }
83498  }
83499}
83500
83501/*
83502** Convert pMem to type integer.  Invalidate any prior representations.
83503*/
83504SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
83505  assert( pMem!=0 );
83506  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
83507  assert( !sqlite3VdbeMemIsRowSet(pMem) );
83508  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
83509
83510  pMem->u.i = sqlite3VdbeIntValue(pMem);
83511  MemSetTypeFlag(pMem, MEM_Int);
83512  return SQLITE_OK;
83513}
83514
83515/*
83516** Convert pMem so that it is of type MEM_Real.
83517** Invalidate any prior representations.
83518*/
83519SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
83520  assert( pMem!=0 );
83521  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
83522  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
83523
83524  pMem->u.r = sqlite3VdbeRealValue(pMem);
83525  MemSetTypeFlag(pMem, MEM_Real);
83526  return SQLITE_OK;
83527}
83528
83529/* Compare a floating point value to an integer.  Return true if the two
83530** values are the same within the precision of the floating point value.
83531**
83532** This function assumes that i was obtained by assignment from r1.
83533**
83534** For some versions of GCC on 32-bit machines, if you do the more obvious
83535** comparison of "r1==(double)i" you sometimes get an answer of false even
83536** though the r1 and (double)i values are bit-for-bit the same.
83537*/
83538SQLITE_PRIVATE int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
83539  double r2 = (double)i;
83540  return r1==0.0
83541      || (memcmp(&r1, &r2, sizeof(r1))==0
83542          && i >= -2251799813685248LL && i < 2251799813685248LL);
83543}
83544
83545/* Convert a floating point value to its closest integer.  Do so in
83546** a way that avoids 'outside the range of representable values' warnings
83547** from UBSAN.
83548*/
83549SQLITE_PRIVATE i64 sqlite3RealToI64(double r){
83550  if( r<-9223372036854774784.0 ) return SMALLEST_INT64;
83551  if( r>+9223372036854774784.0 ) return LARGEST_INT64;
83552  return (i64)r;
83553}
83554
83555/*
83556** Convert pMem so that it has type MEM_Real or MEM_Int.
83557** Invalidate any prior representations.
83558**
83559** Every effort is made to force the conversion, even if the input
83560** is a string that does not look completely like a number.  Convert
83561** as much of the string as we can and ignore the rest.
83562*/
83563SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
83564  assert( pMem!=0 );
83565  testcase( pMem->flags & MEM_Int );
83566  testcase( pMem->flags & MEM_Real );
83567  testcase( pMem->flags & MEM_IntReal );
83568  testcase( pMem->flags & MEM_Null );
83569  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))==0 ){
83570    int rc;
83571    sqlite3_int64 ix;
83572    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
83573    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
83574    rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
83575    if( ((rc==0 || rc==1) && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1)
83576     || sqlite3RealSameAsInt(pMem->u.r, (ix = sqlite3RealToI64(pMem->u.r)))
83577    ){
83578      pMem->u.i = ix;
83579      MemSetTypeFlag(pMem, MEM_Int);
83580    }else{
83581      MemSetTypeFlag(pMem, MEM_Real);
83582    }
83583  }
83584  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))!=0 );
83585  pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
83586  return SQLITE_OK;
83587}
83588
83589/*
83590** Cast the datatype of the value in pMem according to the affinity
83591** "aff".  Casting is different from applying affinity in that a cast
83592** is forced.  In other words, the value is converted into the desired
83593** affinity even if that results in loss of data.  This routine is
83594** used (for example) to implement the SQL "cast()" operator.
83595*/
83596SQLITE_PRIVATE int sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
83597  if( pMem->flags & MEM_Null ) return SQLITE_OK;
83598  switch( aff ){
83599    case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
83600      if( (pMem->flags & MEM_Blob)==0 ){
83601        sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
83602        assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
83603        if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
83604      }else{
83605        pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
83606      }
83607      break;
83608    }
83609    case SQLITE_AFF_NUMERIC: {
83610      sqlite3VdbeMemNumerify(pMem);
83611      break;
83612    }
83613    case SQLITE_AFF_INTEGER: {
83614      sqlite3VdbeMemIntegerify(pMem);
83615      break;
83616    }
83617    case SQLITE_AFF_REAL: {
83618      sqlite3VdbeMemRealify(pMem);
83619      break;
83620    }
83621    default: {
83622      int rc;
83623      assert( aff==SQLITE_AFF_TEXT );
83624      assert( MEM_Str==(MEM_Blob>>3) );
83625      pMem->flags |= (pMem->flags&MEM_Blob)>>3;
83626      sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
83627      assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
83628      pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero);
83629      if( encoding!=SQLITE_UTF8 ) pMem->n &= ~1;
83630      rc = sqlite3VdbeChangeEncoding(pMem, encoding);
83631      if( rc ) return rc;
83632      sqlite3VdbeMemZeroTerminateIfAble(pMem);
83633    }
83634  }
83635  return SQLITE_OK;
83636}
83637
83638/*
83639** Initialize bulk memory to be a consistent Mem object.
83640**
83641** The minimum amount of initialization feasible is performed.
83642*/
83643SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
83644  assert( (flags & ~MEM_TypeMask)==0 );
83645  pMem->flags = flags;
83646  pMem->db = db;
83647  pMem->szMalloc = 0;
83648}
83649
83650
83651/*
83652** Delete any previous value and set the value stored in *pMem to NULL.
83653**
83654** This routine calls the Mem.xDel destructor to dispose of values that
83655** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
83656** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
83657** routine to invoke the destructor and deallocates Mem.zMalloc.
83658**
83659** Use this routine to reset the Mem prior to insert a new value.
83660**
83661** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
83662*/
83663SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
83664  if( VdbeMemDynamic(pMem) ){
83665    vdbeMemClearExternAndSetNull(pMem);
83666  }else{
83667    pMem->flags = MEM_Null;
83668  }
83669}
83670SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
83671  sqlite3VdbeMemSetNull((Mem*)p);
83672}
83673
83674/*
83675** Delete any previous value and set the value to be a BLOB of length
83676** n containing all zeros.
83677*/
83678#ifndef SQLITE_OMIT_INCRBLOB
83679SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
83680  sqlite3VdbeMemRelease(pMem);
83681  pMem->flags = MEM_Blob|MEM_Zero;
83682  pMem->n = 0;
83683  if( n<0 ) n = 0;
83684  pMem->u.nZero = n;
83685  pMem->enc = SQLITE_UTF8;
83686  pMem->z = 0;
83687}
83688#else
83689SQLITE_PRIVATE int sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
83690  int nByte = n>0?n:1;
83691  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
83692    return SQLITE_NOMEM_BKPT;
83693  }
83694  assert( pMem->z!=0 );
83695  assert( sqlite3DbMallocSize(pMem->db, pMem->z)>=nByte );
83696  memset(pMem->z, 0, nByte);
83697  pMem->n = n>0?n:0;
83698  pMem->flags = MEM_Blob;
83699  pMem->enc = SQLITE_UTF8;
83700  return SQLITE_OK;
83701}
83702#endif
83703
83704/*
83705** The pMem is known to contain content that needs to be destroyed prior
83706** to a value change.  So invoke the destructor, then set the value to
83707** a 64-bit integer.
83708*/
83709static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
83710  sqlite3VdbeMemSetNull(pMem);
83711  pMem->u.i = val;
83712  pMem->flags = MEM_Int;
83713}
83714
83715/*
83716** Delete any previous value and set the value stored in *pMem to val,
83717** manifest type INTEGER.
83718*/
83719SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
83720  if( VdbeMemDynamic(pMem) ){
83721    vdbeReleaseAndSetInt64(pMem, val);
83722  }else{
83723    pMem->u.i = val;
83724    pMem->flags = MEM_Int;
83725  }
83726}
83727
83728/*
83729** Set the iIdx'th entry of array aMem[] to contain integer value val.
83730*/
83731SQLITE_PRIVATE void sqlite3MemSetArrayInt64(sqlite3_value *aMem, int iIdx, i64 val){
83732  sqlite3VdbeMemSetInt64(&aMem[iIdx], val);
83733}
83734
83735/* A no-op destructor */
83736SQLITE_PRIVATE void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
83737
83738/*
83739** Set the value stored in *pMem should already be a NULL.
83740** Also store a pointer to go with it.
83741*/
83742SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
83743  Mem *pMem,
83744  void *pPtr,
83745  const char *zPType,
83746  void (*xDestructor)(void*)
83747){
83748  assert( pMem->flags==MEM_Null );
83749  vdbeMemClear(pMem);
83750  pMem->u.zPType = zPType ? zPType : "";
83751  pMem->z = pPtr;
83752  pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
83753  pMem->eSubtype = 'p';
83754  pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
83755}
83756
83757#ifndef SQLITE_OMIT_FLOATING_POINT
83758/*
83759** Delete any previous value and set the value stored in *pMem to val,
83760** manifest type REAL.
83761*/
83762SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
83763  sqlite3VdbeMemSetNull(pMem);
83764  if( !sqlite3IsNaN(val) ){
83765    pMem->u.r = val;
83766    pMem->flags = MEM_Real;
83767  }
83768}
83769#endif
83770
83771#ifdef SQLITE_DEBUG
83772/*
83773** Return true if the Mem holds a RowSet object.  This routine is intended
83774** for use inside of assert() statements.
83775*/
83776SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem *pMem){
83777  return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)
83778         && pMem->xDel==sqlite3RowSetDelete;
83779}
83780#endif
83781
83782/*
83783** Delete any previous value and set the value of pMem to be an
83784** empty boolean index.
83785**
83786** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation
83787** error occurs.
83788*/
83789SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem *pMem){
83790  sqlite3 *db = pMem->db;
83791  RowSet *p;
83792  assert( db!=0 );
83793  assert( !sqlite3VdbeMemIsRowSet(pMem) );
83794  sqlite3VdbeMemRelease(pMem);
83795  p = sqlite3RowSetInit(db);
83796  if( p==0 ) return SQLITE_NOMEM;
83797  pMem->z = (char*)p;
83798  pMem->flags = MEM_Blob|MEM_Dyn;
83799  pMem->xDel = sqlite3RowSetDelete;
83800  return SQLITE_OK;
83801}
83802
83803/*
83804** Return true if the Mem object contains a TEXT or BLOB that is
83805** too large - whose size exceeds SQLITE_MAX_LENGTH.
83806*/
83807SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
83808  assert( p->db!=0 );
83809  if( p->flags & (MEM_Str|MEM_Blob) ){
83810    int n = p->n;
83811    if( p->flags & MEM_Zero ){
83812      n += p->u.nZero;
83813    }
83814    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
83815  }
83816  return 0;
83817}
83818
83819#ifdef SQLITE_DEBUG
83820/*
83821** This routine prepares a memory cell for modification by breaking
83822** its link to a shallow copy and by marking any current shallow
83823** copies of this cell as invalid.
83824**
83825** This is used for testing and debugging only - to help ensure that shallow
83826** copies (created by OP_SCopy) are not misused.
83827*/
83828SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
83829  int i;
83830  Mem *pX;
83831  for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){
83832    if( pX->pScopyFrom==pMem ){
83833      u16 mFlags;
83834      if( pVdbe->db->flags & SQLITE_VdbeTrace ){
83835        sqlite3DebugPrintf("Invalidate R[%d] due to change in R[%d]\n",
83836          (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem));
83837      }
83838      /* If pX is marked as a shallow copy of pMem, then try to verify that
83839      ** no significant changes have been made to pX since the OP_SCopy.
83840      ** A significant change would indicated a missed call to this
83841      ** function for pX.  Minor changes, such as adding or removing a
83842      ** dual type, are allowed, as long as the underlying value is the
83843      ** same. */
83844      mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
83845      assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i );
83846
83847      /* pMem is the register that is changing.  But also mark pX as
83848      ** undefined so that we can quickly detect the shallow-copy error */
83849      pX->flags = MEM_Undefined;
83850      pX->pScopyFrom = 0;
83851    }
83852  }
83853  pMem->pScopyFrom = 0;
83854}
83855#endif /* SQLITE_DEBUG */
83856
83857/*
83858** Make an shallow copy of pFrom into pTo.  Prior contents of
83859** pTo are freed.  The pFrom->z field is not duplicated.  If
83860** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
83861** and flags gets srcType (either MEM_Ephem or MEM_Static).
83862*/
83863static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
83864  vdbeMemClearExternAndSetNull(pTo);
83865  assert( !VdbeMemDynamic(pTo) );
83866  sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
83867}
83868SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
83869  assert( !sqlite3VdbeMemIsRowSet(pFrom) );
83870  assert( pTo->db==pFrom->db );
83871  if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
83872  memcpy(pTo, pFrom, MEMCELLSIZE);
83873  if( (pFrom->flags&MEM_Static)==0 ){
83874    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
83875    assert( srcType==MEM_Ephem || srcType==MEM_Static );
83876    pTo->flags |= srcType;
83877  }
83878}
83879
83880/*
83881** Make a full copy of pFrom into pTo.  Prior contents of pTo are
83882** freed before the copy is made.
83883*/
83884SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
83885  int rc = SQLITE_OK;
83886
83887  assert( !sqlite3VdbeMemIsRowSet(pFrom) );
83888  if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
83889  memcpy(pTo, pFrom, MEMCELLSIZE);
83890  pTo->flags &= ~MEM_Dyn;
83891  if( pTo->flags&(MEM_Str|MEM_Blob) ){
83892    if( 0==(pFrom->flags&MEM_Static) ){
83893      pTo->flags |= MEM_Ephem;
83894      rc = sqlite3VdbeMemMakeWriteable(pTo);
83895    }
83896  }
83897
83898  return rc;
83899}
83900
83901/*
83902** Transfer the contents of pFrom to pTo. Any existing value in pTo is
83903** freed. If pFrom contains ephemeral data, a copy is made.
83904**
83905** pFrom contains an SQL NULL when this routine returns.
83906*/
83907SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
83908  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
83909  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
83910  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
83911
83912  sqlite3VdbeMemRelease(pTo);
83913  memcpy(pTo, pFrom, sizeof(Mem));
83914  pFrom->flags = MEM_Null;
83915  pFrom->szMalloc = 0;
83916}
83917
83918/*
83919** Change the value of a Mem to be a string or a BLOB.
83920**
83921** The memory management strategy depends on the value of the xDel
83922** parameter. If the value passed is SQLITE_TRANSIENT, then the
83923** string is copied into a (possibly existing) buffer managed by the
83924** Mem structure. Otherwise, any existing buffer is freed and the
83925** pointer copied.
83926**
83927** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
83928** size limit) then no memory allocation occurs.  If the string can be
83929** stored without allocating memory, then it is.  If a memory allocation
83930** is required to store the string, then value of pMem is unchanged.  In
83931** either case, SQLITE_TOOBIG is returned.
83932**
83933** The "enc" parameter is the text encoding for the string, or zero
83934** to store a blob.
83935**
83936** If n is negative, then the string consists of all bytes up to but
83937** excluding the first zero character.  The n parameter must be
83938** non-negative for blobs.
83939*/
83940SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
83941  Mem *pMem,          /* Memory cell to set to string value */
83942  const char *z,      /* String pointer */
83943  i64 n,              /* Bytes in string, or negative */
83944  u8 enc,             /* Encoding of z.  0 for BLOBs */
83945  void (*xDel)(void*) /* Destructor function */
83946){
83947  i64 nByte = n;      /* New value for pMem->n */
83948  int iLimit;         /* Maximum allowed string or blob size */
83949  u16 flags;          /* New value for pMem->flags */
83950
83951  assert( pMem!=0 );
83952  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
83953  assert( !sqlite3VdbeMemIsRowSet(pMem) );
83954  assert( enc!=0 || n>=0 );
83955
83956  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
83957  if( !z ){
83958    sqlite3VdbeMemSetNull(pMem);
83959    return SQLITE_OK;
83960  }
83961
83962  if( pMem->db ){
83963    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
83964  }else{
83965    iLimit = SQLITE_MAX_LENGTH;
83966  }
83967  if( nByte<0 ){
83968    assert( enc!=0 );
83969    if( enc==SQLITE_UTF8 ){
83970      nByte = strlen(z);
83971    }else{
83972      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
83973    }
83974    flags= MEM_Str|MEM_Term;
83975  }else if( enc==0 ){
83976    flags = MEM_Blob;
83977    enc = SQLITE_UTF8;
83978  }else{
83979    flags = MEM_Str;
83980  }
83981  if( nByte>iLimit ){
83982    if( xDel && xDel!=SQLITE_TRANSIENT ){
83983      if( xDel==SQLITE_DYNAMIC ){
83984        sqlite3DbFree(pMem->db, (void*)z);
83985      }else{
83986        xDel((void*)z);
83987      }
83988    }
83989    sqlite3VdbeMemSetNull(pMem);
83990    return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
83991  }
83992
83993  /* The following block sets the new values of Mem.z and Mem.xDel. It
83994  ** also sets a flag in local variable "flags" to indicate the memory
83995  ** management (one of MEM_Dyn or MEM_Static).
83996  */
83997  if( xDel==SQLITE_TRANSIENT ){
83998    i64 nAlloc = nByte;
83999    if( flags&MEM_Term ){
84000      nAlloc += (enc==SQLITE_UTF8?1:2);
84001    }
84002    testcase( nAlloc==0 );
84003    testcase( nAlloc==31 );
84004    testcase( nAlloc==32 );
84005    if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){
84006      return SQLITE_NOMEM_BKPT;
84007    }
84008    memcpy(pMem->z, z, nAlloc);
84009  }else{
84010    sqlite3VdbeMemRelease(pMem);
84011    pMem->z = (char *)z;
84012    if( xDel==SQLITE_DYNAMIC ){
84013      pMem->zMalloc = pMem->z;
84014      pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
84015    }else{
84016      pMem->xDel = xDel;
84017      flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
84018    }
84019  }
84020
84021  pMem->n = (int)(nByte & 0x7fffffff);
84022  pMem->flags = flags;
84023  pMem->enc = enc;
84024
84025#ifndef SQLITE_OMIT_UTF16
84026  if( enc>SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
84027    return SQLITE_NOMEM_BKPT;
84028  }
84029#endif
84030
84031
84032  return SQLITE_OK;
84033}
84034
84035/*
84036** Move data out of a btree key or data field and into a Mem structure.
84037** The data is payload from the entry that pCur is currently pointing
84038** to.  offset and amt determine what portion of the data or key to retrieve.
84039** The result is written into the pMem element.
84040**
84041** The pMem object must have been initialized.  This routine will use
84042** pMem->zMalloc to hold the content from the btree, if possible.  New
84043** pMem->zMalloc space will be allocated if necessary.  The calling routine
84044** is responsible for making sure that the pMem object is eventually
84045** destroyed.
84046**
84047** If this routine fails for any reason (malloc returns NULL or unable
84048** to read from the disk) then the pMem is left in an inconsistent state.
84049*/
84050SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
84051  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
84052  u32 offset,       /* Offset from the start of data to return bytes from. */
84053  u32 amt,          /* Number of bytes to return. */
84054  Mem *pMem         /* OUT: Return data in this Mem structure. */
84055){
84056  int rc;
84057  pMem->flags = MEM_Null;
84058  if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){
84059    return SQLITE_CORRUPT_BKPT;
84060  }
84061  if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
84062    rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
84063    if( rc==SQLITE_OK ){
84064      pMem->z[amt] = 0;   /* Overrun area used when reading malformed records */
84065      pMem->flags = MEM_Blob;
84066      pMem->n = (int)amt;
84067    }else{
84068      sqlite3VdbeMemRelease(pMem);
84069    }
84070  }
84071  return rc;
84072}
84073SQLITE_PRIVATE int sqlite3VdbeMemFromBtreeZeroOffset(
84074  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
84075  u32 amt,          /* Number of bytes to return. */
84076  Mem *pMem         /* OUT: Return data in this Mem structure. */
84077){
84078  u32 available = 0;  /* Number of bytes available on the local btree page */
84079  int rc = SQLITE_OK; /* Return code */
84080
84081  assert( sqlite3BtreeCursorIsValid(pCur) );
84082  assert( !VdbeMemDynamic(pMem) );
84083
84084  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
84085  ** that both the BtShared and database handle mutexes are held. */
84086  assert( !sqlite3VdbeMemIsRowSet(pMem) );
84087  pMem->z = (char *)sqlite3BtreePayloadFetch(pCur, &available);
84088  assert( pMem->z!=0 );
84089
84090  if( amt<=available ){
84091    pMem->flags = MEM_Blob|MEM_Ephem;
84092    pMem->n = (int)amt;
84093  }else{
84094    rc = sqlite3VdbeMemFromBtree(pCur, 0, amt, pMem);
84095  }
84096
84097  return rc;
84098}
84099
84100/*
84101** The pVal argument is known to be a value other than NULL.
84102** Convert it into a string with encoding enc and return a pointer
84103** to a zero-terminated version of that string.
84104*/
84105static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
84106  assert( pVal!=0 );
84107  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
84108  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
84109  assert( !sqlite3VdbeMemIsRowSet(pVal) );
84110  assert( (pVal->flags & (MEM_Null))==0 );
84111  if( pVal->flags & (MEM_Blob|MEM_Str) ){
84112    if( ExpandBlob(pVal) ) return 0;
84113    pVal->flags |= MEM_Str;
84114    if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
84115      sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
84116    }
84117    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
84118      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
84119      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
84120        return 0;
84121      }
84122    }
84123    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
84124  }else{
84125    sqlite3VdbeMemStringify(pVal, enc, 0);
84126    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
84127  }
84128  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
84129              || pVal->db->mallocFailed );
84130  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
84131    assert( sqlite3VdbeMemValidStrRep(pVal) );
84132    return pVal->z;
84133  }else{
84134    return 0;
84135  }
84136}
84137
84138/* This function is only available internally, it is not part of the
84139** external API. It works in a similar way to sqlite3_value_text(),
84140** except the data returned is in the encoding specified by the second
84141** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
84142** SQLITE_UTF8.
84143**
84144** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
84145** If that is the case, then the result must be aligned on an even byte
84146** boundary.
84147*/
84148SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
84149  if( !pVal ) return 0;
84150  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
84151  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
84152  assert( !sqlite3VdbeMemIsRowSet(pVal) );
84153  if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
84154    assert( sqlite3VdbeMemValidStrRep(pVal) );
84155    return pVal->z;
84156  }
84157  if( pVal->flags&MEM_Null ){
84158    return 0;
84159  }
84160  return valueToText(pVal, enc);
84161}
84162
84163/* Return true if sqlit3_value object pVal is a string or blob value
84164** that uses the destructor specified in the second argument.
84165**
84166** TODO:  Maybe someday promote this interface into a published API so
84167** that third-party extensions can get access to it?
84168*/
84169SQLITE_PRIVATE int sqlite3ValueIsOfClass(const sqlite3_value *pVal, void(*xFree)(void*)){
84170  if( ALWAYS(pVal!=0)
84171   && ALWAYS((pVal->flags & (MEM_Str|MEM_Blob))!=0)
84172   && (pVal->flags & MEM_Dyn)!=0
84173   && pVal->xDel==xFree
84174  ){
84175    return 1;
84176  }else{
84177    return 0;
84178  }
84179}
84180
84181/*
84182** Create a new sqlite3_value object.
84183*/
84184SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
84185  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
84186  if( p ){
84187    p->flags = MEM_Null;
84188    p->db = db;
84189  }
84190  return p;
84191}
84192
84193/*
84194** Context object passed by sqlite3Stat4ProbeSetValue() through to
84195** valueNew(). See comments above valueNew() for details.
84196*/
84197struct ValueNewStat4Ctx {
84198  Parse *pParse;
84199  Index *pIdx;
84200  UnpackedRecord **ppRec;
84201  int iVal;
84202};
84203
84204/*
84205** Allocate and return a pointer to a new sqlite3_value object. If
84206** the second argument to this function is NULL, the object is allocated
84207** by calling sqlite3ValueNew().
84208**
84209** Otherwise, if the second argument is non-zero, then this function is
84210** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
84211** already been allocated, allocate the UnpackedRecord structure that
84212** that function will return to its caller here. Then return a pointer to
84213** an sqlite3_value within the UnpackedRecord.a[] array.
84214*/
84215static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
84216#ifdef SQLITE_ENABLE_STAT4
84217  if( p ){
84218    UnpackedRecord *pRec = p->ppRec[0];
84219
84220    if( pRec==0 ){
84221      Index *pIdx = p->pIdx;      /* Index being probed */
84222      int nByte;                  /* Bytes of space to allocate */
84223      int i;                      /* Counter variable */
84224      int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
84225
84226      nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
84227      pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
84228      if( pRec ){
84229        pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
84230        if( pRec->pKeyInfo ){
84231          assert( pRec->pKeyInfo->nAllField==nCol );
84232          assert( pRec->pKeyInfo->enc==ENC(db) );
84233          pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
84234          for(i=0; i<nCol; i++){
84235            pRec->aMem[i].flags = MEM_Null;
84236            pRec->aMem[i].db = db;
84237          }
84238        }else{
84239          sqlite3DbFreeNN(db, pRec);
84240          pRec = 0;
84241        }
84242      }
84243      if( pRec==0 ) return 0;
84244      p->ppRec[0] = pRec;
84245    }
84246
84247    pRec->nField = p->iVal+1;
84248    sqlite3VdbeMemSetNull(&pRec->aMem[p->iVal]);
84249    return &pRec->aMem[p->iVal];
84250  }
84251#else
84252  UNUSED_PARAMETER(p);
84253#endif /* defined(SQLITE_ENABLE_STAT4) */
84254  return sqlite3ValueNew(db);
84255}
84256
84257/*
84258** The expression object indicated by the second argument is guaranteed
84259** to be a scalar SQL function. If
84260**
84261**   * all function arguments are SQL literals,
84262**   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
84263**   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
84264**
84265** then this routine attempts to invoke the SQL function. Assuming no
84266** error occurs, output parameter (*ppVal) is set to point to a value
84267** object containing the result before returning SQLITE_OK.
84268**
84269** Affinity aff is applied to the result of the function before returning.
84270** If the result is a text value, the sqlite3_value object uses encoding
84271** enc.
84272**
84273** If the conditions above are not met, this function returns SQLITE_OK
84274** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
84275** NULL and an SQLite error code returned.
84276*/
84277#ifdef SQLITE_ENABLE_STAT4
84278static int valueFromFunction(
84279  sqlite3 *db,                    /* The database connection */
84280  const Expr *p,                  /* The expression to evaluate */
84281  u8 enc,                         /* Encoding to use */
84282  u8 aff,                         /* Affinity to use */
84283  sqlite3_value **ppVal,          /* Write the new value here */
84284  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
84285){
84286  sqlite3_context ctx;            /* Context object for function invocation */
84287  sqlite3_value **apVal = 0;      /* Function arguments */
84288  int nVal = 0;                   /* Size of apVal[] array */
84289  FuncDef *pFunc = 0;             /* Function definition */
84290  sqlite3_value *pVal = 0;        /* New value */
84291  int rc = SQLITE_OK;             /* Return code */
84292  ExprList *pList = 0;            /* Function arguments */
84293  int i;                          /* Iterator variable */
84294
84295  assert( pCtx!=0 );
84296  assert( (p->flags & EP_TokenOnly)==0 );
84297  assert( ExprUseXList(p) );
84298  pList = p->x.pList;
84299  if( pList ) nVal = pList->nExpr;
84300  assert( !ExprHasProperty(p, EP_IntValue) );
84301  pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
84302#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
84303  if( pFunc==0 ) return SQLITE_OK;
84304#endif
84305  assert( pFunc );
84306  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
84307   || (pFunc->funcFlags & (SQLITE_FUNC_NEEDCOLL|SQLITE_FUNC_RUNONLY))!=0
84308  ){
84309    return SQLITE_OK;
84310  }
84311
84312  if( pList ){
84313    apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
84314    if( apVal==0 ){
84315      rc = SQLITE_NOMEM_BKPT;
84316      goto value_from_function_out;
84317    }
84318    for(i=0; i<nVal; i++){
84319      rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
84320      if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
84321    }
84322  }
84323
84324  pVal = valueNew(db, pCtx);
84325  if( pVal==0 ){
84326    rc = SQLITE_NOMEM_BKPT;
84327    goto value_from_function_out;
84328  }
84329
84330  memset(&ctx, 0, sizeof(ctx));
84331  ctx.pOut = pVal;
84332  ctx.pFunc = pFunc;
84333  ctx.enc = ENC(db);
84334  pFunc->xSFunc(&ctx, nVal, apVal);
84335  if( ctx.isError ){
84336    rc = ctx.isError;
84337    sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
84338  }else{
84339    sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
84340    assert( rc==SQLITE_OK );
84341    rc = sqlite3VdbeChangeEncoding(pVal, enc);
84342    if( NEVER(rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal)) ){
84343      rc = SQLITE_TOOBIG;
84344      pCtx->pParse->nErr++;
84345    }
84346  }
84347
84348 value_from_function_out:
84349  if( rc!=SQLITE_OK ){
84350    pVal = 0;
84351    pCtx->pParse->rc = rc;
84352  }
84353  if( apVal ){
84354    for(i=0; i<nVal; i++){
84355      sqlite3ValueFree(apVal[i]);
84356    }
84357    sqlite3DbFreeNN(db, apVal);
84358  }
84359
84360  *ppVal = pVal;
84361  return rc;
84362}
84363#else
84364# define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
84365#endif /* defined(SQLITE_ENABLE_STAT4) */
84366
84367/*
84368** Extract a value from the supplied expression in the manner described
84369** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
84370** using valueNew().
84371**
84372** If pCtx is NULL and an error occurs after the sqlite3_value object
84373** has been allocated, it is freed before returning. Or, if pCtx is not
84374** NULL, it is assumed that the caller will free any allocated object
84375** in all cases.
84376*/
84377static int valueFromExpr(
84378  sqlite3 *db,                    /* The database connection */
84379  const Expr *pExpr,              /* The expression to evaluate */
84380  u8 enc,                         /* Encoding to use */
84381  u8 affinity,                    /* Affinity to use */
84382  sqlite3_value **ppVal,          /* Write the new value here */
84383  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
84384){
84385  int op;
84386  char *zVal = 0;
84387  sqlite3_value *pVal = 0;
84388  int negInt = 1;
84389  const char *zNeg = "";
84390  int rc = SQLITE_OK;
84391
84392  assert( pExpr!=0 );
84393  while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
84394  if( op==TK_REGISTER ) op = pExpr->op2;
84395
84396  /* Compressed expressions only appear when parsing the DEFAULT clause
84397  ** on a table column definition, and hence only when pCtx==0.  This
84398  ** check ensures that an EP_TokenOnly expression is never passed down
84399  ** into valueFromFunction(). */
84400  assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
84401
84402  if( op==TK_CAST ){
84403    u8 aff;
84404    assert( !ExprHasProperty(pExpr, EP_IntValue) );
84405    aff = sqlite3AffinityType(pExpr->u.zToken,0);
84406    rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
84407    testcase( rc!=SQLITE_OK );
84408    if( *ppVal ){
84409#ifdef SQLITE_ENABLE_STAT4
84410      rc = ExpandBlob(*ppVal);
84411#else
84412      /* zero-blobs only come from functions, not literal values.  And
84413      ** functions are only processed under STAT4 */
84414      assert( (ppVal[0][0].flags & MEM_Zero)==0 );
84415#endif
84416      sqlite3VdbeMemCast(*ppVal, aff, enc);
84417      sqlite3ValueApplyAffinity(*ppVal, affinity, enc);
84418    }
84419    return rc;
84420  }
84421
84422  /* Handle negative integers in a single step.  This is needed in the
84423  ** case when the value is -9223372036854775808. Except - do not do this
84424  ** for hexadecimal literals.  */
84425  if( op==TK_UMINUS ){
84426    Expr *pLeft = pExpr->pLeft;
84427    if( (pLeft->op==TK_INTEGER || pLeft->op==TK_FLOAT) ){
84428      if( ExprHasProperty(pLeft, EP_IntValue)
84429       || pLeft->u.zToken[0]!='0' || (pLeft->u.zToken[1] & ~0x20)!='X'
84430      ){
84431        pExpr = pLeft;
84432        op = pExpr->op;
84433        negInt = -1;
84434        zNeg = "-";
84435      }
84436    }
84437  }
84438
84439  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
84440    pVal = valueNew(db, pCtx);
84441    if( pVal==0 ) goto no_mem;
84442    if( ExprHasProperty(pExpr, EP_IntValue) ){
84443      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
84444    }else{
84445      i64 iVal;
84446      if( op==TK_INTEGER && 0==sqlite3DecOrHexToI64(pExpr->u.zToken, &iVal) ){
84447        sqlite3VdbeMemSetInt64(pVal, iVal*negInt);
84448      }else{
84449        zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
84450        if( zVal==0 ) goto no_mem;
84451        sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
84452      }
84453    }
84454    if( affinity==SQLITE_AFF_BLOB ){
84455      if( op==TK_FLOAT ){
84456        assert( pVal && pVal->z && pVal->flags==(MEM_Str|MEM_Term) );
84457        sqlite3AtoF(pVal->z, &pVal->u.r, pVal->n, SQLITE_UTF8);
84458        pVal->flags = MEM_Real;
84459      }else if( op==TK_INTEGER ){
84460        /* This case is required by -9223372036854775808 and other strings
84461        ** that look like integers but cannot be handled by the
84462        ** sqlite3DecOrHexToI64() call above.  */
84463        sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
84464      }
84465    }else{
84466      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
84467    }
84468    assert( (pVal->flags & MEM_IntReal)==0 );
84469    if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){
84470      testcase( pVal->flags & MEM_Int );
84471      testcase( pVal->flags & MEM_Real );
84472      pVal->flags &= ~MEM_Str;
84473    }
84474    if( enc!=SQLITE_UTF8 ){
84475      rc = sqlite3VdbeChangeEncoding(pVal, enc);
84476    }
84477  }else if( op==TK_UMINUS ) {
84478    /* This branch happens for multiple negative signs.  Ex: -(-5) */
84479    if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
84480     && pVal!=0
84481    ){
84482      sqlite3VdbeMemNumerify(pVal);
84483      if( pVal->flags & MEM_Real ){
84484        pVal->u.r = -pVal->u.r;
84485      }else if( pVal->u.i==SMALLEST_INT64 ){
84486#ifndef SQLITE_OMIT_FLOATING_POINT
84487        pVal->u.r = -(double)SMALLEST_INT64;
84488#else
84489        pVal->u.r = LARGEST_INT64;
84490#endif
84491        MemSetTypeFlag(pVal, MEM_Real);
84492      }else{
84493        pVal->u.i = -pVal->u.i;
84494      }
84495      sqlite3ValueApplyAffinity(pVal, affinity, enc);
84496    }
84497  }else if( op==TK_NULL ){
84498    pVal = valueNew(db, pCtx);
84499    if( pVal==0 ) goto no_mem;
84500    sqlite3VdbeMemSetNull(pVal);
84501  }
84502#ifndef SQLITE_OMIT_BLOB_LITERAL
84503  else if( op==TK_BLOB ){
84504    int nVal;
84505    assert( !ExprHasProperty(pExpr, EP_IntValue) );
84506    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
84507    assert( pExpr->u.zToken[1]=='\'' );
84508    pVal = valueNew(db, pCtx);
84509    if( !pVal ) goto no_mem;
84510    zVal = &pExpr->u.zToken[2];
84511    nVal = sqlite3Strlen30(zVal)-1;
84512    assert( zVal[nVal]=='\'' );
84513    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
84514                         0, SQLITE_DYNAMIC);
84515  }
84516#endif
84517#ifdef SQLITE_ENABLE_STAT4
84518  else if( op==TK_FUNCTION && pCtx!=0 ){
84519    rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
84520  }
84521#endif
84522  else if( op==TK_TRUEFALSE ){
84523    assert( !ExprHasProperty(pExpr, EP_IntValue) );
84524    pVal = valueNew(db, pCtx);
84525    if( pVal ){
84526      pVal->flags = MEM_Int;
84527      pVal->u.i = pExpr->u.zToken[4]==0;
84528      sqlite3ValueApplyAffinity(pVal, affinity, enc);
84529    }
84530  }
84531
84532  *ppVal = pVal;
84533  return rc;
84534
84535no_mem:
84536#ifdef SQLITE_ENABLE_STAT4
84537  if( pCtx==0 || NEVER(pCtx->pParse->nErr==0) )
84538#endif
84539    sqlite3OomFault(db);
84540  sqlite3DbFree(db, zVal);
84541  assert( *ppVal==0 );
84542#ifdef SQLITE_ENABLE_STAT4
84543  if( pCtx==0 ) sqlite3ValueFree(pVal);
84544#else
84545  assert( pCtx==0 ); sqlite3ValueFree(pVal);
84546#endif
84547  return SQLITE_NOMEM_BKPT;
84548}
84549
84550/*
84551** Create a new sqlite3_value object, containing the value of pExpr.
84552**
84553** This only works for very simple expressions that consist of one constant
84554** token (i.e. "5", "5.1", "'a string'"). If the expression can
84555** be converted directly into a value, then the value is allocated and
84556** a pointer written to *ppVal. The caller is responsible for deallocating
84557** the value by passing it to sqlite3ValueFree() later on. If the expression
84558** cannot be converted to a value, then *ppVal is set to NULL.
84559*/
84560SQLITE_PRIVATE int sqlite3ValueFromExpr(
84561  sqlite3 *db,              /* The database connection */
84562  const Expr *pExpr,        /* The expression to evaluate */
84563  u8 enc,                   /* Encoding to use */
84564  u8 affinity,              /* Affinity to use */
84565  sqlite3_value **ppVal     /* Write the new value here */
84566){
84567  return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
84568}
84569
84570#ifdef SQLITE_ENABLE_STAT4
84571/*
84572** Attempt to extract a value from pExpr and use it to construct *ppVal.
84573**
84574** If pAlloc is not NULL, then an UnpackedRecord object is created for
84575** pAlloc if one does not exist and the new value is added to the
84576** UnpackedRecord object.
84577**
84578** A value is extracted in the following cases:
84579**
84580**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
84581**
84582**  * The expression is a bound variable, and this is a reprepare, or
84583**
84584**  * The expression is a literal value.
84585**
84586** On success, *ppVal is made to point to the extracted value.  The caller
84587** is responsible for ensuring that the value is eventually freed.
84588*/
84589static int stat4ValueFromExpr(
84590  Parse *pParse,                  /* Parse context */
84591  Expr *pExpr,                    /* The expression to extract a value from */
84592  u8 affinity,                    /* Affinity to use */
84593  struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
84594  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
84595){
84596  int rc = SQLITE_OK;
84597  sqlite3_value *pVal = 0;
84598  sqlite3 *db = pParse->db;
84599
84600  /* Skip over any TK_COLLATE nodes */
84601  pExpr = sqlite3ExprSkipCollate(pExpr);
84602
84603  assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
84604  if( !pExpr ){
84605    pVal = valueNew(db, pAlloc);
84606    if( pVal ){
84607      sqlite3VdbeMemSetNull((Mem*)pVal);
84608    }
84609  }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
84610    Vdbe *v;
84611    int iBindVar = pExpr->iColumn;
84612    sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
84613    if( (v = pParse->pReprepare)!=0 ){
84614      pVal = valueNew(db, pAlloc);
84615      if( pVal ){
84616        rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
84617        sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
84618        pVal->db = pParse->db;
84619      }
84620    }
84621  }else{
84622    rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
84623  }
84624
84625  assert( pVal==0 || pVal->db==db );
84626  *ppVal = pVal;
84627  return rc;
84628}
84629
84630/*
84631** This function is used to allocate and populate UnpackedRecord
84632** structures intended to be compared against sample index keys stored
84633** in the sqlite_stat4 table.
84634**
84635** A single call to this function populates zero or more fields of the
84636** record starting with field iVal (fields are numbered from left to
84637** right starting with 0). A single field is populated if:
84638**
84639**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
84640**
84641**  * The expression is a bound variable, and this is a reprepare, or
84642**
84643**  * The sqlite3ValueFromExpr() function is able to extract a value
84644**    from the expression (i.e. the expression is a literal value).
84645**
84646** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
84647** vector components that match either of the two latter criteria listed
84648** above.
84649**
84650** Before any value is appended to the record, the affinity of the
84651** corresponding column within index pIdx is applied to it. Before
84652** this function returns, output parameter *pnExtract is set to the
84653** number of values appended to the record.
84654**
84655** When this function is called, *ppRec must either point to an object
84656** allocated by an earlier call to this function, or must be NULL. If it
84657** is NULL and a value can be successfully extracted, a new UnpackedRecord
84658** is allocated (and *ppRec set to point to it) before returning.
84659**
84660** Unless an error is encountered, SQLITE_OK is returned. It is not an
84661** error if a value cannot be extracted from pExpr. If an error does
84662** occur, an SQLite error code is returned.
84663*/
84664SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
84665  Parse *pParse,                  /* Parse context */
84666  Index *pIdx,                    /* Index being probed */
84667  UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
84668  Expr *pExpr,                    /* The expression to extract a value from */
84669  int nElem,                      /* Maximum number of values to append */
84670  int iVal,                       /* Array element to populate */
84671  int *pnExtract                  /* OUT: Values appended to the record */
84672){
84673  int rc = SQLITE_OK;
84674  int nExtract = 0;
84675
84676  if( pExpr==0 || pExpr->op!=TK_SELECT ){
84677    int i;
84678    struct ValueNewStat4Ctx alloc;
84679
84680    alloc.pParse = pParse;
84681    alloc.pIdx = pIdx;
84682    alloc.ppRec = ppRec;
84683
84684    for(i=0; i<nElem; i++){
84685      sqlite3_value *pVal = 0;
84686      Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
84687      u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
84688      alloc.iVal = iVal+i;
84689      rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
84690      if( !pVal ) break;
84691      nExtract++;
84692    }
84693  }
84694
84695  *pnExtract = nExtract;
84696  return rc;
84697}
84698
84699/*
84700** Attempt to extract a value from expression pExpr using the methods
84701** as described for sqlite3Stat4ProbeSetValue() above.
84702**
84703** If successful, set *ppVal to point to a new value object and return
84704** SQLITE_OK. If no value can be extracted, but no other error occurs
84705** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
84706** does occur, return an SQLite error code. The final value of *ppVal
84707** is undefined in this case.
84708*/
84709SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
84710  Parse *pParse,                  /* Parse context */
84711  Expr *pExpr,                    /* The expression to extract a value from */
84712  u8 affinity,                    /* Affinity to use */
84713  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
84714){
84715  return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
84716}
84717
84718/*
84719** Extract the iCol-th column from the nRec-byte record in pRec.  Write
84720** the column value into *ppVal.  If *ppVal is initially NULL then a new
84721** sqlite3_value object is allocated.
84722**
84723** If *ppVal is initially NULL then the caller is responsible for
84724** ensuring that the value written into *ppVal is eventually freed.
84725*/
84726SQLITE_PRIVATE int sqlite3Stat4Column(
84727  sqlite3 *db,                    /* Database handle */
84728  const void *pRec,               /* Pointer to buffer containing record */
84729  int nRec,                       /* Size of buffer pRec in bytes */
84730  int iCol,                       /* Column to extract */
84731  sqlite3_value **ppVal           /* OUT: Extracted value */
84732){
84733  u32 t = 0;                      /* a column type code */
84734  u32 nHdr;                       /* Size of the header in the record */
84735  u32 iHdr;                       /* Next unread header byte */
84736  i64 iField;                     /* Next unread data byte */
84737  u32 szField = 0;                /* Size of the current data field */
84738  int i;                          /* Column index */
84739  u8 *a = (u8*)pRec;              /* Typecast byte array */
84740  Mem *pMem = *ppVal;             /* Write result into this Mem object */
84741
84742  assert( iCol>0 );
84743  iHdr = getVarint32(a, nHdr);
84744  if( nHdr>(u32)nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
84745  iField = nHdr;
84746  for(i=0; i<=iCol; i++){
84747    iHdr += getVarint32(&a[iHdr], t);
84748    testcase( iHdr==nHdr );
84749    testcase( iHdr==nHdr+1 );
84750    if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
84751    szField = sqlite3VdbeSerialTypeLen(t);
84752    iField += szField;
84753  }
84754  testcase( iField==nRec );
84755  testcase( iField==nRec+1 );
84756  if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
84757  if( pMem==0 ){
84758    pMem = *ppVal = sqlite3ValueNew(db);
84759    if( pMem==0 ) return SQLITE_NOMEM_BKPT;
84760  }
84761  sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
84762  pMem->enc = ENC(db);
84763  return SQLITE_OK;
84764}
84765
84766/*
84767** Unless it is NULL, the argument must be an UnpackedRecord object returned
84768** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
84769** the object.
84770*/
84771SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
84772  if( pRec ){
84773    int i;
84774    int nCol = pRec->pKeyInfo->nAllField;
84775    Mem *aMem = pRec->aMem;
84776    sqlite3 *db = aMem[0].db;
84777    for(i=0; i<nCol; i++){
84778      sqlite3VdbeMemRelease(&aMem[i]);
84779    }
84780    sqlite3KeyInfoUnref(pRec->pKeyInfo);
84781    sqlite3DbFreeNN(db, pRec);
84782  }
84783}
84784#endif /* ifdef SQLITE_ENABLE_STAT4 */
84785
84786/*
84787** Change the string value of an sqlite3_value object
84788*/
84789SQLITE_PRIVATE void sqlite3ValueSetStr(
84790  sqlite3_value *v,     /* Value to be set */
84791  int n,                /* Length of string z */
84792  const void *z,        /* Text of the new string */
84793  u8 enc,               /* Encoding to use */
84794  void (*xDel)(void*)   /* Destructor for the string */
84795){
84796  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
84797}
84798
84799/*
84800** Free an sqlite3_value object
84801*/
84802SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
84803  if( !v ) return;
84804  sqlite3VdbeMemRelease((Mem *)v);
84805  sqlite3DbFreeNN(((Mem*)v)->db, v);
84806}
84807
84808/*
84809** The sqlite3ValueBytes() routine returns the number of bytes in the
84810** sqlite3_value object assuming that it uses the encoding "enc".
84811** The valueBytes() routine is a helper function.
84812*/
84813static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
84814  return valueToText(pVal, enc)!=0 ? pVal->n : 0;
84815}
84816SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
84817  Mem *p = (Mem*)pVal;
84818  assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
84819  if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
84820    return p->n;
84821  }
84822  if( (p->flags & MEM_Str)!=0 && enc!=SQLITE_UTF8 && pVal->enc!=SQLITE_UTF8 ){
84823    return p->n;
84824  }
84825  if( (p->flags & MEM_Blob)!=0 ){
84826    if( p->flags & MEM_Zero ){
84827      return p->n + p->u.nZero;
84828    }else{
84829      return p->n;
84830    }
84831  }
84832  if( p->flags & MEM_Null ) return 0;
84833  return valueBytes(pVal, enc);
84834}
84835
84836/************** End of vdbemem.c *********************************************/
84837/************** Begin file vdbeaux.c *****************************************/
84838/*
84839** 2003 September 6
84840**
84841** The author disclaims copyright to this source code.  In place of
84842** a legal notice, here is a blessing:
84843**
84844**    May you do good and not evil.
84845**    May you find forgiveness for yourself and forgive others.
84846**    May you share freely, never taking more than you give.
84847**
84848*************************************************************************
84849** This file contains code used for creating, destroying, and populating
84850** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
84851*/
84852/* #include "sqliteInt.h" */
84853/* #include "vdbeInt.h" */
84854
84855/* Forward references */
84856static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);
84857static void vdbeFreeOpArray(sqlite3 *, Op *, int);
84858
84859/*
84860** Create a new virtual database engine.
84861*/
84862SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
84863  sqlite3 *db = pParse->db;
84864  Vdbe *p;
84865  p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
84866  if( p==0 ) return 0;
84867  memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
84868  p->db = db;
84869  if( db->pVdbe ){
84870    db->pVdbe->ppVPrev = &p->pVNext;
84871  }
84872  p->pVNext = db->pVdbe;
84873  p->ppVPrev = &db->pVdbe;
84874  db->pVdbe = p;
84875  assert( p->eVdbeState==VDBE_INIT_STATE );
84876  p->pParse = pParse;
84877  pParse->pVdbe = p;
84878  assert( pParse->aLabel==0 );
84879  assert( pParse->nLabel==0 );
84880  assert( p->nOpAlloc==0 );
84881  assert( pParse->szOpAlloc==0 );
84882  sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
84883  return p;
84884}
84885
84886/*
84887** Return the Parse object that owns a Vdbe object.
84888*/
84889SQLITE_PRIVATE Parse *sqlite3VdbeParser(Vdbe *p){
84890  return p->pParse;
84891}
84892
84893/*
84894** Change the error string stored in Vdbe.zErrMsg
84895*/
84896SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
84897  va_list ap;
84898  sqlite3DbFree(p->db, p->zErrMsg);
84899  va_start(ap, zFormat);
84900  p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
84901  va_end(ap);
84902}
84903
84904/*
84905** Remember the SQL string for a prepared statement.
84906*/
84907SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
84908  if( p==0 ) return;
84909  p->prepFlags = prepFlags;
84910  if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
84911    p->expmask = 0;
84912  }
84913  assert( p->zSql==0 );
84914  p->zSql = sqlite3DbStrNDup(p->db, z, n);
84915}
84916
84917#ifdef SQLITE_ENABLE_NORMALIZE
84918/*
84919** Add a new element to the Vdbe->pDblStr list.
84920*/
84921SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3 *db, Vdbe *p, const char *z){
84922  if( p ){
84923    int n = sqlite3Strlen30(z);
84924    DblquoteStr *pStr = sqlite3DbMallocRawNN(db,
84925                            sizeof(*pStr)+n+1-sizeof(pStr->z));
84926    if( pStr ){
84927      pStr->pNextStr = p->pDblStr;
84928      p->pDblStr = pStr;
84929      memcpy(pStr->z, z, n+1);
84930    }
84931  }
84932}
84933#endif
84934
84935#ifdef SQLITE_ENABLE_NORMALIZE
84936/*
84937** zId of length nId is a double-quoted identifier.  Check to see if
84938** that identifier is really used as a string literal.
84939*/
84940SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(
84941  Vdbe *pVdbe,            /* The prepared statement */
84942  const char *zId         /* The double-quoted identifier, already dequoted */
84943){
84944  DblquoteStr *pStr;
84945  assert( zId!=0 );
84946  if( pVdbe->pDblStr==0 ) return 0;
84947  for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){
84948    if( strcmp(zId, pStr->z)==0 ) return 1;
84949  }
84950  return 0;
84951}
84952#endif
84953
84954/*
84955** Swap byte-code between two VDBE structures.
84956**
84957** This happens after pB was previously run and returned
84958** SQLITE_SCHEMA.  The statement was then reprepared in pA.
84959** This routine transfers the new bytecode in pA over to pB
84960** so that pB can be run again.  The old pB byte code is
84961** moved back to pA so that it will be cleaned up when pA is
84962** finalized.
84963*/
84964SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
84965  Vdbe tmp, *pTmp, **ppTmp;
84966  char *zTmp;
84967  assert( pA->db==pB->db );
84968  tmp = *pA;
84969  *pA = *pB;
84970  *pB = tmp;
84971  pTmp = pA->pVNext;
84972  pA->pVNext = pB->pVNext;
84973  pB->pVNext = pTmp;
84974  ppTmp = pA->ppVPrev;
84975  pA->ppVPrev = pB->ppVPrev;
84976  pB->ppVPrev = ppTmp;
84977  zTmp = pA->zSql;
84978  pA->zSql = pB->zSql;
84979  pB->zSql = zTmp;
84980#ifdef SQLITE_ENABLE_NORMALIZE
84981  zTmp = pA->zNormSql;
84982  pA->zNormSql = pB->zNormSql;
84983  pB->zNormSql = zTmp;
84984#endif
84985  pB->expmask = pA->expmask;
84986  pB->prepFlags = pA->prepFlags;
84987  memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
84988  pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
84989}
84990
84991/*
84992** Resize the Vdbe.aOp array so that it is at least nOp elements larger
84993** than its current size. nOp is guaranteed to be less than or equal
84994** to 1024/sizeof(Op).
84995**
84996** If an out-of-memory error occurs while resizing the array, return
84997** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
84998** unchanged (this is so that any opcodes already allocated can be
84999** correctly deallocated along with the rest of the Vdbe).
85000*/
85001static int growOpArray(Vdbe *v, int nOp){
85002  VdbeOp *pNew;
85003  Parse *p = v->pParse;
85004
85005  /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
85006  ** more frequent reallocs and hence provide more opportunities for
85007  ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
85008  ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
85009  ** by the minimum* amount required until the size reaches 512.  Normal
85010  ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
85011  ** size of the op array or add 1KB of space, whichever is smaller. */
85012#ifdef SQLITE_TEST_REALLOC_STRESS
85013  sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc
85014                        : (sqlite3_int64)v->nOpAlloc+nOp);
85015#else
85016  sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc
85017                        : (sqlite3_int64)(1024/sizeof(Op)));
85018  UNUSED_PARAMETER(nOp);
85019#endif
85020
85021  /* Ensure that the size of a VDBE does not grow too large */
85022  if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
85023    sqlite3OomFault(p->db);
85024    return SQLITE_NOMEM;
85025  }
85026
85027  assert( nOp<=(int)(1024/sizeof(Op)) );
85028  assert( nNew>=(v->nOpAlloc+nOp) );
85029  pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
85030  if( pNew ){
85031    p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
85032    v->nOpAlloc = p->szOpAlloc/sizeof(Op);
85033    v->aOp = pNew;
85034  }
85035  return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
85036}
85037
85038#ifdef SQLITE_DEBUG
85039/* This routine is just a convenient place to set a breakpoint that will
85040** fire after each opcode is inserted and displayed using
85041** "PRAGMA vdbe_addoptrace=on".  Parameters "pc" (program counter) and
85042** pOp are available to make the breakpoint conditional.
85043**
85044** Other useful labels for breakpoints include:
85045**   test_trace_breakpoint(pc,pOp)
85046**   sqlite3CorruptError(lineno)
85047**   sqlite3MisuseError(lineno)
85048**   sqlite3CantopenError(lineno)
85049*/
85050static void test_addop_breakpoint(int pc, Op *pOp){
85051  static u64 n = 0;
85052  (void)pc;
85053  (void)pOp;
85054  n++;
85055  if( n==LARGEST_UINT64 ) abort(); /* so that n is used, preventing a warning */
85056}
85057#endif
85058
85059/*
85060** Slow paths for sqlite3VdbeAddOp3() and sqlite3VdbeAddOp4Int() for the
85061** unusual case when we need to increase the size of the Vdbe.aOp[] array
85062** before adding the new opcode.
85063*/
85064static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
85065  assert( p->nOpAlloc<=p->nOp );
85066  if( growOpArray(p, 1) ) return 1;
85067  assert( p->nOpAlloc>p->nOp );
85068  return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
85069}
85070static SQLITE_NOINLINE int addOp4IntSlow(
85071  Vdbe *p,            /* Add the opcode to this VM */
85072  int op,             /* The new opcode */
85073  int p1,             /* The P1 operand */
85074  int p2,             /* The P2 operand */
85075  int p3,             /* The P3 operand */
85076  int p4              /* The P4 operand as an integer */
85077){
85078  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
85079  if( p->db->mallocFailed==0 ){
85080    VdbeOp *pOp = &p->aOp[addr];
85081    pOp->p4type = P4_INT32;
85082    pOp->p4.i = p4;
85083  }
85084  return addr;
85085}
85086
85087
85088/*
85089** Add a new instruction to the list of instructions current in the
85090** VDBE.  Return the address of the new instruction.
85091**
85092** Parameters:
85093**
85094**    p               Pointer to the VDBE
85095**
85096**    op              The opcode for this instruction
85097**
85098**    p1, p2, p3, p4  Operands
85099*/
85100SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
85101  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
85102}
85103SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
85104  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
85105}
85106SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
85107  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
85108}
85109SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
85110  int i;
85111  VdbeOp *pOp;
85112
85113  i = p->nOp;
85114  assert( p->eVdbeState==VDBE_INIT_STATE );
85115  assert( op>=0 && op<0xff );
85116  if( p->nOpAlloc<=i ){
85117    return growOp3(p, op, p1, p2, p3);
85118  }
85119  assert( p->aOp!=0 );
85120  p->nOp++;
85121  pOp = &p->aOp[i];
85122  assert( pOp!=0 );
85123  pOp->opcode = (u8)op;
85124  pOp->p5 = 0;
85125  pOp->p1 = p1;
85126  pOp->p2 = p2;
85127  pOp->p3 = p3;
85128  pOp->p4.p = 0;
85129  pOp->p4type = P4_NOTUSED;
85130
85131  /* Replicate this logic in sqlite3VdbeAddOp4Int()
85132  ** vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv   */
85133#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
85134  pOp->zComment = 0;
85135#endif
85136#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
85137  pOp->nExec = 0;
85138  pOp->nCycle = 0;
85139#endif
85140#ifdef SQLITE_DEBUG
85141  if( p->db->flags & SQLITE_VdbeAddopTrace ){
85142    sqlite3VdbePrintOp(0, i, &p->aOp[i]);
85143    test_addop_breakpoint(i, &p->aOp[i]);
85144  }
85145#endif
85146#ifdef SQLITE_VDBE_COVERAGE
85147  pOp->iSrcLine = 0;
85148#endif
85149  /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
85150  ** Replicate in sqlite3VdbeAddOp4Int() */
85151
85152  return i;
85153}
85154SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
85155  Vdbe *p,            /* Add the opcode to this VM */
85156  int op,             /* The new opcode */
85157  int p1,             /* The P1 operand */
85158  int p2,             /* The P2 operand */
85159  int p3,             /* The P3 operand */
85160  int p4              /* The P4 operand as an integer */
85161){
85162  int i;
85163  VdbeOp *pOp;
85164
85165  i = p->nOp;
85166  if( p->nOpAlloc<=i ){
85167    return addOp4IntSlow(p, op, p1, p2, p3, p4);
85168  }
85169  p->nOp++;
85170  pOp = &p->aOp[i];
85171  assert( pOp!=0 );
85172  pOp->opcode = (u8)op;
85173  pOp->p5 = 0;
85174  pOp->p1 = p1;
85175  pOp->p2 = p2;
85176  pOp->p3 = p3;
85177  pOp->p4.i = p4;
85178  pOp->p4type = P4_INT32;
85179
85180  /* Replicate this logic in sqlite3VdbeAddOp3()
85181  ** vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv   */
85182#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
85183  pOp->zComment = 0;
85184#endif
85185#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
85186  pOp->nExec = 0;
85187  pOp->nCycle = 0;
85188#endif
85189#ifdef SQLITE_DEBUG
85190  if( p->db->flags & SQLITE_VdbeAddopTrace ){
85191    sqlite3VdbePrintOp(0, i, &p->aOp[i]);
85192    test_addop_breakpoint(i, &p->aOp[i]);
85193  }
85194#endif
85195#ifdef SQLITE_VDBE_COVERAGE
85196  pOp->iSrcLine = 0;
85197#endif
85198  /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
85199  ** Replicate in sqlite3VdbeAddOp3() */
85200
85201  return i;
85202}
85203
85204/* Generate code for an unconditional jump to instruction iDest
85205*/
85206SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
85207  return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
85208}
85209
85210/* Generate code to cause the string zStr to be loaded into
85211** register iDest
85212*/
85213SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
85214  return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
85215}
85216
85217/*
85218** Generate code that initializes multiple registers to string or integer
85219** constants.  The registers begin with iDest and increase consecutively.
85220** One register is initialized for each characgter in zTypes[].  For each
85221** "s" character in zTypes[], the register is a string if the argument is
85222** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
85223** in zTypes[], the register is initialized to an integer.
85224**
85225** If the input string does not end with "X" then an OP_ResultRow instruction
85226** is generated for the values inserted.
85227*/
85228SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
85229  va_list ap;
85230  int i;
85231  char c;
85232  va_start(ap, zTypes);
85233  for(i=0; (c = zTypes[i])!=0; i++){
85234    if( c=='s' ){
85235      const char *z = va_arg(ap, const char*);
85236      sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
85237    }else if( c=='i' ){
85238      sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
85239    }else{
85240      goto skip_op_resultrow;
85241    }
85242  }
85243  sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
85244skip_op_resultrow:
85245  va_end(ap);
85246}
85247
85248/*
85249** Add an opcode that includes the p4 value as a pointer.
85250*/
85251SQLITE_PRIVATE int sqlite3VdbeAddOp4(
85252  Vdbe *p,            /* Add the opcode to this VM */
85253  int op,             /* The new opcode */
85254  int p1,             /* The P1 operand */
85255  int p2,             /* The P2 operand */
85256  int p3,             /* The P3 operand */
85257  const char *zP4,    /* The P4 operand */
85258  int p4type          /* P4 operand type */
85259){
85260  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
85261  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
85262  return addr;
85263}
85264
85265/*
85266** Add an OP_Function or OP_PureFunc opcode.
85267**
85268** The eCallCtx argument is information (typically taken from Expr.op2)
85269** that describes the calling context of the function.  0 means a general
85270** function call.  NC_IsCheck means called by a check constraint,
85271** NC_IdxExpr means called as part of an index expression.  NC_PartIdx
85272** means in the WHERE clause of a partial index.  NC_GenCol means called
85273** while computing a generated column value.  0 is the usual case.
85274*/
85275SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(
85276  Parse *pParse,        /* Parsing context */
85277  int p1,               /* Constant argument mask */
85278  int p2,               /* First argument register */
85279  int p3,               /* Register into which results are written */
85280  int nArg,             /* Number of argument */
85281  const FuncDef *pFunc, /* The function to be invoked */
85282  int eCallCtx          /* Calling context */
85283){
85284  Vdbe *v = pParse->pVdbe;
85285  int nByte;
85286  int addr;
85287  sqlite3_context *pCtx;
85288  assert( v );
85289  nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*);
85290  pCtx = sqlite3DbMallocRawNN(pParse->db, nByte);
85291  if( pCtx==0 ){
85292    assert( pParse->db->mallocFailed );
85293    freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);
85294    return 0;
85295  }
85296  pCtx->pOut = 0;
85297  pCtx->pFunc = (FuncDef*)pFunc;
85298  pCtx->pVdbe = 0;
85299  pCtx->isError = 0;
85300  pCtx->argc = nArg;
85301  pCtx->iOp = sqlite3VdbeCurrentAddr(v);
85302  addr = sqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function,
85303                           p1, p2, p3, (char*)pCtx, P4_FUNCCTX);
85304  sqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef);
85305  sqlite3MayAbort(pParse);
85306  return addr;
85307}
85308
85309/*
85310** Add an opcode that includes the p4 value with a P4_INT64 or
85311** P4_REAL type.
85312*/
85313SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
85314  Vdbe *p,            /* Add the opcode to this VM */
85315  int op,             /* The new opcode */
85316  int p1,             /* The P1 operand */
85317  int p2,             /* The P2 operand */
85318  int p3,             /* The P3 operand */
85319  const u8 *zP4,      /* The P4 operand */
85320  int p4type          /* P4 operand type */
85321){
85322  char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
85323  if( p4copy ) memcpy(p4copy, zP4, 8);
85324  return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
85325}
85326
85327#ifndef SQLITE_OMIT_EXPLAIN
85328/*
85329** Return the address of the current EXPLAIN QUERY PLAN baseline.
85330** 0 means "none".
85331*/
85332SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse *pParse){
85333  VdbeOp *pOp;
85334  if( pParse->addrExplain==0 ) return 0;
85335  pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
85336  return pOp->p2;
85337}
85338
85339/*
85340** Set a debugger breakpoint on the following routine in order to
85341** monitor the EXPLAIN QUERY PLAN code generation.
85342*/
85343#if defined(SQLITE_DEBUG)
85344SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char *z1, const char *z2){
85345  (void)z1;
85346  (void)z2;
85347}
85348#endif
85349
85350/*
85351** Add a new OP_Explain opcode.
85352**
85353** If the bPush flag is true, then make this opcode the parent for
85354** subsequent Explains until sqlite3VdbeExplainPop() is called.
85355*/
85356SQLITE_PRIVATE int sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
85357  int addr = 0;
85358#if !defined(SQLITE_DEBUG)
85359  /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.
85360  ** But omit them (for performance) during production builds */
85361  if( pParse->explain==2 || IS_STMT_SCANSTATUS(pParse->db) )
85362#endif
85363  {
85364    char *zMsg;
85365    Vdbe *v;
85366    va_list ap;
85367    int iThis;
85368    va_start(ap, zFmt);
85369    zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
85370    va_end(ap);
85371    v = pParse->pVdbe;
85372    iThis = v->nOp;
85373    addr = sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
85374                      zMsg, P4_DYNAMIC);
85375    sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetLastOp(v)->p4.z);
85376    if( bPush){
85377      pParse->addrExplain = iThis;
85378    }
85379    sqlite3VdbeScanStatus(v, iThis, -1, -1, 0, 0);
85380  }
85381  return addr;
85382}
85383
85384/*
85385** Pop the EXPLAIN QUERY PLAN stack one level.
85386*/
85387SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse *pParse){
85388  sqlite3ExplainBreakpoint("POP", 0);
85389  pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
85390}
85391#endif /* SQLITE_OMIT_EXPLAIN */
85392
85393/*
85394** Add an OP_ParseSchema opcode.  This routine is broken out from
85395** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
85396** as having been used.
85397**
85398** The zWhere string must have been obtained from sqlite3_malloc().
85399** This routine will take ownership of the allocated memory.
85400*/
85401SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere, u16 p5){
85402  int j;
85403  sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
85404  sqlite3VdbeChangeP5(p, p5);
85405  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
85406  sqlite3MayAbort(p->pParse);
85407}
85408
85409/* Insert the end of a co-routine
85410*/
85411SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
85412  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
85413
85414  /* Clear the temporary register cache, thereby ensuring that each
85415  ** co-routine has its own independent set of registers, because co-routines
85416  ** might expect their registers to be preserved across an OP_Yield, and
85417  ** that could cause problems if two or more co-routines are using the same
85418  ** temporary register.
85419  */
85420  v->pParse->nTempReg = 0;
85421  v->pParse->nRangeReg = 0;
85422}
85423
85424/*
85425** Create a new symbolic label for an instruction that has yet to be
85426** coded.  The symbolic label is really just a negative number.  The
85427** label can be used as the P2 value of an operation.  Later, when
85428** the label is resolved to a specific address, the VDBE will scan
85429** through its operation list and change all values of P2 which match
85430** the label into the resolved address.
85431**
85432** The VDBE knows that a P2 value is a label because labels are
85433** always negative and P2 values are suppose to be non-negative.
85434** Hence, a negative P2 value is a label that has yet to be resolved.
85435** (Later:) This is only true for opcodes that have the OPFLG_JUMP
85436** property.
85437**
85438** Variable usage notes:
85439**
85440**     Parse.aLabel[x]     Stores the address that the x-th label resolves
85441**                         into.  For testing (SQLITE_DEBUG), unresolved
85442**                         labels stores -1, but that is not required.
85443**     Parse.nLabelAlloc   Number of slots allocated to Parse.aLabel[]
85444**     Parse.nLabel        The *negative* of the number of labels that have
85445**                         been issued.  The negative is stored because
85446**                         that gives a performance improvement over storing
85447**                         the equivalent positive value.
85448*/
85449SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse *pParse){
85450  return --pParse->nLabel;
85451}
85452
85453/*
85454** Resolve label "x" to be the address of the next instruction to
85455** be inserted.  The parameter "x" must have been obtained from
85456** a prior call to sqlite3VdbeMakeLabel().
85457*/
85458static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
85459  int nNewSize = 10 - p->nLabel;
85460  p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
85461                     nNewSize*sizeof(p->aLabel[0]));
85462  if( p->aLabel==0 ){
85463    p->nLabelAlloc = 0;
85464  }else{
85465#ifdef SQLITE_DEBUG
85466    int i;
85467    for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;
85468#endif
85469    if( nNewSize>=100 && (nNewSize/100)>(p->nLabelAlloc/100) ){
85470      sqlite3ProgressCheck(p);
85471    }
85472    p->nLabelAlloc = nNewSize;
85473    p->aLabel[j] = v->nOp;
85474  }
85475}
85476SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
85477  Parse *p = v->pParse;
85478  int j = ADDR(x);
85479  assert( v->eVdbeState==VDBE_INIT_STATE );
85480  assert( j<-p->nLabel );
85481  assert( j>=0 );
85482#ifdef SQLITE_DEBUG
85483  if( p->db->flags & SQLITE_VdbeAddopTrace ){
85484    printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
85485  }
85486#endif
85487  if( p->nLabelAlloc + p->nLabel < 0 ){
85488    resizeResolveLabel(p,v,j);
85489  }else{
85490    assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
85491    p->aLabel[j] = v->nOp;
85492  }
85493}
85494
85495/*
85496** Mark the VDBE as one that can only be run one time.
85497*/
85498SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
85499  sqlite3VdbeAddOp2(p, OP_Expire, 1, 1);
85500}
85501
85502/*
85503** Mark the VDBE as one that can be run multiple times.
85504*/
85505SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
85506  int i;
85507  for(i=1; ALWAYS(i<p->nOp); i++){
85508    if( ALWAYS(p->aOp[i].opcode==OP_Expire) ){
85509      p->aOp[1].opcode = OP_Noop;
85510      break;
85511    }
85512  }
85513}
85514
85515#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
85516
85517/*
85518** The following type and function are used to iterate through all opcodes
85519** in a Vdbe main program and each of the sub-programs (triggers) it may
85520** invoke directly or indirectly. It should be used as follows:
85521**
85522**   Op *pOp;
85523**   VdbeOpIter sIter;
85524**
85525**   memset(&sIter, 0, sizeof(sIter));
85526**   sIter.v = v;                            // v is of type Vdbe*
85527**   while( (pOp = opIterNext(&sIter)) ){
85528**     // Do something with pOp
85529**   }
85530**   sqlite3DbFree(v->db, sIter.apSub);
85531**
85532*/
85533typedef struct VdbeOpIter VdbeOpIter;
85534struct VdbeOpIter {
85535  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
85536  SubProgram **apSub;        /* Array of subprograms */
85537  int nSub;                  /* Number of entries in apSub */
85538  int iAddr;                 /* Address of next instruction to return */
85539  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
85540};
85541static Op *opIterNext(VdbeOpIter *p){
85542  Vdbe *v = p->v;
85543  Op *pRet = 0;
85544  Op *aOp;
85545  int nOp;
85546
85547  if( p->iSub<=p->nSub ){
85548
85549    if( p->iSub==0 ){
85550      aOp = v->aOp;
85551      nOp = v->nOp;
85552    }else{
85553      aOp = p->apSub[p->iSub-1]->aOp;
85554      nOp = p->apSub[p->iSub-1]->nOp;
85555    }
85556    assert( p->iAddr<nOp );
85557
85558    pRet = &aOp[p->iAddr];
85559    p->iAddr++;
85560    if( p->iAddr==nOp ){
85561      p->iSub++;
85562      p->iAddr = 0;
85563    }
85564
85565    if( pRet->p4type==P4_SUBPROGRAM ){
85566      int nByte = (p->nSub+1)*sizeof(SubProgram*);
85567      int j;
85568      for(j=0; j<p->nSub; j++){
85569        if( p->apSub[j]==pRet->p4.pProgram ) break;
85570      }
85571      if( j==p->nSub ){
85572        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
85573        if( !p->apSub ){
85574          pRet = 0;
85575        }else{
85576          p->apSub[p->nSub++] = pRet->p4.pProgram;
85577        }
85578      }
85579    }
85580  }
85581
85582  return pRet;
85583}
85584
85585/*
85586** Check if the program stored in the VM associated with pParse may
85587** throw an ABORT exception (causing the statement, but not entire transaction
85588** to be rolled back). This condition is true if the main program or any
85589** sub-programs contains any of the following:
85590**
85591**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
85592**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
85593**   *  OP_Destroy
85594**   *  OP_VUpdate
85595**   *  OP_VCreate
85596**   *  OP_VRename
85597**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
85598**   *  OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
85599**      (for CREATE TABLE AS SELECT ...)
85600**
85601** Then check that the value of Parse.mayAbort is true if an
85602** ABORT may be thrown, or false otherwise. Return true if it does
85603** match, or false otherwise. This function is intended to be used as
85604** part of an assert statement in the compiler. Similar to:
85605**
85606**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
85607*/
85608SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
85609  int hasAbort = 0;
85610  int hasFkCounter = 0;
85611  int hasCreateTable = 0;
85612  int hasCreateIndex = 0;
85613  int hasInitCoroutine = 0;
85614  Op *pOp;
85615  VdbeOpIter sIter;
85616
85617  if( v==0 ) return 0;
85618  memset(&sIter, 0, sizeof(sIter));
85619  sIter.v = v;
85620
85621  while( (pOp = opIterNext(&sIter))!=0 ){
85622    int opcode = pOp->opcode;
85623    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
85624     || opcode==OP_VDestroy
85625     || opcode==OP_VCreate
85626     || opcode==OP_ParseSchema
85627     || opcode==OP_Function || opcode==OP_PureFunc
85628     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
85629      && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
85630    ){
85631      hasAbort = 1;
85632      break;
85633    }
85634    if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
85635    if( mayAbort ){
85636      /* hasCreateIndex may also be set for some DELETE statements that use
85637      ** OP_Clear. So this routine may end up returning true in the case
85638      ** where a "DELETE FROM tbl" has a statement-journal but does not
85639      ** require one. This is not so bad - it is an inefficiency, not a bug. */
85640      if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;
85641      if( opcode==OP_Clear ) hasCreateIndex = 1;
85642    }
85643    if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
85644#ifndef SQLITE_OMIT_FOREIGN_KEY
85645    if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
85646      hasFkCounter = 1;
85647    }
85648#endif
85649  }
85650  sqlite3DbFree(v->db, sIter.apSub);
85651
85652  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
85653  ** If malloc failed, then the while() loop above may not have iterated
85654  ** through all opcodes and hasAbort may be set incorrectly. Return
85655  ** true for this case to prevent the assert() in the callers frame
85656  ** from failing.  */
85657  return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
85658        || (hasCreateTable && hasInitCoroutine) || hasCreateIndex
85659  );
85660}
85661#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
85662
85663#ifdef SQLITE_DEBUG
85664/*
85665** Increment the nWrite counter in the VDBE if the cursor is not an
85666** ephemeral cursor, or if the cursor argument is NULL.
85667*/
85668SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
85669  if( pC==0
85670   || (pC->eCurType!=CURTYPE_SORTER
85671       && pC->eCurType!=CURTYPE_PSEUDO
85672       && !pC->isEphemeral)
85673  ){
85674    p->nWrite++;
85675  }
85676}
85677#endif
85678
85679#ifdef SQLITE_DEBUG
85680/*
85681** Assert if an Abort at this point in time might result in a corrupt
85682** database.
85683*/
85684SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){
85685  assert( p->nWrite==0 || p->usesStmtJournal );
85686}
85687#endif
85688
85689/*
85690** This routine is called after all opcodes have been inserted.  It loops
85691** through all the opcodes and fixes up some details.
85692**
85693** (1) For each jump instruction with a negative P2 value (a label)
85694**     resolve the P2 value to an actual address.
85695**
85696** (2) Compute the maximum number of arguments used by any SQL function
85697**     and store that value in *pMaxFuncArgs.
85698**
85699** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
85700**     indicate what the prepared statement actually does.
85701**
85702** (4) (discontinued)
85703**
85704** (5) Reclaim the memory allocated for storing labels.
85705**
85706** This routine will only function correctly if the mkopcodeh.tcl generator
85707** script numbers the opcodes correctly.  Changes to this routine must be
85708** coordinated with changes to mkopcodeh.tcl.
85709*/
85710static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
85711  int nMaxArgs = *pMaxFuncArgs;
85712  Op *pOp;
85713  Parse *pParse = p->pParse;
85714  int *aLabel = pParse->aLabel;
85715
85716  assert( pParse->db->mallocFailed==0 ); /* tag-20230419-1 */
85717  p->readOnly = 1;
85718  p->bIsReader = 0;
85719  pOp = &p->aOp[p->nOp-1];
85720  assert( p->aOp[0].opcode==OP_Init );
85721  while( 1 /* Loop terminates when it reaches the OP_Init opcode */ ){
85722    /* Only JUMP opcodes and the short list of special opcodes in the switch
85723    ** below need to be considered.  The mkopcodeh.tcl generator script groups
85724    ** all these opcodes together near the front of the opcode list.  Skip
85725    ** any opcode that does not need processing by virtual of the fact that
85726    ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
85727    */
85728    if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
85729      /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
85730      ** cases from this switch! */
85731      switch( pOp->opcode ){
85732        case OP_Transaction: {
85733          if( pOp->p2!=0 ) p->readOnly = 0;
85734          /* no break */ deliberate_fall_through
85735        }
85736        case OP_AutoCommit:
85737        case OP_Savepoint: {
85738          p->bIsReader = 1;
85739          break;
85740        }
85741#ifndef SQLITE_OMIT_WAL
85742        case OP_Checkpoint:
85743#endif
85744        case OP_Vacuum:
85745        case OP_JournalMode: {
85746          p->readOnly = 0;
85747          p->bIsReader = 1;
85748          break;
85749        }
85750        case OP_Init: {
85751          assert( pOp->p2>=0 );
85752          goto resolve_p2_values_loop_exit;
85753        }
85754#ifndef SQLITE_OMIT_VIRTUALTABLE
85755        case OP_VUpdate: {
85756          if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
85757          break;
85758        }
85759        case OP_VFilter: {
85760          int n;
85761          assert( (pOp - p->aOp) >= 3 );
85762          assert( pOp[-1].opcode==OP_Integer );
85763          n = pOp[-1].p1;
85764          if( n>nMaxArgs ) nMaxArgs = n;
85765          /* Fall through into the default case */
85766          /* no break */ deliberate_fall_through
85767        }
85768#endif
85769        default: {
85770          if( pOp->p2<0 ){
85771            /* The mkopcodeh.tcl script has so arranged things that the only
85772            ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
85773            ** have non-negative values for P2. */
85774            assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
85775            assert( ADDR(pOp->p2)<-pParse->nLabel );
85776            assert( aLabel!=0 );  /* True because of tag-20230419-1 */
85777            pOp->p2 = aLabel[ADDR(pOp->p2)];
85778          }
85779
85780          /* OPFLG_JUMP opcodes never have P2==0, though OPFLG_JUMP0 opcodes
85781          ** might */
85782          assert( pOp->p2>0
85783                  || (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP0)!=0 );
85784
85785          /* Jumps never go off the end of the bytecode array */
85786          assert( pOp->p2<p->nOp
85787                  || (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)==0 );
85788          break;
85789        }
85790      }
85791      /* The mkopcodeh.tcl script has so arranged things that the only
85792      ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
85793      ** have non-negative values for P2. */
85794      assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
85795    }
85796    assert( pOp>p->aOp );
85797    pOp--;
85798  }
85799resolve_p2_values_loop_exit:
85800  if( aLabel ){
85801    sqlite3DbNNFreeNN(p->db, pParse->aLabel);
85802    pParse->aLabel = 0;
85803  }
85804  pParse->nLabel = 0;
85805  *pMaxFuncArgs = nMaxArgs;
85806  assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
85807}
85808
85809#ifdef SQLITE_DEBUG
85810/*
85811** Check to see if a subroutine contains a jump to a location outside of
85812** the subroutine.  If a jump outside the subroutine is detected, add code
85813** that will cause the program to halt with an error message.
85814**
85815** The subroutine consists of opcodes between iFirst and iLast.  Jumps to
85816** locations within the subroutine are acceptable.  iRetReg is a register
85817** that contains the return address.  Jumps to outside the range of iFirst
85818** through iLast are also acceptable as long as the jump destination is
85819** an OP_Return to iReturnAddr.
85820**
85821** A jump to an unresolved label means that the jump destination will be
85822** beyond the current address.  That is normally a jump to an early
85823** termination and is consider acceptable.
85824**
85825** This routine only runs during debug builds.  The purpose is (of course)
85826** to detect invalid escapes out of a subroutine.  The OP_Halt opcode
85827** is generated rather than an assert() or other error, so that ".eqp full"
85828** will still work to show the original bytecode, to aid in debugging.
85829*/
85830SQLITE_PRIVATE void sqlite3VdbeNoJumpsOutsideSubrtn(
85831  Vdbe *v,          /* The byte-code program under construction */
85832  int iFirst,       /* First opcode of the subroutine */
85833  int iLast,        /* Last opcode of the subroutine */
85834  int iRetReg       /* Subroutine return address register */
85835){
85836  VdbeOp *pOp;
85837  Parse *pParse;
85838  int i;
85839  sqlite3_str *pErr = 0;
85840  assert( v!=0 );
85841  pParse = v->pParse;
85842  assert( pParse!=0 );
85843  if( pParse->nErr ) return;
85844  assert( iLast>=iFirst );
85845  assert( iLast<v->nOp );
85846  pOp = &v->aOp[iFirst];
85847  for(i=iFirst; i<=iLast; i++, pOp++){
85848    if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 ){
85849      int iDest = pOp->p2;   /* Jump destination */
85850      if( iDest==0 ) continue;
85851      if( pOp->opcode==OP_Gosub ) continue;
85852      if( pOp->p3==20230325 && pOp->opcode==OP_NotNull ){
85853        /* This is a deliberately taken illegal branch.  tag-20230325-2 */
85854        continue;
85855      }
85856      if( iDest<0 ){
85857        int j = ADDR(iDest);
85858        assert( j>=0 );
85859        if( j>=-pParse->nLabel || pParse->aLabel[j]<0 ){
85860          continue;
85861        }
85862        iDest = pParse->aLabel[j];
85863      }
85864      if( iDest<iFirst || iDest>iLast ){
85865        int j = iDest;
85866        for(; j<v->nOp; j++){
85867          VdbeOp *pX = &v->aOp[j];
85868          if( pX->opcode==OP_Return ){
85869            if( pX->p1==iRetReg ) break;
85870            continue;
85871          }
85872          if( pX->opcode==OP_Noop ) continue;
85873          if( pX->opcode==OP_Explain ) continue;
85874          if( pErr==0 ){
85875            pErr = sqlite3_str_new(0);
85876          }else{
85877            sqlite3_str_appendchar(pErr, 1, '\n');
85878          }
85879          sqlite3_str_appendf(pErr,
85880              "Opcode at %d jumps to %d which is outside the "
85881              "subroutine at %d..%d",
85882              i, iDest, iFirst, iLast);
85883          break;
85884        }
85885      }
85886    }
85887  }
85888  if( pErr ){
85889    char *zErr = sqlite3_str_finish(pErr);
85890    sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_INTERNAL, OE_Abort, 0, zErr, 0);
85891    sqlite3_free(zErr);
85892    sqlite3MayAbort(pParse);
85893  }
85894}
85895#endif /* SQLITE_DEBUG */
85896
85897/*
85898** Return the address of the next instruction to be inserted.
85899*/
85900SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
85901  assert( p->eVdbeState==VDBE_INIT_STATE );
85902  return p->nOp;
85903}
85904
85905/*
85906** Verify that at least N opcode slots are available in p without
85907** having to malloc for more space (except when compiled using
85908** SQLITE_TEST_REALLOC_STRESS).  This interface is used during testing
85909** to verify that certain calls to sqlite3VdbeAddOpList() can never
85910** fail due to a OOM fault and hence that the return value from
85911** sqlite3VdbeAddOpList() will always be non-NULL.
85912*/
85913#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
85914SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
85915  assert( p->nOp + N <= p->nOpAlloc );
85916}
85917#endif
85918
85919/*
85920** Verify that the VM passed as the only argument does not contain
85921** an OP_ResultRow opcode. Fail an assert() if it does. This is used
85922** by code in pragma.c to ensure that the implementation of certain
85923** pragmas comports with the flags specified in the mkpragmatab.tcl
85924** script.
85925*/
85926#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
85927SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
85928  int i;
85929  for(i=0; i<p->nOp; i++){
85930    assert( p->aOp[i].opcode!=OP_ResultRow );
85931  }
85932}
85933#endif
85934
85935/*
85936** Generate code (a single OP_Abortable opcode) that will
85937** verify that the VDBE program can safely call Abort in the current
85938** context.
85939*/
85940#if defined(SQLITE_DEBUG)
85941SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
85942  if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
85943}
85944#endif
85945
85946/*
85947** This function returns a pointer to the array of opcodes associated with
85948** the Vdbe passed as the first argument. It is the callers responsibility
85949** to arrange for the returned array to be eventually freed using the
85950** vdbeFreeOpArray() function.
85951**
85952** Before returning, *pnOp is set to the number of entries in the returned
85953** array. Also, *pnMaxArg is set to the larger of its current value and
85954** the number of entries in the Vdbe.apArg[] array required to execute the
85955** returned program.
85956*/
85957SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
85958  VdbeOp *aOp = p->aOp;
85959  assert( aOp && !p->db->mallocFailed );
85960
85961  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
85962  assert( DbMaskAllZero(p->btreeMask) );
85963
85964  resolveP2Values(p, pnMaxArg);
85965  *pnOp = p->nOp;
85966  p->aOp = 0;
85967  return aOp;
85968}
85969
85970/*
85971** Add a whole list of operations to the operation stack.  Return a
85972** pointer to the first operation inserted.
85973**
85974** Non-zero P2 arguments to jump instructions are automatically adjusted
85975** so that the jump target is relative to the first operation inserted.
85976*/
85977SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
85978  Vdbe *p,                     /* Add opcodes to the prepared statement */
85979  int nOp,                     /* Number of opcodes to add */
85980  VdbeOpList const *aOp,       /* The opcodes to be added */
85981  int iLineno                  /* Source-file line number of first opcode */
85982){
85983  int i;
85984  VdbeOp *pOut, *pFirst;
85985  assert( nOp>0 );
85986  assert( p->eVdbeState==VDBE_INIT_STATE );
85987  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
85988    return 0;
85989  }
85990  pFirst = pOut = &p->aOp[p->nOp];
85991  for(i=0; i<nOp; i++, aOp++, pOut++){
85992    pOut->opcode = aOp->opcode;
85993    pOut->p1 = aOp->p1;
85994    pOut->p2 = aOp->p2;
85995    assert( aOp->p2>=0 );
85996    if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
85997      pOut->p2 += p->nOp;
85998    }
85999    pOut->p3 = aOp->p3;
86000    pOut->p4type = P4_NOTUSED;
86001    pOut->p4.p = 0;
86002    pOut->p5 = 0;
86003#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
86004    pOut->zComment = 0;
86005#endif
86006#ifdef SQLITE_VDBE_COVERAGE
86007    pOut->iSrcLine = iLineno+i;
86008#else
86009    (void)iLineno;
86010#endif
86011#ifdef SQLITE_DEBUG
86012    if( p->db->flags & SQLITE_VdbeAddopTrace ){
86013      sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
86014    }
86015#endif
86016  }
86017  p->nOp += nOp;
86018  return pFirst;
86019}
86020
86021#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
86022/*
86023** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
86024*/
86025SQLITE_PRIVATE void sqlite3VdbeScanStatus(
86026  Vdbe *p,                        /* VM to add scanstatus() to */
86027  int addrExplain,                /* Address of OP_Explain (or 0) */
86028  int addrLoop,                   /* Address of loop counter */
86029  int addrVisit,                  /* Address of rows visited counter */
86030  LogEst nEst,                    /* Estimated number of output rows */
86031  const char *zName               /* Name of table or index being scanned */
86032){
86033  if( IS_STMT_SCANSTATUS(p->db) ){
86034    sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);
86035    ScanStatus *aNew;
86036    aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
86037    if( aNew ){
86038      ScanStatus *pNew = &aNew[p->nScan++];
86039      memset(pNew, 0, sizeof(ScanStatus));
86040      pNew->addrExplain = addrExplain;
86041      pNew->addrLoop = addrLoop;
86042      pNew->addrVisit = addrVisit;
86043      pNew->nEst = nEst;
86044      pNew->zName = sqlite3DbStrDup(p->db, zName);
86045      p->aScan = aNew;
86046    }
86047  }
86048}
86049
86050/*
86051** Add the range of instructions from addrStart to addrEnd (inclusive) to
86052** the set of those corresponding to the sqlite3_stmt_scanstatus() counters
86053** associated with the OP_Explain instruction at addrExplain. The
86054** sum of the sqlite3Hwtime() values for each of these instructions
86055** will be returned for SQLITE_SCANSTAT_NCYCLE requests.
86056*/
86057SQLITE_PRIVATE void sqlite3VdbeScanStatusRange(
86058  Vdbe *p,
86059  int addrExplain,
86060  int addrStart,
86061  int addrEnd
86062){
86063  if( IS_STMT_SCANSTATUS(p->db) ){
86064    ScanStatus *pScan = 0;
86065    int ii;
86066    for(ii=p->nScan-1; ii>=0; ii--){
86067      pScan = &p->aScan[ii];
86068      if( pScan->addrExplain==addrExplain ) break;
86069      pScan = 0;
86070    }
86071    if( pScan ){
86072      if( addrEnd<0 ) addrEnd = sqlite3VdbeCurrentAddr(p)-1;
86073      for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
86074        if( pScan->aAddrRange[ii]==0 ){
86075          pScan->aAddrRange[ii] = addrStart;
86076          pScan->aAddrRange[ii+1] = addrEnd;
86077          break;
86078        }
86079      }
86080    }
86081  }
86082}
86083
86084/*
86085** Set the addresses for the SQLITE_SCANSTAT_NLOOP and SQLITE_SCANSTAT_NROW
86086** counters for the query element associated with the OP_Explain at
86087** addrExplain.
86088*/
86089SQLITE_PRIVATE void sqlite3VdbeScanStatusCounters(
86090  Vdbe *p,
86091  int addrExplain,
86092  int addrLoop,
86093  int addrVisit
86094){
86095  if( IS_STMT_SCANSTATUS(p->db) ){
86096    ScanStatus *pScan = 0;
86097    int ii;
86098    for(ii=p->nScan-1; ii>=0; ii--){
86099      pScan = &p->aScan[ii];
86100      if( pScan->addrExplain==addrExplain ) break;
86101      pScan = 0;
86102    }
86103    if( pScan ){
86104      if( addrLoop>0 ) pScan->addrLoop = addrLoop;
86105      if( addrVisit>0 ) pScan->addrVisit = addrVisit;
86106    }
86107  }
86108}
86109#endif /* defined(SQLITE_ENABLE_STMT_SCANSTATUS) */
86110
86111
86112/*
86113** Change the value of the opcode, or P1, P2, P3, or P5 operands
86114** for a specific instruction.
86115*/
86116SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){
86117  assert( addr>=0 );
86118  sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
86119}
86120SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
86121  assert( addr>=0 );
86122  sqlite3VdbeGetOp(p,addr)->p1 = val;
86123}
86124SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
86125  assert( addr>=0 || p->db->mallocFailed );
86126  sqlite3VdbeGetOp(p,addr)->p2 = val;
86127}
86128SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
86129  assert( addr>=0 );
86130  sqlite3VdbeGetOp(p,addr)->p3 = val;
86131}
86132SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
86133  assert( p->nOp>0 || p->db->mallocFailed );
86134  if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
86135}
86136
86137/*
86138** If the previous opcode is an OP_Column that delivers results
86139** into register iDest, then add the OPFLAG_TYPEOFARG flag to that
86140** opcode.
86141*/
86142SQLITE_PRIVATE void sqlite3VdbeTypeofColumn(Vdbe *p, int iDest){
86143  VdbeOp *pOp = sqlite3VdbeGetLastOp(p);
86144  if( pOp->p3==iDest && pOp->opcode==OP_Column ){
86145    pOp->p5 |= OPFLAG_TYPEOFARG;
86146  }
86147}
86148
86149/*
86150** Change the P2 operand of instruction addr so that it points to
86151** the address of the next instruction to be coded.
86152*/
86153SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
86154  sqlite3VdbeChangeP2(p, addr, p->nOp);
86155}
86156
86157/*
86158** Change the P2 operand of the jump instruction at addr so that
86159** the jump lands on the next opcode.  Or if the jump instruction was
86160** the previous opcode (and is thus a no-op) then simply back up
86161** the next instruction counter by one slot so that the jump is
86162** overwritten by the next inserted opcode.
86163**
86164** This routine is an optimization of sqlite3VdbeJumpHere() that
86165** strives to omit useless byte-code like this:
86166**
86167**        7   Once 0 8 0
86168**        8   ...
86169*/
86170SQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe *p, int addr){
86171  if( addr==p->nOp-1 ){
86172    assert( p->aOp[addr].opcode==OP_Once
86173         || p->aOp[addr].opcode==OP_If
86174         || p->aOp[addr].opcode==OP_FkIfZero );
86175    assert( p->aOp[addr].p4type==0 );
86176#ifdef SQLITE_VDBE_COVERAGE
86177    sqlite3VdbeGetLastOp(p)->iSrcLine = 0;  /* Erase VdbeCoverage() macros */
86178#endif
86179    p->nOp--;
86180  }else{
86181    sqlite3VdbeChangeP2(p, addr, p->nOp);
86182  }
86183}
86184
86185
86186/*
86187** If the input FuncDef structure is ephemeral, then free it.  If
86188** the FuncDef is not ephemeral, then do nothing.
86189*/
86190static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
86191  assert( db!=0 );
86192  if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
86193    sqlite3DbNNFreeNN(db, pDef);
86194  }
86195}
86196
86197/*
86198** Delete a P4 value if necessary.
86199*/
86200static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
86201  if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
86202  sqlite3DbNNFreeNN(db, p);
86203}
86204static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
86205  assert( db!=0 );
86206  freeEphemeralFunction(db, p->pFunc);
86207  sqlite3DbNNFreeNN(db, p);
86208}
86209static void freeP4(sqlite3 *db, int p4type, void *p4){
86210  assert( db );
86211  switch( p4type ){
86212    case P4_FUNCCTX: {
86213      freeP4FuncCtx(db, (sqlite3_context*)p4);
86214      break;
86215    }
86216    case P4_REAL:
86217    case P4_INT64:
86218    case P4_DYNAMIC:
86219    case P4_INTARRAY: {
86220      if( p4 ) sqlite3DbNNFreeNN(db, p4);
86221      break;
86222    }
86223    case P4_KEYINFO: {
86224      if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
86225      break;
86226    }
86227#ifdef SQLITE_ENABLE_CURSOR_HINTS
86228    case P4_EXPR: {
86229      sqlite3ExprDelete(db, (Expr*)p4);
86230      break;
86231    }
86232#endif
86233    case P4_FUNCDEF: {
86234      freeEphemeralFunction(db, (FuncDef*)p4);
86235      break;
86236    }
86237    case P4_MEM: {
86238      if( db->pnBytesFreed==0 ){
86239        sqlite3ValueFree((sqlite3_value*)p4);
86240      }else{
86241        freeP4Mem(db, (Mem*)p4);
86242      }
86243      break;
86244    }
86245    case P4_VTAB : {
86246      if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
86247      break;
86248    }
86249    case P4_TABLEREF: {
86250      if( db->pnBytesFreed==0 ) sqlite3DeleteTable(db, (Table*)p4);
86251      break;
86252    }
86253  }
86254}
86255
86256/*
86257** Free the space allocated for aOp and any p4 values allocated for the
86258** opcodes contained within. If aOp is not NULL it is assumed to contain
86259** nOp entries.
86260*/
86261static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
86262  assert( nOp>=0 );
86263  assert( db!=0 );
86264  if( aOp ){
86265    Op *pOp = &aOp[nOp-1];
86266    while(1){  /* Exit via break */
86267      if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
86268#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
86269      sqlite3DbFree(db, pOp->zComment);
86270#endif
86271      if( pOp==aOp ) break;
86272      pOp--;
86273    }
86274    sqlite3DbNNFreeNN(db, aOp);
86275  }
86276}
86277
86278/*
86279** Link the SubProgram object passed as the second argument into the linked
86280** list at Vdbe.pSubProgram. This list is used to delete all sub-program
86281** objects when the VM is no longer required.
86282*/
86283SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
86284  p->pNext = pVdbe->pProgram;
86285  pVdbe->pProgram = p;
86286}
86287
86288/*
86289** Return true if the given Vdbe has any SubPrograms.
86290*/
86291SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe *pVdbe){
86292  return pVdbe->pProgram!=0;
86293}
86294
86295/*
86296** Change the opcode at addr into OP_Noop
86297*/
86298SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
86299  VdbeOp *pOp;
86300  if( p->db->mallocFailed ) return 0;
86301  assert( addr>=0 && addr<p->nOp );
86302  pOp = &p->aOp[addr];
86303  freeP4(p->db, pOp->p4type, pOp->p4.p);
86304  pOp->p4type = P4_NOTUSED;
86305  pOp->p4.z = 0;
86306  pOp->opcode = OP_Noop;
86307  return 1;
86308}
86309
86310/*
86311** If the last opcode is "op" and it is not a jump destination,
86312** then remove it.  Return true if and only if an opcode was removed.
86313*/
86314SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
86315  if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
86316    return sqlite3VdbeChangeToNoop(p, p->nOp-1);
86317  }else{
86318    return 0;
86319  }
86320}
86321
86322#ifdef SQLITE_DEBUG
86323/*
86324** Generate an OP_ReleaseReg opcode to indicate that a range of
86325** registers, except any identified by mask, are no longer in use.
86326*/
86327SQLITE_PRIVATE void sqlite3VdbeReleaseRegisters(
86328  Parse *pParse,       /* Parsing context */
86329  int iFirst,          /* Index of first register to be released */
86330  int N,               /* Number of registers to release */
86331  u32 mask,            /* Mask of registers to NOT release */
86332  int bUndefine        /* If true, mark registers as undefined */
86333){
86334  if( N==0 || OptimizationDisabled(pParse->db, SQLITE_ReleaseReg) ) return;
86335  assert( pParse->pVdbe );
86336  assert( iFirst>=1 );
86337  assert( iFirst+N-1<=pParse->nMem );
86338  if( N<=31 && mask!=0 ){
86339    while( N>0 && (mask&1)!=0 ){
86340      mask >>= 1;
86341      iFirst++;
86342      N--;
86343    }
86344    while( N>0 && N<=32 && (mask & MASKBIT32(N-1))!=0 ){
86345      mask &= ~MASKBIT32(N-1);
86346      N--;
86347    }
86348  }
86349  if( N>0 ){
86350    sqlite3VdbeAddOp3(pParse->pVdbe, OP_ReleaseReg, iFirst, N, *(int*)&mask);
86351    if( bUndefine ) sqlite3VdbeChangeP5(pParse->pVdbe, 1);
86352  }
86353}
86354#endif /* SQLITE_DEBUG */
86355
86356/*
86357** Change the value of the P4 operand for a specific instruction.
86358** This routine is useful when a large program is loaded from a
86359** static array using sqlite3VdbeAddOpList but we want to make a
86360** few minor changes to the program.
86361**
86362** If n>=0 then the P4 operand is dynamic, meaning that a copy of
86363** the string is made into memory obtained from sqlite3_malloc().
86364** A value of n==0 means copy bytes of zP4 up to and including the
86365** first null byte.  If n>0 then copy n+1 bytes of zP4.
86366**
86367** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
86368** to a string or structure that is guaranteed to exist for the lifetime of
86369** the Vdbe. In these cases we can just copy the pointer.
86370**
86371** If addr<0 then change P4 on the most recently inserted instruction.
86372*/
86373static void SQLITE_NOINLINE vdbeChangeP4Full(
86374  Vdbe *p,
86375  Op *pOp,
86376  const char *zP4,
86377  int n
86378){
86379  if( pOp->p4type ){
86380    assert( pOp->p4type > P4_FREE_IF_LE );
86381    pOp->p4type = 0;
86382    pOp->p4.p = 0;
86383  }
86384  if( n<0 ){
86385    sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
86386  }else{
86387    if( n==0 ) n = sqlite3Strlen30(zP4);
86388    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
86389    pOp->p4type = P4_DYNAMIC;
86390  }
86391}
86392SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
86393  Op *pOp;
86394  sqlite3 *db;
86395  assert( p!=0 );
86396  db = p->db;
86397  assert( p->eVdbeState==VDBE_INIT_STATE );
86398  assert( p->aOp!=0 || db->mallocFailed );
86399  if( db->mallocFailed ){
86400    if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
86401    return;
86402  }
86403  assert( p->nOp>0 );
86404  assert( addr<p->nOp );
86405  if( addr<0 ){
86406    addr = p->nOp - 1;
86407  }
86408  pOp = &p->aOp[addr];
86409  if( n>=0 || pOp->p4type ){
86410    vdbeChangeP4Full(p, pOp, zP4, n);
86411    return;
86412  }
86413  if( n==P4_INT32 ){
86414    /* Note: this cast is safe, because the origin data point was an int
86415    ** that was cast to a (const char *). */
86416    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
86417    pOp->p4type = P4_INT32;
86418  }else if( zP4!=0 ){
86419    assert( n<0 );
86420    pOp->p4.p = (void*)zP4;
86421    pOp->p4type = (signed char)n;
86422    if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
86423  }
86424}
86425
86426/*
86427** Change the P4 operand of the most recently coded instruction
86428** to the value defined by the arguments.  This is a high-speed
86429** version of sqlite3VdbeChangeP4().
86430**
86431** The P4 operand must not have been previously defined.  And the new
86432** P4 must not be P4_INT32.  Use sqlite3VdbeChangeP4() in either of
86433** those cases.
86434*/
86435SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
86436  VdbeOp *pOp;
86437  assert( n!=P4_INT32 && n!=P4_VTAB );
86438  assert( n<=0 );
86439  if( p->db->mallocFailed ){
86440    freeP4(p->db, n, pP4);
86441  }else{
86442    assert( pP4!=0 || n==P4_DYNAMIC );
86443    assert( p->nOp>0 );
86444    pOp = &p->aOp[p->nOp-1];
86445    assert( pOp->p4type==P4_NOTUSED );
86446    pOp->p4type = n;
86447    pOp->p4.p = pP4;
86448  }
86449}
86450
86451/*
86452** Set the P4 on the most recently added opcode to the KeyInfo for the
86453** index given.
86454*/
86455SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
86456  Vdbe *v = pParse->pVdbe;
86457  KeyInfo *pKeyInfo;
86458  assert( v!=0 );
86459  assert( pIdx!=0 );
86460  pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
86461  if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
86462}
86463
86464#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
86465/*
86466** Change the comment on the most recently coded instruction.  Or
86467** insert a No-op and add the comment to that new instruction.  This
86468** makes the code easier to read during debugging.  None of this happens
86469** in a production build.
86470*/
86471static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
86472  assert( p->nOp>0 || p->aOp==0 );
86473  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->pParse->nErr>0 );
86474  if( p->nOp ){
86475    assert( p->aOp );
86476    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
86477    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
86478  }
86479}
86480SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
86481  va_list ap;
86482  if( p ){
86483    va_start(ap, zFormat);
86484    vdbeVComment(p, zFormat, ap);
86485    va_end(ap);
86486  }
86487}
86488SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
86489  va_list ap;
86490  if( p ){
86491    sqlite3VdbeAddOp0(p, OP_Noop);
86492    va_start(ap, zFormat);
86493    vdbeVComment(p, zFormat, ap);
86494    va_end(ap);
86495  }
86496}
86497#endif  /* NDEBUG */
86498
86499#ifdef SQLITE_VDBE_COVERAGE
86500/*
86501** Set the value if the iSrcLine field for the previously coded instruction.
86502*/
86503SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
86504  sqlite3VdbeGetLastOp(v)->iSrcLine = iLine;
86505}
86506#endif /* SQLITE_VDBE_COVERAGE */
86507
86508/*
86509** Return the opcode for a given address.  The address must be non-negative.
86510** See sqlite3VdbeGetLastOp() to get the most recently added opcode.
86511**
86512** If a memory allocation error has occurred prior to the calling of this
86513** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
86514** is readable but not writable, though it is cast to a writable value.
86515** The return of a dummy opcode allows the call to continue functioning
86516** after an OOM fault without having to check to see if the return from
86517** this routine is a valid pointer.  But because the dummy.opcode is 0,
86518** dummy will never be written to.  This is verified by code inspection and
86519** by running with Valgrind.
86520*/
86521SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
86522  /* C89 specifies that the constant "dummy" will be initialized to all
86523  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
86524  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
86525  assert( p->eVdbeState==VDBE_INIT_STATE );
86526  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
86527  if( p->db->mallocFailed ){
86528    return (VdbeOp*)&dummy;
86529  }else{
86530    return &p->aOp[addr];
86531  }
86532}
86533
86534/* Return the most recently added opcode
86535*/
86536SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetLastOp(Vdbe *p){
86537  return sqlite3VdbeGetOp(p, p->nOp - 1);
86538}
86539
86540#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
86541/*
86542** Return an integer value for one of the parameters to the opcode pOp
86543** determined by character c.
86544*/
86545static int translateP(char c, const Op *pOp){
86546  if( c=='1' ) return pOp->p1;
86547  if( c=='2' ) return pOp->p2;
86548  if( c=='3' ) return pOp->p3;
86549  if( c=='4' ) return pOp->p4.i;
86550  return pOp->p5;
86551}
86552
86553/*
86554** Compute a string for the "comment" field of a VDBE opcode listing.
86555**
86556** The Synopsis: field in comments in the vdbe.c source file gets converted
86557** to an extra string that is appended to the sqlite3OpcodeName().  In the
86558** absence of other comments, this synopsis becomes the comment on the opcode.
86559** Some translation occurs:
86560**
86561**       "PX"      ->  "r[X]"
86562**       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
86563**       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
86564**       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
86565*/
86566SQLITE_PRIVATE char *sqlite3VdbeDisplayComment(
86567  sqlite3 *db,       /* Optional - Oom error reporting only */
86568  const Op *pOp,     /* The opcode to be commented */
86569  const char *zP4    /* Previously obtained value for P4 */
86570){
86571  const char *zOpName;
86572  const char *zSynopsis;
86573  int nOpName;
86574  int ii;
86575  char zAlt[50];
86576  StrAccum x;
86577
86578  sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
86579  zOpName = sqlite3OpcodeName(pOp->opcode);
86580  nOpName = sqlite3Strlen30(zOpName);
86581  if( zOpName[nOpName+1] ){
86582    int seenCom = 0;
86583    char c;
86584    zSynopsis = zOpName + nOpName + 1;
86585    if( strncmp(zSynopsis,"IF ",3)==0 ){
86586      sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
86587      zSynopsis = zAlt;
86588    }
86589    for(ii=0; (c = zSynopsis[ii])!=0; ii++){
86590      if( c=='P' ){
86591        c = zSynopsis[++ii];
86592        if( c=='4' ){
86593          sqlite3_str_appendall(&x, zP4);
86594        }else if( c=='X' ){
86595          if( pOp->zComment && pOp->zComment[0] ){
86596            sqlite3_str_appendall(&x, pOp->zComment);
86597            seenCom = 1;
86598            break;
86599          }
86600        }else{
86601          int v1 = translateP(c, pOp);
86602          int v2;
86603          if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
86604            ii += 3;
86605            v2 = translateP(zSynopsis[ii], pOp);
86606            if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
86607              ii += 2;
86608              v2++;
86609            }
86610            if( v2<2 ){
86611              sqlite3_str_appendf(&x, "%d", v1);
86612            }else{
86613              sqlite3_str_appendf(&x, "%d..%d", v1, v1+v2-1);
86614            }
86615          }else if( strncmp(zSynopsis+ii+1, "@NP", 3)==0 ){
86616            sqlite3_context *pCtx = pOp->p4.pCtx;
86617            if( pOp->p4type!=P4_FUNCCTX || pCtx->argc==1 ){
86618              sqlite3_str_appendf(&x, "%d", v1);
86619            }else if( pCtx->argc>1 ){
86620              sqlite3_str_appendf(&x, "%d..%d", v1, v1+pCtx->argc-1);
86621            }else if( x.accError==0 ){
86622              assert( x.nChar>2 );
86623              x.nChar -= 2;
86624              ii++;
86625            }
86626            ii += 3;
86627          }else{
86628            sqlite3_str_appendf(&x, "%d", v1);
86629            if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
86630              ii += 4;
86631            }
86632          }
86633        }
86634      }else{
86635        sqlite3_str_appendchar(&x, 1, c);
86636      }
86637    }
86638    if( !seenCom && pOp->zComment ){
86639      sqlite3_str_appendf(&x, "; %s", pOp->zComment);
86640    }
86641  }else if( pOp->zComment ){
86642    sqlite3_str_appendall(&x, pOp->zComment);
86643  }
86644  if( (x.accError & SQLITE_NOMEM)!=0 && db!=0 ){
86645    sqlite3OomFault(db);
86646  }
86647  return sqlite3StrAccumFinish(&x);
86648}
86649#endif /* SQLITE_ENABLE_EXPLAIN_COMMENTS */
86650
86651#if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
86652/*
86653** Translate the P4.pExpr value for an OP_CursorHint opcode into text
86654** that can be displayed in the P4 column of EXPLAIN output.
86655*/
86656static void displayP4Expr(StrAccum *p, Expr *pExpr){
86657  const char *zOp = 0;
86658  switch( pExpr->op ){
86659    case TK_STRING:
86660      assert( !ExprHasProperty(pExpr, EP_IntValue) );
86661      sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
86662      break;
86663    case TK_INTEGER:
86664      sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
86665      break;
86666    case TK_NULL:
86667      sqlite3_str_appendf(p, "NULL");
86668      break;
86669    case TK_REGISTER: {
86670      sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
86671      break;
86672    }
86673    case TK_COLUMN: {
86674      if( pExpr->iColumn<0 ){
86675        sqlite3_str_appendf(p, "rowid");
86676      }else{
86677        sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
86678      }
86679      break;
86680    }
86681    case TK_LT:      zOp = "LT";      break;
86682    case TK_LE:      zOp = "LE";      break;
86683    case TK_GT:      zOp = "GT";      break;
86684    case TK_GE:      zOp = "GE";      break;
86685    case TK_NE:      zOp = "NE";      break;
86686    case TK_EQ:      zOp = "EQ";      break;
86687    case TK_IS:      zOp = "IS";      break;
86688    case TK_ISNOT:   zOp = "ISNOT";   break;
86689    case TK_AND:     zOp = "AND";     break;
86690    case TK_OR:      zOp = "OR";      break;
86691    case TK_PLUS:    zOp = "ADD";     break;
86692    case TK_STAR:    zOp = "MUL";     break;
86693    case TK_MINUS:   zOp = "SUB";     break;
86694    case TK_REM:     zOp = "REM";     break;
86695    case TK_BITAND:  zOp = "BITAND";  break;
86696    case TK_BITOR:   zOp = "BITOR";   break;
86697    case TK_SLASH:   zOp = "DIV";     break;
86698    case TK_LSHIFT:  zOp = "LSHIFT";  break;
86699    case TK_RSHIFT:  zOp = "RSHIFT";  break;
86700    case TK_CONCAT:  zOp = "CONCAT";  break;
86701    case TK_UMINUS:  zOp = "MINUS";   break;
86702    case TK_UPLUS:   zOp = "PLUS";    break;
86703    case TK_BITNOT:  zOp = "BITNOT";  break;
86704    case TK_NOT:     zOp = "NOT";     break;
86705    case TK_ISNULL:  zOp = "ISNULL";  break;
86706    case TK_NOTNULL: zOp = "NOTNULL"; break;
86707
86708    default:
86709      sqlite3_str_appendf(p, "%s", "expr");
86710      break;
86711  }
86712
86713  if( zOp ){
86714    sqlite3_str_appendf(p, "%s(", zOp);
86715    displayP4Expr(p, pExpr->pLeft);
86716    if( pExpr->pRight ){
86717      sqlite3_str_append(p, ",", 1);
86718      displayP4Expr(p, pExpr->pRight);
86719    }
86720    sqlite3_str_append(p, ")", 1);
86721  }
86722}
86723#endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
86724
86725
86726#if VDBE_DISPLAY_P4
86727/*
86728** Compute a string that describes the P4 parameter for an opcode.
86729** Use zTemp for any required temporary buffer space.
86730*/
86731SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){
86732  char *zP4 = 0;
86733  StrAccum x;
86734
86735  sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
86736  switch( pOp->p4type ){
86737    case P4_KEYINFO: {
86738      int j;
86739      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
86740      assert( pKeyInfo->aSortFlags!=0 );
86741      sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
86742      for(j=0; j<pKeyInfo->nKeyField; j++){
86743        CollSeq *pColl = pKeyInfo->aColl[j];
86744        const char *zColl = pColl ? pColl->zName : "";
86745        if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
86746        sqlite3_str_appendf(&x, ",%s%s%s",
86747               (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "",
86748               (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "",
86749               zColl);
86750      }
86751      sqlite3_str_append(&x, ")", 1);
86752      break;
86753    }
86754#ifdef SQLITE_ENABLE_CURSOR_HINTS
86755    case P4_EXPR: {
86756      displayP4Expr(&x, pOp->p4.pExpr);
86757      break;
86758    }
86759#endif
86760    case P4_COLLSEQ: {
86761      static const char *const encnames[] = {"?", "8", "16LE", "16BE"};
86762      CollSeq *pColl = pOp->p4.pColl;
86763      assert( pColl->enc<4 );
86764      sqlite3_str_appendf(&x, "%.18s-%s", pColl->zName,
86765                          encnames[pColl->enc]);
86766      break;
86767    }
86768    case P4_FUNCDEF: {
86769      FuncDef *pDef = pOp->p4.pFunc;
86770      sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
86771      break;
86772    }
86773    case P4_FUNCCTX: {
86774      FuncDef *pDef = pOp->p4.pCtx->pFunc;
86775      sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
86776      break;
86777    }
86778    case P4_INT64: {
86779      sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
86780      break;
86781    }
86782    case P4_INT32: {
86783      sqlite3_str_appendf(&x, "%d", pOp->p4.i);
86784      break;
86785    }
86786    case P4_REAL: {
86787      sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
86788      break;
86789    }
86790    case P4_MEM: {
86791      Mem *pMem = pOp->p4.pMem;
86792      if( pMem->flags & MEM_Str ){
86793        zP4 = pMem->z;
86794      }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
86795        sqlite3_str_appendf(&x, "%lld", pMem->u.i);
86796      }else if( pMem->flags & MEM_Real ){
86797        sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
86798      }else if( pMem->flags & MEM_Null ){
86799        zP4 = "NULL";
86800      }else{
86801        assert( pMem->flags & MEM_Blob );
86802        zP4 = "(blob)";
86803      }
86804      break;
86805    }
86806#ifndef SQLITE_OMIT_VIRTUALTABLE
86807    case P4_VTAB: {
86808      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
86809      sqlite3_str_appendf(&x, "vtab:%p", pVtab);
86810      break;
86811    }
86812#endif
86813    case P4_INTARRAY: {
86814      u32 i;
86815      u32 *ai = pOp->p4.ai;
86816      u32 n = ai[0];   /* The first element of an INTARRAY is always the
86817                       ** count of the number of elements to follow */
86818      for(i=1; i<=n; i++){
86819        sqlite3_str_appendf(&x, "%c%u", (i==1 ? '[' : ','), ai[i]);
86820      }
86821      sqlite3_str_append(&x, "]", 1);
86822      break;
86823    }
86824    case P4_SUBPROGRAM: {
86825      zP4 = "program";
86826      break;
86827    }
86828    case P4_TABLE: {
86829      zP4 = pOp->p4.pTab->zName;
86830      break;
86831    }
86832    default: {
86833      zP4 = pOp->p4.z;
86834    }
86835  }
86836  if( zP4 ) sqlite3_str_appendall(&x, zP4);
86837  if( (x.accError & SQLITE_NOMEM)!=0 ){
86838    sqlite3OomFault(db);
86839  }
86840  return sqlite3StrAccumFinish(&x);
86841}
86842#endif /* VDBE_DISPLAY_P4 */
86843
86844/*
86845** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
86846**
86847** The prepared statements need to know in advance the complete set of
86848** attached databases that will be use.  A mask of these databases
86849** is maintained in p->btreeMask.  The p->lockMask value is the subset of
86850** p->btreeMask of databases that will require a lock.
86851*/
86852SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
86853  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
86854  assert( i<(int)sizeof(p->btreeMask)*8 );
86855  DbMaskSet(p->btreeMask, i);
86856  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
86857    DbMaskSet(p->lockMask, i);
86858  }
86859}
86860
86861#if !defined(SQLITE_OMIT_SHARED_CACHE)
86862/*
86863** If SQLite is compiled to support shared-cache mode and to be threadsafe,
86864** this routine obtains the mutex associated with each BtShared structure
86865** that may be accessed by the VM passed as an argument. In doing so it also
86866** sets the BtShared.db member of each of the BtShared structures, ensuring
86867** that the correct busy-handler callback is invoked if required.
86868**
86869** If SQLite is not threadsafe but does support shared-cache mode, then
86870** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
86871** of all of BtShared structures accessible via the database handle
86872** associated with the VM.
86873**
86874** If SQLite is not threadsafe and does not support shared-cache mode, this
86875** function is a no-op.
86876**
86877** The p->btreeMask field is a bitmask of all btrees that the prepared
86878** statement p will ever use.  Let N be the number of bits in p->btreeMask
86879** corresponding to btrees that use shared cache.  Then the runtime of
86880** this routine is N*N.  But as N is rarely more than 1, this should not
86881** be a problem.
86882*/
86883SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
86884  int i;
86885  sqlite3 *db;
86886  Db *aDb;
86887  int nDb;
86888  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
86889  db = p->db;
86890  aDb = db->aDb;
86891  nDb = db->nDb;
86892  for(i=0; i<nDb; i++){
86893    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
86894      sqlite3BtreeEnter(aDb[i].pBt);
86895    }
86896  }
86897}
86898#endif
86899
86900#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
86901/*
86902** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
86903*/
86904static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
86905  int i;
86906  sqlite3 *db;
86907  Db *aDb;
86908  int nDb;
86909  db = p->db;
86910  aDb = db->aDb;
86911  nDb = db->nDb;
86912  for(i=0; i<nDb; i++){
86913    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
86914      sqlite3BtreeLeave(aDb[i].pBt);
86915    }
86916  }
86917}
86918SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
86919  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
86920  vdbeLeave(p);
86921}
86922#endif
86923
86924#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
86925/*
86926** Print a single opcode.  This routine is used for debugging only.
86927*/
86928SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
86929  char *zP4;
86930  char *zCom;
86931  sqlite3 dummyDb;
86932  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
86933  if( pOut==0 ) pOut = stdout;
86934  sqlite3BeginBenignMalloc();
86935  dummyDb.mallocFailed = 1;
86936  zP4 = sqlite3VdbeDisplayP4(&dummyDb, pOp);
86937#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
86938  zCom = sqlite3VdbeDisplayComment(0, pOp, zP4);
86939#else
86940  zCom = 0;
86941#endif
86942  /* NB:  The sqlite3OpcodeName() function is implemented by code created
86943  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
86944  ** information from the vdbe.c source text */
86945  fprintf(pOut, zFormat1, pc,
86946      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3,
86947      zP4 ? zP4 : "", pOp->p5,
86948      zCom ? zCom : ""
86949  );
86950  fflush(pOut);
86951  sqlite3_free(zP4);
86952  sqlite3_free(zCom);
86953  sqlite3EndBenignMalloc();
86954}
86955#endif
86956
86957/*
86958** Initialize an array of N Mem element.
86959**
86960** This is a high-runner, so only those fields that really do need to
86961** be initialized are set.  The Mem structure is organized so that
86962** the fields that get initialized are nearby and hopefully on the same
86963** cache line.
86964**
86965**    Mem.flags = flags
86966**    Mem.db = db
86967**    Mem.szMalloc = 0
86968**
86969** All other fields of Mem can safely remain uninitialized for now.  They
86970** will be initialized before use.
86971*/
86972static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
86973  if( N>0 ){
86974    do{
86975      p->flags = flags;
86976      p->db = db;
86977      p->szMalloc = 0;
86978#ifdef SQLITE_DEBUG
86979      p->pScopyFrom = 0;
86980#endif
86981      p++;
86982    }while( (--N)>0 );
86983  }
86984}
86985
86986/*
86987** Release auxiliary memory held in an array of N Mem elements.
86988**
86989** After this routine returns, all Mem elements in the array will still
86990** be valid.  Those Mem elements that were not holding auxiliary resources
86991** will be unchanged.  Mem elements which had something freed will be
86992** set to MEM_Undefined.
86993*/
86994static void releaseMemArray(Mem *p, int N){
86995  if( p && N ){
86996    Mem *pEnd = &p[N];
86997    sqlite3 *db = p->db;
86998    if( db->pnBytesFreed ){
86999      do{
87000        if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
87001      }while( (++p)<pEnd );
87002      return;
87003    }
87004    do{
87005      assert( (&p[1])==pEnd || p[0].db==p[1].db );
87006      assert( sqlite3VdbeCheckMemInvariants(p) );
87007
87008      /* This block is really an inlined version of sqlite3VdbeMemRelease()
87009      ** that takes advantage of the fact that the memory cell value is
87010      ** being set to NULL after releasing any dynamic resources.
87011      **
87012      ** The justification for duplicating code is that according to
87013      ** callgrind, this causes a certain test case to hit the CPU 4.7
87014      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
87015      ** sqlite3MemRelease() were called from here. With -O2, this jumps
87016      ** to 6.6 percent. The test case is inserting 1000 rows into a table
87017      ** with no indexes using a single prepared INSERT statement, bind()
87018      ** and reset(). Inserts are grouped into a transaction.
87019      */
87020      testcase( p->flags & MEM_Agg );
87021      testcase( p->flags & MEM_Dyn );
87022      if( p->flags&(MEM_Agg|MEM_Dyn) ){
87023        testcase( (p->flags & MEM_Dyn)!=0 && p->xDel==sqlite3VdbeFrameMemDel );
87024        sqlite3VdbeMemRelease(p);
87025        p->flags = MEM_Undefined;
87026      }else if( p->szMalloc ){
87027        sqlite3DbNNFreeNN(db, p->zMalloc);
87028        p->szMalloc = 0;
87029        p->flags = MEM_Undefined;
87030      }
87031#ifdef SQLITE_DEBUG
87032      else{
87033        p->flags = MEM_Undefined;
87034      }
87035#endif
87036    }while( (++p)<pEnd );
87037  }
87038}
87039
87040#ifdef SQLITE_DEBUG
87041/*
87042** Verify that pFrame is a valid VdbeFrame pointer.  Return true if it is
87043** and false if something is wrong.
87044**
87045** This routine is intended for use inside of assert() statements only.
87046*/
87047SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){
87048  if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
87049  return 1;
87050}
87051#endif
87052
87053
87054/*
87055** This is a destructor on a Mem object (which is really an sqlite3_value)
87056** that deletes the Frame object that is attached to it as a blob.
87057**
87058** This routine does not delete the Frame right away.  It merely adds the
87059** frame to a list of frames to be deleted when the Vdbe halts.
87060*/
87061SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void *pArg){
87062  VdbeFrame *pFrame = (VdbeFrame*)pArg;
87063  assert( sqlite3VdbeFrameIsValid(pFrame) );
87064  pFrame->pParent = pFrame->v->pDelFrame;
87065  pFrame->v->pDelFrame = pFrame;
87066}
87067
87068#if defined(SQLITE_ENABLE_BYTECODE_VTAB) || !defined(SQLITE_OMIT_EXPLAIN)
87069/*
87070** Locate the next opcode to be displayed in EXPLAIN or EXPLAIN
87071** QUERY PLAN output.
87072**
87073** Return SQLITE_ROW on success.  Return SQLITE_DONE if there are no
87074** more opcodes to be displayed.
87075*/
87076SQLITE_PRIVATE int sqlite3VdbeNextOpcode(
87077  Vdbe *p,         /* The statement being explained */
87078  Mem *pSub,       /* Storage for keeping track of subprogram nesting */
87079  int eMode,       /* 0: normal.  1: EQP.  2:  TablesUsed */
87080  int *piPc,       /* IN/OUT: Current rowid.  Overwritten with next rowid */
87081  int *piAddr,     /* OUT: Write index into (*paOp)[] here */
87082  Op **paOp        /* OUT: Write the opcode array here */
87083){
87084  int nRow;                            /* Stop when row count reaches this */
87085  int nSub = 0;                        /* Number of sub-vdbes seen so far */
87086  SubProgram **apSub = 0;              /* Array of sub-vdbes */
87087  int i;                               /* Next instruction address */
87088  int rc = SQLITE_OK;                  /* Result code */
87089  Op *aOp = 0;                         /* Opcode array */
87090  int iPc;                             /* Rowid.  Copy of value in *piPc */
87091
87092  /* When the number of output rows reaches nRow, that means the
87093  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
87094  ** nRow is the sum of the number of rows in the main program, plus
87095  ** the sum of the number of rows in all trigger subprograms encountered
87096  ** so far.  The nRow value will increase as new trigger subprograms are
87097  ** encountered, but p->pc will eventually catch up to nRow.
87098  */
87099  nRow = p->nOp;
87100  if( pSub!=0 ){
87101    if( pSub->flags&MEM_Blob ){
87102      /* pSub is initiallly NULL.  It is initialized to a BLOB by
87103      ** the P4_SUBPROGRAM processing logic below */
87104      nSub = pSub->n/sizeof(Vdbe*);
87105      apSub = (SubProgram **)pSub->z;
87106    }
87107    for(i=0; i<nSub; i++){
87108      nRow += apSub[i]->nOp;
87109    }
87110  }
87111  iPc = *piPc;
87112  while(1){  /* Loop exits via break */
87113    i = iPc++;
87114    if( i>=nRow ){
87115      p->rc = SQLITE_OK;
87116      rc = SQLITE_DONE;
87117      break;
87118    }
87119    if( i<p->nOp ){
87120      /* The rowid is small enough that we are still in the
87121      ** main program. */
87122      aOp = p->aOp;
87123    }else{
87124      /* We are currently listing subprograms.  Figure out which one and
87125      ** pick up the appropriate opcode. */
87126      int j;
87127      i -= p->nOp;
87128      assert( apSub!=0 );
87129      assert( nSub>0 );
87130      for(j=0; i>=apSub[j]->nOp; j++){
87131        i -= apSub[j]->nOp;
87132        assert( i<apSub[j]->nOp || j+1<nSub );
87133      }
87134      aOp = apSub[j]->aOp;
87135    }
87136
87137    /* When an OP_Program opcode is encounter (the only opcode that has
87138    ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
87139    ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
87140    ** has not already been seen.
87141    */
87142    if( pSub!=0 && aOp[i].p4type==P4_SUBPROGRAM ){
87143      int nByte = (nSub+1)*sizeof(SubProgram*);
87144      int j;
87145      for(j=0; j<nSub; j++){
87146        if( apSub[j]==aOp[i].p4.pProgram ) break;
87147      }
87148      if( j==nSub ){
87149        p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
87150        if( p->rc!=SQLITE_OK ){
87151          rc = SQLITE_ERROR;
87152          break;
87153        }
87154        apSub = (SubProgram **)pSub->z;
87155        apSub[nSub++] = aOp[i].p4.pProgram;
87156        MemSetTypeFlag(pSub, MEM_Blob);
87157        pSub->n = nSub*sizeof(SubProgram*);
87158        nRow += aOp[i].p4.pProgram->nOp;
87159      }
87160    }
87161    if( eMode==0 ) break;
87162#ifdef SQLITE_ENABLE_BYTECODE_VTAB
87163    if( eMode==2 ){
87164      Op *pOp = aOp + i;
87165      if( pOp->opcode==OP_OpenRead ) break;
87166      if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;
87167      if( pOp->opcode==OP_ReopenIdx ) break;
87168    }else
87169#endif
87170    {
87171      assert( eMode==1 );
87172      if( aOp[i].opcode==OP_Explain ) break;
87173      if( aOp[i].opcode==OP_Init && iPc>1 ) break;
87174    }
87175  }
87176  *piPc = iPc;
87177  *piAddr = i;
87178  *paOp = aOp;
87179  return rc;
87180}
87181#endif /* SQLITE_ENABLE_BYTECODE_VTAB || !SQLITE_OMIT_EXPLAIN */
87182
87183
87184/*
87185** Delete a VdbeFrame object and its contents. VdbeFrame objects are
87186** allocated by the OP_Program opcode in sqlite3VdbeExec().
87187*/
87188SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
87189  int i;
87190  Mem *aMem = VdbeFrameMem(p);
87191  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
87192  assert( sqlite3VdbeFrameIsValid(p) );
87193  for(i=0; i<p->nChildCsr; i++){
87194    if( apCsr[i] ) sqlite3VdbeFreeCursorNN(p->v, apCsr[i]);
87195  }
87196  releaseMemArray(aMem, p->nChildMem);
87197  sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
87198  sqlite3DbFree(p->v->db, p);
87199}
87200
87201#ifndef SQLITE_OMIT_EXPLAIN
87202/*
87203** Give a listing of the program in the virtual machine.
87204**
87205** The interface is the same as sqlite3VdbeExec().  But instead of
87206** running the code, it invokes the callback once for each instruction.
87207** This feature is used to implement "EXPLAIN".
87208**
87209** When p->explain==1, each instruction is listed.  When
87210** p->explain==2, only OP_Explain instructions are listed and these
87211** are shown in a different format.  p->explain==2 is used to implement
87212** EXPLAIN QUERY PLAN.
87213** 2018-04-24:  In p->explain==2 mode, the OP_Init opcodes of triggers
87214** are also shown, so that the boundaries between the main program and
87215** each trigger are clear.
87216**
87217** When p->explain==1, first the main program is listed, then each of
87218** the trigger subprograms are listed one by one.
87219*/
87220SQLITE_PRIVATE int sqlite3VdbeList(
87221  Vdbe *p                   /* The VDBE */
87222){
87223  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
87224  sqlite3 *db = p->db;                 /* The database connection */
87225  int i;                               /* Loop counter */
87226  int rc = SQLITE_OK;                  /* Return code */
87227  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
87228  int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
87229  Op *aOp;                             /* Array of opcodes */
87230  Op *pOp;                             /* Current opcode */
87231
87232  assert( p->explain );
87233  assert( p->eVdbeState==VDBE_RUN_STATE );
87234  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
87235
87236  /* Even though this opcode does not use dynamic strings for
87237  ** the result, result columns may become dynamic if the user calls
87238  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
87239  */
87240  releaseMemArray(pMem, 8);
87241
87242  if( p->rc==SQLITE_NOMEM ){
87243    /* This happens if a malloc() inside a call to sqlite3_column_text() or
87244    ** sqlite3_column_text16() failed.  */
87245    sqlite3OomFault(db);
87246    return SQLITE_ERROR;
87247  }
87248
87249  if( bListSubprogs ){
87250    /* The first 8 memory cells are used for the result set.  So we will
87251    ** commandeer the 9th cell to use as storage for an array of pointers
87252    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
87253    ** cells.  */
87254    assert( p->nMem>9 );
87255    pSub = &p->aMem[9];
87256  }else{
87257    pSub = 0;
87258  }
87259
87260  /* Figure out which opcode is next to display */
87261  rc = sqlite3VdbeNextOpcode(p, pSub, p->explain==2, &p->pc, &i, &aOp);
87262
87263  if( rc==SQLITE_OK ){
87264    pOp = aOp + i;
87265    if( AtomicLoad(&db->u1.isInterrupted) ){
87266      p->rc = SQLITE_INTERRUPT;
87267      rc = SQLITE_ERROR;
87268      sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
87269    }else{
87270      char *zP4 = sqlite3VdbeDisplayP4(db, pOp);
87271      if( p->explain==2 ){
87272        sqlite3VdbeMemSetInt64(pMem, pOp->p1);
87273        sqlite3VdbeMemSetInt64(pMem+1, pOp->p2);
87274        sqlite3VdbeMemSetInt64(pMem+2, pOp->p3);
87275        sqlite3VdbeMemSetStr(pMem+3, zP4, -1, SQLITE_UTF8, sqlite3_free);
87276        assert( p->nResColumn==4 );
87277      }else{
87278        sqlite3VdbeMemSetInt64(pMem+0, i);
87279        sqlite3VdbeMemSetStr(pMem+1, (char*)sqlite3OpcodeName(pOp->opcode),
87280                             -1, SQLITE_UTF8, SQLITE_STATIC);
87281        sqlite3VdbeMemSetInt64(pMem+2, pOp->p1);
87282        sqlite3VdbeMemSetInt64(pMem+3, pOp->p2);
87283        sqlite3VdbeMemSetInt64(pMem+4, pOp->p3);
87284        /* pMem+5 for p4 is done last */
87285        sqlite3VdbeMemSetInt64(pMem+6, pOp->p5);
87286#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
87287        {
87288          char *zCom = sqlite3VdbeDisplayComment(db, pOp, zP4);
87289          sqlite3VdbeMemSetStr(pMem+7, zCom, -1, SQLITE_UTF8, sqlite3_free);
87290        }
87291#else
87292        sqlite3VdbeMemSetNull(pMem+7);
87293#endif
87294        sqlite3VdbeMemSetStr(pMem+5, zP4, -1, SQLITE_UTF8, sqlite3_free);
87295        assert( p->nResColumn==8 );
87296      }
87297      p->pResultRow = pMem;
87298      if( db->mallocFailed ){
87299        p->rc = SQLITE_NOMEM;
87300        rc = SQLITE_ERROR;
87301      }else{
87302        p->rc = SQLITE_OK;
87303        rc = SQLITE_ROW;
87304      }
87305    }
87306  }
87307  return rc;
87308}
87309#endif /* SQLITE_OMIT_EXPLAIN */
87310
87311#ifdef SQLITE_DEBUG
87312/*
87313** Print the SQL that was used to generate a VDBE program.
87314*/
87315SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
87316  const char *z = 0;
87317  if( p->zSql ){
87318    z = p->zSql;
87319  }else if( p->nOp>=1 ){
87320    const VdbeOp *pOp = &p->aOp[0];
87321    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
87322      z = pOp->p4.z;
87323      while( sqlite3Isspace(*z) ) z++;
87324    }
87325  }
87326  if( z ) printf("SQL: [%s]\n", z);
87327}
87328#endif
87329
87330#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
87331/*
87332** Print an IOTRACE message showing SQL content.
87333*/
87334SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
87335  int nOp = p->nOp;
87336  VdbeOp *pOp;
87337  if( sqlite3IoTrace==0 ) return;
87338  if( nOp<1 ) return;
87339  pOp = &p->aOp[0];
87340  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
87341    int i, j;
87342    char z[1000];
87343    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
87344    for(i=0; sqlite3Isspace(z[i]); i++){}
87345    for(j=0; z[i]; i++){
87346      if( sqlite3Isspace(z[i]) ){
87347        if( z[i-1]!=' ' ){
87348          z[j++] = ' ';
87349        }
87350      }else{
87351        z[j++] = z[i];
87352      }
87353    }
87354    z[j] = 0;
87355    sqlite3IoTrace("SQL %s\n", z);
87356  }
87357}
87358#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
87359
87360/* An instance of this object describes bulk memory available for use
87361** by subcomponents of a prepared statement.  Space is allocated out
87362** of a ReusableSpace object by the allocSpace() routine below.
87363*/
87364struct ReusableSpace {
87365  u8 *pSpace;            /* Available memory */
87366  sqlite3_int64 nFree;   /* Bytes of available memory */
87367  sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */
87368};
87369
87370/* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
87371** from the ReusableSpace object.  Return a pointer to the allocated
87372** memory on success.  If insufficient memory is available in the
87373** ReusableSpace object, increase the ReusableSpace.nNeeded
87374** value by the amount needed and return NULL.
87375**
87376** If pBuf is not initially NULL, that means that the memory has already
87377** been allocated by a prior call to this routine, so just return a copy
87378** of pBuf and leave ReusableSpace unchanged.
87379**
87380** This allocator is employed to repurpose unused slots at the end of the
87381** opcode array of prepared state for other memory needs of the prepared
87382** statement.
87383*/
87384static void *allocSpace(
87385  struct ReusableSpace *p,  /* Bulk memory available for allocation */
87386  void *pBuf,               /* Pointer to a prior allocation */
87387  sqlite3_int64 nByte       /* Bytes of memory needed. */
87388){
87389  assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
87390  if( pBuf==0 ){
87391    nByte = ROUND8P(nByte);
87392    if( nByte <= p->nFree ){
87393      p->nFree -= nByte;
87394      pBuf = &p->pSpace[p->nFree];
87395    }else{
87396      p->nNeeded += nByte;
87397    }
87398  }
87399  assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
87400  return pBuf;
87401}
87402
87403/*
87404** Rewind the VDBE back to the beginning in preparation for
87405** running it.
87406*/
87407SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
87408#if defined(SQLITE_DEBUG)
87409  int i;
87410#endif
87411  assert( p!=0 );
87412  assert( p->eVdbeState==VDBE_INIT_STATE
87413       || p->eVdbeState==VDBE_READY_STATE
87414       || p->eVdbeState==VDBE_HALT_STATE );
87415
87416  /* There should be at least one opcode.
87417  */
87418  assert( p->nOp>0 );
87419
87420  p->eVdbeState = VDBE_READY_STATE;
87421
87422#ifdef SQLITE_DEBUG
87423  for(i=0; i<p->nMem; i++){
87424    assert( p->aMem[i].db==p->db );
87425  }
87426#endif
87427  p->pc = -1;
87428  p->rc = SQLITE_OK;
87429  p->errorAction = OE_Abort;
87430  p->nChange = 0;
87431  p->cacheCtr = 1;
87432  p->minWriteFileFormat = 255;
87433  p->iStatement = 0;
87434  p->nFkConstraint = 0;
87435#ifdef VDBE_PROFILE
87436  for(i=0; i<p->nOp; i++){
87437    p->aOp[i].nExec = 0;
87438    p->aOp[i].nCycle = 0;
87439  }
87440#endif
87441}
87442
87443/*
87444** Prepare a virtual machine for execution for the first time after
87445** creating the virtual machine.  This involves things such
87446** as allocating registers and initializing the program counter.
87447** After the VDBE has be prepped, it can be executed by one or more
87448** calls to sqlite3VdbeExec().
87449**
87450** This function may be called exactly once on each virtual machine.
87451** After this routine is called the VM has been "packaged" and is ready
87452** to run.  After this routine is called, further calls to
87453** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
87454** the Vdbe from the Parse object that helped generate it so that the
87455** the Vdbe becomes an independent entity and the Parse object can be
87456** destroyed.
87457**
87458** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
87459** to its initial state after it has been run.
87460*/
87461SQLITE_PRIVATE void sqlite3VdbeMakeReady(
87462  Vdbe *p,                       /* The VDBE */
87463  Parse *pParse                  /* Parsing context */
87464){
87465  sqlite3 *db;                   /* The database connection */
87466  int nVar;                      /* Number of parameters */
87467  int nMem;                      /* Number of VM memory registers */
87468  int nCursor;                   /* Number of cursors required */
87469  int nArg;                      /* Number of arguments in subprograms */
87470  int n;                         /* Loop counter */
87471  struct ReusableSpace x;        /* Reusable bulk memory */
87472
87473  assert( p!=0 );
87474  assert( p->nOp>0 );
87475  assert( pParse!=0 );
87476  assert( p->eVdbeState==VDBE_INIT_STATE );
87477  assert( pParse==p->pParse );
87478  p->pVList = pParse->pVList;
87479  pParse->pVList =  0;
87480  db = p->db;
87481  assert( db->mallocFailed==0 );
87482  nVar = pParse->nVar;
87483  nMem = pParse->nMem;
87484  nCursor = pParse->nTab;
87485  nArg = pParse->nMaxArg;
87486
87487  /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
87488  ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
87489  ** space at the end of aMem[] for cursors 1 and greater.
87490  ** See also: allocateCursor().
87491  */
87492  nMem += nCursor;
87493  if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
87494
87495  /* Figure out how much reusable memory is available at the end of the
87496  ** opcode array.  This extra memory will be reallocated for other elements
87497  ** of the prepared statement.
87498  */
87499  n = ROUND8P(sizeof(Op)*p->nOp);             /* Bytes of opcode memory used */
87500  x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
87501  assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
87502  x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */
87503  assert( x.nFree>=0 );
87504  assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
87505
87506  resolveP2Values(p, &nArg);
87507  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
87508  if( pParse->explain ){
87509    if( nMem<10 ) nMem = 10;
87510    p->explain = pParse->explain;
87511    p->nResColumn = 12 - 4*p->explain;
87512  }
87513  p->expired = 0;
87514
87515  /* Memory for registers, parameters, cursor, etc, is allocated in one or two
87516  ** passes.  On the first pass, we try to reuse unused memory at the
87517  ** end of the opcode array.  If we are unable to satisfy all memory
87518  ** requirements by reusing the opcode array tail, then the second
87519  ** pass will fill in the remainder using a fresh memory allocation.
87520  **
87521  ** This two-pass approach that reuses as much memory as possible from
87522  ** the leftover memory at the end of the opcode array.  This can significantly
87523  ** reduce the amount of memory held by a prepared statement.
87524  */
87525  x.nNeeded = 0;
87526  p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
87527  p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
87528  p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
87529  p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
87530  if( x.nNeeded ){
87531    x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
87532    x.nFree = x.nNeeded;
87533    if( !db->mallocFailed ){
87534      p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
87535      p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
87536      p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
87537      p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
87538    }
87539  }
87540
87541  if( db->mallocFailed ){
87542    p->nVar = 0;
87543    p->nCursor = 0;
87544    p->nMem = 0;
87545  }else{
87546    p->nCursor = nCursor;
87547    p->nVar = (ynVar)nVar;
87548    initMemArray(p->aVar, nVar, db, MEM_Null);
87549    p->nMem = nMem;
87550    initMemArray(p->aMem, nMem, db, MEM_Undefined);
87551    memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
87552  }
87553  sqlite3VdbeRewind(p);
87554}
87555
87556/*
87557** Close a VDBE cursor and release all the resources that cursor
87558** happens to hold.
87559*/
87560SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
87561  if( pCx ) sqlite3VdbeFreeCursorNN(p,pCx);
87562}
87563static SQLITE_NOINLINE void freeCursorWithCache(Vdbe *p, VdbeCursor *pCx){
87564  VdbeTxtBlbCache *pCache = pCx->pCache;
87565  assert( pCx->colCache );
87566  pCx->colCache = 0;
87567  pCx->pCache = 0;
87568  if( pCache->pCValue ){
87569    sqlite3RCStrUnref(pCache->pCValue);
87570    pCache->pCValue = 0;
87571  }
87572  sqlite3DbFree(p->db, pCache);
87573  sqlite3VdbeFreeCursorNN(p, pCx);
87574}
87575SQLITE_PRIVATE void sqlite3VdbeFreeCursorNN(Vdbe *p, VdbeCursor *pCx){
87576  if( pCx->colCache ){
87577    freeCursorWithCache(p, pCx);
87578    return;
87579  }
87580  switch( pCx->eCurType ){
87581    case CURTYPE_SORTER: {
87582      sqlite3VdbeSorterClose(p->db, pCx);
87583      break;
87584    }
87585    case CURTYPE_BTREE: {
87586      assert( pCx->uc.pCursor!=0 );
87587      sqlite3BtreeCloseCursor(pCx->uc.pCursor);
87588      break;
87589    }
87590#ifndef SQLITE_OMIT_VIRTUALTABLE
87591    case CURTYPE_VTAB: {
87592      sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
87593      const sqlite3_module *pModule = pVCur->pVtab->pModule;
87594      assert( pVCur->pVtab->nRef>0 );
87595      pVCur->pVtab->nRef--;
87596      pModule->xClose(pVCur);
87597      break;
87598    }
87599#endif
87600  }
87601}
87602
87603/*
87604** Close all cursors in the current frame.
87605*/
87606static void closeCursorsInFrame(Vdbe *p){
87607  int i;
87608  for(i=0; i<p->nCursor; i++){
87609    VdbeCursor *pC = p->apCsr[i];
87610    if( pC ){
87611      sqlite3VdbeFreeCursorNN(p, pC);
87612      p->apCsr[i] = 0;
87613    }
87614  }
87615}
87616
87617/*
87618** Copy the values stored in the VdbeFrame structure to its Vdbe. This
87619** is used, for example, when a trigger sub-program is halted to restore
87620** control to the main program.
87621*/
87622SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
87623  Vdbe *v = pFrame->v;
87624  closeCursorsInFrame(v);
87625  v->aOp = pFrame->aOp;
87626  v->nOp = pFrame->nOp;
87627  v->aMem = pFrame->aMem;
87628  v->nMem = pFrame->nMem;
87629  v->apCsr = pFrame->apCsr;
87630  v->nCursor = pFrame->nCursor;
87631  v->db->lastRowid = pFrame->lastRowid;
87632  v->nChange = pFrame->nChange;
87633  v->db->nChange = pFrame->nDbChange;
87634  sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
87635  v->pAuxData = pFrame->pAuxData;
87636  pFrame->pAuxData = 0;
87637  return pFrame->pc;
87638}
87639
87640/*
87641** Close all cursors.
87642**
87643** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
87644** cell array. This is necessary as the memory cell array may contain
87645** pointers to VdbeFrame objects, which may in turn contain pointers to
87646** open cursors.
87647*/
87648static void closeAllCursors(Vdbe *p){
87649  if( p->pFrame ){
87650    VdbeFrame *pFrame;
87651    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
87652    sqlite3VdbeFrameRestore(pFrame);
87653    p->pFrame = 0;
87654    p->nFrame = 0;
87655  }
87656  assert( p->nFrame==0 );
87657  closeCursorsInFrame(p);
87658  releaseMemArray(p->aMem, p->nMem);
87659  while( p->pDelFrame ){
87660    VdbeFrame *pDel = p->pDelFrame;
87661    p->pDelFrame = pDel->pParent;
87662    sqlite3VdbeFrameDelete(pDel);
87663  }
87664
87665  /* Delete any auxdata allocations made by the VM */
87666  if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
87667  assert( p->pAuxData==0 );
87668}
87669
87670/*
87671** Set the number of result columns that will be returned by this SQL
87672** statement. This is now set at compile time, rather than during
87673** execution of the vdbe program so that sqlite3_column_count() can
87674** be called on an SQL statement before sqlite3_step().
87675*/
87676SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
87677  int n;
87678  sqlite3 *db = p->db;
87679
87680  if( p->nResAlloc ){
87681    releaseMemArray(p->aColName, p->nResAlloc*COLNAME_N);
87682    sqlite3DbFree(db, p->aColName);
87683  }
87684  n = nResColumn*COLNAME_N;
87685  p->nResColumn = p->nResAlloc = (u16)nResColumn;
87686  p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
87687  if( p->aColName==0 ) return;
87688  initMemArray(p->aColName, n, db, MEM_Null);
87689}
87690
87691/*
87692** Set the name of the idx'th column to be returned by the SQL statement.
87693** zName must be a pointer to a nul terminated string.
87694**
87695** This call must be made after a call to sqlite3VdbeSetNumCols().
87696**
87697** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
87698** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
87699** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
87700*/
87701SQLITE_PRIVATE int sqlite3VdbeSetColName(
87702  Vdbe *p,                         /* Vdbe being configured */
87703  int idx,                         /* Index of column zName applies to */
87704  int var,                         /* One of the COLNAME_* constants */
87705  const char *zName,               /* Pointer to buffer containing name */
87706  void (*xDel)(void*)              /* Memory management strategy for zName */
87707){
87708  int rc;
87709  Mem *pColName;
87710  assert( idx<p->nResAlloc );
87711  assert( var<COLNAME_N );
87712  if( p->db->mallocFailed ){
87713    assert( !zName || xDel!=SQLITE_DYNAMIC );
87714    return SQLITE_NOMEM_BKPT;
87715  }
87716  assert( p->aColName!=0 );
87717  pColName = &(p->aColName[idx+var*p->nResAlloc]);
87718  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
87719  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
87720  return rc;
87721}
87722
87723/*
87724** A read or write transaction may or may not be active on database handle
87725** db. If a transaction is active, commit it. If there is a
87726** write-transaction spanning more than one database file, this routine
87727** takes care of the super-journal trickery.
87728*/
87729static int vdbeCommit(sqlite3 *db, Vdbe *p){
87730  int i;
87731  int nTrans = 0;  /* Number of databases with an active write-transaction
87732                   ** that are candidates for a two-phase commit using a
87733                   ** super-journal */
87734  int rc = SQLITE_OK;
87735  int needXcommit = 0;
87736
87737#ifdef SQLITE_OMIT_VIRTUALTABLE
87738  /* With this option, sqlite3VtabSync() is defined to be simply
87739  ** SQLITE_OK so p is not used.
87740  */
87741  UNUSED_PARAMETER(p);
87742#endif
87743
87744  /* Before doing anything else, call the xSync() callback for any
87745  ** virtual module tables written in this transaction. This has to
87746  ** be done before determining whether a super-journal file is
87747  ** required, as an xSync() callback may add an attached database
87748  ** to the transaction.
87749  */
87750  rc = sqlite3VtabSync(db, p);
87751
87752  /* This loop determines (a) if the commit hook should be invoked and
87753  ** (b) how many database files have open write transactions, not
87754  ** including the temp database. (b) is important because if more than
87755  ** one database file has an open write transaction, a super-journal
87756  ** file is required for an atomic commit.
87757  */
87758  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
87759    Btree *pBt = db->aDb[i].pBt;
87760    if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
87761      /* Whether or not a database might need a super-journal depends upon
87762      ** its journal mode (among other things).  This matrix determines which
87763      ** journal modes use a super-journal and which do not */
87764      static const u8 aMJNeeded[] = {
87765        /* DELETE   */  1,
87766        /* PERSIST   */ 1,
87767        /* OFF       */ 0,
87768        /* TRUNCATE  */ 1,
87769        /* MEMORY    */ 0,
87770        /* WAL       */ 0
87771      };
87772      Pager *pPager;   /* Pager associated with pBt */
87773      needXcommit = 1;
87774      sqlite3BtreeEnter(pBt);
87775      pPager = sqlite3BtreePager(pBt);
87776      if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
87777       && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
87778       && sqlite3PagerIsMemdb(pPager)==0
87779      ){
87780        assert( i!=1 );
87781        nTrans++;
87782      }
87783      rc = sqlite3PagerExclusiveLock(pPager);
87784      sqlite3BtreeLeave(pBt);
87785    }
87786  }
87787  if( rc!=SQLITE_OK ){
87788    return rc;
87789  }
87790
87791  /* If there are any write-transactions at all, invoke the commit hook */
87792  if( needXcommit && db->xCommitCallback ){
87793    rc = db->xCommitCallback(db->pCommitArg);
87794    if( rc ){
87795      return SQLITE_CONSTRAINT_COMMITHOOK;
87796    }
87797  }
87798
87799  /* The simple case - no more than one database file (not counting the
87800  ** TEMP database) has a transaction active.   There is no need for the
87801  ** super-journal.
87802  **
87803  ** If the return value of sqlite3BtreeGetFilename() is a zero length
87804  ** string, it means the main database is :memory: or a temp file.  In
87805  ** that case we do not support atomic multi-file commits, so use the
87806  ** simple case then too.
87807  */
87808  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
87809   || nTrans<=1
87810  ){
87811    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
87812      Btree *pBt = db->aDb[i].pBt;
87813      if( pBt ){
87814        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
87815      }
87816    }
87817
87818    /* Do the commit only if all databases successfully complete phase 1.
87819    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
87820    ** IO error while deleting or truncating a journal file. It is unlikely,
87821    ** but could happen. In this case abandon processing and return the error.
87822    */
87823    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
87824      Btree *pBt = db->aDb[i].pBt;
87825      if( pBt ){
87826        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
87827      }
87828    }
87829    if( rc==SQLITE_OK ){
87830      sqlite3VtabCommit(db);
87831    }
87832  }
87833
87834  /* The complex case - There is a multi-file write-transaction active.
87835  ** This requires a super-journal file to ensure the transaction is
87836  ** committed atomically.
87837  */
87838#ifndef SQLITE_OMIT_DISKIO
87839  else{
87840    sqlite3_vfs *pVfs = db->pVfs;
87841    char *zSuper = 0;   /* File-name for the super-journal */
87842    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
87843    sqlite3_file *pSuperJrnl = 0;
87844    i64 offset = 0;
87845    int res;
87846    int retryCount = 0;
87847    int nMainFile;
87848
87849    /* Select a super-journal file name */
87850    nMainFile = sqlite3Strlen30(zMainFile);
87851    zSuper = sqlite3MPrintf(db, "%.4c%s%.16c", 0,zMainFile,0);
87852    if( zSuper==0 ) return SQLITE_NOMEM_BKPT;
87853    zSuper += 4;
87854    do {
87855      u32 iRandom;
87856      if( retryCount ){
87857        if( retryCount>100 ){
87858          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zSuper);
87859          sqlite3OsDelete(pVfs, zSuper, 0);
87860          break;
87861        }else if( retryCount==1 ){
87862          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zSuper);
87863        }
87864      }
87865      retryCount++;
87866      sqlite3_randomness(sizeof(iRandom), &iRandom);
87867      sqlite3_snprintf(13, &zSuper[nMainFile], "-mj%06X9%02X",
87868                               (iRandom>>8)&0xffffff, iRandom&0xff);
87869      /* The antipenultimate character of the super-journal name must
87870      ** be "9" to avoid name collisions when using 8+3 filenames. */
87871      assert( zSuper[sqlite3Strlen30(zSuper)-3]=='9' );
87872      sqlite3FileSuffix3(zMainFile, zSuper);
87873      rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
87874    }while( rc==SQLITE_OK && res );
87875    if( rc==SQLITE_OK ){
87876      /* Open the super-journal. */
87877      rc = sqlite3OsOpenMalloc(pVfs, zSuper, &pSuperJrnl,
87878          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
87879          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_SUPER_JOURNAL, 0
87880      );
87881    }
87882    if( rc!=SQLITE_OK ){
87883      sqlite3DbFree(db, zSuper-4);
87884      return rc;
87885    }
87886
87887    /* Write the name of each database file in the transaction into the new
87888    ** super-journal file. If an error occurs at this point close
87889    ** and delete the super-journal file. All the individual journal files
87890    ** still have 'null' as the super-journal pointer, so they will roll
87891    ** back independently if a failure occurs.
87892    */
87893    for(i=0; i<db->nDb; i++){
87894      Btree *pBt = db->aDb[i].pBt;
87895      if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
87896        char const *zFile = sqlite3BtreeGetJournalname(pBt);
87897        if( zFile==0 ){
87898          continue;  /* Ignore TEMP and :memory: databases */
87899        }
87900        assert( zFile[0]!=0 );
87901        rc = sqlite3OsWrite(pSuperJrnl, zFile, sqlite3Strlen30(zFile)+1,offset);
87902        offset += sqlite3Strlen30(zFile)+1;
87903        if( rc!=SQLITE_OK ){
87904          sqlite3OsCloseFree(pSuperJrnl);
87905          sqlite3OsDelete(pVfs, zSuper, 0);
87906          sqlite3DbFree(db, zSuper-4);
87907          return rc;
87908        }
87909      }
87910    }
87911
87912    /* Sync the super-journal file. If the IOCAP_SEQUENTIAL device
87913    ** flag is set this is not required.
87914    */
87915    if( 0==(sqlite3OsDeviceCharacteristics(pSuperJrnl)&SQLITE_IOCAP_SEQUENTIAL)
87916     && SQLITE_OK!=(rc = sqlite3OsSync(pSuperJrnl, SQLITE_SYNC_NORMAL))
87917    ){
87918      sqlite3OsCloseFree(pSuperJrnl);
87919      sqlite3OsDelete(pVfs, zSuper, 0);
87920      sqlite3DbFree(db, zSuper-4);
87921      return rc;
87922    }
87923
87924    /* Sync all the db files involved in the transaction. The same call
87925    ** sets the super-journal pointer in each individual journal. If
87926    ** an error occurs here, do not delete the super-journal file.
87927    **
87928    ** If the error occurs during the first call to
87929    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
87930    ** super-journal file will be orphaned. But we cannot delete it,
87931    ** in case the super-journal file name was written into the journal
87932    ** file before the failure occurred.
87933    */
87934    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
87935      Btree *pBt = db->aDb[i].pBt;
87936      if( pBt ){
87937        rc = sqlite3BtreeCommitPhaseOne(pBt, zSuper);
87938      }
87939    }
87940    sqlite3OsCloseFree(pSuperJrnl);
87941    assert( rc!=SQLITE_BUSY );
87942    if( rc!=SQLITE_OK ){
87943      sqlite3DbFree(db, zSuper-4);
87944      return rc;
87945    }
87946
87947    /* Delete the super-journal file. This commits the transaction. After
87948    ** doing this the directory is synced again before any individual
87949    ** transaction files are deleted.
87950    */
87951    rc = sqlite3OsDelete(pVfs, zSuper, 1);
87952    sqlite3DbFree(db, zSuper-4);
87953    zSuper = 0;
87954    if( rc ){
87955      return rc;
87956    }
87957
87958    /* All files and directories have already been synced, so the following
87959    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
87960    ** deleting or truncating journals. If something goes wrong while
87961    ** this is happening we don't really care. The integrity of the
87962    ** transaction is already guaranteed, but some stray 'cold' journals
87963    ** may be lying around. Returning an error code won't help matters.
87964    */
87965    disable_simulated_io_errors();
87966    sqlite3BeginBenignMalloc();
87967    for(i=0; i<db->nDb; i++){
87968      Btree *pBt = db->aDb[i].pBt;
87969      if( pBt ){
87970        sqlite3BtreeCommitPhaseTwo(pBt, 1);
87971      }
87972    }
87973    sqlite3EndBenignMalloc();
87974    enable_simulated_io_errors();
87975
87976    sqlite3VtabCommit(db);
87977  }
87978#endif
87979
87980  return rc;
87981}
87982
87983/*
87984** This routine checks that the sqlite3.nVdbeActive count variable
87985** matches the number of vdbe's in the list sqlite3.pVdbe that are
87986** currently active. An assertion fails if the two counts do not match.
87987** This is an internal self-check only - it is not an essential processing
87988** step.
87989**
87990** This is a no-op if NDEBUG is defined.
87991*/
87992#ifndef NDEBUG
87993static void checkActiveVdbeCnt(sqlite3 *db){
87994  Vdbe *p;
87995  int cnt = 0;
87996  int nWrite = 0;
87997  int nRead = 0;
87998  p = db->pVdbe;
87999  while( p ){
88000    if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
88001      cnt++;
88002      if( p->readOnly==0 ) nWrite++;
88003      if( p->bIsReader ) nRead++;
88004    }
88005    p = p->pVNext;
88006  }
88007  assert( cnt==db->nVdbeActive );
88008  assert( nWrite==db->nVdbeWrite );
88009  assert( nRead==db->nVdbeRead );
88010}
88011#else
88012#define checkActiveVdbeCnt(x)
88013#endif
88014
88015/*
88016** If the Vdbe passed as the first argument opened a statement-transaction,
88017** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
88018** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
88019** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
88020** statement transaction is committed.
88021**
88022** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
88023** Otherwise SQLITE_OK.
88024*/
88025static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
88026  sqlite3 *const db = p->db;
88027  int rc = SQLITE_OK;
88028  int i;
88029  const int iSavepoint = p->iStatement-1;
88030
88031  assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
88032  assert( db->nStatement>0 );
88033  assert( p->iStatement==(db->nStatement+db->nSavepoint) );
88034
88035  for(i=0; i<db->nDb; i++){
88036    int rc2 = SQLITE_OK;
88037    Btree *pBt = db->aDb[i].pBt;
88038    if( pBt ){
88039      if( eOp==SAVEPOINT_ROLLBACK ){
88040        rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
88041      }
88042      if( rc2==SQLITE_OK ){
88043        rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
88044      }
88045      if( rc==SQLITE_OK ){
88046        rc = rc2;
88047      }
88048    }
88049  }
88050  db->nStatement--;
88051  p->iStatement = 0;
88052
88053  if( rc==SQLITE_OK ){
88054    if( eOp==SAVEPOINT_ROLLBACK ){
88055      rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
88056    }
88057    if( rc==SQLITE_OK ){
88058      rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
88059    }
88060  }
88061
88062  /* If the statement transaction is being rolled back, also restore the
88063  ** database handles deferred constraint counter to the value it had when
88064  ** the statement transaction was opened.  */
88065  if( eOp==SAVEPOINT_ROLLBACK ){
88066    db->nDeferredCons = p->nStmtDefCons;
88067    db->nDeferredImmCons = p->nStmtDefImmCons;
88068  }
88069  return rc;
88070}
88071SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
88072  if( p->db->nStatement && p->iStatement ){
88073    return vdbeCloseStatement(p, eOp);
88074  }
88075  return SQLITE_OK;
88076}
88077
88078
88079/*
88080** This function is called when a transaction opened by the database
88081** handle associated with the VM passed as an argument is about to be
88082** committed. If there are outstanding deferred foreign key constraint
88083** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
88084**
88085** If there are outstanding FK violations and this function returns
88086** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
88087** and write an error message to it. Then return SQLITE_ERROR.
88088*/
88089#ifndef SQLITE_OMIT_FOREIGN_KEY
88090SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
88091  sqlite3 *db = p->db;
88092  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
88093   || (!deferred && p->nFkConstraint>0)
88094  ){
88095    p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
88096    p->errorAction = OE_Abort;
88097    sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
88098    if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ) return SQLITE_ERROR;
88099    return SQLITE_CONSTRAINT_FOREIGNKEY;
88100  }
88101  return SQLITE_OK;
88102}
88103#endif
88104
88105/*
88106** This routine is called the when a VDBE tries to halt.  If the VDBE
88107** has made changes and is in autocommit mode, then commit those
88108** changes.  If a rollback is needed, then do the rollback.
88109**
88110** This routine is the only way to move the sqlite3eOpenState of a VM from
88111** SQLITE_STATE_RUN to SQLITE_STATE_HALT.  It is harmless to
88112** call this on a VM that is in the SQLITE_STATE_HALT state.
88113**
88114** Return an error code.  If the commit could not complete because of
88115** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
88116** means the close did not happen and needs to be repeated.
88117*/
88118SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
88119  int rc;                         /* Used to store transient return codes */
88120  sqlite3 *db = p->db;
88121
88122  /* This function contains the logic that determines if a statement or
88123  ** transaction will be committed or rolled back as a result of the
88124  ** execution of this virtual machine.
88125  **
88126  ** If any of the following errors occur:
88127  **
88128  **     SQLITE_NOMEM
88129  **     SQLITE_IOERR
88130  **     SQLITE_FULL
88131  **     SQLITE_INTERRUPT
88132  **
88133  ** Then the internal cache might have been left in an inconsistent
88134  ** state.  We need to rollback the statement transaction, if there is
88135  ** one, or the complete transaction if there is no statement transaction.
88136  */
88137
88138  assert( p->eVdbeState==VDBE_RUN_STATE );
88139  if( db->mallocFailed ){
88140    p->rc = SQLITE_NOMEM_BKPT;
88141  }
88142  closeAllCursors(p);
88143  checkActiveVdbeCnt(db);
88144
88145  /* No commit or rollback needed if the program never started or if the
88146  ** SQL statement does not read or write a database file.  */
88147  if( p->bIsReader ){
88148    int mrc;   /* Primary error code from p->rc */
88149    int eStatementOp = 0;
88150    int isSpecialError;            /* Set to true if a 'special' error */
88151
88152    /* Lock all btrees used by the statement */
88153    sqlite3VdbeEnter(p);
88154
88155    /* Check for one of the special errors */
88156    if( p->rc ){
88157      mrc = p->rc & 0xff;
88158      isSpecialError = mrc==SQLITE_NOMEM
88159                    || mrc==SQLITE_IOERR
88160                    || mrc==SQLITE_INTERRUPT
88161                    || mrc==SQLITE_FULL;
88162    }else{
88163      mrc = isSpecialError = 0;
88164    }
88165    if( isSpecialError ){
88166      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
88167      ** no rollback is necessary. Otherwise, at least a savepoint
88168      ** transaction must be rolled back to restore the database to a
88169      ** consistent state.
88170      **
88171      ** Even if the statement is read-only, it is important to perform
88172      ** a statement or transaction rollback operation. If the error
88173      ** occurred while writing to the journal, sub-journal or database
88174      ** file as part of an effort to free up cache space (see function
88175      ** pagerStress() in pager.c), the rollback is required to restore
88176      ** the pager to a consistent state.
88177      */
88178      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
88179        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
88180          eStatementOp = SAVEPOINT_ROLLBACK;
88181        }else{
88182          /* We are forced to roll back the active transaction. Before doing
88183          ** so, abort any other statements this handle currently has active.
88184          */
88185          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
88186          sqlite3CloseSavepoints(db);
88187          db->autoCommit = 1;
88188          p->nChange = 0;
88189        }
88190      }
88191    }
88192
88193    /* Check for immediate foreign key violations. */
88194    if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
88195      (void)sqlite3VdbeCheckFk(p, 0);
88196    }
88197
88198    /* If the auto-commit flag is set and this is the only active writer
88199    ** VM, then we do either a commit or rollback of the current transaction.
88200    **
88201    ** Note: This block also runs if one of the special errors handled
88202    ** above has occurred.
88203    */
88204    if( !sqlite3VtabInSync(db)
88205     && db->autoCommit
88206     && db->nVdbeWrite==(p->readOnly==0)
88207    ){
88208      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
88209        rc = sqlite3VdbeCheckFk(p, 1);
88210        if( rc!=SQLITE_OK ){
88211          if( NEVER(p->readOnly) ){
88212            sqlite3VdbeLeave(p);
88213            return SQLITE_ERROR;
88214          }
88215          rc = SQLITE_CONSTRAINT_FOREIGNKEY;
88216        }else if( db->flags & SQLITE_CorruptRdOnly ){
88217          rc = SQLITE_CORRUPT;
88218          db->flags &= ~SQLITE_CorruptRdOnly;
88219        }else{
88220          /* The auto-commit flag is true, the vdbe program was successful
88221          ** or hit an 'OR FAIL' constraint and there are no deferred foreign
88222          ** key constraints to hold up the transaction. This means a commit
88223          ** is required. */
88224          rc = vdbeCommit(db, p);
88225        }
88226        if( rc==SQLITE_BUSY && p->readOnly ){
88227          sqlite3VdbeLeave(p);
88228          return SQLITE_BUSY;
88229        }else if( rc!=SQLITE_OK ){
88230          sqlite3SystemError(db, rc);
88231          p->rc = rc;
88232          sqlite3RollbackAll(db, SQLITE_OK);
88233          p->nChange = 0;
88234        }else{
88235          db->nDeferredCons = 0;
88236          db->nDeferredImmCons = 0;
88237          db->flags &= ~(u64)SQLITE_DeferFKs;
88238          sqlite3CommitInternalChanges(db);
88239        }
88240      }else if( p->rc==SQLITE_SCHEMA && db->nVdbeActive>1 ){
88241        p->nChange = 0;
88242      }else{
88243        sqlite3RollbackAll(db, SQLITE_OK);
88244        p->nChange = 0;
88245      }
88246      db->nStatement = 0;
88247    }else if( eStatementOp==0 ){
88248      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
88249        eStatementOp = SAVEPOINT_RELEASE;
88250      }else if( p->errorAction==OE_Abort ){
88251        eStatementOp = SAVEPOINT_ROLLBACK;
88252      }else{
88253        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
88254        sqlite3CloseSavepoints(db);
88255        db->autoCommit = 1;
88256        p->nChange = 0;
88257      }
88258    }
88259
88260    /* If eStatementOp is non-zero, then a statement transaction needs to
88261    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
88262    ** do so. If this operation returns an error, and the current statement
88263    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
88264    ** current statement error code.
88265    */
88266    if( eStatementOp ){
88267      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
88268      if( rc ){
88269        if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
88270          p->rc = rc;
88271          sqlite3DbFree(db, p->zErrMsg);
88272          p->zErrMsg = 0;
88273        }
88274        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
88275        sqlite3CloseSavepoints(db);
88276        db->autoCommit = 1;
88277        p->nChange = 0;
88278      }
88279    }
88280
88281    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
88282    ** has been rolled back, update the database connection change-counter.
88283    */
88284    if( p->changeCntOn ){
88285      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
88286        sqlite3VdbeSetChanges(db, p->nChange);
88287      }else{
88288        sqlite3VdbeSetChanges(db, 0);
88289      }
88290      p->nChange = 0;
88291    }
88292
88293    /* Release the locks */
88294    sqlite3VdbeLeave(p);
88295  }
88296
88297  /* We have successfully halted and closed the VM.  Record this fact. */
88298  db->nVdbeActive--;
88299  if( !p->readOnly ) db->nVdbeWrite--;
88300  if( p->bIsReader ) db->nVdbeRead--;
88301  assert( db->nVdbeActive>=db->nVdbeRead );
88302  assert( db->nVdbeRead>=db->nVdbeWrite );
88303  assert( db->nVdbeWrite>=0 );
88304  p->eVdbeState = VDBE_HALT_STATE;
88305  checkActiveVdbeCnt(db);
88306  if( db->mallocFailed ){
88307    p->rc = SQLITE_NOMEM_BKPT;
88308  }
88309
88310  /* If the auto-commit flag is set to true, then any locks that were held
88311  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
88312  ** to invoke any required unlock-notify callbacks.
88313  */
88314  if( db->autoCommit ){
88315    sqlite3ConnectionUnlocked(db);
88316  }
88317
88318  assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
88319  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
88320}
88321
88322
88323/*
88324** Each VDBE holds the result of the most recent sqlite3_step() call
88325** in p->rc.  This routine sets that result back to SQLITE_OK.
88326*/
88327SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
88328  p->rc = SQLITE_OK;
88329}
88330
88331/*
88332** Copy the error code and error message belonging to the VDBE passed
88333** as the first argument to its database handle (so that they will be
88334** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
88335**
88336** This function does not clear the VDBE error code or message, just
88337** copies them to the database handle.
88338*/
88339SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
88340  sqlite3 *db = p->db;
88341  int rc = p->rc;
88342  if( p->zErrMsg ){
88343    db->bBenignMalloc++;
88344    sqlite3BeginBenignMalloc();
88345    if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
88346    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
88347    sqlite3EndBenignMalloc();
88348    db->bBenignMalloc--;
88349  }else if( db->pErr ){
88350    sqlite3ValueSetNull(db->pErr);
88351  }
88352  db->errCode = rc;
88353  db->errByteOffset = -1;
88354  return rc;
88355}
88356
88357#ifdef SQLITE_ENABLE_SQLLOG
88358/*
88359** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
88360** invoke it.
88361*/
88362static void vdbeInvokeSqllog(Vdbe *v){
88363  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
88364    char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
88365    assert( v->db->init.busy==0 );
88366    if( zExpanded ){
88367      sqlite3GlobalConfig.xSqllog(
88368          sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
88369      );
88370      sqlite3DbFree(v->db, zExpanded);
88371    }
88372  }
88373}
88374#else
88375# define vdbeInvokeSqllog(x)
88376#endif
88377
88378/*
88379** Clean up a VDBE after execution but do not delete the VDBE just yet.
88380** Write any error messages into *pzErrMsg.  Return the result code.
88381**
88382** After this routine is run, the VDBE should be ready to be executed
88383** again.
88384**
88385** To look at it another way, this routine resets the state of the
88386** virtual machine from VDBE_RUN_STATE or VDBE_HALT_STATE back to
88387** VDBE_READY_STATE.
88388*/
88389SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
88390#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
88391  int i;
88392#endif
88393
88394  sqlite3 *db;
88395  db = p->db;
88396
88397  /* If the VM did not run to completion or if it encountered an
88398  ** error, then it might not have been halted properly.  So halt
88399  ** it now.
88400  */
88401  if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
88402
88403  /* If the VDBE has been run even partially, then transfer the error code
88404  ** and error message from the VDBE into the main database structure.  But
88405  ** if the VDBE has just been set to run but has not actually executed any
88406  ** instructions yet, leave the main database error information unchanged.
88407  */
88408  if( p->pc>=0 ){
88409    vdbeInvokeSqllog(p);
88410    if( db->pErr || p->zErrMsg ){
88411      sqlite3VdbeTransferError(p);
88412    }else{
88413      db->errCode = p->rc;
88414    }
88415  }
88416
88417  /* Reset register contents and reclaim error message memory.
88418  */
88419#ifdef SQLITE_DEBUG
88420  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
88421  ** Vdbe.aMem[] arrays have already been cleaned up.  */
88422  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
88423  if( p->aMem ){
88424    for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
88425  }
88426#endif
88427  if( p->zErrMsg ){
88428    sqlite3DbFree(db, p->zErrMsg);
88429    p->zErrMsg = 0;
88430  }
88431  p->pResultRow = 0;
88432#ifdef SQLITE_DEBUG
88433  p->nWrite = 0;
88434#endif
88435
88436  /* Save profiling information from this VDBE run.
88437  */
88438#ifdef VDBE_PROFILE
88439  {
88440    FILE *out = fopen("vdbe_profile.out", "a");
88441    if( out ){
88442      fprintf(out, "---- ");
88443      for(i=0; i<p->nOp; i++){
88444        fprintf(out, "%02x", p->aOp[i].opcode);
88445      }
88446      fprintf(out, "\n");
88447      if( p->zSql ){
88448        char c, pc = 0;
88449        fprintf(out, "-- ");
88450        for(i=0; (c = p->zSql[i])!=0; i++){
88451          if( pc=='\n' ) fprintf(out, "-- ");
88452          putc(c, out);
88453          pc = c;
88454        }
88455        if( pc!='\n' ) fprintf(out, "\n");
88456      }
88457      for(i=0; i<p->nOp; i++){
88458        char zHdr[100];
88459        i64 cnt = p->aOp[i].nExec;
88460        i64 cycles = p->aOp[i].nCycle;
88461        sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
88462           cnt,
88463           cycles,
88464           cnt>0 ? cycles/cnt : 0
88465        );
88466        fprintf(out, "%s", zHdr);
88467        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
88468      }
88469      fclose(out);
88470    }
88471  }
88472#endif
88473  return p->rc & db->errMask;
88474}
88475
88476/*
88477** Clean up and delete a VDBE after execution.  Return an integer which is
88478** the result code.  Write any error message text into *pzErrMsg.
88479*/
88480SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
88481  int rc = SQLITE_OK;
88482  assert( VDBE_RUN_STATE>VDBE_READY_STATE );
88483  assert( VDBE_HALT_STATE>VDBE_READY_STATE );
88484  assert( VDBE_INIT_STATE<VDBE_READY_STATE );
88485  if( p->eVdbeState>=VDBE_READY_STATE ){
88486    rc = sqlite3VdbeReset(p);
88487    assert( (rc & p->db->errMask)==rc );
88488  }
88489  sqlite3VdbeDelete(p);
88490  return rc;
88491}
88492
88493/*
88494** If parameter iOp is less than zero, then invoke the destructor for
88495** all auxiliary data pointers currently cached by the VM passed as
88496** the first argument.
88497**
88498** Or, if iOp is greater than or equal to zero, then the destructor is
88499** only invoked for those auxiliary data pointers created by the user
88500** function invoked by the OP_Function opcode at instruction iOp of
88501** VM pVdbe, and only then if:
88502**
88503**    * the associated function parameter is the 32nd or later (counting
88504**      from left to right), or
88505**
88506**    * the corresponding bit in argument mask is clear (where the first
88507**      function parameter corresponds to bit 0 etc.).
88508*/
88509SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
88510  while( *pp ){
88511    AuxData *pAux = *pp;
88512    if( (iOp<0)
88513     || (pAux->iAuxOp==iOp
88514          && pAux->iAuxArg>=0
88515          && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
88516    ){
88517      testcase( pAux->iAuxArg==31 );
88518      if( pAux->xDeleteAux ){
88519        pAux->xDeleteAux(pAux->pAux);
88520      }
88521      *pp = pAux->pNextAux;
88522      sqlite3DbFree(db, pAux);
88523    }else{
88524      pp= &pAux->pNextAux;
88525    }
88526  }
88527}
88528
88529/*
88530** Free all memory associated with the Vdbe passed as the second argument,
88531** except for object itself, which is preserved.
88532**
88533** The difference between this function and sqlite3VdbeDelete() is that
88534** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
88535** the database connection and frees the object itself.
88536*/
88537static void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
88538  SubProgram *pSub, *pNext;
88539  assert( db!=0 );
88540  assert( p->db==0 || p->db==db );
88541  if( p->aColName ){
88542    releaseMemArray(p->aColName, p->nResAlloc*COLNAME_N);
88543    sqlite3DbNNFreeNN(db, p->aColName);
88544  }
88545  for(pSub=p->pProgram; pSub; pSub=pNext){
88546    pNext = pSub->pNext;
88547    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
88548    sqlite3DbFree(db, pSub);
88549  }
88550  if( p->eVdbeState!=VDBE_INIT_STATE ){
88551    releaseMemArray(p->aVar, p->nVar);
88552    if( p->pVList ) sqlite3DbNNFreeNN(db, p->pVList);
88553    if( p->pFree ) sqlite3DbNNFreeNN(db, p->pFree);
88554  }
88555  vdbeFreeOpArray(db, p->aOp, p->nOp);
88556  if( p->zSql ) sqlite3DbNNFreeNN(db, p->zSql);
88557#ifdef SQLITE_ENABLE_NORMALIZE
88558  sqlite3DbFree(db, p->zNormSql);
88559  {
88560    DblquoteStr *pThis, *pNxt;
88561    for(pThis=p->pDblStr; pThis; pThis=pNxt){
88562      pNxt = pThis->pNextStr;
88563      sqlite3DbFree(db, pThis);
88564    }
88565  }
88566#endif
88567#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
88568  {
88569    int i;
88570    for(i=0; i<p->nScan; i++){
88571      sqlite3DbFree(db, p->aScan[i].zName);
88572    }
88573    sqlite3DbFree(db, p->aScan);
88574  }
88575#endif
88576}
88577
88578/*
88579** Delete an entire VDBE.
88580*/
88581SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
88582  sqlite3 *db;
88583
88584  assert( p!=0 );
88585  db = p->db;
88586  assert( db!=0 );
88587  assert( sqlite3_mutex_held(db->mutex) );
88588  sqlite3VdbeClearObject(db, p);
88589  if( db->pnBytesFreed==0 ){
88590    assert( p->ppVPrev!=0 );
88591    *p->ppVPrev = p->pVNext;
88592    if( p->pVNext ){
88593      p->pVNext->ppVPrev = p->ppVPrev;
88594    }
88595  }
88596  sqlite3DbNNFreeNN(db, p);
88597}
88598
88599/*
88600** The cursor "p" has a pending seek operation that has not yet been
88601** carried out.  Seek the cursor now.  If an error occurs, return
88602** the appropriate error code.
88603*/
88604SQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor *p){
88605  int res, rc;
88606#ifdef SQLITE_TEST
88607  extern int sqlite3_search_count;
88608#endif
88609  assert( p->deferredMoveto );
88610  assert( p->isTable );
88611  assert( p->eCurType==CURTYPE_BTREE );
88612  rc = sqlite3BtreeTableMoveto(p->uc.pCursor, p->movetoTarget, 0, &res);
88613  if( rc ) return rc;
88614  if( res!=0 ) return SQLITE_CORRUPT_BKPT;
88615#ifdef SQLITE_TEST
88616  sqlite3_search_count++;
88617#endif
88618  p->deferredMoveto = 0;
88619  p->cacheStatus = CACHE_STALE;
88620  return SQLITE_OK;
88621}
88622
88623/*
88624** Something has moved cursor "p" out of place.  Maybe the row it was
88625** pointed to was deleted out from under it.  Or maybe the btree was
88626** rebalanced.  Whatever the cause, try to restore "p" to the place it
88627** is supposed to be pointing.  If the row was deleted out from under the
88628** cursor, set the cursor to point to a NULL row.
88629*/
88630SQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeHandleMovedCursor(VdbeCursor *p){
88631  int isDifferentRow, rc;
88632  assert( p->eCurType==CURTYPE_BTREE );
88633  assert( p->uc.pCursor!=0 );
88634  assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
88635  rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
88636  p->cacheStatus = CACHE_STALE;
88637  if( isDifferentRow ) p->nullRow = 1;
88638  return rc;
88639}
88640
88641/*
88642** Check to ensure that the cursor is valid.  Restore the cursor
88643** if need be.  Return any I/O error from the restore operation.
88644*/
88645SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
88646  assert( p->eCurType==CURTYPE_BTREE || IsNullCursor(p) );
88647  if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
88648    return sqlite3VdbeHandleMovedCursor(p);
88649  }
88650  return SQLITE_OK;
88651}
88652
88653/*
88654** The following functions:
88655**
88656** sqlite3VdbeSerialType()
88657** sqlite3VdbeSerialTypeLen()
88658** sqlite3VdbeSerialLen()
88659** sqlite3VdbeSerialPut()  <--- in-lined into OP_MakeRecord as of 2022-04-02
88660** sqlite3VdbeSerialGet()
88661**
88662** encapsulate the code that serializes values for storage in SQLite
88663** data and index records. Each serialized value consists of a
88664** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
88665** integer, stored as a varint.
88666**
88667** In an SQLite index record, the serial type is stored directly before
88668** the blob of data that it corresponds to. In a table record, all serial
88669** types are stored at the start of the record, and the blobs of data at
88670** the end. Hence these functions allow the caller to handle the
88671** serial-type and data blob separately.
88672**
88673** The following table describes the various storage classes for data:
88674**
88675**   serial type        bytes of data      type
88676**   --------------     ---------------    ---------------
88677**      0                     0            NULL
88678**      1                     1            signed integer
88679**      2                     2            signed integer
88680**      3                     3            signed integer
88681**      4                     4            signed integer
88682**      5                     6            signed integer
88683**      6                     8            signed integer
88684**      7                     8            IEEE float
88685**      8                     0            Integer constant 0
88686**      9                     0            Integer constant 1
88687**     10,11                               reserved for expansion
88688**    N>=12 and even       (N-12)/2        BLOB
88689**    N>=13 and odd        (N-13)/2        text
88690**
88691** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
88692** of SQLite will not understand those serial types.
88693*/
88694
88695#if 0 /* Inlined into the OP_MakeRecord opcode */
88696/*
88697** Return the serial-type for the value stored in pMem.
88698**
88699** This routine might convert a large MEM_IntReal value into MEM_Real.
88700**
88701** 2019-07-11:  The primary user of this subroutine was the OP_MakeRecord
88702** opcode in the byte-code engine.  But by moving this routine in-line, we
88703** can omit some redundant tests and make that opcode a lot faster.  So
88704** this routine is now only used by the STAT3 logic and STAT3 support has
88705** ended.  The code is kept here for historical reference only.
88706*/
88707SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
88708  int flags = pMem->flags;
88709  u32 n;
88710
88711  assert( pLen!=0 );
88712  if( flags&MEM_Null ){
88713    *pLen = 0;
88714    return 0;
88715  }
88716  if( flags&(MEM_Int|MEM_IntReal) ){
88717    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
88718#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
88719    i64 i = pMem->u.i;
88720    u64 u;
88721    testcase( flags & MEM_Int );
88722    testcase( flags & MEM_IntReal );
88723    if( i<0 ){
88724      u = ~i;
88725    }else{
88726      u = i;
88727    }
88728    if( u<=127 ){
88729      if( (i&1)==i && file_format>=4 ){
88730        *pLen = 0;
88731        return 8+(u32)u;
88732      }else{
88733        *pLen = 1;
88734        return 1;
88735      }
88736    }
88737    if( u<=32767 ){ *pLen = 2; return 2; }
88738    if( u<=8388607 ){ *pLen = 3; return 3; }
88739    if( u<=2147483647 ){ *pLen = 4; return 4; }
88740    if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
88741    *pLen = 8;
88742    if( flags&MEM_IntReal ){
88743      /* If the value is IntReal and is going to take up 8 bytes to store
88744      ** as an integer, then we might as well make it an 8-byte floating
88745      ** point value */
88746      pMem->u.r = (double)pMem->u.i;
88747      pMem->flags &= ~MEM_IntReal;
88748      pMem->flags |= MEM_Real;
88749      return 7;
88750    }
88751    return 6;
88752  }
88753  if( flags&MEM_Real ){
88754    *pLen = 8;
88755    return 7;
88756  }
88757  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
88758  assert( pMem->n>=0 );
88759  n = (u32)pMem->n;
88760  if( flags & MEM_Zero ){
88761    n += pMem->u.nZero;
88762  }
88763  *pLen = n;
88764  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
88765}
88766#endif /* inlined into OP_MakeRecord */
88767
88768/*
88769** The sizes for serial types less than 128
88770*/
88771SQLITE_PRIVATE const u8 sqlite3SmallTypeSizes[128] = {
88772        /*  0   1   2   3   4   5   6   7   8   9 */
88773/*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
88774/*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
88775/*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
88776/*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
88777/*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
88778/*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
88779/*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
88780/*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
88781/*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
88782/*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
88783/* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
88784/* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
88785/* 120 */  54, 54, 55, 55, 56, 56, 57, 57
88786};
88787
88788/*
88789** Return the length of the data corresponding to the supplied serial-type.
88790*/
88791SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
88792  if( serial_type>=128 ){
88793    return (serial_type-12)/2;
88794  }else{
88795    assert( serial_type<12
88796            || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
88797    return sqlite3SmallTypeSizes[serial_type];
88798  }
88799}
88800SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
88801  assert( serial_type<128 );
88802  return sqlite3SmallTypeSizes[serial_type];
88803}
88804
88805/*
88806** If we are on an architecture with mixed-endian floating
88807** points (ex: ARM7) then swap the lower 4 bytes with the
88808** upper 4 bytes.  Return the result.
88809**
88810** For most architectures, this is a no-op.
88811**
88812** (later):  It is reported to me that the mixed-endian problem
88813** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
88814** that early versions of GCC stored the two words of a 64-bit
88815** float in the wrong order.  And that error has been propagated
88816** ever since.  The blame is not necessarily with GCC, though.
88817** GCC might have just copying the problem from a prior compiler.
88818** I am also told that newer versions of GCC that follow a different
88819** ABI get the byte order right.
88820**
88821** Developers using SQLite on an ARM7 should compile and run their
88822** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
88823** enabled, some asserts below will ensure that the byte order of
88824** floating point values is correct.
88825**
88826** (2007-08-30)  Frank van Vugt has studied this problem closely
88827** and has send his findings to the SQLite developers.  Frank
88828** writes that some Linux kernels offer floating point hardware
88829** emulation that uses only 32-bit mantissas instead of a full
88830** 48-bits as required by the IEEE standard.  (This is the
88831** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
88832** byte swapping becomes very complicated.  To avoid problems,
88833** the necessary byte swapping is carried out using a 64-bit integer
88834** rather than a 64-bit float.  Frank assures us that the code here
88835** works for him.  We, the developers, have no way to independently
88836** verify this, but Frank seems to know what he is talking about
88837** so we trust him.
88838*/
88839#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
88840SQLITE_PRIVATE u64 sqlite3FloatSwap(u64 in){
88841  union {
88842    u64 r;
88843    u32 i[2];
88844  } u;
88845  u32 t;
88846
88847  u.r = in;
88848  t = u.i[0];
88849  u.i[0] = u.i[1];
88850  u.i[1] = t;
88851  return u.r;
88852}
88853#endif /* SQLITE_MIXED_ENDIAN_64BIT_FLOAT */
88854
88855
88856/* Input "x" is a sequence of unsigned characters that represent a
88857** big-endian integer.  Return the equivalent native integer
88858*/
88859#define ONE_BYTE_INT(x)    ((i8)(x)[0])
88860#define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
88861#define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
88862#define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
88863#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
88864
88865/*
88866** Deserialize the data blob pointed to by buf as serial type serial_type
88867** and store the result in pMem.
88868**
88869** This function is implemented as two separate routines for performance.
88870** The few cases that require local variables are broken out into a separate
88871** routine so that in most cases the overhead of moving the stack pointer
88872** is avoided.
88873*/
88874static void serialGet(
88875  const unsigned char *buf,     /* Buffer to deserialize from */
88876  u32 serial_type,              /* Serial type to deserialize */
88877  Mem *pMem                     /* Memory cell to write value into */
88878){
88879  u64 x = FOUR_BYTE_UINT(buf);
88880  u32 y = FOUR_BYTE_UINT(buf+4);
88881  x = (x<<32) + y;
88882  if( serial_type==6 ){
88883    /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
88884    ** twos-complement integer. */
88885    pMem->u.i = *(i64*)&x;
88886    pMem->flags = MEM_Int;
88887    testcase( pMem->u.i<0 );
88888  }else{
88889    /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
88890    ** floating point number. */
88891#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
88892    /* Verify that integers and floating point values use the same
88893    ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
88894    ** defined that 64-bit floating point values really are mixed
88895    ** endian.
88896    */
88897    static const u64 t1 = ((u64)0x3ff00000)<<32;
88898    static const double r1 = 1.0;
88899    u64 t2 = t1;
88900    swapMixedEndianFloat(t2);
88901    assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
88902#endif
88903    assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
88904    swapMixedEndianFloat(x);
88905    memcpy(&pMem->u.r, &x, sizeof(x));
88906    pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;
88907  }
88908}
88909static int serialGet7(
88910  const unsigned char *buf,     /* Buffer to deserialize from */
88911  Mem *pMem                     /* Memory cell to write value into */
88912){
88913  u64 x = FOUR_BYTE_UINT(buf);
88914  u32 y = FOUR_BYTE_UINT(buf+4);
88915  x = (x<<32) + y;
88916  assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
88917  swapMixedEndianFloat(x);
88918  memcpy(&pMem->u.r, &x, sizeof(x));
88919  if( IsNaN(x) ){
88920    pMem->flags = MEM_Null;
88921    return 1;
88922  }
88923  pMem->flags = MEM_Real;
88924  return 0;
88925}
88926SQLITE_PRIVATE void sqlite3VdbeSerialGet(
88927  const unsigned char *buf,     /* Buffer to deserialize from */
88928  u32 serial_type,              /* Serial type to deserialize */
88929  Mem *pMem                     /* Memory cell to write value into */
88930){
88931  switch( serial_type ){
88932    case 10: { /* Internal use only: NULL with virtual table
88933               ** UPDATE no-change flag set */
88934      pMem->flags = MEM_Null|MEM_Zero;
88935      pMem->n = 0;
88936      pMem->u.nZero = 0;
88937      return;
88938    }
88939    case 11:   /* Reserved for future use */
88940    case 0: {  /* Null */
88941      /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
88942      pMem->flags = MEM_Null;
88943      return;
88944    }
88945    case 1: {
88946      /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
88947      ** integer. */
88948      pMem->u.i = ONE_BYTE_INT(buf);
88949      pMem->flags = MEM_Int;
88950      testcase( pMem->u.i<0 );
88951      return;
88952    }
88953    case 2: { /* 2-byte signed integer */
88954      /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
88955      ** twos-complement integer. */
88956      pMem->u.i = TWO_BYTE_INT(buf);
88957      pMem->flags = MEM_Int;
88958      testcase( pMem->u.i<0 );
88959      return;
88960    }
88961    case 3: { /* 3-byte signed integer */
88962      /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
88963      ** twos-complement integer. */
88964      pMem->u.i = THREE_BYTE_INT(buf);
88965      pMem->flags = MEM_Int;
88966      testcase( pMem->u.i<0 );
88967      return;
88968    }
88969    case 4: { /* 4-byte signed integer */
88970      /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
88971      ** twos-complement integer. */
88972      pMem->u.i = FOUR_BYTE_INT(buf);
88973#ifdef __HP_cc
88974      /* Work around a sign-extension bug in the HP compiler for HP/UX */
88975      if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
88976#endif
88977      pMem->flags = MEM_Int;
88978      testcase( pMem->u.i<0 );
88979      return;
88980    }
88981    case 5: { /* 6-byte signed integer */
88982      /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
88983      ** twos-complement integer. */
88984      pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
88985      pMem->flags = MEM_Int;
88986      testcase( pMem->u.i<0 );
88987      return;
88988    }
88989    case 6:   /* 8-byte signed integer */
88990    case 7: { /* IEEE floating point */
88991      /* These use local variables, so do them in a separate routine
88992      ** to avoid having to move the frame pointer in the common case */
88993      serialGet(buf,serial_type,pMem);
88994      return;
88995    }
88996    case 8:    /* Integer 0 */
88997    case 9: {  /* Integer 1 */
88998      /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
88999      /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
89000      pMem->u.i = serial_type-8;
89001      pMem->flags = MEM_Int;
89002      return;
89003    }
89004    default: {
89005      /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
89006      ** length.
89007      ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
89008      ** (N-13)/2 bytes in length. */
89009      static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
89010      pMem->z = (char *)buf;
89011      pMem->n = (serial_type-12)/2;
89012      pMem->flags = aFlag[serial_type&1];
89013      return;
89014    }
89015  }
89016  return;
89017}
89018/*
89019** This routine is used to allocate sufficient space for an UnpackedRecord
89020** structure large enough to be used with sqlite3VdbeRecordUnpack() if
89021** the first argument is a pointer to KeyInfo structure pKeyInfo.
89022**
89023** The space is either allocated using sqlite3DbMallocRaw() or from within
89024** the unaligned buffer passed via the second and third arguments (presumably
89025** stack space). If the former, then *ppFree is set to a pointer that should
89026** be eventually freed by the caller using sqlite3DbFree(). Or, if the
89027** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
89028** before returning.
89029**
89030** If an OOM error occurs, NULL is returned.
89031*/
89032SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
89033  KeyInfo *pKeyInfo               /* Description of the record */
89034){
89035  UnpackedRecord *p;              /* Unpacked record to return */
89036  int nByte;                      /* Number of bytes required for *p */
89037  nByte = ROUND8P(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
89038  p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
89039  if( !p ) return 0;
89040  p->aMem = (Mem*)&((char*)p)[ROUND8P(sizeof(UnpackedRecord))];
89041  assert( pKeyInfo->aSortFlags!=0 );
89042  p->pKeyInfo = pKeyInfo;
89043  p->nField = pKeyInfo->nKeyField + 1;
89044  return p;
89045}
89046
89047/*
89048** Given the nKey-byte encoding of a record in pKey[], populate the
89049** UnpackedRecord structure indicated by the fourth argument with the
89050** contents of the decoded record.
89051*/
89052SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
89053  KeyInfo *pKeyInfo,     /* Information about the record format */
89054  int nKey,              /* Size of the binary record */
89055  const void *pKey,      /* The binary record */
89056  UnpackedRecord *p      /* Populate this structure before returning. */
89057){
89058  const unsigned char *aKey = (const unsigned char *)pKey;
89059  u32 d;
89060  u32 idx;                        /* Offset in aKey[] to read from */
89061  u16 u;                          /* Unsigned loop counter */
89062  u32 szHdr;
89063  Mem *pMem = p->aMem;
89064
89065  p->default_rc = 0;
89066  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
89067  idx = getVarint32(aKey, szHdr);
89068  d = szHdr;
89069  u = 0;
89070  while( idx<szHdr && d<=(u32)nKey ){
89071    u32 serial_type;
89072
89073    idx += getVarint32(&aKey[idx], serial_type);
89074    pMem->enc = pKeyInfo->enc;
89075    pMem->db = pKeyInfo->db;
89076    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
89077    pMem->szMalloc = 0;
89078    pMem->z = 0;
89079    sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
89080    d += sqlite3VdbeSerialTypeLen(serial_type);
89081    pMem++;
89082    if( (++u)>=p->nField ) break;
89083  }
89084  if( d>(u32)nKey && u ){
89085    assert( CORRUPT_DB );
89086    /* In a corrupt record entry, the last pMem might have been set up using
89087    ** uninitialized memory. Overwrite its value with NULL, to prevent
89088    ** warnings from MSAN. */
89089    sqlite3VdbeMemSetNull(pMem-1);
89090  }
89091  assert( u<=pKeyInfo->nKeyField + 1 );
89092  p->nField = u;
89093}
89094
89095#ifdef SQLITE_DEBUG
89096/*
89097** This function compares two index or table record keys in the same way
89098** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
89099** this function deserializes and compares values using the
89100** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
89101** in assert() statements to ensure that the optimized code in
89102** sqlite3VdbeRecordCompare() returns results with these two primitives.
89103**
89104** Return true if the result of comparison is equivalent to desiredResult.
89105** Return false if there is a disagreement.
89106*/
89107static int vdbeRecordCompareDebug(
89108  int nKey1, const void *pKey1, /* Left key */
89109  const UnpackedRecord *pPKey2, /* Right key */
89110  int desiredResult             /* Correct answer */
89111){
89112  u32 d1;            /* Offset into aKey[] of next data element */
89113  u32 idx1;          /* Offset into aKey[] of next header element */
89114  u32 szHdr1;        /* Number of bytes in header */
89115  int i = 0;
89116  int rc = 0;
89117  const unsigned char *aKey1 = (const unsigned char *)pKey1;
89118  KeyInfo *pKeyInfo;
89119  Mem mem1;
89120
89121  pKeyInfo = pPKey2->pKeyInfo;
89122  if( pKeyInfo->db==0 ) return 1;
89123  mem1.enc = pKeyInfo->enc;
89124  mem1.db = pKeyInfo->db;
89125  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
89126  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
89127
89128  /* Compilers may complain that mem1.u.i is potentially uninitialized.
89129  ** We could initialize it, as shown here, to silence those complaints.
89130  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
89131  ** the unnecessary initialization has a measurable negative performance
89132  ** impact, since this routine is a very high runner.  And so, we choose
89133  ** to ignore the compiler warnings and leave this variable uninitialized.
89134  */
89135  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
89136
89137  idx1 = getVarint32(aKey1, szHdr1);
89138  if( szHdr1>98307 ) return SQLITE_CORRUPT;
89139  d1 = szHdr1;
89140  assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
89141  assert( pKeyInfo->aSortFlags!=0 );
89142  assert( pKeyInfo->nKeyField>0 );
89143  assert( idx1<=szHdr1 || CORRUPT_DB );
89144  do{
89145    u32 serial_type1;
89146
89147    /* Read the serial types for the next element in each key. */
89148    idx1 += getVarint32( aKey1+idx1, serial_type1 );
89149
89150    /* Verify that there is enough key space remaining to avoid
89151    ** a buffer overread.  The "d1+serial_type1+2" subexpression will
89152    ** always be greater than or equal to the amount of required key space.
89153    ** Use that approximation to avoid the more expensive call to
89154    ** sqlite3VdbeSerialTypeLen() in the common case.
89155    */
89156    if( d1+(u64)serial_type1+2>(u64)nKey1
89157     && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1
89158    ){
89159      if( serial_type1>=1
89160       && serial_type1<=7
89161       && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)<=(u64)nKey1+8
89162       && CORRUPT_DB
89163      ){
89164        return 1;  /* corrupt record not detected by
89165                   ** sqlite3VdbeRecordCompareWithSkip().  Return true
89166                   ** to avoid firing the assert() */
89167      }
89168      break;
89169    }
89170
89171    /* Extract the values to be compared.
89172    */
89173    sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
89174    d1 += sqlite3VdbeSerialTypeLen(serial_type1);
89175
89176    /* Do the comparison
89177    */
89178    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
89179                           pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
89180    if( rc!=0 ){
89181      assert( mem1.szMalloc==0 );  /* See comment below */
89182      if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
89183       && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null))
89184      ){
89185        rc = -rc;
89186      }
89187      if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){
89188        rc = -rc;  /* Invert the result for DESC sort order. */
89189      }
89190      goto debugCompareEnd;
89191    }
89192    i++;
89193  }while( idx1<szHdr1 && i<pPKey2->nField );
89194
89195  /* No memory allocation is ever used on mem1.  Prove this using
89196  ** the following assert().  If the assert() fails, it indicates a
89197  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
89198  */
89199  assert( mem1.szMalloc==0 );
89200
89201  /* rc==0 here means that one of the keys ran out of fields and
89202  ** all the fields up to that point were equal. Return the default_rc
89203  ** value.  */
89204  rc = pPKey2->default_rc;
89205
89206debugCompareEnd:
89207  if( desiredResult==0 && rc==0 ) return 1;
89208  if( desiredResult<0 && rc<0 ) return 1;
89209  if( desiredResult>0 && rc>0 ) return 1;
89210  if( CORRUPT_DB ) return 1;
89211  if( pKeyInfo->db->mallocFailed ) return 1;
89212  return 0;
89213}
89214#endif
89215
89216#ifdef SQLITE_DEBUG
89217/*
89218** Count the number of fields (a.k.a. columns) in the record given by
89219** pKey,nKey.  The verify that this count is less than or equal to the
89220** limit given by pKeyInfo->nAllField.
89221**
89222** If this constraint is not satisfied, it means that the high-speed
89223** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
89224** not work correctly.  If this assert() ever fires, it probably means
89225** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
89226** incorrectly.
89227*/
89228static void vdbeAssertFieldCountWithinLimits(
89229  int nKey, const void *pKey,   /* The record to verify */
89230  const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
89231){
89232  int nField = 0;
89233  u32 szHdr;
89234  u32 idx;
89235  u32 notUsed;
89236  const unsigned char *aKey = (const unsigned char*)pKey;
89237
89238  if( CORRUPT_DB ) return;
89239  idx = getVarint32(aKey, szHdr);
89240  assert( nKey>=0 );
89241  assert( szHdr<=(u32)nKey );
89242  while( idx<szHdr ){
89243    idx += getVarint32(aKey+idx, notUsed);
89244    nField++;
89245  }
89246  assert( nField <= pKeyInfo->nAllField );
89247}
89248#else
89249# define vdbeAssertFieldCountWithinLimits(A,B,C)
89250#endif
89251
89252/*
89253** Both *pMem1 and *pMem2 contain string values. Compare the two values
89254** using the collation sequence pColl. As usual, return a negative , zero
89255** or positive value if *pMem1 is less than, equal to or greater than
89256** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
89257*/
89258static int vdbeCompareMemString(
89259  const Mem *pMem1,
89260  const Mem *pMem2,
89261  const CollSeq *pColl,
89262  u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
89263){
89264  if( pMem1->enc==pColl->enc ){
89265    /* The strings are already in the correct encoding.  Call the
89266     ** comparison function directly */
89267    return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
89268  }else{
89269    int rc;
89270    const void *v1, *v2;
89271    Mem c1;
89272    Mem c2;
89273    sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
89274    sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
89275    sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
89276    sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
89277    v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
89278    v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
89279    if( (v1==0 || v2==0) ){
89280      if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
89281      rc = 0;
89282    }else{
89283      rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
89284    }
89285    sqlite3VdbeMemReleaseMalloc(&c1);
89286    sqlite3VdbeMemReleaseMalloc(&c2);
89287    return rc;
89288  }
89289}
89290
89291/*
89292** The input pBlob is guaranteed to be a Blob that is not marked
89293** with MEM_Zero.  Return true if it could be a zero-blob.
89294*/
89295static int isAllZero(const char *z, int n){
89296  int i;
89297  for(i=0; i<n; i++){
89298    if( z[i] ) return 0;
89299  }
89300  return 1;
89301}
89302
89303/*
89304** Compare two blobs.  Return negative, zero, or positive if the first
89305** is less than, equal to, or greater than the second, respectively.
89306** If one blob is a prefix of the other, then the shorter is the lessor.
89307*/
89308SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
89309  int c;
89310  int n1 = pB1->n;
89311  int n2 = pB2->n;
89312
89313  /* It is possible to have a Blob value that has some non-zero content
89314  ** followed by zero content.  But that only comes up for Blobs formed
89315  ** by the OP_MakeRecord opcode, and such Blobs never get passed into
89316  ** sqlite3MemCompare(). */
89317  assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
89318  assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
89319
89320  if( (pB1->flags|pB2->flags) & MEM_Zero ){
89321    if( pB1->flags & pB2->flags & MEM_Zero ){
89322      return pB1->u.nZero - pB2->u.nZero;
89323    }else if( pB1->flags & MEM_Zero ){
89324      if( !isAllZero(pB2->z, pB2->n) ) return -1;
89325      return pB1->u.nZero - n2;
89326    }else{
89327      if( !isAllZero(pB1->z, pB1->n) ) return +1;
89328      return n1 - pB2->u.nZero;
89329    }
89330  }
89331  c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
89332  if( c ) return c;
89333  return n1 - n2;
89334}
89335
89336/* The following two functions are used only within testcase() to prove
89337** test coverage.  These functions do no exist for production builds.
89338** We must use separate SQLITE_NOINLINE functions here, since otherwise
89339** optimizer code movement causes gcov to become very confused.
89340*/
89341#if  defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
89342static int SQLITE_NOINLINE doubleLt(double a, double b){ return a<b; }
89343static int SQLITE_NOINLINE doubleEq(double a, double b){ return a==b; }
89344#endif
89345
89346/*
89347** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
89348** number.  Return negative, zero, or positive if the first (i64) is less than,
89349** equal to, or greater than the second (double).
89350*/
89351SQLITE_PRIVATE int sqlite3IntFloatCompare(i64 i, double r){
89352  if( sqlite3IsNaN(r) ){
89353    /* SQLite considers NaN to be a NULL. And all integer values are greater
89354    ** than NULL */
89355    return 1;
89356  }
89357  if( sqlite3Config.bUseLongDouble ){
89358    LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
89359    testcase( x<r );
89360    testcase( x>r );
89361    testcase( x==r );
89362    return (x<r) ? -1 : (x>r);
89363  }else{
89364    i64 y;
89365    if( r<-9223372036854775808.0 ) return +1;
89366    if( r>=9223372036854775808.0 ) return -1;
89367    y = (i64)r;
89368    if( i<y ) return -1;
89369    if( i>y ) return +1;
89370    testcase( doubleLt(((double)i),r) );
89371    testcase( doubleLt(r,((double)i)) );
89372    testcase( doubleEq(r,((double)i)) );
89373    return (((double)i)<r) ? -1 : (((double)i)>r);
89374  }
89375}
89376
89377/*
89378** Compare the values contained by the two memory cells, returning
89379** negative, zero or positive if pMem1 is less than, equal to, or greater
89380** than pMem2. Sorting order is NULL's first, followed by numbers (integers
89381** and reals) sorted numerically, followed by text ordered by the collating
89382** sequence pColl and finally blob's ordered by memcmp().
89383**
89384** Two NULL values are considered equal by this function.
89385*/
89386SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
89387  int f1, f2;
89388  int combined_flags;
89389
89390  f1 = pMem1->flags;
89391  f2 = pMem2->flags;
89392  combined_flags = f1|f2;
89393  assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
89394
89395  /* If one value is NULL, it is less than the other. If both values
89396  ** are NULL, return 0.
89397  */
89398  if( combined_flags&MEM_Null ){
89399    return (f2&MEM_Null) - (f1&MEM_Null);
89400  }
89401
89402  /* At least one of the two values is a number
89403  */
89404  if( combined_flags&(MEM_Int|MEM_Real|MEM_IntReal) ){
89405    testcase( combined_flags & MEM_Int );
89406    testcase( combined_flags & MEM_Real );
89407    testcase( combined_flags & MEM_IntReal );
89408    if( (f1 & f2 & (MEM_Int|MEM_IntReal))!=0 ){
89409      testcase( f1 & f2 & MEM_Int );
89410      testcase( f1 & f2 & MEM_IntReal );
89411      if( pMem1->u.i < pMem2->u.i ) return -1;
89412      if( pMem1->u.i > pMem2->u.i ) return +1;
89413      return 0;
89414    }
89415    if( (f1 & f2 & MEM_Real)!=0 ){
89416      if( pMem1->u.r < pMem2->u.r ) return -1;
89417      if( pMem1->u.r > pMem2->u.r ) return +1;
89418      return 0;
89419    }
89420    if( (f1&(MEM_Int|MEM_IntReal))!=0 ){
89421      testcase( f1 & MEM_Int );
89422      testcase( f1 & MEM_IntReal );
89423      if( (f2&MEM_Real)!=0 ){
89424        return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
89425      }else if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
89426        if( pMem1->u.i < pMem2->u.i ) return -1;
89427        if( pMem1->u.i > pMem2->u.i ) return +1;
89428        return 0;
89429      }else{
89430        return -1;
89431      }
89432    }
89433    if( (f1&MEM_Real)!=0 ){
89434      if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
89435        testcase( f2 & MEM_Int );
89436        testcase( f2 & MEM_IntReal );
89437        return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
89438      }else{
89439        return -1;
89440      }
89441    }
89442    return +1;
89443  }
89444
89445  /* If one value is a string and the other is a blob, the string is less.
89446  ** If both are strings, compare using the collating functions.
89447  */
89448  if( combined_flags&MEM_Str ){
89449    if( (f1 & MEM_Str)==0 ){
89450      return 1;
89451    }
89452    if( (f2 & MEM_Str)==0 ){
89453      return -1;
89454    }
89455
89456    assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
89457    assert( pMem1->enc==SQLITE_UTF8 ||
89458            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
89459
89460    /* The collation sequence must be defined at this point, even if
89461    ** the user deletes the collation sequence after the vdbe program is
89462    ** compiled (this was not always the case).
89463    */
89464    assert( !pColl || pColl->xCmp );
89465
89466    if( pColl ){
89467      return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
89468    }
89469    /* If a NULL pointer was passed as the collate function, fall through
89470    ** to the blob case and use memcmp().  */
89471  }
89472
89473  /* Both values must be blobs.  Compare using memcmp().  */
89474  return sqlite3BlobCompare(pMem1, pMem2);
89475}
89476
89477
89478/*
89479** The first argument passed to this function is a serial-type that
89480** corresponds to an integer - all values between 1 and 9 inclusive
89481** except 7. The second points to a buffer containing an integer value
89482** serialized according to serial_type. This function deserializes
89483** and returns the value.
89484*/
89485static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
89486  u32 y;
89487  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
89488  switch( serial_type ){
89489    case 0:
89490    case 1:
89491      testcase( aKey[0]&0x80 );
89492      return ONE_BYTE_INT(aKey);
89493    case 2:
89494      testcase( aKey[0]&0x80 );
89495      return TWO_BYTE_INT(aKey);
89496    case 3:
89497      testcase( aKey[0]&0x80 );
89498      return THREE_BYTE_INT(aKey);
89499    case 4: {
89500      testcase( aKey[0]&0x80 );
89501      y = FOUR_BYTE_UINT(aKey);
89502      return (i64)*(int*)&y;
89503    }
89504    case 5: {
89505      testcase( aKey[0]&0x80 );
89506      return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
89507    }
89508    case 6: {
89509      u64 x = FOUR_BYTE_UINT(aKey);
89510      testcase( aKey[0]&0x80 );
89511      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
89512      return (i64)*(i64*)&x;
89513    }
89514  }
89515
89516  return (serial_type - 8);
89517}
89518
89519/*
89520** This function compares the two table rows or index records
89521** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
89522** or positive integer if key1 is less than, equal to or
89523** greater than key2.  The {nKey1, pKey1} key must be a blob
89524** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
89525** key must be a parsed key such as obtained from
89526** sqlite3VdbeParseRecord.
89527**
89528** If argument bSkip is non-zero, it is assumed that the caller has already
89529** determined that the first fields of the keys are equal.
89530**
89531** Key1 and Key2 do not have to contain the same number of fields. If all
89532** fields that appear in both keys are equal, then pPKey2->default_rc is
89533** returned.
89534**
89535** If database corruption is discovered, set pPKey2->errCode to
89536** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
89537** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
89538** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
89539*/
89540SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
89541  int nKey1, const void *pKey1,   /* Left key */
89542  UnpackedRecord *pPKey2,         /* Right key */
89543  int bSkip                       /* If true, skip the first field */
89544){
89545  u32 d1;                         /* Offset into aKey[] of next data element */
89546  int i;                          /* Index of next field to compare */
89547  u32 szHdr1;                     /* Size of record header in bytes */
89548  u32 idx1;                       /* Offset of first type in header */
89549  int rc = 0;                     /* Return value */
89550  Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
89551  KeyInfo *pKeyInfo;
89552  const unsigned char *aKey1 = (const unsigned char *)pKey1;
89553  Mem mem1;
89554
89555  /* If bSkip is true, then the caller has already determined that the first
89556  ** two elements in the keys are equal. Fix the various stack variables so
89557  ** that this routine begins comparing at the second field. */
89558  if( bSkip ){
89559    u32 s1 = aKey1[1];
89560    if( s1<0x80 ){
89561      idx1 = 2;
89562    }else{
89563      idx1 = 1 + sqlite3GetVarint32(&aKey1[1], &s1);
89564    }
89565    szHdr1 = aKey1[0];
89566    d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
89567    i = 1;
89568    pRhs++;
89569  }else{
89570    if( (szHdr1 = aKey1[0])<0x80 ){
89571      idx1 = 1;
89572    }else{
89573      idx1 = sqlite3GetVarint32(aKey1, &szHdr1);
89574    }
89575    d1 = szHdr1;
89576    i = 0;
89577  }
89578  if( d1>(unsigned)nKey1 ){
89579    pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
89580    return 0;  /* Corruption */
89581  }
89582
89583  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
89584  assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
89585       || CORRUPT_DB );
89586  assert( pPKey2->pKeyInfo->aSortFlags!=0 );
89587  assert( pPKey2->pKeyInfo->nKeyField>0 );
89588  assert( idx1<=szHdr1 || CORRUPT_DB );
89589  while( 1 /*exit-by-break*/ ){
89590    u32 serial_type;
89591
89592    /* RHS is an integer */
89593    if( pRhs->flags & (MEM_Int|MEM_IntReal) ){
89594      testcase( pRhs->flags & MEM_Int );
89595      testcase( pRhs->flags & MEM_IntReal );
89596      serial_type = aKey1[idx1];
89597      testcase( serial_type==12 );
89598      if( serial_type>=10 ){
89599        rc = serial_type==10 ? -1 : +1;
89600      }else if( serial_type==0 ){
89601        rc = -1;
89602      }else if( serial_type==7 ){
89603        serialGet7(&aKey1[d1], &mem1);
89604        rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
89605      }else{
89606        i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
89607        i64 rhs = pRhs->u.i;
89608        if( lhs<rhs ){
89609          rc = -1;
89610        }else if( lhs>rhs ){
89611          rc = +1;
89612        }
89613      }
89614    }
89615
89616    /* RHS is real */
89617    else if( pRhs->flags & MEM_Real ){
89618      serial_type = aKey1[idx1];
89619      if( serial_type>=10 ){
89620        /* Serial types 12 or greater are strings and blobs (greater than
89621        ** numbers). Types 10 and 11 are currently "reserved for future
89622        ** use", so it doesn't really matter what the results of comparing
89623        ** them to numeric values are.  */
89624        rc = serial_type==10 ? -1 : +1;
89625      }else if( serial_type==0 ){
89626        rc = -1;
89627      }else{
89628        if( serial_type==7 ){
89629          if( serialGet7(&aKey1[d1], &mem1) ){
89630            rc = -1;  /* mem1 is a NaN */
89631          }else if( mem1.u.r<pRhs->u.r ){
89632            rc = -1;
89633          }else if( mem1.u.r>pRhs->u.r ){
89634            rc = +1;
89635          }else{
89636            assert( rc==0 );
89637          }
89638        }else{
89639          sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
89640          rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
89641        }
89642      }
89643    }
89644
89645    /* RHS is a string */
89646    else if( pRhs->flags & MEM_Str ){
89647      getVarint32NR(&aKey1[idx1], serial_type);
89648      testcase( serial_type==12 );
89649      if( serial_type<12 ){
89650        rc = -1;
89651      }else if( !(serial_type & 0x01) ){
89652        rc = +1;
89653      }else{
89654        mem1.n = (serial_type - 12) / 2;
89655        testcase( (d1+mem1.n)==(unsigned)nKey1 );
89656        testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
89657        if( (d1+mem1.n) > (unsigned)nKey1
89658         || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
89659        ){
89660          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
89661          return 0;                /* Corruption */
89662        }else if( pKeyInfo->aColl[i] ){
89663          mem1.enc = pKeyInfo->enc;
89664          mem1.db = pKeyInfo->db;
89665          mem1.flags = MEM_Str;
89666          mem1.z = (char*)&aKey1[d1];
89667          rc = vdbeCompareMemString(
89668              &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
89669          );
89670        }else{
89671          int nCmp = MIN(mem1.n, pRhs->n);
89672          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
89673          if( rc==0 ) rc = mem1.n - pRhs->n;
89674        }
89675      }
89676    }
89677
89678    /* RHS is a blob */
89679    else if( pRhs->flags & MEM_Blob ){
89680      assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
89681      getVarint32NR(&aKey1[idx1], serial_type);
89682      testcase( serial_type==12 );
89683      if( serial_type<12 || (serial_type & 0x01) ){
89684        rc = -1;
89685      }else{
89686        int nStr = (serial_type - 12) / 2;
89687        testcase( (d1+nStr)==(unsigned)nKey1 );
89688        testcase( (d1+nStr+1)==(unsigned)nKey1 );
89689        if( (d1+nStr) > (unsigned)nKey1 ){
89690          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
89691          return 0;                /* Corruption */
89692        }else if( pRhs->flags & MEM_Zero ){
89693          if( !isAllZero((const char*)&aKey1[d1],nStr) ){
89694            rc = 1;
89695          }else{
89696            rc = nStr - pRhs->u.nZero;
89697          }
89698        }else{
89699          int nCmp = MIN(nStr, pRhs->n);
89700          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
89701          if( rc==0 ) rc = nStr - pRhs->n;
89702        }
89703      }
89704    }
89705
89706    /* RHS is null */
89707    else{
89708      serial_type = aKey1[idx1];
89709      if( serial_type==0
89710       || serial_type==10
89711       || (serial_type==7 && serialGet7(&aKey1[d1], &mem1)!=0)
89712      ){
89713        assert( rc==0 );
89714      }else{
89715        rc = 1;
89716      }
89717    }
89718
89719    if( rc!=0 ){
89720      int sortFlags = pPKey2->pKeyInfo->aSortFlags[i];
89721      if( sortFlags ){
89722        if( (sortFlags & KEYINFO_ORDER_BIGNULL)==0
89723         || ((sortFlags & KEYINFO_ORDER_DESC)
89724           !=(serial_type==0 || (pRhs->flags&MEM_Null)))
89725        ){
89726          rc = -rc;
89727        }
89728      }
89729      assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
89730      assert( mem1.szMalloc==0 );  /* See comment below */
89731      return rc;
89732    }
89733
89734    i++;
89735    if( i==pPKey2->nField ) break;
89736    pRhs++;
89737    d1 += sqlite3VdbeSerialTypeLen(serial_type);
89738    if( d1>(unsigned)nKey1 ) break;
89739    idx1 += sqlite3VarintLen(serial_type);
89740    if( idx1>=(unsigned)szHdr1 ){
89741      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
89742      return 0;  /* Corrupt index */
89743    }
89744  }
89745
89746  /* No memory allocation is ever used on mem1.  Prove this using
89747  ** the following assert().  If the assert() fails, it indicates a
89748  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
89749  assert( mem1.szMalloc==0 );
89750
89751  /* rc==0 here means that one or both of the keys ran out of fields and
89752  ** all the fields up to that point were equal. Return the default_rc
89753  ** value.  */
89754  assert( CORRUPT_DB
89755       || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
89756       || pPKey2->pKeyInfo->db->mallocFailed
89757  );
89758  pPKey2->eqSeen = 1;
89759  return pPKey2->default_rc;
89760}
89761SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
89762  int nKey1, const void *pKey1,   /* Left key */
89763  UnpackedRecord *pPKey2          /* Right key */
89764){
89765  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
89766}
89767
89768
89769/*
89770** This function is an optimized version of sqlite3VdbeRecordCompare()
89771** that (a) the first field of pPKey2 is an integer, and (b) the
89772** size-of-header varint at the start of (pKey1/nKey1) fits in a single
89773** byte (i.e. is less than 128).
89774**
89775** To avoid concerns about buffer overreads, this routine is only used
89776** on schemas where the maximum valid header size is 63 bytes or less.
89777*/
89778static int vdbeRecordCompareInt(
89779  int nKey1, const void *pKey1, /* Left key */
89780  UnpackedRecord *pPKey2        /* Right key */
89781){
89782  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
89783  int serial_type = ((const u8*)pKey1)[1];
89784  int res;
89785  u32 y;
89786  u64 x;
89787  i64 v;
89788  i64 lhs;
89789
89790  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
89791  assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
89792  switch( serial_type ){
89793    case 1: { /* 1-byte signed integer */
89794      lhs = ONE_BYTE_INT(aKey);
89795      testcase( lhs<0 );
89796      break;
89797    }
89798    case 2: { /* 2-byte signed integer */
89799      lhs = TWO_BYTE_INT(aKey);
89800      testcase( lhs<0 );
89801      break;
89802    }
89803    case 3: { /* 3-byte signed integer */
89804      lhs = THREE_BYTE_INT(aKey);
89805      testcase( lhs<0 );
89806      break;
89807    }
89808    case 4: { /* 4-byte signed integer */
89809      y = FOUR_BYTE_UINT(aKey);
89810      lhs = (i64)*(int*)&y;
89811      testcase( lhs<0 );
89812      break;
89813    }
89814    case 5: { /* 6-byte signed integer */
89815      lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
89816      testcase( lhs<0 );
89817      break;
89818    }
89819    case 6: { /* 8-byte signed integer */
89820      x = FOUR_BYTE_UINT(aKey);
89821      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
89822      lhs = *(i64*)&x;
89823      testcase( lhs<0 );
89824      break;
89825    }
89826    case 8:
89827      lhs = 0;
89828      break;
89829    case 9:
89830      lhs = 1;
89831      break;
89832
89833    /* This case could be removed without changing the results of running
89834    ** this code. Including it causes gcc to generate a faster switch
89835    ** statement (since the range of switch targets now starts at zero and
89836    ** is contiguous) but does not cause any duplicate code to be generated
89837    ** (as gcc is clever enough to combine the two like cases). Other
89838    ** compilers might be similar.  */
89839    case 0: case 7:
89840      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
89841
89842    default:
89843      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
89844  }
89845
89846  assert( pPKey2->u.i == pPKey2->aMem[0].u.i );
89847  v = pPKey2->u.i;
89848  if( v>lhs ){
89849    res = pPKey2->r1;
89850  }else if( v<lhs ){
89851    res = pPKey2->r2;
89852  }else if( pPKey2->nField>1 ){
89853    /* The first fields of the two keys are equal. Compare the trailing
89854    ** fields.  */
89855    res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
89856  }else{
89857    /* The first fields of the two keys are equal and there are no trailing
89858    ** fields. Return pPKey2->default_rc in this case. */
89859    res = pPKey2->default_rc;
89860    pPKey2->eqSeen = 1;
89861  }
89862
89863  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
89864  return res;
89865}
89866
89867/*
89868** This function is an optimized version of sqlite3VdbeRecordCompare()
89869** that (a) the first field of pPKey2 is a string, that (b) the first field
89870** uses the collation sequence BINARY and (c) that the size-of-header varint
89871** at the start of (pKey1/nKey1) fits in a single byte.
89872*/
89873static int vdbeRecordCompareString(
89874  int nKey1, const void *pKey1, /* Left key */
89875  UnpackedRecord *pPKey2        /* Right key */
89876){
89877  const u8 *aKey1 = (const u8*)pKey1;
89878  int serial_type;
89879  int res;
89880
89881  assert( pPKey2->aMem[0].flags & MEM_Str );
89882  assert( pPKey2->aMem[0].n == pPKey2->n );
89883  assert( pPKey2->aMem[0].z == pPKey2->u.z );
89884  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
89885  serial_type = (signed char)(aKey1[1]);
89886
89887vrcs_restart:
89888  if( serial_type<12 ){
89889    if( serial_type<0 ){
89890      sqlite3GetVarint32(&aKey1[1], (u32*)&serial_type);
89891      if( serial_type>=12 ) goto vrcs_restart;
89892      assert( CORRUPT_DB );
89893    }
89894    res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
89895  }else if( !(serial_type & 0x01) ){
89896    res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
89897  }else{
89898    int nCmp;
89899    int nStr;
89900    int szHdr = aKey1[0];
89901
89902    nStr = (serial_type-12) / 2;
89903    if( (szHdr + nStr) > nKey1 ){
89904      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
89905      return 0;    /* Corruption */
89906    }
89907    nCmp = MIN( pPKey2->n, nStr );
89908    res = memcmp(&aKey1[szHdr], pPKey2->u.z, nCmp);
89909
89910    if( res>0 ){
89911      res = pPKey2->r2;
89912    }else if( res<0 ){
89913      res = pPKey2->r1;
89914    }else{
89915      res = nStr - pPKey2->n;
89916      if( res==0 ){
89917        if( pPKey2->nField>1 ){
89918          res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
89919        }else{
89920          res = pPKey2->default_rc;
89921          pPKey2->eqSeen = 1;
89922        }
89923      }else if( res>0 ){
89924        res = pPKey2->r2;
89925      }else{
89926        res = pPKey2->r1;
89927      }
89928    }
89929  }
89930
89931  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
89932       || CORRUPT_DB
89933       || pPKey2->pKeyInfo->db->mallocFailed
89934  );
89935  return res;
89936}
89937
89938/*
89939** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
89940** suitable for comparing serialized records to the unpacked record passed
89941** as the only argument.
89942*/
89943SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
89944  /* varintRecordCompareInt() and varintRecordCompareString() both assume
89945  ** that the size-of-header varint that occurs at the start of each record
89946  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
89947  ** also assumes that it is safe to overread a buffer by at least the
89948  ** maximum possible legal header size plus 8 bytes. Because there is
89949  ** guaranteed to be at least 74 (but not 136) bytes of padding following each
89950  ** buffer passed to varintRecordCompareInt() this makes it convenient to
89951  ** limit the size of the header to 64 bytes in cases where the first field
89952  ** is an integer.
89953  **
89954  ** The easiest way to enforce this limit is to consider only records with
89955  ** 13 fields or less. If the first field is an integer, the maximum legal
89956  ** header size is (12*5 + 1 + 1) bytes.  */
89957  if( p->pKeyInfo->nAllField<=13 ){
89958    int flags = p->aMem[0].flags;
89959    if( p->pKeyInfo->aSortFlags[0] ){
89960      if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){
89961        return sqlite3VdbeRecordCompare;
89962      }
89963      p->r1 = 1;
89964      p->r2 = -1;
89965    }else{
89966      p->r1 = -1;
89967      p->r2 = 1;
89968    }
89969    if( (flags & MEM_Int) ){
89970      p->u.i = p->aMem[0].u.i;
89971      return vdbeRecordCompareInt;
89972    }
89973    testcase( flags & MEM_Real );
89974    testcase( flags & MEM_Null );
89975    testcase( flags & MEM_Blob );
89976    if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0
89977     && p->pKeyInfo->aColl[0]==0
89978    ){
89979      assert( flags & MEM_Str );
89980      p->u.z = p->aMem[0].z;
89981      p->n = p->aMem[0].n;
89982      return vdbeRecordCompareString;
89983    }
89984  }
89985
89986  return sqlite3VdbeRecordCompare;
89987}
89988
89989/*
89990** pCur points at an index entry created using the OP_MakeRecord opcode.
89991** Read the rowid (the last field in the record) and store it in *rowid.
89992** Return SQLITE_OK if everything works, or an error code otherwise.
89993**
89994** pCur might be pointing to text obtained from a corrupt database file.
89995** So the content cannot be trusted.  Do appropriate checks on the content.
89996*/
89997SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
89998  i64 nCellKey = 0;
89999  int rc;
90000  u32 szHdr;        /* Size of the header */
90001  u32 typeRowid;    /* Serial type of the rowid */
90002  u32 lenRowid;     /* Size of the rowid */
90003  Mem m, v;
90004
90005  /* Get the size of the index entry.  Only indices entries of less
90006  ** than 2GiB are support - anything large must be database corruption.
90007  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
90008  ** this code can safely assume that nCellKey is 32-bits
90009  */
90010  assert( sqlite3BtreeCursorIsValid(pCur) );
90011  nCellKey = sqlite3BtreePayloadSize(pCur);
90012  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
90013
90014  /* Read in the complete content of the index entry */
90015  sqlite3VdbeMemInit(&m, db, 0);
90016  rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
90017  if( rc ){
90018    return rc;
90019  }
90020
90021  /* The index entry must begin with a header size */
90022  getVarint32NR((u8*)m.z, szHdr);
90023  testcase( szHdr==3 );
90024  testcase( szHdr==(u32)m.n );
90025  testcase( szHdr>0x7fffffff );
90026  assert( m.n>=0 );
90027  if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
90028    goto idx_rowid_corruption;
90029  }
90030
90031  /* The last field of the index should be an integer - the ROWID.
90032  ** Verify that the last entry really is an integer. */
90033  getVarint32NR((u8*)&m.z[szHdr-1], typeRowid);
90034  testcase( typeRowid==1 );
90035  testcase( typeRowid==2 );
90036  testcase( typeRowid==3 );
90037  testcase( typeRowid==4 );
90038  testcase( typeRowid==5 );
90039  testcase( typeRowid==6 );
90040  testcase( typeRowid==8 );
90041  testcase( typeRowid==9 );
90042  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
90043    goto idx_rowid_corruption;
90044  }
90045  lenRowid = sqlite3SmallTypeSizes[typeRowid];
90046  testcase( (u32)m.n==szHdr+lenRowid );
90047  if( unlikely((u32)m.n<szHdr+lenRowid) ){
90048    goto idx_rowid_corruption;
90049  }
90050
90051  /* Fetch the integer off the end of the index record */
90052  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
90053  *rowid = v.u.i;
90054  sqlite3VdbeMemReleaseMalloc(&m);
90055  return SQLITE_OK;
90056
90057  /* Jump here if database corruption is detected after m has been
90058  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
90059idx_rowid_corruption:
90060  testcase( m.szMalloc!=0 );
90061  sqlite3VdbeMemReleaseMalloc(&m);
90062  return SQLITE_CORRUPT_BKPT;
90063}
90064
90065/*
90066** Compare the key of the index entry that cursor pC is pointing to against
90067** the key string in pUnpacked.  Write into *pRes a number
90068** that is negative, zero, or positive if pC is less than, equal to,
90069** or greater than pUnpacked.  Return SQLITE_OK on success.
90070**
90071** pUnpacked is either created without a rowid or is truncated so that it
90072** omits the rowid at the end.  The rowid at the end of the index entry
90073** is ignored as well.  Hence, this routine only compares the prefixes
90074** of the keys prior to the final rowid, not the entire key.
90075*/
90076SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
90077  sqlite3 *db,                     /* Database connection */
90078  VdbeCursor *pC,                  /* The cursor to compare against */
90079  UnpackedRecord *pUnpacked,       /* Unpacked version of key */
90080  int *res                         /* Write the comparison result here */
90081){
90082  i64 nCellKey = 0;
90083  int rc;
90084  BtCursor *pCur;
90085  Mem m;
90086
90087  assert( pC->eCurType==CURTYPE_BTREE );
90088  pCur = pC->uc.pCursor;
90089  assert( sqlite3BtreeCursorIsValid(pCur) );
90090  nCellKey = sqlite3BtreePayloadSize(pCur);
90091  /* nCellKey will always be between 0 and 0xffffffff because of the way
90092  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
90093  if( nCellKey<=0 || nCellKey>0x7fffffff ){
90094    *res = 0;
90095    return SQLITE_CORRUPT_BKPT;
90096  }
90097  sqlite3VdbeMemInit(&m, db, 0);
90098  rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
90099  if( rc ){
90100    return rc;
90101  }
90102  *res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);
90103  sqlite3VdbeMemReleaseMalloc(&m);
90104  return SQLITE_OK;
90105}
90106
90107/*
90108** This routine sets the value to be returned by subsequent calls to
90109** sqlite3_changes() on the database handle 'db'.
90110*/
90111SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, i64 nChange){
90112  assert( sqlite3_mutex_held(db->mutex) );
90113  db->nChange = nChange;
90114  db->nTotalChange += nChange;
90115}
90116
90117/*
90118** Set a flag in the vdbe to update the change counter when it is finalised
90119** or reset.
90120*/
90121SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
90122  v->changeCntOn = 1;
90123}
90124
90125/*
90126** Mark every prepared statement associated with a database connection
90127** as expired.
90128**
90129** An expired statement means that recompilation of the statement is
90130** recommend.  Statements expire when things happen that make their
90131** programs obsolete.  Removing user-defined functions or collating
90132** sequences, or changing an authorization function are the types of
90133** things that make prepared statements obsolete.
90134**
90135** If iCode is 1, then expiration is advisory.  The statement should
90136** be reprepared before being restarted, but if it is already running
90137** it is allowed to run to completion.
90138**
90139** Internally, this function just sets the Vdbe.expired flag on all
90140** prepared statements.  The flag is set to 1 for an immediate expiration
90141** and set to 2 for an advisory expiration.
90142*/
90143SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){
90144  Vdbe *p;
90145  for(p = db->pVdbe; p; p=p->pVNext){
90146    p->expired = iCode+1;
90147  }
90148}
90149
90150/*
90151** Return the database associated with the Vdbe.
90152*/
90153SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
90154  return v->db;
90155}
90156
90157/*
90158** Return the SQLITE_PREPARE flags for a Vdbe.
90159*/
90160SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
90161  return v->prepFlags;
90162}
90163
90164/*
90165** Return a pointer to an sqlite3_value structure containing the value bound
90166** parameter iVar of VM v. Except, if the value is an SQL NULL, return
90167** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
90168** constants) to the value before returning it.
90169**
90170** The returned value must be freed by the caller using sqlite3ValueFree().
90171*/
90172SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
90173  assert( iVar>0 );
90174  if( v ){
90175    Mem *pMem = &v->aVar[iVar-1];
90176    assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
90177    if( 0==(pMem->flags & MEM_Null) ){
90178      sqlite3_value *pRet = sqlite3ValueNew(v->db);
90179      if( pRet ){
90180        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
90181        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
90182      }
90183      return pRet;
90184    }
90185  }
90186  return 0;
90187}
90188
90189/*
90190** Configure SQL variable iVar so that binding a new value to it signals
90191** to sqlite3_reoptimize() that re-preparing the statement may result
90192** in a better query plan.
90193*/
90194SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
90195  assert( iVar>0 );
90196  assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
90197  if( iVar>=32 ){
90198    v->expmask |= 0x80000000;
90199  }else{
90200    v->expmask |= ((u32)1 << (iVar-1));
90201  }
90202}
90203
90204/*
90205** Cause a function to throw an error if it was call from OP_PureFunc
90206** rather than OP_Function.
90207**
90208** OP_PureFunc means that the function must be deterministic, and should
90209** throw an error if it is given inputs that would make it non-deterministic.
90210** This routine is invoked by date/time functions that use non-deterministic
90211** features such as 'now'.
90212*/
90213SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
90214  const VdbeOp *pOp;
90215#ifdef SQLITE_ENABLE_STAT4
90216  if( pCtx->pVdbe==0 ) return 1;
90217#endif
90218  pOp = pCtx->pVdbe->aOp + pCtx->iOp;
90219  if( pOp->opcode==OP_PureFunc ){
90220    const char *zContext;
90221    char *zMsg;
90222    if( pOp->p5 & NC_IsCheck ){
90223      zContext = "a CHECK constraint";
90224    }else if( pOp->p5 & NC_GenCol ){
90225      zContext = "a generated column";
90226    }else{
90227      zContext = "an index";
90228    }
90229    zMsg = sqlite3_mprintf("non-deterministic use of %s() in %s",
90230                           pCtx->pFunc->zName, zContext);
90231    sqlite3_result_error(pCtx, zMsg, -1);
90232    sqlite3_free(zMsg);
90233    return 0;
90234  }
90235  return 1;
90236}
90237
90238#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
90239/*
90240** This Walker callback is used to help verify that calls to
90241** sqlite3BtreeCursorHint() with opcode BTREE_HINT_RANGE have
90242** byte-code register values correctly initialized.
90243*/
90244SQLITE_PRIVATE int sqlite3CursorRangeHintExprCheck(Walker *pWalker, Expr *pExpr){
90245  if( pExpr->op==TK_REGISTER ){
90246    assert( (pWalker->u.aMem[pExpr->iTable].flags & MEM_Undefined)==0 );
90247  }
90248  return WRC_Continue;
90249}
90250#endif /* SQLITE_ENABLE_CURSOR_HINTS && SQLITE_DEBUG */
90251
90252#ifndef SQLITE_OMIT_VIRTUALTABLE
90253/*
90254** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
90255** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
90256** in memory obtained from sqlite3DbMalloc).
90257*/
90258SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
90259  if( pVtab->zErrMsg ){
90260    sqlite3 *db = p->db;
90261    sqlite3DbFree(db, p->zErrMsg);
90262    p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
90263    sqlite3_free(pVtab->zErrMsg);
90264    pVtab->zErrMsg = 0;
90265  }
90266}
90267#endif /* SQLITE_OMIT_VIRTUALTABLE */
90268
90269#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
90270
90271/*
90272** If the second argument is not NULL, release any allocations associated
90273** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
90274** structure itself, using sqlite3DbFree().
90275**
90276** This function is used to free UnpackedRecord structures allocated by
90277** the vdbeUnpackRecord() function found in vdbeapi.c.
90278*/
90279static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
90280  assert( db!=0 );
90281  if( p ){
90282    int i;
90283    for(i=0; i<nField; i++){
90284      Mem *pMem = &p->aMem[i];
90285      if( pMem->zMalloc ) sqlite3VdbeMemReleaseMalloc(pMem);
90286    }
90287    sqlite3DbNNFreeNN(db, p);
90288  }
90289}
90290#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
90291
90292#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
90293/*
90294** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
90295** then cursor passed as the second argument should point to the row about
90296** to be update or deleted. If the application calls sqlite3_preupdate_old(),
90297** the required value will be read from the row the cursor points to.
90298*/
90299SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
90300  Vdbe *v,                        /* Vdbe pre-update hook is invoked by */
90301  VdbeCursor *pCsr,               /* Cursor to grab old.* values from */
90302  int op,                         /* SQLITE_INSERT, UPDATE or DELETE */
90303  const char *zDb,                /* Database name */
90304  Table *pTab,                    /* Modified table */
90305  i64 iKey1,                      /* Initial key value */
90306  int iReg,                       /* Register for new.* record */
90307  int iBlobWrite
90308){
90309  sqlite3 *db = v->db;
90310  i64 iKey2;
90311  PreUpdate preupdate;
90312  const char *zTbl = pTab->zName;
90313  static const u8 fakeSortOrder = 0;
90314#ifdef SQLITE_DEBUG
90315  int nRealCol;
90316  if( pTab->tabFlags & TF_WithoutRowid ){
90317    nRealCol = sqlite3PrimaryKeyIndex(pTab)->nColumn;
90318  }else if( pTab->tabFlags & TF_HasVirtual ){
90319    nRealCol = pTab->nNVCol;
90320  }else{
90321    nRealCol = pTab->nCol;
90322  }
90323#endif
90324
90325  assert( db->pPreUpdate==0 );
90326  memset(&preupdate, 0, sizeof(PreUpdate));
90327  if( HasRowid(pTab)==0 ){
90328    iKey1 = iKey2 = 0;
90329    preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
90330  }else{
90331    if( op==SQLITE_UPDATE ){
90332      iKey2 = v->aMem[iReg].u.i;
90333    }else{
90334      iKey2 = iKey1;
90335    }
90336  }
90337
90338  assert( pCsr!=0 );
90339  assert( pCsr->eCurType==CURTYPE_BTREE );
90340  assert( pCsr->nField==nRealCol
90341       || (pCsr->nField==nRealCol+1 && op==SQLITE_DELETE && iReg==-1)
90342  );
90343
90344  preupdate.v = v;
90345  preupdate.pCsr = pCsr;
90346  preupdate.op = op;
90347  preupdate.iNewReg = iReg;
90348  preupdate.keyinfo.db = db;
90349  preupdate.keyinfo.enc = ENC(db);
90350  preupdate.keyinfo.nKeyField = pTab->nCol;
90351  preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder;
90352  preupdate.iKey1 = iKey1;
90353  preupdate.iKey2 = iKey2;
90354  preupdate.pTab = pTab;
90355  preupdate.iBlobWrite = iBlobWrite;
90356
90357  db->pPreUpdate = &preupdate;
90358  db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
90359  db->pPreUpdate = 0;
90360  sqlite3DbFree(db, preupdate.aRecord);
90361  vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
90362  vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
90363  if( preupdate.aNew ){
90364    int i;
90365    for(i=0; i<pCsr->nField; i++){
90366      sqlite3VdbeMemRelease(&preupdate.aNew[i]);
90367    }
90368    sqlite3DbNNFreeNN(db, preupdate.aNew);
90369  }
90370}
90371#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
90372
90373/************** End of vdbeaux.c *********************************************/
90374/************** Begin file vdbeapi.c *****************************************/
90375/*
90376** 2004 May 26
90377**
90378** The author disclaims copyright to this source code.  In place of
90379** a legal notice, here is a blessing:
90380**
90381**    May you do good and not evil.
90382**    May you find forgiveness for yourself and forgive others.
90383**    May you share freely, never taking more than you give.
90384**
90385*************************************************************************
90386**
90387** This file contains code use to implement APIs that are part of the
90388** VDBE.
90389*/
90390/* #include "sqliteInt.h" */
90391/* #include "vdbeInt.h" */
90392/* #include "opcodes.h" */
90393
90394#ifndef SQLITE_OMIT_DEPRECATED
90395/*
90396** Return TRUE (non-zero) of the statement supplied as an argument needs
90397** to be recompiled.  A statement needs to be recompiled whenever the
90398** execution environment changes in a way that would alter the program
90399** that sqlite3_prepare() generates.  For example, if new functions or
90400** collating sequences are registered or if an authorizer function is
90401** added or changed.
90402*/
90403SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
90404  Vdbe *p = (Vdbe*)pStmt;
90405  return p==0 || p->expired;
90406}
90407#endif
90408
90409/*
90410** Check on a Vdbe to make sure it has not been finalized.  Log
90411** an error and return true if it has been finalized (or is otherwise
90412** invalid).  Return false if it is ok.
90413*/
90414static int vdbeSafety(Vdbe *p){
90415  if( p->db==0 ){
90416    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
90417    return 1;
90418  }else{
90419    return 0;
90420  }
90421}
90422static int vdbeSafetyNotNull(Vdbe *p){
90423  if( p==0 ){
90424    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
90425    return 1;
90426  }else{
90427    return vdbeSafety(p);
90428  }
90429}
90430
90431#ifndef SQLITE_OMIT_TRACE
90432/*
90433** Invoke the profile callback.  This routine is only called if we already
90434** know that the profile callback is defined and needs to be invoked.
90435*/
90436static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
90437  sqlite3_int64 iNow;
90438  sqlite3_int64 iElapse;
90439  assert( p->startTime>0 );
90440  assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 );
90441  assert( db->init.busy==0 );
90442  assert( p->zSql!=0 );
90443  sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
90444  iElapse = (iNow - p->startTime)*1000000;
90445#ifndef SQLITE_OMIT_DEPRECATED
90446  if( db->xProfile ){
90447    db->xProfile(db->pProfileArg, p->zSql, iElapse);
90448  }
90449#endif
90450  if( db->mTrace & SQLITE_TRACE_PROFILE ){
90451    db->trace.xV2(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
90452  }
90453  p->startTime = 0;
90454}
90455/*
90456** The checkProfileCallback(DB,P) macro checks to see if a profile callback
90457** is needed, and it invokes the callback if it is needed.
90458*/
90459# define checkProfileCallback(DB,P) \
90460   if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
90461#else
90462# define checkProfileCallback(DB,P)  /*no-op*/
90463#endif
90464
90465/*
90466** The following routine destroys a virtual machine that is created by
90467** the sqlite3_compile() routine. The integer returned is an SQLITE_
90468** success/failure code that describes the result of executing the virtual
90469** machine.
90470**
90471** This routine sets the error code and string returned by
90472** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
90473*/
90474SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
90475  int rc;
90476  if( pStmt==0 ){
90477    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
90478    ** pointer is a harmless no-op. */
90479    rc = SQLITE_OK;
90480  }else{
90481    Vdbe *v = (Vdbe*)pStmt;
90482    sqlite3 *db = v->db;
90483    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
90484    sqlite3_mutex_enter(db->mutex);
90485    checkProfileCallback(db, v);
90486    assert( v->eVdbeState>=VDBE_READY_STATE );
90487    rc = sqlite3VdbeReset(v);
90488    sqlite3VdbeDelete(v);
90489    rc = sqlite3ApiExit(db, rc);
90490    sqlite3LeaveMutexAndCloseZombie(db);
90491  }
90492  return rc;
90493}
90494
90495/*
90496** Terminate the current execution of an SQL statement and reset it
90497** back to its starting state so that it can be reused. A success code from
90498** the prior execution is returned.
90499**
90500** This routine sets the error code and string returned by
90501** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
90502*/
90503SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
90504  int rc;
90505  if( pStmt==0 ){
90506    rc = SQLITE_OK;
90507  }else{
90508    Vdbe *v = (Vdbe*)pStmt;
90509    sqlite3 *db = v->db;
90510    sqlite3_mutex_enter(db->mutex);
90511    checkProfileCallback(db, v);
90512    rc = sqlite3VdbeReset(v);
90513    sqlite3VdbeRewind(v);
90514    assert( (rc & (db->errMask))==rc );
90515    rc = sqlite3ApiExit(db, rc);
90516    sqlite3_mutex_leave(db->mutex);
90517  }
90518  return rc;
90519}
90520
90521/*
90522** Set all the parameters in the compiled SQL statement to NULL.
90523*/
90524SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
90525  int i;
90526  int rc = SQLITE_OK;
90527  Vdbe *p = (Vdbe*)pStmt;
90528#if SQLITE_THREADSAFE
90529  sqlite3_mutex *mutex;
90530#endif
90531#ifdef SQLITE_ENABLE_API_ARMOR
90532  if( pStmt==0 ){
90533    return SQLITE_MISUSE_BKPT;
90534  }
90535#endif
90536#if SQLITE_THREADSAFE
90537  mutex = p->db->mutex;
90538#endif
90539  sqlite3_mutex_enter(mutex);
90540  for(i=0; i<p->nVar; i++){
90541    sqlite3VdbeMemRelease(&p->aVar[i]);
90542    p->aVar[i].flags = MEM_Null;
90543  }
90544  assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
90545  if( p->expmask ){
90546    p->expired = 1;
90547  }
90548  sqlite3_mutex_leave(mutex);
90549  return rc;
90550}
90551
90552
90553/**************************** sqlite3_value_  *******************************
90554** The following routines extract information from a Mem or sqlite3_value
90555** structure.
90556*/
90557SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
90558  Mem *p = (Mem*)pVal;
90559  if( p->flags & (MEM_Blob|MEM_Str) ){
90560    if( ExpandBlob(p)!=SQLITE_OK ){
90561      assert( p->flags==MEM_Null && p->z==0 );
90562      return 0;
90563    }
90564    p->flags |= MEM_Blob;
90565    return p->n ? p->z : 0;
90566  }else{
90567    return sqlite3_value_text(pVal);
90568  }
90569}
90570SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
90571  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
90572}
90573SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
90574  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
90575}
90576SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
90577  return sqlite3VdbeRealValue((Mem*)pVal);
90578}
90579SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
90580  return (int)sqlite3VdbeIntValue((Mem*)pVal);
90581}
90582SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
90583  return sqlite3VdbeIntValue((Mem*)pVal);
90584}
90585SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
90586  Mem *pMem = (Mem*)pVal;
90587  return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
90588}
90589SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
90590  Mem *p = (Mem*)pVal;
90591  if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
90592                 (MEM_Null|MEM_Term|MEM_Subtype)
90593   && zPType!=0
90594   && p->eSubtype=='p'
90595   && strcmp(p->u.zPType, zPType)==0
90596  ){
90597    return (void*)p->z;
90598  }else{
90599    return 0;
90600  }
90601}
90602SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
90603  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
90604}
90605#ifndef SQLITE_OMIT_UTF16
90606SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
90607  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
90608}
90609SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
90610  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
90611}
90612SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
90613  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
90614}
90615#endif /* SQLITE_OMIT_UTF16 */
90616/* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
90617** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
90618** point number string BLOB NULL
90619*/
90620SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
90621  static const u8 aType[] = {
90622     SQLITE_BLOB,     /* 0x00 (not possible) */
90623     SQLITE_NULL,     /* 0x01 NULL */
90624     SQLITE_TEXT,     /* 0x02 TEXT */
90625     SQLITE_NULL,     /* 0x03 (not possible) */
90626     SQLITE_INTEGER,  /* 0x04 INTEGER */
90627     SQLITE_NULL,     /* 0x05 (not possible) */
90628     SQLITE_INTEGER,  /* 0x06 INTEGER + TEXT */
90629     SQLITE_NULL,     /* 0x07 (not possible) */
90630     SQLITE_FLOAT,    /* 0x08 FLOAT */
90631     SQLITE_NULL,     /* 0x09 (not possible) */
90632     SQLITE_FLOAT,    /* 0x0a FLOAT + TEXT */
90633     SQLITE_NULL,     /* 0x0b (not possible) */
90634     SQLITE_INTEGER,  /* 0x0c (not possible) */
90635     SQLITE_NULL,     /* 0x0d (not possible) */
90636     SQLITE_INTEGER,  /* 0x0e (not possible) */
90637     SQLITE_NULL,     /* 0x0f (not possible) */
90638     SQLITE_BLOB,     /* 0x10 BLOB */
90639     SQLITE_NULL,     /* 0x11 (not possible) */
90640     SQLITE_TEXT,     /* 0x12 (not possible) */
90641     SQLITE_NULL,     /* 0x13 (not possible) */
90642     SQLITE_INTEGER,  /* 0x14 INTEGER + BLOB */
90643     SQLITE_NULL,     /* 0x15 (not possible) */
90644     SQLITE_INTEGER,  /* 0x16 (not possible) */
90645     SQLITE_NULL,     /* 0x17 (not possible) */
90646     SQLITE_FLOAT,    /* 0x18 FLOAT + BLOB */
90647     SQLITE_NULL,     /* 0x19 (not possible) */
90648     SQLITE_FLOAT,    /* 0x1a (not possible) */
90649     SQLITE_NULL,     /* 0x1b (not possible) */
90650     SQLITE_INTEGER,  /* 0x1c (not possible) */
90651     SQLITE_NULL,     /* 0x1d (not possible) */
90652     SQLITE_INTEGER,  /* 0x1e (not possible) */
90653     SQLITE_NULL,     /* 0x1f (not possible) */
90654     SQLITE_FLOAT,    /* 0x20 INTREAL */
90655     SQLITE_NULL,     /* 0x21 (not possible) */
90656     SQLITE_FLOAT,    /* 0x22 INTREAL + TEXT */
90657     SQLITE_NULL,     /* 0x23 (not possible) */
90658     SQLITE_FLOAT,    /* 0x24 (not possible) */
90659     SQLITE_NULL,     /* 0x25 (not possible) */
90660     SQLITE_FLOAT,    /* 0x26 (not possible) */
90661     SQLITE_NULL,     /* 0x27 (not possible) */
90662     SQLITE_FLOAT,    /* 0x28 (not possible) */
90663     SQLITE_NULL,     /* 0x29 (not possible) */
90664     SQLITE_FLOAT,    /* 0x2a (not possible) */
90665     SQLITE_NULL,     /* 0x2b (not possible) */
90666     SQLITE_FLOAT,    /* 0x2c (not possible) */
90667     SQLITE_NULL,     /* 0x2d (not possible) */
90668     SQLITE_FLOAT,    /* 0x2e (not possible) */
90669     SQLITE_NULL,     /* 0x2f (not possible) */
90670     SQLITE_BLOB,     /* 0x30 (not possible) */
90671     SQLITE_NULL,     /* 0x31 (not possible) */
90672     SQLITE_TEXT,     /* 0x32 (not possible) */
90673     SQLITE_NULL,     /* 0x33 (not possible) */
90674     SQLITE_FLOAT,    /* 0x34 (not possible) */
90675     SQLITE_NULL,     /* 0x35 (not possible) */
90676     SQLITE_FLOAT,    /* 0x36 (not possible) */
90677     SQLITE_NULL,     /* 0x37 (not possible) */
90678     SQLITE_FLOAT,    /* 0x38 (not possible) */
90679     SQLITE_NULL,     /* 0x39 (not possible) */
90680     SQLITE_FLOAT,    /* 0x3a (not possible) */
90681     SQLITE_NULL,     /* 0x3b (not possible) */
90682     SQLITE_FLOAT,    /* 0x3c (not possible) */
90683     SQLITE_NULL,     /* 0x3d (not possible) */
90684     SQLITE_FLOAT,    /* 0x3e (not possible) */
90685     SQLITE_NULL,     /* 0x3f (not possible) */
90686  };
90687#ifdef SQLITE_DEBUG
90688  {
90689    int eType = SQLITE_BLOB;
90690    if( pVal->flags & MEM_Null ){
90691      eType = SQLITE_NULL;
90692    }else if( pVal->flags & (MEM_Real|MEM_IntReal) ){
90693      eType = SQLITE_FLOAT;
90694    }else if( pVal->flags & MEM_Int ){
90695      eType = SQLITE_INTEGER;
90696    }else if( pVal->flags & MEM_Str ){
90697      eType = SQLITE_TEXT;
90698    }
90699    assert( eType == aType[pVal->flags&MEM_AffMask] );
90700  }
90701#endif
90702  return aType[pVal->flags&MEM_AffMask];
90703}
90704SQLITE_API int sqlite3_value_encoding(sqlite3_value *pVal){
90705  return pVal->enc;
90706}
90707
90708/* Return true if a parameter to xUpdate represents an unchanged column */
90709SQLITE_API int sqlite3_value_nochange(sqlite3_value *pVal){
90710  return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
90711}
90712
90713/* Return true if a parameter value originated from an sqlite3_bind() */
90714SQLITE_API int sqlite3_value_frombind(sqlite3_value *pVal){
90715  return (pVal->flags&MEM_FromBind)!=0;
90716}
90717
90718/* Make a copy of an sqlite3_value object
90719*/
90720SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
90721  sqlite3_value *pNew;
90722  if( pOrig==0 ) return 0;
90723  pNew = sqlite3_malloc( sizeof(*pNew) );
90724  if( pNew==0 ) return 0;
90725  memset(pNew, 0, sizeof(*pNew));
90726  memcpy(pNew, pOrig, MEMCELLSIZE);
90727  pNew->flags &= ~MEM_Dyn;
90728  pNew->db = 0;
90729  if( pNew->flags&(MEM_Str|MEM_Blob) ){
90730    pNew->flags &= ~(MEM_Static|MEM_Dyn);
90731    pNew->flags |= MEM_Ephem;
90732    if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
90733      sqlite3ValueFree(pNew);
90734      pNew = 0;
90735    }
90736  }else if( pNew->flags & MEM_Null ){
90737    /* Do not duplicate pointer values */
90738    pNew->flags &= ~(MEM_Term|MEM_Subtype);
90739  }
90740  return pNew;
90741}
90742
90743/* Destroy an sqlite3_value object previously obtained from
90744** sqlite3_value_dup().
90745*/
90746SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
90747  sqlite3ValueFree(pOld);
90748}
90749
90750
90751/**************************** sqlite3_result_  *******************************
90752** The following routines are used by user-defined functions to specify
90753** the function result.
90754**
90755** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
90756** result as a string or blob.  Appropriate errors are set if the string/blob
90757** is too big or if an OOM occurs.
90758**
90759** The invokeValueDestructor(P,X) routine invokes destructor function X()
90760** on value P if P is not going to be used and need to be destroyed.
90761*/
90762static void setResultStrOrError(
90763  sqlite3_context *pCtx,  /* Function context */
90764  const char *z,          /* String pointer */
90765  int n,                  /* Bytes in string, or negative */
90766  u8 enc,                 /* Encoding of z.  0 for BLOBs */
90767  void (*xDel)(void*)     /* Destructor function */
90768){
90769  Mem *pOut = pCtx->pOut;
90770  int rc = sqlite3VdbeMemSetStr(pOut, z, n, enc, xDel);
90771  if( rc ){
90772    if( rc==SQLITE_TOOBIG ){
90773      sqlite3_result_error_toobig(pCtx);
90774    }else{
90775      /* The only errors possible from sqlite3VdbeMemSetStr are
90776      ** SQLITE_TOOBIG and SQLITE_NOMEM */
90777      assert( rc==SQLITE_NOMEM );
90778      sqlite3_result_error_nomem(pCtx);
90779    }
90780    return;
90781  }
90782  sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
90783  if( sqlite3VdbeMemTooBig(pOut) ){
90784    sqlite3_result_error_toobig(pCtx);
90785  }
90786}
90787static int invokeValueDestructor(
90788  const void *p,             /* Value to destroy */
90789  void (*xDel)(void*),       /* The destructor */
90790  sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if not NULL */
90791){
90792  assert( xDel!=SQLITE_DYNAMIC );
90793  if( xDel==0 ){
90794    /* noop */
90795  }else if( xDel==SQLITE_TRANSIENT ){
90796    /* noop */
90797  }else{
90798    xDel((void*)p);
90799  }
90800#ifdef SQLITE_ENABLE_API_ARMOR
90801  if( pCtx!=0 ){
90802    sqlite3_result_error_toobig(pCtx);
90803  }
90804#else
90805  assert( pCtx!=0 );
90806  sqlite3_result_error_toobig(pCtx);
90807#endif
90808  return SQLITE_TOOBIG;
90809}
90810SQLITE_API void sqlite3_result_blob(
90811  sqlite3_context *pCtx,
90812  const void *z,
90813  int n,
90814  void (*xDel)(void *)
90815){
90816#ifdef SQLITE_ENABLE_API_ARMOR
90817  if( pCtx==0 || n<0 ){
90818    invokeValueDestructor(z, xDel, pCtx);
90819    return;
90820  }
90821#endif
90822  assert( n>=0 );
90823  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
90824  setResultStrOrError(pCtx, z, n, 0, xDel);
90825}
90826SQLITE_API void sqlite3_result_blob64(
90827  sqlite3_context *pCtx,
90828  const void *z,
90829  sqlite3_uint64 n,
90830  void (*xDel)(void *)
90831){
90832  assert( xDel!=SQLITE_DYNAMIC );
90833#ifdef SQLITE_ENABLE_API_ARMOR
90834  if( pCtx==0 ){
90835    invokeValueDestructor(z, xDel, 0);
90836    return;
90837  }
90838#endif
90839  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
90840  if( n>0x7fffffff ){
90841    (void)invokeValueDestructor(z, xDel, pCtx);
90842  }else{
90843    setResultStrOrError(pCtx, z, (int)n, 0, xDel);
90844  }
90845}
90846SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
90847#ifdef SQLITE_ENABLE_API_ARMOR
90848  if( pCtx==0 ) return;
90849#endif
90850  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
90851  sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
90852}
90853SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
90854#ifdef SQLITE_ENABLE_API_ARMOR
90855  if( pCtx==0 ) return;
90856#endif
90857  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
90858  pCtx->isError = SQLITE_ERROR;
90859  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
90860}
90861#ifndef SQLITE_OMIT_UTF16
90862SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
90863#ifdef SQLITE_ENABLE_API_ARMOR
90864  if( pCtx==0 ) return;
90865#endif
90866  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
90867  pCtx->isError = SQLITE_ERROR;
90868  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
90869}
90870#endif
90871SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
90872#ifdef SQLITE_ENABLE_API_ARMOR
90873  if( pCtx==0 ) return;
90874#endif
90875  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
90876  sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
90877}
90878SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
90879#ifdef SQLITE_ENABLE_API_ARMOR
90880  if( pCtx==0 ) return;
90881#endif
90882  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
90883  sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
90884}
90885SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
90886#ifdef SQLITE_ENABLE_API_ARMOR
90887  if( pCtx==0 ) return;
90888#endif
90889  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
90890  sqlite3VdbeMemSetNull(pCtx->pOut);
90891}
90892SQLITE_API void sqlite3_result_pointer(
90893  sqlite3_context *pCtx,
90894  void *pPtr,
90895  const char *zPType,
90896  void (*xDestructor)(void*)
90897){
90898  Mem *pOut;
90899#ifdef SQLITE_ENABLE_API_ARMOR
90900  if( pCtx==0 ){
90901    invokeValueDestructor(pPtr, xDestructor, 0);
90902    return;
90903  }
90904#endif
90905  pOut = pCtx->pOut;
90906  assert( sqlite3_mutex_held(pOut->db->mutex) );
90907  sqlite3VdbeMemRelease(pOut);
90908  pOut->flags = MEM_Null;
90909  sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
90910}
90911SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
90912  Mem *pOut;
90913#ifdef SQLITE_ENABLE_API_ARMOR
90914  if( pCtx==0 ) return;
90915#endif
90916#if defined(SQLITE_STRICT_SUBTYPE) && SQLITE_STRICT_SUBTYPE+0!=0
90917  if( pCtx->pFunc!=0
90918   && (pCtx->pFunc->funcFlags & SQLITE_RESULT_SUBTYPE)==0
90919  ){
90920    char zErr[200];
90921    sqlite3_snprintf(sizeof(zErr), zErr,
90922                     "misuse of sqlite3_result_subtype() by %s()",
90923                     pCtx->pFunc->zName);
90924    sqlite3_result_error(pCtx, zErr, -1);
90925    return;
90926  }
90927#endif /* SQLITE_STRICT_SUBTYPE */
90928  pOut = pCtx->pOut;
90929  assert( sqlite3_mutex_held(pOut->db->mutex) );
90930  pOut->eSubtype = eSubtype & 0xff;
90931  pOut->flags |= MEM_Subtype;
90932}
90933SQLITE_API void sqlite3_result_text(
90934  sqlite3_context *pCtx,
90935  const char *z,
90936  int n,
90937  void (*xDel)(void *)
90938){
90939#ifdef SQLITE_ENABLE_API_ARMOR
90940  if( pCtx==0 ){
90941    invokeValueDestructor(z, xDel, 0);
90942    return;
90943  }
90944#endif
90945  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
90946  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
90947}
90948SQLITE_API void sqlite3_result_text64(
90949  sqlite3_context *pCtx,
90950  const char *z,
90951  sqlite3_uint64 n,
90952  void (*xDel)(void *),
90953  unsigned char enc
90954){
90955#ifdef SQLITE_ENABLE_API_ARMOR
90956  if( pCtx==0 ){
90957    invokeValueDestructor(z, xDel, 0);
90958    return;
90959  }
90960#endif
90961  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
90962  assert( xDel!=SQLITE_DYNAMIC );
90963  if( enc!=SQLITE_UTF8 ){
90964    if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
90965    n &= ~(u64)1;
90966  }
90967  if( n>0x7fffffff ){
90968    (void)invokeValueDestructor(z, xDel, pCtx);
90969  }else{
90970    setResultStrOrError(pCtx, z, (int)n, enc, xDel);
90971    sqlite3VdbeMemZeroTerminateIfAble(pCtx->pOut);
90972  }
90973}
90974#ifndef SQLITE_OMIT_UTF16
90975SQLITE_API void sqlite3_result_text16(
90976  sqlite3_context *pCtx,
90977  const void *z,
90978  int n,
90979  void (*xDel)(void *)
90980){
90981  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
90982  setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16NATIVE, xDel);
90983}
90984SQLITE_API void sqlite3_result_text16be(
90985  sqlite3_context *pCtx,
90986  const void *z,
90987  int n,
90988  void (*xDel)(void *)
90989){
90990  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
90991  setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16BE, xDel);
90992}
90993SQLITE_API void sqlite3_result_text16le(
90994  sqlite3_context *pCtx,
90995  const void *z,
90996  int n,
90997  void (*xDel)(void *)
90998){
90999  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91000  setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16LE, xDel);
91001}
91002#endif /* SQLITE_OMIT_UTF16 */
91003SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
91004  Mem *pOut;
91005
91006#ifdef SQLITE_ENABLE_API_ARMOR
91007  if( pCtx==0 ) return;
91008  if( pValue==0 ){
91009    sqlite3_result_null(pCtx);
91010    return;
91011  }
91012#endif
91013  pOut = pCtx->pOut;
91014  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91015  sqlite3VdbeMemCopy(pOut, pValue);
91016  sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
91017  if( sqlite3VdbeMemTooBig(pOut) ){
91018    sqlite3_result_error_toobig(pCtx);
91019  }
91020}
91021SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
91022  sqlite3_result_zeroblob64(pCtx, n>0 ? n : 0);
91023}
91024SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
91025  Mem *pOut;
91026
91027#ifdef SQLITE_ENABLE_API_ARMOR
91028  if( pCtx==0 ) return SQLITE_MISUSE_BKPT;
91029#endif
91030  pOut = pCtx->pOut;
91031  assert( sqlite3_mutex_held(pOut->db->mutex) );
91032  if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
91033    sqlite3_result_error_toobig(pCtx);
91034    return SQLITE_TOOBIG;
91035  }
91036#ifndef SQLITE_OMIT_INCRBLOB
91037  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
91038  return SQLITE_OK;
91039#else
91040  return sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
91041#endif
91042}
91043SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
91044#ifdef SQLITE_ENABLE_API_ARMOR
91045  if( pCtx==0 ) return;
91046#endif
91047  pCtx->isError = errCode ? errCode : -1;
91048#ifdef SQLITE_DEBUG
91049  if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
91050#endif
91051  if( pCtx->pOut->flags & MEM_Null ){
91052    setResultStrOrError(pCtx, sqlite3ErrStr(errCode), -1, SQLITE_UTF8,
91053                        SQLITE_STATIC);
91054  }
91055}
91056
91057/* Force an SQLITE_TOOBIG error. */
91058SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
91059#ifdef SQLITE_ENABLE_API_ARMOR
91060  if( pCtx==0 ) return;
91061#endif
91062  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91063  pCtx->isError = SQLITE_TOOBIG;
91064  sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
91065                       SQLITE_UTF8, SQLITE_STATIC);
91066}
91067
91068/* An SQLITE_NOMEM error. */
91069SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
91070#ifdef SQLITE_ENABLE_API_ARMOR
91071  if( pCtx==0 ) return;
91072#endif
91073  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91074  sqlite3VdbeMemSetNull(pCtx->pOut);
91075  pCtx->isError = SQLITE_NOMEM_BKPT;
91076  sqlite3OomFault(pCtx->pOut->db);
91077}
91078
91079#ifndef SQLITE_UNTESTABLE
91080/* Force the INT64 value currently stored as the result to be
91081** a MEM_IntReal value.  See the SQLITE_TESTCTRL_RESULT_INTREAL
91082** test-control.
91083*/
91084SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context *pCtx){
91085  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91086  if( pCtx->pOut->flags & MEM_Int ){
91087    pCtx->pOut->flags &= ~MEM_Int;
91088    pCtx->pOut->flags |= MEM_IntReal;
91089  }
91090}
91091#endif
91092
91093
91094/*
91095** This function is called after a transaction has been committed. It
91096** invokes callbacks registered with sqlite3_wal_hook() as required.
91097*/
91098static int doWalCallbacks(sqlite3 *db){
91099  int rc = SQLITE_OK;
91100#ifndef SQLITE_OMIT_WAL
91101  int i;
91102  for(i=0; i<db->nDb; i++){
91103    Btree *pBt = db->aDb[i].pBt;
91104    if( pBt ){
91105      int nEntry;
91106      sqlite3BtreeEnter(pBt);
91107      nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
91108      sqlite3BtreeLeave(pBt);
91109      if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
91110        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
91111      }
91112    }
91113  }
91114#endif
91115  return rc;
91116}
91117
91118
91119/*
91120** Execute the statement pStmt, either until a row of data is ready, the
91121** statement is completely executed or an error occurs.
91122**
91123** This routine implements the bulk of the logic behind the sqlite_step()
91124** API.  The only thing omitted is the automatic recompile if a
91125** schema change has occurred.  That detail is handled by the
91126** outer sqlite3_step() wrapper procedure.
91127*/
91128static int sqlite3Step(Vdbe *p){
91129  sqlite3 *db;
91130  int rc;
91131
91132  assert(p);
91133  db = p->db;
91134  if( p->eVdbeState!=VDBE_RUN_STATE ){
91135    restart_step:
91136    if( p->eVdbeState==VDBE_READY_STATE ){
91137      if( p->expired ){
91138        p->rc = SQLITE_SCHEMA;
91139        rc = SQLITE_ERROR;
91140        if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
91141          /* If this statement was prepared using saved SQL and an
91142          ** error has occurred, then return the error code in p->rc to the
91143          ** caller. Set the error code in the database handle to the same
91144          ** value.
91145          */
91146          rc = sqlite3VdbeTransferError(p);
91147        }
91148        goto end_of_step;
91149      }
91150
91151      /* If there are no other statements currently running, then
91152      ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
91153      ** from interrupting a statement that has not yet started.
91154      */
91155      if( db->nVdbeActive==0 ){
91156        AtomicStore(&db->u1.isInterrupted, 0);
91157      }
91158
91159      assert( db->nVdbeWrite>0 || db->autoCommit==0
91160          || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
91161      );
91162
91163#ifndef SQLITE_OMIT_TRACE
91164      if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0
91165          && !db->init.busy && p->zSql ){
91166        sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
91167      }else{
91168        assert( p->startTime==0 );
91169      }
91170#endif
91171
91172      db->nVdbeActive++;
91173      if( p->readOnly==0 ) db->nVdbeWrite++;
91174      if( p->bIsReader ) db->nVdbeRead++;
91175      p->pc = 0;
91176      p->eVdbeState = VDBE_RUN_STATE;
91177    }else
91178
91179    if( ALWAYS(p->eVdbeState==VDBE_HALT_STATE) ){
91180      /* We used to require that sqlite3_reset() be called before retrying
91181      ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
91182      ** with version 3.7.0, we changed this so that sqlite3_reset() would
91183      ** be called automatically instead of throwing the SQLITE_MISUSE error.
91184      ** This "automatic-reset" change is not technically an incompatibility,
91185      ** since any application that receives an SQLITE_MISUSE is broken by
91186      ** definition.
91187      **
91188      ** Nevertheless, some published applications that were originally written
91189      ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
91190      ** returns, and those were broken by the automatic-reset change.  As a
91191      ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
91192      ** legacy behavior of returning SQLITE_MISUSE for cases where the
91193      ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
91194      ** or SQLITE_BUSY error.
91195      */
91196#ifdef SQLITE_OMIT_AUTORESET
91197      if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
91198        sqlite3_reset((sqlite3_stmt*)p);
91199      }else{
91200        return SQLITE_MISUSE_BKPT;
91201      }
91202#else
91203      sqlite3_reset((sqlite3_stmt*)p);
91204#endif
91205      assert( p->eVdbeState==VDBE_READY_STATE );
91206      goto restart_step;
91207    }
91208  }
91209
91210#ifdef SQLITE_DEBUG
91211  p->rcApp = SQLITE_OK;
91212#endif
91213#ifndef SQLITE_OMIT_EXPLAIN
91214  if( p->explain ){
91215    rc = sqlite3VdbeList(p);
91216  }else
91217#endif /* SQLITE_OMIT_EXPLAIN */
91218  {
91219    db->nVdbeExec++;
91220    rc = sqlite3VdbeExec(p);
91221    db->nVdbeExec--;
91222  }
91223
91224  if( rc==SQLITE_ROW ){
91225    assert( p->rc==SQLITE_OK );
91226    assert( db->mallocFailed==0 );
91227    db->errCode = SQLITE_ROW;
91228    return SQLITE_ROW;
91229  }else{
91230#ifndef SQLITE_OMIT_TRACE
91231    /* If the statement completed successfully, invoke the profile callback */
91232    checkProfileCallback(db, p);
91233#endif
91234    p->pResultRow = 0;
91235    if( rc==SQLITE_DONE && db->autoCommit ){
91236      assert( p->rc==SQLITE_OK );
91237      p->rc = doWalCallbacks(db);
91238      if( p->rc!=SQLITE_OK ){
91239        rc = SQLITE_ERROR;
91240      }
91241    }else if( rc!=SQLITE_DONE && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
91242      /* If this statement was prepared using saved SQL and an
91243      ** error has occurred, then return the error code in p->rc to the
91244      ** caller. Set the error code in the database handle to the same value.
91245      */
91246      rc = sqlite3VdbeTransferError(p);
91247    }
91248  }
91249
91250  db->errCode = rc;
91251  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
91252    p->rc = SQLITE_NOMEM_BKPT;
91253    if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ) rc = p->rc;
91254  }
91255end_of_step:
91256  /* There are only a limited number of result codes allowed from the
91257  ** statements prepared using the legacy sqlite3_prepare() interface */
91258  assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
91259       || rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
91260       || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
91261  );
91262  return (rc&db->errMask);
91263}
91264
91265/*
91266** This is the top-level implementation of sqlite3_step().  Call
91267** sqlite3Step() to do most of the work.  If a schema error occurs,
91268** call sqlite3Reprepare() and try again.
91269*/
91270SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
91271  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
91272  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
91273  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
91274  sqlite3 *db;             /* The database connection */
91275
91276  if( vdbeSafetyNotNull(v) ){
91277    return SQLITE_MISUSE_BKPT;
91278  }
91279  db = v->db;
91280  sqlite3_mutex_enter(db->mutex);
91281  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
91282         && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
91283    int savedPc = v->pc;
91284    rc = sqlite3Reprepare(v);
91285    if( rc!=SQLITE_OK ){
91286      /* This case occurs after failing to recompile an sql statement.
91287      ** The error message from the SQL compiler has already been loaded
91288      ** into the database handle. This block copies the error message
91289      ** from the database handle into the statement and sets the statement
91290      ** program counter to 0 to ensure that when the statement is
91291      ** finalized or reset the parser error message is available via
91292      ** sqlite3_errmsg() and sqlite3_errcode().
91293      */
91294      const char *zErr = (const char *)sqlite3_value_text(db->pErr);
91295      sqlite3DbFree(db, v->zErrMsg);
91296      if( !db->mallocFailed ){
91297        v->zErrMsg = sqlite3DbStrDup(db, zErr);
91298        v->rc = rc = sqlite3ApiExit(db, rc);
91299      } else {
91300        v->zErrMsg = 0;
91301        v->rc = rc = SQLITE_NOMEM_BKPT;
91302      }
91303      break;
91304    }
91305    sqlite3_reset(pStmt);
91306    if( savedPc>=0 ){
91307      /* Setting minWriteFileFormat to 254 is a signal to the OP_Init and
91308      ** OP_Trace opcodes to *not* perform SQLITE_TRACE_STMT because it has
91309      ** already been done once on a prior invocation that failed due to
91310      ** SQLITE_SCHEMA.   tag-20220401a  */
91311      v->minWriteFileFormat = 254;
91312    }
91313    assert( v->expired==0 );
91314  }
91315  sqlite3_mutex_leave(db->mutex);
91316  return rc;
91317}
91318
91319
91320/*
91321** Extract the user data from a sqlite3_context structure and return a
91322** pointer to it.
91323*/
91324SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
91325#ifdef SQLITE_ENABLE_API_ARMOR
91326  if( p==0 ) return 0;
91327#endif
91328  assert( p && p->pFunc );
91329  return p->pFunc->pUserData;
91330}
91331
91332/*
91333** Extract the user data from a sqlite3_context structure and return a
91334** pointer to it.
91335**
91336** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
91337** returns a copy of the pointer to the database connection (the 1st
91338** parameter) of the sqlite3_create_function() and
91339** sqlite3_create_function16() routines that originally registered the
91340** application defined function.
91341*/
91342SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
91343#ifdef SQLITE_ENABLE_API_ARMOR
91344  if( p==0 ) return 0;
91345#else
91346  assert( p && p->pOut );
91347#endif
91348  return p->pOut->db;
91349}
91350
91351/*
91352** If this routine is invoked from within an xColumn method of a virtual
91353** table, then it returns true if and only if the the call is during an
91354** UPDATE operation and the value of the column will not be modified
91355** by the UPDATE.
91356**
91357** If this routine is called from any context other than within the
91358** xColumn method of a virtual table, then the return value is meaningless
91359** and arbitrary.
91360**
91361** Virtual table implements might use this routine to optimize their
91362** performance by substituting a NULL result, or some other light-weight
91363** value, as a signal to the xUpdate routine that the column is unchanged.
91364*/
91365SQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){
91366#ifdef SQLITE_ENABLE_API_ARMOR
91367  if( p==0 ) return 0;
91368#else
91369  assert( p );
91370#endif
91371  return sqlite3_value_nochange(p->pOut);
91372}
91373
91374/*
91375** The destructor function for a ValueList object.  This needs to be
91376** a separate function, unknowable to the application, to ensure that
91377** calls to sqlite3_vtab_in_first()/sqlite3_vtab_in_next() that are not
91378** preceded by activation of IN processing via sqlite3_vtab_int() do not
91379** try to access a fake ValueList object inserted by a hostile extension.
91380*/
91381SQLITE_PRIVATE void sqlite3VdbeValueListFree(void *pToDelete){
91382  sqlite3_free(pToDelete);
91383}
91384
91385/*
91386** Implementation of sqlite3_vtab_in_first() (if bNext==0) and
91387** sqlite3_vtab_in_next() (if bNext!=0).
91388*/
91389static int valueFromValueList(
91390  sqlite3_value *pVal,        /* Pointer to the ValueList object */
91391  sqlite3_value **ppOut,      /* Store the next value from the list here */
91392  int bNext                   /* 1 for _next(). 0 for _first() */
91393){
91394  int rc;
91395  ValueList *pRhs;
91396
91397  *ppOut = 0;
91398  if( pVal==0 ) return SQLITE_MISUSE_BKPT;
91399  if( (pVal->flags & MEM_Dyn)==0 || pVal->xDel!=sqlite3VdbeValueListFree ){
91400    return SQLITE_ERROR;
91401  }else{
91402    assert( (pVal->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
91403                 (MEM_Null|MEM_Term|MEM_Subtype) );
91404    assert( pVal->eSubtype=='p' );
91405    assert( pVal->u.zPType!=0 && strcmp(pVal->u.zPType,"ValueList")==0 );
91406    pRhs = (ValueList*)pVal->z;
91407  }
91408  if( bNext ){
91409    rc = sqlite3BtreeNext(pRhs->pCsr, 0);
91410  }else{
91411    int dummy = 0;
91412    rc = sqlite3BtreeFirst(pRhs->pCsr, &dummy);
91413    assert( rc==SQLITE_OK || sqlite3BtreeEof(pRhs->pCsr) );
91414    if( sqlite3BtreeEof(pRhs->pCsr) ) rc = SQLITE_DONE;
91415  }
91416  if( rc==SQLITE_OK ){
91417    u32 sz;       /* Size of current row in bytes */
91418    Mem sMem;     /* Raw content of current row */
91419    memset(&sMem, 0, sizeof(sMem));
91420    sz = sqlite3BtreePayloadSize(pRhs->pCsr);
91421    rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,(int)sz,&sMem);
91422    if( rc==SQLITE_OK ){
91423      u8 *zBuf = (u8*)sMem.z;
91424      u32 iSerial;
91425      sqlite3_value *pOut = pRhs->pOut;
91426      int iOff = 1 + getVarint32(&zBuf[1], iSerial);
91427      sqlite3VdbeSerialGet(&zBuf[iOff], iSerial, pOut);
91428      pOut->enc = ENC(pOut->db);
91429      if( (pOut->flags & MEM_Ephem)!=0 && sqlite3VdbeMemMakeWriteable(pOut) ){
91430        rc = SQLITE_NOMEM;
91431      }else{
91432        *ppOut = pOut;
91433      }
91434    }
91435    sqlite3VdbeMemRelease(&sMem);
91436  }
91437  return rc;
91438}
91439
91440/*
91441** Set the iterator value pVal to point to the first value in the set.
91442** Set (*ppOut) to point to this value before returning.
91443*/
91444SQLITE_API int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut){
91445  return valueFromValueList(pVal, ppOut, 0);
91446}
91447
91448/*
91449** Set the iterator value pVal to point to the next value in the set.
91450** Set (*ppOut) to point to this value before returning.
91451*/
91452SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut){
91453  return valueFromValueList(pVal, ppOut, 1);
91454}
91455
91456/*
91457** Return the current time for a statement.  If the current time
91458** is requested more than once within the same run of a single prepared
91459** statement, the exact same time is returned for each invocation regardless
91460** of the amount of time that elapses between invocations.  In other words,
91461** the time returned is always the time of the first call.
91462*/
91463SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
91464  int rc;
91465#ifndef SQLITE_ENABLE_STAT4
91466  sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
91467  assert( p->pVdbe!=0 );
91468#else
91469  sqlite3_int64 iTime = 0;
91470  sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
91471#endif
91472  if( *piTime==0 ){
91473    rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
91474    if( rc ) *piTime = 0;
91475  }
91476  return *piTime;
91477}
91478
91479/*
91480** Create a new aggregate context for p and return a pointer to
91481** its pMem->z element.
91482*/
91483static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
91484  Mem *pMem = p->pMem;
91485  assert( (pMem->flags & MEM_Agg)==0 );
91486  if( nByte<=0 ){
91487    sqlite3VdbeMemSetNull(pMem);
91488    pMem->z = 0;
91489  }else{
91490    sqlite3VdbeMemClearAndResize(pMem, nByte);
91491    pMem->flags = MEM_Agg;
91492    pMem->u.pDef = p->pFunc;
91493    if( pMem->z ){
91494      memset(pMem->z, 0, nByte);
91495    }
91496  }
91497  return (void*)pMem->z;
91498}
91499
91500/*
91501** Allocate or return the aggregate context for a user function.  A new
91502** context is allocated on the first call.  Subsequent calls return the
91503** same context that was returned on prior calls.
91504*/
91505SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
91506  assert( p && p->pFunc && p->pFunc->xFinalize );
91507  assert( sqlite3_mutex_held(p->pOut->db->mutex) );
91508  testcase( nByte<0 );
91509  if( (p->pMem->flags & MEM_Agg)==0 ){
91510    return createAggContext(p, nByte);
91511  }else{
91512    return (void*)p->pMem->z;
91513  }
91514}
91515
91516/*
91517** Return the auxiliary data pointer, if any, for the iArg'th argument to
91518** the user-function defined by pCtx.
91519**
91520** The left-most argument is 0.
91521**
91522** Undocumented behavior:  If iArg is negative then access a cache of
91523** auxiliary data pointers that is available to all functions within a
91524** single prepared statement.  The iArg values must match.
91525*/
91526SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
91527  AuxData *pAuxData;
91528
91529#ifdef SQLITE_ENABLE_API_ARMOR
91530  if( pCtx==0 ) return 0;
91531#endif
91532  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91533#if SQLITE_ENABLE_STAT4
91534  if( pCtx->pVdbe==0 ) return 0;
91535#else
91536  assert( pCtx->pVdbe!=0 );
91537#endif
91538  for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
91539    if(  pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
91540      return pAuxData->pAux;
91541    }
91542  }
91543  return 0;
91544}
91545
91546/*
91547** Set the auxiliary data pointer and delete function, for the iArg'th
91548** argument to the user-function defined by pCtx. Any previous value is
91549** deleted by calling the delete function specified when it was set.
91550**
91551** The left-most argument is 0.
91552**
91553** Undocumented behavior:  If iArg is negative then make the data available
91554** to all functions within the current prepared statement using iArg as an
91555** access code.
91556*/
91557SQLITE_API void sqlite3_set_auxdata(
91558  sqlite3_context *pCtx,
91559  int iArg,
91560  void *pAux,
91561  void (*xDelete)(void*)
91562){
91563  AuxData *pAuxData;
91564  Vdbe *pVdbe;
91565
91566#ifdef SQLITE_ENABLE_API_ARMOR
91567  if( pCtx==0 ) return;
91568#endif
91569  pVdbe= pCtx->pVdbe;
91570  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91571#ifdef SQLITE_ENABLE_STAT4
91572  if( pVdbe==0 ) goto failed;
91573#else
91574  assert( pVdbe!=0 );
91575#endif
91576
91577  for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
91578    if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
91579      break;
91580    }
91581  }
91582  if( pAuxData==0 ){
91583    pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
91584    if( !pAuxData ) goto failed;
91585    pAuxData->iAuxOp = pCtx->iOp;
91586    pAuxData->iAuxArg = iArg;
91587    pAuxData->pNextAux = pVdbe->pAuxData;
91588    pVdbe->pAuxData = pAuxData;
91589    if( pCtx->isError==0 ) pCtx->isError = -1;
91590  }else if( pAuxData->xDeleteAux ){
91591    pAuxData->xDeleteAux(pAuxData->pAux);
91592  }
91593
91594  pAuxData->pAux = pAux;
91595  pAuxData->xDeleteAux = xDelete;
91596  return;
91597
91598failed:
91599  if( xDelete ){
91600    xDelete(pAux);
91601  }
91602}
91603
91604#ifndef SQLITE_OMIT_DEPRECATED
91605/*
91606** Return the number of times the Step function of an aggregate has been
91607** called.
91608**
91609** This function is deprecated.  Do not use it for new code.  It is
91610** provide only to avoid breaking legacy code.  New aggregate function
91611** implementations should keep their own counts within their aggregate
91612** context.
91613*/
91614SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
91615  assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
91616  return p->pMem->n;
91617}
91618#endif
91619
91620/*
91621** Return the number of columns in the result set for the statement pStmt.
91622*/
91623SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
91624  Vdbe *pVm = (Vdbe *)pStmt;
91625  if( pVm==0 ) return 0;
91626  return pVm->nResColumn;
91627}
91628
91629/*
91630** Return the number of values available from the current row of the
91631** currently executing statement pStmt.
91632*/
91633SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
91634  Vdbe *pVm = (Vdbe *)pStmt;
91635  if( pVm==0 || pVm->pResultRow==0 ) return 0;
91636  return pVm->nResColumn;
91637}
91638
91639/*
91640** Return a pointer to static memory containing an SQL NULL value.
91641*/
91642static const Mem *columnNullValue(void){
91643  /* Even though the Mem structure contains an element
91644  ** of type i64, on certain architectures (x86) with certain compiler
91645  ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
91646  ** instead of an 8-byte one. This all works fine, except that when
91647  ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
91648  ** that a Mem structure is located on an 8-byte boundary. To prevent
91649  ** these assert()s from failing, when building with SQLITE_DEBUG defined
91650  ** using gcc, we force nullMem to be 8-byte aligned using the magical
91651  ** __attribute__((aligned(8))) macro.  */
91652  static const Mem nullMem
91653#if defined(SQLITE_DEBUG) && defined(__GNUC__)
91654    __attribute__((aligned(8)))
91655#endif
91656    = {
91657        /* .u          = */ {0},
91658        /* .z          = */ (char*)0,
91659        /* .n          = */ (int)0,
91660        /* .flags      = */ (u16)MEM_Null,
91661        /* .enc        = */ (u8)0,
91662        /* .eSubtype   = */ (u8)0,
91663        /* .db         = */ (sqlite3*)0,
91664        /* .szMalloc   = */ (int)0,
91665        /* .uTemp      = */ (u32)0,
91666        /* .zMalloc    = */ (char*)0,
91667        /* .xDel       = */ (void(*)(void*))0,
91668#ifdef SQLITE_DEBUG
91669        /* .pScopyFrom = */ (Mem*)0,
91670        /* .mScopyFlags= */ 0,
91671#endif
91672      };
91673  return &nullMem;
91674}
91675
91676/*
91677** Check to see if column iCol of the given statement is valid.  If
91678** it is, return a pointer to the Mem for the value of that column.
91679** If iCol is not valid, return a pointer to a Mem which has a value
91680** of NULL.
91681*/
91682static Mem *columnMem(sqlite3_stmt *pStmt, int i){
91683  Vdbe *pVm;
91684  Mem *pOut;
91685
91686  pVm = (Vdbe *)pStmt;
91687  if( pVm==0 ) return (Mem*)columnNullValue();
91688  assert( pVm->db );
91689  sqlite3_mutex_enter(pVm->db->mutex);
91690  if( pVm->pResultRow!=0 && i<pVm->nResColumn && i>=0 ){
91691    pOut = &pVm->pResultRow[i];
91692  }else{
91693    sqlite3Error(pVm->db, SQLITE_RANGE);
91694    pOut = (Mem*)columnNullValue();
91695  }
91696  return pOut;
91697}
91698
91699/*
91700** This function is called after invoking an sqlite3_value_XXX function on a
91701** column value (i.e. a value returned by evaluating an SQL expression in the
91702** select list of a SELECT statement) that may cause a malloc() failure. If
91703** malloc() has failed, the threads mallocFailed flag is cleared and the result
91704** code of statement pStmt set to SQLITE_NOMEM.
91705**
91706** Specifically, this is called from within:
91707**
91708**     sqlite3_column_int()
91709**     sqlite3_column_int64()
91710**     sqlite3_column_text()
91711**     sqlite3_column_text16()
91712**     sqlite3_column_real()
91713**     sqlite3_column_bytes()
91714**     sqlite3_column_bytes16()
91715**     sqlite3_column_blob()
91716*/
91717static void columnMallocFailure(sqlite3_stmt *pStmt)
91718{
91719  /* If malloc() failed during an encoding conversion within an
91720  ** sqlite3_column_XXX API, then set the return code of the statement to
91721  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
91722  ** and _finalize() will return NOMEM.
91723  */
91724  Vdbe *p = (Vdbe *)pStmt;
91725  if( p ){
91726    assert( p->db!=0 );
91727    assert( sqlite3_mutex_held(p->db->mutex) );
91728    p->rc = sqlite3ApiExit(p->db, p->rc);
91729    sqlite3_mutex_leave(p->db->mutex);
91730  }
91731}
91732
91733/**************************** sqlite3_column_  *******************************
91734** The following routines are used to access elements of the current row
91735** in the result set.
91736*/
91737SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
91738  const void *val;
91739  val = sqlite3_value_blob( columnMem(pStmt,i) );
91740  /* Even though there is no encoding conversion, value_blob() might
91741  ** need to call malloc() to expand the result of a zeroblob()
91742  ** expression.
91743  */
91744  columnMallocFailure(pStmt);
91745  return val;
91746}
91747SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
91748  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
91749  columnMallocFailure(pStmt);
91750  return val;
91751}
91752SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
91753  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
91754  columnMallocFailure(pStmt);
91755  return val;
91756}
91757SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
91758  double val = sqlite3_value_double( columnMem(pStmt,i) );
91759  columnMallocFailure(pStmt);
91760  return val;
91761}
91762SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
91763  int val = sqlite3_value_int( columnMem(pStmt,i) );
91764  columnMallocFailure(pStmt);
91765  return val;
91766}
91767SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
91768  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
91769  columnMallocFailure(pStmt);
91770  return val;
91771}
91772SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
91773  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
91774  columnMallocFailure(pStmt);
91775  return val;
91776}
91777SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
91778  Mem *pOut = columnMem(pStmt, i);
91779  if( pOut->flags&MEM_Static ){
91780    pOut->flags &= ~MEM_Static;
91781    pOut->flags |= MEM_Ephem;
91782  }
91783  columnMallocFailure(pStmt);
91784  return (sqlite3_value *)pOut;
91785}
91786#ifndef SQLITE_OMIT_UTF16
91787SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
91788  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
91789  columnMallocFailure(pStmt);
91790  return val;
91791}
91792#endif /* SQLITE_OMIT_UTF16 */
91793SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
91794  int iType = sqlite3_value_type( columnMem(pStmt,i) );
91795  columnMallocFailure(pStmt);
91796  return iType;
91797}
91798
91799/*
91800** Column names appropriate for EXPLAIN or EXPLAIN QUERY PLAN.
91801*/
91802static const char * const azExplainColNames8[] = {
91803   "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",  /* EXPLAIN */
91804   "id", "parent", "notused", "detail"                         /* EQP */
91805};
91806static const u16 azExplainColNames16data[] = {
91807  /*   0 */  'a', 'd', 'd', 'r',                0,
91808  /*   5 */  'o', 'p', 'c', 'o', 'd', 'e',      0,
91809  /*  12 */  'p', '1',                          0,
91810  /*  15 */  'p', '2',                          0,
91811  /*  18 */  'p', '3',                          0,
91812  /*  21 */  'p', '4',                          0,
91813  /*  24 */  'p', '5',                          0,
91814  /*  27 */  'c', 'o', 'm', 'm', 'e', 'n', 't', 0,
91815  /*  35 */  'i', 'd',                          0,
91816  /*  38 */  'p', 'a', 'r', 'e', 'n', 't',      0,
91817  /*  45 */  'n', 'o', 't', 'u', 's', 'e', 'd', 0,
91818  /*  53 */  'd', 'e', 't', 'a', 'i', 'l',      0
91819};
91820static const u8 iExplainColNames16[] = {
91821  0, 5, 12, 15, 18, 21, 24, 27,
91822  35, 38, 45, 53
91823};
91824
91825/*
91826** Convert the N-th element of pStmt->pColName[] into a string using
91827** xFunc() then return that string.  If N is out of range, return 0.
91828**
91829** There are up to 5 names for each column.  useType determines which
91830** name is returned.  Here are the names:
91831**
91832**    0      The column name as it should be displayed for output
91833**    1      The datatype name for the column
91834**    2      The name of the database that the column derives from
91835**    3      The name of the table that the column derives from
91836**    4      The name of the table column that the result column derives from
91837**
91838** If the result is not a simple column reference (if it is an expression
91839** or a constant) then useTypes 2, 3, and 4 return NULL.
91840*/
91841static const void *columnName(
91842  sqlite3_stmt *pStmt,     /* The statement */
91843  int N,                   /* Which column to get the name for */
91844  int useUtf16,            /* True to return the name as UTF16 */
91845  int useType              /* What type of name */
91846){
91847  const void *ret;
91848  Vdbe *p;
91849  int n;
91850  sqlite3 *db;
91851#ifdef SQLITE_ENABLE_API_ARMOR
91852  if( pStmt==0 ){
91853    (void)SQLITE_MISUSE_BKPT;
91854    return 0;
91855  }
91856#endif
91857  if( N<0 ) return 0;
91858  ret = 0;
91859  p = (Vdbe *)pStmt;
91860  db = p->db;
91861  assert( db!=0 );
91862  sqlite3_mutex_enter(db->mutex);
91863
91864  if( p->explain ){
91865    if( useType>0 ) goto columnName_end;
91866    n = p->explain==1 ? 8 : 4;
91867    if( N>=n ) goto columnName_end;
91868    if( useUtf16 ){
91869      int i = iExplainColNames16[N + 8*p->explain - 8];
91870      ret = (void*)&azExplainColNames16data[i];
91871    }else{
91872      ret = (void*)azExplainColNames8[N + 8*p->explain - 8];
91873    }
91874    goto columnName_end;
91875  }
91876  n = p->nResColumn;
91877  if( N<n ){
91878    u8 prior_mallocFailed = db->mallocFailed;
91879    N += useType*n;
91880#ifndef SQLITE_OMIT_UTF16
91881    if( useUtf16 ){
91882      ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
91883    }else
91884#endif
91885    {
91886      ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
91887    }
91888    /* A malloc may have failed inside of the _text() call. If this
91889    ** is the case, clear the mallocFailed flag and return NULL.
91890    */
91891    assert( db->mallocFailed==0 || db->mallocFailed==1 );
91892    if( db->mallocFailed > prior_mallocFailed ){
91893      sqlite3OomClear(db);
91894      ret = 0;
91895    }
91896  }
91897columnName_end:
91898  sqlite3_mutex_leave(db->mutex);
91899  return ret;
91900}
91901
91902/*
91903** Return the name of the Nth column of the result set returned by SQL
91904** statement pStmt.
91905*/
91906SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
91907  return columnName(pStmt, N, 0, COLNAME_NAME);
91908}
91909#ifndef SQLITE_OMIT_UTF16
91910SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
91911  return columnName(pStmt, N, 1, COLNAME_NAME);
91912}
91913#endif
91914
91915/*
91916** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
91917** not define OMIT_DECLTYPE.
91918*/
91919#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
91920# error "Must not define both SQLITE_OMIT_DECLTYPE \
91921         and SQLITE_ENABLE_COLUMN_METADATA"
91922#endif
91923
91924#ifndef SQLITE_OMIT_DECLTYPE
91925/*
91926** Return the column declaration type (if applicable) of the 'i'th column
91927** of the result set of SQL statement pStmt.
91928*/
91929SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
91930  return columnName(pStmt, N, 0, COLNAME_DECLTYPE);
91931}
91932#ifndef SQLITE_OMIT_UTF16
91933SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
91934  return columnName(pStmt, N, 1, COLNAME_DECLTYPE);
91935}
91936#endif /* SQLITE_OMIT_UTF16 */
91937#endif /* SQLITE_OMIT_DECLTYPE */
91938
91939#ifdef SQLITE_ENABLE_COLUMN_METADATA
91940/*
91941** Return the name of the database from which a result column derives.
91942** NULL is returned if the result column is an expression or constant or
91943** anything else which is not an unambiguous reference to a database column.
91944*/
91945SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
91946  return columnName(pStmt, N, 0, COLNAME_DATABASE);
91947}
91948#ifndef SQLITE_OMIT_UTF16
91949SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
91950  return columnName(pStmt, N, 1, COLNAME_DATABASE);
91951}
91952#endif /* SQLITE_OMIT_UTF16 */
91953
91954/*
91955** Return the name of the table from which a result column derives.
91956** NULL is returned if the result column is an expression or constant or
91957** anything else which is not an unambiguous reference to a database column.
91958*/
91959SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
91960  return columnName(pStmt, N, 0, COLNAME_TABLE);
91961}
91962#ifndef SQLITE_OMIT_UTF16
91963SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
91964  return columnName(pStmt, N, 1, COLNAME_TABLE);
91965}
91966#endif /* SQLITE_OMIT_UTF16 */
91967
91968/*
91969** Return the name of the table column from which a result column derives.
91970** NULL is returned if the result column is an expression or constant or
91971** anything else which is not an unambiguous reference to a database column.
91972*/
91973SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
91974  return columnName(pStmt, N, 0, COLNAME_COLUMN);
91975}
91976#ifndef SQLITE_OMIT_UTF16
91977SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
91978  return columnName(pStmt, N, 1, COLNAME_COLUMN);
91979}
91980#endif /* SQLITE_OMIT_UTF16 */
91981#endif /* SQLITE_ENABLE_COLUMN_METADATA */
91982
91983
91984/******************************* sqlite3_bind_  ***************************
91985**
91986** Routines used to attach values to wildcards in a compiled SQL statement.
91987*/
91988/*
91989** Unbind the value bound to variable i in virtual machine p. This is the
91990** the same as binding a NULL value to the column. If the "i" parameter is
91991** out of range, then SQLITE_RANGE is returned. Otherwise SQLITE_OK.
91992**
91993** A successful evaluation of this routine acquires the mutex on p.
91994** the mutex is released if any kind of error occurs.
91995**
91996** The error code stored in database p->db is overwritten with the return
91997** value in any case.
91998*/
91999static int vdbeUnbind(Vdbe *p, unsigned int i){
92000  Mem *pVar;
92001  if( vdbeSafetyNotNull(p) ){
92002    return SQLITE_MISUSE_BKPT;
92003  }
92004  sqlite3_mutex_enter(p->db->mutex);
92005  if( p->eVdbeState!=VDBE_READY_STATE ){
92006    sqlite3Error(p->db, SQLITE_MISUSE_BKPT);
92007    sqlite3_mutex_leave(p->db->mutex);
92008    sqlite3_log(SQLITE_MISUSE,
92009        "bind on a busy prepared statement: [%s]", p->zSql);
92010    return SQLITE_MISUSE_BKPT;
92011  }
92012  if( i>=(unsigned int)p->nVar ){
92013    sqlite3Error(p->db, SQLITE_RANGE);
92014    sqlite3_mutex_leave(p->db->mutex);
92015    return SQLITE_RANGE;
92016  }
92017  pVar = &p->aVar[i];
92018  sqlite3VdbeMemRelease(pVar);
92019  pVar->flags = MEM_Null;
92020  p->db->errCode = SQLITE_OK;
92021
92022  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
92023  ** binding a new value to this variable invalidates the current query plan.
92024  **
92025  ** IMPLEMENTATION-OF: R-57496-20354 If the specific value bound to a host
92026  ** parameter in the WHERE clause might influence the choice of query plan
92027  ** for a statement, then the statement will be automatically recompiled,
92028  ** as if there had been a schema change, on the first sqlite3_step() call
92029  ** following any change to the bindings of that parameter.
92030  */
92031  assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
92032  if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
92033    p->expired = 1;
92034  }
92035  return SQLITE_OK;
92036}
92037
92038/*
92039** Bind a text or BLOB value.
92040*/
92041static int bindText(
92042  sqlite3_stmt *pStmt,   /* The statement to bind against */
92043  int i,                 /* Index of the parameter to bind */
92044  const void *zData,     /* Pointer to the data to be bound */
92045  i64 nData,             /* Number of bytes of data to be bound */
92046  void (*xDel)(void*),   /* Destructor for the data */
92047  u8 encoding            /* Encoding for the data */
92048){
92049  Vdbe *p = (Vdbe *)pStmt;
92050  Mem *pVar;
92051  int rc;
92052
92053  rc = vdbeUnbind(p, (u32)(i-1));
92054  if( rc==SQLITE_OK ){
92055    if( zData!=0 ){
92056      pVar = &p->aVar[i-1];
92057      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
92058      if( rc==SQLITE_OK && encoding!=0 ){
92059        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
92060      }
92061      if( rc ){
92062        sqlite3Error(p->db, rc);
92063        rc = sqlite3ApiExit(p->db, rc);
92064      }
92065    }
92066    sqlite3_mutex_leave(p->db->mutex);
92067  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
92068    xDel((void*)zData);
92069  }
92070  return rc;
92071}
92072
92073
92074/*
92075** Bind a blob value to an SQL statement variable.
92076*/
92077SQLITE_API int sqlite3_bind_blob(
92078  sqlite3_stmt *pStmt,
92079  int i,
92080  const void *zData,
92081  int nData,
92082  void (*xDel)(void*)
92083){
92084#ifdef SQLITE_ENABLE_API_ARMOR
92085  if( nData<0 ) return SQLITE_MISUSE_BKPT;
92086#endif
92087  return bindText(pStmt, i, zData, nData, xDel, 0);
92088}
92089SQLITE_API int sqlite3_bind_blob64(
92090  sqlite3_stmt *pStmt,
92091  int i,
92092  const void *zData,
92093  sqlite3_uint64 nData,
92094  void (*xDel)(void*)
92095){
92096  assert( xDel!=SQLITE_DYNAMIC );
92097  return bindText(pStmt, i, zData, nData, xDel, 0);
92098}
92099SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
92100  int rc;
92101  Vdbe *p = (Vdbe *)pStmt;
92102  rc = vdbeUnbind(p, (u32)(i-1));
92103  if( rc==SQLITE_OK ){
92104    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
92105    sqlite3_mutex_leave(p->db->mutex);
92106  }
92107  return rc;
92108}
92109SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
92110  return sqlite3_bind_int64(p, i, (i64)iValue);
92111}
92112SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
92113  int rc;
92114  Vdbe *p = (Vdbe *)pStmt;
92115  rc = vdbeUnbind(p, (u32)(i-1));
92116  if( rc==SQLITE_OK ){
92117    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
92118    sqlite3_mutex_leave(p->db->mutex);
92119  }
92120  return rc;
92121}
92122SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
92123  int rc;
92124  Vdbe *p = (Vdbe*)pStmt;
92125  rc = vdbeUnbind(p, (u32)(i-1));
92126  if( rc==SQLITE_OK ){
92127    sqlite3_mutex_leave(p->db->mutex);
92128  }
92129  return rc;
92130}
92131SQLITE_API int sqlite3_bind_pointer(
92132  sqlite3_stmt *pStmt,
92133  int i,
92134  void *pPtr,
92135  const char *zPTtype,
92136  void (*xDestructor)(void*)
92137){
92138  int rc;
92139  Vdbe *p = (Vdbe*)pStmt;
92140  rc = vdbeUnbind(p, (u32)(i-1));
92141  if( rc==SQLITE_OK ){
92142    sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
92143    sqlite3_mutex_leave(p->db->mutex);
92144  }else if( xDestructor ){
92145    xDestructor(pPtr);
92146  }
92147  return rc;
92148}
92149SQLITE_API int sqlite3_bind_text(
92150  sqlite3_stmt *pStmt,
92151  int i,
92152  const char *zData,
92153  int nData,
92154  void (*xDel)(void*)
92155){
92156  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
92157}
92158SQLITE_API int sqlite3_bind_text64(
92159  sqlite3_stmt *pStmt,
92160  int i,
92161  const char *zData,
92162  sqlite3_uint64 nData,
92163  void (*xDel)(void*),
92164  unsigned char enc
92165){
92166  assert( xDel!=SQLITE_DYNAMIC );
92167  if( enc!=SQLITE_UTF8 ){
92168    if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
92169    nData &= ~(u16)1;
92170  }
92171  return bindText(pStmt, i, zData, nData, xDel, enc);
92172}
92173#ifndef SQLITE_OMIT_UTF16
92174SQLITE_API int sqlite3_bind_text16(
92175  sqlite3_stmt *pStmt,
92176  int i,
92177  const void *zData,
92178  int n,
92179  void (*xDel)(void*)
92180){
92181  return bindText(pStmt, i, zData, n & ~(u64)1, xDel, SQLITE_UTF16NATIVE);
92182}
92183#endif /* SQLITE_OMIT_UTF16 */
92184SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
92185  int rc;
92186  switch( sqlite3_value_type((sqlite3_value*)pValue) ){
92187    case SQLITE_INTEGER: {
92188      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
92189      break;
92190    }
92191    case SQLITE_FLOAT: {
92192      assert( pValue->flags & (MEM_Real|MEM_IntReal) );
92193      rc = sqlite3_bind_double(pStmt, i,
92194          (pValue->flags & MEM_Real) ? pValue->u.r : (double)pValue->u.i
92195      );
92196      break;
92197    }
92198    case SQLITE_BLOB: {
92199      if( pValue->flags & MEM_Zero ){
92200        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
92201      }else{
92202        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
92203      }
92204      break;
92205    }
92206    case SQLITE_TEXT: {
92207      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
92208                              pValue->enc);
92209      break;
92210    }
92211    default: {
92212      rc = sqlite3_bind_null(pStmt, i);
92213      break;
92214    }
92215  }
92216  return rc;
92217}
92218SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
92219  int rc;
92220  Vdbe *p = (Vdbe *)pStmt;
92221  rc = vdbeUnbind(p, (u32)(i-1));
92222  if( rc==SQLITE_OK ){
92223#ifndef SQLITE_OMIT_INCRBLOB
92224    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
92225#else
92226    rc = sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
92227#endif
92228    sqlite3_mutex_leave(p->db->mutex);
92229  }
92230  return rc;
92231}
92232SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
92233  int rc;
92234  Vdbe *p = (Vdbe *)pStmt;
92235#ifdef SQLITE_ENABLE_API_ARMOR
92236  if( p==0 ) return SQLITE_MISUSE_BKPT;
92237#endif
92238  sqlite3_mutex_enter(p->db->mutex);
92239  if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
92240    rc = SQLITE_TOOBIG;
92241  }else{
92242    assert( (n & 0x7FFFFFFF)==n );
92243    rc = sqlite3_bind_zeroblob(pStmt, i, n);
92244  }
92245  rc = sqlite3ApiExit(p->db, rc);
92246  sqlite3_mutex_leave(p->db->mutex);
92247  return rc;
92248}
92249
92250/*
92251** Return the number of wildcards that can be potentially bound to.
92252** This routine is added to support DBD::SQLite.
92253*/
92254SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
92255  Vdbe *p = (Vdbe*)pStmt;
92256  return p ? p->nVar : 0;
92257}
92258
92259/*
92260** Return the name of a wildcard parameter.  Return NULL if the index
92261** is out of range or if the wildcard is unnamed.
92262**
92263** The result is always UTF-8.
92264*/
92265SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
92266  Vdbe *p = (Vdbe*)pStmt;
92267  if( p==0 ) return 0;
92268  return sqlite3VListNumToName(p->pVList, i);
92269}
92270
92271/*
92272** Given a wildcard parameter name, return the index of the variable
92273** with that name.  If there is no variable with the given name,
92274** return 0.
92275*/
92276SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
92277  if( p==0 || zName==0 ) return 0;
92278  return sqlite3VListNameToNum(p->pVList, zName, nName);
92279}
92280SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
92281  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
92282}
92283
92284/*
92285** Transfer all bindings from the first statement over to the second.
92286*/
92287SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
92288  Vdbe *pFrom = (Vdbe*)pFromStmt;
92289  Vdbe *pTo = (Vdbe*)pToStmt;
92290  int i;
92291  assert( pTo->db==pFrom->db );
92292  assert( pTo->nVar==pFrom->nVar );
92293  sqlite3_mutex_enter(pTo->db->mutex);
92294  for(i=0; i<pFrom->nVar; i++){
92295    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
92296  }
92297  sqlite3_mutex_leave(pTo->db->mutex);
92298  return SQLITE_OK;
92299}
92300
92301#ifndef SQLITE_OMIT_DEPRECATED
92302/*
92303** Deprecated external interface.  Internal/core SQLite code
92304** should call sqlite3TransferBindings.
92305**
92306** It is misuse to call this routine with statements from different
92307** database connections.  But as this is a deprecated interface, we
92308** will not bother to check for that condition.
92309**
92310** If the two statements contain a different number of bindings, then
92311** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
92312** SQLITE_OK is returned.
92313*/
92314SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
92315  Vdbe *pFrom = (Vdbe*)pFromStmt;
92316  Vdbe *pTo = (Vdbe*)pToStmt;
92317  if( pFrom->nVar!=pTo->nVar ){
92318    return SQLITE_ERROR;
92319  }
92320  assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
92321  if( pTo->expmask ){
92322    pTo->expired = 1;
92323  }
92324  assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
92325  if( pFrom->expmask ){
92326    pFrom->expired = 1;
92327  }
92328  return sqlite3TransferBindings(pFromStmt, pToStmt);
92329}
92330#endif
92331
92332/*
92333** Return the sqlite3* database handle to which the prepared statement given
92334** in the argument belongs.  This is the same database handle that was
92335** the first argument to the sqlite3_prepare() that was used to create
92336** the statement in the first place.
92337*/
92338SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
92339  return pStmt ? ((Vdbe*)pStmt)->db : 0;
92340}
92341
92342/*
92343** Return true if the prepared statement is guaranteed to not modify the
92344** database.
92345*/
92346SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
92347  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
92348}
92349
92350/*
92351** Return 1 if the statement is an EXPLAIN and return 2 if the
92352** statement is an EXPLAIN QUERY PLAN
92353*/
92354SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt){
92355  return pStmt ? ((Vdbe*)pStmt)->explain : 0;
92356}
92357
92358/*
92359** Set the explain mode for a statement.
92360*/
92361SQLITE_API int sqlite3_stmt_explain(sqlite3_stmt *pStmt, int eMode){
92362  Vdbe *v = (Vdbe*)pStmt;
92363  int rc;
92364#ifdef SQLITE_ENABLE_API_ARMOR
92365  if( pStmt==0 ) return SQLITE_MISUSE_BKPT;
92366#endif
92367  sqlite3_mutex_enter(v->db->mutex);
92368  if( ((int)v->explain)==eMode ){
92369    rc = SQLITE_OK;
92370  }else if( eMode<0 || eMode>2 ){
92371    rc = SQLITE_ERROR;
92372  }else if( (v->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
92373    rc = SQLITE_ERROR;
92374  }else if( v->eVdbeState!=VDBE_READY_STATE ){
92375    rc = SQLITE_BUSY;
92376  }else if( v->nMem>=10 && (eMode!=2 || v->haveEqpOps) ){
92377    /* No reprepare necessary */
92378    v->explain = eMode;
92379    rc = SQLITE_OK;
92380  }else{
92381    v->explain = eMode;
92382    rc = sqlite3Reprepare(v);
92383    v->haveEqpOps = eMode==2;
92384  }
92385  if( v->explain ){
92386    v->nResColumn = 12 - 4*v->explain;
92387  }else{
92388    v->nResColumn = v->nResAlloc;
92389  }
92390  sqlite3_mutex_leave(v->db->mutex);
92391  return rc;
92392}
92393
92394/*
92395** Return true if the prepared statement is in need of being reset.
92396*/
92397SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
92398  Vdbe *v = (Vdbe*)pStmt;
92399  return v!=0 && v->eVdbeState==VDBE_RUN_STATE;
92400}
92401
92402/*
92403** Return a pointer to the next prepared statement after pStmt associated
92404** with database connection pDb.  If pStmt is NULL, return the first
92405** prepared statement for the database connection.  Return NULL if there
92406** are no more.
92407*/
92408SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
92409  sqlite3_stmt *pNext;
92410#ifdef SQLITE_ENABLE_API_ARMOR
92411  if( !sqlite3SafetyCheckOk(pDb) ){
92412    (void)SQLITE_MISUSE_BKPT;
92413    return 0;
92414  }
92415#endif
92416  sqlite3_mutex_enter(pDb->mutex);
92417  if( pStmt==0 ){
92418    pNext = (sqlite3_stmt*)pDb->pVdbe;
92419  }else{
92420    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pVNext;
92421  }
92422  sqlite3_mutex_leave(pDb->mutex);
92423  return pNext;
92424}
92425
92426/*
92427** Return the value of a status counter for a prepared statement
92428*/
92429SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
92430  Vdbe *pVdbe = (Vdbe*)pStmt;
92431  u32 v;
92432#ifdef SQLITE_ENABLE_API_ARMOR
92433  if( !pStmt
92434   || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
92435  ){
92436    (void)SQLITE_MISUSE_BKPT;
92437    return 0;
92438  }
92439#endif
92440  if( op==SQLITE_STMTSTATUS_MEMUSED ){
92441    sqlite3 *db = pVdbe->db;
92442    sqlite3_mutex_enter(db->mutex);
92443    v = 0;
92444    db->pnBytesFreed = (int*)&v;
92445    assert( db->lookaside.pEnd==db->lookaside.pTrueEnd );
92446    db->lookaside.pEnd = db->lookaside.pStart;
92447    sqlite3VdbeDelete(pVdbe);
92448    db->pnBytesFreed = 0;
92449    db->lookaside.pEnd = db->lookaside.pTrueEnd;
92450    sqlite3_mutex_leave(db->mutex);
92451  }else{
92452    v = pVdbe->aCounter[op];
92453    if( resetFlag ) pVdbe->aCounter[op] = 0;
92454  }
92455  return (int)v;
92456}
92457
92458/*
92459** Return the SQL associated with a prepared statement
92460*/
92461SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
92462  Vdbe *p = (Vdbe *)pStmt;
92463  return p ? p->zSql : 0;
92464}
92465
92466/*
92467** Return the SQL associated with a prepared statement with
92468** bound parameters expanded.  Space to hold the returned string is
92469** obtained from sqlite3_malloc().  The caller is responsible for
92470** freeing the returned string by passing it to sqlite3_free().
92471**
92472** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
92473** expanded bound parameters.
92474*/
92475SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
92476#ifdef SQLITE_OMIT_TRACE
92477  return 0;
92478#else
92479  char *z = 0;
92480  const char *zSql = sqlite3_sql(pStmt);
92481  if( zSql ){
92482    Vdbe *p = (Vdbe *)pStmt;
92483    sqlite3_mutex_enter(p->db->mutex);
92484    z = sqlite3VdbeExpandSql(p, zSql);
92485    sqlite3_mutex_leave(p->db->mutex);
92486  }
92487  return z;
92488#endif
92489}
92490
92491#ifdef SQLITE_ENABLE_NORMALIZE
92492/*
92493** Return the normalized SQL associated with a prepared statement.
92494*/
92495SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
92496  Vdbe *p = (Vdbe *)pStmt;
92497  if( p==0 ) return 0;
92498  if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){
92499    sqlite3_mutex_enter(p->db->mutex);
92500    p->zNormSql = sqlite3Normalize(p, p->zSql);
92501    sqlite3_mutex_leave(p->db->mutex);
92502  }
92503  return p->zNormSql;
92504}
92505#endif /* SQLITE_ENABLE_NORMALIZE */
92506
92507#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
92508/*
92509** Allocate and populate an UnpackedRecord structure based on the serialized
92510** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
92511** if successful, or a NULL pointer if an OOM error is encountered.
92512*/
92513static UnpackedRecord *vdbeUnpackRecord(
92514  KeyInfo *pKeyInfo,
92515  int nKey,
92516  const void *pKey
92517){
92518  UnpackedRecord *pRet;           /* Return value */
92519
92520  pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
92521  if( pRet ){
92522    memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
92523    sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
92524  }
92525  return pRet;
92526}
92527
92528/*
92529** This function is called from within a pre-update callback to retrieve
92530** a field of the row currently being updated or deleted.
92531*/
92532SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
92533  PreUpdate *p;
92534  Mem *pMem;
92535  int rc = SQLITE_OK;
92536
92537#ifdef SQLITE_ENABLE_API_ARMOR
92538  if( db==0 || ppValue==0 ){
92539    return SQLITE_MISUSE_BKPT;
92540  }
92541#endif
92542  p = db->pPreUpdate;
92543  /* Test that this call is being made from within an SQLITE_DELETE or
92544  ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
92545  if( !p || p->op==SQLITE_INSERT ){
92546    rc = SQLITE_MISUSE_BKPT;
92547    goto preupdate_old_out;
92548  }
92549  if( p->pPk ){
92550    iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
92551  }
92552  if( iIdx>=p->pCsr->nField || iIdx<0 ){
92553    rc = SQLITE_RANGE;
92554    goto preupdate_old_out;
92555  }
92556
92557  /* If the old.* record has not yet been loaded into memory, do so now. */
92558  if( p->pUnpacked==0 ){
92559    u32 nRec;
92560    u8 *aRec;
92561
92562    assert( p->pCsr->eCurType==CURTYPE_BTREE );
92563    nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
92564    aRec = sqlite3DbMallocRaw(db, nRec);
92565    if( !aRec ) goto preupdate_old_out;
92566    rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
92567    if( rc==SQLITE_OK ){
92568      p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
92569      if( !p->pUnpacked ) rc = SQLITE_NOMEM;
92570    }
92571    if( rc!=SQLITE_OK ){
92572      sqlite3DbFree(db, aRec);
92573      goto preupdate_old_out;
92574    }
92575    p->aRecord = aRec;
92576  }
92577
92578  pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
92579  if( iIdx==p->pTab->iPKey ){
92580    sqlite3VdbeMemSetInt64(pMem, p->iKey1);
92581  }else if( iIdx>=p->pUnpacked->nField ){
92582    *ppValue = (sqlite3_value *)columnNullValue();
92583  }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
92584    if( pMem->flags & (MEM_Int|MEM_IntReal) ){
92585      testcase( pMem->flags & MEM_Int );
92586      testcase( pMem->flags & MEM_IntReal );
92587      sqlite3VdbeMemRealify(pMem);
92588    }
92589  }
92590
92591 preupdate_old_out:
92592  sqlite3Error(db, rc);
92593  return sqlite3ApiExit(db, rc);
92594}
92595#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
92596
92597#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
92598/*
92599** This function is called from within a pre-update callback to retrieve
92600** the number of columns in the row being updated, deleted or inserted.
92601*/
92602SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
92603  PreUpdate *p;
92604#ifdef SQLITE_ENABLE_API_ARMOR
92605  p = db!=0 ? db->pPreUpdate : 0;
92606#else
92607  p = db->pPreUpdate;
92608#endif
92609  return (p ? p->keyinfo.nKeyField : 0);
92610}
92611#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
92612
92613#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
92614/*
92615** This function is designed to be called from within a pre-update callback
92616** only. It returns zero if the change that caused the callback was made
92617** immediately by a user SQL statement. Or, if the change was made by a
92618** trigger program, it returns the number of trigger programs currently
92619** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
92620** top-level trigger etc.).
92621**
92622** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
92623** or SET DEFAULT action is considered a trigger.
92624*/
92625SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
92626  PreUpdate *p;
92627#ifdef SQLITE_ENABLE_API_ARMOR
92628  p = db!=0 ? db->pPreUpdate : 0;
92629#else
92630  p = db->pPreUpdate;
92631#endif
92632  return (p ? p->v->nFrame : 0);
92633}
92634#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
92635
92636#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
92637/*
92638** This function is designed to be called from within a pre-update callback
92639** only.
92640*/
92641SQLITE_API int sqlite3_preupdate_blobwrite(sqlite3 *db){
92642  PreUpdate *p;
92643#ifdef SQLITE_ENABLE_API_ARMOR
92644  p = db!=0 ? db->pPreUpdate : 0;
92645#else
92646  p = db->pPreUpdate;
92647#endif
92648  return (p ? p->iBlobWrite : -1);
92649}
92650#endif
92651
92652#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
92653/*
92654** This function is called from within a pre-update callback to retrieve
92655** a field of the row currently being updated or inserted.
92656*/
92657SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
92658  PreUpdate *p;
92659  int rc = SQLITE_OK;
92660  Mem *pMem;
92661
92662#ifdef SQLITE_ENABLE_API_ARMOR
92663  if( db==0 || ppValue==0 ){
92664    return SQLITE_MISUSE_BKPT;
92665  }
92666#endif
92667  p = db->pPreUpdate;
92668  if( !p || p->op==SQLITE_DELETE ){
92669    rc = SQLITE_MISUSE_BKPT;
92670    goto preupdate_new_out;
92671  }
92672  if( p->pPk && p->op!=SQLITE_UPDATE ){
92673    iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
92674  }
92675  if( iIdx>=p->pCsr->nField || iIdx<0 ){
92676    rc = SQLITE_RANGE;
92677    goto preupdate_new_out;
92678  }
92679
92680  if( p->op==SQLITE_INSERT ){
92681    /* For an INSERT, memory cell p->iNewReg contains the serialized record
92682    ** that is being inserted. Deserialize it. */
92683    UnpackedRecord *pUnpack = p->pNewUnpacked;
92684    if( !pUnpack ){
92685      Mem *pData = &p->v->aMem[p->iNewReg];
92686      rc = ExpandBlob(pData);
92687      if( rc!=SQLITE_OK ) goto preupdate_new_out;
92688      pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
92689      if( !pUnpack ){
92690        rc = SQLITE_NOMEM;
92691        goto preupdate_new_out;
92692      }
92693      p->pNewUnpacked = pUnpack;
92694    }
92695    pMem = &pUnpack->aMem[iIdx];
92696    if( iIdx==p->pTab->iPKey ){
92697      sqlite3VdbeMemSetInt64(pMem, p->iKey2);
92698    }else if( iIdx>=pUnpack->nField ){
92699      pMem = (sqlite3_value *)columnNullValue();
92700    }
92701  }else{
92702    /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
92703    ** value. Make a copy of the cell contents and return a pointer to it.
92704    ** It is not safe to return a pointer to the memory cell itself as the
92705    ** caller may modify the value text encoding.
92706    */
92707    assert( p->op==SQLITE_UPDATE );
92708    if( !p->aNew ){
92709      p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
92710      if( !p->aNew ){
92711        rc = SQLITE_NOMEM;
92712        goto preupdate_new_out;
92713      }
92714    }
92715    assert( iIdx>=0 && iIdx<p->pCsr->nField );
92716    pMem = &p->aNew[iIdx];
92717    if( pMem->flags==0 ){
92718      if( iIdx==p->pTab->iPKey ){
92719        sqlite3VdbeMemSetInt64(pMem, p->iKey2);
92720      }else{
92721        rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
92722        if( rc!=SQLITE_OK ) goto preupdate_new_out;
92723      }
92724    }
92725  }
92726  *ppValue = pMem;
92727
92728 preupdate_new_out:
92729  sqlite3Error(db, rc);
92730  return sqlite3ApiExit(db, rc);
92731}
92732#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
92733
92734#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
92735/*
92736** Return status data for a single loop within query pStmt.
92737*/
92738SQLITE_API int sqlite3_stmt_scanstatus_v2(
92739  sqlite3_stmt *pStmt,            /* Prepared statement being queried */
92740  int iScan,                      /* Index of loop to report on */
92741  int iScanStatusOp,              /* Which metric to return */
92742  int flags,
92743  void *pOut                      /* OUT: Write the answer here */
92744){
92745  Vdbe *p = (Vdbe*)pStmt;
92746  VdbeOp *aOp;
92747  int nOp;
92748  ScanStatus *pScan = 0;
92749  int idx;
92750
92751#ifdef SQLITE_ENABLE_API_ARMOR
92752  if( p==0 || pOut==0
92753      || iScanStatusOp<SQLITE_SCANSTAT_NLOOP
92754      || iScanStatusOp>SQLITE_SCANSTAT_NCYCLE ){
92755    return 1;
92756  }
92757#endif
92758  aOp = p->aOp;
92759  nOp = p->nOp;
92760  if( p->pFrame ){
92761    VdbeFrame *pFrame;
92762    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
92763    aOp = pFrame->aOp;
92764    nOp = pFrame->nOp;
92765  }
92766
92767  if( iScan<0 ){
92768    int ii;
92769    if( iScanStatusOp==SQLITE_SCANSTAT_NCYCLE ){
92770      i64 res = 0;
92771      for(ii=0; ii<nOp; ii++){
92772        res += aOp[ii].nCycle;
92773      }
92774      *(i64*)pOut = res;
92775      return 0;
92776    }
92777    return 1;
92778  }
92779  if( flags & SQLITE_SCANSTAT_COMPLEX ){
92780    idx = iScan;
92781  }else{
92782    /* If the COMPLEX flag is clear, then this function must ignore any
92783    ** ScanStatus structures with ScanStatus.addrLoop set to 0. */
92784    for(idx=0; idx<p->nScan; idx++){
92785      pScan = &p->aScan[idx];
92786      if( pScan->zName ){
92787        iScan--;
92788        if( iScan<0 ) break;
92789      }
92790    }
92791  }
92792  if( idx>=p->nScan ) return 1;
92793  assert( pScan==0 || pScan==&p->aScan[idx] );
92794  pScan = &p->aScan[idx];
92795
92796  switch( iScanStatusOp ){
92797    case SQLITE_SCANSTAT_NLOOP: {
92798      if( pScan->addrLoop>0 ){
92799        *(sqlite3_int64*)pOut = aOp[pScan->addrLoop].nExec;
92800      }else{
92801        *(sqlite3_int64*)pOut = -1;
92802      }
92803      break;
92804    }
92805    case SQLITE_SCANSTAT_NVISIT: {
92806      if( pScan->addrVisit>0 ){
92807        *(sqlite3_int64*)pOut = aOp[pScan->addrVisit].nExec;
92808      }else{
92809        *(sqlite3_int64*)pOut = -1;
92810      }
92811      break;
92812    }
92813    case SQLITE_SCANSTAT_EST: {
92814      double r = 1.0;
92815      LogEst x = pScan->nEst;
92816      while( x<100 ){
92817        x += 10;
92818        r *= 0.5;
92819      }
92820      *(double*)pOut = r*sqlite3LogEstToInt(x);
92821      break;
92822    }
92823    case SQLITE_SCANSTAT_NAME: {
92824      *(const char**)pOut = pScan->zName;
92825      break;
92826    }
92827    case SQLITE_SCANSTAT_EXPLAIN: {
92828      if( pScan->addrExplain ){
92829        *(const char**)pOut = aOp[ pScan->addrExplain ].p4.z;
92830      }else{
92831        *(const char**)pOut = 0;
92832      }
92833      break;
92834    }
92835    case SQLITE_SCANSTAT_SELECTID: {
92836      if( pScan->addrExplain ){
92837        *(int*)pOut = aOp[ pScan->addrExplain ].p1;
92838      }else{
92839        *(int*)pOut = -1;
92840      }
92841      break;
92842    }
92843    case SQLITE_SCANSTAT_PARENTID: {
92844      if( pScan->addrExplain ){
92845        *(int*)pOut = aOp[ pScan->addrExplain ].p2;
92846      }else{
92847        *(int*)pOut = -1;
92848      }
92849      break;
92850    }
92851    case SQLITE_SCANSTAT_NCYCLE: {
92852      i64 res = 0;
92853      if( pScan->aAddrRange[0]==0 ){
92854        res = -1;
92855      }else{
92856        int ii;
92857        for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
92858          int iIns = pScan->aAddrRange[ii];
92859          int iEnd = pScan->aAddrRange[ii+1];
92860          if( iIns==0 ) break;
92861          if( iIns>0 ){
92862            while( iIns<=iEnd ){
92863              res += aOp[iIns].nCycle;
92864              iIns++;
92865            }
92866          }else{
92867            int iOp;
92868            for(iOp=0; iOp<nOp; iOp++){
92869              Op *pOp = &aOp[iOp];
92870              if( pOp->p1!=iEnd ) continue;
92871              if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_NCYCLE)==0 ){
92872                continue;
92873              }
92874              res += aOp[iOp].nCycle;
92875            }
92876          }
92877        }
92878      }
92879      *(i64*)pOut = res;
92880      break;
92881    }
92882    default: {
92883      return 1;
92884    }
92885  }
92886  return 0;
92887}
92888
92889/*
92890** Return status data for a single loop within query pStmt.
92891*/
92892SQLITE_API int sqlite3_stmt_scanstatus(
92893  sqlite3_stmt *pStmt,            /* Prepared statement being queried */
92894  int iScan,                      /* Index of loop to report on */
92895  int iScanStatusOp,              /* Which metric to return */
92896  void *pOut                      /* OUT: Write the answer here */
92897){
92898  return sqlite3_stmt_scanstatus_v2(pStmt, iScan, iScanStatusOp, 0, pOut);
92899}
92900
92901/*
92902** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
92903*/
92904SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
92905  Vdbe *p = (Vdbe*)pStmt;
92906  int ii;
92907  for(ii=0; p!=0 && ii<p->nOp; ii++){
92908    Op *pOp = &p->aOp[ii];
92909    pOp->nExec = 0;
92910    pOp->nCycle = 0;
92911  }
92912}
92913#endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
92914
92915/************** End of vdbeapi.c *********************************************/
92916/************** Begin file vdbetrace.c ***************************************/
92917/*
92918** 2009 November 25
92919**
92920** The author disclaims copyright to this source code.  In place of
92921** a legal notice, here is a blessing:
92922**
92923**    May you do good and not evil.
92924**    May you find forgiveness for yourself and forgive others.
92925**    May you share freely, never taking more than you give.
92926**
92927*************************************************************************
92928**
92929** This file contains code used to insert the values of host parameters
92930** (aka "wildcards") into the SQL text output by sqlite3_trace().
92931**
92932** The Vdbe parse-tree explainer is also found here.
92933*/
92934/* #include "sqliteInt.h" */
92935/* #include "vdbeInt.h" */
92936
92937#ifndef SQLITE_OMIT_TRACE
92938
92939/*
92940** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
92941** bytes in this text up to but excluding the first character in
92942** a host parameter.  If the text contains no host parameters, return
92943** the total number of bytes in the text.
92944*/
92945static int findNextHostParameter(const char *zSql, int *pnToken){
92946  int tokenType;
92947  int nTotal = 0;
92948  int n;
92949
92950  *pnToken = 0;
92951  while( zSql[0] ){
92952    n = sqlite3GetToken((u8*)zSql, &tokenType);
92953    assert( n>0 && tokenType!=TK_ILLEGAL );
92954    if( tokenType==TK_VARIABLE ){
92955      *pnToken = n;
92956      break;
92957    }
92958    nTotal += n;
92959    zSql += n;
92960  }
92961  return nTotal;
92962}
92963
92964/*
92965** This function returns a pointer to a nul-terminated string in memory
92966** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
92967** string contains a copy of zRawSql but with host parameters expanded to
92968** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
92969** then the returned string holds a copy of zRawSql with "-- " prepended
92970** to each line of text.
92971**
92972** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
92973** then long strings and blobs are truncated to that many bytes.  This
92974** can be used to prevent unreasonably large trace strings when dealing
92975** with large (multi-megabyte) strings and blobs.
92976**
92977** The calling function is responsible for making sure the memory returned
92978** is eventually freed.
92979**
92980** ALGORITHM:  Scan the input string looking for host parameters in any of
92981** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
92982** string literals, quoted identifier names, and comments.  For text forms,
92983** the host parameter index is found by scanning the prepared
92984** statement for the corresponding OP_Variable opcode.  Once the host
92985** parameter index is known, locate the value in p->aVar[].  Then render
92986** the value as a literal in place of the host parameter name.
92987*/
92988SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
92989  Vdbe *p,                 /* The prepared statement being evaluated */
92990  const char *zRawSql      /* Raw text of the SQL statement */
92991){
92992  sqlite3 *db;             /* The database connection */
92993  int idx = 0;             /* Index of a host parameter */
92994  int nextIndex = 1;       /* Index of next ? host parameter */
92995  int n;                   /* Length of a token prefix */
92996  int nToken;              /* Length of the parameter token */
92997  int i;                   /* Loop counter */
92998  Mem *pVar;               /* Value of a host parameter */
92999  StrAccum out;            /* Accumulate the output here */
93000#ifndef SQLITE_OMIT_UTF16
93001  Mem utf8;                /* Used to convert UTF16 into UTF8 for display */
93002#endif
93003
93004  db = p->db;
93005  sqlite3StrAccumInit(&out, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
93006  if( db->nVdbeExec>1 ){
93007    while( *zRawSql ){
93008      const char *zStart = zRawSql;
93009      while( *(zRawSql++)!='\n' && *zRawSql );
93010      sqlite3_str_append(&out, "-- ", 3);
93011      assert( (zRawSql - zStart) > 0 );
93012      sqlite3_str_append(&out, zStart, (int)(zRawSql-zStart));
93013    }
93014  }else if( p->nVar==0 ){
93015    sqlite3_str_append(&out, zRawSql, sqlite3Strlen30(zRawSql));
93016  }else{
93017    while( zRawSql[0] ){
93018      n = findNextHostParameter(zRawSql, &nToken);
93019      assert( n>0 );
93020      sqlite3_str_append(&out, zRawSql, n);
93021      zRawSql += n;
93022      assert( zRawSql[0] || nToken==0 );
93023      if( nToken==0 ) break;
93024      if( zRawSql[0]=='?' ){
93025        if( nToken>1 ){
93026          assert( sqlite3Isdigit(zRawSql[1]) );
93027          sqlite3GetInt32(&zRawSql[1], &idx);
93028        }else{
93029          idx = nextIndex;
93030        }
93031      }else{
93032        assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
93033                zRawSql[0]=='@' || zRawSql[0]=='#' );
93034        testcase( zRawSql[0]==':' );
93035        testcase( zRawSql[0]=='$' );
93036        testcase( zRawSql[0]=='@' );
93037        testcase( zRawSql[0]=='#' );
93038        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
93039        assert( idx>0 );
93040      }
93041      zRawSql += nToken;
93042      nextIndex = MAX(idx + 1, nextIndex);
93043      assert( idx>0 && idx<=p->nVar );
93044      pVar = &p->aVar[idx-1];
93045      if( pVar->flags & MEM_Null ){
93046        sqlite3_str_append(&out, "NULL", 4);
93047      }else if( pVar->flags & (MEM_Int|MEM_IntReal) ){
93048        sqlite3_str_appendf(&out, "%lld", pVar->u.i);
93049      }else if( pVar->flags & MEM_Real ){
93050        sqlite3_str_appendf(&out, "%!.15g", pVar->u.r);
93051      }else if( pVar->flags & MEM_Str ){
93052        int nOut;  /* Number of bytes of the string text to include in output */
93053#ifndef SQLITE_OMIT_UTF16
93054        u8 enc = ENC(db);
93055        if( enc!=SQLITE_UTF8 ){
93056          memset(&utf8, 0, sizeof(utf8));
93057          utf8.db = db;
93058          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
93059          if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
93060            out.accError = SQLITE_NOMEM;
93061            out.nAlloc = 0;
93062          }
93063          pVar = &utf8;
93064        }
93065#endif
93066        nOut = pVar->n;
93067#ifdef SQLITE_TRACE_SIZE_LIMIT
93068        if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
93069          nOut = SQLITE_TRACE_SIZE_LIMIT;
93070          while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
93071        }
93072#endif
93073        sqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z);
93074#ifdef SQLITE_TRACE_SIZE_LIMIT
93075        if( nOut<pVar->n ){
93076          sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
93077        }
93078#endif
93079#ifndef SQLITE_OMIT_UTF16
93080        if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
93081#endif
93082      }else if( pVar->flags & MEM_Zero ){
93083        sqlite3_str_appendf(&out, "zeroblob(%d)", pVar->u.nZero);
93084      }else{
93085        int nOut;  /* Number of bytes of the blob to include in output */
93086        assert( pVar->flags & MEM_Blob );
93087        sqlite3_str_append(&out, "x'", 2);
93088        nOut = pVar->n;
93089#ifdef SQLITE_TRACE_SIZE_LIMIT
93090        if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
93091#endif
93092        for(i=0; i<nOut; i++){
93093          sqlite3_str_appendf(&out, "%02x", pVar->z[i]&0xff);
93094        }
93095        sqlite3_str_append(&out, "'", 1);
93096#ifdef SQLITE_TRACE_SIZE_LIMIT
93097        if( nOut<pVar->n ){
93098          sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
93099        }
93100#endif
93101      }
93102    }
93103  }
93104  if( out.accError ) sqlite3_str_reset(&out);
93105  return sqlite3StrAccumFinish(&out);
93106}
93107
93108#endif /* #ifndef SQLITE_OMIT_TRACE */
93109
93110/************** End of vdbetrace.c *******************************************/
93111/************** Begin file vdbe.c ********************************************/
93112/*
93113** 2001 September 15
93114**
93115** The author disclaims copyright to this source code.  In place of
93116** a legal notice, here is a blessing:
93117**
93118**    May you do good and not evil.
93119**    May you find forgiveness for yourself and forgive others.
93120**    May you share freely, never taking more than you give.
93121**
93122*************************************************************************
93123** The code in this file implements the function that runs the
93124** bytecode of a prepared statement.
93125**
93126** Various scripts scan this source file in order to generate HTML
93127** documentation, headers files, or other derived files.  The formatting
93128** of the code in this file is, therefore, important.  See other comments
93129** in this file for details.  If in doubt, do not deviate from existing
93130** commenting and indentation practices when changing or adding code.
93131*/
93132/* #include "sqliteInt.h" */
93133/* #include "vdbeInt.h" */
93134
93135/*
93136** Invoke this macro on memory cells just prior to changing the
93137** value of the cell.  This macro verifies that shallow copies are
93138** not misused.  A shallow copy of a string or blob just copies a
93139** pointer to the string or blob, not the content.  If the original
93140** is changed while the copy is still in use, the string or blob might
93141** be changed out from under the copy.  This macro verifies that nothing
93142** like that ever happens.
93143*/
93144#ifdef SQLITE_DEBUG
93145# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
93146#else
93147# define memAboutToChange(P,M)
93148#endif
93149
93150/*
93151** The following global variable is incremented every time a cursor
93152** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
93153** procedures use this information to make sure that indices are
93154** working correctly.  This variable has no function other than to
93155** help verify the correct operation of the library.
93156*/
93157#ifdef SQLITE_TEST
93158SQLITE_API int sqlite3_search_count = 0;
93159#endif
93160
93161/*
93162** When this global variable is positive, it gets decremented once before
93163** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
93164** field of the sqlite3 structure is set in order to simulate an interrupt.
93165**
93166** This facility is used for testing purposes only.  It does not function
93167** in an ordinary build.
93168*/
93169#ifdef SQLITE_TEST
93170SQLITE_API int sqlite3_interrupt_count = 0;
93171#endif
93172
93173/*
93174** The next global variable is incremented each type the OP_Sort opcode
93175** is executed.  The test procedures use this information to make sure that
93176** sorting is occurring or not occurring at appropriate times.   This variable
93177** has no function other than to help verify the correct operation of the
93178** library.
93179*/
93180#ifdef SQLITE_TEST
93181SQLITE_API int sqlite3_sort_count = 0;
93182#endif
93183
93184/*
93185** The next global variable records the size of the largest MEM_Blob
93186** or MEM_Str that has been used by a VDBE opcode.  The test procedures
93187** use this information to make sure that the zero-blob functionality
93188** is working correctly.   This variable has no function other than to
93189** help verify the correct operation of the library.
93190*/
93191#ifdef SQLITE_TEST
93192SQLITE_API int sqlite3_max_blobsize = 0;
93193static void updateMaxBlobsize(Mem *p){
93194  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
93195    sqlite3_max_blobsize = p->n;
93196  }
93197}
93198#endif
93199
93200/*
93201** This macro evaluates to true if either the update hook or the preupdate
93202** hook are enabled for database connect DB.
93203*/
93204#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
93205# define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
93206#else
93207# define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
93208#endif
93209
93210/*
93211** The next global variable is incremented each time the OP_Found opcode
93212** is executed. This is used to test whether or not the foreign key
93213** operation implemented using OP_FkIsZero is working. This variable
93214** has no function other than to help verify the correct operation of the
93215** library.
93216*/
93217#ifdef SQLITE_TEST
93218SQLITE_API int sqlite3_found_count = 0;
93219#endif
93220
93221/*
93222** Test a register to see if it exceeds the current maximum blob size.
93223** If it does, record the new maximum blob size.
93224*/
93225#if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
93226# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
93227#else
93228# define UPDATE_MAX_BLOBSIZE(P)
93229#endif
93230
93231#ifdef SQLITE_DEBUG
93232/* This routine provides a convenient place to set a breakpoint during
93233** tracing with PRAGMA vdbe_trace=on.  The breakpoint fires right after
93234** each opcode is printed.  Variables "pc" (program counter) and pOp are
93235** available to add conditionals to the breakpoint.  GDB example:
93236**
93237**         break test_trace_breakpoint if pc=22
93238**
93239** Other useful labels for breakpoints include:
93240**   test_addop_breakpoint(pc,pOp)
93241**   sqlite3CorruptError(lineno)
93242**   sqlite3MisuseError(lineno)
93243**   sqlite3CantopenError(lineno)
93244*/
93245static void test_trace_breakpoint(int pc, Op *pOp, Vdbe *v){
93246  static u64 n = 0;
93247  (void)pc;
93248  (void)pOp;
93249  (void)v;
93250  n++;
93251  if( n==LARGEST_UINT64 ) abort(); /* So that n is used, preventing a warning */
93252}
93253#endif
93254
93255/*
93256** Invoke the VDBE coverage callback, if that callback is defined.  This
93257** feature is used for test suite validation only and does not appear an
93258** production builds.
93259**
93260** M is the type of branch.  I is the direction taken for this instance of
93261** the branch.
93262**
93263**   M: 2 - two-way branch (I=0: fall-thru   1: jump                )
93264**      3 - two-way + NULL (I=0: fall-thru   1: jump      2: NULL   )
93265**      4 - OP_Jump        (I=0: jump p1     1: jump p2   2: jump p3)
93266**
93267** In other words, if M is 2, then I is either 0 (for fall-through) or
93268** 1 (for when the branch is taken).  If M is 3, the I is 0 for an
93269** ordinary fall-through, I is 1 if the branch was taken, and I is 2
93270** if the result of comparison is NULL.  For M=3, I=2 the jump may or
93271** may not be taken, depending on the SQLITE_JUMPIFNULL flags in p5.
93272** When M is 4, that means that an OP_Jump is being run.  I is 0, 1, or 2
93273** depending on if the operands are less than, equal, or greater than.
93274**
93275** iSrcLine is the source code line (from the __LINE__ macro) that
93276** generated the VDBE instruction combined with flag bits.  The source
93277** code line number is in the lower 24 bits of iSrcLine and the upper
93278** 8 bytes are flags.  The lower three bits of the flags indicate
93279** values for I that should never occur.  For example, if the branch is
93280** always taken, the flags should be 0x05 since the fall-through and
93281** alternate branch are never taken.  If a branch is never taken then
93282** flags should be 0x06 since only the fall-through approach is allowed.
93283**
93284** Bit 0x08 of the flags indicates an OP_Jump opcode that is only
93285** interested in equal or not-equal.  In other words, I==0 and I==2
93286** should be treated as equivalent
93287**
93288** Since only a line number is retained, not the filename, this macro
93289** only works for amalgamation builds.  But that is ok, since these macros
93290** should be no-ops except for special builds used to measure test coverage.
93291*/
93292#if !defined(SQLITE_VDBE_COVERAGE)
93293# define VdbeBranchTaken(I,M)
93294#else
93295# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
93296  static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){
93297    u8 mNever;
93298    assert( I<=2 );  /* 0: fall through,  1: taken,  2: alternate taken */
93299    assert( M<=4 );  /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */
93300    assert( I<M );   /* I can only be 2 if M is 3 or 4 */
93301    /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */
93302    I = 1<<I;
93303    /* The upper 8 bits of iSrcLine are flags.  The lower three bits of
93304    ** the flags indicate directions that the branch can never go.  If
93305    ** a branch really does go in one of those directions, assert right
93306    ** away. */
93307    mNever = iSrcLine >> 24;
93308    assert( (I & mNever)==0 );
93309    if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
93310    /* Invoke the branch coverage callback with three arguments:
93311    **    iSrcLine - the line number of the VdbeCoverage() macro, with
93312    **               flags removed.
93313    **    I        - Mask of bits 0x07 indicating which cases are are
93314    **               fulfilled by this instance of the jump.  0x01 means
93315    **               fall-thru, 0x02 means taken, 0x04 means NULL.  Any
93316    **               impossible cases (ex: if the comparison is never NULL)
93317    **               are filled in automatically so that the coverage
93318    **               measurement logic does not flag those impossible cases
93319    **               as missed coverage.
93320    **    M        - Type of jump.  Same as M argument above
93321    */
93322    I |= mNever;
93323    if( M==2 ) I |= 0x04;
93324    if( M==4 ){
93325      I |= 0x08;
93326      if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/
93327    }
93328    sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
93329                                    iSrcLine&0xffffff, I, M);
93330  }
93331#endif
93332
93333/*
93334** An ephemeral string value (signified by the MEM_Ephem flag) contains
93335** a pointer to a dynamically allocated string where some other entity
93336** is responsible for deallocating that string.  Because the register
93337** does not control the string, it might be deleted without the register
93338** knowing it.
93339**
93340** This routine converts an ephemeral string into a dynamically allocated
93341** string that the register itself controls.  In other words, it
93342** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
93343*/
93344#define Deephemeralize(P) \
93345   if( ((P)->flags&MEM_Ephem)!=0 \
93346       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
93347
93348/* Return true if the cursor was opened using the OP_OpenSorter opcode. */
93349#define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
93350
93351/*
93352** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
93353** if we run out of memory.
93354*/
93355static VdbeCursor *allocateCursor(
93356  Vdbe *p,              /* The virtual machine */
93357  int iCur,             /* Index of the new VdbeCursor */
93358  int nField,           /* Number of fields in the table or index */
93359  u8 eCurType           /* Type of the new cursor */
93360){
93361  /* Find the memory cell that will be used to store the blob of memory
93362  ** required for this VdbeCursor structure. It is convenient to use a
93363  ** vdbe memory cell to manage the memory allocation required for a
93364  ** VdbeCursor structure for the following reasons:
93365  **
93366  **   * Sometimes cursor numbers are used for a couple of different
93367  **     purposes in a vdbe program. The different uses might require
93368  **     different sized allocations. Memory cells provide growable
93369  **     allocations.
93370  **
93371  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
93372  **     be freed lazily via the sqlite3_release_memory() API. This
93373  **     minimizes the number of malloc calls made by the system.
93374  **
93375  ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
93376  ** the top of the register space.  Cursor 1 is at Mem[p->nMem-1].
93377  ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
93378  */
93379  Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
93380
93381  int nByte;
93382  VdbeCursor *pCx = 0;
93383  nByte =
93384      ROUND8P(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
93385      (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
93386
93387  assert( iCur>=0 && iCur<p->nCursor );
93388  if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
93389    sqlite3VdbeFreeCursorNN(p, p->apCsr[iCur]);
93390    p->apCsr[iCur] = 0;
93391  }
93392
93393  /* There used to be a call to sqlite3VdbeMemClearAndResize() to make sure
93394  ** the pMem used to hold space for the cursor has enough storage available
93395  ** in pMem->zMalloc.  But for the special case of the aMem[] entries used
93396  ** to hold cursors, it is faster to in-line the logic. */
93397  assert( pMem->flags==MEM_Undefined );
93398  assert( (pMem->flags & MEM_Dyn)==0 );
93399  assert( pMem->szMalloc==0 || pMem->z==pMem->zMalloc );
93400  if( pMem->szMalloc<nByte ){
93401    if( pMem->szMalloc>0 ){
93402      sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
93403    }
93404    pMem->z = pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, nByte);
93405    if( pMem->zMalloc==0 ){
93406      pMem->szMalloc = 0;
93407      return 0;
93408    }
93409    pMem->szMalloc = nByte;
93410  }
93411
93412  p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->zMalloc;
93413  memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
93414  pCx->eCurType = eCurType;
93415  pCx->nField = nField;
93416  pCx->aOffset = &pCx->aType[nField];
93417  if( eCurType==CURTYPE_BTREE ){
93418    pCx->uc.pCursor = (BtCursor*)
93419        &pMem->z[ROUND8P(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
93420    sqlite3BtreeCursorZero(pCx->uc.pCursor);
93421  }
93422  return pCx;
93423}
93424
93425/*
93426** The string in pRec is known to look like an integer and to have a
93427** floating point value of rValue.  Return true and set *piValue to the
93428** integer value if the string is in range to be an integer.  Otherwise,
93429** return false.
93430*/
93431static int alsoAnInt(Mem *pRec, double rValue, i64 *piValue){
93432  i64 iValue;
93433  iValue = sqlite3RealToI64(rValue);
93434  if( sqlite3RealSameAsInt(rValue,iValue) ){
93435    *piValue = iValue;
93436    return 1;
93437  }
93438  return 0==sqlite3Atoi64(pRec->z, piValue, pRec->n, pRec->enc);
93439}
93440
93441/*
93442** Try to convert a value into a numeric representation if we can
93443** do so without loss of information.  In other words, if the string
93444** looks like a number, convert it into a number.  If it does not
93445** look like a number, leave it alone.
93446**
93447** If the bTryForInt flag is true, then extra effort is made to give
93448** an integer representation.  Strings that look like floating point
93449** values but which have no fractional component (example: '48.00')
93450** will have a MEM_Int representation when bTryForInt is true.
93451**
93452** If bTryForInt is false, then if the input string contains a decimal
93453** point or exponential notation, the result is only MEM_Real, even
93454** if there is an exact integer representation of the quantity.
93455*/
93456static void applyNumericAffinity(Mem *pRec, int bTryForInt){
93457  double rValue;
93458  u8 enc = pRec->enc;
93459  int rc;
93460  assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str );
93461  rc = sqlite3AtoF(pRec->z, &rValue, pRec->n, enc);
93462  if( rc<=0 ) return;
93463  if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){
93464    pRec->flags |= MEM_Int;
93465  }else{
93466    pRec->u.r = rValue;
93467    pRec->flags |= MEM_Real;
93468    if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
93469  }
93470  /* TEXT->NUMERIC is many->one.  Hence, it is important to invalidate the
93471  ** string representation after computing a numeric equivalent, because the
93472  ** string representation might not be the canonical representation for the
93473  ** numeric value.  Ticket [343634942dd54ab57b7024] 2018-01-31. */
93474  pRec->flags &= ~MEM_Str;
93475}
93476
93477/*
93478** Processing is determine by the affinity parameter:
93479**
93480** SQLITE_AFF_INTEGER:
93481** SQLITE_AFF_REAL:
93482** SQLITE_AFF_NUMERIC:
93483**    Try to convert pRec to an integer representation or a
93484**    floating-point representation if an integer representation
93485**    is not possible.  Note that the integer representation is
93486**    always preferred, even if the affinity is REAL, because
93487**    an integer representation is more space efficient on disk.
93488**
93489** SQLITE_AFF_FLEXNUM:
93490**    If the value is text, then try to convert it into a number of
93491**    some kind (integer or real) but do not make any other changes.
93492**
93493** SQLITE_AFF_TEXT:
93494**    Convert pRec to a text representation.
93495**
93496** SQLITE_AFF_BLOB:
93497** SQLITE_AFF_NONE:
93498**    No-op.  pRec is unchanged.
93499*/
93500static void applyAffinity(
93501  Mem *pRec,          /* The value to apply affinity to */
93502  char affinity,      /* The affinity to be applied */
93503  u8 enc              /* Use this text encoding */
93504){
93505  if( affinity>=SQLITE_AFF_NUMERIC ){
93506    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
93507             || affinity==SQLITE_AFF_NUMERIC || affinity==SQLITE_AFF_FLEXNUM );
93508    if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
93509      if( (pRec->flags & (MEM_Real|MEM_IntReal))==0 ){
93510        if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
93511      }else if( affinity<=SQLITE_AFF_REAL ){
93512        sqlite3VdbeIntegerAffinity(pRec);
93513      }
93514    }
93515  }else if( affinity==SQLITE_AFF_TEXT ){
93516    /* Only attempt the conversion to TEXT if there is an integer or real
93517    ** representation (blob and NULL do not get converted) but no string
93518    ** representation.  It would be harmless to repeat the conversion if
93519    ** there is already a string rep, but it is pointless to waste those
93520    ** CPU cycles. */
93521    if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
93522      if( (pRec->flags&(MEM_Real|MEM_Int|MEM_IntReal)) ){
93523        testcase( pRec->flags & MEM_Int );
93524        testcase( pRec->flags & MEM_Real );
93525        testcase( pRec->flags & MEM_IntReal );
93526        sqlite3VdbeMemStringify(pRec, enc, 1);
93527      }
93528    }
93529    pRec->flags &= ~(MEM_Real|MEM_Int|MEM_IntReal);
93530  }
93531}
93532
93533/*
93534** Try to convert the type of a function argument or a result column
93535** into a numeric representation.  Use either INTEGER or REAL whichever
93536** is appropriate.  But only do the conversion if it is possible without
93537** loss of information and return the revised type of the argument.
93538*/
93539SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
93540  int eType = sqlite3_value_type(pVal);
93541  if( eType==SQLITE_TEXT ){
93542    Mem *pMem = (Mem*)pVal;
93543    applyNumericAffinity(pMem, 0);
93544    eType = sqlite3_value_type(pVal);
93545  }
93546  return eType;
93547}
93548
93549/*
93550** Exported version of applyAffinity(). This one works on sqlite3_value*,
93551** not the internal Mem* type.
93552*/
93553SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
93554  sqlite3_value *pVal,
93555  u8 affinity,
93556  u8 enc
93557){
93558  applyAffinity((Mem *)pVal, affinity, enc);
93559}
93560
93561/*
93562** pMem currently only holds a string type (or maybe a BLOB that we can
93563** interpret as a string if we want to).  Compute its corresponding
93564** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
93565** accordingly.
93566*/
93567static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
93568  int rc;
93569  sqlite3_int64 ix;
93570  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 );
93571  assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
93572  if( ExpandBlob(pMem) ){
93573    pMem->u.i = 0;
93574    return MEM_Int;
93575  }
93576  rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
93577  if( rc<=0 ){
93578    if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){
93579      pMem->u.i = ix;
93580      return MEM_Int;
93581    }else{
93582      return MEM_Real;
93583    }
93584  }else if( rc==1 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){
93585    pMem->u.i = ix;
93586    return MEM_Int;
93587  }
93588  return MEM_Real;
93589}
93590
93591/*
93592** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
93593** none.
93594**
93595** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
93596** But it does set pMem->u.r and pMem->u.i appropriately.
93597*/
93598static u16 numericType(Mem *pMem){
93599  assert( (pMem->flags & MEM_Null)==0
93600       || pMem->db==0 || pMem->db->mallocFailed );
93601  if( pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null) ){
93602    testcase( pMem->flags & MEM_Int );
93603    testcase( pMem->flags & MEM_Real );
93604    testcase( pMem->flags & MEM_IntReal );
93605    return pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null);
93606  }
93607  assert( pMem->flags & (MEM_Str|MEM_Blob) );
93608  testcase( pMem->flags & MEM_Str );
93609  testcase( pMem->flags & MEM_Blob );
93610  return computeNumericType(pMem);
93611  return 0;
93612}
93613
93614#ifdef SQLITE_DEBUG
93615/*
93616** Write a nice string representation of the contents of cell pMem
93617** into buffer zBuf, length nBuf.
93618*/
93619SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr){
93620  int f = pMem->flags;
93621  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
93622  if( f&MEM_Blob ){
93623    int i;
93624    char c;
93625    if( f & MEM_Dyn ){
93626      c = 'z';
93627      assert( (f & (MEM_Static|MEM_Ephem))==0 );
93628    }else if( f & MEM_Static ){
93629      c = 't';
93630      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
93631    }else if( f & MEM_Ephem ){
93632      c = 'e';
93633      assert( (f & (MEM_Static|MEM_Dyn))==0 );
93634    }else{
93635      c = 's';
93636    }
93637    sqlite3_str_appendf(pStr, "%cx[", c);
93638    for(i=0; i<25 && i<pMem->n; i++){
93639      sqlite3_str_appendf(pStr, "%02X", ((int)pMem->z[i] & 0xFF));
93640    }
93641    sqlite3_str_appendf(pStr, "|");
93642    for(i=0; i<25 && i<pMem->n; i++){
93643      char z = pMem->z[i];
93644      sqlite3_str_appendchar(pStr, 1, (z<32||z>126)?'.':z);
93645    }
93646    sqlite3_str_appendf(pStr,"]");
93647    if( f & MEM_Zero ){
93648      sqlite3_str_appendf(pStr, "+%dz",pMem->u.nZero);
93649    }
93650  }else if( f & MEM_Str ){
93651    int j;
93652    u8 c;
93653    if( f & MEM_Dyn ){
93654      c = 'z';
93655      assert( (f & (MEM_Static|MEM_Ephem))==0 );
93656    }else if( f & MEM_Static ){
93657      c = 't';
93658      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
93659    }else if( f & MEM_Ephem ){
93660      c = 'e';
93661      assert( (f & (MEM_Static|MEM_Dyn))==0 );
93662    }else{
93663      c = 's';
93664    }
93665    sqlite3_str_appendf(pStr, " %c%d[", c, pMem->n);
93666    for(j=0; j<25 && j<pMem->n; j++){
93667      c = pMem->z[j];
93668      sqlite3_str_appendchar(pStr, 1, (c>=0x20&&c<=0x7f) ? c : '.');
93669    }
93670    sqlite3_str_appendf(pStr, "]%s", encnames[pMem->enc]);
93671    if( f & MEM_Term ){
93672      sqlite3_str_appendf(pStr, "(0-term)");
93673    }
93674  }
93675}
93676#endif
93677
93678#ifdef SQLITE_DEBUG
93679/*
93680** Print the value of a register for tracing purposes:
93681*/
93682static void memTracePrint(Mem *p){
93683  if( p->flags & MEM_Undefined ){
93684    printf(" undefined");
93685  }else if( p->flags & MEM_Null ){
93686    printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
93687  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
93688    printf(" si:%lld", p->u.i);
93689  }else if( (p->flags & (MEM_IntReal))!=0 ){
93690    printf(" ir:%lld", p->u.i);
93691  }else if( p->flags & MEM_Int ){
93692    printf(" i:%lld", p->u.i);
93693#ifndef SQLITE_OMIT_FLOATING_POINT
93694  }else if( p->flags & MEM_Real ){
93695    printf(" r:%.17g", p->u.r);
93696#endif
93697  }else if( sqlite3VdbeMemIsRowSet(p) ){
93698    printf(" (rowset)");
93699  }else{
93700    StrAccum acc;
93701    char zBuf[1000];
93702    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
93703    sqlite3VdbeMemPrettyPrint(p, &acc);
93704    printf(" %s", sqlite3StrAccumFinish(&acc));
93705  }
93706  if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
93707}
93708static void registerTrace(int iReg, Mem *p){
93709  printf("R[%d] = ", iReg);
93710  memTracePrint(p);
93711  if( p->pScopyFrom ){
93712    printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg]));
93713  }
93714  printf("\n");
93715  sqlite3VdbeCheckMemInvariants(p);
93716}
93717/**/ void sqlite3PrintMem(Mem *pMem){
93718  memTracePrint(pMem);
93719  printf("\n");
93720  fflush(stdout);
93721}
93722#endif
93723
93724#ifdef SQLITE_DEBUG
93725/*
93726** Show the values of all registers in the virtual machine.  Used for
93727** interactive debugging.
93728*/
93729SQLITE_PRIVATE void sqlite3VdbeRegisterDump(Vdbe *v){
93730  int i;
93731  for(i=1; i<v->nMem; i++) registerTrace(i, v->aMem+i);
93732}
93733#endif /* SQLITE_DEBUG */
93734
93735
93736#ifdef SQLITE_DEBUG
93737#  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
93738#else
93739#  define REGISTER_TRACE(R,M)
93740#endif
93741
93742#ifndef NDEBUG
93743/*
93744** This function is only called from within an assert() expression. It
93745** checks that the sqlite3.nTransaction variable is correctly set to
93746** the number of non-transaction savepoints currently in the
93747** linked list starting at sqlite3.pSavepoint.
93748**
93749** Usage:
93750**
93751**     assert( checkSavepointCount(db) );
93752*/
93753static int checkSavepointCount(sqlite3 *db){
93754  int n = 0;
93755  Savepoint *p;
93756  for(p=db->pSavepoint; p; p=p->pNext) n++;
93757  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
93758  return 1;
93759}
93760#endif
93761
93762/*
93763** Return the register of pOp->p2 after first preparing it to be
93764** overwritten with an integer value.
93765*/
93766static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
93767  sqlite3VdbeMemSetNull(pOut);
93768  pOut->flags = MEM_Int;
93769  return pOut;
93770}
93771static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
93772  Mem *pOut;
93773  assert( pOp->p2>0 );
93774  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
93775  pOut = &p->aMem[pOp->p2];
93776  memAboutToChange(p, pOut);
93777  if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
93778    return out2PrereleaseWithClear(pOut);
93779  }else{
93780    pOut->flags = MEM_Int;
93781    return pOut;
93782  }
93783}
93784
93785/*
93786** Compute a bloom filter hash using pOp->p4.i registers from aMem[] beginning
93787** with pOp->p3.  Return the hash.
93788*/
93789static u64 filterHash(const Mem *aMem, const Op *pOp){
93790  int i, mx;
93791  u64 h = 0;
93792
93793  assert( pOp->p4type==P4_INT32 );
93794  for(i=pOp->p3, mx=i+pOp->p4.i; i<mx; i++){
93795    const Mem *p = &aMem[i];
93796    if( p->flags & (MEM_Int|MEM_IntReal) ){
93797      h += p->u.i;
93798    }else if( p->flags & MEM_Real ){
93799      h += sqlite3VdbeIntValue(p);
93800    }else if( p->flags & (MEM_Str|MEM_Blob) ){
93801      /* All strings have the same hash and all blobs have the same hash,
93802      ** though, at least, those hashes are different from each other and
93803      ** from NULL. */
93804      h += 4093 + (p->flags & (MEM_Str|MEM_Blob));
93805    }
93806  }
93807  return h;
93808}
93809
93810
93811/*
93812** For OP_Column, factor out the case where content is loaded from
93813** overflow pages, so that the code to implement this case is separate
93814** the common case where all content fits on the page.  Factoring out
93815** the code reduces register pressure and helps the common case
93816** to run faster.
93817*/
93818static SQLITE_NOINLINE int vdbeColumnFromOverflow(
93819  VdbeCursor *pC,       /* The BTree cursor from which we are reading */
93820  int iCol,             /* The column to read */
93821  int t,                /* The serial-type code for the column value */
93822  i64 iOffset,          /* Offset to the start of the content value */
93823  u32 cacheStatus,      /* Current Vdbe.cacheCtr value */
93824  u32 colCacheCtr,      /* Current value of the column cache counter */
93825  Mem *pDest            /* Store the value into this register. */
93826){
93827  int rc;
93828  sqlite3 *db = pDest->db;
93829  int encoding = pDest->enc;
93830  int len = sqlite3VdbeSerialTypeLen(t);
93831  assert( pC->eCurType==CURTYPE_BTREE );
93832  if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) return SQLITE_TOOBIG;
93833  if( len > 4000 && pC->pKeyInfo==0 ){
93834    /* Cache large column values that are on overflow pages using
93835    ** an RCStr (reference counted string) so that if they are reloaded,
93836    ** that do not have to be copied a second time.  The overhead of
93837    ** creating and managing the cache is such that this is only
93838    ** profitable for larger TEXT and BLOB values.
93839    **
93840    ** Only do this on table-btrees so that writes to index-btrees do not
93841    ** need to clear the cache.  This buys performance in the common case
93842    ** in exchange for generality.
93843    */
93844    VdbeTxtBlbCache *pCache;
93845    char *pBuf;
93846    if( pC->colCache==0 ){
93847      pC->pCache = sqlite3DbMallocZero(db, sizeof(VdbeTxtBlbCache) );
93848      if( pC->pCache==0 ) return SQLITE_NOMEM;
93849      pC->colCache = 1;
93850    }
93851    pCache = pC->pCache;
93852    if( pCache->pCValue==0
93853     || pCache->iCol!=iCol
93854     || pCache->cacheStatus!=cacheStatus
93855     || pCache->colCacheCtr!=colCacheCtr
93856     || pCache->iOffset!=sqlite3BtreeOffset(pC->uc.pCursor)
93857    ){
93858      if( pCache->pCValue ) sqlite3RCStrUnref(pCache->pCValue);
93859      pBuf = pCache->pCValue = sqlite3RCStrNew( len+3 );
93860      if( pBuf==0 ) return SQLITE_NOMEM;
93861      rc = sqlite3BtreePayload(pC->uc.pCursor, iOffset, len, pBuf);
93862      if( rc ) return rc;
93863      pBuf[len] = 0;
93864      pBuf[len+1] = 0;
93865      pBuf[len+2] = 0;
93866      pCache->iCol = iCol;
93867      pCache->cacheStatus = cacheStatus;
93868      pCache->colCacheCtr = colCacheCtr;
93869      pCache->iOffset = sqlite3BtreeOffset(pC->uc.pCursor);
93870    }else{
93871      pBuf = pCache->pCValue;
93872    }
93873    assert( t>=12 );
93874    sqlite3RCStrRef(pBuf);
93875    if( t&1 ){
93876      rc = sqlite3VdbeMemSetStr(pDest, pBuf, len, encoding,
93877                                sqlite3RCStrUnref);
93878      pDest->flags |= MEM_Term;
93879    }else{
93880      rc = sqlite3VdbeMemSetStr(pDest, pBuf, len, 0,
93881                                sqlite3RCStrUnref);
93882    }
93883  }else{
93884    rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, iOffset, len, pDest);
93885    if( rc ) return rc;
93886    sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
93887    if( (t&1)!=0 && encoding==SQLITE_UTF8 ){
93888      pDest->z[len] = 0;
93889      pDest->flags |= MEM_Term;
93890    }
93891  }
93892  pDest->flags &= ~MEM_Ephem;
93893  return rc;
93894}
93895
93896
93897/*
93898** Return the symbolic name for the data type of a pMem
93899*/
93900static const char *vdbeMemTypeName(Mem *pMem){
93901  static const char *azTypes[] = {
93902      /* SQLITE_INTEGER */ "INT",
93903      /* SQLITE_FLOAT   */ "REAL",
93904      /* SQLITE_TEXT    */ "TEXT",
93905      /* SQLITE_BLOB    */ "BLOB",
93906      /* SQLITE_NULL    */ "NULL"
93907  };
93908  return azTypes[sqlite3_value_type(pMem)-1];
93909}
93910
93911/*
93912** Execute as much of a VDBE program as we can.
93913** This is the core of sqlite3_step().
93914*/
93915SQLITE_PRIVATE int sqlite3VdbeExec(
93916  Vdbe *p                    /* The VDBE */
93917){
93918  Op *aOp = p->aOp;          /* Copy of p->aOp */
93919  Op *pOp = aOp;             /* Current operation */
93920#ifdef SQLITE_DEBUG
93921  Op *pOrigOp;               /* Value of pOp at the top of the loop */
93922  int nExtraDelete = 0;      /* Verifies FORDELETE and AUXDELETE flags */
93923  u8 iCompareIsInit = 0;     /* iCompare is initialized */
93924#endif
93925  int rc = SQLITE_OK;        /* Value to return */
93926  sqlite3 *db = p->db;       /* The database */
93927  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
93928  u8 encoding = ENC(db);     /* The database encoding */
93929  int iCompare = 0;          /* Result of last comparison */
93930  u64 nVmStep = 0;           /* Number of virtual machine steps */
93931#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
93932  u64 nProgressLimit;        /* Invoke xProgress() when nVmStep reaches this */
93933#endif
93934  Mem *aMem = p->aMem;       /* Copy of p->aMem */
93935  Mem *pIn1 = 0;             /* 1st input operand */
93936  Mem *pIn2 = 0;             /* 2nd input operand */
93937  Mem *pIn3 = 0;             /* 3rd input operand */
93938  Mem *pOut = 0;             /* Output operand */
93939  u32 colCacheCtr = 0;       /* Column cache counter */
93940#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
93941  u64 *pnCycle = 0;
93942  int bStmtScanStatus = IS_STMT_SCANSTATUS(db)!=0;
93943#endif
93944  /*** INSERT STACK UNION HERE ***/
93945
93946  assert( p->eVdbeState==VDBE_RUN_STATE );  /* sqlite3_step() verifies this */
93947  if( DbMaskNonZero(p->lockMask) ){
93948    sqlite3VdbeEnter(p);
93949  }
93950#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
93951  if( db->xProgress ){
93952    u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
93953    assert( 0 < db->nProgressOps );
93954    nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
93955  }else{
93956    nProgressLimit = LARGEST_UINT64;
93957  }
93958#endif
93959  if( p->rc==SQLITE_NOMEM ){
93960    /* This happens if a malloc() inside a call to sqlite3_column_text() or
93961    ** sqlite3_column_text16() failed.  */
93962    goto no_mem;
93963  }
93964  assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
93965  testcase( p->rc!=SQLITE_OK );
93966  p->rc = SQLITE_OK;
93967  assert( p->bIsReader || p->readOnly!=0 );
93968  p->iCurrentTime = 0;
93969  assert( p->explain==0 );
93970  db->busyHandler.nBusy = 0;
93971  if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
93972  sqlite3VdbeIOTraceSql(p);
93973#ifdef SQLITE_DEBUG
93974  sqlite3BeginBenignMalloc();
93975  if( p->pc==0
93976   && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
93977  ){
93978    int i;
93979    int once = 1;
93980    sqlite3VdbePrintSql(p);
93981    if( p->db->flags & SQLITE_VdbeListing ){
93982      printf("VDBE Program Listing:\n");
93983      for(i=0; i<p->nOp; i++){
93984        sqlite3VdbePrintOp(stdout, i, &aOp[i]);
93985      }
93986    }
93987    if( p->db->flags & SQLITE_VdbeEQP ){
93988      for(i=0; i<p->nOp; i++){
93989        if( aOp[i].opcode==OP_Explain ){
93990          if( once ) printf("VDBE Query Plan:\n");
93991          printf("%s\n", aOp[i].p4.z);
93992          once = 0;
93993        }
93994      }
93995    }
93996    if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
93997  }
93998  sqlite3EndBenignMalloc();
93999#endif
94000  for(pOp=&aOp[p->pc]; 1; pOp++){
94001    /* Errors are detected by individual opcodes, with an immediate
94002    ** jumps to abort_due_to_error. */
94003    assert( rc==SQLITE_OK );
94004
94005    assert( pOp>=aOp && pOp<&aOp[p->nOp]);
94006    nVmStep++;
94007
94008#if defined(VDBE_PROFILE)
94009    pOp->nExec++;
94010    pnCycle = &pOp->nCycle;
94011    if( sqlite3NProfileCnt==0 ) *pnCycle -= sqlite3Hwtime();
94012#elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
94013    if( bStmtScanStatus ){
94014      pOp->nExec++;
94015      pnCycle = &pOp->nCycle;
94016      *pnCycle -= sqlite3Hwtime();
94017    }
94018#endif
94019
94020    /* Only allow tracing if SQLITE_DEBUG is defined.
94021    */
94022#ifdef SQLITE_DEBUG
94023    if( db->flags & SQLITE_VdbeTrace ){
94024      sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
94025      test_trace_breakpoint((int)(pOp - aOp),pOp,p);
94026    }
94027#endif
94028
94029
94030    /* Check to see if we need to simulate an interrupt.  This only happens
94031    ** if we have a special test build.
94032    */
94033#ifdef SQLITE_TEST
94034    if( sqlite3_interrupt_count>0 ){
94035      sqlite3_interrupt_count--;
94036      if( sqlite3_interrupt_count==0 ){
94037        sqlite3_interrupt(db);
94038      }
94039    }
94040#endif
94041
94042    /* Sanity checking on other operands */
94043#ifdef SQLITE_DEBUG
94044    {
94045      u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
94046      if( (opProperty & OPFLG_IN1)!=0 ){
94047        assert( pOp->p1>0 );
94048        assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
94049        assert( memIsValid(&aMem[pOp->p1]) );
94050        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
94051        REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
94052      }
94053      if( (opProperty & OPFLG_IN2)!=0 ){
94054        assert( pOp->p2>0 );
94055        assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
94056        assert( memIsValid(&aMem[pOp->p2]) );
94057        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
94058        REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
94059      }
94060      if( (opProperty & OPFLG_IN3)!=0 ){
94061        assert( pOp->p3>0 );
94062        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
94063        assert( memIsValid(&aMem[pOp->p3]) );
94064        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
94065        REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
94066      }
94067      if( (opProperty & OPFLG_OUT2)!=0 ){
94068        assert( pOp->p2>0 );
94069        assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
94070        memAboutToChange(p, &aMem[pOp->p2]);
94071      }
94072      if( (opProperty & OPFLG_OUT3)!=0 ){
94073        assert( pOp->p3>0 );
94074        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
94075        memAboutToChange(p, &aMem[pOp->p3]);
94076      }
94077    }
94078#endif
94079#ifdef SQLITE_DEBUG
94080    pOrigOp = pOp;
94081#endif
94082
94083    switch( pOp->opcode ){
94084
94085/*****************************************************************************
94086** What follows is a massive switch statement where each case implements a
94087** separate instruction in the virtual machine.  If we follow the usual
94088** indentation conventions, each case should be indented by 6 spaces.  But
94089** that is a lot of wasted space on the left margin.  So the code within
94090** the switch statement will break with convention and be flush-left. Another
94091** big comment (similar to this one) will mark the point in the code where
94092** we transition back to normal indentation.
94093**
94094** The formatting of each case is important.  The makefile for SQLite
94095** generates two C files "opcodes.h" and "opcodes.c" by scanning this
94096** file looking for lines that begin with "case OP_".  The opcodes.h files
94097** will be filled with #defines that give unique integer values to each
94098** opcode and the opcodes.c file is filled with an array of strings where
94099** each string is the symbolic name for the corresponding opcode.  If the
94100** case statement is followed by a comment of the form "/# same as ... #/"
94101** that comment is used to determine the particular value of the opcode.
94102**
94103** Other keywords in the comment that follows each case are used to
94104** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
94105** Keywords include: in1, in2, in3, out2, out3.  See
94106** the mkopcodeh.awk script for additional information.
94107**
94108** Documentation about VDBE opcodes is generated by scanning this file
94109** for lines of that contain "Opcode:".  That line and all subsequent
94110** comment lines are used in the generation of the opcode.html documentation
94111** file.
94112**
94113** SUMMARY:
94114**
94115**     Formatting is important to scripts that scan this file.
94116**     Do not deviate from the formatting style currently in use.
94117**
94118*****************************************************************************/
94119
94120/* Opcode:  Goto * P2 * * *
94121**
94122** An unconditional jump to address P2.
94123** The next instruction executed will be
94124** the one at index P2 from the beginning of
94125** the program.
94126**
94127** The P1 parameter is not actually used by this opcode.  However, it
94128** is sometimes set to 1 instead of 0 as a hint to the command-line shell
94129** that this Goto is the bottom of a loop and that the lines from P2 down
94130** to the current line should be indented for EXPLAIN output.
94131*/
94132case OP_Goto: {             /* jump */
94133
94134#ifdef SQLITE_DEBUG
94135  /* In debugging mode, when the p5 flags is set on an OP_Goto, that
94136  ** means we should really jump back to the preceding OP_ReleaseReg
94137  ** instruction. */
94138  if( pOp->p5 ){
94139    assert( pOp->p2 < (int)(pOp - aOp) );
94140    assert( pOp->p2 > 1 );
94141    pOp = &aOp[pOp->p2 - 2];
94142    assert( pOp[1].opcode==OP_ReleaseReg );
94143    goto check_for_interrupt;
94144  }
94145#endif
94146
94147jump_to_p2_and_check_for_interrupt:
94148  pOp = &aOp[pOp->p2 - 1];
94149
94150  /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
94151  ** OP_VNext, or OP_SorterNext) all jump here upon
94152  ** completion.  Check to see if sqlite3_interrupt() has been called
94153  ** or if the progress callback needs to be invoked.
94154  **
94155  ** This code uses unstructured "goto" statements and does not look clean.
94156  ** But that is not due to sloppy coding habits. The code is written this
94157  ** way for performance, to avoid having to run the interrupt and progress
94158  ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
94159  ** faster according to "valgrind --tool=cachegrind" */
94160check_for_interrupt:
94161  if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
94162#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
94163  /* Call the progress callback if it is configured and the required number
94164  ** of VDBE ops have been executed (either since this invocation of
94165  ** sqlite3VdbeExec() or since last time the progress callback was called).
94166  ** If the progress callback returns non-zero, exit the virtual machine with
94167  ** a return code SQLITE_ABORT.
94168  */
94169  while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
94170    assert( db->nProgressOps!=0 );
94171    nProgressLimit += db->nProgressOps;
94172    if( db->xProgress(db->pProgressArg) ){
94173      nProgressLimit = LARGEST_UINT64;
94174      rc = SQLITE_INTERRUPT;
94175      goto abort_due_to_error;
94176    }
94177  }
94178#endif
94179
94180  break;
94181}
94182
94183/* Opcode:  Gosub P1 P2 * * *
94184**
94185** Write the current address onto register P1
94186** and then jump to address P2.
94187*/
94188case OP_Gosub: {            /* jump */
94189  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
94190  pIn1 = &aMem[pOp->p1];
94191  assert( VdbeMemDynamic(pIn1)==0 );
94192  memAboutToChange(p, pIn1);
94193  pIn1->flags = MEM_Int;
94194  pIn1->u.i = (int)(pOp-aOp);
94195  REGISTER_TRACE(pOp->p1, pIn1);
94196  goto jump_to_p2_and_check_for_interrupt;
94197}
94198
94199/* Opcode:  Return P1 P2 P3 * *
94200**
94201** Jump to the address stored in register P1.  If P1 is a return address
94202** register, then this accomplishes a return from a subroutine.
94203**
94204** If P3 is 1, then the jump is only taken if register P1 holds an integer
94205** values, otherwise execution falls through to the next opcode, and the
94206** OP_Return becomes a no-op. If P3 is 0, then register P1 must hold an
94207** integer or else an assert() is raised.  P3 should be set to 1 when
94208** this opcode is used in combination with OP_BeginSubrtn, and set to 0
94209** otherwise.
94210**
94211** The value in register P1 is unchanged by this opcode.
94212**
94213** P2 is not used by the byte-code engine.  However, if P2 is positive
94214** and also less than the current address, then the "EXPLAIN" output
94215** formatter in the CLI will indent all opcodes from the P2 opcode up
94216** to be not including the current Return.   P2 should be the first opcode
94217** in the subroutine from which this opcode is returning.  Thus the P2
94218** value is a byte-code indentation hint.  See tag-20220407a in
94219** wherecode.c and shell.c.
94220*/
94221case OP_Return: {           /* in1 */
94222  pIn1 = &aMem[pOp->p1];
94223  if( pIn1->flags & MEM_Int ){
94224    if( pOp->p3 ){ VdbeBranchTaken(1, 2); }
94225    pOp = &aOp[pIn1->u.i];
94226  }else if( ALWAYS(pOp->p3) ){
94227    VdbeBranchTaken(0, 2);
94228  }
94229  break;
94230}
94231
94232/* Opcode: InitCoroutine P1 P2 P3 * *
94233**
94234** Set up register P1 so that it will Yield to the coroutine
94235** located at address P3.
94236**
94237** If P2!=0 then the coroutine implementation immediately follows
94238** this opcode.  So jump over the coroutine implementation to
94239** address P2.
94240**
94241** See also: EndCoroutine
94242*/
94243case OP_InitCoroutine: {     /* jump0 */
94244  assert( pOp->p1>0 &&  pOp->p1<=(p->nMem+1 - p->nCursor) );
94245  assert( pOp->p2>=0 && pOp->p2<p->nOp );
94246  assert( pOp->p3>=0 && pOp->p3<p->nOp );
94247  pOut = &aMem[pOp->p1];
94248  assert( !VdbeMemDynamic(pOut) );
94249  pOut->u.i = pOp->p3 - 1;
94250  pOut->flags = MEM_Int;
94251  if( pOp->p2==0 ) break;
94252
94253  /* Most jump operations do a goto to this spot in order to update
94254  ** the pOp pointer. */
94255jump_to_p2:
94256  assert( pOp->p2>0 );       /* There are never any jumps to instruction 0 */
94257  assert( pOp->p2<p->nOp );  /* Jumps must be in range */
94258  pOp = &aOp[pOp->p2 - 1];
94259  break;
94260}
94261
94262/* Opcode:  EndCoroutine P1 * * * *
94263**
94264** The instruction at the address in register P1 is a Yield.
94265** Jump to the P2 parameter of that Yield.
94266** After the jump, the value register P1 is left with a value
94267** such that subsequent OP_Yields go back to the this same
94268** OP_EndCoroutine instruction.
94269**
94270** See also: InitCoroutine
94271*/
94272case OP_EndCoroutine: {           /* in1 */
94273  VdbeOp *pCaller;
94274  pIn1 = &aMem[pOp->p1];
94275  assert( pIn1->flags==MEM_Int );
94276  assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
94277  pCaller = &aOp[pIn1->u.i];
94278  assert( pCaller->opcode==OP_Yield );
94279  assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
94280  pIn1->u.i = (int)(pOp - p->aOp) - 1;
94281  pOp = &aOp[pCaller->p2 - 1];
94282  break;
94283}
94284
94285/* Opcode:  Yield P1 P2 * * *
94286**
94287** Swap the program counter with the value in register P1.  This
94288** has the effect of yielding to a coroutine.
94289**
94290** If the coroutine that is launched by this instruction ends with
94291** Yield or Return then continue to the next instruction.  But if
94292** the coroutine launched by this instruction ends with
94293** EndCoroutine, then jump to P2 rather than continuing with the
94294** next instruction.
94295**
94296** See also: InitCoroutine
94297*/
94298case OP_Yield: {            /* in1, jump0 */
94299  int pcDest;
94300  pIn1 = &aMem[pOp->p1];
94301  assert( VdbeMemDynamic(pIn1)==0 );
94302  pIn1->flags = MEM_Int;
94303  pcDest = (int)pIn1->u.i;
94304  pIn1->u.i = (int)(pOp - aOp);
94305  REGISTER_TRACE(pOp->p1, pIn1);
94306  pOp = &aOp[pcDest];
94307  break;
94308}
94309
94310/* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
94311** Synopsis: if r[P3]=null halt
94312**
94313** Check the value in register P3.  If it is NULL then Halt using
94314** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
94315** value in register P3 is not NULL, then this routine is a no-op.
94316** The P5 parameter should be 1.
94317*/
94318case OP_HaltIfNull: {      /* in3 */
94319  pIn3 = &aMem[pOp->p3];
94320#ifdef SQLITE_DEBUG
94321  if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
94322#endif
94323  if( (pIn3->flags & MEM_Null)==0 ) break;
94324  /* Fall through into OP_Halt */
94325  /* no break */ deliberate_fall_through
94326}
94327
94328/* Opcode:  Halt P1 P2 * P4 P5
94329**
94330** Exit immediately.  All open cursors, etc are closed
94331** automatically.
94332**
94333** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
94334** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
94335** For errors, it can be some other value.  If P1!=0 then P2 will determine
94336** whether or not to rollback the current transaction.  Do not rollback
94337** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
94338** then back out all changes that have occurred during this execution of the
94339** VDBE, but do not rollback the transaction.
94340**
94341** If P4 is not null then it is an error message string.
94342**
94343** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
94344**
94345**    0:  (no change)
94346**    1:  NOT NULL constraint failed: P4
94347**    2:  UNIQUE constraint failed: P4
94348**    3:  CHECK constraint failed: P4
94349**    4:  FOREIGN KEY constraint failed: P4
94350**
94351** If P5 is not zero and P4 is NULL, then everything after the ":" is
94352** omitted.
94353**
94354** There is an implied "Halt 0 0 0" instruction inserted at the very end of
94355** every program.  So a jump past the last instruction of the program
94356** is the same as executing Halt.
94357*/
94358case OP_Halt: {
94359  VdbeFrame *pFrame;
94360  int pcx;
94361
94362#ifdef SQLITE_DEBUG
94363  if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
94364#endif
94365
94366  /* A deliberately coded "OP_Halt SQLITE_INTERNAL * * * *" opcode indicates
94367  ** something is wrong with the code generator.  Raise an assertion in order
94368  ** to bring this to the attention of fuzzers and other testing tools. */
94369  assert( pOp->p1!=SQLITE_INTERNAL );
94370
94371  if( p->pFrame && pOp->p1==SQLITE_OK ){
94372    /* Halt the sub-program. Return control to the parent frame. */
94373    pFrame = p->pFrame;
94374    p->pFrame = pFrame->pParent;
94375    p->nFrame--;
94376    sqlite3VdbeSetChanges(db, p->nChange);
94377    pcx = sqlite3VdbeFrameRestore(pFrame);
94378    if( pOp->p2==OE_Ignore ){
94379      /* Instruction pcx is the OP_Program that invoked the sub-program
94380      ** currently being halted. If the p2 instruction of this OP_Halt
94381      ** instruction is set to OE_Ignore, then the sub-program is throwing
94382      ** an IGNORE exception. In this case jump to the address specified
94383      ** as the p2 of the calling OP_Program.  */
94384      pcx = p->aOp[pcx].p2-1;
94385    }
94386    aOp = p->aOp;
94387    aMem = p->aMem;
94388    pOp = &aOp[pcx];
94389    break;
94390  }
94391  p->rc = pOp->p1;
94392  p->errorAction = (u8)pOp->p2;
94393  assert( pOp->p5<=4 );
94394  if( p->rc ){
94395    if( pOp->p5 ){
94396      static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
94397                                             "FOREIGN KEY" };
94398      testcase( pOp->p5==1 );
94399      testcase( pOp->p5==2 );
94400      testcase( pOp->p5==3 );
94401      testcase( pOp->p5==4 );
94402      sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
94403      if( pOp->p4.z ){
94404        p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
94405      }
94406    }else{
94407      sqlite3VdbeError(p, "%s", pOp->p4.z);
94408    }
94409    pcx = (int)(pOp - aOp);
94410    sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
94411  }
94412  rc = sqlite3VdbeHalt(p);
94413  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
94414  if( rc==SQLITE_BUSY ){
94415    p->rc = SQLITE_BUSY;
94416  }else{
94417    assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
94418    assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
94419    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
94420  }
94421  goto vdbe_return;
94422}
94423
94424/* Opcode: Integer P1 P2 * * *
94425** Synopsis: r[P2]=P1
94426**
94427** The 32-bit integer value P1 is written into register P2.
94428*/
94429case OP_Integer: {         /* out2 */
94430  pOut = out2Prerelease(p, pOp);
94431  pOut->u.i = pOp->p1;
94432  break;
94433}
94434
94435/* Opcode: Int64 * P2 * P4 *
94436** Synopsis: r[P2]=P4
94437**
94438** P4 is a pointer to a 64-bit integer value.
94439** Write that value into register P2.
94440*/
94441case OP_Int64: {           /* out2 */
94442  pOut = out2Prerelease(p, pOp);
94443  assert( pOp->p4.pI64!=0 );
94444  pOut->u.i = *pOp->p4.pI64;
94445  break;
94446}
94447
94448#ifndef SQLITE_OMIT_FLOATING_POINT
94449/* Opcode: Real * P2 * P4 *
94450** Synopsis: r[P2]=P4
94451**
94452** P4 is a pointer to a 64-bit floating point value.
94453** Write that value into register P2.
94454*/
94455case OP_Real: {            /* same as TK_FLOAT, out2 */
94456  pOut = out2Prerelease(p, pOp);
94457  pOut->flags = MEM_Real;
94458  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
94459  pOut->u.r = *pOp->p4.pReal;
94460  break;
94461}
94462#endif
94463
94464/* Opcode: String8 * P2 * P4 *
94465** Synopsis: r[P2]='P4'
94466**
94467** P4 points to a nul terminated UTF-8 string. This opcode is transformed
94468** into a String opcode before it is executed for the first time.  During
94469** this transformation, the length of string P4 is computed and stored
94470** as the P1 parameter.
94471*/
94472case OP_String8: {         /* same as TK_STRING, out2 */
94473  assert( pOp->p4.z!=0 );
94474  pOut = out2Prerelease(p, pOp);
94475  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
94476
94477#ifndef SQLITE_OMIT_UTF16
94478  if( encoding!=SQLITE_UTF8 ){
94479    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
94480    assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
94481    if( rc ) goto too_big;
94482    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
94483    assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
94484    assert( VdbeMemDynamic(pOut)==0 );
94485    pOut->szMalloc = 0;
94486    pOut->flags |= MEM_Static;
94487    if( pOp->p4type==P4_DYNAMIC ){
94488      sqlite3DbFree(db, pOp->p4.z);
94489    }
94490    pOp->p4type = P4_DYNAMIC;
94491    pOp->p4.z = pOut->z;
94492    pOp->p1 = pOut->n;
94493  }
94494#endif
94495  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
94496    goto too_big;
94497  }
94498  pOp->opcode = OP_String;
94499  assert( rc==SQLITE_OK );
94500  /* Fall through to the next case, OP_String */
94501  /* no break */ deliberate_fall_through
94502}
94503
94504/* Opcode: String P1 P2 P3 P4 P5
94505** Synopsis: r[P2]='P4' (len=P1)
94506**
94507** The string value P4 of length P1 (bytes) is stored in register P2.
94508**
94509** If P3 is not zero and the content of register P3 is equal to P5, then
94510** the datatype of the register P2 is converted to BLOB.  The content is
94511** the same sequence of bytes, it is merely interpreted as a BLOB instead
94512** of a string, as if it had been CAST.  In other words:
94513**
94514** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
94515*/
94516case OP_String: {          /* out2 */
94517  assert( pOp->p4.z!=0 );
94518  pOut = out2Prerelease(p, pOp);
94519  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
94520  pOut->z = pOp->p4.z;
94521  pOut->n = pOp->p1;
94522  pOut->enc = encoding;
94523  UPDATE_MAX_BLOBSIZE(pOut);
94524#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
94525  if( pOp->p3>0 ){
94526    assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
94527    pIn3 = &aMem[pOp->p3];
94528    assert( pIn3->flags & MEM_Int );
94529    if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
94530  }
94531#endif
94532  break;
94533}
94534
94535/* Opcode: BeginSubrtn * P2 * * *
94536** Synopsis: r[P2]=NULL
94537**
94538** Mark the beginning of a subroutine that can be entered in-line
94539** or that can be called using OP_Gosub.  The subroutine should
94540** be terminated by an OP_Return instruction that has a P1 operand that
94541** is the same as the P2 operand to this opcode and that has P3 set to 1.
94542** If the subroutine is entered in-line, then the OP_Return will simply
94543** fall through.  But if the subroutine is entered using OP_Gosub, then
94544** the OP_Return will jump back to the first instruction after the OP_Gosub.
94545**
94546** This routine works by loading a NULL into the P2 register.  When the
94547** return address register contains a NULL, the OP_Return instruction is
94548** a no-op that simply falls through to the next instruction (assuming that
94549** the OP_Return opcode has a P3 value of 1).  Thus if the subroutine is
94550** entered in-line, then the OP_Return will cause in-line execution to
94551** continue.  But if the subroutine is entered via OP_Gosub, then the
94552** OP_Return will cause a return to the address following the OP_Gosub.
94553**
94554** This opcode is identical to OP_Null.  It has a different name
94555** only to make the byte code easier to read and verify.
94556*/
94557/* Opcode: Null P1 P2 P3 * *
94558** Synopsis: r[P2..P3]=NULL
94559**
94560** Write a NULL into registers P2.  If P3 greater than P2, then also write
94561** NULL into register P3 and every register in between P2 and P3.  If P3
94562** is less than P2 (typically P3 is zero) then only register P2 is
94563** set to NULL.
94564**
94565** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
94566** NULL values will not compare equal even if SQLITE_NULLEQ is set on
94567** OP_Ne or OP_Eq.
94568*/
94569case OP_BeginSubrtn:
94570case OP_Null: {           /* out2 */
94571  int cnt;
94572  u16 nullFlag;
94573  pOut = out2Prerelease(p, pOp);
94574  cnt = pOp->p3-pOp->p2;
94575  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
94576  pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
94577  pOut->n = 0;
94578#ifdef SQLITE_DEBUG
94579  pOut->uTemp = 0;
94580#endif
94581  while( cnt>0 ){
94582    pOut++;
94583    memAboutToChange(p, pOut);
94584    sqlite3VdbeMemSetNull(pOut);
94585    pOut->flags = nullFlag;
94586    pOut->n = 0;
94587    cnt--;
94588  }
94589  break;
94590}
94591
94592/* Opcode: SoftNull P1 * * * *
94593** Synopsis: r[P1]=NULL
94594**
94595** Set register P1 to have the value NULL as seen by the OP_MakeRecord
94596** instruction, but do not free any string or blob memory associated with
94597** the register, so that if the value was a string or blob that was
94598** previously copied using OP_SCopy, the copies will continue to be valid.
94599*/
94600case OP_SoftNull: {
94601  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
94602  pOut = &aMem[pOp->p1];
94603  pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
94604  break;
94605}
94606
94607/* Opcode: Blob P1 P2 * P4 *
94608** Synopsis: r[P2]=P4 (len=P1)
94609**
94610** P4 points to a blob of data P1 bytes long.  Store this
94611** blob in register P2.  If P4 is a NULL pointer, then construct
94612** a zero-filled blob that is P1 bytes long in P2.
94613*/
94614case OP_Blob: {                /* out2 */
94615  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
94616  pOut = out2Prerelease(p, pOp);
94617  if( pOp->p4.z==0 ){
94618    sqlite3VdbeMemSetZeroBlob(pOut, pOp->p1);
94619    if( sqlite3VdbeMemExpandBlob(pOut) ) goto no_mem;
94620  }else{
94621    sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
94622  }
94623  pOut->enc = encoding;
94624  UPDATE_MAX_BLOBSIZE(pOut);
94625  break;
94626}
94627
94628/* Opcode: Variable P1 P2 * * *
94629** Synopsis: r[P2]=parameter(P1)
94630**
94631** Transfer the values of bound parameter P1 into register P2
94632*/
94633case OP_Variable: {            /* out2 */
94634  Mem *pVar;       /* Value being transferred */
94635
94636  assert( pOp->p1>0 && pOp->p1<=p->nVar );
94637  pVar = &p->aVar[pOp->p1 - 1];
94638  if( sqlite3VdbeMemTooBig(pVar) ){
94639    goto too_big;
94640  }
94641  pOut = &aMem[pOp->p2];
94642  if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
94643  memcpy(pOut, pVar, MEMCELLSIZE);
94644  pOut->flags &= ~(MEM_Dyn|MEM_Ephem);
94645  pOut->flags |= MEM_Static|MEM_FromBind;
94646  UPDATE_MAX_BLOBSIZE(pOut);
94647  break;
94648}
94649
94650/* Opcode: Move P1 P2 P3 * *
94651** Synopsis: r[P2@P3]=r[P1@P3]
94652**
94653** Move the P3 values in register P1..P1+P3-1 over into
94654** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
94655** left holding a NULL.  It is an error for register ranges
94656** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
94657** for P3 to be less than 1.
94658*/
94659case OP_Move: {
94660  int n;           /* Number of registers left to copy */
94661  int p1;          /* Register to copy from */
94662  int p2;          /* Register to copy to */
94663
94664  n = pOp->p3;
94665  p1 = pOp->p1;
94666  p2 = pOp->p2;
94667  assert( n>0 && p1>0 && p2>0 );
94668  assert( p1+n<=p2 || p2+n<=p1 );
94669
94670  pIn1 = &aMem[p1];
94671  pOut = &aMem[p2];
94672  do{
94673    assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
94674    assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
94675    assert( memIsValid(pIn1) );
94676    memAboutToChange(p, pOut);
94677    sqlite3VdbeMemMove(pOut, pIn1);
94678#ifdef SQLITE_DEBUG
94679    pIn1->pScopyFrom = 0;
94680    { int i;
94681      for(i=1; i<p->nMem; i++){
94682        if( aMem[i].pScopyFrom==pIn1 ){
94683          aMem[i].pScopyFrom = pOut;
94684        }
94685      }
94686    }
94687#endif
94688    Deephemeralize(pOut);
94689    REGISTER_TRACE(p2++, pOut);
94690    pIn1++;
94691    pOut++;
94692  }while( --n );
94693  break;
94694}
94695
94696/* Opcode: Copy P1 P2 P3 * P5
94697** Synopsis: r[P2@P3+1]=r[P1@P3+1]
94698**
94699** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
94700**
94701** If the 0x0002 bit of P5 is set then also clear the MEM_Subtype flag in the
94702** destination.  The 0x0001 bit of P5 indicates that this Copy opcode cannot
94703** be merged.  The 0x0001 bit is used by the query planner and does not
94704** come into play during query execution.
94705**
94706** This instruction makes a deep copy of the value.  A duplicate
94707** is made of any string or blob constant.  See also OP_SCopy.
94708*/
94709case OP_Copy: {
94710  int n;
94711
94712  n = pOp->p3;
94713  pIn1 = &aMem[pOp->p1];
94714  pOut = &aMem[pOp->p2];
94715  assert( pOut!=pIn1 );
94716  while( 1 ){
94717    memAboutToChange(p, pOut);
94718    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
94719    Deephemeralize(pOut);
94720    if( (pOut->flags & MEM_Subtype)!=0 &&  (pOp->p5 & 0x0002)!=0 ){
94721      pOut->flags &= ~MEM_Subtype;
94722    }
94723#ifdef SQLITE_DEBUG
94724    pOut->pScopyFrom = 0;
94725#endif
94726    REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
94727    if( (n--)==0 ) break;
94728    pOut++;
94729    pIn1++;
94730  }
94731  break;
94732}
94733
94734/* Opcode: SCopy P1 P2 * * *
94735** Synopsis: r[P2]=r[P1]
94736**
94737** Make a shallow copy of register P1 into register P2.
94738**
94739** This instruction makes a shallow copy of the value.  If the value
94740** is a string or blob, then the copy is only a pointer to the
94741** original and hence if the original changes so will the copy.
94742** Worse, if the original is deallocated, the copy becomes invalid.
94743** Thus the program must guarantee that the original will not change
94744** during the lifetime of the copy.  Use OP_Copy to make a complete
94745** copy.
94746*/
94747case OP_SCopy: {            /* out2 */
94748  pIn1 = &aMem[pOp->p1];
94749  pOut = &aMem[pOp->p2];
94750  assert( pOut!=pIn1 );
94751  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
94752#ifdef SQLITE_DEBUG
94753  pOut->pScopyFrom = pIn1;
94754  pOut->mScopyFlags = pIn1->flags;
94755#endif
94756  break;
94757}
94758
94759/* Opcode: IntCopy P1 P2 * * *
94760** Synopsis: r[P2]=r[P1]
94761**
94762** Transfer the integer value held in register P1 into register P2.
94763**
94764** This is an optimized version of SCopy that works only for integer
94765** values.
94766*/
94767case OP_IntCopy: {            /* out2 */
94768  pIn1 = &aMem[pOp->p1];
94769  assert( (pIn1->flags & MEM_Int)!=0 );
94770  pOut = &aMem[pOp->p2];
94771  sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
94772  break;
94773}
94774
94775/* Opcode: FkCheck * * * * *
94776**
94777** Halt with an SQLITE_CONSTRAINT error if there are any unresolved
94778** foreign key constraint violations.  If there are no foreign key
94779** constraint violations, this is a no-op.
94780**
94781** FK constraint violations are also checked when the prepared statement
94782** exits.  This opcode is used to raise foreign key constraint errors prior
94783** to returning results such as a row change count or the result of a
94784** RETURNING clause.
94785*/
94786case OP_FkCheck: {
94787  if( (rc = sqlite3VdbeCheckFk(p,0))!=SQLITE_OK ){
94788    goto abort_due_to_error;
94789  }
94790  break;
94791}
94792
94793/* Opcode: ResultRow P1 P2 * * *
94794** Synopsis: output=r[P1@P2]
94795**
94796** The registers P1 through P1+P2-1 contain a single row of
94797** results. This opcode causes the sqlite3_step() call to terminate
94798** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
94799** structure to provide access to the r(P1)..r(P1+P2-1) values as
94800** the result row.
94801*/
94802case OP_ResultRow: {
94803  assert( p->nResColumn==pOp->p2 );
94804  assert( pOp->p1>0 || CORRUPT_DB );
94805  assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
94806
94807  p->cacheCtr = (p->cacheCtr + 2)|1;
94808  p->pResultRow = &aMem[pOp->p1];
94809#ifdef SQLITE_DEBUG
94810  {
94811    Mem *pMem = p->pResultRow;
94812    int i;
94813    for(i=0; i<pOp->p2; i++){
94814      assert( memIsValid(&pMem[i]) );
94815      REGISTER_TRACE(pOp->p1+i, &pMem[i]);
94816      /* The registers in the result will not be used again when the
94817      ** prepared statement restarts.  This is because sqlite3_column()
94818      ** APIs might have caused type conversions of made other changes to
94819      ** the register values.  Therefore, we can go ahead and break any
94820      ** OP_SCopy dependencies. */
94821      pMem[i].pScopyFrom = 0;
94822    }
94823  }
94824#endif
94825  if( db->mallocFailed ) goto no_mem;
94826  if( db->mTrace & SQLITE_TRACE_ROW ){
94827    db->trace.xV2(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
94828  }
94829  p->pc = (int)(pOp - aOp) + 1;
94830  rc = SQLITE_ROW;
94831  goto vdbe_return;
94832}
94833
94834/* Opcode: Concat P1 P2 P3 * *
94835** Synopsis: r[P3]=r[P2]+r[P1]
94836**
94837** Add the text in register P1 onto the end of the text in
94838** register P2 and store the result in register P3.
94839** If either the P1 or P2 text are NULL then store NULL in P3.
94840**
94841**   P3 = P2 || P1
94842**
94843** It is illegal for P1 and P3 to be the same register. Sometimes,
94844** if P3 is the same register as P2, the implementation is able
94845** to avoid a memcpy().
94846*/
94847case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
94848  i64 nByte;          /* Total size of the output string or blob */
94849  u16 flags1;         /* Initial flags for P1 */
94850  u16 flags2;         /* Initial flags for P2 */
94851
94852  pIn1 = &aMem[pOp->p1];
94853  pIn2 = &aMem[pOp->p2];
94854  pOut = &aMem[pOp->p3];
94855  testcase( pOut==pIn2 );
94856  assert( pIn1!=pOut );
94857  flags1 = pIn1->flags;
94858  testcase( flags1 & MEM_Null );
94859  testcase( pIn2->flags & MEM_Null );
94860  if( (flags1 | pIn2->flags) & MEM_Null ){
94861    sqlite3VdbeMemSetNull(pOut);
94862    break;
94863  }
94864  if( (flags1 & (MEM_Str|MEM_Blob))==0 ){
94865    if( sqlite3VdbeMemStringify(pIn1,encoding,0) ) goto no_mem;
94866    flags1 = pIn1->flags & ~MEM_Str;
94867  }else if( (flags1 & MEM_Zero)!=0 ){
94868    if( sqlite3VdbeMemExpandBlob(pIn1) ) goto no_mem;
94869    flags1 = pIn1->flags & ~MEM_Str;
94870  }
94871  flags2 = pIn2->flags;
94872  if( (flags2 & (MEM_Str|MEM_Blob))==0 ){
94873    if( sqlite3VdbeMemStringify(pIn2,encoding,0) ) goto no_mem;
94874    flags2 = pIn2->flags & ~MEM_Str;
94875  }else if( (flags2 & MEM_Zero)!=0 ){
94876    if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem;
94877    flags2 = pIn2->flags & ~MEM_Str;
94878  }
94879  nByte = pIn1->n + pIn2->n;
94880  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
94881    goto too_big;
94882  }
94883  if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
94884    goto no_mem;
94885  }
94886  MemSetTypeFlag(pOut, MEM_Str);
94887  if( pOut!=pIn2 ){
94888    memcpy(pOut->z, pIn2->z, pIn2->n);
94889    assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) );
94890    pIn2->flags = flags2;
94891  }
94892  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
94893  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
94894  pIn1->flags = flags1;
94895  if( encoding>SQLITE_UTF8 ) nByte &= ~1;
94896  pOut->z[nByte]=0;
94897  pOut->z[nByte+1] = 0;
94898  pOut->flags |= MEM_Term;
94899  pOut->n = (int)nByte;
94900  pOut->enc = encoding;
94901  UPDATE_MAX_BLOBSIZE(pOut);
94902  break;
94903}
94904
94905/* Opcode: Add P1 P2 P3 * *
94906** Synopsis: r[P3]=r[P1]+r[P2]
94907**
94908** Add the value in register P1 to the value in register P2
94909** and store the result in register P3.
94910** If either input is NULL, the result is NULL.
94911*/
94912/* Opcode: Multiply P1 P2 P3 * *
94913** Synopsis: r[P3]=r[P1]*r[P2]
94914**
94915**
94916** Multiply the value in register P1 by the value in register P2
94917** and store the result in register P3.
94918** If either input is NULL, the result is NULL.
94919*/
94920/* Opcode: Subtract P1 P2 P3 * *
94921** Synopsis: r[P3]=r[P2]-r[P1]
94922**
94923** Subtract the value in register P1 from the value in register P2
94924** and store the result in register P3.
94925** If either input is NULL, the result is NULL.
94926*/
94927/* Opcode: Divide P1 P2 P3 * *
94928** Synopsis: r[P3]=r[P2]/r[P1]
94929**
94930** Divide the value in register P1 by the value in register P2
94931** and store the result in register P3 (P3=P2/P1). If the value in
94932** register P1 is zero, then the result is NULL. If either input is
94933** NULL, the result is NULL.
94934*/
94935/* Opcode: Remainder P1 P2 P3 * *
94936** Synopsis: r[P3]=r[P2]%r[P1]
94937**
94938** Compute the remainder after integer register P2 is divided by
94939** register P1 and store the result in register P3.
94940** If the value in register P1 is zero the result is NULL.
94941** If either operand is NULL, the result is NULL.
94942*/
94943case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
94944case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
94945case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
94946case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
94947case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
94948  u16 type1;      /* Numeric type of left operand */
94949  u16 type2;      /* Numeric type of right operand */
94950  i64 iA;         /* Integer value of left operand */
94951  i64 iB;         /* Integer value of right operand */
94952  double rA;      /* Real value of left operand */
94953  double rB;      /* Real value of right operand */
94954
94955  pIn1 = &aMem[pOp->p1];
94956  type1 = pIn1->flags;
94957  pIn2 = &aMem[pOp->p2];
94958  type2 = pIn2->flags;
94959  pOut = &aMem[pOp->p3];
94960  if( (type1 & type2 & MEM_Int)!=0 ){
94961int_math:
94962    iA = pIn1->u.i;
94963    iB = pIn2->u.i;
94964    switch( pOp->opcode ){
94965      case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
94966      case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
94967      case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
94968      case OP_Divide: {
94969        if( iA==0 ) goto arithmetic_result_is_null;
94970        if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
94971        iB /= iA;
94972        break;
94973      }
94974      default: {
94975        if( iA==0 ) goto arithmetic_result_is_null;
94976        if( iA==-1 ) iA = 1;
94977        iB %= iA;
94978        break;
94979      }
94980    }
94981    pOut->u.i = iB;
94982    MemSetTypeFlag(pOut, MEM_Int);
94983  }else if( ((type1 | type2) & MEM_Null)!=0 ){
94984    goto arithmetic_result_is_null;
94985  }else{
94986    type1 = numericType(pIn1);
94987    type2 = numericType(pIn2);
94988    if( (type1 & type2 & MEM_Int)!=0 ) goto int_math;
94989fp_math:
94990    rA = sqlite3VdbeRealValue(pIn1);
94991    rB = sqlite3VdbeRealValue(pIn2);
94992    switch( pOp->opcode ){
94993      case OP_Add:         rB += rA;       break;
94994      case OP_Subtract:    rB -= rA;       break;
94995      case OP_Multiply:    rB *= rA;       break;
94996      case OP_Divide: {
94997        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
94998        if( rA==(double)0 ) goto arithmetic_result_is_null;
94999        rB /= rA;
95000        break;
95001      }
95002      default: {
95003        iA = sqlite3VdbeIntValue(pIn1);
95004        iB = sqlite3VdbeIntValue(pIn2);
95005        if( iA==0 ) goto arithmetic_result_is_null;
95006        if( iA==-1 ) iA = 1;
95007        rB = (double)(iB % iA);
95008        break;
95009      }
95010    }
95011#ifdef SQLITE_OMIT_FLOATING_POINT
95012    pOut->u.i = rB;
95013    MemSetTypeFlag(pOut, MEM_Int);
95014#else
95015    if( sqlite3IsNaN(rB) ){
95016      goto arithmetic_result_is_null;
95017    }
95018    pOut->u.r = rB;
95019    MemSetTypeFlag(pOut, MEM_Real);
95020#endif
95021  }
95022  break;
95023
95024arithmetic_result_is_null:
95025  sqlite3VdbeMemSetNull(pOut);
95026  break;
95027}
95028
95029/* Opcode: CollSeq P1 * * P4
95030**
95031** P4 is a pointer to a CollSeq object. If the next call to a user function
95032** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
95033** be returned. This is used by the built-in min(), max() and nullif()
95034** functions.
95035**
95036** If P1 is not zero, then it is a register that a subsequent min() or
95037** max() aggregate will set to 1 if the current row is not the minimum or
95038** maximum.  The P1 register is initialized to 0 by this instruction.
95039**
95040** The interface used by the implementation of the aforementioned functions
95041** to retrieve the collation sequence set by this opcode is not available
95042** publicly.  Only built-in functions have access to this feature.
95043*/
95044case OP_CollSeq: {
95045  assert( pOp->p4type==P4_COLLSEQ );
95046  if( pOp->p1 ){
95047    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
95048  }
95049  break;
95050}
95051
95052/* Opcode: BitAnd P1 P2 P3 * *
95053** Synopsis: r[P3]=r[P1]&r[P2]
95054**
95055** Take the bit-wise AND of the values in register P1 and P2 and
95056** store the result in register P3.
95057** If either input is NULL, the result is NULL.
95058*/
95059/* Opcode: BitOr P1 P2 P3 * *
95060** Synopsis: r[P3]=r[P1]|r[P2]
95061**
95062** Take the bit-wise OR of the values in register P1 and P2 and
95063** store the result in register P3.
95064** If either input is NULL, the result is NULL.
95065*/
95066/* Opcode: ShiftLeft P1 P2 P3 * *
95067** Synopsis: r[P3]=r[P2]<<r[P1]
95068**
95069** Shift the integer value in register P2 to the left by the
95070** number of bits specified by the integer in register P1.
95071** Store the result in register P3.
95072** If either input is NULL, the result is NULL.
95073*/
95074/* Opcode: ShiftRight P1 P2 P3 * *
95075** Synopsis: r[P3]=r[P2]>>r[P1]
95076**
95077** Shift the integer value in register P2 to the right by the
95078** number of bits specified by the integer in register P1.
95079** Store the result in register P3.
95080** If either input is NULL, the result is NULL.
95081*/
95082case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
95083case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
95084case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
95085case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
95086  i64 iA;
95087  u64 uA;
95088  i64 iB;
95089  u8 op;
95090
95091  pIn1 = &aMem[pOp->p1];
95092  pIn2 = &aMem[pOp->p2];
95093  pOut = &aMem[pOp->p3];
95094  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
95095    sqlite3VdbeMemSetNull(pOut);
95096    break;
95097  }
95098  iA = sqlite3VdbeIntValue(pIn2);
95099  iB = sqlite3VdbeIntValue(pIn1);
95100  op = pOp->opcode;
95101  if( op==OP_BitAnd ){
95102    iA &= iB;
95103  }else if( op==OP_BitOr ){
95104    iA |= iB;
95105  }else if( iB!=0 ){
95106    assert( op==OP_ShiftRight || op==OP_ShiftLeft );
95107
95108    /* If shifting by a negative amount, shift in the other direction */
95109    if( iB<0 ){
95110      assert( OP_ShiftRight==OP_ShiftLeft+1 );
95111      op = 2*OP_ShiftLeft + 1 - op;
95112      iB = iB>(-64) ? -iB : 64;
95113    }
95114
95115    if( iB>=64 ){
95116      iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
95117    }else{
95118      memcpy(&uA, &iA, sizeof(uA));
95119      if( op==OP_ShiftLeft ){
95120        uA <<= iB;
95121      }else{
95122        uA >>= iB;
95123        /* Sign-extend on a right shift of a negative number */
95124        if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
95125      }
95126      memcpy(&iA, &uA, sizeof(iA));
95127    }
95128  }
95129  pOut->u.i = iA;
95130  MemSetTypeFlag(pOut, MEM_Int);
95131  break;
95132}
95133
95134/* Opcode: AddImm  P1 P2 * * *
95135** Synopsis: r[P1]=r[P1]+P2
95136**
95137** Add the constant P2 to the value in register P1.
95138** The result is always an integer.
95139**
95140** To force any register to be an integer, just add 0.
95141*/
95142case OP_AddImm: {            /* in1 */
95143  pIn1 = &aMem[pOp->p1];
95144  memAboutToChange(p, pIn1);
95145  sqlite3VdbeMemIntegerify(pIn1);
95146  *(u64*)&pIn1->u.i += (u64)pOp->p2;
95147  break;
95148}
95149
95150/* Opcode: MustBeInt P1 P2 * * *
95151**
95152** Force the value in register P1 to be an integer.  If the value
95153** in P1 is not an integer and cannot be converted into an integer
95154** without data loss, then jump immediately to P2, or if P2==0
95155** raise an SQLITE_MISMATCH exception.
95156*/
95157case OP_MustBeInt: {            /* jump0, in1 */
95158  pIn1 = &aMem[pOp->p1];
95159  if( (pIn1->flags & MEM_Int)==0 ){
95160    applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
95161    if( (pIn1->flags & MEM_Int)==0 ){
95162      VdbeBranchTaken(1, 2);
95163      if( pOp->p2==0 ){
95164        rc = SQLITE_MISMATCH;
95165        goto abort_due_to_error;
95166      }else{
95167        goto jump_to_p2;
95168      }
95169    }
95170  }
95171  VdbeBranchTaken(0, 2);
95172  MemSetTypeFlag(pIn1, MEM_Int);
95173  break;
95174}
95175
95176#ifndef SQLITE_OMIT_FLOATING_POINT
95177/* Opcode: RealAffinity P1 * * * *
95178**
95179** If register P1 holds an integer convert it to a real value.
95180**
95181** This opcode is used when extracting information from a column that
95182** has REAL affinity.  Such column values may still be stored as
95183** integers, for space efficiency, but after extraction we want them
95184** to have only a real value.
95185*/
95186case OP_RealAffinity: {                  /* in1 */
95187  pIn1 = &aMem[pOp->p1];
95188  if( pIn1->flags & (MEM_Int|MEM_IntReal) ){
95189    testcase( pIn1->flags & MEM_Int );
95190    testcase( pIn1->flags & MEM_IntReal );
95191    sqlite3VdbeMemRealify(pIn1);
95192    REGISTER_TRACE(pOp->p1, pIn1);
95193  }
95194  break;
95195}
95196#endif
95197
95198#if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_ANALYZE)
95199/* Opcode: Cast P1 P2 * * *
95200** Synopsis: affinity(r[P1])
95201**
95202** Force the value in register P1 to be the type defined by P2.
95203**
95204** <ul>
95205** <li> P2=='A' &rarr; BLOB
95206** <li> P2=='B' &rarr; TEXT
95207** <li> P2=='C' &rarr; NUMERIC
95208** <li> P2=='D' &rarr; INTEGER
95209** <li> P2=='E' &rarr; REAL
95210** </ul>
95211**
95212** A NULL value is not changed by this routine.  It remains NULL.
95213*/
95214case OP_Cast: {                  /* in1 */
95215  assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
95216  testcase( pOp->p2==SQLITE_AFF_TEXT );
95217  testcase( pOp->p2==SQLITE_AFF_BLOB );
95218  testcase( pOp->p2==SQLITE_AFF_NUMERIC );
95219  testcase( pOp->p2==SQLITE_AFF_INTEGER );
95220  testcase( pOp->p2==SQLITE_AFF_REAL );
95221  pIn1 = &aMem[pOp->p1];
95222  memAboutToChange(p, pIn1);
95223  rc = ExpandBlob(pIn1);
95224  if( rc ) goto abort_due_to_error;
95225  rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
95226  if( rc ) goto abort_due_to_error;
95227  UPDATE_MAX_BLOBSIZE(pIn1);
95228  REGISTER_TRACE(pOp->p1, pIn1);
95229  break;
95230}
95231#endif /* SQLITE_OMIT_CAST */
95232
95233/* Opcode: Eq P1 P2 P3 P4 P5
95234** Synopsis: IF r[P3]==r[P1]
95235**
95236** Compare the values in register P1 and P3.  If reg(P3)==reg(P1) then
95237** jump to address P2.
95238**
95239** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
95240** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
95241** to coerce both inputs according to this affinity before the
95242** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
95243** affinity is used. Note that the affinity conversions are stored
95244** back into the input registers P1 and P3.  So this opcode can cause
95245** persistent changes to registers P1 and P3.
95246**
95247** Once any conversions have taken place, and neither value is NULL,
95248** the values are compared. If both values are blobs then memcmp() is
95249** used to determine the results of the comparison.  If both values
95250** are text, then the appropriate collating function specified in
95251** P4 is used to do the comparison.  If P4 is not specified then
95252** memcmp() is used to compare text string.  If both values are
95253** numeric, then a numeric comparison is used. If the two values
95254** are of different types, then numbers are considered less than
95255** strings and strings are considered less than blobs.
95256**
95257** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
95258** true or false and is never NULL.  If both operands are NULL then the result
95259** of comparison is true.  If either operand is NULL then the result is false.
95260** If neither operand is NULL the result is the same as it would be if
95261** the SQLITE_NULLEQ flag were omitted from P5.
95262**
95263** This opcode saves the result of comparison for use by the new
95264** OP_Jump opcode.
95265*/
95266/* Opcode: Ne P1 P2 P3 P4 P5
95267** Synopsis: IF r[P3]!=r[P1]
95268**
95269** This works just like the Eq opcode except that the jump is taken if
95270** the operands in registers P1 and P3 are not equal.  See the Eq opcode for
95271** additional information.
95272*/
95273/* Opcode: Lt P1 P2 P3 P4 P5
95274** Synopsis: IF r[P3]<r[P1]
95275**
95276** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
95277** jump to address P2.
95278**
95279** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
95280** reg(P3) is NULL then the take the jump.  If the SQLITE_JUMPIFNULL
95281** bit is clear then fall through if either operand is NULL.
95282**
95283** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
95284** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
95285** to coerce both inputs according to this affinity before the
95286** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
95287** affinity is used. Note that the affinity conversions are stored
95288** back into the input registers P1 and P3.  So this opcode can cause
95289** persistent changes to registers P1 and P3.
95290**
95291** Once any conversions have taken place, and neither value is NULL,
95292** the values are compared. If both values are blobs then memcmp() is
95293** used to determine the results of the comparison.  If both values
95294** are text, then the appropriate collating function specified in
95295** P4 is  used to do the comparison.  If P4 is not specified then
95296** memcmp() is used to compare text string.  If both values are
95297** numeric, then a numeric comparison is used. If the two values
95298** are of different types, then numbers are considered less than
95299** strings and strings are considered less than blobs.
95300**
95301** This opcode saves the result of comparison for use by the new
95302** OP_Jump opcode.
95303*/
95304/* Opcode: Le P1 P2 P3 P4 P5
95305** Synopsis: IF r[P3]<=r[P1]
95306**
95307** This works just like the Lt opcode except that the jump is taken if
95308** the content of register P3 is less than or equal to the content of
95309** register P1.  See the Lt opcode for additional information.
95310*/
95311/* Opcode: Gt P1 P2 P3 P4 P5
95312** Synopsis: IF r[P3]>r[P1]
95313**
95314** This works just like the Lt opcode except that the jump is taken if
95315** the content of register P3 is greater than the content of
95316** register P1.  See the Lt opcode for additional information.
95317*/
95318/* Opcode: Ge P1 P2 P3 P4 P5
95319** Synopsis: IF r[P3]>=r[P1]
95320**
95321** This works just like the Lt opcode except that the jump is taken if
95322** the content of register P3 is greater than or equal to the content of
95323** register P1.  See the Lt opcode for additional information.
95324*/
95325case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
95326case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
95327case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
95328case OP_Le:               /* same as TK_LE, jump, in1, in3 */
95329case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
95330case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
95331  int res, res2;      /* Result of the comparison of pIn1 against pIn3 */
95332  char affinity;      /* Affinity to use for comparison */
95333  u16 flags1;         /* Copy of initial value of pIn1->flags */
95334  u16 flags3;         /* Copy of initial value of pIn3->flags */
95335
95336  pIn1 = &aMem[pOp->p1];
95337  pIn3 = &aMem[pOp->p3];
95338  flags1 = pIn1->flags;
95339  flags3 = pIn3->flags;
95340  if( (flags1 & flags3 & MEM_Int)!=0 ){
95341    /* Common case of comparison of two integers */
95342    if( pIn3->u.i > pIn1->u.i ){
95343      if( sqlite3aGTb[pOp->opcode] ){
95344        VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
95345        goto jump_to_p2;
95346      }
95347      iCompare = +1;
95348      VVA_ONLY( iCompareIsInit = 1; )
95349    }else if( pIn3->u.i < pIn1->u.i ){
95350      if( sqlite3aLTb[pOp->opcode] ){
95351        VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
95352        goto jump_to_p2;
95353      }
95354      iCompare = -1;
95355      VVA_ONLY( iCompareIsInit = 1; )
95356    }else{
95357      if( sqlite3aEQb[pOp->opcode] ){
95358        VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
95359        goto jump_to_p2;
95360      }
95361      iCompare = 0;
95362      VVA_ONLY( iCompareIsInit = 1; )
95363    }
95364    VdbeBranchTaken(0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
95365    break;
95366  }
95367  if( (flags1 | flags3)&MEM_Null ){
95368    /* One or both operands are NULL */
95369    if( pOp->p5 & SQLITE_NULLEQ ){
95370      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
95371      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
95372      ** or not both operands are null.
95373      */
95374      assert( (flags1 & MEM_Cleared)==0 );
95375      assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );
95376      testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );
95377      if( (flags1&flags3&MEM_Null)!=0
95378       && (flags3&MEM_Cleared)==0
95379      ){
95380        res = 0;  /* Operands are equal */
95381      }else{
95382        res = ((flags3 & MEM_Null) ? -1 : +1);  /* Operands are not equal */
95383      }
95384    }else{
95385      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
95386      ** then the result is always NULL.
95387      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
95388      */
95389      VdbeBranchTaken(2,3);
95390      if( pOp->p5 & SQLITE_JUMPIFNULL ){
95391        goto jump_to_p2;
95392      }
95393      iCompare = 1;    /* Operands are not equal */
95394      VVA_ONLY( iCompareIsInit = 1; )
95395      break;
95396    }
95397  }else{
95398    /* Neither operand is NULL and we couldn't do the special high-speed
95399    ** integer comparison case.  So do a general-case comparison. */
95400    affinity = pOp->p5 & SQLITE_AFF_MASK;
95401    if( affinity>=SQLITE_AFF_NUMERIC ){
95402      if( (flags1 | flags3)&MEM_Str ){
95403        if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
95404          applyNumericAffinity(pIn1,0);
95405          assert( flags3==pIn3->flags || CORRUPT_DB );
95406          flags3 = pIn3->flags;
95407        }
95408        if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
95409          applyNumericAffinity(pIn3,0);
95410        }
95411      }
95412    }else if( affinity==SQLITE_AFF_TEXT && ((flags1 | flags3) & MEM_Str)!=0 ){
95413      if( (flags1 & MEM_Str)!=0 ){
95414        pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
95415      }else if( (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
95416        testcase( pIn1->flags & MEM_Int );
95417        testcase( pIn1->flags & MEM_Real );
95418        testcase( pIn1->flags & MEM_IntReal );
95419        sqlite3VdbeMemStringify(pIn1, encoding, 1);
95420        testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
95421        flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
95422        if( NEVER(pIn1==pIn3) ) flags3 = flags1 | MEM_Str;
95423      }
95424      if( (flags3 & MEM_Str)!=0 ){
95425        pIn3->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
95426      }else if( (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
95427        testcase( pIn3->flags & MEM_Int );
95428        testcase( pIn3->flags & MEM_Real );
95429        testcase( pIn3->flags & MEM_IntReal );
95430        sqlite3VdbeMemStringify(pIn3, encoding, 1);
95431        testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
95432        flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
95433      }
95434    }
95435    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
95436    res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
95437  }
95438
95439  /* At this point, res is negative, zero, or positive if reg[P1] is
95440  ** less than, equal to, or greater than reg[P3], respectively.  Compute
95441  ** the answer to this operator in res2, depending on what the comparison
95442  ** operator actually is.  The next block of code depends on the fact
95443  ** that the 6 comparison operators are consecutive integers in this
95444  ** order:  NE, EQ, GT, LE, LT, GE */
95445  assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
95446  assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
95447  if( res<0 ){
95448    res2 = sqlite3aLTb[pOp->opcode];
95449  }else if( res==0 ){
95450    res2 = sqlite3aEQb[pOp->opcode];
95451  }else{
95452    res2 = sqlite3aGTb[pOp->opcode];
95453  }
95454  iCompare = res;
95455  VVA_ONLY( iCompareIsInit = 1; )
95456
95457  /* Undo any changes made by applyAffinity() to the input registers. */
95458  assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
95459  pIn3->flags = flags3;
95460  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
95461  pIn1->flags = flags1;
95462
95463  VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
95464  if( res2 ){
95465    goto jump_to_p2;
95466  }
95467  break;
95468}
95469
95470/* Opcode: ElseEq * P2 * * *
95471**
95472** This opcode must follow an OP_Lt or OP_Gt comparison operator.  There
95473** can be zero or more OP_ReleaseReg opcodes intervening, but no other
95474** opcodes are allowed to occur between this instruction and the previous
95475** OP_Lt or OP_Gt.
95476**
95477** If the result of an OP_Eq comparison on the same two operands as
95478** the prior OP_Lt or OP_Gt would have been true, then jump to P2.  If
95479** the result of an OP_Eq comparison on the two previous operands
95480** would have been false or NULL, then fall through.
95481*/
95482case OP_ElseEq: {       /* same as TK_ESCAPE, jump */
95483
95484#ifdef SQLITE_DEBUG
95485  /* Verify the preconditions of this opcode - that it follows an OP_Lt or
95486  ** OP_Gt with zero or more intervening OP_ReleaseReg opcodes */
95487  int iAddr;
95488  for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){
95489    if( aOp[iAddr].opcode==OP_ReleaseReg ) continue;
95490    assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt );
95491    break;
95492  }
95493#endif /* SQLITE_DEBUG */
95494  assert( iCompareIsInit );
95495  VdbeBranchTaken(iCompare==0, 2);
95496  if( iCompare==0 ) goto jump_to_p2;
95497  break;
95498}
95499
95500
95501/* Opcode: Permutation * * * P4 *
95502**
95503** Set the permutation used by the OP_Compare operator in the next
95504** instruction.  The permutation is stored in the P4 operand.
95505**
95506** The permutation is only valid for the next opcode which must be
95507** an OP_Compare that has the OPFLAG_PERMUTE bit set in P5.
95508**
95509** The first integer in the P4 integer array is the length of the array
95510** and does not become part of the permutation.
95511*/
95512case OP_Permutation: {
95513  assert( pOp->p4type==P4_INTARRAY );
95514  assert( pOp->p4.ai );
95515  assert( pOp[1].opcode==OP_Compare );
95516  assert( pOp[1].p5 & OPFLAG_PERMUTE );
95517  break;
95518}
95519
95520/* Opcode: Compare P1 P2 P3 P4 P5
95521** Synopsis: r[P1@P3] <-> r[P2@P3]
95522**
95523** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
95524** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
95525** the comparison for use by the next OP_Jump instruct.
95526**
95527** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
95528** determined by the most recent OP_Permutation operator.  If the
95529** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
95530** order.
95531**
95532** P4 is a KeyInfo structure that defines collating sequences and sort
95533** orders for the comparison.  The permutation applies to registers
95534** only.  The KeyInfo elements are used sequentially.
95535**
95536** The comparison is a sort comparison, so NULLs compare equal,
95537** NULLs are less than numbers, numbers are less than strings,
95538** and strings are less than blobs.
95539**
95540** This opcode must be immediately followed by an OP_Jump opcode.
95541*/
95542case OP_Compare: {
95543  int n;
95544  int i;
95545  int p1;
95546  int p2;
95547  const KeyInfo *pKeyInfo;
95548  u32 idx;
95549  CollSeq *pColl;    /* Collating sequence to use on this term */
95550  int bRev;          /* True for DESCENDING sort order */
95551  u32 *aPermute;     /* The permutation */
95552
95553  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
95554    aPermute = 0;
95555  }else{
95556    assert( pOp>aOp );
95557    assert( pOp[-1].opcode==OP_Permutation );
95558    assert( pOp[-1].p4type==P4_INTARRAY );
95559    aPermute = pOp[-1].p4.ai + 1;
95560    assert( aPermute!=0 );
95561  }
95562  n = pOp->p3;
95563  pKeyInfo = pOp->p4.pKeyInfo;
95564  assert( n>0 );
95565  assert( pKeyInfo!=0 );
95566  p1 = pOp->p1;
95567  p2 = pOp->p2;
95568#ifdef SQLITE_DEBUG
95569  if( aPermute ){
95570    int k, mx = 0;
95571    for(k=0; k<n; k++) if( aPermute[k]>(u32)mx ) mx = aPermute[k];
95572    assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
95573    assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
95574  }else{
95575    assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
95576    assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
95577  }
95578#endif /* SQLITE_DEBUG */
95579  for(i=0; i<n; i++){
95580    idx = aPermute ? aPermute[i] : (u32)i;
95581    assert( memIsValid(&aMem[p1+idx]) );
95582    assert( memIsValid(&aMem[p2+idx]) );
95583    REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
95584    REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
95585    assert( i<pKeyInfo->nKeyField );
95586    pColl = pKeyInfo->aColl[i];
95587    bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC);
95588    iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
95589    VVA_ONLY( iCompareIsInit = 1; )
95590    if( iCompare ){
95591      if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
95592       && ((aMem[p1+idx].flags & MEM_Null) || (aMem[p2+idx].flags & MEM_Null))
95593      ){
95594        iCompare = -iCompare;
95595      }
95596      if( bRev ) iCompare = -iCompare;
95597      break;
95598    }
95599  }
95600  assert( pOp[1].opcode==OP_Jump );
95601  break;
95602}
95603
95604/* Opcode: Jump P1 P2 P3 * *
95605**
95606** Jump to the instruction at address P1, P2, or P3 depending on whether
95607** in the most recent OP_Compare instruction the P1 vector was less than,
95608** equal to, or greater than the P2 vector, respectively.
95609**
95610** This opcode must immediately follow an OP_Compare opcode.
95611*/
95612case OP_Jump: {             /* jump */
95613  assert( pOp>aOp && pOp[-1].opcode==OP_Compare );
95614  assert( iCompareIsInit );
95615  if( iCompare<0 ){
95616    VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
95617  }else if( iCompare==0 ){
95618    VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
95619  }else{
95620    VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
95621  }
95622  break;
95623}
95624
95625/* Opcode: And P1 P2 P3 * *
95626** Synopsis: r[P3]=(r[P1] && r[P2])
95627**
95628** Take the logical AND of the values in registers P1 and P2 and
95629** write the result into register P3.
95630**
95631** If either P1 or P2 is 0 (false) then the result is 0 even if
95632** the other input is NULL.  A NULL and true or two NULLs give
95633** a NULL output.
95634*/
95635/* Opcode: Or P1 P2 P3 * *
95636** Synopsis: r[P3]=(r[P1] || r[P2])
95637**
95638** Take the logical OR of the values in register P1 and P2 and
95639** store the answer in register P3.
95640**
95641** If either P1 or P2 is nonzero (true) then the result is 1 (true)
95642** even if the other input is NULL.  A NULL and false or two NULLs
95643** give a NULL output.
95644*/
95645case OP_And:              /* same as TK_AND, in1, in2, out3 */
95646case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
95647  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
95648  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
95649
95650  v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
95651  v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
95652  if( pOp->opcode==OP_And ){
95653    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
95654    v1 = and_logic[v1*3+v2];
95655  }else{
95656    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
95657    v1 = or_logic[v1*3+v2];
95658  }
95659  pOut = &aMem[pOp->p3];
95660  if( v1==2 ){
95661    MemSetTypeFlag(pOut, MEM_Null);
95662  }else{
95663    pOut->u.i = v1;
95664    MemSetTypeFlag(pOut, MEM_Int);
95665  }
95666  break;
95667}
95668
95669/* Opcode: IsTrue P1 P2 P3 P4 *
95670** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
95671**
95672** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
95673** IS NOT FALSE operators.
95674**
95675** Interpret the value in register P1 as a boolean value.  Store that
95676** boolean (a 0 or 1) in register P2.  Or if the value in register P1 is
95677** NULL, then the P3 is stored in register P2.  Invert the answer if P4
95678** is 1.
95679**
95680** The logic is summarized like this:
95681**
95682** <ul>
95683** <li> If P3==0 and P4==0  then  r[P2] := r[P1] IS TRUE
95684** <li> If P3==1 and P4==1  then  r[P2] := r[P1] IS FALSE
95685** <li> If P3==0 and P4==1  then  r[P2] := r[P1] IS NOT TRUE
95686** <li> If P3==1 and P4==0  then  r[P2] := r[P1] IS NOT FALSE
95687** </ul>
95688*/
95689case OP_IsTrue: {               /* in1, out2 */
95690  assert( pOp->p4type==P4_INT32 );
95691  assert( pOp->p4.i==0 || pOp->p4.i==1 );
95692  assert( pOp->p3==0 || pOp->p3==1 );
95693  sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
95694      sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
95695  break;
95696}
95697
95698/* Opcode: Not P1 P2 * * *
95699** Synopsis: r[P2]= !r[P1]
95700**
95701** Interpret the value in register P1 as a boolean value.  Store the
95702** boolean complement in register P2.  If the value in register P1 is
95703** NULL, then a NULL is stored in P2.
95704*/
95705case OP_Not: {                /* same as TK_NOT, in1, out2 */
95706  pIn1 = &aMem[pOp->p1];
95707  pOut = &aMem[pOp->p2];
95708  if( (pIn1->flags & MEM_Null)==0 ){
95709    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
95710  }else{
95711    sqlite3VdbeMemSetNull(pOut);
95712  }
95713  break;
95714}
95715
95716/* Opcode: BitNot P1 P2 * * *
95717** Synopsis: r[P2]= ~r[P1]
95718**
95719** Interpret the content of register P1 as an integer.  Store the
95720** ones-complement of the P1 value into register P2.  If P1 holds
95721** a NULL then store a NULL in P2.
95722*/
95723case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
95724  pIn1 = &aMem[pOp->p1];
95725  pOut = &aMem[pOp->p2];
95726  sqlite3VdbeMemSetNull(pOut);
95727  if( (pIn1->flags & MEM_Null)==0 ){
95728    pOut->flags = MEM_Int;
95729    pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
95730  }
95731  break;
95732}
95733
95734/* Opcode: Once P1 P2 * * *
95735**
95736** Fall through to the next instruction the first time this opcode is
95737** encountered on each invocation of the byte-code program.  Jump to P2
95738** on the second and all subsequent encounters during the same invocation.
95739**
95740** Top-level programs determine first invocation by comparing the P1
95741** operand against the P1 operand on the OP_Init opcode at the beginning
95742** of the program.  If the P1 values differ, then fall through and make
95743** the P1 of this opcode equal to the P1 of OP_Init.  If P1 values are
95744** the same then take the jump.
95745**
95746** For subprograms, there is a bitmask in the VdbeFrame that determines
95747** whether or not the jump should be taken.  The bitmask is necessary
95748** because the self-altering code trick does not work for recursive
95749** triggers.
95750*/
95751case OP_Once: {             /* jump */
95752  u32 iAddr;                /* Address of this instruction */
95753  assert( p->aOp[0].opcode==OP_Init );
95754  if( p->pFrame ){
95755    iAddr = (int)(pOp - p->aOp);
95756    if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
95757      VdbeBranchTaken(1, 2);
95758      goto jump_to_p2;
95759    }
95760    p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
95761  }else{
95762    if( p->aOp[0].p1==pOp->p1 ){
95763      VdbeBranchTaken(1, 2);
95764      goto jump_to_p2;
95765    }
95766  }
95767  VdbeBranchTaken(0, 2);
95768  pOp->p1 = p->aOp[0].p1;
95769  break;
95770}
95771
95772/* Opcode: If P1 P2 P3 * *
95773**
95774** Jump to P2 if the value in register P1 is true.  The value
95775** is considered true if it is numeric and non-zero.  If the value
95776** in P1 is NULL then take the jump if and only if P3 is non-zero.
95777*/
95778case OP_If:  {               /* jump, in1 */
95779  int c;
95780  c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
95781  VdbeBranchTaken(c!=0, 2);
95782  if( c ) goto jump_to_p2;
95783  break;
95784}
95785
95786/* Opcode: IfNot P1 P2 P3 * *
95787**
95788** Jump to P2 if the value in register P1 is False.  The value
95789** is considered false if it has a numeric value of zero.  If the value
95790** in P1 is NULL then take the jump if and only if P3 is non-zero.
95791*/
95792case OP_IfNot: {            /* jump, in1 */
95793  int c;
95794  c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
95795  VdbeBranchTaken(c!=0, 2);
95796  if( c ) goto jump_to_p2;
95797  break;
95798}
95799
95800/* Opcode: IsNull P1 P2 * * *
95801** Synopsis: if r[P1]==NULL goto P2
95802**
95803** Jump to P2 if the value in register P1 is NULL.
95804*/
95805case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
95806  pIn1 = &aMem[pOp->p1];
95807  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
95808  if( (pIn1->flags & MEM_Null)!=0 ){
95809    goto jump_to_p2;
95810  }
95811  break;
95812}
95813
95814/* Opcode: IsType P1 P2 P3 P4 P5
95815** Synopsis: if typeof(P1.P3) in P5 goto P2
95816**
95817** Jump to P2 if the type of a column in a btree is one of the types specified
95818** by the P5 bitmask.
95819**
95820** P1 is normally a cursor on a btree for which the row decode cache is
95821** valid through at least column P3.  In other words, there should have been
95822** a prior OP_Column for column P3 or greater.  If the cursor is not valid,
95823** then this opcode might give spurious results.
95824** The the btree row has fewer than P3 columns, then use P4 as the
95825** datatype.
95826**
95827** If P1 is -1, then P3 is a register number and the datatype is taken
95828** from the value in that register.
95829**
95830** P5 is a bitmask of data types.  SQLITE_INTEGER is the least significant
95831** (0x01) bit. SQLITE_FLOAT is the 0x02 bit. SQLITE_TEXT is 0x04.
95832** SQLITE_BLOB is 0x08.  SQLITE_NULL is 0x10.
95833**
95834** WARNING: This opcode does not reliably distinguish between NULL and REAL
95835** when P1>=0.  If the database contains a NaN value, this opcode will think
95836** that the datatype is REAL when it should be NULL.  When P1<0 and the value
95837** is already stored in register P3, then this opcode does reliably
95838** distinguish between NULL and REAL.  The problem only arises then P1>=0.
95839**
95840** Take the jump to address P2 if and only if the datatype of the
95841** value determined by P1 and P3 corresponds to one of the bits in the
95842** P5 bitmask.
95843**
95844*/
95845case OP_IsType: {        /* jump */
95846  VdbeCursor *pC;
95847  u16 typeMask;
95848  u32 serialType;
95849
95850  assert( pOp->p1>=(-1) && pOp->p1<p->nCursor );
95851  assert( pOp->p1>=0 || (pOp->p3>=0 && pOp->p3<=(p->nMem+1 - p->nCursor)) );
95852  if( pOp->p1>=0 ){
95853    pC = p->apCsr[pOp->p1];
95854    assert( pC!=0 );
95855    assert( pOp->p3>=0 );
95856    if( pOp->p3<pC->nHdrParsed ){
95857      serialType = pC->aType[pOp->p3];
95858      if( serialType>=12 ){
95859        if( serialType&1 ){
95860          typeMask = 0x04;   /* SQLITE_TEXT */
95861        }else{
95862          typeMask = 0x08;   /* SQLITE_BLOB */
95863        }
95864      }else{
95865        static const unsigned char aMask[] = {
95866           0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x2,
95867           0x01, 0x01, 0x10, 0x10
95868        };
95869        testcase( serialType==0 );
95870        testcase( serialType==1 );
95871        testcase( serialType==2 );
95872        testcase( serialType==3 );
95873        testcase( serialType==4 );
95874        testcase( serialType==5 );
95875        testcase( serialType==6 );
95876        testcase( serialType==7 );
95877        testcase( serialType==8 );
95878        testcase( serialType==9 );
95879        testcase( serialType==10 );
95880        testcase( serialType==11 );
95881        typeMask = aMask[serialType];
95882      }
95883    }else{
95884      typeMask = 1 << (pOp->p4.i - 1);
95885      testcase( typeMask==0x01 );
95886      testcase( typeMask==0x02 );
95887      testcase( typeMask==0x04 );
95888      testcase( typeMask==0x08 );
95889      testcase( typeMask==0x10 );
95890    }
95891  }else{
95892    assert( memIsValid(&aMem[pOp->p3]) );
95893    typeMask = 1 << (sqlite3_value_type((sqlite3_value*)&aMem[pOp->p3])-1);
95894    testcase( typeMask==0x01 );
95895    testcase( typeMask==0x02 );
95896    testcase( typeMask==0x04 );
95897    testcase( typeMask==0x08 );
95898    testcase( typeMask==0x10 );
95899  }
95900  VdbeBranchTaken( (typeMask & pOp->p5)!=0, 2);
95901  if( typeMask & pOp->p5 ){
95902    goto jump_to_p2;
95903  }
95904  break;
95905}
95906
95907/* Opcode: ZeroOrNull P1 P2 P3 * *
95908** Synopsis: r[P2] = 0 OR NULL
95909**
95910** If both registers P1 and P3 are NOT NULL, then store a zero in
95911** register P2.  If either registers P1 or P3 are NULL then put
95912** a NULL in register P2.
95913*/
95914case OP_ZeroOrNull: {            /* in1, in2, out2, in3 */
95915  if( (aMem[pOp->p1].flags & MEM_Null)!=0
95916   || (aMem[pOp->p3].flags & MEM_Null)!=0
95917  ){
95918    sqlite3VdbeMemSetNull(aMem + pOp->p2);
95919  }else{
95920    sqlite3VdbeMemSetInt64(aMem + pOp->p2, 0);
95921  }
95922  break;
95923}
95924
95925/* Opcode: NotNull P1 P2 * * *
95926** Synopsis: if r[P1]!=NULL goto P2
95927**
95928** Jump to P2 if the value in register P1 is not NULL.
95929*/
95930case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
95931  pIn1 = &aMem[pOp->p1];
95932  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
95933  if( (pIn1->flags & MEM_Null)==0 ){
95934    goto jump_to_p2;
95935  }
95936  break;
95937}
95938
95939/* Opcode: IfNullRow P1 P2 P3 * *
95940** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
95941**
95942** Check the cursor P1 to see if it is currently pointing at a NULL row.
95943** If it is, then set register P3 to NULL and jump immediately to P2.
95944** If P1 is not on a NULL row, then fall through without making any
95945** changes.
95946**
95947** If P1 is not an open cursor, then this opcode is a no-op.
95948*/
95949case OP_IfNullRow: {         /* jump */
95950  VdbeCursor *pC;
95951  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
95952  pC = p->apCsr[pOp->p1];
95953  if( pC && pC->nullRow ){
95954    sqlite3VdbeMemSetNull(aMem + pOp->p3);
95955    goto jump_to_p2;
95956  }
95957  break;
95958}
95959
95960#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
95961/* Opcode: Offset P1 P2 P3 * *
95962** Synopsis: r[P3] = sqlite_offset(P1)
95963**
95964** Store in register r[P3] the byte offset into the database file that is the
95965** start of the payload for the record at which that cursor P1 is currently
95966** pointing.
95967**
95968** P2 is the column number for the argument to the sqlite_offset() function.
95969** This opcode does not use P2 itself, but the P2 value is used by the
95970** code generator.  The P1, P2, and P3 operands to this opcode are the
95971** same as for OP_Column.
95972**
95973** This opcode is only available if SQLite is compiled with the
95974** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
95975*/
95976case OP_Offset: {          /* out3 */
95977  VdbeCursor *pC;    /* The VDBE cursor */
95978  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
95979  pC = p->apCsr[pOp->p1];
95980  pOut = &p->aMem[pOp->p3];
95981  if( pC==0 || pC->eCurType!=CURTYPE_BTREE ){
95982    sqlite3VdbeMemSetNull(pOut);
95983  }else{
95984    if( pC->deferredMoveto ){
95985      rc = sqlite3VdbeFinishMoveto(pC);
95986      if( rc ) goto abort_due_to_error;
95987    }
95988    if( sqlite3BtreeEof(pC->uc.pCursor) ){
95989      sqlite3VdbeMemSetNull(pOut);
95990    }else{
95991      sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
95992    }
95993  }
95994  break;
95995}
95996#endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
95997
95998/* Opcode: Column P1 P2 P3 P4 P5
95999** Synopsis: r[P3]=PX cursor P1 column P2
96000**
96001** Interpret the data that cursor P1 points to as a structure built using
96002** the MakeRecord instruction.  (See the MakeRecord opcode for additional
96003** information about the format of the data.)  Extract the P2-th column
96004** from this record.  If there are less than (P2+1)
96005** values in the record, extract a NULL.
96006**
96007** The value extracted is stored in register P3.
96008**
96009** If the record contains fewer than P2 fields, then extract a NULL.  Or,
96010** if the P4 argument is a P4_MEM use the value of the P4 argument as
96011** the result.
96012**
96013** If the OPFLAG_LENGTHARG bit is set in P5 then the result is guaranteed
96014** to only be used by the length() function or the equivalent.  The content
96015** of large blobs is not loaded, thus saving CPU cycles.  If the
96016** OPFLAG_TYPEOFARG bit is set then the result will only be used by the
96017** typeof() function or the IS NULL or IS NOT NULL operators or the
96018** equivalent.  In this case, all content loading can be omitted.
96019*/
96020case OP_Column: {            /* ncycle */
96021  u32 p2;            /* column number to retrieve */
96022  VdbeCursor *pC;    /* The VDBE cursor */
96023  BtCursor *pCrsr;   /* The B-Tree cursor corresponding to pC */
96024  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
96025  int len;           /* The length of the serialized data for the column */
96026  int i;             /* Loop counter */
96027  Mem *pDest;        /* Where to write the extracted value */
96028  Mem sMem;          /* For storing the record being decoded */
96029  const u8 *zData;   /* Part of the record being decoded */
96030  const u8 *zHdr;    /* Next unparsed byte of the header */
96031  const u8 *zEndHdr; /* Pointer to first byte after the header */
96032  u64 offset64;      /* 64-bit offset */
96033  u32 t;             /* A type code from the record header */
96034  Mem *pReg;         /* PseudoTable input register */
96035
96036  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96037  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
96038  pC = p->apCsr[pOp->p1];
96039  p2 = (u32)pOp->p2;
96040
96041op_column_restart:
96042  assert( pC!=0 );
96043  assert( p2<(u32)pC->nField
96044       || (pC->eCurType==CURTYPE_PSEUDO && pC->seekResult==0) );
96045  aOffset = pC->aOffset;
96046  assert( aOffset==pC->aType+pC->nField );
96047  assert( pC->eCurType!=CURTYPE_VTAB );
96048  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
96049  assert( pC->eCurType!=CURTYPE_SORTER );
96050
96051  if( pC->cacheStatus!=p->cacheCtr ){                /*OPTIMIZATION-IF-FALSE*/
96052    if( pC->nullRow ){
96053      if( pC->eCurType==CURTYPE_PSEUDO && pC->seekResult>0 ){
96054        /* For the special case of as pseudo-cursor, the seekResult field
96055        ** identifies the register that holds the record */
96056        pReg = &aMem[pC->seekResult];
96057        assert( pReg->flags & MEM_Blob );
96058        assert( memIsValid(pReg) );
96059        pC->payloadSize = pC->szRow = pReg->n;
96060        pC->aRow = (u8*)pReg->z;
96061      }else{
96062        pDest = &aMem[pOp->p3];
96063        memAboutToChange(p, pDest);
96064        sqlite3VdbeMemSetNull(pDest);
96065        goto op_column_out;
96066      }
96067    }else{
96068      pCrsr = pC->uc.pCursor;
96069      if( pC->deferredMoveto ){
96070        u32 iMap;
96071        assert( !pC->isEphemeral );
96072        if( pC->ub.aAltMap && (iMap = pC->ub.aAltMap[1+p2])>0  ){
96073          pC = pC->pAltCursor;
96074          p2 = iMap - 1;
96075          goto op_column_restart;
96076        }
96077        rc = sqlite3VdbeFinishMoveto(pC);
96078        if( rc ) goto abort_due_to_error;
96079      }else if( sqlite3BtreeCursorHasMoved(pCrsr) ){
96080        rc = sqlite3VdbeHandleMovedCursor(pC);
96081        if( rc ) goto abort_due_to_error;
96082        goto op_column_restart;
96083      }
96084      assert( pC->eCurType==CURTYPE_BTREE );
96085      assert( pCrsr );
96086      assert( sqlite3BtreeCursorIsValid(pCrsr) );
96087      pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
96088      pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
96089      assert( pC->szRow<=pC->payloadSize );
96090      assert( pC->szRow<=65536 );  /* Maximum page size is 64KiB */
96091    }
96092    pC->cacheStatus = p->cacheCtr;
96093    if( (aOffset[0] = pC->aRow[0])<0x80 ){
96094      pC->iHdrOffset = 1;
96095    }else{
96096      pC->iHdrOffset = sqlite3GetVarint32(pC->aRow, aOffset);
96097    }
96098    pC->nHdrParsed = 0;
96099
96100    if( pC->szRow<aOffset[0] ){      /*OPTIMIZATION-IF-FALSE*/
96101      /* pC->aRow does not have to hold the entire row, but it does at least
96102      ** need to cover the header of the record.  If pC->aRow does not contain
96103      ** the complete header, then set it to zero, forcing the header to be
96104      ** dynamically allocated. */
96105      pC->aRow = 0;
96106      pC->szRow = 0;
96107
96108      /* Make sure a corrupt database has not given us an oversize header.
96109      ** Do this now to avoid an oversize memory allocation.
96110      **
96111      ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
96112      ** types use so much data space that there can only be 4096 and 32 of
96113      ** them, respectively.  So the maximum header length results from a
96114      ** 3-byte type for each of the maximum of 32768 columns plus three
96115      ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
96116      */
96117      if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
96118        goto op_column_corrupt;
96119      }
96120    }else{
96121      /* This is an optimization.  By skipping over the first few tests
96122      ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
96123      ** measurable performance gain.
96124      **
96125      ** This branch is taken even if aOffset[0]==0.  Such a record is never
96126      ** generated by SQLite, and could be considered corruption, but we
96127      ** accept it for historical reasons.  When aOffset[0]==0, the code this
96128      ** branch jumps to reads past the end of the record, but never more
96129      ** than a few bytes.  Even if the record occurs at the end of the page
96130      ** content area, the "page header" comes after the page content and so
96131      ** this overread is harmless.  Similar overreads can occur for a corrupt
96132      ** database file.
96133      */
96134      zData = pC->aRow;
96135      assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
96136      testcase( aOffset[0]==0 );
96137      goto op_column_read_header;
96138    }
96139  }else if( sqlite3BtreeCursorHasMoved(pC->uc.pCursor) ){
96140    rc = sqlite3VdbeHandleMovedCursor(pC);
96141    if( rc ) goto abort_due_to_error;
96142    goto op_column_restart;
96143  }
96144
96145  /* Make sure at least the first p2+1 entries of the header have been
96146  ** parsed and valid information is in aOffset[] and pC->aType[].
96147  */
96148  if( pC->nHdrParsed<=p2 ){
96149    /* If there is more header available for parsing in the record, try
96150    ** to extract additional fields up through the p2+1-th field
96151    */
96152    if( pC->iHdrOffset<aOffset[0] ){
96153      /* Make sure zData points to enough of the record to cover the header. */
96154      if( pC->aRow==0 ){
96155        memset(&sMem, 0, sizeof(sMem));
96156        rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem);
96157        if( rc!=SQLITE_OK ) goto abort_due_to_error;
96158        zData = (u8*)sMem.z;
96159      }else{
96160        zData = pC->aRow;
96161      }
96162
96163      /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
96164    op_column_read_header:
96165      i = pC->nHdrParsed;
96166      offset64 = aOffset[i];
96167      zHdr = zData + pC->iHdrOffset;
96168      zEndHdr = zData + aOffset[0];
96169      testcase( zHdr>=zEndHdr );
96170      do{
96171        if( (pC->aType[i] = t = zHdr[0])<0x80 ){
96172          zHdr++;
96173          offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
96174        }else{
96175          zHdr += sqlite3GetVarint32(zHdr, &t);
96176          pC->aType[i] = t;
96177          offset64 += sqlite3VdbeSerialTypeLen(t);
96178        }
96179        aOffset[++i] = (u32)(offset64 & 0xffffffff);
96180      }while( (u32)i<=p2 && zHdr<zEndHdr );
96181
96182      /* The record is corrupt if any of the following are true:
96183      ** (1) the bytes of the header extend past the declared header size
96184      ** (2) the entire header was used but not all data was used
96185      ** (3) the end of the data extends beyond the end of the record.
96186      */
96187      if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
96188       || (offset64 > pC->payloadSize)
96189      ){
96190        if( aOffset[0]==0 ){
96191          i = 0;
96192          zHdr = zEndHdr;
96193        }else{
96194          if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
96195          goto op_column_corrupt;
96196        }
96197      }
96198
96199      pC->nHdrParsed = i;
96200      pC->iHdrOffset = (u32)(zHdr - zData);
96201      if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
96202    }else{
96203      t = 0;
96204    }
96205
96206    /* If after trying to extract new entries from the header, nHdrParsed is
96207    ** still not up to p2, that means that the record has fewer than p2
96208    ** columns.  So the result will be either the default value or a NULL.
96209    */
96210    if( pC->nHdrParsed<=p2 ){
96211      pDest = &aMem[pOp->p3];
96212      memAboutToChange(p, pDest);
96213      if( pOp->p4type==P4_MEM ){
96214        sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
96215      }else{
96216        sqlite3VdbeMemSetNull(pDest);
96217      }
96218      goto op_column_out;
96219    }
96220  }else{
96221    t = pC->aType[p2];
96222  }
96223
96224  /* Extract the content for the p2+1-th column.  Control can only
96225  ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
96226  ** all valid.
96227  */
96228  assert( p2<pC->nHdrParsed );
96229  assert( rc==SQLITE_OK );
96230  pDest = &aMem[pOp->p3];
96231  memAboutToChange(p, pDest);
96232  assert( sqlite3VdbeCheckMemInvariants(pDest) );
96233  if( VdbeMemDynamic(pDest) ){
96234    sqlite3VdbeMemSetNull(pDest);
96235  }
96236  assert( t==pC->aType[p2] );
96237  if( pC->szRow>=aOffset[p2+1] ){
96238    /* This is the common case where the desired content fits on the original
96239    ** page - where the content is not on an overflow page */
96240    zData = pC->aRow + aOffset[p2];
96241    if( t<12 ){
96242      sqlite3VdbeSerialGet(zData, t, pDest);
96243    }else{
96244      /* If the column value is a string, we need a persistent value, not
96245      ** a MEM_Ephem value.  This branch is a fast short-cut that is equivalent
96246      ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
96247      */
96248      static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
96249      pDest->n = len = (t-12)/2;
96250      pDest->enc = encoding;
96251      if( pDest->szMalloc < len+2 ){
96252        if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) goto too_big;
96253        pDest->flags = MEM_Null;
96254        if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
96255      }else{
96256        pDest->z = pDest->zMalloc;
96257      }
96258      memcpy(pDest->z, zData, len);
96259      pDest->z[len] = 0;
96260      pDest->z[len+1] = 0;
96261      pDest->flags = aFlag[t&1];
96262    }
96263  }else{
96264    u8 p5;
96265    pDest->enc = encoding;
96266    assert( pDest->db==db );
96267    /* This branch happens only when content is on overflow pages */
96268    if( ((p5 = (pOp->p5 & OPFLAG_BYTELENARG))!=0
96269          && (p5==OPFLAG_TYPEOFARG
96270              || (t>=12 && ((t&1)==0 || p5==OPFLAG_BYTELENARG))
96271             )
96272        )
96273     || sqlite3VdbeSerialTypeLen(t)==0
96274    ){
96275      /* Content is irrelevant for
96276      **    1. the typeof() function,
96277      **    2. the length(X) function if X is a blob, and
96278      **    3. if the content length is zero.
96279      ** So we might as well use bogus content rather than reading
96280      ** content from disk.
96281      **
96282      ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
96283      ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
96284      ** read more.  Use the global constant sqlite3CtypeMap[] as the array,
96285      ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint())
96286      ** and it begins with a bunch of zeros.
96287      */
96288      sqlite3VdbeSerialGet((u8*)sqlite3CtypeMap, t, pDest);
96289    }else{
96290      rc = vdbeColumnFromOverflow(pC, p2, t, aOffset[p2],
96291                p->cacheCtr, colCacheCtr, pDest);
96292      if( rc ){
96293        if( rc==SQLITE_NOMEM ) goto no_mem;
96294        if( rc==SQLITE_TOOBIG ) goto too_big;
96295        goto abort_due_to_error;
96296      }
96297    }
96298  }
96299
96300op_column_out:
96301  UPDATE_MAX_BLOBSIZE(pDest);
96302  REGISTER_TRACE(pOp->p3, pDest);
96303  break;
96304
96305op_column_corrupt:
96306  if( aOp[0].p3>0 ){
96307    pOp = &aOp[aOp[0].p3-1];
96308    break;
96309  }else{
96310    rc = SQLITE_CORRUPT_BKPT;
96311    goto abort_due_to_error;
96312  }
96313}
96314
96315/* Opcode: TypeCheck P1 P2 P3 P4 *
96316** Synopsis: typecheck(r[P1@P2])
96317**
96318** Apply affinities to the range of P2 registers beginning with P1.
96319** Take the affinities from the Table object in P4.  If any value
96320** cannot be coerced into the correct type, then raise an error.
96321**
96322** This opcode is similar to OP_Affinity except that this opcode
96323** forces the register type to the Table column type.  This is used
96324** to implement "strict affinity".
96325**
96326** GENERATED ALWAYS AS ... STATIC columns are only checked if P3
96327** is zero.  When P3 is non-zero, no type checking occurs for
96328** static generated columns.  Virtual columns are computed at query time
96329** and so they are never checked.
96330**
96331** Preconditions:
96332**
96333** <ul>
96334** <li> P2 should be the number of non-virtual columns in the
96335**      table of P4.
96336** <li> Table P4 should be a STRICT table.
96337** </ul>
96338**
96339** If any precondition is false, an assertion fault occurs.
96340*/
96341case OP_TypeCheck: {
96342  Table *pTab;
96343  Column *aCol;
96344  int i;
96345
96346  assert( pOp->p4type==P4_TABLE );
96347  pTab = pOp->p4.pTab;
96348  assert( pTab->tabFlags & TF_Strict );
96349  assert( pTab->nNVCol==pOp->p2 );
96350  aCol = pTab->aCol;
96351  pIn1 = &aMem[pOp->p1];
96352  for(i=0; i<pTab->nCol; i++){
96353    if( aCol[i].colFlags & COLFLAG_GENERATED ){
96354      if( aCol[i].colFlags & COLFLAG_VIRTUAL ) continue;
96355      if( pOp->p3 ){ pIn1++; continue; }
96356    }
96357    assert( pIn1 < &aMem[pOp->p1+pOp->p2] );
96358    applyAffinity(pIn1, aCol[i].affinity, encoding);
96359    if( (pIn1->flags & MEM_Null)==0 ){
96360      switch( aCol[i].eCType ){
96361        case COLTYPE_BLOB: {
96362          if( (pIn1->flags & MEM_Blob)==0 ) goto vdbe_type_error;
96363          break;
96364        }
96365        case COLTYPE_INTEGER:
96366        case COLTYPE_INT: {
96367          if( (pIn1->flags & MEM_Int)==0 ) goto vdbe_type_error;
96368          break;
96369        }
96370        case COLTYPE_TEXT: {
96371          if( (pIn1->flags & MEM_Str)==0 ) goto vdbe_type_error;
96372          break;
96373        }
96374        case COLTYPE_REAL: {
96375          testcase( (pIn1->flags & (MEM_Real|MEM_IntReal))==MEM_Real );
96376          assert( (pIn1->flags & MEM_IntReal)==0 );
96377          if( pIn1->flags & MEM_Int ){
96378            /* When applying REAL affinity, if the result is still an MEM_Int
96379            ** that will fit in 6 bytes, then change the type to MEM_IntReal
96380            ** so that we keep the high-resolution integer value but know that
96381            ** the type really wants to be REAL. */
96382            testcase( pIn1->u.i==140737488355328LL );
96383            testcase( pIn1->u.i==140737488355327LL );
96384            testcase( pIn1->u.i==-140737488355328LL );
96385            testcase( pIn1->u.i==-140737488355329LL );
96386            if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL){
96387              pIn1->flags |= MEM_IntReal;
96388              pIn1->flags &= ~MEM_Int;
96389            }else{
96390              pIn1->u.r = (double)pIn1->u.i;
96391              pIn1->flags |= MEM_Real;
96392              pIn1->flags &= ~MEM_Int;
96393            }
96394          }else if( (pIn1->flags & (MEM_Real|MEM_IntReal))==0 ){
96395            goto vdbe_type_error;
96396          }
96397          break;
96398        }
96399        default: {
96400          /* COLTYPE_ANY.  Accept anything. */
96401          break;
96402        }
96403      }
96404    }
96405    REGISTER_TRACE((int)(pIn1-aMem), pIn1);
96406    pIn1++;
96407  }
96408  assert( pIn1 == &aMem[pOp->p1+pOp->p2] );
96409  break;
96410
96411vdbe_type_error:
96412  sqlite3VdbeError(p, "cannot store %s value in %s column %s.%s",
96413     vdbeMemTypeName(pIn1), sqlite3StdType[aCol[i].eCType-1],
96414     pTab->zName, aCol[i].zCnName);
96415  rc = SQLITE_CONSTRAINT_DATATYPE;
96416  goto abort_due_to_error;
96417}
96418
96419/* Opcode: Affinity P1 P2 * P4 *
96420** Synopsis: affinity(r[P1@P2])
96421**
96422** Apply affinities to a range of P2 registers starting with P1.
96423**
96424** P4 is a string that is P2 characters long. The N-th character of the
96425** string indicates the column affinity that should be used for the N-th
96426** memory cell in the range.
96427*/
96428case OP_Affinity: {
96429  const char *zAffinity;   /* The affinity to be applied */
96430
96431  zAffinity = pOp->p4.z;
96432  assert( zAffinity!=0 );
96433  assert( pOp->p2>0 );
96434  assert( zAffinity[pOp->p2]==0 );
96435  pIn1 = &aMem[pOp->p1];
96436  while( 1 /*exit-by-break*/ ){
96437    assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
96438    assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) );
96439    applyAffinity(pIn1, zAffinity[0], encoding);
96440    if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
96441      /* When applying REAL affinity, if the result is still an MEM_Int
96442      ** that will fit in 6 bytes, then change the type to MEM_IntReal
96443      ** so that we keep the high-resolution integer value but know that
96444      ** the type really wants to be REAL. */
96445      testcase( pIn1->u.i==140737488355328LL );
96446      testcase( pIn1->u.i==140737488355327LL );
96447      testcase( pIn1->u.i==-140737488355328LL );
96448      testcase( pIn1->u.i==-140737488355329LL );
96449      if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
96450        pIn1->flags |= MEM_IntReal;
96451        pIn1->flags &= ~MEM_Int;
96452      }else{
96453        pIn1->u.r = (double)pIn1->u.i;
96454        pIn1->flags |= MEM_Real;
96455        pIn1->flags &= ~(MEM_Int|MEM_Str);
96456      }
96457    }
96458    REGISTER_TRACE((int)(pIn1-aMem), pIn1);
96459    zAffinity++;
96460    if( zAffinity[0]==0 ) break;
96461    pIn1++;
96462  }
96463  break;
96464}
96465
96466/* Opcode: MakeRecord P1 P2 P3 P4 *
96467** Synopsis: r[P3]=mkrec(r[P1@P2])
96468**
96469** Convert P2 registers beginning with P1 into the [record format]
96470** use as a data record in a database table or as a key
96471** in an index.  The OP_Column opcode can decode the record later.
96472**
96473** P4 may be a string that is P2 characters long.  The N-th character of the
96474** string indicates the column affinity that should be used for the N-th
96475** field of the index key.
96476**
96477** The mapping from character to affinity is given by the SQLITE_AFF_
96478** macros defined in sqliteInt.h.
96479**
96480** If P4 is NULL then all index fields have the affinity BLOB.
96481**
96482** The meaning of P5 depends on whether or not the SQLITE_ENABLE_NULL_TRIM
96483** compile-time option is enabled:
96484**
96485**   * If SQLITE_ENABLE_NULL_TRIM is enabled, then the P5 is the index
96486**     of the right-most table that can be null-trimmed.
96487**
96488**   * If SQLITE_ENABLE_NULL_TRIM is omitted, then P5 has the value
96489**     OPFLAG_NOCHNG_MAGIC if the OP_MakeRecord opcode is allowed to
96490**     accept no-change records with serial_type 10.  This value is
96491**     only used inside an assert() and does not affect the end result.
96492*/
96493case OP_MakeRecord: {
96494  Mem *pRec;             /* The new record */
96495  u64 nData;             /* Number of bytes of data space */
96496  int nHdr;              /* Number of bytes of header space */
96497  i64 nByte;             /* Data space required for this record */
96498  i64 nZero;             /* Number of zero bytes at the end of the record */
96499  int nVarint;           /* Number of bytes in a varint */
96500  u32 serial_type;       /* Type field */
96501  Mem *pData0;           /* First field to be combined into the record */
96502  Mem *pLast;            /* Last field of the record */
96503  int nField;            /* Number of fields in the record */
96504  char *zAffinity;       /* The affinity string for the record */
96505  u32 len;               /* Length of a field */
96506  u8 *zHdr;              /* Where to write next byte of the header */
96507  u8 *zPayload;          /* Where to write next byte of the payload */
96508
96509  /* Assuming the record contains N fields, the record format looks
96510  ** like this:
96511  **
96512  ** ------------------------------------------------------------------------
96513  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
96514  ** ------------------------------------------------------------------------
96515  **
96516  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
96517  ** and so forth.
96518  **
96519  ** Each type field is a varint representing the serial type of the
96520  ** corresponding data element (see sqlite3VdbeSerialType()). The
96521  ** hdr-size field is also a varint which is the offset from the beginning
96522  ** of the record to data0.
96523  */
96524  nData = 0;         /* Number of bytes of data space */
96525  nHdr = 0;          /* Number of bytes of header space */
96526  nZero = 0;         /* Number of zero bytes at the end of the record */
96527  nField = pOp->p1;
96528  zAffinity = pOp->p4.z;
96529  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
96530  pData0 = &aMem[nField];
96531  nField = pOp->p2;
96532  pLast = &pData0[nField-1];
96533
96534  /* Identify the output register */
96535  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
96536  pOut = &aMem[pOp->p3];
96537  memAboutToChange(p, pOut);
96538
96539  /* Apply the requested affinity to all inputs
96540  */
96541  assert( pData0<=pLast );
96542  if( zAffinity ){
96543    pRec = pData0;
96544    do{
96545      applyAffinity(pRec, zAffinity[0], encoding);
96546      if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
96547        pRec->flags |= MEM_IntReal;
96548        pRec->flags &= ~(MEM_Int);
96549      }
96550      REGISTER_TRACE((int)(pRec-aMem), pRec);
96551      zAffinity++;
96552      pRec++;
96553      assert( zAffinity[0]==0 || pRec<=pLast );
96554    }while( zAffinity[0] );
96555  }
96556
96557#ifdef SQLITE_ENABLE_NULL_TRIM
96558  /* NULLs can be safely trimmed from the end of the record, as long as
96559  ** as the schema format is 2 or more and none of the omitted columns
96560  ** have a non-NULL default value.  Also, the record must be left with
96561  ** at least one field.  If P5>0 then it will be one more than the
96562  ** index of the right-most column with a non-NULL default value */
96563  if( pOp->p5 ){
96564    while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
96565      pLast--;
96566      nField--;
96567    }
96568  }
96569#endif
96570
96571  /* Loop through the elements that will make up the record to figure
96572  ** out how much space is required for the new record.  After this loop,
96573  ** the Mem.uTemp field of each term should hold the serial-type that will
96574  ** be used for that term in the generated record:
96575  **
96576  **   Mem.uTemp value    type
96577  **   ---------------    ---------------
96578  **      0               NULL
96579  **      1               1-byte signed integer
96580  **      2               2-byte signed integer
96581  **      3               3-byte signed integer
96582  **      4               4-byte signed integer
96583  **      5               6-byte signed integer
96584  **      6               8-byte signed integer
96585  **      7               IEEE float
96586  **      8               Integer constant 0
96587  **      9               Integer constant 1
96588  **     10,11            reserved for expansion
96589  **    N>=12 and even    BLOB
96590  **    N>=13 and odd     text
96591  **
96592  ** The following additional values are computed:
96593  **     nHdr        Number of bytes needed for the record header
96594  **     nData       Number of bytes of data space needed for the record
96595  **     nZero       Zero bytes at the end of the record
96596  */
96597  pRec = pLast;
96598  do{
96599    assert( memIsValid(pRec) );
96600    if( pRec->flags & MEM_Null ){
96601      if( pRec->flags & MEM_Zero ){
96602        /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
96603        ** table methods that never invoke sqlite3_result_xxxxx() while
96604        ** computing an unchanging column value in an UPDATE statement.
96605        ** Give such values a special internal-use-only serial-type of 10
96606        ** so that they can be passed through to xUpdate and have
96607        ** a true sqlite3_value_nochange(). */
96608#ifndef SQLITE_ENABLE_NULL_TRIM
96609        assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
96610#endif
96611        pRec->uTemp = 10;
96612      }else{
96613        pRec->uTemp = 0;
96614      }
96615      nHdr++;
96616    }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){
96617      /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
96618      i64 i = pRec->u.i;
96619      u64 uu;
96620      testcase( pRec->flags & MEM_Int );
96621      testcase( pRec->flags & MEM_IntReal );
96622      if( i<0 ){
96623        uu = ~i;
96624      }else{
96625        uu = i;
96626      }
96627      nHdr++;
96628      testcase( uu==127 );               testcase( uu==128 );
96629      testcase( uu==32767 );             testcase( uu==32768 );
96630      testcase( uu==8388607 );           testcase( uu==8388608 );
96631      testcase( uu==2147483647 );        testcase( uu==2147483648LL );
96632      testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL );
96633      if( uu<=127 ){
96634        if( (i&1)==i && p->minWriteFileFormat>=4 ){
96635          pRec->uTemp = 8+(u32)uu;
96636        }else{
96637          nData++;
96638          pRec->uTemp = 1;
96639        }
96640      }else if( uu<=32767 ){
96641        nData += 2;
96642        pRec->uTemp = 2;
96643      }else if( uu<=8388607 ){
96644        nData += 3;
96645        pRec->uTemp = 3;
96646      }else if( uu<=2147483647 ){
96647        nData += 4;
96648        pRec->uTemp = 4;
96649      }else if( uu<=140737488355327LL ){
96650        nData += 6;
96651        pRec->uTemp = 5;
96652      }else{
96653        nData += 8;
96654        if( pRec->flags & MEM_IntReal ){
96655          /* If the value is IntReal and is going to take up 8 bytes to store
96656          ** as an integer, then we might as well make it an 8-byte floating
96657          ** point value */
96658          pRec->u.r = (double)pRec->u.i;
96659          pRec->flags &= ~MEM_IntReal;
96660          pRec->flags |= MEM_Real;
96661          pRec->uTemp = 7;
96662        }else{
96663          pRec->uTemp = 6;
96664        }
96665      }
96666    }else if( pRec->flags & MEM_Real ){
96667      nHdr++;
96668      nData += 8;
96669      pRec->uTemp = 7;
96670    }else{
96671      assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
96672      assert( pRec->n>=0 );
96673      len = (u32)pRec->n;
96674      serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
96675      if( pRec->flags & MEM_Zero ){
96676        serial_type += pRec->u.nZero*2;
96677        if( nData ){
96678          if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
96679          len += pRec->u.nZero;
96680        }else{
96681          nZero += pRec->u.nZero;
96682        }
96683      }
96684      nData += len;
96685      nHdr += sqlite3VarintLen(serial_type);
96686      pRec->uTemp = serial_type;
96687    }
96688    if( pRec==pData0 ) break;
96689    pRec--;
96690  }while(1);
96691
96692  /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
96693  ** which determines the total number of bytes in the header. The varint
96694  ** value is the size of the header in bytes including the size varint
96695  ** itself. */
96696  testcase( nHdr==126 );
96697  testcase( nHdr==127 );
96698  if( nHdr<=126 ){
96699    /* The common case */
96700    nHdr += 1;
96701  }else{
96702    /* Rare case of a really large header */
96703    nVarint = sqlite3VarintLen(nHdr);
96704    nHdr += nVarint;
96705    if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
96706  }
96707  nByte = nHdr+nData;
96708
96709  /* Make sure the output register has a buffer large enough to store
96710  ** the new record. The output register (pOp->p3) is not allowed to
96711  ** be one of the input registers (because the following call to
96712  ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
96713  */
96714  if( nByte+nZero<=pOut->szMalloc ){
96715    /* The output register is already large enough to hold the record.
96716    ** No error checks or buffer enlargement is required */
96717    pOut->z = pOut->zMalloc;
96718  }else{
96719    /* Need to make sure that the output is not too big and then enlarge
96720    ** the output register to hold the full result */
96721    if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
96722      goto too_big;
96723    }
96724    if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
96725      goto no_mem;
96726    }
96727  }
96728  pOut->n = (int)nByte;
96729  pOut->flags = MEM_Blob;
96730  if( nZero ){
96731    pOut->u.nZero = nZero;
96732    pOut->flags |= MEM_Zero;
96733  }
96734  UPDATE_MAX_BLOBSIZE(pOut);
96735  zHdr = (u8 *)pOut->z;
96736  zPayload = zHdr + nHdr;
96737
96738  /* Write the record */
96739  if( nHdr<0x80 ){
96740    *(zHdr++) = nHdr;
96741  }else{
96742    zHdr += sqlite3PutVarint(zHdr,nHdr);
96743  }
96744  assert( pData0<=pLast );
96745  pRec = pData0;
96746  while( 1 /*exit-by-break*/ ){
96747    serial_type = pRec->uTemp;
96748    /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
96749    ** additional varints, one per column.
96750    ** EVIDENCE-OF: R-64536-51728 The values for each column in the record
96751    ** immediately follow the header. */
96752    if( serial_type<=7 ){
96753      *(zHdr++) = serial_type;
96754      if( serial_type==0 ){
96755        /* NULL value.  No change in zPayload */
96756      }else{
96757        u64 v;
96758        if( serial_type==7 ){
96759          assert( sizeof(v)==sizeof(pRec->u.r) );
96760          memcpy(&v, &pRec->u.r, sizeof(v));
96761          swapMixedEndianFloat(v);
96762        }else{
96763          v = pRec->u.i;
96764        }
96765        len = sqlite3SmallTypeSizes[serial_type];
96766        assert( len>=1 && len<=8 && len!=5 && len!=7 );
96767        switch( len ){
96768          default: zPayload[7] = (u8)(v&0xff); v >>= 8;
96769                   zPayload[6] = (u8)(v&0xff); v >>= 8;
96770                   /* no break */ deliberate_fall_through
96771          case 6:  zPayload[5] = (u8)(v&0xff); v >>= 8;
96772                   zPayload[4] = (u8)(v&0xff); v >>= 8;
96773                   /* no break */ deliberate_fall_through
96774          case 4:  zPayload[3] = (u8)(v&0xff); v >>= 8;
96775                   /* no break */ deliberate_fall_through
96776          case 3:  zPayload[2] = (u8)(v&0xff); v >>= 8;
96777                   /* no break */ deliberate_fall_through
96778          case 2:  zPayload[1] = (u8)(v&0xff); v >>= 8;
96779                   /* no break */ deliberate_fall_through
96780          case 1:  zPayload[0] = (u8)(v&0xff);
96781        }
96782        zPayload += len;
96783      }
96784    }else if( serial_type<0x80 ){
96785      *(zHdr++) = serial_type;
96786      if( serial_type>=14 && pRec->n>0 ){
96787        assert( pRec->z!=0 );
96788        memcpy(zPayload, pRec->z, pRec->n);
96789        zPayload += pRec->n;
96790      }
96791    }else{
96792      zHdr += sqlite3PutVarint(zHdr, serial_type);
96793      if( pRec->n ){
96794        assert( pRec->z!=0 );
96795        memcpy(zPayload, pRec->z, pRec->n);
96796        zPayload += pRec->n;
96797      }
96798    }
96799    if( pRec==pLast ) break;
96800    pRec++;
96801  }
96802  assert( nHdr==(int)(zHdr - (u8*)pOut->z) );
96803  assert( nByte==(int)(zPayload - (u8*)pOut->z) );
96804
96805  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
96806  REGISTER_TRACE(pOp->p3, pOut);
96807  break;
96808}
96809
96810/* Opcode: Count P1 P2 P3 * *
96811** Synopsis: r[P2]=count()
96812**
96813** Store the number of entries (an integer value) in the table or index
96814** opened by cursor P1 in register P2.
96815**
96816** If P3==0, then an exact count is obtained, which involves visiting
96817** every btree page of the table.  But if P3 is non-zero, an estimate
96818** is returned based on the current cursor position.
96819*/
96820case OP_Count: {         /* out2 */
96821  i64 nEntry;
96822  BtCursor *pCrsr;
96823
96824  assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
96825  pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
96826  assert( pCrsr );
96827  if( pOp->p3 ){
96828    nEntry = sqlite3BtreeRowCountEst(pCrsr);
96829  }else{
96830    nEntry = 0;  /* Not needed.  Only used to silence a warning. */
96831    rc = sqlite3BtreeCount(db, pCrsr, &nEntry);
96832    if( rc ) goto abort_due_to_error;
96833  }
96834  pOut = out2Prerelease(p, pOp);
96835  pOut->u.i = nEntry;
96836  goto check_for_interrupt;
96837}
96838
96839/* Opcode: Savepoint P1 * * P4 *
96840**
96841** Open, release or rollback the savepoint named by parameter P4, depending
96842** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN).
96843** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).
96844** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).
96845*/
96846case OP_Savepoint: {
96847  int p1;                         /* Value of P1 operand */
96848  char *zName;                    /* Name of savepoint */
96849  int nName;
96850  Savepoint *pNew;
96851  Savepoint *pSavepoint;
96852  Savepoint *pTmp;
96853  int iSavepoint;
96854  int ii;
96855
96856  p1 = pOp->p1;
96857  zName = pOp->p4.z;
96858
96859  /* Assert that the p1 parameter is valid. Also that if there is no open
96860  ** transaction, then there cannot be any savepoints.
96861  */
96862  assert( db->pSavepoint==0 || db->autoCommit==0 );
96863  assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
96864  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
96865  assert( checkSavepointCount(db) );
96866  assert( p->bIsReader );
96867
96868  if( p1==SAVEPOINT_BEGIN ){
96869    if( db->nVdbeWrite>0 ){
96870      /* A new savepoint cannot be created if there are active write
96871      ** statements (i.e. open read/write incremental blob handles).
96872      */
96873      sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
96874      rc = SQLITE_BUSY;
96875    }else{
96876      nName = sqlite3Strlen30(zName);
96877
96878#ifndef SQLITE_OMIT_VIRTUALTABLE
96879      /* This call is Ok even if this savepoint is actually a transaction
96880      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
96881      ** If this is a transaction savepoint being opened, it is guaranteed
96882      ** that the db->aVTrans[] array is empty.  */
96883      assert( db->autoCommit==0 || db->nVTrans==0 );
96884      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
96885                                db->nStatement+db->nSavepoint);
96886      if( rc!=SQLITE_OK ) goto abort_due_to_error;
96887#endif
96888
96889      /* Create a new savepoint structure. */
96890      pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
96891      if( pNew ){
96892        pNew->zName = (char *)&pNew[1];
96893        memcpy(pNew->zName, zName, nName+1);
96894
96895        /* If there is no open transaction, then mark this as a special
96896        ** "transaction savepoint". */
96897        if( db->autoCommit ){
96898          db->autoCommit = 0;
96899          db->isTransactionSavepoint = 1;
96900        }else{
96901          db->nSavepoint++;
96902        }
96903
96904        /* Link the new savepoint into the database handle's list. */
96905        pNew->pNext = db->pSavepoint;
96906        db->pSavepoint = pNew;
96907        pNew->nDeferredCons = db->nDeferredCons;
96908        pNew->nDeferredImmCons = db->nDeferredImmCons;
96909      }
96910    }
96911  }else{
96912    assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK );
96913    iSavepoint = 0;
96914
96915    /* Find the named savepoint. If there is no such savepoint, then an
96916    ** an error is returned to the user.  */
96917    for(
96918      pSavepoint = db->pSavepoint;
96919      pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
96920      pSavepoint = pSavepoint->pNext
96921    ){
96922      iSavepoint++;
96923    }
96924    if( !pSavepoint ){
96925      sqlite3VdbeError(p, "no such savepoint: %s", zName);
96926      rc = SQLITE_ERROR;
96927    }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
96928      /* It is not possible to release (commit) a savepoint if there are
96929      ** active write statements.
96930      */
96931      sqlite3VdbeError(p, "cannot release savepoint - "
96932                          "SQL statements in progress");
96933      rc = SQLITE_BUSY;
96934    }else{
96935
96936      /* Determine whether or not this is a transaction savepoint. If so,
96937      ** and this is a RELEASE command, then the current transaction
96938      ** is committed.
96939      */
96940      int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
96941      if( isTransaction && p1==SAVEPOINT_RELEASE ){
96942        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
96943          goto vdbe_return;
96944        }
96945        db->autoCommit = 1;
96946        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
96947          p->pc = (int)(pOp - aOp);
96948          db->autoCommit = 0;
96949          p->rc = rc = SQLITE_BUSY;
96950          goto vdbe_return;
96951        }
96952        rc = p->rc;
96953        if( rc ){
96954          db->autoCommit = 0;
96955        }else{
96956          db->isTransactionSavepoint = 0;
96957        }
96958      }else{
96959        int isSchemaChange;
96960        iSavepoint = db->nSavepoint - iSavepoint - 1;
96961        if( p1==SAVEPOINT_ROLLBACK ){
96962          isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
96963          for(ii=0; ii<db->nDb; ii++){
96964            rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
96965                                       SQLITE_ABORT_ROLLBACK,
96966                                       isSchemaChange==0);
96967            if( rc!=SQLITE_OK ) goto abort_due_to_error;
96968          }
96969        }else{
96970          assert( p1==SAVEPOINT_RELEASE );
96971          isSchemaChange = 0;
96972        }
96973        for(ii=0; ii<db->nDb; ii++){
96974          rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
96975          if( rc!=SQLITE_OK ){
96976            goto abort_due_to_error;
96977          }
96978        }
96979        if( isSchemaChange ){
96980          sqlite3ExpirePreparedStatements(db, 0);
96981          sqlite3ResetAllSchemasOfConnection(db);
96982          db->mDbFlags |= DBFLAG_SchemaChange;
96983        }
96984      }
96985      if( rc ) goto abort_due_to_error;
96986
96987      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
96988      ** savepoints nested inside of the savepoint being operated on. */
96989      while( db->pSavepoint!=pSavepoint ){
96990        pTmp = db->pSavepoint;
96991        db->pSavepoint = pTmp->pNext;
96992        sqlite3DbFree(db, pTmp);
96993        db->nSavepoint--;
96994      }
96995
96996      /* If it is a RELEASE, then destroy the savepoint being operated on
96997      ** too. If it is a ROLLBACK TO, then set the number of deferred
96998      ** constraint violations present in the database to the value stored
96999      ** when the savepoint was created.  */
97000      if( p1==SAVEPOINT_RELEASE ){
97001        assert( pSavepoint==db->pSavepoint );
97002        db->pSavepoint = pSavepoint->pNext;
97003        sqlite3DbFree(db, pSavepoint);
97004        if( !isTransaction ){
97005          db->nSavepoint--;
97006        }
97007      }else{
97008        assert( p1==SAVEPOINT_ROLLBACK );
97009        db->nDeferredCons = pSavepoint->nDeferredCons;
97010        db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
97011      }
97012
97013      if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
97014        rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
97015        if( rc!=SQLITE_OK ) goto abort_due_to_error;
97016      }
97017    }
97018  }
97019  if( rc ) goto abort_due_to_error;
97020  if( p->eVdbeState==VDBE_HALT_STATE ){
97021    rc = SQLITE_DONE;
97022    goto vdbe_return;
97023  }
97024  break;
97025}
97026
97027/* Opcode: AutoCommit P1 P2 * * *
97028**
97029** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
97030** back any currently active btree transactions. If there are any active
97031** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
97032** there are active writing VMs or active VMs that use shared cache.
97033**
97034** This instruction causes the VM to halt.
97035*/
97036case OP_AutoCommit: {
97037  int desiredAutoCommit;
97038  int iRollback;
97039
97040  desiredAutoCommit = pOp->p1;
97041  iRollback = pOp->p2;
97042  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
97043  assert( desiredAutoCommit==1 || iRollback==0 );
97044  assert( db->nVdbeActive>0 );  /* At least this one VM is active */
97045  assert( p->bIsReader );
97046
97047  if( desiredAutoCommit!=db->autoCommit ){
97048    if( iRollback ){
97049      assert( desiredAutoCommit==1 );
97050      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
97051      db->autoCommit = 1;
97052    }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
97053      /* If this instruction implements a COMMIT and other VMs are writing
97054      ** return an error indicating that the other VMs must complete first.
97055      */
97056      sqlite3VdbeError(p, "cannot commit transaction - "
97057                          "SQL statements in progress");
97058      rc = SQLITE_BUSY;
97059      goto abort_due_to_error;
97060    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
97061      goto vdbe_return;
97062    }else{
97063      db->autoCommit = (u8)desiredAutoCommit;
97064    }
97065    if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
97066      p->pc = (int)(pOp - aOp);
97067      db->autoCommit = (u8)(1-desiredAutoCommit);
97068      p->rc = rc = SQLITE_BUSY;
97069      goto vdbe_return;
97070    }
97071    sqlite3CloseSavepoints(db);
97072    if( p->rc==SQLITE_OK ){
97073      rc = SQLITE_DONE;
97074    }else{
97075      rc = SQLITE_ERROR;
97076    }
97077    goto vdbe_return;
97078  }else{
97079    sqlite3VdbeError(p,
97080        (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
97081        (iRollback)?"cannot rollback - no transaction is active":
97082                   "cannot commit - no transaction is active"));
97083
97084    rc = SQLITE_ERROR;
97085    goto abort_due_to_error;
97086  }
97087  /*NOTREACHED*/ assert(0);
97088}
97089
97090/* Opcode: Transaction P1 P2 P3 P4 P5
97091**
97092** Begin a transaction on database P1 if a transaction is not already
97093** active.
97094** If P2 is non-zero, then a write-transaction is started, or if a
97095** read-transaction is already active, it is upgraded to a write-transaction.
97096** If P2 is zero, then a read-transaction is started.  If P2 is 2 or more
97097** then an exclusive transaction is started.
97098**
97099** P1 is the index of the database file on which the transaction is
97100** started.  Index 0 is the main database file and index 1 is the
97101** file used for temporary tables.  Indices of 2 or more are used for
97102** attached databases.
97103**
97104** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
97105** true (this flag is set if the Vdbe may modify more than one row and may
97106** throw an ABORT exception), a statement transaction may also be opened.
97107** More specifically, a statement transaction is opened iff the database
97108** connection is currently not in autocommit mode, or if there are other
97109** active statements. A statement transaction allows the changes made by this
97110** VDBE to be rolled back after an error without having to roll back the
97111** entire transaction. If no error is encountered, the statement transaction
97112** will automatically commit when the VDBE halts.
97113**
97114** If P5!=0 then this opcode also checks the schema cookie against P3
97115** and the schema generation counter against P4.
97116** The cookie changes its value whenever the database schema changes.
97117** This operation is used to detect when that the cookie has changed
97118** and that the current process needs to reread the schema.  If the schema
97119** cookie in P3 differs from the schema cookie in the database header or
97120** if the schema generation counter in P4 differs from the current
97121** generation counter, then an SQLITE_SCHEMA error is raised and execution
97122** halts.  The sqlite3_step() wrapper function might then reprepare the
97123** statement and rerun it from the beginning.
97124*/
97125case OP_Transaction: {
97126  Btree *pBt;
97127  Db *pDb;
97128  int iMeta = 0;
97129
97130  assert( p->bIsReader );
97131  assert( p->readOnly==0 || pOp->p2==0 );
97132  assert( pOp->p2>=0 && pOp->p2<=2 );
97133  assert( pOp->p1>=0 && pOp->p1<db->nDb );
97134  assert( DbMaskTest(p->btreeMask, pOp->p1) );
97135  assert( rc==SQLITE_OK );
97136  if( pOp->p2 && (db->flags & (SQLITE_QueryOnly|SQLITE_CorruptRdOnly))!=0 ){
97137    if( db->flags & SQLITE_QueryOnly ){
97138      /* Writes prohibited by the "PRAGMA query_only=TRUE" statement */
97139      rc = SQLITE_READONLY;
97140    }else{
97141      /* Writes prohibited due to a prior SQLITE_CORRUPT in the current
97142      ** transaction */
97143      rc = SQLITE_CORRUPT;
97144    }
97145    goto abort_due_to_error;
97146  }
97147  pDb = &db->aDb[pOp->p1];
97148  pBt = pDb->pBt;
97149
97150  if( pBt ){
97151    rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
97152    testcase( rc==SQLITE_BUSY_SNAPSHOT );
97153    testcase( rc==SQLITE_BUSY_RECOVERY );
97154    if( rc!=SQLITE_OK ){
97155      if( (rc&0xff)==SQLITE_BUSY ){
97156        p->pc = (int)(pOp - aOp);
97157        p->rc = rc;
97158        goto vdbe_return;
97159      }
97160      goto abort_due_to_error;
97161    }
97162
97163    if( p->usesStmtJournal
97164     && pOp->p2
97165     && (db->autoCommit==0 || db->nVdbeRead>1)
97166    ){
97167      assert( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE );
97168      if( p->iStatement==0 ){
97169        assert( db->nStatement>=0 && db->nSavepoint>=0 );
97170        db->nStatement++;
97171        p->iStatement = db->nSavepoint + db->nStatement;
97172      }
97173
97174      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
97175      if( rc==SQLITE_OK ){
97176        rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
97177      }
97178
97179      /* Store the current value of the database handles deferred constraint
97180      ** counter. If the statement transaction needs to be rolled back,
97181      ** the value of this counter needs to be restored too.  */
97182      p->nStmtDefCons = db->nDeferredCons;
97183      p->nStmtDefImmCons = db->nDeferredImmCons;
97184    }
97185  }
97186  assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
97187  if( rc==SQLITE_OK
97188   && pOp->p5
97189   && (iMeta!=pOp->p3 || pDb->pSchema->iGeneration!=pOp->p4.i)
97190  ){
97191    /*
97192    ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
97193    ** version is checked to ensure that the schema has not changed since the
97194    ** SQL statement was prepared.
97195    */
97196    sqlite3DbFree(db, p->zErrMsg);
97197    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
97198    /* If the schema-cookie from the database file matches the cookie
97199    ** stored with the in-memory representation of the schema, do
97200    ** not reload the schema from the database file.
97201    **
97202    ** If virtual-tables are in use, this is not just an optimization.
97203    ** Often, v-tables store their data in other SQLite tables, which
97204    ** are queried from within xNext() and other v-table methods using
97205    ** prepared queries. If such a query is out-of-date, we do not want to
97206    ** discard the database schema, as the user code implementing the
97207    ** v-table would have to be ready for the sqlite3_vtab structure itself
97208    ** to be invalidated whenever sqlite3_step() is called from within
97209    ** a v-table method.
97210    */
97211    if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
97212      sqlite3ResetOneSchema(db, pOp->p1);
97213    }
97214    p->expired = 1;
97215    rc = SQLITE_SCHEMA;
97216
97217    /* Set changeCntOn to 0 to prevent the value returned by sqlite3_changes()
97218    ** from being modified in sqlite3VdbeHalt(). If this statement is
97219    ** reprepared, changeCntOn will be set again. */
97220    p->changeCntOn = 0;
97221  }
97222  if( rc ) goto abort_due_to_error;
97223  break;
97224}
97225
97226/* Opcode: ReadCookie P1 P2 P3 * *
97227**
97228** Read cookie number P3 from database P1 and write it into register P2.
97229** P3==1 is the schema version.  P3==2 is the database format.
97230** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
97231** the main database file and P1==1 is the database file used to store
97232** temporary tables.
97233**
97234** There must be a read-lock on the database (either a transaction
97235** must be started or there must be an open cursor) before
97236** executing this instruction.
97237*/
97238case OP_ReadCookie: {               /* out2 */
97239  int iMeta;
97240  int iDb;
97241  int iCookie;
97242
97243  assert( p->bIsReader );
97244  iDb = pOp->p1;
97245  iCookie = pOp->p3;
97246  assert( pOp->p3<SQLITE_N_BTREE_META );
97247  assert( iDb>=0 && iDb<db->nDb );
97248  assert( db->aDb[iDb].pBt!=0 );
97249  assert( DbMaskTest(p->btreeMask, iDb) );
97250
97251  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
97252  pOut = out2Prerelease(p, pOp);
97253  pOut->u.i = iMeta;
97254  break;
97255}
97256
97257/* Opcode: SetCookie P1 P2 P3 * P5
97258**
97259** Write the integer value P3 into cookie number P2 of database P1.
97260** P2==1 is the schema version.  P2==2 is the database format.
97261** P2==3 is the recommended pager cache
97262** size, and so forth.  P1==0 is the main database file and P1==1 is the
97263** database file used to store temporary tables.
97264**
97265** A transaction must be started before executing this opcode.
97266**
97267** If P2 is the SCHEMA_VERSION cookie (cookie number 1) then the internal
97268** schema version is set to P3-P5.  The "PRAGMA schema_version=N" statement
97269** has P5 set to 1, so that the internal schema version will be different
97270** from the database schema version, resulting in a schema reset.
97271*/
97272case OP_SetCookie: {
97273  Db *pDb;
97274
97275  sqlite3VdbeIncrWriteCounter(p, 0);
97276  assert( pOp->p2<SQLITE_N_BTREE_META );
97277  assert( pOp->p1>=0 && pOp->p1<db->nDb );
97278  assert( DbMaskTest(p->btreeMask, pOp->p1) );
97279  assert( p->readOnly==0 );
97280  pDb = &db->aDb[pOp->p1];
97281  assert( pDb->pBt!=0 );
97282  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
97283  /* See note about index shifting on OP_ReadCookie */
97284  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
97285  if( pOp->p2==BTREE_SCHEMA_VERSION ){
97286    /* When the schema cookie changes, record the new cookie internally */
97287    *(u32*)&pDb->pSchema->schema_cookie = *(u32*)&pOp->p3 - pOp->p5;
97288    db->mDbFlags |= DBFLAG_SchemaChange;
97289    sqlite3FkClearTriggerCache(db, pOp->p1);
97290  }else if( pOp->p2==BTREE_FILE_FORMAT ){
97291    /* Record changes in the file format */
97292    pDb->pSchema->file_format = pOp->p3;
97293  }
97294  if( pOp->p1==1 ){
97295    /* Invalidate all prepared statements whenever the TEMP database
97296    ** schema is changed.  Ticket #1644 */
97297    sqlite3ExpirePreparedStatements(db, 0);
97298    p->expired = 0;
97299  }
97300  if( rc ) goto abort_due_to_error;
97301  break;
97302}
97303
97304/* Opcode: OpenRead P1 P2 P3 P4 P5
97305** Synopsis: root=P2 iDb=P3
97306**
97307** Open a read-only cursor for the database table whose root page is
97308** P2 in a database file.  The database file is determined by P3.
97309** P3==0 means the main database, P3==1 means the database used for
97310** temporary tables, and P3>1 means used the corresponding attached
97311** database.  Give the new cursor an identifier of P1.  The P1
97312** values need not be contiguous but all P1 values should be small integers.
97313** It is an error for P1 to be negative.
97314**
97315** Allowed P5 bits:
97316** <ul>
97317** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
97318**       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
97319**       of OP_SeekLE/OP_IdxLT)
97320** </ul>
97321**
97322** The P4 value may be either an integer (P4_INT32) or a pointer to
97323** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
97324** object, then table being opened must be an [index b-tree] where the
97325** KeyInfo object defines the content and collating
97326** sequence of that index b-tree. Otherwise, if P4 is an integer
97327** value, then the table being opened must be a [table b-tree] with a
97328** number of columns no less than the value of P4.
97329**
97330** See also: OpenWrite, ReopenIdx
97331*/
97332/* Opcode: ReopenIdx P1 P2 P3 P4 P5
97333** Synopsis: root=P2 iDb=P3
97334**
97335** The ReopenIdx opcode works like OP_OpenRead except that it first
97336** checks to see if the cursor on P1 is already open on the same
97337** b-tree and if it is this opcode becomes a no-op.  In other words,
97338** if the cursor is already open, do not reopen it.
97339**
97340** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
97341** and with P4 being a P4_KEYINFO object.  Furthermore, the P3 value must
97342** be the same as every other ReopenIdx or OpenRead for the same cursor
97343** number.
97344**
97345** Allowed P5 bits:
97346** <ul>
97347** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
97348**       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
97349**       of OP_SeekLE/OP_IdxLT)
97350** </ul>
97351**
97352** See also: OP_OpenRead, OP_OpenWrite
97353*/
97354/* Opcode: OpenWrite P1 P2 P3 P4 P5
97355** Synopsis: root=P2 iDb=P3
97356**
97357** Open a read/write cursor named P1 on the table or index whose root
97358** page is P2 (or whose root page is held in register P2 if the
97359** OPFLAG_P2ISREG bit is set in P5 - see below).
97360**
97361** The P4 value may be either an integer (P4_INT32) or a pointer to
97362** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
97363** object, then table being opened must be an [index b-tree] where the
97364** KeyInfo object defines the content and collating
97365** sequence of that index b-tree. Otherwise, if P4 is an integer
97366** value, then the table being opened must be a [table b-tree] with a
97367** number of columns no less than the value of P4.
97368**
97369** Allowed P5 bits:
97370** <ul>
97371** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
97372**       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
97373**       of OP_SeekLE/OP_IdxLT)
97374** <li>  <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
97375**       and subsequently delete entries in an index btree.  This is a
97376**       hint to the storage engine that the storage engine is allowed to
97377**       ignore.  The hint is not used by the official SQLite b*tree storage
97378**       engine, but is used by COMDB2.
97379** <li>  <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
97380**       as the root page, not the value of P2 itself.
97381** </ul>
97382**
97383** This instruction works like OpenRead except that it opens the cursor
97384** in read/write mode.
97385**
97386** See also: OP_OpenRead, OP_ReopenIdx
97387*/
97388case OP_ReopenIdx: {         /* ncycle */
97389  int nField;
97390  KeyInfo *pKeyInfo;
97391  u32 p2;
97392  int iDb;
97393  int wrFlag;
97394  Btree *pX;
97395  VdbeCursor *pCur;
97396  Db *pDb;
97397
97398  assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
97399  assert( pOp->p4type==P4_KEYINFO );
97400  pCur = p->apCsr[pOp->p1];
97401  if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
97402    assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
97403    assert( pCur->eCurType==CURTYPE_BTREE );
97404    sqlite3BtreeClearCursor(pCur->uc.pCursor);
97405    goto open_cursor_set_hints;
97406  }
97407  /* If the cursor is not currently open or is open on a different
97408  ** index, then fall through into OP_OpenRead to force a reopen */
97409case OP_OpenRead:            /* ncycle */
97410case OP_OpenWrite:
97411
97412  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
97413  assert( p->bIsReader );
97414  assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
97415          || p->readOnly==0 );
97416
97417  if( p->expired==1 ){
97418    rc = SQLITE_ABORT_ROLLBACK;
97419    goto abort_due_to_error;
97420  }
97421
97422  nField = 0;
97423  pKeyInfo = 0;
97424  p2 = (u32)pOp->p2;
97425  iDb = pOp->p3;
97426  assert( iDb>=0 && iDb<db->nDb );
97427  assert( DbMaskTest(p->btreeMask, iDb) );
97428  pDb = &db->aDb[iDb];
97429  pX = pDb->pBt;
97430  assert( pX!=0 );
97431  if( pOp->opcode==OP_OpenWrite ){
97432    assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
97433    wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
97434    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97435    if( pDb->pSchema->file_format < p->minWriteFileFormat ){
97436      p->minWriteFileFormat = pDb->pSchema->file_format;
97437    }
97438  }else{
97439    wrFlag = 0;
97440  }
97441  if( pOp->p5 & OPFLAG_P2ISREG ){
97442    assert( p2>0 );
97443    assert( p2<=(u32)(p->nMem+1 - p->nCursor) );
97444    assert( pOp->opcode==OP_OpenWrite );
97445    pIn2 = &aMem[p2];
97446    assert( memIsValid(pIn2) );
97447    assert( (pIn2->flags & MEM_Int)!=0 );
97448    sqlite3VdbeMemIntegerify(pIn2);
97449    p2 = (int)pIn2->u.i;
97450    /* The p2 value always comes from a prior OP_CreateBtree opcode and
97451    ** that opcode will always set the p2 value to 2 or more or else fail.
97452    ** If there were a failure, the prepared statement would have halted
97453    ** before reaching this instruction. */
97454    assert( p2>=2 );
97455  }
97456  if( pOp->p4type==P4_KEYINFO ){
97457    pKeyInfo = pOp->p4.pKeyInfo;
97458    assert( pKeyInfo->enc==ENC(db) );
97459    assert( pKeyInfo->db==db );
97460    nField = pKeyInfo->nAllField;
97461  }else if( pOp->p4type==P4_INT32 ){
97462    nField = pOp->p4.i;
97463  }
97464  assert( pOp->p1>=0 );
97465  assert( nField>=0 );
97466  testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
97467  pCur = allocateCursor(p, pOp->p1, nField, CURTYPE_BTREE);
97468  if( pCur==0 ) goto no_mem;
97469  pCur->iDb = iDb;
97470  pCur->nullRow = 1;
97471  pCur->isOrdered = 1;
97472  pCur->pgnoRoot = p2;
97473#ifdef SQLITE_DEBUG
97474  pCur->wrFlag = wrFlag;
97475#endif
97476  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
97477  pCur->pKeyInfo = pKeyInfo;
97478  /* Set the VdbeCursor.isTable variable. Previous versions of
97479  ** SQLite used to check if the root-page flags were sane at this point
97480  ** and report database corruption if they were not, but this check has
97481  ** since moved into the btree layer.  */
97482  pCur->isTable = pOp->p4type!=P4_KEYINFO;
97483
97484open_cursor_set_hints:
97485  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
97486  assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
97487  testcase( pOp->p5 & OPFLAG_BULKCSR );
97488  testcase( pOp->p2 & OPFLAG_SEEKEQ );
97489  sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
97490                               (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
97491  if( rc ) goto abort_due_to_error;
97492  break;
97493}
97494
97495/* Opcode: OpenDup P1 P2 * * *
97496**
97497** Open a new cursor P1 that points to the same ephemeral table as
97498** cursor P2.  The P2 cursor must have been opened by a prior OP_OpenEphemeral
97499** opcode.  Only ephemeral cursors may be duplicated.
97500**
97501** Duplicate ephemeral cursors are used for self-joins of materialized views.
97502*/
97503case OP_OpenDup: {           /* ncycle */
97504  VdbeCursor *pOrig;    /* The original cursor to be duplicated */
97505  VdbeCursor *pCx;      /* The new cursor */
97506
97507  pOrig = p->apCsr[pOp->p2];
97508  assert( pOrig );
97509  assert( pOrig->isEphemeral );  /* Only ephemeral cursors can be duplicated */
97510
97511  pCx = allocateCursor(p, pOp->p1, pOrig->nField, CURTYPE_BTREE);
97512  if( pCx==0 ) goto no_mem;
97513  pCx->nullRow = 1;
97514  pCx->isEphemeral = 1;
97515  pCx->pKeyInfo = pOrig->pKeyInfo;
97516  pCx->isTable = pOrig->isTable;
97517  pCx->pgnoRoot = pOrig->pgnoRoot;
97518  pCx->isOrdered = pOrig->isOrdered;
97519  pCx->ub.pBtx = pOrig->ub.pBtx;
97520  pCx->noReuse = 1;
97521  pOrig->noReuse = 1;
97522  rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
97523                          pCx->pKeyInfo, pCx->uc.pCursor);
97524  /* The sqlite3BtreeCursor() routine can only fail for the first cursor
97525  ** opened for a database.  Since there is already an open cursor when this
97526  ** opcode is run, the sqlite3BtreeCursor() cannot fail */
97527  assert( rc==SQLITE_OK );
97528  break;
97529}
97530
97531
97532/* Opcode: OpenEphemeral P1 P2 P3 P4 P5
97533** Synopsis: nColumn=P2
97534**
97535** Open a new cursor P1 to a transient table.
97536** The cursor is always opened read/write even if
97537** the main database is read-only.  The ephemeral
97538** table is deleted automatically when the cursor is closed.
97539**
97540** If the cursor P1 is already opened on an ephemeral table, the table
97541** is cleared (all content is erased).
97542**
97543** P2 is the number of columns in the ephemeral table.
97544** The cursor points to a BTree table if P4==0 and to a BTree index
97545** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
97546** that defines the format of keys in the index.
97547**
97548** The P5 parameter can be a mask of the BTREE_* flags defined
97549** in btree.h.  These flags control aspects of the operation of
97550** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
97551** added automatically.
97552**
97553** If P3 is positive, then reg[P3] is modified slightly so that it
97554** can be used as zero-length data for OP_Insert.  This is an optimization
97555** that avoids an extra OP_Blob opcode to initialize that register.
97556*/
97557/* Opcode: OpenAutoindex P1 P2 * P4 *
97558** Synopsis: nColumn=P2
97559**
97560** This opcode works the same as OP_OpenEphemeral.  It has a
97561** different name to distinguish its use.  Tables created using
97562** by this opcode will be used for automatically created transient
97563** indices in joins.
97564*/
97565case OP_OpenAutoindex:       /* ncycle */
97566case OP_OpenEphemeral: {     /* ncycle */
97567  VdbeCursor *pCx;
97568  KeyInfo *pKeyInfo;
97569
97570  static const int vfsFlags =
97571      SQLITE_OPEN_READWRITE |
97572      SQLITE_OPEN_CREATE |
97573      SQLITE_OPEN_EXCLUSIVE |
97574      SQLITE_OPEN_DELETEONCLOSE |
97575      SQLITE_OPEN_TRANSIENT_DB;
97576  assert( pOp->p1>=0 );
97577  assert( pOp->p2>=0 );
97578  if( pOp->p3>0 ){
97579    /* Make register reg[P3] into a value that can be used as the data
97580    ** form sqlite3BtreeInsert() where the length of the data is zero. */
97581    assert( pOp->p2==0 ); /* Only used when number of columns is zero */
97582    assert( pOp->opcode==OP_OpenEphemeral );
97583    assert( aMem[pOp->p3].flags & MEM_Null );
97584    aMem[pOp->p3].n = 0;
97585    aMem[pOp->p3].z = "";
97586  }
97587  pCx = p->apCsr[pOp->p1];
97588  if( pCx && !pCx->noReuse &&  ALWAYS(pOp->p2<=pCx->nField) ){
97589    /* If the ephemeral table is already open and has no duplicates from
97590    ** OP_OpenDup, then erase all existing content so that the table is
97591    ** empty again, rather than creating a new table. */
97592    assert( pCx->isEphemeral );
97593    pCx->seqCount = 0;
97594    pCx->cacheStatus = CACHE_STALE;
97595    rc = sqlite3BtreeClearTable(pCx->ub.pBtx, pCx->pgnoRoot, 0);
97596  }else{
97597    pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_BTREE);
97598    if( pCx==0 ) goto no_mem;
97599    pCx->isEphemeral = 1;
97600    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->ub.pBtx,
97601                          BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
97602                          vfsFlags);
97603    if( rc==SQLITE_OK ){
97604      rc = sqlite3BtreeBeginTrans(pCx->ub.pBtx, 1, 0);
97605      if( rc==SQLITE_OK ){
97606        /* If a transient index is required, create it by calling
97607        ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
97608        ** opening it. If a transient table is required, just use the
97609        ** automatically created table with root-page 1 (an BLOB_INTKEY table).
97610        */
97611        if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
97612          assert( pOp->p4type==P4_KEYINFO );
97613          rc = sqlite3BtreeCreateTable(pCx->ub.pBtx, &pCx->pgnoRoot,
97614              BTREE_BLOBKEY | pOp->p5);
97615          if( rc==SQLITE_OK ){
97616            assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
97617            assert( pKeyInfo->db==db );
97618            assert( pKeyInfo->enc==ENC(db) );
97619            rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
97620                pKeyInfo, pCx->uc.pCursor);
97621          }
97622          pCx->isTable = 0;
97623        }else{
97624          pCx->pgnoRoot = SCHEMA_ROOT;
97625          rc = sqlite3BtreeCursor(pCx->ub.pBtx, SCHEMA_ROOT, BTREE_WRCSR,
97626              0, pCx->uc.pCursor);
97627          pCx->isTable = 1;
97628        }
97629      }
97630      pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
97631      if( rc ){
97632        sqlite3BtreeClose(pCx->ub.pBtx);
97633      }
97634    }
97635  }
97636  if( rc ) goto abort_due_to_error;
97637  pCx->nullRow = 1;
97638  break;
97639}
97640
97641/* Opcode: SorterOpen P1 P2 P3 P4 *
97642**
97643** This opcode works like OP_OpenEphemeral except that it opens
97644** a transient index that is specifically designed to sort large
97645** tables using an external merge-sort algorithm.
97646**
97647** If argument P3 is non-zero, then it indicates that the sorter may
97648** assume that a stable sort considering the first P3 fields of each
97649** key is sufficient to produce the required results.
97650*/
97651case OP_SorterOpen: {
97652  VdbeCursor *pCx;
97653
97654  assert( pOp->p1>=0 );
97655  assert( pOp->p2>=0 );
97656  pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_SORTER);
97657  if( pCx==0 ) goto no_mem;
97658  pCx->pKeyInfo = pOp->p4.pKeyInfo;
97659  assert( pCx->pKeyInfo->db==db );
97660  assert( pCx->pKeyInfo->enc==ENC(db) );
97661  rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
97662  if( rc ) goto abort_due_to_error;
97663  break;
97664}
97665
97666/* Opcode: SequenceTest P1 P2 * * *
97667** Synopsis: if( cursor[P1].ctr++ ) pc = P2
97668**
97669** P1 is a sorter cursor. If the sequence counter is currently zero, jump
97670** to P2. Regardless of whether or not the jump is taken, increment the
97671** the sequence value.
97672*/
97673case OP_SequenceTest: {
97674  VdbeCursor *pC;
97675  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
97676  pC = p->apCsr[pOp->p1];
97677  assert( isSorter(pC) );
97678  if( (pC->seqCount++)==0 ){
97679    goto jump_to_p2;
97680  }
97681  break;
97682}
97683
97684/* Opcode: OpenPseudo P1 P2 P3 * *
97685** Synopsis: P3 columns in r[P2]
97686**
97687** Open a new cursor that points to a fake table that contains a single
97688** row of data.  The content of that one row is the content of memory
97689** register P2.  In other words, cursor P1 becomes an alias for the
97690** MEM_Blob content contained in register P2.
97691**
97692** A pseudo-table created by this opcode is used to hold a single
97693** row output from the sorter so that the row can be decomposed into
97694** individual columns using the OP_Column opcode.  The OP_Column opcode
97695** is the only cursor opcode that works with a pseudo-table.
97696**
97697** P3 is the number of fields in the records that will be stored by
97698** the pseudo-table.  If P2 is 0 or negative then the pseudo-cursor
97699** will return NULL for every column.
97700*/
97701case OP_OpenPseudo: {
97702  VdbeCursor *pCx;
97703
97704  assert( pOp->p1>=0 );
97705  assert( pOp->p3>=0 );
97706  pCx = allocateCursor(p, pOp->p1, pOp->p3, CURTYPE_PSEUDO);
97707  if( pCx==0 ) goto no_mem;
97708  pCx->nullRow = 1;
97709  pCx->seekResult = pOp->p2;
97710  pCx->isTable = 1;
97711  /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
97712  ** can be safely passed to sqlite3VdbeCursorMoveto().  This avoids a test
97713  ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
97714  ** which is a performance optimization */
97715  pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
97716  assert( pOp->p5==0 );
97717  break;
97718}
97719
97720/* Opcode: Close P1 * * * *
97721**
97722** Close a cursor previously opened as P1.  If P1 is not
97723** currently open, this instruction is a no-op.
97724*/
97725case OP_Close: {             /* ncycle */
97726  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
97727  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
97728  p->apCsr[pOp->p1] = 0;
97729  break;
97730}
97731
97732#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
97733/* Opcode: ColumnsUsed P1 * * P4 *
97734**
97735** This opcode (which only exists if SQLite was compiled with
97736** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
97737** table or index for cursor P1 are used.  P4 is a 64-bit integer
97738** (P4_INT64) in which the first 63 bits are one for each of the
97739** first 63 columns of the table or index that are actually used
97740** by the cursor.  The high-order bit is set if any column after
97741** the 64th is used.
97742*/
97743case OP_ColumnsUsed: {
97744  VdbeCursor *pC;
97745  pC = p->apCsr[pOp->p1];
97746  assert( pC->eCurType==CURTYPE_BTREE );
97747  pC->maskUsed = *(u64*)pOp->p4.pI64;
97748  break;
97749}
97750#endif
97751
97752/* Opcode: SeekGE P1 P2 P3 P4 *
97753** Synopsis: key=r[P3@P4]
97754**
97755** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
97756** use the value in register P3 as the key.  If cursor P1 refers
97757** to an SQL index, then P3 is the first in an array of P4 registers
97758** that are used as an unpacked index key.
97759**
97760** Reposition cursor P1 so that  it points to the smallest entry that
97761** is greater than or equal to the key value. If there are no records
97762** greater than or equal to the key and P2 is not zero, then jump to P2.
97763**
97764** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
97765** opcode will either land on a record that exactly matches the key, or
97766** else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,
97767** this opcode must be followed by an IdxLE opcode with the same arguments.
97768** The IdxGT opcode will be skipped if this opcode succeeds, but the
97769** IdxGT opcode will be used on subsequent loop iterations.  The
97770** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
97771** is an equality search.
97772**
97773** This opcode leaves the cursor configured to move in forward order,
97774** from the beginning toward the end.  In other words, the cursor is
97775** configured to use Next, not Prev.
97776**
97777** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
97778*/
97779/* Opcode: SeekGT P1 P2 P3 P4 *
97780** Synopsis: key=r[P3@P4]
97781**
97782** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
97783** use the value in register P3 as a key. If cursor P1 refers
97784** to an SQL index, then P3 is the first in an array of P4 registers
97785** that are used as an unpacked index key.
97786**
97787** Reposition cursor P1 so that it points to the smallest entry that
97788** is greater than the key value. If there are no records greater than
97789** the key and P2 is not zero, then jump to P2.
97790**
97791** This opcode leaves the cursor configured to move in forward order,
97792** from the beginning toward the end.  In other words, the cursor is
97793** configured to use Next, not Prev.
97794**
97795** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
97796*/
97797/* Opcode: SeekLT P1 P2 P3 P4 *
97798** Synopsis: key=r[P3@P4]
97799**
97800** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
97801** use the value in register P3 as a key. If cursor P1 refers
97802** to an SQL index, then P3 is the first in an array of P4 registers
97803** that are used as an unpacked index key.
97804**
97805** Reposition cursor P1 so that  it points to the largest entry that
97806** is less than the key value. If there are no records less than
97807** the key and P2 is not zero, then jump to P2.
97808**
97809** This opcode leaves the cursor configured to move in reverse order,
97810** from the end toward the beginning.  In other words, the cursor is
97811** configured to use Prev, not Next.
97812**
97813** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
97814*/
97815/* Opcode: SeekLE P1 P2 P3 P4 *
97816** Synopsis: key=r[P3@P4]
97817**
97818** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
97819** use the value in register P3 as a key. If cursor P1 refers
97820** to an SQL index, then P3 is the first in an array of P4 registers
97821** that are used as an unpacked index key.
97822**
97823** Reposition cursor P1 so that it points to the largest entry that
97824** is less than or equal to the key value. If there are no records
97825** less than or equal to the key and P2 is not zero, then jump to P2.
97826**
97827** This opcode leaves the cursor configured to move in reverse order,
97828** from the end toward the beginning.  In other words, the cursor is
97829** configured to use Prev, not Next.
97830**
97831** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
97832** opcode will either land on a record that exactly matches the key, or
97833** else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,
97834** this opcode must be followed by an IdxLE opcode with the same arguments.
97835** The IdxGE opcode will be skipped if this opcode succeeds, but the
97836** IdxGE opcode will be used on subsequent loop iterations.  The
97837** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
97838** is an equality search.
97839**
97840** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
97841*/
97842case OP_SeekLT:         /* jump0, in3, group, ncycle */
97843case OP_SeekLE:         /* jump0, in3, group, ncycle */
97844case OP_SeekGE:         /* jump0, in3, group, ncycle */
97845case OP_SeekGT: {       /* jump0, in3, group, ncycle */
97846  int res;           /* Comparison result */
97847  int oc;            /* Opcode */
97848  VdbeCursor *pC;    /* The cursor to seek */
97849  UnpackedRecord r;  /* The key to seek for */
97850  int nField;        /* Number of columns or fields in the key */
97851  i64 iKey;          /* The rowid we are to seek to */
97852  int eqOnly;        /* Only interested in == results */
97853
97854  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
97855  assert( pOp->p2!=0 );
97856  pC = p->apCsr[pOp->p1];
97857  assert( pC!=0 );
97858  assert( pC->eCurType==CURTYPE_BTREE );
97859  assert( OP_SeekLE == OP_SeekLT+1 );
97860  assert( OP_SeekGE == OP_SeekLT+2 );
97861  assert( OP_SeekGT == OP_SeekLT+3 );
97862  assert( pC->isOrdered );
97863  assert( pC->uc.pCursor!=0 );
97864  oc = pOp->opcode;
97865  eqOnly = 0;
97866  pC->nullRow = 0;
97867#ifdef SQLITE_DEBUG
97868  pC->seekOp = pOp->opcode;
97869#endif
97870
97871  pC->deferredMoveto = 0;
97872  pC->cacheStatus = CACHE_STALE;
97873  if( pC->isTable ){
97874    u16 flags3, newType;
97875    /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */
97876    assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
97877              || CORRUPT_DB );
97878
97879    /* The input value in P3 might be of any type: integer, real, string,
97880    ** blob, or NULL.  But it needs to be an integer before we can do
97881    ** the seek, so convert it. */
97882    pIn3 = &aMem[pOp->p3];
97883    flags3 = pIn3->flags;
97884    if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){
97885      applyNumericAffinity(pIn3, 0);
97886    }
97887    iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */
97888    newType = pIn3->flags; /* Record the type after applying numeric affinity */
97889    pIn3->flags = flags3;  /* But convert the type back to its original */
97890
97891    /* If the P3 value could not be converted into an integer without
97892    ** loss of information, then special processing is required... */
97893    if( (newType & (MEM_Int|MEM_IntReal))==0 ){
97894      int c;
97895      if( (newType & MEM_Real)==0 ){
97896        if( (newType & MEM_Null) || oc>=OP_SeekGE ){
97897          VdbeBranchTaken(1,2);
97898          goto jump_to_p2;
97899        }else{
97900          rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
97901          if( rc!=SQLITE_OK ) goto abort_due_to_error;
97902          goto seek_not_found;
97903        }
97904      }
97905      c = sqlite3IntFloatCompare(iKey, pIn3->u.r);
97906
97907      /* If the approximation iKey is larger than the actual real search
97908      ** term, substitute >= for > and < for <=. e.g. if the search term
97909      ** is 4.9 and the integer approximation 5:
97910      **
97911      **        (x >  4.9)    ->     (x >= 5)
97912      **        (x <= 4.9)    ->     (x <  5)
97913      */
97914      if( c>0 ){
97915        assert( OP_SeekGE==(OP_SeekGT-1) );
97916        assert( OP_SeekLT==(OP_SeekLE-1) );
97917        assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
97918        if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
97919      }
97920
97921      /* If the approximation iKey is smaller than the actual real search
97922      ** term, substitute <= for < and > for >=.  */
97923      else if( c<0 ){
97924        assert( OP_SeekLE==(OP_SeekLT+1) );
97925        assert( OP_SeekGT==(OP_SeekGE+1) );
97926        assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
97927        if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
97928      }
97929    }
97930    rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)iKey, 0, &res);
97931    pC->movetoTarget = iKey;  /* Used by OP_Delete */
97932    if( rc!=SQLITE_OK ){
97933      goto abort_due_to_error;
97934    }
97935  }else{
97936    /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the
97937    ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be
97938    ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,
97939    ** with the same key.
97940    */
97941    if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
97942      eqOnly = 1;
97943      assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
97944      assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
97945      assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
97946      assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
97947      assert( pOp[1].p1==pOp[0].p1 );
97948      assert( pOp[1].p2==pOp[0].p2 );
97949      assert( pOp[1].p3==pOp[0].p3 );
97950      assert( pOp[1].p4.i==pOp[0].p4.i );
97951    }
97952
97953    nField = pOp->p4.i;
97954    assert( pOp->p4type==P4_INT32 );
97955    assert( nField>0 );
97956    r.pKeyInfo = pC->pKeyInfo;
97957    r.nField = (u16)nField;
97958
97959    /* The next line of code computes as follows, only faster:
97960    **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
97961    **     r.default_rc = -1;
97962    **   }else{
97963    **     r.default_rc = +1;
97964    **   }
97965    */
97966    r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
97967    assert( oc!=OP_SeekGT || r.default_rc==-1 );
97968    assert( oc!=OP_SeekLE || r.default_rc==-1 );
97969    assert( oc!=OP_SeekGE || r.default_rc==+1 );
97970    assert( oc!=OP_SeekLT || r.default_rc==+1 );
97971
97972    r.aMem = &aMem[pOp->p3];
97973#ifdef SQLITE_DEBUG
97974    {
97975      int i;
97976      for(i=0; i<r.nField; i++){
97977        assert( memIsValid(&r.aMem[i]) );
97978        if( i>0 ) REGISTER_TRACE(pOp->p3+i, &r.aMem[i]);
97979      }
97980    }
97981#endif
97982    r.eqSeen = 0;
97983    rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &res);
97984    if( rc!=SQLITE_OK ){
97985      goto abort_due_to_error;
97986    }
97987    if( eqOnly && r.eqSeen==0 ){
97988      assert( res!=0 );
97989      goto seek_not_found;
97990    }
97991  }
97992#ifdef SQLITE_TEST
97993  sqlite3_search_count++;
97994#endif
97995  if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
97996    if( res<0 || (res==0 && oc==OP_SeekGT) ){
97997      res = 0;
97998      rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
97999      if( rc!=SQLITE_OK ){
98000        if( rc==SQLITE_DONE ){
98001          rc = SQLITE_OK;
98002          res = 1;
98003        }else{
98004          goto abort_due_to_error;
98005        }
98006      }
98007    }else{
98008      res = 0;
98009    }
98010  }else{
98011    assert( oc==OP_SeekLT || oc==OP_SeekLE );
98012    if( res>0 || (res==0 && oc==OP_SeekLT) ){
98013      res = 0;
98014      rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
98015      if( rc!=SQLITE_OK ){
98016        if( rc==SQLITE_DONE ){
98017          rc = SQLITE_OK;
98018          res = 1;
98019        }else{
98020          goto abort_due_to_error;
98021        }
98022      }
98023    }else{
98024      /* res might be negative because the table is empty.  Check to
98025      ** see if this is the case.
98026      */
98027      res = sqlite3BtreeEof(pC->uc.pCursor);
98028    }
98029  }
98030seek_not_found:
98031  assert( pOp->p2>0 );
98032  VdbeBranchTaken(res!=0,2);
98033  if( res ){
98034    goto jump_to_p2;
98035  }else if( eqOnly ){
98036    assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
98037    pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
98038  }
98039  break;
98040}
98041
98042
98043/* Opcode: SeekScan  P1 P2 * * P5
98044** Synopsis: Scan-ahead up to P1 rows
98045**
98046** This opcode is a prefix opcode to OP_SeekGE.  In other words, this
98047** opcode must be immediately followed by OP_SeekGE. This constraint is
98048** checked by assert() statements.
98049**
98050** This opcode uses the P1 through P4 operands of the subsequent
98051** OP_SeekGE.  In the text that follows, the operands of the subsequent
98052** OP_SeekGE opcode are denoted as SeekOP.P1 through SeekOP.P4.   Only
98053** the P1, P2 and P5 operands of this opcode are also used, and  are called
98054** This.P1, This.P2 and This.P5.
98055**
98056** This opcode helps to optimize IN operators on a multi-column index
98057** where the IN operator is on the later terms of the index by avoiding
98058** unnecessary seeks on the btree, substituting steps to the next row
98059** of the b-tree instead.  A correct answer is obtained if this opcode
98060** is omitted or is a no-op.
98061**
98062** The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which
98063** is the desired entry that we want the cursor SeekGE.P1 to be pointing
98064** to.  Call this SeekGE.P3/P4 row the "target".
98065**
98066** If the SeekGE.P1 cursor is not currently pointing to a valid row,
98067** then this opcode is a no-op and control passes through into the OP_SeekGE.
98068**
98069** If the SeekGE.P1 cursor is pointing to a valid row, then that row
98070** might be the target row, or it might be near and slightly before the
98071** target row, or it might be after the target row.  If the cursor is
98072** currently before the target row, then this opcode attempts to position
98073** the cursor on or after the target row by invoking sqlite3BtreeStep()
98074** on the cursor between 1 and This.P1 times.
98075**
98076** The This.P5 parameter is a flag that indicates what to do if the
98077** cursor ends up pointing at a valid row that is past the target
98078** row.  If This.P5 is false (0) then a jump is made to SeekGE.P2.  If
98079** This.P5 is true (non-zero) then a jump is made to This.P2.  The P5==0
98080** case occurs when there are no inequality constraints to the right of
98081** the IN constraint.  The jump to SeekGE.P2 ends the loop.  The P5!=0 case
98082** occurs when there are inequality constraints to the right of the IN
98083** operator.  In that case, the This.P2 will point either directly to or
98084** to setup code prior to the OP_IdxGT or OP_IdxGE opcode that checks for
98085** loop terminate.
98086**
98087** Possible outcomes from this opcode:<ol>
98088**
98089** <li> If the cursor is initially not pointed to any valid row, then
98090**      fall through into the subsequent OP_SeekGE opcode.
98091**
98092** <li> If the cursor is left pointing to a row that is before the target
98093**      row, even after making as many as This.P1 calls to
98094**      sqlite3BtreeNext(), then also fall through into OP_SeekGE.
98095**
98096** <li> If the cursor is left pointing at the target row, either because it
98097**      was at the target row to begin with or because one or more
98098**      sqlite3BtreeNext() calls moved the cursor to the target row,
98099**      then jump to This.P2..,
98100**
98101** <li> If the cursor started out before the target row and a call to
98102**      to sqlite3BtreeNext() moved the cursor off the end of the index
98103**      (indicating that the target row definitely does not exist in the
98104**      btree) then jump to SeekGE.P2, ending the loop.
98105**
98106** <li> If the cursor ends up on a valid row that is past the target row
98107**      (indicating that the target row does not exist in the btree) then
98108**      jump to SeekOP.P2 if This.P5==0 or to This.P2 if This.P5>0.
98109** </ol>
98110*/
98111case OP_SeekScan: {          /* ncycle */
98112  VdbeCursor *pC;
98113  int res;
98114  int nStep;
98115  UnpackedRecord r;
98116
98117  assert( pOp[1].opcode==OP_SeekGE );
98118
98119  /* If pOp->p5 is clear, then pOp->p2 points to the first instruction past the
98120  ** OP_IdxGT that follows the OP_SeekGE. Otherwise, it points to the first
98121  ** opcode past the OP_SeekGE itself.  */
98122  assert( pOp->p2>=(int)(pOp-aOp)+2 );
98123#ifdef SQLITE_DEBUG
98124  if( pOp->p5==0 ){
98125    /* There are no inequality constraints following the IN constraint. */
98126    assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
98127    assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
98128    assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
98129    assert( aOp[pOp->p2-1].opcode==OP_IdxGT
98130         || aOp[pOp->p2-1].opcode==OP_IdxGE );
98131    testcase( aOp[pOp->p2-1].opcode==OP_IdxGE );
98132  }else{
98133    /* There are inequality constraints.  */
98134    assert( pOp->p2==(int)(pOp-aOp)+2 );
98135    assert( aOp[pOp->p2-1].opcode==OP_SeekGE );
98136  }
98137#endif
98138
98139  assert( pOp->p1>0 );
98140  pC = p->apCsr[pOp[1].p1];
98141  assert( pC!=0 );
98142  assert( pC->eCurType==CURTYPE_BTREE );
98143  assert( !pC->isTable );
98144  if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){
98145#ifdef SQLITE_DEBUG
98146     if( db->flags&SQLITE_VdbeTrace ){
98147       printf("... cursor not valid - fall through\n");
98148     }
98149#endif
98150    break;
98151  }
98152  nStep = pOp->p1;
98153  assert( nStep>=1 );
98154  r.pKeyInfo = pC->pKeyInfo;
98155  r.nField = (u16)pOp[1].p4.i;
98156  r.default_rc = 0;
98157  r.aMem = &aMem[pOp[1].p3];
98158#ifdef SQLITE_DEBUG
98159  {
98160    int i;
98161    for(i=0; i<r.nField; i++){
98162      assert( memIsValid(&r.aMem[i]) );
98163      REGISTER_TRACE(pOp[1].p3+i, &aMem[pOp[1].p3+i]);
98164    }
98165  }
98166#endif
98167  res = 0;  /* Not needed.  Only used to silence a warning. */
98168  while(1){
98169    rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
98170    if( rc ) goto abort_due_to_error;
98171    if( res>0 && pOp->p5==0 ){
98172      seekscan_search_fail:
98173      /* Jump to SeekGE.P2, ending the loop */
98174#ifdef SQLITE_DEBUG
98175      if( db->flags&SQLITE_VdbeTrace ){
98176        printf("... %d steps and then skip\n", pOp->p1 - nStep);
98177      }
98178#endif
98179      VdbeBranchTaken(1,3);
98180      pOp++;
98181      goto jump_to_p2;
98182    }
98183    if( res>=0 ){
98184      /* Jump to This.P2, bypassing the OP_SeekGE opcode */
98185#ifdef SQLITE_DEBUG
98186      if( db->flags&SQLITE_VdbeTrace ){
98187        printf("... %d steps and then success\n", pOp->p1 - nStep);
98188      }
98189#endif
98190      VdbeBranchTaken(2,3);
98191      goto jump_to_p2;
98192      break;
98193    }
98194    if( nStep<=0 ){
98195#ifdef SQLITE_DEBUG
98196      if( db->flags&SQLITE_VdbeTrace ){
98197        printf("... fall through after %d steps\n", pOp->p1);
98198      }
98199#endif
98200      VdbeBranchTaken(0,3);
98201      break;
98202    }
98203    nStep--;
98204    pC->cacheStatus = CACHE_STALE;
98205    rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
98206    if( rc ){
98207      if( rc==SQLITE_DONE ){
98208        rc = SQLITE_OK;
98209        goto seekscan_search_fail;
98210      }else{
98211        goto abort_due_to_error;
98212      }
98213    }
98214  }
98215
98216  break;
98217}
98218
98219
98220/* Opcode: SeekHit P1 P2 P3 * *
98221** Synopsis: set P2<=seekHit<=P3
98222**
98223** Increase or decrease the seekHit value for cursor P1, if necessary,
98224** so that it is no less than P2 and no greater than P3.
98225**
98226** The seekHit integer represents the maximum of terms in an index for which
98227** there is known to be at least one match.  If the seekHit value is smaller
98228** than the total number of equality terms in an index lookup, then the
98229** OP_IfNoHope opcode might run to see if the IN loop can be abandoned
98230** early, thus saving work.  This is part of the IN-early-out optimization.
98231**
98232** P1 must be a valid b-tree cursor.
98233*/
98234case OP_SeekHit: {           /* ncycle */
98235  VdbeCursor *pC;
98236  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98237  pC = p->apCsr[pOp->p1];
98238  assert( pC!=0 );
98239  assert( pOp->p3>=pOp->p2 );
98240  if( pC->seekHit<pOp->p2 ){
98241#ifdef SQLITE_DEBUG
98242    if( db->flags&SQLITE_VdbeTrace ){
98243      printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p2);
98244    }
98245#endif
98246    pC->seekHit = pOp->p2;
98247  }else if( pC->seekHit>pOp->p3 ){
98248#ifdef SQLITE_DEBUG
98249    if( db->flags&SQLITE_VdbeTrace ){
98250      printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p3);
98251    }
98252#endif
98253    pC->seekHit = pOp->p3;
98254  }
98255  break;
98256}
98257
98258/* Opcode: IfNotOpen P1 P2 * * *
98259** Synopsis: if( !csr[P1] ) goto P2
98260**
98261** If cursor P1 is not open or if P1 is set to a NULL row using the
98262** OP_NullRow opcode, then jump to instruction P2. Otherwise, fall through.
98263*/
98264case OP_IfNotOpen: {        /* jump */
98265  VdbeCursor *pCur;
98266
98267  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98268  pCur = p->apCsr[pOp->p1];
98269  VdbeBranchTaken(pCur==0 || pCur->nullRow, 2);
98270  if( pCur==0 || pCur->nullRow ){
98271    goto jump_to_p2_and_check_for_interrupt;
98272  }
98273  break;
98274}
98275
98276/* Opcode: Found P1 P2 P3 P4 *
98277** Synopsis: key=r[P3@P4]
98278**
98279** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
98280** P4>0 then register P3 is the first of P4 registers that form an unpacked
98281** record.
98282**
98283** Cursor P1 is on an index btree.  If the record identified by P3 and P4
98284** is a prefix of any entry in P1 then a jump is made to P2 and
98285** P1 is left pointing at the matching entry.
98286**
98287** This operation leaves the cursor in a state where it can be
98288** advanced in the forward direction.  The Next instruction will work,
98289** but not the Prev instruction.
98290**
98291** See also: NotFound, NoConflict, NotExists. SeekGe
98292*/
98293/* Opcode: NotFound P1 P2 P3 P4 *
98294** Synopsis: key=r[P3@P4]
98295**
98296** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
98297** P4>0 then register P3 is the first of P4 registers that form an unpacked
98298** record.
98299**
98300** Cursor P1 is on an index btree.  If the record identified by P3 and P4
98301** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
98302** does contain an entry whose prefix matches the P3/P4 record then control
98303** falls through to the next instruction and P1 is left pointing at the
98304** matching entry.
98305**
98306** This operation leaves the cursor in a state where it cannot be
98307** advanced in either direction.  In other words, the Next and Prev
98308** opcodes do not work after this operation.
98309**
98310** See also: Found, NotExists, NoConflict, IfNoHope
98311*/
98312/* Opcode: IfNoHope P1 P2 P3 P4 *
98313** Synopsis: key=r[P3@P4]
98314**
98315** Register P3 is the first of P4 registers that form an unpacked
98316** record.  Cursor P1 is an index btree.  P2 is a jump destination.
98317** In other words, the operands to this opcode are the same as the
98318** operands to OP_NotFound and OP_IdxGT.
98319**
98320** This opcode is an optimization attempt only.  If this opcode always
98321** falls through, the correct answer is still obtained, but extra work
98322** is performed.
98323**
98324** A value of N in the seekHit flag of cursor P1 means that there exists
98325** a key P3:N that will match some record in the index.  We want to know
98326** if it is possible for a record P3:P4 to match some record in the
98327** index.  If it is not possible, we can skip some work.  So if seekHit
98328** is less than P4, attempt to find out if a match is possible by running
98329** OP_NotFound.
98330**
98331** This opcode is used in IN clause processing for a multi-column key.
98332** If an IN clause is attached to an element of the key other than the
98333** left-most element, and if there are no matches on the most recent
98334** seek over the whole key, then it might be that one of the key element
98335** to the left is prohibiting a match, and hence there is "no hope" of
98336** any match regardless of how many IN clause elements are checked.
98337** In such a case, we abandon the IN clause search early, using this
98338** opcode.  The opcode name comes from the fact that the
98339** jump is taken if there is "no hope" of achieving a match.
98340**
98341** See also: NotFound, SeekHit
98342*/
98343/* Opcode: NoConflict P1 P2 P3 P4 *
98344** Synopsis: key=r[P3@P4]
98345**
98346** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
98347** P4>0 then register P3 is the first of P4 registers that form an unpacked
98348** record.
98349**
98350** Cursor P1 is on an index btree.  If the record identified by P3 and P4
98351** contains any NULL value, jump immediately to P2.  If all terms of the
98352** record are not-NULL then a check is done to determine if any row in the
98353** P1 index btree has a matching key prefix.  If there are no matches, jump
98354** immediately to P2.  If there is a match, fall through and leave the P1
98355** cursor pointing to the matching row.
98356**
98357** This opcode is similar to OP_NotFound with the exceptions that the
98358** branch is always taken if any part of the search key input is NULL.
98359**
98360** This operation leaves the cursor in a state where it cannot be
98361** advanced in either direction.  In other words, the Next and Prev
98362** opcodes do not work after this operation.
98363**
98364** See also: NotFound, Found, NotExists
98365*/
98366case OP_IfNoHope: {     /* jump, in3, ncycle */
98367  VdbeCursor *pC;
98368  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98369  pC = p->apCsr[pOp->p1];
98370  assert( pC!=0 );
98371#ifdef SQLITE_DEBUG
98372  if( db->flags&SQLITE_VdbeTrace ){
98373    printf("seekHit is %d\n", pC->seekHit);
98374  }
98375#endif
98376  if( pC->seekHit>=pOp->p4.i ) break;
98377  /* Fall through into OP_NotFound */
98378  /* no break */ deliberate_fall_through
98379}
98380case OP_NoConflict:     /* jump, in3, ncycle */
98381case OP_NotFound:       /* jump, in3, ncycle */
98382case OP_Found: {        /* jump, in3, ncycle */
98383  int alreadyExists;
98384  int ii;
98385  VdbeCursor *pC;
98386  UnpackedRecord *pIdxKey;
98387  UnpackedRecord r;
98388
98389#ifdef SQLITE_TEST
98390  if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
98391#endif
98392
98393  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98394  assert( pOp->p4type==P4_INT32 );
98395  pC = p->apCsr[pOp->p1];
98396  assert( pC!=0 );
98397#ifdef SQLITE_DEBUG
98398  pC->seekOp = pOp->opcode;
98399#endif
98400  r.aMem = &aMem[pOp->p3];
98401  assert( pC->eCurType==CURTYPE_BTREE );
98402  assert( pC->uc.pCursor!=0 );
98403  assert( pC->isTable==0 );
98404  r.nField = (u16)pOp->p4.i;
98405  if( r.nField>0 ){
98406    /* Key values in an array of registers */
98407    r.pKeyInfo = pC->pKeyInfo;
98408    r.default_rc = 0;
98409#ifdef SQLITE_DEBUG
98410    for(ii=0; ii<r.nField; ii++){
98411      assert( memIsValid(&r.aMem[ii]) );
98412      assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
98413      if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
98414    }
98415#endif
98416    rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &pC->seekResult);
98417  }else{
98418    /* Composite key generated by OP_MakeRecord */
98419    assert( r.aMem->flags & MEM_Blob );
98420    assert( pOp->opcode!=OP_NoConflict );
98421    rc = ExpandBlob(r.aMem);
98422    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
98423    if( rc ) goto no_mem;
98424    pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
98425    if( pIdxKey==0 ) goto no_mem;
98426    sqlite3VdbeRecordUnpack(pC->pKeyInfo, r.aMem->n, r.aMem->z, pIdxKey);
98427    pIdxKey->default_rc = 0;
98428    rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, pIdxKey, &pC->seekResult);
98429    sqlite3DbFreeNN(db, pIdxKey);
98430  }
98431  if( rc!=SQLITE_OK ){
98432    goto abort_due_to_error;
98433  }
98434  alreadyExists = (pC->seekResult==0);
98435  pC->nullRow = 1-alreadyExists;
98436  pC->deferredMoveto = 0;
98437  pC->cacheStatus = CACHE_STALE;
98438  if( pOp->opcode==OP_Found ){
98439    VdbeBranchTaken(alreadyExists!=0,2);
98440    if( alreadyExists ) goto jump_to_p2;
98441  }else{
98442    if( !alreadyExists ){
98443      VdbeBranchTaken(1,2);
98444      goto jump_to_p2;
98445    }
98446    if( pOp->opcode==OP_NoConflict ){
98447      /* For the OP_NoConflict opcode, take the jump if any of the
98448      ** input fields are NULL, since any key with a NULL will not
98449      ** conflict */
98450      for(ii=0; ii<r.nField; ii++){
98451        if( r.aMem[ii].flags & MEM_Null ){
98452          VdbeBranchTaken(1,2);
98453          goto jump_to_p2;
98454        }
98455      }
98456    }
98457    VdbeBranchTaken(0,2);
98458    if( pOp->opcode==OP_IfNoHope ){
98459      pC->seekHit = pOp->p4.i;
98460    }
98461  }
98462  break;
98463}
98464
98465/* Opcode: SeekRowid P1 P2 P3 * *
98466** Synopsis: intkey=r[P3]
98467**
98468** P1 is the index of a cursor open on an SQL table btree (with integer
98469** keys).  If register P3 does not contain an integer or if P1 does not
98470** contain a record with rowid P3 then jump immediately to P2.
98471** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
98472** a record with rowid P3 then
98473** leave the cursor pointing at that record and fall through to the next
98474** instruction.
98475**
98476** The OP_NotExists opcode performs the same operation, but with OP_NotExists
98477** the P3 register must be guaranteed to contain an integer value.  With this
98478** opcode, register P3 might not contain an integer.
98479**
98480** The OP_NotFound opcode performs the same operation on index btrees
98481** (with arbitrary multi-value keys).
98482**
98483** This opcode leaves the cursor in a state where it cannot be advanced
98484** in either direction.  In other words, the Next and Prev opcodes will
98485** not work following this opcode.
98486**
98487** See also: Found, NotFound, NoConflict, SeekRowid
98488*/
98489/* Opcode: NotExists P1 P2 P3 * *
98490** Synopsis: intkey=r[P3]
98491**
98492** P1 is the index of a cursor open on an SQL table btree (with integer
98493** keys).  P3 is an integer rowid.  If P1 does not contain a record with
98494** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
98495** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
98496** leave the cursor pointing at that record and fall through to the next
98497** instruction.
98498**
98499** The OP_SeekRowid opcode performs the same operation but also allows the
98500** P3 register to contain a non-integer value, in which case the jump is
98501** always taken.  This opcode requires that P3 always contain an integer.
98502**
98503** The OP_NotFound opcode performs the same operation on index btrees
98504** (with arbitrary multi-value keys).
98505**
98506** This opcode leaves the cursor in a state where it cannot be advanced
98507** in either direction.  In other words, the Next and Prev opcodes will
98508** not work following this opcode.
98509**
98510** See also: Found, NotFound, NoConflict, SeekRowid
98511*/
98512case OP_SeekRowid: {        /* jump0, in3, ncycle */
98513  VdbeCursor *pC;
98514  BtCursor *pCrsr;
98515  int res;
98516  u64 iKey;
98517
98518  pIn3 = &aMem[pOp->p3];
98519  testcase( pIn3->flags & MEM_Int );
98520  testcase( pIn3->flags & MEM_IntReal );
98521  testcase( pIn3->flags & MEM_Real );
98522  testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );
98523  if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
98524    /* If pIn3->u.i does not contain an integer, compute iKey as the
98525    ** integer value of pIn3.  Jump to P2 if pIn3 cannot be converted
98526    ** into an integer without loss of information.  Take care to avoid
98527    ** changing the datatype of pIn3, however, as it is used by other
98528    ** parts of the prepared statement. */
98529    Mem x = pIn3[0];
98530    applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);
98531    if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;
98532    iKey = x.u.i;
98533    goto notExistsWithKey;
98534  }
98535  /* Fall through into OP_NotExists */
98536  /* no break */ deliberate_fall_through
98537case OP_NotExists:          /* jump, in3, ncycle */
98538  pIn3 = &aMem[pOp->p3];
98539  assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
98540  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98541  iKey = pIn3->u.i;
98542notExistsWithKey:
98543  pC = p->apCsr[pOp->p1];
98544  assert( pC!=0 );
98545#ifdef SQLITE_DEBUG
98546  if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
98547#endif
98548  assert( pC->isTable );
98549  assert( pC->eCurType==CURTYPE_BTREE );
98550  pCrsr = pC->uc.pCursor;
98551  assert( pCrsr!=0 );
98552  res = 0;
98553  rc = sqlite3BtreeTableMoveto(pCrsr, iKey, 0, &res);
98554  assert( rc==SQLITE_OK || res==0 );
98555  pC->movetoTarget = iKey;  /* Used by OP_Delete */
98556  pC->nullRow = 0;
98557  pC->cacheStatus = CACHE_STALE;
98558  pC->deferredMoveto = 0;
98559  VdbeBranchTaken(res!=0,2);
98560  pC->seekResult = res;
98561  if( res!=0 ){
98562    assert( rc==SQLITE_OK );
98563    if( pOp->p2==0 ){
98564      rc = SQLITE_CORRUPT_BKPT;
98565    }else{
98566      goto jump_to_p2;
98567    }
98568  }
98569  if( rc ) goto abort_due_to_error;
98570  break;
98571}
98572
98573/* Opcode: Sequence P1 P2 * * *
98574** Synopsis: r[P2]=cursor[P1].ctr++
98575**
98576** Find the next available sequence number for cursor P1.
98577** Write the sequence number into register P2.
98578** The sequence number on the cursor is incremented after this
98579** instruction.
98580*/
98581case OP_Sequence: {           /* out2 */
98582  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98583  assert( p->apCsr[pOp->p1]!=0 );
98584  assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
98585  pOut = out2Prerelease(p, pOp);
98586  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
98587  break;
98588}
98589
98590
98591/* Opcode: NewRowid P1 P2 P3 * *
98592** Synopsis: r[P2]=rowid
98593**
98594** Get a new integer record number (a.k.a "rowid") used as the key to a table.
98595** The record number is not previously used as a key in the database
98596** table that cursor P1 points to.  The new record number is written
98597** written to register P2.
98598**
98599** If P3>0 then P3 is a register in the root frame of this VDBE that holds
98600** the largest previously generated record number. No new record numbers are
98601** allowed to be less than this value. When this value reaches its maximum,
98602** an SQLITE_FULL error is generated. The P3 register is updated with the '
98603** generated record number. This P3 mechanism is used to help implement the
98604** AUTOINCREMENT feature.
98605*/
98606case OP_NewRowid: {           /* out2 */
98607  i64 v;                 /* The new rowid */
98608  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
98609  int res;               /* Result of an sqlite3BtreeLast() */
98610  int cnt;               /* Counter to limit the number of searches */
98611#ifndef SQLITE_OMIT_AUTOINCREMENT
98612  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
98613  VdbeFrame *pFrame;     /* Root frame of VDBE */
98614#endif
98615
98616  v = 0;
98617  res = 0;
98618  pOut = out2Prerelease(p, pOp);
98619  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98620  pC = p->apCsr[pOp->p1];
98621  assert( pC!=0 );
98622  assert( pC->isTable );
98623  assert( pC->eCurType==CURTYPE_BTREE );
98624  assert( pC->uc.pCursor!=0 );
98625  {
98626    /* The next rowid or record number (different terms for the same
98627    ** thing) is obtained in a two-step algorithm.
98628    **
98629    ** First we attempt to find the largest existing rowid and add one
98630    ** to that.  But if the largest existing rowid is already the maximum
98631    ** positive integer, we have to fall through to the second
98632    ** probabilistic algorithm
98633    **
98634    ** The second algorithm is to select a rowid at random and see if
98635    ** it already exists in the table.  If it does not exist, we have
98636    ** succeeded.  If the random rowid does exist, we select a new one
98637    ** and try again, up to 100 times.
98638    */
98639    assert( pC->isTable );
98640
98641#ifdef SQLITE_32BIT_ROWID
98642#   define MAX_ROWID 0x7fffffff
98643#else
98644    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
98645    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
98646    ** to provide the constant while making all compilers happy.
98647    */
98648#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
98649#endif
98650
98651    if( !pC->useRandomRowid ){
98652      rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
98653      if( rc!=SQLITE_OK ){
98654        goto abort_due_to_error;
98655      }
98656      if( res ){
98657        v = 1;   /* IMP: R-61914-48074 */
98658      }else{
98659        assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
98660        v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
98661        if( v>=MAX_ROWID ){
98662          pC->useRandomRowid = 1;
98663        }else{
98664          v++;   /* IMP: R-29538-34987 */
98665        }
98666      }
98667    }
98668
98669#ifndef SQLITE_OMIT_AUTOINCREMENT
98670    if( pOp->p3 ){
98671      /* Assert that P3 is a valid memory cell. */
98672      assert( pOp->p3>0 );
98673      if( p->pFrame ){
98674        for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
98675        /* Assert that P3 is a valid memory cell. */
98676        assert( pOp->p3<=pFrame->nMem );
98677        pMem = &pFrame->aMem[pOp->p3];
98678      }else{
98679        /* Assert that P3 is a valid memory cell. */
98680        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
98681        pMem = &aMem[pOp->p3];
98682        memAboutToChange(p, pMem);
98683      }
98684      assert( memIsValid(pMem) );
98685
98686      REGISTER_TRACE(pOp->p3, pMem);
98687      sqlite3VdbeMemIntegerify(pMem);
98688      assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
98689      if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
98690        rc = SQLITE_FULL;   /* IMP: R-17817-00630 */
98691        goto abort_due_to_error;
98692      }
98693      if( v<pMem->u.i+1 ){
98694        v = pMem->u.i + 1;
98695      }
98696      pMem->u.i = v;
98697    }
98698#endif
98699    if( pC->useRandomRowid ){
98700      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
98701      ** largest possible integer (9223372036854775807) then the database
98702      ** engine starts picking positive candidate ROWIDs at random until
98703      ** it finds one that is not previously used. */
98704      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
98705                             ** an AUTOINCREMENT table. */
98706      cnt = 0;
98707      do{
98708        sqlite3_randomness(sizeof(v), &v);
98709        v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
98710      }while(  ((rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)v,
98711                                                 0, &res))==SQLITE_OK)
98712            && (res==0)
98713            && (++cnt<100));
98714      if( rc ) goto abort_due_to_error;
98715      if( res==0 ){
98716        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
98717        goto abort_due_to_error;
98718      }
98719      assert( v>0 );  /* EV: R-40812-03570 */
98720    }
98721    pC->deferredMoveto = 0;
98722    pC->cacheStatus = CACHE_STALE;
98723  }
98724  pOut->u.i = v;
98725  break;
98726}
98727
98728/* Opcode: Insert P1 P2 P3 P4 P5
98729** Synopsis: intkey=r[P3] data=r[P2]
98730**
98731** Write an entry into the table of cursor P1.  A new entry is
98732** created if it doesn't already exist or the data for an existing
98733** entry is overwritten.  The data is the value MEM_Blob stored in register
98734** number P2. The key is stored in register P3. The key must
98735** be a MEM_Int.
98736**
98737** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
98738** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
98739** then rowid is stored for subsequent return by the
98740** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
98741**
98742** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
98743** run faster by avoiding an unnecessary seek on cursor P1.  However,
98744** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
98745** seeks on the cursor or if the most recent seek used a key equal to P3.
98746**
98747** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
98748** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
98749** is part of an INSERT operation.  The difference is only important to
98750** the update hook.
98751**
98752** Parameter P4 may point to a Table structure, or may be NULL. If it is
98753** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
98754** following a successful insert.
98755**
98756** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
98757** allocated, then ownership of P2 is transferred to the pseudo-cursor
98758** and register P2 becomes ephemeral.  If the cursor is changed, the
98759** value of register P2 will then change.  Make sure this does not
98760** cause any problems.)
98761**
98762** This instruction only works on tables.  The equivalent instruction
98763** for indices is OP_IdxInsert.
98764*/
98765case OP_Insert: {
98766  Mem *pData;       /* MEM cell holding data for the record to be inserted */
98767  Mem *pKey;        /* MEM cell holding key  for the record */
98768  VdbeCursor *pC;   /* Cursor to table into which insert is written */
98769  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
98770  const char *zDb;  /* database name - used by the update hook */
98771  Table *pTab;      /* Table structure - used by update and pre-update hooks */
98772  BtreePayload x;   /* Payload to be inserted */
98773
98774  pData = &aMem[pOp->p2];
98775  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98776  assert( memIsValid(pData) );
98777  pC = p->apCsr[pOp->p1];
98778  assert( pC!=0 );
98779  assert( pC->eCurType==CURTYPE_BTREE );
98780  assert( pC->deferredMoveto==0 );
98781  assert( pC->uc.pCursor!=0 );
98782  assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
98783  assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
98784  REGISTER_TRACE(pOp->p2, pData);
98785  sqlite3VdbeIncrWriteCounter(p, pC);
98786
98787  pKey = &aMem[pOp->p3];
98788  assert( pKey->flags & MEM_Int );
98789  assert( memIsValid(pKey) );
98790  REGISTER_TRACE(pOp->p3, pKey);
98791  x.nKey = pKey->u.i;
98792
98793  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
98794    assert( pC->iDb>=0 );
98795    zDb = db->aDb[pC->iDb].zDbSName;
98796    pTab = pOp->p4.pTab;
98797    assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
98798  }else{
98799    pTab = 0;
98800    zDb = 0;
98801  }
98802
98803#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
98804  /* Invoke the pre-update hook, if any */
98805  if( pTab ){
98806    if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
98807      sqlite3VdbePreUpdateHook(p,pC,SQLITE_INSERT,zDb,pTab,x.nKey,pOp->p2,-1);
98808    }
98809    if( db->xUpdateCallback==0 || pTab->aCol==0 ){
98810      /* Prevent post-update hook from running in cases when it should not */
98811      pTab = 0;
98812    }
98813  }
98814  if( pOp->p5 & OPFLAG_ISNOOP ) break;
98815#endif
98816
98817  assert( (pOp->p5 & OPFLAG_LASTROWID)==0 || (pOp->p5 & OPFLAG_NCHANGE)!=0 );
98818  if( pOp->p5 & OPFLAG_NCHANGE ){
98819    p->nChange++;
98820    if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
98821  }
98822  assert( (pData->flags & (MEM_Blob|MEM_Str))!=0 || pData->n==0 );
98823  x.pData = pData->z;
98824  x.nData = pData->n;
98825  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
98826  if( pData->flags & MEM_Zero ){
98827    x.nZero = pData->u.nZero;
98828  }else{
98829    x.nZero = 0;
98830  }
98831  x.pKey = 0;
98832  assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT );
98833  rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
98834      (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
98835      seekResult
98836  );
98837  pC->deferredMoveto = 0;
98838  pC->cacheStatus = CACHE_STALE;
98839  colCacheCtr++;
98840
98841  /* Invoke the update-hook if required. */
98842  if( rc ) goto abort_due_to_error;
98843  if( pTab ){
98844    assert( db->xUpdateCallback!=0 );
98845    assert( pTab->aCol!=0 );
98846    db->xUpdateCallback(db->pUpdateArg,
98847           (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
98848           zDb, pTab->zName, x.nKey);
98849  }
98850  break;
98851}
98852
98853/* Opcode: RowCell P1 P2 P3 * *
98854**
98855** P1 and P2 are both open cursors. Both must be opened on the same type
98856** of table - intkey or index. This opcode is used as part of copying
98857** the current row from P2 into P1. If the cursors are opened on intkey
98858** tables, register P3 contains the rowid to use with the new record in
98859** P1. If they are opened on index tables, P3 is not used.
98860**
98861** This opcode must be followed by either an Insert or InsertIdx opcode
98862** with the OPFLAG_PREFORMAT flag set to complete the insert operation.
98863*/
98864case OP_RowCell: {
98865  VdbeCursor *pDest;              /* Cursor to write to */
98866  VdbeCursor *pSrc;               /* Cursor to read from */
98867  i64 iKey;                       /* Rowid value to insert with */
98868  assert( pOp[1].opcode==OP_Insert || pOp[1].opcode==OP_IdxInsert );
98869  assert( pOp[1].opcode==OP_Insert    || pOp->p3==0 );
98870  assert( pOp[1].opcode==OP_IdxInsert || pOp->p3>0 );
98871  assert( pOp[1].p5 & OPFLAG_PREFORMAT );
98872  pDest = p->apCsr[pOp->p1];
98873  pSrc = p->apCsr[pOp->p2];
98874  iKey = pOp->p3 ? aMem[pOp->p3].u.i : 0;
98875  rc = sqlite3BtreeTransferRow(pDest->uc.pCursor, pSrc->uc.pCursor, iKey);
98876  if( rc!=SQLITE_OK ) goto abort_due_to_error;
98877  break;
98878};
98879
98880/* Opcode: Delete P1 P2 P3 P4 P5
98881**
98882** Delete the record at which the P1 cursor is currently pointing.
98883**
98884** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
98885** the cursor will be left pointing at  either the next or the previous
98886** record in the table. If it is left pointing at the next record, then
98887** the next Next instruction will be a no-op. As a result, in this case
98888** it is ok to delete a record from within a Next loop. If
98889** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
98890** left in an undefined state.
98891**
98892** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
98893** delete is one of several associated with deleting a table row and
98894** all its associated index entries.  Exactly one of those deletes is
98895** the "primary" delete.  The others are all on OPFLAG_FORDELETE
98896** cursors or else are marked with the AUXDELETE flag.
98897**
98898** If the OPFLAG_NCHANGE (0x01) flag of P2 (NB: P2 not P5) is set, then
98899** the row change count is incremented (otherwise not).
98900**
98901** If the OPFLAG_ISNOOP (0x40) flag of P2 (not P5!) is set, then the
98902** pre-update-hook for deletes is run, but the btree is otherwise unchanged.
98903** This happens when the OP_Delete is to be shortly followed by an OP_Insert
98904** with the same key, causing the btree entry to be overwritten.
98905**
98906** P1 must not be pseudo-table.  It has to be a real table with
98907** multiple rows.
98908**
98909** If P4 is not NULL then it points to a Table object. In this case either
98910** the update or pre-update hook, or both, may be invoked. The P1 cursor must
98911** have been positioned using OP_NotFound prior to invoking this opcode in
98912** this case. Specifically, if one is configured, the pre-update hook is
98913** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
98914** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
98915**
98916** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
98917** of the memory cell that contains the value that the rowid of the row will
98918** be set to by the update.
98919*/
98920case OP_Delete: {
98921  VdbeCursor *pC;
98922  const char *zDb;
98923  Table *pTab;
98924  int opflags;
98925
98926  opflags = pOp->p2;
98927  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98928  pC = p->apCsr[pOp->p1];
98929  assert( pC!=0 );
98930  assert( pC->eCurType==CURTYPE_BTREE );
98931  assert( pC->uc.pCursor!=0 );
98932  assert( pC->deferredMoveto==0 );
98933  sqlite3VdbeIncrWriteCounter(p, pC);
98934
98935#ifdef SQLITE_DEBUG
98936  if( pOp->p4type==P4_TABLE
98937   && HasRowid(pOp->p4.pTab)
98938   && pOp->p5==0
98939   && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
98940  ){
98941    /* If p5 is zero, the seek operation that positioned the cursor prior to
98942    ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
98943    ** the row that is being deleted */
98944    i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
98945    assert( CORRUPT_DB || pC->movetoTarget==iKey );
98946  }
98947#endif
98948
98949  /* If the update-hook or pre-update-hook will be invoked, set zDb to
98950  ** the name of the db to pass as to it. Also set local pTab to a copy
98951  ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
98952  ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
98953  ** VdbeCursor.movetoTarget to the current rowid.  */
98954  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
98955    assert( pC->iDb>=0 );
98956    assert( pOp->p4.pTab!=0 );
98957    zDb = db->aDb[pC->iDb].zDbSName;
98958    pTab = pOp->p4.pTab;
98959    if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
98960      pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
98961    }
98962  }else{
98963    zDb = 0;
98964    pTab = 0;
98965  }
98966
98967#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
98968  /* Invoke the pre-update-hook if required. */
98969  assert( db->xPreUpdateCallback==0 || pTab==pOp->p4.pTab );
98970  if( db->xPreUpdateCallback && pTab ){
98971    assert( !(opflags & OPFLAG_ISUPDATE)
98972         || HasRowid(pTab)==0
98973         || (aMem[pOp->p3].flags & MEM_Int)
98974    );
98975    sqlite3VdbePreUpdateHook(p, pC,
98976        (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
98977        zDb, pTab, pC->movetoTarget,
98978        pOp->p3, -1
98979    );
98980  }
98981  if( opflags & OPFLAG_ISNOOP ) break;
98982#endif
98983
98984  /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
98985  assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
98986  assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
98987  assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
98988
98989#ifdef SQLITE_DEBUG
98990  if( p->pFrame==0 ){
98991    if( pC->isEphemeral==0
98992        && (pOp->p5 & OPFLAG_AUXDELETE)==0
98993        && (pC->wrFlag & OPFLAG_FORDELETE)==0
98994      ){
98995      nExtraDelete++;
98996    }
98997    if( pOp->p2 & OPFLAG_NCHANGE ){
98998      nExtraDelete--;
98999    }
99000  }
99001#endif
99002
99003  rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
99004  pC->cacheStatus = CACHE_STALE;
99005  colCacheCtr++;
99006  pC->seekResult = 0;
99007  if( rc ) goto abort_due_to_error;
99008
99009  /* Invoke the update-hook if required. */
99010  if( opflags & OPFLAG_NCHANGE ){
99011    p->nChange++;
99012    if( db->xUpdateCallback && ALWAYS(pTab!=0) && HasRowid(pTab) ){
99013      db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
99014          pC->movetoTarget);
99015      assert( pC->iDb>=0 );
99016    }
99017  }
99018
99019  break;
99020}
99021/* Opcode: ResetCount * * * * *
99022**
99023** The value of the change counter is copied to the database handle
99024** change counter (returned by subsequent calls to sqlite3_changes()).
99025** Then the VMs internal change counter resets to 0.
99026** This is used by trigger programs.
99027*/
99028case OP_ResetCount: {
99029  sqlite3VdbeSetChanges(db, p->nChange);
99030  p->nChange = 0;
99031  break;
99032}
99033
99034/* Opcode: SorterCompare P1 P2 P3 P4
99035** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
99036**
99037** P1 is a sorter cursor. This instruction compares a prefix of the
99038** record blob in register P3 against a prefix of the entry that
99039** the sorter cursor currently points to.  Only the first P4 fields
99040** of r[P3] and the sorter record are compared.
99041**
99042** If either P3 or the sorter contains a NULL in one of their significant
99043** fields (not counting the P4 fields at the end which are ignored) then
99044** the comparison is assumed to be equal.
99045**
99046** Fall through to next instruction if the two records compare equal to
99047** each other.  Jump to P2 if they are different.
99048*/
99049case OP_SorterCompare: {
99050  VdbeCursor *pC;
99051  int res;
99052  int nKeyCol;
99053
99054  pC = p->apCsr[pOp->p1];
99055  assert( isSorter(pC) );
99056  assert( pOp->p4type==P4_INT32 );
99057  pIn3 = &aMem[pOp->p3];
99058  nKeyCol = pOp->p4.i;
99059  res = 0;
99060  rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
99061  VdbeBranchTaken(res!=0,2);
99062  if( rc ) goto abort_due_to_error;
99063  if( res ) goto jump_to_p2;
99064  break;
99065};
99066
99067/* Opcode: SorterData P1 P2 P3 * *
99068** Synopsis: r[P2]=data
99069**
99070** Write into register P2 the current sorter data for sorter cursor P1.
99071** Then clear the column header cache on cursor P3.
99072**
99073** This opcode is normally used to move a record out of the sorter and into
99074** a register that is the source for a pseudo-table cursor created using
99075** OpenPseudo.  That pseudo-table cursor is the one that is identified by
99076** parameter P3.  Clearing the P3 column cache as part of this opcode saves
99077** us from having to issue a separate NullRow instruction to clear that cache.
99078*/
99079case OP_SorterData: {       /* ncycle */
99080  VdbeCursor *pC;
99081
99082  pOut = &aMem[pOp->p2];
99083  pC = p->apCsr[pOp->p1];
99084  assert( isSorter(pC) );
99085  rc = sqlite3VdbeSorterRowkey(pC, pOut);
99086  assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
99087  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99088  if( rc ) goto abort_due_to_error;
99089  p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
99090  break;
99091}
99092
99093/* Opcode: RowData P1 P2 P3 * *
99094** Synopsis: r[P2]=data
99095**
99096** Write into register P2 the complete row content for the row at
99097** which cursor P1 is currently pointing.
99098** There is no interpretation of the data.
99099** It is just copied onto the P2 register exactly as
99100** it is found in the database file.
99101**
99102** If cursor P1 is an index, then the content is the key of the row.
99103** If cursor P2 is a table, then the content extracted is the data.
99104**
99105** If the P1 cursor must be pointing to a valid row (not a NULL row)
99106** of a real table, not a pseudo-table.
99107**
99108** If P3!=0 then this opcode is allowed to make an ephemeral pointer
99109** into the database page.  That means that the content of the output
99110** register will be invalidated as soon as the cursor moves - including
99111** moves caused by other cursors that "save" the current cursors
99112** position in order that they can write to the same table.  If P3==0
99113** then a copy of the data is made into memory.  P3!=0 is faster, but
99114** P3==0 is safer.
99115**
99116** If P3!=0 then the content of the P2 register is unsuitable for use
99117** in OP_Result and any OP_Result will invalidate the P2 register content.
99118** The P2 register content is invalidated by opcodes like OP_Function or
99119** by any use of another cursor pointing to the same table.
99120*/
99121case OP_RowData: {
99122  VdbeCursor *pC;
99123  BtCursor *pCrsr;
99124  u32 n;
99125
99126  pOut = out2Prerelease(p, pOp);
99127
99128  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99129  pC = p->apCsr[pOp->p1];
99130  assert( pC!=0 );
99131  assert( pC->eCurType==CURTYPE_BTREE );
99132  assert( isSorter(pC)==0 );
99133  assert( pC->nullRow==0 );
99134  assert( pC->uc.pCursor!=0 );
99135  pCrsr = pC->uc.pCursor;
99136
99137  /* The OP_RowData opcodes always follow OP_NotExists or
99138  ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
99139  ** that might invalidate the cursor.
99140  ** If this where not the case, on of the following assert()s
99141  ** would fail.  Should this ever change (because of changes in the code
99142  ** generator) then the fix would be to insert a call to
99143  ** sqlite3VdbeCursorMoveto().
99144  */
99145  assert( pC->deferredMoveto==0 );
99146  assert( sqlite3BtreeCursorIsValid(pCrsr) );
99147
99148  n = sqlite3BtreePayloadSize(pCrsr);
99149  if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
99150    goto too_big;
99151  }
99152  testcase( n==0 );
99153  rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut);
99154  if( rc ) goto abort_due_to_error;
99155  if( !pOp->p3 ) Deephemeralize(pOut);
99156  UPDATE_MAX_BLOBSIZE(pOut);
99157  REGISTER_TRACE(pOp->p2, pOut);
99158  break;
99159}
99160
99161/* Opcode: Rowid P1 P2 * * *
99162** Synopsis: r[P2]=PX rowid of P1
99163**
99164** Store in register P2 an integer which is the key of the table entry that
99165** P1 is currently point to.
99166**
99167** P1 can be either an ordinary table or a virtual table.  There used to
99168** be a separate OP_VRowid opcode for use with virtual tables, but this
99169** one opcode now works for both table types.
99170*/
99171case OP_Rowid: {                 /* out2, ncycle */
99172  VdbeCursor *pC;
99173  i64 v;
99174  sqlite3_vtab *pVtab;
99175  const sqlite3_module *pModule;
99176
99177  pOut = out2Prerelease(p, pOp);
99178  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99179  pC = p->apCsr[pOp->p1];
99180  assert( pC!=0 );
99181  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
99182  if( pC->nullRow ){
99183    pOut->flags = MEM_Null;
99184    break;
99185  }else if( pC->deferredMoveto ){
99186    v = pC->movetoTarget;
99187#ifndef SQLITE_OMIT_VIRTUALTABLE
99188  }else if( pC->eCurType==CURTYPE_VTAB ){
99189    assert( pC->uc.pVCur!=0 );
99190    pVtab = pC->uc.pVCur->pVtab;
99191    pModule = pVtab->pModule;
99192    assert( pModule->xRowid );
99193    rc = pModule->xRowid(pC->uc.pVCur, &v);
99194    sqlite3VtabImportErrmsg(p, pVtab);
99195    if( rc ) goto abort_due_to_error;
99196#endif /* SQLITE_OMIT_VIRTUALTABLE */
99197  }else{
99198    assert( pC->eCurType==CURTYPE_BTREE );
99199    assert( pC->uc.pCursor!=0 );
99200    rc = sqlite3VdbeCursorRestore(pC);
99201    if( rc ) goto abort_due_to_error;
99202    if( pC->nullRow ){
99203      pOut->flags = MEM_Null;
99204      break;
99205    }
99206    v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
99207  }
99208  pOut->u.i = v;
99209  break;
99210}
99211
99212/* Opcode: NullRow P1 * * * *
99213**
99214** Move the cursor P1 to a null row.  Any OP_Column operations
99215** that occur while the cursor is on the null row will always
99216** write a NULL.
99217**
99218** If cursor P1 is not previously opened, open it now to a special
99219** pseudo-cursor that always returns NULL for every column.
99220*/
99221case OP_NullRow: {
99222  VdbeCursor *pC;
99223
99224  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99225  pC = p->apCsr[pOp->p1];
99226  if( pC==0 ){
99227    /* If the cursor is not already open, create a special kind of
99228    ** pseudo-cursor that always gives null rows. */
99229    pC = allocateCursor(p, pOp->p1, 1, CURTYPE_PSEUDO);
99230    if( pC==0 ) goto no_mem;
99231    pC->seekResult = 0;
99232    pC->isTable = 1;
99233    pC->noReuse = 1;
99234    pC->uc.pCursor = sqlite3BtreeFakeValidCursor();
99235  }
99236  pC->nullRow = 1;
99237  pC->cacheStatus = CACHE_STALE;
99238  if( pC->eCurType==CURTYPE_BTREE ){
99239    assert( pC->uc.pCursor!=0 );
99240    sqlite3BtreeClearCursor(pC->uc.pCursor);
99241  }
99242#ifdef SQLITE_DEBUG
99243  if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
99244#endif
99245  break;
99246}
99247
99248/* Opcode: SeekEnd P1 * * * *
99249**
99250** Position cursor P1 at the end of the btree for the purpose of
99251** appending a new entry onto the btree.
99252**
99253** It is assumed that the cursor is used only for appending and so
99254** if the cursor is valid, then the cursor must already be pointing
99255** at the end of the btree and so no changes are made to
99256** the cursor.
99257*/
99258/* Opcode: Last P1 P2 * * *
99259**
99260** The next use of the Rowid or Column or Prev instruction for P1
99261** will refer to the last entry in the database table or index.
99262** If the table or index is empty and P2>0, then jump immediately to P2.
99263** If P2 is 0 or if the table or index is not empty, fall through
99264** to the following instruction.
99265**
99266** This opcode leaves the cursor configured to move in reverse order,
99267** from the end toward the beginning.  In other words, the cursor is
99268** configured to use Prev, not Next.
99269*/
99270case OP_SeekEnd:             /* ncycle */
99271case OP_Last: {              /* jump0, ncycle */
99272  VdbeCursor *pC;
99273  BtCursor *pCrsr;
99274  int res;
99275
99276  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99277  pC = p->apCsr[pOp->p1];
99278  assert( pC!=0 );
99279  assert( pC->eCurType==CURTYPE_BTREE );
99280  pCrsr = pC->uc.pCursor;
99281  res = 0;
99282  assert( pCrsr!=0 );
99283#ifdef SQLITE_DEBUG
99284  pC->seekOp = pOp->opcode;
99285#endif
99286  if( pOp->opcode==OP_SeekEnd ){
99287    assert( pOp->p2==0 );
99288    pC->seekResult = -1;
99289    if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
99290      break;
99291    }
99292  }
99293  rc = sqlite3BtreeLast(pCrsr, &res);
99294  pC->nullRow = (u8)res;
99295  pC->deferredMoveto = 0;
99296  pC->cacheStatus = CACHE_STALE;
99297  if( rc ) goto abort_due_to_error;
99298  if( pOp->p2>0 ){
99299    VdbeBranchTaken(res!=0,2);
99300    if( res ) goto jump_to_p2;
99301  }
99302  break;
99303}
99304
99305/* Opcode: IfSizeBetween P1 P2 P3 P4 *
99306**
99307** Let N be the approximate number of rows in the table or index
99308** with cursor P1 and let X be 10*log2(N) if N is positive or -1
99309** if N is zero.
99310**
99311** Jump to P2 if X is in between P3 and P4, inclusive.
99312*/
99313case OP_IfSizeBetween: {        /* jump */
99314  VdbeCursor *pC;
99315  BtCursor *pCrsr;
99316  int res;
99317  i64 sz;
99318
99319  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99320  assert( pOp->p4type==P4_INT32 );
99321  assert( pOp->p3>=-1 && pOp->p3<=640*2 );
99322  assert( pOp->p4.i>=-1 && pOp->p4.i<=640*2 );
99323  pC = p->apCsr[pOp->p1];
99324  assert( pC!=0 );
99325  pCrsr = pC->uc.pCursor;
99326  assert( pCrsr );
99327  rc = sqlite3BtreeFirst(pCrsr, &res);
99328  if( rc ) goto abort_due_to_error;
99329  if( res!=0 ){
99330    sz = -1;  /* -Infinity encoding */
99331  }else{
99332    sz = sqlite3BtreeRowCountEst(pCrsr);
99333    assert( sz>0 );
99334    sz = sqlite3LogEst((u64)sz);
99335  }
99336  res = sz>=pOp->p3 && sz<=pOp->p4.i;
99337  VdbeBranchTaken(res!=0,2);
99338  if( res ) goto jump_to_p2;
99339  break;
99340}
99341
99342
99343/* Opcode: SorterSort P1 P2 * * *
99344**
99345** After all records have been inserted into the Sorter object
99346** identified by P1, invoke this opcode to actually do the sorting.
99347** Jump to P2 if there are no records to be sorted.
99348**
99349** This opcode is an alias for OP_Sort and OP_Rewind that is used
99350** for Sorter objects.
99351*/
99352/* Opcode: Sort P1 P2 * * *
99353**
99354** This opcode does exactly the same thing as OP_Rewind except that
99355** it increments an undocumented global variable used for testing.
99356**
99357** Sorting is accomplished by writing records into a sorting index,
99358** then rewinding that index and playing it back from beginning to
99359** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
99360** rewinding so that the global variable will be incremented and
99361** regression tests can determine whether or not the optimizer is
99362** correctly optimizing out sorts.
99363*/
99364case OP_SorterSort:    /* jump ncycle */
99365case OP_Sort: {        /* jump ncycle */
99366#ifdef SQLITE_TEST
99367  sqlite3_sort_count++;
99368  sqlite3_search_count--;
99369#endif
99370  p->aCounter[SQLITE_STMTSTATUS_SORT]++;
99371  /* Fall through into OP_Rewind */
99372  /* no break */ deliberate_fall_through
99373}
99374/* Opcode: Rewind P1 P2 * * *
99375**
99376** The next use of the Rowid or Column or Next instruction for P1
99377** will refer to the first entry in the database table or index.
99378** If the table or index is empty, jump immediately to P2.
99379** If the table or index is not empty, fall through to the following
99380** instruction.
99381**
99382** If P2 is zero, that is an assertion that the P1 table is never
99383** empty and hence the jump will never be taken.
99384**
99385** This opcode leaves the cursor configured to move in forward order,
99386** from the beginning toward the end.  In other words, the cursor is
99387** configured to use Next, not Prev.
99388*/
99389case OP_Rewind: {        /* jump0, ncycle */
99390  VdbeCursor *pC;
99391  BtCursor *pCrsr;
99392  int res;
99393
99394  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99395  assert( pOp->p5==0 );
99396  assert( pOp->p2>=0 && pOp->p2<p->nOp );
99397
99398  pC = p->apCsr[pOp->p1];
99399  assert( pC!=0 );
99400  assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
99401  res = 1;
99402#ifdef SQLITE_DEBUG
99403  pC->seekOp = OP_Rewind;
99404#endif
99405  if( isSorter(pC) ){
99406    rc = sqlite3VdbeSorterRewind(pC, &res);
99407  }else{
99408    assert( pC->eCurType==CURTYPE_BTREE );
99409    pCrsr = pC->uc.pCursor;
99410    assert( pCrsr );
99411    rc = sqlite3BtreeFirst(pCrsr, &res);
99412    pC->deferredMoveto = 0;
99413    pC->cacheStatus = CACHE_STALE;
99414  }
99415  if( rc ) goto abort_due_to_error;
99416  pC->nullRow = (u8)res;
99417  if( pOp->p2>0 ){
99418    VdbeBranchTaken(res!=0,2);
99419    if( res ) goto jump_to_p2;
99420  }
99421  break;
99422}
99423
99424/* Opcode: Next P1 P2 P3 * P5
99425**
99426** Advance cursor P1 so that it points to the next key/data pair in its
99427** table or index.  If there are no more key/value pairs then fall through
99428** to the following instruction.  But if the cursor advance was successful,
99429** jump immediately to P2.
99430**
99431** The Next opcode is only valid following an SeekGT, SeekGE, or
99432** OP_Rewind opcode used to position the cursor.  Next is not allowed
99433** to follow SeekLT, SeekLE, or OP_Last.
99434**
99435** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
99436** been opened prior to this opcode or the program will segfault.
99437**
99438** The P3 value is a hint to the btree implementation. If P3==1, that
99439** means P1 is an SQL index and that this instruction could have been
99440** omitted if that index had been unique.  P3 is usually 0.  P3 is
99441** always either 0 or 1.
99442**
99443** If P5 is positive and the jump is taken, then event counter
99444** number P5-1 in the prepared statement is incremented.
99445**
99446** See also: Prev
99447*/
99448/* Opcode: Prev P1 P2 P3 * P5
99449**
99450** Back up cursor P1 so that it points to the previous key/data pair in its
99451** table or index.  If there is no previous key/value pairs then fall through
99452** to the following instruction.  But if the cursor backup was successful,
99453** jump immediately to P2.
99454**
99455**
99456** The Prev opcode is only valid following an SeekLT, SeekLE, or
99457** OP_Last opcode used to position the cursor.  Prev is not allowed
99458** to follow SeekGT, SeekGE, or OP_Rewind.
99459**
99460** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
99461** not open then the behavior is undefined.
99462**
99463** The P3 value is a hint to the btree implementation. If P3==1, that
99464** means P1 is an SQL index and that this instruction could have been
99465** omitted if that index had been unique.  P3 is usually 0.  P3 is
99466** always either 0 or 1.
99467**
99468** If P5 is positive and the jump is taken, then event counter
99469** number P5-1 in the prepared statement is incremented.
99470*/
99471/* Opcode: SorterNext P1 P2 * * P5
99472**
99473** This opcode works just like OP_Next except that P1 must be a
99474** sorter object for which the OP_SorterSort opcode has been
99475** invoked.  This opcode advances the cursor to the next sorted
99476** record, or jumps to P2 if there are no more sorted records.
99477*/
99478case OP_SorterNext: {  /* jump */
99479  VdbeCursor *pC;
99480
99481  pC = p->apCsr[pOp->p1];
99482  assert( isSorter(pC) );
99483  rc = sqlite3VdbeSorterNext(db, pC);
99484  goto next_tail;
99485
99486case OP_Prev:          /* jump, ncycle */
99487  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99488  assert( pOp->p5==0
99489       || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
99490       || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
99491  pC = p->apCsr[pOp->p1];
99492  assert( pC!=0 );
99493  assert( pC->deferredMoveto==0 );
99494  assert( pC->eCurType==CURTYPE_BTREE );
99495  assert( pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
99496       || pC->seekOp==OP_Last   || pC->seekOp==OP_IfNoHope
99497       || pC->seekOp==OP_NullRow);
99498  rc = sqlite3BtreePrevious(pC->uc.pCursor, pOp->p3);
99499  goto next_tail;
99500
99501case OP_Next:          /* jump, ncycle */
99502  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99503  assert( pOp->p5==0
99504       || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
99505       || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
99506  pC = p->apCsr[pOp->p1];
99507  assert( pC!=0 );
99508  assert( pC->deferredMoveto==0 );
99509  assert( pC->eCurType==CURTYPE_BTREE );
99510  assert( pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
99511       || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
99512       || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid
99513       || pC->seekOp==OP_IfNoHope);
99514  rc = sqlite3BtreeNext(pC->uc.pCursor, pOp->p3);
99515
99516next_tail:
99517  pC->cacheStatus = CACHE_STALE;
99518  VdbeBranchTaken(rc==SQLITE_OK,2);
99519  if( rc==SQLITE_OK ){
99520    pC->nullRow = 0;
99521    p->aCounter[pOp->p5]++;
99522#ifdef SQLITE_TEST
99523    sqlite3_search_count++;
99524#endif
99525    goto jump_to_p2_and_check_for_interrupt;
99526  }
99527  if( rc!=SQLITE_DONE ) goto abort_due_to_error;
99528  rc = SQLITE_OK;
99529  pC->nullRow = 1;
99530  goto check_for_interrupt;
99531}
99532
99533/* Opcode: IdxInsert P1 P2 P3 P4 P5
99534** Synopsis: key=r[P2]
99535**
99536** Register P2 holds an SQL index key made using the
99537** MakeRecord instructions.  This opcode writes that key
99538** into the index P1.  Data for the entry is nil.
99539**
99540** If P4 is not zero, then it is the number of values in the unpacked
99541** key of reg(P2).  In that case, P3 is the index of the first register
99542** for the unpacked key.  The availability of the unpacked key can sometimes
99543** be an optimization.
99544**
99545** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
99546** that this insert is likely to be an append.
99547**
99548** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
99549** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
99550** then the change counter is unchanged.
99551**
99552** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
99553** run faster by avoiding an unnecessary seek on cursor P1.  However,
99554** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
99555** seeks on the cursor or if the most recent seek used a key equivalent
99556** to P2.
99557**
99558** This instruction only works for indices.  The equivalent instruction
99559** for tables is OP_Insert.
99560*/
99561case OP_IdxInsert: {        /* in2 */
99562  VdbeCursor *pC;
99563  BtreePayload x;
99564
99565  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99566  pC = p->apCsr[pOp->p1];
99567  sqlite3VdbeIncrWriteCounter(p, pC);
99568  assert( pC!=0 );
99569  assert( !isSorter(pC) );
99570  pIn2 = &aMem[pOp->p2];
99571  assert( (pIn2->flags & MEM_Blob) || (pOp->p5 & OPFLAG_PREFORMAT) );
99572  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
99573  assert( pC->eCurType==CURTYPE_BTREE );
99574  assert( pC->isTable==0 );
99575  rc = ExpandBlob(pIn2);
99576  if( rc ) goto abort_due_to_error;
99577  x.nKey = pIn2->n;
99578  x.pKey = pIn2->z;
99579  x.aMem = aMem + pOp->p3;
99580  x.nMem = (u16)pOp->p4.i;
99581  rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
99582       (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
99583      ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
99584      );
99585  assert( pC->deferredMoveto==0 );
99586  pC->cacheStatus = CACHE_STALE;
99587  if( rc) goto abort_due_to_error;
99588  break;
99589}
99590
99591/* Opcode: SorterInsert P1 P2 * * *
99592** Synopsis: key=r[P2]
99593**
99594** Register P2 holds an SQL index key made using the
99595** MakeRecord instructions.  This opcode writes that key
99596** into the sorter P1.  Data for the entry is nil.
99597*/
99598case OP_SorterInsert: {     /* in2 */
99599  VdbeCursor *pC;
99600
99601  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99602  pC = p->apCsr[pOp->p1];
99603  sqlite3VdbeIncrWriteCounter(p, pC);
99604  assert( pC!=0 );
99605  assert( isSorter(pC) );
99606  pIn2 = &aMem[pOp->p2];
99607  assert( pIn2->flags & MEM_Blob );
99608  assert( pC->isTable==0 );
99609  rc = ExpandBlob(pIn2);
99610  if( rc ) goto abort_due_to_error;
99611  rc = sqlite3VdbeSorterWrite(pC, pIn2);
99612  if( rc) goto abort_due_to_error;
99613  break;
99614}
99615
99616/* Opcode: IdxDelete P1 P2 P3 * P5
99617** Synopsis: key=r[P2@P3]
99618**
99619** The content of P3 registers starting at register P2 form
99620** an unpacked index key. This opcode removes that entry from the
99621** index opened by cursor P1.
99622**
99623** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
99624** if no matching index entry is found.  This happens when running
99625** an UPDATE or DELETE statement and the index entry to be updated
99626** or deleted is not found.  For some uses of IdxDelete
99627** (example:  the EXCEPT operator) it does not matter that no matching
99628** entry is found.  For those cases, P5 is zero.  Also, do not raise
99629** this (self-correcting and non-critical) error if in writable_schema mode.
99630*/
99631case OP_IdxDelete: {
99632  VdbeCursor *pC;
99633  BtCursor *pCrsr;
99634  int res;
99635  UnpackedRecord r;
99636
99637  assert( pOp->p3>0 );
99638  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
99639  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99640  pC = p->apCsr[pOp->p1];
99641  assert( pC!=0 );
99642  assert( pC->eCurType==CURTYPE_BTREE );
99643  sqlite3VdbeIncrWriteCounter(p, pC);
99644  pCrsr = pC->uc.pCursor;
99645  assert( pCrsr!=0 );
99646  r.pKeyInfo = pC->pKeyInfo;
99647  r.nField = (u16)pOp->p3;
99648  r.default_rc = 0;
99649  r.aMem = &aMem[pOp->p2];
99650  rc = sqlite3BtreeIndexMoveto(pCrsr, &r, &res);
99651  if( rc ) goto abort_due_to_error;
99652  if( res==0 ){
99653    rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
99654    if( rc ) goto abort_due_to_error;
99655  }else if( pOp->p5 && !sqlite3WritableSchema(db) ){
99656    rc = sqlite3ReportError(SQLITE_CORRUPT_INDEX, __LINE__, "index corruption");
99657    goto abort_due_to_error;
99658  }
99659  assert( pC->deferredMoveto==0 );
99660  pC->cacheStatus = CACHE_STALE;
99661  pC->seekResult = 0;
99662  break;
99663}
99664
99665/* Opcode: DeferredSeek P1 * P3 P4 *
99666** Synopsis: Move P3 to P1.rowid if needed
99667**
99668** P1 is an open index cursor and P3 is a cursor on the corresponding
99669** table.  This opcode does a deferred seek of the P3 table cursor
99670** to the row that corresponds to the current row of P1.
99671**
99672** This is a deferred seek.  Nothing actually happens until
99673** the cursor is used to read a record.  That way, if no reads
99674** occur, no unnecessary I/O happens.
99675**
99676** P4 may be an array of integers (type P4_INTARRAY) containing
99677** one entry for each column in the P3 table.  If array entry a(i)
99678** is non-zero, then reading column a(i)-1 from cursor P3 is
99679** equivalent to performing the deferred seek and then reading column i
99680** from P1.  This information is stored in P3 and used to redirect
99681** reads against P3 over to P1, thus possibly avoiding the need to
99682** seek and read cursor P3.
99683*/
99684/* Opcode: IdxRowid P1 P2 * * *
99685** Synopsis: r[P2]=rowid
99686**
99687** Write into register P2 an integer which is the last entry in the record at
99688** the end of the index key pointed to by cursor P1.  This integer should be
99689** the rowid of the table entry to which this index entry points.
99690**
99691** See also: Rowid, MakeRecord.
99692*/
99693case OP_DeferredSeek:         /* ncycle */
99694case OP_IdxRowid: {           /* out2, ncycle */
99695  VdbeCursor *pC;             /* The P1 index cursor */
99696  VdbeCursor *pTabCur;        /* The P2 table cursor (OP_DeferredSeek only) */
99697  i64 rowid;                  /* Rowid that P1 current points to */
99698
99699  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99700  pC = p->apCsr[pOp->p1];
99701  assert( pC!=0 );
99702  assert( pC->eCurType==CURTYPE_BTREE || IsNullCursor(pC) );
99703  assert( pC->uc.pCursor!=0 );
99704  assert( pC->isTable==0 || IsNullCursor(pC) );
99705  assert( pC->deferredMoveto==0 );
99706  assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
99707
99708  /* The IdxRowid and Seek opcodes are combined because of the commonality
99709  ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
99710  rc = sqlite3VdbeCursorRestore(pC);
99711
99712  /* sqlite3VdbeCursorRestore() may fail if the cursor has been disturbed
99713  ** since it was last positioned and an error (e.g. OOM or an IO error)
99714  ** occurs while trying to reposition it. */
99715  if( rc!=SQLITE_OK ) goto abort_due_to_error;
99716
99717  if( !pC->nullRow ){
99718    rowid = 0;  /* Not needed.  Only used to silence a warning. */
99719    rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
99720    if( rc!=SQLITE_OK ){
99721      goto abort_due_to_error;
99722    }
99723    if( pOp->opcode==OP_DeferredSeek ){
99724      assert( pOp->p3>=0 && pOp->p3<p->nCursor );
99725      pTabCur = p->apCsr[pOp->p3];
99726      assert( pTabCur!=0 );
99727      assert( pTabCur->eCurType==CURTYPE_BTREE );
99728      assert( pTabCur->uc.pCursor!=0 );
99729      assert( pTabCur->isTable );
99730      pTabCur->nullRow = 0;
99731      pTabCur->movetoTarget = rowid;
99732      pTabCur->deferredMoveto = 1;
99733      pTabCur->cacheStatus = CACHE_STALE;
99734      assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
99735      assert( !pTabCur->isEphemeral );
99736      pTabCur->ub.aAltMap = pOp->p4.ai;
99737      assert( !pC->isEphemeral );
99738      pTabCur->pAltCursor = pC;
99739    }else{
99740      pOut = out2Prerelease(p, pOp);
99741      pOut->u.i = rowid;
99742    }
99743  }else{
99744    assert( pOp->opcode==OP_IdxRowid );
99745    sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
99746  }
99747  break;
99748}
99749
99750/* Opcode: FinishSeek P1 * * * *
99751**
99752** If cursor P1 was previously moved via OP_DeferredSeek, complete that
99753** seek operation now, without further delay.  If the cursor seek has
99754** already occurred, this instruction is a no-op.
99755*/
99756case OP_FinishSeek: {        /* ncycle */
99757  VdbeCursor *pC;            /* The P1 index cursor */
99758
99759  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99760  pC = p->apCsr[pOp->p1];
99761  if( pC->deferredMoveto ){
99762    rc = sqlite3VdbeFinishMoveto(pC);
99763    if( rc ) goto abort_due_to_error;
99764  }
99765  break;
99766}
99767
99768/* Opcode: IdxGE P1 P2 P3 P4 *
99769** Synopsis: key=r[P3@P4]
99770**
99771** The P4 register values beginning with P3 form an unpacked index
99772** key that omits the PRIMARY KEY.  Compare this key value against the index
99773** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
99774** fields at the end.
99775**
99776** If the P1 index entry is greater than or equal to the key value
99777** then jump to P2.  Otherwise fall through to the next instruction.
99778*/
99779/* Opcode: IdxGT P1 P2 P3 P4 *
99780** Synopsis: key=r[P3@P4]
99781**
99782** The P4 register values beginning with P3 form an unpacked index
99783** key that omits the PRIMARY KEY.  Compare this key value against the index
99784** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
99785** fields at the end.
99786**
99787** If the P1 index entry is greater than the key value
99788** then jump to P2.  Otherwise fall through to the next instruction.
99789*/
99790/* Opcode: IdxLT P1 P2 P3 P4 *
99791** Synopsis: key=r[P3@P4]
99792**
99793** The P4 register values beginning with P3 form an unpacked index
99794** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
99795** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
99796** ROWID on the P1 index.
99797**
99798** If the P1 index entry is less than the key value then jump to P2.
99799** Otherwise fall through to the next instruction.
99800*/
99801/* Opcode: IdxLE P1 P2 P3 P4 *
99802** Synopsis: key=r[P3@P4]
99803**
99804** The P4 register values beginning with P3 form an unpacked index
99805** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
99806** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
99807** ROWID on the P1 index.
99808**
99809** If the P1 index entry is less than or equal to the key value then jump
99810** to P2. Otherwise fall through to the next instruction.
99811*/
99812case OP_IdxLE:          /* jump, ncycle */
99813case OP_IdxGT:          /* jump, ncycle */
99814case OP_IdxLT:          /* jump, ncycle */
99815case OP_IdxGE:  {       /* jump, ncycle */
99816  VdbeCursor *pC;
99817  int res;
99818  UnpackedRecord r;
99819
99820  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99821  pC = p->apCsr[pOp->p1];
99822  assert( pC!=0 );
99823  assert( pC->isOrdered );
99824  assert( pC->eCurType==CURTYPE_BTREE );
99825  assert( pC->uc.pCursor!=0);
99826  assert( pC->deferredMoveto==0 );
99827  assert( pOp->p4type==P4_INT32 );
99828  r.pKeyInfo = pC->pKeyInfo;
99829  r.nField = (u16)pOp->p4.i;
99830  if( pOp->opcode<OP_IdxLT ){
99831    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
99832    r.default_rc = -1;
99833  }else{
99834    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
99835    r.default_rc = 0;
99836  }
99837  r.aMem = &aMem[pOp->p3];
99838#ifdef SQLITE_DEBUG
99839  {
99840    int i;
99841    for(i=0; i<r.nField; i++){
99842      assert( memIsValid(&r.aMem[i]) );
99843      REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
99844    }
99845  }
99846#endif
99847
99848  /* Inlined version of sqlite3VdbeIdxKeyCompare() */
99849  {
99850    i64 nCellKey = 0;
99851    BtCursor *pCur;
99852    Mem m;
99853
99854    assert( pC->eCurType==CURTYPE_BTREE );
99855    pCur = pC->uc.pCursor;
99856    assert( sqlite3BtreeCursorIsValid(pCur) );
99857    nCellKey = sqlite3BtreePayloadSize(pCur);
99858    /* nCellKey will always be between 0 and 0xffffffff because of the way
99859    ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
99860    if( nCellKey<=0 || nCellKey>0x7fffffff ){
99861      rc = SQLITE_CORRUPT_BKPT;
99862      goto abort_due_to_error;
99863    }
99864    sqlite3VdbeMemInit(&m, db, 0);
99865    rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
99866    if( rc ) goto abort_due_to_error;
99867    res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, &r, 0);
99868    sqlite3VdbeMemReleaseMalloc(&m);
99869  }
99870  /* End of inlined sqlite3VdbeIdxKeyCompare() */
99871
99872  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
99873  if( (pOp->opcode&1)==(OP_IdxLT&1) ){
99874    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
99875    res = -res;
99876  }else{
99877    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
99878    res++;
99879  }
99880  VdbeBranchTaken(res>0,2);
99881  assert( rc==SQLITE_OK );
99882  if( res>0 ) goto jump_to_p2;
99883  break;
99884}
99885
99886/* Opcode: Destroy P1 P2 P3 * *
99887**
99888** Delete an entire database table or index whose root page in the database
99889** file is given by P1.
99890**
99891** The table being destroyed is in the main database file if P3==0.  If
99892** P3==1 then the table to be destroyed is in the auxiliary database file
99893** that is used to store tables create using CREATE TEMPORARY TABLE.
99894**
99895** If AUTOVACUUM is enabled then it is possible that another root page
99896** might be moved into the newly deleted root page in order to keep all
99897** root pages contiguous at the beginning of the database.  The former
99898** value of the root page that moved - its value before the move occurred -
99899** is stored in register P2. If no page movement was required (because the
99900** table being dropped was already the last one in the database) then a
99901** zero is stored in register P2.  If AUTOVACUUM is disabled then a zero
99902** is stored in register P2.
99903**
99904** This opcode throws an error if there are any active reader VMs when
99905** it is invoked. This is done to avoid the difficulty associated with
99906** updating existing cursors when a root page is moved in an AUTOVACUUM
99907** database. This error is thrown even if the database is not an AUTOVACUUM
99908** db in order to avoid introducing an incompatibility between autovacuum
99909** and non-autovacuum modes.
99910**
99911** See also: Clear
99912*/
99913case OP_Destroy: {     /* out2 */
99914  int iMoved;
99915  int iDb;
99916
99917  sqlite3VdbeIncrWriteCounter(p, 0);
99918  assert( p->readOnly==0 );
99919  assert( pOp->p1>1 );
99920  pOut = out2Prerelease(p, pOp);
99921  pOut->flags = MEM_Null;
99922  if( db->nVdbeRead > db->nVDestroy+1 ){
99923    rc = SQLITE_LOCKED;
99924    p->errorAction = OE_Abort;
99925    goto abort_due_to_error;
99926  }else{
99927    iDb = pOp->p3;
99928    assert( DbMaskTest(p->btreeMask, iDb) );
99929    iMoved = 0;  /* Not needed.  Only to silence a warning. */
99930    rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
99931    pOut->flags = MEM_Int;
99932    pOut->u.i = iMoved;
99933    if( rc ) goto abort_due_to_error;
99934#ifndef SQLITE_OMIT_AUTOVACUUM
99935    if( iMoved!=0 ){
99936      sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
99937      /* All OP_Destroy operations occur on the same btree */
99938      assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
99939      resetSchemaOnFault = iDb+1;
99940    }
99941#endif
99942  }
99943  break;
99944}
99945
99946/* Opcode: Clear P1 P2 P3
99947**
99948** Delete all contents of the database table or index whose root page
99949** in the database file is given by P1.  But, unlike Destroy, do not
99950** remove the table or index from the database file.
99951**
99952** The table being cleared is in the main database file if P2==0.  If
99953** P2==1 then the table to be cleared is in the auxiliary database file
99954** that is used to store tables create using CREATE TEMPORARY TABLE.
99955**
99956** If the P3 value is non-zero, then the row change count is incremented
99957** by the number of rows in the table being cleared. If P3 is greater
99958** than zero, then the value stored in register P3 is also incremented
99959** by the number of rows in the table being cleared.
99960**
99961** See also: Destroy
99962*/
99963case OP_Clear: {
99964  i64 nChange;
99965
99966  sqlite3VdbeIncrWriteCounter(p, 0);
99967  nChange = 0;
99968  assert( p->readOnly==0 );
99969  assert( DbMaskTest(p->btreeMask, pOp->p2) );
99970  rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, (u32)pOp->p1, &nChange);
99971  if( pOp->p3 ){
99972    p->nChange += nChange;
99973    if( pOp->p3>0 ){
99974      assert( memIsValid(&aMem[pOp->p3]) );
99975      memAboutToChange(p, &aMem[pOp->p3]);
99976      aMem[pOp->p3].u.i += nChange;
99977    }
99978  }
99979  if( rc ) goto abort_due_to_error;
99980  break;
99981}
99982
99983/* Opcode: ResetSorter P1 * * * *
99984**
99985** Delete all contents from the ephemeral table or sorter
99986** that is open on cursor P1.
99987**
99988** This opcode only works for cursors used for sorting and
99989** opened with OP_OpenEphemeral or OP_SorterOpen.
99990*/
99991case OP_ResetSorter: {
99992  VdbeCursor *pC;
99993
99994  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99995  pC = p->apCsr[pOp->p1];
99996  assert( pC!=0 );
99997  if( isSorter(pC) ){
99998    sqlite3VdbeSorterReset(db, pC->uc.pSorter);
99999  }else{
100000    assert( pC->eCurType==CURTYPE_BTREE );
100001    assert( pC->isEphemeral );
100002    rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
100003    if( rc ) goto abort_due_to_error;
100004  }
100005  break;
100006}
100007
100008/* Opcode: CreateBtree P1 P2 P3 * *
100009** Synopsis: r[P2]=root iDb=P1 flags=P3
100010**
100011** Allocate a new b-tree in the main database file if P1==0 or in the
100012** TEMP database file if P1==1 or in an attached database if
100013** P1>1.  The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
100014** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
100015** The root page number of the new b-tree is stored in register P2.
100016*/
100017case OP_CreateBtree: {          /* out2 */
100018  Pgno pgno;
100019  Db *pDb;
100020
100021  sqlite3VdbeIncrWriteCounter(p, 0);
100022  pOut = out2Prerelease(p, pOp);
100023  pgno = 0;
100024  assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
100025  assert( pOp->p1>=0 && pOp->p1<db->nDb );
100026  assert( DbMaskTest(p->btreeMask, pOp->p1) );
100027  assert( p->readOnly==0 );
100028  pDb = &db->aDb[pOp->p1];
100029  assert( pDb->pBt!=0 );
100030  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
100031  if( rc ) goto abort_due_to_error;
100032  pOut->u.i = pgno;
100033  break;
100034}
100035
100036/* Opcode: SqlExec P1 P2 * P4 *
100037**
100038** Run the SQL statement or statements specified in the P4 string.
100039**
100040** The P1 parameter is a bitmask of options:
100041**
100042**    0x0001     Disable Auth and Trace callbacks while the statements
100043**               in P4 are running.
100044**
100045**    0x0002     Set db->nAnalysisLimit to P2 while the statements in
100046**               P4 are running.
100047**
100048*/
100049case OP_SqlExec: {
100050  char *zErr;
100051#ifndef SQLITE_OMIT_AUTHORIZATION
100052  sqlite3_xauth xAuth;
100053#endif
100054  u8 mTrace;
100055  int savedAnalysisLimit;
100056
100057  sqlite3VdbeIncrWriteCounter(p, 0);
100058  db->nSqlExec++;
100059  zErr = 0;
100060#ifndef SQLITE_OMIT_AUTHORIZATION
100061  xAuth = db->xAuth;
100062#endif
100063  mTrace = db->mTrace;
100064  savedAnalysisLimit = db->nAnalysisLimit;
100065  if( pOp->p1 & 0x0001 ){
100066#ifndef SQLITE_OMIT_AUTHORIZATION
100067    db->xAuth = 0;
100068#endif
100069    db->mTrace = 0;
100070  }
100071  if( pOp->p1 & 0x0002 ){
100072    db->nAnalysisLimit = pOp->p2;
100073  }
100074  rc = sqlite3_exec(db, pOp->p4.z, 0, 0, &zErr);
100075  db->nSqlExec--;
100076#ifndef SQLITE_OMIT_AUTHORIZATION
100077  db->xAuth = xAuth;
100078#endif
100079  db->mTrace = mTrace;
100080  db->nAnalysisLimit = savedAnalysisLimit;
100081  if( zErr || rc ){
100082    sqlite3VdbeError(p, "%s", zErr);
100083    sqlite3_free(zErr);
100084    if( rc==SQLITE_NOMEM ) goto no_mem;
100085    goto abort_due_to_error;
100086  }
100087  break;
100088}
100089
100090/* Opcode: ParseSchema P1 * * P4 *
100091**
100092** Read and parse all entries from the schema table of database P1
100093** that match the WHERE clause P4.  If P4 is a NULL pointer, then the
100094** entire schema for P1 is reparsed.
100095**
100096** This opcode invokes the parser to create a new virtual machine,
100097** then runs the new virtual machine.  It is thus a re-entrant opcode.
100098*/
100099case OP_ParseSchema: {
100100  int iDb;
100101  const char *zSchema;
100102  char *zSql;
100103  InitData initData;
100104
100105  /* Any prepared statement that invokes this opcode will hold mutexes
100106  ** on every btree.  This is a prerequisite for invoking
100107  ** sqlite3InitCallback().
100108  */
100109#ifdef SQLITE_DEBUG
100110  for(iDb=0; iDb<db->nDb; iDb++){
100111    assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
100112  }
100113#endif
100114
100115  iDb = pOp->p1;
100116  assert( iDb>=0 && iDb<db->nDb );
100117  assert( DbHasProperty(db, iDb, DB_SchemaLoaded)
100118           || db->mallocFailed
100119           || (CORRUPT_DB && (db->flags & SQLITE_NoSchemaError)!=0) );
100120
100121#ifndef SQLITE_OMIT_ALTERTABLE
100122  if( pOp->p4.z==0 ){
100123    sqlite3SchemaClear(db->aDb[iDb].pSchema);
100124    db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
100125    rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
100126    db->mDbFlags |= DBFLAG_SchemaChange;
100127    p->expired = 0;
100128  }else
100129#endif
100130  {
100131    zSchema = LEGACY_SCHEMA_TABLE;
100132    initData.db = db;
100133    initData.iDb = iDb;
100134    initData.pzErrMsg = &p->zErrMsg;
100135    initData.mInitFlags = 0;
100136    initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt);
100137    zSql = sqlite3MPrintf(db,
100138       "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid",
100139       db->aDb[iDb].zDbSName, zSchema, pOp->p4.z);
100140    if( zSql==0 ){
100141      rc = SQLITE_NOMEM_BKPT;
100142    }else{
100143      assert( db->init.busy==0 );
100144      db->init.busy = 1;
100145      initData.rc = SQLITE_OK;
100146      initData.nInitRow = 0;
100147      assert( !db->mallocFailed );
100148      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
100149      if( rc==SQLITE_OK ) rc = initData.rc;
100150      if( rc==SQLITE_OK && initData.nInitRow==0 ){
100151        /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
100152        ** at least one SQL statement. Any less than that indicates that
100153        ** the sqlite_schema table is corrupt. */
100154        rc = SQLITE_CORRUPT_BKPT;
100155      }
100156      sqlite3DbFreeNN(db, zSql);
100157      db->init.busy = 0;
100158    }
100159  }
100160  if( rc ){
100161    sqlite3ResetAllSchemasOfConnection(db);
100162    if( rc==SQLITE_NOMEM ){
100163      goto no_mem;
100164    }
100165    goto abort_due_to_error;
100166  }
100167  break;
100168}
100169
100170#if !defined(SQLITE_OMIT_ANALYZE)
100171/* Opcode: LoadAnalysis P1 * * * *
100172**
100173** Read the sqlite_stat1 table for database P1 and load the content
100174** of that table into the internal index hash table.  This will cause
100175** the analysis to be used when preparing all subsequent queries.
100176*/
100177case OP_LoadAnalysis: {
100178  assert( pOp->p1>=0 && pOp->p1<db->nDb );
100179  rc = sqlite3AnalysisLoad(db, pOp->p1);
100180  if( rc ) goto abort_due_to_error;
100181  break;
100182}
100183#endif /* !defined(SQLITE_OMIT_ANALYZE) */
100184
100185/* Opcode: DropTable P1 * * P4 *
100186**
100187** Remove the internal (in-memory) data structures that describe
100188** the table named P4 in database P1.  This is called after a table
100189** is dropped from disk (using the Destroy opcode) in order to keep
100190** the internal representation of the
100191** schema consistent with what is on disk.
100192*/
100193case OP_DropTable: {
100194  sqlite3VdbeIncrWriteCounter(p, 0);
100195  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
100196  break;
100197}
100198
100199/* Opcode: DropIndex P1 * * P4 *
100200**
100201** Remove the internal (in-memory) data structures that describe
100202** the index named P4 in database P1.  This is called after an index
100203** is dropped from disk (using the Destroy opcode)
100204** in order to keep the internal representation of the
100205** schema consistent with what is on disk.
100206*/
100207case OP_DropIndex: {
100208  sqlite3VdbeIncrWriteCounter(p, 0);
100209  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
100210  break;
100211}
100212
100213/* Opcode: DropTrigger P1 * * P4 *
100214**
100215** Remove the internal (in-memory) data structures that describe
100216** the trigger named P4 in database P1.  This is called after a trigger
100217** is dropped from disk (using the Destroy opcode) in order to keep
100218** the internal representation of the
100219** schema consistent with what is on disk.
100220*/
100221case OP_DropTrigger: {
100222  sqlite3VdbeIncrWriteCounter(p, 0);
100223  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
100224  break;
100225}
100226
100227
100228#ifndef SQLITE_OMIT_INTEGRITY_CHECK
100229/* Opcode: IntegrityCk P1 P2 P3 P4 P5
100230**
100231** Do an analysis of the currently open database.  Store in
100232** register (P1+1) the text of an error message describing any problems.
100233** If no problems are found, store a NULL in register (P1+1).
100234**
100235** The register (P1) contains one less than the maximum number of allowed
100236** errors.  At most reg(P1) errors will be reported.
100237** In other words, the analysis stops as soon as reg(P1) errors are
100238** seen.  Reg(P1) is updated with the number of errors remaining.
100239**
100240** The root page numbers of all tables in the database are integers
100241** stored in P4_INTARRAY argument.
100242**
100243** If P5 is not zero, the check is done on the auxiliary database
100244** file, not the main database file.
100245**
100246** This opcode is used to implement the integrity_check pragma.
100247*/
100248case OP_IntegrityCk: {
100249  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
100250  Pgno *aRoot;    /* Array of rootpage numbers for tables to be checked */
100251  int nErr;       /* Number of errors reported */
100252  char *z;        /* Text of the error report */
100253  Mem *pnErr;     /* Register keeping track of errors remaining */
100254
100255  assert( p->bIsReader );
100256  assert( pOp->p4type==P4_INTARRAY );
100257  nRoot = pOp->p2;
100258  aRoot = pOp->p4.ai;
100259  assert( nRoot>0 );
100260  assert( aRoot!=0 );
100261  assert( aRoot[0]==(Pgno)nRoot );
100262  assert( pOp->p1>0 && (pOp->p1+1)<=(p->nMem+1 - p->nCursor) );
100263  pnErr = &aMem[pOp->p1];
100264  assert( (pnErr->flags & MEM_Int)!=0 );
100265  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
100266  pIn1 = &aMem[pOp->p1+1];
100267  assert( pOp->p5<db->nDb );
100268  assert( DbMaskTest(p->btreeMask, pOp->p5) );
100269  rc = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1],
100270      &aMem[pOp->p3], nRoot, (int)pnErr->u.i+1, &nErr, &z);
100271  sqlite3VdbeMemSetNull(pIn1);
100272  if( nErr==0 ){
100273    assert( z==0 );
100274  }else if( rc ){
100275    sqlite3_free(z);
100276    goto abort_due_to_error;
100277  }else{
100278    pnErr->u.i -= nErr-1;
100279    sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
100280  }
100281  UPDATE_MAX_BLOBSIZE(pIn1);
100282  sqlite3VdbeChangeEncoding(pIn1, encoding);
100283  goto check_for_interrupt;
100284}
100285#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
100286
100287/* Opcode: RowSetAdd P1 P2 * * *
100288** Synopsis: rowset(P1)=r[P2]
100289**
100290** Insert the integer value held by register P2 into a RowSet object
100291** held in register P1.
100292**
100293** An assertion fails if P2 is not an integer.
100294*/
100295case OP_RowSetAdd: {       /* in1, in2 */
100296  pIn1 = &aMem[pOp->p1];
100297  pIn2 = &aMem[pOp->p2];
100298  assert( (pIn2->flags & MEM_Int)!=0 );
100299  if( (pIn1->flags & MEM_Blob)==0 ){
100300    if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
100301  }
100302  assert( sqlite3VdbeMemIsRowSet(pIn1) );
100303  sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
100304  break;
100305}
100306
100307/* Opcode: RowSetRead P1 P2 P3 * *
100308** Synopsis: r[P3]=rowset(P1)
100309**
100310** Extract the smallest value from the RowSet object in P1
100311** and put that value into register P3.
100312** Or, if RowSet object P1 is initially empty, leave P3
100313** unchanged and jump to instruction P2.
100314*/
100315case OP_RowSetRead: {       /* jump, in1, out3 */
100316  i64 val;
100317
100318  pIn1 = &aMem[pOp->p1];
100319  assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
100320  if( (pIn1->flags & MEM_Blob)==0
100321   || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
100322  ){
100323    /* The boolean index is empty */
100324    sqlite3VdbeMemSetNull(pIn1);
100325    VdbeBranchTaken(1,2);
100326    goto jump_to_p2_and_check_for_interrupt;
100327  }else{
100328    /* A value was pulled from the index */
100329    VdbeBranchTaken(0,2);
100330    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
100331  }
100332  goto check_for_interrupt;
100333}
100334
100335/* Opcode: RowSetTest P1 P2 P3 P4
100336** Synopsis: if r[P3] in rowset(P1) goto P2
100337**
100338** Register P3 is assumed to hold a 64-bit integer value. If register P1
100339** contains a RowSet object and that RowSet object contains
100340** the value held in P3, jump to register P2. Otherwise, insert the
100341** integer in P3 into the RowSet and continue on to the
100342** next opcode.
100343**
100344** The RowSet object is optimized for the case where sets of integers
100345** are inserted in distinct phases, which each set contains no duplicates.
100346** Each set is identified by a unique P4 value. The first set
100347** must have P4==0, the final set must have P4==-1, and for all other sets
100348** must have P4>0.
100349**
100350** This allows optimizations: (a) when P4==0 there is no need to test
100351** the RowSet object for P3, as it is guaranteed not to contain it,
100352** (b) when P4==-1 there is no need to insert the value, as it will
100353** never be tested for, and (c) when a value that is part of set X is
100354** inserted, there is no need to search to see if the same value was
100355** previously inserted as part of set X (only if it was previously
100356** inserted as part of some other set).
100357*/
100358case OP_RowSetTest: {                     /* jump, in1, in3 */
100359  int iSet;
100360  int exists;
100361
100362  pIn1 = &aMem[pOp->p1];
100363  pIn3 = &aMem[pOp->p3];
100364  iSet = pOp->p4.i;
100365  assert( pIn3->flags&MEM_Int );
100366
100367  /* If there is anything other than a rowset object in memory cell P1,
100368  ** delete it now and initialize P1 with an empty rowset
100369  */
100370  if( (pIn1->flags & MEM_Blob)==0 ){
100371    if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
100372  }
100373  assert( sqlite3VdbeMemIsRowSet(pIn1) );
100374  assert( pOp->p4type==P4_INT32 );
100375  assert( iSet==-1 || iSet>=0 );
100376  if( iSet ){
100377    exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
100378    VdbeBranchTaken(exists!=0,2);
100379    if( exists ) goto jump_to_p2;
100380  }
100381  if( iSet>=0 ){
100382    sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
100383  }
100384  break;
100385}
100386
100387
100388#ifndef SQLITE_OMIT_TRIGGER
100389
100390/* Opcode: Program P1 P2 P3 P4 P5
100391**
100392** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
100393**
100394** P1 contains the address of the memory cell that contains the first memory
100395** cell in an array of values used as arguments to the sub-program. P2
100396** contains the address to jump to if the sub-program throws an IGNORE
100397** exception using the RAISE() function. P2 might be zero, if there is
100398** no possibility that an IGNORE exception will be raised.
100399** Register P3 contains the address
100400** of a memory cell in this (the parent) VM that is used to allocate the
100401** memory required by the sub-vdbe at runtime.
100402**
100403** P4 is a pointer to the VM containing the trigger program.
100404**
100405** If P5 is non-zero, then recursive program invocation is enabled.
100406*/
100407case OP_Program: {        /* jump0 */
100408  int nMem;               /* Number of memory registers for sub-program */
100409  int nByte;              /* Bytes of runtime space required for sub-program */
100410  Mem *pRt;               /* Register to allocate runtime space */
100411  Mem *pMem;              /* Used to iterate through memory cells */
100412  Mem *pEnd;              /* Last memory cell in new array */
100413  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
100414  SubProgram *pProgram;   /* Sub-program to execute */
100415  void *t;                /* Token identifying trigger */
100416
100417  pProgram = pOp->p4.pProgram;
100418  pRt = &aMem[pOp->p3];
100419  assert( pProgram->nOp>0 );
100420
100421  /* If the p5 flag is clear, then recursive invocation of triggers is
100422  ** disabled for backwards compatibility (p5 is set if this sub-program
100423  ** is really a trigger, not a foreign key action, and the flag set
100424  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
100425  **
100426  ** It is recursive invocation of triggers, at the SQL level, that is
100427  ** disabled. In some cases a single trigger may generate more than one
100428  ** SubProgram (if the trigger may be executed with more than one different
100429  ** ON CONFLICT algorithm). SubProgram structures associated with a
100430  ** single trigger all have the same value for the SubProgram.token
100431  ** variable.  */
100432  if( pOp->p5 ){
100433    t = pProgram->token;
100434    for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
100435    if( pFrame ) break;
100436  }
100437
100438  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
100439    rc = SQLITE_ERROR;
100440    sqlite3VdbeError(p, "too many levels of trigger recursion");
100441    goto abort_due_to_error;
100442  }
100443
100444  /* Register pRt is used to store the memory required to save the state
100445  ** of the current program, and the memory required at runtime to execute
100446  ** the trigger program. If this trigger has been fired before, then pRt
100447  ** is already allocated. Otherwise, it must be initialized.  */
100448  if( (pRt->flags&MEM_Blob)==0 ){
100449    /* SubProgram.nMem is set to the number of memory cells used by the
100450    ** program stored in SubProgram.aOp. As well as these, one memory
100451    ** cell is required for each cursor used by the program. Set local
100452    ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
100453    */
100454    nMem = pProgram->nMem + pProgram->nCsr;
100455    assert( nMem>0 );
100456    if( pProgram->nCsr==0 ) nMem++;
100457    nByte = ROUND8(sizeof(VdbeFrame))
100458              + nMem * sizeof(Mem)
100459              + pProgram->nCsr * sizeof(VdbeCursor*)
100460              + (pProgram->nOp + 7)/8;
100461    pFrame = sqlite3DbMallocZero(db, nByte);
100462    if( !pFrame ){
100463      goto no_mem;
100464    }
100465    sqlite3VdbeMemRelease(pRt);
100466    pRt->flags = MEM_Blob|MEM_Dyn;
100467    pRt->z = (char*)pFrame;
100468    pRt->n = nByte;
100469    pRt->xDel = sqlite3VdbeFrameMemDel;
100470
100471    pFrame->v = p;
100472    pFrame->nChildMem = nMem;
100473    pFrame->nChildCsr = pProgram->nCsr;
100474    pFrame->pc = (int)(pOp - aOp);
100475    pFrame->aMem = p->aMem;
100476    pFrame->nMem = p->nMem;
100477    pFrame->apCsr = p->apCsr;
100478    pFrame->nCursor = p->nCursor;
100479    pFrame->aOp = p->aOp;
100480    pFrame->nOp = p->nOp;
100481    pFrame->token = pProgram->token;
100482#ifdef SQLITE_DEBUG
100483    pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
100484#endif
100485
100486    pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
100487    for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
100488      pMem->flags = MEM_Undefined;
100489      pMem->db = db;
100490    }
100491  }else{
100492    pFrame = (VdbeFrame*)pRt->z;
100493    assert( pRt->xDel==sqlite3VdbeFrameMemDel );
100494    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
100495        || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
100496    assert( pProgram->nCsr==pFrame->nChildCsr );
100497    assert( (int)(pOp - aOp)==pFrame->pc );
100498  }
100499
100500  p->nFrame++;
100501  pFrame->pParent = p->pFrame;
100502  pFrame->lastRowid = db->lastRowid;
100503  pFrame->nChange = p->nChange;
100504  pFrame->nDbChange = p->db->nChange;
100505  assert( pFrame->pAuxData==0 );
100506  pFrame->pAuxData = p->pAuxData;
100507  p->pAuxData = 0;
100508  p->nChange = 0;
100509  p->pFrame = pFrame;
100510  p->aMem = aMem = VdbeFrameMem(pFrame);
100511  p->nMem = pFrame->nChildMem;
100512  p->nCursor = (u16)pFrame->nChildCsr;
100513  p->apCsr = (VdbeCursor **)&aMem[p->nMem];
100514  pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
100515  memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
100516  p->aOp = aOp = pProgram->aOp;
100517  p->nOp = pProgram->nOp;
100518#ifdef SQLITE_DEBUG
100519  /* Verify that second and subsequent executions of the same trigger do not
100520  ** try to reuse register values from the first use. */
100521  {
100522    int i;
100523    for(i=0; i<p->nMem; i++){
100524      aMem[i].pScopyFrom = 0;  /* Prevent false-positive AboutToChange() errs */
100525      MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */
100526    }
100527  }
100528#endif
100529  pOp = &aOp[-1];
100530  goto check_for_interrupt;
100531}
100532
100533/* Opcode: Param P1 P2 * * *
100534**
100535** This opcode is only ever present in sub-programs called via the
100536** OP_Program instruction. Copy a value currently stored in a memory
100537** cell of the calling (parent) frame to cell P2 in the current frames
100538** address space. This is used by trigger programs to access the new.*
100539** and old.* values.
100540**
100541** The address of the cell in the parent frame is determined by adding
100542** the value of the P1 argument to the value of the P1 argument to the
100543** calling OP_Program instruction.
100544*/
100545case OP_Param: {           /* out2 */
100546  VdbeFrame *pFrame;
100547  Mem *pIn;
100548  pOut = out2Prerelease(p, pOp);
100549  pFrame = p->pFrame;
100550  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
100551  sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
100552  break;
100553}
100554
100555#endif /* #ifndef SQLITE_OMIT_TRIGGER */
100556
100557#ifndef SQLITE_OMIT_FOREIGN_KEY
100558/* Opcode: FkCounter P1 P2 * * *
100559** Synopsis: fkctr[P1]+=P2
100560**
100561** Increment a "constraint counter" by P2 (P2 may be negative or positive).
100562** If P1 is non-zero, the database constraint counter is incremented
100563** (deferred foreign key constraints). Otherwise, if P1 is zero, the
100564** statement counter is incremented (immediate foreign key constraints).
100565*/
100566case OP_FkCounter: {
100567  if( db->flags & SQLITE_DeferFKs ){
100568    db->nDeferredImmCons += pOp->p2;
100569  }else if( pOp->p1 ){
100570    db->nDeferredCons += pOp->p2;
100571  }else{
100572    p->nFkConstraint += pOp->p2;
100573  }
100574  break;
100575}
100576
100577/* Opcode: FkIfZero P1 P2 * * *
100578** Synopsis: if fkctr[P1]==0 goto P2
100579**
100580** This opcode tests if a foreign key constraint-counter is currently zero.
100581** If so, jump to instruction P2. Otherwise, fall through to the next
100582** instruction.
100583**
100584** If P1 is non-zero, then the jump is taken if the database constraint-counter
100585** is zero (the one that counts deferred constraint violations). If P1 is
100586** zero, the jump is taken if the statement constraint-counter is zero
100587** (immediate foreign key constraint violations).
100588*/
100589case OP_FkIfZero: {         /* jump */
100590  if( pOp->p1 ){
100591    VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
100592    if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
100593  }else{
100594    VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
100595    if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
100596  }
100597  break;
100598}
100599#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
100600
100601#ifndef SQLITE_OMIT_AUTOINCREMENT
100602/* Opcode: MemMax P1 P2 * * *
100603** Synopsis: r[P1]=max(r[P1],r[P2])
100604**
100605** P1 is a register in the root frame of this VM (the root frame is
100606** different from the current frame if this instruction is being executed
100607** within a sub-program). Set the value of register P1 to the maximum of
100608** its current value and the value in register P2.
100609**
100610** This instruction throws an error if the memory cell is not initially
100611** an integer.
100612*/
100613case OP_MemMax: {        /* in2 */
100614  VdbeFrame *pFrame;
100615  if( p->pFrame ){
100616    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
100617    pIn1 = &pFrame->aMem[pOp->p1];
100618  }else{
100619    pIn1 = &aMem[pOp->p1];
100620  }
100621  assert( memIsValid(pIn1) );
100622  sqlite3VdbeMemIntegerify(pIn1);
100623  pIn2 = &aMem[pOp->p2];
100624  sqlite3VdbeMemIntegerify(pIn2);
100625  if( pIn1->u.i<pIn2->u.i){
100626    pIn1->u.i = pIn2->u.i;
100627  }
100628  break;
100629}
100630#endif /* SQLITE_OMIT_AUTOINCREMENT */
100631
100632/* Opcode: IfPos P1 P2 P3 * *
100633** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
100634**
100635** Register P1 must contain an integer.
100636** If the value of register P1 is 1 or greater, subtract P3 from the
100637** value in P1 and jump to P2.
100638**
100639** If the initial value of register P1 is less than 1, then the
100640** value is unchanged and control passes through to the next instruction.
100641*/
100642case OP_IfPos: {        /* jump, in1 */
100643  pIn1 = &aMem[pOp->p1];
100644  assert( pIn1->flags&MEM_Int );
100645  VdbeBranchTaken( pIn1->u.i>0, 2);
100646  if( pIn1->u.i>0 ){
100647    pIn1->u.i -= pOp->p3;
100648    goto jump_to_p2;
100649  }
100650  break;
100651}
100652
100653/* Opcode: OffsetLimit P1 P2 P3 * *
100654** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
100655**
100656** This opcode performs a commonly used computation associated with
100657** LIMIT and OFFSET processing.  r[P1] holds the limit counter.  r[P3]
100658** holds the offset counter.  The opcode computes the combined value
100659** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]
100660** value computed is the total number of rows that will need to be
100661** visited in order to complete the query.
100662**
100663** If r[P3] is zero or negative, that means there is no OFFSET
100664** and r[P2] is set to be the value of the LIMIT, r[P1].
100665**
100666** if r[P1] is zero or negative, that means there is no LIMIT
100667** and r[P2] is set to -1.
100668**
100669** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
100670*/
100671case OP_OffsetLimit: {    /* in1, out2, in3 */
100672  i64 x;
100673  pIn1 = &aMem[pOp->p1];
100674  pIn3 = &aMem[pOp->p3];
100675  pOut = out2Prerelease(p, pOp);
100676  assert( pIn1->flags & MEM_Int );
100677  assert( pIn3->flags & MEM_Int );
100678  x = pIn1->u.i;
100679  if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
100680    /* If the LIMIT is less than or equal to zero, loop forever.  This
100681    ** is documented.  But also, if the LIMIT+OFFSET exceeds 2^63 then
100682    ** also loop forever.  This is undocumented.  In fact, one could argue
100683    ** that the loop should terminate.  But assuming 1 billion iterations
100684    ** per second (far exceeding the capabilities of any current hardware)
100685    ** it would take nearly 300 years to actually reach the limit.  So
100686    ** looping forever is a reasonable approximation. */
100687    pOut->u.i = -1;
100688  }else{
100689    pOut->u.i = x;
100690  }
100691  break;
100692}
100693
100694/* Opcode: IfNotZero P1 P2 * * *
100695** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
100696**
100697** Register P1 must contain an integer.  If the content of register P1 is
100698** initially greater than zero, then decrement the value in register P1.
100699** If it is non-zero (negative or positive) and then also jump to P2.
100700** If register P1 is initially zero, leave it unchanged and fall through.
100701*/
100702case OP_IfNotZero: {        /* jump, in1 */
100703  pIn1 = &aMem[pOp->p1];
100704  assert( pIn1->flags&MEM_Int );
100705  VdbeBranchTaken(pIn1->u.i<0, 2);
100706  if( pIn1->u.i ){
100707     if( pIn1->u.i>0 ) pIn1->u.i--;
100708     goto jump_to_p2;
100709  }
100710  break;
100711}
100712
100713/* Opcode: DecrJumpZero P1 P2 * * *
100714** Synopsis: if (--r[P1])==0 goto P2
100715**
100716** Register P1 must hold an integer.  Decrement the value in P1
100717** and jump to P2 if the new value is exactly zero.
100718*/
100719case OP_DecrJumpZero: {      /* jump, in1 */
100720  pIn1 = &aMem[pOp->p1];
100721  assert( pIn1->flags&MEM_Int );
100722  if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
100723  VdbeBranchTaken(pIn1->u.i==0, 2);
100724  if( pIn1->u.i==0 ) goto jump_to_p2;
100725  break;
100726}
100727
100728
100729/* Opcode: AggStep * P2 P3 P4 P5
100730** Synopsis: accum=r[P3] step(r[P2@P5])
100731**
100732** Execute the xStep function for an aggregate.
100733** The function has P5 arguments.  P4 is a pointer to the
100734** FuncDef structure that specifies the function.  Register P3 is the
100735** accumulator.
100736**
100737** The P5 arguments are taken from register P2 and its
100738** successors.
100739*/
100740/* Opcode: AggInverse * P2 P3 P4 P5
100741** Synopsis: accum=r[P3] inverse(r[P2@P5])
100742**
100743** Execute the xInverse function for an aggregate.
100744** The function has P5 arguments.  P4 is a pointer to the
100745** FuncDef structure that specifies the function.  Register P3 is the
100746** accumulator.
100747**
100748** The P5 arguments are taken from register P2 and its
100749** successors.
100750*/
100751/* Opcode: AggStep1 P1 P2 P3 P4 P5
100752** Synopsis: accum=r[P3] step(r[P2@P5])
100753**
100754** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
100755** aggregate.  The function has P5 arguments.  P4 is a pointer to the
100756** FuncDef structure that specifies the function.  Register P3 is the
100757** accumulator.
100758**
100759** The P5 arguments are taken from register P2 and its
100760** successors.
100761**
100762** This opcode is initially coded as OP_AggStep0.  On first evaluation,
100763** the FuncDef stored in P4 is converted into an sqlite3_context and
100764** the opcode is changed.  In this way, the initialization of the
100765** sqlite3_context only happens once, instead of on each call to the
100766** step function.
100767*/
100768case OP_AggInverse:
100769case OP_AggStep: {
100770  int n;
100771  sqlite3_context *pCtx;
100772
100773  assert( pOp->p4type==P4_FUNCDEF );
100774  n = pOp->p5;
100775  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
100776  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
100777  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
100778  pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
100779               (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
100780  if( pCtx==0 ) goto no_mem;
100781  pCtx->pMem = 0;
100782  pCtx->pOut = (Mem*)&(pCtx->argv[n]);
100783  sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
100784  pCtx->pFunc = pOp->p4.pFunc;
100785  pCtx->iOp = (int)(pOp - aOp);
100786  pCtx->pVdbe = p;
100787  pCtx->skipFlag = 0;
100788  pCtx->isError = 0;
100789  pCtx->enc = encoding;
100790  pCtx->argc = n;
100791  pOp->p4type = P4_FUNCCTX;
100792  pOp->p4.pCtx = pCtx;
100793
100794  /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
100795  assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
100796
100797  pOp->opcode = OP_AggStep1;
100798  /* Fall through into OP_AggStep */
100799  /* no break */ deliberate_fall_through
100800}
100801case OP_AggStep1: {
100802  int i;
100803  sqlite3_context *pCtx;
100804  Mem *pMem;
100805
100806  assert( pOp->p4type==P4_FUNCCTX );
100807  pCtx = pOp->p4.pCtx;
100808  pMem = &aMem[pOp->p3];
100809
100810#ifdef SQLITE_DEBUG
100811  if( pOp->p1 ){
100812    /* This is an OP_AggInverse call.  Verify that xStep has always
100813    ** been called at least once prior to any xInverse call. */
100814    assert( pMem->uTemp==0x1122e0e3 );
100815  }else{
100816    /* This is an OP_AggStep call.  Mark it as such. */
100817    pMem->uTemp = 0x1122e0e3;
100818  }
100819#endif
100820
100821  /* If this function is inside of a trigger, the register array in aMem[]
100822  ** might change from one evaluation to the next.  The next block of code
100823  ** checks to see if the register array has changed, and if so it
100824  ** reinitializes the relevant parts of the sqlite3_context object */
100825  if( pCtx->pMem != pMem ){
100826    pCtx->pMem = pMem;
100827    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
100828  }
100829
100830#ifdef SQLITE_DEBUG
100831  for(i=0; i<pCtx->argc; i++){
100832    assert( memIsValid(pCtx->argv[i]) );
100833    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
100834  }
100835#endif
100836
100837  pMem->n++;
100838  assert( pCtx->pOut->flags==MEM_Null );
100839  assert( pCtx->isError==0 );
100840  assert( pCtx->skipFlag==0 );
100841#ifndef SQLITE_OMIT_WINDOWFUNC
100842  if( pOp->p1 ){
100843    (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
100844  }else
100845#endif
100846  (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
100847
100848  if( pCtx->isError ){
100849    if( pCtx->isError>0 ){
100850      sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
100851      rc = pCtx->isError;
100852    }
100853    if( pCtx->skipFlag ){
100854      assert( pOp[-1].opcode==OP_CollSeq );
100855      i = pOp[-1].p1;
100856      if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
100857      pCtx->skipFlag = 0;
100858    }
100859    sqlite3VdbeMemRelease(pCtx->pOut);
100860    pCtx->pOut->flags = MEM_Null;
100861    pCtx->isError = 0;
100862    if( rc ) goto abort_due_to_error;
100863  }
100864  assert( pCtx->pOut->flags==MEM_Null );
100865  assert( pCtx->skipFlag==0 );
100866  break;
100867}
100868
100869/* Opcode: AggFinal P1 P2 * P4 *
100870** Synopsis: accum=r[P1] N=P2
100871**
100872** P1 is the memory location that is the accumulator for an aggregate
100873** or window function.  Execute the finalizer function
100874** for an aggregate and store the result in P1.
100875**
100876** P2 is the number of arguments that the step function takes and
100877** P4 is a pointer to the FuncDef for this function.  The P2
100878** argument is not used by this opcode.  It is only there to disambiguate
100879** functions that can take varying numbers of arguments.  The
100880** P4 argument is only needed for the case where
100881** the step function was not previously called.
100882*/
100883/* Opcode: AggValue * P2 P3 P4 *
100884** Synopsis: r[P3]=value N=P2
100885**
100886** Invoke the xValue() function and store the result in register P3.
100887**
100888** P2 is the number of arguments that the step function takes and
100889** P4 is a pointer to the FuncDef for this function.  The P2
100890** argument is not used by this opcode.  It is only there to disambiguate
100891** functions that can take varying numbers of arguments.  The
100892** P4 argument is only needed for the case where
100893** the step function was not previously called.
100894*/
100895case OP_AggValue:
100896case OP_AggFinal: {
100897  Mem *pMem;
100898  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
100899  assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
100900  pMem = &aMem[pOp->p1];
100901  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
100902#ifndef SQLITE_OMIT_WINDOWFUNC
100903  if( pOp->p3 ){
100904    memAboutToChange(p, &aMem[pOp->p3]);
100905    rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
100906    pMem = &aMem[pOp->p3];
100907  }else
100908#endif
100909  {
100910    rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
100911  }
100912
100913  if( rc ){
100914    sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
100915    goto abort_due_to_error;
100916  }
100917  sqlite3VdbeChangeEncoding(pMem, encoding);
100918  UPDATE_MAX_BLOBSIZE(pMem);
100919  REGISTER_TRACE((int)(pMem-aMem), pMem);
100920  break;
100921}
100922
100923#ifndef SQLITE_OMIT_WAL
100924/* Opcode: Checkpoint P1 P2 P3 * *
100925**
100926** Checkpoint database P1. This is a no-op if P1 is not currently in
100927** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
100928** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
100929** SQLITE_BUSY or not, respectively.  Write the number of pages in the
100930** WAL after the checkpoint into mem[P3+1] and the number of pages
100931** in the WAL that have been checkpointed after the checkpoint
100932** completes into mem[P3+2].  However on an error, mem[P3+1] and
100933** mem[P3+2] are initialized to -1.
100934*/
100935case OP_Checkpoint: {
100936  int i;                          /* Loop counter */
100937  int aRes[3];                    /* Results */
100938  Mem *pMem;                      /* Write results here */
100939
100940  assert( p->readOnly==0 );
100941  aRes[0] = 0;
100942  aRes[1] = aRes[2] = -1;
100943  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
100944       || pOp->p2==SQLITE_CHECKPOINT_FULL
100945       || pOp->p2==SQLITE_CHECKPOINT_RESTART
100946       || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
100947  );
100948  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
100949  if( rc ){
100950    if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
100951    rc = SQLITE_OK;
100952    aRes[0] = 1;
100953  }
100954  for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
100955    sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
100956  }
100957  break;
100958};
100959#endif
100960
100961#ifndef SQLITE_OMIT_PRAGMA
100962/* Opcode: JournalMode P1 P2 P3 * *
100963**
100964** Change the journal mode of database P1 to P3. P3 must be one of the
100965** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
100966** modes (delete, truncate, persist, off and memory), this is a simple
100967** operation. No IO is required.
100968**
100969** If changing into or out of WAL mode the procedure is more complicated.
100970**
100971** Write a string containing the final journal-mode to register P2.
100972*/
100973case OP_JournalMode: {    /* out2 */
100974  Btree *pBt;                     /* Btree to change journal mode of */
100975  Pager *pPager;                  /* Pager associated with pBt */
100976  int eNew;                       /* New journal mode */
100977  int eOld;                       /* The old journal mode */
100978#ifndef SQLITE_OMIT_WAL
100979  const char *zFilename;          /* Name of database file for pPager */
100980#endif
100981
100982  pOut = out2Prerelease(p, pOp);
100983  eNew = pOp->p3;
100984  assert( eNew==PAGER_JOURNALMODE_DELETE
100985       || eNew==PAGER_JOURNALMODE_TRUNCATE
100986       || eNew==PAGER_JOURNALMODE_PERSIST
100987       || eNew==PAGER_JOURNALMODE_OFF
100988       || eNew==PAGER_JOURNALMODE_MEMORY
100989       || eNew==PAGER_JOURNALMODE_WAL
100990       || eNew==PAGER_JOURNALMODE_QUERY
100991  );
100992  assert( pOp->p1>=0 && pOp->p1<db->nDb );
100993  assert( p->readOnly==0 );
100994
100995  pBt = db->aDb[pOp->p1].pBt;
100996  pPager = sqlite3BtreePager(pBt);
100997  eOld = sqlite3PagerGetJournalMode(pPager);
100998  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
100999  assert( sqlite3BtreeHoldsMutex(pBt) );
101000  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
101001
101002#ifndef SQLITE_OMIT_WAL
101003  zFilename = sqlite3PagerFilename(pPager, 1);
101004
101005  /* Do not allow a transition to journal_mode=WAL for a database
101006  ** in temporary storage or if the VFS does not support shared memory
101007  */
101008  if( eNew==PAGER_JOURNALMODE_WAL
101009   && (sqlite3Strlen30(zFilename)==0           /* Temp file */
101010       || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
101011  ){
101012    eNew = eOld;
101013  }
101014
101015  if( (eNew!=eOld)
101016   && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
101017  ){
101018    if( !db->autoCommit || db->nVdbeRead>1 ){
101019      rc = SQLITE_ERROR;
101020      sqlite3VdbeError(p,
101021          "cannot change %s wal mode from within a transaction",
101022          (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
101023      );
101024      goto abort_due_to_error;
101025    }else{
101026
101027      if( eOld==PAGER_JOURNALMODE_WAL ){
101028        /* If leaving WAL mode, close the log file. If successful, the call
101029        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
101030        ** file. An EXCLUSIVE lock may still be held on the database file
101031        ** after a successful return.
101032        */
101033        rc = sqlite3PagerCloseWal(pPager, db);
101034        if( rc==SQLITE_OK ){
101035          sqlite3PagerSetJournalMode(pPager, eNew);
101036        }
101037      }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
101038        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
101039        ** as an intermediate */
101040        sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
101041      }
101042
101043      /* Open a transaction on the database file. Regardless of the journal
101044      ** mode, this transaction always uses a rollback journal.
101045      */
101046      assert( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE );
101047      if( rc==SQLITE_OK ){
101048        rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
101049      }
101050    }
101051  }
101052#endif /* ifndef SQLITE_OMIT_WAL */
101053
101054  if( rc ) eNew = eOld;
101055  eNew = sqlite3PagerSetJournalMode(pPager, eNew);
101056
101057  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
101058  pOut->z = (char *)sqlite3JournalModename(eNew);
101059  pOut->n = sqlite3Strlen30(pOut->z);
101060  pOut->enc = SQLITE_UTF8;
101061  sqlite3VdbeChangeEncoding(pOut, encoding);
101062  if( rc ) goto abort_due_to_error;
101063  break;
101064};
101065#endif /* SQLITE_OMIT_PRAGMA */
101066
101067#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
101068/* Opcode: Vacuum P1 P2 * * *
101069**
101070** Vacuum the entire database P1.  P1 is 0 for "main", and 2 or more
101071** for an attached database.  The "temp" database may not be vacuumed.
101072**
101073** If P2 is not zero, then it is a register holding a string which is
101074** the file into which the result of vacuum should be written.  When
101075** P2 is zero, the vacuum overwrites the original database.
101076*/
101077case OP_Vacuum: {
101078  assert( p->readOnly==0 );
101079  rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
101080                        pOp->p2 ? &aMem[pOp->p2] : 0);
101081  if( rc ) goto abort_due_to_error;
101082  break;
101083}
101084#endif
101085
101086#if !defined(SQLITE_OMIT_AUTOVACUUM)
101087/* Opcode: IncrVacuum P1 P2 * * *
101088**
101089** Perform a single step of the incremental vacuum procedure on
101090** the P1 database. If the vacuum has finished, jump to instruction
101091** P2. Otherwise, fall through to the next instruction.
101092*/
101093case OP_IncrVacuum: {        /* jump */
101094  Btree *pBt;
101095
101096  assert( pOp->p1>=0 && pOp->p1<db->nDb );
101097  assert( DbMaskTest(p->btreeMask, pOp->p1) );
101098  assert( p->readOnly==0 );
101099  pBt = db->aDb[pOp->p1].pBt;
101100  rc = sqlite3BtreeIncrVacuum(pBt);
101101  VdbeBranchTaken(rc==SQLITE_DONE,2);
101102  if( rc ){
101103    if( rc!=SQLITE_DONE ) goto abort_due_to_error;
101104    rc = SQLITE_OK;
101105    goto jump_to_p2;
101106  }
101107  break;
101108}
101109#endif
101110
101111/* Opcode: Expire P1 P2 * * *
101112**
101113** Cause precompiled statements to expire.  When an expired statement
101114** is executed using sqlite3_step() it will either automatically
101115** reprepare itself (if it was originally created using sqlite3_prepare_v2())
101116** or it will fail with SQLITE_SCHEMA.
101117**
101118** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
101119** then only the currently executing statement is expired.
101120**
101121** If P2 is 0, then SQL statements are expired immediately.  If P2 is 1,
101122** then running SQL statements are allowed to continue to run to completion.
101123** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
101124** that might help the statement run faster but which does not affect the
101125** correctness of operation.
101126*/
101127case OP_Expire: {
101128  assert( pOp->p2==0 || pOp->p2==1 );
101129  if( !pOp->p1 ){
101130    sqlite3ExpirePreparedStatements(db, pOp->p2);
101131  }else{
101132    p->expired = pOp->p2+1;
101133  }
101134  break;
101135}
101136
101137/* Opcode: CursorLock P1 * * * *
101138**
101139** Lock the btree to which cursor P1 is pointing so that the btree cannot be
101140** written by an other cursor.
101141*/
101142case OP_CursorLock: {
101143  VdbeCursor *pC;
101144  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
101145  pC = p->apCsr[pOp->p1];
101146  assert( pC!=0 );
101147  assert( pC->eCurType==CURTYPE_BTREE );
101148  sqlite3BtreeCursorPin(pC->uc.pCursor);
101149  break;
101150}
101151
101152/* Opcode: CursorUnlock P1 * * * *
101153**
101154** Unlock the btree to which cursor P1 is pointing so that it can be
101155** written by other cursors.
101156*/
101157case OP_CursorUnlock: {
101158  VdbeCursor *pC;
101159  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
101160  pC = p->apCsr[pOp->p1];
101161  assert( pC!=0 );
101162  assert( pC->eCurType==CURTYPE_BTREE );
101163  sqlite3BtreeCursorUnpin(pC->uc.pCursor);
101164  break;
101165}
101166
101167#ifndef SQLITE_OMIT_SHARED_CACHE
101168/* Opcode: TableLock P1 P2 P3 P4 *
101169** Synopsis: iDb=P1 root=P2 write=P3
101170**
101171** Obtain a lock on a particular table. This instruction is only used when
101172** the shared-cache feature is enabled.
101173**
101174** P1 is the index of the database in sqlite3.aDb[] of the database
101175** on which the lock is acquired.  A readlock is obtained if P3==0 or
101176** a write lock if P3==1.
101177**
101178** P2 contains the root-page of the table to lock.
101179**
101180** P4 contains a pointer to the name of the table being locked. This is only
101181** used to generate an error message if the lock cannot be obtained.
101182*/
101183case OP_TableLock: {
101184  u8 isWriteLock = (u8)pOp->p3;
101185  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
101186    int p1 = pOp->p1;
101187    assert( p1>=0 && p1<db->nDb );
101188    assert( DbMaskTest(p->btreeMask, p1) );
101189    assert( isWriteLock==0 || isWriteLock==1 );
101190    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
101191    if( rc ){
101192      if( (rc&0xFF)==SQLITE_LOCKED ){
101193        const char *z = pOp->p4.z;
101194        sqlite3VdbeError(p, "database table is locked: %s", z);
101195      }
101196      goto abort_due_to_error;
101197    }
101198  }
101199  break;
101200}
101201#endif /* SQLITE_OMIT_SHARED_CACHE */
101202
101203#ifndef SQLITE_OMIT_VIRTUALTABLE
101204/* Opcode: VBegin * * * P4 *
101205**
101206** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
101207** xBegin method for that table.
101208**
101209** Also, whether or not P4 is set, check that this is not being called from
101210** within a callback to a virtual table xSync() method. If it is, the error
101211** code will be set to SQLITE_LOCKED.
101212*/
101213case OP_VBegin: {
101214  VTable *pVTab;
101215  pVTab = pOp->p4.pVtab;
101216  rc = sqlite3VtabBegin(db, pVTab);
101217  if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
101218  if( rc ) goto abort_due_to_error;
101219  break;
101220}
101221#endif /* SQLITE_OMIT_VIRTUALTABLE */
101222
101223#ifndef SQLITE_OMIT_VIRTUALTABLE
101224/* Opcode: VCreate P1 P2 * * *
101225**
101226** P2 is a register that holds the name of a virtual table in database
101227** P1. Call the xCreate method for that table.
101228*/
101229case OP_VCreate: {
101230  Mem sMem;          /* For storing the record being decoded */
101231  const char *zTab;  /* Name of the virtual table */
101232
101233  memset(&sMem, 0, sizeof(sMem));
101234  sMem.db = db;
101235  /* Because P2 is always a static string, it is impossible for the
101236  ** sqlite3VdbeMemCopy() to fail */
101237  assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
101238  assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
101239  rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
101240  assert( rc==SQLITE_OK );
101241  zTab = (const char*)sqlite3_value_text(&sMem);
101242  assert( zTab || db->mallocFailed );
101243  if( zTab ){
101244    rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
101245  }
101246  sqlite3VdbeMemRelease(&sMem);
101247  if( rc ) goto abort_due_to_error;
101248  break;
101249}
101250#endif /* SQLITE_OMIT_VIRTUALTABLE */
101251
101252#ifndef SQLITE_OMIT_VIRTUALTABLE
101253/* Opcode: VDestroy P1 * * P4 *
101254**
101255** P4 is the name of a virtual table in database P1.  Call the xDestroy method
101256** of that table.
101257*/
101258case OP_VDestroy: {
101259  db->nVDestroy++;
101260  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
101261  db->nVDestroy--;
101262  assert( p->errorAction==OE_Abort && p->usesStmtJournal );
101263  if( rc ) goto abort_due_to_error;
101264  break;
101265}
101266#endif /* SQLITE_OMIT_VIRTUALTABLE */
101267
101268#ifndef SQLITE_OMIT_VIRTUALTABLE
101269/* Opcode: VOpen P1 * * P4 *
101270**
101271** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
101272** P1 is a cursor number.  This opcode opens a cursor to the virtual
101273** table and stores that cursor in P1.
101274*/
101275case OP_VOpen: {             /* ncycle */
101276  VdbeCursor *pCur;
101277  sqlite3_vtab_cursor *pVCur;
101278  sqlite3_vtab *pVtab;
101279  const sqlite3_module *pModule;
101280
101281  assert( p->bIsReader );
101282  pCur = 0;
101283  pVCur = 0;
101284  pVtab = pOp->p4.pVtab->pVtab;
101285  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
101286    rc = SQLITE_LOCKED;
101287    goto abort_due_to_error;
101288  }
101289  pModule = pVtab->pModule;
101290  rc = pModule->xOpen(pVtab, &pVCur);
101291  sqlite3VtabImportErrmsg(p, pVtab);
101292  if( rc ) goto abort_due_to_error;
101293
101294  /* Initialize sqlite3_vtab_cursor base class */
101295  pVCur->pVtab = pVtab;
101296
101297  /* Initialize vdbe cursor object */
101298  pCur = allocateCursor(p, pOp->p1, 0, CURTYPE_VTAB);
101299  if( pCur ){
101300    pCur->uc.pVCur = pVCur;
101301    pVtab->nRef++;
101302  }else{
101303    assert( db->mallocFailed );
101304    pModule->xClose(pVCur);
101305    goto no_mem;
101306  }
101307  break;
101308}
101309#endif /* SQLITE_OMIT_VIRTUALTABLE */
101310
101311#ifndef SQLITE_OMIT_VIRTUALTABLE
101312/* Opcode: VCheck P1 P2 P3 P4 *
101313**
101314** P4 is a pointer to a Table object that is a virtual table in schema P1
101315** that supports the xIntegrity() method.  This opcode runs the xIntegrity()
101316** method for that virtual table, using P3 as the integer argument.  If
101317** an error is reported back, the table name is prepended to the error
101318** message and that message is stored in P2.  If no errors are seen,
101319** register P2 is set to NULL.
101320*/
101321case OP_VCheck: {             /* out2 */
101322  Table *pTab;
101323  sqlite3_vtab *pVtab;
101324  const sqlite3_module *pModule;
101325  char *zErr = 0;
101326
101327  pOut = &aMem[pOp->p2];
101328  sqlite3VdbeMemSetNull(pOut);  /* Innocent until proven guilty */
101329  assert( pOp->p4type==P4_TABLEREF );
101330  pTab = pOp->p4.pTab;
101331  assert( pTab!=0 );
101332  assert( pTab->nTabRef>0 );
101333  assert( IsVirtual(pTab) );
101334  if( pTab->u.vtab.p==0 ) break;
101335  pVtab = pTab->u.vtab.p->pVtab;
101336  assert( pVtab!=0 );
101337  pModule = pVtab->pModule;
101338  assert( pModule!=0 );
101339  assert( pModule->iVersion>=4 );
101340  assert( pModule->xIntegrity!=0 );
101341  sqlite3VtabLock(pTab->u.vtab.p);
101342  assert( pOp->p1>=0 && pOp->p1<db->nDb );
101343  rc = pModule->xIntegrity(pVtab, db->aDb[pOp->p1].zDbSName, pTab->zName,
101344                           pOp->p3, &zErr);
101345  sqlite3VtabUnlock(pTab->u.vtab.p);
101346  if( rc ){
101347    sqlite3_free(zErr);
101348    goto abort_due_to_error;
101349  }
101350  if( zErr ){
101351    sqlite3VdbeMemSetStr(pOut, zErr, -1, SQLITE_UTF8, sqlite3_free);
101352  }
101353  break;
101354}
101355#endif /* SQLITE_OMIT_VIRTUALTABLE */
101356
101357#ifndef SQLITE_OMIT_VIRTUALTABLE
101358/* Opcode: VInitIn P1 P2 P3 * *
101359** Synopsis: r[P2]=ValueList(P1,P3)
101360**
101361** Set register P2 to be a pointer to a ValueList object for cursor P1
101362** with cache register P3 and output register P3+1.  This ValueList object
101363** can be used as the first argument to sqlite3_vtab_in_first() and
101364** sqlite3_vtab_in_next() to extract all of the values stored in the P1
101365** cursor.  Register P3 is used to hold the values returned by
101366** sqlite3_vtab_in_first() and sqlite3_vtab_in_next().
101367*/
101368case OP_VInitIn: {        /* out2, ncycle */
101369  VdbeCursor *pC;         /* The cursor containing the RHS values */
101370  ValueList *pRhs;        /* New ValueList object to put in reg[P2] */
101371
101372  pC = p->apCsr[pOp->p1];
101373  pRhs = sqlite3_malloc64( sizeof(*pRhs) );
101374  if( pRhs==0 ) goto no_mem;
101375  pRhs->pCsr = pC->uc.pCursor;
101376  pRhs->pOut = &aMem[pOp->p3];
101377  pOut = out2Prerelease(p, pOp);
101378  pOut->flags = MEM_Null;
101379  sqlite3VdbeMemSetPointer(pOut, pRhs, "ValueList", sqlite3VdbeValueListFree);
101380  break;
101381}
101382#endif /* SQLITE_OMIT_VIRTUALTABLE */
101383
101384
101385#ifndef SQLITE_OMIT_VIRTUALTABLE
101386/* Opcode: VFilter P1 P2 P3 P4 *
101387** Synopsis: iplan=r[P3] zplan='P4'
101388**
101389** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
101390** the filtered result set is empty.
101391**
101392** P4 is either NULL or a string that was generated by the xBestIndex
101393** method of the module.  The interpretation of the P4 string is left
101394** to the module implementation.
101395**
101396** This opcode invokes the xFilter method on the virtual table specified
101397** by P1.  The integer query plan parameter to xFilter is stored in register
101398** P3. Register P3+1 stores the argc parameter to be passed to the
101399** xFilter method. Registers P3+2..P3+1+argc are the argc
101400** additional parameters which are passed to
101401** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
101402**
101403** A jump is made to P2 if the result set after filtering would be empty.
101404*/
101405case OP_VFilter: {   /* jump, ncycle */
101406  int nArg;
101407  int iQuery;
101408  const sqlite3_module *pModule;
101409  Mem *pQuery;
101410  Mem *pArgc;
101411  sqlite3_vtab_cursor *pVCur;
101412  sqlite3_vtab *pVtab;
101413  VdbeCursor *pCur;
101414  int res;
101415  int i;
101416  Mem **apArg;
101417
101418  pQuery = &aMem[pOp->p3];
101419  pArgc = &pQuery[1];
101420  pCur = p->apCsr[pOp->p1];
101421  assert( memIsValid(pQuery) );
101422  REGISTER_TRACE(pOp->p3, pQuery);
101423  assert( pCur!=0 );
101424  assert( pCur->eCurType==CURTYPE_VTAB );
101425  pVCur = pCur->uc.pVCur;
101426  pVtab = pVCur->pVtab;
101427  pModule = pVtab->pModule;
101428
101429  /* Grab the index number and argc parameters */
101430  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
101431  nArg = (int)pArgc->u.i;
101432  iQuery = (int)pQuery->u.i;
101433
101434  /* Invoke the xFilter method */
101435  apArg = p->apArg;
101436  for(i = 0; i<nArg; i++){
101437    apArg[i] = &pArgc[i+1];
101438  }
101439  rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
101440  sqlite3VtabImportErrmsg(p, pVtab);
101441  if( rc ) goto abort_due_to_error;
101442  res = pModule->xEof(pVCur);
101443  pCur->nullRow = 0;
101444  VdbeBranchTaken(res!=0,2);
101445  if( res ) goto jump_to_p2;
101446  break;
101447}
101448#endif /* SQLITE_OMIT_VIRTUALTABLE */
101449
101450#ifndef SQLITE_OMIT_VIRTUALTABLE
101451/* Opcode: VColumn P1 P2 P3 * P5
101452** Synopsis: r[P3]=vcolumn(P2)
101453**
101454** Store in register P3 the value of the P2-th column of
101455** the current row of the virtual-table of cursor P1.
101456**
101457** If the VColumn opcode is being used to fetch the value of
101458** an unchanging column during an UPDATE operation, then the P5
101459** value is OPFLAG_NOCHNG.  This will cause the sqlite3_vtab_nochange()
101460** function to return true inside the xColumn method of the virtual
101461** table implementation.  The P5 column might also contain other
101462** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
101463** unused by OP_VColumn.
101464*/
101465case OP_VColumn: {           /* ncycle */
101466  sqlite3_vtab *pVtab;
101467  const sqlite3_module *pModule;
101468  Mem *pDest;
101469  sqlite3_context sContext;
101470  FuncDef nullFunc;
101471
101472  VdbeCursor *pCur = p->apCsr[pOp->p1];
101473  assert( pCur!=0 );
101474  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
101475  pDest = &aMem[pOp->p3];
101476  memAboutToChange(p, pDest);
101477  if( pCur->nullRow ){
101478    sqlite3VdbeMemSetNull(pDest);
101479    break;
101480  }
101481  assert( pCur->eCurType==CURTYPE_VTAB );
101482  pVtab = pCur->uc.pVCur->pVtab;
101483  pModule = pVtab->pModule;
101484  assert( pModule->xColumn );
101485  memset(&sContext, 0, sizeof(sContext));
101486  sContext.pOut = pDest;
101487  sContext.enc = encoding;
101488  nullFunc.pUserData = 0;
101489  nullFunc.funcFlags = SQLITE_RESULT_SUBTYPE;
101490  sContext.pFunc = &nullFunc;
101491  assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
101492  if( pOp->p5 & OPFLAG_NOCHNG ){
101493    sqlite3VdbeMemSetNull(pDest);
101494    pDest->flags = MEM_Null|MEM_Zero;
101495    pDest->u.nZero = 0;
101496  }else{
101497    MemSetTypeFlag(pDest, MEM_Null);
101498  }
101499  rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
101500  sqlite3VtabImportErrmsg(p, pVtab);
101501  if( sContext.isError>0 ){
101502    sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
101503    rc = sContext.isError;
101504  }
101505  sqlite3VdbeChangeEncoding(pDest, encoding);
101506  REGISTER_TRACE(pOp->p3, pDest);
101507  UPDATE_MAX_BLOBSIZE(pDest);
101508
101509  if( rc ) goto abort_due_to_error;
101510  break;
101511}
101512#endif /* SQLITE_OMIT_VIRTUALTABLE */
101513
101514#ifndef SQLITE_OMIT_VIRTUALTABLE
101515/* Opcode: VNext P1 P2 * * *
101516**
101517** Advance virtual table P1 to the next row in its result set and
101518** jump to instruction P2.  Or, if the virtual table has reached
101519** the end of its result set, then fall through to the next instruction.
101520*/
101521case OP_VNext: {   /* jump, ncycle */
101522  sqlite3_vtab *pVtab;
101523  const sqlite3_module *pModule;
101524  int res;
101525  VdbeCursor *pCur;
101526
101527  pCur = p->apCsr[pOp->p1];
101528  assert( pCur!=0 );
101529  assert( pCur->eCurType==CURTYPE_VTAB );
101530  if( pCur->nullRow ){
101531    break;
101532  }
101533  pVtab = pCur->uc.pVCur->pVtab;
101534  pModule = pVtab->pModule;
101535  assert( pModule->xNext );
101536
101537  /* Invoke the xNext() method of the module. There is no way for the
101538  ** underlying implementation to return an error if one occurs during
101539  ** xNext(). Instead, if an error occurs, true is returned (indicating that
101540  ** data is available) and the error code returned when xColumn or
101541  ** some other method is next invoked on the save virtual table cursor.
101542  */
101543  rc = pModule->xNext(pCur->uc.pVCur);
101544  sqlite3VtabImportErrmsg(p, pVtab);
101545  if( rc ) goto abort_due_to_error;
101546  res = pModule->xEof(pCur->uc.pVCur);
101547  VdbeBranchTaken(!res,2);
101548  if( !res ){
101549    /* If there is data, jump to P2 */
101550    goto jump_to_p2_and_check_for_interrupt;
101551  }
101552  goto check_for_interrupt;
101553}
101554#endif /* SQLITE_OMIT_VIRTUALTABLE */
101555
101556#ifndef SQLITE_OMIT_VIRTUALTABLE
101557/* Opcode: VRename P1 * * P4 *
101558**
101559** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
101560** This opcode invokes the corresponding xRename method. The value
101561** in register P1 is passed as the zName argument to the xRename method.
101562*/
101563case OP_VRename: {
101564  sqlite3_vtab *pVtab;
101565  Mem *pName;
101566  int isLegacy;
101567
101568  isLegacy = (db->flags & SQLITE_LegacyAlter);
101569  db->flags |= SQLITE_LegacyAlter;
101570  pVtab = pOp->p4.pVtab->pVtab;
101571  pName = &aMem[pOp->p1];
101572  assert( pVtab->pModule->xRename );
101573  assert( memIsValid(pName) );
101574  assert( p->readOnly==0 );
101575  REGISTER_TRACE(pOp->p1, pName);
101576  assert( pName->flags & MEM_Str );
101577  testcase( pName->enc==SQLITE_UTF8 );
101578  testcase( pName->enc==SQLITE_UTF16BE );
101579  testcase( pName->enc==SQLITE_UTF16LE );
101580  rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
101581  if( rc ) goto abort_due_to_error;
101582  rc = pVtab->pModule->xRename(pVtab, pName->z);
101583  if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
101584  sqlite3VtabImportErrmsg(p, pVtab);
101585  p->expired = 0;
101586  if( rc ) goto abort_due_to_error;
101587  break;
101588}
101589#endif
101590
101591#ifndef SQLITE_OMIT_VIRTUALTABLE
101592/* Opcode: VUpdate P1 P2 P3 P4 P5
101593** Synopsis: data=r[P3@P2]
101594**
101595** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
101596** This opcode invokes the corresponding xUpdate method. P2 values
101597** are contiguous memory cells starting at P3 to pass to the xUpdate
101598** invocation. The value in register (P3+P2-1) corresponds to the
101599** p2th element of the argv array passed to xUpdate.
101600**
101601** The xUpdate method will do a DELETE or an INSERT or both.
101602** The argv[0] element (which corresponds to memory cell P3)
101603** is the rowid of a row to delete.  If argv[0] is NULL then no
101604** deletion occurs.  The argv[1] element is the rowid of the new
101605** row.  This can be NULL to have the virtual table select the new
101606** rowid for itself.  The subsequent elements in the array are
101607** the values of columns in the new row.
101608**
101609** If P2==1 then no insert is performed.  argv[0] is the rowid of
101610** a row to delete.
101611**
101612** P1 is a boolean flag. If it is set to true and the xUpdate call
101613** is successful, then the value returned by sqlite3_last_insert_rowid()
101614** is set to the value of the rowid for the row just inserted.
101615**
101616** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
101617** apply in the case of a constraint failure on an insert or update.
101618*/
101619case OP_VUpdate: {
101620  sqlite3_vtab *pVtab;
101621  const sqlite3_module *pModule;
101622  int nArg;
101623  int i;
101624  sqlite_int64 rowid = 0;
101625  Mem **apArg;
101626  Mem *pX;
101627
101628  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
101629       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
101630  );
101631  assert( p->readOnly==0 );
101632  if( db->mallocFailed ) goto no_mem;
101633  sqlite3VdbeIncrWriteCounter(p, 0);
101634  pVtab = pOp->p4.pVtab->pVtab;
101635  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
101636    rc = SQLITE_LOCKED;
101637    goto abort_due_to_error;
101638  }
101639  pModule = pVtab->pModule;
101640  nArg = pOp->p2;
101641  assert( pOp->p4type==P4_VTAB );
101642  if( ALWAYS(pModule->xUpdate) ){
101643    u8 vtabOnConflict = db->vtabOnConflict;
101644    apArg = p->apArg;
101645    pX = &aMem[pOp->p3];
101646    for(i=0; i<nArg; i++){
101647      assert( memIsValid(pX) );
101648      memAboutToChange(p, pX);
101649      apArg[i] = pX;
101650      pX++;
101651    }
101652    db->vtabOnConflict = pOp->p5;
101653    rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
101654    db->vtabOnConflict = vtabOnConflict;
101655    sqlite3VtabImportErrmsg(p, pVtab);
101656    if( rc==SQLITE_OK && pOp->p1 ){
101657      assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
101658      db->lastRowid = rowid;
101659    }
101660    if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
101661      if( pOp->p5==OE_Ignore ){
101662        rc = SQLITE_OK;
101663      }else{
101664        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
101665      }
101666    }else{
101667      p->nChange++;
101668    }
101669    if( rc ) goto abort_due_to_error;
101670  }
101671  break;
101672}
101673#endif /* SQLITE_OMIT_VIRTUALTABLE */
101674
101675#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
101676/* Opcode: Pagecount P1 P2 * * *
101677**
101678** Write the current number of pages in database P1 to memory cell P2.
101679*/
101680case OP_Pagecount: {            /* out2 */
101681  pOut = out2Prerelease(p, pOp);
101682  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
101683  break;
101684}
101685#endif
101686
101687
101688#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
101689/* Opcode: MaxPgcnt P1 P2 P3 * *
101690**
101691** Try to set the maximum page count for database P1 to the value in P3.
101692** Do not let the maximum page count fall below the current page count and
101693** do not change the maximum page count value if P3==0.
101694**
101695** Store the maximum page count after the change in register P2.
101696*/
101697case OP_MaxPgcnt: {            /* out2 */
101698  unsigned int newMax;
101699  Btree *pBt;
101700
101701  pOut = out2Prerelease(p, pOp);
101702  pBt = db->aDb[pOp->p1].pBt;
101703  newMax = 0;
101704  if( pOp->p3 ){
101705    newMax = sqlite3BtreeLastPage(pBt);
101706    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
101707  }
101708  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
101709  break;
101710}
101711#endif
101712
101713/* Opcode: Function P1 P2 P3 P4 *
101714** Synopsis: r[P3]=func(r[P2@NP])
101715**
101716** Invoke a user function (P4 is a pointer to an sqlite3_context object that
101717** contains a pointer to the function to be run) with arguments taken
101718** from register P2 and successors.  The number of arguments is in
101719** the sqlite3_context object that P4 points to.
101720** The result of the function is stored
101721** in register P3.  Register P3 must not be one of the function inputs.
101722**
101723** P1 is a 32-bit bitmask indicating whether or not each argument to the
101724** function was determined to be constant at compile time. If the first
101725** argument was constant then bit 0 of P1 is set. This is used to determine
101726** whether meta data associated with a user function argument using the
101727** sqlite3_set_auxdata() API may be safely retained until the next
101728** invocation of this opcode.
101729**
101730** See also: AggStep, AggFinal, PureFunc
101731*/
101732/* Opcode: PureFunc P1 P2 P3 P4 *
101733** Synopsis: r[P3]=func(r[P2@NP])
101734**
101735** Invoke a user function (P4 is a pointer to an sqlite3_context object that
101736** contains a pointer to the function to be run) with arguments taken
101737** from register P2 and successors.  The number of arguments is in
101738** the sqlite3_context object that P4 points to.
101739** The result of the function is stored
101740** in register P3.  Register P3 must not be one of the function inputs.
101741**
101742** P1 is a 32-bit bitmask indicating whether or not each argument to the
101743** function was determined to be constant at compile time. If the first
101744** argument was constant then bit 0 of P1 is set. This is used to determine
101745** whether meta data associated with a user function argument using the
101746** sqlite3_set_auxdata() API may be safely retained until the next
101747** invocation of this opcode.
101748**
101749** This opcode works exactly like OP_Function.  The only difference is in
101750** its name.  This opcode is used in places where the function must be
101751** purely non-deterministic.  Some built-in date/time functions can be
101752** either deterministic of non-deterministic, depending on their arguments.
101753** When those function are used in a non-deterministic way, they will check
101754** to see if they were called using OP_PureFunc instead of OP_Function, and
101755** if they were, they throw an error.
101756**
101757** See also: AggStep, AggFinal, Function
101758*/
101759case OP_PureFunc:              /* group */
101760case OP_Function: {            /* group */
101761  int i;
101762  sqlite3_context *pCtx;
101763
101764  assert( pOp->p4type==P4_FUNCCTX );
101765  pCtx = pOp->p4.pCtx;
101766
101767  /* If this function is inside of a trigger, the register array in aMem[]
101768  ** might change from one evaluation to the next.  The next block of code
101769  ** checks to see if the register array has changed, and if so it
101770  ** reinitializes the relevant parts of the sqlite3_context object */
101771  pOut = &aMem[pOp->p3];
101772  if( pCtx->pOut != pOut ){
101773    pCtx->pVdbe = p;
101774    pCtx->pOut = pOut;
101775    pCtx->enc = encoding;
101776    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
101777  }
101778  assert( pCtx->pVdbe==p );
101779
101780  memAboutToChange(p, pOut);
101781#ifdef SQLITE_DEBUG
101782  for(i=0; i<pCtx->argc; i++){
101783    assert( memIsValid(pCtx->argv[i]) );
101784    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
101785  }
101786#endif
101787  MemSetTypeFlag(pOut, MEM_Null);
101788  assert( pCtx->isError==0 );
101789  (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
101790
101791  /* If the function returned an error, throw an exception */
101792  if( pCtx->isError ){
101793    if( pCtx->isError>0 ){
101794      sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
101795      rc = pCtx->isError;
101796    }
101797    sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
101798    pCtx->isError = 0;
101799    if( rc ) goto abort_due_to_error;
101800  }
101801
101802  assert( (pOut->flags&MEM_Str)==0
101803       || pOut->enc==encoding
101804       || db->mallocFailed );
101805  assert( !sqlite3VdbeMemTooBig(pOut) );
101806
101807  REGISTER_TRACE(pOp->p3, pOut);
101808  UPDATE_MAX_BLOBSIZE(pOut);
101809  break;
101810}
101811
101812/* Opcode: ClrSubtype P1 * * * *
101813** Synopsis:  r[P1].subtype = 0
101814**
101815** Clear the subtype from register P1.
101816*/
101817case OP_ClrSubtype: {   /* in1 */
101818  pIn1 = &aMem[pOp->p1];
101819  pIn1->flags &= ~MEM_Subtype;
101820  break;
101821}
101822
101823/* Opcode: GetSubtype P1 P2 * * *
101824** Synopsis:  r[P2] = r[P1].subtype
101825**
101826** Extract the subtype value from register P1 and write that subtype
101827** into register P2.  If P1 has no subtype, then P1 gets a NULL.
101828*/
101829case OP_GetSubtype: {   /* in1 out2 */
101830  pIn1 = &aMem[pOp->p1];
101831  pOut = &aMem[pOp->p2];
101832  if( pIn1->flags & MEM_Subtype ){
101833    sqlite3VdbeMemSetInt64(pOut, pIn1->eSubtype);
101834  }else{
101835    sqlite3VdbeMemSetNull(pOut);
101836  }
101837  break;
101838}
101839
101840/* Opcode: SetSubtype P1 P2 * * *
101841** Synopsis:  r[P2].subtype = r[P1]
101842**
101843** Set the subtype value of register P2 to the integer from register P1.
101844** If P1 is NULL, clear the subtype from p2.
101845*/
101846case OP_SetSubtype: {   /* in1 out2 */
101847  pIn1 = &aMem[pOp->p1];
101848  pOut = &aMem[pOp->p2];
101849  if( pIn1->flags & MEM_Null ){
101850    pOut->flags &= ~MEM_Subtype;
101851  }else{
101852    assert( pIn1->flags & MEM_Int );
101853    pOut->flags |= MEM_Subtype;
101854    pOut->eSubtype = (u8)(pIn1->u.i & 0xff);
101855  }
101856  break;
101857}
101858
101859/* Opcode: FilterAdd P1 * P3 P4 *
101860** Synopsis: filter(P1) += key(P3@P4)
101861**
101862** Compute a hash on the P4 registers starting with r[P3] and
101863** add that hash to the bloom filter contained in r[P1].
101864*/
101865case OP_FilterAdd: {
101866  u64 h;
101867
101868  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
101869  pIn1 = &aMem[pOp->p1];
101870  assert( pIn1->flags & MEM_Blob );
101871  assert( pIn1->n>0 );
101872  h = filterHash(aMem, pOp);
101873#ifdef SQLITE_DEBUG
101874  if( db->flags&SQLITE_VdbeTrace ){
101875    int ii;
101876    for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
101877      registerTrace(ii, &aMem[ii]);
101878    }
101879    printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
101880  }
101881#endif
101882  h %= (pIn1->n*8);
101883  pIn1->z[h/8] |= 1<<(h&7);
101884  break;
101885}
101886
101887/* Opcode: Filter P1 P2 P3 P4 *
101888** Synopsis: if key(P3@P4) not in filter(P1) goto P2
101889**
101890** Compute a hash on the key contained in the P4 registers starting
101891** with r[P3].  Check to see if that hash is found in the
101892** bloom filter hosted by register P1.  If it is not present then
101893** maybe jump to P2.  Otherwise fall through.
101894**
101895** False negatives are harmless.  It is always safe to fall through,
101896** even if the value is in the bloom filter.  A false negative causes
101897** more CPU cycles to be used, but it should still yield the correct
101898** answer.  However, an incorrect answer may well arise from a
101899** false positive - if the jump is taken when it should fall through.
101900*/
101901case OP_Filter: {          /* jump */
101902  u64 h;
101903
101904  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
101905  pIn1 = &aMem[pOp->p1];
101906  assert( (pIn1->flags & MEM_Blob)!=0 );
101907  assert( pIn1->n >= 1 );
101908  h = filterHash(aMem, pOp);
101909#ifdef SQLITE_DEBUG
101910  if( db->flags&SQLITE_VdbeTrace ){
101911    int ii;
101912    for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
101913      registerTrace(ii, &aMem[ii]);
101914    }
101915    printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
101916  }
101917#endif
101918  h %= (pIn1->n*8);
101919  if( (pIn1->z[h/8] & (1<<(h&7)))==0 ){
101920    VdbeBranchTaken(1, 2);
101921    p->aCounter[SQLITE_STMTSTATUS_FILTER_HIT]++;
101922    goto jump_to_p2;
101923  }else{
101924    p->aCounter[SQLITE_STMTSTATUS_FILTER_MISS]++;
101925    VdbeBranchTaken(0, 2);
101926  }
101927  break;
101928}
101929
101930/* Opcode: Trace P1 P2 * P4 *
101931**
101932** Write P4 on the statement trace output if statement tracing is
101933** enabled.
101934**
101935** Operand P1 must be 0x7fffffff and P2 must positive.
101936*/
101937/* Opcode: Init P1 P2 P3 P4 *
101938** Synopsis: Start at P2
101939**
101940** Programs contain a single instance of this opcode as the very first
101941** opcode.
101942**
101943** If tracing is enabled (by the sqlite3_trace()) interface, then
101944** the UTF-8 string contained in P4 is emitted on the trace callback.
101945** Or if P4 is blank, use the string returned by sqlite3_sql().
101946**
101947** If P2 is not zero, jump to instruction P2.
101948**
101949** Increment the value of P1 so that OP_Once opcodes will jump the
101950** first time they are evaluated for this run.
101951**
101952** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
101953** error is encountered.
101954*/
101955case OP_Trace:
101956case OP_Init: {          /* jump0 */
101957  int i;
101958#ifndef SQLITE_OMIT_TRACE
101959  char *zTrace;
101960#endif
101961
101962  /* If the P4 argument is not NULL, then it must be an SQL comment string.
101963  ** The "--" string is broken up to prevent false-positives with srcck1.c.
101964  **
101965  ** This assert() provides evidence for:
101966  ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
101967  ** would have been returned by the legacy sqlite3_trace() interface by
101968  ** using the X argument when X begins with "--" and invoking
101969  ** sqlite3_expanded_sql(P) otherwise.
101970  */
101971  assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
101972
101973  /* OP_Init is always instruction 0 */
101974  assert( pOp==p->aOp || pOp->opcode==OP_Trace );
101975
101976#ifndef SQLITE_OMIT_TRACE
101977  if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
101978   && p->minWriteFileFormat!=254  /* tag-20220401a */
101979   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
101980  ){
101981#ifndef SQLITE_OMIT_DEPRECATED
101982    if( db->mTrace & SQLITE_TRACE_LEGACY ){
101983      char *z = sqlite3VdbeExpandSql(p, zTrace);
101984      db->trace.xLegacy(db->pTraceArg, z);
101985      sqlite3_free(z);
101986    }else
101987#endif
101988    if( db->nVdbeExec>1 ){
101989      char *z = sqlite3MPrintf(db, "-- %s", zTrace);
101990      (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
101991      sqlite3DbFree(db, z);
101992    }else{
101993      (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
101994    }
101995  }
101996#ifdef SQLITE_USE_FCNTL_TRACE
101997  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
101998  if( zTrace ){
101999    int j;
102000    for(j=0; j<db->nDb; j++){
102001      if( DbMaskTest(p->btreeMask, j)==0 ) continue;
102002      sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
102003    }
102004  }
102005#endif /* SQLITE_USE_FCNTL_TRACE */
102006#ifdef SQLITE_DEBUG
102007  if( (db->flags & SQLITE_SqlTrace)!=0
102008   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
102009  ){
102010    sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
102011  }
102012#endif /* SQLITE_DEBUG */
102013#endif /* SQLITE_OMIT_TRACE */
102014  assert( pOp->p2>0 );
102015  if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
102016    if( pOp->opcode==OP_Trace ) break;
102017    for(i=1; i<p->nOp; i++){
102018      if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
102019    }
102020    pOp->p1 = 0;
102021  }
102022  pOp->p1++;
102023  p->aCounter[SQLITE_STMTSTATUS_RUN]++;
102024  goto jump_to_p2;
102025}
102026
102027#ifdef SQLITE_ENABLE_CURSOR_HINTS
102028/* Opcode: CursorHint P1 * * P4 *
102029**
102030** Provide a hint to cursor P1 that it only needs to return rows that
102031** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
102032** to values currently held in registers.  TK_COLUMN terms in the P4
102033** expression refer to columns in the b-tree to which cursor P1 is pointing.
102034*/
102035case OP_CursorHint: {
102036  VdbeCursor *pC;
102037
102038  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
102039  assert( pOp->p4type==P4_EXPR );
102040  pC = p->apCsr[pOp->p1];
102041  if( pC ){
102042    assert( pC->eCurType==CURTYPE_BTREE );
102043    sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
102044                           pOp->p4.pExpr, aMem);
102045  }
102046  break;
102047}
102048#endif /* SQLITE_ENABLE_CURSOR_HINTS */
102049
102050#ifdef SQLITE_DEBUG
102051/* Opcode:  Abortable   * * * * *
102052**
102053** Verify that an Abort can happen.  Assert if an Abort at this point
102054** might cause database corruption.  This opcode only appears in debugging
102055** builds.
102056**
102057** An Abort is safe if either there have been no writes, or if there is
102058** an active statement journal.
102059*/
102060case OP_Abortable: {
102061  sqlite3VdbeAssertAbortable(p);
102062  break;
102063}
102064#endif
102065
102066#ifdef SQLITE_DEBUG
102067/* Opcode:  ReleaseReg   P1 P2 P3 * P5
102068** Synopsis: release r[P1@P2] mask P3
102069**
102070** Release registers from service.  Any content that was in the
102071** the registers is unreliable after this opcode completes.
102072**
102073** The registers released will be the P2 registers starting at P1,
102074** except if bit ii of P3 set, then do not release register P1+ii.
102075** In other words, P3 is a mask of registers to preserve.
102076**
102077** Releasing a register clears the Mem.pScopyFrom pointer.  That means
102078** that if the content of the released register was set using OP_SCopy,
102079** a change to the value of the source register for the OP_SCopy will no longer
102080** generate an assertion fault in sqlite3VdbeMemAboutToChange().
102081**
102082** If P5 is set, then all released registers have their type set
102083** to MEM_Undefined so that any subsequent attempt to read the released
102084** register (before it is reinitialized) will generate an assertion fault.
102085**
102086** P5 ought to be set on every call to this opcode.
102087** However, there are places in the code generator will release registers
102088** before their are used, under the (valid) assumption that the registers
102089** will not be reallocated for some other purpose before they are used and
102090** hence are safe to release.
102091**
102092** This opcode is only available in testing and debugging builds.  It is
102093** not generated for release builds.  The purpose of this opcode is to help
102094** validate the generated bytecode.  This opcode does not actually contribute
102095** to computing an answer.
102096*/
102097case OP_ReleaseReg: {
102098  Mem *pMem;
102099  int i;
102100  u32 constMask;
102101  assert( pOp->p1>0 );
102102  assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
102103  pMem = &aMem[pOp->p1];
102104  constMask = pOp->p3;
102105  for(i=0; i<pOp->p2; i++, pMem++){
102106    if( i>=32 || (constMask & MASKBIT32(i))==0 ){
102107      pMem->pScopyFrom = 0;
102108      if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
102109    }
102110  }
102111  break;
102112}
102113#endif
102114
102115/* Opcode: Noop * * * * *
102116**
102117** Do nothing.  This instruction is often useful as a jump
102118** destination.
102119*/
102120/*
102121** The magic Explain opcode are only inserted when explain==2 (which
102122** is to say when the EXPLAIN QUERY PLAN syntax is used.)
102123** This opcode records information from the optimizer.  It is the
102124** the same as a no-op.  This opcodesnever appears in a real VM program.
102125*/
102126default: {          /* This is really OP_Noop, OP_Explain */
102127  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
102128
102129  break;
102130}
102131
102132/*****************************************************************************
102133** The cases of the switch statement above this line should all be indented
102134** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
102135** readability.  From this point on down, the normal indentation rules are
102136** restored.
102137*****************************************************************************/
102138    }
102139
102140#if defined(VDBE_PROFILE)
102141    *pnCycle += sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
102142    pnCycle = 0;
102143#elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
102144    if( pnCycle ){
102145      *pnCycle += sqlite3Hwtime();
102146      pnCycle = 0;
102147    }
102148#endif
102149
102150    /* The following code adds nothing to the actual functionality
102151    ** of the program.  It is only here for testing and debugging.
102152    ** On the other hand, it does burn CPU cycles every time through
102153    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
102154    */
102155#ifndef NDEBUG
102156    assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
102157
102158#ifdef SQLITE_DEBUG
102159    if( db->flags & SQLITE_VdbeTrace ){
102160      u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
102161      if( rc!=0 ) printf("rc=%d\n",rc);
102162      if( opProperty & (OPFLG_OUT2) ){
102163        registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
102164      }
102165      if( opProperty & OPFLG_OUT3 ){
102166        registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
102167      }
102168      if( opProperty==0xff ){
102169        /* Never happens.  This code exists to avoid a harmless linkage
102170        ** warning about sqlite3VdbeRegisterDump() being defined but not
102171        ** used. */
102172        sqlite3VdbeRegisterDump(p);
102173      }
102174    }
102175#endif  /* SQLITE_DEBUG */
102176#endif  /* NDEBUG */
102177  }  /* The end of the for(;;) loop the loops through opcodes */
102178
102179  /* If we reach this point, it means that execution is finished with
102180  ** an error of some kind.
102181  */
102182abort_due_to_error:
102183  if( db->mallocFailed ){
102184    rc = SQLITE_NOMEM_BKPT;
102185  }else if( rc==SQLITE_IOERR_CORRUPTFS ){
102186    rc = SQLITE_CORRUPT_BKPT;
102187  }
102188  assert( rc );
102189#ifdef SQLITE_DEBUG
102190  if( db->flags & SQLITE_VdbeTrace ){
102191    const char *zTrace = p->zSql;
102192    if( zTrace==0 ){
102193      if( aOp[0].opcode==OP_Trace ){
102194        zTrace = aOp[0].p4.z;
102195      }
102196      if( zTrace==0 ) zTrace = "???";
102197    }
102198    printf("ABORT-due-to-error (rc=%d): %s\n", rc, zTrace);
102199  }
102200#endif
102201  if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
102202    sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
102203  }
102204  p->rc = rc;
102205  sqlite3SystemError(db, rc);
102206  testcase( sqlite3GlobalConfig.xLog!=0 );
102207  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
102208                   (int)(pOp - aOp), p->zSql, p->zErrMsg);
102209  if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
102210  if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
102211  if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){
102212    db->flags |= SQLITE_CorruptRdOnly;
102213  }
102214  rc = SQLITE_ERROR;
102215  if( resetSchemaOnFault>0 ){
102216    sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
102217  }
102218
102219  /* This is the only way out of this procedure.  We have to
102220  ** release the mutexes on btrees that were acquired at the
102221  ** top. */
102222vdbe_return:
102223#if defined(VDBE_PROFILE)
102224  if( pnCycle ){
102225    *pnCycle += sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
102226    pnCycle = 0;
102227  }
102228#elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
102229  if( pnCycle ){
102230    *pnCycle += sqlite3Hwtime();
102231    pnCycle = 0;
102232  }
102233#endif
102234
102235#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
102236  while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
102237    nProgressLimit += db->nProgressOps;
102238    if( db->xProgress(db->pProgressArg) ){
102239      nProgressLimit = LARGEST_UINT64;
102240      rc = SQLITE_INTERRUPT;
102241      goto abort_due_to_error;
102242    }
102243  }
102244#endif
102245  p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
102246  if( DbMaskNonZero(p->lockMask) ){
102247    sqlite3VdbeLeave(p);
102248  }
102249  assert( rc!=SQLITE_OK || nExtraDelete==0
102250       || sqlite3_strlike("DELETE%",p->zSql,0)!=0
102251  );
102252  return rc;
102253
102254  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
102255  ** is encountered.
102256  */
102257too_big:
102258  sqlite3VdbeError(p, "string or blob too big");
102259  rc = SQLITE_TOOBIG;
102260  goto abort_due_to_error;
102261
102262  /* Jump to here if a malloc() fails.
102263  */
102264no_mem:
102265  sqlite3OomFault(db);
102266  sqlite3VdbeError(p, "out of memory");
102267  rc = SQLITE_NOMEM_BKPT;
102268  goto abort_due_to_error;
102269
102270  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
102271  ** flag.
102272  */
102273abort_due_to_interrupt:
102274  assert( AtomicLoad(&db->u1.isInterrupted) );
102275  rc = SQLITE_INTERRUPT;
102276  goto abort_due_to_error;
102277}
102278
102279
102280/************** End of vdbe.c ************************************************/
102281/************** Begin file vdbeblob.c ****************************************/
102282/*
102283** 2007 May 1
102284**
102285** The author disclaims copyright to this source code.  In place of
102286** a legal notice, here is a blessing:
102287**
102288**    May you do good and not evil.
102289**    May you find forgiveness for yourself and forgive others.
102290**    May you share freely, never taking more than you give.
102291**
102292*************************************************************************
102293**
102294** This file contains code used to implement incremental BLOB I/O.
102295*/
102296
102297/* #include "sqliteInt.h" */
102298/* #include "vdbeInt.h" */
102299
102300#ifndef SQLITE_OMIT_INCRBLOB
102301
102302/*
102303** Valid sqlite3_blob* handles point to Incrblob structures.
102304*/
102305typedef struct Incrblob Incrblob;
102306struct Incrblob {
102307  int nByte;              /* Size of open blob, in bytes */
102308  int iOffset;            /* Byte offset of blob in cursor data */
102309  u16 iCol;               /* Table column this handle is open on */
102310  BtCursor *pCsr;         /* Cursor pointing at blob row */
102311  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
102312  sqlite3 *db;            /* The associated database */
102313  char *zDb;              /* Database name */
102314  Table *pTab;            /* Table object */
102315};
102316
102317
102318/*
102319** This function is used by both blob_open() and blob_reopen(). It seeks
102320** the b-tree cursor associated with blob handle p to point to row iRow.
102321** If successful, SQLITE_OK is returned and subsequent calls to
102322** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
102323**
102324** If an error occurs, or if the specified row does not exist or does not
102325** contain a value of type TEXT or BLOB in the column nominated when the
102326** blob handle was opened, then an error code is returned and *pzErr may
102327** be set to point to a buffer containing an error message. It is the
102328** responsibility of the caller to free the error message buffer using
102329** sqlite3DbFree().
102330**
102331** If an error does occur, then the b-tree cursor is closed. All subsequent
102332** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
102333** immediately return SQLITE_ABORT.
102334*/
102335static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
102336  int rc;                         /* Error code */
102337  char *zErr = 0;                 /* Error message */
102338  Vdbe *v = (Vdbe *)p->pStmt;
102339
102340  /* Set the value of register r[1] in the SQL statement to integer iRow.
102341  ** This is done directly as a performance optimization
102342  */
102343  sqlite3VdbeMemSetInt64(&v->aMem[1], iRow);
102344
102345  /* If the statement has been run before (and is paused at the OP_ResultRow)
102346  ** then back it up to the point where it does the OP_NotExists.  This could
102347  ** have been down with an extra OP_Goto, but simply setting the program
102348  ** counter is faster. */
102349  if( v->pc>4 ){
102350    v->pc = 4;
102351    assert( v->aOp[v->pc].opcode==OP_NotExists );
102352    rc = sqlite3VdbeExec(v);
102353  }else{
102354    rc = sqlite3_step(p->pStmt);
102355  }
102356  if( rc==SQLITE_ROW ){
102357    VdbeCursor *pC = v->apCsr[0];
102358    u32 type;
102359    assert( pC!=0 );
102360    assert( pC->eCurType==CURTYPE_BTREE );
102361    type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
102362    testcase( pC->nHdrParsed==p->iCol );
102363    testcase( pC->nHdrParsed==p->iCol+1 );
102364    if( type<12 ){
102365      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
102366          type==0?"null": type==7?"real": "integer"
102367      );
102368      rc = SQLITE_ERROR;
102369      sqlite3_finalize(p->pStmt);
102370      p->pStmt = 0;
102371    }else{
102372      p->iOffset = pC->aType[p->iCol + pC->nField];
102373      p->nByte = sqlite3VdbeSerialTypeLen(type);
102374      p->pCsr =  pC->uc.pCursor;
102375      sqlite3BtreeIncrblobCursor(p->pCsr);
102376    }
102377  }
102378
102379  if( rc==SQLITE_ROW ){
102380    rc = SQLITE_OK;
102381  }else if( p->pStmt ){
102382    rc = sqlite3_finalize(p->pStmt);
102383    p->pStmt = 0;
102384    if( rc==SQLITE_OK ){
102385      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
102386      rc = SQLITE_ERROR;
102387    }else{
102388      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
102389    }
102390  }
102391
102392  assert( rc!=SQLITE_OK || zErr==0 );
102393  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
102394
102395  *pzErr = zErr;
102396  return rc;
102397}
102398
102399/*
102400** Open a blob handle.
102401*/
102402SQLITE_API int sqlite3_blob_open(
102403  sqlite3* db,            /* The database connection */
102404  const char *zDb,        /* The attached database containing the blob */
102405  const char *zTable,     /* The table containing the blob */
102406  const char *zColumn,    /* The column containing the blob */
102407  sqlite_int64 iRow,      /* The row containing the glob */
102408  int wrFlag,             /* True -> read/write access, false -> read-only */
102409  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
102410){
102411  int nAttempt = 0;
102412  int iCol;               /* Index of zColumn in row-record */
102413  int rc = SQLITE_OK;
102414  char *zErr = 0;
102415  Table *pTab;
102416  Incrblob *pBlob = 0;
102417  Parse sParse;
102418
102419#ifdef SQLITE_ENABLE_API_ARMOR
102420  if( ppBlob==0 ){
102421    return SQLITE_MISUSE_BKPT;
102422  }
102423#endif
102424  *ppBlob = 0;
102425#ifdef SQLITE_ENABLE_API_ARMOR
102426  if( !sqlite3SafetyCheckOk(db) || zTable==0 || zColumn==0 ){
102427    return SQLITE_MISUSE_BKPT;
102428  }
102429#endif
102430  wrFlag = !!wrFlag;                /* wrFlag = (wrFlag ? 1 : 0); */
102431
102432  sqlite3_mutex_enter(db->mutex);
102433
102434  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
102435  while(1){
102436    sqlite3ParseObjectInit(&sParse,db);
102437    if( !pBlob ) goto blob_open_out;
102438    sqlite3DbFree(db, zErr);
102439    zErr = 0;
102440
102441    sqlite3BtreeEnterAll(db);
102442    pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
102443    if( pTab && IsVirtual(pTab) ){
102444      pTab = 0;
102445      sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
102446    }
102447    if( pTab && !HasRowid(pTab) ){
102448      pTab = 0;
102449      sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
102450    }
102451#ifndef SQLITE_OMIT_VIEW
102452    if( pTab && IsView(pTab) ){
102453      pTab = 0;
102454      sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
102455    }
102456#endif
102457    if( !pTab ){
102458      if( sParse.zErrMsg ){
102459        sqlite3DbFree(db, zErr);
102460        zErr = sParse.zErrMsg;
102461        sParse.zErrMsg = 0;
102462      }
102463      rc = SQLITE_ERROR;
102464      sqlite3BtreeLeaveAll(db);
102465      goto blob_open_out;
102466    }
102467    pBlob->pTab = pTab;
102468    pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
102469
102470    /* Now search pTab for the exact column. */
102471    for(iCol=0; iCol<pTab->nCol; iCol++) {
102472      if( sqlite3StrICmp(pTab->aCol[iCol].zCnName, zColumn)==0 ){
102473        break;
102474      }
102475    }
102476    if( iCol==pTab->nCol ){
102477      sqlite3DbFree(db, zErr);
102478      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
102479      rc = SQLITE_ERROR;
102480      sqlite3BtreeLeaveAll(db);
102481      goto blob_open_out;
102482    }
102483
102484    /* If the value is being opened for writing, check that the
102485    ** column is not indexed, and that it is not part of a foreign key.
102486    */
102487    if( wrFlag ){
102488      const char *zFault = 0;
102489      Index *pIdx;
102490#ifndef SQLITE_OMIT_FOREIGN_KEY
102491      if( db->flags&SQLITE_ForeignKeys ){
102492        /* Check that the column is not part of an FK child key definition. It
102493        ** is not necessary to check if it is part of a parent key, as parent
102494        ** key columns must be indexed. The check below will pick up this
102495        ** case.  */
102496        FKey *pFKey;
102497        assert( IsOrdinaryTable(pTab) );
102498        for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
102499          int j;
102500          for(j=0; j<pFKey->nCol; j++){
102501            if( pFKey->aCol[j].iFrom==iCol ){
102502              zFault = "foreign key";
102503            }
102504          }
102505        }
102506      }
102507#endif
102508      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102509        int j;
102510        for(j=0; j<pIdx->nKeyCol; j++){
102511          /* FIXME: Be smarter about indexes that use expressions */
102512          if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
102513            zFault = "indexed";
102514          }
102515        }
102516      }
102517      if( zFault ){
102518        sqlite3DbFree(db, zErr);
102519        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
102520        rc = SQLITE_ERROR;
102521        sqlite3BtreeLeaveAll(db);
102522        goto blob_open_out;
102523      }
102524    }
102525
102526    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
102527    assert( pBlob->pStmt || db->mallocFailed );
102528    if( pBlob->pStmt ){
102529
102530      /* This VDBE program seeks a btree cursor to the identified
102531      ** db/table/row entry. The reason for using a vdbe program instead
102532      ** of writing code to use the b-tree layer directly is that the
102533      ** vdbe program will take advantage of the various transaction,
102534      ** locking and error handling infrastructure built into the vdbe.
102535      **
102536      ** After seeking the cursor, the vdbe executes an OP_ResultRow.
102537      ** Code external to the Vdbe then "borrows" the b-tree cursor and
102538      ** uses it to implement the blob_read(), blob_write() and
102539      ** blob_bytes() functions.
102540      **
102541      ** The sqlite3_blob_close() function finalizes the vdbe program,
102542      ** which closes the b-tree cursor and (possibly) commits the
102543      ** transaction.
102544      */
102545      static const int iLn = VDBE_OFFSET_LINENO(2);
102546      static const VdbeOpList openBlob[] = {
102547        {OP_TableLock,      0, 0, 0},  /* 0: Acquire a read or write lock */
102548        {OP_OpenRead,       0, 0, 0},  /* 1: Open a cursor */
102549        /* blobSeekToRow() will initialize r[1] to the desired rowid */
102550        {OP_NotExists,      0, 5, 1},  /* 2: Seek the cursor to rowid=r[1] */
102551        {OP_Column,         0, 0, 1},  /* 3  */
102552        {OP_ResultRow,      1, 0, 0},  /* 4  */
102553        {OP_Halt,           0, 0, 0},  /* 5  */
102554      };
102555      Vdbe *v = (Vdbe *)pBlob->pStmt;
102556      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102557      VdbeOp *aOp;
102558
102559      sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
102560                           pTab->pSchema->schema_cookie,
102561                           pTab->pSchema->iGeneration);
102562      sqlite3VdbeChangeP5(v, 1);
102563      assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
102564      aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
102565
102566      /* Make sure a mutex is held on the table to be accessed */
102567      sqlite3VdbeUsesBtree(v, iDb);
102568
102569      if( db->mallocFailed==0 ){
102570        assert( aOp!=0 );
102571        /* Configure the OP_TableLock instruction */
102572#ifdef SQLITE_OMIT_SHARED_CACHE
102573        aOp[0].opcode = OP_Noop;
102574#else
102575        aOp[0].p1 = iDb;
102576        aOp[0].p2 = pTab->tnum;
102577        aOp[0].p3 = wrFlag;
102578        sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
102579      }
102580      if( db->mallocFailed==0 ){
102581#endif
102582
102583        /* Remove either the OP_OpenWrite or OpenRead. Set the P2
102584        ** parameter of the other to pTab->tnum.  */
102585        if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
102586        aOp[1].p2 = pTab->tnum;
102587        aOp[1].p3 = iDb;
102588
102589        /* Configure the number of columns. Configure the cursor to
102590        ** think that the table has one more column than it really
102591        ** does. An OP_Column to retrieve this imaginary column will
102592        ** always return an SQL NULL. This is useful because it means
102593        ** we can invoke OP_Column to fill in the vdbe cursors type
102594        ** and offset cache without causing any IO.
102595        */
102596        aOp[1].p4type = P4_INT32;
102597        aOp[1].p4.i = pTab->nCol+1;
102598        aOp[3].p2 = pTab->nCol;
102599
102600        sParse.nVar = 0;
102601        sParse.nMem = 1;
102602        sParse.nTab = 1;
102603        sqlite3VdbeMakeReady(v, &sParse);
102604      }
102605    }
102606
102607    pBlob->iCol = iCol;
102608    pBlob->db = db;
102609    sqlite3BtreeLeaveAll(db);
102610    if( db->mallocFailed ){
102611      goto blob_open_out;
102612    }
102613    rc = blobSeekToRow(pBlob, iRow, &zErr);
102614    if( (++nAttempt)>=SQLITE_MAX_SCHEMA_RETRY || rc!=SQLITE_SCHEMA ) break;
102615    sqlite3ParseObjectReset(&sParse);
102616  }
102617
102618blob_open_out:
102619  if( rc==SQLITE_OK && db->mallocFailed==0 ){
102620    *ppBlob = (sqlite3_blob *)pBlob;
102621  }else{
102622    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
102623    sqlite3DbFree(db, pBlob);
102624  }
102625  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : (char*)0), zErr);
102626  sqlite3DbFree(db, zErr);
102627  sqlite3ParseObjectReset(&sParse);
102628  rc = sqlite3ApiExit(db, rc);
102629  sqlite3_mutex_leave(db->mutex);
102630  return rc;
102631}
102632
102633/*
102634** Close a blob handle that was previously created using
102635** sqlite3_blob_open().
102636*/
102637SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
102638  Incrblob *p = (Incrblob *)pBlob;
102639  int rc;
102640  sqlite3 *db;
102641
102642  if( p ){
102643    sqlite3_stmt *pStmt = p->pStmt;
102644    db = p->db;
102645    sqlite3_mutex_enter(db->mutex);
102646    sqlite3DbFree(db, p);
102647    sqlite3_mutex_leave(db->mutex);
102648    rc = sqlite3_finalize(pStmt);
102649  }else{
102650    rc = SQLITE_OK;
102651  }
102652  return rc;
102653}
102654
102655/*
102656** Perform a read or write operation on a blob
102657*/
102658static int blobReadWrite(
102659  sqlite3_blob *pBlob,
102660  void *z,
102661  int n,
102662  int iOffset,
102663  int (*xCall)(BtCursor*, u32, u32, void*)
102664){
102665  int rc;
102666  Incrblob *p = (Incrblob *)pBlob;
102667  Vdbe *v;
102668  sqlite3 *db;
102669
102670  if( p==0 ) return SQLITE_MISUSE_BKPT;
102671  db = p->db;
102672  sqlite3_mutex_enter(db->mutex);
102673  v = (Vdbe*)p->pStmt;
102674
102675  if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
102676    /* Request is out of range. Return a transient error. */
102677    rc = SQLITE_ERROR;
102678  }else if( v==0 ){
102679    /* If there is no statement handle, then the blob-handle has
102680    ** already been invalidated. Return SQLITE_ABORT in this case.
102681    */
102682    rc = SQLITE_ABORT;
102683  }else{
102684    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
102685    ** returned, clean-up the statement handle.
102686    */
102687    assert( db == v->db );
102688    sqlite3BtreeEnterCursor(p->pCsr);
102689
102690#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
102691    if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
102692      /* If a pre-update hook is registered and this is a write cursor,
102693      ** invoke it here.
102694      **
102695      ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
102696      ** operation should really be an SQLITE_UPDATE. This is probably
102697      ** incorrect, but is convenient because at this point the new.* values
102698      ** are not easily obtainable. And for the sessions module, an
102699      ** SQLITE_UPDATE where the PK columns do not change is handled in the
102700      ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
102701      ** slightly more efficient). Since you cannot write to a PK column
102702      ** using the incremental-blob API, this works. For the sessions module
102703      ** anyhow.
102704      */
102705      sqlite3_int64 iKey;
102706      iKey = sqlite3BtreeIntegerKey(p->pCsr);
102707      assert( v->apCsr[0]!=0 );
102708      assert( v->apCsr[0]->eCurType==CURTYPE_BTREE );
102709      sqlite3VdbePreUpdateHook(
102710          v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1, p->iCol
102711      );
102712    }
102713#endif
102714
102715    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
102716    sqlite3BtreeLeaveCursor(p->pCsr);
102717    if( rc==SQLITE_ABORT ){
102718      sqlite3VdbeFinalize(v);
102719      p->pStmt = 0;
102720    }else{
102721      v->rc = rc;
102722    }
102723  }
102724  sqlite3Error(db, rc);
102725  rc = sqlite3ApiExit(db, rc);
102726  sqlite3_mutex_leave(db->mutex);
102727  return rc;
102728}
102729
102730/*
102731** Read data from a blob handle.
102732*/
102733SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
102734  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
102735}
102736
102737/*
102738** Write data to a blob handle.
102739*/
102740SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
102741  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
102742}
102743
102744/*
102745** Query a blob handle for the size of the data.
102746**
102747** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
102748** so no mutex is required for access.
102749*/
102750SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
102751  Incrblob *p = (Incrblob *)pBlob;
102752  return (p && p->pStmt) ? p->nByte : 0;
102753}
102754
102755/*
102756** Move an existing blob handle to point to a different row of the same
102757** database table.
102758**
102759** If an error occurs, or if the specified row does not exist or does not
102760** contain a blob or text value, then an error code is returned and the
102761** database handle error code and message set. If this happens, then all
102762** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
102763** immediately return SQLITE_ABORT.
102764*/
102765SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
102766  int rc;
102767  Incrblob *p = (Incrblob *)pBlob;
102768  sqlite3 *db;
102769
102770  if( p==0 ) return SQLITE_MISUSE_BKPT;
102771  db = p->db;
102772  sqlite3_mutex_enter(db->mutex);
102773
102774  if( p->pStmt==0 ){
102775    /* If there is no statement handle, then the blob-handle has
102776    ** already been invalidated. Return SQLITE_ABORT in this case.
102777    */
102778    rc = SQLITE_ABORT;
102779  }else{
102780    char *zErr;
102781    ((Vdbe*)p->pStmt)->rc = SQLITE_OK;
102782    rc = blobSeekToRow(p, iRow, &zErr);
102783    if( rc!=SQLITE_OK ){
102784      sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : (char*)0), zErr);
102785      sqlite3DbFree(db, zErr);
102786    }
102787    assert( rc!=SQLITE_SCHEMA );
102788  }
102789
102790  rc = sqlite3ApiExit(db, rc);
102791  assert( rc==SQLITE_OK || p->pStmt==0 );
102792  sqlite3_mutex_leave(db->mutex);
102793  return rc;
102794}
102795
102796#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
102797
102798/************** End of vdbeblob.c ********************************************/
102799/************** Begin file vdbesort.c ****************************************/
102800/*
102801** 2011-07-09
102802**
102803** The author disclaims copyright to this source code.  In place of
102804** a legal notice, here is a blessing:
102805**
102806**    May you do good and not evil.
102807**    May you find forgiveness for yourself and forgive others.
102808**    May you share freely, never taking more than you give.
102809**
102810*************************************************************************
102811** This file contains code for the VdbeSorter object, used in concert with
102812** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
102813** or by SELECT statements with ORDER BY clauses that cannot be satisfied
102814** using indexes and without LIMIT clauses.
102815**
102816** The VdbeSorter object implements a multi-threaded external merge sort
102817** algorithm that is efficient even if the number of elements being sorted
102818** exceeds the available memory.
102819**
102820** Here is the (internal, non-API) interface between this module and the
102821** rest of the SQLite system:
102822**
102823**    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
102824**
102825**    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
102826**                                  object.  The row is a binary blob in the
102827**                                  OP_MakeRecord format that contains both
102828**                                  the ORDER BY key columns and result columns
102829**                                  in the case of a SELECT w/ ORDER BY, or
102830**                                  the complete record for an index entry
102831**                                  in the case of a CREATE INDEX.
102832**
102833**    sqlite3VdbeSorterRewind()     Sort all content previously added.
102834**                                  Position the read cursor on the
102835**                                  first sorted element.
102836**
102837**    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
102838**                                  element.
102839**
102840**    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
102841**                                  row currently under the read cursor.
102842**
102843**    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
102844**                                  currently under the read cursor against
102845**                                  another binary blob X and report if
102846**                                  X is strictly less than the read cursor.
102847**                                  Used to enforce uniqueness in a
102848**                                  CREATE UNIQUE INDEX statement.
102849**
102850**    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
102851**                                  all resources.
102852**
102853**    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
102854**                                  is like Close() followed by Init() only
102855**                                  much faster.
102856**
102857** The interfaces above must be called in a particular order.  Write() can
102858** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
102859** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
102860**
102861**   Init()
102862**   for each record: Write()
102863**   Rewind()
102864**     Rowkey()/Compare()
102865**   Next()
102866**   Close()
102867**
102868** Algorithm:
102869**
102870** Records passed to the sorter via calls to Write() are initially held
102871** unsorted in main memory. Assuming the amount of memory used never exceeds
102872** a threshold, when Rewind() is called the set of records is sorted using
102873** an in-memory merge sort. In this case, no temporary files are required
102874** and subsequent calls to Rowkey(), Next() and Compare() read records
102875** directly from main memory.
102876**
102877** If the amount of space used to store records in main memory exceeds the
102878** threshold, then the set of records currently in memory are sorted and
102879** written to a temporary file in "Packed Memory Array" (PMA) format.
102880** A PMA created at this point is known as a "level-0 PMA". Higher levels
102881** of PMAs may be created by merging existing PMAs together - for example
102882** merging two or more level-0 PMAs together creates a level-1 PMA.
102883**
102884** The threshold for the amount of main memory to use before flushing
102885** records to a PMA is roughly the same as the limit configured for the
102886** page-cache of the main database. Specifically, the threshold is set to
102887** the value returned by "PRAGMA main.page_size" multiplied by
102888** that returned by "PRAGMA main.cache_size", in bytes.
102889**
102890** If the sorter is running in single-threaded mode, then all PMAs generated
102891** are appended to a single temporary file. Or, if the sorter is running in
102892** multi-threaded mode then up to (N+1) temporary files may be opened, where
102893** N is the configured number of worker threads. In this case, instead of
102894** sorting the records and writing the PMA to a temporary file itself, the
102895** calling thread usually launches a worker thread to do so. Except, if
102896** there are already N worker threads running, the main thread does the work
102897** itself.
102898**
102899** The sorter is running in multi-threaded mode if (a) the library was built
102900** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
102901** than zero, and (b) worker threads have been enabled at runtime by calling
102902** "PRAGMA threads=N" with some value of N greater than 0.
102903**
102904** When Rewind() is called, any data remaining in memory is flushed to a
102905** final PMA. So at this point the data is stored in some number of sorted
102906** PMAs within temporary files on disk.
102907**
102908** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
102909** sorter is running in single-threaded mode, then these PMAs are merged
102910** incrementally as keys are retrieved from the sorter by the VDBE.  The
102911** MergeEngine object, described in further detail below, performs this
102912** merge.
102913**
102914** Or, if running in multi-threaded mode, then a background thread is
102915** launched to merge the existing PMAs. Once the background thread has
102916** merged T bytes of data into a single sorted PMA, the main thread
102917** begins reading keys from that PMA while the background thread proceeds
102918** with merging the next T bytes of data. And so on.
102919**
102920** Parameter T is set to half the value of the memory threshold used
102921** by Write() above to determine when to create a new PMA.
102922**
102923** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
102924** Rewind() is called, then a hierarchy of incremental-merges is used.
102925** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
102926** disk are merged together. Then T bytes of data from the second set, and
102927** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
102928** PMAs at a time. This done is to improve locality.
102929**
102930** If running in multi-threaded mode and there are more than
102931** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
102932** than one background thread may be created. Specifically, there may be
102933** one background thread for each temporary file on disk, and one background
102934** thread to merge the output of each of the others to a single PMA for
102935** the main thread to read from.
102936*/
102937/* #include "sqliteInt.h" */
102938/* #include "vdbeInt.h" */
102939
102940/*
102941** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
102942** messages to stderr that may be helpful in understanding the performance
102943** characteristics of the sorter in multi-threaded mode.
102944*/
102945#if 0
102946# define SQLITE_DEBUG_SORTER_THREADS 1
102947#endif
102948
102949/*
102950** Hard-coded maximum amount of data to accumulate in memory before flushing
102951** to a level 0 PMA. The purpose of this limit is to prevent various integer
102952** overflows. 512MiB.
102953*/
102954#define SQLITE_MAX_PMASZ    (1<<29)
102955
102956/*
102957** Private objects used by the sorter
102958*/
102959typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
102960typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
102961typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
102962typedef struct SorterRecord SorterRecord;   /* A record being sorted */
102963typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
102964typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
102965typedef struct SorterList SorterList;       /* In-memory list of records */
102966typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
102967
102968/*
102969** A container for a temp file handle and the current amount of data
102970** stored in the file.
102971*/
102972struct SorterFile {
102973  sqlite3_file *pFd;              /* File handle */
102974  i64 iEof;                       /* Bytes of data stored in pFd */
102975};
102976
102977/*
102978** An in-memory list of objects to be sorted.
102979**
102980** If aMemory==0 then each object is allocated separately and the objects
102981** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
102982** are stored in the aMemory[] bulk memory, one right after the other, and
102983** are connected using SorterRecord.u.iNext.
102984*/
102985struct SorterList {
102986  SorterRecord *pList;            /* Linked list of records */
102987  u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
102988  i64 szPMA;                      /* Size of pList as PMA in bytes */
102989};
102990
102991/*
102992** The MergeEngine object is used to combine two or more smaller PMAs into
102993** one big PMA using a merge operation.  Separate PMAs all need to be
102994** combined into one big PMA in order to be able to step through the sorted
102995** records in order.
102996**
102997** The aReadr[] array contains a PmaReader object for each of the PMAs being
102998** merged.  An aReadr[] object either points to a valid key or else is at EOF.
102999** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
103000** For the purposes of the paragraphs below, we assume that the array is
103001** actually N elements in size, where N is the smallest power of 2 greater
103002** to or equal to the number of PMAs being merged. The extra aReadr[] elements
103003** are treated as if they are empty (always at EOF).
103004**
103005** The aTree[] array is also N elements in size. The value of N is stored in
103006** the MergeEngine.nTree variable.
103007**
103008** The final (N/2) elements of aTree[] contain the results of comparing
103009** pairs of PMA keys together. Element i contains the result of
103010** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
103011** aTree element is set to the index of it.
103012**
103013** For the purposes of this comparison, EOF is considered greater than any
103014** other key value. If the keys are equal (only possible with two EOF
103015** values), it doesn't matter which index is stored.
103016**
103017** The (N/4) elements of aTree[] that precede the final (N/2) described
103018** above contains the index of the smallest of each block of 4 PmaReaders
103019** And so on. So that aTree[1] contains the index of the PmaReader that
103020** currently points to the smallest key value. aTree[0] is unused.
103021**
103022** Example:
103023**
103024**     aReadr[0] -> Banana
103025**     aReadr[1] -> Feijoa
103026**     aReadr[2] -> Elderberry
103027**     aReadr[3] -> Currant
103028**     aReadr[4] -> Grapefruit
103029**     aReadr[5] -> Apple
103030**     aReadr[6] -> Durian
103031**     aReadr[7] -> EOF
103032**
103033**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
103034**
103035** The current element is "Apple" (the value of the key indicated by
103036** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
103037** be advanced to the next key in its segment. Say the next key is
103038** "Eggplant":
103039**
103040**     aReadr[5] -> Eggplant
103041**
103042** The contents of aTree[] are updated first by comparing the new PmaReader
103043** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
103044** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
103045** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
103046** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
103047** so the value written into element 1 of the array is 0. As follows:
103048**
103049**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
103050**
103051** In other words, each time we advance to the next sorter element, log2(N)
103052** key comparison operations are required, where N is the number of segments
103053** being merged (rounded up to the next power of 2).
103054*/
103055struct MergeEngine {
103056  int nTree;                 /* Used size of aTree/aReadr (power of 2) */
103057  SortSubtask *pTask;        /* Used by this thread only */
103058  int *aTree;                /* Current state of incremental merge */
103059  PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
103060};
103061
103062/*
103063** This object represents a single thread of control in a sort operation.
103064** Exactly VdbeSorter.nTask instances of this object are allocated
103065** as part of each VdbeSorter object. Instances are never allocated any
103066** other way. VdbeSorter.nTask is set to the number of worker threads allowed
103067** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
103068** single-threaded operation, there is exactly one instance of this object
103069** and for multi-threaded operation there are two or more instances.
103070**
103071** Essentially, this structure contains all those fields of the VdbeSorter
103072** structure for which each thread requires a separate instance. For example,
103073** each thread requeries its own UnpackedRecord object to unpack records in
103074** as part of comparison operations.
103075**
103076** Before a background thread is launched, variable bDone is set to 0. Then,
103077** right before it exits, the thread itself sets bDone to 1. This is used for
103078** two purposes:
103079**
103080**   1. When flushing the contents of memory to a level-0 PMA on disk, to
103081**      attempt to select a SortSubtask for which there is not already an
103082**      active background thread (since doing so causes the main thread
103083**      to block until it finishes).
103084**
103085**   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
103086**      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
103087**      block provoke debugging output.
103088**
103089** In both cases, the effects of the main thread seeing (bDone==0) even
103090** after the thread has finished are not dire. So we don't worry about
103091** memory barriers and such here.
103092*/
103093typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
103094struct SortSubtask {
103095  SQLiteThread *pThread;          /* Background thread, if any */
103096  int bDone;                      /* Set if thread is finished but not joined */
103097  int nPMA;                       /* Number of PMAs currently in file */
103098  VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
103099  UnpackedRecord *pUnpacked;      /* Space to unpack a record */
103100  SorterList list;                /* List for thread to write to a PMA */
103101  SorterCompare xCompare;         /* Compare function to use */
103102  SorterFile file;                /* Temp file for level-0 PMAs */
103103  SorterFile file2;               /* Space for other PMAs */
103104};
103105
103106
103107/*
103108** Main sorter structure. A single instance of this is allocated for each
103109** sorter cursor created by the VDBE.
103110**
103111** mxKeysize:
103112**   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
103113**   this variable is updated so as to be set to the size on disk of the
103114**   largest record in the sorter.
103115*/
103116struct VdbeSorter {
103117  int mnPmaSize;                  /* Minimum PMA size, in bytes */
103118  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
103119  int mxKeysize;                  /* Largest serialized key seen so far */
103120  int pgsz;                       /* Main database page size */
103121  PmaReader *pReader;             /* Readr data from here after Rewind() */
103122  MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
103123  sqlite3 *db;                    /* Database connection */
103124  KeyInfo *pKeyInfo;              /* How to compare records */
103125  UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
103126  SorterList list;                /* List of in-memory records */
103127  int iMemory;                    /* Offset of free space in list.aMemory */
103128  int nMemory;                    /* Size of list.aMemory allocation in bytes */
103129  u8 bUsePMA;                     /* True if one or more PMAs created */
103130  u8 bUseThreads;                 /* True to use background threads */
103131  u8 iPrev;                       /* Previous thread used to flush PMA */
103132  u8 nTask;                       /* Size of aTask[] array */
103133  u8 typeMask;
103134  SortSubtask aTask[1];           /* One or more subtasks */
103135};
103136
103137#define SORTER_TYPE_INTEGER 0x01
103138#define SORTER_TYPE_TEXT    0x02
103139
103140/*
103141** An instance of the following object is used to read records out of a
103142** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
103143** aKey might point into aMap or into aBuffer.  If neither of those locations
103144** contain a contiguous representation of the key, then aAlloc is allocated
103145** and the key is copied into aAlloc and aKey is made to point to aAlloc.
103146**
103147** pFd==0 at EOF.
103148*/
103149struct PmaReader {
103150  i64 iReadOff;               /* Current read offset */
103151  i64 iEof;                   /* 1 byte past EOF for this PmaReader */
103152  int nAlloc;                 /* Bytes of space at aAlloc */
103153  int nKey;                   /* Number of bytes in key */
103154  sqlite3_file *pFd;          /* File handle we are reading from */
103155  u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
103156  u8 *aKey;                   /* Pointer to current key */
103157  u8 *aBuffer;                /* Current read buffer */
103158  int nBuffer;                /* Size of read buffer in bytes */
103159  u8 *aMap;                   /* Pointer to mapping of entire file */
103160  IncrMerger *pIncr;          /* Incremental merger */
103161};
103162
103163/*
103164** Normally, a PmaReader object iterates through an existing PMA stored
103165** within a temp file. However, if the PmaReader.pIncr variable points to
103166** an object of the following type, it may be used to iterate/merge through
103167** multiple PMAs simultaneously.
103168**
103169** There are two types of IncrMerger object - single (bUseThread==0) and
103170** multi-threaded (bUseThread==1).
103171**
103172** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
103173** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
103174** size. When the IncrMerger is initialized, it reads enough data from
103175** pMerger to populate aFile[0]. It then sets variables within the
103176** corresponding PmaReader object to read from that file and kicks off
103177** a background thread to populate aFile[1] with the next mxSz bytes of
103178** sorted record data from pMerger.
103179**
103180** When the PmaReader reaches the end of aFile[0], it blocks until the
103181** background thread has finished populating aFile[1]. It then exchanges
103182** the contents of the aFile[0] and aFile[1] variables within this structure,
103183** sets the PmaReader fields to read from the new aFile[0] and kicks off
103184** another background thread to populate the new aFile[1]. And so on, until
103185** the contents of pMerger are exhausted.
103186**
103187** A single-threaded IncrMerger does not open any temporary files of its
103188** own. Instead, it has exclusive access to mxSz bytes of space beginning
103189** at offset iStartOff of file pTask->file2. And instead of using a
103190** background thread to prepare data for the PmaReader, with a single
103191** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
103192** keys from pMerger by the calling thread whenever the PmaReader runs out
103193** of data.
103194*/
103195struct IncrMerger {
103196  SortSubtask *pTask;             /* Task that owns this merger */
103197  MergeEngine *pMerger;           /* Merge engine thread reads data from */
103198  i64 iStartOff;                  /* Offset to start writing file at */
103199  int mxSz;                       /* Maximum bytes of data to store */
103200  int bEof;                       /* Set to true when merge is finished */
103201  int bUseThread;                 /* True to use a bg thread for this object */
103202  SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
103203};
103204
103205/*
103206** An instance of this object is used for writing a PMA.
103207**
103208** The PMA is written one record at a time.  Each record is of an arbitrary
103209** size.  But I/O is more efficient if it occurs in page-sized blocks where
103210** each block is aligned on a page boundary.  This object caches writes to
103211** the PMA so that aligned, page-size blocks are written.
103212*/
103213struct PmaWriter {
103214  int eFWErr;                     /* Non-zero if in an error state */
103215  u8 *aBuffer;                    /* Pointer to write buffer */
103216  int nBuffer;                    /* Size of write buffer in bytes */
103217  int iBufStart;                  /* First byte of buffer to write */
103218  int iBufEnd;                    /* Last byte of buffer to write */
103219  i64 iWriteOff;                  /* Offset of start of buffer in file */
103220  sqlite3_file *pFd;              /* File handle to write to */
103221};
103222
103223/*
103224** This object is the header on a single record while that record is being
103225** held in memory and prior to being written out as part of a PMA.
103226**
103227** How the linked list is connected depends on how memory is being managed
103228** by this module. If using a separate allocation for each in-memory record
103229** (VdbeSorter.list.aMemory==0), then the list is always connected using the
103230** SorterRecord.u.pNext pointers.
103231**
103232** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
103233** then while records are being accumulated the list is linked using the
103234** SorterRecord.u.iNext offset. This is because the aMemory[] array may
103235** be sqlite3Realloc()ed while records are being accumulated. Once the VM
103236** has finished passing records to the sorter, or when the in-memory buffer
103237** is full, the list is sorted. As part of the sorting process, it is
103238** converted to use the SorterRecord.u.pNext pointers. See function
103239** vdbeSorterSort() for details.
103240*/
103241struct SorterRecord {
103242  int nVal;                       /* Size of the record in bytes */
103243  union {
103244    SorterRecord *pNext;          /* Pointer to next record in list */
103245    int iNext;                    /* Offset within aMemory of next record */
103246  } u;
103247  /* The data for the record immediately follows this header */
103248};
103249
103250/* Return a pointer to the buffer containing the record data for SorterRecord
103251** object p. Should be used as if:
103252**
103253**   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
103254*/
103255#define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
103256
103257
103258/* Maximum number of PMAs that a single MergeEngine can merge */
103259#define SORTER_MAX_MERGE_COUNT 16
103260
103261static int vdbeIncrSwap(IncrMerger*);
103262static void vdbeIncrFree(IncrMerger *);
103263
103264/*
103265** Free all memory belonging to the PmaReader object passed as the
103266** argument. All structure fields are set to zero before returning.
103267*/
103268static void vdbePmaReaderClear(PmaReader *pReadr){
103269  sqlite3_free(pReadr->aAlloc);
103270  sqlite3_free(pReadr->aBuffer);
103271  if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
103272  vdbeIncrFree(pReadr->pIncr);
103273  memset(pReadr, 0, sizeof(PmaReader));
103274}
103275
103276/*
103277** Read the next nByte bytes of data from the PMA p.
103278** If successful, set *ppOut to point to a buffer containing the data
103279** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
103280** error code.
103281**
103282** The buffer returned in *ppOut is only valid until the
103283** next call to this function.
103284*/
103285static int vdbePmaReadBlob(
103286  PmaReader *p,                   /* PmaReader from which to take the blob */
103287  int nByte,                      /* Bytes of data to read */
103288  u8 **ppOut                      /* OUT: Pointer to buffer containing data */
103289){
103290  int iBuf;                       /* Offset within buffer to read from */
103291  int nAvail;                     /* Bytes of data available in buffer */
103292
103293  if( p->aMap ){
103294    *ppOut = &p->aMap[p->iReadOff];
103295    p->iReadOff += nByte;
103296    return SQLITE_OK;
103297  }
103298
103299  assert( p->aBuffer );
103300
103301  /* If there is no more data to be read from the buffer, read the next
103302  ** p->nBuffer bytes of data from the file into it. Or, if there are less
103303  ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
103304  iBuf = p->iReadOff % p->nBuffer;
103305  if( iBuf==0 ){
103306    int nRead;                    /* Bytes to read from disk */
103307    int rc;                       /* sqlite3OsRead() return code */
103308
103309    /* Determine how many bytes of data to read. */
103310    if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
103311      nRead = p->nBuffer;
103312    }else{
103313      nRead = (int)(p->iEof - p->iReadOff);
103314    }
103315    assert( nRead>0 );
103316
103317    /* Readr data from the file. Return early if an error occurs. */
103318    rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
103319    assert( rc!=SQLITE_IOERR_SHORT_READ );
103320    if( rc!=SQLITE_OK ) return rc;
103321  }
103322  nAvail = p->nBuffer - iBuf;
103323
103324  if( nByte<=nAvail ){
103325    /* The requested data is available in the in-memory buffer. In this
103326    ** case there is no need to make a copy of the data, just return a
103327    ** pointer into the buffer to the caller.  */
103328    *ppOut = &p->aBuffer[iBuf];
103329    p->iReadOff += nByte;
103330  }else{
103331    /* The requested data is not all available in the in-memory buffer.
103332    ** In this case, allocate space at p->aAlloc[] to copy the requested
103333    ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
103334    int nRem;                     /* Bytes remaining to copy */
103335
103336    /* Extend the p->aAlloc[] allocation if required. */
103337    if( p->nAlloc<nByte ){
103338      u8 *aNew;
103339      sqlite3_int64 nNew = MAX(128, 2*(sqlite3_int64)p->nAlloc);
103340      while( nByte>nNew ) nNew = nNew*2;
103341      aNew = sqlite3Realloc(p->aAlloc, nNew);
103342      if( !aNew ) return SQLITE_NOMEM_BKPT;
103343      p->nAlloc = nNew;
103344      p->aAlloc = aNew;
103345    }
103346
103347    /* Copy as much data as is available in the buffer into the start of
103348    ** p->aAlloc[].  */
103349    memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
103350    p->iReadOff += nAvail;
103351    nRem = nByte - nAvail;
103352
103353    /* The following loop copies up to p->nBuffer bytes per iteration into
103354    ** the p->aAlloc[] buffer.  */
103355    while( nRem>0 ){
103356      int rc;                     /* vdbePmaReadBlob() return code */
103357      int nCopy;                  /* Number of bytes to copy */
103358      u8 *aNext;                  /* Pointer to buffer to copy data from */
103359
103360      nCopy = nRem;
103361      if( nRem>p->nBuffer ) nCopy = p->nBuffer;
103362      rc = vdbePmaReadBlob(p, nCopy, &aNext);
103363      if( rc!=SQLITE_OK ) return rc;
103364      assert( aNext!=p->aAlloc );
103365      memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
103366      nRem -= nCopy;
103367    }
103368
103369    *ppOut = p->aAlloc;
103370  }
103371
103372  return SQLITE_OK;
103373}
103374
103375/*
103376** Read a varint from the stream of data accessed by p. Set *pnOut to
103377** the value read.
103378*/
103379static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
103380  int iBuf;
103381
103382  if( p->aMap ){
103383    p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
103384  }else{
103385    iBuf = p->iReadOff % p->nBuffer;
103386    if( iBuf && (p->nBuffer-iBuf)>=9 ){
103387      p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
103388    }else{
103389      u8 aVarint[16], *a;
103390      int i = 0, rc;
103391      do{
103392        rc = vdbePmaReadBlob(p, 1, &a);
103393        if( rc ) return rc;
103394        aVarint[(i++)&0xf] = a[0];
103395      }while( (a[0]&0x80)!=0 );
103396      sqlite3GetVarint(aVarint, pnOut);
103397    }
103398  }
103399
103400  return SQLITE_OK;
103401}
103402
103403/*
103404** Attempt to memory map file pFile. If successful, set *pp to point to the
103405** new mapping and return SQLITE_OK. If the mapping is not attempted
103406** (because the file is too large or the VFS layer is configured not to use
103407** mmap), return SQLITE_OK and set *pp to NULL.
103408**
103409** Or, if an error occurs, return an SQLite error code. The final value of
103410** *pp is undefined in this case.
103411*/
103412static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
103413  int rc = SQLITE_OK;
103414  if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
103415    sqlite3_file *pFd = pFile->pFd;
103416    if( pFd->pMethods->iVersion>=3 ){
103417      rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
103418      testcase( rc!=SQLITE_OK );
103419    }
103420  }
103421  return rc;
103422}
103423
103424/*
103425** Attach PmaReader pReadr to file pFile (if it is not already attached to
103426** that file) and seek it to offset iOff within the file.  Return SQLITE_OK
103427** if successful, or an SQLite error code if an error occurs.
103428*/
103429static int vdbePmaReaderSeek(
103430  SortSubtask *pTask,             /* Task context */
103431  PmaReader *pReadr,              /* Reader whose cursor is to be moved */
103432  SorterFile *pFile,              /* Sorter file to read from */
103433  i64 iOff                        /* Offset in pFile */
103434){
103435  int rc = SQLITE_OK;
103436
103437  assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
103438
103439  if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
103440  if( pReadr->aMap ){
103441    sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
103442    pReadr->aMap = 0;
103443  }
103444  pReadr->iReadOff = iOff;
103445  pReadr->iEof = pFile->iEof;
103446  pReadr->pFd = pFile->pFd;
103447
103448  rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
103449  if( rc==SQLITE_OK && pReadr->aMap==0 ){
103450    int pgsz = pTask->pSorter->pgsz;
103451    int iBuf = pReadr->iReadOff % pgsz;
103452    if( pReadr->aBuffer==0 ){
103453      pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
103454      if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
103455      pReadr->nBuffer = pgsz;
103456    }
103457    if( rc==SQLITE_OK && iBuf ){
103458      int nRead = pgsz - iBuf;
103459      if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
103460        nRead = (int)(pReadr->iEof - pReadr->iReadOff);
103461      }
103462      rc = sqlite3OsRead(
103463          pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
103464      );
103465      testcase( rc!=SQLITE_OK );
103466    }
103467  }
103468
103469  return rc;
103470}
103471
103472/*
103473** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
103474** no error occurs, or an SQLite error code if one does.
103475*/
103476static int vdbePmaReaderNext(PmaReader *pReadr){
103477  int rc = SQLITE_OK;             /* Return Code */
103478  u64 nRec = 0;                   /* Size of record in bytes */
103479
103480
103481  if( pReadr->iReadOff>=pReadr->iEof ){
103482    IncrMerger *pIncr = pReadr->pIncr;
103483    int bEof = 1;
103484    if( pIncr ){
103485      rc = vdbeIncrSwap(pIncr);
103486      if( rc==SQLITE_OK && pIncr->bEof==0 ){
103487        rc = vdbePmaReaderSeek(
103488            pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
103489        );
103490        bEof = 0;
103491      }
103492    }
103493
103494    if( bEof ){
103495      /* This is an EOF condition */
103496      vdbePmaReaderClear(pReadr);
103497      testcase( rc!=SQLITE_OK );
103498      return rc;
103499    }
103500  }
103501
103502  if( rc==SQLITE_OK ){
103503    rc = vdbePmaReadVarint(pReadr, &nRec);
103504  }
103505  if( rc==SQLITE_OK ){
103506    pReadr->nKey = (int)nRec;
103507    rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
103508    testcase( rc!=SQLITE_OK );
103509  }
103510
103511  return rc;
103512}
103513
103514/*
103515** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
103516** starting at offset iStart and ending at offset iEof-1. This function
103517** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
103518** PMA is empty).
103519**
103520** If the pnByte parameter is NULL, then it is assumed that the file
103521** contains a single PMA, and that that PMA omits the initial length varint.
103522*/
103523static int vdbePmaReaderInit(
103524  SortSubtask *pTask,             /* Task context */
103525  SorterFile *pFile,              /* Sorter file to read from */
103526  i64 iStart,                     /* Start offset in pFile */
103527  PmaReader *pReadr,              /* PmaReader to populate */
103528  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
103529){
103530  int rc;
103531
103532  assert( pFile->iEof>iStart );
103533  assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
103534  assert( pReadr->aBuffer==0 );
103535  assert( pReadr->aMap==0 );
103536
103537  rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
103538  if( rc==SQLITE_OK ){
103539    u64 nByte = 0;                 /* Size of PMA in bytes */
103540    rc = vdbePmaReadVarint(pReadr, &nByte);
103541    pReadr->iEof = pReadr->iReadOff + nByte;
103542    *pnByte += nByte;
103543  }
103544
103545  if( rc==SQLITE_OK ){
103546    rc = vdbePmaReaderNext(pReadr);
103547  }
103548  return rc;
103549}
103550
103551/*
103552** A version of vdbeSorterCompare() that assumes that it has already been
103553** determined that the first field of key1 is equal to the first field of
103554** key2.
103555*/
103556static int vdbeSorterCompareTail(
103557  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
103558  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
103559  const void *pKey1, int nKey1,   /* Left side of comparison */
103560  const void *pKey2, int nKey2    /* Right side of comparison */
103561){
103562  UnpackedRecord *r2 = pTask->pUnpacked;
103563  if( *pbKey2Cached==0 ){
103564    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
103565    *pbKey2Cached = 1;
103566  }
103567  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
103568}
103569
103570/*
103571** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
103572** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
103573** used by the comparison. Return the result of the comparison.
103574**
103575** If IN/OUT parameter *pbKey2Cached is true when this function is called,
103576** it is assumed that (pTask->pUnpacked) contains the unpacked version
103577** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
103578** version of key2 and *pbKey2Cached set to true before returning.
103579**
103580** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
103581** to SQLITE_NOMEM.
103582*/
103583static int vdbeSorterCompare(
103584  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
103585  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
103586  const void *pKey1, int nKey1,   /* Left side of comparison */
103587  const void *pKey2, int nKey2    /* Right side of comparison */
103588){
103589  UnpackedRecord *r2 = pTask->pUnpacked;
103590  if( !*pbKey2Cached ){
103591    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
103592    *pbKey2Cached = 1;
103593  }
103594  return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
103595}
103596
103597/*
103598** A specially optimized version of vdbeSorterCompare() that assumes that
103599** the first field of each key is a TEXT value and that the collation
103600** sequence to compare them with is BINARY.
103601*/
103602static int vdbeSorterCompareText(
103603  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
103604  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
103605  const void *pKey1, int nKey1,   /* Left side of comparison */
103606  const void *pKey2, int nKey2    /* Right side of comparison */
103607){
103608  const u8 * const p1 = (const u8 * const)pKey1;
103609  const u8 * const p2 = (const u8 * const)pKey2;
103610  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
103611  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
103612
103613  int n1;
103614  int n2;
103615  int res;
103616
103617  getVarint32NR(&p1[1], n1);
103618  getVarint32NR(&p2[1], n2);
103619  res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
103620  if( res==0 ){
103621    res = n1 - n2;
103622  }
103623
103624  if( res==0 ){
103625    if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
103626      res = vdbeSorterCompareTail(
103627          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
103628      );
103629    }
103630  }else{
103631    assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );
103632    if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){
103633      res = res * -1;
103634    }
103635  }
103636
103637  return res;
103638}
103639
103640/*
103641** A specially optimized version of vdbeSorterCompare() that assumes that
103642** the first field of each key is an INTEGER value.
103643*/
103644static int vdbeSorterCompareInt(
103645  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
103646  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
103647  const void *pKey1, int nKey1,   /* Left side of comparison */
103648  const void *pKey2, int nKey2    /* Right side of comparison */
103649){
103650  const u8 * const p1 = (const u8 * const)pKey1;
103651  const u8 * const p2 = (const u8 * const)pKey2;
103652  const int s1 = p1[1];                 /* Left hand serial type */
103653  const int s2 = p2[1];                 /* Right hand serial type */
103654  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
103655  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
103656  int res;                              /* Return value */
103657
103658  assert( (s1>0 && s1<7) || s1==8 || s1==9 );
103659  assert( (s2>0 && s2<7) || s2==8 || s2==9 );
103660
103661  if( s1==s2 ){
103662    /* The two values have the same sign. Compare using memcmp(). */
103663    static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
103664    const u8 n = aLen[s1];
103665    int i;
103666    res = 0;
103667    for(i=0; i<n; i++){
103668      if( (res = v1[i] - v2[i])!=0 ){
103669        if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
103670          res = v1[0] & 0x80 ? -1 : +1;
103671        }
103672        break;
103673      }
103674    }
103675  }else if( s1>7 && s2>7 ){
103676    res = s1 - s2;
103677  }else{
103678    if( s2>7 ){
103679      res = +1;
103680    }else if( s1>7 ){
103681      res = -1;
103682    }else{
103683      res = s1 - s2;
103684    }
103685    assert( res!=0 );
103686
103687    if( res>0 ){
103688      if( *v1 & 0x80 ) res = -1;
103689    }else{
103690      if( *v2 & 0x80 ) res = +1;
103691    }
103692  }
103693
103694  if( res==0 ){
103695    if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
103696      res = vdbeSorterCompareTail(
103697          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
103698      );
103699    }
103700  }else if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){
103701    assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );
103702    res = res * -1;
103703  }
103704
103705  return res;
103706}
103707
103708/*
103709** Initialize the temporary index cursor just opened as a sorter cursor.
103710**
103711** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
103712** to determine the number of fields that should be compared from the
103713** records being sorted. However, if the value passed as argument nField
103714** is non-zero and the sorter is able to guarantee a stable sort, nField
103715** is used instead. This is used when sorting records for a CREATE INDEX
103716** statement. In this case, keys are always delivered to the sorter in
103717** order of the primary key, which happens to be make up the final part
103718** of the records being sorted. So if the sort is stable, there is never
103719** any reason to compare PK fields and they can be ignored for a small
103720** performance boost.
103721**
103722** The sorter can guarantee a stable sort when running in single-threaded
103723** mode, but not in multi-threaded mode.
103724**
103725** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
103726*/
103727SQLITE_PRIVATE int sqlite3VdbeSorterInit(
103728  sqlite3 *db,                    /* Database connection (for malloc()) */
103729  int nField,                     /* Number of key fields in each record */
103730  VdbeCursor *pCsr                /* Cursor that holds the new sorter */
103731){
103732  int pgsz;                       /* Page size of main database */
103733  int i;                          /* Used to iterate through aTask[] */
103734  VdbeSorter *pSorter;            /* The new sorter */
103735  KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
103736  int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
103737  int sz;                         /* Size of pSorter in bytes */
103738  int rc = SQLITE_OK;
103739#if SQLITE_MAX_WORKER_THREADS==0
103740# define nWorker 0
103741#else
103742  int nWorker;
103743#endif
103744
103745  /* Initialize the upper limit on the number of worker threads */
103746#if SQLITE_MAX_WORKER_THREADS>0
103747  if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
103748    nWorker = 0;
103749  }else{
103750    nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
103751  }
103752#endif
103753
103754  /* Do not allow the total number of threads (main thread + all workers)
103755  ** to exceed the maximum merge count */
103756#if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
103757  if( nWorker>=SORTER_MAX_MERGE_COUNT ){
103758    nWorker = SORTER_MAX_MERGE_COUNT-1;
103759  }
103760#endif
103761
103762  assert( pCsr->pKeyInfo );
103763  assert( !pCsr->isEphemeral );
103764  assert( pCsr->eCurType==CURTYPE_SORTER );
103765  szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
103766  sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
103767
103768  pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
103769  pCsr->uc.pSorter = pSorter;
103770  if( pSorter==0 ){
103771    rc = SQLITE_NOMEM_BKPT;
103772  }else{
103773    Btree *pBt = db->aDb[0].pBt;
103774    pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
103775    memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
103776    pKeyInfo->db = 0;
103777    if( nField && nWorker==0 ){
103778      pKeyInfo->nKeyField = nField;
103779    }
103780    sqlite3BtreeEnter(pBt);
103781    pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(pBt);
103782    sqlite3BtreeLeave(pBt);
103783    pSorter->nTask = nWorker + 1;
103784    pSorter->iPrev = (u8)(nWorker - 1);
103785    pSorter->bUseThreads = (pSorter->nTask>1);
103786    pSorter->db = db;
103787    for(i=0; i<pSorter->nTask; i++){
103788      SortSubtask *pTask = &pSorter->aTask[i];
103789      pTask->pSorter = pSorter;
103790    }
103791
103792    if( !sqlite3TempInMemory(db) ){
103793      i64 mxCache;                /* Cache size in bytes*/
103794      u32 szPma = sqlite3GlobalConfig.szPma;
103795      pSorter->mnPmaSize = szPma * pgsz;
103796
103797      mxCache = db->aDb[0].pSchema->cache_size;
103798      if( mxCache<0 ){
103799        /* A negative cache-size value C indicates that the cache is abs(C)
103800        ** KiB in size.  */
103801        mxCache = mxCache * -1024;
103802      }else{
103803        mxCache = mxCache * pgsz;
103804      }
103805      mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
103806      pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
103807
103808      /* Avoid large memory allocations if the application has requested
103809      ** SQLITE_CONFIG_SMALL_MALLOC. */
103810      if( sqlite3GlobalConfig.bSmallMalloc==0 ){
103811        assert( pSorter->iMemory==0 );
103812        pSorter->nMemory = pgsz;
103813        pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
103814        if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
103815      }
103816    }
103817
103818    if( pKeyInfo->nAllField<13
103819     && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
103820     && (pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL)==0
103821    ){
103822      pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
103823    }
103824  }
103825
103826  return rc;
103827}
103828#undef nWorker   /* Defined at the top of this function */
103829
103830/*
103831** Free the list of sorted records starting at pRecord.
103832*/
103833static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
103834  SorterRecord *p;
103835  SorterRecord *pNext;
103836  for(p=pRecord; p; p=pNext){
103837    pNext = p->u.pNext;
103838    sqlite3DbFree(db, p);
103839  }
103840}
103841
103842/*
103843** Free all resources owned by the object indicated by argument pTask. All
103844** fields of *pTask are zeroed before returning.
103845*/
103846static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
103847  sqlite3DbFree(db, pTask->pUnpacked);
103848#if SQLITE_MAX_WORKER_THREADS>0
103849  /* pTask->list.aMemory can only be non-zero if it was handed memory
103850  ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
103851  if( pTask->list.aMemory ){
103852    sqlite3_free(pTask->list.aMemory);
103853  }else
103854#endif
103855  {
103856    assert( pTask->list.aMemory==0 );
103857    vdbeSorterRecordFree(0, pTask->list.pList);
103858  }
103859  if( pTask->file.pFd ){
103860    sqlite3OsCloseFree(pTask->file.pFd);
103861  }
103862  if( pTask->file2.pFd ){
103863    sqlite3OsCloseFree(pTask->file2.pFd);
103864  }
103865  memset(pTask, 0, sizeof(SortSubtask));
103866}
103867
103868#ifdef SQLITE_DEBUG_SORTER_THREADS
103869static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
103870  i64 t;
103871  int iTask = (pTask - pTask->pSorter->aTask);
103872  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
103873  fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
103874}
103875static void vdbeSorterRewindDebug(const char *zEvent){
103876  i64 t = 0;
103877  sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
103878  if( ALWAYS(pVfs) ) sqlite3OsCurrentTimeInt64(pVfs, &t);
103879  fprintf(stderr, "%lld:X %s\n", t, zEvent);
103880}
103881static void vdbeSorterPopulateDebug(
103882  SortSubtask *pTask,
103883  const char *zEvent
103884){
103885  i64 t;
103886  int iTask = (pTask - pTask->pSorter->aTask);
103887  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
103888  fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
103889}
103890static void vdbeSorterBlockDebug(
103891  SortSubtask *pTask,
103892  int bBlocked,
103893  const char *zEvent
103894){
103895  if( bBlocked ){
103896    i64 t;
103897    sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
103898    fprintf(stderr, "%lld:main %s\n", t, zEvent);
103899  }
103900}
103901#else
103902# define vdbeSorterWorkDebug(x,y)
103903# define vdbeSorterRewindDebug(y)
103904# define vdbeSorterPopulateDebug(x,y)
103905# define vdbeSorterBlockDebug(x,y,z)
103906#endif
103907
103908#if SQLITE_MAX_WORKER_THREADS>0
103909/*
103910** Join thread pTask->thread.
103911*/
103912static int vdbeSorterJoinThread(SortSubtask *pTask){
103913  int rc = SQLITE_OK;
103914  if( pTask->pThread ){
103915#ifdef SQLITE_DEBUG_SORTER_THREADS
103916    int bDone = pTask->bDone;
103917#endif
103918    void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
103919    vdbeSorterBlockDebug(pTask, !bDone, "enter");
103920    (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
103921    vdbeSorterBlockDebug(pTask, !bDone, "exit");
103922    rc = SQLITE_PTR_TO_INT(pRet);
103923    assert( pTask->bDone==1 );
103924    pTask->bDone = 0;
103925    pTask->pThread = 0;
103926  }
103927  return rc;
103928}
103929
103930/*
103931** Launch a background thread to run xTask(pIn).
103932*/
103933static int vdbeSorterCreateThread(
103934  SortSubtask *pTask,             /* Thread will use this task object */
103935  void *(*xTask)(void*),          /* Routine to run in a separate thread */
103936  void *pIn                       /* Argument passed into xTask() */
103937){
103938  assert( pTask->pThread==0 && pTask->bDone==0 );
103939  return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
103940}
103941
103942/*
103943** Join all outstanding threads launched by SorterWrite() to create
103944** level-0 PMAs.
103945*/
103946static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
103947  int rc = rcin;
103948  int i;
103949
103950  /* This function is always called by the main user thread.
103951  **
103952  ** If this function is being called after SorterRewind() has been called,
103953  ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
103954  ** is currently attempt to join one of the other threads. To avoid a race
103955  ** condition where this thread also attempts to join the same object, join
103956  ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
103957  for(i=pSorter->nTask-1; i>=0; i--){
103958    SortSubtask *pTask = &pSorter->aTask[i];
103959    int rc2 = vdbeSorterJoinThread(pTask);
103960    if( rc==SQLITE_OK ) rc = rc2;
103961  }
103962  return rc;
103963}
103964#else
103965# define vdbeSorterJoinAll(x,rcin) (rcin)
103966# define vdbeSorterJoinThread(pTask) SQLITE_OK
103967#endif
103968
103969/*
103970** Allocate a new MergeEngine object capable of handling up to
103971** nReader PmaReader inputs.
103972**
103973** nReader is automatically rounded up to the next power of two.
103974** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
103975*/
103976static MergeEngine *vdbeMergeEngineNew(int nReader){
103977  int N = 2;                      /* Smallest power of two >= nReader */
103978  int nByte;                      /* Total bytes of space to allocate */
103979  MergeEngine *pNew;              /* Pointer to allocated object to return */
103980
103981  assert( nReader<=SORTER_MAX_MERGE_COUNT );
103982
103983  while( N<nReader ) N += N;
103984  nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
103985
103986  pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
103987  if( pNew ){
103988    pNew->nTree = N;
103989    pNew->pTask = 0;
103990    pNew->aReadr = (PmaReader*)&pNew[1];
103991    pNew->aTree = (int*)&pNew->aReadr[N];
103992  }
103993  return pNew;
103994}
103995
103996/*
103997** Free the MergeEngine object passed as the only argument.
103998*/
103999static void vdbeMergeEngineFree(MergeEngine *pMerger){
104000  int i;
104001  if( pMerger ){
104002    for(i=0; i<pMerger->nTree; i++){
104003      vdbePmaReaderClear(&pMerger->aReadr[i]);
104004    }
104005  }
104006  sqlite3_free(pMerger);
104007}
104008
104009/*
104010** Free all resources associated with the IncrMerger object indicated by
104011** the first argument.
104012*/
104013static void vdbeIncrFree(IncrMerger *pIncr){
104014  if( pIncr ){
104015#if SQLITE_MAX_WORKER_THREADS>0
104016    if( pIncr->bUseThread ){
104017      vdbeSorterJoinThread(pIncr->pTask);
104018      if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
104019      if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
104020    }
104021#endif
104022    vdbeMergeEngineFree(pIncr->pMerger);
104023    sqlite3_free(pIncr);
104024  }
104025}
104026
104027/*
104028** Reset a sorting cursor back to its original empty state.
104029*/
104030SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
104031  int i;
104032  (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
104033  assert( pSorter->bUseThreads || pSorter->pReader==0 );
104034#if SQLITE_MAX_WORKER_THREADS>0
104035  if( pSorter->pReader ){
104036    vdbePmaReaderClear(pSorter->pReader);
104037    sqlite3DbFree(db, pSorter->pReader);
104038    pSorter->pReader = 0;
104039  }
104040#endif
104041  vdbeMergeEngineFree(pSorter->pMerger);
104042  pSorter->pMerger = 0;
104043  for(i=0; i<pSorter->nTask; i++){
104044    SortSubtask *pTask = &pSorter->aTask[i];
104045    vdbeSortSubtaskCleanup(db, pTask);
104046    pTask->pSorter = pSorter;
104047  }
104048  if( pSorter->list.aMemory==0 ){
104049    vdbeSorterRecordFree(0, pSorter->list.pList);
104050  }
104051  pSorter->list.pList = 0;
104052  pSorter->list.szPMA = 0;
104053  pSorter->bUsePMA = 0;
104054  pSorter->iMemory = 0;
104055  pSorter->mxKeysize = 0;
104056  sqlite3DbFree(db, pSorter->pUnpacked);
104057  pSorter->pUnpacked = 0;
104058}
104059
104060/*
104061** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
104062*/
104063SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
104064  VdbeSorter *pSorter;
104065  assert( pCsr->eCurType==CURTYPE_SORTER );
104066  pSorter = pCsr->uc.pSorter;
104067  if( pSorter ){
104068    sqlite3VdbeSorterReset(db, pSorter);
104069    sqlite3_free(pSorter->list.aMemory);
104070    sqlite3DbFree(db, pSorter);
104071    pCsr->uc.pSorter = 0;
104072  }
104073}
104074
104075#if SQLITE_MAX_MMAP_SIZE>0
104076/*
104077** The first argument is a file-handle open on a temporary file. The file
104078** is guaranteed to be nByte bytes or smaller in size. This function
104079** attempts to extend the file to nByte bytes in size and to ensure that
104080** the VFS has memory mapped it.
104081**
104082** Whether or not the file does end up memory mapped of course depends on
104083** the specific VFS implementation.
104084*/
104085static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
104086  if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
104087    void *p = 0;
104088    int chunksize = 4*1024;
104089    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
104090    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
104091    sqlite3OsFetch(pFd, 0, (int)nByte, &p);
104092    if( p ) sqlite3OsUnfetch(pFd, 0, p);
104093  }
104094}
104095#else
104096# define vdbeSorterExtendFile(x,y,z)
104097#endif
104098
104099/*
104100** Allocate space for a file-handle and open a temporary file. If successful,
104101** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
104102** Otherwise, set *ppFd to 0 and return an SQLite error code.
104103*/
104104static int vdbeSorterOpenTempFile(
104105  sqlite3 *db,                    /* Database handle doing sort */
104106  i64 nExtend,                    /* Attempt to extend file to this size */
104107  sqlite3_file **ppFd
104108){
104109  int rc;
104110  if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
104111  rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
104112      SQLITE_OPEN_TEMP_JOURNAL |
104113      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
104114      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
104115  );
104116  if( rc==SQLITE_OK ){
104117    i64 max = SQLITE_MAX_MMAP_SIZE;
104118    sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
104119    if( nExtend>0 ){
104120      vdbeSorterExtendFile(db, *ppFd, nExtend);
104121    }
104122  }
104123  return rc;
104124}
104125
104126/*
104127** If it has not already been allocated, allocate the UnpackedRecord
104128** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
104129** if no allocation was required), or SQLITE_NOMEM otherwise.
104130*/
104131static int vdbeSortAllocUnpacked(SortSubtask *pTask){
104132  if( pTask->pUnpacked==0 ){
104133    pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
104134    if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
104135    pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
104136    pTask->pUnpacked->errCode = 0;
104137  }
104138  return SQLITE_OK;
104139}
104140
104141
104142/*
104143** Merge the two sorted lists p1 and p2 into a single list.
104144*/
104145static SorterRecord *vdbeSorterMerge(
104146  SortSubtask *pTask,             /* Calling thread context */
104147  SorterRecord *p1,               /* First list to merge */
104148  SorterRecord *p2                /* Second list to merge */
104149){
104150  SorterRecord *pFinal = 0;
104151  SorterRecord **pp = &pFinal;
104152  int bCached = 0;
104153
104154  assert( p1!=0 && p2!=0 );
104155  for(;;){
104156    int res;
104157    res = pTask->xCompare(
104158        pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
104159    );
104160
104161    if( res<=0 ){
104162      *pp = p1;
104163      pp = &p1->u.pNext;
104164      p1 = p1->u.pNext;
104165      if( p1==0 ){
104166        *pp = p2;
104167        break;
104168      }
104169    }else{
104170      *pp = p2;
104171      pp = &p2->u.pNext;
104172      p2 = p2->u.pNext;
104173      bCached = 0;
104174      if( p2==0 ){
104175        *pp = p1;
104176        break;
104177      }
104178    }
104179  }
104180  return pFinal;
104181}
104182
104183/*
104184** Return the SorterCompare function to compare values collected by the
104185** sorter object passed as the only argument.
104186*/
104187static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
104188  if( p->typeMask==SORTER_TYPE_INTEGER ){
104189    return vdbeSorterCompareInt;
104190  }else if( p->typeMask==SORTER_TYPE_TEXT ){
104191    return vdbeSorterCompareText;
104192  }
104193  return vdbeSorterCompare;
104194}
104195
104196/*
104197** Sort the linked list of records headed at pTask->pList. Return
104198** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
104199** an error occurs.
104200*/
104201static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
104202  int i;
104203  SorterRecord *p;
104204  int rc;
104205  SorterRecord *aSlot[64];
104206
104207  rc = vdbeSortAllocUnpacked(pTask);
104208  if( rc!=SQLITE_OK ) return rc;
104209
104210  p = pList->pList;
104211  pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
104212  memset(aSlot, 0, sizeof(aSlot));
104213
104214  while( p ){
104215    SorterRecord *pNext;
104216    if( pList->aMemory ){
104217      if( (u8*)p==pList->aMemory ){
104218        pNext = 0;
104219      }else{
104220        assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
104221        pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
104222      }
104223    }else{
104224      pNext = p->u.pNext;
104225    }
104226
104227    p->u.pNext = 0;
104228    for(i=0; aSlot[i]; i++){
104229      p = vdbeSorterMerge(pTask, p, aSlot[i]);
104230      aSlot[i] = 0;
104231    }
104232    aSlot[i] = p;
104233    p = pNext;
104234  }
104235
104236  p = 0;
104237  for(i=0; i<ArraySize(aSlot); i++){
104238    if( aSlot[i]==0 ) continue;
104239    p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
104240  }
104241  pList->pList = p;
104242
104243  assert( pTask->pUnpacked->errCode==SQLITE_OK
104244       || pTask->pUnpacked->errCode==SQLITE_NOMEM
104245  );
104246  return pTask->pUnpacked->errCode;
104247}
104248
104249/*
104250** Initialize a PMA-writer object.
104251*/
104252static void vdbePmaWriterInit(
104253  sqlite3_file *pFd,              /* File handle to write to */
104254  PmaWriter *p,                   /* Object to populate */
104255  int nBuf,                       /* Buffer size */
104256  i64 iStart                      /* Offset of pFd to begin writing at */
104257){
104258  memset(p, 0, sizeof(PmaWriter));
104259  p->aBuffer = (u8*)sqlite3Malloc(nBuf);
104260  if( !p->aBuffer ){
104261    p->eFWErr = SQLITE_NOMEM_BKPT;
104262  }else{
104263    p->iBufEnd = p->iBufStart = (iStart % nBuf);
104264    p->iWriteOff = iStart - p->iBufStart;
104265    p->nBuffer = nBuf;
104266    p->pFd = pFd;
104267  }
104268}
104269
104270/*
104271** Write nData bytes of data to the PMA. Return SQLITE_OK
104272** if successful, or an SQLite error code if an error occurs.
104273*/
104274static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
104275  int nRem = nData;
104276  while( nRem>0 && p->eFWErr==0 ){
104277    int nCopy = nRem;
104278    if( nCopy>(p->nBuffer - p->iBufEnd) ){
104279      nCopy = p->nBuffer - p->iBufEnd;
104280    }
104281
104282    memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
104283    p->iBufEnd += nCopy;
104284    if( p->iBufEnd==p->nBuffer ){
104285      p->eFWErr = sqlite3OsWrite(p->pFd,
104286          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
104287          p->iWriteOff + p->iBufStart
104288      );
104289      p->iBufStart = p->iBufEnd = 0;
104290      p->iWriteOff += p->nBuffer;
104291    }
104292    assert( p->iBufEnd<p->nBuffer );
104293
104294    nRem -= nCopy;
104295  }
104296}
104297
104298/*
104299** Flush any buffered data to disk and clean up the PMA-writer object.
104300** The results of using the PMA-writer after this call are undefined.
104301** Return SQLITE_OK if flushing the buffered data succeeds or is not
104302** required. Otherwise, return an SQLite error code.
104303**
104304** Before returning, set *piEof to the offset immediately following the
104305** last byte written to the file.
104306*/
104307static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
104308  int rc;
104309  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
104310    p->eFWErr = sqlite3OsWrite(p->pFd,
104311        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
104312        p->iWriteOff + p->iBufStart
104313    );
104314  }
104315  *piEof = (p->iWriteOff + p->iBufEnd);
104316  sqlite3_free(p->aBuffer);
104317  rc = p->eFWErr;
104318  memset(p, 0, sizeof(PmaWriter));
104319  return rc;
104320}
104321
104322/*
104323** Write value iVal encoded as a varint to the PMA. Return
104324** SQLITE_OK if successful, or an SQLite error code if an error occurs.
104325*/
104326static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
104327  int nByte;
104328  u8 aByte[10];
104329  nByte = sqlite3PutVarint(aByte, iVal);
104330  vdbePmaWriteBlob(p, aByte, nByte);
104331}
104332
104333/*
104334** Write the current contents of in-memory linked-list pList to a level-0
104335** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
104336** successful, or an SQLite error code otherwise.
104337**
104338** The format of a PMA is:
104339**
104340**     * A varint. This varint contains the total number of bytes of content
104341**       in the PMA (not including the varint itself).
104342**
104343**     * One or more records packed end-to-end in order of ascending keys.
104344**       Each record consists of a varint followed by a blob of data (the
104345**       key). The varint is the number of bytes in the blob of data.
104346*/
104347static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
104348  sqlite3 *db = pTask->pSorter->db;
104349  int rc = SQLITE_OK;             /* Return code */
104350  PmaWriter writer;               /* Object used to write to the file */
104351
104352#ifdef SQLITE_DEBUG
104353  /* Set iSz to the expected size of file pTask->file after writing the PMA.
104354  ** This is used by an assert() statement at the end of this function.  */
104355  i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
104356#endif
104357
104358  vdbeSorterWorkDebug(pTask, "enter");
104359  memset(&writer, 0, sizeof(PmaWriter));
104360  assert( pList->szPMA>0 );
104361
104362  /* If the first temporary PMA file has not been opened, open it now. */
104363  if( pTask->file.pFd==0 ){
104364    rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
104365    assert( rc!=SQLITE_OK || pTask->file.pFd );
104366    assert( pTask->file.iEof==0 );
104367    assert( pTask->nPMA==0 );
104368  }
104369
104370  /* Try to get the file to memory map */
104371  if( rc==SQLITE_OK ){
104372    vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
104373  }
104374
104375  /* Sort the list */
104376  if( rc==SQLITE_OK ){
104377    rc = vdbeSorterSort(pTask, pList);
104378  }
104379
104380  if( rc==SQLITE_OK ){
104381    SorterRecord *p;
104382    SorterRecord *pNext = 0;
104383
104384    vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
104385                      pTask->file.iEof);
104386    pTask->nPMA++;
104387    vdbePmaWriteVarint(&writer, pList->szPMA);
104388    for(p=pList->pList; p; p=pNext){
104389      pNext = p->u.pNext;
104390      vdbePmaWriteVarint(&writer, p->nVal);
104391      vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
104392      if( pList->aMemory==0 ) sqlite3_free(p);
104393    }
104394    pList->pList = p;
104395    rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
104396  }
104397
104398  vdbeSorterWorkDebug(pTask, "exit");
104399  assert( rc!=SQLITE_OK || pList->pList==0 );
104400  assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
104401  return rc;
104402}
104403
104404/*
104405** Advance the MergeEngine to its next entry.
104406** Set *pbEof to true there is no next entry because
104407** the MergeEngine has reached the end of all its inputs.
104408**
104409** Return SQLITE_OK if successful or an error code if an error occurs.
104410*/
104411static int vdbeMergeEngineStep(
104412  MergeEngine *pMerger,      /* The merge engine to advance to the next row */
104413  int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
104414){
104415  int rc;
104416  int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
104417  SortSubtask *pTask = pMerger->pTask;
104418
104419  /* Advance the current PmaReader */
104420  rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
104421
104422  /* Update contents of aTree[] */
104423  if( rc==SQLITE_OK ){
104424    int i;                      /* Index of aTree[] to recalculate */
104425    PmaReader *pReadr1;         /* First PmaReader to compare */
104426    PmaReader *pReadr2;         /* Second PmaReader to compare */
104427    int bCached = 0;
104428
104429    /* Find the first two PmaReaders to compare. The one that was just
104430    ** advanced (iPrev) and the one next to it in the array.  */
104431    pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
104432    pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
104433
104434    for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
104435      /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
104436      int iRes;
104437      if( pReadr1->pFd==0 ){
104438        iRes = +1;
104439      }else if( pReadr2->pFd==0 ){
104440        iRes = -1;
104441      }else{
104442        iRes = pTask->xCompare(pTask, &bCached,
104443            pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
104444        );
104445      }
104446
104447      /* If pReadr1 contained the smaller value, set aTree[i] to its index.
104448      ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
104449      ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
104450      ** pKey2 to point to the record belonging to pReadr2.
104451      **
104452      ** Alternatively, if pReadr2 contains the smaller of the two values,
104453      ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
104454      ** was actually called above, then pTask->pUnpacked now contains
104455      ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
104456      ** vdbeSorterCompare() from decoding pReadr2 again.
104457      **
104458      ** If the two values were equal, then the value from the oldest
104459      ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
104460      ** is sorted from oldest to newest, so pReadr1 contains older values
104461      ** than pReadr2 iff (pReadr1<pReadr2).  */
104462      if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
104463        pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
104464        pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
104465        bCached = 0;
104466      }else{
104467        if( pReadr1->pFd ) bCached = 0;
104468        pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
104469        pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
104470      }
104471    }
104472    *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
104473  }
104474
104475  return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
104476}
104477
104478#if SQLITE_MAX_WORKER_THREADS>0
104479/*
104480** The main routine for background threads that write level-0 PMAs.
104481*/
104482static void *vdbeSorterFlushThread(void *pCtx){
104483  SortSubtask *pTask = (SortSubtask*)pCtx;
104484  int rc;                         /* Return code */
104485  assert( pTask->bDone==0 );
104486  rc = vdbeSorterListToPMA(pTask, &pTask->list);
104487  pTask->bDone = 1;
104488  return SQLITE_INT_TO_PTR(rc);
104489}
104490#endif /* SQLITE_MAX_WORKER_THREADS>0 */
104491
104492/*
104493** Flush the current contents of VdbeSorter.list to a new PMA, possibly
104494** using a background thread.
104495*/
104496static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
104497#if SQLITE_MAX_WORKER_THREADS==0
104498  pSorter->bUsePMA = 1;
104499  return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
104500#else
104501  int rc = SQLITE_OK;
104502  int i;
104503  SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
104504  int nWorker = (pSorter->nTask-1);
104505
104506  /* Set the flag to indicate that at least one PMA has been written.
104507  ** Or will be, anyhow.  */
104508  pSorter->bUsePMA = 1;
104509
104510  /* Select a sub-task to sort and flush the current list of in-memory
104511  ** records to disk. If the sorter is running in multi-threaded mode,
104512  ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
104513  ** the background thread from a sub-tasks previous turn is still running,
104514  ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
104515  ** fall back to using the final sub-task. The first (pSorter->nTask-1)
104516  ** sub-tasks are preferred as they use background threads - the final
104517  ** sub-task uses the main thread. */
104518  for(i=0; i<nWorker; i++){
104519    int iTest = (pSorter->iPrev + i + 1) % nWorker;
104520    pTask = &pSorter->aTask[iTest];
104521    if( pTask->bDone ){
104522      rc = vdbeSorterJoinThread(pTask);
104523    }
104524    if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
104525  }
104526
104527  if( rc==SQLITE_OK ){
104528    if( i==nWorker ){
104529      /* Use the foreground thread for this operation */
104530      rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
104531    }else{
104532      /* Launch a background thread for this operation */
104533      u8 *aMem;
104534      void *pCtx;
104535
104536      assert( pTask!=0 );
104537      assert( pTask->pThread==0 && pTask->bDone==0 );
104538      assert( pTask->list.pList==0 );
104539      assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
104540
104541      aMem = pTask->list.aMemory;
104542      pCtx = (void*)pTask;
104543      pSorter->iPrev = (u8)(pTask - pSorter->aTask);
104544      pTask->list = pSorter->list;
104545      pSorter->list.pList = 0;
104546      pSorter->list.szPMA = 0;
104547      if( aMem ){
104548        pSorter->list.aMemory = aMem;
104549        pSorter->nMemory = sqlite3MallocSize(aMem);
104550      }else if( pSorter->list.aMemory ){
104551        pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
104552        if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
104553      }
104554
104555      rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
104556    }
104557  }
104558
104559  return rc;
104560#endif /* SQLITE_MAX_WORKER_THREADS!=0 */
104561}
104562
104563/*
104564** Add a record to the sorter.
104565*/
104566SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
104567  const VdbeCursor *pCsr,         /* Sorter cursor */
104568  Mem *pVal                       /* Memory cell containing record */
104569){
104570  VdbeSorter *pSorter;
104571  int rc = SQLITE_OK;             /* Return Code */
104572  SorterRecord *pNew;             /* New list element */
104573  int bFlush;                     /* True to flush contents of memory to PMA */
104574  i64 nReq;                       /* Bytes of memory required */
104575  i64 nPMA;                       /* Bytes of PMA space required */
104576  int t;                          /* serial type of first record field */
104577
104578  assert( pCsr->eCurType==CURTYPE_SORTER );
104579  pSorter = pCsr->uc.pSorter;
104580  getVarint32NR((const u8*)&pVal->z[1], t);
104581  if( t>0 && t<10 && t!=7 ){
104582    pSorter->typeMask &= SORTER_TYPE_INTEGER;
104583  }else if( t>10 && (t & 0x01) ){
104584    pSorter->typeMask &= SORTER_TYPE_TEXT;
104585  }else{
104586    pSorter->typeMask = 0;
104587  }
104588
104589  assert( pSorter );
104590
104591  /* Figure out whether or not the current contents of memory should be
104592  ** flushed to a PMA before continuing. If so, do so.
104593  **
104594  ** If using the single large allocation mode (pSorter->aMemory!=0), then
104595  ** flush the contents of memory to a new PMA if (a) at least one value is
104596  ** already in memory and (b) the new value will not fit in memory.
104597  **
104598  ** Or, if using separate allocations for each record, flush the contents
104599  ** of memory to a PMA if either of the following are true:
104600  **
104601  **   * The total memory allocated for the in-memory list is greater
104602  **     than (page-size * cache-size), or
104603  **
104604  **   * The total memory allocated for the in-memory list is greater
104605  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
104606  */
104607  nReq = pVal->n + sizeof(SorterRecord);
104608  nPMA = pVal->n + sqlite3VarintLen(pVal->n);
104609  if( pSorter->mxPmaSize ){
104610    if( pSorter->list.aMemory ){
104611      bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
104612    }else{
104613      bFlush = (
104614          (pSorter->list.szPMA > pSorter->mxPmaSize)
104615       || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
104616      );
104617    }
104618    if( bFlush ){
104619      rc = vdbeSorterFlushPMA(pSorter);
104620      pSorter->list.szPMA = 0;
104621      pSorter->iMemory = 0;
104622      assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
104623    }
104624  }
104625
104626  pSorter->list.szPMA += nPMA;
104627  if( nPMA>pSorter->mxKeysize ){
104628    pSorter->mxKeysize = nPMA;
104629  }
104630
104631  if( pSorter->list.aMemory ){
104632    int nMin = pSorter->iMemory + nReq;
104633
104634    if( nMin>pSorter->nMemory ){
104635      u8 *aNew;
104636      sqlite3_int64 nNew = 2 * (sqlite3_int64)pSorter->nMemory;
104637      int iListOff = -1;
104638      if( pSorter->list.pList ){
104639        iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
104640      }
104641      while( nNew < nMin ) nNew = nNew*2;
104642      if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
104643      if( nNew < nMin ) nNew = nMin;
104644      aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
104645      if( !aNew ) return SQLITE_NOMEM_BKPT;
104646      if( iListOff>=0 ){
104647        pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
104648      }
104649      pSorter->list.aMemory = aNew;
104650      pSorter->nMemory = nNew;
104651    }
104652
104653    pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
104654    pSorter->iMemory += ROUND8(nReq);
104655    if( pSorter->list.pList ){
104656      pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
104657    }
104658  }else{
104659    pNew = (SorterRecord *)sqlite3Malloc(nReq);
104660    if( pNew==0 ){
104661      return SQLITE_NOMEM_BKPT;
104662    }
104663    pNew->u.pNext = pSorter->list.pList;
104664  }
104665
104666  memcpy(SRVAL(pNew), pVal->z, pVal->n);
104667  pNew->nVal = pVal->n;
104668  pSorter->list.pList = pNew;
104669
104670  return rc;
104671}
104672
104673/*
104674** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
104675** of the data stored in aFile[1] is the same as that used by regular PMAs,
104676** except that the number-of-bytes varint is omitted from the start.
104677*/
104678static int vdbeIncrPopulate(IncrMerger *pIncr){
104679  int rc = SQLITE_OK;
104680  int rc2;
104681  i64 iStart = pIncr->iStartOff;
104682  SorterFile *pOut = &pIncr->aFile[1];
104683  SortSubtask *pTask = pIncr->pTask;
104684  MergeEngine *pMerger = pIncr->pMerger;
104685  PmaWriter writer;
104686  assert( pIncr->bEof==0 );
104687
104688  vdbeSorterPopulateDebug(pTask, "enter");
104689
104690  vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
104691  while( rc==SQLITE_OK ){
104692    int dummy;
104693    PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
104694    int nKey = pReader->nKey;
104695    i64 iEof = writer.iWriteOff + writer.iBufEnd;
104696
104697    /* Check if the output file is full or if the input has been exhausted.
104698    ** In either case exit the loop. */
104699    if( pReader->pFd==0 ) break;
104700    if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
104701
104702    /* Write the next key to the output. */
104703    vdbePmaWriteVarint(&writer, nKey);
104704    vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
104705    assert( pIncr->pMerger->pTask==pTask );
104706    rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
104707  }
104708
104709  rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
104710  if( rc==SQLITE_OK ) rc = rc2;
104711  vdbeSorterPopulateDebug(pTask, "exit");
104712  return rc;
104713}
104714
104715#if SQLITE_MAX_WORKER_THREADS>0
104716/*
104717** The main routine for background threads that populate aFile[1] of
104718** multi-threaded IncrMerger objects.
104719*/
104720static void *vdbeIncrPopulateThread(void *pCtx){
104721  IncrMerger *pIncr = (IncrMerger*)pCtx;
104722  void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
104723  pIncr->pTask->bDone = 1;
104724  return pRet;
104725}
104726
104727/*
104728** Launch a background thread to populate aFile[1] of pIncr.
104729*/
104730static int vdbeIncrBgPopulate(IncrMerger *pIncr){
104731  void *p = (void*)pIncr;
104732  assert( pIncr->bUseThread );
104733  return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
104734}
104735#endif
104736
104737/*
104738** This function is called when the PmaReader corresponding to pIncr has
104739** finished reading the contents of aFile[0]. Its purpose is to "refill"
104740** aFile[0] such that the PmaReader should start rereading it from the
104741** beginning.
104742**
104743** For single-threaded objects, this is accomplished by literally reading
104744** keys from pIncr->pMerger and repopulating aFile[0].
104745**
104746** For multi-threaded objects, all that is required is to wait until the
104747** background thread is finished (if it is not already) and then swap
104748** aFile[0] and aFile[1] in place. If the contents of pMerger have not
104749** been exhausted, this function also launches a new background thread
104750** to populate the new aFile[1].
104751**
104752** SQLITE_OK is returned on success, or an SQLite error code otherwise.
104753*/
104754static int vdbeIncrSwap(IncrMerger *pIncr){
104755  int rc = SQLITE_OK;
104756
104757#if SQLITE_MAX_WORKER_THREADS>0
104758  if( pIncr->bUseThread ){
104759    rc = vdbeSorterJoinThread(pIncr->pTask);
104760
104761    if( rc==SQLITE_OK ){
104762      SorterFile f0 = pIncr->aFile[0];
104763      pIncr->aFile[0] = pIncr->aFile[1];
104764      pIncr->aFile[1] = f0;
104765    }
104766
104767    if( rc==SQLITE_OK ){
104768      if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
104769        pIncr->bEof = 1;
104770      }else{
104771        rc = vdbeIncrBgPopulate(pIncr);
104772      }
104773    }
104774  }else
104775#endif
104776  {
104777    rc = vdbeIncrPopulate(pIncr);
104778    pIncr->aFile[0] = pIncr->aFile[1];
104779    if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
104780      pIncr->bEof = 1;
104781    }
104782  }
104783
104784  return rc;
104785}
104786
104787/*
104788** Allocate and return a new IncrMerger object to read data from pMerger.
104789**
104790** If an OOM condition is encountered, return NULL. In this case free the
104791** pMerger argument before returning.
104792*/
104793static int vdbeIncrMergerNew(
104794  SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
104795  MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
104796  IncrMerger **ppOut      /* Write the new IncrMerger here */
104797){
104798  int rc = SQLITE_OK;
104799  IncrMerger *pIncr = *ppOut = (IncrMerger*)
104800       (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
104801  if( pIncr ){
104802    pIncr->pMerger = pMerger;
104803    pIncr->pTask = pTask;
104804    pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
104805    pTask->file2.iEof += pIncr->mxSz;
104806  }else{
104807    vdbeMergeEngineFree(pMerger);
104808    rc = SQLITE_NOMEM_BKPT;
104809  }
104810  assert( *ppOut!=0 || rc!=SQLITE_OK );
104811  return rc;
104812}
104813
104814#if SQLITE_MAX_WORKER_THREADS>0
104815/*
104816** Set the "use-threads" flag on object pIncr.
104817*/
104818static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
104819  pIncr->bUseThread = 1;
104820  pIncr->pTask->file2.iEof -= pIncr->mxSz;
104821}
104822#endif /* SQLITE_MAX_WORKER_THREADS>0 */
104823
104824
104825
104826/*
104827** Recompute pMerger->aTree[iOut] by comparing the next keys on the
104828** two PmaReaders that feed that entry.  Neither of the PmaReaders
104829** are advanced.  This routine merely does the comparison.
104830*/
104831static void vdbeMergeEngineCompare(
104832  MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
104833  int iOut               /* Store the result in pMerger->aTree[iOut] */
104834){
104835  int i1;
104836  int i2;
104837  int iRes;
104838  PmaReader *p1;
104839  PmaReader *p2;
104840
104841  assert( iOut<pMerger->nTree && iOut>0 );
104842
104843  if( iOut>=(pMerger->nTree/2) ){
104844    i1 = (iOut - pMerger->nTree/2) * 2;
104845    i2 = i1 + 1;
104846  }else{
104847    i1 = pMerger->aTree[iOut*2];
104848    i2 = pMerger->aTree[iOut*2+1];
104849  }
104850
104851  p1 = &pMerger->aReadr[i1];
104852  p2 = &pMerger->aReadr[i2];
104853
104854  if( p1->pFd==0 ){
104855    iRes = i2;
104856  }else if( p2->pFd==0 ){
104857    iRes = i1;
104858  }else{
104859    SortSubtask *pTask = pMerger->pTask;
104860    int bCached = 0;
104861    int res;
104862    assert( pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
104863    res = pTask->xCompare(
104864        pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
104865    );
104866    if( res<=0 ){
104867      iRes = i1;
104868    }else{
104869      iRes = i2;
104870    }
104871  }
104872
104873  pMerger->aTree[iOut] = iRes;
104874}
104875
104876/*
104877** Allowed values for the eMode parameter to vdbeMergeEngineInit()
104878** and vdbePmaReaderIncrMergeInit().
104879**
104880** Only INCRINIT_NORMAL is valid in single-threaded builds (when
104881** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
104882** when there exists one or more separate worker threads.
104883*/
104884#define INCRINIT_NORMAL 0
104885#define INCRINIT_TASK   1
104886#define INCRINIT_ROOT   2
104887
104888/*
104889** Forward reference required as the vdbeIncrMergeInit() and
104890** vdbePmaReaderIncrInit() routines are called mutually recursively when
104891** building a merge tree.
104892*/
104893static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
104894
104895/*
104896** Initialize the MergeEngine object passed as the second argument. Once this
104897** function returns, the first key of merged data may be read from the
104898** MergeEngine object in the usual fashion.
104899**
104900** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
104901** objects attached to the PmaReader objects that the merger reads from have
104902** already been populated, but that they have not yet populated aFile[0] and
104903** set the PmaReader objects up to read from it. In this case all that is
104904** required is to call vdbePmaReaderNext() on each PmaReader to point it at
104905** its first key.
104906**
104907** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
104908** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
104909** to pMerger.
104910**
104911** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
104912*/
104913static int vdbeMergeEngineInit(
104914  SortSubtask *pTask,             /* Thread that will run pMerger */
104915  MergeEngine *pMerger,           /* MergeEngine to initialize */
104916  int eMode                       /* One of the INCRINIT_XXX constants */
104917){
104918  int rc = SQLITE_OK;             /* Return code */
104919  int i;                          /* For looping over PmaReader objects */
104920  int nTree;                      /* Number of subtrees to merge */
104921
104922  /* Failure to allocate the merge would have been detected prior to
104923  ** invoking this routine */
104924  assert( pMerger!=0 );
104925
104926  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
104927  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
104928
104929  /* Verify that the MergeEngine is assigned to a single thread */
104930  assert( pMerger->pTask==0 );
104931  pMerger->pTask = pTask;
104932
104933  nTree = pMerger->nTree;
104934  for(i=0; i<nTree; i++){
104935    if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
104936      /* PmaReaders should be normally initialized in order, as if they are
104937      ** reading from the same temp file this makes for more linear file IO.
104938      ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
104939      ** in use it will block the vdbePmaReaderNext() call while it uses
104940      ** the main thread to fill its buffer. So calling PmaReaderNext()
104941      ** on this PmaReader before any of the multi-threaded PmaReaders takes
104942      ** better advantage of multi-processor hardware. */
104943      rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
104944    }else{
104945      rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
104946    }
104947    if( rc!=SQLITE_OK ) return rc;
104948  }
104949
104950  for(i=pMerger->nTree-1; i>0; i--){
104951    vdbeMergeEngineCompare(pMerger, i);
104952  }
104953  return pTask->pUnpacked->errCode;
104954}
104955
104956/*
104957** The PmaReader passed as the first argument is guaranteed to be an
104958** incremental-reader (pReadr->pIncr!=0). This function serves to open
104959** and/or initialize the temp file related fields of the IncrMerge
104960** object at (pReadr->pIncr).
104961**
104962** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
104963** in the sub-tree headed by pReadr are also initialized. Data is then
104964** loaded into the buffers belonging to pReadr and it is set to point to
104965** the first key in its range.
104966**
104967** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
104968** to be a multi-threaded PmaReader and this function is being called in a
104969** background thread. In this case all PmaReaders in the sub-tree are
104970** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
104971** pReadr is populated. However, pReadr itself is not set up to point
104972** to its first key. A call to vdbePmaReaderNext() is still required to do
104973** that.
104974**
104975** The reason this function does not call vdbePmaReaderNext() immediately
104976** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
104977** to block on thread (pTask->thread) before accessing aFile[1]. But, since
104978** this entire function is being run by thread (pTask->thread), that will
104979** lead to the current background thread attempting to join itself.
104980**
104981** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
104982** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
104983** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
104984** In this case vdbePmaReaderNext() is called on all child PmaReaders and
104985** the current PmaReader set to point to the first key in its range.
104986**
104987** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
104988*/
104989static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
104990  int rc = SQLITE_OK;
104991  IncrMerger *pIncr = pReadr->pIncr;
104992  SortSubtask *pTask = pIncr->pTask;
104993  sqlite3 *db = pTask->pSorter->db;
104994
104995  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
104996  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
104997
104998  rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
104999
105000  /* Set up the required files for pIncr. A multi-threaded IncrMerge object
105001  ** requires two temp files to itself, whereas a single-threaded object
105002  ** only requires a region of pTask->file2. */
105003  if( rc==SQLITE_OK ){
105004    int mxSz = pIncr->mxSz;
105005#if SQLITE_MAX_WORKER_THREADS>0
105006    if( pIncr->bUseThread ){
105007      rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
105008      if( rc==SQLITE_OK ){
105009        rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
105010      }
105011    }else
105012#endif
105013    /*if( !pIncr->bUseThread )*/{
105014      if( pTask->file2.pFd==0 ){
105015        assert( pTask->file2.iEof>0 );
105016        rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
105017        pTask->file2.iEof = 0;
105018      }
105019      if( rc==SQLITE_OK ){
105020        pIncr->aFile[1].pFd = pTask->file2.pFd;
105021        pIncr->iStartOff = pTask->file2.iEof;
105022        pTask->file2.iEof += mxSz;
105023      }
105024    }
105025  }
105026
105027#if SQLITE_MAX_WORKER_THREADS>0
105028  if( rc==SQLITE_OK && pIncr->bUseThread ){
105029    /* Use the current thread to populate aFile[1], even though this
105030    ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
105031    ** then this function is already running in background thread
105032    ** pIncr->pTask->thread.
105033    **
105034    ** If this is the INCRINIT_ROOT object, then it is running in the
105035    ** main VDBE thread. But that is Ok, as that thread cannot return
105036    ** control to the VDBE or proceed with anything useful until the
105037    ** first results are ready from this merger object anyway.
105038    */
105039    assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
105040    rc = vdbeIncrPopulate(pIncr);
105041  }
105042#endif
105043
105044  if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
105045    rc = vdbePmaReaderNext(pReadr);
105046  }
105047
105048  return rc;
105049}
105050
105051#if SQLITE_MAX_WORKER_THREADS>0
105052/*
105053** The main routine for vdbePmaReaderIncrMergeInit() operations run in
105054** background threads.
105055*/
105056static void *vdbePmaReaderBgIncrInit(void *pCtx){
105057  PmaReader *pReader = (PmaReader*)pCtx;
105058  void *pRet = SQLITE_INT_TO_PTR(
105059                  vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
105060               );
105061  pReader->pIncr->pTask->bDone = 1;
105062  return pRet;
105063}
105064#endif
105065
105066/*
105067** If the PmaReader passed as the first argument is not an incremental-reader
105068** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
105069** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
105070** this routine to initialize the incremental merge.
105071**
105072** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
105073** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
105074** Or, if the IncrMerger is single threaded, the same function is called
105075** using the current thread.
105076*/
105077static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
105078  IncrMerger *pIncr = pReadr->pIncr;   /* Incremental merger */
105079  int rc = SQLITE_OK;                  /* Return code */
105080  if( pIncr ){
105081#if SQLITE_MAX_WORKER_THREADS>0
105082    assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
105083    if( pIncr->bUseThread ){
105084      void *pCtx = (void*)pReadr;
105085      rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
105086    }else
105087#endif
105088    {
105089      rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
105090    }
105091  }
105092  return rc;
105093}
105094
105095/*
105096** Allocate a new MergeEngine object to merge the contents of nPMA level-0
105097** PMAs from pTask->file. If no error occurs, set *ppOut to point to
105098** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
105099** to NULL and return an SQLite error code.
105100**
105101** When this function is called, *piOffset is set to the offset of the
105102** first PMA to read from pTask->file. Assuming no error occurs, it is
105103** set to the offset immediately following the last byte of the last
105104** PMA before returning. If an error does occur, then the final value of
105105** *piOffset is undefined.
105106*/
105107static int vdbeMergeEngineLevel0(
105108  SortSubtask *pTask,             /* Sorter task to read from */
105109  int nPMA,                       /* Number of PMAs to read */
105110  i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
105111  MergeEngine **ppOut             /* OUT: New merge-engine */
105112){
105113  MergeEngine *pNew;              /* Merge engine to return */
105114  i64 iOff = *piOffset;
105115  int i;
105116  int rc = SQLITE_OK;
105117
105118  *ppOut = pNew = vdbeMergeEngineNew(nPMA);
105119  if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
105120
105121  for(i=0; i<nPMA && rc==SQLITE_OK; i++){
105122    i64 nDummy = 0;
105123    PmaReader *pReadr = &pNew->aReadr[i];
105124    rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
105125    iOff = pReadr->iEof;
105126  }
105127
105128  if( rc!=SQLITE_OK ){
105129    vdbeMergeEngineFree(pNew);
105130    *ppOut = 0;
105131  }
105132  *piOffset = iOff;
105133  return rc;
105134}
105135
105136/*
105137** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
105138** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
105139**
105140** i.e.
105141**
105142**   nPMA<=16    -> TreeDepth() == 0
105143**   nPMA<=256   -> TreeDepth() == 1
105144**   nPMA<=65536 -> TreeDepth() == 2
105145*/
105146static int vdbeSorterTreeDepth(int nPMA){
105147  int nDepth = 0;
105148  i64 nDiv = SORTER_MAX_MERGE_COUNT;
105149  while( nDiv < (i64)nPMA ){
105150    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
105151    nDepth++;
105152  }
105153  return nDepth;
105154}
105155
105156/*
105157** pRoot is the root of an incremental merge-tree with depth nDepth (according
105158** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
105159** tree, counting from zero. This function adds pLeaf to the tree.
105160**
105161** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
105162** code is returned and pLeaf is freed.
105163*/
105164static int vdbeSorterAddToTree(
105165  SortSubtask *pTask,             /* Task context */
105166  int nDepth,                     /* Depth of tree according to TreeDepth() */
105167  int iSeq,                       /* Sequence number of leaf within tree */
105168  MergeEngine *pRoot,             /* Root of tree */
105169  MergeEngine *pLeaf              /* Leaf to add to tree */
105170){
105171  int rc = SQLITE_OK;
105172  int nDiv = 1;
105173  int i;
105174  MergeEngine *p = pRoot;
105175  IncrMerger *pIncr;
105176
105177  rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
105178
105179  for(i=1; i<nDepth; i++){
105180    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
105181  }
105182
105183  for(i=1; i<nDepth && rc==SQLITE_OK; i++){
105184    int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
105185    PmaReader *pReadr = &p->aReadr[iIter];
105186
105187    if( pReadr->pIncr==0 ){
105188      MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
105189      if( pNew==0 ){
105190        rc = SQLITE_NOMEM_BKPT;
105191      }else{
105192        rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
105193      }
105194    }
105195    if( rc==SQLITE_OK ){
105196      p = pReadr->pIncr->pMerger;
105197      nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
105198    }
105199  }
105200
105201  if( rc==SQLITE_OK ){
105202    p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
105203  }else{
105204    vdbeIncrFree(pIncr);
105205  }
105206  return rc;
105207}
105208
105209/*
105210** This function is called as part of a SorterRewind() operation on a sorter
105211** that has already written two or more level-0 PMAs to one or more temp
105212** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
105213** can be used to incrementally merge all PMAs on disk.
105214**
105215** If successful, SQLITE_OK is returned and *ppOut set to point to the
105216** MergeEngine object at the root of the tree before returning. Or, if an
105217** error occurs, an SQLite error code is returned and the final value
105218** of *ppOut is undefined.
105219*/
105220static int vdbeSorterMergeTreeBuild(
105221  VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
105222  MergeEngine **ppOut        /* Write the MergeEngine here */
105223){
105224  MergeEngine *pMain = 0;
105225  int rc = SQLITE_OK;
105226  int iTask;
105227
105228#if SQLITE_MAX_WORKER_THREADS>0
105229  /* If the sorter uses more than one task, then create the top-level
105230  ** MergeEngine here. This MergeEngine will read data from exactly
105231  ** one PmaReader per sub-task.  */
105232  assert( pSorter->bUseThreads || pSorter->nTask==1 );
105233  if( pSorter->nTask>1 ){
105234    pMain = vdbeMergeEngineNew(pSorter->nTask);
105235    if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
105236  }
105237#endif
105238
105239  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
105240    SortSubtask *pTask = &pSorter->aTask[iTask];
105241    assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
105242    if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
105243      MergeEngine *pRoot = 0;     /* Root node of tree for this task */
105244      int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
105245      i64 iReadOff = 0;
105246
105247      if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
105248        rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
105249      }else{
105250        int i;
105251        int iSeq = 0;
105252        pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
105253        if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
105254        for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
105255          MergeEngine *pMerger = 0; /* New level-0 PMA merger */
105256          int nReader;              /* Number of level-0 PMAs to merge */
105257
105258          nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
105259          rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
105260          if( rc==SQLITE_OK ){
105261            rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
105262          }
105263        }
105264      }
105265
105266      if( rc==SQLITE_OK ){
105267#if SQLITE_MAX_WORKER_THREADS>0
105268        if( pMain!=0 ){
105269          rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
105270        }else
105271#endif
105272        {
105273          assert( pMain==0 );
105274          pMain = pRoot;
105275        }
105276      }else{
105277        vdbeMergeEngineFree(pRoot);
105278      }
105279    }
105280  }
105281
105282  if( rc!=SQLITE_OK ){
105283    vdbeMergeEngineFree(pMain);
105284    pMain = 0;
105285  }
105286  *ppOut = pMain;
105287  return rc;
105288}
105289
105290/*
105291** This function is called as part of an sqlite3VdbeSorterRewind() operation
105292** on a sorter that has written two or more PMAs to temporary files. It sets
105293** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
105294** (for multi-threaded sorters) so that it can be used to iterate through
105295** all records stored in the sorter.
105296**
105297** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
105298*/
105299static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
105300  int rc;                         /* Return code */
105301  SortSubtask *pTask0 = &pSorter->aTask[0];
105302  MergeEngine *pMain = 0;
105303#if SQLITE_MAX_WORKER_THREADS
105304  sqlite3 *db = pTask0->pSorter->db;
105305  int i;
105306  SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
105307  for(i=0; i<pSorter->nTask; i++){
105308    pSorter->aTask[i].xCompare = xCompare;
105309  }
105310#endif
105311
105312  rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
105313  if( rc==SQLITE_OK ){
105314#if SQLITE_MAX_WORKER_THREADS
105315    assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
105316    if( pSorter->bUseThreads ){
105317      int iTask;
105318      PmaReader *pReadr = 0;
105319      SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
105320      rc = vdbeSortAllocUnpacked(pLast);
105321      if( rc==SQLITE_OK ){
105322        pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
105323        pSorter->pReader = pReadr;
105324        if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
105325      }
105326      if( rc==SQLITE_OK ){
105327        rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
105328        if( rc==SQLITE_OK ){
105329          vdbeIncrMergerSetThreads(pReadr->pIncr);
105330          for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
105331            IncrMerger *pIncr;
105332            if( (pIncr = pMain->aReadr[iTask].pIncr) ){
105333              vdbeIncrMergerSetThreads(pIncr);
105334              assert( pIncr->pTask!=pLast );
105335            }
105336          }
105337          for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
105338            /* Check that:
105339            **
105340            **   a) The incremental merge object is configured to use the
105341            **      right task, and
105342            **   b) If it is using task (nTask-1), it is configured to run
105343            **      in single-threaded mode. This is important, as the
105344            **      root merge (INCRINIT_ROOT) will be using the same task
105345            **      object.
105346            */
105347            PmaReader *p = &pMain->aReadr[iTask];
105348            assert( p->pIncr==0 || (
105349                (p->pIncr->pTask==&pSorter->aTask[iTask])             /* a */
105350             && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0)  /* b */
105351            ));
105352            rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
105353          }
105354        }
105355        pMain = 0;
105356      }
105357      if( rc==SQLITE_OK ){
105358        rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
105359      }
105360    }else
105361#endif
105362    {
105363      rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
105364      pSorter->pMerger = pMain;
105365      pMain = 0;
105366    }
105367  }
105368
105369  if( rc!=SQLITE_OK ){
105370    vdbeMergeEngineFree(pMain);
105371  }
105372  return rc;
105373}
105374
105375
105376/*
105377** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
105378** this function is called to prepare for iterating through the records
105379** in sorted order.
105380*/
105381SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
105382  VdbeSorter *pSorter;
105383  int rc = SQLITE_OK;             /* Return code */
105384
105385  assert( pCsr->eCurType==CURTYPE_SORTER );
105386  pSorter = pCsr->uc.pSorter;
105387  assert( pSorter );
105388
105389  /* If no data has been written to disk, then do not do so now. Instead,
105390  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
105391  ** from the in-memory list.  */
105392  if( pSorter->bUsePMA==0 ){
105393    if( pSorter->list.pList ){
105394      *pbEof = 0;
105395      rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
105396    }else{
105397      *pbEof = 1;
105398    }
105399    return rc;
105400  }
105401
105402  /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
105403  ** function flushes the contents of memory to disk, it immediately always
105404  ** creates a new list consisting of a single key immediately afterwards.
105405  ** So the list is never empty at this point.  */
105406  assert( pSorter->list.pList );
105407  rc = vdbeSorterFlushPMA(pSorter);
105408
105409  /* Join all threads */
105410  rc = vdbeSorterJoinAll(pSorter, rc);
105411
105412  vdbeSorterRewindDebug("rewind");
105413
105414  /* Assuming no errors have occurred, set up a merger structure to
105415  ** incrementally read and merge all remaining PMAs.  */
105416  assert( pSorter->pReader==0 );
105417  if( rc==SQLITE_OK ){
105418    rc = vdbeSorterSetupMerge(pSorter);
105419    *pbEof = 0;
105420  }
105421
105422  vdbeSorterRewindDebug("rewinddone");
105423  return rc;
105424}
105425
105426/*
105427** Advance to the next element in the sorter.  Return value:
105428**
105429**    SQLITE_OK     success
105430**    SQLITE_DONE   end of data
105431**    otherwise     some kind of error.
105432*/
105433SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
105434  VdbeSorter *pSorter;
105435  int rc;                         /* Return code */
105436
105437  assert( pCsr->eCurType==CURTYPE_SORTER );
105438  pSorter = pCsr->uc.pSorter;
105439  assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
105440  if( pSorter->bUsePMA ){
105441    assert( pSorter->pReader==0 || pSorter->pMerger==0 );
105442    assert( pSorter->bUseThreads==0 || pSorter->pReader );
105443    assert( pSorter->bUseThreads==1 || pSorter->pMerger );
105444#if SQLITE_MAX_WORKER_THREADS>0
105445    if( pSorter->bUseThreads ){
105446      rc = vdbePmaReaderNext(pSorter->pReader);
105447      if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
105448    }else
105449#endif
105450    /*if( !pSorter->bUseThreads )*/ {
105451      int res = 0;
105452      assert( pSorter->pMerger!=0 );
105453      assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
105454      rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
105455      if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
105456    }
105457  }else{
105458    SorterRecord *pFree = pSorter->list.pList;
105459    pSorter->list.pList = pFree->u.pNext;
105460    pFree->u.pNext = 0;
105461    if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
105462    rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
105463  }
105464  return rc;
105465}
105466
105467/*
105468** Return a pointer to a buffer owned by the sorter that contains the
105469** current key.
105470*/
105471static void *vdbeSorterRowkey(
105472  const VdbeSorter *pSorter,      /* Sorter object */
105473  int *pnKey                      /* OUT: Size of current key in bytes */
105474){
105475  void *pKey;
105476  if( pSorter->bUsePMA ){
105477    PmaReader *pReader;
105478#if SQLITE_MAX_WORKER_THREADS>0
105479    if( pSorter->bUseThreads ){
105480      pReader = pSorter->pReader;
105481    }else
105482#endif
105483    /*if( !pSorter->bUseThreads )*/{
105484      pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
105485    }
105486    *pnKey = pReader->nKey;
105487    pKey = pReader->aKey;
105488  }else{
105489    *pnKey = pSorter->list.pList->nVal;
105490    pKey = SRVAL(pSorter->list.pList);
105491  }
105492  return pKey;
105493}
105494
105495/*
105496** Copy the current sorter key into the memory cell pOut.
105497*/
105498SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
105499  VdbeSorter *pSorter;
105500  void *pKey; int nKey;           /* Sorter key to copy into pOut */
105501
105502  assert( pCsr->eCurType==CURTYPE_SORTER );
105503  pSorter = pCsr->uc.pSorter;
105504  pKey = vdbeSorterRowkey(pSorter, &nKey);
105505  if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
105506    return SQLITE_NOMEM_BKPT;
105507  }
105508  pOut->n = nKey;
105509  MemSetTypeFlag(pOut, MEM_Blob);
105510  memcpy(pOut->z, pKey, nKey);
105511
105512  return SQLITE_OK;
105513}
105514
105515/*
105516** Compare the key in memory cell pVal with the key that the sorter cursor
105517** passed as the first argument currently points to. For the purposes of
105518** the comparison, ignore the rowid field at the end of each record.
105519**
105520** If the sorter cursor key contains any NULL values, consider it to be
105521** less than pVal. Even if pVal also contains NULL values.
105522**
105523** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
105524** Otherwise, set *pRes to a negative, zero or positive value if the
105525** key in pVal is smaller than, equal to or larger than the current sorter
105526** key.
105527**
105528** This routine forms the core of the OP_SorterCompare opcode, which in
105529** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
105530*/
105531SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
105532  const VdbeCursor *pCsr,         /* Sorter cursor */
105533  Mem *pVal,                      /* Value to compare to current sorter key */
105534  int nKeyCol,                    /* Compare this many columns */
105535  int *pRes                       /* OUT: Result of comparison */
105536){
105537  VdbeSorter *pSorter;
105538  UnpackedRecord *r2;
105539  KeyInfo *pKeyInfo;
105540  int i;
105541  void *pKey; int nKey;           /* Sorter key to compare pVal with */
105542
105543  assert( pCsr->eCurType==CURTYPE_SORTER );
105544  pSorter = pCsr->uc.pSorter;
105545  r2 = pSorter->pUnpacked;
105546  pKeyInfo = pCsr->pKeyInfo;
105547  if( r2==0 ){
105548    r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
105549    if( r2==0 ) return SQLITE_NOMEM_BKPT;
105550    r2->nField = nKeyCol;
105551  }
105552  assert( r2->nField==nKeyCol );
105553
105554  pKey = vdbeSorterRowkey(pSorter, &nKey);
105555  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
105556  for(i=0; i<nKeyCol; i++){
105557    if( r2->aMem[i].flags & MEM_Null ){
105558      *pRes = -1;
105559      return SQLITE_OK;
105560    }
105561  }
105562
105563  *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
105564  return SQLITE_OK;
105565}
105566
105567/************** End of vdbesort.c ********************************************/
105568/************** Begin file vdbevtab.c ****************************************/
105569/*
105570** 2020-03-23
105571**
105572** The author disclaims copyright to this source code.  In place of
105573** a legal notice, here is a blessing:
105574**
105575**    May you do good and not evil.
105576**    May you find forgiveness for yourself and forgive others.
105577**    May you share freely, never taking more than you give.
105578**
105579*************************************************************************
105580**
105581** This file implements virtual-tables for examining the bytecode content
105582** of a prepared statement.
105583*/
105584/* #include "sqliteInt.h" */
105585#if defined(SQLITE_ENABLE_BYTECODE_VTAB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
105586/* #include "vdbeInt.h" */
105587
105588/* An instance of the bytecode() table-valued function.
105589*/
105590typedef struct bytecodevtab bytecodevtab;
105591struct bytecodevtab {
105592  sqlite3_vtab base;     /* Base class - must be first */
105593  sqlite3 *db;           /* Database connection */
105594  int bTablesUsed;       /* 2 for tables_used().  0 for bytecode(). */
105595};
105596
105597/* A cursor for scanning through the bytecode
105598*/
105599typedef struct bytecodevtab_cursor bytecodevtab_cursor;
105600struct bytecodevtab_cursor {
105601  sqlite3_vtab_cursor base;  /* Base class - must be first */
105602  sqlite3_stmt *pStmt;       /* The statement whose bytecode is displayed */
105603  int iRowid;                /* The rowid of the output table */
105604  int iAddr;                 /* Address */
105605  int needFinalize;          /* Cursors owns pStmt and must finalize it */
105606  int showSubprograms;       /* Provide a listing of subprograms */
105607  Op *aOp;                   /* Operand array */
105608  char *zP4;                 /* Rendered P4 value */
105609  const char *zType;         /* tables_used.type */
105610  const char *zSchema;       /* tables_used.schema */
105611  const char *zName;         /* tables_used.name */
105612  Mem sub;                   /* Subprograms */
105613};
105614
105615/*
105616** Create a new bytecode() table-valued function.
105617*/
105618static int bytecodevtabConnect(
105619  sqlite3 *db,
105620  void *pAux,
105621  int argc, const char *const*argv,
105622  sqlite3_vtab **ppVtab,
105623  char **pzErr
105624){
105625  bytecodevtab *pNew;
105626  int rc;
105627  int isTabUsed = pAux!=0;
105628  const char *azSchema[2] = {
105629    /* bytecode() schema */
105630    "CREATE TABLE x("
105631      "addr INT,"
105632      "opcode TEXT,"
105633      "p1 INT,"
105634      "p2 INT,"
105635      "p3 INT,"
105636      "p4 TEXT,"
105637      "p5 INT,"
105638      "comment TEXT,"
105639      "subprog TEXT,"
105640      "nexec INT,"
105641      "ncycle INT,"
105642      "stmt HIDDEN"
105643    ");",
105644
105645    /* Tables_used() schema */
105646    "CREATE TABLE x("
105647      "type TEXT,"
105648      "schema TEXT,"
105649      "name TEXT,"
105650      "wr INT,"
105651      "subprog TEXT,"
105652      "stmt HIDDEN"
105653   ");"
105654  };
105655
105656  (void)argc;
105657  (void)argv;
105658  (void)pzErr;
105659  rc = sqlite3_declare_vtab(db, azSchema[isTabUsed]);
105660  if( rc==SQLITE_OK ){
105661    pNew = sqlite3_malloc( sizeof(*pNew) );
105662    *ppVtab = (sqlite3_vtab*)pNew;
105663    if( pNew==0 ) return SQLITE_NOMEM;
105664    memset(pNew, 0, sizeof(*pNew));
105665    pNew->db = db;
105666    pNew->bTablesUsed = isTabUsed*2;
105667  }
105668  return rc;
105669}
105670
105671/*
105672** This method is the destructor for bytecodevtab objects.
105673*/
105674static int bytecodevtabDisconnect(sqlite3_vtab *pVtab){
105675  bytecodevtab *p = (bytecodevtab*)pVtab;
105676  sqlite3_free(p);
105677  return SQLITE_OK;
105678}
105679
105680/*
105681** Constructor for a new bytecodevtab_cursor object.
105682*/
105683static int bytecodevtabOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
105684  bytecodevtab *pVTab = (bytecodevtab*)p;
105685  bytecodevtab_cursor *pCur;
105686  pCur = sqlite3_malloc( sizeof(*pCur) );
105687  if( pCur==0 ) return SQLITE_NOMEM;
105688  memset(pCur, 0, sizeof(*pCur));
105689  sqlite3VdbeMemInit(&pCur->sub, pVTab->db, 1);
105690  *ppCursor = &pCur->base;
105691  return SQLITE_OK;
105692}
105693
105694/*
105695** Clear all internal content from a bytecodevtab cursor.
105696*/
105697static void bytecodevtabCursorClear(bytecodevtab_cursor *pCur){
105698  sqlite3_free(pCur->zP4);
105699  pCur->zP4 = 0;
105700  sqlite3VdbeMemRelease(&pCur->sub);
105701  sqlite3VdbeMemSetNull(&pCur->sub);
105702  if( pCur->needFinalize ){
105703    sqlite3_finalize(pCur->pStmt);
105704  }
105705  pCur->pStmt = 0;
105706  pCur->needFinalize = 0;
105707  pCur->zType = 0;
105708  pCur->zSchema = 0;
105709  pCur->zName = 0;
105710}
105711
105712/*
105713** Destructor for a bytecodevtab_cursor.
105714*/
105715static int bytecodevtabClose(sqlite3_vtab_cursor *cur){
105716  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
105717  bytecodevtabCursorClear(pCur);
105718  sqlite3_free(pCur);
105719  return SQLITE_OK;
105720}
105721
105722
105723/*
105724** Advance a bytecodevtab_cursor to its next row of output.
105725*/
105726static int bytecodevtabNext(sqlite3_vtab_cursor *cur){
105727  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
105728  bytecodevtab *pTab = (bytecodevtab*)cur->pVtab;
105729  int rc;
105730  if( pCur->zP4 ){
105731    sqlite3_free(pCur->zP4);
105732    pCur->zP4 = 0;
105733  }
105734  if( pCur->zName ){
105735    pCur->zName = 0;
105736    pCur->zType = 0;
105737    pCur->zSchema = 0;
105738  }
105739  rc = sqlite3VdbeNextOpcode(
105740           (Vdbe*)pCur->pStmt,
105741           pCur->showSubprograms ? &pCur->sub : 0,
105742           pTab->bTablesUsed,
105743           &pCur->iRowid,
105744           &pCur->iAddr,
105745           &pCur->aOp);
105746  if( rc!=SQLITE_OK ){
105747    sqlite3VdbeMemSetNull(&pCur->sub);
105748    pCur->aOp = 0;
105749  }
105750  return SQLITE_OK;
105751}
105752
105753/*
105754** Return TRUE if the cursor has been moved off of the last
105755** row of output.
105756*/
105757static int bytecodevtabEof(sqlite3_vtab_cursor *cur){
105758  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
105759  return pCur->aOp==0;
105760}
105761
105762/*
105763** Return values of columns for the row at which the bytecodevtab_cursor
105764** is currently pointing.
105765*/
105766static int bytecodevtabColumn(
105767  sqlite3_vtab_cursor *cur,   /* The cursor */
105768  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
105769  int i                       /* Which column to return */
105770){
105771  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
105772  bytecodevtab *pVTab = (bytecodevtab*)cur->pVtab;
105773  Op *pOp = pCur->aOp + pCur->iAddr;
105774  if( pVTab->bTablesUsed ){
105775    if( i==4 ){
105776      i = 8;
105777    }else{
105778      if( i<=2 && pCur->zType==0 ){
105779        Schema *pSchema;
105780        HashElem *k;
105781        int iDb = pOp->p3;
105782        Pgno iRoot = (Pgno)pOp->p2;
105783        sqlite3 *db = pVTab->db;
105784        pSchema = db->aDb[iDb].pSchema;
105785        pCur->zSchema = db->aDb[iDb].zDbSName;
105786        for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
105787          Table *pTab = (Table*)sqliteHashData(k);
105788          if( !IsVirtual(pTab) && pTab->tnum==iRoot ){
105789            pCur->zName = pTab->zName;
105790            pCur->zType = "table";
105791            break;
105792          }
105793        }
105794        if( pCur->zName==0 ){
105795          for(k=sqliteHashFirst(&pSchema->idxHash); k; k=sqliteHashNext(k)){
105796            Index *pIdx = (Index*)sqliteHashData(k);
105797            if( pIdx->tnum==iRoot ){
105798              pCur->zName = pIdx->zName;
105799              pCur->zType = "index";
105800            }
105801          }
105802        }
105803      }
105804      i += 20;
105805    }
105806  }
105807  switch( i ){
105808    case 0:   /* addr */
105809      sqlite3_result_int(ctx, pCur->iAddr);
105810      break;
105811    case 1:   /* opcode */
105812      sqlite3_result_text(ctx, (char*)sqlite3OpcodeName(pOp->opcode),
105813                          -1, SQLITE_STATIC);
105814      break;
105815    case 2:   /* p1 */
105816      sqlite3_result_int(ctx, pOp->p1);
105817      break;
105818    case 3:   /* p2 */
105819      sqlite3_result_int(ctx, pOp->p2);
105820      break;
105821    case 4:   /* p3 */
105822      sqlite3_result_int(ctx, pOp->p3);
105823      break;
105824    case 5:   /* p4 */
105825    case 7:   /* comment */
105826      if( pCur->zP4==0 ){
105827        pCur->zP4 = sqlite3VdbeDisplayP4(pVTab->db, pOp);
105828      }
105829      if( i==5 ){
105830        sqlite3_result_text(ctx, pCur->zP4, -1, SQLITE_STATIC);
105831      }else{
105832#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
105833        char *zCom = sqlite3VdbeDisplayComment(pVTab->db, pOp, pCur->zP4);
105834        sqlite3_result_text(ctx, zCom, -1, sqlite3_free);
105835#endif
105836      }
105837      break;
105838    case 6:     /* p5 */
105839      sqlite3_result_int(ctx, pOp->p5);
105840      break;
105841    case 8: {   /* subprog */
105842      Op *aOp = pCur->aOp;
105843      assert( aOp[0].opcode==OP_Init );
105844      assert( aOp[0].p4.z==0 || strncmp(aOp[0].p4.z,"-" "- ",3)==0 );
105845      if( pCur->iRowid==pCur->iAddr+1 ){
105846        break;  /* Result is NULL for the main program */
105847      }else if( aOp[0].p4.z!=0 ){
105848         sqlite3_result_text(ctx, aOp[0].p4.z+3, -1, SQLITE_STATIC);
105849      }else{
105850         sqlite3_result_text(ctx, "(FK)", 4, SQLITE_STATIC);
105851      }
105852      break;
105853    }
105854
105855#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
105856    case 9:     /* nexec */
105857      sqlite3_result_int64(ctx, pOp->nExec);
105858      break;
105859    case 10:    /* ncycle */
105860      sqlite3_result_int64(ctx, pOp->nCycle);
105861      break;
105862#else
105863    case 9:     /* nexec */
105864    case 10:    /* ncycle */
105865      sqlite3_result_int(ctx, 0);
105866      break;
105867#endif
105868
105869    case 20:  /* tables_used.type */
105870      sqlite3_result_text(ctx, pCur->zType, -1, SQLITE_STATIC);
105871      break;
105872    case 21:  /* tables_used.schema */
105873      sqlite3_result_text(ctx, pCur->zSchema, -1, SQLITE_STATIC);
105874      break;
105875    case 22:  /* tables_used.name */
105876      sqlite3_result_text(ctx, pCur->zName, -1, SQLITE_STATIC);
105877      break;
105878    case 23:  /* tables_used.wr */
105879      sqlite3_result_int(ctx, pOp->opcode==OP_OpenWrite);
105880      break;
105881  }
105882  return SQLITE_OK;
105883}
105884
105885/*
105886** Return the rowid for the current row.  In this implementation, the
105887** rowid is the same as the output value.
105888*/
105889static int bytecodevtabRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
105890  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
105891  *pRowid = pCur->iRowid;
105892  return SQLITE_OK;
105893}
105894
105895/*
105896** Initialize a cursor.
105897**
105898**    idxNum==0     means show all subprograms
105899**    idxNum==1     means show only the main bytecode and omit subprograms.
105900*/
105901static int bytecodevtabFilter(
105902  sqlite3_vtab_cursor *pVtabCursor,
105903  int idxNum, const char *idxStr,
105904  int argc, sqlite3_value **argv
105905){
105906  bytecodevtab_cursor *pCur = (bytecodevtab_cursor *)pVtabCursor;
105907  bytecodevtab *pVTab = (bytecodevtab *)pVtabCursor->pVtab;
105908  int rc = SQLITE_OK;
105909  (void)idxStr;
105910
105911  bytecodevtabCursorClear(pCur);
105912  pCur->iRowid = 0;
105913  pCur->iAddr = 0;
105914  pCur->showSubprograms = idxNum==0;
105915  assert( argc==1 );
105916  if( sqlite3_value_type(argv[0])==SQLITE_TEXT ){
105917    const char *zSql = (const char*)sqlite3_value_text(argv[0]);
105918    if( zSql==0 ){
105919      rc = SQLITE_NOMEM;
105920    }else{
105921      rc = sqlite3_prepare_v2(pVTab->db, zSql, -1, &pCur->pStmt, 0);
105922      pCur->needFinalize = 1;
105923    }
105924  }else{
105925    pCur->pStmt = (sqlite3_stmt*)sqlite3_value_pointer(argv[0],"stmt-pointer");
105926  }
105927  if( pCur->pStmt==0 ){
105928    pVTab->base.zErrMsg = sqlite3_mprintf(
105929       "argument to %s() is not a valid SQL statement",
105930       pVTab->bTablesUsed ? "tables_used" : "bytecode"
105931    );
105932    rc = SQLITE_ERROR;
105933  }else{
105934    bytecodevtabNext(pVtabCursor);
105935  }
105936  return rc;
105937}
105938
105939/*
105940** We must have a single stmt=? constraint that will be passed through
105941** into the xFilter method.  If there is no valid stmt=? constraint,
105942** then return an SQLITE_CONSTRAINT error.
105943*/
105944static int bytecodevtabBestIndex(
105945  sqlite3_vtab *tab,
105946  sqlite3_index_info *pIdxInfo
105947){
105948  int i;
105949  int rc = SQLITE_CONSTRAINT;
105950  struct sqlite3_index_constraint *p;
105951  bytecodevtab *pVTab = (bytecodevtab*)tab;
105952  int iBaseCol = pVTab->bTablesUsed ? 4 : 10;
105953  pIdxInfo->estimatedCost = (double)100;
105954  pIdxInfo->estimatedRows = 100;
105955  pIdxInfo->idxNum = 0;
105956  for(i=0, p=pIdxInfo->aConstraint; i<pIdxInfo->nConstraint; i++, p++){
105957    if( p->usable==0 ) continue;
105958    if( p->op==SQLITE_INDEX_CONSTRAINT_EQ && p->iColumn==iBaseCol+1 ){
105959      rc = SQLITE_OK;
105960      pIdxInfo->aConstraintUsage[i].omit = 1;
105961      pIdxInfo->aConstraintUsage[i].argvIndex = 1;
105962    }
105963    if( p->op==SQLITE_INDEX_CONSTRAINT_ISNULL && p->iColumn==iBaseCol ){
105964      pIdxInfo->aConstraintUsage[i].omit = 1;
105965      pIdxInfo->idxNum = 1;
105966    }
105967  }
105968  return rc;
105969}
105970
105971/*
105972** This following structure defines all the methods for the
105973** virtual table.
105974*/
105975static sqlite3_module bytecodevtabModule = {
105976  /* iVersion    */ 0,
105977  /* xCreate     */ 0,
105978  /* xConnect    */ bytecodevtabConnect,
105979  /* xBestIndex  */ bytecodevtabBestIndex,
105980  /* xDisconnect */ bytecodevtabDisconnect,
105981  /* xDestroy    */ 0,
105982  /* xOpen       */ bytecodevtabOpen,
105983  /* xClose      */ bytecodevtabClose,
105984  /* xFilter     */ bytecodevtabFilter,
105985  /* xNext       */ bytecodevtabNext,
105986  /* xEof        */ bytecodevtabEof,
105987  /* xColumn     */ bytecodevtabColumn,
105988  /* xRowid      */ bytecodevtabRowid,
105989  /* xUpdate     */ 0,
105990  /* xBegin      */ 0,
105991  /* xSync       */ 0,
105992  /* xCommit     */ 0,
105993  /* xRollback   */ 0,
105994  /* xFindMethod */ 0,
105995  /* xRename     */ 0,
105996  /* xSavepoint  */ 0,
105997  /* xRelease    */ 0,
105998  /* xRollbackTo */ 0,
105999  /* xShadowName */ 0,
106000  /* xIntegrity  */ 0
106001};
106002
106003
106004SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3 *db){
106005  int rc;
106006  rc = sqlite3_create_module(db, "bytecode", &bytecodevtabModule, 0);
106007  if( rc==SQLITE_OK ){
106008    rc = sqlite3_create_module(db, "tables_used", &bytecodevtabModule, &db);
106009  }
106010  return rc;
106011}
106012#elif defined(SQLITE_ENABLE_BYTECODE_VTAB)
106013SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3 *db){ return SQLITE_OK; }
106014#endif /* SQLITE_ENABLE_BYTECODE_VTAB */
106015
106016/************** End of vdbevtab.c ********************************************/
106017/************** Begin file memjournal.c **************************************/
106018/*
106019** 2008 October 7
106020**
106021** The author disclaims copyright to this source code.  In place of
106022** a legal notice, here is a blessing:
106023**
106024**    May you do good and not evil.
106025**    May you find forgiveness for yourself and forgive others.
106026**    May you share freely, never taking more than you give.
106027**
106028*************************************************************************
106029**
106030** This file contains code use to implement an in-memory rollback journal.
106031** The in-memory rollback journal is used to journal transactions for
106032** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
106033**
106034** Update:  The in-memory journal is also used to temporarily cache
106035** smaller journals that are not critical for power-loss recovery.
106036** For example, statement journals that are not too big will be held
106037** entirely in memory, thus reducing the number of file I/O calls, and
106038** more importantly, reducing temporary file creation events.  If these
106039** journals become too large for memory, they are spilled to disk.  But
106040** in the common case, they are usually small and no file I/O needs to
106041** occur.
106042*/
106043/* #include "sqliteInt.h" */
106044
106045/* Forward references to internal structures */
106046typedef struct MemJournal MemJournal;
106047typedef struct FilePoint FilePoint;
106048typedef struct FileChunk FileChunk;
106049
106050/*
106051** The rollback journal is composed of a linked list of these structures.
106052**
106053** The zChunk array is always at least 8 bytes in size - usually much more.
106054** Its actual size is stored in the MemJournal.nChunkSize variable.
106055*/
106056struct FileChunk {
106057  FileChunk *pNext;               /* Next chunk in the journal */
106058  u8 zChunk[8];                   /* Content of this chunk */
106059};
106060
106061/*
106062** By default, allocate this many bytes of memory for each FileChunk object.
106063*/
106064#define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
106065
106066/*
106067** For chunk size nChunkSize, return the number of bytes that should
106068** be allocated for each FileChunk structure.
106069*/
106070#define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
106071
106072/*
106073** An instance of this object serves as a cursor into the rollback journal.
106074** The cursor can be either for reading or writing.
106075*/
106076struct FilePoint {
106077  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
106078  FileChunk *pChunk;              /* Specific chunk into which cursor points */
106079};
106080
106081/*
106082** This structure is a subclass of sqlite3_file. Each open memory-journal
106083** is an instance of this class.
106084*/
106085struct MemJournal {
106086  const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
106087  int nChunkSize;                 /* In-memory chunk-size */
106088
106089  int nSpill;                     /* Bytes of data before flushing */
106090  FileChunk *pFirst;              /* Head of in-memory chunk-list */
106091  FilePoint endpoint;             /* Pointer to the end of the file */
106092  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
106093
106094  int flags;                      /* xOpen flags */
106095  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
106096  const char *zJournal;           /* Name of the journal file */
106097};
106098
106099/*
106100** Read data from the in-memory journal file.  This is the implementation
106101** of the sqlite3_vfs.xRead method.
106102*/
106103static int memjrnlRead(
106104  sqlite3_file *pJfd,    /* The journal file from which to read */
106105  void *zBuf,            /* Put the results here */
106106  int iAmt,              /* Number of bytes to read */
106107  sqlite_int64 iOfst     /* Begin reading at this offset */
106108){
106109  MemJournal *p = (MemJournal *)pJfd;
106110  u8 *zOut = zBuf;
106111  int nRead = iAmt;
106112  int iChunkOffset;
106113  FileChunk *pChunk;
106114
106115  if( (iAmt+iOfst)>p->endpoint.iOffset ){
106116    return SQLITE_IOERR_SHORT_READ;
106117  }
106118  assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
106119  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
106120    sqlite3_int64 iOff = 0;
106121    for(pChunk=p->pFirst;
106122        ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
106123        pChunk=pChunk->pNext
106124    ){
106125      iOff += p->nChunkSize;
106126    }
106127  }else{
106128    pChunk = p->readpoint.pChunk;
106129    assert( pChunk!=0 );
106130  }
106131
106132  iChunkOffset = (int)(iOfst%p->nChunkSize);
106133  do {
106134    int iSpace = p->nChunkSize - iChunkOffset;
106135    int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
106136    memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
106137    zOut += nCopy;
106138    nRead -= iSpace;
106139    iChunkOffset = 0;
106140  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
106141  p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
106142  p->readpoint.pChunk = pChunk;
106143
106144  return SQLITE_OK;
106145}
106146
106147/*
106148** Free the list of FileChunk structures headed at MemJournal.pFirst.
106149*/
106150static void memjrnlFreeChunks(FileChunk *pFirst){
106151  FileChunk *pIter;
106152  FileChunk *pNext;
106153  for(pIter=pFirst; pIter; pIter=pNext){
106154    pNext = pIter->pNext;
106155    sqlite3_free(pIter);
106156  }
106157}
106158
106159/*
106160** Flush the contents of memory to a real file on disk.
106161*/
106162static int memjrnlCreateFile(MemJournal *p){
106163  int rc;
106164  sqlite3_file *pReal = (sqlite3_file*)p;
106165  MemJournal copy = *p;
106166
106167  memset(p, 0, sizeof(MemJournal));
106168  rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
106169  if( rc==SQLITE_OK ){
106170    int nChunk = copy.nChunkSize;
106171    i64 iOff = 0;
106172    FileChunk *pIter;
106173    for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
106174      if( iOff + nChunk > copy.endpoint.iOffset ){
106175        nChunk = copy.endpoint.iOffset - iOff;
106176      }
106177      rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
106178      if( rc ) break;
106179      iOff += nChunk;
106180    }
106181    if( rc==SQLITE_OK ){
106182      /* No error has occurred. Free the in-memory buffers. */
106183      memjrnlFreeChunks(copy.pFirst);
106184    }
106185  }
106186  if( rc!=SQLITE_OK ){
106187    /* If an error occurred while creating or writing to the file, restore
106188    ** the original before returning. This way, SQLite uses the in-memory
106189    ** journal data to roll back changes made to the internal page-cache
106190    ** before this function was called.  */
106191    sqlite3OsClose(pReal);
106192    *p = copy;
106193  }
106194  return rc;
106195}
106196
106197
106198/* Forward reference */
106199static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size);
106200
106201/*
106202** Write data to the file.
106203*/
106204static int memjrnlWrite(
106205  sqlite3_file *pJfd,    /* The journal file into which to write */
106206  const void *zBuf,      /* Take data to be written from here */
106207  int iAmt,              /* Number of bytes to write */
106208  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
106209){
106210  MemJournal *p = (MemJournal *)pJfd;
106211  int nWrite = iAmt;
106212  u8 *zWrite = (u8 *)zBuf;
106213
106214  /* If the file should be created now, create it and write the new data
106215  ** into the file on disk. */
106216  if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
106217    int rc = memjrnlCreateFile(p);
106218    if( rc==SQLITE_OK ){
106219      rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
106220    }
106221    return rc;
106222  }
106223
106224  /* If the contents of this write should be stored in memory */
106225  else{
106226    /* An in-memory journal file should only ever be appended to. Random
106227    ** access writes are not required. The only exception to this is when
106228    ** the in-memory journal is being used by a connection using the
106229    ** atomic-write optimization. In this case the first 28 bytes of the
106230    ** journal file may be written as part of committing the transaction. */
106231    assert( iOfst<=p->endpoint.iOffset );
106232    if( iOfst>0 && iOfst!=p->endpoint.iOffset ){
106233      memjrnlTruncate(pJfd, iOfst);
106234    }
106235    if( iOfst==0 && p->pFirst ){
106236      assert( p->nChunkSize>iAmt );
106237      memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
106238    }else{
106239      while( nWrite>0 ){
106240        FileChunk *pChunk = p->endpoint.pChunk;
106241        int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
106242        int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
106243
106244        assert( pChunk!=0 || iChunkOffset==0 );
106245        if( iChunkOffset==0 ){
106246          /* New chunk is required to extend the file. */
106247          FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
106248          if( !pNew ){
106249            return SQLITE_IOERR_NOMEM_BKPT;
106250          }
106251          pNew->pNext = 0;
106252          if( pChunk ){
106253            assert( p->pFirst );
106254            pChunk->pNext = pNew;
106255          }else{
106256            assert( !p->pFirst );
106257            p->pFirst = pNew;
106258          }
106259          pChunk = p->endpoint.pChunk = pNew;
106260        }
106261
106262        assert( pChunk!=0 );
106263        memcpy((u8*)pChunk->zChunk + iChunkOffset, zWrite, iSpace);
106264        zWrite += iSpace;
106265        nWrite -= iSpace;
106266        p->endpoint.iOffset += iSpace;
106267      }
106268    }
106269  }
106270
106271  return SQLITE_OK;
106272}
106273
106274/*
106275** Truncate the in-memory file.
106276*/
106277static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
106278  MemJournal *p = (MemJournal *)pJfd;
106279  assert( p->endpoint.pChunk==0 || p->endpoint.pChunk->pNext==0 );
106280  if( size<p->endpoint.iOffset ){
106281    FileChunk *pIter = 0;
106282    if( size==0 ){
106283      memjrnlFreeChunks(p->pFirst);
106284      p->pFirst = 0;
106285    }else{
106286      i64 iOff = p->nChunkSize;
106287      for(pIter=p->pFirst; ALWAYS(pIter) && iOff<size; pIter=pIter->pNext){
106288        iOff += p->nChunkSize;
106289      }
106290      if( ALWAYS(pIter) ){
106291        memjrnlFreeChunks(pIter->pNext);
106292        pIter->pNext = 0;
106293      }
106294    }
106295
106296    p->endpoint.pChunk = pIter;
106297    p->endpoint.iOffset = size;
106298    p->readpoint.pChunk = 0;
106299    p->readpoint.iOffset = 0;
106300  }
106301  return SQLITE_OK;
106302}
106303
106304/*
106305** Close the file.
106306*/
106307static int memjrnlClose(sqlite3_file *pJfd){
106308  MemJournal *p = (MemJournal *)pJfd;
106309  memjrnlFreeChunks(p->pFirst);
106310  return SQLITE_OK;
106311}
106312
106313/*
106314** Sync the file.
106315**
106316** If the real file has been created, call its xSync method. Otherwise,
106317** syncing an in-memory journal is a no-op.
106318*/
106319static int memjrnlSync(sqlite3_file *pJfd, int flags){
106320  UNUSED_PARAMETER2(pJfd, flags);
106321  return SQLITE_OK;
106322}
106323
106324/*
106325** Query the size of the file in bytes.
106326*/
106327static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
106328  MemJournal *p = (MemJournal *)pJfd;
106329  *pSize = (sqlite_int64) p->endpoint.iOffset;
106330  return SQLITE_OK;
106331}
106332
106333/*
106334** Table of methods for MemJournal sqlite3_file object.
106335*/
106336static const struct sqlite3_io_methods MemJournalMethods = {
106337  1,                /* iVersion */
106338  memjrnlClose,     /* xClose */
106339  memjrnlRead,      /* xRead */
106340  memjrnlWrite,     /* xWrite */
106341  memjrnlTruncate,  /* xTruncate */
106342  memjrnlSync,      /* xSync */
106343  memjrnlFileSize,  /* xFileSize */
106344  0,                /* xLock */
106345  0,                /* xUnlock */
106346  0,                /* xCheckReservedLock */
106347  0,                /* xFileControl */
106348  0,                /* xSectorSize */
106349  0,                /* xDeviceCharacteristics */
106350  0,                /* xShmMap */
106351  0,                /* xShmLock */
106352  0,                /* xShmBarrier */
106353  0,                /* xShmUnmap */
106354  0,                /* xFetch */
106355  0                 /* xUnfetch */
106356};
106357
106358/*
106359** Open a journal file.
106360**
106361** The behaviour of the journal file depends on the value of parameter
106362** nSpill. If nSpill is 0, then the journal file is always create and
106363** accessed using the underlying VFS. If nSpill is less than zero, then
106364** all content is always stored in main-memory. Finally, if nSpill is a
106365** positive value, then the journal file is initially created in-memory
106366** but may be flushed to disk later on. In this case the journal file is
106367** flushed to disk either when it grows larger than nSpill bytes in size,
106368** or when sqlite3JournalCreate() is called.
106369*/
106370SQLITE_PRIVATE int sqlite3JournalOpen(
106371  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
106372  const char *zName,         /* Name of the journal file */
106373  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
106374  int flags,                 /* Opening flags */
106375  int nSpill                 /* Bytes buffered before opening the file */
106376){
106377  MemJournal *p = (MemJournal*)pJfd;
106378
106379  assert( zName || nSpill<0 || (flags & SQLITE_OPEN_EXCLUSIVE) );
106380
106381  /* Zero the file-handle object. If nSpill was passed zero, initialize
106382  ** it using the sqlite3OsOpen() function of the underlying VFS. In this
106383  ** case none of the code in this module is executed as a result of calls
106384  ** made on the journal file-handle.  */
106385  memset(p, 0, sizeof(MemJournal));
106386  if( nSpill==0 ){
106387    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
106388  }
106389
106390  if( nSpill>0 ){
106391    p->nChunkSize = nSpill;
106392  }else{
106393    p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
106394    assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
106395  }
106396
106397  pJfd->pMethods = (const sqlite3_io_methods*)&MemJournalMethods;
106398  p->nSpill = nSpill;
106399  p->flags = flags;
106400  p->zJournal = zName;
106401  p->pVfs = pVfs;
106402  return SQLITE_OK;
106403}
106404
106405/*
106406** Open an in-memory journal file.
106407*/
106408SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
106409  sqlite3JournalOpen(0, 0, pJfd, 0, -1);
106410}
106411
106412#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
106413 || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
106414/*
106415** If the argument p points to a MemJournal structure that is not an
106416** in-memory-only journal file (i.e. is one that was opened with a +ve
106417** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying
106418** file has not yet been created, create it now.
106419*/
106420SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
106421  int rc = SQLITE_OK;
106422  MemJournal *p = (MemJournal*)pJfd;
106423  if( pJfd->pMethods==&MemJournalMethods && (
106424#ifdef SQLITE_ENABLE_ATOMIC_WRITE
106425     p->nSpill>0
106426#else
106427     /* While this appears to not be possible without ATOMIC_WRITE, the
106428     ** paths are complex, so it seems prudent to leave the test in as
106429     ** a NEVER(), in case our analysis is subtly flawed. */
106430     NEVER(p->nSpill>0)
106431#endif
106432#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
106433     || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
106434#endif
106435  )){
106436    rc = memjrnlCreateFile(p);
106437  }
106438  return rc;
106439}
106440#endif
106441
106442/*
106443** The file-handle passed as the only argument is open on a journal file.
106444** Return true if this "journal file" is currently stored in heap memory,
106445** or false otherwise.
106446*/
106447SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
106448  return p->pMethods==&MemJournalMethods;
106449}
106450
106451/*
106452** Return the number of bytes required to store a JournalFile that uses vfs
106453** pVfs to create the underlying on-disk files.
106454*/
106455SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
106456  return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
106457}
106458
106459/************** End of memjournal.c ******************************************/
106460/************** Begin file walker.c ******************************************/
106461/*
106462** 2008 August 16
106463**
106464** The author disclaims copyright to this source code.  In place of
106465** a legal notice, here is a blessing:
106466**
106467**    May you do good and not evil.
106468**    May you find forgiveness for yourself and forgive others.
106469**    May you share freely, never taking more than you give.
106470**
106471*************************************************************************
106472** This file contains routines used for walking the parser tree for
106473** an SQL statement.
106474*/
106475/* #include "sqliteInt.h" */
106476/* #include <stdlib.h> */
106477/* #include <string.h> */
106478
106479
106480#if !defined(SQLITE_OMIT_WINDOWFUNC)
106481/*
106482** Walk all expressions linked into the list of Window objects passed
106483** as the second argument.
106484*/
106485static int walkWindowList(Walker *pWalker, Window *pList, int bOneOnly){
106486  Window *pWin;
106487  for(pWin=pList; pWin; pWin=pWin->pNextWin){
106488    int rc;
106489    rc = sqlite3WalkExprList(pWalker, pWin->pOrderBy);
106490    if( rc ) return WRC_Abort;
106491    rc = sqlite3WalkExprList(pWalker, pWin->pPartition);
106492    if( rc ) return WRC_Abort;
106493    rc = sqlite3WalkExpr(pWalker, pWin->pFilter);
106494    if( rc ) return WRC_Abort;
106495    rc = sqlite3WalkExpr(pWalker, pWin->pStart);
106496    if( rc ) return WRC_Abort;
106497    rc = sqlite3WalkExpr(pWalker, pWin->pEnd);
106498    if( rc ) return WRC_Abort;
106499    if( bOneOnly ) break;
106500  }
106501  return WRC_Continue;
106502}
106503#endif
106504
106505/*
106506** Walk an expression tree.  Invoke the callback once for each node
106507** of the expression, while descending.  (In other words, the callback
106508** is invoked before visiting children.)
106509**
106510** The return value from the callback should be one of the WRC_*
106511** constants to specify how to proceed with the walk.
106512**
106513**    WRC_Continue      Continue descending down the tree.
106514**
106515**    WRC_Prune         Do not descend into child nodes, but allow
106516**                      the walk to continue with sibling nodes.
106517**
106518**    WRC_Abort         Do no more callbacks.  Unwind the stack and
106519**                      return from the top-level walk call.
106520**
106521** The return value from this routine is WRC_Abort to abandon the tree walk
106522** and WRC_Continue to continue.
106523*/
106524SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3WalkExprNN(Walker *pWalker, Expr *pExpr){
106525  int rc;
106526  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
106527  testcase( ExprHasProperty(pExpr, EP_Reduced) );
106528  while(1){
106529    rc = pWalker->xExprCallback(pWalker, pExpr);
106530    if( rc ) return rc & WRC_Abort;
106531    if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
106532      assert( pExpr->x.pList==0 || pExpr->pRight==0 );
106533      if( pExpr->pLeft && sqlite3WalkExprNN(pWalker, pExpr->pLeft) ){
106534        return WRC_Abort;
106535      }
106536      if( pExpr->pRight ){
106537        assert( !ExprHasProperty(pExpr, EP_WinFunc) );
106538        pExpr = pExpr->pRight;
106539        continue;
106540      }else if( ExprUseXSelect(pExpr) ){
106541        assert( !ExprHasProperty(pExpr, EP_WinFunc) );
106542        if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
106543      }else{
106544        if( pExpr->x.pList ){
106545          if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
106546        }
106547#ifndef SQLITE_OMIT_WINDOWFUNC
106548        if( ExprHasProperty(pExpr, EP_WinFunc) ){
106549          if( walkWindowList(pWalker, pExpr->y.pWin, 1) ) return WRC_Abort;
106550        }
106551#endif
106552      }
106553    }
106554    break;
106555  }
106556  return WRC_Continue;
106557}
106558SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
106559  return pExpr ? sqlite3WalkExprNN(pWalker,pExpr) : WRC_Continue;
106560}
106561
106562/*
106563** Call sqlite3WalkExpr() for every expression in list p or until
106564** an abort request is seen.
106565*/
106566SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
106567  int i;
106568  struct ExprList_item *pItem;
106569  if( p ){
106570    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
106571      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
106572    }
106573  }
106574  return WRC_Continue;
106575}
106576
106577/*
106578** This is a no-op callback for Walker->xSelectCallback2.  If this
106579** callback is set, then the Select->pWinDefn list is traversed.
106580*/
106581SQLITE_PRIVATE void sqlite3WalkWinDefnDummyCallback(Walker *pWalker, Select *p){
106582  UNUSED_PARAMETER(pWalker);
106583  UNUSED_PARAMETER(p);
106584  /* No-op */
106585}
106586
106587/*
106588** Walk all expressions associated with SELECT statement p.  Do
106589** not invoke the SELECT callback on p, but do (of course) invoke
106590** any expr callbacks and SELECT callbacks that come from subqueries.
106591** Return WRC_Abort or WRC_Continue.
106592*/
106593SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
106594  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
106595  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
106596  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
106597  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
106598  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
106599  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
106600#if !defined(SQLITE_OMIT_WINDOWFUNC)
106601  if( p->pWinDefn ){
106602    Parse *pParse;
106603    if( pWalker->xSelectCallback2==sqlite3WalkWinDefnDummyCallback
106604     || ((pParse = pWalker->pParse)!=0 && IN_RENAME_OBJECT)
106605#ifndef SQLITE_OMIT_CTE
106606     || pWalker->xSelectCallback2==sqlite3SelectPopWith
106607#endif
106608    ){
106609      /* The following may return WRC_Abort if there are unresolvable
106610      ** symbols (e.g. a table that does not exist) in a window definition. */
106611      int rc = walkWindowList(pWalker, p->pWinDefn, 0);
106612      return rc;
106613    }
106614  }
106615#endif
106616  return WRC_Continue;
106617}
106618
106619/*
106620** Walk the parse trees associated with all subqueries in the
106621** FROM clause of SELECT statement p.  Do not invoke the select
106622** callback on p, but do invoke it on each FROM clause subquery
106623** and on any subqueries further down in the tree.  Return
106624** WRC_Abort or WRC_Continue;
106625*/
106626SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
106627  SrcList *pSrc;
106628  int i;
106629  SrcItem *pItem;
106630
106631  pSrc = p->pSrc;
106632  if( ALWAYS(pSrc) ){
106633    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
106634      if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
106635        return WRC_Abort;
106636      }
106637      if( pItem->fg.isTabFunc
106638       && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
106639      ){
106640        return WRC_Abort;
106641      }
106642    }
106643  }
106644  return WRC_Continue;
106645}
106646
106647/*
106648** Call sqlite3WalkExpr() for every expression in Select statement p.
106649** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
106650** on the compound select chain, p->pPrior.
106651**
106652** If it is not NULL, the xSelectCallback() callback is invoked before
106653** the walk of the expressions and FROM clause. The xSelectCallback2()
106654** method is invoked following the walk of the expressions and FROM clause,
106655** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
106656** and if the expressions and FROM clause both return WRC_Continue;
106657**
106658** Return WRC_Continue under normal conditions.  Return WRC_Abort if
106659** there is an abort request.
106660**
106661** If the Walker does not have an xSelectCallback() then this routine
106662** is a no-op returning WRC_Continue.
106663*/
106664SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
106665  int rc;
106666  if( p==0 ) return WRC_Continue;
106667  if( pWalker->xSelectCallback==0 ) return WRC_Continue;
106668  do{
106669    rc = pWalker->xSelectCallback(pWalker, p);
106670    if( rc ) return rc & WRC_Abort;
106671    if( sqlite3WalkSelectExpr(pWalker, p)
106672     || sqlite3WalkSelectFrom(pWalker, p)
106673    ){
106674      return WRC_Abort;
106675    }
106676    if( pWalker->xSelectCallback2 ){
106677      pWalker->xSelectCallback2(pWalker, p);
106678    }
106679    p = p->pPrior;
106680  }while( p!=0 );
106681  return WRC_Continue;
106682}
106683
106684/* Increase the walkerDepth when entering a subquery, and
106685** decrease when leaving the subquery.
106686*/
106687SQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker *pWalker, Select *pSelect){
106688  UNUSED_PARAMETER(pSelect);
106689  pWalker->walkerDepth++;
106690  return WRC_Continue;
106691}
106692SQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker *pWalker, Select *pSelect){
106693  UNUSED_PARAMETER(pSelect);
106694  pWalker->walkerDepth--;
106695}
106696
106697
106698/*
106699** No-op routine for the parse-tree walker.
106700**
106701** When this routine is the Walker.xExprCallback then expression trees
106702** are walked without any actions being taken at each node.  Presumably,
106703** when this routine is used for Walker.xExprCallback then
106704** Walker.xSelectCallback is set to do something useful for every
106705** subquery in the parser tree.
106706*/
106707SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
106708  UNUSED_PARAMETER2(NotUsed, NotUsed2);
106709  return WRC_Continue;
106710}
106711
106712/*
106713** No-op routine for the parse-tree walker for SELECT statements.
106714** subquery in the parser tree.
106715*/
106716SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
106717  UNUSED_PARAMETER2(NotUsed, NotUsed2);
106718  return WRC_Continue;
106719}
106720
106721/************** End of walker.c **********************************************/
106722/************** Begin file resolve.c *****************************************/
106723/*
106724** 2008 August 18
106725**
106726** The author disclaims copyright to this source code.  In place of
106727** a legal notice, here is a blessing:
106728**
106729**    May you do good and not evil.
106730**    May you find forgiveness for yourself and forgive others.
106731**    May you share freely, never taking more than you give.
106732**
106733*************************************************************************
106734**
106735** This file contains routines used for walking the parser tree and
106736** resolve all identifiers by associating them with a particular
106737** table and column.
106738*/
106739/* #include "sqliteInt.h" */
106740
106741/*
106742** Magic table number to mean the EXCLUDED table in an UPSERT statement.
106743*/
106744#define EXCLUDED_TABLE_NUMBER  2
106745
106746/*
106747** Walk the expression tree pExpr and increase the aggregate function
106748** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
106749** This needs to occur when copying a TK_AGG_FUNCTION node from an
106750** outer query into an inner subquery.
106751**
106752** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
106753** is a helper function - a callback for the tree walker.
106754**
106755** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c
106756*/
106757static int incrAggDepth(Walker *pWalker, Expr *pExpr){
106758  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
106759  return WRC_Continue;
106760}
106761static void incrAggFunctionDepth(Expr *pExpr, int N){
106762  if( N>0 ){
106763    Walker w;
106764    memset(&w, 0, sizeof(w));
106765    w.xExprCallback = incrAggDepth;
106766    w.u.n = N;
106767    sqlite3WalkExpr(&w, pExpr);
106768  }
106769}
106770
106771/*
106772** Turn the pExpr expression into an alias for the iCol-th column of the
106773** result set in pEList.
106774**
106775** If the reference is followed by a COLLATE operator, then make sure
106776** the COLLATE operator is preserved.  For example:
106777**
106778**     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
106779**
106780** Should be transformed into:
106781**
106782**     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
106783**
106784** The nSubquery parameter specifies how many levels of subquery the
106785** alias is removed from the original expression.  The usual value is
106786** zero but it might be more if the alias is contained within a subquery
106787** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
106788** structures must be increased by the nSubquery amount.
106789*/
106790static void resolveAlias(
106791  Parse *pParse,         /* Parsing context */
106792  ExprList *pEList,      /* A result set */
106793  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
106794  Expr *pExpr,           /* Transform this into an alias to the result set */
106795  int nSubquery          /* Number of subqueries that the label is moving */
106796){
106797  Expr *pOrig;           /* The iCol-th column of the result set */
106798  Expr *pDup;            /* Copy of pOrig */
106799  sqlite3 *db;           /* The database connection */
106800
106801  assert( iCol>=0 && iCol<pEList->nExpr );
106802  pOrig = pEList->a[iCol].pExpr;
106803  assert( pOrig!=0 );
106804  assert( !ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) );
106805  if( pExpr->pAggInfo ) return;
106806  db = pParse->db;
106807  pDup = sqlite3ExprDup(db, pOrig, 0);
106808  if( db->mallocFailed ){
106809    sqlite3ExprDelete(db, pDup);
106810    pDup = 0;
106811  }else{
106812    Expr temp;
106813    incrAggFunctionDepth(pDup, nSubquery);
106814    if( pExpr->op==TK_COLLATE ){
106815      assert( !ExprHasProperty(pExpr, EP_IntValue) );
106816      pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
106817    }
106818    memcpy(&temp, pDup, sizeof(Expr));
106819    memcpy(pDup, pExpr, sizeof(Expr));
106820    memcpy(pExpr, &temp, sizeof(Expr));
106821    if( ExprHasProperty(pExpr, EP_WinFunc) ){
106822      if( ALWAYS(pExpr->y.pWin!=0) ){
106823        pExpr->y.pWin->pOwner = pExpr;
106824      }
106825    }
106826    sqlite3ExprDeferredDelete(pParse, pDup);
106827  }
106828}
106829
106830/*
106831** Subqueries store the original database, table and column names for their
106832** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN",
106833** and mark the expression-list item by setting ExprList.a[].fg.eEName
106834** to ENAME_TAB.
106835**
106836** Check to see if the zSpan/eEName of the expression-list item passed to this
106837** routine matches the zDb, zTab, and zCol.  If any of zDb, zTab, and zCol are
106838** NULL then those fields will match anything. Return true if there is a match,
106839** or false otherwise.
106840**
106841** SF_NestedFrom subqueries also store an entry for the implicit rowid (or
106842** _rowid_, or oid) column by setting ExprList.a[].fg.eEName to ENAME_ROWID,
106843** and setting zSpan to "DATABASE.TABLE.<rowid-alias>". This type of pItem
106844** argument matches if zCol is a rowid alias. If it is not NULL, (*pbRowid)
106845** is set to 1 if there is this kind of match.
106846*/
106847SQLITE_PRIVATE int sqlite3MatchEName(
106848  const struct ExprList_item *pItem,
106849  const char *zCol,
106850  const char *zTab,
106851  const char *zDb,
106852  int *pbRowid
106853){
106854  int n;
106855  const char *zSpan;
106856  int eEName = pItem->fg.eEName;
106857  if( eEName!=ENAME_TAB && (eEName!=ENAME_ROWID || NEVER(pbRowid==0)) ){
106858    return 0;
106859  }
106860  assert( pbRowid==0 || *pbRowid==0 );
106861  zSpan = pItem->zEName;
106862  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
106863  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
106864    return 0;
106865  }
106866  zSpan += n+1;
106867  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
106868  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
106869    return 0;
106870  }
106871  zSpan += n+1;
106872  if( zCol ){
106873    if( eEName==ENAME_TAB && sqlite3StrICmp(zSpan, zCol)!=0 ) return 0;
106874    if( eEName==ENAME_ROWID && sqlite3IsRowid(zCol)==0 ) return 0;
106875  }
106876  if( eEName==ENAME_ROWID ) *pbRowid = 1;
106877  return 1;
106878}
106879
106880/*
106881** Return TRUE if the double-quoted string  mis-feature should be supported.
106882*/
106883static int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){
106884  if( db->init.busy ) return 1;  /* Always support for legacy schemas */
106885  if( pTopNC->ncFlags & NC_IsDDL ){
106886    /* Currently parsing a DDL statement */
106887    if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){
106888      return 1;
106889    }
106890    return (db->flags & SQLITE_DqsDDL)!=0;
106891  }else{
106892    /* Currently parsing a DML statement */
106893    return (db->flags & SQLITE_DqsDML)!=0;
106894  }
106895}
106896
106897/*
106898** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
106899** return the appropriate colUsed mask.
106900*/
106901SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr *pExpr){
106902  int n;
106903  Table *pExTab;
106904
106905  n = pExpr->iColumn;
106906  assert( ExprUseYTab(pExpr) );
106907  pExTab = pExpr->y.pTab;
106908  assert( pExTab!=0 );
106909  assert( n < pExTab->nCol );
106910  if( (pExTab->tabFlags & TF_HasGenerated)!=0
106911   && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0
106912  ){
106913    testcase( pExTab->nCol==BMS-1 );
106914    testcase( pExTab->nCol==BMS );
106915    return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1;
106916  }else{
106917    testcase( n==BMS-1 );
106918    testcase( n==BMS );
106919    if( n>=BMS ) n = BMS-1;
106920    return ((Bitmask)1)<<n;
106921  }
106922}
106923
106924/*
106925** Create a new expression term for the column specified by pMatch and
106926** iColumn.  Append this new expression term to the FULL JOIN Match set
106927** in *ppList.  Create a new *ppList if this is the first term in the
106928** set.
106929*/
106930static void extendFJMatch(
106931  Parse *pParse,          /* Parsing context */
106932  ExprList **ppList,      /* ExprList to extend */
106933  SrcItem *pMatch,        /* Source table containing the column */
106934  i16 iColumn             /* The column number */
106935){
106936  Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
106937  if( pNew ){
106938    pNew->iTable = pMatch->iCursor;
106939    pNew->iColumn = iColumn;
106940    pNew->y.pTab = pMatch->pTab;
106941    assert( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 );
106942    ExprSetProperty(pNew, EP_CanBeNull);
106943    *ppList = sqlite3ExprListAppend(pParse, *ppList, pNew);
106944  }
106945}
106946
106947/*
106948** Return TRUE (non-zero) if zTab is a valid name for the schema table pTab.
106949*/
106950static SQLITE_NOINLINE int isValidSchemaTableName(
106951  const char *zTab,         /* Name as it appears in the SQL */
106952  Table *pTab,              /* The schema table we are trying to match */
106953  Schema *pSchema           /* non-NULL if a database qualifier is present */
106954){
106955  const char *zLegacy;
106956  assert( pTab!=0 );
106957  assert( pTab->tnum==1 );
106958  if( sqlite3StrNICmp(zTab, "sqlite_", 7)!=0 ) return 0;
106959  zLegacy = pTab->zName;
106960  if( strcmp(zLegacy+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
106961    if( sqlite3StrICmp(zTab+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
106962      return 1;
106963    }
106964    if( pSchema==0 ) return 0;
106965    if( sqlite3StrICmp(zTab+7, &LEGACY_SCHEMA_TABLE[7])==0 ) return 1;
106966    if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1;
106967  }else{
106968    if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1;
106969  }
106970  return 0;
106971}
106972
106973/*
106974** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
106975** that name in the set of source tables in pSrcList and make the pExpr
106976** expression node refer back to that source column.  The following changes
106977** are made to pExpr:
106978**
106979**    pExpr->iDb           Set the index in db->aDb[] of the database X
106980**                         (even if X is implied).
106981**    pExpr->iTable        Set to the cursor number for the table obtained
106982**                         from pSrcList.
106983**    pExpr->y.pTab        Points to the Table structure of X.Y (even if
106984**                         X and/or Y are implied.)
106985**    pExpr->iColumn       Set to the column number within the table.
106986**    pExpr->op            Set to TK_COLUMN.
106987**    pExpr->pLeft         Any expression this points to is deleted
106988**    pExpr->pRight        Any expression this points to is deleted.
106989**
106990** The zDb variable is the name of the database (the "X").  This value may be
106991** NULL meaning that name is of the form Y.Z or Z.  Any available database
106992** can be used.  The zTable variable is the name of the table (the "Y").  This
106993** value can be NULL if zDb is also NULL.  If zTable is NULL it
106994** means that the form of the name is Z and that columns from any table
106995** can be used.
106996**
106997** If the name cannot be resolved unambiguously, leave an error message
106998** in pParse and return WRC_Abort.  Return WRC_Prune on success.
106999*/
107000static int lookupName(
107001  Parse *pParse,       /* The parsing context */
107002  const char *zDb,     /* Name of the database containing table, or NULL */
107003  const char *zTab,    /* Name of table containing column, or NULL */
107004  const Expr *pRight,  /* Name of the column. */
107005  NameContext *pNC,    /* The name context used to resolve the name */
107006  Expr *pExpr          /* Make this EXPR node point to the selected column */
107007){
107008  int i, j;                         /* Loop counters */
107009  int cnt = 0;                      /* Number of matching column names */
107010  int cntTab = 0;                   /* Number of potential "rowid" matches */
107011  int nSubquery = 0;                /* How many levels of subquery */
107012  sqlite3 *db = pParse->db;         /* The database connection */
107013  SrcItem *pItem;                   /* Use for looping over pSrcList items */
107014  SrcItem *pMatch = 0;              /* The matching pSrcList item */
107015  NameContext *pTopNC = pNC;        /* First namecontext in the list */
107016  Schema *pSchema = 0;              /* Schema of the expression */
107017  int eNewExprOp = TK_COLUMN;       /* New value for pExpr->op on success */
107018  Table *pTab = 0;                  /* Table holding the row */
107019  Column *pCol;                     /* A column of pTab */
107020  ExprList *pFJMatch = 0;           /* Matches for FULL JOIN .. USING */
107021  const char *zCol = pRight->u.zToken;
107022
107023  assert( pNC );     /* the name context cannot be NULL. */
107024  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
107025  assert( zDb==0 || zTab!=0 );
107026  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
107027
107028  /* Initialize the node to no-match */
107029  pExpr->iTable = -1;
107030  ExprSetVVAProperty(pExpr, EP_NoReduce);
107031
107032  /* Translate the schema name in zDb into a pointer to the corresponding
107033  ** schema.  If not found, pSchema will remain NULL and nothing will match
107034  ** resulting in an appropriate error message toward the end of this routine
107035  */
107036  if( zDb ){
107037    testcase( pNC->ncFlags & NC_PartIdx );
107038    testcase( pNC->ncFlags & NC_IsCheck );
107039    if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
107040      /* Silently ignore database qualifiers inside CHECK constraints and
107041      ** partial indices.  Do not raise errors because that might break
107042      ** legacy and because it does not hurt anything to just ignore the
107043      ** database name. */
107044      zDb = 0;
107045    }else{
107046      for(i=0; i<db->nDb; i++){
107047        assert( db->aDb[i].zDbSName );
107048        if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
107049          pSchema = db->aDb[i].pSchema;
107050          break;
107051        }
107052      }
107053      if( i==db->nDb && sqlite3StrICmp("main", zDb)==0 ){
107054        /* This branch is taken when the main database has been renamed
107055        ** using SQLITE_DBCONFIG_MAINDBNAME. */
107056        pSchema = db->aDb[0].pSchema;
107057        zDb = db->aDb[0].zDbSName;
107058      }
107059    }
107060  }
107061
107062  /* Start at the inner-most context and move outward until a match is found */
107063  assert( pNC && cnt==0 );
107064  do{
107065    ExprList *pEList;
107066    SrcList *pSrcList = pNC->pSrcList;
107067
107068    if( pSrcList ){
107069      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
107070        u8 hCol;
107071        pTab = pItem->pTab;
107072        assert( pTab!=0 && pTab->zName!=0 );
107073        assert( pTab->nCol>0 || pParse->nErr );
107074        assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
107075        if( pItem->fg.isNestedFrom ){
107076          /* In this case, pItem is a subquery that has been formed from a
107077          ** parenthesized subset of the FROM clause terms.  Example:
107078          **   .... FROM t1 LEFT JOIN (t2 RIGHT JOIN t3 USING(x)) USING(y) ...
107079          **                          \_________________________/
107080          **             This pItem -------------^
107081          */
107082          int hit = 0;
107083          assert( pItem->pSelect!=0 );
107084          pEList = pItem->pSelect->pEList;
107085          assert( pEList!=0 );
107086          assert( pEList->nExpr==pTab->nCol );
107087          for(j=0; j<pEList->nExpr; j++){
107088            int bRowid = 0;       /* True if possible rowid match */
107089            if( !sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb, &bRowid) ){
107090              continue;
107091            }
107092            if( bRowid==0 ){
107093              if( cnt>0 ){
107094                if( pItem->fg.isUsing==0
107095                 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
107096                ){
107097                  /* Two or more tables have the same column name which is
107098                  ** not joined by USING.  This is an error.  Signal as much
107099                  ** by clearing pFJMatch and letting cnt go above 1. */
107100                  sqlite3ExprListDelete(db, pFJMatch);
107101                  pFJMatch = 0;
107102                }else
107103                if( (pItem->fg.jointype & JT_RIGHT)==0 ){
107104                  /* An INNER or LEFT JOIN.  Use the left-most table */
107105                  continue;
107106                }else
107107                if( (pItem->fg.jointype & JT_LEFT)==0 ){
107108                  /* A RIGHT JOIN.  Use the right-most table */
107109                  cnt = 0;
107110                  sqlite3ExprListDelete(db, pFJMatch);
107111                  pFJMatch = 0;
107112                }else{
107113                  /* For a FULL JOIN, we must construct a coalesce() func */
107114                  extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
107115                }
107116              }
107117              cnt++;
107118              hit = 1;
107119            }else if( cnt>0 ){
107120              /* This is a potential rowid match, but there has already been
107121              ** a real match found. So this can be ignored.  */
107122              continue;
107123            }
107124            cntTab++;
107125            pMatch = pItem;
107126            pExpr->iColumn = j;
107127            pEList->a[j].fg.bUsed = 1;
107128
107129            /* rowid cannot be part of a USING clause - assert() this. */
107130            assert( bRowid==0 || pEList->a[j].fg.bUsingTerm==0 );
107131            if( pEList->a[j].fg.bUsingTerm ) break;
107132          }
107133          if( hit || zTab==0 ) continue;
107134        }
107135        assert( zDb==0 || zTab!=0 );
107136        if( zTab ){
107137          if( zDb ){
107138            if( pTab->pSchema!=pSchema ) continue;
107139            if( pSchema==0 && strcmp(zDb,"*")!=0 ) continue;
107140          }
107141          if( pItem->zAlias!=0 ){
107142            if( sqlite3StrICmp(zTab, pItem->zAlias)!=0 ){
107143              continue;
107144            }
107145          }else if( sqlite3StrICmp(zTab, pTab->zName)!=0 ){
107146            if( pTab->tnum!=1 ) continue;
107147            if( !isValidSchemaTableName(zTab, pTab, pSchema) ) continue;
107148          }
107149          assert( ExprUseYTab(pExpr) );
107150          if( IN_RENAME_OBJECT && pItem->zAlias ){
107151            sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
107152          }
107153        }
107154        hCol = sqlite3StrIHash(zCol);
107155        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
107156          if( pCol->hName==hCol
107157           && sqlite3StrICmp(pCol->zCnName, zCol)==0
107158          ){
107159            if( cnt>0 ){
107160              if( pItem->fg.isUsing==0
107161               || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
107162              ){
107163                /* Two or more tables have the same column name which is
107164                ** not joined by USING.  This is an error.  Signal as much
107165                ** by clearing pFJMatch and letting cnt go above 1. */
107166                sqlite3ExprListDelete(db, pFJMatch);
107167                pFJMatch = 0;
107168              }else
107169              if( (pItem->fg.jointype & JT_RIGHT)==0 ){
107170                /* An INNER or LEFT JOIN.  Use the left-most table */
107171                continue;
107172              }else
107173              if( (pItem->fg.jointype & JT_LEFT)==0 ){
107174                /* A RIGHT JOIN.  Use the right-most table */
107175                cnt = 0;
107176                sqlite3ExprListDelete(db, pFJMatch);
107177                pFJMatch = 0;
107178              }else{
107179                /* For a FULL JOIN, we must construct a coalesce() func */
107180                extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
107181              }
107182            }
107183            cnt++;
107184            pMatch = pItem;
107185            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
107186            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
107187            if( pItem->fg.isNestedFrom ){
107188              sqlite3SrcItemColumnUsed(pItem, j);
107189            }
107190            break;
107191          }
107192        }
107193        if( 0==cnt && VisibleRowid(pTab) ){
107194          /* pTab is a potential ROWID match.  Keep track of it and match
107195          ** the ROWID later if that seems appropriate.  (Search for "cntTab"
107196          ** to find related code.)  Only allow a ROWID match if there is
107197          ** a single ROWID match candidate.
107198          */
107199#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
107200          /* In SQLITE_ALLOW_ROWID_IN_VIEW mode, allow a ROWID match
107201          ** if there is a single VIEW candidate or if there is a single
107202          ** non-VIEW candidate plus multiple VIEW candidates.  In other
107203          ** words non-VIEW candidate terms take precedence over VIEWs.
107204          */
107205          if( cntTab==0
107206           || (cntTab==1
107207               && ALWAYS(pMatch!=0)
107208               && ALWAYS(pMatch->pTab!=0)
107209               && (pMatch->pTab->tabFlags & TF_Ephemeral)!=0
107210               && (pTab->tabFlags & TF_Ephemeral)==0)
107211          ){
107212            cntTab = 1;
107213            pMatch = pItem;
107214          }else{
107215            cntTab++;
107216          }
107217#else
107218          /* The (much more common) non-SQLITE_ALLOW_ROWID_IN_VIEW case is
107219          ** simpler since we require exactly one candidate, which will
107220          ** always be a non-VIEW
107221          */
107222          cntTab++;
107223          pMatch = pItem;
107224#endif
107225        }
107226      }
107227      if( pMatch ){
107228        pExpr->iTable = pMatch->iCursor;
107229        assert( ExprUseYTab(pExpr) );
107230        pExpr->y.pTab = pMatch->pTab;
107231        if( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 ){
107232          ExprSetProperty(pExpr, EP_CanBeNull);
107233        }
107234        pSchema = pExpr->y.pTab->pSchema;
107235      }
107236    } /* if( pSrcList ) */
107237
107238#if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
107239    /* If we have not already resolved the name, then maybe
107240    ** it is a new.* or old.* trigger argument reference.  Or
107241    ** maybe it is an excluded.* from an upsert.  Or maybe it is
107242    ** a reference in the RETURNING clause to a table being modified.
107243    */
107244    if( cnt==0 && zDb==0 ){
107245      pTab = 0;
107246#ifndef SQLITE_OMIT_TRIGGER
107247      if( pParse->pTriggerTab!=0 ){
107248        int op = pParse->eTriggerOp;
107249        assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
107250        if( pParse->bReturning ){
107251          if( (pNC->ncFlags & NC_UBaseReg)!=0
107252           && ALWAYS(zTab==0
107253                     || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0
107254                     || isValidSchemaTableName(zTab, pParse->pTriggerTab, 0))
107255          ){
107256            pExpr->iTable = op!=TK_DELETE;
107257            pTab = pParse->pTriggerTab;
107258          }
107259        }else if( op!=TK_DELETE && zTab && sqlite3StrICmp("new",zTab) == 0 ){
107260          pExpr->iTable = 1;
107261          pTab = pParse->pTriggerTab;
107262        }else if( op!=TK_INSERT && zTab && sqlite3StrICmp("old",zTab)==0 ){
107263          pExpr->iTable = 0;
107264          pTab = pParse->pTriggerTab;
107265        }
107266      }
107267#endif /* SQLITE_OMIT_TRIGGER */
107268#ifndef SQLITE_OMIT_UPSERT
107269      if( (pNC->ncFlags & NC_UUpsert)!=0 && zTab!=0 ){
107270        Upsert *pUpsert = pNC->uNC.pUpsert;
107271        if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
107272          pTab = pUpsert->pUpsertSrc->a[0].pTab;
107273          pExpr->iTable = EXCLUDED_TABLE_NUMBER;
107274        }
107275      }
107276#endif /* SQLITE_OMIT_UPSERT */
107277
107278      if( pTab ){
107279        int iCol;
107280        u8 hCol = sqlite3StrIHash(zCol);
107281        pSchema = pTab->pSchema;
107282        cntTab++;
107283        for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
107284          if( pCol->hName==hCol
107285           && sqlite3StrICmp(pCol->zCnName, zCol)==0
107286          ){
107287            if( iCol==pTab->iPKey ){
107288              iCol = -1;
107289            }
107290            break;
107291          }
107292        }
107293        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
107294          /* IMP: R-51414-32910 */
107295          iCol = -1;
107296        }
107297        if( iCol<pTab->nCol ){
107298          cnt++;
107299          pMatch = 0;
107300#ifndef SQLITE_OMIT_UPSERT
107301          if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){
107302            testcase( iCol==(-1) );
107303            assert( ExprUseYTab(pExpr) );
107304            if( IN_RENAME_OBJECT ){
107305              pExpr->iColumn = iCol;
107306              pExpr->y.pTab = pTab;
107307              eNewExprOp = TK_COLUMN;
107308            }else{
107309              pExpr->iTable = pNC->uNC.pUpsert->regData +
107310                 sqlite3TableColumnToStorage(pTab, iCol);
107311              eNewExprOp = TK_REGISTER;
107312            }
107313          }else
107314#endif /* SQLITE_OMIT_UPSERT */
107315          {
107316            assert( ExprUseYTab(pExpr) );
107317            pExpr->y.pTab = pTab;
107318            if( pParse->bReturning ){
107319              eNewExprOp = TK_REGISTER;
107320              pExpr->op2 = TK_COLUMN;
107321              pExpr->iColumn = iCol;
107322              pExpr->iTable = pNC->uNC.iBaseReg + (pTab->nCol+1)*pExpr->iTable +
107323                 sqlite3TableColumnToStorage(pTab, iCol) + 1;
107324            }else{
107325              pExpr->iColumn = (i16)iCol;
107326              eNewExprOp = TK_TRIGGER;
107327#ifndef SQLITE_OMIT_TRIGGER
107328              if( iCol<0 ){
107329                pExpr->affExpr = SQLITE_AFF_INTEGER;
107330              }else if( pExpr->iTable==0 ){
107331                testcase( iCol==31 );
107332                testcase( iCol==32 );
107333                pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
107334              }else{
107335                testcase( iCol==31 );
107336                testcase( iCol==32 );
107337                pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
107338              }
107339#endif /* SQLITE_OMIT_TRIGGER */
107340            }
107341          }
107342        }
107343      }
107344    }
107345#endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
107346
107347    /*
107348    ** Perhaps the name is a reference to the ROWID
107349    */
107350    if( cnt==0
107351     && cntTab>=1
107352     && pMatch
107353     && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
107354     && sqlite3IsRowid(zCol)
107355     && ALWAYS(VisibleRowid(pMatch->pTab) || pMatch->fg.isNestedFrom)
107356    ){
107357      cnt = cntTab;
107358#if SQLITE_ALLOW_ROWID_IN_VIEW+0==2
107359      if( pMatch->pTab!=0 && IsView(pMatch->pTab) ){
107360        eNewExprOp = TK_NULL;
107361      }
107362#endif
107363      if( pMatch->fg.isNestedFrom==0 ) pExpr->iColumn = -1;
107364      pExpr->affExpr = SQLITE_AFF_INTEGER;
107365    }
107366
107367    /*
107368    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
107369    ** might refer to an result-set alias.  This happens, for example, when
107370    ** we are resolving names in the WHERE clause of the following command:
107371    **
107372    **     SELECT a+b AS x FROM table WHERE x<10;
107373    **
107374    ** In cases like this, replace pExpr with a copy of the expression that
107375    ** forms the result set entry ("a+b" in the example) and return immediately.
107376    ** Note that the expression in the result set should have already been
107377    ** resolved by the time the WHERE clause is resolved.
107378    **
107379    ** The ability to use an output result-set column in the WHERE, GROUP BY,
107380    ** or HAVING clauses, or as part of a larger expression in the ORDER BY
107381    ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
107382    ** is supported for backwards compatibility only. Hence, we issue a warning
107383    ** on sqlite3_log() whenever the capability is used.
107384    */
107385    if( cnt==0
107386     && (pNC->ncFlags & NC_UEList)!=0
107387     && zTab==0
107388    ){
107389      pEList = pNC->uNC.pEList;
107390      assert( pEList!=0 );
107391      for(j=0; j<pEList->nExpr; j++){
107392        char *zAs = pEList->a[j].zEName;
107393        if( pEList->a[j].fg.eEName==ENAME_NAME
107394         && sqlite3_stricmp(zAs, zCol)==0
107395        ){
107396          Expr *pOrig;
107397          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
107398          assert( ExprUseXList(pExpr)==0 || pExpr->x.pList==0 );
107399          assert( ExprUseXSelect(pExpr)==0 || pExpr->x.pSelect==0 );
107400          pOrig = pEList->a[j].pExpr;
107401          if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
107402            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
107403            return WRC_Abort;
107404          }
107405          if( ExprHasProperty(pOrig, EP_Win)
107406           && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC )
107407          ){
107408            sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs);
107409            return WRC_Abort;
107410          }
107411          if( sqlite3ExprVectorSize(pOrig)!=1 ){
107412            sqlite3ErrorMsg(pParse, "row value misused");
107413            return WRC_Abort;
107414          }
107415          resolveAlias(pParse, pEList, j, pExpr, nSubquery);
107416          cnt = 1;
107417          pMatch = 0;
107418          assert( zTab==0 && zDb==0 );
107419          if( IN_RENAME_OBJECT ){
107420            sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
107421          }
107422          goto lookupname_end;
107423        }
107424      }
107425    }
107426
107427    /* Advance to the next name context.  The loop will exit when either
107428    ** we have a match (cnt>0) or when we run out of name contexts.
107429    */
107430    if( cnt ) break;
107431    pNC = pNC->pNext;
107432    nSubquery++;
107433  }while( pNC );
107434
107435
107436  /*
107437  ** If X and Y are NULL (in other words if only the column name Z is
107438  ** supplied) and the value of Z is enclosed in double-quotes, then
107439  ** Z is a string literal if it doesn't match any column names.  In that
107440  ** case, we need to return right away and not make any changes to
107441  ** pExpr.
107442  **
107443  ** Because no reference was made to outer contexts, the pNC->nRef
107444  ** fields are not changed in any context.
107445  */
107446  if( cnt==0 && zTab==0 ){
107447    assert( pExpr->op==TK_ID );
107448    if( ExprHasProperty(pExpr,EP_DblQuoted)
107449     && areDoubleQuotedStringsEnabled(db, pTopNC)
107450    ){
107451      /* If a double-quoted identifier does not match any known column name,
107452      ** then treat it as a string.
107453      **
107454      ** This hack was added in the early days of SQLite in a misguided attempt
107455      ** to be compatible with MySQL 3.x, which used double-quotes for strings.
107456      ** I now sorely regret putting in this hack. The effect of this hack is
107457      ** that misspelled identifier names are silently converted into strings
107458      ** rather than causing an error, to the frustration of countless
107459      ** programmers. To all those frustrated programmers, my apologies.
107460      **
107461      ** Someday, I hope to get rid of this hack. Unfortunately there is
107462      ** a huge amount of legacy SQL that uses it. So for now, we just
107463      ** issue a warning.
107464      */
107465      sqlite3_log(SQLITE_WARNING,
107466        "double-quoted string literal: \"%w\"", zCol);
107467#ifdef SQLITE_ENABLE_NORMALIZE
107468      sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
107469#endif
107470      pExpr->op = TK_STRING;
107471      memset(&pExpr->y, 0, sizeof(pExpr->y));
107472      return WRC_Prune;
107473    }
107474    if( sqlite3ExprIdToTrueFalse(pExpr) ){
107475      return WRC_Prune;
107476    }
107477  }
107478
107479  /*
107480  ** cnt==0 means there was not match.
107481  ** cnt>1 means there were two or more matches.
107482  **
107483  ** cnt==0 is always an error.  cnt>1 is often an error, but might
107484  ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING.
107485  */
107486  assert( pFJMatch==0 || cnt>0 );
107487  assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
107488  if( cnt!=1 ){
107489    const char *zErr;
107490    if( pFJMatch ){
107491      if( pFJMatch->nExpr==cnt-1 ){
107492        if( ExprHasProperty(pExpr,EP_Leaf) ){
107493          ExprClearProperty(pExpr,EP_Leaf);
107494        }else{
107495          sqlite3ExprDelete(db, pExpr->pLeft);
107496          pExpr->pLeft = 0;
107497          sqlite3ExprDelete(db, pExpr->pRight);
107498          pExpr->pRight = 0;
107499        }
107500        extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
107501        pExpr->op = TK_FUNCTION;
107502        pExpr->u.zToken = "coalesce";
107503        pExpr->x.pList = pFJMatch;
107504        cnt = 1;
107505        goto lookupname_end;
107506      }else{
107507        sqlite3ExprListDelete(db, pFJMatch);
107508        pFJMatch = 0;
107509      }
107510    }
107511    zErr = cnt==0 ? "no such column" : "ambiguous column name";
107512    if( zDb ){
107513      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
107514    }else if( zTab ){
107515      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
107516    }else if( cnt==0 && ExprHasProperty(pRight,EP_DblQuoted) ){
107517      sqlite3ErrorMsg(pParse, "%s: \"%s\" - should this be a"
107518                              " string literal in single-quotes?",
107519                              zErr, zCol);
107520    }else{
107521      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
107522    }
107523    sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
107524    pParse->checkSchema = 1;
107525    pTopNC->nNcErr++;
107526    eNewExprOp = TK_NULL;
107527  }
107528  assert( pFJMatch==0 );
107529
107530  /* Remove all substructure from pExpr */
107531  if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
107532    sqlite3ExprDelete(db, pExpr->pLeft);
107533    pExpr->pLeft = 0;
107534    sqlite3ExprDelete(db, pExpr->pRight);
107535    pExpr->pRight = 0;
107536    ExprSetProperty(pExpr, EP_Leaf);
107537  }
107538
107539  /* If a column from a table in pSrcList is referenced, then record
107540  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
107541  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  Bit 63 is
107542  ** set if the 63rd or any subsequent column is used.
107543  **
107544  ** The colUsed mask is an optimization used to help determine if an
107545  ** index is a covering index.  The correct answer is still obtained
107546  ** if the mask contains extra set bits.  However, it is important to
107547  ** avoid setting bits beyond the maximum column number of the table.
107548  ** (See ticket [b92e5e8ec2cdbaa1]).
107549  **
107550  ** If a generated column is referenced, set bits for every column
107551  ** of the table.
107552  */
107553  if( pMatch ){
107554    if( pExpr->iColumn>=0 ){
107555      pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
107556    }else{
107557      pMatch->fg.rowidUsed = 1;
107558    }
107559  }
107560
107561  pExpr->op = eNewExprOp;
107562lookupname_end:
107563  if( cnt==1 ){
107564    assert( pNC!=0 );
107565#ifndef SQLITE_OMIT_AUTHORIZATION
107566    if( pParse->db->xAuth
107567     && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER)
107568    ){
107569      sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
107570    }
107571#endif
107572    /* Increment the nRef value on all name contexts from TopNC up to
107573    ** the point where the name matched. */
107574    for(;;){
107575      assert( pTopNC!=0 );
107576      pTopNC->nRef++;
107577      if( pTopNC==pNC ) break;
107578      pTopNC = pTopNC->pNext;
107579    }
107580    return WRC_Prune;
107581  } else {
107582    return WRC_Abort;
107583  }
107584}
107585
107586/*
107587** Allocate and return a pointer to an expression to load the column iCol
107588** from datasource iSrc in SrcList pSrc.
107589*/
107590SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
107591  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
107592  if( p ){
107593    SrcItem *pItem = &pSrc->a[iSrc];
107594    Table *pTab;
107595    assert( ExprUseYTab(p) );
107596    pTab = p->y.pTab = pItem->pTab;
107597    p->iTable = pItem->iCursor;
107598    if( p->y.pTab->iPKey==iCol ){
107599      p->iColumn = -1;
107600    }else{
107601      p->iColumn = (ynVar)iCol;
107602      if( (pTab->tabFlags & TF_HasGenerated)!=0
107603       && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0
107604      ){
107605        testcase( pTab->nCol==63 );
107606        testcase( pTab->nCol==64 );
107607        pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;
107608      }else{
107609        testcase( iCol==BMS );
107610        testcase( iCol==BMS-1 );
107611        pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
107612      }
107613    }
107614  }
107615  return p;
107616}
107617
107618/*
107619** Report an error that an expression is not valid for some set of
107620** pNC->ncFlags values determined by validMask.
107621**
107622** static void notValid(
107623**   Parse *pParse,       // Leave error message here
107624**   NameContext *pNC,    // The name context
107625**   const char *zMsg,    // Type of error
107626**   int validMask,       // Set of contexts for which prohibited
107627**   Expr *pExpr          // Invalidate this expression on error
107628** ){...}
107629**
107630** As an optimization, since the conditional is almost always false
107631** (because errors are rare), the conditional is moved outside of the
107632** function call using a macro.
107633*/
107634static void notValidImpl(
107635   Parse *pParse,       /* Leave error message here */
107636   NameContext *pNC,    /* The name context */
107637   const char *zMsg,    /* Type of error */
107638   Expr *pExpr,         /* Invalidate this expression on error */
107639   Expr *pError         /* Associate error with this expression */
107640){
107641  const char *zIn = "partial index WHERE clauses";
107642  if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
107643#ifndef SQLITE_OMIT_CHECK
107644  else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
107645#endif
107646#ifndef SQLITE_OMIT_GENERATED_COLUMNS
107647  else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
107648#endif
107649  sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
107650  if( pExpr ) pExpr->op = TK_NULL;
107651  sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
107652}
107653#define sqlite3ResolveNotValid(P,N,M,X,E,R) \
107654  assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
107655  if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
107656
107657/*
107658** Expression p should encode a floating point value between 1.0 and 0.0.
107659** Return 1024 times this value.  Or return -1 if p is not a floating point
107660** value between 1.0 and 0.0.
107661*/
107662static int exprProbability(Expr *p){
107663  double r = -1.0;
107664  if( p->op!=TK_FLOAT ) return -1;
107665  assert( !ExprHasProperty(p, EP_IntValue) );
107666  sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
107667  assert( r>=0.0 );
107668  if( r>1.0 ) return -1;
107669  return (int)(r*134217728.0);
107670}
107671
107672/*
107673** This routine is callback for sqlite3WalkExpr().
107674**
107675** Resolve symbolic names into TK_COLUMN operators for the current
107676** node in the expression tree.  Return 0 to continue the search down
107677** the tree or 2 to abort the tree walk.
107678**
107679** This routine also does error checking and name resolution for
107680** function names.  The operator for aggregate functions is changed
107681** to TK_AGG_FUNCTION.
107682*/
107683static int resolveExprStep(Walker *pWalker, Expr *pExpr){
107684  NameContext *pNC;
107685  Parse *pParse;
107686
107687  pNC = pWalker->u.pNC;
107688  assert( pNC!=0 );
107689  pParse = pNC->pParse;
107690  assert( pParse==pWalker->pParse );
107691
107692#ifndef NDEBUG
107693  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
107694    SrcList *pSrcList = pNC->pSrcList;
107695    int i;
107696    for(i=0; i<pNC->pSrcList->nSrc; i++){
107697      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
107698    }
107699  }
107700#endif
107701  switch( pExpr->op ){
107702
107703    /* The special operator TK_ROW means use the rowid for the first
107704    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
107705    ** clause processing on UPDATE and DELETE statements, and by
107706    ** UPDATE ... FROM statement processing.
107707    */
107708    case TK_ROW: {
107709      SrcList *pSrcList = pNC->pSrcList;
107710      SrcItem *pItem;
107711      assert( pSrcList && pSrcList->nSrc>=1 );
107712      pItem = pSrcList->a;
107713      pExpr->op = TK_COLUMN;
107714      assert( ExprUseYTab(pExpr) );
107715      pExpr->y.pTab = pItem->pTab;
107716      pExpr->iTable = pItem->iCursor;
107717      pExpr->iColumn--;
107718      pExpr->affExpr = SQLITE_AFF_INTEGER;
107719      break;
107720    }
107721
107722    /* An optimization:  Attempt to convert
107723    **
107724    **      "expr IS NOT NULL"  -->  "TRUE"
107725    **      "expr IS NULL"      -->  "FALSE"
107726    **
107727    ** if we can prove that "expr" is never NULL.  Call this the
107728    ** "NOT NULL strength reduction optimization".
107729    **
107730    ** If this optimization occurs, also restore the NameContext ref-counts
107731    ** to the state they where in before the "column" LHS expression was
107732    ** resolved.  This prevents "column" from being counted as having been
107733    ** referenced, which might prevent a SELECT from being erroneously
107734    ** marked as correlated.
107735    **
107736    ** 2024-03-28: Beware of aggregates.  A bare column of aggregated table
107737    ** can still evaluate to NULL even though it is marked as NOT NULL.
107738    ** Example:
107739    **
107740    **       CREATE TABLE t1(a INT NOT NULL);
107741    **       SELECT a, a IS NULL, a IS NOT NULL, count(*) FROM t1;
107742    **
107743    ** The "a IS NULL" and "a IS NOT NULL" expressions cannot be optimized
107744    ** here because at the time this case is hit, we do not yet know whether
107745    ** or not t1 is being aggregated.  We have to assume the worst and omit
107746    ** the optimization.  The only time it is safe to apply this optimization
107747    ** is within the WHERE clause.
107748    */
107749    case TK_NOTNULL:
107750    case TK_ISNULL: {
107751      int anRef[8];
107752      NameContext *p;
107753      int i;
107754      for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
107755        anRef[i] = p->nRef;
107756      }
107757      sqlite3WalkExpr(pWalker, pExpr->pLeft);
107758      if( IN_RENAME_OBJECT ) return WRC_Prune;
107759      if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
107760        /* The expression can be NULL.  So the optimization does not apply */
107761        return WRC_Prune;
107762      }
107763
107764      for(i=0, p=pNC; p; p=p->pNext, i++){
107765        if( (p->ncFlags & NC_Where)==0 ){
107766          return WRC_Prune;  /* Not in a WHERE clause.  Unsafe to optimize. */
107767        }
107768      }
107769      testcase( ExprHasProperty(pExpr, EP_OuterON) );
107770      assert( !ExprHasProperty(pExpr, EP_IntValue) );
107771#if TREETRACE_ENABLED
107772      if( sqlite3TreeTrace & 0x80000 ){
107773        sqlite3DebugPrintf(
107774           "NOT NULL strength reduction converts the following to %d:\n",
107775           pExpr->op==TK_NOTNULL
107776        );
107777        sqlite3ShowExpr(pExpr);
107778      }
107779#endif /* TREETRACE_ENABLED */
107780      pExpr->u.iValue = (pExpr->op==TK_NOTNULL);
107781      pExpr->flags |= EP_IntValue;
107782      pExpr->op = TK_INTEGER;
107783      for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
107784        p->nRef = anRef[i];
107785      }
107786      sqlite3ExprDelete(pParse->db, pExpr->pLeft);
107787      pExpr->pLeft = 0;
107788      return WRC_Prune;
107789    }
107790
107791    /* A column name:                    ID
107792    ** Or table name and column name:    ID.ID
107793    ** Or a database, table and column:  ID.ID.ID
107794    **
107795    ** The TK_ID and TK_OUT cases are combined so that there will only
107796    ** be one call to lookupName().  Then the compiler will in-line
107797    ** lookupName() for a size reduction and performance increase.
107798    */
107799    case TK_ID:
107800    case TK_DOT: {
107801      const char *zTable;
107802      const char *zDb;
107803      Expr *pRight;
107804
107805      if( pExpr->op==TK_ID ){
107806        zDb = 0;
107807        zTable = 0;
107808        assert( !ExprHasProperty(pExpr, EP_IntValue) );
107809        pRight = pExpr;
107810      }else{
107811        Expr *pLeft = pExpr->pLeft;
107812        testcase( pNC->ncFlags & NC_IdxExpr );
107813        testcase( pNC->ncFlags & NC_GenCol );
107814        sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator",
107815                               NC_IdxExpr|NC_GenCol, 0, pExpr);
107816        pRight = pExpr->pRight;
107817        if( pRight->op==TK_ID ){
107818          zDb = 0;
107819        }else{
107820          assert( pRight->op==TK_DOT );
107821          assert( !ExprHasProperty(pRight, EP_IntValue) );
107822          zDb = pLeft->u.zToken;
107823          pLeft = pRight->pLeft;
107824          pRight = pRight->pRight;
107825        }
107826        assert( ExprUseUToken(pLeft) && ExprUseUToken(pRight) );
107827        zTable = pLeft->u.zToken;
107828        assert( ExprUseYTab(pExpr) );
107829        if( IN_RENAME_OBJECT ){
107830          sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
107831          sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
107832        }
107833      }
107834      return lookupName(pParse, zDb, zTable, pRight, pNC, pExpr);
107835    }
107836
107837    /* Resolve function names
107838    */
107839    case TK_FUNCTION: {
107840      ExprList *pList = pExpr->x.pList;    /* The argument list */
107841      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
107842      int no_such_func = 0;       /* True if no such function exists */
107843      int wrong_num_args = 0;     /* True if wrong number of arguments */
107844      int is_agg = 0;             /* True if is an aggregate function */
107845      const char *zId;            /* The function name. */
107846      FuncDef *pDef;              /* Information about the function */
107847      u8 enc = ENC(pParse->db);   /* The database encoding */
107848      int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
107849#ifndef SQLITE_OMIT_WINDOWFUNC
107850      Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
107851#endif
107852      assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
107853      assert( pExpr->pLeft==0 || pExpr->pLeft->op==TK_ORDER );
107854      zId = pExpr->u.zToken;
107855      pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
107856      if( pDef==0 ){
107857        pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
107858        if( pDef==0 ){
107859          no_such_func = 1;
107860        }else{
107861          wrong_num_args = 1;
107862        }
107863      }else{
107864        is_agg = pDef->xFinalize!=0;
107865        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
107866          ExprSetProperty(pExpr, EP_Unlikely);
107867          if( n==2 ){
107868            pExpr->iTable = exprProbability(pList->a[1].pExpr);
107869            if( pExpr->iTable<0 ){
107870              sqlite3ErrorMsg(pParse,
107871                "second argument to %#T() must be a "
107872                "constant between 0.0 and 1.0", pExpr);
107873              pNC->nNcErr++;
107874            }
107875          }else{
107876            /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
107877            ** equivalent to likelihood(X, 0.0625).
107878            ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
107879            ** short-hand for likelihood(X,0.0625).
107880            ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
107881            ** for likelihood(X,0.9375).
107882            ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
107883            ** to likelihood(X,0.9375). */
107884            /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
107885            pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
107886          }
107887        }
107888#ifndef SQLITE_OMIT_AUTHORIZATION
107889        {
107890          int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
107891          if( auth!=SQLITE_OK ){
107892            if( auth==SQLITE_DENY ){
107893              sqlite3ErrorMsg(pParse, "not authorized to use function: %#T",
107894                                      pExpr);
107895              pNC->nNcErr++;
107896            }
107897            pExpr->op = TK_NULL;
107898            return WRC_Prune;
107899          }
107900        }
107901#endif
107902        if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
107903          /* For the purposes of the EP_ConstFunc flag, date and time
107904          ** functions and other functions that change slowly are considered
107905          ** constant because they are constant for the duration of one query.
107906          ** This allows them to be factored out of inner loops. */
107907          ExprSetProperty(pExpr,EP_ConstFunc);
107908        }
107909        if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
107910          /* Clearly non-deterministic functions like random(), but also
107911          ** date/time functions that use 'now', and other functions like
107912          ** sqlite_version() that might change over time cannot be used
107913          ** in an index or generated column.  Curiously, they can be used
107914          ** in a CHECK constraint.  SQLServer, MySQL, and PostgreSQL all
107915          ** all this. */
107916          sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
107917                                 NC_IdxExpr|NC_PartIdx|NC_GenCol, 0, pExpr);
107918        }else{
107919          assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */
107920          pExpr->op2 = pNC->ncFlags & NC_SelfRef;
107921          if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);
107922        }
107923        if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
107924         && pParse->nested==0
107925         && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0
107926        ){
107927          /* Internal-use-only functions are disallowed unless the
107928          ** SQL is being compiled using sqlite3NestedParse() or
107929          ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
107930          ** used to activate internal functions for testing purposes */
107931          no_such_func = 1;
107932          pDef = 0;
107933        }else
107934        if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0
107935         && !IN_RENAME_OBJECT
107936        ){
107937          sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
107938        }
107939      }
107940
107941      if( 0==IN_RENAME_OBJECT ){
107942#ifndef SQLITE_OMIT_WINDOWFUNC
107943        assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
107944          || (pDef->xValue==0 && pDef->xInverse==0)
107945          || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
107946        );
107947        if( pDef && pDef->xValue==0 && pWin ){
107948          sqlite3ErrorMsg(pParse,
107949              "%#T() may not be used as a window function", pExpr
107950          );
107951          pNC->nNcErr++;
107952        }else if(
107953              (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
107954           || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
107955           || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
107956        ){
107957          const char *zType;
107958          if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){
107959            zType = "window";
107960          }else{
107961            zType = "aggregate";
107962          }
107963          sqlite3ErrorMsg(pParse, "misuse of %s function %#T()",zType,pExpr);
107964          pNC->nNcErr++;
107965          is_agg = 0;
107966        }
107967#else
107968        if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
107969          sqlite3ErrorMsg(pParse,"misuse of aggregate function %#T()",pExpr);
107970          pNC->nNcErr++;
107971          is_agg = 0;
107972        }
107973#endif
107974        else if( no_such_func && pParse->db->init.busy==0
107975#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
107976                  && pParse->explain==0
107977#endif
107978        ){
107979          sqlite3ErrorMsg(pParse, "no such function: %#T", pExpr);
107980          pNC->nNcErr++;
107981        }else if( wrong_num_args ){
107982          sqlite3ErrorMsg(pParse,"wrong number of arguments to function %#T()",
107983               pExpr);
107984          pNC->nNcErr++;
107985        }
107986#ifndef SQLITE_OMIT_WINDOWFUNC
107987        else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
107988          sqlite3ErrorMsg(pParse,
107989              "FILTER may not be used with non-aggregate %#T()",
107990              pExpr
107991          );
107992          pNC->nNcErr++;
107993        }
107994#endif
107995        else if( is_agg==0 && pExpr->pLeft ){
107996          sqlite3ExprOrderByAggregateError(pParse, pExpr);
107997          pNC->nNcErr++;
107998        }
107999        if( is_agg ){
108000          /* Window functions may not be arguments of aggregate functions.
108001          ** Or arguments of other window functions. But aggregate functions
108002          ** may be arguments for window functions.  */
108003#ifndef SQLITE_OMIT_WINDOWFUNC
108004          pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
108005#else
108006          pNC->ncFlags &= ~NC_AllowAgg;
108007#endif
108008        }
108009      }
108010      else if( ExprHasProperty(pExpr, EP_WinFunc) || pExpr->pLeft ){
108011        is_agg = 1;
108012      }
108013      sqlite3WalkExprList(pWalker, pList);
108014      if( is_agg ){
108015        if( pExpr->pLeft ){
108016          assert( pExpr->pLeft->op==TK_ORDER );
108017          assert( ExprUseXList(pExpr->pLeft) );
108018          sqlite3WalkExprList(pWalker, pExpr->pLeft->x.pList);
108019        }
108020#ifndef SQLITE_OMIT_WINDOWFUNC
108021        if( pWin ){
108022          Select *pSel = pNC->pWinSelect;
108023          assert( pWin==0 || (ExprUseYWin(pExpr) && pWin==pExpr->y.pWin) );
108024          if( IN_RENAME_OBJECT==0 ){
108025            sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
108026            if( pParse->db->mallocFailed ) break;
108027          }
108028          sqlite3WalkExprList(pWalker, pWin->pPartition);
108029          sqlite3WalkExprList(pWalker, pWin->pOrderBy);
108030          sqlite3WalkExpr(pWalker, pWin->pFilter);
108031          sqlite3WindowLink(pSel, pWin);
108032          pNC->ncFlags |= NC_HasWin;
108033        }else
108034#endif /* SQLITE_OMIT_WINDOWFUNC */
108035        {
108036          NameContext *pNC2;          /* For looping up thru outer contexts */
108037          pExpr->op = TK_AGG_FUNCTION;
108038          pExpr->op2 = 0;
108039#ifndef SQLITE_OMIT_WINDOWFUNC
108040          if( ExprHasProperty(pExpr, EP_WinFunc) ){
108041            sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
108042          }
108043#endif
108044          pNC2 = pNC;
108045          while( pNC2
108046              && sqlite3ReferencesSrcList(pParse, pExpr, pNC2->pSrcList)==0
108047          ){
108048            pExpr->op2 += (1 + pNC2->nNestedSelect);
108049            pNC2 = pNC2->pNext;
108050          }
108051          assert( pDef!=0 || IN_RENAME_OBJECT );
108052          if( pNC2 && pDef ){
108053            pExpr->op2 += pNC2->nNestedSelect;
108054            assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
108055            assert( SQLITE_FUNC_ANYORDER==NC_OrderAgg );
108056            testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
108057            testcase( (pDef->funcFlags & SQLITE_FUNC_ANYORDER)!=0 );
108058            pNC2->ncFlags |= NC_HasAgg
108059              | ((pDef->funcFlags^SQLITE_FUNC_ANYORDER)
108060                  & (SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER));
108061          }
108062        }
108063        pNC->ncFlags |= savedAllowFlags;
108064      }
108065      /* FIX ME:  Compute pExpr->affinity based on the expected return
108066      ** type of the function
108067      */
108068      return WRC_Prune;
108069    }
108070#ifndef SQLITE_OMIT_SUBQUERY
108071    case TK_SELECT:
108072    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
108073#endif
108074    case TK_IN: {
108075      testcase( pExpr->op==TK_IN );
108076      if( ExprUseXSelect(pExpr) ){
108077        int nRef = pNC->nRef;
108078        testcase( pNC->ncFlags & NC_IsCheck );
108079        testcase( pNC->ncFlags & NC_PartIdx );
108080        testcase( pNC->ncFlags & NC_IdxExpr );
108081        testcase( pNC->ncFlags & NC_GenCol );
108082        assert( pExpr->x.pSelect );
108083        if( pNC->ncFlags & NC_SelfRef ){
108084          notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr);
108085        }else{
108086          sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
108087        }
108088        assert( pNC->nRef>=nRef );
108089        if( nRef!=pNC->nRef ){
108090          ExprSetProperty(pExpr, EP_VarSelect);
108091          pExpr->x.pSelect->selFlags |= SF_Correlated;
108092        }
108093        pNC->ncFlags |= NC_Subquery;
108094      }
108095      break;
108096    }
108097    case TK_VARIABLE: {
108098      testcase( pNC->ncFlags & NC_IsCheck );
108099      testcase( pNC->ncFlags & NC_PartIdx );
108100      testcase( pNC->ncFlags & NC_IdxExpr );
108101      testcase( pNC->ncFlags & NC_GenCol );
108102      sqlite3ResolveNotValid(pParse, pNC, "parameters",
108103               NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr, pExpr);
108104      break;
108105    }
108106    case TK_IS:
108107    case TK_ISNOT: {
108108      Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
108109      assert( !ExprHasProperty(pExpr, EP_Reduced) );
108110      /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
108111      ** and "x IS NOT FALSE". */
108112      if( ALWAYS(pRight) && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
108113        int rc = resolveExprStep(pWalker, pRight);
108114        if( rc==WRC_Abort ) return WRC_Abort;
108115        if( pRight->op==TK_TRUEFALSE ){
108116          pExpr->op2 = pExpr->op;
108117          pExpr->op = TK_TRUTH;
108118          return WRC_Continue;
108119        }
108120      }
108121      /* no break */ deliberate_fall_through
108122    }
108123    case TK_BETWEEN:
108124    case TK_EQ:
108125    case TK_NE:
108126    case TK_LT:
108127    case TK_LE:
108128    case TK_GT:
108129    case TK_GE: {
108130      int nLeft, nRight;
108131      if( pParse->db->mallocFailed ) break;
108132      assert( pExpr->pLeft!=0 );
108133      nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
108134      if( pExpr->op==TK_BETWEEN ){
108135        assert( ExprUseXList(pExpr) );
108136        nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
108137        if( nRight==nLeft ){
108138          nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
108139        }
108140      }else{
108141        assert( pExpr->pRight!=0 );
108142        nRight = sqlite3ExprVectorSize(pExpr->pRight);
108143      }
108144      if( nLeft!=nRight ){
108145        testcase( pExpr->op==TK_EQ );
108146        testcase( pExpr->op==TK_NE );
108147        testcase( pExpr->op==TK_LT );
108148        testcase( pExpr->op==TK_LE );
108149        testcase( pExpr->op==TK_GT );
108150        testcase( pExpr->op==TK_GE );
108151        testcase( pExpr->op==TK_IS );
108152        testcase( pExpr->op==TK_ISNOT );
108153        testcase( pExpr->op==TK_BETWEEN );
108154        sqlite3ErrorMsg(pParse, "row value misused");
108155        sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
108156      }
108157      break;
108158    }
108159  }
108160  assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
108161  return pParse->nErr ? WRC_Abort : WRC_Continue;
108162}
108163
108164/*
108165** pEList is a list of expressions which are really the result set of the
108166** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
108167** This routine checks to see if pE is a simple identifier which corresponds
108168** to the AS-name of one of the terms of the expression list.  If it is,
108169** this routine return an integer between 1 and N where N is the number of
108170** elements in pEList, corresponding to the matching entry.  If there is
108171** no match, or if pE is not a simple identifier, then this routine
108172** return 0.
108173**
108174** pEList has been resolved.  pE has not.
108175*/
108176static int resolveAsName(
108177  Parse *pParse,     /* Parsing context for error messages */
108178  ExprList *pEList,  /* List of expressions to scan */
108179  Expr *pE           /* Expression we are trying to match */
108180){
108181  int i;             /* Loop counter */
108182
108183  UNUSED_PARAMETER(pParse);
108184
108185  if( pE->op==TK_ID ){
108186    const char *zCol;
108187    assert( !ExprHasProperty(pE, EP_IntValue) );
108188    zCol = pE->u.zToken;
108189    for(i=0; i<pEList->nExpr; i++){
108190      if( pEList->a[i].fg.eEName==ENAME_NAME
108191       && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
108192      ){
108193        return i+1;
108194      }
108195    }
108196  }
108197  return 0;
108198}
108199
108200/*
108201** pE is a pointer to an expression which is a single term in the
108202** ORDER BY of a compound SELECT.  The expression has not been
108203** name resolved.
108204**
108205** At the point this routine is called, we already know that the
108206** ORDER BY term is not an integer index into the result set.  That
108207** case is handled by the calling routine.
108208**
108209** Attempt to match pE against result set columns in the left-most
108210** SELECT statement.  Return the index i of the matching column,
108211** as an indication to the caller that it should sort by the i-th column.
108212** The left-most column is 1.  In other words, the value returned is the
108213** same integer value that would be used in the SQL statement to indicate
108214** the column.
108215**
108216** If there is no match, return 0.  Return -1 if an error occurs.
108217*/
108218static int resolveOrderByTermToExprList(
108219  Parse *pParse,     /* Parsing context for error messages */
108220  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
108221  Expr *pE           /* The specific ORDER BY term */
108222){
108223  int i;             /* Loop counter */
108224  ExprList *pEList;  /* The columns of the result set */
108225  NameContext nc;    /* Name context for resolving pE */
108226  sqlite3 *db;       /* Database connection */
108227  int rc;            /* Return code from subprocedures */
108228  u8 savedSuppErr;   /* Saved value of db->suppressErr */
108229
108230  assert( sqlite3ExprIsInteger(pE, &i)==0 );
108231  pEList = pSelect->pEList;
108232
108233  /* Resolve all names in the ORDER BY term expression
108234  */
108235  memset(&nc, 0, sizeof(nc));
108236  nc.pParse = pParse;
108237  nc.pSrcList = pSelect->pSrc;
108238  nc.uNC.pEList = pEList;
108239  nc.ncFlags = NC_AllowAgg|NC_UEList|NC_NoSelect;
108240  nc.nNcErr = 0;
108241  db = pParse->db;
108242  savedSuppErr = db->suppressErr;
108243  db->suppressErr = 1;
108244  rc = sqlite3ResolveExprNames(&nc, pE);
108245  db->suppressErr = savedSuppErr;
108246  if( rc ) return 0;
108247
108248  /* Try to match the ORDER BY expression against an expression
108249  ** in the result set.  Return an 1-based index of the matching
108250  ** result-set entry.
108251  */
108252  for(i=0; i<pEList->nExpr; i++){
108253    if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
108254      return i+1;
108255    }
108256  }
108257
108258  /* If no match, return 0. */
108259  return 0;
108260}
108261
108262/*
108263** Generate an ORDER BY or GROUP BY term out-of-range error.
108264*/
108265static void resolveOutOfRangeError(
108266  Parse *pParse,         /* The error context into which to write the error */
108267  const char *zType,     /* "ORDER" or "GROUP" */
108268  int i,                 /* The index (1-based) of the term out of range */
108269  int mx,                /* Largest permissible value of i */
108270  Expr *pError           /* Associate the error with the expression */
108271){
108272  sqlite3ErrorMsg(pParse,
108273    "%r %s BY term out of range - should be "
108274    "between 1 and %d", i, zType, mx);
108275  sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
108276}
108277
108278/*
108279** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
108280** each term of the ORDER BY clause is a constant integer between 1
108281** and N where N is the number of columns in the compound SELECT.
108282**
108283** ORDER BY terms that are already an integer between 1 and N are
108284** unmodified.  ORDER BY terms that are integers outside the range of
108285** 1 through N generate an error.  ORDER BY terms that are expressions
108286** are matched against result set expressions of compound SELECT
108287** beginning with the left-most SELECT and working toward the right.
108288** At the first match, the ORDER BY expression is transformed into
108289** the integer column number.
108290**
108291** Return the number of errors seen.
108292*/
108293static int resolveCompoundOrderBy(
108294  Parse *pParse,        /* Parsing context.  Leave error messages here */
108295  Select *pSelect       /* The SELECT statement containing the ORDER BY */
108296){
108297  int i;
108298  ExprList *pOrderBy;
108299  ExprList *pEList;
108300  sqlite3 *db;
108301  int moreToDo = 1;
108302
108303  pOrderBy = pSelect->pOrderBy;
108304  if( pOrderBy==0 ) return 0;
108305  db = pParse->db;
108306  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
108307    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
108308    return 1;
108309  }
108310  for(i=0; i<pOrderBy->nExpr; i++){
108311    pOrderBy->a[i].fg.done = 0;
108312  }
108313  pSelect->pNext = 0;
108314  while( pSelect->pPrior ){
108315    pSelect->pPrior->pNext = pSelect;
108316    pSelect = pSelect->pPrior;
108317  }
108318  while( pSelect && moreToDo ){
108319    struct ExprList_item *pItem;
108320    moreToDo = 0;
108321    pEList = pSelect->pEList;
108322    assert( pEList!=0 );
108323    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
108324      int iCol = -1;
108325      Expr *pE, *pDup;
108326      if( pItem->fg.done ) continue;
108327      pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
108328      if( NEVER(pE==0) ) continue;
108329      if( sqlite3ExprIsInteger(pE, &iCol) ){
108330        if( iCol<=0 || iCol>pEList->nExpr ){
108331          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
108332          return 1;
108333        }
108334      }else{
108335        iCol = resolveAsName(pParse, pEList, pE);
108336        if( iCol==0 ){
108337          /* Now test if expression pE matches one of the values returned
108338          ** by pSelect. In the usual case this is done by duplicating the
108339          ** expression, resolving any symbols in it, and then comparing
108340          ** it against each expression returned by the SELECT statement.
108341          ** Once the comparisons are finished, the duplicate expression
108342          ** is deleted.
108343          **
108344          ** If this is running as part of an ALTER TABLE operation and
108345          ** the symbols resolve successfully, also resolve the symbols in the
108346          ** actual expression. This allows the code in alter.c to modify
108347          ** column references within the ORDER BY expression as required.  */
108348          pDup = sqlite3ExprDup(db, pE, 0);
108349          if( !db->mallocFailed ){
108350            assert(pDup);
108351            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
108352            if( IN_RENAME_OBJECT && iCol>0 ){
108353              resolveOrderByTermToExprList(pParse, pSelect, pE);
108354            }
108355          }
108356          sqlite3ExprDelete(db, pDup);
108357        }
108358      }
108359      if( iCol>0 ){
108360        /* Convert the ORDER BY term into an integer column number iCol,
108361        ** taking care to preserve the COLLATE clause if it exists. */
108362        if( !IN_RENAME_OBJECT ){
108363          Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
108364          if( pNew==0 ) return 1;
108365          pNew->flags |= EP_IntValue;
108366          pNew->u.iValue = iCol;
108367          if( pItem->pExpr==pE ){
108368            pItem->pExpr = pNew;
108369          }else{
108370            Expr *pParent = pItem->pExpr;
108371            assert( pParent->op==TK_COLLATE );
108372            while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
108373            assert( pParent->pLeft==pE );
108374            pParent->pLeft = pNew;
108375          }
108376          sqlite3ExprDelete(db, pE);
108377          pItem->u.x.iOrderByCol = (u16)iCol;
108378        }
108379        pItem->fg.done = 1;
108380      }else{
108381        moreToDo = 1;
108382      }
108383    }
108384    pSelect = pSelect->pNext;
108385  }
108386  for(i=0; i<pOrderBy->nExpr; i++){
108387    if( pOrderBy->a[i].fg.done==0 ){
108388      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
108389            "column in the result set", i+1);
108390      return 1;
108391    }
108392  }
108393  return 0;
108394}
108395
108396/*
108397** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
108398** the SELECT statement pSelect.  If any term is reference to a
108399** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
108400** field) then convert that term into a copy of the corresponding result set
108401** column.
108402**
108403** If any errors are detected, add an error message to pParse and
108404** return non-zero.  Return zero if no errors are seen.
108405*/
108406SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
108407  Parse *pParse,        /* Parsing context.  Leave error messages here */
108408  Select *pSelect,      /* The SELECT statement containing the clause */
108409  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
108410  const char *zType     /* "ORDER" or "GROUP" */
108411){
108412  int i;
108413  sqlite3 *db = pParse->db;
108414  ExprList *pEList;
108415  struct ExprList_item *pItem;
108416
108417  if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
108418  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
108419    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
108420    return 1;
108421  }
108422  pEList = pSelect->pEList;
108423  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
108424  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
108425    if( pItem->u.x.iOrderByCol ){
108426      if( pItem->u.x.iOrderByCol>pEList->nExpr ){
108427        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr, 0);
108428        return 1;
108429      }
108430      resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0);
108431    }
108432  }
108433  return 0;
108434}
108435
108436#ifndef SQLITE_OMIT_WINDOWFUNC
108437/*
108438** Walker callback for windowRemoveExprFromSelect().
108439*/
108440static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
108441  UNUSED_PARAMETER(pWalker);
108442  if( ExprHasProperty(pExpr, EP_WinFunc) ){
108443    Window *pWin = pExpr->y.pWin;
108444    sqlite3WindowUnlinkFromSelect(pWin);
108445  }
108446  return WRC_Continue;
108447}
108448
108449/*
108450** Remove any Window objects owned by the expression pExpr from the
108451** Select.pWin list of Select object pSelect.
108452*/
108453static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){
108454  if( pSelect->pWin ){
108455    Walker sWalker;
108456    memset(&sWalker, 0, sizeof(Walker));
108457    sWalker.xExprCallback = resolveRemoveWindowsCb;
108458    sWalker.u.pSelect = pSelect;
108459    sqlite3WalkExpr(&sWalker, pExpr);
108460  }
108461}
108462#else
108463# define windowRemoveExprFromSelect(a, b)
108464#endif /* SQLITE_OMIT_WINDOWFUNC */
108465
108466/*
108467** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
108468** The Name context of the SELECT statement is pNC.  zType is either
108469** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
108470**
108471** This routine resolves each term of the clause into an expression.
108472** If the order-by term is an integer I between 1 and N (where N is the
108473** number of columns in the result set of the SELECT) then the expression
108474** in the resolution is a copy of the I-th result-set expression.  If
108475** the order-by term is an identifier that corresponds to the AS-name of
108476** a result-set expression, then the term resolves to a copy of the
108477** result-set expression.  Otherwise, the expression is resolved in
108478** the usual way - using sqlite3ResolveExprNames().
108479**
108480** This routine returns the number of errors.  If errors occur, then
108481** an appropriate error message might be left in pParse.  (OOM errors
108482** excepted.)
108483*/
108484static int resolveOrderGroupBy(
108485  NameContext *pNC,     /* The name context of the SELECT statement */
108486  Select *pSelect,      /* The SELECT statement holding pOrderBy */
108487  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
108488  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
108489){
108490  int i, j;                      /* Loop counters */
108491  int iCol;                      /* Column number */
108492  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
108493  Parse *pParse;                 /* Parsing context */
108494  int nResult;                   /* Number of terms in the result set */
108495
108496  assert( pOrderBy!=0 );
108497  nResult = pSelect->pEList->nExpr;
108498  pParse = pNC->pParse;
108499  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
108500    Expr *pE = pItem->pExpr;
108501    Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
108502    if( NEVER(pE2==0) ) continue;
108503    if( zType[0]!='G' ){
108504      iCol = resolveAsName(pParse, pSelect->pEList, pE2);
108505      if( iCol>0 ){
108506        /* If an AS-name match is found, mark this ORDER BY column as being
108507        ** a copy of the iCol-th result-set column.  The subsequent call to
108508        ** sqlite3ResolveOrderGroupBy() will convert the expression to a
108509        ** copy of the iCol-th result-set expression. */
108510        pItem->u.x.iOrderByCol = (u16)iCol;
108511        continue;
108512      }
108513    }
108514    if( sqlite3ExprIsInteger(pE2, &iCol) ){
108515      /* The ORDER BY term is an integer constant.  Again, set the column
108516      ** number so that sqlite3ResolveOrderGroupBy() will convert the
108517      ** order-by term to a copy of the result-set expression */
108518      if( iCol<1 || iCol>0xffff ){
108519        resolveOutOfRangeError(pParse, zType, i+1, nResult, pE2);
108520        return 1;
108521      }
108522      pItem->u.x.iOrderByCol = (u16)iCol;
108523      continue;
108524    }
108525
108526    /* Otherwise, treat the ORDER BY term as an ordinary expression */
108527    pItem->u.x.iOrderByCol = 0;
108528    if( sqlite3ResolveExprNames(pNC, pE) ){
108529      return 1;
108530    }
108531    for(j=0; j<pSelect->pEList->nExpr; j++){
108532      if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
108533        /* Since this expression is being changed into a reference
108534        ** to an identical expression in the result set, remove all Window
108535        ** objects belonging to the expression from the Select.pWin list. */
108536        windowRemoveExprFromSelect(pSelect, pE);
108537        pItem->u.x.iOrderByCol = j+1;
108538      }
108539    }
108540  }
108541  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
108542}
108543
108544/*
108545** Resolve names in the SELECT statement p and all of its descendants.
108546*/
108547static int resolveSelectStep(Walker *pWalker, Select *p){
108548  NameContext *pOuterNC;  /* Context that contains this SELECT */
108549  NameContext sNC;        /* Name context of this SELECT */
108550  int isCompound;         /* True if p is a compound select */
108551  int nCompound;          /* Number of compound terms processed so far */
108552  Parse *pParse;          /* Parsing context */
108553  int i;                  /* Loop counter */
108554  ExprList *pGroupBy;     /* The GROUP BY clause */
108555  Select *pLeftmost;      /* Left-most of SELECT of a compound */
108556  sqlite3 *db;            /* Database connection */
108557
108558
108559  assert( p!=0 );
108560  if( p->selFlags & SF_Resolved ){
108561    return WRC_Prune;
108562  }
108563  pOuterNC = pWalker->u.pNC;
108564  pParse = pWalker->pParse;
108565  db = pParse->db;
108566
108567  /* Normally sqlite3SelectExpand() will be called first and will have
108568  ** already expanded this SELECT.  However, if this is a subquery within
108569  ** an expression, sqlite3ResolveExprNames() will be called without a
108570  ** prior call to sqlite3SelectExpand().  When that happens, let
108571  ** sqlite3SelectPrep() do all of the processing for this SELECT.
108572  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
108573  ** this routine in the correct order.
108574  */
108575  if( (p->selFlags & SF_Expanded)==0 ){
108576    sqlite3SelectPrep(pParse, p, pOuterNC);
108577    return pParse->nErr ? WRC_Abort : WRC_Prune;
108578  }
108579
108580  isCompound = p->pPrior!=0;
108581  nCompound = 0;
108582  pLeftmost = p;
108583  while( p ){
108584    assert( (p->selFlags & SF_Expanded)!=0 );
108585    assert( (p->selFlags & SF_Resolved)==0 );
108586    p->selFlags |= SF_Resolved;
108587
108588    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
108589    ** are not allowed to refer to any names, so pass an empty NameContext.
108590    */
108591    memset(&sNC, 0, sizeof(sNC));
108592    sNC.pParse = pParse;
108593    sNC.pWinSelect = p;
108594    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
108595      return WRC_Abort;
108596    }
108597
108598    /* If the SF_Converted flags is set, then this Select object was
108599    ** was created by the convertCompoundSelectToSubquery() function.
108600    ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
108601    ** as if it were part of the sub-query, not the parent. This block
108602    ** moves the pOrderBy down to the sub-query. It will be moved back
108603    ** after the names have been resolved.  */
108604    if( p->selFlags & SF_Converted ){
108605      Select *pSub = p->pSrc->a[0].pSelect;
108606      assert( p->pSrc->nSrc==1 && p->pOrderBy );
108607      assert( pSub->pPrior && pSub->pOrderBy==0 );
108608      pSub->pOrderBy = p->pOrderBy;
108609      p->pOrderBy = 0;
108610    }
108611
108612    /* Recursively resolve names in all subqueries in the FROM clause
108613    */
108614    if( pOuterNC ) pOuterNC->nNestedSelect++;
108615    for(i=0; i<p->pSrc->nSrc; i++){
108616      SrcItem *pItem = &p->pSrc->a[i];
108617      assert( pItem->zName!=0 || pItem->pSelect!=0 );/* Test of tag-20240424-1*/
108618      if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
108619        int nRef = pOuterNC ? pOuterNC->nRef : 0;
108620        const char *zSavedContext = pParse->zAuthContext;
108621
108622        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
108623        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
108624        pParse->zAuthContext = zSavedContext;
108625        if( pParse->nErr ) return WRC_Abort;
108626        assert( db->mallocFailed==0 );
108627
108628        /* If the number of references to the outer context changed when
108629        ** expressions in the sub-select were resolved, the sub-select
108630        ** is correlated. It is not required to check the refcount on any
108631        ** but the innermost outer context object, as lookupName() increments
108632        ** the refcount on all contexts between the current one and the
108633        ** context containing the column when it resolves a name. */
108634        if( pOuterNC ){
108635          assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef );
108636          pItem->fg.isCorrelated = (pOuterNC->nRef>nRef);
108637        }
108638      }
108639    }
108640    if( pOuterNC && ALWAYS(pOuterNC->nNestedSelect>0) ){
108641      pOuterNC->nNestedSelect--;
108642    }
108643
108644    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
108645    ** resolve the result-set expression list.
108646    */
108647    sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
108648    sNC.pSrcList = p->pSrc;
108649    sNC.pNext = pOuterNC;
108650
108651    /* Resolve names in the result set. */
108652    if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
108653    sNC.ncFlags &= ~NC_AllowWin;
108654
108655    /* If there are no aggregate functions in the result-set, and no GROUP BY
108656    ** expression, do not allow aggregates in any of the other expressions.
108657    */
108658    assert( (p->selFlags & SF_Aggregate)==0 );
108659    pGroupBy = p->pGroupBy;
108660    if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
108661      assert( NC_MinMaxAgg==SF_MinMaxAgg );
108662      assert( NC_OrderAgg==SF_OrderByReqd );
108663      p->selFlags |= SF_Aggregate | (sNC.ncFlags&(NC_MinMaxAgg|NC_OrderAgg));
108664    }else{
108665      sNC.ncFlags &= ~NC_AllowAgg;
108666    }
108667
108668    /* Add the output column list to the name-context before parsing the
108669    ** other expressions in the SELECT statement. This is so that
108670    ** expressions in the WHERE clause (etc.) can refer to expressions by
108671    ** aliases in the result set.
108672    **
108673    ** Minor point: If this is the case, then the expression will be
108674    ** re-evaluated for each reference to it.
108675    */
108676    assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert|NC_UBaseReg))==0 );
108677    sNC.uNC.pEList = p->pEList;
108678    sNC.ncFlags |= NC_UEList;
108679    if( p->pHaving ){
108680      if( (p->selFlags & SF_Aggregate)==0 ){
108681        sqlite3ErrorMsg(pParse, "HAVING clause on a non-aggregate query");
108682        return WRC_Abort;
108683      }
108684      if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
108685    }
108686    sNC.ncFlags |= NC_Where;
108687    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
108688    sNC.ncFlags &= ~NC_Where;
108689
108690    /* Resolve names in table-valued-function arguments */
108691    for(i=0; i<p->pSrc->nSrc; i++){
108692      SrcItem *pItem = &p->pSrc->a[i];
108693      if( pItem->fg.isTabFunc
108694       && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
108695      ){
108696        return WRC_Abort;
108697      }
108698    }
108699
108700#ifndef SQLITE_OMIT_WINDOWFUNC
108701    if( IN_RENAME_OBJECT ){
108702      Window *pWin;
108703      for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
108704        if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
108705         || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
108706        ){
108707          return WRC_Abort;
108708        }
108709      }
108710    }
108711#endif
108712
108713    /* The ORDER BY and GROUP BY clauses may not refer to terms in
108714    ** outer queries
108715    */
108716    sNC.pNext = 0;
108717    sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
108718
108719    /* If this is a converted compound query, move the ORDER BY clause from
108720    ** the sub-query back to the parent query. At this point each term
108721    ** within the ORDER BY clause has been transformed to an integer value.
108722    ** These integers will be replaced by copies of the corresponding result
108723    ** set expressions by the call to resolveOrderGroupBy() below.  */
108724    if( p->selFlags & SF_Converted ){
108725      Select *pSub = p->pSrc->a[0].pSelect;
108726      p->pOrderBy = pSub->pOrderBy;
108727      pSub->pOrderBy = 0;
108728    }
108729
108730    /* Process the ORDER BY clause for singleton SELECT statements.
108731    ** The ORDER BY clause for compounds SELECT statements is handled
108732    ** below, after all of the result-sets for all of the elements of
108733    ** the compound have been resolved.
108734    **
108735    ** If there is an ORDER BY clause on a term of a compound-select other
108736    ** than the right-most term, then that is a syntax error.  But the error
108737    ** is not detected until much later, and so we need to go ahead and
108738    ** resolve those symbols on the incorrect ORDER BY for consistency.
108739    */
108740    if( p->pOrderBy!=0
108741     && isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
108742     && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
108743    ){
108744      return WRC_Abort;
108745    }
108746    if( db->mallocFailed ){
108747      return WRC_Abort;
108748    }
108749    sNC.ncFlags &= ~NC_AllowWin;
108750
108751    /* Resolve the GROUP BY clause.  At the same time, make sure
108752    ** the GROUP BY clause does not contain aggregate functions.
108753    */
108754    if( pGroupBy ){
108755      struct ExprList_item *pItem;
108756
108757      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
108758        return WRC_Abort;
108759      }
108760      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
108761        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
108762          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
108763              "the GROUP BY clause");
108764          return WRC_Abort;
108765        }
108766      }
108767    }
108768
108769    /* If this is part of a compound SELECT, check that it has the right
108770    ** number of expressions in the select list. */
108771    if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
108772      sqlite3SelectWrongNumTermsError(pParse, p->pNext);
108773      return WRC_Abort;
108774    }
108775
108776    /* Advance to the next term of the compound
108777    */
108778    p = p->pPrior;
108779    nCompound++;
108780  }
108781
108782  /* Resolve the ORDER BY on a compound SELECT after all terms of
108783  ** the compound have been resolved.
108784  */
108785  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
108786    return WRC_Abort;
108787  }
108788
108789  return WRC_Prune;
108790}
108791
108792/*
108793** This routine walks an expression tree and resolves references to
108794** table columns and result-set columns.  At the same time, do error
108795** checking on function usage and set a flag if any aggregate functions
108796** are seen.
108797**
108798** To resolve table columns references we look for nodes (or subtrees) of the
108799** form X.Y.Z or Y.Z or just Z where
108800**
108801**      X:   The name of a database.  Ex:  "main" or "temp" or
108802**           the symbolic name assigned to an ATTACH-ed database.
108803**
108804**      Y:   The name of a table in a FROM clause.  Or in a trigger
108805**           one of the special names "old" or "new".
108806**
108807**      Z:   The name of a column in table Y.
108808**
108809** The node at the root of the subtree is modified as follows:
108810**
108811**    Expr.op        Changed to TK_COLUMN
108812**    Expr.pTab      Points to the Table object for X.Y
108813**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
108814**    Expr.iTable    The VDBE cursor number for X.Y
108815**
108816**
108817** To resolve result-set references, look for expression nodes of the
108818** form Z (with no X and Y prefix) where the Z matches the right-hand
108819** size of an AS clause in the result-set of a SELECT.  The Z expression
108820** is replaced by a copy of the left-hand side of the result-set expression.
108821** Table-name and function resolution occurs on the substituted expression
108822** tree.  For example, in:
108823**
108824**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
108825**
108826** The "x" term of the order by is replaced by "a+b" to render:
108827**
108828**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
108829**
108830** Function calls are checked to make sure that the function is
108831** defined and that the correct number of arguments are specified.
108832** If the function is an aggregate function, then the NC_HasAgg flag is
108833** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
108834** If an expression contains aggregate functions then the EP_Agg
108835** property on the expression is set.
108836**
108837** An error message is left in pParse if anything is amiss.  The number
108838** if errors is returned.
108839*/
108840SQLITE_PRIVATE int sqlite3ResolveExprNames(
108841  NameContext *pNC,       /* Namespace to resolve expressions in. */
108842  Expr *pExpr             /* The expression to be analyzed. */
108843){
108844  int savedHasAgg;
108845  Walker w;
108846
108847  if( pExpr==0 ) return SQLITE_OK;
108848  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
108849  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
108850  w.pParse = pNC->pParse;
108851  w.xExprCallback = resolveExprStep;
108852  w.xSelectCallback = (pNC->ncFlags & NC_NoSelect) ? 0 : resolveSelectStep;
108853  w.xSelectCallback2 = 0;
108854  w.u.pNC = pNC;
108855#if SQLITE_MAX_EXPR_DEPTH>0
108856  w.pParse->nHeight += pExpr->nHeight;
108857  if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
108858    return SQLITE_ERROR;
108859  }
108860#endif
108861  assert( pExpr!=0 );
108862  sqlite3WalkExprNN(&w, pExpr);
108863#if SQLITE_MAX_EXPR_DEPTH>0
108864  w.pParse->nHeight -= pExpr->nHeight;
108865#endif
108866  assert( EP_Agg==NC_HasAgg );
108867  assert( EP_Win==NC_HasWin );
108868  testcase( pNC->ncFlags & NC_HasAgg );
108869  testcase( pNC->ncFlags & NC_HasWin );
108870  ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
108871  pNC->ncFlags |= savedHasAgg;
108872  return pNC->nNcErr>0 || w.pParse->nErr>0;
108873}
108874
108875/*
108876** Resolve all names for all expression in an expression list.  This is
108877** just like sqlite3ResolveExprNames() except that it works for an expression
108878** list rather than a single expression.
108879*/
108880SQLITE_PRIVATE int sqlite3ResolveExprListNames(
108881  NameContext *pNC,       /* Namespace to resolve expressions in. */
108882  ExprList *pList         /* The expression list to be analyzed. */
108883){
108884  int i;
108885  int savedHasAgg = 0;
108886  Walker w;
108887  if( pList==0 ) return WRC_Continue;
108888  w.pParse = pNC->pParse;
108889  w.xExprCallback = resolveExprStep;
108890  w.xSelectCallback = resolveSelectStep;
108891  w.xSelectCallback2 = 0;
108892  w.u.pNC = pNC;
108893  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
108894  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
108895  for(i=0; i<pList->nExpr; i++){
108896    Expr *pExpr = pList->a[i].pExpr;
108897    if( pExpr==0 ) continue;
108898#if SQLITE_MAX_EXPR_DEPTH>0
108899    w.pParse->nHeight += pExpr->nHeight;
108900    if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
108901      return WRC_Abort;
108902    }
108903#endif
108904    sqlite3WalkExprNN(&w, pExpr);
108905#if SQLITE_MAX_EXPR_DEPTH>0
108906    w.pParse->nHeight -= pExpr->nHeight;
108907#endif
108908    assert( EP_Agg==NC_HasAgg );
108909    assert( EP_Win==NC_HasWin );
108910    testcase( pNC->ncFlags & NC_HasAgg );
108911    testcase( pNC->ncFlags & NC_HasWin );
108912    if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg) ){
108913      ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
108914      savedHasAgg |= pNC->ncFlags &
108915                          (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
108916      pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
108917    }
108918    if( w.pParse->nErr>0 ) return WRC_Abort;
108919  }
108920  pNC->ncFlags |= savedHasAgg;
108921  return WRC_Continue;
108922}
108923
108924/*
108925** Resolve all names in all expressions of a SELECT and in all
108926** descendants of the SELECT, including compounds off of p->pPrior,
108927** subqueries in expressions, and subqueries used as FROM clause
108928** terms.
108929**
108930** See sqlite3ResolveExprNames() for a description of the kinds of
108931** transformations that occur.
108932**
108933** All SELECT statements should have been expanded using
108934** sqlite3SelectExpand() prior to invoking this routine.
108935*/
108936SQLITE_PRIVATE void sqlite3ResolveSelectNames(
108937  Parse *pParse,         /* The parser context */
108938  Select *p,             /* The SELECT statement being coded. */
108939  NameContext *pOuterNC  /* Name context for parent SELECT statement */
108940){
108941  Walker w;
108942
108943  assert( p!=0 );
108944  w.xExprCallback = resolveExprStep;
108945  w.xSelectCallback = resolveSelectStep;
108946  w.xSelectCallback2 = 0;
108947  w.pParse = pParse;
108948  w.u.pNC = pOuterNC;
108949  sqlite3WalkSelect(&w, p);
108950}
108951
108952/*
108953** Resolve names in expressions that can only reference a single table
108954** or which cannot reference any tables at all.  Examples:
108955**
108956**                                                    "type" flag
108957**                                                    ------------
108958**    (1)   CHECK constraints                         NC_IsCheck
108959**    (2)   WHERE clauses on partial indices          NC_PartIdx
108960**    (3)   Expressions in indexes on expressions     NC_IdxExpr
108961**    (4)   Expression arguments to VACUUM INTO.      0
108962**    (5)   GENERATED ALWAYS as expressions           NC_GenCol
108963**
108964** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
108965** nodes of the expression is set to -1 and the Expr.iColumn value is
108966** set to the column number.  In case (4), TK_COLUMN nodes cause an error.
108967**
108968** Any errors cause an error message to be set in pParse.
108969*/
108970SQLITE_PRIVATE int sqlite3ResolveSelfReference(
108971  Parse *pParse,   /* Parsing context */
108972  Table *pTab,     /* The table being referenced, or NULL */
108973  int type,        /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
108974  Expr *pExpr,     /* Expression to resolve.  May be NULL. */
108975  ExprList *pList  /* Expression list to resolve.  May be NULL. */
108976){
108977  SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
108978  NameContext sNC;                /* Name context for pParse->pNewTable */
108979  int rc;
108980
108981  assert( type==0 || pTab!=0 );
108982  assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr
108983          || type==NC_GenCol || pTab==0 );
108984  memset(&sNC, 0, sizeof(sNC));
108985  memset(&sSrc, 0, sizeof(sSrc));
108986  if( pTab ){
108987    sSrc.nSrc = 1;
108988    sSrc.a[0].zName = pTab->zName;
108989    sSrc.a[0].pTab = pTab;
108990    sSrc.a[0].iCursor = -1;
108991    if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
108992      /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
108993      ** schema elements */
108994      type |= NC_FromDDL;
108995    }
108996  }
108997  sNC.pParse = pParse;
108998  sNC.pSrcList = &sSrc;
108999  sNC.ncFlags = type | NC_IsDDL;
109000  if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
109001  if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
109002  return rc;
109003}
109004
109005/************** End of resolve.c *********************************************/
109006/************** Begin file expr.c ********************************************/
109007/*
109008** 2001 September 15
109009**
109010** The author disclaims copyright to this source code.  In place of
109011** a legal notice, here is a blessing:
109012**
109013**    May you do good and not evil.
109014**    May you find forgiveness for yourself and forgive others.
109015**    May you share freely, never taking more than you give.
109016**
109017*************************************************************************
109018** This file contains routines used for analyzing expressions and
109019** for generating VDBE code that evaluates expressions in SQLite.
109020*/
109021/* #include "sqliteInt.h" */
109022
109023/* Forward declarations */
109024static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
109025static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
109026
109027/*
109028** Return the affinity character for a single column of a table.
109029*/
109030SQLITE_PRIVATE char sqlite3TableColumnAffinity(const Table *pTab, int iCol){
109031  if( iCol<0 || NEVER(iCol>=pTab->nCol) ) return SQLITE_AFF_INTEGER;
109032  return pTab->aCol[iCol].affinity;
109033}
109034
109035/*
109036** Return the 'affinity' of the expression pExpr if any.
109037**
109038** If pExpr is a column, a reference to a column via an 'AS' alias,
109039** or a sub-select with a column as the return value, then the
109040** affinity of that column is returned. Otherwise, 0x00 is returned,
109041** indicating no affinity for the expression.
109042**
109043** i.e. the WHERE clause expressions in the following statements all
109044** have an affinity:
109045**
109046** CREATE TABLE t1(a);
109047** SELECT * FROM t1 WHERE a;
109048** SELECT a AS b FROM t1 WHERE b;
109049** SELECT * FROM t1 WHERE (select a from t1);
109050*/
109051SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr){
109052  int op;
109053  op = pExpr->op;
109054  while( 1 /* exit-by-break */ ){
109055    if( op==TK_COLUMN || (op==TK_AGG_COLUMN && pExpr->y.pTab!=0) ){
109056      assert( ExprUseYTab(pExpr) );
109057      assert( pExpr->y.pTab!=0 );
109058      return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
109059    }
109060    if( op==TK_SELECT ){
109061      assert( ExprUseXSelect(pExpr) );
109062      assert( pExpr->x.pSelect!=0 );
109063      assert( pExpr->x.pSelect->pEList!=0 );
109064      assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 );
109065      return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
109066    }
109067#ifndef SQLITE_OMIT_CAST
109068    if( op==TK_CAST ){
109069      assert( !ExprHasProperty(pExpr, EP_IntValue) );
109070      return sqlite3AffinityType(pExpr->u.zToken, 0);
109071    }
109072#endif
109073    if( op==TK_SELECT_COLUMN ){
109074      assert( pExpr->pLeft!=0 && ExprUseXSelect(pExpr->pLeft) );
109075      assert( pExpr->iColumn < pExpr->iTable );
109076      assert( pExpr->iColumn >= 0 );
109077      assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr );
109078      return sqlite3ExprAffinity(
109079          pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
109080      );
109081    }
109082    if( op==TK_VECTOR ){
109083      assert( ExprUseXList(pExpr) );
109084      return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
109085    }
109086    if( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){
109087      assert( pExpr->op==TK_COLLATE
109088           || pExpr->op==TK_IF_NULL_ROW
109089           || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );
109090      pExpr = pExpr->pLeft;
109091      op = pExpr->op;
109092      continue;
109093    }
109094    if( op!=TK_REGISTER || (op = pExpr->op2)==TK_REGISTER ) break;
109095  }
109096  return pExpr->affExpr;
109097}
109098
109099/*
109100** Make a guess at all the possible datatypes of the result that could
109101** be returned by an expression.  Return a bitmask indicating the answer:
109102**
109103**     0x01         Numeric
109104**     0x02         Text
109105**     0x04         Blob
109106**
109107** If the expression must return NULL, then 0x00 is returned.
109108*/
109109SQLITE_PRIVATE int sqlite3ExprDataType(const Expr *pExpr){
109110  while( pExpr ){
109111    switch( pExpr->op ){
109112      case TK_COLLATE:
109113      case TK_IF_NULL_ROW:
109114      case TK_UPLUS:  {
109115        pExpr = pExpr->pLeft;
109116        break;
109117      }
109118      case TK_NULL: {
109119        pExpr = 0;
109120        break;
109121      }
109122      case TK_STRING: {
109123        return 0x02;
109124      }
109125      case TK_BLOB: {
109126        return 0x04;
109127      }
109128      case TK_CONCAT: {
109129        return 0x06;
109130      }
109131      case TK_VARIABLE:
109132      case TK_AGG_FUNCTION:
109133      case TK_FUNCTION: {
109134        return 0x07;
109135      }
109136      case TK_COLUMN:
109137      case TK_AGG_COLUMN:
109138      case TK_SELECT:
109139      case TK_CAST:
109140      case TK_SELECT_COLUMN:
109141      case TK_VECTOR:  {
109142        int aff = sqlite3ExprAffinity(pExpr);
109143        if( aff>=SQLITE_AFF_NUMERIC ) return 0x05;
109144        if( aff==SQLITE_AFF_TEXT )    return 0x06;
109145        return 0x07;
109146      }
109147      case TK_CASE: {
109148        int res = 0;
109149        int ii;
109150        ExprList *pList = pExpr->x.pList;
109151        assert( ExprUseXList(pExpr) && pList!=0 );
109152        assert( pList->nExpr > 0);
109153        for(ii=1; ii<pList->nExpr; ii+=2){
109154          res |= sqlite3ExprDataType(pList->a[ii].pExpr);
109155        }
109156        if( pList->nExpr % 2 ){
109157          res |= sqlite3ExprDataType(pList->a[pList->nExpr-1].pExpr);
109158        }
109159        return res;
109160      }
109161      default: {
109162        return 0x01;
109163      }
109164    } /* End of switch(op) */
109165  } /* End of while(pExpr) */
109166  return 0x00;
109167}
109168
109169/*
109170** Set the collating sequence for expression pExpr to be the collating
109171** sequence named by pToken.   Return a pointer to a new Expr node that
109172** implements the COLLATE operator.
109173**
109174** If a memory allocation error occurs, that fact is recorded in pParse->db
109175** and the pExpr parameter is returned unchanged.
109176*/
109177SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
109178  const Parse *pParse,     /* Parsing context */
109179  Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
109180  const Token *pCollName,  /* Name of collating sequence */
109181  int dequote              /* True to dequote pCollName */
109182){
109183  if( pCollName->n>0 ){
109184    Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
109185    if( pNew ){
109186      pNew->pLeft = pExpr;
109187      pNew->flags |= EP_Collate|EP_Skip;
109188      pExpr = pNew;
109189    }
109190  }
109191  return pExpr;
109192}
109193SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(
109194  const Parse *pParse,  /* Parsing context */
109195  Expr *pExpr,          /* Add the "COLLATE" clause to this expression */
109196  const char *zC        /* The collating sequence name */
109197){
109198  Token s;
109199  assert( zC!=0 );
109200  sqlite3TokenInit(&s, (char*)zC);
109201  return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
109202}
109203
109204/*
109205** Skip over any TK_COLLATE operators.
109206*/
109207SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
109208  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
109209    assert( pExpr->op==TK_COLLATE );
109210    pExpr = pExpr->pLeft;
109211  }
109212  return pExpr;
109213}
109214
109215/*
109216** Skip over any TK_COLLATE operators and/or any unlikely()
109217** or likelihood() or likely() functions at the root of an
109218** expression.
109219*/
109220SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
109221  while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
109222    if( ExprHasProperty(pExpr, EP_Unlikely) ){
109223      assert( ExprUseXList(pExpr) );
109224      assert( pExpr->x.pList->nExpr>0 );
109225      assert( pExpr->op==TK_FUNCTION );
109226      pExpr = pExpr->x.pList->a[0].pExpr;
109227    }else if( pExpr->op==TK_COLLATE ){
109228      pExpr = pExpr->pLeft;
109229    }else{
109230      break;
109231    }
109232  }
109233  return pExpr;
109234}
109235
109236/*
109237** Return the collation sequence for the expression pExpr. If
109238** there is no defined collating sequence, return NULL.
109239**
109240** See also: sqlite3ExprNNCollSeq()
109241**
109242** The sqlite3ExprNNCollSeq() works the same exact that it returns the
109243** default collation if pExpr has no defined collation.
109244**
109245** The collating sequence might be determined by a COLLATE operator
109246** or by the presence of a column with a defined collating sequence.
109247** COLLATE operators take first precedence.  Left operands take
109248** precedence over right operands.
109249*/
109250SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){
109251  sqlite3 *db = pParse->db;
109252  CollSeq *pColl = 0;
109253  const Expr *p = pExpr;
109254  while( p ){
109255    int op = p->op;
109256    if( op==TK_REGISTER ) op = p->op2;
109257    if( (op==TK_AGG_COLUMN && p->y.pTab!=0)
109258     || op==TK_COLUMN || op==TK_TRIGGER
109259    ){
109260      int j;
109261      assert( ExprUseYTab(p) );
109262      assert( p->y.pTab!=0 );
109263      if( (j = p->iColumn)>=0 ){
109264        const char *zColl = sqlite3ColumnColl(&p->y.pTab->aCol[j]);
109265        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
109266      }
109267      break;
109268    }
109269    if( op==TK_CAST || op==TK_UPLUS ){
109270      p = p->pLeft;
109271      continue;
109272    }
109273    if( op==TK_VECTOR ){
109274      assert( ExprUseXList(p) );
109275      p = p->x.pList->a[0].pExpr;
109276      continue;
109277    }
109278    if( op==TK_COLLATE ){
109279      assert( !ExprHasProperty(p, EP_IntValue) );
109280      pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
109281      break;
109282    }
109283    if( p->flags & EP_Collate ){
109284      if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
109285        p = p->pLeft;
109286      }else{
109287        Expr *pNext  = p->pRight;
109288        /* The Expr.x union is never used at the same time as Expr.pRight */
109289        assert( !ExprUseXList(p) || p->x.pList==0 || p->pRight==0 );
109290        if( ExprUseXList(p) && p->x.pList!=0 && !db->mallocFailed ){
109291          int i;
109292          for(i=0; i<p->x.pList->nExpr; i++){
109293            if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
109294              pNext = p->x.pList->a[i].pExpr;
109295              break;
109296            }
109297          }
109298        }
109299        p = pNext;
109300      }
109301    }else{
109302      break;
109303    }
109304  }
109305  if( sqlite3CheckCollSeq(pParse, pColl) ){
109306    pColl = 0;
109307  }
109308  return pColl;
109309}
109310
109311/*
109312** Return the collation sequence for the expression pExpr. If
109313** there is no defined collating sequence, return a pointer to the
109314** default collation sequence.
109315**
109316** See also: sqlite3ExprCollSeq()
109317**
109318** The sqlite3ExprCollSeq() routine works the same except that it
109319** returns NULL if there is no defined collation.
109320*/
109321SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){
109322  CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
109323  if( p==0 ) p = pParse->db->pDfltColl;
109324  assert( p!=0 );
109325  return p;
109326}
109327
109328/*
109329** Return TRUE if the two expressions have equivalent collating sequences.
109330*/
109331SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){
109332  CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
109333  CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
109334  return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
109335}
109336
109337/*
109338** pExpr is an operand of a comparison operator.  aff2 is the
109339** type affinity of the other operand.  This routine returns the
109340** type affinity that should be used for the comparison operator.
109341*/
109342SQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2){
109343  char aff1 = sqlite3ExprAffinity(pExpr);
109344  if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
109345    /* Both sides of the comparison are columns. If one has numeric
109346    ** affinity, use that. Otherwise use no affinity.
109347    */
109348    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
109349      return SQLITE_AFF_NUMERIC;
109350    }else{
109351      return SQLITE_AFF_BLOB;
109352    }
109353  }else{
109354    /* One side is a column, the other is not. Use the columns affinity. */
109355    assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
109356    return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
109357  }
109358}
109359
109360/*
109361** pExpr is a comparison operator.  Return the type affinity that should
109362** be applied to both operands prior to doing the comparison.
109363*/
109364static char comparisonAffinity(const Expr *pExpr){
109365  char aff;
109366  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
109367          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
109368          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
109369  assert( pExpr->pLeft );
109370  aff = sqlite3ExprAffinity(pExpr->pLeft);
109371  if( pExpr->pRight ){
109372    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
109373  }else if( ExprUseXSelect(pExpr) ){
109374    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
109375  }else if( aff==0 ){
109376    aff = SQLITE_AFF_BLOB;
109377  }
109378  return aff;
109379}
109380
109381/*
109382** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
109383** idx_affinity is the affinity of an indexed column. Return true
109384** if the index with affinity idx_affinity may be used to implement
109385** the comparison in pExpr.
109386*/
109387SQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){
109388  char aff = comparisonAffinity(pExpr);
109389  if( aff<SQLITE_AFF_TEXT ){
109390    return 1;
109391  }
109392  if( aff==SQLITE_AFF_TEXT ){
109393    return idx_affinity==SQLITE_AFF_TEXT;
109394  }
109395  return sqlite3IsNumericAffinity(idx_affinity);
109396}
109397
109398/*
109399** Return the P5 value that should be used for a binary comparison
109400** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
109401*/
109402static u8 binaryCompareP5(
109403  const Expr *pExpr1,   /* Left operand */
109404  const Expr *pExpr2,   /* Right operand */
109405  int jumpIfNull        /* Extra flags added to P5 */
109406){
109407  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
109408  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
109409  return aff;
109410}
109411
109412/*
109413** Return a pointer to the collation sequence that should be used by
109414** a binary comparison operator comparing pLeft and pRight.
109415**
109416** If the left hand expression has a collating sequence type, then it is
109417** used. Otherwise the collation sequence for the right hand expression
109418** is used, or the default (BINARY) if neither expression has a collating
109419** type.
109420**
109421** Argument pRight (but not pLeft) may be a null pointer. In this case,
109422** it is not considered.
109423*/
109424SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
109425  Parse *pParse,
109426  const Expr *pLeft,
109427  const Expr *pRight
109428){
109429  CollSeq *pColl;
109430  assert( pLeft );
109431  if( pLeft->flags & EP_Collate ){
109432    pColl = sqlite3ExprCollSeq(pParse, pLeft);
109433  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
109434    pColl = sqlite3ExprCollSeq(pParse, pRight);
109435  }else{
109436    pColl = sqlite3ExprCollSeq(pParse, pLeft);
109437    if( !pColl ){
109438      pColl = sqlite3ExprCollSeq(pParse, pRight);
109439    }
109440  }
109441  return pColl;
109442}
109443
109444/* Expression p is a comparison operator.  Return a collation sequence
109445** appropriate for the comparison operator.
109446**
109447** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
109448** However, if the OP_Commuted flag is set, then the order of the operands
109449** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
109450** correct collating sequence is found.
109451*/
109452SQLITE_PRIVATE CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){
109453  if( ExprHasProperty(p, EP_Commuted) ){
109454    return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
109455  }else{
109456    return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
109457  }
109458}
109459
109460/*
109461** Generate code for a comparison operator.
109462*/
109463static int codeCompare(
109464  Parse *pParse,    /* The parsing (and code generating) context */
109465  Expr *pLeft,      /* The left operand */
109466  Expr *pRight,     /* The right operand */
109467  int opcode,       /* The comparison opcode */
109468  int in1, int in2, /* Register holding operands */
109469  int dest,         /* Jump here if true.  */
109470  int jumpIfNull,   /* If true, jump if either operand is NULL */
109471  int isCommuted    /* The comparison has been commuted */
109472){
109473  int p5;
109474  int addr;
109475  CollSeq *p4;
109476
109477  if( pParse->nErr ) return 0;
109478  if( isCommuted ){
109479    p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
109480  }else{
109481    p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
109482  }
109483  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
109484  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
109485                           (void*)p4, P4_COLLSEQ);
109486  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
109487  return addr;
109488}
109489
109490/*
109491** Return true if expression pExpr is a vector, or false otherwise.
109492**
109493** A vector is defined as any expression that results in two or more
109494** columns of result.  Every TK_VECTOR node is an vector because the
109495** parser will not generate a TK_VECTOR with fewer than two entries.
109496** But a TK_SELECT might be either a vector or a scalar. It is only
109497** considered a vector if it has two or more result columns.
109498*/
109499SQLITE_PRIVATE int sqlite3ExprIsVector(const Expr *pExpr){
109500  return sqlite3ExprVectorSize(pExpr)>1;
109501}
109502
109503/*
109504** If the expression passed as the only argument is of type TK_VECTOR
109505** return the number of expressions in the vector. Or, if the expression
109506** is a sub-select, return the number of columns in the sub-select. For
109507** any other type of expression, return 1.
109508*/
109509SQLITE_PRIVATE int sqlite3ExprVectorSize(const Expr *pExpr){
109510  u8 op = pExpr->op;
109511  if( op==TK_REGISTER ) op = pExpr->op2;
109512  if( op==TK_VECTOR ){
109513    assert( ExprUseXList(pExpr) );
109514    return pExpr->x.pList->nExpr;
109515  }else if( op==TK_SELECT ){
109516    assert( ExprUseXSelect(pExpr) );
109517    return pExpr->x.pSelect->pEList->nExpr;
109518  }else{
109519    return 1;
109520  }
109521}
109522
109523/*
109524** Return a pointer to a subexpression of pVector that is the i-th
109525** column of the vector (numbered starting with 0).  The caller must
109526** ensure that i is within range.
109527**
109528** If pVector is really a scalar (and "scalar" here includes subqueries
109529** that return a single column!) then return pVector unmodified.
109530**
109531** pVector retains ownership of the returned subexpression.
109532**
109533** If the vector is a (SELECT ...) then the expression returned is
109534** just the expression for the i-th term of the result set, and may
109535** not be ready for evaluation because the table cursor has not yet
109536** been positioned.
109537*/
109538SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
109539  assert( i<sqlite3ExprVectorSize(pVector) || pVector->op==TK_ERROR );
109540  if( sqlite3ExprIsVector(pVector) ){
109541    assert( pVector->op2==0 || pVector->op==TK_REGISTER );
109542    if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
109543      assert( ExprUseXSelect(pVector) );
109544      return pVector->x.pSelect->pEList->a[i].pExpr;
109545    }else{
109546      assert( ExprUseXList(pVector) );
109547      return pVector->x.pList->a[i].pExpr;
109548    }
109549  }
109550  return pVector;
109551}
109552
109553/*
109554** Compute and return a new Expr object which when passed to
109555** sqlite3ExprCode() will generate all necessary code to compute
109556** the iField-th column of the vector expression pVector.
109557**
109558** It is ok for pVector to be a scalar (as long as iField==0).
109559** In that case, this routine works like sqlite3ExprDup().
109560**
109561** The caller owns the returned Expr object and is responsible for
109562** ensuring that the returned value eventually gets freed.
109563**
109564** The caller retains ownership of pVector.  If pVector is a TK_SELECT,
109565** then the returned object will reference pVector and so pVector must remain
109566** valid for the life of the returned object.  If pVector is a TK_VECTOR
109567** or a scalar expression, then it can be deleted as soon as this routine
109568** returns.
109569**
109570** A trick to cause a TK_SELECT pVector to be deleted together with
109571** the returned Expr object is to attach the pVector to the pRight field
109572** of the returned TK_SELECT_COLUMN Expr object.
109573*/
109574SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
109575  Parse *pParse,       /* Parsing context */
109576  Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */
109577  int iField,          /* Which column of the vector to return */
109578  int nField           /* Total number of columns in the vector */
109579){
109580  Expr *pRet;
109581  if( pVector->op==TK_SELECT ){
109582    assert( ExprUseXSelect(pVector) );
109583    /* The TK_SELECT_COLUMN Expr node:
109584    **
109585    ** pLeft:           pVector containing TK_SELECT.  Not deleted.
109586    ** pRight:          not used.  But recursively deleted.
109587    ** iColumn:         Index of a column in pVector
109588    ** iTable:          0 or the number of columns on the LHS of an assignment
109589    ** pLeft->iTable:   First in an array of register holding result, or 0
109590    **                  if the result is not yet computed.
109591    **
109592    ** sqlite3ExprDelete() specifically skips the recursive delete of
109593    ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector
109594    ** can be attached to pRight to cause this node to take ownership of
109595    ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes
109596    ** with the same pLeft pointer to the pVector, but only one of them
109597    ** will own the pVector.
109598    */
109599    pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
109600    if( pRet ){
109601      ExprSetProperty(pRet, EP_FullSize);
109602      pRet->iTable = nField;
109603      pRet->iColumn = iField;
109604      pRet->pLeft = pVector;
109605    }
109606  }else{
109607    if( pVector->op==TK_VECTOR ){
109608      Expr **ppVector;
109609      assert( ExprUseXList(pVector) );
109610      ppVector = &pVector->x.pList->a[iField].pExpr;
109611      pVector = *ppVector;
109612      if( IN_RENAME_OBJECT ){
109613        /* This must be a vector UPDATE inside a trigger */
109614        *ppVector = 0;
109615        return pVector;
109616      }
109617    }
109618    pRet = sqlite3ExprDup(pParse->db, pVector, 0);
109619  }
109620  return pRet;
109621}
109622
109623/*
109624** If expression pExpr is of type TK_SELECT, generate code to evaluate
109625** it. Return the register in which the result is stored (or, if the
109626** sub-select returns more than one column, the first in an array
109627** of registers in which the result is stored).
109628**
109629** If pExpr is not a TK_SELECT expression, return 0.
109630*/
109631static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
109632  int reg = 0;
109633#ifndef SQLITE_OMIT_SUBQUERY
109634  if( pExpr->op==TK_SELECT ){
109635    reg = sqlite3CodeSubselect(pParse, pExpr);
109636  }
109637#endif
109638  return reg;
109639}
109640
109641/*
109642** Argument pVector points to a vector expression - either a TK_VECTOR
109643** or TK_SELECT that returns more than one column. This function returns
109644** the register number of a register that contains the value of
109645** element iField of the vector.
109646**
109647** If pVector is a TK_SELECT expression, then code for it must have
109648** already been generated using the exprCodeSubselect() routine. In this
109649** case parameter regSelect should be the first in an array of registers
109650** containing the results of the sub-select.
109651**
109652** If pVector is of type TK_VECTOR, then code for the requested field
109653** is generated. In this case (*pRegFree) may be set to the number of
109654** a temporary register to be freed by the caller before returning.
109655**
109656** Before returning, output parameter (*ppExpr) is set to point to the
109657** Expr object corresponding to element iElem of the vector.
109658*/
109659static int exprVectorRegister(
109660  Parse *pParse,                  /* Parse context */
109661  Expr *pVector,                  /* Vector to extract element from */
109662  int iField,                     /* Field to extract from pVector */
109663  int regSelect,                  /* First in array of registers */
109664  Expr **ppExpr,                  /* OUT: Expression element */
109665  int *pRegFree                   /* OUT: Temp register to free */
109666){
109667  u8 op = pVector->op;
109668  assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT || op==TK_ERROR );
109669  if( op==TK_REGISTER ){
109670    *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
109671    return pVector->iTable+iField;
109672  }
109673  if( op==TK_SELECT ){
109674    assert( ExprUseXSelect(pVector) );
109675    *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
109676     return regSelect+iField;
109677  }
109678  if( op==TK_VECTOR ){
109679    assert( ExprUseXList(pVector) );
109680    *ppExpr = pVector->x.pList->a[iField].pExpr;
109681    return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
109682  }
109683  return 0;
109684}
109685
109686/*
109687** Expression pExpr is a comparison between two vector values. Compute
109688** the result of the comparison (1, 0, or NULL) and write that
109689** result into register dest.
109690**
109691** The caller must satisfy the following preconditions:
109692**
109693**    if pExpr->op==TK_IS:      op==TK_EQ and p5==SQLITE_NULLEQ
109694**    if pExpr->op==TK_ISNOT:   op==TK_NE and p5==SQLITE_NULLEQ
109695**    otherwise:                op==pExpr->op and p5==0
109696*/
109697static void codeVectorCompare(
109698  Parse *pParse,        /* Code generator context */
109699  Expr *pExpr,          /* The comparison operation */
109700  int dest,             /* Write results into this register */
109701  u8 op,                /* Comparison operator */
109702  u8 p5                 /* SQLITE_NULLEQ or zero */
109703){
109704  Vdbe *v = pParse->pVdbe;
109705  Expr *pLeft = pExpr->pLeft;
109706  Expr *pRight = pExpr->pRight;
109707  int nLeft = sqlite3ExprVectorSize(pLeft);
109708  int i;
109709  int regLeft = 0;
109710  int regRight = 0;
109711  u8 opx = op;
109712  int addrCmp = 0;
109713  int addrDone = sqlite3VdbeMakeLabel(pParse);
109714  int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
109715
109716  assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
109717  if( pParse->nErr ) return;
109718  if( nLeft!=sqlite3ExprVectorSize(pRight) ){
109719    sqlite3ErrorMsg(pParse, "row value misused");
109720    return;
109721  }
109722  assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
109723       || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
109724       || pExpr->op==TK_LT || pExpr->op==TK_GT
109725       || pExpr->op==TK_LE || pExpr->op==TK_GE
109726  );
109727  assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
109728            || (pExpr->op==TK_ISNOT && op==TK_NE) );
109729  assert( p5==0 || pExpr->op!=op );
109730  assert( p5==SQLITE_NULLEQ || pExpr->op==op );
109731
109732  if( op==TK_LE ) opx = TK_LT;
109733  if( op==TK_GE ) opx = TK_GT;
109734  if( op==TK_NE ) opx = TK_EQ;
109735
109736  regLeft = exprCodeSubselect(pParse, pLeft);
109737  regRight = exprCodeSubselect(pParse, pRight);
109738
109739  sqlite3VdbeAddOp2(v, OP_Integer, 1, dest);
109740  for(i=0; 1 /*Loop exits by "break"*/; i++){
109741    int regFree1 = 0, regFree2 = 0;
109742    Expr *pL = 0, *pR = 0;
109743    int r1, r2;
109744    assert( i>=0 && i<nLeft );
109745    if( addrCmp ) sqlite3VdbeJumpHere(v, addrCmp);
109746    r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
109747    r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
109748    addrCmp = sqlite3VdbeCurrentAddr(v);
109749    codeCompare(pParse, pL, pR, opx, r1, r2, addrDone, p5, isCommuted);
109750    testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
109751    testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
109752    testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
109753    testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
109754    testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
109755    testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
109756    sqlite3ReleaseTempReg(pParse, regFree1);
109757    sqlite3ReleaseTempReg(pParse, regFree2);
109758    if( (opx==TK_LT || opx==TK_GT) && i<nLeft-1 ){
109759      addrCmp = sqlite3VdbeAddOp0(v, OP_ElseEq);
109760      testcase(opx==TK_LT); VdbeCoverageIf(v,opx==TK_LT);
109761      testcase(opx==TK_GT); VdbeCoverageIf(v,opx==TK_GT);
109762    }
109763    if( p5==SQLITE_NULLEQ ){
109764      sqlite3VdbeAddOp2(v, OP_Integer, 0, dest);
109765    }else{
109766      sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, dest, r2);
109767    }
109768    if( i==nLeft-1 ){
109769      break;
109770    }
109771    if( opx==TK_EQ ){
109772      sqlite3VdbeAddOp2(v, OP_NotNull, dest, addrDone); VdbeCoverage(v);
109773    }else{
109774      assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
109775      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
109776      if( i==nLeft-2 ) opx = op;
109777    }
109778  }
109779  sqlite3VdbeJumpHere(v, addrCmp);
109780  sqlite3VdbeResolveLabel(v, addrDone);
109781  if( op==TK_NE ){
109782    sqlite3VdbeAddOp2(v, OP_Not, dest, dest);
109783  }
109784}
109785
109786#if SQLITE_MAX_EXPR_DEPTH>0
109787/*
109788** Check that argument nHeight is less than or equal to the maximum
109789** expression depth allowed. If it is not, leave an error message in
109790** pParse.
109791*/
109792SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
109793  int rc = SQLITE_OK;
109794  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
109795  if( nHeight>mxHeight ){
109796    sqlite3ErrorMsg(pParse,
109797       "Expression tree is too large (maximum depth %d)", mxHeight
109798    );
109799    rc = SQLITE_ERROR;
109800  }
109801  return rc;
109802}
109803
109804/* The following three functions, heightOfExpr(), heightOfExprList()
109805** and heightOfSelect(), are used to determine the maximum height
109806** of any expression tree referenced by the structure passed as the
109807** first argument.
109808**
109809** If this maximum height is greater than the current value pointed
109810** to by pnHeight, the second parameter, then set *pnHeight to that
109811** value.
109812*/
109813static void heightOfExpr(const Expr *p, int *pnHeight){
109814  if( p ){
109815    if( p->nHeight>*pnHeight ){
109816      *pnHeight = p->nHeight;
109817    }
109818  }
109819}
109820static void heightOfExprList(const ExprList *p, int *pnHeight){
109821  if( p ){
109822    int i;
109823    for(i=0; i<p->nExpr; i++){
109824      heightOfExpr(p->a[i].pExpr, pnHeight);
109825    }
109826  }
109827}
109828static void heightOfSelect(const Select *pSelect, int *pnHeight){
109829  const Select *p;
109830  for(p=pSelect; p; p=p->pPrior){
109831    heightOfExpr(p->pWhere, pnHeight);
109832    heightOfExpr(p->pHaving, pnHeight);
109833    heightOfExpr(p->pLimit, pnHeight);
109834    heightOfExprList(p->pEList, pnHeight);
109835    heightOfExprList(p->pGroupBy, pnHeight);
109836    heightOfExprList(p->pOrderBy, pnHeight);
109837  }
109838}
109839
109840/*
109841** Set the Expr.nHeight variable in the structure passed as an
109842** argument. An expression with no children, Expr.pList or
109843** Expr.pSelect member has a height of 1. Any other expression
109844** has a height equal to the maximum height of any other
109845** referenced Expr plus one.
109846**
109847** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
109848** if appropriate.
109849*/
109850static void exprSetHeight(Expr *p){
109851  int nHeight = p->pLeft ? p->pLeft->nHeight : 0;
109852  if( NEVER(p->pRight) && p->pRight->nHeight>nHeight ){
109853    nHeight = p->pRight->nHeight;
109854  }
109855  if( ExprUseXSelect(p) ){
109856    heightOfSelect(p->x.pSelect, &nHeight);
109857  }else if( p->x.pList ){
109858    heightOfExprList(p->x.pList, &nHeight);
109859    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
109860  }
109861  p->nHeight = nHeight + 1;
109862}
109863
109864/*
109865** Set the Expr.nHeight variable using the exprSetHeight() function. If
109866** the height is greater than the maximum allowed expression depth,
109867** leave an error in pParse.
109868**
109869** Also propagate all EP_Propagate flags from the Expr.x.pList into
109870** Expr.flags.
109871*/
109872SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
109873  if( pParse->nErr ) return;
109874  exprSetHeight(p);
109875  sqlite3ExprCheckHeight(pParse, p->nHeight);
109876}
109877
109878/*
109879** Return the maximum height of any expression tree referenced
109880** by the select statement passed as an argument.
109881*/
109882SQLITE_PRIVATE int sqlite3SelectExprHeight(const Select *p){
109883  int nHeight = 0;
109884  heightOfSelect(p, &nHeight);
109885  return nHeight;
109886}
109887#else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
109888/*
109889** Propagate all EP_Propagate flags from the Expr.x.pList into
109890** Expr.flags.
109891*/
109892SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
109893  if( pParse->nErr ) return;
109894  if( p && ExprUseXList(p) && p->x.pList ){
109895    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
109896  }
109897}
109898#define exprSetHeight(y)
109899#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
109900
109901/*
109902** Set the error offset for an Expr node, if possible.
109903*/
109904SQLITE_PRIVATE void sqlite3ExprSetErrorOffset(Expr *pExpr, int iOfst){
109905  if( pExpr==0 ) return;
109906  if( NEVER(ExprUseWJoin(pExpr)) ) return;
109907  pExpr->w.iOfst = iOfst;
109908}
109909
109910/*
109911** This routine is the core allocator for Expr nodes.
109912**
109913** Construct a new expression node and return a pointer to it.  Memory
109914** for this node and for the pToken argument is a single allocation
109915** obtained from sqlite3DbMalloc().  The calling function
109916** is responsible for making sure the node eventually gets freed.
109917**
109918** If dequote is true, then the token (if it exists) is dequoted.
109919** If dequote is false, no dequoting is performed.  The deQuote
109920** parameter is ignored if pToken is NULL or if the token does not
109921** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
109922** then the EP_DblQuoted flag is set on the expression node.
109923**
109924** Special case (tag-20240227-a):  If op==TK_INTEGER and pToken points to
109925** a string that can be translated into a 32-bit integer, then the token is
109926** not stored in u.zToken.  Instead, the integer values is written
109927** into u.iValue and the EP_IntValue flag is set. No extra storage
109928** is allocated to hold the integer text and the dequote flag is ignored.
109929** See also tag-20240227-b.
109930*/
109931SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
109932  sqlite3 *db,            /* Handle for sqlite3DbMallocRawNN() */
109933  int op,                 /* Expression opcode */
109934  const Token *pToken,    /* Token argument.  Might be NULL */
109935  int dequote             /* True to dequote */
109936){
109937  Expr *pNew;
109938  int nExtra = 0;
109939  int iValue = 0;
109940
109941  assert( db!=0 );
109942  if( pToken ){
109943    if( op!=TK_INTEGER || pToken->z==0
109944          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
109945      nExtra = pToken->n+1;  /* tag-20240227-a */
109946      assert( iValue>=0 );
109947    }
109948  }
109949  pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
109950  if( pNew ){
109951    memset(pNew, 0, sizeof(Expr));
109952    pNew->op = (u8)op;
109953    pNew->iAgg = -1;
109954    if( pToken ){
109955      if( nExtra==0 ){
109956        pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
109957        pNew->u.iValue = iValue;
109958      }else{
109959        pNew->u.zToken = (char*)&pNew[1];
109960        assert( pToken->z!=0 || pToken->n==0 );
109961        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
109962        pNew->u.zToken[pToken->n] = 0;
109963        if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
109964          sqlite3DequoteExpr(pNew);
109965        }
109966      }
109967    }
109968#if SQLITE_MAX_EXPR_DEPTH>0
109969    pNew->nHeight = 1;
109970#endif
109971  }
109972  return pNew;
109973}
109974
109975/*
109976** Allocate a new expression node from a zero-terminated token that has
109977** already been dequoted.
109978*/
109979SQLITE_PRIVATE Expr *sqlite3Expr(
109980  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
109981  int op,                 /* Expression opcode */
109982  const char *zToken      /* Token argument.  Might be NULL */
109983){
109984  Token x;
109985  x.z = zToken;
109986  x.n = sqlite3Strlen30(zToken);
109987  return sqlite3ExprAlloc(db, op, &x, 0);
109988}
109989
109990/*
109991** Attach subtrees pLeft and pRight to the Expr node pRoot.
109992**
109993** If pRoot==NULL that means that a memory allocation error has occurred.
109994** In that case, delete the subtrees pLeft and pRight.
109995*/
109996SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
109997  sqlite3 *db,
109998  Expr *pRoot,
109999  Expr *pLeft,
110000  Expr *pRight
110001){
110002  if( pRoot==0 ){
110003    assert( db->mallocFailed );
110004    sqlite3ExprDelete(db, pLeft);
110005    sqlite3ExprDelete(db, pRight);
110006  }else{
110007    assert( ExprUseXList(pRoot) );
110008    assert( pRoot->x.pSelect==0 );
110009    if( pRight ){
110010      pRoot->pRight = pRight;
110011      pRoot->flags |= EP_Propagate & pRight->flags;
110012#if SQLITE_MAX_EXPR_DEPTH>0
110013      pRoot->nHeight = pRight->nHeight+1;
110014    }else{
110015      pRoot->nHeight = 1;
110016#endif
110017    }
110018    if( pLeft ){
110019      pRoot->pLeft = pLeft;
110020      pRoot->flags |= EP_Propagate & pLeft->flags;
110021#if SQLITE_MAX_EXPR_DEPTH>0
110022      if( pLeft->nHeight>=pRoot->nHeight ){
110023        pRoot->nHeight = pLeft->nHeight+1;
110024      }
110025#endif
110026    }
110027  }
110028}
110029
110030/*
110031** Allocate an Expr node which joins as many as two subtrees.
110032**
110033** One or both of the subtrees can be NULL.  Return a pointer to the new
110034** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
110035** free the subtrees and return NULL.
110036*/
110037SQLITE_PRIVATE Expr *sqlite3PExpr(
110038  Parse *pParse,          /* Parsing context */
110039  int op,                 /* Expression opcode */
110040  Expr *pLeft,            /* Left operand */
110041  Expr *pRight            /* Right operand */
110042){
110043  Expr *p;
110044  p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
110045  if( p ){
110046    memset(p, 0, sizeof(Expr));
110047    p->op = op & 0xff;
110048    p->iAgg = -1;
110049    sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
110050    sqlite3ExprCheckHeight(pParse, p->nHeight);
110051  }else{
110052    sqlite3ExprDelete(pParse->db, pLeft);
110053    sqlite3ExprDelete(pParse->db, pRight);
110054  }
110055  return p;
110056}
110057
110058/*
110059** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
110060** do a memory allocation failure) then delete the pSelect object.
110061*/
110062SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
110063  if( pExpr ){
110064    pExpr->x.pSelect = pSelect;
110065    ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
110066    sqlite3ExprSetHeightAndFlags(pParse, pExpr);
110067  }else{
110068    assert( pParse->db->mallocFailed );
110069    sqlite3SelectDelete(pParse->db, pSelect);
110070  }
110071}
110072
110073/*
110074** Expression list pEList is a list of vector values. This function
110075** converts the contents of pEList to a VALUES(...) Select statement
110076** returning 1 row for each element of the list. For example, the
110077** expression list:
110078**
110079**   ( (1,2), (3,4) (5,6) )
110080**
110081** is translated to the equivalent of:
110082**
110083**   VALUES(1,2), (3,4), (5,6)
110084**
110085** Each of the vector values in pEList must contain exactly nElem terms.
110086** If a list element that is not a vector or does not contain nElem terms,
110087** an error message is left in pParse.
110088**
110089** This is used as part of processing IN(...) expressions with a list
110090** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))".
110091*/
110092SQLITE_PRIVATE Select *sqlite3ExprListToValues(Parse *pParse, int nElem, ExprList *pEList){
110093  int ii;
110094  Select *pRet = 0;
110095  assert( nElem>1 );
110096  for(ii=0; ii<pEList->nExpr; ii++){
110097    Select *pSel;
110098    Expr *pExpr = pEList->a[ii].pExpr;
110099    int nExprElem;
110100    if( pExpr->op==TK_VECTOR ){
110101      assert( ExprUseXList(pExpr) );
110102      nExprElem = pExpr->x.pList->nExpr;
110103    }else{
110104      nExprElem = 1;
110105    }
110106    if( nExprElem!=nElem ){
110107      sqlite3ErrorMsg(pParse, "IN(...) element has %d term%s - expected %d",
110108          nExprElem, nExprElem>1?"s":"", nElem
110109      );
110110      break;
110111    }
110112    assert( ExprUseXList(pExpr) );
110113    pSel = sqlite3SelectNew(pParse, pExpr->x.pList, 0, 0, 0, 0, 0, SF_Values,0);
110114    pExpr->x.pList = 0;
110115    if( pSel ){
110116      if( pRet ){
110117        pSel->op = TK_ALL;
110118        pSel->pPrior = pRet;
110119      }
110120      pRet = pSel;
110121    }
110122  }
110123
110124  if( pRet && pRet->pPrior ){
110125    pRet->selFlags |= SF_MultiValue;
110126  }
110127  sqlite3ExprListDelete(pParse->db, pEList);
110128  return pRet;
110129}
110130
110131/*
110132** Join two expressions using an AND operator.  If either expression is
110133** NULL, then just return the other expression.
110134**
110135** If one side or the other of the AND is known to be false, and neither side
110136** is part of an ON clause, then instead of returning an AND expression,
110137** just return a constant expression with a value of false.
110138*/
110139SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
110140  sqlite3 *db = pParse->db;
110141  if( pLeft==0  ){
110142    return pRight;
110143  }else if( pRight==0 ){
110144    return pLeft;
110145  }else{
110146    u32 f = pLeft->flags | pRight->flags;
110147    if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse))==EP_IsFalse
110148     && !IN_RENAME_OBJECT
110149    ){
110150      sqlite3ExprDeferredDelete(pParse, pLeft);
110151      sqlite3ExprDeferredDelete(pParse, pRight);
110152      return sqlite3Expr(db, TK_INTEGER, "0");
110153    }else{
110154      return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
110155    }
110156  }
110157}
110158
110159/*
110160** Construct a new expression node for a function with multiple
110161** arguments.
110162*/
110163SQLITE_PRIVATE Expr *sqlite3ExprFunction(
110164  Parse *pParse,        /* Parsing context */
110165  ExprList *pList,      /* Argument list */
110166  const Token *pToken,  /* Name of the function */
110167  int eDistinct         /* SF_Distinct or SF_ALL or 0 */
110168){
110169  Expr *pNew;
110170  sqlite3 *db = pParse->db;
110171  assert( pToken );
110172  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
110173  if( pNew==0 ){
110174    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
110175    return 0;
110176  }
110177  assert( !ExprHasProperty(pNew, EP_InnerON|EP_OuterON) );
110178  pNew->w.iOfst = (int)(pToken->z - pParse->zTail);
110179  if( pList
110180   && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG]
110181   && !pParse->nested
110182  ){
110183    sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
110184  }
110185  pNew->x.pList = pList;
110186  ExprSetProperty(pNew, EP_HasFunc);
110187  assert( ExprUseXList(pNew) );
110188  sqlite3ExprSetHeightAndFlags(pParse, pNew);
110189  if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
110190  return pNew;
110191}
110192
110193/*
110194** Report an error when attempting to use an ORDER BY clause within
110195** the arguments of a non-aggregate function.
110196*/
110197SQLITE_PRIVATE void sqlite3ExprOrderByAggregateError(Parse *pParse, Expr *p){
110198  sqlite3ErrorMsg(pParse,
110199     "ORDER BY may not be used with non-aggregate %#T()", p
110200  );
110201}
110202
110203/*
110204** Attach an ORDER BY clause to a function call.
110205**
110206**     functionname( arguments ORDER BY sortlist )
110207**     \_____________________/          \______/
110208**             pExpr                    pOrderBy
110209**
110210** The ORDER BY clause is inserted into a new Expr node of type TK_ORDER
110211** and added to the Expr.pLeft field of the parent TK_FUNCTION node.
110212*/
110213SQLITE_PRIVATE void sqlite3ExprAddFunctionOrderBy(
110214  Parse *pParse,        /* Parsing context */
110215  Expr *pExpr,          /* The function call to which ORDER BY is to be added */
110216  ExprList *pOrderBy    /* The ORDER BY clause to add */
110217){
110218  Expr *pOB;
110219  sqlite3 *db = pParse->db;
110220  if( NEVER(pOrderBy==0) ){
110221    assert( db->mallocFailed );
110222    return;
110223  }
110224  if( pExpr==0 ){
110225    assert( db->mallocFailed );
110226    sqlite3ExprListDelete(db, pOrderBy);
110227    return;
110228  }
110229  assert( pExpr->op==TK_FUNCTION );
110230  assert( pExpr->pLeft==0 );
110231  assert( ExprUseXList(pExpr) );
110232  if( pExpr->x.pList==0 || NEVER(pExpr->x.pList->nExpr==0) ){
110233    /* Ignore ORDER BY on zero-argument aggregates */
110234    sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pOrderBy);
110235    return;
110236  }
110237  if( IsWindowFunc(pExpr) ){
110238    sqlite3ExprOrderByAggregateError(pParse, pExpr);
110239    sqlite3ExprListDelete(db, pOrderBy);
110240    return;
110241  }
110242
110243  pOB = sqlite3ExprAlloc(db, TK_ORDER, 0, 0);
110244  if( pOB==0 ){
110245    sqlite3ExprListDelete(db, pOrderBy);
110246    return;
110247  }
110248  pOB->x.pList = pOrderBy;
110249  assert( ExprUseXList(pOB) );
110250  pExpr->pLeft = pOB;
110251  ExprSetProperty(pOB, EP_FullSize);
110252}
110253
110254/*
110255** Check to see if a function is usable according to current access
110256** rules:
110257**
110258**    SQLITE_FUNC_DIRECT    -     Only usable from top-level SQL
110259**
110260**    SQLITE_FUNC_UNSAFE    -     Usable if TRUSTED_SCHEMA or from
110261**                                top-level SQL
110262**
110263** If the function is not usable, create an error.
110264*/
110265SQLITE_PRIVATE void sqlite3ExprFunctionUsable(
110266  Parse *pParse,         /* Parsing and code generating context */
110267  const Expr *pExpr,     /* The function invocation */
110268  const FuncDef *pDef    /* The function being invoked */
110269){
110270  assert( !IN_RENAME_OBJECT );
110271  assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
110272  if( ExprHasProperty(pExpr, EP_FromDDL) ){
110273    if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
110274     || (pParse->db->flags & SQLITE_TrustedSchema)==0
110275    ){
110276      /* Functions prohibited in triggers and views if:
110277      **     (1) tagged with SQLITE_DIRECTONLY
110278      **     (2) not tagged with SQLITE_INNOCUOUS (which means it
110279      **         is tagged with SQLITE_FUNC_UNSAFE) and
110280      **         SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
110281      **         that the schema is possibly tainted).
110282      */
110283      sqlite3ErrorMsg(pParse, "unsafe use of %#T()", pExpr);
110284    }
110285  }
110286}
110287
110288/*
110289** Assign a variable number to an expression that encodes a wildcard
110290** in the original SQL statement.
110291**
110292** Wildcards consisting of a single "?" are assigned the next sequential
110293** variable number.
110294**
110295** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
110296** sure "nnn" is not too big to avoid a denial of service attack when
110297** the SQL statement comes from an external source.
110298**
110299** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
110300** as the previous instance of the same wildcard.  Or if this is the first
110301** instance of the wildcard, the next sequential variable number is
110302** assigned.
110303*/
110304SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
110305  sqlite3 *db = pParse->db;
110306  const char *z;
110307  ynVar x;
110308
110309  if( pExpr==0 ) return;
110310  assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
110311  z = pExpr->u.zToken;
110312  assert( z!=0 );
110313  assert( z[0]!=0 );
110314  assert( n==(u32)sqlite3Strlen30(z) );
110315  if( z[1]==0 ){
110316    /* Wildcard of the form "?".  Assign the next variable number */
110317    assert( z[0]=='?' );
110318    x = (ynVar)(++pParse->nVar);
110319  }else{
110320    int doAdd = 0;
110321    if( z[0]=='?' ){
110322      /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
110323      ** use it as the variable number */
110324      i64 i;
110325      int bOk;
110326      if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
110327        i = z[1]-'0';  /* The common case of ?N for a single digit N */
110328        bOk = 1;
110329      }else{
110330        bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
110331      }
110332      testcase( i==0 );
110333      testcase( i==1 );
110334      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
110335      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
110336      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
110337        sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
110338            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
110339        sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
110340        return;
110341      }
110342      x = (ynVar)i;
110343      if( x>pParse->nVar ){
110344        pParse->nVar = (int)x;
110345        doAdd = 1;
110346      }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
110347        doAdd = 1;
110348      }
110349    }else{
110350      /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
110351      ** number as the prior appearance of the same name, or if the name
110352      ** has never appeared before, reuse the same variable number
110353      */
110354      x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
110355      if( x==0 ){
110356        x = (ynVar)(++pParse->nVar);
110357        doAdd = 1;
110358      }
110359    }
110360    if( doAdd ){
110361      pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
110362    }
110363  }
110364  pExpr->iColumn = x;
110365  if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
110366    sqlite3ErrorMsg(pParse, "too many SQL variables");
110367    sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
110368  }
110369}
110370
110371/*
110372** Recursively delete an expression tree.
110373*/
110374static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
110375  assert( p!=0 );
110376  assert( db!=0 );
110377exprDeleteRestart:
110378  assert( !ExprUseUValue(p) || p->u.iValue>=0 );
110379  assert( !ExprUseYWin(p) || !ExprUseYSub(p) );
110380  assert( !ExprUseYWin(p) || p->y.pWin!=0 || db->mallocFailed );
110381  assert( p->op!=TK_FUNCTION || !ExprUseYSub(p) );
110382#ifdef SQLITE_DEBUG
110383  if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
110384    assert( p->pLeft==0 );
110385    assert( p->pRight==0 );
110386    assert( !ExprUseXSelect(p) || p->x.pSelect==0 );
110387    assert( !ExprUseXList(p) || p->x.pList==0 );
110388  }
110389#endif
110390  if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
110391    /* The Expr.x union is never used at the same time as Expr.pRight */
110392    assert( (ExprUseXList(p) && p->x.pList==0) || p->pRight==0 );
110393    if( p->pRight ){
110394      assert( !ExprHasProperty(p, EP_WinFunc) );
110395      sqlite3ExprDeleteNN(db, p->pRight);
110396    }else if( ExprUseXSelect(p) ){
110397      assert( !ExprHasProperty(p, EP_WinFunc) );
110398      sqlite3SelectDelete(db, p->x.pSelect);
110399    }else{
110400      sqlite3ExprListDelete(db, p->x.pList);
110401#ifndef SQLITE_OMIT_WINDOWFUNC
110402      if( ExprHasProperty(p, EP_WinFunc) ){
110403        sqlite3WindowDelete(db, p->y.pWin);
110404      }
110405#endif
110406    }
110407    if( p->pLeft && p->op!=TK_SELECT_COLUMN ){
110408      Expr *pLeft = p->pLeft;
110409      if( !ExprHasProperty(p, EP_Static)
110410       && !ExprHasProperty(pLeft, EP_Static)
110411      ){
110412        /* Avoid unnecessary recursion on unary operators */
110413        sqlite3DbNNFreeNN(db, p);
110414        p = pLeft;
110415        goto exprDeleteRestart;
110416      }else{
110417        sqlite3ExprDeleteNN(db, pLeft);
110418      }
110419    }
110420  }
110421  if( !ExprHasProperty(p, EP_Static) ){
110422    sqlite3DbNNFreeNN(db, p);
110423  }
110424}
110425SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
110426  if( p ) sqlite3ExprDeleteNN(db, p);
110427}
110428SQLITE_PRIVATE void sqlite3ExprDeleteGeneric(sqlite3 *db, void *p){
110429  if( ALWAYS(p) ) sqlite3ExprDeleteNN(db, (Expr*)p);
110430}
110431
110432/*
110433** Clear both elements of an OnOrUsing object
110434*/
110435SQLITE_PRIVATE void sqlite3ClearOnOrUsing(sqlite3 *db, OnOrUsing *p){
110436  if( p==0 ){
110437    /* Nothing to clear */
110438  }else if( p->pOn ){
110439    sqlite3ExprDeleteNN(db, p->pOn);
110440  }else if( p->pUsing ){
110441    sqlite3IdListDelete(db, p->pUsing);
110442  }
110443}
110444
110445/*
110446** Arrange to cause pExpr to be deleted when the pParse is deleted.
110447** This is similar to sqlite3ExprDelete() except that the delete is
110448** deferred until the pParse is deleted.
110449**
110450** The pExpr might be deleted immediately on an OOM error.
110451**
110452** Return 0 if the delete was successfully deferred.  Return non-zero
110453** if the delete happened immediately because of an OOM.
110454*/
110455SQLITE_PRIVATE int sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){
110456  return 0==sqlite3ParserAddCleanup(pParse, sqlite3ExprDeleteGeneric, pExpr);
110457}
110458
110459/* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
110460** expression.
110461*/
110462SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
110463  if( p ){
110464    if( IN_RENAME_OBJECT ){
110465      sqlite3RenameExprUnmap(pParse, p);
110466    }
110467    sqlite3ExprDeleteNN(pParse->db, p);
110468  }
110469}
110470
110471/*
110472** Return the number of bytes allocated for the expression structure
110473** passed as the first argument. This is always one of EXPR_FULLSIZE,
110474** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
110475*/
110476static int exprStructSize(const Expr *p){
110477  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
110478  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
110479  return EXPR_FULLSIZE;
110480}
110481
110482/*
110483** The dupedExpr*Size() routines each return the number of bytes required
110484** to store a copy of an expression or expression tree.  They differ in
110485** how much of the tree is measured.
110486**
110487**     dupedExprStructSize()     Size of only the Expr structure
110488**     dupedExprNodeSize()       Size of Expr + space for token
110489**     dupedExprSize()           Expr + token + subtree components
110490**
110491***************************************************************************
110492**
110493** The dupedExprStructSize() function returns two values OR-ed together:
110494** (1) the space required for a copy of the Expr structure only and
110495** (2) the EP_xxx flags that indicate what the structure size should be.
110496** The return values is always one of:
110497**
110498**      EXPR_FULLSIZE
110499**      EXPR_REDUCEDSIZE   | EP_Reduced
110500**      EXPR_TOKENONLYSIZE | EP_TokenOnly
110501**
110502** The size of the structure can be found by masking the return value
110503** of this routine with 0xfff.  The flags can be found by masking the
110504** return value with EP_Reduced|EP_TokenOnly.
110505**
110506** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
110507** (unreduced) Expr objects as they or originally constructed by the parser.
110508** During expression analysis, extra information is computed and moved into
110509** later parts of the Expr object and that extra information might get chopped
110510** off if the expression is reduced.  Note also that it does not work to
110511** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
110512** to reduce a pristine expression tree from the parser.  The implementation
110513** of dupedExprStructSize() contain multiple assert() statements that attempt
110514** to enforce this constraint.
110515*/
110516static int dupedExprStructSize(const Expr *p, int flags){
110517  int nSize;
110518  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
110519  assert( EXPR_FULLSIZE<=0xfff );
110520  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
110521  if( 0==flags || ExprHasProperty(p, EP_FullSize) ){
110522    nSize = EXPR_FULLSIZE;
110523  }else{
110524    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
110525    assert( !ExprHasProperty(p, EP_OuterON) );
110526    assert( !ExprHasVVAProperty(p, EP_NoReduce) );
110527    if( p->pLeft || p->x.pList ){
110528      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
110529    }else{
110530      assert( p->pRight==0 );
110531      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
110532    }
110533  }
110534  return nSize;
110535}
110536
110537/*
110538** This function returns the space in bytes required to store the copy
110539** of the Expr structure and a copy of the Expr.u.zToken string (if that
110540** string is defined.)
110541*/
110542static int dupedExprNodeSize(const Expr *p, int flags){
110543  int nByte = dupedExprStructSize(p, flags) & 0xfff;
110544  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
110545    nByte += sqlite3Strlen30NN(p->u.zToken)+1;
110546  }
110547  return ROUND8(nByte);
110548}
110549
110550/*
110551** Return the number of bytes required to create a duplicate of the
110552** expression passed as the first argument.
110553**
110554** The value returned includes space to create a copy of the Expr struct
110555** itself and the buffer referred to by Expr.u.zToken, if any.
110556**
110557** The return value includes space to duplicate all Expr nodes in the
110558** tree formed by Expr.pLeft and Expr.pRight, but not any other
110559** substructure such as Expr.x.pList, Expr.x.pSelect, and Expr.y.pWin.
110560*/
110561static int dupedExprSize(const Expr *p){
110562  int nByte;
110563  assert( p!=0 );
110564  nByte = dupedExprNodeSize(p, EXPRDUP_REDUCE);
110565  if( p->pLeft ) nByte += dupedExprSize(p->pLeft);
110566  if( p->pRight ) nByte += dupedExprSize(p->pRight);
110567  assert( nByte==ROUND8(nByte) );
110568  return nByte;
110569}
110570
110571/*
110572** An EdupBuf is a memory allocation used to stored multiple Expr objects
110573** together with their Expr.zToken content.  This is used to help implement
110574** compression while doing sqlite3ExprDup().  The top-level Expr does the
110575** allocation for itself and many of its decendents, then passes an instance
110576** of the structure down into exprDup() so that they decendents can have
110577** access to that memory.
110578*/
110579typedef struct EdupBuf EdupBuf;
110580struct EdupBuf {
110581  u8 *zAlloc;          /* Memory space available for storage */
110582#ifdef SQLITE_DEBUG
110583  u8 *zEnd;            /* First byte past the end of memory */
110584#endif
110585};
110586
110587/*
110588** This function is similar to sqlite3ExprDup(), except that if pEdupBuf
110589** is not NULL then it points to memory that can be used to store a copy
110590** of the input Expr p together with its p->u.zToken (if any).  pEdupBuf
110591** is updated with the new buffer tail prior to returning.
110592*/
110593static Expr *exprDup(
110594  sqlite3 *db,          /* Database connection (for memory allocation) */
110595  const Expr *p,        /* Expr tree to be duplicated */
110596  int dupFlags,         /* EXPRDUP_REDUCE for compression.  0 if not */
110597  EdupBuf *pEdupBuf     /* Preallocated storage space, or NULL */
110598){
110599  Expr *pNew;           /* Value to return */
110600  EdupBuf sEdupBuf;     /* Memory space from which to build Expr object */
110601  u32 staticFlag;       /* EP_Static if space not obtained from malloc */
110602  int nToken = -1;       /* Space needed for p->u.zToken.  -1 means unknown */
110603
110604  assert( db!=0 );
110605  assert( p );
110606  assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
110607  assert( pEdupBuf==0 || dupFlags==EXPRDUP_REDUCE );
110608
110609  /* Figure out where to write the new Expr structure. */
110610  if( pEdupBuf ){
110611    sEdupBuf.zAlloc = pEdupBuf->zAlloc;
110612#ifdef SQLITE_DEBUG
110613    sEdupBuf.zEnd = pEdupBuf->zEnd;
110614#endif
110615    staticFlag = EP_Static;
110616    assert( sEdupBuf.zAlloc!=0 );
110617    assert( dupFlags==EXPRDUP_REDUCE );
110618  }else{
110619    int nAlloc;
110620    if( dupFlags ){
110621      nAlloc = dupedExprSize(p);
110622    }else if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
110623      nToken = sqlite3Strlen30NN(p->u.zToken)+1;
110624      nAlloc = ROUND8(EXPR_FULLSIZE + nToken);
110625    }else{
110626      nToken = 0;
110627      nAlloc = ROUND8(EXPR_FULLSIZE);
110628    }
110629    assert( nAlloc==ROUND8(nAlloc) );
110630    sEdupBuf.zAlloc = sqlite3DbMallocRawNN(db, nAlloc);
110631#ifdef SQLITE_DEBUG
110632    sEdupBuf.zEnd = sEdupBuf.zAlloc ? sEdupBuf.zAlloc+nAlloc : 0;
110633#endif
110634
110635    staticFlag = 0;
110636  }
110637  pNew = (Expr *)sEdupBuf.zAlloc;
110638  assert( EIGHT_BYTE_ALIGNMENT(pNew) );
110639
110640  if( pNew ){
110641    /* Set nNewSize to the size allocated for the structure pointed to
110642    ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
110643    ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
110644    ** by the copy of the p->u.zToken string (if any).
110645    */
110646    const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
110647    int nNewSize = nStructSize & 0xfff;
110648    if( nToken<0 ){
110649      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
110650        nToken = sqlite3Strlen30(p->u.zToken) + 1;
110651      }else{
110652        nToken = 0;
110653      }
110654    }
110655    if( dupFlags ){
110656      assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >= nNewSize+nToken );
110657      assert( ExprHasProperty(p, EP_Reduced)==0 );
110658      memcpy(sEdupBuf.zAlloc, p, nNewSize);
110659    }else{
110660      u32 nSize = (u32)exprStructSize(p);
110661      assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >=
110662                                                   (int)EXPR_FULLSIZE+nToken );
110663      memcpy(sEdupBuf.zAlloc, p, nSize);
110664      if( nSize<EXPR_FULLSIZE ){
110665        memset(&sEdupBuf.zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
110666      }
110667      nNewSize = EXPR_FULLSIZE;
110668    }
110669
110670    /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
110671    pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
110672    pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
110673    pNew->flags |= staticFlag;
110674    ExprClearVVAProperties(pNew);
110675    if( dupFlags ){
110676      ExprSetVVAProperty(pNew, EP_Immutable);
110677    }
110678
110679    /* Copy the p->u.zToken string, if any. */
110680    assert( nToken>=0 );
110681    if( nToken>0 ){
110682      char *zToken = pNew->u.zToken = (char*)&sEdupBuf.zAlloc[nNewSize];
110683      memcpy(zToken, p->u.zToken, nToken);
110684      nNewSize += nToken;
110685    }
110686    sEdupBuf.zAlloc += ROUND8(nNewSize);
110687
110688    if( ((p->flags|pNew->flags)&(EP_TokenOnly|EP_Leaf))==0 ){
110689
110690      /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
110691      if( ExprUseXSelect(p) ){
110692        pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
110693      }else{
110694        pNew->x.pList = sqlite3ExprListDup(db, p->x.pList,
110695                           p->op!=TK_ORDER ? dupFlags : 0);
110696      }
110697
110698#ifndef SQLITE_OMIT_WINDOWFUNC
110699      if( ExprHasProperty(p, EP_WinFunc) ){
110700        pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
110701        assert( ExprHasProperty(pNew, EP_WinFunc) );
110702      }
110703#endif /* SQLITE_OMIT_WINDOWFUNC */
110704
110705      /* Fill in pNew->pLeft and pNew->pRight. */
110706      if( dupFlags ){
110707        if( p->op==TK_SELECT_COLUMN ){
110708          pNew->pLeft = p->pLeft;
110709          assert( p->pRight==0
110710               || p->pRight==p->pLeft
110711               || ExprHasProperty(p->pLeft, EP_Subquery) );
110712        }else{
110713          pNew->pLeft = p->pLeft ?
110714                      exprDup(db, p->pLeft, EXPRDUP_REDUCE, &sEdupBuf) : 0;
110715        }
110716        pNew->pRight = p->pRight ?
110717                       exprDup(db, p->pRight, EXPRDUP_REDUCE, &sEdupBuf) : 0;
110718      }else{
110719        if( p->op==TK_SELECT_COLUMN ){
110720          pNew->pLeft = p->pLeft;
110721          assert( p->pRight==0
110722               || p->pRight==p->pLeft
110723               || ExprHasProperty(p->pLeft, EP_Subquery) );
110724        }else{
110725          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
110726        }
110727        pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
110728      }
110729    }
110730  }
110731  if( pEdupBuf ) memcpy(pEdupBuf, &sEdupBuf, sizeof(sEdupBuf));
110732  assert( sEdupBuf.zAlloc <= sEdupBuf.zEnd );
110733  return pNew;
110734}
110735
110736/*
110737** Create and return a deep copy of the object passed as the second
110738** argument. If an OOM condition is encountered, NULL is returned
110739** and the db->mallocFailed flag set.
110740*/
110741#ifndef SQLITE_OMIT_CTE
110742SQLITE_PRIVATE With *sqlite3WithDup(sqlite3 *db, With *p){
110743  With *pRet = 0;
110744  if( p ){
110745    sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
110746    pRet = sqlite3DbMallocZero(db, nByte);
110747    if( pRet ){
110748      int i;
110749      pRet->nCte = p->nCte;
110750      for(i=0; i<p->nCte; i++){
110751        pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
110752        pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
110753        pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
110754        pRet->a[i].eM10d = p->a[i].eM10d;
110755      }
110756    }
110757  }
110758  return pRet;
110759}
110760#else
110761# define sqlite3WithDup(x,y) 0
110762#endif
110763
110764#ifndef SQLITE_OMIT_WINDOWFUNC
110765/*
110766** The gatherSelectWindows() procedure and its helper routine
110767** gatherSelectWindowsCallback() are used to scan all the expressions
110768** an a newly duplicated SELECT statement and gather all of the Window
110769** objects found there, assembling them onto the linked list at Select->pWin.
110770*/
110771static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
110772  if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
110773    Select *pSelect = pWalker->u.pSelect;
110774    Window *pWin = pExpr->y.pWin;
110775    assert( pWin );
110776    assert( IsWindowFunc(pExpr) );
110777    assert( pWin->ppThis==0 );
110778    sqlite3WindowLink(pSelect, pWin);
110779  }
110780  return WRC_Continue;
110781}
110782static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
110783  return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
110784}
110785static void gatherSelectWindows(Select *p){
110786  Walker w;
110787  w.xExprCallback = gatherSelectWindowsCallback;
110788  w.xSelectCallback = gatherSelectWindowsSelectCallback;
110789  w.xSelectCallback2 = 0;
110790  w.pParse = 0;
110791  w.u.pSelect = p;
110792  sqlite3WalkSelect(&w, p);
110793}
110794#endif
110795
110796
110797/*
110798** The following group of routines make deep copies of expressions,
110799** expression lists, ID lists, and select statements.  The copies can
110800** be deleted (by being passed to their respective ...Delete() routines)
110801** without effecting the originals.
110802**
110803** The expression list, ID, and source lists return by sqlite3ExprListDup(),
110804** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
110805** by subsequent calls to sqlite*ListAppend() routines.
110806**
110807** Any tables that the SrcList might point to are not duplicated.
110808**
110809** The flags parameter contains a combination of the EXPRDUP_XXX flags.
110810** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
110811** truncated version of the usual Expr structure that will be stored as
110812** part of the in-memory representation of the database schema.
110813*/
110814SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, const Expr *p, int flags){
110815  assert( flags==0 || flags==EXPRDUP_REDUCE );
110816  return p ? exprDup(db, p, flags, 0) : 0;
110817}
110818SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, const ExprList *p, int flags){
110819  ExprList *pNew;
110820  struct ExprList_item *pItem;
110821  const struct ExprList_item *pOldItem;
110822  int i;
110823  Expr *pPriorSelectColOld = 0;
110824  Expr *pPriorSelectColNew = 0;
110825  assert( db!=0 );
110826  if( p==0 ) return 0;
110827  pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
110828  if( pNew==0 ) return 0;
110829  pNew->nExpr = p->nExpr;
110830  pNew->nAlloc = p->nAlloc;
110831  pItem = pNew->a;
110832  pOldItem = p->a;
110833  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
110834    Expr *pOldExpr = pOldItem->pExpr;
110835    Expr *pNewExpr;
110836    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
110837    if( pOldExpr
110838     && pOldExpr->op==TK_SELECT_COLUMN
110839     && (pNewExpr = pItem->pExpr)!=0
110840    ){
110841      if( pNewExpr->pRight ){
110842        pPriorSelectColOld = pOldExpr->pRight;
110843        pPriorSelectColNew = pNewExpr->pRight;
110844        pNewExpr->pLeft = pNewExpr->pRight;
110845      }else{
110846        if( pOldExpr->pLeft!=pPriorSelectColOld ){
110847          pPriorSelectColOld = pOldExpr->pLeft;
110848          pPriorSelectColNew = sqlite3ExprDup(db, pPriorSelectColOld, flags);
110849          pNewExpr->pRight = pPriorSelectColNew;
110850        }
110851        pNewExpr->pLeft = pPriorSelectColNew;
110852      }
110853    }
110854    pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
110855    pItem->fg = pOldItem->fg;
110856    pItem->fg.done = 0;
110857    pItem->u = pOldItem->u;
110858  }
110859  return pNew;
110860}
110861
110862/*
110863** If cursors, triggers, views and subqueries are all omitted from
110864** the build, then none of the following routines, except for
110865** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
110866** called with a NULL argument.
110867*/
110868#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
110869 || !defined(SQLITE_OMIT_SUBQUERY)
110870SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, const SrcList *p, int flags){
110871  SrcList *pNew;
110872  int i;
110873  int nByte;
110874  assert( db!=0 );
110875  if( p==0 ) return 0;
110876  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
110877  pNew = sqlite3DbMallocRawNN(db, nByte );
110878  if( pNew==0 ) return 0;
110879  pNew->nSrc = pNew->nAlloc = p->nSrc;
110880  for(i=0; i<p->nSrc; i++){
110881    SrcItem *pNewItem = &pNew->a[i];
110882    const SrcItem *pOldItem = &p->a[i];
110883    Table *pTab;
110884    pNewItem->pSchema = pOldItem->pSchema;
110885    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
110886    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
110887    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
110888    pNewItem->fg = pOldItem->fg;
110889    pNewItem->iCursor = pOldItem->iCursor;
110890    pNewItem->addrFillSub = pOldItem->addrFillSub;
110891    pNewItem->regReturn = pOldItem->regReturn;
110892    pNewItem->regResult = pOldItem->regResult;
110893    if( pNewItem->fg.isIndexedBy ){
110894      pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
110895    }else if( pNewItem->fg.isTabFunc ){
110896      pNewItem->u1.pFuncArg =
110897          sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
110898    }else{
110899      pNewItem->u1.nRow = pOldItem->u1.nRow;
110900    }
110901    pNewItem->u2 = pOldItem->u2;
110902    if( pNewItem->fg.isCte ){
110903      pNewItem->u2.pCteUse->nUse++;
110904    }
110905    pTab = pNewItem->pTab = pOldItem->pTab;
110906    if( pTab ){
110907      pTab->nTabRef++;
110908    }
110909    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
110910    if( pOldItem->fg.isUsing ){
110911      assert( pNewItem->fg.isUsing );
110912      pNewItem->u3.pUsing = sqlite3IdListDup(db, pOldItem->u3.pUsing);
110913    }else{
110914      pNewItem->u3.pOn = sqlite3ExprDup(db, pOldItem->u3.pOn, flags);
110915    }
110916    pNewItem->colUsed = pOldItem->colUsed;
110917  }
110918  return pNew;
110919}
110920SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, const IdList *p){
110921  IdList *pNew;
110922  int i;
110923  assert( db!=0 );
110924  if( p==0 ) return 0;
110925  assert( p->eU4!=EU4_EXPR );
110926  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew)+(p->nId-1)*sizeof(p->a[0]) );
110927  if( pNew==0 ) return 0;
110928  pNew->nId = p->nId;
110929  pNew->eU4 = p->eU4;
110930  for(i=0; i<p->nId; i++){
110931    struct IdList_item *pNewItem = &pNew->a[i];
110932    const struct IdList_item *pOldItem = &p->a[i];
110933    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
110934    pNewItem->u4 = pOldItem->u4;
110935  }
110936  return pNew;
110937}
110938SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, const Select *pDup, int flags){
110939  Select *pRet = 0;
110940  Select *pNext = 0;
110941  Select **pp = &pRet;
110942  const Select *p;
110943
110944  assert( db!=0 );
110945  for(p=pDup; p; p=p->pPrior){
110946    Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
110947    if( pNew==0 ) break;
110948    pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
110949    pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
110950    pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
110951    pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
110952    pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
110953    pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
110954    pNew->op = p->op;
110955    pNew->pNext = pNext;
110956    pNew->pPrior = 0;
110957    pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
110958    pNew->iLimit = 0;
110959    pNew->iOffset = 0;
110960    pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
110961    pNew->addrOpenEphm[0] = -1;
110962    pNew->addrOpenEphm[1] = -1;
110963    pNew->nSelectRow = p->nSelectRow;
110964    pNew->pWith = sqlite3WithDup(db, p->pWith);
110965#ifndef SQLITE_OMIT_WINDOWFUNC
110966    pNew->pWin = 0;
110967    pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
110968    if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
110969#endif
110970    pNew->selId = p->selId;
110971    if( db->mallocFailed ){
110972      /* Any prior OOM might have left the Select object incomplete.
110973      ** Delete the whole thing rather than allow an incomplete Select
110974      ** to be used by the code generator. */
110975      pNew->pNext = 0;
110976      sqlite3SelectDelete(db, pNew);
110977      break;
110978    }
110979    *pp = pNew;
110980    pp = &pNew->pPrior;
110981    pNext = pNew;
110982  }
110983
110984  return pRet;
110985}
110986#else
110987SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, const Select *p, int flags){
110988  assert( p==0 );
110989  return 0;
110990}
110991#endif
110992
110993
110994/*
110995** Add a new element to the end of an expression list.  If pList is
110996** initially NULL, then create a new expression list.
110997**
110998** The pList argument must be either NULL or a pointer to an ExprList
110999** obtained from a prior call to sqlite3ExprListAppend().
111000**
111001** If a memory allocation error occurs, the entire list is freed and
111002** NULL is returned.  If non-NULL is returned, then it is guaranteed
111003** that the new entry was successfully appended.
111004*/
111005static const struct ExprList_item zeroItem = {0};
111006SQLITE_PRIVATE SQLITE_NOINLINE ExprList *sqlite3ExprListAppendNew(
111007  sqlite3 *db,            /* Database handle.  Used for memory allocation */
111008  Expr *pExpr             /* Expression to be appended. Might be NULL */
111009){
111010  struct ExprList_item *pItem;
111011  ExprList *pList;
111012
111013  pList = sqlite3DbMallocRawNN(db, sizeof(ExprList)+sizeof(pList->a[0])*4 );
111014  if( pList==0 ){
111015    sqlite3ExprDelete(db, pExpr);
111016    return 0;
111017  }
111018  pList->nAlloc = 4;
111019  pList->nExpr = 1;
111020  pItem = &pList->a[0];
111021  *pItem = zeroItem;
111022  pItem->pExpr = pExpr;
111023  return pList;
111024}
111025SQLITE_PRIVATE SQLITE_NOINLINE ExprList *sqlite3ExprListAppendGrow(
111026  sqlite3 *db,            /* Database handle.  Used for memory allocation */
111027  ExprList *pList,        /* List to which to append. Might be NULL */
111028  Expr *pExpr             /* Expression to be appended. Might be NULL */
111029){
111030  struct ExprList_item *pItem;
111031  ExprList *pNew;
111032  pList->nAlloc *= 2;
111033  pNew = sqlite3DbRealloc(db, pList,
111034       sizeof(*pList)+(pList->nAlloc-1)*sizeof(pList->a[0]));
111035  if( pNew==0 ){
111036    sqlite3ExprListDelete(db, pList);
111037    sqlite3ExprDelete(db, pExpr);
111038    return 0;
111039  }else{
111040    pList = pNew;
111041  }
111042  pItem = &pList->a[pList->nExpr++];
111043  *pItem = zeroItem;
111044  pItem->pExpr = pExpr;
111045  return pList;
111046}
111047SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
111048  Parse *pParse,          /* Parsing context */
111049  ExprList *pList,        /* List to which to append. Might be NULL */
111050  Expr *pExpr             /* Expression to be appended. Might be NULL */
111051){
111052  struct ExprList_item *pItem;
111053  if( pList==0 ){
111054    return sqlite3ExprListAppendNew(pParse->db,pExpr);
111055  }
111056  if( pList->nAlloc<pList->nExpr+1 ){
111057    return sqlite3ExprListAppendGrow(pParse->db,pList,pExpr);
111058  }
111059  pItem = &pList->a[pList->nExpr++];
111060  *pItem = zeroItem;
111061  pItem->pExpr = pExpr;
111062  return pList;
111063}
111064
111065/*
111066** pColumns and pExpr form a vector assignment which is part of the SET
111067** clause of an UPDATE statement.  Like this:
111068**
111069**        (a,b,c) = (expr1,expr2,expr3)
111070** Or:    (a,b,c) = (SELECT x,y,z FROM ....)
111071**
111072** For each term of the vector assignment, append new entries to the
111073** expression list pList.  In the case of a subquery on the RHS, append
111074** TK_SELECT_COLUMN expressions.
111075*/
111076SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
111077  Parse *pParse,         /* Parsing context */
111078  ExprList *pList,       /* List to which to append. Might be NULL */
111079  IdList *pColumns,      /* List of names of LHS of the assignment */
111080  Expr *pExpr            /* Vector expression to be appended. Might be NULL */
111081){
111082  sqlite3 *db = pParse->db;
111083  int n;
111084  int i;
111085  int iFirst = pList ? pList->nExpr : 0;
111086  /* pColumns can only be NULL due to an OOM but an OOM will cause an
111087  ** exit prior to this routine being invoked */
111088  if( NEVER(pColumns==0) ) goto vector_append_error;
111089  if( pExpr==0 ) goto vector_append_error;
111090
111091  /* If the RHS is a vector, then we can immediately check to see that
111092  ** the size of the RHS and LHS match.  But if the RHS is a SELECT,
111093  ** wildcards ("*") in the result set of the SELECT must be expanded before
111094  ** we can do the size check, so defer the size check until code generation.
111095  */
111096  if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
111097    sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
111098                    pColumns->nId, n);
111099    goto vector_append_error;
111100  }
111101
111102  for(i=0; i<pColumns->nId; i++){
111103    Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i, pColumns->nId);
111104    assert( pSubExpr!=0 || db->mallocFailed );
111105    if( pSubExpr==0 ) continue;
111106    pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
111107    if( pList ){
111108      assert( pList->nExpr==iFirst+i+1 );
111109      pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
111110      pColumns->a[i].zName = 0;
111111    }
111112  }
111113
111114  if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
111115    Expr *pFirst = pList->a[iFirst].pExpr;
111116    assert( pFirst!=0 );
111117    assert( pFirst->op==TK_SELECT_COLUMN );
111118
111119    /* Store the SELECT statement in pRight so it will be deleted when
111120    ** sqlite3ExprListDelete() is called */
111121    pFirst->pRight = pExpr;
111122    pExpr = 0;
111123
111124    /* Remember the size of the LHS in iTable so that we can check that
111125    ** the RHS and LHS sizes match during code generation. */
111126    pFirst->iTable = pColumns->nId;
111127  }
111128
111129vector_append_error:
111130  sqlite3ExprUnmapAndDelete(pParse, pExpr);
111131  sqlite3IdListDelete(db, pColumns);
111132  return pList;
111133}
111134
111135/*
111136** Set the sort order for the last element on the given ExprList.
111137*/
111138SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
111139  struct ExprList_item *pItem;
111140  if( p==0 ) return;
111141  assert( p->nExpr>0 );
111142
111143  assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
111144  assert( iSortOrder==SQLITE_SO_UNDEFINED
111145       || iSortOrder==SQLITE_SO_ASC
111146       || iSortOrder==SQLITE_SO_DESC
111147  );
111148  assert( eNulls==SQLITE_SO_UNDEFINED
111149       || eNulls==SQLITE_SO_ASC
111150       || eNulls==SQLITE_SO_DESC
111151  );
111152
111153  pItem = &p->a[p->nExpr-1];
111154  assert( pItem->fg.bNulls==0 );
111155  if( iSortOrder==SQLITE_SO_UNDEFINED ){
111156    iSortOrder = SQLITE_SO_ASC;
111157  }
111158  pItem->fg.sortFlags = (u8)iSortOrder;
111159
111160  if( eNulls!=SQLITE_SO_UNDEFINED ){
111161    pItem->fg.bNulls = 1;
111162    if( iSortOrder!=eNulls ){
111163      pItem->fg.sortFlags |= KEYINFO_ORDER_BIGNULL;
111164    }
111165  }
111166}
111167
111168/*
111169** Set the ExprList.a[].zEName element of the most recently added item
111170** on the expression list.
111171**
111172** pList might be NULL following an OOM error.  But pName should never be
111173** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
111174** is set.
111175*/
111176SQLITE_PRIVATE void sqlite3ExprListSetName(
111177  Parse *pParse,          /* Parsing context */
111178  ExprList *pList,        /* List to which to add the span. */
111179  const Token *pName,     /* Name to be added */
111180  int dequote             /* True to cause the name to be dequoted */
111181){
111182  assert( pList!=0 || pParse->db->mallocFailed!=0 );
111183  assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );
111184  if( pList ){
111185    struct ExprList_item *pItem;
111186    assert( pList->nExpr>0 );
111187    pItem = &pList->a[pList->nExpr-1];
111188    assert( pItem->zEName==0 );
111189    assert( pItem->fg.eEName==ENAME_NAME );
111190    pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
111191    if( dequote ){
111192      /* If dequote==0, then pName->z does not point to part of a DDL
111193      ** statement handled by the parser. And so no token need be added
111194      ** to the token-map.  */
111195      sqlite3Dequote(pItem->zEName);
111196      if( IN_RENAME_OBJECT ){
111197        sqlite3RenameTokenMap(pParse, (const void*)pItem->zEName, pName);
111198      }
111199    }
111200  }
111201}
111202
111203/*
111204** Set the ExprList.a[].zSpan element of the most recently added item
111205** on the expression list.
111206**
111207** pList might be NULL following an OOM error.  But pSpan should never be
111208** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
111209** is set.
111210*/
111211SQLITE_PRIVATE void sqlite3ExprListSetSpan(
111212  Parse *pParse,          /* Parsing context */
111213  ExprList *pList,        /* List to which to add the span. */
111214  const char *zStart,     /* Start of the span */
111215  const char *zEnd        /* End of the span */
111216){
111217  sqlite3 *db = pParse->db;
111218  assert( pList!=0 || db->mallocFailed!=0 );
111219  if( pList ){
111220    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
111221    assert( pList->nExpr>0 );
111222    if( pItem->zEName==0 ){
111223      pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
111224      pItem->fg.eEName = ENAME_SPAN;
111225    }
111226  }
111227}
111228
111229/*
111230** If the expression list pEList contains more than iLimit elements,
111231** leave an error message in pParse.
111232*/
111233SQLITE_PRIVATE void sqlite3ExprListCheckLength(
111234  Parse *pParse,
111235  ExprList *pEList,
111236  const char *zObject
111237){
111238  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
111239  testcase( pEList && pEList->nExpr==mx );
111240  testcase( pEList && pEList->nExpr==mx+1 );
111241  if( pEList && pEList->nExpr>mx ){
111242    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
111243  }
111244}
111245
111246/*
111247** Delete an entire expression list.
111248*/
111249static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
111250  int i = pList->nExpr;
111251  struct ExprList_item *pItem =  pList->a;
111252  assert( pList->nExpr>0 );
111253  assert( db!=0 );
111254  do{
111255    sqlite3ExprDelete(db, pItem->pExpr);
111256    if( pItem->zEName ) sqlite3DbNNFreeNN(db, pItem->zEName);
111257    pItem++;
111258  }while( --i>0 );
111259  sqlite3DbNNFreeNN(db, pList);
111260}
111261SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
111262  if( pList ) exprListDeleteNN(db, pList);
111263}
111264SQLITE_PRIVATE void sqlite3ExprListDeleteGeneric(sqlite3 *db, void *pList){
111265  if( ALWAYS(pList) ) exprListDeleteNN(db, (ExprList*)pList);
111266}
111267
111268/*
111269** Return the bitwise-OR of all Expr.flags fields in the given
111270** ExprList.
111271*/
111272SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
111273  int i;
111274  u32 m = 0;
111275  assert( pList!=0 );
111276  for(i=0; i<pList->nExpr; i++){
111277     Expr *pExpr = pList->a[i].pExpr;
111278     assert( pExpr!=0 );
111279     m |= pExpr->flags;
111280  }
111281  return m;
111282}
111283
111284/*
111285** This is a SELECT-node callback for the expression walker that
111286** always "fails".  By "fail" in this case, we mean set
111287** pWalker->eCode to zero and abort.
111288**
111289** This callback is used by multiple expression walkers.
111290*/
111291SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
111292  UNUSED_PARAMETER(NotUsed);
111293  pWalker->eCode = 0;
111294  return WRC_Abort;
111295}
111296
111297/*
111298** Check the input string to see if it is "true" or "false" (in any case).
111299**
111300**       If the string is....           Return
111301**         "true"                         EP_IsTrue
111302**         "false"                        EP_IsFalse
111303**         anything else                  0
111304*/
111305SQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char *zIn){
111306  if( sqlite3StrICmp(zIn, "true")==0  ) return EP_IsTrue;
111307  if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse;
111308  return 0;
111309}
111310
111311
111312/*
111313** If the input expression is an ID with the name "true" or "false"
111314** then convert it into an TK_TRUEFALSE term.  Return non-zero if
111315** the conversion happened, and zero if the expression is unaltered.
111316*/
111317SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){
111318  u32 v;
111319  assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
111320  if( !ExprHasProperty(pExpr, EP_Quoted|EP_IntValue)
111321   && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
111322  ){
111323    pExpr->op = TK_TRUEFALSE;
111324    ExprSetProperty(pExpr, v);
111325    return 1;
111326  }
111327  return 0;
111328}
111329
111330/*
111331** The argument must be a TK_TRUEFALSE Expr node.  Return 1 if it is TRUE
111332** and 0 if it is FALSE.
111333*/
111334SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr *pExpr){
111335  pExpr = sqlite3ExprSkipCollateAndLikely((Expr*)pExpr);
111336  assert( pExpr->op==TK_TRUEFALSE );
111337  assert( !ExprHasProperty(pExpr, EP_IntValue) );
111338  assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
111339       || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
111340  return pExpr->u.zToken[4]==0;
111341}
111342
111343/*
111344** If pExpr is an AND or OR expression, try to simplify it by eliminating
111345** terms that are always true or false.  Return the simplified expression.
111346** Or return the original expression if no simplification is possible.
111347**
111348** Examples:
111349**
111350**     (x<10) AND true                =>   (x<10)
111351**     (x<10) AND false               =>   false
111352**     (x<10) AND (y=22 OR false)     =>   (x<10) AND (y=22)
111353**     (x<10) AND (y=22 OR true)      =>   (x<10)
111354**     (y=22) OR true                 =>   true
111355*/
111356SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
111357  assert( pExpr!=0 );
111358  if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
111359    Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
111360    Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
111361    if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
111362      pExpr = pExpr->op==TK_AND ? pRight : pLeft;
111363    }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
111364      pExpr = pExpr->op==TK_AND ? pLeft : pRight;
111365    }
111366  }
111367  return pExpr;
111368}
111369
111370/*
111371** pExpr is a TK_FUNCTION node.  Try to determine whether or not the
111372** function is a constant function.  A function is constant if all of
111373** the following are true:
111374**
111375**    (1)  It is a scalar function (not an aggregate or window function)
111376**    (2)  It has either the SQLITE_FUNC_CONSTANT or SQLITE_FUNC_SLOCHNG
111377**         property.
111378**    (3)  All of its arguments are constants
111379**
111380** This routine sets pWalker->eCode to 0 if pExpr is not a constant.
111381** It makes no changes to pWalker->eCode if pExpr is constant.  In
111382** every case, it returns WRC_Abort.
111383**
111384** Called as a service subroutine from exprNodeIsConstant().
111385*/
111386static SQLITE_NOINLINE int exprNodeIsConstantFunction(
111387  Walker *pWalker,
111388  Expr *pExpr
111389){
111390  int n;             /* Number of arguments */
111391  ExprList *pList;   /* List of arguments */
111392  FuncDef *pDef;     /* The function */
111393  sqlite3 *db;       /* The database */
111394
111395  assert( pExpr->op==TK_FUNCTION );
111396  if( ExprHasProperty(pExpr, EP_TokenOnly)
111397   || (pList = pExpr->x.pList)==0
111398  ){;
111399    n = 0;
111400  }else{
111401    n = pList->nExpr;
111402    sqlite3WalkExprList(pWalker, pList);
111403    if( pWalker->eCode==0 ) return WRC_Abort;
111404  }
111405  db = pWalker->pParse->db;
111406  pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
111407  if( pDef==0
111408   || pDef->xFinalize!=0
111409   || (pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
111410   || ExprHasProperty(pExpr, EP_WinFunc)
111411  ){
111412    pWalker->eCode = 0;
111413    return WRC_Abort;
111414  }
111415  return WRC_Prune;
111416}
111417
111418
111419/*
111420** These routines are Walker callbacks used to check expressions to
111421** see if they are "constant" for some definition of constant.  The
111422** Walker.eCode value determines the type of "constant" we are looking
111423** for.
111424**
111425** These callback routines are used to implement the following:
111426**
111427**     sqlite3ExprIsConstant()                  pWalker->eCode==1
111428**     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
111429**     sqlite3ExprIsTableConstant()             pWalker->eCode==3
111430**     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
111431**
111432** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
111433** is found to not be a constant.
111434**
111435** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
111436** expressions in a CREATE TABLE statement.  The Walker.eCode value is 5
111437** when parsing an existing schema out of the sqlite_schema table and 4
111438** when processing a new CREATE TABLE statement.  A bound parameter raises
111439** an error for new statements, but is silently converted
111440** to NULL for existing schemas.  This allows sqlite_schema tables that
111441** contain a bound parameter because they were generated by older versions
111442** of SQLite to be parsed by newer versions of SQLite without raising a
111443** malformed schema error.
111444*/
111445static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
111446  assert( pWalker->eCode>0 );
111447
111448  /* If pWalker->eCode is 2 then any term of the expression that comes from
111449  ** the ON or USING clauses of an outer join disqualifies the expression
111450  ** from being considered constant. */
111451  if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_OuterON) ){
111452    pWalker->eCode = 0;
111453    return WRC_Abort;
111454  }
111455
111456  switch( pExpr->op ){
111457    /* Consider functions to be constant if all their arguments are constant
111458    ** and either pWalker->eCode==4 or 5 or the function has the
111459    ** SQLITE_FUNC_CONST flag. */
111460    case TK_FUNCTION:
111461      if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
111462       && !ExprHasProperty(pExpr, EP_WinFunc)
111463      ){
111464        if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
111465        return WRC_Continue;
111466      }else if( pWalker->pParse ){
111467        return exprNodeIsConstantFunction(pWalker, pExpr);
111468      }else{
111469        pWalker->eCode = 0;
111470        return WRC_Abort;
111471      }
111472    case TK_ID:
111473      /* Convert "true" or "false" in a DEFAULT clause into the
111474      ** appropriate TK_TRUEFALSE operator */
111475      if( sqlite3ExprIdToTrueFalse(pExpr) ){
111476        return WRC_Prune;
111477      }
111478      /* no break */ deliberate_fall_through
111479    case TK_COLUMN:
111480    case TK_AGG_FUNCTION:
111481    case TK_AGG_COLUMN:
111482      testcase( pExpr->op==TK_ID );
111483      testcase( pExpr->op==TK_COLUMN );
111484      testcase( pExpr->op==TK_AGG_FUNCTION );
111485      testcase( pExpr->op==TK_AGG_COLUMN );
111486      if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
111487        return WRC_Continue;
111488      }
111489      if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
111490        return WRC_Continue;
111491      }
111492      /* no break */ deliberate_fall_through
111493    case TK_IF_NULL_ROW:
111494    case TK_REGISTER:
111495    case TK_DOT:
111496    case TK_RAISE:
111497      testcase( pExpr->op==TK_REGISTER );
111498      testcase( pExpr->op==TK_IF_NULL_ROW );
111499      testcase( pExpr->op==TK_DOT );
111500      testcase( pExpr->op==TK_RAISE );
111501      pWalker->eCode = 0;
111502      return WRC_Abort;
111503    case TK_VARIABLE:
111504      if( pWalker->eCode==5 ){
111505        /* Silently convert bound parameters that appear inside of CREATE
111506        ** statements into a NULL when parsing the CREATE statement text out
111507        ** of the sqlite_schema table */
111508        pExpr->op = TK_NULL;
111509      }else if( pWalker->eCode==4 ){
111510        /* A bound parameter in a CREATE statement that originates from
111511        ** sqlite3_prepare() causes an error */
111512        pWalker->eCode = 0;
111513        return WRC_Abort;
111514      }
111515      /* no break */ deliberate_fall_through
111516    default:
111517      testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
111518      testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
111519      return WRC_Continue;
111520  }
111521}
111522static int exprIsConst(Parse *pParse, Expr *p, int initFlag){
111523  Walker w;
111524  w.eCode = initFlag;
111525  w.pParse = pParse;
111526  w.xExprCallback = exprNodeIsConstant;
111527  w.xSelectCallback = sqlite3SelectWalkFail;
111528#ifdef SQLITE_DEBUG
111529  w.xSelectCallback2 = sqlite3SelectWalkAssert2;
111530#endif
111531  sqlite3WalkExpr(&w, p);
111532  return w.eCode;
111533}
111534
111535/*
111536** Walk an expression tree.  Return non-zero if the expression is constant
111537** and 0 if it involves variables or function calls.
111538**
111539** For the purposes of this function, a double-quoted string (ex: "abc")
111540** is considered a variable but a single-quoted string (ex: 'abc') is
111541** a constant.
111542**
111543** The pParse parameter may be NULL.  But if it is NULL, there is no way
111544** to determine if function calls are constant or not, and hence all
111545** function calls will be considered to be non-constant.  If pParse is
111546** not NULL, then a function call might be constant, depending on the
111547** function and on its parameters.
111548*/
111549SQLITE_PRIVATE int sqlite3ExprIsConstant(Parse *pParse, Expr *p){
111550  return exprIsConst(pParse, p, 1);
111551}
111552
111553/*
111554** Walk an expression tree.  Return non-zero if
111555**
111556**   (1) the expression is constant, and
111557**   (2) the expression does originate in the ON or USING clause
111558**       of a LEFT JOIN, and
111559**   (3) the expression does not contain any EP_FixedCol TK_COLUMN
111560**       operands created by the constant propagation optimization.
111561**
111562** When this routine returns true, it indicates that the expression
111563** can be added to the pParse->pConstExpr list and evaluated once when
111564** the prepared statement starts up.  See sqlite3ExprCodeRunJustOnce().
111565*/
111566static int sqlite3ExprIsConstantNotJoin(Parse *pParse, Expr *p){
111567  return exprIsConst(pParse, p, 2);
111568}
111569
111570/*
111571** This routine examines sub-SELECT statements as an expression is being
111572** walked as part of sqlite3ExprIsTableConstant().  Sub-SELECTs are considered
111573** constant as long as they are uncorrelated - meaning that they do not
111574** contain any terms from outer contexts.
111575*/
111576static int exprSelectWalkTableConstant(Walker *pWalker, Select *pSelect){
111577  assert( pSelect!=0 );
111578  assert( pWalker->eCode==3 || pWalker->eCode==0 );
111579  if( (pSelect->selFlags & SF_Correlated)!=0 ){
111580    pWalker->eCode = 0;
111581    return WRC_Abort;
111582  }
111583  return WRC_Prune;
111584}
111585
111586/*
111587** Walk an expression tree.  Return non-zero if the expression is constant
111588** for any single row of the table with cursor iCur.  In other words, the
111589** expression must not refer to any non-deterministic function nor any
111590** table other than iCur.
111591**
111592** Consider uncorrelated subqueries to be constants if the bAllowSubq
111593** parameter is true.
111594*/
111595static int sqlite3ExprIsTableConstant(Expr *p, int iCur, int bAllowSubq){
111596  Walker w;
111597  w.eCode = 3;
111598  w.pParse = 0;
111599  w.xExprCallback = exprNodeIsConstant;
111600  if( bAllowSubq ){
111601    w.xSelectCallback = exprSelectWalkTableConstant;
111602  }else{
111603    w.xSelectCallback = sqlite3SelectWalkFail;
111604#ifdef SQLITE_DEBUG
111605    w.xSelectCallback2 = sqlite3SelectWalkAssert2;
111606#endif
111607  }
111608  w.u.iCur = iCur;
111609  sqlite3WalkExpr(&w, p);
111610  return w.eCode;
111611}
111612
111613/*
111614** Check pExpr to see if it is an constraint on the single data source
111615** pSrc = &pSrcList->a[iSrc].  In other words, check to see if pExpr
111616** constrains pSrc but does not depend on any other tables or data
111617** sources anywhere else in the query.  Return true (non-zero) if pExpr
111618** is a constraint on pSrc only.
111619**
111620** This is an optimization.  False negatives will perhaps cause slower
111621** queries, but false positives will yield incorrect answers.  So when in
111622** doubt, return 0.
111623**
111624** To be an single-source constraint, the following must be true:
111625**
111626**   (1)  pExpr cannot refer to any table other than pSrc->iCursor.
111627**
111628**   (2a) pExpr cannot use subqueries unless the bAllowSubq parameter is
111629**        true and the subquery is non-correlated
111630**
111631**   (2b) pExpr cannot use non-deterministic functions.
111632**
111633**   (3)  pSrc cannot be part of the left operand for a RIGHT JOIN.
111634**        (Is there some way to relax this constraint?)
111635**
111636**   (4)  If pSrc is the right operand of a LEFT JOIN, then...
111637**         (4a)  pExpr must come from an ON clause..
111638**         (4b)  and specifically the ON clause associated with the LEFT JOIN.
111639**
111640**   (5)  If pSrc is not the right operand of a LEFT JOIN or the left
111641**        operand of a RIGHT JOIN, then pExpr must be from the WHERE
111642**        clause, not an ON clause.
111643**
111644**   (6) Either:
111645**
111646**       (6a) pExpr does not originate in an ON or USING clause, or
111647**
111648**       (6b) The ON or USING clause from which pExpr is derived is
111649**            not to the left of a RIGHT JOIN (or FULL JOIN).
111650**
111651**       Without this restriction, accepting pExpr as a single-table
111652**       constraint might move the the ON/USING filter expression
111653**       from the left side of a RIGHT JOIN over to the right side,
111654**       which leads to incorrect answers.  See also restriction (9)
111655**       on push-down.
111656*/
111657SQLITE_PRIVATE int sqlite3ExprIsSingleTableConstraint(
111658  Expr *pExpr,                 /* The constraint */
111659  const SrcList *pSrcList,     /* Complete FROM clause */
111660  int iSrc,                    /* Which element of pSrcList to use */
111661  int bAllowSubq               /* Allow non-correlated subqueries */
111662){
111663  const SrcItem *pSrc = &pSrcList->a[iSrc];
111664  if( pSrc->fg.jointype & JT_LTORJ ){
111665    return 0;  /* rule (3) */
111666  }
111667  if( pSrc->fg.jointype & JT_LEFT ){
111668    if( !ExprHasProperty(pExpr, EP_OuterON) ) return 0;   /* rule (4a) */
111669    if( pExpr->w.iJoin!=pSrc->iCursor ) return 0;         /* rule (4b) */
111670  }else{
111671    if( ExprHasProperty(pExpr, EP_OuterON) ) return 0;    /* rule (5) */
111672  }
111673  if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON)  /* (6a) */
111674   && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0     /* Fast pre-test of (6b) */
111675  ){
111676    int jj;
111677    for(jj=0; jj<iSrc; jj++){
111678      if( pExpr->w.iJoin==pSrcList->a[jj].iCursor ){
111679        if( (pSrcList->a[jj].fg.jointype & JT_LTORJ)!=0 ){
111680          return 0;  /* restriction (6) */
111681        }
111682        break;
111683      }
111684    }
111685  }
111686  /* Rules (1), (2a), and (2b) handled by the following: */
111687  return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor, bAllowSubq);
111688}
111689
111690
111691/*
111692** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
111693*/
111694static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
111695  ExprList *pGroupBy = pWalker->u.pGroupBy;
111696  int i;
111697
111698  /* Check if pExpr is identical to any GROUP BY term. If so, consider
111699  ** it constant.  */
111700  for(i=0; i<pGroupBy->nExpr; i++){
111701    Expr *p = pGroupBy->a[i].pExpr;
111702    if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
111703      CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
111704      if( sqlite3IsBinary(pColl) ){
111705        return WRC_Prune;
111706      }
111707    }
111708  }
111709
111710  /* Check if pExpr is a sub-select. If so, consider it variable. */
111711  if( ExprUseXSelect(pExpr) ){
111712    pWalker->eCode = 0;
111713    return WRC_Abort;
111714  }
111715
111716  return exprNodeIsConstant(pWalker, pExpr);
111717}
111718
111719/*
111720** Walk the expression tree passed as the first argument. Return non-zero
111721** if the expression consists entirely of constants or copies of terms
111722** in pGroupBy that sort with the BINARY collation sequence.
111723**
111724** This routine is used to determine if a term of the HAVING clause can
111725** be promoted into the WHERE clause.  In order for such a promotion to work,
111726** the value of the HAVING clause term must be the same for all members of
111727** a "group".  The requirement that the GROUP BY term must be BINARY
111728** assumes that no other collating sequence will have a finer-grained
111729** grouping than binary.  In other words (A=B COLLATE binary) implies
111730** A=B in every other collating sequence.  The requirement that the
111731** GROUP BY be BINARY is stricter than necessary.  It would also work
111732** to promote HAVING clauses that use the same alternative collating
111733** sequence as the GROUP BY term, but that is much harder to check,
111734** alternative collating sequences are uncommon, and this is only an
111735** optimization, so we take the easy way out and simply require the
111736** GROUP BY to use the BINARY collating sequence.
111737*/
111738SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
111739  Walker w;
111740  w.eCode = 1;
111741  w.xExprCallback = exprNodeIsConstantOrGroupBy;
111742  w.xSelectCallback = 0;
111743  w.u.pGroupBy = pGroupBy;
111744  w.pParse = pParse;
111745  sqlite3WalkExpr(&w, p);
111746  return w.eCode;
111747}
111748
111749/*
111750** Walk an expression tree for the DEFAULT field of a column definition
111751** in a CREATE TABLE statement.  Return non-zero if the expression is
111752** acceptable for use as a DEFAULT.  That is to say, return non-zero if
111753** the expression is constant or a function call with constant arguments.
111754** Return and 0 if there are any variables.
111755**
111756** isInit is true when parsing from sqlite_schema.  isInit is false when
111757** processing a new CREATE TABLE statement.  When isInit is true, parameters
111758** (such as ? or $abc) in the expression are converted into NULL.  When
111759** isInit is false, parameters raise an error.  Parameters should not be
111760** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
111761** allowed it, so we need to support it when reading sqlite_schema for
111762** backwards compatibility.
111763**
111764** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
111765**
111766** For the purposes of this function, a double-quoted string (ex: "abc")
111767** is considered a variable but a single-quoted string (ex: 'abc') is
111768** a constant.
111769*/
111770SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
111771  assert( isInit==0 || isInit==1 );
111772  return exprIsConst(0, p, 4+isInit);
111773}
111774
111775#ifdef SQLITE_ENABLE_CURSOR_HINTS
111776/*
111777** Walk an expression tree.  Return 1 if the expression contains a
111778** subquery of some kind.  Return 0 if there are no subqueries.
111779*/
111780SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
111781  Walker w;
111782  w.eCode = 1;
111783  w.xExprCallback = sqlite3ExprWalkNoop;
111784  w.xSelectCallback = sqlite3SelectWalkFail;
111785#ifdef SQLITE_DEBUG
111786  w.xSelectCallback2 = sqlite3SelectWalkAssert2;
111787#endif
111788  sqlite3WalkExpr(&w, p);
111789  return w.eCode==0;
111790}
111791#endif
111792
111793/*
111794** If the expression p codes a constant integer that is small enough
111795** to fit in a 32-bit integer, return 1 and put the value of the integer
111796** in *pValue.  If the expression is not an integer or if it is too big
111797** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
111798*/
111799SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr *p, int *pValue){
111800  int rc = 0;
111801  if( NEVER(p==0) ) return 0;  /* Used to only happen following on OOM */
111802
111803  /* If an expression is an integer literal that fits in a signed 32-bit
111804  ** integer, then the EP_IntValue flag will have already been set */
111805  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
111806           || sqlite3GetInt32(p->u.zToken, &rc)==0 );
111807
111808  if( p->flags & EP_IntValue ){
111809    *pValue = p->u.iValue;
111810    return 1;
111811  }
111812  switch( p->op ){
111813    case TK_UPLUS: {
111814      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
111815      break;
111816    }
111817    case TK_UMINUS: {
111818      int v = 0;
111819      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
111820        assert( ((unsigned int)v)!=0x80000000 );
111821        *pValue = -v;
111822        rc = 1;
111823      }
111824      break;
111825    }
111826    default: break;
111827  }
111828  return rc;
111829}
111830
111831/*
111832** Return FALSE if there is no chance that the expression can be NULL.
111833**
111834** If the expression might be NULL or if the expression is too complex
111835** to tell return TRUE.
111836**
111837** This routine is used as an optimization, to skip OP_IsNull opcodes
111838** when we know that a value cannot be NULL.  Hence, a false positive
111839** (returning TRUE when in fact the expression can never be NULL) might
111840** be a small performance hit but is otherwise harmless.  On the other
111841** hand, a false negative (returning FALSE when the result could be NULL)
111842** will likely result in an incorrect answer.  So when in doubt, return
111843** TRUE.
111844*/
111845SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
111846  u8 op;
111847  assert( p!=0 );
111848  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
111849    p = p->pLeft;
111850    assert( p!=0 );
111851  }
111852  op = p->op;
111853  if( op==TK_REGISTER ) op = p->op2;
111854  switch( op ){
111855    case TK_INTEGER:
111856    case TK_STRING:
111857    case TK_FLOAT:
111858    case TK_BLOB:
111859      return 0;
111860    case TK_COLUMN:
111861      assert( ExprUseYTab(p) );
111862      return ExprHasProperty(p, EP_CanBeNull)
111863          || NEVER(p->y.pTab==0) /* Reference to column of index on expr */
111864#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
111865          || (p->iColumn==XN_ROWID && IsView(p->y.pTab))
111866#endif
111867          || (p->iColumn>=0
111868              && p->y.pTab->aCol!=0 /* Possible due to prior error */
111869              && ALWAYS(p->iColumn<p->y.pTab->nCol)
111870              && p->y.pTab->aCol[p->iColumn].notNull==0);
111871    default:
111872      return 1;
111873  }
111874}
111875
111876/*
111877** Return TRUE if the given expression is a constant which would be
111878** unchanged by OP_Affinity with the affinity given in the second
111879** argument.
111880**
111881** This routine is used to determine if the OP_Affinity operation
111882** can be omitted.  When in doubt return FALSE.  A false negative
111883** is harmless.  A false positive, however, can result in the wrong
111884** answer.
111885*/
111886SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
111887  u8 op;
111888  int unaryMinus = 0;
111889  if( aff==SQLITE_AFF_BLOB ) return 1;
111890  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
111891    if( p->op==TK_UMINUS ) unaryMinus = 1;
111892    p = p->pLeft;
111893  }
111894  op = p->op;
111895  if( op==TK_REGISTER ) op = p->op2;
111896  switch( op ){
111897    case TK_INTEGER: {
111898      return aff>=SQLITE_AFF_NUMERIC;
111899    }
111900    case TK_FLOAT: {
111901      return aff>=SQLITE_AFF_NUMERIC;
111902    }
111903    case TK_STRING: {
111904      return !unaryMinus && aff==SQLITE_AFF_TEXT;
111905    }
111906    case TK_BLOB: {
111907      return !unaryMinus;
111908    }
111909    case TK_COLUMN: {
111910      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
111911      return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
111912    }
111913    default: {
111914      return 0;
111915    }
111916  }
111917}
111918
111919/*
111920** Return TRUE if the given string is a row-id column name.
111921*/
111922SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
111923  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
111924  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
111925  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
111926  return 0;
111927}
111928
111929/*
111930** Return a pointer to a buffer containing a usable rowid alias for table
111931** pTab. An alias is usable if there is not an explicit user-defined column
111932** of the same name.
111933*/
111934SQLITE_PRIVATE const char *sqlite3RowidAlias(Table *pTab){
111935  const char *azOpt[] = {"_ROWID_", "ROWID", "OID"};
111936  int ii;
111937  assert( VisibleRowid(pTab) );
111938  for(ii=0; ii<ArraySize(azOpt); ii++){
111939    int iCol;
111940    for(iCol=0; iCol<pTab->nCol; iCol++){
111941      if( sqlite3_stricmp(azOpt[ii], pTab->aCol[iCol].zCnName)==0 ) break;
111942    }
111943    if( iCol==pTab->nCol ){
111944      return azOpt[ii];
111945    }
111946  }
111947  return 0;
111948}
111949
111950/*
111951** pX is the RHS of an IN operator.  If pX is a SELECT statement
111952** that can be simplified to a direct table access, then return
111953** a pointer to the SELECT statement.  If pX is not a SELECT statement,
111954** or if the SELECT statement needs to be materialized into a transient
111955** table, then return NULL.
111956*/
111957#ifndef SQLITE_OMIT_SUBQUERY
111958static Select *isCandidateForInOpt(const Expr *pX){
111959  Select *p;
111960  SrcList *pSrc;
111961  ExprList *pEList;
111962  Table *pTab;
111963  int i;
111964  if( !ExprUseXSelect(pX) ) return 0;                 /* Not a subquery */
111965  if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
111966  p = pX->x.pSelect;
111967  if( p->pPrior ) return 0;              /* Not a compound SELECT */
111968  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
111969    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
111970    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
111971    return 0; /* No DISTINCT keyword and no aggregate functions */
111972  }
111973  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
111974  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
111975  if( p->pWhere ) return 0;              /* Has no WHERE clause */
111976  pSrc = p->pSrc;
111977  assert( pSrc!=0 );
111978  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
111979  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
111980  pTab = pSrc->a[0].pTab;
111981  assert( pTab!=0 );
111982  assert( !IsView(pTab)  );              /* FROM clause is not a view */
111983  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
111984  pEList = p->pEList;
111985  assert( pEList!=0 );
111986  /* All SELECT results must be columns. */
111987  for(i=0; i<pEList->nExpr; i++){
111988    Expr *pRes = pEList->a[i].pExpr;
111989    if( pRes->op!=TK_COLUMN ) return 0;
111990    assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
111991  }
111992  return p;
111993}
111994#endif /* SQLITE_OMIT_SUBQUERY */
111995
111996#ifndef SQLITE_OMIT_SUBQUERY
111997/*
111998** Generate code that checks the left-most column of index table iCur to see if
111999** it contains any NULL entries.  Cause the register at regHasNull to be set
112000** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
112001** to be set to NULL if iCur contains one or more NULL values.
112002*/
112003static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
112004  int addr1;
112005  sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
112006  addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
112007  sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
112008  sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
112009  VdbeComment((v, "first_entry_in(%d)", iCur));
112010  sqlite3VdbeJumpHere(v, addr1);
112011}
112012#endif
112013
112014
112015#ifndef SQLITE_OMIT_SUBQUERY
112016/*
112017** The argument is an IN operator with a list (not a subquery) on the
112018** right-hand side.  Return TRUE if that list is constant.
112019*/
112020static int sqlite3InRhsIsConstant(Parse *pParse, Expr *pIn){
112021  Expr *pLHS;
112022  int res;
112023  assert( !ExprHasProperty(pIn, EP_xIsSelect) );
112024  pLHS = pIn->pLeft;
112025  pIn->pLeft = 0;
112026  res = sqlite3ExprIsConstant(pParse, pIn);
112027  pIn->pLeft = pLHS;
112028  return res;
112029}
112030#endif
112031
112032/*
112033** This function is used by the implementation of the IN (...) operator.
112034** The pX parameter is the expression on the RHS of the IN operator, which
112035** might be either a list of expressions or a subquery.
112036**
112037** The job of this routine is to find or create a b-tree object that can
112038** be used either to test for membership in the RHS set or to iterate through
112039** all members of the RHS set, skipping duplicates.
112040**
112041** A cursor is opened on the b-tree object that is the RHS of the IN operator
112042** and the *piTab parameter is set to the index of that cursor.
112043**
112044** The returned value of this function indicates the b-tree type, as follows:
112045**
112046**   IN_INDEX_ROWID      - The cursor was opened on a database table.
112047**   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
112048**   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
112049**   IN_INDEX_EPH        - The cursor was opened on a specially created and
112050**                         populated ephemeral table.
112051**   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
112052**                         implemented as a sequence of comparisons.
112053**
112054** An existing b-tree might be used if the RHS expression pX is a simple
112055** subquery such as:
112056**
112057**     SELECT <column1>, <column2>... FROM <table>
112058**
112059** If the RHS of the IN operator is a list or a more complex subquery, then
112060** an ephemeral table might need to be generated from the RHS and then
112061** pX->iTable made to point to the ephemeral table instead of an
112062** existing table.  In this case, the creation and initialization of the
112063** ephemeral table might be put inside of a subroutine, the EP_Subrtn flag
112064** will be set on pX and the pX->y.sub fields will be set to show where
112065** the subroutine is coded.
112066**
112067** The inFlags parameter must contain, at a minimum, one of the bits
112068** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both.  If inFlags contains
112069** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
112070** membership test.  When the IN_INDEX_LOOP bit is set, the IN index will
112071** be used to loop over all values of the RHS of the IN operator.
112072**
112073** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
112074** through the set members) then the b-tree must not contain duplicates.
112075** An ephemeral table will be created unless the selected columns are guaranteed
112076** to be unique - either because it is an INTEGER PRIMARY KEY or due to
112077** a UNIQUE constraint or index.
112078**
112079** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
112080** for fast set membership tests) then an ephemeral table must
112081** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
112082** index can be found with the specified <columns> as its left-most.
112083**
112084** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
112085** if the RHS of the IN operator is a list (not a subquery) then this
112086** routine might decide that creating an ephemeral b-tree for membership
112087** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
112088** calling routine should implement the IN operator using a sequence
112089** of Eq or Ne comparison operations.
112090**
112091** When the b-tree is being used for membership tests, the calling function
112092** might need to know whether or not the RHS side of the IN operator
112093** contains a NULL.  If prRhsHasNull is not a NULL pointer and
112094** if there is any chance that the (...) might contain a NULL value at
112095** runtime, then a register is allocated and the register number written
112096** to *prRhsHasNull. If there is no chance that the (...) contains a
112097** NULL value, then *prRhsHasNull is left unchanged.
112098**
112099** If a register is allocated and its location stored in *prRhsHasNull, then
112100** the value in that register will be NULL if the b-tree contains one or more
112101** NULL values, and it will be some non-NULL value if the b-tree contains no
112102** NULL values.
112103**
112104** If the aiMap parameter is not NULL, it must point to an array containing
112105** one element for each column returned by the SELECT statement on the RHS
112106** of the IN(...) operator. The i'th entry of the array is populated with the
112107** offset of the index column that matches the i'th column returned by the
112108** SELECT. For example, if the expression and selected index are:
112109**
112110**   (?,?,?) IN (SELECT a, b, c FROM t1)
112111**   CREATE INDEX i1 ON t1(b, c, a);
112112**
112113** then aiMap[] is populated with {2, 0, 1}.
112114*/
112115#ifndef SQLITE_OMIT_SUBQUERY
112116SQLITE_PRIVATE int sqlite3FindInIndex(
112117  Parse *pParse,             /* Parsing context */
112118  Expr *pX,                  /* The IN expression */
112119  u32 inFlags,               /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
112120  int *prRhsHasNull,         /* Register holding NULL status.  See notes */
112121  int *aiMap,                /* Mapping from Index fields to RHS fields */
112122  int *piTab                 /* OUT: index to use */
112123){
112124  Select *p;                            /* SELECT to the right of IN operator */
112125  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
112126  int iTab;                             /* Cursor of the RHS table */
112127  int mustBeUnique;                     /* True if RHS must be unique */
112128  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
112129
112130  assert( pX->op==TK_IN );
112131  mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
112132  iTab = pParse->nTab++;
112133
112134  /* If the RHS of this IN(...) operator is a SELECT, and if it matters
112135  ** whether or not the SELECT result contains NULL values, check whether
112136  ** or not NULL is actually possible (it may not be, for example, due
112137  ** to NOT NULL constraints in the schema). If no NULL values are possible,
112138  ** set prRhsHasNull to 0 before continuing.  */
112139  if( prRhsHasNull && ExprUseXSelect(pX) ){
112140    int i;
112141    ExprList *pEList = pX->x.pSelect->pEList;
112142    for(i=0; i<pEList->nExpr; i++){
112143      if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
112144    }
112145    if( i==pEList->nExpr ){
112146      prRhsHasNull = 0;
112147    }
112148  }
112149
112150  /* Check to see if an existing table or index can be used to
112151  ** satisfy the query.  This is preferable to generating a new
112152  ** ephemeral table.  */
112153  if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
112154    sqlite3 *db = pParse->db;              /* Database connection */
112155    Table *pTab;                           /* Table <table>. */
112156    int iDb;                               /* Database idx for pTab */
112157    ExprList *pEList = p->pEList;
112158    int nExpr = pEList->nExpr;
112159
112160    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
112161    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
112162    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
112163    pTab = p->pSrc->a[0].pTab;
112164
112165    /* Code an OP_Transaction and OP_TableLock for <table>. */
112166    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
112167    assert( iDb>=0 && iDb<SQLITE_MAX_DB );
112168    sqlite3CodeVerifySchema(pParse, iDb);
112169    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
112170
112171    assert(v);  /* sqlite3GetVdbe() has always been previously called */
112172    if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
112173      /* The "x IN (SELECT rowid FROM table)" case */
112174      int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
112175      VdbeCoverage(v);
112176
112177      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
112178      eType = IN_INDEX_ROWID;
112179      ExplainQueryPlan((pParse, 0,
112180            "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
112181      sqlite3VdbeJumpHere(v, iAddr);
112182    }else{
112183      Index *pIdx;                         /* Iterator variable */
112184      int affinity_ok = 1;
112185      int i;
112186
112187      /* Check that the affinity that will be used to perform each
112188      ** comparison is the same as the affinity of each column in table
112189      ** on the RHS of the IN operator.  If it not, it is not possible to
112190      ** use any index of the RHS table.  */
112191      for(i=0; i<nExpr && affinity_ok; i++){
112192        Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
112193        int iCol = pEList->a[i].pExpr->iColumn;
112194        char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
112195        char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
112196        testcase( cmpaff==SQLITE_AFF_BLOB );
112197        testcase( cmpaff==SQLITE_AFF_TEXT );
112198        switch( cmpaff ){
112199          case SQLITE_AFF_BLOB:
112200            break;
112201          case SQLITE_AFF_TEXT:
112202            /* sqlite3CompareAffinity() only returns TEXT if one side or the
112203            ** other has no affinity and the other side is TEXT.  Hence,
112204            ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
112205            ** and for the term on the LHS of the IN to have no affinity. */
112206            assert( idxaff==SQLITE_AFF_TEXT );
112207            break;
112208          default:
112209            affinity_ok = sqlite3IsNumericAffinity(idxaff);
112210        }
112211      }
112212
112213      if( affinity_ok ){
112214        /* Search for an existing index that will work for this IN operator */
112215        for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
112216          Bitmask colUsed;      /* Columns of the index used */
112217          Bitmask mCol;         /* Mask for the current column */
112218          if( pIdx->nColumn<nExpr ) continue;
112219          if( pIdx->pPartIdxWhere!=0 ) continue;
112220          /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
112221          ** BITMASK(nExpr) without overflowing */
112222          testcase( pIdx->nColumn==BMS-2 );
112223          testcase( pIdx->nColumn==BMS-1 );
112224          if( pIdx->nColumn>=BMS-1 ) continue;
112225          if( mustBeUnique ){
112226            if( pIdx->nKeyCol>nExpr
112227             ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
112228            ){
112229              continue;  /* This index is not unique over the IN RHS columns */
112230            }
112231          }
112232
112233          colUsed = 0;   /* Columns of index used so far */
112234          for(i=0; i<nExpr; i++){
112235            Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
112236            Expr *pRhs = pEList->a[i].pExpr;
112237            CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
112238            int j;
112239
112240            for(j=0; j<nExpr; j++){
112241              if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
112242              assert( pIdx->azColl[j] );
112243              if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
112244                continue;
112245              }
112246              break;
112247            }
112248            if( j==nExpr ) break;
112249            mCol = MASKBIT(j);
112250            if( mCol & colUsed ) break; /* Each column used only once */
112251            colUsed |= mCol;
112252            if( aiMap ) aiMap[i] = j;
112253          }
112254
112255          assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
112256          if( colUsed==(MASKBIT(nExpr)-1) ){
112257            /* If we reach this point, that means the index pIdx is usable */
112258            int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
112259            ExplainQueryPlan((pParse, 0,
112260                              "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
112261            sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
112262            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
112263            VdbeComment((v, "%s", pIdx->zName));
112264            assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
112265            eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
112266
112267            if( prRhsHasNull ){
112268#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
112269              i64 mask = (1<<nExpr)-1;
112270              sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
112271                  iTab, 0, 0, (u8*)&mask, P4_INT64);
112272#endif
112273              *prRhsHasNull = ++pParse->nMem;
112274              if( nExpr==1 ){
112275                sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
112276              }
112277            }
112278            sqlite3VdbeJumpHere(v, iAddr);
112279          }
112280        } /* End loop over indexes */
112281      } /* End if( affinity_ok ) */
112282    } /* End if not an rowid index */
112283  } /* End attempt to optimize using an index */
112284
112285  /* If no preexisting index is available for the IN clause
112286  ** and IN_INDEX_NOOP is an allowed reply
112287  ** and the RHS of the IN operator is a list, not a subquery
112288  ** and the RHS is not constant or has two or fewer terms,
112289  ** then it is not worth creating an ephemeral table to evaluate
112290  ** the IN operator so return IN_INDEX_NOOP.
112291  */
112292  if( eType==0
112293   && (inFlags & IN_INDEX_NOOP_OK)
112294   && ExprUseXList(pX)
112295   && (!sqlite3InRhsIsConstant(pParse,pX) || pX->x.pList->nExpr<=2)
112296  ){
112297    pParse->nTab--;  /* Back out the allocation of the unused cursor */
112298    iTab = -1;       /* Cursor is not allocated */
112299    eType = IN_INDEX_NOOP;
112300  }
112301
112302  if( eType==0 ){
112303    /* Could not find an existing table or index to use as the RHS b-tree.
112304    ** We will have to generate an ephemeral table to do the job.
112305    */
112306    u32 savedNQueryLoop = pParse->nQueryLoop;
112307    int rMayHaveNull = 0;
112308    eType = IN_INDEX_EPH;
112309    if( inFlags & IN_INDEX_LOOP ){
112310      pParse->nQueryLoop = 0;
112311    }else if( prRhsHasNull ){
112312      *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
112313    }
112314    assert( pX->op==TK_IN );
112315    sqlite3CodeRhsOfIN(pParse, pX, iTab);
112316    if( rMayHaveNull ){
112317      sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
112318    }
112319    pParse->nQueryLoop = savedNQueryLoop;
112320  }
112321
112322  if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
112323    int i, n;
112324    n = sqlite3ExprVectorSize(pX->pLeft);
112325    for(i=0; i<n; i++) aiMap[i] = i;
112326  }
112327  *piTab = iTab;
112328  return eType;
112329}
112330#endif
112331
112332#ifndef SQLITE_OMIT_SUBQUERY
112333/*
112334** Argument pExpr is an (?, ?...) IN(...) expression. This
112335** function allocates and returns a nul-terminated string containing
112336** the affinities to be used for each column of the comparison.
112337**
112338** It is the responsibility of the caller to ensure that the returned
112339** string is eventually freed using sqlite3DbFree().
112340*/
112341static char *exprINAffinity(Parse *pParse, const Expr *pExpr){
112342  Expr *pLeft = pExpr->pLeft;
112343  int nVal = sqlite3ExprVectorSize(pLeft);
112344  Select *pSelect = ExprUseXSelect(pExpr) ? pExpr->x.pSelect : 0;
112345  char *zRet;
112346
112347  assert( pExpr->op==TK_IN );
112348  zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
112349  if( zRet ){
112350    int i;
112351    for(i=0; i<nVal; i++){
112352      Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
112353      char a = sqlite3ExprAffinity(pA);
112354      if( pSelect ){
112355        zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
112356      }else{
112357        zRet[i] = a;
112358      }
112359    }
112360    zRet[nVal] = '\0';
112361  }
112362  return zRet;
112363}
112364#endif
112365
112366#ifndef SQLITE_OMIT_SUBQUERY
112367/*
112368** Load the Parse object passed as the first argument with an error
112369** message of the form:
112370**
112371**   "sub-select returns N columns - expected M"
112372*/
112373SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
112374  if( pParse->nErr==0 ){
112375    const char *zFmt = "sub-select returns %d columns - expected %d";
112376    sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
112377  }
112378}
112379#endif
112380
112381/*
112382** Expression pExpr is a vector that has been used in a context where
112383** it is not permitted. If pExpr is a sub-select vector, this routine
112384** loads the Parse object with a message of the form:
112385**
112386**   "sub-select returns N columns - expected 1"
112387**
112388** Or, if it is a regular scalar vector:
112389**
112390**   "row value misused"
112391*/
112392SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
112393#ifndef SQLITE_OMIT_SUBQUERY
112394  if( ExprUseXSelect(pExpr) ){
112395    sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
112396  }else
112397#endif
112398  {
112399    sqlite3ErrorMsg(pParse, "row value misused");
112400  }
112401}
112402
112403#ifndef SQLITE_OMIT_SUBQUERY
112404/*
112405** Generate code that will construct an ephemeral table containing all terms
112406** in the RHS of an IN operator.  The IN operator can be in either of two
112407** forms:
112408**
112409**     x IN (4,5,11)              -- IN operator with list on right-hand side
112410**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
112411**
112412** The pExpr parameter is the IN operator.  The cursor number for the
112413** constructed ephemeral table is returned.  The first time the ephemeral
112414** table is computed, the cursor number is also stored in pExpr->iTable,
112415** however the cursor number returned might not be the same, as it might
112416** have been duplicated using OP_OpenDup.
112417**
112418** If the LHS expression ("x" in the examples) is a column value, or
112419** the SELECT statement returns a column value, then the affinity of that
112420** column is used to build the index keys. If both 'x' and the
112421** SELECT... statement are columns, then numeric affinity is used
112422** if either column has NUMERIC or INTEGER affinity. If neither
112423** 'x' nor the SELECT... statement are columns, then numeric affinity
112424** is used.
112425*/
112426SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
112427  Parse *pParse,          /* Parsing context */
112428  Expr *pExpr,            /* The IN operator */
112429  int iTab                /* Use this cursor number */
112430){
112431  int addrOnce = 0;           /* Address of the OP_Once instruction at top */
112432  int addr;                   /* Address of OP_OpenEphemeral instruction */
112433  Expr *pLeft;                /* the LHS of the IN operator */
112434  KeyInfo *pKeyInfo = 0;      /* Key information */
112435  int nVal;                   /* Size of vector pLeft */
112436  Vdbe *v;                    /* The prepared statement under construction */
112437
112438  v = pParse->pVdbe;
112439  assert( v!=0 );
112440
112441  /* The evaluation of the IN must be repeated every time it
112442  ** is encountered if any of the following is true:
112443  **
112444  **    *  The right-hand side is a correlated subquery
112445  **    *  The right-hand side is an expression list containing variables
112446  **    *  We are inside a trigger
112447  **
112448  ** If all of the above are false, then we can compute the RHS just once
112449  ** and reuse it many names.
112450  */
112451  if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
112452    /* Reuse of the RHS is allowed */
112453    /* If this routine has already been coded, but the previous code
112454    ** might not have been invoked yet, so invoke it now as a subroutine.
112455    */
112456    if( ExprHasProperty(pExpr, EP_Subrtn) ){
112457      addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
112458      if( ExprUseXSelect(pExpr) ){
112459        ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
112460              pExpr->x.pSelect->selId));
112461      }
112462      assert( ExprUseYSub(pExpr) );
112463      sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
112464                        pExpr->y.sub.iAddr);
112465      assert( iTab!=pExpr->iTable );
112466      sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
112467      sqlite3VdbeJumpHere(v, addrOnce);
112468      return;
112469    }
112470
112471    /* Begin coding the subroutine */
112472    assert( !ExprUseYWin(pExpr) );
112473    ExprSetProperty(pExpr, EP_Subrtn);
112474    assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
112475    pExpr->y.sub.regReturn = ++pParse->nMem;
112476    pExpr->y.sub.iAddr =
112477      sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
112478
112479    addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
112480  }
112481
112482  /* Check to see if this is a vector IN operator */
112483  pLeft = pExpr->pLeft;
112484  nVal = sqlite3ExprVectorSize(pLeft);
112485
112486  /* Construct the ephemeral table that will contain the content of
112487  ** RHS of the IN operator.
112488  */
112489  pExpr->iTable = iTab;
112490  addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
112491#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
112492  if( ExprUseXSelect(pExpr) ){
112493    VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
112494  }else{
112495    VdbeComment((v, "RHS of IN operator"));
112496  }
112497#endif
112498  pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
112499
112500  if( ExprUseXSelect(pExpr) ){
112501    /* Case 1:     expr IN (SELECT ...)
112502    **
112503    ** Generate code to write the results of the select into the temporary
112504    ** table allocated and opened above.
112505    */
112506    Select *pSelect = pExpr->x.pSelect;
112507    ExprList *pEList = pSelect->pEList;
112508
112509    ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
112510        addrOnce?"":"CORRELATED ", pSelect->selId
112511    ));
112512    /* If the LHS and RHS of the IN operator do not match, that
112513    ** error will have been caught long before we reach this point. */
112514    if( ALWAYS(pEList->nExpr==nVal) ){
112515      Select *pCopy;
112516      SelectDest dest;
112517      int i;
112518      int rc;
112519      sqlite3SelectDestInit(&dest, SRT_Set, iTab);
112520      dest.zAffSdst = exprINAffinity(pParse, pExpr);
112521      pSelect->iLimit = 0;
112522      testcase( pSelect->selFlags & SF_Distinct );
112523      testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
112524      pCopy = sqlite3SelectDup(pParse->db, pSelect, 0);
112525      rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest);
112526      sqlite3SelectDelete(pParse->db, pCopy);
112527      sqlite3DbFree(pParse->db, dest.zAffSdst);
112528      if( rc ){
112529        sqlite3KeyInfoUnref(pKeyInfo);
112530        return;
112531      }
112532      assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
112533      assert( pEList!=0 );
112534      assert( pEList->nExpr>0 );
112535      assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
112536      for(i=0; i<nVal; i++){
112537        Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
112538        pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
112539            pParse, p, pEList->a[i].pExpr
112540        );
112541      }
112542    }
112543  }else if( ALWAYS(pExpr->x.pList!=0) ){
112544    /* Case 2:     expr IN (exprlist)
112545    **
112546    ** For each expression, build an index key from the evaluation and
112547    ** store it in the temporary table. If <expr> is a column, then use
112548    ** that columns affinity when building index keys. If <expr> is not
112549    ** a column, use numeric affinity.
112550    */
112551    char affinity;            /* Affinity of the LHS of the IN */
112552    int i;
112553    ExprList *pList = pExpr->x.pList;
112554    struct ExprList_item *pItem;
112555    int r1, r2;
112556    affinity = sqlite3ExprAffinity(pLeft);
112557    if( affinity<=SQLITE_AFF_NONE ){
112558      affinity = SQLITE_AFF_BLOB;
112559    }else if( affinity==SQLITE_AFF_REAL ){
112560      affinity = SQLITE_AFF_NUMERIC;
112561    }
112562    if( pKeyInfo ){
112563      assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
112564      pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
112565    }
112566
112567    /* Loop through each expression in <exprlist>. */
112568    r1 = sqlite3GetTempReg(pParse);
112569    r2 = sqlite3GetTempReg(pParse);
112570    for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
112571      Expr *pE2 = pItem->pExpr;
112572
112573      /* If the expression is not constant then we will need to
112574      ** disable the test that was generated above that makes sure
112575      ** this code only executes once.  Because for a non-constant
112576      ** expression we need to rerun this code each time.
112577      */
112578      if( addrOnce && !sqlite3ExprIsConstant(pParse, pE2) ){
112579        sqlite3VdbeChangeToNoop(v, addrOnce-1);
112580        sqlite3VdbeChangeToNoop(v, addrOnce);
112581        ExprClearProperty(pExpr, EP_Subrtn);
112582        addrOnce = 0;
112583      }
112584
112585      /* Evaluate the expression and insert it into the temp table */
112586      sqlite3ExprCode(pParse, pE2, r1);
112587      sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
112588      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
112589    }
112590    sqlite3ReleaseTempReg(pParse, r1);
112591    sqlite3ReleaseTempReg(pParse, r2);
112592  }
112593  if( pKeyInfo ){
112594    sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
112595  }
112596  if( addrOnce ){
112597    sqlite3VdbeAddOp1(v, OP_NullRow, iTab);
112598    sqlite3VdbeJumpHere(v, addrOnce);
112599    /* Subroutine return */
112600    assert( ExprUseYSub(pExpr) );
112601    assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
112602            || pParse->nErr );
112603    sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
112604                      pExpr->y.sub.iAddr, 1);
112605    VdbeCoverage(v);
112606    sqlite3ClearTempRegCache(pParse);
112607  }
112608}
112609#endif /* SQLITE_OMIT_SUBQUERY */
112610
112611/*
112612** Generate code for scalar subqueries used as a subquery expression
112613** or EXISTS operator:
112614**
112615**     (SELECT a FROM b)          -- subquery
112616**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
112617**
112618** The pExpr parameter is the SELECT or EXISTS operator to be coded.
112619**
112620** Return the register that holds the result.  For a multi-column SELECT,
112621** the result is stored in a contiguous array of registers and the
112622** return value is the register of the left-most result column.
112623** Return 0 if an error occurs.
112624*/
112625#ifndef SQLITE_OMIT_SUBQUERY
112626SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
112627  int addrOnce = 0;           /* Address of OP_Once at top of subroutine */
112628  int rReg = 0;               /* Register storing resulting */
112629  Select *pSel;               /* SELECT statement to encode */
112630  SelectDest dest;            /* How to deal with SELECT result */
112631  int nReg;                   /* Registers to allocate */
112632  Expr *pLimit;               /* New limit expression */
112633#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
112634  int addrExplain;            /* Address of OP_Explain instruction */
112635#endif
112636
112637  Vdbe *v = pParse->pVdbe;
112638  assert( v!=0 );
112639  if( pParse->nErr ) return 0;
112640  testcase( pExpr->op==TK_EXISTS );
112641  testcase( pExpr->op==TK_SELECT );
112642  assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
112643  assert( ExprUseXSelect(pExpr) );
112644  pSel = pExpr->x.pSelect;
112645
112646  /* If this routine has already been coded, then invoke it as a
112647  ** subroutine. */
112648  if( ExprHasProperty(pExpr, EP_Subrtn) ){
112649    ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
112650    assert( ExprUseYSub(pExpr) );
112651    sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
112652                      pExpr->y.sub.iAddr);
112653    return pExpr->iTable;
112654  }
112655
112656  /* Begin coding the subroutine */
112657  assert( !ExprUseYWin(pExpr) );
112658  assert( !ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) );
112659  ExprSetProperty(pExpr, EP_Subrtn);
112660  pExpr->y.sub.regReturn = ++pParse->nMem;
112661  pExpr->y.sub.iAddr =
112662    sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
112663
112664  /* The evaluation of the EXISTS/SELECT must be repeated every time it
112665  ** is encountered if any of the following is true:
112666  **
112667  **    *  The right-hand side is a correlated subquery
112668  **    *  The right-hand side is an expression list containing variables
112669  **    *  We are inside a trigger
112670  **
112671  ** If all of the above are false, then we can run this code just once
112672  ** save the results, and reuse the same result on subsequent invocations.
112673  */
112674  if( !ExprHasProperty(pExpr, EP_VarSelect) ){
112675    addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
112676  }
112677
112678  /* For a SELECT, generate code to put the values for all columns of
112679  ** the first row into an array of registers and return the index of
112680  ** the first register.
112681  **
112682  ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
112683  ** into a register and return that register number.
112684  **
112685  ** In both cases, the query is augmented with "LIMIT 1".  Any
112686  ** preexisting limit is discarded in place of the new LIMIT 1.
112687  */
112688  ExplainQueryPlan2(addrExplain, (pParse, 1, "%sSCALAR SUBQUERY %d",
112689        addrOnce?"":"CORRELATED ", pSel->selId));
112690  sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, -1);
112691  nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
112692  sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
112693  pParse->nMem += nReg;
112694  if( pExpr->op==TK_SELECT ){
112695    dest.eDest = SRT_Mem;
112696    dest.iSdst = dest.iSDParm;
112697    dest.nSdst = nReg;
112698    sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
112699    VdbeComment((v, "Init subquery result"));
112700  }else{
112701    dest.eDest = SRT_Exists;
112702    sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
112703    VdbeComment((v, "Init EXISTS result"));
112704  }
112705  if( pSel->pLimit ){
112706    /* The subquery already has a limit.  If the pre-existing limit is X
112707    ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
112708    sqlite3 *db = pParse->db;
112709    pLimit = sqlite3Expr(db, TK_INTEGER, "0");
112710    if( pLimit ){
112711      pLimit->affExpr = SQLITE_AFF_NUMERIC;
112712      pLimit = sqlite3PExpr(pParse, TK_NE,
112713                            sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
112714    }
112715    sqlite3ExprDeferredDelete(pParse, pSel->pLimit->pLeft);
112716    pSel->pLimit->pLeft = pLimit;
112717  }else{
112718    /* If there is no pre-existing limit add a limit of 1 */
112719    pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
112720    pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
112721  }
112722  pSel->iLimit = 0;
112723  if( sqlite3Select(pParse, pSel, &dest) ){
112724    pExpr->op2 = pExpr->op;
112725    pExpr->op = TK_ERROR;
112726    return 0;
112727  }
112728  pExpr->iTable = rReg = dest.iSDParm;
112729  ExprSetVVAProperty(pExpr, EP_NoReduce);
112730  if( addrOnce ){
112731    sqlite3VdbeJumpHere(v, addrOnce);
112732  }
112733  sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
112734
112735  /* Subroutine return */
112736  assert( ExprUseYSub(pExpr) );
112737  assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
112738          || pParse->nErr );
112739  sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
112740                    pExpr->y.sub.iAddr, 1);
112741  VdbeCoverage(v);
112742  sqlite3ClearTempRegCache(pParse);
112743  return rReg;
112744}
112745#endif /* SQLITE_OMIT_SUBQUERY */
112746
112747#ifndef SQLITE_OMIT_SUBQUERY
112748/*
112749** Expr pIn is an IN(...) expression. This function checks that the
112750** sub-select on the RHS of the IN() operator has the same number of
112751** columns as the vector on the LHS. Or, if the RHS of the IN() is not
112752** a sub-query, that the LHS is a vector of size 1.
112753*/
112754SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
112755  int nVector = sqlite3ExprVectorSize(pIn->pLeft);
112756  if( ExprUseXSelect(pIn) && !pParse->db->mallocFailed ){
112757    if( nVector!=pIn->x.pSelect->pEList->nExpr ){
112758      sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
112759      return 1;
112760    }
112761  }else if( nVector!=1 ){
112762    sqlite3VectorErrorMsg(pParse, pIn->pLeft);
112763    return 1;
112764  }
112765  return 0;
112766}
112767#endif
112768
112769#ifndef SQLITE_OMIT_SUBQUERY
112770/*
112771** Generate code for an IN expression.
112772**
112773**      x IN (SELECT ...)
112774**      x IN (value, value, ...)
112775**
112776** The left-hand side (LHS) is a scalar or vector expression.  The
112777** right-hand side (RHS) is an array of zero or more scalar values, or a
112778** subquery.  If the RHS is a subquery, the number of result columns must
112779** match the number of columns in the vector on the LHS.  If the RHS is
112780** a list of values, the LHS must be a scalar.
112781**
112782** The IN operator is true if the LHS value is contained within the RHS.
112783** The result is false if the LHS is definitely not in the RHS.  The
112784** result is NULL if the presence of the LHS in the RHS cannot be
112785** determined due to NULLs.
112786**
112787** This routine generates code that jumps to destIfFalse if the LHS is not
112788** contained within the RHS.  If due to NULLs we cannot determine if the LHS
112789** is contained in the RHS then jump to destIfNull.  If the LHS is contained
112790** within the RHS then fall through.
112791**
112792** See the separate in-operator.md documentation file in the canonical
112793** SQLite source tree for additional information.
112794*/
112795static void sqlite3ExprCodeIN(
112796  Parse *pParse,        /* Parsing and code generating context */
112797  Expr *pExpr,          /* The IN expression */
112798  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
112799  int destIfNull        /* Jump here if the results are unknown due to NULLs */
112800){
112801  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
112802  int eType;            /* Type of the RHS */
112803  int rLhs;             /* Register(s) holding the LHS values */
112804  int rLhsOrig;         /* LHS values prior to reordering by aiMap[] */
112805  Vdbe *v;              /* Statement under construction */
112806  int *aiMap = 0;       /* Map from vector field to index column */
112807  char *zAff = 0;       /* Affinity string for comparisons */
112808  int nVector;          /* Size of vectors for this IN operator */
112809  int iDummy;           /* Dummy parameter to exprCodeVector() */
112810  Expr *pLeft;          /* The LHS of the IN operator */
112811  int i;                /* loop counter */
112812  int destStep2;        /* Where to jump when NULLs seen in step 2 */
112813  int destStep6 = 0;    /* Start of code for Step 6 */
112814  int addrTruthOp;      /* Address of opcode that determines the IN is true */
112815  int destNotNull;      /* Jump here if a comparison is not true in step 6 */
112816  int addrTop;          /* Top of the step-6 loop */
112817  int iTab = 0;         /* Index to use */
112818  u8 okConstFactor = pParse->okConstFactor;
112819
112820  assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
112821  pLeft = pExpr->pLeft;
112822  if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
112823  zAff = exprINAffinity(pParse, pExpr);
112824  nVector = sqlite3ExprVectorSize(pExpr->pLeft);
112825  aiMap = (int*)sqlite3DbMallocZero(
112826      pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
112827  );
112828  if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
112829
112830  /* Attempt to compute the RHS. After this step, if anything other than
112831  ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
112832  ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
112833  ** the RHS has not yet been coded.  */
112834  v = pParse->pVdbe;
112835  assert( v!=0 );       /* OOM detected prior to this routine */
112836  VdbeNoopComment((v, "begin IN expr"));
112837  eType = sqlite3FindInIndex(pParse, pExpr,
112838                             IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
112839                             destIfFalse==destIfNull ? 0 : &rRhsHasNull,
112840                             aiMap, &iTab);
112841
112842  assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
112843       || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
112844  );
112845#ifdef SQLITE_DEBUG
112846  /* Confirm that aiMap[] contains nVector integer values between 0 and
112847  ** nVector-1. */
112848  for(i=0; i<nVector; i++){
112849    int j, cnt;
112850    for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
112851    assert( cnt==1 );
112852  }
112853#endif
112854
112855  /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
112856  ** vector, then it is stored in an array of nVector registers starting
112857  ** at r1.
112858  **
112859  ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
112860  ** so that the fields are in the same order as an existing index.   The
112861  ** aiMap[] array contains a mapping from the original LHS field order to
112862  ** the field order that matches the RHS index.
112863  **
112864  ** Avoid factoring the LHS of the IN(...) expression out of the loop,
112865  ** even if it is constant, as OP_Affinity may be used on the register
112866  ** by code generated below.  */
112867  assert( pParse->okConstFactor==okConstFactor );
112868  pParse->okConstFactor = 0;
112869  rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
112870  pParse->okConstFactor = okConstFactor;
112871  for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
112872  if( i==nVector ){
112873    /* LHS fields are not reordered */
112874    rLhs = rLhsOrig;
112875  }else{
112876    /* Need to reorder the LHS fields according to aiMap */
112877    rLhs = sqlite3GetTempRange(pParse, nVector);
112878    for(i=0; i<nVector; i++){
112879      sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
112880    }
112881  }
112882
112883  /* If sqlite3FindInIndex() did not find or create an index that is
112884  ** suitable for evaluating the IN operator, then evaluate using a
112885  ** sequence of comparisons.
112886  **
112887  ** This is step (1) in the in-operator.md optimized algorithm.
112888  */
112889  if( eType==IN_INDEX_NOOP ){
112890    ExprList *pList;
112891    CollSeq *pColl;
112892    int labelOk = sqlite3VdbeMakeLabel(pParse);
112893    int r2, regToFree;
112894    int regCkNull = 0;
112895    int ii;
112896    assert( ExprUseXList(pExpr) );
112897    pList = pExpr->x.pList;
112898    pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
112899    if( destIfNull!=destIfFalse ){
112900      regCkNull = sqlite3GetTempReg(pParse);
112901      sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
112902    }
112903    for(ii=0; ii<pList->nExpr; ii++){
112904      r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
112905      if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
112906        sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
112907      }
112908      sqlite3ReleaseTempReg(pParse, regToFree);
112909      if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
112910        int op = rLhs!=r2 ? OP_Eq : OP_NotNull;
112911        sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,
112912                          (void*)pColl, P4_COLLSEQ);
112913        VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
112914        VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
112915        VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
112916        VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
112917        sqlite3VdbeChangeP5(v, zAff[0]);
112918      }else{
112919        int op = rLhs!=r2 ? OP_Ne : OP_IsNull;
112920        assert( destIfNull==destIfFalse );
112921        sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,
112922                          (void*)pColl, P4_COLLSEQ);
112923        VdbeCoverageIf(v, op==OP_Ne);
112924        VdbeCoverageIf(v, op==OP_IsNull);
112925        sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
112926      }
112927    }
112928    if( regCkNull ){
112929      sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
112930      sqlite3VdbeGoto(v, destIfFalse);
112931    }
112932    sqlite3VdbeResolveLabel(v, labelOk);
112933    sqlite3ReleaseTempReg(pParse, regCkNull);
112934    goto sqlite3ExprCodeIN_finished;
112935  }
112936
112937  /* Step 2: Check to see if the LHS contains any NULL columns.  If the
112938  ** LHS does contain NULLs then the result must be either FALSE or NULL.
112939  ** We will then skip the binary search of the RHS.
112940  */
112941  if( destIfNull==destIfFalse ){
112942    destStep2 = destIfFalse;
112943  }else{
112944    destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
112945  }
112946  for(i=0; i<nVector; i++){
112947    Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
112948    if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error;
112949    if( sqlite3ExprCanBeNull(p) ){
112950      sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
112951      VdbeCoverage(v);
112952    }
112953  }
112954
112955  /* Step 3.  The LHS is now known to be non-NULL.  Do the binary search
112956  ** of the RHS using the LHS as a probe.  If found, the result is
112957  ** true.
112958  */
112959  if( eType==IN_INDEX_ROWID ){
112960    /* In this case, the RHS is the ROWID of table b-tree and so we also
112961    ** know that the RHS is non-NULL.  Hence, we combine steps 3 and 4
112962    ** into a single opcode. */
112963    sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
112964    VdbeCoverage(v);
112965    addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto);  /* Return True */
112966  }else{
112967    sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
112968    if( destIfFalse==destIfNull ){
112969      /* Combine Step 3 and Step 5 into a single opcode */
112970      sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
112971                           rLhs, nVector); VdbeCoverage(v);
112972      goto sqlite3ExprCodeIN_finished;
112973    }
112974    /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
112975    addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
112976                                      rLhs, nVector); VdbeCoverage(v);
112977  }
112978
112979  /* Step 4.  If the RHS is known to be non-NULL and we did not find
112980  ** an match on the search above, then the result must be FALSE.
112981  */
112982  if( rRhsHasNull && nVector==1 ){
112983    sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
112984    VdbeCoverage(v);
112985  }
112986
112987  /* Step 5.  If we do not care about the difference between NULL and
112988  ** FALSE, then just return false.
112989  */
112990  if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
112991
112992  /* Step 6: Loop through rows of the RHS.  Compare each row to the LHS.
112993  ** If any comparison is NULL, then the result is NULL.  If all
112994  ** comparisons are FALSE then the final result is FALSE.
112995  **
112996  ** For a scalar LHS, it is sufficient to check just the first row
112997  ** of the RHS.
112998  */
112999  if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
113000  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
113001  VdbeCoverage(v);
113002  if( nVector>1 ){
113003    destNotNull = sqlite3VdbeMakeLabel(pParse);
113004  }else{
113005    /* For nVector==1, combine steps 6 and 7 by immediately returning
113006    ** FALSE if the first comparison is not NULL */
113007    destNotNull = destIfFalse;
113008  }
113009  for(i=0; i<nVector; i++){
113010    Expr *p;
113011    CollSeq *pColl;
113012    int r3 = sqlite3GetTempReg(pParse);
113013    p = sqlite3VectorFieldSubexpr(pLeft, i);
113014    pColl = sqlite3ExprCollSeq(pParse, p);
113015    sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
113016    sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
113017                      (void*)pColl, P4_COLLSEQ);
113018    VdbeCoverage(v);
113019    sqlite3ReleaseTempReg(pParse, r3);
113020  }
113021  sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
113022  if( nVector>1 ){
113023    sqlite3VdbeResolveLabel(v, destNotNull);
113024    sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
113025    VdbeCoverage(v);
113026
113027    /* Step 7:  If we reach this point, we know that the result must
113028    ** be false. */
113029    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
113030  }
113031
113032  /* Jumps here in order to return true. */
113033  sqlite3VdbeJumpHere(v, addrTruthOp);
113034
113035sqlite3ExprCodeIN_finished:
113036  if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
113037  VdbeComment((v, "end IN expr"));
113038sqlite3ExprCodeIN_oom_error:
113039  sqlite3DbFree(pParse->db, aiMap);
113040  sqlite3DbFree(pParse->db, zAff);
113041}
113042#endif /* SQLITE_OMIT_SUBQUERY */
113043
113044#ifndef SQLITE_OMIT_FLOATING_POINT
113045/*
113046** Generate an instruction that will put the floating point
113047** value described by z[0..n-1] into register iMem.
113048**
113049** The z[] string will probably not be zero-terminated.  But the
113050** z[n] character is guaranteed to be something that does not look
113051** like the continuation of the number.
113052*/
113053static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
113054  if( ALWAYS(z!=0) ){
113055    double value;
113056    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
113057    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
113058    if( negateFlag ) value = -value;
113059    sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
113060  }
113061}
113062#endif
113063
113064
113065/*
113066** Generate an instruction that will put the integer describe by
113067** text z[0..n-1] into register iMem.
113068**
113069** Expr.u.zToken is always UTF8 and zero-terminated.
113070*/
113071static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
113072  Vdbe *v = pParse->pVdbe;
113073  if( pExpr->flags & EP_IntValue ){
113074    int i = pExpr->u.iValue;
113075    assert( i>=0 );
113076    if( negFlag ) i = -i;
113077    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
113078  }else{
113079    int c;
113080    i64 value;
113081    const char *z = pExpr->u.zToken;
113082    assert( z!=0 );
113083    c = sqlite3DecOrHexToI64(z, &value);
113084    if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
113085#ifdef SQLITE_OMIT_FLOATING_POINT
113086      sqlite3ErrorMsg(pParse, "oversized integer: %s%#T", negFlag?"-":"",pExpr);
113087#else
113088#ifndef SQLITE_OMIT_HEX_INTEGER
113089      if( sqlite3_strnicmp(z,"0x",2)==0 ){
113090        sqlite3ErrorMsg(pParse, "hex literal too big: %s%#T",
113091                        negFlag?"-":"",pExpr);
113092      }else
113093#endif
113094      {
113095        codeReal(v, z, negFlag, iMem);
113096      }
113097#endif
113098    }else{
113099      if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
113100      sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
113101    }
113102  }
113103}
113104
113105
113106/* Generate code that will load into register regOut a value that is
113107** appropriate for the iIdxCol-th column of index pIdx.
113108*/
113109SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
113110  Parse *pParse,  /* The parsing context */
113111  Index *pIdx,    /* The index whose column is to be loaded */
113112  int iTabCur,    /* Cursor pointing to a table row */
113113  int iIdxCol,    /* The column of the index to be loaded */
113114  int regOut      /* Store the index column value in this register */
113115){
113116  i16 iTabCol = pIdx->aiColumn[iIdxCol];
113117  if( iTabCol==XN_EXPR ){
113118    assert( pIdx->aColExpr );
113119    assert( pIdx->aColExpr->nExpr>iIdxCol );
113120    pParse->iSelfTab = iTabCur + 1;
113121    sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
113122    pParse->iSelfTab = 0;
113123  }else{
113124    sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
113125                                    iTabCol, regOut);
113126  }
113127}
113128
113129#ifndef SQLITE_OMIT_GENERATED_COLUMNS
113130/*
113131** Generate code that will compute the value of generated column pCol
113132** and store the result in register regOut
113133*/
113134SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(
113135  Parse *pParse,     /* Parsing context */
113136  Table *pTab,       /* Table containing the generated column */
113137  Column *pCol,      /* The generated column */
113138  int regOut         /* Put the result in this register */
113139){
113140  int iAddr;
113141  Vdbe *v = pParse->pVdbe;
113142  int nErr = pParse->nErr;
113143  assert( v!=0 );
113144  assert( pParse->iSelfTab!=0 );
113145  if( pParse->iSelfTab>0 ){
113146    iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
113147  }else{
113148    iAddr = 0;
113149  }
113150  sqlite3ExprCodeCopy(pParse, sqlite3ColumnExpr(pTab,pCol), regOut);
113151  if( pCol->affinity>=SQLITE_AFF_TEXT ){
113152    sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
113153  }
113154  if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
113155  if( pParse->nErr>nErr ) pParse->db->errByteOffset = -1;
113156}
113157#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
113158
113159/*
113160** Generate code to extract the value of the iCol-th column of a table.
113161*/
113162SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
113163  Vdbe *v,        /* Parsing context */
113164  Table *pTab,    /* The table containing the value */
113165  int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
113166  int iCol,       /* Index of the column to extract */
113167  int regOut      /* Extract the value into this register */
113168){
113169  Column *pCol;
113170  assert( v!=0 );
113171  assert( pTab!=0 );
113172  assert( iCol!=XN_EXPR );
113173  if( iCol<0 || iCol==pTab->iPKey ){
113174    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
113175    VdbeComment((v, "%s.rowid", pTab->zName));
113176  }else{
113177    int op;
113178    int x;
113179    if( IsVirtual(pTab) ){
113180      op = OP_VColumn;
113181      x = iCol;
113182#ifndef SQLITE_OMIT_GENERATED_COLUMNS
113183    }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
113184      Parse *pParse = sqlite3VdbeParser(v);
113185      if( pCol->colFlags & COLFLAG_BUSY ){
113186        sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
113187                        pCol->zCnName);
113188      }else{
113189        int savedSelfTab = pParse->iSelfTab;
113190        pCol->colFlags |= COLFLAG_BUSY;
113191        pParse->iSelfTab = iTabCur+1;
113192        sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, regOut);
113193        pParse->iSelfTab = savedSelfTab;
113194        pCol->colFlags &= ~COLFLAG_BUSY;
113195      }
113196      return;
113197#endif
113198    }else if( !HasRowid(pTab) ){
113199      testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
113200      x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
113201      op = OP_Column;
113202    }else{
113203      x = sqlite3TableColumnToStorage(pTab,iCol);
113204      testcase( x!=iCol );
113205      op = OP_Column;
113206    }
113207    sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
113208    sqlite3ColumnDefault(v, pTab, iCol, regOut);
113209  }
113210}
113211
113212/*
113213** Generate code that will extract the iColumn-th column from
113214** table pTab and store the column value in register iReg.
113215**
113216** There must be an open cursor to pTab in iTable when this routine
113217** is called.  If iColumn<0 then code is generated that extracts the rowid.
113218*/
113219SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
113220  Parse *pParse,   /* Parsing and code generating context */
113221  Table *pTab,     /* Description of the table we are reading from */
113222  int iColumn,     /* Index of the table column */
113223  int iTable,      /* The cursor pointing to the table */
113224  int iReg,        /* Store results here */
113225  u8 p5            /* P5 value for OP_Column + FLAGS */
113226){
113227  assert( pParse->pVdbe!=0 );
113228  assert( (p5 & (OPFLAG_NOCHNG|OPFLAG_TYPEOFARG|OPFLAG_LENGTHARG))==p5 );
113229  assert( IsVirtual(pTab) || (p5 & OPFLAG_NOCHNG)==0 );
113230  sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
113231  if( p5 ){
113232    VdbeOp *pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
113233    if( pOp->opcode==OP_Column ) pOp->p5 = p5;
113234    if( pOp->opcode==OP_VColumn ) pOp->p5 = (p5 & OPFLAG_NOCHNG);
113235  }
113236  return iReg;
113237}
113238
113239/*
113240** Generate code to move content from registers iFrom...iFrom+nReg-1
113241** over to iTo..iTo+nReg-1.
113242*/
113243SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
113244  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
113245}
113246
113247/*
113248** Convert a scalar expression node to a TK_REGISTER referencing
113249** register iReg.  The caller must ensure that iReg already contains
113250** the correct value for the expression.
113251*/
113252static void exprToRegister(Expr *pExpr, int iReg){
113253  Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
113254  if( NEVER(p==0) ) return;
113255  p->op2 = p->op;
113256  p->op = TK_REGISTER;
113257  p->iTable = iReg;
113258  ExprClearProperty(p, EP_Skip);
113259}
113260
113261/*
113262** Evaluate an expression (either a vector or a scalar expression) and store
113263** the result in contiguous temporary registers.  Return the index of
113264** the first register used to store the result.
113265**
113266** If the returned result register is a temporary scalar, then also write
113267** that register number into *piFreeable.  If the returned result register
113268** is not a temporary or if the expression is a vector set *piFreeable
113269** to 0.
113270*/
113271static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
113272  int iResult;
113273  int nResult = sqlite3ExprVectorSize(p);
113274  if( nResult==1 ){
113275    iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
113276  }else{
113277    *piFreeable = 0;
113278    if( p->op==TK_SELECT ){
113279#if SQLITE_OMIT_SUBQUERY
113280      iResult = 0;
113281#else
113282      iResult = sqlite3CodeSubselect(pParse, p);
113283#endif
113284    }else{
113285      int i;
113286      iResult = pParse->nMem+1;
113287      pParse->nMem += nResult;
113288      assert( ExprUseXList(p) );
113289      for(i=0; i<nResult; i++){
113290        sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
113291      }
113292    }
113293  }
113294  return iResult;
113295}
113296
113297/*
113298** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
113299** so that a subsequent copy will not be merged into this one.
113300*/
113301static void setDoNotMergeFlagOnCopy(Vdbe *v){
113302  if( sqlite3VdbeGetLastOp(v)->opcode==OP_Copy ){
113303    sqlite3VdbeChangeP5(v, 1);  /* Tag trailing OP_Copy as not mergeable */
113304  }
113305}
113306
113307/*
113308** Generate code to implement special SQL functions that are implemented
113309** in-line rather than by using the usual callbacks.
113310*/
113311static int exprCodeInlineFunction(
113312  Parse *pParse,        /* Parsing context */
113313  ExprList *pFarg,      /* List of function arguments */
113314  int iFuncId,          /* Function ID.  One of the INTFUNC_... values */
113315  int target            /* Store function result in this register */
113316){
113317  int nFarg;
113318  Vdbe *v = pParse->pVdbe;
113319  assert( v!=0 );
113320  assert( pFarg!=0 );
113321  nFarg = pFarg->nExpr;
113322  assert( nFarg>0 );  /* All in-line functions have at least one argument */
113323  switch( iFuncId ){
113324    case INLINEFUNC_coalesce: {
113325      /* Attempt a direct implementation of the built-in COALESCE() and
113326      ** IFNULL() functions.  This avoids unnecessary evaluation of
113327      ** arguments past the first non-NULL argument.
113328      */
113329      int endCoalesce = sqlite3VdbeMakeLabel(pParse);
113330      int i;
113331      assert( nFarg>=2 );
113332      sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
113333      for(i=1; i<nFarg; i++){
113334        sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
113335        VdbeCoverage(v);
113336        sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
113337      }
113338      setDoNotMergeFlagOnCopy(v);
113339      sqlite3VdbeResolveLabel(v, endCoalesce);
113340      break;
113341    }
113342    case INLINEFUNC_iif: {
113343      Expr caseExpr;
113344      memset(&caseExpr, 0, sizeof(caseExpr));
113345      caseExpr.op = TK_CASE;
113346      caseExpr.x.pList = pFarg;
113347      return sqlite3ExprCodeTarget(pParse, &caseExpr, target);
113348    }
113349#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
113350    case INLINEFUNC_sqlite_offset: {
113351      Expr *pArg = pFarg->a[0].pExpr;
113352      if( pArg->op==TK_COLUMN && pArg->iTable>=0 ){
113353        sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
113354      }else{
113355        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
113356      }
113357      break;
113358    }
113359#endif
113360    default: {
113361      /* The UNLIKELY() function is a no-op.  The result is the value
113362      ** of the first argument.
113363      */
113364      assert( nFarg==1 || nFarg==2 );
113365      target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
113366      break;
113367    }
113368
113369  /***********************************************************************
113370  ** Test-only SQL functions that are only usable if enabled
113371  ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
113372  */
113373#if !defined(SQLITE_UNTESTABLE)
113374    case INLINEFUNC_expr_compare: {
113375      /* Compare two expressions using sqlite3ExprCompare() */
113376      assert( nFarg==2 );
113377      sqlite3VdbeAddOp2(v, OP_Integer,
113378         sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
113379         target);
113380      break;
113381    }
113382
113383    case INLINEFUNC_expr_implies_expr: {
113384      /* Compare two expressions using sqlite3ExprImpliesExpr() */
113385      assert( nFarg==2 );
113386      sqlite3VdbeAddOp2(v, OP_Integer,
113387         sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
113388         target);
113389      break;
113390    }
113391
113392    case INLINEFUNC_implies_nonnull_row: {
113393      /* Result of sqlite3ExprImpliesNonNullRow() */
113394      Expr *pA1;
113395      assert( nFarg==2 );
113396      pA1 = pFarg->a[1].pExpr;
113397      if( pA1->op==TK_COLUMN ){
113398        sqlite3VdbeAddOp2(v, OP_Integer,
113399           sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable,1),
113400           target);
113401      }else{
113402        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
113403      }
113404      break;
113405    }
113406
113407    case INLINEFUNC_affinity: {
113408      /* The AFFINITY() function evaluates to a string that describes
113409      ** the type affinity of the argument.  This is used for testing of
113410      ** the SQLite type logic.
113411      */
113412      const char *azAff[] = { "blob", "text", "numeric", "integer",
113413                              "real", "flexnum" };
113414      char aff;
113415      assert( nFarg==1 );
113416      aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
113417      assert( aff<=SQLITE_AFF_NONE
113418           || (aff>=SQLITE_AFF_BLOB && aff<=SQLITE_AFF_FLEXNUM) );
113419      sqlite3VdbeLoadString(v, target,
113420              (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
113421      break;
113422    }
113423#endif /* !defined(SQLITE_UNTESTABLE) */
113424  }
113425  return target;
113426}
113427
113428/*
113429** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
113430** If it is, then resolve the expression by reading from the index and
113431** return the register into which the value has been read.  If pExpr is
113432** not an indexed expression, then return negative.
113433*/
113434static SQLITE_NOINLINE int sqlite3IndexedExprLookup(
113435  Parse *pParse,   /* The parsing context */
113436  Expr *pExpr,     /* The expression to potentially bypass */
113437  int target       /* Where to store the result of the expression */
113438){
113439  IndexedExpr *p;
113440  Vdbe *v;
113441  for(p=pParse->pIdxEpr; p; p=p->pIENext){
113442    u8 exprAff;
113443    int iDataCur = p->iDataCur;
113444    if( iDataCur<0 ) continue;
113445    if( pParse->iSelfTab ){
113446      if( p->iDataCur!=pParse->iSelfTab-1 ) continue;
113447      iDataCur = -1;
113448    }
113449    if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) continue;
113450    assert( p->aff>=SQLITE_AFF_BLOB && p->aff<=SQLITE_AFF_NUMERIC );
113451    exprAff = sqlite3ExprAffinity(pExpr);
113452    if( (exprAff<=SQLITE_AFF_BLOB && p->aff!=SQLITE_AFF_BLOB)
113453     || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT)
113454     || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC)
113455    ){
113456      /* Affinity mismatch on a generated column */
113457      continue;
113458    }
113459
113460    v = pParse->pVdbe;
113461    assert( v!=0 );
113462    if( p->bMaybeNullRow ){
113463      /* If the index is on a NULL row due to an outer join, then we
113464      ** cannot extract the value from the index.  The value must be
113465      ** computed using the original expression. */
113466      int addr = sqlite3VdbeCurrentAddr(v);
113467      sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target);
113468      VdbeCoverage(v);
113469      sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
113470      VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
113471      sqlite3VdbeGoto(v, 0);
113472      p = pParse->pIdxEpr;
113473      pParse->pIdxEpr = 0;
113474      sqlite3ExprCode(pParse, pExpr, target);
113475      pParse->pIdxEpr = p;
113476      sqlite3VdbeJumpHere(v, addr+2);
113477    }else{
113478      sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
113479      VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
113480    }
113481    return target;
113482  }
113483  return -1;  /* Not found */
113484}
113485
113486
113487/*
113488** Expresion pExpr is guaranteed to be a TK_COLUMN or equivalent. This
113489** function checks the Parse.pIdxPartExpr list to see if this column
113490** can be replaced with a constant value. If so, it generates code to
113491** put the constant value in a register (ideally, but not necessarily,
113492** register iTarget) and returns the register number.
113493**
113494** Or, if the TK_COLUMN cannot be replaced by a constant, zero is
113495** returned.
113496*/
113497static int exprPartidxExprLookup(Parse *pParse, Expr *pExpr, int iTarget){
113498  IndexedExpr *p;
113499  for(p=pParse->pIdxPartExpr; p; p=p->pIENext){
113500    if( pExpr->iColumn==p->iIdxCol && pExpr->iTable==p->iDataCur ){
113501      Vdbe *v = pParse->pVdbe;
113502      int addr = 0;
113503      int ret;
113504
113505      if( p->bMaybeNullRow ){
113506        addr = sqlite3VdbeAddOp1(v, OP_IfNullRow, p->iIdxCur);
113507      }
113508      ret = sqlite3ExprCodeTarget(pParse, p->pExpr, iTarget);
113509      sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, ret, 1, 0,
113510                        (const char*)&p->aff, 1);
113511      if( addr ){
113512        sqlite3VdbeJumpHere(v, addr);
113513        sqlite3VdbeChangeP3(v, addr, ret);
113514      }
113515      return ret;
113516    }
113517  }
113518  return 0;
113519}
113520
113521
113522/*
113523** Generate code into the current Vdbe to evaluate the given
113524** expression.  Attempt to store the results in register "target".
113525** Return the register where results are stored.
113526**
113527** With this routine, there is no guarantee that results will
113528** be stored in target.  The result might be stored in some other
113529** register if it is convenient to do so.  The calling function
113530** must check the return code and move the results to the desired
113531** register.
113532*/
113533SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
113534  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
113535  int op;                   /* The opcode being coded */
113536  int inReg = target;       /* Results stored in register inReg */
113537  int regFree1 = 0;         /* If non-zero free this temporary register */
113538  int regFree2 = 0;         /* If non-zero free this temporary register */
113539  int r1, r2;               /* Various register numbers */
113540  Expr tempX;               /* Temporary expression node */
113541  int p5 = 0;
113542
113543  assert( target>0 && target<=pParse->nMem );
113544  assert( v!=0 );
113545
113546expr_code_doover:
113547  if( pExpr==0 ){
113548    op = TK_NULL;
113549  }else if( pParse->pIdxEpr!=0
113550   && !ExprHasProperty(pExpr, EP_Leaf)
113551   && (r1 = sqlite3IndexedExprLookup(pParse, pExpr, target))>=0
113552  ){
113553    return r1;
113554  }else{
113555    assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
113556    op = pExpr->op;
113557  }
113558  assert( op!=TK_ORDER );
113559  switch( op ){
113560    case TK_AGG_COLUMN: {
113561      AggInfo *pAggInfo = pExpr->pAggInfo;
113562      struct AggInfo_col *pCol;
113563      assert( pAggInfo!=0 );
113564      assert( pExpr->iAgg>=0 );
113565      if( pExpr->iAgg>=pAggInfo->nColumn ){
113566        /* Happens when the left table of a RIGHT JOIN is null and
113567        ** is using an expression index */
113568        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
113569#ifdef SQLITE_VDBE_COVERAGE
113570        /* Verify that the OP_Null above is exercised by tests
113571        ** tag-20230325-2 */
113572        sqlite3VdbeAddOp3(v, OP_NotNull, target, 1, 20230325);
113573        VdbeCoverageNeverTaken(v);
113574#endif
113575        break;
113576      }
113577      pCol = &pAggInfo->aCol[pExpr->iAgg];
113578      if( !pAggInfo->directMode ){
113579        return AggInfoColumnReg(pAggInfo, pExpr->iAgg);
113580      }else if( pAggInfo->useSortingIdx ){
113581        Table *pTab = pCol->pTab;
113582        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
113583                              pCol->iSorterColumn, target);
113584        if( pTab==0 ){
113585          /* No comment added */
113586        }else if( pCol->iColumn<0 ){
113587          VdbeComment((v,"%s.rowid",pTab->zName));
113588        }else{
113589          VdbeComment((v,"%s.%s",
113590              pTab->zName, pTab->aCol[pCol->iColumn].zCnName));
113591          if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
113592            sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
113593          }
113594        }
113595        return target;
113596      }else if( pExpr->y.pTab==0 ){
113597        /* This case happens when the argument to an aggregate function
113598        ** is rewritten by aggregateConvertIndexedExprRefToColumn() */
113599        sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, pExpr->iColumn, target);
113600        return target;
113601      }
113602      /* Otherwise, fall thru into the TK_COLUMN case */
113603      /* no break */ deliberate_fall_through
113604    }
113605    case TK_COLUMN: {
113606      int iTab = pExpr->iTable;
113607      int iReg;
113608      if( ExprHasProperty(pExpr, EP_FixedCol) ){
113609        /* This COLUMN expression is really a constant due to WHERE clause
113610        ** constraints, and that constant is coded by the pExpr->pLeft
113611        ** expression.  However, make sure the constant has the correct
113612        ** datatype by applying the Affinity of the table column to the
113613        ** constant.
113614        */
113615        int aff;
113616        iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
113617        assert( ExprUseYTab(pExpr) );
113618        assert( pExpr->y.pTab!=0 );
113619        aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
113620        if( aff>SQLITE_AFF_BLOB ){
113621          static const char zAff[] = "B\000C\000D\000E\000F";
113622          assert( SQLITE_AFF_BLOB=='A' );
113623          assert( SQLITE_AFF_TEXT=='B' );
113624          sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
113625                            &zAff[(aff-'B')*2], P4_STATIC);
113626        }
113627        return iReg;
113628      }
113629      if( iTab<0 ){
113630        if( pParse->iSelfTab<0 ){
113631          /* Other columns in the same row for CHECK constraints or
113632          ** generated columns or for inserting into partial index.
113633          ** The row is unpacked into registers beginning at
113634          ** 0-(pParse->iSelfTab).  The rowid (if any) is in a register
113635          ** immediately prior to the first column.
113636          */
113637          Column *pCol;
113638          Table *pTab;
113639          int iSrc;
113640          int iCol = pExpr->iColumn;
113641          assert( ExprUseYTab(pExpr) );
113642          pTab = pExpr->y.pTab;
113643          assert( pTab!=0 );
113644          assert( iCol>=XN_ROWID );
113645          assert( iCol<pTab->nCol );
113646          if( iCol<0 ){
113647            return -1-pParse->iSelfTab;
113648          }
113649          pCol = pTab->aCol + iCol;
113650          testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
113651          iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
113652#ifndef SQLITE_OMIT_GENERATED_COLUMNS
113653          if( pCol->colFlags & COLFLAG_GENERATED ){
113654            if( pCol->colFlags & COLFLAG_BUSY ){
113655              sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
113656                              pCol->zCnName);
113657              return 0;
113658            }
113659            pCol->colFlags |= COLFLAG_BUSY;
113660            if( pCol->colFlags & COLFLAG_NOTAVAIL ){
113661              sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, iSrc);
113662            }
113663            pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
113664            return iSrc;
113665          }else
113666#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
113667          if( pCol->affinity==SQLITE_AFF_REAL ){
113668            sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
113669            sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
113670            return target;
113671          }else{
113672            return iSrc;
113673          }
113674        }else{
113675          /* Coding an expression that is part of an index where column names
113676          ** in the index refer to the table to which the index belongs */
113677          iTab = pParse->iSelfTab - 1;
113678        }
113679      }
113680      else if( pParse->pIdxPartExpr
113681       && 0!=(r1 = exprPartidxExprLookup(pParse, pExpr, target))
113682      ){
113683        return r1;
113684      }
113685      assert( ExprUseYTab(pExpr) );
113686      assert( pExpr->y.pTab!=0 );
113687      iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
113688                               pExpr->iColumn, iTab, target,
113689                               pExpr->op2);
113690      return iReg;
113691    }
113692    case TK_INTEGER: {
113693      codeInteger(pParse, pExpr, 0, target);
113694      return target;
113695    }
113696    case TK_TRUEFALSE: {
113697      sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
113698      return target;
113699    }
113700#ifndef SQLITE_OMIT_FLOATING_POINT
113701    case TK_FLOAT: {
113702      assert( !ExprHasProperty(pExpr, EP_IntValue) );
113703      codeReal(v, pExpr->u.zToken, 0, target);
113704      return target;
113705    }
113706#endif
113707    case TK_STRING: {
113708      assert( !ExprHasProperty(pExpr, EP_IntValue) );
113709      sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
113710      return target;
113711    }
113712    default: {
113713      /* Make NULL the default case so that if a bug causes an illegal
113714      ** Expr node to be passed into this function, it will be handled
113715      ** sanely and not crash.  But keep the assert() to bring the problem
113716      ** to the attention of the developers. */
113717      assert( op==TK_NULL || op==TK_ERROR || pParse->db->mallocFailed );
113718      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
113719      return target;
113720    }
113721#ifndef SQLITE_OMIT_BLOB_LITERAL
113722    case TK_BLOB: {
113723      int n;
113724      const char *z;
113725      char *zBlob;
113726      assert( !ExprHasProperty(pExpr, EP_IntValue) );
113727      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
113728      assert( pExpr->u.zToken[1]=='\'' );
113729      z = &pExpr->u.zToken[2];
113730      n = sqlite3Strlen30(z) - 1;
113731      assert( z[n]=='\'' );
113732      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
113733      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
113734      return target;
113735    }
113736#endif
113737    case TK_VARIABLE: {
113738      assert( !ExprHasProperty(pExpr, EP_IntValue) );
113739      assert( pExpr->u.zToken!=0 );
113740      assert( pExpr->u.zToken[0]!=0 );
113741      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
113742      return target;
113743    }
113744    case TK_REGISTER: {
113745      return pExpr->iTable;
113746    }
113747#ifndef SQLITE_OMIT_CAST
113748    case TK_CAST: {
113749      /* Expressions of the form:   CAST(pLeft AS token) */
113750      sqlite3ExprCode(pParse, pExpr->pLeft, target);
113751      assert( inReg==target );
113752      assert( !ExprHasProperty(pExpr, EP_IntValue) );
113753      sqlite3VdbeAddOp2(v, OP_Cast, target,
113754                        sqlite3AffinityType(pExpr->u.zToken, 0));
113755      return inReg;
113756    }
113757#endif /* SQLITE_OMIT_CAST */
113758    case TK_IS:
113759    case TK_ISNOT:
113760      op = (op==TK_IS) ? TK_EQ : TK_NE;
113761      p5 = SQLITE_NULLEQ;
113762      /* fall-through */
113763    case TK_LT:
113764    case TK_LE:
113765    case TK_GT:
113766    case TK_GE:
113767    case TK_NE:
113768    case TK_EQ: {
113769      Expr *pLeft = pExpr->pLeft;
113770      if( sqlite3ExprIsVector(pLeft) ){
113771        codeVectorCompare(pParse, pExpr, target, op, p5);
113772      }else{
113773        r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
113774        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
113775        sqlite3VdbeAddOp2(v, OP_Integer, 1, inReg);
113776        codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2,
113777            sqlite3VdbeCurrentAddr(v)+2, p5,
113778            ExprHasProperty(pExpr,EP_Commuted));
113779        assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
113780        assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
113781        assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
113782        assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
113783        assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
113784        assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
113785        if( p5==SQLITE_NULLEQ ){
113786          sqlite3VdbeAddOp2(v, OP_Integer, 0, inReg);
113787        }else{
113788          sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, inReg, r2);
113789        }
113790        testcase( regFree1==0 );
113791        testcase( regFree2==0 );
113792      }
113793      break;
113794    }
113795    case TK_AND:
113796    case TK_OR:
113797    case TK_PLUS:
113798    case TK_STAR:
113799    case TK_MINUS:
113800    case TK_REM:
113801    case TK_BITAND:
113802    case TK_BITOR:
113803    case TK_SLASH:
113804    case TK_LSHIFT:
113805    case TK_RSHIFT:
113806    case TK_CONCAT: {
113807      assert( TK_AND==OP_And );            testcase( op==TK_AND );
113808      assert( TK_OR==OP_Or );              testcase( op==TK_OR );
113809      assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
113810      assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
113811      assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
113812      assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
113813      assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
113814      assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
113815      assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
113816      assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
113817      assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
113818      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
113819      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
113820      sqlite3VdbeAddOp3(v, op, r2, r1, target);
113821      testcase( regFree1==0 );
113822      testcase( regFree2==0 );
113823      break;
113824    }
113825    case TK_UMINUS: {
113826      Expr *pLeft = pExpr->pLeft;
113827      assert( pLeft );
113828      if( pLeft->op==TK_INTEGER ){
113829        codeInteger(pParse, pLeft, 1, target);
113830        return target;
113831#ifndef SQLITE_OMIT_FLOATING_POINT
113832      }else if( pLeft->op==TK_FLOAT ){
113833        assert( !ExprHasProperty(pExpr, EP_IntValue) );
113834        codeReal(v, pLeft->u.zToken, 1, target);
113835        return target;
113836#endif
113837      }else{
113838        tempX.op = TK_INTEGER;
113839        tempX.flags = EP_IntValue|EP_TokenOnly;
113840        tempX.u.iValue = 0;
113841        ExprClearVVAProperties(&tempX);
113842        r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
113843        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
113844        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
113845        testcase( regFree2==0 );
113846      }
113847      break;
113848    }
113849    case TK_BITNOT:
113850    case TK_NOT: {
113851      assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
113852      assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
113853      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
113854      testcase( regFree1==0 );
113855      sqlite3VdbeAddOp2(v, op, r1, inReg);
113856      break;
113857    }
113858    case TK_TRUTH: {
113859      int isTrue;    /* IS TRUE or IS NOT TRUE */
113860      int bNormal;   /* IS TRUE or IS FALSE */
113861      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
113862      testcase( regFree1==0 );
113863      isTrue = sqlite3ExprTruthValue(pExpr->pRight);
113864      bNormal = pExpr->op2==TK_IS;
113865      testcase( isTrue && bNormal);
113866      testcase( !isTrue && bNormal);
113867      sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
113868      break;
113869    }
113870    case TK_ISNULL:
113871    case TK_NOTNULL: {
113872      int addr;
113873      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
113874      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
113875      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
113876      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
113877      testcase( regFree1==0 );
113878      addr = sqlite3VdbeAddOp1(v, op, r1);
113879      VdbeCoverageIf(v, op==TK_ISNULL);
113880      VdbeCoverageIf(v, op==TK_NOTNULL);
113881      sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
113882      sqlite3VdbeJumpHere(v, addr);
113883      break;
113884    }
113885    case TK_AGG_FUNCTION: {
113886      AggInfo *pInfo = pExpr->pAggInfo;
113887      if( pInfo==0
113888       || NEVER(pExpr->iAgg<0)
113889       || NEVER(pExpr->iAgg>=pInfo->nFunc)
113890      ){
113891        assert( !ExprHasProperty(pExpr, EP_IntValue) );
113892        sqlite3ErrorMsg(pParse, "misuse of aggregate: %#T()", pExpr);
113893      }else{
113894        return AggInfoFuncReg(pInfo, pExpr->iAgg);
113895      }
113896      break;
113897    }
113898    case TK_FUNCTION: {
113899      ExprList *pFarg;       /* List of function arguments */
113900      int nFarg;             /* Number of function arguments */
113901      FuncDef *pDef;         /* The function definition object */
113902      const char *zId;       /* The function name */
113903      u32 constMask = 0;     /* Mask of function arguments that are constant */
113904      int i;                 /* Loop counter */
113905      sqlite3 *db = pParse->db;  /* The database connection */
113906      u8 enc = ENC(db);      /* The text encoding used by this database */
113907      CollSeq *pColl = 0;    /* A collating sequence */
113908
113909#ifndef SQLITE_OMIT_WINDOWFUNC
113910      if( ExprHasProperty(pExpr, EP_WinFunc) ){
113911        return pExpr->y.pWin->regResult;
113912      }
113913#endif
113914
113915      if( ConstFactorOk(pParse)
113916       && sqlite3ExprIsConstantNotJoin(pParse,pExpr)
113917      ){
113918        /* SQL functions can be expensive. So try to avoid running them
113919        ** multiple times if we know they always give the same result */
113920        return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
113921      }
113922      assert( !ExprHasProperty(pExpr, EP_TokenOnly) );
113923      assert( ExprUseXList(pExpr) );
113924      pFarg = pExpr->x.pList;
113925      nFarg = pFarg ? pFarg->nExpr : 0;
113926      assert( !ExprHasProperty(pExpr, EP_IntValue) );
113927      zId = pExpr->u.zToken;
113928      pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
113929#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
113930      if( pDef==0 && pParse->explain ){
113931        pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
113932      }
113933#endif
113934      if( pDef==0 || pDef->xFinalize!=0 ){
113935        sqlite3ErrorMsg(pParse, "unknown function: %#T()", pExpr);
113936        break;
113937      }
113938      if( (pDef->funcFlags & SQLITE_FUNC_INLINE)!=0 && ALWAYS(pFarg!=0) ){
113939        assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
113940        assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
113941        return exprCodeInlineFunction(pParse, pFarg,
113942             SQLITE_PTR_TO_INT(pDef->pUserData), target);
113943      }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
113944        sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
113945      }
113946
113947      for(i=0; i<nFarg; i++){
113948        if( i<32 && sqlite3ExprIsConstant(pParse, pFarg->a[i].pExpr) ){
113949          testcase( i==31 );
113950          constMask |= MASKBIT32(i);
113951        }
113952        if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
113953          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
113954        }
113955      }
113956      if( pFarg ){
113957        if( constMask ){
113958          r1 = pParse->nMem+1;
113959          pParse->nMem += nFarg;
113960        }else{
113961          r1 = sqlite3GetTempRange(pParse, nFarg);
113962        }
113963
113964        /* For length() and typeof() and octet_length() functions,
113965        ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
113966        ** or OPFLAG_TYPEOFARG or OPFLAG_BYTELENARG respectively, to avoid
113967        ** unnecessary data loading.
113968        */
113969        if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
113970          u8 exprOp;
113971          assert( nFarg==1 );
113972          assert( pFarg->a[0].pExpr!=0 );
113973          exprOp = pFarg->a[0].pExpr->op;
113974          if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
113975            assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
113976            assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
113977            assert( SQLITE_FUNC_BYTELEN==OPFLAG_BYTELENARG );
113978            assert( (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG)==OPFLAG_BYTELENARG );
113979            testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_LENGTHARG );
113980            testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_TYPEOFARG );
113981            testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_BYTELENARG);
113982            pFarg->a[0].pExpr->op2 = pDef->funcFlags & OPFLAG_BYTELENARG;
113983          }
113984        }
113985
113986        sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, SQLITE_ECEL_FACTOR);
113987      }else{
113988        r1 = 0;
113989      }
113990#ifndef SQLITE_OMIT_VIRTUALTABLE
113991      /* Possibly overload the function if the first argument is
113992      ** a virtual table column.
113993      **
113994      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
113995      ** second argument, not the first, as the argument to test to
113996      ** see if it is a column in a virtual table.  This is done because
113997      ** the left operand of infix functions (the operand we want to
113998      ** control overloading) ends up as the second argument to the
113999      ** function.  The expression "A glob B" is equivalent to
114000      ** "glob(B,A).  We want to use the A in "A glob B" to test
114001      ** for function overloading.  But we use the B term in "glob(B,A)".
114002      */
114003      if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
114004        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
114005      }else if( nFarg>0 ){
114006        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
114007      }
114008#endif
114009      if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
114010        if( !pColl ) pColl = db->pDfltColl;
114011        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
114012      }
114013      sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
114014                                 pDef, pExpr->op2);
114015      if( nFarg ){
114016        if( constMask==0 ){
114017          sqlite3ReleaseTempRange(pParse, r1, nFarg);
114018        }else{
114019          sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1);
114020        }
114021      }
114022      return target;
114023    }
114024#ifndef SQLITE_OMIT_SUBQUERY
114025    case TK_EXISTS:
114026    case TK_SELECT: {
114027      int nCol;
114028      testcase( op==TK_EXISTS );
114029      testcase( op==TK_SELECT );
114030      if( pParse->db->mallocFailed ){
114031        return 0;
114032      }else if( op==TK_SELECT
114033             && ALWAYS( ExprUseXSelect(pExpr) )
114034             && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1
114035      ){
114036        sqlite3SubselectError(pParse, nCol, 1);
114037      }else{
114038        return sqlite3CodeSubselect(pParse, pExpr);
114039      }
114040      break;
114041    }
114042    case TK_SELECT_COLUMN: {
114043      int n;
114044      Expr *pLeft = pExpr->pLeft;
114045      if( pLeft->iTable==0 || pParse->withinRJSubrtn > pLeft->op2 ){
114046        pLeft->iTable = sqlite3CodeSubselect(pParse, pLeft);
114047        pLeft->op2 = pParse->withinRJSubrtn;
114048      }
114049      assert( pLeft->op==TK_SELECT || pLeft->op==TK_ERROR );
114050      n = sqlite3ExprVectorSize(pLeft);
114051      if( pExpr->iTable!=n ){
114052        sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
114053                                pExpr->iTable, n);
114054      }
114055      return pLeft->iTable + pExpr->iColumn;
114056    }
114057    case TK_IN: {
114058      int destIfFalse = sqlite3VdbeMakeLabel(pParse);
114059      int destIfNull = sqlite3VdbeMakeLabel(pParse);
114060      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
114061      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
114062      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
114063      sqlite3VdbeResolveLabel(v, destIfFalse);
114064      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
114065      sqlite3VdbeResolveLabel(v, destIfNull);
114066      return target;
114067    }
114068#endif /* SQLITE_OMIT_SUBQUERY */
114069
114070
114071    /*
114072    **    x BETWEEN y AND z
114073    **
114074    ** This is equivalent to
114075    **
114076    **    x>=y AND x<=z
114077    **
114078    ** X is stored in pExpr->pLeft.
114079    ** Y is stored in pExpr->pList->a[0].pExpr.
114080    ** Z is stored in pExpr->pList->a[1].pExpr.
114081    */
114082    case TK_BETWEEN: {
114083      exprCodeBetween(pParse, pExpr, target, 0, 0);
114084      return target;
114085    }
114086    case TK_COLLATE: {
114087      if( !ExprHasProperty(pExpr, EP_Collate) ){
114088        /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called
114089        ** "SOFT-COLLATE" that is added to constraints that are pushed down
114090        ** from outer queries into sub-queries by the WHERE-clause push-down
114091        ** optimization. Clear subtypes as subtypes may not cross a subquery
114092        ** boundary.
114093        */
114094        assert( pExpr->pLeft );
114095        sqlite3ExprCode(pParse, pExpr->pLeft, target);
114096        sqlite3VdbeAddOp1(v, OP_ClrSubtype, target);
114097        return target;
114098      }else{
114099        pExpr = pExpr->pLeft;
114100        goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. */
114101      }
114102    }
114103    case TK_SPAN:
114104    case TK_UPLUS: {
114105      pExpr = pExpr->pLeft;
114106      goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
114107    }
114108
114109    case TK_TRIGGER: {
114110      /* If the opcode is TK_TRIGGER, then the expression is a reference
114111      ** to a column in the new.* or old.* pseudo-tables available to
114112      ** trigger programs. In this case Expr.iTable is set to 1 for the
114113      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
114114      ** is set to the column of the pseudo-table to read, or to -1 to
114115      ** read the rowid field.
114116      **
114117      ** The expression is implemented using an OP_Param opcode. The p1
114118      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
114119      ** to reference another column of the old.* pseudo-table, where
114120      ** i is the index of the column. For a new.rowid reference, p1 is
114121      ** set to (n+1), where n is the number of columns in each pseudo-table.
114122      ** For a reference to any other column in the new.* pseudo-table, p1
114123      ** is set to (n+2+i), where n and i are as defined previously. For
114124      ** example, if the table on which triggers are being fired is
114125      ** declared as:
114126      **
114127      **   CREATE TABLE t1(a, b);
114128      **
114129      ** Then p1 is interpreted as follows:
114130      **
114131      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
114132      **   p1==1   ->    old.a         p1==4   ->    new.a
114133      **   p1==2   ->    old.b         p1==5   ->    new.b
114134      */
114135      Table *pTab;
114136      int iCol;
114137      int p1;
114138
114139      assert( ExprUseYTab(pExpr) );
114140      pTab = pExpr->y.pTab;
114141      iCol = pExpr->iColumn;
114142      p1 = pExpr->iTable * (pTab->nCol+1) + 1
114143                     + sqlite3TableColumnToStorage(pTab, iCol);
114144
114145      assert( pExpr->iTable==0 || pExpr->iTable==1 );
114146      assert( iCol>=-1 && iCol<pTab->nCol );
114147      assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
114148      assert( p1>=0 && p1<(pTab->nCol*2+2) );
114149
114150      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
114151      VdbeComment((v, "r[%d]=%s.%s", target,
114152        (pExpr->iTable ? "new" : "old"),
114153        (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zCnName)
114154      ));
114155
114156#ifndef SQLITE_OMIT_FLOATING_POINT
114157      /* If the column has REAL affinity, it may currently be stored as an
114158      ** integer. Use OP_RealAffinity to make sure it is really real.
114159      **
114160      ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
114161      ** floating point when extracting it from the record.  */
114162      if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
114163        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
114164      }
114165#endif
114166      break;
114167    }
114168
114169    case TK_VECTOR: {
114170      sqlite3ErrorMsg(pParse, "row value misused");
114171      break;
114172    }
114173
114174    /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
114175    ** that derive from the right-hand table of a LEFT JOIN.  The
114176    ** Expr.iTable value is the table number for the right-hand table.
114177    ** The expression is only evaluated if that table is not currently
114178    ** on a LEFT JOIN NULL row.
114179    */
114180    case TK_IF_NULL_ROW: {
114181      int addrINR;
114182      u8 okConstFactor = pParse->okConstFactor;
114183      AggInfo *pAggInfo = pExpr->pAggInfo;
114184      if( pAggInfo ){
114185        assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
114186        if( !pAggInfo->directMode ){
114187          inReg = AggInfoColumnReg(pAggInfo, pExpr->iAgg);
114188          break;
114189        }
114190        if( pExpr->pAggInfo->useSortingIdx ){
114191          sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
114192                            pAggInfo->aCol[pExpr->iAgg].iSorterColumn,
114193                            target);
114194          inReg = target;
114195          break;
114196        }
114197      }
114198      addrINR = sqlite3VdbeAddOp3(v, OP_IfNullRow, pExpr->iTable, 0, target);
114199      /* The OP_IfNullRow opcode above can overwrite the result register with
114200      ** NULL.  So we have to ensure that the result register is not a value
114201      ** that is suppose to be a constant.  Two defenses are needed:
114202      **   (1)  Temporarily disable factoring of constant expressions
114203      **   (2)  Make sure the computed value really is stored in register
114204      **        "target" and not someplace else.
114205      */
114206      pParse->okConstFactor = 0;   /* note (1) above */
114207      sqlite3ExprCode(pParse, pExpr->pLeft, target);
114208      assert( target==inReg );
114209      pParse->okConstFactor = okConstFactor;
114210      sqlite3VdbeJumpHere(v, addrINR);
114211      break;
114212    }
114213
114214    /*
114215    ** Form A:
114216    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
114217    **
114218    ** Form B:
114219    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
114220    **
114221    ** Form A is can be transformed into the equivalent form B as follows:
114222    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
114223    **        WHEN x=eN THEN rN ELSE y END
114224    **
114225    ** X (if it exists) is in pExpr->pLeft.
114226    ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
114227    ** odd.  The Y is also optional.  If the number of elements in x.pList
114228    ** is even, then Y is omitted and the "otherwise" result is NULL.
114229    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
114230    **
114231    ** The result of the expression is the Ri for the first matching Ei,
114232    ** or if there is no matching Ei, the ELSE term Y, or if there is
114233    ** no ELSE term, NULL.
114234    */
114235    case TK_CASE: {
114236      int endLabel;                     /* GOTO label for end of CASE stmt */
114237      int nextCase;                     /* GOTO label for next WHEN clause */
114238      int nExpr;                        /* 2x number of WHEN terms */
114239      int i;                            /* Loop counter */
114240      ExprList *pEList;                 /* List of WHEN terms */
114241      struct ExprList_item *aListelem;  /* Array of WHEN terms */
114242      Expr opCompare;                   /* The X==Ei expression */
114243      Expr *pX;                         /* The X expression */
114244      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
114245      Expr *pDel = 0;
114246      sqlite3 *db = pParse->db;
114247
114248      assert( ExprUseXList(pExpr) && pExpr->x.pList!=0 );
114249      assert(pExpr->x.pList->nExpr > 0);
114250      pEList = pExpr->x.pList;
114251      aListelem = pEList->a;
114252      nExpr = pEList->nExpr;
114253      endLabel = sqlite3VdbeMakeLabel(pParse);
114254      if( (pX = pExpr->pLeft)!=0 ){
114255        pDel = sqlite3ExprDup(db, pX, 0);
114256        if( db->mallocFailed ){
114257          sqlite3ExprDelete(db, pDel);
114258          break;
114259        }
114260        testcase( pX->op==TK_COLUMN );
114261        exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
114262        testcase( regFree1==0 );
114263        memset(&opCompare, 0, sizeof(opCompare));
114264        opCompare.op = TK_EQ;
114265        opCompare.pLeft = pDel;
114266        pTest = &opCompare;
114267        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
114268        ** The value in regFree1 might get SCopy-ed into the file result.
114269        ** So make sure that the regFree1 register is not reused for other
114270        ** purposes and possibly overwritten.  */
114271        regFree1 = 0;
114272      }
114273      for(i=0; i<nExpr-1; i=i+2){
114274        if( pX ){
114275          assert( pTest!=0 );
114276          opCompare.pRight = aListelem[i].pExpr;
114277        }else{
114278          pTest = aListelem[i].pExpr;
114279        }
114280        nextCase = sqlite3VdbeMakeLabel(pParse);
114281        testcase( pTest->op==TK_COLUMN );
114282        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
114283        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
114284        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
114285        sqlite3VdbeGoto(v, endLabel);
114286        sqlite3VdbeResolveLabel(v, nextCase);
114287      }
114288      if( (nExpr&1)!=0 ){
114289        sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
114290      }else{
114291        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
114292      }
114293      sqlite3ExprDelete(db, pDel);
114294      setDoNotMergeFlagOnCopy(v);
114295      sqlite3VdbeResolveLabel(v, endLabel);
114296      break;
114297    }
114298#ifndef SQLITE_OMIT_TRIGGER
114299    case TK_RAISE: {
114300      assert( pExpr->affExpr==OE_Rollback
114301           || pExpr->affExpr==OE_Abort
114302           || pExpr->affExpr==OE_Fail
114303           || pExpr->affExpr==OE_Ignore
114304      );
114305      if( !pParse->pTriggerTab && !pParse->nested ){
114306        sqlite3ErrorMsg(pParse,
114307                       "RAISE() may only be used within a trigger-program");
114308        return 0;
114309      }
114310      if( pExpr->affExpr==OE_Abort ){
114311        sqlite3MayAbort(pParse);
114312      }
114313      assert( !ExprHasProperty(pExpr, EP_IntValue) );
114314      if( pExpr->affExpr==OE_Ignore ){
114315        sqlite3VdbeAddOp4(
114316            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
114317        VdbeCoverage(v);
114318      }else{
114319        sqlite3HaltConstraint(pParse,
114320             pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
114321             pExpr->affExpr, pExpr->u.zToken, 0, 0);
114322      }
114323
114324      break;
114325    }
114326#endif
114327  }
114328  sqlite3ReleaseTempReg(pParse, regFree1);
114329  sqlite3ReleaseTempReg(pParse, regFree2);
114330  return inReg;
114331}
114332
114333/*
114334** Generate code that will evaluate expression pExpr just one time
114335** per prepared statement execution.
114336**
114337** If the expression uses functions (that might throw an exception) then
114338** guard them with an OP_Once opcode to ensure that the code is only executed
114339** once. If no functions are involved, then factor the code out and put it at
114340** the end of the prepared statement in the initialization section.
114341**
114342** If regDest>0 then the result is always stored in that register and the
114343** result is not reusable.  If regDest<0 then this routine is free to
114344** store the value wherever it wants.  The register where the expression
114345** is stored is returned.  When regDest<0, two identical expressions might
114346** code to the same register, if they do not contain function calls and hence
114347** are factored out into the initialization section at the end of the
114348** prepared statement.
114349*/
114350SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(
114351  Parse *pParse,    /* Parsing context */
114352  Expr *pExpr,      /* The expression to code when the VDBE initializes */
114353  int regDest       /* Store the value in this register */
114354){
114355  ExprList *p;
114356  assert( ConstFactorOk(pParse) );
114357  assert( regDest!=0 );
114358  p = pParse->pConstExpr;
114359  if( regDest<0 && p ){
114360    struct ExprList_item *pItem;
114361    int i;
114362    for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
114363      if( pItem->fg.reusable
114364       && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0
114365      ){
114366        return pItem->u.iConstExprReg;
114367      }
114368    }
114369  }
114370  pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
114371  if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){
114372    Vdbe *v = pParse->pVdbe;
114373    int addr;
114374    assert( v );
114375    addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
114376    pParse->okConstFactor = 0;
114377    if( !pParse->db->mallocFailed ){
114378      if( regDest<0 ) regDest = ++pParse->nMem;
114379      sqlite3ExprCode(pParse, pExpr, regDest);
114380    }
114381    pParse->okConstFactor = 1;
114382    sqlite3ExprDelete(pParse->db, pExpr);
114383    sqlite3VdbeJumpHere(v, addr);
114384  }else{
114385    p = sqlite3ExprListAppend(pParse, p, pExpr);
114386    if( p ){
114387       struct ExprList_item *pItem = &p->a[p->nExpr-1];
114388       pItem->fg.reusable = regDest<0;
114389       if( regDest<0 ) regDest = ++pParse->nMem;
114390       pItem->u.iConstExprReg = regDest;
114391    }
114392    pParse->pConstExpr = p;
114393  }
114394  return regDest;
114395}
114396
114397/*
114398** Generate code to evaluate an expression and store the results
114399** into a register.  Return the register number where the results
114400** are stored.
114401**
114402** If the register is a temporary register that can be deallocated,
114403** then write its number into *pReg.  If the result register is not
114404** a temporary, then set *pReg to zero.
114405**
114406** If pExpr is a constant, then this routine might generate this
114407** code to fill the register in the initialization section of the
114408** VDBE program, in order to factor it out of the evaluation loop.
114409*/
114410SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
114411  int r2;
114412  pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
114413  if( ConstFactorOk(pParse)
114414   && ALWAYS(pExpr!=0)
114415   && pExpr->op!=TK_REGISTER
114416   && sqlite3ExprIsConstantNotJoin(pParse, pExpr)
114417  ){
114418    *pReg  = 0;
114419    r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
114420  }else{
114421    int r1 = sqlite3GetTempReg(pParse);
114422    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
114423    if( r2==r1 ){
114424      *pReg = r1;
114425    }else{
114426      sqlite3ReleaseTempReg(pParse, r1);
114427      *pReg = 0;
114428    }
114429  }
114430  return r2;
114431}
114432
114433/*
114434** Generate code that will evaluate expression pExpr and store the
114435** results in register target.  The results are guaranteed to appear
114436** in register target.
114437*/
114438SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
114439  int inReg;
114440
114441  assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );
114442  assert( target>0 && target<=pParse->nMem );
114443  assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
114444  if( pParse->pVdbe==0 ) return;
114445  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
114446  if( inReg!=target ){
114447    u8 op;
114448    Expr *pX = sqlite3ExprSkipCollateAndLikely(pExpr);
114449    testcase( pX!=pExpr );
114450    if( ALWAYS(pX)
114451     && (ExprHasProperty(pX,EP_Subquery) || pX->op==TK_REGISTER)
114452    ){
114453      op = OP_Copy;
114454    }else{
114455      op = OP_SCopy;
114456    }
114457    sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
114458  }
114459}
114460
114461/*
114462** Make a transient copy of expression pExpr and then code it using
114463** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
114464** except that the input expression is guaranteed to be unchanged.
114465*/
114466SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
114467  sqlite3 *db = pParse->db;
114468  pExpr = sqlite3ExprDup(db, pExpr, 0);
114469  if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
114470  sqlite3ExprDelete(db, pExpr);
114471}
114472
114473/*
114474** Generate code that will evaluate expression pExpr and store the
114475** results in register target.  The results are guaranteed to appear
114476** in register target.  If the expression is constant, then this routine
114477** might choose to code the expression at initialization time.
114478*/
114479SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
114480  if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pParse,pExpr) ){
114481    sqlite3ExprCodeRunJustOnce(pParse, pExpr, target);
114482  }else{
114483    sqlite3ExprCodeCopy(pParse, pExpr, target);
114484  }
114485}
114486
114487/*
114488** Generate code that pushes the value of every element of the given
114489** expression list into a sequence of registers beginning at target.
114490**
114491** Return the number of elements evaluated.  The number returned will
114492** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
114493** is defined.
114494**
114495** The SQLITE_ECEL_DUP flag prevents the arguments from being
114496** filled using OP_SCopy.  OP_Copy must be used instead.
114497**
114498** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
114499** factored out into initialization code.
114500**
114501** The SQLITE_ECEL_REF flag means that expressions in the list with
114502** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
114503** in registers at srcReg, and so the value can be copied from there.
114504** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
114505** are simply omitted rather than being copied from srcReg.
114506*/
114507SQLITE_PRIVATE int sqlite3ExprCodeExprList(
114508  Parse *pParse,     /* Parsing context */
114509  ExprList *pList,   /* The expression list to be coded */
114510  int target,        /* Where to write results */
114511  int srcReg,        /* Source registers if SQLITE_ECEL_REF */
114512  u8 flags           /* SQLITE_ECEL_* flags */
114513){
114514  struct ExprList_item *pItem;
114515  int i, j, n;
114516  u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
114517  Vdbe *v = pParse->pVdbe;
114518  assert( pList!=0 );
114519  assert( target>0 );
114520  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
114521  n = pList->nExpr;
114522  if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
114523  for(pItem=pList->a, i=0; i<n; i++, pItem++){
114524    Expr *pExpr = pItem->pExpr;
114525#ifdef SQLITE_ENABLE_SORTER_REFERENCES
114526    if( pItem->fg.bSorterRef ){
114527      i--;
114528      n--;
114529    }else
114530#endif
114531    if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
114532      if( flags & SQLITE_ECEL_OMITREF ){
114533        i--;
114534        n--;
114535      }else{
114536        sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
114537      }
114538    }else if( (flags & SQLITE_ECEL_FACTOR)!=0
114539           && sqlite3ExprIsConstantNotJoin(pParse,pExpr)
114540    ){
114541      sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i);
114542    }else{
114543      int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
114544      if( inReg!=target+i ){
114545        VdbeOp *pOp;
114546        if( copyOp==OP_Copy
114547         && (pOp=sqlite3VdbeGetLastOp(v))->opcode==OP_Copy
114548         && pOp->p1+pOp->p3+1==inReg
114549         && pOp->p2+pOp->p3+1==target+i
114550         && pOp->p5==0  /* The do-not-merge flag must be clear */
114551        ){
114552          pOp->p3++;
114553        }else{
114554          sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
114555        }
114556      }
114557    }
114558  }
114559  return n;
114560}
114561
114562/*
114563** Generate code for a BETWEEN operator.
114564**
114565**    x BETWEEN y AND z
114566**
114567** The above is equivalent to
114568**
114569**    x>=y AND x<=z
114570**
114571** Code it as such, taking care to do the common subexpression
114572** elimination of x.
114573**
114574** The xJumpIf parameter determines details:
114575**
114576**    NULL:                   Store the boolean result in reg[dest]
114577**    sqlite3ExprIfTrue:      Jump to dest if true
114578**    sqlite3ExprIfFalse:     Jump to dest if false
114579**
114580** The jumpIfNull parameter is ignored if xJumpIf is NULL.
114581*/
114582static void exprCodeBetween(
114583  Parse *pParse,    /* Parsing and code generating context */
114584  Expr *pExpr,      /* The BETWEEN expression */
114585  int dest,         /* Jump destination or storage location */
114586  void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
114587  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
114588){
114589  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
114590  Expr compLeft;    /* The  x>=y  term */
114591  Expr compRight;   /* The  x<=z  term */
114592  int regFree1 = 0; /* Temporary use register */
114593  Expr *pDel = 0;
114594  sqlite3 *db = pParse->db;
114595
114596  memset(&compLeft, 0, sizeof(Expr));
114597  memset(&compRight, 0, sizeof(Expr));
114598  memset(&exprAnd, 0, sizeof(Expr));
114599
114600  assert( ExprUseXList(pExpr) );
114601  pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
114602  if( db->mallocFailed==0 ){
114603    exprAnd.op = TK_AND;
114604    exprAnd.pLeft = &compLeft;
114605    exprAnd.pRight = &compRight;
114606    compLeft.op = TK_GE;
114607    compLeft.pLeft = pDel;
114608    compLeft.pRight = pExpr->x.pList->a[0].pExpr;
114609    compRight.op = TK_LE;
114610    compRight.pLeft = pDel;
114611    compRight.pRight = pExpr->x.pList->a[1].pExpr;
114612    exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
114613    if( xJump ){
114614      xJump(pParse, &exprAnd, dest, jumpIfNull);
114615    }else{
114616      /* Mark the expression is being from the ON or USING clause of a join
114617      ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
114618      ** it into the Parse.pConstExpr list.  We should use a new bit for this,
114619      ** for clarity, but we are out of bits in the Expr.flags field so we
114620      ** have to reuse the EP_OuterON bit.  Bummer. */
114621      pDel->flags |= EP_OuterON;
114622      sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
114623    }
114624    sqlite3ReleaseTempReg(pParse, regFree1);
114625  }
114626  sqlite3ExprDelete(db, pDel);
114627
114628  /* Ensure adequate test coverage */
114629  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1==0 );
114630  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1!=0 );
114631  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1==0 );
114632  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1!=0 );
114633  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
114634  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
114635  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
114636  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
114637  testcase( xJump==0 );
114638}
114639
114640/*
114641** Generate code for a boolean expression such that a jump is made
114642** to the label "dest" if the expression is true but execution
114643** continues straight thru if the expression is false.
114644**
114645** If the expression evaluates to NULL (neither true nor false), then
114646** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
114647**
114648** This code depends on the fact that certain token values (ex: TK_EQ)
114649** are the same as opcode values (ex: OP_Eq) that implement the corresponding
114650** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
114651** the make process cause these values to align.  Assert()s in the code
114652** below verify that the numbers are aligned correctly.
114653*/
114654SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
114655  Vdbe *v = pParse->pVdbe;
114656  int op = 0;
114657  int regFree1 = 0;
114658  int regFree2 = 0;
114659  int r1, r2;
114660
114661  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
114662  if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
114663  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
114664  assert( !ExprHasVVAProperty(pExpr, EP_Immutable) );
114665  op = pExpr->op;
114666  switch( op ){
114667    case TK_AND:
114668    case TK_OR: {
114669      Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
114670      if( pAlt!=pExpr ){
114671        sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
114672      }else if( op==TK_AND ){
114673        int d2 = sqlite3VdbeMakeLabel(pParse);
114674        testcase( jumpIfNull==0 );
114675        sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
114676                           jumpIfNull^SQLITE_JUMPIFNULL);
114677        sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
114678        sqlite3VdbeResolveLabel(v, d2);
114679      }else{
114680        testcase( jumpIfNull==0 );
114681        sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
114682        sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
114683      }
114684      break;
114685    }
114686    case TK_NOT: {
114687      testcase( jumpIfNull==0 );
114688      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
114689      break;
114690    }
114691    case TK_TRUTH: {
114692      int isNot;      /* IS NOT TRUE or IS NOT FALSE */
114693      int isTrue;     /* IS TRUE or IS NOT TRUE */
114694      testcase( jumpIfNull==0 );
114695      isNot = pExpr->op2==TK_ISNOT;
114696      isTrue = sqlite3ExprTruthValue(pExpr->pRight);
114697      testcase( isTrue && isNot );
114698      testcase( !isTrue && isNot );
114699      if( isTrue ^ isNot ){
114700        sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
114701                          isNot ? SQLITE_JUMPIFNULL : 0);
114702      }else{
114703        sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
114704                           isNot ? SQLITE_JUMPIFNULL : 0);
114705      }
114706      break;
114707    }
114708    case TK_IS:
114709    case TK_ISNOT:
114710      testcase( op==TK_IS );
114711      testcase( op==TK_ISNOT );
114712      op = (op==TK_IS) ? TK_EQ : TK_NE;
114713      jumpIfNull = SQLITE_NULLEQ;
114714      /* no break */ deliberate_fall_through
114715    case TK_LT:
114716    case TK_LE:
114717    case TK_GT:
114718    case TK_GE:
114719    case TK_NE:
114720    case TK_EQ: {
114721      if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
114722      testcase( jumpIfNull==0 );
114723      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
114724      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
114725      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
114726                  r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
114727      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
114728      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
114729      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
114730      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
114731      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
114732      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
114733      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
114734      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
114735      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
114736      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
114737      testcase( regFree1==0 );
114738      testcase( regFree2==0 );
114739      break;
114740    }
114741    case TK_ISNULL:
114742    case TK_NOTNULL: {
114743      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
114744      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
114745      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
114746      sqlite3VdbeTypeofColumn(v, r1);
114747      sqlite3VdbeAddOp2(v, op, r1, dest);
114748      VdbeCoverageIf(v, op==TK_ISNULL);
114749      VdbeCoverageIf(v, op==TK_NOTNULL);
114750      testcase( regFree1==0 );
114751      break;
114752    }
114753    case TK_BETWEEN: {
114754      testcase( jumpIfNull==0 );
114755      exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
114756      break;
114757    }
114758#ifndef SQLITE_OMIT_SUBQUERY
114759    case TK_IN: {
114760      int destIfFalse = sqlite3VdbeMakeLabel(pParse);
114761      int destIfNull = jumpIfNull ? dest : destIfFalse;
114762      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
114763      sqlite3VdbeGoto(v, dest);
114764      sqlite3VdbeResolveLabel(v, destIfFalse);
114765      break;
114766    }
114767#endif
114768    default: {
114769    default_expr:
114770      if( ExprAlwaysTrue(pExpr) ){
114771        sqlite3VdbeGoto(v, dest);
114772      }else if( ExprAlwaysFalse(pExpr) ){
114773        /* No-op */
114774      }else{
114775        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
114776        sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
114777        VdbeCoverage(v);
114778        testcase( regFree1==0 );
114779        testcase( jumpIfNull==0 );
114780      }
114781      break;
114782    }
114783  }
114784  sqlite3ReleaseTempReg(pParse, regFree1);
114785  sqlite3ReleaseTempReg(pParse, regFree2);
114786}
114787
114788/*
114789** Generate code for a boolean expression such that a jump is made
114790** to the label "dest" if the expression is false but execution
114791** continues straight thru if the expression is true.
114792**
114793** If the expression evaluates to NULL (neither true nor false) then
114794** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
114795** is 0.
114796*/
114797SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
114798  Vdbe *v = pParse->pVdbe;
114799  int op = 0;
114800  int regFree1 = 0;
114801  int regFree2 = 0;
114802  int r1, r2;
114803
114804  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
114805  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
114806  if( pExpr==0 )    return;
114807  assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
114808
114809  /* The value of pExpr->op and op are related as follows:
114810  **
114811  **       pExpr->op            op
114812  **       ---------          ----------
114813  **       TK_ISNULL          OP_NotNull
114814  **       TK_NOTNULL         OP_IsNull
114815  **       TK_NE              OP_Eq
114816  **       TK_EQ              OP_Ne
114817  **       TK_GT              OP_Le
114818  **       TK_LE              OP_Gt
114819  **       TK_GE              OP_Lt
114820  **       TK_LT              OP_Ge
114821  **
114822  ** For other values of pExpr->op, op is undefined and unused.
114823  ** The value of TK_ and OP_ constants are arranged such that we
114824  ** can compute the mapping above using the following expression.
114825  ** Assert()s verify that the computation is correct.
114826  */
114827  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
114828
114829  /* Verify correct alignment of TK_ and OP_ constants
114830  */
114831  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
114832  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
114833  assert( pExpr->op!=TK_NE || op==OP_Eq );
114834  assert( pExpr->op!=TK_EQ || op==OP_Ne );
114835  assert( pExpr->op!=TK_LT || op==OP_Ge );
114836  assert( pExpr->op!=TK_LE || op==OP_Gt );
114837  assert( pExpr->op!=TK_GT || op==OP_Le );
114838  assert( pExpr->op!=TK_GE || op==OP_Lt );
114839
114840  switch( pExpr->op ){
114841    case TK_AND:
114842    case TK_OR: {
114843      Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
114844      if( pAlt!=pExpr ){
114845        sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
114846      }else if( pExpr->op==TK_AND ){
114847        testcase( jumpIfNull==0 );
114848        sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
114849        sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
114850      }else{
114851        int d2 = sqlite3VdbeMakeLabel(pParse);
114852        testcase( jumpIfNull==0 );
114853        sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
114854                          jumpIfNull^SQLITE_JUMPIFNULL);
114855        sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
114856        sqlite3VdbeResolveLabel(v, d2);
114857      }
114858      break;
114859    }
114860    case TK_NOT: {
114861      testcase( jumpIfNull==0 );
114862      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
114863      break;
114864    }
114865    case TK_TRUTH: {
114866      int isNot;   /* IS NOT TRUE or IS NOT FALSE */
114867      int isTrue;  /* IS TRUE or IS NOT TRUE */
114868      testcase( jumpIfNull==0 );
114869      isNot = pExpr->op2==TK_ISNOT;
114870      isTrue = sqlite3ExprTruthValue(pExpr->pRight);
114871      testcase( isTrue && isNot );
114872      testcase( !isTrue && isNot );
114873      if( isTrue ^ isNot ){
114874        /* IS TRUE and IS NOT FALSE */
114875        sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
114876                           isNot ? 0 : SQLITE_JUMPIFNULL);
114877
114878      }else{
114879        /* IS FALSE and IS NOT TRUE */
114880        sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
114881                          isNot ? 0 : SQLITE_JUMPIFNULL);
114882      }
114883      break;
114884    }
114885    case TK_IS:
114886    case TK_ISNOT:
114887      testcase( pExpr->op==TK_IS );
114888      testcase( pExpr->op==TK_ISNOT );
114889      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
114890      jumpIfNull = SQLITE_NULLEQ;
114891      /* no break */ deliberate_fall_through
114892    case TK_LT:
114893    case TK_LE:
114894    case TK_GT:
114895    case TK_GE:
114896    case TK_NE:
114897    case TK_EQ: {
114898      if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
114899      testcase( jumpIfNull==0 );
114900      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
114901      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
114902      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
114903                  r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
114904      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
114905      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
114906      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
114907      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
114908      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
114909      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
114910      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
114911      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
114912      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
114913      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
114914      testcase( regFree1==0 );
114915      testcase( regFree2==0 );
114916      break;
114917    }
114918    case TK_ISNULL:
114919    case TK_NOTNULL: {
114920      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
114921      sqlite3VdbeTypeofColumn(v, r1);
114922      sqlite3VdbeAddOp2(v, op, r1, dest);
114923      testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
114924      testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
114925      testcase( regFree1==0 );
114926      break;
114927    }
114928    case TK_BETWEEN: {
114929      testcase( jumpIfNull==0 );
114930      exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
114931      break;
114932    }
114933#ifndef SQLITE_OMIT_SUBQUERY
114934    case TK_IN: {
114935      if( jumpIfNull ){
114936        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
114937      }else{
114938        int destIfNull = sqlite3VdbeMakeLabel(pParse);
114939        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
114940        sqlite3VdbeResolveLabel(v, destIfNull);
114941      }
114942      break;
114943    }
114944#endif
114945    default: {
114946    default_expr:
114947      if( ExprAlwaysFalse(pExpr) ){
114948        sqlite3VdbeGoto(v, dest);
114949      }else if( ExprAlwaysTrue(pExpr) ){
114950        /* no-op */
114951      }else{
114952        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
114953        sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
114954        VdbeCoverage(v);
114955        testcase( regFree1==0 );
114956        testcase( jumpIfNull==0 );
114957      }
114958      break;
114959    }
114960  }
114961  sqlite3ReleaseTempReg(pParse, regFree1);
114962  sqlite3ReleaseTempReg(pParse, regFree2);
114963}
114964
114965/*
114966** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
114967** code generation, and that copy is deleted after code generation. This
114968** ensures that the original pExpr is unchanged.
114969*/
114970SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
114971  sqlite3 *db = pParse->db;
114972  Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
114973  if( db->mallocFailed==0 ){
114974    sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
114975  }
114976  sqlite3ExprDelete(db, pCopy);
114977}
114978
114979/*
114980** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
114981** type of expression.
114982**
114983** If pExpr is a simple SQL value - an integer, real, string, blob
114984** or NULL value - then the VDBE currently being prepared is configured
114985** to re-prepare each time a new value is bound to variable pVar.
114986**
114987** Additionally, if pExpr is a simple SQL value and the value is the
114988** same as that currently bound to variable pVar, non-zero is returned.
114989** Otherwise, if the values are not the same or if pExpr is not a simple
114990** SQL value, zero is returned.
114991*/
114992static int exprCompareVariable(
114993  const Parse *pParse,
114994  const Expr *pVar,
114995  const Expr *pExpr
114996){
114997  int res = 0;
114998  int iVar;
114999  sqlite3_value *pL, *pR = 0;
115000
115001  sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
115002  if( pR ){
115003    iVar = pVar->iColumn;
115004    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
115005    pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
115006    if( pL ){
115007      if( sqlite3_value_type(pL)==SQLITE_TEXT ){
115008        sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
115009      }
115010      res =  0==sqlite3MemCompare(pL, pR, 0);
115011    }
115012    sqlite3ValueFree(pR);
115013    sqlite3ValueFree(pL);
115014  }
115015
115016  return res;
115017}
115018
115019/*
115020** Do a deep comparison of two expression trees.  Return 0 if the two
115021** expressions are completely identical.  Return 1 if they differ only
115022** by a COLLATE operator at the top level.  Return 2 if there are differences
115023** other than the top-level COLLATE operator.
115024**
115025** If any subelement of pB has Expr.iTable==(-1) then it is allowed
115026** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
115027**
115028** The pA side might be using TK_REGISTER.  If that is the case and pB is
115029** not using TK_REGISTER but is otherwise equivalent, then still return 0.
115030**
115031** Sometimes this routine will return 2 even if the two expressions
115032** really are equivalent.  If we cannot prove that the expressions are
115033** identical, we return 2 just to be safe.  So if this routine
115034** returns 2, then you do not really know for certain if the two
115035** expressions are the same.  But if you get a 0 or 1 return, then you
115036** can be sure the expressions are the same.  In the places where
115037** this routine is used, it does not hurt to get an extra 2 - that
115038** just might result in some slightly slower code.  But returning
115039** an incorrect 0 or 1 could lead to a malfunction.
115040**
115041** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
115042** pParse->pReprepare can be matched against literals in pB.  The
115043** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
115044** If pParse is NULL (the normal case) then any TK_VARIABLE term in
115045** Argument pParse should normally be NULL. If it is not NULL and pA or
115046** pB causes a return value of 2.
115047*/
115048SQLITE_PRIVATE int sqlite3ExprCompare(
115049  const Parse *pParse,
115050  const Expr *pA,
115051  const Expr *pB,
115052  int iTab
115053){
115054  u32 combinedFlags;
115055  if( pA==0 || pB==0 ){
115056    return pB==pA ? 0 : 2;
115057  }
115058  if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
115059    return 0;
115060  }
115061  combinedFlags = pA->flags | pB->flags;
115062  if( combinedFlags & EP_IntValue ){
115063    if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
115064      return 0;
115065    }
115066    return 2;
115067  }
115068  if( pA->op!=pB->op || pA->op==TK_RAISE ){
115069    if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
115070      return 1;
115071    }
115072    if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
115073      return 1;
115074    }
115075    if( pA->op==TK_AGG_COLUMN && pB->op==TK_COLUMN
115076     && pB->iTable<0 && pA->iTable==iTab
115077    ){
115078      /* fall through */
115079    }else{
115080      return 2;
115081    }
115082  }
115083  assert( !ExprHasProperty(pA, EP_IntValue) );
115084  assert( !ExprHasProperty(pB, EP_IntValue) );
115085  if( pA->u.zToken ){
115086    if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
115087      if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
115088#ifndef SQLITE_OMIT_WINDOWFUNC
115089      assert( pA->op==pB->op );
115090      if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
115091        return 2;
115092      }
115093      if( ExprHasProperty(pA,EP_WinFunc) ){
115094        if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
115095          return 2;
115096        }
115097      }
115098#endif
115099    }else if( pA->op==TK_NULL ){
115100      return 0;
115101    }else if( pA->op==TK_COLLATE ){
115102      if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
115103    }else
115104    if( pB->u.zToken!=0
115105     && pA->op!=TK_COLUMN
115106     && pA->op!=TK_AGG_COLUMN
115107     && strcmp(pA->u.zToken,pB->u.zToken)!=0
115108    ){
115109      return 2;
115110    }
115111  }
115112  if( (pA->flags & (EP_Distinct|EP_Commuted))
115113     != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
115114  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
115115    if( combinedFlags & EP_xIsSelect ) return 2;
115116    if( (combinedFlags & EP_FixedCol)==0
115117     && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
115118    if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
115119    if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
115120    if( pA->op!=TK_STRING
115121     && pA->op!=TK_TRUEFALSE
115122     && ALWAYS((combinedFlags & EP_Reduced)==0)
115123    ){
115124      if( pA->iColumn!=pB->iColumn ) return 2;
115125      if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;
115126      if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
115127        return 2;
115128      }
115129    }
115130  }
115131  return 0;
115132}
115133
115134/*
115135** Compare two ExprList objects.  Return 0 if they are identical, 1
115136** if they are certainly different, or 2 if it is not possible to
115137** determine if they are identical or not.
115138**
115139** If any subelement of pB has Expr.iTable==(-1) then it is allowed
115140** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
115141**
115142** This routine might return non-zero for equivalent ExprLists.  The
115143** only consequence will be disabled optimizations.  But this routine
115144** must never return 0 if the two ExprList objects are different, or
115145** a malfunction will result.
115146**
115147** Two NULL pointers are considered to be the same.  But a NULL pointer
115148** always differs from a non-NULL pointer.
115149*/
115150SQLITE_PRIVATE int sqlite3ExprListCompare(const ExprList *pA, const ExprList *pB, int iTab){
115151  int i;
115152  if( pA==0 && pB==0 ) return 0;
115153  if( pA==0 || pB==0 ) return 1;
115154  if( pA->nExpr!=pB->nExpr ) return 1;
115155  for(i=0; i<pA->nExpr; i++){
115156    int res;
115157    Expr *pExprA = pA->a[i].pExpr;
115158    Expr *pExprB = pB->a[i].pExpr;
115159    if( pA->a[i].fg.sortFlags!=pB->a[i].fg.sortFlags ) return 1;
115160    if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res;
115161  }
115162  return 0;
115163}
115164
115165/*
115166** Like sqlite3ExprCompare() except COLLATE operators at the top-level
115167** are ignored.
115168*/
115169SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA,Expr *pB, int iTab){
115170  return sqlite3ExprCompare(0,
115171             sqlite3ExprSkipCollate(pA),
115172             sqlite3ExprSkipCollate(pB),
115173             iTab);
115174}
115175
115176/*
115177** Return non-zero if Expr p can only be true if pNN is not NULL.
115178**
115179** Or if seenNot is true, return non-zero if Expr p can only be
115180** non-NULL if pNN is not NULL
115181*/
115182static int exprImpliesNotNull(
115183  const Parse *pParse,/* Parsing context */
115184  const Expr *p,      /* The expression to be checked */
115185  const Expr *pNN,    /* The expression that is NOT NULL */
115186  int iTab,           /* Table being evaluated */
115187  int seenNot         /* Return true only if p can be any non-NULL value */
115188){
115189  assert( p );
115190  assert( pNN );
115191  if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
115192    return pNN->op!=TK_NULL;
115193  }
115194  switch( p->op ){
115195    case TK_IN: {
115196      if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
115197      assert( ExprUseXSelect(p) || (p->x.pList!=0 && p->x.pList->nExpr>0) );
115198      return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
115199    }
115200    case TK_BETWEEN: {
115201      ExprList *pList;
115202      assert( ExprUseXList(p) );
115203      pList = p->x.pList;
115204      assert( pList!=0 );
115205      assert( pList->nExpr==2 );
115206      if( seenNot ) return 0;
115207      if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
115208       || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
115209      ){
115210        return 1;
115211      }
115212      return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
115213    }
115214    case TK_EQ:
115215    case TK_NE:
115216    case TK_LT:
115217    case TK_LE:
115218    case TK_GT:
115219    case TK_GE:
115220    case TK_PLUS:
115221    case TK_MINUS:
115222    case TK_BITOR:
115223    case TK_LSHIFT:
115224    case TK_RSHIFT:
115225    case TK_CONCAT:
115226      seenNot = 1;
115227      /* no break */ deliberate_fall_through
115228    case TK_STAR:
115229    case TK_REM:
115230    case TK_BITAND:
115231    case TK_SLASH: {
115232      if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
115233      /* no break */ deliberate_fall_through
115234    }
115235    case TK_SPAN:
115236    case TK_COLLATE:
115237    case TK_UPLUS:
115238    case TK_UMINUS: {
115239      return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
115240    }
115241    case TK_TRUTH: {
115242      if( seenNot ) return 0;
115243      if( p->op2!=TK_IS ) return 0;
115244      return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
115245    }
115246    case TK_BITNOT:
115247    case TK_NOT: {
115248      return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
115249    }
115250  }
115251  return 0;
115252}
115253
115254/*
115255** Return true if we can prove the pE2 will always be true if pE1 is
115256** true.  Return false if we cannot complete the proof or if pE2 might
115257** be false.  Examples:
115258**
115259**     pE1: x==5       pE2: x==5             Result: true
115260**     pE1: x>0        pE2: x==5             Result: false
115261**     pE1: x=21       pE2: x=21 OR y=43     Result: true
115262**     pE1: x!=123     pE2: x IS NOT NULL    Result: true
115263**     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
115264**     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
115265**     pE1: x IS ?2    pE2: x IS NOT NULL    Result: false
115266**
115267** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
115268** Expr.iTable<0 then assume a table number given by iTab.
115269**
115270** If pParse is not NULL, then the values of bound variables in pE1 are
115271** compared against literal values in pE2 and pParse->pVdbe->expmask is
115272** modified to record which bound variables are referenced.  If pParse
115273** is NULL, then false will be returned if pE1 contains any bound variables.
115274**
115275** When in doubt, return false.  Returning true might give a performance
115276** improvement.  Returning false might cause a performance reduction, but
115277** it will always give the correct answer and is hence always safe.
115278*/
115279SQLITE_PRIVATE int sqlite3ExprImpliesExpr(
115280  const Parse *pParse,
115281  const Expr *pE1,
115282  const Expr *pE2,
115283  int iTab
115284){
115285  if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
115286    return 1;
115287  }
115288  if( pE2->op==TK_OR
115289   && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
115290             || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
115291  ){
115292    return 1;
115293  }
115294  if( pE2->op==TK_NOTNULL
115295   && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
115296  ){
115297    return 1;
115298  }
115299  return 0;
115300}
115301
115302/* This is a helper function to impliesNotNullRow().  In this routine,
115303** set pWalker->eCode to one only if *both* of the input expressions
115304** separately have the implies-not-null-row property.
115305*/
115306static void bothImplyNotNullRow(Walker *pWalker, Expr *pE1, Expr *pE2){
115307  if( pWalker->eCode==0 ){
115308    sqlite3WalkExpr(pWalker, pE1);
115309    if( pWalker->eCode ){
115310      pWalker->eCode = 0;
115311      sqlite3WalkExpr(pWalker, pE2);
115312    }
115313  }
115314}
115315
115316/*
115317** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
115318** If the expression node requires that the table at pWalker->iCur
115319** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
115320**
115321** pWalker->mWFlags is non-zero if this inquiry is being undertaking on
115322** behalf of a RIGHT JOIN (or FULL JOIN).  That makes a difference when
115323** evaluating terms in the ON clause of an inner join.
115324**
115325** This routine controls an optimization.  False positives (setting
115326** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
115327** (never setting pWalker->eCode) is a harmless missed optimization.
115328*/
115329static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
115330  testcase( pExpr->op==TK_AGG_COLUMN );
115331  testcase( pExpr->op==TK_AGG_FUNCTION );
115332  if( ExprHasProperty(pExpr, EP_OuterON) ) return WRC_Prune;
115333  if( ExprHasProperty(pExpr, EP_InnerON) && pWalker->mWFlags ){
115334    /* If iCur is used in an inner-join ON clause to the left of a
115335    ** RIGHT JOIN, that does *not* mean that the table must be non-null.
115336    ** But it is difficult to check for that condition precisely.
115337    ** To keep things simple, any use of iCur from any inner-join is
115338    ** ignored while attempting to simplify a RIGHT JOIN. */
115339    return WRC_Prune;
115340  }
115341  switch( pExpr->op ){
115342    case TK_ISNOT:
115343    case TK_ISNULL:
115344    case TK_NOTNULL:
115345    case TK_IS:
115346    case TK_VECTOR:
115347    case TK_FUNCTION:
115348    case TK_TRUTH:
115349    case TK_CASE:
115350      testcase( pExpr->op==TK_ISNOT );
115351      testcase( pExpr->op==TK_ISNULL );
115352      testcase( pExpr->op==TK_NOTNULL );
115353      testcase( pExpr->op==TK_IS );
115354      testcase( pExpr->op==TK_VECTOR );
115355      testcase( pExpr->op==TK_FUNCTION );
115356      testcase( pExpr->op==TK_TRUTH );
115357      testcase( pExpr->op==TK_CASE );
115358      return WRC_Prune;
115359
115360    case TK_COLUMN:
115361      if( pWalker->u.iCur==pExpr->iTable ){
115362        pWalker->eCode = 1;
115363        return WRC_Abort;
115364      }
115365      return WRC_Prune;
115366
115367    case TK_OR:
115368    case TK_AND:
115369      /* Both sides of an AND or OR must separately imply non-null-row.
115370      ** Consider these cases:
115371      **    1.  NOT (x AND y)
115372      **    2.  x OR y
115373      ** If only one of x or y is non-null-row, then the overall expression
115374      ** can be true if the other arm is false (case 1) or true (case 2).
115375      */
115376      testcase( pExpr->op==TK_OR );
115377      testcase( pExpr->op==TK_AND );
115378      bothImplyNotNullRow(pWalker, pExpr->pLeft, pExpr->pRight);
115379      return WRC_Prune;
115380
115381    case TK_IN:
115382      /* Beware of "x NOT IN ()" and "x NOT IN (SELECT 1 WHERE false)",
115383      ** both of which can be true.  But apart from these cases, if
115384      ** the left-hand side of the IN is NULL then the IN itself will be
115385      ** NULL. */
115386      if( ExprUseXList(pExpr) && ALWAYS(pExpr->x.pList->nExpr>0) ){
115387        sqlite3WalkExpr(pWalker, pExpr->pLeft);
115388      }
115389      return WRC_Prune;
115390
115391    case TK_BETWEEN:
115392      /* In "x NOT BETWEEN y AND z" either x must be non-null-row or else
115393      ** both y and z must be non-null row */
115394      assert( ExprUseXList(pExpr) );
115395      assert( pExpr->x.pList->nExpr==2 );
115396      sqlite3WalkExpr(pWalker, pExpr->pLeft);
115397      bothImplyNotNullRow(pWalker, pExpr->x.pList->a[0].pExpr,
115398                                   pExpr->x.pList->a[1].pExpr);
115399      return WRC_Prune;
115400
115401    /* Virtual tables are allowed to use constraints like x=NULL.  So
115402    ** a term of the form x=y does not prove that y is not null if x
115403    ** is the column of a virtual table */
115404    case TK_EQ:
115405    case TK_NE:
115406    case TK_LT:
115407    case TK_LE:
115408    case TK_GT:
115409    case TK_GE: {
115410      Expr *pLeft = pExpr->pLeft;
115411      Expr *pRight = pExpr->pRight;
115412      testcase( pExpr->op==TK_EQ );
115413      testcase( pExpr->op==TK_NE );
115414      testcase( pExpr->op==TK_LT );
115415      testcase( pExpr->op==TK_LE );
115416      testcase( pExpr->op==TK_GT );
115417      testcase( pExpr->op==TK_GE );
115418      /* The y.pTab=0 assignment in wherecode.c always happens after the
115419      ** impliesNotNullRow() test */
115420      assert( pLeft->op!=TK_COLUMN || ExprUseYTab(pLeft) );
115421      assert( pRight->op!=TK_COLUMN || ExprUseYTab(pRight) );
115422      if( (pLeft->op==TK_COLUMN
115423           && ALWAYS(pLeft->y.pTab!=0)
115424           && IsVirtual(pLeft->y.pTab))
115425       || (pRight->op==TK_COLUMN
115426           && ALWAYS(pRight->y.pTab!=0)
115427           && IsVirtual(pRight->y.pTab))
115428      ){
115429        return WRC_Prune;
115430      }
115431      /* no break */ deliberate_fall_through
115432    }
115433    default:
115434      return WRC_Continue;
115435  }
115436}
115437
115438/*
115439** Return true (non-zero) if expression p can only be true if at least
115440** one column of table iTab is non-null.  In other words, return true
115441** if expression p will always be NULL or false if every column of iTab
115442** is NULL.
115443**
115444** False negatives are acceptable.  In other words, it is ok to return
115445** zero even if expression p will never be true of every column of iTab
115446** is NULL.  A false negative is merely a missed optimization opportunity.
115447**
115448** False positives are not allowed, however.  A false positive may result
115449** in an incorrect answer.
115450**
115451** Terms of p that are marked with EP_OuterON (and hence that come from
115452** the ON or USING clauses of OUTER JOINS) are excluded from the analysis.
115453**
115454** This routine is used to check if a LEFT JOIN can be converted into
115455** an ordinary JOIN.  The p argument is the WHERE clause.  If the WHERE
115456** clause requires that some column of the right table of the LEFT JOIN
115457** be non-NULL, then the LEFT JOIN can be safely converted into an
115458** ordinary join.
115459*/
115460SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab, int isRJ){
115461  Walker w;
115462  p = sqlite3ExprSkipCollateAndLikely(p);
115463  if( p==0 ) return 0;
115464  if( p->op==TK_NOTNULL ){
115465    p = p->pLeft;
115466  }else{
115467    while( p->op==TK_AND ){
115468      if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab, isRJ) ) return 1;
115469      p = p->pRight;
115470    }
115471  }
115472  w.xExprCallback = impliesNotNullRow;
115473  w.xSelectCallback = 0;
115474  w.xSelectCallback2 = 0;
115475  w.eCode = 0;
115476  w.mWFlags = isRJ!=0;
115477  w.u.iCur = iTab;
115478  sqlite3WalkExpr(&w, p);
115479  return w.eCode;
115480}
115481
115482/*
115483** An instance of the following structure is used by the tree walker
115484** to determine if an expression can be evaluated by reference to the
115485** index only, without having to do a search for the corresponding
115486** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
115487** is the cursor for the table.
115488*/
115489struct IdxCover {
115490  Index *pIdx;     /* The index to be tested for coverage */
115491  int iCur;        /* Cursor number for the table corresponding to the index */
115492};
115493
115494/*
115495** Check to see if there are references to columns in table
115496** pWalker->u.pIdxCover->iCur can be satisfied using the index
115497** pWalker->u.pIdxCover->pIdx.
115498*/
115499static int exprIdxCover(Walker *pWalker, Expr *pExpr){
115500  if( pExpr->op==TK_COLUMN
115501   && pExpr->iTable==pWalker->u.pIdxCover->iCur
115502   && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
115503  ){
115504    pWalker->eCode = 1;
115505    return WRC_Abort;
115506  }
115507  return WRC_Continue;
115508}
115509
115510/*
115511** Determine if an index pIdx on table with cursor iCur contains will
115512** the expression pExpr.  Return true if the index does cover the
115513** expression and false if the pExpr expression references table columns
115514** that are not found in the index pIdx.
115515**
115516** An index covering an expression means that the expression can be
115517** evaluated using only the index and without having to lookup the
115518** corresponding table entry.
115519*/
115520SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
115521  Expr *pExpr,        /* The index to be tested */
115522  int iCur,           /* The cursor number for the corresponding table */
115523  Index *pIdx         /* The index that might be used for coverage */
115524){
115525  Walker w;
115526  struct IdxCover xcov;
115527  memset(&w, 0, sizeof(w));
115528  xcov.iCur = iCur;
115529  xcov.pIdx = pIdx;
115530  w.xExprCallback = exprIdxCover;
115531  w.u.pIdxCover = &xcov;
115532  sqlite3WalkExpr(&w, pExpr);
115533  return !w.eCode;
115534}
115535
115536
115537/* Structure used to pass information throughout the Walker in order to
115538** implement sqlite3ReferencesSrcList().
115539*/
115540struct RefSrcList {
115541  sqlite3 *db;         /* Database connection used for sqlite3DbRealloc() */
115542  SrcList *pRef;       /* Looking for references to these tables */
115543  i64 nExclude;        /* Number of tables to exclude from the search */
115544  int *aiExclude;      /* Cursor IDs for tables to exclude from the search */
115545};
115546
115547/*
115548** Walker SELECT callbacks for sqlite3ReferencesSrcList().
115549**
115550** When entering a new subquery on the pExpr argument, add all FROM clause
115551** entries for that subquery to the exclude list.
115552**
115553** When leaving the subquery, remove those entries from the exclude list.
115554*/
115555static int selectRefEnter(Walker *pWalker, Select *pSelect){
115556  struct RefSrcList *p = pWalker->u.pRefSrcList;
115557  SrcList *pSrc = pSelect->pSrc;
115558  i64 i, j;
115559  int *piNew;
115560  if( pSrc->nSrc==0 ) return WRC_Continue;
115561  j = p->nExclude;
115562  p->nExclude += pSrc->nSrc;
115563  piNew = sqlite3DbRealloc(p->db, p->aiExclude, p->nExclude*sizeof(int));
115564  if( piNew==0 ){
115565    p->nExclude = 0;
115566    return WRC_Abort;
115567  }else{
115568    p->aiExclude = piNew;
115569  }
115570  for(i=0; i<pSrc->nSrc; i++, j++){
115571     p->aiExclude[j] = pSrc->a[i].iCursor;
115572  }
115573  return WRC_Continue;
115574}
115575static void selectRefLeave(Walker *pWalker, Select *pSelect){
115576  struct RefSrcList *p = pWalker->u.pRefSrcList;
115577  SrcList *pSrc = pSelect->pSrc;
115578  if( p->nExclude ){
115579    assert( p->nExclude>=pSrc->nSrc );
115580    p->nExclude -= pSrc->nSrc;
115581  }
115582}
115583
115584/* This is the Walker EXPR callback for sqlite3ReferencesSrcList().
115585**
115586** Set the 0x01 bit of pWalker->eCode if there is a reference to any
115587** of the tables shown in RefSrcList.pRef.
115588**
115589** Set the 0x02 bit of pWalker->eCode if there is a reference to a
115590** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude.
115591*/
115592static int exprRefToSrcList(Walker *pWalker, Expr *pExpr){
115593  if( pExpr->op==TK_COLUMN
115594   || pExpr->op==TK_AGG_COLUMN
115595  ){
115596    int i;
115597    struct RefSrcList *p = pWalker->u.pRefSrcList;
115598    SrcList *pSrc = p->pRef;
115599    int nSrc = pSrc ? pSrc->nSrc : 0;
115600    for(i=0; i<nSrc; i++){
115601      if( pExpr->iTable==pSrc->a[i].iCursor ){
115602        pWalker->eCode |= 1;
115603        return WRC_Continue;
115604      }
115605    }
115606    for(i=0; i<p->nExclude && p->aiExclude[i]!=pExpr->iTable; i++){}
115607    if( i>=p->nExclude ){
115608      pWalker->eCode |= 2;
115609    }
115610  }
115611  return WRC_Continue;
115612}
115613
115614/*
115615** Check to see if pExpr references any tables in pSrcList.
115616** Possible return values:
115617**
115618**    1         pExpr does references a table in pSrcList.
115619**
115620**    0         pExpr references some table that is not defined in either
115621**              pSrcList or in subqueries of pExpr itself.
115622**
115623**   -1         pExpr only references no tables at all, or it only
115624**              references tables defined in subqueries of pExpr itself.
115625**
115626** As currently used, pExpr is always an aggregate function call.  That
115627** fact is exploited for efficiency.
115628*/
115629SQLITE_PRIVATE int sqlite3ReferencesSrcList(Parse *pParse, Expr *pExpr, SrcList *pSrcList){
115630  Walker w;
115631  struct RefSrcList x;
115632  assert( pParse->db!=0 );
115633  memset(&w, 0, sizeof(w));
115634  memset(&x, 0, sizeof(x));
115635  w.xExprCallback = exprRefToSrcList;
115636  w.xSelectCallback = selectRefEnter;
115637  w.xSelectCallback2 = selectRefLeave;
115638  w.u.pRefSrcList = &x;
115639  x.db = pParse->db;
115640  x.pRef = pSrcList;
115641  assert( pExpr->op==TK_AGG_FUNCTION );
115642  assert( ExprUseXList(pExpr) );
115643  sqlite3WalkExprList(&w, pExpr->x.pList);
115644  if( pExpr->pLeft ){
115645    assert( pExpr->pLeft->op==TK_ORDER );
115646    assert( ExprUseXList(pExpr->pLeft) );
115647    assert( pExpr->pLeft->x.pList!=0 );
115648    sqlite3WalkExprList(&w, pExpr->pLeft->x.pList);
115649  }
115650#ifndef SQLITE_OMIT_WINDOWFUNC
115651  if( ExprHasProperty(pExpr, EP_WinFunc) ){
115652    sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
115653  }
115654#endif
115655  if( x.aiExclude ) sqlite3DbNNFreeNN(pParse->db, x.aiExclude);
115656  if( w.eCode & 0x01 ){
115657    return 1;
115658  }else if( w.eCode ){
115659    return 0;
115660  }else{
115661    return -1;
115662  }
115663}
115664
115665/*
115666** This is a Walker expression node callback.
115667**
115668** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
115669** object that is referenced does not refer directly to the Expr.  If
115670** it does, make a copy.  This is done because the pExpr argument is
115671** subject to change.
115672**
115673** The copy is scheduled for deletion using the sqlite3ExprDeferredDelete()
115674** which builds on the sqlite3ParserAddCleanup() mechanism.
115675*/
115676static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){
115677  if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced))
115678   && pExpr->pAggInfo!=0
115679  ){
115680    AggInfo *pAggInfo = pExpr->pAggInfo;
115681    int iAgg = pExpr->iAgg;
115682    Parse *pParse = pWalker->pParse;
115683    sqlite3 *db = pParse->db;
115684    assert( iAgg>=0 );
115685    if( pExpr->op!=TK_AGG_FUNCTION ){
115686      if( iAgg<pAggInfo->nColumn
115687       && pAggInfo->aCol[iAgg].pCExpr==pExpr
115688      ){
115689        pExpr = sqlite3ExprDup(db, pExpr, 0);
115690        if( pExpr && !sqlite3ExprDeferredDelete(pParse, pExpr) ){
115691          pAggInfo->aCol[iAgg].pCExpr = pExpr;
115692        }
115693      }
115694    }else{
115695      assert( pExpr->op==TK_AGG_FUNCTION );
115696      if( ALWAYS(iAgg<pAggInfo->nFunc)
115697       && pAggInfo->aFunc[iAgg].pFExpr==pExpr
115698      ){
115699        pExpr = sqlite3ExprDup(db, pExpr, 0);
115700        if( pExpr && !sqlite3ExprDeferredDelete(pParse, pExpr) ){
115701          pAggInfo->aFunc[iAgg].pFExpr = pExpr;
115702        }
115703      }
115704    }
115705  }
115706  return WRC_Continue;
115707}
115708
115709/*
115710** Initialize a Walker object so that will persist AggInfo entries referenced
115711** by the tree that is walked.
115712*/
115713SQLITE_PRIVATE void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){
115714  memset(pWalker, 0, sizeof(*pWalker));
115715  pWalker->pParse = pParse;
115716  pWalker->xExprCallback = agginfoPersistExprCb;
115717  pWalker->xSelectCallback = sqlite3SelectWalkNoop;
115718}
115719
115720/*
115721** Add a new element to the pAggInfo->aCol[] array.  Return the index of
115722** the new element.  Return a negative number if malloc fails.
115723*/
115724static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
115725  int i;
115726  pInfo->aCol = sqlite3ArrayAllocate(
115727       db,
115728       pInfo->aCol,
115729       sizeof(pInfo->aCol[0]),
115730       &pInfo->nColumn,
115731       &i
115732  );
115733  return i;
115734}
115735
115736/*
115737** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
115738** the new element.  Return a negative number if malloc fails.
115739*/
115740static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
115741  int i;
115742  pInfo->aFunc = sqlite3ArrayAllocate(
115743       db,
115744       pInfo->aFunc,
115745       sizeof(pInfo->aFunc[0]),
115746       &pInfo->nFunc,
115747       &i
115748  );
115749  return i;
115750}
115751
115752/*
115753** Search the AggInfo object for an aCol[] entry that has iTable and iColumn.
115754** Return the index in aCol[] of the entry that describes that column.
115755**
115756** If no prior entry is found, create a new one and return -1.  The
115757** new column will have an index of pAggInfo->nColumn-1.
115758*/
115759static void findOrCreateAggInfoColumn(
115760  Parse *pParse,       /* Parsing context */
115761  AggInfo *pAggInfo,   /* The AggInfo object to search and/or modify */
115762  Expr *pExpr          /* Expr describing the column to find or insert */
115763){
115764  struct AggInfo_col *pCol;
115765  int k;
115766
115767  assert( pAggInfo->iFirstReg==0 );
115768  pCol = pAggInfo->aCol;
115769  for(k=0; k<pAggInfo->nColumn; k++, pCol++){
115770    if( pCol->pCExpr==pExpr ) return;
115771    if( pCol->iTable==pExpr->iTable
115772     && pCol->iColumn==pExpr->iColumn
115773     && pExpr->op!=TK_IF_NULL_ROW
115774    ){
115775      goto fix_up_expr;
115776    }
115777  }
115778  k = addAggInfoColumn(pParse->db, pAggInfo);
115779  if( k<0 ){
115780    /* OOM on resize */
115781    assert( pParse->db->mallocFailed );
115782    return;
115783  }
115784  pCol = &pAggInfo->aCol[k];
115785  assert( ExprUseYTab(pExpr) );
115786  pCol->pTab = pExpr->y.pTab;
115787  pCol->iTable = pExpr->iTable;
115788  pCol->iColumn = pExpr->iColumn;
115789  pCol->iSorterColumn = -1;
115790  pCol->pCExpr = pExpr;
115791  if( pAggInfo->pGroupBy && pExpr->op!=TK_IF_NULL_ROW ){
115792    int j, n;
115793    ExprList *pGB = pAggInfo->pGroupBy;
115794    struct ExprList_item *pTerm = pGB->a;
115795    n = pGB->nExpr;
115796    for(j=0; j<n; j++, pTerm++){
115797      Expr *pE = pTerm->pExpr;
115798      if( pE->op==TK_COLUMN
115799       && pE->iTable==pExpr->iTable
115800       && pE->iColumn==pExpr->iColumn
115801      ){
115802        pCol->iSorterColumn = j;
115803        break;
115804      }
115805    }
115806  }
115807  if( pCol->iSorterColumn<0 ){
115808    pCol->iSorterColumn = pAggInfo->nSortingColumn++;
115809  }
115810fix_up_expr:
115811  ExprSetVVAProperty(pExpr, EP_NoReduce);
115812  assert( pExpr->pAggInfo==0 || pExpr->pAggInfo==pAggInfo );
115813  pExpr->pAggInfo = pAggInfo;
115814  if( pExpr->op==TK_COLUMN ){
115815    pExpr->op = TK_AGG_COLUMN;
115816  }
115817  pExpr->iAgg = (i16)k;
115818}
115819
115820/*
115821** This is the xExprCallback for a tree walker.  It is used to
115822** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
115823** for additional information.
115824*/
115825static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
115826  int i;
115827  NameContext *pNC = pWalker->u.pNC;
115828  Parse *pParse = pNC->pParse;
115829  SrcList *pSrcList = pNC->pSrcList;
115830  AggInfo *pAggInfo = pNC->uNC.pAggInfo;
115831
115832  assert( pNC->ncFlags & NC_UAggInfo );
115833  assert( pAggInfo->iFirstReg==0 );
115834  switch( pExpr->op ){
115835    default: {
115836      IndexedExpr *pIEpr;
115837      Expr tmp;
115838      assert( pParse->iSelfTab==0 );
115839      if( (pNC->ncFlags & NC_InAggFunc)==0 ) break;
115840      if( pParse->pIdxEpr==0 ) break;
115841      for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
115842        int iDataCur = pIEpr->iDataCur;
115843        if( iDataCur<0 ) continue;
115844        if( sqlite3ExprCompare(0, pExpr, pIEpr->pExpr, iDataCur)==0 ) break;
115845      }
115846      if( pIEpr==0 ) break;
115847      if( NEVER(!ExprUseYTab(pExpr)) ) break;
115848      for(i=0; i<pSrcList->nSrc; i++){
115849         if( pSrcList->a[0].iCursor==pIEpr->iDataCur ) break;
115850      }
115851      if( i>=pSrcList->nSrc ) break;
115852      if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */
115853      if( pParse->nErr ){ return WRC_Abort; }
115854
115855      /* If we reach this point, it means that expression pExpr can be
115856      ** translated into a reference to an index column as described by
115857      ** pIEpr.
115858      */
115859      memset(&tmp, 0, sizeof(tmp));
115860      tmp.op = TK_AGG_COLUMN;
115861      tmp.iTable = pIEpr->iIdxCur;
115862      tmp.iColumn = pIEpr->iIdxCol;
115863      findOrCreateAggInfoColumn(pParse, pAggInfo, &tmp);
115864      if( pParse->nErr ){ return WRC_Abort; }
115865      assert( pAggInfo->aCol!=0 );
115866      assert( tmp.iAgg<pAggInfo->nColumn );
115867      pAggInfo->aCol[tmp.iAgg].pCExpr = pExpr;
115868      pExpr->pAggInfo = pAggInfo;
115869      pExpr->iAgg = tmp.iAgg;
115870      return WRC_Prune;
115871    }
115872    case TK_IF_NULL_ROW:
115873    case TK_AGG_COLUMN:
115874    case TK_COLUMN: {
115875      testcase( pExpr->op==TK_AGG_COLUMN );
115876      testcase( pExpr->op==TK_COLUMN );
115877      testcase( pExpr->op==TK_IF_NULL_ROW );
115878      /* Check to see if the column is in one of the tables in the FROM
115879      ** clause of the aggregate query */
115880      if( ALWAYS(pSrcList!=0) ){
115881        SrcItem *pItem = pSrcList->a;
115882        for(i=0; i<pSrcList->nSrc; i++, pItem++){
115883          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
115884          if( pExpr->iTable==pItem->iCursor ){
115885            findOrCreateAggInfoColumn(pParse, pAggInfo, pExpr);
115886            break;
115887          } /* endif pExpr->iTable==pItem->iCursor */
115888        } /* end loop over pSrcList */
115889      }
115890      return WRC_Continue;
115891    }
115892    case TK_AGG_FUNCTION: {
115893      if( (pNC->ncFlags & NC_InAggFunc)==0
115894       && pWalker->walkerDepth==pExpr->op2
115895       && pExpr->pAggInfo==0
115896      ){
115897        /* Check to see if pExpr is a duplicate of another aggregate
115898        ** function that is already in the pAggInfo structure
115899        */
115900        struct AggInfo_func *pItem = pAggInfo->aFunc;
115901        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
115902          if( NEVER(pItem->pFExpr==pExpr) ) break;
115903          if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
115904            break;
115905          }
115906        }
115907        if( i>=pAggInfo->nFunc ){
115908          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
115909          */
115910          u8 enc = ENC(pParse->db);
115911          i = addAggInfoFunc(pParse->db, pAggInfo);
115912          if( i>=0 ){
115913            int nArg;
115914            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
115915            pItem = &pAggInfo->aFunc[i];
115916            pItem->pFExpr = pExpr;
115917            assert( ExprUseUToken(pExpr) );
115918            nArg = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
115919            pItem->pFunc = sqlite3FindFunction(pParse->db,
115920                                         pExpr->u.zToken, nArg, enc, 0);
115921            assert( pItem->bOBUnique==0 );
115922            if( pExpr->pLeft
115923             && (pItem->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)==0
115924            ){
115925              /* The NEEDCOLL test above causes any ORDER BY clause on
115926              ** aggregate min() or max() to be ignored. */
115927              ExprList *pOBList;
115928              assert( nArg>0 );
115929              assert( pExpr->pLeft->op==TK_ORDER );
115930              assert( ExprUseXList(pExpr->pLeft) );
115931              pItem->iOBTab = pParse->nTab++;
115932              pOBList = pExpr->pLeft->x.pList;
115933              assert( pOBList->nExpr>0 );
115934              assert( pItem->bOBUnique==0 );
115935              if( pOBList->nExpr==1
115936               && nArg==1
115937               && sqlite3ExprCompare(0,pOBList->a[0].pExpr,
115938                               pExpr->x.pList->a[0].pExpr,0)==0
115939              ){
115940                pItem->bOBPayload = 0;
115941                pItem->bOBUnique = ExprHasProperty(pExpr, EP_Distinct);
115942              }else{
115943                pItem->bOBPayload = 1;
115944              }
115945              pItem->bUseSubtype =
115946                    (pItem->pFunc->funcFlags & SQLITE_SUBTYPE)!=0;
115947            }else{
115948              pItem->iOBTab = -1;
115949            }
115950            if( ExprHasProperty(pExpr, EP_Distinct) && !pItem->bOBUnique ){
115951              pItem->iDistinct = pParse->nTab++;
115952            }else{
115953              pItem->iDistinct = -1;
115954            }
115955          }
115956        }
115957        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
115958        */
115959        assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
115960        ExprSetVVAProperty(pExpr, EP_NoReduce);
115961        pExpr->iAgg = (i16)i;
115962        pExpr->pAggInfo = pAggInfo;
115963        return WRC_Prune;
115964      }else{
115965        return WRC_Continue;
115966      }
115967    }
115968  }
115969  return WRC_Continue;
115970}
115971
115972/*
115973** Analyze the pExpr expression looking for aggregate functions and
115974** for variables that need to be added to AggInfo object that pNC->pAggInfo
115975** points to.  Additional entries are made on the AggInfo object as
115976** necessary.
115977**
115978** This routine should only be called after the expression has been
115979** analyzed by sqlite3ResolveExprNames().
115980*/
115981SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
115982  Walker w;
115983  w.xExprCallback = analyzeAggregate;
115984  w.xSelectCallback = sqlite3WalkerDepthIncrease;
115985  w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
115986  w.walkerDepth = 0;
115987  w.u.pNC = pNC;
115988  w.pParse = 0;
115989  assert( pNC->pSrcList!=0 );
115990  sqlite3WalkExpr(&w, pExpr);
115991}
115992
115993/*
115994** Call sqlite3ExprAnalyzeAggregates() for every expression in an
115995** expression list.  Return the number of errors.
115996**
115997** If an error is found, the analysis is cut short.
115998*/
115999SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
116000  struct ExprList_item *pItem;
116001  int i;
116002  if( pList ){
116003    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
116004      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
116005    }
116006  }
116007}
116008
116009/*
116010** Allocate a single new register for use to hold some intermediate result.
116011*/
116012SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
116013  if( pParse->nTempReg==0 ){
116014    return ++pParse->nMem;
116015  }
116016  return pParse->aTempReg[--pParse->nTempReg];
116017}
116018
116019/*
116020** Deallocate a register, making available for reuse for some other
116021** purpose.
116022*/
116023SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
116024  if( iReg ){
116025    sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0);
116026    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
116027      pParse->aTempReg[pParse->nTempReg++] = iReg;
116028    }
116029  }
116030}
116031
116032/*
116033** Allocate or deallocate a block of nReg consecutive registers.
116034*/
116035SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
116036  int i, n;
116037  if( nReg==1 ) return sqlite3GetTempReg(pParse);
116038  i = pParse->iRangeReg;
116039  n = pParse->nRangeReg;
116040  if( nReg<=n ){
116041    pParse->iRangeReg += nReg;
116042    pParse->nRangeReg -= nReg;
116043  }else{
116044    i = pParse->nMem+1;
116045    pParse->nMem += nReg;
116046  }
116047  return i;
116048}
116049SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
116050  if( nReg==1 ){
116051    sqlite3ReleaseTempReg(pParse, iReg);
116052    return;
116053  }
116054  sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0);
116055  if( nReg>pParse->nRangeReg ){
116056    pParse->nRangeReg = nReg;
116057    pParse->iRangeReg = iReg;
116058  }
116059}
116060
116061/*
116062** Mark all temporary registers as being unavailable for reuse.
116063**
116064** Always invoke this procedure after coding a subroutine or co-routine
116065** that might be invoked from other parts of the code, to ensure that
116066** the sub/co-routine does not use registers in common with the code that
116067** invokes the sub/co-routine.
116068*/
116069SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
116070  pParse->nTempReg = 0;
116071  pParse->nRangeReg = 0;
116072}
116073
116074/*
116075** Make sure sufficient registers have been allocated so that
116076** iReg is a valid register number.
116077*/
116078SQLITE_PRIVATE void sqlite3TouchRegister(Parse *pParse, int iReg){
116079  if( pParse->nMem<iReg ) pParse->nMem = iReg;
116080}
116081
116082#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
116083/*
116084** Return the latest reusable register in the set of all registers.
116085** The value returned is no less than iMin.  If any register iMin or
116086** greater is in permanent use, then return one more than that last
116087** permanent register.
116088*/
116089SQLITE_PRIVATE int sqlite3FirstAvailableRegister(Parse *pParse, int iMin){
116090  const ExprList *pList = pParse->pConstExpr;
116091  if( pList ){
116092    int i;
116093    for(i=0; i<pList->nExpr; i++){
116094      if( pList->a[i].u.iConstExprReg>=iMin ){
116095        iMin = pList->a[i].u.iConstExprReg + 1;
116096      }
116097    }
116098  }
116099  pParse->nTempReg = 0;
116100  pParse->nRangeReg = 0;
116101  return iMin;
116102}
116103#endif /* SQLITE_ENABLE_STAT4 || SQLITE_DEBUG */
116104
116105/*
116106** Validate that no temporary register falls within the range of
116107** iFirst..iLast, inclusive.  This routine is only call from within assert()
116108** statements.
116109*/
116110#ifdef SQLITE_DEBUG
116111SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
116112  int i;
116113  if( pParse->nRangeReg>0
116114   && pParse->iRangeReg+pParse->nRangeReg > iFirst
116115   && pParse->iRangeReg <= iLast
116116  ){
116117     return 0;
116118  }
116119  for(i=0; i<pParse->nTempReg; i++){
116120    if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
116121      return 0;
116122    }
116123  }
116124  if( pParse->pConstExpr ){
116125    ExprList *pList = pParse->pConstExpr;
116126    for(i=0; i<pList->nExpr; i++){
116127      int iReg = pList->a[i].u.iConstExprReg;
116128      if( iReg==0 ) continue;
116129      if( iReg>=iFirst && iReg<=iLast ) return 0;
116130    }
116131  }
116132  return 1;
116133}
116134#endif /* SQLITE_DEBUG */
116135
116136/************** End of expr.c ************************************************/
116137/************** Begin file alter.c *******************************************/
116138/*
116139** 2005 February 15
116140**
116141** The author disclaims copyright to this source code.  In place of
116142** a legal notice, here is a blessing:
116143**
116144**    May you do good and not evil.
116145**    May you find forgiveness for yourself and forgive others.
116146**    May you share freely, never taking more than you give.
116147**
116148*************************************************************************
116149** This file contains C code routines that used to generate VDBE code
116150** that implements the ALTER TABLE command.
116151*/
116152/* #include "sqliteInt.h" */
116153
116154/*
116155** The code in this file only exists if we are not omitting the
116156** ALTER TABLE logic from the build.
116157*/
116158#ifndef SQLITE_OMIT_ALTERTABLE
116159
116160/*
116161** Parameter zName is the name of a table that is about to be altered
116162** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
116163** If the table is a system table, this function leaves an error message
116164** in pParse->zErr (system tables may not be altered) and returns non-zero.
116165**
116166** Or, if zName is not a system table, zero is returned.
116167*/
116168static int isAlterableTable(Parse *pParse, Table *pTab){
116169  if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
116170#ifndef SQLITE_OMIT_VIRTUALTABLE
116171   || (pTab->tabFlags & TF_Eponymous)!=0
116172   || ( (pTab->tabFlags & TF_Shadow)!=0
116173        && sqlite3ReadOnlyShadowTables(pParse->db)
116174   )
116175#endif
116176  ){
116177    sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
116178    return 1;
116179  }
116180  return 0;
116181}
116182
116183/*
116184** Generate code to verify that the schemas of database zDb and, if
116185** bTemp is not true, database "temp", can still be parsed. This is
116186** called at the end of the generation of an ALTER TABLE ... RENAME ...
116187** statement to ensure that the operation has not rendered any schema
116188** objects unusable.
116189*/
116190static void renameTestSchema(
116191  Parse *pParse,                  /* Parse context */
116192  const char *zDb,                /* Name of db to verify schema of */
116193  int bTemp,                      /* True if this is the temp db */
116194  const char *zWhen,              /* "when" part of error message */
116195  int bNoDQS                      /* Do not allow DQS in the schema */
116196){
116197  pParse->colNamesSet = 1;
116198  sqlite3NestedParse(pParse,
116199      "SELECT 1 "
116200      "FROM \"%w\"." LEGACY_SCHEMA_TABLE " "
116201      "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
116202      " AND sql NOT LIKE 'create virtual%%'"
116203      " AND sqlite_rename_test(%Q, sql, type, name, %d, %Q, %d)=NULL ",
116204      zDb,
116205      zDb, bTemp, zWhen, bNoDQS
116206  );
116207
116208  if( bTemp==0 ){
116209    sqlite3NestedParse(pParse,
116210        "SELECT 1 "
116211        "FROM temp." LEGACY_SCHEMA_TABLE " "
116212        "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
116213        " AND sql NOT LIKE 'create virtual%%'"
116214        " AND sqlite_rename_test(%Q, sql, type, name, 1, %Q, %d)=NULL ",
116215        zDb, zWhen, bNoDQS
116216    );
116217  }
116218}
116219
116220/*
116221** Generate VM code to replace any double-quoted strings (but not double-quoted
116222** identifiers) within the "sql" column of the sqlite_schema table in
116223** database zDb with their single-quoted equivalents. If argument bTemp is
116224** not true, similarly update all SQL statements in the sqlite_schema table
116225** of the temp db.
116226*/
116227static void renameFixQuotes(Parse *pParse, const char *zDb, int bTemp){
116228  sqlite3NestedParse(pParse,
116229      "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE
116230      " SET sql = sqlite_rename_quotefix(%Q, sql)"
116231      "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
116232      " AND sql NOT LIKE 'create virtual%%'" , zDb, zDb
116233  );
116234  if( bTemp==0 ){
116235    sqlite3NestedParse(pParse,
116236      "UPDATE temp." LEGACY_SCHEMA_TABLE
116237      " SET sql = sqlite_rename_quotefix('temp', sql)"
116238      "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
116239      " AND sql NOT LIKE 'create virtual%%'"
116240    );
116241  }
116242}
116243
116244/*
116245** Generate code to reload the schema for database iDb. And, if iDb!=1, for
116246** the temp database as well.
116247*/
116248static void renameReloadSchema(Parse *pParse, int iDb, u16 p5){
116249  Vdbe *v = pParse->pVdbe;
116250  if( v ){
116251    sqlite3ChangeCookie(pParse, iDb);
116252    sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0, p5);
116253    if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0, p5);
116254  }
116255}
116256
116257/*
116258** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
116259** command.
116260*/
116261SQLITE_PRIVATE void sqlite3AlterRenameTable(
116262  Parse *pParse,            /* Parser context. */
116263  SrcList *pSrc,            /* The table to rename. */
116264  Token *pName              /* The new table name. */
116265){
116266  int iDb;                  /* Database that contains the table */
116267  char *zDb;                /* Name of database iDb */
116268  Table *pTab;              /* Table being renamed */
116269  char *zName = 0;          /* NULL-terminated version of pName */
116270  sqlite3 *db = pParse->db; /* Database connection */
116271  int nTabName;             /* Number of UTF-8 characters in zTabName */
116272  const char *zTabName;     /* Original name of the table */
116273  Vdbe *v;
116274  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
116275
116276  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
116277  assert( pSrc->nSrc==1 );
116278  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
116279
116280  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
116281  if( !pTab ) goto exit_rename_table;
116282  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
116283  zDb = db->aDb[iDb].zDbSName;
116284
116285  /* Get a NULL terminated version of the new table name. */
116286  zName = sqlite3NameFromToken(db, pName);
116287  if( !zName ) goto exit_rename_table;
116288
116289  /* Check that a table or index named 'zName' does not already exist
116290  ** in database iDb. If so, this is an error.
116291  */
116292  if( sqlite3FindTable(db, zName, zDb)
116293   || sqlite3FindIndex(db, zName, zDb)
116294   || sqlite3IsShadowTableOf(db, pTab, zName)
116295  ){
116296    sqlite3ErrorMsg(pParse,
116297        "there is already another table or index with this name: %s", zName);
116298    goto exit_rename_table;
116299  }
116300
116301  /* Make sure it is not a system table being altered, or a reserved name
116302  ** that the table is being renamed to.
116303  */
116304  if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
116305    goto exit_rename_table;
116306  }
116307  if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
116308    goto exit_rename_table;
116309  }
116310
116311#ifndef SQLITE_OMIT_VIEW
116312  if( IsView(pTab) ){
116313    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
116314    goto exit_rename_table;
116315  }
116316#endif
116317
116318#ifndef SQLITE_OMIT_AUTHORIZATION
116319  /* Invoke the authorization callback. */
116320  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
116321    goto exit_rename_table;
116322  }
116323#endif
116324
116325#ifndef SQLITE_OMIT_VIRTUALTABLE
116326  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
116327    goto exit_rename_table;
116328  }
116329  if( IsVirtual(pTab) ){
116330    pVTab = sqlite3GetVTable(db, pTab);
116331    if( pVTab->pVtab->pModule->xRename==0 ){
116332      pVTab = 0;
116333    }
116334  }
116335#endif
116336
116337  /* Begin a transaction for database iDb. Then modify the schema cookie
116338  ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
116339  ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
116340  ** nested SQL may raise an exception.  */
116341  v = sqlite3GetVdbe(pParse);
116342  if( v==0 ){
116343    goto exit_rename_table;
116344  }
116345  sqlite3MayAbort(pParse);
116346
116347  /* figure out how many UTF-8 characters are in zName */
116348  zTabName = pTab->zName;
116349  nTabName = sqlite3Utf8CharLen(zTabName, -1);
116350
116351  /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
116352  ** the schema to use the new table name.  */
116353  sqlite3NestedParse(pParse,
116354      "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
116355      "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
116356      "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
116357      "AND   name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
116358      , zDb, zDb, zTabName, zName, (iDb==1), zTabName
116359  );
116360
116361  /* Update the tbl_name and name columns of the sqlite_schema table
116362  ** as required.  */
116363  sqlite3NestedParse(pParse,
116364      "UPDATE %Q." LEGACY_SCHEMA_TABLE " SET "
116365          "tbl_name = %Q, "
116366          "name = CASE "
116367            "WHEN type='table' THEN %Q "
116368            "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
116369            "     AND type='index' THEN "
116370             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
116371            "ELSE name END "
116372      "WHERE tbl_name=%Q COLLATE nocase AND "
116373          "(type='table' OR type='index' OR type='trigger');",
116374      zDb,
116375      zName, zName, zName,
116376      nTabName, zTabName
116377  );
116378
116379#ifndef SQLITE_OMIT_AUTOINCREMENT
116380  /* If the sqlite_sequence table exists in this database, then update
116381  ** it with the new table name.
116382  */
116383  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
116384    sqlite3NestedParse(pParse,
116385        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
116386        zDb, zName, pTab->zName);
116387  }
116388#endif
116389
116390  /* If the table being renamed is not itself part of the temp database,
116391  ** edit view and trigger definitions within the temp database
116392  ** as required.  */
116393  if( iDb!=1 ){
116394    sqlite3NestedParse(pParse,
116395        "UPDATE sqlite_temp_schema SET "
116396            "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
116397            "tbl_name = "
116398              "CASE WHEN tbl_name=%Q COLLATE nocase AND "
116399              "  sqlite_rename_test(%Q, sql, type, name, 1, 'after rename', 0) "
116400              "THEN %Q ELSE tbl_name END "
116401            "WHERE type IN ('view', 'trigger')"
116402        , zDb, zTabName, zName, zTabName, zDb, zName);
116403  }
116404
116405  /* If this is a virtual table, invoke the xRename() function if
116406  ** one is defined. The xRename() callback will modify the names
116407  ** of any resources used by the v-table implementation (including other
116408  ** SQLite tables) that are identified by the name of the virtual table.
116409  */
116410#ifndef SQLITE_OMIT_VIRTUALTABLE
116411  if( pVTab ){
116412    int i = ++pParse->nMem;
116413    sqlite3VdbeLoadString(v, i, zName);
116414    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
116415  }
116416#endif
116417
116418  renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
116419  renameTestSchema(pParse, zDb, iDb==1, "after rename", 0);
116420
116421exit_rename_table:
116422  sqlite3SrcListDelete(db, pSrc);
116423  sqlite3DbFree(db, zName);
116424}
116425
116426/*
116427** Write code that will raise an error if the table described by
116428** zDb and zTab is not empty.
116429*/
116430static void sqlite3ErrorIfNotEmpty(
116431  Parse *pParse,        /* Parsing context */
116432  const char *zDb,      /* Schema holding the table */
116433  const char *zTab,     /* Table to check for empty */
116434  const char *zErr      /* Error message text */
116435){
116436  sqlite3NestedParse(pParse,
116437     "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
116438     zErr, zDb, zTab
116439  );
116440}
116441
116442/*
116443** This function is called after an "ALTER TABLE ... ADD" statement
116444** has been parsed. Argument pColDef contains the text of the new
116445** column definition.
116446**
116447** The Table structure pParse->pNewTable was extended to include
116448** the new column during parsing.
116449*/
116450SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
116451  Table *pNew;              /* Copy of pParse->pNewTable */
116452  Table *pTab;              /* Table being altered */
116453  int iDb;                  /* Database number */
116454  const char *zDb;          /* Database name */
116455  const char *zTab;         /* Table name */
116456  char *zCol;               /* Null-terminated column definition */
116457  Column *pCol;             /* The new column */
116458  Expr *pDflt;              /* Default value for the new column */
116459  sqlite3 *db;              /* The database connection; */
116460  Vdbe *v;                  /* The prepared statement under construction */
116461  int r1;                   /* Temporary registers */
116462
116463  db = pParse->db;
116464  assert( db->pParse==pParse );
116465  if( pParse->nErr ) return;
116466  assert( db->mallocFailed==0 );
116467  pNew = pParse->pNewTable;
116468  assert( pNew );
116469
116470  assert( sqlite3BtreeHoldsAllMutexes(db) );
116471  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
116472  zDb = db->aDb[iDb].zDbSName;
116473  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
116474  pCol = &pNew->aCol[pNew->nCol-1];
116475  pDflt = sqlite3ColumnExpr(pNew, pCol);
116476  pTab = sqlite3FindTable(db, zTab, zDb);
116477  assert( pTab );
116478
116479#ifndef SQLITE_OMIT_AUTHORIZATION
116480  /* Invoke the authorization callback. */
116481  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
116482    return;
116483  }
116484#endif
116485
116486
116487  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
116488  ** If there is a NOT NULL constraint, then the default value for the
116489  ** column must not be NULL.
116490  */
116491  if( pCol->colFlags & COLFLAG_PRIMKEY ){
116492    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
116493    return;
116494  }
116495  if( pNew->pIndex ){
116496    sqlite3ErrorMsg(pParse,
116497         "Cannot add a UNIQUE column");
116498    return;
116499  }
116500  if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
116501    /* If the default value for the new column was specified with a
116502    ** literal NULL, then set pDflt to 0. This simplifies checking
116503    ** for an SQL NULL default below.
116504    */
116505    assert( pDflt==0 || pDflt->op==TK_SPAN );
116506    if( pDflt && pDflt->pLeft->op==TK_NULL ){
116507      pDflt = 0;
116508    }
116509    assert( IsOrdinaryTable(pNew) );
116510    if( (db->flags&SQLITE_ForeignKeys) && pNew->u.tab.pFKey && pDflt ){
116511      sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
116512          "Cannot add a REFERENCES column with non-NULL default value");
116513    }
116514    if( pCol->notNull && !pDflt ){
116515      sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
116516          "Cannot add a NOT NULL column with default value NULL");
116517    }
116518
116519
116520    /* Ensure the default expression is something that sqlite3ValueFromExpr()
116521    ** can handle (i.e. not CURRENT_TIME etc.)
116522    */
116523    if( pDflt ){
116524      sqlite3_value *pVal = 0;
116525      int rc;
116526      rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
116527      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
116528      if( rc!=SQLITE_OK ){
116529        assert( db->mallocFailed == 1 );
116530        return;
116531      }
116532      if( !pVal ){
116533        sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
116534           "Cannot add a column with non-constant default");
116535      }
116536      sqlite3ValueFree(pVal);
116537    }
116538  }else if( pCol->colFlags & COLFLAG_STORED ){
116539    sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
116540  }
116541
116542
116543  /* Modify the CREATE TABLE statement. */
116544  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
116545  if( zCol ){
116546    char *zEnd = &zCol[pColDef->n-1];
116547    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
116548      *zEnd-- = '\0';
116549    }
116550    /* substr() operations on characters, but addColOffset is in bytes. So we
116551    ** have to use printf() to translate between these units: */
116552    assert( IsOrdinaryTable(pTab) );
116553    assert( IsOrdinaryTable(pNew) );
116554    sqlite3NestedParse(pParse,
116555        "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
116556          "sql = printf('%%.%ds, ',sql) || %Q"
116557          " || substr(sql,1+length(printf('%%.%ds',sql))) "
116558        "WHERE type = 'table' AND name = %Q",
116559      zDb, pNew->u.tab.addColOffset, zCol, pNew->u.tab.addColOffset,
116560      zTab
116561    );
116562    sqlite3DbFree(db, zCol);
116563  }
116564
116565  v = sqlite3GetVdbe(pParse);
116566  if( v ){
116567    /* Make sure the schema version is at least 3.  But do not upgrade
116568    ** from less than 3 to 4, as that will corrupt any preexisting DESC
116569    ** index.
116570    */
116571    r1 = sqlite3GetTempReg(pParse);
116572    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
116573    sqlite3VdbeUsesBtree(v, iDb);
116574    sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
116575    sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
116576    VdbeCoverage(v);
116577    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
116578    sqlite3ReleaseTempReg(pParse, r1);
116579
116580    /* Reload the table definition */
116581    renameReloadSchema(pParse, iDb, INITFLAG_AlterAdd);
116582
116583    /* Verify that constraints are still satisfied */
116584    if( pNew->pCheck!=0
116585     || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0)
116586     || (pTab->tabFlags & TF_Strict)!=0
116587    ){
116588      sqlite3NestedParse(pParse,
116589        "SELECT CASE WHEN quick_check GLOB 'CHECK*'"
116590        " THEN raise(ABORT,'CHECK constraint failed')"
116591        " WHEN quick_check GLOB 'non-* value in*'"
116592        " THEN raise(ABORT,'type mismatch on DEFAULT')"
116593        " ELSE raise(ABORT,'NOT NULL constraint failed')"
116594        " END"
116595        "  FROM pragma_quick_check(%Q,%Q)"
116596        " WHERE quick_check GLOB 'CHECK*'"
116597        " OR quick_check GLOB 'NULL*'"
116598        " OR quick_check GLOB 'non-* value in*'",
116599        zTab, zDb
116600      );
116601    }
116602  }
116603}
116604
116605/*
116606** This function is called by the parser after the table-name in
116607** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
116608** pSrc is the full-name of the table being altered.
116609**
116610** This routine makes a (partial) copy of the Table structure
116611** for the table being altered and sets Parse.pNewTable to point
116612** to it. Routines called by the parser as the column definition
116613** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
116614** the copy. The copy of the Table structure is deleted by tokenize.c
116615** after parsing is finished.
116616**
116617** Routine sqlite3AlterFinishAddColumn() will be called to complete
116618** coding the "ALTER TABLE ... ADD" statement.
116619*/
116620SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
116621  Table *pNew;
116622  Table *pTab;
116623  int iDb;
116624  int i;
116625  int nAlloc;
116626  sqlite3 *db = pParse->db;
116627
116628  /* Look up the table being altered. */
116629  assert( pParse->pNewTable==0 );
116630  assert( sqlite3BtreeHoldsAllMutexes(db) );
116631  if( db->mallocFailed ) goto exit_begin_add_column;
116632  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
116633  if( !pTab ) goto exit_begin_add_column;
116634
116635#ifndef SQLITE_OMIT_VIRTUALTABLE
116636  if( IsVirtual(pTab) ){
116637    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
116638    goto exit_begin_add_column;
116639  }
116640#endif
116641
116642  /* Make sure this is not an attempt to ALTER a view. */
116643  if( IsView(pTab) ){
116644    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
116645    goto exit_begin_add_column;
116646  }
116647  if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
116648    goto exit_begin_add_column;
116649  }
116650
116651  sqlite3MayAbort(pParse);
116652  assert( IsOrdinaryTable(pTab) );
116653  assert( pTab->u.tab.addColOffset>0 );
116654  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
116655
116656  /* Put a copy of the Table struct in Parse.pNewTable for the
116657  ** sqlite3AddColumn() function and friends to modify.  But modify
116658  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
116659  ** prefix, we insure that the name will not collide with an existing
116660  ** table because user table are not allowed to have the "sqlite_"
116661  ** prefix on their name.
116662  */
116663  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
116664  if( !pNew ) goto exit_begin_add_column;
116665  pParse->pNewTable = pNew;
116666  pNew->nTabRef = 1;
116667  pNew->nCol = pTab->nCol;
116668  assert( pNew->nCol>0 );
116669  nAlloc = (((pNew->nCol-1)/8)*8)+8;
116670  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
116671  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
116672  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
116673  if( !pNew->aCol || !pNew->zName ){
116674    assert( db->mallocFailed );
116675    goto exit_begin_add_column;
116676  }
116677  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
116678  for(i=0; i<pNew->nCol; i++){
116679    Column *pCol = &pNew->aCol[i];
116680    pCol->zCnName = sqlite3DbStrDup(db, pCol->zCnName);
116681    pCol->hName = sqlite3StrIHash(pCol->zCnName);
116682  }
116683  assert( IsOrdinaryTable(pNew) );
116684  pNew->u.tab.pDfltList = sqlite3ExprListDup(db, pTab->u.tab.pDfltList, 0);
116685  pNew->pSchema = db->aDb[iDb].pSchema;
116686  pNew->u.tab.addColOffset = pTab->u.tab.addColOffset;
116687  assert( pNew->nTabRef==1 );
116688
116689exit_begin_add_column:
116690  sqlite3SrcListDelete(db, pSrc);
116691  return;
116692}
116693
116694/*
116695** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
116696** command. This function checks if the table is a view or virtual
116697** table (columns of views or virtual tables may not be renamed). If so,
116698** it loads an error message into pParse and returns non-zero.
116699**
116700** Or, if pTab is not a view or virtual table, zero is returned.
116701*/
116702#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
116703static int isRealTable(Parse *pParse, Table *pTab, int bDrop){
116704  const char *zType = 0;
116705#ifndef SQLITE_OMIT_VIEW
116706  if( IsView(pTab) ){
116707    zType = "view";
116708  }
116709#endif
116710#ifndef SQLITE_OMIT_VIRTUALTABLE
116711  if( IsVirtual(pTab) ){
116712    zType = "virtual table";
116713  }
116714#endif
116715  if( zType ){
116716    sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"",
116717        (bDrop ? "drop column from" : "rename columns of"),
116718        zType, pTab->zName
116719    );
116720    return 1;
116721  }
116722  return 0;
116723}
116724#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
116725# define isRealTable(x,y,z) (0)
116726#endif
116727
116728/*
116729** Handles the following parser reduction:
116730**
116731**  cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
116732*/
116733SQLITE_PRIVATE void sqlite3AlterRenameColumn(
116734  Parse *pParse,                  /* Parsing context */
116735  SrcList *pSrc,                  /* Table being altered.  pSrc->nSrc==1 */
116736  Token *pOld,                    /* Name of column being changed */
116737  Token *pNew                     /* New column name */
116738){
116739  sqlite3 *db = pParse->db;       /* Database connection */
116740  Table *pTab;                    /* Table being updated */
116741  int iCol;                       /* Index of column being renamed */
116742  char *zOld = 0;                 /* Old column name */
116743  char *zNew = 0;                 /* New column name */
116744  const char *zDb;                /* Name of schema containing the table */
116745  int iSchema;                    /* Index of the schema */
116746  int bQuote;                     /* True to quote the new name */
116747
116748  /* Locate the table to be altered */
116749  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
116750  if( !pTab ) goto exit_rename_column;
116751
116752  /* Cannot alter a system table */
116753  if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
116754  if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column;
116755
116756  /* Which schema holds the table to be altered */
116757  iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
116758  assert( iSchema>=0 );
116759  zDb = db->aDb[iSchema].zDbSName;
116760
116761#ifndef SQLITE_OMIT_AUTHORIZATION
116762  /* Invoke the authorization callback. */
116763  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
116764    goto exit_rename_column;
116765  }
116766#endif
116767
116768  /* Make sure the old name really is a column name in the table to be
116769  ** altered.  Set iCol to be the index of the column being renamed */
116770  zOld = sqlite3NameFromToken(db, pOld);
116771  if( !zOld ) goto exit_rename_column;
116772  for(iCol=0; iCol<pTab->nCol; iCol++){
116773    if( 0==sqlite3StrICmp(pTab->aCol[iCol].zCnName, zOld) ) break;
116774  }
116775  if( iCol==pTab->nCol ){
116776    sqlite3ErrorMsg(pParse, "no such column: \"%T\"", pOld);
116777    goto exit_rename_column;
116778  }
116779
116780  /* Ensure the schema contains no double-quoted strings */
116781  renameTestSchema(pParse, zDb, iSchema==1, "", 0);
116782  renameFixQuotes(pParse, zDb, iSchema==1);
116783
116784  /* Do the rename operation using a recursive UPDATE statement that
116785  ** uses the sqlite_rename_column() SQL function to compute the new
116786  ** CREATE statement text for the sqlite_schema table.
116787  */
116788  sqlite3MayAbort(pParse);
116789  zNew = sqlite3NameFromToken(db, pNew);
116790  if( !zNew ) goto exit_rename_column;
116791  assert( pNew->n>0 );
116792  bQuote = sqlite3Isquote(pNew->z[0]);
116793  sqlite3NestedParse(pParse,
116794      "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
116795      "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
116796      "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
116797      " AND (type != 'index' OR tbl_name = %Q)",
116798      zDb,
116799      zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
116800      pTab->zName
116801  );
116802
116803  sqlite3NestedParse(pParse,
116804      "UPDATE temp." LEGACY_SCHEMA_TABLE " SET "
116805      "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
116806      "WHERE type IN ('trigger', 'view')",
116807      zDb, pTab->zName, iCol, zNew, bQuote
116808  );
116809
116810  /* Drop and reload the database schema. */
116811  renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename);
116812  renameTestSchema(pParse, zDb, iSchema==1, "after rename", 1);
116813
116814 exit_rename_column:
116815  sqlite3SrcListDelete(db, pSrc);
116816  sqlite3DbFree(db, zOld);
116817  sqlite3DbFree(db, zNew);
116818  return;
116819}
116820
116821/*
116822** Each RenameToken object maps an element of the parse tree into
116823** the token that generated that element.  The parse tree element
116824** might be one of:
116825**
116826**     *  A pointer to an Expr that represents an ID
116827**     *  The name of a table column in Column.zName
116828**
116829** A list of RenameToken objects can be constructed during parsing.
116830** Each new object is created by sqlite3RenameTokenMap().
116831** As the parse tree is transformed, the sqlite3RenameTokenRemap()
116832** routine is used to keep the mapping current.
116833**
116834** After the parse finishes, renameTokenFind() routine can be used
116835** to look up the actual token value that created some element in
116836** the parse tree.
116837*/
116838struct RenameToken {
116839  const void *p;         /* Parse tree element created by token t */
116840  Token t;               /* The token that created parse tree element p */
116841  RenameToken *pNext;    /* Next is a list of all RenameToken objects */
116842};
116843
116844/*
116845** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
116846** down into the Walker.
116847*/
116848typedef struct RenameCtx RenameCtx;
116849struct RenameCtx {
116850  RenameToken *pList;             /* List of tokens to overwrite */
116851  int nList;                      /* Number of tokens in pList */
116852  int iCol;                       /* Index of column being renamed */
116853  Table *pTab;                    /* Table being ALTERed */
116854  const char *zOld;               /* Old column name */
116855};
116856
116857#ifdef SQLITE_DEBUG
116858/*
116859** This function is only for debugging. It performs two tasks:
116860**
116861**   1. Checks that pointer pPtr does not already appear in the
116862**      rename-token list.
116863**
116864**   2. Dereferences each pointer in the rename-token list.
116865**
116866** The second is most effective when debugging under valgrind or
116867** address-sanitizer or similar. If any of these pointers no longer
116868** point to valid objects, an exception is raised by the memory-checking
116869** tool.
116870**
116871** The point of this is to prevent comparisons of invalid pointer values.
116872** Even though this always seems to work, it is undefined according to the
116873** C standard. Example of undefined comparison:
116874**
116875**     sqlite3_free(x);
116876**     if( x==y ) ...
116877**
116878** Technically, as x no longer points into a valid object or to the byte
116879** following a valid object, it may not be used in comparison operations.
116880*/
116881static void renameTokenCheckAll(Parse *pParse, const void *pPtr){
116882  assert( pParse==pParse->db->pParse );
116883  assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
116884  if( pParse->nErr==0 ){
116885    const RenameToken *p;
116886    u32 i = 1;
116887    for(p=pParse->pRename; p; p=p->pNext){
116888      if( p->p ){
116889        assert( p->p!=pPtr );
116890        i += *(u8*)(p->p) | 1;
116891      }
116892    }
116893    assert( i>0 );
116894  }
116895}
116896#else
116897# define renameTokenCheckAll(x,y)
116898#endif
116899
116900/*
116901** Remember that the parser tree element pPtr was created using
116902** the token pToken.
116903**
116904** In other words, construct a new RenameToken object and add it
116905** to the list of RenameToken objects currently being built up
116906** in pParse->pRename.
116907**
116908** The pPtr argument is returned so that this routine can be used
116909** with tail recursion in tokenExpr() routine, for a small performance
116910** improvement.
116911*/
116912SQLITE_PRIVATE const void *sqlite3RenameTokenMap(
116913  Parse *pParse,
116914  const void *pPtr,
116915  const Token *pToken
116916){
116917  RenameToken *pNew;
116918  assert( pPtr || pParse->db->mallocFailed );
116919  renameTokenCheckAll(pParse, pPtr);
116920  if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
116921    pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
116922    if( pNew ){
116923      pNew->p = pPtr;
116924      pNew->t = *pToken;
116925      pNew->pNext = pParse->pRename;
116926      pParse->pRename = pNew;
116927    }
116928  }
116929
116930  return pPtr;
116931}
116932
116933/*
116934** It is assumed that there is already a RenameToken object associated
116935** with parse tree element pFrom. This function remaps the associated token
116936** to parse tree element pTo.
116937*/
116938SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse *pParse, const void *pTo, const void *pFrom){
116939  RenameToken *p;
116940  renameTokenCheckAll(pParse, pTo);
116941  for(p=pParse->pRename; p; p=p->pNext){
116942    if( p->p==pFrom ){
116943      p->p = pTo;
116944      break;
116945    }
116946  }
116947}
116948
116949/*
116950** Walker callback used by sqlite3RenameExprUnmap().
116951*/
116952static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
116953  Parse *pParse = pWalker->pParse;
116954  sqlite3RenameTokenRemap(pParse, 0, (const void*)pExpr);
116955  if( ExprUseYTab(pExpr) ){
116956    sqlite3RenameTokenRemap(pParse, 0, (const void*)&pExpr->y.pTab);
116957  }
116958  return WRC_Continue;
116959}
116960
116961/*
116962** Iterate through the Select objects that are part of WITH clauses attached
116963** to select statement pSelect.
116964*/
116965static void renameWalkWith(Walker *pWalker, Select *pSelect){
116966  With *pWith = pSelect->pWith;
116967  if( pWith ){
116968    Parse *pParse = pWalker->pParse;
116969    int i;
116970    With *pCopy = 0;
116971    assert( pWith->nCte>0 );
116972    if( (pWith->a[0].pSelect->selFlags & SF_Expanded)==0 ){
116973      /* Push a copy of the With object onto the with-stack. We use a copy
116974      ** here as the original will be expanded and resolved (flags SF_Expanded
116975      ** and SF_Resolved) below. And the parser code that uses the with-stack
116976      ** fails if the Select objects on it have already been expanded and
116977      ** resolved.  */
116978      pCopy = sqlite3WithDup(pParse->db, pWith);
116979      pCopy = sqlite3WithPush(pParse, pCopy, 1);
116980    }
116981    for(i=0; i<pWith->nCte; i++){
116982      Select *p = pWith->a[i].pSelect;
116983      NameContext sNC;
116984      memset(&sNC, 0, sizeof(sNC));
116985      sNC.pParse = pParse;
116986      if( pCopy ) sqlite3SelectPrep(sNC.pParse, p, &sNC);
116987      if( sNC.pParse->db->mallocFailed ) return;
116988      sqlite3WalkSelect(pWalker, p);
116989      sqlite3RenameExprlistUnmap(pParse, pWith->a[i].pCols);
116990    }
116991    if( pCopy && pParse->pWith==pCopy ){
116992      pParse->pWith = pCopy->pOuter;
116993    }
116994  }
116995}
116996
116997/*
116998** Unmap all tokens in the IdList object passed as the second argument.
116999*/
117000static void unmapColumnIdlistNames(
117001  Parse *pParse,
117002  const IdList *pIdList
117003){
117004  int ii;
117005  assert( pIdList!=0 );
117006  for(ii=0; ii<pIdList->nId; ii++){
117007    sqlite3RenameTokenRemap(pParse, 0, (const void*)pIdList->a[ii].zName);
117008  }
117009}
117010
117011/*
117012** Walker callback used by sqlite3RenameExprUnmap().
117013*/
117014static int renameUnmapSelectCb(Walker *pWalker, Select *p){
117015  Parse *pParse = pWalker->pParse;
117016  int i;
117017  if( pParse->nErr ) return WRC_Abort;
117018  testcase( p->selFlags & SF_View );
117019  testcase( p->selFlags & SF_CopyCte );
117020  if( p->selFlags & (SF_View|SF_CopyCte) ){
117021    return WRC_Prune;
117022  }
117023  if( ALWAYS(p->pEList) ){
117024    ExprList *pList = p->pEList;
117025    for(i=0; i<pList->nExpr; i++){
117026      if( pList->a[i].zEName && pList->a[i].fg.eEName==ENAME_NAME ){
117027        sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
117028      }
117029    }
117030  }
117031  if( ALWAYS(p->pSrc) ){  /* Every Select as a SrcList, even if it is empty */
117032    SrcList *pSrc = p->pSrc;
117033    for(i=0; i<pSrc->nSrc; i++){
117034      sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
117035      if( pSrc->a[i].fg.isUsing==0 ){
117036        sqlite3WalkExpr(pWalker, pSrc->a[i].u3.pOn);
117037      }else{
117038        unmapColumnIdlistNames(pParse, pSrc->a[i].u3.pUsing);
117039      }
117040    }
117041  }
117042
117043  renameWalkWith(pWalker, p);
117044  return WRC_Continue;
117045}
117046
117047/*
117048** Remove all nodes that are part of expression pExpr from the rename list.
117049*/
117050SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
117051  u8 eMode = pParse->eParseMode;
117052  Walker sWalker;
117053  memset(&sWalker, 0, sizeof(Walker));
117054  sWalker.pParse = pParse;
117055  sWalker.xExprCallback = renameUnmapExprCb;
117056  sWalker.xSelectCallback = renameUnmapSelectCb;
117057  pParse->eParseMode = PARSE_MODE_UNMAP;
117058  sqlite3WalkExpr(&sWalker, pExpr);
117059  pParse->eParseMode = eMode;
117060}
117061
117062/*
117063** Remove all nodes that are part of expression-list pEList from the
117064** rename list.
117065*/
117066SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
117067  if( pEList ){
117068    int i;
117069    Walker sWalker;
117070    memset(&sWalker, 0, sizeof(Walker));
117071    sWalker.pParse = pParse;
117072    sWalker.xExprCallback = renameUnmapExprCb;
117073    sqlite3WalkExprList(&sWalker, pEList);
117074    for(i=0; i<pEList->nExpr; i++){
117075      if( ALWAYS(pEList->a[i].fg.eEName==ENAME_NAME) ){
117076        sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
117077      }
117078    }
117079  }
117080}
117081
117082/*
117083** Free the list of RenameToken objects given in the second argument
117084*/
117085static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
117086  RenameToken *pNext;
117087  RenameToken *p;
117088  for(p=pToken; p; p=pNext){
117089    pNext = p->pNext;
117090    sqlite3DbFree(db, p);
117091  }
117092}
117093
117094/*
117095** Search the Parse object passed as the first argument for a RenameToken
117096** object associated with parse tree element pPtr. If found, return a pointer
117097** to it. Otherwise, return NULL.
117098**
117099** If the second argument passed to this function is not NULL and a matching
117100** RenameToken object is found, remove it from the Parse object and add it to
117101** the list maintained by the RenameCtx object.
117102*/
117103static RenameToken *renameTokenFind(
117104  Parse *pParse,
117105  struct RenameCtx *pCtx,
117106  const void *pPtr
117107){
117108  RenameToken **pp;
117109  if( NEVER(pPtr==0) ){
117110    return 0;
117111  }
117112  for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
117113    if( (*pp)->p==pPtr ){
117114      RenameToken *pToken = *pp;
117115      if( pCtx ){
117116        *pp = pToken->pNext;
117117        pToken->pNext = pCtx->pList;
117118        pCtx->pList = pToken;
117119        pCtx->nList++;
117120      }
117121      return pToken;
117122    }
117123  }
117124  return 0;
117125}
117126
117127/*
117128** This is a Walker select callback. It does nothing. It is only required
117129** because without a dummy callback, sqlite3WalkExpr() and similar do not
117130** descend into sub-select statements.
117131*/
117132static int renameColumnSelectCb(Walker *pWalker, Select *p){
117133  if( p->selFlags & (SF_View|SF_CopyCte) ){
117134    testcase( p->selFlags & SF_View );
117135    testcase( p->selFlags & SF_CopyCte );
117136    return WRC_Prune;
117137  }
117138  renameWalkWith(pWalker, p);
117139  return WRC_Continue;
117140}
117141
117142/*
117143** This is a Walker expression callback.
117144**
117145** For every TK_COLUMN node in the expression tree, search to see
117146** if the column being references is the column being renamed by an
117147** ALTER TABLE statement.  If it is, then attach its associated
117148** RenameToken object to the list of RenameToken objects being
117149** constructed in RenameCtx object at pWalker->u.pRename.
117150*/
117151static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
117152  RenameCtx *p = pWalker->u.pRename;
117153  if( pExpr->op==TK_TRIGGER
117154   && pExpr->iColumn==p->iCol
117155   && pWalker->pParse->pTriggerTab==p->pTab
117156  ){
117157    renameTokenFind(pWalker->pParse, p, (void*)pExpr);
117158  }else if( pExpr->op==TK_COLUMN
117159   && pExpr->iColumn==p->iCol
117160   && ALWAYS(ExprUseYTab(pExpr))
117161   && p->pTab==pExpr->y.pTab
117162  ){
117163    renameTokenFind(pWalker->pParse, p, (void*)pExpr);
117164  }
117165  return WRC_Continue;
117166}
117167
117168/*
117169** The RenameCtx contains a list of tokens that reference a column that
117170** is being renamed by an ALTER TABLE statement.  Return the "last"
117171** RenameToken in the RenameCtx and remove that RenameToken from the
117172** RenameContext.  "Last" means the last RenameToken encountered when
117173** the input SQL is parsed from left to right.  Repeated calls to this routine
117174** return all column name tokens in the order that they are encountered
117175** in the SQL statement.
117176*/
117177static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
117178  RenameToken *pBest = pCtx->pList;
117179  RenameToken *pToken;
117180  RenameToken **pp;
117181
117182  for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
117183    if( pToken->t.z>pBest->t.z ) pBest = pToken;
117184  }
117185  for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
117186  *pp = pBest->pNext;
117187
117188  return pBest;
117189}
117190
117191/*
117192** An error occurred while parsing or otherwise processing a database
117193** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
117194** ALTER TABLE RENAME COLUMN program. The error message emitted by the
117195** sub-routine is currently stored in pParse->zErrMsg. This function
117196** adds context to the error message and then stores it in pCtx.
117197*/
117198static void renameColumnParseError(
117199  sqlite3_context *pCtx,
117200  const char *zWhen,
117201  sqlite3_value *pType,
117202  sqlite3_value *pObject,
117203  Parse *pParse
117204){
117205  const char *zT = (const char*)sqlite3_value_text(pType);
117206  const char *zN = (const char*)sqlite3_value_text(pObject);
117207  char *zErr;
117208
117209  zErr = sqlite3MPrintf(pParse->db, "error in %s %s%s%s: %s",
117210      zT, zN, (zWhen[0] ? " " : ""), zWhen,
117211      pParse->zErrMsg
117212  );
117213  sqlite3_result_error(pCtx, zErr, -1);
117214  sqlite3DbFree(pParse->db, zErr);
117215}
117216
117217/*
117218** For each name in the the expression-list pEList (i.e. each
117219** pEList->a[i].zName) that matches the string in zOld, extract the
117220** corresponding rename-token from Parse object pParse and add it
117221** to the RenameCtx pCtx.
117222*/
117223static void renameColumnElistNames(
117224  Parse *pParse,
117225  RenameCtx *pCtx,
117226  const ExprList *pEList,
117227  const char *zOld
117228){
117229  if( pEList ){
117230    int i;
117231    for(i=0; i<pEList->nExpr; i++){
117232      const char *zName = pEList->a[i].zEName;
117233      if( ALWAYS(pEList->a[i].fg.eEName==ENAME_NAME)
117234       && ALWAYS(zName!=0)
117235       && 0==sqlite3_stricmp(zName, zOld)
117236      ){
117237        renameTokenFind(pParse, pCtx, (const void*)zName);
117238      }
117239    }
117240  }
117241}
117242
117243/*
117244** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
117245** that matches the string in zOld, extract the corresponding rename-token
117246** from Parse object pParse and add it to the RenameCtx pCtx.
117247*/
117248static void renameColumnIdlistNames(
117249  Parse *pParse,
117250  RenameCtx *pCtx,
117251  const IdList *pIdList,
117252  const char *zOld
117253){
117254  if( pIdList ){
117255    int i;
117256    for(i=0; i<pIdList->nId; i++){
117257      const char *zName = pIdList->a[i].zName;
117258      if( 0==sqlite3_stricmp(zName, zOld) ){
117259        renameTokenFind(pParse, pCtx, (const void*)zName);
117260      }
117261    }
117262  }
117263}
117264
117265
117266/*
117267** Parse the SQL statement zSql using Parse object (*p). The Parse object
117268** is initialized by this function before it is used.
117269*/
117270static int renameParseSql(
117271  Parse *p,                       /* Memory to use for Parse object */
117272  const char *zDb,                /* Name of schema SQL belongs to */
117273  sqlite3 *db,                    /* Database handle */
117274  const char *zSql,               /* SQL to parse */
117275  int bTemp                       /* True if SQL is from temp schema */
117276){
117277  int rc;
117278
117279  sqlite3ParseObjectInit(p, db);
117280  if( zSql==0 ){
117281    return SQLITE_NOMEM;
117282  }
117283  if( sqlite3StrNICmp(zSql,"CREATE ",7)!=0 ){
117284    return SQLITE_CORRUPT_BKPT;
117285  }
117286  db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
117287  p->eParseMode = PARSE_MODE_RENAME;
117288  p->db = db;
117289  p->nQueryLoop = 1;
117290  rc = sqlite3RunParser(p, zSql);
117291  if( db->mallocFailed ) rc = SQLITE_NOMEM;
117292  if( rc==SQLITE_OK
117293   && NEVER(p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0)
117294  ){
117295    rc = SQLITE_CORRUPT_BKPT;
117296  }
117297
117298#ifdef SQLITE_DEBUG
117299  /* Ensure that all mappings in the Parse.pRename list really do map to
117300  ** a part of the input string.  */
117301  if( rc==SQLITE_OK ){
117302    int nSql = sqlite3Strlen30(zSql);
117303    RenameToken *pToken;
117304    for(pToken=p->pRename; pToken; pToken=pToken->pNext){
117305      assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
117306    }
117307  }
117308#endif
117309
117310  db->init.iDb = 0;
117311  return rc;
117312}
117313
117314/*
117315** This function edits SQL statement zSql, replacing each token identified
117316** by the linked list pRename with the text of zNew. If argument bQuote is
117317** true, then zNew is always quoted first. If no error occurs, the result
117318** is loaded into context object pCtx as the result.
117319**
117320** Or, if an error occurs (i.e. an OOM condition), an error is left in
117321** pCtx and an SQLite error code returned.
117322*/
117323static int renameEditSql(
117324  sqlite3_context *pCtx,          /* Return result here */
117325  RenameCtx *pRename,             /* Rename context */
117326  const char *zSql,               /* SQL statement to edit */
117327  const char *zNew,               /* New token text */
117328  int bQuote                      /* True to always quote token */
117329){
117330  i64 nNew = sqlite3Strlen30(zNew);
117331  i64 nSql = sqlite3Strlen30(zSql);
117332  sqlite3 *db = sqlite3_context_db_handle(pCtx);
117333  int rc = SQLITE_OK;
117334  char *zQuot = 0;
117335  char *zOut;
117336  i64 nQuot = 0;
117337  char *zBuf1 = 0;
117338  char *zBuf2 = 0;
117339
117340  if( zNew ){
117341    /* Set zQuot to point to a buffer containing a quoted copy of the
117342    ** identifier zNew. If the corresponding identifier in the original
117343    ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
117344    ** point to zQuot so that all substitutions are made using the
117345    ** quoted version of the new column name.  */
117346    zQuot = sqlite3MPrintf(db, "\"%w\" ", zNew);
117347    if( zQuot==0 ){
117348      return SQLITE_NOMEM;
117349    }else{
117350      nQuot = sqlite3Strlen30(zQuot)-1;
117351    }
117352
117353    assert( nQuot>=nNew );
117354    zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
117355  }else{
117356    zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3);
117357    if( zOut ){
117358      zBuf1 = &zOut[nSql*2+1];
117359      zBuf2 = &zOut[nSql*4+2];
117360    }
117361  }
117362
117363  /* At this point pRename->pList contains a list of RenameToken objects
117364  ** corresponding to all tokens in the input SQL that must be replaced
117365  ** with the new column name, or with single-quoted versions of themselves.
117366  ** All that remains is to construct and return the edited SQL string. */
117367  if( zOut ){
117368    int nOut = nSql;
117369    memcpy(zOut, zSql, nSql);
117370    while( pRename->pList ){
117371      int iOff;                   /* Offset of token to replace in zOut */
117372      u32 nReplace;
117373      const char *zReplace;
117374      RenameToken *pBest = renameColumnTokenNext(pRename);
117375
117376      if( zNew ){
117377        if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){
117378          nReplace = nNew;
117379          zReplace = zNew;
117380        }else{
117381          nReplace = nQuot;
117382          zReplace = zQuot;
117383          if( pBest->t.z[pBest->t.n]=='"' ) nReplace++;
117384        }
117385      }else{
117386        /* Dequote the double-quoted token. Then requote it again, this time
117387        ** using single quotes. If the character immediately following the
117388        ** original token within the input SQL was a single quote ('), then
117389        ** add another space after the new, single-quoted version of the
117390        ** token. This is so that (SELECT "string"'alias') maps to
117391        ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias').  */
117392        memcpy(zBuf1, pBest->t.z, pBest->t.n);
117393        zBuf1[pBest->t.n] = 0;
117394        sqlite3Dequote(zBuf1);
117395        sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1,
117396            pBest->t.z[pBest->t.n]=='\'' ? " " : ""
117397        );
117398        zReplace = zBuf2;
117399        nReplace = sqlite3Strlen30(zReplace);
117400      }
117401
117402      iOff = pBest->t.z - zSql;
117403      if( pBest->t.n!=nReplace ){
117404        memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
117405            nOut - (iOff + pBest->t.n)
117406        );
117407        nOut += nReplace - pBest->t.n;
117408        zOut[nOut] = '\0';
117409      }
117410      memcpy(&zOut[iOff], zReplace, nReplace);
117411      sqlite3DbFree(db, pBest);
117412    }
117413
117414    sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
117415    sqlite3DbFree(db, zOut);
117416  }else{
117417    rc = SQLITE_NOMEM;
117418  }
117419
117420  sqlite3_free(zQuot);
117421  return rc;
117422}
117423
117424/*
117425** Set all pEList->a[].fg.eEName fields in the expression-list to val.
117426*/
117427static void renameSetENames(ExprList *pEList, int val){
117428  if( pEList ){
117429    int i;
117430    for(i=0; i<pEList->nExpr; i++){
117431      assert( val==ENAME_NAME || pEList->a[i].fg.eEName==ENAME_NAME );
117432      pEList->a[i].fg.eEName = val;
117433    }
117434  }
117435}
117436
117437/*
117438** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
117439** it was read from the schema of database zDb. Return SQLITE_OK if
117440** successful. Otherwise, return an SQLite error code and leave an error
117441** message in the Parse object.
117442*/
117443static int renameResolveTrigger(Parse *pParse){
117444  sqlite3 *db = pParse->db;
117445  Trigger *pNew = pParse->pNewTrigger;
117446  TriggerStep *pStep;
117447  NameContext sNC;
117448  int rc = SQLITE_OK;
117449
117450  memset(&sNC, 0, sizeof(sNC));
117451  sNC.pParse = pParse;
117452  assert( pNew->pTabSchema );
117453  pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
117454      db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
117455  );
117456  pParse->eTriggerOp = pNew->op;
117457  /* ALWAYS() because if the table of the trigger does not exist, the
117458  ** error would have been hit before this point */
117459  if( ALWAYS(pParse->pTriggerTab) ){
117460    rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
117461  }
117462
117463  /* Resolve symbols in WHEN clause */
117464  if( rc==SQLITE_OK && pNew->pWhen ){
117465    rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
117466  }
117467
117468  for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
117469    if( pStep->pSelect ){
117470      sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
117471      if( pParse->nErr ) rc = pParse->rc;
117472    }
117473    if( rc==SQLITE_OK && pStep->zTarget ){
117474      SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
117475      if( pSrc ){
117476        Select *pSel = sqlite3SelectNew(
117477            pParse, pStep->pExprList, pSrc, 0, 0, 0, 0, 0, 0
117478        );
117479        if( pSel==0 ){
117480          pStep->pExprList = 0;
117481          pSrc = 0;
117482          rc = SQLITE_NOMEM;
117483        }else{
117484          /* pStep->pExprList contains an expression-list used for an UPDATE
117485          ** statement. So the a[].zEName values are the RHS of the
117486          ** "<col> = <expr>" clauses of the UPDATE statement. So, before
117487          ** running SelectPrep(), change all the eEName values in
117488          ** pStep->pExprList to ENAME_SPAN (from their current value of
117489          ** ENAME_NAME). This is to prevent any ids in ON() clauses that are
117490          ** part of pSrc from being incorrectly resolved against the
117491          ** a[].zEName values as if they were column aliases.  */
117492          renameSetENames(pStep->pExprList, ENAME_SPAN);
117493          sqlite3SelectPrep(pParse, pSel, 0);
117494          renameSetENames(pStep->pExprList, ENAME_NAME);
117495          rc = pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
117496          assert( pStep->pExprList==0 || pStep->pExprList==pSel->pEList );
117497          assert( pSrc==pSel->pSrc );
117498          if( pStep->pExprList ) pSel->pEList = 0;
117499          pSel->pSrc = 0;
117500          sqlite3SelectDelete(db, pSel);
117501        }
117502        if( pStep->pFrom ){
117503          int i;
117504          for(i=0; i<pStep->pFrom->nSrc && rc==SQLITE_OK; i++){
117505            SrcItem *p = &pStep->pFrom->a[i];
117506            if( p->pSelect ){
117507              sqlite3SelectPrep(pParse, p->pSelect, 0);
117508            }
117509          }
117510        }
117511
117512        if(  db->mallocFailed ){
117513          rc = SQLITE_NOMEM;
117514        }
117515        sNC.pSrcList = pSrc;
117516        if( rc==SQLITE_OK && pStep->pWhere ){
117517          rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
117518        }
117519        if( rc==SQLITE_OK ){
117520          rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
117521        }
117522        assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
117523        if( pStep->pUpsert && rc==SQLITE_OK ){
117524          Upsert *pUpsert = pStep->pUpsert;
117525          pUpsert->pUpsertSrc = pSrc;
117526          sNC.uNC.pUpsert = pUpsert;
117527          sNC.ncFlags = NC_UUpsert;
117528          rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
117529          if( rc==SQLITE_OK ){
117530            ExprList *pUpsertSet = pUpsert->pUpsertSet;
117531            rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
117532          }
117533          if( rc==SQLITE_OK ){
117534            rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
117535          }
117536          if( rc==SQLITE_OK ){
117537            rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
117538          }
117539          sNC.ncFlags = 0;
117540        }
117541        sNC.pSrcList = 0;
117542        sqlite3SrcListDelete(db, pSrc);
117543      }else{
117544        rc = SQLITE_NOMEM;
117545      }
117546    }
117547  }
117548  return rc;
117549}
117550
117551/*
117552** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
117553** objects that are part of the trigger passed as the second argument.
117554*/
117555static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
117556  TriggerStep *pStep;
117557
117558  /* Find tokens to edit in WHEN clause */
117559  sqlite3WalkExpr(pWalker, pTrigger->pWhen);
117560
117561  /* Find tokens to edit in trigger steps */
117562  for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
117563    sqlite3WalkSelect(pWalker, pStep->pSelect);
117564    sqlite3WalkExpr(pWalker, pStep->pWhere);
117565    sqlite3WalkExprList(pWalker, pStep->pExprList);
117566    if( pStep->pUpsert ){
117567      Upsert *pUpsert = pStep->pUpsert;
117568      sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
117569      sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
117570      sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
117571      sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
117572    }
117573    if( pStep->pFrom ){
117574      int i;
117575      for(i=0; i<pStep->pFrom->nSrc; i++){
117576        sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
117577      }
117578    }
117579  }
117580}
117581
117582/*
117583** Free the contents of Parse object (*pParse). Do not free the memory
117584** occupied by the Parse object itself.
117585*/
117586static void renameParseCleanup(Parse *pParse){
117587  sqlite3 *db = pParse->db;
117588  Index *pIdx;
117589  if( pParse->pVdbe ){
117590    sqlite3VdbeFinalize(pParse->pVdbe);
117591  }
117592  sqlite3DeleteTable(db, pParse->pNewTable);
117593  while( (pIdx = pParse->pNewIndex)!=0 ){
117594    pParse->pNewIndex = pIdx->pNext;
117595    sqlite3FreeIndex(db, pIdx);
117596  }
117597  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
117598  sqlite3DbFree(db, pParse->zErrMsg);
117599  renameTokenFree(db, pParse->pRename);
117600  sqlite3ParseObjectReset(pParse);
117601}
117602
117603/*
117604** SQL function:
117605**
117606**     sqlite_rename_column(SQL,TYPE,OBJ,DB,TABLE,COL,NEWNAME,QUOTE,TEMP)
117607**
117608**   0. zSql:     SQL statement to rewrite
117609**   1. type:     Type of object ("table", "view" etc.)
117610**   2. object:   Name of object
117611**   3. Database: Database name (e.g. "main")
117612**   4. Table:    Table name
117613**   5. iCol:     Index of column to rename
117614**   6. zNew:     New column name
117615**   7. bQuote:   Non-zero if the new column name should be quoted.
117616**   8. bTemp:    True if zSql comes from temp schema
117617**
117618** Do a column rename operation on the CREATE statement given in zSql.
117619** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
117620** into zNew.  The name should be quoted if bQuote is true.
117621**
117622** This function is used internally by the ALTER TABLE RENAME COLUMN command.
117623** It is only accessible to SQL created using sqlite3NestedParse().  It is
117624** not reachable from ordinary SQL passed into sqlite3_prepare() unless the
117625** SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test setting is enabled.
117626*/
117627static void renameColumnFunc(
117628  sqlite3_context *context,
117629  int NotUsed,
117630  sqlite3_value **argv
117631){
117632  sqlite3 *db = sqlite3_context_db_handle(context);
117633  RenameCtx sCtx;
117634  const char *zSql = (const char*)sqlite3_value_text(argv[0]);
117635  const char *zDb = (const char*)sqlite3_value_text(argv[3]);
117636  const char *zTable = (const char*)sqlite3_value_text(argv[4]);
117637  int iCol = sqlite3_value_int(argv[5]);
117638  const char *zNew = (const char*)sqlite3_value_text(argv[6]);
117639  int bQuote = sqlite3_value_int(argv[7]);
117640  int bTemp = sqlite3_value_int(argv[8]);
117641  const char *zOld;
117642  int rc;
117643  Parse sParse;
117644  Walker sWalker;
117645  Index *pIdx;
117646  int i;
117647  Table *pTab;
117648#ifndef SQLITE_OMIT_AUTHORIZATION
117649  sqlite3_xauth xAuth = db->xAuth;
117650#endif
117651
117652  UNUSED_PARAMETER(NotUsed);
117653  if( zSql==0 ) return;
117654  if( zTable==0 ) return;
117655  if( zNew==0 ) return;
117656  if( iCol<0 ) return;
117657  sqlite3BtreeEnterAll(db);
117658  pTab = sqlite3FindTable(db, zTable, zDb);
117659  if( pTab==0 || iCol>=pTab->nCol ){
117660    sqlite3BtreeLeaveAll(db);
117661    return;
117662  }
117663  zOld = pTab->aCol[iCol].zCnName;
117664  memset(&sCtx, 0, sizeof(sCtx));
117665  sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
117666
117667#ifndef SQLITE_OMIT_AUTHORIZATION
117668  db->xAuth = 0;
117669#endif
117670  rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
117671
117672  /* Find tokens that need to be replaced. */
117673  memset(&sWalker, 0, sizeof(Walker));
117674  sWalker.pParse = &sParse;
117675  sWalker.xExprCallback = renameColumnExprCb;
117676  sWalker.xSelectCallback = renameColumnSelectCb;
117677  sWalker.u.pRename = &sCtx;
117678
117679  sCtx.pTab = pTab;
117680  if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
117681  if( sParse.pNewTable ){
117682    if( IsView(sParse.pNewTable) ){
117683      Select *pSelect = sParse.pNewTable->u.view.pSelect;
117684      pSelect->selFlags &= ~SF_View;
117685      sParse.rc = SQLITE_OK;
117686      sqlite3SelectPrep(&sParse, pSelect, 0);
117687      rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
117688      if( rc==SQLITE_OK ){
117689        sqlite3WalkSelect(&sWalker, pSelect);
117690      }
117691      if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
117692    }else if( IsOrdinaryTable(sParse.pNewTable) ){
117693      /* A regular table */
117694      int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
117695      FKey *pFKey;
117696      sCtx.pTab = sParse.pNewTable;
117697      if( bFKOnly==0 ){
117698        if( iCol<sParse.pNewTable->nCol ){
117699          renameTokenFind(
117700              &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zCnName
117701          );
117702        }
117703        if( sCtx.iCol<0 ){
117704          renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
117705        }
117706        sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
117707        for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
117708          sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
117709        }
117710        for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
117711          sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
117712        }
117713#ifndef SQLITE_OMIT_GENERATED_COLUMNS
117714        for(i=0; i<sParse.pNewTable->nCol; i++){
117715          Expr *pExpr = sqlite3ColumnExpr(sParse.pNewTable,
117716                                                  &sParse.pNewTable->aCol[i]);
117717          sqlite3WalkExpr(&sWalker, pExpr);
117718        }
117719#endif
117720      }
117721
117722      assert( IsOrdinaryTable(sParse.pNewTable) );
117723      for(pFKey=sParse.pNewTable->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
117724        for(i=0; i<pFKey->nCol; i++){
117725          if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
117726            renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
117727          }
117728          if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
117729           && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
117730          ){
117731            renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
117732          }
117733        }
117734      }
117735    }
117736  }else if( sParse.pNewIndex ){
117737    sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
117738    sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
117739  }else{
117740    /* A trigger */
117741    TriggerStep *pStep;
117742    rc = renameResolveTrigger(&sParse);
117743    if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
117744
117745    for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
117746      if( pStep->zTarget ){
117747        Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
117748        if( pTarget==pTab ){
117749          if( pStep->pUpsert ){
117750            ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
117751            renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
117752          }
117753          renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
117754          renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
117755        }
117756      }
117757    }
117758
117759
117760    /* Find tokens to edit in UPDATE OF clause */
117761    if( sParse.pTriggerTab==pTab ){
117762      renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
117763    }
117764
117765    /* Find tokens to edit in various expressions and selects */
117766    renameWalkTrigger(&sWalker, sParse.pNewTrigger);
117767  }
117768
117769  assert( rc==SQLITE_OK );
117770  rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
117771
117772renameColumnFunc_done:
117773  if( rc!=SQLITE_OK ){
117774    if( rc==SQLITE_ERROR && sqlite3WritableSchema(db) ){
117775      sqlite3_result_value(context, argv[0]);
117776    }else if( sParse.zErrMsg ){
117777      renameColumnParseError(context, "", argv[1], argv[2], &sParse);
117778    }else{
117779      sqlite3_result_error_code(context, rc);
117780    }
117781  }
117782
117783  renameParseCleanup(&sParse);
117784  renameTokenFree(db, sCtx.pList);
117785#ifndef SQLITE_OMIT_AUTHORIZATION
117786  db->xAuth = xAuth;
117787#endif
117788  sqlite3BtreeLeaveAll(db);
117789}
117790
117791/*
117792** Walker expression callback used by "RENAME TABLE".
117793*/
117794static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
117795  RenameCtx *p = pWalker->u.pRename;
117796  if( pExpr->op==TK_COLUMN
117797   && ALWAYS(ExprUseYTab(pExpr))
117798   && p->pTab==pExpr->y.pTab
117799  ){
117800    renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
117801  }
117802  return WRC_Continue;
117803}
117804
117805/*
117806** Walker select callback used by "RENAME TABLE".
117807*/
117808static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
117809  int i;
117810  RenameCtx *p = pWalker->u.pRename;
117811  SrcList *pSrc = pSelect->pSrc;
117812  if( pSelect->selFlags & (SF_View|SF_CopyCte) ){
117813    testcase( pSelect->selFlags & SF_View );
117814    testcase( pSelect->selFlags & SF_CopyCte );
117815    return WRC_Prune;
117816  }
117817  if( NEVER(pSrc==0) ){
117818    assert( pWalker->pParse->db->mallocFailed );
117819    return WRC_Abort;
117820  }
117821  for(i=0; i<pSrc->nSrc; i++){
117822    SrcItem *pItem = &pSrc->a[i];
117823    if( pItem->pTab==p->pTab ){
117824      renameTokenFind(pWalker->pParse, p, pItem->zName);
117825    }
117826  }
117827  renameWalkWith(pWalker, pSelect);
117828
117829  return WRC_Continue;
117830}
117831
117832
117833/*
117834** This C function implements an SQL user function that is used by SQL code
117835** generated by the ALTER TABLE ... RENAME command to modify the definition
117836** of any foreign key constraints that use the table being renamed as the
117837** parent table. It is passed three arguments:
117838**
117839**   0: The database containing the table being renamed.
117840**   1. type:     Type of object ("table", "view" etc.)
117841**   2. object:   Name of object
117842**   3: The complete text of the schema statement being modified,
117843**   4: The old name of the table being renamed, and
117844**   5: The new name of the table being renamed.
117845**   6: True if the schema statement comes from the temp db.
117846**
117847** It returns the new schema statement. For example:
117848**
117849** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
117850**       -> 'CREATE TABLE t1(a REFERENCES t3)'
117851*/
117852static void renameTableFunc(
117853  sqlite3_context *context,
117854  int NotUsed,
117855  sqlite3_value **argv
117856){
117857  sqlite3 *db = sqlite3_context_db_handle(context);
117858  const char *zDb = (const char*)sqlite3_value_text(argv[0]);
117859  const char *zInput = (const char*)sqlite3_value_text(argv[3]);
117860  const char *zOld = (const char*)sqlite3_value_text(argv[4]);
117861  const char *zNew = (const char*)sqlite3_value_text(argv[5]);
117862  int bTemp = sqlite3_value_int(argv[6]);
117863  UNUSED_PARAMETER(NotUsed);
117864
117865  if( zInput && zOld && zNew ){
117866    Parse sParse;
117867    int rc;
117868    int bQuote = 1;
117869    RenameCtx sCtx;
117870    Walker sWalker;
117871
117872#ifndef SQLITE_OMIT_AUTHORIZATION
117873    sqlite3_xauth xAuth = db->xAuth;
117874    db->xAuth = 0;
117875#endif
117876
117877    sqlite3BtreeEnterAll(db);
117878
117879    memset(&sCtx, 0, sizeof(RenameCtx));
117880    sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
117881    memset(&sWalker, 0, sizeof(Walker));
117882    sWalker.pParse = &sParse;
117883    sWalker.xExprCallback = renameTableExprCb;
117884    sWalker.xSelectCallback = renameTableSelectCb;
117885    sWalker.u.pRename = &sCtx;
117886
117887    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
117888
117889    if( rc==SQLITE_OK ){
117890      int isLegacy = (db->flags & SQLITE_LegacyAlter);
117891      if( sParse.pNewTable ){
117892        Table *pTab = sParse.pNewTable;
117893
117894        if( IsView(pTab) ){
117895          if( isLegacy==0 ){
117896            Select *pSelect = pTab->u.view.pSelect;
117897            NameContext sNC;
117898            memset(&sNC, 0, sizeof(sNC));
117899            sNC.pParse = &sParse;
117900
117901            assert( pSelect->selFlags & SF_View );
117902            pSelect->selFlags &= ~SF_View;
117903            sqlite3SelectPrep(&sParse, pTab->u.view.pSelect, &sNC);
117904            if( sParse.nErr ){
117905              rc = sParse.rc;
117906            }else{
117907              sqlite3WalkSelect(&sWalker, pTab->u.view.pSelect);
117908            }
117909          }
117910        }else{
117911          /* Modify any FK definitions to point to the new table. */
117912#ifndef SQLITE_OMIT_FOREIGN_KEY
117913          if( (isLegacy==0 || (db->flags & SQLITE_ForeignKeys))
117914           && !IsVirtual(pTab)
117915          ){
117916            FKey *pFKey;
117917            assert( IsOrdinaryTable(pTab) );
117918            for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
117919              if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
117920                renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
117921              }
117922            }
117923          }
117924#endif
117925
117926          /* If this is the table being altered, fix any table refs in CHECK
117927          ** expressions. Also update the name that appears right after the
117928          ** "CREATE [VIRTUAL] TABLE" bit. */
117929          if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
117930            sCtx.pTab = pTab;
117931            if( isLegacy==0 ){
117932              sqlite3WalkExprList(&sWalker, pTab->pCheck);
117933            }
117934            renameTokenFind(&sParse, &sCtx, pTab->zName);
117935          }
117936        }
117937      }
117938
117939      else if( sParse.pNewIndex ){
117940        renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
117941        if( isLegacy==0 ){
117942          sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
117943        }
117944      }
117945
117946#ifndef SQLITE_OMIT_TRIGGER
117947      else{
117948        Trigger *pTrigger = sParse.pNewTrigger;
117949        TriggerStep *pStep;
117950        if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
117951            && sCtx.pTab->pSchema==pTrigger->pTabSchema
117952          ){
117953          renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
117954        }
117955
117956        if( isLegacy==0 ){
117957          rc = renameResolveTrigger(&sParse);
117958          if( rc==SQLITE_OK ){
117959            renameWalkTrigger(&sWalker, pTrigger);
117960            for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
117961              if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
117962                renameTokenFind(&sParse, &sCtx, pStep->zTarget);
117963              }
117964              if( pStep->pFrom ){
117965                int i;
117966                for(i=0; i<pStep->pFrom->nSrc; i++){
117967                  SrcItem *pItem = &pStep->pFrom->a[i];
117968                  if( 0==sqlite3_stricmp(pItem->zName, zOld) ){
117969                    renameTokenFind(&sParse, &sCtx, pItem->zName);
117970                  }
117971                }
117972              }
117973            }
117974          }
117975        }
117976      }
117977#endif
117978    }
117979
117980    if( rc==SQLITE_OK ){
117981      rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
117982    }
117983    if( rc!=SQLITE_OK ){
117984      if( rc==SQLITE_ERROR && sqlite3WritableSchema(db) ){
117985        sqlite3_result_value(context, argv[3]);
117986      }else if( sParse.zErrMsg ){
117987        renameColumnParseError(context, "", argv[1], argv[2], &sParse);
117988      }else{
117989        sqlite3_result_error_code(context, rc);
117990      }
117991    }
117992
117993    renameParseCleanup(&sParse);
117994    renameTokenFree(db, sCtx.pList);
117995    sqlite3BtreeLeaveAll(db);
117996#ifndef SQLITE_OMIT_AUTHORIZATION
117997    db->xAuth = xAuth;
117998#endif
117999  }
118000
118001  return;
118002}
118003
118004static int renameQuotefixExprCb(Walker *pWalker, Expr *pExpr){
118005  if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
118006    renameTokenFind(pWalker->pParse, pWalker->u.pRename, (const void*)pExpr);
118007  }
118008  return WRC_Continue;
118009}
118010
118011/* SQL function: sqlite_rename_quotefix(DB,SQL)
118012**
118013** Rewrite the DDL statement "SQL" so that any string literals that use
118014** double-quotes use single quotes instead.
118015**
118016** Two arguments must be passed:
118017**
118018**   0: Database name ("main", "temp" etc.).
118019**   1: SQL statement to edit.
118020**
118021** The returned value is the modified SQL statement. For example, given
118022** the database schema:
118023**
118024**   CREATE TABLE t1(a, b, c);
118025**
118026**   SELECT sqlite_rename_quotefix('main',
118027**       'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
118028**   );
118029**
118030** returns the string:
118031**
118032**   CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
118033**
118034** If there is a error in the input SQL, then raise an error, except
118035** if PRAGMA writable_schema=ON, then just return the input string
118036** unmodified following an error.
118037*/
118038static void renameQuotefixFunc(
118039  sqlite3_context *context,
118040  int NotUsed,
118041  sqlite3_value **argv
118042){
118043  sqlite3 *db = sqlite3_context_db_handle(context);
118044  char const *zDb = (const char*)sqlite3_value_text(argv[0]);
118045  char const *zInput = (const char*)sqlite3_value_text(argv[1]);
118046
118047#ifndef SQLITE_OMIT_AUTHORIZATION
118048  sqlite3_xauth xAuth = db->xAuth;
118049  db->xAuth = 0;
118050#endif
118051
118052  sqlite3BtreeEnterAll(db);
118053
118054  UNUSED_PARAMETER(NotUsed);
118055  if( zDb && zInput ){
118056    int rc;
118057    Parse sParse;
118058    rc = renameParseSql(&sParse, zDb, db, zInput, 0);
118059
118060    if( rc==SQLITE_OK ){
118061      RenameCtx sCtx;
118062      Walker sWalker;
118063
118064      /* Walker to find tokens that need to be replaced. */
118065      memset(&sCtx, 0, sizeof(RenameCtx));
118066      memset(&sWalker, 0, sizeof(Walker));
118067      sWalker.pParse = &sParse;
118068      sWalker.xExprCallback = renameQuotefixExprCb;
118069      sWalker.xSelectCallback = renameColumnSelectCb;
118070      sWalker.u.pRename = &sCtx;
118071
118072      if( sParse.pNewTable ){
118073        if( IsView(sParse.pNewTable) ){
118074          Select *pSelect = sParse.pNewTable->u.view.pSelect;
118075          pSelect->selFlags &= ~SF_View;
118076          sParse.rc = SQLITE_OK;
118077          sqlite3SelectPrep(&sParse, pSelect, 0);
118078          rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
118079          if( rc==SQLITE_OK ){
118080            sqlite3WalkSelect(&sWalker, pSelect);
118081          }
118082        }else{
118083          int i;
118084          sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
118085#ifndef SQLITE_OMIT_GENERATED_COLUMNS
118086          for(i=0; i<sParse.pNewTable->nCol; i++){
118087            sqlite3WalkExpr(&sWalker,
118088               sqlite3ColumnExpr(sParse.pNewTable,
118089                                         &sParse.pNewTable->aCol[i]));
118090          }
118091#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
118092        }
118093      }else if( sParse.pNewIndex ){
118094        sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
118095        sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
118096      }else{
118097#ifndef SQLITE_OMIT_TRIGGER
118098        rc = renameResolveTrigger(&sParse);
118099        if( rc==SQLITE_OK ){
118100          renameWalkTrigger(&sWalker, sParse.pNewTrigger);
118101        }
118102#endif /* SQLITE_OMIT_TRIGGER */
118103      }
118104
118105      if( rc==SQLITE_OK ){
118106        rc = renameEditSql(context, &sCtx, zInput, 0, 0);
118107      }
118108      renameTokenFree(db, sCtx.pList);
118109    }
118110    if( rc!=SQLITE_OK ){
118111      if( sqlite3WritableSchema(db) && rc==SQLITE_ERROR ){
118112        sqlite3_result_value(context, argv[1]);
118113      }else{
118114        sqlite3_result_error_code(context, rc);
118115      }
118116    }
118117    renameParseCleanup(&sParse);
118118  }
118119
118120#ifndef SQLITE_OMIT_AUTHORIZATION
118121  db->xAuth = xAuth;
118122#endif
118123
118124  sqlite3BtreeLeaveAll(db);
118125}
118126
118127/* Function:  sqlite_rename_test(DB,SQL,TYPE,NAME,ISTEMP,WHEN,DQS)
118128**
118129** An SQL user function that checks that there are no parse or symbol
118130** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
118131** After an ALTER TABLE .. RENAME operation is performed and the schema
118132** reloaded, this function is called on each SQL statement in the schema
118133** to ensure that it is still usable.
118134**
118135**   0: Database name ("main", "temp" etc.).
118136**   1: SQL statement.
118137**   2: Object type ("view", "table", "trigger" or "index").
118138**   3: Object name.
118139**   4: True if object is from temp schema.
118140**   5: "when" part of error message.
118141**   6: True to disable the DQS quirk when parsing SQL.
118142**
118143** The return value is computed as follows:
118144**
118145**   A. If an error is seen and not in PRAGMA writable_schema=ON mode,
118146**      then raise the error.
118147**   B. Else if a trigger is created and the the table that the trigger is
118148**      attached to is in database zDb, then return 1.
118149**   C. Otherwise return NULL.
118150*/
118151static void renameTableTest(
118152  sqlite3_context *context,
118153  int NotUsed,
118154  sqlite3_value **argv
118155){
118156  sqlite3 *db = sqlite3_context_db_handle(context);
118157  char const *zDb = (const char*)sqlite3_value_text(argv[0]);
118158  char const *zInput = (const char*)sqlite3_value_text(argv[1]);
118159  int bTemp = sqlite3_value_int(argv[4]);
118160  int isLegacy = (db->flags & SQLITE_LegacyAlter);
118161  char const *zWhen = (const char*)sqlite3_value_text(argv[5]);
118162  int bNoDQS = sqlite3_value_int(argv[6]);
118163
118164#ifndef SQLITE_OMIT_AUTHORIZATION
118165  sqlite3_xauth xAuth = db->xAuth;
118166  db->xAuth = 0;
118167#endif
118168
118169  UNUSED_PARAMETER(NotUsed);
118170
118171  if( zDb && zInput ){
118172    int rc;
118173    Parse sParse;
118174    int flags = db->flags;
118175    if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
118176    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
118177    db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));
118178    if( rc==SQLITE_OK ){
118179      if( isLegacy==0 && sParse.pNewTable && IsView(sParse.pNewTable) ){
118180        NameContext sNC;
118181        memset(&sNC, 0, sizeof(sNC));
118182        sNC.pParse = &sParse;
118183        sqlite3SelectPrep(&sParse, sParse.pNewTable->u.view.pSelect, &sNC);
118184        if( sParse.nErr ) rc = sParse.rc;
118185      }
118186
118187      else if( sParse.pNewTrigger ){
118188        if( isLegacy==0 ){
118189          rc = renameResolveTrigger(&sParse);
118190        }
118191        if( rc==SQLITE_OK ){
118192          int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
118193          int i2 = sqlite3FindDbName(db, zDb);
118194          if( i1==i2 ){
118195            /* Handle output case B */
118196            sqlite3_result_int(context, 1);
118197          }
118198        }
118199      }
118200    }
118201
118202    if( rc!=SQLITE_OK && zWhen && !sqlite3WritableSchema(db) ){
118203      /* Output case A */
118204      renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
118205    }
118206    renameParseCleanup(&sParse);
118207  }
118208
118209#ifndef SQLITE_OMIT_AUTHORIZATION
118210  db->xAuth = xAuth;
118211#endif
118212}
118213
118214/*
118215** The implementation of internal UDF sqlite_drop_column().
118216**
118217** Arguments:
118218**
118219**  argv[0]: An integer - the index of the schema containing the table
118220**  argv[1]: CREATE TABLE statement to modify.
118221**  argv[2]: An integer - the index of the column to remove.
118222**
118223** The value returned is a string containing the CREATE TABLE statement
118224** with column argv[2] removed.
118225*/
118226static void dropColumnFunc(
118227  sqlite3_context *context,
118228  int NotUsed,
118229  sqlite3_value **argv
118230){
118231  sqlite3 *db = sqlite3_context_db_handle(context);
118232  int iSchema = sqlite3_value_int(argv[0]);
118233  const char *zSql = (const char*)sqlite3_value_text(argv[1]);
118234  int iCol = sqlite3_value_int(argv[2]);
118235  const char *zDb = db->aDb[iSchema].zDbSName;
118236  int rc;
118237  Parse sParse;
118238  RenameToken *pCol;
118239  Table *pTab;
118240  const char *zEnd;
118241  char *zNew = 0;
118242
118243#ifndef SQLITE_OMIT_AUTHORIZATION
118244  sqlite3_xauth xAuth = db->xAuth;
118245  db->xAuth = 0;
118246#endif
118247
118248  UNUSED_PARAMETER(NotUsed);
118249  rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
118250  if( rc!=SQLITE_OK ) goto drop_column_done;
118251  pTab = sParse.pNewTable;
118252  if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
118253    /* This can happen if the sqlite_schema table is corrupt */
118254    rc = SQLITE_CORRUPT_BKPT;
118255    goto drop_column_done;
118256  }
118257
118258  pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zCnName);
118259  if( iCol<pTab->nCol-1 ){
118260    RenameToken *pEnd;
118261    pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zCnName);
118262    zEnd = (const char*)pEnd->t.z;
118263  }else{
118264    assert( IsOrdinaryTable(pTab) );
118265    zEnd = (const char*)&zSql[pTab->u.tab.addColOffset];
118266    while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
118267  }
118268
118269  zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
118270  sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
118271  sqlite3_free(zNew);
118272
118273drop_column_done:
118274  renameParseCleanup(&sParse);
118275#ifndef SQLITE_OMIT_AUTHORIZATION
118276  db->xAuth = xAuth;
118277#endif
118278  if( rc!=SQLITE_OK ){
118279    sqlite3_result_error_code(context, rc);
118280  }
118281}
118282
118283/*
118284** This function is called by the parser upon parsing an
118285**
118286**     ALTER TABLE pSrc DROP COLUMN pName
118287**
118288** statement. Argument pSrc contains the possibly qualified name of the
118289** table being edited, and token pName the name of the column to drop.
118290*/
118291SQLITE_PRIVATE void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, const Token *pName){
118292  sqlite3 *db = pParse->db;       /* Database handle */
118293  Table *pTab;                    /* Table to modify */
118294  int iDb;                        /* Index of db containing pTab in aDb[] */
118295  const char *zDb;                /* Database containing pTab ("main" etc.) */
118296  char *zCol = 0;                 /* Name of column to drop */
118297  int iCol;                       /* Index of column zCol in pTab->aCol[] */
118298
118299  /* Look up the table being altered. */
118300  assert( pParse->pNewTable==0 );
118301  assert( sqlite3BtreeHoldsAllMutexes(db) );
118302  if( NEVER(db->mallocFailed) ) goto exit_drop_column;
118303  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
118304  if( !pTab ) goto exit_drop_column;
118305
118306  /* Make sure this is not an attempt to ALTER a view, virtual table or
118307  ** system table. */
118308  if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
118309  if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
118310
118311  /* Find the index of the column being dropped. */
118312  zCol = sqlite3NameFromToken(db, pName);
118313  if( zCol==0 ){
118314    assert( db->mallocFailed );
118315    goto exit_drop_column;
118316  }
118317  iCol = sqlite3ColumnIndex(pTab, zCol);
118318  if( iCol<0 ){
118319    sqlite3ErrorMsg(pParse, "no such column: \"%T\"", pName);
118320    goto exit_drop_column;
118321  }
118322
118323  /* Do not allow the user to drop a PRIMARY KEY column or a column
118324  ** constrained by a UNIQUE constraint.  */
118325  if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
118326    sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
118327        (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
118328        zCol
118329    );
118330    goto exit_drop_column;
118331  }
118332
118333  /* Do not allow the number of columns to go to zero */
118334  if( pTab->nCol<=1 ){
118335    sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol);
118336    goto exit_drop_column;
118337  }
118338
118339  /* Edit the sqlite_schema table */
118340  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
118341  assert( iDb>=0 );
118342  zDb = db->aDb[iDb].zDbSName;
118343#ifndef SQLITE_OMIT_AUTHORIZATION
118344  /* Invoke the authorization callback. */
118345  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, zCol) ){
118346    goto exit_drop_column;
118347  }
118348#endif
118349  renameTestSchema(pParse, zDb, iDb==1, "", 0);
118350  renameFixQuotes(pParse, zDb, iDb==1);
118351  sqlite3NestedParse(pParse,
118352      "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
118353      "sql = sqlite_drop_column(%d, sql, %d) "
118354      "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
118355      , zDb, iDb, iCol, pTab->zName
118356  );
118357
118358  /* Drop and reload the database schema. */
118359  renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
118360  renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
118361
118362  /* Edit rows of table on disk */
118363  if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
118364    int i;
118365    int addr;
118366    int reg;
118367    int regRec;
118368    Index *pPk = 0;
118369    int nField = 0;               /* Number of non-virtual columns after drop */
118370    int iCur;
118371    Vdbe *v = sqlite3GetVdbe(pParse);
118372    iCur = pParse->nTab++;
118373    sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
118374    addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
118375    reg = ++pParse->nMem;
118376    if( HasRowid(pTab) ){
118377      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
118378      pParse->nMem += pTab->nCol;
118379    }else{
118380      pPk = sqlite3PrimaryKeyIndex(pTab);
118381      pParse->nMem += pPk->nColumn;
118382      for(i=0; i<pPk->nKeyCol; i++){
118383        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
118384      }
118385      nField = pPk->nKeyCol;
118386    }
118387    regRec = ++pParse->nMem;
118388    for(i=0; i<pTab->nCol; i++){
118389      if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
118390        int regOut;
118391        if( pPk ){
118392          int iPos = sqlite3TableColumnToIndex(pPk, i);
118393          int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
118394          if( iPos<pPk->nKeyCol ) continue;
118395          regOut = reg+1+iPos-(iPos>iColPos);
118396        }else{
118397          regOut = reg+1+nField;
118398        }
118399        if( i==pTab->iPKey ){
118400          sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
118401        }else{
118402          char aff = pTab->aCol[i].affinity;
118403          if( aff==SQLITE_AFF_REAL ){
118404            pTab->aCol[i].affinity = SQLITE_AFF_NUMERIC;
118405          }
118406          sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
118407          pTab->aCol[i].affinity = aff;
118408        }
118409        nField++;
118410      }
118411    }
118412    if( nField==0 ){
118413      /* dbsqlfuzz 5f09e7bcc78b4954d06bf9f2400d7715f48d1fef */
118414      pParse->nMem++;
118415      sqlite3VdbeAddOp2(v, OP_Null, 0, reg+1);
118416      nField = 1;
118417    }
118418    sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
118419    if( pPk ){
118420      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
118421    }else{
118422      sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
118423    }
118424    sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
118425
118426    sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
118427    sqlite3VdbeJumpHere(v, addr);
118428  }
118429
118430exit_drop_column:
118431  sqlite3DbFree(db, zCol);
118432  sqlite3SrcListDelete(db, pSrc);
118433}
118434
118435/*
118436** Register built-in functions used to help implement ALTER TABLE
118437*/
118438SQLITE_PRIVATE void sqlite3AlterFunctions(void){
118439  static FuncDef aAlterTableFuncs[] = {
118440    INTERNAL_FUNCTION(sqlite_rename_column,  9, renameColumnFunc),
118441    INTERNAL_FUNCTION(sqlite_rename_table,   7, renameTableFunc),
118442    INTERNAL_FUNCTION(sqlite_rename_test,    7, renameTableTest),
118443    INTERNAL_FUNCTION(sqlite_drop_column,    3, dropColumnFunc),
118444    INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
118445  };
118446  sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
118447}
118448#endif  /* SQLITE_ALTER_TABLE */
118449
118450/************** End of alter.c ***********************************************/
118451/************** Begin file analyze.c *****************************************/
118452/*
118453** 2005-07-08
118454**
118455** The author disclaims copyright to this source code.  In place of
118456** a legal notice, here is a blessing:
118457**
118458**    May you do good and not evil.
118459**    May you find forgiveness for yourself and forgive others.
118460**    May you share freely, never taking more than you give.
118461**
118462*************************************************************************
118463** This file contains code associated with the ANALYZE command.
118464**
118465** The ANALYZE command gather statistics about the content of tables
118466** and indices.  These statistics are made available to the query planner
118467** to help it make better decisions about how to perform queries.
118468**
118469** The following system tables are or have been supported:
118470**
118471**    CREATE TABLE sqlite_stat1(tbl, idx, stat);
118472**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
118473**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
118474**    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
118475**
118476** Additional tables might be added in future releases of SQLite.
118477** The sqlite_stat2 table is not created or used unless the SQLite version
118478** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
118479** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
118480** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
118481** created and used by SQLite versions 3.7.9 through 3.29.0 when
118482** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
118483** is a superset of sqlite_stat2 and is also now deprecated.  The
118484** sqlite_stat4 is an enhanced version of sqlite_stat3 and is only
118485** available when compiled with SQLITE_ENABLE_STAT4 and in SQLite
118486** versions 3.8.1 and later.  STAT4 is the only variant that is still
118487** supported.
118488**
118489** For most applications, sqlite_stat1 provides all the statistics required
118490** for the query planner to make good choices.
118491**
118492** Format of sqlite_stat1:
118493**
118494** There is normally one row per index, with the index identified by the
118495** name in the idx column.  The tbl column is the name of the table to
118496** which the index belongs.  In each such row, the stat column will be
118497** a string consisting of a list of integers.  The first integer in this
118498** list is the number of rows in the index.  (This is the same as the
118499** number of rows in the table, except for partial indices.)  The second
118500** integer is the average number of rows in the index that have the same
118501** value in the first column of the index.  The third integer is the average
118502** number of rows in the index that have the same value for the first two
118503** columns.  The N-th integer (for N>1) is the average number of rows in
118504** the index which have the same value for the first N-1 columns.  For
118505** a K-column index, there will be K+1 integers in the stat column.  If
118506** the index is unique, then the last integer will be 1.
118507**
118508** The list of integers in the stat column can optionally be followed
118509** by the keyword "unordered".  The "unordered" keyword, if it is present,
118510** must be separated from the last integer by a single space.  If the
118511** "unordered" keyword is present, then the query planner assumes that
118512** the index is unordered and will not use the index for a range query.
118513**
118514** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
118515** column contains a single integer which is the (estimated) number of
118516** rows in the table identified by sqlite_stat1.tbl.
118517**
118518** Format of sqlite_stat2:
118519**
118520** The sqlite_stat2 is only created and is only used if SQLite is compiled
118521** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
118522** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
118523** about the distribution of keys within an index.  The index is identified by
118524** the "idx" column and the "tbl" column is the name of the table to which
118525** the index belongs.  There are usually 10 rows in the sqlite_stat2
118526** table for each index.
118527**
118528** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
118529** inclusive are samples of the left-most key value in the index taken at
118530** evenly spaced points along the index.  Let the number of samples be S
118531** (10 in the standard build) and let C be the number of rows in the index.
118532** Then the sampled rows are given by:
118533**
118534**     rownumber = (i*C*2 + C)/(S*2)
118535**
118536** For i between 0 and S-1.  Conceptually, the index space is divided into
118537** S uniform buckets and the samples are the middle row from each bucket.
118538**
118539** The format for sqlite_stat2 is recorded here for legacy reference.  This
118540** version of SQLite does not support sqlite_stat2.  It neither reads nor
118541** writes the sqlite_stat2 table.  This version of SQLite only supports
118542** sqlite_stat3.
118543**
118544** Format for sqlite_stat3:
118545**
118546** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
118547** sqlite_stat4 format will be described first.  Further information
118548** about sqlite_stat3 follows the sqlite_stat4 description.
118549**
118550** Format for sqlite_stat4:
118551**
118552** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
118553** to aid the query planner in choosing good indices based on the values
118554** that indexed columns are compared against in the WHERE clauses of
118555** queries.
118556**
118557** The sqlite_stat4 table contains multiple entries for each index.
118558** The idx column names the index and the tbl column is the table of the
118559** index.  If the idx and tbl columns are the same, then the sample is
118560** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
118561** binary encoding of a key from the index.  The nEq column is a
118562** list of integers.  The first integer is the approximate number
118563** of entries in the index whose left-most column exactly matches
118564** the left-most column of the sample.  The second integer in nEq
118565** is the approximate number of entries in the index where the
118566** first two columns match the first two columns of the sample.
118567** And so forth.  nLt is another list of integers that show the approximate
118568** number of entries that are strictly less than the sample.  The first
118569** integer in nLt contains the number of entries in the index where the
118570** left-most column is less than the left-most column of the sample.
118571** The K-th integer in the nLt entry is the number of index entries
118572** where the first K columns are less than the first K columns of the
118573** sample.  The nDLt column is like nLt except that it contains the
118574** number of distinct entries in the index that are less than the
118575** sample.
118576**
118577** There can be an arbitrary number of sqlite_stat4 entries per index.
118578** The ANALYZE command will typically generate sqlite_stat4 tables
118579** that contain between 10 and 40 samples which are distributed across
118580** the key space, though not uniformly, and which include samples with
118581** large nEq values.
118582**
118583** Format for sqlite_stat3 redux:
118584**
118585** The sqlite_stat3 table is like sqlite_stat4 except that it only
118586** looks at the left-most column of the index.  The sqlite_stat3.sample
118587** column contains the actual value of the left-most column instead
118588** of a blob encoding of the complete index key as is found in
118589** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
118590** all contain just a single integer which is the same as the first
118591** integer in the equivalent columns in sqlite_stat4.
118592*/
118593#ifndef SQLITE_OMIT_ANALYZE
118594/* #include "sqliteInt.h" */
118595
118596#if defined(SQLITE_ENABLE_STAT4)
118597# define IsStat4     1
118598#else
118599# define IsStat4     0
118600# undef SQLITE_STAT4_SAMPLES
118601# define SQLITE_STAT4_SAMPLES 1
118602#endif
118603
118604/*
118605** This routine generates code that opens the sqlite_statN tables.
118606** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
118607** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
118608** appropriate compile-time options are provided.
118609**
118610** If the sqlite_statN tables do not previously exist, it is created.
118611**
118612** Argument zWhere may be a pointer to a buffer containing a table name,
118613** or it may be a NULL pointer. If it is not NULL, then all entries in
118614** the sqlite_statN tables associated with the named table are deleted.
118615** If zWhere==0, then code is generated to delete all stat table entries.
118616*/
118617static void openStatTable(
118618  Parse *pParse,          /* Parsing context */
118619  int iDb,                /* The database we are looking in */
118620  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
118621  const char *zWhere,     /* Delete entries for this table or index */
118622  const char *zWhereType  /* Either "tbl" or "idx" */
118623){
118624  static const struct {
118625    const char *zName;
118626    const char *zCols;
118627  } aTable[] = {
118628    { "sqlite_stat1", "tbl,idx,stat" },
118629#if defined(SQLITE_ENABLE_STAT4)
118630    { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
118631#else
118632    { "sqlite_stat4", 0 },
118633#endif
118634    { "sqlite_stat3", 0 },
118635  };
118636  int i;
118637  sqlite3 *db = pParse->db;
118638  Db *pDb;
118639  Vdbe *v = sqlite3GetVdbe(pParse);
118640  u32 aRoot[ArraySize(aTable)];
118641  u8 aCreateTbl[ArraySize(aTable)];
118642#ifdef SQLITE_ENABLE_STAT4
118643  const int nToOpen = OptimizationEnabled(db,SQLITE_Stat4) ? 2 : 1;
118644#else
118645  const int nToOpen = 1;
118646#endif
118647
118648  if( v==0 ) return;
118649  assert( sqlite3BtreeHoldsAllMutexes(db) );
118650  assert( sqlite3VdbeDb(v)==db );
118651  pDb = &db->aDb[iDb];
118652
118653  /* Create new statistic tables if they do not exist, or clear them
118654  ** if they do already exist.
118655  */
118656  for(i=0; i<ArraySize(aTable); i++){
118657    const char *zTab = aTable[i].zName;
118658    Table *pStat;
118659    aCreateTbl[i] = 0;
118660    if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
118661      if( i<nToOpen ){
118662        /* The sqlite_statN table does not exist. Create it. Note that a
118663        ** side-effect of the CREATE TABLE statement is to leave the rootpage
118664        ** of the new table in register pParse->regRoot. This is important
118665        ** because the OpenWrite opcode below will be needing it. */
118666        sqlite3NestedParse(pParse,
118667            "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
118668        );
118669        aRoot[i] = (u32)pParse->regRoot;
118670        aCreateTbl[i] = OPFLAG_P2ISREG;
118671      }
118672    }else{
118673      /* The table already exists. If zWhere is not NULL, delete all entries
118674      ** associated with the table zWhere. If zWhere is NULL, delete the
118675      ** entire contents of the table. */
118676      aRoot[i] = pStat->tnum;
118677      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
118678      if( zWhere ){
118679        sqlite3NestedParse(pParse,
118680           "DELETE FROM %Q.%s WHERE %s=%Q",
118681           pDb->zDbSName, zTab, zWhereType, zWhere
118682        );
118683#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
118684      }else if( db->xPreUpdateCallback ){
118685        sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
118686#endif
118687      }else{
118688        /* The sqlite_stat[134] table already exists.  Delete all rows. */
118689        sqlite3VdbeAddOp2(v, OP_Clear, (int)aRoot[i], iDb);
118690      }
118691    }
118692  }
118693
118694  /* Open the sqlite_stat[134] tables for writing. */
118695  for(i=0; i<nToOpen; i++){
118696    assert( i<ArraySize(aTable) );
118697    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, (int)aRoot[i], iDb, 3);
118698    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
118699    VdbeComment((v, aTable[i].zName));
118700  }
118701}
118702
118703/*
118704** Recommended number of samples for sqlite_stat4
118705*/
118706#ifndef SQLITE_STAT4_SAMPLES
118707# define SQLITE_STAT4_SAMPLES 24
118708#endif
118709
118710/*
118711** Three SQL functions - stat_init(), stat_push(), and stat_get() -
118712** share an instance of the following structure to hold their state
118713** information.
118714*/
118715typedef struct StatAccum StatAccum;
118716typedef struct StatSample StatSample;
118717struct StatSample {
118718  tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
118719#ifdef SQLITE_ENABLE_STAT4
118720  tRowcnt *anEq;                  /* sqlite_stat4.nEq */
118721  tRowcnt *anLt;                  /* sqlite_stat4.nLt */
118722  union {
118723    i64 iRowid;                     /* Rowid in main table of the key */
118724    u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
118725  } u;
118726  u32 nRowid;                     /* Sizeof aRowid[] */
118727  u8 isPSample;                   /* True if a periodic sample */
118728  int iCol;                       /* If !isPSample, the reason for inclusion */
118729  u32 iHash;                      /* Tiebreaker hash */
118730#endif
118731};
118732struct StatAccum {
118733  sqlite3 *db;              /* Database connection, for malloc() */
118734  tRowcnt nEst;             /* Estimated number of rows */
118735  tRowcnt nRow;             /* Number of rows visited so far */
118736  int nLimit;               /* Analysis row-scan limit */
118737  int nCol;                 /* Number of columns in index + pk/rowid */
118738  int nKeyCol;              /* Number of index columns w/o the pk/rowid */
118739  u8 nSkipAhead;            /* Number of times of skip-ahead */
118740  StatSample current;       /* Current row as a StatSample */
118741#ifdef SQLITE_ENABLE_STAT4
118742  tRowcnt nPSample;         /* How often to do a periodic sample */
118743  int mxSample;             /* Maximum number of samples to accumulate */
118744  u32 iPrn;                 /* Pseudo-random number used for sampling */
118745  StatSample *aBest;        /* Array of nCol best samples */
118746  int iMin;                 /* Index in a[] of entry with minimum score */
118747  int nSample;              /* Current number of samples */
118748  int nMaxEqZero;           /* Max leading 0 in anEq[] for any a[] entry */
118749  int iGet;                 /* Index of current sample accessed by stat_get() */
118750  StatSample *a;            /* Array of mxSample StatSample objects */
118751#endif
118752};
118753
118754/* Reclaim memory used by a StatSample
118755*/
118756#ifdef SQLITE_ENABLE_STAT4
118757static void sampleClear(sqlite3 *db, StatSample *p){
118758  assert( db!=0 );
118759  if( p->nRowid ){
118760    sqlite3DbFree(db, p->u.aRowid);
118761    p->nRowid = 0;
118762  }
118763}
118764#endif
118765
118766/* Initialize the BLOB value of a ROWID
118767*/
118768#ifdef SQLITE_ENABLE_STAT4
118769static void sampleSetRowid(sqlite3 *db, StatSample *p, int n, const u8 *pData){
118770  assert( db!=0 );
118771  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
118772  p->u.aRowid = sqlite3DbMallocRawNN(db, n);
118773  if( p->u.aRowid ){
118774    p->nRowid = n;
118775    memcpy(p->u.aRowid, pData, n);
118776  }else{
118777    p->nRowid = 0;
118778  }
118779}
118780#endif
118781
118782/* Initialize the INTEGER value of a ROWID.
118783*/
118784#ifdef SQLITE_ENABLE_STAT4
118785static void sampleSetRowidInt64(sqlite3 *db, StatSample *p, i64 iRowid){
118786  assert( db!=0 );
118787  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
118788  p->nRowid = 0;
118789  p->u.iRowid = iRowid;
118790}
118791#endif
118792
118793
118794/*
118795** Copy the contents of object (*pFrom) into (*pTo).
118796*/
118797#ifdef SQLITE_ENABLE_STAT4
118798static void sampleCopy(StatAccum *p, StatSample *pTo, StatSample *pFrom){
118799  pTo->isPSample = pFrom->isPSample;
118800  pTo->iCol = pFrom->iCol;
118801  pTo->iHash = pFrom->iHash;
118802  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
118803  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
118804  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
118805  if( pFrom->nRowid ){
118806    sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
118807  }else{
118808    sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
118809  }
118810}
118811#endif
118812
118813/*
118814** Reclaim all memory of a StatAccum structure.
118815*/
118816static void statAccumDestructor(void *pOld){
118817  StatAccum *p = (StatAccum*)pOld;
118818#ifdef SQLITE_ENABLE_STAT4
118819  if( p->mxSample ){
118820    int i;
118821    for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
118822    for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
118823    sampleClear(p->db, &p->current);
118824  }
118825#endif
118826  sqlite3DbFree(p->db, p);
118827}
118828
118829/*
118830** Implementation of the stat_init(N,K,C,L) SQL function. The four parameters
118831** are:
118832**     N:    The number of columns in the index including the rowid/pk (note 1)
118833**     K:    The number of columns in the index excluding the rowid/pk.
118834**     C:    Estimated number of rows in the index
118835**     L:    A limit on the number of rows to scan, or 0 for no-limit
118836**
118837** Note 1:  In the special case of the covering index that implements a
118838** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
118839** total number of columns in the table.
118840**
118841** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
118842** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
118843** PRIMARY KEY of the table.  The covering index that implements the
118844** original WITHOUT ROWID table as N==K as a special case.
118845**
118846** This routine allocates the StatAccum object in heap memory. The return
118847** value is a pointer to the StatAccum object.  The datatype of the
118848** return value is BLOB, but it is really just a pointer to the StatAccum
118849** object.
118850*/
118851static void statInit(
118852  sqlite3_context *context,
118853  int argc,
118854  sqlite3_value **argv
118855){
118856  StatAccum *p;
118857  int nCol;                       /* Number of columns in index being sampled */
118858  int nKeyCol;                    /* Number of key columns */
118859  int nColUp;                     /* nCol rounded up for alignment */
118860  int n;                          /* Bytes of space to allocate */
118861  sqlite3 *db = sqlite3_context_db_handle(context);   /* Database connection */
118862#ifdef SQLITE_ENABLE_STAT4
118863  /* Maximum number of samples.  0 if STAT4 data is not collected */
118864  int mxSample = OptimizationEnabled(db,SQLITE_Stat4) ?SQLITE_STAT4_SAMPLES :0;
118865#endif
118866
118867  /* Decode the three function arguments */
118868  UNUSED_PARAMETER(argc);
118869  nCol = sqlite3_value_int(argv[0]);
118870  assert( nCol>0 );
118871  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
118872  nKeyCol = sqlite3_value_int(argv[1]);
118873  assert( nKeyCol<=nCol );
118874  assert( nKeyCol>0 );
118875
118876  /* Allocate the space required for the StatAccum object */
118877  n = sizeof(*p)
118878    + sizeof(tRowcnt)*nColUp;                    /* StatAccum.anDLt */
118879#ifdef SQLITE_ENABLE_STAT4
118880  n += sizeof(tRowcnt)*nColUp;                   /* StatAccum.anEq */
118881  if( mxSample ){
118882    n += sizeof(tRowcnt)*nColUp                  /* StatAccum.anLt */
118883      + sizeof(StatSample)*(nCol+mxSample)       /* StatAccum.aBest[], a[] */
118884      + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample);
118885  }
118886#endif
118887  p = sqlite3DbMallocZero(db, n);
118888  if( p==0 ){
118889    sqlite3_result_error_nomem(context);
118890    return;
118891  }
118892
118893  p->db = db;
118894  p->nEst = sqlite3_value_int64(argv[2]);
118895  p->nRow = 0;
118896  p->nLimit = sqlite3_value_int64(argv[3]);
118897  p->nCol = nCol;
118898  p->nKeyCol = nKeyCol;
118899  p->nSkipAhead = 0;
118900  p->current.anDLt = (tRowcnt*)&p[1];
118901
118902#ifdef SQLITE_ENABLE_STAT4
118903  p->current.anEq = &p->current.anDLt[nColUp];
118904  p->mxSample = p->nLimit==0 ? mxSample : 0;
118905  if( mxSample ){
118906    u8 *pSpace;                     /* Allocated space not yet assigned */
118907    int i;                          /* Used to iterate through p->aSample[] */
118908
118909    p->iGet = -1;
118910    p->nPSample = (tRowcnt)(p->nEst/(mxSample/3+1) + 1);
118911    p->current.anLt = &p->current.anEq[nColUp];
118912    p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
118913
118914    /* Set up the StatAccum.a[] and aBest[] arrays */
118915    p->a = (struct StatSample*)&p->current.anLt[nColUp];
118916    p->aBest = &p->a[mxSample];
118917    pSpace = (u8*)(&p->a[mxSample+nCol]);
118918    for(i=0; i<(mxSample+nCol); i++){
118919      p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
118920      p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
118921      p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
118922    }
118923    assert( (pSpace - (u8*)p)==n );
118924
118925    for(i=0; i<nCol; i++){
118926      p->aBest[i].iCol = i;
118927    }
118928  }
118929#endif
118930
118931  /* Return a pointer to the allocated object to the caller.  Note that
118932  ** only the pointer (the 2nd parameter) matters.  The size of the object
118933  ** (given by the 3rd parameter) is never used and can be any positive
118934  ** value. */
118935  sqlite3_result_blob(context, p, sizeof(*p), statAccumDestructor);
118936}
118937static const FuncDef statInitFuncdef = {
118938  4,               /* nArg */
118939  SQLITE_UTF8,     /* funcFlags */
118940  0,               /* pUserData */
118941  0,               /* pNext */
118942  statInit,        /* xSFunc */
118943  0,               /* xFinalize */
118944  0, 0,            /* xValue, xInverse */
118945  "stat_init",     /* zName */
118946  {0}
118947};
118948
118949#ifdef SQLITE_ENABLE_STAT4
118950/*
118951** pNew and pOld are both candidate non-periodic samples selected for
118952** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
118953** considering only any trailing columns and the sample hash value, this
118954** function returns true if sample pNew is to be preferred over pOld.
118955** In other words, if we assume that the cardinalities of the selected
118956** column for pNew and pOld are equal, is pNew to be preferred over pOld.
118957**
118958** This function assumes that for each argument sample, the contents of
118959** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
118960*/
118961static int sampleIsBetterPost(
118962  StatAccum *pAccum,
118963  StatSample *pNew,
118964  StatSample *pOld
118965){
118966  int nCol = pAccum->nCol;
118967  int i;
118968  assert( pNew->iCol==pOld->iCol );
118969  for(i=pNew->iCol+1; i<nCol; i++){
118970    if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
118971    if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
118972  }
118973  if( pNew->iHash>pOld->iHash ) return 1;
118974  return 0;
118975}
118976#endif
118977
118978#ifdef SQLITE_ENABLE_STAT4
118979/*
118980** Return true if pNew is to be preferred over pOld.
118981**
118982** This function assumes that for each argument sample, the contents of
118983** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
118984*/
118985static int sampleIsBetter(
118986  StatAccum *pAccum,
118987  StatSample *pNew,
118988  StatSample *pOld
118989){
118990  tRowcnt nEqNew = pNew->anEq[pNew->iCol];
118991  tRowcnt nEqOld = pOld->anEq[pOld->iCol];
118992
118993  assert( pOld->isPSample==0 && pNew->isPSample==0 );
118994  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
118995
118996  if( (nEqNew>nEqOld) ) return 1;
118997  if( nEqNew==nEqOld ){
118998    if( pNew->iCol<pOld->iCol ) return 1;
118999    return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
119000  }
119001  return 0;
119002}
119003
119004/*
119005** Copy the contents of sample *pNew into the p->a[] array. If necessary,
119006** remove the least desirable sample from p->a[] to make room.
119007*/
119008static void sampleInsert(StatAccum *p, StatSample *pNew, int nEqZero){
119009  StatSample *pSample = 0;
119010  int i;
119011
119012  assert( IsStat4 || nEqZero==0 );
119013
119014  /* StatAccum.nMaxEqZero is set to the maximum number of leading 0
119015  ** values in the anEq[] array of any sample in StatAccum.a[]. In
119016  ** other words, if nMaxEqZero is n, then it is guaranteed that there
119017  ** are no samples with StatSample.anEq[m]==0 for (m>=n). */
119018  if( nEqZero>p->nMaxEqZero ){
119019    p->nMaxEqZero = nEqZero;
119020  }
119021  if( pNew->isPSample==0 ){
119022    StatSample *pUpgrade = 0;
119023    assert( pNew->anEq[pNew->iCol]>0 );
119024
119025    /* This sample is being added because the prefix that ends in column
119026    ** iCol occurs many times in the table. However, if we have already
119027    ** added a sample that shares this prefix, there is no need to add
119028    ** this one. Instead, upgrade the priority of the highest priority
119029    ** existing sample that shares this prefix.  */
119030    for(i=p->nSample-1; i>=0; i--){
119031      StatSample *pOld = &p->a[i];
119032      if( pOld->anEq[pNew->iCol]==0 ){
119033        if( pOld->isPSample ) return;
119034        assert( pOld->iCol>pNew->iCol );
119035        assert( sampleIsBetter(p, pNew, pOld) );
119036        if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
119037          pUpgrade = pOld;
119038        }
119039      }
119040    }
119041    if( pUpgrade ){
119042      pUpgrade->iCol = pNew->iCol;
119043      pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
119044      goto find_new_min;
119045    }
119046  }
119047
119048  /* If necessary, remove sample iMin to make room for the new sample. */
119049  if( p->nSample>=p->mxSample ){
119050    StatSample *pMin = &p->a[p->iMin];
119051    tRowcnt *anEq = pMin->anEq;
119052    tRowcnt *anLt = pMin->anLt;
119053    tRowcnt *anDLt = pMin->anDLt;
119054    sampleClear(p->db, pMin);
119055    memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
119056    pSample = &p->a[p->nSample-1];
119057    pSample->nRowid = 0;
119058    pSample->anEq = anEq;
119059    pSample->anDLt = anDLt;
119060    pSample->anLt = anLt;
119061    p->nSample = p->mxSample-1;
119062  }
119063
119064  /* The "rows less-than" for the rowid column must be greater than that
119065  ** for the last sample in the p->a[] array. Otherwise, the samples would
119066  ** be out of order. */
119067  assert( p->nSample==0
119068       || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
119069
119070  /* Insert the new sample */
119071  pSample = &p->a[p->nSample];
119072  sampleCopy(p, pSample, pNew);
119073  p->nSample++;
119074
119075  /* Zero the first nEqZero entries in the anEq[] array. */
119076  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
119077
119078find_new_min:
119079  if( p->nSample>=p->mxSample ){
119080    int iMin = -1;
119081    for(i=0; i<p->mxSample; i++){
119082      if( p->a[i].isPSample ) continue;
119083      if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
119084        iMin = i;
119085      }
119086    }
119087    assert( iMin>=0 );
119088    p->iMin = iMin;
119089  }
119090}
119091#endif /* SQLITE_ENABLE_STAT4 */
119092
119093#ifdef SQLITE_ENABLE_STAT4
119094/*
119095** Field iChng of the index being scanned has changed. So at this point
119096** p->current contains a sample that reflects the previous row of the
119097** index. The value of anEq[iChng] and subsequent anEq[] elements are
119098** correct at this point.
119099*/
119100static void samplePushPrevious(StatAccum *p, int iChng){
119101  int i;
119102
119103  /* Check if any samples from the aBest[] array should be pushed
119104  ** into IndexSample.a[] at this point.  */
119105  for(i=(p->nCol-2); i>=iChng; i--){
119106    StatSample *pBest = &p->aBest[i];
119107    pBest->anEq[i] = p->current.anEq[i];
119108    if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
119109      sampleInsert(p, pBest, i);
119110    }
119111  }
119112
119113  /* Check that no sample contains an anEq[] entry with an index of
119114  ** p->nMaxEqZero or greater set to zero. */
119115  for(i=p->nSample-1; i>=0; i--){
119116    int j;
119117    for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
119118  }
119119
119120  /* Update the anEq[] fields of any samples already collected. */
119121  if( iChng<p->nMaxEqZero ){
119122    for(i=p->nSample-1; i>=0; i--){
119123      int j;
119124      for(j=iChng; j<p->nCol; j++){
119125        if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
119126      }
119127    }
119128    p->nMaxEqZero = iChng;
119129  }
119130}
119131#endif /* SQLITE_ENABLE_STAT4 */
119132
119133/*
119134** Implementation of the stat_push SQL function:  stat_push(P,C,R)
119135** Arguments:
119136**
119137**    P     Pointer to the StatAccum object created by stat_init()
119138**    C     Index of left-most column to differ from previous row
119139**    R     Rowid for the current row.  Might be a key record for
119140**          WITHOUT ROWID tables.
119141**
119142** The purpose of this routine is to collect statistical data and/or
119143** samples from the index being analyzed into the StatAccum object.
119144** The stat_get() SQL function will be used afterwards to
119145** retrieve the information gathered.
119146**
119147** This SQL function usually returns NULL, but might return an integer
119148** if it wants the byte-code to do special processing.
119149**
119150** The R parameter is only used for STAT4
119151*/
119152static void statPush(
119153  sqlite3_context *context,
119154  int argc,
119155  sqlite3_value **argv
119156){
119157  int i;
119158
119159  /* The three function arguments */
119160  StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);
119161  int iChng = sqlite3_value_int(argv[1]);
119162
119163  UNUSED_PARAMETER( argc );
119164  UNUSED_PARAMETER( context );
119165  assert( p->nCol>0 );
119166  assert( iChng<p->nCol );
119167
119168  if( p->nRow==0 ){
119169    /* This is the first call to this function. Do initialization. */
119170#ifdef SQLITE_ENABLE_STAT4
119171    for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
119172#endif
119173  }else{
119174    /* Second and subsequent calls get processed here */
119175#ifdef SQLITE_ENABLE_STAT4
119176    if( p->mxSample ) samplePushPrevious(p, iChng);
119177#endif
119178
119179    /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
119180    ** to the current row of the index. */
119181#ifdef SQLITE_ENABLE_STAT4
119182    for(i=0; i<iChng; i++){
119183      p->current.anEq[i]++;
119184    }
119185#endif
119186    for(i=iChng; i<p->nCol; i++){
119187      p->current.anDLt[i]++;
119188#ifdef SQLITE_ENABLE_STAT4
119189      if( p->mxSample ) p->current.anLt[i] += p->current.anEq[i];
119190      p->current.anEq[i] = 1;
119191#endif
119192    }
119193  }
119194
119195  p->nRow++;
119196#ifdef SQLITE_ENABLE_STAT4
119197  if( p->mxSample ){
119198    tRowcnt nLt;
119199    if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
119200      sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
119201    }else{
119202      sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
119203                                         sqlite3_value_blob(argv[2]));
119204    }
119205    p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
119206
119207    nLt = p->current.anLt[p->nCol-1];
119208    /* Check if this is to be a periodic sample. If so, add it. */
119209    if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
119210      p->current.isPSample = 1;
119211      p->current.iCol = 0;
119212      sampleInsert(p, &p->current, p->nCol-1);
119213      p->current.isPSample = 0;
119214    }
119215
119216    /* Update the aBest[] array. */
119217    for(i=0; i<(p->nCol-1); i++){
119218      p->current.iCol = i;
119219      if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
119220        sampleCopy(p, &p->aBest[i], &p->current);
119221      }
119222    }
119223  }else
119224#endif
119225  if( p->nLimit && p->nRow>(tRowcnt)p->nLimit*(p->nSkipAhead+1) ){
119226    p->nSkipAhead++;
119227    sqlite3_result_int(context, p->current.anDLt[0]>0);
119228  }
119229}
119230
119231static const FuncDef statPushFuncdef = {
119232  2+IsStat4,       /* nArg */
119233  SQLITE_UTF8,     /* funcFlags */
119234  0,               /* pUserData */
119235  0,               /* pNext */
119236  statPush,        /* xSFunc */
119237  0,               /* xFinalize */
119238  0, 0,            /* xValue, xInverse */
119239  "stat_push",     /* zName */
119240  {0}
119241};
119242
119243#define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
119244#define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
119245#define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
119246#define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
119247#define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
119248
119249/*
119250** Implementation of the stat_get(P,J) SQL function.  This routine is
119251** used to query statistical information that has been gathered into
119252** the StatAccum object by prior calls to stat_push().  The P parameter
119253** has type BLOB but it is really just a pointer to the StatAccum object.
119254** The content to returned is determined by the parameter J
119255** which is one of the STAT_GET_xxxx values defined above.
119256**
119257** The stat_get(P,J) function is not available to generic SQL.  It is
119258** inserted as part of a manually constructed bytecode program.  (See
119259** the callStatGet() routine below.)  It is guaranteed that the P
119260** parameter will always be a pointer to a StatAccum object, never a
119261** NULL.
119262**
119263** If STAT4 is not enabled, then J is always
119264** STAT_GET_STAT1 and is hence omitted and this routine becomes
119265** a one-parameter function, stat_get(P), that always returns the
119266** stat1 table entry information.
119267*/
119268static void statGet(
119269  sqlite3_context *context,
119270  int argc,
119271  sqlite3_value **argv
119272){
119273  StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);
119274#ifdef SQLITE_ENABLE_STAT4
119275  /* STAT4 has a parameter on this routine. */
119276  int eCall = sqlite3_value_int(argv[1]);
119277  assert( argc==2 );
119278  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
119279       || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
119280       || eCall==STAT_GET_NDLT
119281  );
119282  assert( eCall==STAT_GET_STAT1 || p->mxSample );
119283  if( eCall==STAT_GET_STAT1 )
119284#else
119285  assert( argc==1 );
119286#endif
119287  {
119288    /* Return the value to store in the "stat" column of the sqlite_stat1
119289    ** table for this index.
119290    **
119291    ** The value is a string composed of a list of integers describing
119292    ** the index. The first integer in the list is the total number of
119293    ** entries in the index. There is one additional integer in the list
119294    ** for each indexed column. This additional integer is an estimate of
119295    ** the number of rows matched by a equality query on the index using
119296    ** a key with the corresponding number of fields. In other words,
119297    ** if the index is on columns (a,b) and the sqlite_stat1 value is
119298    ** "100 10 2", then SQLite estimates that:
119299    **
119300    **   * the index contains 100 rows,
119301    **   * "WHERE a=?" matches 10 rows, and
119302    **   * "WHERE a=? AND b=?" matches 2 rows.
119303    **
119304    ** If D is the count of distinct values and K is the total number of
119305    ** rows, then each estimate is usually computed as:
119306    **
119307    **        I = (K+D-1)/D
119308    **
119309    ** In other words, I is K/D rounded up to the next whole integer.
119310    ** However, if I is between 1.0 and 1.1 (in other words if I is
119311    ** close to 1.0 but just a little larger) then do not round up but
119312    ** instead keep the I value at 1.0.
119313    */
119314    sqlite3_str sStat;   /* Text of the constructed "stat" line */
119315    int i;               /* Loop counter */
119316
119317    sqlite3StrAccumInit(&sStat, 0, 0, 0, (p->nKeyCol+1)*100);
119318    sqlite3_str_appendf(&sStat, "%llu",
119319        p->nSkipAhead ? (u64)p->nEst : (u64)p->nRow);
119320    for(i=0; i<p->nKeyCol; i++){
119321      u64 nDistinct = p->current.anDLt[i] + 1;
119322      u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
119323      if( iVal==2 && p->nRow*10 <= nDistinct*11 ) iVal = 1;
119324      sqlite3_str_appendf(&sStat, " %llu", iVal);
119325#ifdef SQLITE_ENABLE_STAT4
119326      assert( p->current.anEq[i] || p->nRow==0 );
119327#endif
119328    }
119329    sqlite3ResultStrAccum(context, &sStat);
119330  }
119331#ifdef SQLITE_ENABLE_STAT4
119332  else if( eCall==STAT_GET_ROWID ){
119333    if( p->iGet<0 ){
119334      samplePushPrevious(p, 0);
119335      p->iGet = 0;
119336    }
119337    if( p->iGet<p->nSample ){
119338      StatSample *pS = p->a + p->iGet;
119339      if( pS->nRowid==0 ){
119340        sqlite3_result_int64(context, pS->u.iRowid);
119341      }else{
119342        sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
119343                            SQLITE_TRANSIENT);
119344      }
119345    }
119346  }else{
119347    tRowcnt *aCnt = 0;
119348    sqlite3_str sStat;
119349    int i;
119350
119351    assert( p->iGet<p->nSample );
119352    switch( eCall ){
119353      case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
119354      case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
119355      default: {
119356        aCnt = p->a[p->iGet].anDLt;
119357        p->iGet++;
119358        break;
119359      }
119360    }
119361    sqlite3StrAccumInit(&sStat, 0, 0, 0, p->nCol*100);
119362    for(i=0; i<p->nCol; i++){
119363      sqlite3_str_appendf(&sStat, "%llu ", (u64)aCnt[i]);
119364    }
119365    if( sStat.nChar ) sStat.nChar--;
119366    sqlite3ResultStrAccum(context, &sStat);
119367  }
119368#endif /* SQLITE_ENABLE_STAT4 */
119369#ifndef SQLITE_DEBUG
119370  UNUSED_PARAMETER( argc );
119371#endif
119372}
119373static const FuncDef statGetFuncdef = {
119374  1+IsStat4,       /* nArg */
119375  SQLITE_UTF8,     /* funcFlags */
119376  0,               /* pUserData */
119377  0,               /* pNext */
119378  statGet,         /* xSFunc */
119379  0,               /* xFinalize */
119380  0, 0,            /* xValue, xInverse */
119381  "stat_get",      /* zName */
119382  {0}
119383};
119384
119385static void callStatGet(Parse *pParse, int regStat, int iParam, int regOut){
119386#ifdef SQLITE_ENABLE_STAT4
119387  sqlite3VdbeAddOp2(pParse->pVdbe, OP_Integer, iParam, regStat+1);
119388#elif SQLITE_DEBUG
119389  assert( iParam==STAT_GET_STAT1 );
119390#else
119391  UNUSED_PARAMETER( iParam );
119392#endif
119393  assert( regOut!=regStat && regOut!=regStat+1 );
119394  sqlite3VdbeAddFunctionCall(pParse, 0, regStat, regOut, 1+IsStat4,
119395                             &statGetFuncdef, 0);
119396}
119397
119398#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
119399/* Add a comment to the most recent VDBE opcode that is the name
119400** of the k-th column of the pIdx index.
119401*/
119402static void analyzeVdbeCommentIndexWithColumnName(
119403  Vdbe *v,         /* Prepared statement under construction */
119404  Index *pIdx,     /* Index whose column is being loaded */
119405  int k            /* Which column index */
119406){
119407  int i;           /* Index of column in the table */
119408  assert( k>=0 && k<pIdx->nColumn );
119409  i = pIdx->aiColumn[k];
119410  if( NEVER(i==XN_ROWID) ){
119411    VdbeComment((v,"%s.rowid",pIdx->zName));
119412  }else if( i==XN_EXPR ){
119413    assert( pIdx->bHasExpr );
119414    VdbeComment((v,"%s.expr(%d)",pIdx->zName, k));
119415  }else{
119416    VdbeComment((v,"%s.%s", pIdx->zName, pIdx->pTable->aCol[i].zCnName));
119417  }
119418}
119419#else
119420# define analyzeVdbeCommentIndexWithColumnName(a,b,c)
119421#endif /* SQLITE_DEBUG */
119422
119423/*
119424** Generate code to do an analysis of all indices associated with
119425** a single table.
119426*/
119427static void analyzeOneTable(
119428  Parse *pParse,   /* Parser context */
119429  Table *pTab,     /* Table whose indices are to be analyzed */
119430  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
119431  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
119432  int iMem,        /* Available memory locations begin here */
119433  int iTab         /* Next available cursor */
119434){
119435  sqlite3 *db = pParse->db;    /* Database handle */
119436  Index *pIdx;                 /* An index to being analyzed */
119437  int iIdxCur;                 /* Cursor open on index being analyzed */
119438  int iTabCur;                 /* Table cursor */
119439  Vdbe *v;                     /* The virtual machine being built up */
119440  int i;                       /* Loop counter */
119441  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
119442  int iDb;                     /* Index of database containing pTab */
119443  u8 needTableCnt = 1;         /* True to count the table */
119444  int regNewRowid = iMem++;    /* Rowid for the inserted record */
119445  int regStat = iMem++;        /* Register to hold StatAccum object */
119446  int regChng = iMem++;        /* Index of changed index field */
119447  int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
119448  int regTemp = iMem++;        /* Temporary use register */
119449  int regTemp2 = iMem++;       /* Second temporary use register */
119450  int regTabname = iMem++;     /* Register containing table name */
119451  int regIdxname = iMem++;     /* Register containing index name */
119452  int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
119453  int regPrev = iMem;          /* MUST BE LAST (see below) */
119454#ifdef SQLITE_ENABLE_STAT4
119455  int doOnce = 1;              /* Flag for a one-time computation */
119456#endif
119457#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
119458  Table *pStat1 = 0;
119459#endif
119460
119461  sqlite3TouchRegister(pParse, iMem);
119462  assert( sqlite3NoTempsInRange(pParse, regNewRowid, iMem) );
119463  v = sqlite3GetVdbe(pParse);
119464  if( v==0 || NEVER(pTab==0) ){
119465    return;
119466  }
119467  if( !IsOrdinaryTable(pTab) ){
119468    /* Do not gather statistics on views or virtual tables */
119469    return;
119470  }
119471  if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){
119472    /* Do not gather statistics on system tables */
119473    return;
119474  }
119475  assert( sqlite3BtreeHoldsAllMutexes(db) );
119476  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
119477  assert( iDb>=0 );
119478  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
119479#ifndef SQLITE_OMIT_AUTHORIZATION
119480  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
119481      db->aDb[iDb].zDbSName ) ){
119482    return;
119483  }
119484#endif
119485
119486#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
119487  if( db->xPreUpdateCallback ){
119488    pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13);
119489    if( pStat1==0 ) return;
119490    pStat1->zName = (char*)&pStat1[1];
119491    memcpy(pStat1->zName, "sqlite_stat1", 13);
119492    pStat1->nCol = 3;
119493    pStat1->iPKey = -1;
119494    sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNAMIC);
119495  }
119496#endif
119497
119498  /* Establish a read-lock on the table at the shared-cache level.
119499  ** Open a read-only cursor on the table. Also allocate a cursor number
119500  ** to use for scanning indexes (iIdxCur). No index cursor is opened at
119501  ** this time though.  */
119502  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
119503  iTabCur = iTab++;
119504  iIdxCur = iTab++;
119505  pParse->nTab = MAX(pParse->nTab, iTab);
119506  sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
119507  sqlite3VdbeLoadString(v, regTabname, pTab->zName);
119508
119509  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
119510    int nCol;                     /* Number of columns in pIdx. "N" */
119511    int addrGotoEnd;               /* Address of "OP_Rewind iIdxCur" */
119512    int addrNextRow;              /* Address of "next_row:" */
119513    const char *zIdxName;         /* Name of the index */
119514    int nColTest;                 /* Number of columns to test for changes */
119515
119516    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
119517    if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
119518    if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
119519      nCol = pIdx->nKeyCol;
119520      zIdxName = pTab->zName;
119521      nColTest = nCol - 1;
119522    }else{
119523      nCol = pIdx->nColumn;
119524      zIdxName = pIdx->zName;
119525      nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
119526    }
119527
119528    /* Populate the register containing the index name. */
119529    sqlite3VdbeLoadString(v, regIdxname, zIdxName);
119530    VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
119531
119532    /*
119533    ** Pseudo-code for loop that calls stat_push():
119534    **
119535    **   regChng = 0
119536    **   Rewind csr
119537    **   if eof(csr){
119538    **      stat_init() with count = 0;
119539    **      goto end_of_scan;
119540    **   }
119541    **   count()
119542    **   stat_init()
119543    **   goto chng_addr_0;
119544    **
119545    **  next_row:
119546    **   regChng = 0
119547    **   if( idx(0) != regPrev(0) ) goto chng_addr_0
119548    **   regChng = 1
119549    **   if( idx(1) != regPrev(1) ) goto chng_addr_1
119550    **   ...
119551    **   regChng = N
119552    **   goto chng_addr_N
119553    **
119554    **  chng_addr_0:
119555    **   regPrev(0) = idx(0)
119556    **  chng_addr_1:
119557    **   regPrev(1) = idx(1)
119558    **  ...
119559    **
119560    **  endDistinctTest:
119561    **   regRowid = idx(rowid)
119562    **   stat_push(P, regChng, regRowid)
119563    **   Next csr
119564    **   if !eof(csr) goto next_row;
119565    **
119566    **  end_of_scan:
119567    */
119568
119569    /* Make sure there are enough memory cells allocated to accommodate
119570    ** the regPrev array and a trailing rowid (the rowid slot is required
119571    ** when building a record to insert into the sample column of
119572    ** the sqlite_stat4 table.  */
119573    sqlite3TouchRegister(pParse, regPrev+nColTest);
119574
119575    /* Open a read-only cursor on the index being analyzed. */
119576    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
119577    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
119578    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
119579    VdbeComment((v, "%s", pIdx->zName));
119580
119581    /* Implementation of the following:
119582    **
119583    **   regChng = 0
119584    **   Rewind csr
119585    **   if eof(csr){
119586    **      stat_init() with count = 0;
119587    **      goto end_of_scan;
119588    **   }
119589    **   count()
119590    **   stat_init()
119591    **   goto chng_addr_0;
119592    */
119593    assert( regTemp2==regStat+4 );
119594    sqlite3VdbeAddOp2(v, OP_Integer, db->nAnalysisLimit, regTemp2);
119595
119596    /* Arguments to stat_init():
119597    **    (1) the number of columns in the index including the rowid
119598    **        (or for a WITHOUT ROWID table, the number of PK columns),
119599    **    (2) the number of columns in the key without the rowid/pk
119600    **    (3) estimated number of rows in the index. */
119601    sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat+1);
119602    assert( regRowid==regStat+2 );
119603    sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regRowid);
119604    sqlite3VdbeAddOp3(v, OP_Count, iIdxCur, regTemp,
119605                      OptimizationDisabled(db, SQLITE_Stat4));
119606    sqlite3VdbeAddFunctionCall(pParse, 0, regStat+1, regStat, 4,
119607                               &statInitFuncdef, 0);
119608    addrGotoEnd = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
119609    VdbeCoverage(v);
119610
119611    sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
119612    addrNextRow = sqlite3VdbeCurrentAddr(v);
119613
119614    if( nColTest>0 ){
119615      int endDistinctTest = sqlite3VdbeMakeLabel(pParse);
119616      int *aGotoChng;               /* Array of jump instruction addresses */
119617      aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
119618      if( aGotoChng==0 ) continue;
119619
119620      /*
119621      **  next_row:
119622      **   regChng = 0
119623      **   if( idx(0) != regPrev(0) ) goto chng_addr_0
119624      **   regChng = 1
119625      **   if( idx(1) != regPrev(1) ) goto chng_addr_1
119626      **   ...
119627      **   regChng = N
119628      **   goto endDistinctTest
119629      */
119630      sqlite3VdbeAddOp0(v, OP_Goto);
119631      addrNextRow = sqlite3VdbeCurrentAddr(v);
119632      if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
119633        /* For a single-column UNIQUE index, once we have found a non-NULL
119634        ** row, we know that all the rest will be distinct, so skip
119635        ** subsequent distinctness tests. */
119636        sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
119637        VdbeCoverage(v);
119638      }
119639      for(i=0; i<nColTest; i++){
119640        char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
119641        sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
119642        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
119643        analyzeVdbeCommentIndexWithColumnName(v,pIdx,i);
119644        aGotoChng[i] =
119645        sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
119646        sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
119647        VdbeCoverage(v);
119648      }
119649      sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
119650      sqlite3VdbeGoto(v, endDistinctTest);
119651
119652
119653      /*
119654      **  chng_addr_0:
119655      **   regPrev(0) = idx(0)
119656      **  chng_addr_1:
119657      **   regPrev(1) = idx(1)
119658      **  ...
119659      */
119660      sqlite3VdbeJumpHere(v, addrNextRow-1);
119661      for(i=0; i<nColTest; i++){
119662        sqlite3VdbeJumpHere(v, aGotoChng[i]);
119663        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
119664        analyzeVdbeCommentIndexWithColumnName(v,pIdx,i);
119665      }
119666      sqlite3VdbeResolveLabel(v, endDistinctTest);
119667      sqlite3DbFree(db, aGotoChng);
119668    }
119669
119670    /*
119671    **  chng_addr_N:
119672    **   regRowid = idx(rowid)            // STAT4 only
119673    **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT4 only
119674    **   Next csr
119675    **   if !eof(csr) goto next_row;
119676    */
119677#ifdef SQLITE_ENABLE_STAT4
119678    if( OptimizationEnabled(db, SQLITE_Stat4) ){
119679      assert( regRowid==(regStat+2) );
119680      if( HasRowid(pTab) ){
119681        sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
119682      }else{
119683        Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
119684        int j, k, regKey;
119685        regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
119686        for(j=0; j<pPk->nKeyCol; j++){
119687          k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
119688          assert( k>=0 && k<pIdx->nColumn );
119689          sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
119690          analyzeVdbeCommentIndexWithColumnName(v,pIdx,k);
119691        }
119692        sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
119693        sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
119694      }
119695    }
119696#endif
119697    assert( regChng==(regStat+1) );
119698    {
119699      sqlite3VdbeAddFunctionCall(pParse, 1, regStat, regTemp, 2+IsStat4,
119700                                 &statPushFuncdef, 0);
119701      if( db->nAnalysisLimit ){
119702        int j1, j2, j3;
119703        j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regTemp); VdbeCoverage(v);
119704        j2 = sqlite3VdbeAddOp1(v, OP_If, regTemp); VdbeCoverage(v);
119705        j3 = sqlite3VdbeAddOp4Int(v, OP_SeekGT, iIdxCur, 0, regPrev, 1);
119706        VdbeCoverage(v);
119707        sqlite3VdbeJumpHere(v, j1);
119708        sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
119709        sqlite3VdbeJumpHere(v, j2);
119710        sqlite3VdbeJumpHere(v, j3);
119711      }else{
119712        sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
119713      }
119714    }
119715
119716    /* Add the entry to the stat1 table. */
119717    if( pIdx->pPartIdxWhere ){
119718      /* Partial indexes might get a zero-entry in sqlite_stat1.  But
119719      ** an empty table is omitted from sqlite_stat1. */
119720      sqlite3VdbeJumpHere(v, addrGotoEnd);
119721      addrGotoEnd = 0;
119722    }
119723    callStatGet(pParse, regStat, STAT_GET_STAT1, regStat1);
119724    assert( "BBB"[0]==SQLITE_AFF_TEXT );
119725    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
119726    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
119727    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
119728#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
119729    sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
119730#endif
119731    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
119732
119733    /* Add the entries to the stat4 table. */
119734#ifdef SQLITE_ENABLE_STAT4
119735    if( OptimizationEnabled(db, SQLITE_Stat4) && db->nAnalysisLimit==0 ){
119736      int regEq = regStat1;
119737      int regLt = regStat1+1;
119738      int regDLt = regStat1+2;
119739      int regSample = regStat1+3;
119740      int regCol = regStat1+4;
119741      int regSampleRowid = regCol + nCol;
119742      int addrNext;
119743      int addrIsNull;
119744      u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
119745
119746      /* No STAT4 data is generated if the number of rows is zero */
119747      if( addrGotoEnd==0 ){
119748        sqlite3VdbeAddOp2(v, OP_Cast, regStat1, SQLITE_AFF_INTEGER);
119749        addrGotoEnd = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
119750        VdbeCoverage(v);
119751      }
119752
119753      if( doOnce ){
119754        int mxCol = nCol;
119755        Index *pX;
119756
119757        /* Compute the maximum number of columns in any index */
119758        for(pX=pTab->pIndex; pX; pX=pX->pNext){
119759          int nColX;                     /* Number of columns in pX */
119760          if( !HasRowid(pTab) && IsPrimaryKeyIndex(pX) ){
119761            nColX = pX->nKeyCol;
119762          }else{
119763            nColX = pX->nColumn;
119764          }
119765          if( nColX>mxCol ) mxCol = nColX;
119766        }
119767
119768        /* Allocate space to compute results for the largest index */
119769        sqlite3TouchRegister(pParse, regCol+mxCol);
119770        doOnce = 0;
119771#ifdef SQLITE_DEBUG
119772        /* Verify that the call to sqlite3ClearTempRegCache() below
119773        ** really is needed.
119774        ** https://sqlite.org/forum/forumpost/83cb4a95a0 (2023-03-25)
119775        */
119776        testcase( !sqlite3NoTempsInRange(pParse, regEq, regCol+mxCol) );
119777#endif
119778        sqlite3ClearTempRegCache(pParse);  /* tag-20230325-1 */
119779        assert( sqlite3NoTempsInRange(pParse, regEq, regCol+mxCol) );
119780      }
119781      assert( sqlite3NoTempsInRange(pParse, regEq, regCol+nCol) );
119782
119783      addrNext = sqlite3VdbeCurrentAddr(v);
119784      callStatGet(pParse, regStat, STAT_GET_ROWID, regSampleRowid);
119785      addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
119786      VdbeCoverage(v);
119787      callStatGet(pParse, regStat, STAT_GET_NEQ, regEq);
119788      callStatGet(pParse, regStat, STAT_GET_NLT, regLt);
119789      callStatGet(pParse, regStat, STAT_GET_NDLT, regDLt);
119790      sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
119791      VdbeCoverage(v);
119792      for(i=0; i<nCol; i++){
119793        sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
119794      }
119795      sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
119796      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
119797      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
119798      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
119799      sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
119800      sqlite3VdbeJumpHere(v, addrIsNull);
119801    }
119802#endif /* SQLITE_ENABLE_STAT4 */
119803
119804    /* End of analysis */
119805    if( addrGotoEnd ) sqlite3VdbeJumpHere(v, addrGotoEnd);
119806  }
119807
119808
119809  /* Create a single sqlite_stat1 entry containing NULL as the index
119810  ** name and the row count as the content.
119811  */
119812  if( pOnlyIdx==0 && needTableCnt ){
119813    VdbeComment((v, "%s", pTab->zName));
119814    sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
119815    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
119816    sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
119817    assert( "BBB"[0]==SQLITE_AFF_TEXT );
119818    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
119819    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
119820    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
119821    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
119822#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
119823    sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
119824#endif
119825    sqlite3VdbeJumpHere(v, jZeroRows);
119826  }
119827}
119828
119829
119830/*
119831** Generate code that will cause the most recent index analysis to
119832** be loaded into internal hash tables where is can be used.
119833*/
119834static void loadAnalysis(Parse *pParse, int iDb){
119835  Vdbe *v = sqlite3GetVdbe(pParse);
119836  if( v ){
119837    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
119838  }
119839}
119840
119841/*
119842** Generate code that will do an analysis of an entire database
119843*/
119844static void analyzeDatabase(Parse *pParse, int iDb){
119845  sqlite3 *db = pParse->db;
119846  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
119847  HashElem *k;
119848  int iStatCur;
119849  int iMem;
119850  int iTab;
119851
119852  sqlite3BeginWriteOperation(pParse, 0, iDb);
119853  iStatCur = pParse->nTab;
119854  pParse->nTab += 3;
119855  openStatTable(pParse, iDb, iStatCur, 0, 0);
119856  iMem = pParse->nMem+1;
119857  iTab = pParse->nTab;
119858  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
119859  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
119860    Table *pTab = (Table*)sqliteHashData(k);
119861    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
119862#ifdef SQLITE_ENABLE_STAT4
119863    iMem = sqlite3FirstAvailableRegister(pParse, iMem);
119864#else
119865    assert( iMem==sqlite3FirstAvailableRegister(pParse,iMem) );
119866#endif
119867  }
119868  loadAnalysis(pParse, iDb);
119869}
119870
119871/*
119872** Generate code that will do an analysis of a single table in
119873** a database.  If pOnlyIdx is not NULL then it is a single index
119874** in pTab that should be analyzed.
119875*/
119876static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
119877  int iDb;
119878  int iStatCur;
119879
119880  assert( pTab!=0 );
119881  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
119882  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
119883  sqlite3BeginWriteOperation(pParse, 0, iDb);
119884  iStatCur = pParse->nTab;
119885  pParse->nTab += 3;
119886  if( pOnlyIdx ){
119887    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
119888  }else{
119889    openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
119890  }
119891  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
119892  loadAnalysis(pParse, iDb);
119893}
119894
119895/*
119896** Generate code for the ANALYZE command.  The parser calls this routine
119897** when it recognizes an ANALYZE command.
119898**
119899**        ANALYZE                            -- 1
119900**        ANALYZE  <database>                -- 2
119901**        ANALYZE  ?<database>.?<tablename>  -- 3
119902**
119903** Form 1 causes all indices in all attached databases to be analyzed.
119904** Form 2 analyzes all indices the single database named.
119905** Form 3 analyzes all indices associated with the named table.
119906*/
119907SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
119908  sqlite3 *db = pParse->db;
119909  int iDb;
119910  int i;
119911  char *z, *zDb;
119912  Table *pTab;
119913  Index *pIdx;
119914  Token *pTableName;
119915  Vdbe *v;
119916
119917  /* Read the database schema. If an error occurs, leave an error message
119918  ** and code in pParse and return NULL. */
119919  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
119920  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
119921    return;
119922  }
119923
119924  assert( pName2!=0 || pName1==0 );
119925  if( pName1==0 ){
119926    /* Form 1:  Analyze everything */
119927    for(i=0; i<db->nDb; i++){
119928      if( i==1 ) continue;  /* Do not analyze the TEMP database */
119929      analyzeDatabase(pParse, i);
119930    }
119931  }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
119932    /* Analyze the schema named as the argument */
119933    analyzeDatabase(pParse, iDb);
119934  }else{
119935    /* Form 3: Analyze the table or index named as an argument */
119936    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
119937    if( iDb>=0 ){
119938      zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
119939      z = sqlite3NameFromToken(db, pTableName);
119940      if( z ){
119941        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
119942          analyzeTable(pParse, pIdx->pTable, pIdx);
119943        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
119944          analyzeTable(pParse, pTab, 0);
119945        }
119946        sqlite3DbFree(db, z);
119947      }
119948    }
119949  }
119950  if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
119951    sqlite3VdbeAddOp0(v, OP_Expire);
119952  }
119953}
119954
119955/*
119956** Used to pass information from the analyzer reader through to the
119957** callback routine.
119958*/
119959typedef struct analysisInfo analysisInfo;
119960struct analysisInfo {
119961  sqlite3 *db;
119962  const char *zDatabase;
119963};
119964
119965/*
119966** The first argument points to a nul-terminated string containing a
119967** list of space separated integers. Read the first nOut of these into
119968** the array aOut[].
119969*/
119970static void decodeIntArray(
119971  char *zIntArray,       /* String containing int array to decode */
119972  int nOut,              /* Number of slots in aOut[] */
119973  tRowcnt *aOut,         /* Store integers here */
119974  LogEst *aLog,          /* Or, if aOut==0, here */
119975  Index *pIndex          /* Handle extra flags for this index, if not NULL */
119976){
119977  char *z = zIntArray;
119978  int c;
119979  int i;
119980  tRowcnt v;
119981
119982#ifdef SQLITE_ENABLE_STAT4
119983  if( z==0 ) z = "";
119984#else
119985  assert( z!=0 );
119986#endif
119987  for(i=0; *z && i<nOut; i++){
119988    v = 0;
119989    while( (c=z[0])>='0' && c<='9' ){
119990      v = v*10 + c - '0';
119991      z++;
119992    }
119993#ifdef SQLITE_ENABLE_STAT4
119994    if( aOut ) aOut[i] = v;
119995    if( aLog ) aLog[i] = sqlite3LogEst(v);
119996#else
119997    assert( aOut==0 );
119998    UNUSED_PARAMETER(aOut);
119999    assert( aLog!=0 );
120000    aLog[i] = sqlite3LogEst(v);
120001#endif
120002    if( *z==' ' ) z++;
120003  }
120004#ifndef SQLITE_ENABLE_STAT4
120005  assert( pIndex!=0 ); {
120006#else
120007  if( pIndex ){
120008#endif
120009    pIndex->bUnordered = 0;
120010    pIndex->noSkipScan = 0;
120011    while( z[0] ){
120012      if( sqlite3_strglob("unordered*", z)==0 ){
120013        pIndex->bUnordered = 1;
120014      }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
120015        int sz = sqlite3Atoi(z+3);
120016        if( sz<2 ) sz = 2;
120017        pIndex->szIdxRow = sqlite3LogEst(sz);
120018      }else if( sqlite3_strglob("noskipscan*", z)==0 ){
120019        pIndex->noSkipScan = 1;
120020      }
120021#ifdef SQLITE_ENABLE_COSTMULT
120022      else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
120023        pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
120024      }
120025#endif
120026      while( z[0]!=0 && z[0]!=' ' ) z++;
120027      while( z[0]==' ' ) z++;
120028    }
120029
120030    /* Set the bLowQual flag if the peak number of rows obtained
120031    ** from a full equality match is so large that a full table scan
120032    ** seems likely to be faster than using the index.
120033    */
120034    if( aLog[0] > 66              /* Index has more than 100 rows */
120035     && aLog[0] <= aLog[nOut-1]   /* And only a single value seen */
120036    ){
120037      pIndex->bLowQual = 1;
120038    }
120039  }
120040}
120041
120042/*
120043** This callback is invoked once for each index when reading the
120044** sqlite_stat1 table.
120045**
120046**     argv[0] = name of the table
120047**     argv[1] = name of the index (might be NULL)
120048**     argv[2] = results of analysis - on integer for each column
120049**
120050** Entries for which argv[1]==NULL simply record the number of rows in
120051** the table.
120052*/
120053static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
120054  analysisInfo *pInfo = (analysisInfo*)pData;
120055  Index *pIndex;
120056  Table *pTable;
120057  const char *z;
120058
120059  assert( argc==3 );
120060  UNUSED_PARAMETER2(NotUsed, argc);
120061
120062  if( argv==0 || argv[0]==0 || argv[2]==0 ){
120063    return 0;
120064  }
120065  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
120066  if( pTable==0 ){
120067    return 0;
120068  }
120069  if( argv[1]==0 ){
120070    pIndex = 0;
120071  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
120072    pIndex = sqlite3PrimaryKeyIndex(pTable);
120073  }else{
120074    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
120075  }
120076  z = argv[2];
120077
120078  if( pIndex ){
120079    tRowcnt *aiRowEst = 0;
120080    int nCol = pIndex->nKeyCol+1;
120081#ifdef SQLITE_ENABLE_STAT4
120082    /* Index.aiRowEst may already be set here if there are duplicate
120083    ** sqlite_stat1 entries for this index. In that case just clobber
120084    ** the old data with the new instead of allocating a new array.  */
120085    if( pIndex->aiRowEst==0 ){
120086      pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
120087      if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
120088    }
120089    aiRowEst = pIndex->aiRowEst;
120090#endif
120091    pIndex->bUnordered = 0;
120092    decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
120093    pIndex->hasStat1 = 1;
120094    if( pIndex->pPartIdxWhere==0 ){
120095      pTable->nRowLogEst = pIndex->aiRowLogEst[0];
120096      pTable->tabFlags |= TF_HasStat1;
120097    }
120098  }else{
120099    Index fakeIdx;
120100    fakeIdx.szIdxRow = pTable->szTabRow;
120101#ifdef SQLITE_ENABLE_COSTMULT
120102    fakeIdx.pTable = pTable;
120103#endif
120104    decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
120105    pTable->szTabRow = fakeIdx.szIdxRow;
120106    pTable->tabFlags |= TF_HasStat1;
120107  }
120108
120109  return 0;
120110}
120111
120112/*
120113** If the Index.aSample variable is not NULL, delete the aSample[] array
120114** and its contents.
120115*/
120116SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
120117  assert( db!=0 );
120118  assert( pIdx!=0 );
120119#ifdef SQLITE_ENABLE_STAT4
120120  if( pIdx->aSample ){
120121    int j;
120122    for(j=0; j<pIdx->nSample; j++){
120123      IndexSample *p = &pIdx->aSample[j];
120124      sqlite3DbFree(db, p->p);
120125    }
120126    sqlite3DbFree(db, pIdx->aSample);
120127  }
120128  if( db->pnBytesFreed==0 ){
120129    pIdx->nSample = 0;
120130    pIdx->aSample = 0;
120131  }
120132#else
120133  UNUSED_PARAMETER(db);
120134  UNUSED_PARAMETER(pIdx);
120135#endif /* SQLITE_ENABLE_STAT4 */
120136}
120137
120138#ifdef SQLITE_ENABLE_STAT4
120139/*
120140** Populate the pIdx->aAvgEq[] array based on the samples currently
120141** stored in pIdx->aSample[].
120142*/
120143static void initAvgEq(Index *pIdx){
120144  if( pIdx ){
120145    IndexSample *aSample = pIdx->aSample;
120146    IndexSample *pFinal = &aSample[pIdx->nSample-1];
120147    int iCol;
120148    int nCol = 1;
120149    if( pIdx->nSampleCol>1 ){
120150      /* If this is stat4 data, then calculate aAvgEq[] values for all
120151      ** sample columns except the last. The last is always set to 1, as
120152      ** once the trailing PK fields are considered all index keys are
120153      ** unique.  */
120154      nCol = pIdx->nSampleCol-1;
120155      pIdx->aAvgEq[nCol] = 1;
120156    }
120157    for(iCol=0; iCol<nCol; iCol++){
120158      int nSample = pIdx->nSample;
120159      int i;                    /* Used to iterate through samples */
120160      tRowcnt sumEq = 0;        /* Sum of the nEq values */
120161      tRowcnt avgEq = 0;
120162      tRowcnt nRow;             /* Number of rows in index */
120163      i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
120164      i64 nDist100;             /* Number of distinct values in index */
120165
120166      if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
120167        nRow = pFinal->anLt[iCol];
120168        nDist100 = (i64)100 * pFinal->anDLt[iCol];
120169        nSample--;
120170      }else{
120171        nRow = pIdx->aiRowEst[0];
120172        nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
120173      }
120174      pIdx->nRowEst0 = nRow;
120175
120176      /* Set nSum to the number of distinct (iCol+1) field prefixes that
120177      ** occur in the stat4 table for this index. Set sumEq to the sum of
120178      ** the nEq values for column iCol for the same set (adding the value
120179      ** only once where there exist duplicate prefixes).  */
120180      for(i=0; i<nSample; i++){
120181        if( i==(pIdx->nSample-1)
120182         || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
120183        ){
120184          sumEq += aSample[i].anEq[iCol];
120185          nSum100 += 100;
120186        }
120187      }
120188
120189      if( nDist100>nSum100 && sumEq<nRow ){
120190        avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
120191      }
120192      if( avgEq==0 ) avgEq = 1;
120193      pIdx->aAvgEq[iCol] = avgEq;
120194    }
120195  }
120196}
120197
120198/*
120199** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
120200** is supplied instead, find the PRIMARY KEY index for that table.
120201*/
120202static Index *findIndexOrPrimaryKey(
120203  sqlite3 *db,
120204  const char *zName,
120205  const char *zDb
120206){
120207  Index *pIdx = sqlite3FindIndex(db, zName, zDb);
120208  if( pIdx==0 ){
120209    Table *pTab = sqlite3FindTable(db, zName, zDb);
120210    if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
120211  }
120212  return pIdx;
120213}
120214
120215/*
120216** Load the content from either the sqlite_stat4
120217** into the relevant Index.aSample[] arrays.
120218**
120219** Arguments zSql1 and zSql2 must point to SQL statements that return
120220** data equivalent to the following:
120221**
120222**    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
120223**    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
120224**
120225** where %Q is replaced with the database name before the SQL is executed.
120226*/
120227static int loadStatTbl(
120228  sqlite3 *db,                  /* Database handle */
120229  const char *zSql1,            /* SQL statement 1 (see above) */
120230  const char *zSql2,            /* SQL statement 2 (see above) */
120231  const char *zDb               /* Database name (e.g. "main") */
120232){
120233  int rc;                       /* Result codes from subroutines */
120234  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
120235  char *zSql;                   /* Text of the SQL statement */
120236  Index *pPrevIdx = 0;          /* Previous index in the loop */
120237  IndexSample *pSample;         /* A slot in pIdx->aSample[] */
120238
120239  assert( db->lookaside.bDisable );
120240  zSql = sqlite3MPrintf(db, zSql1, zDb);
120241  if( !zSql ){
120242    return SQLITE_NOMEM_BKPT;
120243  }
120244  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
120245  sqlite3DbFree(db, zSql);
120246  if( rc ) return rc;
120247
120248  while( sqlite3_step(pStmt)==SQLITE_ROW ){
120249    int nIdxCol = 1;              /* Number of columns in stat4 records */
120250
120251    char *zIndex;   /* Index name */
120252    Index *pIdx;    /* Pointer to the index object */
120253    int nSample;    /* Number of samples */
120254    int nByte;      /* Bytes of space required */
120255    int i;          /* Bytes of space required */
120256    tRowcnt *pSpace;
120257
120258    zIndex = (char *)sqlite3_column_text(pStmt, 0);
120259    if( zIndex==0 ) continue;
120260    nSample = sqlite3_column_int(pStmt, 1);
120261    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
120262    assert( pIdx==0 || pIdx->nSample==0 );
120263    if( pIdx==0 ) continue;
120264    if( pIdx->aSample!=0 ){
120265      /* The same index appears in sqlite_stat4 under multiple names */
120266      continue;
120267    }
120268    assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
120269    if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
120270      nIdxCol = pIdx->nKeyCol;
120271    }else{
120272      nIdxCol = pIdx->nColumn;
120273    }
120274    pIdx->nSampleCol = nIdxCol;
120275    pIdx->mxSample = nSample;
120276    nByte = sizeof(IndexSample) * nSample;
120277    nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
120278    nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
120279
120280    pIdx->aSample = sqlite3DbMallocZero(db, nByte);
120281    if( pIdx->aSample==0 ){
120282      sqlite3_finalize(pStmt);
120283      return SQLITE_NOMEM_BKPT;
120284    }
120285    pSpace = (tRowcnt*)&pIdx->aSample[nSample];
120286    pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
120287    pIdx->pTable->tabFlags |= TF_HasStat4;
120288    for(i=0; i<nSample; i++){
120289      pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
120290      pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
120291      pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
120292    }
120293    assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
120294  }
120295  rc = sqlite3_finalize(pStmt);
120296  if( rc ) return rc;
120297
120298  zSql = sqlite3MPrintf(db, zSql2, zDb);
120299  if( !zSql ){
120300    return SQLITE_NOMEM_BKPT;
120301  }
120302  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
120303  sqlite3DbFree(db, zSql);
120304  if( rc ) return rc;
120305
120306  while( sqlite3_step(pStmt)==SQLITE_ROW ){
120307    char *zIndex;                 /* Index name */
120308    Index *pIdx;                  /* Pointer to the index object */
120309    int nCol = 1;                 /* Number of columns in index */
120310
120311    zIndex = (char *)sqlite3_column_text(pStmt, 0);
120312    if( zIndex==0 ) continue;
120313    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
120314    if( pIdx==0 ) continue;
120315    if( pIdx->nSample>=pIdx->mxSample ){
120316      /* Too many slots used because the same index appears in
120317      ** sqlite_stat4 using multiple names */
120318      continue;
120319    }
120320    /* This next condition is true if data has already been loaded from
120321    ** the sqlite_stat4 table. */
120322    nCol = pIdx->nSampleCol;
120323    if( pIdx!=pPrevIdx ){
120324      initAvgEq(pPrevIdx);
120325      pPrevIdx = pIdx;
120326    }
120327    pSample = &pIdx->aSample[pIdx->nSample];
120328    decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
120329    decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
120330    decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
120331
120332    /* Take a copy of the sample. Add 8 extra 0x00 bytes the end of the buffer.
120333    ** This is in case the sample record is corrupted. In that case, the
120334    ** sqlite3VdbeRecordCompare() may read up to two varints past the
120335    ** end of the allocated buffer before it realizes it is dealing with
120336    ** a corrupt record.  Or it might try to read a large integer from the
120337    ** buffer.  In any case, eight 0x00 bytes prevents this from causing
120338    ** a buffer overread.  */
120339    pSample->n = sqlite3_column_bytes(pStmt, 4);
120340    pSample->p = sqlite3DbMallocZero(db, pSample->n + 8);
120341    if( pSample->p==0 ){
120342      sqlite3_finalize(pStmt);
120343      return SQLITE_NOMEM_BKPT;
120344    }
120345    if( pSample->n ){
120346      memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
120347    }
120348    pIdx->nSample++;
120349  }
120350  rc = sqlite3_finalize(pStmt);
120351  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
120352  return rc;
120353}
120354
120355/*
120356** Load content from the sqlite_stat4 table into
120357** the Index.aSample[] arrays of all indices.
120358*/
120359static int loadStat4(sqlite3 *db, const char *zDb){
120360  int rc = SQLITE_OK;             /* Result codes from subroutines */
120361  const Table *pStat4;
120362
120363  assert( db->lookaside.bDisable );
120364  if( OptimizationEnabled(db, SQLITE_Stat4)
120365   && (pStat4 = sqlite3FindTable(db, "sqlite_stat4", zDb))!=0
120366   && IsOrdinaryTable(pStat4)
120367  ){
120368    rc = loadStatTbl(db,
120369      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx COLLATE nocase",
120370      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
120371      zDb
120372    );
120373  }
120374  return rc;
120375}
120376#endif /* SQLITE_ENABLE_STAT4 */
120377
120378/*
120379** Load the content of the sqlite_stat1 and sqlite_stat4 tables. The
120380** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
120381** arrays. The contents of sqlite_stat4 are used to populate the
120382** Index.aSample[] arrays.
120383**
120384** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
120385** is returned. In this case, even if SQLITE_ENABLE_STAT4 was defined
120386** during compilation and the sqlite_stat4 table is present, no data is
120387** read from it.
120388**
120389** If SQLITE_ENABLE_STAT4 was defined during compilation and the
120390** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
120391** returned. However, in this case, data is read from the sqlite_stat1
120392** table (if it is present) before returning.
120393**
120394** If an OOM error occurs, this function always sets db->mallocFailed.
120395** This means if the caller does not care about other errors, the return
120396** code may be ignored.
120397*/
120398SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
120399  analysisInfo sInfo;
120400  HashElem *i;
120401  char *zSql;
120402  int rc = SQLITE_OK;
120403  Schema *pSchema = db->aDb[iDb].pSchema;
120404  const Table *pStat1;
120405
120406  assert( iDb>=0 && iDb<db->nDb );
120407  assert( db->aDb[iDb].pBt!=0 );
120408
120409  /* Clear any prior statistics */
120410  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
120411  for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
120412    Table *pTab = sqliteHashData(i);
120413    pTab->tabFlags &= ~TF_HasStat1;
120414  }
120415  for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
120416    Index *pIdx = sqliteHashData(i);
120417    pIdx->hasStat1 = 0;
120418#ifdef SQLITE_ENABLE_STAT4
120419    sqlite3DeleteIndexSamples(db, pIdx);
120420    pIdx->aSample = 0;
120421#endif
120422  }
120423
120424  /* Load new statistics out of the sqlite_stat1 table */
120425  sInfo.db = db;
120426  sInfo.zDatabase = db->aDb[iDb].zDbSName;
120427  if( (pStat1 = sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase))
120428   && IsOrdinaryTable(pStat1)
120429  ){
120430    zSql = sqlite3MPrintf(db,
120431        "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
120432    if( zSql==0 ){
120433      rc = SQLITE_NOMEM_BKPT;
120434    }else{
120435      rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
120436      sqlite3DbFree(db, zSql);
120437    }
120438  }
120439
120440  /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
120441  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
120442  for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
120443    Index *pIdx = sqliteHashData(i);
120444    if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
120445  }
120446
120447  /* Load the statistics from the sqlite_stat4 table. */
120448#ifdef SQLITE_ENABLE_STAT4
120449  if( rc==SQLITE_OK ){
120450    DisableLookaside;
120451    rc = loadStat4(db, sInfo.zDatabase);
120452    EnableLookaside;
120453  }
120454  for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
120455    Index *pIdx = sqliteHashData(i);
120456    sqlite3_free(pIdx->aiRowEst);
120457    pIdx->aiRowEst = 0;
120458  }
120459#endif
120460
120461  if( rc==SQLITE_NOMEM ){
120462    sqlite3OomFault(db);
120463  }
120464  return rc;
120465}
120466
120467
120468#endif /* SQLITE_OMIT_ANALYZE */
120469
120470/************** End of analyze.c *********************************************/
120471/************** Begin file attach.c ******************************************/
120472/*
120473** 2003 April 6
120474**
120475** The author disclaims copyright to this source code.  In place of
120476** a legal notice, here is a blessing:
120477**
120478**    May you do good and not evil.
120479**    May you find forgiveness for yourself and forgive others.
120480**    May you share freely, never taking more than you give.
120481**
120482*************************************************************************
120483** This file contains code used to implement the ATTACH and DETACH commands.
120484*/
120485/* #include "sqliteInt.h" */
120486
120487#ifndef SQLITE_OMIT_ATTACH
120488/*
120489** Resolve an expression that was part of an ATTACH or DETACH statement. This
120490** is slightly different from resolving a normal SQL expression, because simple
120491** identifiers are treated as strings, not possible column names or aliases.
120492**
120493** i.e. if the parser sees:
120494**
120495**     ATTACH DATABASE abc AS def
120496**
120497** it treats the two expressions as literal strings 'abc' and 'def' instead of
120498** looking for columns of the same name.
120499**
120500** This only applies to the root node of pExpr, so the statement:
120501**
120502**     ATTACH DATABASE abc||def AS 'db2'
120503**
120504** will fail because neither abc or def can be resolved.
120505*/
120506static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
120507{
120508  int rc = SQLITE_OK;
120509  if( pExpr ){
120510    if( pExpr->op!=TK_ID ){
120511      rc = sqlite3ResolveExprNames(pName, pExpr);
120512    }else{
120513      pExpr->op = TK_STRING;
120514    }
120515  }
120516  return rc;
120517}
120518
120519/*
120520** Return true if zName points to a name that may be used to refer to
120521** database iDb attached to handle db.
120522*/
120523SQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName){
120524  return (
120525      sqlite3StrICmp(db->aDb[iDb].zDbSName, zName)==0
120526   || (iDb==0 && sqlite3StrICmp("main", zName)==0)
120527  );
120528}
120529
120530/*
120531** An SQL user-function registered to do the work of an ATTACH statement. The
120532** three arguments to the function come directly from an attach statement:
120533**
120534**     ATTACH DATABASE x AS y KEY z
120535**
120536**     SELECT sqlite_attach(x, y, z)
120537**
120538** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
120539** third argument.
120540**
120541** If the db->init.reopenMemdb flags is set, then instead of attaching a
120542** new database, close the database on db->init.iDb and reopen it as an
120543** empty MemDB.
120544*/
120545static void attachFunc(
120546  sqlite3_context *context,
120547  int NotUsed,
120548  sqlite3_value **argv
120549){
120550  int i;
120551  int rc = 0;
120552  sqlite3 *db = sqlite3_context_db_handle(context);
120553  const char *zName;
120554  const char *zFile;
120555  char *zPath = 0;
120556  char *zErr = 0;
120557  unsigned int flags;
120558  Db *aNew;                 /* New array of Db pointers */
120559  Db *pNew = 0;             /* Db object for the newly attached database */
120560  char *zErrDyn = 0;
120561  sqlite3_vfs *pVfs;
120562
120563  UNUSED_PARAMETER(NotUsed);
120564  zFile = (const char *)sqlite3_value_text(argv[0]);
120565  zName = (const char *)sqlite3_value_text(argv[1]);
120566  if( zFile==0 ) zFile = "";
120567  if( zName==0 ) zName = "";
120568
120569#ifndef SQLITE_OMIT_DESERIALIZE
120570# define REOPEN_AS_MEMDB(db)  (db->init.reopenMemdb)
120571#else
120572# define REOPEN_AS_MEMDB(db)  (0)
120573#endif
120574
120575  if( REOPEN_AS_MEMDB(db) ){
120576    /* This is not a real ATTACH.  Instead, this routine is being called
120577    ** from sqlite3_deserialize() to close database db->init.iDb and
120578    ** reopen it as a MemDB */
120579    Btree *pNewBt = 0;
120580    pVfs = sqlite3_vfs_find("memdb");
120581    if( pVfs==0 ) return;
120582    rc = sqlite3BtreeOpen(pVfs, "x\0", db, &pNewBt, 0, SQLITE_OPEN_MAIN_DB);
120583    if( rc==SQLITE_OK ){
120584      Schema *pNewSchema = sqlite3SchemaGet(db, pNewBt);
120585      if( pNewSchema ){
120586        /* Both the Btree and the new Schema were allocated successfully.
120587        ** Close the old db and update the aDb[] slot with the new memdb
120588        ** values.  */
120589        pNew = &db->aDb[db->init.iDb];
120590        if( ALWAYS(pNew->pBt) ) sqlite3BtreeClose(pNew->pBt);
120591        pNew->pBt = pNewBt;
120592        pNew->pSchema = pNewSchema;
120593      }else{
120594        sqlite3BtreeClose(pNewBt);
120595        rc = SQLITE_NOMEM;
120596      }
120597    }
120598    if( rc ) goto attach_error;
120599  }else{
120600    /* This is a real ATTACH
120601    **
120602    ** Check for the following errors:
120603    **
120604    **     * Too many attached databases,
120605    **     * Transaction currently open
120606    **     * Specified database name already being used.
120607    */
120608    if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
120609      zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
120610        db->aLimit[SQLITE_LIMIT_ATTACHED]
120611      );
120612      goto attach_error;
120613    }
120614    for(i=0; i<db->nDb; i++){
120615      assert( zName );
120616      if( sqlite3DbIsNamed(db, i, zName) ){
120617        zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
120618        goto attach_error;
120619      }
120620    }
120621
120622    /* Allocate the new entry in the db->aDb[] array and initialize the schema
120623    ** hash tables.
120624    */
120625    if( db->aDb==db->aDbStatic ){
120626      aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
120627      if( aNew==0 ) return;
120628      memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
120629    }else{
120630      aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
120631      if( aNew==0 ) return;
120632    }
120633    db->aDb = aNew;
120634    pNew = &db->aDb[db->nDb];
120635    memset(pNew, 0, sizeof(*pNew));
120636
120637    /* Open the database file. If the btree is successfully opened, use
120638    ** it to obtain the database schema. At this point the schema may
120639    ** or may not be initialized.
120640    */
120641    flags = db->openFlags;
120642    rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
120643    if( rc!=SQLITE_OK ){
120644      if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
120645      sqlite3_result_error(context, zErr, -1);
120646      sqlite3_free(zErr);
120647      return;
120648    }
120649    assert( pVfs );
120650    flags |= SQLITE_OPEN_MAIN_DB;
120651    rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
120652    db->nDb++;
120653    pNew->zDbSName = sqlite3DbStrDup(db, zName);
120654  }
120655  db->noSharedCache = 0;
120656  if( rc==SQLITE_CONSTRAINT ){
120657    rc = SQLITE_ERROR;
120658    zErrDyn = sqlite3MPrintf(db, "database is already attached");
120659  }else if( rc==SQLITE_OK ){
120660    Pager *pPager;
120661    pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
120662    if( !pNew->pSchema ){
120663      rc = SQLITE_NOMEM_BKPT;
120664    }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
120665      zErrDyn = sqlite3MPrintf(db,
120666        "attached databases must use the same text encoding as main database");
120667      rc = SQLITE_ERROR;
120668    }
120669    sqlite3BtreeEnter(pNew->pBt);
120670    pPager = sqlite3BtreePager(pNew->pBt);
120671    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
120672    sqlite3BtreeSecureDelete(pNew->pBt,
120673                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
120674#ifndef SQLITE_OMIT_PAGER_PRAGMAS
120675    sqlite3BtreeSetPagerFlags(pNew->pBt,
120676                      PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
120677#endif
120678    sqlite3BtreeLeave(pNew->pBt);
120679  }
120680  pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
120681  if( rc==SQLITE_OK && pNew->zDbSName==0 ){
120682    rc = SQLITE_NOMEM_BKPT;
120683  }
120684  sqlite3_free_filename( zPath );
120685
120686  /* If the file was opened successfully, read the schema for the new database.
120687  ** If this fails, or if opening the file failed, then close the file and
120688  ** remove the entry from the db->aDb[] array. i.e. put everything back the
120689  ** way we found it.
120690  */
120691  if( rc==SQLITE_OK ){
120692    sqlite3BtreeEnterAll(db);
120693    db->init.iDb = 0;
120694    db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);
120695    if( !REOPEN_AS_MEMDB(db) ){
120696      rc = sqlite3Init(db, &zErrDyn);
120697    }
120698    sqlite3BtreeLeaveAll(db);
120699    assert( zErrDyn==0 || rc!=SQLITE_OK );
120700  }
120701#ifdef SQLITE_USER_AUTHENTICATION
120702  if( rc==SQLITE_OK && !REOPEN_AS_MEMDB(db) ){
120703    u8 newAuth = 0;
120704    rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
120705    if( newAuth<db->auth.authLevel ){
120706      rc = SQLITE_AUTH_USER;
120707    }
120708  }
120709#endif
120710  if( rc ){
120711    if( ALWAYS(!REOPEN_AS_MEMDB(db)) ){
120712      int iDb = db->nDb - 1;
120713      assert( iDb>=2 );
120714      if( db->aDb[iDb].pBt ){
120715        sqlite3BtreeClose(db->aDb[iDb].pBt);
120716        db->aDb[iDb].pBt = 0;
120717        db->aDb[iDb].pSchema = 0;
120718      }
120719      sqlite3ResetAllSchemasOfConnection(db);
120720      db->nDb = iDb;
120721      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
120722        sqlite3OomFault(db);
120723        sqlite3DbFree(db, zErrDyn);
120724        zErrDyn = sqlite3MPrintf(db, "out of memory");
120725      }else if( zErrDyn==0 ){
120726        zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
120727      }
120728    }
120729    goto attach_error;
120730  }
120731
120732  return;
120733
120734attach_error:
120735  /* Return an error if we get here */
120736  if( zErrDyn ){
120737    sqlite3_result_error(context, zErrDyn, -1);
120738    sqlite3DbFree(db, zErrDyn);
120739  }
120740  if( rc ) sqlite3_result_error_code(context, rc);
120741}
120742
120743/*
120744** An SQL user-function registered to do the work of an DETACH statement. The
120745** three arguments to the function come directly from a detach statement:
120746**
120747**     DETACH DATABASE x
120748**
120749**     SELECT sqlite_detach(x)
120750*/
120751static void detachFunc(
120752  sqlite3_context *context,
120753  int NotUsed,
120754  sqlite3_value **argv
120755){
120756  const char *zName = (const char *)sqlite3_value_text(argv[0]);
120757  sqlite3 *db = sqlite3_context_db_handle(context);
120758  int i;
120759  Db *pDb = 0;
120760  HashElem *pEntry;
120761  char zErr[128];
120762
120763  UNUSED_PARAMETER(NotUsed);
120764
120765  if( zName==0 ) zName = "";
120766  for(i=0; i<db->nDb; i++){
120767    pDb = &db->aDb[i];
120768    if( pDb->pBt==0 ) continue;
120769    if( sqlite3DbIsNamed(db, i, zName) ) break;
120770  }
120771
120772  if( i>=db->nDb ){
120773    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
120774    goto detach_error;
120775  }
120776  if( i<2 ){
120777    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
120778    goto detach_error;
120779  }
120780  if( sqlite3BtreeTxnState(pDb->pBt)!=SQLITE_TXN_NONE
120781   || sqlite3BtreeIsInBackup(pDb->pBt)
120782  ){
120783    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
120784    goto detach_error;
120785  }
120786
120787  /* If any TEMP triggers reference the schema being detached, move those
120788  ** triggers to reference the TEMP schema itself. */
120789  assert( db->aDb[1].pSchema );
120790  pEntry = sqliteHashFirst(&db->aDb[1].pSchema->trigHash);
120791  while( pEntry ){
120792    Trigger *pTrig = (Trigger*)sqliteHashData(pEntry);
120793    if( pTrig->pTabSchema==pDb->pSchema ){
120794      pTrig->pTabSchema = pTrig->pSchema;
120795    }
120796    pEntry = sqliteHashNext(pEntry);
120797  }
120798
120799  sqlite3BtreeClose(pDb->pBt);
120800  pDb->pBt = 0;
120801  pDb->pSchema = 0;
120802  sqlite3CollapseDatabaseArray(db);
120803  return;
120804
120805detach_error:
120806  sqlite3_result_error(context, zErr, -1);
120807}
120808
120809/*
120810** This procedure generates VDBE code for a single invocation of either the
120811** sqlite_detach() or sqlite_attach() SQL user functions.
120812*/
120813static void codeAttach(
120814  Parse *pParse,       /* The parser context */
120815  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
120816  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
120817  Expr *pAuthArg,      /* Expression to pass to authorization callback */
120818  Expr *pFilename,     /* Name of database file */
120819  Expr *pDbname,       /* Name of the database to use internally */
120820  Expr *pKey           /* Database key for encryption extension */
120821){
120822  int rc;
120823  NameContext sName;
120824  Vdbe *v;
120825  sqlite3* db = pParse->db;
120826  int regArgs;
120827
120828  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto attach_end;
120829
120830  if( pParse->nErr ) goto attach_end;
120831  memset(&sName, 0, sizeof(NameContext));
120832  sName.pParse = pParse;
120833
120834  if(
120835      SQLITE_OK!=resolveAttachExpr(&sName, pFilename) ||
120836      SQLITE_OK!=resolveAttachExpr(&sName, pDbname) ||
120837      SQLITE_OK!=resolveAttachExpr(&sName, pKey)
120838  ){
120839    goto attach_end;
120840  }
120841
120842#ifndef SQLITE_OMIT_AUTHORIZATION
120843  if( ALWAYS(pAuthArg) ){
120844    char *zAuthArg;
120845    if( pAuthArg->op==TK_STRING ){
120846      assert( !ExprHasProperty(pAuthArg, EP_IntValue) );
120847      zAuthArg = pAuthArg->u.zToken;
120848    }else{
120849      zAuthArg = 0;
120850    }
120851    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
120852    if(rc!=SQLITE_OK ){
120853      goto attach_end;
120854    }
120855  }
120856#endif /* SQLITE_OMIT_AUTHORIZATION */
120857
120858
120859  v = sqlite3GetVdbe(pParse);
120860  regArgs = sqlite3GetTempRange(pParse, 4);
120861  sqlite3ExprCode(pParse, pFilename, regArgs);
120862  sqlite3ExprCode(pParse, pDbname, regArgs+1);
120863  sqlite3ExprCode(pParse, pKey, regArgs+2);
120864
120865  assert( v || db->mallocFailed );
120866  if( v ){
120867    sqlite3VdbeAddFunctionCall(pParse, 0, regArgs+3-pFunc->nArg, regArgs+3,
120868                               pFunc->nArg, pFunc, 0);
120869    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
120870    ** statement only). For DETACH, set it to false (expire all existing
120871    ** statements).
120872    */
120873    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
120874  }
120875
120876attach_end:
120877  sqlite3ExprDelete(db, pFilename);
120878  sqlite3ExprDelete(db, pDbname);
120879  sqlite3ExprDelete(db, pKey);
120880}
120881
120882/*
120883** Called by the parser to compile a DETACH statement.
120884**
120885**     DETACH pDbname
120886*/
120887SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
120888  static const FuncDef detach_func = {
120889    1,                /* nArg */
120890    SQLITE_UTF8,      /* funcFlags */
120891    0,                /* pUserData */
120892    0,                /* pNext */
120893    detachFunc,       /* xSFunc */
120894    0,                /* xFinalize */
120895    0, 0,             /* xValue, xInverse */
120896    "sqlite_detach",  /* zName */
120897    {0}
120898  };
120899  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
120900}
120901
120902/*
120903** Called by the parser to compile an ATTACH statement.
120904**
120905**     ATTACH p AS pDbname KEY pKey
120906*/
120907SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
120908  static const FuncDef attach_func = {
120909    3,                /* nArg */
120910    SQLITE_UTF8,      /* funcFlags */
120911    0,                /* pUserData */
120912    0,                /* pNext */
120913    attachFunc,       /* xSFunc */
120914    0,                /* xFinalize */
120915    0, 0,             /* xValue, xInverse */
120916    "sqlite_attach",  /* zName */
120917    {0}
120918  };
120919  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
120920}
120921#endif /* SQLITE_OMIT_ATTACH */
120922
120923/*
120924** Expression callback used by sqlite3FixAAAA() routines.
120925*/
120926static int fixExprCb(Walker *p, Expr *pExpr){
120927  DbFixer *pFix = p->u.pFix;
120928  if( !pFix->bTemp ) ExprSetProperty(pExpr, EP_FromDDL);
120929  if( pExpr->op==TK_VARIABLE ){
120930    if( pFix->pParse->db->init.busy ){
120931      pExpr->op = TK_NULL;
120932    }else{
120933      sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
120934      return WRC_Abort;
120935    }
120936  }
120937  return WRC_Continue;
120938}
120939
120940/*
120941** Select callback used by sqlite3FixAAAA() routines.
120942*/
120943static int fixSelectCb(Walker *p, Select *pSelect){
120944  DbFixer *pFix = p->u.pFix;
120945  int i;
120946  SrcItem *pItem;
120947  sqlite3 *db = pFix->pParse->db;
120948  int iDb = sqlite3FindDbName(db, pFix->zDb);
120949  SrcList *pList = pSelect->pSrc;
120950
120951  if( NEVER(pList==0) ) return WRC_Continue;
120952  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
120953    if( pFix->bTemp==0 ){
120954      if( pItem->zDatabase ){
120955        if( iDb!=sqlite3FindDbName(db, pItem->zDatabase) ){
120956          sqlite3ErrorMsg(pFix->pParse,
120957              "%s %T cannot reference objects in database %s",
120958              pFix->zType, pFix->pName, pItem->zDatabase);
120959          return WRC_Abort;
120960        }
120961        sqlite3DbFree(db, pItem->zDatabase);
120962        pItem->zDatabase = 0;
120963        pItem->fg.notCte = 1;
120964      }
120965      pItem->pSchema = pFix->pSchema;
120966      pItem->fg.fromDDL = 1;
120967    }
120968#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
120969    if( pList->a[i].fg.isUsing==0
120970     && sqlite3WalkExpr(&pFix->w, pList->a[i].u3.pOn)
120971    ){
120972      return WRC_Abort;
120973    }
120974#endif
120975  }
120976  if( pSelect->pWith ){
120977    for(i=0; i<pSelect->pWith->nCte; i++){
120978      if( sqlite3WalkSelect(p, pSelect->pWith->a[i].pSelect) ){
120979        return WRC_Abort;
120980      }
120981    }
120982  }
120983  return WRC_Continue;
120984}
120985
120986/*
120987** Initialize a DbFixer structure.  This routine must be called prior
120988** to passing the structure to one of the sqliteFixAAAA() routines below.
120989*/
120990SQLITE_PRIVATE void sqlite3FixInit(
120991  DbFixer *pFix,      /* The fixer to be initialized */
120992  Parse *pParse,      /* Error messages will be written here */
120993  int iDb,            /* This is the database that must be used */
120994  const char *zType,  /* "view", "trigger", or "index" */
120995  const Token *pName  /* Name of the view, trigger, or index */
120996){
120997  sqlite3 *db = pParse->db;
120998  assert( db->nDb>iDb );
120999  pFix->pParse = pParse;
121000  pFix->zDb = db->aDb[iDb].zDbSName;
121001  pFix->pSchema = db->aDb[iDb].pSchema;
121002  pFix->zType = zType;
121003  pFix->pName = pName;
121004  pFix->bTemp = (iDb==1);
121005  pFix->w.pParse = pParse;
121006  pFix->w.xExprCallback = fixExprCb;
121007  pFix->w.xSelectCallback = fixSelectCb;
121008  pFix->w.xSelectCallback2 = sqlite3WalkWinDefnDummyCallback;
121009  pFix->w.walkerDepth = 0;
121010  pFix->w.eCode = 0;
121011  pFix->w.u.pFix = pFix;
121012}
121013
121014/*
121015** The following set of routines walk through the parse tree and assign
121016** a specific database to all table references where the database name
121017** was left unspecified in the original SQL statement.  The pFix structure
121018** must have been initialized by a prior call to sqlite3FixInit().
121019**
121020** These routines are used to make sure that an index, trigger, or
121021** view in one database does not refer to objects in a different database.
121022** (Exception: indices, triggers, and views in the TEMP database are
121023** allowed to refer to anything.)  If a reference is explicitly made
121024** to an object in a different database, an error message is added to
121025** pParse->zErrMsg and these routines return non-zero.  If everything
121026** checks out, these routines return 0.
121027*/
121028SQLITE_PRIVATE int sqlite3FixSrcList(
121029  DbFixer *pFix,       /* Context of the fixation */
121030  SrcList *pList       /* The Source list to check and modify */
121031){
121032  int res = 0;
121033  if( pList ){
121034    Select s;
121035    memset(&s, 0, sizeof(s));
121036    s.pSrc = pList;
121037    res = sqlite3WalkSelect(&pFix->w, &s);
121038  }
121039  return res;
121040}
121041#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
121042SQLITE_PRIVATE int sqlite3FixSelect(
121043  DbFixer *pFix,       /* Context of the fixation */
121044  Select *pSelect      /* The SELECT statement to be fixed to one database */
121045){
121046  return sqlite3WalkSelect(&pFix->w, pSelect);
121047}
121048SQLITE_PRIVATE int sqlite3FixExpr(
121049  DbFixer *pFix,     /* Context of the fixation */
121050  Expr *pExpr        /* The expression to be fixed to one database */
121051){
121052  return sqlite3WalkExpr(&pFix->w, pExpr);
121053}
121054#endif
121055
121056#ifndef SQLITE_OMIT_TRIGGER
121057SQLITE_PRIVATE int sqlite3FixTriggerStep(
121058  DbFixer *pFix,     /* Context of the fixation */
121059  TriggerStep *pStep /* The trigger step be fixed to one database */
121060){
121061  while( pStep ){
121062    if( sqlite3WalkSelect(&pFix->w, pStep->pSelect)
121063     || sqlite3WalkExpr(&pFix->w, pStep->pWhere)
121064     || sqlite3WalkExprList(&pFix->w, pStep->pExprList)
121065     || sqlite3FixSrcList(pFix, pStep->pFrom)
121066    ){
121067      return 1;
121068    }
121069#ifndef SQLITE_OMIT_UPSERT
121070    {
121071      Upsert *pUp;
121072      for(pUp=pStep->pUpsert; pUp; pUp=pUp->pNextUpsert){
121073        if( sqlite3WalkExprList(&pFix->w, pUp->pUpsertTarget)
121074         || sqlite3WalkExpr(&pFix->w, pUp->pUpsertTargetWhere)
121075         || sqlite3WalkExprList(&pFix->w, pUp->pUpsertSet)
121076         || sqlite3WalkExpr(&pFix->w, pUp->pUpsertWhere)
121077        ){
121078          return 1;
121079        }
121080      }
121081    }
121082#endif
121083    pStep = pStep->pNext;
121084  }
121085
121086  return 0;
121087}
121088#endif
121089
121090/************** End of attach.c **********************************************/
121091/************** Begin file auth.c ********************************************/
121092/*
121093** 2003 January 11
121094**
121095** The author disclaims copyright to this source code.  In place of
121096** a legal notice, here is a blessing:
121097**
121098**    May you do good and not evil.
121099**    May you find forgiveness for yourself and forgive others.
121100**    May you share freely, never taking more than you give.
121101**
121102*************************************************************************
121103** This file contains code used to implement the sqlite3_set_authorizer()
121104** API.  This facility is an optional feature of the library.  Embedded
121105** systems that do not need this facility may omit it by recompiling
121106** the library with -DSQLITE_OMIT_AUTHORIZATION=1
121107*/
121108/* #include "sqliteInt.h" */
121109
121110/*
121111** All of the code in this file may be omitted by defining a single
121112** macro.
121113*/
121114#ifndef SQLITE_OMIT_AUTHORIZATION
121115
121116/*
121117** Set or clear the access authorization function.
121118**
121119** The access authorization function is be called during the compilation
121120** phase to verify that the user has read and/or write access permission on
121121** various fields of the database.  The first argument to the auth function
121122** is a copy of the 3rd argument to this routine.  The second argument
121123** to the auth function is one of these constants:
121124**
121125**       SQLITE_CREATE_INDEX
121126**       SQLITE_CREATE_TABLE
121127**       SQLITE_CREATE_TEMP_INDEX
121128**       SQLITE_CREATE_TEMP_TABLE
121129**       SQLITE_CREATE_TEMP_TRIGGER
121130**       SQLITE_CREATE_TEMP_VIEW
121131**       SQLITE_CREATE_TRIGGER
121132**       SQLITE_CREATE_VIEW
121133**       SQLITE_DELETE
121134**       SQLITE_DROP_INDEX
121135**       SQLITE_DROP_TABLE
121136**       SQLITE_DROP_TEMP_INDEX
121137**       SQLITE_DROP_TEMP_TABLE
121138**       SQLITE_DROP_TEMP_TRIGGER
121139**       SQLITE_DROP_TEMP_VIEW
121140**       SQLITE_DROP_TRIGGER
121141**       SQLITE_DROP_VIEW
121142**       SQLITE_INSERT
121143**       SQLITE_PRAGMA
121144**       SQLITE_READ
121145**       SQLITE_SELECT
121146**       SQLITE_TRANSACTION
121147**       SQLITE_UPDATE
121148**
121149** The third and fourth arguments to the auth function are the name of
121150** the table and the column that are being accessed.  The auth function
121151** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
121152** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
121153** means that the SQL statement will never-run - the sqlite3_exec() call
121154** will return with an error.  SQLITE_IGNORE means that the SQL statement
121155** should run but attempts to read the specified column will return NULL
121156** and attempts to write the column will be ignored.
121157**
121158** Setting the auth function to NULL disables this hook.  The default
121159** setting of the auth function is NULL.
121160*/
121161SQLITE_API int sqlite3_set_authorizer(
121162  sqlite3 *db,
121163  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
121164  void *pArg
121165){
121166#ifdef SQLITE_ENABLE_API_ARMOR
121167  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
121168#endif
121169  sqlite3_mutex_enter(db->mutex);
121170  db->xAuth = (sqlite3_xauth)xAuth;
121171  db->pAuthArg = pArg;
121172  if( db->xAuth ) sqlite3ExpirePreparedStatements(db, 1);
121173  sqlite3_mutex_leave(db->mutex);
121174  return SQLITE_OK;
121175}
121176
121177/*
121178** Write an error message into pParse->zErrMsg that explains that the
121179** user-supplied authorization function returned an illegal value.
121180*/
121181static void sqliteAuthBadReturnCode(Parse *pParse){
121182  sqlite3ErrorMsg(pParse, "authorizer malfunction");
121183  pParse->rc = SQLITE_ERROR;
121184}
121185
121186/*
121187** Invoke the authorization callback for permission to read column zCol from
121188** table zTab in database zDb. This function assumes that an authorization
121189** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
121190**
121191** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
121192** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
121193** is treated as SQLITE_DENY. In this case an error is left in pParse.
121194*/
121195SQLITE_PRIVATE int sqlite3AuthReadCol(
121196  Parse *pParse,                  /* The parser context */
121197  const char *zTab,               /* Table name */
121198  const char *zCol,               /* Column name */
121199  int iDb                         /* Index of containing database. */
121200){
121201  sqlite3 *db = pParse->db;          /* Database handle */
121202  char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
121203  int rc;                            /* Auth callback return code */
121204
121205  if( db->init.busy ) return SQLITE_OK;
121206  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
121207#ifdef SQLITE_USER_AUTHENTICATION
121208                 ,db->auth.zAuthUser
121209#endif
121210                );
121211  if( rc==SQLITE_DENY ){
121212    char *z = sqlite3_mprintf("%s.%s", zTab, zCol);
121213    if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
121214    sqlite3ErrorMsg(pParse, "access to %z is prohibited", z);
121215    pParse->rc = SQLITE_AUTH;
121216  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
121217    sqliteAuthBadReturnCode(pParse);
121218  }
121219  return rc;
121220}
121221
121222/*
121223** The pExpr should be a TK_COLUMN expression.  The table referred to
121224** is in pTabList or else it is the NEW or OLD table of a trigger.
121225** Check to see if it is OK to read this particular column.
121226**
121227** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
121228** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
121229** then generate an error.
121230*/
121231SQLITE_PRIVATE void sqlite3AuthRead(
121232  Parse *pParse,        /* The parser context */
121233  Expr *pExpr,          /* The expression to check authorization on */
121234  Schema *pSchema,      /* The schema of the expression */
121235  SrcList *pTabList     /* All table that pExpr might refer to */
121236){
121237  Table *pTab = 0;      /* The table being read */
121238  const char *zCol;     /* Name of the column of the table */
121239  int iSrc;             /* Index in pTabList->a[] of table being read */
121240  int iDb;              /* The index of the database the expression refers to */
121241  int iCol;             /* Index of column in table */
121242
121243  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
121244  assert( !IN_RENAME_OBJECT );
121245  assert( pParse->db->xAuth!=0 );
121246  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
121247  if( iDb<0 ){
121248    /* An attempt to read a column out of a subquery or other
121249    ** temporary table. */
121250    return;
121251  }
121252
121253  if( pExpr->op==TK_TRIGGER ){
121254    pTab = pParse->pTriggerTab;
121255  }else{
121256    assert( pTabList );
121257    for(iSrc=0; iSrc<pTabList->nSrc; iSrc++){
121258      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
121259        pTab = pTabList->a[iSrc].pTab;
121260        break;
121261      }
121262    }
121263  }
121264  iCol = pExpr->iColumn;
121265  if( pTab==0 ) return;
121266
121267  if( iCol>=0 ){
121268    assert( iCol<pTab->nCol );
121269    zCol = pTab->aCol[iCol].zCnName;
121270  }else if( pTab->iPKey>=0 ){
121271    assert( pTab->iPKey<pTab->nCol );
121272    zCol = pTab->aCol[pTab->iPKey].zCnName;
121273  }else{
121274    zCol = "ROWID";
121275  }
121276  assert( iDb>=0 && iDb<pParse->db->nDb );
121277  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
121278    pExpr->op = TK_NULL;
121279  }
121280}
121281
121282/*
121283** Do an authorization check using the code and arguments given.  Return
121284** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
121285** is returned, then the error count and error message in pParse are
121286** modified appropriately.
121287*/
121288SQLITE_PRIVATE int sqlite3AuthCheck(
121289  Parse *pParse,
121290  int code,
121291  const char *zArg1,
121292  const char *zArg2,
121293  const char *zArg3
121294){
121295  sqlite3 *db = pParse->db;
121296  int rc;
121297
121298  /* Don't do any authorization checks if the database is initializing
121299  ** or if the parser is being invoked from within sqlite3_declare_vtab.
121300  */
121301  assert( !IN_RENAME_OBJECT || db->xAuth==0 );
121302  if( db->xAuth==0 || db->init.busy || IN_SPECIAL_PARSE ){
121303    return SQLITE_OK;
121304  }
121305
121306  /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
121307  ** callback are either NULL pointers or zero-terminated strings that
121308  ** contain additional details about the action to be authorized.
121309  **
121310  ** The following testcase() macros show that any of the 3rd through 6th
121311  ** parameters can be either NULL or a string. */
121312  testcase( zArg1==0 );
121313  testcase( zArg2==0 );
121314  testcase( zArg3==0 );
121315  testcase( pParse->zAuthContext==0 );
121316
121317  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
121318#ifdef SQLITE_USER_AUTHENTICATION
121319                 ,db->auth.zAuthUser
121320#endif
121321                );
121322  if( rc==SQLITE_DENY ){
121323    sqlite3ErrorMsg(pParse, "not authorized");
121324    pParse->rc = SQLITE_AUTH;
121325  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
121326    rc = SQLITE_DENY;
121327    sqliteAuthBadReturnCode(pParse);
121328  }
121329  return rc;
121330}
121331
121332/*
121333** Push an authorization context.  After this routine is called, the
121334** zArg3 argument to authorization callbacks will be zContext until
121335** popped.  Or if pParse==0, this routine is a no-op.
121336*/
121337SQLITE_PRIVATE void sqlite3AuthContextPush(
121338  Parse *pParse,
121339  AuthContext *pContext,
121340  const char *zContext
121341){
121342  assert( pParse );
121343  pContext->pParse = pParse;
121344  pContext->zAuthContext = pParse->zAuthContext;
121345  pParse->zAuthContext = zContext;
121346}
121347
121348/*
121349** Pop an authorization context that was previously pushed
121350** by sqlite3AuthContextPush
121351*/
121352SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
121353  if( pContext->pParse ){
121354    pContext->pParse->zAuthContext = pContext->zAuthContext;
121355    pContext->pParse = 0;
121356  }
121357}
121358
121359#endif /* SQLITE_OMIT_AUTHORIZATION */
121360
121361/************** End of auth.c ************************************************/
121362/************** Begin file build.c *******************************************/
121363/*
121364** 2001 September 15
121365**
121366** The author disclaims copyright to this source code.  In place of
121367** a legal notice, here is a blessing:
121368**
121369**    May you do good and not evil.
121370**    May you find forgiveness for yourself and forgive others.
121371**    May you share freely, never taking more than you give.
121372**
121373*************************************************************************
121374** This file contains C code routines that are called by the SQLite parser
121375** when syntax rules are reduced.  The routines in this file handle the
121376** following kinds of SQL syntax:
121377**
121378**     CREATE TABLE
121379**     DROP TABLE
121380**     CREATE INDEX
121381**     DROP INDEX
121382**     creating ID lists
121383**     BEGIN TRANSACTION
121384**     COMMIT
121385**     ROLLBACK
121386*/
121387/* #include "sqliteInt.h" */
121388
121389#ifndef SQLITE_OMIT_SHARED_CACHE
121390/*
121391** The TableLock structure is only used by the sqlite3TableLock() and
121392** codeTableLocks() functions.
121393*/
121394struct TableLock {
121395  int iDb;               /* The database containing the table to be locked */
121396  Pgno iTab;             /* The root page of the table to be locked */
121397  u8 isWriteLock;        /* True for write lock.  False for a read lock */
121398  const char *zLockName; /* Name of the table */
121399};
121400
121401/*
121402** Record the fact that we want to lock a table at run-time.
121403**
121404** The table to be locked has root page iTab and is found in database iDb.
121405** A read or a write lock can be taken depending on isWritelock.
121406**
121407** This routine just records the fact that the lock is desired.  The
121408** code to make the lock occur is generated by a later call to
121409** codeTableLocks() which occurs during sqlite3FinishCoding().
121410*/
121411static SQLITE_NOINLINE void lockTable(
121412  Parse *pParse,     /* Parsing context */
121413  int iDb,           /* Index of the database containing the table to lock */
121414  Pgno iTab,         /* Root page number of the table to be locked */
121415  u8 isWriteLock,    /* True for a write lock */
121416  const char *zName  /* Name of the table to be locked */
121417){
121418  Parse *pToplevel;
121419  int i;
121420  int nBytes;
121421  TableLock *p;
121422  assert( iDb>=0 );
121423
121424  pToplevel = sqlite3ParseToplevel(pParse);
121425  for(i=0; i<pToplevel->nTableLock; i++){
121426    p = &pToplevel->aTableLock[i];
121427    if( p->iDb==iDb && p->iTab==iTab ){
121428      p->isWriteLock = (p->isWriteLock || isWriteLock);
121429      return;
121430    }
121431  }
121432
121433  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
121434  pToplevel->aTableLock =
121435      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
121436  if( pToplevel->aTableLock ){
121437    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
121438    p->iDb = iDb;
121439    p->iTab = iTab;
121440    p->isWriteLock = isWriteLock;
121441    p->zLockName = zName;
121442  }else{
121443    pToplevel->nTableLock = 0;
121444    sqlite3OomFault(pToplevel->db);
121445  }
121446}
121447SQLITE_PRIVATE void sqlite3TableLock(
121448  Parse *pParse,     /* Parsing context */
121449  int iDb,           /* Index of the database containing the table to lock */
121450  Pgno iTab,         /* Root page number of the table to be locked */
121451  u8 isWriteLock,    /* True for a write lock */
121452  const char *zName  /* Name of the table to be locked */
121453){
121454  if( iDb==1 ) return;
121455  if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
121456  lockTable(pParse, iDb, iTab, isWriteLock, zName);
121457}
121458
121459/*
121460** Code an OP_TableLock instruction for each table locked by the
121461** statement (configured by calls to sqlite3TableLock()).
121462*/
121463static void codeTableLocks(Parse *pParse){
121464  int i;
121465  Vdbe *pVdbe = pParse->pVdbe;
121466  assert( pVdbe!=0 );
121467
121468  for(i=0; i<pParse->nTableLock; i++){
121469    TableLock *p = &pParse->aTableLock[i];
121470    int p1 = p->iDb;
121471    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
121472                      p->zLockName, P4_STATIC);
121473  }
121474}
121475#else
121476  #define codeTableLocks(x)
121477#endif
121478
121479/*
121480** Return TRUE if the given yDbMask object is empty - if it contains no
121481** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
121482** macros when SQLITE_MAX_ATTACHED is greater than 30.
121483*/
121484#if SQLITE_MAX_ATTACHED>30
121485SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
121486  int i;
121487  for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
121488  return 1;
121489}
121490#endif
121491
121492/*
121493** This routine is called after a single SQL statement has been
121494** parsed and a VDBE program to execute that statement has been
121495** prepared.  This routine puts the finishing touches on the
121496** VDBE program and resets the pParse structure for the next
121497** parse.
121498**
121499** Note that if an error occurred, it might be the case that
121500** no VDBE code was generated.
121501*/
121502SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
121503  sqlite3 *db;
121504  Vdbe *v;
121505  int iDb, i;
121506
121507  assert( pParse->pToplevel==0 );
121508  db = pParse->db;
121509  assert( db->pParse==pParse );
121510  if( pParse->nested ) return;
121511  if( pParse->nErr ){
121512    if( db->mallocFailed ) pParse->rc = SQLITE_NOMEM;
121513    return;
121514  }
121515  assert( db->mallocFailed==0 );
121516
121517  /* Begin by generating some termination code at the end of the
121518  ** vdbe program
121519  */
121520  v = pParse->pVdbe;
121521  if( v==0 ){
121522    if( db->init.busy ){
121523      pParse->rc = SQLITE_DONE;
121524      return;
121525    }
121526    v = sqlite3GetVdbe(pParse);
121527    if( v==0 ) pParse->rc = SQLITE_ERROR;
121528  }
121529  assert( !pParse->isMultiWrite
121530       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
121531  if( v ){
121532    if( pParse->bReturning ){
121533      Returning *pReturning = pParse->u1.pReturning;
121534      int addrRewind;
121535      int reg;
121536
121537      if( pReturning->nRetCol ){
121538        sqlite3VdbeAddOp0(v, OP_FkCheck);
121539        addrRewind =
121540           sqlite3VdbeAddOp1(v, OP_Rewind, pReturning->iRetCur);
121541        VdbeCoverage(v);
121542        reg = pReturning->iRetReg;
121543        for(i=0; i<pReturning->nRetCol; i++){
121544          sqlite3VdbeAddOp3(v, OP_Column, pReturning->iRetCur, i, reg+i);
121545        }
121546        sqlite3VdbeAddOp2(v, OP_ResultRow, reg, i);
121547        sqlite3VdbeAddOp2(v, OP_Next, pReturning->iRetCur, addrRewind+1);
121548        VdbeCoverage(v);
121549        sqlite3VdbeJumpHere(v, addrRewind);
121550      }
121551    }
121552    sqlite3VdbeAddOp0(v, OP_Halt);
121553
121554#if SQLITE_USER_AUTHENTICATION && !defined(SQLITE_OMIT_SHARED_CACHE)
121555    if( pParse->nTableLock>0 && db->init.busy==0 ){
121556      sqlite3UserAuthInit(db);
121557      if( db->auth.authLevel<UAUTH_User ){
121558        sqlite3ErrorMsg(pParse, "user not authenticated");
121559        pParse->rc = SQLITE_AUTH_USER;
121560        return;
121561      }
121562    }
121563#endif
121564
121565    /* The cookie mask contains one bit for each database file open.
121566    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
121567    ** set for each database that is used.  Generate code to start a
121568    ** transaction on each used database and to verify the schema cookie
121569    ** on each used database.
121570    */
121571    assert( pParse->nErr>0 || sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
121572    sqlite3VdbeJumpHere(v, 0);
121573    assert( db->nDb>0 );
121574    iDb = 0;
121575    do{
121576      Schema *pSchema;
121577      if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
121578      sqlite3VdbeUsesBtree(v, iDb);
121579      pSchema = db->aDb[iDb].pSchema;
121580      sqlite3VdbeAddOp4Int(v,
121581        OP_Transaction,                    /* Opcode */
121582        iDb,                               /* P1 */
121583        DbMaskTest(pParse->writeMask,iDb), /* P2 */
121584        pSchema->schema_cookie,            /* P3 */
121585        pSchema->iGeneration               /* P4 */
121586      );
121587      if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
121588      VdbeComment((v,
121589            "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
121590    }while( ++iDb<db->nDb );
121591#ifndef SQLITE_OMIT_VIRTUALTABLE
121592    for(i=0; i<pParse->nVtabLock; i++){
121593      char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
121594      sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
121595    }
121596    pParse->nVtabLock = 0;
121597#endif
121598
121599#ifndef SQLITE_OMIT_SHARED_CACHE
121600    /* Once all the cookies have been verified and transactions opened,
121601    ** obtain the required table-locks. This is a no-op unless the
121602    ** shared-cache feature is enabled.
121603    */
121604    if( pParse->nTableLock ) codeTableLocks(pParse);
121605#endif
121606
121607    /* Initialize any AUTOINCREMENT data structures required.
121608    */
121609    if( pParse->pAinc ) sqlite3AutoincrementBegin(pParse);
121610
121611    /* Code constant expressions that were factored out of inner loops.
121612    */
121613    if( pParse->pConstExpr ){
121614      ExprList *pEL = pParse->pConstExpr;
121615      pParse->okConstFactor = 0;
121616      for(i=0; i<pEL->nExpr; i++){
121617        assert( pEL->a[i].u.iConstExprReg>0 );
121618        sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
121619      }
121620    }
121621
121622    if( pParse->bReturning ){
121623      Returning *pRet = pParse->u1.pReturning;
121624      if( pRet->nRetCol ){
121625        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);
121626      }
121627    }
121628
121629    /* Finally, jump back to the beginning of the executable code. */
121630    sqlite3VdbeGoto(v, 1);
121631  }
121632
121633  /* Get the VDBE program ready for execution
121634  */
121635  assert( v!=0 || pParse->nErr );
121636  assert( db->mallocFailed==0 || pParse->nErr );
121637  if( pParse->nErr==0 ){
121638    /* A minimum of one cursor is required if autoincrement is used
121639    *  See ticket [a696379c1f08866] */
121640    assert( pParse->pAinc==0 || pParse->nTab>0 );
121641    sqlite3VdbeMakeReady(v, pParse);
121642    pParse->rc = SQLITE_DONE;
121643  }else{
121644    pParse->rc = SQLITE_ERROR;
121645  }
121646}
121647
121648/*
121649** Run the parser and code generator recursively in order to generate
121650** code for the SQL statement given onto the end of the pParse context
121651** currently under construction.  Notes:
121652**
121653**   *  The final OP_Halt is not appended and other initialization
121654**      and finalization steps are omitted because those are handling by the
121655**      outermost parser.
121656**
121657**   *  Built-in SQL functions always take precedence over application-defined
121658**      SQL functions.  In other words, it is not possible to override a
121659**      built-in function.
121660*/
121661SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
121662  va_list ap;
121663  char *zSql;
121664  sqlite3 *db = pParse->db;
121665  u32 savedDbFlags = db->mDbFlags;
121666  char saveBuf[PARSE_TAIL_SZ];
121667
121668  if( pParse->nErr ) return;
121669  if( pParse->eParseMode ) return;
121670  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
121671  va_start(ap, zFormat);
121672  zSql = sqlite3VMPrintf(db, zFormat, ap);
121673  va_end(ap);
121674  if( zSql==0 ){
121675    /* This can result either from an OOM or because the formatted string
121676    ** exceeds SQLITE_LIMIT_LENGTH.  In the latter case, we need to set
121677    ** an error */
121678    if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
121679    pParse->nErr++;
121680    return;
121681  }
121682  pParse->nested++;
121683  memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
121684  memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
121685  db->mDbFlags |= DBFLAG_PreferBuiltin;
121686  sqlite3RunParser(pParse, zSql);
121687  db->mDbFlags = savedDbFlags;
121688  sqlite3DbFree(db, zSql);
121689  memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
121690  pParse->nested--;
121691}
121692
121693#if SQLITE_USER_AUTHENTICATION
121694/*
121695** Return TRUE if zTable is the name of the system table that stores the
121696** list of users and their access credentials.
121697*/
121698SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
121699  return sqlite3_stricmp(zTable, "sqlite_user")==0;
121700}
121701#endif
121702
121703/*
121704** Locate the in-memory structure that describes a particular database
121705** table given the name of that table and (optionally) the name of the
121706** database containing the table.  Return NULL if not found.
121707**
121708** If zDatabase is 0, all databases are searched for the table and the
121709** first matching table is returned.  (No checking for duplicate table
121710** names is done.)  The search order is TEMP first, then MAIN, then any
121711** auxiliary databases added using the ATTACH command.
121712**
121713** See also sqlite3LocateTable().
121714*/
121715SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
121716  Table *p = 0;
121717  int i;
121718
121719  /* All mutexes are required for schema access.  Make sure we hold them. */
121720  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
121721#if SQLITE_USER_AUTHENTICATION
121722  /* Only the admin user is allowed to know that the sqlite_user table
121723  ** exists */
121724  if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
121725    return 0;
121726  }
121727#endif
121728  if( zDatabase ){
121729    for(i=0; i<db->nDb; i++){
121730      if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;
121731    }
121732    if( i>=db->nDb ){
121733      /* No match against the official names.  But always match "main"
121734      ** to schema 0 as a legacy fallback. */
121735      if( sqlite3StrICmp(zDatabase,"main")==0 ){
121736        i = 0;
121737      }else{
121738        return 0;
121739      }
121740    }
121741    p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
121742    if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
121743      if( i==1 ){
121744        if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0
121745         || sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0
121746         || sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0
121747        ){
121748          p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
121749                              LEGACY_TEMP_SCHEMA_TABLE);
121750        }
121751      }else{
121752        if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
121753          p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash,
121754                              LEGACY_SCHEMA_TABLE);
121755        }
121756      }
121757    }
121758  }else{
121759    /* Match against TEMP first */
121760    p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);
121761    if( p ) return p;
121762    /* The main database is second */
121763    p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);
121764    if( p ) return p;
121765    /* Attached databases are in order of attachment */
121766    for(i=2; i<db->nDb; i++){
121767      assert( sqlite3SchemaMutexHeld(db, i, 0) );
121768      p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
121769      if( p ) break;
121770    }
121771    if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
121772      if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
121773        p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, LEGACY_SCHEMA_TABLE);
121774      }else if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
121775        p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
121776                            LEGACY_TEMP_SCHEMA_TABLE);
121777      }
121778    }
121779  }
121780  return p;
121781}
121782
121783/*
121784** Locate the in-memory structure that describes a particular database
121785** table given the name of that table and (optionally) the name of the
121786** database containing the table.  Return NULL if not found.  Also leave an
121787** error message in pParse->zErrMsg.
121788**
121789** The difference between this routine and sqlite3FindTable() is that this
121790** routine leaves an error message in pParse->zErrMsg where
121791** sqlite3FindTable() does not.
121792*/
121793SQLITE_PRIVATE Table *sqlite3LocateTable(
121794  Parse *pParse,         /* context in which to report errors */
121795  u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */
121796  const char *zName,     /* Name of the table we are looking for */
121797  const char *zDbase     /* Name of the database.  Might be NULL */
121798){
121799  Table *p;
121800  sqlite3 *db = pParse->db;
121801
121802  /* Read the database schema. If an error occurs, leave an error message
121803  ** and code in pParse and return NULL. */
121804  if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
121805   && SQLITE_OK!=sqlite3ReadSchema(pParse)
121806  ){
121807    return 0;
121808  }
121809
121810  p = sqlite3FindTable(db, zName, zDbase);
121811  if( p==0 ){
121812#ifndef SQLITE_OMIT_VIRTUALTABLE
121813    /* If zName is the not the name of a table in the schema created using
121814    ** CREATE, then check to see if it is the name of an virtual table that
121815    ** can be an eponymous virtual table. */
121816    if( (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)==0 && db->init.busy==0 ){
121817      Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
121818      if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
121819        pMod = sqlite3PragmaVtabRegister(db, zName);
121820      }
121821      if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
121822        testcase( pMod->pEpoTab==0 );
121823        return pMod->pEpoTab;
121824      }
121825    }
121826#endif
121827    if( flags & LOCATE_NOERR ) return 0;
121828    pParse->checkSchema = 1;
121829  }else if( IsVirtual(p) && (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)!=0 ){
121830    p = 0;
121831  }
121832
121833  if( p==0 ){
121834    const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
121835    if( zDbase ){
121836      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
121837    }else{
121838      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
121839    }
121840  }else{
121841    assert( HasRowid(p) || p->iPKey<0 );
121842  }
121843
121844  return p;
121845}
121846
121847/*
121848** Locate the table identified by *p.
121849**
121850** This is a wrapper around sqlite3LocateTable(). The difference between
121851** sqlite3LocateTable() and this function is that this function restricts
121852** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
121853** non-NULL if it is part of a view or trigger program definition. See
121854** sqlite3FixSrcList() for details.
121855*/
121856SQLITE_PRIVATE Table *sqlite3LocateTableItem(
121857  Parse *pParse,
121858  u32 flags,
121859  SrcItem *p
121860){
121861  const char *zDb;
121862  assert( p->pSchema==0 || p->zDatabase==0 );
121863  if( p->pSchema ){
121864    int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
121865    zDb = pParse->db->aDb[iDb].zDbSName;
121866  }else{
121867    zDb = p->zDatabase;
121868  }
121869  return sqlite3LocateTable(pParse, flags, p->zName, zDb);
121870}
121871
121872/*
121873** Return the preferred table name for system tables.  Translate legacy
121874** names into the new preferred names, as appropriate.
121875*/
121876SQLITE_PRIVATE const char *sqlite3PreferredTableName(const char *zName){
121877  if( sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
121878    if( sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0 ){
121879      return PREFERRED_SCHEMA_TABLE;
121880    }
121881    if( sqlite3StrICmp(zName+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
121882      return PREFERRED_TEMP_SCHEMA_TABLE;
121883    }
121884  }
121885  return zName;
121886}
121887
121888/*
121889** Locate the in-memory structure that describes
121890** a particular index given the name of that index
121891** and the name of the database that contains the index.
121892** Return NULL if not found.
121893**
121894** If zDatabase is 0, all databases are searched for the
121895** table and the first matching index is returned.  (No checking
121896** for duplicate index names is done.)  The search order is
121897** TEMP first, then MAIN, then any auxiliary databases added
121898** using the ATTACH command.
121899*/
121900SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
121901  Index *p = 0;
121902  int i;
121903  /* All mutexes are required for schema access.  Make sure we hold them. */
121904  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
121905  for(i=OMIT_TEMPDB; i<db->nDb; i++){
121906    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
121907    Schema *pSchema = db->aDb[j].pSchema;
121908    assert( pSchema );
121909    if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
121910    assert( sqlite3SchemaMutexHeld(db, j, 0) );
121911    p = sqlite3HashFind(&pSchema->idxHash, zName);
121912    if( p ) break;
121913  }
121914  return p;
121915}
121916
121917/*
121918** Reclaim the memory used by an index
121919*/
121920SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3 *db, Index *p){
121921#ifndef SQLITE_OMIT_ANALYZE
121922  sqlite3DeleteIndexSamples(db, p);
121923#endif
121924  sqlite3ExprDelete(db, p->pPartIdxWhere);
121925  sqlite3ExprListDelete(db, p->aColExpr);
121926  sqlite3DbFree(db, p->zColAff);
121927  if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
121928#ifdef SQLITE_ENABLE_STAT4
121929  sqlite3_free(p->aiRowEst);
121930#endif
121931  sqlite3DbFree(db, p);
121932}
121933
121934/*
121935** For the index called zIdxName which is found in the database iDb,
121936** unlike that index from its Table then remove the index from
121937** the index hash table and free all memory structures associated
121938** with the index.
121939*/
121940SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
121941  Index *pIndex;
121942  Hash *pHash;
121943
121944  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
121945  pHash = &db->aDb[iDb].pSchema->idxHash;
121946  pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
121947  if( ALWAYS(pIndex) ){
121948    if( pIndex->pTable->pIndex==pIndex ){
121949      pIndex->pTable->pIndex = pIndex->pNext;
121950    }else{
121951      Index *p;
121952      /* Justification of ALWAYS();  The index must be on the list of
121953      ** indices. */
121954      p = pIndex->pTable->pIndex;
121955      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
121956      if( ALWAYS(p && p->pNext==pIndex) ){
121957        p->pNext = pIndex->pNext;
121958      }
121959    }
121960    sqlite3FreeIndex(db, pIndex);
121961  }
121962  db->mDbFlags |= DBFLAG_SchemaChange;
121963}
121964
121965/*
121966** Look through the list of open database files in db->aDb[] and if
121967** any have been closed, remove them from the list.  Reallocate the
121968** db->aDb[] structure to a smaller size, if possible.
121969**
121970** Entry 0 (the "main" database) and entry 1 (the "temp" database)
121971** are never candidates for being collapsed.
121972*/
121973SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
121974  int i, j;
121975  for(i=j=2; i<db->nDb; i++){
121976    struct Db *pDb = &db->aDb[i];
121977    if( pDb->pBt==0 ){
121978      sqlite3DbFree(db, pDb->zDbSName);
121979      pDb->zDbSName = 0;
121980      continue;
121981    }
121982    if( j<i ){
121983      db->aDb[j] = db->aDb[i];
121984    }
121985    j++;
121986  }
121987  db->nDb = j;
121988  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
121989    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
121990    sqlite3DbFree(db, db->aDb);
121991    db->aDb = db->aDbStatic;
121992  }
121993}
121994
121995/*
121996** Reset the schema for the database at index iDb.  Also reset the
121997** TEMP schema.  The reset is deferred if db->nSchemaLock is not zero.
121998** Deferred resets may be run by calling with iDb<0.
121999*/
122000SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
122001  int i;
122002  assert( iDb<db->nDb );
122003
122004  if( iDb>=0 ){
122005    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
122006    DbSetProperty(db, iDb, DB_ResetWanted);
122007    DbSetProperty(db, 1, DB_ResetWanted);
122008    db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
122009  }
122010
122011  if( db->nSchemaLock==0 ){
122012    for(i=0; i<db->nDb; i++){
122013      if( DbHasProperty(db, i, DB_ResetWanted) ){
122014        sqlite3SchemaClear(db->aDb[i].pSchema);
122015      }
122016    }
122017  }
122018}
122019
122020/*
122021** Erase all schema information from all attached databases (including
122022** "main" and "temp") for a single database connection.
122023*/
122024SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
122025  int i;
122026  sqlite3BtreeEnterAll(db);
122027  for(i=0; i<db->nDb; i++){
122028    Db *pDb = &db->aDb[i];
122029    if( pDb->pSchema ){
122030      if( db->nSchemaLock==0 ){
122031        sqlite3SchemaClear(pDb->pSchema);
122032      }else{
122033        DbSetProperty(db, i, DB_ResetWanted);
122034      }
122035    }
122036  }
122037  db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
122038  sqlite3VtabUnlockList(db);
122039  sqlite3BtreeLeaveAll(db);
122040  if( db->nSchemaLock==0 ){
122041    sqlite3CollapseDatabaseArray(db);
122042  }
122043}
122044
122045/*
122046** This routine is called when a commit occurs.
122047*/
122048SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
122049  db->mDbFlags &= ~DBFLAG_SchemaChange;
122050}
122051
122052/*
122053** Set the expression associated with a column.  This is usually
122054** the DEFAULT value, but might also be the expression that computes
122055** the value for a generated column.
122056*/
122057SQLITE_PRIVATE void sqlite3ColumnSetExpr(
122058  Parse *pParse,    /* Parsing context */
122059  Table *pTab,      /* The table containing the column */
122060  Column *pCol,     /* The column to receive the new DEFAULT expression */
122061  Expr *pExpr       /* The new default expression */
122062){
122063  ExprList *pList;
122064  assert( IsOrdinaryTable(pTab) );
122065  pList = pTab->u.tab.pDfltList;
122066  if( pCol->iDflt==0
122067   || NEVER(pList==0)
122068   || NEVER(pList->nExpr<pCol->iDflt)
122069  ){
122070    pCol->iDflt = pList==0 ? 1 : pList->nExpr+1;
122071    pTab->u.tab.pDfltList = sqlite3ExprListAppend(pParse, pList, pExpr);
122072  }else{
122073    sqlite3ExprDelete(pParse->db, pList->a[pCol->iDflt-1].pExpr);
122074    pList->a[pCol->iDflt-1].pExpr = pExpr;
122075  }
122076}
122077
122078/*
122079** Return the expression associated with a column.  The expression might be
122080** the DEFAULT clause or the AS clause of a generated column.
122081** Return NULL if the column has no associated expression.
122082*/
122083SQLITE_PRIVATE Expr *sqlite3ColumnExpr(Table *pTab, Column *pCol){
122084  if( pCol->iDflt==0 ) return 0;
122085  if( !IsOrdinaryTable(pTab) ) return 0;
122086  if( NEVER(pTab->u.tab.pDfltList==0) ) return 0;
122087  if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0;
122088  return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr;
122089}
122090
122091/*
122092** Set the collating sequence name for a column.
122093*/
122094SQLITE_PRIVATE void sqlite3ColumnSetColl(
122095  sqlite3 *db,
122096  Column *pCol,
122097  const char *zColl
122098){
122099  i64 nColl;
122100  i64 n;
122101  char *zNew;
122102  assert( zColl!=0 );
122103  n = sqlite3Strlen30(pCol->zCnName) + 1;
122104  if( pCol->colFlags & COLFLAG_HASTYPE ){
122105    n += sqlite3Strlen30(pCol->zCnName+n) + 1;
122106  }
122107  nColl = sqlite3Strlen30(zColl) + 1;
122108  zNew = sqlite3DbRealloc(db, pCol->zCnName, nColl+n);
122109  if( zNew ){
122110    pCol->zCnName = zNew;
122111    memcpy(pCol->zCnName + n, zColl, nColl);
122112    pCol->colFlags |= COLFLAG_HASCOLL;
122113  }
122114}
122115
122116/*
122117** Return the collating sequence name for a column
122118*/
122119SQLITE_PRIVATE const char *sqlite3ColumnColl(Column *pCol){
122120  const char *z;
122121  if( (pCol->colFlags & COLFLAG_HASCOLL)==0 ) return 0;
122122  z = pCol->zCnName;
122123  while( *z ){ z++; }
122124  if( pCol->colFlags & COLFLAG_HASTYPE ){
122125    do{ z++; }while( *z );
122126  }
122127  return z+1;
122128}
122129
122130/*
122131** Delete memory allocated for the column names of a table or view (the
122132** Table.aCol[] array).
122133*/
122134SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
122135  int i;
122136  Column *pCol;
122137  assert( pTable!=0 );
122138  assert( db!=0 );
122139  if( (pCol = pTable->aCol)!=0 ){
122140    for(i=0; i<pTable->nCol; i++, pCol++){
122141      assert( pCol->zCnName==0 || pCol->hName==sqlite3StrIHash(pCol->zCnName) );
122142      sqlite3DbFree(db, pCol->zCnName);
122143    }
122144    sqlite3DbNNFreeNN(db, pTable->aCol);
122145    if( IsOrdinaryTable(pTable) ){
122146      sqlite3ExprListDelete(db, pTable->u.tab.pDfltList);
122147    }
122148    if( db->pnBytesFreed==0 ){
122149      pTable->aCol = 0;
122150      pTable->nCol = 0;
122151      if( IsOrdinaryTable(pTable) ){
122152        pTable->u.tab.pDfltList = 0;
122153      }
122154    }
122155  }
122156}
122157
122158/*
122159** Remove the memory data structures associated with the given
122160** Table.  No changes are made to disk by this routine.
122161**
122162** This routine just deletes the data structure.  It does not unlink
122163** the table data structure from the hash table.  But it does destroy
122164** memory structures of the indices and foreign keys associated with
122165** the table.
122166**
122167** The db parameter is optional.  It is needed if the Table object
122168** contains lookaside memory.  (Table objects in the schema do not use
122169** lookaside memory, but some ephemeral Table objects do.)  Or the
122170** db parameter can be used with db->pnBytesFreed to measure the memory
122171** used by the Table object.
122172*/
122173static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
122174  Index *pIndex, *pNext;
122175
122176#ifdef SQLITE_DEBUG
122177  /* Record the number of outstanding lookaside allocations in schema Tables
122178  ** prior to doing any free() operations. Since schema Tables do not use
122179  ** lookaside, this number should not change.
122180  **
122181  ** If malloc has already failed, it may be that it failed while allocating
122182  ** a Table object that was going to be marked ephemeral. So do not check
122183  ** that no lookaside memory is used in this case either. */
122184  int nLookaside = 0;
122185  assert( db!=0 );
122186  if( !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
122187    nLookaside = sqlite3LookasideUsed(db, 0);
122188  }
122189#endif
122190
122191  /* Delete all indices associated with this table. */
122192  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
122193    pNext = pIndex->pNext;
122194    assert( pIndex->pSchema==pTable->pSchema
122195         || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
122196    if( db->pnBytesFreed==0 && !IsVirtual(pTable) ){
122197      char *zName = pIndex->zName;
122198      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
122199         &pIndex->pSchema->idxHash, zName, 0
122200      );
122201      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
122202      assert( pOld==pIndex || pOld==0 );
122203    }
122204    sqlite3FreeIndex(db, pIndex);
122205  }
122206
122207  if( IsOrdinaryTable(pTable) ){
122208    sqlite3FkDelete(db, pTable);
122209  }
122210#ifndef SQLITE_OMIT_VIRTUALTABLE
122211  else if( IsVirtual(pTable) ){
122212    sqlite3VtabClear(db, pTable);
122213  }
122214#endif
122215  else{
122216    assert( IsView(pTable) );
122217    sqlite3SelectDelete(db, pTable->u.view.pSelect);
122218  }
122219
122220  /* Delete the Table structure itself.
122221  */
122222  sqlite3DeleteColumnNames(db, pTable);
122223  sqlite3DbFree(db, pTable->zName);
122224  sqlite3DbFree(db, pTable->zColAff);
122225  sqlite3ExprListDelete(db, pTable->pCheck);
122226  sqlite3DbFree(db, pTable);
122227
122228  /* Verify that no lookaside memory was used by schema tables */
122229  assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
122230}
122231SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
122232  /* Do not delete the table until the reference count reaches zero. */
122233  assert( db!=0 );
122234  if( !pTable ) return;
122235  if( db->pnBytesFreed==0 && (--pTable->nTabRef)>0 ) return;
122236  deleteTable(db, pTable);
122237}
122238SQLITE_PRIVATE void sqlite3DeleteTableGeneric(sqlite3 *db, void *pTable){
122239  sqlite3DeleteTable(db, (Table*)pTable);
122240}
122241
122242
122243/*
122244** Unlink the given table from the hash tables and the delete the
122245** table structure with all its indices and foreign keys.
122246*/
122247SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
122248  Table *p;
122249  Db *pDb;
122250
122251  assert( db!=0 );
122252  assert( iDb>=0 && iDb<db->nDb );
122253  assert( zTabName );
122254  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
122255  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
122256  pDb = &db->aDb[iDb];
122257  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
122258  sqlite3DeleteTable(db, p);
122259  db->mDbFlags |= DBFLAG_SchemaChange;
122260}
122261
122262/*
122263** Given a token, return a string that consists of the text of that
122264** token.  Space to hold the returned string
122265** is obtained from sqliteMalloc() and must be freed by the calling
122266** function.
122267**
122268** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
122269** surround the body of the token are removed.
122270**
122271** Tokens are often just pointers into the original SQL text and so
122272** are not \000 terminated and are not persistent.  The returned string
122273** is \000 terminated and is persistent.
122274*/
122275SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, const Token *pName){
122276  char *zName;
122277  if( pName ){
122278    zName = sqlite3DbStrNDup(db, (const char*)pName->z, pName->n);
122279    sqlite3Dequote(zName);
122280  }else{
122281    zName = 0;
122282  }
122283  return zName;
122284}
122285
122286/*
122287** Open the sqlite_schema table stored in database number iDb for
122288** writing. The table is opened using cursor 0.
122289*/
122290SQLITE_PRIVATE void sqlite3OpenSchemaTable(Parse *p, int iDb){
122291  Vdbe *v = sqlite3GetVdbe(p);
122292  sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, LEGACY_SCHEMA_TABLE);
122293  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5);
122294  if( p->nTab==0 ){
122295    p->nTab = 1;
122296  }
122297}
122298
122299/*
122300** Parameter zName points to a nul-terminated buffer containing the name
122301** of a database ("main", "temp" or the name of an attached db). This
122302** function returns the index of the named database in db->aDb[], or
122303** -1 if the named db cannot be found.
122304*/
122305SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
122306  int i = -1;         /* Database number */
122307  if( zName ){
122308    Db *pDb;
122309    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
122310      if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
122311      /* "main" is always an acceptable alias for the primary database
122312      ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
122313      if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
122314    }
122315  }
122316  return i;
122317}
122318
122319/*
122320** The token *pName contains the name of a database (either "main" or
122321** "temp" or the name of an attached db). This routine returns the
122322** index of the named database in db->aDb[], or -1 if the named db
122323** does not exist.
122324*/
122325SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
122326  int i;                               /* Database number */
122327  char *zName;                         /* Name we are searching for */
122328  zName = sqlite3NameFromToken(db, pName);
122329  i = sqlite3FindDbName(db, zName);
122330  sqlite3DbFree(db, zName);
122331  return i;
122332}
122333
122334/* The table or view or trigger name is passed to this routine via tokens
122335** pName1 and pName2. If the table name was fully qualified, for example:
122336**
122337** CREATE TABLE xxx.yyy (...);
122338**
122339** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
122340** the table name is not fully qualified, i.e.:
122341**
122342** CREATE TABLE yyy(...);
122343**
122344** Then pName1 is set to "yyy" and pName2 is "".
122345**
122346** This routine sets the *ppUnqual pointer to point at the token (pName1 or
122347** pName2) that stores the unqualified table name.  The index of the
122348** database "xxx" is returned.
122349*/
122350SQLITE_PRIVATE int sqlite3TwoPartName(
122351  Parse *pParse,      /* Parsing and code generating context */
122352  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
122353  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
122354  Token **pUnqual     /* Write the unqualified object name here */
122355){
122356  int iDb;                    /* Database holding the object */
122357  sqlite3 *db = pParse->db;
122358
122359  assert( pName2!=0 );
122360  if( pName2->n>0 ){
122361    if( db->init.busy ) {
122362      sqlite3ErrorMsg(pParse, "corrupt database");
122363      return -1;
122364    }
122365    *pUnqual = pName2;
122366    iDb = sqlite3FindDb(db, pName1);
122367    if( iDb<0 ){
122368      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
122369      return -1;
122370    }
122371  }else{
122372    assert( db->init.iDb==0 || db->init.busy || IN_SPECIAL_PARSE
122373             || (db->mDbFlags & DBFLAG_Vacuum)!=0);
122374    iDb = db->init.iDb;
122375    *pUnqual = pName1;
122376  }
122377  return iDb;
122378}
122379
122380/*
122381** True if PRAGMA writable_schema is ON
122382*/
122383SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3 *db){
122384  testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
122385  testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
122386               SQLITE_WriteSchema );
122387  testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
122388               SQLITE_Defensive );
122389  testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
122390               (SQLITE_WriteSchema|SQLITE_Defensive) );
122391  return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
122392}
122393
122394/*
122395** This routine is used to check if the UTF-8 string zName is a legal
122396** unqualified name for a new schema object (table, index, view or
122397** trigger). All names are legal except those that begin with the string
122398** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
122399** is reserved for internal use.
122400**
122401** When parsing the sqlite_schema table, this routine also checks to
122402** make sure the "type", "name", and "tbl_name" columns are consistent
122403** with the SQL.
122404*/
122405SQLITE_PRIVATE int sqlite3CheckObjectName(
122406  Parse *pParse,            /* Parsing context */
122407  const char *zName,        /* Name of the object to check */
122408  const char *zType,        /* Type of this object */
122409  const char *zTblName      /* Parent table name for triggers and indexes */
122410){
122411  sqlite3 *db = pParse->db;
122412  if( sqlite3WritableSchema(db)
122413   || db->init.imposterTable
122414   || !sqlite3Config.bExtraSchemaChecks
122415  ){
122416    /* Skip these error checks for writable_schema=ON */
122417    return SQLITE_OK;
122418  }
122419  if( db->init.busy ){
122420    if( sqlite3_stricmp(zType, db->init.azInit[0])
122421     || sqlite3_stricmp(zName, db->init.azInit[1])
122422     || sqlite3_stricmp(zTblName, db->init.azInit[2])
122423    ){
122424      sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
122425      return SQLITE_ERROR;
122426    }
122427  }else{
122428    if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
122429     || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
122430    ){
122431      sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
122432                      zName);
122433      return SQLITE_ERROR;
122434    }
122435
122436  }
122437  return SQLITE_OK;
122438}
122439
122440/*
122441** Return the PRIMARY KEY index of a table
122442*/
122443SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
122444  Index *p;
122445  for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
122446  return p;
122447}
122448
122449/*
122450** Convert an table column number into a index column number.  That is,
122451** for the column iCol in the table (as defined by the CREATE TABLE statement)
122452** find the (first) offset of that column in index pIdx.  Or return -1
122453** if column iCol is not used in index pIdx.
122454*/
122455SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){
122456  int i;
122457  for(i=0; i<pIdx->nColumn; i++){
122458    if( iCol==pIdx->aiColumn[i] ) return i;
122459  }
122460  return -1;
122461}
122462
122463#ifndef SQLITE_OMIT_GENERATED_COLUMNS
122464/* Convert a storage column number into a table column number.
122465**
122466** The storage column number (0,1,2,....) is the index of the value
122467** as it appears in the record on disk.  The true column number
122468** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
122469**
122470** The storage column number is less than the table column number if
122471** and only there are VIRTUAL columns to the left.
122472**
122473** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
122474*/
122475SQLITE_PRIVATE i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){
122476  if( pTab->tabFlags & TF_HasVirtual ){
122477    int i;
122478    for(i=0; i<=iCol; i++){
122479      if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
122480    }
122481  }
122482  return iCol;
122483}
122484#endif
122485
122486#ifndef SQLITE_OMIT_GENERATED_COLUMNS
122487/* Convert a table column number into a storage column number.
122488**
122489** The storage column number (0,1,2,....) is the index of the value
122490** as it appears in the record on disk.  Or, if the input column is
122491** the N-th virtual column (zero-based) then the storage number is
122492** the number of non-virtual columns in the table plus N.
122493**
122494** The true column number is the index (0,1,2,...) of the column in
122495** the CREATE TABLE statement.
122496**
122497** If the input column is a VIRTUAL column, then it should not appear
122498** in storage.  But the value sometimes is cached in registers that
122499** follow the range of registers used to construct storage.  This
122500** avoids computing the same VIRTUAL column multiple times, and provides
122501** values for use by OP_Param opcodes in triggers.  Hence, if the
122502** input column is a VIRTUAL table, put it after all the other columns.
122503**
122504** In the following, N means "normal column", S means STORED, and
122505** V means VIRTUAL.  Suppose the CREATE TABLE has columns like this:
122506**
122507**        CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
122508**                     -- 0 1 2 3 4 5 6 7 8
122509**
122510** Then the mapping from this function is as follows:
122511**
122512**    INPUTS:     0 1 2 3 4 5 6 7 8
122513**    OUTPUTS:    0 1 6 2 3 7 4 5 8
122514**
122515** So, in other words, this routine shifts all the virtual columns to
122516** the end.
122517**
122518** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
122519** this routine is a no-op macro.  If the pTab does not have any virtual
122520** columns, then this routine is no-op that always return iCol.  If iCol
122521** is negative (indicating the ROWID column) then this routine return iCol.
122522*/
122523SQLITE_PRIVATE i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
122524  int i;
122525  i16 n;
122526  assert( iCol<pTab->nCol );
122527  if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
122528  for(i=0, n=0; i<iCol; i++){
122529    if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
122530  }
122531  if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
122532    /* iCol is a virtual column itself */
122533    return pTab->nNVCol + i - n;
122534  }else{
122535    /* iCol is a normal or stored column */
122536    return n;
122537  }
122538}
122539#endif
122540
122541/*
122542** Insert a single OP_JournalMode query opcode in order to force the
122543** prepared statement to return false for sqlite3_stmt_readonly().  This
122544** is used by CREATE TABLE IF NOT EXISTS and similar if the table already
122545** exists, so that the prepared statement for CREATE TABLE IF NOT EXISTS
122546** will return false for sqlite3_stmt_readonly() even if that statement
122547** is a read-only no-op.
122548*/
122549static void sqlite3ForceNotReadOnly(Parse *pParse){
122550  int iReg = ++pParse->nMem;
122551  Vdbe *v = sqlite3GetVdbe(pParse);
122552  if( v ){
122553    sqlite3VdbeAddOp3(v, OP_JournalMode, 0, iReg, PAGER_JOURNALMODE_QUERY);
122554    sqlite3VdbeUsesBtree(v, 0);
122555  }
122556}
122557
122558/*
122559** Begin constructing a new table representation in memory.  This is
122560** the first of several action routines that get called in response
122561** to a CREATE TABLE statement.  In particular, this routine is called
122562** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
122563** flag is true if the table should be stored in the auxiliary database
122564** file instead of in the main database file.  This is normally the case
122565** when the "TEMP" or "TEMPORARY" keyword occurs in between
122566** CREATE and TABLE.
122567**
122568** The new table record is initialized and put in pParse->pNewTable.
122569** As more of the CREATE TABLE statement is parsed, additional action
122570** routines will be called to add more information to this record.
122571** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
122572** is called to complete the construction of the new table record.
122573*/
122574SQLITE_PRIVATE void sqlite3StartTable(
122575  Parse *pParse,   /* Parser context */
122576  Token *pName1,   /* First part of the name of the table or view */
122577  Token *pName2,   /* Second part of the name of the table or view */
122578  int isTemp,      /* True if this is a TEMP table */
122579  int isView,      /* True if this is a VIEW */
122580  int isVirtual,   /* True if this is a VIRTUAL table */
122581  int noErr        /* Do nothing if table already exists */
122582){
122583  Table *pTable;
122584  char *zName = 0; /* The name of the new table */
122585  sqlite3 *db = pParse->db;
122586  Vdbe *v;
122587  int iDb;         /* Database number to create the table in */
122588  Token *pName;    /* Unqualified name of the table to create */
122589
122590  if( db->init.busy && db->init.newTnum==1 ){
122591    /* Special case:  Parsing the sqlite_schema or sqlite_temp_schema schema */
122592    iDb = db->init.iDb;
122593    zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
122594    pName = pName1;
122595  }else{
122596    /* The common case */
122597    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
122598    if( iDb<0 ) return;
122599    if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
122600      /* If creating a temp table, the name may not be qualified. Unless
122601      ** the database name is "temp" anyway.  */
122602      sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
122603      return;
122604    }
122605    if( !OMIT_TEMPDB && isTemp ) iDb = 1;
122606    zName = sqlite3NameFromToken(db, pName);
122607    if( IN_RENAME_OBJECT ){
122608      sqlite3RenameTokenMap(pParse, (void*)zName, pName);
122609    }
122610  }
122611  pParse->sNameToken = *pName;
122612  if( zName==0 ) return;
122613  if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){
122614    goto begin_table_error;
122615  }
122616  if( db->init.iDb==1 ) isTemp = 1;
122617#ifndef SQLITE_OMIT_AUTHORIZATION
122618  assert( isTemp==0 || isTemp==1 );
122619  assert( isView==0 || isView==1 );
122620  {
122621    static const u8 aCode[] = {
122622       SQLITE_CREATE_TABLE,
122623       SQLITE_CREATE_TEMP_TABLE,
122624       SQLITE_CREATE_VIEW,
122625       SQLITE_CREATE_TEMP_VIEW
122626    };
122627    char *zDb = db->aDb[iDb].zDbSName;
122628    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
122629      goto begin_table_error;
122630    }
122631    if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
122632                                       zName, 0, zDb) ){
122633      goto begin_table_error;
122634    }
122635  }
122636#endif
122637
122638  /* Make sure the new table name does not collide with an existing
122639  ** index or table name in the same database.  Issue an error message if
122640  ** it does. The exception is if the statement being parsed was passed
122641  ** to an sqlite3_declare_vtab() call. In that case only the column names
122642  ** and types will be used, so there is no need to test for namespace
122643  ** collisions.
122644  */
122645  if( !IN_SPECIAL_PARSE ){
122646    char *zDb = db->aDb[iDb].zDbSName;
122647    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
122648      goto begin_table_error;
122649    }
122650    pTable = sqlite3FindTable(db, zName, zDb);
122651    if( pTable ){
122652      if( !noErr ){
122653        sqlite3ErrorMsg(pParse, "%s %T already exists",
122654                        (IsView(pTable)? "view" : "table"), pName);
122655      }else{
122656        assert( !db->init.busy || CORRUPT_DB );
122657        sqlite3CodeVerifySchema(pParse, iDb);
122658        sqlite3ForceNotReadOnly(pParse);
122659      }
122660      goto begin_table_error;
122661    }
122662    if( sqlite3FindIndex(db, zName, zDb)!=0 ){
122663      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
122664      goto begin_table_error;
122665    }
122666  }
122667
122668  pTable = sqlite3DbMallocZero(db, sizeof(Table));
122669  if( pTable==0 ){
122670    assert( db->mallocFailed );
122671    pParse->rc = SQLITE_NOMEM_BKPT;
122672    pParse->nErr++;
122673    goto begin_table_error;
122674  }
122675  pTable->zName = zName;
122676  pTable->iPKey = -1;
122677  pTable->pSchema = db->aDb[iDb].pSchema;
122678  pTable->nTabRef = 1;
122679#ifdef SQLITE_DEFAULT_ROWEST
122680  pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
122681#else
122682  pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
122683#endif
122684  assert( pParse->pNewTable==0 );
122685  pParse->pNewTable = pTable;
122686
122687  /* Begin generating the code that will insert the table record into
122688  ** the schema table.  Note in particular that we must go ahead
122689  ** and allocate the record number for the table entry now.  Before any
122690  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
122691  ** indices to be created and the table record must come before the
122692  ** indices.  Hence, the record number for the table must be allocated
122693  ** now.
122694  */
122695  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
122696    int addr1;
122697    int fileFormat;
122698    int reg1, reg2, reg3;
122699    /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
122700    static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
122701    sqlite3BeginWriteOperation(pParse, 1, iDb);
122702
122703#ifndef SQLITE_OMIT_VIRTUALTABLE
122704    if( isVirtual ){
122705      sqlite3VdbeAddOp0(v, OP_VBegin);
122706    }
122707#endif
122708
122709    /* If the file format and encoding in the database have not been set,
122710    ** set them now.
122711    */
122712    reg1 = pParse->regRowid = ++pParse->nMem;
122713    reg2 = pParse->regRoot = ++pParse->nMem;
122714    reg3 = ++pParse->nMem;
122715    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
122716    sqlite3VdbeUsesBtree(v, iDb);
122717    addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
122718    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
122719                  1 : SQLITE_MAX_FILE_FORMAT;
122720    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
122721    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
122722    sqlite3VdbeJumpHere(v, addr1);
122723
122724    /* This just creates a place-holder record in the sqlite_schema table.
122725    ** The record created does not contain anything yet.  It will be replaced
122726    ** by the real entry in code generated at sqlite3EndTable().
122727    **
122728    ** The rowid for the new entry is left in register pParse->regRowid.
122729    ** The root page number of the new table is left in reg pParse->regRoot.
122730    ** The rowid and root page number values are needed by the code that
122731    ** sqlite3EndTable will generate.
122732    */
122733#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
122734    if( isView || isVirtual ){
122735      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
122736    }else
122737#endif
122738    {
122739      assert( !pParse->bReturning );
122740      pParse->u1.addrCrTab =
122741         sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
122742    }
122743    sqlite3OpenSchemaTable(pParse, iDb);
122744    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
122745    sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
122746    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
122747    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
122748    sqlite3VdbeAddOp0(v, OP_Close);
122749  }
122750
122751  /* Normal (non-error) return. */
122752  return;
122753
122754  /* If an error occurs, we jump here */
122755begin_table_error:
122756  pParse->checkSchema = 1;
122757  sqlite3DbFree(db, zName);
122758  return;
122759}
122760
122761/* Set properties of a table column based on the (magical)
122762** name of the column.
122763*/
122764#if SQLITE_ENABLE_HIDDEN_COLUMNS
122765SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
122766  if( sqlite3_strnicmp(pCol->zCnName, "__hidden__", 10)==0 ){
122767    pCol->colFlags |= COLFLAG_HIDDEN;
122768    if( pTab ) pTab->tabFlags |= TF_HasHidden;
122769  }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
122770    pTab->tabFlags |= TF_OOOHidden;
122771  }
122772}
122773#endif
122774
122775/*
122776** Clean up the data structures associated with the RETURNING clause.
122777*/
122778static void sqlite3DeleteReturning(sqlite3 *db, void *pArg){
122779  Returning *pRet = (Returning*)pArg;
122780  Hash *pHash;
122781  pHash = &(db->aDb[1].pSchema->trigHash);
122782  sqlite3HashInsert(pHash, pRet->zName, 0);
122783  sqlite3ExprListDelete(db, pRet->pReturnEL);
122784  sqlite3DbFree(db, pRet);
122785}
122786
122787/*
122788** Add the RETURNING clause to the parse currently underway.
122789**
122790** This routine creates a special TEMP trigger that will fire for each row
122791** of the DML statement.  That TEMP trigger contains a single SELECT
122792** statement with a result set that is the argument of the RETURNING clause.
122793** The trigger has the Trigger.bReturning flag and an opcode of
122794** TK_RETURNING instead of TK_SELECT, so that the trigger code generator
122795** knows to handle it specially.  The TEMP trigger is automatically
122796** removed at the end of the parse.
122797**
122798** When this routine is called, we do not yet know if the RETURNING clause
122799** is attached to a DELETE, INSERT, or UPDATE, so construct it as a
122800** RETURNING trigger instead.  It will then be converted into the appropriate
122801** type on the first call to sqlite3TriggersExist().
122802*/
122803SQLITE_PRIVATE void sqlite3AddReturning(Parse *pParse, ExprList *pList){
122804  Returning *pRet;
122805  Hash *pHash;
122806  sqlite3 *db = pParse->db;
122807  if( pParse->pNewTrigger ){
122808    sqlite3ErrorMsg(pParse, "cannot use RETURNING in a trigger");
122809  }else{
122810    assert( pParse->bReturning==0 || pParse->ifNotExists );
122811  }
122812  pParse->bReturning = 1;
122813  pRet = sqlite3DbMallocZero(db, sizeof(*pRet));
122814  if( pRet==0 ){
122815    sqlite3ExprListDelete(db, pList);
122816    return;
122817  }
122818  pParse->u1.pReturning = pRet;
122819  pRet->pParse = pParse;
122820  pRet->pReturnEL = pList;
122821  sqlite3ParserAddCleanup(pParse, sqlite3DeleteReturning, pRet);
122822  testcase( pParse->earlyCleanup );
122823  if( db->mallocFailed ) return;
122824  sqlite3_snprintf(sizeof(pRet->zName), pRet->zName,
122825                   "sqlite_returning_%p", pParse);
122826  pRet->retTrig.zName = pRet->zName;
122827  pRet->retTrig.op = TK_RETURNING;
122828  pRet->retTrig.tr_tm = TRIGGER_AFTER;
122829  pRet->retTrig.bReturning = 1;
122830  pRet->retTrig.pSchema = db->aDb[1].pSchema;
122831  pRet->retTrig.pTabSchema = db->aDb[1].pSchema;
122832  pRet->retTrig.step_list = &pRet->retTStep;
122833  pRet->retTStep.op = TK_RETURNING;
122834  pRet->retTStep.pTrig = &pRet->retTrig;
122835  pRet->retTStep.pExprList = pList;
122836  pHash = &(db->aDb[1].pSchema->trigHash);
122837  assert( sqlite3HashFind(pHash, pRet->zName)==0
122838          || pParse->nErr  || pParse->ifNotExists );
122839  if( sqlite3HashInsert(pHash, pRet->zName, &pRet->retTrig)
122840          ==&pRet->retTrig ){
122841    sqlite3OomFault(db);
122842  }
122843}
122844
122845/*
122846** Add a new column to the table currently being constructed.
122847**
122848** The parser calls this routine once for each column declaration
122849** in a CREATE TABLE statement.  sqlite3StartTable() gets called
122850** first to get things going.  Then this routine is called for each
122851** column.
122852*/
122853SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){
122854  Table *p;
122855  int i;
122856  char *z;
122857  char *zType;
122858  Column *pCol;
122859  sqlite3 *db = pParse->db;
122860  u8 hName;
122861  Column *aNew;
122862  u8 eType = COLTYPE_CUSTOM;
122863  u8 szEst = 1;
122864  char affinity = SQLITE_AFF_BLOB;
122865
122866  if( (p = pParse->pNewTable)==0 ) return;
122867  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
122868    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
122869    return;
122870  }
122871  if( !IN_RENAME_OBJECT ) sqlite3DequoteToken(&sName);
122872
122873  /* Because keywords GENERATE ALWAYS can be converted into identifiers
122874  ** by the parser, we can sometimes end up with a typename that ends
122875  ** with "generated always".  Check for this case and omit the surplus
122876  ** text. */
122877  if( sType.n>=16
122878   && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0
122879  ){
122880    sType.n -= 6;
122881    while( ALWAYS(sType.n>0) && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
122882    if( sType.n>=9
122883     && sqlite3_strnicmp(sType.z+(sType.n-9),"generated",9)==0
122884    ){
122885      sType.n -= 9;
122886      while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
122887    }
122888  }
122889
122890  /* Check for standard typenames.  For standard typenames we will
122891  ** set the Column.eType field rather than storing the typename after
122892  ** the column name, in order to save space. */
122893  if( sType.n>=3 ){
122894    sqlite3DequoteToken(&sType);
122895    for(i=0; i<SQLITE_N_STDTYPE; i++){
122896       if( sType.n==sqlite3StdTypeLen[i]
122897        && sqlite3_strnicmp(sType.z, sqlite3StdType[i], sType.n)==0
122898       ){
122899         sType.n = 0;
122900         eType = i+1;
122901         affinity = sqlite3StdTypeAffinity[i];
122902         if( affinity<=SQLITE_AFF_TEXT ) szEst = 5;
122903         break;
122904       }
122905    }
122906  }
122907
122908  z = sqlite3DbMallocRaw(db, (i64)sName.n + 1 + (i64)sType.n + (sType.n>0) );
122909  if( z==0 ) return;
122910  if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, &sName);
122911  memcpy(z, sName.z, sName.n);
122912  z[sName.n] = 0;
122913  sqlite3Dequote(z);
122914  hName = sqlite3StrIHash(z);
122915  for(i=0; i<p->nCol; i++){
122916    if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zCnName)==0 ){
122917      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
122918      sqlite3DbFree(db, z);
122919      return;
122920    }
122921  }
122922  aNew = sqlite3DbRealloc(db,p->aCol,((i64)p->nCol+1)*sizeof(p->aCol[0]));
122923  if( aNew==0 ){
122924    sqlite3DbFree(db, z);
122925    return;
122926  }
122927  p->aCol = aNew;
122928  pCol = &p->aCol[p->nCol];
122929  memset(pCol, 0, sizeof(p->aCol[0]));
122930  pCol->zCnName = z;
122931  pCol->hName = hName;
122932  sqlite3ColumnPropertiesFromName(p, pCol);
122933
122934  if( sType.n==0 ){
122935    /* If there is no type specified, columns have the default affinity
122936    ** 'BLOB' with a default size of 4 bytes. */
122937    pCol->affinity = affinity;
122938    pCol->eCType = eType;
122939    pCol->szEst = szEst;
122940#ifdef SQLITE_ENABLE_SORTER_REFERENCES
122941    if( affinity==SQLITE_AFF_BLOB ){
122942      if( 4>=sqlite3GlobalConfig.szSorterRef ){
122943        pCol->colFlags |= COLFLAG_SORTERREF;
122944      }
122945    }
122946#endif
122947  }else{
122948    zType = z + sqlite3Strlen30(z) + 1;
122949    memcpy(zType, sType.z, sType.n);
122950    zType[sType.n] = 0;
122951    sqlite3Dequote(zType);
122952    pCol->affinity = sqlite3AffinityType(zType, pCol);
122953    pCol->colFlags |= COLFLAG_HASTYPE;
122954  }
122955  p->nCol++;
122956  p->nNVCol++;
122957  pParse->constraintName.n = 0;
122958}
122959
122960/*
122961** This routine is called by the parser while in the middle of
122962** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
122963** been seen on a column.  This routine sets the notNull flag on
122964** the column currently under construction.
122965*/
122966SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
122967  Table *p;
122968  Column *pCol;
122969  p = pParse->pNewTable;
122970  if( p==0 || NEVER(p->nCol<1) ) return;
122971  pCol = &p->aCol[p->nCol-1];
122972  pCol->notNull = (u8)onError;
122973  p->tabFlags |= TF_HasNotNull;
122974
122975  /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
122976  ** on this column.  */
122977  if( pCol->colFlags & COLFLAG_UNIQUE ){
122978    Index *pIdx;
122979    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
122980      assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
122981      if( pIdx->aiColumn[0]==p->nCol-1 ){
122982        pIdx->uniqNotNull = 1;
122983      }
122984    }
122985  }
122986}
122987
122988/*
122989** Scan the column type name zType (length nType) and return the
122990** associated affinity type.
122991**
122992** This routine does a case-independent search of zType for the
122993** substrings in the following table. If one of the substrings is
122994** found, the corresponding affinity is returned. If zType contains
122995** more than one of the substrings, entries toward the top of
122996** the table take priority. For example, if zType is 'BLOBINT',
122997** SQLITE_AFF_INTEGER is returned.
122998**
122999** Substring     | Affinity
123000** --------------------------------
123001** 'INT'         | SQLITE_AFF_INTEGER
123002** 'CHAR'        | SQLITE_AFF_TEXT
123003** 'CLOB'        | SQLITE_AFF_TEXT
123004** 'TEXT'        | SQLITE_AFF_TEXT
123005** 'BLOB'        | SQLITE_AFF_BLOB
123006** 'REAL'        | SQLITE_AFF_REAL
123007** 'FLOA'        | SQLITE_AFF_REAL
123008** 'DOUB'        | SQLITE_AFF_REAL
123009**
123010** If none of the substrings in the above table are found,
123011** SQLITE_AFF_NUMERIC is returned.
123012*/
123013SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, Column *pCol){
123014  u32 h = 0;
123015  char aff = SQLITE_AFF_NUMERIC;
123016  const char *zChar = 0;
123017
123018  assert( zIn!=0 );
123019  while( zIn[0] ){
123020    u8 x = *(u8*)zIn;
123021    h = (h<<8) + sqlite3UpperToLower[x];
123022    zIn++;
123023    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
123024      aff = SQLITE_AFF_TEXT;
123025      zChar = zIn;
123026    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
123027      aff = SQLITE_AFF_TEXT;
123028    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
123029      aff = SQLITE_AFF_TEXT;
123030    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
123031        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
123032      aff = SQLITE_AFF_BLOB;
123033      if( zIn[0]=='(' ) zChar = zIn;
123034#ifndef SQLITE_OMIT_FLOATING_POINT
123035    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
123036        && aff==SQLITE_AFF_NUMERIC ){
123037      aff = SQLITE_AFF_REAL;
123038    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
123039        && aff==SQLITE_AFF_NUMERIC ){
123040      aff = SQLITE_AFF_REAL;
123041    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
123042        && aff==SQLITE_AFF_NUMERIC ){
123043      aff = SQLITE_AFF_REAL;
123044#endif
123045    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
123046      aff = SQLITE_AFF_INTEGER;
123047      break;
123048    }
123049  }
123050
123051  /* If pCol is not NULL, store an estimate of the field size.  The
123052  ** estimate is scaled so that the size of an integer is 1.  */
123053  if( pCol ){
123054    int v = 0;   /* default size is approx 4 bytes */
123055    if( aff<SQLITE_AFF_NUMERIC ){
123056      if( zChar ){
123057        while( zChar[0] ){
123058          if( sqlite3Isdigit(zChar[0]) ){
123059            /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
123060            sqlite3GetInt32(zChar, &v);
123061            break;
123062          }
123063          zChar++;
123064        }
123065      }else{
123066        v = 16;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
123067      }
123068    }
123069#ifdef SQLITE_ENABLE_SORTER_REFERENCES
123070    if( v>=sqlite3GlobalConfig.szSorterRef ){
123071      pCol->colFlags |= COLFLAG_SORTERREF;
123072    }
123073#endif
123074    v = v/4 + 1;
123075    if( v>255 ) v = 255;
123076    pCol->szEst = v;
123077  }
123078  return aff;
123079}
123080
123081/*
123082** The expression is the default value for the most recently added column
123083** of the table currently under construction.
123084**
123085** Default value expressions must be constant.  Raise an exception if this
123086** is not the case.
123087**
123088** This routine is called by the parser while in the middle of
123089** parsing a CREATE TABLE statement.
123090*/
123091SQLITE_PRIVATE void sqlite3AddDefaultValue(
123092  Parse *pParse,           /* Parsing context */
123093  Expr *pExpr,             /* The parsed expression of the default value */
123094  const char *zStart,      /* Start of the default value text */
123095  const char *zEnd         /* First character past end of default value text */
123096){
123097  Table *p;
123098  Column *pCol;
123099  sqlite3 *db = pParse->db;
123100  p = pParse->pNewTable;
123101  if( p!=0 ){
123102    int isInit = db->init.busy && db->init.iDb!=1;
123103    pCol = &(p->aCol[p->nCol-1]);
123104    if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
123105      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
123106          pCol->zCnName);
123107#ifndef SQLITE_OMIT_GENERATED_COLUMNS
123108    }else if( pCol->colFlags & COLFLAG_GENERATED ){
123109      testcase( pCol->colFlags & COLFLAG_VIRTUAL );
123110      testcase( pCol->colFlags & COLFLAG_STORED );
123111      sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
123112#endif
123113    }else{
123114      /* A copy of pExpr is used instead of the original, as pExpr contains
123115      ** tokens that point to volatile memory.
123116      */
123117      Expr x, *pDfltExpr;
123118      memset(&x, 0, sizeof(x));
123119      x.op = TK_SPAN;
123120      x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
123121      x.pLeft = pExpr;
123122      x.flags = EP_Skip;
123123      pDfltExpr = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
123124      sqlite3DbFree(db, x.u.zToken);
123125      sqlite3ColumnSetExpr(pParse, p, pCol, pDfltExpr);
123126    }
123127  }
123128  if( IN_RENAME_OBJECT ){
123129    sqlite3RenameExprUnmap(pParse, pExpr);
123130  }
123131  sqlite3ExprDelete(db, pExpr);
123132}
123133
123134/*
123135** Backwards Compatibility Hack:
123136**
123137** Historical versions of SQLite accepted strings as column names in
123138** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
123139**
123140**     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
123141**     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
123142**
123143** This is goofy.  But to preserve backwards compatibility we continue to
123144** accept it.  This routine does the necessary conversion.  It converts
123145** the expression given in its argument from a TK_STRING into a TK_ID
123146** if the expression is just a TK_STRING with an optional COLLATE clause.
123147** If the expression is anything other than TK_STRING, the expression is
123148** unchanged.
123149*/
123150static void sqlite3StringToId(Expr *p){
123151  if( p->op==TK_STRING ){
123152    p->op = TK_ID;
123153  }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
123154    p->pLeft->op = TK_ID;
123155  }
123156}
123157
123158/*
123159** Tag the given column as being part of the PRIMARY KEY
123160*/
123161static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
123162  pCol->colFlags |= COLFLAG_PRIMKEY;
123163#ifndef SQLITE_OMIT_GENERATED_COLUMNS
123164  if( pCol->colFlags & COLFLAG_GENERATED ){
123165    testcase( pCol->colFlags & COLFLAG_VIRTUAL );
123166    testcase( pCol->colFlags & COLFLAG_STORED );
123167    sqlite3ErrorMsg(pParse,
123168      "generated columns cannot be part of the PRIMARY KEY");
123169  }
123170#endif
123171}
123172
123173/*
123174** Designate the PRIMARY KEY for the table.  pList is a list of names
123175** of columns that form the primary key.  If pList is NULL, then the
123176** most recently added column of the table is the primary key.
123177**
123178** A table can have at most one primary key.  If the table already has
123179** a primary key (and this is the second primary key) then create an
123180** error.
123181**
123182** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
123183** then we will try to use that column as the rowid.  Set the Table.iPKey
123184** field of the table under construction to be the index of the
123185** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
123186** no INTEGER PRIMARY KEY.
123187**
123188** If the key is not an INTEGER PRIMARY KEY, then create a unique
123189** index for the key.  No index is created for INTEGER PRIMARY KEYs.
123190*/
123191SQLITE_PRIVATE void sqlite3AddPrimaryKey(
123192  Parse *pParse,    /* Parsing context */
123193  ExprList *pList,  /* List of field names to be indexed */
123194  int onError,      /* What to do with a uniqueness conflict */
123195  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
123196  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
123197){
123198  Table *pTab = pParse->pNewTable;
123199  Column *pCol = 0;
123200  int iCol = -1, i;
123201  int nTerm;
123202  if( pTab==0 ) goto primary_key_exit;
123203  if( pTab->tabFlags & TF_HasPrimaryKey ){
123204    sqlite3ErrorMsg(pParse,
123205      "table \"%s\" has more than one primary key", pTab->zName);
123206    goto primary_key_exit;
123207  }
123208  pTab->tabFlags |= TF_HasPrimaryKey;
123209  if( pList==0 ){
123210    iCol = pTab->nCol - 1;
123211    pCol = &pTab->aCol[iCol];
123212    makeColumnPartOfPrimaryKey(pParse, pCol);
123213    nTerm = 1;
123214  }else{
123215    nTerm = pList->nExpr;
123216    for(i=0; i<nTerm; i++){
123217      Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
123218      assert( pCExpr!=0 );
123219      sqlite3StringToId(pCExpr);
123220      if( pCExpr->op==TK_ID ){
123221        const char *zCName;
123222        assert( !ExprHasProperty(pCExpr, EP_IntValue) );
123223        zCName = pCExpr->u.zToken;
123224        for(iCol=0; iCol<pTab->nCol; iCol++){
123225          if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zCnName)==0 ){
123226            pCol = &pTab->aCol[iCol];
123227            makeColumnPartOfPrimaryKey(pParse, pCol);
123228            break;
123229          }
123230        }
123231      }
123232    }
123233  }
123234  if( nTerm==1
123235   && pCol
123236   && pCol->eCType==COLTYPE_INTEGER
123237   && sortOrder!=SQLITE_SO_DESC
123238  ){
123239    if( IN_RENAME_OBJECT && pList ){
123240      Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
123241      sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
123242    }
123243    pTab->iPKey = iCol;
123244    pTab->keyConf = (u8)onError;
123245    assert( autoInc==0 || autoInc==1 );
123246    pTab->tabFlags |= autoInc*TF_Autoincrement;
123247    if( pList ) pParse->iPkSortOrder = pList->a[0].fg.sortFlags;
123248    (void)sqlite3HasExplicitNulls(pParse, pList);
123249  }else if( autoInc ){
123250#ifndef SQLITE_OMIT_AUTOINCREMENT
123251    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
123252       "INTEGER PRIMARY KEY");
123253#endif
123254  }else{
123255    sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
123256                           0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
123257    pList = 0;
123258  }
123259
123260primary_key_exit:
123261  sqlite3ExprListDelete(pParse->db, pList);
123262  return;
123263}
123264
123265/*
123266** Add a new CHECK constraint to the table currently under construction.
123267*/
123268SQLITE_PRIVATE void sqlite3AddCheckConstraint(
123269  Parse *pParse,      /* Parsing context */
123270  Expr *pCheckExpr,   /* The check expression */
123271  const char *zStart, /* Opening "(" */
123272  const char *zEnd    /* Closing ")" */
123273){
123274#ifndef SQLITE_OMIT_CHECK
123275  Table *pTab = pParse->pNewTable;
123276  sqlite3 *db = pParse->db;
123277  if( pTab && !IN_DECLARE_VTAB
123278   && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
123279  ){
123280    pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
123281    if( pParse->constraintName.n ){
123282      sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
123283    }else{
123284      Token t;
123285      for(zStart++; sqlite3Isspace(zStart[0]); zStart++){}
123286      while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; }
123287      t.z = zStart;
123288      t.n = (int)(zEnd - t.z);
123289      sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1);
123290    }
123291  }else
123292#endif
123293  {
123294    sqlite3ExprDelete(pParse->db, pCheckExpr);
123295  }
123296}
123297
123298/*
123299** Set the collation function of the most recently parsed table column
123300** to the CollSeq given.
123301*/
123302SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
123303  Table *p;
123304  int i;
123305  char *zColl;              /* Dequoted name of collation sequence */
123306  sqlite3 *db;
123307
123308  if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return;
123309  i = p->nCol-1;
123310  db = pParse->db;
123311  zColl = sqlite3NameFromToken(db, pToken);
123312  if( !zColl ) return;
123313
123314  if( sqlite3LocateCollSeq(pParse, zColl) ){
123315    Index *pIdx;
123316    sqlite3ColumnSetColl(db, &p->aCol[i], zColl);
123317
123318    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
123319    ** then an index may have been created on this column before the
123320    ** collation type was added. Correct this if it is the case.
123321    */
123322    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
123323      assert( pIdx->nKeyCol==1 );
123324      if( pIdx->aiColumn[0]==i ){
123325        pIdx->azColl[0] = sqlite3ColumnColl(&p->aCol[i]);
123326      }
123327    }
123328  }
123329  sqlite3DbFree(db, zColl);
123330}
123331
123332/* Change the most recently parsed column to be a GENERATED ALWAYS AS
123333** column.
123334*/
123335SQLITE_PRIVATE void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
123336#ifndef SQLITE_OMIT_GENERATED_COLUMNS
123337  u8 eType = COLFLAG_VIRTUAL;
123338  Table *pTab = pParse->pNewTable;
123339  Column *pCol;
123340  if( pTab==0 ){
123341    /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
123342    goto generated_done;
123343  }
123344  pCol = &(pTab->aCol[pTab->nCol-1]);
123345  if( IN_DECLARE_VTAB ){
123346    sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
123347    goto generated_done;
123348  }
123349  if( pCol->iDflt>0 ) goto generated_error;
123350  if( pType ){
123351    if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
123352      /* no-op */
123353    }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
123354      eType = COLFLAG_STORED;
123355    }else{
123356      goto generated_error;
123357    }
123358  }
123359  if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
123360  pCol->colFlags |= eType;
123361  assert( TF_HasVirtual==COLFLAG_VIRTUAL );
123362  assert( TF_HasStored==COLFLAG_STORED );
123363  pTab->tabFlags |= eType;
123364  if( pCol->colFlags & COLFLAG_PRIMKEY ){
123365    makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
123366  }
123367  if( ALWAYS(pExpr) && pExpr->op==TK_ID ){
123368    /* The value of a generated column needs to be a real expression, not
123369    ** just a reference to another column, in order for covering index
123370    ** optimizations to work correctly.  So if the value is not an expression,
123371    ** turn it into one by adding a unary "+" operator. */
123372    pExpr = sqlite3PExpr(pParse, TK_UPLUS, pExpr, 0);
123373  }
123374  if( pExpr && pExpr->op!=TK_RAISE ) pExpr->affExpr = pCol->affinity;
123375  sqlite3ColumnSetExpr(pParse, pTab, pCol, pExpr);
123376  pExpr = 0;
123377  goto generated_done;
123378
123379generated_error:
123380  sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
123381                  pCol->zCnName);
123382generated_done:
123383  sqlite3ExprDelete(pParse->db, pExpr);
123384#else
123385  /* Throw and error for the GENERATED ALWAYS AS clause if the
123386  ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
123387  sqlite3ErrorMsg(pParse, "generated columns not supported");
123388  sqlite3ExprDelete(pParse->db, pExpr);
123389#endif
123390}
123391
123392/*
123393** Generate code that will increment the schema cookie.
123394**
123395** The schema cookie is used to determine when the schema for the
123396** database changes.  After each schema change, the cookie value
123397** changes.  When a process first reads the schema it records the
123398** cookie.  Thereafter, whenever it goes to access the database,
123399** it checks the cookie to make sure the schema has not changed
123400** since it was last read.
123401**
123402** This plan is not completely bullet-proof.  It is possible for
123403** the schema to change multiple times and for the cookie to be
123404** set back to prior value.  But schema changes are infrequent
123405** and the probability of hitting the same cookie value is only
123406** 1 chance in 2^32.  So we're safe enough.
123407**
123408** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
123409** the schema-version whenever the schema changes.
123410*/
123411SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
123412  sqlite3 *db = pParse->db;
123413  Vdbe *v = pParse->pVdbe;
123414  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
123415  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
123416                   (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
123417}
123418
123419/*
123420** Measure the number of characters needed to output the given
123421** identifier.  The number returned includes any quotes used
123422** but does not include the null terminator.
123423**
123424** The estimate is conservative.  It might be larger that what is
123425** really needed.
123426*/
123427static int identLength(const char *z){
123428  int n;
123429  for(n=0; *z; n++, z++){
123430    if( *z=='"' ){ n++; }
123431  }
123432  return n + 2;
123433}
123434
123435/*
123436** The first parameter is a pointer to an output buffer. The second
123437** parameter is a pointer to an integer that contains the offset at
123438** which to write into the output buffer. This function copies the
123439** nul-terminated string pointed to by the third parameter, zSignedIdent,
123440** to the specified offset in the buffer and updates *pIdx to refer
123441** to the first byte after the last byte written before returning.
123442**
123443** If the string zSignedIdent consists entirely of alphanumeric
123444** characters, does not begin with a digit and is not an SQL keyword,
123445** then it is copied to the output buffer exactly as it is. Otherwise,
123446** it is quoted using double-quotes.
123447*/
123448static void identPut(char *z, int *pIdx, char *zSignedIdent){
123449  unsigned char *zIdent = (unsigned char*)zSignedIdent;
123450  int i, j, needQuote;
123451  i = *pIdx;
123452
123453  for(j=0; zIdent[j]; j++){
123454    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
123455  }
123456  needQuote = sqlite3Isdigit(zIdent[0])
123457            || sqlite3KeywordCode(zIdent, j)!=TK_ID
123458            || zIdent[j]!=0
123459            || j==0;
123460
123461  if( needQuote ) z[i++] = '"';
123462  for(j=0; zIdent[j]; j++){
123463    z[i++] = zIdent[j];
123464    if( zIdent[j]=='"' ) z[i++] = '"';
123465  }
123466  if( needQuote ) z[i++] = '"';
123467  z[i] = 0;
123468  *pIdx = i;
123469}
123470
123471/*
123472** Generate a CREATE TABLE statement appropriate for the given
123473** table.  Memory to hold the text of the statement is obtained
123474** from sqliteMalloc() and must be freed by the calling function.
123475*/
123476static char *createTableStmt(sqlite3 *db, Table *p){
123477  int i, k, n;
123478  char *zStmt;
123479  char *zSep, *zSep2, *zEnd;
123480  Column *pCol;
123481  n = 0;
123482  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
123483    n += identLength(pCol->zCnName) + 5;
123484  }
123485  n += identLength(p->zName);
123486  if( n<50 ){
123487    zSep = "";
123488    zSep2 = ",";
123489    zEnd = ")";
123490  }else{
123491    zSep = "\n  ";
123492    zSep2 = ",\n  ";
123493    zEnd = "\n)";
123494  }
123495  n += 35 + 6*p->nCol;
123496  zStmt = sqlite3DbMallocRaw(0, n);
123497  if( zStmt==0 ){
123498    sqlite3OomFault(db);
123499    return 0;
123500  }
123501  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
123502  k = sqlite3Strlen30(zStmt);
123503  identPut(zStmt, &k, p->zName);
123504  zStmt[k++] = '(';
123505  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
123506    static const char * const azType[] = {
123507        /* SQLITE_AFF_BLOB    */ "",
123508        /* SQLITE_AFF_TEXT    */ " TEXT",
123509        /* SQLITE_AFF_NUMERIC */ " NUM",
123510        /* SQLITE_AFF_INTEGER */ " INT",
123511        /* SQLITE_AFF_REAL    */ " REAL",
123512        /* SQLITE_AFF_FLEXNUM */ " NUM",
123513    };
123514    int len;
123515    const char *zType;
123516
123517    sqlite3_snprintf(n-k, &zStmt[k], zSep);
123518    k += sqlite3Strlen30(&zStmt[k]);
123519    zSep = zSep2;
123520    identPut(zStmt, &k, pCol->zCnName);
123521    assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
123522    assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
123523    testcase( pCol->affinity==SQLITE_AFF_BLOB );
123524    testcase( pCol->affinity==SQLITE_AFF_TEXT );
123525    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
123526    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
123527    testcase( pCol->affinity==SQLITE_AFF_REAL );
123528    testcase( pCol->affinity==SQLITE_AFF_FLEXNUM );
123529
123530    zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
123531    len = sqlite3Strlen30(zType);
123532    assert( pCol->affinity==SQLITE_AFF_BLOB
123533            || pCol->affinity==SQLITE_AFF_FLEXNUM
123534            || pCol->affinity==sqlite3AffinityType(zType, 0) );
123535    memcpy(&zStmt[k], zType, len);
123536    k += len;
123537    assert( k<=n );
123538  }
123539  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
123540  return zStmt;
123541}
123542
123543/*
123544** Resize an Index object to hold N columns total.  Return SQLITE_OK
123545** on success and SQLITE_NOMEM on an OOM error.
123546*/
123547static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
123548  char *zExtra;
123549  int nByte;
123550  if( pIdx->nColumn>=N ) return SQLITE_OK;
123551  assert( pIdx->isResized==0 );
123552  nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N;
123553  zExtra = sqlite3DbMallocZero(db, nByte);
123554  if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
123555  memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
123556  pIdx->azColl = (const char**)zExtra;
123557  zExtra += sizeof(char*)*N;
123558  memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1));
123559  pIdx->aiRowLogEst = (LogEst*)zExtra;
123560  zExtra += sizeof(LogEst)*N;
123561  memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
123562  pIdx->aiColumn = (i16*)zExtra;
123563  zExtra += sizeof(i16)*N;
123564  memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
123565  pIdx->aSortOrder = (u8*)zExtra;
123566  pIdx->nColumn = N;
123567  pIdx->isResized = 1;
123568  return SQLITE_OK;
123569}
123570
123571/*
123572** Estimate the total row width for a table.
123573*/
123574static void estimateTableWidth(Table *pTab){
123575  unsigned wTable = 0;
123576  const Column *pTabCol;
123577  int i;
123578  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
123579    wTable += pTabCol->szEst;
123580  }
123581  if( pTab->iPKey<0 ) wTable++;
123582  pTab->szTabRow = sqlite3LogEst(wTable*4);
123583}
123584
123585/*
123586** Estimate the average size of a row for an index.
123587*/
123588static void estimateIndexWidth(Index *pIdx){
123589  unsigned wIndex = 0;
123590  int i;
123591  const Column *aCol = pIdx->pTable->aCol;
123592  for(i=0; i<pIdx->nColumn; i++){
123593    i16 x = pIdx->aiColumn[i];
123594    assert( x<pIdx->pTable->nCol );
123595    wIndex += x<0 ? 1 : aCol[x].szEst;
123596  }
123597  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
123598}
123599
123600/* Return true if column number x is any of the first nCol entries of aiCol[].
123601** This is used to determine if the column number x appears in any of the
123602** first nCol entries of an index.
123603*/
123604static int hasColumn(const i16 *aiCol, int nCol, int x){
123605  while( nCol-- > 0 ){
123606    if( x==*(aiCol++) ){
123607      return 1;
123608    }
123609  }
123610  return 0;
123611}
123612
123613/*
123614** Return true if any of the first nKey entries of index pIdx exactly
123615** match the iCol-th entry of pPk.  pPk is always a WITHOUT ROWID
123616** PRIMARY KEY index.  pIdx is an index on the same table.  pIdx may
123617** or may not be the same index as pPk.
123618**
123619** The first nKey entries of pIdx are guaranteed to be ordinary columns,
123620** not a rowid or expression.
123621**
123622** This routine differs from hasColumn() in that both the column and the
123623** collating sequence must match for this routine, but for hasColumn() only
123624** the column name must match.
123625*/
123626static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
123627  int i, j;
123628  assert( nKey<=pIdx->nColumn );
123629  assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
123630  assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
123631  assert( pPk->pTable->tabFlags & TF_WithoutRowid );
123632  assert( pPk->pTable==pIdx->pTable );
123633  testcase( pPk==pIdx );
123634  j = pPk->aiColumn[iCol];
123635  assert( j!=XN_ROWID && j!=XN_EXPR );
123636  for(i=0; i<nKey; i++){
123637    assert( pIdx->aiColumn[i]>=0 || j>=0 );
123638    if( pIdx->aiColumn[i]==j
123639     && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
123640    ){
123641      return 1;
123642    }
123643  }
123644  return 0;
123645}
123646
123647/* Recompute the colNotIdxed field of the Index.
123648**
123649** colNotIdxed is a bitmask that has a 0 bit representing each indexed
123650** columns that are within the first 63 columns of the table and a 1 for
123651** all other bits (all columns that are not in the index).  The
123652** high-order bit of colNotIdxed is always 1.  All unindexed columns
123653** of the table have a 1.
123654**
123655** 2019-10-24:  For the purpose of this computation, virtual columns are
123656** not considered to be covered by the index, even if they are in the
123657** index, because we do not trust the logic in whereIndexExprTrans() to be
123658** able to find all instances of a reference to the indexed table column
123659** and convert them into references to the index.  Hence we always want
123660** the actual table at hand in order to recompute the virtual column, if
123661** necessary.
123662**
123663** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
123664** to determine if the index is covering index.
123665*/
123666static void recomputeColumnsNotIndexed(Index *pIdx){
123667  Bitmask m = 0;
123668  int j;
123669  Table *pTab = pIdx->pTable;
123670  for(j=pIdx->nColumn-1; j>=0; j--){
123671    int x = pIdx->aiColumn[j];
123672    if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
123673      testcase( x==BMS-1 );
123674      testcase( x==BMS-2 );
123675      if( x<BMS-1 ) m |= MASKBIT(x);
123676    }
123677  }
123678  pIdx->colNotIdxed = ~m;
123679  assert( (pIdx->colNotIdxed>>63)==1 );  /* See note-20221022-a */
123680}
123681
123682/*
123683** This routine runs at the end of parsing a CREATE TABLE statement that
123684** has a WITHOUT ROWID clause.  The job of this routine is to convert both
123685** internal schema data structures and the generated VDBE code so that they
123686** are appropriate for a WITHOUT ROWID table instead of a rowid table.
123687** Changes include:
123688**
123689**     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
123690**     (2)  Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
123691**          into BTREE_BLOBKEY.
123692**     (3)  Bypass the creation of the sqlite_schema table entry
123693**          for the PRIMARY KEY as the primary key index is now
123694**          identified by the sqlite_schema table entry of the table itself.
123695**     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
123696**          schema to the rootpage from the main table.
123697**     (5)  Add all table columns to the PRIMARY KEY Index object
123698**          so that the PRIMARY KEY is a covering index.  The surplus
123699**          columns are part of KeyInfo.nAllField and are not used for
123700**          sorting or lookup or uniqueness checks.
123701**     (6)  Replace the rowid tail on all automatically generated UNIQUE
123702**          indices with the PRIMARY KEY columns.
123703**
123704** For virtual tables, only (1) is performed.
123705*/
123706static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
123707  Index *pIdx;
123708  Index *pPk;
123709  int nPk;
123710  int nExtra;
123711  int i, j;
123712  sqlite3 *db = pParse->db;
123713  Vdbe *v = pParse->pVdbe;
123714
123715  /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
123716  */
123717  if( !db->init.imposterTable ){
123718    for(i=0; i<pTab->nCol; i++){
123719      if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
123720       && (pTab->aCol[i].notNull==OE_None)
123721      ){
123722        pTab->aCol[i].notNull = OE_Abort;
123723      }
123724    }
123725    pTab->tabFlags |= TF_HasNotNull;
123726  }
123727
123728  /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
123729  ** into BTREE_BLOBKEY.
123730  */
123731  assert( !pParse->bReturning );
123732  if( pParse->u1.addrCrTab ){
123733    assert( v );
123734    sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY);
123735  }
123736
123737  /* Locate the PRIMARY KEY index.  Or, if this table was originally
123738  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
123739  */
123740  if( pTab->iPKey>=0 ){
123741    ExprList *pList;
123742    Token ipkToken;
123743    sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zCnName);
123744    pList = sqlite3ExprListAppend(pParse, 0,
123745                  sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
123746    if( pList==0 ){
123747      pTab->tabFlags &= ~TF_WithoutRowid;
123748      return;
123749    }
123750    if( IN_RENAME_OBJECT ){
123751      sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
123752    }
123753    pList->a[0].fg.sortFlags = pParse->iPkSortOrder;
123754    assert( pParse->pNewTable==pTab );
123755    pTab->iPKey = -1;
123756    sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
123757                       SQLITE_IDXTYPE_PRIMARYKEY);
123758    if( pParse->nErr ){
123759      pTab->tabFlags &= ~TF_WithoutRowid;
123760      return;
123761    }
123762    assert( db->mallocFailed==0 );
123763    pPk = sqlite3PrimaryKeyIndex(pTab);
123764    assert( pPk->nKeyCol==1 );
123765  }else{
123766    pPk = sqlite3PrimaryKeyIndex(pTab);
123767    assert( pPk!=0 );
123768
123769    /*
123770    ** Remove all redundant columns from the PRIMARY KEY.  For example, change
123771    ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
123772    ** code assumes the PRIMARY KEY contains no repeated columns.
123773    */
123774    for(i=j=1; i<pPk->nKeyCol; i++){
123775      if( isDupColumn(pPk, j, pPk, i) ){
123776        pPk->nColumn--;
123777      }else{
123778        testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
123779        pPk->azColl[j] = pPk->azColl[i];
123780        pPk->aSortOrder[j] = pPk->aSortOrder[i];
123781        pPk->aiColumn[j++] = pPk->aiColumn[i];
123782      }
123783    }
123784    pPk->nKeyCol = j;
123785  }
123786  assert( pPk!=0 );
123787  pPk->isCovering = 1;
123788  if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
123789  nPk = pPk->nColumn = pPk->nKeyCol;
123790
123791  /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema
123792  ** table entry. This is only required if currently generating VDBE
123793  ** code for a CREATE TABLE (not when parsing one as part of reading
123794  ** a database schema).  */
123795  if( v && pPk->tnum>0 ){
123796    assert( db->init.busy==0 );
123797    sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto);
123798  }
123799
123800  /* The root page of the PRIMARY KEY is the table root page */
123801  pPk->tnum = pTab->tnum;
123802
123803  /* Update the in-memory representation of all UNIQUE indices by converting
123804  ** the final rowid column into one or more columns of the PRIMARY KEY.
123805  */
123806  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
123807    int n;
123808    if( IsPrimaryKeyIndex(pIdx) ) continue;
123809    for(i=n=0; i<nPk; i++){
123810      if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
123811        testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
123812        n++;
123813      }
123814    }
123815    if( n==0 ){
123816      /* This index is a superset of the primary key */
123817      pIdx->nColumn = pIdx->nKeyCol;
123818      continue;
123819    }
123820    if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
123821    for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
123822      if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
123823        testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
123824        pIdx->aiColumn[j] = pPk->aiColumn[i];
123825        pIdx->azColl[j] = pPk->azColl[i];
123826        if( pPk->aSortOrder[i] ){
123827          /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
123828          pIdx->bAscKeyBug = 1;
123829        }
123830        j++;
123831      }
123832    }
123833    assert( pIdx->nColumn>=pIdx->nKeyCol+n );
123834    assert( pIdx->nColumn>=j );
123835  }
123836
123837  /* Add all table columns to the PRIMARY KEY index
123838  */
123839  nExtra = 0;
123840  for(i=0; i<pTab->nCol; i++){
123841    if( !hasColumn(pPk->aiColumn, nPk, i)
123842     && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
123843  }
123844  if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;
123845  for(i=0, j=nPk; i<pTab->nCol; i++){
123846    if( !hasColumn(pPk->aiColumn, j, i)
123847     && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
123848    ){
123849      assert( j<pPk->nColumn );
123850      pPk->aiColumn[j] = i;
123851      pPk->azColl[j] = sqlite3StrBINARY;
123852      j++;
123853    }
123854  }
123855  assert( pPk->nColumn==j );
123856  assert( pTab->nNVCol<=j );
123857  recomputeColumnsNotIndexed(pPk);
123858}
123859
123860
123861#ifndef SQLITE_OMIT_VIRTUALTABLE
123862/*
123863** Return true if pTab is a virtual table and zName is a shadow table name
123864** for that virtual table.
123865*/
123866SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){
123867  int nName;                    /* Length of zName */
123868  Module *pMod;                 /* Module for the virtual table */
123869
123870  if( !IsVirtual(pTab) ) return 0;
123871  nName = sqlite3Strlen30(pTab->zName);
123872  if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
123873  if( zName[nName]!='_' ) return 0;
123874  pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
123875  if( pMod==0 ) return 0;
123876  if( pMod->pModule->iVersion<3 ) return 0;
123877  if( pMod->pModule->xShadowName==0 ) return 0;
123878  return pMod->pModule->xShadowName(zName+nName+1);
123879}
123880#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
123881
123882#ifndef SQLITE_OMIT_VIRTUALTABLE
123883/*
123884** Table pTab is a virtual table.  If it the virtual table implementation
123885** exists and has an xShadowName method, then loop over all other ordinary
123886** tables within the same schema looking for shadow tables of pTab, and mark
123887** any shadow tables seen using the TF_Shadow flag.
123888*/
123889SQLITE_PRIVATE void sqlite3MarkAllShadowTablesOf(sqlite3 *db, Table *pTab){
123890  int nName;                    /* Length of pTab->zName */
123891  Module *pMod;                 /* Module for the virtual table */
123892  HashElem *k;                  /* For looping through the symbol table */
123893
123894  assert( IsVirtual(pTab) );
123895  pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
123896  if( pMod==0 ) return;
123897  if( NEVER(pMod->pModule==0) ) return;
123898  if( pMod->pModule->iVersion<3 ) return;
123899  if( pMod->pModule->xShadowName==0 ) return;
123900  assert( pTab->zName!=0 );
123901  nName = sqlite3Strlen30(pTab->zName);
123902  for(k=sqliteHashFirst(&pTab->pSchema->tblHash); k; k=sqliteHashNext(k)){
123903    Table *pOther = sqliteHashData(k);
123904    assert( pOther->zName!=0 );
123905    if( !IsOrdinaryTable(pOther) ) continue;
123906    if( pOther->tabFlags & TF_Shadow ) continue;
123907    if( sqlite3StrNICmp(pOther->zName, pTab->zName, nName)==0
123908     && pOther->zName[nName]=='_'
123909     && pMod->pModule->xShadowName(pOther->zName+nName+1)
123910    ){
123911      pOther->tabFlags |= TF_Shadow;
123912    }
123913  }
123914}
123915#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
123916
123917#ifndef SQLITE_OMIT_VIRTUALTABLE
123918/*
123919** Return true if zName is a shadow table name in the current database
123920** connection.
123921**
123922** zName is temporarily modified while this routine is running, but is
123923** restored to its original value prior to this routine returning.
123924*/
123925SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
123926  char *zTail;                  /* Pointer to the last "_" in zName */
123927  Table *pTab;                  /* Table that zName is a shadow of */
123928  zTail = strrchr(zName, '_');
123929  if( zTail==0 ) return 0;
123930  *zTail = 0;
123931  pTab = sqlite3FindTable(db, zName, 0);
123932  *zTail = '_';
123933  if( pTab==0 ) return 0;
123934  if( !IsVirtual(pTab) ) return 0;
123935  return sqlite3IsShadowTableOf(db, pTab, zName);
123936}
123937#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
123938
123939
123940#ifdef SQLITE_DEBUG
123941/*
123942** Mark all nodes of an expression as EP_Immutable, indicating that
123943** they should not be changed.  Expressions attached to a table or
123944** index definition are tagged this way to help ensure that we do
123945** not pass them into code generator routines by mistake.
123946*/
123947static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){
123948  (void)pWalker;
123949  ExprSetVVAProperty(pExpr, EP_Immutable);
123950  return WRC_Continue;
123951}
123952static void markExprListImmutable(ExprList *pList){
123953  if( pList ){
123954    Walker w;
123955    memset(&w, 0, sizeof(w));
123956    w.xExprCallback = markImmutableExprStep;
123957    w.xSelectCallback = sqlite3SelectWalkNoop;
123958    w.xSelectCallback2 = 0;
123959    sqlite3WalkExprList(&w, pList);
123960  }
123961}
123962#else
123963#define markExprListImmutable(X)  /* no-op */
123964#endif /* SQLITE_DEBUG */
123965
123966
123967/*
123968** This routine is called to report the final ")" that terminates
123969** a CREATE TABLE statement.
123970**
123971** The table structure that other action routines have been building
123972** is added to the internal hash tables, assuming no errors have
123973** occurred.
123974**
123975** An entry for the table is made in the schema table on disk, unless
123976** this is a temporary table or db->init.busy==1.  When db->init.busy==1
123977** it means we are reading the sqlite_schema table because we just
123978** connected to the database or because the sqlite_schema table has
123979** recently changed, so the entry for this table already exists in
123980** the sqlite_schema table.  We do not want to create it again.
123981**
123982** If the pSelect argument is not NULL, it means that this routine
123983** was called to create a table generated from a
123984** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
123985** the new table will match the result set of the SELECT.
123986*/
123987SQLITE_PRIVATE void sqlite3EndTable(
123988  Parse *pParse,          /* Parse context */
123989  Token *pCons,           /* The ',' token after the last column defn. */
123990  Token *pEnd,            /* The ')' before options in the CREATE TABLE */
123991  u32 tabOpts,            /* Extra table options. Usually 0. */
123992  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
123993){
123994  Table *p;                 /* The new table */
123995  sqlite3 *db = pParse->db; /* The database connection */
123996  int iDb;                  /* Database in which the table lives */
123997  Index *pIdx;              /* An implied index of the table */
123998
123999  if( pEnd==0 && pSelect==0 ){
124000    return;
124001  }
124002  p = pParse->pNewTable;
124003  if( p==0 ) return;
124004
124005  if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
124006    p->tabFlags |= TF_Shadow;
124007  }
124008
124009  /* If the db->init.busy is 1 it means we are reading the SQL off the
124010  ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
124011  ** So do not write to the disk again.  Extract the root page number
124012  ** for the table from the db->init.newTnum field.  (The page number
124013  ** should have been put there by the sqliteOpenCb routine.)
124014  **
124015  ** If the root page number is 1, that means this is the sqlite_schema
124016  ** table itself.  So mark it read-only.
124017  */
124018  if( db->init.busy ){
124019    if( pSelect || (!IsOrdinaryTable(p) && db->init.newTnum) ){
124020      sqlite3ErrorMsg(pParse, "");
124021      return;
124022    }
124023    p->tnum = db->init.newTnum;
124024    if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
124025  }
124026
124027  /* Special processing for tables that include the STRICT keyword:
124028  **
124029  **   *  Do not allow custom column datatypes.  Every column must have
124030  **      a datatype that is one of INT, INTEGER, REAL, TEXT, or BLOB.
124031  **
124032  **   *  If a PRIMARY KEY is defined, other than the INTEGER PRIMARY KEY,
124033  **      then all columns of the PRIMARY KEY must have a NOT NULL
124034  **      constraint.
124035  */
124036  if( tabOpts & TF_Strict ){
124037    int ii;
124038    p->tabFlags |= TF_Strict;
124039    for(ii=0; ii<p->nCol; ii++){
124040      Column *pCol = &p->aCol[ii];
124041      if( pCol->eCType==COLTYPE_CUSTOM ){
124042        if( pCol->colFlags & COLFLAG_HASTYPE ){
124043          sqlite3ErrorMsg(pParse,
124044            "unknown datatype for %s.%s: \"%s\"",
124045            p->zName, pCol->zCnName, sqlite3ColumnType(pCol, "")
124046          );
124047        }else{
124048          sqlite3ErrorMsg(pParse, "missing datatype for %s.%s",
124049                          p->zName, pCol->zCnName);
124050        }
124051        return;
124052      }else if( pCol->eCType==COLTYPE_ANY ){
124053        pCol->affinity = SQLITE_AFF_BLOB;
124054      }
124055      if( (pCol->colFlags & COLFLAG_PRIMKEY)!=0
124056       && p->iPKey!=ii
124057       && pCol->notNull == OE_None
124058      ){
124059        pCol->notNull = OE_Abort;
124060        p->tabFlags |= TF_HasNotNull;
124061      }
124062    }
124063  }
124064
124065  assert( (p->tabFlags & TF_HasPrimaryKey)==0
124066       || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
124067  assert( (p->tabFlags & TF_HasPrimaryKey)!=0
124068       || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
124069
124070  /* Special processing for WITHOUT ROWID Tables */
124071  if( tabOpts & TF_WithoutRowid ){
124072    if( (p->tabFlags & TF_Autoincrement) ){
124073      sqlite3ErrorMsg(pParse,
124074          "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
124075      return;
124076    }
124077    if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
124078      sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
124079      return;
124080    }
124081    p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
124082    convertToWithoutRowidTable(pParse, p);
124083  }
124084  iDb = sqlite3SchemaToIndex(db, p->pSchema);
124085
124086#ifndef SQLITE_OMIT_CHECK
124087  /* Resolve names in all CHECK constraint expressions.
124088  */
124089  if( p->pCheck ){
124090    sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
124091    if( pParse->nErr ){
124092      /* If errors are seen, delete the CHECK constraints now, else they might
124093      ** actually be used if PRAGMA writable_schema=ON is set. */
124094      sqlite3ExprListDelete(db, p->pCheck);
124095      p->pCheck = 0;
124096    }else{
124097      markExprListImmutable(p->pCheck);
124098    }
124099  }
124100#endif /* !defined(SQLITE_OMIT_CHECK) */
124101#ifndef SQLITE_OMIT_GENERATED_COLUMNS
124102  if( p->tabFlags & TF_HasGenerated ){
124103    int ii, nNG = 0;
124104    testcase( p->tabFlags & TF_HasVirtual );
124105    testcase( p->tabFlags & TF_HasStored );
124106    for(ii=0; ii<p->nCol; ii++){
124107      u32 colFlags = p->aCol[ii].colFlags;
124108      if( (colFlags & COLFLAG_GENERATED)!=0 ){
124109        Expr *pX = sqlite3ColumnExpr(p, &p->aCol[ii]);
124110        testcase( colFlags & COLFLAG_VIRTUAL );
124111        testcase( colFlags & COLFLAG_STORED );
124112        if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
124113          /* If there are errors in resolving the expression, change the
124114          ** expression to a NULL.  This prevents code generators that operate
124115          ** on the expression from inserting extra parts into the expression
124116          ** tree that have been allocated from lookaside memory, which is
124117          ** illegal in a schema and will lead to errors or heap corruption
124118          ** when the database connection closes. */
124119          sqlite3ColumnSetExpr(pParse, p, &p->aCol[ii],
124120               sqlite3ExprAlloc(db, TK_NULL, 0, 0));
124121        }
124122      }else{
124123        nNG++;
124124      }
124125    }
124126    if( nNG==0 ){
124127      sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
124128      return;
124129    }
124130  }
124131#endif
124132
124133  /* Estimate the average row size for the table and for all implied indices */
124134  estimateTableWidth(p);
124135  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
124136    estimateIndexWidth(pIdx);
124137  }
124138
124139  /* If not initializing, then create a record for the new table
124140  ** in the schema table of the database.
124141  **
124142  ** If this is a TEMPORARY table, write the entry into the auxiliary
124143  ** file instead of into the main database file.
124144  */
124145  if( !db->init.busy ){
124146    int n;
124147    Vdbe *v;
124148    char *zType;    /* "view" or "table" */
124149    char *zType2;   /* "VIEW" or "TABLE" */
124150    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
124151
124152    v = sqlite3GetVdbe(pParse);
124153    if( NEVER(v==0) ) return;
124154
124155    sqlite3VdbeAddOp1(v, OP_Close, 0);
124156
124157    /*
124158    ** Initialize zType for the new view or table.
124159    */
124160    if( IsOrdinaryTable(p) ){
124161      /* A regular table */
124162      zType = "table";
124163      zType2 = "TABLE";
124164#ifndef SQLITE_OMIT_VIEW
124165    }else{
124166      /* A view */
124167      zType = "view";
124168      zType2 = "VIEW";
124169#endif
124170    }
124171
124172    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
124173    ** statement to populate the new table. The root-page number for the
124174    ** new table is in register pParse->regRoot.
124175    **
124176    ** Once the SELECT has been coded by sqlite3Select(), it is in a
124177    ** suitable state to query for the column names and types to be used
124178    ** by the new table.
124179    **
124180    ** A shared-cache write-lock is not required to write to the new table,
124181    ** as a schema-lock must have already been obtained to create it. Since
124182    ** a schema-lock excludes all other database users, the write-lock would
124183    ** be redundant.
124184    */
124185    if( pSelect ){
124186      SelectDest dest;    /* Where the SELECT should store results */
124187      int regYield;       /* Register holding co-routine entry-point */
124188      int addrTop;        /* Top of the co-routine */
124189      int regRec;         /* A record to be insert into the new table */
124190      int regRowid;       /* Rowid of the next row to insert */
124191      int addrInsLoop;    /* Top of the loop for inserting rows */
124192      Table *pSelTab;     /* A table that describes the SELECT results */
124193      int iCsr;           /* Write cursor on the new table */
124194
124195      if( IN_SPECIAL_PARSE ){
124196        pParse->rc = SQLITE_ERROR;
124197        pParse->nErr++;
124198        return;
124199      }
124200      iCsr = pParse->nTab++;
124201      regYield = ++pParse->nMem;
124202      regRec = ++pParse->nMem;
124203      regRowid = ++pParse->nMem;
124204      sqlite3MayAbort(pParse);
124205      sqlite3VdbeAddOp3(v, OP_OpenWrite, iCsr, pParse->regRoot, iDb);
124206      sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
124207      addrTop = sqlite3VdbeCurrentAddr(v) + 1;
124208      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
124209      if( pParse->nErr ) return;
124210      pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
124211      if( pSelTab==0 ) return;
124212      assert( p->aCol==0 );
124213      p->nCol = p->nNVCol = pSelTab->nCol;
124214      p->aCol = pSelTab->aCol;
124215      pSelTab->nCol = 0;
124216      pSelTab->aCol = 0;
124217      sqlite3DeleteTable(db, pSelTab);
124218      sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
124219      sqlite3Select(pParse, pSelect, &dest);
124220      if( pParse->nErr ) return;
124221      sqlite3VdbeEndCoroutine(v, regYield);
124222      sqlite3VdbeJumpHere(v, addrTop - 1);
124223      addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
124224      VdbeCoverage(v);
124225      sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
124226      sqlite3TableAffinity(v, p, 0);
124227      sqlite3VdbeAddOp2(v, OP_NewRowid, iCsr, regRowid);
124228      sqlite3VdbeAddOp3(v, OP_Insert, iCsr, regRec, regRowid);
124229      sqlite3VdbeGoto(v, addrInsLoop);
124230      sqlite3VdbeJumpHere(v, addrInsLoop);
124231      sqlite3VdbeAddOp1(v, OP_Close, iCsr);
124232    }
124233
124234    /* Compute the complete text of the CREATE statement */
124235    if( pSelect ){
124236      zStmt = createTableStmt(db, p);
124237    }else{
124238      Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
124239      n = (int)(pEnd2->z - pParse->sNameToken.z);
124240      if( pEnd2->z[0]!=';' ) n += pEnd2->n;
124241      zStmt = sqlite3MPrintf(db,
124242          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
124243      );
124244    }
124245
124246    /* A slot for the record has already been allocated in the
124247    ** schema table.  We just need to update that slot with all
124248    ** the information we've collected.
124249    */
124250    sqlite3NestedParse(pParse,
124251      "UPDATE %Q." LEGACY_SCHEMA_TABLE
124252      " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
124253      " WHERE rowid=#%d",
124254      db->aDb[iDb].zDbSName,
124255      zType,
124256      p->zName,
124257      p->zName,
124258      pParse->regRoot,
124259      zStmt,
124260      pParse->regRowid
124261    );
124262    sqlite3DbFree(db, zStmt);
124263    sqlite3ChangeCookie(pParse, iDb);
124264
124265#ifndef SQLITE_OMIT_AUTOINCREMENT
124266    /* Check to see if we need to create an sqlite_sequence table for
124267    ** keeping track of autoincrement keys.
124268    */
124269    if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){
124270      Db *pDb = &db->aDb[iDb];
124271      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
124272      if( pDb->pSchema->pSeqTab==0 ){
124273        sqlite3NestedParse(pParse,
124274          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
124275          pDb->zDbSName
124276        );
124277      }
124278    }
124279#endif
124280
124281    /* Reparse everything to update our internal data structures */
124282    sqlite3VdbeAddParseSchemaOp(v, iDb,
124283           sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0);
124284
124285    /* Test for cycles in generated columns and illegal expressions
124286    ** in CHECK constraints and in DEFAULT clauses. */
124287    if( p->tabFlags & TF_HasGenerated ){
124288      sqlite3VdbeAddOp4(v, OP_SqlExec, 0x0001, 0, 0,
124289             sqlite3MPrintf(db, "SELECT*FROM\"%w\".\"%w\"",
124290                   db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
124291    }
124292  }
124293
124294  /* Add the table to the in-memory representation of the database.
124295  */
124296  if( db->init.busy ){
124297    Table *pOld;
124298    Schema *pSchema = p->pSchema;
124299    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
124300    assert( HasRowid(p) || p->iPKey<0 );
124301    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
124302    if( pOld ){
124303      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
124304      sqlite3OomFault(db);
124305      return;
124306    }
124307    pParse->pNewTable = 0;
124308    db->mDbFlags |= DBFLAG_SchemaChange;
124309
124310    /* If this is the magic sqlite_sequence table used by autoincrement,
124311    ** then record a pointer to this table in the main database structure
124312    ** so that INSERT can find the table easily.  */
124313    assert( !pParse->nested );
124314#ifndef SQLITE_OMIT_AUTOINCREMENT
124315    if( strcmp(p->zName, "sqlite_sequence")==0 ){
124316      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
124317      p->pSchema->pSeqTab = p;
124318    }
124319#endif
124320  }
124321
124322#ifndef SQLITE_OMIT_ALTERTABLE
124323  if( !pSelect && IsOrdinaryTable(p) ){
124324    assert( pCons && pEnd );
124325    if( pCons->z==0 ){
124326      pCons = pEnd;
124327    }
124328    p->u.tab.addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
124329  }
124330#endif
124331}
124332
124333#ifndef SQLITE_OMIT_VIEW
124334/*
124335** The parser calls this routine in order to create a new VIEW
124336*/
124337SQLITE_PRIVATE void sqlite3CreateView(
124338  Parse *pParse,     /* The parsing context */
124339  Token *pBegin,     /* The CREATE token that begins the statement */
124340  Token *pName1,     /* The token that holds the name of the view */
124341  Token *pName2,     /* The token that holds the name of the view */
124342  ExprList *pCNames, /* Optional list of view column names */
124343  Select *pSelect,   /* A SELECT statement that will become the new view */
124344  int isTemp,        /* TRUE for a TEMPORARY view */
124345  int noErr          /* Suppress error messages if VIEW already exists */
124346){
124347  Table *p;
124348  int n;
124349  const char *z;
124350  Token sEnd;
124351  DbFixer sFix;
124352  Token *pName = 0;
124353  int iDb;
124354  sqlite3 *db = pParse->db;
124355
124356  if( pParse->nVar>0 ){
124357    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
124358    goto create_view_fail;
124359  }
124360  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
124361  p = pParse->pNewTable;
124362  if( p==0 || pParse->nErr ) goto create_view_fail;
124363
124364  /* Legacy versions of SQLite allowed the use of the magic "rowid" column
124365  ** on a view, even though views do not have rowids.  The following flag
124366  ** setting fixes this problem.  But the fix can be disabled by compiling
124367  ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that
124368  ** depend upon the old buggy behavior.  The ability can also be toggled
124369  ** using sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW,...) */
124370#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
124371  p->tabFlags |= sqlite3Config.mNoVisibleRowid; /* Optional. Allow by default */
124372#else
124373  p->tabFlags |= TF_NoVisibleRowid;             /* Never allow rowid in view */
124374#endif
124375
124376  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
124377  iDb = sqlite3SchemaToIndex(db, p->pSchema);
124378  sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
124379  if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
124380
124381  /* Make a copy of the entire SELECT statement that defines the view.
124382  ** This will force all the Expr.token.z values to be dynamically
124383  ** allocated rather than point to the input string - which means that
124384  ** they will persist after the current sqlite3_exec() call returns.
124385  */
124386  pSelect->selFlags |= SF_View;
124387  if( IN_RENAME_OBJECT ){
124388    p->u.view.pSelect = pSelect;
124389    pSelect = 0;
124390  }else{
124391    p->u.view.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
124392  }
124393  p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
124394  p->eTabType = TABTYP_VIEW;
124395  if( db->mallocFailed ) goto create_view_fail;
124396
124397  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
124398  ** the end.
124399  */
124400  sEnd = pParse->sLastToken;
124401  assert( sEnd.z[0]!=0 || sEnd.n==0 );
124402  if( sEnd.z[0]!=';' ){
124403    sEnd.z += sEnd.n;
124404  }
124405  sEnd.n = 0;
124406  n = (int)(sEnd.z - pBegin->z);
124407  assert( n>0 );
124408  z = pBegin->z;
124409  while( sqlite3Isspace(z[n-1]) ){ n--; }
124410  sEnd.z = &z[n-1];
124411  sEnd.n = 1;
124412
124413  /* Use sqlite3EndTable() to add the view to the schema table */
124414  sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
124415
124416create_view_fail:
124417  sqlite3SelectDelete(db, pSelect);
124418  if( IN_RENAME_OBJECT ){
124419    sqlite3RenameExprlistUnmap(pParse, pCNames);
124420  }
124421  sqlite3ExprListDelete(db, pCNames);
124422  return;
124423}
124424#endif /* SQLITE_OMIT_VIEW */
124425
124426#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
124427/*
124428** The Table structure pTable is really a VIEW.  Fill in the names of
124429** the columns of the view in the pTable structure.  Return the number
124430** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
124431*/
124432static SQLITE_NOINLINE int viewGetColumnNames(Parse *pParse, Table *pTable){
124433  Table *pSelTab;   /* A fake table from which we get the result set */
124434  Select *pSel;     /* Copy of the SELECT that implements the view */
124435  int nErr = 0;     /* Number of errors encountered */
124436  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
124437#ifndef SQLITE_OMIT_VIRTUALTABLE
124438  int rc;
124439#endif
124440#ifndef SQLITE_OMIT_AUTHORIZATION
124441  sqlite3_xauth xAuth;       /* Saved xAuth pointer */
124442#endif
124443
124444  assert( pTable );
124445
124446#ifndef SQLITE_OMIT_VIRTUALTABLE
124447  if( IsVirtual(pTable) ){
124448    db->nSchemaLock++;
124449    rc = sqlite3VtabCallConnect(pParse, pTable);
124450    db->nSchemaLock--;
124451    return rc;
124452  }
124453#endif
124454
124455#ifndef SQLITE_OMIT_VIEW
124456  /* A positive nCol means the columns names for this view are
124457  ** already known.  This routine is not called unless either the
124458  ** table is virtual or nCol is zero.
124459  */
124460  assert( pTable->nCol<=0 );
124461
124462  /* A negative nCol is a special marker meaning that we are currently
124463  ** trying to compute the column names.  If we enter this routine with
124464  ** a negative nCol, it means two or more views form a loop, like this:
124465  **
124466  **     CREATE VIEW one AS SELECT * FROM two;
124467  **     CREATE VIEW two AS SELECT * FROM one;
124468  **
124469  ** Actually, the error above is now caught prior to reaching this point.
124470  ** But the following test is still important as it does come up
124471  ** in the following:
124472  **
124473  **     CREATE TABLE main.ex1(a);
124474  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
124475  **     SELECT * FROM temp.ex1;
124476  */
124477  if( pTable->nCol<0 ){
124478    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
124479    return 1;
124480  }
124481  assert( pTable->nCol>=0 );
124482
124483  /* If we get this far, it means we need to compute the table names.
124484  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
124485  ** "*" elements in the results set of the view and will assign cursors
124486  ** to the elements of the FROM clause.  But we do not want these changes
124487  ** to be permanent.  So the computation is done on a copy of the SELECT
124488  ** statement that defines the view.
124489  */
124490  assert( IsView(pTable) );
124491  pSel = sqlite3SelectDup(db, pTable->u.view.pSelect, 0);
124492  if( pSel ){
124493    u8 eParseMode = pParse->eParseMode;
124494    int nTab = pParse->nTab;
124495    int nSelect = pParse->nSelect;
124496    pParse->eParseMode = PARSE_MODE_NORMAL;
124497    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
124498    pTable->nCol = -1;
124499    DisableLookaside;
124500#ifndef SQLITE_OMIT_AUTHORIZATION
124501    xAuth = db->xAuth;
124502    db->xAuth = 0;
124503    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
124504    db->xAuth = xAuth;
124505#else
124506    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
124507#endif
124508    pParse->nTab = nTab;
124509    pParse->nSelect = nSelect;
124510    if( pSelTab==0 ){
124511      pTable->nCol = 0;
124512      nErr++;
124513    }else if( pTable->pCheck ){
124514      /* CREATE VIEW name(arglist) AS ...
124515      ** The names of the columns in the table are taken from
124516      ** arglist which is stored in pTable->pCheck.  The pCheck field
124517      ** normally holds CHECK constraints on an ordinary table, but for
124518      ** a VIEW it holds the list of column names.
124519      */
124520      sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
124521                                 &pTable->nCol, &pTable->aCol);
124522      if( pParse->nErr==0
124523       && pTable->nCol==pSel->pEList->nExpr
124524      ){
124525        assert( db->mallocFailed==0 );
124526        sqlite3SubqueryColumnTypes(pParse, pTable, pSel, SQLITE_AFF_NONE);
124527      }
124528    }else{
124529      /* CREATE VIEW name AS...  without an argument list.  Construct
124530      ** the column names from the SELECT statement that defines the view.
124531      */
124532      assert( pTable->aCol==0 );
124533      pTable->nCol = pSelTab->nCol;
124534      pTable->aCol = pSelTab->aCol;
124535      pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT);
124536      pSelTab->nCol = 0;
124537      pSelTab->aCol = 0;
124538      assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
124539    }
124540    pTable->nNVCol = pTable->nCol;
124541    sqlite3DeleteTable(db, pSelTab);
124542    sqlite3SelectDelete(db, pSel);
124543    EnableLookaside;
124544    pParse->eParseMode = eParseMode;
124545  } else {
124546    nErr++;
124547  }
124548  pTable->pSchema->schemaFlags |= DB_UnresetViews;
124549  if( db->mallocFailed ){
124550    sqlite3DeleteColumnNames(db, pTable);
124551  }
124552#endif /* SQLITE_OMIT_VIEW */
124553  return nErr;
124554}
124555SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
124556  assert( pTable!=0 );
124557  if( !IsVirtual(pTable) && pTable->nCol>0 ) return 0;
124558  return viewGetColumnNames(pParse, pTable);
124559}
124560#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
124561
124562#ifndef SQLITE_OMIT_VIEW
124563/*
124564** Clear the column names from every VIEW in database idx.
124565*/
124566static void sqliteViewResetAll(sqlite3 *db, int idx){
124567  HashElem *i;
124568  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
124569  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
124570  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
124571    Table *pTab = sqliteHashData(i);
124572    if( IsView(pTab) ){
124573      sqlite3DeleteColumnNames(db, pTab);
124574    }
124575  }
124576  DbClearProperty(db, idx, DB_UnresetViews);
124577}
124578#else
124579# define sqliteViewResetAll(A,B)
124580#endif /* SQLITE_OMIT_VIEW */
124581
124582/*
124583** This function is called by the VDBE to adjust the internal schema
124584** used by SQLite when the btree layer moves a table root page. The
124585** root-page of a table or index in database iDb has changed from iFrom
124586** to iTo.
124587**
124588** Ticket #1728:  The symbol table might still contain information
124589** on tables and/or indices that are the process of being deleted.
124590** If you are unlucky, one of those deleted indices or tables might
124591** have the same rootpage number as the real table or index that is
124592** being moved.  So we cannot stop searching after the first match
124593** because the first match might be for one of the deleted indices
124594** or tables and not the table/index that is actually being moved.
124595** We must continue looping until all tables and indices with
124596** rootpage==iFrom have been converted to have a rootpage of iTo
124597** in order to be certain that we got the right one.
124598*/
124599#ifndef SQLITE_OMIT_AUTOVACUUM
124600SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){
124601  HashElem *pElem;
124602  Hash *pHash;
124603  Db *pDb;
124604
124605  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
124606  pDb = &db->aDb[iDb];
124607  pHash = &pDb->pSchema->tblHash;
124608  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
124609    Table *pTab = sqliteHashData(pElem);
124610    if( pTab->tnum==iFrom ){
124611      pTab->tnum = iTo;
124612    }
124613  }
124614  pHash = &pDb->pSchema->idxHash;
124615  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
124616    Index *pIdx = sqliteHashData(pElem);
124617    if( pIdx->tnum==iFrom ){
124618      pIdx->tnum = iTo;
124619    }
124620  }
124621}
124622#endif
124623
124624/*
124625** Write code to erase the table with root-page iTable from database iDb.
124626** Also write code to modify the sqlite_schema table and internal schema
124627** if a root-page of another table is moved by the btree-layer whilst
124628** erasing iTable (this can happen with an auto-vacuum database).
124629*/
124630static void destroyRootPage(Parse *pParse, int iTable, int iDb){
124631  Vdbe *v = sqlite3GetVdbe(pParse);
124632  int r1 = sqlite3GetTempReg(pParse);
124633  if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
124634  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
124635  sqlite3MayAbort(pParse);
124636#ifndef SQLITE_OMIT_AUTOVACUUM
124637  /* OP_Destroy stores an in integer r1. If this integer
124638  ** is non-zero, then it is the root page number of a table moved to
124639  ** location iTable. The following code modifies the sqlite_schema table to
124640  ** reflect this.
124641  **
124642  ** The "#NNN" in the SQL is a special constant that means whatever value
124643  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
124644  ** token for additional information.
124645  */
124646  sqlite3NestedParse(pParse,
124647     "UPDATE %Q." LEGACY_SCHEMA_TABLE
124648     " SET rootpage=%d WHERE #%d AND rootpage=#%d",
124649     pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
124650#endif
124651  sqlite3ReleaseTempReg(pParse, r1);
124652}
124653
124654/*
124655** Write VDBE code to erase table pTab and all associated indices on disk.
124656** Code to update the sqlite_schema tables and internal schema definitions
124657** in case a root-page belonging to another table is moved by the btree layer
124658** is also added (this can happen with an auto-vacuum database).
124659*/
124660static void destroyTable(Parse *pParse, Table *pTab){
124661  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
124662  ** is not defined), then it is important to call OP_Destroy on the
124663  ** table and index root-pages in order, starting with the numerically
124664  ** largest root-page number. This guarantees that none of the root-pages
124665  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
124666  ** following were coded:
124667  **
124668  ** OP_Destroy 4 0
124669  ** ...
124670  ** OP_Destroy 5 0
124671  **
124672  ** and root page 5 happened to be the largest root-page number in the
124673  ** database, then root page 5 would be moved to page 4 by the
124674  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
124675  ** a free-list page.
124676  */
124677  Pgno iTab = pTab->tnum;
124678  Pgno iDestroyed = 0;
124679
124680  while( 1 ){
124681    Index *pIdx;
124682    Pgno iLargest = 0;
124683
124684    if( iDestroyed==0 || iTab<iDestroyed ){
124685      iLargest = iTab;
124686    }
124687    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
124688      Pgno iIdx = pIdx->tnum;
124689      assert( pIdx->pSchema==pTab->pSchema );
124690      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
124691        iLargest = iIdx;
124692      }
124693    }
124694    if( iLargest==0 ){
124695      return;
124696    }else{
124697      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
124698      assert( iDb>=0 && iDb<pParse->db->nDb );
124699      destroyRootPage(pParse, iLargest, iDb);
124700      iDestroyed = iLargest;
124701    }
124702  }
124703}
124704
124705/*
124706** Remove entries from the sqlite_statN tables (for N in (1,2,3))
124707** after a DROP INDEX or DROP TABLE command.
124708*/
124709static void sqlite3ClearStatTables(
124710  Parse *pParse,         /* The parsing context */
124711  int iDb,               /* The database number */
124712  const char *zType,     /* "idx" or "tbl" */
124713  const char *zName      /* Name of index or table */
124714){
124715  int i;
124716  const char *zDbName = pParse->db->aDb[iDb].zDbSName;
124717  for(i=1; i<=4; i++){
124718    char zTab[24];
124719    sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
124720    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
124721      sqlite3NestedParse(pParse,
124722        "DELETE FROM %Q.%s WHERE %s=%Q",
124723        zDbName, zTab, zType, zName
124724      );
124725    }
124726  }
124727}
124728
124729/*
124730** Generate code to drop a table.
124731*/
124732SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
124733  Vdbe *v;
124734  sqlite3 *db = pParse->db;
124735  Trigger *pTrigger;
124736  Db *pDb = &db->aDb[iDb];
124737
124738  v = sqlite3GetVdbe(pParse);
124739  assert( v!=0 );
124740  sqlite3BeginWriteOperation(pParse, 1, iDb);
124741
124742#ifndef SQLITE_OMIT_VIRTUALTABLE
124743  if( IsVirtual(pTab) ){
124744    sqlite3VdbeAddOp0(v, OP_VBegin);
124745  }
124746#endif
124747
124748  /* Drop all triggers associated with the table being dropped. Code
124749  ** is generated to remove entries from sqlite_schema and/or
124750  ** sqlite_temp_schema if required.
124751  */
124752  pTrigger = sqlite3TriggerList(pParse, pTab);
124753  while( pTrigger ){
124754    assert( pTrigger->pSchema==pTab->pSchema ||
124755        pTrigger->pSchema==db->aDb[1].pSchema );
124756    sqlite3DropTriggerPtr(pParse, pTrigger);
124757    pTrigger = pTrigger->pNext;
124758  }
124759
124760#ifndef SQLITE_OMIT_AUTOINCREMENT
124761  /* Remove any entries of the sqlite_sequence table associated with
124762  ** the table being dropped. This is done before the table is dropped
124763  ** at the btree level, in case the sqlite_sequence table needs to
124764  ** move as a result of the drop (can happen in auto-vacuum mode).
124765  */
124766  if( pTab->tabFlags & TF_Autoincrement ){
124767    sqlite3NestedParse(pParse,
124768      "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
124769      pDb->zDbSName, pTab->zName
124770    );
124771  }
124772#endif
124773
124774  /* Drop all entries in the schema table that refer to the
124775  ** table. The program name loops through the schema table and deletes
124776  ** every row that refers to a table of the same name as the one being
124777  ** dropped. Triggers are handled separately because a trigger can be
124778  ** created in the temp database that refers to a table in another
124779  ** database.
124780  */
124781  sqlite3NestedParse(pParse,
124782      "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
124783      " WHERE tbl_name=%Q and type!='trigger'",
124784      pDb->zDbSName, pTab->zName);
124785  if( !isView && !IsVirtual(pTab) ){
124786    destroyTable(pParse, pTab);
124787  }
124788
124789  /* Remove the table entry from SQLite's internal schema and modify
124790  ** the schema cookie.
124791  */
124792  if( IsVirtual(pTab) ){
124793    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
124794    sqlite3MayAbort(pParse);
124795  }
124796  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
124797  sqlite3ChangeCookie(pParse, iDb);
124798  sqliteViewResetAll(db, iDb);
124799}
124800
124801/*
124802** Return TRUE if shadow tables should be read-only in the current
124803** context.
124804*/
124805SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db){
124806#ifndef SQLITE_OMIT_VIRTUALTABLE
124807  if( (db->flags & SQLITE_Defensive)!=0
124808   && db->pVtabCtx==0
124809   && db->nVdbeExec==0
124810   && !sqlite3VtabInSync(db)
124811  ){
124812    return 1;
124813  }
124814#endif
124815  return 0;
124816}
124817
124818/*
124819** Return true if it is not allowed to drop the given table
124820*/
124821static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
124822  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
124823    if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
124824    if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
124825    return 1;
124826  }
124827  if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
124828    return 1;
124829  }
124830  if( pTab->tabFlags & TF_Eponymous ){
124831    return 1;
124832  }
124833  return 0;
124834}
124835
124836/*
124837** This routine is called to do the work of a DROP TABLE statement.
124838** pName is the name of the table to be dropped.
124839*/
124840SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
124841  Table *pTab;
124842  Vdbe *v;
124843  sqlite3 *db = pParse->db;
124844  int iDb;
124845
124846  if( db->mallocFailed ){
124847    goto exit_drop_table;
124848  }
124849  assert( pParse->nErr==0 );
124850  assert( pName->nSrc==1 );
124851  if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
124852  if( noErr ) db->suppressErr++;
124853  assert( isView==0 || isView==LOCATE_VIEW );
124854  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
124855  if( noErr ) db->suppressErr--;
124856
124857  if( pTab==0 ){
124858    if( noErr ){
124859      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
124860      sqlite3ForceNotReadOnly(pParse);
124861    }
124862    goto exit_drop_table;
124863  }
124864  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
124865  assert( iDb>=0 && iDb<db->nDb );
124866
124867  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
124868  ** it is initialized.
124869  */
124870  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
124871    goto exit_drop_table;
124872  }
124873#ifndef SQLITE_OMIT_AUTHORIZATION
124874  {
124875    int code;
124876    const char *zTab = SCHEMA_TABLE(iDb);
124877    const char *zDb = db->aDb[iDb].zDbSName;
124878    const char *zArg2 = 0;
124879    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
124880      goto exit_drop_table;
124881    }
124882    if( isView ){
124883      if( !OMIT_TEMPDB && iDb==1 ){
124884        code = SQLITE_DROP_TEMP_VIEW;
124885      }else{
124886        code = SQLITE_DROP_VIEW;
124887      }
124888#ifndef SQLITE_OMIT_VIRTUALTABLE
124889    }else if( IsVirtual(pTab) ){
124890      code = SQLITE_DROP_VTABLE;
124891      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
124892#endif
124893    }else{
124894      if( !OMIT_TEMPDB && iDb==1 ){
124895        code = SQLITE_DROP_TEMP_TABLE;
124896      }else{
124897        code = SQLITE_DROP_TABLE;
124898      }
124899    }
124900    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
124901      goto exit_drop_table;
124902    }
124903    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
124904      goto exit_drop_table;
124905    }
124906  }
124907#endif
124908  if( tableMayNotBeDropped(db, pTab) ){
124909    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
124910    goto exit_drop_table;
124911  }
124912
124913#ifndef SQLITE_OMIT_VIEW
124914  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
124915  ** on a table.
124916  */
124917  if( isView && !IsView(pTab) ){
124918    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
124919    goto exit_drop_table;
124920  }
124921  if( !isView && IsView(pTab) ){
124922    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
124923    goto exit_drop_table;
124924  }
124925#endif
124926
124927  /* Generate code to remove the table from the schema table
124928  ** on disk.
124929  */
124930  v = sqlite3GetVdbe(pParse);
124931  if( v ){
124932    sqlite3BeginWriteOperation(pParse, 1, iDb);
124933    if( !isView ){
124934      sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
124935      sqlite3FkDropTable(pParse, pName, pTab);
124936    }
124937    sqlite3CodeDropTable(pParse, pTab, iDb, isView);
124938  }
124939
124940exit_drop_table:
124941  sqlite3SrcListDelete(db, pName);
124942}
124943
124944/*
124945** This routine is called to create a new foreign key on the table
124946** currently under construction.  pFromCol determines which columns
124947** in the current table point to the foreign key.  If pFromCol==0 then
124948** connect the key to the last column inserted.  pTo is the name of
124949** the table referred to (a.k.a the "parent" table).  pToCol is a list
124950** of tables in the parent pTo table.  flags contains all
124951** information about the conflict resolution algorithms specified
124952** in the ON DELETE, ON UPDATE and ON INSERT clauses.
124953**
124954** An FKey structure is created and added to the table currently
124955** under construction in the pParse->pNewTable field.
124956**
124957** The foreign key is set for IMMEDIATE processing.  A subsequent call
124958** to sqlite3DeferForeignKey() might change this to DEFERRED.
124959*/
124960SQLITE_PRIVATE void sqlite3CreateForeignKey(
124961  Parse *pParse,       /* Parsing context */
124962  ExprList *pFromCol,  /* Columns in this table that point to other table */
124963  Token *pTo,          /* Name of the other table */
124964  ExprList *pToCol,    /* Columns in the other table */
124965  int flags            /* Conflict resolution algorithms. */
124966){
124967  sqlite3 *db = pParse->db;
124968#ifndef SQLITE_OMIT_FOREIGN_KEY
124969  FKey *pFKey = 0;
124970  FKey *pNextTo;
124971  Table *p = pParse->pNewTable;
124972  i64 nByte;
124973  int i;
124974  int nCol;
124975  char *z;
124976
124977  assert( pTo!=0 );
124978  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
124979  if( pFromCol==0 ){
124980    int iCol = p->nCol-1;
124981    if( NEVER(iCol<0) ) goto fk_end;
124982    if( pToCol && pToCol->nExpr!=1 ){
124983      sqlite3ErrorMsg(pParse, "foreign key on %s"
124984         " should reference only one column of table %T",
124985         p->aCol[iCol].zCnName, pTo);
124986      goto fk_end;
124987    }
124988    nCol = 1;
124989  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
124990    sqlite3ErrorMsg(pParse,
124991        "number of columns in foreign key does not match the number of "
124992        "columns in the referenced table");
124993    goto fk_end;
124994  }else{
124995    nCol = pFromCol->nExpr;
124996  }
124997  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
124998  if( pToCol ){
124999    for(i=0; i<pToCol->nExpr; i++){
125000      nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
125001    }
125002  }
125003  pFKey = sqlite3DbMallocZero(db, nByte );
125004  if( pFKey==0 ){
125005    goto fk_end;
125006  }
125007  pFKey->pFrom = p;
125008  assert( IsOrdinaryTable(p) );
125009  pFKey->pNextFrom = p->u.tab.pFKey;
125010  z = (char*)&pFKey->aCol[nCol];
125011  pFKey->zTo = z;
125012  if( IN_RENAME_OBJECT ){
125013    sqlite3RenameTokenMap(pParse, (void*)z, pTo);
125014  }
125015  memcpy(z, pTo->z, pTo->n);
125016  z[pTo->n] = 0;
125017  sqlite3Dequote(z);
125018  z += pTo->n+1;
125019  pFKey->nCol = nCol;
125020  if( pFromCol==0 ){
125021    pFKey->aCol[0].iFrom = p->nCol-1;
125022  }else{
125023    for(i=0; i<nCol; i++){
125024      int j;
125025      for(j=0; j<p->nCol; j++){
125026        if( sqlite3StrICmp(p->aCol[j].zCnName, pFromCol->a[i].zEName)==0 ){
125027          pFKey->aCol[i].iFrom = j;
125028          break;
125029        }
125030      }
125031      if( j>=p->nCol ){
125032        sqlite3ErrorMsg(pParse,
125033          "unknown column \"%s\" in foreign key definition",
125034          pFromCol->a[i].zEName);
125035        goto fk_end;
125036      }
125037      if( IN_RENAME_OBJECT ){
125038        sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
125039      }
125040    }
125041  }
125042  if( pToCol ){
125043    for(i=0; i<nCol; i++){
125044      int n = sqlite3Strlen30(pToCol->a[i].zEName);
125045      pFKey->aCol[i].zCol = z;
125046      if( IN_RENAME_OBJECT ){
125047        sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
125048      }
125049      memcpy(z, pToCol->a[i].zEName, n);
125050      z[n] = 0;
125051      z += n+1;
125052    }
125053  }
125054  pFKey->isDeferred = 0;
125055  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
125056  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
125057
125058  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
125059  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
125060      pFKey->zTo, (void *)pFKey
125061  );
125062  if( pNextTo==pFKey ){
125063    sqlite3OomFault(db);
125064    goto fk_end;
125065  }
125066  if( pNextTo ){
125067    assert( pNextTo->pPrevTo==0 );
125068    pFKey->pNextTo = pNextTo;
125069    pNextTo->pPrevTo = pFKey;
125070  }
125071
125072  /* Link the foreign key to the table as the last step.
125073  */
125074  assert( IsOrdinaryTable(p) );
125075  p->u.tab.pFKey = pFKey;
125076  pFKey = 0;
125077
125078fk_end:
125079  sqlite3DbFree(db, pFKey);
125080#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
125081  sqlite3ExprListDelete(db, pFromCol);
125082  sqlite3ExprListDelete(db, pToCol);
125083}
125084
125085/*
125086** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
125087** clause is seen as part of a foreign key definition.  The isDeferred
125088** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
125089** The behavior of the most recently created foreign key is adjusted
125090** accordingly.
125091*/
125092SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
125093#ifndef SQLITE_OMIT_FOREIGN_KEY
125094  Table *pTab;
125095  FKey *pFKey;
125096  if( (pTab = pParse->pNewTable)==0 ) return;
125097  if( NEVER(!IsOrdinaryTable(pTab)) ) return;
125098  if( (pFKey = pTab->u.tab.pFKey)==0 ) return;
125099  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
125100  pFKey->isDeferred = (u8)isDeferred;
125101#endif
125102}
125103
125104/*
125105** Generate code that will erase and refill index *pIdx.  This is
125106** used to initialize a newly created index or to recompute the
125107** content of an index in response to a REINDEX command.
125108**
125109** if memRootPage is not negative, it means that the index is newly
125110** created.  The register specified by memRootPage contains the
125111** root page number of the index.  If memRootPage is negative, then
125112** the index already exists and must be cleared before being refilled and
125113** the root page number of the index is taken from pIndex->tnum.
125114*/
125115static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
125116  Table *pTab = pIndex->pTable;  /* The table that is indexed */
125117  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
125118  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
125119  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
125120  int addr1;                     /* Address of top of loop */
125121  int addr2;                     /* Address to jump to for next iteration */
125122  Pgno tnum;                     /* Root page of index */
125123  int iPartIdxLabel;             /* Jump to this label to skip a row */
125124  Vdbe *v;                       /* Generate code into this virtual machine */
125125  KeyInfo *pKey;                 /* KeyInfo for index */
125126  int regRecord;                 /* Register holding assembled index record */
125127  sqlite3 *db = pParse->db;      /* The database connection */
125128  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
125129
125130#ifndef SQLITE_OMIT_AUTHORIZATION
125131  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
125132      db->aDb[iDb].zDbSName ) ){
125133    return;
125134  }
125135#endif
125136
125137  /* Require a write-lock on the table to perform this operation */
125138  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
125139
125140  v = sqlite3GetVdbe(pParse);
125141  if( v==0 ) return;
125142  if( memRootPage>=0 ){
125143    tnum = (Pgno)memRootPage;
125144  }else{
125145    tnum = pIndex->tnum;
125146  }
125147  pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
125148  assert( pKey!=0 || pParse->nErr );
125149
125150  /* Open the sorter cursor if we are to use one. */
125151  iSorter = pParse->nTab++;
125152  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
125153                    sqlite3KeyInfoRef(pKey), P4_KEYINFO);
125154
125155  /* Open the table. Loop through all rows of the table, inserting index
125156  ** records into the sorter. */
125157  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
125158  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
125159  regRecord = sqlite3GetTempReg(pParse);
125160  sqlite3MultiWrite(pParse);
125161
125162  sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
125163  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
125164  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
125165  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
125166  sqlite3VdbeJumpHere(v, addr1);
125167  if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
125168  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb,
125169                    (char *)pKey, P4_KEYINFO);
125170  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
125171
125172  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
125173  if( IsUniqueIndex(pIndex) ){
125174    int j2 = sqlite3VdbeGoto(v, 1);
125175    addr2 = sqlite3VdbeCurrentAddr(v);
125176    sqlite3VdbeVerifyAbortable(v, OE_Abort);
125177    sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
125178                         pIndex->nKeyCol); VdbeCoverage(v);
125179    sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
125180    sqlite3VdbeJumpHere(v, j2);
125181  }else{
125182    /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
125183    ** abort. The exception is if one of the indexed expressions contains a
125184    ** user function that throws an exception when it is evaluated. But the
125185    ** overhead of adding a statement journal to a CREATE INDEX statement is
125186    ** very small (since most of the pages written do not contain content that
125187    ** needs to be restored if the statement aborts), so we call
125188    ** sqlite3MayAbort() for all CREATE INDEX statements.  */
125189    sqlite3MayAbort(pParse);
125190    addr2 = sqlite3VdbeCurrentAddr(v);
125191  }
125192  sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
125193  if( !pIndex->bAscKeyBug ){
125194    /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
125195    ** faster by avoiding unnecessary seeks.  But the optimization does
125196    ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
125197    ** with DESC primary keys, since those indexes have there keys in
125198    ** a different order from the main table.
125199    ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
125200    */
125201    sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
125202  }
125203  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
125204  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
125205  sqlite3ReleaseTempReg(pParse, regRecord);
125206  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
125207  sqlite3VdbeJumpHere(v, addr1);
125208
125209  sqlite3VdbeAddOp1(v, OP_Close, iTab);
125210  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
125211  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
125212}
125213
125214/*
125215** Allocate heap space to hold an Index object with nCol columns.
125216**
125217** Increase the allocation size to provide an extra nExtra bytes
125218** of 8-byte aligned space after the Index object and return a
125219** pointer to this extra space in *ppExtra.
125220*/
125221SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
125222  sqlite3 *db,         /* Database connection */
125223  i16 nCol,            /* Total number of columns in the index */
125224  int nExtra,          /* Number of bytes of extra space to alloc */
125225  char **ppExtra       /* Pointer to the "extra" space */
125226){
125227  Index *p;            /* Allocated index object */
125228  int nByte;           /* Bytes of space for Index object + arrays */
125229
125230  nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
125231          ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
125232          ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
125233                 sizeof(i16)*nCol +            /* Index.aiColumn   */
125234                 sizeof(u8)*nCol);             /* Index.aSortOrder */
125235  p = sqlite3DbMallocZero(db, nByte + nExtra);
125236  if( p ){
125237    char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
125238    p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
125239    p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
125240    p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
125241    p->aSortOrder = (u8*)pExtra;
125242    p->nColumn = nCol;
125243    p->nKeyCol = nCol - 1;
125244    *ppExtra = ((char*)p) + nByte;
125245  }
125246  return p;
125247}
125248
125249/*
125250** If expression list pList contains an expression that was parsed with
125251** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
125252** pParse and return non-zero. Otherwise, return zero.
125253*/
125254SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
125255  if( pList ){
125256    int i;
125257    for(i=0; i<pList->nExpr; i++){
125258      if( pList->a[i].fg.bNulls ){
125259        u8 sf = pList->a[i].fg.sortFlags;
125260        sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
125261            (sf==0 || sf==3) ? "FIRST" : "LAST"
125262        );
125263        return 1;
125264      }
125265    }
125266  }
125267  return 0;
125268}
125269
125270/*
125271** Create a new index for an SQL table.  pName1.pName2 is the name of the index
125272** and pTblList is the name of the table that is to be indexed.  Both will
125273** be NULL for a primary key or an index that is created to satisfy a
125274** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
125275** as the table to be indexed.  pParse->pNewTable is a table that is
125276** currently being constructed by a CREATE TABLE statement.
125277**
125278** pList is a list of columns to be indexed.  pList will be NULL if this
125279** is a primary key or unique-constraint on the most recent column added
125280** to the table currently under construction.
125281*/
125282SQLITE_PRIVATE void sqlite3CreateIndex(
125283  Parse *pParse,     /* All information about this parse */
125284  Token *pName1,     /* First part of index name. May be NULL */
125285  Token *pName2,     /* Second part of index name. May be NULL */
125286  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
125287  ExprList *pList,   /* A list of columns to be indexed */
125288  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
125289  Token *pStart,     /* The CREATE token that begins this statement */
125290  Expr *pPIWhere,    /* WHERE clause for partial indices */
125291  int sortOrder,     /* Sort order of primary key when pList==NULL */
125292  int ifNotExist,    /* Omit error if index already exists */
125293  u8 idxType         /* The index type */
125294){
125295  Table *pTab = 0;     /* Table to be indexed */
125296  Index *pIndex = 0;   /* The index to be created */
125297  char *zName = 0;     /* Name of the index */
125298  int nName;           /* Number of characters in zName */
125299  int i, j;
125300  DbFixer sFix;        /* For assigning database names to pTable */
125301  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
125302  sqlite3 *db = pParse->db;
125303  Db *pDb;             /* The specific table containing the indexed database */
125304  int iDb;             /* Index of the database that is being written */
125305  Token *pName = 0;    /* Unqualified name of the index to create */
125306  struct ExprList_item *pListItem; /* For looping over pList */
125307  int nExtra = 0;                  /* Space allocated for zExtra[] */
125308  int nExtraCol;                   /* Number of extra columns needed */
125309  char *zExtra = 0;                /* Extra space after the Index object */
125310  Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
125311
125312  assert( db->pParse==pParse );
125313  if( pParse->nErr ){
125314    goto exit_create_index;
125315  }
125316  assert( db->mallocFailed==0 );
125317  if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
125318    goto exit_create_index;
125319  }
125320  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
125321    goto exit_create_index;
125322  }
125323  if( sqlite3HasExplicitNulls(pParse, pList) ){
125324    goto exit_create_index;
125325  }
125326
125327  /*
125328  ** Find the table that is to be indexed.  Return early if not found.
125329  */
125330  if( pTblName!=0 ){
125331
125332    /* Use the two-part index name to determine the database
125333    ** to search for the table. 'Fix' the table name to this db
125334    ** before looking up the table.
125335    */
125336    assert( pName1 && pName2 );
125337    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
125338    if( iDb<0 ) goto exit_create_index;
125339    assert( pName && pName->z );
125340
125341#ifndef SQLITE_OMIT_TEMPDB
125342    /* If the index name was unqualified, check if the table
125343    ** is a temp table. If so, set the database to 1. Do not do this
125344    ** if initializing a database schema.
125345    */
125346    if( !db->init.busy ){
125347      pTab = sqlite3SrcListLookup(pParse, pTblName);
125348      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
125349        iDb = 1;
125350      }
125351    }
125352#endif
125353
125354    sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
125355    if( sqlite3FixSrcList(&sFix, pTblName) ){
125356      /* Because the parser constructs pTblName from a single identifier,
125357      ** sqlite3FixSrcList can never fail. */
125358      assert(0);
125359    }
125360    pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
125361    assert( db->mallocFailed==0 || pTab==0 );
125362    if( pTab==0 ) goto exit_create_index;
125363    if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
125364      sqlite3ErrorMsg(pParse,
125365           "cannot create a TEMP index on non-TEMP table \"%s\"",
125366           pTab->zName);
125367      goto exit_create_index;
125368    }
125369    if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
125370  }else{
125371    assert( pName==0 );
125372    assert( pStart==0 );
125373    pTab = pParse->pNewTable;
125374    if( !pTab ) goto exit_create_index;
125375    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
125376  }
125377  pDb = &db->aDb[iDb];
125378
125379  assert( pTab!=0 );
125380  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
125381       && db->init.busy==0
125382       && pTblName!=0
125383#if SQLITE_USER_AUTHENTICATION
125384       && sqlite3UserAuthTable(pTab->zName)==0
125385#endif
125386  ){
125387    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
125388    goto exit_create_index;
125389  }
125390#ifndef SQLITE_OMIT_VIEW
125391  if( IsView(pTab) ){
125392    sqlite3ErrorMsg(pParse, "views may not be indexed");
125393    goto exit_create_index;
125394  }
125395#endif
125396#ifndef SQLITE_OMIT_VIRTUALTABLE
125397  if( IsVirtual(pTab) ){
125398    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
125399    goto exit_create_index;
125400  }
125401#endif
125402
125403  /*
125404  ** Find the name of the index.  Make sure there is not already another
125405  ** index or table with the same name.
125406  **
125407  ** Exception:  If we are reading the names of permanent indices from the
125408  ** sqlite_schema table (because some other process changed the schema) and
125409  ** one of the index names collides with the name of a temporary table or
125410  ** index, then we will continue to process this index.
125411  **
125412  ** If pName==0 it means that we are
125413  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
125414  ** own name.
125415  */
125416  if( pName ){
125417    zName = sqlite3NameFromToken(db, pName);
125418    if( zName==0 ) goto exit_create_index;
125419    assert( pName->z!=0 );
125420    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
125421      goto exit_create_index;
125422    }
125423    if( !IN_RENAME_OBJECT ){
125424      if( !db->init.busy ){
125425        if( sqlite3FindTable(db, zName, pDb->zDbSName)!=0 ){
125426          sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
125427          goto exit_create_index;
125428        }
125429      }
125430      if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
125431        if( !ifNotExist ){
125432          sqlite3ErrorMsg(pParse, "index %s already exists", zName);
125433        }else{
125434          assert( !db->init.busy );
125435          sqlite3CodeVerifySchema(pParse, iDb);
125436          sqlite3ForceNotReadOnly(pParse);
125437        }
125438        goto exit_create_index;
125439      }
125440    }
125441  }else{
125442    int n;
125443    Index *pLoop;
125444    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
125445    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
125446    if( zName==0 ){
125447      goto exit_create_index;
125448    }
125449
125450    /* Automatic index names generated from within sqlite3_declare_vtab()
125451    ** must have names that are distinct from normal automatic index names.
125452    ** The following statement converts "sqlite3_autoindex..." into
125453    ** "sqlite3_butoindex..." in order to make the names distinct.
125454    ** The "vtab_err.test" test demonstrates the need of this statement. */
125455    if( IN_SPECIAL_PARSE ) zName[7]++;
125456  }
125457
125458  /* Check for authorization to create an index.
125459  */
125460#ifndef SQLITE_OMIT_AUTHORIZATION
125461  if( !IN_RENAME_OBJECT ){
125462    const char *zDb = pDb->zDbSName;
125463    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
125464      goto exit_create_index;
125465    }
125466    i = SQLITE_CREATE_INDEX;
125467    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
125468    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
125469      goto exit_create_index;
125470    }
125471  }
125472#endif
125473
125474  /* If pList==0, it means this routine was called to make a primary
125475  ** key out of the last column added to the table under construction.
125476  ** So create a fake list to simulate this.
125477  */
125478  if( pList==0 ){
125479    Token prevCol;
125480    Column *pCol = &pTab->aCol[pTab->nCol-1];
125481    pCol->colFlags |= COLFLAG_UNIQUE;
125482    sqlite3TokenInit(&prevCol, pCol->zCnName);
125483    pList = sqlite3ExprListAppend(pParse, 0,
125484              sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
125485    if( pList==0 ) goto exit_create_index;
125486    assert( pList->nExpr==1 );
125487    sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
125488  }else{
125489    sqlite3ExprListCheckLength(pParse, pList, "index");
125490    if( pParse->nErr ) goto exit_create_index;
125491  }
125492
125493  /* Figure out how many bytes of space are required to store explicitly
125494  ** specified collation sequence names.
125495  */
125496  for(i=0; i<pList->nExpr; i++){
125497    Expr *pExpr = pList->a[i].pExpr;
125498    assert( pExpr!=0 );
125499    if( pExpr->op==TK_COLLATE ){
125500      assert( !ExprHasProperty(pExpr, EP_IntValue) );
125501      nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
125502    }
125503  }
125504
125505  /*
125506  ** Allocate the index structure.
125507  */
125508  nName = sqlite3Strlen30(zName);
125509  nExtraCol = pPk ? pPk->nKeyCol : 1;
125510  assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
125511  pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
125512                                      nName + nExtra + 1, &zExtra);
125513  if( db->mallocFailed ){
125514    goto exit_create_index;
125515  }
125516  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
125517  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
125518  pIndex->zName = zExtra;
125519  zExtra += nName + 1;
125520  memcpy(pIndex->zName, zName, nName+1);
125521  pIndex->pTable = pTab;
125522  pIndex->onError = (u8)onError;
125523  pIndex->uniqNotNull = onError!=OE_None;
125524  pIndex->idxType = idxType;
125525  pIndex->pSchema = db->aDb[iDb].pSchema;
125526  pIndex->nKeyCol = pList->nExpr;
125527  if( pPIWhere ){
125528    sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
125529    pIndex->pPartIdxWhere = pPIWhere;
125530    pPIWhere = 0;
125531  }
125532  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
125533
125534  /* Check to see if we should honor DESC requests on index columns
125535  */
125536  if( pDb->pSchema->file_format>=4 ){
125537    sortOrderMask = -1;   /* Honor DESC */
125538  }else{
125539    sortOrderMask = 0;    /* Ignore DESC */
125540  }
125541
125542  /* Analyze the list of expressions that form the terms of the index and
125543  ** report any errors.  In the common case where the expression is exactly
125544  ** a table column, store that column in aiColumn[].  For general expressions,
125545  ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
125546  **
125547  ** TODO: Issue a warning if two or more columns of the index are identical.
125548  ** TODO: Issue a warning if the table primary key is used as part of the
125549  ** index key.
125550  */
125551  pListItem = pList->a;
125552  if( IN_RENAME_OBJECT ){
125553    pIndex->aColExpr = pList;
125554    pList = 0;
125555  }
125556  for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
125557    Expr *pCExpr;                  /* The i-th index expression */
125558    int requestedSortOrder;        /* ASC or DESC on the i-th expression */
125559    const char *zColl;             /* Collation sequence name */
125560
125561    sqlite3StringToId(pListItem->pExpr);
125562    sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
125563    if( pParse->nErr ) goto exit_create_index;
125564    pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
125565    if( pCExpr->op!=TK_COLUMN ){
125566      if( pTab==pParse->pNewTable ){
125567        sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
125568                                "UNIQUE constraints");
125569        goto exit_create_index;
125570      }
125571      if( pIndex->aColExpr==0 ){
125572        pIndex->aColExpr = pList;
125573        pList = 0;
125574      }
125575      j = XN_EXPR;
125576      pIndex->aiColumn[i] = XN_EXPR;
125577      pIndex->uniqNotNull = 0;
125578      pIndex->bHasExpr = 1;
125579    }else{
125580      j = pCExpr->iColumn;
125581      assert( j<=0x7fff );
125582      if( j<0 ){
125583        j = pTab->iPKey;
125584      }else{
125585        if( pTab->aCol[j].notNull==0 ){
125586          pIndex->uniqNotNull = 0;
125587        }
125588        if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
125589          pIndex->bHasVCol = 1;
125590          pIndex->bHasExpr = 1;
125591        }
125592      }
125593      pIndex->aiColumn[i] = (i16)j;
125594    }
125595    zColl = 0;
125596    if( pListItem->pExpr->op==TK_COLLATE ){
125597      int nColl;
125598      assert( !ExprHasProperty(pListItem->pExpr, EP_IntValue) );
125599      zColl = pListItem->pExpr->u.zToken;
125600      nColl = sqlite3Strlen30(zColl) + 1;
125601      assert( nExtra>=nColl );
125602      memcpy(zExtra, zColl, nColl);
125603      zColl = zExtra;
125604      zExtra += nColl;
125605      nExtra -= nColl;
125606    }else if( j>=0 ){
125607      zColl = sqlite3ColumnColl(&pTab->aCol[j]);
125608    }
125609    if( !zColl ) zColl = sqlite3StrBINARY;
125610    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
125611      goto exit_create_index;
125612    }
125613    pIndex->azColl[i] = zColl;
125614    requestedSortOrder = pListItem->fg.sortFlags & sortOrderMask;
125615    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
125616  }
125617
125618  /* Append the table key to the end of the index.  For WITHOUT ROWID
125619  ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
125620  ** normal tables (when pPk==0) this will be the rowid.
125621  */
125622  if( pPk ){
125623    for(j=0; j<pPk->nKeyCol; j++){
125624      int x = pPk->aiColumn[j];
125625      assert( x>=0 );
125626      if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
125627        pIndex->nColumn--;
125628      }else{
125629        testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
125630        pIndex->aiColumn[i] = x;
125631        pIndex->azColl[i] = pPk->azColl[j];
125632        pIndex->aSortOrder[i] = pPk->aSortOrder[j];
125633        i++;
125634      }
125635    }
125636    assert( i==pIndex->nColumn );
125637  }else{
125638    pIndex->aiColumn[i] = XN_ROWID;
125639    pIndex->azColl[i] = sqlite3StrBINARY;
125640  }
125641  sqlite3DefaultRowEst(pIndex);
125642  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
125643
125644  /* If this index contains every column of its table, then mark
125645  ** it as a covering index */
125646  assert( HasRowid(pTab)
125647      || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
125648  recomputeColumnsNotIndexed(pIndex);
125649  if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
125650    pIndex->isCovering = 1;
125651    for(j=0; j<pTab->nCol; j++){
125652      if( j==pTab->iPKey ) continue;
125653      if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
125654      pIndex->isCovering = 0;
125655      break;
125656    }
125657  }
125658
125659  if( pTab==pParse->pNewTable ){
125660    /* This routine has been called to create an automatic index as a
125661    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
125662    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
125663    ** i.e. one of:
125664    **
125665    ** CREATE TABLE t(x PRIMARY KEY, y);
125666    ** CREATE TABLE t(x, y, UNIQUE(x, y));
125667    **
125668    ** Either way, check to see if the table already has such an index. If
125669    ** so, don't bother creating this one. This only applies to
125670    ** automatically created indices. Users can do as they wish with
125671    ** explicit indices.
125672    **
125673    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
125674    ** (and thus suppressing the second one) even if they have different
125675    ** sort orders.
125676    **
125677    ** If there are different collating sequences or if the columns of
125678    ** the constraint occur in different orders, then the constraints are
125679    ** considered distinct and both result in separate indices.
125680    */
125681    Index *pIdx;
125682    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
125683      int k;
125684      assert( IsUniqueIndex(pIdx) );
125685      assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
125686      assert( IsUniqueIndex(pIndex) );
125687
125688      if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
125689      for(k=0; k<pIdx->nKeyCol; k++){
125690        const char *z1;
125691        const char *z2;
125692        assert( pIdx->aiColumn[k]>=0 );
125693        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
125694        z1 = pIdx->azColl[k];
125695        z2 = pIndex->azColl[k];
125696        if( sqlite3StrICmp(z1, z2) ) break;
125697      }
125698      if( k==pIdx->nKeyCol ){
125699        if( pIdx->onError!=pIndex->onError ){
125700          /* This constraint creates the same index as a previous
125701          ** constraint specified somewhere in the CREATE TABLE statement.
125702          ** However the ON CONFLICT clauses are different. If both this
125703          ** constraint and the previous equivalent constraint have explicit
125704          ** ON CONFLICT clauses this is an error. Otherwise, use the
125705          ** explicitly specified behavior for the index.
125706          */
125707          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
125708            sqlite3ErrorMsg(pParse,
125709                "conflicting ON CONFLICT clauses specified", 0);
125710          }
125711          if( pIdx->onError==OE_Default ){
125712            pIdx->onError = pIndex->onError;
125713          }
125714        }
125715        if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
125716        if( IN_RENAME_OBJECT ){
125717          pIndex->pNext = pParse->pNewIndex;
125718          pParse->pNewIndex = pIndex;
125719          pIndex = 0;
125720        }
125721        goto exit_create_index;
125722      }
125723    }
125724  }
125725
125726  if( !IN_RENAME_OBJECT ){
125727
125728    /* Link the new Index structure to its table and to the other
125729    ** in-memory database structures.
125730    */
125731    assert( pParse->nErr==0 );
125732    if( db->init.busy ){
125733      Index *p;
125734      assert( !IN_SPECIAL_PARSE );
125735      assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
125736      if( pTblName!=0 ){
125737        pIndex->tnum = db->init.newTnum;
125738        if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
125739          sqlite3ErrorMsg(pParse, "invalid rootpage");
125740          pParse->rc = SQLITE_CORRUPT_BKPT;
125741          goto exit_create_index;
125742        }
125743      }
125744      p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
125745          pIndex->zName, pIndex);
125746      if( p ){
125747        assert( p==pIndex );  /* Malloc must have failed */
125748        sqlite3OomFault(db);
125749        goto exit_create_index;
125750      }
125751      db->mDbFlags |= DBFLAG_SchemaChange;
125752    }
125753
125754    /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
125755    ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
125756    ** emit code to allocate the index rootpage on disk and make an entry for
125757    ** the index in the sqlite_schema table and populate the index with
125758    ** content.  But, do not do this if we are simply reading the sqlite_schema
125759    ** table to parse the schema, or if this index is the PRIMARY KEY index
125760    ** of a WITHOUT ROWID table.
125761    **
125762    ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
125763    ** or UNIQUE index in a CREATE TABLE statement.  Since the table
125764    ** has just been created, it contains no data and the index initialization
125765    ** step can be skipped.
125766    */
125767    else if( HasRowid(pTab) || pTblName!=0 ){
125768      Vdbe *v;
125769      char *zStmt;
125770      int iMem = ++pParse->nMem;
125771
125772      v = sqlite3GetVdbe(pParse);
125773      if( v==0 ) goto exit_create_index;
125774
125775      sqlite3BeginWriteOperation(pParse, 1, iDb);
125776
125777      /* Create the rootpage for the index using CreateIndex. But before
125778      ** doing so, code a Noop instruction and store its address in
125779      ** Index.tnum. This is required in case this index is actually a
125780      ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
125781      ** that case the convertToWithoutRowidTable() routine will replace
125782      ** the Noop with a Goto to jump over the VDBE code generated below. */
125783      pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop);
125784      sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
125785
125786      /* Gather the complete text of the CREATE INDEX statement into
125787      ** the zStmt variable
125788      */
125789      assert( pName!=0 || pStart==0 );
125790      if( pStart ){
125791        int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
125792        if( pName->z[n-1]==';' ) n--;
125793        /* A named index with an explicit CREATE INDEX statement */
125794        zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
125795            onError==OE_None ? "" : " UNIQUE", n, pName->z);
125796      }else{
125797        /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
125798        /* zStmt = sqlite3MPrintf(""); */
125799        zStmt = 0;
125800      }
125801
125802      /* Add an entry in sqlite_schema for this index
125803      */
125804      sqlite3NestedParse(pParse,
125805         "INSERT INTO %Q." LEGACY_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);",
125806         db->aDb[iDb].zDbSName,
125807         pIndex->zName,
125808         pTab->zName,
125809         iMem,
125810         zStmt
125811      );
125812      sqlite3DbFree(db, zStmt);
125813
125814      /* Fill the index with data and reparse the schema. Code an OP_Expire
125815      ** to invalidate all pre-compiled statements.
125816      */
125817      if( pTblName ){
125818        sqlite3RefillIndex(pParse, pIndex, iMem);
125819        sqlite3ChangeCookie(pParse, iDb);
125820        sqlite3VdbeAddParseSchemaOp(v, iDb,
125821            sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0);
125822        sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
125823      }
125824
125825      sqlite3VdbeJumpHere(v, (int)pIndex->tnum);
125826    }
125827  }
125828  if( db->init.busy || pTblName==0 ){
125829    pIndex->pNext = pTab->pIndex;
125830    pTab->pIndex = pIndex;
125831    pIndex = 0;
125832  }
125833  else if( IN_RENAME_OBJECT ){
125834    assert( pParse->pNewIndex==0 );
125835    pParse->pNewIndex = pIndex;
125836    pIndex = 0;
125837  }
125838
125839  /* Clean up before exiting */
125840exit_create_index:
125841  if( pIndex ) sqlite3FreeIndex(db, pIndex);
125842  if( pTab ){
125843    /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list.
125844    ** The list was already ordered when this routine was entered, so at this
125845    ** point at most a single index (the newly added index) will be out of
125846    ** order.  So we have to reorder at most one index. */
125847    Index **ppFrom;
125848    Index *pThis;
125849    for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
125850      Index *pNext;
125851      if( pThis->onError!=OE_Replace ) continue;
125852      while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
125853        *ppFrom = pNext;
125854        pThis->pNext = pNext->pNext;
125855        pNext->pNext = pThis;
125856        ppFrom = &pNext->pNext;
125857      }
125858      break;
125859    }
125860#ifdef SQLITE_DEBUG
125861    /* Verify that all REPLACE indexes really are now at the end
125862    ** of the index list.  In other words, no other index type ever
125863    ** comes after a REPLACE index on the list. */
125864    for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){
125865      assert( pThis->onError!=OE_Replace
125866           || pThis->pNext==0
125867           || pThis->pNext->onError==OE_Replace );
125868    }
125869#endif
125870  }
125871  sqlite3ExprDelete(db, pPIWhere);
125872  sqlite3ExprListDelete(db, pList);
125873  sqlite3SrcListDelete(db, pTblName);
125874  sqlite3DbFree(db, zName);
125875}
125876
125877/*
125878** Fill the Index.aiRowEst[] array with default information - information
125879** to be used when we have not run the ANALYZE command.
125880**
125881** aiRowEst[0] is supposed to contain the number of elements in the index.
125882** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
125883** number of rows in the table that match any particular value of the
125884** first column of the index.  aiRowEst[2] is an estimate of the number
125885** of rows that match any particular combination of the first 2 columns
125886** of the index.  And so forth.  It must always be the case that
125887*
125888**           aiRowEst[N]<=aiRowEst[N-1]
125889**           aiRowEst[N]>=1
125890**
125891** Apart from that, we have little to go on besides intuition as to
125892** how aiRowEst[] should be initialized.  The numbers generated here
125893** are based on typical values found in actual indices.
125894*/
125895SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
125896               /*                10,  9,  8,  7,  6 */
125897  static const LogEst aVal[] = { 33, 32, 30, 28, 26 };
125898  LogEst *a = pIdx->aiRowLogEst;
125899  LogEst x;
125900  int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
125901  int i;
125902
125903  /* Indexes with default row estimates should not have stat1 data */
125904  assert( !pIdx->hasStat1 );
125905
125906  /* Set the first entry (number of rows in the index) to the estimated
125907  ** number of rows in the table, or half the number of rows in the table
125908  ** for a partial index.
125909  **
125910  ** 2020-05-27:  If some of the stat data is coming from the sqlite_stat1
125911  ** table but other parts we are having to guess at, then do not let the
125912  ** estimated number of rows in the table be less than 1000 (LogEst 99).
125913  ** Failure to do this can cause the indexes for which we do not have
125914  ** stat1 data to be ignored by the query planner.
125915  */
125916  x = pIdx->pTable->nRowLogEst;
125917  assert( 99==sqlite3LogEst(1000) );
125918  if( x<99 ){
125919    pIdx->pTable->nRowLogEst = x = 99;
125920  }
125921  if( pIdx->pPartIdxWhere!=0 ){ x -= 10;  assert( 10==sqlite3LogEst(2) ); }
125922  a[0] = x;
125923
125924  /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
125925  ** 6 and each subsequent value (if any) is 5.  */
125926  memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
125927  for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
125928    a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
125929  }
125930
125931  assert( 0==sqlite3LogEst(1) );
125932  if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
125933}
125934
125935/*
125936** This routine will drop an existing named index.  This routine
125937** implements the DROP INDEX statement.
125938*/
125939SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
125940  Index *pIndex;
125941  Vdbe *v;
125942  sqlite3 *db = pParse->db;
125943  int iDb;
125944
125945  if( db->mallocFailed ){
125946    goto exit_drop_index;
125947  }
125948  assert( pParse->nErr==0 );   /* Never called with prior non-OOM errors */
125949  assert( pName->nSrc==1 );
125950  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
125951    goto exit_drop_index;
125952  }
125953  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
125954  if( pIndex==0 ){
125955    if( !ifExists ){
125956      sqlite3ErrorMsg(pParse, "no such index: %S", pName->a);
125957    }else{
125958      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
125959      sqlite3ForceNotReadOnly(pParse);
125960    }
125961    pParse->checkSchema = 1;
125962    goto exit_drop_index;
125963  }
125964  if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
125965    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
125966      "or PRIMARY KEY constraint cannot be dropped", 0);
125967    goto exit_drop_index;
125968  }
125969  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
125970#ifndef SQLITE_OMIT_AUTHORIZATION
125971  {
125972    int code = SQLITE_DROP_INDEX;
125973    Table *pTab = pIndex->pTable;
125974    const char *zDb = db->aDb[iDb].zDbSName;
125975    const char *zTab = SCHEMA_TABLE(iDb);
125976    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
125977      goto exit_drop_index;
125978    }
125979    if( !OMIT_TEMPDB && iDb==1 ) code = SQLITE_DROP_TEMP_INDEX;
125980    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
125981      goto exit_drop_index;
125982    }
125983  }
125984#endif
125985
125986  /* Generate code to remove the index and from the schema table */
125987  v = sqlite3GetVdbe(pParse);
125988  if( v ){
125989    sqlite3BeginWriteOperation(pParse, 1, iDb);
125990    sqlite3NestedParse(pParse,
125991       "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
125992       db->aDb[iDb].zDbSName, pIndex->zName
125993    );
125994    sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
125995    sqlite3ChangeCookie(pParse, iDb);
125996    destroyRootPage(pParse, pIndex->tnum, iDb);
125997    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
125998  }
125999
126000exit_drop_index:
126001  sqlite3SrcListDelete(db, pName);
126002}
126003
126004/*
126005** pArray is a pointer to an array of objects. Each object in the
126006** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
126007** to extend the array so that there is space for a new object at the end.
126008**
126009** When this function is called, *pnEntry contains the current size of
126010** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
126011** in total).
126012**
126013** If the realloc() is successful (i.e. if no OOM condition occurs), the
126014** space allocated for the new object is zeroed, *pnEntry updated to
126015** reflect the new size of the array and a pointer to the new allocation
126016** returned. *pIdx is set to the index of the new array entry in this case.
126017**
126018** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
126019** unchanged and a copy of pArray returned.
126020*/
126021SQLITE_PRIVATE void *sqlite3ArrayAllocate(
126022  sqlite3 *db,      /* Connection to notify of malloc failures */
126023  void *pArray,     /* Array of objects.  Might be reallocated */
126024  int szEntry,      /* Size of each object in the array */
126025  int *pnEntry,     /* Number of objects currently in use */
126026  int *pIdx         /* Write the index of a new slot here */
126027){
126028  char *z;
126029  sqlite3_int64 n = *pIdx = *pnEntry;
126030  if( (n & (n-1))==0 ){
126031    sqlite3_int64 sz = (n==0) ? 1 : 2*n;
126032    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
126033    if( pNew==0 ){
126034      *pIdx = -1;
126035      return pArray;
126036    }
126037    pArray = pNew;
126038  }
126039  z = (char*)pArray;
126040  memset(&z[n * szEntry], 0, szEntry);
126041  ++*pnEntry;
126042  return pArray;
126043}
126044
126045/*
126046** Append a new element to the given IdList.  Create a new IdList if
126047** need be.
126048**
126049** A new IdList is returned, or NULL if malloc() fails.
126050*/
126051SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
126052  sqlite3 *db = pParse->db;
126053  int i;
126054  if( pList==0 ){
126055    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
126056    if( pList==0 ) return 0;
126057  }else{
126058    IdList *pNew;
126059    pNew = sqlite3DbRealloc(db, pList,
126060                 sizeof(IdList) + pList->nId*sizeof(pList->a));
126061    if( pNew==0 ){
126062      sqlite3IdListDelete(db, pList);
126063      return 0;
126064    }
126065    pList = pNew;
126066  }
126067  i = pList->nId++;
126068  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
126069  if( IN_RENAME_OBJECT && pList->a[i].zName ){
126070    sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
126071  }
126072  return pList;
126073}
126074
126075/*
126076** Delete an IdList.
126077*/
126078SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
126079  int i;
126080  assert( db!=0 );
126081  if( pList==0 ) return;
126082  assert( pList->eU4!=EU4_EXPR ); /* EU4_EXPR mode is not currently used */
126083  for(i=0; i<pList->nId; i++){
126084    sqlite3DbFree(db, pList->a[i].zName);
126085  }
126086  sqlite3DbNNFreeNN(db, pList);
126087}
126088
126089/*
126090** Return the index in pList of the identifier named zId.  Return -1
126091** if not found.
126092*/
126093SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
126094  int i;
126095  assert( pList!=0 );
126096  for(i=0; i<pList->nId; i++){
126097    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
126098  }
126099  return -1;
126100}
126101
126102/*
126103** Maximum size of a SrcList object.
126104** The SrcList object is used to represent the FROM clause of a
126105** SELECT statement, and the query planner cannot deal with more
126106** than 64 tables in a join.  So any value larger than 64 here
126107** is sufficient for most uses.  Smaller values, like say 10, are
126108** appropriate for small and memory-limited applications.
126109*/
126110#ifndef SQLITE_MAX_SRCLIST
126111# define SQLITE_MAX_SRCLIST 200
126112#endif
126113
126114/*
126115** Expand the space allocated for the given SrcList object by
126116** creating nExtra new slots beginning at iStart.  iStart is zero based.
126117** New slots are zeroed.
126118**
126119** For example, suppose a SrcList initially contains two entries: A,B.
126120** To append 3 new entries onto the end, do this:
126121**
126122**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
126123**
126124** After the call above it would contain:  A, B, nil, nil, nil.
126125** If the iStart argument had been 1 instead of 2, then the result
126126** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
126127** the iStart value would be 0.  The result then would
126128** be: nil, nil, nil, A, B.
126129**
126130** If a memory allocation fails or the SrcList becomes too large, leave
126131** the original SrcList unchanged, return NULL, and leave an error message
126132** in pParse.
126133*/
126134SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
126135  Parse *pParse,     /* Parsing context into which errors are reported */
126136  SrcList *pSrc,     /* The SrcList to be enlarged */
126137  int nExtra,        /* Number of new slots to add to pSrc->a[] */
126138  int iStart         /* Index in pSrc->a[] of first new slot */
126139){
126140  int i;
126141
126142  /* Sanity checking on calling parameters */
126143  assert( iStart>=0 );
126144  assert( nExtra>=1 );
126145  assert( pSrc!=0 );
126146  assert( iStart<=pSrc->nSrc );
126147
126148  /* Allocate additional space if needed */
126149  if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
126150    SrcList *pNew;
126151    sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
126152    sqlite3 *db = pParse->db;
126153
126154    if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
126155      sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
126156                      SQLITE_MAX_SRCLIST);
126157      return 0;
126158    }
126159    if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
126160    pNew = sqlite3DbRealloc(db, pSrc,
126161               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
126162    if( pNew==0 ){
126163      assert( db->mallocFailed );
126164      return 0;
126165    }
126166    pSrc = pNew;
126167    pSrc->nAlloc = nAlloc;
126168  }
126169
126170  /* Move existing slots that come after the newly inserted slots
126171  ** out of the way */
126172  for(i=pSrc->nSrc-1; i>=iStart; i--){
126173    pSrc->a[i+nExtra] = pSrc->a[i];
126174  }
126175  pSrc->nSrc += nExtra;
126176
126177  /* Zero the newly allocated slots */
126178  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
126179  for(i=iStart; i<iStart+nExtra; i++){
126180    pSrc->a[i].iCursor = -1;
126181  }
126182
126183  /* Return a pointer to the enlarged SrcList */
126184  return pSrc;
126185}
126186
126187
126188/*
126189** Append a new table name to the given SrcList.  Create a new SrcList if
126190** need be.  A new entry is created in the SrcList even if pTable is NULL.
126191**
126192** A SrcList is returned, or NULL if there is an OOM error or if the
126193** SrcList grows to large.  The returned
126194** SrcList might be the same as the SrcList that was input or it might be
126195** a new one.  If an OOM error does occurs, then the prior value of pList
126196** that is input to this routine is automatically freed.
126197**
126198** If pDatabase is not null, it means that the table has an optional
126199** database name prefix.  Like this:  "database.table".  The pDatabase
126200** points to the table name and the pTable points to the database name.
126201** The SrcList.a[].zName field is filled with the table name which might
126202** come from pTable (if pDatabase is NULL) or from pDatabase.
126203** SrcList.a[].zDatabase is filled with the database name from pTable,
126204** or with NULL if no database is specified.
126205**
126206** In other words, if call like this:
126207**
126208**         sqlite3SrcListAppend(D,A,B,0);
126209**
126210** Then B is a table name and the database name is unspecified.  If called
126211** like this:
126212**
126213**         sqlite3SrcListAppend(D,A,B,C);
126214**
126215** Then C is the table name and B is the database name.  If C is defined
126216** then so is B.  In other words, we never have a case where:
126217**
126218**         sqlite3SrcListAppend(D,A,0,C);
126219**
126220** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
126221** before being added to the SrcList.
126222*/
126223SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
126224  Parse *pParse,      /* Parsing context, in which errors are reported */
126225  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
126226  Token *pTable,      /* Table to append */
126227  Token *pDatabase    /* Database of the table */
126228){
126229  SrcItem *pItem;
126230  sqlite3 *db;
126231  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
126232  assert( pParse!=0 );
126233  assert( pParse->db!=0 );
126234  db = pParse->db;
126235  if( pList==0 ){
126236    pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
126237    if( pList==0 ) return 0;
126238    pList->nAlloc = 1;
126239    pList->nSrc = 1;
126240    memset(&pList->a[0], 0, sizeof(pList->a[0]));
126241    pList->a[0].iCursor = -1;
126242  }else{
126243    SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
126244    if( pNew==0 ){
126245      sqlite3SrcListDelete(db, pList);
126246      return 0;
126247    }else{
126248      pList = pNew;
126249    }
126250  }
126251  pItem = &pList->a[pList->nSrc-1];
126252  if( pDatabase && pDatabase->z==0 ){
126253    pDatabase = 0;
126254  }
126255  if( pDatabase ){
126256    pItem->zName = sqlite3NameFromToken(db, pDatabase);
126257    pItem->zDatabase = sqlite3NameFromToken(db, pTable);
126258  }else{
126259    pItem->zName = sqlite3NameFromToken(db, pTable);
126260    pItem->zDatabase = 0;
126261  }
126262  return pList;
126263}
126264
126265/*
126266** Assign VdbeCursor index numbers to all tables in a SrcList
126267*/
126268SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
126269  int i;
126270  SrcItem *pItem;
126271  assert( pList || pParse->db->mallocFailed );
126272  if( ALWAYS(pList) ){
126273    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
126274      if( pItem->iCursor>=0 ) continue;
126275      pItem->iCursor = pParse->nTab++;
126276      if( pItem->pSelect ){
126277        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
126278      }
126279    }
126280  }
126281}
126282
126283/*
126284** Delete an entire SrcList including all its substructure.
126285*/
126286SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
126287  int i;
126288  SrcItem *pItem;
126289  assert( db!=0 );
126290  if( pList==0 ) return;
126291  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
126292    if( pItem->zDatabase ) sqlite3DbNNFreeNN(db, pItem->zDatabase);
126293    if( pItem->zName ) sqlite3DbNNFreeNN(db, pItem->zName);
126294    if( pItem->zAlias ) sqlite3DbNNFreeNN(db, pItem->zAlias);
126295    if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
126296    if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
126297    sqlite3DeleteTable(db, pItem->pTab);
126298    if( pItem->pSelect ) sqlite3SelectDelete(db, pItem->pSelect);
126299    if( pItem->fg.isUsing ){
126300      sqlite3IdListDelete(db, pItem->u3.pUsing);
126301    }else if( pItem->u3.pOn ){
126302      sqlite3ExprDelete(db, pItem->u3.pOn);
126303    }
126304  }
126305  sqlite3DbNNFreeNN(db, pList);
126306}
126307
126308/*
126309** This routine is called by the parser to add a new term to the
126310** end of a growing FROM clause.  The "p" parameter is the part of
126311** the FROM clause that has already been constructed.  "p" is NULL
126312** if this is the first term of the FROM clause.  pTable and pDatabase
126313** are the name of the table and database named in the FROM clause term.
126314** pDatabase is NULL if the database name qualifier is missing - the
126315** usual case.  If the term has an alias, then pAlias points to the
126316** alias token.  If the term is a subquery, then pSubquery is the
126317** SELECT statement that the subquery encodes.  The pTable and
126318** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
126319** parameters are the content of the ON and USING clauses.
126320**
126321** Return a new SrcList which encodes is the FROM with the new
126322** term added.
126323*/
126324SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
126325  Parse *pParse,          /* Parsing context */
126326  SrcList *p,             /* The left part of the FROM clause already seen */
126327  Token *pTable,          /* Name of the table to add to the FROM clause */
126328  Token *pDatabase,       /* Name of the database containing pTable */
126329  Token *pAlias,          /* The right-hand side of the AS subexpression */
126330  Select *pSubquery,      /* A subquery used in place of a table name */
126331  OnOrUsing *pOnUsing     /* Either the ON clause or the USING clause */
126332){
126333  SrcItem *pItem;
126334  sqlite3 *db = pParse->db;
126335  if( !p && pOnUsing!=0 && (pOnUsing->pOn || pOnUsing->pUsing) ){
126336    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
126337      (pOnUsing->pOn ? "ON" : "USING")
126338    );
126339    goto append_from_error;
126340  }
126341  p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
126342  if( p==0 ){
126343    goto append_from_error;
126344  }
126345  assert( p->nSrc>0 );
126346  pItem = &p->a[p->nSrc-1];
126347  assert( (pTable==0)==(pDatabase==0) );
126348  assert( pItem->zName==0 || pDatabase!=0 );
126349  if( IN_RENAME_OBJECT && pItem->zName ){
126350    Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
126351    sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
126352  }
126353  assert( pAlias!=0 );
126354  if( pAlias->n ){
126355    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
126356  }
126357  if( pSubquery ){
126358    pItem->pSelect = pSubquery;
126359    if( pSubquery->selFlags & SF_NestedFrom ){
126360      pItem->fg.isNestedFrom = 1;
126361    }
126362  }
126363  assert( pOnUsing==0 || pOnUsing->pOn==0 || pOnUsing->pUsing==0 );
126364  assert( pItem->fg.isUsing==0 );
126365  if( pOnUsing==0 ){
126366    pItem->u3.pOn = 0;
126367  }else if( pOnUsing->pUsing ){
126368    pItem->fg.isUsing = 1;
126369    pItem->u3.pUsing = pOnUsing->pUsing;
126370  }else{
126371    pItem->u3.pOn = pOnUsing->pOn;
126372  }
126373  return p;
126374
126375append_from_error:
126376  assert( p==0 );
126377  sqlite3ClearOnOrUsing(db, pOnUsing);
126378  sqlite3SelectDelete(db, pSubquery);
126379  return 0;
126380}
126381
126382/*
126383** Add an INDEXED BY or NOT INDEXED clause to the most recently added
126384** element of the source-list passed as the second argument.
126385*/
126386SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
126387  assert( pIndexedBy!=0 );
126388  if( p && pIndexedBy->n>0 ){
126389    SrcItem *pItem;
126390    assert( p->nSrc>0 );
126391    pItem = &p->a[p->nSrc-1];
126392    assert( pItem->fg.notIndexed==0 );
126393    assert( pItem->fg.isIndexedBy==0 );
126394    assert( pItem->fg.isTabFunc==0 );
126395    if( pIndexedBy->n==1 && !pIndexedBy->z ){
126396      /* A "NOT INDEXED" clause was supplied. See parse.y
126397      ** construct "indexed_opt" for details. */
126398      pItem->fg.notIndexed = 1;
126399    }else{
126400      pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
126401      pItem->fg.isIndexedBy = 1;
126402      assert( pItem->fg.isCte==0 );  /* No collision on union u2 */
126403    }
126404  }
126405}
126406
126407/*
126408** Append the contents of SrcList p2 to SrcList p1 and return the resulting
126409** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
126410** are deleted by this function.
126411*/
126412SQLITE_PRIVATE SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){
126413  assert( p1 && p1->nSrc==1 );
126414  if( p2 ){
126415    SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1);
126416    if( pNew==0 ){
126417      sqlite3SrcListDelete(pParse->db, p2);
126418    }else{
126419      p1 = pNew;
126420      memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem));
126421      sqlite3DbFree(pParse->db, p2);
126422      p1->a[0].fg.jointype |= (JT_LTORJ & p1->a[1].fg.jointype);
126423    }
126424  }
126425  return p1;
126426}
126427
126428/*
126429** Add the list of function arguments to the SrcList entry for a
126430** table-valued-function.
126431*/
126432SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
126433  if( p ){
126434    SrcItem *pItem = &p->a[p->nSrc-1];
126435    assert( pItem->fg.notIndexed==0 );
126436    assert( pItem->fg.isIndexedBy==0 );
126437    assert( pItem->fg.isTabFunc==0 );
126438    pItem->u1.pFuncArg = pList;
126439    pItem->fg.isTabFunc = 1;
126440  }else{
126441    sqlite3ExprListDelete(pParse->db, pList);
126442  }
126443}
126444
126445/*
126446** When building up a FROM clause in the parser, the join operator
126447** is initially attached to the left operand.  But the code generator
126448** expects the join operator to be on the right operand.  This routine
126449** Shifts all join operators from left to right for an entire FROM
126450** clause.
126451**
126452** Example: Suppose the join is like this:
126453**
126454**           A natural cross join B
126455**
126456** The operator is "natural cross join".  The A and B operands are stored
126457** in p->a[0] and p->a[1], respectively.  The parser initially stores the
126458** operator with A.  This routine shifts that operator over to B.
126459**
126460** Additional changes:
126461**
126462**   *   All tables to the left of the right-most RIGHT JOIN are tagged with
126463**       JT_LTORJ (mnemonic: Left Table Of Right Join) so that the
126464**       code generator can easily tell that the table is part of
126465**       the left operand of at least one RIGHT JOIN.
126466*/
126467SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(Parse *pParse, SrcList *p){
126468  (void)pParse;
126469  if( p && p->nSrc>1 ){
126470    int i = p->nSrc-1;
126471    u8 allFlags = 0;
126472    do{
126473      allFlags |= p->a[i].fg.jointype = p->a[i-1].fg.jointype;
126474    }while( (--i)>0 );
126475    p->a[0].fg.jointype = 0;
126476
126477    /* All terms to the left of a RIGHT JOIN should be tagged with the
126478    ** JT_LTORJ flags */
126479    if( allFlags & JT_RIGHT ){
126480      for(i=p->nSrc-1; ALWAYS(i>0) && (p->a[i].fg.jointype&JT_RIGHT)==0; i--){}
126481      i--;
126482      assert( i>=0 );
126483      do{
126484        p->a[i].fg.jointype |= JT_LTORJ;
126485      }while( (--i)>=0 );
126486    }
126487  }
126488}
126489
126490/*
126491** Generate VDBE code for a BEGIN statement.
126492*/
126493SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
126494  sqlite3 *db;
126495  Vdbe *v;
126496  int i;
126497
126498  assert( pParse!=0 );
126499  db = pParse->db;
126500  assert( db!=0 );
126501  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
126502    return;
126503  }
126504  v = sqlite3GetVdbe(pParse);
126505  if( !v ) return;
126506  if( type!=TK_DEFERRED ){
126507    for(i=0; i<db->nDb; i++){
126508      int eTxnType;
126509      Btree *pBt = db->aDb[i].pBt;
126510      if( pBt && sqlite3BtreeIsReadonly(pBt) ){
126511        eTxnType = 0;  /* Read txn */
126512      }else if( type==TK_EXCLUSIVE ){
126513        eTxnType = 2;  /* Exclusive txn */
126514      }else{
126515        eTxnType = 1;  /* Write txn */
126516      }
126517      sqlite3VdbeAddOp2(v, OP_Transaction, i, eTxnType);
126518      sqlite3VdbeUsesBtree(v, i);
126519    }
126520  }
126521  sqlite3VdbeAddOp0(v, OP_AutoCommit);
126522}
126523
126524/*
126525** Generate VDBE code for a COMMIT or ROLLBACK statement.
126526** Code for ROLLBACK is generated if eType==TK_ROLLBACK.  Otherwise
126527** code is generated for a COMMIT.
126528*/
126529SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
126530  Vdbe *v;
126531  int isRollback;
126532
126533  assert( pParse!=0 );
126534  assert( pParse->db!=0 );
126535  assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
126536  isRollback = eType==TK_ROLLBACK;
126537  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
126538       isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
126539    return;
126540  }
126541  v = sqlite3GetVdbe(pParse);
126542  if( v ){
126543    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
126544  }
126545}
126546
126547/*
126548** This function is called by the parser when it parses a command to create,
126549** release or rollback an SQL savepoint.
126550*/
126551SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
126552  char *zName = sqlite3NameFromToken(pParse->db, pName);
126553  if( zName ){
126554    Vdbe *v = sqlite3GetVdbe(pParse);
126555#ifndef SQLITE_OMIT_AUTHORIZATION
126556    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
126557    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
126558#endif
126559    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
126560      sqlite3DbFree(pParse->db, zName);
126561      return;
126562    }
126563    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
126564  }
126565}
126566
126567/*
126568** Make sure the TEMP database is open and available for use.  Return
126569** the number of errors.  Leave any error messages in the pParse structure.
126570*/
126571SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
126572  sqlite3 *db = pParse->db;
126573  if( db->aDb[1].pBt==0 && !pParse->explain ){
126574    int rc;
126575    Btree *pBt;
126576    static const int flags =
126577          SQLITE_OPEN_READWRITE |
126578          SQLITE_OPEN_CREATE |
126579          SQLITE_OPEN_EXCLUSIVE |
126580          SQLITE_OPEN_DELETEONCLOSE |
126581          SQLITE_OPEN_TEMP_DB;
126582
126583    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
126584    if( rc!=SQLITE_OK ){
126585      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
126586        "file for storing temporary tables");
126587      pParse->rc = rc;
126588      return 1;
126589    }
126590    db->aDb[1].pBt = pBt;
126591    assert( db->aDb[1].pSchema );
126592    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
126593      sqlite3OomFault(db);
126594      return 1;
126595    }
126596  }
126597  return 0;
126598}
126599
126600/*
126601** Record the fact that the schema cookie will need to be verified
126602** for database iDb.  The code to actually verify the schema cookie
126603** will occur at the end of the top-level VDBE and will be generated
126604** later, by sqlite3FinishCoding().
126605*/
126606static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){
126607  assert( iDb>=0 && iDb<pToplevel->db->nDb );
126608  assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
126609  assert( iDb<SQLITE_MAX_DB );
126610  assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
126611  if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
126612    DbMaskSet(pToplevel->cookieMask, iDb);
126613    if( !OMIT_TEMPDB && iDb==1 ){
126614      sqlite3OpenTempDatabase(pToplevel);
126615    }
126616  }
126617}
126618SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
126619  sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb);
126620}
126621
126622
126623/*
126624** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
126625** attached database. Otherwise, invoke it for the database named zDb only.
126626*/
126627SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
126628  sqlite3 *db = pParse->db;
126629  int i;
126630  for(i=0; i<db->nDb; i++){
126631    Db *pDb = &db->aDb[i];
126632    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
126633      sqlite3CodeVerifySchema(pParse, i);
126634    }
126635  }
126636}
126637
126638/*
126639** Generate VDBE code that prepares for doing an operation that
126640** might change the database.
126641**
126642** This routine starts a new transaction if we are not already within
126643** a transaction.  If we are already within a transaction, then a checkpoint
126644** is set if the setStatement parameter is true.  A checkpoint should
126645** be set for operations that might fail (due to a constraint) part of
126646** the way through and which will need to undo some writes without having to
126647** rollback the whole transaction.  For operations where all constraints
126648** can be checked before any changes are made to the database, it is never
126649** necessary to undo a write and the checkpoint should not be set.
126650*/
126651SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
126652  Parse *pToplevel = sqlite3ParseToplevel(pParse);
126653  sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb);
126654  DbMaskSet(pToplevel->writeMask, iDb);
126655  pToplevel->isMultiWrite |= setStatement;
126656}
126657
126658/*
126659** Indicate that the statement currently under construction might write
126660** more than one entry (example: deleting one row then inserting another,
126661** inserting multiple rows in a table, or inserting a row and index entries.)
126662** If an abort occurs after some of these writes have completed, then it will
126663** be necessary to undo the completed writes.
126664*/
126665SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
126666  Parse *pToplevel = sqlite3ParseToplevel(pParse);
126667  pToplevel->isMultiWrite = 1;
126668}
126669
126670/*
126671** The code generator calls this routine if is discovers that it is
126672** possible to abort a statement prior to completion.  In order to
126673** perform this abort without corrupting the database, we need to make
126674** sure that the statement is protected by a statement transaction.
126675**
126676** Technically, we only need to set the mayAbort flag if the
126677** isMultiWrite flag was previously set.  There is a time dependency
126678** such that the abort must occur after the multiwrite.  This makes
126679** some statements involving the REPLACE conflict resolution algorithm
126680** go a little faster.  But taking advantage of this time dependency
126681** makes it more difficult to prove that the code is correct (in
126682** particular, it prevents us from writing an effective
126683** implementation of sqlite3AssertMayAbort()) and so we have chosen
126684** to take the safe route and skip the optimization.
126685*/
126686SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
126687  Parse *pToplevel = sqlite3ParseToplevel(pParse);
126688  pToplevel->mayAbort = 1;
126689}
126690
126691/*
126692** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
126693** error. The onError parameter determines which (if any) of the statement
126694** and/or current transaction is rolled back.
126695*/
126696SQLITE_PRIVATE void sqlite3HaltConstraint(
126697  Parse *pParse,    /* Parsing context */
126698  int errCode,      /* extended error code */
126699  int onError,      /* Constraint type */
126700  char *p4,         /* Error message */
126701  i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
126702  u8 p5Errmsg       /* P5_ErrMsg type */
126703){
126704  Vdbe *v;
126705  assert( pParse->pVdbe!=0 );
126706  v = sqlite3GetVdbe(pParse);
126707  assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
126708  if( onError==OE_Abort ){
126709    sqlite3MayAbort(pParse);
126710  }
126711  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
126712  sqlite3VdbeChangeP5(v, p5Errmsg);
126713}
126714
126715/*
126716** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
126717*/
126718SQLITE_PRIVATE void sqlite3UniqueConstraint(
126719  Parse *pParse,    /* Parsing context */
126720  int onError,      /* Constraint type */
126721  Index *pIdx       /* The index that triggers the constraint */
126722){
126723  char *zErr;
126724  int j;
126725  StrAccum errMsg;
126726  Table *pTab = pIdx->pTable;
126727
126728  sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
126729                      pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
126730  if( pIdx->aColExpr ){
126731    sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
126732  }else{
126733    for(j=0; j<pIdx->nKeyCol; j++){
126734      char *zCol;
126735      assert( pIdx->aiColumn[j]>=0 );
126736      zCol = pTab->aCol[pIdx->aiColumn[j]].zCnName;
126737      if( j ) sqlite3_str_append(&errMsg, ", ", 2);
126738      sqlite3_str_appendall(&errMsg, pTab->zName);
126739      sqlite3_str_append(&errMsg, ".", 1);
126740      sqlite3_str_appendall(&errMsg, zCol);
126741    }
126742  }
126743  zErr = sqlite3StrAccumFinish(&errMsg);
126744  sqlite3HaltConstraint(pParse,
126745    IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
126746                            : SQLITE_CONSTRAINT_UNIQUE,
126747    onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
126748}
126749
126750
126751/*
126752** Code an OP_Halt due to non-unique rowid.
126753*/
126754SQLITE_PRIVATE void sqlite3RowidConstraint(
126755  Parse *pParse,    /* Parsing context */
126756  int onError,      /* Conflict resolution algorithm */
126757  Table *pTab       /* The table with the non-unique rowid */
126758){
126759  char *zMsg;
126760  int rc;
126761  if( pTab->iPKey>=0 ){
126762    zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
126763                          pTab->aCol[pTab->iPKey].zCnName);
126764    rc = SQLITE_CONSTRAINT_PRIMARYKEY;
126765  }else{
126766    zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
126767    rc = SQLITE_CONSTRAINT_ROWID;
126768  }
126769  sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
126770                        P5_ConstraintUnique);
126771}
126772
126773/*
126774** Check to see if pIndex uses the collating sequence pColl.  Return
126775** true if it does and false if it does not.
126776*/
126777#ifndef SQLITE_OMIT_REINDEX
126778static int collationMatch(const char *zColl, Index *pIndex){
126779  int i;
126780  assert( zColl!=0 );
126781  for(i=0; i<pIndex->nColumn; i++){
126782    const char *z = pIndex->azColl[i];
126783    assert( z!=0 || pIndex->aiColumn[i]<0 );
126784    if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
126785      return 1;
126786    }
126787  }
126788  return 0;
126789}
126790#endif
126791
126792/*
126793** Recompute all indices of pTab that use the collating sequence pColl.
126794** If pColl==0 then recompute all indices of pTab.
126795*/
126796#ifndef SQLITE_OMIT_REINDEX
126797static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
126798  if( !IsVirtual(pTab) ){
126799    Index *pIndex;              /* An index associated with pTab */
126800
126801    for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
126802      if( zColl==0 || collationMatch(zColl, pIndex) ){
126803        int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
126804        sqlite3BeginWriteOperation(pParse, 0, iDb);
126805        sqlite3RefillIndex(pParse, pIndex, -1);
126806      }
126807    }
126808  }
126809}
126810#endif
126811
126812/*
126813** Recompute all indices of all tables in all databases where the
126814** indices use the collating sequence pColl.  If pColl==0 then recompute
126815** all indices everywhere.
126816*/
126817#ifndef SQLITE_OMIT_REINDEX
126818static void reindexDatabases(Parse *pParse, char const *zColl){
126819  Db *pDb;                    /* A single database */
126820  int iDb;                    /* The database index number */
126821  sqlite3 *db = pParse->db;   /* The database connection */
126822  HashElem *k;                /* For looping over tables in pDb */
126823  Table *pTab;                /* A table in the database */
126824
126825  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
126826  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
126827    assert( pDb!=0 );
126828    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
126829      pTab = (Table*)sqliteHashData(k);
126830      reindexTable(pParse, pTab, zColl);
126831    }
126832  }
126833}
126834#endif
126835
126836/*
126837** Generate code for the REINDEX command.
126838**
126839**        REINDEX                            -- 1
126840**        REINDEX  <collation>               -- 2
126841**        REINDEX  ?<database>.?<tablename>  -- 3
126842**        REINDEX  ?<database>.?<indexname>  -- 4
126843**
126844** Form 1 causes all indices in all attached databases to be rebuilt.
126845** Form 2 rebuilds all indices in all databases that use the named
126846** collating function.  Forms 3 and 4 rebuild the named index or all
126847** indices associated with the named table.
126848*/
126849#ifndef SQLITE_OMIT_REINDEX
126850SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
126851  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
126852  char *z;                    /* Name of a table or index */
126853  const char *zDb;            /* Name of the database */
126854  Table *pTab;                /* A table in the database */
126855  Index *pIndex;              /* An index associated with pTab */
126856  int iDb;                    /* The database index number */
126857  sqlite3 *db = pParse->db;   /* The database connection */
126858  Token *pObjName;            /* Name of the table or index to be reindexed */
126859
126860  /* Read the database schema. If an error occurs, leave an error message
126861  ** and code in pParse and return NULL. */
126862  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
126863    return;
126864  }
126865
126866  if( pName1==0 ){
126867    reindexDatabases(pParse, 0);
126868    return;
126869  }else if( NEVER(pName2==0) || pName2->z==0 ){
126870    char *zColl;
126871    assert( pName1->z );
126872    zColl = sqlite3NameFromToken(pParse->db, pName1);
126873    if( !zColl ) return;
126874    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
126875    if( pColl ){
126876      reindexDatabases(pParse, zColl);
126877      sqlite3DbFree(db, zColl);
126878      return;
126879    }
126880    sqlite3DbFree(db, zColl);
126881  }
126882  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
126883  if( iDb<0 ) return;
126884  z = sqlite3NameFromToken(db, pObjName);
126885  if( z==0 ) return;
126886  zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
126887  pTab = sqlite3FindTable(db, z, zDb);
126888  if( pTab ){
126889    reindexTable(pParse, pTab, 0);
126890    sqlite3DbFree(db, z);
126891    return;
126892  }
126893  pIndex = sqlite3FindIndex(db, z, zDb);
126894  sqlite3DbFree(db, z);
126895  if( pIndex ){
126896    iDb = sqlite3SchemaToIndex(db, pIndex->pTable->pSchema);
126897    sqlite3BeginWriteOperation(pParse, 0, iDb);
126898    sqlite3RefillIndex(pParse, pIndex, -1);
126899    return;
126900  }
126901  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
126902}
126903#endif
126904
126905/*
126906** Return a KeyInfo structure that is appropriate for the given Index.
126907**
126908** The caller should invoke sqlite3KeyInfoUnref() on the returned object
126909** when it has finished using it.
126910*/
126911SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
126912  int i;
126913  int nCol = pIdx->nColumn;
126914  int nKey = pIdx->nKeyCol;
126915  KeyInfo *pKey;
126916  if( pParse->nErr ) return 0;
126917  if( pIdx->uniqNotNull ){
126918    pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
126919  }else{
126920    pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
126921  }
126922  if( pKey ){
126923    assert( sqlite3KeyInfoIsWriteable(pKey) );
126924    for(i=0; i<nCol; i++){
126925      const char *zColl = pIdx->azColl[i];
126926      pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
126927                        sqlite3LocateCollSeq(pParse, zColl);
126928      pKey->aSortFlags[i] = pIdx->aSortOrder[i];
126929      assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
126930    }
126931    if( pParse->nErr ){
126932      assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
126933      if( pIdx->bNoQuery==0 ){
126934        /* Deactivate the index because it contains an unknown collating
126935        ** sequence.  The only way to reactive the index is to reload the
126936        ** schema.  Adding the missing collating sequence later does not
126937        ** reactive the index.  The application had the chance to register
126938        ** the missing index using the collation-needed callback.  For
126939        ** simplicity, SQLite will not give the application a second chance.
126940        */
126941        pIdx->bNoQuery = 1;
126942        pParse->rc = SQLITE_ERROR_RETRY;
126943      }
126944      sqlite3KeyInfoUnref(pKey);
126945      pKey = 0;
126946    }
126947  }
126948  return pKey;
126949}
126950
126951#ifndef SQLITE_OMIT_CTE
126952/*
126953** Create a new CTE object
126954*/
126955SQLITE_PRIVATE Cte *sqlite3CteNew(
126956  Parse *pParse,          /* Parsing context */
126957  Token *pName,           /* Name of the common-table */
126958  ExprList *pArglist,     /* Optional column name list for the table */
126959  Select *pQuery,         /* Query used to initialize the table */
126960  u8 eM10d                /* The MATERIALIZED flag */
126961){
126962  Cte *pNew;
126963  sqlite3 *db = pParse->db;
126964
126965  pNew = sqlite3DbMallocZero(db, sizeof(*pNew));
126966  assert( pNew!=0 || db->mallocFailed );
126967
126968  if( db->mallocFailed ){
126969    sqlite3ExprListDelete(db, pArglist);
126970    sqlite3SelectDelete(db, pQuery);
126971  }else{
126972    pNew->pSelect = pQuery;
126973    pNew->pCols = pArglist;
126974    pNew->zName = sqlite3NameFromToken(pParse->db, pName);
126975    pNew->eM10d = eM10d;
126976  }
126977  return pNew;
126978}
126979
126980/*
126981** Clear information from a Cte object, but do not deallocate storage
126982** for the object itself.
126983*/
126984static void cteClear(sqlite3 *db, Cte *pCte){
126985  assert( pCte!=0 );
126986  sqlite3ExprListDelete(db, pCte->pCols);
126987  sqlite3SelectDelete(db, pCte->pSelect);
126988  sqlite3DbFree(db, pCte->zName);
126989}
126990
126991/*
126992** Free the contents of the CTE object passed as the second argument.
126993*/
126994SQLITE_PRIVATE void sqlite3CteDelete(sqlite3 *db, Cte *pCte){
126995  assert( pCte!=0 );
126996  cteClear(db, pCte);
126997  sqlite3DbFree(db, pCte);
126998}
126999
127000/*
127001** This routine is invoked once per CTE by the parser while parsing a
127002** WITH clause.  The CTE described by the third argument is added to
127003** the WITH clause of the second argument.  If the second argument is
127004** NULL, then a new WITH argument is created.
127005*/
127006SQLITE_PRIVATE With *sqlite3WithAdd(
127007  Parse *pParse,          /* Parsing context */
127008  With *pWith,            /* Existing WITH clause, or NULL */
127009  Cte *pCte               /* CTE to add to the WITH clause */
127010){
127011  sqlite3 *db = pParse->db;
127012  With *pNew;
127013  char *zName;
127014
127015  if( pCte==0 ){
127016    return pWith;
127017  }
127018
127019  /* Check that the CTE name is unique within this WITH clause. If
127020  ** not, store an error in the Parse structure. */
127021  zName = pCte->zName;
127022  if( zName && pWith ){
127023    int i;
127024    for(i=0; i<pWith->nCte; i++){
127025      if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
127026        sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
127027      }
127028    }
127029  }
127030
127031  if( pWith ){
127032    sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
127033    pNew = sqlite3DbRealloc(db, pWith, nByte);
127034  }else{
127035    pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
127036  }
127037  assert( (pNew!=0 && zName!=0) || db->mallocFailed );
127038
127039  if( db->mallocFailed ){
127040    sqlite3CteDelete(db, pCte);
127041    pNew = pWith;
127042  }else{
127043    pNew->a[pNew->nCte++] = *pCte;
127044    sqlite3DbFree(db, pCte);
127045  }
127046
127047  return pNew;
127048}
127049
127050/*
127051** Free the contents of the With object passed as the second argument.
127052*/
127053SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
127054  if( pWith ){
127055    int i;
127056    for(i=0; i<pWith->nCte; i++){
127057      cteClear(db, &pWith->a[i]);
127058    }
127059    sqlite3DbFree(db, pWith);
127060  }
127061}
127062SQLITE_PRIVATE void sqlite3WithDeleteGeneric(sqlite3 *db, void *pWith){
127063  sqlite3WithDelete(db, (With*)pWith);
127064}
127065#endif /* !defined(SQLITE_OMIT_CTE) */
127066
127067/************** End of build.c ***********************************************/
127068/************** Begin file callback.c ****************************************/
127069/*
127070** 2005 May 23
127071**
127072** The author disclaims copyright to this source code.  In place of
127073** a legal notice, here is a blessing:
127074**
127075**    May you do good and not evil.
127076**    May you find forgiveness for yourself and forgive others.
127077**    May you share freely, never taking more than you give.
127078**
127079*************************************************************************
127080**
127081** This file contains functions used to access the internal hash tables
127082** of user defined functions and collation sequences.
127083*/
127084
127085/* #include "sqliteInt.h" */
127086
127087/*
127088** Invoke the 'collation needed' callback to request a collation sequence
127089** in the encoding enc of name zName, length nName.
127090*/
127091static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
127092  assert( !db->xCollNeeded || !db->xCollNeeded16 );
127093  if( db->xCollNeeded ){
127094    char *zExternal = sqlite3DbStrDup(db, zName);
127095    if( !zExternal ) return;
127096    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
127097    sqlite3DbFree(db, zExternal);
127098  }
127099#ifndef SQLITE_OMIT_UTF16
127100  if( db->xCollNeeded16 ){
127101    char const *zExternal;
127102    sqlite3_value *pTmp = sqlite3ValueNew(db);
127103    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
127104    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
127105    if( zExternal ){
127106      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
127107    }
127108    sqlite3ValueFree(pTmp);
127109  }
127110#endif
127111}
127112
127113/*
127114** This routine is called if the collation factory fails to deliver a
127115** collation function in the best encoding but there may be other versions
127116** of this collation function (for other text encodings) available. Use one
127117** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
127118** possible.
127119*/
127120static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
127121  CollSeq *pColl2;
127122  char *z = pColl->zName;
127123  int i;
127124  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
127125  for(i=0; i<3; i++){
127126    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
127127    if( pColl2->xCmp!=0 ){
127128      memcpy(pColl, pColl2, sizeof(CollSeq));
127129      pColl->xDel = 0;         /* Do not copy the destructor */
127130      return SQLITE_OK;
127131    }
127132  }
127133  return SQLITE_ERROR;
127134}
127135
127136/*
127137** This routine is called on a collation sequence before it is used to
127138** check that it is defined. An undefined collation sequence exists when
127139** a database is loaded that contains references to collation sequences
127140** that have not been defined by sqlite3_create_collation() etc.
127141**
127142** If required, this routine calls the 'collation needed' callback to
127143** request a definition of the collating sequence. If this doesn't work,
127144** an equivalent collating sequence that uses a text encoding different
127145** from the main database is substituted, if one is available.
127146*/
127147SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
127148  if( pColl && pColl->xCmp==0 ){
127149    const char *zName = pColl->zName;
127150    sqlite3 *db = pParse->db;
127151    CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
127152    if( !p ){
127153      return SQLITE_ERROR;
127154    }
127155    assert( p==pColl );
127156  }
127157  return SQLITE_OK;
127158}
127159
127160
127161
127162/*
127163** Locate and return an entry from the db.aCollSeq hash table. If the entry
127164** specified by zName and nName is not found and parameter 'create' is
127165** true, then create a new entry. Otherwise return NULL.
127166**
127167** Each pointer stored in the sqlite3.aCollSeq hash table contains an
127168** array of three CollSeq structures. The first is the collation sequence
127169** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
127170**
127171** Stored immediately after the three collation sequences is a copy of
127172** the collation sequence name. A pointer to this string is stored in
127173** each collation sequence structure.
127174*/
127175static CollSeq *findCollSeqEntry(
127176  sqlite3 *db,          /* Database connection */
127177  const char *zName,    /* Name of the collating sequence */
127178  int create            /* Create a new entry if true */
127179){
127180  CollSeq *pColl;
127181  pColl = sqlite3HashFind(&db->aCollSeq, zName);
127182
127183  if( 0==pColl && create ){
127184    int nName = sqlite3Strlen30(zName) + 1;
127185    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
127186    if( pColl ){
127187      CollSeq *pDel = 0;
127188      pColl[0].zName = (char*)&pColl[3];
127189      pColl[0].enc = SQLITE_UTF8;
127190      pColl[1].zName = (char*)&pColl[3];
127191      pColl[1].enc = SQLITE_UTF16LE;
127192      pColl[2].zName = (char*)&pColl[3];
127193      pColl[2].enc = SQLITE_UTF16BE;
127194      memcpy(pColl[0].zName, zName, nName);
127195      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
127196
127197      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
127198      ** return the pColl pointer to be deleted (because it wasn't added
127199      ** to the hash table).
127200      */
127201      assert( pDel==0 || pDel==pColl );
127202      if( pDel!=0 ){
127203        sqlite3OomFault(db);
127204        sqlite3DbFree(db, pDel);
127205        pColl = 0;
127206      }
127207    }
127208  }
127209  return pColl;
127210}
127211
127212/*
127213** Parameter zName points to a UTF-8 encoded string nName bytes long.
127214** Return the CollSeq* pointer for the collation sequence named zName
127215** for the encoding 'enc' from the database 'db'.
127216**
127217** If the entry specified is not found and 'create' is true, then create a
127218** new entry.  Otherwise return NULL.
127219**
127220** A separate function sqlite3LocateCollSeq() is a wrapper around
127221** this routine.  sqlite3LocateCollSeq() invokes the collation factory
127222** if necessary and generates an error message if the collating sequence
127223** cannot be found.
127224**
127225** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
127226*/
127227SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
127228  sqlite3 *db,          /* Database connection to search */
127229  u8 enc,               /* Desired text encoding */
127230  const char *zName,    /* Name of the collating sequence.  Might be NULL */
127231  int create            /* True to create CollSeq if doesn't already exist */
127232){
127233  CollSeq *pColl;
127234  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
127235  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
127236  if( zName ){
127237    pColl = findCollSeqEntry(db, zName, create);
127238    if( pColl ) pColl += enc-1;
127239  }else{
127240    pColl = db->pDfltColl;
127241  }
127242  return pColl;
127243}
127244
127245/*
127246** Change the text encoding for a database connection. This means that
127247** the pDfltColl must change as well.
127248*/
127249SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8 enc){
127250  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
127251  db->enc = enc;
127252  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
127253  ** strings is BINARY.
127254  */
127255  db->pDfltColl = sqlite3FindCollSeq(db, enc, sqlite3StrBINARY, 0);
127256  sqlite3ExpirePreparedStatements(db, 1);
127257}
127258
127259/*
127260** This function is responsible for invoking the collation factory callback
127261** or substituting a collation sequence of a different encoding when the
127262** requested collation sequence is not available in the desired encoding.
127263**
127264** If it is not NULL, then pColl must point to the database native encoding
127265** collation sequence with name zName, length nName.
127266**
127267** The return value is either the collation sequence to be used in database
127268** db for collation type name zName, length nName, or NULL, if no collation
127269** sequence can be found.  If no collation is found, leave an error message.
127270**
127271** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
127272*/
127273SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
127274  Parse *pParse,        /* Parsing context */
127275  u8 enc,               /* The desired encoding for the collating sequence */
127276  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
127277  const char *zName     /* Collating sequence name */
127278){
127279  CollSeq *p;
127280  sqlite3 *db = pParse->db;
127281
127282  p = pColl;
127283  if( !p ){
127284    p = sqlite3FindCollSeq(db, enc, zName, 0);
127285  }
127286  if( !p || !p->xCmp ){
127287    /* No collation sequence of this type for this encoding is registered.
127288    ** Call the collation factory to see if it can supply us with one.
127289    */
127290    callCollNeeded(db, enc, zName);
127291    p = sqlite3FindCollSeq(db, enc, zName, 0);
127292  }
127293  if( p && !p->xCmp && synthCollSeq(db, p) ){
127294    p = 0;
127295  }
127296  assert( !p || p->xCmp );
127297  if( p==0 ){
127298    sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
127299    pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
127300  }
127301  return p;
127302}
127303
127304/*
127305** This function returns the collation sequence for database native text
127306** encoding identified by the string zName.
127307**
127308** If the requested collation sequence is not available, or not available
127309** in the database native encoding, the collation factory is invoked to
127310** request it. If the collation factory does not supply such a sequence,
127311** and the sequence is available in another text encoding, then that is
127312** returned instead.
127313**
127314** If no versions of the requested collations sequence are available, or
127315** another error occurs, NULL is returned and an error message written into
127316** pParse.
127317**
127318** This routine is a wrapper around sqlite3FindCollSeq().  This routine
127319** invokes the collation factory if the named collation cannot be found
127320** and generates an error message.
127321**
127322** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
127323*/
127324SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
127325  sqlite3 *db = pParse->db;
127326  u8 enc = ENC(db);
127327  u8 initbusy = db->init.busy;
127328  CollSeq *pColl;
127329
127330  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
127331  if( !initbusy && (!pColl || !pColl->xCmp) ){
127332    pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
127333  }
127334
127335  return pColl;
127336}
127337
127338/* During the search for the best function definition, this procedure
127339** is called to test how well the function passed as the first argument
127340** matches the request for a function with nArg arguments in a system
127341** that uses encoding enc. The value returned indicates how well the
127342** request is matched. A higher value indicates a better match.
127343**
127344** If nArg is -1 that means to only return a match (non-zero) if p->nArg
127345** is also -1.  In other words, we are searching for a function that
127346** takes a variable number of arguments.
127347**
127348** If nArg is -2 that means that we are searching for any function
127349** regardless of the number of arguments it uses, so return a positive
127350** match score for any
127351**
127352** The returned value is always between 0 and 6, as follows:
127353**
127354** 0: Not a match.
127355** 1: UTF8/16 conversion required and function takes any number of arguments.
127356** 2: UTF16 byte order change required and function takes any number of args.
127357** 3: encoding matches and function takes any number of arguments
127358** 4: UTF8/16 conversion required - argument count matches exactly
127359** 5: UTF16 byte order conversion required - argument count matches exactly
127360** 6: Perfect match:  encoding and argument count match exactly.
127361**
127362** If nArg==(-2) then any function with a non-null xSFunc is
127363** a perfect match and any function with xSFunc NULL is
127364** a non-match.
127365*/
127366#define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
127367static int matchQuality(
127368  FuncDef *p,     /* The function we are evaluating for match quality */
127369  int nArg,       /* Desired number of arguments.  (-1)==any */
127370  u8 enc          /* Desired text encoding */
127371){
127372  int match;
127373  assert( p->nArg>=-1 );
127374
127375  /* Wrong number of arguments means "no match" */
127376  if( p->nArg!=nArg ){
127377    if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
127378    if( p->nArg>=0 ) return 0;
127379  }
127380
127381  /* Give a better score to a function with a specific number of arguments
127382  ** than to function that accepts any number of arguments. */
127383  if( p->nArg==nArg ){
127384    match = 4;
127385  }else{
127386    match = 1;
127387  }
127388
127389  /* Bonus points if the text encoding matches */
127390  if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
127391    match += 2;  /* Exact encoding match */
127392  }else if( (enc & p->funcFlags & 2)!=0 ){
127393    match += 1;  /* Both are UTF16, but with different byte orders */
127394  }
127395
127396  return match;
127397}
127398
127399/*
127400** Search a FuncDefHash for a function with the given name.  Return
127401** a pointer to the matching FuncDef if found, or 0 if there is no match.
127402*/
127403SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(
127404  int h,               /* Hash of the name */
127405  const char *zFunc    /* Name of function */
127406){
127407  FuncDef *p;
127408  for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
127409    assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
127410    if( sqlite3StrICmp(p->zName, zFunc)==0 ){
127411      return p;
127412    }
127413  }
127414  return 0;
127415}
127416
127417/*
127418** Insert a new FuncDef into a FuncDefHash hash table.
127419*/
127420SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
127421  FuncDef *aDef,      /* List of global functions to be inserted */
127422  int nDef            /* Length of the apDef[] list */
127423){
127424  int i;
127425  for(i=0; i<nDef; i++){
127426    FuncDef *pOther;
127427    const char *zName = aDef[i].zName;
127428    int nName = sqlite3Strlen30(zName);
127429    int h = SQLITE_FUNC_HASH(zName[0], nName);
127430    assert( aDef[i].funcFlags & SQLITE_FUNC_BUILTIN );
127431    pOther = sqlite3FunctionSearch(h, zName);
127432    if( pOther ){
127433      assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
127434      aDef[i].pNext = pOther->pNext;
127435      pOther->pNext = &aDef[i];
127436    }else{
127437      aDef[i].pNext = 0;
127438      aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
127439      sqlite3BuiltinFunctions.a[h] = &aDef[i];
127440    }
127441  }
127442}
127443
127444
127445
127446/*
127447** Locate a user function given a name, a number of arguments and a flag
127448** indicating whether the function prefers UTF-16 over UTF-8.  Return a
127449** pointer to the FuncDef structure that defines that function, or return
127450** NULL if the function does not exist.
127451**
127452** If the createFlag argument is true, then a new (blank) FuncDef
127453** structure is created and liked into the "db" structure if a
127454** no matching function previously existed.
127455**
127456** If nArg is -2, then the first valid function found is returned.  A
127457** function is valid if xSFunc is non-zero.  The nArg==(-2)
127458** case is used to see if zName is a valid function name for some number
127459** of arguments.  If nArg is -2, then createFlag must be 0.
127460**
127461** If createFlag is false, then a function with the required name and
127462** number of arguments may be returned even if the eTextRep flag does not
127463** match that requested.
127464*/
127465SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
127466  sqlite3 *db,       /* An open database */
127467  const char *zName, /* Name of the function.  zero-terminated */
127468  int nArg,          /* Number of arguments.  -1 means any number */
127469  u8 enc,            /* Preferred text encoding */
127470  u8 createFlag      /* Create new entry if true and does not otherwise exist */
127471){
127472  FuncDef *p;         /* Iterator variable */
127473  FuncDef *pBest = 0; /* Best match found so far */
127474  int bestScore = 0;  /* Score of best match */
127475  int h;              /* Hash value */
127476  int nName;          /* Length of the name */
127477
127478  assert( nArg>=(-2) );
127479  assert( nArg>=(-1) || createFlag==0 );
127480  nName = sqlite3Strlen30(zName);
127481
127482  /* First search for a match amongst the application-defined functions.
127483  */
127484  p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
127485  while( p ){
127486    int score = matchQuality(p, nArg, enc);
127487    if( score>bestScore ){
127488      pBest = p;
127489      bestScore = score;
127490    }
127491    p = p->pNext;
127492  }
127493
127494  /* If no match is found, search the built-in functions.
127495  **
127496  ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
127497  ** functions even if a prior app-defined function was found.  And give
127498  ** priority to built-in functions.
127499  **
127500  ** Except, if createFlag is true, that means that we are trying to
127501  ** install a new function.  Whatever FuncDef structure is returned it will
127502  ** have fields overwritten with new information appropriate for the
127503  ** new function.  But the FuncDefs for built-in functions are read-only.
127504  ** So we must not search for built-ins when creating a new function.
127505  */
127506  if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
127507    bestScore = 0;
127508    h = SQLITE_FUNC_HASH(sqlite3UpperToLower[(u8)zName[0]], nName);
127509    p = sqlite3FunctionSearch(h, zName);
127510    while( p ){
127511      int score = matchQuality(p, nArg, enc);
127512      if( score>bestScore ){
127513        pBest = p;
127514        bestScore = score;
127515      }
127516      p = p->pNext;
127517    }
127518  }
127519
127520  /* If the createFlag parameter is true and the search did not reveal an
127521  ** exact match for the name, number of arguments and encoding, then add a
127522  ** new entry to the hash table and return it.
127523  */
127524  if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
127525      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
127526    FuncDef *pOther;
127527    u8 *z;
127528    pBest->zName = (const char*)&pBest[1];
127529    pBest->nArg = (u16)nArg;
127530    pBest->funcFlags = enc;
127531    memcpy((char*)&pBest[1], zName, nName+1);
127532    for(z=(u8*)pBest->zName; *z; z++) *z = sqlite3UpperToLower[*z];
127533    pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
127534    if( pOther==pBest ){
127535      sqlite3DbFree(db, pBest);
127536      sqlite3OomFault(db);
127537      return 0;
127538    }else{
127539      pBest->pNext = pOther;
127540    }
127541  }
127542
127543  if( pBest && (pBest->xSFunc || createFlag) ){
127544    return pBest;
127545  }
127546  return 0;
127547}
127548
127549/*
127550** Free all resources held by the schema structure. The void* argument points
127551** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
127552** pointer itself, it just cleans up subsidiary resources (i.e. the contents
127553** of the schema hash tables).
127554**
127555** The Schema.cache_size variable is not cleared.
127556*/
127557SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
127558  Hash temp1;
127559  Hash temp2;
127560  HashElem *pElem;
127561  Schema *pSchema = (Schema *)p;
127562  sqlite3 xdb;
127563
127564  memset(&xdb, 0, sizeof(xdb));
127565  temp1 = pSchema->tblHash;
127566  temp2 = pSchema->trigHash;
127567  sqlite3HashInit(&pSchema->trigHash);
127568  sqlite3HashClear(&pSchema->idxHash);
127569  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
127570    sqlite3DeleteTrigger(&xdb, (Trigger*)sqliteHashData(pElem));
127571  }
127572  sqlite3HashClear(&temp2);
127573  sqlite3HashInit(&pSchema->tblHash);
127574  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
127575    Table *pTab = sqliteHashData(pElem);
127576    sqlite3DeleteTable(&xdb, pTab);
127577  }
127578  sqlite3HashClear(&temp1);
127579  sqlite3HashClear(&pSchema->fkeyHash);
127580  pSchema->pSeqTab = 0;
127581  if( pSchema->schemaFlags & DB_SchemaLoaded ){
127582    pSchema->iGeneration++;
127583  }
127584  pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
127585}
127586
127587/*
127588** Find and return the schema associated with a BTree.  Create
127589** a new one if necessary.
127590*/
127591SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
127592  Schema * p;
127593  if( pBt ){
127594    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
127595  }else{
127596    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
127597  }
127598  if( !p ){
127599    sqlite3OomFault(db);
127600  }else if ( 0==p->file_format ){
127601    sqlite3HashInit(&p->tblHash);
127602    sqlite3HashInit(&p->idxHash);
127603    sqlite3HashInit(&p->trigHash);
127604    sqlite3HashInit(&p->fkeyHash);
127605    p->enc = SQLITE_UTF8;
127606  }
127607  return p;
127608}
127609
127610/************** End of callback.c ********************************************/
127611/************** Begin file delete.c ******************************************/
127612/*
127613** 2001 September 15
127614**
127615** The author disclaims copyright to this source code.  In place of
127616** a legal notice, here is a blessing:
127617**
127618**    May you do good and not evil.
127619**    May you find forgiveness for yourself and forgive others.
127620**    May you share freely, never taking more than you give.
127621**
127622*************************************************************************
127623** This file contains C code routines that are called by the parser
127624** in order to generate code for DELETE FROM statements.
127625*/
127626/* #include "sqliteInt.h" */
127627
127628/*
127629** While a SrcList can in general represent multiple tables and subqueries
127630** (as in the FROM clause of a SELECT statement) in this case it contains
127631** the name of a single table, as one might find in an INSERT, DELETE,
127632** or UPDATE statement.  Look up that table in the symbol table and
127633** return a pointer.  Set an error message and return NULL if the table
127634** name is not found or if any other error occurs.
127635**
127636** The following fields are initialized appropriate in pSrc:
127637**
127638**    pSrc->a[0].pTab       Pointer to the Table object
127639**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
127640**
127641*/
127642SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
127643  SrcItem *pItem = pSrc->a;
127644  Table *pTab;
127645  assert( pItem && pSrc->nSrc>=1 );
127646  pTab = sqlite3LocateTableItem(pParse, 0, pItem);
127647  if( pItem->pTab ) sqlite3DeleteTable(pParse->db, pItem->pTab);
127648  pItem->pTab = pTab;
127649  pItem->fg.notCte = 1;
127650  if( pTab ){
127651    pTab->nTabRef++;
127652    if( pItem->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pItem) ){
127653      pTab = 0;
127654    }
127655  }
127656  return pTab;
127657}
127658
127659/* Generate byte-code that will report the number of rows modified
127660** by a DELETE, INSERT, or UPDATE statement.
127661*/
127662SQLITE_PRIVATE void sqlite3CodeChangeCount(Vdbe *v, int regCounter, const char *zColName){
127663  sqlite3VdbeAddOp0(v, OP_FkCheck);
127664  sqlite3VdbeAddOp2(v, OP_ResultRow, regCounter, 1);
127665  sqlite3VdbeSetNumCols(v, 1);
127666  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zColName, SQLITE_STATIC);
127667}
127668
127669/* Return true if table pTab is read-only.
127670**
127671** A table is read-only if any of the following are true:
127672**
127673**   1) It is a virtual table and no implementation of the xUpdate method
127674**      has been provided
127675**
127676**   2) A trigger is currently being coded and the table is a virtual table
127677**      that is SQLITE_VTAB_DIRECTONLY or if PRAGMA trusted_schema=OFF and
127678**      the table is not SQLITE_VTAB_INNOCUOUS.
127679**
127680**   3) It is a system table (i.e. sqlite_schema), this call is not
127681**      part of a nested parse and writable_schema pragma has not
127682**      been specified
127683**
127684**   4) The table is a shadow table, the database connection is in
127685**      defensive mode, and the current sqlite3_prepare()
127686**      is for a top-level SQL statement.
127687*/
127688static int vtabIsReadOnly(Parse *pParse, Table *pTab){
127689  if( sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 ){
127690    return 1;
127691  }
127692
127693  /* Within triggers:
127694  **   *  Do not allow DELETE, INSERT, or UPDATE of SQLITE_VTAB_DIRECTONLY
127695  **      virtual tables
127696  **   *  Only allow DELETE, INSERT, or UPDATE of non-SQLITE_VTAB_INNOCUOUS
127697  **      virtual tables if PRAGMA trusted_schema=ON.
127698  */
127699  if( pParse->pToplevel!=0
127700   && pTab->u.vtab.p->eVtabRisk >
127701           ((pParse->db->flags & SQLITE_TrustedSchema)!=0)
127702  ){
127703    sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
127704      pTab->zName);
127705  }
127706  return 0;
127707}
127708static int tabIsReadOnly(Parse *pParse, Table *pTab){
127709  sqlite3 *db;
127710  if( IsVirtual(pTab) ){
127711    return vtabIsReadOnly(pParse, pTab);
127712  }
127713  if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0;
127714  db = pParse->db;
127715  if( (pTab->tabFlags & TF_Readonly)!=0 ){
127716    return sqlite3WritableSchema(db)==0 && pParse->nested==0;
127717  }
127718  assert( pTab->tabFlags & TF_Shadow );
127719  return sqlite3ReadOnlyShadowTables(db);
127720}
127721
127722/*
127723** Check to make sure the given table is writable.
127724**
127725** If pTab is not writable  ->  generate an error message and return 1.
127726** If pTab is writable but other errors have occurred -> return 1.
127727** If pTab is writable and no prior errors -> return 0;
127728*/
127729SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, Trigger *pTrigger){
127730  if( tabIsReadOnly(pParse, pTab) ){
127731    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
127732    return 1;
127733  }
127734#ifndef SQLITE_OMIT_VIEW
127735  if( IsView(pTab)
127736   && (pTrigger==0 || (pTrigger->bReturning && pTrigger->pNext==0))
127737  ){
127738    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
127739    return 1;
127740  }
127741#endif
127742  return 0;
127743}
127744
127745
127746#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
127747/*
127748** Evaluate a view and store its result in an ephemeral table.  The
127749** pWhere argument is an optional WHERE clause that restricts the
127750** set of rows in the view that are to be added to the ephemeral table.
127751*/
127752SQLITE_PRIVATE void sqlite3MaterializeView(
127753  Parse *pParse,       /* Parsing context */
127754  Table *pView,        /* View definition */
127755  Expr *pWhere,        /* Optional WHERE clause to be added */
127756  ExprList *pOrderBy,  /* Optional ORDER BY clause */
127757  Expr *pLimit,        /* Optional LIMIT clause */
127758  int iCur             /* Cursor number for ephemeral table */
127759){
127760  SelectDest dest;
127761  Select *pSel;
127762  SrcList *pFrom;
127763  sqlite3 *db = pParse->db;
127764  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
127765  pWhere = sqlite3ExprDup(db, pWhere, 0);
127766  pFrom = sqlite3SrcListAppend(pParse, 0, 0, 0);
127767  if( pFrom ){
127768    assert( pFrom->nSrc==1 );
127769    pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
127770    pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
127771    assert( pFrom->a[0].fg.isUsing==0 );
127772    assert( pFrom->a[0].u3.pOn==0 );
127773  }
127774  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy,
127775                          SF_IncludeHidden, pLimit);
127776  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
127777  sqlite3Select(pParse, pSel, &dest);
127778  sqlite3SelectDelete(db, pSel);
127779}
127780#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
127781
127782#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
127783/*
127784** Generate an expression tree to implement the WHERE, ORDER BY,
127785** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
127786**
127787**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
127788**                            \__________________________/
127789**                               pLimitWhere (pInClause)
127790*/
127791SQLITE_PRIVATE Expr *sqlite3LimitWhere(
127792  Parse *pParse,               /* The parser context */
127793  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
127794  Expr *pWhere,                /* The WHERE clause.  May be null */
127795  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
127796  Expr *pLimit,                /* The LIMIT clause.  May be null */
127797  char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
127798){
127799  sqlite3 *db = pParse->db;
127800  Expr *pLhs = NULL;           /* LHS of IN(SELECT...) operator */
127801  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
127802  ExprList *pEList = NULL;     /* Expression list containing only pSelectRowid*/
127803  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
127804  Select *pSelect = NULL;      /* Complete SELECT tree */
127805  Table *pTab;
127806
127807  /* Check that there isn't an ORDER BY without a LIMIT clause.
127808  */
127809  if( pOrderBy && pLimit==0 ) {
127810    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
127811    sqlite3ExprDelete(pParse->db, pWhere);
127812    sqlite3ExprListDelete(pParse->db, pOrderBy);
127813    return 0;
127814  }
127815
127816  /* We only need to generate a select expression if there
127817  ** is a limit/offset term to enforce.
127818  */
127819  if( pLimit == 0 ) {
127820    return pWhere;
127821  }
127822
127823  /* Generate a select expression tree to enforce the limit/offset
127824  ** term for the DELETE or UPDATE statement.  For example:
127825  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
127826  ** becomes:
127827  **   DELETE FROM table_a WHERE rowid IN (
127828  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
127829  **   );
127830  */
127831
127832  pTab = pSrc->a[0].pTab;
127833  if( HasRowid(pTab) ){
127834    pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0);
127835    pEList = sqlite3ExprListAppend(
127836        pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0)
127837    );
127838  }else{
127839    Index *pPk = sqlite3PrimaryKeyIndex(pTab);
127840    assert( pPk!=0 );
127841    assert( pPk->nKeyCol>=1 );
127842    if( pPk->nKeyCol==1 ){
127843      const char *zName;
127844      assert( pPk->aiColumn[0]>=0 && pPk->aiColumn[0]<pTab->nCol );
127845      zName = pTab->aCol[pPk->aiColumn[0]].zCnName;
127846      pLhs = sqlite3Expr(db, TK_ID, zName);
127847      pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));
127848    }else{
127849      int i;
127850      for(i=0; i<pPk->nKeyCol; i++){
127851        Expr *p;
127852        assert( pPk->aiColumn[i]>=0 && pPk->aiColumn[i]<pTab->nCol );
127853        p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zCnName);
127854        pEList = sqlite3ExprListAppend(pParse, pEList, p);
127855      }
127856      pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
127857      if( pLhs ){
127858        pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
127859      }
127860    }
127861  }
127862
127863  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
127864  ** and the SELECT subtree. */
127865  pSrc->a[0].pTab = 0;
127866  pSelectSrc = sqlite3SrcListDup(db, pSrc, 0);
127867  pSrc->a[0].pTab = pTab;
127868  if( pSrc->a[0].fg.isIndexedBy ){
127869    assert( pSrc->a[0].fg.isCte==0 );
127870    pSrc->a[0].u2.pIBIndex = 0;
127871    pSrc->a[0].fg.isIndexedBy = 0;
127872    sqlite3DbFree(db, pSrc->a[0].u1.zIndexedBy);
127873  }else if( pSrc->a[0].fg.isCte ){
127874    pSrc->a[0].u2.pCteUse->nUse++;
127875  }
127876
127877  /* generate the SELECT expression tree. */
127878  pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0,
127879      pOrderBy,0,pLimit
127880  );
127881
127882  /* now generate the new WHERE rowid IN clause for the DELETE/UPDATE */
127883  pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0);
127884  sqlite3PExprAddSelect(pParse, pInClause, pSelect);
127885  return pInClause;
127886}
127887#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
127888       /*      && !defined(SQLITE_OMIT_SUBQUERY) */
127889
127890/*
127891** Generate code for a DELETE FROM statement.
127892**
127893**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
127894**                 \________/       \________________/
127895**                  pTabList              pWhere
127896*/
127897SQLITE_PRIVATE void sqlite3DeleteFrom(
127898  Parse *pParse,         /* The parser context */
127899  SrcList *pTabList,     /* The table from which we should delete things */
127900  Expr *pWhere,          /* The WHERE clause.  May be null */
127901  ExprList *pOrderBy,    /* ORDER BY clause. May be null */
127902  Expr *pLimit           /* LIMIT clause. May be null */
127903){
127904  Vdbe *v;               /* The virtual database engine */
127905  Table *pTab;           /* The table from which records will be deleted */
127906  int i;                 /* Loop counter */
127907  WhereInfo *pWInfo;     /* Information about the WHERE clause */
127908  Index *pIdx;           /* For looping over indices of the table */
127909  int iTabCur;           /* Cursor number for the table */
127910  int iDataCur = 0;      /* VDBE cursor for the canonical data source */
127911  int iIdxCur = 0;       /* Cursor number of the first index */
127912  int nIdx;              /* Number of indices */
127913  sqlite3 *db;           /* Main database structure */
127914  AuthContext sContext;  /* Authorization context */
127915  NameContext sNC;       /* Name context to resolve expressions in */
127916  int iDb;               /* Database number */
127917  int memCnt = 0;        /* Memory cell used for change counting */
127918  int rcauth;            /* Value returned by authorization callback */
127919  int eOnePass;          /* ONEPASS_OFF or _SINGLE or _MULTI */
127920  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
127921  u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
127922  Index *pPk;            /* The PRIMARY KEY index on the table */
127923  int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
127924  i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
127925  int iKey;              /* Memory cell holding key of row to be deleted */
127926  i16 nKey;              /* Number of memory cells in the row key */
127927  int iEphCur = 0;       /* Ephemeral table holding all primary key values */
127928  int iRowSet = 0;       /* Register for rowset of rows to delete */
127929  int addrBypass = 0;    /* Address of jump over the delete logic */
127930  int addrLoop = 0;      /* Top of the delete loop */
127931  int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
127932  int bComplex;          /* True if there are triggers or FKs or
127933                         ** subqueries in the WHERE clause */
127934
127935#ifndef SQLITE_OMIT_TRIGGER
127936  int isView;                  /* True if attempting to delete from a view */
127937  Trigger *pTrigger;           /* List of table triggers, if required */
127938#endif
127939
127940  memset(&sContext, 0, sizeof(sContext));
127941  db = pParse->db;
127942  assert( db->pParse==pParse );
127943  if( pParse->nErr ){
127944    goto delete_from_cleanup;
127945  }
127946  assert( db->mallocFailed==0 );
127947  assert( pTabList->nSrc==1 );
127948
127949  /* Locate the table which we want to delete.  This table has to be
127950  ** put in an SrcList structure because some of the subroutines we
127951  ** will be calling are designed to work with multiple tables and expect
127952  ** an SrcList* parameter instead of just a Table* parameter.
127953  */
127954  pTab = sqlite3SrcListLookup(pParse, pTabList);
127955  if( pTab==0 )  goto delete_from_cleanup;
127956
127957  /* Figure out if we have any triggers and if the table being
127958  ** deleted from is a view
127959  */
127960#ifndef SQLITE_OMIT_TRIGGER
127961  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
127962  isView = IsView(pTab);
127963#else
127964# define pTrigger 0
127965# define isView 0
127966#endif
127967  bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
127968#ifdef SQLITE_OMIT_VIEW
127969# undef isView
127970# define isView 0
127971#endif
127972
127973#if TREETRACE_ENABLED
127974  if( sqlite3TreeTrace & 0x10000 ){
127975    sqlite3TreeViewLine(0, "In sqlite3Delete() at %s:%d", __FILE__, __LINE__);
127976    sqlite3TreeViewDelete(pParse->pWith, pTabList, pWhere,
127977                          pOrderBy, pLimit, pTrigger);
127978  }
127979#endif
127980
127981#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
127982  if( !isView ){
127983    pWhere = sqlite3LimitWhere(
127984        pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE"
127985    );
127986    pOrderBy = 0;
127987    pLimit = 0;
127988  }
127989#endif
127990
127991  /* If pTab is really a view, make sure it has been initialized.
127992  */
127993  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
127994    goto delete_from_cleanup;
127995  }
127996
127997  if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
127998    goto delete_from_cleanup;
127999  }
128000  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
128001  assert( iDb<db->nDb );
128002  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
128003                            db->aDb[iDb].zDbSName);
128004  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
128005  if( rcauth==SQLITE_DENY ){
128006    goto delete_from_cleanup;
128007  }
128008  assert(!isView || pTrigger);
128009
128010  /* Assign cursor numbers to the table and all its indices.
128011  */
128012  assert( pTabList->nSrc==1 );
128013  iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
128014  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
128015    pParse->nTab++;
128016  }
128017
128018  /* Start the view context
128019  */
128020  if( isView ){
128021    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
128022  }
128023
128024  /* Begin generating code.
128025  */
128026  v = sqlite3GetVdbe(pParse);
128027  if( v==0 ){
128028    goto delete_from_cleanup;
128029  }
128030  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
128031  sqlite3BeginWriteOperation(pParse, bComplex, iDb);
128032
128033  /* If we are trying to delete from a view, realize that view into
128034  ** an ephemeral table.
128035  */
128036#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
128037  if( isView ){
128038    sqlite3MaterializeView(pParse, pTab,
128039        pWhere, pOrderBy, pLimit, iTabCur
128040    );
128041    iDataCur = iIdxCur = iTabCur;
128042    pOrderBy = 0;
128043    pLimit = 0;
128044  }
128045#endif
128046
128047  /* Resolve the column names in the WHERE clause.
128048  */
128049  memset(&sNC, 0, sizeof(sNC));
128050  sNC.pParse = pParse;
128051  sNC.pSrcList = pTabList;
128052  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
128053    goto delete_from_cleanup;
128054  }
128055
128056  /* Initialize the counter of the number of rows deleted, if
128057  ** we are counting rows.
128058  */
128059  if( (db->flags & SQLITE_CountRows)!=0
128060   && !pParse->nested
128061   && !pParse->pTriggerTab
128062   && !pParse->bReturning
128063  ){
128064    memCnt = ++pParse->nMem;
128065    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
128066  }
128067
128068#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
128069  /* Special case: A DELETE without a WHERE clause deletes everything.
128070  ** It is easier just to erase the whole table. Prior to version 3.6.5,
128071  ** this optimization caused the row change count (the value returned by
128072  ** API function sqlite3_count_changes) to be set incorrectly.
128073  **
128074  ** The "rcauth==SQLITE_OK" terms is the
128075  ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
128076  ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
128077  ** the truncate optimization is disabled and all rows are deleted
128078  ** individually.
128079  */
128080  if( rcauth==SQLITE_OK
128081   && pWhere==0
128082   && !bComplex
128083   && !IsVirtual(pTab)
128084#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
128085   && db->xPreUpdateCallback==0
128086#endif
128087  ){
128088    assert( !isView );
128089    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
128090    if( HasRowid(pTab) ){
128091      sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1,
128092                        pTab->zName, P4_STATIC);
128093    }
128094    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
128095      assert( pIdx->pSchema==pTab->pSchema );
128096      if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
128097        sqlite3VdbeAddOp3(v, OP_Clear, pIdx->tnum, iDb, memCnt ? memCnt : -1);
128098      }else{
128099        sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
128100      }
128101    }
128102  }else
128103#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
128104  {
128105    u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
128106    if( sNC.ncFlags & NC_Subquery ) bComplex = 1;
128107    wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
128108    if( HasRowid(pTab) ){
128109      /* For a rowid table, initialize the RowSet to an empty set */
128110      pPk = 0;
128111      assert( nPk==1 );
128112      iRowSet = ++pParse->nMem;
128113      sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
128114    }else{
128115      /* For a WITHOUT ROWID table, create an ephemeral table used to
128116      ** hold all primary keys for rows to be deleted. */
128117      pPk = sqlite3PrimaryKeyIndex(pTab);
128118      assert( pPk!=0 );
128119      nPk = pPk->nKeyCol;
128120      iPk = pParse->nMem+1;
128121      pParse->nMem += nPk;
128122      iEphCur = pParse->nTab++;
128123      addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
128124      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
128125    }
128126
128127    /* Construct a query to find the rowid or primary key for every row
128128    ** to be deleted, based on the WHERE clause. Set variable eOnePass
128129    ** to indicate the strategy used to implement this delete:
128130    **
128131    **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.
128132    **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
128133    **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
128134    */
128135    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,0,wcf,iTabCur+1);
128136    if( pWInfo==0 ) goto delete_from_cleanup;
128137    eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
128138    assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
128139    assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF
128140            || OptimizationDisabled(db, SQLITE_OnePass) );
128141    if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse);
128142    if( sqlite3WhereUsesDeferredSeek(pWInfo) ){
128143      sqlite3VdbeAddOp1(v, OP_FinishSeek, iTabCur);
128144    }
128145
128146    /* Keep track of the number of rows to be deleted */
128147    if( memCnt ){
128148      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
128149    }
128150
128151    /* Extract the rowid or primary key for the current row */
128152    if( pPk ){
128153      for(i=0; i<nPk; i++){
128154        assert( pPk->aiColumn[i]>=0 );
128155        sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
128156                                        pPk->aiColumn[i], iPk+i);
128157      }
128158      iKey = iPk;
128159    }else{
128160      iKey = ++pParse->nMem;
128161      sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey);
128162    }
128163
128164    if( eOnePass!=ONEPASS_OFF ){
128165      /* For ONEPASS, no need to store the rowid/primary-key. There is only
128166      ** one, so just keep it in its register(s) and fall through to the
128167      ** delete code.  */
128168      nKey = nPk; /* OP_Found will use an unpacked key */
128169      aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
128170      if( aToOpen==0 ){
128171        sqlite3WhereEnd(pWInfo);
128172        goto delete_from_cleanup;
128173      }
128174      memset(aToOpen, 1, nIdx+1);
128175      aToOpen[nIdx+1] = 0;
128176      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
128177      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
128178      if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
128179      addrBypass = sqlite3VdbeMakeLabel(pParse);
128180    }else{
128181      if( pPk ){
128182        /* Add the PK key for this row to the temporary table */
128183        iKey = ++pParse->nMem;
128184        nKey = 0;   /* Zero tells OP_Found to use a composite key */
128185        sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
128186            sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
128187        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
128188      }else{
128189        /* Add the rowid of the row to be deleted to the RowSet */
128190        nKey = 1;  /* OP_DeferredSeek always uses a single rowid */
128191        sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
128192      }
128193      sqlite3WhereEnd(pWInfo);
128194    }
128195
128196    /* Unless this is a view, open cursors for the table we are
128197    ** deleting from and all its indices. If this is a view, then the
128198    ** only effect this statement has is to fire the INSTEAD OF
128199    ** triggers.
128200    */
128201    if( !isView ){
128202      int iAddrOnce = 0;
128203      if( eOnePass==ONEPASS_MULTI ){
128204        iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
128205      }
128206      testcase( IsVirtual(pTab) );
128207      sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
128208                                 iTabCur, aToOpen, &iDataCur, &iIdxCur);
128209      assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
128210      assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
128211      if( eOnePass==ONEPASS_MULTI ){
128212        sqlite3VdbeJumpHereOrPopInst(v, iAddrOnce);
128213      }
128214    }
128215
128216    /* Set up a loop over the rowids/primary-keys that were found in the
128217    ** where-clause loop above.
128218    */
128219    if( eOnePass!=ONEPASS_OFF ){
128220      assert( nKey==nPk );  /* OP_Found will use an unpacked key */
128221      if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
128222        assert( pPk!=0 || IsView(pTab) );
128223        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
128224        VdbeCoverage(v);
128225      }
128226    }else if( pPk ){
128227      addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
128228      if( IsVirtual(pTab) ){
128229        sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
128230      }else{
128231        sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
128232      }
128233      assert( nKey==0 );  /* OP_Found will use a composite key */
128234    }else{
128235      addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
128236      VdbeCoverage(v);
128237      assert( nKey==1 );
128238    }
128239
128240    /* Delete the row */
128241#ifndef SQLITE_OMIT_VIRTUALTABLE
128242    if( IsVirtual(pTab) ){
128243      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
128244      sqlite3VtabMakeWritable(pParse, pTab);
128245      assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
128246      sqlite3MayAbort(pParse);
128247      if( eOnePass==ONEPASS_SINGLE ){
128248        sqlite3VdbeAddOp1(v, OP_Close, iTabCur);
128249        if( sqlite3IsToplevel(pParse) ){
128250          pParse->isMultiWrite = 0;
128251        }
128252      }
128253      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
128254      sqlite3VdbeChangeP5(v, OE_Abort);
128255    }else
128256#endif
128257    {
128258      int count = (pParse->nested==0);    /* True to count changes */
128259      sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
128260          iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
128261    }
128262
128263    /* End of the loop over all rowids/primary-keys. */
128264    if( eOnePass!=ONEPASS_OFF ){
128265      sqlite3VdbeResolveLabel(v, addrBypass);
128266      sqlite3WhereEnd(pWInfo);
128267    }else if( pPk ){
128268      sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
128269      sqlite3VdbeJumpHere(v, addrLoop);
128270    }else{
128271      sqlite3VdbeGoto(v, addrLoop);
128272      sqlite3VdbeJumpHere(v, addrLoop);
128273    }
128274  } /* End non-truncate path */
128275
128276  /* Update the sqlite_sequence table by storing the content of the
128277  ** maximum rowid counter values recorded while inserting into
128278  ** autoincrement tables.
128279  */
128280  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
128281    sqlite3AutoincrementEnd(pParse);
128282  }
128283
128284  /* Return the number of rows that were deleted. If this routine is
128285  ** generating code because of a call to sqlite3NestedParse(), do not
128286  ** invoke the callback function.
128287  */
128288  if( memCnt ){
128289    sqlite3CodeChangeCount(v, memCnt, "rows deleted");
128290  }
128291
128292delete_from_cleanup:
128293  sqlite3AuthContextPop(&sContext);
128294  sqlite3SrcListDelete(db, pTabList);
128295  sqlite3ExprDelete(db, pWhere);
128296#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
128297  sqlite3ExprListDelete(db, pOrderBy);
128298  sqlite3ExprDelete(db, pLimit);
128299#endif
128300  if( aToOpen ) sqlite3DbNNFreeNN(db, aToOpen);
128301  return;
128302}
128303/* Make sure "isView" and other macros defined above are undefined. Otherwise
128304** they may interfere with compilation of other functions in this file
128305** (or in another file, if this file becomes part of the amalgamation).  */
128306#ifdef isView
128307 #undef isView
128308#endif
128309#ifdef pTrigger
128310 #undef pTrigger
128311#endif
128312
128313/*
128314** This routine generates VDBE code that causes a single row of a
128315** single table to be deleted.  Both the original table entry and
128316** all indices are removed.
128317**
128318** Preconditions:
128319**
128320**   1.  iDataCur is an open cursor on the btree that is the canonical data
128321**       store for the table.  (This will be either the table itself,
128322**       in the case of a rowid table, or the PRIMARY KEY index in the case
128323**       of a WITHOUT ROWID table.)
128324**
128325**   2.  Read/write cursors for all indices of pTab must be open as
128326**       cursor number iIdxCur+i for the i-th index.
128327**
128328**   3.  The primary key for the row to be deleted must be stored in a
128329**       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
128330**       that a search record formed from OP_MakeRecord is contained in the
128331**       single memory location iPk.
128332**
128333** eMode:
128334**   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
128335**   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
128336**   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
128337**   then this function must seek iDataCur to the entry identified by iPk
128338**   and nPk before reading from it.
128339**
128340**   If eMode is ONEPASS_MULTI, then this call is being made as part
128341**   of a ONEPASS delete that affects multiple rows. In this case, if
128342**   iIdxNoSeek is a valid cursor number (>=0) and is not the same as
128343**   iDataCur, then its position should be preserved following the delete
128344**   operation. Or, if iIdxNoSeek is not a valid cursor number, the
128345**   position of iDataCur should be preserved instead.
128346**
128347** iIdxNoSeek:
128348**   If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
128349**   then it identifies an index cursor (from within array of cursors
128350**   starting at iIdxCur) that already points to the index entry to be deleted.
128351**   Except, this optimization is disabled if there are BEFORE triggers since
128352**   the trigger body might have moved the cursor.
128353*/
128354SQLITE_PRIVATE void sqlite3GenerateRowDelete(
128355  Parse *pParse,     /* Parsing context */
128356  Table *pTab,       /* Table containing the row to be deleted */
128357  Trigger *pTrigger, /* List of triggers to (potentially) fire */
128358  int iDataCur,      /* Cursor from which column data is extracted */
128359  int iIdxCur,       /* First index cursor */
128360  int iPk,           /* First memory cell containing the PRIMARY KEY */
128361  i16 nPk,           /* Number of PRIMARY KEY memory cells */
128362  u8 count,          /* If non-zero, increment the row change counter */
128363  u8 onconf,         /* Default ON CONFLICT policy for triggers */
128364  u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
128365  int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
128366){
128367  Vdbe *v = pParse->pVdbe;        /* Vdbe */
128368  int iOld = 0;                   /* First register in OLD.* array */
128369  int iLabel;                     /* Label resolved to end of generated code */
128370  u8 opSeek;                      /* Seek opcode */
128371
128372  /* Vdbe is guaranteed to have been allocated by this stage. */
128373  assert( v );
128374  VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
128375                         iDataCur, iIdxCur, iPk, (int)nPk));
128376
128377  /* Seek cursor iCur to the row to delete. If this row no longer exists
128378  ** (this can happen if a trigger program has already deleted it), do
128379  ** not attempt to delete it or fire any DELETE triggers.  */
128380  iLabel = sqlite3VdbeMakeLabel(pParse);
128381  opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
128382  if( eMode==ONEPASS_OFF ){
128383    sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
128384    VdbeCoverageIf(v, opSeek==OP_NotExists);
128385    VdbeCoverageIf(v, opSeek==OP_NotFound);
128386  }
128387
128388  /* If there are any triggers to fire, allocate a range of registers to
128389  ** use for the old.* references in the triggers.  */
128390  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
128391    u32 mask;                     /* Mask of OLD.* columns in use */
128392    int iCol;                     /* Iterator used while populating OLD.* */
128393    int addrStart;                /* Start of BEFORE trigger programs */
128394
128395    /* TODO: Could use temporary registers here. Also could attempt to
128396    ** avoid copying the contents of the rowid register.  */
128397    mask = sqlite3TriggerColmask(
128398        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
128399    );
128400    mask |= sqlite3FkOldmask(pParse, pTab);
128401    iOld = pParse->nMem+1;
128402    pParse->nMem += (1 + pTab->nCol);
128403
128404    /* Populate the OLD.* pseudo-table register array. These values will be
128405    ** used by any BEFORE and AFTER triggers that exist.  */
128406    sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
128407    for(iCol=0; iCol<pTab->nCol; iCol++){
128408      testcase( mask!=0xffffffff && iCol==31 );
128409      testcase( mask!=0xffffffff && iCol==32 );
128410      if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
128411        int kk = sqlite3TableColumnToStorage(pTab, iCol);
128412        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+kk+1);
128413      }
128414    }
128415
128416    /* Invoke BEFORE DELETE trigger programs. */
128417    addrStart = sqlite3VdbeCurrentAddr(v);
128418    sqlite3CodeRowTrigger(pParse, pTrigger,
128419        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
128420    );
128421
128422    /* If any BEFORE triggers were coded, then seek the cursor to the
128423    ** row to be deleted again. It may be that the BEFORE triggers moved
128424    ** the cursor or already deleted the row that the cursor was
128425    ** pointing to.
128426    **
128427    ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
128428    ** may have moved that cursor.
128429    */
128430    if( addrStart<sqlite3VdbeCurrentAddr(v) ){
128431      sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
128432      VdbeCoverageIf(v, opSeek==OP_NotExists);
128433      VdbeCoverageIf(v, opSeek==OP_NotFound);
128434      testcase( iIdxNoSeek>=0 );
128435      iIdxNoSeek = -1;
128436    }
128437
128438    /* Do FK processing. This call checks that any FK constraints that
128439    ** refer to this table (i.e. constraints attached to other tables)
128440    ** are not violated by deleting this row.  */
128441    sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
128442  }
128443
128444  /* Delete the index and table entries. Skip this step if pTab is really
128445  ** a view (in which case the only effect of the DELETE statement is to
128446  ** fire the INSTEAD OF triggers).
128447  **
128448  ** If variable 'count' is non-zero, then this OP_Delete instruction should
128449  ** invoke the update-hook. The pre-update-hook, on the other hand should
128450  ** be invoked unless table pTab is a system table. The difference is that
128451  ** the update-hook is not invoked for rows removed by REPLACE, but the
128452  ** pre-update-hook is.
128453  */
128454  if( !IsView(pTab) ){
128455    u8 p5 = 0;
128456    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
128457    sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
128458    if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
128459      sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
128460    }
128461    if( eMode!=ONEPASS_OFF ){
128462      sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
128463    }
128464    if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
128465      sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
128466    }
128467    if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
128468    sqlite3VdbeChangeP5(v, p5);
128469  }
128470
128471  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
128472  ** handle rows (possibly in other tables) that refer via a foreign key
128473  ** to the row just deleted. */
128474  sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
128475
128476  /* Invoke AFTER DELETE trigger programs. */
128477  if( pTrigger ){
128478    sqlite3CodeRowTrigger(pParse, pTrigger,
128479        TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
128480    );
128481  }
128482
128483  /* Jump here if the row had already been deleted before any BEFORE
128484  ** trigger programs were invoked. Or if a trigger program throws a
128485  ** RAISE(IGNORE) exception.  */
128486  sqlite3VdbeResolveLabel(v, iLabel);
128487  VdbeModuleComment((v, "END: GenRowDel()"));
128488}
128489
128490/*
128491** This routine generates VDBE code that causes the deletion of all
128492** index entries associated with a single row of a single table, pTab
128493**
128494** Preconditions:
128495**
128496**   1.  A read/write cursor "iDataCur" must be open on the canonical storage
128497**       btree for the table pTab.  (This will be either the table itself
128498**       for rowid tables or to the primary key index for WITHOUT ROWID
128499**       tables.)
128500**
128501**   2.  Read/write cursors for all indices of pTab must be open as
128502**       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
128503**       index is the 0-th index.)
128504**
128505**   3.  The "iDataCur" cursor must be already be positioned on the row
128506**       that is to be deleted.
128507*/
128508SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
128509  Parse *pParse,     /* Parsing and code generating context */
128510  Table *pTab,       /* Table containing the row to be deleted */
128511  int iDataCur,      /* Cursor of table holding data. */
128512  int iIdxCur,       /* First index cursor */
128513  int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
128514  int iIdxNoSeek     /* Do not delete from this cursor */
128515){
128516  int i;             /* Index loop counter */
128517  int r1 = -1;       /* Register holding an index key */
128518  int iPartIdxLabel; /* Jump destination for skipping partial index entries */
128519  Index *pIdx;       /* Current index */
128520  Index *pPrior = 0; /* Prior index */
128521  Vdbe *v;           /* The prepared statement under construction */
128522  Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
128523
128524  v = pParse->pVdbe;
128525  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
128526  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
128527    assert( iIdxCur+i!=iDataCur || pPk==pIdx );
128528    if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
128529    if( pIdx==pPk ) continue;
128530    if( iIdxCur+i==iIdxNoSeek ) continue;
128531    VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
128532    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
128533        &iPartIdxLabel, pPrior, r1);
128534    sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
128535        pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
128536    sqlite3VdbeChangeP5(v, 1);  /* Cause IdxDelete to error if no entry found */
128537    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
128538    pPrior = pIdx;
128539  }
128540}
128541
128542/*
128543** Generate code that will assemble an index key and stores it in register
128544** regOut.  The key with be for index pIdx which is an index on pTab.
128545** iCur is the index of a cursor open on the pTab table and pointing to
128546** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
128547** iCur must be the cursor of the PRIMARY KEY index.
128548**
128549** Return a register number which is the first in a block of
128550** registers that holds the elements of the index key.  The
128551** block of registers has already been deallocated by the time
128552** this routine returns.
128553**
128554** If *piPartIdxLabel is not NULL, fill it in with a label and jump
128555** to that label if pIdx is a partial index that should be skipped.
128556** The label should be resolved using sqlite3ResolvePartIdxLabel().
128557** A partial index should be skipped if its WHERE clause evaluates
128558** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
128559** will be set to zero which is an empty label that is ignored by
128560** sqlite3ResolvePartIdxLabel().
128561**
128562** The pPrior and regPrior parameters are used to implement a cache to
128563** avoid unnecessary register loads.  If pPrior is not NULL, then it is
128564** a pointer to a different index for which an index key has just been
128565** computed into register regPrior.  If the current pIdx index is generating
128566** its key into the same sequence of registers and if pPrior and pIdx share
128567** a column in common, then the register corresponding to that column already
128568** holds the correct value and the loading of that register is skipped.
128569** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
128570** on a table with multiple indices, and especially with the ROWID or
128571** PRIMARY KEY columns of the index.
128572*/
128573SQLITE_PRIVATE int sqlite3GenerateIndexKey(
128574  Parse *pParse,       /* Parsing context */
128575  Index *pIdx,         /* The index for which to generate a key */
128576  int iDataCur,        /* Cursor number from which to take column data */
128577  int regOut,          /* Put the new key into this register if not 0 */
128578  int prefixOnly,      /* Compute only a unique prefix of the key */
128579  int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
128580  Index *pPrior,       /* Previously generated index key */
128581  int regPrior         /* Register holding previous generated key */
128582){
128583  Vdbe *v = pParse->pVdbe;
128584  int j;
128585  int regBase;
128586  int nCol;
128587
128588  if( piPartIdxLabel ){
128589    if( pIdx->pPartIdxWhere ){
128590      *piPartIdxLabel = sqlite3VdbeMakeLabel(pParse);
128591      pParse->iSelfTab = iDataCur + 1;
128592      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
128593                            SQLITE_JUMPIFNULL);
128594      pParse->iSelfTab = 0;
128595      pPrior = 0; /* Ticket a9efb42811fa41ee 2019-11-02;
128596                  ** pPartIdxWhere may have corrupted regPrior registers */
128597    }else{
128598      *piPartIdxLabel = 0;
128599    }
128600  }
128601  nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
128602  regBase = sqlite3GetTempRange(pParse, nCol);
128603  if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
128604  for(j=0; j<nCol; j++){
128605    if( pPrior
128606     && pPrior->aiColumn[j]==pIdx->aiColumn[j]
128607     && pPrior->aiColumn[j]!=XN_EXPR
128608    ){
128609      /* This column was already computed by the previous index */
128610      continue;
128611    }
128612    sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
128613    if( pIdx->aiColumn[j]>=0 ){
128614      /* If the column affinity is REAL but the number is an integer, then it
128615      ** might be stored in the table as an integer (using a compact
128616      ** representation) then converted to REAL by an OP_RealAffinity opcode.
128617      ** But we are getting ready to store this value back into an index, where
128618      ** it should be converted by to INTEGER again.  So omit the
128619      ** OP_RealAffinity opcode if it is present */
128620      sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
128621    }
128622  }
128623  if( regOut ){
128624    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
128625  }
128626  sqlite3ReleaseTempRange(pParse, regBase, nCol);
128627  return regBase;
128628}
128629
128630/*
128631** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
128632** because it was a partial index, then this routine should be called to
128633** resolve that label.
128634*/
128635SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
128636  if( iLabel ){
128637    sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
128638  }
128639}
128640
128641/************** End of delete.c **********************************************/
128642/************** Begin file func.c ********************************************/
128643/*
128644** 2002 February 23
128645**
128646** The author disclaims copyright to this source code.  In place of
128647** a legal notice, here is a blessing:
128648**
128649**    May you do good and not evil.
128650**    May you find forgiveness for yourself and forgive others.
128651**    May you share freely, never taking more than you give.
128652**
128653*************************************************************************
128654** This file contains the C-language implementations for many of the SQL
128655** functions of SQLite.  (Some function, and in particular the date and
128656** time functions, are implemented separately.)
128657*/
128658/* #include "sqliteInt.h" */
128659/* #include <stdlib.h> */
128660/* #include <assert.h> */
128661#ifndef SQLITE_OMIT_FLOATING_POINT
128662/* #include <math.h> */
128663#endif
128664/* #include "vdbeInt.h" */
128665
128666/*
128667** Return the collating function associated with a function.
128668*/
128669static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
128670  VdbeOp *pOp;
128671  assert( context->pVdbe!=0 );
128672  pOp = &context->pVdbe->aOp[context->iOp-1];
128673  assert( pOp->opcode==OP_CollSeq );
128674  assert( pOp->p4type==P4_COLLSEQ );
128675  return pOp->p4.pColl;
128676}
128677
128678/*
128679** Indicate that the accumulator load should be skipped on this
128680** iteration of the aggregate loop.
128681*/
128682static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
128683  assert( context->isError<=0 );
128684  context->isError = -1;
128685  context->skipFlag = 1;
128686}
128687
128688/*
128689** Implementation of the non-aggregate min() and max() functions
128690*/
128691static void minmaxFunc(
128692  sqlite3_context *context,
128693  int argc,
128694  sqlite3_value **argv
128695){
128696  int i;
128697  int mask;    /* 0 for min() or 0xffffffff for max() */
128698  int iBest;
128699  CollSeq *pColl;
128700
128701  assert( argc>1 );
128702  mask = sqlite3_user_data(context)==0 ? 0 : -1;
128703  pColl = sqlite3GetFuncCollSeq(context);
128704  assert( pColl );
128705  assert( mask==-1 || mask==0 );
128706  iBest = 0;
128707  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
128708  for(i=1; i<argc; i++){
128709    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
128710    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
128711      testcase( mask==0 );
128712      iBest = i;
128713    }
128714  }
128715  sqlite3_result_value(context, argv[iBest]);
128716}
128717
128718/*
128719** Return the type of the argument.
128720*/
128721static void typeofFunc(
128722  sqlite3_context *context,
128723  int NotUsed,
128724  sqlite3_value **argv
128725){
128726  static const char *azType[] = { "integer", "real", "text", "blob", "null" };
128727  int i = sqlite3_value_type(argv[0]) - 1;
128728  UNUSED_PARAMETER(NotUsed);
128729  assert( i>=0 && i<ArraySize(azType) );
128730  assert( SQLITE_INTEGER==1 );
128731  assert( SQLITE_FLOAT==2 );
128732  assert( SQLITE_TEXT==3 );
128733  assert( SQLITE_BLOB==4 );
128734  assert( SQLITE_NULL==5 );
128735  /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
128736  ** the datatype code for the initial datatype of the sqlite3_value object
128737  ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
128738  ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
128739  sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
128740}
128741
128742/* subtype(X)
128743**
128744** Return the subtype of X
128745*/
128746static void subtypeFunc(
128747  sqlite3_context *context,
128748  int argc,
128749  sqlite3_value **argv
128750){
128751  UNUSED_PARAMETER(argc);
128752  sqlite3_result_int(context, sqlite3_value_subtype(argv[0]));
128753}
128754
128755/*
128756** Implementation of the length() function
128757*/
128758static void lengthFunc(
128759  sqlite3_context *context,
128760  int argc,
128761  sqlite3_value **argv
128762){
128763  assert( argc==1 );
128764  UNUSED_PARAMETER(argc);
128765  switch( sqlite3_value_type(argv[0]) ){
128766    case SQLITE_BLOB:
128767    case SQLITE_INTEGER:
128768    case SQLITE_FLOAT: {
128769      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
128770      break;
128771    }
128772    case SQLITE_TEXT: {
128773      const unsigned char *z = sqlite3_value_text(argv[0]);
128774      const unsigned char *z0;
128775      unsigned char c;
128776      if( z==0 ) return;
128777      z0 = z;
128778      while( (c = *z)!=0 ){
128779        z++;
128780        if( c>=0xc0 ){
128781          while( (*z & 0xc0)==0x80 ){ z++; z0++; }
128782        }
128783      }
128784      sqlite3_result_int(context, (int)(z-z0));
128785      break;
128786    }
128787    default: {
128788      sqlite3_result_null(context);
128789      break;
128790    }
128791  }
128792}
128793
128794/*
128795** Implementation of the octet_length() function
128796*/
128797static void bytelengthFunc(
128798  sqlite3_context *context,
128799  int argc,
128800  sqlite3_value **argv
128801){
128802  assert( argc==1 );
128803  UNUSED_PARAMETER(argc);
128804  switch( sqlite3_value_type(argv[0]) ){
128805    case SQLITE_BLOB: {
128806      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
128807      break;
128808    }
128809    case SQLITE_INTEGER:
128810    case SQLITE_FLOAT: {
128811      i64 m = sqlite3_context_db_handle(context)->enc<=SQLITE_UTF8 ? 1 : 2;
128812      sqlite3_result_int64(context, sqlite3_value_bytes(argv[0])*m);
128813      break;
128814    }
128815    case SQLITE_TEXT: {
128816      if( sqlite3_value_encoding(argv[0])<=SQLITE_UTF8 ){
128817        sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
128818      }else{
128819        sqlite3_result_int(context, sqlite3_value_bytes16(argv[0]));
128820      }
128821      break;
128822    }
128823    default: {
128824      sqlite3_result_null(context);
128825      break;
128826    }
128827  }
128828}
128829
128830/*
128831** Implementation of the abs() function.
128832**
128833** IMP: R-23979-26855 The abs(X) function returns the absolute value of
128834** the numeric argument X.
128835*/
128836static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
128837  assert( argc==1 );
128838  UNUSED_PARAMETER(argc);
128839  switch( sqlite3_value_type(argv[0]) ){
128840    case SQLITE_INTEGER: {
128841      i64 iVal = sqlite3_value_int64(argv[0]);
128842      if( iVal<0 ){
128843        if( iVal==SMALLEST_INT64 ){
128844          /* IMP: R-31676-45509 If X is the integer -9223372036854775808
128845          ** then abs(X) throws an integer overflow error since there is no
128846          ** equivalent positive 64-bit two complement value. */
128847          sqlite3_result_error(context, "integer overflow", -1);
128848          return;
128849        }
128850        iVal = -iVal;
128851      }
128852      sqlite3_result_int64(context, iVal);
128853      break;
128854    }
128855    case SQLITE_NULL: {
128856      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
128857      sqlite3_result_null(context);
128858      break;
128859    }
128860    default: {
128861      /* Because sqlite3_value_double() returns 0.0 if the argument is not
128862      ** something that can be converted into a number, we have:
128863      ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
128864      ** that cannot be converted to a numeric value.
128865      */
128866      double rVal = sqlite3_value_double(argv[0]);
128867      if( rVal<0 ) rVal = -rVal;
128868      sqlite3_result_double(context, rVal);
128869      break;
128870    }
128871  }
128872}
128873
128874/*
128875** Implementation of the instr() function.
128876**
128877** instr(haystack,needle) finds the first occurrence of needle
128878** in haystack and returns the number of previous characters plus 1,
128879** or 0 if needle does not occur within haystack.
128880**
128881** If both haystack and needle are BLOBs, then the result is one more than
128882** the number of bytes in haystack prior to the first occurrence of needle,
128883** or 0 if needle never occurs in haystack.
128884*/
128885static void instrFunc(
128886  sqlite3_context *context,
128887  int argc,
128888  sqlite3_value **argv
128889){
128890  const unsigned char *zHaystack;
128891  const unsigned char *zNeedle;
128892  int nHaystack;
128893  int nNeedle;
128894  int typeHaystack, typeNeedle;
128895  int N = 1;
128896  int isText;
128897  unsigned char firstChar;
128898  sqlite3_value *pC1 = 0;
128899  sqlite3_value *pC2 = 0;
128900
128901  UNUSED_PARAMETER(argc);
128902  typeHaystack = sqlite3_value_type(argv[0]);
128903  typeNeedle = sqlite3_value_type(argv[1]);
128904  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
128905  nHaystack = sqlite3_value_bytes(argv[0]);
128906  nNeedle = sqlite3_value_bytes(argv[1]);
128907  if( nNeedle>0 ){
128908    if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
128909      zHaystack = sqlite3_value_blob(argv[0]);
128910      zNeedle = sqlite3_value_blob(argv[1]);
128911      isText = 0;
128912    }else if( typeHaystack!=SQLITE_BLOB && typeNeedle!=SQLITE_BLOB ){
128913      zHaystack = sqlite3_value_text(argv[0]);
128914      zNeedle = sqlite3_value_text(argv[1]);
128915      isText = 1;
128916    }else{
128917      pC1 = sqlite3_value_dup(argv[0]);
128918      zHaystack = sqlite3_value_text(pC1);
128919      if( zHaystack==0 ) goto endInstrOOM;
128920      nHaystack = sqlite3_value_bytes(pC1);
128921      pC2 = sqlite3_value_dup(argv[1]);
128922      zNeedle = sqlite3_value_text(pC2);
128923      if( zNeedle==0 ) goto endInstrOOM;
128924      nNeedle = sqlite3_value_bytes(pC2);
128925      isText = 1;
128926    }
128927    if( zNeedle==0 || (nHaystack && zHaystack==0) ) goto endInstrOOM;
128928    firstChar = zNeedle[0];
128929    while( nNeedle<=nHaystack
128930       && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0)
128931    ){
128932      N++;
128933      do{
128934        nHaystack--;
128935        zHaystack++;
128936      }while( isText && (zHaystack[0]&0xc0)==0x80 );
128937    }
128938    if( nNeedle>nHaystack ) N = 0;
128939  }
128940  sqlite3_result_int(context, N);
128941endInstr:
128942  sqlite3_value_free(pC1);
128943  sqlite3_value_free(pC2);
128944  return;
128945endInstrOOM:
128946  sqlite3_result_error_nomem(context);
128947  goto endInstr;
128948}
128949
128950/*
128951** Implementation of the printf() (a.k.a. format()) SQL function.
128952*/
128953static void printfFunc(
128954  sqlite3_context *context,
128955  int argc,
128956  sqlite3_value **argv
128957){
128958  PrintfArguments x;
128959  StrAccum str;
128960  const char *zFormat;
128961  int n;
128962  sqlite3 *db = sqlite3_context_db_handle(context);
128963
128964  if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
128965    x.nArg = argc-1;
128966    x.nUsed = 0;
128967    x.apArg = argv+1;
128968    sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
128969    str.printfFlags = SQLITE_PRINTF_SQLFUNC;
128970    sqlite3_str_appendf(&str, zFormat, &x);
128971    n = str.nChar;
128972    sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
128973                        SQLITE_DYNAMIC);
128974  }
128975}
128976
128977/*
128978** Implementation of the substr() function.
128979**
128980** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
128981** p1 is 1-indexed.  So substr(x,1,1) returns the first character
128982** of x.  If x is text, then we actually count UTF-8 characters.
128983** If x is a blob, then we count bytes.
128984**
128985** If p1 is negative, then we begin abs(p1) from the end of x[].
128986**
128987** If p2 is negative, return the p2 characters preceding p1.
128988*/
128989static void substrFunc(
128990  sqlite3_context *context,
128991  int argc,
128992  sqlite3_value **argv
128993){
128994  const unsigned char *z;
128995  const unsigned char *z2;
128996  int len;
128997  int p0type;
128998  i64 p1, p2;
128999  int negP2 = 0;
129000
129001  assert( argc==3 || argc==2 );
129002  if( sqlite3_value_type(argv[1])==SQLITE_NULL
129003   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
129004  ){
129005    return;
129006  }
129007  p0type = sqlite3_value_type(argv[0]);
129008  p1 = sqlite3_value_int(argv[1]);
129009  if( p0type==SQLITE_BLOB ){
129010    len = sqlite3_value_bytes(argv[0]);
129011    z = sqlite3_value_blob(argv[0]);
129012    if( z==0 ) return;
129013    assert( len==sqlite3_value_bytes(argv[0]) );
129014  }else{
129015    z = sqlite3_value_text(argv[0]);
129016    if( z==0 ) return;
129017    len = 0;
129018    if( p1<0 ){
129019      for(z2=z; *z2; len++){
129020        SQLITE_SKIP_UTF8(z2);
129021      }
129022    }
129023  }
129024#ifdef SQLITE_SUBSTR_COMPATIBILITY
129025  /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
129026  ** as substr(X,1,N) - it returns the first N characters of X.  This
129027  ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
129028  ** from 2009-02-02 for compatibility of applications that exploited the
129029  ** old buggy behavior. */
129030  if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
129031#endif
129032  if( argc==3 ){
129033    p2 = sqlite3_value_int(argv[2]);
129034    if( p2<0 ){
129035      p2 = -p2;
129036      negP2 = 1;
129037    }
129038  }else{
129039    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
129040  }
129041  if( p1<0 ){
129042    p1 += len;
129043    if( p1<0 ){
129044      p2 += p1;
129045      if( p2<0 ) p2 = 0;
129046      p1 = 0;
129047    }
129048  }else if( p1>0 ){
129049    p1--;
129050  }else if( p2>0 ){
129051    p2--;
129052  }
129053  if( negP2 ){
129054    p1 -= p2;
129055    if( p1<0 ){
129056      p2 += p1;
129057      p1 = 0;
129058    }
129059  }
129060  assert( p1>=0 && p2>=0 );
129061  if( p0type!=SQLITE_BLOB ){
129062    while( *z && p1 ){
129063      SQLITE_SKIP_UTF8(z);
129064      p1--;
129065    }
129066    for(z2=z; *z2 && p2; p2--){
129067      SQLITE_SKIP_UTF8(z2);
129068    }
129069    sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
129070                          SQLITE_UTF8);
129071  }else{
129072    if( p1+p2>len ){
129073      p2 = len-p1;
129074      if( p2<0 ) p2 = 0;
129075    }
129076    sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
129077  }
129078}
129079
129080/*
129081** Implementation of the round() function
129082*/
129083#ifndef SQLITE_OMIT_FLOATING_POINT
129084static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
129085  int n = 0;
129086  double r;
129087  char *zBuf;
129088  assert( argc==1 || argc==2 );
129089  if( argc==2 ){
129090    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
129091    n = sqlite3_value_int(argv[1]);
129092    if( n>30 ) n = 30;
129093    if( n<0 ) n = 0;
129094  }
129095  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
129096  r = sqlite3_value_double(argv[0]);
129097  /* If Y==0 and X will fit in a 64-bit int,
129098  ** handle the rounding directly,
129099  ** otherwise use printf.
129100  */
129101  if( r<-4503599627370496.0 || r>+4503599627370496.0 ){
129102    /* The value has no fractional part so there is nothing to round */
129103  }else if( n==0 ){
129104    r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5)));
129105  }else{
129106    zBuf = sqlite3_mprintf("%!.*f",n,r);
129107    if( zBuf==0 ){
129108      sqlite3_result_error_nomem(context);
129109      return;
129110    }
129111    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
129112    sqlite3_free(zBuf);
129113  }
129114  sqlite3_result_double(context, r);
129115}
129116#endif
129117
129118/*
129119** Allocate nByte bytes of space using sqlite3Malloc(). If the
129120** allocation fails, call sqlite3_result_error_nomem() to notify
129121** the database handle that malloc() has failed and return NULL.
129122** If nByte is larger than the maximum string or blob length, then
129123** raise an SQLITE_TOOBIG exception and return NULL.
129124*/
129125static void *contextMalloc(sqlite3_context *context, i64 nByte){
129126  char *z;
129127  sqlite3 *db = sqlite3_context_db_handle(context);
129128  assert( nByte>0 );
129129  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
129130  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
129131  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
129132    sqlite3_result_error_toobig(context);
129133    z = 0;
129134  }else{
129135    z = sqlite3Malloc(nByte);
129136    if( !z ){
129137      sqlite3_result_error_nomem(context);
129138    }
129139  }
129140  return z;
129141}
129142
129143/*
129144** Implementation of the upper() and lower() SQL functions.
129145*/
129146static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
129147  char *z1;
129148  const char *z2;
129149  int i, n;
129150  UNUSED_PARAMETER(argc);
129151  z2 = (char*)sqlite3_value_text(argv[0]);
129152  n = sqlite3_value_bytes(argv[0]);
129153  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
129154  assert( z2==(char*)sqlite3_value_text(argv[0]) );
129155  if( z2 ){
129156    z1 = contextMalloc(context, ((i64)n)+1);
129157    if( z1 ){
129158      for(i=0; i<n; i++){
129159        z1[i] = (char)sqlite3Toupper(z2[i]);
129160      }
129161      sqlite3_result_text(context, z1, n, sqlite3_free);
129162    }
129163  }
129164}
129165static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
129166  char *z1;
129167  const char *z2;
129168  int i, n;
129169  UNUSED_PARAMETER(argc);
129170  z2 = (char*)sqlite3_value_text(argv[0]);
129171  n = sqlite3_value_bytes(argv[0]);
129172  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
129173  assert( z2==(char*)sqlite3_value_text(argv[0]) );
129174  if( z2 ){
129175    z1 = contextMalloc(context, ((i64)n)+1);
129176    if( z1 ){
129177      for(i=0; i<n; i++){
129178        z1[i] = sqlite3Tolower(z2[i]);
129179      }
129180      sqlite3_result_text(context, z1, n, sqlite3_free);
129181    }
129182  }
129183}
129184
129185/*
129186** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
129187** as VDBE code so that unused argument values do not have to be computed.
129188** However, we still need some kind of function implementation for this
129189** routines in the function table.  The noopFunc macro provides this.
129190** noopFunc will never be called so it doesn't matter what the implementation
129191** is.  We might as well use the "version()" function as a substitute.
129192*/
129193#define noopFunc versionFunc   /* Substitute function - never called */
129194
129195/*
129196** Implementation of random().  Return a random integer.
129197*/
129198static void randomFunc(
129199  sqlite3_context *context,
129200  int NotUsed,
129201  sqlite3_value **NotUsed2
129202){
129203  sqlite_int64 r;
129204  UNUSED_PARAMETER2(NotUsed, NotUsed2);
129205  sqlite3_randomness(sizeof(r), &r);
129206  if( r<0 ){
129207    /* We need to prevent a random number of 0x8000000000000000
129208    ** (or -9223372036854775808) since when you do abs() of that
129209    ** number of you get the same value back again.  To do this
129210    ** in a way that is testable, mask the sign bit off of negative
129211    ** values, resulting in a positive value.  Then take the
129212    ** 2s complement of that positive value.  The end result can
129213    ** therefore be no less than -9223372036854775807.
129214    */
129215    r = -(r & LARGEST_INT64);
129216  }
129217  sqlite3_result_int64(context, r);
129218}
129219
129220/*
129221** Implementation of randomblob(N).  Return a random blob
129222** that is N bytes long.
129223*/
129224static void randomBlob(
129225  sqlite3_context *context,
129226  int argc,
129227  sqlite3_value **argv
129228){
129229  sqlite3_int64 n;
129230  unsigned char *p;
129231  assert( argc==1 );
129232  UNUSED_PARAMETER(argc);
129233  n = sqlite3_value_int64(argv[0]);
129234  if( n<1 ){
129235    n = 1;
129236  }
129237  p = contextMalloc(context, n);
129238  if( p ){
129239    sqlite3_randomness(n, p);
129240    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
129241  }
129242}
129243
129244/*
129245** Implementation of the last_insert_rowid() SQL function.  The return
129246** value is the same as the sqlite3_last_insert_rowid() API function.
129247*/
129248static void last_insert_rowid(
129249  sqlite3_context *context,
129250  int NotUsed,
129251  sqlite3_value **NotUsed2
129252){
129253  sqlite3 *db = sqlite3_context_db_handle(context);
129254  UNUSED_PARAMETER2(NotUsed, NotUsed2);
129255  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
129256  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
129257  ** function. */
129258  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
129259}
129260
129261/*
129262** Implementation of the changes() SQL function.
129263**
129264** IMP: R-32760-32347 The changes() SQL function is a wrapper
129265** around the sqlite3_changes64() C/C++ function and hence follows the
129266** same rules for counting changes.
129267*/
129268static void changes(
129269  sqlite3_context *context,
129270  int NotUsed,
129271  sqlite3_value **NotUsed2
129272){
129273  sqlite3 *db = sqlite3_context_db_handle(context);
129274  UNUSED_PARAMETER2(NotUsed, NotUsed2);
129275  sqlite3_result_int64(context, sqlite3_changes64(db));
129276}
129277
129278/*
129279** Implementation of the total_changes() SQL function.  The return value is
129280** the same as the sqlite3_total_changes64() API function.
129281*/
129282static void total_changes(
129283  sqlite3_context *context,
129284  int NotUsed,
129285  sqlite3_value **NotUsed2
129286){
129287  sqlite3 *db = sqlite3_context_db_handle(context);
129288  UNUSED_PARAMETER2(NotUsed, NotUsed2);
129289  /* IMP: R-11217-42568 This function is a wrapper around the
129290  ** sqlite3_total_changes64() C/C++ interface. */
129291  sqlite3_result_int64(context, sqlite3_total_changes64(db));
129292}
129293
129294/*
129295** A structure defining how to do GLOB-style comparisons.
129296*/
129297struct compareInfo {
129298  u8 matchAll;          /* "*" or "%" */
129299  u8 matchOne;          /* "?" or "_" */
129300  u8 matchSet;          /* "[" or 0 */
129301  u8 noCase;            /* true to ignore case differences */
129302};
129303
129304/*
129305** For LIKE and GLOB matching on EBCDIC machines, assume that every
129306** character is exactly one byte in size.  Also, provide the Utf8Read()
129307** macro for fast reading of the next character in the common case where
129308** the next character is ASCII.
129309*/
129310#if defined(SQLITE_EBCDIC)
129311# define sqlite3Utf8Read(A)        (*((*A)++))
129312# define Utf8Read(A)               (*(A++))
129313#else
129314# define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
129315#endif
129316
129317static const struct compareInfo globInfo = { '*', '?', '[', 0 };
129318/* The correct SQL-92 behavior is for the LIKE operator to ignore
129319** case.  Thus  'a' LIKE 'A' would be true. */
129320static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
129321/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
129322** is case sensitive causing 'a' LIKE 'A' to be false */
129323static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
129324
129325/*
129326** Possible error returns from patternMatch()
129327*/
129328#define SQLITE_MATCH             0
129329#define SQLITE_NOMATCH           1
129330#define SQLITE_NOWILDCARDMATCH   2
129331
129332/*
129333** Compare two UTF-8 strings for equality where the first string is
129334** a GLOB or LIKE expression.  Return values:
129335**
129336**    SQLITE_MATCH:            Match
129337**    SQLITE_NOMATCH:          No match
129338**    SQLITE_NOWILDCARDMATCH:  No match in spite of having * or % wildcards.
129339**
129340** Globbing rules:
129341**
129342**      '*'       Matches any sequence of zero or more characters.
129343**
129344**      '?'       Matches exactly one character.
129345**
129346**     [...]      Matches one character from the enclosed list of
129347**                characters.
129348**
129349**     [^...]     Matches one character not in the enclosed list.
129350**
129351** With the [...] and [^...] matching, a ']' character can be included
129352** in the list by making it the first character after '[' or '^'.  A
129353** range of characters can be specified using '-'.  Example:
129354** "[a-z]" matches any single lower-case letter.  To match a '-', make
129355** it the last character in the list.
129356**
129357** Like matching rules:
129358**
129359**      '%'       Matches any sequence of zero or more characters
129360**
129361***     '_'       Matches any one character
129362**
129363**      Ec        Where E is the "esc" character and c is any other
129364**                character, including '%', '_', and esc, match exactly c.
129365**
129366** The comments within this routine usually assume glob matching.
129367**
129368** This routine is usually quick, but can be N**2 in the worst case.
129369*/
129370static int patternCompare(
129371  const u8 *zPattern,              /* The glob pattern */
129372  const u8 *zString,               /* The string to compare against the glob */
129373  const struct compareInfo *pInfo, /* Information about how to do the compare */
129374  u32 matchOther                   /* The escape char (LIKE) or '[' (GLOB) */
129375){
129376  u32 c, c2;                       /* Next pattern and input string chars */
129377  u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
129378  u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
129379  u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
129380  const u8 *zEscaped = 0;          /* One past the last escaped input char */
129381
129382  while( (c = Utf8Read(zPattern))!=0 ){
129383    if( c==matchAll ){  /* Match "*" */
129384      /* Skip over multiple "*" characters in the pattern.  If there
129385      ** are also "?" characters, skip those as well, but consume a
129386      ** single character of the input string for each "?" skipped */
129387      while( (c=Utf8Read(zPattern)) == matchAll
129388             || (c == matchOne && matchOne!=0) ){
129389        if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
129390          return SQLITE_NOWILDCARDMATCH;
129391        }
129392      }
129393      if( c==0 ){
129394        return SQLITE_MATCH;   /* "*" at the end of the pattern matches */
129395      }else if( c==matchOther ){
129396        if( pInfo->matchSet==0 ){
129397          c = sqlite3Utf8Read(&zPattern);
129398          if( c==0 ) return SQLITE_NOWILDCARDMATCH;
129399        }else{
129400          /* "[...]" immediately follows the "*".  We have to do a slow
129401          ** recursive search in this case, but it is an unusual case. */
129402          assert( matchOther<0x80 );  /* '[' is a single-byte character */
129403          while( *zString ){
129404            int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
129405            if( bMatch!=SQLITE_NOMATCH ) return bMatch;
129406            SQLITE_SKIP_UTF8(zString);
129407          }
129408          return SQLITE_NOWILDCARDMATCH;
129409        }
129410      }
129411
129412      /* At this point variable c contains the first character of the
129413      ** pattern string past the "*".  Search in the input string for the
129414      ** first matching character and recursively continue the match from
129415      ** that point.
129416      **
129417      ** For a case-insensitive search, set variable cx to be the same as
129418      ** c but in the other case and search the input string for either
129419      ** c or cx.
129420      */
129421      if( c<0x80 ){
129422        char zStop[3];
129423        int bMatch;
129424        if( noCase ){
129425          zStop[0] = sqlite3Toupper(c);
129426          zStop[1] = sqlite3Tolower(c);
129427          zStop[2] = 0;
129428        }else{
129429          zStop[0] = c;
129430          zStop[1] = 0;
129431        }
129432        while(1){
129433          zString += strcspn((const char*)zString, zStop);
129434          if( zString[0]==0 ) break;
129435          zString++;
129436          bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
129437          if( bMatch!=SQLITE_NOMATCH ) return bMatch;
129438        }
129439      }else{
129440        int bMatch;
129441        while( (c2 = Utf8Read(zString))!=0 ){
129442          if( c2!=c ) continue;
129443          bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
129444          if( bMatch!=SQLITE_NOMATCH ) return bMatch;
129445        }
129446      }
129447      return SQLITE_NOWILDCARDMATCH;
129448    }
129449    if( c==matchOther ){
129450      if( pInfo->matchSet==0 ){
129451        c = sqlite3Utf8Read(&zPattern);
129452        if( c==0 ) return SQLITE_NOMATCH;
129453        zEscaped = zPattern;
129454      }else{
129455        u32 prior_c = 0;
129456        int seen = 0;
129457        int invert = 0;
129458        c = sqlite3Utf8Read(&zString);
129459        if( c==0 ) return SQLITE_NOMATCH;
129460        c2 = sqlite3Utf8Read(&zPattern);
129461        if( c2=='^' ){
129462          invert = 1;
129463          c2 = sqlite3Utf8Read(&zPattern);
129464        }
129465        if( c2==']' ){
129466          if( c==']' ) seen = 1;
129467          c2 = sqlite3Utf8Read(&zPattern);
129468        }
129469        while( c2 && c2!=']' ){
129470          if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
129471            c2 = sqlite3Utf8Read(&zPattern);
129472            if( c>=prior_c && c<=c2 ) seen = 1;
129473            prior_c = 0;
129474          }else{
129475            if( c==c2 ){
129476              seen = 1;
129477            }
129478            prior_c = c2;
129479          }
129480          c2 = sqlite3Utf8Read(&zPattern);
129481        }
129482        if( c2==0 || (seen ^ invert)==0 ){
129483          return SQLITE_NOMATCH;
129484        }
129485        continue;
129486      }
129487    }
129488    c2 = Utf8Read(zString);
129489    if( c==c2 ) continue;
129490    if( noCase  && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
129491      continue;
129492    }
129493    if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
129494    return SQLITE_NOMATCH;
129495  }
129496  return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
129497}
129498
129499/*
129500** The sqlite3_strglob() interface.  Return 0 on a match (like strcmp()) and
129501** non-zero if there is no match.
129502*/
129503SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
129504  if( zString==0 ){
129505    return zGlobPattern!=0;
129506  }else if( zGlobPattern==0 ){
129507    return 1;
129508  }else {
129509    return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
129510  }
129511}
129512
129513/*
129514** The sqlite3_strlike() interface.  Return 0 on a match and non-zero for
129515** a miss - like strcmp().
129516*/
129517SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
129518  if( zStr==0 ){
129519    return zPattern!=0;
129520  }else if( zPattern==0 ){
129521    return 1;
129522  }else{
129523    return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
129524  }
129525}
129526
129527/*
129528** Count the number of times that the LIKE operator (or GLOB which is
129529** just a variation of LIKE) gets called.  This is used for testing
129530** only.
129531*/
129532#ifdef SQLITE_TEST
129533SQLITE_API int sqlite3_like_count = 0;
129534#endif
129535
129536
129537/*
129538** Implementation of the like() SQL function.  This function implements
129539** the built-in LIKE operator.  The first argument to the function is the
129540** pattern and the second argument is the string.  So, the SQL statements:
129541**
129542**       A LIKE B
129543**
129544** is implemented as like(B,A).
129545**
129546** This same function (with a different compareInfo structure) computes
129547** the GLOB operator.
129548*/
129549static void likeFunc(
129550  sqlite3_context *context,
129551  int argc,
129552  sqlite3_value **argv
129553){
129554  const unsigned char *zA, *zB;
129555  u32 escape;
129556  int nPat;
129557  sqlite3 *db = sqlite3_context_db_handle(context);
129558  struct compareInfo *pInfo = sqlite3_user_data(context);
129559  struct compareInfo backupInfo;
129560
129561#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
129562  if( sqlite3_value_type(argv[0])==SQLITE_BLOB
129563   || sqlite3_value_type(argv[1])==SQLITE_BLOB
129564  ){
129565#ifdef SQLITE_TEST
129566    sqlite3_like_count++;
129567#endif
129568    sqlite3_result_int(context, 0);
129569    return;
129570  }
129571#endif
129572
129573  /* Limit the length of the LIKE or GLOB pattern to avoid problems
129574  ** of deep recursion and N*N behavior in patternCompare().
129575  */
129576  nPat = sqlite3_value_bytes(argv[0]);
129577  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
129578  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
129579  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
129580    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
129581    return;
129582  }
129583  if( argc==3 ){
129584    /* The escape character string must consist of a single UTF-8 character.
129585    ** Otherwise, return an error.
129586    */
129587    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
129588    if( zEsc==0 ) return;
129589    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
129590      sqlite3_result_error(context,
129591          "ESCAPE expression must be a single character", -1);
129592      return;
129593    }
129594    escape = sqlite3Utf8Read(&zEsc);
129595    if( escape==pInfo->matchAll || escape==pInfo->matchOne ){
129596      memcpy(&backupInfo, pInfo, sizeof(backupInfo));
129597      pInfo = &backupInfo;
129598      if( escape==pInfo->matchAll ) pInfo->matchAll = 0;
129599      if( escape==pInfo->matchOne ) pInfo->matchOne = 0;
129600    }
129601  }else{
129602    escape = pInfo->matchSet;
129603  }
129604  zB = sqlite3_value_text(argv[0]);
129605  zA = sqlite3_value_text(argv[1]);
129606  if( zA && zB ){
129607#ifdef SQLITE_TEST
129608    sqlite3_like_count++;
129609#endif
129610    sqlite3_result_int(context,
129611                      patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
129612  }
129613}
129614
129615/*
129616** Implementation of the NULLIF(x,y) function.  The result is the first
129617** argument if the arguments are different.  The result is NULL if the
129618** arguments are equal to each other.
129619*/
129620static void nullifFunc(
129621  sqlite3_context *context,
129622  int NotUsed,
129623  sqlite3_value **argv
129624){
129625  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
129626  UNUSED_PARAMETER(NotUsed);
129627  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
129628    sqlite3_result_value(context, argv[0]);
129629  }
129630}
129631
129632/*
129633** Implementation of the sqlite_version() function.  The result is the version
129634** of the SQLite library that is running.
129635*/
129636static void versionFunc(
129637  sqlite3_context *context,
129638  int NotUsed,
129639  sqlite3_value **NotUsed2
129640){
129641  UNUSED_PARAMETER2(NotUsed, NotUsed2);
129642  /* IMP: R-48699-48617 This function is an SQL wrapper around the
129643  ** sqlite3_libversion() C-interface. */
129644  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
129645}
129646
129647/*
129648** Implementation of the sqlite_source_id() function. The result is a string
129649** that identifies the particular version of the source code used to build
129650** SQLite.
129651*/
129652static void sourceidFunc(
129653  sqlite3_context *context,
129654  int NotUsed,
129655  sqlite3_value **NotUsed2
129656){
129657  UNUSED_PARAMETER2(NotUsed, NotUsed2);
129658  /* IMP: R-24470-31136 This function is an SQL wrapper around the
129659  ** sqlite3_sourceid() C interface. */
129660  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
129661}
129662
129663/*
129664** Implementation of the sqlite_log() function.  This is a wrapper around
129665** sqlite3_log().  The return value is NULL.  The function exists purely for
129666** its side-effects.
129667*/
129668static void errlogFunc(
129669  sqlite3_context *context,
129670  int argc,
129671  sqlite3_value **argv
129672){
129673  UNUSED_PARAMETER(argc);
129674  UNUSED_PARAMETER(context);
129675  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
129676}
129677
129678/*
129679** Implementation of the sqlite_compileoption_used() function.
129680** The result is an integer that identifies if the compiler option
129681** was used to build SQLite.
129682*/
129683#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
129684static void compileoptionusedFunc(
129685  sqlite3_context *context,
129686  int argc,
129687  sqlite3_value **argv
129688){
129689  const char *zOptName;
129690  assert( argc==1 );
129691  UNUSED_PARAMETER(argc);
129692  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
129693  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
129694  ** function.
129695  */
129696  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
129697    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
129698  }
129699}
129700#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
129701
129702/*
129703** Implementation of the sqlite_compileoption_get() function.
129704** The result is a string that identifies the compiler options
129705** used to build SQLite.
129706*/
129707#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
129708static void compileoptiongetFunc(
129709  sqlite3_context *context,
129710  int argc,
129711  sqlite3_value **argv
129712){
129713  int n;
129714  assert( argc==1 );
129715  UNUSED_PARAMETER(argc);
129716  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
129717  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
129718  */
129719  n = sqlite3_value_int(argv[0]);
129720  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
129721}
129722#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
129723
129724/* Array for converting from half-bytes (nybbles) into ASCII hex
129725** digits. */
129726static const char hexdigits[] = {
129727  '0', '1', '2', '3', '4', '5', '6', '7',
129728  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
129729};
129730
129731/*
129732** Append to pStr text that is the SQL literal representation of the
129733** value contained in pValue.
129734*/
129735SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){
129736  /* As currently implemented, the string must be initially empty.
129737  ** we might relax this requirement in the future, but that will
129738  ** require enhancements to the implementation. */
129739  assert( pStr!=0 && pStr->nChar==0 );
129740
129741  switch( sqlite3_value_type(pValue) ){
129742    case SQLITE_FLOAT: {
129743      double r1, r2;
129744      const char *zVal;
129745      r1 = sqlite3_value_double(pValue);
129746      sqlite3_str_appendf(pStr, "%!0.15g", r1);
129747      zVal = sqlite3_str_value(pStr);
129748      if( zVal ){
129749        sqlite3AtoF(zVal, &r2, pStr->nChar, SQLITE_UTF8);
129750        if( r1!=r2 ){
129751          sqlite3_str_reset(pStr);
129752          sqlite3_str_appendf(pStr, "%!0.20e", r1);
129753        }
129754      }
129755      break;
129756    }
129757    case SQLITE_INTEGER: {
129758      sqlite3_str_appendf(pStr, "%lld", sqlite3_value_int64(pValue));
129759      break;
129760    }
129761    case SQLITE_BLOB: {
129762      char const *zBlob = sqlite3_value_blob(pValue);
129763      i64 nBlob = sqlite3_value_bytes(pValue);
129764      assert( zBlob==sqlite3_value_blob(pValue) ); /* No encoding change */
129765      sqlite3StrAccumEnlarge(pStr, nBlob*2 + 4);
129766      if( pStr->accError==0 ){
129767        char *zText = pStr->zText;
129768        int i;
129769        for(i=0; i<nBlob; i++){
129770          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
129771          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
129772        }
129773        zText[(nBlob*2)+2] = '\'';
129774        zText[(nBlob*2)+3] = '\0';
129775        zText[0] = 'X';
129776        zText[1] = '\'';
129777        pStr->nChar = nBlob*2 + 3;
129778      }
129779      break;
129780    }
129781    case SQLITE_TEXT: {
129782      const unsigned char *zArg = sqlite3_value_text(pValue);
129783      sqlite3_str_appendf(pStr, "%Q", zArg);
129784      break;
129785    }
129786    default: {
129787      assert( sqlite3_value_type(pValue)==SQLITE_NULL );
129788      sqlite3_str_append(pStr, "NULL", 4);
129789      break;
129790    }
129791  }
129792}
129793
129794/*
129795** Implementation of the QUOTE() function.
129796**
129797** The quote(X) function returns the text of an SQL literal which is the
129798** value of its argument suitable for inclusion into an SQL statement.
129799** Strings are surrounded by single-quotes with escapes on interior quotes
129800** as needed. BLOBs are encoded as hexadecimal literals. Strings with
129801** embedded NUL characters cannot be represented as string literals in SQL
129802** and hence the returned string literal is truncated prior to the first NUL.
129803*/
129804static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
129805  sqlite3_str str;
129806  sqlite3 *db = sqlite3_context_db_handle(context);
129807  assert( argc==1 );
129808  UNUSED_PARAMETER(argc);
129809  sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
129810  sqlite3QuoteValue(&str,argv[0]);
129811  sqlite3_result_text(context, sqlite3StrAccumFinish(&str), str.nChar,
129812                      SQLITE_DYNAMIC);
129813  if( str.accError!=SQLITE_OK ){
129814    sqlite3_result_null(context);
129815    sqlite3_result_error_code(context, str.accError);
129816  }
129817}
129818
129819/*
129820** The unicode() function.  Return the integer unicode code-point value
129821** for the first character of the input string.
129822*/
129823static void unicodeFunc(
129824  sqlite3_context *context,
129825  int argc,
129826  sqlite3_value **argv
129827){
129828  const unsigned char *z = sqlite3_value_text(argv[0]);
129829  (void)argc;
129830  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
129831}
129832
129833/*
129834** The char() function takes zero or more arguments, each of which is
129835** an integer.  It constructs a string where each character of the string
129836** is the unicode character for the corresponding integer argument.
129837*/
129838static void charFunc(
129839  sqlite3_context *context,
129840  int argc,
129841  sqlite3_value **argv
129842){
129843  unsigned char *z, *zOut;
129844  int i;
129845  zOut = z = sqlite3_malloc64( argc*4+1 );
129846  if( z==0 ){
129847    sqlite3_result_error_nomem(context);
129848    return;
129849  }
129850  for(i=0; i<argc; i++){
129851    sqlite3_int64 x;
129852    unsigned c;
129853    x = sqlite3_value_int64(argv[i]);
129854    if( x<0 || x>0x10ffff ) x = 0xfffd;
129855    c = (unsigned)(x & 0x1fffff);
129856    if( c<0x00080 ){
129857      *zOut++ = (u8)(c&0xFF);
129858    }else if( c<0x00800 ){
129859      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
129860      *zOut++ = 0x80 + (u8)(c & 0x3F);
129861    }else if( c<0x10000 ){
129862      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
129863      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
129864      *zOut++ = 0x80 + (u8)(c & 0x3F);
129865    }else{
129866      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
129867      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
129868      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
129869      *zOut++ = 0x80 + (u8)(c & 0x3F);
129870    }                                                    \
129871  }
129872  *zOut = 0;
129873  sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
129874}
129875
129876/*
129877** The hex() function.  Interpret the argument as a blob.  Return
129878** a hexadecimal rendering as text.
129879*/
129880static void hexFunc(
129881  sqlite3_context *context,
129882  int argc,
129883  sqlite3_value **argv
129884){
129885  int i, n;
129886  const unsigned char *pBlob;
129887  char *zHex, *z;
129888  assert( argc==1 );
129889  UNUSED_PARAMETER(argc);
129890  pBlob = sqlite3_value_blob(argv[0]);
129891  n = sqlite3_value_bytes(argv[0]);
129892  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
129893  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
129894  if( zHex ){
129895    for(i=0; i<n; i++, pBlob++){
129896      unsigned char c = *pBlob;
129897      *(z++) = hexdigits[(c>>4)&0xf];
129898      *(z++) = hexdigits[c&0xf];
129899    }
129900    *z = 0;
129901    sqlite3_result_text64(context, zHex, (u64)(z-zHex),
129902                          sqlite3_free, SQLITE_UTF8);
129903  }
129904}
129905
129906/*
129907** Buffer zStr contains nStr bytes of utf-8 encoded text. Return 1 if zStr
129908** contains character ch, or 0 if it does not.
129909*/
129910static int strContainsChar(const u8 *zStr, int nStr, u32 ch){
129911  const u8 *zEnd = &zStr[nStr];
129912  const u8 *z = zStr;
129913  while( z<zEnd ){
129914    u32 tst = Utf8Read(z);
129915    if( tst==ch ) return 1;
129916  }
129917  return 0;
129918}
129919
129920/*
129921** The unhex() function. This function may be invoked with either one or
129922** two arguments. In both cases the first argument is interpreted as text
129923** a text value containing a set of pairs of hexadecimal digits which are
129924** decoded and returned as a blob.
129925**
129926** If there is only a single argument, then it must consist only of an
129927** even number of hexadecimal digits. Otherwise, return NULL.
129928**
129929** Or, if there is a second argument, then any character that appears in
129930** the second argument is also allowed to appear between pairs of hexadecimal
129931** digits in the first argument. If any other character appears in the
129932** first argument, or if one of the allowed characters appears between
129933** two hexadecimal digits that make up a single byte, NULL is returned.
129934**
129935** The following expressions are all true:
129936**
129937**     unhex('ABCD')       IS x'ABCD'
129938**     unhex('AB CD')      IS NULL
129939**     unhex('AB CD', ' ') IS x'ABCD'
129940**     unhex('A BCD', ' ') IS NULL
129941*/
129942static void unhexFunc(
129943  sqlite3_context *pCtx,
129944  int argc,
129945  sqlite3_value **argv
129946){
129947  const u8 *zPass = (const u8*)"";
129948  int nPass = 0;
129949  const u8 *zHex = sqlite3_value_text(argv[0]);
129950  int nHex = sqlite3_value_bytes(argv[0]);
129951#ifdef SQLITE_DEBUG
129952  const u8 *zEnd = zHex ? &zHex[nHex] : 0;
129953#endif
129954  u8 *pBlob = 0;
129955  u8 *p = 0;
129956
129957  assert( argc==1 || argc==2 );
129958  if( argc==2 ){
129959    zPass = sqlite3_value_text(argv[1]);
129960    nPass = sqlite3_value_bytes(argv[1]);
129961  }
129962  if( !zHex || !zPass ) return;
129963
129964  p = pBlob = contextMalloc(pCtx, (nHex/2)+1);
129965  if( pBlob ){
129966    u8 c;                         /* Most significant digit of next byte */
129967    u8 d;                         /* Least significant digit of next byte */
129968
129969    while( (c = *zHex)!=0x00 ){
129970      while( !sqlite3Isxdigit(c) ){
129971        u32 ch = Utf8Read(zHex);
129972        assert( zHex<=zEnd );
129973        if( !strContainsChar(zPass, nPass, ch) ) goto unhex_null;
129974        c = *zHex;
129975        if( c==0x00 ) goto unhex_done;
129976      }
129977      zHex++;
129978      assert( *zEnd==0x00 );
129979      assert( zHex<=zEnd );
129980      d = *(zHex++);
129981      if( !sqlite3Isxdigit(d) ) goto unhex_null;
129982      *(p++) = (sqlite3HexToInt(c)<<4) | sqlite3HexToInt(d);
129983    }
129984  }
129985
129986 unhex_done:
129987  sqlite3_result_blob(pCtx, pBlob, (p - pBlob), sqlite3_free);
129988  return;
129989
129990 unhex_null:
129991  sqlite3_free(pBlob);
129992  return;
129993}
129994
129995
129996/*
129997** The zeroblob(N) function returns a zero-filled blob of size N bytes.
129998*/
129999static void zeroblobFunc(
130000  sqlite3_context *context,
130001  int argc,
130002  sqlite3_value **argv
130003){
130004  i64 n;
130005  int rc;
130006  assert( argc==1 );
130007  UNUSED_PARAMETER(argc);
130008  n = sqlite3_value_int64(argv[0]);
130009  if( n<0 ) n = 0;
130010  rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
130011  if( rc ){
130012    sqlite3_result_error_code(context, rc);
130013  }
130014}
130015
130016/*
130017** The replace() function.  Three arguments are all strings: call
130018** them A, B, and C. The result is also a string which is derived
130019** from A by replacing every occurrence of B with C.  The match
130020** must be exact.  Collating sequences are not used.
130021*/
130022static void replaceFunc(
130023  sqlite3_context *context,
130024  int argc,
130025  sqlite3_value **argv
130026){
130027  const unsigned char *zStr;        /* The input string A */
130028  const unsigned char *zPattern;    /* The pattern string B */
130029  const unsigned char *zRep;        /* The replacement string C */
130030  unsigned char *zOut;              /* The output */
130031  int nStr;                /* Size of zStr */
130032  int nPattern;            /* Size of zPattern */
130033  int nRep;                /* Size of zRep */
130034  i64 nOut;                /* Maximum size of zOut */
130035  int loopLimit;           /* Last zStr[] that might match zPattern[] */
130036  int i, j;                /* Loop counters */
130037  unsigned cntExpand;      /* Number zOut expansions */
130038  sqlite3 *db = sqlite3_context_db_handle(context);
130039
130040  assert( argc==3 );
130041  UNUSED_PARAMETER(argc);
130042  zStr = sqlite3_value_text(argv[0]);
130043  if( zStr==0 ) return;
130044  nStr = sqlite3_value_bytes(argv[0]);
130045  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
130046  zPattern = sqlite3_value_text(argv[1]);
130047  if( zPattern==0 ){
130048    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
130049            || sqlite3_context_db_handle(context)->mallocFailed );
130050    return;
130051  }
130052  if( zPattern[0]==0 ){
130053    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
130054    sqlite3_result_text(context, (const char*)zStr, nStr, SQLITE_TRANSIENT);
130055    return;
130056  }
130057  nPattern = sqlite3_value_bytes(argv[1]);
130058  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
130059  zRep = sqlite3_value_text(argv[2]);
130060  if( zRep==0 ) return;
130061  nRep = sqlite3_value_bytes(argv[2]);
130062  assert( zRep==sqlite3_value_text(argv[2]) );
130063  nOut = nStr + 1;
130064  assert( nOut<SQLITE_MAX_LENGTH );
130065  zOut = contextMalloc(context, (i64)nOut);
130066  if( zOut==0 ){
130067    return;
130068  }
130069  loopLimit = nStr - nPattern;
130070  cntExpand = 0;
130071  for(i=j=0; i<=loopLimit; i++){
130072    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
130073      zOut[j++] = zStr[i];
130074    }else{
130075      if( nRep>nPattern ){
130076        nOut += nRep - nPattern;
130077        testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
130078        testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
130079        if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
130080          sqlite3_result_error_toobig(context);
130081          sqlite3_free(zOut);
130082          return;
130083        }
130084        cntExpand++;
130085        if( (cntExpand&(cntExpand-1))==0 ){
130086          /* Grow the size of the output buffer only on substitutions
130087          ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */
130088          u8 *zOld;
130089          zOld = zOut;
130090          zOut = sqlite3Realloc(zOut, (int)nOut + (nOut - nStr - 1));
130091          if( zOut==0 ){
130092            sqlite3_result_error_nomem(context);
130093            sqlite3_free(zOld);
130094            return;
130095          }
130096        }
130097      }
130098      memcpy(&zOut[j], zRep, nRep);
130099      j += nRep;
130100      i += nPattern-1;
130101    }
130102  }
130103  assert( j+nStr-i+1<=nOut );
130104  memcpy(&zOut[j], &zStr[i], nStr-i);
130105  j += nStr - i;
130106  assert( j<=nOut );
130107  zOut[j] = 0;
130108  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
130109}
130110
130111/*
130112** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
130113** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
130114*/
130115static void trimFunc(
130116  sqlite3_context *context,
130117  int argc,
130118  sqlite3_value **argv
130119){
130120  const unsigned char *zIn;         /* Input string */
130121  const unsigned char *zCharSet;    /* Set of characters to trim */
130122  unsigned int nIn;                 /* Number of bytes in input */
130123  int flags;                        /* 1: trimleft  2: trimright  3: trim */
130124  int i;                            /* Loop counter */
130125  unsigned int *aLen = 0;           /* Length of each character in zCharSet */
130126  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
130127  int nChar;                        /* Number of characters in zCharSet */
130128
130129  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
130130    return;
130131  }
130132  zIn = sqlite3_value_text(argv[0]);
130133  if( zIn==0 ) return;
130134  nIn = (unsigned)sqlite3_value_bytes(argv[0]);
130135  assert( zIn==sqlite3_value_text(argv[0]) );
130136  if( argc==1 ){
130137    static const unsigned lenOne[] = { 1 };
130138    static unsigned char * const azOne[] = { (u8*)" " };
130139    nChar = 1;
130140    aLen = (unsigned*)lenOne;
130141    azChar = (unsigned char **)azOne;
130142    zCharSet = 0;
130143  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
130144    return;
130145  }else{
130146    const unsigned char *z;
130147    for(z=zCharSet, nChar=0; *z; nChar++){
130148      SQLITE_SKIP_UTF8(z);
130149    }
130150    if( nChar>0 ){
130151      azChar = contextMalloc(context,
130152                     ((i64)nChar)*(sizeof(char*)+sizeof(unsigned)));
130153      if( azChar==0 ){
130154        return;
130155      }
130156      aLen = (unsigned*)&azChar[nChar];
130157      for(z=zCharSet, nChar=0; *z; nChar++){
130158        azChar[nChar] = (unsigned char *)z;
130159        SQLITE_SKIP_UTF8(z);
130160        aLen[nChar] = (unsigned)(z - azChar[nChar]);
130161      }
130162    }
130163  }
130164  if( nChar>0 ){
130165    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
130166    if( flags & 1 ){
130167      while( nIn>0 ){
130168        unsigned int len = 0;
130169        for(i=0; i<nChar; i++){
130170          len = aLen[i];
130171          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
130172        }
130173        if( i>=nChar ) break;
130174        zIn += len;
130175        nIn -= len;
130176      }
130177    }
130178    if( flags & 2 ){
130179      while( nIn>0 ){
130180        unsigned int len = 0;
130181        for(i=0; i<nChar; i++){
130182          len = aLen[i];
130183          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
130184        }
130185        if( i>=nChar ) break;
130186        nIn -= len;
130187      }
130188    }
130189    if( zCharSet ){
130190      sqlite3_free(azChar);
130191    }
130192  }
130193  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
130194}
130195
130196/* The core implementation of the CONCAT(...) and CONCAT_WS(SEP,...)
130197** functions.
130198**
130199** Return a string value that is the concatenation of all non-null
130200** entries in argv[].  Use zSep as the separator.
130201*/
130202static void concatFuncCore(
130203  sqlite3_context *context,
130204  int argc,
130205  sqlite3_value **argv,
130206  int nSep,
130207  const char *zSep
130208){
130209  i64 j, k, n = 0;
130210  int i;
130211  char *z;
130212  for(i=0; i<argc; i++){
130213    n += sqlite3_value_bytes(argv[i]);
130214  }
130215  n += (argc-1)*nSep;
130216  z = sqlite3_malloc64(n+1);
130217  if( z==0 ){
130218    sqlite3_result_error_nomem(context);
130219    return;
130220  }
130221  j = 0;
130222  for(i=0; i<argc; i++){
130223    k = sqlite3_value_bytes(argv[i]);
130224    if( k>0 ){
130225      const char *v = (const char*)sqlite3_value_text(argv[i]);
130226      if( v!=0 ){
130227        if( j>0 && nSep>0 ){
130228          memcpy(&z[j], zSep, nSep);
130229          j += nSep;
130230        }
130231        memcpy(&z[j], v, k);
130232        j += k;
130233      }
130234    }
130235  }
130236  z[j] = 0;
130237  assert( j<=n );
130238  sqlite3_result_text64(context, z, j, sqlite3_free, SQLITE_UTF8);
130239}
130240
130241/*
130242** The CONCAT(...) function.  Generate a string result that is the
130243** concatentation of all non-null arguments.
130244*/
130245static void concatFunc(
130246  sqlite3_context *context,
130247  int argc,
130248  sqlite3_value **argv
130249){
130250  concatFuncCore(context, argc, argv, 0, "");
130251}
130252
130253/*
130254** The CONCAT_WS(separator, ...) function.
130255**
130256** Generate a string that is the concatenation of 2nd through the Nth
130257** argument.  Use the first argument (which must be non-NULL) as the
130258** separator.
130259*/
130260static void concatwsFunc(
130261  sqlite3_context *context,
130262  int argc,
130263  sqlite3_value **argv
130264){
130265  int nSep = sqlite3_value_bytes(argv[0]);
130266  const char *zSep = (const char*)sqlite3_value_text(argv[0]);
130267  if( zSep==0 ) return;
130268  concatFuncCore(context, argc-1, argv+1, nSep, zSep);
130269}
130270
130271
130272#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
130273/*
130274** The "unknown" function is automatically substituted in place of
130275** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
130276** when the SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION compile-time option is used.
130277** When the "sqlite3" command-line shell is built using this functionality,
130278** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
130279** involving application-defined functions to be examined in a generic
130280** sqlite3 shell.
130281*/
130282static void unknownFunc(
130283  sqlite3_context *context,
130284  int argc,
130285  sqlite3_value **argv
130286){
130287  /* no-op */
130288  (void)context;
130289  (void)argc;
130290  (void)argv;
130291}
130292#endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
130293
130294
130295/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
130296** is only available if the SQLITE_SOUNDEX compile-time option is used
130297** when SQLite is built.
130298*/
130299#ifdef SQLITE_SOUNDEX
130300/*
130301** Compute the soundex encoding of a word.
130302**
130303** IMP: R-59782-00072 The soundex(X) function returns a string that is the
130304** soundex encoding of the string X.
130305*/
130306static void soundexFunc(
130307  sqlite3_context *context,
130308  int argc,
130309  sqlite3_value **argv
130310){
130311  char zResult[8];
130312  const u8 *zIn;
130313  int i, j;
130314  static const unsigned char iCode[] = {
130315    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
130316    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
130317    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
130318    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
130319    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
130320    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
130321    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
130322    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
130323  };
130324  assert( argc==1 );
130325  zIn = (u8*)sqlite3_value_text(argv[0]);
130326  if( zIn==0 ) zIn = (u8*)"";
130327  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
130328  if( zIn[i] ){
130329    u8 prevcode = iCode[zIn[i]&0x7f];
130330    zResult[0] = sqlite3Toupper(zIn[i]);
130331    for(j=1; j<4 && zIn[i]; i++){
130332      int code = iCode[zIn[i]&0x7f];
130333      if( code>0 ){
130334        if( code!=prevcode ){
130335          prevcode = code;
130336          zResult[j++] = code + '0';
130337        }
130338      }else{
130339        prevcode = 0;
130340      }
130341    }
130342    while( j<4 ){
130343      zResult[j++] = '0';
130344    }
130345    zResult[j] = 0;
130346    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
130347  }else{
130348    /* IMP: R-64894-50321 The string "?000" is returned if the argument
130349    ** is NULL or contains no ASCII alphabetic characters. */
130350    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
130351  }
130352}
130353#endif /* SQLITE_SOUNDEX */
130354
130355#ifndef SQLITE_OMIT_LOAD_EXTENSION
130356/*
130357** A function that loads a shared-library extension then returns NULL.
130358*/
130359static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
130360  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
130361  const char *zProc;
130362  sqlite3 *db = sqlite3_context_db_handle(context);
130363  char *zErrMsg = 0;
130364
130365  /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
130366  ** flag is set.  See the sqlite3_enable_load_extension() API.
130367  */
130368  if( (db->flags & SQLITE_LoadExtFunc)==0 ){
130369    sqlite3_result_error(context, "not authorized", -1);
130370    return;
130371  }
130372
130373  if( argc==2 ){
130374    zProc = (const char *)sqlite3_value_text(argv[1]);
130375  }else{
130376    zProc = 0;
130377  }
130378  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
130379    sqlite3_result_error(context, zErrMsg, -1);
130380    sqlite3_free(zErrMsg);
130381  }
130382}
130383#endif
130384
130385
130386/*
130387** An instance of the following structure holds the context of a
130388** sum() or avg() aggregate computation.
130389*/
130390typedef struct SumCtx SumCtx;
130391struct SumCtx {
130392  double rSum;      /* Running sum as as a double */
130393  double rErr;      /* Error term for Kahan-Babushka-Neumaier summation */
130394  i64 iSum;         /* Running sum as a signed integer */
130395  i64 cnt;          /* Number of elements summed */
130396  u8 approx;        /* True if any non-integer value was input to the sum */
130397  u8 ovrfl;         /* Integer overflow seen */
130398};
130399
130400/*
130401** Do one step of the Kahan-Babushka-Neumaier summation.
130402**
130403** https://en.wikipedia.org/wiki/Kahan_summation_algorithm
130404**
130405** Variables are marked "volatile" to defeat c89 x86 floating point
130406** optimizations can mess up this algorithm.
130407*/
130408static void kahanBabuskaNeumaierStep(
130409  volatile SumCtx *pSum,
130410  volatile double r
130411){
130412  volatile double s = pSum->rSum;
130413  volatile double t = s + r;
130414  if( fabs(s) > fabs(r) ){
130415    pSum->rErr += (s - t) + r;
130416  }else{
130417    pSum->rErr += (r - t) + s;
130418  }
130419  pSum->rSum = t;
130420}
130421
130422/*
130423** Add a (possibly large) integer to the running sum.
130424*/
130425static void kahanBabuskaNeumaierStepInt64(volatile SumCtx *pSum, i64 iVal){
130426  if( iVal<=-4503599627370496LL || iVal>=+4503599627370496LL ){
130427    i64 iBig, iSm;
130428    iSm = iVal % 16384;
130429    iBig = iVal - iSm;
130430    kahanBabuskaNeumaierStep(pSum, iBig);
130431    kahanBabuskaNeumaierStep(pSum, iSm);
130432  }else{
130433    kahanBabuskaNeumaierStep(pSum, (double)iVal);
130434  }
130435}
130436
130437/*
130438** Initialize the Kahan-Babaska-Neumaier sum from a 64-bit integer
130439*/
130440static void kahanBabuskaNeumaierInit(
130441  volatile SumCtx *p,
130442  i64 iVal
130443){
130444  if( iVal<=-4503599627370496LL || iVal>=+4503599627370496LL ){
130445    i64 iSm = iVal % 16384;
130446    p->rSum = (double)(iVal - iSm);
130447    p->rErr = (double)iSm;
130448  }else{
130449    p->rSum = (double)iVal;
130450    p->rErr = 0.0;
130451  }
130452}
130453
130454/*
130455** Routines used to compute the sum, average, and total.
130456**
130457** The SUM() function follows the (broken) SQL standard which means
130458** that it returns NULL if it sums over no inputs.  TOTAL returns
130459** 0.0 in that case.  In addition, TOTAL always returns a float where
130460** SUM might return an integer if it never encounters a floating point
130461** value.  TOTAL never fails, but SUM might through an exception if
130462** it overflows an integer.
130463*/
130464static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
130465  SumCtx *p;
130466  int type;
130467  assert( argc==1 );
130468  UNUSED_PARAMETER(argc);
130469  p = sqlite3_aggregate_context(context, sizeof(*p));
130470  type = sqlite3_value_numeric_type(argv[0]);
130471  if( p && type!=SQLITE_NULL ){
130472    p->cnt++;
130473    if( p->approx==0 ){
130474      if( type!=SQLITE_INTEGER ){
130475        kahanBabuskaNeumaierInit(p, p->iSum);
130476        p->approx = 1;
130477        kahanBabuskaNeumaierStep(p, sqlite3_value_double(argv[0]));
130478      }else{
130479        i64 x = p->iSum;
130480        if( sqlite3AddInt64(&x, sqlite3_value_int64(argv[0]))==0 ){
130481          p->iSum = x;
130482        }else{
130483          p->ovrfl = 1;
130484          kahanBabuskaNeumaierInit(p, p->iSum);
130485          p->approx = 1;
130486          kahanBabuskaNeumaierStepInt64(p, sqlite3_value_int64(argv[0]));
130487        }
130488      }
130489    }else{
130490      if( type==SQLITE_INTEGER ){
130491        kahanBabuskaNeumaierStepInt64(p, sqlite3_value_int64(argv[0]));
130492      }else{
130493        p->ovrfl = 0;
130494        kahanBabuskaNeumaierStep(p, sqlite3_value_double(argv[0]));
130495      }
130496    }
130497  }
130498}
130499#ifndef SQLITE_OMIT_WINDOWFUNC
130500static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){
130501  SumCtx *p;
130502  int type;
130503  assert( argc==1 );
130504  UNUSED_PARAMETER(argc);
130505  p = sqlite3_aggregate_context(context, sizeof(*p));
130506  type = sqlite3_value_numeric_type(argv[0]);
130507  /* p is always non-NULL because sumStep() will have been called first
130508  ** to initialize it */
130509  if( ALWAYS(p) && type!=SQLITE_NULL ){
130510    assert( p->cnt>0 );
130511    p->cnt--;
130512    if( !p->approx ){
130513      p->iSum -= sqlite3_value_int64(argv[0]);
130514    }else if( type==SQLITE_INTEGER ){
130515      i64 iVal = sqlite3_value_int64(argv[0]);
130516      if( iVal!=SMALLEST_INT64 ){
130517        kahanBabuskaNeumaierStepInt64(p, -iVal);
130518      }else{
130519        kahanBabuskaNeumaierStepInt64(p, LARGEST_INT64);
130520        kahanBabuskaNeumaierStepInt64(p, 1);
130521      }
130522    }else{
130523      kahanBabuskaNeumaierStep(p, -sqlite3_value_double(argv[0]));
130524    }
130525  }
130526}
130527#else
130528# define sumInverse 0
130529#endif /* SQLITE_OMIT_WINDOWFUNC */
130530static void sumFinalize(sqlite3_context *context){
130531  SumCtx *p;
130532  p = sqlite3_aggregate_context(context, 0);
130533  if( p && p->cnt>0 ){
130534    if( p->approx ){
130535      if( p->ovrfl ){
130536        sqlite3_result_error(context,"integer overflow",-1);
130537      }else if( !sqlite3IsOverflow(p->rErr) ){
130538        sqlite3_result_double(context, p->rSum+p->rErr);
130539      }else{
130540        sqlite3_result_double(context, p->rSum);
130541      }
130542    }else{
130543      sqlite3_result_int64(context, p->iSum);
130544    }
130545  }
130546}
130547static void avgFinalize(sqlite3_context *context){
130548  SumCtx *p;
130549  p = sqlite3_aggregate_context(context, 0);
130550  if( p && p->cnt>0 ){
130551    double r;
130552    if( p->approx ){
130553      r = p->rSum;
130554      if( !sqlite3IsOverflow(p->rErr) ) r += p->rErr;
130555    }else{
130556      r = (double)(p->iSum);
130557    }
130558    sqlite3_result_double(context, r/(double)p->cnt);
130559  }
130560}
130561static void totalFinalize(sqlite3_context *context){
130562  SumCtx *p;
130563  double r = 0.0;
130564  p = sqlite3_aggregate_context(context, 0);
130565  if( p ){
130566    if( p->approx ){
130567      r = p->rSum;
130568      if( !sqlite3IsOverflow(p->rErr) ) r += p->rErr;
130569    }else{
130570      r = (double)(p->iSum);
130571    }
130572  }
130573  sqlite3_result_double(context, r);
130574}
130575
130576/*
130577** The following structure keeps track of state information for the
130578** count() aggregate function.
130579*/
130580typedef struct CountCtx CountCtx;
130581struct CountCtx {
130582  i64 n;
130583#ifdef SQLITE_DEBUG
130584  int bInverse;                   /* True if xInverse() ever called */
130585#endif
130586};
130587
130588/*
130589** Routines to implement the count() aggregate function.
130590*/
130591static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
130592  CountCtx *p;
130593  p = sqlite3_aggregate_context(context, sizeof(*p));
130594  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
130595    p->n++;
130596  }
130597
130598#ifndef SQLITE_OMIT_DEPRECATED
130599  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
130600  ** sure it still operates correctly, verify that its count agrees with our
130601  ** internal count when using count(*) and when the total count can be
130602  ** expressed as a 32-bit integer. */
130603  assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse
130604          || p->n==sqlite3_aggregate_count(context) );
130605#endif
130606}
130607static void countFinalize(sqlite3_context *context){
130608  CountCtx *p;
130609  p = sqlite3_aggregate_context(context, 0);
130610  sqlite3_result_int64(context, p ? p->n : 0);
130611}
130612#ifndef SQLITE_OMIT_WINDOWFUNC
130613static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){
130614  CountCtx *p;
130615  p = sqlite3_aggregate_context(ctx, sizeof(*p));
130616  /* p is always non-NULL since countStep() will have been called first */
130617  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){
130618    p->n--;
130619#ifdef SQLITE_DEBUG
130620    p->bInverse = 1;
130621#endif
130622  }
130623}
130624#else
130625# define countInverse 0
130626#endif /* SQLITE_OMIT_WINDOWFUNC */
130627
130628/*
130629** Routines to implement min() and max() aggregate functions.
130630*/
130631static void minmaxStep(
130632  sqlite3_context *context,
130633  int NotUsed,
130634  sqlite3_value **argv
130635){
130636  Mem *pArg  = (Mem *)argv[0];
130637  Mem *pBest;
130638  UNUSED_PARAMETER(NotUsed);
130639
130640  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
130641  if( !pBest ) return;
130642
130643  if( sqlite3_value_type(pArg)==SQLITE_NULL ){
130644    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
130645  }else if( pBest->flags ){
130646    int max;
130647    int cmp;
130648    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
130649    /* This step function is used for both the min() and max() aggregates,
130650    ** the only difference between the two being that the sense of the
130651    ** comparison is inverted. For the max() aggregate, the
130652    ** sqlite3_user_data() function returns (void *)-1. For min() it
130653    ** returns (void *)db, where db is the sqlite3* database pointer.
130654    ** Therefore the next statement sets variable 'max' to 1 for the max()
130655    ** aggregate, or 0 for min().
130656    */
130657    max = sqlite3_user_data(context)!=0;
130658    cmp = sqlite3MemCompare(pBest, pArg, pColl);
130659    if( (max && cmp<0) || (!max && cmp>0) ){
130660      sqlite3VdbeMemCopy(pBest, pArg);
130661    }else{
130662      sqlite3SkipAccumulatorLoad(context);
130663    }
130664  }else{
130665    pBest->db = sqlite3_context_db_handle(context);
130666    sqlite3VdbeMemCopy(pBest, pArg);
130667  }
130668}
130669static void minMaxValueFinalize(sqlite3_context *context, int bValue){
130670  sqlite3_value *pRes;
130671  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
130672  if( pRes ){
130673    if( pRes->flags ){
130674      sqlite3_result_value(context, pRes);
130675    }
130676    if( bValue==0 ) sqlite3VdbeMemRelease(pRes);
130677  }
130678}
130679#ifndef SQLITE_OMIT_WINDOWFUNC
130680static void minMaxValue(sqlite3_context *context){
130681  minMaxValueFinalize(context, 1);
130682}
130683#else
130684# define minMaxValue 0
130685#endif /* SQLITE_OMIT_WINDOWFUNC */
130686static void minMaxFinalize(sqlite3_context *context){
130687  minMaxValueFinalize(context, 0);
130688}
130689
130690/*
130691** group_concat(EXPR, ?SEPARATOR?)
130692** string_agg(EXPR, SEPARATOR)
130693**
130694** The SEPARATOR goes before the EXPR string.  This is tragic.  The
130695** groupConcatInverse() implementation would have been easier if the
130696** SEPARATOR were appended after EXPR.  And the order is undocumented,
130697** so we could change it, in theory.  But the old behavior has been
130698** around for so long that we dare not, for fear of breaking something.
130699*/
130700typedef struct {
130701  StrAccum str;          /* The accumulated concatenation */
130702#ifndef SQLITE_OMIT_WINDOWFUNC
130703  int nAccum;            /* Number of strings presently concatenated */
130704  int nFirstSepLength;   /* Used to detect separator length change */
130705  /* If pnSepLengths!=0, refs an array of inter-string separator lengths,
130706  ** stored as actually incorporated into presently accumulated result.
130707  ** (Hence, its slots in use number nAccum-1 between method calls.)
130708  ** If pnSepLengths==0, nFirstSepLength is the length used throughout.
130709  */
130710  int *pnSepLengths;
130711#endif
130712} GroupConcatCtx;
130713
130714static void groupConcatStep(
130715  sqlite3_context *context,
130716  int argc,
130717  sqlite3_value **argv
130718){
130719  const char *zVal;
130720  GroupConcatCtx *pGCC;
130721  const char *zSep;
130722  int nVal, nSep;
130723  assert( argc==1 || argc==2 );
130724  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
130725  pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, sizeof(*pGCC));
130726  if( pGCC ){
130727    sqlite3 *db = sqlite3_context_db_handle(context);
130728    int firstTerm = pGCC->str.mxAlloc==0;
130729    pGCC->str.mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
130730    if( argc==1 ){
130731      if( !firstTerm ){
130732        sqlite3_str_appendchar(&pGCC->str, 1, ',');
130733      }
130734#ifndef SQLITE_OMIT_WINDOWFUNC
130735      else{
130736        pGCC->nFirstSepLength = 1;
130737      }
130738#endif
130739    }else if( !firstTerm ){
130740      zSep = (char*)sqlite3_value_text(argv[1]);
130741      nSep = sqlite3_value_bytes(argv[1]);
130742      if( zSep ){
130743        sqlite3_str_append(&pGCC->str, zSep, nSep);
130744      }
130745#ifndef SQLITE_OMIT_WINDOWFUNC
130746      else{
130747        nSep = 0;
130748      }
130749      if( nSep != pGCC->nFirstSepLength || pGCC->pnSepLengths != 0 ){
130750        int *pnsl = pGCC->pnSepLengths;
130751        if( pnsl == 0 ){
130752          /* First separator length variation seen, start tracking them. */
130753          pnsl = (int*)sqlite3_malloc64((pGCC->nAccum+1) * sizeof(int));
130754          if( pnsl!=0 ){
130755            int i = 0, nA = pGCC->nAccum-1;
130756            while( i<nA ) pnsl[i++] = pGCC->nFirstSepLength;
130757          }
130758        }else{
130759          pnsl = (int*)sqlite3_realloc64(pnsl, pGCC->nAccum * sizeof(int));
130760        }
130761        if( pnsl!=0 ){
130762          if( ALWAYS(pGCC->nAccum>0) ){
130763            pnsl[pGCC->nAccum-1] = nSep;
130764          }
130765          pGCC->pnSepLengths = pnsl;
130766        }else{
130767          sqlite3StrAccumSetError(&pGCC->str, SQLITE_NOMEM);
130768        }
130769      }
130770#endif
130771    }
130772#ifndef SQLITE_OMIT_WINDOWFUNC
130773    else{
130774      pGCC->nFirstSepLength = sqlite3_value_bytes(argv[1]);
130775    }
130776    pGCC->nAccum += 1;
130777#endif
130778    zVal = (char*)sqlite3_value_text(argv[0]);
130779    nVal = sqlite3_value_bytes(argv[0]);
130780    if( zVal ) sqlite3_str_append(&pGCC->str, zVal, nVal);
130781  }
130782}
130783
130784#ifndef SQLITE_OMIT_WINDOWFUNC
130785static void groupConcatInverse(
130786  sqlite3_context *context,
130787  int argc,
130788  sqlite3_value **argv
130789){
130790  GroupConcatCtx *pGCC;
130791  assert( argc==1 || argc==2 );
130792  (void)argc;  /* Suppress unused parameter warning */
130793  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
130794  pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, sizeof(*pGCC));
130795  /* pGCC is always non-NULL since groupConcatStep() will have always
130796  ** run first to initialize it */
130797  if( ALWAYS(pGCC) ){
130798    int nVS;
130799    /* Must call sqlite3_value_text() to convert the argument into text prior
130800    ** to invoking sqlite3_value_bytes(), in case the text encoding is UTF16 */
130801    (void)sqlite3_value_text(argv[0]);
130802    nVS = sqlite3_value_bytes(argv[0]);
130803    pGCC->nAccum -= 1;
130804    if( pGCC->pnSepLengths!=0 ){
130805      assert(pGCC->nAccum >= 0);
130806      if( pGCC->nAccum>0 ){
130807        nVS += *pGCC->pnSepLengths;
130808        memmove(pGCC->pnSepLengths, pGCC->pnSepLengths+1,
130809               (pGCC->nAccum-1)*sizeof(int));
130810      }
130811    }else{
130812      /* If removing single accumulated string, harmlessly over-do. */
130813      nVS += pGCC->nFirstSepLength;
130814    }
130815    if( nVS>=(int)pGCC->str.nChar ){
130816      pGCC->str.nChar = 0;
130817    }else{
130818      pGCC->str.nChar -= nVS;
130819      memmove(pGCC->str.zText, &pGCC->str.zText[nVS], pGCC->str.nChar);
130820    }
130821    if( pGCC->str.nChar==0 ){
130822      pGCC->str.mxAlloc = 0;
130823      sqlite3_free(pGCC->pnSepLengths);
130824      pGCC->pnSepLengths = 0;
130825    }
130826  }
130827}
130828#else
130829# define groupConcatInverse 0
130830#endif /* SQLITE_OMIT_WINDOWFUNC */
130831static void groupConcatFinalize(sqlite3_context *context){
130832  GroupConcatCtx *pGCC
130833    = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
130834  if( pGCC ){
130835    sqlite3ResultStrAccum(context, &pGCC->str);
130836#ifndef SQLITE_OMIT_WINDOWFUNC
130837    sqlite3_free(pGCC->pnSepLengths);
130838#endif
130839  }
130840}
130841#ifndef SQLITE_OMIT_WINDOWFUNC
130842static void groupConcatValue(sqlite3_context *context){
130843  GroupConcatCtx *pGCC
130844    = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
130845  if( pGCC ){
130846    StrAccum *pAccum = &pGCC->str;
130847    if( pAccum->accError==SQLITE_TOOBIG ){
130848      sqlite3_result_error_toobig(context);
130849    }else if( pAccum->accError==SQLITE_NOMEM ){
130850      sqlite3_result_error_nomem(context);
130851    }else{
130852      const char *zText = sqlite3_str_value(pAccum);
130853      sqlite3_result_text(context, zText, pAccum->nChar, SQLITE_TRANSIENT);
130854    }
130855  }
130856}
130857#else
130858# define groupConcatValue 0
130859#endif /* SQLITE_OMIT_WINDOWFUNC */
130860
130861/*
130862** This routine does per-connection function registration.  Most
130863** of the built-in functions above are part of the global function set.
130864** This routine only deals with those that are not global.
130865*/
130866SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
130867  int rc = sqlite3_overload_function(db, "MATCH", 2);
130868  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
130869  if( rc==SQLITE_NOMEM ){
130870    sqlite3OomFault(db);
130871  }
130872}
130873
130874/*
130875** Re-register the built-in LIKE functions.  The caseSensitive
130876** parameter determines whether or not the LIKE operator is case
130877** sensitive.
130878*/
130879SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
130880  FuncDef *pDef;
130881  struct compareInfo *pInfo;
130882  int flags;
130883  int nArg;
130884  if( caseSensitive ){
130885    pInfo = (struct compareInfo*)&likeInfoAlt;
130886    flags = SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE;
130887  }else{
130888    pInfo = (struct compareInfo*)&likeInfoNorm;
130889    flags = SQLITE_FUNC_LIKE;
130890  }
130891  for(nArg=2; nArg<=3; nArg++){
130892    sqlite3CreateFunc(db, "like", nArg, SQLITE_UTF8, pInfo, likeFunc,
130893                      0, 0, 0, 0, 0);
130894    pDef = sqlite3FindFunction(db, "like", nArg, SQLITE_UTF8, 0);
130895    pDef->funcFlags |= flags;
130896    pDef->funcFlags &= ~SQLITE_FUNC_UNSAFE;
130897  }
130898}
130899
130900/*
130901** pExpr points to an expression which implements a function.  If
130902** it is appropriate to apply the LIKE optimization to that function
130903** then set aWc[0] through aWc[2] to the wildcard characters and the
130904** escape character and then return TRUE.  If the function is not a
130905** LIKE-style function then return FALSE.
130906**
130907** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
130908** operator if c is a string literal that is exactly one byte in length.
130909** That one byte is stored in aWc[3].  aWc[3] is set to zero if there is
130910** no ESCAPE clause.
130911**
130912** *pIsNocase is set to true if uppercase and lowercase are equivalent for
130913** the function (default for LIKE).  If the function makes the distinction
130914** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
130915** false.
130916*/
130917SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
130918  FuncDef *pDef;
130919  int nExpr;
130920  assert( pExpr!=0 );
130921  assert( pExpr->op==TK_FUNCTION );
130922  assert( ExprUseXList(pExpr) );
130923  if( !pExpr->x.pList ){
130924    return 0;
130925  }
130926  nExpr = pExpr->x.pList->nExpr;
130927  assert( !ExprHasProperty(pExpr, EP_IntValue) );
130928  pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
130929#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
130930  if( pDef==0 ) return 0;
130931#endif
130932  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
130933    return 0;
130934  }
130935
130936  /* The memcpy() statement assumes that the wildcard characters are
130937  ** the first three statements in the compareInfo structure.  The
130938  ** asserts() that follow verify that assumption
130939  */
130940  memcpy(aWc, pDef->pUserData, 3);
130941  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
130942  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
130943  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
130944
130945  if( nExpr<3 ){
130946    aWc[3] = 0;
130947  }else{
130948    Expr *pEscape = pExpr->x.pList->a[2].pExpr;
130949    char *zEscape;
130950    if( pEscape->op!=TK_STRING ) return 0;
130951    assert( !ExprHasProperty(pEscape, EP_IntValue) );
130952    zEscape = pEscape->u.zToken;
130953    if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
130954    if( zEscape[0]==aWc[0] ) return 0;
130955    if( zEscape[0]==aWc[1] ) return 0;
130956    aWc[3] = zEscape[0];
130957  }
130958
130959  *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
130960  return 1;
130961}
130962
130963/* Mathematical Constants */
130964#ifndef M_PI
130965# define M_PI   3.141592653589793238462643383279502884
130966#endif
130967#ifndef M_LN10
130968# define M_LN10 2.302585092994045684017991454684364208
130969#endif
130970#ifndef M_LN2
130971# define M_LN2  0.693147180559945309417232121458176568
130972#endif
130973
130974
130975/* Extra math functions that require linking with -lm
130976*/
130977#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
130978/*
130979** Implementation SQL functions:
130980**
130981**   ceil(X)
130982**   ceiling(X)
130983**   floor(X)
130984**
130985** The sqlite3_user_data() pointer is a pointer to the libm implementation
130986** of the underlying C function.
130987*/
130988static void ceilingFunc(
130989  sqlite3_context *context,
130990  int argc,
130991  sqlite3_value **argv
130992){
130993  assert( argc==1 );
130994  switch( sqlite3_value_numeric_type(argv[0]) ){
130995    case SQLITE_INTEGER: {
130996       sqlite3_result_int64(context, sqlite3_value_int64(argv[0]));
130997       break;
130998    }
130999    case SQLITE_FLOAT: {
131000       double (*x)(double) = (double(*)(double))sqlite3_user_data(context);
131001       sqlite3_result_double(context, x(sqlite3_value_double(argv[0])));
131002       break;
131003    }
131004    default: {
131005       break;
131006    }
131007  }
131008}
131009
131010/*
131011** On some systems, ceil() and floor() are intrinsic function.  You are
131012** unable to take a pointer to these functions.  Hence, we here wrap them
131013** in our own actual functions.
131014*/
131015static double xCeil(double x){ return ceil(x); }
131016static double xFloor(double x){ return floor(x); }
131017
131018/*
131019** Some systems do not have log2() and log10() in their standard math
131020** libraries.
131021*/
131022#if defined(HAVE_LOG10) && HAVE_LOG10==0
131023# define log10(X) (0.4342944819032517867*log(X))
131024#endif
131025#if defined(HAVE_LOG2) && HAVE_LOG2==0
131026# define log2(X) (1.442695040888963456*log(X))
131027#endif
131028
131029
131030/*
131031** Implementation of SQL functions:
131032**
131033**   ln(X)       - natural logarithm
131034**   log(X)      - log X base 10
131035**   log10(X)    - log X base 10
131036**   log(B,X)    - log X base B
131037*/
131038static void logFunc(
131039  sqlite3_context *context,
131040  int argc,
131041  sqlite3_value **argv
131042){
131043  double x, b, ans;
131044  assert( argc==1 || argc==2 );
131045  switch( sqlite3_value_numeric_type(argv[0]) ){
131046    case SQLITE_INTEGER:
131047    case SQLITE_FLOAT:
131048      x = sqlite3_value_double(argv[0]);
131049      if( x<=0.0 ) return;
131050      break;
131051    default:
131052      return;
131053  }
131054  if( argc==2 ){
131055    switch( sqlite3_value_numeric_type(argv[0]) ){
131056      case SQLITE_INTEGER:
131057      case SQLITE_FLOAT:
131058        b = log(x);
131059        if( b<=0.0 ) return;
131060        x = sqlite3_value_double(argv[1]);
131061        if( x<=0.0 ) return;
131062        break;
131063     default:
131064        return;
131065    }
131066    ans = log(x)/b;
131067  }else{
131068    switch( SQLITE_PTR_TO_INT(sqlite3_user_data(context)) ){
131069      case 1:
131070        ans = log10(x);
131071        break;
131072      case 2:
131073        ans = log2(x);
131074        break;
131075      default:
131076        ans = log(x);
131077        break;
131078    }
131079  }
131080  sqlite3_result_double(context, ans);
131081}
131082
131083/*
131084** Functions to converts degrees to radians and radians to degrees.
131085*/
131086static double degToRad(double x){ return x*(M_PI/180.0); }
131087static double radToDeg(double x){ return x*(180.0/M_PI); }
131088
131089/*
131090** Implementation of 1-argument SQL math functions:
131091**
131092**   exp(X)  - Compute e to the X-th power
131093*/
131094static void math1Func(
131095  sqlite3_context *context,
131096  int argc,
131097  sqlite3_value **argv
131098){
131099  int type0;
131100  double v0, ans;
131101  double (*x)(double);
131102  assert( argc==1 );
131103  type0 = sqlite3_value_numeric_type(argv[0]);
131104  if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return;
131105  v0 = sqlite3_value_double(argv[0]);
131106  x = (double(*)(double))sqlite3_user_data(context);
131107  ans = x(v0);
131108  sqlite3_result_double(context, ans);
131109}
131110
131111/*
131112** Implementation of 2-argument SQL math functions:
131113**
131114**   power(X,Y)  - Compute X to the Y-th power
131115*/
131116static void math2Func(
131117  sqlite3_context *context,
131118  int argc,
131119  sqlite3_value **argv
131120){
131121  int type0, type1;
131122  double v0, v1, ans;
131123  double (*x)(double,double);
131124  assert( argc==2 );
131125  type0 = sqlite3_value_numeric_type(argv[0]);
131126  if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return;
131127  type1 = sqlite3_value_numeric_type(argv[1]);
131128  if( type1!=SQLITE_INTEGER && type1!=SQLITE_FLOAT ) return;
131129  v0 = sqlite3_value_double(argv[0]);
131130  v1 = sqlite3_value_double(argv[1]);
131131  x = (double(*)(double,double))sqlite3_user_data(context);
131132  ans = x(v0, v1);
131133  sqlite3_result_double(context, ans);
131134}
131135
131136/*
131137** Implementation of 0-argument pi() function.
131138*/
131139static void piFunc(
131140  sqlite3_context *context,
131141  int argc,
131142  sqlite3_value **argv
131143){
131144  assert( argc==0 );
131145  (void)argv;
131146  sqlite3_result_double(context, M_PI);
131147}
131148
131149#endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
131150
131151/*
131152** Implementation of sign(X) function.
131153*/
131154static void signFunc(
131155  sqlite3_context *context,
131156  int argc,
131157  sqlite3_value **argv
131158){
131159  int type0;
131160  double x;
131161  UNUSED_PARAMETER(argc);
131162  assert( argc==1 );
131163  type0 = sqlite3_value_numeric_type(argv[0]);
131164  if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return;
131165  x = sqlite3_value_double(argv[0]);
131166  sqlite3_result_int(context, x<0.0 ? -1 : x>0.0 ? +1 : 0);
131167}
131168
131169#ifdef SQLITE_DEBUG
131170/*
131171** Implementation of fpdecode(x,y,z) function.
131172**
131173** x is a real number that is to be decoded.  y is the precision.
131174** z is the maximum real precision.
131175*/
131176static void fpdecodeFunc(
131177  sqlite3_context *context,
131178  int argc,
131179  sqlite3_value **argv
131180){
131181  FpDecode s;
131182  double x;
131183  int y, z;
131184  char zBuf[100];
131185  UNUSED_PARAMETER(argc);
131186  assert( argc==3 );
131187  x = sqlite3_value_double(argv[0]);
131188  y = sqlite3_value_int(argv[1]);
131189  z = sqlite3_value_int(argv[2]);
131190  sqlite3FpDecode(&s, x, y, z);
131191  if( s.isSpecial==2 ){
131192    sqlite3_snprintf(sizeof(zBuf), zBuf, "NaN");
131193  }else{
131194    sqlite3_snprintf(sizeof(zBuf), zBuf, "%c%.*s/%d", s.sign, s.n, s.z, s.iDP);
131195  }
131196  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
131197}
131198#endif /* SQLITE_DEBUG */
131199
131200/*
131201** All of the FuncDef structures in the aBuiltinFunc[] array above
131202** to the global function hash table.  This occurs at start-time (as
131203** a consequence of calling sqlite3_initialize()).
131204**
131205** After this routine runs
131206*/
131207SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
131208  /*
131209  ** The following array holds FuncDef structures for all of the functions
131210  ** defined in this file.
131211  **
131212  ** The array cannot be constant since changes are made to the
131213  ** FuncDef.pHash elements at start-time.  The elements of this array
131214  ** are read-only after initialization is complete.
131215  **
131216  ** For peak efficiency, put the most frequently used function last.
131217  */
131218  static FuncDef aBuiltinFunc[] = {
131219/***** Functions only available with SQLITE_TESTCTRL_INTERNAL_FUNCTIONS *****/
131220#if !defined(SQLITE_UNTESTABLE)
131221    TEST_FUNC(implies_nonnull_row, 2, INLINEFUNC_implies_nonnull_row, 0),
131222    TEST_FUNC(expr_compare,        2, INLINEFUNC_expr_compare,        0),
131223    TEST_FUNC(expr_implies_expr,   2, INLINEFUNC_expr_implies_expr,   0),
131224    TEST_FUNC(affinity,            1, INLINEFUNC_affinity,            0),
131225#endif /* !defined(SQLITE_UNTESTABLE) */
131226/***** Regular functions *****/
131227#ifdef SQLITE_SOUNDEX
131228    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
131229#endif
131230#ifndef SQLITE_OMIT_LOAD_EXTENSION
131231    SFUNCTION(load_extension,    1, 0, 0, loadExt          ),
131232    SFUNCTION(load_extension,    2, 0, 0, loadExt          ),
131233#endif
131234#if SQLITE_USER_AUTHENTICATION
131235    FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
131236#endif
131237#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
131238    DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
131239    DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
131240#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
131241    INLINE_FUNC(unlikely,        1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
131242    INLINE_FUNC(likelihood,      2, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
131243    INLINE_FUNC(likely,          1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
131244#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
131245    INLINE_FUNC(sqlite_offset,   1, INLINEFUNC_sqlite_offset, 0 ),
131246#endif
131247    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
131248    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
131249    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
131250    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
131251    FUNCTION(trim,               1, 3, 0, trimFunc         ),
131252    FUNCTION(trim,               2, 3, 0, trimFunc         ),
131253    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
131254    FUNCTION(min,                0, 0, 1, 0                ),
131255    WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
131256                                 SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ),
131257    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
131258    FUNCTION(max,                0, 1, 1, 0                ),
131259    WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
131260                                 SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ),
131261    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
131262    FUNCTION2(subtype,           1, 0, 0, subtypeFunc, SQLITE_FUNC_TYPEOF),
131263    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
131264    FUNCTION2(octet_length,      1, 0, 0, bytelengthFunc,SQLITE_FUNC_BYTELEN),
131265    FUNCTION(instr,              2, 0, 0, instrFunc        ),
131266    FUNCTION(printf,            -1, 0, 0, printfFunc       ),
131267    FUNCTION(format,            -1, 0, 0, printfFunc       ),
131268    FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
131269    FUNCTION(char,              -1, 0, 0, charFunc         ),
131270    FUNCTION(abs,                1, 0, 0, absFunc          ),
131271#ifdef SQLITE_DEBUG
131272    FUNCTION(fpdecode,           3, 0, 0, fpdecodeFunc     ),
131273#endif
131274#ifndef SQLITE_OMIT_FLOATING_POINT
131275    FUNCTION(round,              1, 0, 0, roundFunc        ),
131276    FUNCTION(round,              2, 0, 0, roundFunc        ),
131277#endif
131278    FUNCTION(upper,              1, 0, 0, upperFunc        ),
131279    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
131280    FUNCTION(hex,                1, 0, 0, hexFunc          ),
131281    FUNCTION(unhex,              1, 0, 0, unhexFunc        ),
131282    FUNCTION(unhex,              2, 0, 0, unhexFunc        ),
131283    FUNCTION(concat,            -1, 0, 0, concatFunc       ),
131284    FUNCTION(concat,             0, 0, 0, 0                ),
131285    FUNCTION(concat_ws,         -1, 0, 0, concatwsFunc     ),
131286    FUNCTION(concat_ws,          0, 0, 0, 0                ),
131287    FUNCTION(concat_ws,          1, 0, 0, 0                ),
131288    INLINE_FUNC(ifnull,          2, INLINEFUNC_coalesce, 0 ),
131289    VFUNCTION(random,            0, 0, 0, randomFunc       ),
131290    VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
131291    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
131292    DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
131293    DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
131294    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
131295    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
131296    VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
131297    VFUNCTION(changes,           0, 0, 0, changes          ),
131298    VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
131299    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
131300    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
131301    FUNCTION(substr,             2, 0, 0, substrFunc       ),
131302    FUNCTION(substr,             3, 0, 0, substrFunc       ),
131303    FUNCTION(substring,          2, 0, 0, substrFunc       ),
131304    FUNCTION(substring,          3, 0, 0, substrFunc       ),
131305    WAGGREGATE(sum,   1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0),
131306    WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0),
131307    WAGGREGATE(avg,   1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0),
131308    WAGGREGATE(count, 0,0,0, countStep,
131309        countFinalize, countFinalize, countInverse,
131310        SQLITE_FUNC_COUNT|SQLITE_FUNC_ANYORDER  ),
131311    WAGGREGATE(count, 1,0,0, countStep,
131312        countFinalize, countFinalize, countInverse, SQLITE_FUNC_ANYORDER ),
131313    WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep,
131314        groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
131315    WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep,
131316        groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
131317    WAGGREGATE(string_agg,   2, 0, 0, groupConcatStep,
131318        groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
131319
131320    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
131321#ifdef SQLITE_CASE_SENSITIVE_LIKE
131322    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
131323    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
131324#else
131325    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
131326    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
131327#endif
131328#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
131329    FUNCTION(unknown,           -1, 0, 0, unknownFunc      ),
131330#endif
131331    FUNCTION(coalesce,           1, 0, 0, 0                ),
131332    FUNCTION(coalesce,           0, 0, 0, 0                ),
131333#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
131334    MFUNCTION(ceil,              1, xCeil,     ceilingFunc ),
131335    MFUNCTION(ceiling,           1, xCeil,     ceilingFunc ),
131336    MFUNCTION(floor,             1, xFloor,    ceilingFunc ),
131337#if SQLITE_HAVE_C99_MATH_FUNCS
131338    MFUNCTION(trunc,             1, trunc,     ceilingFunc ),
131339#endif
131340    FUNCTION(ln,                 1, 0, 0,      logFunc     ),
131341    FUNCTION(log,                1, 1, 0,      logFunc     ),
131342    FUNCTION(log10,              1, 1, 0,      logFunc     ),
131343    FUNCTION(log2,               1, 2, 0,      logFunc     ),
131344    FUNCTION(log,                2, 0, 0,      logFunc     ),
131345    MFUNCTION(exp,               1, exp,       math1Func   ),
131346    MFUNCTION(pow,               2, pow,       math2Func   ),
131347    MFUNCTION(power,             2, pow,       math2Func   ),
131348    MFUNCTION(mod,               2, fmod,      math2Func   ),
131349    MFUNCTION(acos,              1, acos,      math1Func   ),
131350    MFUNCTION(asin,              1, asin,      math1Func   ),
131351    MFUNCTION(atan,              1, atan,      math1Func   ),
131352    MFUNCTION(atan2,             2, atan2,     math2Func   ),
131353    MFUNCTION(cos,               1, cos,       math1Func   ),
131354    MFUNCTION(sin,               1, sin,       math1Func   ),
131355    MFUNCTION(tan,               1, tan,       math1Func   ),
131356    MFUNCTION(cosh,              1, cosh,      math1Func   ),
131357    MFUNCTION(sinh,              1, sinh,      math1Func   ),
131358    MFUNCTION(tanh,              1, tanh,      math1Func   ),
131359#if SQLITE_HAVE_C99_MATH_FUNCS
131360    MFUNCTION(acosh,             1, acosh,     math1Func   ),
131361    MFUNCTION(asinh,             1, asinh,     math1Func   ),
131362    MFUNCTION(atanh,             1, atanh,     math1Func   ),
131363#endif
131364    MFUNCTION(sqrt,              1, sqrt,      math1Func   ),
131365    MFUNCTION(radians,           1, degToRad,  math1Func   ),
131366    MFUNCTION(degrees,           1, radToDeg,  math1Func   ),
131367    FUNCTION(pi,                 0, 0, 0,      piFunc      ),
131368#endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
131369    FUNCTION(sign,               1, 0, 0,      signFunc    ),
131370    INLINE_FUNC(coalesce,       -1, INLINEFUNC_coalesce, 0 ),
131371    INLINE_FUNC(iif,             3, INLINEFUNC_iif,      0 ),
131372  };
131373#ifndef SQLITE_OMIT_ALTERTABLE
131374  sqlite3AlterFunctions();
131375#endif
131376  sqlite3WindowFunctions();
131377  sqlite3RegisterDateTimeFunctions();
131378  sqlite3RegisterJsonFunctions();
131379  sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
131380
131381#if 0  /* Enable to print out how the built-in functions are hashed */
131382  {
131383    int i;
131384    FuncDef *p;
131385    for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
131386      printf("FUNC-HASH %02d:", i);
131387      for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
131388        int n = sqlite3Strlen30(p->zName);
131389        int h = p->zName[0] + n;
131390        assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
131391        printf(" %s(%d)", p->zName, h);
131392      }
131393      printf("\n");
131394    }
131395  }
131396#endif
131397}
131398
131399/************** End of func.c ************************************************/
131400/************** Begin file fkey.c ********************************************/
131401/*
131402**
131403** The author disclaims copyright to this source code.  In place of
131404** a legal notice, here is a blessing:
131405**
131406**    May you do good and not evil.
131407**    May you find forgiveness for yourself and forgive others.
131408**    May you share freely, never taking more than you give.
131409**
131410*************************************************************************
131411** This file contains code used by the compiler to add foreign key
131412** support to compiled SQL statements.
131413*/
131414/* #include "sqliteInt.h" */
131415
131416#ifndef SQLITE_OMIT_FOREIGN_KEY
131417#ifndef SQLITE_OMIT_TRIGGER
131418
131419/*
131420** Deferred and Immediate FKs
131421** --------------------------
131422**
131423** Foreign keys in SQLite come in two flavours: deferred and immediate.
131424** If an immediate foreign key constraint is violated,
131425** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
131426** statement transaction rolled back. If a
131427** deferred foreign key constraint is violated, no action is taken
131428** immediately. However if the application attempts to commit the
131429** transaction before fixing the constraint violation, the attempt fails.
131430**
131431** Deferred constraints are implemented using a simple counter associated
131432** with the database handle. The counter is set to zero each time a
131433** database transaction is opened. Each time a statement is executed
131434** that causes a foreign key violation, the counter is incremented. Each
131435** time a statement is executed that removes an existing violation from
131436** the database, the counter is decremented. When the transaction is
131437** committed, the commit fails if the current value of the counter is
131438** greater than zero. This scheme has two big drawbacks:
131439**
131440**   * When a commit fails due to a deferred foreign key constraint,
131441**     there is no way to tell which foreign constraint is not satisfied,
131442**     or which row it is not satisfied for.
131443**
131444**   * If the database contains foreign key violations when the
131445**     transaction is opened, this may cause the mechanism to malfunction.
131446**
131447** Despite these problems, this approach is adopted as it seems simpler
131448** than the alternatives.
131449**
131450** INSERT operations:
131451**
131452**   I.1) For each FK for which the table is the child table, search
131453**        the parent table for a match. If none is found increment the
131454**        constraint counter.
131455**
131456**   I.2) For each FK for which the table is the parent table,
131457**        search the child table for rows that correspond to the new
131458**        row in the parent table. Decrement the counter for each row
131459**        found (as the constraint is now satisfied).
131460**
131461** DELETE operations:
131462**
131463**   D.1) For each FK for which the table is the child table,
131464**        search the parent table for a row that corresponds to the
131465**        deleted row in the child table. If such a row is not found,
131466**        decrement the counter.
131467**
131468**   D.2) For each FK for which the table is the parent table, search
131469**        the child table for rows that correspond to the deleted row
131470**        in the parent table. For each found increment the counter.
131471**
131472** UPDATE operations:
131473**
131474**   An UPDATE command requires that all 4 steps above are taken, but only
131475**   for FK constraints for which the affected columns are actually
131476**   modified (values must be compared at runtime).
131477**
131478** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
131479** This simplifies the implementation a bit.
131480**
131481** For the purposes of immediate FK constraints, the OR REPLACE conflict
131482** resolution is considered to delete rows before the new row is inserted.
131483** If a delete caused by OR REPLACE violates an FK constraint, an exception
131484** is thrown, even if the FK constraint would be satisfied after the new
131485** row is inserted.
131486**
131487** Immediate constraints are usually handled similarly. The only difference
131488** is that the counter used is stored as part of each individual statement
131489** object (struct Vdbe). If, after the statement has run, its immediate
131490** constraint counter is greater than zero,
131491** it returns SQLITE_CONSTRAINT_FOREIGNKEY
131492** and the statement transaction is rolled back. An exception is an INSERT
131493** statement that inserts a single row only (no triggers). In this case,
131494** instead of using a counter, an exception is thrown immediately if the
131495** INSERT violates a foreign key constraint. This is necessary as such
131496** an INSERT does not open a statement transaction.
131497**
131498** TODO: How should dropping a table be handled? How should renaming a
131499** table be handled?
131500**
131501**
131502** Query API Notes
131503** ---------------
131504**
131505** Before coding an UPDATE or DELETE row operation, the code-generator
131506** for those two operations needs to know whether or not the operation
131507** requires any FK processing and, if so, which columns of the original
131508** row are required by the FK processing VDBE code (i.e. if FKs were
131509** implemented using triggers, which of the old.* columns would be
131510** accessed). No information is required by the code-generator before
131511** coding an INSERT operation. The functions used by the UPDATE/DELETE
131512** generation code to query for this information are:
131513**
131514**   sqlite3FkRequired() - Test to see if FK processing is required.
131515**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
131516**
131517**
131518** Externally accessible module functions
131519** --------------------------------------
131520**
131521**   sqlite3FkCheck()    - Check for foreign key violations.
131522**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
131523**   sqlite3FkDelete()   - Delete an FKey structure.
131524*/
131525
131526/*
131527** VDBE Calling Convention
131528** -----------------------
131529**
131530** Example:
131531**
131532**   For the following INSERT statement:
131533**
131534**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
131535**     INSERT INTO t1 VALUES(1, 2, 3.1);
131536**
131537**   Register (x):        2    (type integer)
131538**   Register (x+1):      1    (type integer)
131539**   Register (x+2):      NULL (type NULL)
131540**   Register (x+3):      3.1  (type real)
131541*/
131542
131543/*
131544** A foreign key constraint requires that the key columns in the parent
131545** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
131546** Given that pParent is the parent table for foreign key constraint pFKey,
131547** search the schema for a unique index on the parent key columns.
131548**
131549** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
131550** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
131551** is set to point to the unique index.
131552**
131553** If the parent key consists of a single column (the foreign key constraint
131554** is not a composite foreign key), output variable *paiCol is set to NULL.
131555** Otherwise, it is set to point to an allocated array of size N, where
131556** N is the number of columns in the parent key. The first element of the
131557** array is the index of the child table column that is mapped by the FK
131558** constraint to the parent table column stored in the left-most column
131559** of index *ppIdx. The second element of the array is the index of the
131560** child table column that corresponds to the second left-most column of
131561** *ppIdx, and so on.
131562**
131563** If the required index cannot be found, either because:
131564**
131565**   1) The named parent key columns do not exist, or
131566**
131567**   2) The named parent key columns do exist, but are not subject to a
131568**      UNIQUE or PRIMARY KEY constraint, or
131569**
131570**   3) No parent key columns were provided explicitly as part of the
131571**      foreign key definition, and the parent table does not have a
131572**      PRIMARY KEY, or
131573**
131574**   4) No parent key columns were provided explicitly as part of the
131575**      foreign key definition, and the PRIMARY KEY of the parent table
131576**      consists of a different number of columns to the child key in
131577**      the child table.
131578**
131579** then non-zero is returned, and a "foreign key mismatch" error loaded
131580** into pParse. If an OOM error occurs, non-zero is returned and the
131581** pParse->db->mallocFailed flag is set.
131582*/
131583SQLITE_PRIVATE int sqlite3FkLocateIndex(
131584  Parse *pParse,                  /* Parse context to store any error in */
131585  Table *pParent,                 /* Parent table of FK constraint pFKey */
131586  FKey *pFKey,                    /* Foreign key to find index for */
131587  Index **ppIdx,                  /* OUT: Unique index on parent table */
131588  int **paiCol                    /* OUT: Map of index columns in pFKey */
131589){
131590  Index *pIdx = 0;                    /* Value to return via *ppIdx */
131591  int *aiCol = 0;                     /* Value to return via *paiCol */
131592  int nCol = pFKey->nCol;             /* Number of columns in parent key */
131593  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
131594
131595  /* The caller is responsible for zeroing output parameters. */
131596  assert( ppIdx && *ppIdx==0 );
131597  assert( !paiCol || *paiCol==0 );
131598  assert( pParse );
131599
131600  /* If this is a non-composite (single column) foreign key, check if it
131601  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
131602  ** and *paiCol set to zero and return early.
131603  **
131604  ** Otherwise, for a composite foreign key (more than one column), allocate
131605  ** space for the aiCol array (returned via output parameter *paiCol).
131606  ** Non-composite foreign keys do not require the aiCol array.
131607  */
131608  if( nCol==1 ){
131609    /* The FK maps to the IPK if any of the following are true:
131610    **
131611    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
131612    **      mapped to the primary key of table pParent, or
131613    **   2) The FK is explicitly mapped to a column declared as INTEGER
131614    **      PRIMARY KEY.
131615    */
131616    if( pParent->iPKey>=0 ){
131617      if( !zKey ) return 0;
131618      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zCnName, zKey) ){
131619        return 0;
131620      }
131621    }
131622  }else if( paiCol ){
131623    assert( nCol>1 );
131624    aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
131625    if( !aiCol ) return 1;
131626    *paiCol = aiCol;
131627  }
131628
131629  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
131630    if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
131631      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
131632      ** of columns. If each indexed column corresponds to a foreign key
131633      ** column of pFKey, then this index is a winner.  */
131634
131635      if( zKey==0 ){
131636        /* If zKey is NULL, then this foreign key is implicitly mapped to
131637        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
131638        ** identified by the test.  */
131639        if( IsPrimaryKeyIndex(pIdx) ){
131640          if( aiCol ){
131641            int i;
131642            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
131643          }
131644          break;
131645        }
131646      }else{
131647        /* If zKey is non-NULL, then this foreign key was declared to
131648        ** map to an explicit list of columns in table pParent. Check if this
131649        ** index matches those columns. Also, check that the index uses
131650        ** the default collation sequences for each column. */
131651        int i, j;
131652        for(i=0; i<nCol; i++){
131653          i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
131654          const char *zDfltColl;            /* Def. collation for column */
131655          char *zIdxCol;                    /* Name of indexed column */
131656
131657          if( iCol<0 ) break; /* No foreign keys against expression indexes */
131658
131659          /* If the index uses a collation sequence that is different from
131660          ** the default collation sequence for the column, this index is
131661          ** unusable. Bail out early in this case.  */
131662          zDfltColl = sqlite3ColumnColl(&pParent->aCol[iCol]);
131663          if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
131664          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
131665
131666          zIdxCol = pParent->aCol[iCol].zCnName;
131667          for(j=0; j<nCol; j++){
131668            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
131669              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
131670              break;
131671            }
131672          }
131673          if( j==nCol ) break;
131674        }
131675        if( i==nCol ) break;      /* pIdx is usable */
131676      }
131677    }
131678  }
131679
131680  if( !pIdx ){
131681    if( !pParse->disableTriggers ){
131682      sqlite3ErrorMsg(pParse,
131683           "foreign key mismatch - \"%w\" referencing \"%w\"",
131684           pFKey->pFrom->zName, pFKey->zTo);
131685    }
131686    sqlite3DbFree(pParse->db, aiCol);
131687    return 1;
131688  }
131689
131690  *ppIdx = pIdx;
131691  return 0;
131692}
131693
131694/*
131695** This function is called when a row is inserted into or deleted from the
131696** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
131697** on the child table of pFKey, this function is invoked twice for each row
131698** affected - once to "delete" the old row, and then again to "insert" the
131699** new row.
131700**
131701** Each time it is called, this function generates VDBE code to locate the
131702** row in the parent table that corresponds to the row being inserted into
131703** or deleted from the child table. If the parent row can be found, no
131704** special action is taken. Otherwise, if the parent row can *not* be
131705** found in the parent table:
131706**
131707**   Operation | FK type   | Action taken
131708**   --------------------------------------------------------------------------
131709**   INSERT      immediate   Increment the "immediate constraint counter".
131710**
131711**   DELETE      immediate   Decrement the "immediate constraint counter".
131712**
131713**   INSERT      deferred    Increment the "deferred constraint counter".
131714**
131715**   DELETE      deferred    Decrement the "deferred constraint counter".
131716**
131717** These operations are identified in the comment at the top of this file
131718** (fkey.c) as "I.1" and "D.1".
131719*/
131720static void fkLookupParent(
131721  Parse *pParse,        /* Parse context */
131722  int iDb,              /* Index of database housing pTab */
131723  Table *pTab,          /* Parent table of FK pFKey */
131724  Index *pIdx,          /* Unique index on parent key columns in pTab */
131725  FKey *pFKey,          /* Foreign key constraint */
131726  int *aiCol,           /* Map from parent key columns to child table columns */
131727  int regData,          /* Address of array containing child table row */
131728  int nIncr,            /* Increment constraint counter by this */
131729  int isIgnore          /* If true, pretend pTab contains all NULL values */
131730){
131731  int i;                                    /* Iterator variable */
131732  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
131733  int iCur = pParse->nTab - 1;              /* Cursor number to use */
131734  int iOk = sqlite3VdbeMakeLabel(pParse);   /* jump here if parent key found */
131735
131736  sqlite3VdbeVerifyAbortable(v,
131737    (!pFKey->isDeferred
131738      && !(pParse->db->flags & SQLITE_DeferFKs)
131739      && !pParse->pToplevel
131740      && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);
131741
131742  /* If nIncr is less than zero, then check at runtime if there are any
131743  ** outstanding constraints to resolve. If there are not, there is no need
131744  ** to check if deleting this row resolves any outstanding violations.
131745  **
131746  ** Check if any of the key columns in the child table row are NULL. If
131747  ** any are, then the constraint is considered satisfied. No need to
131748  ** search for a matching row in the parent table.  */
131749  if( nIncr<0 ){
131750    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
131751    VdbeCoverage(v);
131752  }
131753  for(i=0; i<pFKey->nCol; i++){
131754    int iReg = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i]) + regData + 1;
131755    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
131756  }
131757
131758  if( isIgnore==0 ){
131759    if( pIdx==0 ){
131760      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
131761      ** column of the parent table (table pTab).  */
131762      int iMustBeInt;               /* Address of MustBeInt instruction */
131763      int regTemp = sqlite3GetTempReg(pParse);
131764
131765      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
131766      ** apply the affinity of the parent key). If this fails, then there
131767      ** is no matching parent key. Before using MustBeInt, make a copy of
131768      ** the value. Otherwise, the value inserted into the child key column
131769      ** will have INTEGER affinity applied to it, which may not be correct.  */
131770      sqlite3VdbeAddOp2(v, OP_SCopy,
131771        sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[0])+1+regData, regTemp);
131772      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
131773      VdbeCoverage(v);
131774
131775      /* If the parent table is the same as the child table, and we are about
131776      ** to increment the constraint-counter (i.e. this is an INSERT operation),
131777      ** then check if the row being inserted matches itself. If so, do not
131778      ** increment the constraint-counter.  */
131779      if( pTab==pFKey->pFrom && nIncr==1 ){
131780        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
131781        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
131782      }
131783
131784      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
131785      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
131786      sqlite3VdbeGoto(v, iOk);
131787      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
131788      sqlite3VdbeJumpHere(v, iMustBeInt);
131789      sqlite3ReleaseTempReg(pParse, regTemp);
131790    }else{
131791      int nCol = pFKey->nCol;
131792      int regTemp = sqlite3GetTempRange(pParse, nCol);
131793
131794      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
131795      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
131796      for(i=0; i<nCol; i++){
131797        sqlite3VdbeAddOp2(v, OP_Copy,
131798               sqlite3TableColumnToStorage(pFKey->pFrom, aiCol[i])+1+regData,
131799               regTemp+i);
131800      }
131801
131802      /* If the parent table is the same as the child table, and we are about
131803      ** to increment the constraint-counter (i.e. this is an INSERT operation),
131804      ** then check if the row being inserted matches itself. If so, do not
131805      ** increment the constraint-counter.
131806      **
131807      ** If any of the parent-key values are NULL, then the row cannot match
131808      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
131809      ** of the parent-key values are NULL (at this point it is known that
131810      ** none of the child key values are).
131811      */
131812      if( pTab==pFKey->pFrom && nIncr==1 ){
131813        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
131814        for(i=0; i<nCol; i++){
131815          int iChild = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i])
131816                              +1+regData;
131817          int iParent = 1+regData;
131818          iParent += sqlite3TableColumnToStorage(pIdx->pTable,
131819                                                 pIdx->aiColumn[i]);
131820          assert( pIdx->aiColumn[i]>=0 );
131821          assert( aiCol[i]!=pTab->iPKey );
131822          if( pIdx->aiColumn[i]==pTab->iPKey ){
131823            /* The parent key is a composite key that includes the IPK column */
131824            iParent = regData;
131825          }
131826          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
131827          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
131828        }
131829        sqlite3VdbeGoto(v, iOk);
131830      }
131831
131832      sqlite3VdbeAddOp4(v, OP_Affinity, regTemp, nCol, 0,
131833                        sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
131834      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regTemp, nCol);
131835      VdbeCoverage(v);
131836      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
131837    }
131838  }
131839
131840  if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
131841   && !pParse->pToplevel
131842   && !pParse->isMultiWrite
131843  ){
131844    /* Special case: If this is an INSERT statement that will insert exactly
131845    ** one row into the table, raise a constraint immediately instead of
131846    ** incrementing a counter. This is necessary as the VM code is being
131847    ** generated for will not open a statement transaction.  */
131848    assert( nIncr==1 );
131849    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
131850        OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
131851  }else{
131852    if( nIncr>0 && pFKey->isDeferred==0 ){
131853      sqlite3MayAbort(pParse);
131854    }
131855    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
131856  }
131857
131858  sqlite3VdbeResolveLabel(v, iOk);
131859  sqlite3VdbeAddOp1(v, OP_Close, iCur);
131860}
131861
131862
131863/*
131864** Return an Expr object that refers to a memory register corresponding
131865** to column iCol of table pTab.
131866**
131867** regBase is the first of an array of register that contains the data
131868** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
131869** column.  regBase+2 holds the second column, and so forth.
131870*/
131871static Expr *exprTableRegister(
131872  Parse *pParse,     /* Parsing and code generating context */
131873  Table *pTab,       /* The table whose content is at r[regBase]... */
131874  int regBase,       /* Contents of table pTab */
131875  i16 iCol           /* Which column of pTab is desired */
131876){
131877  Expr *pExpr;
131878  Column *pCol;
131879  const char *zColl;
131880  sqlite3 *db = pParse->db;
131881
131882  pExpr = sqlite3Expr(db, TK_REGISTER, 0);
131883  if( pExpr ){
131884    if( iCol>=0 && iCol!=pTab->iPKey ){
131885      pCol = &pTab->aCol[iCol];
131886      pExpr->iTable = regBase + sqlite3TableColumnToStorage(pTab,iCol) + 1;
131887      pExpr->affExpr = pCol->affinity;
131888      zColl = sqlite3ColumnColl(pCol);
131889      if( zColl==0 ) zColl = db->pDfltColl->zName;
131890      pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
131891    }else{
131892      pExpr->iTable = regBase;
131893      pExpr->affExpr = SQLITE_AFF_INTEGER;
131894    }
131895  }
131896  return pExpr;
131897}
131898
131899/*
131900** Return an Expr object that refers to column iCol of table pTab which
131901** has cursor iCur.
131902*/
131903static Expr *exprTableColumn(
131904  sqlite3 *db,      /* The database connection */
131905  Table *pTab,      /* The table whose column is desired */
131906  int iCursor,      /* The open cursor on the table */
131907  i16 iCol          /* The column that is wanted */
131908){
131909  Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
131910  if( pExpr ){
131911    assert( ExprUseYTab(pExpr) );
131912    pExpr->y.pTab = pTab;
131913    pExpr->iTable = iCursor;
131914    pExpr->iColumn = iCol;
131915  }
131916  return pExpr;
131917}
131918
131919/*
131920** This function is called to generate code executed when a row is deleted
131921** from the parent table of foreign key constraint pFKey and, if pFKey is
131922** deferred, when a row is inserted into the same table. When generating
131923** code for an SQL UPDATE operation, this function may be called twice -
131924** once to "delete" the old row and once to "insert" the new row.
131925**
131926** Parameter nIncr is passed -1 when inserting a row (as this may decrease
131927** the number of FK violations in the db) or +1 when deleting one (as this
131928** may increase the number of FK constraint problems).
131929**
131930** The code generated by this function scans through the rows in the child
131931** table that correspond to the parent table row being deleted or inserted.
131932** For each child row found, one of the following actions is taken:
131933**
131934**   Operation | FK type   | Action taken
131935**   --------------------------------------------------------------------------
131936**   DELETE      immediate   Increment the "immediate constraint counter".
131937**
131938**   INSERT      immediate   Decrement the "immediate constraint counter".
131939**
131940**   DELETE      deferred    Increment the "deferred constraint counter".
131941**
131942**   INSERT      deferred    Decrement the "deferred constraint counter".
131943**
131944** These operations are identified in the comment at the top of this file
131945** (fkey.c) as "I.2" and "D.2".
131946*/
131947static void fkScanChildren(
131948  Parse *pParse,                  /* Parse context */
131949  SrcList *pSrc,                  /* The child table to be scanned */
131950  Table *pTab,                    /* The parent table */
131951  Index *pIdx,                    /* Index on parent covering the foreign key */
131952  FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
131953  int *aiCol,                     /* Map from pIdx cols to child table cols */
131954  int regData,                    /* Parent row data starts here */
131955  int nIncr                       /* Amount to increment deferred counter by */
131956){
131957  sqlite3 *db = pParse->db;       /* Database handle */
131958  int i;                          /* Iterator variable */
131959  Expr *pWhere = 0;               /* WHERE clause to scan with */
131960  NameContext sNameContext;       /* Context used to resolve WHERE clause */
131961  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
131962  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
131963  Vdbe *v = sqlite3GetVdbe(pParse);
131964
131965  assert( pIdx==0 || pIdx->pTable==pTab );
131966  assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
131967  assert( pIdx!=0 || pFKey->nCol==1 );
131968  assert( pIdx!=0 || HasRowid(pTab) );
131969
131970  if( nIncr<0 ){
131971    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
131972    VdbeCoverage(v);
131973  }
131974
131975  /* Create an Expr object representing an SQL expression like:
131976  **
131977  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
131978  **
131979  ** The collation sequence used for the comparison should be that of
131980  ** the parent key columns. The affinity of the parent key column should
131981  ** be applied to each child key value before the comparison takes place.
131982  */
131983  for(i=0; i<pFKey->nCol; i++){
131984    Expr *pLeft;                  /* Value from parent table row */
131985    Expr *pRight;                 /* Column ref to child table */
131986    Expr *pEq;                    /* Expression (pLeft = pRight) */
131987    i16 iCol;                     /* Index of column in child table */
131988    const char *zCol;             /* Name of column in child table */
131989
131990    iCol = pIdx ? pIdx->aiColumn[i] : -1;
131991    pLeft = exprTableRegister(pParse, pTab, regData, iCol);
131992    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
131993    assert( iCol>=0 );
131994    zCol = pFKey->pFrom->aCol[iCol].zCnName;
131995    pRight = sqlite3Expr(db, TK_ID, zCol);
131996    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
131997    pWhere = sqlite3ExprAnd(pParse, pWhere, pEq);
131998  }
131999
132000  /* If the child table is the same as the parent table, then add terms
132001  ** to the WHERE clause that prevent this entry from being scanned.
132002  ** The added WHERE clause terms are like this:
132003  **
132004  **     $current_rowid!=rowid
132005  **     NOT( $current_a==a AND $current_b==b AND ... )
132006  **
132007  ** The first form is used for rowid tables.  The second form is used
132008  ** for WITHOUT ROWID tables. In the second form, the *parent* key is
132009  ** (a,b,...). Either the parent or primary key could be used to
132010  ** uniquely identify the current row, but the parent key is more convenient
132011  ** as the required values have already been loaded into registers
132012  ** by the caller.
132013  */
132014  if( pTab==pFKey->pFrom && nIncr>0 ){
132015    Expr *pNe;                    /* Expression (pLeft != pRight) */
132016    Expr *pLeft;                  /* Value from parent table row */
132017    Expr *pRight;                 /* Column ref to child table */
132018    if( HasRowid(pTab) ){
132019      pLeft = exprTableRegister(pParse, pTab, regData, -1);
132020      pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
132021      pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
132022    }else{
132023      Expr *pEq, *pAll = 0;
132024      assert( pIdx!=0 );
132025      for(i=0; i<pIdx->nKeyCol; i++){
132026        i16 iCol = pIdx->aiColumn[i];
132027        assert( iCol>=0 );
132028        pLeft = exprTableRegister(pParse, pTab, regData, iCol);
132029        pRight = sqlite3Expr(db, TK_ID, pTab->aCol[iCol].zCnName);
132030        pEq = sqlite3PExpr(pParse, TK_IS, pLeft, pRight);
132031        pAll = sqlite3ExprAnd(pParse, pAll, pEq);
132032      }
132033      pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
132034    }
132035    pWhere = sqlite3ExprAnd(pParse, pWhere, pNe);
132036  }
132037
132038  /* Resolve the references in the WHERE clause. */
132039  memset(&sNameContext, 0, sizeof(NameContext));
132040  sNameContext.pSrcList = pSrc;
132041  sNameContext.pParse = pParse;
132042  sqlite3ResolveExprNames(&sNameContext, pWhere);
132043
132044  /* Create VDBE to loop through the entries in pSrc that match the WHERE
132045  ** clause. For each row found, increment either the deferred or immediate
132046  ** foreign key constraint counter. */
132047  if( pParse->nErr==0 ){
132048    pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0, 0);
132049    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
132050    if( pWInfo ){
132051      sqlite3WhereEnd(pWInfo);
132052    }
132053  }
132054
132055  /* Clean up the WHERE clause constructed above. */
132056  sqlite3ExprDelete(db, pWhere);
132057  if( iFkIfZero ){
132058    sqlite3VdbeJumpHereOrPopInst(v, iFkIfZero);
132059  }
132060}
132061
132062/*
132063** This function returns a linked list of FKey objects (connected by
132064** FKey.pNextTo) holding all children of table pTab.  For example,
132065** given the following schema:
132066**
132067**   CREATE TABLE t1(a PRIMARY KEY);
132068**   CREATE TABLE t2(b REFERENCES t1(a);
132069**
132070** Calling this function with table "t1" as an argument returns a pointer
132071** to the FKey structure representing the foreign key constraint on table
132072** "t2". Calling this function with "t2" as the argument would return a
132073** NULL pointer (as there are no FK constraints for which t2 is the parent
132074** table).
132075*/
132076SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
132077  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
132078}
132079
132080/*
132081** The second argument is a Trigger structure allocated by the
132082** fkActionTrigger() routine. This function deletes the Trigger structure
132083** and all of its sub-components.
132084**
132085** The Trigger structure or any of its sub-components may be allocated from
132086** the lookaside buffer belonging to database handle dbMem.
132087*/
132088static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
132089  if( p ){
132090    TriggerStep *pStep = p->step_list;
132091    sqlite3ExprDelete(dbMem, pStep->pWhere);
132092    sqlite3ExprListDelete(dbMem, pStep->pExprList);
132093    sqlite3SelectDelete(dbMem, pStep->pSelect);
132094    sqlite3ExprDelete(dbMem, p->pWhen);
132095    sqlite3DbFree(dbMem, p);
132096  }
132097}
132098
132099/*
132100** Clear the apTrigger[] cache of CASCADE triggers for all foreign keys
132101** in a particular database.  This needs to happen when the schema
132102** changes.
132103*/
132104SQLITE_PRIVATE void sqlite3FkClearTriggerCache(sqlite3 *db, int iDb){
132105  HashElem *k;
132106  Hash *pHash = &db->aDb[iDb].pSchema->tblHash;
132107  for(k=sqliteHashFirst(pHash); k; k=sqliteHashNext(k)){
132108    Table *pTab = sqliteHashData(k);
132109    FKey *pFKey;
132110    if( !IsOrdinaryTable(pTab) ) continue;
132111    for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
132112      fkTriggerDelete(db, pFKey->apTrigger[0]); pFKey->apTrigger[0] = 0;
132113      fkTriggerDelete(db, pFKey->apTrigger[1]); pFKey->apTrigger[1] = 0;
132114    }
132115  }
132116}
132117
132118/*
132119** This function is called to generate code that runs when table pTab is
132120** being dropped from the database. The SrcList passed as the second argument
132121** to this function contains a single entry guaranteed to resolve to
132122** table pTab.
132123**
132124** Normally, no code is required. However, if either
132125**
132126**   (a) The table is the parent table of a FK constraint, or
132127**   (b) The table is the child table of a deferred FK constraint and it is
132128**       determined at runtime that there are outstanding deferred FK
132129**       constraint violations in the database,
132130**
132131** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
132132** the table from the database. Triggers are disabled while running this
132133** DELETE, but foreign key actions are not.
132134*/
132135SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
132136  sqlite3 *db = pParse->db;
132137  if( (db->flags&SQLITE_ForeignKeys) && IsOrdinaryTable(pTab) ){
132138    int iSkip = 0;
132139    Vdbe *v = sqlite3GetVdbe(pParse);
132140
132141    assert( v );                  /* VDBE has already been allocated */
132142    assert( IsOrdinaryTable(pTab) );
132143    if( sqlite3FkReferences(pTab)==0 ){
132144      /* Search for a deferred foreign key constraint for which this table
132145      ** is the child table. If one cannot be found, return without
132146      ** generating any VDBE code. If one can be found, then jump over
132147      ** the entire DELETE if there are no outstanding deferred constraints
132148      ** when this statement is run.  */
132149      FKey *p;
132150      for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
132151        if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
132152      }
132153      if( !p ) return;
132154      iSkip = sqlite3VdbeMakeLabel(pParse);
132155      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
132156    }
132157
132158    pParse->disableTriggers = 1;
132159    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0);
132160    pParse->disableTriggers = 0;
132161
132162    /* If the DELETE has generated immediate foreign key constraint
132163    ** violations, halt the VDBE and return an error at this point, before
132164    ** any modifications to the schema are made. This is because statement
132165    ** transactions are not able to rollback schema changes.
132166    **
132167    ** If the SQLITE_DeferFKs flag is set, then this is not required, as
132168    ** the statement transaction will not be rolled back even if FK
132169    ** constraints are violated.
132170    */
132171    if( (db->flags & SQLITE_DeferFKs)==0 ){
132172      sqlite3VdbeVerifyAbortable(v, OE_Abort);
132173      sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
132174      VdbeCoverage(v);
132175      sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
132176          OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
132177    }
132178
132179    if( iSkip ){
132180      sqlite3VdbeResolveLabel(v, iSkip);
132181    }
132182  }
132183}
132184
132185
132186/*
132187** The second argument points to an FKey object representing a foreign key
132188** for which pTab is the child table. An UPDATE statement against pTab
132189** is currently being processed. For each column of the table that is
132190** actually updated, the corresponding element in the aChange[] array
132191** is zero or greater (if a column is unmodified the corresponding element
132192** is set to -1). If the rowid column is modified by the UPDATE statement
132193** the bChngRowid argument is non-zero.
132194**
132195** This function returns true if any of the columns that are part of the
132196** child key for FK constraint *p are modified.
132197*/
132198static int fkChildIsModified(
132199  Table *pTab,                    /* Table being updated */
132200  FKey *p,                        /* Foreign key for which pTab is the child */
132201  int *aChange,                   /* Array indicating modified columns */
132202  int bChngRowid                  /* True if rowid is modified by this update */
132203){
132204  int i;
132205  for(i=0; i<p->nCol; i++){
132206    int iChildKey = p->aCol[i].iFrom;
132207    if( aChange[iChildKey]>=0 ) return 1;
132208    if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
132209  }
132210  return 0;
132211}
132212
132213/*
132214** The second argument points to an FKey object representing a foreign key
132215** for which pTab is the parent table. An UPDATE statement against pTab
132216** is currently being processed. For each column of the table that is
132217** actually updated, the corresponding element in the aChange[] array
132218** is zero or greater (if a column is unmodified the corresponding element
132219** is set to -1). If the rowid column is modified by the UPDATE statement
132220** the bChngRowid argument is non-zero.
132221**
132222** This function returns true if any of the columns that are part of the
132223** parent key for FK constraint *p are modified.
132224*/
132225static int fkParentIsModified(
132226  Table *pTab,
132227  FKey *p,
132228  int *aChange,
132229  int bChngRowid
132230){
132231  int i;
132232  for(i=0; i<p->nCol; i++){
132233    char *zKey = p->aCol[i].zCol;
132234    int iKey;
132235    for(iKey=0; iKey<pTab->nCol; iKey++){
132236      if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
132237        Column *pCol = &pTab->aCol[iKey];
132238        if( zKey ){
132239          if( 0==sqlite3StrICmp(pCol->zCnName, zKey) ) return 1;
132240        }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
132241          return 1;
132242        }
132243      }
132244    }
132245  }
132246  return 0;
132247}
132248
132249/*
132250** Return true if the parser passed as the first argument is being
132251** used to code a trigger that is really a "SET NULL" action belonging
132252** to trigger pFKey.
132253*/
132254static int isSetNullAction(Parse *pParse, FKey *pFKey){
132255  Parse *pTop = sqlite3ParseToplevel(pParse);
132256  if( pTop->pTriggerPrg ){
132257    Trigger *p = pTop->pTriggerPrg->pTrigger;
132258    if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
132259     || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
132260    ){
132261      assert( (pTop->db->flags & SQLITE_FkNoAction)==0 );
132262      return 1;
132263    }
132264  }
132265  return 0;
132266}
132267
132268/*
132269** This function is called when inserting, deleting or updating a row of
132270** table pTab to generate VDBE code to perform foreign key constraint
132271** processing for the operation.
132272**
132273** For a DELETE operation, parameter regOld is passed the index of the
132274** first register in an array of (pTab->nCol+1) registers containing the
132275** rowid of the row being deleted, followed by each of the column values
132276** of the row being deleted, from left to right. Parameter regNew is passed
132277** zero in this case.
132278**
132279** For an INSERT operation, regOld is passed zero and regNew is passed the
132280** first register of an array of (pTab->nCol+1) registers containing the new
132281** row data.
132282**
132283** For an UPDATE operation, this function is called twice. Once before
132284** the original record is deleted from the table using the calling convention
132285** described for DELETE. Then again after the original record is deleted
132286** but before the new record is inserted using the INSERT convention.
132287*/
132288SQLITE_PRIVATE void sqlite3FkCheck(
132289  Parse *pParse,                  /* Parse context */
132290  Table *pTab,                    /* Row is being deleted from this table */
132291  int regOld,                     /* Previous row data is stored here */
132292  int regNew,                     /* New row data is stored here */
132293  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
132294  int bChngRowid                  /* True if rowid is UPDATEd */
132295){
132296  sqlite3 *db = pParse->db;       /* Database handle */
132297  FKey *pFKey;                    /* Used to iterate through FKs */
132298  int iDb;                        /* Index of database containing pTab */
132299  const char *zDb;                /* Name of database containing pTab */
132300  int isIgnoreErrors = pParse->disableTriggers;
132301
132302  /* Exactly one of regOld and regNew should be non-zero. */
132303  assert( (regOld==0)!=(regNew==0) );
132304
132305  /* If foreign-keys are disabled, this function is a no-op. */
132306  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
132307  if( !IsOrdinaryTable(pTab) ) return;
132308
132309  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
132310  zDb = db->aDb[iDb].zDbSName;
132311
132312  /* Loop through all the foreign key constraints for which pTab is the
132313  ** child table (the table that the foreign key definition is part of).  */
132314  for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
132315    Table *pTo;                   /* Parent table of foreign key pFKey */
132316    Index *pIdx = 0;              /* Index on key columns in pTo */
132317    int *aiFree = 0;
132318    int *aiCol;
132319    int iCol;
132320    int i;
132321    int bIgnore = 0;
132322
132323    if( aChange
132324     && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
132325     && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
132326    ){
132327      continue;
132328    }
132329
132330    /* Find the parent table of this foreign key. Also find a unique index
132331    ** on the parent key columns in the parent table. If either of these
132332    ** schema items cannot be located, set an error in pParse and return
132333    ** early.  */
132334    if( pParse->disableTriggers ){
132335      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
132336    }else{
132337      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
132338    }
132339    if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
132340      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
132341      if( !isIgnoreErrors || db->mallocFailed ) return;
132342      if( pTo==0 ){
132343        /* If isIgnoreErrors is true, then a table is being dropped. In this
132344        ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
132345        ** before actually dropping it in order to check FK constraints.
132346        ** If the parent table of an FK constraint on the current table is
132347        ** missing, behave as if it is empty. i.e. decrement the relevant
132348        ** FK counter for each row of the current table with non-NULL keys.
132349        */
132350        Vdbe *v = sqlite3GetVdbe(pParse);
132351        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
132352        for(i=0; i<pFKey->nCol; i++){
132353          int iFromCol, iReg;
132354          iFromCol = pFKey->aCol[i].iFrom;
132355          iReg = sqlite3TableColumnToStorage(pFKey->pFrom,iFromCol) + regOld+1;
132356          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
132357        }
132358        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
132359      }
132360      continue;
132361    }
132362    assert( pFKey->nCol==1 || (aiFree && pIdx) );
132363
132364    if( aiFree ){
132365      aiCol = aiFree;
132366    }else{
132367      iCol = pFKey->aCol[0].iFrom;
132368      aiCol = &iCol;
132369    }
132370    for(i=0; i<pFKey->nCol; i++){
132371      if( aiCol[i]==pTab->iPKey ){
132372        aiCol[i] = -1;
132373      }
132374      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
132375#ifndef SQLITE_OMIT_AUTHORIZATION
132376      /* Request permission to read the parent key columns. If the
132377      ** authorization callback returns SQLITE_IGNORE, behave as if any
132378      ** values read from the parent table are NULL. */
132379      if( db->xAuth ){
132380        int rcauth;
132381        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zCnName;
132382        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
132383        bIgnore = (rcauth==SQLITE_IGNORE);
132384      }
132385#endif
132386    }
132387
132388    /* Take a shared-cache advisory read-lock on the parent table. Allocate
132389    ** a cursor to use to search the unique index on the parent key columns
132390    ** in the parent table.  */
132391    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
132392    pParse->nTab++;
132393
132394    if( regOld!=0 ){
132395      /* A row is being removed from the child table. Search for the parent.
132396      ** If the parent does not exist, removing the child row resolves an
132397      ** outstanding foreign key constraint violation. */
132398      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
132399    }
132400    if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
132401      /* A row is being added to the child table. If a parent row cannot
132402      ** be found, adding the child row has violated the FK constraint.
132403      **
132404      ** If this operation is being performed as part of a trigger program
132405      ** that is actually a "SET NULL" action belonging to this very
132406      ** foreign key, then omit this scan altogether. As all child key
132407      ** values are guaranteed to be NULL, it is not possible for adding
132408      ** this row to cause an FK violation.  */
132409      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
132410    }
132411
132412    sqlite3DbFree(db, aiFree);
132413  }
132414
132415  /* Loop through all the foreign key constraints that refer to this table.
132416  ** (the "child" constraints) */
132417  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
132418    Index *pIdx = 0;              /* Foreign key index for pFKey */
132419    SrcList *pSrc;
132420    int *aiCol = 0;
132421
132422    if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
132423      continue;
132424    }
132425
132426    if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
132427     && !pParse->pToplevel && !pParse->isMultiWrite
132428    ){
132429      assert( regOld==0 && regNew!=0 );
132430      /* Inserting a single row into a parent table cannot cause (or fix)
132431      ** an immediate foreign key violation. So do nothing in this case.  */
132432      continue;
132433    }
132434
132435    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
132436      if( !isIgnoreErrors || db->mallocFailed ) return;
132437      continue;
132438    }
132439    assert( aiCol || pFKey->nCol==1 );
132440
132441    /* Create a SrcList structure containing the child table.  We need the
132442    ** child table as a SrcList for sqlite3WhereBegin() */
132443    pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
132444    if( pSrc ){
132445      SrcItem *pItem = pSrc->a;
132446      pItem->pTab = pFKey->pFrom;
132447      pItem->zName = pFKey->pFrom->zName;
132448      pItem->pTab->nTabRef++;
132449      pItem->iCursor = pParse->nTab++;
132450
132451      if( regNew!=0 ){
132452        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
132453      }
132454      if( regOld!=0 ){
132455        int eAction = pFKey->aAction[aChange!=0];
132456        if( (db->flags & SQLITE_FkNoAction) ) eAction = OE_None;
132457
132458        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
132459        /* If this is a deferred FK constraint, or a CASCADE or SET NULL
132460        ** action applies, then any foreign key violations caused by
132461        ** removing the parent key will be rectified by the action trigger.
132462        ** So do not set the "may-abort" flag in this case.
132463        **
132464        ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
132465        ** may-abort flag will eventually be set on this statement anyway
132466        ** (when this function is called as part of processing the UPDATE
132467        ** within the action trigger).
132468        **
132469        ** Note 2: At first glance it may seem like SQLite could simply omit
132470        ** all OP_FkCounter related scans when either CASCADE or SET NULL
132471        ** applies. The trouble starts if the CASCADE or SET NULL action
132472        ** trigger causes other triggers or action rules attached to the
132473        ** child table to fire. In these cases the fk constraint counters
132474        ** might be set incorrectly if any OP_FkCounter related scans are
132475        ** omitted.  */
132476        if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
132477          sqlite3MayAbort(pParse);
132478        }
132479      }
132480      pItem->zName = 0;
132481      sqlite3SrcListDelete(db, pSrc);
132482    }
132483    sqlite3DbFree(db, aiCol);
132484  }
132485}
132486
132487#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
132488
132489/*
132490** This function is called before generating code to update or delete a
132491** row contained in table pTab.
132492*/
132493SQLITE_PRIVATE u32 sqlite3FkOldmask(
132494  Parse *pParse,                  /* Parse context */
132495  Table *pTab                     /* Table being modified */
132496){
132497  u32 mask = 0;
132498  if( pParse->db->flags&SQLITE_ForeignKeys && IsOrdinaryTable(pTab) ){
132499    FKey *p;
132500    int i;
132501    for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
132502      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
132503    }
132504    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
132505      Index *pIdx = 0;
132506      sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
132507      if( pIdx ){
132508        for(i=0; i<pIdx->nKeyCol; i++){
132509          assert( pIdx->aiColumn[i]>=0 );
132510          mask |= COLUMN_MASK(pIdx->aiColumn[i]);
132511        }
132512      }
132513    }
132514  }
132515  return mask;
132516}
132517
132518
132519/*
132520** This function is called before generating code to update or delete a
132521** row contained in table pTab. If the operation is a DELETE, then
132522** parameter aChange is passed a NULL value. For an UPDATE, aChange points
132523** to an array of size N, where N is the number of columns in table pTab.
132524** If the i'th column is not modified by the UPDATE, then the corresponding
132525** entry in the aChange[] array is set to -1. If the column is modified,
132526** the value is 0 or greater. Parameter chngRowid is set to true if the
132527** UPDATE statement modifies the rowid fields of the table.
132528**
132529** If any foreign key processing will be required, this function returns
132530** non-zero. If there is no foreign key related processing, this function
132531** returns zero.
132532**
132533** For an UPDATE, this function returns 2 if:
132534**
132535**   * There are any FKs for which pTab is the child and the parent table
132536**     and any FK processing at all is required (even of a different FK), or
132537**
132538**   * the UPDATE modifies one or more parent keys for which the action is
132539**     not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
132540**
132541** Or, assuming some other foreign key processing is required, 1.
132542*/
132543SQLITE_PRIVATE int sqlite3FkRequired(
132544  Parse *pParse,                  /* Parse context */
132545  Table *pTab,                    /* Table being modified */
132546  int *aChange,                   /* Non-NULL for UPDATE operations */
132547  int chngRowid                   /* True for UPDATE that affects rowid */
132548){
132549  int eRet = 1;                   /* Value to return if bHaveFK is true */
132550  int bHaveFK = 0;                /* If FK processing is required */
132551  if( pParse->db->flags&SQLITE_ForeignKeys && IsOrdinaryTable(pTab) ){
132552    if( !aChange ){
132553      /* A DELETE operation. Foreign key processing is required if the
132554      ** table in question is either the child or parent table for any
132555      ** foreign key constraint.  */
132556      bHaveFK = (sqlite3FkReferences(pTab) || pTab->u.tab.pFKey);
132557    }else{
132558      /* This is an UPDATE. Foreign key processing is only required if the
132559      ** operation modifies one or more child or parent key columns. */
132560      FKey *p;
132561
132562      /* Check if any child key columns are being modified. */
132563      for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
132564        if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
132565          if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) eRet = 2;
132566          bHaveFK = 1;
132567        }
132568      }
132569
132570      /* Check if any parent key columns are being modified. */
132571      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
132572        if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
132573          if( (pParse->db->flags & SQLITE_FkNoAction)==0
132574           && p->aAction[1]!=OE_None
132575          ){
132576            return 2;
132577          }
132578          bHaveFK = 1;
132579        }
132580      }
132581    }
132582  }
132583  return bHaveFK ? eRet : 0;
132584}
132585
132586/*
132587** This function is called when an UPDATE or DELETE operation is being
132588** compiled on table pTab, which is the parent table of foreign-key pFKey.
132589** If the current operation is an UPDATE, then the pChanges parameter is
132590** passed a pointer to the list of columns being modified. If it is a
132591** DELETE, pChanges is passed a NULL pointer.
132592**
132593** It returns a pointer to a Trigger structure containing a trigger
132594** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
132595** If the action is "NO ACTION" then a NULL pointer is returned (these actions
132596** require no special handling by the triggers sub-system, code for them is
132597** created by fkScanChildren()).
132598**
132599** For example, if pFKey is the foreign key and pTab is table "p" in
132600** the following schema:
132601**
132602**   CREATE TABLE p(pk PRIMARY KEY);
132603**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
132604**
132605** then the returned trigger structure is equivalent to:
132606**
132607**   CREATE TRIGGER ... DELETE ON p BEGIN
132608**     DELETE FROM c WHERE ck = old.pk;
132609**   END;
132610**
132611** The returned pointer is cached as part of the foreign key object. It
132612** is eventually freed along with the rest of the foreign key object by
132613** sqlite3FkDelete().
132614*/
132615static Trigger *fkActionTrigger(
132616  Parse *pParse,                  /* Parse context */
132617  Table *pTab,                    /* Table being updated or deleted from */
132618  FKey *pFKey,                    /* Foreign key to get action for */
132619  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
132620){
132621  sqlite3 *db = pParse->db;       /* Database handle */
132622  int action;                     /* One of OE_None, OE_Cascade etc. */
132623  Trigger *pTrigger;              /* Trigger definition to return */
132624  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
132625
132626  action = pFKey->aAction[iAction];
132627  if( (db->flags & SQLITE_FkNoAction) ) action = OE_None;
132628  if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
132629    return 0;
132630  }
132631  pTrigger = pFKey->apTrigger[iAction];
132632
132633  if( action!=OE_None && !pTrigger ){
132634    char const *zFrom;            /* Name of child table */
132635    int nFrom;                    /* Length in bytes of zFrom */
132636    Index *pIdx = 0;              /* Parent key index for this FK */
132637    int *aiCol = 0;               /* child table cols -> parent key cols */
132638    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
132639    Expr *pWhere = 0;             /* WHERE clause of trigger step */
132640    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
132641    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
132642    int i;                        /* Iterator variable */
132643    Expr *pWhen = 0;              /* WHEN clause for the trigger */
132644
132645    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
132646    assert( aiCol || pFKey->nCol==1 );
132647
132648    for(i=0; i<pFKey->nCol; i++){
132649      Token tOld = { "old", 3 };  /* Literal "old" token */
132650      Token tNew = { "new", 3 };  /* Literal "new" token */
132651      Token tFromCol;             /* Name of column in child table */
132652      Token tToCol;               /* Name of column in parent table */
132653      int iFromCol;               /* Idx of column in child table */
132654      Expr *pEq;                  /* tFromCol = OLD.tToCol */
132655
132656      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
132657      assert( iFromCol>=0 );
132658      assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
132659      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
132660      sqlite3TokenInit(&tToCol,
132661                   pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zCnName);
132662      sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zCnName);
132663
132664      /* Create the expression "OLD.zToCol = zFromCol". It is important
132665      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
132666      ** that the affinity and collation sequence associated with the
132667      ** parent table are used for the comparison. */
132668      pEq = sqlite3PExpr(pParse, TK_EQ,
132669          sqlite3PExpr(pParse, TK_DOT,
132670            sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
132671            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
132672          sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
132673      );
132674      pWhere = sqlite3ExprAnd(pParse, pWhere, pEq);
132675
132676      /* For ON UPDATE, construct the next term of the WHEN clause.
132677      ** The final WHEN clause will be like this:
132678      **
132679      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
132680      */
132681      if( pChanges ){
132682        pEq = sqlite3PExpr(pParse, TK_IS,
132683            sqlite3PExpr(pParse, TK_DOT,
132684              sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
132685              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
132686            sqlite3PExpr(pParse, TK_DOT,
132687              sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
132688              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
132689            );
132690        pWhen = sqlite3ExprAnd(pParse, pWhen, pEq);
132691      }
132692
132693      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
132694        Expr *pNew;
132695        if( action==OE_Cascade ){
132696          pNew = sqlite3PExpr(pParse, TK_DOT,
132697            sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
132698            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
132699        }else if( action==OE_SetDflt ){
132700          Column *pCol = pFKey->pFrom->aCol + iFromCol;
132701          Expr *pDflt;
132702          if( pCol->colFlags & COLFLAG_GENERATED ){
132703            testcase( pCol->colFlags & COLFLAG_VIRTUAL );
132704            testcase( pCol->colFlags & COLFLAG_STORED );
132705            pDflt = 0;
132706          }else{
132707            pDflt = sqlite3ColumnExpr(pFKey->pFrom, pCol);
132708          }
132709          if( pDflt ){
132710            pNew = sqlite3ExprDup(db, pDflt, 0);
132711          }else{
132712            pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
132713          }
132714        }else{
132715          pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
132716        }
132717        pList = sqlite3ExprListAppend(pParse, pList, pNew);
132718        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
132719      }
132720    }
132721    sqlite3DbFree(db, aiCol);
132722
132723    zFrom = pFKey->pFrom->zName;
132724    nFrom = sqlite3Strlen30(zFrom);
132725
132726    if( action==OE_Restrict ){
132727      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
132728      SrcList *pSrc;
132729      Expr *pRaise;
132730
132731      pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
132732      if( pRaise ){
132733        pRaise->affExpr = OE_Abort;
132734      }
132735      pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
132736      if( pSrc ){
132737        assert( pSrc->nSrc==1 );
132738        pSrc->a[0].zName = sqlite3DbStrDup(db, zFrom);
132739        pSrc->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
132740      }
132741      pSelect = sqlite3SelectNew(pParse,
132742          sqlite3ExprListAppend(pParse, 0, pRaise),
132743          pSrc,
132744          pWhere,
132745          0, 0, 0, 0, 0
132746      );
132747      pWhere = 0;
132748    }
132749
132750    /* Disable lookaside memory allocation */
132751    DisableLookaside;
132752
132753    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
132754        sizeof(Trigger) +         /* struct Trigger */
132755        sizeof(TriggerStep) +     /* Single step in trigger program */
132756        nFrom + 1                 /* Space for pStep->zTarget */
132757    );
132758    if( pTrigger ){
132759      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
132760      pStep->zTarget = (char *)&pStep[1];
132761      memcpy((char *)pStep->zTarget, zFrom, nFrom);
132762
132763      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
132764      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
132765      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
132766      if( pWhen ){
132767        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
132768        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
132769      }
132770    }
132771
132772    /* Re-enable the lookaside buffer, if it was disabled earlier. */
132773    EnableLookaside;
132774
132775    sqlite3ExprDelete(db, pWhere);
132776    sqlite3ExprDelete(db, pWhen);
132777    sqlite3ExprListDelete(db, pList);
132778    sqlite3SelectDelete(db, pSelect);
132779    if( db->mallocFailed==1 ){
132780      fkTriggerDelete(db, pTrigger);
132781      return 0;
132782    }
132783    assert( pStep!=0 );
132784    assert( pTrigger!=0 );
132785
132786    switch( action ){
132787      case OE_Restrict:
132788        pStep->op = TK_SELECT;
132789        break;
132790      case OE_Cascade:
132791        if( !pChanges ){
132792          pStep->op = TK_DELETE;
132793          break;
132794        }
132795        /* no break */ deliberate_fall_through
132796      default:
132797        pStep->op = TK_UPDATE;
132798    }
132799    pStep->pTrig = pTrigger;
132800    pTrigger->pSchema = pTab->pSchema;
132801    pTrigger->pTabSchema = pTab->pSchema;
132802    pFKey->apTrigger[iAction] = pTrigger;
132803    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
132804  }
132805
132806  return pTrigger;
132807}
132808
132809/*
132810** This function is called when deleting or updating a row to implement
132811** any required CASCADE, SET NULL or SET DEFAULT actions.
132812*/
132813SQLITE_PRIVATE void sqlite3FkActions(
132814  Parse *pParse,                  /* Parse context */
132815  Table *pTab,                    /* Table being updated or deleted from */
132816  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
132817  int regOld,                     /* Address of array containing old row */
132818  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
132819  int bChngRowid                  /* True if rowid is UPDATEd */
132820){
132821  /* If foreign-key support is enabled, iterate through all FKs that
132822  ** refer to table pTab. If there is an action associated with the FK
132823  ** for this operation (either update or delete), invoke the associated
132824  ** trigger sub-program.  */
132825  if( pParse->db->flags&SQLITE_ForeignKeys ){
132826    FKey *pFKey;                  /* Iterator variable */
132827    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
132828      if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
132829        Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
132830        if( pAct ){
132831          sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
132832        }
132833      }
132834    }
132835  }
132836}
132837
132838#endif /* ifndef SQLITE_OMIT_TRIGGER */
132839
132840/*
132841** Free all memory associated with foreign key definitions attached to
132842** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
132843** hash table.
132844*/
132845SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
132846  FKey *pFKey;                    /* Iterator variable */
132847  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
132848
132849  assert( IsOrdinaryTable(pTab) );
132850  assert( db!=0 );
132851  for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pNext){
132852    assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
132853
132854    /* Remove the FK from the fkeyHash hash table. */
132855    if( db->pnBytesFreed==0 ){
132856      if( pFKey->pPrevTo ){
132857        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
132858      }else{
132859        const char *z = (pFKey->pNextTo ? pFKey->pNextTo->zTo : pFKey->zTo);
132860        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, pFKey->pNextTo);
132861      }
132862      if( pFKey->pNextTo ){
132863        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
132864      }
132865    }
132866
132867    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
132868    ** classified as either immediate or deferred.
132869    */
132870    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
132871
132872    /* Delete any triggers created to implement actions for this FK. */
132873#ifndef SQLITE_OMIT_TRIGGER
132874    fkTriggerDelete(db, pFKey->apTrigger[0]);
132875    fkTriggerDelete(db, pFKey->apTrigger[1]);
132876#endif
132877
132878    pNext = pFKey->pNextFrom;
132879    sqlite3DbFree(db, pFKey);
132880  }
132881}
132882#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
132883
132884/************** End of fkey.c ************************************************/
132885/************** Begin file insert.c ******************************************/
132886/*
132887** 2001 September 15
132888**
132889** The author disclaims copyright to this source code.  In place of
132890** a legal notice, here is a blessing:
132891**
132892**    May you do good and not evil.
132893**    May you find forgiveness for yourself and forgive others.
132894**    May you share freely, never taking more than you give.
132895**
132896*************************************************************************
132897** This file contains C code routines that are called by the parser
132898** to handle INSERT statements in SQLite.
132899*/
132900/* #include "sqliteInt.h" */
132901
132902/*
132903** Generate code that will
132904**
132905**   (1) acquire a lock for table pTab then
132906**   (2) open pTab as cursor iCur.
132907**
132908** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
132909** for that table that is actually opened.
132910*/
132911SQLITE_PRIVATE void sqlite3OpenTable(
132912  Parse *pParse,  /* Generate code into this VDBE */
132913  int iCur,       /* The cursor number of the table */
132914  int iDb,        /* The database index in sqlite3.aDb[] */
132915  Table *pTab,    /* The table to be opened */
132916  int opcode      /* OP_OpenRead or OP_OpenWrite */
132917){
132918  Vdbe *v;
132919  assert( !IsVirtual(pTab) );
132920  assert( pParse->pVdbe!=0 );
132921  v = pParse->pVdbe;
132922  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
132923  if( !pParse->db->noSharedCache ){
132924    sqlite3TableLock(pParse, iDb, pTab->tnum,
132925                     (opcode==OP_OpenWrite)?1:0, pTab->zName);
132926  }
132927  if( HasRowid(pTab) ){
132928    sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
132929    VdbeComment((v, "%s", pTab->zName));
132930  }else{
132931    Index *pPk = sqlite3PrimaryKeyIndex(pTab);
132932    assert( pPk!=0 );
132933    assert( pPk->tnum==pTab->tnum || CORRUPT_DB );
132934    sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
132935    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
132936    VdbeComment((v, "%s", pTab->zName));
132937  }
132938}
132939
132940/*
132941** Return a pointer to the column affinity string associated with index
132942** pIdx. A column affinity string has one character for each column in
132943** the table, according to the affinity of the column:
132944**
132945**  Character      Column affinity
132946**  ------------------------------
132947**  'A'            BLOB
132948**  'B'            TEXT
132949**  'C'            NUMERIC
132950**  'D'            INTEGER
132951**  'F'            REAL
132952**
132953** An extra 'D' is appended to the end of the string to cover the
132954** rowid that appears as the last column in every index.
132955**
132956** Memory for the buffer containing the column index affinity string
132957** is managed along with the rest of the Index structure. It will be
132958** released when sqlite3DeleteIndex() is called.
132959*/
132960static SQLITE_NOINLINE const char *computeIndexAffStr(sqlite3 *db, Index *pIdx){
132961  /* The first time a column affinity string for a particular index is
132962  ** required, it is allocated and populated here. It is then stored as
132963  ** a member of the Index structure for subsequent use.
132964  **
132965  ** The column affinity string will eventually be deleted by
132966  ** sqliteDeleteIndex() when the Index structure itself is cleaned
132967  ** up.
132968  */
132969  int n;
132970  Table *pTab = pIdx->pTable;
132971  pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
132972  if( !pIdx->zColAff ){
132973    sqlite3OomFault(db);
132974    return 0;
132975  }
132976  for(n=0; n<pIdx->nColumn; n++){
132977    i16 x = pIdx->aiColumn[n];
132978    char aff;
132979    if( x>=0 ){
132980      aff = pTab->aCol[x].affinity;
132981    }else if( x==XN_ROWID ){
132982      aff = SQLITE_AFF_INTEGER;
132983    }else{
132984      assert( x==XN_EXPR );
132985      assert( pIdx->bHasExpr );
132986      assert( pIdx->aColExpr!=0 );
132987      aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
132988    }
132989    if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
132990    if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
132991    pIdx->zColAff[n] = aff;
132992  }
132993  pIdx->zColAff[n] = 0;
132994  return pIdx->zColAff;
132995}
132996SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
132997  if( !pIdx->zColAff ) return computeIndexAffStr(db, pIdx);
132998  return pIdx->zColAff;
132999}
133000
133001
133002/*
133003** Compute an affinity string for a table.   Space is obtained
133004** from sqlite3DbMalloc().  The caller is responsible for freeing
133005** the space when done.
133006*/
133007SQLITE_PRIVATE char *sqlite3TableAffinityStr(sqlite3 *db, const Table *pTab){
133008  char *zColAff;
133009  zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1);
133010  if( zColAff ){
133011    int i, j;
133012    for(i=j=0; i<pTab->nCol; i++){
133013      if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
133014        zColAff[j++] = pTab->aCol[i].affinity;
133015      }
133016    }
133017    do{
133018      zColAff[j--] = 0;
133019    }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB );
133020  }
133021  return zColAff;
133022}
133023
133024/*
133025** Make changes to the evolving bytecode to do affinity transformations
133026** of values that are about to be gathered into a row for table pTab.
133027**
133028** For ordinary (legacy, non-strict) tables:
133029** -----------------------------------------
133030**
133031** Compute the affinity string for table pTab, if it has not already been
133032** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
133033**
133034** If the affinity string is empty (because it was all SQLITE_AFF_BLOB entries
133035** which were then optimized out) then this routine becomes a no-op.
133036**
133037** Otherwise if iReg>0 then code an OP_Affinity opcode that will set the
133038** affinities for register iReg and following.  Or if iReg==0,
133039** then just set the P4 operand of the previous opcode (which should  be
133040** an OP_MakeRecord) to the affinity string.
133041**
133042** A column affinity string has one character per column:
133043**
133044**    Character      Column affinity
133045**    ---------      ---------------
133046**    'A'            BLOB
133047**    'B'            TEXT
133048**    'C'            NUMERIC
133049**    'D'            INTEGER
133050**    'E'            REAL
133051**
133052** For STRICT tables:
133053** ------------------
133054**
133055** Generate an appropriate OP_TypeCheck opcode that will verify the
133056** datatypes against the column definitions in pTab.  If iReg==0, that
133057** means an OP_MakeRecord opcode has already been generated and should be
133058** the last opcode generated.  The new OP_TypeCheck needs to be inserted
133059** before the OP_MakeRecord.  The new OP_TypeCheck should use the same
133060** register set as the OP_MakeRecord.  If iReg>0 then register iReg is
133061** the first of a series of registers that will form the new record.
133062** Apply the type checking to that array of registers.
133063*/
133064SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
133065  int i;
133066  char *zColAff;
133067  if( pTab->tabFlags & TF_Strict ){
133068    if( iReg==0 ){
133069      /* Move the previous opcode (which should be OP_MakeRecord) forward
133070      ** by one slot and insert a new OP_TypeCheck where the current
133071      ** OP_MakeRecord is found */
133072      VdbeOp *pPrev;
133073      sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
133074      pPrev = sqlite3VdbeGetLastOp(v);
133075      assert( pPrev!=0 );
133076      assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed );
133077      pPrev->opcode = OP_TypeCheck;
133078      sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, pPrev->p3);
133079    }else{
133080      /* Insert an isolated OP_Typecheck */
133081      sqlite3VdbeAddOp2(v, OP_TypeCheck, iReg, pTab->nNVCol);
133082      sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
133083    }
133084    return;
133085  }
133086  zColAff = pTab->zColAff;
133087  if( zColAff==0 ){
133088    zColAff = sqlite3TableAffinityStr(0, pTab);
133089    if( !zColAff ){
133090      sqlite3OomFault(sqlite3VdbeDb(v));
133091      return;
133092    }
133093    pTab->zColAff = zColAff;
133094  }
133095  assert( zColAff!=0 );
133096  i = sqlite3Strlen30NN(zColAff);
133097  if( i ){
133098    if( iReg ){
133099      sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
133100    }else{
133101      assert( sqlite3VdbeGetLastOp(v)->opcode==OP_MakeRecord
133102              || sqlite3VdbeDb(v)->mallocFailed );
133103      sqlite3VdbeChangeP4(v, -1, zColAff, i);
133104    }
133105  }
133106}
133107
133108/*
133109** Return non-zero if the table pTab in database iDb or any of its indices
133110** have been opened at any point in the VDBE program. This is used to see if
133111** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
133112** run without using a temporary table for the results of the SELECT.
133113*/
133114static int readsTable(Parse *p, int iDb, Table *pTab){
133115  Vdbe *v = sqlite3GetVdbe(p);
133116  int i;
133117  int iEnd = sqlite3VdbeCurrentAddr(v);
133118#ifndef SQLITE_OMIT_VIRTUALTABLE
133119  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
133120#endif
133121
133122  for(i=1; i<iEnd; i++){
133123    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
133124    assert( pOp!=0 );
133125    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
133126      Index *pIndex;
133127      Pgno tnum = pOp->p2;
133128      if( tnum==pTab->tnum ){
133129        return 1;
133130      }
133131      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
133132        if( tnum==pIndex->tnum ){
133133          return 1;
133134        }
133135      }
133136    }
133137#ifndef SQLITE_OMIT_VIRTUALTABLE
133138    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
133139      assert( pOp->p4.pVtab!=0 );
133140      assert( pOp->p4type==P4_VTAB );
133141      return 1;
133142    }
133143#endif
133144  }
133145  return 0;
133146}
133147
133148/* This walker callback will compute the union of colFlags flags for all
133149** referenced columns in a CHECK constraint or generated column expression.
133150*/
133151static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){
133152  if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
133153    assert( pExpr->iColumn < pWalker->u.pTab->nCol );
133154    pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
133155  }
133156  return WRC_Continue;
133157}
133158
133159#ifndef SQLITE_OMIT_GENERATED_COLUMNS
133160/*
133161** All regular columns for table pTab have been puts into registers
133162** starting with iRegStore.  The registers that correspond to STORED
133163** or VIRTUAL columns have not yet been initialized.  This routine goes
133164** back and computes the values for those columns based on the previously
133165** computed normal columns.
133166*/
133167SQLITE_PRIVATE void sqlite3ComputeGeneratedColumns(
133168  Parse *pParse,    /* Parsing context */
133169  int iRegStore,    /* Register holding the first column */
133170  Table *pTab       /* The table */
133171){
133172  int i;
133173  Walker w;
133174  Column *pRedo;
133175  int eProgress;
133176  VdbeOp *pOp;
133177
133178  assert( pTab->tabFlags & TF_HasGenerated );
133179  testcase( pTab->tabFlags & TF_HasVirtual );
133180  testcase( pTab->tabFlags & TF_HasStored );
133181
133182  /* Before computing generated columns, first go through and make sure
133183  ** that appropriate affinity has been applied to the regular columns
133184  */
133185  sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
133186  if( (pTab->tabFlags & TF_HasStored)!=0 ){
133187    pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
133188    if( pOp->opcode==OP_Affinity ){
133189      /* Change the OP_Affinity argument to '@' (NONE) for all stored
133190      ** columns.  '@' is the no-op affinity and those columns have not
133191      ** yet been computed. */
133192      int ii, jj;
133193      char *zP4 = pOp->p4.z;
133194      assert( zP4!=0 );
133195      assert( pOp->p4type==P4_DYNAMIC );
133196      for(ii=jj=0; zP4[jj]; ii++){
133197        if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
133198          continue;
133199        }
133200        if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
133201          zP4[jj] = SQLITE_AFF_NONE;
133202        }
133203        jj++;
133204      }
133205    }else if( pOp->opcode==OP_TypeCheck ){
133206      /* If an OP_TypeCheck was generated because the table is STRICT,
133207      ** then set the P3 operand to indicate that generated columns should
133208      ** not be checked */
133209      pOp->p3 = 1;
133210    }
133211  }
133212
133213  /* Because there can be multiple generated columns that refer to one another,
133214  ** this is a two-pass algorithm.  On the first pass, mark all generated
133215  ** columns as "not available".
133216  */
133217  for(i=0; i<pTab->nCol; i++){
133218    if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
133219      testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
133220      testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
133221      pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
133222    }
133223  }
133224
133225  w.u.pTab = pTab;
133226  w.xExprCallback = exprColumnFlagUnion;
133227  w.xSelectCallback = 0;
133228  w.xSelectCallback2 = 0;
133229
133230  /* On the second pass, compute the value of each NOT-AVAILABLE column.
133231  ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will
133232  ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as
133233  ** they are needed.
133234  */
133235  pParse->iSelfTab = -iRegStore;
133236  do{
133237    eProgress = 0;
133238    pRedo = 0;
133239    for(i=0; i<pTab->nCol; i++){
133240      Column *pCol = pTab->aCol + i;
133241      if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
133242        int x;
133243        pCol->colFlags |= COLFLAG_BUSY;
133244        w.eCode = 0;
133245        sqlite3WalkExpr(&w, sqlite3ColumnExpr(pTab, pCol));
133246        pCol->colFlags &= ~COLFLAG_BUSY;
133247        if( w.eCode & COLFLAG_NOTAVAIL ){
133248          pRedo = pCol;
133249          continue;
133250        }
133251        eProgress = 1;
133252        assert( pCol->colFlags & COLFLAG_GENERATED );
133253        x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;
133254        sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, x);
133255        pCol->colFlags &= ~COLFLAG_NOTAVAIL;
133256      }
133257    }
133258  }while( pRedo && eProgress );
133259  if( pRedo ){
133260    sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zCnName);
133261  }
133262  pParse->iSelfTab = 0;
133263}
133264#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
133265
133266
133267#ifndef SQLITE_OMIT_AUTOINCREMENT
133268/*
133269** Locate or create an AutoincInfo structure associated with table pTab
133270** which is in database iDb.  Return the register number for the register
133271** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
133272** table.  (Also return zero when doing a VACUUM since we do not want to
133273** update the AUTOINCREMENT counters during a VACUUM.)
133274**
133275** There is at most one AutoincInfo structure per table even if the
133276** same table is autoincremented multiple times due to inserts within
133277** triggers.  A new AutoincInfo structure is created if this is the
133278** first use of table pTab.  On 2nd and subsequent uses, the original
133279** AutoincInfo structure is used.
133280**
133281** Four consecutive registers are allocated:
133282**
133283**   (1)  The name of the pTab table.
133284**   (2)  The maximum ROWID of pTab.
133285**   (3)  The rowid in sqlite_sequence of pTab
133286**   (4)  The original value of the max ROWID in pTab, or NULL if none
133287**
133288** The 2nd register is the one that is returned.  That is all the
133289** insert routine needs to know about.
133290*/
133291static int autoIncBegin(
133292  Parse *pParse,      /* Parsing context */
133293  int iDb,            /* Index of the database holding pTab */
133294  Table *pTab         /* The table we are writing to */
133295){
133296  int memId = 0;      /* Register holding maximum rowid */
133297  assert( pParse->db->aDb[iDb].pSchema!=0 );
133298  if( (pTab->tabFlags & TF_Autoincrement)!=0
133299   && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
133300  ){
133301    Parse *pToplevel = sqlite3ParseToplevel(pParse);
133302    AutoincInfo *pInfo;
133303    Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
133304
133305    /* Verify that the sqlite_sequence table exists and is an ordinary
133306    ** rowid table with exactly two columns.
133307    ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
133308    if( pSeqTab==0
133309     || !HasRowid(pSeqTab)
133310     || NEVER(IsVirtual(pSeqTab))
133311     || pSeqTab->nCol!=2
133312    ){
133313      pParse->nErr++;
133314      pParse->rc = SQLITE_CORRUPT_SEQUENCE;
133315      return 0;
133316    }
133317
133318    pInfo = pToplevel->pAinc;
133319    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
133320    if( pInfo==0 ){
133321      pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
133322      sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo);
133323      testcase( pParse->earlyCleanup );
133324      if( pParse->db->mallocFailed ) return 0;
133325      pInfo->pNext = pToplevel->pAinc;
133326      pToplevel->pAinc = pInfo;
133327      pInfo->pTab = pTab;
133328      pInfo->iDb = iDb;
133329      pToplevel->nMem++;                  /* Register to hold name of table */
133330      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
133331      pToplevel->nMem +=2;       /* Rowid in sqlite_sequence + orig max val */
133332    }
133333    memId = pInfo->regCtr;
133334  }
133335  return memId;
133336}
133337
133338/*
133339** This routine generates code that will initialize all of the
133340** register used by the autoincrement tracker.
133341*/
133342SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
133343  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
133344  sqlite3 *db = pParse->db;  /* The database connection */
133345  Db *pDb;                   /* Database only autoinc table */
133346  int memId;                 /* Register holding max rowid */
133347  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
133348
133349  /* This routine is never called during trigger-generation.  It is
133350  ** only called from the top-level */
133351  assert( pParse->pTriggerTab==0 );
133352  assert( sqlite3IsToplevel(pParse) );
133353
133354  assert( v );   /* We failed long ago if this is not so */
133355  for(p = pParse->pAinc; p; p = p->pNext){
133356    static const int iLn = VDBE_OFFSET_LINENO(2);
133357    static const VdbeOpList autoInc[] = {
133358      /* 0  */ {OP_Null,    0,  0, 0},
133359      /* 1  */ {OP_Rewind,  0, 10, 0},
133360      /* 2  */ {OP_Column,  0,  0, 0},
133361      /* 3  */ {OP_Ne,      0,  9, 0},
133362      /* 4  */ {OP_Rowid,   0,  0, 0},
133363      /* 5  */ {OP_Column,  0,  1, 0},
133364      /* 6  */ {OP_AddImm,  0,  0, 0},
133365      /* 7  */ {OP_Copy,    0,  0, 0},
133366      /* 8  */ {OP_Goto,    0, 11, 0},
133367      /* 9  */ {OP_Next,    0,  2, 0},
133368      /* 10 */ {OP_Integer, 0,  0, 0},
133369      /* 11 */ {OP_Close,   0,  0, 0}
133370    };
133371    VdbeOp *aOp;
133372    pDb = &db->aDb[p->iDb];
133373    memId = p->regCtr;
133374    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
133375    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
133376    sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
133377    aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
133378    if( aOp==0 ) break;
133379    aOp[0].p2 = memId;
133380    aOp[0].p3 = memId+2;
133381    aOp[2].p3 = memId;
133382    aOp[3].p1 = memId-1;
133383    aOp[3].p3 = memId;
133384    aOp[3].p5 = SQLITE_JUMPIFNULL;
133385    aOp[4].p2 = memId+1;
133386    aOp[5].p3 = memId;
133387    aOp[6].p1 = memId;
133388    aOp[7].p2 = memId+2;
133389    aOp[7].p1 = memId;
133390    aOp[10].p2 = memId;
133391    if( pParse->nTab==0 ) pParse->nTab = 1;
133392  }
133393}
133394
133395/*
133396** Update the maximum rowid for an autoincrement calculation.
133397**
133398** This routine should be called when the regRowid register holds a
133399** new rowid that is about to be inserted.  If that new rowid is
133400** larger than the maximum rowid in the memId memory cell, then the
133401** memory cell is updated.
133402*/
133403static void autoIncStep(Parse *pParse, int memId, int regRowid){
133404  if( memId>0 ){
133405    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
133406  }
133407}
133408
133409/*
133410** This routine generates the code needed to write autoincrement
133411** maximum rowid values back into the sqlite_sequence register.
133412** Every statement that might do an INSERT into an autoincrement
133413** table (either directly or through triggers) needs to call this
133414** routine just before the "exit" code.
133415*/
133416static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
133417  AutoincInfo *p;
133418  Vdbe *v = pParse->pVdbe;
133419  sqlite3 *db = pParse->db;
133420
133421  assert( v );
133422  for(p = pParse->pAinc; p; p = p->pNext){
133423    static const int iLn = VDBE_OFFSET_LINENO(2);
133424    static const VdbeOpList autoIncEnd[] = {
133425      /* 0 */ {OP_NotNull,     0, 2, 0},
133426      /* 1 */ {OP_NewRowid,    0, 0, 0},
133427      /* 2 */ {OP_MakeRecord,  0, 2, 0},
133428      /* 3 */ {OP_Insert,      0, 0, 0},
133429      /* 4 */ {OP_Close,       0, 0, 0}
133430    };
133431    VdbeOp *aOp;
133432    Db *pDb = &db->aDb[p->iDb];
133433    int iRec;
133434    int memId = p->regCtr;
133435
133436    iRec = sqlite3GetTempReg(pParse);
133437    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
133438    sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
133439    VdbeCoverage(v);
133440    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
133441    aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
133442    if( aOp==0 ) break;
133443    aOp[0].p1 = memId+1;
133444    aOp[1].p2 = memId+1;
133445    aOp[2].p1 = memId-1;
133446    aOp[2].p3 = iRec;
133447    aOp[3].p2 = iRec;
133448    aOp[3].p3 = memId+1;
133449    aOp[3].p5 = OPFLAG_APPEND;
133450    sqlite3ReleaseTempReg(pParse, iRec);
133451  }
133452}
133453SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
133454  if( pParse->pAinc ) autoIncrementEnd(pParse);
133455}
133456#else
133457/*
133458** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
133459** above are all no-ops
133460*/
133461# define autoIncBegin(A,B,C) (0)
133462# define autoIncStep(A,B,C)
133463#endif /* SQLITE_OMIT_AUTOINCREMENT */
133464
133465/*
133466** If argument pVal is a Select object returned by an sqlite3MultiValues()
133467** that was able to use the co-routine optimization, finish coding the
133468** co-routine.
133469*/
133470SQLITE_PRIVATE void sqlite3MultiValuesEnd(Parse *pParse, Select *pVal){
133471  if( ALWAYS(pVal) && pVal->pSrc->nSrc>0 ){
133472    SrcItem *pItem = &pVal->pSrc->a[0];
133473    sqlite3VdbeEndCoroutine(pParse->pVdbe, pItem->regReturn);
133474    sqlite3VdbeJumpHere(pParse->pVdbe, pItem->addrFillSub - 1);
133475  }
133476}
133477
133478/*
133479** Return true if all expressions in the expression-list passed as the
133480** only argument are constant.
133481*/
133482static int exprListIsConstant(Parse *pParse, ExprList *pRow){
133483  int ii;
133484  for(ii=0; ii<pRow->nExpr; ii++){
133485    if( 0==sqlite3ExprIsConstant(pParse, pRow->a[ii].pExpr) ) return 0;
133486  }
133487  return 1;
133488}
133489
133490/*
133491** Return true if all expressions in the expression-list passed as the
133492** only argument are both constant and have no affinity.
133493*/
133494static int exprListIsNoAffinity(Parse *pParse, ExprList *pRow){
133495  int ii;
133496  if( exprListIsConstant(pParse,pRow)==0 ) return 0;
133497  for(ii=0; ii<pRow->nExpr; ii++){
133498    Expr *pExpr = pRow->a[ii].pExpr;
133499    assert( pExpr->op!=TK_RAISE );
133500    assert( pExpr->affExpr==0 );
133501    if( 0!=sqlite3ExprAffinity(pExpr) ) return 0;
133502  }
133503  return 1;
133504
133505}
133506
133507/*
133508** This function is called by the parser for the second and subsequent
133509** rows of a multi-row VALUES clause. Argument pLeft is the part of
133510** the VALUES clause already parsed, argument pRow is the vector of values
133511** for the new row. The Select object returned represents the complete
133512** VALUES clause, including the new row.
133513**
133514** There are two ways in which this may be achieved - by incremental
133515** coding of a co-routine (the "co-routine" method) or by returning a
133516** Select object equivalent to the following (the "UNION ALL" method):
133517**
133518**        "pLeft UNION ALL SELECT pRow"
133519**
133520** If the VALUES clause contains a lot of rows, this compound Select
133521** object may consume a lot of memory.
133522**
133523** When the co-routine method is used, each row that will be returned
133524** by the VALUES clause is coded into part of a co-routine as it is
133525** passed to this function. The returned Select object is equivalent to:
133526**
133527**     SELECT * FROM (
133528**       Select object to read co-routine
133529**     )
133530**
133531** The co-routine method is used in most cases. Exceptions are:
133532**
133533**    a) If the current statement has a WITH clause. This is to avoid
133534**       statements like:
133535**
133536**            WITH cte AS ( VALUES('x'), ('y') ... )
133537**            SELECT * FROM cte AS a, cte AS b;
133538**
133539**       This will not work, as the co-routine uses a hard-coded register
133540**       for its OP_Yield instructions, and so it is not possible for two
133541**       cursors to iterate through it concurrently.
133542**
133543**    b) The schema is currently being parsed (i.e. the VALUES clause is part
133544**       of a schema item like a VIEW or TRIGGER). In this case there is no VM
133545**       being generated when parsing is taking place, and so generating
133546**       a co-routine is not possible.
133547**
133548**    c) There are non-constant expressions in the VALUES clause (e.g.
133549**       the VALUES clause is part of a correlated sub-query).
133550**
133551**    d) One or more of the values in the first row of the VALUES clause
133552**       has an affinity (i.e. is a CAST expression). This causes problems
133553**       because the complex rules SQLite uses (see function
133554**       sqlite3SubqueryColumnTypes() in select.c) to determine the effective
133555**       affinity of such a column for all rows require access to all values in
133556**       the column simultaneously.
133557*/
133558SQLITE_PRIVATE Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList *pRow){
133559
133560  if( pParse->bHasWith                   /* condition (a) above */
133561   || pParse->db->init.busy              /* condition (b) above */
133562   || exprListIsConstant(pParse,pRow)==0 /* condition (c) above */
133563   || (pLeft->pSrc->nSrc==0 &&
133564       exprListIsNoAffinity(pParse,pLeft->pEList)==0) /* condition (d) above */
133565   || IN_SPECIAL_PARSE
133566  ){
133567    /* The co-routine method cannot be used. Fall back to UNION ALL. */
133568    Select *pSelect = 0;
133569    int f = SF_Values | SF_MultiValue;
133570    if( pLeft->pSrc->nSrc ){
133571      sqlite3MultiValuesEnd(pParse, pLeft);
133572      f = SF_Values;
133573    }else if( pLeft->pPrior ){
133574      /* In this case set the SF_MultiValue flag only if it was set on pLeft */
133575      f = (f & pLeft->selFlags);
133576    }
133577    pSelect = sqlite3SelectNew(pParse, pRow, 0, 0, 0, 0, 0, f, 0);
133578    pLeft->selFlags &= ~SF_MultiValue;
133579    if( pSelect ){
133580      pSelect->op = TK_ALL;
133581      pSelect->pPrior = pLeft;
133582      pLeft = pSelect;
133583    }
133584  }else{
133585    SrcItem *p = 0;               /* SrcItem that reads from co-routine */
133586
133587    if( pLeft->pSrc->nSrc==0 ){
133588      /* Co-routine has not yet been started and the special Select object
133589      ** that accesses the co-routine has not yet been created. This block
133590      ** does both those things. */
133591      Vdbe *v = sqlite3GetVdbe(pParse);
133592      Select *pRet = sqlite3SelectNew(pParse, 0, 0, 0, 0, 0, 0, 0, 0);
133593
133594      /* Ensure the database schema has been read. This is to ensure we have
133595      ** the correct text encoding.  */
133596      if( (pParse->db->mDbFlags & DBFLAG_SchemaKnownOk)==0 ){
133597        sqlite3ReadSchema(pParse);
133598      }
133599
133600      if( pRet ){
133601        SelectDest dest;
133602        pRet->pSrc->nSrc = 1;
133603        pRet->pPrior = pLeft->pPrior;
133604        pRet->op = pLeft->op;
133605        pLeft->pPrior = 0;
133606        pLeft->op = TK_SELECT;
133607        assert( pLeft->pNext==0 );
133608        assert( pRet->pNext==0 );
133609        p = &pRet->pSrc->a[0];
133610        p->pSelect = pLeft;
133611        p->fg.viaCoroutine = 1;
133612        p->addrFillSub = sqlite3VdbeCurrentAddr(v) + 1;
133613        p->regReturn = ++pParse->nMem;
133614        p->iCursor = -1;
133615        p->u1.nRow = 2;
133616        sqlite3VdbeAddOp3(v,OP_InitCoroutine,p->regReturn,0,p->addrFillSub);
133617        sqlite3SelectDestInit(&dest, SRT_Coroutine, p->regReturn);
133618
133619        /* Allocate registers for the output of the co-routine. Do so so
133620        ** that there are two unused registers immediately before those
133621        ** used by the co-routine. This allows the code in sqlite3Insert()
133622        ** to use these registers directly, instead of copying the output
133623        ** of the co-routine to a separate array for processing.  */
133624        dest.iSdst = pParse->nMem + 3;
133625        dest.nSdst = pLeft->pEList->nExpr;
133626        pParse->nMem += 2 + dest.nSdst;
133627
133628        pLeft->selFlags |= SF_MultiValue;
133629        sqlite3Select(pParse, pLeft, &dest);
133630        p->regResult = dest.iSdst;
133631        assert( pParse->nErr || dest.iSdst>0 );
133632        pLeft = pRet;
133633      }
133634    }else{
133635      p = &pLeft->pSrc->a[0];
133636      assert( !p->fg.isTabFunc && !p->fg.isIndexedBy );
133637      p->u1.nRow++;
133638    }
133639
133640    if( pParse->nErr==0 ){
133641      assert( p!=0 );
133642      if( p->pSelect->pEList->nExpr!=pRow->nExpr ){
133643        sqlite3SelectWrongNumTermsError(pParse, p->pSelect);
133644      }else{
133645        sqlite3ExprCodeExprList(pParse, pRow, p->regResult, 0, 0);
133646        sqlite3VdbeAddOp1(pParse->pVdbe, OP_Yield, p->regReturn);
133647      }
133648    }
133649    sqlite3ExprListDelete(pParse->db, pRow);
133650  }
133651
133652  return pLeft;
133653}
133654
133655/* Forward declaration */
133656static int xferOptimization(
133657  Parse *pParse,        /* Parser context */
133658  Table *pDest,         /* The table we are inserting into */
133659  Select *pSelect,      /* A SELECT statement to use as the data source */
133660  int onError,          /* How to handle constraint errors */
133661  int iDbDest           /* The database of pDest */
133662);
133663
133664/*
133665** This routine is called to handle SQL of the following forms:
133666**
133667**    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
133668**    insert into TABLE (IDLIST) select
133669**    insert into TABLE (IDLIST) default values
133670**
133671** The IDLIST following the table name is always optional.  If omitted,
133672** then a list of all (non-hidden) columns for the table is substituted.
133673** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
133674** is omitted.
133675**
133676** For the pSelect parameter holds the values to be inserted for the
133677** first two forms shown above.  A VALUES clause is really just short-hand
133678** for a SELECT statement that omits the FROM clause and everything else
133679** that follows.  If the pSelect parameter is NULL, that means that the
133680** DEFAULT VALUES form of the INSERT statement is intended.
133681**
133682** The code generated follows one of four templates.  For a simple
133683** insert with data coming from a single-row VALUES clause, the code executes
133684** once straight down through.  Pseudo-code follows (we call this
133685** the "1st template"):
133686**
133687**         open write cursor to <table> and its indices
133688**         put VALUES clause expressions into registers
133689**         write the resulting record into <table>
133690**         cleanup
133691**
133692** The three remaining templates assume the statement is of the form
133693**
133694**   INSERT INTO <table> SELECT ...
133695**
133696** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
133697** in other words if the SELECT pulls all columns from a single table
133698** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
133699** if <table2> and <table1> are distinct tables but have identical
133700** schemas, including all the same indices, then a special optimization
133701** is invoked that copies raw records from <table2> over to <table1>.
133702** See the xferOptimization() function for the implementation of this
133703** template.  This is the 2nd template.
133704**
133705**         open a write cursor to <table>
133706**         open read cursor on <table2>
133707**         transfer all records in <table2> over to <table>
133708**         close cursors
133709**         foreach index on <table>
133710**           open a write cursor on the <table> index
133711**           open a read cursor on the corresponding <table2> index
133712**           transfer all records from the read to the write cursors
133713**           close cursors
133714**         end foreach
133715**
133716** The 3rd template is for when the second template does not apply
133717** and the SELECT clause does not read from <table> at any time.
133718** The generated code follows this template:
133719**
133720**         X <- A
133721**         goto B
133722**      A: setup for the SELECT
133723**         loop over the rows in the SELECT
133724**           load values into registers R..R+n
133725**           yield X
133726**         end loop
133727**         cleanup after the SELECT
133728**         end-coroutine X
133729**      B: open write cursor to <table> and its indices
133730**      C: yield X, at EOF goto D
133731**         insert the select result into <table> from R..R+n
133732**         goto C
133733**      D: cleanup
133734**
133735** The 4th template is used if the insert statement takes its
133736** values from a SELECT but the data is being inserted into a table
133737** that is also read as part of the SELECT.  In the third form,
133738** we have to use an intermediate table to store the results of
133739** the select.  The template is like this:
133740**
133741**         X <- A
133742**         goto B
133743**      A: setup for the SELECT
133744**         loop over the tables in the SELECT
133745**           load value into register R..R+n
133746**           yield X
133747**         end loop
133748**         cleanup after the SELECT
133749**         end co-routine R
133750**      B: open temp table
133751**      L: yield X, at EOF goto M
133752**         insert row from R..R+n into temp table
133753**         goto L
133754**      M: open write cursor to <table> and its indices
133755**         rewind temp table
133756**      C: loop over rows of intermediate table
133757**           transfer values form intermediate table into <table>
133758**         end loop
133759**      D: cleanup
133760*/
133761SQLITE_PRIVATE void sqlite3Insert(
133762  Parse *pParse,        /* Parser context */
133763  SrcList *pTabList,    /* Name of table into which we are inserting */
133764  Select *pSelect,      /* A SELECT statement to use as the data source */
133765  IdList *pColumn,      /* Column names corresponding to IDLIST, or NULL. */
133766  int onError,          /* How to handle constraint errors */
133767  Upsert *pUpsert       /* ON CONFLICT clauses for upsert, or NULL */
133768){
133769  sqlite3 *db;          /* The main database structure */
133770  Table *pTab;          /* The table to insert into.  aka TABLE */
133771  int i, j;             /* Loop counters */
133772  Vdbe *v;              /* Generate code into this virtual machine */
133773  Index *pIdx;          /* For looping over indices of the table */
133774  int nColumn;          /* Number of columns in the data */
133775  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
133776  int iDataCur = 0;     /* VDBE cursor that is the main data repository */
133777  int iIdxCur = 0;      /* First index cursor */
133778  int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
133779  int endOfLoop;        /* Label for the end of the insertion loop */
133780  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
133781  int addrInsTop = 0;   /* Jump to label "D" */
133782  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
133783  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
133784  int iDb;              /* Index of database holding TABLE */
133785  u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
133786  u8 appendFlag = 0;    /* True if the insert is likely to be an append */
133787  u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
133788  u8 bIdListInOrder;    /* True if IDLIST is in table order */
133789  ExprList *pList = 0;  /* List of VALUES() to be inserted  */
133790  int iRegStore;        /* Register in which to store next column */
133791
133792  /* Register allocations */
133793  int regFromSelect = 0;/* Base register for data coming from SELECT */
133794  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
133795  int regRowCount = 0;  /* Memory cell used for the row counter */
133796  int regIns;           /* Block of regs holding rowid+data being inserted */
133797  int regRowid;         /* registers holding insert rowid */
133798  int regData;          /* register holding first column to insert */
133799  int *aRegIdx = 0;     /* One register allocated to each index */
133800
133801#ifndef SQLITE_OMIT_TRIGGER
133802  int isView;                 /* True if attempting to insert into a view */
133803  Trigger *pTrigger;          /* List of triggers on pTab, if required */
133804  int tmask;                  /* Mask of trigger times */
133805#endif
133806
133807  db = pParse->db;
133808  assert( db->pParse==pParse );
133809  if( pParse->nErr ){
133810    goto insert_cleanup;
133811  }
133812  assert( db->mallocFailed==0 );
133813  dest.iSDParm = 0;  /* Suppress a harmless compiler warning */
133814
133815  /* If the Select object is really just a simple VALUES() list with a
133816  ** single row (the common case) then keep that one row of values
133817  ** and discard the other (unused) parts of the pSelect object
133818  */
133819  if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
133820    pList = pSelect->pEList;
133821    pSelect->pEList = 0;
133822    sqlite3SelectDelete(db, pSelect);
133823    pSelect = 0;
133824  }
133825
133826  /* Locate the table into which we will be inserting new information.
133827  */
133828  assert( pTabList->nSrc==1 );
133829  pTab = sqlite3SrcListLookup(pParse, pTabList);
133830  if( pTab==0 ){
133831    goto insert_cleanup;
133832  }
133833  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
133834  assert( iDb<db->nDb );
133835  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
133836                       db->aDb[iDb].zDbSName) ){
133837    goto insert_cleanup;
133838  }
133839  withoutRowid = !HasRowid(pTab);
133840
133841  /* Figure out if we have any triggers and if the table being
133842  ** inserted into is a view
133843  */
133844#ifndef SQLITE_OMIT_TRIGGER
133845  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
133846  isView = IsView(pTab);
133847#else
133848# define pTrigger 0
133849# define tmask 0
133850# define isView 0
133851#endif
133852#ifdef SQLITE_OMIT_VIEW
133853# undef isView
133854# define isView 0
133855#endif
133856  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
133857
133858#if TREETRACE_ENABLED
133859  if( sqlite3TreeTrace & 0x10000 ){
133860    sqlite3TreeViewLine(0, "In sqlite3Insert() at %s:%d", __FILE__, __LINE__);
133861    sqlite3TreeViewInsert(pParse->pWith, pTabList, pColumn, pSelect, pList,
133862                          onError, pUpsert, pTrigger);
133863  }
133864#endif
133865
133866  /* If pTab is really a view, make sure it has been initialized.
133867  ** ViewGetColumnNames() is a no-op if pTab is not a view.
133868  */
133869  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
133870    goto insert_cleanup;
133871  }
133872
133873  /* Cannot insert into a read-only table.
133874  */
133875  if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
133876    goto insert_cleanup;
133877  }
133878
133879  /* Allocate a VDBE
133880  */
133881  v = sqlite3GetVdbe(pParse);
133882  if( v==0 ) goto insert_cleanup;
133883  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
133884  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
133885
133886#ifndef SQLITE_OMIT_XFER_OPT
133887  /* If the statement is of the form
133888  **
133889  **       INSERT INTO <table1> SELECT * FROM <table2>;
133890  **
133891  ** Then special optimizations can be applied that make the transfer
133892  ** very fast and which reduce fragmentation of indices.
133893  **
133894  ** This is the 2nd template.
133895  */
133896  if( pColumn==0
133897   && pSelect!=0
133898   && pTrigger==0
133899   && xferOptimization(pParse, pTab, pSelect, onError, iDb)
133900  ){
133901    assert( !pTrigger );
133902    assert( pList==0 );
133903    goto insert_end;
133904  }
133905#endif /* SQLITE_OMIT_XFER_OPT */
133906
133907  /* If this is an AUTOINCREMENT table, look up the sequence number in the
133908  ** sqlite_sequence table and store it in memory cell regAutoinc.
133909  */
133910  regAutoinc = autoIncBegin(pParse, iDb, pTab);
133911
133912  /* Allocate a block registers to hold the rowid and the values
133913  ** for all columns of the new row.
133914  */
133915  regRowid = regIns = pParse->nMem+1;
133916  pParse->nMem += pTab->nCol + 1;
133917  if( IsVirtual(pTab) ){
133918    regRowid++;
133919    pParse->nMem++;
133920  }
133921  regData = regRowid+1;
133922
133923  /* If the INSERT statement included an IDLIST term, then make sure
133924  ** all elements of the IDLIST really are columns of the table and
133925  ** remember the column indices.
133926  **
133927  ** If the table has an INTEGER PRIMARY KEY column and that column
133928  ** is named in the IDLIST, then record in the ipkColumn variable
133929  ** the index into IDLIST of the primary key column.  ipkColumn is
133930  ** the index of the primary key as it appears in IDLIST, not as
133931  ** is appears in the original table.  (The index of the INTEGER
133932  ** PRIMARY KEY in the original table is pTab->iPKey.)  After this
133933  ** loop, if ipkColumn==(-1), that means that integer primary key
133934  ** is unspecified, and hence the table is either WITHOUT ROWID or
133935  ** it will automatically generated an integer primary key.
133936  **
133937  ** bIdListInOrder is true if the columns in IDLIST are in storage
133938  ** order.  This enables an optimization that avoids shuffling the
133939  ** columns into storage order.  False negatives are harmless,
133940  ** but false positives will cause database corruption.
133941  */
133942  bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
133943  if( pColumn ){
133944    assert( pColumn->eU4!=EU4_EXPR );
133945    pColumn->eU4 = EU4_IDX;
133946    for(i=0; i<pColumn->nId; i++){
133947      pColumn->a[i].u4.idx = -1;
133948    }
133949    for(i=0; i<pColumn->nId; i++){
133950      for(j=0; j<pTab->nCol; j++){
133951        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zCnName)==0 ){
133952          pColumn->a[i].u4.idx = j;
133953          if( i!=j ) bIdListInOrder = 0;
133954          if( j==pTab->iPKey ){
133955            ipkColumn = i;  assert( !withoutRowid );
133956          }
133957#ifndef SQLITE_OMIT_GENERATED_COLUMNS
133958          if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
133959            sqlite3ErrorMsg(pParse,
133960               "cannot INSERT into generated column \"%s\"",
133961               pTab->aCol[j].zCnName);
133962            goto insert_cleanup;
133963          }
133964#endif
133965          break;
133966        }
133967      }
133968      if( j>=pTab->nCol ){
133969        if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
133970          ipkColumn = i;
133971          bIdListInOrder = 0;
133972        }else{
133973          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
133974              pTabList->a, pColumn->a[i].zName);
133975          pParse->checkSchema = 1;
133976          goto insert_cleanup;
133977        }
133978      }
133979    }
133980  }
133981
133982  /* Figure out how many columns of data are supplied.  If the data
133983  ** is coming from a SELECT statement, then generate a co-routine that
133984  ** produces a single row of the SELECT on each invocation.  The
133985  ** co-routine is the common header to the 3rd and 4th templates.
133986  */
133987  if( pSelect ){
133988    /* Data is coming from a SELECT or from a multi-row VALUES clause.
133989    ** Generate a co-routine to run the SELECT. */
133990    int rc;             /* Result code */
133991
133992    if( pSelect->pSrc->nSrc==1
133993     && pSelect->pSrc->a[0].fg.viaCoroutine
133994     && pSelect->pPrior==0
133995    ){
133996      SrcItem *pItem = &pSelect->pSrc->a[0];
133997      dest.iSDParm = pItem->regReturn;
133998      regFromSelect = pItem->regResult;
133999      nColumn = pItem->pSelect->pEList->nExpr;
134000      ExplainQueryPlan((pParse, 0, "SCAN %S", pItem));
134001      if( bIdListInOrder && nColumn==pTab->nCol ){
134002        regData = regFromSelect;
134003        regRowid = regData - 1;
134004        regIns = regRowid - (IsVirtual(pTab) ? 1 : 0);
134005      }
134006    }else{
134007      int addrTop;        /* Top of the co-routine */
134008      int regYield = ++pParse->nMem;
134009      addrTop = sqlite3VdbeCurrentAddr(v) + 1;
134010      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
134011      sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
134012      dest.iSdst = bIdListInOrder ? regData : 0;
134013      dest.nSdst = pTab->nCol;
134014      rc = sqlite3Select(pParse, pSelect, &dest);
134015      regFromSelect = dest.iSdst;
134016      assert( db->pParse==pParse );
134017      if( rc || pParse->nErr ) goto insert_cleanup;
134018      assert( db->mallocFailed==0 );
134019      sqlite3VdbeEndCoroutine(v, regYield);
134020      sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
134021      assert( pSelect->pEList );
134022      nColumn = pSelect->pEList->nExpr;
134023    }
134024
134025    /* Set useTempTable to TRUE if the result of the SELECT statement
134026    ** should be written into a temporary table (template 4).  Set to
134027    ** FALSE if each output row of the SELECT can be written directly into
134028    ** the destination table (template 3).
134029    **
134030    ** A temp table must be used if the table being updated is also one
134031    ** of the tables being read by the SELECT statement.  Also use a
134032    ** temp table in the case of row triggers.
134033    */
134034    if( pTrigger || readsTable(pParse, iDb, pTab) ){
134035      useTempTable = 1;
134036    }
134037
134038    if( useTempTable ){
134039      /* Invoke the coroutine to extract information from the SELECT
134040      ** and add it to a transient table srcTab.  The code generated
134041      ** here is from the 4th template:
134042      **
134043      **      B: open temp table
134044      **      L: yield X, goto M at EOF
134045      **         insert row from R..R+n into temp table
134046      **         goto L
134047      **      M: ...
134048      */
134049      int regRec;          /* Register to hold packed record */
134050      int regTempRowid;    /* Register to hold temp table ROWID */
134051      int addrL;           /* Label "L" */
134052
134053      srcTab = pParse->nTab++;
134054      regRec = sqlite3GetTempReg(pParse);
134055      regTempRowid = sqlite3GetTempReg(pParse);
134056      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
134057      addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
134058      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
134059      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
134060      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
134061      sqlite3VdbeGoto(v, addrL);
134062      sqlite3VdbeJumpHere(v, addrL);
134063      sqlite3ReleaseTempReg(pParse, regRec);
134064      sqlite3ReleaseTempReg(pParse, regTempRowid);
134065    }
134066  }else{
134067    /* This is the case if the data for the INSERT is coming from a
134068    ** single-row VALUES clause
134069    */
134070    NameContext sNC;
134071    memset(&sNC, 0, sizeof(sNC));
134072    sNC.pParse = pParse;
134073    srcTab = -1;
134074    assert( useTempTable==0 );
134075    if( pList ){
134076      nColumn = pList->nExpr;
134077      if( sqlite3ResolveExprListNames(&sNC, pList) ){
134078        goto insert_cleanup;
134079      }
134080    }else{
134081      nColumn = 0;
134082    }
134083  }
134084
134085  /* If there is no IDLIST term but the table has an integer primary
134086  ** key, the set the ipkColumn variable to the integer primary key
134087  ** column index in the original table definition.
134088  */
134089  if( pColumn==0 && nColumn>0 ){
134090    ipkColumn = pTab->iPKey;
134091#ifndef SQLITE_OMIT_GENERATED_COLUMNS
134092    if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
134093      testcase( pTab->tabFlags & TF_HasVirtual );
134094      testcase( pTab->tabFlags & TF_HasStored );
134095      for(i=ipkColumn-1; i>=0; i--){
134096        if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
134097          testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
134098          testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
134099          ipkColumn--;
134100        }
134101      }
134102    }
134103#endif
134104
134105    /* Make sure the number of columns in the source data matches the number
134106    ** of columns to be inserted into the table.
134107    */
134108    assert( TF_HasHidden==COLFLAG_HIDDEN );
134109    assert( TF_HasGenerated==COLFLAG_GENERATED );
134110    assert( COLFLAG_NOINSERT==(COLFLAG_GENERATED|COLFLAG_HIDDEN) );
134111    if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
134112      for(i=0; i<pTab->nCol; i++){
134113        if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
134114      }
134115    }
134116    if( nColumn!=(pTab->nCol-nHidden) ){
134117      sqlite3ErrorMsg(pParse,
134118         "table %S has %d columns but %d values were supplied",
134119         pTabList->a, pTab->nCol-nHidden, nColumn);
134120     goto insert_cleanup;
134121    }
134122  }
134123  if( pColumn!=0 && nColumn!=pColumn->nId ){
134124    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
134125    goto insert_cleanup;
134126  }
134127
134128  /* Initialize the count of rows to be inserted
134129  */
134130  if( (db->flags & SQLITE_CountRows)!=0
134131   && !pParse->nested
134132   && !pParse->pTriggerTab
134133   && !pParse->bReturning
134134  ){
134135    regRowCount = ++pParse->nMem;
134136    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
134137  }
134138
134139  /* If this is not a view, open the table and and all indices */
134140  if( !isView ){
134141    int nIdx;
134142    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
134143                                      &iDataCur, &iIdxCur);
134144    aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
134145    if( aRegIdx==0 ){
134146      goto insert_cleanup;
134147    }
134148    for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
134149      assert( pIdx );
134150      aRegIdx[i] = ++pParse->nMem;
134151      pParse->nMem += pIdx->nColumn;
134152    }
134153    aRegIdx[i] = ++pParse->nMem;  /* Register to store the table record */
134154  }
134155#ifndef SQLITE_OMIT_UPSERT
134156  if( pUpsert ){
134157    Upsert *pNx;
134158    if( IsVirtual(pTab) ){
134159      sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
134160              pTab->zName);
134161      goto insert_cleanup;
134162    }
134163    if( IsView(pTab) ){
134164      sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
134165      goto insert_cleanup;
134166    }
134167    if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
134168      goto insert_cleanup;
134169    }
134170    pTabList->a[0].iCursor = iDataCur;
134171    pNx = pUpsert;
134172    do{
134173      pNx->pUpsertSrc = pTabList;
134174      pNx->regData = regData;
134175      pNx->iDataCur = iDataCur;
134176      pNx->iIdxCur = iIdxCur;
134177      if( pNx->pUpsertTarget ){
134178        if( sqlite3UpsertAnalyzeTarget(pParse, pTabList, pNx, pUpsert) ){
134179          goto insert_cleanup;
134180        }
134181      }
134182      pNx = pNx->pNextUpsert;
134183    }while( pNx!=0 );
134184  }
134185#endif
134186
134187
134188  /* This is the top of the main insertion loop */
134189  if( useTempTable ){
134190    /* This block codes the top of loop only.  The complete loop is the
134191    ** following pseudocode (template 4):
134192    **
134193    **         rewind temp table, if empty goto D
134194    **      C: loop over rows of intermediate table
134195    **           transfer values form intermediate table into <table>
134196    **         end loop
134197    **      D: ...
134198    */
134199    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
134200    addrCont = sqlite3VdbeCurrentAddr(v);
134201  }else if( pSelect ){
134202    /* This block codes the top of loop only.  The complete loop is the
134203    ** following pseudocode (template 3):
134204    **
134205    **      C: yield X, at EOF goto D
134206    **         insert the select result into <table> from R..R+n
134207    **         goto C
134208    **      D: ...
134209    */
134210    sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
134211    addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
134212    VdbeCoverage(v);
134213    if( ipkColumn>=0 ){
134214      /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
134215      ** SELECT, go ahead and copy the value into the rowid slot now, so that
134216      ** the value does not get overwritten by a NULL at tag-20191021-002. */
134217      sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
134218    }
134219  }
134220
134221  /* Compute data for ordinary columns of the new entry.  Values
134222  ** are written in storage order into registers starting with regData.
134223  ** Only ordinary columns are computed in this loop. The rowid
134224  ** (if there is one) is computed later and generated columns are
134225  ** computed after the rowid since they might depend on the value
134226  ** of the rowid.
134227  */
134228  nHidden = 0;
134229  iRegStore = regData;  assert( regData==regRowid+1 );
134230  for(i=0; i<pTab->nCol; i++, iRegStore++){
134231    int k;
134232    u32 colFlags;
134233    assert( i>=nHidden );
134234    if( i==pTab->iPKey ){
134235      /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
134236      ** using the rowid. So put a NULL in the IPK slot of the record to avoid
134237      ** using excess space.  The file format definition requires this extra
134238      ** NULL - we cannot optimize further by skipping the column completely */
134239      sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
134240      continue;
134241    }
134242    if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
134243      nHidden++;
134244      if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
134245        /* Virtual columns do not participate in OP_MakeRecord.  So back up
134246        ** iRegStore by one slot to compensate for the iRegStore++ in the
134247        ** outer for() loop */
134248        iRegStore--;
134249        continue;
134250      }else if( (colFlags & COLFLAG_STORED)!=0 ){
134251        /* Stored columns are computed later.  But if there are BEFORE
134252        ** triggers, the slots used for stored columns will be OP_Copy-ed
134253        ** to a second block of registers, so the register needs to be
134254        ** initialized to NULL to avoid an uninitialized register read */
134255        if( tmask & TRIGGER_BEFORE ){
134256          sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
134257        }
134258        continue;
134259      }else if( pColumn==0 ){
134260        /* Hidden columns that are not explicitly named in the INSERT
134261        ** get there default value */
134262        sqlite3ExprCodeFactorable(pParse,
134263            sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
134264            iRegStore);
134265        continue;
134266      }
134267    }
134268    if( pColumn ){
134269      assert( pColumn->eU4==EU4_IDX );
134270      for(j=0; j<pColumn->nId && pColumn->a[j].u4.idx!=i; j++){}
134271      if( j>=pColumn->nId ){
134272        /* A column not named in the insert column list gets its
134273        ** default value */
134274        sqlite3ExprCodeFactorable(pParse,
134275            sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
134276            iRegStore);
134277        continue;
134278      }
134279      k = j;
134280    }else if( nColumn==0 ){
134281      /* This is INSERT INTO ... DEFAULT VALUES.  Load the default value. */
134282      sqlite3ExprCodeFactorable(pParse,
134283          sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
134284          iRegStore);
134285      continue;
134286    }else{
134287      k = i - nHidden;
134288    }
134289
134290    if( useTempTable ){
134291      sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
134292    }else if( pSelect ){
134293      if( regFromSelect!=regData ){
134294        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
134295      }
134296    }else{
134297      Expr *pX = pList->a[k].pExpr;
134298      int y = sqlite3ExprCodeTarget(pParse, pX, iRegStore);
134299      if( y!=iRegStore ){
134300        sqlite3VdbeAddOp2(v,
134301          ExprHasProperty(pX, EP_Subquery) ? OP_Copy : OP_SCopy, y, iRegStore);
134302      }
134303    }
134304  }
134305
134306
134307  /* Run the BEFORE and INSTEAD OF triggers, if there are any
134308  */
134309  endOfLoop = sqlite3VdbeMakeLabel(pParse);
134310  if( tmask & TRIGGER_BEFORE ){
134311    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
134312
134313    /* build the NEW.* reference row.  Note that if there is an INTEGER
134314    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
134315    ** translated into a unique ID for the row.  But on a BEFORE trigger,
134316    ** we do not know what the unique ID will be (because the insert has
134317    ** not happened yet) so we substitute a rowid of -1
134318    */
134319    if( ipkColumn<0 ){
134320      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
134321    }else{
134322      int addr1;
134323      assert( !withoutRowid );
134324      if( useTempTable ){
134325        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
134326      }else{
134327        assert( pSelect==0 );  /* Otherwise useTempTable is true */
134328        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
134329      }
134330      addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
134331      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
134332      sqlite3VdbeJumpHere(v, addr1);
134333      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
134334    }
134335
134336    /* Copy the new data already generated. */
134337    assert( pTab->nNVCol>0 || pParse->nErr>0 );
134338    sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
134339
134340#ifndef SQLITE_OMIT_GENERATED_COLUMNS
134341    /* Compute the new value for generated columns after all other
134342    ** columns have already been computed.  This must be done after
134343    ** computing the ROWID in case one of the generated columns
134344    ** refers to the ROWID. */
134345    if( pTab->tabFlags & TF_HasGenerated ){
134346      testcase( pTab->tabFlags & TF_HasVirtual );
134347      testcase( pTab->tabFlags & TF_HasStored );
134348      sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
134349    }
134350#endif
134351
134352    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
134353    ** do not attempt any conversions before assembling the record.
134354    ** If this is a real table, attempt conversions as required by the
134355    ** table column affinities.
134356    */
134357    if( !isView ){
134358      sqlite3TableAffinity(v, pTab, regCols+1);
134359    }
134360
134361    /* Fire BEFORE or INSTEAD OF triggers */
134362    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
134363        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
134364
134365    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
134366  }
134367
134368  if( !isView ){
134369    if( IsVirtual(pTab) ){
134370      /* The row that the VUpdate opcode will delete: none */
134371      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
134372    }
134373    if( ipkColumn>=0 ){
134374      /* Compute the new rowid */
134375      if( useTempTable ){
134376        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
134377      }else if( pSelect ){
134378        /* Rowid already initialized at tag-20191021-001 */
134379      }else{
134380        Expr *pIpk = pList->a[ipkColumn].pExpr;
134381        if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
134382          sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
134383          appendFlag = 1;
134384        }else{
134385          sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
134386        }
134387      }
134388      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
134389      ** to generate a unique primary key value.
134390      */
134391      if( !appendFlag ){
134392        int addr1;
134393        if( !IsVirtual(pTab) ){
134394          addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
134395          sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
134396          sqlite3VdbeJumpHere(v, addr1);
134397        }else{
134398          addr1 = sqlite3VdbeCurrentAddr(v);
134399          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
134400        }
134401        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
134402      }
134403    }else if( IsVirtual(pTab) || withoutRowid ){
134404      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
134405    }else{
134406      sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
134407      appendFlag = 1;
134408    }
134409    autoIncStep(pParse, regAutoinc, regRowid);
134410
134411#ifndef SQLITE_OMIT_GENERATED_COLUMNS
134412    /* Compute the new value for generated columns after all other
134413    ** columns have already been computed.  This must be done after
134414    ** computing the ROWID in case one of the generated columns
134415    ** is derived from the INTEGER PRIMARY KEY. */
134416    if( pTab->tabFlags & TF_HasGenerated ){
134417      sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
134418    }
134419#endif
134420
134421    /* Generate code to check constraints and generate index keys and
134422    ** do the insertion.
134423    */
134424#ifndef SQLITE_OMIT_VIRTUALTABLE
134425    if( IsVirtual(pTab) ){
134426      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
134427      sqlite3VtabMakeWritable(pParse, pTab);
134428      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
134429      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
134430      sqlite3MayAbort(pParse);
134431    }else
134432#endif
134433    {
134434      int isReplace = 0;/* Set to true if constraints may cause a replace */
134435      int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
134436      sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
134437          regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
134438      );
134439      if( db->flags & SQLITE_ForeignKeys ){
134440        sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
134441      }
134442
134443      /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
134444      ** constraints or (b) there are no triggers and this table is not a
134445      ** parent table in a foreign key constraint. It is safe to set the
134446      ** flag in the second case as if any REPLACE constraint is hit, an
134447      ** OP_Delete or OP_IdxDelete instruction will be executed on each
134448      ** cursor that is disturbed. And these instructions both clear the
134449      ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
134450      ** functionality.  */
134451      bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
134452      sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
134453          regIns, aRegIdx, 0, appendFlag, bUseSeek
134454      );
134455    }
134456#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
134457  }else if( pParse->bReturning ){
134458    /* If there is a RETURNING clause, populate the rowid register with
134459    ** constant value -1, in case one or more of the returned expressions
134460    ** refer to the "rowid" of the view.  */
134461    sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
134462#endif
134463  }
134464
134465  /* Update the count of rows that are inserted
134466  */
134467  if( regRowCount ){
134468    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
134469  }
134470
134471  if( pTrigger ){
134472    /* Code AFTER triggers */
134473    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
134474        pTab, regData-2-pTab->nCol, onError, endOfLoop);
134475  }
134476
134477  /* The bottom of the main insertion loop, if the data source
134478  ** is a SELECT statement.
134479  */
134480  sqlite3VdbeResolveLabel(v, endOfLoop);
134481  if( useTempTable ){
134482    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
134483    sqlite3VdbeJumpHere(v, addrInsTop);
134484    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
134485  }else if( pSelect ){
134486    sqlite3VdbeGoto(v, addrCont);
134487#ifdef SQLITE_DEBUG
134488    /* If we are jumping back to an OP_Yield that is preceded by an
134489    ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
134490    ** OP_ReleaseReg will be included in the loop. */
134491    if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
134492      assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
134493      sqlite3VdbeChangeP5(v, 1);
134494    }
134495#endif
134496    sqlite3VdbeJumpHere(v, addrInsTop);
134497  }
134498
134499#ifndef SQLITE_OMIT_XFER_OPT
134500insert_end:
134501#endif /* SQLITE_OMIT_XFER_OPT */
134502  /* Update the sqlite_sequence table by storing the content of the
134503  ** maximum rowid counter values recorded while inserting into
134504  ** autoincrement tables.
134505  */
134506  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
134507    sqlite3AutoincrementEnd(pParse);
134508  }
134509
134510  /*
134511  ** Return the number of rows inserted. If this routine is
134512  ** generating code because of a call to sqlite3NestedParse(), do not
134513  ** invoke the callback function.
134514  */
134515  if( regRowCount ){
134516    sqlite3CodeChangeCount(v, regRowCount, "rows inserted");
134517  }
134518
134519insert_cleanup:
134520  sqlite3SrcListDelete(db, pTabList);
134521  sqlite3ExprListDelete(db, pList);
134522  sqlite3UpsertDelete(db, pUpsert);
134523  sqlite3SelectDelete(db, pSelect);
134524  sqlite3IdListDelete(db, pColumn);
134525  if( aRegIdx ) sqlite3DbNNFreeNN(db, aRegIdx);
134526}
134527
134528/* Make sure "isView" and other macros defined above are undefined. Otherwise
134529** they may interfere with compilation of other functions in this file
134530** (or in another file, if this file becomes part of the amalgamation).  */
134531#ifdef isView
134532 #undef isView
134533#endif
134534#ifdef pTrigger
134535 #undef pTrigger
134536#endif
134537#ifdef tmask
134538 #undef tmask
134539#endif
134540
134541/*
134542** Meanings of bits in of pWalker->eCode for
134543** sqlite3ExprReferencesUpdatedColumn()
134544*/
134545#define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
134546#define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
134547
134548/* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
134549*  Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
134550** expression node references any of the
134551** columns that are being modified by an UPDATE statement.
134552*/
134553static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
134554  if( pExpr->op==TK_COLUMN ){
134555    assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
134556    if( pExpr->iColumn>=0 ){
134557      if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
134558        pWalker->eCode |= CKCNSTRNT_COLUMN;
134559      }
134560    }else{
134561      pWalker->eCode |= CKCNSTRNT_ROWID;
134562    }
134563  }
134564  return WRC_Continue;
134565}
134566
134567/*
134568** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
134569** only columns that are modified by the UPDATE are those for which
134570** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
134571**
134572** Return true if CHECK constraint pExpr uses any of the
134573** changing columns (or the rowid if it is changing).  In other words,
134574** return true if this CHECK constraint must be validated for
134575** the new row in the UPDATE statement.
134576**
134577** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
134578** The operation of this routine is the same - return true if an only if
134579** the expression uses one or more of columns identified by the second and
134580** third arguments.
134581*/
134582SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(
134583  Expr *pExpr,    /* The expression to be checked */
134584  int *aiChng,    /* aiChng[x]>=0 if column x changed by the UPDATE */
134585  int chngRowid   /* True if UPDATE changes the rowid */
134586){
134587  Walker w;
134588  memset(&w, 0, sizeof(w));
134589  w.eCode = 0;
134590  w.xExprCallback = checkConstraintExprNode;
134591  w.u.aiCol = aiChng;
134592  sqlite3WalkExpr(&w, pExpr);
134593  if( !chngRowid ){
134594    testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
134595    w.eCode &= ~CKCNSTRNT_ROWID;
134596  }
134597  testcase( w.eCode==0 );
134598  testcase( w.eCode==CKCNSTRNT_COLUMN );
134599  testcase( w.eCode==CKCNSTRNT_ROWID );
134600  testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
134601  return w.eCode!=0;
134602}
134603
134604/*
134605** The sqlite3GenerateConstraintChecks() routine usually wants to visit
134606** the indexes of a table in the order provided in the Table->pIndex list.
134607** However, sometimes (rarely - when there is an upsert) it wants to visit
134608** the indexes in a different order.  The following data structures accomplish
134609** this.
134610**
134611** The IndexIterator object is used to walk through all of the indexes
134612** of a table in either Index.pNext order, or in some other order established
134613** by an array of IndexListTerm objects.
134614*/
134615typedef struct IndexListTerm IndexListTerm;
134616typedef struct IndexIterator IndexIterator;
134617struct IndexIterator {
134618  int eType;    /* 0 for Index.pNext list.  1 for an array of IndexListTerm */
134619  int i;        /* Index of the current item from the list */
134620  union {
134621    struct {    /* Use this object for eType==0: A Index.pNext list */
134622      Index *pIdx;   /* The current Index */
134623    } lx;
134624    struct {    /* Use this object for eType==1; Array of IndexListTerm */
134625      int nIdx;               /* Size of the array */
134626      IndexListTerm *aIdx;    /* Array of IndexListTerms */
134627    } ax;
134628  } u;
134629};
134630
134631/* When IndexIterator.eType==1, then each index is an array of instances
134632** of the following object
134633*/
134634struct IndexListTerm {
134635  Index *p;  /* The index */
134636  int ix;    /* Which entry in the original Table.pIndex list is this index*/
134637};
134638
134639/* Return the first index on the list */
134640static Index *indexIteratorFirst(IndexIterator *pIter, int *pIx){
134641  assert( pIter->i==0 );
134642  if( pIter->eType ){
134643    *pIx = pIter->u.ax.aIdx[0].ix;
134644    return pIter->u.ax.aIdx[0].p;
134645  }else{
134646    *pIx = 0;
134647    return pIter->u.lx.pIdx;
134648  }
134649}
134650
134651/* Return the next index from the list.  Return NULL when out of indexes */
134652static Index *indexIteratorNext(IndexIterator *pIter, int *pIx){
134653  if( pIter->eType ){
134654    int i = ++pIter->i;
134655    if( i>=pIter->u.ax.nIdx ){
134656      *pIx = i;
134657      return 0;
134658    }
134659    *pIx = pIter->u.ax.aIdx[i].ix;
134660    return pIter->u.ax.aIdx[i].p;
134661  }else{
134662    ++(*pIx);
134663    pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
134664    return pIter->u.lx.pIdx;
134665  }
134666}
134667
134668/*
134669** Generate code to do constraint checks prior to an INSERT or an UPDATE
134670** on table pTab.
134671**
134672** The regNewData parameter is the first register in a range that contains
134673** the data to be inserted or the data after the update.  There will be
134674** pTab->nCol+1 registers in this range.  The first register (the one
134675** that regNewData points to) will contain the new rowid, or NULL in the
134676** case of a WITHOUT ROWID table.  The second register in the range will
134677** contain the content of the first table column.  The third register will
134678** contain the content of the second table column.  And so forth.
134679**
134680** The regOldData parameter is similar to regNewData except that it contains
134681** the data prior to an UPDATE rather than afterwards.  regOldData is zero
134682** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
134683** checking regOldData for zero.
134684**
134685** For an UPDATE, the pkChng boolean is true if the true primary key (the
134686** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
134687** might be modified by the UPDATE.  If pkChng is false, then the key of
134688** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
134689**
134690** For an INSERT, the pkChng boolean indicates whether or not the rowid
134691** was explicitly specified as part of the INSERT statement.  If pkChng
134692** is zero, it means that the either rowid is computed automatically or
134693** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
134694** pkChng will only be true if the INSERT statement provides an integer
134695** value for either the rowid column or its INTEGER PRIMARY KEY alias.
134696**
134697** The code generated by this routine will store new index entries into
134698** registers identified by aRegIdx[].  No index entry is created for
134699** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
134700** the same as the order of indices on the linked list of indices
134701** at pTab->pIndex.
134702**
134703** (2019-05-07) The generated code also creates a new record for the
134704** main table, if pTab is a rowid table, and stores that record in the
134705** register identified by aRegIdx[nIdx] - in other words in the first
134706** entry of aRegIdx[] past the last index.  It is important that the
134707** record be generated during constraint checks to avoid affinity changes
134708** to the register content that occur after constraint checks but before
134709** the new record is inserted.
134710**
134711** The caller must have already opened writeable cursors on the main
134712** table and all applicable indices (that is to say, all indices for which
134713** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
134714** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
134715** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
134716** for the first index in the pTab->pIndex list.  Cursors for other indices
134717** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
134718**
134719** This routine also generates code to check constraints.  NOT NULL,
134720** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
134721** then the appropriate action is performed.  There are five possible
134722** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
134723**
134724**  Constraint type  Action       What Happens
134725**  ---------------  ----------   ----------------------------------------
134726**  any              ROLLBACK     The current transaction is rolled back and
134727**                                sqlite3_step() returns immediately with a
134728**                                return code of SQLITE_CONSTRAINT.
134729**
134730**  any              ABORT        Back out changes from the current command
134731**                                only (do not do a complete rollback) then
134732**                                cause sqlite3_step() to return immediately
134733**                                with SQLITE_CONSTRAINT.
134734**
134735**  any              FAIL         Sqlite3_step() returns immediately with a
134736**                                return code of SQLITE_CONSTRAINT.  The
134737**                                transaction is not rolled back and any
134738**                                changes to prior rows are retained.
134739**
134740**  any              IGNORE       The attempt in insert or update the current
134741**                                row is skipped, without throwing an error.
134742**                                Processing continues with the next row.
134743**                                (There is an immediate jump to ignoreDest.)
134744**
134745**  NOT NULL         REPLACE      The NULL value is replace by the default
134746**                                value for that column.  If the default value
134747**                                is NULL, the action is the same as ABORT.
134748**
134749**  UNIQUE           REPLACE      The other row that conflicts with the row
134750**                                being inserted is removed.
134751**
134752**  CHECK            REPLACE      Illegal.  The results in an exception.
134753**
134754** Which action to take is determined by the overrideError parameter.
134755** Or if overrideError==OE_Default, then the pParse->onError parameter
134756** is used.  Or if pParse->onError==OE_Default then the onError value
134757** for the constraint is used.
134758*/
134759SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
134760  Parse *pParse,       /* The parser context */
134761  Table *pTab,         /* The table being inserted or updated */
134762  int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
134763  int iDataCur,        /* Canonical data cursor (main table or PK index) */
134764  int iIdxCur,         /* First index cursor */
134765  int regNewData,      /* First register in a range holding values to insert */
134766  int regOldData,      /* Previous content.  0 for INSERTs */
134767  u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
134768  u8 overrideError,    /* Override onError to this if not OE_Default */
134769  int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
134770  int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
134771  int *aiChng,         /* column i is unchanged if aiChng[i]<0 */
134772  Upsert *pUpsert      /* ON CONFLICT clauses, if any.  NULL otherwise */
134773){
134774  Vdbe *v;             /* VDBE under construction */
134775  Index *pIdx;         /* Pointer to one of the indices */
134776  Index *pPk = 0;      /* The PRIMARY KEY index for WITHOUT ROWID tables */
134777  sqlite3 *db;         /* Database connection */
134778  int i;               /* loop counter */
134779  int ix;              /* Index loop counter */
134780  int nCol;            /* Number of columns */
134781  int onError;         /* Conflict resolution strategy */
134782  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
134783  int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
134784  Upsert *pUpsertClause = 0;  /* The specific ON CONFLICT clause for pIdx */
134785  u8 isUpdate;           /* True if this is an UPDATE operation */
134786  u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
134787  int upsertIpkReturn = 0; /* Address of Goto at end of IPK uniqueness check */
134788  int upsertIpkDelay = 0;  /* Address of Goto to bypass initial IPK check */
134789  int ipkTop = 0;        /* Top of the IPK uniqueness check */
134790  int ipkBottom = 0;     /* OP_Goto at the end of the IPK uniqueness check */
134791  /* Variables associated with retesting uniqueness constraints after
134792  ** replace triggers fire have run */
134793  int regTrigCnt;       /* Register used to count replace trigger invocations */
134794  int addrRecheck = 0;  /* Jump here to recheck all uniqueness constraints */
134795  int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
134796  Trigger *pTrigger;    /* List of DELETE triggers on the table pTab */
134797  int nReplaceTrig = 0; /* Number of replace triggers coded */
134798  IndexIterator sIdxIter;  /* Index iterator */
134799
134800  isUpdate = regOldData!=0;
134801  db = pParse->db;
134802  v = pParse->pVdbe;
134803  assert( v!=0 );
134804  assert( !IsView(pTab) );  /* This table is not a VIEW */
134805  nCol = pTab->nCol;
134806
134807  /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
134808  ** normal rowid tables.  nPkField is the number of key fields in the
134809  ** pPk index or 1 for a rowid table.  In other words, nPkField is the
134810  ** number of fields in the true primary key of the table. */
134811  if( HasRowid(pTab) ){
134812    pPk = 0;
134813    nPkField = 1;
134814  }else{
134815    pPk = sqlite3PrimaryKeyIndex(pTab);
134816    nPkField = pPk->nKeyCol;
134817  }
134818
134819  /* Record that this module has started */
134820  VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
134821                     iDataCur, iIdxCur, regNewData, regOldData, pkChng));
134822
134823  /* Test all NOT NULL constraints.
134824  */
134825  if( pTab->tabFlags & TF_HasNotNull ){
134826    int b2ndPass = 0;         /* True if currently running 2nd pass */
134827    int nSeenReplace = 0;     /* Number of ON CONFLICT REPLACE operations */
134828    int nGenerated = 0;       /* Number of generated columns with NOT NULL */
134829    while(1){  /* Make 2 passes over columns. Exit loop via "break" */
134830      for(i=0; i<nCol; i++){
134831        int iReg;                        /* Register holding column value */
134832        Column *pCol = &pTab->aCol[i];   /* The column to check for NOT NULL */
134833        int isGenerated;                 /* non-zero if column is generated */
134834        onError = pCol->notNull;
134835        if( onError==OE_None ) continue; /* No NOT NULL on this column */
134836        if( i==pTab->iPKey ){
134837          continue;        /* ROWID is never NULL */
134838        }
134839        isGenerated = pCol->colFlags & COLFLAG_GENERATED;
134840        if( isGenerated && !b2ndPass ){
134841          nGenerated++;
134842          continue;        /* Generated columns processed on 2nd pass */
134843        }
134844        if( aiChng && aiChng[i]<0 && !isGenerated ){
134845          /* Do not check NOT NULL on columns that do not change */
134846          continue;
134847        }
134848        if( overrideError!=OE_Default ){
134849          onError = overrideError;
134850        }else if( onError==OE_Default ){
134851          onError = OE_Abort;
134852        }
134853        if( onError==OE_Replace ){
134854          if( b2ndPass        /* REPLACE becomes ABORT on the 2nd pass */
134855           || pCol->iDflt==0  /* REPLACE is ABORT if no DEFAULT value */
134856          ){
134857            testcase( pCol->colFlags & COLFLAG_VIRTUAL );
134858            testcase( pCol->colFlags & COLFLAG_STORED );
134859            testcase( pCol->colFlags & COLFLAG_GENERATED );
134860            onError = OE_Abort;
134861          }else{
134862            assert( !isGenerated );
134863          }
134864        }else if( b2ndPass && !isGenerated ){
134865          continue;
134866        }
134867        assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
134868            || onError==OE_Ignore || onError==OE_Replace );
134869        testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
134870        iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
134871        switch( onError ){
134872          case OE_Replace: {
134873            int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
134874            VdbeCoverage(v);
134875            assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
134876            nSeenReplace++;
134877            sqlite3ExprCodeCopy(pParse,
134878               sqlite3ColumnExpr(pTab, pCol), iReg);
134879            sqlite3VdbeJumpHere(v, addr1);
134880            break;
134881          }
134882          case OE_Abort:
134883            sqlite3MayAbort(pParse);
134884            /* no break */ deliberate_fall_through
134885          case OE_Rollback:
134886          case OE_Fail: {
134887            char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
134888                                        pCol->zCnName);
134889            testcase( zMsg==0 && db->mallocFailed==0 );
134890            sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
134891                              onError, iReg);
134892            sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
134893            sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
134894            VdbeCoverage(v);
134895            break;
134896          }
134897          default: {
134898            assert( onError==OE_Ignore );
134899            sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
134900            VdbeCoverage(v);
134901            break;
134902          }
134903        } /* end switch(onError) */
134904      } /* end loop i over columns */
134905      if( nGenerated==0 && nSeenReplace==0 ){
134906        /* If there are no generated columns with NOT NULL constraints
134907        ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
134908        ** pass is sufficient */
134909        break;
134910      }
134911      if( b2ndPass ) break;  /* Never need more than 2 passes */
134912      b2ndPass = 1;
134913#ifndef SQLITE_OMIT_GENERATED_COLUMNS
134914      if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
134915        /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
134916        ** first pass, recomputed values for all generated columns, as
134917        ** those values might depend on columns affected by the REPLACE.
134918        */
134919        sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
134920      }
134921#endif
134922    } /* end of 2-pass loop */
134923  } /* end if( has-not-null-constraints ) */
134924
134925  /* Test all CHECK constraints
134926  */
134927#ifndef SQLITE_OMIT_CHECK
134928  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
134929    ExprList *pCheck = pTab->pCheck;
134930    pParse->iSelfTab = -(regNewData+1);
134931    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
134932    for(i=0; i<pCheck->nExpr; i++){
134933      int allOk;
134934      Expr *pCopy;
134935      Expr *pExpr = pCheck->a[i].pExpr;
134936      if( aiChng
134937       && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
134938      ){
134939        /* The check constraints do not reference any of the columns being
134940        ** updated so there is no point it verifying the check constraint */
134941        continue;
134942      }
134943      if( bAffinityDone==0 ){
134944        sqlite3TableAffinity(v, pTab, regNewData+1);
134945        bAffinityDone = 1;
134946      }
134947      allOk = sqlite3VdbeMakeLabel(pParse);
134948      sqlite3VdbeVerifyAbortable(v, onError);
134949      pCopy = sqlite3ExprDup(db, pExpr, 0);
134950      if( !db->mallocFailed ){
134951        sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
134952      }
134953      sqlite3ExprDelete(db, pCopy);
134954      if( onError==OE_Ignore ){
134955        sqlite3VdbeGoto(v, ignoreDest);
134956      }else{
134957        char *zName = pCheck->a[i].zEName;
134958        assert( zName!=0 || pParse->db->mallocFailed );
134959        if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
134960        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
134961                              onError, zName, P4_TRANSIENT,
134962                              P5_ConstraintCheck);
134963      }
134964      sqlite3VdbeResolveLabel(v, allOk);
134965    }
134966    pParse->iSelfTab = 0;
134967  }
134968#endif /* !defined(SQLITE_OMIT_CHECK) */
134969
134970  /* UNIQUE and PRIMARY KEY constraints should be handled in the following
134971  ** order:
134972  **
134973  **   (1)  OE_Update
134974  **   (2)  OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
134975  **   (3)  OE_Replace
134976  **
134977  ** OE_Fail and OE_Ignore must happen before any changes are made.
134978  ** OE_Update guarantees that only a single row will change, so it
134979  ** must happen before OE_Replace.  Technically, OE_Abort and OE_Rollback
134980  ** could happen in any order, but they are grouped up front for
134981  ** convenience.
134982  **
134983  ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
134984  ** The order of constraints used to have OE_Update as (2) and OE_Abort
134985  ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
134986  ** constraint before any others, so it had to be moved.
134987  **
134988  ** Constraint checking code is generated in this order:
134989  **   (A)  The rowid constraint
134990  **   (B)  Unique index constraints that do not have OE_Replace as their
134991  **        default conflict resolution strategy
134992  **   (C)  Unique index that do use OE_Replace by default.
134993  **
134994  ** The ordering of (2) and (3) is accomplished by making sure the linked
134995  ** list of indexes attached to a table puts all OE_Replace indexes last
134996  ** in the list.  See sqlite3CreateIndex() for where that happens.
134997  */
134998  sIdxIter.eType = 0;
134999  sIdxIter.i = 0;
135000  sIdxIter.u.ax.aIdx = 0;  /* Silence harmless compiler warning */
135001  sIdxIter.u.lx.pIdx = pTab->pIndex;
135002  if( pUpsert ){
135003    if( pUpsert->pUpsertTarget==0 ){
135004      /* There is just on ON CONFLICT clause and it has no constraint-target */
135005      assert( pUpsert->pNextUpsert==0 );
135006      if( pUpsert->isDoUpdate==0 ){
135007        /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
135008        ** Make all unique constraint resolution be OE_Ignore */
135009        overrideError = OE_Ignore;
135010        pUpsert = 0;
135011      }else{
135012        /* A single ON CONFLICT DO UPDATE.  Make all resolutions OE_Update */
135013        overrideError = OE_Update;
135014      }
135015    }else if( pTab->pIndex!=0 ){
135016      /* Otherwise, we'll need to run the IndexListTerm array version of the
135017      ** iterator to ensure that all of the ON CONFLICT conditions are
135018      ** checked first and in order. */
135019      int nIdx, jj;
135020      u64 nByte;
135021      Upsert *pTerm;
135022      u8 *bUsed;
135023      for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
135024         assert( aRegIdx[nIdx]>0 );
135025      }
135026      sIdxIter.eType = 1;
135027      sIdxIter.u.ax.nIdx = nIdx;
135028      nByte = (sizeof(IndexListTerm)+1)*nIdx + nIdx;
135029      sIdxIter.u.ax.aIdx = sqlite3DbMallocZero(db, nByte);
135030      if( sIdxIter.u.ax.aIdx==0 ) return; /* OOM */
135031      bUsed = (u8*)&sIdxIter.u.ax.aIdx[nIdx];
135032      pUpsert->pToFree = sIdxIter.u.ax.aIdx;
135033      for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
135034        if( pTerm->pUpsertTarget==0 ) break;
135035        if( pTerm->pUpsertIdx==0 ) continue;  /* Skip ON CONFLICT for the IPK */
135036        jj = 0;
135037        pIdx = pTab->pIndex;
135038        while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
135039           pIdx = pIdx->pNext;
135040           jj++;
135041        }
135042        if( bUsed[jj] ) continue; /* Duplicate ON CONFLICT clause ignored */
135043        bUsed[jj] = 1;
135044        sIdxIter.u.ax.aIdx[i].p = pIdx;
135045        sIdxIter.u.ax.aIdx[i].ix = jj;
135046        i++;
135047      }
135048      for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
135049        if( bUsed[jj] ) continue;
135050        sIdxIter.u.ax.aIdx[i].p = pIdx;
135051        sIdxIter.u.ax.aIdx[i].ix = jj;
135052        i++;
135053      }
135054      assert( i==nIdx );
135055    }
135056  }
135057
135058  /* Determine if it is possible that triggers (either explicitly coded
135059  ** triggers or FK resolution actions) might run as a result of deletes
135060  ** that happen when OE_Replace conflict resolution occurs. (Call these
135061  ** "replace triggers".)  If any replace triggers run, we will need to
135062  ** recheck all of the uniqueness constraints after they have all run.
135063  ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
135064  **
135065  ** If replace triggers are a possibility, then
135066  **
135067  **   (1) Allocate register regTrigCnt and initialize it to zero.
135068  **       That register will count the number of replace triggers that
135069  **       fire.  Constraint recheck only occurs if the number is positive.
135070  **   (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
135071  **   (3) Initialize addrRecheck and lblRecheckOk
135072  **
135073  ** The uniqueness rechecking code will create a series of tests to run
135074  ** in a second pass.  The addrRecheck and lblRecheckOk variables are
135075  ** used to link together these tests which are separated from each other
135076  ** in the generate bytecode.
135077  */
135078  if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
135079    /* There are not DELETE triggers nor FK constraints.  No constraint
135080    ** rechecks are needed. */
135081    pTrigger = 0;
135082    regTrigCnt = 0;
135083  }else{
135084    if( db->flags&SQLITE_RecTriggers ){
135085      pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
135086      regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
135087    }else{
135088      pTrigger = 0;
135089      regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
135090    }
135091    if( regTrigCnt ){
135092      /* Replace triggers might exist.  Allocate the counter and
135093      ** initialize it to zero. */
135094      regTrigCnt = ++pParse->nMem;
135095      sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
135096      VdbeComment((v, "trigger count"));
135097      lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
135098      addrRecheck = lblRecheckOk;
135099    }
135100  }
135101
135102  /* If rowid is changing, make sure the new rowid does not previously
135103  ** exist in the table.
135104  */
135105  if( pkChng && pPk==0 ){
135106    int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
135107
135108    /* Figure out what action to take in case of a rowid collision */
135109    onError = pTab->keyConf;
135110    if( overrideError!=OE_Default ){
135111      onError = overrideError;
135112    }else if( onError==OE_Default ){
135113      onError = OE_Abort;
135114    }
135115
135116    /* figure out whether or not upsert applies in this case */
135117    if( pUpsert ){
135118      pUpsertClause = sqlite3UpsertOfIndex(pUpsert,0);
135119      if( pUpsertClause!=0 ){
135120        if( pUpsertClause->isDoUpdate==0 ){
135121          onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
135122        }else{
135123          onError = OE_Update;  /* DO UPDATE */
135124        }
135125      }
135126      if( pUpsertClause!=pUpsert ){
135127        /* The first ON CONFLICT clause has a conflict target other than
135128        ** the IPK.  We have to jump ahead to that first ON CONFLICT clause
135129        ** and then come back here and deal with the IPK afterwards */
135130        upsertIpkDelay = sqlite3VdbeAddOp0(v, OP_Goto);
135131      }
135132    }
135133
135134    /* If the response to a rowid conflict is REPLACE but the response
135135    ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
135136    ** to defer the running of the rowid conflict checking until after
135137    ** the UNIQUE constraints have run.
135138    */
135139    if( onError==OE_Replace      /* IPK rule is REPLACE */
135140     && onError!=overrideError   /* Rules for other constraints are different */
135141     && pTab->pIndex             /* There exist other constraints */
135142     && !upsertIpkDelay          /* IPK check already deferred by UPSERT */
135143    ){
135144      ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
135145      VdbeComment((v, "defer IPK REPLACE until last"));
135146    }
135147
135148    if( isUpdate ){
135149      /* pkChng!=0 does not mean that the rowid has changed, only that
135150      ** it might have changed.  Skip the conflict logic below if the rowid
135151      ** is unchanged. */
135152      sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
135153      sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
135154      VdbeCoverage(v);
135155    }
135156
135157    /* Check to see if the new rowid already exists in the table.  Skip
135158    ** the following conflict logic if it does not. */
135159    VdbeNoopComment((v, "uniqueness check for ROWID"));
135160    sqlite3VdbeVerifyAbortable(v, onError);
135161    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
135162    VdbeCoverage(v);
135163
135164    switch( onError ){
135165      default: {
135166        onError = OE_Abort;
135167        /* no break */ deliberate_fall_through
135168      }
135169      case OE_Rollback:
135170      case OE_Abort:
135171      case OE_Fail: {
135172        testcase( onError==OE_Rollback );
135173        testcase( onError==OE_Abort );
135174        testcase( onError==OE_Fail );
135175        sqlite3RowidConstraint(pParse, onError, pTab);
135176        break;
135177      }
135178      case OE_Replace: {
135179        /* If there are DELETE triggers on this table and the
135180        ** recursive-triggers flag is set, call GenerateRowDelete() to
135181        ** remove the conflicting row from the table. This will fire
135182        ** the triggers and remove both the table and index b-tree entries.
135183        **
135184        ** Otherwise, if there are no triggers or the recursive-triggers
135185        ** flag is not set, but the table has one or more indexes, call
135186        ** GenerateRowIndexDelete(). This removes the index b-tree entries
135187        ** only. The table b-tree entry will be replaced by the new entry
135188        ** when it is inserted.
135189        **
135190        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
135191        ** also invoke MultiWrite() to indicate that this VDBE may require
135192        ** statement rollback (if the statement is aborted after the delete
135193        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
135194        ** but being more selective here allows statements like:
135195        **
135196        **   REPLACE INTO t(rowid) VALUES($newrowid)
135197        **
135198        ** to run without a statement journal if there are no indexes on the
135199        ** table.
135200        */
135201        if( regTrigCnt ){
135202          sqlite3MultiWrite(pParse);
135203          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
135204                                   regNewData, 1, 0, OE_Replace, 1, -1);
135205          sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
135206          nReplaceTrig++;
135207        }else{
135208#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
135209          assert( HasRowid(pTab) );
135210          /* This OP_Delete opcode fires the pre-update-hook only. It does
135211          ** not modify the b-tree. It is more efficient to let the coming
135212          ** OP_Insert replace the existing entry than it is to delete the
135213          ** existing entry and then insert a new one. */
135214          sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
135215          sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
135216#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
135217          if( pTab->pIndex ){
135218            sqlite3MultiWrite(pParse);
135219            sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
135220          }
135221        }
135222        seenReplace = 1;
135223        break;
135224      }
135225#ifndef SQLITE_OMIT_UPSERT
135226      case OE_Update: {
135227        sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
135228        /* no break */ deliberate_fall_through
135229      }
135230#endif
135231      case OE_Ignore: {
135232        testcase( onError==OE_Ignore );
135233        sqlite3VdbeGoto(v, ignoreDest);
135234        break;
135235      }
135236    }
135237    sqlite3VdbeResolveLabel(v, addrRowidOk);
135238    if( pUpsert && pUpsertClause!=pUpsert ){
135239      upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
135240    }else if( ipkTop ){
135241      ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
135242      sqlite3VdbeJumpHere(v, ipkTop-1);
135243    }
135244  }
135245
135246  /* Test all UNIQUE constraints by creating entries for each UNIQUE
135247  ** index and making sure that duplicate entries do not already exist.
135248  ** Compute the revised record entries for indices as we go.
135249  **
135250  ** This loop also handles the case of the PRIMARY KEY index for a
135251  ** WITHOUT ROWID table.
135252  */
135253  for(pIdx = indexIteratorFirst(&sIdxIter, &ix);
135254      pIdx;
135255      pIdx = indexIteratorNext(&sIdxIter, &ix)
135256  ){
135257    int regIdx;          /* Range of registers holding content for pIdx */
135258    int regR;            /* Range of registers holding conflicting PK */
135259    int iThisCur;        /* Cursor for this UNIQUE index */
135260    int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
135261    int addrConflictCk;  /* First opcode in the conflict check logic */
135262
135263    if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
135264    if( pUpsert ){
135265      pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
135266      if( upsertIpkDelay && pUpsertClause==pUpsert ){
135267        sqlite3VdbeJumpHere(v, upsertIpkDelay);
135268      }
135269    }
135270    addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
135271    if( bAffinityDone==0 ){
135272      sqlite3TableAffinity(v, pTab, regNewData+1);
135273      bAffinityDone = 1;
135274    }
135275    VdbeNoopComment((v, "prep index %s", pIdx->zName));
135276    iThisCur = iIdxCur+ix;
135277
135278
135279    /* Skip partial indices for which the WHERE clause is not true */
135280    if( pIdx->pPartIdxWhere ){
135281      sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
135282      pParse->iSelfTab = -(regNewData+1);
135283      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
135284                            SQLITE_JUMPIFNULL);
135285      pParse->iSelfTab = 0;
135286    }
135287
135288    /* Create a record for this index entry as it should appear after
135289    ** the insert or update.  Store that record in the aRegIdx[ix] register
135290    */
135291    regIdx = aRegIdx[ix]+1;
135292    for(i=0; i<pIdx->nColumn; i++){
135293      int iField = pIdx->aiColumn[i];
135294      int x;
135295      if( iField==XN_EXPR ){
135296        pParse->iSelfTab = -(regNewData+1);
135297        sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
135298        pParse->iSelfTab = 0;
135299        VdbeComment((v, "%s column %d", pIdx->zName, i));
135300      }else if( iField==XN_ROWID || iField==pTab->iPKey ){
135301        x = regNewData;
135302        sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
135303        VdbeComment((v, "rowid"));
135304      }else{
135305        testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
135306        x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
135307        sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
135308        VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
135309      }
135310    }
135311    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
135312    VdbeComment((v, "for %s", pIdx->zName));
135313#ifdef SQLITE_ENABLE_NULL_TRIM
135314    if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
135315      sqlite3SetMakeRecordP5(v, pIdx->pTable);
135316    }
135317#endif
135318    sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
135319
135320    /* In an UPDATE operation, if this index is the PRIMARY KEY index
135321    ** of a WITHOUT ROWID table and there has been no change the
135322    ** primary key, then no collision is possible.  The collision detection
135323    ** logic below can all be skipped. */
135324    if( isUpdate && pPk==pIdx && pkChng==0 ){
135325      sqlite3VdbeResolveLabel(v, addrUniqueOk);
135326      continue;
135327    }
135328
135329    /* Find out what action to take in case there is a uniqueness conflict */
135330    onError = pIdx->onError;
135331    if( onError==OE_None ){
135332      sqlite3VdbeResolveLabel(v, addrUniqueOk);
135333      continue;  /* pIdx is not a UNIQUE index */
135334    }
135335    if( overrideError!=OE_Default ){
135336      onError = overrideError;
135337    }else if( onError==OE_Default ){
135338      onError = OE_Abort;
135339    }
135340
135341    /* Figure out if the upsert clause applies to this index */
135342    if( pUpsertClause ){
135343      if( pUpsertClause->isDoUpdate==0 ){
135344        onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
135345      }else{
135346        onError = OE_Update;  /* DO UPDATE */
135347      }
135348    }
135349
135350    /* Collision detection may be omitted if all of the following are true:
135351    **   (1) The conflict resolution algorithm is REPLACE
135352    **   (2) The table is a WITHOUT ROWID table
135353    **   (3) There are no secondary indexes on the table
135354    **   (4) No delete triggers need to be fired if there is a conflict
135355    **   (5) No FK constraint counters need to be updated if a conflict occurs.
135356    **
135357    ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
135358    ** must be explicitly deleted in order to ensure any pre-update hook
135359    ** is invoked.  */
135360    assert( IsOrdinaryTable(pTab) );
135361#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
135362    if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
135363     && pPk==pIdx                                   /* Condition 2 */
135364     && onError==OE_Replace                         /* Condition 1 */
135365     && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
135366          0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
135367     && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
135368         (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
135369    ){
135370      sqlite3VdbeResolveLabel(v, addrUniqueOk);
135371      continue;
135372    }
135373#endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
135374
135375    /* Check to see if the new index entry will be unique */
135376    sqlite3VdbeVerifyAbortable(v, onError);
135377    addrConflictCk =
135378      sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
135379                           regIdx, pIdx->nKeyCol); VdbeCoverage(v);
135380
135381    /* Generate code to handle collisions */
135382    regR = pIdx==pPk ? regIdx : sqlite3GetTempRange(pParse, nPkField);
135383    if( isUpdate || onError==OE_Replace ){
135384      if( HasRowid(pTab) ){
135385        sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
135386        /* Conflict only if the rowid of the existing index entry
135387        ** is different from old-rowid */
135388        if( isUpdate ){
135389          sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
135390          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
135391          VdbeCoverage(v);
135392        }
135393      }else{
135394        int x;
135395        /* Extract the PRIMARY KEY from the end of the index entry and
135396        ** store it in registers regR..regR+nPk-1 */
135397        if( pIdx!=pPk ){
135398          for(i=0; i<pPk->nKeyCol; i++){
135399            assert( pPk->aiColumn[i]>=0 );
135400            x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
135401            sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
135402            VdbeComment((v, "%s.%s", pTab->zName,
135403                         pTab->aCol[pPk->aiColumn[i]].zCnName));
135404          }
135405        }
135406        if( isUpdate ){
135407          /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
135408          ** table, only conflict if the new PRIMARY KEY values are actually
135409          ** different from the old.  See TH3 withoutrowid04.test.
135410          **
135411          ** For a UNIQUE index, only conflict if the PRIMARY KEY values
135412          ** of the matched index row are different from the original PRIMARY
135413          ** KEY values of this row before the update.  */
135414          int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
135415          int op = OP_Ne;
135416          int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
135417
135418          for(i=0; i<pPk->nKeyCol; i++){
135419            char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
135420            x = pPk->aiColumn[i];
135421            assert( x>=0 );
135422            if( i==(pPk->nKeyCol-1) ){
135423              addrJump = addrUniqueOk;
135424              op = OP_Eq;
135425            }
135426            x = sqlite3TableColumnToStorage(pTab, x);
135427            sqlite3VdbeAddOp4(v, op,
135428                regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
135429            );
135430            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
135431            VdbeCoverageIf(v, op==OP_Eq);
135432            VdbeCoverageIf(v, op==OP_Ne);
135433          }
135434        }
135435      }
135436    }
135437
135438    /* Generate code that executes if the new index entry is not unique */
135439    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
135440        || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
135441    switch( onError ){
135442      case OE_Rollback:
135443      case OE_Abort:
135444      case OE_Fail: {
135445        testcase( onError==OE_Rollback );
135446        testcase( onError==OE_Abort );
135447        testcase( onError==OE_Fail );
135448        sqlite3UniqueConstraint(pParse, onError, pIdx);
135449        break;
135450      }
135451#ifndef SQLITE_OMIT_UPSERT
135452      case OE_Update: {
135453        sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
135454        /* no break */ deliberate_fall_through
135455      }
135456#endif
135457      case OE_Ignore: {
135458        testcase( onError==OE_Ignore );
135459        sqlite3VdbeGoto(v, ignoreDest);
135460        break;
135461      }
135462      default: {
135463        int nConflictCk;   /* Number of opcodes in conflict check logic */
135464
135465        assert( onError==OE_Replace );
135466        nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
135467        assert( nConflictCk>0 || db->mallocFailed );
135468        testcase( nConflictCk<=0 );
135469        testcase( nConflictCk>1 );
135470        if( regTrigCnt ){
135471          sqlite3MultiWrite(pParse);
135472          nReplaceTrig++;
135473        }
135474        if( pTrigger && isUpdate ){
135475          sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
135476        }
135477        sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
135478            regR, nPkField, 0, OE_Replace,
135479            (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
135480        if( pTrigger && isUpdate ){
135481          sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
135482        }
135483        if( regTrigCnt ){
135484          int addrBypass;  /* Jump destination to bypass recheck logic */
135485
135486          sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
135487          addrBypass = sqlite3VdbeAddOp0(v, OP_Goto);  /* Bypass recheck */
135488          VdbeComment((v, "bypass recheck"));
135489
135490          /* Here we insert code that will be invoked after all constraint
135491          ** checks have run, if and only if one or more replace triggers
135492          ** fired. */
135493          sqlite3VdbeResolveLabel(v, lblRecheckOk);
135494          lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
135495          if( pIdx->pPartIdxWhere ){
135496            /* Bypass the recheck if this partial index is not defined
135497            ** for the current row */
135498            sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
135499            VdbeCoverage(v);
135500          }
135501          /* Copy the constraint check code from above, except change
135502          ** the constraint-ok jump destination to be the address of
135503          ** the next retest block */
135504          while( nConflictCk>0 ){
135505            VdbeOp x;    /* Conflict check opcode to copy */
135506            /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
135507            ** Hence, make a complete copy of the opcode, rather than using
135508            ** a pointer to the opcode. */
135509            x = *sqlite3VdbeGetOp(v, addrConflictCk);
135510            if( x.opcode!=OP_IdxRowid ){
135511              int p2;      /* New P2 value for copied conflict check opcode */
135512              const char *zP4;
135513              if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
135514                p2 = lblRecheckOk;
135515              }else{
135516                p2 = x.p2;
135517              }
135518              zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
135519              sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
135520              sqlite3VdbeChangeP5(v, x.p5);
135521              VdbeCoverageIf(v, p2!=x.p2);
135522            }
135523            nConflictCk--;
135524            addrConflictCk++;
135525          }
135526          /* If the retest fails, issue an abort */
135527          sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
135528
135529          sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
135530        }
135531        seenReplace = 1;
135532        break;
135533      }
135534    }
135535    sqlite3VdbeResolveLabel(v, addrUniqueOk);
135536    if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
135537    if( pUpsertClause
135538     && upsertIpkReturn
135539     && sqlite3UpsertNextIsIPK(pUpsertClause)
135540    ){
135541      sqlite3VdbeGoto(v, upsertIpkDelay+1);
135542      sqlite3VdbeJumpHere(v, upsertIpkReturn);
135543      upsertIpkReturn = 0;
135544    }
135545  }
135546
135547  /* If the IPK constraint is a REPLACE, run it last */
135548  if( ipkTop ){
135549    sqlite3VdbeGoto(v, ipkTop);
135550    VdbeComment((v, "Do IPK REPLACE"));
135551    assert( ipkBottom>0 );
135552    sqlite3VdbeJumpHere(v, ipkBottom);
135553  }
135554
135555  /* Recheck all uniqueness constraints after replace triggers have run */
135556  testcase( regTrigCnt!=0 && nReplaceTrig==0 );
135557  assert( regTrigCnt!=0 || nReplaceTrig==0 );
135558  if( nReplaceTrig ){
135559    sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
135560    if( !pPk ){
135561      if( isUpdate ){
135562        sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
135563        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
135564        VdbeCoverage(v);
135565      }
135566      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
135567      VdbeCoverage(v);
135568      sqlite3RowidConstraint(pParse, OE_Abort, pTab);
135569    }else{
135570      sqlite3VdbeGoto(v, addrRecheck);
135571    }
135572    sqlite3VdbeResolveLabel(v, lblRecheckOk);
135573  }
135574
135575  /* Generate the table record */
135576  if( HasRowid(pTab) ){
135577    int regRec = aRegIdx[ix];
135578    sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
135579    sqlite3SetMakeRecordP5(v, pTab);
135580    if( !bAffinityDone ){
135581      sqlite3TableAffinity(v, pTab, 0);
135582    }
135583  }
135584
135585  *pbMayReplace = seenReplace;
135586  VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
135587}
135588
135589#ifdef SQLITE_ENABLE_NULL_TRIM
135590/*
135591** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
135592** to be the number of columns in table pTab that must not be NULL-trimmed.
135593**
135594** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
135595*/
135596SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
135597  u16 i;
135598
135599  /* Records with omitted columns are only allowed for schema format
135600  ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
135601  if( pTab->pSchema->file_format<2 ) return;
135602
135603  for(i=pTab->nCol-1; i>0; i--){
135604    if( pTab->aCol[i].iDflt!=0 ) break;
135605    if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
135606  }
135607  sqlite3VdbeChangeP5(v, i+1);
135608}
135609#endif
135610
135611/*
135612** Table pTab is a WITHOUT ROWID table that is being written to. The cursor
135613** number is iCur, and register regData contains the new record for the
135614** PK index. This function adds code to invoke the pre-update hook,
135615** if one is registered.
135616*/
135617#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
135618static void codeWithoutRowidPreupdate(
135619  Parse *pParse,                  /* Parse context */
135620  Table *pTab,                    /* Table being updated */
135621  int iCur,                       /* Cursor number for table */
135622  int regData                     /* Data containing new record */
135623){
135624  Vdbe *v = pParse->pVdbe;
135625  int r = sqlite3GetTempReg(pParse);
135626  assert( !HasRowid(pTab) );
135627  assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
135628  sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
135629  sqlite3VdbeAddOp4(v, OP_Insert, iCur, regData, r, (char*)pTab, P4_TABLE);
135630  sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
135631  sqlite3ReleaseTempReg(pParse, r);
135632}
135633#else
135634# define codeWithoutRowidPreupdate(a,b,c,d)
135635#endif
135636
135637/*
135638** This routine generates code to finish the INSERT or UPDATE operation
135639** that was started by a prior call to sqlite3GenerateConstraintChecks.
135640** A consecutive range of registers starting at regNewData contains the
135641** rowid and the content to be inserted.
135642**
135643** The arguments to this routine should be the same as the first six
135644** arguments to sqlite3GenerateConstraintChecks.
135645*/
135646SQLITE_PRIVATE void sqlite3CompleteInsertion(
135647  Parse *pParse,      /* The parser context */
135648  Table *pTab,        /* the table into which we are inserting */
135649  int iDataCur,       /* Cursor of the canonical data source */
135650  int iIdxCur,        /* First index cursor */
135651  int regNewData,     /* Range of content */
135652  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
135653  int update_flags,   /* True for UPDATE, False for INSERT */
135654  int appendBias,     /* True if this is likely to be an append */
135655  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
135656){
135657  Vdbe *v;            /* Prepared statements under construction */
135658  Index *pIdx;        /* An index being inserted or updated */
135659  u8 pik_flags;       /* flag values passed to the btree insert */
135660  int i;              /* Loop counter */
135661
135662  assert( update_flags==0
135663       || update_flags==OPFLAG_ISUPDATE
135664       || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
135665  );
135666
135667  v = pParse->pVdbe;
135668  assert( v!=0 );
135669  assert( !IsView(pTab) );  /* This table is not a VIEW */
135670  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
135671    /* All REPLACE indexes are at the end of the list */
135672    assert( pIdx->onError!=OE_Replace
135673         || pIdx->pNext==0
135674         || pIdx->pNext->onError==OE_Replace );
135675    if( aRegIdx[i]==0 ) continue;
135676    if( pIdx->pPartIdxWhere ){
135677      sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
135678      VdbeCoverage(v);
135679    }
135680    pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
135681    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
135682      pik_flags |= OPFLAG_NCHANGE;
135683      pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
135684      if( update_flags==0 ){
135685        codeWithoutRowidPreupdate(pParse, pTab, iIdxCur+i, aRegIdx[i]);
135686      }
135687    }
135688    sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
135689                         aRegIdx[i]+1,
135690                         pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
135691    sqlite3VdbeChangeP5(v, pik_flags);
135692  }
135693  if( !HasRowid(pTab) ) return;
135694  if( pParse->nested ){
135695    pik_flags = 0;
135696  }else{
135697    pik_flags = OPFLAG_NCHANGE;
135698    pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
135699  }
135700  if( appendBias ){
135701    pik_flags |= OPFLAG_APPEND;
135702  }
135703  if( useSeekResult ){
135704    pik_flags |= OPFLAG_USESEEKRESULT;
135705  }
135706  sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
135707  if( !pParse->nested ){
135708    sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
135709  }
135710  sqlite3VdbeChangeP5(v, pik_flags);
135711}
135712
135713/*
135714** Allocate cursors for the pTab table and all its indices and generate
135715** code to open and initialized those cursors.
135716**
135717** The cursor for the object that contains the complete data (normally
135718** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
135719** ROWID table) is returned in *piDataCur.  The first index cursor is
135720** returned in *piIdxCur.  The number of indices is returned.
135721**
135722** Use iBase as the first cursor (either the *piDataCur for rowid tables
135723** or the first index for WITHOUT ROWID tables) if it is non-negative.
135724** If iBase is negative, then allocate the next available cursor.
135725**
135726** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
135727** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
135728** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
135729** pTab->pIndex list.
135730**
135731** If pTab is a virtual table, then this routine is a no-op and the
135732** *piDataCur and *piIdxCur values are left uninitialized.
135733*/
135734SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
135735  Parse *pParse,   /* Parsing context */
135736  Table *pTab,     /* Table to be opened */
135737  int op,          /* OP_OpenRead or OP_OpenWrite */
135738  u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
135739  int iBase,       /* Use this for the table cursor, if there is one */
135740  u8 *aToOpen,     /* If not NULL: boolean for each table and index */
135741  int *piDataCur,  /* Write the database source cursor number here */
135742  int *piIdxCur    /* Write the first index cursor number here */
135743){
135744  int i;
135745  int iDb;
135746  int iDataCur;
135747  Index *pIdx;
135748  Vdbe *v;
135749
135750  assert( op==OP_OpenRead || op==OP_OpenWrite );
135751  assert( op==OP_OpenWrite || p5==0 );
135752  assert( piDataCur!=0 );
135753  assert( piIdxCur!=0 );
135754  if( IsVirtual(pTab) ){
135755    /* This routine is a no-op for virtual tables. Leave the output
135756    ** variables *piDataCur and *piIdxCur set to illegal cursor numbers
135757    ** for improved error detection. */
135758    *piDataCur = *piIdxCur = -999;
135759    return 0;
135760  }
135761  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
135762  v = pParse->pVdbe;
135763  assert( v!=0 );
135764  if( iBase<0 ) iBase = pParse->nTab;
135765  iDataCur = iBase++;
135766  *piDataCur = iDataCur;
135767  if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
135768    sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
135769  }else if( pParse->db->noSharedCache==0 ){
135770    sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
135771  }
135772  *piIdxCur = iBase;
135773  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
135774    int iIdxCur = iBase++;
135775    assert( pIdx->pSchema==pTab->pSchema );
135776    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
135777      *piDataCur = iIdxCur;
135778      p5 = 0;
135779    }
135780    if( aToOpen==0 || aToOpen[i+1] ){
135781      sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
135782      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
135783      sqlite3VdbeChangeP5(v, p5);
135784      VdbeComment((v, "%s", pIdx->zName));
135785    }
135786  }
135787  if( iBase>pParse->nTab ) pParse->nTab = iBase;
135788  return i;
135789}
135790
135791
135792#ifdef SQLITE_TEST
135793/*
135794** The following global variable is incremented whenever the
135795** transfer optimization is used.  This is used for testing
135796** purposes only - to make sure the transfer optimization really
135797** is happening when it is supposed to.
135798*/
135799SQLITE_API int sqlite3_xferopt_count;
135800#endif /* SQLITE_TEST */
135801
135802
135803#ifndef SQLITE_OMIT_XFER_OPT
135804/*
135805** Check to see if index pSrc is compatible as a source of data
135806** for index pDest in an insert transfer optimization.  The rules
135807** for a compatible index:
135808**
135809**    *   The index is over the same set of columns
135810**    *   The same DESC and ASC markings occurs on all columns
135811**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
135812**    *   The same collating sequence on each column
135813**    *   The index has the exact same WHERE clause
135814*/
135815static int xferCompatibleIndex(Index *pDest, Index *pSrc){
135816  int i;
135817  assert( pDest && pSrc );
135818  assert( pDest->pTable!=pSrc->pTable );
135819  if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
135820    return 0;   /* Different number of columns */
135821  }
135822  if( pDest->onError!=pSrc->onError ){
135823    return 0;   /* Different conflict resolution strategies */
135824  }
135825  for(i=0; i<pSrc->nKeyCol; i++){
135826    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
135827      return 0;   /* Different columns indexed */
135828    }
135829    if( pSrc->aiColumn[i]==XN_EXPR ){
135830      assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
135831      if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
135832                             pDest->aColExpr->a[i].pExpr, -1)!=0 ){
135833        return 0;   /* Different expressions in the index */
135834      }
135835    }
135836    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
135837      return 0;   /* Different sort orders */
135838    }
135839    if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
135840      return 0;   /* Different collating sequences */
135841    }
135842  }
135843  if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
135844    return 0;     /* Different WHERE clauses */
135845  }
135846
135847  /* If no test above fails then the indices must be compatible */
135848  return 1;
135849}
135850
135851/*
135852** Attempt the transfer optimization on INSERTs of the form
135853**
135854**     INSERT INTO tab1 SELECT * FROM tab2;
135855**
135856** The xfer optimization transfers raw records from tab2 over to tab1.
135857** Columns are not decoded and reassembled, which greatly improves
135858** performance.  Raw index records are transferred in the same way.
135859**
135860** The xfer optimization is only attempted if tab1 and tab2 are compatible.
135861** There are lots of rules for determining compatibility - see comments
135862** embedded in the code for details.
135863**
135864** This routine returns TRUE if the optimization is guaranteed to be used.
135865** Sometimes the xfer optimization will only work if the destination table
135866** is empty - a factor that can only be determined at run-time.  In that
135867** case, this routine generates code for the xfer optimization but also
135868** does a test to see if the destination table is empty and jumps over the
135869** xfer optimization code if the test fails.  In that case, this routine
135870** returns FALSE so that the caller will know to go ahead and generate
135871** an unoptimized transfer.  This routine also returns FALSE if there
135872** is no chance that the xfer optimization can be applied.
135873**
135874** This optimization is particularly useful at making VACUUM run faster.
135875*/
135876static int xferOptimization(
135877  Parse *pParse,        /* Parser context */
135878  Table *pDest,         /* The table we are inserting into */
135879  Select *pSelect,      /* A SELECT statement to use as the data source */
135880  int onError,          /* How to handle constraint errors */
135881  int iDbDest           /* The database of pDest */
135882){
135883  sqlite3 *db = pParse->db;
135884  ExprList *pEList;                /* The result set of the SELECT */
135885  Table *pSrc;                     /* The table in the FROM clause of SELECT */
135886  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
135887  SrcItem *pItem;                  /* An element of pSelect->pSrc */
135888  int i;                           /* Loop counter */
135889  int iDbSrc;                      /* The database of pSrc */
135890  int iSrc, iDest;                 /* Cursors from source and destination */
135891  int addr1, addr2;                /* Loop addresses */
135892  int emptyDestTest = 0;           /* Address of test for empty pDest */
135893  int emptySrcTest = 0;            /* Address of test for empty pSrc */
135894  Vdbe *v;                         /* The VDBE we are building */
135895  int regAutoinc;                  /* Memory register used by AUTOINC */
135896  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
135897  int regData, regRowid;           /* Registers holding data and rowid */
135898
135899  assert( pSelect!=0 );
135900  if( pParse->pWith || pSelect->pWith ){
135901    /* Do not attempt to process this query if there are an WITH clauses
135902    ** attached to it. Proceeding may generate a false "no such table: xxx"
135903    ** error if pSelect reads from a CTE named "xxx".  */
135904    return 0;
135905  }
135906#ifndef SQLITE_OMIT_VIRTUALTABLE
135907  if( IsVirtual(pDest) ){
135908    return 0;   /* tab1 must not be a virtual table */
135909  }
135910#endif
135911  if( onError==OE_Default ){
135912    if( pDest->iPKey>=0 ) onError = pDest->keyConf;
135913    if( onError==OE_Default ) onError = OE_Abort;
135914  }
135915  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
135916  if( pSelect->pSrc->nSrc!=1 ){
135917    return 0;   /* FROM clause must have exactly one term */
135918  }
135919  if( pSelect->pSrc->a[0].pSelect ){
135920    return 0;   /* FROM clause cannot contain a subquery */
135921  }
135922  if( pSelect->pWhere ){
135923    return 0;   /* SELECT may not have a WHERE clause */
135924  }
135925  if( pSelect->pOrderBy ){
135926    return 0;   /* SELECT may not have an ORDER BY clause */
135927  }
135928  /* Do not need to test for a HAVING clause.  If HAVING is present but
135929  ** there is no ORDER BY, we will get an error. */
135930  if( pSelect->pGroupBy ){
135931    return 0;   /* SELECT may not have a GROUP BY clause */
135932  }
135933  if( pSelect->pLimit ){
135934    return 0;   /* SELECT may not have a LIMIT clause */
135935  }
135936  if( pSelect->pPrior ){
135937    return 0;   /* SELECT may not be a compound query */
135938  }
135939  if( pSelect->selFlags & SF_Distinct ){
135940    return 0;   /* SELECT may not be DISTINCT */
135941  }
135942  pEList = pSelect->pEList;
135943  assert( pEList!=0 );
135944  if( pEList->nExpr!=1 ){
135945    return 0;   /* The result set must have exactly one column */
135946  }
135947  assert( pEList->a[0].pExpr );
135948  if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
135949    return 0;   /* The result set must be the special operator "*" */
135950  }
135951
135952  /* At this point we have established that the statement is of the
135953  ** correct syntactic form to participate in this optimization.  Now
135954  ** we have to check the semantics.
135955  */
135956  pItem = pSelect->pSrc->a;
135957  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
135958  if( pSrc==0 ){
135959    return 0;   /* FROM clause does not contain a real table */
135960  }
135961  if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
135962    testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */
135963    return 0;   /* tab1 and tab2 may not be the same table */
135964  }
135965  if( HasRowid(pDest)!=HasRowid(pSrc) ){
135966    return 0;   /* source and destination must both be WITHOUT ROWID or not */
135967  }
135968  if( !IsOrdinaryTable(pSrc) ){
135969    return 0;   /* tab2 may not be a view or virtual table */
135970  }
135971  if( pDest->nCol!=pSrc->nCol ){
135972    return 0;   /* Number of columns must be the same in tab1 and tab2 */
135973  }
135974  if( pDest->iPKey!=pSrc->iPKey ){
135975    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
135976  }
135977  if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){
135978    return 0;   /* Cannot feed from a non-strict into a strict table */
135979  }
135980  for(i=0; i<pDest->nCol; i++){
135981    Column *pDestCol = &pDest->aCol[i];
135982    Column *pSrcCol = &pSrc->aCol[i];
135983#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
135984    if( (db->mDbFlags & DBFLAG_Vacuum)==0
135985     && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
135986    ){
135987      return 0;    /* Neither table may have __hidden__ columns */
135988    }
135989#endif
135990#ifndef SQLITE_OMIT_GENERATED_COLUMNS
135991    /* Even if tables t1 and t2 have identical schemas, if they contain
135992    ** generated columns, then this statement is semantically incorrect:
135993    **
135994    **     INSERT INTO t2 SELECT * FROM t1;
135995    **
135996    ** The reason is that generated column values are returned by the
135997    ** the SELECT statement on the right but the INSERT statement on the
135998    ** left wants them to be omitted.
135999    **
136000    ** Nevertheless, this is a useful notational shorthand to tell SQLite
136001    ** to do a bulk transfer all of the content from t1 over to t2.
136002    **
136003    ** We could, in theory, disable this (except for internal use by the
136004    ** VACUUM command where it is actually needed).  But why do that?  It
136005    ** seems harmless enough, and provides a useful service.
136006    */
136007    if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
136008        (pSrcCol->colFlags & COLFLAG_GENERATED) ){
136009      return 0;    /* Both columns have the same generated-column type */
136010    }
136011    /* But the transfer is only allowed if both the source and destination
136012    ** tables have the exact same expressions for generated columns.
136013    ** This requirement could be relaxed for VIRTUAL columns, I suppose.
136014    */
136015    if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
136016      if( sqlite3ExprCompare(0,
136017             sqlite3ColumnExpr(pSrc, pSrcCol),
136018             sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
136019        testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
136020        testcase( pDestCol->colFlags & COLFLAG_STORED );
136021        return 0;  /* Different generator expressions */
136022      }
136023    }
136024#endif
136025    if( pDestCol->affinity!=pSrcCol->affinity ){
136026      return 0;    /* Affinity must be the same on all columns */
136027    }
136028    if( sqlite3_stricmp(sqlite3ColumnColl(pDestCol),
136029                        sqlite3ColumnColl(pSrcCol))!=0 ){
136030      return 0;    /* Collating sequence must be the same on all columns */
136031    }
136032    if( pDestCol->notNull && !pSrcCol->notNull ){
136033      return 0;    /* tab2 must be NOT NULL if tab1 is */
136034    }
136035    /* Default values for second and subsequent columns need to match. */
136036    if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
136037      Expr *pDestExpr = sqlite3ColumnExpr(pDest, pDestCol);
136038      Expr *pSrcExpr = sqlite3ColumnExpr(pSrc, pSrcCol);
136039      assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
136040      assert( pDestExpr==0 || !ExprHasProperty(pDestExpr, EP_IntValue) );
136041      assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
136042      assert( pSrcExpr==0 || !ExprHasProperty(pSrcExpr, EP_IntValue) );
136043      if( (pDestExpr==0)!=(pSrcExpr==0)
136044       || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
136045                                       pSrcExpr->u.zToken)!=0)
136046      ){
136047        return 0;    /* Default values must be the same for all columns */
136048      }
136049    }
136050  }
136051  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
136052    if( IsUniqueIndex(pDestIdx) ){
136053      destHasUniqueIdx = 1;
136054    }
136055    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
136056      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
136057    }
136058    if( pSrcIdx==0 ){
136059      return 0;    /* pDestIdx has no corresponding index in pSrc */
136060    }
136061    if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
136062         && sqlite3FaultSim(411)==SQLITE_OK ){
136063      /* The sqlite3FaultSim() call allows this corruption test to be
136064      ** bypassed during testing, in order to exercise other corruption tests
136065      ** further downstream. */
136066      return 0;   /* Corrupt schema - two indexes on the same btree */
136067    }
136068  }
136069#ifndef SQLITE_OMIT_CHECK
136070  if( pDest->pCheck
136071   && (db->mDbFlags & DBFLAG_Vacuum)==0
136072   && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1)
136073  ){
136074    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
136075  }
136076#endif
136077#ifndef SQLITE_OMIT_FOREIGN_KEY
136078  /* Disallow the transfer optimization if the destination table contains
136079  ** any foreign key constraints.  This is more restrictive than necessary.
136080  ** But the main beneficiary of the transfer optimization is the VACUUM
136081  ** command, and the VACUUM command disables foreign key constraints.  So
136082  ** the extra complication to make this rule less restrictive is probably
136083  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
136084  */
136085  assert( IsOrdinaryTable(pDest) );
136086  if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
136087    return 0;
136088  }
136089#endif
136090  if( (db->flags & SQLITE_CountRows)!=0 ){
136091    return 0;  /* xfer opt does not play well with PRAGMA count_changes */
136092  }
136093
136094  /* If we get this far, it means that the xfer optimization is at
136095  ** least a possibility, though it might only work if the destination
136096  ** table (tab1) is initially empty.
136097  */
136098#ifdef SQLITE_TEST
136099  sqlite3_xferopt_count++;
136100#endif
136101  iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
136102  v = sqlite3GetVdbe(pParse);
136103  sqlite3CodeVerifySchema(pParse, iDbSrc);
136104  iSrc = pParse->nTab++;
136105  iDest = pParse->nTab++;
136106  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
136107  regData = sqlite3GetTempReg(pParse);
136108  sqlite3VdbeAddOp2(v, OP_Null, 0, regData);
136109  regRowid = sqlite3GetTempReg(pParse);
136110  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
136111  assert( HasRowid(pDest) || destHasUniqueIdx );
136112  if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
136113      (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
136114   || destHasUniqueIdx                              /* (2) */
136115   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
136116  )){
136117    /* In some circumstances, we are able to run the xfer optimization
136118    ** only if the destination table is initially empty. Unless the
136119    ** DBFLAG_Vacuum flag is set, this block generates code to make
136120    ** that determination. If DBFLAG_Vacuum is set, then the destination
136121    ** table is always empty.
136122    **
136123    ** Conditions under which the destination must be empty:
136124    **
136125    ** (1) There is no INTEGER PRIMARY KEY but there are indices.
136126    **     (If the destination is not initially empty, the rowid fields
136127    **     of index entries might need to change.)
136128    **
136129    ** (2) The destination has a unique index.  (The xfer optimization
136130    **     is unable to test uniqueness.)
136131    **
136132    ** (3) onError is something other than OE_Abort and OE_Rollback.
136133    */
136134    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
136135    emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
136136    sqlite3VdbeJumpHere(v, addr1);
136137  }
136138  if( HasRowid(pSrc) ){
136139    u8 insFlags;
136140    sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
136141    emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
136142    if( pDest->iPKey>=0 ){
136143      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
136144      if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
136145        sqlite3VdbeVerifyAbortable(v, onError);
136146        addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
136147        VdbeCoverage(v);
136148        sqlite3RowidConstraint(pParse, onError, pDest);
136149        sqlite3VdbeJumpHere(v, addr2);
136150      }
136151      autoIncStep(pParse, regAutoinc, regRowid);
136152    }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
136153      addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
136154    }else{
136155      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
136156      assert( (pDest->tabFlags & TF_Autoincrement)==0 );
136157    }
136158
136159    if( db->mDbFlags & DBFLAG_Vacuum ){
136160      sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
136161      insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
136162    }else{
136163      insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND|OPFLAG_PREFORMAT;
136164    }
136165#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
136166    if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
136167      sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
136168      insFlags &= ~OPFLAG_PREFORMAT;
136169    }else
136170#endif
136171    {
136172      sqlite3VdbeAddOp3(v, OP_RowCell, iDest, iSrc, regRowid);
136173    }
136174    sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
136175    if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
136176      sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
136177    }
136178    sqlite3VdbeChangeP5(v, insFlags);
136179
136180    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
136181    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
136182    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
136183  }else{
136184    sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
136185    sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
136186  }
136187  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
136188    u8 idxInsFlags = 0;
136189    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
136190      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
136191    }
136192    assert( pSrcIdx );
136193    sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
136194    sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
136195    VdbeComment((v, "%s", pSrcIdx->zName));
136196    sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
136197    sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
136198    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
136199    VdbeComment((v, "%s", pDestIdx->zName));
136200    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
136201    if( db->mDbFlags & DBFLAG_Vacuum ){
136202      /* This INSERT command is part of a VACUUM operation, which guarantees
136203      ** that the destination table is empty. If all indexed columns use
136204      ** collation sequence BINARY, then it can also be assumed that the
136205      ** index will be populated by inserting keys in strictly sorted
136206      ** order. In this case, instead of seeking within the b-tree as part
136207      ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
136208      ** OP_IdxInsert to seek to the point within the b-tree where each key
136209      ** should be inserted. This is faster.
136210      **
136211      ** If any of the indexed columns use a collation sequence other than
136212      ** BINARY, this optimization is disabled. This is because the user
136213      ** might change the definition of a collation sequence and then run
136214      ** a VACUUM command. In that case keys may not be written in strictly
136215      ** sorted order.  */
136216      for(i=0; i<pSrcIdx->nColumn; i++){
136217        const char *zColl = pSrcIdx->azColl[i];
136218        if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
136219      }
136220      if( i==pSrcIdx->nColumn ){
136221        idxInsFlags = OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
136222        sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
136223        sqlite3VdbeAddOp2(v, OP_RowCell, iDest, iSrc);
136224      }
136225    }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
136226      idxInsFlags |= OPFLAG_NCHANGE;
136227    }
136228    if( idxInsFlags!=(OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT) ){
136229      sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
136230      if( (db->mDbFlags & DBFLAG_Vacuum)==0
136231       && !HasRowid(pDest)
136232       && IsPrimaryKeyIndex(pDestIdx)
136233      ){
136234        codeWithoutRowidPreupdate(pParse, pDest, iDest, regData);
136235      }
136236    }
136237    sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
136238    sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
136239    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
136240    sqlite3VdbeJumpHere(v, addr1);
136241    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
136242    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
136243  }
136244  if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
136245  sqlite3ReleaseTempReg(pParse, regRowid);
136246  sqlite3ReleaseTempReg(pParse, regData);
136247  if( emptyDestTest ){
136248    sqlite3AutoincrementEnd(pParse);
136249    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
136250    sqlite3VdbeJumpHere(v, emptyDestTest);
136251    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
136252    return 0;
136253  }else{
136254    return 1;
136255  }
136256}
136257#endif /* SQLITE_OMIT_XFER_OPT */
136258
136259/************** End of insert.c **********************************************/
136260/************** Begin file legacy.c ******************************************/
136261/*
136262** 2001 September 15
136263**
136264** The author disclaims copyright to this source code.  In place of
136265** a legal notice, here is a blessing:
136266**
136267**    May you do good and not evil.
136268**    May you find forgiveness for yourself and forgive others.
136269**    May you share freely, never taking more than you give.
136270**
136271*************************************************************************
136272** Main file for the SQLite library.  The routines in this file
136273** implement the programmer interface to the library.  Routines in
136274** other files are for internal use by SQLite and should not be
136275** accessed by users of the library.
136276*/
136277
136278/* #include "sqliteInt.h" */
136279
136280/*
136281** Execute SQL code.  Return one of the SQLITE_ success/failure
136282** codes.  Also write an error message into memory obtained from
136283** malloc() and make *pzErrMsg point to that message.
136284**
136285** If the SQL is a query, then for each row in the query result
136286** the xCallback() function is called.  pArg becomes the first
136287** argument to xCallback().  If xCallback=NULL then no callback
136288** is invoked, even for queries.
136289*/
136290SQLITE_API int sqlite3_exec(
136291  sqlite3 *db,                /* The database on which the SQL executes */
136292  const char *zSql,           /* The SQL to be executed */
136293  sqlite3_callback xCallback, /* Invoke this callback routine */
136294  void *pArg,                 /* First argument to xCallback() */
136295  char **pzErrMsg             /* Write error messages here */
136296){
136297  int rc = SQLITE_OK;         /* Return code */
136298  const char *zLeftover;      /* Tail of unprocessed SQL */
136299  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
136300  char **azCols = 0;          /* Names of result columns */
136301  int callbackIsInit;         /* True if callback data is initialized */
136302
136303  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
136304  if( zSql==0 ) zSql = "";
136305
136306  sqlite3_mutex_enter(db->mutex);
136307  sqlite3Error(db, SQLITE_OK);
136308  while( rc==SQLITE_OK && zSql[0] ){
136309    int nCol = 0;
136310    char **azVals = 0;
136311
136312    pStmt = 0;
136313    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
136314    assert( rc==SQLITE_OK || pStmt==0 );
136315    if( rc!=SQLITE_OK ){
136316      continue;
136317    }
136318    if( !pStmt ){
136319      /* this happens for a comment or white-space */
136320      zSql = zLeftover;
136321      continue;
136322    }
136323    callbackIsInit = 0;
136324
136325    while( 1 ){
136326      int i;
136327      rc = sqlite3_step(pStmt);
136328
136329      /* Invoke the callback function if required */
136330      if( xCallback && (SQLITE_ROW==rc ||
136331          (SQLITE_DONE==rc && !callbackIsInit
136332                           && db->flags&SQLITE_NullCallback)) ){
136333        if( !callbackIsInit ){
136334          nCol = sqlite3_column_count(pStmt);
136335          azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
136336          if( azCols==0 ){
136337            goto exec_out;
136338          }
136339          for(i=0; i<nCol; i++){
136340            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
136341            /* sqlite3VdbeSetColName() installs column names as UTF8
136342            ** strings so there is no way for sqlite3_column_name() to fail. */
136343            assert( azCols[i]!=0 );
136344          }
136345          callbackIsInit = 1;
136346        }
136347        if( rc==SQLITE_ROW ){
136348          azVals = &azCols[nCol];
136349          for(i=0; i<nCol; i++){
136350            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
136351            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
136352              sqlite3OomFault(db);
136353              goto exec_out;
136354            }
136355          }
136356          azVals[i] = 0;
136357        }
136358        if( xCallback(pArg, nCol, azVals, azCols) ){
136359          /* EVIDENCE-OF: R-38229-40159 If the callback function to
136360          ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
136361          ** return SQLITE_ABORT. */
136362          rc = SQLITE_ABORT;
136363          sqlite3VdbeFinalize((Vdbe *)pStmt);
136364          pStmt = 0;
136365          sqlite3Error(db, SQLITE_ABORT);
136366          goto exec_out;
136367        }
136368      }
136369
136370      if( rc!=SQLITE_ROW ){
136371        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
136372        pStmt = 0;
136373        zSql = zLeftover;
136374        while( sqlite3Isspace(zSql[0]) ) zSql++;
136375        break;
136376      }
136377    }
136378
136379    sqlite3DbFree(db, azCols);
136380    azCols = 0;
136381  }
136382
136383exec_out:
136384  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
136385  sqlite3DbFree(db, azCols);
136386
136387  rc = sqlite3ApiExit(db, rc);
136388  if( rc!=SQLITE_OK && pzErrMsg ){
136389    *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
136390    if( *pzErrMsg==0 ){
136391      rc = SQLITE_NOMEM_BKPT;
136392      sqlite3Error(db, SQLITE_NOMEM);
136393    }
136394  }else if( pzErrMsg ){
136395    *pzErrMsg = 0;
136396  }
136397
136398  assert( (rc&db->errMask)==rc );
136399  sqlite3_mutex_leave(db->mutex);
136400  return rc;
136401}
136402
136403/************** End of legacy.c **********************************************/
136404/************** Begin file loadext.c *****************************************/
136405/*
136406** 2006 June 7
136407**
136408** The author disclaims copyright to this source code.  In place of
136409** a legal notice, here is a blessing:
136410**
136411**    May you do good and not evil.
136412**    May you find forgiveness for yourself and forgive others.
136413**    May you share freely, never taking more than you give.
136414**
136415*************************************************************************
136416** This file contains code used to dynamically load extensions into
136417** the SQLite library.
136418*/
136419
136420#ifndef SQLITE_CORE
136421  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
136422#endif
136423/************** Include sqlite3ext.h in the middle of loadext.c **************/
136424/************** Begin file sqlite3ext.h **************************************/
136425/*
136426** 2006 June 7
136427**
136428** The author disclaims copyright to this source code.  In place of
136429** a legal notice, here is a blessing:
136430**
136431**    May you do good and not evil.
136432**    May you find forgiveness for yourself and forgive others.
136433**    May you share freely, never taking more than you give.
136434**
136435*************************************************************************
136436** This header file defines the SQLite interface for use by
136437** shared libraries that want to be imported as extensions into
136438** an SQLite instance.  Shared libraries that intend to be loaded
136439** as extensions by SQLite should #include this file instead of
136440** sqlite3.h.
136441*/
136442#ifndef SQLITE3EXT_H
136443#define SQLITE3EXT_H
136444/* #include "sqlite3.h" */
136445
136446/*
136447** The following structure holds pointers to all of the SQLite API
136448** routines.
136449**
136450** WARNING:  In order to maintain backwards compatibility, add new
136451** interfaces to the end of this structure only.  If you insert new
136452** interfaces in the middle of this structure, then older different
136453** versions of SQLite will not be able to load each other's shared
136454** libraries!
136455*/
136456struct sqlite3_api_routines {
136457  void * (*aggregate_context)(sqlite3_context*,int nBytes);
136458  int  (*aggregate_count)(sqlite3_context*);
136459  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
136460  int  (*bind_double)(sqlite3_stmt*,int,double);
136461  int  (*bind_int)(sqlite3_stmt*,int,int);
136462  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
136463  int  (*bind_null)(sqlite3_stmt*,int);
136464  int  (*bind_parameter_count)(sqlite3_stmt*);
136465  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
136466  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
136467  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
136468  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
136469  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
136470  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
136471  int  (*busy_timeout)(sqlite3*,int ms);
136472  int  (*changes)(sqlite3*);
136473  int  (*close)(sqlite3*);
136474  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
136475                           int eTextRep,const char*));
136476  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
136477                             int eTextRep,const void*));
136478  const void * (*column_blob)(sqlite3_stmt*,int iCol);
136479  int  (*column_bytes)(sqlite3_stmt*,int iCol);
136480  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
136481  int  (*column_count)(sqlite3_stmt*pStmt);
136482  const char * (*column_database_name)(sqlite3_stmt*,int);
136483  const void * (*column_database_name16)(sqlite3_stmt*,int);
136484  const char * (*column_decltype)(sqlite3_stmt*,int i);
136485  const void * (*column_decltype16)(sqlite3_stmt*,int);
136486  double  (*column_double)(sqlite3_stmt*,int iCol);
136487  int  (*column_int)(sqlite3_stmt*,int iCol);
136488  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
136489  const char * (*column_name)(sqlite3_stmt*,int);
136490  const void * (*column_name16)(sqlite3_stmt*,int);
136491  const char * (*column_origin_name)(sqlite3_stmt*,int);
136492  const void * (*column_origin_name16)(sqlite3_stmt*,int);
136493  const char * (*column_table_name)(sqlite3_stmt*,int);
136494  const void * (*column_table_name16)(sqlite3_stmt*,int);
136495  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
136496  const void * (*column_text16)(sqlite3_stmt*,int iCol);
136497  int  (*column_type)(sqlite3_stmt*,int iCol);
136498  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
136499  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
136500  int  (*complete)(const char*sql);
136501  int  (*complete16)(const void*sql);
136502  int  (*create_collation)(sqlite3*,const char*,int,void*,
136503                           int(*)(void*,int,const void*,int,const void*));
136504  int  (*create_collation16)(sqlite3*,const void*,int,void*,
136505                             int(*)(void*,int,const void*,int,const void*));
136506  int  (*create_function)(sqlite3*,const char*,int,int,void*,
136507                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
136508                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
136509                          void (*xFinal)(sqlite3_context*));
136510  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
136511                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
136512                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
136513                            void (*xFinal)(sqlite3_context*));
136514  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
136515  int  (*data_count)(sqlite3_stmt*pStmt);
136516  sqlite3 * (*db_handle)(sqlite3_stmt*);
136517  int (*declare_vtab)(sqlite3*,const char*);
136518  int  (*enable_shared_cache)(int);
136519  int  (*errcode)(sqlite3*db);
136520  const char * (*errmsg)(sqlite3*);
136521  const void * (*errmsg16)(sqlite3*);
136522  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
136523  int  (*expired)(sqlite3_stmt*);
136524  int  (*finalize)(sqlite3_stmt*pStmt);
136525  void  (*free)(void*);
136526  void  (*free_table)(char**result);
136527  int  (*get_autocommit)(sqlite3*);
136528  void * (*get_auxdata)(sqlite3_context*,int);
136529  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
136530  int  (*global_recover)(void);
136531  void  (*interruptx)(sqlite3*);
136532  sqlite_int64  (*last_insert_rowid)(sqlite3*);
136533  const char * (*libversion)(void);
136534  int  (*libversion_number)(void);
136535  void *(*malloc)(int);
136536  char * (*mprintf)(const char*,...);
136537  int  (*open)(const char*,sqlite3**);
136538  int  (*open16)(const void*,sqlite3**);
136539  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
136540  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
136541  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
136542  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
136543  void *(*realloc)(void*,int);
136544  int  (*reset)(sqlite3_stmt*pStmt);
136545  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
136546  void  (*result_double)(sqlite3_context*,double);
136547  void  (*result_error)(sqlite3_context*,const char*,int);
136548  void  (*result_error16)(sqlite3_context*,const void*,int);
136549  void  (*result_int)(sqlite3_context*,int);
136550  void  (*result_int64)(sqlite3_context*,sqlite_int64);
136551  void  (*result_null)(sqlite3_context*);
136552  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
136553  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
136554  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
136555  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
136556  void  (*result_value)(sqlite3_context*,sqlite3_value*);
136557  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
136558  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
136559                         const char*,const char*),void*);
136560  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
136561  char * (*xsnprintf)(int,char*,const char*,...);
136562  int  (*step)(sqlite3_stmt*);
136563  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
136564                                char const**,char const**,int*,int*,int*);
136565  void  (*thread_cleanup)(void);
136566  int  (*total_changes)(sqlite3*);
136567  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
136568  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
136569  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
136570                                         sqlite_int64),void*);
136571  void * (*user_data)(sqlite3_context*);
136572  const void * (*value_blob)(sqlite3_value*);
136573  int  (*value_bytes)(sqlite3_value*);
136574  int  (*value_bytes16)(sqlite3_value*);
136575  double  (*value_double)(sqlite3_value*);
136576  int  (*value_int)(sqlite3_value*);
136577  sqlite_int64  (*value_int64)(sqlite3_value*);
136578  int  (*value_numeric_type)(sqlite3_value*);
136579  const unsigned char * (*value_text)(sqlite3_value*);
136580  const void * (*value_text16)(sqlite3_value*);
136581  const void * (*value_text16be)(sqlite3_value*);
136582  const void * (*value_text16le)(sqlite3_value*);
136583  int  (*value_type)(sqlite3_value*);
136584  char *(*vmprintf)(const char*,va_list);
136585  /* Added ??? */
136586  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
136587  /* Added by 3.3.13 */
136588  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
136589  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
136590  int (*clear_bindings)(sqlite3_stmt*);
136591  /* Added by 3.4.1 */
136592  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
136593                          void (*xDestroy)(void *));
136594  /* Added by 3.5.0 */
136595  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
136596  int (*blob_bytes)(sqlite3_blob*);
136597  int (*blob_close)(sqlite3_blob*);
136598  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
136599                   int,sqlite3_blob**);
136600  int (*blob_read)(sqlite3_blob*,void*,int,int);
136601  int (*blob_write)(sqlite3_blob*,const void*,int,int);
136602  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
136603                             int(*)(void*,int,const void*,int,const void*),
136604                             void(*)(void*));
136605  int (*file_control)(sqlite3*,const char*,int,void*);
136606  sqlite3_int64 (*memory_highwater)(int);
136607  sqlite3_int64 (*memory_used)(void);
136608  sqlite3_mutex *(*mutex_alloc)(int);
136609  void (*mutex_enter)(sqlite3_mutex*);
136610  void (*mutex_free)(sqlite3_mutex*);
136611  void (*mutex_leave)(sqlite3_mutex*);
136612  int (*mutex_try)(sqlite3_mutex*);
136613  int (*open_v2)(const char*,sqlite3**,int,const char*);
136614  int (*release_memory)(int);
136615  void (*result_error_nomem)(sqlite3_context*);
136616  void (*result_error_toobig)(sqlite3_context*);
136617  int (*sleep)(int);
136618  void (*soft_heap_limit)(int);
136619  sqlite3_vfs *(*vfs_find)(const char*);
136620  int (*vfs_register)(sqlite3_vfs*,int);
136621  int (*vfs_unregister)(sqlite3_vfs*);
136622  int (*xthreadsafe)(void);
136623  void (*result_zeroblob)(sqlite3_context*,int);
136624  void (*result_error_code)(sqlite3_context*,int);
136625  int (*test_control)(int, ...);
136626  void (*randomness)(int,void*);
136627  sqlite3 *(*context_db_handle)(sqlite3_context*);
136628  int (*extended_result_codes)(sqlite3*,int);
136629  int (*limit)(sqlite3*,int,int);
136630  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
136631  const char *(*sql)(sqlite3_stmt*);
136632  int (*status)(int,int*,int*,int);
136633  int (*backup_finish)(sqlite3_backup*);
136634  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
136635  int (*backup_pagecount)(sqlite3_backup*);
136636  int (*backup_remaining)(sqlite3_backup*);
136637  int (*backup_step)(sqlite3_backup*,int);
136638  const char *(*compileoption_get)(int);
136639  int (*compileoption_used)(const char*);
136640  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
136641                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
136642                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
136643                            void (*xFinal)(sqlite3_context*),
136644                            void(*xDestroy)(void*));
136645  int (*db_config)(sqlite3*,int,...);
136646  sqlite3_mutex *(*db_mutex)(sqlite3*);
136647  int (*db_status)(sqlite3*,int,int*,int*,int);
136648  int (*extended_errcode)(sqlite3*);
136649  void (*log)(int,const char*,...);
136650  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
136651  const char *(*sourceid)(void);
136652  int (*stmt_status)(sqlite3_stmt*,int,int);
136653  int (*strnicmp)(const char*,const char*,int);
136654  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
136655  int (*wal_autocheckpoint)(sqlite3*,int);
136656  int (*wal_checkpoint)(sqlite3*,const char*);
136657  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
136658  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
136659  int (*vtab_config)(sqlite3*,int op,...);
136660  int (*vtab_on_conflict)(sqlite3*);
136661  /* Version 3.7.16 and later */
136662  int (*close_v2)(sqlite3*);
136663  const char *(*db_filename)(sqlite3*,const char*);
136664  int (*db_readonly)(sqlite3*,const char*);
136665  int (*db_release_memory)(sqlite3*);
136666  const char *(*errstr)(int);
136667  int (*stmt_busy)(sqlite3_stmt*);
136668  int (*stmt_readonly)(sqlite3_stmt*);
136669  int (*stricmp)(const char*,const char*);
136670  int (*uri_boolean)(const char*,const char*,int);
136671  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
136672  const char *(*uri_parameter)(const char*,const char*);
136673  char *(*xvsnprintf)(int,char*,const char*,va_list);
136674  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
136675  /* Version 3.8.7 and later */
136676  int (*auto_extension)(void(*)(void));
136677  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
136678                     void(*)(void*));
136679  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
136680                      void(*)(void*),unsigned char);
136681  int (*cancel_auto_extension)(void(*)(void));
136682  int (*load_extension)(sqlite3*,const char*,const char*,char**);
136683  void *(*malloc64)(sqlite3_uint64);
136684  sqlite3_uint64 (*msize)(void*);
136685  void *(*realloc64)(void*,sqlite3_uint64);
136686  void (*reset_auto_extension)(void);
136687  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
136688                        void(*)(void*));
136689  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
136690                         void(*)(void*), unsigned char);
136691  int (*strglob)(const char*,const char*);
136692  /* Version 3.8.11 and later */
136693  sqlite3_value *(*value_dup)(const sqlite3_value*);
136694  void (*value_free)(sqlite3_value*);
136695  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
136696  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
136697  /* Version 3.9.0 and later */
136698  unsigned int (*value_subtype)(sqlite3_value*);
136699  void (*result_subtype)(sqlite3_context*,unsigned int);
136700  /* Version 3.10.0 and later */
136701  int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
136702  int (*strlike)(const char*,const char*,unsigned int);
136703  int (*db_cacheflush)(sqlite3*);
136704  /* Version 3.12.0 and later */
136705  int (*system_errno)(sqlite3*);
136706  /* Version 3.14.0 and later */
136707  int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
136708  char *(*expanded_sql)(sqlite3_stmt*);
136709  /* Version 3.18.0 and later */
136710  void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
136711  /* Version 3.20.0 and later */
136712  int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
136713                    sqlite3_stmt**,const char**);
136714  int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
136715                      sqlite3_stmt**,const void**);
136716  int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
136717  void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
136718  void *(*value_pointer)(sqlite3_value*,const char*);
136719  int (*vtab_nochange)(sqlite3_context*);
136720  int (*value_nochange)(sqlite3_value*);
136721  const char *(*vtab_collation)(sqlite3_index_info*,int);
136722  /* Version 3.24.0 and later */
136723  int (*keyword_count)(void);
136724  int (*keyword_name)(int,const char**,int*);
136725  int (*keyword_check)(const char*,int);
136726  sqlite3_str *(*str_new)(sqlite3*);
136727  char *(*str_finish)(sqlite3_str*);
136728  void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
136729  void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
136730  void (*str_append)(sqlite3_str*, const char *zIn, int N);
136731  void (*str_appendall)(sqlite3_str*, const char *zIn);
136732  void (*str_appendchar)(sqlite3_str*, int N, char C);
136733  void (*str_reset)(sqlite3_str*);
136734  int (*str_errcode)(sqlite3_str*);
136735  int (*str_length)(sqlite3_str*);
136736  char *(*str_value)(sqlite3_str*);
136737  /* Version 3.25.0 and later */
136738  int (*create_window_function)(sqlite3*,const char*,int,int,void*,
136739                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
136740                            void (*xFinal)(sqlite3_context*),
136741                            void (*xValue)(sqlite3_context*),
136742                            void (*xInv)(sqlite3_context*,int,sqlite3_value**),
136743                            void(*xDestroy)(void*));
136744  /* Version 3.26.0 and later */
136745  const char *(*normalized_sql)(sqlite3_stmt*);
136746  /* Version 3.28.0 and later */
136747  int (*stmt_isexplain)(sqlite3_stmt*);
136748  int (*value_frombind)(sqlite3_value*);
136749  /* Version 3.30.0 and later */
136750  int (*drop_modules)(sqlite3*,const char**);
136751  /* Version 3.31.0 and later */
136752  sqlite3_int64 (*hard_heap_limit64)(sqlite3_int64);
136753  const char *(*uri_key)(const char*,int);
136754  const char *(*filename_database)(const char*);
136755  const char *(*filename_journal)(const char*);
136756  const char *(*filename_wal)(const char*);
136757  /* Version 3.32.0 and later */
136758  const char *(*create_filename)(const char*,const char*,const char*,
136759                           int,const char**);
136760  void (*free_filename)(const char*);
136761  sqlite3_file *(*database_file_object)(const char*);
136762  /* Version 3.34.0 and later */
136763  int (*txn_state)(sqlite3*,const char*);
136764  /* Version 3.36.1 and later */
136765  sqlite3_int64 (*changes64)(sqlite3*);
136766  sqlite3_int64 (*total_changes64)(sqlite3*);
136767  /* Version 3.37.0 and later */
136768  int (*autovacuum_pages)(sqlite3*,
136769     unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int),
136770     void*, void(*)(void*));
136771  /* Version 3.38.0 and later */
136772  int (*error_offset)(sqlite3*);
136773  int (*vtab_rhs_value)(sqlite3_index_info*,int,sqlite3_value**);
136774  int (*vtab_distinct)(sqlite3_index_info*);
136775  int (*vtab_in)(sqlite3_index_info*,int,int);
136776  int (*vtab_in_first)(sqlite3_value*,sqlite3_value**);
136777  int (*vtab_in_next)(sqlite3_value*,sqlite3_value**);
136778  /* Version 3.39.0 and later */
136779  int (*deserialize)(sqlite3*,const char*,unsigned char*,
136780                     sqlite3_int64,sqlite3_int64,unsigned);
136781  unsigned char *(*serialize)(sqlite3*,const char *,sqlite3_int64*,
136782                              unsigned int);
136783  const char *(*db_name)(sqlite3*,int);
136784  /* Version 3.40.0 and later */
136785  int (*value_encoding)(sqlite3_value*);
136786  /* Version 3.41.0 and later */
136787  int (*is_interrupted)(sqlite3*);
136788  /* Version 3.43.0 and later */
136789  int (*stmt_explain)(sqlite3_stmt*,int);
136790  /* Version 3.44.0 and later */
136791  void *(*get_clientdata)(sqlite3*,const char*);
136792  int (*set_clientdata)(sqlite3*, const char*, void*, void(*)(void*));
136793};
136794
136795/*
136796** This is the function signature used for all extension entry points.  It
136797** is also defined in the file "loadext.c".
136798*/
136799typedef int (*sqlite3_loadext_entry)(
136800  sqlite3 *db,                       /* Handle to the database. */
136801  char **pzErrMsg,                   /* Used to set error string on failure. */
136802  const sqlite3_api_routines *pThunk /* Extension API function pointers. */
136803);
136804
136805/*
136806** The following macros redefine the API routines so that they are
136807** redirected through the global sqlite3_api structure.
136808**
136809** This header file is also used by the loadext.c source file
136810** (part of the main SQLite library - not an extension) so that
136811** it can get access to the sqlite3_api_routines structure
136812** definition.  But the main library does not want to redefine
136813** the API.  So the redefinition macros are only valid if the
136814** SQLITE_CORE macros is undefined.
136815*/
136816#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
136817#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
136818#ifndef SQLITE_OMIT_DEPRECATED
136819#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
136820#endif
136821#define sqlite3_bind_blob              sqlite3_api->bind_blob
136822#define sqlite3_bind_double            sqlite3_api->bind_double
136823#define sqlite3_bind_int               sqlite3_api->bind_int
136824#define sqlite3_bind_int64             sqlite3_api->bind_int64
136825#define sqlite3_bind_null              sqlite3_api->bind_null
136826#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
136827#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
136828#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
136829#define sqlite3_bind_text              sqlite3_api->bind_text
136830#define sqlite3_bind_text16            sqlite3_api->bind_text16
136831#define sqlite3_bind_value             sqlite3_api->bind_value
136832#define sqlite3_busy_handler           sqlite3_api->busy_handler
136833#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
136834#define sqlite3_changes                sqlite3_api->changes
136835#define sqlite3_close                  sqlite3_api->close
136836#define sqlite3_collation_needed       sqlite3_api->collation_needed
136837#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
136838#define sqlite3_column_blob            sqlite3_api->column_blob
136839#define sqlite3_column_bytes           sqlite3_api->column_bytes
136840#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
136841#define sqlite3_column_count           sqlite3_api->column_count
136842#define sqlite3_column_database_name   sqlite3_api->column_database_name
136843#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
136844#define sqlite3_column_decltype        sqlite3_api->column_decltype
136845#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
136846#define sqlite3_column_double          sqlite3_api->column_double
136847#define sqlite3_column_int             sqlite3_api->column_int
136848#define sqlite3_column_int64           sqlite3_api->column_int64
136849#define sqlite3_column_name            sqlite3_api->column_name
136850#define sqlite3_column_name16          sqlite3_api->column_name16
136851#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
136852#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
136853#define sqlite3_column_table_name      sqlite3_api->column_table_name
136854#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
136855#define sqlite3_column_text            sqlite3_api->column_text
136856#define sqlite3_column_text16          sqlite3_api->column_text16
136857#define sqlite3_column_type            sqlite3_api->column_type
136858#define sqlite3_column_value           sqlite3_api->column_value
136859#define sqlite3_commit_hook            sqlite3_api->commit_hook
136860#define sqlite3_complete               sqlite3_api->complete
136861#define sqlite3_complete16             sqlite3_api->complete16
136862#define sqlite3_create_collation       sqlite3_api->create_collation
136863#define sqlite3_create_collation16     sqlite3_api->create_collation16
136864#define sqlite3_create_function        sqlite3_api->create_function
136865#define sqlite3_create_function16      sqlite3_api->create_function16
136866#define sqlite3_create_module          sqlite3_api->create_module
136867#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
136868#define sqlite3_data_count             sqlite3_api->data_count
136869#define sqlite3_db_handle              sqlite3_api->db_handle
136870#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
136871#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
136872#define sqlite3_errcode                sqlite3_api->errcode
136873#define sqlite3_errmsg                 sqlite3_api->errmsg
136874#define sqlite3_errmsg16               sqlite3_api->errmsg16
136875#define sqlite3_exec                   sqlite3_api->exec
136876#ifndef SQLITE_OMIT_DEPRECATED
136877#define sqlite3_expired                sqlite3_api->expired
136878#endif
136879#define sqlite3_finalize               sqlite3_api->finalize
136880#define sqlite3_free                   sqlite3_api->free
136881#define sqlite3_free_table             sqlite3_api->free_table
136882#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
136883#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
136884#define sqlite3_get_table              sqlite3_api->get_table
136885#ifndef SQLITE_OMIT_DEPRECATED
136886#define sqlite3_global_recover         sqlite3_api->global_recover
136887#endif
136888#define sqlite3_interrupt              sqlite3_api->interruptx
136889#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
136890#define sqlite3_libversion             sqlite3_api->libversion
136891#define sqlite3_libversion_number      sqlite3_api->libversion_number
136892#define sqlite3_malloc                 sqlite3_api->malloc
136893#define sqlite3_mprintf                sqlite3_api->mprintf
136894#define sqlite3_open                   sqlite3_api->open
136895#define sqlite3_open16                 sqlite3_api->open16
136896#define sqlite3_prepare                sqlite3_api->prepare
136897#define sqlite3_prepare16              sqlite3_api->prepare16
136898#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
136899#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
136900#define sqlite3_profile                sqlite3_api->profile
136901#define sqlite3_progress_handler       sqlite3_api->progress_handler
136902#define sqlite3_realloc                sqlite3_api->realloc
136903#define sqlite3_reset                  sqlite3_api->reset
136904#define sqlite3_result_blob            sqlite3_api->result_blob
136905#define sqlite3_result_double          sqlite3_api->result_double
136906#define sqlite3_result_error           sqlite3_api->result_error
136907#define sqlite3_result_error16         sqlite3_api->result_error16
136908#define sqlite3_result_int             sqlite3_api->result_int
136909#define sqlite3_result_int64           sqlite3_api->result_int64
136910#define sqlite3_result_null            sqlite3_api->result_null
136911#define sqlite3_result_text            sqlite3_api->result_text
136912#define sqlite3_result_text16          sqlite3_api->result_text16
136913#define sqlite3_result_text16be        sqlite3_api->result_text16be
136914#define sqlite3_result_text16le        sqlite3_api->result_text16le
136915#define sqlite3_result_value           sqlite3_api->result_value
136916#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
136917#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
136918#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
136919#define sqlite3_snprintf               sqlite3_api->xsnprintf
136920#define sqlite3_step                   sqlite3_api->step
136921#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
136922#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
136923#define sqlite3_total_changes          sqlite3_api->total_changes
136924#define sqlite3_trace                  sqlite3_api->trace
136925#ifndef SQLITE_OMIT_DEPRECATED
136926#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
136927#endif
136928#define sqlite3_update_hook            sqlite3_api->update_hook
136929#define sqlite3_user_data              sqlite3_api->user_data
136930#define sqlite3_value_blob             sqlite3_api->value_blob
136931#define sqlite3_value_bytes            sqlite3_api->value_bytes
136932#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
136933#define sqlite3_value_double           sqlite3_api->value_double
136934#define sqlite3_value_int              sqlite3_api->value_int
136935#define sqlite3_value_int64            sqlite3_api->value_int64
136936#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
136937#define sqlite3_value_text             sqlite3_api->value_text
136938#define sqlite3_value_text16           sqlite3_api->value_text16
136939#define sqlite3_value_text16be         sqlite3_api->value_text16be
136940#define sqlite3_value_text16le         sqlite3_api->value_text16le
136941#define sqlite3_value_type             sqlite3_api->value_type
136942#define sqlite3_vmprintf               sqlite3_api->vmprintf
136943#define sqlite3_vsnprintf              sqlite3_api->xvsnprintf
136944#define sqlite3_overload_function      sqlite3_api->overload_function
136945#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
136946#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
136947#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
136948#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
136949#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
136950#define sqlite3_blob_close             sqlite3_api->blob_close
136951#define sqlite3_blob_open              sqlite3_api->blob_open
136952#define sqlite3_blob_read              sqlite3_api->blob_read
136953#define sqlite3_blob_write             sqlite3_api->blob_write
136954#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
136955#define sqlite3_file_control           sqlite3_api->file_control
136956#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
136957#define sqlite3_memory_used            sqlite3_api->memory_used
136958#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
136959#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
136960#define sqlite3_mutex_free             sqlite3_api->mutex_free
136961#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
136962#define sqlite3_mutex_try              sqlite3_api->mutex_try
136963#define sqlite3_open_v2                sqlite3_api->open_v2
136964#define sqlite3_release_memory         sqlite3_api->release_memory
136965#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
136966#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
136967#define sqlite3_sleep                  sqlite3_api->sleep
136968#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
136969#define sqlite3_vfs_find               sqlite3_api->vfs_find
136970#define sqlite3_vfs_register           sqlite3_api->vfs_register
136971#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
136972#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
136973#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
136974#define sqlite3_result_error_code      sqlite3_api->result_error_code
136975#define sqlite3_test_control           sqlite3_api->test_control
136976#define sqlite3_randomness             sqlite3_api->randomness
136977#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
136978#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
136979#define sqlite3_limit                  sqlite3_api->limit
136980#define sqlite3_next_stmt              sqlite3_api->next_stmt
136981#define sqlite3_sql                    sqlite3_api->sql
136982#define sqlite3_status                 sqlite3_api->status
136983#define sqlite3_backup_finish          sqlite3_api->backup_finish
136984#define sqlite3_backup_init            sqlite3_api->backup_init
136985#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
136986#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
136987#define sqlite3_backup_step            sqlite3_api->backup_step
136988#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
136989#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
136990#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
136991#define sqlite3_db_config              sqlite3_api->db_config
136992#define sqlite3_db_mutex               sqlite3_api->db_mutex
136993#define sqlite3_db_status              sqlite3_api->db_status
136994#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
136995#define sqlite3_log                    sqlite3_api->log
136996#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
136997#define sqlite3_sourceid               sqlite3_api->sourceid
136998#define sqlite3_stmt_status            sqlite3_api->stmt_status
136999#define sqlite3_strnicmp               sqlite3_api->strnicmp
137000#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
137001#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
137002#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
137003#define sqlite3_wal_hook               sqlite3_api->wal_hook
137004#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
137005#define sqlite3_vtab_config            sqlite3_api->vtab_config
137006#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
137007/* Version 3.7.16 and later */
137008#define sqlite3_close_v2               sqlite3_api->close_v2
137009#define sqlite3_db_filename            sqlite3_api->db_filename
137010#define sqlite3_db_readonly            sqlite3_api->db_readonly
137011#define sqlite3_db_release_memory      sqlite3_api->db_release_memory
137012#define sqlite3_errstr                 sqlite3_api->errstr
137013#define sqlite3_stmt_busy              sqlite3_api->stmt_busy
137014#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
137015#define sqlite3_stricmp                sqlite3_api->stricmp
137016#define sqlite3_uri_boolean            sqlite3_api->uri_boolean
137017#define sqlite3_uri_int64              sqlite3_api->uri_int64
137018#define sqlite3_uri_parameter          sqlite3_api->uri_parameter
137019#define sqlite3_uri_vsnprintf          sqlite3_api->xvsnprintf
137020#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
137021/* Version 3.8.7 and later */
137022#define sqlite3_auto_extension         sqlite3_api->auto_extension
137023#define sqlite3_bind_blob64            sqlite3_api->bind_blob64
137024#define sqlite3_bind_text64            sqlite3_api->bind_text64
137025#define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
137026#define sqlite3_load_extension         sqlite3_api->load_extension
137027#define sqlite3_malloc64               sqlite3_api->malloc64
137028#define sqlite3_msize                  sqlite3_api->msize
137029#define sqlite3_realloc64              sqlite3_api->realloc64
137030#define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
137031#define sqlite3_result_blob64          sqlite3_api->result_blob64
137032#define sqlite3_result_text64          sqlite3_api->result_text64
137033#define sqlite3_strglob                sqlite3_api->strglob
137034/* Version 3.8.11 and later */
137035#define sqlite3_value_dup              sqlite3_api->value_dup
137036#define sqlite3_value_free             sqlite3_api->value_free
137037#define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
137038#define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
137039/* Version 3.9.0 and later */
137040#define sqlite3_value_subtype          sqlite3_api->value_subtype
137041#define sqlite3_result_subtype         sqlite3_api->result_subtype
137042/* Version 3.10.0 and later */
137043#define sqlite3_status64               sqlite3_api->status64
137044#define sqlite3_strlike                sqlite3_api->strlike
137045#define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush
137046/* Version 3.12.0 and later */
137047#define sqlite3_system_errno           sqlite3_api->system_errno
137048/* Version 3.14.0 and later */
137049#define sqlite3_trace_v2               sqlite3_api->trace_v2
137050#define sqlite3_expanded_sql           sqlite3_api->expanded_sql
137051/* Version 3.18.0 and later */
137052#define sqlite3_set_last_insert_rowid  sqlite3_api->set_last_insert_rowid
137053/* Version 3.20.0 and later */
137054#define sqlite3_prepare_v3             sqlite3_api->prepare_v3
137055#define sqlite3_prepare16_v3           sqlite3_api->prepare16_v3
137056#define sqlite3_bind_pointer           sqlite3_api->bind_pointer
137057#define sqlite3_result_pointer         sqlite3_api->result_pointer
137058#define sqlite3_value_pointer          sqlite3_api->value_pointer
137059/* Version 3.22.0 and later */
137060#define sqlite3_vtab_nochange          sqlite3_api->vtab_nochange
137061#define sqlite3_value_nochange         sqlite3_api->value_nochange
137062#define sqlite3_vtab_collation         sqlite3_api->vtab_collation
137063/* Version 3.24.0 and later */
137064#define sqlite3_keyword_count          sqlite3_api->keyword_count
137065#define sqlite3_keyword_name           sqlite3_api->keyword_name
137066#define sqlite3_keyword_check          sqlite3_api->keyword_check
137067#define sqlite3_str_new                sqlite3_api->str_new
137068#define sqlite3_str_finish             sqlite3_api->str_finish
137069#define sqlite3_str_appendf            sqlite3_api->str_appendf
137070#define sqlite3_str_vappendf           sqlite3_api->str_vappendf
137071#define sqlite3_str_append             sqlite3_api->str_append
137072#define sqlite3_str_appendall          sqlite3_api->str_appendall
137073#define sqlite3_str_appendchar         sqlite3_api->str_appendchar
137074#define sqlite3_str_reset              sqlite3_api->str_reset
137075#define sqlite3_str_errcode            sqlite3_api->str_errcode
137076#define sqlite3_str_length             sqlite3_api->str_length
137077#define sqlite3_str_value              sqlite3_api->str_value
137078/* Version 3.25.0 and later */
137079#define sqlite3_create_window_function sqlite3_api->create_window_function
137080/* Version 3.26.0 and later */
137081#define sqlite3_normalized_sql         sqlite3_api->normalized_sql
137082/* Version 3.28.0 and later */
137083#define sqlite3_stmt_isexplain         sqlite3_api->stmt_isexplain
137084#define sqlite3_value_frombind         sqlite3_api->value_frombind
137085/* Version 3.30.0 and later */
137086#define sqlite3_drop_modules           sqlite3_api->drop_modules
137087/* Version 3.31.0 and later */
137088#define sqlite3_hard_heap_limit64      sqlite3_api->hard_heap_limit64
137089#define sqlite3_uri_key                sqlite3_api->uri_key
137090#define sqlite3_filename_database      sqlite3_api->filename_database
137091#define sqlite3_filename_journal       sqlite3_api->filename_journal
137092#define sqlite3_filename_wal           sqlite3_api->filename_wal
137093/* Version 3.32.0 and later */
137094#define sqlite3_create_filename        sqlite3_api->create_filename
137095#define sqlite3_free_filename          sqlite3_api->free_filename
137096#define sqlite3_database_file_object   sqlite3_api->database_file_object
137097/* Version 3.34.0 and later */
137098#define sqlite3_txn_state              sqlite3_api->txn_state
137099/* Version 3.36.1 and later */
137100#define sqlite3_changes64              sqlite3_api->changes64
137101#define sqlite3_total_changes64        sqlite3_api->total_changes64
137102/* Version 3.37.0 and later */
137103#define sqlite3_autovacuum_pages       sqlite3_api->autovacuum_pages
137104/* Version 3.38.0 and later */
137105#define sqlite3_error_offset           sqlite3_api->error_offset
137106#define sqlite3_vtab_rhs_value         sqlite3_api->vtab_rhs_value
137107#define sqlite3_vtab_distinct          sqlite3_api->vtab_distinct
137108#define sqlite3_vtab_in                sqlite3_api->vtab_in
137109#define sqlite3_vtab_in_first          sqlite3_api->vtab_in_first
137110#define sqlite3_vtab_in_next           sqlite3_api->vtab_in_next
137111/* Version 3.39.0 and later */
137112#ifndef SQLITE_OMIT_DESERIALIZE
137113#define sqlite3_deserialize            sqlite3_api->deserialize
137114#define sqlite3_serialize              sqlite3_api->serialize
137115#endif
137116#define sqlite3_db_name                sqlite3_api->db_name
137117/* Version 3.40.0 and later */
137118#define sqlite3_value_encoding         sqlite3_api->value_encoding
137119/* Version 3.41.0 and later */
137120#define sqlite3_is_interrupted         sqlite3_api->is_interrupted
137121/* Version 3.43.0 and later */
137122#define sqlite3_stmt_explain           sqlite3_api->stmt_explain
137123/* Version 3.44.0 and later */
137124#define sqlite3_get_clientdata         sqlite3_api->get_clientdata
137125#define sqlite3_set_clientdata         sqlite3_api->set_clientdata
137126#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
137127
137128#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
137129  /* This case when the file really is being compiled as a loadable
137130  ** extension */
137131# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
137132# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
137133# define SQLITE_EXTENSION_INIT3     \
137134    extern const sqlite3_api_routines *sqlite3_api;
137135#else
137136  /* This case when the file is being statically linked into the
137137  ** application */
137138# define SQLITE_EXTENSION_INIT1     /*no-op*/
137139# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
137140# define SQLITE_EXTENSION_INIT3     /*no-op*/
137141#endif
137142
137143#endif /* SQLITE3EXT_H */
137144
137145/************** End of sqlite3ext.h ******************************************/
137146/************** Continuing where we left off in loadext.c ********************/
137147/* #include "sqliteInt.h" */
137148
137149#ifndef SQLITE_OMIT_LOAD_EXTENSION
137150/*
137151** Some API routines are omitted when various features are
137152** excluded from a build of SQLite.  Substitute a NULL pointer
137153** for any missing APIs.
137154*/
137155#ifndef SQLITE_ENABLE_COLUMN_METADATA
137156# define sqlite3_column_database_name   0
137157# define sqlite3_column_database_name16 0
137158# define sqlite3_column_table_name      0
137159# define sqlite3_column_table_name16    0
137160# define sqlite3_column_origin_name     0
137161# define sqlite3_column_origin_name16   0
137162#endif
137163
137164#ifdef SQLITE_OMIT_AUTHORIZATION
137165# define sqlite3_set_authorizer         0
137166#endif
137167
137168#ifdef SQLITE_OMIT_UTF16
137169# define sqlite3_bind_text16            0
137170# define sqlite3_collation_needed16     0
137171# define sqlite3_column_decltype16      0
137172# define sqlite3_column_name16          0
137173# define sqlite3_column_text16          0
137174# define sqlite3_complete16             0
137175# define sqlite3_create_collation16     0
137176# define sqlite3_create_function16      0
137177# define sqlite3_errmsg16               0
137178# define sqlite3_open16                 0
137179# define sqlite3_prepare16              0
137180# define sqlite3_prepare16_v2           0
137181# define sqlite3_prepare16_v3           0
137182# define sqlite3_result_error16         0
137183# define sqlite3_result_text16          0
137184# define sqlite3_result_text16be        0
137185# define sqlite3_result_text16le        0
137186# define sqlite3_value_text16           0
137187# define sqlite3_value_text16be         0
137188# define sqlite3_value_text16le         0
137189# define sqlite3_column_database_name16 0
137190# define sqlite3_column_table_name16    0
137191# define sqlite3_column_origin_name16   0
137192#endif
137193
137194#ifdef SQLITE_OMIT_COMPLETE
137195# define sqlite3_complete 0
137196# define sqlite3_complete16 0
137197#endif
137198
137199#ifdef SQLITE_OMIT_DECLTYPE
137200# define sqlite3_column_decltype16      0
137201# define sqlite3_column_decltype        0
137202#endif
137203
137204#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
137205# define sqlite3_progress_handler 0
137206#endif
137207
137208#ifdef SQLITE_OMIT_VIRTUALTABLE
137209# define sqlite3_create_module 0
137210# define sqlite3_create_module_v2 0
137211# define sqlite3_declare_vtab 0
137212# define sqlite3_vtab_config 0
137213# define sqlite3_vtab_on_conflict 0
137214# define sqlite3_vtab_collation 0
137215#endif
137216
137217#ifdef SQLITE_OMIT_SHARED_CACHE
137218# define sqlite3_enable_shared_cache 0
137219#endif
137220
137221#if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
137222# define sqlite3_profile       0
137223# define sqlite3_trace         0
137224#endif
137225
137226#ifdef SQLITE_OMIT_GET_TABLE
137227# define sqlite3_free_table    0
137228# define sqlite3_get_table     0
137229#endif
137230
137231#ifdef SQLITE_OMIT_INCRBLOB
137232#define sqlite3_bind_zeroblob  0
137233#define sqlite3_blob_bytes     0
137234#define sqlite3_blob_close     0
137235#define sqlite3_blob_open      0
137236#define sqlite3_blob_read      0
137237#define sqlite3_blob_write     0
137238#define sqlite3_blob_reopen    0
137239#endif
137240
137241#if defined(SQLITE_OMIT_TRACE)
137242# define sqlite3_trace_v2      0
137243#endif
137244
137245/*
137246** The following structure contains pointers to all SQLite API routines.
137247** A pointer to this structure is passed into extensions when they are
137248** loaded so that the extension can make calls back into the SQLite
137249** library.
137250**
137251** When adding new APIs, add them to the bottom of this structure
137252** in order to preserve backwards compatibility.
137253**
137254** Extensions that use newer APIs should first call the
137255** sqlite3_libversion_number() to make sure that the API they
137256** intend to use is supported by the library.  Extensions should
137257** also check to make sure that the pointer to the function is
137258** not NULL before calling it.
137259*/
137260static const sqlite3_api_routines sqlite3Apis = {
137261  sqlite3_aggregate_context,
137262#ifndef SQLITE_OMIT_DEPRECATED
137263  sqlite3_aggregate_count,
137264#else
137265  0,
137266#endif
137267  sqlite3_bind_blob,
137268  sqlite3_bind_double,
137269  sqlite3_bind_int,
137270  sqlite3_bind_int64,
137271  sqlite3_bind_null,
137272  sqlite3_bind_parameter_count,
137273  sqlite3_bind_parameter_index,
137274  sqlite3_bind_parameter_name,
137275  sqlite3_bind_text,
137276  sqlite3_bind_text16,
137277  sqlite3_bind_value,
137278  sqlite3_busy_handler,
137279  sqlite3_busy_timeout,
137280  sqlite3_changes,
137281  sqlite3_close,
137282  sqlite3_collation_needed,
137283  sqlite3_collation_needed16,
137284  sqlite3_column_blob,
137285  sqlite3_column_bytes,
137286  sqlite3_column_bytes16,
137287  sqlite3_column_count,
137288  sqlite3_column_database_name,
137289  sqlite3_column_database_name16,
137290  sqlite3_column_decltype,
137291  sqlite3_column_decltype16,
137292  sqlite3_column_double,
137293  sqlite3_column_int,
137294  sqlite3_column_int64,
137295  sqlite3_column_name,
137296  sqlite3_column_name16,
137297  sqlite3_column_origin_name,
137298  sqlite3_column_origin_name16,
137299  sqlite3_column_table_name,
137300  sqlite3_column_table_name16,
137301  sqlite3_column_text,
137302  sqlite3_column_text16,
137303  sqlite3_column_type,
137304  sqlite3_column_value,
137305  sqlite3_commit_hook,
137306  sqlite3_complete,
137307  sqlite3_complete16,
137308  sqlite3_create_collation,
137309  sqlite3_create_collation16,
137310  sqlite3_create_function,
137311  sqlite3_create_function16,
137312  sqlite3_create_module,
137313  sqlite3_data_count,
137314  sqlite3_db_handle,
137315  sqlite3_declare_vtab,
137316  sqlite3_enable_shared_cache,
137317  sqlite3_errcode,
137318  sqlite3_errmsg,
137319  sqlite3_errmsg16,
137320  sqlite3_exec,
137321#ifndef SQLITE_OMIT_DEPRECATED
137322  sqlite3_expired,
137323#else
137324  0,
137325#endif
137326  sqlite3_finalize,
137327  sqlite3_free,
137328  sqlite3_free_table,
137329  sqlite3_get_autocommit,
137330  sqlite3_get_auxdata,
137331  sqlite3_get_table,
137332  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
137333  sqlite3_interrupt,
137334  sqlite3_last_insert_rowid,
137335  sqlite3_libversion,
137336  sqlite3_libversion_number,
137337  sqlite3_malloc,
137338  sqlite3_mprintf,
137339  sqlite3_open,
137340  sqlite3_open16,
137341  sqlite3_prepare,
137342  sqlite3_prepare16,
137343  sqlite3_profile,
137344  sqlite3_progress_handler,
137345  sqlite3_realloc,
137346  sqlite3_reset,
137347  sqlite3_result_blob,
137348  sqlite3_result_double,
137349  sqlite3_result_error,
137350  sqlite3_result_error16,
137351  sqlite3_result_int,
137352  sqlite3_result_int64,
137353  sqlite3_result_null,
137354  sqlite3_result_text,
137355  sqlite3_result_text16,
137356  sqlite3_result_text16be,
137357  sqlite3_result_text16le,
137358  sqlite3_result_value,
137359  sqlite3_rollback_hook,
137360  sqlite3_set_authorizer,
137361  sqlite3_set_auxdata,
137362  sqlite3_snprintf,
137363  sqlite3_step,
137364  sqlite3_table_column_metadata,
137365#ifndef SQLITE_OMIT_DEPRECATED
137366  sqlite3_thread_cleanup,
137367#else
137368  0,
137369#endif
137370  sqlite3_total_changes,
137371  sqlite3_trace,
137372#ifndef SQLITE_OMIT_DEPRECATED
137373  sqlite3_transfer_bindings,
137374#else
137375  0,
137376#endif
137377  sqlite3_update_hook,
137378  sqlite3_user_data,
137379  sqlite3_value_blob,
137380  sqlite3_value_bytes,
137381  sqlite3_value_bytes16,
137382  sqlite3_value_double,
137383  sqlite3_value_int,
137384  sqlite3_value_int64,
137385  sqlite3_value_numeric_type,
137386  sqlite3_value_text,
137387  sqlite3_value_text16,
137388  sqlite3_value_text16be,
137389  sqlite3_value_text16le,
137390  sqlite3_value_type,
137391  sqlite3_vmprintf,
137392  /*
137393  ** The original API set ends here.  All extensions can call any
137394  ** of the APIs above provided that the pointer is not NULL.  But
137395  ** before calling APIs that follow, extension should check the
137396  ** sqlite3_libversion_number() to make sure they are dealing with
137397  ** a library that is new enough to support that API.
137398  *************************************************************************
137399  */
137400  sqlite3_overload_function,
137401
137402  /*
137403  ** Added after 3.3.13
137404  */
137405  sqlite3_prepare_v2,
137406  sqlite3_prepare16_v2,
137407  sqlite3_clear_bindings,
137408
137409  /*
137410  ** Added for 3.4.1
137411  */
137412  sqlite3_create_module_v2,
137413
137414  /*
137415  ** Added for 3.5.0
137416  */
137417  sqlite3_bind_zeroblob,
137418  sqlite3_blob_bytes,
137419  sqlite3_blob_close,
137420  sqlite3_blob_open,
137421  sqlite3_blob_read,
137422  sqlite3_blob_write,
137423  sqlite3_create_collation_v2,
137424  sqlite3_file_control,
137425  sqlite3_memory_highwater,
137426  sqlite3_memory_used,
137427#ifdef SQLITE_MUTEX_OMIT
137428  0,
137429  0,
137430  0,
137431  0,
137432  0,
137433#else
137434  sqlite3_mutex_alloc,
137435  sqlite3_mutex_enter,
137436  sqlite3_mutex_free,
137437  sqlite3_mutex_leave,
137438  sqlite3_mutex_try,
137439#endif
137440  sqlite3_open_v2,
137441  sqlite3_release_memory,
137442  sqlite3_result_error_nomem,
137443  sqlite3_result_error_toobig,
137444  sqlite3_sleep,
137445  sqlite3_soft_heap_limit,
137446  sqlite3_vfs_find,
137447  sqlite3_vfs_register,
137448  sqlite3_vfs_unregister,
137449
137450  /*
137451  ** Added for 3.5.8
137452  */
137453  sqlite3_threadsafe,
137454  sqlite3_result_zeroblob,
137455  sqlite3_result_error_code,
137456  sqlite3_test_control,
137457  sqlite3_randomness,
137458  sqlite3_context_db_handle,
137459
137460  /*
137461  ** Added for 3.6.0
137462  */
137463  sqlite3_extended_result_codes,
137464  sqlite3_limit,
137465  sqlite3_next_stmt,
137466  sqlite3_sql,
137467  sqlite3_status,
137468
137469  /*
137470  ** Added for 3.7.4
137471  */
137472  sqlite3_backup_finish,
137473  sqlite3_backup_init,
137474  sqlite3_backup_pagecount,
137475  sqlite3_backup_remaining,
137476  sqlite3_backup_step,
137477#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
137478  sqlite3_compileoption_get,
137479  sqlite3_compileoption_used,
137480#else
137481  0,
137482  0,
137483#endif
137484  sqlite3_create_function_v2,
137485  sqlite3_db_config,
137486  sqlite3_db_mutex,
137487  sqlite3_db_status,
137488  sqlite3_extended_errcode,
137489  sqlite3_log,
137490  sqlite3_soft_heap_limit64,
137491  sqlite3_sourceid,
137492  sqlite3_stmt_status,
137493  sqlite3_strnicmp,
137494#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
137495  sqlite3_unlock_notify,
137496#else
137497  0,
137498#endif
137499#ifndef SQLITE_OMIT_WAL
137500  sqlite3_wal_autocheckpoint,
137501  sqlite3_wal_checkpoint,
137502  sqlite3_wal_hook,
137503#else
137504  0,
137505  0,
137506  0,
137507#endif
137508  sqlite3_blob_reopen,
137509  sqlite3_vtab_config,
137510  sqlite3_vtab_on_conflict,
137511  sqlite3_close_v2,
137512  sqlite3_db_filename,
137513  sqlite3_db_readonly,
137514  sqlite3_db_release_memory,
137515  sqlite3_errstr,
137516  sqlite3_stmt_busy,
137517  sqlite3_stmt_readonly,
137518  sqlite3_stricmp,
137519  sqlite3_uri_boolean,
137520  sqlite3_uri_int64,
137521  sqlite3_uri_parameter,
137522  sqlite3_vsnprintf,
137523  sqlite3_wal_checkpoint_v2,
137524  /* Version 3.8.7 and later */
137525  sqlite3_auto_extension,
137526  sqlite3_bind_blob64,
137527  sqlite3_bind_text64,
137528  sqlite3_cancel_auto_extension,
137529  sqlite3_load_extension,
137530  sqlite3_malloc64,
137531  sqlite3_msize,
137532  sqlite3_realloc64,
137533  sqlite3_reset_auto_extension,
137534  sqlite3_result_blob64,
137535  sqlite3_result_text64,
137536  sqlite3_strglob,
137537  /* Version 3.8.11 and later */
137538  (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
137539  sqlite3_value_free,
137540  sqlite3_result_zeroblob64,
137541  sqlite3_bind_zeroblob64,
137542  /* Version 3.9.0 and later */
137543  sqlite3_value_subtype,
137544  sqlite3_result_subtype,
137545  /* Version 3.10.0 and later */
137546  sqlite3_status64,
137547  sqlite3_strlike,
137548  sqlite3_db_cacheflush,
137549  /* Version 3.12.0 and later */
137550  sqlite3_system_errno,
137551  /* Version 3.14.0 and later */
137552  sqlite3_trace_v2,
137553  sqlite3_expanded_sql,
137554  /* Version 3.18.0 and later */
137555  sqlite3_set_last_insert_rowid,
137556  /* Version 3.20.0 and later */
137557  sqlite3_prepare_v3,
137558  sqlite3_prepare16_v3,
137559  sqlite3_bind_pointer,
137560  sqlite3_result_pointer,
137561  sqlite3_value_pointer,
137562  /* Version 3.22.0 and later */
137563  sqlite3_vtab_nochange,
137564  sqlite3_value_nochange,
137565  sqlite3_vtab_collation,
137566  /* Version 3.24.0 and later */
137567  sqlite3_keyword_count,
137568  sqlite3_keyword_name,
137569  sqlite3_keyword_check,
137570  sqlite3_str_new,
137571  sqlite3_str_finish,
137572  sqlite3_str_appendf,
137573  sqlite3_str_vappendf,
137574  sqlite3_str_append,
137575  sqlite3_str_appendall,
137576  sqlite3_str_appendchar,
137577  sqlite3_str_reset,
137578  sqlite3_str_errcode,
137579  sqlite3_str_length,
137580  sqlite3_str_value,
137581  /* Version 3.25.0 and later */
137582  sqlite3_create_window_function,
137583  /* Version 3.26.0 and later */
137584#ifdef SQLITE_ENABLE_NORMALIZE
137585  sqlite3_normalized_sql,
137586#else
137587  0,
137588#endif
137589  /* Version 3.28.0 and later */
137590  sqlite3_stmt_isexplain,
137591  sqlite3_value_frombind,
137592  /* Version 3.30.0 and later */
137593#ifndef SQLITE_OMIT_VIRTUALTABLE
137594  sqlite3_drop_modules,
137595#else
137596  0,
137597#endif
137598  /* Version 3.31.0 and later */
137599  sqlite3_hard_heap_limit64,
137600  sqlite3_uri_key,
137601  sqlite3_filename_database,
137602  sqlite3_filename_journal,
137603  sqlite3_filename_wal,
137604  /* Version 3.32.0 and later */
137605  sqlite3_create_filename,
137606  sqlite3_free_filename,
137607  sqlite3_database_file_object,
137608  /* Version 3.34.0 and later */
137609  sqlite3_txn_state,
137610  /* Version 3.36.1 and later */
137611  sqlite3_changes64,
137612  sqlite3_total_changes64,
137613  /* Version 3.37.0 and later */
137614  sqlite3_autovacuum_pages,
137615  /* Version 3.38.0 and later */
137616  sqlite3_error_offset,
137617#ifndef SQLITE_OMIT_VIRTUALTABLE
137618  sqlite3_vtab_rhs_value,
137619  sqlite3_vtab_distinct,
137620  sqlite3_vtab_in,
137621  sqlite3_vtab_in_first,
137622  sqlite3_vtab_in_next,
137623#else
137624  0,
137625  0,
137626  0,
137627  0,
137628  0,
137629#endif
137630  /* Version 3.39.0 and later */
137631#ifndef SQLITE_OMIT_DESERIALIZE
137632  sqlite3_deserialize,
137633  sqlite3_serialize,
137634#else
137635  0,
137636  0,
137637#endif
137638  sqlite3_db_name,
137639  /* Version 3.40.0 and later */
137640  sqlite3_value_encoding,
137641  /* Version 3.41.0 and later */
137642  sqlite3_is_interrupted,
137643  /* Version 3.43.0 and later */
137644  sqlite3_stmt_explain,
137645  /* Version 3.44.0 and later */
137646  sqlite3_get_clientdata,
137647  sqlite3_set_clientdata
137648};
137649
137650/* True if x is the directory separator character
137651*/
137652#if SQLITE_OS_WIN
137653# define DirSep(X)  ((X)=='/'||(X)=='\\')
137654#else
137655# define DirSep(X)  ((X)=='/')
137656#endif
137657
137658/*
137659** Attempt to load an SQLite extension library contained in the file
137660** zFile.  The entry point is zProc.  zProc may be 0 in which case a
137661** default entry point name (sqlite3_extension_init) is used.  Use
137662** of the default name is recommended.
137663**
137664** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
137665**
137666** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
137667** error message text.  The calling function should free this memory
137668** by calling sqlite3DbFree(db, ).
137669*/
137670static int sqlite3LoadExtension(
137671  sqlite3 *db,          /* Load the extension into this database connection */
137672  const char *zFile,    /* Name of the shared library containing extension */
137673  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
137674  char **pzErrMsg       /* Put error message here if not 0 */
137675){
137676  sqlite3_vfs *pVfs = db->pVfs;
137677  void *handle;
137678  sqlite3_loadext_entry xInit;
137679  char *zErrmsg = 0;
137680  const char *zEntry;
137681  char *zAltEntry = 0;
137682  void **aHandle;
137683  u64 nMsg = strlen(zFile);
137684  int ii;
137685  int rc;
137686
137687  /* Shared library endings to try if zFile cannot be loaded as written */
137688  static const char *azEndings[] = {
137689#if SQLITE_OS_WIN
137690     "dll"
137691#elif defined(__APPLE__)
137692     "dylib"
137693#else
137694     "so"
137695#endif
137696  };
137697
137698
137699  if( pzErrMsg ) *pzErrMsg = 0;
137700
137701  /* Ticket #1863.  To avoid a creating security problems for older
137702  ** applications that relink against newer versions of SQLite, the
137703  ** ability to run load_extension is turned off by default.  One
137704  ** must call either sqlite3_enable_load_extension(db) or
137705  ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
137706  ** to turn on extension loading.
137707  */
137708  if( (db->flags & SQLITE_LoadExtension)==0 ){
137709    if( pzErrMsg ){
137710      *pzErrMsg = sqlite3_mprintf("not authorized");
137711    }
137712    return SQLITE_ERROR;
137713  }
137714
137715  zEntry = zProc ? zProc : "sqlite3_extension_init";
137716
137717  /* tag-20210611-1.  Some dlopen() implementations will segfault if given
137718  ** an oversize filename.  Most filesystems have a pathname limit of 4K,
137719  ** so limit the extension filename length to about twice that.
137720  ** https://sqlite.org/forum/forumpost/08a0d6d9bf
137721  **
137722  ** Later (2023-03-25): Save an extra 6 bytes for the filename suffix.
137723  ** See https://sqlite.org/forum/forumpost/24083b579d.
137724  */
137725  if( nMsg>SQLITE_MAX_PATHLEN ) goto extension_not_found;
137726
137727  /* Do not allow sqlite3_load_extension() to link to a copy of the
137728  ** running application, by passing in an empty filename. */
137729  if( nMsg==0 ) goto extension_not_found;
137730
137731  handle = sqlite3OsDlOpen(pVfs, zFile);
137732#if SQLITE_OS_UNIX || SQLITE_OS_WIN
137733  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
137734    char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
137735    if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
137736    if( nMsg+strlen(azEndings[ii])+1<=SQLITE_MAX_PATHLEN ){
137737      handle = sqlite3OsDlOpen(pVfs, zAltFile);
137738    }
137739    sqlite3_free(zAltFile);
137740  }
137741#endif
137742  if( handle==0 ) goto extension_not_found;
137743  xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
137744
137745  /* If no entry point was specified and the default legacy
137746  ** entry point name "sqlite3_extension_init" was not found, then
137747  ** construct an entry point name "sqlite3_X_init" where the X is
137748  ** replaced by the lowercase value of every ASCII alphabetic
137749  ** character in the filename after the last "/" upto the first ".",
137750  ** and eliding the first three characters if they are "lib".
137751  ** Examples:
137752  **
137753  **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
137754  **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
137755  */
137756  if( xInit==0 && zProc==0 ){
137757    int iFile, iEntry, c;
137758    int ncFile = sqlite3Strlen30(zFile);
137759    zAltEntry = sqlite3_malloc64(ncFile+30);
137760    if( zAltEntry==0 ){
137761      sqlite3OsDlClose(pVfs, handle);
137762      return SQLITE_NOMEM_BKPT;
137763    }
137764    memcpy(zAltEntry, "sqlite3_", 8);
137765    for(iFile=ncFile-1; iFile>=0 && !DirSep(zFile[iFile]); iFile--){}
137766    iFile++;
137767    if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
137768    for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
137769      if( sqlite3Isalpha(c) ){
137770        zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
137771      }
137772    }
137773    memcpy(zAltEntry+iEntry, "_init", 6);
137774    zEntry = zAltEntry;
137775    xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
137776  }
137777  if( xInit==0 ){
137778    if( pzErrMsg ){
137779      nMsg += strlen(zEntry) + 300;
137780      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
137781      if( zErrmsg ){
137782        assert( nMsg<0x7fffffff );  /* zErrmsg would be NULL if not so */
137783        sqlite3_snprintf((int)nMsg, zErrmsg,
137784            "no entry point [%s] in shared library [%s]", zEntry, zFile);
137785        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
137786      }
137787    }
137788    sqlite3OsDlClose(pVfs, handle);
137789    sqlite3_free(zAltEntry);
137790    return SQLITE_ERROR;
137791  }
137792  sqlite3_free(zAltEntry);
137793  rc = xInit(db, &zErrmsg, &sqlite3Apis);
137794  if( rc ){
137795    if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
137796    if( pzErrMsg ){
137797      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
137798    }
137799    sqlite3_free(zErrmsg);
137800    sqlite3OsDlClose(pVfs, handle);
137801    return SQLITE_ERROR;
137802  }
137803
137804  /* Append the new shared library handle to the db->aExtension array. */
137805  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
137806  if( aHandle==0 ){
137807    return SQLITE_NOMEM_BKPT;
137808  }
137809  if( db->nExtension>0 ){
137810    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
137811  }
137812  sqlite3DbFree(db, db->aExtension);
137813  db->aExtension = aHandle;
137814
137815  db->aExtension[db->nExtension++] = handle;
137816  return SQLITE_OK;
137817
137818extension_not_found:
137819  if( pzErrMsg ){
137820    nMsg += 300;
137821    *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
137822    if( zErrmsg ){
137823      assert( nMsg<0x7fffffff );  /* zErrmsg would be NULL if not so */
137824      sqlite3_snprintf((int)nMsg, zErrmsg,
137825          "unable to open shared library [%.*s]", SQLITE_MAX_PATHLEN, zFile);
137826      sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
137827    }
137828  }
137829  return SQLITE_ERROR;
137830}
137831SQLITE_API int sqlite3_load_extension(
137832  sqlite3 *db,          /* Load the extension into this database connection */
137833  const char *zFile,    /* Name of the shared library containing extension */
137834  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
137835  char **pzErrMsg       /* Put error message here if not 0 */
137836){
137837  int rc;
137838  sqlite3_mutex_enter(db->mutex);
137839  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
137840  rc = sqlite3ApiExit(db, rc);
137841  sqlite3_mutex_leave(db->mutex);
137842  return rc;
137843}
137844
137845/*
137846** Call this routine when the database connection is closing in order
137847** to clean up loaded extensions
137848*/
137849SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
137850  int i;
137851  assert( sqlite3_mutex_held(db->mutex) );
137852  for(i=0; i<db->nExtension; i++){
137853    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
137854  }
137855  sqlite3DbFree(db, db->aExtension);
137856}
137857
137858/*
137859** Enable or disable extension loading.  Extension loading is disabled by
137860** default so as not to open security holes in older applications.
137861*/
137862SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
137863#ifdef SQLITE_ENABLE_API_ARMOR
137864  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
137865#endif
137866  sqlite3_mutex_enter(db->mutex);
137867  if( onoff ){
137868    db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
137869  }else{
137870    db->flags &= ~(u64)(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
137871  }
137872  sqlite3_mutex_leave(db->mutex);
137873  return SQLITE_OK;
137874}
137875
137876#endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
137877
137878/*
137879** The following object holds the list of automatically loaded
137880** extensions.
137881**
137882** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MAIN
137883** mutex must be held while accessing this list.
137884*/
137885typedef struct sqlite3AutoExtList sqlite3AutoExtList;
137886static SQLITE_WSD struct sqlite3AutoExtList {
137887  u32 nExt;              /* Number of entries in aExt[] */
137888  void (**aExt)(void);   /* Pointers to the extension init functions */
137889} sqlite3Autoext = { 0, 0 };
137890
137891/* The "wsdAutoext" macro will resolve to the autoextension
137892** state vector.  If writable static data is unsupported on the target,
137893** we have to locate the state vector at run-time.  In the more common
137894** case where writable static data is supported, wsdStat can refer directly
137895** to the "sqlite3Autoext" state vector declared above.
137896*/
137897#ifdef SQLITE_OMIT_WSD
137898# define wsdAutoextInit \
137899  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
137900# define wsdAutoext x[0]
137901#else
137902# define wsdAutoextInit
137903# define wsdAutoext sqlite3Autoext
137904#endif
137905
137906
137907/*
137908** Register a statically linked extension that is automatically
137909** loaded by every new database connection.
137910*/
137911SQLITE_API int sqlite3_auto_extension(
137912  void (*xInit)(void)
137913){
137914  int rc = SQLITE_OK;
137915#ifdef SQLITE_ENABLE_API_ARMOR
137916  if( xInit==0 ) return SQLITE_MISUSE_BKPT;
137917#endif
137918#ifndef SQLITE_OMIT_AUTOINIT
137919  rc = sqlite3_initialize();
137920  if( rc ){
137921    return rc;
137922  }else
137923#endif
137924  {
137925    u32 i;
137926#if SQLITE_THREADSAFE
137927    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
137928#endif
137929    wsdAutoextInit;
137930    sqlite3_mutex_enter(mutex);
137931    for(i=0; i<wsdAutoext.nExt; i++){
137932      if( wsdAutoext.aExt[i]==xInit ) break;
137933    }
137934    if( i==wsdAutoext.nExt ){
137935      u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
137936      void (**aNew)(void);
137937      aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
137938      if( aNew==0 ){
137939        rc = SQLITE_NOMEM_BKPT;
137940      }else{
137941        wsdAutoext.aExt = aNew;
137942        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
137943        wsdAutoext.nExt++;
137944      }
137945    }
137946    sqlite3_mutex_leave(mutex);
137947    assert( (rc&0xff)==rc );
137948    return rc;
137949  }
137950}
137951
137952/*
137953** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
137954** set of routines that is invoked for each new database connection, if it
137955** is currently on the list.  If xInit is not on the list, then this
137956** routine is a no-op.
137957**
137958** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
137959** was not on the list.
137960*/
137961SQLITE_API int sqlite3_cancel_auto_extension(
137962  void (*xInit)(void)
137963){
137964#if SQLITE_THREADSAFE
137965  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
137966#endif
137967  int i;
137968  int n = 0;
137969  wsdAutoextInit;
137970#ifdef SQLITE_ENABLE_API_ARMOR
137971  if( xInit==0 ) return 0;
137972#endif
137973  sqlite3_mutex_enter(mutex);
137974  for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
137975    if( wsdAutoext.aExt[i]==xInit ){
137976      wsdAutoext.nExt--;
137977      wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
137978      n++;
137979      break;
137980    }
137981  }
137982  sqlite3_mutex_leave(mutex);
137983  return n;
137984}
137985
137986/*
137987** Reset the automatic extension loading mechanism.
137988*/
137989SQLITE_API void sqlite3_reset_auto_extension(void){
137990#ifndef SQLITE_OMIT_AUTOINIT
137991  if( sqlite3_initialize()==SQLITE_OK )
137992#endif
137993  {
137994#if SQLITE_THREADSAFE
137995    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
137996#endif
137997    wsdAutoextInit;
137998    sqlite3_mutex_enter(mutex);
137999    sqlite3_free(wsdAutoext.aExt);
138000    wsdAutoext.aExt = 0;
138001    wsdAutoext.nExt = 0;
138002    sqlite3_mutex_leave(mutex);
138003  }
138004}
138005
138006/*
138007** Load all automatic extensions.
138008**
138009** If anything goes wrong, set an error in the database connection.
138010*/
138011SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
138012  u32 i;
138013  int go = 1;
138014  int rc;
138015  sqlite3_loadext_entry xInit;
138016
138017  wsdAutoextInit;
138018  if( wsdAutoext.nExt==0 ){
138019    /* Common case: early out without every having to acquire a mutex */
138020    return;
138021  }
138022  for(i=0; go; i++){
138023    char *zErrmsg;
138024#if SQLITE_THREADSAFE
138025    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
138026#endif
138027#ifdef SQLITE_OMIT_LOAD_EXTENSION
138028    const sqlite3_api_routines *pThunk = 0;
138029#else
138030    const sqlite3_api_routines *pThunk = &sqlite3Apis;
138031#endif
138032    sqlite3_mutex_enter(mutex);
138033    if( i>=wsdAutoext.nExt ){
138034      xInit = 0;
138035      go = 0;
138036    }else{
138037      xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
138038    }
138039    sqlite3_mutex_leave(mutex);
138040    zErrmsg = 0;
138041    if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
138042      sqlite3ErrorWithMsg(db, rc,
138043            "automatic extension loading failed: %s", zErrmsg);
138044      go = 0;
138045    }
138046    sqlite3_free(zErrmsg);
138047  }
138048}
138049
138050/************** End of loadext.c *********************************************/
138051/************** Begin file pragma.c ******************************************/
138052/*
138053** 2003 April 6
138054**
138055** The author disclaims copyright to this source code.  In place of
138056** a legal notice, here is a blessing:
138057**
138058**    May you do good and not evil.
138059**    May you find forgiveness for yourself and forgive others.
138060**    May you share freely, never taking more than you give.
138061**
138062*************************************************************************
138063** This file contains code used to implement the PRAGMA command.
138064*/
138065/* #include "sqliteInt.h" */
138066
138067#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
138068#  if defined(__APPLE__)
138069#    define SQLITE_ENABLE_LOCKING_STYLE 1
138070#  else
138071#    define SQLITE_ENABLE_LOCKING_STYLE 0
138072#  endif
138073#endif
138074
138075/***************************************************************************
138076** The "pragma.h" include file is an automatically generated file that
138077** that includes the PragType_XXXX macro definitions and the aPragmaName[]
138078** object.  This ensures that the aPragmaName[] table is arranged in
138079** lexicographical order to facility a binary search of the pragma name.
138080** Do not edit pragma.h directly.  Edit and rerun the script in at
138081** ../tool/mkpragmatab.tcl. */
138082/************** Include pragma.h in the middle of pragma.c *******************/
138083/************** Begin file pragma.h ******************************************/
138084/* DO NOT EDIT!
138085** This file is automatically generated by the script at
138086** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit
138087** that script and rerun it.
138088*/
138089
138090/* The various pragma types */
138091#define PragTyp_ACTIVATE_EXTENSIONS            0
138092#define PragTyp_ANALYSIS_LIMIT                 1
138093#define PragTyp_HEADER_VALUE                   2
138094#define PragTyp_AUTO_VACUUM                    3
138095#define PragTyp_FLAG                           4
138096#define PragTyp_BUSY_TIMEOUT                   5
138097#define PragTyp_CACHE_SIZE                     6
138098#define PragTyp_CACHE_SPILL                    7
138099#define PragTyp_CASE_SENSITIVE_LIKE            8
138100#define PragTyp_COLLATION_LIST                 9
138101#define PragTyp_COMPILE_OPTIONS               10
138102#define PragTyp_DATA_STORE_DIRECTORY          11
138103#define PragTyp_DATABASE_LIST                 12
138104#define PragTyp_DEFAULT_CACHE_SIZE            13
138105#define PragTyp_ENCODING                      14
138106#define PragTyp_FOREIGN_KEY_CHECK             15
138107#define PragTyp_FOREIGN_KEY_LIST              16
138108#define PragTyp_FUNCTION_LIST                 17
138109#define PragTyp_HARD_HEAP_LIMIT               18
138110#define PragTyp_INCREMENTAL_VACUUM            19
138111#define PragTyp_INDEX_INFO                    20
138112#define PragTyp_INDEX_LIST                    21
138113#define PragTyp_INTEGRITY_CHECK               22
138114#define PragTyp_JOURNAL_MODE                  23
138115#define PragTyp_JOURNAL_SIZE_LIMIT            24
138116#define PragTyp_LOCK_PROXY_FILE               25
138117#define PragTyp_LOCKING_MODE                  26
138118#define PragTyp_PAGE_COUNT                    27
138119#define PragTyp_MMAP_SIZE                     28
138120#define PragTyp_MODULE_LIST                   29
138121#define PragTyp_OPTIMIZE                      30
138122#define PragTyp_PAGE_SIZE                     31
138123#define PragTyp_PRAGMA_LIST                   32
138124#define PragTyp_SECURE_DELETE                 33
138125#define PragTyp_SHRINK_MEMORY                 34
138126#define PragTyp_SOFT_HEAP_LIMIT               35
138127#define PragTyp_SYNCHRONOUS                   36
138128#define PragTyp_TABLE_INFO                    37
138129#define PragTyp_TABLE_LIST                    38
138130#define PragTyp_TEMP_STORE                    39
138131#define PragTyp_TEMP_STORE_DIRECTORY          40
138132#define PragTyp_THREADS                       41
138133#define PragTyp_WAL_AUTOCHECKPOINT            42
138134#define PragTyp_WAL_CHECKPOINT                43
138135#define PragTyp_LOCK_STATUS                   44
138136#define PragTyp_STATS                         45
138137
138138/* Property flags associated with various pragma. */
138139#define PragFlg_NeedSchema 0x01 /* Force schema load before running */
138140#define PragFlg_NoColumns  0x02 /* OP_ResultRow called with zero columns */
138141#define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
138142#define PragFlg_ReadOnly   0x08 /* Read-only HEADER_VALUE */
138143#define PragFlg_Result0    0x10 /* Acts as query when no argument */
138144#define PragFlg_Result1    0x20 /* Acts as query when has one argument */
138145#define PragFlg_SchemaOpt  0x40 /* Schema restricts name search if present */
138146#define PragFlg_SchemaReq  0x80 /* Schema required - "main" is default */
138147
138148/* Names of columns for pragmas that return multi-column result
138149** or that return single-column results where the name of the
138150** result column is different from the name of the pragma
138151*/
138152static const char *const pragCName[] = {
138153  /*   0 */ "id",          /* Used by: foreign_key_list */
138154  /*   1 */ "seq",
138155  /*   2 */ "table",
138156  /*   3 */ "from",
138157  /*   4 */ "to",
138158  /*   5 */ "on_update",
138159  /*   6 */ "on_delete",
138160  /*   7 */ "match",
138161  /*   8 */ "cid",         /* Used by: table_xinfo */
138162  /*   9 */ "name",
138163  /*  10 */ "type",
138164  /*  11 */ "notnull",
138165  /*  12 */ "dflt_value",
138166  /*  13 */ "pk",
138167  /*  14 */ "hidden",
138168                           /* table_info reuses 8 */
138169  /*  15 */ "schema",      /* Used by: table_list */
138170  /*  16 */ "name",
138171  /*  17 */ "type",
138172  /*  18 */ "ncol",
138173  /*  19 */ "wr",
138174  /*  20 */ "strict",
138175  /*  21 */ "seqno",       /* Used by: index_xinfo */
138176  /*  22 */ "cid",
138177  /*  23 */ "name",
138178  /*  24 */ "desc",
138179  /*  25 */ "coll",
138180  /*  26 */ "key",
138181  /*  27 */ "name",        /* Used by: function_list */
138182  /*  28 */ "builtin",
138183  /*  29 */ "type",
138184  /*  30 */ "enc",
138185  /*  31 */ "narg",
138186  /*  32 */ "flags",
138187  /*  33 */ "tbl",         /* Used by: stats */
138188  /*  34 */ "idx",
138189  /*  35 */ "wdth",
138190  /*  36 */ "hght",
138191  /*  37 */ "flgs",
138192  /*  38 */ "seq",         /* Used by: index_list */
138193  /*  39 */ "name",
138194  /*  40 */ "unique",
138195  /*  41 */ "origin",
138196  /*  42 */ "partial",
138197  /*  43 */ "table",       /* Used by: foreign_key_check */
138198  /*  44 */ "rowid",
138199  /*  45 */ "parent",
138200  /*  46 */ "fkid",
138201                           /* index_info reuses 21 */
138202  /*  47 */ "seq",         /* Used by: database_list */
138203  /*  48 */ "name",
138204  /*  49 */ "file",
138205  /*  50 */ "busy",        /* Used by: wal_checkpoint */
138206  /*  51 */ "log",
138207  /*  52 */ "checkpointed",
138208                           /* collation_list reuses 38 */
138209  /*  53 */ "database",    /* Used by: lock_status */
138210  /*  54 */ "status",
138211  /*  55 */ "cache_size",  /* Used by: default_cache_size */
138212                           /* module_list pragma_list reuses 9 */
138213  /*  56 */ "timeout",     /* Used by: busy_timeout */
138214};
138215
138216/* Definitions of all built-in pragmas */
138217typedef struct PragmaName {
138218  const char *const zName; /* Name of pragma */
138219  u8 ePragTyp;             /* PragTyp_XXX value */
138220  u8 mPragFlg;             /* Zero or more PragFlg_XXX values */
138221  u8 iPragCName;           /* Start of column names in pragCName[] */
138222  u8 nPragCName;           /* Num of col names. 0 means use pragma name */
138223  u64 iArg;                /* Extra argument */
138224} PragmaName;
138225static const PragmaName aPragmaName[] = {
138226#if defined(SQLITE_ENABLE_CEROD)
138227 {/* zName:     */ "activate_extensions",
138228  /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
138229  /* ePragFlg:  */ 0,
138230  /* ColNames:  */ 0, 0,
138231  /* iArg:      */ 0 },
138232#endif
138233 {/* zName:     */ "analysis_limit",
138234  /* ePragTyp:  */ PragTyp_ANALYSIS_LIMIT,
138235  /* ePragFlg:  */ PragFlg_Result0,
138236  /* ColNames:  */ 0, 0,
138237  /* iArg:      */ 0 },
138238#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
138239 {/* zName:     */ "application_id",
138240  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
138241  /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
138242  /* ColNames:  */ 0, 0,
138243  /* iArg:      */ BTREE_APPLICATION_ID },
138244#endif
138245#if !defined(SQLITE_OMIT_AUTOVACUUM)
138246 {/* zName:     */ "auto_vacuum",
138247  /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
138248  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
138249  /* ColNames:  */ 0, 0,
138250  /* iArg:      */ 0 },
138251#endif
138252#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138253#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
138254 {/* zName:     */ "automatic_index",
138255  /* ePragTyp:  */ PragTyp_FLAG,
138256  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138257  /* ColNames:  */ 0, 0,
138258  /* iArg:      */ SQLITE_AutoIndex },
138259#endif
138260#endif
138261 {/* zName:     */ "busy_timeout",
138262  /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
138263  /* ePragFlg:  */ PragFlg_Result0,
138264  /* ColNames:  */ 56, 1,
138265  /* iArg:      */ 0 },
138266#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
138267 {/* zName:     */ "cache_size",
138268  /* ePragTyp:  */ PragTyp_CACHE_SIZE,
138269  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
138270  /* ColNames:  */ 0, 0,
138271  /* iArg:      */ 0 },
138272#endif
138273#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138274 {/* zName:     */ "cache_spill",
138275  /* ePragTyp:  */ PragTyp_CACHE_SPILL,
138276  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
138277  /* ColNames:  */ 0, 0,
138278  /* iArg:      */ 0 },
138279#endif
138280#if !defined(SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA)
138281 {/* zName:     */ "case_sensitive_like",
138282  /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
138283  /* ePragFlg:  */ PragFlg_NoColumns,
138284  /* ColNames:  */ 0, 0,
138285  /* iArg:      */ 0 },
138286#endif
138287 {/* zName:     */ "cell_size_check",
138288  /* ePragTyp:  */ PragTyp_FLAG,
138289  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138290  /* ColNames:  */ 0, 0,
138291  /* iArg:      */ SQLITE_CellSizeCk },
138292#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138293 {/* zName:     */ "checkpoint_fullfsync",
138294  /* ePragTyp:  */ PragTyp_FLAG,
138295  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138296  /* ColNames:  */ 0, 0,
138297  /* iArg:      */ SQLITE_CkptFullFSync },
138298#endif
138299#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
138300 {/* zName:     */ "collation_list",
138301  /* ePragTyp:  */ PragTyp_COLLATION_LIST,
138302  /* ePragFlg:  */ PragFlg_Result0,
138303  /* ColNames:  */ 38, 2,
138304  /* iArg:      */ 0 },
138305#endif
138306#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
138307 {/* zName:     */ "compile_options",
138308  /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
138309  /* ePragFlg:  */ PragFlg_Result0,
138310  /* ColNames:  */ 0, 0,
138311  /* iArg:      */ 0 },
138312#endif
138313#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138314 {/* zName:     */ "count_changes",
138315  /* ePragTyp:  */ PragTyp_FLAG,
138316  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138317  /* ColNames:  */ 0, 0,
138318  /* iArg:      */ SQLITE_CountRows },
138319#endif
138320#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
138321 {/* zName:     */ "data_store_directory",
138322  /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
138323  /* ePragFlg:  */ PragFlg_NoColumns1,
138324  /* ColNames:  */ 0, 0,
138325  /* iArg:      */ 0 },
138326#endif
138327#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
138328 {/* zName:     */ "data_version",
138329  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
138330  /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,
138331  /* ColNames:  */ 0, 0,
138332  /* iArg:      */ BTREE_DATA_VERSION },
138333#endif
138334#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
138335 {/* zName:     */ "database_list",
138336  /* ePragTyp:  */ PragTyp_DATABASE_LIST,
138337  /* ePragFlg:  */ PragFlg_Result0,
138338  /* ColNames:  */ 47, 3,
138339  /* iArg:      */ 0 },
138340#endif
138341#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
138342 {/* zName:     */ "default_cache_size",
138343  /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
138344  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
138345  /* ColNames:  */ 55, 1,
138346  /* iArg:      */ 0 },
138347#endif
138348#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138349#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
138350 {/* zName:     */ "defer_foreign_keys",
138351  /* ePragTyp:  */ PragTyp_FLAG,
138352  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138353  /* ColNames:  */ 0, 0,
138354  /* iArg:      */ SQLITE_DeferFKs },
138355#endif
138356#endif
138357#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138358 {/* zName:     */ "empty_result_callbacks",
138359  /* ePragTyp:  */ PragTyp_FLAG,
138360  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138361  /* ColNames:  */ 0, 0,
138362  /* iArg:      */ SQLITE_NullCallback },
138363#endif
138364#if !defined(SQLITE_OMIT_UTF16)
138365 {/* zName:     */ "encoding",
138366  /* ePragTyp:  */ PragTyp_ENCODING,
138367  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138368  /* ColNames:  */ 0, 0,
138369  /* iArg:      */ 0 },
138370#endif
138371#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
138372 {/* zName:     */ "foreign_key_check",
138373  /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
138374  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1|PragFlg_SchemaOpt,
138375  /* ColNames:  */ 43, 4,
138376  /* iArg:      */ 0 },
138377#endif
138378#if !defined(SQLITE_OMIT_FOREIGN_KEY)
138379 {/* zName:     */ "foreign_key_list",
138380  /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
138381  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
138382  /* ColNames:  */ 0, 8,
138383  /* iArg:      */ 0 },
138384#endif
138385#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138386#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
138387 {/* zName:     */ "foreign_keys",
138388  /* ePragTyp:  */ PragTyp_FLAG,
138389  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138390  /* ColNames:  */ 0, 0,
138391  /* iArg:      */ SQLITE_ForeignKeys },
138392#endif
138393#endif
138394#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
138395 {/* zName:     */ "freelist_count",
138396  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
138397  /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,
138398  /* ColNames:  */ 0, 0,
138399  /* iArg:      */ BTREE_FREE_PAGE_COUNT },
138400#endif
138401#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138402 {/* zName:     */ "full_column_names",
138403  /* ePragTyp:  */ PragTyp_FLAG,
138404  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138405  /* ColNames:  */ 0, 0,
138406  /* iArg:      */ SQLITE_FullColNames },
138407 {/* zName:     */ "fullfsync",
138408  /* ePragTyp:  */ PragTyp_FLAG,
138409  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138410  /* ColNames:  */ 0, 0,
138411  /* iArg:      */ SQLITE_FullFSync },
138412#endif
138413#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
138414#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
138415 {/* zName:     */ "function_list",
138416  /* ePragTyp:  */ PragTyp_FUNCTION_LIST,
138417  /* ePragFlg:  */ PragFlg_Result0,
138418  /* ColNames:  */ 27, 6,
138419  /* iArg:      */ 0 },
138420#endif
138421#endif
138422 {/* zName:     */ "hard_heap_limit",
138423  /* ePragTyp:  */ PragTyp_HARD_HEAP_LIMIT,
138424  /* ePragFlg:  */ PragFlg_Result0,
138425  /* ColNames:  */ 0, 0,
138426  /* iArg:      */ 0 },
138427#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138428#if !defined(SQLITE_OMIT_CHECK)
138429 {/* zName:     */ "ignore_check_constraints",
138430  /* ePragTyp:  */ PragTyp_FLAG,
138431  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138432  /* ColNames:  */ 0, 0,
138433  /* iArg:      */ SQLITE_IgnoreChecks },
138434#endif
138435#endif
138436#if !defined(SQLITE_OMIT_AUTOVACUUM)
138437 {/* zName:     */ "incremental_vacuum",
138438  /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
138439  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_NoColumns,
138440  /* ColNames:  */ 0, 0,
138441  /* iArg:      */ 0 },
138442#endif
138443#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
138444 {/* zName:     */ "index_info",
138445  /* ePragTyp:  */ PragTyp_INDEX_INFO,
138446  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
138447  /* ColNames:  */ 21, 3,
138448  /* iArg:      */ 0 },
138449 {/* zName:     */ "index_list",
138450  /* ePragTyp:  */ PragTyp_INDEX_LIST,
138451  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
138452  /* ColNames:  */ 38, 5,
138453  /* iArg:      */ 0 },
138454 {/* zName:     */ "index_xinfo",
138455  /* ePragTyp:  */ PragTyp_INDEX_INFO,
138456  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
138457  /* ColNames:  */ 21, 6,
138458  /* iArg:      */ 1 },
138459#endif
138460#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
138461 {/* zName:     */ "integrity_check",
138462  /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
138463  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1|PragFlg_SchemaOpt,
138464  /* ColNames:  */ 0, 0,
138465  /* iArg:      */ 0 },
138466#endif
138467#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
138468 {/* zName:     */ "journal_mode",
138469  /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
138470  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
138471  /* ColNames:  */ 0, 0,
138472  /* iArg:      */ 0 },
138473 {/* zName:     */ "journal_size_limit",
138474  /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
138475  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,
138476  /* ColNames:  */ 0, 0,
138477  /* iArg:      */ 0 },
138478#endif
138479#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138480 {/* zName:     */ "legacy_alter_table",
138481  /* ePragTyp:  */ PragTyp_FLAG,
138482  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138483  /* ColNames:  */ 0, 0,
138484  /* iArg:      */ SQLITE_LegacyAlter },
138485#endif
138486#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
138487 {/* zName:     */ "lock_proxy_file",
138488  /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
138489  /* ePragFlg:  */ PragFlg_NoColumns1,
138490  /* ColNames:  */ 0, 0,
138491  /* iArg:      */ 0 },
138492#endif
138493#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
138494 {/* zName:     */ "lock_status",
138495  /* ePragTyp:  */ PragTyp_LOCK_STATUS,
138496  /* ePragFlg:  */ PragFlg_Result0,
138497  /* ColNames:  */ 53, 2,
138498  /* iArg:      */ 0 },
138499#endif
138500#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
138501 {/* zName:     */ "locking_mode",
138502  /* ePragTyp:  */ PragTyp_LOCKING_MODE,
138503  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,
138504  /* ColNames:  */ 0, 0,
138505  /* iArg:      */ 0 },
138506 {/* zName:     */ "max_page_count",
138507  /* ePragTyp:  */ PragTyp_PAGE_COUNT,
138508  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
138509  /* ColNames:  */ 0, 0,
138510  /* iArg:      */ 0 },
138511 {/* zName:     */ "mmap_size",
138512  /* ePragTyp:  */ PragTyp_MMAP_SIZE,
138513  /* ePragFlg:  */ 0,
138514  /* ColNames:  */ 0, 0,
138515  /* iArg:      */ 0 },
138516#endif
138517#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
138518#if !defined(SQLITE_OMIT_VIRTUALTABLE)
138519#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
138520 {/* zName:     */ "module_list",
138521  /* ePragTyp:  */ PragTyp_MODULE_LIST,
138522  /* ePragFlg:  */ PragFlg_Result0,
138523  /* ColNames:  */ 9, 1,
138524  /* iArg:      */ 0 },
138525#endif
138526#endif
138527#endif
138528 {/* zName:     */ "optimize",
138529  /* ePragTyp:  */ PragTyp_OPTIMIZE,
138530  /* ePragFlg:  */ PragFlg_Result1|PragFlg_NeedSchema,
138531  /* ColNames:  */ 0, 0,
138532  /* iArg:      */ 0 },
138533#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
138534 {/* zName:     */ "page_count",
138535  /* ePragTyp:  */ PragTyp_PAGE_COUNT,
138536  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
138537  /* ColNames:  */ 0, 0,
138538  /* iArg:      */ 0 },
138539 {/* zName:     */ "page_size",
138540  /* ePragTyp:  */ PragTyp_PAGE_SIZE,
138541  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
138542  /* ColNames:  */ 0, 0,
138543  /* iArg:      */ 0 },
138544#endif
138545#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138546#if defined(SQLITE_DEBUG)
138547 {/* zName:     */ "parser_trace",
138548  /* ePragTyp:  */ PragTyp_FLAG,
138549  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138550  /* ColNames:  */ 0, 0,
138551  /* iArg:      */ SQLITE_ParserTrace },
138552#endif
138553#endif
138554#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
138555 {/* zName:     */ "pragma_list",
138556  /* ePragTyp:  */ PragTyp_PRAGMA_LIST,
138557  /* ePragFlg:  */ PragFlg_Result0,
138558  /* ColNames:  */ 9, 1,
138559  /* iArg:      */ 0 },
138560#endif
138561#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138562 {/* zName:     */ "query_only",
138563  /* ePragTyp:  */ PragTyp_FLAG,
138564  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138565  /* ColNames:  */ 0, 0,
138566  /* iArg:      */ SQLITE_QueryOnly },
138567#endif
138568#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
138569 {/* zName:     */ "quick_check",
138570  /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
138571  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1|PragFlg_SchemaOpt,
138572  /* ColNames:  */ 0, 0,
138573  /* iArg:      */ 0 },
138574#endif
138575#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138576 {/* zName:     */ "read_uncommitted",
138577  /* ePragTyp:  */ PragTyp_FLAG,
138578  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138579  /* ColNames:  */ 0, 0,
138580  /* iArg:      */ SQLITE_ReadUncommit },
138581 {/* zName:     */ "recursive_triggers",
138582  /* ePragTyp:  */ PragTyp_FLAG,
138583  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138584  /* ColNames:  */ 0, 0,
138585  /* iArg:      */ SQLITE_RecTriggers },
138586 {/* zName:     */ "reverse_unordered_selects",
138587  /* ePragTyp:  */ PragTyp_FLAG,
138588  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138589  /* ColNames:  */ 0, 0,
138590  /* iArg:      */ SQLITE_ReverseOrder },
138591#endif
138592#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
138593 {/* zName:     */ "schema_version",
138594  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
138595  /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
138596  /* ColNames:  */ 0, 0,
138597  /* iArg:      */ BTREE_SCHEMA_VERSION },
138598#endif
138599#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
138600 {/* zName:     */ "secure_delete",
138601  /* ePragTyp:  */ PragTyp_SECURE_DELETE,
138602  /* ePragFlg:  */ PragFlg_Result0,
138603  /* ColNames:  */ 0, 0,
138604  /* iArg:      */ 0 },
138605#endif
138606#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138607 {/* zName:     */ "short_column_names",
138608  /* ePragTyp:  */ PragTyp_FLAG,
138609  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138610  /* ColNames:  */ 0, 0,
138611  /* iArg:      */ SQLITE_ShortColNames },
138612#endif
138613 {/* zName:     */ "shrink_memory",
138614  /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
138615  /* ePragFlg:  */ PragFlg_NoColumns,
138616  /* ColNames:  */ 0, 0,
138617  /* iArg:      */ 0 },
138618 {/* zName:     */ "soft_heap_limit",
138619  /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
138620  /* ePragFlg:  */ PragFlg_Result0,
138621  /* ColNames:  */ 0, 0,
138622  /* iArg:      */ 0 },
138623#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138624#if defined(SQLITE_DEBUG)
138625 {/* zName:     */ "sql_trace",
138626  /* ePragTyp:  */ PragTyp_FLAG,
138627  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138628  /* ColNames:  */ 0, 0,
138629  /* iArg:      */ SQLITE_SqlTrace },
138630#endif
138631#endif
138632#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
138633 {/* zName:     */ "stats",
138634  /* ePragTyp:  */ PragTyp_STATS,
138635  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
138636  /* ColNames:  */ 33, 5,
138637  /* iArg:      */ 0 },
138638#endif
138639#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
138640 {/* zName:     */ "synchronous",
138641  /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
138642  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
138643  /* ColNames:  */ 0, 0,
138644  /* iArg:      */ 0 },
138645#endif
138646#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
138647 {/* zName:     */ "table_info",
138648  /* ePragTyp:  */ PragTyp_TABLE_INFO,
138649  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
138650  /* ColNames:  */ 8, 6,
138651  /* iArg:      */ 0 },
138652 {/* zName:     */ "table_list",
138653  /* ePragTyp:  */ PragTyp_TABLE_LIST,
138654  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1,
138655  /* ColNames:  */ 15, 6,
138656  /* iArg:      */ 0 },
138657 {/* zName:     */ "table_xinfo",
138658  /* ePragTyp:  */ PragTyp_TABLE_INFO,
138659  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
138660  /* ColNames:  */ 8, 7,
138661  /* iArg:      */ 1 },
138662#endif
138663#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
138664 {/* zName:     */ "temp_store",
138665  /* ePragTyp:  */ PragTyp_TEMP_STORE,
138666  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138667  /* ColNames:  */ 0, 0,
138668  /* iArg:      */ 0 },
138669 {/* zName:     */ "temp_store_directory",
138670  /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
138671  /* ePragFlg:  */ PragFlg_NoColumns1,
138672  /* ColNames:  */ 0, 0,
138673  /* iArg:      */ 0 },
138674#endif
138675 {/* zName:     */ "threads",
138676  /* ePragTyp:  */ PragTyp_THREADS,
138677  /* ePragFlg:  */ PragFlg_Result0,
138678  /* ColNames:  */ 0, 0,
138679  /* iArg:      */ 0 },
138680#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138681 {/* zName:     */ "trusted_schema",
138682  /* ePragTyp:  */ PragTyp_FLAG,
138683  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138684  /* ColNames:  */ 0, 0,
138685  /* iArg:      */ SQLITE_TrustedSchema },
138686#endif
138687#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
138688 {/* zName:     */ "user_version",
138689  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
138690  /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
138691  /* ColNames:  */ 0, 0,
138692  /* iArg:      */ BTREE_USER_VERSION },
138693#endif
138694#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138695#if defined(SQLITE_DEBUG)
138696 {/* zName:     */ "vdbe_addoptrace",
138697  /* ePragTyp:  */ PragTyp_FLAG,
138698  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138699  /* ColNames:  */ 0, 0,
138700  /* iArg:      */ SQLITE_VdbeAddopTrace },
138701 {/* zName:     */ "vdbe_debug",
138702  /* ePragTyp:  */ PragTyp_FLAG,
138703  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138704  /* ColNames:  */ 0, 0,
138705  /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
138706 {/* zName:     */ "vdbe_eqp",
138707  /* ePragTyp:  */ PragTyp_FLAG,
138708  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138709  /* ColNames:  */ 0, 0,
138710  /* iArg:      */ SQLITE_VdbeEQP },
138711 {/* zName:     */ "vdbe_listing",
138712  /* ePragTyp:  */ PragTyp_FLAG,
138713  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138714  /* ColNames:  */ 0, 0,
138715  /* iArg:      */ SQLITE_VdbeListing },
138716 {/* zName:     */ "vdbe_trace",
138717  /* ePragTyp:  */ PragTyp_FLAG,
138718  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138719  /* ColNames:  */ 0, 0,
138720  /* iArg:      */ SQLITE_VdbeTrace },
138721#endif
138722#endif
138723#if !defined(SQLITE_OMIT_WAL)
138724 {/* zName:     */ "wal_autocheckpoint",
138725  /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
138726  /* ePragFlg:  */ 0,
138727  /* ColNames:  */ 0, 0,
138728  /* iArg:      */ 0 },
138729 {/* zName:     */ "wal_checkpoint",
138730  /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
138731  /* ePragFlg:  */ PragFlg_NeedSchema,
138732  /* ColNames:  */ 50, 3,
138733  /* iArg:      */ 0 },
138734#endif
138735#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
138736 {/* zName:     */ "writable_schema",
138737  /* ePragTyp:  */ PragTyp_FLAG,
138738  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
138739  /* ColNames:  */ 0, 0,
138740  /* iArg:      */ SQLITE_WriteSchema|SQLITE_NoSchemaError },
138741#endif
138742};
138743/* Number of pragmas: 68 on by default, 78 total. */
138744
138745/************** End of pragma.h **********************************************/
138746/************** Continuing where we left off in pragma.c *********************/
138747
138748/*
138749** When the 0x10 bit of PRAGMA optimize is set, any ANALYZE commands
138750** will be run with an analysis_limit set to the lessor of the value of
138751** the following macro or to the actual analysis_limit if it is non-zero,
138752** in order to prevent PRAGMA optimize from running for too long.
138753**
138754** The value of 2000 is chosen emperically so that the worst-case run-time
138755** for PRAGMA optimize does not exceed 100 milliseconds against a variety
138756** of test databases on a RaspberryPI-4 compiled using -Os and without
138757** -DSQLITE_DEBUG.  Of course, your mileage may vary.  For the purpose of
138758** this paragraph, "worst-case" means that ANALYZE ends up being
138759** run on every table in the database.  The worst case typically only
138760** happens if PRAGMA optimize is run on a database file for which ANALYZE
138761** has not been previously run and the 0x10000 flag is included so that
138762** all tables are analyzed.  The usual case for PRAGMA optimize is that
138763** no ANALYZE commands will be run at all, or if any ANALYZE happens it
138764** will be against a single table, so that expected timing for PRAGMA
138765** optimize on a PI-4 is more like 1 millisecond or less with the 0x10000
138766** flag or less than 100 microseconds without the 0x10000 flag.
138767**
138768** An analysis limit of 2000 is almost always sufficient for the query
138769** planner to fully characterize an index.  The additional accuracy from
138770** a larger analysis is not usually helpful.
138771*/
138772#ifndef SQLITE_DEFAULT_OPTIMIZE_LIMIT
138773# define SQLITE_DEFAULT_OPTIMIZE_LIMIT 2000
138774#endif
138775
138776/*
138777** Interpret the given string as a safety level.  Return 0 for OFF,
138778** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or
138779** unrecognized string argument.  The FULL and EXTRA option is disallowed
138780** if the omitFull parameter it 1.
138781**
138782** Note that the values returned are one less that the values that
138783** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
138784** to support legacy SQL code.  The safety level used to be boolean
138785** and older scripts may have used numbers 0 for OFF and 1 for ON.
138786*/
138787static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
138788                             /* 123456789 123456789 123 */
138789  static const char zText[] = "onoffalseyestruextrafull";
138790  static const u8 iOffset[] = {0, 1, 2,  4,    9,  12,  15,   20};
138791  static const u8 iLength[] = {2, 2, 3,  5,    3,   4,   5,    4};
138792  static const u8 iValue[] =  {1, 0, 0,  0,    1,   1,   3,    2};
138793                            /* on no off false yes true extra full */
138794  int i, n;
138795  if( sqlite3Isdigit(*z) ){
138796    return (u8)sqlite3Atoi(z);
138797  }
138798  n = sqlite3Strlen30(z);
138799  for(i=0; i<ArraySize(iLength); i++){
138800    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
138801     && (!omitFull || iValue[i]<=1)
138802    ){
138803      return iValue[i];
138804    }
138805  }
138806  return dflt;
138807}
138808
138809/*
138810** Interpret the given string as a boolean value.
138811*/
138812SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
138813  return getSafetyLevel(z,1,dflt)!=0;
138814}
138815
138816/* The sqlite3GetBoolean() function is used by other modules but the
138817** remainder of this file is specific to PRAGMA processing.  So omit
138818** the rest of the file if PRAGMAs are omitted from the build.
138819*/
138820#if !defined(SQLITE_OMIT_PRAGMA)
138821
138822/*
138823** Interpret the given string as a locking mode value.
138824*/
138825static int getLockingMode(const char *z){
138826  if( z ){
138827    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
138828    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
138829  }
138830  return PAGER_LOCKINGMODE_QUERY;
138831}
138832
138833#ifndef SQLITE_OMIT_AUTOVACUUM
138834/*
138835** Interpret the given string as an auto-vacuum mode value.
138836**
138837** The following strings, "none", "full" and "incremental" are
138838** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
138839*/
138840static int getAutoVacuum(const char *z){
138841  int i;
138842  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
138843  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
138844  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
138845  i = sqlite3Atoi(z);
138846  return (u8)((i>=0&&i<=2)?i:0);
138847}
138848#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
138849
138850#ifndef SQLITE_OMIT_PAGER_PRAGMAS
138851/*
138852** Interpret the given string as a temp db location. Return 1 for file
138853** backed temporary databases, 2 for the Red-Black tree in memory database
138854** and 0 to use the compile-time default.
138855*/
138856static int getTempStore(const char *z){
138857  if( z[0]>='0' && z[0]<='2' ){
138858    return z[0] - '0';
138859  }else if( sqlite3StrICmp(z, "file")==0 ){
138860    return 1;
138861  }else if( sqlite3StrICmp(z, "memory")==0 ){
138862    return 2;
138863  }else{
138864    return 0;
138865  }
138866}
138867#endif /* SQLITE_PAGER_PRAGMAS */
138868
138869#ifndef SQLITE_OMIT_PAGER_PRAGMAS
138870/*
138871** Invalidate temp storage, either when the temp storage is changed
138872** from default, or when 'file' and the temp_store_directory has changed
138873*/
138874static int invalidateTempStorage(Parse *pParse){
138875  sqlite3 *db = pParse->db;
138876  if( db->aDb[1].pBt!=0 ){
138877    if( !db->autoCommit
138878     || sqlite3BtreeTxnState(db->aDb[1].pBt)!=SQLITE_TXN_NONE
138879    ){
138880      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
138881        "from within a transaction");
138882      return SQLITE_ERROR;
138883    }
138884    sqlite3BtreeClose(db->aDb[1].pBt);
138885    db->aDb[1].pBt = 0;
138886    sqlite3ResetAllSchemasOfConnection(db);
138887  }
138888  return SQLITE_OK;
138889}
138890#endif /* SQLITE_PAGER_PRAGMAS */
138891
138892#ifndef SQLITE_OMIT_PAGER_PRAGMAS
138893/*
138894** If the TEMP database is open, close it and mark the database schema
138895** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
138896** or DEFAULT_TEMP_STORE pragmas.
138897*/
138898static int changeTempStorage(Parse *pParse, const char *zStorageType){
138899  int ts = getTempStore(zStorageType);
138900  sqlite3 *db = pParse->db;
138901  if( db->temp_store==ts ) return SQLITE_OK;
138902  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
138903    return SQLITE_ERROR;
138904  }
138905  db->temp_store = (u8)ts;
138906  return SQLITE_OK;
138907}
138908#endif /* SQLITE_PAGER_PRAGMAS */
138909
138910/*
138911** Set result column names for a pragma.
138912*/
138913static void setPragmaResultColumnNames(
138914  Vdbe *v,                     /* The query under construction */
138915  const PragmaName *pPragma    /* The pragma */
138916){
138917  u8 n = pPragma->nPragCName;
138918  sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
138919  if( n==0 ){
138920    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
138921  }else{
138922    int i, j;
138923    for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
138924      sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
138925    }
138926  }
138927}
138928
138929/*
138930** Generate code to return a single integer value.
138931*/
138932static void returnSingleInt(Vdbe *v, i64 value){
138933  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
138934  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
138935}
138936
138937/*
138938** Generate code to return a single text value.
138939*/
138940static void returnSingleText(
138941  Vdbe *v,                /* Prepared statement under construction */
138942  const char *zValue      /* Value to be returned */
138943){
138944  if( zValue ){
138945    sqlite3VdbeLoadString(v, 1, (const char*)zValue);
138946    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
138947  }
138948}
138949
138950
138951/*
138952** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
138953** set these values for all pagers.
138954*/
138955#ifndef SQLITE_OMIT_PAGER_PRAGMAS
138956static void setAllPagerFlags(sqlite3 *db){
138957  if( db->autoCommit ){
138958    Db *pDb = db->aDb;
138959    int n = db->nDb;
138960    assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
138961    assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
138962    assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
138963    assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
138964             ==  PAGER_FLAGS_MASK );
138965    assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
138966    while( (n--) > 0 ){
138967      if( pDb->pBt ){
138968        sqlite3BtreeSetPagerFlags(pDb->pBt,
138969                 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
138970      }
138971      pDb++;
138972    }
138973  }
138974}
138975#else
138976# define setAllPagerFlags(X)  /* no-op */
138977#endif
138978
138979
138980/*
138981** Return a human-readable name for a constraint resolution action.
138982*/
138983#ifndef SQLITE_OMIT_FOREIGN_KEY
138984static const char *actionName(u8 action){
138985  const char *zName;
138986  switch( action ){
138987    case OE_SetNull:  zName = "SET NULL";        break;
138988    case OE_SetDflt:  zName = "SET DEFAULT";     break;
138989    case OE_Cascade:  zName = "CASCADE";         break;
138990    case OE_Restrict: zName = "RESTRICT";        break;
138991    default:          zName = "NO ACTION";
138992                      assert( action==OE_None ); break;
138993  }
138994  return zName;
138995}
138996#endif
138997
138998
138999/*
139000** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
139001** defined in pager.h. This function returns the associated lowercase
139002** journal-mode name.
139003*/
139004SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
139005  static char * const azModeName[] = {
139006    "delete", "persist", "off", "truncate", "memory"
139007#ifndef SQLITE_OMIT_WAL
139008     , "wal"
139009#endif
139010  };
139011  assert( PAGER_JOURNALMODE_DELETE==0 );
139012  assert( PAGER_JOURNALMODE_PERSIST==1 );
139013  assert( PAGER_JOURNALMODE_OFF==2 );
139014  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
139015  assert( PAGER_JOURNALMODE_MEMORY==4 );
139016  assert( PAGER_JOURNALMODE_WAL==5 );
139017  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
139018
139019  if( eMode==ArraySize(azModeName) ) return 0;
139020  return azModeName[eMode];
139021}
139022
139023/*
139024** Locate a pragma in the aPragmaName[] array.
139025*/
139026static const PragmaName *pragmaLocate(const char *zName){
139027  int upr, lwr, mid = 0, rc;
139028  lwr = 0;
139029  upr = ArraySize(aPragmaName)-1;
139030  while( lwr<=upr ){
139031    mid = (lwr+upr)/2;
139032    rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
139033    if( rc==0 ) break;
139034    if( rc<0 ){
139035      upr = mid - 1;
139036    }else{
139037      lwr = mid + 1;
139038    }
139039  }
139040  return lwr>upr ? 0 : &aPragmaName[mid];
139041}
139042
139043/*
139044** Create zero or more entries in the output for the SQL functions
139045** defined by FuncDef p.
139046*/
139047static void pragmaFunclistLine(
139048  Vdbe *v,               /* The prepared statement being created */
139049  FuncDef *p,            /* A particular function definition */
139050  int isBuiltin,         /* True if this is a built-in function */
139051  int showInternFuncs    /* True if showing internal functions */
139052){
139053  u32 mask =
139054      SQLITE_DETERMINISTIC |
139055      SQLITE_DIRECTONLY |
139056      SQLITE_SUBTYPE |
139057      SQLITE_INNOCUOUS |
139058      SQLITE_FUNC_INTERNAL
139059  ;
139060  if( showInternFuncs ) mask = 0xffffffff;
139061  for(; p; p=p->pNext){
139062    const char *zType;
139063    static const char *azEnc[] = { 0, "utf8", "utf16le", "utf16be" };
139064
139065    assert( SQLITE_FUNC_ENCMASK==0x3 );
139066    assert( strcmp(azEnc[SQLITE_UTF8],"utf8")==0 );
139067    assert( strcmp(azEnc[SQLITE_UTF16LE],"utf16le")==0 );
139068    assert( strcmp(azEnc[SQLITE_UTF16BE],"utf16be")==0 );
139069
139070    if( p->xSFunc==0 ) continue;
139071    if( (p->funcFlags & SQLITE_FUNC_INTERNAL)!=0
139072     && showInternFuncs==0
139073    ){
139074      continue;
139075    }
139076    if( p->xValue!=0 ){
139077      zType = "w";
139078    }else if( p->xFinalize!=0 ){
139079      zType = "a";
139080    }else{
139081      zType = "s";
139082    }
139083    sqlite3VdbeMultiLoad(v, 1, "sissii",
139084       p->zName, isBuiltin,
139085       zType, azEnc[p->funcFlags&SQLITE_FUNC_ENCMASK],
139086       p->nArg,
139087       (p->funcFlags & mask) ^ SQLITE_INNOCUOUS
139088    );
139089  }
139090}
139091
139092
139093/*
139094** Helper subroutine for PRAGMA integrity_check:
139095**
139096** Generate code to output a single-column result row with a value of the
139097** string held in register 3.  Decrement the result count in register 1
139098** and halt if the maximum number of result rows have been issued.
139099*/
139100static int integrityCheckResultRow(Vdbe *v){
139101  int addr;
139102  sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
139103  addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
139104  VdbeCoverage(v);
139105  sqlite3VdbeAddOp0(v, OP_Halt);
139106  return addr;
139107}
139108
139109/*
139110** Process a pragma statement.
139111**
139112** Pragmas are of this form:
139113**
139114**      PRAGMA [schema.]id [= value]
139115**
139116** The identifier might also be a string.  The value is a string, and
139117** identifier, or a number.  If minusFlag is true, then the value is
139118** a number that was preceded by a minus sign.
139119**
139120** If the left side is "database.id" then pId1 is the database name
139121** and pId2 is the id.  If the left side is just "id" then pId1 is the
139122** id and pId2 is any empty string.
139123*/
139124SQLITE_PRIVATE void sqlite3Pragma(
139125  Parse *pParse,
139126  Token *pId1,        /* First part of [schema.]id field */
139127  Token *pId2,        /* Second part of [schema.]id field, or NULL */
139128  Token *pValue,      /* Token for <value>, or NULL */
139129  int minusFlag       /* True if a '-' sign preceded <value> */
139130){
139131  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
139132  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
139133  const char *zDb = 0;   /* The database name */
139134  Token *pId;            /* Pointer to <id> token */
139135  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
139136  int iDb;               /* Database index for <database> */
139137  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
139138  sqlite3 *db = pParse->db;    /* The database connection */
139139  Db *pDb;                     /* The specific database being pragmaed */
139140  Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
139141  const PragmaName *pPragma;   /* The pragma */
139142
139143  if( v==0 ) return;
139144  sqlite3VdbeRunOnlyOnce(v);
139145  pParse->nMem = 2;
139146
139147  /* Interpret the [schema.] part of the pragma statement. iDb is the
139148  ** index of the database this pragma is being applied to in db.aDb[]. */
139149  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
139150  if( iDb<0 ) return;
139151  pDb = &db->aDb[iDb];
139152
139153  /* If the temp database has been explicitly named as part of the
139154  ** pragma, make sure it is open.
139155  */
139156  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
139157    return;
139158  }
139159
139160  zLeft = sqlite3NameFromToken(db, pId);
139161  if( !zLeft ) return;
139162  if( minusFlag ){
139163    zRight = sqlite3MPrintf(db, "-%T", pValue);
139164  }else{
139165    zRight = sqlite3NameFromToken(db, pValue);
139166  }
139167
139168  assert( pId2 );
139169  zDb = pId2->n>0 ? pDb->zDbSName : 0;
139170  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
139171    goto pragma_out;
139172  }
139173
139174  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
139175  ** connection.  If it returns SQLITE_OK, then assume that the VFS
139176  ** handled the pragma and generate a no-op prepared statement.
139177  **
139178  ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
139179  ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
139180  ** object corresponding to the database file to which the pragma
139181  ** statement refers.
139182  **
139183  ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
139184  ** file control is an array of pointers to strings (char**) in which the
139185  ** second element of the array is the name of the pragma and the third
139186  ** element is the argument to the pragma or NULL if the pragma has no
139187  ** argument.
139188  */
139189  aFcntl[0] = 0;
139190  aFcntl[1] = zLeft;
139191  aFcntl[2] = zRight;
139192  aFcntl[3] = 0;
139193  db->busyHandler.nBusy = 0;
139194  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
139195  if( rc==SQLITE_OK ){
139196    sqlite3VdbeSetNumCols(v, 1);
139197    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
139198    returnSingleText(v, aFcntl[0]);
139199    sqlite3_free(aFcntl[0]);
139200    goto pragma_out;
139201  }
139202  if( rc!=SQLITE_NOTFOUND ){
139203    if( aFcntl[0] ){
139204      sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
139205      sqlite3_free(aFcntl[0]);
139206    }
139207    pParse->nErr++;
139208    pParse->rc = rc;
139209    goto pragma_out;
139210  }
139211
139212  /* Locate the pragma in the lookup table */
139213  pPragma = pragmaLocate(zLeft);
139214  if( pPragma==0 ){
139215    /* IMP: R-43042-22504 No error messages are generated if an
139216    ** unknown pragma is issued. */
139217    goto pragma_out;
139218  }
139219
139220  /* Make sure the database schema is loaded if the pragma requires that */
139221  if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
139222    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
139223  }
139224
139225  /* Register the result column names for pragmas that return results */
139226  if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
139227   && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
139228  ){
139229    setPragmaResultColumnNames(v, pPragma);
139230  }
139231
139232  /* Jump to the appropriate pragma handler */
139233  switch( pPragma->ePragTyp ){
139234
139235#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
139236  /*
139237  **  PRAGMA [schema.]default_cache_size
139238  **  PRAGMA [schema.]default_cache_size=N
139239  **
139240  ** The first form reports the current persistent setting for the
139241  ** page cache size.  The value returned is the maximum number of
139242  ** pages in the page cache.  The second form sets both the current
139243  ** page cache size value and the persistent page cache size value
139244  ** stored in the database file.
139245  **
139246  ** Older versions of SQLite would set the default cache size to a
139247  ** negative number to indicate synchronous=OFF.  These days, synchronous
139248  ** is always on by default regardless of the sign of the default cache
139249  ** size.  But continue to take the absolute value of the default cache
139250  ** size of historical compatibility.
139251  */
139252  case PragTyp_DEFAULT_CACHE_SIZE: {
139253    static const int iLn = VDBE_OFFSET_LINENO(2);
139254    static const VdbeOpList getCacheSize[] = {
139255      { OP_Transaction, 0, 0,        0},                         /* 0 */
139256      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
139257      { OP_IfPos,       1, 8,        0},
139258      { OP_Integer,     0, 2,        0},
139259      { OP_Subtract,    1, 2,        1},
139260      { OP_IfPos,       1, 8,        0},
139261      { OP_Integer,     0, 1,        0},                         /* 6 */
139262      { OP_Noop,        0, 0,        0},
139263      { OP_ResultRow,   1, 1,        0},
139264    };
139265    VdbeOp *aOp;
139266    sqlite3VdbeUsesBtree(v, iDb);
139267    if( !zRight ){
139268      pParse->nMem += 2;
139269      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
139270      aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
139271      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
139272      aOp[0].p1 = iDb;
139273      aOp[1].p1 = iDb;
139274      aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
139275    }else{
139276      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
139277      sqlite3BeginWriteOperation(pParse, 0, iDb);
139278      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
139279      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
139280      pDb->pSchema->cache_size = size;
139281      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
139282    }
139283    break;
139284  }
139285#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
139286
139287#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
139288  /*
139289  **  PRAGMA [schema.]page_size
139290  **  PRAGMA [schema.]page_size=N
139291  **
139292  ** The first form reports the current setting for the
139293  ** database page size in bytes.  The second form sets the
139294  ** database page size value.  The value can only be set if
139295  ** the database has not yet been created.
139296  */
139297  case PragTyp_PAGE_SIZE: {
139298    Btree *pBt = pDb->pBt;
139299    assert( pBt!=0 );
139300    if( !zRight ){
139301      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
139302      returnSingleInt(v, size);
139303    }else{
139304      /* Malloc may fail when setting the page-size, as there is an internal
139305      ** buffer that the pager module resizes using sqlite3_realloc().
139306      */
139307      db->nextPagesize = sqlite3Atoi(zRight);
139308      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,0,0) ){
139309        sqlite3OomFault(db);
139310      }
139311    }
139312    break;
139313  }
139314
139315  /*
139316  **  PRAGMA [schema.]secure_delete
139317  **  PRAGMA [schema.]secure_delete=ON/OFF/FAST
139318  **
139319  ** The first form reports the current setting for the
139320  ** secure_delete flag.  The second form changes the secure_delete
139321  ** flag setting and reports the new value.
139322  */
139323  case PragTyp_SECURE_DELETE: {
139324    Btree *pBt = pDb->pBt;
139325    int b = -1;
139326    assert( pBt!=0 );
139327    if( zRight ){
139328      if( sqlite3_stricmp(zRight, "fast")==0 ){
139329        b = 2;
139330      }else{
139331        b = sqlite3GetBoolean(zRight, 0);
139332      }
139333    }
139334    if( pId2->n==0 && b>=0 ){
139335      int ii;
139336      for(ii=0; ii<db->nDb; ii++){
139337        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
139338      }
139339    }
139340    b = sqlite3BtreeSecureDelete(pBt, b);
139341    returnSingleInt(v, b);
139342    break;
139343  }
139344
139345  /*
139346  **  PRAGMA [schema.]max_page_count
139347  **  PRAGMA [schema.]max_page_count=N
139348  **
139349  ** The first form reports the current setting for the
139350  ** maximum number of pages in the database file.  The
139351  ** second form attempts to change this setting.  Both
139352  ** forms return the current setting.
139353  **
139354  ** The absolute value of N is used.  This is undocumented and might
139355  ** change.  The only purpose is to provide an easy way to test
139356  ** the sqlite3AbsInt32() function.
139357  **
139358  **  PRAGMA [schema.]page_count
139359  **
139360  ** Return the number of pages in the specified database.
139361  */
139362  case PragTyp_PAGE_COUNT: {
139363    int iReg;
139364    i64 x = 0;
139365    sqlite3CodeVerifySchema(pParse, iDb);
139366    iReg = ++pParse->nMem;
139367    if( sqlite3Tolower(zLeft[0])=='p' ){
139368      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
139369    }else{
139370      if( zRight && sqlite3DecOrHexToI64(zRight,&x)==0 ){
139371        if( x<0 ) x = 0;
139372        else if( x>0xfffffffe ) x = 0xfffffffe;
139373      }else{
139374        x = 0;
139375      }
139376      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, (int)x);
139377    }
139378    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
139379    break;
139380  }
139381
139382  /*
139383  **  PRAGMA [schema.]locking_mode
139384  **  PRAGMA [schema.]locking_mode = (normal|exclusive)
139385  */
139386  case PragTyp_LOCKING_MODE: {
139387    const char *zRet = "normal";
139388    int eMode = getLockingMode(zRight);
139389
139390    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
139391      /* Simple "PRAGMA locking_mode;" statement. This is a query for
139392      ** the current default locking mode (which may be different to
139393      ** the locking-mode of the main database).
139394      */
139395      eMode = db->dfltLockMode;
139396    }else{
139397      Pager *pPager;
139398      if( pId2->n==0 ){
139399        /* This indicates that no database name was specified as part
139400        ** of the PRAGMA command. In this case the locking-mode must be
139401        ** set on all attached databases, as well as the main db file.
139402        **
139403        ** Also, the sqlite3.dfltLockMode variable is set so that
139404        ** any subsequently attached databases also use the specified
139405        ** locking mode.
139406        */
139407        int ii;
139408        assert(pDb==&db->aDb[0]);
139409        for(ii=2; ii<db->nDb; ii++){
139410          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
139411          sqlite3PagerLockingMode(pPager, eMode);
139412        }
139413        db->dfltLockMode = (u8)eMode;
139414      }
139415      pPager = sqlite3BtreePager(pDb->pBt);
139416      eMode = sqlite3PagerLockingMode(pPager, eMode);
139417    }
139418
139419    assert( eMode==PAGER_LOCKINGMODE_NORMAL
139420            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
139421    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
139422      zRet = "exclusive";
139423    }
139424    returnSingleText(v, zRet);
139425    break;
139426  }
139427
139428  /*
139429  **  PRAGMA [schema.]journal_mode
139430  **  PRAGMA [schema.]journal_mode =
139431  **                      (delete|persist|off|truncate|memory|wal|off)
139432  */
139433  case PragTyp_JOURNAL_MODE: {
139434    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
139435    int ii;           /* Loop counter */
139436
139437    if( zRight==0 ){
139438      /* If there is no "=MODE" part of the pragma, do a query for the
139439      ** current mode */
139440      eMode = PAGER_JOURNALMODE_QUERY;
139441    }else{
139442      const char *zMode;
139443      int n = sqlite3Strlen30(zRight);
139444      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
139445        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
139446      }
139447      if( !zMode ){
139448        /* If the "=MODE" part does not match any known journal mode,
139449        ** then do a query */
139450        eMode = PAGER_JOURNALMODE_QUERY;
139451      }
139452      if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){
139453        /* Do not allow journal-mode "OFF" in defensive since the database
139454        ** can become corrupted using ordinary SQL when the journal is off */
139455        eMode = PAGER_JOURNALMODE_QUERY;
139456      }
139457    }
139458    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
139459      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
139460      iDb = 0;
139461      pId2->n = 1;
139462    }
139463    for(ii=db->nDb-1; ii>=0; ii--){
139464      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
139465        sqlite3VdbeUsesBtree(v, ii);
139466        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
139467      }
139468    }
139469    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
139470    break;
139471  }
139472
139473  /*
139474  **  PRAGMA [schema.]journal_size_limit
139475  **  PRAGMA [schema.]journal_size_limit=N
139476  **
139477  ** Get or set the size limit on rollback journal files.
139478  */
139479  case PragTyp_JOURNAL_SIZE_LIMIT: {
139480    Pager *pPager = sqlite3BtreePager(pDb->pBt);
139481    i64 iLimit = -2;
139482    if( zRight ){
139483      sqlite3DecOrHexToI64(zRight, &iLimit);
139484      if( iLimit<-1 ) iLimit = -1;
139485    }
139486    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
139487    returnSingleInt(v, iLimit);
139488    break;
139489  }
139490
139491#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
139492
139493  /*
139494  **  PRAGMA [schema.]auto_vacuum
139495  **  PRAGMA [schema.]auto_vacuum=N
139496  **
139497  ** Get or set the value of the database 'auto-vacuum' parameter.
139498  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
139499  */
139500#ifndef SQLITE_OMIT_AUTOVACUUM
139501  case PragTyp_AUTO_VACUUM: {
139502    Btree *pBt = pDb->pBt;
139503    assert( pBt!=0 );
139504    if( !zRight ){
139505      returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
139506    }else{
139507      int eAuto = getAutoVacuum(zRight);
139508      assert( eAuto>=0 && eAuto<=2 );
139509      db->nextAutovac = (u8)eAuto;
139510      /* Call SetAutoVacuum() to set initialize the internal auto and
139511      ** incr-vacuum flags. This is required in case this connection
139512      ** creates the database file. It is important that it is created
139513      ** as an auto-vacuum capable db.
139514      */
139515      rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
139516      if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
139517        /* When setting the auto_vacuum mode to either "full" or
139518        ** "incremental", write the value of meta[6] in the database
139519        ** file. Before writing to meta[6], check that meta[3] indicates
139520        ** that this really is an auto-vacuum capable database.
139521        */
139522        static const int iLn = VDBE_OFFSET_LINENO(2);
139523        static const VdbeOpList setMeta6[] = {
139524          { OP_Transaction,    0,         1,                 0},    /* 0 */
139525          { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
139526          { OP_If,             1,         0,                 0},    /* 2 */
139527          { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
139528          { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */
139529        };
139530        VdbeOp *aOp;
139531        int iAddr = sqlite3VdbeCurrentAddr(v);
139532        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
139533        aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
139534        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
139535        aOp[0].p1 = iDb;
139536        aOp[1].p1 = iDb;
139537        aOp[2].p2 = iAddr+4;
139538        aOp[4].p1 = iDb;
139539        aOp[4].p3 = eAuto - 1;
139540        sqlite3VdbeUsesBtree(v, iDb);
139541      }
139542    }
139543    break;
139544  }
139545#endif
139546
139547  /*
139548  **  PRAGMA [schema.]incremental_vacuum(N)
139549  **
139550  ** Do N steps of incremental vacuuming on a database.
139551  */
139552#ifndef SQLITE_OMIT_AUTOVACUUM
139553  case PragTyp_INCREMENTAL_VACUUM: {
139554    int iLimit = 0, addr;
139555    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
139556      iLimit = 0x7fffffff;
139557    }
139558    sqlite3BeginWriteOperation(pParse, 0, iDb);
139559    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
139560    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
139561    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
139562    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
139563    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
139564    sqlite3VdbeJumpHere(v, addr);
139565    break;
139566  }
139567#endif
139568
139569#ifndef SQLITE_OMIT_PAGER_PRAGMAS
139570  /*
139571  **  PRAGMA [schema.]cache_size
139572  **  PRAGMA [schema.]cache_size=N
139573  **
139574  ** The first form reports the current local setting for the
139575  ** page cache size. The second form sets the local
139576  ** page cache size value.  If N is positive then that is the
139577  ** number of pages in the cache.  If N is negative, then the
139578  ** number of pages is adjusted so that the cache uses -N kibibytes
139579  ** of memory.
139580  */
139581  case PragTyp_CACHE_SIZE: {
139582    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
139583    if( !zRight ){
139584      returnSingleInt(v, pDb->pSchema->cache_size);
139585    }else{
139586      int size = sqlite3Atoi(zRight);
139587      pDb->pSchema->cache_size = size;
139588      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
139589    }
139590    break;
139591  }
139592
139593  /*
139594  **  PRAGMA [schema.]cache_spill
139595  **  PRAGMA cache_spill=BOOLEAN
139596  **  PRAGMA [schema.]cache_spill=N
139597  **
139598  ** The first form reports the current local setting for the
139599  ** page cache spill size. The second form turns cache spill on
139600  ** or off.  When turning cache spill on, the size is set to the
139601  ** current cache_size.  The third form sets a spill size that
139602  ** may be different form the cache size.
139603  ** If N is positive then that is the
139604  ** number of pages in the cache.  If N is negative, then the
139605  ** number of pages is adjusted so that the cache uses -N kibibytes
139606  ** of memory.
139607  **
139608  ** If the number of cache_spill pages is less then the number of
139609  ** cache_size pages, no spilling occurs until the page count exceeds
139610  ** the number of cache_size pages.
139611  **
139612  ** The cache_spill=BOOLEAN setting applies to all attached schemas,
139613  ** not just the schema specified.
139614  */
139615  case PragTyp_CACHE_SPILL: {
139616    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
139617    if( !zRight ){
139618      returnSingleInt(v,
139619         (db->flags & SQLITE_CacheSpill)==0 ? 0 :
139620            sqlite3BtreeSetSpillSize(pDb->pBt,0));
139621    }else{
139622      int size = 1;
139623      if( sqlite3GetInt32(zRight, &size) ){
139624        sqlite3BtreeSetSpillSize(pDb->pBt, size);
139625      }
139626      if( sqlite3GetBoolean(zRight, size!=0) ){
139627        db->flags |= SQLITE_CacheSpill;
139628      }else{
139629        db->flags &= ~(u64)SQLITE_CacheSpill;
139630      }
139631      setAllPagerFlags(db);
139632    }
139633    break;
139634  }
139635
139636  /*
139637  **  PRAGMA [schema.]mmap_size(N)
139638  **
139639  ** Used to set mapping size limit. The mapping size limit is
139640  ** used to limit the aggregate size of all memory mapped regions of the
139641  ** database file. If this parameter is set to zero, then memory mapping
139642  ** is not used at all.  If N is negative, then the default memory map
139643  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
139644  ** The parameter N is measured in bytes.
139645  **
139646  ** This value is advisory.  The underlying VFS is free to memory map
139647  ** as little or as much as it wants.  Except, if N is set to 0 then the
139648  ** upper layers will never invoke the xFetch interfaces to the VFS.
139649  */
139650  case PragTyp_MMAP_SIZE: {
139651    sqlite3_int64 sz;
139652#if SQLITE_MAX_MMAP_SIZE>0
139653    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
139654    if( zRight ){
139655      int ii;
139656      sqlite3DecOrHexToI64(zRight, &sz);
139657      if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
139658      if( pId2->n==0 ) db->szMmap = sz;
139659      for(ii=db->nDb-1; ii>=0; ii--){
139660        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
139661          sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
139662        }
139663      }
139664    }
139665    sz = -1;
139666    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
139667#else
139668    sz = 0;
139669    rc = SQLITE_OK;
139670#endif
139671    if( rc==SQLITE_OK ){
139672      returnSingleInt(v, sz);
139673    }else if( rc!=SQLITE_NOTFOUND ){
139674      pParse->nErr++;
139675      pParse->rc = rc;
139676    }
139677    break;
139678  }
139679
139680  /*
139681  **   PRAGMA temp_store
139682  **   PRAGMA temp_store = "default"|"memory"|"file"
139683  **
139684  ** Return or set the local value of the temp_store flag.  Changing
139685  ** the local value does not make changes to the disk file and the default
139686  ** value will be restored the next time the database is opened.
139687  **
139688  ** Note that it is possible for the library compile-time options to
139689  ** override this setting
139690  */
139691  case PragTyp_TEMP_STORE: {
139692    if( !zRight ){
139693      returnSingleInt(v, db->temp_store);
139694    }else{
139695      changeTempStorage(pParse, zRight);
139696    }
139697    break;
139698  }
139699
139700  /*
139701  **   PRAGMA temp_store_directory
139702  **   PRAGMA temp_store_directory = ""|"directory_name"
139703  **
139704  ** Return or set the local value of the temp_store_directory flag.  Changing
139705  ** the value sets a specific directory to be used for temporary files.
139706  ** Setting to a null string reverts to the default temporary directory search.
139707  ** If temporary directory is changed, then invalidateTempStorage.
139708  **
139709  */
139710  case PragTyp_TEMP_STORE_DIRECTORY: {
139711    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
139712    if( !zRight ){
139713      returnSingleText(v, sqlite3_temp_directory);
139714    }else{
139715#ifndef SQLITE_OMIT_WSD
139716      if( zRight[0] ){
139717        int res;
139718        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
139719        if( rc!=SQLITE_OK || res==0 ){
139720          sqlite3ErrorMsg(pParse, "not a writable directory");
139721          sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
139722          goto pragma_out;
139723        }
139724      }
139725      if( SQLITE_TEMP_STORE==0
139726       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
139727       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
139728      ){
139729        invalidateTempStorage(pParse);
139730      }
139731      sqlite3_free(sqlite3_temp_directory);
139732      if( zRight[0] ){
139733        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
139734      }else{
139735        sqlite3_temp_directory = 0;
139736      }
139737#endif /* SQLITE_OMIT_WSD */
139738    }
139739    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
139740    break;
139741  }
139742
139743#if SQLITE_OS_WIN
139744  /*
139745  **   PRAGMA data_store_directory
139746  **   PRAGMA data_store_directory = ""|"directory_name"
139747  **
139748  ** Return or set the local value of the data_store_directory flag.  Changing
139749  ** the value sets a specific directory to be used for database files that
139750  ** were specified with a relative pathname.  Setting to a null string reverts
139751  ** to the default database directory, which for database files specified with
139752  ** a relative path will probably be based on the current directory for the
139753  ** process.  Database file specified with an absolute path are not impacted
139754  ** by this setting, regardless of its value.
139755  **
139756  */
139757  case PragTyp_DATA_STORE_DIRECTORY: {
139758    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
139759    if( !zRight ){
139760      returnSingleText(v, sqlite3_data_directory);
139761    }else{
139762#ifndef SQLITE_OMIT_WSD
139763      if( zRight[0] ){
139764        int res;
139765        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
139766        if( rc!=SQLITE_OK || res==0 ){
139767          sqlite3ErrorMsg(pParse, "not a writable directory");
139768          sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
139769          goto pragma_out;
139770        }
139771      }
139772      sqlite3_free(sqlite3_data_directory);
139773      if( zRight[0] ){
139774        sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
139775      }else{
139776        sqlite3_data_directory = 0;
139777      }
139778#endif /* SQLITE_OMIT_WSD */
139779    }
139780    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
139781    break;
139782  }
139783#endif
139784
139785#if SQLITE_ENABLE_LOCKING_STYLE
139786  /*
139787  **   PRAGMA [schema.]lock_proxy_file
139788  **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
139789  **
139790  ** Return or set the value of the lock_proxy_file flag.  Changing
139791  ** the value sets a specific file to be used for database access locks.
139792  **
139793  */
139794  case PragTyp_LOCK_PROXY_FILE: {
139795    if( !zRight ){
139796      Pager *pPager = sqlite3BtreePager(pDb->pBt);
139797      char *proxy_file_path = NULL;
139798      sqlite3_file *pFile = sqlite3PagerFile(pPager);
139799      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
139800                           &proxy_file_path);
139801      returnSingleText(v, proxy_file_path);
139802    }else{
139803      Pager *pPager = sqlite3BtreePager(pDb->pBt);
139804      sqlite3_file *pFile = sqlite3PagerFile(pPager);
139805      int res;
139806      if( zRight[0] ){
139807        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
139808                                     zRight);
139809      } else {
139810        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
139811                                     NULL);
139812      }
139813      if( res!=SQLITE_OK ){
139814        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
139815        goto pragma_out;
139816      }
139817    }
139818    break;
139819  }
139820#endif /* SQLITE_ENABLE_LOCKING_STYLE */
139821
139822  /*
139823  **   PRAGMA [schema.]synchronous
139824  **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
139825  **
139826  ** Return or set the local value of the synchronous flag.  Changing
139827  ** the local value does not make changes to the disk file and the
139828  ** default value will be restored the next time the database is
139829  ** opened.
139830  */
139831  case PragTyp_SYNCHRONOUS: {
139832    if( !zRight ){
139833      returnSingleInt(v, pDb->safety_level-1);
139834    }else{
139835      if( !db->autoCommit ){
139836        sqlite3ErrorMsg(pParse,
139837            "Safety level may not be changed inside a transaction");
139838      }else if( iDb!=1 ){
139839        int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
139840        if( iLevel==0 ) iLevel = 1;
139841        pDb->safety_level = iLevel;
139842        pDb->bSyncSet = 1;
139843        setAllPagerFlags(db);
139844      }
139845    }
139846    break;
139847  }
139848#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
139849
139850#ifndef SQLITE_OMIT_FLAG_PRAGMAS
139851  case PragTyp_FLAG: {
139852    if( zRight==0 ){
139853      setPragmaResultColumnNames(v, pPragma);
139854      returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
139855    }else{
139856      u64 mask = pPragma->iArg;    /* Mask of bits to set or clear. */
139857      if( db->autoCommit==0 ){
139858        /* Foreign key support may not be enabled or disabled while not
139859        ** in auto-commit mode.  */
139860        mask &= ~(SQLITE_ForeignKeys);
139861      }
139862#if SQLITE_USER_AUTHENTICATION
139863      if( db->auth.authLevel==UAUTH_User ){
139864        /* Do not allow non-admin users to modify the schema arbitrarily */
139865        mask &= ~(SQLITE_WriteSchema);
139866      }
139867#endif
139868
139869      if( sqlite3GetBoolean(zRight, 0) ){
139870        if( (mask & SQLITE_WriteSchema)==0
139871         || (db->flags & SQLITE_Defensive)==0
139872        ){
139873          db->flags |= mask;
139874        }
139875      }else{
139876        db->flags &= ~mask;
139877        if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
139878        if( (mask & SQLITE_WriteSchema)!=0
139879         && sqlite3_stricmp(zRight, "reset")==0
139880        ){
139881          /* IMP: R-60817-01178 If the argument is "RESET" then schema
139882          ** writing is disabled (as with "PRAGMA writable_schema=OFF") and,
139883          ** in addition, the schema is reloaded. */
139884          sqlite3ResetAllSchemasOfConnection(db);
139885        }
139886      }
139887
139888      /* Many of the flag-pragmas modify the code generated by the SQL
139889      ** compiler (eg. count_changes). So add an opcode to expire all
139890      ** compiled SQL statements after modifying a pragma value.
139891      */
139892      sqlite3VdbeAddOp0(v, OP_Expire);
139893      setAllPagerFlags(db);
139894    }
139895    break;
139896  }
139897#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
139898
139899#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
139900  /*
139901  **   PRAGMA table_info(<table>)
139902  **
139903  ** Return a single row for each column of the named table. The columns of
139904  ** the returned data set are:
139905  **
139906  ** cid:        Column id (numbered from left to right, starting at 0)
139907  ** name:       Column name
139908  ** type:       Column declaration type.
139909  ** notnull:    True if 'NOT NULL' is part of column declaration
139910  ** dflt_value: The default value for the column, if any.
139911  ** pk:         Non-zero for PK fields.
139912  */
139913  case PragTyp_TABLE_INFO: if( zRight ){
139914    Table *pTab;
139915    sqlite3CodeVerifyNamedSchema(pParse, zDb);
139916    pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
139917    if( pTab ){
139918      int i, k;
139919      int nHidden = 0;
139920      Column *pCol;
139921      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
139922      pParse->nMem = 7;
139923      sqlite3ViewGetColumnNames(pParse, pTab);
139924      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
139925        int isHidden = 0;
139926        const Expr *pColExpr;
139927        if( pCol->colFlags & COLFLAG_NOINSERT ){
139928          if( pPragma->iArg==0 ){
139929            nHidden++;
139930            continue;
139931          }
139932          if( pCol->colFlags & COLFLAG_VIRTUAL ){
139933            isHidden = 2;  /* GENERATED ALWAYS AS ... VIRTUAL */
139934          }else if( pCol->colFlags & COLFLAG_STORED ){
139935            isHidden = 3;  /* GENERATED ALWAYS AS ... STORED */
139936          }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );
139937            isHidden = 1;  /* HIDDEN */
139938          }
139939        }
139940        if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
139941          k = 0;
139942        }else if( pPk==0 ){
139943          k = 1;
139944        }else{
139945          for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
139946        }
139947        pColExpr = sqlite3ColumnExpr(pTab,pCol);
139948        assert( pColExpr==0 || pColExpr->op==TK_SPAN || isHidden>=2 );
139949        assert( pColExpr==0 || !ExprHasProperty(pColExpr, EP_IntValue)
139950                  || isHidden>=2 );
139951        sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
139952               i-nHidden,
139953               pCol->zCnName,
139954               sqlite3ColumnType(pCol,""),
139955               pCol->notNull ? 1 : 0,
139956               (isHidden>=2 || pColExpr==0) ? 0 : pColExpr->u.zToken,
139957               k,
139958               isHidden);
139959      }
139960    }
139961  }
139962  break;
139963
139964  /*
139965  **   PRAGMA table_list
139966  **
139967  ** Return a single row for each table, virtual table, or view in the
139968  ** entire schema.
139969  **
139970  ** schema:     Name of attached database hold this table
139971  ** name:       Name of the table itself
139972  ** type:       "table", "view", "virtual", "shadow"
139973  ** ncol:       Number of columns
139974  ** wr:         True for a WITHOUT ROWID table
139975  ** strict:     True for a STRICT table
139976  */
139977  case PragTyp_TABLE_LIST: {
139978    int ii;
139979    pParse->nMem = 6;
139980    sqlite3CodeVerifyNamedSchema(pParse, zDb);
139981    for(ii=0; ii<db->nDb; ii++){
139982      HashElem *k;
139983      Hash *pHash;
139984      int initNCol;
139985      if( zDb && sqlite3_stricmp(zDb, db->aDb[ii].zDbSName)!=0 ) continue;
139986
139987      /* Ensure that the Table.nCol field is initialized for all views
139988      ** and virtual tables.  Each time we initialize a Table.nCol value
139989      ** for a table, that can potentially disrupt the hash table, so restart
139990      ** the initialization scan.
139991      */
139992      pHash = &db->aDb[ii].pSchema->tblHash;
139993      initNCol = sqliteHashCount(pHash);
139994      while( initNCol-- ){
139995        for(k=sqliteHashFirst(pHash); 1; k=sqliteHashNext(k) ){
139996          Table *pTab;
139997          if( k==0 ){ initNCol = 0; break; }
139998          pTab = sqliteHashData(k);
139999          if( pTab->nCol==0 ){
140000            char *zSql = sqlite3MPrintf(db, "SELECT*FROM\"%w\"", pTab->zName);
140001            if( zSql ){
140002              sqlite3_stmt *pDummy = 0;
140003              (void)sqlite3_prepare(db, zSql, -1, &pDummy, 0);
140004              (void)sqlite3_finalize(pDummy);
140005              sqlite3DbFree(db, zSql);
140006            }
140007            if( db->mallocFailed ){
140008              sqlite3ErrorMsg(db->pParse, "out of memory");
140009              db->pParse->rc = SQLITE_NOMEM_BKPT;
140010            }
140011            pHash = &db->aDb[ii].pSchema->tblHash;
140012            break;
140013          }
140014        }
140015      }
140016
140017      for(k=sqliteHashFirst(pHash); k; k=sqliteHashNext(k) ){
140018        Table *pTab = sqliteHashData(k);
140019        const char *zType;
140020        if( zRight && sqlite3_stricmp(zRight, pTab->zName)!=0 ) continue;
140021        if( IsView(pTab) ){
140022          zType = "view";
140023        }else if( IsVirtual(pTab) ){
140024          zType = "virtual";
140025        }else if( pTab->tabFlags & TF_Shadow ){
140026          zType = "shadow";
140027        }else{
140028          zType = "table";
140029        }
140030        sqlite3VdbeMultiLoad(v, 1, "sssiii",
140031           db->aDb[ii].zDbSName,
140032           sqlite3PreferredTableName(pTab->zName),
140033           zType,
140034           pTab->nCol,
140035           (pTab->tabFlags & TF_WithoutRowid)!=0,
140036           (pTab->tabFlags & TF_Strict)!=0
140037        );
140038      }
140039    }
140040  }
140041  break;
140042
140043#ifdef SQLITE_DEBUG
140044  case PragTyp_STATS: {
140045    Index *pIdx;
140046    HashElem *i;
140047    pParse->nMem = 5;
140048    sqlite3CodeVerifySchema(pParse, iDb);
140049    for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
140050      Table *pTab = sqliteHashData(i);
140051      sqlite3VdbeMultiLoad(v, 1, "ssiii",
140052           sqlite3PreferredTableName(pTab->zName),
140053           0,
140054           pTab->szTabRow,
140055           pTab->nRowLogEst,
140056           pTab->tabFlags);
140057      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
140058        sqlite3VdbeMultiLoad(v, 2, "siiiX",
140059           pIdx->zName,
140060           pIdx->szIdxRow,
140061           pIdx->aiRowLogEst[0],
140062           pIdx->hasStat1);
140063        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
140064      }
140065    }
140066  }
140067  break;
140068#endif
140069
140070  case PragTyp_INDEX_INFO: if( zRight ){
140071    Index *pIdx;
140072    Table *pTab;
140073    pIdx = sqlite3FindIndex(db, zRight, zDb);
140074    if( pIdx==0 ){
140075      /* If there is no index named zRight, check to see if there is a
140076      ** WITHOUT ROWID table named zRight, and if there is, show the
140077      ** structure of the PRIMARY KEY index for that table. */
140078      pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
140079      if( pTab && !HasRowid(pTab) ){
140080        pIdx = sqlite3PrimaryKeyIndex(pTab);
140081      }
140082    }
140083    if( pIdx ){
140084      int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
140085      int i;
140086      int mx;
140087      if( pPragma->iArg ){
140088        /* PRAGMA index_xinfo (newer version with more rows and columns) */
140089        mx = pIdx->nColumn;
140090        pParse->nMem = 6;
140091      }else{
140092        /* PRAGMA index_info (legacy version) */
140093        mx = pIdx->nKeyCol;
140094        pParse->nMem = 3;
140095      }
140096      pTab = pIdx->pTable;
140097      sqlite3CodeVerifySchema(pParse, iIdxDb);
140098      assert( pParse->nMem<=pPragma->nPragCName );
140099      for(i=0; i<mx; i++){
140100        i16 cnum = pIdx->aiColumn[i];
140101        sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
140102                             cnum<0 ? 0 : pTab->aCol[cnum].zCnName);
140103        if( pPragma->iArg ){
140104          sqlite3VdbeMultiLoad(v, 4, "isiX",
140105            pIdx->aSortOrder[i],
140106            pIdx->azColl[i],
140107            i<pIdx->nKeyCol);
140108        }
140109        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
140110      }
140111    }
140112  }
140113  break;
140114
140115  case PragTyp_INDEX_LIST: if( zRight ){
140116    Index *pIdx;
140117    Table *pTab;
140118    int i;
140119    pTab = sqlite3FindTable(db, zRight, zDb);
140120    if( pTab ){
140121      int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
140122      pParse->nMem = 5;
140123      sqlite3CodeVerifySchema(pParse, iTabDb);
140124      for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
140125        const char *azOrigin[] = { "c", "u", "pk" };
140126        sqlite3VdbeMultiLoad(v, 1, "isisi",
140127           i,
140128           pIdx->zName,
140129           IsUniqueIndex(pIdx),
140130           azOrigin[pIdx->idxType],
140131           pIdx->pPartIdxWhere!=0);
140132      }
140133    }
140134  }
140135  break;
140136
140137  case PragTyp_DATABASE_LIST: {
140138    int i;
140139    pParse->nMem = 3;
140140    for(i=0; i<db->nDb; i++){
140141      if( db->aDb[i].pBt==0 ) continue;
140142      assert( db->aDb[i].zDbSName!=0 );
140143      sqlite3VdbeMultiLoad(v, 1, "iss",
140144         i,
140145         db->aDb[i].zDbSName,
140146         sqlite3BtreeGetFilename(db->aDb[i].pBt));
140147    }
140148  }
140149  break;
140150
140151  case PragTyp_COLLATION_LIST: {
140152    int i = 0;
140153    HashElem *p;
140154    pParse->nMem = 2;
140155    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
140156      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
140157      sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
140158    }
140159  }
140160  break;
140161
140162#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
140163  case PragTyp_FUNCTION_LIST: {
140164    int i;
140165    HashElem *j;
140166    FuncDef *p;
140167    int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0;
140168    pParse->nMem = 6;
140169    for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
140170      for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
140171        assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
140172        pragmaFunclistLine(v, p, 1, showInternFunc);
140173      }
140174    }
140175    for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
140176      p = (FuncDef*)sqliteHashData(j);
140177      assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
140178      pragmaFunclistLine(v, p, 0, showInternFunc);
140179    }
140180  }
140181  break;
140182
140183#ifndef SQLITE_OMIT_VIRTUALTABLE
140184  case PragTyp_MODULE_LIST: {
140185    HashElem *j;
140186    pParse->nMem = 1;
140187    for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
140188      Module *pMod = (Module*)sqliteHashData(j);
140189      sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
140190    }
140191  }
140192  break;
140193#endif /* SQLITE_OMIT_VIRTUALTABLE */
140194
140195  case PragTyp_PRAGMA_LIST: {
140196    int i;
140197    for(i=0; i<ArraySize(aPragmaName); i++){
140198      sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
140199    }
140200  }
140201  break;
140202#endif /* SQLITE_INTROSPECTION_PRAGMAS */
140203
140204#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
140205
140206#ifndef SQLITE_OMIT_FOREIGN_KEY
140207  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
140208    FKey *pFK;
140209    Table *pTab;
140210    pTab = sqlite3FindTable(db, zRight, zDb);
140211    if( pTab && IsOrdinaryTable(pTab) ){
140212      pFK = pTab->u.tab.pFKey;
140213      if( pFK ){
140214        int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
140215        int i = 0;
140216        pParse->nMem = 8;
140217        sqlite3CodeVerifySchema(pParse, iTabDb);
140218        while(pFK){
140219          int j;
140220          for(j=0; j<pFK->nCol; j++){
140221            sqlite3VdbeMultiLoad(v, 1, "iissssss",
140222                   i,
140223                   j,
140224                   pFK->zTo,
140225                   pTab->aCol[pFK->aCol[j].iFrom].zCnName,
140226                   pFK->aCol[j].zCol,
140227                   actionName(pFK->aAction[1]),  /* ON UPDATE */
140228                   actionName(pFK->aAction[0]),  /* ON DELETE */
140229                   "NONE");
140230          }
140231          ++i;
140232          pFK = pFK->pNextFrom;
140233        }
140234      }
140235    }
140236  }
140237  break;
140238#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
140239
140240#ifndef SQLITE_OMIT_FOREIGN_KEY
140241#ifndef SQLITE_OMIT_TRIGGER
140242  case PragTyp_FOREIGN_KEY_CHECK: {
140243    FKey *pFK;             /* A foreign key constraint */
140244    Table *pTab;           /* Child table contain "REFERENCES" keyword */
140245    Table *pParent;        /* Parent table that child points to */
140246    Index *pIdx;           /* Index in the parent table */
140247    int i;                 /* Loop counter:  Foreign key number for pTab */
140248    int j;                 /* Loop counter:  Field of the foreign key */
140249    HashElem *k;           /* Loop counter:  Next table in schema */
140250    int x;                 /* result variable */
140251    int regResult;         /* 3 registers to hold a result row */
140252    int regRow;            /* Registers to hold a row from pTab */
140253    int addrTop;           /* Top of a loop checking foreign keys */
140254    int addrOk;            /* Jump here if the key is OK */
140255    int *aiCols;           /* child to parent column mapping */
140256
140257    regResult = pParse->nMem+1;
140258    pParse->nMem += 4;
140259    regRow = ++pParse->nMem;
140260    k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
140261    while( k ){
140262      if( zRight ){
140263        pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
140264        k = 0;
140265      }else{
140266        pTab = (Table*)sqliteHashData(k);
140267        k = sqliteHashNext(k);
140268      }
140269      if( pTab==0 || !IsOrdinaryTable(pTab) || pTab->u.tab.pFKey==0 ) continue;
140270      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
140271      zDb = db->aDb[iDb].zDbSName;
140272      sqlite3CodeVerifySchema(pParse, iDb);
140273      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
140274      sqlite3TouchRegister(pParse, pTab->nCol+regRow);
140275      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
140276      sqlite3VdbeLoadString(v, regResult, pTab->zName);
140277      assert( IsOrdinaryTable(pTab) );
140278      for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
140279        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
140280        if( pParent==0 ) continue;
140281        pIdx = 0;
140282        sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
140283        x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
140284        if( x==0 ){
140285          if( pIdx==0 ){
140286            sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
140287          }else{
140288            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
140289            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
140290          }
140291        }else{
140292          k = 0;
140293          break;
140294        }
140295      }
140296      assert( pParse->nErr>0 || pFK==0 );
140297      if( pFK ) break;
140298      if( pParse->nTab<i ) pParse->nTab = i;
140299      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
140300      assert( IsOrdinaryTable(pTab) );
140301      for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
140302        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
140303        pIdx = 0;
140304        aiCols = 0;
140305        if( pParent ){
140306          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
140307          assert( x==0 || db->mallocFailed );
140308        }
140309        addrOk = sqlite3VdbeMakeLabel(pParse);
140310
140311        /* Generate code to read the child key values into registers
140312        ** regRow..regRow+n. If any of the child key values are NULL, this
140313        ** row cannot cause an FK violation. Jump directly to addrOk in
140314        ** this case. */
140315        sqlite3TouchRegister(pParse, regRow + pFK->nCol);
140316        for(j=0; j<pFK->nCol; j++){
140317          int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
140318          sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
140319          sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
140320        }
140321
140322        /* Generate code to query the parent index for a matching parent
140323        ** key. If a match is found, jump to addrOk. */
140324        if( pIdx ){
140325          sqlite3VdbeAddOp4(v, OP_Affinity, regRow, pFK->nCol, 0,
140326              sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
140327          sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regRow, pFK->nCol);
140328          VdbeCoverage(v);
140329        }else if( pParent ){
140330          int jmp = sqlite3VdbeCurrentAddr(v)+2;
140331          sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
140332          sqlite3VdbeGoto(v, addrOk);
140333          assert( pFK->nCol==1 || db->mallocFailed );
140334        }
140335
140336        /* Generate code to report an FK violation to the caller. */
140337        if( HasRowid(pTab) ){
140338          sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
140339        }else{
140340          sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
140341        }
140342        sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
140343        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
140344        sqlite3VdbeResolveLabel(v, addrOk);
140345        sqlite3DbFree(db, aiCols);
140346      }
140347      sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
140348      sqlite3VdbeJumpHere(v, addrTop);
140349    }
140350  }
140351  break;
140352#endif /* !defined(SQLITE_OMIT_TRIGGER) */
140353#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
140354
140355#ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
140356  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
140357  ** used will be case sensitive or not depending on the RHS.
140358  */
140359  case PragTyp_CASE_SENSITIVE_LIKE: {
140360    if( zRight ){
140361      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
140362    }
140363  }
140364  break;
140365#endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
140366
140367#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
140368# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
140369#endif
140370
140371#ifndef SQLITE_OMIT_INTEGRITY_CHECK
140372  /*    PRAGMA integrity_check
140373  **    PRAGMA integrity_check(N)
140374  **    PRAGMA quick_check
140375  **    PRAGMA quick_check(N)
140376  **
140377  ** Verify the integrity of the database.
140378  **
140379  ** The "quick_check" is reduced version of
140380  ** integrity_check designed to detect most database corruption
140381  ** without the overhead of cross-checking indexes.  Quick_check
140382  ** is linear time whereas integrity_check is O(NlogN).
140383  **
140384  ** The maximum number of errors is 100 by default.  A different default
140385  ** can be specified using a numeric parameter N.
140386  **
140387  ** Or, the parameter N can be the name of a table.  In that case, only
140388  ** the one table named is verified.  The freelist is only verified if
140389  ** the named table is "sqlite_schema" (or one of its aliases).
140390  **
140391  ** All schemas are checked by default.  To check just a single
140392  ** schema, use the form:
140393  **
140394  **      PRAGMA schema.integrity_check;
140395  */
140396  case PragTyp_INTEGRITY_CHECK: {
140397    int i, j, addr, mxErr;
140398    Table *pObjTab = 0;     /* Check only this one table, if not NULL */
140399
140400    int isQuick = (sqlite3Tolower(zLeft[0])=='q');
140401
140402    /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
140403    ** then iDb is set to the index of the database identified by <db>.
140404    ** In this case, the integrity of database iDb only is verified by
140405    ** the VDBE created below.
140406    **
140407    ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
140408    ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
140409    ** to -1 here, to indicate that the VDBE should verify the integrity
140410    ** of all attached databases.  */
140411    assert( iDb>=0 );
140412    assert( iDb==0 || pId2->z );
140413    if( pId2->z==0 ) iDb = -1;
140414
140415    /* Initialize the VDBE program */
140416    pParse->nMem = 6;
140417
140418    /* Set the maximum error count */
140419    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
140420    if( zRight ){
140421      if( sqlite3GetInt32(pValue->z, &mxErr) ){
140422        if( mxErr<=0 ){
140423          mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
140424        }
140425      }else{
140426        pObjTab = sqlite3LocateTable(pParse, 0, zRight,
140427                      iDb>=0 ? db->aDb[iDb].zDbSName : 0);
140428      }
140429    }
140430    sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
140431
140432    /* Do an integrity check on each database file */
140433    for(i=0; i<db->nDb; i++){
140434      HashElem *x;     /* For looping over tables in the schema */
140435      Hash *pTbls;     /* Set of all tables in the schema */
140436      int *aRoot;      /* Array of root page numbers of all btrees */
140437      int cnt = 0;     /* Number of entries in aRoot[] */
140438
140439      if( OMIT_TEMPDB && i==1 ) continue;
140440      if( iDb>=0 && i!=iDb ) continue;
140441
140442      sqlite3CodeVerifySchema(pParse, i);
140443      pParse->okConstFactor = 0;  /* tag-20230327-1 */
140444
140445      /* Do an integrity check of the B-Tree
140446      **
140447      ** Begin by finding the root pages numbers
140448      ** for all tables and indices in the database.
140449      */
140450      assert( sqlite3SchemaMutexHeld(db, i, 0) );
140451      pTbls = &db->aDb[i].pSchema->tblHash;
140452      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
140453        Table *pTab = sqliteHashData(x);  /* Current table */
140454        Index *pIdx;                      /* An index on pTab */
140455        int nIdx;                         /* Number of indexes on pTab */
140456        if( pObjTab && pObjTab!=pTab ) continue;
140457        if( HasRowid(pTab) ) cnt++;
140458        for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
140459      }
140460      if( cnt==0 ) continue;
140461      if( pObjTab ) cnt++;
140462      aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
140463      if( aRoot==0 ) break;
140464      cnt = 0;
140465      if( pObjTab ) aRoot[++cnt] = 0;
140466      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
140467        Table *pTab = sqliteHashData(x);
140468        Index *pIdx;
140469        if( pObjTab && pObjTab!=pTab ) continue;
140470        if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
140471        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
140472          aRoot[++cnt] = pIdx->tnum;
140473        }
140474      }
140475      aRoot[0] = cnt;
140476
140477      /* Make sure sufficient number of registers have been allocated */
140478      sqlite3TouchRegister(pParse, 8+cnt);
140479      sqlite3ClearTempRegCache(pParse);
140480
140481      /* Do the b-tree integrity checks */
140482      sqlite3VdbeAddOp4(v, OP_IntegrityCk, 1, cnt, 8, (char*)aRoot,P4_INTARRAY);
140483      sqlite3VdbeChangeP5(v, (u8)i);
140484      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
140485      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
140486         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
140487         P4_DYNAMIC);
140488      sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
140489      integrityCheckResultRow(v);
140490      sqlite3VdbeJumpHere(v, addr);
140491
140492      /* Check that the indexes all have the right number of rows */
140493      cnt = pObjTab ? 1 : 0;
140494      sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
140495      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
140496        int iTab = 0;
140497        Table *pTab = sqliteHashData(x);
140498        Index *pIdx;
140499        if( pObjTab && pObjTab!=pTab ) continue;
140500        if( HasRowid(pTab) ){
140501          iTab = cnt++;
140502        }else{
140503          iTab = cnt;
140504          for(pIdx=pTab->pIndex; ALWAYS(pIdx); pIdx=pIdx->pNext){
140505            if( IsPrimaryKeyIndex(pIdx) ) break;
140506            iTab++;
140507          }
140508        }
140509        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
140510          if( pIdx->pPartIdxWhere==0 ){
140511            addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+cnt, 0, 8+iTab);
140512            VdbeCoverageNeverNull(v);
140513            sqlite3VdbeLoadString(v, 4, pIdx->zName);
140514            sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
140515            integrityCheckResultRow(v);
140516            sqlite3VdbeJumpHere(v, addr);
140517          }
140518          cnt++;
140519        }
140520      }
140521
140522      /* Make sure all the indices are constructed correctly.
140523      */
140524      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
140525        Table *pTab = sqliteHashData(x);
140526        Index *pIdx, *pPk;
140527        Index *pPrior = 0;      /* Previous index */
140528        int loopTop;
140529        int iDataCur, iIdxCur;
140530        int r1 = -1;
140531        int bStrict;            /* True for a STRICT table */
140532        int r2;                 /* Previous key for WITHOUT ROWID tables */
140533        int mxCol;              /* Maximum non-virtual column number */
140534
140535        if( pObjTab && pObjTab!=pTab ) continue;
140536        if( !IsOrdinaryTable(pTab) ) continue;
140537        if( isQuick || HasRowid(pTab) ){
140538          pPk = 0;
140539          r2 = 0;
140540        }else{
140541          pPk = sqlite3PrimaryKeyIndex(pTab);
140542          r2 = sqlite3GetTempRange(pParse, pPk->nKeyCol);
140543          sqlite3VdbeAddOp3(v, OP_Null, 1, r2, r2+pPk->nKeyCol-1);
140544        }
140545        sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
140546                                   1, 0, &iDataCur, &iIdxCur);
140547        /* reg[7] counts the number of entries in the table.
140548        ** reg[8+i] counts the number of entries in the i-th index
140549        */
140550        sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
140551        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
140552          sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
140553        }
140554        assert( pParse->nMem>=8+j );
140555        assert( sqlite3NoTempsInRange(pParse,1,7+j) );
140556        sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
140557        loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
140558
140559        /* Fetch the right-most column from the table.  This will cause
140560        ** the entire record header to be parsed and sanity checked.  It
140561        ** will also prepopulate the cursor column cache that is used
140562        ** by the OP_IsType code, so it is a required step.
140563        */
140564        assert( !IsVirtual(pTab) );
140565        if( HasRowid(pTab) ){
140566          mxCol = -1;
140567          for(j=0; j<pTab->nCol; j++){
140568            if( (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)==0 ) mxCol++;
140569          }
140570          if( mxCol==pTab->iPKey ) mxCol--;
140571        }else{
140572          /* COLFLAG_VIRTUAL columns are not included in the WITHOUT ROWID
140573          ** PK index column-count, so there is no need to account for them
140574          ** in this case. */
140575          mxCol = sqlite3PrimaryKeyIndex(pTab)->nColumn-1;
140576        }
140577        if( mxCol>=0 ){
140578          sqlite3VdbeAddOp3(v, OP_Column, iDataCur, mxCol, 3);
140579          sqlite3VdbeTypeofColumn(v, 3);
140580        }
140581
140582        if( !isQuick ){
140583          if( pPk ){
140584            /* Verify WITHOUT ROWID keys are in ascending order */
140585            int a1;
140586            char *zErr;
140587            a1 = sqlite3VdbeAddOp4Int(v, OP_IdxGT, iDataCur, 0,r2,pPk->nKeyCol);
140588            VdbeCoverage(v);
140589            sqlite3VdbeAddOp1(v, OP_IsNull, r2); VdbeCoverage(v);
140590            zErr = sqlite3MPrintf(db,
140591                   "row not in PRIMARY KEY order for %s",
140592                    pTab->zName);
140593            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
140594            integrityCheckResultRow(v);
140595            sqlite3VdbeJumpHere(v, a1);
140596            sqlite3VdbeJumpHere(v, a1+1);
140597            for(j=0; j<pPk->nKeyCol; j++){
140598              sqlite3ExprCodeLoadIndexColumn(pParse, pPk, iDataCur, j, r2+j);
140599            }
140600          }
140601        }
140602        /* Verify datatypes for all columns:
140603        **
140604        **   (1) NOT NULL columns may not contain a NULL
140605        **   (2) Datatype must be exact for non-ANY columns in STRICT tables
140606        **   (3) Datatype for TEXT columns in non-STRICT tables must be
140607        **       NULL, TEXT, or BLOB.
140608        **   (4) Datatype for numeric columns in non-STRICT tables must not
140609        **       be a TEXT value that can be losslessly converted to numeric.
140610        */
140611        bStrict = (pTab->tabFlags & TF_Strict)!=0;
140612        for(j=0; j<pTab->nCol; j++){
140613          char *zErr;
140614          Column *pCol = pTab->aCol + j;  /* The column to be checked */
140615          int labelError;               /* Jump here to report an error */
140616          int labelOk;                  /* Jump here if all looks ok */
140617          int p1, p3, p4;               /* Operands to the OP_IsType opcode */
140618          int doTypeCheck;              /* Check datatypes (besides NOT NULL) */
140619
140620          if( j==pTab->iPKey ) continue;
140621          if( bStrict ){
140622            doTypeCheck = pCol->eCType>COLTYPE_ANY;
140623          }else{
140624            doTypeCheck = pCol->affinity>SQLITE_AFF_BLOB;
140625          }
140626          if( pCol->notNull==0 && !doTypeCheck ) continue;
140627
140628          /* Compute the operands that will be needed for OP_IsType */
140629          p4 = SQLITE_NULL;
140630          if( pCol->colFlags & COLFLAG_VIRTUAL ){
140631            sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
140632            p1 = -1;
140633            p3 = 3;
140634          }else{
140635            if( pCol->iDflt ){
140636              sqlite3_value *pDfltValue = 0;
140637              sqlite3ValueFromExpr(db, sqlite3ColumnExpr(pTab,pCol), ENC(db),
140638                                   pCol->affinity, &pDfltValue);
140639              if( pDfltValue ){
140640                p4 = sqlite3_value_type(pDfltValue);
140641                sqlite3ValueFree(pDfltValue);
140642              }
140643            }
140644            p1 = iDataCur;
140645            if( !HasRowid(pTab) ){
140646              testcase( j!=sqlite3TableColumnToStorage(pTab, j) );
140647              p3 = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), j);
140648            }else{
140649              p3 = sqlite3TableColumnToStorage(pTab,j);
140650              testcase( p3!=j);
140651            }
140652          }
140653
140654          labelError = sqlite3VdbeMakeLabel(pParse);
140655          labelOk = sqlite3VdbeMakeLabel(pParse);
140656          if( pCol->notNull ){
140657            /* (1) NOT NULL columns may not contain a NULL */
140658            int jmp3;
140659            int jmp2 = sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
140660            VdbeCoverage(v);
140661            if( p1<0 ){
140662              sqlite3VdbeChangeP5(v, 0x0f); /* INT, REAL, TEXT, or BLOB */
140663              jmp3 = jmp2;
140664            }else{
140665              sqlite3VdbeChangeP5(v, 0x0d); /* INT, TEXT, or BLOB */
140666              /* OP_IsType does not detect NaN values in the database file
140667              ** which should be treated as a NULL.  So if the header type
140668              ** is REAL, we have to load the actual data using OP_Column
140669              ** to reliably determine if the value is a NULL. */
140670              sqlite3VdbeAddOp3(v, OP_Column, p1, p3, 3);
140671              sqlite3ColumnDefault(v, pTab, j, 3);
140672              jmp3 = sqlite3VdbeAddOp2(v, OP_NotNull, 3, labelOk);
140673              VdbeCoverage(v);
140674            }
140675            zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
140676                                pCol->zCnName);
140677            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
140678            if( doTypeCheck ){
140679              sqlite3VdbeGoto(v, labelError);
140680              sqlite3VdbeJumpHere(v, jmp2);
140681              sqlite3VdbeJumpHere(v, jmp3);
140682            }else{
140683              /* VDBE byte code will fall thru */
140684            }
140685          }
140686          if( bStrict && doTypeCheck ){
140687            /* (2) Datatype must be exact for non-ANY columns in STRICT tables*/
140688            static unsigned char aStdTypeMask[] = {
140689               0x1f,    /* ANY */
140690               0x18,    /* BLOB */
140691               0x11,    /* INT */
140692               0x11,    /* INTEGER */
140693               0x13,    /* REAL */
140694               0x14     /* TEXT */
140695            };
140696            sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
140697            assert( pCol->eCType>=1 && pCol->eCType<=sizeof(aStdTypeMask) );
140698            sqlite3VdbeChangeP5(v, aStdTypeMask[pCol->eCType-1]);
140699            VdbeCoverage(v);
140700            zErr = sqlite3MPrintf(db, "non-%s value in %s.%s",
140701                                  sqlite3StdType[pCol->eCType-1],
140702                                  pTab->zName, pTab->aCol[j].zCnName);
140703            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
140704          }else if( !bStrict && pCol->affinity==SQLITE_AFF_TEXT ){
140705            /* (3) Datatype for TEXT columns in non-STRICT tables must be
140706            **     NULL, TEXT, or BLOB. */
140707            sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
140708            sqlite3VdbeChangeP5(v, 0x1c); /* NULL, TEXT, or BLOB */
140709            VdbeCoverage(v);
140710            zErr = sqlite3MPrintf(db, "NUMERIC value in %s.%s",
140711                                  pTab->zName, pTab->aCol[j].zCnName);
140712            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
140713          }else if( !bStrict && pCol->affinity>=SQLITE_AFF_NUMERIC ){
140714            /* (4) Datatype for numeric columns in non-STRICT tables must not
140715            **     be a TEXT value that can be converted to numeric. */
140716            sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
140717            sqlite3VdbeChangeP5(v, 0x1b); /* NULL, INT, FLOAT, or BLOB */
140718            VdbeCoverage(v);
140719            if( p1>=0 ){
140720              sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
140721            }
140722            sqlite3VdbeAddOp4(v, OP_Affinity, 3, 1, 0, "C", P4_STATIC);
140723            sqlite3VdbeAddOp4Int(v, OP_IsType, -1, labelOk, 3, p4);
140724            sqlite3VdbeChangeP5(v, 0x1c); /* NULL, TEXT, or BLOB */
140725            VdbeCoverage(v);
140726            zErr = sqlite3MPrintf(db, "TEXT value in %s.%s",
140727                                  pTab->zName, pTab->aCol[j].zCnName);
140728            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
140729          }
140730          sqlite3VdbeResolveLabel(v, labelError);
140731          integrityCheckResultRow(v);
140732          sqlite3VdbeResolveLabel(v, labelOk);
140733        }
140734        /* Verify CHECK constraints */
140735        if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
140736          ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
140737          if( db->mallocFailed==0 ){
140738            int addrCkFault = sqlite3VdbeMakeLabel(pParse);
140739            int addrCkOk = sqlite3VdbeMakeLabel(pParse);
140740            char *zErr;
140741            int k;
140742            pParse->iSelfTab = iDataCur + 1;
140743            for(k=pCheck->nExpr-1; k>0; k--){
140744              sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
140745            }
140746            sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
140747                SQLITE_JUMPIFNULL);
140748            sqlite3VdbeResolveLabel(v, addrCkFault);
140749            pParse->iSelfTab = 0;
140750            zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
140751                pTab->zName);
140752            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
140753            integrityCheckResultRow(v);
140754            sqlite3VdbeResolveLabel(v, addrCkOk);
140755          }
140756          sqlite3ExprListDelete(db, pCheck);
140757        }
140758        if( !isQuick ){ /* Omit the remaining tests for quick_check */
140759          /* Validate index entries for the current row */
140760          for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
140761            int jmp2, jmp3, jmp4, jmp5, label6;
140762            int kk;
140763            int ckUniq = sqlite3VdbeMakeLabel(pParse);
140764            if( pPk==pIdx ) continue;
140765            r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
140766                                         pPrior, r1);
140767            pPrior = pIdx;
140768            sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
140769            /* Verify that an index entry exists for the current table row */
140770            jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
140771                                        pIdx->nColumn); VdbeCoverage(v);
140772            sqlite3VdbeLoadString(v, 3, "row ");
140773            sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
140774            sqlite3VdbeLoadString(v, 4, " missing from index ");
140775            sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
140776            jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
140777            sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
140778            jmp4 = integrityCheckResultRow(v);
140779            sqlite3VdbeJumpHere(v, jmp2);
140780
140781            /* The OP_IdxRowid opcode is an optimized version of OP_Column
140782            ** that extracts the rowid off the end of the index record.
140783            ** But it only works correctly if index record does not have
140784            ** any extra bytes at the end.  Verify that this is the case. */
140785            if( HasRowid(pTab) ){
140786              int jmp7;
140787              sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur+j, 3);
140788              jmp7 = sqlite3VdbeAddOp3(v, OP_Eq, 3, 0, r1+pIdx->nColumn-1);
140789              VdbeCoverageNeverNull(v);
140790              sqlite3VdbeLoadString(v, 3,
140791                 "rowid not at end-of-record for row ");
140792              sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
140793              sqlite3VdbeLoadString(v, 4, " of index ");
140794              sqlite3VdbeGoto(v, jmp5-1);
140795              sqlite3VdbeJumpHere(v, jmp7);
140796            }
140797
140798            /* Any indexed columns with non-BINARY collations must still hold
140799            ** the exact same text value as the table. */
140800            label6 = 0;
140801            for(kk=0; kk<pIdx->nKeyCol; kk++){
140802              if( pIdx->azColl[kk]==sqlite3StrBINARY ) continue;
140803              if( label6==0 ) label6 = sqlite3VdbeMakeLabel(pParse);
140804              sqlite3VdbeAddOp3(v, OP_Column, iIdxCur+j, kk, 3);
140805              sqlite3VdbeAddOp3(v, OP_Ne, 3, label6, r1+kk); VdbeCoverage(v);
140806            }
140807            if( label6 ){
140808              int jmp6 = sqlite3VdbeAddOp0(v, OP_Goto);
140809              sqlite3VdbeResolveLabel(v, label6);
140810              sqlite3VdbeLoadString(v, 3, "row ");
140811              sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
140812              sqlite3VdbeLoadString(v, 4, " values differ from index ");
140813              sqlite3VdbeGoto(v, jmp5-1);
140814              sqlite3VdbeJumpHere(v, jmp6);
140815            }
140816
140817            /* For UNIQUE indexes, verify that only one entry exists with the
140818            ** current key.  The entry is unique if (1) any column is NULL
140819            ** or (2) the next entry has a different key */
140820            if( IsUniqueIndex(pIdx) ){
140821              int uniqOk = sqlite3VdbeMakeLabel(pParse);
140822              int jmp6;
140823              for(kk=0; kk<pIdx->nKeyCol; kk++){
140824                int iCol = pIdx->aiColumn[kk];
140825                assert( iCol!=XN_ROWID && iCol<pTab->nCol );
140826                if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
140827                sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
140828                VdbeCoverage(v);
140829              }
140830              jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
140831              sqlite3VdbeGoto(v, uniqOk);
140832              sqlite3VdbeJumpHere(v, jmp6);
140833              sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
140834                                   pIdx->nKeyCol); VdbeCoverage(v);
140835              sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
140836              sqlite3VdbeGoto(v, jmp5);
140837              sqlite3VdbeResolveLabel(v, uniqOk);
140838            }
140839            sqlite3VdbeJumpHere(v, jmp4);
140840            sqlite3ResolvePartIdxLabel(pParse, jmp3);
140841          }
140842        }
140843        sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
140844        sqlite3VdbeJumpHere(v, loopTop-1);
140845        if( pPk ){
140846          assert( !isQuick );
140847          sqlite3ReleaseTempRange(pParse, r2, pPk->nKeyCol);
140848        }
140849      }
140850
140851#ifndef SQLITE_OMIT_VIRTUALTABLE
140852      /* Second pass to invoke the xIntegrity method on all virtual
140853      ** tables.
140854      */
140855      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
140856        Table *pTab = sqliteHashData(x);
140857        sqlite3_vtab *pVTab;
140858        int a1;
140859        if( pObjTab && pObjTab!=pTab ) continue;
140860        if( IsOrdinaryTable(pTab) ) continue;
140861        if( !IsVirtual(pTab) ) continue;
140862        if( pTab->nCol<=0 ){
140863          const char *zMod = pTab->u.vtab.azArg[0];
140864          if( sqlite3HashFind(&db->aModule, zMod)==0 ) continue;
140865        }
140866        sqlite3ViewGetColumnNames(pParse, pTab);
140867        if( pTab->u.vtab.p==0 ) continue;
140868        pVTab = pTab->u.vtab.p->pVtab;
140869        if( NEVER(pVTab==0) ) continue;
140870        if( NEVER(pVTab->pModule==0) ) continue;
140871        if( pVTab->pModule->iVersion<4 ) continue;
140872        if( pVTab->pModule->xIntegrity==0 ) continue;
140873        sqlite3VdbeAddOp3(v, OP_VCheck, i, 3, isQuick);
140874        pTab->nTabRef++;
140875        sqlite3VdbeAppendP4(v, pTab, P4_TABLEREF);
140876        a1 = sqlite3VdbeAddOp1(v, OP_IsNull, 3); VdbeCoverage(v);
140877        integrityCheckResultRow(v);
140878        sqlite3VdbeJumpHere(v, a1);
140879        continue;
140880      }
140881#endif
140882    }
140883    {
140884      static const int iLn = VDBE_OFFSET_LINENO(2);
140885      static const VdbeOpList endCode[] = {
140886        { OP_AddImm,      1, 0,        0},    /* 0 */
140887        { OP_IfNotZero,   1, 4,        0},    /* 1 */
140888        { OP_String8,     0, 3,        0},    /* 2 */
140889        { OP_ResultRow,   3, 1,        0},    /* 3 */
140890        { OP_Halt,        0, 0,        0},    /* 4 */
140891        { OP_String8,     0, 3,        0},    /* 5 */
140892        { OP_Goto,        0, 3,        0},    /* 6 */
140893      };
140894      VdbeOp *aOp;
140895
140896      aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
140897      if( aOp ){
140898        aOp[0].p2 = 1-mxErr;
140899        aOp[2].p4type = P4_STATIC;
140900        aOp[2].p4.z = "ok";
140901        aOp[5].p4type = P4_STATIC;
140902        aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
140903      }
140904      sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
140905    }
140906  }
140907  break;
140908#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
140909
140910#ifndef SQLITE_OMIT_UTF16
140911  /*
140912  **   PRAGMA encoding
140913  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
140914  **
140915  ** In its first form, this pragma returns the encoding of the main
140916  ** database. If the database is not initialized, it is initialized now.
140917  **
140918  ** The second form of this pragma is a no-op if the main database file
140919  ** has not already been initialized. In this case it sets the default
140920  ** encoding that will be used for the main database file if a new file
140921  ** is created. If an existing main database file is opened, then the
140922  ** default text encoding for the existing database is used.
140923  **
140924  ** In all cases new databases created using the ATTACH command are
140925  ** created to use the same default text encoding as the main database. If
140926  ** the main database has not been initialized and/or created when ATTACH
140927  ** is executed, this is done before the ATTACH operation.
140928  **
140929  ** In the second form this pragma sets the text encoding to be used in
140930  ** new database files created using this database handle. It is only
140931  ** useful if invoked immediately after the main database i
140932  */
140933  case PragTyp_ENCODING: {
140934    static const struct EncName {
140935      char *zName;
140936      u8 enc;
140937    } encnames[] = {
140938      { "UTF8",     SQLITE_UTF8        },
140939      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
140940      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
140941      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
140942      { "UTF16le",  SQLITE_UTF16LE     },
140943      { "UTF16be",  SQLITE_UTF16BE     },
140944      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
140945      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
140946      { 0, 0 }
140947    };
140948    const struct EncName *pEnc;
140949    if( !zRight ){    /* "PRAGMA encoding" */
140950      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
140951      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
140952      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
140953      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
140954      returnSingleText(v, encnames[ENC(pParse->db)].zName);
140955    }else{                        /* "PRAGMA encoding = XXX" */
140956      /* Only change the value of sqlite.enc if the database handle is not
140957      ** initialized. If the main database exists, the new sqlite.enc value
140958      ** will be overwritten when the schema is next loaded. If it does not
140959      ** already exists, it will be created to use the new encoding value.
140960      */
140961      if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
140962        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
140963          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
140964            u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
140965            SCHEMA_ENC(db) = enc;
140966            sqlite3SetTextEncoding(db, enc);
140967            break;
140968          }
140969        }
140970        if( !pEnc->zName ){
140971          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
140972        }
140973      }
140974    }
140975  }
140976  break;
140977#endif /* SQLITE_OMIT_UTF16 */
140978
140979#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
140980  /*
140981  **   PRAGMA [schema.]schema_version
140982  **   PRAGMA [schema.]schema_version = <integer>
140983  **
140984  **   PRAGMA [schema.]user_version
140985  **   PRAGMA [schema.]user_version = <integer>
140986  **
140987  **   PRAGMA [schema.]freelist_count
140988  **
140989  **   PRAGMA [schema.]data_version
140990  **
140991  **   PRAGMA [schema.]application_id
140992  **   PRAGMA [schema.]application_id = <integer>
140993  **
140994  ** The pragma's schema_version and user_version are used to set or get
140995  ** the value of the schema-version and user-version, respectively. Both
140996  ** the schema-version and the user-version are 32-bit signed integers
140997  ** stored in the database header.
140998  **
140999  ** The schema-cookie is usually only manipulated internally by SQLite. It
141000  ** is incremented by SQLite whenever the database schema is modified (by
141001  ** creating or dropping a table or index). The schema version is used by
141002  ** SQLite each time a query is executed to ensure that the internal cache
141003  ** of the schema used when compiling the SQL query matches the schema of
141004  ** the database against which the compiled query is actually executed.
141005  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
141006  ** the schema-version is potentially dangerous and may lead to program
141007  ** crashes or database corruption. Use with caution!
141008  **
141009  ** The user-version is not used internally by SQLite. It may be used by
141010  ** applications for any purpose.
141011  */
141012  case PragTyp_HEADER_VALUE: {
141013    int iCookie = pPragma->iArg;  /* Which cookie to read or write */
141014    sqlite3VdbeUsesBtree(v, iDb);
141015    if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
141016      /* Write the specified cookie value */
141017      static const VdbeOpList setCookie[] = {
141018        { OP_Transaction,    0,  1,  0},    /* 0 */
141019        { OP_SetCookie,      0,  0,  0},    /* 1 */
141020      };
141021      VdbeOp *aOp;
141022      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
141023      aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
141024      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
141025      aOp[0].p1 = iDb;
141026      aOp[1].p1 = iDb;
141027      aOp[1].p2 = iCookie;
141028      aOp[1].p3 = sqlite3Atoi(zRight);
141029      aOp[1].p5 = 1;
141030      if( iCookie==BTREE_SCHEMA_VERSION && (db->flags & SQLITE_Defensive)!=0 ){
141031        /* Do not allow the use of PRAGMA schema_version=VALUE in defensive
141032        ** mode.  Change the OP_SetCookie opcode into a no-op.  */
141033        aOp[1].opcode = OP_Noop;
141034      }
141035    }else{
141036      /* Read the specified cookie value */
141037      static const VdbeOpList readCookie[] = {
141038        { OP_Transaction,     0,  0,  0},    /* 0 */
141039        { OP_ReadCookie,      0,  1,  0},    /* 1 */
141040        { OP_ResultRow,       1,  1,  0}
141041      };
141042      VdbeOp *aOp;
141043      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
141044      aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
141045      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
141046      aOp[0].p1 = iDb;
141047      aOp[1].p1 = iDb;
141048      aOp[1].p3 = iCookie;
141049      sqlite3VdbeReusable(v);
141050    }
141051  }
141052  break;
141053#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
141054
141055#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
141056  /*
141057  **   PRAGMA compile_options
141058  **
141059  ** Return the names of all compile-time options used in this build,
141060  ** one option per row.
141061  */
141062  case PragTyp_COMPILE_OPTIONS: {
141063    int i = 0;
141064    const char *zOpt;
141065    pParse->nMem = 1;
141066    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
141067      sqlite3VdbeLoadString(v, 1, zOpt);
141068      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
141069    }
141070    sqlite3VdbeReusable(v);
141071  }
141072  break;
141073#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
141074
141075#ifndef SQLITE_OMIT_WAL
141076  /*
141077  **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
141078  **
141079  ** Checkpoint the database.
141080  */
141081  case PragTyp_WAL_CHECKPOINT: {
141082    int iBt = (pId2->z?iDb:SQLITE_MAX_DB);
141083    int eMode = SQLITE_CHECKPOINT_PASSIVE;
141084    if( zRight ){
141085      if( sqlite3StrICmp(zRight, "full")==0 ){
141086        eMode = SQLITE_CHECKPOINT_FULL;
141087      }else if( sqlite3StrICmp(zRight, "restart")==0 ){
141088        eMode = SQLITE_CHECKPOINT_RESTART;
141089      }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
141090        eMode = SQLITE_CHECKPOINT_TRUNCATE;
141091      }
141092    }
141093    pParse->nMem = 3;
141094    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
141095    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
141096  }
141097  break;
141098
141099  /*
141100  **   PRAGMA wal_autocheckpoint
141101  **   PRAGMA wal_autocheckpoint = N
141102  **
141103  ** Configure a database connection to automatically checkpoint a database
141104  ** after accumulating N frames in the log. Or query for the current value
141105  ** of N.
141106  */
141107  case PragTyp_WAL_AUTOCHECKPOINT: {
141108    if( zRight ){
141109      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
141110    }
141111    returnSingleInt(v,
141112       db->xWalCallback==sqlite3WalDefaultHook ?
141113           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
141114  }
141115  break;
141116#endif
141117
141118  /*
141119  **  PRAGMA shrink_memory
141120  **
141121  ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
141122  ** connection on which it is invoked to free up as much memory as it
141123  ** can, by calling sqlite3_db_release_memory().
141124  */
141125  case PragTyp_SHRINK_MEMORY: {
141126    sqlite3_db_release_memory(db);
141127    break;
141128  }
141129
141130  /*
141131  **  PRAGMA optimize
141132  **  PRAGMA optimize(MASK)
141133  **  PRAGMA schema.optimize
141134  **  PRAGMA schema.optimize(MASK)
141135  **
141136  ** Attempt to optimize the database.  All schemas are optimized in the first
141137  ** two forms, and only the specified schema is optimized in the latter two.
141138  **
141139  ** The details of optimizations performed by this pragma are expected
141140  ** to change and improve over time.  Applications should anticipate that
141141  ** this pragma will perform new optimizations in future releases.
141142  **
141143  ** The optional argument is a bitmask of optimizations to perform:
141144  **
141145  **    0x00001    Debugging mode.  Do not actually perform any optimizations
141146  **               but instead return one line of text for each optimization
141147  **               that would have been done.  Off by default.
141148  **
141149  **    0x00002    Run ANALYZE on tables that might benefit.  On by default.
141150  **               See below for additional information.
141151  **
141152  **    0x00010    Run all ANALYZE operations using an analysis_limit that
141153  **               is the lessor of the current analysis_limit and the
141154  **               SQLITE_DEFAULT_OPTIMIZE_LIMIT compile-time option.
141155  **               The default value of SQLITE_DEFAULT_OPTIMIZE_LIMIT is
141156  **               currently (2024-02-19) set to 2000, which is such that
141157  **               the worst case run-time for PRAGMA optimize on a 100MB
141158  **               database will usually be less than 100 milliseconds on
141159  **               a RaspberryPI-4 class machine.  On by default.
141160  **
141161  **    0x10000    Look at tables to see if they need to be reanalyzed
141162  **               due to growth or shrinkage even if they have not been
141163  **               queried during the current connection.  Off by default.
141164  **
141165  ** The default MASK is and always shall be 0x0fffe.  In the current
141166  ** implementation, the default mask only covers the 0x00002 optimization,
141167  ** though additional optimizations that are covered by 0x0fffe might be
141168  ** added in the future.  Optimizations that are off by default and must
141169  ** be explicitly requested have masks of 0x10000 or greater.
141170  **
141171  ** DETERMINATION OF WHEN TO RUN ANALYZE
141172  **
141173  ** In the current implementation, a table is analyzed if only if all of
141174  ** the following are true:
141175  **
141176  ** (1) MASK bit 0x00002 is set.
141177  **
141178  ** (2) The table is an ordinary table, not a virtual table or view.
141179  **
141180  ** (3) The table name does not begin with "sqlite_".
141181  **
141182  ** (4) One or more of the following is true:
141183  **      (4a) The 0x10000 MASK bit is set.
141184  **      (4b) One or more indexes on the table lacks an entry
141185  **           in the sqlite_stat1 table.
141186  **      (4c) The query planner used sqlite_stat1-style statistics for one
141187  **           or more indexes of the table at some point during the lifetime
141188  **           of the current connection.
141189  **
141190  ** (5) One or more of the following is true:
141191  **      (5a) One or more indexes on the table lacks an entry
141192  **           in the sqlite_stat1 table.  (Same as 4a)
141193  **      (5b) The number of rows in the table has increased or decreased by
141194  **           10-fold.  In other words, the current size of the table is
141195  **           10 times larger than the size in sqlite_stat1 or else the
141196  **           current size is less than 1/10th the size in sqlite_stat1.
141197  **
141198  ** The rules for when tables are analyzed are likely to change in
141199  ** future releases.  Future versions of SQLite might accept a string
141200  ** literal argument to this pragma that contains a mnemonic description
141201  ** of the options rather than a bitmap.
141202  */
141203  case PragTyp_OPTIMIZE: {
141204    int iDbLast;           /* Loop termination point for the schema loop */
141205    int iTabCur;           /* Cursor for a table whose size needs checking */
141206    HashElem *k;           /* Loop over tables of a schema */
141207    Schema *pSchema;       /* The current schema */
141208    Table *pTab;           /* A table in the schema */
141209    Index *pIdx;           /* An index of the table */
141210    LogEst szThreshold;    /* Size threshold above which reanalysis needed */
141211    char *zSubSql;         /* SQL statement for the OP_SqlExec opcode */
141212    u32 opMask;            /* Mask of operations to perform */
141213    int nLimit;            /* Analysis limit to use */
141214    int nCheck = 0;        /* Number of tables to be optimized */
141215    int nBtree = 0;        /* Number of btrees to scan */
141216    int nIndex;            /* Number of indexes on the current table */
141217
141218    if( zRight ){
141219      opMask = (u32)sqlite3Atoi(zRight);
141220      if( (opMask & 0x02)==0 ) break;
141221    }else{
141222      opMask = 0xfffe;
141223    }
141224    if( (opMask & 0x10)==0 ){
141225      nLimit = 0;
141226    }else if( db->nAnalysisLimit>0
141227           && db->nAnalysisLimit<SQLITE_DEFAULT_OPTIMIZE_LIMIT ){
141228      nLimit = 0;
141229    }else{
141230      nLimit = SQLITE_DEFAULT_OPTIMIZE_LIMIT;
141231    }
141232    iTabCur = pParse->nTab++;
141233    for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
141234      if( iDb==1 ) continue;
141235      sqlite3CodeVerifySchema(pParse, iDb);
141236      pSchema = db->aDb[iDb].pSchema;
141237      for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
141238        pTab = (Table*)sqliteHashData(k);
141239
141240        /* This only works for ordinary tables */
141241        if( !IsOrdinaryTable(pTab) ) continue;
141242
141243        /* Do not scan system tables */
141244        if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ) continue;
141245
141246        /* Find the size of the table as last recorded in sqlite_stat1.
141247        ** If any index is unanalyzed, then the threshold is -1 to
141248        ** indicate a new, unanalyzed index
141249        */
141250        szThreshold = pTab->nRowLogEst;
141251        nIndex = 0;
141252        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
141253          nIndex++;
141254          if( !pIdx->hasStat1 ){
141255            szThreshold = -1; /* Always analyze if any index lacks statistics */
141256          }
141257        }
141258
141259        /* If table pTab has not been used in a way that would benefit from
141260        ** having analysis statistics during the current session, then skip it,
141261        ** unless the 0x10000 MASK bit is set. */
141262        if( (pTab->tabFlags & TF_MaybeReanalyze)!=0 ){
141263          /* Check for size change if stat1 has been used for a query */
141264        }else if( opMask & 0x10000 ){
141265          /* Check for size change if 0x10000 is set */
141266        }else if( pTab->pIndex!=0 && szThreshold<0 ){
141267          /* Do analysis if unanalyzed indexes exists */
141268        }else{
141269          /* Otherwise, we can skip this table */
141270          continue;
141271        }
141272
141273        nCheck++;
141274        if( nCheck==2 ){
141275          /* If ANALYZE might be invoked two or more times, hold a write
141276          ** transaction for efficiency */
141277          sqlite3BeginWriteOperation(pParse, 0, iDb);
141278        }
141279        nBtree += nIndex+1;
141280
141281        /* Reanalyze if the table is 10 times larger or smaller than
141282        ** the last analysis.  Unconditional reanalysis if there are
141283        ** unanalyzed indexes. */
141284        sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
141285        if( szThreshold>=0 ){
141286          const LogEst iRange = 33;   /* 10x size change */
141287          sqlite3VdbeAddOp4Int(v, OP_IfSizeBetween, iTabCur,
141288                         sqlite3VdbeCurrentAddr(v)+2+(opMask&1),
141289                         szThreshold>=iRange ? szThreshold-iRange : -1,
141290                         szThreshold+iRange);
141291          VdbeCoverage(v);
141292        }else{
141293          sqlite3VdbeAddOp2(v, OP_Rewind, iTabCur,
141294                         sqlite3VdbeCurrentAddr(v)+2+(opMask&1));
141295          VdbeCoverage(v);
141296        }
141297        zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
141298                                 db->aDb[iDb].zDbSName, pTab->zName);
141299        if( opMask & 0x01 ){
141300          int r1 = sqlite3GetTempReg(pParse);
141301          sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
141302          sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
141303        }else{
141304          sqlite3VdbeAddOp4(v, OP_SqlExec, nLimit ? 0x02 : 00, nLimit, 0,
141305                            zSubSql, P4_DYNAMIC);
141306        }
141307      }
141308    }
141309    sqlite3VdbeAddOp0(v, OP_Expire);
141310
141311    /* In a schema with a large number of tables and indexes, scale back
141312    ** the analysis_limit to avoid excess run-time in the worst case.
141313    */
141314    if( !db->mallocFailed && nLimit>0 && nBtree>100 ){
141315      int iAddr, iEnd;
141316      VdbeOp *aOp;
141317      nLimit = 100*nLimit/nBtree;
141318      if( nLimit<100 ) nLimit = 100;
141319      aOp = sqlite3VdbeGetOp(v, 0);
141320      iEnd = sqlite3VdbeCurrentAddr(v);
141321      for(iAddr=0; iAddr<iEnd; iAddr++){
141322        if( aOp[iAddr].opcode==OP_SqlExec ) aOp[iAddr].p2 = nLimit;
141323      }
141324    }
141325    break;
141326  }
141327
141328  /*
141329  **   PRAGMA busy_timeout
141330  **   PRAGMA busy_timeout = N
141331  **
141332  ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
141333  ** if one is set.  If no busy handler or a different busy handler is set
141334  ** then 0 is returned.  Setting the busy_timeout to 0 or negative
141335  ** disables the timeout.
141336  */
141337  /*case PragTyp_BUSY_TIMEOUT*/ default: {
141338    assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
141339    if( zRight ){
141340      sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
141341    }
141342    returnSingleInt(v, db->busyTimeout);
141343    break;
141344  }
141345
141346  /*
141347  **   PRAGMA soft_heap_limit
141348  **   PRAGMA soft_heap_limit = N
141349  **
141350  ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
141351  ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
141352  ** specified and is a non-negative integer.
141353  ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
141354  ** returns the same integer that would be returned by the
141355  ** sqlite3_soft_heap_limit64(-1) C-language function.
141356  */
141357  case PragTyp_SOFT_HEAP_LIMIT: {
141358    sqlite3_int64 N;
141359    if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
141360      sqlite3_soft_heap_limit64(N);
141361    }
141362    returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
141363    break;
141364  }
141365
141366  /*
141367  **   PRAGMA hard_heap_limit
141368  **   PRAGMA hard_heap_limit = N
141369  **
141370  ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
141371  ** limit.  The hard heap limit can be activated or lowered by this
141372  ** pragma, but not raised or deactivated.  Only the
141373  ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
141374  ** the hard heap limit.  This allows an application to set a heap limit
141375  ** constraint that cannot be relaxed by an untrusted SQL script.
141376  */
141377  case PragTyp_HARD_HEAP_LIMIT: {
141378    sqlite3_int64 N;
141379    if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
141380      sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);
141381      if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N);
141382    }
141383    returnSingleInt(v, sqlite3_hard_heap_limit64(-1));
141384    break;
141385  }
141386
141387  /*
141388  **   PRAGMA threads
141389  **   PRAGMA threads = N
141390  **
141391  ** Configure the maximum number of worker threads.  Return the new
141392  ** maximum, which might be less than requested.
141393  */
141394  case PragTyp_THREADS: {
141395    sqlite3_int64 N;
141396    if( zRight
141397     && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
141398     && N>=0
141399    ){
141400      sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
141401    }
141402    returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
141403    break;
141404  }
141405
141406  /*
141407  **   PRAGMA analysis_limit
141408  **   PRAGMA analysis_limit = N
141409  **
141410  ** Configure the maximum number of rows that ANALYZE will examine
141411  ** in each index that it looks at.  Return the new limit.
141412  */
141413  case PragTyp_ANALYSIS_LIMIT: {
141414    sqlite3_int64 N;
141415    if( zRight
141416     && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK /* IMP: R-40975-20399 */
141417     && N>=0
141418    ){
141419      db->nAnalysisLimit = (int)(N&0x7fffffff);
141420    }
141421    returnSingleInt(v, db->nAnalysisLimit); /* IMP: R-57594-65522 */
141422    break;
141423  }
141424
141425#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
141426  /*
141427  ** Report the current state of file logs for all databases
141428  */
141429  case PragTyp_LOCK_STATUS: {
141430    static const char *const azLockName[] = {
141431      "unlocked", "shared", "reserved", "pending", "exclusive"
141432    };
141433    int i;
141434    pParse->nMem = 2;
141435    for(i=0; i<db->nDb; i++){
141436      Btree *pBt;
141437      const char *zState = "unknown";
141438      int j;
141439      if( db->aDb[i].zDbSName==0 ) continue;
141440      pBt = db->aDb[i].pBt;
141441      if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
141442        zState = "closed";
141443      }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
141444                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
141445         zState = azLockName[j];
141446      }
141447      sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
141448    }
141449    break;
141450  }
141451#endif
141452
141453#if defined(SQLITE_ENABLE_CEROD)
141454  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
141455    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
141456      sqlite3_activate_cerod(&zRight[6]);
141457    }
141458  }
141459  break;
141460#endif
141461
141462  } /* End of the PRAGMA switch */
141463
141464  /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
141465  ** purpose is to execute assert() statements to verify that if the
141466  ** PragFlg_NoColumns1 flag is set and the caller specified an argument
141467  ** to the PRAGMA, the implementation has not added any OP_ResultRow
141468  ** instructions to the VM.  */
141469  if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
141470    sqlite3VdbeVerifyNoResultRow(v);
141471  }
141472
141473pragma_out:
141474  sqlite3DbFree(db, zLeft);
141475  sqlite3DbFree(db, zRight);
141476}
141477#ifndef SQLITE_OMIT_VIRTUALTABLE
141478/*****************************************************************************
141479** Implementation of an eponymous virtual table that runs a pragma.
141480**
141481*/
141482typedef struct PragmaVtab PragmaVtab;
141483typedef struct PragmaVtabCursor PragmaVtabCursor;
141484struct PragmaVtab {
141485  sqlite3_vtab base;        /* Base class.  Must be first */
141486  sqlite3 *db;              /* The database connection to which it belongs */
141487  const PragmaName *pName;  /* Name of the pragma */
141488  u8 nHidden;               /* Number of hidden columns */
141489  u8 iHidden;               /* Index of the first hidden column */
141490};
141491struct PragmaVtabCursor {
141492  sqlite3_vtab_cursor base; /* Base class.  Must be first */
141493  sqlite3_stmt *pPragma;    /* The pragma statement to run */
141494  sqlite_int64 iRowid;      /* Current rowid */
141495  char *azArg[2];           /* Value of the argument and schema */
141496};
141497
141498/*
141499** Pragma virtual table module xConnect method.
141500*/
141501static int pragmaVtabConnect(
141502  sqlite3 *db,
141503  void *pAux,
141504  int argc, const char *const*argv,
141505  sqlite3_vtab **ppVtab,
141506  char **pzErr
141507){
141508  const PragmaName *pPragma = (const PragmaName*)pAux;
141509  PragmaVtab *pTab = 0;
141510  int rc;
141511  int i, j;
141512  char cSep = '(';
141513  StrAccum acc;
141514  char zBuf[200];
141515
141516  UNUSED_PARAMETER(argc);
141517  UNUSED_PARAMETER(argv);
141518  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
141519  sqlite3_str_appendall(&acc, "CREATE TABLE x");
141520  for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
141521    sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
141522    cSep = ',';
141523  }
141524  if( i==0 ){
141525    sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
141526    i++;
141527  }
141528  j = 0;
141529  if( pPragma->mPragFlg & PragFlg_Result1 ){
141530    sqlite3_str_appendall(&acc, ",arg HIDDEN");
141531    j++;
141532  }
141533  if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
141534    sqlite3_str_appendall(&acc, ",schema HIDDEN");
141535    j++;
141536  }
141537  sqlite3_str_append(&acc, ")", 1);
141538  sqlite3StrAccumFinish(&acc);
141539  assert( strlen(zBuf) < sizeof(zBuf)-1 );
141540  rc = sqlite3_declare_vtab(db, zBuf);
141541  if( rc==SQLITE_OK ){
141542    pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
141543    if( pTab==0 ){
141544      rc = SQLITE_NOMEM;
141545    }else{
141546      memset(pTab, 0, sizeof(PragmaVtab));
141547      pTab->pName = pPragma;
141548      pTab->db = db;
141549      pTab->iHidden = i;
141550      pTab->nHidden = j;
141551    }
141552  }else{
141553    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
141554  }
141555
141556  *ppVtab = (sqlite3_vtab*)pTab;
141557  return rc;
141558}
141559
141560/*
141561** Pragma virtual table module xDisconnect method.
141562*/
141563static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
141564  PragmaVtab *pTab = (PragmaVtab*)pVtab;
141565  sqlite3_free(pTab);
141566  return SQLITE_OK;
141567}
141568
141569/* Figure out the best index to use to search a pragma virtual table.
141570**
141571** There are not really any index choices.  But we want to encourage the
141572** query planner to give == constraints on as many hidden parameters as
141573** possible, and especially on the first hidden parameter.  So return a
141574** high cost if hidden parameters are unconstrained.
141575*/
141576static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
141577  PragmaVtab *pTab = (PragmaVtab*)tab;
141578  const struct sqlite3_index_constraint *pConstraint;
141579  int i, j;
141580  int seen[2];
141581
141582  pIdxInfo->estimatedCost = (double)1;
141583  if( pTab->nHidden==0 ){ return SQLITE_OK; }
141584  pConstraint = pIdxInfo->aConstraint;
141585  seen[0] = 0;
141586  seen[1] = 0;
141587  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
141588    if( pConstraint->iColumn < pTab->iHidden ) continue;
141589    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
141590    if( pConstraint->usable==0 ) return SQLITE_CONSTRAINT;
141591    j = pConstraint->iColumn - pTab->iHidden;
141592    assert( j < 2 );
141593    seen[j] = i+1;
141594  }
141595  if( seen[0]==0 ){
141596    pIdxInfo->estimatedCost = (double)2147483647;
141597    pIdxInfo->estimatedRows = 2147483647;
141598    return SQLITE_OK;
141599  }
141600  j = seen[0]-1;
141601  pIdxInfo->aConstraintUsage[j].argvIndex = 1;
141602  pIdxInfo->aConstraintUsage[j].omit = 1;
141603  pIdxInfo->estimatedCost = (double)20;
141604  pIdxInfo->estimatedRows = 20;
141605  if( seen[1] ){
141606    j = seen[1]-1;
141607    pIdxInfo->aConstraintUsage[j].argvIndex = 2;
141608    pIdxInfo->aConstraintUsage[j].omit = 1;
141609  }
141610  return SQLITE_OK;
141611}
141612
141613/* Create a new cursor for the pragma virtual table */
141614static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
141615  PragmaVtabCursor *pCsr;
141616  pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
141617  if( pCsr==0 ) return SQLITE_NOMEM;
141618  memset(pCsr, 0, sizeof(PragmaVtabCursor));
141619  pCsr->base.pVtab = pVtab;
141620  *ppCursor = &pCsr->base;
141621  return SQLITE_OK;
141622}
141623
141624/* Clear all content from pragma virtual table cursor. */
141625static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
141626  int i;
141627  sqlite3_finalize(pCsr->pPragma);
141628  pCsr->pPragma = 0;
141629  pCsr->iRowid = 0;
141630  for(i=0; i<ArraySize(pCsr->azArg); i++){
141631    sqlite3_free(pCsr->azArg[i]);
141632    pCsr->azArg[i] = 0;
141633  }
141634}
141635
141636/* Close a pragma virtual table cursor */
141637static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
141638  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
141639  pragmaVtabCursorClear(pCsr);
141640  sqlite3_free(pCsr);
141641  return SQLITE_OK;
141642}
141643
141644/* Advance the pragma virtual table cursor to the next row */
141645static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
141646  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
141647  int rc = SQLITE_OK;
141648
141649  /* Increment the xRowid value */
141650  pCsr->iRowid++;
141651  assert( pCsr->pPragma );
141652  if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
141653    rc = sqlite3_finalize(pCsr->pPragma);
141654    pCsr->pPragma = 0;
141655    pragmaVtabCursorClear(pCsr);
141656  }
141657  return rc;
141658}
141659
141660/*
141661** Pragma virtual table module xFilter method.
141662*/
141663static int pragmaVtabFilter(
141664  sqlite3_vtab_cursor *pVtabCursor,
141665  int idxNum, const char *idxStr,
141666  int argc, sqlite3_value **argv
141667){
141668  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
141669  PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
141670  int rc;
141671  int i, j;
141672  StrAccum acc;
141673  char *zSql;
141674
141675  UNUSED_PARAMETER(idxNum);
141676  UNUSED_PARAMETER(idxStr);
141677  pragmaVtabCursorClear(pCsr);
141678  j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
141679  for(i=0; i<argc; i++, j++){
141680    const char *zText = (const char*)sqlite3_value_text(argv[i]);
141681    assert( j<ArraySize(pCsr->azArg) );
141682    assert( pCsr->azArg[j]==0 );
141683    if( zText ){
141684      pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
141685      if( pCsr->azArg[j]==0 ){
141686        return SQLITE_NOMEM;
141687      }
141688    }
141689  }
141690  sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
141691  sqlite3_str_appendall(&acc, "PRAGMA ");
141692  if( pCsr->azArg[1] ){
141693    sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
141694  }
141695  sqlite3_str_appendall(&acc, pTab->pName->zName);
141696  if( pCsr->azArg[0] ){
141697    sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
141698  }
141699  zSql = sqlite3StrAccumFinish(&acc);
141700  if( zSql==0 ) return SQLITE_NOMEM;
141701  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
141702  sqlite3_free(zSql);
141703  if( rc!=SQLITE_OK ){
141704    pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
141705    return rc;
141706  }
141707  return pragmaVtabNext(pVtabCursor);
141708}
141709
141710/*
141711** Pragma virtual table module xEof method.
141712*/
141713static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
141714  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
141715  return (pCsr->pPragma==0);
141716}
141717
141718/* The xColumn method simply returns the corresponding column from
141719** the PRAGMA.
141720*/
141721static int pragmaVtabColumn(
141722  sqlite3_vtab_cursor *pVtabCursor,
141723  sqlite3_context *ctx,
141724  int i
141725){
141726  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
141727  PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
141728  if( i<pTab->iHidden ){
141729    sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
141730  }else{
141731    sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
141732  }
141733  return SQLITE_OK;
141734}
141735
141736/*
141737** Pragma virtual table module xRowid method.
141738*/
141739static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
141740  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
141741  *p = pCsr->iRowid;
141742  return SQLITE_OK;
141743}
141744
141745/* The pragma virtual table object */
141746static const sqlite3_module pragmaVtabModule = {
141747  0,                           /* iVersion */
141748  0,                           /* xCreate - create a table */
141749  pragmaVtabConnect,           /* xConnect - connect to an existing table */
141750  pragmaVtabBestIndex,         /* xBestIndex - Determine search strategy */
141751  pragmaVtabDisconnect,        /* xDisconnect - Disconnect from a table */
141752  0,                           /* xDestroy - Drop a table */
141753  pragmaVtabOpen,              /* xOpen - open a cursor */
141754  pragmaVtabClose,             /* xClose - close a cursor */
141755  pragmaVtabFilter,            /* xFilter - configure scan constraints */
141756  pragmaVtabNext,              /* xNext - advance a cursor */
141757  pragmaVtabEof,               /* xEof */
141758  pragmaVtabColumn,            /* xColumn - read data */
141759  pragmaVtabRowid,             /* xRowid - read data */
141760  0,                           /* xUpdate - write data */
141761  0,                           /* xBegin - begin transaction */
141762  0,                           /* xSync - sync transaction */
141763  0,                           /* xCommit - commit transaction */
141764  0,                           /* xRollback - rollback transaction */
141765  0,                           /* xFindFunction - function overloading */
141766  0,                           /* xRename - rename the table */
141767  0,                           /* xSavepoint */
141768  0,                           /* xRelease */
141769  0,                           /* xRollbackTo */
141770  0,                           /* xShadowName */
141771  0                            /* xIntegrity */
141772};
141773
141774/*
141775** Check to see if zTabName is really the name of a pragma.  If it is,
141776** then register an eponymous virtual table for that pragma and return
141777** a pointer to the Module object for the new virtual table.
141778*/
141779SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
141780  const PragmaName *pName;
141781  assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
141782  pName = pragmaLocate(zName+7);
141783  if( pName==0 ) return 0;
141784  if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
141785  assert( sqlite3HashFind(&db->aModule, zName)==0 );
141786  return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
141787}
141788
141789#endif /* SQLITE_OMIT_VIRTUALTABLE */
141790
141791#endif /* SQLITE_OMIT_PRAGMA */
141792
141793/************** End of pragma.c **********************************************/
141794/************** Begin file prepare.c *****************************************/
141795/*
141796** 2005 May 25
141797**
141798** The author disclaims copyright to this source code.  In place of
141799** a legal notice, here is a blessing:
141800**
141801**    May you do good and not evil.
141802**    May you find forgiveness for yourself and forgive others.
141803**    May you share freely, never taking more than you give.
141804**
141805*************************************************************************
141806** This file contains the implementation of the sqlite3_prepare()
141807** interface, and routines that contribute to loading the database schema
141808** from disk.
141809*/
141810/* #include "sqliteInt.h" */
141811
141812/*
141813** Fill the InitData structure with an error message that indicates
141814** that the database is corrupt.
141815*/
141816static void corruptSchema(
141817  InitData *pData,     /* Initialization context */
141818  char **azObj,        /* Type and name of object being parsed */
141819  const char *zExtra   /* Error information */
141820){
141821  sqlite3 *db = pData->db;
141822  if( db->mallocFailed ){
141823    pData->rc = SQLITE_NOMEM_BKPT;
141824  }else if( pData->pzErrMsg[0]!=0 ){
141825    /* A error message has already been generated.  Do not overwrite it */
141826  }else if( pData->mInitFlags & (INITFLAG_AlterMask) ){
141827    static const char *azAlterType[] = {
141828       "rename",
141829       "drop column",
141830       "add column"
141831    };
141832    *pData->pzErrMsg = sqlite3MPrintf(db,
141833        "error in %s %s after %s: %s", azObj[0], azObj[1],
141834        azAlterType[(pData->mInitFlags&INITFLAG_AlterMask)-1],
141835        zExtra
141836    );
141837    pData->rc = SQLITE_ERROR;
141838  }else if( db->flags & SQLITE_WriteSchema ){
141839    pData->rc = SQLITE_CORRUPT_BKPT;
141840  }else{
141841    char *z;
141842    const char *zObj = azObj[1] ? azObj[1] : "?";
141843    z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
141844    if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
141845    *pData->pzErrMsg = z;
141846    pData->rc = SQLITE_CORRUPT_BKPT;
141847  }
141848}
141849
141850/*
141851** Check to see if any sibling index (another index on the same table)
141852** of pIndex has the same root page number, and if it does, return true.
141853** This would indicate a corrupt schema.
141854*/
141855SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index *pIndex){
141856  Index *p;
141857  for(p=pIndex->pTable->pIndex; p; p=p->pNext){
141858    if( p->tnum==pIndex->tnum && p!=pIndex ) return 1;
141859  }
141860  return 0;
141861}
141862
141863/* forward declaration */
141864static int sqlite3Prepare(
141865  sqlite3 *db,              /* Database handle. */
141866  const char *zSql,         /* UTF-8 encoded SQL statement. */
141867  int nBytes,               /* Length of zSql in bytes. */
141868  u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
141869  Vdbe *pReprepare,         /* VM being reprepared */
141870  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
141871  const char **pzTail       /* OUT: End of parsed string */
141872);
141873
141874
141875/*
141876** This is the callback routine for the code that initializes the
141877** database.  See sqlite3Init() below for additional information.
141878** This routine is also called from the OP_ParseSchema opcode of the VDBE.
141879**
141880** Each callback contains the following information:
141881**
141882**     argv[0] = type of object: "table", "index", "trigger", or "view".
141883**     argv[1] = name of thing being created
141884**     argv[2] = associated table if an index or trigger
141885**     argv[3] = root page number for table or index. 0 for trigger or view.
141886**     argv[4] = SQL text for the CREATE statement.
141887**
141888*/
141889SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
141890  InitData *pData = (InitData*)pInit;
141891  sqlite3 *db = pData->db;
141892  int iDb = pData->iDb;
141893
141894  assert( argc==5 );
141895  UNUSED_PARAMETER2(NotUsed, argc);
141896  assert( sqlite3_mutex_held(db->mutex) );
141897  db->mDbFlags |= DBFLAG_EncodingFixed;
141898  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
141899  pData->nInitRow++;
141900  if( db->mallocFailed ){
141901    corruptSchema(pData, argv, 0);
141902    return 1;
141903  }
141904
141905  assert( iDb>=0 && iDb<db->nDb );
141906  if( argv[3]==0 ){
141907    corruptSchema(pData, argv, 0);
141908  }else if( argv[4]
141909         && 'c'==sqlite3UpperToLower[(unsigned char)argv[4][0]]
141910         && 'r'==sqlite3UpperToLower[(unsigned char)argv[4][1]] ){
141911    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
141912    ** But because db->init.busy is set to 1, no VDBE code is generated
141913    ** or executed.  All the parser does is build the internal data
141914    ** structures that describe the table, index, or view.
141915    **
141916    ** No other valid SQL statement, other than the variable CREATE statements,
141917    ** can begin with the letters "C" and "R".  Thus, it is not possible run
141918    ** any other kind of statement while parsing the schema, even a corrupt
141919    ** schema.
141920    */
141921    int rc;
141922    u8 saved_iDb = db->init.iDb;
141923    sqlite3_stmt *pStmt;
141924    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
141925
141926    assert( db->init.busy );
141927    db->init.iDb = iDb;
141928    if( sqlite3GetUInt32(argv[3], &db->init.newTnum)==0
141929     || (db->init.newTnum>pData->mxPage && pData->mxPage>0)
141930    ){
141931      if( sqlite3Config.bExtraSchemaChecks ){
141932        corruptSchema(pData, argv, "invalid rootpage");
141933      }
141934    }
141935    db->init.orphanTrigger = 0;
141936    db->init.azInit = (const char**)argv;
141937    pStmt = 0;
141938    TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0);
141939    rc = db->errCode;
141940    assert( (rc&0xFF)==(rcp&0xFF) );
141941    db->init.iDb = saved_iDb;
141942    /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */
141943    if( SQLITE_OK!=rc ){
141944      if( db->init.orphanTrigger ){
141945        assert( iDb==1 );
141946      }else{
141947        if( rc > pData->rc ) pData->rc = rc;
141948        if( rc==SQLITE_NOMEM ){
141949          sqlite3OomFault(db);
141950        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
141951          corruptSchema(pData, argv, sqlite3_errmsg(db));
141952        }
141953      }
141954    }
141955    db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
141956    sqlite3_finalize(pStmt);
141957  }else if( argv[1]==0 || (argv[4]!=0 && argv[4][0]!=0) ){
141958    corruptSchema(pData, argv, 0);
141959  }else{
141960    /* If the SQL column is blank it means this is an index that
141961    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
141962    ** constraint for a CREATE TABLE.  The index should have already
141963    ** been created when we processed the CREATE TABLE.  All we have
141964    ** to do here is record the root page number for that index.
141965    */
141966    Index *pIndex;
141967    pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName);
141968    if( pIndex==0 ){
141969      corruptSchema(pData, argv, "orphan index");
141970    }else
141971    if( sqlite3GetUInt32(argv[3],&pIndex->tnum)==0
141972     || pIndex->tnum<2
141973     || pIndex->tnum>pData->mxPage
141974     || sqlite3IndexHasDuplicateRootPage(pIndex)
141975    ){
141976      if( sqlite3Config.bExtraSchemaChecks ){
141977        corruptSchema(pData, argv, "invalid rootpage");
141978      }
141979    }
141980  }
141981  return 0;
141982}
141983
141984/*
141985** Attempt to read the database schema and initialize internal
141986** data structures for a single database file.  The index of the
141987** database file is given by iDb.  iDb==0 is used for the main
141988** database.  iDb==1 should never be used.  iDb>=2 is used for
141989** auxiliary databases.  Return one of the SQLITE_ error codes to
141990** indicate success or failure.
141991*/
141992SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){
141993  int rc;
141994  int i;
141995#ifndef SQLITE_OMIT_DEPRECATED
141996  int size;
141997#endif
141998  Db *pDb;
141999  char const *azArg[6];
142000  int meta[5];
142001  InitData initData;
142002  const char *zSchemaTabName;
142003  int openedTransaction = 0;
142004  int mask = ((db->mDbFlags & DBFLAG_EncodingFixed) | ~DBFLAG_EncodingFixed);
142005
142006  assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
142007  assert( iDb>=0 && iDb<db->nDb );
142008  assert( db->aDb[iDb].pSchema );
142009  assert( sqlite3_mutex_held(db->mutex) );
142010  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
142011
142012  db->init.busy = 1;
142013
142014  /* Construct the in-memory representation schema tables (sqlite_schema or
142015  ** sqlite_temp_schema) by invoking the parser directly.  The appropriate
142016  ** table name will be inserted automatically by the parser so we can just
142017  ** use the abbreviation "x" here.  The parser will also automatically tag
142018  ** the schema table as read-only. */
142019  azArg[0] = "table";
142020  azArg[1] = zSchemaTabName = SCHEMA_TABLE(iDb);
142021  azArg[2] = azArg[1];
142022  azArg[3] = "1";
142023  azArg[4] = "CREATE TABLE x(type text,name text,tbl_name text,"
142024                            "rootpage int,sql text)";
142025  azArg[5] = 0;
142026  initData.db = db;
142027  initData.iDb = iDb;
142028  initData.rc = SQLITE_OK;
142029  initData.pzErrMsg = pzErrMsg;
142030  initData.mInitFlags = mFlags;
142031  initData.nInitRow = 0;
142032  initData.mxPage = 0;
142033  sqlite3InitCallback(&initData, 5, (char **)azArg, 0);
142034  db->mDbFlags &= mask;
142035  if( initData.rc ){
142036    rc = initData.rc;
142037    goto error_out;
142038  }
142039
142040  /* Create a cursor to hold the database open
142041  */
142042  pDb = &db->aDb[iDb];
142043  if( pDb->pBt==0 ){
142044    assert( iDb==1 );
142045    DbSetProperty(db, 1, DB_SchemaLoaded);
142046    rc = SQLITE_OK;
142047    goto error_out;
142048  }
142049
142050  /* If there is not already a read-only (or read-write) transaction opened
142051  ** on the b-tree database, open one now. If a transaction is opened, it
142052  ** will be closed before this function returns.  */
142053  sqlite3BtreeEnter(pDb->pBt);
142054  if( sqlite3BtreeTxnState(pDb->pBt)==SQLITE_TXN_NONE ){
142055    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
142056    if( rc!=SQLITE_OK ){
142057      sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
142058      goto initone_error_out;
142059    }
142060    openedTransaction = 1;
142061  }
142062
142063  /* Get the database meta information.
142064  **
142065  ** Meta values are as follows:
142066  **    meta[0]   Schema cookie.  Changes with each schema change.
142067  **    meta[1]   File format of schema layer.
142068  **    meta[2]   Size of the page cache.
142069  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
142070  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
142071  **    meta[5]   User version
142072  **    meta[6]   Incremental vacuum mode
142073  **    meta[7]   unused
142074  **    meta[8]   unused
142075  **    meta[9]   unused
142076  **
142077  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
142078  ** the possible values of meta[4].
142079  */
142080  for(i=0; i<ArraySize(meta); i++){
142081    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
142082  }
142083  if( (db->flags & SQLITE_ResetDatabase)!=0 ){
142084    memset(meta, 0, sizeof(meta));
142085  }
142086  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
142087
142088  /* If opening a non-empty database, check the text encoding. For the
142089  ** main database, set sqlite3.enc to the encoding of the main database.
142090  ** For an attached db, it is an error if the encoding is not the same
142091  ** as sqlite3.enc.
142092  */
142093  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
142094    if( iDb==0 && (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
142095      u8 encoding;
142096#ifndef SQLITE_OMIT_UTF16
142097      /* If opening the main database, set ENC(db). */
142098      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
142099      if( encoding==0 ) encoding = SQLITE_UTF8;
142100#else
142101      encoding = SQLITE_UTF8;
142102#endif
142103      if( db->nVdbeActive>0 && encoding!=ENC(db)
142104       && (db->mDbFlags & DBFLAG_Vacuum)==0
142105      ){
142106        rc = SQLITE_LOCKED;
142107        goto initone_error_out;
142108      }else{
142109        sqlite3SetTextEncoding(db, encoding);
142110      }
142111    }else{
142112      /* If opening an attached database, the encoding much match ENC(db) */
142113      if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){
142114        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
142115            " text encoding as main database");
142116        rc = SQLITE_ERROR;
142117        goto initone_error_out;
142118      }
142119    }
142120  }
142121  pDb->pSchema->enc = ENC(db);
142122
142123  if( pDb->pSchema->cache_size==0 ){
142124#ifndef SQLITE_OMIT_DEPRECATED
142125    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
142126    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
142127    pDb->pSchema->cache_size = size;
142128#else
142129    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
142130#endif
142131    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
142132  }
142133
142134  /*
142135  ** file_format==1    Version 3.0.0.
142136  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
142137  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
142138  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
142139  */
142140  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
142141  if( pDb->pSchema->file_format==0 ){
142142    pDb->pSchema->file_format = 1;
142143  }
142144  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
142145    sqlite3SetString(pzErrMsg, db, "unsupported file format");
142146    rc = SQLITE_ERROR;
142147    goto initone_error_out;
142148  }
142149
142150  /* Ticket #2804:  When we open a database in the newer file format,
142151  ** clear the legacy_file_format pragma flag so that a VACUUM will
142152  ** not downgrade the database and thus invalidate any descending
142153  ** indices that the user might have created.
142154  */
142155  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
142156    db->flags &= ~(u64)SQLITE_LegacyFileFmt;
142157  }
142158
142159  /* Read the schema information out of the schema tables
142160  */
142161  assert( db->init.busy );
142162  initData.mxPage = sqlite3BtreeLastPage(pDb->pBt);
142163  {
142164    char *zSql;
142165    zSql = sqlite3MPrintf(db,
142166        "SELECT*FROM\"%w\".%s ORDER BY rowid",
142167        db->aDb[iDb].zDbSName, zSchemaTabName);
142168#ifndef SQLITE_OMIT_AUTHORIZATION
142169    {
142170      sqlite3_xauth xAuth;
142171      xAuth = db->xAuth;
142172      db->xAuth = 0;
142173#endif
142174      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
142175#ifndef SQLITE_OMIT_AUTHORIZATION
142176      db->xAuth = xAuth;
142177    }
142178#endif
142179    if( rc==SQLITE_OK ) rc = initData.rc;
142180    sqlite3DbFree(db, zSql);
142181#ifndef SQLITE_OMIT_ANALYZE
142182    if( rc==SQLITE_OK ){
142183      sqlite3AnalysisLoad(db, iDb);
142184    }
142185#endif
142186  }
142187  assert( pDb == &(db->aDb[iDb]) );
142188  if( db->mallocFailed ){
142189    rc = SQLITE_NOMEM_BKPT;
142190    sqlite3ResetAllSchemasOfConnection(db);
142191    pDb = &db->aDb[iDb];
142192  }else
142193  if( rc==SQLITE_OK || ((db->flags&SQLITE_NoSchemaError) && rc!=SQLITE_NOMEM)){
142194    /* Hack: If the SQLITE_NoSchemaError flag is set, then consider
142195    ** the schema loaded, even if errors (other than OOM) occurred. In
142196    ** this situation the current sqlite3_prepare() operation will fail,
142197    ** but the following one will attempt to compile the supplied statement
142198    ** against whatever subset of the schema was loaded before the error
142199    ** occurred.
142200    **
142201    ** The primary purpose of this is to allow access to the sqlite_schema
142202    ** table even when its contents have been corrupted.
142203    */
142204    DbSetProperty(db, iDb, DB_SchemaLoaded);
142205    rc = SQLITE_OK;
142206  }
142207
142208  /* Jump here for an error that occurs after successfully allocating
142209  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
142210  ** before that point, jump to error_out.
142211  */
142212initone_error_out:
142213  if( openedTransaction ){
142214    sqlite3BtreeCommit(pDb->pBt);
142215  }
142216  sqlite3BtreeLeave(pDb->pBt);
142217
142218error_out:
142219  if( rc ){
142220    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
142221      sqlite3OomFault(db);
142222    }
142223    sqlite3ResetOneSchema(db, iDb);
142224  }
142225  db->init.busy = 0;
142226  return rc;
142227}
142228
142229/*
142230** Initialize all database files - the main database file, the file
142231** used to store temporary tables, and any additional database files
142232** created using ATTACH statements.  Return a success code.  If an
142233** error occurs, write an error message into *pzErrMsg.
142234**
142235** After a database is initialized, the DB_SchemaLoaded bit is set
142236** bit is set in the flags field of the Db structure.
142237*/
142238SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
142239  int i, rc;
142240  int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
142241
142242  assert( sqlite3_mutex_held(db->mutex) );
142243  assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
142244  assert( db->init.busy==0 );
142245  ENC(db) = SCHEMA_ENC(db);
142246  assert( db->nDb>0 );
142247  /* Do the main schema first */
142248  if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
142249    rc = sqlite3InitOne(db, 0, pzErrMsg, 0);
142250    if( rc ) return rc;
142251  }
142252  /* All other schemas after the main schema. The "temp" schema must be last */
142253  for(i=db->nDb-1; i>0; i--){
142254    assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
142255    if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
142256      rc = sqlite3InitOne(db, i, pzErrMsg, 0);
142257      if( rc ) return rc;
142258    }
142259  }
142260  if( commit_internal ){
142261    sqlite3CommitInternalChanges(db);
142262  }
142263  return SQLITE_OK;
142264}
142265
142266/*
142267** This routine is a no-op if the database schema is already initialized.
142268** Otherwise, the schema is loaded. An error code is returned.
142269*/
142270SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
142271  int rc = SQLITE_OK;
142272  sqlite3 *db = pParse->db;
142273  assert( sqlite3_mutex_held(db->mutex) );
142274  if( !db->init.busy ){
142275    rc = sqlite3Init(db, &pParse->zErrMsg);
142276    if( rc!=SQLITE_OK ){
142277      pParse->rc = rc;
142278      pParse->nErr++;
142279    }else if( db->noSharedCache ){
142280      db->mDbFlags |= DBFLAG_SchemaKnownOk;
142281    }
142282  }
142283  return rc;
142284}
142285
142286
142287/*
142288** Check schema cookies in all databases.  If any cookie is out
142289** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
142290** make no changes to pParse->rc.
142291*/
142292static void schemaIsValid(Parse *pParse){
142293  sqlite3 *db = pParse->db;
142294  int iDb;
142295  int rc;
142296  int cookie;
142297
142298  assert( pParse->checkSchema );
142299  assert( sqlite3_mutex_held(db->mutex) );
142300  for(iDb=0; iDb<db->nDb; iDb++){
142301    int openedTransaction = 0;         /* True if a transaction is opened */
142302    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
142303    if( pBt==0 ) continue;
142304
142305    /* If there is not already a read-only (or read-write) transaction opened
142306    ** on the b-tree database, open one now. If a transaction is opened, it
142307    ** will be closed immediately after reading the meta-value. */
142308    if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_NONE ){
142309      rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
142310      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
142311        sqlite3OomFault(db);
142312        pParse->rc = SQLITE_NOMEM;
142313      }
142314      if( rc!=SQLITE_OK ) return;
142315      openedTransaction = 1;
142316    }
142317
142318    /* Read the schema cookie from the database. If it does not match the
142319    ** value stored as part of the in-memory schema representation,
142320    ** set Parse.rc to SQLITE_SCHEMA. */
142321    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
142322    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
142323    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
142324      if( DbHasProperty(db, iDb, DB_SchemaLoaded) ) pParse->rc = SQLITE_SCHEMA;
142325      sqlite3ResetOneSchema(db, iDb);
142326    }
142327
142328    /* Close the transaction, if one was opened. */
142329    if( openedTransaction ){
142330      sqlite3BtreeCommit(pBt);
142331    }
142332  }
142333}
142334
142335/*
142336** Convert a schema pointer into the iDb index that indicates
142337** which database file in db->aDb[] the schema refers to.
142338**
142339** If the same database is attached more than once, the first
142340** attached database is returned.
142341*/
142342SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
142343  int i = -32768;
142344
142345  /* If pSchema is NULL, then return -32768. This happens when code in
142346  ** expr.c is trying to resolve a reference to a transient table (i.e. one
142347  ** created by a sub-select). In this case the return value of this
142348  ** function should never be used.
142349  **
142350  ** We return -32768 instead of the more usual -1 simply because using
142351  ** -32768 as the incorrect index into db->aDb[] is much
142352  ** more likely to cause a segfault than -1 (of course there are assert()
142353  ** statements too, but it never hurts to play the odds) and
142354  ** -32768 will still fit into a 16-bit signed integer.
142355  */
142356  assert( sqlite3_mutex_held(db->mutex) );
142357  if( pSchema ){
142358    for(i=0; 1; i++){
142359      assert( i<db->nDb );
142360      if( db->aDb[i].pSchema==pSchema ){
142361        break;
142362      }
142363    }
142364    assert( i>=0 && i<db->nDb );
142365  }
142366  return i;
142367}
142368
142369/*
142370** Free all memory allocations in the pParse object
142371*/
142372SQLITE_PRIVATE void sqlite3ParseObjectReset(Parse *pParse){
142373  sqlite3 *db = pParse->db;
142374  assert( db!=0 );
142375  assert( db->pParse==pParse );
142376  assert( pParse->nested==0 );
142377#ifndef SQLITE_OMIT_SHARED_CACHE
142378  if( pParse->aTableLock ) sqlite3DbNNFreeNN(db, pParse->aTableLock);
142379#endif
142380  while( pParse->pCleanup ){
142381    ParseCleanup *pCleanup = pParse->pCleanup;
142382    pParse->pCleanup = pCleanup->pNext;
142383    pCleanup->xCleanup(db, pCleanup->pPtr);
142384    sqlite3DbNNFreeNN(db, pCleanup);
142385  }
142386  if( pParse->aLabel ) sqlite3DbNNFreeNN(db, pParse->aLabel);
142387  if( pParse->pConstExpr ){
142388    sqlite3ExprListDelete(db, pParse->pConstExpr);
142389  }
142390  assert( db->lookaside.bDisable >= pParse->disableLookaside );
142391  db->lookaside.bDisable -= pParse->disableLookaside;
142392  db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue;
142393  assert( pParse->db->pParse==pParse );
142394  db->pParse = pParse->pOuterParse;
142395}
142396
142397/*
142398** Add a new cleanup operation to a Parser.  The cleanup should happen when
142399** the parser object is destroyed.  But, beware: the cleanup might happen
142400** immediately.
142401**
142402** Use this mechanism for uncommon cleanups.  There is a higher setup
142403** cost for this mechanism (an extra malloc), so it should not be used
142404** for common cleanups that happen on most calls.  But for less
142405** common cleanups, we save a single NULL-pointer comparison in
142406** sqlite3ParseObjectReset(), which reduces the total CPU cycle count.
142407**
142408** If a memory allocation error occurs, then the cleanup happens immediately.
142409** When either SQLITE_DEBUG or SQLITE_COVERAGE_TEST are defined, the
142410** pParse->earlyCleanup flag is set in that case.  Calling code show verify
142411** that test cases exist for which this happens, to guard against possible
142412** use-after-free errors following an OOM.  The preferred way to do this is
142413** to immediately follow the call to this routine with:
142414**
142415**       testcase( pParse->earlyCleanup );
142416**
142417** This routine returns a copy of its pPtr input (the third parameter)
142418** except if an early cleanup occurs, in which case it returns NULL.  So
142419** another way to check for early cleanup is to check the return value.
142420** Or, stop using the pPtr parameter with this call and use only its
142421** return value thereafter.  Something like this:
142422**
142423**       pObj = sqlite3ParserAddCleanup(pParse, destructor, pObj);
142424*/
142425SQLITE_PRIVATE void *sqlite3ParserAddCleanup(
142426  Parse *pParse,                      /* Destroy when this Parser finishes */
142427  void (*xCleanup)(sqlite3*,void*),   /* The cleanup routine */
142428  void *pPtr                          /* Pointer to object to be cleaned up */
142429){
142430  ParseCleanup *pCleanup;
142431  if( sqlite3FaultSim(300) ){
142432    pCleanup = 0;
142433    sqlite3OomFault(pParse->db);
142434  }else{
142435    pCleanup = sqlite3DbMallocRaw(pParse->db, sizeof(*pCleanup));
142436  }
142437  if( pCleanup ){
142438    pCleanup->pNext = pParse->pCleanup;
142439    pParse->pCleanup = pCleanup;
142440    pCleanup->pPtr = pPtr;
142441    pCleanup->xCleanup = xCleanup;
142442  }else{
142443    xCleanup(pParse->db, pPtr);
142444    pPtr = 0;
142445#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
142446    pParse->earlyCleanup = 1;
142447#endif
142448  }
142449  return pPtr;
142450}
142451
142452/*
142453** Turn bulk memory into a valid Parse object and link that Parse object
142454** into database connection db.
142455**
142456** Call sqlite3ParseObjectReset() to undo this operation.
142457**
142458** Caution:  Do not confuse this routine with sqlite3ParseObjectInit() which
142459** is generated by Lemon.
142460*/
142461SQLITE_PRIVATE void sqlite3ParseObjectInit(Parse *pParse, sqlite3 *db){
142462  memset(PARSE_HDR(pParse), 0, PARSE_HDR_SZ);
142463  memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
142464  assert( db->pParse!=pParse );
142465  pParse->pOuterParse = db->pParse;
142466  db->pParse = pParse;
142467  pParse->db = db;
142468  if( db->mallocFailed ) sqlite3ErrorMsg(pParse, "out of memory");
142469}
142470
142471/*
142472** Maximum number of times that we will try again to prepare a statement
142473** that returns SQLITE_ERROR_RETRY.
142474*/
142475#ifndef SQLITE_MAX_PREPARE_RETRY
142476# define SQLITE_MAX_PREPARE_RETRY 25
142477#endif
142478
142479/*
142480** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
142481*/
142482static int sqlite3Prepare(
142483  sqlite3 *db,              /* Database handle. */
142484  const char *zSql,         /* UTF-8 encoded SQL statement. */
142485  int nBytes,               /* Length of zSql in bytes. */
142486  u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
142487  Vdbe *pReprepare,         /* VM being reprepared */
142488  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
142489  const char **pzTail       /* OUT: End of parsed string */
142490){
142491  int rc = SQLITE_OK;       /* Result code */
142492  int i;                    /* Loop counter */
142493  Parse sParse;             /* Parsing context */
142494
142495  /* sqlite3ParseObjectInit(&sParse, db); // inlined for performance */
142496  memset(PARSE_HDR(&sParse), 0, PARSE_HDR_SZ);
142497  memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
142498  sParse.pOuterParse = db->pParse;
142499  db->pParse = &sParse;
142500  sParse.db = db;
142501  if( pReprepare ){
142502    sParse.pReprepare = pReprepare;
142503    sParse.explain = sqlite3_stmt_isexplain((sqlite3_stmt*)pReprepare);
142504  }else{
142505    assert( sParse.pReprepare==0 );
142506  }
142507  assert( ppStmt && *ppStmt==0 );
142508  if( db->mallocFailed ){
142509    sqlite3ErrorMsg(&sParse, "out of memory");
142510    db->errCode = rc = SQLITE_NOMEM;
142511    goto end_prepare;
142512  }
142513  assert( sqlite3_mutex_held(db->mutex) );
142514
142515  /* For a long-term use prepared statement avoid the use of
142516  ** lookaside memory.
142517  */
142518  if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
142519    sParse.disableLookaside++;
142520    DisableLookaside;
142521  }
142522  sParse.prepFlags = prepFlags & 0xff;
142523
142524  /* Check to verify that it is possible to get a read lock on all
142525  ** database schemas.  The inability to get a read lock indicates that
142526  ** some other database connection is holding a write-lock, which in
142527  ** turn means that the other connection has made uncommitted changes
142528  ** to the schema.
142529  **
142530  ** Were we to proceed and prepare the statement against the uncommitted
142531  ** schema changes and if those schema changes are subsequently rolled
142532  ** back and different changes are made in their place, then when this
142533  ** prepared statement goes to run the schema cookie would fail to detect
142534  ** the schema change.  Disaster would follow.
142535  **
142536  ** This thread is currently holding mutexes on all Btrees (because
142537  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
142538  ** is not possible for another thread to start a new schema change
142539  ** while this routine is running.  Hence, we do not need to hold
142540  ** locks on the schema, we just need to make sure nobody else is
142541  ** holding them.
142542  **
142543  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
142544  ** but it does *not* override schema lock detection, so this all still
142545  ** works even if READ_UNCOMMITTED is set.
142546  */
142547  if( !db->noSharedCache ){
142548    for(i=0; i<db->nDb; i++) {
142549      Btree *pBt = db->aDb[i].pBt;
142550      if( pBt ){
142551        assert( sqlite3BtreeHoldsMutex(pBt) );
142552        rc = sqlite3BtreeSchemaLocked(pBt);
142553        if( rc ){
142554          const char *zDb = db->aDb[i].zDbSName;
142555          sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
142556          testcase( db->flags & SQLITE_ReadUncommit );
142557          goto end_prepare;
142558        }
142559      }
142560    }
142561  }
142562
142563#ifndef SQLITE_OMIT_VIRTUALTABLE
142564  if( db->pDisconnect ) sqlite3VtabUnlockList(db);
142565#endif
142566
142567  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
142568    char *zSqlCopy;
142569    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
142570    testcase( nBytes==mxLen );
142571    testcase( nBytes==mxLen+1 );
142572    if( nBytes>mxLen ){
142573      sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
142574      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
142575      goto end_prepare;
142576    }
142577    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
142578    if( zSqlCopy ){
142579      sqlite3RunParser(&sParse, zSqlCopy);
142580      sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
142581      sqlite3DbFree(db, zSqlCopy);
142582    }else{
142583      sParse.zTail = &zSql[nBytes];
142584    }
142585  }else{
142586    sqlite3RunParser(&sParse, zSql);
142587  }
142588  assert( 0==sParse.nQueryLoop );
142589
142590  if( pzTail ){
142591    *pzTail = sParse.zTail;
142592  }
142593
142594  if( db->init.busy==0 ){
142595    sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
142596  }
142597  if( db->mallocFailed ){
142598    sParse.rc = SQLITE_NOMEM_BKPT;
142599    sParse.checkSchema = 0;
142600  }
142601  if( sParse.rc!=SQLITE_OK && sParse.rc!=SQLITE_DONE ){
142602    if( sParse.checkSchema && db->init.busy==0 ){
142603      schemaIsValid(&sParse);
142604    }
142605    if( sParse.pVdbe ){
142606      sqlite3VdbeFinalize(sParse.pVdbe);
142607    }
142608    assert( 0==(*ppStmt) );
142609    rc = sParse.rc;
142610    if( sParse.zErrMsg ){
142611      sqlite3ErrorWithMsg(db, rc, "%s", sParse.zErrMsg);
142612      sqlite3DbFree(db, sParse.zErrMsg);
142613    }else{
142614      sqlite3Error(db, rc);
142615    }
142616  }else{
142617    assert( sParse.zErrMsg==0 );
142618    *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
142619    rc = SQLITE_OK;
142620    sqlite3ErrorClear(db);
142621  }
142622
142623
142624  /* Delete any TriggerPrg structures allocated while parsing this statement. */
142625  while( sParse.pTriggerPrg ){
142626    TriggerPrg *pT = sParse.pTriggerPrg;
142627    sParse.pTriggerPrg = pT->pNext;
142628    sqlite3DbFree(db, pT);
142629  }
142630
142631end_prepare:
142632
142633  sqlite3ParseObjectReset(&sParse);
142634  return rc;
142635}
142636static int sqlite3LockAndPrepare(
142637  sqlite3 *db,              /* Database handle. */
142638  const char *zSql,         /* UTF-8 encoded SQL statement. */
142639  int nBytes,               /* Length of zSql in bytes. */
142640  u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
142641  Vdbe *pOld,               /* VM being reprepared */
142642  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
142643  const char **pzTail       /* OUT: End of parsed string */
142644){
142645  int rc;
142646  int cnt = 0;
142647
142648#ifdef SQLITE_ENABLE_API_ARMOR
142649  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
142650#endif
142651  *ppStmt = 0;
142652  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
142653    return SQLITE_MISUSE_BKPT;
142654  }
142655  sqlite3_mutex_enter(db->mutex);
142656  sqlite3BtreeEnterAll(db);
142657  do{
142658    /* Make multiple attempts to compile the SQL, until it either succeeds
142659    ** or encounters a permanent error.  A schema problem after one schema
142660    ** reset is considered a permanent error. */
142661    rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
142662    assert( rc==SQLITE_OK || *ppStmt==0 );
142663    if( rc==SQLITE_OK || db->mallocFailed ) break;
142664  }while( (rc==SQLITE_ERROR_RETRY && (cnt++)<SQLITE_MAX_PREPARE_RETRY)
142665       || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
142666  sqlite3BtreeLeaveAll(db);
142667  rc = sqlite3ApiExit(db, rc);
142668  assert( (rc&db->errMask)==rc );
142669  db->busyHandler.nBusy = 0;
142670  sqlite3_mutex_leave(db->mutex);
142671  assert( rc==SQLITE_OK || (*ppStmt)==0 );
142672  return rc;
142673}
142674
142675
142676/*
142677** Rerun the compilation of a statement after a schema change.
142678**
142679** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
142680** if the statement cannot be recompiled because another connection has
142681** locked the sqlite3_schema table, return SQLITE_LOCKED. If any other error
142682** occurs, return SQLITE_SCHEMA.
142683*/
142684SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
142685  int rc;
142686  sqlite3_stmt *pNew;
142687  const char *zSql;
142688  sqlite3 *db;
142689  u8 prepFlags;
142690
142691  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
142692  zSql = sqlite3_sql((sqlite3_stmt *)p);
142693  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
142694  db = sqlite3VdbeDb(p);
142695  assert( sqlite3_mutex_held(db->mutex) );
142696  prepFlags = sqlite3VdbePrepareFlags(p);
142697  rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
142698  if( rc ){
142699    if( rc==SQLITE_NOMEM ){
142700      sqlite3OomFault(db);
142701    }
142702    assert( pNew==0 );
142703    return rc;
142704  }else{
142705    assert( pNew!=0 );
142706  }
142707  sqlite3VdbeSwap((Vdbe*)pNew, p);
142708  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
142709  sqlite3VdbeResetStepResult((Vdbe*)pNew);
142710  sqlite3VdbeFinalize((Vdbe*)pNew);
142711  return SQLITE_OK;
142712}
142713
142714
142715/*
142716** Two versions of the official API.  Legacy and new use.  In the legacy
142717** version, the original SQL text is not saved in the prepared statement
142718** and so if a schema change occurs, SQLITE_SCHEMA is returned by
142719** sqlite3_step().  In the new version, the original SQL text is retained
142720** and the statement is automatically recompiled if an schema change
142721** occurs.
142722*/
142723SQLITE_API int sqlite3_prepare(
142724  sqlite3 *db,              /* Database handle. */
142725  const char *zSql,         /* UTF-8 encoded SQL statement. */
142726  int nBytes,               /* Length of zSql in bytes. */
142727  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
142728  const char **pzTail       /* OUT: End of parsed string */
142729){
142730  int rc;
142731  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
142732  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
142733  return rc;
142734}
142735SQLITE_API int sqlite3_prepare_v2(
142736  sqlite3 *db,              /* Database handle. */
142737  const char *zSql,         /* UTF-8 encoded SQL statement. */
142738  int nBytes,               /* Length of zSql in bytes. */
142739  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
142740  const char **pzTail       /* OUT: End of parsed string */
142741){
142742  int rc;
142743  /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
142744  ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
142745  ** parameter.
142746  **
142747  ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
142748  rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
142749                             ppStmt,pzTail);
142750  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
142751  return rc;
142752}
142753SQLITE_API int sqlite3_prepare_v3(
142754  sqlite3 *db,              /* Database handle. */
142755  const char *zSql,         /* UTF-8 encoded SQL statement. */
142756  int nBytes,               /* Length of zSql in bytes. */
142757  unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
142758  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
142759  const char **pzTail       /* OUT: End of parsed string */
142760){
142761  int rc;
142762  /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
142763  ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
142764  ** which is a bit array consisting of zero or more of the
142765  ** SQLITE_PREPARE_* flags.
142766  **
142767  ** Proof by comparison to the implementation of sqlite3_prepare_v2()
142768  ** directly above. */
142769  rc = sqlite3LockAndPrepare(db,zSql,nBytes,
142770                 SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
142771                 0,ppStmt,pzTail);
142772  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
142773  return rc;
142774}
142775
142776
142777#ifndef SQLITE_OMIT_UTF16
142778/*
142779** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
142780*/
142781static int sqlite3Prepare16(
142782  sqlite3 *db,              /* Database handle. */
142783  const void *zSql,         /* UTF-16 encoded SQL statement. */
142784  int nBytes,               /* Length of zSql in bytes. */
142785  u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
142786  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
142787  const void **pzTail       /* OUT: End of parsed string */
142788){
142789  /* This function currently works by first transforming the UTF-16
142790  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
142791  ** tricky bit is figuring out the pointer to return in *pzTail.
142792  */
142793  char *zSql8;
142794  const char *zTail8 = 0;
142795  int rc = SQLITE_OK;
142796
142797#ifdef SQLITE_ENABLE_API_ARMOR
142798  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
142799#endif
142800  *ppStmt = 0;
142801  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
142802    return SQLITE_MISUSE_BKPT;
142803  }
142804  if( nBytes>=0 ){
142805    int sz;
142806    const char *z = (const char*)zSql;
142807    for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
142808    nBytes = sz;
142809  }
142810  sqlite3_mutex_enter(db->mutex);
142811  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
142812  if( zSql8 ){
142813    rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
142814  }
142815
142816  if( zTail8 && pzTail ){
142817    /* If sqlite3_prepare returns a tail pointer, we calculate the
142818    ** equivalent pointer into the UTF-16 string by counting the unicode
142819    ** characters between zSql8 and zTail8, and then returning a pointer
142820    ** the same number of characters into the UTF-16 string.
142821    */
142822    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
142823    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
142824  }
142825  sqlite3DbFree(db, zSql8);
142826  rc = sqlite3ApiExit(db, rc);
142827  sqlite3_mutex_leave(db->mutex);
142828  return rc;
142829}
142830
142831/*
142832** Two versions of the official API.  Legacy and new use.  In the legacy
142833** version, the original SQL text is not saved in the prepared statement
142834** and so if a schema change occurs, SQLITE_SCHEMA is returned by
142835** sqlite3_step().  In the new version, the original SQL text is retained
142836** and the statement is automatically recompiled if an schema change
142837** occurs.
142838*/
142839SQLITE_API int sqlite3_prepare16(
142840  sqlite3 *db,              /* Database handle. */
142841  const void *zSql,         /* UTF-16 encoded SQL statement. */
142842  int nBytes,               /* Length of zSql in bytes. */
142843  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
142844  const void **pzTail       /* OUT: End of parsed string */
142845){
142846  int rc;
142847  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
142848  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
142849  return rc;
142850}
142851SQLITE_API int sqlite3_prepare16_v2(
142852  sqlite3 *db,              /* Database handle. */
142853  const void *zSql,         /* UTF-16 encoded SQL statement. */
142854  int nBytes,               /* Length of zSql in bytes. */
142855  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
142856  const void **pzTail       /* OUT: End of parsed string */
142857){
142858  int rc;
142859  rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
142860  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
142861  return rc;
142862}
142863SQLITE_API int sqlite3_prepare16_v3(
142864  sqlite3 *db,              /* Database handle. */
142865  const void *zSql,         /* UTF-16 encoded SQL statement. */
142866  int nBytes,               /* Length of zSql in bytes. */
142867  unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
142868  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
142869  const void **pzTail       /* OUT: End of parsed string */
142870){
142871  int rc;
142872  rc = sqlite3Prepare16(db,zSql,nBytes,
142873         SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
142874         ppStmt,pzTail);
142875  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
142876  return rc;
142877}
142878
142879#endif /* SQLITE_OMIT_UTF16 */
142880
142881/************** End of prepare.c *********************************************/
142882/************** Begin file select.c ******************************************/
142883/*
142884** 2001 September 15
142885**
142886** The author disclaims copyright to this source code.  In place of
142887** a legal notice, here is a blessing:
142888**
142889**    May you do good and not evil.
142890**    May you find forgiveness for yourself and forgive others.
142891**    May you share freely, never taking more than you give.
142892**
142893*************************************************************************
142894** This file contains C code routines that are called by the parser
142895** to handle SELECT statements in SQLite.
142896*/
142897/* #include "sqliteInt.h" */
142898
142899/*
142900** An instance of the following object is used to record information about
142901** how to process the DISTINCT keyword, to simplify passing that information
142902** into the selectInnerLoop() routine.
142903*/
142904typedef struct DistinctCtx DistinctCtx;
142905struct DistinctCtx {
142906  u8 isTnct;      /* 0: Not distinct. 1: DISTICT  2: DISTINCT and ORDER BY */
142907  u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
142908  int tabTnct;    /* Ephemeral table used for DISTINCT processing */
142909  int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
142910};
142911
142912/*
142913** An instance of the following object is used to record information about
142914** the ORDER BY (or GROUP BY) clause of query is being coded.
142915**
142916** The aDefer[] array is used by the sorter-references optimization. For
142917** example, assuming there is no index that can be used for the ORDER BY,
142918** for the query:
142919**
142920**     SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
142921**
142922** it may be more efficient to add just the "a" values to the sorter, and
142923** retrieve the associated "bigblob" values directly from table t1 as the
142924** 10 smallest "a" values are extracted from the sorter.
142925**
142926** When the sorter-reference optimization is used, there is one entry in the
142927** aDefer[] array for each database table that may be read as values are
142928** extracted from the sorter.
142929*/
142930typedef struct SortCtx SortCtx;
142931struct SortCtx {
142932  ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
142933  int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
142934  int iECursor;         /* Cursor number for the sorter */
142935  int regReturn;        /* Register holding block-output return address */
142936  int labelBkOut;       /* Start label for the block-output subroutine */
142937  int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
142938  int labelDone;        /* Jump here when done, ex: LIMIT reached */
142939  int labelOBLopt;      /* Jump here when sorter is full */
142940  u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
142941#ifdef SQLITE_ENABLE_SORTER_REFERENCES
142942  u8 nDefer;            /* Number of valid entries in aDefer[] */
142943  struct DeferredCsr {
142944    Table *pTab;        /* Table definition */
142945    int iCsr;           /* Cursor number for table */
142946    int nKey;           /* Number of PK columns for table pTab (>=1) */
142947  } aDefer[4];
142948#endif
142949  struct RowLoadInfo *pDeferredRowLoad;  /* Deferred row loading info or NULL */
142950#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
142951  int addrPush;         /* First instruction to push data into sorter */
142952  int addrPushEnd;      /* Last instruction that pushes data into sorter */
142953#endif
142954};
142955#define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
142956
142957/*
142958** Delete all the content of a Select structure.  Deallocate the structure
142959** itself depending on the value of bFree
142960**
142961** If bFree==1, call sqlite3DbFree() on the p object.
142962** If bFree==0, Leave the first Select object unfreed
142963*/
142964static void clearSelect(sqlite3 *db, Select *p, int bFree){
142965  assert( db!=0 );
142966  while( p ){
142967    Select *pPrior = p->pPrior;
142968    sqlite3ExprListDelete(db, p->pEList);
142969    sqlite3SrcListDelete(db, p->pSrc);
142970    sqlite3ExprDelete(db, p->pWhere);
142971    sqlite3ExprListDelete(db, p->pGroupBy);
142972    sqlite3ExprDelete(db, p->pHaving);
142973    sqlite3ExprListDelete(db, p->pOrderBy);
142974    sqlite3ExprDelete(db, p->pLimit);
142975    if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
142976#ifndef SQLITE_OMIT_WINDOWFUNC
142977    if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
142978      sqlite3WindowListDelete(db, p->pWinDefn);
142979    }
142980    while( p->pWin ){
142981      assert( p->pWin->ppThis==&p->pWin );
142982      sqlite3WindowUnlinkFromSelect(p->pWin);
142983    }
142984#endif
142985    if( bFree ) sqlite3DbNNFreeNN(db, p);
142986    p = pPrior;
142987    bFree = 1;
142988  }
142989}
142990
142991/*
142992** Initialize a SelectDest structure.
142993*/
142994SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
142995  pDest->eDest = (u8)eDest;
142996  pDest->iSDParm = iParm;
142997  pDest->iSDParm2 = 0;
142998  pDest->zAffSdst = 0;
142999  pDest->iSdst = 0;
143000  pDest->nSdst = 0;
143001}
143002
143003
143004/*
143005** Allocate a new Select structure and return a pointer to that
143006** structure.
143007*/
143008SQLITE_PRIVATE Select *sqlite3SelectNew(
143009  Parse *pParse,        /* Parsing context */
143010  ExprList *pEList,     /* which columns to include in the result */
143011  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
143012  Expr *pWhere,         /* the WHERE clause */
143013  ExprList *pGroupBy,   /* the GROUP BY clause */
143014  Expr *pHaving,        /* the HAVING clause */
143015  ExprList *pOrderBy,   /* the ORDER BY clause */
143016  u32 selFlags,         /* Flag parameters, such as SF_Distinct */
143017  Expr *pLimit          /* LIMIT value.  NULL means not used */
143018){
143019  Select *pNew, *pAllocated;
143020  Select standin;
143021  pAllocated = pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
143022  if( pNew==0 ){
143023    assert( pParse->db->mallocFailed );
143024    pNew = &standin;
143025  }
143026  if( pEList==0 ){
143027    pEList = sqlite3ExprListAppend(pParse, 0,
143028                                   sqlite3Expr(pParse->db,TK_ASTERISK,0));
143029  }
143030  pNew->pEList = pEList;
143031  pNew->op = TK_SELECT;
143032  pNew->selFlags = selFlags;
143033  pNew->iLimit = 0;
143034  pNew->iOffset = 0;
143035  pNew->selId = ++pParse->nSelect;
143036  pNew->addrOpenEphm[0] = -1;
143037  pNew->addrOpenEphm[1] = -1;
143038  pNew->nSelectRow = 0;
143039  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
143040  pNew->pSrc = pSrc;
143041  pNew->pWhere = pWhere;
143042  pNew->pGroupBy = pGroupBy;
143043  pNew->pHaving = pHaving;
143044  pNew->pOrderBy = pOrderBy;
143045  pNew->pPrior = 0;
143046  pNew->pNext = 0;
143047  pNew->pLimit = pLimit;
143048  pNew->pWith = 0;
143049#ifndef SQLITE_OMIT_WINDOWFUNC
143050  pNew->pWin = 0;
143051  pNew->pWinDefn = 0;
143052#endif
143053  if( pParse->db->mallocFailed ) {
143054    clearSelect(pParse->db, pNew, pNew!=&standin);
143055    pAllocated = 0;
143056  }else{
143057    assert( pNew->pSrc!=0 || pParse->nErr>0 );
143058  }
143059  return pAllocated;
143060}
143061
143062
143063/*
143064** Delete the given Select structure and all of its substructures.
143065*/
143066SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
143067  if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
143068}
143069SQLITE_PRIVATE void sqlite3SelectDeleteGeneric(sqlite3 *db, void *p){
143070  if( ALWAYS(p) ) clearSelect(db, (Select*)p, 1);
143071}
143072
143073/*
143074** Return a pointer to the right-most SELECT statement in a compound.
143075*/
143076static Select *findRightmost(Select *p){
143077  while( p->pNext ) p = p->pNext;
143078  return p;
143079}
143080
143081/*
143082** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
143083** type of join.  Return an integer constant that expresses that type
143084** in terms of the following bit values:
143085**
143086**     JT_INNER
143087**     JT_CROSS
143088**     JT_OUTER
143089**     JT_NATURAL
143090**     JT_LEFT
143091**     JT_RIGHT
143092**
143093** A full outer join is the combination of JT_LEFT and JT_RIGHT.
143094**
143095** If an illegal or unsupported join type is seen, then still return
143096** a join type, but put an error in the pParse structure.
143097**
143098** These are the valid join types:
143099**
143100**
143101**      pA       pB       pC               Return Value
143102**     -------  -----    -----             ------------
143103**     CROSS      -        -                 JT_CROSS
143104**     INNER      -        -                 JT_INNER
143105**     LEFT       -        -                 JT_LEFT|JT_OUTER
143106**     LEFT     OUTER      -                 JT_LEFT|JT_OUTER
143107**     RIGHT      -        -                 JT_RIGHT|JT_OUTER
143108**     RIGHT    OUTER      -                 JT_RIGHT|JT_OUTER
143109**     FULL       -        -                 JT_LEFT|JT_RIGHT|JT_OUTER
143110**     FULL     OUTER      -                 JT_LEFT|JT_RIGHT|JT_OUTER
143111**     NATURAL  INNER      -                 JT_NATURAL|JT_INNER
143112**     NATURAL  LEFT       -                 JT_NATURAL|JT_LEFT|JT_OUTER
143113**     NATURAL  LEFT     OUTER               JT_NATURAL|JT_LEFT|JT_OUTER
143114**     NATURAL  RIGHT      -                 JT_NATURAL|JT_RIGHT|JT_OUTER
143115**     NATURAL  RIGHT    OUTER               JT_NATURAL|JT_RIGHT|JT_OUTER
143116**     NATURAL  FULL       -                 JT_NATURAL|JT_LEFT|JT_RIGHT
143117**     NATURAL  FULL     OUTER               JT_NATRUAL|JT_LEFT|JT_RIGHT
143118**
143119** To preserve historical compatibly, SQLite also accepts a variety
143120** of other non-standard and in many cases nonsensical join types.
143121** This routine makes as much sense at it can from the nonsense join
143122** type and returns a result.  Examples of accepted nonsense join types
143123** include but are not limited to:
143124**
143125**          INNER CROSS JOIN        ->   same as JOIN
143126**          NATURAL CROSS JOIN      ->   same as NATURAL JOIN
143127**          OUTER LEFT JOIN         ->   same as LEFT JOIN
143128**          LEFT NATURAL JOIN       ->   same as NATURAL LEFT JOIN
143129**          LEFT RIGHT JOIN         ->   same as FULL JOIN
143130**          RIGHT OUTER FULL JOIN   ->   same as FULL JOIN
143131**          CROSS CROSS CROSS JOIN  ->   same as JOIN
143132**
143133** The only restrictions on the join type name are:
143134**
143135**    *   "INNER" cannot appear together with "OUTER", "LEFT", "RIGHT",
143136**        or "FULL".
143137**
143138**    *   "CROSS" cannot appear together with "OUTER", "LEFT", "RIGHT,
143139**        or "FULL".
143140**
143141**    *   If "OUTER" is present then there must also be one of
143142**        "LEFT", "RIGHT", or "FULL"
143143*/
143144SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
143145  int jointype = 0;
143146  Token *apAll[3];
143147  Token *p;
143148                             /*   0123456789 123456789 123456789 123 */
143149  static const char zKeyText[] = "naturaleftouterightfullinnercross";
143150  static const struct {
143151    u8 i;        /* Beginning of keyword text in zKeyText[] */
143152    u8 nChar;    /* Length of the keyword in characters */
143153    u8 code;     /* Join type mask */
143154  } aKeyword[] = {
143155    /* (0) natural */ { 0,  7, JT_NATURAL                },
143156    /* (1) left    */ { 6,  4, JT_LEFT|JT_OUTER          },
143157    /* (2) outer   */ { 10, 5, JT_OUTER                  },
143158    /* (3) right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
143159    /* (4) full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
143160    /* (5) inner   */ { 23, 5, JT_INNER                  },
143161    /* (6) cross   */ { 28, 5, JT_INNER|JT_CROSS         },
143162  };
143163  int i, j;
143164  apAll[0] = pA;
143165  apAll[1] = pB;
143166  apAll[2] = pC;
143167  for(i=0; i<3 && apAll[i]; i++){
143168    p = apAll[i];
143169    for(j=0; j<ArraySize(aKeyword); j++){
143170      if( p->n==aKeyword[j].nChar
143171          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
143172        jointype |= aKeyword[j].code;
143173        break;
143174      }
143175    }
143176    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
143177    if( j>=ArraySize(aKeyword) ){
143178      jointype |= JT_ERROR;
143179      break;
143180    }
143181  }
143182  if(
143183     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
143184     (jointype & JT_ERROR)!=0 ||
143185     (jointype & (JT_OUTER|JT_LEFT|JT_RIGHT))==JT_OUTER
143186  ){
143187    const char *zSp1 = " ";
143188    const char *zSp2 = " ";
143189    if( pB==0 ){ zSp1++; }
143190    if( pC==0 ){ zSp2++; }
143191    sqlite3ErrorMsg(pParse, "unknown join type: "
143192       "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
143193    jointype = JT_INNER;
143194  }
143195  return jointype;
143196}
143197
143198/*
143199** Return the index of a column in a table.  Return -1 if the column
143200** is not contained in the table.
143201*/
143202SQLITE_PRIVATE int sqlite3ColumnIndex(Table *pTab, const char *zCol){
143203  int i;
143204  u8 h = sqlite3StrIHash(zCol);
143205  Column *pCol;
143206  for(pCol=pTab->aCol, i=0; i<pTab->nCol; pCol++, i++){
143207    if( pCol->hName==h && sqlite3StrICmp(pCol->zCnName, zCol)==0 ) return i;
143208  }
143209  return -1;
143210}
143211
143212/*
143213** Mark a subquery result column as having been used.
143214*/
143215SQLITE_PRIVATE void sqlite3SrcItemColumnUsed(SrcItem *pItem, int iCol){
143216  assert( pItem!=0 );
143217  assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
143218  if( pItem->fg.isNestedFrom ){
143219    ExprList *pResults;
143220    assert( pItem->pSelect!=0 );
143221    pResults = pItem->pSelect->pEList;
143222    assert( pResults!=0 );
143223    assert( iCol>=0 && iCol<pResults->nExpr );
143224    pResults->a[iCol].fg.bUsed = 1;
143225  }
143226}
143227
143228/*
143229** Search the tables iStart..iEnd (inclusive) in pSrc, looking for a
143230** table that has a column named zCol.  The search is left-to-right.
143231** The first match found is returned.
143232**
143233** When found, set *piTab and *piCol to the table index and column index
143234** of the matching column and return TRUE.
143235**
143236** If not found, return FALSE.
143237*/
143238static int tableAndColumnIndex(
143239  SrcList *pSrc,       /* Array of tables to search */
143240  int iStart,          /* First member of pSrc->a[] to check */
143241  int iEnd,            /* Last member of pSrc->a[] to check */
143242  const char *zCol,    /* Name of the column we are looking for */
143243  int *piTab,          /* Write index of pSrc->a[] here */
143244  int *piCol,          /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
143245  int bIgnoreHidden    /* Ignore hidden columns */
143246){
143247  int i;               /* For looping over tables in pSrc */
143248  int iCol;            /* Index of column matching zCol */
143249
143250  assert( iEnd<pSrc->nSrc );
143251  assert( iStart>=0 );
143252  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
143253
143254  for(i=iStart; i<=iEnd; i++){
143255    iCol = sqlite3ColumnIndex(pSrc->a[i].pTab, zCol);
143256    if( iCol>=0
143257     && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0)
143258    ){
143259      if( piTab ){
143260        sqlite3SrcItemColumnUsed(&pSrc->a[i], iCol);
143261        *piTab = i;
143262        *piCol = iCol;
143263      }
143264      return 1;
143265    }
143266  }
143267  return 0;
143268}
143269
143270/*
143271** Set the EP_OuterON property on all terms of the given expression.
143272** And set the Expr.w.iJoin to iTable for every term in the
143273** expression.
143274**
143275** The EP_OuterON property is used on terms of an expression to tell
143276** the OUTER JOIN processing logic that this term is part of the
143277** join restriction specified in the ON or USING clause and not a part
143278** of the more general WHERE clause.  These terms are moved over to the
143279** WHERE clause during join processing but we need to remember that they
143280** originated in the ON or USING clause.
143281**
143282** The Expr.w.iJoin tells the WHERE clause processing that the
143283** expression depends on table w.iJoin even if that table is not
143284** explicitly mentioned in the expression.  That information is needed
143285** for cases like this:
143286**
143287**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
143288**
143289** The where clause needs to defer the handling of the t1.x=5
143290** term until after the t2 loop of the join.  In that way, a
143291** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
143292** defer the handling of t1.x=5, it will be processed immediately
143293** after the t1 loop and rows with t1.x!=5 will never appear in
143294** the output, which is incorrect.
143295*/
143296SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr *p, int iTable, u32 joinFlag){
143297  assert( joinFlag==EP_OuterON || joinFlag==EP_InnerON );
143298  while( p ){
143299    ExprSetProperty(p, joinFlag);
143300    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
143301    ExprSetVVAProperty(p, EP_NoReduce);
143302    p->w.iJoin = iTable;
143303    if( p->op==TK_FUNCTION ){
143304      assert( ExprUseXList(p) );
143305      if( p->x.pList ){
143306        int i;
143307        for(i=0; i<p->x.pList->nExpr; i++){
143308          sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable, joinFlag);
143309        }
143310      }
143311    }
143312    sqlite3SetJoinExpr(p->pLeft, iTable, joinFlag);
143313    p = p->pRight;
143314  }
143315}
143316
143317/* Undo the work of sqlite3SetJoinExpr().  This is used when a LEFT JOIN
143318** is simplified into an ordinary JOIN, and when an ON expression is
143319** "pushed down" into the WHERE clause of a subquery.
143320**
143321** Convert every term that is marked with EP_OuterON and w.iJoin==iTable into
143322** an ordinary term that omits the EP_OuterON mark.  Or if iTable<0, then
143323** just clear every EP_OuterON and EP_InnerON mark from the expression tree.
143324**
143325** If nullable is true, that means that Expr p might evaluate to NULL even
143326** if it is a reference to a NOT NULL column.  This can happen, for example,
143327** if the table that p references is on the left side of a RIGHT JOIN.
143328** If nullable is true, then take care to not remove the EP_CanBeNull bit.
143329** See forum thread https://sqlite.org/forum/forumpost/b40696f50145d21c
143330*/
143331static void unsetJoinExpr(Expr *p, int iTable, int nullable){
143332  while( p ){
143333    if( iTable<0 || (ExprHasProperty(p, EP_OuterON) && p->w.iJoin==iTable) ){
143334      ExprClearProperty(p, EP_OuterON|EP_InnerON);
143335      if( iTable>=0 ) ExprSetProperty(p, EP_InnerON);
143336    }
143337    if( p->op==TK_COLUMN && p->iTable==iTable && !nullable ){
143338      ExprClearProperty(p, EP_CanBeNull);
143339    }
143340    if( p->op==TK_FUNCTION ){
143341      assert( ExprUseXList(p) );
143342      assert( p->pLeft==0 );
143343      if( p->x.pList ){
143344        int i;
143345        for(i=0; i<p->x.pList->nExpr; i++){
143346          unsetJoinExpr(p->x.pList->a[i].pExpr, iTable, nullable);
143347        }
143348      }
143349    }
143350    unsetJoinExpr(p->pLeft, iTable, nullable);
143351    p = p->pRight;
143352  }
143353}
143354
143355/*
143356** This routine processes the join information for a SELECT statement.
143357**
143358**   *  A NATURAL join is converted into a USING join.  After that, we
143359**      do not need to be concerned with NATURAL joins and we only have
143360**      think about USING joins.
143361**
143362**   *  ON and USING clauses result in extra terms being added to the
143363**      WHERE clause to enforce the specified constraints.  The extra
143364**      WHERE clause terms will be tagged with EP_OuterON or
143365**      EP_InnerON so that we know that they originated in ON/USING.
143366**
143367** The terms of a FROM clause are contained in the Select.pSrc structure.
143368** The left most table is the first entry in Select.pSrc.  The right-most
143369** table is the last entry.  The join operator is held in the entry to
143370** the right.  Thus entry 1 contains the join operator for the join between
143371** entries 0 and 1.  Any ON or USING clauses associated with the join are
143372** also attached to the right entry.
143373**
143374** This routine returns the number of errors encountered.
143375*/
143376static int sqlite3ProcessJoin(Parse *pParse, Select *p){
143377  SrcList *pSrc;                  /* All tables in the FROM clause */
143378  int i, j;                       /* Loop counters */
143379  SrcItem *pLeft;                 /* Left table being joined */
143380  SrcItem *pRight;                /* Right table being joined */
143381
143382  pSrc = p->pSrc;
143383  pLeft = &pSrc->a[0];
143384  pRight = &pLeft[1];
143385  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
143386    Table *pRightTab = pRight->pTab;
143387    u32 joinType;
143388
143389    if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
143390    joinType = (pRight->fg.jointype & JT_OUTER)!=0 ? EP_OuterON : EP_InnerON;
143391
143392    /* If this is a NATURAL join, synthesize an appropriate USING clause
143393    ** to specify which columns should be joined.
143394    */
143395    if( pRight->fg.jointype & JT_NATURAL ){
143396      IdList *pUsing = 0;
143397      if( pRight->fg.isUsing || pRight->u3.pOn ){
143398        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
143399           "an ON or USING clause", 0);
143400        return 1;
143401      }
143402      for(j=0; j<pRightTab->nCol; j++){
143403        char *zName;   /* Name of column in the right table */
143404
143405        if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue;
143406        zName = pRightTab->aCol[j].zCnName;
143407        if( tableAndColumnIndex(pSrc, 0, i, zName, 0, 0, 1) ){
143408          pUsing = sqlite3IdListAppend(pParse, pUsing, 0);
143409          if( pUsing ){
143410            assert( pUsing->nId>0 );
143411            assert( pUsing->a[pUsing->nId-1].zName==0 );
143412            pUsing->a[pUsing->nId-1].zName = sqlite3DbStrDup(pParse->db, zName);
143413          }
143414        }
143415      }
143416      if( pUsing ){
143417        pRight->fg.isUsing = 1;
143418        pRight->fg.isSynthUsing = 1;
143419        pRight->u3.pUsing = pUsing;
143420      }
143421      if( pParse->nErr ) return 1;
143422    }
143423
143424    /* Create extra terms on the WHERE clause for each column named
143425    ** in the USING clause.  Example: If the two tables to be joined are
143426    ** A and B and the USING clause names X, Y, and Z, then add this
143427    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
143428    ** Report an error if any column mentioned in the USING clause is
143429    ** not contained in both tables to be joined.
143430    */
143431    if( pRight->fg.isUsing ){
143432      IdList *pList = pRight->u3.pUsing;
143433      sqlite3 *db = pParse->db;
143434      assert( pList!=0 );
143435      for(j=0; j<pList->nId; j++){
143436        char *zName;     /* Name of the term in the USING clause */
143437        int iLeft;       /* Table on the left with matching column name */
143438        int iLeftCol;    /* Column number of matching column on the left */
143439        int iRightCol;   /* Column number of matching column on the right */
143440        Expr *pE1;       /* Reference to the column on the LEFT of the join */
143441        Expr *pE2;       /* Reference to the column on the RIGHT of the join */
143442        Expr *pEq;       /* Equality constraint.  pE1 == pE2 */
143443
143444        zName = pList->a[j].zName;
143445        iRightCol = sqlite3ColumnIndex(pRightTab, zName);
143446        if( iRightCol<0
143447         || tableAndColumnIndex(pSrc, 0, i, zName, &iLeft, &iLeftCol,
143448                                pRight->fg.isSynthUsing)==0
143449        ){
143450          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
143451            "not present in both tables", zName);
143452          return 1;
143453        }
143454        pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol);
143455        sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
143456        if( (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
143457          /* This branch runs if the query contains one or more RIGHT or FULL
143458          ** JOINs.  If only a single table on the left side of this join
143459          ** contains the zName column, then this branch is a no-op.
143460          ** But if there are two or more tables on the left side
143461          ** of the join, construct a coalesce() function that gathers all
143462          ** such tables.  Raise an error if more than one of those references
143463          ** to zName is not also within a prior USING clause.
143464          **
143465          ** We really ought to raise an error if there are two or more
143466          ** non-USING references to zName on the left of an INNER or LEFT
143467          ** JOIN.  But older versions of SQLite do not do that, so we avoid
143468          ** adding a new error so as to not break legacy applications.
143469          */
143470          ExprList *pFuncArgs = 0;   /* Arguments to the coalesce() */
143471          static const Token tkCoalesce = { "coalesce", 8 };
143472          while( tableAndColumnIndex(pSrc, iLeft+1, i, zName, &iLeft, &iLeftCol,
143473                                     pRight->fg.isSynthUsing)!=0 ){
143474            if( pSrc->a[iLeft].fg.isUsing==0
143475             || sqlite3IdListIndex(pSrc->a[iLeft].u3.pUsing, zName)<0
143476            ){
143477              sqlite3ErrorMsg(pParse, "ambiguous reference to %s in USING()",
143478                              zName);
143479              break;
143480            }
143481            pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1);
143482            pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol);
143483            sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
143484          }
143485          if( pFuncArgs ){
143486            pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1);
143487            pE1 = sqlite3ExprFunction(pParse, pFuncArgs, &tkCoalesce, 0);
143488          }
143489        }
143490        pE2 = sqlite3CreateColumnExpr(db, pSrc, i+1, iRightCol);
143491        sqlite3SrcItemColumnUsed(pRight, iRightCol);
143492        pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
143493        assert( pE2!=0 || pEq==0 );
143494        if( pEq ){
143495          ExprSetProperty(pEq, joinType);
143496          assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
143497          ExprSetVVAProperty(pEq, EP_NoReduce);
143498          pEq->w.iJoin = pE2->iTable;
143499        }
143500        p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pEq);
143501      }
143502    }
143503
143504    /* Add the ON clause to the end of the WHERE clause, connected by
143505    ** an AND operator.
143506    */
143507    else if( pRight->u3.pOn ){
143508      sqlite3SetJoinExpr(pRight->u3.pOn, pRight->iCursor, joinType);
143509      p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->u3.pOn);
143510      pRight->u3.pOn = 0;
143511      pRight->fg.isOn = 1;
143512    }
143513  }
143514  return 0;
143515}
143516
143517/*
143518** An instance of this object holds information (beyond pParse and pSelect)
143519** needed to load the next result row that is to be added to the sorter.
143520*/
143521typedef struct RowLoadInfo RowLoadInfo;
143522struct RowLoadInfo {
143523  int regResult;               /* Store results in array of registers here */
143524  u8 ecelFlags;                /* Flag argument to ExprCodeExprList() */
143525#ifdef SQLITE_ENABLE_SORTER_REFERENCES
143526  ExprList *pExtra;            /* Extra columns needed by sorter refs */
143527  int regExtraResult;          /* Where to load the extra columns */
143528#endif
143529};
143530
143531/*
143532** This routine does the work of loading query data into an array of
143533** registers so that it can be added to the sorter.
143534*/
143535static void innerLoopLoadRow(
143536  Parse *pParse,             /* Statement under construction */
143537  Select *pSelect,           /* The query being coded */
143538  RowLoadInfo *pInfo         /* Info needed to complete the row load */
143539){
143540  sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
143541                          0, pInfo->ecelFlags);
143542#ifdef SQLITE_ENABLE_SORTER_REFERENCES
143543  if( pInfo->pExtra ){
143544    sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
143545    sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
143546  }
143547#endif
143548}
143549
143550/*
143551** Code the OP_MakeRecord instruction that generates the entry to be
143552** added into the sorter.
143553**
143554** Return the register in which the result is stored.
143555*/
143556static int makeSorterRecord(
143557  Parse *pParse,
143558  SortCtx *pSort,
143559  Select *pSelect,
143560  int regBase,
143561  int nBase
143562){
143563  int nOBSat = pSort->nOBSat;
143564  Vdbe *v = pParse->pVdbe;
143565  int regOut = ++pParse->nMem;
143566  if( pSort->pDeferredRowLoad ){
143567    innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
143568  }
143569  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
143570  return regOut;
143571}
143572
143573/*
143574** Generate code that will push the record in registers regData
143575** through regData+nData-1 onto the sorter.
143576*/
143577static void pushOntoSorter(
143578  Parse *pParse,         /* Parser context */
143579  SortCtx *pSort,        /* Information about the ORDER BY clause */
143580  Select *pSelect,       /* The whole SELECT statement */
143581  int regData,           /* First register holding data to be sorted */
143582  int regOrigData,       /* First register holding data before packing */
143583  int nData,             /* Number of elements in the regData data array */
143584  int nPrefixReg         /* No. of reg prior to regData available for use */
143585){
143586  Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
143587  int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
143588  int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
143589  int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
143590  int regBase;                                     /* Regs for sorter record */
143591  int regRecord = 0;                               /* Assembled sorter record */
143592  int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
143593  int op;                            /* Opcode to add sorter record to sorter */
143594  int iLimit;                        /* LIMIT counter */
143595  int iSkip = 0;                     /* End of the sorter insert loop */
143596
143597  assert( bSeq==0 || bSeq==1 );
143598
143599  /* Three cases:
143600  **   (1) The data to be sorted has already been packed into a Record
143601  **       by a prior OP_MakeRecord.  In this case nData==1 and regData
143602  **       will be completely unrelated to regOrigData.
143603  **   (2) All output columns are included in the sort record.  In that
143604  **       case regData==regOrigData.
143605  **   (3) Some output columns are omitted from the sort record due to
143606  **       the SQLITE_ENABLE_SORTER_REFERENCES optimization, or due to the
143607  **       SQLITE_ECEL_OMITREF optimization, or due to the
143608  **       SortCtx.pDeferredRowLoad optimization.  In any of these cases
143609  **       regOrigData is 0 to prevent this routine from trying to copy
143610  **       values that might not yet exist.
143611  */
143612  assert( nData==1 || regData==regOrigData || regOrigData==0 );
143613
143614#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
143615  pSort->addrPush = sqlite3VdbeCurrentAddr(v);
143616#endif
143617
143618  if( nPrefixReg ){
143619    assert( nPrefixReg==nExpr+bSeq );
143620    regBase = regData - nPrefixReg;
143621  }else{
143622    regBase = pParse->nMem + 1;
143623    pParse->nMem += nBase;
143624  }
143625  assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
143626  iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
143627  pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
143628  sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
143629                          SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
143630  if( bSeq ){
143631    sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
143632  }
143633  if( nPrefixReg==0 && nData>0 ){
143634    sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
143635  }
143636  if( nOBSat>0 ){
143637    int regPrevKey;   /* The first nOBSat columns of the previous row */
143638    int addrFirst;    /* Address of the OP_IfNot opcode */
143639    int addrJmp;      /* Address of the OP_Jump opcode */
143640    VdbeOp *pOp;      /* Opcode that opens the sorter */
143641    int nKey;         /* Number of sorting key columns, including OP_Sequence */
143642    KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
143643
143644    regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
143645    regPrevKey = pParse->nMem+1;
143646    pParse->nMem += pSort->nOBSat;
143647    nKey = nExpr - pSort->nOBSat + bSeq;
143648    if( bSeq ){
143649      addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
143650    }else{
143651      addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
143652    }
143653    VdbeCoverage(v);
143654    sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
143655    pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
143656    if( pParse->db->mallocFailed ) return;
143657    pOp->p2 = nKey + nData;
143658    pKI = pOp->p4.pKeyInfo;
143659    memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */
143660    sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
143661    testcase( pKI->nAllField > pKI->nKeyField+2 );
143662    pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
143663                                           pKI->nAllField-pKI->nKeyField-1);
143664    pOp = 0; /* Ensure pOp not used after sqlite3VdbeAddOp3() */
143665    addrJmp = sqlite3VdbeCurrentAddr(v);
143666    sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
143667    pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
143668    pSort->regReturn = ++pParse->nMem;
143669    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
143670    sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
143671    if( iLimit ){
143672      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
143673      VdbeCoverage(v);
143674    }
143675    sqlite3VdbeJumpHere(v, addrFirst);
143676    sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
143677    sqlite3VdbeJumpHere(v, addrJmp);
143678  }
143679  if( iLimit ){
143680    /* At this point the values for the new sorter entry are stored
143681    ** in an array of registers. They need to be composed into a record
143682    ** and inserted into the sorter if either (a) there are currently
143683    ** less than LIMIT+OFFSET items or (b) the new record is smaller than
143684    ** the largest record currently in the sorter. If (b) is true and there
143685    ** are already LIMIT+OFFSET items in the sorter, delete the largest
143686    ** entry before inserting the new one. This way there are never more
143687    ** than LIMIT+OFFSET items in the sorter.
143688    **
143689    ** If the new record does not need to be inserted into the sorter,
143690    ** jump to the next iteration of the loop. If the pSort->labelOBLopt
143691    ** value is not zero, then it is a label of where to jump.  Otherwise,
143692    ** just bypass the row insert logic.  See the header comment on the
143693    ** sqlite3WhereOrderByLimitOptLabel() function for additional info.
143694    */
143695    int iCsr = pSort->iECursor;
143696    sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
143697    VdbeCoverage(v);
143698    sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
143699    iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
143700                                 iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
143701    VdbeCoverage(v);
143702    sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
143703  }
143704  if( regRecord==0 ){
143705    regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
143706  }
143707  if( pSort->sortFlags & SORTFLAG_UseSorter ){
143708    op = OP_SorterInsert;
143709  }else{
143710    op = OP_IdxInsert;
143711  }
143712  sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
143713                       regBase+nOBSat, nBase-nOBSat);
143714  if( iSkip ){
143715    sqlite3VdbeChangeP2(v, iSkip,
143716         pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
143717  }
143718#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
143719  pSort->addrPushEnd = sqlite3VdbeCurrentAddr(v)-1;
143720#endif
143721}
143722
143723/*
143724** Add code to implement the OFFSET
143725*/
143726static void codeOffset(
143727  Vdbe *v,          /* Generate code into this VM */
143728  int iOffset,      /* Register holding the offset counter */
143729  int iContinue     /* Jump here to skip the current record */
143730){
143731  if( iOffset>0 ){
143732    sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
143733    VdbeComment((v, "OFFSET"));
143734  }
143735}
143736
143737/*
143738** Add code that will check to make sure the array of registers starting at
143739** iMem form a distinct entry. This is used by both "SELECT DISTINCT ..." and
143740** distinct aggregates ("SELECT count(DISTINCT <expr>) ..."). Three strategies
143741** are available. Which is used depends on the value of parameter eTnctType,
143742** as follows:
143743**
143744**   WHERE_DISTINCT_UNORDERED/WHERE_DISTINCT_NOOP:
143745**     Build an ephemeral table that contains all entries seen before and
143746**     skip entries which have been seen before.
143747**
143748**     Parameter iTab is the cursor number of an ephemeral table that must
143749**     be opened before the VM code generated by this routine is executed.
143750**     The ephemeral cursor table is queried for a record identical to the
143751**     record formed by the current array of registers. If one is found,
143752**     jump to VM address addrRepeat. Otherwise, insert a new record into
143753**     the ephemeral cursor and proceed.
143754**
143755**     The returned value in this case is a copy of parameter iTab.
143756**
143757**   WHERE_DISTINCT_ORDERED:
143758**     In this case rows are being delivered sorted order. The ephemeral
143759**     table is not required. Instead, the current set of values
143760**     is compared against previous row. If they match, the new row
143761**     is not distinct and control jumps to VM address addrRepeat. Otherwise,
143762**     the VM program proceeds with processing the new row.
143763**
143764**     The returned value in this case is the register number of the first
143765**     in an array of registers used to store the previous result row so that
143766**     it can be compared to the next. The caller must ensure that this
143767**     register is initialized to NULL.  (The fixDistinctOpenEph() routine
143768**     will take care of this initialization.)
143769**
143770**   WHERE_DISTINCT_UNIQUE:
143771**     In this case it has already been determined that the rows are distinct.
143772**     No special action is required. The return value is zero.
143773**
143774** Parameter pEList is the list of expressions used to generated the
143775** contents of each row. It is used by this routine to determine (a)
143776** how many elements there are in the array of registers and (b) the
143777** collation sequences that should be used for the comparisons if
143778** eTnctType is WHERE_DISTINCT_ORDERED.
143779*/
143780static int codeDistinct(
143781  Parse *pParse,     /* Parsing and code generating context */
143782  int eTnctType,     /* WHERE_DISTINCT_* value */
143783  int iTab,          /* A sorting index used to test for distinctness */
143784  int addrRepeat,    /* Jump to here if not distinct */
143785  ExprList *pEList,  /* Expression for each element */
143786  int regElem        /* First element */
143787){
143788  int iRet = 0;
143789  int nResultCol = pEList->nExpr;
143790  Vdbe *v = pParse->pVdbe;
143791
143792  switch( eTnctType ){
143793    case WHERE_DISTINCT_ORDERED: {
143794      int i;
143795      int iJump;              /* Jump destination */
143796      int regPrev;            /* Previous row content */
143797
143798      /* Allocate space for the previous row */
143799      iRet = regPrev = pParse->nMem+1;
143800      pParse->nMem += nResultCol;
143801
143802      iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
143803      for(i=0; i<nResultCol; i++){
143804        CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
143805        if( i<nResultCol-1 ){
143806          sqlite3VdbeAddOp3(v, OP_Ne, regElem+i, iJump, regPrev+i);
143807          VdbeCoverage(v);
143808        }else{
143809          sqlite3VdbeAddOp3(v, OP_Eq, regElem+i, addrRepeat, regPrev+i);
143810          VdbeCoverage(v);
143811         }
143812        sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
143813        sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
143814      }
143815      assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
143816      sqlite3VdbeAddOp3(v, OP_Copy, regElem, regPrev, nResultCol-1);
143817      break;
143818    }
143819
143820    case WHERE_DISTINCT_UNIQUE: {
143821      /* nothing to do */
143822      break;
143823    }
143824
143825    default: {
143826      int r1 = sqlite3GetTempReg(pParse);
143827      sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, regElem, nResultCol);
143828      VdbeCoverage(v);
143829      sqlite3VdbeAddOp3(v, OP_MakeRecord, regElem, nResultCol, r1);
143830      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, regElem, nResultCol);
143831      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
143832      sqlite3ReleaseTempReg(pParse, r1);
143833      iRet = iTab;
143834      break;
143835    }
143836  }
143837
143838  return iRet;
143839}
143840
143841/*
143842** This routine runs after codeDistinct().  It makes necessary
143843** adjustments to the OP_OpenEphemeral opcode that the codeDistinct()
143844** routine made use of.  This processing must be done separately since
143845** sometimes codeDistinct is called before the OP_OpenEphemeral is actually
143846** laid down.
143847**
143848** WHERE_DISTINCT_NOOP:
143849** WHERE_DISTINCT_UNORDERED:
143850**
143851**     No adjustments necessary.  This function is a no-op.
143852**
143853** WHERE_DISTINCT_UNIQUE:
143854**
143855**     The ephemeral table is not needed.  So change the
143856**     OP_OpenEphemeral opcode into an OP_Noop.
143857**
143858** WHERE_DISTINCT_ORDERED:
143859**
143860**     The ephemeral table is not needed.  But we do need register
143861**     iVal to be initialized to NULL.  So change the OP_OpenEphemeral
143862**     into an OP_Null on the iVal register.
143863*/
143864static void fixDistinctOpenEph(
143865  Parse *pParse,     /* Parsing and code generating context */
143866  int eTnctType,     /* WHERE_DISTINCT_* value */
143867  int iVal,          /* Value returned by codeDistinct() */
143868  int iOpenEphAddr   /* Address of OP_OpenEphemeral instruction for iTab */
143869){
143870  if( pParse->nErr==0
143871   && (eTnctType==WHERE_DISTINCT_UNIQUE || eTnctType==WHERE_DISTINCT_ORDERED)
143872  ){
143873    Vdbe *v = pParse->pVdbe;
143874    sqlite3VdbeChangeToNoop(v, iOpenEphAddr);
143875    if( sqlite3VdbeGetOp(v, iOpenEphAddr+1)->opcode==OP_Explain ){
143876      sqlite3VdbeChangeToNoop(v, iOpenEphAddr+1);
143877    }
143878    if( eTnctType==WHERE_DISTINCT_ORDERED ){
143879      /* Change the OP_OpenEphemeral to an OP_Null that sets the MEM_Cleared
143880      ** bit on the first register of the previous value.  This will cause the
143881      ** OP_Ne added in codeDistinct() to always fail on the first iteration of
143882      ** the loop even if the first row is all NULLs.  */
143883      VdbeOp *pOp = sqlite3VdbeGetOp(v, iOpenEphAddr);
143884      pOp->opcode = OP_Null;
143885      pOp->p1 = 1;
143886      pOp->p2 = iVal;
143887    }
143888  }
143889}
143890
143891#ifdef SQLITE_ENABLE_SORTER_REFERENCES
143892/*
143893** This function is called as part of inner-loop generation for a SELECT
143894** statement with an ORDER BY that is not optimized by an index. It
143895** determines the expressions, if any, that the sorter-reference
143896** optimization should be used for. The sorter-reference optimization
143897** is used for SELECT queries like:
143898**
143899**   SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
143900**
143901** If the optimization is used for expression "bigblob", then instead of
143902** storing values read from that column in the sorter records, the PK of
143903** the row from table t1 is stored instead. Then, as records are extracted from
143904** the sorter to return to the user, the required value of bigblob is
143905** retrieved directly from table t1. If the values are very large, this
143906** can be more efficient than storing them directly in the sorter records.
143907**
143908** The ExprList_item.fg.bSorterRef flag is set for each expression in pEList
143909** for which the sorter-reference optimization should be enabled.
143910** Additionally, the pSort->aDefer[] array is populated with entries
143911** for all cursors required to evaluate all selected expressions. Finally.
143912** output variable (*ppExtra) is set to an expression list containing
143913** expressions for all extra PK values that should be stored in the
143914** sorter records.
143915*/
143916static void selectExprDefer(
143917  Parse *pParse,                  /* Leave any error here */
143918  SortCtx *pSort,                 /* Sorter context */
143919  ExprList *pEList,               /* Expressions destined for sorter */
143920  ExprList **ppExtra              /* Expressions to append to sorter record */
143921){
143922  int i;
143923  int nDefer = 0;
143924  ExprList *pExtra = 0;
143925  for(i=0; i<pEList->nExpr; i++){
143926    struct ExprList_item *pItem = &pEList->a[i];
143927    if( pItem->u.x.iOrderByCol==0 ){
143928      Expr *pExpr = pItem->pExpr;
143929      Table *pTab;
143930      if( pExpr->op==TK_COLUMN
143931       && pExpr->iColumn>=0
143932       && ALWAYS( ExprUseYTab(pExpr) )
143933       && (pTab = pExpr->y.pTab)!=0
143934       && IsOrdinaryTable(pTab)
143935       && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)!=0
143936      ){
143937        int j;
143938        for(j=0; j<nDefer; j++){
143939          if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
143940        }
143941        if( j==nDefer ){
143942          if( nDefer==ArraySize(pSort->aDefer) ){
143943            continue;
143944          }else{
143945            int nKey = 1;
143946            int k;
143947            Index *pPk = 0;
143948            if( !HasRowid(pTab) ){
143949              pPk = sqlite3PrimaryKeyIndex(pTab);
143950              nKey = pPk->nKeyCol;
143951            }
143952            for(k=0; k<nKey; k++){
143953              Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
143954              if( pNew ){
143955                pNew->iTable = pExpr->iTable;
143956                assert( ExprUseYTab(pNew) );
143957                pNew->y.pTab = pExpr->y.pTab;
143958                pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
143959                pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
143960              }
143961            }
143962            pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
143963            pSort->aDefer[nDefer].iCsr = pExpr->iTable;
143964            pSort->aDefer[nDefer].nKey = nKey;
143965            nDefer++;
143966          }
143967        }
143968        pItem->fg.bSorterRef = 1;
143969      }
143970    }
143971  }
143972  pSort->nDefer = (u8)nDefer;
143973  *ppExtra = pExtra;
143974}
143975#endif
143976
143977/*
143978** This routine generates the code for the inside of the inner loop
143979** of a SELECT.
143980**
143981** If srcTab is negative, then the p->pEList expressions
143982** are evaluated in order to get the data for this row.  If srcTab is
143983** zero or more, then data is pulled from srcTab and p->pEList is used only
143984** to get the number of columns and the collation sequence for each column.
143985*/
143986static void selectInnerLoop(
143987  Parse *pParse,          /* The parser context */
143988  Select *p,              /* The complete select statement being coded */
143989  int srcTab,             /* Pull data from this table if non-negative */
143990  SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
143991  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
143992  SelectDest *pDest,      /* How to dispose of the results */
143993  int iContinue,          /* Jump here to continue with next row */
143994  int iBreak              /* Jump here to break out of the inner loop */
143995){
143996  Vdbe *v = pParse->pVdbe;
143997  int i;
143998  int hasDistinct;            /* True if the DISTINCT keyword is present */
143999  int eDest = pDest->eDest;   /* How to dispose of results */
144000  int iParm = pDest->iSDParm; /* First argument to disposal method */
144001  int nResultCol;             /* Number of result columns */
144002  int nPrefixReg = 0;         /* Number of extra registers before regResult */
144003  RowLoadInfo sRowLoadInfo;   /* Info for deferred row loading */
144004
144005  /* Usually, regResult is the first cell in an array of memory cells
144006  ** containing the current result row. In this case regOrig is set to the
144007  ** same value. However, if the results are being sent to the sorter, the
144008  ** values for any expressions that are also part of the sort-key are omitted
144009  ** from this array. In this case regOrig is set to zero.  */
144010  int regResult;              /* Start of memory holding current results */
144011  int regOrig;                /* Start of memory holding full result (or 0) */
144012
144013  assert( v );
144014  assert( p->pEList!=0 );
144015  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
144016  if( pSort && pSort->pOrderBy==0 ) pSort = 0;
144017  if( pSort==0 && !hasDistinct ){
144018    assert( iContinue!=0 );
144019    codeOffset(v, p->iOffset, iContinue);
144020  }
144021
144022  /* Pull the requested columns.
144023  */
144024  nResultCol = p->pEList->nExpr;
144025
144026  if( pDest->iSdst==0 ){
144027    if( pSort ){
144028      nPrefixReg = pSort->pOrderBy->nExpr;
144029      if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
144030      pParse->nMem += nPrefixReg;
144031    }
144032    pDest->iSdst = pParse->nMem+1;
144033    pParse->nMem += nResultCol;
144034  }else if( pDest->iSdst+nResultCol > pParse->nMem ){
144035    /* This is an error condition that can result, for example, when a SELECT
144036    ** on the right-hand side of an INSERT contains more result columns than
144037    ** there are columns in the table on the left.  The error will be caught
144038    ** and reported later.  But we need to make sure enough memory is allocated
144039    ** to avoid other spurious errors in the meantime. */
144040    pParse->nMem += nResultCol;
144041  }
144042  pDest->nSdst = nResultCol;
144043  regOrig = regResult = pDest->iSdst;
144044  if( srcTab>=0 ){
144045    for(i=0; i<nResultCol; i++){
144046      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
144047      VdbeComment((v, "%s", p->pEList->a[i].zEName));
144048    }
144049  }else if( eDest!=SRT_Exists ){
144050#ifdef SQLITE_ENABLE_SORTER_REFERENCES
144051    ExprList *pExtra = 0;
144052#endif
144053    /* If the destination is an EXISTS(...) expression, the actual
144054    ** values returned by the SELECT are not required.
144055    */
144056    u8 ecelFlags;    /* "ecel" is an abbreviation of "ExprCodeExprList" */
144057    ExprList *pEList;
144058    if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
144059      ecelFlags = SQLITE_ECEL_DUP;
144060    }else{
144061      ecelFlags = 0;
144062    }
144063    if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
144064      /* For each expression in p->pEList that is a copy of an expression in
144065      ** the ORDER BY clause (pSort->pOrderBy), set the associated
144066      ** iOrderByCol value to one more than the index of the ORDER BY
144067      ** expression within the sort-key that pushOntoSorter() will generate.
144068      ** This allows the p->pEList field to be omitted from the sorted record,
144069      ** saving space and CPU cycles.  */
144070      ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
144071
144072      for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
144073        int j;
144074        if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
144075          p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
144076        }
144077      }
144078#ifdef SQLITE_ENABLE_SORTER_REFERENCES
144079      selectExprDefer(pParse, pSort, p->pEList, &pExtra);
144080      if( pExtra && pParse->db->mallocFailed==0 ){
144081        /* If there are any extra PK columns to add to the sorter records,
144082        ** allocate extra memory cells and adjust the OpenEphemeral
144083        ** instruction to account for the larger records. This is only
144084        ** required if there are one or more WITHOUT ROWID tables with
144085        ** composite primary keys in the SortCtx.aDefer[] array.  */
144086        VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
144087        pOp->p2 += (pExtra->nExpr - pSort->nDefer);
144088        pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
144089        pParse->nMem += pExtra->nExpr;
144090      }
144091#endif
144092
144093      /* Adjust nResultCol to account for columns that are omitted
144094      ** from the sorter by the optimizations in this branch */
144095      pEList = p->pEList;
144096      for(i=0; i<pEList->nExpr; i++){
144097        if( pEList->a[i].u.x.iOrderByCol>0
144098#ifdef SQLITE_ENABLE_SORTER_REFERENCES
144099         || pEList->a[i].fg.bSorterRef
144100#endif
144101        ){
144102          nResultCol--;
144103          regOrig = 0;
144104        }
144105      }
144106
144107      testcase( regOrig );
144108      testcase( eDest==SRT_Set );
144109      testcase( eDest==SRT_Mem );
144110      testcase( eDest==SRT_Coroutine );
144111      testcase( eDest==SRT_Output );
144112      assert( eDest==SRT_Set || eDest==SRT_Mem
144113           || eDest==SRT_Coroutine || eDest==SRT_Output
144114           || eDest==SRT_Upfrom );
144115    }
144116    sRowLoadInfo.regResult = regResult;
144117    sRowLoadInfo.ecelFlags = ecelFlags;
144118#ifdef SQLITE_ENABLE_SORTER_REFERENCES
144119    sRowLoadInfo.pExtra = pExtra;
144120    sRowLoadInfo.regExtraResult = regResult + nResultCol;
144121    if( pExtra ) nResultCol += pExtra->nExpr;
144122#endif
144123    if( p->iLimit
144124     && (ecelFlags & SQLITE_ECEL_OMITREF)!=0
144125     && nPrefixReg>0
144126    ){
144127      assert( pSort!=0 );
144128      assert( hasDistinct==0 );
144129      pSort->pDeferredRowLoad = &sRowLoadInfo;
144130      regOrig = 0;
144131    }else{
144132      innerLoopLoadRow(pParse, p, &sRowLoadInfo);
144133    }
144134  }
144135
144136  /* If the DISTINCT keyword was present on the SELECT statement
144137  ** and this row has been seen before, then do not make this row
144138  ** part of the result.
144139  */
144140  if( hasDistinct ){
144141    int eType = pDistinct->eTnctType;
144142    int iTab = pDistinct->tabTnct;
144143    assert( nResultCol==p->pEList->nExpr );
144144    iTab = codeDistinct(pParse, eType, iTab, iContinue, p->pEList, regResult);
144145    fixDistinctOpenEph(pParse, eType, iTab, pDistinct->addrTnct);
144146    if( pSort==0 ){
144147      codeOffset(v, p->iOffset, iContinue);
144148    }
144149  }
144150
144151  switch( eDest ){
144152    /* In this mode, write each query result to the key of the temporary
144153    ** table iParm.
144154    */
144155#ifndef SQLITE_OMIT_COMPOUND_SELECT
144156    case SRT_Union: {
144157      int r1;
144158      r1 = sqlite3GetTempReg(pParse);
144159      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
144160      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
144161      sqlite3ReleaseTempReg(pParse, r1);
144162      break;
144163    }
144164
144165    /* Construct a record from the query result, but instead of
144166    ** saving that record, use it as a key to delete elements from
144167    ** the temporary table iParm.
144168    */
144169    case SRT_Except: {
144170      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
144171      break;
144172    }
144173#endif /* SQLITE_OMIT_COMPOUND_SELECT */
144174
144175    /* Store the result as data using a unique key.
144176    */
144177    case SRT_Fifo:
144178    case SRT_DistFifo:
144179    case SRT_Table:
144180    case SRT_EphemTab: {
144181      int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
144182      testcase( eDest==SRT_Table );
144183      testcase( eDest==SRT_EphemTab );
144184      testcase( eDest==SRT_Fifo );
144185      testcase( eDest==SRT_DistFifo );
144186      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
144187#if !defined(SQLITE_ENABLE_NULL_TRIM) && defined(SQLITE_DEBUG)
144188      /* A destination of SRT_Table and a non-zero iSDParm2 parameter means
144189      ** that this is an "UPDATE ... FROM" on a virtual table or view. In this
144190      ** case set the p5 parameter of the OP_MakeRecord to OPFLAG_NOCHNG_MAGIC.
144191      ** This does not affect operation in any way - it just allows MakeRecord
144192      ** to process OPFLAG_NOCHANGE values without an assert() failing. */
144193      if( eDest==SRT_Table && pDest->iSDParm2 ){
144194        sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
144195      }
144196#endif
144197#ifndef SQLITE_OMIT_CTE
144198      if( eDest==SRT_DistFifo ){
144199        /* If the destination is DistFifo, then cursor (iParm+1) is open
144200        ** on an ephemeral index. If the current row is already present
144201        ** in the index, do not write it to the output. If not, add the
144202        ** current row to the index and proceed with writing it to the
144203        ** output table as well.  */
144204        int addr = sqlite3VdbeCurrentAddr(v) + 4;
144205        sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
144206        VdbeCoverage(v);
144207        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
144208        assert( pSort==0 );
144209      }
144210#endif
144211      if( pSort ){
144212        assert( regResult==regOrig );
144213        pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
144214      }else{
144215        int r2 = sqlite3GetTempReg(pParse);
144216        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
144217        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
144218        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
144219        sqlite3ReleaseTempReg(pParse, r2);
144220      }
144221      sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
144222      break;
144223    }
144224
144225    case SRT_Upfrom: {
144226      if( pSort ){
144227        pushOntoSorter(
144228            pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
144229      }else{
144230        int i2 = pDest->iSDParm2;
144231        int r1 = sqlite3GetTempReg(pParse);
144232
144233        /* If the UPDATE FROM join is an aggregate that matches no rows, it
144234        ** might still be trying to return one row, because that is what
144235        ** aggregates do.  Don't record that empty row in the output table. */
144236        sqlite3VdbeAddOp2(v, OP_IsNull, regResult, iBreak); VdbeCoverage(v);
144237
144238        sqlite3VdbeAddOp3(v, OP_MakeRecord,
144239                          regResult+(i2<0), nResultCol-(i2<0), r1);
144240        if( i2<0 ){
144241          sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regResult);
144242        }else{
144243          sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, i2);
144244        }
144245      }
144246      break;
144247    }
144248
144249#ifndef SQLITE_OMIT_SUBQUERY
144250    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
144251    ** then there should be a single item on the stack.  Write this
144252    ** item into the set table with bogus data.
144253    */
144254    case SRT_Set: {
144255      if( pSort ){
144256        /* At first glance you would think we could optimize out the
144257        ** ORDER BY in this case since the order of entries in the set
144258        ** does not matter.  But there might be a LIMIT clause, in which
144259        ** case the order does matter */
144260        pushOntoSorter(
144261            pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
144262      }else{
144263        int r1 = sqlite3GetTempReg(pParse);
144264        assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
144265        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
144266            r1, pDest->zAffSdst, nResultCol);
144267        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
144268        sqlite3ReleaseTempReg(pParse, r1);
144269      }
144270      break;
144271    }
144272
144273
144274    /* If any row exist in the result set, record that fact and abort.
144275    */
144276    case SRT_Exists: {
144277      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
144278      /* The LIMIT clause will terminate the loop for us */
144279      break;
144280    }
144281
144282    /* If this is a scalar select that is part of an expression, then
144283    ** store the results in the appropriate memory cell or array of
144284    ** memory cells and break out of the scan loop.
144285    */
144286    case SRT_Mem: {
144287      if( pSort ){
144288        assert( nResultCol<=pDest->nSdst );
144289        pushOntoSorter(
144290            pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
144291      }else{
144292        assert( nResultCol==pDest->nSdst );
144293        assert( regResult==iParm );
144294        /* The LIMIT clause will jump out of the loop for us */
144295      }
144296      break;
144297    }
144298#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
144299
144300    case SRT_Coroutine:       /* Send data to a co-routine */
144301    case SRT_Output: {        /* Return the results */
144302      testcase( eDest==SRT_Coroutine );
144303      testcase( eDest==SRT_Output );
144304      if( pSort ){
144305        pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
144306                       nPrefixReg);
144307      }else if( eDest==SRT_Coroutine ){
144308        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
144309      }else{
144310        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
144311      }
144312      break;
144313    }
144314
144315#ifndef SQLITE_OMIT_CTE
144316    /* Write the results into a priority queue that is order according to
144317    ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
144318    ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
144319    ** pSO->nExpr columns, then make sure all keys are unique by adding a
144320    ** final OP_Sequence column.  The last column is the record as a blob.
144321    */
144322    case SRT_DistQueue:
144323    case SRT_Queue: {
144324      int nKey;
144325      int r1, r2, r3;
144326      int addrTest = 0;
144327      ExprList *pSO;
144328      pSO = pDest->pOrderBy;
144329      assert( pSO );
144330      nKey = pSO->nExpr;
144331      r1 = sqlite3GetTempReg(pParse);
144332      r2 = sqlite3GetTempRange(pParse, nKey+2);
144333      r3 = r2+nKey+1;
144334      if( eDest==SRT_DistQueue ){
144335        /* If the destination is DistQueue, then cursor (iParm+1) is open
144336        ** on a second ephemeral index that holds all values every previously
144337        ** added to the queue. */
144338        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
144339                                        regResult, nResultCol);
144340        VdbeCoverage(v);
144341      }
144342      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
144343      if( eDest==SRT_DistQueue ){
144344        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
144345        sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
144346      }
144347      for(i=0; i<nKey; i++){
144348        sqlite3VdbeAddOp2(v, OP_SCopy,
144349                          regResult + pSO->a[i].u.x.iOrderByCol - 1,
144350                          r2+i);
144351      }
144352      sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
144353      sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
144354      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
144355      if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
144356      sqlite3ReleaseTempReg(pParse, r1);
144357      sqlite3ReleaseTempRange(pParse, r2, nKey+2);
144358      break;
144359    }
144360#endif /* SQLITE_OMIT_CTE */
144361
144362
144363
144364#if !defined(SQLITE_OMIT_TRIGGER)
144365    /* Discard the results.  This is used for SELECT statements inside
144366    ** the body of a TRIGGER.  The purpose of such selects is to call
144367    ** user-defined functions that have side effects.  We do not care
144368    ** about the actual results of the select.
144369    */
144370    default: {
144371      assert( eDest==SRT_Discard );
144372      break;
144373    }
144374#endif
144375  }
144376
144377  /* Jump to the end of the loop if the LIMIT is reached.  Except, if
144378  ** there is a sorter, in which case the sorter has already limited
144379  ** the output for us.
144380  */
144381  if( pSort==0 && p->iLimit ){
144382    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
144383  }
144384}
144385
144386/*
144387** Allocate a KeyInfo object sufficient for an index of N key columns and
144388** X extra columns.
144389*/
144390SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
144391  int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
144392  KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
144393  if( p ){
144394    p->aSortFlags = (u8*)&p->aColl[N+X];
144395    p->nKeyField = (u16)N;
144396    p->nAllField = (u16)(N+X);
144397    p->enc = ENC(db);
144398    p->db = db;
144399    p->nRef = 1;
144400    memset(&p[1], 0, nExtra);
144401  }else{
144402    return (KeyInfo*)sqlite3OomFault(db);
144403  }
144404  return p;
144405}
144406
144407/*
144408** Deallocate a KeyInfo object
144409*/
144410SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
144411  if( p ){
144412    assert( p->db!=0 );
144413    assert( p->nRef>0 );
144414    p->nRef--;
144415    if( p->nRef==0 ) sqlite3DbNNFreeNN(p->db, p);
144416  }
144417}
144418
144419/*
144420** Make a new pointer to a KeyInfo object
144421*/
144422SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
144423  if( p ){
144424    assert( p->nRef>0 );
144425    p->nRef++;
144426  }
144427  return p;
144428}
144429
144430#ifdef SQLITE_DEBUG
144431/*
144432** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
144433** can only be changed if this is just a single reference to the object.
144434**
144435** This routine is used only inside of assert() statements.
144436*/
144437SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
144438#endif /* SQLITE_DEBUG */
144439
144440/*
144441** Given an expression list, generate a KeyInfo structure that records
144442** the collating sequence for each expression in that expression list.
144443**
144444** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
144445** KeyInfo structure is appropriate for initializing a virtual index to
144446** implement that clause.  If the ExprList is the result set of a SELECT
144447** then the KeyInfo structure is appropriate for initializing a virtual
144448** index to implement a DISTINCT test.
144449**
144450** Space to hold the KeyInfo structure is obtained from malloc.  The calling
144451** function is responsible for seeing that this structure is eventually
144452** freed.
144453*/
144454SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(
144455  Parse *pParse,       /* Parsing context */
144456  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
144457  int iStart,          /* Begin with this column of pList */
144458  int nExtra           /* Add this many extra columns to the end */
144459){
144460  int nExpr;
144461  KeyInfo *pInfo;
144462  struct ExprList_item *pItem;
144463  sqlite3 *db = pParse->db;
144464  int i;
144465
144466  nExpr = pList->nExpr;
144467  pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
144468  if( pInfo ){
144469    assert( sqlite3KeyInfoIsWriteable(pInfo) );
144470    for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
144471      pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
144472      pInfo->aSortFlags[i-iStart] = pItem->fg.sortFlags;
144473    }
144474  }
144475  return pInfo;
144476}
144477
144478/*
144479** Name of the connection operator, used for error messages.
144480*/
144481SQLITE_PRIVATE const char *sqlite3SelectOpName(int id){
144482  char *z;
144483  switch( id ){
144484    case TK_ALL:       z = "UNION ALL";   break;
144485    case TK_INTERSECT: z = "INTERSECT";   break;
144486    case TK_EXCEPT:    z = "EXCEPT";      break;
144487    default:           z = "UNION";       break;
144488  }
144489  return z;
144490}
144491
144492#ifndef SQLITE_OMIT_EXPLAIN
144493/*
144494** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
144495** is a no-op. Otherwise, it adds a single row of output to the EQP result,
144496** where the caption is of the form:
144497**
144498**   "USE TEMP B-TREE FOR xxx"
144499**
144500** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
144501** is determined by the zUsage argument.
144502*/
144503static void explainTempTable(Parse *pParse, const char *zUsage){
144504  ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
144505}
144506
144507/*
144508** Assign expression b to lvalue a. A second, no-op, version of this macro
144509** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
144510** in sqlite3Select() to assign values to structure member variables that
144511** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
144512** code with #ifndef directives.
144513*/
144514# define explainSetInteger(a, b) a = b
144515
144516#else
144517/* No-op versions of the explainXXX() functions and macros. */
144518# define explainTempTable(y,z)
144519# define explainSetInteger(y,z)
144520#endif
144521
144522
144523/*
144524** If the inner loop was generated using a non-null pOrderBy argument,
144525** then the results were placed in a sorter.  After the loop is terminated
144526** we need to run the sorter and output the results.  The following
144527** routine generates the code needed to do that.
144528*/
144529static void generateSortTail(
144530  Parse *pParse,    /* Parsing context */
144531  Select *p,        /* The SELECT statement */
144532  SortCtx *pSort,   /* Information on the ORDER BY clause */
144533  int nColumn,      /* Number of columns of data */
144534  SelectDest *pDest /* Write the sorted results here */
144535){
144536  Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
144537  int addrBreak = pSort->labelDone;            /* Jump here to exit loop */
144538  int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
144539  int addr;                       /* Top of output loop. Jump for Next. */
144540  int addrOnce = 0;
144541  int iTab;
144542  ExprList *pOrderBy = pSort->pOrderBy;
144543  int eDest = pDest->eDest;
144544  int iParm = pDest->iSDParm;
144545  int regRow;
144546  int regRowid;
144547  int iCol;
144548  int nKey;                       /* Number of key columns in sorter record */
144549  int iSortTab;                   /* Sorter cursor to read from */
144550  int i;
144551  int bSeq;                       /* True if sorter record includes seq. no. */
144552  int nRefKey = 0;
144553  struct ExprList_item *aOutEx = p->pEList->a;
144554#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
144555  int addrExplain;                /* Address of OP_Explain instruction */
144556#endif
144557
144558  nKey = pOrderBy->nExpr - pSort->nOBSat;
144559  if( pSort->nOBSat==0 || nKey==1 ){
144560    ExplainQueryPlan2(addrExplain, (pParse, 0,
144561      "USE TEMP B-TREE FOR %sORDER BY", pSort->nOBSat?"LAST TERM OF ":""
144562    ));
144563  }else{
144564    ExplainQueryPlan2(addrExplain, (pParse, 0,
144565      "USE TEMP B-TREE FOR LAST %d TERMS OF ORDER BY", nKey
144566    ));
144567  }
144568  sqlite3VdbeScanStatusRange(v, addrExplain,pSort->addrPush,pSort->addrPushEnd);
144569  sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, pSort->addrPush);
144570
144571
144572  assert( addrBreak<0 );
144573  if( pSort->labelBkOut ){
144574    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
144575    sqlite3VdbeGoto(v, addrBreak);
144576    sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
144577  }
144578
144579#ifdef SQLITE_ENABLE_SORTER_REFERENCES
144580  /* Open any cursors needed for sorter-reference expressions */
144581  for(i=0; i<pSort->nDefer; i++){
144582    Table *pTab = pSort->aDefer[i].pTab;
144583    int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
144584    sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
144585    nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
144586  }
144587#endif
144588
144589  iTab = pSort->iECursor;
144590  if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
144591    if( eDest==SRT_Mem && p->iOffset ){
144592      sqlite3VdbeAddOp2(v, OP_Null, 0, pDest->iSdst);
144593    }
144594    regRowid = 0;
144595    regRow = pDest->iSdst;
144596  }else{
144597    regRowid = sqlite3GetTempReg(pParse);
144598    if( eDest==SRT_EphemTab || eDest==SRT_Table ){
144599      regRow = sqlite3GetTempReg(pParse);
144600      nColumn = 0;
144601    }else{
144602      regRow = sqlite3GetTempRange(pParse, nColumn);
144603    }
144604  }
144605  if( pSort->sortFlags & SORTFLAG_UseSorter ){
144606    int regSortOut = ++pParse->nMem;
144607    iSortTab = pParse->nTab++;
144608    if( pSort->labelBkOut ){
144609      addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
144610    }
144611    sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
144612        nKey+1+nColumn+nRefKey);
144613    if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
144614    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
144615    VdbeCoverage(v);
144616    assert( p->iLimit==0 && p->iOffset==0 );
144617    sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
144618    bSeq = 0;
144619  }else{
144620    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
144621    codeOffset(v, p->iOffset, addrContinue);
144622    iSortTab = iTab;
144623    bSeq = 1;
144624    if( p->iOffset>0 ){
144625      sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
144626    }
144627  }
144628  for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
144629#ifdef SQLITE_ENABLE_SORTER_REFERENCES
144630    if( aOutEx[i].fg.bSorterRef ) continue;
144631#endif
144632    if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
144633  }
144634#ifdef SQLITE_ENABLE_SORTER_REFERENCES
144635  if( pSort->nDefer ){
144636    int iKey = iCol+1;
144637    int regKey = sqlite3GetTempRange(pParse, nRefKey);
144638
144639    for(i=0; i<pSort->nDefer; i++){
144640      int iCsr = pSort->aDefer[i].iCsr;
144641      Table *pTab = pSort->aDefer[i].pTab;
144642      int nKey = pSort->aDefer[i].nKey;
144643
144644      sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
144645      if( HasRowid(pTab) ){
144646        sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
144647        sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
144648            sqlite3VdbeCurrentAddr(v)+1, regKey);
144649      }else{
144650        int k;
144651        int iJmp;
144652        assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
144653        for(k=0; k<nKey; k++){
144654          sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
144655        }
144656        iJmp = sqlite3VdbeCurrentAddr(v);
144657        sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
144658        sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
144659        sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
144660      }
144661    }
144662    sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
144663  }
144664#endif
144665  for(i=nColumn-1; i>=0; i--){
144666#ifdef SQLITE_ENABLE_SORTER_REFERENCES
144667    if( aOutEx[i].fg.bSorterRef ){
144668      sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
144669    }else
144670#endif
144671    {
144672      int iRead;
144673      if( aOutEx[i].u.x.iOrderByCol ){
144674        iRead = aOutEx[i].u.x.iOrderByCol-1;
144675      }else{
144676        iRead = iCol--;
144677      }
144678      sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
144679      VdbeComment((v, "%s", aOutEx[i].zEName));
144680    }
144681  }
144682  sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
144683  switch( eDest ){
144684    case SRT_Table:
144685    case SRT_EphemTab: {
144686      sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
144687      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
144688      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
144689      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
144690      break;
144691    }
144692#ifndef SQLITE_OMIT_SUBQUERY
144693    case SRT_Set: {
144694      assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
144695      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
144696                        pDest->zAffSdst, nColumn);
144697      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
144698      break;
144699    }
144700    case SRT_Mem: {
144701      /* The LIMIT clause will terminate the loop for us */
144702      break;
144703    }
144704#endif
144705    case SRT_Upfrom: {
144706      int i2 = pDest->iSDParm2;
144707      int r1 = sqlite3GetTempReg(pParse);
144708      sqlite3VdbeAddOp3(v, OP_MakeRecord,regRow+(i2<0),nColumn-(i2<0),r1);
144709      if( i2<0 ){
144710        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regRow);
144711      }else{
144712        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regRow, i2);
144713      }
144714      break;
144715    }
144716    default: {
144717      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
144718      testcase( eDest==SRT_Output );
144719      testcase( eDest==SRT_Coroutine );
144720      if( eDest==SRT_Output ){
144721        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
144722      }else{
144723        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
144724      }
144725      break;
144726    }
144727  }
144728  if( regRowid ){
144729    if( eDest==SRT_Set ){
144730      sqlite3ReleaseTempRange(pParse, regRow, nColumn);
144731    }else{
144732      sqlite3ReleaseTempReg(pParse, regRow);
144733    }
144734    sqlite3ReleaseTempReg(pParse, regRowid);
144735  }
144736  /* The bottom of the loop
144737  */
144738  sqlite3VdbeResolveLabel(v, addrContinue);
144739  if( pSort->sortFlags & SORTFLAG_UseSorter ){
144740    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
144741  }else{
144742    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
144743  }
144744  sqlite3VdbeScanStatusRange(v, addrExplain, sqlite3VdbeCurrentAddr(v)-1, -1);
144745  if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
144746  sqlite3VdbeResolveLabel(v, addrBreak);
144747}
144748
144749/*
144750** Return a pointer to a string containing the 'declaration type' of the
144751** expression pExpr. The string may be treated as static by the caller.
144752**
144753** The declaration type is the exact datatype definition extracted from the
144754** original CREATE TABLE statement if the expression is a column. The
144755** declaration type for a ROWID field is INTEGER. Exactly when an expression
144756** is considered a column can be complex in the presence of subqueries. The
144757** result-set expression in all of the following SELECT statements is
144758** considered a column by this function.
144759**
144760**   SELECT col FROM tbl;
144761**   SELECT (SELECT col FROM tbl;
144762**   SELECT (SELECT col FROM tbl);
144763**   SELECT abc FROM (SELECT col AS abc FROM tbl);
144764**
144765** The declaration type for any expression other than a column is NULL.
144766**
144767** This routine has either 3 or 6 parameters depending on whether or not
144768** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
144769*/
144770#ifdef SQLITE_ENABLE_COLUMN_METADATA
144771# define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
144772#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
144773# define columnType(A,B,C,D,E) columnTypeImpl(A,B)
144774#endif
144775static const char *columnTypeImpl(
144776  NameContext *pNC,
144777#ifndef SQLITE_ENABLE_COLUMN_METADATA
144778  Expr *pExpr
144779#else
144780  Expr *pExpr,
144781  const char **pzOrigDb,
144782  const char **pzOrigTab,
144783  const char **pzOrigCol
144784#endif
144785){
144786  char const *zType = 0;
144787  int j;
144788#ifdef SQLITE_ENABLE_COLUMN_METADATA
144789  char const *zOrigDb = 0;
144790  char const *zOrigTab = 0;
144791  char const *zOrigCol = 0;
144792#endif
144793
144794  assert( pExpr!=0 );
144795  assert( pNC->pSrcList!=0 );
144796  switch( pExpr->op ){
144797    case TK_COLUMN: {
144798      /* The expression is a column. Locate the table the column is being
144799      ** extracted from in NameContext.pSrcList. This table may be real
144800      ** database table or a subquery.
144801      */
144802      Table *pTab = 0;            /* Table structure column is extracted from */
144803      Select *pS = 0;             /* Select the column is extracted from */
144804      int iCol = pExpr->iColumn;  /* Index of column in pTab */
144805      while( pNC && !pTab ){
144806        SrcList *pTabList = pNC->pSrcList;
144807        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
144808        if( j<pTabList->nSrc ){
144809          pTab = pTabList->a[j].pTab;
144810          pS = pTabList->a[j].pSelect;
144811        }else{
144812          pNC = pNC->pNext;
144813        }
144814      }
144815
144816      if( pTab==0 ){
144817        /* At one time, code such as "SELECT new.x" within a trigger would
144818        ** cause this condition to run.  Since then, we have restructured how
144819        ** trigger code is generated and so this condition is no longer
144820        ** possible. However, it can still be true for statements like
144821        ** the following:
144822        **
144823        **   CREATE TABLE t1(col INTEGER);
144824        **   SELECT (SELECT t1.col) FROM FROM t1;
144825        **
144826        ** when columnType() is called on the expression "t1.col" in the
144827        ** sub-select. In this case, set the column type to NULL, even
144828        ** though it should really be "INTEGER".
144829        **
144830        ** This is not a problem, as the column type of "t1.col" is never
144831        ** used. When columnType() is called on the expression
144832        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
144833        ** branch below.  */
144834        break;
144835      }
144836
144837      assert( pTab && ExprUseYTab(pExpr) && pExpr->y.pTab==pTab );
144838      if( pS ){
144839        /* The "table" is actually a sub-select or a view in the FROM clause
144840        ** of the SELECT statement. Return the declaration type and origin
144841        ** data for the result-set column of the sub-select.
144842        */
144843        if( iCol<pS->pEList->nExpr
144844         && (!ViewCanHaveRowid || iCol>=0)
144845        ){
144846          /* If iCol is less than zero, then the expression requests the
144847          ** rowid of the sub-select or view. This expression is legal (see
144848          ** test case misc2.2.2) - it always evaluates to NULL.
144849          */
144850          NameContext sNC;
144851          Expr *p = pS->pEList->a[iCol].pExpr;
144852          sNC.pSrcList = pS->pSrc;
144853          sNC.pNext = pNC;
144854          sNC.pParse = pNC->pParse;
144855          zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
144856        }
144857      }else{
144858        /* A real table or a CTE table */
144859        assert( !pS );
144860#ifdef SQLITE_ENABLE_COLUMN_METADATA
144861        if( iCol<0 ) iCol = pTab->iPKey;
144862        assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
144863        if( iCol<0 ){
144864          zType = "INTEGER";
144865          zOrigCol = "rowid";
144866        }else{
144867          zOrigCol = pTab->aCol[iCol].zCnName;
144868          zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
144869        }
144870        zOrigTab = pTab->zName;
144871        if( pNC->pParse && pTab->pSchema ){
144872          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
144873          zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
144874        }
144875#else
144876        assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
144877        if( iCol<0 ){
144878          zType = "INTEGER";
144879        }else{
144880          zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
144881        }
144882#endif
144883      }
144884      break;
144885    }
144886#ifndef SQLITE_OMIT_SUBQUERY
144887    case TK_SELECT: {
144888      /* The expression is a sub-select. Return the declaration type and
144889      ** origin info for the single column in the result set of the SELECT
144890      ** statement.
144891      */
144892      NameContext sNC;
144893      Select *pS;
144894      Expr *p;
144895      assert( ExprUseXSelect(pExpr) );
144896      pS = pExpr->x.pSelect;
144897      p = pS->pEList->a[0].pExpr;
144898      sNC.pSrcList = pS->pSrc;
144899      sNC.pNext = pNC;
144900      sNC.pParse = pNC->pParse;
144901      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
144902      break;
144903    }
144904#endif
144905  }
144906
144907#ifdef SQLITE_ENABLE_COLUMN_METADATA
144908  if( pzOrigDb ){
144909    assert( pzOrigTab && pzOrigCol );
144910    *pzOrigDb = zOrigDb;
144911    *pzOrigTab = zOrigTab;
144912    *pzOrigCol = zOrigCol;
144913  }
144914#endif
144915  return zType;
144916}
144917
144918/*
144919** Generate code that will tell the VDBE the declaration types of columns
144920** in the result set.
144921*/
144922static void generateColumnTypes(
144923  Parse *pParse,      /* Parser context */
144924  SrcList *pTabList,  /* List of tables */
144925  ExprList *pEList    /* Expressions defining the result set */
144926){
144927#ifndef SQLITE_OMIT_DECLTYPE
144928  Vdbe *v = pParse->pVdbe;
144929  int i;
144930  NameContext sNC;
144931  sNC.pSrcList = pTabList;
144932  sNC.pParse = pParse;
144933  sNC.pNext = 0;
144934  for(i=0; i<pEList->nExpr; i++){
144935    Expr *p = pEList->a[i].pExpr;
144936    const char *zType;
144937#ifdef SQLITE_ENABLE_COLUMN_METADATA
144938    const char *zOrigDb = 0;
144939    const char *zOrigTab = 0;
144940    const char *zOrigCol = 0;
144941    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
144942
144943    /* The vdbe must make its own copy of the column-type and other
144944    ** column specific strings, in case the schema is reset before this
144945    ** virtual machine is deleted.
144946    */
144947    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
144948    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
144949    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
144950#else
144951    zType = columnType(&sNC, p, 0, 0, 0);
144952#endif
144953    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
144954  }
144955#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
144956}
144957
144958
144959/*
144960** Compute the column names for a SELECT statement.
144961**
144962** The only guarantee that SQLite makes about column names is that if the
144963** column has an AS clause assigning it a name, that will be the name used.
144964** That is the only documented guarantee.  However, countless applications
144965** developed over the years have made baseless assumptions about column names
144966** and will break if those assumptions changes.  Hence, use extreme caution
144967** when modifying this routine to avoid breaking legacy.
144968**
144969** See Also: sqlite3ColumnsFromExprList()
144970**
144971** The PRAGMA short_column_names and PRAGMA full_column_names settings are
144972** deprecated.  The default setting is short=ON, full=OFF.  99.9% of all
144973** applications should operate this way.  Nevertheless, we need to support the
144974** other modes for legacy:
144975**
144976**    short=OFF, full=OFF:      Column name is the text of the expression has it
144977**                              originally appears in the SELECT statement.  In
144978**                              other words, the zSpan of the result expression.
144979**
144980**    short=ON, full=OFF:       (This is the default setting).  If the result
144981**                              refers directly to a table column, then the
144982**                              result column name is just the table column
144983**                              name: COLUMN.  Otherwise use zSpan.
144984**
144985**    full=ON, short=ANY:       If the result refers directly to a table column,
144986**                              then the result column name with the table name
144987**                              prefix, ex: TABLE.COLUMN.  Otherwise use zSpan.
144988*/
144989SQLITE_PRIVATE void sqlite3GenerateColumnNames(
144990  Parse *pParse,      /* Parser context */
144991  Select *pSelect     /* Generate column names for this SELECT statement */
144992){
144993  Vdbe *v = pParse->pVdbe;
144994  int i;
144995  Table *pTab;
144996  SrcList *pTabList;
144997  ExprList *pEList;
144998  sqlite3 *db = pParse->db;
144999  int fullName;    /* TABLE.COLUMN if no AS clause and is a direct table ref */
145000  int srcName;     /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
145001
145002  if( pParse->colNamesSet ) return;
145003  /* Column names are determined by the left-most term of a compound select */
145004  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
145005  TREETRACE(0x80,pParse,pSelect,("generating column names\n"));
145006  pTabList = pSelect->pSrc;
145007  pEList = pSelect->pEList;
145008  assert( v!=0 );
145009  assert( pTabList!=0 );
145010  pParse->colNamesSet = 1;
145011  fullName = (db->flags & SQLITE_FullColNames)!=0;
145012  srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
145013  sqlite3VdbeSetNumCols(v, pEList->nExpr);
145014  for(i=0; i<pEList->nExpr; i++){
145015    Expr *p = pEList->a[i].pExpr;
145016
145017    assert( p!=0 );
145018    assert( p->op!=TK_AGG_COLUMN );  /* Agg processing has not run yet */
145019    assert( p->op!=TK_COLUMN
145020        || (ExprUseYTab(p) && p->y.pTab!=0) ); /* Covering idx not yet coded */
145021    if( pEList->a[i].zEName && pEList->a[i].fg.eEName==ENAME_NAME ){
145022      /* An AS clause always takes first priority */
145023      char *zName = pEList->a[i].zEName;
145024      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
145025    }else if( srcName && p->op==TK_COLUMN ){
145026      char *zCol;
145027      int iCol = p->iColumn;
145028      pTab = p->y.pTab;
145029      assert( pTab!=0 );
145030      if( iCol<0 ) iCol = pTab->iPKey;
145031      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
145032      if( iCol<0 ){
145033        zCol = "rowid";
145034      }else{
145035        zCol = pTab->aCol[iCol].zCnName;
145036      }
145037      if( fullName ){
145038        char *zName = 0;
145039        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
145040        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
145041      }else{
145042        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
145043      }
145044    }else{
145045      const char *z = pEList->a[i].zEName;
145046      z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
145047      sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
145048    }
145049  }
145050  generateColumnTypes(pParse, pTabList, pEList);
145051}
145052
145053/*
145054** Given an expression list (which is really the list of expressions
145055** that form the result set of a SELECT statement) compute appropriate
145056** column names for a table that would hold the expression list.
145057**
145058** All column names will be unique.
145059**
145060** Only the column names are computed.  Column.zType, Column.zColl,
145061** and other fields of Column are zeroed.
145062**
145063** Return SQLITE_OK on success.  If a memory allocation error occurs,
145064** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
145065**
145066** The only guarantee that SQLite makes about column names is that if the
145067** column has an AS clause assigning it a name, that will be the name used.
145068** That is the only documented guarantee.  However, countless applications
145069** developed over the years have made baseless assumptions about column names
145070** and will break if those assumptions changes.  Hence, use extreme caution
145071** when modifying this routine to avoid breaking legacy.
145072**
145073** See Also: sqlite3GenerateColumnNames()
145074*/
145075SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
145076  Parse *pParse,          /* Parsing context */
145077  ExprList *pEList,       /* Expr list from which to derive column names */
145078  i16 *pnCol,             /* Write the number of columns here */
145079  Column **paCol          /* Write the new column list here */
145080){
145081  sqlite3 *db = pParse->db;   /* Database connection */
145082  int i, j;                   /* Loop counters */
145083  u32 cnt;                    /* Index added to make the name unique */
145084  Column *aCol, *pCol;        /* For looping over result columns */
145085  int nCol;                   /* Number of columns in the result set */
145086  char *zName;                /* Column name */
145087  int nName;                  /* Size of name in zName[] */
145088  Hash ht;                    /* Hash table of column names */
145089  Table *pTab;
145090
145091  sqlite3HashInit(&ht);
145092  if( pEList ){
145093    nCol = pEList->nExpr;
145094    aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
145095    testcase( aCol==0 );
145096    if( NEVER(nCol>32767) ) nCol = 32767;
145097  }else{
145098    nCol = 0;
145099    aCol = 0;
145100  }
145101  assert( nCol==(i16)nCol );
145102  *pnCol = nCol;
145103  *paCol = aCol;
145104
145105  for(i=0, pCol=aCol; i<nCol && !pParse->nErr; i++, pCol++){
145106    struct ExprList_item *pX = &pEList->a[i];
145107    struct ExprList_item *pCollide;
145108    /* Get an appropriate name for the column
145109    */
145110    if( (zName = pX->zEName)!=0 && pX->fg.eEName==ENAME_NAME ){
145111      /* If the column contains an "AS <name>" phrase, use <name> as the name */
145112    }else{
145113      Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pX->pExpr);
145114      while( ALWAYS(pColExpr!=0) && pColExpr->op==TK_DOT ){
145115        pColExpr = pColExpr->pRight;
145116        assert( pColExpr!=0 );
145117      }
145118      if( pColExpr->op==TK_COLUMN
145119       && ALWAYS( ExprUseYTab(pColExpr) )
145120       && ALWAYS( pColExpr->y.pTab!=0 )
145121      ){
145122        /* For columns use the column name name */
145123        int iCol = pColExpr->iColumn;
145124        pTab = pColExpr->y.pTab;
145125        if( iCol<0 ) iCol = pTab->iPKey;
145126        zName = iCol>=0 ? pTab->aCol[iCol].zCnName : "rowid";
145127      }else if( pColExpr->op==TK_ID ){
145128        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
145129        zName = pColExpr->u.zToken;
145130      }else{
145131        /* Use the original text of the column expression as its name */
145132        assert( zName==pX->zEName );  /* pointer comparison intended */
145133      }
145134    }
145135    if( zName && !sqlite3IsTrueOrFalse(zName) ){
145136      zName = sqlite3DbStrDup(db, zName);
145137    }else{
145138      zName = sqlite3MPrintf(db,"column%d",i+1);
145139    }
145140
145141    /* Make sure the column name is unique.  If the name is not unique,
145142    ** append an integer to the name so that it becomes unique.
145143    */
145144    cnt = 0;
145145    while( zName && (pCollide = sqlite3HashFind(&ht, zName))!=0 ){
145146      if( pCollide->fg.bUsingTerm ){
145147        pCol->colFlags |= COLFLAG_NOEXPAND;
145148      }
145149      nName = sqlite3Strlen30(zName);
145150      if( nName>0 ){
145151        for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
145152        if( zName[j]==':' ) nName = j;
145153      }
145154      zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
145155      sqlite3ProgressCheck(pParse);
145156      if( cnt>3 ){
145157        sqlite3_randomness(sizeof(cnt), &cnt);
145158      }
145159    }
145160    pCol->zCnName = zName;
145161    pCol->hName = sqlite3StrIHash(zName);
145162    if( pX->fg.bNoExpand ){
145163      pCol->colFlags |= COLFLAG_NOEXPAND;
145164    }
145165    sqlite3ColumnPropertiesFromName(0, pCol);
145166    if( zName && sqlite3HashInsert(&ht, zName, pX)==pX ){
145167      sqlite3OomFault(db);
145168    }
145169  }
145170  sqlite3HashClear(&ht);
145171  if( pParse->nErr ){
145172    for(j=0; j<i; j++){
145173      sqlite3DbFree(db, aCol[j].zCnName);
145174    }
145175    sqlite3DbFree(db, aCol);
145176    *paCol = 0;
145177    *pnCol = 0;
145178    return pParse->rc;
145179  }
145180  return SQLITE_OK;
145181}
145182
145183/*
145184** pTab is a transient Table object that represents a subquery of some
145185** kind (maybe a parenthesized subquery in the FROM clause of a larger
145186** query, or a VIEW, or a CTE).  This routine computes type information
145187** for that Table object based on the Select object that implements the
145188** subquery.  For the purposes of this routine, "type information" means:
145189**
145190**    *   The datatype name, as it might appear in a CREATE TABLE statement
145191**    *   Which collating sequence to use for the column
145192**    *   The affinity of the column
145193*/
145194SQLITE_PRIVATE void sqlite3SubqueryColumnTypes(
145195  Parse *pParse,      /* Parsing contexts */
145196  Table *pTab,        /* Add column type information to this table */
145197  Select *pSelect,    /* SELECT used to determine types and collations */
145198  char aff            /* Default affinity. */
145199){
145200  sqlite3 *db = pParse->db;
145201  Column *pCol;
145202  CollSeq *pColl;
145203  int i,j;
145204  Expr *p;
145205  struct ExprList_item *a;
145206  NameContext sNC;
145207
145208  assert( pSelect!=0 );
145209  assert( (pSelect->selFlags & SF_Resolved)!=0 );
145210  assert( pTab->nCol==pSelect->pEList->nExpr || pParse->nErr>0 );
145211  assert( aff==SQLITE_AFF_NONE || aff==SQLITE_AFF_BLOB );
145212  if( db->mallocFailed || IN_RENAME_OBJECT ) return;
145213  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
145214  a = pSelect->pEList->a;
145215  memset(&sNC, 0, sizeof(sNC));
145216  sNC.pSrcList = pSelect->pSrc;
145217  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
145218    const char *zType;
145219    i64 n;
145220    int m = 0;
145221    Select *pS2 = pSelect;
145222    pTab->tabFlags |= (pCol->colFlags & COLFLAG_NOINSERT);
145223    p = a[i].pExpr;
145224    /* pCol->szEst = ... // Column size est for SELECT tables never used */
145225    pCol->affinity = sqlite3ExprAffinity(p);
145226    while( pCol->affinity<=SQLITE_AFF_NONE && pS2->pNext!=0 ){
145227      m |= sqlite3ExprDataType(pS2->pEList->a[i].pExpr);
145228      pS2 = pS2->pNext;
145229      pCol->affinity = sqlite3ExprAffinity(pS2->pEList->a[i].pExpr);
145230    }
145231    if( pCol->affinity<=SQLITE_AFF_NONE ){
145232      pCol->affinity = aff;
145233    }
145234    if( pCol->affinity>=SQLITE_AFF_TEXT && (pS2->pNext || pS2!=pSelect) ){
145235      for(pS2=pS2->pNext; pS2; pS2=pS2->pNext){
145236        m |= sqlite3ExprDataType(pS2->pEList->a[i].pExpr);
145237      }
145238      if( pCol->affinity==SQLITE_AFF_TEXT && (m&0x01)!=0 ){
145239        pCol->affinity = SQLITE_AFF_BLOB;
145240      }else
145241      if( pCol->affinity>=SQLITE_AFF_NUMERIC && (m&0x02)!=0 ){
145242        pCol->affinity = SQLITE_AFF_BLOB;
145243      }
145244      if( pCol->affinity>=SQLITE_AFF_NUMERIC && p->op==TK_CAST ){
145245        pCol->affinity = SQLITE_AFF_FLEXNUM;
145246      }
145247    }
145248    zType = columnType(&sNC, p, 0, 0, 0);
145249    if( zType==0 || pCol->affinity!=sqlite3AffinityType(zType, 0) ){
145250      if( pCol->affinity==SQLITE_AFF_NUMERIC
145251       || pCol->affinity==SQLITE_AFF_FLEXNUM
145252      ){
145253        zType = "NUM";
145254      }else{
145255        zType = 0;
145256        for(j=1; j<SQLITE_N_STDTYPE; j++){
145257          if( sqlite3StdTypeAffinity[j]==pCol->affinity ){
145258            zType = sqlite3StdType[j];
145259            break;
145260          }
145261        }
145262      }
145263    }
145264    if( zType ){
145265      const i64 k = sqlite3Strlen30(zType);
145266      n = sqlite3Strlen30(pCol->zCnName);
145267      pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+k+2);
145268      pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL);
145269      if( pCol->zCnName ){
145270        memcpy(&pCol->zCnName[n+1], zType, k+1);
145271        pCol->colFlags |= COLFLAG_HASTYPE;
145272      }
145273    }
145274    pColl = sqlite3ExprCollSeq(pParse, p);
145275    if( pColl ){
145276      assert( pTab->pIndex==0 );
145277      sqlite3ColumnSetColl(db, pCol, pColl->zName);
145278    }
145279  }
145280  pTab->szTabRow = 1; /* Any non-zero value works */
145281}
145282
145283/*
145284** Given a SELECT statement, generate a Table structure that describes
145285** the result set of that SELECT.
145286*/
145287SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
145288  Table *pTab;
145289  sqlite3 *db = pParse->db;
145290  u64 savedFlags;
145291
145292  savedFlags = db->flags;
145293  db->flags &= ~(u64)SQLITE_FullColNames;
145294  db->flags |= SQLITE_ShortColNames;
145295  sqlite3SelectPrep(pParse, pSelect, 0);
145296  db->flags = savedFlags;
145297  if( pParse->nErr ) return 0;
145298  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
145299  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
145300  if( pTab==0 ){
145301    return 0;
145302  }
145303  pTab->nTabRef = 1;
145304  pTab->zName = 0;
145305  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
145306  sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
145307  sqlite3SubqueryColumnTypes(pParse, pTab, pSelect, aff);
145308  pTab->iPKey = -1;
145309  if( db->mallocFailed ){
145310    sqlite3DeleteTable(db, pTab);
145311    return 0;
145312  }
145313  return pTab;
145314}
145315
145316/*
145317** Get a VDBE for the given parser context.  Create a new one if necessary.
145318** If an error occurs, return NULL and leave a message in pParse.
145319*/
145320SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
145321  if( pParse->pVdbe ){
145322    return pParse->pVdbe;
145323  }
145324  if( pParse->pToplevel==0
145325   && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
145326  ){
145327    pParse->okConstFactor = 1;
145328  }
145329  return sqlite3VdbeCreate(pParse);
145330}
145331
145332
145333/*
145334** Compute the iLimit and iOffset fields of the SELECT based on the
145335** pLimit expressions.  pLimit->pLeft and pLimit->pRight hold the expressions
145336** that appear in the original SQL statement after the LIMIT and OFFSET
145337** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
145338** are the integer memory register numbers for counters used to compute
145339** the limit and offset.  If there is no limit and/or offset, then
145340** iLimit and iOffset are negative.
145341**
145342** This routine changes the values of iLimit and iOffset only if
145343** a limit or offset is defined by pLimit->pLeft and pLimit->pRight.  iLimit
145344** and iOffset should have been preset to appropriate default values (zero)
145345** prior to calling this routine.
145346**
145347** The iOffset register (if it exists) is initialized to the value
145348** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
145349** iOffset+1 is initialized to LIMIT+OFFSET.
145350**
145351** Only if pLimit->pLeft!=0 do the limit registers get
145352** redefined.  The UNION ALL operator uses this property to force
145353** the reuse of the same limit and offset registers across multiple
145354** SELECT statements.
145355*/
145356static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
145357  Vdbe *v = 0;
145358  int iLimit = 0;
145359  int iOffset;
145360  int n;
145361  Expr *pLimit = p->pLimit;
145362
145363  if( p->iLimit ) return;
145364
145365  /*
145366  ** "LIMIT -1" always shows all rows.  There is some
145367  ** controversy about what the correct behavior should be.
145368  ** The current implementation interprets "LIMIT 0" to mean
145369  ** no rows.
145370  */
145371  if( pLimit ){
145372    assert( pLimit->op==TK_LIMIT );
145373    assert( pLimit->pLeft!=0 );
145374    p->iLimit = iLimit = ++pParse->nMem;
145375    v = sqlite3GetVdbe(pParse);
145376    assert( v!=0 );
145377    if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
145378      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
145379      VdbeComment((v, "LIMIT counter"));
145380      if( n==0 ){
145381        sqlite3VdbeGoto(v, iBreak);
145382      }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
145383        p->nSelectRow = sqlite3LogEst((u64)n);
145384        p->selFlags |= SF_FixedLimit;
145385      }
145386    }else{
145387      sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
145388      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
145389      VdbeComment((v, "LIMIT counter"));
145390      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
145391    }
145392    if( pLimit->pRight ){
145393      p->iOffset = iOffset = ++pParse->nMem;
145394      pParse->nMem++;   /* Allocate an extra register for limit+offset */
145395      sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
145396      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
145397      VdbeComment((v, "OFFSET counter"));
145398      sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
145399      VdbeComment((v, "LIMIT+OFFSET"));
145400    }
145401  }
145402}
145403
145404#ifndef SQLITE_OMIT_COMPOUND_SELECT
145405/*
145406** Return the appropriate collating sequence for the iCol-th column of
145407** the result set for the compound-select statement "p".  Return NULL if
145408** the column has no default collating sequence.
145409**
145410** The collating sequence for the compound select is taken from the
145411** left-most term of the select that has a collating sequence.
145412*/
145413static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
145414  CollSeq *pRet;
145415  if( p->pPrior ){
145416    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
145417  }else{
145418    pRet = 0;
145419  }
145420  assert( iCol>=0 );
145421  /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
145422  ** have been thrown during name resolution and we would not have gotten
145423  ** this far */
145424  if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
145425    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
145426  }
145427  return pRet;
145428}
145429
145430/*
145431** The select statement passed as the second parameter is a compound SELECT
145432** with an ORDER BY clause. This function allocates and returns a KeyInfo
145433** structure suitable for implementing the ORDER BY.
145434**
145435** Space to hold the KeyInfo structure is obtained from malloc. The calling
145436** function is responsible for ensuring that this structure is eventually
145437** freed.
145438*/
145439static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
145440  ExprList *pOrderBy = p->pOrderBy;
145441  int nOrderBy = ALWAYS(pOrderBy!=0) ? pOrderBy->nExpr : 0;
145442  sqlite3 *db = pParse->db;
145443  KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
145444  if( pRet ){
145445    int i;
145446    for(i=0; i<nOrderBy; i++){
145447      struct ExprList_item *pItem = &pOrderBy->a[i];
145448      Expr *pTerm = pItem->pExpr;
145449      CollSeq *pColl;
145450
145451      if( pTerm->flags & EP_Collate ){
145452        pColl = sqlite3ExprCollSeq(pParse, pTerm);
145453      }else{
145454        pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
145455        if( pColl==0 ) pColl = db->pDfltColl;
145456        pOrderBy->a[i].pExpr =
145457          sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
145458      }
145459      assert( sqlite3KeyInfoIsWriteable(pRet) );
145460      pRet->aColl[i] = pColl;
145461      pRet->aSortFlags[i] = pOrderBy->a[i].fg.sortFlags;
145462    }
145463  }
145464
145465  return pRet;
145466}
145467
145468#ifndef SQLITE_OMIT_CTE
145469/*
145470** This routine generates VDBE code to compute the content of a WITH RECURSIVE
145471** query of the form:
145472**
145473**   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
145474**                         \___________/             \_______________/
145475**                           p->pPrior                      p
145476**
145477**
145478** There is exactly one reference to the recursive-table in the FROM clause
145479** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
145480**
145481** The setup-query runs once to generate an initial set of rows that go
145482** into a Queue table.  Rows are extracted from the Queue table one by
145483** one.  Each row extracted from Queue is output to pDest.  Then the single
145484** extracted row (now in the iCurrent table) becomes the content of the
145485** recursive-table for a recursive-query run.  The output of the recursive-query
145486** is added back into the Queue table.  Then another row is extracted from Queue
145487** and the iteration continues until the Queue table is empty.
145488**
145489** If the compound query operator is UNION then no duplicate rows are ever
145490** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
145491** that have ever been inserted into Queue and causes duplicates to be
145492** discarded.  If the operator is UNION ALL, then duplicates are allowed.
145493**
145494** If the query has an ORDER BY, then entries in the Queue table are kept in
145495** ORDER BY order and the first entry is extracted for each cycle.  Without
145496** an ORDER BY, the Queue table is just a FIFO.
145497**
145498** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
145499** have been output to pDest.  A LIMIT of zero means to output no rows and a
145500** negative LIMIT means to output all rows.  If there is also an OFFSET clause
145501** with a positive value, then the first OFFSET outputs are discarded rather
145502** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
145503** rows have been skipped.
145504*/
145505static void generateWithRecursiveQuery(
145506  Parse *pParse,        /* Parsing context */
145507  Select *p,            /* The recursive SELECT to be coded */
145508  SelectDest *pDest     /* What to do with query results */
145509){
145510  SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
145511  int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
145512  Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
145513  Select *pSetup;               /* The setup query */
145514  Select *pFirstRec;            /* Left-most recursive term */
145515  int addrTop;                  /* Top of the loop */
145516  int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
145517  int iCurrent = 0;             /* The Current table */
145518  int regCurrent;               /* Register holding Current table */
145519  int iQueue;                   /* The Queue table */
145520  int iDistinct = 0;            /* To ensure unique results if UNION */
145521  int eDest = SRT_Fifo;         /* How to write to Queue */
145522  SelectDest destQueue;         /* SelectDest targeting the Queue table */
145523  int i;                        /* Loop counter */
145524  int rc;                       /* Result code */
145525  ExprList *pOrderBy;           /* The ORDER BY clause */
145526  Expr *pLimit;                 /* Saved LIMIT and OFFSET */
145527  int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
145528
145529#ifndef SQLITE_OMIT_WINDOWFUNC
145530  if( p->pWin ){
145531    sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
145532    return;
145533  }
145534#endif
145535
145536  /* Obtain authorization to do a recursive query */
145537  if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
145538
145539  /* Process the LIMIT and OFFSET clauses, if they exist */
145540  addrBreak = sqlite3VdbeMakeLabel(pParse);
145541  p->nSelectRow = 320;  /* 4 billion rows */
145542  computeLimitRegisters(pParse, p, addrBreak);
145543  pLimit = p->pLimit;
145544  regLimit = p->iLimit;
145545  regOffset = p->iOffset;
145546  p->pLimit = 0;
145547  p->iLimit = p->iOffset = 0;
145548  pOrderBy = p->pOrderBy;
145549
145550  /* Locate the cursor number of the Current table */
145551  for(i=0; ALWAYS(i<pSrc->nSrc); i++){
145552    if( pSrc->a[i].fg.isRecursive ){
145553      iCurrent = pSrc->a[i].iCursor;
145554      break;
145555    }
145556  }
145557
145558  /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
145559  ** the Distinct table must be exactly one greater than Queue in order
145560  ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
145561  iQueue = pParse->nTab++;
145562  if( p->op==TK_UNION ){
145563    eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
145564    iDistinct = pParse->nTab++;
145565  }else{
145566    eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
145567  }
145568  sqlite3SelectDestInit(&destQueue, eDest, iQueue);
145569
145570  /* Allocate cursors for Current, Queue, and Distinct. */
145571  regCurrent = ++pParse->nMem;
145572  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
145573  if( pOrderBy ){
145574    KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
145575    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
145576                      (char*)pKeyInfo, P4_KEYINFO);
145577    destQueue.pOrderBy = pOrderBy;
145578  }else{
145579    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
145580  }
145581  VdbeComment((v, "Queue table"));
145582  if( iDistinct ){
145583    p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
145584    p->selFlags |= SF_UsesEphemeral;
145585  }
145586
145587  /* Detach the ORDER BY clause from the compound SELECT */
145588  p->pOrderBy = 0;
145589
145590  /* Figure out how many elements of the compound SELECT are part of the
145591  ** recursive query.  Make sure no recursive elements use aggregate
145592  ** functions.  Mark the recursive elements as UNION ALL even if they
145593  ** are really UNION because the distinctness will be enforced by the
145594  ** iDistinct table.  pFirstRec is left pointing to the left-most
145595  ** recursive term of the CTE.
145596  */
145597  for(pFirstRec=p; ALWAYS(pFirstRec!=0); pFirstRec=pFirstRec->pPrior){
145598    if( pFirstRec->selFlags & SF_Aggregate ){
145599      sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
145600      goto end_of_recursive_query;
145601    }
145602    pFirstRec->op = TK_ALL;
145603    if( (pFirstRec->pPrior->selFlags & SF_Recursive)==0 ) break;
145604  }
145605
145606  /* Store the results of the setup-query in Queue. */
145607  pSetup = pFirstRec->pPrior;
145608  pSetup->pNext = 0;
145609  ExplainQueryPlan((pParse, 1, "SETUP"));
145610  rc = sqlite3Select(pParse, pSetup, &destQueue);
145611  pSetup->pNext = p;
145612  if( rc ) goto end_of_recursive_query;
145613
145614  /* Find the next row in the Queue and output that row */
145615  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
145616
145617  /* Transfer the next row in Queue over to Current */
145618  sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
145619  if( pOrderBy ){
145620    sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
145621  }else{
145622    sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
145623  }
145624  sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
145625
145626  /* Output the single row in Current */
145627  addrCont = sqlite3VdbeMakeLabel(pParse);
145628  codeOffset(v, regOffset, addrCont);
145629  selectInnerLoop(pParse, p, iCurrent,
145630      0, 0, pDest, addrCont, addrBreak);
145631  if( regLimit ){
145632    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
145633    VdbeCoverage(v);
145634  }
145635  sqlite3VdbeResolveLabel(v, addrCont);
145636
145637  /* Execute the recursive SELECT taking the single row in Current as
145638  ** the value for the recursive-table. Store the results in the Queue.
145639  */
145640  pFirstRec->pPrior = 0;
145641  ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
145642  sqlite3Select(pParse, p, &destQueue);
145643  assert( pFirstRec->pPrior==0 );
145644  pFirstRec->pPrior = pSetup;
145645
145646  /* Keep running the loop until the Queue is empty */
145647  sqlite3VdbeGoto(v, addrTop);
145648  sqlite3VdbeResolveLabel(v, addrBreak);
145649
145650end_of_recursive_query:
145651  sqlite3ExprListDelete(pParse->db, p->pOrderBy);
145652  p->pOrderBy = pOrderBy;
145653  p->pLimit = pLimit;
145654  return;
145655}
145656#endif /* SQLITE_OMIT_CTE */
145657
145658/* Forward references */
145659static int multiSelectOrderBy(
145660  Parse *pParse,        /* Parsing context */
145661  Select *p,            /* The right-most of SELECTs to be coded */
145662  SelectDest *pDest     /* What to do with query results */
145663);
145664
145665/*
145666** Handle the special case of a compound-select that originates from a
145667** VALUES clause.  By handling this as a special case, we avoid deep
145668** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
145669** on a VALUES clause.
145670**
145671** Because the Select object originates from a VALUES clause:
145672**   (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
145673**   (2) All terms are UNION ALL
145674**   (3) There is no ORDER BY clause
145675**
145676** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
145677** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
145678** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
145679** Since the limit is exactly 1, we only need to evaluate the left-most VALUES.
145680*/
145681static int multiSelectValues(
145682  Parse *pParse,        /* Parsing context */
145683  Select *p,            /* The right-most of SELECTs to be coded */
145684  SelectDest *pDest     /* What to do with query results */
145685){
145686  int nRow = 1;
145687  int rc = 0;
145688  int bShowAll = p->pLimit==0;
145689  assert( p->selFlags & SF_MultiValue );
145690  do{
145691    assert( p->selFlags & SF_Values );
145692    assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
145693    assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
145694#ifndef SQLITE_OMIT_WINDOWFUNC
145695    if( p->pWin ) return -1;
145696#endif
145697    if( p->pPrior==0 ) break;
145698    assert( p->pPrior->pNext==p );
145699    p = p->pPrior;
145700    nRow += bShowAll;
145701  }while(1);
145702  ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
145703                    nRow==1 ? "" : "S"));
145704  while( p ){
145705    selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
145706    if( !bShowAll ) break;
145707    p->nSelectRow = nRow;
145708    p = p->pNext;
145709  }
145710  return rc;
145711}
145712
145713/*
145714** Return true if the SELECT statement which is known to be the recursive
145715** part of a recursive CTE still has its anchor terms attached.  If the
145716** anchor terms have already been removed, then return false.
145717*/
145718static int hasAnchor(Select *p){
145719  while( p && (p->selFlags & SF_Recursive)!=0 ){ p = p->pPrior; }
145720  return p!=0;
145721}
145722
145723/*
145724** This routine is called to process a compound query form from
145725** two or more separate queries using UNION, UNION ALL, EXCEPT, or
145726** INTERSECT
145727**
145728** "p" points to the right-most of the two queries.  the query on the
145729** left is p->pPrior.  The left query could also be a compound query
145730** in which case this routine will be called recursively.
145731**
145732** The results of the total query are to be written into a destination
145733** of type eDest with parameter iParm.
145734**
145735** Example 1:  Consider a three-way compound SQL statement.
145736**
145737**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
145738**
145739** This statement is parsed up as follows:
145740**
145741**     SELECT c FROM t3
145742**      |
145743**      `----->  SELECT b FROM t2
145744**                |
145745**                `------>  SELECT a FROM t1
145746**
145747** The arrows in the diagram above represent the Select.pPrior pointer.
145748** So if this routine is called with p equal to the t3 query, then
145749** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
145750**
145751** Notice that because of the way SQLite parses compound SELECTs, the
145752** individual selects always group from left to right.
145753*/
145754static int multiSelect(
145755  Parse *pParse,        /* Parsing context */
145756  Select *p,            /* The right-most of SELECTs to be coded */
145757  SelectDest *pDest     /* What to do with query results */
145758){
145759  int rc = SQLITE_OK;   /* Success code from a subroutine */
145760  Select *pPrior;       /* Another SELECT immediately to our left */
145761  Vdbe *v;              /* Generate code to this VDBE */
145762  SelectDest dest;      /* Alternative data destination */
145763  Select *pDelete = 0;  /* Chain of simple selects to delete */
145764  sqlite3 *db;          /* Database connection */
145765
145766  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
145767  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
145768  */
145769  assert( p && p->pPrior );  /* Calling function guarantees this much */
145770  assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
145771  assert( p->selFlags & SF_Compound );
145772  db = pParse->db;
145773  pPrior = p->pPrior;
145774  dest = *pDest;
145775  assert( pPrior->pOrderBy==0 );
145776  assert( pPrior->pLimit==0 );
145777
145778  v = sqlite3GetVdbe(pParse);
145779  assert( v!=0 );  /* The VDBE already created by calling function */
145780
145781  /* Create the destination temporary table if necessary
145782  */
145783  if( dest.eDest==SRT_EphemTab ){
145784    assert( p->pEList );
145785    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
145786    dest.eDest = SRT_Table;
145787  }
145788
145789  /* Special handling for a compound-select that originates as a VALUES clause.
145790  */
145791  if( p->selFlags & SF_MultiValue ){
145792    rc = multiSelectValues(pParse, p, &dest);
145793    if( rc>=0 ) goto multi_select_end;
145794    rc = SQLITE_OK;
145795  }
145796
145797  /* Make sure all SELECTs in the statement have the same number of elements
145798  ** in their result sets.
145799  */
145800  assert( p->pEList && pPrior->pEList );
145801  assert( p->pEList->nExpr==pPrior->pEList->nExpr );
145802
145803#ifndef SQLITE_OMIT_CTE
145804  if( (p->selFlags & SF_Recursive)!=0 && hasAnchor(p) ){
145805    generateWithRecursiveQuery(pParse, p, &dest);
145806  }else
145807#endif
145808
145809  /* Compound SELECTs that have an ORDER BY clause are handled separately.
145810  */
145811  if( p->pOrderBy ){
145812    return multiSelectOrderBy(pParse, p, pDest);
145813  }else{
145814
145815#ifndef SQLITE_OMIT_EXPLAIN
145816    if( pPrior->pPrior==0 ){
145817      ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
145818      ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
145819    }
145820#endif
145821
145822    /* Generate code for the left and right SELECT statements.
145823    */
145824    switch( p->op ){
145825      case TK_ALL: {
145826        int addr = 0;
145827        int nLimit = 0;  /* Initialize to suppress harmless compiler warning */
145828        assert( !pPrior->pLimit );
145829        pPrior->iLimit = p->iLimit;
145830        pPrior->iOffset = p->iOffset;
145831        pPrior->pLimit = p->pLimit;
145832        TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL left...\n"));
145833        rc = sqlite3Select(pParse, pPrior, &dest);
145834        pPrior->pLimit = 0;
145835        if( rc ){
145836          goto multi_select_end;
145837        }
145838        p->pPrior = 0;
145839        p->iLimit = pPrior->iLimit;
145840        p->iOffset = pPrior->iOffset;
145841        if( p->iLimit ){
145842          addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
145843          VdbeComment((v, "Jump ahead if LIMIT reached"));
145844          if( p->iOffset ){
145845            sqlite3VdbeAddOp3(v, OP_OffsetLimit,
145846                              p->iLimit, p->iOffset+1, p->iOffset);
145847          }
145848        }
145849        ExplainQueryPlan((pParse, 1, "UNION ALL"));
145850        TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL right...\n"));
145851        rc = sqlite3Select(pParse, p, &dest);
145852        testcase( rc!=SQLITE_OK );
145853        pDelete = p->pPrior;
145854        p->pPrior = pPrior;
145855        p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
145856        if( p->pLimit
145857         && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit)
145858         && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
145859        ){
145860          p->nSelectRow = sqlite3LogEst((u64)nLimit);
145861        }
145862        if( addr ){
145863          sqlite3VdbeJumpHere(v, addr);
145864        }
145865        break;
145866      }
145867      case TK_EXCEPT:
145868      case TK_UNION: {
145869        int unionTab;    /* Cursor number of the temp table holding result */
145870        u8 op = 0;       /* One of the SRT_ operations to apply to self */
145871        int priorOp;     /* The SRT_ operation to apply to prior selects */
145872        Expr *pLimit;    /* Saved values of p->nLimit  */
145873        int addr;
145874        SelectDest uniondest;
145875
145876        testcase( p->op==TK_EXCEPT );
145877        testcase( p->op==TK_UNION );
145878        priorOp = SRT_Union;
145879        if( dest.eDest==priorOp ){
145880          /* We can reuse a temporary table generated by a SELECT to our
145881          ** right.
145882          */
145883          assert( p->pLimit==0 );      /* Not allowed on leftward elements */
145884          unionTab = dest.iSDParm;
145885        }else{
145886          /* We will need to create our own temporary table to hold the
145887          ** intermediate results.
145888          */
145889          unionTab = pParse->nTab++;
145890          assert( p->pOrderBy==0 );
145891          addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
145892          assert( p->addrOpenEphm[0] == -1 );
145893          p->addrOpenEphm[0] = addr;
145894          findRightmost(p)->selFlags |= SF_UsesEphemeral;
145895          assert( p->pEList );
145896        }
145897
145898
145899        /* Code the SELECT statements to our left
145900        */
145901        assert( !pPrior->pOrderBy );
145902        sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
145903        TREETRACE(0x200, pParse, p, ("multiSelect EXCEPT/UNION left...\n"));
145904        rc = sqlite3Select(pParse, pPrior, &uniondest);
145905        if( rc ){
145906          goto multi_select_end;
145907        }
145908
145909        /* Code the current SELECT statement
145910        */
145911        if( p->op==TK_EXCEPT ){
145912          op = SRT_Except;
145913        }else{
145914          assert( p->op==TK_UNION );
145915          op = SRT_Union;
145916        }
145917        p->pPrior = 0;
145918        pLimit = p->pLimit;
145919        p->pLimit = 0;
145920        uniondest.eDest = op;
145921        ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
145922                          sqlite3SelectOpName(p->op)));
145923        TREETRACE(0x200, pParse, p, ("multiSelect EXCEPT/UNION right...\n"));
145924        rc = sqlite3Select(pParse, p, &uniondest);
145925        testcase( rc!=SQLITE_OK );
145926        assert( p->pOrderBy==0 );
145927        pDelete = p->pPrior;
145928        p->pPrior = pPrior;
145929        p->pOrderBy = 0;
145930        if( p->op==TK_UNION ){
145931          p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
145932        }
145933        sqlite3ExprDelete(db, p->pLimit);
145934        p->pLimit = pLimit;
145935        p->iLimit = 0;
145936        p->iOffset = 0;
145937
145938        /* Convert the data in the temporary table into whatever form
145939        ** it is that we currently need.
145940        */
145941        assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
145942        assert( p->pEList || db->mallocFailed );
145943        if( dest.eDest!=priorOp && db->mallocFailed==0 ){
145944          int iCont, iBreak, iStart;
145945          iBreak = sqlite3VdbeMakeLabel(pParse);
145946          iCont = sqlite3VdbeMakeLabel(pParse);
145947          computeLimitRegisters(pParse, p, iBreak);
145948          sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
145949          iStart = sqlite3VdbeCurrentAddr(v);
145950          selectInnerLoop(pParse, p, unionTab,
145951                          0, 0, &dest, iCont, iBreak);
145952          sqlite3VdbeResolveLabel(v, iCont);
145953          sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
145954          sqlite3VdbeResolveLabel(v, iBreak);
145955          sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
145956        }
145957        break;
145958      }
145959      default: assert( p->op==TK_INTERSECT ); {
145960        int tab1, tab2;
145961        int iCont, iBreak, iStart;
145962        Expr *pLimit;
145963        int addr;
145964        SelectDest intersectdest;
145965        int r1;
145966
145967        /* INTERSECT is different from the others since it requires
145968        ** two temporary tables.  Hence it has its own case.  Begin
145969        ** by allocating the tables we will need.
145970        */
145971        tab1 = pParse->nTab++;
145972        tab2 = pParse->nTab++;
145973        assert( p->pOrderBy==0 );
145974
145975        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
145976        assert( p->addrOpenEphm[0] == -1 );
145977        p->addrOpenEphm[0] = addr;
145978        findRightmost(p)->selFlags |= SF_UsesEphemeral;
145979        assert( p->pEList );
145980
145981        /* Code the SELECTs to our left into temporary table "tab1".
145982        */
145983        sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
145984        TREETRACE(0x400, pParse, p, ("multiSelect INTERSECT left...\n"));
145985        rc = sqlite3Select(pParse, pPrior, &intersectdest);
145986        if( rc ){
145987          goto multi_select_end;
145988        }
145989
145990        /* Code the current SELECT into temporary table "tab2"
145991        */
145992        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
145993        assert( p->addrOpenEphm[1] == -1 );
145994        p->addrOpenEphm[1] = addr;
145995        p->pPrior = 0;
145996        pLimit = p->pLimit;
145997        p->pLimit = 0;
145998        intersectdest.iSDParm = tab2;
145999        ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
146000                          sqlite3SelectOpName(p->op)));
146001        TREETRACE(0x400, pParse, p, ("multiSelect INTERSECT right...\n"));
146002        rc = sqlite3Select(pParse, p, &intersectdest);
146003        testcase( rc!=SQLITE_OK );
146004        pDelete = p->pPrior;
146005        p->pPrior = pPrior;
146006        if( p->nSelectRow>pPrior->nSelectRow ){
146007          p->nSelectRow = pPrior->nSelectRow;
146008        }
146009        sqlite3ExprDelete(db, p->pLimit);
146010        p->pLimit = pLimit;
146011
146012        /* Generate code to take the intersection of the two temporary
146013        ** tables.
146014        */
146015        if( rc ) break;
146016        assert( p->pEList );
146017        iBreak = sqlite3VdbeMakeLabel(pParse);
146018        iCont = sqlite3VdbeMakeLabel(pParse);
146019        computeLimitRegisters(pParse, p, iBreak);
146020        sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
146021        r1 = sqlite3GetTempReg(pParse);
146022        iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
146023        sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
146024        VdbeCoverage(v);
146025        sqlite3ReleaseTempReg(pParse, r1);
146026        selectInnerLoop(pParse, p, tab1,
146027                        0, 0, &dest, iCont, iBreak);
146028        sqlite3VdbeResolveLabel(v, iCont);
146029        sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
146030        sqlite3VdbeResolveLabel(v, iBreak);
146031        sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
146032        sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
146033        break;
146034      }
146035    }
146036
146037  #ifndef SQLITE_OMIT_EXPLAIN
146038    if( p->pNext==0 ){
146039      ExplainQueryPlanPop(pParse);
146040    }
146041  #endif
146042  }
146043  if( pParse->nErr ) goto multi_select_end;
146044
146045  /* Compute collating sequences used by
146046  ** temporary tables needed to implement the compound select.
146047  ** Attach the KeyInfo structure to all temporary tables.
146048  **
146049  ** This section is run by the right-most SELECT statement only.
146050  ** SELECT statements to the left always skip this part.  The right-most
146051  ** SELECT might also skip this part if it has no ORDER BY clause and
146052  ** no temp tables are required.
146053  */
146054  if( p->selFlags & SF_UsesEphemeral ){
146055    int i;                        /* Loop counter */
146056    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
146057    Select *pLoop;                /* For looping through SELECT statements */
146058    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
146059    int nCol;                     /* Number of columns in result set */
146060
146061    assert( p->pNext==0 );
146062    assert( p->pEList!=0 );
146063    nCol = p->pEList->nExpr;
146064    pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
146065    if( !pKeyInfo ){
146066      rc = SQLITE_NOMEM_BKPT;
146067      goto multi_select_end;
146068    }
146069    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
146070      *apColl = multiSelectCollSeq(pParse, p, i);
146071      if( 0==*apColl ){
146072        *apColl = db->pDfltColl;
146073      }
146074    }
146075
146076    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
146077      for(i=0; i<2; i++){
146078        int addr = pLoop->addrOpenEphm[i];
146079        if( addr<0 ){
146080          /* If [0] is unused then [1] is also unused.  So we can
146081          ** always safely abort as soon as the first unused slot is found */
146082          assert( pLoop->addrOpenEphm[1]<0 );
146083          break;
146084        }
146085        sqlite3VdbeChangeP2(v, addr, nCol);
146086        sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
146087                            P4_KEYINFO);
146088        pLoop->addrOpenEphm[i] = -1;
146089      }
146090    }
146091    sqlite3KeyInfoUnref(pKeyInfo);
146092  }
146093
146094multi_select_end:
146095  pDest->iSdst = dest.iSdst;
146096  pDest->nSdst = dest.nSdst;
146097  if( pDelete ){
146098    sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pDelete);
146099  }
146100  return rc;
146101}
146102#endif /* SQLITE_OMIT_COMPOUND_SELECT */
146103
146104/*
146105** Error message for when two or more terms of a compound select have different
146106** size result sets.
146107*/
146108SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
146109  if( p->selFlags & SF_Values ){
146110    sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
146111  }else{
146112    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
146113      " do not have the same number of result columns",
146114      sqlite3SelectOpName(p->op));
146115  }
146116}
146117
146118/*
146119** Code an output subroutine for a coroutine implementation of a
146120** SELECT statement.
146121**
146122** The data to be output is contained in pIn->iSdst.  There are
146123** pIn->nSdst columns to be output.  pDest is where the output should
146124** be sent.
146125**
146126** regReturn is the number of the register holding the subroutine
146127** return address.
146128**
146129** If regPrev>0 then it is the first register in a vector that
146130** records the previous output.  mem[regPrev] is a flag that is false
146131** if there has been no previous output.  If regPrev>0 then code is
146132** generated to suppress duplicates.  pKeyInfo is used for comparing
146133** keys.
146134**
146135** If the LIMIT found in p->iLimit is reached, jump immediately to
146136** iBreak.
146137*/
146138static int generateOutputSubroutine(
146139  Parse *pParse,          /* Parsing context */
146140  Select *p,              /* The SELECT statement */
146141  SelectDest *pIn,        /* Coroutine supplying data */
146142  SelectDest *pDest,      /* Where to send the data */
146143  int regReturn,          /* The return address register */
146144  int regPrev,            /* Previous result register.  No uniqueness if 0 */
146145  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
146146  int iBreak              /* Jump here if we hit the LIMIT */
146147){
146148  Vdbe *v = pParse->pVdbe;
146149  int iContinue;
146150  int addr;
146151
146152  addr = sqlite3VdbeCurrentAddr(v);
146153  iContinue = sqlite3VdbeMakeLabel(pParse);
146154
146155  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
146156  */
146157  if( regPrev ){
146158    int addr1, addr2;
146159    addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
146160    addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
146161                              (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
146162    sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
146163    sqlite3VdbeJumpHere(v, addr1);
146164    sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
146165    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
146166  }
146167  if( pParse->db->mallocFailed ) return 0;
146168
146169  /* Suppress the first OFFSET entries if there is an OFFSET clause
146170  */
146171  codeOffset(v, p->iOffset, iContinue);
146172
146173  assert( pDest->eDest!=SRT_Exists );
146174  assert( pDest->eDest!=SRT_Table );
146175  switch( pDest->eDest ){
146176    /* Store the result as data using a unique key.
146177    */
146178    case SRT_EphemTab: {
146179      int r1 = sqlite3GetTempReg(pParse);
146180      int r2 = sqlite3GetTempReg(pParse);
146181      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
146182      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
146183      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
146184      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
146185      sqlite3ReleaseTempReg(pParse, r2);
146186      sqlite3ReleaseTempReg(pParse, r1);
146187      break;
146188    }
146189
146190#ifndef SQLITE_OMIT_SUBQUERY
146191    /* If we are creating a set for an "expr IN (SELECT ...)".
146192    */
146193    case SRT_Set: {
146194      int r1;
146195      testcase( pIn->nSdst>1 );
146196      r1 = sqlite3GetTempReg(pParse);
146197      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
146198          r1, pDest->zAffSdst, pIn->nSdst);
146199      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
146200                           pIn->iSdst, pIn->nSdst);
146201      sqlite3ReleaseTempReg(pParse, r1);
146202      break;
146203    }
146204
146205    /* If this is a scalar select that is part of an expression, then
146206    ** store the results in the appropriate memory cell and break out
146207    ** of the scan loop.  Note that the select might return multiple columns
146208    ** if it is the RHS of a row-value IN operator.
146209    */
146210    case SRT_Mem: {
146211      testcase( pIn->nSdst>1 );
146212      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
146213      /* The LIMIT clause will jump out of the loop for us */
146214      break;
146215    }
146216#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
146217
146218    /* The results are stored in a sequence of registers
146219    ** starting at pDest->iSdst.  Then the co-routine yields.
146220    */
146221    case SRT_Coroutine: {
146222      if( pDest->iSdst==0 ){
146223        pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
146224        pDest->nSdst = pIn->nSdst;
146225      }
146226      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
146227      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
146228      break;
146229    }
146230
146231    /* If none of the above, then the result destination must be
146232    ** SRT_Output.  This routine is never called with any other
146233    ** destination other than the ones handled above or SRT_Output.
146234    **
146235    ** For SRT_Output, results are stored in a sequence of registers.
146236    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
146237    ** return the next row of result.
146238    */
146239    default: {
146240      assert( pDest->eDest==SRT_Output );
146241      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
146242      break;
146243    }
146244  }
146245
146246  /* Jump to the end of the loop if the LIMIT is reached.
146247  */
146248  if( p->iLimit ){
146249    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
146250  }
146251
146252  /* Generate the subroutine return
146253  */
146254  sqlite3VdbeResolveLabel(v, iContinue);
146255  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
146256
146257  return addr;
146258}
146259
146260/*
146261** Alternative compound select code generator for cases when there
146262** is an ORDER BY clause.
146263**
146264** We assume a query of the following form:
146265**
146266**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
146267**
146268** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
146269** is to code both <selectA> and <selectB> with the ORDER BY clause as
146270** co-routines.  Then run the co-routines in parallel and merge the results
146271** into the output.  In addition to the two coroutines (called selectA and
146272** selectB) there are 7 subroutines:
146273**
146274**    outA:    Move the output of the selectA coroutine into the output
146275**             of the compound query.
146276**
146277**    outB:    Move the output of the selectB coroutine into the output
146278**             of the compound query.  (Only generated for UNION and
146279**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
146280**             appears only in B.)
146281**
146282**    AltB:    Called when there is data from both coroutines and A<B.
146283**
146284**    AeqB:    Called when there is data from both coroutines and A==B.
146285**
146286**    AgtB:    Called when there is data from both coroutines and A>B.
146287**
146288**    EofA:    Called when data is exhausted from selectA.
146289**
146290**    EofB:    Called when data is exhausted from selectB.
146291**
146292** The implementation of the latter five subroutines depend on which
146293** <operator> is used:
146294**
146295**
146296**             UNION ALL         UNION            EXCEPT          INTERSECT
146297**          -------------  -----------------  --------------  -----------------
146298**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
146299**
146300**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
146301**
146302**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
146303**
146304**   EofA:   outB, nextB      outB, nextB          halt             halt
146305**
146306**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
146307**
146308** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
146309** causes an immediate jump to EofA and an EOF on B following nextB causes
146310** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
146311** following nextX causes a jump to the end of the select processing.
146312**
146313** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
146314** within the output subroutine.  The regPrev register set holds the previously
146315** output value.  A comparison is made against this value and the output
146316** is skipped if the next results would be the same as the previous.
146317**
146318** The implementation plan is to implement the two coroutines and seven
146319** subroutines first, then put the control logic at the bottom.  Like this:
146320**
146321**          goto Init
146322**     coA: coroutine for left query (A)
146323**     coB: coroutine for right query (B)
146324**    outA: output one row of A
146325**    outB: output one row of B (UNION and UNION ALL only)
146326**    EofA: ...
146327**    EofB: ...
146328**    AltB: ...
146329**    AeqB: ...
146330**    AgtB: ...
146331**    Init: initialize coroutine registers
146332**          yield coA
146333**          if eof(A) goto EofA
146334**          yield coB
146335**          if eof(B) goto EofB
146336**    Cmpr: Compare A, B
146337**          Jump AltB, AeqB, AgtB
146338**     End: ...
146339**
146340** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
146341** actually called using Gosub and they do not Return.  EofA and EofB loop
146342** until all data is exhausted then jump to the "end" label.  AltB, AeqB,
146343** and AgtB jump to either L2 or to one of EofA or EofB.
146344*/
146345#ifndef SQLITE_OMIT_COMPOUND_SELECT
146346static int multiSelectOrderBy(
146347  Parse *pParse,        /* Parsing context */
146348  Select *p,            /* The right-most of SELECTs to be coded */
146349  SelectDest *pDest     /* What to do with query results */
146350){
146351  int i, j;             /* Loop counters */
146352  Select *pPrior;       /* Another SELECT immediately to our left */
146353  Select *pSplit;       /* Left-most SELECT in the right-hand group */
146354  int nSelect;          /* Number of SELECT statements in the compound */
146355  Vdbe *v;              /* Generate code to this VDBE */
146356  SelectDest destA;     /* Destination for coroutine A */
146357  SelectDest destB;     /* Destination for coroutine B */
146358  int regAddrA;         /* Address register for select-A coroutine */
146359  int regAddrB;         /* Address register for select-B coroutine */
146360  int addrSelectA;      /* Address of the select-A coroutine */
146361  int addrSelectB;      /* Address of the select-B coroutine */
146362  int regOutA;          /* Address register for the output-A subroutine */
146363  int regOutB;          /* Address register for the output-B subroutine */
146364  int addrOutA;         /* Address of the output-A subroutine */
146365  int addrOutB = 0;     /* Address of the output-B subroutine */
146366  int addrEofA;         /* Address of the select-A-exhausted subroutine */
146367  int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
146368  int addrEofB;         /* Address of the select-B-exhausted subroutine */
146369  int addrAltB;         /* Address of the A<B subroutine */
146370  int addrAeqB;         /* Address of the A==B subroutine */
146371  int addrAgtB;         /* Address of the A>B subroutine */
146372  int regLimitA;        /* Limit register for select-A */
146373  int regLimitB;        /* Limit register for select-A */
146374  int regPrev;          /* A range of registers to hold previous output */
146375  int savedLimit;       /* Saved value of p->iLimit */
146376  int savedOffset;      /* Saved value of p->iOffset */
146377  int labelCmpr;        /* Label for the start of the merge algorithm */
146378  int labelEnd;         /* Label for the end of the overall SELECT stmt */
146379  int addr1;            /* Jump instructions that get retargeted */
146380  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
146381  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
146382  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
146383  sqlite3 *db;          /* Database connection */
146384  ExprList *pOrderBy;   /* The ORDER BY clause */
146385  int nOrderBy;         /* Number of terms in the ORDER BY clause */
146386  u32 *aPermute;        /* Mapping from ORDER BY terms to result set columns */
146387
146388  assert( p->pOrderBy!=0 );
146389  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
146390  db = pParse->db;
146391  v = pParse->pVdbe;
146392  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
146393  labelEnd = sqlite3VdbeMakeLabel(pParse);
146394  labelCmpr = sqlite3VdbeMakeLabel(pParse);
146395
146396
146397  /* Patch up the ORDER BY clause
146398  */
146399  op = p->op;
146400  assert( p->pPrior->pOrderBy==0 );
146401  pOrderBy = p->pOrderBy;
146402  assert( pOrderBy );
146403  nOrderBy = pOrderBy->nExpr;
146404
146405  /* For operators other than UNION ALL we have to make sure that
146406  ** the ORDER BY clause covers every term of the result set.  Add
146407  ** terms to the ORDER BY clause as necessary.
146408  */
146409  if( op!=TK_ALL ){
146410    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
146411      struct ExprList_item *pItem;
146412      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
146413        assert( pItem!=0 );
146414        assert( pItem->u.x.iOrderByCol>0 );
146415        if( pItem->u.x.iOrderByCol==i ) break;
146416      }
146417      if( j==nOrderBy ){
146418        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
146419        if( pNew==0 ) return SQLITE_NOMEM_BKPT;
146420        pNew->flags |= EP_IntValue;
146421        pNew->u.iValue = i;
146422        p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
146423        if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
146424      }
146425    }
146426  }
146427
146428  /* Compute the comparison permutation and keyinfo that is used with
146429  ** the permutation used to determine if the next
146430  ** row of results comes from selectA or selectB.  Also add explicit
146431  ** collations to the ORDER BY clause terms so that when the subqueries
146432  ** to the right and the left are evaluated, they use the correct
146433  ** collation.
146434  */
146435  aPermute = sqlite3DbMallocRawNN(db, sizeof(u32)*(nOrderBy + 1));
146436  if( aPermute ){
146437    struct ExprList_item *pItem;
146438    aPermute[0] = nOrderBy;
146439    for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
146440      assert( pItem!=0 );
146441      assert( pItem->u.x.iOrderByCol>0 );
146442      assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
146443      aPermute[i] = pItem->u.x.iOrderByCol - 1;
146444    }
146445    pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
146446  }else{
146447    pKeyMerge = 0;
146448  }
146449
146450  /* Allocate a range of temporary registers and the KeyInfo needed
146451  ** for the logic that removes duplicate result rows when the
146452  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
146453  */
146454  if( op==TK_ALL ){
146455    regPrev = 0;
146456  }else{
146457    int nExpr = p->pEList->nExpr;
146458    assert( nOrderBy>=nExpr || db->mallocFailed );
146459    regPrev = pParse->nMem+1;
146460    pParse->nMem += nExpr+1;
146461    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
146462    pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
146463    if( pKeyDup ){
146464      assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
146465      for(i=0; i<nExpr; i++){
146466        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
146467        pKeyDup->aSortFlags[i] = 0;
146468      }
146469    }
146470  }
146471
146472  /* Separate the left and the right query from one another
146473  */
146474  nSelect = 1;
146475  if( (op==TK_ALL || op==TK_UNION)
146476   && OptimizationEnabled(db, SQLITE_BalancedMerge)
146477  ){
146478    for(pSplit=p; pSplit->pPrior!=0 && pSplit->op==op; pSplit=pSplit->pPrior){
146479      nSelect++;
146480      assert( pSplit->pPrior->pNext==pSplit );
146481    }
146482  }
146483  if( nSelect<=3 ){
146484    pSplit = p;
146485  }else{
146486    pSplit = p;
146487    for(i=2; i<nSelect; i+=2){ pSplit = pSplit->pPrior; }
146488  }
146489  pPrior = pSplit->pPrior;
146490  assert( pPrior!=0 );
146491  pSplit->pPrior = 0;
146492  pPrior->pNext = 0;
146493  assert( p->pOrderBy == pOrderBy );
146494  assert( pOrderBy!=0 || db->mallocFailed );
146495  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
146496  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
146497  sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
146498
146499  /* Compute the limit registers */
146500  computeLimitRegisters(pParse, p, labelEnd);
146501  if( p->iLimit && op==TK_ALL ){
146502    regLimitA = ++pParse->nMem;
146503    regLimitB = ++pParse->nMem;
146504    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
146505                                  regLimitA);
146506    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
146507  }else{
146508    regLimitA = regLimitB = 0;
146509  }
146510  sqlite3ExprDelete(db, p->pLimit);
146511  p->pLimit = 0;
146512
146513  regAddrA = ++pParse->nMem;
146514  regAddrB = ++pParse->nMem;
146515  regOutA = ++pParse->nMem;
146516  regOutB = ++pParse->nMem;
146517  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
146518  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
146519
146520  ExplainQueryPlan((pParse, 1, "MERGE (%s)", sqlite3SelectOpName(p->op)));
146521
146522  /* Generate a coroutine to evaluate the SELECT statement to the
146523  ** left of the compound operator - the "A" select.
146524  */
146525  addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
146526  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
146527  VdbeComment((v, "left SELECT"));
146528  pPrior->iLimit = regLimitA;
146529  ExplainQueryPlan((pParse, 1, "LEFT"));
146530  sqlite3Select(pParse, pPrior, &destA);
146531  sqlite3VdbeEndCoroutine(v, regAddrA);
146532  sqlite3VdbeJumpHere(v, addr1);
146533
146534  /* Generate a coroutine to evaluate the SELECT statement on
146535  ** the right - the "B" select
146536  */
146537  addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
146538  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
146539  VdbeComment((v, "right SELECT"));
146540  savedLimit = p->iLimit;
146541  savedOffset = p->iOffset;
146542  p->iLimit = regLimitB;
146543  p->iOffset = 0;
146544  ExplainQueryPlan((pParse, 1, "RIGHT"));
146545  sqlite3Select(pParse, p, &destB);
146546  p->iLimit = savedLimit;
146547  p->iOffset = savedOffset;
146548  sqlite3VdbeEndCoroutine(v, regAddrB);
146549
146550  /* Generate a subroutine that outputs the current row of the A
146551  ** select as the next output row of the compound select.
146552  */
146553  VdbeNoopComment((v, "Output routine for A"));
146554  addrOutA = generateOutputSubroutine(pParse,
146555                 p, &destA, pDest, regOutA,
146556                 regPrev, pKeyDup, labelEnd);
146557
146558  /* Generate a subroutine that outputs the current row of the B
146559  ** select as the next output row of the compound select.
146560  */
146561  if( op==TK_ALL || op==TK_UNION ){
146562    VdbeNoopComment((v, "Output routine for B"));
146563    addrOutB = generateOutputSubroutine(pParse,
146564                 p, &destB, pDest, regOutB,
146565                 regPrev, pKeyDup, labelEnd);
146566  }
146567  sqlite3KeyInfoUnref(pKeyDup);
146568
146569  /* Generate a subroutine to run when the results from select A
146570  ** are exhausted and only data in select B remains.
146571  */
146572  if( op==TK_EXCEPT || op==TK_INTERSECT ){
146573    addrEofA_noB = addrEofA = labelEnd;
146574  }else{
146575    VdbeNoopComment((v, "eof-A subroutine"));
146576    addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
146577    addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
146578                                     VdbeCoverage(v);
146579    sqlite3VdbeGoto(v, addrEofA);
146580    p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
146581  }
146582
146583  /* Generate a subroutine to run when the results from select B
146584  ** are exhausted and only data in select A remains.
146585  */
146586  if( op==TK_INTERSECT ){
146587    addrEofB = addrEofA;
146588    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
146589  }else{
146590    VdbeNoopComment((v, "eof-B subroutine"));
146591    addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
146592    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
146593    sqlite3VdbeGoto(v, addrEofB);
146594  }
146595
146596  /* Generate code to handle the case of A<B
146597  */
146598  VdbeNoopComment((v, "A-lt-B subroutine"));
146599  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
146600  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
146601  sqlite3VdbeGoto(v, labelCmpr);
146602
146603  /* Generate code to handle the case of A==B
146604  */
146605  if( op==TK_ALL ){
146606    addrAeqB = addrAltB;
146607  }else if( op==TK_INTERSECT ){
146608    addrAeqB = addrAltB;
146609    addrAltB++;
146610  }else{
146611    VdbeNoopComment((v, "A-eq-B subroutine"));
146612    addrAeqB =
146613    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
146614    sqlite3VdbeGoto(v, labelCmpr);
146615  }
146616
146617  /* Generate code to handle the case of A>B
146618  */
146619  VdbeNoopComment((v, "A-gt-B subroutine"));
146620  addrAgtB = sqlite3VdbeCurrentAddr(v);
146621  if( op==TK_ALL || op==TK_UNION ){
146622    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
146623  }
146624  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
146625  sqlite3VdbeGoto(v, labelCmpr);
146626
146627  /* This code runs once to initialize everything.
146628  */
146629  sqlite3VdbeJumpHere(v, addr1);
146630  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
146631  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
146632
146633  /* Implement the main merge loop
146634  */
146635  sqlite3VdbeResolveLabel(v, labelCmpr);
146636  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
146637  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
146638                         (char*)pKeyMerge, P4_KEYINFO);
146639  sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
146640  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
146641
146642  /* Jump to the this point in order to terminate the query.
146643  */
146644  sqlite3VdbeResolveLabel(v, labelEnd);
146645
146646  /* Make arrangements to free the 2nd and subsequent arms of the compound
146647  ** after the parse has finished */
146648  if( pSplit->pPrior ){
146649    sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pSplit->pPrior);
146650  }
146651  pSplit->pPrior = pPrior;
146652  pPrior->pNext = pSplit;
146653  sqlite3ExprListDelete(db, pPrior->pOrderBy);
146654  pPrior->pOrderBy = 0;
146655
146656  /*** TBD:  Insert subroutine calls to close cursors on incomplete
146657  **** subqueries ****/
146658  ExplainQueryPlanPop(pParse);
146659  return pParse->nErr!=0;
146660}
146661#endif
146662
146663#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
146664
146665/* An instance of the SubstContext object describes an substitution edit
146666** to be performed on a parse tree.
146667**
146668** All references to columns in table iTable are to be replaced by corresponding
146669** expressions in pEList.
146670**
146671** ## About "isOuterJoin":
146672**
146673** The isOuterJoin column indicates that the replacement will occur into a
146674** position in the parent that NULL-able due to an OUTER JOIN.  Either the
146675** target slot in the parent is the right operand of a LEFT JOIN, or one of
146676** the left operands of a RIGHT JOIN.  In either case, we need to potentially
146677** bypass the substituted expression with OP_IfNullRow.
146678**
146679** Suppose the original expression is an integer constant. Even though the table
146680** has the nullRow flag set, because the expression is an integer constant,
146681** it will not be NULLed out.  So instead, we insert an OP_IfNullRow opcode
146682** that checks to see if the nullRow flag is set on the table.  If the nullRow
146683** flag is set, then the value in the register is set to NULL and the original
146684** expression is bypassed.  If the nullRow flag is not set, then the original
146685** expression runs to populate the register.
146686**
146687** Example where this is needed:
146688**
146689**      CREATE TABLE t1(a INTEGER PRIMARY KEY, b INT);
146690**      CREATE TABLE t2(x INT UNIQUE);
146691**
146692**      SELECT a,b,m,x FROM t1 LEFT JOIN (SELECT 59 AS m,x FROM t2) ON b=x;
146693**
146694** When the subquery on the right side of the LEFT JOIN is flattened, we
146695** have to add OP_IfNullRow in front of the OP_Integer that implements the
146696** "m" value of the subquery so that a NULL will be loaded instead of 59
146697** when processing a non-matched row of the left.
146698*/
146699typedef struct SubstContext {
146700  Parse *pParse;            /* The parsing context */
146701  int iTable;               /* Replace references to this table */
146702  int iNewTable;            /* New table number */
146703  int isOuterJoin;          /* Add TK_IF_NULL_ROW opcodes on each replacement */
146704  ExprList *pEList;         /* Replacement expressions */
146705  ExprList *pCList;         /* Collation sequences for replacement expr */
146706} SubstContext;
146707
146708/* Forward Declarations */
146709static void substExprList(SubstContext*, ExprList*);
146710static void substSelect(SubstContext*, Select*, int);
146711
146712/*
146713** Scan through the expression pExpr.  Replace every reference to
146714** a column in table number iTable with a copy of the iColumn-th
146715** entry in pEList.  (But leave references to the ROWID column
146716** unchanged.)
146717**
146718** This routine is part of the flattening procedure.  A subquery
146719** whose result set is defined by pEList appears as entry in the
146720** FROM clause of a SELECT such that the VDBE cursor assigned to that
146721** FORM clause entry is iTable.  This routine makes the necessary
146722** changes to pExpr so that it refers directly to the source table
146723** of the subquery rather the result set of the subquery.
146724*/
146725static Expr *substExpr(
146726  SubstContext *pSubst,  /* Description of the substitution */
146727  Expr *pExpr            /* Expr in which substitution occurs */
146728){
146729  if( pExpr==0 ) return 0;
146730  if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON)
146731   && pExpr->w.iJoin==pSubst->iTable
146732  ){
146733    testcase( ExprHasProperty(pExpr, EP_InnerON) );
146734    pExpr->w.iJoin = pSubst->iNewTable;
146735  }
146736  if( pExpr->op==TK_COLUMN
146737   && pExpr->iTable==pSubst->iTable
146738   && !ExprHasProperty(pExpr, EP_FixedCol)
146739  ){
146740#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
146741    if( pExpr->iColumn<0 ){
146742      pExpr->op = TK_NULL;
146743    }else
146744#endif
146745    {
146746      Expr *pNew;
146747      int iColumn;
146748      Expr *pCopy;
146749      Expr ifNullRow;
146750      iColumn = pExpr->iColumn;
146751      assert( iColumn>=0 );
146752      assert( pSubst->pEList!=0 && iColumn<pSubst->pEList->nExpr );
146753      assert( pExpr->pRight==0 );
146754      pCopy = pSubst->pEList->a[iColumn].pExpr;
146755      if( sqlite3ExprIsVector(pCopy) ){
146756        sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
146757      }else{
146758        sqlite3 *db = pSubst->pParse->db;
146759        if( pSubst->isOuterJoin
146760         && (pCopy->op!=TK_COLUMN || pCopy->iTable!=pSubst->iNewTable)
146761        ){
146762          memset(&ifNullRow, 0, sizeof(ifNullRow));
146763          ifNullRow.op = TK_IF_NULL_ROW;
146764          ifNullRow.pLeft = pCopy;
146765          ifNullRow.iTable = pSubst->iNewTable;
146766          ifNullRow.iColumn = -99;
146767          ifNullRow.flags = EP_IfNullRow;
146768          pCopy = &ifNullRow;
146769        }
146770        testcase( ExprHasProperty(pCopy, EP_Subquery) );
146771        pNew = sqlite3ExprDup(db, pCopy, 0);
146772        if( db->mallocFailed ){
146773          sqlite3ExprDelete(db, pNew);
146774          return pExpr;
146775        }
146776        if( pSubst->isOuterJoin ){
146777          ExprSetProperty(pNew, EP_CanBeNull);
146778        }
146779        if( ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) ){
146780          sqlite3SetJoinExpr(pNew, pExpr->w.iJoin,
146781                             pExpr->flags & (EP_OuterON|EP_InnerON));
146782        }
146783        sqlite3ExprDelete(db, pExpr);
146784        pExpr = pNew;
146785        if( pExpr->op==TK_TRUEFALSE ){
146786          pExpr->u.iValue = sqlite3ExprTruthValue(pExpr);
146787          pExpr->op = TK_INTEGER;
146788          ExprSetProperty(pExpr, EP_IntValue);
146789        }
146790
146791        /* Ensure that the expression now has an implicit collation sequence,
146792        ** just as it did when it was a column of a view or sub-query. */
146793        {
146794          CollSeq *pNat = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
146795          CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse,
146796                pSubst->pCList->a[iColumn].pExpr
146797          );
146798          if( pNat!=pColl || (pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE) ){
146799            pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
146800                (pColl ? pColl->zName : "BINARY")
146801            );
146802          }
146803        }
146804        ExprClearProperty(pExpr, EP_Collate);
146805      }
146806    }
146807  }else{
146808    if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
146809      pExpr->iTable = pSubst->iNewTable;
146810    }
146811    pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
146812    pExpr->pRight = substExpr(pSubst, pExpr->pRight);
146813    if( ExprUseXSelect(pExpr) ){
146814      substSelect(pSubst, pExpr->x.pSelect, 1);
146815    }else{
146816      substExprList(pSubst, pExpr->x.pList);
146817    }
146818#ifndef SQLITE_OMIT_WINDOWFUNC
146819    if( ExprHasProperty(pExpr, EP_WinFunc) ){
146820      Window *pWin = pExpr->y.pWin;
146821      pWin->pFilter = substExpr(pSubst, pWin->pFilter);
146822      substExprList(pSubst, pWin->pPartition);
146823      substExprList(pSubst, pWin->pOrderBy);
146824    }
146825#endif
146826  }
146827  return pExpr;
146828}
146829static void substExprList(
146830  SubstContext *pSubst, /* Description of the substitution */
146831  ExprList *pList       /* List to scan and in which to make substitutes */
146832){
146833  int i;
146834  if( pList==0 ) return;
146835  for(i=0; i<pList->nExpr; i++){
146836    pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
146837  }
146838}
146839static void substSelect(
146840  SubstContext *pSubst, /* Description of the substitution */
146841  Select *p,            /* SELECT statement in which to make substitutions */
146842  int doPrior           /* Do substitutes on p->pPrior too */
146843){
146844  SrcList *pSrc;
146845  SrcItem *pItem;
146846  int i;
146847  if( !p ) return;
146848  do{
146849    substExprList(pSubst, p->pEList);
146850    substExprList(pSubst, p->pGroupBy);
146851    substExprList(pSubst, p->pOrderBy);
146852    p->pHaving = substExpr(pSubst, p->pHaving);
146853    p->pWhere = substExpr(pSubst, p->pWhere);
146854    pSrc = p->pSrc;
146855    assert( pSrc!=0 );
146856    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
146857      substSelect(pSubst, pItem->pSelect, 1);
146858      if( pItem->fg.isTabFunc ){
146859        substExprList(pSubst, pItem->u1.pFuncArg);
146860      }
146861    }
146862  }while( doPrior && (p = p->pPrior)!=0 );
146863}
146864#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
146865
146866#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
146867/*
146868** pSelect is a SELECT statement and pSrcItem is one item in the FROM
146869** clause of that SELECT.
146870**
146871** This routine scans the entire SELECT statement and recomputes the
146872** pSrcItem->colUsed mask.
146873*/
146874static int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){
146875  SrcItem *pItem;
146876  if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
146877  pItem = pWalker->u.pSrcItem;
146878  if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue;
146879  if( pExpr->iColumn<0 ) return WRC_Continue;
146880  pItem->colUsed |= sqlite3ExprColUsed(pExpr);
146881  return WRC_Continue;
146882}
146883static void recomputeColumnsUsed(
146884  Select *pSelect,                 /* The complete SELECT statement */
146885  SrcItem *pSrcItem                /* Which FROM clause item to recompute */
146886){
146887  Walker w;
146888  if( NEVER(pSrcItem->pTab==0) ) return;
146889  memset(&w, 0, sizeof(w));
146890  w.xExprCallback = recomputeColumnsUsedExpr;
146891  w.xSelectCallback = sqlite3SelectWalkNoop;
146892  w.u.pSrcItem = pSrcItem;
146893  pSrcItem->colUsed = 0;
146894  sqlite3WalkSelect(&w, pSelect);
146895}
146896#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
146897
146898#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
146899/*
146900** Assign new cursor numbers to each of the items in pSrc. For each
146901** new cursor number assigned, set an entry in the aCsrMap[] array
146902** to map the old cursor number to the new:
146903**
146904**     aCsrMap[iOld+1] = iNew;
146905**
146906** The array is guaranteed by the caller to be large enough for all
146907** existing cursor numbers in pSrc.  aCsrMap[0] is the array size.
146908**
146909** If pSrc contains any sub-selects, call this routine recursively
146910** on the FROM clause of each such sub-select, with iExcept set to -1.
146911*/
146912static void srclistRenumberCursors(
146913  Parse *pParse,                  /* Parse context */
146914  int *aCsrMap,                   /* Array to store cursor mappings in */
146915  SrcList *pSrc,                  /* FROM clause to renumber */
146916  int iExcept                     /* FROM clause item to skip */
146917){
146918  int i;
146919  SrcItem *pItem;
146920  for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
146921    if( i!=iExcept ){
146922      Select *p;
146923      assert( pItem->iCursor < aCsrMap[0] );
146924      if( !pItem->fg.isRecursive || aCsrMap[pItem->iCursor+1]==0 ){
146925        aCsrMap[pItem->iCursor+1] = pParse->nTab++;
146926      }
146927      pItem->iCursor = aCsrMap[pItem->iCursor+1];
146928      for(p=pItem->pSelect; p; p=p->pPrior){
146929        srclistRenumberCursors(pParse, aCsrMap, p->pSrc, -1);
146930      }
146931    }
146932  }
146933}
146934
146935/*
146936** *piCursor is a cursor number.  Change it if it needs to be mapped.
146937*/
146938static void renumberCursorDoMapping(Walker *pWalker, int *piCursor){
146939  int *aCsrMap = pWalker->u.aiCol;
146940  int iCsr = *piCursor;
146941  if( iCsr < aCsrMap[0] && aCsrMap[iCsr+1]>0 ){
146942    *piCursor = aCsrMap[iCsr+1];
146943  }
146944}
146945
146946/*
146947** Expression walker callback used by renumberCursors() to update
146948** Expr objects to match newly assigned cursor numbers.
146949*/
146950static int renumberCursorsCb(Walker *pWalker, Expr *pExpr){
146951  int op = pExpr->op;
146952  if( op==TK_COLUMN || op==TK_IF_NULL_ROW ){
146953    renumberCursorDoMapping(pWalker, &pExpr->iTable);
146954  }
146955  if( ExprHasProperty(pExpr, EP_OuterON) ){
146956    renumberCursorDoMapping(pWalker, &pExpr->w.iJoin);
146957  }
146958  return WRC_Continue;
146959}
146960
146961/*
146962** Assign a new cursor number to each cursor in the FROM clause (Select.pSrc)
146963** of the SELECT statement passed as the second argument, and to each
146964** cursor in the FROM clause of any FROM clause sub-selects, recursively.
146965** Except, do not assign a new cursor number to the iExcept'th element in
146966** the FROM clause of (*p). Update all expressions and other references
146967** to refer to the new cursor numbers.
146968**
146969** Argument aCsrMap is an array that may be used for temporary working
146970** space. Two guarantees are made by the caller:
146971**
146972**   * the array is larger than the largest cursor number used within the
146973**     select statement passed as an argument, and
146974**
146975**   * the array entries for all cursor numbers that do *not* appear in
146976**     FROM clauses of the select statement as described above are
146977**     initialized to zero.
146978*/
146979static void renumberCursors(
146980  Parse *pParse,                  /* Parse context */
146981  Select *p,                      /* Select to renumber cursors within */
146982  int iExcept,                    /* FROM clause item to skip */
146983  int *aCsrMap                    /* Working space */
146984){
146985  Walker w;
146986  srclistRenumberCursors(pParse, aCsrMap, p->pSrc, iExcept);
146987  memset(&w, 0, sizeof(w));
146988  w.u.aiCol = aCsrMap;
146989  w.xExprCallback = renumberCursorsCb;
146990  w.xSelectCallback = sqlite3SelectWalkNoop;
146991  sqlite3WalkSelect(&w, p);
146992}
146993#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
146994
146995/*
146996** If pSel is not part of a compound SELECT, return a pointer to its
146997** expression list. Otherwise, return a pointer to the expression list
146998** of the leftmost SELECT in the compound.
146999*/
147000static ExprList *findLeftmostExprlist(Select *pSel){
147001  while( pSel->pPrior ){
147002    pSel = pSel->pPrior;
147003  }
147004  return pSel->pEList;
147005}
147006
147007/*
147008** Return true if any of the result-set columns in the compound query
147009** have incompatible affinities on one or more arms of the compound.
147010*/
147011static int compoundHasDifferentAffinities(Select *p){
147012  int ii;
147013  ExprList *pList;
147014  assert( p!=0 );
147015  assert( p->pEList!=0 );
147016  assert( p->pPrior!=0 );
147017  pList = p->pEList;
147018  for(ii=0; ii<pList->nExpr; ii++){
147019    char aff;
147020    Select *pSub1;
147021    assert( pList->a[ii].pExpr!=0 );
147022    aff = sqlite3ExprAffinity(pList->a[ii].pExpr);
147023    for(pSub1=p->pPrior; pSub1; pSub1=pSub1->pPrior){
147024      assert( pSub1->pEList!=0 );
147025      assert( pSub1->pEList->nExpr>ii );
147026      assert( pSub1->pEList->a[ii].pExpr!=0 );
147027      if( sqlite3ExprAffinity(pSub1->pEList->a[ii].pExpr)!=aff ){
147028        return 1;
147029      }
147030    }
147031  }
147032  return 0;
147033}
147034
147035#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
147036/*
147037** This routine attempts to flatten subqueries as a performance optimization.
147038** This routine returns 1 if it makes changes and 0 if no flattening occurs.
147039**
147040** To understand the concept of flattening, consider the following
147041** query:
147042**
147043**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
147044**
147045** The default way of implementing this query is to execute the
147046** subquery first and store the results in a temporary table, then
147047** run the outer query on that temporary table.  This requires two
147048** passes over the data.  Furthermore, because the temporary table
147049** has no indices, the WHERE clause on the outer query cannot be
147050** optimized.
147051**
147052** This routine attempts to rewrite queries such as the above into
147053** a single flat select, like this:
147054**
147055**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
147056**
147057** The code generated for this simplification gives the same result
147058** but only has to scan the data once.  And because indices might
147059** exist on the table t1, a complete scan of the data might be
147060** avoided.
147061**
147062** Flattening is subject to the following constraints:
147063**
147064**  (**)  We no longer attempt to flatten aggregate subqueries. Was:
147065**        The subquery and the outer query cannot both be aggregates.
147066**
147067**  (**)  We no longer attempt to flatten aggregate subqueries. Was:
147068**        (2) If the subquery is an aggregate then
147069**        (2a) the outer query must not be a join and
147070**        (2b) the outer query must not use subqueries
147071**             other than the one FROM-clause subquery that is a candidate
147072**             for flattening.  (This is due to ticket [2f7170d73bf9abf80]
147073**             from 2015-02-09.)
147074**
147075**   (3)  If the subquery is the right operand of a LEFT JOIN then
147076**        (3a) the subquery may not be a join and
147077**        (3b) the FROM clause of the subquery may not contain a virtual
147078**             table and
147079**        (**) Was: "The outer query may not have a GROUP BY." This case
147080**             is now managed correctly
147081**        (3d) the outer query may not be DISTINCT.
147082**        See also (26) for restrictions on RIGHT JOIN.
147083**
147084**   (4)  The subquery can not be DISTINCT.
147085**
147086**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
147087**        sub-queries that were excluded from this optimization. Restriction
147088**        (4) has since been expanded to exclude all DISTINCT subqueries.
147089**
147090**  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
147091**        If the subquery is aggregate, the outer query may not be DISTINCT.
147092**
147093**   (7)  The subquery must have a FROM clause.  TODO:  For subqueries without
147094**        A FROM clause, consider adding a FROM clause with the special
147095**        table sqlite_once that consists of a single row containing a
147096**        single NULL.
147097**
147098**   (8)  If the subquery uses LIMIT then the outer query may not be a join.
147099**
147100**   (9)  If the subquery uses LIMIT then the outer query may not be aggregate.
147101**
147102**  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
147103**        accidentally carried the comment forward until 2014-09-15.  Original
147104**        constraint: "If the subquery is aggregate then the outer query
147105**        may not use LIMIT."
147106**
147107**  (11)  The subquery and the outer query may not both have ORDER BY clauses.
147108**
147109**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
147110**        a separate restriction deriving from ticket #350.
147111**
147112**  (13)  The subquery and outer query may not both use LIMIT.
147113**
147114**  (14)  The subquery may not use OFFSET.
147115**
147116**  (15)  If the outer query is part of a compound select, then the
147117**        subquery may not use LIMIT.
147118**        (See ticket #2339 and ticket [02a8e81d44]).
147119**
147120**  (16)  If the outer query is aggregate, then the subquery may not
147121**        use ORDER BY.  (Ticket #2942)  This used to not matter
147122**        until we introduced the group_concat() function.
147123**
147124**  (17)  If the subquery is a compound select, then
147125**        (17a) all compound operators must be a UNION ALL, and
147126**        (17b) no terms within the subquery compound may be aggregate
147127**              or DISTINCT, and
147128**        (17c) every term within the subquery compound must have a FROM clause
147129**        (17d) the outer query may not be
147130**              (17d1) aggregate, or
147131**              (17d2) DISTINCT
147132**        (17e) the subquery may not contain window functions, and
147133**        (17f) the subquery must not be the RHS of a LEFT JOIN.
147134**        (17g) either the subquery is the first element of the outer
147135**              query or there are no RIGHT or FULL JOINs in any arm
147136**              of the subquery.  (This is a duplicate of condition (27b).)
147137**        (17h) The corresponding result set expressions in all arms of the
147138**              compound must have the same affinity.
147139**
147140**        The parent and sub-query may contain WHERE clauses. Subject to
147141**        rules (11), (13) and (14), they may also contain ORDER BY,
147142**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
147143**        operator other than UNION ALL because all the other compound
147144**        operators have an implied DISTINCT which is disallowed by
147145**        restriction (4).
147146**
147147**        Also, each component of the sub-query must return the same number
147148**        of result columns. This is actually a requirement for any compound
147149**        SELECT statement, but all the code here does is make sure that no
147150**        such (illegal) sub-query is flattened. The caller will detect the
147151**        syntax error and return a detailed message.
147152**
147153**  (18)  If the sub-query is a compound select, then all terms of the
147154**        ORDER BY clause of the parent must be copies of a term returned
147155**        by the parent query.
147156**
147157**  (19)  If the subquery uses LIMIT then the outer query may not
147158**        have a WHERE clause.
147159**
147160**  (20)  If the sub-query is a compound select, then it must not use
147161**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
147162**        somewhat by saying that the terms of the ORDER BY clause must
147163**        appear as unmodified result columns in the outer query.  But we
147164**        have other optimizations in mind to deal with that case.
147165**
147166**  (21)  If the subquery uses LIMIT then the outer query may not be
147167**        DISTINCT.  (See ticket [752e1646fc]).
147168**
147169**  (22)  The subquery may not be a recursive CTE.
147170**
147171**  (23)  If the outer query is a recursive CTE, then the sub-query may not be
147172**        a compound query.  This restriction is because transforming the
147173**        parent to a compound query confuses the code that handles
147174**        recursive queries in multiSelect().
147175**
147176**  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
147177**        The subquery may not be an aggregate that uses the built-in min() or
147178**        or max() functions.  (Without this restriction, a query like:
147179**        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
147180**        return the value X for which Y was maximal.)
147181**
147182**  (25)  If either the subquery or the parent query contains a window
147183**        function in the select list or ORDER BY clause, flattening
147184**        is not attempted.
147185**
147186**  (26)  The subquery may not be the right operand of a RIGHT JOIN.
147187**        See also (3) for restrictions on LEFT JOIN.
147188**
147189**  (27)  The subquery may not contain a FULL or RIGHT JOIN unless it
147190**        is the first element of the parent query.  Two subcases:
147191**        (27a) the subquery is not a compound query.
147192**        (27b) the subquery is a compound query and the RIGHT JOIN occurs
147193**              in any arm of the compound query.  (See also (17g).)
147194**
147195**  (28)  The subquery is not a MATERIALIZED CTE.  (This is handled
147196**        in the caller before ever reaching this routine.)
147197**
147198**
147199** In this routine, the "p" parameter is a pointer to the outer query.
147200** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
147201** uses aggregates.
147202**
147203** If flattening is not attempted, this routine is a no-op and returns 0.
147204** If flattening is attempted this routine returns 1.
147205**
147206** All of the expression analysis must occur on both the outer query and
147207** the subquery before this routine runs.
147208*/
147209static int flattenSubquery(
147210  Parse *pParse,       /* Parsing context */
147211  Select *p,           /* The parent or outer SELECT statement */
147212  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
147213  int isAgg            /* True if outer SELECT uses aggregate functions */
147214){
147215  const char *zSavedAuthContext = pParse->zAuthContext;
147216  Select *pParent;    /* Current UNION ALL term of the other query */
147217  Select *pSub;       /* The inner query or "subquery" */
147218  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
147219  SrcList *pSrc;      /* The FROM clause of the outer query */
147220  SrcList *pSubSrc;   /* The FROM clause of the subquery */
147221  int iParent;        /* VDBE cursor number of the pSub result set temp table */
147222  int iNewParent = -1;/* Replacement table for iParent */
147223  int isOuterJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
147224  int i;              /* Loop counter */
147225  Expr *pWhere;                    /* The WHERE clause */
147226  SrcItem *pSubitem;               /* The subquery */
147227  sqlite3 *db = pParse->db;
147228  Walker w;                        /* Walker to persist agginfo data */
147229  int *aCsrMap = 0;
147230
147231  /* Check to see if flattening is permitted.  Return 0 if not.
147232  */
147233  assert( p!=0 );
147234  assert( p->pPrior==0 );
147235  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
147236  pSrc = p->pSrc;
147237  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
147238  pSubitem = &pSrc->a[iFrom];
147239  iParent = pSubitem->iCursor;
147240  pSub = pSubitem->pSelect;
147241  assert( pSub!=0 );
147242
147243#ifndef SQLITE_OMIT_WINDOWFUNC
147244  if( p->pWin || pSub->pWin ) return 0;                  /* Restriction (25) */
147245#endif
147246
147247  pSubSrc = pSub->pSrc;
147248  assert( pSubSrc );
147249  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
147250  ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
147251  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
147252  ** became arbitrary expressions, we were forced to add restrictions (13)
147253  ** and (14). */
147254  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
147255  if( pSub->pLimit && pSub->pLimit->pRight ) return 0;   /* Restriction (14) */
147256  if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
147257    return 0;                                            /* Restriction (15) */
147258  }
147259  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
147260  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (4)  */
147261  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
147262     return 0;         /* Restrictions (8)(9) */
147263  }
147264  if( p->pOrderBy && pSub->pOrderBy ){
147265     return 0;                                           /* Restriction (11) */
147266  }
147267  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
147268  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
147269  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
147270     return 0;         /* Restriction (21) */
147271  }
147272  if( pSub->selFlags & (SF_Recursive) ){
147273    return 0; /* Restrictions (22) */
147274  }
147275
147276  /*
147277  ** If the subquery is the right operand of a LEFT JOIN, then the
147278  ** subquery may not be a join itself (3a). Example of why this is not
147279  ** allowed:
147280  **
147281  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
147282  **
147283  ** If we flatten the above, we would get
147284  **
147285  **         (t1 LEFT OUTER JOIN t2) JOIN t3
147286  **
147287  ** which is not at all the same thing.
147288  **
147289  ** See also tickets #306, #350, and #3300.
147290  */
147291  if( (pSubitem->fg.jointype & (JT_OUTER|JT_LTORJ))!=0 ){
147292    if( pSubSrc->nSrc>1                        /* (3a) */
147293     || IsVirtual(pSubSrc->a[0].pTab)          /* (3b) */
147294     || (p->selFlags & SF_Distinct)!=0         /* (3d) */
147295     || (pSubitem->fg.jointype & JT_RIGHT)!=0  /* (26) */
147296    ){
147297      return 0;
147298    }
147299    isOuterJoin = 1;
147300  }
147301
147302  assert( pSubSrc->nSrc>0 );  /* True by restriction (7) */
147303  if( iFrom>0 && (pSubSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
147304    return 0;   /* Restriction (27a) */
147305  }
147306
147307  /* Condition (28) is blocked by the caller */
147308  assert( !pSubitem->fg.isCte || pSubitem->u2.pCteUse->eM10d!=M10d_Yes );
147309
147310  /* Restriction (17): If the sub-query is a compound SELECT, then it must
147311  ** use only the UNION ALL operator. And none of the simple select queries
147312  ** that make up the compound SELECT are allowed to be aggregate or distinct
147313  ** queries.
147314  */
147315  if( pSub->pPrior ){
147316    int ii;
147317    if( pSub->pOrderBy ){
147318      return 0;  /* Restriction (20) */
147319    }
147320    if( isAgg || (p->selFlags & SF_Distinct)!=0 || isOuterJoin>0 ){
147321      return 0; /* (17d1), (17d2), or (17f) */
147322    }
147323    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
147324      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
147325      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
147326      assert( pSub->pSrc!=0 );
147327      assert( (pSub->selFlags & SF_Recursive)==0 );
147328      assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
147329      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0    /* (17b) */
147330       || (pSub1->pPrior && pSub1->op!=TK_ALL)                 /* (17a) */
147331       || pSub1->pSrc->nSrc<1                                  /* (17c) */
147332#ifndef SQLITE_OMIT_WINDOWFUNC
147333       || pSub1->pWin                                          /* (17e) */
147334#endif
147335      ){
147336        return 0;
147337      }
147338      if( iFrom>0 && (pSub1->pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
147339        /* Without this restriction, the JT_LTORJ flag would end up being
147340        ** omitted on left-hand tables of the right join that is being
147341        ** flattened. */
147342        return 0;   /* Restrictions (17g), (27b) */
147343      }
147344      testcase( pSub1->pSrc->nSrc>1 );
147345    }
147346
147347    /* Restriction (18). */
147348    if( p->pOrderBy ){
147349      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
147350        if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
147351      }
147352    }
147353
147354    /* Restriction (23) */
147355    if( (p->selFlags & SF_Recursive) ) return 0;
147356
147357    /* Restriction (17h) */
147358    if( compoundHasDifferentAffinities(pSub) ) return 0;
147359
147360    if( pSrc->nSrc>1 ){
147361      if( pParse->nSelect>500 ) return 0;
147362      if( OptimizationDisabled(db, SQLITE_FlttnUnionAll) ) return 0;
147363      aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int));
147364      if( aCsrMap ) aCsrMap[0] = pParse->nTab;
147365    }
147366  }
147367
147368  /***** If we reach this point, flattening is permitted. *****/
147369  TREETRACE(0x4,pParse,p,("flatten %u.%p from term %d\n",
147370                   pSub->selId, pSub, iFrom));
147371
147372  /* Authorize the subquery */
147373  pParse->zAuthContext = pSubitem->zName;
147374  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
147375  testcase( i==SQLITE_DENY );
147376  pParse->zAuthContext = zSavedAuthContext;
147377
147378  /* Delete the transient structures associated with the subquery */
147379  pSub1 = pSubitem->pSelect;
147380  sqlite3DbFree(db, pSubitem->zDatabase);
147381  sqlite3DbFree(db, pSubitem->zName);
147382  sqlite3DbFree(db, pSubitem->zAlias);
147383  pSubitem->zDatabase = 0;
147384  pSubitem->zName = 0;
147385  pSubitem->zAlias = 0;
147386  pSubitem->pSelect = 0;
147387  assert( pSubitem->fg.isUsing!=0 || pSubitem->u3.pOn==0 );
147388
147389  /* If the sub-query is a compound SELECT statement, then (by restrictions
147390  ** 17 and 18 above) it must be a UNION ALL and the parent query must
147391  ** be of the form:
147392  **
147393  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
147394  **
147395  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
147396  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
147397  ** OFFSET clauses and joins them to the left-hand-side of the original
147398  ** using UNION ALL operators. In this case N is the number of simple
147399  ** select statements in the compound sub-query.
147400  **
147401  ** Example:
147402  **
147403  **     SELECT a+1 FROM (
147404  **        SELECT x FROM tab
147405  **        UNION ALL
147406  **        SELECT y FROM tab
147407  **        UNION ALL
147408  **        SELECT abs(z*2) FROM tab2
147409  **     ) WHERE a!=5 ORDER BY 1
147410  **
147411  ** Transformed into:
147412  **
147413  **     SELECT x+1 FROM tab WHERE x+1!=5
147414  **     UNION ALL
147415  **     SELECT y+1 FROM tab WHERE y+1!=5
147416  **     UNION ALL
147417  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
147418  **     ORDER BY 1
147419  **
147420  ** We call this the "compound-subquery flattening".
147421  */
147422  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
147423    Select *pNew;
147424    ExprList *pOrderBy = p->pOrderBy;
147425    Expr *pLimit = p->pLimit;
147426    Select *pPrior = p->pPrior;
147427    Table *pItemTab = pSubitem->pTab;
147428    pSubitem->pTab = 0;
147429    p->pOrderBy = 0;
147430    p->pPrior = 0;
147431    p->pLimit = 0;
147432    pNew = sqlite3SelectDup(db, p, 0);
147433    p->pLimit = pLimit;
147434    p->pOrderBy = pOrderBy;
147435    p->op = TK_ALL;
147436    pSubitem->pTab = pItemTab;
147437    if( pNew==0 ){
147438      p->pPrior = pPrior;
147439    }else{
147440      pNew->selId = ++pParse->nSelect;
147441      if( aCsrMap && ALWAYS(db->mallocFailed==0) ){
147442        renumberCursors(pParse, pNew, iFrom, aCsrMap);
147443      }
147444      pNew->pPrior = pPrior;
147445      if( pPrior ) pPrior->pNext = pNew;
147446      pNew->pNext = p;
147447      p->pPrior = pNew;
147448      TREETRACE(0x4,pParse,p,("compound-subquery flattener"
147449                              " creates %u as peer\n",pNew->selId));
147450    }
147451    assert( pSubitem->pSelect==0 );
147452  }
147453  sqlite3DbFree(db, aCsrMap);
147454  if( db->mallocFailed ){
147455    pSubitem->pSelect = pSub1;
147456    return 1;
147457  }
147458
147459  /* Defer deleting the Table object associated with the
147460  ** subquery until code generation is
147461  ** complete, since there may still exist Expr.pTab entries that
147462  ** refer to the subquery even after flattening.  Ticket #3346.
147463  **
147464  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
147465  */
147466  if( ALWAYS(pSubitem->pTab!=0) ){
147467    Table *pTabToDel = pSubitem->pTab;
147468    if( pTabToDel->nTabRef==1 ){
147469      Parse *pToplevel = sqlite3ParseToplevel(pParse);
147470      sqlite3ParserAddCleanup(pToplevel, sqlite3DeleteTableGeneric, pTabToDel);
147471      testcase( pToplevel->earlyCleanup );
147472    }else{
147473      pTabToDel->nTabRef--;
147474    }
147475    pSubitem->pTab = 0;
147476  }
147477
147478  /* The following loop runs once for each term in a compound-subquery
147479  ** flattening (as described above).  If we are doing a different kind
147480  ** of flattening - a flattening other than a compound-subquery flattening -
147481  ** then this loop only runs once.
147482  **
147483  ** This loop moves all of the FROM elements of the subquery into the
147484  ** the FROM clause of the outer query.  Before doing this, remember
147485  ** the cursor number for the original outer query FROM element in
147486  ** iParent.  The iParent cursor will never be used.  Subsequent code
147487  ** will scan expressions looking for iParent references and replace
147488  ** those references with expressions that resolve to the subquery FROM
147489  ** elements we are now copying in.
147490  */
147491  pSub = pSub1;
147492  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
147493    int nSubSrc;
147494    u8 jointype = 0;
147495    u8 ltorj = pSrc->a[iFrom].fg.jointype & JT_LTORJ;
147496    assert( pSub!=0 );
147497    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
147498    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
147499    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
147500
147501    if( pParent==p ){
147502      jointype = pSubitem->fg.jointype;     /* First time through the loop */
147503    }
147504
147505    /* The subquery uses a single slot of the FROM clause of the outer
147506    ** query.  If the subquery has more than one element in its FROM clause,
147507    ** then expand the outer query to make space for it to hold all elements
147508    ** of the subquery.
147509    **
147510    ** Example:
147511    **
147512    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
147513    **
147514    ** The outer query has 3 slots in its FROM clause.  One slot of the
147515    ** outer query (the middle slot) is used by the subquery.  The next
147516    ** block of code will expand the outer query FROM clause to 4 slots.
147517    ** The middle slot is expanded to two slots in order to make space
147518    ** for the two elements in the FROM clause of the subquery.
147519    */
147520    if( nSubSrc>1 ){
147521      pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
147522      if( pSrc==0 ) break;
147523      pParent->pSrc = pSrc;
147524    }
147525
147526    /* Transfer the FROM clause terms from the subquery into the
147527    ** outer query.
147528    */
147529    for(i=0; i<nSubSrc; i++){
147530      SrcItem *pItem = &pSrc->a[i+iFrom];
147531      if( pItem->fg.isUsing ) sqlite3IdListDelete(db, pItem->u3.pUsing);
147532      assert( pItem->fg.isTabFunc==0 );
147533      *pItem = pSubSrc->a[i];
147534      pItem->fg.jointype |= ltorj;
147535      iNewParent = pSubSrc->a[i].iCursor;
147536      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
147537    }
147538    pSrc->a[iFrom].fg.jointype &= JT_LTORJ;
147539    pSrc->a[iFrom].fg.jointype |= jointype | ltorj;
147540
147541    /* Now begin substituting subquery result set expressions for
147542    ** references to the iParent in the outer query.
147543    **
147544    ** Example:
147545    **
147546    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
147547    **   \                     \_____________ subquery __________/          /
147548    **    \_____________________ outer query ______________________________/
147549    **
147550    ** We look at every expression in the outer query and every place we see
147551    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
147552    */
147553    if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){
147554      /* At this point, any non-zero iOrderByCol values indicate that the
147555      ** ORDER BY column expression is identical to the iOrderByCol'th
147556      ** expression returned by SELECT statement pSub. Since these values
147557      ** do not necessarily correspond to columns in SELECT statement pParent,
147558      ** zero them before transferring the ORDER BY clause.
147559      **
147560      ** Not doing this may cause an error if a subsequent call to this
147561      ** function attempts to flatten a compound sub-query into pParent
147562      ** (the only way this can happen is if the compound sub-query is
147563      ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
147564      ExprList *pOrderBy = pSub->pOrderBy;
147565      for(i=0; i<pOrderBy->nExpr; i++){
147566        pOrderBy->a[i].u.x.iOrderByCol = 0;
147567      }
147568      assert( pParent->pOrderBy==0 );
147569      pParent->pOrderBy = pOrderBy;
147570      pSub->pOrderBy = 0;
147571    }
147572    pWhere = pSub->pWhere;
147573    pSub->pWhere = 0;
147574    if( isOuterJoin>0 ){
147575      sqlite3SetJoinExpr(pWhere, iNewParent, EP_OuterON);
147576    }
147577    if( pWhere ){
147578      if( pParent->pWhere ){
147579        pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere);
147580      }else{
147581        pParent->pWhere = pWhere;
147582      }
147583    }
147584    if( db->mallocFailed==0 ){
147585      SubstContext x;
147586      x.pParse = pParse;
147587      x.iTable = iParent;
147588      x.iNewTable = iNewParent;
147589      x.isOuterJoin = isOuterJoin;
147590      x.pEList = pSub->pEList;
147591      x.pCList = findLeftmostExprlist(pSub);
147592      substSelect(&x, pParent, 0);
147593    }
147594
147595    /* The flattened query is a compound if either the inner or the
147596    ** outer query is a compound. */
147597    pParent->selFlags |= pSub->selFlags & SF_Compound;
147598    assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
147599
147600    /*
147601    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
147602    **
147603    ** One is tempted to try to add a and b to combine the limits.  But this
147604    ** does not work if either limit is negative.
147605    */
147606    if( pSub->pLimit ){
147607      pParent->pLimit = pSub->pLimit;
147608      pSub->pLimit = 0;
147609    }
147610
147611    /* Recompute the SrcItem.colUsed masks for the flattened
147612    ** tables. */
147613    for(i=0; i<nSubSrc; i++){
147614      recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]);
147615    }
147616  }
147617
147618  /* Finally, delete what is left of the subquery and return success.
147619  */
147620  sqlite3AggInfoPersistWalkerInit(&w, pParse);
147621  sqlite3WalkSelect(&w,pSub1);
147622  sqlite3SelectDelete(db, pSub1);
147623
147624#if TREETRACE_ENABLED
147625  if( sqlite3TreeTrace & 0x4 ){
147626    TREETRACE(0x4,pParse,p,("After flattening:\n"));
147627    sqlite3TreeViewSelect(0, p, 0);
147628  }
147629#endif
147630
147631  return 1;
147632}
147633#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
147634
147635/*
147636** A structure to keep track of all of the column values that are fixed to
147637** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
147638*/
147639typedef struct WhereConst WhereConst;
147640struct WhereConst {
147641  Parse *pParse;   /* Parsing context */
147642  u8 *pOomFault;   /* Pointer to pParse->db->mallocFailed */
147643  int nConst;      /* Number for COLUMN=CONSTANT terms */
147644  int nChng;       /* Number of times a constant is propagated */
147645  int bHasAffBlob; /* At least one column in apExpr[] as affinity BLOB */
147646  u32 mExcludeOn;  /* Which ON expressions to exclude from considertion.
147647                   ** Either EP_OuterON or EP_InnerON|EP_OuterON */
147648  Expr **apExpr;   /* [i*2] is COLUMN and [i*2+1] is VALUE */
147649};
147650
147651/*
147652** Add a new entry to the pConst object.  Except, do not add duplicate
147653** pColumn entries.  Also, do not add if doing so would not be appropriate.
147654**
147655** The caller guarantees the pColumn is a column and pValue is a constant.
147656** This routine has to do some additional checks before completing the
147657** insert.
147658*/
147659static void constInsert(
147660  WhereConst *pConst,  /* The WhereConst into which we are inserting */
147661  Expr *pColumn,       /* The COLUMN part of the constraint */
147662  Expr *pValue,        /* The VALUE part of the constraint */
147663  Expr *pExpr          /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */
147664){
147665  int i;
147666  assert( pColumn->op==TK_COLUMN );
147667  assert( sqlite3ExprIsConstant(pConst->pParse, pValue) );
147668
147669  if( ExprHasProperty(pColumn, EP_FixedCol) ) return;
147670  if( sqlite3ExprAffinity(pValue)!=0 ) return;
147671  if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){
147672    return;
147673  }
147674
147675  /* 2018-10-25 ticket [cf5ed20f]
147676  ** Make sure the same pColumn is not inserted more than once */
147677  for(i=0; i<pConst->nConst; i++){
147678    const Expr *pE2 = pConst->apExpr[i*2];
147679    assert( pE2->op==TK_COLUMN );
147680    if( pE2->iTable==pColumn->iTable
147681     && pE2->iColumn==pColumn->iColumn
147682    ){
147683      return;  /* Already present.  Return without doing anything. */
147684    }
147685  }
147686  if( sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
147687    pConst->bHasAffBlob = 1;
147688  }
147689
147690  pConst->nConst++;
147691  pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
147692                         pConst->nConst*2*sizeof(Expr*));
147693  if( pConst->apExpr==0 ){
147694    pConst->nConst = 0;
147695  }else{
147696    pConst->apExpr[pConst->nConst*2-2] = pColumn;
147697    pConst->apExpr[pConst->nConst*2-1] = pValue;
147698  }
147699}
147700
147701/*
147702** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
147703** is a constant expression and where the term must be true because it
147704** is part of the AND-connected terms of the expression.  For each term
147705** found, add it to the pConst structure.
147706*/
147707static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
147708  Expr *pRight, *pLeft;
147709  if( NEVER(pExpr==0) ) return;
147710  if( ExprHasProperty(pExpr, pConst->mExcludeOn) ){
147711    testcase( ExprHasProperty(pExpr, EP_OuterON) );
147712    testcase( ExprHasProperty(pExpr, EP_InnerON) );
147713    return;
147714  }
147715  if( pExpr->op==TK_AND ){
147716    findConstInWhere(pConst, pExpr->pRight);
147717    findConstInWhere(pConst, pExpr->pLeft);
147718    return;
147719  }
147720  if( pExpr->op!=TK_EQ ) return;
147721  pRight = pExpr->pRight;
147722  pLeft = pExpr->pLeft;
147723  assert( pRight!=0 );
147724  assert( pLeft!=0 );
147725  if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pConst->pParse, pLeft) ){
147726    constInsert(pConst,pRight,pLeft,pExpr);
147727  }
147728  if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pConst->pParse, pRight) ){
147729    constInsert(pConst,pLeft,pRight,pExpr);
147730  }
147731}
147732
147733/*
147734** This is a helper function for Walker callback propagateConstantExprRewrite().
147735**
147736** Argument pExpr is a candidate expression to be replaced by a value. If
147737** pExpr is equivalent to one of the columns named in pWalker->u.pConst,
147738** then overwrite it with the corresponding value. Except, do not do so
147739** if argument bIgnoreAffBlob is non-zero and the affinity of pExpr
147740** is SQLITE_AFF_BLOB.
147741*/
147742static int propagateConstantExprRewriteOne(
147743  WhereConst *pConst,
147744  Expr *pExpr,
147745  int bIgnoreAffBlob
147746){
147747  int i;
147748  if( pConst->pOomFault[0] ) return WRC_Prune;
147749  if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
147750  if( ExprHasProperty(pExpr, EP_FixedCol|pConst->mExcludeOn) ){
147751    testcase( ExprHasProperty(pExpr, EP_FixedCol) );
147752    testcase( ExprHasProperty(pExpr, EP_OuterON) );
147753    testcase( ExprHasProperty(pExpr, EP_InnerON) );
147754    return WRC_Continue;
147755  }
147756  for(i=0; i<pConst->nConst; i++){
147757    Expr *pColumn = pConst->apExpr[i*2];
147758    if( pColumn==pExpr ) continue;
147759    if( pColumn->iTable!=pExpr->iTable ) continue;
147760    if( pColumn->iColumn!=pExpr->iColumn ) continue;
147761    if( bIgnoreAffBlob && sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
147762      break;
147763    }
147764    /* A match is found.  Add the EP_FixedCol property */
147765    pConst->nChng++;
147766    ExprClearProperty(pExpr, EP_Leaf);
147767    ExprSetProperty(pExpr, EP_FixedCol);
147768    assert( pExpr->pLeft==0 );
147769    pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
147770    if( pConst->pParse->db->mallocFailed ) return WRC_Prune;
147771    break;
147772  }
147773  return WRC_Prune;
147774}
147775
147776/*
147777** This is a Walker expression callback. pExpr is a node from the WHERE
147778** clause of a SELECT statement. This function examines pExpr to see if
147779** any substitutions based on the contents of pWalker->u.pConst should
147780** be made to pExpr or its immediate children.
147781**
147782** A substitution is made if:
147783**
147784**   + pExpr is a column with an affinity other than BLOB that matches
147785**     one of the columns in pWalker->u.pConst, or
147786**
147787**   + pExpr is a binary comparison operator (=, <=, >=, <, >) that
147788**     uses an affinity other than TEXT and one of its immediate
147789**     children is a column that matches one of the columns in
147790**     pWalker->u.pConst.
147791*/
147792static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
147793  WhereConst *pConst = pWalker->u.pConst;
147794  assert( TK_GT==TK_EQ+1 );
147795  assert( TK_LE==TK_EQ+2 );
147796  assert( TK_LT==TK_EQ+3 );
147797  assert( TK_GE==TK_EQ+4 );
147798  if( pConst->bHasAffBlob ){
147799    if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE)
147800     || pExpr->op==TK_IS
147801    ){
147802      propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
147803      if( pConst->pOomFault[0] ) return WRC_Prune;
147804      if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){
147805        propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0);
147806      }
147807    }
147808  }
147809  return propagateConstantExprRewriteOne(pConst, pExpr, pConst->bHasAffBlob);
147810}
147811
147812/*
147813** The WHERE-clause constant propagation optimization.
147814**
147815** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
147816** CONSTANT=COLUMN that are top-level AND-connected terms that are not
147817** part of a ON clause from a LEFT JOIN, then throughout the query
147818** replace all other occurrences of COLUMN with CONSTANT.
147819**
147820** For example, the query:
147821**
147822**      SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
147823**
147824** Is transformed into
147825**
147826**      SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
147827**
147828** Return true if any transformations where made and false if not.
147829**
147830** Implementation note:  Constant propagation is tricky due to affinity
147831** and collating sequence interactions.  Consider this example:
147832**
147833**    CREATE TABLE t1(a INT,b TEXT);
147834**    INSERT INTO t1 VALUES(123,'0123');
147835**    SELECT * FROM t1 WHERE a=123 AND b=a;
147836**    SELECT * FROM t1 WHERE a=123 AND b=123;
147837**
147838** The two SELECT statements above should return different answers.  b=a
147839** is always true because the comparison uses numeric affinity, but b=123
147840** is false because it uses text affinity and '0123' is not the same as '123'.
147841** To work around this, the expression tree is not actually changed from
147842** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
147843** and the "123" value is hung off of the pLeft pointer.  Code generator
147844** routines know to generate the constant "123" instead of looking up the
147845** column value.  Also, to avoid collation problems, this optimization is
147846** only attempted if the "a=123" term uses the default BINARY collation.
147847**
147848** 2021-05-25 forum post 6a06202608: Another troublesome case is...
147849**
147850**    CREATE TABLE t1(x);
147851**    INSERT INTO t1 VALUES(10.0);
147852**    SELECT 1 FROM t1 WHERE x=10 AND x LIKE 10;
147853**
147854** The query should return no rows, because the t1.x value is '10.0' not '10'
147855** and '10.0' is not LIKE '10'.  But if we are not careful, the first WHERE
147856** term "x=10" will cause the second WHERE term to become "10 LIKE 10",
147857** resulting in a false positive.  To avoid this, constant propagation for
147858** columns with BLOB affinity is only allowed if the constant is used with
147859** operators ==, <=, <, >=, >, or IS in a way that will cause the correct
147860** type conversions to occur.  See logic associated with the bHasAffBlob flag
147861** for details.
147862*/
147863static int propagateConstants(
147864  Parse *pParse,   /* The parsing context */
147865  Select *p        /* The query in which to propagate constants */
147866){
147867  WhereConst x;
147868  Walker w;
147869  int nChng = 0;
147870  x.pParse = pParse;
147871  x.pOomFault = &pParse->db->mallocFailed;
147872  do{
147873    x.nConst = 0;
147874    x.nChng = 0;
147875    x.apExpr = 0;
147876    x.bHasAffBlob = 0;
147877    if( ALWAYS(p->pSrc!=0)
147878     && p->pSrc->nSrc>0
147879     && (p->pSrc->a[0].fg.jointype & JT_LTORJ)!=0
147880    ){
147881      /* Do not propagate constants on any ON clause if there is a
147882      ** RIGHT JOIN anywhere in the query */
147883      x.mExcludeOn = EP_InnerON | EP_OuterON;
147884    }else{
147885      /* Do not propagate constants through the ON clause of a LEFT JOIN */
147886      x.mExcludeOn = EP_OuterON;
147887    }
147888    findConstInWhere(&x, p->pWhere);
147889    if( x.nConst ){
147890      memset(&w, 0, sizeof(w));
147891      w.pParse = pParse;
147892      w.xExprCallback = propagateConstantExprRewrite;
147893      w.xSelectCallback = sqlite3SelectWalkNoop;
147894      w.xSelectCallback2 = 0;
147895      w.walkerDepth = 0;
147896      w.u.pConst = &x;
147897      sqlite3WalkExpr(&w, p->pWhere);
147898      sqlite3DbFree(x.pParse->db, x.apExpr);
147899      nChng += x.nChng;
147900    }
147901  }while( x.nChng );
147902  return nChng;
147903}
147904
147905#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
147906# if !defined(SQLITE_OMIT_WINDOWFUNC)
147907/*
147908** This function is called to determine whether or not it is safe to
147909** push WHERE clause expression pExpr down to FROM clause sub-query
147910** pSubq, which contains at least one window function. Return 1
147911** if it is safe and the expression should be pushed down, or 0
147912** otherwise.
147913**
147914** It is only safe to push the expression down if it consists only
147915** of constants and copies of expressions that appear in the PARTITION
147916** BY clause of all window function used by the sub-query. It is safe
147917** to filter out entire partitions, but not rows within partitions, as
147918** this may change the results of the window functions.
147919**
147920** At the time this function is called it is guaranteed that
147921**
147922**   * the sub-query uses only one distinct window frame, and
147923**   * that the window frame has a PARTITION BY clause.
147924*/
147925static int pushDownWindowCheck(Parse *pParse, Select *pSubq, Expr *pExpr){
147926  assert( pSubq->pWin->pPartition );
147927  assert( (pSubq->selFlags & SF_MultiPart)==0 );
147928  assert( pSubq->pPrior==0 );
147929  return sqlite3ExprIsConstantOrGroupBy(pParse, pExpr, pSubq->pWin->pPartition);
147930}
147931# endif /* SQLITE_OMIT_WINDOWFUNC */
147932#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
147933
147934#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
147935/*
147936** Make copies of relevant WHERE clause terms of the outer query into
147937** the WHERE clause of subquery.  Example:
147938**
147939**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
147940**
147941** Transformed into:
147942**
147943**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
147944**     WHERE x=5 AND y=10;
147945**
147946** The hope is that the terms added to the inner query will make it more
147947** efficient.
147948**
147949** NAME AMBIGUITY
147950**
147951** This optimization is called the "WHERE-clause push-down optimization".
147952**
147953** Do not confuse this optimization with another unrelated optimization
147954** with a similar name:  The "MySQL push-down optimization" causes WHERE
147955** clause terms that can be evaluated using only the index and without
147956** reference to the table are run first, so that if they are false,
147957** unnecessary table seeks are avoided.
147958**
147959** RULES
147960**
147961** Do not attempt this optimization if:
147962**
147963**   (1) (** This restriction was removed on 2017-09-29.  We used to
147964**           disallow this optimization for aggregate subqueries, but now
147965**           it is allowed by putting the extra terms on the HAVING clause.
147966**           The added HAVING clause is pointless if the subquery lacks
147967**           a GROUP BY clause.  But such a HAVING clause is also harmless
147968**           so there does not appear to be any reason to add extra logic
147969**           to suppress it. **)
147970**
147971**   (2) The inner query is the recursive part of a common table expression.
147972**
147973**   (3) The inner query has a LIMIT clause (since the changes to the WHERE
147974**       clause would change the meaning of the LIMIT).
147975**
147976**   (4) The inner query is the right operand of a LEFT JOIN and the
147977**       expression to be pushed down does not come from the ON clause
147978**       on that LEFT JOIN.
147979**
147980**   (5) The WHERE clause expression originates in the ON or USING clause
147981**       of a LEFT JOIN where iCursor is not the right-hand table of that
147982**       left join.  An example:
147983**
147984**           SELECT *
147985**           FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
147986**           JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
147987**           LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
147988**
147989**       The correct answer is three rows:  (1,1,NULL),(2,2,8),(2,2,9).
147990**       But if the (b2=2) term were to be pushed down into the bb subquery,
147991**       then the (1,1,NULL) row would be suppressed.
147992**
147993**   (6) Window functions make things tricky as changes to the WHERE clause
147994**       of the inner query could change the window over which window
147995**       functions are calculated. Therefore, do not attempt the optimization
147996**       if:
147997**
147998**     (6a) The inner query uses multiple incompatible window partitions.
147999**
148000**     (6b) The inner query is a compound and uses window-functions.
148001**
148002**     (6c) The WHERE clause does not consist entirely of constants and
148003**          copies of expressions found in the PARTITION BY clause of
148004**          all window-functions used by the sub-query. It is safe to
148005**          filter out entire partitions, as this does not change the
148006**          window over which any window-function is calculated.
148007**
148008**   (7) The inner query is a Common Table Expression (CTE) that should
148009**       be materialized.  (This restriction is implemented in the calling
148010**       routine.)
148011**
148012**   (8) If the subquery is a compound that uses UNION, INTERSECT,
148013**       or EXCEPT, then all of the result set columns for all arms of
148014**       the compound must use the BINARY collating sequence.
148015**
148016**   (9) All three of the following are true:
148017**
148018**       (9a) The WHERE clause expression originates in the ON or USING clause
148019**            of a join (either an INNER or an OUTER join), and
148020**
148021**       (9b) The subquery is to the right of the ON/USING clause
148022**
148023**       (9c) There is a RIGHT JOIN (or FULL JOIN) in between the ON/USING
148024**            clause and the subquery.
148025**
148026**       Without this restriction, the WHERE-clause push-down optimization
148027**       might move the ON/USING filter expression from the left side of a
148028**       RIGHT JOIN over to the right side, which leads to incorrect answers.
148029**       See also restriction (6) in sqlite3ExprIsSingleTableConstraint().
148030**
148031**  (10) The inner query is not the right-hand table of a RIGHT JOIN.
148032**
148033**  (11) The subquery is not a VALUES clause
148034**
148035**  (12) The WHERE clause is not "rowid ISNULL" or the equivalent.  This
148036**       case only comes up if SQLite is compiled using
148037**       SQLITE_ALLOW_ROWID_IN_VIEW.
148038**
148039** Return 0 if no changes are made and non-zero if one or more WHERE clause
148040** terms are duplicated into the subquery.
148041*/
148042static int pushDownWhereTerms(
148043  Parse *pParse,        /* Parse context (for malloc() and error reporting) */
148044  Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
148045  Expr *pWhere,         /* The WHERE clause of the outer query */
148046  SrcList *pSrcList,    /* The complete from clause of the outer query */
148047  int iSrc              /* Which FROM clause term to try to push into  */
148048){
148049  Expr *pNew;
148050  SrcItem *pSrc;        /* The subquery FROM term into which WHERE is pushed */
148051  int nChng = 0;
148052  pSrc = &pSrcList->a[iSrc];
148053  if( pWhere==0 ) return 0;
148054  if( pSubq->selFlags & (SF_Recursive|SF_MultiPart) ){
148055    return 0;           /* restrictions (2) and (11) */
148056  }
148057  if( pSrc->fg.jointype & (JT_LTORJ|JT_RIGHT) ){
148058    return 0;           /* restrictions (10) */
148059  }
148060
148061  if( pSubq->pPrior ){
148062    Select *pSel;
148063    int notUnionAll = 0;
148064    for(pSel=pSubq; pSel; pSel=pSel->pPrior){
148065      u8 op = pSel->op;
148066      assert( op==TK_ALL || op==TK_SELECT
148067           || op==TK_UNION || op==TK_INTERSECT || op==TK_EXCEPT );
148068      if( op!=TK_ALL && op!=TK_SELECT ){
148069        notUnionAll = 1;
148070      }
148071#ifndef SQLITE_OMIT_WINDOWFUNC
148072      if( pSel->pWin ) return 0;    /* restriction (6b) */
148073#endif
148074    }
148075    if( notUnionAll ){
148076      /* If any of the compound arms are connected using UNION, INTERSECT,
148077      ** or EXCEPT, then we must ensure that none of the columns use a
148078      ** non-BINARY collating sequence. */
148079      for(pSel=pSubq; pSel; pSel=pSel->pPrior){
148080        int ii;
148081        const ExprList *pList = pSel->pEList;
148082        assert( pList!=0 );
148083        for(ii=0; ii<pList->nExpr; ii++){
148084          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[ii].pExpr);
148085          if( !sqlite3IsBinary(pColl) ){
148086            return 0;  /* Restriction (8) */
148087          }
148088        }
148089      }
148090    }
148091  }else{
148092#ifndef SQLITE_OMIT_WINDOWFUNC
148093    if( pSubq->pWin && pSubq->pWin->pPartition==0 ) return 0;
148094#endif
148095  }
148096
148097#ifdef SQLITE_DEBUG
148098  /* Only the first term of a compound can have a WITH clause.  But make
148099  ** sure no other terms are marked SF_Recursive in case something changes
148100  ** in the future.
148101  */
148102  {
148103    Select *pX;
148104    for(pX=pSubq; pX; pX=pX->pPrior){
148105      assert( (pX->selFlags & (SF_Recursive))==0 );
148106    }
148107  }
148108#endif
148109
148110  if( pSubq->pLimit!=0 ){
148111    return 0; /* restriction (3) */
148112  }
148113  while( pWhere->op==TK_AND ){
148114    nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, pSrcList, iSrc);
148115    pWhere = pWhere->pLeft;
148116  }
148117
148118#if 0 /* These checks now done by sqlite3ExprIsSingleTableConstraint() */
148119  if( ExprHasProperty(pWhere, EP_OuterON|EP_InnerON) /* (9a) */
148120   && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0     /* Fast pre-test of (9c) */
148121  ){
148122    int jj;
148123    for(jj=0; jj<iSrc; jj++){
148124      if( pWhere->w.iJoin==pSrcList->a[jj].iCursor ){
148125        /* If we reach this point, both (9a) and (9b) are satisfied.
148126        ** The following loop checks (9c):
148127        */
148128        for(jj++; jj<iSrc; jj++){
148129          if( (pSrcList->a[jj].fg.jointype & JT_RIGHT)!=0 ){
148130            return 0;  /* restriction (9) */
148131          }
148132        }
148133      }
148134    }
148135  }
148136  if( isLeftJoin
148137   && (ExprHasProperty(pWhere,EP_OuterON)==0
148138         || pWhere->w.iJoin!=iCursor)
148139  ){
148140    return 0; /* restriction (4) */
148141  }
148142  if( ExprHasProperty(pWhere,EP_OuterON)
148143   && pWhere->w.iJoin!=iCursor
148144  ){
148145    return 0; /* restriction (5) */
148146  }
148147#endif
148148
148149#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
148150  if( ViewCanHaveRowid && (pWhere->op==TK_ISNULL || pWhere->op==TK_NOTNULL) ){
148151    Expr *pLeft = pWhere->pLeft;
148152    if( ALWAYS(pLeft)
148153     && pLeft->op==TK_COLUMN
148154     && pLeft->iColumn < 0
148155    ){
148156      return 0;  /* Restriction (12) */
148157    }
148158  }
148159#endif
148160
148161  if( sqlite3ExprIsSingleTableConstraint(pWhere, pSrcList, iSrc, 1) ){
148162    nChng++;
148163    pSubq->selFlags |= SF_PushDown;
148164    while( pSubq ){
148165      SubstContext x;
148166      pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
148167      unsetJoinExpr(pNew, -1, 1);
148168      x.pParse = pParse;
148169      x.iTable = pSrc->iCursor;
148170      x.iNewTable = pSrc->iCursor;
148171      x.isOuterJoin = 0;
148172      x.pEList = pSubq->pEList;
148173      x.pCList = findLeftmostExprlist(pSubq);
148174      pNew = substExpr(&x, pNew);
148175#ifndef SQLITE_OMIT_WINDOWFUNC
148176      if( pSubq->pWin && 0==pushDownWindowCheck(pParse, pSubq, pNew) ){
148177        /* Restriction 6c has prevented push-down in this case */
148178        sqlite3ExprDelete(pParse->db, pNew);
148179        nChng--;
148180        break;
148181      }
148182#endif
148183      if( pSubq->selFlags & SF_Aggregate ){
148184        pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
148185      }else{
148186        pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
148187      }
148188      pSubq = pSubq->pPrior;
148189    }
148190  }
148191  return nChng;
148192}
148193#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
148194
148195/*
148196** Check to see if a subquery contains result-set columns that are
148197** never used.  If it does, change the value of those result-set columns
148198** to NULL so that they do not cause unnecessary work to compute.
148199**
148200** Return the number of column that were changed to NULL.
148201*/
148202static int disableUnusedSubqueryResultColumns(SrcItem *pItem){
148203  int nCol;
148204  Select *pSub;      /* The subquery to be simplified */
148205  Select *pX;        /* For looping over compound elements of pSub */
148206  Table *pTab;       /* The table that describes the subquery */
148207  int j;             /* Column number */
148208  int nChng = 0;     /* Number of columns converted to NULL */
148209  Bitmask colUsed;   /* Columns that may not be NULLed out */
148210
148211  assert( pItem!=0 );
148212  if( pItem->fg.isCorrelated || pItem->fg.isCte ){
148213    return 0;
148214  }
148215  assert( pItem->pTab!=0 );
148216  pTab = pItem->pTab;
148217  assert( pItem->pSelect!=0 );
148218  pSub = pItem->pSelect;
148219  assert( pSub->pEList->nExpr==pTab->nCol );
148220  for(pX=pSub; pX; pX=pX->pPrior){
148221    if( (pX->selFlags & (SF_Distinct|SF_Aggregate))!=0 ){
148222      testcase( pX->selFlags & SF_Distinct );
148223      testcase( pX->selFlags & SF_Aggregate );
148224      return 0;
148225    }
148226    if( pX->pPrior && pX->op!=TK_ALL ){
148227      /* This optimization does not work for compound subqueries that
148228      ** use UNION, INTERSECT, or EXCEPT.  Only UNION ALL is allowed. */
148229      return 0;
148230    }
148231#ifndef SQLITE_OMIT_WINDOWFUNC
148232    if( pX->pWin ){
148233      /* This optimization does not work for subqueries that use window
148234      ** functions. */
148235      return 0;
148236    }
148237#endif
148238  }
148239  colUsed = pItem->colUsed;
148240  if( pSub->pOrderBy ){
148241    ExprList *pList = pSub->pOrderBy;
148242    for(j=0; j<pList->nExpr; j++){
148243      u16 iCol = pList->a[j].u.x.iOrderByCol;
148244      if( iCol>0 ){
148245        iCol--;
148246        colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
148247      }
148248    }
148249  }
148250  nCol = pTab->nCol;
148251  for(j=0; j<nCol; j++){
148252    Bitmask m = j<BMS-1 ? MASKBIT(j) : TOPBIT;
148253    if( (m & colUsed)!=0 ) continue;
148254    for(pX=pSub; pX; pX=pX->pPrior) {
148255      Expr *pY = pX->pEList->a[j].pExpr;
148256      if( pY->op==TK_NULL ) continue;
148257      pY->op = TK_NULL;
148258      ExprClearProperty(pY, EP_Skip|EP_Unlikely);
148259      pX->selFlags |= SF_PushDown;
148260      nChng++;
148261    }
148262  }
148263  return nChng;
148264}
148265
148266
148267/*
148268** The pFunc is the only aggregate function in the query.  Check to see
148269** if the query is a candidate for the min/max optimization.
148270**
148271** If the query is a candidate for the min/max optimization, then set
148272** *ppMinMax to be an ORDER BY clause to be used for the optimization
148273** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
148274** whether pFunc is a min() or max() function.
148275**
148276** If the query is not a candidate for the min/max optimization, return
148277** WHERE_ORDERBY_NORMAL (which must be zero).
148278**
148279** This routine must be called after aggregate functions have been
148280** located but before their arguments have been subjected to aggregate
148281** analysis.
148282*/
148283static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
148284  int eRet = WHERE_ORDERBY_NORMAL;      /* Return value */
148285  ExprList *pEList;                     /* Arguments to agg function */
148286  const char *zFunc;                    /* Name of aggregate function pFunc */
148287  ExprList *pOrderBy;
148288  u8 sortFlags = 0;
148289
148290  assert( *ppMinMax==0 );
148291  assert( pFunc->op==TK_AGG_FUNCTION );
148292  assert( !IsWindowFunc(pFunc) );
148293  assert( ExprUseXList(pFunc) );
148294  pEList = pFunc->x.pList;
148295  if( pEList==0
148296   || pEList->nExpr!=1
148297   || ExprHasProperty(pFunc, EP_WinFunc)
148298   || OptimizationDisabled(db, SQLITE_MinMaxOpt)
148299  ){
148300    return eRet;
148301  }
148302  assert( !ExprHasProperty(pFunc, EP_IntValue) );
148303  zFunc = pFunc->u.zToken;
148304  if( sqlite3StrICmp(zFunc, "min")==0 ){
148305    eRet = WHERE_ORDERBY_MIN;
148306    if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){
148307      sortFlags = KEYINFO_ORDER_BIGNULL;
148308    }
148309  }else if( sqlite3StrICmp(zFunc, "max")==0 ){
148310    eRet = WHERE_ORDERBY_MAX;
148311    sortFlags = KEYINFO_ORDER_DESC;
148312  }else{
148313    return eRet;
148314  }
148315  *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
148316  assert( pOrderBy!=0 || db->mallocFailed );
148317  if( pOrderBy ) pOrderBy->a[0].fg.sortFlags = sortFlags;
148318  return eRet;
148319}
148320
148321/*
148322** The select statement passed as the first argument is an aggregate query.
148323** The second argument is the associated aggregate-info object. This
148324** function tests if the SELECT is of the form:
148325**
148326**   SELECT count(*) FROM <tbl>
148327**
148328** where table is a database table, not a sub-select or view. If the query
148329** does match this pattern, then a pointer to the Table object representing
148330** <tbl> is returned. Otherwise, NULL is returned.
148331**
148332** This routine checks to see if it is safe to use the count optimization.
148333** A correct answer is still obtained (though perhaps more slowly) if
148334** this routine returns NULL when it could have returned a table pointer.
148335** But returning the pointer when NULL should have been returned can
148336** result in incorrect answers and/or crashes.  So, when in doubt, return NULL.
148337*/
148338static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
148339  Table *pTab;
148340  Expr *pExpr;
148341
148342  assert( !p->pGroupBy );
148343
148344  if( p->pWhere
148345   || p->pEList->nExpr!=1
148346   || p->pSrc->nSrc!=1
148347   || p->pSrc->a[0].pSelect
148348   || pAggInfo->nFunc!=1
148349   || p->pHaving
148350  ){
148351    return 0;
148352  }
148353  pTab = p->pSrc->a[0].pTab;
148354  assert( pTab!=0 );
148355  assert( !IsView(pTab) );
148356  if( !IsOrdinaryTable(pTab) ) return 0;
148357  pExpr = p->pEList->a[0].pExpr;
148358  assert( pExpr!=0 );
148359  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
148360  if( pExpr->pAggInfo!=pAggInfo ) return 0;
148361  if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
148362  assert( pAggInfo->aFunc[0].pFExpr==pExpr );
148363  testcase( ExprHasProperty(pExpr, EP_Distinct) );
148364  testcase( ExprHasProperty(pExpr, EP_WinFunc) );
148365  if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;
148366
148367  return pTab;
148368}
148369
148370/*
148371** If the source-list item passed as an argument was augmented with an
148372** INDEXED BY clause, then try to locate the specified index. If there
148373** was such a clause and the named index cannot be found, return
148374** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
148375** pFrom->pIndex and return SQLITE_OK.
148376*/
148377SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, SrcItem *pFrom){
148378  Table *pTab = pFrom->pTab;
148379  char *zIndexedBy = pFrom->u1.zIndexedBy;
148380  Index *pIdx;
148381  assert( pTab!=0 );
148382  assert( pFrom->fg.isIndexedBy!=0 );
148383
148384  for(pIdx=pTab->pIndex;
148385      pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
148386      pIdx=pIdx->pNext
148387  );
148388  if( !pIdx ){
148389    sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
148390    pParse->checkSchema = 1;
148391    return SQLITE_ERROR;
148392  }
148393  assert( pFrom->fg.isCte==0 );
148394  pFrom->u2.pIBIndex = pIdx;
148395  return SQLITE_OK;
148396}
148397
148398/*
148399** Detect compound SELECT statements that use an ORDER BY clause with
148400** an alternative collating sequence.
148401**
148402**    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
148403**
148404** These are rewritten as a subquery:
148405**
148406**    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
148407**     ORDER BY ... COLLATE ...
148408**
148409** This transformation is necessary because the multiSelectOrderBy() routine
148410** above that generates the code for a compound SELECT with an ORDER BY clause
148411** uses a merge algorithm that requires the same collating sequence on the
148412** result columns as on the ORDER BY clause.  See ticket
148413** http://www.sqlite.org/src/info/6709574d2a
148414**
148415** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
148416** The UNION ALL operator works fine with multiSelectOrderBy() even when
148417** there are COLLATE terms in the ORDER BY.
148418*/
148419static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
148420  int i;
148421  Select *pNew;
148422  Select *pX;
148423  sqlite3 *db;
148424  struct ExprList_item *a;
148425  SrcList *pNewSrc;
148426  Parse *pParse;
148427  Token dummy;
148428
148429  if( p->pPrior==0 ) return WRC_Continue;
148430  if( p->pOrderBy==0 ) return WRC_Continue;
148431  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
148432  if( pX==0 ) return WRC_Continue;
148433  a = p->pOrderBy->a;
148434#ifndef SQLITE_OMIT_WINDOWFUNC
148435  /* If iOrderByCol is already non-zero, then it has already been matched
148436  ** to a result column of the SELECT statement. This occurs when the
148437  ** SELECT is rewritten for window-functions processing and then passed
148438  ** to sqlite3SelectPrep() and similar a second time. The rewriting done
148439  ** by this function is not required in this case. */
148440  if( a[0].u.x.iOrderByCol ) return WRC_Continue;
148441#endif
148442  for(i=p->pOrderBy->nExpr-1; i>=0; i--){
148443    if( a[i].pExpr->flags & EP_Collate ) break;
148444  }
148445  if( i<0 ) return WRC_Continue;
148446
148447  /* If we reach this point, that means the transformation is required. */
148448
148449  pParse = pWalker->pParse;
148450  db = pParse->db;
148451  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
148452  if( pNew==0 ) return WRC_Abort;
148453  memset(&dummy, 0, sizeof(dummy));
148454  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0);
148455  if( pNewSrc==0 ) return WRC_Abort;
148456  *pNew = *p;
148457  p->pSrc = pNewSrc;
148458  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
148459  p->op = TK_SELECT;
148460  p->pWhere = 0;
148461  pNew->pGroupBy = 0;
148462  pNew->pHaving = 0;
148463  pNew->pOrderBy = 0;
148464  p->pPrior = 0;
148465  p->pNext = 0;
148466  p->pWith = 0;
148467#ifndef SQLITE_OMIT_WINDOWFUNC
148468  p->pWinDefn = 0;
148469#endif
148470  p->selFlags &= ~SF_Compound;
148471  assert( (p->selFlags & SF_Converted)==0 );
148472  p->selFlags |= SF_Converted;
148473  assert( pNew->pPrior!=0 );
148474  pNew->pPrior->pNext = pNew;
148475  pNew->pLimit = 0;
148476  return WRC_Continue;
148477}
148478
148479/*
148480** Check to see if the FROM clause term pFrom has table-valued function
148481** arguments.  If it does, leave an error message in pParse and return
148482** non-zero, since pFrom is not allowed to be a table-valued function.
148483*/
148484static int cannotBeFunction(Parse *pParse, SrcItem *pFrom){
148485  if( pFrom->fg.isTabFunc ){
148486    sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
148487    return 1;
148488  }
148489  return 0;
148490}
148491
148492#ifndef SQLITE_OMIT_CTE
148493/*
148494** Argument pWith (which may be NULL) points to a linked list of nested
148495** WITH contexts, from inner to outermost. If the table identified by
148496** FROM clause element pItem is really a common-table-expression (CTE)
148497** then return a pointer to the CTE definition for that table. Otherwise
148498** return NULL.
148499**
148500** If a non-NULL value is returned, set *ppContext to point to the With
148501** object that the returned CTE belongs to.
148502*/
148503static struct Cte *searchWith(
148504  With *pWith,                    /* Current innermost WITH clause */
148505  SrcItem *pItem,                 /* FROM clause element to resolve */
148506  With **ppContext                /* OUT: WITH clause return value belongs to */
148507){
148508  const char *zName = pItem->zName;
148509  With *p;
148510  assert( pItem->zDatabase==0 );
148511  assert( zName!=0 );
148512  for(p=pWith; p; p=p->pOuter){
148513    int i;
148514    for(i=0; i<p->nCte; i++){
148515      if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
148516        *ppContext = p;
148517        return &p->a[i];
148518      }
148519    }
148520    if( p->bView ) break;
148521  }
148522  return 0;
148523}
148524
148525/* The code generator maintains a stack of active WITH clauses
148526** with the inner-most WITH clause being at the top of the stack.
148527**
148528** This routine pushes the WITH clause passed as the second argument
148529** onto the top of the stack. If argument bFree is true, then this
148530** WITH clause will never be popped from the stack but should instead
148531** be freed along with the Parse object. In other cases, when
148532** bFree==0, the With object will be freed along with the SELECT
148533** statement with which it is associated.
148534**
148535** This routine returns a copy of pWith.  Or, if bFree is true and
148536** the pWith object is destroyed immediately due to an OOM condition,
148537** then this routine return NULL.
148538**
148539** If bFree is true, do not continue to use the pWith pointer after
148540** calling this routine,  Instead, use only the return value.
148541*/
148542SQLITE_PRIVATE With *sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
148543  if( pWith ){
148544    if( bFree ){
148545      pWith = (With*)sqlite3ParserAddCleanup(pParse, sqlite3WithDeleteGeneric,
148546                      pWith);
148547      if( pWith==0 ) return 0;
148548    }
148549    if( pParse->nErr==0 ){
148550      assert( pParse->pWith!=pWith );
148551      pWith->pOuter = pParse->pWith;
148552      pParse->pWith = pWith;
148553    }
148554  }
148555  return pWith;
148556}
148557
148558/*
148559** This function checks if argument pFrom refers to a CTE declared by
148560** a WITH clause on the stack currently maintained by the parser (on the
148561** pParse->pWith linked list).  And if currently processing a CTE
148562** CTE expression, through routine checks to see if the reference is
148563** a recursive reference to the CTE.
148564**
148565** If pFrom matches a CTE according to either of these two above, pFrom->pTab
148566** and other fields are populated accordingly.
148567**
148568** Return 0 if no match is found.
148569** Return 1 if a match is found.
148570** Return 2 if an error condition is detected.
148571*/
148572static int resolveFromTermToCte(
148573  Parse *pParse,                  /* The parsing context */
148574  Walker *pWalker,                /* Current tree walker */
148575  SrcItem *pFrom                  /* The FROM clause term to check */
148576){
148577  Cte *pCte;               /* Matched CTE (or NULL if no match) */
148578  With *pWith;             /* The matching WITH */
148579
148580  assert( pFrom->pTab==0 );
148581  if( pParse->pWith==0 ){
148582    /* There are no WITH clauses in the stack.  No match is possible */
148583    return 0;
148584  }
148585  if( pParse->nErr ){
148586    /* Prior errors might have left pParse->pWith in a goofy state, so
148587    ** go no further. */
148588    return 0;
148589  }
148590  if( pFrom->zDatabase!=0 ){
148591    /* The FROM term contains a schema qualifier (ex: main.t1) and so
148592    ** it cannot possibly be a CTE reference. */
148593    return 0;
148594  }
148595  if( pFrom->fg.notCte ){
148596    /* The FROM term is specifically excluded from matching a CTE.
148597    **   (1)  It is part of a trigger that used to have zDatabase but had
148598    **        zDatabase removed by sqlite3FixTriggerStep().
148599    **   (2)  This is the first term in the FROM clause of an UPDATE.
148600    */
148601    return 0;
148602  }
148603  pCte = searchWith(pParse->pWith, pFrom, &pWith);
148604  if( pCte ){
148605    sqlite3 *db = pParse->db;
148606    Table *pTab;
148607    ExprList *pEList;
148608    Select *pSel;
148609    Select *pLeft;                /* Left-most SELECT statement */
148610    Select *pRecTerm;             /* Left-most recursive term */
148611    int bMayRecursive;            /* True if compound joined by UNION [ALL] */
148612    With *pSavedWith;             /* Initial value of pParse->pWith */
148613    int iRecTab = -1;             /* Cursor for recursive table */
148614    CteUse *pCteUse;
148615
148616    /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
148617    ** recursive reference to CTE pCte. Leave an error in pParse and return
148618    ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
148619    ** In this case, proceed.  */
148620    if( pCte->zCteErr ){
148621      sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
148622      return 2;
148623    }
148624    if( cannotBeFunction(pParse, pFrom) ) return 2;
148625
148626    assert( pFrom->pTab==0 );
148627    pTab = sqlite3DbMallocZero(db, sizeof(Table));
148628    if( pTab==0 ) return 2;
148629    pCteUse = pCte->pUse;
148630    if( pCteUse==0 ){
148631      pCte->pUse = pCteUse = sqlite3DbMallocZero(db, sizeof(pCteUse[0]));
148632      if( pCteUse==0
148633       || sqlite3ParserAddCleanup(pParse,sqlite3DbFree,pCteUse)==0
148634      ){
148635        sqlite3DbFree(db, pTab);
148636        return 2;
148637      }
148638      pCteUse->eM10d = pCte->eM10d;
148639    }
148640    pFrom->pTab = pTab;
148641    pTab->nTabRef = 1;
148642    pTab->zName = sqlite3DbStrDup(db, pCte->zName);
148643    pTab->iPKey = -1;
148644    pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
148645    pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
148646    pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
148647    if( db->mallocFailed ) return 2;
148648    pFrom->pSelect->selFlags |= SF_CopyCte;
148649    assert( pFrom->pSelect );
148650    if( pFrom->fg.isIndexedBy ){
148651      sqlite3ErrorMsg(pParse, "no such index: \"%s\"", pFrom->u1.zIndexedBy);
148652      return 2;
148653    }
148654    pFrom->fg.isCte = 1;
148655    pFrom->u2.pCteUse = pCteUse;
148656    pCteUse->nUse++;
148657
148658    /* Check if this is a recursive CTE. */
148659    pRecTerm = pSel = pFrom->pSelect;
148660    bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
148661    while( bMayRecursive && pRecTerm->op==pSel->op ){
148662      int i;
148663      SrcList *pSrc = pRecTerm->pSrc;
148664      assert( pRecTerm->pPrior!=0 );
148665      for(i=0; i<pSrc->nSrc; i++){
148666        SrcItem *pItem = &pSrc->a[i];
148667        if( pItem->zDatabase==0
148668         && pItem->zName!=0
148669         && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
148670        ){
148671          pItem->pTab = pTab;
148672          pTab->nTabRef++;
148673          pItem->fg.isRecursive = 1;
148674          if( pRecTerm->selFlags & SF_Recursive ){
148675            sqlite3ErrorMsg(pParse,
148676               "multiple references to recursive table: %s", pCte->zName
148677            );
148678            return 2;
148679          }
148680          pRecTerm->selFlags |= SF_Recursive;
148681          if( iRecTab<0 ) iRecTab = pParse->nTab++;
148682          pItem->iCursor = iRecTab;
148683        }
148684      }
148685      if( (pRecTerm->selFlags & SF_Recursive)==0 ) break;
148686      pRecTerm = pRecTerm->pPrior;
148687    }
148688
148689    pCte->zCteErr = "circular reference: %s";
148690    pSavedWith = pParse->pWith;
148691    pParse->pWith = pWith;
148692    if( pSel->selFlags & SF_Recursive ){
148693      int rc;
148694      assert( pRecTerm!=0 );
148695      assert( (pRecTerm->selFlags & SF_Recursive)==0 );
148696      assert( pRecTerm->pNext!=0 );
148697      assert( (pRecTerm->pNext->selFlags & SF_Recursive)!=0 );
148698      assert( pRecTerm->pWith==0 );
148699      pRecTerm->pWith = pSel->pWith;
148700      rc = sqlite3WalkSelect(pWalker, pRecTerm);
148701      pRecTerm->pWith = 0;
148702      if( rc ){
148703        pParse->pWith = pSavedWith;
148704        return 2;
148705      }
148706    }else{
148707      if( sqlite3WalkSelect(pWalker, pSel) ){
148708        pParse->pWith = pSavedWith;
148709        return 2;
148710      }
148711    }
148712    pParse->pWith = pWith;
148713
148714    for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
148715    pEList = pLeft->pEList;
148716    if( pCte->pCols ){
148717      if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
148718        sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
148719            pCte->zName, pEList->nExpr, pCte->pCols->nExpr
148720        );
148721        pParse->pWith = pSavedWith;
148722        return 2;
148723      }
148724      pEList = pCte->pCols;
148725    }
148726
148727    sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
148728    if( bMayRecursive ){
148729      if( pSel->selFlags & SF_Recursive ){
148730        pCte->zCteErr = "multiple recursive references: %s";
148731      }else{
148732        pCte->zCteErr = "recursive reference in a subquery: %s";
148733      }
148734      sqlite3WalkSelect(pWalker, pSel);
148735    }
148736    pCte->zCteErr = 0;
148737    pParse->pWith = pSavedWith;
148738    return 1;  /* Success */
148739  }
148740  return 0;  /* No match */
148741}
148742#endif
148743
148744#ifndef SQLITE_OMIT_CTE
148745/*
148746** If the SELECT passed as the second argument has an associated WITH
148747** clause, pop it from the stack stored as part of the Parse object.
148748**
148749** This function is used as the xSelectCallback2() callback by
148750** sqlite3SelectExpand() when walking a SELECT tree to resolve table
148751** names and other FROM clause elements.
148752*/
148753SQLITE_PRIVATE void sqlite3SelectPopWith(Walker *pWalker, Select *p){
148754  Parse *pParse = pWalker->pParse;
148755  if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
148756    With *pWith = findRightmost(p)->pWith;
148757    if( pWith!=0 ){
148758      assert( pParse->pWith==pWith || pParse->nErr );
148759      pParse->pWith = pWith->pOuter;
148760    }
148761  }
148762}
148763#endif
148764
148765/*
148766** The SrcItem structure passed as the second argument represents a
148767** sub-query in the FROM clause of a SELECT statement. This function
148768** allocates and populates the SrcItem.pTab object. If successful,
148769** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
148770** SQLITE_NOMEM.
148771*/
148772SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse *pParse, SrcItem *pFrom){
148773  Select *pSel = pFrom->pSelect;
148774  Table *pTab;
148775
148776  assert( pSel );
148777  pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
148778  if( pTab==0 ) return SQLITE_NOMEM;
148779  pTab->nTabRef = 1;
148780  if( pFrom->zAlias ){
148781    pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
148782  }else{
148783    pTab->zName = sqlite3MPrintf(pParse->db, "%!S", pFrom);
148784  }
148785  while( pSel->pPrior ){ pSel = pSel->pPrior; }
148786  sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
148787  pTab->iPKey = -1;
148788  pTab->eTabType = TABTYP_VIEW;
148789  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
148790#ifndef SQLITE_ALLOW_ROWID_IN_VIEW
148791  /* The usual case - do not allow ROWID on a subquery */
148792  pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
148793#else
148794  /* Legacy compatibility mode */
148795  pTab->tabFlags |= TF_Ephemeral | sqlite3Config.mNoVisibleRowid;
148796#endif
148797  return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
148798}
148799
148800
148801/*
148802** Check the N SrcItem objects to the right of pBase.  (N might be zero!)
148803** If any of those SrcItem objects have a USING clause containing zName
148804** then return true.
148805**
148806** If N is zero, or none of the N SrcItem objects to the right of pBase
148807** contains a USING clause, or if none of the USING clauses contain zName,
148808** then return false.
148809*/
148810static int inAnyUsingClause(
148811  const char *zName, /* Name we are looking for */
148812  SrcItem *pBase,    /* The base SrcItem.  Looking at pBase[1] and following */
148813  int N              /* How many SrcItems to check */
148814){
148815  while( N>0 ){
148816    N--;
148817    pBase++;
148818    if( pBase->fg.isUsing==0 ) continue;
148819    if( NEVER(pBase->u3.pUsing==0) ) continue;
148820    if( sqlite3IdListIndex(pBase->u3.pUsing, zName)>=0 ) return 1;
148821  }
148822  return 0;
148823}
148824
148825
148826/*
148827** This routine is a Walker callback for "expanding" a SELECT statement.
148828** "Expanding" means to do the following:
148829**
148830**    (1)  Make sure VDBE cursor numbers have been assigned to every
148831**         element of the FROM clause.
148832**
148833**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
148834**         defines FROM clause.  When views appear in the FROM clause,
148835**         fill pTabList->a[].pSelect with a copy of the SELECT statement
148836**         that implements the view.  A copy is made of the view's SELECT
148837**         statement so that we can freely modify or delete that statement
148838**         without worrying about messing up the persistent representation
148839**         of the view.
148840**
148841**    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
148842**         on joins and the ON and USING clause of joins.
148843**
148844**    (4)  Scan the list of columns in the result set (pEList) looking
148845**         for instances of the "*" operator or the TABLE.* operator.
148846**         If found, expand each "*" to be every column in every table
148847**         and TABLE.* to be every column in TABLE.
148848**
148849*/
148850static int selectExpander(Walker *pWalker, Select *p){
148851  Parse *pParse = pWalker->pParse;
148852  int i, j, k, rc;
148853  SrcList *pTabList;
148854  ExprList *pEList;
148855  SrcItem *pFrom;
148856  sqlite3 *db = pParse->db;
148857  Expr *pE, *pRight, *pExpr;
148858  u16 selFlags = p->selFlags;
148859  u32 elistFlags = 0;
148860
148861  p->selFlags |= SF_Expanded;
148862  if( db->mallocFailed  ){
148863    return WRC_Abort;
148864  }
148865  assert( p->pSrc!=0 );
148866  if( (selFlags & SF_Expanded)!=0 ){
148867    return WRC_Prune;
148868  }
148869  if( pWalker->eCode ){
148870    /* Renumber selId because it has been copied from a view */
148871    p->selId = ++pParse->nSelect;
148872  }
148873  pTabList = p->pSrc;
148874  pEList = p->pEList;
148875  if( pParse->pWith && (p->selFlags & SF_View) ){
148876    if( p->pWith==0 ){
148877      p->pWith = (With*)sqlite3DbMallocZero(db, sizeof(With));
148878      if( p->pWith==0 ){
148879        return WRC_Abort;
148880      }
148881    }
148882    p->pWith->bView = 1;
148883  }
148884  sqlite3WithPush(pParse, p->pWith, 0);
148885
148886  /* Make sure cursor numbers have been assigned to all entries in
148887  ** the FROM clause of the SELECT statement.
148888  */
148889  sqlite3SrcListAssignCursors(pParse, pTabList);
148890
148891  /* Look up every table named in the FROM clause of the select.  If
148892  ** an entry of the FROM clause is a subquery instead of a table or view,
148893  ** then create a transient table structure to describe the subquery.
148894  */
148895  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
148896    Table *pTab;
148897    assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
148898    if( pFrom->pTab ) continue;
148899    assert( pFrom->fg.isRecursive==0 );
148900    if( pFrom->zName==0 ){
148901#ifndef SQLITE_OMIT_SUBQUERY
148902      Select *pSel = pFrom->pSelect;
148903      /* A sub-query in the FROM clause of a SELECT */
148904      assert( pSel!=0 );
148905      assert( pFrom->pTab==0 );
148906      if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
148907      if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
148908#endif
148909#ifndef SQLITE_OMIT_CTE
148910    }else if( (rc = resolveFromTermToCte(pParse, pWalker, pFrom))!=0 ){
148911      if( rc>1 ) return WRC_Abort;
148912      pTab = pFrom->pTab;
148913      assert( pTab!=0 );
148914#endif
148915    }else{
148916      /* An ordinary table or view name in the FROM clause */
148917      assert( pFrom->pTab==0 );
148918      pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
148919      if( pTab==0 ) return WRC_Abort;
148920      if( pTab->nTabRef>=0xffff ){
148921        sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
148922           pTab->zName);
148923        pFrom->pTab = 0;
148924        return WRC_Abort;
148925      }
148926      pTab->nTabRef++;
148927      if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
148928        return WRC_Abort;
148929      }
148930#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
148931      if( !IsOrdinaryTable(pTab) ){
148932        i16 nCol;
148933        u8 eCodeOrig = pWalker->eCode;
148934        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
148935        assert( pFrom->pSelect==0 );
148936        if( IsView(pTab) ){
148937          if( (db->flags & SQLITE_EnableView)==0
148938           && pTab->pSchema!=db->aDb[1].pSchema
148939          ){
148940            sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
148941              pTab->zName);
148942          }
148943          pFrom->pSelect = sqlite3SelectDup(db, pTab->u.view.pSelect, 0);
148944        }
148945#ifndef SQLITE_OMIT_VIRTUALTABLE
148946        else if( ALWAYS(IsVirtual(pTab))
148947         && pFrom->fg.fromDDL
148948         && ALWAYS(pTab->u.vtab.p!=0)
148949         && pTab->u.vtab.p->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
148950        ){
148951          sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
148952                                  pTab->zName);
148953        }
148954        assert( SQLITE_VTABRISK_Normal==1 && SQLITE_VTABRISK_High==2 );
148955#endif
148956        nCol = pTab->nCol;
148957        pTab->nCol = -1;
148958        pWalker->eCode = 1;  /* Turn on Select.selId renumbering */
148959        sqlite3WalkSelect(pWalker, pFrom->pSelect);
148960        pWalker->eCode = eCodeOrig;
148961        pTab->nCol = nCol;
148962      }
148963#endif
148964    }
148965
148966    /* Locate the index named by the INDEXED BY clause, if any. */
148967    if( pFrom->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pFrom) ){
148968      return WRC_Abort;
148969    }
148970  }
148971
148972  /* Process NATURAL keywords, and ON and USING clauses of joins.
148973  */
148974  assert( db->mallocFailed==0 || pParse->nErr!=0 );
148975  if( pParse->nErr || sqlite3ProcessJoin(pParse, p) ){
148976    return WRC_Abort;
148977  }
148978
148979  /* For every "*" that occurs in the column list, insert the names of
148980  ** all columns in all tables.  And for every TABLE.* insert the names
148981  ** of all columns in TABLE.  The parser inserted a special expression
148982  ** with the TK_ASTERISK operator for each "*" that it found in the column
148983  ** list.  The following code just has to locate the TK_ASTERISK
148984  ** expressions and expand each one to the list of all columns in
148985  ** all tables.
148986  **
148987  ** The first loop just checks to see if there are any "*" operators
148988  ** that need expanding.
148989  */
148990  for(k=0; k<pEList->nExpr; k++){
148991    pE = pEList->a[k].pExpr;
148992    if( pE->op==TK_ASTERISK ) break;
148993    assert( pE->op!=TK_DOT || pE->pRight!=0 );
148994    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
148995    if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
148996    elistFlags |= pE->flags;
148997  }
148998  if( k<pEList->nExpr ){
148999    /*
149000    ** If we get here it means the result set contains one or more "*"
149001    ** operators that need to be expanded.  Loop through each expression
149002    ** in the result set and expand them one by one.
149003    */
149004    struct ExprList_item *a = pEList->a;
149005    ExprList *pNew = 0;
149006    int flags = pParse->db->flags;
149007    int longNames = (flags & SQLITE_FullColNames)!=0
149008                      && (flags & SQLITE_ShortColNames)==0;
149009
149010    for(k=0; k<pEList->nExpr; k++){
149011      pE = a[k].pExpr;
149012      elistFlags |= pE->flags;
149013      pRight = pE->pRight;
149014      assert( pE->op!=TK_DOT || pRight!=0 );
149015      if( pE->op!=TK_ASTERISK
149016       && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
149017      ){
149018        /* This particular expression does not need to be expanded.
149019        */
149020        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
149021        if( pNew ){
149022          pNew->a[pNew->nExpr-1].zEName = a[k].zEName;
149023          pNew->a[pNew->nExpr-1].fg.eEName = a[k].fg.eEName;
149024          a[k].zEName = 0;
149025        }
149026        a[k].pExpr = 0;
149027      }else{
149028        /* This expression is a "*" or a "TABLE.*" and needs to be
149029        ** expanded. */
149030        int tableSeen = 0;      /* Set to 1 when TABLE matches */
149031        char *zTName = 0;       /* text of name of TABLE */
149032        int iErrOfst;
149033        if( pE->op==TK_DOT ){
149034          assert( (selFlags & SF_NestedFrom)==0 );
149035          assert( pE->pLeft!=0 );
149036          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
149037          zTName = pE->pLeft->u.zToken;
149038          assert( ExprUseWOfst(pE->pLeft) );
149039          iErrOfst = pE->pRight->w.iOfst;
149040        }else{
149041          assert( ExprUseWOfst(pE) );
149042          iErrOfst = pE->w.iOfst;
149043        }
149044        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
149045          int nAdd;                    /* Number of cols including rowid */
149046          Table *pTab = pFrom->pTab;   /* Table for this data source */
149047          ExprList *pNestedFrom;       /* Result-set of a nested FROM clause */
149048          char *zTabName;              /* AS name for this data source */
149049          const char *zSchemaName = 0; /* Schema name for this data source */
149050          int iDb;                     /* Schema index for this data src */
149051          IdList *pUsing;              /* USING clause for pFrom[1] */
149052
149053          if( (zTabName = pFrom->zAlias)==0 ){
149054            zTabName = pTab->zName;
149055          }
149056          if( db->mallocFailed ) break;
149057          assert( (int)pFrom->fg.isNestedFrom == IsNestedFrom(pFrom->pSelect) );
149058          if( pFrom->fg.isNestedFrom ){
149059            assert( pFrom->pSelect!=0 );
149060            pNestedFrom = pFrom->pSelect->pEList;
149061            assert( pNestedFrom!=0 );
149062            assert( pNestedFrom->nExpr==pTab->nCol );
149063            assert( VisibleRowid(pTab)==0 || ViewCanHaveRowid );
149064          }else{
149065            if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
149066              continue;
149067            }
149068            pNestedFrom = 0;
149069            iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
149070            zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
149071          }
149072          if( i+1<pTabList->nSrc
149073           && pFrom[1].fg.isUsing
149074           && (selFlags & SF_NestedFrom)!=0
149075          ){
149076            int ii;
149077            pUsing = pFrom[1].u3.pUsing;
149078            for(ii=0; ii<pUsing->nId; ii++){
149079              const char *zUName = pUsing->a[ii].zName;
149080              pRight = sqlite3Expr(db, TK_ID, zUName);
149081              sqlite3ExprSetErrorOffset(pRight, iErrOfst);
149082              pNew = sqlite3ExprListAppend(pParse, pNew, pRight);
149083              if( pNew ){
149084                struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
149085                assert( pX->zEName==0 );
149086                pX->zEName = sqlite3MPrintf(db,"..%s", zUName);
149087                pX->fg.eEName = ENAME_TAB;
149088                pX->fg.bUsingTerm = 1;
149089              }
149090            }
149091          }else{
149092            pUsing = 0;
149093          }
149094
149095          nAdd = pTab->nCol;
149096          if( VisibleRowid(pTab) && (selFlags & SF_NestedFrom)!=0 ) nAdd++;
149097          for(j=0; j<nAdd; j++){
149098            const char *zName;
149099            struct ExprList_item *pX; /* Newly added ExprList term */
149100
149101            if( j==pTab->nCol ){
149102              zName = sqlite3RowidAlias(pTab);
149103              if( zName==0 ) continue;
149104            }else{
149105              zName = pTab->aCol[j].zCnName;
149106
149107              /* If pTab is actually an SF_NestedFrom sub-select, do not
149108              ** expand any ENAME_ROWID columns.  */
149109              if( pNestedFrom && pNestedFrom->a[j].fg.eEName==ENAME_ROWID ){
149110                continue;
149111              }
149112
149113              if( zTName
149114               && pNestedFrom
149115               && sqlite3MatchEName(&pNestedFrom->a[j], 0, zTName, 0, 0)==0
149116              ){
149117                continue;
149118              }
149119
149120              /* If a column is marked as 'hidden', omit it from the expanded
149121              ** result-set list unless the SELECT has the SF_IncludeHidden
149122              ** bit set.
149123              */
149124              if( (p->selFlags & SF_IncludeHidden)==0
149125                && IsHiddenColumn(&pTab->aCol[j])
149126              ){
149127                continue;
149128              }
149129              if( (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
149130               && zTName==0
149131               && (selFlags & (SF_NestedFrom))==0
149132              ){
149133                continue;
149134              }
149135            }
149136            assert( zName );
149137            tableSeen = 1;
149138
149139            if( i>0 && zTName==0 && (selFlags & SF_NestedFrom)==0 ){
149140              if( pFrom->fg.isUsing
149141               && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0
149142              ){
149143                /* In a join with a USING clause, omit columns in the
149144                ** using clause from the table on the right. */
149145                continue;
149146              }
149147            }
149148            pRight = sqlite3Expr(db, TK_ID, zName);
149149            if( (pTabList->nSrc>1
149150                 && (  (pFrom->fg.jointype & JT_LTORJ)==0
149151                     || (selFlags & SF_NestedFrom)!=0
149152                     || !inAnyUsingClause(zName,pFrom,pTabList->nSrc-i-1)
149153                    )
149154                )
149155             || IN_RENAME_OBJECT
149156            ){
149157              Expr *pLeft;
149158              pLeft = sqlite3Expr(db, TK_ID, zTabName);
149159              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
149160              if( IN_RENAME_OBJECT && pE->pLeft ){
149161                sqlite3RenameTokenRemap(pParse, pLeft, pE->pLeft);
149162              }
149163              if( zSchemaName ){
149164                pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
149165                pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
149166              }
149167            }else{
149168              pExpr = pRight;
149169            }
149170            sqlite3ExprSetErrorOffset(pExpr, iErrOfst);
149171            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
149172            if( pNew==0 ){
149173              break;  /* OOM */
149174            }
149175            pX = &pNew->a[pNew->nExpr-1];
149176            assert( pX->zEName==0 );
149177            if( (selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){
149178              if( pNestedFrom && (!ViewCanHaveRowid || j<pNestedFrom->nExpr) ){
149179                assert( j<pNestedFrom->nExpr );
149180                pX->zEName = sqlite3DbStrDup(db, pNestedFrom->a[j].zEName);
149181                testcase( pX->zEName==0 );
149182              }else{
149183                pX->zEName = sqlite3MPrintf(db, "%s.%s.%s",
149184                                           zSchemaName, zTabName, zName);
149185                testcase( pX->zEName==0 );
149186              }
149187              pX->fg.eEName = (j==pTab->nCol ? ENAME_ROWID : ENAME_TAB);
149188              if( (pFrom->fg.isUsing
149189                   && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0)
149190               || (pUsing && sqlite3IdListIndex(pUsing, zName)>=0)
149191               || (j<pTab->nCol && (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND))
149192              ){
149193                pX->fg.bNoExpand = 1;
149194              }
149195            }else if( longNames ){
149196              pX->zEName = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
149197              pX->fg.eEName = ENAME_NAME;
149198            }else{
149199              pX->zEName = sqlite3DbStrDup(db, zName);
149200              pX->fg.eEName = ENAME_NAME;
149201            }
149202          }
149203        }
149204        if( !tableSeen ){
149205          if( zTName ){
149206            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
149207          }else{
149208            sqlite3ErrorMsg(pParse, "no tables specified");
149209          }
149210        }
149211      }
149212    }
149213    sqlite3ExprListDelete(db, pEList);
149214    p->pEList = pNew;
149215  }
149216  if( p->pEList ){
149217    if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
149218      sqlite3ErrorMsg(pParse, "too many columns in result set");
149219      return WRC_Abort;
149220    }
149221    if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
149222      p->selFlags |= SF_ComplexResult;
149223    }
149224  }
149225#if TREETRACE_ENABLED
149226  if( sqlite3TreeTrace & 0x8 ){
149227    TREETRACE(0x8,pParse,p,("After result-set wildcard expansion:\n"));
149228    sqlite3TreeViewSelect(0, p, 0);
149229  }
149230#endif
149231  return WRC_Continue;
149232}
149233
149234#if SQLITE_DEBUG
149235/*
149236** Always assert.  This xSelectCallback2 implementation proves that the
149237** xSelectCallback2 is never invoked.
149238*/
149239SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
149240  UNUSED_PARAMETER2(NotUsed, NotUsed2);
149241  assert( 0 );
149242}
149243#endif
149244/*
149245** This routine "expands" a SELECT statement and all of its subqueries.
149246** For additional information on what it means to "expand" a SELECT
149247** statement, see the comment on the selectExpand worker callback above.
149248**
149249** Expanding a SELECT statement is the first step in processing a
149250** SELECT statement.  The SELECT statement must be expanded before
149251** name resolution is performed.
149252**
149253** If anything goes wrong, an error message is written into pParse.
149254** The calling function can detect the problem by looking at pParse->nErr
149255** and/or pParse->db->mallocFailed.
149256*/
149257static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
149258  Walker w;
149259  w.xExprCallback = sqlite3ExprWalkNoop;
149260  w.pParse = pParse;
149261  if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
149262    w.xSelectCallback = convertCompoundSelectToSubquery;
149263    w.xSelectCallback2 = 0;
149264    sqlite3WalkSelect(&w, pSelect);
149265  }
149266  w.xSelectCallback = selectExpander;
149267  w.xSelectCallback2 = sqlite3SelectPopWith;
149268  w.eCode = 0;
149269  sqlite3WalkSelect(&w, pSelect);
149270}
149271
149272
149273#ifndef SQLITE_OMIT_SUBQUERY
149274/*
149275** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
149276** interface.
149277**
149278** For each FROM-clause subquery, add Column.zType, Column.zColl, and
149279** Column.affinity information to the Table structure that represents
149280** the result set of that subquery.
149281**
149282** The Table structure that represents the result set was constructed
149283** by selectExpander() but the type and collation and affinity information
149284** was omitted at that point because identifiers had not yet been resolved.
149285** This routine is called after identifier resolution.
149286*/
149287static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
149288  Parse *pParse;
149289  int i;
149290  SrcList *pTabList;
149291  SrcItem *pFrom;
149292
149293  if( p->selFlags & SF_HasTypeInfo ) return;
149294  p->selFlags |= SF_HasTypeInfo;
149295  pParse = pWalker->pParse;
149296  assert( (p->selFlags & SF_Resolved) );
149297  pTabList = p->pSrc;
149298  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
149299    Table *pTab = pFrom->pTab;
149300    assert( pTab!=0 );
149301    if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
149302      /* A sub-query in the FROM clause of a SELECT */
149303      Select *pSel = pFrom->pSelect;
149304      if( pSel ){
149305        sqlite3SubqueryColumnTypes(pParse, pTab, pSel, SQLITE_AFF_NONE);
149306      }
149307    }
149308  }
149309}
149310#endif
149311
149312
149313/*
149314** This routine adds datatype and collating sequence information to
149315** the Table structures of all FROM-clause subqueries in a
149316** SELECT statement.
149317**
149318** Use this routine after name resolution.
149319*/
149320static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
149321#ifndef SQLITE_OMIT_SUBQUERY
149322  Walker w;
149323  w.xSelectCallback = sqlite3SelectWalkNoop;
149324  w.xSelectCallback2 = selectAddSubqueryTypeInfo;
149325  w.xExprCallback = sqlite3ExprWalkNoop;
149326  w.pParse = pParse;
149327  sqlite3WalkSelect(&w, pSelect);
149328#endif
149329}
149330
149331
149332/*
149333** This routine sets up a SELECT statement for processing.  The
149334** following is accomplished:
149335**
149336**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
149337**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
149338**     *  ON and USING clauses are shifted into WHERE statements
149339**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
149340**     *  Identifiers in expression are matched to tables.
149341**
149342** This routine acts recursively on all subqueries within the SELECT.
149343*/
149344SQLITE_PRIVATE void sqlite3SelectPrep(
149345  Parse *pParse,         /* The parser context */
149346  Select *p,             /* The SELECT statement being coded. */
149347  NameContext *pOuterNC  /* Name context for container */
149348){
149349  assert( p!=0 || pParse->db->mallocFailed );
149350  assert( pParse->db->pParse==pParse );
149351  if( pParse->db->mallocFailed ) return;
149352  if( p->selFlags & SF_HasTypeInfo ) return;
149353  sqlite3SelectExpand(pParse, p);
149354  if( pParse->nErr ) return;
149355  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
149356  if( pParse->nErr ) return;
149357  sqlite3SelectAddTypeInfo(pParse, p);
149358}
149359
149360#if TREETRACE_ENABLED
149361/*
149362** Display all information about an AggInfo object
149363*/
149364static void printAggInfo(AggInfo *pAggInfo){
149365  int ii;
149366  sqlite3DebugPrintf("AggInfo %d/%p:\n",
149367     pAggInfo->selId, pAggInfo);
149368  for(ii=0; ii<pAggInfo->nColumn; ii++){
149369    struct AggInfo_col *pCol = &pAggInfo->aCol[ii];
149370    sqlite3DebugPrintf(
149371       "agg-column[%d] pTab=%s iTable=%d iColumn=%d iMem=%d"
149372       " iSorterColumn=%d %s\n",
149373       ii, pCol->pTab ? pCol->pTab->zName : "NULL",
149374       pCol->iTable, pCol->iColumn, pAggInfo->iFirstReg+ii,
149375       pCol->iSorterColumn,
149376       ii>=pAggInfo->nAccumulator ? "" : " Accumulator");
149377    sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pCExpr, 0);
149378  }
149379  for(ii=0; ii<pAggInfo->nFunc; ii++){
149380    sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
149381        ii, pAggInfo->iFirstReg+pAggInfo->nColumn+ii);
149382    sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pFExpr, 0);
149383  }
149384}
149385#endif /* TREETRACE_ENABLED */
149386
149387/*
149388** Analyze the arguments to aggregate functions.  Create new pAggInfo->aCol[]
149389** entries for columns that are arguments to aggregate functions but which
149390** are not otherwise used.
149391**
149392** The aCol[] entries in AggInfo prior to nAccumulator are columns that
149393** are referenced outside of aggregate functions.  These might be columns
149394** that are part of the GROUP by clause, for example.  Other database engines
149395** would throw an error if there is a column reference that is not in the
149396** GROUP BY clause and that is not part of an aggregate function argument.
149397** But SQLite allows this.
149398**
149399** The aCol[] entries beginning with the aCol[nAccumulator] and following
149400** are column references that are used exclusively as arguments to
149401** aggregate functions.  This routine is responsible for computing
149402** (or recomputing) those aCol[] entries.
149403*/
149404static void analyzeAggFuncArgs(
149405  AggInfo *pAggInfo,
149406  NameContext *pNC
149407){
149408  int i;
149409  assert( pAggInfo!=0 );
149410  assert( pAggInfo->iFirstReg==0 );
149411  pNC->ncFlags |= NC_InAggFunc;
149412  for(i=0; i<pAggInfo->nFunc; i++){
149413    Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
149414    assert( pExpr->op==TK_FUNCTION || pExpr->op==TK_AGG_FUNCTION );
149415    assert( ExprUseXList(pExpr) );
149416    sqlite3ExprAnalyzeAggList(pNC, pExpr->x.pList);
149417    if( pExpr->pLeft ){
149418      assert( pExpr->pLeft->op==TK_ORDER );
149419      assert( ExprUseXList(pExpr->pLeft) );
149420      sqlite3ExprAnalyzeAggList(pNC, pExpr->pLeft->x.pList);
149421    }
149422#ifndef SQLITE_OMIT_WINDOWFUNC
149423    assert( !IsWindowFunc(pExpr) );
149424    if( ExprHasProperty(pExpr, EP_WinFunc) ){
149425      sqlite3ExprAnalyzeAggregates(pNC, pExpr->y.pWin->pFilter);
149426    }
149427#endif
149428  }
149429  pNC->ncFlags &= ~NC_InAggFunc;
149430}
149431
149432/*
149433** An index on expressions is being used in the inner loop of an
149434** aggregate query with a GROUP BY clause.  This routine attempts
149435** to adjust the AggInfo object to take advantage of index and to
149436** perhaps use the index as a covering index.
149437**
149438*/
149439static void optimizeAggregateUseOfIndexedExpr(
149440  Parse *pParse,          /* Parsing context */
149441  Select *pSelect,        /* The SELECT statement being processed */
149442  AggInfo *pAggInfo,      /* The aggregate info */
149443  NameContext *pNC        /* Name context used to resolve agg-func args */
149444){
149445  assert( pAggInfo->iFirstReg==0 );
149446  assert( pSelect!=0 );
149447  assert( pSelect->pGroupBy!=0 );
149448  pAggInfo->nColumn = pAggInfo->nAccumulator;
149449  if( ALWAYS(pAggInfo->nSortingColumn>0) ){
149450    int mx = pSelect->pGroupBy->nExpr - 1;
149451    int j, k;
149452    for(j=0; j<pAggInfo->nColumn; j++){
149453      k = pAggInfo->aCol[j].iSorterColumn;
149454      if( k>mx ) mx = k;
149455    }
149456    pAggInfo->nSortingColumn = mx+1;
149457  }
149458  analyzeAggFuncArgs(pAggInfo, pNC);
149459#if TREETRACE_ENABLED
149460  if( sqlite3TreeTrace & 0x20 ){
149461    IndexedExpr *pIEpr;
149462    TREETRACE(0x20, pParse, pSelect,
149463        ("AggInfo (possibly) adjusted for Indexed Exprs\n"));
149464    sqlite3TreeViewSelect(0, pSelect, 0);
149465    for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
149466      printf("data-cursor=%d index={%d,%d}\n",
149467          pIEpr->iDataCur, pIEpr->iIdxCur, pIEpr->iIdxCol);
149468      sqlite3TreeViewExpr(0, pIEpr->pExpr, 0);
149469    }
149470    printAggInfo(pAggInfo);
149471  }
149472#else
149473  UNUSED_PARAMETER(pSelect);
149474  UNUSED_PARAMETER(pParse);
149475#endif
149476}
149477
149478/*
149479** Walker callback for aggregateConvertIndexedExprRefToColumn().
149480*/
149481static int aggregateIdxEprRefToColCallback(Walker *pWalker, Expr *pExpr){
149482  AggInfo *pAggInfo;
149483  struct AggInfo_col *pCol;
149484  UNUSED_PARAMETER(pWalker);
149485  if( pExpr->pAggInfo==0 ) return WRC_Continue;
149486  if( pExpr->op==TK_AGG_COLUMN ) return WRC_Continue;
149487  if( pExpr->op==TK_AGG_FUNCTION ) return WRC_Continue;
149488  if( pExpr->op==TK_IF_NULL_ROW ) return WRC_Continue;
149489  pAggInfo = pExpr->pAggInfo;
149490  if( NEVER(pExpr->iAgg>=pAggInfo->nColumn) ) return WRC_Continue;
149491  assert( pExpr->iAgg>=0 );
149492  pCol = &pAggInfo->aCol[pExpr->iAgg];
149493  pExpr->op = TK_AGG_COLUMN;
149494  pExpr->iTable = pCol->iTable;
149495  pExpr->iColumn = pCol->iColumn;
149496  ExprClearProperty(pExpr, EP_Skip|EP_Collate|EP_Unlikely);
149497  return WRC_Prune;
149498}
149499
149500/*
149501** Convert every pAggInfo->aFunc[].pExpr such that any node within
149502** those expressions that has pAppInfo set is changed into a TK_AGG_COLUMN
149503** opcode.
149504*/
149505static void aggregateConvertIndexedExprRefToColumn(AggInfo *pAggInfo){
149506  int i;
149507  Walker w;
149508  memset(&w, 0, sizeof(w));
149509  w.xExprCallback = aggregateIdxEprRefToColCallback;
149510  for(i=0; i<pAggInfo->nFunc; i++){
149511    sqlite3WalkExpr(&w, pAggInfo->aFunc[i].pFExpr);
149512  }
149513}
149514
149515
149516/*
149517** Allocate a block of registers so that there is one register for each
149518** pAggInfo->aCol[] and pAggInfo->aFunc[] entry in pAggInfo.  The first
149519** register in this block is stored in pAggInfo->iFirstReg.
149520**
149521** This routine may only be called once for each AggInfo object.  Prior
149522** to calling this routine:
149523**
149524**     *  The aCol[] and aFunc[] arrays may be modified
149525**     *  The AggInfoColumnReg() and AggInfoFuncReg() macros may not be used
149526**
149527** After calling this routine:
149528**
149529**     *  The aCol[] and aFunc[] arrays are fixed
149530**     *  The AggInfoColumnReg() and AggInfoFuncReg() macros may be used
149531**
149532*/
149533static void assignAggregateRegisters(Parse *pParse, AggInfo *pAggInfo){
149534  assert( pAggInfo!=0 );
149535  assert( pAggInfo->iFirstReg==0 );
149536  pAggInfo->iFirstReg = pParse->nMem + 1;
149537  pParse->nMem += pAggInfo->nColumn + pAggInfo->nFunc;
149538}
149539
149540/*
149541** Reset the aggregate accumulator.
149542**
149543** The aggregate accumulator is a set of memory cells that hold
149544** intermediate results while calculating an aggregate.  This
149545** routine generates code that stores NULLs in all of those memory
149546** cells.
149547*/
149548static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
149549  Vdbe *v = pParse->pVdbe;
149550  int i;
149551  struct AggInfo_func *pFunc;
149552  int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
149553  assert( pAggInfo->iFirstReg>0 );
149554  assert( pParse->db->pParse==pParse );
149555  assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
149556  if( nReg==0 ) return;
149557  if( pParse->nErr ) return;
149558  sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->iFirstReg,
149559                    pAggInfo->iFirstReg+nReg-1);
149560  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
149561    if( pFunc->iDistinct>=0 ){
149562      Expr *pE = pFunc->pFExpr;
149563      assert( ExprUseXList(pE) );
149564      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
149565        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
149566           "argument");
149567        pFunc->iDistinct = -1;
149568      }else{
149569        KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
149570        pFunc->iDistAddr = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
149571            pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO);
149572        ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(DISTINCT)",
149573                          pFunc->pFunc->zName));
149574      }
149575    }
149576    if( pFunc->iOBTab>=0 ){
149577      ExprList *pOBList;
149578      KeyInfo *pKeyInfo;
149579      int nExtra = 0;
149580      assert( pFunc->pFExpr->pLeft!=0 );
149581      assert( pFunc->pFExpr->pLeft->op==TK_ORDER );
149582      assert( ExprUseXList(pFunc->pFExpr->pLeft) );
149583      assert( pFunc->pFunc!=0 );
149584      pOBList = pFunc->pFExpr->pLeft->x.pList;
149585      if( !pFunc->bOBUnique ){
149586        nExtra++;  /* One extra column for the OP_Sequence */
149587      }
149588      if( pFunc->bOBPayload ){
149589        /* extra columns for the function arguments */
149590        assert( ExprUseXList(pFunc->pFExpr) );
149591        nExtra += pFunc->pFExpr->x.pList->nExpr;
149592      }
149593      if( pFunc->bUseSubtype ){
149594        nExtra += pFunc->pFExpr->x.pList->nExpr;
149595      }
149596      pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOBList, 0, nExtra);
149597      if( !pFunc->bOBUnique && pParse->nErr==0 ){
149598        pKeyInfo->nKeyField++;
149599      }
149600      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
149601            pFunc->iOBTab, pOBList->nExpr+nExtra, 0,
149602            (char*)pKeyInfo, P4_KEYINFO);
149603      ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(ORDER BY)",
149604                          pFunc->pFunc->zName));
149605    }
149606  }
149607}
149608
149609/*
149610** Invoke the OP_AggFinalize opcode for every aggregate function
149611** in the AggInfo structure.
149612*/
149613static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
149614  Vdbe *v = pParse->pVdbe;
149615  int i;
149616  struct AggInfo_func *pF;
149617  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
149618    ExprList *pList;
149619    assert( ExprUseXList(pF->pFExpr) );
149620    pList = pF->pFExpr->x.pList;
149621    if( pF->iOBTab>=0 ){
149622      /* For an ORDER BY aggregate, calls to OP_AggStep were deferred.  Inputs
149623      ** were stored in emphermal table pF->iOBTab.  Here, we extract those
149624      ** inputs (in ORDER BY order) and make all calls to OP_AggStep
149625      ** before doing the OP_AggFinal call. */
149626      int iTop;        /* Start of loop for extracting columns */
149627      int nArg;        /* Number of columns to extract */
149628      int nKey;        /* Key columns to be skipped */
149629      int regAgg;      /* Extract into this array */
149630      int j;           /* Loop counter */
149631
149632      assert( pF->pFunc!=0 );
149633      nArg = pList->nExpr;
149634      regAgg = sqlite3GetTempRange(pParse, nArg);
149635
149636      if( pF->bOBPayload==0 ){
149637        nKey = 0;
149638      }else{
149639        assert( pF->pFExpr->pLeft!=0 );
149640        assert( ExprUseXList(pF->pFExpr->pLeft) );
149641        assert( pF->pFExpr->pLeft->x.pList!=0 );
149642        nKey = pF->pFExpr->pLeft->x.pList->nExpr;
149643        if( ALWAYS(!pF->bOBUnique) ) nKey++;
149644      }
149645      iTop = sqlite3VdbeAddOp1(v, OP_Rewind, pF->iOBTab); VdbeCoverage(v);
149646      for(j=nArg-1; j>=0; j--){
149647        sqlite3VdbeAddOp3(v, OP_Column, pF->iOBTab, nKey+j, regAgg+j);
149648      }
149649      if( pF->bUseSubtype ){
149650        int regSubtype = sqlite3GetTempReg(pParse);
149651        int iBaseCol = nKey + nArg + (pF->bOBPayload==0 && pF->bOBUnique==0);
149652        for(j=nArg-1; j>=0; j--){
149653          sqlite3VdbeAddOp3(v, OP_Column, pF->iOBTab, iBaseCol+j, regSubtype);
149654          sqlite3VdbeAddOp2(v, OP_SetSubtype, regSubtype, regAgg+j);
149655        }
149656        sqlite3ReleaseTempReg(pParse, regSubtype);
149657      }
149658      sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i));
149659      sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
149660      sqlite3VdbeChangeP5(v, (u8)nArg);
149661      sqlite3VdbeAddOp2(v, OP_Next, pF->iOBTab, iTop+1); VdbeCoverage(v);
149662      sqlite3VdbeJumpHere(v, iTop);
149663      sqlite3ReleaseTempRange(pParse, regAgg, nArg);
149664    }
149665    sqlite3VdbeAddOp2(v, OP_AggFinal, AggInfoFuncReg(pAggInfo,i),
149666                      pList ? pList->nExpr : 0);
149667    sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
149668  }
149669}
149670
149671/*
149672** Generate code that will update the accumulator memory cells for an
149673** aggregate based on the current cursor position.
149674**
149675** If regAcc is non-zero and there are no min() or max() aggregates
149676** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
149677** registers if register regAcc contains 0. The caller will take care
149678** of setting and clearing regAcc.
149679**
149680** For an ORDER BY aggregate, the actual accumulator memory cell update
149681** is deferred until after all input rows have been received, so that they
149682** can be run in the requested order.  In that case, instead of invoking
149683** OP_AggStep to update the accumulator, just add the arguments that would
149684** have been passed into OP_AggStep into the sorting ephemeral table
149685** (along with the appropriate sort key).
149686*/
149687static void updateAccumulator(
149688  Parse *pParse,
149689  int regAcc,
149690  AggInfo *pAggInfo,
149691  int eDistinctType
149692){
149693  Vdbe *v = pParse->pVdbe;
149694  int i;
149695  int regHit = 0;
149696  int addrHitTest = 0;
149697  struct AggInfo_func *pF;
149698  struct AggInfo_col *pC;
149699
149700  assert( pAggInfo->iFirstReg>0 );
149701  if( pParse->nErr ) return;
149702  pAggInfo->directMode = 1;
149703  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
149704    int nArg;
149705    int addrNext = 0;
149706    int regAgg;
149707    int regAggSz = 0;
149708    int regDistinct = 0;
149709    ExprList *pList;
149710    assert( ExprUseXList(pF->pFExpr) );
149711    assert( !IsWindowFunc(pF->pFExpr) );
149712    assert( pF->pFunc!=0 );
149713    pList = pF->pFExpr->x.pList;
149714    if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){
149715      Expr *pFilter = pF->pFExpr->y.pWin->pFilter;
149716      if( pAggInfo->nAccumulator
149717       && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
149718       && regAcc
149719      ){
149720        /* If regAcc==0, there there exists some min() or max() function
149721        ** without a FILTER clause that will ensure the magnet registers
149722        ** are populated. */
149723        if( regHit==0 ) regHit = ++pParse->nMem;
149724        /* If this is the first row of the group (regAcc contains 0), clear the
149725        ** "magnet" register regHit so that the accumulator registers
149726        ** are populated if the FILTER clause jumps over the the
149727        ** invocation of min() or max() altogether. Or, if this is not
149728        ** the first row (regAcc contains 1), set the magnet register so that
149729        ** the accumulators are not populated unless the min()/max() is invoked
149730        ** and indicates that they should be.  */
149731        sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);
149732      }
149733      addrNext = sqlite3VdbeMakeLabel(pParse);
149734      sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);
149735    }
149736    if( pF->iOBTab>=0 ){
149737      /* Instead of invoking AggStep, we must push the arguments that would
149738      ** have been passed to AggStep onto the sorting table. */
149739      int jj;                /* Registered used so far in building the record */
149740      ExprList *pOBList;     /* The ORDER BY clause */
149741      assert( pList!=0 );
149742      nArg = pList->nExpr;
149743      assert( nArg>0 );
149744      assert( pF->pFExpr->pLeft!=0 );
149745      assert( pF->pFExpr->pLeft->op==TK_ORDER );
149746      assert( ExprUseXList(pF->pFExpr->pLeft) );
149747      pOBList = pF->pFExpr->pLeft->x.pList;
149748      assert( pOBList!=0 );
149749      assert( pOBList->nExpr>0 );
149750      regAggSz = pOBList->nExpr;
149751      if( !pF->bOBUnique ){
149752        regAggSz++;   /* One register for OP_Sequence */
149753      }
149754      if( pF->bOBPayload ){
149755        regAggSz += nArg;
149756      }
149757      if( pF->bUseSubtype ){
149758        regAggSz += nArg;
149759      }
149760      regAggSz++;  /* One extra register to hold result of MakeRecord */
149761      regAgg = sqlite3GetTempRange(pParse, regAggSz);
149762      regDistinct = regAgg;
149763      sqlite3ExprCodeExprList(pParse, pOBList, regAgg, 0, SQLITE_ECEL_DUP);
149764      jj = pOBList->nExpr;
149765      if( !pF->bOBUnique ){
149766        sqlite3VdbeAddOp2(v, OP_Sequence, pF->iOBTab, regAgg+jj);
149767        jj++;
149768      }
149769      if( pF->bOBPayload ){
149770        regDistinct = regAgg+jj;
149771        sqlite3ExprCodeExprList(pParse, pList, regDistinct, 0, SQLITE_ECEL_DUP);
149772        jj += nArg;
149773      }
149774      if( pF->bUseSubtype ){
149775        int kk;
149776        int regBase = pF->bOBPayload ? regDistinct : regAgg;
149777        for(kk=0; kk<nArg; kk++, jj++){
149778          sqlite3VdbeAddOp2(v, OP_GetSubtype, regBase+kk, regAgg+jj);
149779        }
149780      }
149781    }else if( pList ){
149782      nArg = pList->nExpr;
149783      regAgg = sqlite3GetTempRange(pParse, nArg);
149784      regDistinct = regAgg;
149785      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
149786    }else{
149787      nArg = 0;
149788      regAgg = 0;
149789    }
149790    if( pF->iDistinct>=0 && pList ){
149791      if( addrNext==0 ){
149792        addrNext = sqlite3VdbeMakeLabel(pParse);
149793      }
149794      pF->iDistinct = codeDistinct(pParse, eDistinctType,
149795          pF->iDistinct, addrNext, pList, regDistinct);
149796    }
149797    if( pF->iOBTab>=0 ){
149798      /* Insert a new record into the ORDER BY table */
149799      sqlite3VdbeAddOp3(v, OP_MakeRecord, regAgg, regAggSz-1,
149800                        regAgg+regAggSz-1);
149801      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pF->iOBTab, regAgg+regAggSz-1,
149802                           regAgg, regAggSz-1);
149803      sqlite3ReleaseTempRange(pParse, regAgg, regAggSz);
149804    }else{
149805      /* Invoke the AggStep function */
149806      if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
149807        CollSeq *pColl = 0;
149808        struct ExprList_item *pItem;
149809        int j;
149810        assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
149811        for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
149812          pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
149813        }
149814        if( !pColl ){
149815          pColl = pParse->db->pDfltColl;
149816        }
149817        if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
149818        sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0,
149819                         (char *)pColl, P4_COLLSEQ);
149820      }
149821      sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i));
149822      sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
149823      sqlite3VdbeChangeP5(v, (u8)nArg);
149824      sqlite3ReleaseTempRange(pParse, regAgg, nArg);
149825    }
149826    if( addrNext ){
149827      sqlite3VdbeResolveLabel(v, addrNext);
149828    }
149829  }
149830  if( regHit==0 && pAggInfo->nAccumulator ){
149831    regHit = regAcc;
149832  }
149833  if( regHit ){
149834    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
149835  }
149836  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
149837    sqlite3ExprCode(pParse, pC->pCExpr, AggInfoColumnReg(pAggInfo,i));
149838  }
149839
149840  pAggInfo->directMode = 0;
149841  if( addrHitTest ){
149842    sqlite3VdbeJumpHereOrPopInst(v, addrHitTest);
149843  }
149844}
149845
149846/*
149847** Add a single OP_Explain instruction to the VDBE to explain a simple
149848** count(*) query ("SELECT count(*) FROM pTab").
149849*/
149850#ifndef SQLITE_OMIT_EXPLAIN
149851static void explainSimpleCount(
149852  Parse *pParse,                  /* Parse context */
149853  Table *pTab,                    /* Table being queried */
149854  Index *pIdx                     /* Index used to optimize scan, or NULL */
149855){
149856  if( pParse->explain==2 ){
149857    int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
149858    sqlite3VdbeExplain(pParse, 0, "SCAN %s%s%s",
149859        pTab->zName,
149860        bCover ? " USING COVERING INDEX " : "",
149861        bCover ? pIdx->zName : ""
149862    );
149863  }
149864}
149865#else
149866# define explainSimpleCount(a,b,c)
149867#endif
149868
149869/*
149870** sqlite3WalkExpr() callback used by havingToWhere().
149871**
149872** If the node passed to the callback is a TK_AND node, return
149873** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
149874**
149875** Otherwise, return WRC_Prune. In this case, also check if the
149876** sub-expression matches the criteria for being moved to the WHERE
149877** clause. If so, add it to the WHERE clause and replace the sub-expression
149878** within the HAVING expression with a constant "1".
149879*/
149880static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
149881  if( pExpr->op!=TK_AND ){
149882    Select *pS = pWalker->u.pSelect;
149883    /* This routine is called before the HAVING clause of the current
149884    ** SELECT is analyzed for aggregates. So if pExpr->pAggInfo is set
149885    ** here, it indicates that the expression is a correlated reference to a
149886    ** column from an outer aggregate query, or an aggregate function that
149887    ** belongs to an outer query. Do not move the expression to the WHERE
149888    ** clause in this obscure case, as doing so may corrupt the outer Select
149889    ** statements AggInfo structure.  */
149890    if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy)
149891     && ExprAlwaysFalse(pExpr)==0
149892     && pExpr->pAggInfo==0
149893    ){
149894      sqlite3 *db = pWalker->pParse->db;
149895      Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1");
149896      if( pNew ){
149897        Expr *pWhere = pS->pWhere;
149898        SWAP(Expr, *pNew, *pExpr);
149899        pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
149900        pS->pWhere = pNew;
149901        pWalker->eCode = 1;
149902      }
149903    }
149904    return WRC_Prune;
149905  }
149906  return WRC_Continue;
149907}
149908
149909/*
149910** Transfer eligible terms from the HAVING clause of a query, which is
149911** processed after grouping, to the WHERE clause, which is processed before
149912** grouping. For example, the query:
149913**
149914**   SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
149915**
149916** can be rewritten as:
149917**
149918**   SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
149919**
149920** A term of the HAVING expression is eligible for transfer if it consists
149921** entirely of constants and expressions that are also GROUP BY terms that
149922** use the "BINARY" collation sequence.
149923*/
149924static void havingToWhere(Parse *pParse, Select *p){
149925  Walker sWalker;
149926  memset(&sWalker, 0, sizeof(sWalker));
149927  sWalker.pParse = pParse;
149928  sWalker.xExprCallback = havingToWhereExprCb;
149929  sWalker.u.pSelect = p;
149930  sqlite3WalkExpr(&sWalker, p->pHaving);
149931#if TREETRACE_ENABLED
149932  if( sWalker.eCode && (sqlite3TreeTrace & 0x100)!=0 ){
149933    TREETRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
149934    sqlite3TreeViewSelect(0, p, 0);
149935  }
149936#endif
149937}
149938
149939/*
149940** Check to see if the pThis entry of pTabList is a self-join of another view.
149941** Search FROM-clause entries in the range of iFirst..iEnd, including iFirst
149942** but stopping before iEnd.
149943**
149944** If pThis is a self-join, then return the SrcItem for the first other
149945** instance of that view found.  If pThis is not a self-join then return 0.
149946*/
149947static SrcItem *isSelfJoinView(
149948  SrcList *pTabList,           /* Search for self-joins in this FROM clause */
149949  SrcItem *pThis,              /* Search for prior reference to this subquery */
149950  int iFirst, int iEnd        /* Range of FROM-clause entries to search. */
149951){
149952  SrcItem *pItem;
149953  assert( pThis->pSelect!=0 );
149954  if( pThis->pSelect->selFlags & SF_PushDown ) return 0;
149955  while( iFirst<iEnd ){
149956    Select *pS1;
149957    pItem = &pTabList->a[iFirst++];
149958    if( pItem->pSelect==0 ) continue;
149959    if( pItem->fg.viaCoroutine ) continue;
149960    if( pItem->zName==0 ) continue;
149961    assert( pItem->pTab!=0 );
149962    assert( pThis->pTab!=0 );
149963    if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;
149964    if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
149965    pS1 = pItem->pSelect;
149966    if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){
149967      /* The query flattener left two different CTE tables with identical
149968      ** names in the same FROM clause. */
149969      continue;
149970    }
149971    if( pItem->pSelect->selFlags & SF_PushDown ){
149972      /* The view was modified by some other optimization such as
149973      ** pushDownWhereTerms() */
149974      continue;
149975    }
149976    return pItem;
149977  }
149978  return 0;
149979}
149980
149981/*
149982** Deallocate a single AggInfo object
149983*/
149984static void agginfoFree(sqlite3 *db, void *pArg){
149985  AggInfo *p = (AggInfo*)pArg;
149986  sqlite3DbFree(db, p->aCol);
149987  sqlite3DbFree(db, p->aFunc);
149988  sqlite3DbFreeNN(db, p);
149989}
149990
149991/*
149992** Attempt to transform a query of the form
149993**
149994**    SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
149995**
149996** Into this:
149997**
149998**    SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
149999**
150000** The transformation only works if all of the following are true:
150001**
150002**   *  The subquery is a UNION ALL of two or more terms
150003**   *  The subquery does not have a LIMIT clause
150004**   *  There is no WHERE or GROUP BY or HAVING clauses on the subqueries
150005**   *  The outer query is a simple count(*) with no WHERE clause or other
150006**      extraneous syntax.
150007**
150008** Return TRUE if the optimization is undertaken.
150009*/
150010static int countOfViewOptimization(Parse *pParse, Select *p){
150011  Select *pSub, *pPrior;
150012  Expr *pExpr;
150013  Expr *pCount;
150014  sqlite3 *db;
150015  if( (p->selFlags & SF_Aggregate)==0 ) return 0;   /* This is an aggregate */
150016  if( p->pEList->nExpr!=1 ) return 0;               /* Single result column */
150017  if( p->pWhere ) return 0;
150018  if( p->pHaving ) return 0;
150019  if( p->pGroupBy ) return 0;
150020  if( p->pOrderBy ) return 0;
150021  pExpr = p->pEList->a[0].pExpr;
150022  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;        /* Result is an aggregate */
150023  assert( ExprUseUToken(pExpr) );
150024  if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0;  /* Is count() */
150025  assert( ExprUseXList(pExpr) );
150026  if( pExpr->x.pList!=0 ) return 0;                 /* Must be count(*) */
150027  if( p->pSrc->nSrc!=1 ) return 0;                  /* One table in FROM  */
150028  if( ExprHasProperty(pExpr, EP_WinFunc) ) return 0;/* Not a window function */
150029  pSub = p->pSrc->a[0].pSelect;
150030  if( pSub==0 ) return 0;                           /* The FROM is a subquery */
150031  if( pSub->pPrior==0 ) return 0;                   /* Must be a compound */
150032  if( pSub->selFlags & SF_CopyCte ) return 0;       /* Not a CTE */
150033  do{
150034    if( pSub->op!=TK_ALL && pSub->pPrior ) return 0;  /* Must be UNION ALL */
150035    if( pSub->pWhere ) return 0;                      /* No WHERE clause */
150036    if( pSub->pLimit ) return 0;                      /* No LIMIT clause */
150037    if( pSub->selFlags & SF_Aggregate ) return 0;     /* Not an aggregate */
150038    assert( pSub->pHaving==0 );  /* Due to the previous */
150039   pSub = pSub->pPrior;                              /* Repeat over compound */
150040  }while( pSub );
150041
150042  /* If we reach this point then it is OK to perform the transformation */
150043
150044  db = pParse->db;
150045  pCount = pExpr;
150046  pExpr = 0;
150047  pSub = p->pSrc->a[0].pSelect;
150048  p->pSrc->a[0].pSelect = 0;
150049  sqlite3SrcListDelete(db, p->pSrc);
150050  p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
150051  while( pSub ){
150052    Expr *pTerm;
150053    pPrior = pSub->pPrior;
150054    pSub->pPrior = 0;
150055    pSub->pNext = 0;
150056    pSub->selFlags |= SF_Aggregate;
150057    pSub->selFlags &= ~SF_Compound;
150058    pSub->nSelectRow = 0;
150059    sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pSub->pEList);
150060    pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
150061    pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
150062    pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
150063    sqlite3PExprAddSelect(pParse, pTerm, pSub);
150064    if( pExpr==0 ){
150065      pExpr = pTerm;
150066    }else{
150067      pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
150068    }
150069    pSub = pPrior;
150070  }
150071  p->pEList->a[0].pExpr = pExpr;
150072  p->selFlags &= ~SF_Aggregate;
150073
150074#if TREETRACE_ENABLED
150075  if( sqlite3TreeTrace & 0x200 ){
150076    TREETRACE(0x200,pParse,p,("After count-of-view optimization:\n"));
150077    sqlite3TreeViewSelect(0, p, 0);
150078  }
150079#endif
150080  return 1;
150081}
150082
150083/*
150084** If any term of pSrc, or any SF_NestedFrom sub-query, is not the same
150085** as pSrcItem but has the same alias as p0, then return true.
150086** Otherwise return false.
150087*/
150088static int sameSrcAlias(SrcItem *p0, SrcList *pSrc){
150089  int i;
150090  for(i=0; i<pSrc->nSrc; i++){
150091    SrcItem *p1 = &pSrc->a[i];
150092    if( p1==p0 ) continue;
150093    if( p0->pTab==p1->pTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){
150094      return 1;
150095    }
150096    if( p1->pSelect
150097     && (p1->pSelect->selFlags & SF_NestedFrom)!=0
150098     && sameSrcAlias(p0, p1->pSelect->pSrc)
150099    ){
150100      return 1;
150101    }
150102  }
150103  return 0;
150104}
150105
150106/*
150107** Return TRUE (non-zero) if the i-th entry in the pTabList SrcList can
150108** be implemented as a co-routine.  The i-th entry is guaranteed to be
150109** a subquery.
150110**
150111** The subquery is implemented as a co-routine if all of the following are
150112** true:
150113**
150114**    (1)  The subquery will likely be implemented in the outer loop of
150115**         the query.  This will be the case if any one of the following
150116**         conditions hold:
150117**         (a)  The subquery is the only term in the FROM clause
150118**         (b)  The subquery is the left-most term and a CROSS JOIN or similar
150119**              requires it to be the outer loop
150120**         (c)  All of the following are true:
150121**                (i) The subquery is the left-most subquery in the FROM clause
150122**               (ii) There is nothing that would prevent the subquery from
150123**                    being used as the outer loop if the sqlite3WhereBegin()
150124**                    routine nominates it to that position.
150125**              (iii) The query is not a UPDATE ... FROM
150126**    (2)  The subquery is not a CTE that should be materialized because
150127**         (a) the AS MATERIALIZED keyword is used, or
150128**         (b) the CTE is used multiple times and does not have the
150129**             NOT MATERIALIZED keyword
150130**    (3)  The subquery is not part of a left operand for a RIGHT JOIN
150131**    (4)  The SQLITE_Coroutine optimization disable flag is not set
150132**    (5)  The subquery is not self-joined
150133*/
150134static int fromClauseTermCanBeCoroutine(
150135  Parse *pParse,          /* Parsing context */
150136  SrcList *pTabList,      /* FROM clause */
150137  int i,                  /* Which term of the FROM clause holds the subquery */
150138  int selFlags            /* Flags on the SELECT statement */
150139){
150140  SrcItem *pItem = &pTabList->a[i];
150141  if( pItem->fg.isCte ){
150142    const CteUse *pCteUse = pItem->u2.pCteUse;
150143    if( pCteUse->eM10d==M10d_Yes ) return 0;                          /* (2a) */
150144    if( pCteUse->nUse>=2 && pCteUse->eM10d!=M10d_No ) return 0;       /* (2b) */
150145  }
150146  if( pTabList->a[0].fg.jointype & JT_LTORJ ) return 0;               /* (3)  */
150147  if( OptimizationDisabled(pParse->db, SQLITE_Coroutines) ) return 0; /* (4)  */
150148  if( isSelfJoinView(pTabList, pItem, i+1, pTabList->nSrc)!=0 ){
150149    return 0;                                                          /* (5) */
150150  }
150151  if( i==0 ){
150152    if( pTabList->nSrc==1 ) return 1;                             /* (1a) */
150153    if( pTabList->a[1].fg.jointype & JT_CROSS ) return 1;         /* (1b) */
150154    if( selFlags & SF_UpdateFrom )              return 0;         /* (1c-iii) */
150155    return 1;
150156  }
150157  if( selFlags & SF_UpdateFrom ) return 0;                        /* (1c-iii) */
150158  while( 1 /*exit-by-break*/ ){
150159    if( pItem->fg.jointype & (JT_OUTER|JT_CROSS)  ) return 0;     /* (1c-ii) */
150160    if( i==0 ) break;
150161    i--;
150162    pItem--;
150163    if( pItem->pSelect!=0 ) return 0;                             /* (1c-i) */
150164  }
150165  return 1;
150166}
150167
150168/*
150169** Generate code for the SELECT statement given in the p argument.
150170**
150171** The results are returned according to the SelectDest structure.
150172** See comments in sqliteInt.h for further information.
150173**
150174** This routine returns the number of errors.  If any errors are
150175** encountered, then an appropriate error message is left in
150176** pParse->zErrMsg.
150177**
150178** This routine does NOT free the Select structure passed in.  The
150179** calling function needs to do that.
150180*/
150181SQLITE_PRIVATE int sqlite3Select(
150182  Parse *pParse,         /* The parser context */
150183  Select *p,             /* The SELECT statement being coded. */
150184  SelectDest *pDest      /* What to do with the query results */
150185){
150186  int i, j;              /* Loop counters */
150187  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
150188  Vdbe *v;               /* The virtual machine under construction */
150189  int isAgg;             /* True for select lists like "count(*)" */
150190  ExprList *pEList = 0;  /* List of columns to extract. */
150191  SrcList *pTabList;     /* List of tables to select from */
150192  Expr *pWhere;          /* The WHERE clause.  May be NULL */
150193  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
150194  Expr *pHaving;         /* The HAVING clause.  May be NULL */
150195  AggInfo *pAggInfo = 0; /* Aggregate information */
150196  int rc = 1;            /* Value to return from this function */
150197  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
150198  SortCtx sSort;         /* Info on how to code the ORDER BY clause */
150199  int iEnd;              /* Address of the end of the query */
150200  sqlite3 *db;           /* The database connection */
150201  ExprList *pMinMaxOrderBy = 0;  /* Added ORDER BY for min/max queries */
150202  u8 minMaxFlag;                 /* Flag for min/max queries */
150203
150204  db = pParse->db;
150205  assert( pParse==db->pParse );
150206  v = sqlite3GetVdbe(pParse);
150207  if( p==0 || pParse->nErr ){
150208    return 1;
150209  }
150210  assert( db->mallocFailed==0 );
150211  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
150212#if TREETRACE_ENABLED
150213  TREETRACE(0x1,pParse,p, ("begin processing:\n", pParse->addrExplain));
150214  if( sqlite3TreeTrace & 0x10000 ){
150215    if( (sqlite3TreeTrace & 0x10001)==0x10000 ){
150216      sqlite3TreeViewLine(0, "In sqlite3Select() at %s:%d",
150217                           __FILE__, __LINE__);
150218    }
150219    sqlite3ShowSelect(p);
150220  }
150221#endif
150222
150223  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
150224  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
150225  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
150226  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
150227  if( IgnorableDistinct(pDest) ){
150228    assert(pDest->eDest==SRT_Exists     || pDest->eDest==SRT_Union ||
150229           pDest->eDest==SRT_Except     || pDest->eDest==SRT_Discard ||
150230           pDest->eDest==SRT_DistQueue  || pDest->eDest==SRT_DistFifo );
150231    /* All of these destinations are also able to ignore the ORDER BY clause */
150232    if( p->pOrderBy ){
150233#if TREETRACE_ENABLED
150234      TREETRACE(0x800,pParse,p, ("dropping superfluous ORDER BY:\n"));
150235      if( sqlite3TreeTrace & 0x800 ){
150236        sqlite3TreeViewExprList(0, p->pOrderBy, 0, "ORDERBY");
150237      }
150238#endif
150239      sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric,
150240                              p->pOrderBy);
150241      testcase( pParse->earlyCleanup );
150242      p->pOrderBy = 0;
150243    }
150244    p->selFlags &= ~SF_Distinct;
150245    p->selFlags |= SF_NoopOrderBy;
150246  }
150247  sqlite3SelectPrep(pParse, p, 0);
150248  if( pParse->nErr ){
150249    goto select_end;
150250  }
150251  assert( db->mallocFailed==0 );
150252  assert( p->pEList!=0 );
150253#if TREETRACE_ENABLED
150254  if( sqlite3TreeTrace & 0x10 ){
150255    TREETRACE(0x10,pParse,p, ("after name resolution:\n"));
150256    sqlite3TreeViewSelect(0, p, 0);
150257  }
150258#endif
150259
150260  /* If the SF_UFSrcCheck flag is set, then this function is being called
150261  ** as part of populating the temp table for an UPDATE...FROM statement.
150262  ** In this case, it is an error if the target object (pSrc->a[0]) name
150263  ** or alias is duplicated within FROM clause (pSrc->a[1..n]).
150264  **
150265  ** Postgres disallows this case too. The reason is that some other
150266  ** systems handle this case differently, and not all the same way,
150267  ** which is just confusing. To avoid this, we follow PG's lead and
150268  ** disallow it altogether.  */
150269  if( p->selFlags & SF_UFSrcCheck ){
150270    SrcItem *p0 = &p->pSrc->a[0];
150271    if( sameSrcAlias(p0, p->pSrc) ){
150272      sqlite3ErrorMsg(pParse,
150273          "target object/alias may not appear in FROM clause: %s",
150274          p0->zAlias ? p0->zAlias : p0->pTab->zName
150275      );
150276      goto select_end;
150277    }
150278
150279    /* Clear the SF_UFSrcCheck flag. The check has already been performed,
150280    ** and leaving this flag set can cause errors if a compound sub-query
150281    ** in p->pSrc is flattened into this query and this function called
150282    ** again as part of compound SELECT processing.  */
150283    p->selFlags &= ~SF_UFSrcCheck;
150284  }
150285
150286  if( pDest->eDest==SRT_Output ){
150287    sqlite3GenerateColumnNames(pParse, p);
150288  }
150289
150290#ifndef SQLITE_OMIT_WINDOWFUNC
150291  if( sqlite3WindowRewrite(pParse, p) ){
150292    assert( pParse->nErr );
150293    goto select_end;
150294  }
150295#if TREETRACE_ENABLED
150296  if( p->pWin && (sqlite3TreeTrace & 0x40)!=0 ){
150297    TREETRACE(0x40,pParse,p, ("after window rewrite:\n"));
150298    sqlite3TreeViewSelect(0, p, 0);
150299  }
150300#endif
150301#endif /* SQLITE_OMIT_WINDOWFUNC */
150302  pTabList = p->pSrc;
150303  isAgg = (p->selFlags & SF_Aggregate)!=0;
150304  memset(&sSort, 0, sizeof(sSort));
150305  sSort.pOrderBy = p->pOrderBy;
150306
150307  /* Try to do various optimizations (flattening subqueries, and strength
150308  ** reduction of join operators) in the FROM clause up into the main query
150309  */
150310#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
150311  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
150312    SrcItem *pItem = &pTabList->a[i];
150313    Select *pSub = pItem->pSelect;
150314    Table *pTab = pItem->pTab;
150315
150316    /* The expander should have already created transient Table objects
150317    ** even for FROM clause elements such as subqueries that do not correspond
150318    ** to a real table */
150319    assert( pTab!=0 );
150320
150321    /* Try to simplify joins:
150322    **
150323    **      LEFT JOIN  ->  JOIN
150324    **     RIGHT JOIN  ->  JOIN
150325    **      FULL JOIN  ->  RIGHT JOIN
150326    **
150327    ** If terms of the i-th table are used in the WHERE clause in such a
150328    ** way that the i-th table cannot be the NULL row of a join, then
150329    ** perform the appropriate simplification. This is called
150330    ** "OUTER JOIN strength reduction" in the SQLite documentation.
150331    */
150332    if( (pItem->fg.jointype & (JT_LEFT|JT_LTORJ))!=0
150333     && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor,
150334                                     pItem->fg.jointype & JT_LTORJ)
150335     && OptimizationEnabled(db, SQLITE_SimplifyJoin)
150336    ){
150337      if( pItem->fg.jointype & JT_LEFT ){
150338        if( pItem->fg.jointype & JT_RIGHT ){
150339          TREETRACE(0x1000,pParse,p,
150340                    ("FULL-JOIN simplifies to RIGHT-JOIN on term %d\n",i));
150341          pItem->fg.jointype &= ~JT_LEFT;
150342        }else{
150343          TREETRACE(0x1000,pParse,p,
150344                    ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
150345          pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
150346          unsetJoinExpr(p->pWhere, pItem->iCursor, 0);
150347        }
150348      }
150349      if( pItem->fg.jointype & JT_LTORJ ){
150350        for(j=i+1; j<pTabList->nSrc; j++){
150351          SrcItem *pI2 = &pTabList->a[j];
150352          if( pI2->fg.jointype & JT_RIGHT ){
150353            if( pI2->fg.jointype & JT_LEFT ){
150354              TREETRACE(0x1000,pParse,p,
150355                        ("FULL-JOIN simplifies to LEFT-JOIN on term %d\n",j));
150356              pI2->fg.jointype &= ~JT_RIGHT;
150357            }else{
150358              TREETRACE(0x1000,pParse,p,
150359                        ("RIGHT-JOIN simplifies to JOIN on term %d\n",j));
150360              pI2->fg.jointype &= ~(JT_RIGHT|JT_OUTER);
150361              unsetJoinExpr(p->pWhere, pI2->iCursor, 1);
150362            }
150363          }
150364        }
150365        for(j=pTabList->nSrc-1; j>=0; j--){
150366          pTabList->a[j].fg.jointype &= ~JT_LTORJ;
150367          if( pTabList->a[j].fg.jointype & JT_RIGHT ) break;
150368        }
150369      }
150370    }
150371
150372    /* No further action if this term of the FROM clause is not a subquery */
150373    if( pSub==0 ) continue;
150374
150375    /* Catch mismatch in the declared columns of a view and the number of
150376    ** columns in the SELECT on the RHS */
150377    if( pTab->nCol!=pSub->pEList->nExpr ){
150378      sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
150379                      pTab->nCol, pTab->zName, pSub->pEList->nExpr);
150380      goto select_end;
150381    }
150382
150383    /* Do not attempt the usual optimizations (flattening and ORDER BY
150384    ** elimination) on a MATERIALIZED common table expression because
150385    ** a MATERIALIZED common table expression is an optimization fence.
150386    */
150387    if( pItem->fg.isCte && pItem->u2.pCteUse->eM10d==M10d_Yes ){
150388      continue;
150389    }
150390
150391    /* Do not try to flatten an aggregate subquery.
150392    **
150393    ** Flattening an aggregate subquery is only possible if the outer query
150394    ** is not a join.  But if the outer query is not a join, then the subquery
150395    ** will be implemented as a co-routine and there is no advantage to
150396    ** flattening in that case.
150397    */
150398    if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
150399    assert( pSub->pGroupBy==0 );
150400
150401    /* If a FROM-clause subquery has an ORDER BY clause that is not
150402    ** really doing anything, then delete it now so that it does not
150403    ** interfere with query flattening.  See the discussion at
150404    ** https://sqlite.org/forum/forumpost/2d76f2bcf65d256a
150405    **
150406    ** Beware of these cases where the ORDER BY clause may not be safely
150407    ** omitted:
150408    **
150409    **    (1)   There is also a LIMIT clause
150410    **    (2)   The subquery was added to help with window-function
150411    **          processing
150412    **    (3)   The subquery is in the FROM clause of an UPDATE
150413    **    (4)   The outer query uses an aggregate function other than
150414    **          the built-in count(), min(), or max().
150415    **    (5)   The ORDER BY isn't going to accomplish anything because
150416    **          one of:
150417    **            (a)  The outer query has a different ORDER BY clause
150418    **            (b)  The subquery is part of a join
150419    **          See forum post 062d576715d277c8
150420    **
150421    ** Also retain the ORDER BY if the OmitOrderBy optimization is disabled.
150422    */
150423    if( pSub->pOrderBy!=0
150424     && (p->pOrderBy!=0 || pTabList->nSrc>1)      /* Condition (5) */
150425     && pSub->pLimit==0                           /* Condition (1) */
150426     && (pSub->selFlags & SF_OrderByReqd)==0      /* Condition (2) */
150427     && (p->selFlags & SF_OrderByReqd)==0         /* Condition (3) and (4) */
150428     && OptimizationEnabled(db, SQLITE_OmitOrderBy)
150429    ){
150430      TREETRACE(0x800,pParse,p,
150431                ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
150432      sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric,
150433                              pSub->pOrderBy);
150434      pSub->pOrderBy = 0;
150435    }
150436
150437    /* If the outer query contains a "complex" result set (that is,
150438    ** if the result set of the outer query uses functions or subqueries)
150439    ** and if the subquery contains an ORDER BY clause and if
150440    ** it will be implemented as a co-routine, then do not flatten.  This
150441    ** restriction allows SQL constructs like this:
150442    **
150443    **  SELECT expensive_function(x)
150444    **    FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
150445    **
150446    ** The expensive_function() is only computed on the 10 rows that
150447    ** are output, rather than every row of the table.
150448    **
150449    ** The requirement that the outer query have a complex result set
150450    ** means that flattening does occur on simpler SQL constraints without
150451    ** the expensive_function() like:
150452    **
150453    **  SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
150454    */
150455    if( pSub->pOrderBy!=0
150456     && i==0
150457     && (p->selFlags & SF_ComplexResult)!=0
150458     && (pTabList->nSrc==1
150459         || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0)
150460    ){
150461      continue;
150462    }
150463
150464    if( flattenSubquery(pParse, p, i, isAgg) ){
150465      if( pParse->nErr ) goto select_end;
150466      /* This subquery can be absorbed into its parent. */
150467      i = -1;
150468    }
150469    pTabList = p->pSrc;
150470    if( db->mallocFailed ) goto select_end;
150471    if( !IgnorableOrderby(pDest) ){
150472      sSort.pOrderBy = p->pOrderBy;
150473    }
150474  }
150475#endif
150476
150477#ifndef SQLITE_OMIT_COMPOUND_SELECT
150478  /* Handle compound SELECT statements using the separate multiSelect()
150479  ** procedure.
150480  */
150481  if( p->pPrior ){
150482    rc = multiSelect(pParse, p, pDest);
150483#if TREETRACE_ENABLED
150484    TREETRACE(0x400,pParse,p,("end compound-select processing\n"));
150485    if( (sqlite3TreeTrace & 0x400)!=0 && ExplainQueryPlanParent(pParse)==0 ){
150486      sqlite3TreeViewSelect(0, p, 0);
150487    }
150488#endif
150489    if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
150490    return rc;
150491  }
150492#endif
150493
150494  /* Do the WHERE-clause constant propagation optimization if this is
150495  ** a join.  No need to speed time on this operation for non-join queries
150496  ** as the equivalent optimization will be handled by query planner in
150497  ** sqlite3WhereBegin().
150498  */
150499  if( p->pWhere!=0
150500   && p->pWhere->op==TK_AND
150501   && OptimizationEnabled(db, SQLITE_PropagateConst)
150502   && propagateConstants(pParse, p)
150503  ){
150504#if TREETRACE_ENABLED
150505    if( sqlite3TreeTrace & 0x2000 ){
150506      TREETRACE(0x2000,pParse,p,("After constant propagation:\n"));
150507      sqlite3TreeViewSelect(0, p, 0);
150508    }
150509#endif
150510  }else{
150511    TREETRACE(0x2000,pParse,p,("Constant propagation not helpful\n"));
150512  }
150513
150514  if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
150515   && countOfViewOptimization(pParse, p)
150516  ){
150517    if( db->mallocFailed ) goto select_end;
150518    pTabList = p->pSrc;
150519  }
150520
150521  /* For each term in the FROM clause, do two things:
150522  ** (1) Authorized unreferenced tables
150523  ** (2) Generate code for all sub-queries
150524  */
150525  for(i=0; i<pTabList->nSrc; i++){
150526    SrcItem *pItem = &pTabList->a[i];
150527    SrcItem *pPrior;
150528    SelectDest dest;
150529    Select *pSub;
150530#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
150531    const char *zSavedAuthContext;
150532#endif
150533
150534    /* Issue SQLITE_READ authorizations with a fake column name for any
150535    ** tables that are referenced but from which no values are extracted.
150536    ** Examples of where these kinds of null SQLITE_READ authorizations
150537    ** would occur:
150538    **
150539    **     SELECT count(*) FROM t1;   -- SQLITE_READ t1.""
150540    **     SELECT t1.* FROM t1, t2;   -- SQLITE_READ t2.""
150541    **
150542    ** The fake column name is an empty string.  It is possible for a table to
150543    ** have a column named by the empty string, in which case there is no way to
150544    ** distinguish between an unreferenced table and an actual reference to the
150545    ** "" column. The original design was for the fake column name to be a NULL,
150546    ** which would be unambiguous.  But legacy authorization callbacks might
150547    ** assume the column name is non-NULL and segfault.  The use of an empty
150548    ** string for the fake column name seems safer.
150549    */
150550    if( pItem->colUsed==0 && pItem->zName!=0 ){
150551      sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
150552    }
150553
150554#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
150555    /* Generate code for all sub-queries in the FROM clause
150556    */
150557    pSub = pItem->pSelect;
150558    if( pSub==0 || pItem->addrFillSub!=0 ) continue;
150559
150560    /* The code for a subquery should only be generated once. */
150561    assert( pItem->addrFillSub==0 );
150562
150563    /* Increment Parse.nHeight by the height of the largest expression
150564    ** tree referred to by this, the parent select. The child select
150565    ** may contain expression trees of at most
150566    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
150567    ** more conservative than necessary, but much easier than enforcing
150568    ** an exact limit.
150569    */
150570    pParse->nHeight += sqlite3SelectExprHeight(p);
150571
150572    /* Make copies of constant WHERE-clause terms in the outer query down
150573    ** inside the subquery.  This can help the subquery to run more efficiently.
150574    */
150575    if( OptimizationEnabled(db, SQLITE_PushDown)
150576     && (pItem->fg.isCte==0
150577         || (pItem->u2.pCteUse->eM10d!=M10d_Yes && pItem->u2.pCteUse->nUse<2))
150578     && pushDownWhereTerms(pParse, pSub, p->pWhere, pTabList, i)
150579    ){
150580#if TREETRACE_ENABLED
150581      if( sqlite3TreeTrace & 0x4000 ){
150582        TREETRACE(0x4000,pParse,p,
150583            ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
150584        sqlite3TreeViewSelect(0, p, 0);
150585      }
150586#endif
150587      assert( pItem->pSelect && (pItem->pSelect->selFlags & SF_PushDown)!=0 );
150588    }else{
150589      TREETRACE(0x4000,pParse,p,("WHERE-lcause push-down not possible\n"));
150590    }
150591
150592    /* Convert unused result columns of the subquery into simple NULL
150593    ** expressions, to avoid unneeded searching and computation.
150594    */
150595    if( OptimizationEnabled(db, SQLITE_NullUnusedCols)
150596     && disableUnusedSubqueryResultColumns(pItem)
150597    ){
150598#if TREETRACE_ENABLED
150599      if( sqlite3TreeTrace & 0x4000 ){
150600        TREETRACE(0x4000,pParse,p,
150601            ("Change unused result columns to NULL for subquery %d:\n",
150602             pSub->selId));
150603        sqlite3TreeViewSelect(0, p, 0);
150604      }
150605#endif
150606    }
150607
150608    zSavedAuthContext = pParse->zAuthContext;
150609    pParse->zAuthContext = pItem->zName;
150610
150611    /* Generate code to implement the subquery
150612    */
150613    if( fromClauseTermCanBeCoroutine(pParse, pTabList, i, p->selFlags) ){
150614      /* Implement a co-routine that will return a single row of the result
150615      ** set on each invocation.
150616      */
150617      int addrTop = sqlite3VdbeCurrentAddr(v)+1;
150618
150619      pItem->regReturn = ++pParse->nMem;
150620      sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
150621      VdbeComment((v, "%!S", pItem));
150622      pItem->addrFillSub = addrTop;
150623      sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
150624      ExplainQueryPlan((pParse, 1, "CO-ROUTINE %!S", pItem));
150625      sqlite3Select(pParse, pSub, &dest);
150626      pItem->pTab->nRowLogEst = pSub->nSelectRow;
150627      pItem->fg.viaCoroutine = 1;
150628      pItem->regResult = dest.iSdst;
150629      sqlite3VdbeEndCoroutine(v, pItem->regReturn);
150630      sqlite3VdbeJumpHere(v, addrTop-1);
150631      sqlite3ClearTempRegCache(pParse);
150632    }else if( pItem->fg.isCte && pItem->u2.pCteUse->addrM9e>0 ){
150633      /* This is a CTE for which materialization code has already been
150634      ** generated.  Invoke the subroutine to compute the materialization,
150635      ** the make the pItem->iCursor be a copy of the ephemeral table that
150636      ** holds the result of the materialization. */
150637      CteUse *pCteUse = pItem->u2.pCteUse;
150638      sqlite3VdbeAddOp2(v, OP_Gosub, pCteUse->regRtn, pCteUse->addrM9e);
150639      if( pItem->iCursor!=pCteUse->iCur ){
150640        sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pCteUse->iCur);
150641        VdbeComment((v, "%!S", pItem));
150642      }
150643      pSub->nSelectRow = pCteUse->nRowEst;
150644    }else if( (pPrior = isSelfJoinView(pTabList, pItem, 0, i))!=0 ){
150645      /* This view has already been materialized by a prior entry in
150646      ** this same FROM clause.  Reuse it. */
150647      if( pPrior->addrFillSub ){
150648        sqlite3VdbeAddOp2(v, OP_Gosub, pPrior->regReturn, pPrior->addrFillSub);
150649      }
150650      sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
150651      pSub->nSelectRow = pPrior->pSelect->nSelectRow;
150652    }else{
150653      /* Materialize the view.  If the view is not correlated, generate a
150654      ** subroutine to do the materialization so that subsequent uses of
150655      ** the same view can reuse the materialization. */
150656      int topAddr;
150657      int onceAddr = 0;
150658#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
150659      int addrExplain;
150660#endif
150661
150662      pItem->regReturn = ++pParse->nMem;
150663      topAddr = sqlite3VdbeAddOp0(v, OP_Goto);
150664      pItem->addrFillSub = topAddr+1;
150665      pItem->fg.isMaterialized = 1;
150666      if( pItem->fg.isCorrelated==0 ){
150667        /* If the subquery is not correlated and if we are not inside of
150668        ** a trigger, then we only need to compute the value of the subquery
150669        ** once. */
150670        onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
150671        VdbeComment((v, "materialize %!S", pItem));
150672      }else{
150673        VdbeNoopComment((v, "materialize %!S", pItem));
150674      }
150675      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
150676
150677      ExplainQueryPlan2(addrExplain, (pParse, 1, "MATERIALIZE %!S", pItem));
150678      sqlite3Select(pParse, pSub, &dest);
150679      pItem->pTab->nRowLogEst = pSub->nSelectRow;
150680      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
150681      sqlite3VdbeAddOp2(v, OP_Return, pItem->regReturn, topAddr+1);
150682      VdbeComment((v, "end %!S", pItem));
150683      sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
150684      sqlite3VdbeJumpHere(v, topAddr);
150685      sqlite3ClearTempRegCache(pParse);
150686      if( pItem->fg.isCte && pItem->fg.isCorrelated==0 ){
150687        CteUse *pCteUse = pItem->u2.pCteUse;
150688        pCteUse->addrM9e = pItem->addrFillSub;
150689        pCteUse->regRtn = pItem->regReturn;
150690        pCteUse->iCur = pItem->iCursor;
150691        pCteUse->nRowEst = pSub->nSelectRow;
150692      }
150693    }
150694    if( db->mallocFailed ) goto select_end;
150695    pParse->nHeight -= sqlite3SelectExprHeight(p);
150696    pParse->zAuthContext = zSavedAuthContext;
150697#endif
150698  }
150699
150700  /* Various elements of the SELECT copied into local variables for
150701  ** convenience */
150702  pEList = p->pEList;
150703  pWhere = p->pWhere;
150704  pGroupBy = p->pGroupBy;
150705  pHaving = p->pHaving;
150706  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
150707
150708#if TREETRACE_ENABLED
150709  if( sqlite3TreeTrace & 0x8000 ){
150710    TREETRACE(0x8000,pParse,p,("After all FROM-clause analysis:\n"));
150711    sqlite3TreeViewSelect(0, p, 0);
150712  }
150713#endif
150714
150715  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
150716  ** if the select-list is the same as the ORDER BY list, then this query
150717  ** can be rewritten as a GROUP BY. In other words, this:
150718  **
150719  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
150720  **
150721  ** is transformed to:
150722  **
150723  **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
150724  **
150725  ** The second form is preferred as a single index (or temp-table) may be
150726  ** used for both the ORDER BY and DISTINCT processing. As originally
150727  ** written the query must use a temp-table for at least one of the ORDER
150728  ** BY and DISTINCT, and an index or separate temp-table for the other.
150729  */
150730  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
150731   && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
150732#ifndef SQLITE_OMIT_WINDOWFUNC
150733   && p->pWin==0
150734#endif
150735  ){
150736    p->selFlags &= ~SF_Distinct;
150737    pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
150738    p->selFlags |= SF_Aggregate;
150739    /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
150740    ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
150741    ** original setting of the SF_Distinct flag, not the current setting */
150742    assert( sDistinct.isTnct );
150743    sDistinct.isTnct = 2;
150744
150745#if TREETRACE_ENABLED
150746    if( sqlite3TreeTrace & 0x20000 ){
150747      TREETRACE(0x20000,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
150748      sqlite3TreeViewSelect(0, p, 0);
150749    }
150750#endif
150751  }
150752
150753  /* If there is an ORDER BY clause, then create an ephemeral index to
150754  ** do the sorting.  But this sorting ephemeral index might end up
150755  ** being unused if the data can be extracted in pre-sorted order.
150756  ** If that is the case, then the OP_OpenEphemeral instruction will be
150757  ** changed to an OP_Noop once we figure out that the sorting index is
150758  ** not needed.  The sSort.addrSortIndex variable is used to facilitate
150759  ** that change.
150760  */
150761  if( sSort.pOrderBy ){
150762    KeyInfo *pKeyInfo;
150763    pKeyInfo = sqlite3KeyInfoFromExprList(
150764        pParse, sSort.pOrderBy, 0, pEList->nExpr);
150765    sSort.iECursor = pParse->nTab++;
150766    sSort.addrSortIndex =
150767      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
150768          sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
150769          (char*)pKeyInfo, P4_KEYINFO
150770      );
150771  }else{
150772    sSort.addrSortIndex = -1;
150773  }
150774
150775  /* If the output is destined for a temporary table, open that table.
150776  */
150777  if( pDest->eDest==SRT_EphemTab ){
150778    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
150779    if( p->selFlags & SF_NestedFrom ){
150780      /* Delete or NULL-out result columns that will never be used */
150781      int ii;
150782      for(ii=pEList->nExpr-1; ii>0 && pEList->a[ii].fg.bUsed==0; ii--){
150783        sqlite3ExprDelete(db, pEList->a[ii].pExpr);
150784        sqlite3DbFree(db, pEList->a[ii].zEName);
150785        pEList->nExpr--;
150786      }
150787      for(ii=0; ii<pEList->nExpr; ii++){
150788        if( pEList->a[ii].fg.bUsed==0 ) pEList->a[ii].pExpr->op = TK_NULL;
150789      }
150790    }
150791  }
150792
150793  /* Set the limiter.
150794  */
150795  iEnd = sqlite3VdbeMakeLabel(pParse);
150796  if( (p->selFlags & SF_FixedLimit)==0 ){
150797    p->nSelectRow = 320;  /* 4 billion rows */
150798  }
150799  if( p->pLimit ) computeLimitRegisters(pParse, p, iEnd);
150800  if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
150801    sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
150802    sSort.sortFlags |= SORTFLAG_UseSorter;
150803  }
150804
150805  /* Open an ephemeral index to use for the distinct set.
150806  */
150807  if( p->selFlags & SF_Distinct ){
150808    sDistinct.tabTnct = pParse->nTab++;
150809    sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
150810                       sDistinct.tabTnct, 0, 0,
150811                       (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
150812                       P4_KEYINFO);
150813    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
150814    sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
150815  }else{
150816    sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
150817  }
150818
150819  if( !isAgg && pGroupBy==0 ){
150820    /* No aggregate functions and no GROUP BY clause */
150821    u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
150822                   | (p->selFlags & SF_FixedLimit);
150823#ifndef SQLITE_OMIT_WINDOWFUNC
150824    Window *pWin = p->pWin;      /* Main window object (or NULL) */
150825    if( pWin ){
150826      sqlite3WindowCodeInit(pParse, p);
150827    }
150828#endif
150829    assert( WHERE_USE_LIMIT==SF_FixedLimit );
150830
150831
150832    /* Begin the database scan. */
150833    TREETRACE(0x2,pParse,p,("WhereBegin\n"));
150834    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
150835                               p->pEList, p, wctrlFlags, p->nSelectRow);
150836    if( pWInfo==0 ) goto select_end;
150837    if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
150838      p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
150839    }
150840    if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
150841      sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
150842    }
150843    if( sSort.pOrderBy ){
150844      sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
150845      sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
150846      if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
150847        sSort.pOrderBy = 0;
150848      }
150849    }
150850    TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
150851
150852    /* If sorting index that was created by a prior OP_OpenEphemeral
150853    ** instruction ended up not being needed, then change the OP_OpenEphemeral
150854    ** into an OP_Noop.
150855    */
150856    if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
150857      sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
150858    }
150859
150860    assert( p->pEList==pEList );
150861#ifndef SQLITE_OMIT_WINDOWFUNC
150862    if( pWin ){
150863      int addrGosub = sqlite3VdbeMakeLabel(pParse);
150864      int iCont = sqlite3VdbeMakeLabel(pParse);
150865      int iBreak = sqlite3VdbeMakeLabel(pParse);
150866      int regGosub = ++pParse->nMem;
150867
150868      sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
150869
150870      sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
150871      sqlite3VdbeResolveLabel(v, addrGosub);
150872      VdbeNoopComment((v, "inner-loop subroutine"));
150873      sSort.labelOBLopt = 0;
150874      selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
150875      sqlite3VdbeResolveLabel(v, iCont);
150876      sqlite3VdbeAddOp1(v, OP_Return, regGosub);
150877      VdbeComment((v, "end inner-loop subroutine"));
150878      sqlite3VdbeResolveLabel(v, iBreak);
150879    }else
150880#endif /* SQLITE_OMIT_WINDOWFUNC */
150881    {
150882      /* Use the standard inner loop. */
150883      selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
150884          sqlite3WhereContinueLabel(pWInfo),
150885          sqlite3WhereBreakLabel(pWInfo));
150886
150887      /* End the database scan loop.
150888      */
150889      TREETRACE(0x2,pParse,p,("WhereEnd\n"));
150890      sqlite3WhereEnd(pWInfo);
150891    }
150892  }else{
150893    /* This case when there exist aggregate functions or a GROUP BY clause
150894    ** or both */
150895    NameContext sNC;    /* Name context for processing aggregate information */
150896    int iAMem;          /* First Mem address for storing current GROUP BY */
150897    int iBMem;          /* First Mem address for previous GROUP BY */
150898    int iUseFlag;       /* Mem address holding flag indicating that at least
150899                        ** one row of the input to the aggregator has been
150900                        ** processed */
150901    int iAbortFlag;     /* Mem address which causes query abort if positive */
150902    int groupBySort;    /* Rows come from source in GROUP BY order */
150903    int addrEnd;        /* End of processing for this SELECT */
150904    int sortPTab = 0;   /* Pseudotable used to decode sorting results */
150905    int sortOut = 0;    /* Output register from the sorter */
150906    int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
150907
150908    /* Remove any and all aliases between the result set and the
150909    ** GROUP BY clause.
150910    */
150911    if( pGroupBy ){
150912      int k;                        /* Loop counter */
150913      struct ExprList_item *pItem;  /* For looping over expression in a list */
150914
150915      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
150916        pItem->u.x.iAlias = 0;
150917      }
150918      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
150919        pItem->u.x.iAlias = 0;
150920      }
150921      assert( 66==sqlite3LogEst(100) );
150922      if( p->nSelectRow>66 ) p->nSelectRow = 66;
150923
150924      /* If there is both a GROUP BY and an ORDER BY clause and they are
150925      ** identical, then it may be possible to disable the ORDER BY clause
150926      ** on the grounds that the GROUP BY will cause elements to come out
150927      ** in the correct order. It also may not - the GROUP BY might use a
150928      ** database index that causes rows to be grouped together as required
150929      ** but not actually sorted. Either way, record the fact that the
150930      ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
150931      ** variable.  */
150932      if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){
150933        int ii;
150934        /* The GROUP BY processing doesn't care whether rows are delivered in
150935        ** ASC or DESC order - only that each group is returned contiguously.
150936        ** So set the ASC/DESC flags in the GROUP BY to match those in the
150937        ** ORDER BY to maximize the chances of rows being delivered in an
150938        ** order that makes the ORDER BY redundant.  */
150939        for(ii=0; ii<pGroupBy->nExpr; ii++){
150940          u8 sortFlags;
150941          sortFlags = sSort.pOrderBy->a[ii].fg.sortFlags & KEYINFO_ORDER_DESC;
150942          pGroupBy->a[ii].fg.sortFlags = sortFlags;
150943        }
150944        if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
150945          orderByGrp = 1;
150946        }
150947      }
150948    }else{
150949      assert( 0==sqlite3LogEst(1) );
150950      p->nSelectRow = 0;
150951    }
150952
150953    /* Create a label to jump to when we want to abort the query */
150954    addrEnd = sqlite3VdbeMakeLabel(pParse);
150955
150956    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
150957    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
150958    ** SELECT statement.
150959    */
150960    pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) );
150961    if( pAggInfo ){
150962      sqlite3ParserAddCleanup(pParse, agginfoFree, pAggInfo);
150963      testcase( pParse->earlyCleanup );
150964    }
150965    if( db->mallocFailed ){
150966      goto select_end;
150967    }
150968    pAggInfo->selId = p->selId;
150969#ifdef SQLITE_DEBUG
150970    pAggInfo->pSelect = p;
150971#endif
150972    memset(&sNC, 0, sizeof(sNC));
150973    sNC.pParse = pParse;
150974    sNC.pSrcList = pTabList;
150975    sNC.uNC.pAggInfo = pAggInfo;
150976    VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
150977    pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
150978    pAggInfo->pGroupBy = pGroupBy;
150979    sqlite3ExprAnalyzeAggList(&sNC, pEList);
150980    sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
150981    if( pHaving ){
150982      if( pGroupBy ){
150983        assert( pWhere==p->pWhere );
150984        assert( pHaving==p->pHaving );
150985        assert( pGroupBy==p->pGroupBy );
150986        havingToWhere(pParse, p);
150987        pWhere = p->pWhere;
150988      }
150989      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
150990    }
150991    pAggInfo->nAccumulator = pAggInfo->nColumn;
150992    if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){
150993      minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pFExpr, &pMinMaxOrderBy);
150994    }else{
150995      minMaxFlag = WHERE_ORDERBY_NORMAL;
150996    }
150997    analyzeAggFuncArgs(pAggInfo, &sNC);
150998    if( db->mallocFailed ) goto select_end;
150999#if TREETRACE_ENABLED
151000    if( sqlite3TreeTrace & 0x20 ){
151001      TREETRACE(0x20,pParse,p,("After aggregate analysis %p:\n", pAggInfo));
151002      sqlite3TreeViewSelect(0, p, 0);
151003      if( minMaxFlag ){
151004        sqlite3DebugPrintf("MIN/MAX Optimization (0x%02x) adds:\n", minMaxFlag);
151005        sqlite3TreeViewExprList(0, pMinMaxOrderBy, 0, "ORDERBY");
151006      }
151007      printAggInfo(pAggInfo);
151008    }
151009#endif
151010
151011
151012    /* Processing for aggregates with GROUP BY is very different and
151013    ** much more complex than aggregates without a GROUP BY.
151014    */
151015    if( pGroupBy ){
151016      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
151017      int addr1;          /* A-vs-B comparison jump */
151018      int addrOutputRow;  /* Start of subroutine that outputs a result row */
151019      int regOutputRow;   /* Return address register for output subroutine */
151020      int addrSetAbort;   /* Set the abort flag and return */
151021      int addrTopOfLoop;  /* Top of the input loop */
151022      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
151023      int addrReset;      /* Subroutine for resetting the accumulator */
151024      int regReset;       /* Return address register for reset subroutine */
151025      ExprList *pDistinct = 0;
151026      u16 distFlag = 0;
151027      int eDist = WHERE_DISTINCT_NOOP;
151028
151029      if( pAggInfo->nFunc==1
151030       && pAggInfo->aFunc[0].iDistinct>=0
151031       && ALWAYS(pAggInfo->aFunc[0].pFExpr!=0)
151032       && ALWAYS(ExprUseXList(pAggInfo->aFunc[0].pFExpr))
151033       && pAggInfo->aFunc[0].pFExpr->x.pList!=0
151034      ){
151035        Expr *pExpr = pAggInfo->aFunc[0].pFExpr->x.pList->a[0].pExpr;
151036        pExpr = sqlite3ExprDup(db, pExpr, 0);
151037        pDistinct = sqlite3ExprListDup(db, pGroupBy, 0);
151038        pDistinct = sqlite3ExprListAppend(pParse, pDistinct, pExpr);
151039        distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
151040      }
151041
151042      /* If there is a GROUP BY clause we might need a sorting index to
151043      ** implement it.  Allocate that sorting index now.  If it turns out
151044      ** that we do not need it after all, the OP_SorterOpen instruction
151045      ** will be converted into a Noop.
151046      */
151047      pAggInfo->sortingIdx = pParse->nTab++;
151048      pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pGroupBy,
151049                                            0, pAggInfo->nColumn);
151050      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
151051          pAggInfo->sortingIdx, pAggInfo->nSortingColumn,
151052          0, (char*)pKeyInfo, P4_KEYINFO);
151053
151054      /* Initialize memory locations used by GROUP BY aggregate processing
151055      */
151056      iUseFlag = ++pParse->nMem;
151057      iAbortFlag = ++pParse->nMem;
151058      regOutputRow = ++pParse->nMem;
151059      addrOutputRow = sqlite3VdbeMakeLabel(pParse);
151060      regReset = ++pParse->nMem;
151061      addrReset = sqlite3VdbeMakeLabel(pParse);
151062      iAMem = pParse->nMem + 1;
151063      pParse->nMem += pGroupBy->nExpr;
151064      iBMem = pParse->nMem + 1;
151065      pParse->nMem += pGroupBy->nExpr;
151066      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
151067      VdbeComment((v, "clear abort flag"));
151068      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
151069
151070      /* Begin a loop that will extract all source rows in GROUP BY order.
151071      ** This might involve two separate loops with an OP_Sort in between, or
151072      ** it might be a single loop that uses an index to extract information
151073      ** in the right order to begin with.
151074      */
151075      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
151076      TREETRACE(0x2,pParse,p,("WhereBegin\n"));
151077      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, pDistinct,
151078          p, (sDistinct.isTnct==2 ? WHERE_DISTINCTBY : WHERE_GROUPBY)
151079          |  (orderByGrp ? WHERE_SORTBYGROUP : 0) | distFlag, 0
151080      );
151081      if( pWInfo==0 ){
151082        sqlite3ExprListDelete(db, pDistinct);
151083        goto select_end;
151084      }
151085      if( pParse->pIdxEpr ){
151086        optimizeAggregateUseOfIndexedExpr(pParse, p, pAggInfo, &sNC);
151087      }
151088      assignAggregateRegisters(pParse, pAggInfo);
151089      eDist = sqlite3WhereIsDistinct(pWInfo);
151090      TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
151091      if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
151092        /* The optimizer is able to deliver rows in group by order so
151093        ** we do not have to sort.  The OP_OpenEphemeral table will be
151094        ** cancelled later because we still need to use the pKeyInfo
151095        */
151096        groupBySort = 0;
151097      }else{
151098        /* Rows are coming out in undetermined order.  We have to push
151099        ** each row into a sorting index, terminate the first loop,
151100        ** then loop over the sorting index in order to get the output
151101        ** in sorted order
151102        */
151103        int regBase;
151104        int regRecord;
151105        int nCol;
151106        int nGroupBy;
151107
151108#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
151109        int addrExp;              /* Address of OP_Explain instruction */
151110#endif
151111        ExplainQueryPlan2(addrExp, (pParse, 0, "USE TEMP B-TREE FOR %s",
151112            (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
151113                    "DISTINCT" : "GROUP BY"
151114        ));
151115
151116        groupBySort = 1;
151117        nGroupBy = pGroupBy->nExpr;
151118        nCol = nGroupBy;
151119        j = nGroupBy;
151120        for(i=0; i<pAggInfo->nColumn; i++){
151121          if( pAggInfo->aCol[i].iSorterColumn>=j ){
151122            nCol++;
151123            j++;
151124          }
151125        }
151126        regBase = sqlite3GetTempRange(pParse, nCol);
151127        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
151128        j = nGroupBy;
151129        pAggInfo->directMode = 1;
151130        for(i=0; i<pAggInfo->nColumn; i++){
151131          struct AggInfo_col *pCol = &pAggInfo->aCol[i];
151132          if( pCol->iSorterColumn>=j ){
151133            sqlite3ExprCode(pParse, pCol->pCExpr, j + regBase);
151134            j++;
151135          }
151136        }
151137        pAggInfo->directMode = 0;
151138        regRecord = sqlite3GetTempReg(pParse);
151139        sqlite3VdbeScanStatusCounters(v, addrExp, 0, sqlite3VdbeCurrentAddr(v));
151140        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
151141        sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord);
151142        sqlite3VdbeScanStatusRange(v, addrExp, sqlite3VdbeCurrentAddr(v)-2, -1);
151143        sqlite3ReleaseTempReg(pParse, regRecord);
151144        sqlite3ReleaseTempRange(pParse, regBase, nCol);
151145        TREETRACE(0x2,pParse,p,("WhereEnd\n"));
151146        sqlite3WhereEnd(pWInfo);
151147        pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++;
151148        sortOut = sqlite3GetTempReg(pParse);
151149        sqlite3VdbeScanStatusCounters(v, addrExp, sqlite3VdbeCurrentAddr(v), 0);
151150        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
151151        sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd);
151152        VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
151153        pAggInfo->useSortingIdx = 1;
151154        sqlite3VdbeScanStatusRange(v, addrExp, -1, sortPTab);
151155        sqlite3VdbeScanStatusRange(v, addrExp, -1, pAggInfo->sortingIdx);
151156      }
151157
151158      /* If there are entries in pAgggInfo->aFunc[] that contain subexpressions
151159      ** that are indexed (and that were previously identified and tagged
151160      ** in optimizeAggregateUseOfIndexedExpr()) then those subexpressions
151161      ** must now be converted into a TK_AGG_COLUMN node so that the value
151162      ** is correctly pulled from the index rather than being recomputed. */
151163      if( pParse->pIdxEpr ){
151164        aggregateConvertIndexedExprRefToColumn(pAggInfo);
151165#if TREETRACE_ENABLED
151166        if( sqlite3TreeTrace & 0x20 ){
151167          TREETRACE(0x20, pParse, p,
151168             ("AggInfo function expressions converted to reference index\n"));
151169          sqlite3TreeViewSelect(0, p, 0);
151170          printAggInfo(pAggInfo);
151171        }
151172#endif
151173      }
151174
151175      /* If the index or temporary table used by the GROUP BY sort
151176      ** will naturally deliver rows in the order required by the ORDER BY
151177      ** clause, cancel the ephemeral table open coded earlier.
151178      **
151179      ** This is an optimization - the correct answer should result regardless.
151180      ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
151181      ** disable this optimization for testing purposes.  */
151182      if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
151183       && (groupBySort || sqlite3WhereIsSorted(pWInfo))
151184      ){
151185        sSort.pOrderBy = 0;
151186        sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
151187      }
151188
151189      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
151190      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
151191      ** Then compare the current GROUP BY terms against the GROUP BY terms
151192      ** from the previous row currently stored in a0, a1, a2...
151193      */
151194      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
151195      if( groupBySort ){
151196        sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,
151197                          sortOut, sortPTab);
151198      }
151199      for(j=0; j<pGroupBy->nExpr; j++){
151200        if( groupBySort ){
151201          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
151202        }else{
151203          pAggInfo->directMode = 1;
151204          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
151205        }
151206      }
151207      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
151208                          (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
151209      addr1 = sqlite3VdbeCurrentAddr(v);
151210      sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
151211
151212      /* Generate code that runs whenever the GROUP BY changes.
151213      ** Changes in the GROUP BY are detected by the previous code
151214      ** block.  If there were no changes, this block is skipped.
151215      **
151216      ** This code copies current group by terms in b0,b1,b2,...
151217      ** over to a0,a1,a2.  It then calls the output subroutine
151218      ** and resets the aggregate accumulator registers in preparation
151219      ** for the next GROUP BY batch.
151220      */
151221      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
151222      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
151223      VdbeComment((v, "output one row"));
151224      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
151225      VdbeComment((v, "check abort flag"));
151226      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
151227      VdbeComment((v, "reset accumulator"));
151228
151229      /* Update the aggregate accumulators based on the content of
151230      ** the current row
151231      */
151232      sqlite3VdbeJumpHere(v, addr1);
151233      updateAccumulator(pParse, iUseFlag, pAggInfo, eDist);
151234      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
151235      VdbeComment((v, "indicate data in accumulator"));
151236
151237      /* End of the loop
151238      */
151239      if( groupBySort ){
151240        sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx,addrTopOfLoop);
151241        VdbeCoverage(v);
151242      }else{
151243        TREETRACE(0x2,pParse,p,("WhereEnd\n"));
151244        sqlite3WhereEnd(pWInfo);
151245        sqlite3VdbeChangeToNoop(v, addrSortingIdx);
151246      }
151247      sqlite3ExprListDelete(db, pDistinct);
151248
151249      /* Output the final row of result
151250      */
151251      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
151252      VdbeComment((v, "output final row"));
151253
151254      /* Jump over the subroutines
151255      */
151256      sqlite3VdbeGoto(v, addrEnd);
151257
151258      /* Generate a subroutine that outputs a single row of the result
151259      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
151260      ** is less than or equal to zero, the subroutine is a no-op.  If
151261      ** the processing calls for the query to abort, this subroutine
151262      ** increments the iAbortFlag memory location before returning in
151263      ** order to signal the caller to abort.
151264      */
151265      addrSetAbort = sqlite3VdbeCurrentAddr(v);
151266      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
151267      VdbeComment((v, "set abort flag"));
151268      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
151269      sqlite3VdbeResolveLabel(v, addrOutputRow);
151270      addrOutputRow = sqlite3VdbeCurrentAddr(v);
151271      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
151272      VdbeCoverage(v);
151273      VdbeComment((v, "Groupby result generator entry point"));
151274      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
151275      finalizeAggFunctions(pParse, pAggInfo);
151276      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
151277      selectInnerLoop(pParse, p, -1, &sSort,
151278                      &sDistinct, pDest,
151279                      addrOutputRow+1, addrSetAbort);
151280      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
151281      VdbeComment((v, "end groupby result generator"));
151282
151283      /* Generate a subroutine that will reset the group-by accumulator
151284      */
151285      sqlite3VdbeResolveLabel(v, addrReset);
151286      resetAccumulator(pParse, pAggInfo);
151287      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
151288      VdbeComment((v, "indicate accumulator empty"));
151289      sqlite3VdbeAddOp1(v, OP_Return, regReset);
151290
151291      if( distFlag!=0 && eDist!=WHERE_DISTINCT_NOOP ){
151292        struct AggInfo_func *pF = &pAggInfo->aFunc[0];
151293        fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
151294      }
151295    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
151296    else {
151297      Table *pTab;
151298      if( (pTab = isSimpleCount(p, pAggInfo))!=0 ){
151299        /* If isSimpleCount() returns a pointer to a Table structure, then
151300        ** the SQL statement is of the form:
151301        **
151302        **   SELECT count(*) FROM <tbl>
151303        **
151304        ** where the Table structure returned represents table <tbl>.
151305        **
151306        ** This statement is so common that it is optimized specially. The
151307        ** OP_Count instruction is executed either on the intkey table that
151308        ** contains the data for table <tbl> or on one of its indexes. It
151309        ** is better to execute the op on an index, as indexes are almost
151310        ** always spread across less pages than their corresponding tables.
151311        */
151312        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
151313        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
151314        Index *pIdx;                         /* Iterator variable */
151315        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
151316        Index *pBest = 0;                    /* Best index found so far */
151317        Pgno iRoot = pTab->tnum;             /* Root page of scanned b-tree */
151318
151319        sqlite3CodeVerifySchema(pParse, iDb);
151320        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
151321
151322        /* Search for the index that has the lowest scan cost.
151323        **
151324        ** (2011-04-15) Do not do a full scan of an unordered index.
151325        **
151326        ** (2013-10-03) Do not count the entries in a partial index.
151327        **
151328        ** In practice the KeyInfo structure will not be used. It is only
151329        ** passed to keep OP_OpenRead happy.
151330        */
151331        if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
151332        if( !p->pSrc->a[0].fg.notIndexed ){
151333          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
151334            if( pIdx->bUnordered==0
151335             && pIdx->szIdxRow<pTab->szTabRow
151336             && pIdx->pPartIdxWhere==0
151337             && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
151338            ){
151339              pBest = pIdx;
151340            }
151341          }
151342        }
151343        if( pBest ){
151344          iRoot = pBest->tnum;
151345          pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
151346        }
151347
151348        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
151349        sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, (int)iRoot, iDb, 1);
151350        if( pKeyInfo ){
151351          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
151352        }
151353        assignAggregateRegisters(pParse, pAggInfo);
151354        sqlite3VdbeAddOp2(v, OP_Count, iCsr, AggInfoFuncReg(pAggInfo,0));
151355        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
151356        explainSimpleCount(pParse, pTab, pBest);
151357      }else{
151358        int regAcc = 0;           /* "populate accumulators" flag */
151359        ExprList *pDistinct = 0;
151360        u16 distFlag = 0;
151361        int eDist;
151362
151363        /* If there are accumulator registers but no min() or max() functions
151364        ** without FILTER clauses, allocate register regAcc. Register regAcc
151365        ** will contain 0 the first time the inner loop runs, and 1 thereafter.
151366        ** The code generated by updateAccumulator() uses this to ensure
151367        ** that the accumulator registers are (a) updated only once if
151368        ** there are no min() or max functions or (b) always updated for the
151369        ** first row visited by the aggregate, so that they are updated at
151370        ** least once even if the FILTER clause means the min() or max()
151371        ** function visits zero rows.  */
151372        if( pAggInfo->nAccumulator ){
151373          for(i=0; i<pAggInfo->nFunc; i++){
151374            if( ExprHasProperty(pAggInfo->aFunc[i].pFExpr, EP_WinFunc) ){
151375              continue;
151376            }
151377            if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){
151378              break;
151379            }
151380          }
151381          if( i==pAggInfo->nFunc ){
151382            regAcc = ++pParse->nMem;
151383            sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
151384          }
151385        }else if( pAggInfo->nFunc==1 && pAggInfo->aFunc[0].iDistinct>=0 ){
151386          assert( ExprUseXList(pAggInfo->aFunc[0].pFExpr) );
151387          pDistinct = pAggInfo->aFunc[0].pFExpr->x.pList;
151388          distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
151389        }
151390        assignAggregateRegisters(pParse, pAggInfo);
151391
151392        /* This case runs if the aggregate has no GROUP BY clause.  The
151393        ** processing is much simpler since there is only a single row
151394        ** of output.
151395        */
151396        assert( p->pGroupBy==0 );
151397        resetAccumulator(pParse, pAggInfo);
151398
151399        /* If this query is a candidate for the min/max optimization, then
151400        ** minMaxFlag will have been previously set to either
151401        ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
151402        ** be an appropriate ORDER BY expression for the optimization.
151403        */
151404        assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
151405        assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
151406
151407        TREETRACE(0x2,pParse,p,("WhereBegin\n"));
151408        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
151409                                   pDistinct, p, minMaxFlag|distFlag, 0);
151410        if( pWInfo==0 ){
151411          goto select_end;
151412        }
151413        TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
151414        eDist = sqlite3WhereIsDistinct(pWInfo);
151415        updateAccumulator(pParse, regAcc, pAggInfo, eDist);
151416        if( eDist!=WHERE_DISTINCT_NOOP ){
151417          struct AggInfo_func *pF = pAggInfo->aFunc;
151418          if( pF ){
151419            fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
151420          }
151421        }
151422
151423        if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
151424        if( minMaxFlag ){
151425          sqlite3WhereMinMaxOptEarlyOut(v, pWInfo);
151426        }
151427        TREETRACE(0x2,pParse,p,("WhereEnd\n"));
151428        sqlite3WhereEnd(pWInfo);
151429        finalizeAggFunctions(pParse, pAggInfo);
151430      }
151431
151432      sSort.pOrderBy = 0;
151433      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
151434      selectInnerLoop(pParse, p, -1, 0, 0,
151435                      pDest, addrEnd, addrEnd);
151436    }
151437    sqlite3VdbeResolveLabel(v, addrEnd);
151438
151439  } /* endif aggregate query */
151440
151441  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
151442    explainTempTable(pParse, "DISTINCT");
151443  }
151444
151445  /* If there is an ORDER BY clause, then we need to sort the results
151446  ** and send them to the callback one by one.
151447  */
151448  if( sSort.pOrderBy ){
151449    assert( p->pEList==pEList );
151450    generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
151451  }
151452
151453  /* Jump here to skip this query
151454  */
151455  sqlite3VdbeResolveLabel(v, iEnd);
151456
151457  /* The SELECT has been coded. If there is an error in the Parse structure,
151458  ** set the return code to 1. Otherwise 0. */
151459  rc = (pParse->nErr>0);
151460
151461  /* Control jumps to here if an error is encountered above, or upon
151462  ** successful coding of the SELECT.
151463  */
151464select_end:
151465  assert( db->mallocFailed==0 || db->mallocFailed==1 );
151466  assert( db->mallocFailed==0 || pParse->nErr!=0 );
151467  sqlite3ExprListDelete(db, pMinMaxOrderBy);
151468#ifdef SQLITE_DEBUG
151469  if( pAggInfo && !db->mallocFailed ){
151470#if TREETRACE_ENABLED
151471    if( sqlite3TreeTrace & 0x20 ){
151472      TREETRACE(0x20,pParse,p,("Finished with AggInfo\n"));
151473      printAggInfo(pAggInfo);
151474    }
151475#endif
151476    for(i=0; i<pAggInfo->nColumn; i++){
151477      Expr *pExpr = pAggInfo->aCol[i].pCExpr;
151478      if( pExpr==0 ) continue;
151479      assert( pExpr->pAggInfo==pAggInfo );
151480      assert( pExpr->iAgg==i );
151481    }
151482    for(i=0; i<pAggInfo->nFunc; i++){
151483      Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
151484      assert( pExpr!=0 );
151485      assert( pExpr->pAggInfo==pAggInfo );
151486      assert( pExpr->iAgg==i );
151487    }
151488  }
151489#endif
151490
151491#if TREETRACE_ENABLED
151492  TREETRACE(0x1,pParse,p,("end processing\n"));
151493  if( (sqlite3TreeTrace & 0x40000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
151494    sqlite3TreeViewSelect(0, p, 0);
151495  }
151496#endif
151497  ExplainQueryPlanPop(pParse);
151498  return rc;
151499}
151500
151501/************** End of select.c **********************************************/
151502/************** Begin file table.c *******************************************/
151503/*
151504** 2001 September 15
151505**
151506** The author disclaims copyright to this source code.  In place of
151507** a legal notice, here is a blessing:
151508**
151509**    May you do good and not evil.
151510**    May you find forgiveness for yourself and forgive others.
151511**    May you share freely, never taking more than you give.
151512**
151513*************************************************************************
151514** This file contains the sqlite3_get_table() and sqlite3_free_table()
151515** interface routines.  These are just wrappers around the main
151516** interface routine of sqlite3_exec().
151517**
151518** These routines are in a separate files so that they will not be linked
151519** if they are not used.
151520*/
151521/* #include "sqliteInt.h" */
151522
151523#ifndef SQLITE_OMIT_GET_TABLE
151524
151525/*
151526** This structure is used to pass data from sqlite3_get_table() through
151527** to the callback function is uses to build the result.
151528*/
151529typedef struct TabResult {
151530  char **azResult;   /* Accumulated output */
151531  char *zErrMsg;     /* Error message text, if an error occurs */
151532  u32 nAlloc;        /* Slots allocated for azResult[] */
151533  u32 nRow;          /* Number of rows in the result */
151534  u32 nColumn;       /* Number of columns in the result */
151535  u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
151536  int rc;            /* Return code from sqlite3_exec() */
151537} TabResult;
151538
151539/*
151540** This routine is called once for each row in the result table.  Its job
151541** is to fill in the TabResult structure appropriately, allocating new
151542** memory as necessary.
151543*/
151544static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
151545  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
151546  int need;                         /* Slots needed in p->azResult[] */
151547  int i;                            /* Loop counter */
151548  char *z;                          /* A single column of result */
151549
151550  /* Make sure there is enough space in p->azResult to hold everything
151551  ** we need to remember from this invocation of the callback.
151552  */
151553  if( p->nRow==0 && argv!=0 ){
151554    need = nCol*2;
151555  }else{
151556    need = nCol;
151557  }
151558  if( p->nData + need > p->nAlloc ){
151559    char **azNew;
151560    p->nAlloc = p->nAlloc*2 + need;
151561    azNew = sqlite3Realloc( p->azResult, sizeof(char*)*p->nAlloc );
151562    if( azNew==0 ) goto malloc_failed;
151563    p->azResult = azNew;
151564  }
151565
151566  /* If this is the first row, then generate an extra row containing
151567  ** the names of all columns.
151568  */
151569  if( p->nRow==0 ){
151570    p->nColumn = nCol;
151571    for(i=0; i<nCol; i++){
151572      z = sqlite3_mprintf("%s", colv[i]);
151573      if( z==0 ) goto malloc_failed;
151574      p->azResult[p->nData++] = z;
151575    }
151576  }else if( (int)p->nColumn!=nCol ){
151577    sqlite3_free(p->zErrMsg);
151578    p->zErrMsg = sqlite3_mprintf(
151579       "sqlite3_get_table() called with two or more incompatible queries"
151580    );
151581    p->rc = SQLITE_ERROR;
151582    return 1;
151583  }
151584
151585  /* Copy over the row data
151586  */
151587  if( argv!=0 ){
151588    for(i=0; i<nCol; i++){
151589      if( argv[i]==0 ){
151590        z = 0;
151591      }else{
151592        int n = sqlite3Strlen30(argv[i])+1;
151593        z = sqlite3_malloc64( n );
151594        if( z==0 ) goto malloc_failed;
151595        memcpy(z, argv[i], n);
151596      }
151597      p->azResult[p->nData++] = z;
151598    }
151599    p->nRow++;
151600  }
151601  return 0;
151602
151603malloc_failed:
151604  p->rc = SQLITE_NOMEM_BKPT;
151605  return 1;
151606}
151607
151608/*
151609** Query the database.  But instead of invoking a callback for each row,
151610** malloc() for space to hold the result and return the entire results
151611** at the conclusion of the call.
151612**
151613** The result that is written to ***pazResult is held in memory obtained
151614** from malloc().  But the caller cannot free this memory directly.
151615** Instead, the entire table should be passed to sqlite3_free_table() when
151616** the calling procedure is finished using it.
151617*/
151618SQLITE_API int sqlite3_get_table(
151619  sqlite3 *db,                /* The database on which the SQL executes */
151620  const char *zSql,           /* The SQL to be executed */
151621  char ***pazResult,          /* Write the result table here */
151622  int *pnRow,                 /* Write the number of rows in the result here */
151623  int *pnColumn,              /* Write the number of columns of result here */
151624  char **pzErrMsg             /* Write error messages here */
151625){
151626  int rc;
151627  TabResult res;
151628
151629#ifdef SQLITE_ENABLE_API_ARMOR
151630  if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
151631#endif
151632  *pazResult = 0;
151633  if( pnColumn ) *pnColumn = 0;
151634  if( pnRow ) *pnRow = 0;
151635  if( pzErrMsg ) *pzErrMsg = 0;
151636  res.zErrMsg = 0;
151637  res.nRow = 0;
151638  res.nColumn = 0;
151639  res.nData = 1;
151640  res.nAlloc = 20;
151641  res.rc = SQLITE_OK;
151642  res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
151643  if( res.azResult==0 ){
151644     db->errCode = SQLITE_NOMEM;
151645     return SQLITE_NOMEM_BKPT;
151646  }
151647  res.azResult[0] = 0;
151648  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
151649  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
151650  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
151651  if( (rc&0xff)==SQLITE_ABORT ){
151652    sqlite3_free_table(&res.azResult[1]);
151653    if( res.zErrMsg ){
151654      if( pzErrMsg ){
151655        sqlite3_free(*pzErrMsg);
151656        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
151657      }
151658      sqlite3_free(res.zErrMsg);
151659    }
151660    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
151661    return res.rc;
151662  }
151663  sqlite3_free(res.zErrMsg);
151664  if( rc!=SQLITE_OK ){
151665    sqlite3_free_table(&res.azResult[1]);
151666    return rc;
151667  }
151668  if( res.nAlloc>res.nData ){
151669    char **azNew;
151670    azNew = sqlite3Realloc( res.azResult, sizeof(char*)*res.nData );
151671    if( azNew==0 ){
151672      sqlite3_free_table(&res.azResult[1]);
151673      db->errCode = SQLITE_NOMEM;
151674      return SQLITE_NOMEM_BKPT;
151675    }
151676    res.azResult = azNew;
151677  }
151678  *pazResult = &res.azResult[1];
151679  if( pnColumn ) *pnColumn = res.nColumn;
151680  if( pnRow ) *pnRow = res.nRow;
151681  return rc;
151682}
151683
151684/*
151685** This routine frees the space the sqlite3_get_table() malloced.
151686*/
151687SQLITE_API void sqlite3_free_table(
151688  char **azResult            /* Result returned from sqlite3_get_table() */
151689){
151690  if( azResult ){
151691    int i, n;
151692    azResult--;
151693    assert( azResult!=0 );
151694    n = SQLITE_PTR_TO_INT(azResult[0]);
151695    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
151696    sqlite3_free(azResult);
151697  }
151698}
151699
151700#endif /* SQLITE_OMIT_GET_TABLE */
151701
151702/************** End of table.c ***********************************************/
151703/************** Begin file trigger.c *****************************************/
151704/*
151705**
151706** The author disclaims copyright to this source code.  In place of
151707** a legal notice, here is a blessing:
151708**
151709**    May you do good and not evil.
151710**    May you find forgiveness for yourself and forgive others.
151711**    May you share freely, never taking more than you give.
151712**
151713*************************************************************************
151714** This file contains the implementation for TRIGGERs
151715*/
151716/* #include "sqliteInt.h" */
151717
151718#ifndef SQLITE_OMIT_TRIGGER
151719/*
151720** Delete a linked list of TriggerStep structures.
151721*/
151722SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
151723  while( pTriggerStep ){
151724    TriggerStep * pTmp = pTriggerStep;
151725    pTriggerStep = pTriggerStep->pNext;
151726
151727    sqlite3ExprDelete(db, pTmp->pWhere);
151728    sqlite3ExprListDelete(db, pTmp->pExprList);
151729    sqlite3SelectDelete(db, pTmp->pSelect);
151730    sqlite3IdListDelete(db, pTmp->pIdList);
151731    sqlite3UpsertDelete(db, pTmp->pUpsert);
151732    sqlite3SrcListDelete(db, pTmp->pFrom);
151733    sqlite3DbFree(db, pTmp->zSpan);
151734
151735    sqlite3DbFree(db, pTmp);
151736  }
151737}
151738
151739/*
151740** Given table pTab, return a list of all the triggers attached to
151741** the table. The list is connected by Trigger.pNext pointers.
151742**
151743** All of the triggers on pTab that are in the same database as pTab
151744** are already attached to pTab->pTrigger.  But there might be additional
151745** triggers on pTab in the TEMP schema.  This routine prepends all
151746** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
151747** and returns the combined list.
151748**
151749** To state it another way:  This routine returns a list of all triggers
151750** that fire off of pTab.  The list will include any TEMP triggers on
151751** pTab as well as the triggers lised in pTab->pTrigger.
151752*/
151753SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
151754  Schema *pTmpSchema;       /* Schema of the pTab table */
151755  Trigger *pList;           /* List of triggers to return */
151756  HashElem *p;              /* Loop variable for TEMP triggers */
151757
151758  assert( pParse->disableTriggers==0 );
151759  pTmpSchema = pParse->db->aDb[1].pSchema;
151760  p = sqliteHashFirst(&pTmpSchema->trigHash);
151761  pList = pTab->pTrigger;
151762  while( p ){
151763    Trigger *pTrig = (Trigger *)sqliteHashData(p);
151764    if( pTrig->pTabSchema==pTab->pSchema
151765     && pTrig->table
151766     && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
151767     && (pTrig->pTabSchema!=pTmpSchema || pTrig->bReturning)
151768    ){
151769      pTrig->pNext = pList;
151770      pList = pTrig;
151771    }else if( pTrig->op==TK_RETURNING ){
151772#ifndef SQLITE_OMIT_VIRTUALTABLE
151773      assert( pParse->db->pVtabCtx==0 );
151774#endif
151775      assert( pParse->bReturning );
151776      assert( &(pParse->u1.pReturning->retTrig) == pTrig );
151777      pTrig->table = pTab->zName;
151778      pTrig->pTabSchema = pTab->pSchema;
151779      pTrig->pNext = pList;
151780      pList = pTrig;
151781    }
151782    p = sqliteHashNext(p);
151783  }
151784#if 0
151785  if( pList ){
151786    Trigger *pX;
151787    printf("Triggers for %s:", pTab->zName);
151788    for(pX=pList; pX; pX=pX->pNext){
151789      printf(" %s", pX->zName);
151790    }
151791    printf("\n");
151792    fflush(stdout);
151793  }
151794#endif
151795  return pList;
151796}
151797
151798/*
151799** This is called by the parser when it sees a CREATE TRIGGER statement
151800** up to the point of the BEGIN before the trigger actions.  A Trigger
151801** structure is generated based on the information available and stored
151802** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
151803** sqlite3FinishTrigger() function is called to complete the trigger
151804** construction process.
151805*/
151806SQLITE_PRIVATE void sqlite3BeginTrigger(
151807  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
151808  Token *pName1,      /* The name of the trigger */
151809  Token *pName2,      /* The name of the trigger */
151810  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
151811  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
151812  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
151813  SrcList *pTableName,/* The name of the table/view the trigger applies to */
151814  Expr *pWhen,        /* WHEN clause */
151815  int isTemp,         /* True if the TEMPORARY keyword is present */
151816  int noErr           /* Suppress errors if the trigger already exists */
151817){
151818  Trigger *pTrigger = 0;  /* The new trigger */
151819  Table *pTab;            /* Table that the trigger fires off of */
151820  char *zName = 0;        /* Name of the trigger */
151821  sqlite3 *db = pParse->db;  /* The database connection */
151822  int iDb;                /* The database to store the trigger in */
151823  Token *pName;           /* The unqualified db name */
151824  DbFixer sFix;           /* State vector for the DB fixer */
151825
151826  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
151827  assert( pName2!=0 );
151828  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
151829  assert( op>0 && op<0xff );
151830  if( isTemp ){
151831    /* If TEMP was specified, then the trigger name may not be qualified. */
151832    if( pName2->n>0 ){
151833      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
151834      goto trigger_cleanup;
151835    }
151836    iDb = 1;
151837    pName = pName1;
151838  }else{
151839    /* Figure out the db that the trigger will be created in */
151840    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
151841    if( iDb<0 ){
151842      goto trigger_cleanup;
151843    }
151844  }
151845  if( !pTableName || db->mallocFailed ){
151846    goto trigger_cleanup;
151847  }
151848
151849  /* A long-standing parser bug is that this syntax was allowed:
151850  **
151851  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
151852  **                                                 ^^^^^^^^
151853  **
151854  ** To maintain backwards compatibility, ignore the database
151855  ** name on pTableName if we are reparsing out of the schema table
151856  */
151857  if( db->init.busy && iDb!=1 ){
151858    sqlite3DbFree(db, pTableName->a[0].zDatabase);
151859    pTableName->a[0].zDatabase = 0;
151860  }
151861
151862  /* If the trigger name was unqualified, and the table is a temp table,
151863  ** then set iDb to 1 to create the trigger in the temporary database.
151864  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
151865  ** exist, the error is caught by the block below.
151866  */
151867  pTab = sqlite3SrcListLookup(pParse, pTableName);
151868  if( db->init.busy==0 && pName2->n==0 && pTab
151869        && pTab->pSchema==db->aDb[1].pSchema ){
151870    iDb = 1;
151871  }
151872
151873  /* Ensure the table name matches database name and that the table exists */
151874  if( db->mallocFailed ) goto trigger_cleanup;
151875  assert( pTableName->nSrc==1 );
151876  sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
151877  if( sqlite3FixSrcList(&sFix, pTableName) ){
151878    goto trigger_cleanup;
151879  }
151880  pTab = sqlite3SrcListLookup(pParse, pTableName);
151881  if( !pTab ){
151882    /* The table does not exist. */
151883    goto trigger_orphan_error;
151884  }
151885  if( IsVirtual(pTab) ){
151886    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
151887    goto trigger_orphan_error;
151888  }
151889  if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
151890    sqlite3ErrorMsg(pParse, "cannot create triggers on shadow tables");
151891    goto trigger_orphan_error;
151892  }
151893
151894  /* Check that the trigger name is not reserved and that no trigger of the
151895  ** specified name exists */
151896  zName = sqlite3NameFromToken(db, pName);
151897  if( zName==0 ){
151898    assert( db->mallocFailed );
151899    goto trigger_cleanup;
151900  }
151901  if( sqlite3CheckObjectName(pParse, zName, "trigger", pTab->zName) ){
151902    goto trigger_cleanup;
151903  }
151904  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
151905  if( !IN_RENAME_OBJECT ){
151906    if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
151907      if( !noErr ){
151908        sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
151909      }else{
151910        assert( !db->init.busy );
151911        sqlite3CodeVerifySchema(pParse, iDb);
151912        VVA_ONLY( pParse->ifNotExists = 1; )
151913      }
151914      goto trigger_cleanup;
151915    }
151916  }
151917
151918  /* Do not create a trigger on a system table */
151919  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
151920    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
151921    goto trigger_cleanup;
151922  }
151923
151924  /* INSTEAD of triggers are only for views and views only support INSTEAD
151925  ** of triggers.
151926  */
151927  if( IsView(pTab) && tr_tm!=TK_INSTEAD ){
151928    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
151929        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName->a);
151930    goto trigger_orphan_error;
151931  }
151932  if( !IsView(pTab) && tr_tm==TK_INSTEAD ){
151933    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
151934        " trigger on table: %S", pTableName->a);
151935    goto trigger_orphan_error;
151936  }
151937
151938#ifndef SQLITE_OMIT_AUTHORIZATION
151939  if( !IN_RENAME_OBJECT ){
151940    int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
151941    int code = SQLITE_CREATE_TRIGGER;
151942    const char *zDb = db->aDb[iTabDb].zDbSName;
151943    const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
151944    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
151945    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
151946      goto trigger_cleanup;
151947    }
151948    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
151949      goto trigger_cleanup;
151950    }
151951  }
151952#endif
151953
151954  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
151955  ** cannot appear on views.  So we might as well translate every
151956  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
151957  ** elsewhere.
151958  */
151959  if (tr_tm == TK_INSTEAD){
151960    tr_tm = TK_BEFORE;
151961  }
151962
151963  /* Build the Trigger object */
151964  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
151965  if( pTrigger==0 ) goto trigger_cleanup;
151966  pTrigger->zName = zName;
151967  zName = 0;
151968  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
151969  pTrigger->pSchema = db->aDb[iDb].pSchema;
151970  pTrigger->pTabSchema = pTab->pSchema;
151971  pTrigger->op = (u8)op;
151972  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
151973  if( IN_RENAME_OBJECT ){
151974    sqlite3RenameTokenRemap(pParse, pTrigger->table, pTableName->a[0].zName);
151975    pTrigger->pWhen = pWhen;
151976    pWhen = 0;
151977  }else{
151978    pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
151979  }
151980  pTrigger->pColumns = pColumns;
151981  pColumns = 0;
151982  assert( pParse->pNewTrigger==0 );
151983  pParse->pNewTrigger = pTrigger;
151984
151985trigger_cleanup:
151986  sqlite3DbFree(db, zName);
151987  sqlite3SrcListDelete(db, pTableName);
151988  sqlite3IdListDelete(db, pColumns);
151989  sqlite3ExprDelete(db, pWhen);
151990  if( !pParse->pNewTrigger ){
151991    sqlite3DeleteTrigger(db, pTrigger);
151992  }else{
151993    assert( pParse->pNewTrigger==pTrigger );
151994  }
151995  return;
151996
151997trigger_orphan_error:
151998  if( db->init.iDb==1 ){
151999    /* Ticket #3810.
152000    ** Normally, whenever a table is dropped, all associated triggers are
152001    ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
152002    ** and the table is dropped by a different database connection, the
152003    ** trigger is not visible to the database connection that does the
152004    ** drop so the trigger cannot be dropped.  This results in an
152005    ** "orphaned trigger" - a trigger whose associated table is missing.
152006    **
152007    ** 2020-11-05 see also https://sqlite.org/forum/forumpost/157dc791df
152008    */
152009    db->init.orphanTrigger = 1;
152010  }
152011  goto trigger_cleanup;
152012}
152013
152014/*
152015** This routine is called after all of the trigger actions have been parsed
152016** in order to complete the process of building the trigger.
152017*/
152018SQLITE_PRIVATE void sqlite3FinishTrigger(
152019  Parse *pParse,          /* Parser context */
152020  TriggerStep *pStepList, /* The triggered program */
152021  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
152022){
152023  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
152024  char *zName;                            /* Name of trigger */
152025  sqlite3 *db = pParse->db;               /* The database */
152026  DbFixer sFix;                           /* Fixer object */
152027  int iDb;                                /* Database containing the trigger */
152028  Token nameToken;                        /* Trigger name for error reporting */
152029
152030  pParse->pNewTrigger = 0;
152031  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
152032  zName = pTrig->zName;
152033  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
152034  pTrig->step_list = pStepList;
152035  while( pStepList ){
152036    pStepList->pTrig = pTrig;
152037    pStepList = pStepList->pNext;
152038  }
152039  sqlite3TokenInit(&nameToken, pTrig->zName);
152040  sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
152041  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
152042   || sqlite3FixExpr(&sFix, pTrig->pWhen)
152043  ){
152044    goto triggerfinish_cleanup;
152045  }
152046
152047#ifndef SQLITE_OMIT_ALTERTABLE
152048  if( IN_RENAME_OBJECT ){
152049    assert( !db->init.busy );
152050    pParse->pNewTrigger = pTrig;
152051    pTrig = 0;
152052  }else
152053#endif
152054
152055  /* if we are not initializing,
152056  ** build the sqlite_schema entry
152057  */
152058  if( !db->init.busy ){
152059    Vdbe *v;
152060    char *z;
152061
152062    /* If this is a new CREATE TABLE statement, and if shadow tables
152063    ** are read-only, and the trigger makes a change to a shadow table,
152064    ** then raise an error - do not allow the trigger to be created. */
152065    if( sqlite3ReadOnlyShadowTables(db) ){
152066      TriggerStep *pStep;
152067      for(pStep=pTrig->step_list; pStep; pStep=pStep->pNext){
152068        if( pStep->zTarget!=0
152069         && sqlite3ShadowTableName(db, pStep->zTarget)
152070        ){
152071          sqlite3ErrorMsg(pParse,
152072            "trigger \"%s\" may not write to shadow table \"%s\"",
152073            pTrig->zName, pStep->zTarget);
152074          goto triggerfinish_cleanup;
152075        }
152076      }
152077    }
152078
152079    /* Make an entry in the sqlite_schema table */
152080    v = sqlite3GetVdbe(pParse);
152081    if( v==0 ) goto triggerfinish_cleanup;
152082    sqlite3BeginWriteOperation(pParse, 0, iDb);
152083    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
152084    testcase( z==0 );
152085    sqlite3NestedParse(pParse,
152086       "INSERT INTO %Q." LEGACY_SCHEMA_TABLE
152087       " VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
152088       db->aDb[iDb].zDbSName, zName,
152089       pTrig->table, z);
152090    sqlite3DbFree(db, z);
152091    sqlite3ChangeCookie(pParse, iDb);
152092    sqlite3VdbeAddParseSchemaOp(v, iDb,
152093        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName), 0);
152094  }
152095
152096  if( db->init.busy ){
152097    Trigger *pLink = pTrig;
152098    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
152099    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
152100    assert( pLink!=0 );
152101    pTrig = sqlite3HashInsert(pHash, zName, pTrig);
152102    if( pTrig ){
152103      sqlite3OomFault(db);
152104    }else if( pLink->pSchema==pLink->pTabSchema ){
152105      Table *pTab;
152106      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
152107      assert( pTab!=0 );
152108      pLink->pNext = pTab->pTrigger;
152109      pTab->pTrigger = pLink;
152110    }
152111  }
152112
152113triggerfinish_cleanup:
152114  sqlite3DeleteTrigger(db, pTrig);
152115  assert( IN_RENAME_OBJECT || !pParse->pNewTrigger );
152116  sqlite3DeleteTriggerStep(db, pStepList);
152117}
152118
152119/*
152120** Duplicate a range of text from an SQL statement, then convert all
152121** whitespace characters into ordinary space characters.
152122*/
152123static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
152124  char *z = sqlite3DbSpanDup(db, zStart, zEnd);
152125  int i;
152126  if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';
152127  return z;
152128}
152129
152130/*
152131** Turn a SELECT statement (that the pSelect parameter points to) into
152132** a trigger step.  Return a pointer to a TriggerStep structure.
152133**
152134** The parser calls this routine when it finds a SELECT statement in
152135** body of a TRIGGER.
152136*/
152137SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(
152138  sqlite3 *db,                /* Database connection */
152139  Select *pSelect,            /* The SELECT statement */
152140  const char *zStart,         /* Start of SQL text */
152141  const char *zEnd            /* End of SQL text */
152142){
152143  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
152144  if( pTriggerStep==0 ) {
152145    sqlite3SelectDelete(db, pSelect);
152146    return 0;
152147  }
152148  pTriggerStep->op = TK_SELECT;
152149  pTriggerStep->pSelect = pSelect;
152150  pTriggerStep->orconf = OE_Default;
152151  pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
152152  return pTriggerStep;
152153}
152154
152155/*
152156** Allocate space to hold a new trigger step.  The allocated space
152157** holds both the TriggerStep object and the TriggerStep.target.z string.
152158**
152159** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
152160*/
152161static TriggerStep *triggerStepAllocate(
152162  Parse *pParse,              /* Parser context */
152163  u8 op,                      /* Trigger opcode */
152164  Token *pName,               /* The target name */
152165  const char *zStart,         /* Start of SQL text */
152166  const char *zEnd            /* End of SQL text */
152167){
152168  sqlite3 *db = pParse->db;
152169  TriggerStep *pTriggerStep;
152170
152171  if( pParse->nErr ) return 0;
152172  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
152173  if( pTriggerStep ){
152174    char *z = (char*)&pTriggerStep[1];
152175    memcpy(z, pName->z, pName->n);
152176    sqlite3Dequote(z);
152177    pTriggerStep->zTarget = z;
152178    pTriggerStep->op = op;
152179    pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
152180    if( IN_RENAME_OBJECT ){
152181      sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName);
152182    }
152183  }
152184  return pTriggerStep;
152185}
152186
152187/*
152188** Build a trigger step out of an INSERT statement.  Return a pointer
152189** to the new trigger step.
152190**
152191** The parser calls this routine when it sees an INSERT inside the
152192** body of a trigger.
152193*/
152194SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
152195  Parse *pParse,      /* Parser */
152196  Token *pTableName,  /* Name of the table into which we insert */
152197  IdList *pColumn,    /* List of columns in pTableName to insert into */
152198  Select *pSelect,    /* A SELECT statement that supplies values */
152199  u8 orconf,          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
152200  Upsert *pUpsert,    /* ON CONFLICT clauses for upsert */
152201  const char *zStart, /* Start of SQL text */
152202  const char *zEnd    /* End of SQL text */
152203){
152204  sqlite3 *db = pParse->db;
152205  TriggerStep *pTriggerStep;
152206
152207  assert(pSelect != 0 || db->mallocFailed);
152208
152209  pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTableName,zStart,zEnd);
152210  if( pTriggerStep ){
152211    if( IN_RENAME_OBJECT ){
152212      pTriggerStep->pSelect = pSelect;
152213      pSelect = 0;
152214    }else{
152215      pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
152216    }
152217    pTriggerStep->pIdList = pColumn;
152218    pTriggerStep->pUpsert = pUpsert;
152219    pTriggerStep->orconf = orconf;
152220    if( pUpsert ){
152221      sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget);
152222    }
152223  }else{
152224    testcase( pColumn );
152225    sqlite3IdListDelete(db, pColumn);
152226    testcase( pUpsert );
152227    sqlite3UpsertDelete(db, pUpsert);
152228  }
152229  sqlite3SelectDelete(db, pSelect);
152230
152231  return pTriggerStep;
152232}
152233
152234/*
152235** Construct a trigger step that implements an UPDATE statement and return
152236** a pointer to that trigger step.  The parser calls this routine when it
152237** sees an UPDATE statement inside the body of a CREATE TRIGGER.
152238*/
152239SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
152240  Parse *pParse,          /* Parser */
152241  Token *pTableName,   /* Name of the table to be updated */
152242  SrcList *pFrom,      /* FROM clause for an UPDATE-FROM, or NULL */
152243  ExprList *pEList,    /* The SET clause: list of column and new values */
152244  Expr *pWhere,        /* The WHERE clause */
152245  u8 orconf,           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
152246  const char *zStart,  /* Start of SQL text */
152247  const char *zEnd     /* End of SQL text */
152248){
152249  sqlite3 *db = pParse->db;
152250  TriggerStep *pTriggerStep;
152251
152252  pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTableName,zStart,zEnd);
152253  if( pTriggerStep ){
152254    if( IN_RENAME_OBJECT ){
152255      pTriggerStep->pExprList = pEList;
152256      pTriggerStep->pWhere = pWhere;
152257      pTriggerStep->pFrom = pFrom;
152258      pEList = 0;
152259      pWhere = 0;
152260      pFrom = 0;
152261    }else{
152262      pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
152263      pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
152264      pTriggerStep->pFrom = sqlite3SrcListDup(db, pFrom, EXPRDUP_REDUCE);
152265    }
152266    pTriggerStep->orconf = orconf;
152267  }
152268  sqlite3ExprListDelete(db, pEList);
152269  sqlite3ExprDelete(db, pWhere);
152270  sqlite3SrcListDelete(db, pFrom);
152271  return pTriggerStep;
152272}
152273
152274/*
152275** Construct a trigger step that implements a DELETE statement and return
152276** a pointer to that trigger step.  The parser calls this routine when it
152277** sees a DELETE statement inside the body of a CREATE TRIGGER.
152278*/
152279SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
152280  Parse *pParse,          /* Parser */
152281  Token *pTableName,      /* The table from which rows are deleted */
152282  Expr *pWhere,           /* The WHERE clause */
152283  const char *zStart,     /* Start of SQL text */
152284  const char *zEnd        /* End of SQL text */
152285){
152286  sqlite3 *db = pParse->db;
152287  TriggerStep *pTriggerStep;
152288
152289  pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTableName,zStart,zEnd);
152290  if( pTriggerStep ){
152291    if( IN_RENAME_OBJECT ){
152292      pTriggerStep->pWhere = pWhere;
152293      pWhere = 0;
152294    }else{
152295      pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
152296    }
152297    pTriggerStep->orconf = OE_Default;
152298  }
152299  sqlite3ExprDelete(db, pWhere);
152300  return pTriggerStep;
152301}
152302
152303/*
152304** Recursively delete a Trigger structure
152305*/
152306SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
152307  if( pTrigger==0 || pTrigger->bReturning ) return;
152308  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
152309  sqlite3DbFree(db, pTrigger->zName);
152310  sqlite3DbFree(db, pTrigger->table);
152311  sqlite3ExprDelete(db, pTrigger->pWhen);
152312  sqlite3IdListDelete(db, pTrigger->pColumns);
152313  sqlite3DbFree(db, pTrigger);
152314}
152315
152316/*
152317** This function is called to drop a trigger from the database schema.
152318**
152319** This may be called directly from the parser and therefore identifies
152320** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
152321** same job as this routine except it takes a pointer to the trigger
152322** instead of the trigger name.
152323**/
152324SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
152325  Trigger *pTrigger = 0;
152326  int i;
152327  const char *zDb;
152328  const char *zName;
152329  sqlite3 *db = pParse->db;
152330
152331  if( db->mallocFailed ) goto drop_trigger_cleanup;
152332  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
152333    goto drop_trigger_cleanup;
152334  }
152335
152336  assert( pName->nSrc==1 );
152337  zDb = pName->a[0].zDatabase;
152338  zName = pName->a[0].zName;
152339  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
152340  for(i=OMIT_TEMPDB; i<db->nDb; i++){
152341    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
152342    if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
152343    assert( sqlite3SchemaMutexHeld(db, j, 0) );
152344    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
152345    if( pTrigger ) break;
152346  }
152347  if( !pTrigger ){
152348    if( !noErr ){
152349      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName->a);
152350    }else{
152351      sqlite3CodeVerifyNamedSchema(pParse, zDb);
152352    }
152353    pParse->checkSchema = 1;
152354    goto drop_trigger_cleanup;
152355  }
152356  sqlite3DropTriggerPtr(pParse, pTrigger);
152357
152358drop_trigger_cleanup:
152359  sqlite3SrcListDelete(db, pName);
152360}
152361
152362/*
152363** Return a pointer to the Table structure for the table that a trigger
152364** is set on.
152365*/
152366static Table *tableOfTrigger(Trigger *pTrigger){
152367  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
152368}
152369
152370
152371/*
152372** Drop a trigger given a pointer to that trigger.
152373*/
152374SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
152375  Table   *pTable;
152376  Vdbe *v;
152377  sqlite3 *db = pParse->db;
152378  int iDb;
152379
152380  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
152381  assert( iDb>=0 && iDb<db->nDb );
152382  pTable = tableOfTrigger(pTrigger);
152383  assert( (pTable && pTable->pSchema==pTrigger->pSchema) || iDb==1 );
152384#ifndef SQLITE_OMIT_AUTHORIZATION
152385  if( pTable ){
152386    int code = SQLITE_DROP_TRIGGER;
152387    const char *zDb = db->aDb[iDb].zDbSName;
152388    const char *zTab = SCHEMA_TABLE(iDb);
152389    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
152390    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
152391      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
152392      return;
152393    }
152394  }
152395#endif
152396
152397  /* Generate code to destroy the database record of the trigger.
152398  */
152399  if( (v = sqlite3GetVdbe(pParse))!=0 ){
152400    sqlite3NestedParse(pParse,
152401       "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='trigger'",
152402       db->aDb[iDb].zDbSName, pTrigger->zName
152403    );
152404    sqlite3ChangeCookie(pParse, iDb);
152405    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
152406  }
152407}
152408
152409/*
152410** Remove a trigger from the hash tables of the sqlite* pointer.
152411*/
152412SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
152413  Trigger *pTrigger;
152414  Hash *pHash;
152415
152416  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
152417  pHash = &(db->aDb[iDb].pSchema->trigHash);
152418  pTrigger = sqlite3HashInsert(pHash, zName, 0);
152419  if( ALWAYS(pTrigger) ){
152420    if( pTrigger->pSchema==pTrigger->pTabSchema ){
152421      Table *pTab = tableOfTrigger(pTrigger);
152422      if( pTab ){
152423        Trigger **pp;
152424        for(pp=&pTab->pTrigger; *pp; pp=&((*pp)->pNext)){
152425          if( *pp==pTrigger ){
152426            *pp = (*pp)->pNext;
152427            break;
152428          }
152429        }
152430      }
152431    }
152432    sqlite3DeleteTrigger(db, pTrigger);
152433    db->mDbFlags |= DBFLAG_SchemaChange;
152434  }
152435}
152436
152437/*
152438** pEList is the SET clause of an UPDATE statement.  Each entry
152439** in pEList is of the format <id>=<expr>.  If any of the entries
152440** in pEList have an <id> which matches an identifier in pIdList,
152441** then return TRUE.  If pIdList==NULL, then it is considered a
152442** wildcard that matches anything.  Likewise if pEList==NULL then
152443** it matches anything so always return true.  Return false only
152444** if there is no match.
152445*/
152446static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
152447  int e;
152448  if( pIdList==0 || NEVER(pEList==0) ) return 1;
152449  for(e=0; e<pEList->nExpr; e++){
152450    if( sqlite3IdListIndex(pIdList, pEList->a[e].zEName)>=0 ) return 1;
152451  }
152452  return 0;
152453}
152454
152455/*
152456** Return true if any TEMP triggers exist
152457*/
152458static int tempTriggersExist(sqlite3 *db){
152459  if( NEVER(db->aDb[1].pSchema==0) ) return 0;
152460  if( sqliteHashFirst(&db->aDb[1].pSchema->trigHash)==0 ) return 0;
152461  return 1;
152462}
152463
152464/*
152465** Return a list of all triggers on table pTab if there exists at least
152466** one trigger that must be fired when an operation of type 'op' is
152467** performed on the table, and, if that operation is an UPDATE, if at
152468** least one of the columns in pChanges is being modified.
152469*/
152470static SQLITE_NOINLINE Trigger *triggersReallyExist(
152471  Parse *pParse,          /* Parse context */
152472  Table *pTab,            /* The table the contains the triggers */
152473  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
152474  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
152475  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
152476){
152477  int mask = 0;
152478  Trigger *pList = 0;
152479  Trigger *p;
152480
152481  pList = sqlite3TriggerList(pParse, pTab);
152482  assert( pList==0 || IsVirtual(pTab)==0
152483           || (pList->bReturning && pList->pNext==0) );
152484  if( pList!=0 ){
152485    p = pList;
152486    if( (pParse->db->flags & SQLITE_EnableTrigger)==0
152487     && pTab->pTrigger!=0
152488    ){
152489      /* The SQLITE_DBCONFIG_ENABLE_TRIGGER setting is off.  That means that
152490      ** only TEMP triggers are allowed.  Truncate the pList so that it
152491      ** includes only TEMP triggers */
152492      if( pList==pTab->pTrigger ){
152493        pList = 0;
152494        goto exit_triggers_exist;
152495      }
152496      while( ALWAYS(p->pNext) && p->pNext!=pTab->pTrigger ) p = p->pNext;
152497      p->pNext = 0;
152498      p = pList;
152499    }
152500    do{
152501      if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
152502        mask |= p->tr_tm;
152503      }else if( p->op==TK_RETURNING ){
152504        /* The first time a RETURNING trigger is seen, the "op" value tells
152505        ** us what time of trigger it should be. */
152506        assert( sqlite3IsToplevel(pParse) );
152507        p->op = op;
152508        if( IsVirtual(pTab) ){
152509          if( op!=TK_INSERT ){
152510            sqlite3ErrorMsg(pParse,
152511              "%s RETURNING is not available on virtual tables",
152512              op==TK_DELETE ? "DELETE" : "UPDATE");
152513          }
152514          p->tr_tm = TRIGGER_BEFORE;
152515        }else{
152516          p->tr_tm = TRIGGER_AFTER;
152517        }
152518        mask |= p->tr_tm;
152519      }else if( p->bReturning && p->op==TK_INSERT && op==TK_UPDATE
152520                && sqlite3IsToplevel(pParse) ){
152521        /* Also fire a RETURNING trigger for an UPSERT */
152522        mask |= p->tr_tm;
152523      }
152524      p = p->pNext;
152525    }while( p );
152526  }
152527exit_triggers_exist:
152528  if( pMask ){
152529    *pMask = mask;
152530  }
152531  return (mask ? pList : 0);
152532}
152533SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
152534  Parse *pParse,          /* Parse context */
152535  Table *pTab,            /* The table the contains the triggers */
152536  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
152537  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
152538  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
152539){
152540  assert( pTab!=0 );
152541  if( (pTab->pTrigger==0 && !tempTriggersExist(pParse->db))
152542   || pParse->disableTriggers
152543  ){
152544    if( pMask ) *pMask = 0;
152545    return 0;
152546  }
152547  return triggersReallyExist(pParse,pTab,op,pChanges,pMask);
152548}
152549
152550/*
152551** Convert the pStep->zTarget string into a SrcList and return a pointer
152552** to that SrcList.
152553**
152554** This routine adds a specific database name, if needed, to the target when
152555** forming the SrcList.  This prevents a trigger in one database from
152556** referring to a target in another database.  An exception is when the
152557** trigger is in TEMP in which case it can refer to any other database it
152558** wants.
152559*/
152560SQLITE_PRIVATE SrcList *sqlite3TriggerStepSrc(
152561  Parse *pParse,       /* The parsing context */
152562  TriggerStep *pStep   /* The trigger containing the target token */
152563){
152564  sqlite3 *db = pParse->db;
152565  SrcList *pSrc;                  /* SrcList to be returned */
152566  char *zName = sqlite3DbStrDup(db, pStep->zTarget);
152567  pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
152568  assert( pSrc==0 || pSrc->nSrc==1 );
152569  assert( zName || pSrc==0 );
152570  if( pSrc ){
152571    Schema *pSchema = pStep->pTrig->pSchema;
152572    pSrc->a[0].zName = zName;
152573    if( pSchema!=db->aDb[1].pSchema ){
152574      pSrc->a[0].pSchema = pSchema;
152575    }
152576    if( pStep->pFrom ){
152577      SrcList *pDup = sqlite3SrcListDup(db, pStep->pFrom, 0);
152578      if( pDup && pDup->nSrc>1 && !IN_RENAME_OBJECT ){
152579        Select *pSubquery;
152580        Token as;
152581        pSubquery = sqlite3SelectNew(pParse,0,pDup,0,0,0,0,SF_NestedFrom,0);
152582        as.n = 0;
152583        as.z = 0;
152584        pDup = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&as,pSubquery,0);
152585      }
152586      pSrc = sqlite3SrcListAppendList(pParse, pSrc, pDup);
152587    }
152588  }else{
152589    sqlite3DbFree(db, zName);
152590  }
152591  return pSrc;
152592}
152593
152594/*
152595** Return true if the pExpr term from the RETURNING clause argument
152596** list is of the form "*".  Raise an error if the terms if of the
152597** form "table.*".
152598*/
152599static int isAsteriskTerm(
152600  Parse *pParse,      /* Parsing context */
152601  Expr *pTerm         /* A term in the RETURNING clause */
152602){
152603  assert( pTerm!=0 );
152604  if( pTerm->op==TK_ASTERISK ) return 1;
152605  if( pTerm->op!=TK_DOT ) return 0;
152606  assert( pTerm->pRight!=0 );
152607  assert( pTerm->pLeft!=0 );
152608  if( pTerm->pRight->op!=TK_ASTERISK ) return 0;
152609  sqlite3ErrorMsg(pParse, "RETURNING may not use \"TABLE.*\" wildcards");
152610  return 1;
152611}
152612
152613/* The input list pList is the list of result set terms from a RETURNING
152614** clause.  The table that we are returning from is pTab.
152615**
152616** This routine makes a copy of the pList, and at the same time expands
152617** any "*" wildcards to be the complete set of columns from pTab.
152618*/
152619static ExprList *sqlite3ExpandReturning(
152620  Parse *pParse,        /* Parsing context */
152621  ExprList *pList,      /* The arguments to RETURNING */
152622  Table *pTab           /* The table being updated */
152623){
152624  ExprList *pNew = 0;
152625  sqlite3 *db = pParse->db;
152626  int i;
152627
152628  for(i=0; i<pList->nExpr; i++){
152629    Expr *pOldExpr = pList->a[i].pExpr;
152630    if( NEVER(pOldExpr==0) ) continue;
152631    if( isAsteriskTerm(pParse, pOldExpr) ){
152632      int jj;
152633      for(jj=0; jj<pTab->nCol; jj++){
152634        Expr *pNewExpr;
152635        if( IsHiddenColumn(pTab->aCol+jj) ) continue;
152636        pNewExpr = sqlite3Expr(db, TK_ID, pTab->aCol[jj].zCnName);
152637        pNew = sqlite3ExprListAppend(pParse, pNew, pNewExpr);
152638        if( !db->mallocFailed ){
152639          struct ExprList_item *pItem = &pNew->a[pNew->nExpr-1];
152640          pItem->zEName = sqlite3DbStrDup(db, pTab->aCol[jj].zCnName);
152641          pItem->fg.eEName = ENAME_NAME;
152642        }
152643      }
152644    }else{
152645      Expr *pNewExpr = sqlite3ExprDup(db, pOldExpr, 0);
152646      pNew = sqlite3ExprListAppend(pParse, pNew, pNewExpr);
152647      if( !db->mallocFailed && ALWAYS(pList->a[i].zEName!=0) ){
152648        struct ExprList_item *pItem = &pNew->a[pNew->nExpr-1];
152649        pItem->zEName = sqlite3DbStrDup(db, pList->a[i].zEName);
152650        pItem->fg.eEName = pList->a[i].fg.eEName;
152651      }
152652    }
152653  }
152654  return pNew;
152655}
152656
152657/* If the Expr node is a subquery or an EXISTS operator or an IN operator that
152658** uses a subquery, and if the subquery is SF_Correlated, then mark the
152659** expression as EP_VarSelect.
152660*/
152661static int sqlite3ReturningSubqueryVarSelect(Walker *NotUsed, Expr *pExpr){
152662  UNUSED_PARAMETER(NotUsed);
152663  if( ExprUseXSelect(pExpr)
152664   && (pExpr->x.pSelect->selFlags & SF_Correlated)!=0
152665  ){
152666    testcase( ExprHasProperty(pExpr, EP_VarSelect) );
152667    ExprSetProperty(pExpr, EP_VarSelect);
152668  }
152669  return WRC_Continue;
152670}
152671
152672
152673/*
152674** If the SELECT references the table pWalker->u.pTab, then do two things:
152675**
152676**    (1) Mark the SELECT as as SF_Correlated.
152677**    (2) Set pWalker->eCode to non-zero so that the caller will know
152678**        that (1) has happened.
152679*/
152680static int sqlite3ReturningSubqueryCorrelated(Walker *pWalker, Select *pSelect){
152681  int i;
152682  SrcList *pSrc;
152683  assert( pSelect!=0 );
152684  pSrc = pSelect->pSrc;
152685  assert( pSrc!=0 );
152686  for(i=0; i<pSrc->nSrc; i++){
152687    if( pSrc->a[i].pTab==pWalker->u.pTab ){
152688      testcase( pSelect->selFlags & SF_Correlated );
152689      pSelect->selFlags |= SF_Correlated;
152690      pWalker->eCode = 1;
152691      break;
152692    }
152693  }
152694  return WRC_Continue;
152695}
152696
152697/*
152698** Scan the expression list that is the argument to RETURNING looking
152699** for subqueries that depend on the table which is being modified in the
152700** statement that is hosting the RETURNING clause (pTab).  Mark all such
152701** subqueries as SF_Correlated.  If the subqueries are part of an
152702** expression, mark the expression as EP_VarSelect.
152703**
152704** https://sqlite.org/forum/forumpost/2c83569ce8945d39
152705*/
152706static void sqlite3ProcessReturningSubqueries(
152707  ExprList *pEList,
152708  Table *pTab
152709){
152710  Walker w;
152711  memset(&w, 0, sizeof(w));
152712  w.xExprCallback = sqlite3ExprWalkNoop;
152713  w.xSelectCallback = sqlite3ReturningSubqueryCorrelated;
152714  w.u.pTab = pTab;
152715  sqlite3WalkExprList(&w, pEList);
152716  if( w.eCode ){
152717    w.xExprCallback = sqlite3ReturningSubqueryVarSelect;
152718    w.xSelectCallback = sqlite3SelectWalkNoop;
152719    sqlite3WalkExprList(&w, pEList);
152720  }
152721}
152722
152723/*
152724** Generate code for the RETURNING trigger.  Unlike other triggers
152725** that invoke a subprogram in the bytecode, the code for RETURNING
152726** is generated in-line.
152727*/
152728static void codeReturningTrigger(
152729  Parse *pParse,       /* Parse context */
152730  Trigger *pTrigger,   /* The trigger step that defines the RETURNING */
152731  Table *pTab,         /* The table to code triggers from */
152732  int regIn            /* The first in an array of registers */
152733){
152734  Vdbe *v = pParse->pVdbe;
152735  sqlite3 *db = pParse->db;
152736  ExprList *pNew;
152737  Returning *pReturning;
152738  Select sSelect;
152739  SrcList sFrom;
152740
152741  assert( v!=0 );
152742  if( !pParse->bReturning ){
152743    /* This RETURNING trigger must be for a different statement as
152744    ** this statement lacks a RETURNING clause. */
152745    return;
152746  }
152747  assert( db->pParse==pParse );
152748  pReturning = pParse->u1.pReturning;
152749  if( pTrigger != &(pReturning->retTrig) ){
152750    /* This RETURNING trigger is for a different statement */
152751    return;
152752  }
152753  memset(&sSelect, 0, sizeof(sSelect));
152754  memset(&sFrom, 0, sizeof(sFrom));
152755  sSelect.pEList = sqlite3ExprListDup(db, pReturning->pReturnEL, 0);
152756  sSelect.pSrc = &sFrom;
152757  sFrom.nSrc = 1;
152758  sFrom.a[0].pTab = pTab;
152759  sFrom.a[0].zName = pTab->zName; /* tag-20240424-1 */
152760  sFrom.a[0].iCursor = -1;
152761  sqlite3SelectPrep(pParse, &sSelect, 0);
152762  if( pParse->nErr==0 ){
152763    assert( db->mallocFailed==0 );
152764    sqlite3GenerateColumnNames(pParse, &sSelect);
152765  }
152766  sqlite3ExprListDelete(db, sSelect.pEList);
152767  pNew = sqlite3ExpandReturning(pParse, pReturning->pReturnEL, pTab);
152768  if( pParse->nErr==0 ){
152769    NameContext sNC;
152770    memset(&sNC, 0, sizeof(sNC));
152771    if( pReturning->nRetCol==0 ){
152772      pReturning->nRetCol = pNew->nExpr;
152773      pReturning->iRetCur = pParse->nTab++;
152774    }
152775    sNC.pParse = pParse;
152776    sNC.uNC.iBaseReg = regIn;
152777    sNC.ncFlags = NC_UBaseReg;
152778    pParse->eTriggerOp = pTrigger->op;
152779    pParse->pTriggerTab = pTab;
152780    if( sqlite3ResolveExprListNames(&sNC, pNew)==SQLITE_OK
152781     && ALWAYS(!db->mallocFailed)
152782    ){
152783      int i;
152784      int nCol = pNew->nExpr;
152785      int reg = pParse->nMem+1;
152786      sqlite3ProcessReturningSubqueries(pNew, pTab);
152787      pParse->nMem += nCol+2;
152788      pReturning->iRetReg = reg;
152789      for(i=0; i<nCol; i++){
152790        Expr *pCol = pNew->a[i].pExpr;
152791        assert( pCol!=0 ); /* Due to !db->mallocFailed ~9 lines above */
152792        sqlite3ExprCodeFactorable(pParse, pCol, reg+i);
152793        if( sqlite3ExprAffinity(pCol)==SQLITE_AFF_REAL ){
152794          sqlite3VdbeAddOp1(v, OP_RealAffinity, reg+i);
152795        }
152796      }
152797      sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, i, reg+i);
152798      sqlite3VdbeAddOp2(v, OP_NewRowid, pReturning->iRetCur, reg+i+1);
152799      sqlite3VdbeAddOp3(v, OP_Insert, pReturning->iRetCur, reg+i, reg+i+1);
152800    }
152801  }
152802  sqlite3ExprListDelete(db, pNew);
152803  pParse->eTriggerOp = 0;
152804  pParse->pTriggerTab = 0;
152805}
152806
152807
152808
152809/*
152810** Generate VDBE code for the statements inside the body of a single
152811** trigger.
152812*/
152813static int codeTriggerProgram(
152814  Parse *pParse,            /* The parser context */
152815  TriggerStep *pStepList,   /* List of statements inside the trigger body */
152816  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
152817){
152818  TriggerStep *pStep;
152819  Vdbe *v = pParse->pVdbe;
152820  sqlite3 *db = pParse->db;
152821
152822  assert( pParse->pTriggerTab && pParse->pToplevel );
152823  assert( pStepList );
152824  assert( v!=0 );
152825  for(pStep=pStepList; pStep; pStep=pStep->pNext){
152826    /* Figure out the ON CONFLICT policy that will be used for this step
152827    ** of the trigger program. If the statement that caused this trigger
152828    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
152829    ** the ON CONFLICT policy that was specified as part of the trigger
152830    ** step statement. Example:
152831    **
152832    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
152833    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
152834    **   END;
152835    **
152836    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
152837    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
152838    */
152839    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
152840    assert( pParse->okConstFactor==0 );
152841
152842#ifndef SQLITE_OMIT_TRACE
152843    if( pStep->zSpan ){
152844      sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0,
152845                        sqlite3MPrintf(db, "-- %s", pStep->zSpan),
152846                        P4_DYNAMIC);
152847    }
152848#endif
152849
152850    switch( pStep->op ){
152851      case TK_UPDATE: {
152852        sqlite3Update(pParse,
152853          sqlite3TriggerStepSrc(pParse, pStep),
152854          sqlite3ExprListDup(db, pStep->pExprList, 0),
152855          sqlite3ExprDup(db, pStep->pWhere, 0),
152856          pParse->eOrconf, 0, 0, 0
152857        );
152858        sqlite3VdbeAddOp0(v, OP_ResetCount);
152859        break;
152860      }
152861      case TK_INSERT: {
152862        sqlite3Insert(pParse,
152863          sqlite3TriggerStepSrc(pParse, pStep),
152864          sqlite3SelectDup(db, pStep->pSelect, 0),
152865          sqlite3IdListDup(db, pStep->pIdList),
152866          pParse->eOrconf,
152867          sqlite3UpsertDup(db, pStep->pUpsert)
152868        );
152869        sqlite3VdbeAddOp0(v, OP_ResetCount);
152870        break;
152871      }
152872      case TK_DELETE: {
152873        sqlite3DeleteFrom(pParse,
152874          sqlite3TriggerStepSrc(pParse, pStep),
152875          sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
152876        );
152877        sqlite3VdbeAddOp0(v, OP_ResetCount);
152878        break;
152879      }
152880      default: assert( pStep->op==TK_SELECT ); {
152881        SelectDest sDest;
152882        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
152883        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
152884        sqlite3Select(pParse, pSelect, &sDest);
152885        sqlite3SelectDelete(db, pSelect);
152886        break;
152887      }
152888    }
152889  }
152890
152891  return 0;
152892}
152893
152894#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
152895/*
152896** This function is used to add VdbeComment() annotations to a VDBE
152897** program. It is not used in production code, only for debugging.
152898*/
152899static const char *onErrorText(int onError){
152900  switch( onError ){
152901    case OE_Abort:    return "abort";
152902    case OE_Rollback: return "rollback";
152903    case OE_Fail:     return "fail";
152904    case OE_Replace:  return "replace";
152905    case OE_Ignore:   return "ignore";
152906    case OE_Default:  return "default";
152907  }
152908  return "n/a";
152909}
152910#endif
152911
152912/*
152913** Parse context structure pFrom has just been used to create a sub-vdbe
152914** (trigger program). If an error has occurred, transfer error information
152915** from pFrom to pTo.
152916*/
152917static void transferParseError(Parse *pTo, Parse *pFrom){
152918  assert( pFrom->zErrMsg==0 || pFrom->nErr );
152919  assert( pTo->zErrMsg==0 || pTo->nErr );
152920  if( pTo->nErr==0 ){
152921    pTo->zErrMsg = pFrom->zErrMsg;
152922    pTo->nErr = pFrom->nErr;
152923    pTo->rc = pFrom->rc;
152924  }else{
152925    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
152926  }
152927}
152928
152929/*
152930** Create and populate a new TriggerPrg object with a sub-program
152931** implementing trigger pTrigger with ON CONFLICT policy orconf.
152932*/
152933static TriggerPrg *codeRowTrigger(
152934  Parse *pParse,       /* Current parse context */
152935  Trigger *pTrigger,   /* Trigger to code */
152936  Table *pTab,         /* The table pTrigger is attached to */
152937  int orconf           /* ON CONFLICT policy to code trigger program with */
152938){
152939  Parse *pTop = sqlite3ParseToplevel(pParse);
152940  sqlite3 *db = pParse->db;   /* Database handle */
152941  TriggerPrg *pPrg;           /* Value to return */
152942  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
152943  Vdbe *v;                    /* Temporary VM */
152944  NameContext sNC;            /* Name context for sub-vdbe */
152945  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
152946  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
152947  Parse sSubParse;            /* Parse context for sub-vdbe */
152948
152949  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
152950  assert( pTop->pVdbe );
152951
152952  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
152953  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
152954  ** list of the top-level Parse object sooner rather than later.  */
152955  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
152956  if( !pPrg ) return 0;
152957  pPrg->pNext = pTop->pTriggerPrg;
152958  pTop->pTriggerPrg = pPrg;
152959  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
152960  if( !pProgram ) return 0;
152961  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
152962  pPrg->pTrigger = pTrigger;
152963  pPrg->orconf = orconf;
152964  pPrg->aColmask[0] = 0xffffffff;
152965  pPrg->aColmask[1] = 0xffffffff;
152966
152967  /* Allocate and populate a new Parse context to use for coding the
152968  ** trigger sub-program.  */
152969  sqlite3ParseObjectInit(&sSubParse, db);
152970  memset(&sNC, 0, sizeof(sNC));
152971  sNC.pParse = &sSubParse;
152972  sSubParse.pTriggerTab = pTab;
152973  sSubParse.pToplevel = pTop;
152974  sSubParse.zAuthContext = pTrigger->zName;
152975  sSubParse.eTriggerOp = pTrigger->op;
152976  sSubParse.nQueryLoop = pParse->nQueryLoop;
152977  sSubParse.prepFlags = pParse->prepFlags;
152978
152979  v = sqlite3GetVdbe(&sSubParse);
152980  if( v ){
152981    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
152982      pTrigger->zName, onErrorText(orconf),
152983      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
152984        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
152985        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
152986        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
152987      pTab->zName
152988    ));
152989#ifndef SQLITE_OMIT_TRACE
152990    if( pTrigger->zName ){
152991      sqlite3VdbeChangeP4(v, -1,
152992        sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
152993      );
152994    }
152995#endif
152996
152997    /* If one was specified, code the WHEN clause. If it evaluates to false
152998    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
152999    ** OP_Halt inserted at the end of the program.  */
153000    if( pTrigger->pWhen ){
153001      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
153002      if( db->mallocFailed==0
153003       && SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
153004      ){
153005        iEndTrigger = sqlite3VdbeMakeLabel(&sSubParse);
153006        sqlite3ExprIfFalse(&sSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
153007      }
153008      sqlite3ExprDelete(db, pWhen);
153009    }
153010
153011    /* Code the trigger program into the sub-vdbe. */
153012    codeTriggerProgram(&sSubParse, pTrigger->step_list, orconf);
153013
153014    /* Insert an OP_Halt at the end of the sub-program. */
153015    if( iEndTrigger ){
153016      sqlite3VdbeResolveLabel(v, iEndTrigger);
153017    }
153018    sqlite3VdbeAddOp0(v, OP_Halt);
153019    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
153020    transferParseError(pParse, &sSubParse);
153021
153022    if( pParse->nErr==0 ){
153023      assert( db->mallocFailed==0 );
153024      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
153025    }
153026    pProgram->nMem = sSubParse.nMem;
153027    pProgram->nCsr = sSubParse.nTab;
153028    pProgram->token = (void *)pTrigger;
153029    pPrg->aColmask[0] = sSubParse.oldmask;
153030    pPrg->aColmask[1] = sSubParse.newmask;
153031    sqlite3VdbeDelete(v);
153032  }else{
153033    transferParseError(pParse, &sSubParse);
153034  }
153035
153036  assert( !sSubParse.pTriggerPrg && !sSubParse.nMaxArg );
153037  sqlite3ParseObjectReset(&sSubParse);
153038  return pPrg;
153039}
153040
153041/*
153042** Return a pointer to a TriggerPrg object containing the sub-program for
153043** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
153044** TriggerPrg object exists, a new object is allocated and populated before
153045** being returned.
153046*/
153047static TriggerPrg *getRowTrigger(
153048  Parse *pParse,       /* Current parse context */
153049  Trigger *pTrigger,   /* Trigger to code */
153050  Table *pTab,         /* The table trigger pTrigger is attached to */
153051  int orconf           /* ON CONFLICT algorithm. */
153052){
153053  Parse *pRoot = sqlite3ParseToplevel(pParse);
153054  TriggerPrg *pPrg;
153055
153056  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
153057
153058  /* It may be that this trigger has already been coded (or is in the
153059  ** process of being coded). If this is the case, then an entry with
153060  ** a matching TriggerPrg.pTrigger field will be present somewhere
153061  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
153062  for(pPrg=pRoot->pTriggerPrg;
153063      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
153064      pPrg=pPrg->pNext
153065  );
153066
153067  /* If an existing TriggerPrg could not be located, create a new one. */
153068  if( !pPrg ){
153069    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
153070    pParse->db->errByteOffset = -1;
153071  }
153072
153073  return pPrg;
153074}
153075
153076/*
153077** Generate code for the trigger program associated with trigger p on
153078** table pTab. The reg, orconf and ignoreJump parameters passed to this
153079** function are the same as those described in the header function for
153080** sqlite3CodeRowTrigger()
153081*/
153082SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
153083  Parse *pParse,       /* Parse context */
153084  Trigger *p,          /* Trigger to code */
153085  Table *pTab,         /* The table to code triggers from */
153086  int reg,             /* Reg array containing OLD.* and NEW.* values */
153087  int orconf,          /* ON CONFLICT policy */
153088  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
153089){
153090  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
153091  TriggerPrg *pPrg;
153092  pPrg = getRowTrigger(pParse, p, pTab, orconf);
153093  assert( pPrg || pParse->nErr );
153094
153095  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
153096  ** is a pointer to the sub-vdbe containing the trigger program.  */
153097  if( pPrg ){
153098    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
153099
153100    sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
153101                      (const char *)pPrg->pProgram, P4_SUBPROGRAM);
153102    VdbeComment(
153103        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
153104
153105    /* Set the P5 operand of the OP_Program instruction to non-zero if
153106    ** recursive invocation of this trigger program is disallowed. Recursive
153107    ** invocation is disallowed if (a) the sub-program is really a trigger,
153108    ** not a foreign key action, and (b) the flag to enable recursive triggers
153109    ** is clear.  */
153110    sqlite3VdbeChangeP5(v, (u8)bRecursive);
153111  }
153112}
153113
153114/*
153115** This is called to code the required FOR EACH ROW triggers for an operation
153116** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
153117** is given by the op parameter. The tr_tm parameter determines whether the
153118** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
153119** parameter pChanges is passed the list of columns being modified.
153120**
153121** If there are no triggers that fire at the specified time for the specified
153122** operation on pTab, this function is a no-op.
153123**
153124** The reg argument is the address of the first in an array of registers
153125** that contain the values substituted for the new.* and old.* references
153126** in the trigger program. If N is the number of columns in table pTab
153127** (a copy of pTab->nCol), then registers are populated as follows:
153128**
153129**   Register       Contains
153130**   ------------------------------------------------------
153131**   reg+0          OLD.rowid
153132**   reg+1          OLD.* value of left-most column of pTab
153133**   ...            ...
153134**   reg+N          OLD.* value of right-most column of pTab
153135**   reg+N+1        NEW.rowid
153136**   reg+N+2        NEW.* value of left-most column of pTab
153137**   ...            ...
153138**   reg+N+N+1      NEW.* value of right-most column of pTab
153139**
153140** For ON DELETE triggers, the registers containing the NEW.* values will
153141** never be accessed by the trigger program, so they are not allocated or
153142** populated by the caller (there is no data to populate them with anyway).
153143** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
153144** are never accessed, and so are not allocated by the caller. So, for an
153145** ON INSERT trigger, the value passed to this function as parameter reg
153146** is not a readable register, although registers (reg+N) through
153147** (reg+N+N+1) are.
153148**
153149** Parameter orconf is the default conflict resolution algorithm for the
153150** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
153151** is the instruction that control should jump to if a trigger program
153152** raises an IGNORE exception.
153153*/
153154SQLITE_PRIVATE void sqlite3CodeRowTrigger(
153155  Parse *pParse,       /* Parse context */
153156  Trigger *pTrigger,   /* List of triggers on table pTab */
153157  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
153158  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
153159  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
153160  Table *pTab,         /* The table to code triggers from */
153161  int reg,             /* The first in an array of registers (see above) */
153162  int orconf,          /* ON CONFLICT policy */
153163  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
153164){
153165  Trigger *p;          /* Used to iterate through pTrigger list */
153166
153167  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
153168  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
153169  assert( (op==TK_UPDATE)==(pChanges!=0) );
153170
153171  for(p=pTrigger; p; p=p->pNext){
153172
153173    /* Sanity checking:  The schema for the trigger and for the table are
153174    ** always defined.  The trigger must be in the same schema as the table
153175    ** or else it must be a TEMP trigger. */
153176    assert( p->pSchema!=0 );
153177    assert( p->pTabSchema!=0 );
153178    assert( p->pSchema==p->pTabSchema
153179         || p->pSchema==pParse->db->aDb[1].pSchema );
153180
153181    /* Determine whether we should code this trigger.  One of two choices:
153182    **   1. The trigger is an exact match to the current DML statement
153183    **   2. This is a RETURNING trigger for INSERT but we are currently
153184    **      doing the UPDATE part of an UPSERT.
153185    */
153186    if( (p->op==op || (p->bReturning && p->op==TK_INSERT && op==TK_UPDATE))
153187     && p->tr_tm==tr_tm
153188     && checkColumnOverlap(p->pColumns, pChanges)
153189    ){
153190      if( !p->bReturning ){
153191        sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
153192      }else if( sqlite3IsToplevel(pParse) ){
153193        codeReturningTrigger(pParse, p, pTab, reg);
153194      }
153195    }
153196  }
153197}
153198
153199/*
153200** Triggers may access values stored in the old.* or new.* pseudo-table.
153201** This function returns a 32-bit bitmask indicating which columns of the
153202** old.* or new.* tables actually are used by triggers. This information
153203** may be used by the caller, for example, to avoid having to load the entire
153204** old.* record into memory when executing an UPDATE or DELETE command.
153205**
153206** Bit 0 of the returned mask is set if the left-most column of the
153207** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
153208** the second leftmost column value is required, and so on. If there
153209** are more than 32 columns in the table, and at least one of the columns
153210** with an index greater than 32 may be accessed, 0xffffffff is returned.
153211**
153212** It is not possible to determine if the old.rowid or new.rowid column is
153213** accessed by triggers. The caller must always assume that it is.
153214**
153215** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
153216** applies to the old.* table. If 1, the new.* table.
153217**
153218** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
153219** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
153220** included in the returned mask if the TRIGGER_BEFORE bit is set in the
153221** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
153222** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
153223*/
153224SQLITE_PRIVATE u32 sqlite3TriggerColmask(
153225  Parse *pParse,       /* Parse context */
153226  Trigger *pTrigger,   /* List of triggers on table pTab */
153227  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
153228  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
153229  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
153230  Table *pTab,         /* The table to code triggers from */
153231  int orconf           /* Default ON CONFLICT policy for trigger steps */
153232){
153233  const int op = pChanges ? TK_UPDATE : TK_DELETE;
153234  u32 mask = 0;
153235  Trigger *p;
153236
153237  assert( isNew==1 || isNew==0 );
153238  if( IsView(pTab) ){
153239    return 0xffffffff;
153240  }
153241  for(p=pTrigger; p; p=p->pNext){
153242    if( p->op==op
153243     && (tr_tm&p->tr_tm)
153244     && checkColumnOverlap(p->pColumns,pChanges)
153245    ){
153246      if( p->bReturning ){
153247        mask = 0xffffffff;
153248      }else{
153249        TriggerPrg *pPrg;
153250        pPrg = getRowTrigger(pParse, p, pTab, orconf);
153251        if( pPrg ){
153252          mask |= pPrg->aColmask[isNew];
153253        }
153254      }
153255    }
153256  }
153257
153258  return mask;
153259}
153260
153261#endif /* !defined(SQLITE_OMIT_TRIGGER) */
153262
153263/************** End of trigger.c *********************************************/
153264/************** Begin file update.c ******************************************/
153265/*
153266** 2001 September 15
153267**
153268** The author disclaims copyright to this source code.  In place of
153269** a legal notice, here is a blessing:
153270**
153271**    May you do good and not evil.
153272**    May you find forgiveness for yourself and forgive others.
153273**    May you share freely, never taking more than you give.
153274**
153275*************************************************************************
153276** This file contains C code routines that are called by the parser
153277** to handle UPDATE statements.
153278*/
153279/* #include "sqliteInt.h" */
153280
153281#ifndef SQLITE_OMIT_VIRTUALTABLE
153282/* Forward declaration */
153283static void updateVirtualTable(
153284  Parse *pParse,       /* The parsing context */
153285  SrcList *pSrc,       /* The virtual table to be modified */
153286  Table *pTab,         /* The virtual table */
153287  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
153288  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
153289  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
153290  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
153291  int onError          /* ON CONFLICT strategy */
153292);
153293#endif /* SQLITE_OMIT_VIRTUALTABLE */
153294
153295/*
153296** The most recently coded instruction was an OP_Column to retrieve the
153297** i-th column of table pTab. This routine sets the P4 parameter of the
153298** OP_Column to the default value, if any.
153299**
153300** The default value of a column is specified by a DEFAULT clause in the
153301** column definition. This was either supplied by the user when the table
153302** was created, or added later to the table definition by an ALTER TABLE
153303** command. If the latter, then the row-records in the table btree on disk
153304** may not contain a value for the column and the default value, taken
153305** from the P4 parameter of the OP_Column instruction, is returned instead.
153306** If the former, then all row-records are guaranteed to include a value
153307** for the column and the P4 value is not required.
153308**
153309** Column definitions created by an ALTER TABLE command may only have
153310** literal default values specified: a number, null or a string. (If a more
153311** complicated default expression value was provided, it is evaluated
153312** when the ALTER TABLE is executed and one of the literal values written
153313** into the sqlite_schema table.)
153314**
153315** Therefore, the P4 parameter is only required if the default value for
153316** the column is a literal number, string or null. The sqlite3ValueFromExpr()
153317** function is capable of transforming these types of expressions into
153318** sqlite3_value objects.
153319**
153320** If column as REAL affinity and the table is an ordinary b-tree table
153321** (not a virtual table) then the value might have been stored as an
153322** integer.  In that case, add an OP_RealAffinity opcode to make sure
153323** it has been converted into REAL.
153324*/
153325SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
153326  Column *pCol;
153327  assert( pTab!=0 );
153328  assert( pTab->nCol>i );
153329  pCol = &pTab->aCol[i];
153330  if( pCol->iDflt ){
153331    sqlite3_value *pValue = 0;
153332    u8 enc = ENC(sqlite3VdbeDb(v));
153333    assert( !IsView(pTab) );
153334    VdbeComment((v, "%s.%s", pTab->zName, pCol->zCnName));
153335    assert( i<pTab->nCol );
153336    sqlite3ValueFromExpr(sqlite3VdbeDb(v),
153337                         sqlite3ColumnExpr(pTab,pCol), enc,
153338                         pCol->affinity, &pValue);
153339    if( pValue ){
153340      sqlite3VdbeAppendP4(v, pValue, P4_MEM);
153341    }
153342  }
153343#ifndef SQLITE_OMIT_FLOATING_POINT
153344  if( pCol->affinity==SQLITE_AFF_REAL && !IsVirtual(pTab) ){
153345    sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
153346  }
153347#endif
153348}
153349
153350/*
153351** Check to see if column iCol of index pIdx references any of the
153352** columns defined by aXRef and chngRowid.  Return true if it does
153353** and false if not.  This is an optimization.  False-positives are a
153354** performance degradation, but false-negatives can result in a corrupt
153355** index and incorrect answers.
153356**
153357** aXRef[j] will be non-negative if column j of the original table is
153358** being updated.  chngRowid will be true if the rowid of the table is
153359** being updated.
153360*/
153361static int indexColumnIsBeingUpdated(
153362  Index *pIdx,      /* The index to check */
153363  int iCol,         /* Which column of the index to check */
153364  int *aXRef,       /* aXRef[j]>=0 if column j is being updated */
153365  int chngRowid     /* true if the rowid is being updated */
153366){
153367  i16 iIdxCol = pIdx->aiColumn[iCol];
153368  assert( iIdxCol!=XN_ROWID ); /* Cannot index rowid */
153369  if( iIdxCol>=0 ){
153370    return aXRef[iIdxCol]>=0;
153371  }
153372  assert( iIdxCol==XN_EXPR );
153373  assert( pIdx->aColExpr!=0 );
153374  assert( pIdx->aColExpr->a[iCol].pExpr!=0 );
153375  return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr,
153376                                            aXRef,chngRowid);
153377}
153378
153379/*
153380** Check to see if index pIdx is a partial index whose conditional
153381** expression might change values due to an UPDATE.  Return true if
153382** the index is subject to change and false if the index is guaranteed
153383** to be unchanged.  This is an optimization.  False-positives are a
153384** performance degradation, but false-negatives can result in a corrupt
153385** index and incorrect answers.
153386**
153387** aXRef[j] will be non-negative if column j of the original table is
153388** being updated.  chngRowid will be true if the rowid of the table is
153389** being updated.
153390*/
153391static int indexWhereClauseMightChange(
153392  Index *pIdx,      /* The index to check */
153393  int *aXRef,       /* aXRef[j]>=0 if column j is being updated */
153394  int chngRowid     /* true if the rowid is being updated */
153395){
153396  if( pIdx->pPartIdxWhere==0 ) return 0;
153397  return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere,
153398                                            aXRef, chngRowid);
153399}
153400
153401/*
153402** Allocate and return a pointer to an expression of type TK_ROW with
153403** Expr.iColumn set to value (iCol+1). The resolver will modify the
153404** expression to be a TK_COLUMN reading column iCol of the first
153405** table in the source-list (pSrc->a[0]).
153406*/
153407static Expr *exprRowColumn(Parse *pParse, int iCol){
153408  Expr *pRet = sqlite3PExpr(pParse, TK_ROW, 0, 0);
153409  if( pRet ) pRet->iColumn = iCol+1;
153410  return pRet;
153411}
153412
153413/*
153414** Assuming both the pLimit and pOrderBy parameters are NULL, this function
153415** generates VM code to run the query:
153416**
153417**   SELECT <other-columns>, pChanges FROM pTabList WHERE pWhere
153418**
153419** and write the results to the ephemeral table already opened as cursor
153420** iEph. None of pChanges, pTabList or pWhere are modified or consumed by
153421** this function, they must be deleted by the caller.
153422**
153423** Or, if pLimit and pOrderBy are not NULL, and pTab is not a view:
153424**
153425**   SELECT <other-columns>, pChanges FROM pTabList
153426**   WHERE pWhere
153427**   GROUP BY <other-columns>
153428**   ORDER BY pOrderBy LIMIT pLimit
153429**
153430** If pTab is a view, the GROUP BY clause is omitted.
153431**
153432** Exactly how results are written to table iEph, and exactly what
153433** the <other-columns> in the query above are is determined by the type
153434** of table pTabList->a[0].pTab.
153435**
153436** If the table is a WITHOUT ROWID table, then argument pPk must be its
153437** PRIMARY KEY. In this case <other-columns> are the primary key columns
153438** of the table, in order. The results of the query are written to ephemeral
153439** table iEph as index keys, using OP_IdxInsert.
153440**
153441** If the table is actually a view, then <other-columns> are all columns of
153442** the view. The results are written to the ephemeral table iEph as records
153443** with automatically assigned integer keys.
153444**
153445** If the table is a virtual or ordinary intkey table, then <other-columns>
153446** is its rowid. For a virtual table, the results are written to iEph as
153447** records with automatically assigned integer keys For intkey tables, the
153448** rowid value in <other-columns> is used as the integer key, and the
153449** remaining fields make up the table record.
153450*/
153451static void updateFromSelect(
153452  Parse *pParse,                  /* Parse context */
153453  int iEph,                       /* Cursor for open eph. table */
153454  Index *pPk,                     /* PK if table 0 is WITHOUT ROWID */
153455  ExprList *pChanges,             /* List of expressions to return */
153456  SrcList *pTabList,              /* List of tables to select from */
153457  Expr *pWhere,                   /* WHERE clause for query */
153458  ExprList *pOrderBy,             /* ORDER BY clause */
153459  Expr *pLimit                    /* LIMIT clause */
153460){
153461  int i;
153462  SelectDest dest;
153463  Select *pSelect = 0;
153464  ExprList *pList = 0;
153465  ExprList *pGrp = 0;
153466  Expr *pLimit2 = 0;
153467  ExprList *pOrderBy2 = 0;
153468  sqlite3 *db = pParse->db;
153469  Table *pTab = pTabList->a[0].pTab;
153470  SrcList *pSrc;
153471  Expr *pWhere2;
153472  int eDest;
153473
153474#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
153475  if( pOrderBy && pLimit==0 ) {
153476    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on UPDATE");
153477    return;
153478  }
153479  pOrderBy2 = sqlite3ExprListDup(db, pOrderBy, 0);
153480  pLimit2 = sqlite3ExprDup(db, pLimit, 0);
153481#else
153482  UNUSED_PARAMETER(pOrderBy);
153483  UNUSED_PARAMETER(pLimit);
153484#endif
153485
153486  pSrc = sqlite3SrcListDup(db, pTabList, 0);
153487  pWhere2 = sqlite3ExprDup(db, pWhere, 0);
153488
153489  assert( pTabList->nSrc>1 );
153490  if( pSrc ){
153491    assert( pSrc->a[0].fg.notCte );
153492    pSrc->a[0].iCursor = -1;
153493    pSrc->a[0].pTab->nTabRef--;
153494    pSrc->a[0].pTab = 0;
153495  }
153496  if( pPk ){
153497    for(i=0; i<pPk->nKeyCol; i++){
153498      Expr *pNew = exprRowColumn(pParse, pPk->aiColumn[i]);
153499#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
153500      if( pLimit ){
153501        pGrp = sqlite3ExprListAppend(pParse, pGrp, sqlite3ExprDup(db, pNew, 0));
153502      }
153503#endif
153504      pList = sqlite3ExprListAppend(pParse, pList, pNew);
153505    }
153506    eDest = IsVirtual(pTab) ? SRT_Table : SRT_Upfrom;
153507  }else if( IsView(pTab) ){
153508    for(i=0; i<pTab->nCol; i++){
153509      pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i));
153510    }
153511    eDest = SRT_Table;
153512  }else{
153513    eDest = IsVirtual(pTab) ? SRT_Table : SRT_Upfrom;
153514    pList = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0));
153515#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
153516    if( pLimit ){
153517      pGrp = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0));
153518    }
153519#endif
153520  }
153521  assert( pChanges!=0 || pParse->db->mallocFailed );
153522  if( pChanges ){
153523    for(i=0; i<pChanges->nExpr; i++){
153524      pList = sqlite3ExprListAppend(pParse, pList,
153525          sqlite3ExprDup(db, pChanges->a[i].pExpr, 0)
153526      );
153527    }
153528  }
153529  pSelect = sqlite3SelectNew(pParse, pList,
153530      pSrc, pWhere2, pGrp, 0, pOrderBy2,
153531      SF_UFSrcCheck|SF_IncludeHidden|SF_UpdateFrom, pLimit2
153532  );
153533  if( pSelect ) pSelect->selFlags |= SF_OrderByReqd;
153534  sqlite3SelectDestInit(&dest, eDest, iEph);
153535  dest.iSDParm2 = (pPk ? pPk->nKeyCol : -1);
153536  sqlite3Select(pParse, pSelect, &dest);
153537  sqlite3SelectDelete(db, pSelect);
153538}
153539
153540/*
153541** Process an UPDATE statement.
153542**
153543**   UPDATE OR IGNORE tbl SET a=b, c=d FROM tbl2... WHERE e<5 AND f NOT NULL;
153544**          \_______/ \_/     \______/      \_____/       \________________/
153545**           onError   |      pChanges         |                pWhere
153546**                     \_______________________/
153547**                               pTabList
153548*/
153549SQLITE_PRIVATE void sqlite3Update(
153550  Parse *pParse,         /* The parser context */
153551  SrcList *pTabList,     /* The table in which we should change things */
153552  ExprList *pChanges,    /* Things to be changed */
153553  Expr *pWhere,          /* The WHERE clause.  May be null */
153554  int onError,           /* How to handle constraint errors */
153555  ExprList *pOrderBy,    /* ORDER BY clause. May be null */
153556  Expr *pLimit,          /* LIMIT clause. May be null */
153557  Upsert *pUpsert        /* ON CONFLICT clause, or null */
153558){
153559  int i, j, k;           /* Loop counters */
153560  Table *pTab;           /* The table to be updated */
153561  int addrTop = 0;       /* VDBE instruction address of the start of the loop */
153562  WhereInfo *pWInfo = 0; /* Information about the WHERE clause */
153563  Vdbe *v;               /* The virtual database engine */
153564  Index *pIdx;           /* For looping over indices */
153565  Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
153566  int nIdx;              /* Number of indices that need updating */
153567  int nAllIdx;           /* Total number of indexes */
153568  int iBaseCur;          /* Base cursor number */
153569  int iDataCur;          /* Cursor for the canonical data btree */
153570  int iIdxCur;           /* Cursor for the first index */
153571  sqlite3 *db;           /* The database structure */
153572  int *aRegIdx = 0;      /* Registers for to each index and the main table */
153573  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
153574                         ** an expression for the i-th column of the table.
153575                         ** aXRef[i]==-1 if the i-th column is not changed. */
153576  u8 *aToOpen;           /* 1 for tables and indices to be opened */
153577  u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
153578  u8 chngRowid;          /* Rowid changed in a normal table */
153579  u8 chngKey;            /* Either chngPk or chngRowid */
153580  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
153581  int iRowidExpr = -1;   /* Index of "rowid=" (or IPK) assignment in pChanges */
153582  AuthContext sContext;  /* The authorization context */
153583  NameContext sNC;       /* The name-context to resolve expressions in */
153584  int iDb;               /* Database containing the table being updated */
153585  int eOnePass;          /* ONEPASS_XXX value from where.c */
153586  int hasFK;             /* True if foreign key processing is required */
153587  int labelBreak;        /* Jump here to break out of UPDATE loop */
153588  int labelContinue;     /* Jump here to continue next step of UPDATE loop */
153589  int flags;             /* Flags for sqlite3WhereBegin() */
153590
153591#ifndef SQLITE_OMIT_TRIGGER
153592  int isView;            /* True when updating a view (INSTEAD OF trigger) */
153593  Trigger *pTrigger;     /* List of triggers on pTab, if required */
153594  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
153595#endif
153596  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
153597  int iEph = 0;          /* Ephemeral table holding all primary key values */
153598  int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
153599  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
153600  int addrOpen = 0;      /* Address of OP_OpenEphemeral */
153601  int iPk = 0;           /* First of nPk cells holding PRIMARY KEY value */
153602  i16 nPk = 0;           /* Number of components of the PRIMARY KEY */
153603  int bReplace = 0;      /* True if REPLACE conflict resolution might happen */
153604  int bFinishSeek = 1;   /* The OP_FinishSeek opcode is needed */
153605  int nChangeFrom = 0;   /* If there is a FROM, pChanges->nExpr, else 0 */
153606
153607  /* Register Allocations */
153608  int regRowCount = 0;   /* A count of rows changed */
153609  int regOldRowid = 0;   /* The old rowid */
153610  int regNewRowid = 0;   /* The new rowid */
153611  int regNew = 0;        /* Content of the NEW.* table in triggers */
153612  int regOld = 0;        /* Content of OLD.* table in triggers */
153613  int regRowSet = 0;     /* Rowset of rows to be updated */
153614  int regKey = 0;        /* composite PRIMARY KEY value */
153615
153616  memset(&sContext, 0, sizeof(sContext));
153617  db = pParse->db;
153618  assert( db->pParse==pParse );
153619  if( pParse->nErr ){
153620    goto update_cleanup;
153621  }
153622  assert( db->mallocFailed==0 );
153623
153624  /* Locate the table which we want to update.
153625  */
153626  pTab = sqlite3SrcListLookup(pParse, pTabList);
153627  if( pTab==0 ) goto update_cleanup;
153628  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
153629
153630  /* Figure out if we have any triggers and if the table being
153631  ** updated is a view.
153632  */
153633#ifndef SQLITE_OMIT_TRIGGER
153634  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
153635  isView = IsView(pTab);
153636  assert( pTrigger || tmask==0 );
153637#else
153638# define pTrigger 0
153639# define isView 0
153640# define tmask 0
153641#endif
153642#ifdef SQLITE_OMIT_VIEW
153643# undef isView
153644# define isView 0
153645#endif
153646
153647#if TREETRACE_ENABLED
153648  if( sqlite3TreeTrace & 0x10000 ){
153649    sqlite3TreeViewLine(0, "In sqlite3Update() at %s:%d", __FILE__, __LINE__);
153650    sqlite3TreeViewUpdate(pParse->pWith, pTabList, pChanges, pWhere,
153651                          onError, pOrderBy, pLimit, pUpsert, pTrigger);
153652  }
153653#endif
153654
153655  /* If there was a FROM clause, set nChangeFrom to the number of expressions
153656  ** in the change-list. Otherwise, set it to 0. There cannot be a FROM
153657  ** clause if this function is being called to generate code for part of
153658  ** an UPSERT statement.  */
153659  nChangeFrom = (pTabList->nSrc>1) ? pChanges->nExpr : 0;
153660  assert( nChangeFrom==0 || pUpsert==0 );
153661
153662#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
153663  if( !isView && nChangeFrom==0 ){
153664    pWhere = sqlite3LimitWhere(
153665        pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
153666    );
153667    pOrderBy = 0;
153668    pLimit = 0;
153669  }
153670#endif
153671
153672  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
153673    goto update_cleanup;
153674  }
153675  if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
153676    goto update_cleanup;
153677  }
153678
153679  /* Allocate a cursors for the main database table and for all indices.
153680  ** The index cursors might not be used, but if they are used they
153681  ** need to occur right after the database cursor.  So go ahead and
153682  ** allocate enough space, just in case.
153683  */
153684  iBaseCur = iDataCur = pParse->nTab++;
153685  iIdxCur = iDataCur+1;
153686  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
153687  testcase( pPk!=0 && pPk!=pTab->pIndex );
153688  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
153689    if( pPk==pIdx ){
153690      iDataCur = pParse->nTab;
153691    }
153692    pParse->nTab++;
153693  }
153694  if( pUpsert ){
153695    /* On an UPSERT, reuse the same cursors already opened by INSERT */
153696    iDataCur = pUpsert->iDataCur;
153697    iIdxCur = pUpsert->iIdxCur;
153698    pParse->nTab = iBaseCur;
153699  }
153700  pTabList->a[0].iCursor = iDataCur;
153701
153702  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
153703  ** Initialize aXRef[] and aToOpen[] to their default values.
153704  */
153705  aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx+1) + nIdx+2 );
153706  if( aXRef==0 ) goto update_cleanup;
153707  aRegIdx = aXRef+pTab->nCol;
153708  aToOpen = (u8*)(aRegIdx+nIdx+1);
153709  memset(aToOpen, 1, nIdx+1);
153710  aToOpen[nIdx+1] = 0;
153711  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
153712
153713  /* Initialize the name-context */
153714  memset(&sNC, 0, sizeof(sNC));
153715  sNC.pParse = pParse;
153716  sNC.pSrcList = pTabList;
153717  sNC.uNC.pUpsert = pUpsert;
153718  sNC.ncFlags = NC_UUpsert;
153719
153720  /* Begin generating code. */
153721  v = sqlite3GetVdbe(pParse);
153722  if( v==0 ) goto update_cleanup;
153723
153724  /* Resolve the column names in all the expressions of the
153725  ** of the UPDATE statement.  Also find the column index
153726  ** for each column to be updated in the pChanges array.  For each
153727  ** column to be updated, make sure we have authorization to change
153728  ** that column.
153729  */
153730  chngRowid = chngPk = 0;
153731  for(i=0; i<pChanges->nExpr; i++){
153732    u8 hCol = sqlite3StrIHash(pChanges->a[i].zEName);
153733    /* If this is an UPDATE with a FROM clause, do not resolve expressions
153734    ** here. The call to sqlite3Select() below will do that. */
153735    if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
153736      goto update_cleanup;
153737    }
153738    for(j=0; j<pTab->nCol; j++){
153739      if( pTab->aCol[j].hName==hCol
153740       && sqlite3StrICmp(pTab->aCol[j].zCnName, pChanges->a[i].zEName)==0
153741      ){
153742        if( j==pTab->iPKey ){
153743          chngRowid = 1;
153744          pRowidExpr = pChanges->a[i].pExpr;
153745          iRowidExpr = i;
153746        }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
153747          chngPk = 1;
153748        }
153749#ifndef SQLITE_OMIT_GENERATED_COLUMNS
153750        else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){
153751          testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL );
153752          testcase( pTab->aCol[j].colFlags & COLFLAG_STORED );
153753          sqlite3ErrorMsg(pParse,
153754             "cannot UPDATE generated column \"%s\"",
153755             pTab->aCol[j].zCnName);
153756          goto update_cleanup;
153757        }
153758#endif
153759        aXRef[j] = i;
153760        break;
153761      }
153762    }
153763    if( j>=pTab->nCol ){
153764      if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zEName) ){
153765        j = -1;
153766        chngRowid = 1;
153767        pRowidExpr = pChanges->a[i].pExpr;
153768        iRowidExpr = i;
153769      }else{
153770        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zEName);
153771        pParse->checkSchema = 1;
153772        goto update_cleanup;
153773      }
153774    }
153775#ifndef SQLITE_OMIT_AUTHORIZATION
153776    {
153777      int rc;
153778      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
153779                            j<0 ? "ROWID" : pTab->aCol[j].zCnName,
153780                            db->aDb[iDb].zDbSName);
153781      if( rc==SQLITE_DENY ){
153782        goto update_cleanup;
153783      }else if( rc==SQLITE_IGNORE ){
153784        aXRef[j] = -1;
153785      }
153786    }
153787#endif
153788  }
153789  assert( (chngRowid & chngPk)==0 );
153790  assert( chngRowid==0 || chngRowid==1 );
153791  assert( chngPk==0 || chngPk==1 );
153792  chngKey = chngRowid + chngPk;
153793
153794#ifndef SQLITE_OMIT_GENERATED_COLUMNS
153795  /* Mark generated columns as changing if their generator expressions
153796  ** reference any changing column.  The actual aXRef[] value for
153797  ** generated expressions is not used, other than to check to see that it
153798  ** is non-negative, so the value of aXRef[] for generated columns can be
153799  ** set to any non-negative number.  We use 99999 so that the value is
153800  ** obvious when looking at aXRef[] in a symbolic debugger.
153801  */
153802  if( pTab->tabFlags & TF_HasGenerated ){
153803    int bProgress;
153804    testcase( pTab->tabFlags & TF_HasVirtual );
153805    testcase( pTab->tabFlags & TF_HasStored );
153806    do{
153807      bProgress = 0;
153808      for(i=0; i<pTab->nCol; i++){
153809        if( aXRef[i]>=0 ) continue;
153810        if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ) continue;
153811        if( sqlite3ExprReferencesUpdatedColumn(
153812                sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
153813                 aXRef, chngRowid)
153814        ){
153815          aXRef[i] = 99999;
153816          bProgress = 1;
153817        }
153818      }
153819    }while( bProgress );
153820  }
153821#endif
153822
153823  /* The SET expressions are not actually used inside the WHERE loop.
153824  ** So reset the colUsed mask. Unless this is a virtual table. In that
153825  ** case, set all bits of the colUsed mask (to ensure that the virtual
153826  ** table implementation makes all columns available).
153827  */
153828  pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
153829
153830  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
153831
153832  /* There is one entry in the aRegIdx[] array for each index on the table
153833  ** being updated.  Fill in aRegIdx[] with a register number that will hold
153834  ** the key for accessing each index.
153835  */
153836  if( onError==OE_Replace ) bReplace = 1;
153837  for(nAllIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nAllIdx++){
153838    int reg;
153839    if( chngKey || hasFK>1 || pIdx==pPk
153840     || indexWhereClauseMightChange(pIdx,aXRef,chngRowid)
153841    ){
153842      reg = ++pParse->nMem;
153843      pParse->nMem += pIdx->nColumn;
153844    }else{
153845      reg = 0;
153846      for(i=0; i<pIdx->nKeyCol; i++){
153847        if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){
153848          reg = ++pParse->nMem;
153849          pParse->nMem += pIdx->nColumn;
153850          if( onError==OE_Default && pIdx->onError==OE_Replace ){
153851            bReplace = 1;
153852          }
153853          break;
153854        }
153855      }
153856    }
153857    if( reg==0 ) aToOpen[nAllIdx+1] = 0;
153858    aRegIdx[nAllIdx] = reg;
153859  }
153860  aRegIdx[nAllIdx] = ++pParse->nMem;  /* Register storing the table record */
153861  if( bReplace ){
153862    /* If REPLACE conflict resolution might be invoked, open cursors on all
153863    ** indexes in case they are needed to delete records.  */
153864    memset(aToOpen, 1, nIdx+1);
153865  }
153866
153867  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
153868  sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb);
153869
153870  /* Allocate required registers. */
153871  if( !IsVirtual(pTab) ){
153872    /* For now, regRowSet and aRegIdx[nAllIdx] share the same register.
153873    ** If regRowSet turns out to be needed, then aRegIdx[nAllIdx] will be
153874    ** reallocated.  aRegIdx[nAllIdx] is the register in which the main
153875    ** table record is written.  regRowSet holds the RowSet for the
153876    ** two-pass update algorithm. */
153877    assert( aRegIdx[nAllIdx]==pParse->nMem );
153878    regRowSet = aRegIdx[nAllIdx];
153879    regOldRowid = regNewRowid = ++pParse->nMem;
153880    if( chngPk || pTrigger || hasFK ){
153881      regOld = pParse->nMem + 1;
153882      pParse->nMem += pTab->nCol;
153883    }
153884    if( chngKey || pTrigger || hasFK ){
153885      regNewRowid = ++pParse->nMem;
153886    }
153887    regNew = pParse->nMem + 1;
153888    pParse->nMem += pTab->nCol;
153889  }
153890
153891  /* Start the view context. */
153892  if( isView ){
153893    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
153894  }
153895
153896  /* If we are trying to update a view, realize that view into
153897  ** an ephemeral table.
153898  */
153899#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
153900  if( nChangeFrom==0 && isView ){
153901    sqlite3MaterializeView(pParse, pTab,
153902        pWhere, pOrderBy, pLimit, iDataCur
153903    );
153904    pOrderBy = 0;
153905    pLimit = 0;
153906  }
153907#endif
153908
153909  /* Resolve the column names in all the expressions in the
153910  ** WHERE clause.
153911  */
153912  if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pWhere) ){
153913    goto update_cleanup;
153914  }
153915
153916#ifndef SQLITE_OMIT_VIRTUALTABLE
153917  /* Virtual tables must be handled separately */
153918  if( IsVirtual(pTab) ){
153919    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
153920                       pWhere, onError);
153921    goto update_cleanup;
153922  }
153923#endif
153924
153925  /* Jump to labelBreak to abandon further processing of this UPDATE */
153926  labelContinue = labelBreak = sqlite3VdbeMakeLabel(pParse);
153927
153928  /* Not an UPSERT.  Normal processing.  Begin by
153929  ** initialize the count of updated rows */
153930  if( (db->flags&SQLITE_CountRows)!=0
153931   && !pParse->pTriggerTab
153932   && !pParse->nested
153933   && !pParse->bReturning
153934   && pUpsert==0
153935  ){
153936    regRowCount = ++pParse->nMem;
153937    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
153938  }
153939
153940  if( nChangeFrom==0 && HasRowid(pTab) ){
153941    sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
153942    iEph = pParse->nTab++;
153943    addrOpen = sqlite3VdbeAddOp3(v, OP_OpenEphemeral, iEph, 0, regRowSet);
153944  }else{
153945    assert( pPk!=0 || HasRowid(pTab) );
153946    nPk = pPk ? pPk->nKeyCol : 0;
153947    iPk = pParse->nMem+1;
153948    pParse->nMem += nPk;
153949    pParse->nMem += nChangeFrom;
153950    regKey = ++pParse->nMem;
153951    if( pUpsert==0 ){
153952      int nEphCol = nPk + nChangeFrom + (isView ? pTab->nCol : 0);
153953      iEph = pParse->nTab++;
153954      if( pPk ) sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
153955      addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nEphCol);
153956      if( pPk ){
153957        KeyInfo *pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pPk);
153958        if( pKeyInfo ){
153959          pKeyInfo->nAllField = nEphCol;
153960          sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
153961        }
153962      }
153963      if( nChangeFrom ){
153964        updateFromSelect(
153965            pParse, iEph, pPk, pChanges, pTabList, pWhere, pOrderBy, pLimit
153966        );
153967#ifndef SQLITE_OMIT_SUBQUERY
153968        if( isView ) iDataCur = iEph;
153969#endif
153970      }
153971    }
153972  }
153973
153974  if( nChangeFrom ){
153975    sqlite3MultiWrite(pParse);
153976    eOnePass = ONEPASS_OFF;
153977    nKey = nPk;
153978    regKey = iPk;
153979  }else{
153980    if( pUpsert ){
153981      /* If this is an UPSERT, then all cursors have already been opened by
153982      ** the outer INSERT and the data cursor should be pointing at the row
153983      ** that is to be updated.  So bypass the code that searches for the
153984      ** row(s) to be updated.
153985      */
153986      pWInfo = 0;
153987      eOnePass = ONEPASS_SINGLE;
153988      sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
153989      bFinishSeek = 0;
153990    }else{
153991      /* Begin the database scan.
153992      **
153993      ** Do not consider a single-pass strategy for a multi-row update if
153994      ** there is anything that might disrupt the cursor being used to do
153995      ** the UPDATE:
153996      **   (1) This is a nested UPDATE
153997      **   (2) There are triggers
153998      **   (3) There are FOREIGN KEY constraints
153999      **   (4) There are REPLACE conflict handlers
154000      **   (5) There are subqueries in the WHERE clause
154001      */
154002      flags = WHERE_ONEPASS_DESIRED;
154003      if( !pParse->nested
154004       && !pTrigger
154005       && !hasFK
154006       && !chngKey
154007       && !bReplace
154008       && (pWhere==0 || !ExprHasProperty(pWhere, EP_Subquery))
154009      ){
154010        flags |= WHERE_ONEPASS_MULTIROW;
154011      }
154012      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,0,0,flags,iIdxCur);
154013      if( pWInfo==0 ) goto update_cleanup;
154014
154015      /* A one-pass strategy that might update more than one row may not
154016      ** be used if any column of the index used for the scan is being
154017      ** updated. Otherwise, if there is an index on "b", statements like
154018      ** the following could create an infinite loop:
154019      **
154020      **   UPDATE t1 SET b=b+1 WHERE b>?
154021      **
154022      ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
154023      ** strategy that uses an index for which one or more columns are being
154024      ** updated.  */
154025      eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
154026      bFinishSeek = sqlite3WhereUsesDeferredSeek(pWInfo);
154027      if( eOnePass!=ONEPASS_SINGLE ){
154028        sqlite3MultiWrite(pParse);
154029        if( eOnePass==ONEPASS_MULTI ){
154030          int iCur = aiCurOnePass[1];
154031          if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
154032            eOnePass = ONEPASS_OFF;
154033          }
154034          assert( iCur!=iDataCur || !HasRowid(pTab) );
154035        }
154036      }
154037    }
154038
154039    if( HasRowid(pTab) ){
154040      /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
154041      ** mode, write the rowid into the FIFO. In either of the one-pass modes,
154042      ** leave it in register regOldRowid.  */
154043      sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
154044      if( eOnePass==ONEPASS_OFF ){
154045        aRegIdx[nAllIdx] = ++pParse->nMem;
154046        sqlite3VdbeAddOp3(v, OP_Insert, iEph, regRowSet, regOldRowid);
154047      }else{
154048        if( ALWAYS(addrOpen) ) sqlite3VdbeChangeToNoop(v, addrOpen);
154049      }
154050    }else{
154051      /* Read the PK of the current row into an array of registers. In
154052      ** ONEPASS_OFF mode, serialize the array into a record and store it in
154053      ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
154054      ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
154055      ** is not required) and leave the PK fields in the array of registers.  */
154056      for(i=0; i<nPk; i++){
154057        assert( pPk->aiColumn[i]>=0 );
154058        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,
154059                                        pPk->aiColumn[i], iPk+i);
154060      }
154061      if( eOnePass ){
154062        if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);
154063        nKey = nPk;
154064        regKey = iPk;
154065      }else{
154066        sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
154067                          sqlite3IndexAffinityStr(db, pPk), nPk);
154068        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
154069      }
154070    }
154071  }
154072
154073  if( pUpsert==0 ){
154074    if( nChangeFrom==0 && eOnePass!=ONEPASS_MULTI ){
154075      sqlite3WhereEnd(pWInfo);
154076    }
154077
154078    if( !isView ){
154079      int addrOnce = 0;
154080      int iNotUsed1 = 0;
154081      int iNotUsed2 = 0;
154082
154083      /* Open every index that needs updating. */
154084      if( eOnePass!=ONEPASS_OFF ){
154085        if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
154086        if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
154087      }
154088
154089      if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
154090        addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
154091      }
154092      sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur,
154093                                 aToOpen, &iNotUsed1, &iNotUsed2);
154094      if( addrOnce ){
154095        sqlite3VdbeJumpHereOrPopInst(v, addrOnce);
154096      }
154097    }
154098
154099    /* Top of the update loop */
154100    if( eOnePass!=ONEPASS_OFF ){
154101      if( aiCurOnePass[0]!=iDataCur
154102       && aiCurOnePass[1]!=iDataCur
154103#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
154104       && !isView
154105#endif
154106      ){
154107        assert( pPk );
154108        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey);
154109        VdbeCoverage(v);
154110      }
154111      if( eOnePass!=ONEPASS_SINGLE ){
154112        labelContinue = sqlite3VdbeMakeLabel(pParse);
154113      }
154114      sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
154115      VdbeCoverageIf(v, pPk==0);
154116      VdbeCoverageIf(v, pPk!=0);
154117    }else if( pPk || nChangeFrom ){
154118      labelContinue = sqlite3VdbeMakeLabel(pParse);
154119      sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
154120      addrTop = sqlite3VdbeCurrentAddr(v);
154121      if( nChangeFrom ){
154122        if( !isView ){
154123          if( pPk ){
154124            for(i=0; i<nPk; i++){
154125              sqlite3VdbeAddOp3(v, OP_Column, iEph, i, iPk+i);
154126            }
154127            sqlite3VdbeAddOp4Int(
154128                v, OP_NotFound, iDataCur, labelContinue, iPk, nPk
154129            ); VdbeCoverage(v);
154130          }else{
154131            sqlite3VdbeAddOp2(v, OP_Rowid, iEph, regOldRowid);
154132            sqlite3VdbeAddOp3(
154133                v, OP_NotExists, iDataCur, labelContinue, regOldRowid
154134            ); VdbeCoverage(v);
154135          }
154136        }
154137      }else{
154138        sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
154139        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey,0);
154140        VdbeCoverage(v);
154141      }
154142    }else{
154143      sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
154144      labelContinue = sqlite3VdbeMakeLabel(pParse);
154145      addrTop = sqlite3VdbeAddOp2(v, OP_Rowid, iEph, regOldRowid);
154146      VdbeCoverage(v);
154147      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
154148      VdbeCoverage(v);
154149    }
154150  }
154151
154152  /* If the rowid value will change, set register regNewRowid to
154153  ** contain the new value. If the rowid is not being modified,
154154  ** then regNewRowid is the same register as regOldRowid, which is
154155  ** already populated.  */
154156  assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
154157  if( chngRowid ){
154158    assert( iRowidExpr>=0 );
154159    if( nChangeFrom==0 ){
154160      sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
154161    }else{
154162      sqlite3VdbeAddOp3(v, OP_Column, iEph, iRowidExpr, regNewRowid);
154163    }
154164    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
154165  }
154166
154167  /* Compute the old pre-UPDATE content of the row being changed, if that
154168  ** information is needed */
154169  if( chngPk || hasFK || pTrigger ){
154170    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
154171    oldmask |= sqlite3TriggerColmask(pParse,
154172        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
154173    );
154174    for(i=0; i<pTab->nCol; i++){
154175      u32 colFlags = pTab->aCol[i].colFlags;
154176      k = sqlite3TableColumnToStorage(pTab, i) + regOld;
154177      if( oldmask==0xffffffff
154178       || (i<32 && (oldmask & MASKBIT32(i))!=0)
154179       || (colFlags & COLFLAG_PRIMKEY)!=0
154180      ){
154181        testcase(  oldmask!=0xffffffff && i==31 );
154182        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
154183      }else{
154184        sqlite3VdbeAddOp2(v, OP_Null, 0, k);
154185      }
154186    }
154187    if( chngRowid==0 && pPk==0 ){
154188#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
154189      if( isView ) sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
154190#endif
154191      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
154192    }
154193  }
154194
154195  /* Populate the array of registers beginning at regNew with the new
154196  ** row data. This array is used to check constants, create the new
154197  ** table and index records, and as the values for any new.* references
154198  ** made by triggers.
154199  **
154200  ** If there are one or more BEFORE triggers, then do not populate the
154201  ** registers associated with columns that are (a) not modified by
154202  ** this UPDATE statement and (b) not accessed by new.* references. The
154203  ** values for registers not modified by the UPDATE must be reloaded from
154204  ** the database after the BEFORE triggers are fired anyway (as the trigger
154205  ** may have modified them). So not loading those that are not going to
154206  ** be used eliminates some redundant opcodes.
154207  */
154208  newmask = sqlite3TriggerColmask(
154209      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
154210  );
154211  for(i=0, k=regNew; i<pTab->nCol; i++, k++){
154212    if( i==pTab->iPKey ){
154213      sqlite3VdbeAddOp2(v, OP_Null, 0, k);
154214    }else if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)!=0 ){
154215      if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
154216    }else{
154217      j = aXRef[i];
154218      if( j>=0 ){
154219        if( nChangeFrom ){
154220          int nOff = (isView ? pTab->nCol : nPk);
154221          assert( eOnePass==ONEPASS_OFF );
154222          sqlite3VdbeAddOp3(v, OP_Column, iEph, nOff+j, k);
154223        }else{
154224          sqlite3ExprCode(pParse, pChanges->a[j].pExpr, k);
154225        }
154226      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
154227        /* This branch loads the value of a column that will not be changed
154228        ** into a register. This is done if there are no BEFORE triggers, or
154229        ** if there are one or more BEFORE triggers that use this value via
154230        ** a new.* reference in a trigger program.
154231        */
154232        testcase( i==31 );
154233        testcase( i==32 );
154234        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
154235        bFinishSeek = 0;
154236      }else{
154237        sqlite3VdbeAddOp2(v, OP_Null, 0, k);
154238      }
154239    }
154240  }
154241#ifndef SQLITE_OMIT_GENERATED_COLUMNS
154242  if( pTab->tabFlags & TF_HasGenerated ){
154243    testcase( pTab->tabFlags & TF_HasVirtual );
154244    testcase( pTab->tabFlags & TF_HasStored );
154245    sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);
154246  }
154247#endif
154248
154249  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
154250  ** verified. One could argue that this is wrong.
154251  */
154252  if( tmask&TRIGGER_BEFORE ){
154253    sqlite3TableAffinity(v, pTab, regNew);
154254    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
154255        TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
154256
154257    if( !isView ){
154258      /* The row-trigger may have deleted the row being updated. In this
154259      ** case, jump to the next row. No updates or AFTER triggers are
154260      ** required. This behavior - what happens when the row being updated
154261      ** is deleted or renamed by a BEFORE trigger - is left undefined in the
154262      ** documentation.
154263      */
154264      if( pPk ){
154265        sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey);
154266        VdbeCoverage(v);
154267      }else{
154268        sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid);
154269        VdbeCoverage(v);
154270      }
154271
154272      /* After-BEFORE-trigger-reload-loop:
154273      ** If it did not delete it, the BEFORE trigger may still have modified
154274      ** some of the columns of the row being updated. Load the values for
154275      ** all columns not modified by the update statement into their registers
154276      ** in case this has happened. Only unmodified columns are reloaded.
154277      ** The values computed for modified columns use the values before the
154278      ** BEFORE trigger runs.  See test case trigger1-18.0 (added 2018-04-26)
154279      ** for an example.
154280      */
154281      for(i=0, k=regNew; i<pTab->nCol; i++, k++){
154282        if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
154283          if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
154284        }else if( aXRef[i]<0 && i!=pTab->iPKey ){
154285          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
154286        }
154287      }
154288#ifndef SQLITE_OMIT_GENERATED_COLUMNS
154289      if( pTab->tabFlags & TF_HasGenerated ){
154290        testcase( pTab->tabFlags & TF_HasVirtual );
154291        testcase( pTab->tabFlags & TF_HasStored );
154292        sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);
154293      }
154294#endif
154295    }
154296  }
154297
154298  if( !isView ){
154299    /* Do constraint checks. */
154300    assert( regOldRowid>0 );
154301    sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
154302        regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
154303        aXRef, 0);
154304
154305    /* If REPLACE conflict handling may have been used, or if the PK of the
154306    ** row is changing, then the GenerateConstraintChecks() above may have
154307    ** moved cursor iDataCur. Reseek it. */
154308    if( bReplace || chngKey ){
154309      if( pPk ){
154310        sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey);
154311      }else{
154312        sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid);
154313      }
154314      VdbeCoverage(v);
154315    }
154316
154317    /* Do FK constraint checks. */
154318    if( hasFK ){
154319      sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
154320    }
154321
154322    /* Delete the index entries associated with the current record.  */
154323    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
154324
154325    /* We must run the OP_FinishSeek opcode to resolve a prior
154326    ** OP_DeferredSeek if there is any possibility that there have been
154327    ** no OP_Column opcodes since the OP_DeferredSeek was issued.  But
154328    ** we want to avoid the OP_FinishSeek if possible, as running it
154329    ** costs CPU cycles. */
154330    if( bFinishSeek ){
154331      sqlite3VdbeAddOp1(v, OP_FinishSeek, iDataCur);
154332    }
154333
154334    /* If changing the rowid value, or if there are foreign key constraints
154335    ** to process, delete the old record. Otherwise, add a noop OP_Delete
154336    ** to invoke the pre-update hook.
154337    **
154338    ** That (regNew==regnewRowid+1) is true is also important for the
154339    ** pre-update hook. If the caller invokes preupdate_new(), the returned
154340    ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
154341    ** is the column index supplied by the user.
154342    */
154343    assert( regNew==regNewRowid+1 );
154344#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
154345    sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
154346        OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
154347        regNewRowid
154348    );
154349    if( eOnePass==ONEPASS_MULTI ){
154350      assert( hasFK==0 && chngKey==0 );
154351      sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
154352    }
154353    if( !pParse->nested ){
154354      sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
154355    }
154356#else
154357    if( hasFK>1 || chngKey ){
154358      sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
154359    }
154360#endif
154361
154362    if( hasFK ){
154363      sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
154364    }
154365
154366    /* Insert the new index entries and the new record. */
154367    sqlite3CompleteInsertion(
154368        pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
154369        OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
154370        0, 0
154371    );
154372
154373    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
154374    ** handle rows (possibly in other tables) that refer via a foreign key
154375    ** to the row just updated. */
154376    if( hasFK ){
154377      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
154378    }
154379  }
154380
154381  /* Increment the row counter
154382  */
154383  if( regRowCount ){
154384    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
154385  }
154386
154387  if( pTrigger ){
154388    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
154389        TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
154390  }
154391
154392  /* Repeat the above with the next record to be updated, until
154393  ** all record selected by the WHERE clause have been updated.
154394  */
154395  if( eOnePass==ONEPASS_SINGLE ){
154396    /* Nothing to do at end-of-loop for a single-pass */
154397  }else if( eOnePass==ONEPASS_MULTI ){
154398    sqlite3VdbeResolveLabel(v, labelContinue);
154399    sqlite3WhereEnd(pWInfo);
154400  }else{
154401    sqlite3VdbeResolveLabel(v, labelContinue);
154402    sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
154403  }
154404  sqlite3VdbeResolveLabel(v, labelBreak);
154405
154406  /* Update the sqlite_sequence table by storing the content of the
154407  ** maximum rowid counter values recorded while inserting into
154408  ** autoincrement tables.
154409  */
154410  if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){
154411    sqlite3AutoincrementEnd(pParse);
154412  }
154413
154414  /*
154415  ** Return the number of rows that were changed, if we are tracking
154416  ** that information.
154417  */
154418  if( regRowCount ){
154419    sqlite3CodeChangeCount(v, regRowCount, "rows updated");
154420  }
154421
154422update_cleanup:
154423  sqlite3AuthContextPop(&sContext);
154424  sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
154425  sqlite3SrcListDelete(db, pTabList);
154426  sqlite3ExprListDelete(db, pChanges);
154427  sqlite3ExprDelete(db, pWhere);
154428#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
154429  sqlite3ExprListDelete(db, pOrderBy);
154430  sqlite3ExprDelete(db, pLimit);
154431#endif
154432  return;
154433}
154434/* Make sure "isView" and other macros defined above are undefined. Otherwise
154435** they may interfere with compilation of other functions in this file
154436** (or in another file, if this file becomes part of the amalgamation).  */
154437#ifdef isView
154438 #undef isView
154439#endif
154440#ifdef pTrigger
154441 #undef pTrigger
154442#endif
154443
154444#ifndef SQLITE_OMIT_VIRTUALTABLE
154445/*
154446** Generate code for an UPDATE of a virtual table.
154447**
154448** There are two possible strategies - the default and the special
154449** "onepass" strategy. Onepass is only used if the virtual table
154450** implementation indicates that pWhere may match at most one row.
154451**
154452** The default strategy is to create an ephemeral table that contains
154453** for each row to be changed:
154454**
154455**   (A)  The original rowid of that row.
154456**   (B)  The revised rowid for the row.
154457**   (C)  The content of every column in the row.
154458**
154459** Then loop through the contents of this ephemeral table executing a
154460** VUpdate for each row. When finished, drop the ephemeral table.
154461**
154462** The "onepass" strategy does not use an ephemeral table. Instead, it
154463** stores the same values (A, B and C above) in a register array and
154464** makes a single invocation of VUpdate.
154465*/
154466static void updateVirtualTable(
154467  Parse *pParse,       /* The parsing context */
154468  SrcList *pSrc,       /* The virtual table to be modified */
154469  Table *pTab,         /* The virtual table */
154470  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
154471  Expr *pRowid,        /* Expression used to recompute the rowid */
154472  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
154473  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
154474  int onError          /* ON CONFLICT strategy */
154475){
154476  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
154477  int ephemTab;             /* Table holding the result of the SELECT */
154478  int i;                    /* Loop counter */
154479  sqlite3 *db = pParse->db; /* Database connection */
154480  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
154481  WhereInfo *pWInfo = 0;
154482  int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
154483  int regArg;                     /* First register in VUpdate arg array */
154484  int regRec;                     /* Register in which to assemble record */
154485  int regRowid;                   /* Register for ephemeral table rowid */
154486  int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
154487  int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
154488  int eOnePass;                   /* True to use onepass strategy */
154489  int addr;                       /* Address of OP_OpenEphemeral */
154490
154491  /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
154492  ** create and open the ephemeral table in which the records created from
154493  ** these arguments will be temporarily stored. */
154494  assert( v );
154495  ephemTab = pParse->nTab++;
154496  addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
154497  regArg = pParse->nMem + 1;
154498  pParse->nMem += nArg;
154499  if( pSrc->nSrc>1 ){
154500    Index *pPk = 0;
154501    Expr *pRow;
154502    ExprList *pList;
154503    if( HasRowid(pTab) ){
154504      if( pRowid ){
154505        pRow = sqlite3ExprDup(db, pRowid, 0);
154506      }else{
154507        pRow = sqlite3PExpr(pParse, TK_ROW, 0, 0);
154508      }
154509    }else{
154510      i16 iPk;      /* PRIMARY KEY column */
154511      pPk = sqlite3PrimaryKeyIndex(pTab);
154512      assert( pPk!=0 );
154513      assert( pPk->nKeyCol==1 );
154514      iPk = pPk->aiColumn[0];
154515      if( aXRef[iPk]>=0 ){
154516        pRow = sqlite3ExprDup(db, pChanges->a[aXRef[iPk]].pExpr, 0);
154517      }else{
154518        pRow = exprRowColumn(pParse, iPk);
154519      }
154520    }
154521    pList = sqlite3ExprListAppend(pParse, 0, pRow);
154522
154523    for(i=0; i<pTab->nCol; i++){
154524      if( aXRef[i]>=0 ){
154525        pList = sqlite3ExprListAppend(pParse, pList,
154526          sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0)
154527        );
154528      }else{
154529        Expr *pRowExpr = exprRowColumn(pParse, i);
154530        if( pRowExpr ) pRowExpr->op2 = OPFLAG_NOCHNG;
154531        pList = sqlite3ExprListAppend(pParse, pList, pRowExpr);
154532      }
154533    }
154534
154535    updateFromSelect(pParse, ephemTab, pPk, pList, pSrc, pWhere, 0, 0);
154536    sqlite3ExprListDelete(db, pList);
154537    eOnePass = ONEPASS_OFF;
154538  }else{
154539    regRec = ++pParse->nMem;
154540    regRowid = ++pParse->nMem;
154541
154542    /* Start scanning the virtual table */
154543    pWInfo = sqlite3WhereBegin(
154544        pParse, pSrc, pWhere, 0, 0, 0, WHERE_ONEPASS_DESIRED, 0
154545    );
154546    if( pWInfo==0 ) return;
154547
154548    /* Populate the argument registers. */
154549    for(i=0; i<pTab->nCol; i++){
154550      assert( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 );
154551      if( aXRef[i]>=0 ){
154552        sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
154553      }else{
154554        sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
154555        sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* For sqlite3_vtab_nochange() */
154556      }
154557    }
154558    if( HasRowid(pTab) ){
154559      sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
154560      if( pRowid ){
154561        sqlite3ExprCode(pParse, pRowid, regArg+1);
154562      }else{
154563        sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
154564      }
154565    }else{
154566      Index *pPk;   /* PRIMARY KEY index */
154567      i16 iPk;      /* PRIMARY KEY column */
154568      pPk = sqlite3PrimaryKeyIndex(pTab);
154569      assert( pPk!=0 );
154570      assert( pPk->nKeyCol==1 );
154571      iPk = pPk->aiColumn[0];
154572      sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
154573      sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
154574    }
154575
154576    eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
154577
154578    /* There is no ONEPASS_MULTI on virtual tables */
154579    assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
154580
154581    if( eOnePass ){
154582      /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
154583      ** above. */
154584      sqlite3VdbeChangeToNoop(v, addr);
154585      sqlite3VdbeAddOp1(v, OP_Close, iCsr);
154586    }else{
154587      /* Create a record from the argument register contents and insert it into
154588      ** the ephemeral table. */
154589      sqlite3MultiWrite(pParse);
154590      sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
154591#if defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_NULL_TRIM)
154592      /* Signal an assert() within OP_MakeRecord that it is allowed to
154593      ** accept no-change records with serial_type 10 */
154594      sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
154595#endif
154596      sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
154597      sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
154598    }
154599  }
154600
154601
154602  if( eOnePass==ONEPASS_OFF ){
154603    /* End the virtual table scan */
154604    if( pSrc->nSrc==1 ){
154605      sqlite3WhereEnd(pWInfo);
154606    }
154607
154608    /* Begin scanning through the ephemeral table. */
154609    addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
154610
154611    /* Extract arguments from the current row of the ephemeral table and
154612    ** invoke the VUpdate method.  */
154613    for(i=0; i<nArg; i++){
154614      sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
154615    }
154616  }
154617  sqlite3VtabMakeWritable(pParse, pTab);
154618  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
154619  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
154620  sqlite3MayAbort(pParse);
154621
154622  /* End of the ephemeral table scan. Or, if using the onepass strategy,
154623  ** jump to here if the scan visited zero rows. */
154624  if( eOnePass==ONEPASS_OFF ){
154625    sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
154626    sqlite3VdbeJumpHere(v, addr);
154627    sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
154628  }else{
154629    sqlite3WhereEnd(pWInfo);
154630  }
154631}
154632#endif /* SQLITE_OMIT_VIRTUALTABLE */
154633
154634/************** End of update.c **********************************************/
154635/************** Begin file upsert.c ******************************************/
154636/*
154637** 2018-04-12
154638**
154639** The author disclaims copyright to this source code.  In place of
154640** a legal notice, here is a blessing:
154641**
154642**    May you do good and not evil.
154643**    May you find forgiveness for yourself and forgive others.
154644**    May you share freely, never taking more than you give.
154645**
154646*************************************************************************
154647** This file contains code to implement various aspects of UPSERT
154648** processing and handling of the Upsert object.
154649*/
154650/* #include "sqliteInt.h" */
154651
154652#ifndef SQLITE_OMIT_UPSERT
154653/*
154654** Free a list of Upsert objects
154655*/
154656static void SQLITE_NOINLINE upsertDelete(sqlite3 *db, Upsert *p){
154657  do{
154658    Upsert *pNext = p->pNextUpsert;
154659    sqlite3ExprListDelete(db, p->pUpsertTarget);
154660    sqlite3ExprDelete(db, p->pUpsertTargetWhere);
154661    sqlite3ExprListDelete(db, p->pUpsertSet);
154662    sqlite3ExprDelete(db, p->pUpsertWhere);
154663    sqlite3DbFree(db, p->pToFree);
154664    sqlite3DbFree(db, p);
154665    p = pNext;
154666  }while( p );
154667}
154668SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3 *db, Upsert *p){
154669  if( p ) upsertDelete(db, p);
154670}
154671
154672
154673/*
154674** Duplicate an Upsert object.
154675*/
154676SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3 *db, Upsert *p){
154677  if( p==0 ) return 0;
154678  return sqlite3UpsertNew(db,
154679           sqlite3ExprListDup(db, p->pUpsertTarget, 0),
154680           sqlite3ExprDup(db, p->pUpsertTargetWhere, 0),
154681           sqlite3ExprListDup(db, p->pUpsertSet, 0),
154682           sqlite3ExprDup(db, p->pUpsertWhere, 0),
154683           sqlite3UpsertDup(db, p->pNextUpsert)
154684         );
154685}
154686
154687/*
154688** Create a new Upsert object.
154689*/
154690SQLITE_PRIVATE Upsert *sqlite3UpsertNew(
154691  sqlite3 *db,           /* Determines which memory allocator to use */
154692  ExprList *pTarget,     /* Target argument to ON CONFLICT, or NULL */
154693  Expr *pTargetWhere,    /* Optional WHERE clause on the target */
154694  ExprList *pSet,        /* UPDATE columns, or NULL for a DO NOTHING */
154695  Expr *pWhere,          /* WHERE clause for the ON CONFLICT UPDATE */
154696  Upsert *pNext          /* Next ON CONFLICT clause in the list */
154697){
154698  Upsert *pNew;
154699  pNew = sqlite3DbMallocZero(db, sizeof(Upsert));
154700  if( pNew==0 ){
154701    sqlite3ExprListDelete(db, pTarget);
154702    sqlite3ExprDelete(db, pTargetWhere);
154703    sqlite3ExprListDelete(db, pSet);
154704    sqlite3ExprDelete(db, pWhere);
154705    sqlite3UpsertDelete(db, pNext);
154706    return 0;
154707  }else{
154708    pNew->pUpsertTarget = pTarget;
154709    pNew->pUpsertTargetWhere = pTargetWhere;
154710    pNew->pUpsertSet = pSet;
154711    pNew->pUpsertWhere = pWhere;
154712    pNew->isDoUpdate = pSet!=0;
154713    pNew->pNextUpsert = pNext;
154714  }
154715  return pNew;
154716}
154717
154718/*
154719** Analyze the ON CONFLICT clause described by pUpsert.  Resolve all
154720** symbols in the conflict-target.
154721**
154722** Return SQLITE_OK if everything works, or an error code is something
154723** is wrong.
154724*/
154725SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(
154726  Parse *pParse,     /* The parsing context */
154727  SrcList *pTabList, /* Table into which we are inserting */
154728  Upsert *pUpsert,   /* The ON CONFLICT clauses */
154729  Upsert *pAll       /* Complete list of all ON CONFLICT clauses */
154730){
154731  Table *pTab;            /* That table into which we are inserting */
154732  int rc;                 /* Result code */
154733  int iCursor;            /* Cursor used by pTab */
154734  Index *pIdx;            /* One of the indexes of pTab */
154735  ExprList *pTarget;      /* The conflict-target clause */
154736  Expr *pTerm;            /* One term of the conflict-target clause */
154737  NameContext sNC;        /* Context for resolving symbolic names */
154738  Expr sCol[2];           /* Index column converted into an Expr */
154739  int nClause = 0;        /* Counter of ON CONFLICT clauses */
154740
154741  assert( pTabList->nSrc==1 );
154742  assert( pTabList->a[0].pTab!=0 );
154743  assert( pUpsert!=0 );
154744  assert( pUpsert->pUpsertTarget!=0 );
154745
154746  /* Resolve all symbolic names in the conflict-target clause, which
154747  ** includes both the list of columns and the optional partial-index
154748  ** WHERE clause.
154749  */
154750  memset(&sNC, 0, sizeof(sNC));
154751  sNC.pParse = pParse;
154752  sNC.pSrcList = pTabList;
154753  for(; pUpsert && pUpsert->pUpsertTarget;
154754        pUpsert=pUpsert->pNextUpsert, nClause++){
154755    rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
154756    if( rc ) return rc;
154757    rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
154758    if( rc ) return rc;
154759
154760    /* Check to see if the conflict target matches the rowid. */
154761    pTab = pTabList->a[0].pTab;
154762    pTarget = pUpsert->pUpsertTarget;
154763    iCursor = pTabList->a[0].iCursor;
154764    if( HasRowid(pTab)
154765     && pTarget->nExpr==1
154766     && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN
154767     && pTerm->iColumn==XN_ROWID
154768    ){
154769      /* The conflict-target is the rowid of the primary table */
154770      assert( pUpsert->pUpsertIdx==0 );
154771      continue;
154772    }
154773
154774    /* Initialize sCol[0..1] to be an expression parse tree for a
154775    ** single column of an index.  The sCol[0] node will be the TK_COLLATE
154776    ** operator and sCol[1] will be the TK_COLUMN operator.  Code below
154777    ** will populate the specific collation and column number values
154778    ** prior to comparing against the conflict-target expression.
154779    */
154780    memset(sCol, 0, sizeof(sCol));
154781    sCol[0].op = TK_COLLATE;
154782    sCol[0].pLeft = &sCol[1];
154783    sCol[1].op = TK_COLUMN;
154784    sCol[1].iTable = pTabList->a[0].iCursor;
154785
154786    /* Check for matches against other indexes */
154787    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
154788      int ii, jj, nn;
154789      if( !IsUniqueIndex(pIdx) ) continue;
154790      if( pTarget->nExpr!=pIdx->nKeyCol ) continue;
154791      if( pIdx->pPartIdxWhere ){
154792        if( pUpsert->pUpsertTargetWhere==0 ) continue;
154793        if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere,
154794                               pIdx->pPartIdxWhere, iCursor)!=0 ){
154795          continue;
154796        }
154797      }
154798      nn = pIdx->nKeyCol;
154799      for(ii=0; ii<nn; ii++){
154800        Expr *pExpr;
154801        sCol[0].u.zToken = (char*)pIdx->azColl[ii];
154802        if( pIdx->aiColumn[ii]==XN_EXPR ){
154803          assert( pIdx->aColExpr!=0 );
154804          assert( pIdx->aColExpr->nExpr>ii );
154805          assert( pIdx->bHasExpr );
154806          pExpr = pIdx->aColExpr->a[ii].pExpr;
154807          if( pExpr->op!=TK_COLLATE ){
154808            sCol[0].pLeft = pExpr;
154809            pExpr = &sCol[0];
154810          }
154811        }else{
154812          sCol[0].pLeft = &sCol[1];
154813          sCol[1].iColumn = pIdx->aiColumn[ii];
154814          pExpr = &sCol[0];
154815        }
154816        for(jj=0; jj<nn; jj++){
154817          if( sqlite3ExprCompare(0,pTarget->a[jj].pExpr,pExpr,iCursor)<2 ){
154818            break;  /* Column ii of the index matches column jj of target */
154819          }
154820        }
154821        if( jj>=nn ){
154822          /* The target contains no match for column jj of the index */
154823          break;
154824        }
154825      }
154826      if( ii<nn ){
154827        /* Column ii of the index did not match any term of the conflict target.
154828        ** Continue the search with the next index. */
154829        continue;
154830      }
154831      pUpsert->pUpsertIdx = pIdx;
154832      if( sqlite3UpsertOfIndex(pAll,pIdx)!=pUpsert ){
154833        /* Really this should be an error.  The isDup ON CONFLICT clause will
154834        ** never fire.  But this problem was not discovered until three years
154835        ** after multi-CONFLICT upsert was added, and so we silently ignore
154836        ** the problem to prevent breaking applications that might actually
154837        ** have redundant ON CONFLICT clauses. */
154838        pUpsert->isDup = 1;
154839      }
154840      break;
154841    }
154842    if( pUpsert->pUpsertIdx==0 ){
154843      char zWhich[16];
154844      if( nClause==0 && pUpsert->pNextUpsert==0 ){
154845        zWhich[0] = 0;
154846      }else{
154847        sqlite3_snprintf(sizeof(zWhich),zWhich,"%r ", nClause+1);
154848      }
154849      sqlite3ErrorMsg(pParse, "%sON CONFLICT clause does not match any "
154850                              "PRIMARY KEY or UNIQUE constraint", zWhich);
154851      return SQLITE_ERROR;
154852    }
154853  }
154854  return SQLITE_OK;
154855}
154856
154857/*
154858** Return true if pUpsert is the last ON CONFLICT clause with a
154859** conflict target, or if pUpsert is followed by another ON CONFLICT
154860** clause that targets the INTEGER PRIMARY KEY.
154861*/
154862SQLITE_PRIVATE int sqlite3UpsertNextIsIPK(Upsert *pUpsert){
154863  Upsert *pNext;
154864  if( NEVER(pUpsert==0) ) return 0;
154865  pNext = pUpsert->pNextUpsert;
154866  while( 1 /*exit-by-return*/ ){
154867    if( pNext==0 ) return 1;
154868    if( pNext->pUpsertTarget==0 ) return 1;
154869    if( pNext->pUpsertIdx==0 ) return 1;
154870    if( !pNext->isDup ) return 0;
154871    pNext = pNext->pNextUpsert;
154872  }
154873  return 0;
154874}
154875
154876/*
154877** Given the list of ON CONFLICT clauses described by pUpsert, and
154878** a particular index pIdx, return a pointer to the particular ON CONFLICT
154879** clause that applies to the index.  Or, if the index is not subject to
154880** any ON CONFLICT clause, return NULL.
154881*/
154882SQLITE_PRIVATE Upsert *sqlite3UpsertOfIndex(Upsert *pUpsert, Index *pIdx){
154883  while(
154884      pUpsert
154885   && pUpsert->pUpsertTarget!=0
154886   && pUpsert->pUpsertIdx!=pIdx
154887  ){
154888     pUpsert = pUpsert->pNextUpsert;
154889  }
154890  return pUpsert;
154891}
154892
154893/*
154894** Generate bytecode that does an UPDATE as part of an upsert.
154895**
154896** If pIdx is NULL, then the UNIQUE constraint that failed was the IPK.
154897** In this case parameter iCur is a cursor open on the table b-tree that
154898** currently points to the conflicting table row. Otherwise, if pIdx
154899** is not NULL, then pIdx is the constraint that failed and iCur is a
154900** cursor points to the conflicting row.
154901*/
154902SQLITE_PRIVATE void sqlite3UpsertDoUpdate(
154903  Parse *pParse,        /* The parsing and code-generating context */
154904  Upsert *pUpsert,      /* The ON CONFLICT clause for the upsert */
154905  Table *pTab,          /* The table being updated */
154906  Index *pIdx,          /* The UNIQUE constraint that failed */
154907  int iCur              /* Cursor for pIdx (or pTab if pIdx==NULL) */
154908){
154909  Vdbe *v = pParse->pVdbe;
154910  sqlite3 *db = pParse->db;
154911  SrcList *pSrc;            /* FROM clause for the UPDATE */
154912  int iDataCur;
154913  int i;
154914  Upsert *pTop = pUpsert;
154915
154916  assert( v!=0 );
154917  assert( pUpsert!=0 );
154918  iDataCur = pUpsert->iDataCur;
154919  pUpsert = sqlite3UpsertOfIndex(pTop, pIdx);
154920  VdbeNoopComment((v, "Begin DO UPDATE of UPSERT"));
154921  if( pIdx && iCur!=iDataCur ){
154922    if( HasRowid(pTab) ){
154923      int regRowid = sqlite3GetTempReg(pParse);
154924      sqlite3VdbeAddOp2(v, OP_IdxRowid, iCur, regRowid);
154925      sqlite3VdbeAddOp3(v, OP_SeekRowid, iDataCur, 0, regRowid);
154926      VdbeCoverage(v);
154927      sqlite3ReleaseTempReg(pParse, regRowid);
154928    }else{
154929      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
154930      int nPk = pPk->nKeyCol;
154931      int iPk = pParse->nMem+1;
154932      pParse->nMem += nPk;
154933      for(i=0; i<nPk; i++){
154934        int k;
154935        assert( pPk->aiColumn[i]>=0 );
154936        k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
154937        sqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i);
154938        VdbeComment((v, "%s.%s", pIdx->zName,
154939                    pTab->aCol[pPk->aiColumn[i]].zCnName));
154940      }
154941      sqlite3VdbeVerifyAbortable(v, OE_Abort);
154942      i = sqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk);
154943      VdbeCoverage(v);
154944      sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0,
154945            "corrupt database", P4_STATIC);
154946      sqlite3MayAbort(pParse);
154947      sqlite3VdbeJumpHere(v, i);
154948    }
154949  }
154950  /* pUpsert does not own pTop->pUpsertSrc - the outer INSERT statement does.
154951  ** So we have to make a copy before passing it down into sqlite3Update() */
154952  pSrc = sqlite3SrcListDup(db, pTop->pUpsertSrc, 0);
154953  /* excluded.* columns of type REAL need to be converted to a hard real */
154954  for(i=0; i<pTab->nCol; i++){
154955    if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
154956      sqlite3VdbeAddOp1(v, OP_RealAffinity, pTop->regData+i);
154957    }
154958  }
154959  sqlite3Update(pParse, pSrc, sqlite3ExprListDup(db,pUpsert->pUpsertSet,0),
154960      sqlite3ExprDup(db,pUpsert->pUpsertWhere,0), OE_Abort, 0, 0, pUpsert);
154961  VdbeNoopComment((v, "End DO UPDATE of UPSERT"));
154962}
154963
154964#endif /* SQLITE_OMIT_UPSERT */
154965
154966/************** End of upsert.c **********************************************/
154967/************** Begin file vacuum.c ******************************************/
154968/*
154969** 2003 April 6
154970**
154971** The author disclaims copyright to this source code.  In place of
154972** a legal notice, here is a blessing:
154973**
154974**    May you do good and not evil.
154975**    May you find forgiveness for yourself and forgive others.
154976**    May you share freely, never taking more than you give.
154977**
154978*************************************************************************
154979** This file contains code used to implement the VACUUM command.
154980**
154981** Most of the code in this file may be omitted by defining the
154982** SQLITE_OMIT_VACUUM macro.
154983*/
154984/* #include "sqliteInt.h" */
154985/* #include "vdbeInt.h" */
154986
154987#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
154988
154989/*
154990** Execute zSql on database db.
154991**
154992** If zSql returns rows, then each row will have exactly one
154993** column.  (This will only happen if zSql begins with "SELECT".)
154994** Take each row of result and call execSql() again recursively.
154995**
154996** The execSqlF() routine does the same thing, except it accepts
154997** a format string as its third argument
154998*/
154999static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
155000  sqlite3_stmt *pStmt;
155001  int rc;
155002
155003  /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
155004  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
155005  if( rc!=SQLITE_OK ) return rc;
155006  while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
155007    const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
155008    assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
155009    /* The secondary SQL must be one of CREATE TABLE, CREATE INDEX,
155010    ** or INSERT.  Historically there have been attacks that first
155011    ** corrupt the sqlite_schema.sql field with other kinds of statements
155012    ** then run VACUUM to get those statements to execute at inappropriate
155013    ** times. */
155014    if( zSubSql
155015     && (strncmp(zSubSql,"CRE",3)==0 || strncmp(zSubSql,"INS",3)==0)
155016    ){
155017      rc = execSql(db, pzErrMsg, zSubSql);
155018      if( rc!=SQLITE_OK ) break;
155019    }
155020  }
155021  assert( rc!=SQLITE_ROW );
155022  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
155023  if( rc ){
155024    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
155025  }
155026  (void)sqlite3_finalize(pStmt);
155027  return rc;
155028}
155029static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
155030  char *z;
155031  va_list ap;
155032  int rc;
155033  va_start(ap, zSql);
155034  z = sqlite3VMPrintf(db, zSql, ap);
155035  va_end(ap);
155036  if( z==0 ) return SQLITE_NOMEM;
155037  rc = execSql(db, pzErrMsg, z);
155038  sqlite3DbFree(db, z);
155039  return rc;
155040}
155041
155042/*
155043** The VACUUM command is used to clean up the database,
155044** collapse free space, etc.  It is modelled after the VACUUM command
155045** in PostgreSQL.  The VACUUM command works as follows:
155046**
155047**   (1)  Create a new transient database file
155048**   (2)  Copy all content from the database being vacuumed into
155049**        the new transient database file
155050**   (3)  Copy content from the transient database back into the
155051**        original database.
155052**
155053** The transient database requires temporary disk space approximately
155054** equal to the size of the original database.  The copy operation of
155055** step (3) requires additional temporary disk space approximately equal
155056** to the size of the original database for the rollback journal.
155057** Hence, temporary disk space that is approximately 2x the size of the
155058** original database is required.  Every page of the database is written
155059** approximately 3 times:  Once for step (2) and twice for step (3).
155060** Two writes per page are required in step (3) because the original
155061** database content must be written into the rollback journal prior to
155062** overwriting the database with the vacuumed content.
155063**
155064** Only 1x temporary space and only 1x writes would be required if
155065** the copy of step (3) were replaced by deleting the original database
155066** and renaming the transient database as the original.  But that will
155067** not work if other processes are attached to the original database.
155068** And a power loss in between deleting the original and renaming the
155069** transient would cause the database file to appear to be deleted
155070** following reboot.
155071*/
155072SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm, Expr *pInto){
155073  Vdbe *v = sqlite3GetVdbe(pParse);
155074  int iDb = 0;
155075  if( v==0 ) goto build_vacuum_end;
155076  if( pParse->nErr ) goto build_vacuum_end;
155077  if( pNm ){
155078#ifndef SQLITE_BUG_COMPATIBLE_20160819
155079    /* Default behavior:  Report an error if the argument to VACUUM is
155080    ** not recognized */
155081    iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
155082    if( iDb<0 ) goto build_vacuum_end;
155083#else
155084    /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
155085    ** to VACUUM are silently ignored.  This is a back-out of a bug fix that
155086    ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
155087    ** The buggy behavior is required for binary compatibility with some
155088    ** legacy applications. */
155089    iDb = sqlite3FindDb(pParse->db, pNm);
155090    if( iDb<0 ) iDb = 0;
155091#endif
155092  }
155093  if( iDb!=1 ){
155094    int iIntoReg = 0;
155095    if( pInto && sqlite3ResolveSelfReference(pParse,0,0,pInto,0)==0 ){
155096      iIntoReg = ++pParse->nMem;
155097      sqlite3ExprCode(pParse, pInto, iIntoReg);
155098    }
155099    sqlite3VdbeAddOp2(v, OP_Vacuum, iDb, iIntoReg);
155100    sqlite3VdbeUsesBtree(v, iDb);
155101  }
155102build_vacuum_end:
155103  sqlite3ExprDelete(pParse->db, pInto);
155104  return;
155105}
155106
155107/*
155108** This routine implements the OP_Vacuum opcode of the VDBE.
155109*/
155110SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(
155111  char **pzErrMsg,        /* Write error message here */
155112  sqlite3 *db,            /* Database connection */
155113  int iDb,                /* Which attached DB to vacuum */
155114  sqlite3_value *pOut     /* Write results here, if not NULL. VACUUM INTO */
155115){
155116  int rc = SQLITE_OK;     /* Return code from service routines */
155117  Btree *pMain;           /* The database being vacuumed */
155118  Btree *pTemp;           /* The temporary database we vacuum into */
155119  u32 saved_mDbFlags;     /* Saved value of db->mDbFlags */
155120  u64 saved_flags;        /* Saved value of db->flags */
155121  i64 saved_nChange;      /* Saved value of db->nChange */
155122  i64 saved_nTotalChange; /* Saved value of db->nTotalChange */
155123  u32 saved_openFlags;    /* Saved value of db->openFlags */
155124  u8 saved_mTrace;        /* Saved trace settings */
155125  Db *pDb = 0;            /* Database to detach at end of vacuum */
155126  int isMemDb;            /* True if vacuuming a :memory: database */
155127  int nRes;               /* Bytes of reserved space at the end of each page */
155128  int nDb;                /* Number of attached databases */
155129  const char *zDbMain;    /* Schema name of database to vacuum */
155130  const char *zOut;       /* Name of output file */
155131  u32 pgflags = PAGER_SYNCHRONOUS_OFF; /* sync flags for output db */
155132
155133  if( !db->autoCommit ){
155134    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
155135    return SQLITE_ERROR; /* IMP: R-12218-18073 */
155136  }
155137  if( db->nVdbeActive>1 ){
155138    sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
155139    return SQLITE_ERROR; /* IMP: R-15610-35227 */
155140  }
155141  saved_openFlags = db->openFlags;
155142  if( pOut ){
155143    if( sqlite3_value_type(pOut)!=SQLITE_TEXT ){
155144      sqlite3SetString(pzErrMsg, db, "non-text filename");
155145      return SQLITE_ERROR;
155146    }
155147    zOut = (const char*)sqlite3_value_text(pOut);
155148    db->openFlags &= ~SQLITE_OPEN_READONLY;
155149    db->openFlags |= SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
155150  }else{
155151    zOut = "";
155152  }
155153
155154  /* Save the current value of the database flags so that it can be
155155  ** restored before returning. Then set the writable-schema flag, and
155156  ** disable CHECK and foreign key constraints.  */
155157  saved_flags = db->flags;
155158  saved_mDbFlags = db->mDbFlags;
155159  saved_nChange = db->nChange;
155160  saved_nTotalChange = db->nTotalChange;
155161  saved_mTrace = db->mTrace;
155162  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
155163  db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
155164  db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder
155165                   | SQLITE_Defensive | SQLITE_CountRows);
155166  db->mTrace = 0;
155167
155168  zDbMain = db->aDb[iDb].zDbSName;
155169  pMain = db->aDb[iDb].pBt;
155170  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
155171
155172  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
155173  ** can be set to 'off' for this file, as it is not recovered if a crash
155174  ** occurs anyway. The integrity of the database is maintained by a
155175  ** (possibly synchronous) transaction opened on the main database before
155176  ** sqlite3BtreeCopyFile() is called.
155177  **
155178  ** An optimization would be to use a non-journaled pager.
155179  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
155180  ** that actually made the VACUUM run slower.  Very little journalling
155181  ** actually occurs when doing a vacuum since the vacuum_db is initially
155182  ** empty.  Only the journal header is written.  Apparently it takes more
155183  ** time to parse and run the PRAGMA to turn journalling off than it does
155184  ** to write the journal header file.
155185  */
155186  nDb = db->nDb;
155187  rc = execSqlF(db, pzErrMsg, "ATTACH %Q AS vacuum_db", zOut);
155188  db->openFlags = saved_openFlags;
155189  if( rc!=SQLITE_OK ) goto end_of_vacuum;
155190  assert( (db->nDb-1)==nDb );
155191  pDb = &db->aDb[nDb];
155192  assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
155193  pTemp = pDb->pBt;
155194  if( pOut ){
155195    sqlite3_file *id = sqlite3PagerFile(sqlite3BtreePager(pTemp));
155196    i64 sz = 0;
155197    if( id->pMethods!=0 && (sqlite3OsFileSize(id, &sz)!=SQLITE_OK || sz>0) ){
155198      rc = SQLITE_ERROR;
155199      sqlite3SetString(pzErrMsg, db, "output file already exists");
155200      goto end_of_vacuum;
155201    }
155202    db->mDbFlags |= DBFLAG_VacuumInto;
155203
155204    /* For a VACUUM INTO, the pager-flags are set to the same values as
155205    ** they are for the database being vacuumed, except that PAGER_CACHESPILL
155206    ** is always set. */
155207    pgflags = db->aDb[iDb].safety_level | (db->flags & PAGER_FLAGS_MASK);
155208  }
155209  nRes = sqlite3BtreeGetRequestedReserve(pMain);
155210
155211  sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
155212  sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
155213  sqlite3BtreeSetPagerFlags(pTemp, pgflags|PAGER_CACHESPILL);
155214
155215  /* Begin a transaction and take an exclusive lock on the main database
155216  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
155217  ** to ensure that we do not try to change the page-size on a WAL database.
155218  */
155219  rc = execSql(db, pzErrMsg, "BEGIN");
155220  if( rc!=SQLITE_OK ) goto end_of_vacuum;
155221  rc = sqlite3BtreeBeginTrans(pMain, pOut==0 ? 2 : 0, 0);
155222  if( rc!=SQLITE_OK ) goto end_of_vacuum;
155223
155224  /* Do not attempt to change the page size for a WAL database */
155225  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
155226                                               ==PAGER_JOURNALMODE_WAL
155227   && pOut==0
155228  ){
155229    db->nextPagesize = 0;
155230  }
155231
155232  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
155233   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
155234   || NEVER(db->mallocFailed)
155235  ){
155236    rc = SQLITE_NOMEM_BKPT;
155237    goto end_of_vacuum;
155238  }
155239
155240#ifndef SQLITE_OMIT_AUTOVACUUM
155241  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
155242                                           sqlite3BtreeGetAutoVacuum(pMain));
155243#endif
155244
155245  /* Query the schema of the main database. Create a mirror schema
155246  ** in the temporary database.
155247  */
155248  db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
155249  rc = execSqlF(db, pzErrMsg,
155250      "SELECT sql FROM \"%w\".sqlite_schema"
155251      " WHERE type='table'AND name<>'sqlite_sequence'"
155252      " AND coalesce(rootpage,1)>0",
155253      zDbMain
155254  );
155255  if( rc!=SQLITE_OK ) goto end_of_vacuum;
155256  rc = execSqlF(db, pzErrMsg,
155257      "SELECT sql FROM \"%w\".sqlite_schema"
155258      " WHERE type='index'",
155259      zDbMain
155260  );
155261  if( rc!=SQLITE_OK ) goto end_of_vacuum;
155262  db->init.iDb = 0;
155263
155264  /* Loop through the tables in the main database. For each, do
155265  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
155266  ** the contents to the temporary database.
155267  */
155268  rc = execSqlF(db, pzErrMsg,
155269      "SELECT'INSERT INTO vacuum_db.'||quote(name)"
155270      "||' SELECT*FROM\"%w\".'||quote(name)"
155271      "FROM vacuum_db.sqlite_schema "
155272      "WHERE type='table'AND coalesce(rootpage,1)>0",
155273      zDbMain
155274  );
155275  assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
155276  db->mDbFlags &= ~DBFLAG_Vacuum;
155277  if( rc!=SQLITE_OK ) goto end_of_vacuum;
155278
155279  /* Copy the triggers, views, and virtual tables from the main database
155280  ** over to the temporary database.  None of these objects has any
155281  ** associated storage, so all we have to do is copy their entries
155282  ** from the schema table.
155283  */
155284  rc = execSqlF(db, pzErrMsg,
155285      "INSERT INTO vacuum_db.sqlite_schema"
155286      " SELECT*FROM \"%w\".sqlite_schema"
155287      " WHERE type IN('view','trigger')"
155288      " OR(type='table'AND rootpage=0)",
155289      zDbMain
155290  );
155291  if( rc ) goto end_of_vacuum;
155292
155293  /* At this point, there is a write transaction open on both the
155294  ** vacuum database and the main database. Assuming no error occurs,
155295  ** both transactions are closed by this block - the main database
155296  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
155297  ** call to sqlite3BtreeCommit().
155298  */
155299  {
155300    u32 meta;
155301    int i;
155302
155303    /* This array determines which meta meta values are preserved in the
155304    ** vacuum.  Even entries are the meta value number and odd entries
155305    ** are an increment to apply to the meta value after the vacuum.
155306    ** The increment is used to increase the schema cookie so that other
155307    ** connections to the same database will know to reread the schema.
155308    */
155309    static const unsigned char aCopy[] = {
155310       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
155311       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
155312       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
155313       BTREE_USER_VERSION,       0,  /* Preserve the user version */
155314       BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
155315    };
155316
155317    assert( SQLITE_TXN_WRITE==sqlite3BtreeTxnState(pTemp) );
155318    assert( pOut!=0 || SQLITE_TXN_WRITE==sqlite3BtreeTxnState(pMain) );
155319
155320    /* Copy Btree meta values */
155321    for(i=0; i<ArraySize(aCopy); i+=2){
155322      /* GetMeta() and UpdateMeta() cannot fail in this context because
155323      ** we already have page 1 loaded into cache and marked dirty. */
155324      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
155325      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
155326      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
155327    }
155328
155329    if( pOut==0 ){
155330      rc = sqlite3BtreeCopyFile(pMain, pTemp);
155331    }
155332    if( rc!=SQLITE_OK ) goto end_of_vacuum;
155333    rc = sqlite3BtreeCommit(pTemp);
155334    if( rc!=SQLITE_OK ) goto end_of_vacuum;
155335#ifndef SQLITE_OMIT_AUTOVACUUM
155336    if( pOut==0 ){
155337      sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
155338    }
155339#endif
155340  }
155341
155342  assert( rc==SQLITE_OK );
155343  if( pOut==0 ){
155344    nRes = sqlite3BtreeGetRequestedReserve(pTemp);
155345    rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
155346  }
155347
155348end_of_vacuum:
155349  /* Restore the original value of db->flags */
155350  db->init.iDb = 0;
155351  db->mDbFlags = saved_mDbFlags;
155352  db->flags = saved_flags;
155353  db->nChange = saved_nChange;
155354  db->nTotalChange = saved_nTotalChange;
155355  db->mTrace = saved_mTrace;
155356  sqlite3BtreeSetPageSize(pMain, -1, 0, 1);
155357
155358  /* Currently there is an SQL level transaction open on the vacuum
155359  ** database. No locks are held on any other files (since the main file
155360  ** was committed at the btree level). So it safe to end the transaction
155361  ** by manually setting the autoCommit flag to true and detaching the
155362  ** vacuum database. The vacuum_db journal file is deleted when the pager
155363  ** is closed by the DETACH.
155364  */
155365  db->autoCommit = 1;
155366
155367  if( pDb ){
155368    sqlite3BtreeClose(pDb->pBt);
155369    pDb->pBt = 0;
155370    pDb->pSchema = 0;
155371  }
155372
155373  /* This both clears the schemas and reduces the size of the db->aDb[]
155374  ** array. */
155375  sqlite3ResetAllSchemasOfConnection(db);
155376
155377  return rc;
155378}
155379
155380#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
155381
155382/************** End of vacuum.c **********************************************/
155383/************** Begin file vtab.c ********************************************/
155384/*
155385** 2006 June 10
155386**
155387** The author disclaims copyright to this source code.  In place of
155388** a legal notice, here is a blessing:
155389**
155390**    May you do good and not evil.
155391**    May you find forgiveness for yourself and forgive others.
155392**    May you share freely, never taking more than you give.
155393**
155394*************************************************************************
155395** This file contains code used to help implement virtual tables.
155396*/
155397#ifndef SQLITE_OMIT_VIRTUALTABLE
155398/* #include "sqliteInt.h" */
155399
155400/*
155401** Before a virtual table xCreate() or xConnect() method is invoked, the
155402** sqlite3.pVtabCtx member variable is set to point to an instance of
155403** this struct allocated on the stack. It is used by the implementation of
155404** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
155405** are invoked only from within xCreate and xConnect methods.
155406*/
155407struct VtabCtx {
155408  VTable *pVTable;    /* The virtual table being constructed */
155409  Table *pTab;        /* The Table object to which the virtual table belongs */
155410  VtabCtx *pPrior;    /* Parent context (if any) */
155411  int bDeclared;      /* True after sqlite3_declare_vtab() is called */
155412};
155413
155414/*
155415** Construct and install a Module object for a virtual table.  When this
155416** routine is called, it is guaranteed that all appropriate locks are held
155417** and the module is not already part of the connection.
155418**
155419** If there already exists a module with zName, replace it with the new one.
155420** If pModule==0, then delete the module zName if it exists.
155421*/
155422SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
155423  sqlite3 *db,                    /* Database in which module is registered */
155424  const char *zName,              /* Name assigned to this module */
155425  const sqlite3_module *pModule,  /* The definition of the module */
155426  void *pAux,                     /* Context pointer for xCreate/xConnect */
155427  void (*xDestroy)(void *)        /* Module destructor function */
155428){
155429  Module *pMod;
155430  Module *pDel;
155431  char *zCopy;
155432  if( pModule==0 ){
155433    zCopy = (char*)zName;
155434    pMod = 0;
155435  }else{
155436    int nName = sqlite3Strlen30(zName);
155437    pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);
155438    if( pMod==0 ){
155439      sqlite3OomFault(db);
155440      return 0;
155441    }
155442    zCopy = (char *)(&pMod[1]);
155443    memcpy(zCopy, zName, nName+1);
155444    pMod->zName = zCopy;
155445    pMod->pModule = pModule;
155446    pMod->pAux = pAux;
155447    pMod->xDestroy = xDestroy;
155448    pMod->pEpoTab = 0;
155449    pMod->nRefModule = 1;
155450  }
155451  pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
155452  if( pDel ){
155453    if( pDel==pMod ){
155454      sqlite3OomFault(db);
155455      sqlite3DbFree(db, pDel);
155456      pMod = 0;
155457    }else{
155458      sqlite3VtabEponymousTableClear(db, pDel);
155459      sqlite3VtabModuleUnref(db, pDel);
155460    }
155461  }
155462  return pMod;
155463}
155464
155465/*
155466** The actual function that does the work of creating a new module.
155467** This function implements the sqlite3_create_module() and
155468** sqlite3_create_module_v2() interfaces.
155469*/
155470static int createModule(
155471  sqlite3 *db,                    /* Database in which module is registered */
155472  const char *zName,              /* Name assigned to this module */
155473  const sqlite3_module *pModule,  /* The definition of the module */
155474  void *pAux,                     /* Context pointer for xCreate/xConnect */
155475  void (*xDestroy)(void *)        /* Module destructor function */
155476){
155477  int rc = SQLITE_OK;
155478
155479  sqlite3_mutex_enter(db->mutex);
155480  (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
155481  rc = sqlite3ApiExit(db, rc);
155482  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
155483  sqlite3_mutex_leave(db->mutex);
155484  return rc;
155485}
155486
155487
155488/*
155489** External API function used to create a new virtual-table module.
155490*/
155491SQLITE_API int sqlite3_create_module(
155492  sqlite3 *db,                    /* Database in which module is registered */
155493  const char *zName,              /* Name assigned to this module */
155494  const sqlite3_module *pModule,  /* The definition of the module */
155495  void *pAux                      /* Context pointer for xCreate/xConnect */
155496){
155497#ifdef SQLITE_ENABLE_API_ARMOR
155498  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
155499#endif
155500  return createModule(db, zName, pModule, pAux, 0);
155501}
155502
155503/*
155504** External API function used to create a new virtual-table module.
155505*/
155506SQLITE_API int sqlite3_create_module_v2(
155507  sqlite3 *db,                    /* Database in which module is registered */
155508  const char *zName,              /* Name assigned to this module */
155509  const sqlite3_module *pModule,  /* The definition of the module */
155510  void *pAux,                     /* Context pointer for xCreate/xConnect */
155511  void (*xDestroy)(void *)        /* Module destructor function */
155512){
155513#ifdef SQLITE_ENABLE_API_ARMOR
155514  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
155515#endif
155516  return createModule(db, zName, pModule, pAux, xDestroy);
155517}
155518
155519/*
155520** External API to drop all virtual-table modules, except those named
155521** on the azNames list.
155522*/
155523SQLITE_API int sqlite3_drop_modules(sqlite3 *db, const char** azNames){
155524  HashElem *pThis, *pNext;
155525#ifdef SQLITE_ENABLE_API_ARMOR
155526  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
155527#endif
155528  for(pThis=sqliteHashFirst(&db->aModule); pThis; pThis=pNext){
155529    Module *pMod = (Module*)sqliteHashData(pThis);
155530    pNext = sqliteHashNext(pThis);
155531    if( azNames ){
155532      int ii;
155533      for(ii=0; azNames[ii]!=0 && strcmp(azNames[ii],pMod->zName)!=0; ii++){}
155534      if( azNames[ii]!=0 ) continue;
155535    }
155536    createModule(db, pMod->zName, 0, 0, 0);
155537  }
155538  return SQLITE_OK;
155539}
155540
155541/*
155542** Decrement the reference count on a Module object.  Destroy the
155543** module when the reference count reaches zero.
155544*/
155545SQLITE_PRIVATE void sqlite3VtabModuleUnref(sqlite3 *db, Module *pMod){
155546  assert( pMod->nRefModule>0 );
155547  pMod->nRefModule--;
155548  if( pMod->nRefModule==0 ){
155549    if( pMod->xDestroy ){
155550      pMod->xDestroy(pMod->pAux);
155551    }
155552    assert( pMod->pEpoTab==0 );
155553    sqlite3DbFree(db, pMod);
155554  }
155555}
155556
155557/*
155558** Lock the virtual table so that it cannot be disconnected.
155559** Locks nest.  Every lock should have a corresponding unlock.
155560** If an unlock is omitted, resources leaks will occur.
155561**
155562** If a disconnect is attempted while a virtual table is locked,
155563** the disconnect is deferred until all locks have been removed.
155564*/
155565SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
155566  pVTab->nRef++;
155567}
155568
155569
155570/*
155571** pTab is a pointer to a Table structure representing a virtual-table.
155572** Return a pointer to the VTable object used by connection db to access
155573** this virtual-table, if one has been created, or NULL otherwise.
155574*/
155575SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
155576  VTable *pVtab;
155577  assert( IsVirtual(pTab) );
155578  for(pVtab=pTab->u.vtab.p; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
155579  return pVtab;
155580}
155581
155582/*
155583** Decrement the ref-count on a virtual table object. When the ref-count
155584** reaches zero, call the xDisconnect() method to delete the object.
155585*/
155586SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
155587  sqlite3 *db = pVTab->db;
155588
155589  assert( db );
155590  assert( pVTab->nRef>0 );
155591  assert( db->eOpenState==SQLITE_STATE_OPEN
155592       || db->eOpenState==SQLITE_STATE_ZOMBIE );
155593
155594  pVTab->nRef--;
155595  if( pVTab->nRef==0 ){
155596    sqlite3_vtab *p = pVTab->pVtab;
155597    if( p ){
155598      p->pModule->xDisconnect(p);
155599    }
155600    sqlite3VtabModuleUnref(pVTab->db, pVTab->pMod);
155601    sqlite3DbFree(db, pVTab);
155602  }
155603}
155604
155605/*
155606** Table p is a virtual table. This function moves all elements in the
155607** p->u.vtab.p list to the sqlite3.pDisconnect lists of their associated
155608** database connections to be disconnected at the next opportunity.
155609** Except, if argument db is not NULL, then the entry associated with
155610** connection db is left in the p->u.vtab.p list.
155611*/
155612static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
155613  VTable *pRet = 0;
155614  VTable *pVTable;
155615
155616  assert( IsVirtual(p) );
155617  pVTable = p->u.vtab.p;
155618  p->u.vtab.p = 0;
155619
155620  /* Assert that the mutex (if any) associated with the BtShared database
155621  ** that contains table p is held by the caller. See header comments
155622  ** above function sqlite3VtabUnlockList() for an explanation of why
155623  ** this makes it safe to access the sqlite3.pDisconnect list of any
155624  ** database connection that may have an entry in the p->u.vtab.p list.
155625  */
155626  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
155627
155628  while( pVTable ){
155629    sqlite3 *db2 = pVTable->db;
155630    VTable *pNext = pVTable->pNext;
155631    assert( db2 );
155632    if( db2==db ){
155633      pRet = pVTable;
155634      p->u.vtab.p = pRet;
155635      pRet->pNext = 0;
155636    }else{
155637      pVTable->pNext = db2->pDisconnect;
155638      db2->pDisconnect = pVTable;
155639    }
155640    pVTable = pNext;
155641  }
155642
155643  assert( !db || pRet );
155644  return pRet;
155645}
155646
155647/*
155648** Table *p is a virtual table. This function removes the VTable object
155649** for table *p associated with database connection db from the linked
155650** list in p->pVTab. It also decrements the VTable ref count. This is
155651** used when closing database connection db to free all of its VTable
155652** objects without disturbing the rest of the Schema object (which may
155653** be being used by other shared-cache connections).
155654*/
155655SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
155656  VTable **ppVTab;
155657
155658  assert( IsVirtual(p) );
155659  assert( sqlite3BtreeHoldsAllMutexes(db) );
155660  assert( sqlite3_mutex_held(db->mutex) );
155661
155662  for(ppVTab=&p->u.vtab.p; *ppVTab; ppVTab=&(*ppVTab)->pNext){
155663    if( (*ppVTab)->db==db  ){
155664      VTable *pVTab = *ppVTab;
155665      *ppVTab = pVTab->pNext;
155666      sqlite3VtabUnlock(pVTab);
155667      break;
155668    }
155669  }
155670}
155671
155672
155673/*
155674** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
155675**
155676** This function may only be called when the mutexes associated with all
155677** shared b-tree databases opened using connection db are held by the
155678** caller. This is done to protect the sqlite3.pDisconnect list. The
155679** sqlite3.pDisconnect list is accessed only as follows:
155680**
155681**   1) By this function. In this case, all BtShared mutexes and the mutex
155682**      associated with the database handle itself must be held.
155683**
155684**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
155685**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
155686**      associated with the database the virtual table is stored in is held
155687**      or, if the virtual table is stored in a non-sharable database, then
155688**      the database handle mutex is held.
155689**
155690** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
155691** by multiple threads. It is thread-safe.
155692*/
155693SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
155694  VTable *p = db->pDisconnect;
155695
155696  assert( sqlite3BtreeHoldsAllMutexes(db) );
155697  assert( sqlite3_mutex_held(db->mutex) );
155698
155699  if( p ){
155700    db->pDisconnect = 0;
155701    do {
155702      VTable *pNext = p->pNext;
155703      sqlite3VtabUnlock(p);
155704      p = pNext;
155705    }while( p );
155706  }
155707}
155708
155709/*
155710** Clear any and all virtual-table information from the Table record.
155711** This routine is called, for example, just before deleting the Table
155712** record.
155713**
155714** Since it is a virtual-table, the Table structure contains a pointer
155715** to the head of a linked list of VTable structures. Each VTable
155716** structure is associated with a single sqlite3* user of the schema.
155717** The reference count of the VTable structure associated with database
155718** connection db is decremented immediately (which may lead to the
155719** structure being xDisconnected and free). Any other VTable structures
155720** in the list are moved to the sqlite3.pDisconnect list of the associated
155721** database connection.
155722*/
155723SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
155724  assert( IsVirtual(p) );
155725  assert( db!=0 );
155726  if( db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
155727  if( p->u.vtab.azArg ){
155728    int i;
155729    for(i=0; i<p->u.vtab.nArg; i++){
155730      if( i!=1 ) sqlite3DbFree(db, p->u.vtab.azArg[i]);
155731    }
155732    sqlite3DbFree(db, p->u.vtab.azArg);
155733  }
155734}
155735
155736/*
155737** Add a new module argument to pTable->u.vtab.azArg[].
155738** The string is not copied - the pointer is stored.  The
155739** string will be freed automatically when the table is
155740** deleted.
155741*/
155742static void addModuleArgument(Parse *pParse, Table *pTable, char *zArg){
155743  sqlite3_int64 nBytes;
155744  char **azModuleArg;
155745  sqlite3 *db = pParse->db;
155746
155747  assert( IsVirtual(pTable) );
155748  nBytes = sizeof(char *)*(2+pTable->u.vtab.nArg);
155749  if( pTable->u.vtab.nArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){
155750    sqlite3ErrorMsg(pParse, "too many columns on %s", pTable->zName);
155751  }
155752  azModuleArg = sqlite3DbRealloc(db, pTable->u.vtab.azArg, nBytes);
155753  if( azModuleArg==0 ){
155754    sqlite3DbFree(db, zArg);
155755  }else{
155756    int i = pTable->u.vtab.nArg++;
155757    azModuleArg[i] = zArg;
155758    azModuleArg[i+1] = 0;
155759    pTable->u.vtab.azArg = azModuleArg;
155760  }
155761}
155762
155763/*
155764** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
155765** statement.  The module name has been parsed, but the optional list
155766** of parameters that follow the module name are still pending.
155767*/
155768SQLITE_PRIVATE void sqlite3VtabBeginParse(
155769  Parse *pParse,        /* Parsing context */
155770  Token *pName1,        /* Name of new table, or database name */
155771  Token *pName2,        /* Name of new table or NULL */
155772  Token *pModuleName,   /* Name of the module for the virtual table */
155773  int ifNotExists       /* No error if the table already exists */
155774){
155775  Table *pTable;        /* The new virtual table */
155776  sqlite3 *db;          /* Database connection */
155777
155778  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
155779  pTable = pParse->pNewTable;
155780  if( pTable==0 ) return;
155781  assert( 0==pTable->pIndex );
155782  pTable->eTabType = TABTYP_VTAB;
155783
155784  db = pParse->db;
155785
155786  assert( pTable->u.vtab.nArg==0 );
155787  addModuleArgument(pParse, pTable, sqlite3NameFromToken(db, pModuleName));
155788  addModuleArgument(pParse, pTable, 0);
155789  addModuleArgument(pParse, pTable, sqlite3DbStrDup(db, pTable->zName));
155790  assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
155791       || (pParse->sNameToken.z==pName1->z && pName2->z==0)
155792  );
155793  pParse->sNameToken.n = (int)(
155794      &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
155795  );
155796
155797#ifndef SQLITE_OMIT_AUTHORIZATION
155798  /* Creating a virtual table invokes the authorization callback twice.
155799  ** The first invocation, to obtain permission to INSERT a row into the
155800  ** sqlite_schema table, has already been made by sqlite3StartTable().
155801  ** The second call, to obtain permission to create the table, is made now.
155802  */
155803  if( pTable->u.vtab.azArg ){
155804    int iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
155805    assert( iDb>=0 ); /* The database the table is being created in */
155806    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
155807            pTable->u.vtab.azArg[0], pParse->db->aDb[iDb].zDbSName);
155808  }
155809#endif
155810}
155811
155812/*
155813** This routine takes the module argument that has been accumulating
155814** in pParse->zArg[] and appends it to the list of arguments on the
155815** virtual table currently under construction in pParse->pTable.
155816*/
155817static void addArgumentToVtab(Parse *pParse){
155818  if( pParse->sArg.z && pParse->pNewTable ){
155819    const char *z = (const char*)pParse->sArg.z;
155820    int n = pParse->sArg.n;
155821    sqlite3 *db = pParse->db;
155822    addModuleArgument(pParse, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
155823  }
155824}
155825
155826/*
155827** The parser calls this routine after the CREATE VIRTUAL TABLE statement
155828** has been completely parsed.
155829*/
155830SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
155831  Table *pTab = pParse->pNewTable;  /* The table being constructed */
155832  sqlite3 *db = pParse->db;         /* The database connection */
155833
155834  if( pTab==0 ) return;
155835  assert( IsVirtual(pTab) );
155836  addArgumentToVtab(pParse);
155837  pParse->sArg.z = 0;
155838  if( pTab->u.vtab.nArg<1 ) return;
155839
155840  /* If the CREATE VIRTUAL TABLE statement is being entered for the
155841  ** first time (in other words if the virtual table is actually being
155842  ** created now instead of just being read out of sqlite_schema) then
155843  ** do additional initialization work and store the statement text
155844  ** in the sqlite_schema table.
155845  */
155846  if( !db->init.busy ){
155847    char *zStmt;
155848    char *zWhere;
155849    int iDb;
155850    int iReg;
155851    Vdbe *v;
155852
155853    sqlite3MayAbort(pParse);
155854
155855    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
155856    if( pEnd ){
155857      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
155858    }
155859    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
155860
155861    /* A slot for the record has already been allocated in the
155862    ** schema table.  We just need to update that slot with all
155863    ** the information we've collected.
155864    **
155865    ** The VM register number pParse->regRowid holds the rowid of an
155866    ** entry in the sqlite_schema table that was created for this vtab
155867    ** by sqlite3StartTable().
155868    */
155869    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
155870    sqlite3NestedParse(pParse,
155871      "UPDATE %Q." LEGACY_SCHEMA_TABLE " "
155872         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
155873       "WHERE rowid=#%d",
155874      db->aDb[iDb].zDbSName,
155875      pTab->zName,
155876      pTab->zName,
155877      zStmt,
155878      pParse->regRowid
155879    );
155880    v = sqlite3GetVdbe(pParse);
155881    sqlite3ChangeCookie(pParse, iDb);
155882
155883    sqlite3VdbeAddOp0(v, OP_Expire);
155884    zWhere = sqlite3MPrintf(db, "name=%Q AND sql=%Q", pTab->zName, zStmt);
155885    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere, 0);
155886    sqlite3DbFree(db, zStmt);
155887
155888    iReg = ++pParse->nMem;
155889    sqlite3VdbeLoadString(v, iReg, pTab->zName);
155890    sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
155891  }else{
155892    /* If we are rereading the sqlite_schema table create the in-memory
155893    ** record of the table. */
155894    Table *pOld;
155895    Schema *pSchema = pTab->pSchema;
155896    const char *zName = pTab->zName;
155897    assert( zName!=0 );
155898    sqlite3MarkAllShadowTablesOf(db, pTab);
155899    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
155900    if( pOld ){
155901      sqlite3OomFault(db);
155902      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
155903      return;
155904    }
155905    pParse->pNewTable = 0;
155906  }
155907}
155908
155909/*
155910** The parser calls this routine when it sees the first token
155911** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
155912*/
155913SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
155914  addArgumentToVtab(pParse);
155915  pParse->sArg.z = 0;
155916  pParse->sArg.n = 0;
155917}
155918
155919/*
155920** The parser calls this routine for each token after the first token
155921** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
155922*/
155923SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
155924  Token *pArg = &pParse->sArg;
155925  if( pArg->z==0 ){
155926    pArg->z = p->z;
155927    pArg->n = p->n;
155928  }else{
155929    assert(pArg->z <= p->z);
155930    pArg->n = (int)(&p->z[p->n] - pArg->z);
155931  }
155932}
155933
155934/*
155935** Invoke a virtual table constructor (either xCreate or xConnect). The
155936** pointer to the function to invoke is passed as the fourth parameter
155937** to this procedure.
155938*/
155939static int vtabCallConstructor(
155940  sqlite3 *db,
155941  Table *pTab,
155942  Module *pMod,
155943  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
155944  char **pzErr
155945){
155946  VtabCtx sCtx;
155947  VTable *pVTable;
155948  int rc;
155949  const char *const*azArg;
155950  int nArg = pTab->u.vtab.nArg;
155951  char *zErr = 0;
155952  char *zModuleName;
155953  int iDb;
155954  VtabCtx *pCtx;
155955
155956  assert( IsVirtual(pTab) );
155957  azArg = (const char *const*)pTab->u.vtab.azArg;
155958
155959  /* Check that the virtual-table is not already being initialized */
155960  for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
155961    if( pCtx->pTab==pTab ){
155962      *pzErr = sqlite3MPrintf(db,
155963          "vtable constructor called recursively: %s", pTab->zName
155964      );
155965      return SQLITE_LOCKED;
155966    }
155967  }
155968
155969  zModuleName = sqlite3DbStrDup(db, pTab->zName);
155970  if( !zModuleName ){
155971    return SQLITE_NOMEM_BKPT;
155972  }
155973
155974  pVTable = sqlite3MallocZero(sizeof(VTable));
155975  if( !pVTable ){
155976    sqlite3OomFault(db);
155977    sqlite3DbFree(db, zModuleName);
155978    return SQLITE_NOMEM_BKPT;
155979  }
155980  pVTable->db = db;
155981  pVTable->pMod = pMod;
155982  pVTable->eVtabRisk = SQLITE_VTABRISK_Normal;
155983
155984  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
155985  pTab->u.vtab.azArg[1] = db->aDb[iDb].zDbSName;
155986
155987  /* Invoke the virtual table constructor */
155988  assert( &db->pVtabCtx );
155989  assert( xConstruct );
155990  sCtx.pTab = pTab;
155991  sCtx.pVTable = pVTable;
155992  sCtx.pPrior = db->pVtabCtx;
155993  sCtx.bDeclared = 0;
155994  db->pVtabCtx = &sCtx;
155995  pTab->nTabRef++;
155996  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
155997  assert( pTab!=0 );
155998  assert( pTab->nTabRef>1 || rc!=SQLITE_OK );
155999  sqlite3DeleteTable(db, pTab);
156000  db->pVtabCtx = sCtx.pPrior;
156001  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
156002  assert( sCtx.pTab==pTab );
156003
156004  if( SQLITE_OK!=rc ){
156005    if( zErr==0 ){
156006      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
156007    }else {
156008      *pzErr = sqlite3MPrintf(db, "%s", zErr);
156009      sqlite3_free(zErr);
156010    }
156011    sqlite3DbFree(db, pVTable);
156012  }else if( ALWAYS(pVTable->pVtab) ){
156013    /* Justification of ALWAYS():  A correct vtab constructor must allocate
156014    ** the sqlite3_vtab object if successful.  */
156015    memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
156016    pVTable->pVtab->pModule = pMod->pModule;
156017    pMod->nRefModule++;
156018    pVTable->nRef = 1;
156019    if( sCtx.bDeclared==0 ){
156020      const char *zFormat = "vtable constructor did not declare schema: %s";
156021      *pzErr = sqlite3MPrintf(db, zFormat, zModuleName);
156022      sqlite3VtabUnlock(pVTable);
156023      rc = SQLITE_ERROR;
156024    }else{
156025      int iCol;
156026      u16 oooHidden = 0;
156027      /* If everything went according to plan, link the new VTable structure
156028      ** into the linked list headed by pTab->u.vtab.p. Then loop through the
156029      ** columns of the table to see if any of them contain the token "hidden".
156030      ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
156031      ** the type string.  */
156032      pVTable->pNext = pTab->u.vtab.p;
156033      pTab->u.vtab.p = pVTable;
156034
156035      for(iCol=0; iCol<pTab->nCol; iCol++){
156036        char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
156037        int nType;
156038        int i = 0;
156039        nType = sqlite3Strlen30(zType);
156040        for(i=0; i<nType; i++){
156041          if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
156042           && (i==0 || zType[i-1]==' ')
156043           && (zType[i+6]=='\0' || zType[i+6]==' ')
156044          ){
156045            break;
156046          }
156047        }
156048        if( i<nType ){
156049          int j;
156050          int nDel = 6 + (zType[i+6] ? 1 : 0);
156051          for(j=i; (j+nDel)<=nType; j++){
156052            zType[j] = zType[j+nDel];
156053          }
156054          if( zType[i]=='\0' && i>0 ){
156055            assert(zType[i-1]==' ');
156056            zType[i-1] = '\0';
156057          }
156058          pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
156059          pTab->tabFlags |= TF_HasHidden;
156060          oooHidden = TF_OOOHidden;
156061        }else{
156062          pTab->tabFlags |= oooHidden;
156063        }
156064      }
156065    }
156066  }
156067
156068  sqlite3DbFree(db, zModuleName);
156069  return rc;
156070}
156071
156072/*
156073** This function is invoked by the parser to call the xConnect() method
156074** of the virtual table pTab. If an error occurs, an error code is returned
156075** and an error left in pParse.
156076**
156077** This call is a no-op if table pTab is not a virtual table.
156078*/
156079SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
156080  sqlite3 *db = pParse->db;
156081  const char *zMod;
156082  Module *pMod;
156083  int rc;
156084
156085  assert( pTab );
156086  assert( IsVirtual(pTab) );
156087  if( sqlite3GetVTable(db, pTab) ){
156088    return SQLITE_OK;
156089  }
156090
156091  /* Locate the required virtual table module */
156092  zMod = pTab->u.vtab.azArg[0];
156093  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
156094
156095  if( !pMod ){
156096    const char *zModule = pTab->u.vtab.azArg[0];
156097    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
156098    rc = SQLITE_ERROR;
156099  }else{
156100    char *zErr = 0;
156101    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
156102    if( rc!=SQLITE_OK ){
156103      sqlite3ErrorMsg(pParse, "%s", zErr);
156104      pParse->rc = rc;
156105    }
156106    sqlite3DbFree(db, zErr);
156107  }
156108
156109  return rc;
156110}
156111/*
156112** Grow the db->aVTrans[] array so that there is room for at least one
156113** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
156114*/
156115static int growVTrans(sqlite3 *db){
156116  const int ARRAY_INCR = 5;
156117
156118  /* Grow the sqlite3.aVTrans array if required */
156119  if( (db->nVTrans%ARRAY_INCR)==0 ){
156120    VTable **aVTrans;
156121    sqlite3_int64 nBytes = sizeof(sqlite3_vtab*)*
156122                                 ((sqlite3_int64)db->nVTrans + ARRAY_INCR);
156123    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
156124    if( !aVTrans ){
156125      return SQLITE_NOMEM_BKPT;
156126    }
156127    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
156128    db->aVTrans = aVTrans;
156129  }
156130
156131  return SQLITE_OK;
156132}
156133
156134/*
156135** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
156136** have already been reserved using growVTrans().
156137*/
156138static void addToVTrans(sqlite3 *db, VTable *pVTab){
156139  /* Add pVtab to the end of sqlite3.aVTrans */
156140  db->aVTrans[db->nVTrans++] = pVTab;
156141  sqlite3VtabLock(pVTab);
156142}
156143
156144/*
156145** This function is invoked by the vdbe to call the xCreate method
156146** of the virtual table named zTab in database iDb.
156147**
156148** If an error occurs, *pzErr is set to point to an English language
156149** description of the error and an SQLITE_XXX error code is returned.
156150** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
156151*/
156152SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
156153  int rc = SQLITE_OK;
156154  Table *pTab;
156155  Module *pMod;
156156  const char *zMod;
156157
156158  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
156159  assert( pTab && IsVirtual(pTab) && !pTab->u.vtab.p );
156160
156161  /* Locate the required virtual table module */
156162  zMod = pTab->u.vtab.azArg[0];
156163  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
156164
156165  /* If the module has been registered and includes a Create method,
156166  ** invoke it now. If the module has not been registered, return an
156167  ** error. Otherwise, do nothing.
156168  */
156169  if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
156170    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
156171    rc = SQLITE_ERROR;
156172  }else{
156173    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
156174  }
156175
156176  /* Justification of ALWAYS():  The xConstructor method is required to
156177  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
156178  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
156179    rc = growVTrans(db);
156180    if( rc==SQLITE_OK ){
156181      addToVTrans(db, sqlite3GetVTable(db, pTab));
156182    }
156183  }
156184
156185  return rc;
156186}
156187
156188/*
156189** This function is used to set the schema of a virtual table.  It is only
156190** valid to call this function from within the xCreate() or xConnect() of a
156191** virtual table module.
156192*/
156193SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
156194  VtabCtx *pCtx;
156195  int rc = SQLITE_OK;
156196  Table *pTab;
156197  Parse sParse;
156198  int initBusy;
156199  int i;
156200  const unsigned char *z;
156201  static const u8 aKeyword[] = { TK_CREATE, TK_TABLE, 0 };
156202
156203#ifdef SQLITE_ENABLE_API_ARMOR
156204  if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
156205    return SQLITE_MISUSE_BKPT;
156206  }
156207#endif
156208
156209  /* Verify that the first two keywords in the CREATE TABLE statement
156210  ** really are "CREATE" and "TABLE".  If this is not the case, then
156211  ** sqlite3_declare_vtab() is being misused.
156212  */
156213  z = (const unsigned char*)zCreateTable;
156214  for(i=0; aKeyword[i]; i++){
156215    int tokenType = 0;
156216    do{ z += sqlite3GetToken(z, &tokenType); }while( tokenType==TK_SPACE );
156217    if( tokenType!=aKeyword[i] ){
156218      sqlite3ErrorWithMsg(db, SQLITE_ERROR, "syntax error");
156219      return SQLITE_ERROR;
156220    }
156221  }
156222
156223  sqlite3_mutex_enter(db->mutex);
156224  pCtx = db->pVtabCtx;
156225  if( !pCtx || pCtx->bDeclared ){
156226    sqlite3Error(db, SQLITE_MISUSE_BKPT);
156227    sqlite3_mutex_leave(db->mutex);
156228    return SQLITE_MISUSE_BKPT;
156229  }
156230
156231  pTab = pCtx->pTab;
156232  assert( IsVirtual(pTab) );
156233
156234  sqlite3ParseObjectInit(&sParse, db);
156235  sParse.eParseMode = PARSE_MODE_DECLARE_VTAB;
156236  sParse.disableTriggers = 1;
156237  /* We should never be able to reach this point while loading the
156238  ** schema.  Nevertheless, defend against that (turn off db->init.busy)
156239  ** in case a bug arises. */
156240  assert( db->init.busy==0 );
156241  initBusy = db->init.busy;
156242  db->init.busy = 0;
156243  sParse.nQueryLoop = 1;
156244  if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable) ){
156245    assert( sParse.pNewTable!=0 );
156246    assert( !db->mallocFailed );
156247    assert( IsOrdinaryTable(sParse.pNewTable) );
156248    assert( sParse.zErrMsg==0 );
156249    if( !pTab->aCol ){
156250      Table *pNew = sParse.pNewTable;
156251      Index *pIdx;
156252      pTab->aCol = pNew->aCol;
156253      sqlite3ExprListDelete(db, pNew->u.tab.pDfltList);
156254      pTab->nNVCol = pTab->nCol = pNew->nCol;
156255      pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
156256      pNew->nCol = 0;
156257      pNew->aCol = 0;
156258      assert( pTab->pIndex==0 );
156259      assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );
156260      if( !HasRowid(pNew)
156261       && pCtx->pVTable->pMod->pModule->xUpdate!=0
156262       && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
156263      ){
156264        /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
156265        ** or else must have a single-column PRIMARY KEY */
156266        rc = SQLITE_ERROR;
156267      }
156268      pIdx = pNew->pIndex;
156269      if( pIdx ){
156270        assert( pIdx->pNext==0 );
156271        pTab->pIndex = pIdx;
156272        pNew->pIndex = 0;
156273        pIdx->pTable = pTab;
156274      }
156275    }
156276    pCtx->bDeclared = 1;
156277  }else{
156278    sqlite3ErrorWithMsg(db, SQLITE_ERROR,
156279          (sParse.zErrMsg ? "%s" : 0), sParse.zErrMsg);
156280    sqlite3DbFree(db, sParse.zErrMsg);
156281    rc = SQLITE_ERROR;
156282  }
156283  sParse.eParseMode = PARSE_MODE_NORMAL;
156284
156285  if( sParse.pVdbe ){
156286    sqlite3VdbeFinalize(sParse.pVdbe);
156287  }
156288  sqlite3DeleteTable(db, sParse.pNewTable);
156289  sqlite3ParseObjectReset(&sParse);
156290  db->init.busy = initBusy;
156291
156292  assert( (rc&0xff)==rc );
156293  rc = sqlite3ApiExit(db, rc);
156294  sqlite3_mutex_leave(db->mutex);
156295  return rc;
156296}
156297
156298/*
156299** This function is invoked by the vdbe to call the xDestroy method
156300** of the virtual table named zTab in database iDb. This occurs
156301** when a DROP TABLE is mentioned.
156302**
156303** This call is a no-op if zTab is not a virtual table.
156304*/
156305SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
156306  int rc = SQLITE_OK;
156307  Table *pTab;
156308
156309  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
156310  if( ALWAYS(pTab!=0)
156311   && ALWAYS(IsVirtual(pTab))
156312   && ALWAYS(pTab->u.vtab.p!=0)
156313  ){
156314    VTable *p;
156315    int (*xDestroy)(sqlite3_vtab *);
156316    for(p=pTab->u.vtab.p; p; p=p->pNext){
156317      assert( p->pVtab );
156318      if( p->pVtab->nRef>0 ){
156319        return SQLITE_LOCKED;
156320      }
156321    }
156322    p = vtabDisconnectAll(db, pTab);
156323    xDestroy = p->pMod->pModule->xDestroy;
156324    if( xDestroy==0 ) xDestroy = p->pMod->pModule->xDisconnect;
156325    assert( xDestroy!=0 );
156326    pTab->nTabRef++;
156327    rc = xDestroy(p->pVtab);
156328    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
156329    if( rc==SQLITE_OK ){
156330      assert( pTab->u.vtab.p==p && p->pNext==0 );
156331      p->pVtab = 0;
156332      pTab->u.vtab.p = 0;
156333      sqlite3VtabUnlock(p);
156334    }
156335    sqlite3DeleteTable(db, pTab);
156336  }
156337
156338  return rc;
156339}
156340
156341/*
156342** This function invokes either the xRollback or xCommit method
156343** of each of the virtual tables in the sqlite3.aVTrans array. The method
156344** called is identified by the second argument, "offset", which is
156345** the offset of the method to call in the sqlite3_module structure.
156346**
156347** The array is cleared after invoking the callbacks.
156348*/
156349static void callFinaliser(sqlite3 *db, int offset){
156350  int i;
156351  if( db->aVTrans ){
156352    VTable **aVTrans = db->aVTrans;
156353    db->aVTrans = 0;
156354    for(i=0; i<db->nVTrans; i++){
156355      VTable *pVTab = aVTrans[i];
156356      sqlite3_vtab *p = pVTab->pVtab;
156357      if( p ){
156358        int (*x)(sqlite3_vtab *);
156359        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
156360        if( x ) x(p);
156361      }
156362      pVTab->iSavepoint = 0;
156363      sqlite3VtabUnlock(pVTab);
156364    }
156365    sqlite3DbFree(db, aVTrans);
156366    db->nVTrans = 0;
156367  }
156368}
156369
156370/*
156371** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
156372** array. Return the error code for the first error that occurs, or
156373** SQLITE_OK if all xSync operations are successful.
156374**
156375** If an error message is available, leave it in p->zErrMsg.
156376*/
156377SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
156378  int i;
156379  int rc = SQLITE_OK;
156380  VTable **aVTrans = db->aVTrans;
156381
156382  db->aVTrans = 0;
156383  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
156384    int (*x)(sqlite3_vtab *);
156385    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
156386    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
156387      rc = x(pVtab);
156388      sqlite3VtabImportErrmsg(p, pVtab);
156389    }
156390  }
156391  db->aVTrans = aVTrans;
156392  return rc;
156393}
156394
156395/*
156396** Invoke the xRollback method of all virtual tables in the
156397** sqlite3.aVTrans array. Then clear the array itself.
156398*/
156399SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
156400  callFinaliser(db, offsetof(sqlite3_module,xRollback));
156401  return SQLITE_OK;
156402}
156403
156404/*
156405** Invoke the xCommit method of all virtual tables in the
156406** sqlite3.aVTrans array. Then clear the array itself.
156407*/
156408SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
156409  callFinaliser(db, offsetof(sqlite3_module,xCommit));
156410  return SQLITE_OK;
156411}
156412
156413/*
156414** If the virtual table pVtab supports the transaction interface
156415** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
156416** not currently open, invoke the xBegin method now.
156417**
156418** If the xBegin call is successful, place the sqlite3_vtab pointer
156419** in the sqlite3.aVTrans array.
156420*/
156421SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
156422  int rc = SQLITE_OK;
156423  const sqlite3_module *pModule;
156424
156425  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
156426  ** than zero, then this function is being called from within a
156427  ** virtual module xSync() callback. It is illegal to write to
156428  ** virtual module tables in this case, so return SQLITE_LOCKED.
156429  */
156430  if( sqlite3VtabInSync(db) ){
156431    return SQLITE_LOCKED;
156432  }
156433  if( !pVTab ){
156434    return SQLITE_OK;
156435  }
156436  pModule = pVTab->pVtab->pModule;
156437
156438  if( pModule->xBegin ){
156439    int i;
156440
156441    /* If pVtab is already in the aVTrans array, return early */
156442    for(i=0; i<db->nVTrans; i++){
156443      if( db->aVTrans[i]==pVTab ){
156444        return SQLITE_OK;
156445      }
156446    }
156447
156448    /* Invoke the xBegin method. If successful, add the vtab to the
156449    ** sqlite3.aVTrans[] array. */
156450    rc = growVTrans(db);
156451    if( rc==SQLITE_OK ){
156452      rc = pModule->xBegin(pVTab->pVtab);
156453      if( rc==SQLITE_OK ){
156454        int iSvpt = db->nStatement + db->nSavepoint;
156455        addToVTrans(db, pVTab);
156456        if( iSvpt && pModule->xSavepoint ){
156457          pVTab->iSavepoint = iSvpt;
156458          rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
156459        }
156460      }
156461    }
156462  }
156463  return rc;
156464}
156465
156466/*
156467** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
156468** virtual tables that currently have an open transaction. Pass iSavepoint
156469** as the second argument to the virtual table method invoked.
156470**
156471** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
156472** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
156473** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
156474** an open transaction is invoked.
156475**
156476** If any virtual table method returns an error code other than SQLITE_OK,
156477** processing is abandoned and the error returned to the caller of this
156478** function immediately. If all calls to virtual table methods are successful,
156479** SQLITE_OK is returned.
156480*/
156481SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
156482  int rc = SQLITE_OK;
156483
156484  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
156485  assert( iSavepoint>=-1 );
156486  if( db->aVTrans ){
156487    int i;
156488    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
156489      VTable *pVTab = db->aVTrans[i];
156490      const sqlite3_module *pMod = pVTab->pMod->pModule;
156491      if( pVTab->pVtab && pMod->iVersion>=2 ){
156492        int (*xMethod)(sqlite3_vtab *, int);
156493        sqlite3VtabLock(pVTab);
156494        switch( op ){
156495          case SAVEPOINT_BEGIN:
156496            xMethod = pMod->xSavepoint;
156497            pVTab->iSavepoint = iSavepoint+1;
156498            break;
156499          case SAVEPOINT_ROLLBACK:
156500            xMethod = pMod->xRollbackTo;
156501            break;
156502          default:
156503            xMethod = pMod->xRelease;
156504            break;
156505        }
156506        if( xMethod && pVTab->iSavepoint>iSavepoint ){
156507          u64 savedFlags = (db->flags & SQLITE_Defensive);
156508          db->flags &= ~(u64)SQLITE_Defensive;
156509          rc = xMethod(pVTab->pVtab, iSavepoint);
156510          db->flags |= savedFlags;
156511        }
156512        sqlite3VtabUnlock(pVTab);
156513      }
156514    }
156515  }
156516  return rc;
156517}
156518
156519/*
156520** The first parameter (pDef) is a function implementation.  The
156521** second parameter (pExpr) is the first argument to this function.
156522** If pExpr is a column in a virtual table, then let the virtual
156523** table implementation have an opportunity to overload the function.
156524**
156525** This routine is used to allow virtual table implementations to
156526** overload MATCH, LIKE, GLOB, and REGEXP operators.
156527**
156528** Return either the pDef argument (indicating no change) or a
156529** new FuncDef structure that is marked as ephemeral using the
156530** SQLITE_FUNC_EPHEM flag.
156531*/
156532SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
156533  sqlite3 *db,    /* Database connection for reporting malloc problems */
156534  FuncDef *pDef,  /* Function to possibly overload */
156535  int nArg,       /* Number of arguments to the function */
156536  Expr *pExpr     /* First argument to the function */
156537){
156538  Table *pTab;
156539  sqlite3_vtab *pVtab;
156540  sqlite3_module *pMod;
156541  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
156542  void *pArg = 0;
156543  FuncDef *pNew;
156544  int rc = 0;
156545
156546  /* Check to see the left operand is a column in a virtual table */
156547  if( NEVER(pExpr==0) ) return pDef;
156548  if( pExpr->op!=TK_COLUMN ) return pDef;
156549  assert( ExprUseYTab(pExpr) );
156550  pTab = pExpr->y.pTab;
156551  if( NEVER(pTab==0) ) return pDef;
156552  if( !IsVirtual(pTab) ) return pDef;
156553  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
156554  assert( pVtab!=0 );
156555  assert( pVtab->pModule!=0 );
156556  pMod = (sqlite3_module *)pVtab->pModule;
156557  if( pMod->xFindFunction==0 ) return pDef;
156558
156559  /* Call the xFindFunction method on the virtual table implementation
156560  ** to see if the implementation wants to overload this function.
156561  **
156562  ** Though undocumented, we have historically always invoked xFindFunction
156563  ** with an all lower-case function name.  Continue in this tradition to
156564  ** avoid any chance of an incompatibility.
156565  */
156566#ifdef SQLITE_DEBUG
156567  {
156568    int i;
156569    for(i=0; pDef->zName[i]; i++){
156570      unsigned char x = (unsigned char)pDef->zName[i];
156571      assert( x==sqlite3UpperToLower[x] );
156572    }
156573  }
156574#endif
156575  rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg);
156576  if( rc==0 ){
156577    return pDef;
156578  }
156579
156580  /* Create a new ephemeral function definition for the overloaded
156581  ** function */
156582  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
156583                             + sqlite3Strlen30(pDef->zName) + 1);
156584  if( pNew==0 ){
156585    return pDef;
156586  }
156587  *pNew = *pDef;
156588  pNew->zName = (const char*)&pNew[1];
156589  memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
156590  pNew->xSFunc = xSFunc;
156591  pNew->pUserData = pArg;
156592  pNew->funcFlags |= SQLITE_FUNC_EPHEM;
156593  return pNew;
156594}
156595
156596/*
156597** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
156598** array so that an OP_VBegin will get generated for it.  Add pTab to the
156599** array if it is missing.  If pTab is already in the array, this routine
156600** is a no-op.
156601*/
156602SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
156603  Parse *pToplevel = sqlite3ParseToplevel(pParse);
156604  int i, n;
156605  Table **apVtabLock;
156606
156607  assert( IsVirtual(pTab) );
156608  for(i=0; i<pToplevel->nVtabLock; i++){
156609    if( pTab==pToplevel->apVtabLock[i] ) return;
156610  }
156611  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
156612  apVtabLock = sqlite3Realloc(pToplevel->apVtabLock, n);
156613  if( apVtabLock ){
156614    pToplevel->apVtabLock = apVtabLock;
156615    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
156616  }else{
156617    sqlite3OomFault(pToplevel->db);
156618  }
156619}
156620
156621/*
156622** Check to see if virtual table module pMod can be have an eponymous
156623** virtual table instance.  If it can, create one if one does not already
156624** exist. Return non-zero if either the eponymous virtual table instance
156625** exists when this routine returns or if an attempt to create it failed
156626** and an error message was left in pParse.
156627**
156628** An eponymous virtual table instance is one that is named after its
156629** module, and more importantly, does not require a CREATE VIRTUAL TABLE
156630** statement in order to come into existence.  Eponymous virtual table
156631** instances always exist.  They cannot be DROP-ed.
156632**
156633** Any virtual table module for which xConnect and xCreate are the same
156634** method can have an eponymous virtual table instance.
156635*/
156636SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
156637  const sqlite3_module *pModule = pMod->pModule;
156638  Table *pTab;
156639  char *zErr = 0;
156640  int rc;
156641  sqlite3 *db = pParse->db;
156642  if( pMod->pEpoTab ) return 1;
156643  if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
156644  pTab = sqlite3DbMallocZero(db, sizeof(Table));
156645  if( pTab==0 ) return 0;
156646  pTab->zName = sqlite3DbStrDup(db, pMod->zName);
156647  if( pTab->zName==0 ){
156648    sqlite3DbFree(db, pTab);
156649    return 0;
156650  }
156651  pMod->pEpoTab = pTab;
156652  pTab->nTabRef = 1;
156653  pTab->eTabType = TABTYP_VTAB;
156654  pTab->pSchema = db->aDb[0].pSchema;
156655  assert( pTab->u.vtab.nArg==0 );
156656  pTab->iPKey = -1;
156657  pTab->tabFlags |= TF_Eponymous;
156658  addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
156659  addModuleArgument(pParse, pTab, 0);
156660  addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
156661  rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
156662  if( rc ){
156663    sqlite3ErrorMsg(pParse, "%s", zErr);
156664    sqlite3DbFree(db, zErr);
156665    sqlite3VtabEponymousTableClear(db, pMod);
156666  }
156667  return 1;
156668}
156669
156670/*
156671** Erase the eponymous virtual table instance associated with
156672** virtual table module pMod, if it exists.
156673*/
156674SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
156675  Table *pTab = pMod->pEpoTab;
156676  if( pTab!=0 ){
156677    /* Mark the table as Ephemeral prior to deleting it, so that the
156678    ** sqlite3DeleteTable() routine will know that it is not stored in
156679    ** the schema. */
156680    pTab->tabFlags |= TF_Ephemeral;
156681    sqlite3DeleteTable(db, pTab);
156682    pMod->pEpoTab = 0;
156683  }
156684}
156685
156686/*
156687** Return the ON CONFLICT resolution mode in effect for the virtual
156688** table update operation currently in progress.
156689**
156690** The results of this routine are undefined unless it is called from
156691** within an xUpdate method.
156692*/
156693SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
156694  static const unsigned char aMap[] = {
156695    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
156696  };
156697#ifdef SQLITE_ENABLE_API_ARMOR
156698  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
156699#endif
156700  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
156701  assert( OE_Ignore==4 && OE_Replace==5 );
156702  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
156703  return (int)aMap[db->vtabOnConflict-1];
156704}
156705
156706/*
156707** Call from within the xCreate() or xConnect() methods to provide
156708** the SQLite core with additional information about the behavior
156709** of the virtual table being implemented.
156710*/
156711SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
156712  va_list ap;
156713  int rc = SQLITE_OK;
156714  VtabCtx *p;
156715
156716#ifdef SQLITE_ENABLE_API_ARMOR
156717  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
156718#endif
156719  sqlite3_mutex_enter(db->mutex);
156720  p = db->pVtabCtx;
156721  if( !p ){
156722    rc = SQLITE_MISUSE_BKPT;
156723  }else{
156724    assert( p->pTab==0 || IsVirtual(p->pTab) );
156725    va_start(ap, op);
156726    switch( op ){
156727      case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
156728        p->pVTable->bConstraint = (u8)va_arg(ap, int);
156729        break;
156730      }
156731      case SQLITE_VTAB_INNOCUOUS: {
156732        p->pVTable->eVtabRisk = SQLITE_VTABRISK_Low;
156733        break;
156734      }
156735      case SQLITE_VTAB_DIRECTONLY: {
156736        p->pVTable->eVtabRisk = SQLITE_VTABRISK_High;
156737        break;
156738      }
156739      case SQLITE_VTAB_USES_ALL_SCHEMAS: {
156740        p->pVTable->bAllSchemas = 1;
156741        break;
156742      }
156743      default: {
156744        rc = SQLITE_MISUSE_BKPT;
156745        break;
156746      }
156747    }
156748    va_end(ap);
156749  }
156750
156751  if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
156752  sqlite3_mutex_leave(db->mutex);
156753  return rc;
156754}
156755
156756#endif /* SQLITE_OMIT_VIRTUALTABLE */
156757
156758/************** End of vtab.c ************************************************/
156759/************** Begin file wherecode.c ***************************************/
156760/*
156761** 2015-06-06
156762**
156763** The author disclaims copyright to this source code.  In place of
156764** a legal notice, here is a blessing:
156765**
156766**    May you do good and not evil.
156767**    May you find forgiveness for yourself and forgive others.
156768**    May you share freely, never taking more than you give.
156769**
156770*************************************************************************
156771** This module contains C code that generates VDBE code used to process
156772** the WHERE clause of SQL statements.
156773**
156774** This file was split off from where.c on 2015-06-06 in order to reduce the
156775** size of where.c and make it easier to edit.  This file contains the routines
156776** that actually generate the bulk of the WHERE loop code.  The original where.c
156777** file retains the code that does query planning and analysis.
156778*/
156779/* #include "sqliteInt.h" */
156780/************** Include whereInt.h in the middle of wherecode.c **************/
156781/************** Begin file whereInt.h ****************************************/
156782/*
156783** 2013-11-12
156784**
156785** The author disclaims copyright to this source code.  In place of
156786** a legal notice, here is a blessing:
156787**
156788**    May you do good and not evil.
156789**    May you find forgiveness for yourself and forgive others.
156790**    May you share freely, never taking more than you give.
156791**
156792*************************************************************************
156793**
156794** This file contains structure and macro definitions for the query
156795** planner logic in "where.c".  These definitions are broken out into
156796** a separate source file for easier editing.
156797*/
156798#ifndef SQLITE_WHEREINT_H
156799#define SQLITE_WHEREINT_H
156800
156801
156802/* Forward references
156803*/
156804typedef struct WhereClause WhereClause;
156805typedef struct WhereMaskSet WhereMaskSet;
156806typedef struct WhereOrInfo WhereOrInfo;
156807typedef struct WhereAndInfo WhereAndInfo;
156808typedef struct WhereLevel WhereLevel;
156809typedef struct WhereLoop WhereLoop;
156810typedef struct WherePath WherePath;
156811typedef struct WhereTerm WhereTerm;
156812typedef struct WhereLoopBuilder WhereLoopBuilder;
156813typedef struct WhereScan WhereScan;
156814typedef struct WhereOrCost WhereOrCost;
156815typedef struct WhereOrSet WhereOrSet;
156816typedef struct WhereMemBlock WhereMemBlock;
156817typedef struct WhereRightJoin WhereRightJoin;
156818
156819/*
156820** This object is a header on a block of allocated memory that will be
156821** automatically freed when its WInfo object is destructed.
156822*/
156823struct WhereMemBlock {
156824  WhereMemBlock *pNext;      /* Next block in the chain */
156825  u64 sz;                    /* Bytes of space */
156826};
156827
156828/*
156829** Extra information attached to a WhereLevel that is a RIGHT JOIN.
156830*/
156831struct WhereRightJoin {
156832  int iMatch;          /* Cursor used to determine prior matched rows */
156833  int regBloom;        /* Bloom filter for iRJMatch */
156834  int regReturn;       /* Return register for the interior subroutine */
156835  int addrSubrtn;      /* Starting address for the interior subroutine */
156836  int endSubrtn;       /* The last opcode in the interior subroutine */
156837};
156838
156839/*
156840** This object contains information needed to implement a single nested
156841** loop in WHERE clause.
156842**
156843** Contrast this object with WhereLoop.  This object describes the
156844** implementation of the loop.  WhereLoop describes the algorithm.
156845** This object contains a pointer to the WhereLoop algorithm as one of
156846** its elements.
156847**
156848** The WhereInfo object contains a single instance of this object for
156849** each term in the FROM clause (which is to say, for each of the
156850** nested loops as implemented).  The order of WhereLevel objects determines
156851** the loop nested order, with WhereInfo.a[0] being the outer loop and
156852** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
156853*/
156854struct WhereLevel {
156855  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
156856  int iTabCur;          /* The VDBE cursor used to access the table */
156857  int iIdxCur;          /* The VDBE cursor used to access pIdx */
156858  int addrBrk;          /* Jump here to break out of the loop */
156859  int addrNxt;          /* Jump here to start the next IN combination */
156860  int addrSkip;         /* Jump here for next iteration of skip-scan */
156861  int addrCont;         /* Jump here to continue with the next loop cycle */
156862  int addrFirst;        /* First instruction of interior of the loop */
156863  int addrBody;         /* Beginning of the body of this loop */
156864  int regBignull;       /* big-null flag reg. True if a NULL-scan is needed */
156865  int addrBignull;      /* Jump here for next part of big-null scan */
156866#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
156867  u32 iLikeRepCntr;     /* LIKE range processing counter register (times 2) */
156868  int addrLikeRep;      /* LIKE range processing address */
156869#endif
156870  int regFilter;        /* Bloom filter */
156871  WhereRightJoin *pRJ;  /* Extra information for RIGHT JOIN */
156872  u8 iFrom;             /* Which entry in the FROM clause */
156873  u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
156874  int p1, p2;           /* Operands of the opcode used to end the loop */
156875  union {               /* Information that depends on pWLoop->wsFlags */
156876    struct {
156877      int nIn;              /* Number of entries in aInLoop[] */
156878      struct InLoop {
156879        int iCur;              /* The VDBE cursor used by this IN operator */
156880        int addrInTop;         /* Top of the IN loop */
156881        int iBase;             /* Base register of multi-key index record */
156882        int nPrefix;           /* Number of prior entries in the key */
156883        u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
156884      } *aInLoop;           /* Information about each nested IN operator */
156885    } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
156886    Index *pCoveringIdx;  /* Possible covering index for WHERE_MULTI_OR */
156887  } u;
156888  struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
156889  Bitmask notReady;          /* FROM entries not usable at this level */
156890#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
156891  int addrVisit;        /* Address at which row is visited */
156892#endif
156893};
156894
156895/*
156896** Each instance of this object represents an algorithm for evaluating one
156897** term of a join.  Every term of the FROM clause will have at least
156898** one corresponding WhereLoop object (unless INDEXED BY constraints
156899** prevent a query solution - which is an error) and many terms of the
156900** FROM clause will have multiple WhereLoop objects, each describing a
156901** potential way of implementing that FROM-clause term, together with
156902** dependencies and cost estimates for using the chosen algorithm.
156903**
156904** Query planning consists of building up a collection of these WhereLoop
156905** objects, then computing a particular sequence of WhereLoop objects, with
156906** one WhereLoop object per FROM clause term, that satisfy all dependencies
156907** and that minimize the overall cost.
156908*/
156909struct WhereLoop {
156910  Bitmask prereq;       /* Bitmask of other loops that must run first */
156911  Bitmask maskSelf;     /* Bitmask identifying table iTab */
156912#ifdef SQLITE_DEBUG
156913  char cId;             /* Symbolic ID of this loop for debugging use */
156914#endif
156915  u8 iTab;              /* Position in FROM clause of table for this loop */
156916  u8 iSortIdx;          /* Sorting index number.  0==None */
156917  LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
156918  LogEst rRun;          /* Cost of running each loop */
156919  LogEst nOut;          /* Estimated number of output rows */
156920  union {
156921    struct {               /* Information for internal btree tables */
156922      u16 nEq;               /* Number of equality constraints */
156923      u16 nBtm;              /* Size of BTM vector */
156924      u16 nTop;              /* Size of TOP vector */
156925      u16 nDistinctCol;      /* Index columns used to sort for DISTINCT */
156926      Index *pIndex;         /* Index used, or NULL */
156927    } btree;
156928    struct {               /* Information for virtual tables */
156929      int idxNum;            /* Index number */
156930      u32 needFree : 1;      /* True if sqlite3_free(idxStr) is needed */
156931      u32 bOmitOffset : 1;   /* True to let virtual table handle offset */
156932      i8 isOrdered;          /* True if satisfies ORDER BY */
156933      u16 omitMask;          /* Terms that may be omitted */
156934      char *idxStr;          /* Index identifier string */
156935      u32 mHandleIn;         /* Terms to handle as IN(...) instead of == */
156936    } vtab;
156937  } u;
156938  u32 wsFlags;          /* WHERE_* flags describing the plan */
156939  u16 nLTerm;           /* Number of entries in aLTerm[] */
156940  u16 nSkip;            /* Number of NULL aLTerm[] entries */
156941  /**** whereLoopXfer() copies fields above ***********************/
156942# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
156943  u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
156944  WhereTerm **aLTerm;   /* WhereTerms used */
156945  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
156946  WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
156947};
156948
156949/* This object holds the prerequisites and the cost of running a
156950** subquery on one operand of an OR operator in the WHERE clause.
156951** See WhereOrSet for additional information
156952*/
156953struct WhereOrCost {
156954  Bitmask prereq;     /* Prerequisites */
156955  LogEst rRun;        /* Cost of running this subquery */
156956  LogEst nOut;        /* Number of outputs for this subquery */
156957};
156958
156959/* The WhereOrSet object holds a set of possible WhereOrCosts that
156960** correspond to the subquery(s) of OR-clause processing.  Only the
156961** best N_OR_COST elements are retained.
156962*/
156963#define N_OR_COST 3
156964struct WhereOrSet {
156965  u16 n;                      /* Number of valid a[] entries */
156966  WhereOrCost a[N_OR_COST];   /* Set of best costs */
156967};
156968
156969/*
156970** Each instance of this object holds a sequence of WhereLoop objects
156971** that implement some or all of a query plan.
156972**
156973** Think of each WhereLoop object as a node in a graph with arcs
156974** showing dependencies and costs for travelling between nodes.  (That is
156975** not a completely accurate description because WhereLoop costs are a
156976** vector, not a scalar, and because dependencies are many-to-one, not
156977** one-to-one as are graph nodes.  But it is a useful visualization aid.)
156978** Then a WherePath object is a path through the graph that visits some
156979** or all of the WhereLoop objects once.
156980**
156981** The "solver" works by creating the N best WherePath objects of length
156982** 1.  Then using those as a basis to compute the N best WherePath objects
156983** of length 2.  And so forth until the length of WherePaths equals the
156984** number of nodes in the FROM clause.  The best (lowest cost) WherePath
156985** at the end is the chosen query plan.
156986*/
156987struct WherePath {
156988  Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
156989  Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
156990  LogEst nRow;          /* Estimated number of rows generated by this path */
156991  LogEst rCost;         /* Total cost of this path */
156992  LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
156993  i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
156994  WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
156995};
156996
156997/*
156998** The query generator uses an array of instances of this structure to
156999** help it analyze the subexpressions of the WHERE clause.  Each WHERE
157000** clause subexpression is separated from the others by AND operators,
157001** usually, or sometimes subexpressions separated by OR.
157002**
157003** All WhereTerms are collected into a single WhereClause structure.
157004** The following identity holds:
157005**
157006**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
157007**
157008** When a term is of the form:
157009**
157010**              X <op> <expr>
157011**
157012** where X is a column name and <op> is one of certain operators,
157013** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
157014** cursor number and column number for X.  WhereTerm.eOperator records
157015** the <op> using a bitmask encoding defined by WO_xxx below.  The
157016** use of a bitmask encoding for the operator allows us to search
157017** quickly for terms that match any of several different operators.
157018**
157019** A WhereTerm might also be two or more subterms connected by OR:
157020**
157021**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
157022**
157023** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
157024** and the WhereTerm.u.pOrInfo field points to auxiliary information that
157025** is collected about the OR clause.
157026**
157027** If a term in the WHERE clause does not match either of the two previous
157028** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
157029** to the original subexpression content and wtFlags is set up appropriately
157030** but no other fields in the WhereTerm object are meaningful.
157031**
157032** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
157033** but they do so indirectly.  A single WhereMaskSet structure translates
157034** cursor number into bits and the translated bit is stored in the prereq
157035** fields.  The translation is used in order to maximize the number of
157036** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
157037** spread out over the non-negative integers.  For example, the cursor
157038** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
157039** translates these sparse cursor numbers into consecutive integers
157040** beginning with 0 in order to make the best possible use of the available
157041** bits in the Bitmask.  So, in the example above, the cursor numbers
157042** would be mapped into integers 0 through 7.
157043**
157044** The number of terms in a join is limited by the number of bits
157045** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
157046** is only able to process joins with 64 or fewer tables.
157047*/
157048struct WhereTerm {
157049  Expr *pExpr;            /* Pointer to the subexpression that is this term */
157050  WhereClause *pWC;       /* The clause this term is part of */
157051  LogEst truthProb;       /* Probability of truth for this expression */
157052  u16 wtFlags;            /* TERM_xxx bit flags.  See below */
157053  u16 eOperator;          /* A WO_xx value describing <op> */
157054  u8 nChild;              /* Number of children that must disable us */
157055  u8 eMatchOp;            /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
157056  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
157057  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
157058  union {
157059    struct {
157060      int leftColumn;         /* Column number of X in "X <op> <expr>" */
157061      int iField;             /* Field in (?,?,?) IN (SELECT...) vector */
157062    } x;                    /* Opcode other than OP_OR or OP_AND */
157063    WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
157064    WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
157065  } u;
157066  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
157067  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
157068};
157069
157070/*
157071** Allowed values of WhereTerm.wtFlags
157072*/
157073#define TERM_DYNAMIC    0x0001 /* Need to call sqlite3ExprDelete(db, pExpr) */
157074#define TERM_VIRTUAL    0x0002 /* Added by the optimizer.  Do not code */
157075#define TERM_CODED      0x0004 /* This term is already coded */
157076#define TERM_COPIED     0x0008 /* Has a child */
157077#define TERM_ORINFO     0x0010 /* Need to free the WhereTerm.u.pOrInfo object */
157078#define TERM_ANDINFO    0x0020 /* Need to free the WhereTerm.u.pAndInfo obj */
157079#define TERM_OK         0x0040 /* Used during OR-clause processing */
157080#define TERM_VNULL      0x0080 /* Manufactured x>NULL or x<=NULL term */
157081#define TERM_LIKEOPT    0x0100 /* Virtual terms from the LIKE optimization */
157082#define TERM_LIKECOND   0x0200 /* Conditionally this LIKE operator term */
157083#define TERM_LIKE       0x0400 /* The original LIKE operator */
157084#define TERM_IS         0x0800 /* Term.pExpr is an IS operator */
157085#define TERM_VARSELECT  0x1000 /* Term.pExpr contains a correlated sub-query */
157086#define TERM_HEURTRUTH  0x2000 /* Heuristic truthProb used */
157087#ifdef SQLITE_ENABLE_STAT4
157088#  define TERM_HIGHTRUTH  0x4000 /* Term excludes few rows */
157089#else
157090#  define TERM_HIGHTRUTH  0      /* Only used with STAT4 */
157091#endif
157092#define TERM_SLICE      0x8000 /* One slice of a row-value/vector comparison */
157093
157094/*
157095** An instance of the WhereScan object is used as an iterator for locating
157096** terms in the WHERE clause that are useful to the query planner.
157097*/
157098struct WhereScan {
157099  WhereClause *pOrigWC;      /* Original, innermost WhereClause */
157100  WhereClause *pWC;          /* WhereClause currently being scanned */
157101  const char *zCollName;     /* Required collating sequence, if not NULL */
157102  Expr *pIdxExpr;            /* Search for this index expression */
157103  int k;                     /* Resume scanning at this->pWC->a[this->k] */
157104  u32 opMask;                /* Acceptable operators */
157105  char idxaff;               /* Must match this affinity, if zCollName!=NULL */
157106  unsigned char iEquiv;      /* Current slot in aiCur[] and aiColumn[] */
157107  unsigned char nEquiv;      /* Number of entries in aiCur[] and aiColumn[] */
157108  int aiCur[11];             /* Cursors in the equivalence class */
157109  i16 aiColumn[11];          /* Corresponding column number in the eq-class */
157110};
157111
157112/*
157113** An instance of the following structure holds all information about a
157114** WHERE clause.  Mostly this is a container for one or more WhereTerms.
157115**
157116** Explanation of pOuter:  For a WHERE clause of the form
157117**
157118**           a AND ((b AND c) OR (d AND e)) AND f
157119**
157120** There are separate WhereClause objects for the whole clause and for
157121** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
157122** subclauses points to the WhereClause object for the whole clause.
157123*/
157124struct WhereClause {
157125  WhereInfo *pWInfo;       /* WHERE clause processing context */
157126  WhereClause *pOuter;     /* Outer conjunction */
157127  u8 op;                   /* Split operator.  TK_AND or TK_OR */
157128  u8 hasOr;                /* True if any a[].eOperator is WO_OR */
157129  int nTerm;               /* Number of terms */
157130  int nSlot;               /* Number of entries in a[] */
157131  int nBase;               /* Number of terms through the last non-Virtual */
157132  WhereTerm *a;            /* Each a[] describes a term of the WHERE clause */
157133#if defined(SQLITE_SMALL_STACK)
157134  WhereTerm aStatic[1];    /* Initial static space for a[] */
157135#else
157136  WhereTerm aStatic[8];    /* Initial static space for a[] */
157137#endif
157138};
157139
157140/*
157141** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
157142** a dynamically allocated instance of the following structure.
157143*/
157144struct WhereOrInfo {
157145  WhereClause wc;          /* Decomposition into subterms */
157146  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
157147};
157148
157149/*
157150** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
157151** a dynamically allocated instance of the following structure.
157152*/
157153struct WhereAndInfo {
157154  WhereClause wc;          /* The subexpression broken out */
157155};
157156
157157/*
157158** An instance of the following structure keeps track of a mapping
157159** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
157160**
157161** The VDBE cursor numbers are small integers contained in
157162** SrcItem.iCursor and Expr.iTable fields.  For any given WHERE
157163** clause, the cursor numbers might not begin with 0 and they might
157164** contain gaps in the numbering sequence.  But we want to make maximum
157165** use of the bits in our bitmasks.  This structure provides a mapping
157166** from the sparse cursor numbers into consecutive integers beginning
157167** with 0.
157168**
157169** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
157170** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
157171**
157172** For example, if the WHERE clause expression used these VDBE
157173** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
157174** would map those cursor numbers into bits 0 through 5.
157175**
157176** Note that the mapping is not necessarily ordered.  In the example
157177** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
157178** 57->5, 73->4.  Or one of 719 other combinations might be used. It
157179** does not really matter.  What is important is that sparse cursor
157180** numbers all get mapped into bit numbers that begin with 0 and contain
157181** no gaps.
157182*/
157183struct WhereMaskSet {
157184  int bVarSelect;               /* Used by sqlite3WhereExprUsage() */
157185  int n;                        /* Number of assigned cursor values */
157186  int ix[BMS];                  /* Cursor assigned to each bit */
157187};
157188
157189/*
157190** This object is a convenience wrapper holding all information needed
157191** to construct WhereLoop objects for a particular query.
157192*/
157193struct WhereLoopBuilder {
157194  WhereInfo *pWInfo;        /* Information about this WHERE */
157195  WhereClause *pWC;         /* WHERE clause terms */
157196  WhereLoop *pNew;          /* Template WhereLoop */
157197  WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
157198#ifdef SQLITE_ENABLE_STAT4
157199  UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
157200  int nRecValid;            /* Number of valid fields currently in pRec */
157201#endif
157202  unsigned char bldFlags1;  /* First set of SQLITE_BLDF_* flags */
157203  unsigned char bldFlags2;  /* Second set of SQLITE_BLDF_* flags */
157204  unsigned int iPlanLimit;  /* Search limiter */
157205};
157206
157207/* Allowed values for WhereLoopBuider.bldFlags */
157208#define SQLITE_BLDF1_INDEXED  0x0001   /* An index is used */
157209#define SQLITE_BLDF1_UNIQUE   0x0002   /* All keys of a UNIQUE index used */
157210
157211#define SQLITE_BLDF2_2NDPASS  0x0004   /* Second builder pass needed */
157212
157213/* The WhereLoopBuilder.iPlanLimit is used to limit the number of
157214** index+constraint combinations the query planner will consider for a
157215** particular query.  If this parameter is unlimited, then certain
157216** pathological queries can spend excess time in the sqlite3WhereBegin()
157217** routine.  The limit is high enough that is should not impact real-world
157218** queries.
157219**
157220** SQLITE_QUERY_PLANNER_LIMIT is the baseline limit.  The limit is
157221** increased by SQLITE_QUERY_PLANNER_LIMIT_INCR before each term of the FROM
157222** clause is processed, so that every table in a join is guaranteed to be
157223** able to propose a some index+constraint combinations even if the initial
157224** baseline limit was exhausted by prior tables of the join.
157225*/
157226#ifndef SQLITE_QUERY_PLANNER_LIMIT
157227# define SQLITE_QUERY_PLANNER_LIMIT 20000
157228#endif
157229#ifndef SQLITE_QUERY_PLANNER_LIMIT_INCR
157230# define SQLITE_QUERY_PLANNER_LIMIT_INCR 1000
157231#endif
157232
157233/*
157234** The WHERE clause processing routine has two halves.  The
157235** first part does the start of the WHERE loop and the second
157236** half does the tail of the WHERE loop.  An instance of
157237** this structure is returned by the first half and passed
157238** into the second half to give some continuity.
157239**
157240** An instance of this object holds the complete state of the query
157241** planner.
157242*/
157243struct WhereInfo {
157244  Parse *pParse;            /* Parsing and code generating context */
157245  SrcList *pTabList;        /* List of tables in the join */
157246  ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
157247  ExprList *pResultSet;     /* Result set of the query */
157248#if WHERETRACE_ENABLED
157249  Expr *pWhere;             /* The complete WHERE clause */
157250#endif
157251  Select *pSelect;          /* The entire SELECT statement containing WHERE */
157252  int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
157253  int iContinue;            /* Jump here to continue with next record */
157254  int iBreak;               /* Jump here to break out of the loop */
157255  int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
157256  u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
157257  LogEst iLimit;            /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
157258  u8 nLevel;                /* Number of nested loop */
157259  i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
157260  u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
157261  u8 eDistinct;             /* One of the WHERE_DISTINCT_* values */
157262  unsigned bDeferredSeek :1;   /* Uses OP_DeferredSeek */
157263  unsigned untestedTerms :1;   /* Not all WHERE terms resolved by outer loop */
157264  unsigned bOrderedInnerLoop:1;/* True if only the inner-most loop is ordered */
157265  unsigned sorted :1;          /* True if really sorted (not just grouped) */
157266  LogEst nRowOut;           /* Estimated number of output rows */
157267  int iTop;                 /* The very beginning of the WHERE loop */
157268  int iEndWhere;            /* End of the WHERE clause itself */
157269  WhereLoop *pLoops;        /* List of all WhereLoop objects */
157270  WhereMemBlock *pMemToFree;/* Memory to free when this object destroyed */
157271  Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
157272  WhereClause sWC;          /* Decomposition of the WHERE clause */
157273  WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
157274  WhereLevel a[1];          /* Information about each nest loop in WHERE */
157275};
157276
157277/*
157278** Private interfaces - callable only by other where.c routines.
157279**
157280** where.c:
157281*/
157282SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
157283#ifdef WHERETRACE_ENABLED
157284SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
157285SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm);
157286SQLITE_PRIVATE void sqlite3WhereLoopPrint(const WhereLoop *p, const WhereClause *pWC);
157287#endif
157288SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
157289  WhereClause *pWC,     /* The WHERE clause to be searched */
157290  int iCur,             /* Cursor number of LHS */
157291  int iColumn,          /* Column number of LHS */
157292  Bitmask notReady,     /* RHS must not overlap with this mask */
157293  u32 op,               /* Mask of WO_xx values describing operator */
157294  Index *pIdx           /* Must be compatible with this index, if not NULL */
157295);
157296SQLITE_PRIVATE void *sqlite3WhereMalloc(WhereInfo *pWInfo, u64 nByte);
157297SQLITE_PRIVATE void *sqlite3WhereRealloc(WhereInfo *pWInfo, void *pOld, u64 nByte);
157298
157299/* wherecode.c: */
157300#ifndef SQLITE_OMIT_EXPLAIN
157301SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
157302  Parse *pParse,                  /* Parse context */
157303  SrcList *pTabList,              /* Table list this loop refers to */
157304  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
157305  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
157306);
157307SQLITE_PRIVATE int sqlite3WhereExplainBloomFilter(
157308  const Parse *pParse,            /* Parse context */
157309  const WhereInfo *pWInfo,        /* WHERE clause */
157310  const WhereLevel *pLevel        /* Bloom filter on this level */
157311);
157312#else
157313# define sqlite3WhereExplainOneScan(u,v,w,x) 0
157314# define sqlite3WhereExplainBloomFilter(u,v,w) 0
157315#endif /* SQLITE_OMIT_EXPLAIN */
157316#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
157317SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
157318  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
157319  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
157320  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
157321  int addrExplain                 /* Address of OP_Explain (or 0) */
157322);
157323#else
157324# define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
157325#endif
157326SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
157327  Parse *pParse,       /* Parsing context */
157328  Vdbe *v,             /* Prepared statement under construction */
157329  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
157330  int iLevel,          /* Which level of pWInfo->a[] should be coded */
157331  WhereLevel *pLevel,  /* The current level pointer */
157332  Bitmask notReady     /* Which tables are currently available */
157333);
157334SQLITE_PRIVATE SQLITE_NOINLINE void sqlite3WhereRightJoinLoop(
157335  WhereInfo *pWInfo,
157336  int iLevel,
157337  WhereLevel *pLevel
157338);
157339
157340/* whereexpr.c: */
157341SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
157342SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
157343SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
157344SQLITE_PRIVATE void sqlite3WhereAddLimit(WhereClause*, Select*);
157345SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
157346SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*);
157347SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
157348SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
157349SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, SrcItem*, WhereClause*);
157350
157351
157352
157353
157354
157355/*
157356** Bitmasks for the operators on WhereTerm objects.  These are all
157357** operators that are of interest to the query planner.  An
157358** OR-ed combination of these values can be used when searching for
157359** particular WhereTerms within a WhereClause.
157360**
157361** Value constraints:
157362**     WO_EQ    == SQLITE_INDEX_CONSTRAINT_EQ
157363**     WO_LT    == SQLITE_INDEX_CONSTRAINT_LT
157364**     WO_LE    == SQLITE_INDEX_CONSTRAINT_LE
157365**     WO_GT    == SQLITE_INDEX_CONSTRAINT_GT
157366**     WO_GE    == SQLITE_INDEX_CONSTRAINT_GE
157367*/
157368#define WO_IN     0x0001
157369#define WO_EQ     0x0002
157370#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
157371#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
157372#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
157373#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
157374#define WO_AUX    0x0040       /* Op useful to virtual tables only */
157375#define WO_IS     0x0080
157376#define WO_ISNULL 0x0100
157377#define WO_OR     0x0200       /* Two or more OR-connected terms */
157378#define WO_AND    0x0400       /* Two or more AND-connected terms */
157379#define WO_EQUIV  0x0800       /* Of the form A==B, both columns */
157380#define WO_NOOP   0x1000       /* This term does not restrict search space */
157381#define WO_ROWVAL 0x2000       /* A row-value term */
157382
157383#define WO_ALL    0x3fff       /* Mask of all possible WO_* values */
157384#define WO_SINGLE 0x01ff       /* Mask of all non-compound WO_* values */
157385
157386/*
157387** These are definitions of bits in the WhereLoop.wsFlags field.
157388** The particular combination of bits in each WhereLoop help to
157389** determine the algorithm that WhereLoop represents.
157390*/
157391#define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
157392#define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
157393#define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
157394#define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
157395#define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
157396#define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
157397#define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
157398#define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
157399#define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
157400#define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
157401#define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
157402#define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
157403#define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
157404#define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
157405#define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
157406#define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
157407#define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
157408#define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
157409#define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
157410#define WHERE_IN_EARLYOUT  0x00040000  /* Perhaps quit IN loops early */
157411#define WHERE_BIGNULL_SORT 0x00080000  /* Column nEq of index is BIGNULL */
157412#define WHERE_IN_SEEKSCAN  0x00100000  /* Seek-scan optimization for IN */
157413#define WHERE_TRANSCONS    0x00200000  /* Uses a transitive constraint */
157414#define WHERE_BLOOMFILTER  0x00400000  /* Consider using a Bloom-filter */
157415#define WHERE_SELFCULL     0x00800000  /* nOut reduced by extra WHERE terms */
157416#define WHERE_OMIT_OFFSET  0x01000000  /* Set offset counter to zero */
157417                      /*   0x02000000  -- available for reuse */
157418#define WHERE_EXPRIDX      0x04000000  /* Uses an index-on-expressions */
157419
157420#endif /* !defined(SQLITE_WHEREINT_H) */
157421
157422/************** End of whereInt.h ********************************************/
157423/************** Continuing where we left off in wherecode.c ******************/
157424
157425#ifndef SQLITE_OMIT_EXPLAIN
157426
157427/*
157428** Return the name of the i-th column of the pIdx index.
157429*/
157430static const char *explainIndexColumnName(Index *pIdx, int i){
157431  i = pIdx->aiColumn[i];
157432  if( i==XN_EXPR ) return "<expr>";
157433  if( i==XN_ROWID ) return "rowid";
157434  return pIdx->pTable->aCol[i].zCnName;
157435}
157436
157437/*
157438** This routine is a helper for explainIndexRange() below
157439**
157440** pStr holds the text of an expression that we are building up one term
157441** at a time.  This routine adds a new term to the end of the expression.
157442** Terms are separated by AND so add the "AND" text for second and subsequent
157443** terms only.
157444*/
157445static void explainAppendTerm(
157446  StrAccum *pStr,             /* The text expression being built */
157447  Index *pIdx,                /* Index to read column names from */
157448  int nTerm,                  /* Number of terms */
157449  int iTerm,                  /* Zero-based index of first term. */
157450  int bAnd,                   /* Non-zero to append " AND " */
157451  const char *zOp             /* Name of the operator */
157452){
157453  int i;
157454
157455  assert( nTerm>=1 );
157456  if( bAnd ) sqlite3_str_append(pStr, " AND ", 5);
157457
157458  if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
157459  for(i=0; i<nTerm; i++){
157460    if( i ) sqlite3_str_append(pStr, ",", 1);
157461    sqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i));
157462  }
157463  if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
157464
157465  sqlite3_str_append(pStr, zOp, 1);
157466
157467  if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
157468  for(i=0; i<nTerm; i++){
157469    if( i ) sqlite3_str_append(pStr, ",", 1);
157470    sqlite3_str_append(pStr, "?", 1);
157471  }
157472  if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
157473}
157474
157475/*
157476** Argument pLevel describes a strategy for scanning table pTab. This
157477** function appends text to pStr that describes the subset of table
157478** rows scanned by the strategy in the form of an SQL expression.
157479**
157480** For example, if the query:
157481**
157482**   SELECT * FROM t1 WHERE a=1 AND b>2;
157483**
157484** is run and there is an index on (a, b), then this function returns a
157485** string similar to:
157486**
157487**   "a=? AND b>?"
157488*/
157489static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
157490  Index *pIndex = pLoop->u.btree.pIndex;
157491  u16 nEq = pLoop->u.btree.nEq;
157492  u16 nSkip = pLoop->nSkip;
157493  int i, j;
157494
157495  if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
157496  sqlite3_str_append(pStr, " (", 2);
157497  for(i=0; i<nEq; i++){
157498    const char *z = explainIndexColumnName(pIndex, i);
157499    if( i ) sqlite3_str_append(pStr, " AND ", 5);
157500    sqlite3_str_appendf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
157501  }
157502
157503  j = i;
157504  if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
157505    explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
157506    i = 1;
157507  }
157508  if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
157509    explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
157510  }
157511  sqlite3_str_append(pStr, ")", 1);
157512}
157513
157514/*
157515** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
157516** command, or if stmt_scanstatus_v2() stats are enabled, or if SQLITE_DEBUG
157517** was defined at compile-time. If it is not a no-op, a single OP_Explain
157518** opcode is added to the output to describe the table scan strategy in pLevel.
157519**
157520** If an OP_Explain opcode is added to the VM, its address is returned.
157521** Otherwise, if no OP_Explain is coded, zero is returned.
157522*/
157523SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
157524  Parse *pParse,                  /* Parse context */
157525  SrcList *pTabList,              /* Table list this loop refers to */
157526  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
157527  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
157528){
157529  int ret = 0;
157530#if !defined(SQLITE_DEBUG)
157531  if( sqlite3ParseToplevel(pParse)->explain==2 || IS_STMT_SCANSTATUS(pParse->db) )
157532#endif
157533  {
157534    SrcItem *pItem = &pTabList->a[pLevel->iFrom];
157535    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
157536    sqlite3 *db = pParse->db;     /* Database handle */
157537    int isSearch;                 /* True for a SEARCH. False for SCAN. */
157538    WhereLoop *pLoop;             /* The controlling WhereLoop object */
157539    u32 flags;                    /* Flags that describe this loop */
157540    char *zMsg;                   /* Text to add to EQP output */
157541    StrAccum str;                 /* EQP output string */
157542    char zBuf[100];               /* Initial space for EQP output string */
157543
157544    pLoop = pLevel->pWLoop;
157545    flags = pLoop->wsFlags;
157546    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
157547
157548    isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
157549            || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
157550            || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
157551
157552    sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
157553    str.printfFlags = SQLITE_PRINTF_INTERNAL;
157554    sqlite3_str_appendf(&str, "%s %S", isSearch ? "SEARCH" : "SCAN", pItem);
157555    if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
157556      const char *zFmt = 0;
157557      Index *pIdx;
157558
157559      assert( pLoop->u.btree.pIndex!=0 );
157560      pIdx = pLoop->u.btree.pIndex;
157561      assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
157562      if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
157563        if( isSearch ){
157564          zFmt = "PRIMARY KEY";
157565        }
157566      }else if( flags & WHERE_PARTIALIDX ){
157567        zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
157568      }else if( flags & WHERE_AUTO_INDEX ){
157569        zFmt = "AUTOMATIC COVERING INDEX";
157570      }else if( flags & WHERE_IDX_ONLY ){
157571        zFmt = "COVERING INDEX %s";
157572      }else{
157573        zFmt = "INDEX %s";
157574      }
157575      if( zFmt ){
157576        sqlite3_str_append(&str, " USING ", 7);
157577        sqlite3_str_appendf(&str, zFmt, pIdx->zName);
157578        explainIndexRange(&str, pLoop);
157579      }
157580    }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
157581      char cRangeOp;
157582#if 0  /* Better output, but breaks many tests */
157583      const Table *pTab = pItem->pTab;
157584      const char *zRowid = pTab->iPKey>=0 ? pTab->aCol[pTab->iPKey].zCnName:
157585                              "rowid";
157586#else
157587      const char *zRowid = "rowid";
157588#endif
157589      sqlite3_str_appendf(&str, " USING INTEGER PRIMARY KEY (%s", zRowid);
157590      if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
157591        cRangeOp = '=';
157592      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
157593        sqlite3_str_appendf(&str, ">? AND %s", zRowid);
157594        cRangeOp = '<';
157595      }else if( flags&WHERE_BTM_LIMIT ){
157596        cRangeOp = '>';
157597      }else{
157598        assert( flags&WHERE_TOP_LIMIT);
157599        cRangeOp = '<';
157600      }
157601      sqlite3_str_appendf(&str, "%c?)", cRangeOp);
157602    }
157603#ifndef SQLITE_OMIT_VIRTUALTABLE
157604    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
157605      sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s",
157606                  pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
157607    }
157608#endif
157609    if( pItem->fg.jointype & JT_LEFT ){
157610      sqlite3_str_appendf(&str, " LEFT-JOIN");
157611    }
157612#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
157613    if( pLoop->nOut>=10 ){
157614      sqlite3_str_appendf(&str, " (~%llu rows)",
157615             sqlite3LogEstToInt(pLoop->nOut));
157616    }else{
157617      sqlite3_str_append(&str, " (~1 row)", 9);
157618    }
157619#endif
157620    zMsg = sqlite3StrAccumFinish(&str);
157621    sqlite3ExplainBreakpoint("",zMsg);
157622    ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
157623                            pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
157624  }
157625  return ret;
157626}
157627
157628/*
157629** Add a single OP_Explain opcode that describes a Bloom filter.
157630**
157631** Or if not processing EXPLAIN QUERY PLAN and not in a SQLITE_DEBUG and/or
157632** SQLITE_ENABLE_STMT_SCANSTATUS build, then OP_Explain opcodes are not
157633** required and this routine is a no-op.
157634**
157635** If an OP_Explain opcode is added to the VM, its address is returned.
157636** Otherwise, if no OP_Explain is coded, zero is returned.
157637*/
157638SQLITE_PRIVATE int sqlite3WhereExplainBloomFilter(
157639  const Parse *pParse,               /* Parse context */
157640  const WhereInfo *pWInfo,           /* WHERE clause */
157641  const WhereLevel *pLevel           /* Bloom filter on this level */
157642){
157643  int ret = 0;
157644  SrcItem *pItem = &pWInfo->pTabList->a[pLevel->iFrom];
157645  Vdbe *v = pParse->pVdbe;      /* VM being constructed */
157646  sqlite3 *db = pParse->db;     /* Database handle */
157647  char *zMsg;                   /* Text to add to EQP output */
157648  int i;                        /* Loop counter */
157649  WhereLoop *pLoop;             /* The where loop */
157650  StrAccum str;                 /* EQP output string */
157651  char zBuf[100];               /* Initial space for EQP output string */
157652
157653  sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
157654  str.printfFlags = SQLITE_PRINTF_INTERNAL;
157655  sqlite3_str_appendf(&str, "BLOOM FILTER ON %S (", pItem);
157656  pLoop = pLevel->pWLoop;
157657  if( pLoop->wsFlags & WHERE_IPK ){
157658    const Table *pTab = pItem->pTab;
157659    if( pTab->iPKey>=0 ){
157660      sqlite3_str_appendf(&str, "%s=?", pTab->aCol[pTab->iPKey].zCnName);
157661    }else{
157662      sqlite3_str_appendf(&str, "rowid=?");
157663    }
157664  }else{
157665    for(i=pLoop->nSkip; i<pLoop->u.btree.nEq; i++){
157666      const char *z = explainIndexColumnName(pLoop->u.btree.pIndex, i);
157667      if( i>pLoop->nSkip ) sqlite3_str_append(&str, " AND ", 5);
157668      sqlite3_str_appendf(&str, "%s=?", z);
157669    }
157670  }
157671  sqlite3_str_append(&str, ")", 1);
157672  zMsg = sqlite3StrAccumFinish(&str);
157673  ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
157674                          pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
157675
157676  sqlite3VdbeScanStatus(v, sqlite3VdbeCurrentAddr(v)-1, 0, 0, 0, 0);
157677  return ret;
157678}
157679#endif /* SQLITE_OMIT_EXPLAIN */
157680
157681#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
157682/*
157683** Configure the VM passed as the first argument with an
157684** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
157685** implement level pLvl. Argument pSrclist is a pointer to the FROM
157686** clause that the scan reads data from.
157687**
157688** If argument addrExplain is not 0, it must be the address of an
157689** OP_Explain instruction that describes the same loop.
157690*/
157691SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
157692  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
157693  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
157694  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
157695  int addrExplain                 /* Address of OP_Explain (or 0) */
157696){
157697  if( IS_STMT_SCANSTATUS( sqlite3VdbeDb(v) ) ){
157698    const char *zObj = 0;
157699    WhereLoop *pLoop = pLvl->pWLoop;
157700    int wsFlags = pLoop->wsFlags;
157701    int viaCoroutine = 0;
157702
157703    if( (wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
157704      zObj = pLoop->u.btree.pIndex->zName;
157705    }else{
157706      zObj = pSrclist->a[pLvl->iFrom].zName;
157707      viaCoroutine = pSrclist->a[pLvl->iFrom].fg.viaCoroutine;
157708    }
157709    sqlite3VdbeScanStatus(
157710        v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
157711    );
157712
157713    if( viaCoroutine==0 ){
157714      if( (wsFlags & (WHERE_MULTI_OR|WHERE_AUTO_INDEX))==0 ){
157715        sqlite3VdbeScanStatusRange(v, addrExplain, -1, pLvl->iTabCur);
157716      }
157717      if( wsFlags & WHERE_INDEXED ){
157718        sqlite3VdbeScanStatusRange(v, addrExplain, -1, pLvl->iIdxCur);
157719      }
157720    }else{
157721      int addr = pSrclist->a[pLvl->iFrom].addrFillSub;
157722      VdbeOp *pOp = sqlite3VdbeGetOp(v, addr-1);
157723      assert( sqlite3VdbeDb(v)->mallocFailed || pOp->opcode==OP_InitCoroutine );
157724      assert( sqlite3VdbeDb(v)->mallocFailed || pOp->p2>addr );
157725      sqlite3VdbeScanStatusRange(v, addrExplain, addr, pOp->p2-1);
157726    }
157727  }
157728}
157729#endif
157730
157731
157732/*
157733** Disable a term in the WHERE clause.  Except, do not disable the term
157734** if it controls a LEFT OUTER JOIN and it did not originate in the ON
157735** or USING clause of that join.
157736**
157737** Consider the term t2.z='ok' in the following queries:
157738**
157739**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
157740**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
157741**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
157742**
157743** The t2.z='ok' is disabled in the in (2) because it originates
157744** in the ON clause.  The term is disabled in (3) because it is not part
157745** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
157746**
157747** Disabling a term causes that term to not be tested in the inner loop
157748** of the join.  Disabling is an optimization.  When terms are satisfied
157749** by indices, we disable them to prevent redundant tests in the inner
157750** loop.  We would get the correct results if nothing were ever disabled,
157751** but joins might run a little slower.  The trick is to disable as much
157752** as we can without disabling too much.  If we disabled in (1), we'd get
157753** the wrong answer.  See ticket #813.
157754**
157755** If all the children of a term are disabled, then that term is also
157756** automatically disabled.  In this way, terms get disabled if derived
157757** virtual terms are tested first.  For example:
157758**
157759**      x GLOB 'abc*' AND x>='abc' AND x<'acd'
157760**      \___________/     \______/     \_____/
157761**         parent          child1       child2
157762**
157763** Only the parent term was in the original WHERE clause.  The child1
157764** and child2 terms were added by the LIKE optimization.  If both of
157765** the virtual child terms are valid, then testing of the parent can be
157766** skipped.
157767**
157768** Usually the parent term is marked as TERM_CODED.  But if the parent
157769** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
157770** The TERM_LIKECOND marking indicates that the term should be coded inside
157771** a conditional such that is only evaluated on the second pass of a
157772** LIKE-optimization loop, when scanning BLOBs instead of strings.
157773*/
157774static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
157775  int nLoop = 0;
157776  assert( pTerm!=0 );
157777  while( (pTerm->wtFlags & TERM_CODED)==0
157778      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_OuterON))
157779      && (pLevel->notReady & pTerm->prereqAll)==0
157780  ){
157781    if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
157782      pTerm->wtFlags |= TERM_LIKECOND;
157783    }else{
157784      pTerm->wtFlags |= TERM_CODED;
157785    }
157786#ifdef WHERETRACE_ENABLED
157787    if( (sqlite3WhereTrace & 0x4001)==0x4001 ){
157788      sqlite3DebugPrintf("DISABLE-");
157789      sqlite3WhereTermPrint(pTerm, (int)(pTerm - (pTerm->pWC->a)));
157790    }
157791#endif
157792    if( pTerm->iParent<0 ) break;
157793    pTerm = &pTerm->pWC->a[pTerm->iParent];
157794    assert( pTerm!=0 );
157795    pTerm->nChild--;
157796    if( pTerm->nChild!=0 ) break;
157797    nLoop++;
157798  }
157799}
157800
157801/*
157802** Code an OP_Affinity opcode to apply the column affinity string zAff
157803** to the n registers starting at base.
157804**
157805** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which
157806** are no-ops) at the beginning and end of zAff are ignored.  If all entries
157807** in zAff are SQLITE_AFF_BLOB or SQLITE_AFF_NONE, then no code gets generated.
157808**
157809** This routine makes its own copy of zAff so that the caller is free
157810** to modify zAff after this routine returns.
157811*/
157812static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
157813  Vdbe *v = pParse->pVdbe;
157814  if( zAff==0 ){
157815    assert( pParse->db->mallocFailed );
157816    return;
157817  }
157818  assert( v!=0 );
157819
157820  /* Adjust base and n to skip over SQLITE_AFF_BLOB and SQLITE_AFF_NONE
157821  ** entries at the beginning and end of the affinity string.
157822  */
157823  assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB );
157824  while( n>0 && zAff[0]<=SQLITE_AFF_BLOB ){
157825    n--;
157826    base++;
157827    zAff++;
157828  }
157829  while( n>1 && zAff[n-1]<=SQLITE_AFF_BLOB ){
157830    n--;
157831  }
157832
157833  /* Code the OP_Affinity opcode if there is anything left to do. */
157834  if( n>0 ){
157835    sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
157836  }
157837}
157838
157839/*
157840** Expression pRight, which is the RHS of a comparison operation, is
157841** either a vector of n elements or, if n==1, a scalar expression.
157842** Before the comparison operation, affinity zAff is to be applied
157843** to the pRight values. This function modifies characters within the
157844** affinity string to SQLITE_AFF_BLOB if either:
157845**
157846**   * the comparison will be performed with no affinity, or
157847**   * the affinity change in zAff is guaranteed not to change the value.
157848*/
157849static void updateRangeAffinityStr(
157850  Expr *pRight,                   /* RHS of comparison */
157851  int n,                          /* Number of vector elements in comparison */
157852  char *zAff                      /* Affinity string to modify */
157853){
157854  int i;
157855  for(i=0; i<n; i++){
157856    Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
157857    if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
157858     || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
157859    ){
157860      zAff[i] = SQLITE_AFF_BLOB;
157861    }
157862  }
157863}
157864
157865
157866/*
157867** pX is an expression of the form:  (vector) IN (SELECT ...)
157868** In other words, it is a vector IN operator with a SELECT clause on the
157869** LHS.  But not all terms in the vector are indexable and the terms might
157870** not be in the correct order for indexing.
157871**
157872** This routine makes a copy of the input pX expression and then adjusts
157873** the vector on the LHS with corresponding changes to the SELECT so that
157874** the vector contains only index terms and those terms are in the correct
157875** order.  The modified IN expression is returned.  The caller is responsible
157876** for deleting the returned expression.
157877**
157878** Example:
157879**
157880**    CREATE TABLE t1(a,b,c,d,e,f);
157881**    CREATE INDEX t1x1 ON t1(e,c);
157882**    SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
157883**                           \_______________________________________/
157884**                                     The pX expression
157885**
157886** Since only columns e and c can be used with the index, in that order,
157887** the modified IN expression that is returned will be:
157888**
157889**        (e,c) IN (SELECT z,x FROM t2)
157890**
157891** The reduced pX is different from the original (obviously) and thus is
157892** only used for indexing, to improve performance.  The original unaltered
157893** IN expression must also be run on each output row for correctness.
157894*/
157895static Expr *removeUnindexableInClauseTerms(
157896  Parse *pParse,        /* The parsing context */
157897  int iEq,              /* Look at loop terms starting here */
157898  WhereLoop *pLoop,     /* The current loop */
157899  Expr *pX              /* The IN expression to be reduced */
157900){
157901  sqlite3 *db = pParse->db;
157902  Select *pSelect;            /* Pointer to the SELECT on the RHS */
157903  Expr *pNew;
157904  pNew = sqlite3ExprDup(db, pX, 0);
157905  if( db->mallocFailed==0 ){
157906    for(pSelect=pNew->x.pSelect; pSelect; pSelect=pSelect->pPrior){
157907      ExprList *pOrigRhs;         /* Original unmodified RHS */
157908      ExprList *pOrigLhs = 0;     /* Original unmodified LHS */
157909      ExprList *pRhs = 0;         /* New RHS after modifications */
157910      ExprList *pLhs = 0;         /* New LHS after mods */
157911      int i;                      /* Loop counter */
157912
157913      assert( ExprUseXSelect(pNew) );
157914      pOrigRhs = pSelect->pEList;
157915      assert( pNew->pLeft!=0 );
157916      assert( ExprUseXList(pNew->pLeft) );
157917      if( pSelect==pNew->x.pSelect ){
157918        pOrigLhs = pNew->pLeft->x.pList;
157919      }
157920      for(i=iEq; i<pLoop->nLTerm; i++){
157921        if( pLoop->aLTerm[i]->pExpr==pX ){
157922          int iField;
157923          assert( (pLoop->aLTerm[i]->eOperator & (WO_OR|WO_AND))==0 );
157924          iField = pLoop->aLTerm[i]->u.x.iField - 1;
157925          if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
157926          pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
157927          pOrigRhs->a[iField].pExpr = 0;
157928          if( pOrigLhs ){
157929            assert( pOrigLhs->a[iField].pExpr!=0 );
157930            pLhs = sqlite3ExprListAppend(pParse,pLhs,pOrigLhs->a[iField].pExpr);
157931            pOrigLhs->a[iField].pExpr = 0;
157932          }
157933        }
157934      }
157935      sqlite3ExprListDelete(db, pOrigRhs);
157936      if( pOrigLhs ){
157937        sqlite3ExprListDelete(db, pOrigLhs);
157938        pNew->pLeft->x.pList = pLhs;
157939      }
157940      pSelect->pEList = pRhs;
157941      if( pLhs && pLhs->nExpr==1 ){
157942        /* Take care here not to generate a TK_VECTOR containing only a
157943        ** single value. Since the parser never creates such a vector, some
157944        ** of the subroutines do not handle this case.  */
157945        Expr *p = pLhs->a[0].pExpr;
157946        pLhs->a[0].pExpr = 0;
157947        sqlite3ExprDelete(db, pNew->pLeft);
157948        pNew->pLeft = p;
157949      }
157950      if( pSelect->pOrderBy ){
157951        /* If the SELECT statement has an ORDER BY clause, zero the
157952        ** iOrderByCol variables. These are set to non-zero when an
157953        ** ORDER BY term exactly matches one of the terms of the
157954        ** result-set. Since the result-set of the SELECT statement may
157955        ** have been modified or reordered, these variables are no longer
157956        ** set correctly.  Since setting them is just an optimization,
157957        ** it's easiest just to zero them here.  */
157958        ExprList *pOrderBy = pSelect->pOrderBy;
157959        for(i=0; i<pOrderBy->nExpr; i++){
157960          pOrderBy->a[i].u.x.iOrderByCol = 0;
157961        }
157962      }
157963
157964#if 0
157965      printf("For indexing, change the IN expr:\n");
157966      sqlite3TreeViewExpr(0, pX, 0);
157967      printf("Into:\n");
157968      sqlite3TreeViewExpr(0, pNew, 0);
157969#endif
157970    }
157971  }
157972  return pNew;
157973}
157974
157975
157976/*
157977** Generate code for a single equality term of the WHERE clause.  An equality
157978** term can be either X=expr or X IN (...).   pTerm is the term to be
157979** coded.
157980**
157981** The current value for the constraint is left in a register, the index
157982** of which is returned.  An attempt is made store the result in iTarget but
157983** this is only guaranteed for TK_ISNULL and TK_IN constraints.  If the
157984** constraint is a TK_EQ or TK_IS, then the current value might be left in
157985** some other register and it is the caller's responsibility to compensate.
157986**
157987** For a constraint of the form X=expr, the expression is evaluated in
157988** straight-line code.  For constraints of the form X IN (...)
157989** this routine sets up a loop that will iterate over all values of X.
157990*/
157991static int codeEqualityTerm(
157992  Parse *pParse,      /* The parsing context */
157993  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
157994  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
157995  int iEq,            /* Index of the equality term within this level */
157996  int bRev,           /* True for reverse-order IN operations */
157997  int iTarget         /* Attempt to leave results in this register */
157998){
157999  Expr *pX = pTerm->pExpr;
158000  Vdbe *v = pParse->pVdbe;
158001  int iReg;                  /* Register holding results */
158002
158003  assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
158004  assert( iTarget>0 );
158005  if( pX->op==TK_EQ || pX->op==TK_IS ){
158006    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
158007  }else if( pX->op==TK_ISNULL ){
158008    iReg = iTarget;
158009    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
158010#ifndef SQLITE_OMIT_SUBQUERY
158011  }else{
158012    int eType = IN_INDEX_NOOP;
158013    int iTab;
158014    struct InLoop *pIn;
158015    WhereLoop *pLoop = pLevel->pWLoop;
158016    int i;
158017    int nEq = 0;
158018    int *aiMap = 0;
158019
158020    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
158021      && pLoop->u.btree.pIndex!=0
158022      && pLoop->u.btree.pIndex->aSortOrder[iEq]
158023    ){
158024      testcase( iEq==0 );
158025      testcase( bRev );
158026      bRev = !bRev;
158027    }
158028    assert( pX->op==TK_IN );
158029    iReg = iTarget;
158030
158031    for(i=0; i<iEq; i++){
158032      if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
158033        disableTerm(pLevel, pTerm);
158034        return iTarget;
158035      }
158036    }
158037    for(i=iEq;i<pLoop->nLTerm; i++){
158038      assert( pLoop->aLTerm[i]!=0 );
158039      if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
158040    }
158041
158042    iTab = 0;
158043    if( !ExprUseXSelect(pX) || pX->x.pSelect->pEList->nExpr==1 ){
158044      eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab);
158045    }else{
158046      Expr *pExpr = pTerm->pExpr;
158047      if( pExpr->iTable==0 || !ExprHasProperty(pExpr, EP_Subrtn) ){
158048        sqlite3 *db = pParse->db;
158049        pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
158050        if( !db->mallocFailed ){
158051          aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
158052          eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap,&iTab);
158053          pExpr->iTable = iTab;
158054        }
158055        sqlite3ExprDelete(db, pX);
158056      }else{
158057        int n = sqlite3ExprVectorSize(pX->pLeft);
158058        aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*MAX(nEq,n));
158059        eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab);
158060      }
158061      pX = pExpr;
158062    }
158063
158064    if( eType==IN_INDEX_INDEX_DESC ){
158065      testcase( bRev );
158066      bRev = !bRev;
158067    }
158068    sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
158069    VdbeCoverageIf(v, bRev);
158070    VdbeCoverageIf(v, !bRev);
158071
158072    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
158073    pLoop->wsFlags |= WHERE_IN_ABLE;
158074    if( pLevel->u.in.nIn==0 ){
158075      pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
158076    }
158077    if( iEq>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 ){
158078      pLoop->wsFlags |= WHERE_IN_EARLYOUT;
158079    }
158080
158081    i = pLevel->u.in.nIn;
158082    pLevel->u.in.nIn += nEq;
158083    pLevel->u.in.aInLoop =
158084       sqlite3WhereRealloc(pTerm->pWC->pWInfo,
158085                           pLevel->u.in.aInLoop,
158086                           sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
158087    pIn = pLevel->u.in.aInLoop;
158088    if( pIn ){
158089      int iMap = 0;               /* Index in aiMap[] */
158090      pIn += i;
158091      for(i=iEq;i<pLoop->nLTerm; i++){
158092        if( pLoop->aLTerm[i]->pExpr==pX ){
158093          int iOut = iReg + i - iEq;
158094          if( eType==IN_INDEX_ROWID ){
158095            pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
158096          }else{
158097            int iCol = aiMap ? aiMap[iMap++] : 0;
158098            pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
158099          }
158100          sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
158101          if( i==iEq ){
158102            pIn->iCur = iTab;
158103            pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
158104            if( iEq>0 ){
158105              pIn->iBase = iReg - i;
158106              pIn->nPrefix = i;
158107            }else{
158108              pIn->nPrefix = 0;
158109            }
158110          }else{
158111            pIn->eEndLoopOp = OP_Noop;
158112          }
158113          pIn++;
158114        }
158115      }
158116      testcase( iEq>0
158117                && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
158118                && (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 );
158119      if( iEq>0
158120       && (pLoop->wsFlags & (WHERE_IN_SEEKSCAN|WHERE_VIRTUALTABLE))==0
158121      ){
158122        sqlite3VdbeAddOp3(v, OP_SeekHit, pLevel->iIdxCur, 0, iEq);
158123      }
158124    }else{
158125      pLevel->u.in.nIn = 0;
158126    }
158127    sqlite3DbFree(pParse->db, aiMap);
158128#endif
158129  }
158130
158131  /* As an optimization, try to disable the WHERE clause term that is
158132  ** driving the index as it will always be true.  The correct answer is
158133  ** obtained regardless, but we might get the answer with fewer CPU cycles
158134  ** by omitting the term.
158135  **
158136  ** But do not disable the term unless we are certain that the term is
158137  ** not a transitive constraint.  For an example of where that does not
158138  ** work, see https://sqlite.org/forum/forumpost/eb8613976a (2021-05-04)
158139  */
158140  if( (pLevel->pWLoop->wsFlags & WHERE_TRANSCONS)==0
158141   || (pTerm->eOperator & WO_EQUIV)==0
158142  ){
158143    disableTerm(pLevel, pTerm);
158144  }
158145
158146  return iReg;
158147}
158148
158149/*
158150** Generate code that will evaluate all == and IN constraints for an
158151** index scan.
158152**
158153** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
158154** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
158155** The index has as many as three equality constraints, but in this
158156** example, the third "c" value is an inequality.  So only two
158157** constraints are coded.  This routine will generate code to evaluate
158158** a==5 and b IN (1,2,3).  The current values for a and b will be stored
158159** in consecutive registers and the index of the first register is returned.
158160**
158161** In the example above nEq==2.  But this subroutine works for any value
158162** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
158163** The only thing it does is allocate the pLevel->iMem memory cell and
158164** compute the affinity string.
158165**
158166** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
158167** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
158168** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
158169** occurs after the nEq quality constraints.
158170**
158171** This routine allocates a range of nEq+nExtraReg memory cells and returns
158172** the index of the first memory cell in that range. The code that
158173** calls this routine will use that memory range to store keys for
158174** start and termination conditions of the loop.
158175** key value of the loop.  If one or more IN operators appear, then
158176** this routine allocates an additional nEq memory cells for internal
158177** use.
158178**
158179** Before returning, *pzAff is set to point to a buffer containing a
158180** copy of the column affinity string of the index allocated using
158181** sqlite3DbMalloc(). Except, entries in the copy of the string associated
158182** with equality constraints that use BLOB or NONE affinity are set to
158183** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
158184**
158185**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
158186**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
158187**
158188** In the example above, the index on t1(a) has TEXT affinity. But since
158189** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
158190** no conversion should be attempted before using a t2.b value as part of
158191** a key to search the index. Hence the first byte in the returned affinity
158192** string in this example would be set to SQLITE_AFF_BLOB.
158193*/
158194static int codeAllEqualityTerms(
158195  Parse *pParse,        /* Parsing context */
158196  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
158197  int bRev,             /* Reverse the order of IN operators */
158198  int nExtraReg,        /* Number of extra registers to allocate */
158199  char **pzAff          /* OUT: Set to point to affinity string */
158200){
158201  u16 nEq;                      /* The number of == or IN constraints to code */
158202  u16 nSkip;                    /* Number of left-most columns to skip */
158203  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
158204  Index *pIdx;                  /* The index being used for this loop */
158205  WhereTerm *pTerm;             /* A single constraint term */
158206  WhereLoop *pLoop;             /* The WhereLoop object */
158207  int j;                        /* Loop counter */
158208  int regBase;                  /* Base register */
158209  int nReg;                     /* Number of registers to allocate */
158210  char *zAff;                   /* Affinity string to return */
158211
158212  /* This module is only called on query plans that use an index. */
158213  pLoop = pLevel->pWLoop;
158214  assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
158215  nEq = pLoop->u.btree.nEq;
158216  nSkip = pLoop->nSkip;
158217  pIdx = pLoop->u.btree.pIndex;
158218  assert( pIdx!=0 );
158219
158220  /* Figure out how many memory cells we will need then allocate them.
158221  */
158222  regBase = pParse->nMem + 1;
158223  nReg = nEq + nExtraReg;
158224  pParse->nMem += nReg;
158225
158226  zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
158227  assert( zAff!=0 || pParse->db->mallocFailed );
158228
158229  if( nSkip ){
158230    int iIdxCur = pLevel->iIdxCur;
158231    sqlite3VdbeAddOp3(v, OP_Null, 0, regBase, regBase+nSkip-1);
158232    sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
158233    VdbeCoverageIf(v, bRev==0);
158234    VdbeCoverageIf(v, bRev!=0);
158235    VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
158236    j = sqlite3VdbeAddOp0(v, OP_Goto);
158237    assert( pLevel->addrSkip==0 );
158238    pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
158239                            iIdxCur, 0, regBase, nSkip);
158240    VdbeCoverageIf(v, bRev==0);
158241    VdbeCoverageIf(v, bRev!=0);
158242    sqlite3VdbeJumpHere(v, j);
158243    for(j=0; j<nSkip; j++){
158244      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
158245      testcase( pIdx->aiColumn[j]==XN_EXPR );
158246      VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
158247    }
158248  }
158249
158250  /* Evaluate the equality constraints
158251  */
158252  assert( zAff==0 || (int)strlen(zAff)>=nEq );
158253  for(j=nSkip; j<nEq; j++){
158254    int r1;
158255    pTerm = pLoop->aLTerm[j];
158256    assert( pTerm!=0 );
158257    /* The following testcase is true for indices with redundant columns.
158258    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
158259    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
158260    testcase( pTerm->wtFlags & TERM_VIRTUAL );
158261    r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
158262    if( r1!=regBase+j ){
158263      if( nReg==1 ){
158264        sqlite3ReleaseTempReg(pParse, regBase);
158265        regBase = r1;
158266      }else{
158267        sqlite3VdbeAddOp2(v, OP_Copy, r1, regBase+j);
158268      }
158269    }
158270    if( pTerm->eOperator & WO_IN ){
158271      if( pTerm->pExpr->flags & EP_xIsSelect ){
158272        /* No affinity ever needs to be (or should be) applied to a value
158273        ** from the RHS of an "? IN (SELECT ...)" expression. The
158274        ** sqlite3FindInIndex() routine has already ensured that the
158275        ** affinity of the comparison has been applied to the value.  */
158276        if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
158277      }
158278    }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
158279      Expr *pRight = pTerm->pExpr->pRight;
158280      if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
158281        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
158282        VdbeCoverage(v);
158283      }
158284      if( pParse->nErr==0 ){
158285        assert( pParse->db->mallocFailed==0 );
158286        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
158287          zAff[j] = SQLITE_AFF_BLOB;
158288        }
158289        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
158290          zAff[j] = SQLITE_AFF_BLOB;
158291        }
158292      }
158293    }
158294  }
158295  *pzAff = zAff;
158296  return regBase;
158297}
158298
158299#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
158300/*
158301** If the most recently coded instruction is a constant range constraint
158302** (a string literal) that originated from the LIKE optimization, then
158303** set P3 and P5 on the OP_String opcode so that the string will be cast
158304** to a BLOB at appropriate times.
158305**
158306** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
158307** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
158308** scan loop run twice, once for strings and a second time for BLOBs.
158309** The OP_String opcodes on the second pass convert the upper and lower
158310** bound string constants to blobs.  This routine makes the necessary changes
158311** to the OP_String opcodes for that to happen.
158312**
158313** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
158314** only the one pass through the string space is required, so this routine
158315** becomes a no-op.
158316*/
158317static void whereLikeOptimizationStringFixup(
158318  Vdbe *v,                /* prepared statement under construction */
158319  WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
158320  WhereTerm *pTerm        /* The upper or lower bound just coded */
158321){
158322  if( pTerm->wtFlags & TERM_LIKEOPT ){
158323    VdbeOp *pOp;
158324    assert( pLevel->iLikeRepCntr>0 );
158325    pOp = sqlite3VdbeGetLastOp(v);
158326    assert( pOp!=0 );
158327    assert( pOp->opcode==OP_String8
158328            || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
158329    pOp->p3 = (int)(pLevel->iLikeRepCntr>>1);  /* Register holding counter */
158330    pOp->p5 = (u8)(pLevel->iLikeRepCntr&1);    /* ASC or DESC */
158331  }
158332}
158333#else
158334# define whereLikeOptimizationStringFixup(A,B,C)
158335#endif
158336
158337#ifdef SQLITE_ENABLE_CURSOR_HINTS
158338/*
158339** Information is passed from codeCursorHint() down to individual nodes of
158340** the expression tree (by sqlite3WalkExpr()) using an instance of this
158341** structure.
158342*/
158343struct CCurHint {
158344  int iTabCur;    /* Cursor for the main table */
158345  int iIdxCur;    /* Cursor for the index, if pIdx!=0.  Unused otherwise */
158346  Index *pIdx;    /* The index used to access the table */
158347};
158348
158349/*
158350** This function is called for every node of an expression that is a candidate
158351** for a cursor hint on an index cursor.  For TK_COLUMN nodes that reference
158352** the table CCurHint.iTabCur, verify that the same column can be
158353** accessed through the index.  If it cannot, then set pWalker->eCode to 1.
158354*/
158355static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
158356  struct CCurHint *pHint = pWalker->u.pCCurHint;
158357  assert( pHint->pIdx!=0 );
158358  if( pExpr->op==TK_COLUMN
158359   && pExpr->iTable==pHint->iTabCur
158360   && sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0
158361  ){
158362    pWalker->eCode = 1;
158363  }
158364  return WRC_Continue;
158365}
158366
158367/*
158368** Test whether or not expression pExpr, which was part of a WHERE clause,
158369** should be included in the cursor-hint for a table that is on the rhs
158370** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
158371** expression is not suitable.
158372**
158373** An expression is unsuitable if it might evaluate to non NULL even if
158374** a TK_COLUMN node that does affect the value of the expression is set
158375** to NULL. For example:
158376**
158377**   col IS NULL
158378**   col IS NOT NULL
158379**   coalesce(col, 1)
158380**   CASE WHEN col THEN 0 ELSE 1 END
158381*/
158382static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
158383  if( pExpr->op==TK_IS
158384   || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
158385   || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
158386  ){
158387    pWalker->eCode = 1;
158388  }else if( pExpr->op==TK_FUNCTION ){
158389    int d1;
158390    char d2[4];
158391    if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
158392      pWalker->eCode = 1;
158393    }
158394  }
158395
158396  return WRC_Continue;
158397}
158398
158399
158400/*
158401** This function is called on every node of an expression tree used as an
158402** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
158403** that accesses any table other than the one identified by
158404** CCurHint.iTabCur, then do the following:
158405**
158406**   1) allocate a register and code an OP_Column instruction to read
158407**      the specified column into the new register, and
158408**
158409**   2) transform the expression node to a TK_REGISTER node that reads
158410**      from the newly populated register.
158411**
158412** Also, if the node is a TK_COLUMN that does access the table identified
158413** by pCCurHint.iTabCur, and an index is being used (which we will
158414** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
158415** an access of the index rather than the original table.
158416*/
158417static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
158418  int rc = WRC_Continue;
158419  int reg;
158420  struct CCurHint *pHint = pWalker->u.pCCurHint;
158421  if( pExpr->op==TK_COLUMN ){
158422    if( pExpr->iTable!=pHint->iTabCur ){
158423      reg = ++pWalker->pParse->nMem;   /* Register for column value */
158424      reg = sqlite3ExprCodeTarget(pWalker->pParse, pExpr, reg);
158425      pExpr->op = TK_REGISTER;
158426      pExpr->iTable = reg;
158427    }else if( pHint->pIdx!=0 ){
158428      pExpr->iTable = pHint->iIdxCur;
158429      pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn);
158430      assert( pExpr->iColumn>=0 );
158431    }
158432  }else if( pExpr->pAggInfo ){
158433    rc = WRC_Prune;
158434    reg = ++pWalker->pParse->nMem;   /* Register for column value */
158435    reg = sqlite3ExprCodeTarget(pWalker->pParse, pExpr, reg);
158436    pExpr->op = TK_REGISTER;
158437    pExpr->iTable = reg;
158438  }else if( pExpr->op==TK_TRUEFALSE ){
158439    /* Do not walk disabled expressions.  tag-20230504-1 */
158440    return WRC_Prune;
158441  }
158442  return rc;
158443}
158444
158445/*
158446** Insert an OP_CursorHint instruction if it is appropriate to do so.
158447*/
158448static void codeCursorHint(
158449  SrcItem *pTabItem,  /* FROM clause item */
158450  WhereInfo *pWInfo,    /* The where clause */
158451  WhereLevel *pLevel,   /* Which loop to provide hints for */
158452  WhereTerm *pEndRange  /* Hint this end-of-scan boundary term if not NULL */
158453){
158454  Parse *pParse = pWInfo->pParse;
158455  sqlite3 *db = pParse->db;
158456  Vdbe *v = pParse->pVdbe;
158457  Expr *pExpr = 0;
158458  WhereLoop *pLoop = pLevel->pWLoop;
158459  int iCur;
158460  WhereClause *pWC;
158461  WhereTerm *pTerm;
158462  int i, j;
158463  struct CCurHint sHint;
158464  Walker sWalker;
158465
158466  if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
158467  iCur = pLevel->iTabCur;
158468  assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
158469  sHint.iTabCur = iCur;
158470  sHint.iIdxCur = pLevel->iIdxCur;
158471  sHint.pIdx = pLoop->u.btree.pIndex;
158472  memset(&sWalker, 0, sizeof(sWalker));
158473  sWalker.pParse = pParse;
158474  sWalker.u.pCCurHint = &sHint;
158475  pWC = &pWInfo->sWC;
158476  for(i=0; i<pWC->nBase; i++){
158477    pTerm = &pWC->a[i];
158478    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
158479    if( pTerm->prereqAll & pLevel->notReady ) continue;
158480
158481    /* Any terms specified as part of the ON(...) clause for any LEFT
158482    ** JOIN for which the current table is not the rhs are omitted
158483    ** from the cursor-hint.
158484    **
158485    ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
158486    ** that were specified as part of the WHERE clause must be excluded.
158487    ** This is to address the following:
158488    **
158489    **   SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
158490    **
158491    ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
158492    ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
158493    ** pushed down to the cursor, this row is filtered out, causing
158494    ** SQLite to synthesize a row of NULL values. Which does match the
158495    ** WHERE clause, and so the query returns a row. Which is incorrect.
158496    **
158497    ** For the same reason, WHERE terms such as:
158498    **
158499    **   WHERE 1 = (t2.c IS NULL)
158500    **
158501    ** are also excluded. See codeCursorHintIsOrFunction() for details.
158502    */
158503    if( pTabItem->fg.jointype & JT_LEFT ){
158504      Expr *pExpr = pTerm->pExpr;
158505      if( !ExprHasProperty(pExpr, EP_OuterON)
158506       || pExpr->w.iJoin!=pTabItem->iCursor
158507      ){
158508        sWalker.eCode = 0;
158509        sWalker.xExprCallback = codeCursorHintIsOrFunction;
158510        sqlite3WalkExpr(&sWalker, pTerm->pExpr);
158511        if( sWalker.eCode ) continue;
158512      }
158513    }else{
158514      if( ExprHasProperty(pTerm->pExpr, EP_OuterON) ) continue;
158515    }
158516
158517    /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
158518    ** the cursor.  These terms are not needed as hints for a pure range
158519    ** scan (that has no == terms) so omit them. */
158520    if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
158521      for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
158522      if( j<pLoop->nLTerm ) continue;
158523    }
158524
158525    /* No subqueries or non-deterministic functions allowed */
158526    if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
158527
158528    /* For an index scan, make sure referenced columns are actually in
158529    ** the index. */
158530    if( sHint.pIdx!=0 ){
158531      sWalker.eCode = 0;
158532      sWalker.xExprCallback = codeCursorHintCheckExpr;
158533      sqlite3WalkExpr(&sWalker, pTerm->pExpr);
158534      if( sWalker.eCode ) continue;
158535    }
158536
158537    /* If we survive all prior tests, that means this term is worth hinting */
158538    pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
158539  }
158540  if( pExpr!=0 ){
158541    sWalker.xExprCallback = codeCursorHintFixExpr;
158542    if( pParse->nErr==0 ) sqlite3WalkExpr(&sWalker, pExpr);
158543    sqlite3VdbeAddOp4(v, OP_CursorHint,
158544                      (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
158545                      (const char*)pExpr, P4_EXPR);
158546  }
158547}
158548#else
158549# define codeCursorHint(A,B,C,D)  /* No-op */
158550#endif /* SQLITE_ENABLE_CURSOR_HINTS */
158551
158552/*
158553** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
158554** a rowid value just read from cursor iIdxCur, open on index pIdx. This
158555** function generates code to do a deferred seek of cursor iCur to the
158556** rowid stored in register iRowid.
158557**
158558** Normally, this is just:
158559**
158560**   OP_DeferredSeek $iCur $iRowid
158561**
158562** Which causes a seek on $iCur to the row with rowid $iRowid.
158563**
158564** However, if the scan currently being coded is a branch of an OR-loop and
158565** the statement currently being coded is a SELECT, then additional information
158566** is added that might allow OP_Column to omit the seek and instead do its
158567** lookup on the index, thus avoiding an expensive seek operation.  To
158568** enable this optimization, the P3 of OP_DeferredSeek is set to iIdxCur
158569** and P4 is set to an array of integers containing one entry for each column
158570** in the table.  For each table column, if the column is the i'th
158571** column of the index, then the corresponding array entry is set to (i+1).
158572** If the column does not appear in the index at all, the array entry is set
158573** to 0.  The OP_Column opcode can check this array to see if the column it
158574** wants is in the index and if it is, it will substitute the index cursor
158575** and column number and continue with those new values, rather than seeking
158576** the table cursor.
158577*/
158578static void codeDeferredSeek(
158579  WhereInfo *pWInfo,              /* Where clause context */
158580  Index *pIdx,                    /* Index scan is using */
158581  int iCur,                       /* Cursor for IPK b-tree */
158582  int iIdxCur                     /* Index cursor */
158583){
158584  Parse *pParse = pWInfo->pParse; /* Parse context */
158585  Vdbe *v = pParse->pVdbe;        /* Vdbe to generate code within */
158586
158587  assert( iIdxCur>0 );
158588  assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
158589
158590  pWInfo->bDeferredSeek = 1;
158591  sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
158592  if( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))
158593   && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
158594  ){
158595    int i;
158596    Table *pTab = pIdx->pTable;
158597    u32 *ai = (u32*)sqlite3DbMallocZero(pParse->db, sizeof(u32)*(pTab->nCol+1));
158598    if( ai ){
158599      ai[0] = pTab->nCol;
158600      for(i=0; i<pIdx->nColumn-1; i++){
158601        int x1, x2;
158602        assert( pIdx->aiColumn[i]<pTab->nCol );
158603        x1 = pIdx->aiColumn[i];
158604        x2 = sqlite3TableColumnToStorage(pTab, x1);
158605        testcase( x1!=x2 );
158606        if( x1>=0 ) ai[x2+1] = i+1;
158607      }
158608      sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
158609    }
158610  }
158611}
158612
158613/*
158614** If the expression passed as the second argument is a vector, generate
158615** code to write the first nReg elements of the vector into an array
158616** of registers starting with iReg.
158617**
158618** If the expression is not a vector, then nReg must be passed 1. In
158619** this case, generate code to evaluate the expression and leave the
158620** result in register iReg.
158621*/
158622static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
158623  assert( nReg>0 );
158624  if( p && sqlite3ExprIsVector(p) ){
158625#ifndef SQLITE_OMIT_SUBQUERY
158626    if( ExprUseXSelect(p) ){
158627      Vdbe *v = pParse->pVdbe;
158628      int iSelect;
158629      assert( p->op==TK_SELECT );
158630      iSelect = sqlite3CodeSubselect(pParse, p);
158631      sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
158632    }else
158633#endif
158634    {
158635      int i;
158636      const ExprList *pList;
158637      assert( ExprUseXList(p) );
158638      pList = p->x.pList;
158639      assert( nReg<=pList->nExpr );
158640      for(i=0; i<nReg; i++){
158641        sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
158642      }
158643    }
158644  }else{
158645    assert( nReg==1 || pParse->nErr );
158646    sqlite3ExprCode(pParse, p, iReg);
158647  }
158648}
158649
158650/*
158651** The pTruth expression is always true because it is the WHERE clause
158652** a partial index that is driving a query loop.  Look through all of the
158653** WHERE clause terms on the query, and if any of those terms must be
158654** true because pTruth is true, then mark those WHERE clause terms as
158655** coded.
158656*/
158657static void whereApplyPartialIndexConstraints(
158658  Expr *pTruth,
158659  int iTabCur,
158660  WhereClause *pWC
158661){
158662  int i;
158663  WhereTerm *pTerm;
158664  while( pTruth->op==TK_AND ){
158665    whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC);
158666    pTruth = pTruth->pRight;
158667  }
158668  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
158669    Expr *pExpr;
158670    if( pTerm->wtFlags & TERM_CODED ) continue;
158671    pExpr = pTerm->pExpr;
158672    if( sqlite3ExprCompare(0, pExpr, pTruth, iTabCur)==0 ){
158673      pTerm->wtFlags |= TERM_CODED;
158674    }
158675  }
158676}
158677
158678/*
158679** This routine is called right after An OP_Filter has been generated and
158680** before the corresponding index search has been performed.  This routine
158681** checks to see if there are additional Bloom filters in inner loops that
158682** can be checked prior to doing the index lookup.  If there are available
158683** inner-loop Bloom filters, then evaluate those filters now, before the
158684** index lookup.  The idea is that a Bloom filter check is way faster than
158685** an index lookup, and the Bloom filter might return false, meaning that
158686** the index lookup can be skipped.
158687**
158688** We know that an inner loop uses a Bloom filter because it has the
158689** WhereLevel.regFilter set.  If an inner-loop Bloom filter is checked,
158690** then clear the WhereLevel.regFilter value to prevent the Bloom filter
158691** from being checked a second time when the inner loop is evaluated.
158692*/
158693static SQLITE_NOINLINE void filterPullDown(
158694  Parse *pParse,       /* Parsing context */
158695  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
158696  int iLevel,          /* Which level of pWInfo->a[] should be coded */
158697  int addrNxt,         /* Jump here to bypass inner loops */
158698  Bitmask notReady     /* Loops that are not ready */
158699){
158700  while( ++iLevel < pWInfo->nLevel ){
158701    WhereLevel *pLevel = &pWInfo->a[iLevel];
158702    WhereLoop *pLoop = pLevel->pWLoop;
158703    if( pLevel->regFilter==0 ) continue;
158704    if( pLevel->pWLoop->nSkip ) continue;
158705    /*         ,--- Because sqlite3ConstructBloomFilter() has will not have set
158706    **  vvvvv--'    pLevel->regFilter if this were true. */
158707    if( NEVER(pLoop->prereq & notReady) ) continue;
158708    assert( pLevel->addrBrk==0 );
158709    pLevel->addrBrk = addrNxt;
158710    if( pLoop->wsFlags & WHERE_IPK ){
158711      WhereTerm *pTerm = pLoop->aLTerm[0];
158712      int regRowid;
158713      assert( pTerm!=0 );
158714      assert( pTerm->pExpr!=0 );
158715      testcase( pTerm->wtFlags & TERM_VIRTUAL );
158716      regRowid = sqlite3GetTempReg(pParse);
158717      regRowid = codeEqualityTerm(pParse, pTerm, pLevel, 0, 0, regRowid);
158718      sqlite3VdbeAddOp2(pParse->pVdbe, OP_MustBeInt, regRowid, addrNxt);
158719      VdbeCoverage(pParse->pVdbe);
158720      sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
158721                           addrNxt, regRowid, 1);
158722      VdbeCoverage(pParse->pVdbe);
158723    }else{
158724      u16 nEq = pLoop->u.btree.nEq;
158725      int r1;
158726      char *zStartAff;
158727
158728      assert( pLoop->wsFlags & WHERE_INDEXED );
158729      assert( (pLoop->wsFlags & WHERE_COLUMN_IN)==0 );
158730      r1 = codeAllEqualityTerms(pParse,pLevel,0,0,&zStartAff);
158731      codeApplyAffinity(pParse, r1, nEq, zStartAff);
158732      sqlite3DbFree(pParse->db, zStartAff);
158733      sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
158734                           addrNxt, r1, nEq);
158735      VdbeCoverage(pParse->pVdbe);
158736    }
158737    pLevel->regFilter = 0;
158738    pLevel->addrBrk = 0;
158739  }
158740}
158741
158742/*
158743** Loop pLoop is a WHERE_INDEXED level that uses at least one IN(...)
158744** operator. Return true if level pLoop is guaranteed to visit only one
158745** row for each key generated for the index.
158746*/
158747static int whereLoopIsOneRow(WhereLoop *pLoop){
158748  if( pLoop->u.btree.pIndex->onError
158749   && pLoop->nSkip==0
158750   && pLoop->u.btree.nEq==pLoop->u.btree.pIndex->nKeyCol
158751  ){
158752    int ii;
158753    for(ii=0; ii<pLoop->u.btree.nEq; ii++){
158754      if( pLoop->aLTerm[ii]->eOperator & (WO_IS|WO_ISNULL) ){
158755        return 0;
158756      }
158757    }
158758    return 1;
158759  }
158760  return 0;
158761}
158762
158763/*
158764** Generate code for the start of the iLevel-th loop in the WHERE clause
158765** implementation described by pWInfo.
158766*/
158767SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
158768  Parse *pParse,       /* Parsing context */
158769  Vdbe *v,             /* Prepared statement under construction */
158770  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
158771  int iLevel,          /* Which level of pWInfo->a[] should be coded */
158772  WhereLevel *pLevel,  /* The current level pointer */
158773  Bitmask notReady     /* Which tables are currently available */
158774){
158775  int j, k;            /* Loop counters */
158776  int iCur;            /* The VDBE cursor for the table */
158777  int addrNxt;         /* Where to jump to continue with the next IN case */
158778  int bRev;            /* True if we need to scan in reverse order */
158779  WhereLoop *pLoop;    /* The WhereLoop object being coded */
158780  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
158781  WhereTerm *pTerm;               /* A WHERE clause term */
158782  sqlite3 *db;                    /* Database connection */
158783  SrcItem *pTabItem;              /* FROM clause term being coded */
158784  int addrBrk;                    /* Jump here to break out of the loop */
158785  int addrHalt;                   /* addrBrk for the outermost loop */
158786  int addrCont;                   /* Jump here to continue with next cycle */
158787  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
158788  int iReleaseReg = 0;      /* Temp register to free before returning */
158789  Index *pIdx = 0;          /* Index used by loop (if any) */
158790  int iLoop;                /* Iteration of constraint generator loop */
158791
158792  pWC = &pWInfo->sWC;
158793  db = pParse->db;
158794  pLoop = pLevel->pWLoop;
158795  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
158796  iCur = pTabItem->iCursor;
158797  pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
158798  bRev = (pWInfo->revMask>>iLevel)&1;
158799  VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
158800#if WHERETRACE_ENABLED /* 0x4001 */
158801  if( sqlite3WhereTrace & 0x1 ){
158802    sqlite3DebugPrintf("Coding level %d of %d:  notReady=%llx  iFrom=%d\n",
158803       iLevel, pWInfo->nLevel, (u64)notReady, pLevel->iFrom);
158804    if( sqlite3WhereTrace & 0x1000 ){
158805      sqlite3WhereLoopPrint(pLoop, pWC);
158806    }
158807  }
158808  if( (sqlite3WhereTrace & 0x4001)==0x4001 ){
158809    if( iLevel==0 ){
158810      sqlite3DebugPrintf("WHERE clause being coded:\n");
158811      sqlite3TreeViewExpr(0, pWInfo->pWhere, 0);
158812    }
158813    sqlite3DebugPrintf("All WHERE-clause terms before coding:\n");
158814    sqlite3WhereClausePrint(pWC);
158815  }
158816#endif
158817
158818  /* Create labels for the "break" and "continue" instructions
158819  ** for the current loop.  Jump to addrBrk to break out of a loop.
158820  ** Jump to cont to go immediately to the next iteration of the
158821  ** loop.
158822  **
158823  ** When there is an IN operator, we also have a "addrNxt" label that
158824  ** means to continue with the next IN value combination.  When
158825  ** there are no IN operators in the constraints, the "addrNxt" label
158826  ** is the same as "addrBrk".
158827  */
158828  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
158829  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse);
158830
158831  /* If this is the right table of a LEFT OUTER JOIN, allocate and
158832  ** initialize a memory cell that records if this table matches any
158833  ** row of the left table of the join.
158834  */
158835  assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))
158836       || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
158837  );
158838  if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
158839    pLevel->iLeftJoin = ++pParse->nMem;
158840    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
158841    VdbeComment((v, "init LEFT JOIN match flag"));
158842  }
158843
158844  /* Compute a safe address to jump to if we discover that the table for
158845  ** this loop is empty and can never contribute content. */
158846  for(j=iLevel; j>0; j--){
158847    if( pWInfo->a[j].iLeftJoin ) break;
158848    if( pWInfo->a[j].pRJ ) break;
158849  }
158850  addrHalt = pWInfo->a[j].addrBrk;
158851
158852  /* Special case of a FROM clause subquery implemented as a co-routine */
158853  if( pTabItem->fg.viaCoroutine ){
158854    int regYield = pTabItem->regReturn;
158855    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
158856    pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
158857    VdbeCoverage(v);
158858    VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
158859    pLevel->op = OP_Goto;
158860  }else
158861
158862#ifndef SQLITE_OMIT_VIRTUALTABLE
158863  if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
158864    /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
158865    **          to access the data.
158866    */
158867    int iReg;   /* P3 Value for OP_VFilter */
158868    int addrNotFound;
158869    int nConstraint = pLoop->nLTerm;
158870
158871    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
158872    addrNotFound = pLevel->addrBrk;
158873    for(j=0; j<nConstraint; j++){
158874      int iTarget = iReg+j+2;
158875      pTerm = pLoop->aLTerm[j];
158876      if( NEVER(pTerm==0) ) continue;
158877      if( pTerm->eOperator & WO_IN ){
158878        if( SMASKBIT32(j) & pLoop->u.vtab.mHandleIn ){
158879          int iTab = pParse->nTab++;
158880          int iCache = ++pParse->nMem;
158881          sqlite3CodeRhsOfIN(pParse, pTerm->pExpr, iTab);
158882          sqlite3VdbeAddOp3(v, OP_VInitIn, iTab, iTarget, iCache);
158883        }else{
158884          codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
158885          addrNotFound = pLevel->addrNxt;
158886        }
158887      }else{
158888        Expr *pRight = pTerm->pExpr->pRight;
158889        codeExprOrVector(pParse, pRight, iTarget, 1);
158890        if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET
158891         && pLoop->u.vtab.bOmitOffset
158892        ){
158893          assert( pTerm->eOperator==WO_AUX );
158894          assert( pWInfo->pSelect!=0 );
158895          assert( pWInfo->pSelect->iOffset>0 );
158896          sqlite3VdbeAddOp2(v, OP_Integer, 0, pWInfo->pSelect->iOffset);
158897          VdbeComment((v,"Zero OFFSET counter"));
158898        }
158899      }
158900    }
158901    sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
158902    sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
158903    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
158904                      pLoop->u.vtab.idxStr,
158905                      pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
158906    VdbeCoverage(v);
158907    pLoop->u.vtab.needFree = 0;
158908    /* An OOM inside of AddOp4(OP_VFilter) instruction above might have freed
158909    ** the u.vtab.idxStr.  NULL it out to prevent a use-after-free */
158910    if( db->mallocFailed ) pLoop->u.vtab.idxStr = 0;
158911    pLevel->p1 = iCur;
158912    pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
158913    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
158914    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
158915
158916    for(j=0; j<nConstraint; j++){
158917      pTerm = pLoop->aLTerm[j];
158918      if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
158919        disableTerm(pLevel, pTerm);
158920        continue;
158921      }
158922      if( (pTerm->eOperator & WO_IN)!=0
158923       && (SMASKBIT32(j) & pLoop->u.vtab.mHandleIn)==0
158924       && !db->mallocFailed
158925      ){
158926        Expr *pCompare;  /* The comparison operator */
158927        Expr *pRight;    /* RHS of the comparison */
158928        VdbeOp *pOp;     /* Opcode to access the value of the IN constraint */
158929        int iIn;         /* IN loop corresponding to the j-th constraint */
158930
158931        /* Reload the constraint value into reg[iReg+j+2].  The same value
158932        ** was loaded into the same register prior to the OP_VFilter, but
158933        ** the xFilter implementation might have changed the datatype or
158934        ** encoding of the value in the register, so it *must* be reloaded.
158935        */
158936        for(iIn=0; ALWAYS(iIn<pLevel->u.in.nIn); iIn++){
158937          pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop);
158938          if( (pOp->opcode==OP_Column && pOp->p3==iReg+j+2)
158939           || (pOp->opcode==OP_Rowid && pOp->p2==iReg+j+2)
158940          ){
158941            testcase( pOp->opcode==OP_Rowid );
158942            sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
158943            break;
158944          }
158945        }
158946
158947        /* Generate code that will continue to the next row if
158948        ** the IN constraint is not satisfied
158949        */
158950        pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
158951        if( !db->mallocFailed ){
158952          int iFld = pTerm->u.x.iField;
158953          Expr *pLeft = pTerm->pExpr->pLeft;
158954          assert( pLeft!=0 );
158955          if( iFld>0 ){
158956            assert( pLeft->op==TK_VECTOR );
158957            assert( ExprUseXList(pLeft) );
158958            assert( iFld<=pLeft->x.pList->nExpr );
158959            pCompare->pLeft = pLeft->x.pList->a[iFld-1].pExpr;
158960          }else{
158961            pCompare->pLeft = pLeft;
158962          }
158963          pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
158964          if( pRight ){
158965            pRight->iTable = iReg+j+2;
158966            sqlite3ExprIfFalse(
158967                pParse, pCompare, pLevel->addrCont, SQLITE_JUMPIFNULL
158968            );
158969          }
158970          pCompare->pLeft = 0;
158971        }
158972        sqlite3ExprDelete(db, pCompare);
158973      }
158974    }
158975
158976    /* These registers need to be preserved in case there is an IN operator
158977    ** loop.  So we could deallocate the registers here (and potentially
158978    ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0.  But it seems
158979    ** simpler and safer to simply not reuse the registers.
158980    **
158981    **    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
158982    */
158983  }else
158984#endif /* SQLITE_OMIT_VIRTUALTABLE */
158985
158986  if( (pLoop->wsFlags & WHERE_IPK)!=0
158987   && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
158988  ){
158989    /* Case 2:  We can directly reference a single row using an
158990    **          equality comparison against the ROWID field.  Or
158991    **          we reference multiple rows using a "rowid IN (...)"
158992    **          construct.
158993    */
158994    assert( pLoop->u.btree.nEq==1 );
158995    pTerm = pLoop->aLTerm[0];
158996    assert( pTerm!=0 );
158997    assert( pTerm->pExpr!=0 );
158998    testcase( pTerm->wtFlags & TERM_VIRTUAL );
158999    iReleaseReg = ++pParse->nMem;
159000    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
159001    if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
159002    addrNxt = pLevel->addrNxt;
159003    if( pLevel->regFilter ){
159004      sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
159005      VdbeCoverage(v);
159006      sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt,
159007                           iRowidReg, 1);
159008      VdbeCoverage(v);
159009      filterPullDown(pParse, pWInfo, iLevel, addrNxt, notReady);
159010    }
159011    sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
159012    VdbeCoverage(v);
159013    pLevel->op = OP_Noop;
159014  }else if( (pLoop->wsFlags & WHERE_IPK)!=0
159015         && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
159016  ){
159017    /* Case 3:  We have an inequality comparison against the ROWID field.
159018    */
159019    int testOp = OP_Noop;
159020    int start;
159021    int memEndValue = 0;
159022    WhereTerm *pStart, *pEnd;
159023
159024    j = 0;
159025    pStart = pEnd = 0;
159026    if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
159027    if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
159028    assert( pStart!=0 || pEnd!=0 );
159029    if( bRev ){
159030      pTerm = pStart;
159031      pStart = pEnd;
159032      pEnd = pTerm;
159033    }
159034    codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
159035    if( pStart ){
159036      Expr *pX;             /* The expression that defines the start bound */
159037      int r1, rTemp;        /* Registers for holding the start boundary */
159038      int op;               /* Cursor seek operation */
159039
159040      /* The following constant maps TK_xx codes into corresponding
159041      ** seek opcodes.  It depends on a particular ordering of TK_xx
159042      */
159043      const u8 aMoveOp[] = {
159044           /* TK_GT */  OP_SeekGT,
159045           /* TK_LE */  OP_SeekLE,
159046           /* TK_LT */  OP_SeekLT,
159047           /* TK_GE */  OP_SeekGE
159048      };
159049      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
159050      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
159051      assert( TK_GE==TK_GT+3 );      /*  ... is correct. */
159052
159053      assert( (pStart->wtFlags & TERM_VNULL)==0 );
159054      testcase( pStart->wtFlags & TERM_VIRTUAL );
159055      pX = pStart->pExpr;
159056      assert( pX!=0 );
159057      testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
159058      if( sqlite3ExprIsVector(pX->pRight) ){
159059        r1 = rTemp = sqlite3GetTempReg(pParse);
159060        codeExprOrVector(pParse, pX->pRight, r1, 1);
159061        testcase( pX->op==TK_GT );
159062        testcase( pX->op==TK_GE );
159063        testcase( pX->op==TK_LT );
159064        testcase( pX->op==TK_LE );
159065        op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];
159066        assert( pX->op!=TK_GT || op==OP_SeekGE );
159067        assert( pX->op!=TK_GE || op==OP_SeekGE );
159068        assert( pX->op!=TK_LT || op==OP_SeekLE );
159069        assert( pX->op!=TK_LE || op==OP_SeekLE );
159070      }else{
159071        r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
159072        disableTerm(pLevel, pStart);
159073        op = aMoveOp[(pX->op - TK_GT)];
159074      }
159075      sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
159076      VdbeComment((v, "pk"));
159077      VdbeCoverageIf(v, pX->op==TK_GT);
159078      VdbeCoverageIf(v, pX->op==TK_LE);
159079      VdbeCoverageIf(v, pX->op==TK_LT);
159080      VdbeCoverageIf(v, pX->op==TK_GE);
159081      sqlite3ReleaseTempReg(pParse, rTemp);
159082    }else{
159083      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
159084      VdbeCoverageIf(v, bRev==0);
159085      VdbeCoverageIf(v, bRev!=0);
159086    }
159087    if( pEnd ){
159088      Expr *pX;
159089      pX = pEnd->pExpr;
159090      assert( pX!=0 );
159091      assert( (pEnd->wtFlags & TERM_VNULL)==0 );
159092      testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
159093      testcase( pEnd->wtFlags & TERM_VIRTUAL );
159094      memEndValue = ++pParse->nMem;
159095      codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
159096      if( 0==sqlite3ExprIsVector(pX->pRight)
159097       && (pX->op==TK_LT || pX->op==TK_GT)
159098      ){
159099        testOp = bRev ? OP_Le : OP_Ge;
159100      }else{
159101        testOp = bRev ? OP_Lt : OP_Gt;
159102      }
159103      if( 0==sqlite3ExprIsVector(pX->pRight) ){
159104        disableTerm(pLevel, pEnd);
159105      }
159106    }
159107    start = sqlite3VdbeCurrentAddr(v);
159108    pLevel->op = bRev ? OP_Prev : OP_Next;
159109    pLevel->p1 = iCur;
159110    pLevel->p2 = start;
159111    assert( pLevel->p5==0 );
159112    if( testOp!=OP_Noop ){
159113      iRowidReg = ++pParse->nMem;
159114      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
159115      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
159116      VdbeCoverageIf(v, testOp==OP_Le);
159117      VdbeCoverageIf(v, testOp==OP_Lt);
159118      VdbeCoverageIf(v, testOp==OP_Ge);
159119      VdbeCoverageIf(v, testOp==OP_Gt);
159120      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
159121    }
159122  }else if( pLoop->wsFlags & WHERE_INDEXED ){
159123    /* Case 4: A scan using an index.
159124    **
159125    **         The WHERE clause may contain zero or more equality
159126    **         terms ("==" or "IN" operators) that refer to the N
159127    **         left-most columns of the index. It may also contain
159128    **         inequality constraints (>, <, >= or <=) on the indexed
159129    **         column that immediately follows the N equalities. Only
159130    **         the right-most column can be an inequality - the rest must
159131    **         use the "==" and "IN" operators. For example, if the
159132    **         index is on (x,y,z), then the following clauses are all
159133    **         optimized:
159134    **
159135    **            x=5
159136    **            x=5 AND y=10
159137    **            x=5 AND y<10
159138    **            x=5 AND y>5 AND y<10
159139    **            x=5 AND y=5 AND z<=10
159140    **
159141    **         The z<10 term of the following cannot be used, only
159142    **         the x=5 term:
159143    **
159144    **            x=5 AND z<10
159145    **
159146    **         N may be zero if there are inequality constraints.
159147    **         If there are no inequality constraints, then N is at
159148    **         least one.
159149    **
159150    **         This case is also used when there are no WHERE clause
159151    **         constraints but an index is selected anyway, in order
159152    **         to force the output order to conform to an ORDER BY.
159153    */
159154    static const u8 aStartOp[] = {
159155      0,
159156      0,
159157      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
159158      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
159159      OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
159160      OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
159161      OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
159162      OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
159163    };
159164    static const u8 aEndOp[] = {
159165      OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
159166      OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
159167      OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
159168      OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
159169    };
159170    u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
159171    u16 nBtm = pLoop->u.btree.nBtm;   /* Length of BTM vector */
159172    u16 nTop = pLoop->u.btree.nTop;   /* Length of TOP vector */
159173    int regBase;                 /* Base register holding constraint values */
159174    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
159175    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
159176    int startEq;                 /* True if range start uses ==, >= or <= */
159177    int endEq;                   /* True if range end uses ==, >= or <= */
159178    int start_constraints;       /* Start of range is constrained */
159179    int nConstraint;             /* Number of constraint terms */
159180    int iIdxCur;                 /* The VDBE cursor for the index */
159181    int nExtraReg = 0;           /* Number of extra registers needed */
159182    int op;                      /* Instruction opcode */
159183    char *zStartAff;             /* Affinity for start of range constraint */
159184    char *zEndAff = 0;           /* Affinity for end of range constraint */
159185    u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
159186    u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
159187    int omitTable;               /* True if we use the index only */
159188    int regBignull = 0;          /* big-null flag register */
159189    int addrSeekScan = 0;        /* Opcode of the OP_SeekScan, if any */
159190
159191    pIdx = pLoop->u.btree.pIndex;
159192    iIdxCur = pLevel->iIdxCur;
159193    assert( nEq>=pLoop->nSkip );
159194
159195    /* Find any inequality constraint terms for the start and end
159196    ** of the range.
159197    */
159198    j = nEq;
159199    if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
159200      pRangeStart = pLoop->aLTerm[j++];
159201      nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
159202      /* Like optimization range constraints always occur in pairs */
159203      assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
159204              (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
159205    }
159206    if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
159207      pRangeEnd = pLoop->aLTerm[j++];
159208      nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
159209#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
159210      if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
159211        assert( pRangeStart!=0 );                     /* LIKE opt constraints */
159212        assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
159213        pLevel->iLikeRepCntr = (u32)++pParse->nMem;
159214        sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
159215        VdbeComment((v, "LIKE loop counter"));
159216        pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
159217        /* iLikeRepCntr actually stores 2x the counter register number.  The
159218        ** bottom bit indicates whether the search order is ASC or DESC. */
159219        testcase( bRev );
159220        testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
159221        assert( (bRev & ~1)==0 );
159222        pLevel->iLikeRepCntr <<=1;
159223        pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
159224      }
159225#endif
159226      if( pRangeStart==0 ){
159227        j = pIdx->aiColumn[nEq];
159228        if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
159229          bSeekPastNull = 1;
159230        }
159231      }
159232    }
159233    assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
159234
159235    /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses
159236    ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS
159237    ** FIRST). In both cases separate ordered scans are made of those
159238    ** index entries for which the column is null and for those for which
159239    ** it is not. For an ASC sort, the non-NULL entries are scanned first.
159240    ** For DESC, NULL entries are scanned first.
159241    */
159242    if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0
159243     && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0
159244    ){
159245      assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 );
159246      assert( pRangeEnd==0 && pRangeStart==0 );
159247      testcase( pLoop->nSkip>0 );
159248      nExtraReg = 1;
159249      bSeekPastNull = 1;
159250      pLevel->regBignull = regBignull = ++pParse->nMem;
159251      if( pLevel->iLeftJoin ){
159252        sqlite3VdbeAddOp2(v, OP_Integer, 0, regBignull);
159253      }
159254      pLevel->addrBignull = sqlite3VdbeMakeLabel(pParse);
159255    }
159256
159257    /* If we are doing a reverse order scan on an ascending index, or
159258    ** a forward order scan on a descending index, interchange the
159259    ** start and end terms (pRangeStart and pRangeEnd).
159260    */
159261    if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) ){
159262      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
159263      SWAP(u8, bSeekPastNull, bStopAtNull);
159264      SWAP(u8, nBtm, nTop);
159265    }
159266
159267    if( iLevel>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 ){
159268      /* In case OP_SeekScan is used, ensure that the index cursor does not
159269      ** point to a valid row for the first iteration of this loop. */
159270      sqlite3VdbeAddOp1(v, OP_NullRow, iIdxCur);
159271    }
159272
159273    /* Generate code to evaluate all constraint terms using == or IN
159274    ** and store the values of those terms in an array of registers
159275    ** starting at regBase.
159276    */
159277    codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
159278    regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
159279    assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
159280    if( zStartAff && nTop ){
159281      zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
159282    }
159283    addrNxt = (regBignull ? pLevel->addrBignull : pLevel->addrNxt);
159284
159285    testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
159286    testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
159287    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
159288    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
159289    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
159290    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
159291    start_constraints = pRangeStart || nEq>0;
159292
159293    /* Seek the index cursor to the start of the range. */
159294    nConstraint = nEq;
159295    if( pRangeStart ){
159296      Expr *pRight = pRangeStart->pExpr->pRight;
159297      codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
159298      whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
159299      if( (pRangeStart->wtFlags & TERM_VNULL)==0
159300       && sqlite3ExprCanBeNull(pRight)
159301      ){
159302        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
159303        VdbeCoverage(v);
159304      }
159305      if( zStartAff ){
159306        updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
159307      }
159308      nConstraint += nBtm;
159309      testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
159310      if( sqlite3ExprIsVector(pRight)==0 ){
159311        disableTerm(pLevel, pRangeStart);
159312      }else{
159313        startEq = 1;
159314      }
159315      bSeekPastNull = 0;
159316    }else if( bSeekPastNull ){
159317      startEq = 0;
159318      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
159319      start_constraints = 1;
159320      nConstraint++;
159321    }else if( regBignull ){
159322      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
159323      start_constraints = 1;
159324      nConstraint++;
159325    }
159326    codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
159327    if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
159328      /* The skip-scan logic inside the call to codeAllEqualityConstraints()
159329      ** above has already left the cursor sitting on the correct row,
159330      ** so no further seeking is needed */
159331    }else{
159332      if( regBignull ){
159333        sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull);
159334        VdbeComment((v, "NULL-scan pass ctr"));
159335      }
159336      if( pLevel->regFilter ){
159337        sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt,
159338                             regBase, nEq);
159339        VdbeCoverage(v);
159340        filterPullDown(pParse, pWInfo, iLevel, addrNxt, notReady);
159341      }
159342
159343      op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
159344      assert( op!=0 );
159345      if( (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 && op==OP_SeekGE ){
159346        assert( regBignull==0 );
159347        /* TUNING:  The OP_SeekScan opcode seeks to reduce the number
159348        ** of expensive seek operations by replacing a single seek with
159349        ** 1 or more step operations.  The question is, how many steps
159350        ** should we try before giving up and going with a seek.  The cost
159351        ** of a seek is proportional to the logarithm of the of the number
159352        ** of entries in the tree, so basing the number of steps to try
159353        ** on the estimated number of rows in the btree seems like a good
159354        ** guess. */
159355        addrSeekScan = sqlite3VdbeAddOp1(v, OP_SeekScan,
159356                                         (pIdx->aiRowLogEst[0]+9)/10);
159357        if( pRangeStart || pRangeEnd ){
159358          sqlite3VdbeChangeP5(v, 1);
159359          sqlite3VdbeChangeP2(v, addrSeekScan, sqlite3VdbeCurrentAddr(v)+1);
159360          addrSeekScan = 0;
159361        }
159362        VdbeCoverage(v);
159363      }
159364      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
159365      VdbeCoverage(v);
159366      VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
159367      VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
159368      VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
159369      VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
159370      VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
159371      VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
159372
159373      assert( bSeekPastNull==0 || bStopAtNull==0 );
159374      if( regBignull ){
159375        assert( bSeekPastNull==1 || bStopAtNull==1 );
159376        assert( bSeekPastNull==!bStopAtNull );
159377        assert( bStopAtNull==startEq );
159378        sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2);
159379        op = aStartOp[(nConstraint>1)*4 + 2 + bRev];
159380        sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase,
159381                             nConstraint-startEq);
159382        VdbeCoverage(v);
159383        VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
159384        VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
159385        VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
159386        VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
159387        assert( op==OP_Rewind || op==OP_Last || op==OP_SeekGE || op==OP_SeekLE);
159388      }
159389    }
159390
159391    /* Load the value for the inequality constraint at the end of the
159392    ** range (if any).
159393    */
159394    nConstraint = nEq;
159395    assert( pLevel->p2==0 );
159396    if( pRangeEnd ){
159397      Expr *pRight = pRangeEnd->pExpr->pRight;
159398      assert( addrSeekScan==0 );
159399      codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
159400      whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
159401      if( (pRangeEnd->wtFlags & TERM_VNULL)==0
159402       && sqlite3ExprCanBeNull(pRight)
159403      ){
159404        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
159405        VdbeCoverage(v);
159406      }
159407      if( zEndAff ){
159408        updateRangeAffinityStr(pRight, nTop, zEndAff);
159409        codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
159410      }else{
159411        assert( pParse->db->mallocFailed );
159412      }
159413      nConstraint += nTop;
159414      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
159415
159416      if( sqlite3ExprIsVector(pRight)==0 ){
159417        disableTerm(pLevel, pRangeEnd);
159418      }else{
159419        endEq = 1;
159420      }
159421    }else if( bStopAtNull ){
159422      if( regBignull==0 ){
159423        sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
159424        endEq = 0;
159425      }
159426      nConstraint++;
159427    }
159428    if( zStartAff ) sqlite3DbNNFreeNN(db, zStartAff);
159429    if( zEndAff ) sqlite3DbNNFreeNN(db, zEndAff);
159430
159431    /* Top of the loop body */
159432    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
159433
159434    /* Check if the index cursor is past the end of the range. */
159435    if( nConstraint ){
159436      if( regBignull ){
159437        /* Except, skip the end-of-range check while doing the NULL-scan */
159438        sqlite3VdbeAddOp2(v, OP_IfNot, regBignull, sqlite3VdbeCurrentAddr(v)+3);
159439        VdbeComment((v, "If NULL-scan 2nd pass"));
159440        VdbeCoverage(v);
159441      }
159442      op = aEndOp[bRev*2 + endEq];
159443      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
159444      testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
159445      testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
159446      testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
159447      testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
159448      if( addrSeekScan ) sqlite3VdbeJumpHere(v, addrSeekScan);
159449    }
159450    if( regBignull ){
159451      /* During a NULL-scan, check to see if we have reached the end of
159452      ** the NULLs */
159453      assert( bSeekPastNull==!bStopAtNull );
159454      assert( bSeekPastNull+bStopAtNull==1 );
159455      assert( nConstraint+bSeekPastNull>0 );
159456      sqlite3VdbeAddOp2(v, OP_If, regBignull, sqlite3VdbeCurrentAddr(v)+2);
159457      VdbeComment((v, "If NULL-scan 1st pass"));
159458      VdbeCoverage(v);
159459      op = aEndOp[bRev*2 + bSeekPastNull];
159460      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase,
159461                           nConstraint+bSeekPastNull);
159462      testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
159463      testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
159464      testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
159465      testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
159466    }
159467
159468    if( (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0 ){
159469      sqlite3VdbeAddOp3(v, OP_SeekHit, iIdxCur, nEq, nEq);
159470    }
159471
159472    /* Seek the table cursor, if required */
159473    omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
159474           && (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))==0;
159475    if( omitTable ){
159476      /* pIdx is a covering index.  No need to access the main table. */
159477    }else if( HasRowid(pIdx->pTable) ){
159478      codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
159479    }else if( iCur!=iIdxCur ){
159480      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
159481      iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
159482      for(j=0; j<pPk->nKeyCol; j++){
159483        k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
159484        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
159485      }
159486      sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
159487                           iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
159488    }
159489
159490    if( pLevel->iLeftJoin==0 ){
159491      /* If a partial index is driving the loop, try to eliminate WHERE clause
159492      ** terms from the query that must be true due to the WHERE clause of
159493      ** the partial index.
159494      **
159495      ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work
159496      ** for a LEFT JOIN.
159497      */
159498      if( pIdx->pPartIdxWhere ){
159499        whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC);
159500      }
159501    }else{
159502      testcase( pIdx->pPartIdxWhere );
159503      /* The following assert() is not a requirement, merely an observation:
159504      ** The OR-optimization doesn't work for the right hand table of
159505      ** a LEFT JOIN: */
159506      assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))==0 );
159507    }
159508
159509    /* Record the instruction used to terminate the loop. */
159510    if( (pLoop->wsFlags & WHERE_ONEROW)
159511     || (pLevel->u.in.nIn && regBignull==0 && whereLoopIsOneRow(pLoop))
159512    ){
159513      pLevel->op = OP_Noop;
159514    }else if( bRev ){
159515      pLevel->op = OP_Prev;
159516    }else{
159517      pLevel->op = OP_Next;
159518    }
159519    pLevel->p1 = iIdxCur;
159520    pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
159521    if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
159522      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
159523    }else{
159524      assert( pLevel->p5==0 );
159525    }
159526    if( omitTable ) pIdx = 0;
159527  }else
159528
159529#ifndef SQLITE_OMIT_OR_OPTIMIZATION
159530  if( pLoop->wsFlags & WHERE_MULTI_OR ){
159531    /* Case 5:  Two or more separately indexed terms connected by OR
159532    **
159533    ** Example:
159534    **
159535    **   CREATE TABLE t1(a,b,c,d);
159536    **   CREATE INDEX i1 ON t1(a);
159537    **   CREATE INDEX i2 ON t1(b);
159538    **   CREATE INDEX i3 ON t1(c);
159539    **
159540    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
159541    **
159542    ** In the example, there are three indexed terms connected by OR.
159543    ** The top of the loop looks like this:
159544    **
159545    **          Null       1                # Zero the rowset in reg 1
159546    **
159547    ** Then, for each indexed term, the following. The arguments to
159548    ** RowSetTest are such that the rowid of the current row is inserted
159549    ** into the RowSet. If it is already present, control skips the
159550    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
159551    **
159552    **        sqlite3WhereBegin(<term>)
159553    **          RowSetTest                  # Insert rowid into rowset
159554    **          Gosub      2 A
159555    **        sqlite3WhereEnd()
159556    **
159557    ** Following the above, code to terminate the loop. Label A, the target
159558    ** of the Gosub above, jumps to the instruction right after the Goto.
159559    **
159560    **          Null       1                # Zero the rowset in reg 1
159561    **          Goto       B                # The loop is finished.
159562    **
159563    **       A: <loop body>                 # Return data, whatever.
159564    **
159565    **          Return     2                # Jump back to the Gosub
159566    **
159567    **       B: <after the loop>
159568    **
159569    ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
159570    ** use an ephemeral index instead of a RowSet to record the primary
159571    ** keys of the rows we have already seen.
159572    **
159573    */
159574    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
159575    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
159576    Index *pCov = 0;             /* Potential covering index (or NULL) */
159577    int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
159578
159579    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
159580    int regRowset = 0;                        /* Register for RowSet object */
159581    int regRowid = 0;                         /* Register holding rowid */
159582    int iLoopBody = sqlite3VdbeMakeLabel(pParse);/* Start of loop body */
159583    int iRetInit;                             /* Address of regReturn init */
159584    int untestedTerms = 0;             /* Some terms not completely tested */
159585    int ii;                            /* Loop counter */
159586    Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
159587    Table *pTab = pTabItem->pTab;
159588
159589    pTerm = pLoop->aLTerm[0];
159590    assert( pTerm!=0 );
159591    assert( pTerm->eOperator & WO_OR );
159592    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
159593    pOrWc = &pTerm->u.pOrInfo->wc;
159594    pLevel->op = OP_Return;
159595    pLevel->p1 = regReturn;
159596
159597    /* Set up a new SrcList in pOrTab containing the table being scanned
159598    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
159599    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
159600    */
159601    if( pWInfo->nLevel>1 ){
159602      int nNotReady;                 /* The number of notReady tables */
159603      SrcItem *origSrc;              /* Original list of tables */
159604      nNotReady = pWInfo->nLevel - iLevel - 1;
159605      pOrTab = sqlite3DbMallocRawNN(db,
159606                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
159607      if( pOrTab==0 ) return notReady;
159608      pOrTab->nAlloc = (u8)(nNotReady + 1);
159609      pOrTab->nSrc = pOrTab->nAlloc;
159610      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
159611      origSrc = pWInfo->pTabList->a;
159612      for(k=1; k<=nNotReady; k++){
159613        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
159614      }
159615    }else{
159616      pOrTab = pWInfo->pTabList;
159617    }
159618
159619    /* Initialize the rowset register to contain NULL. An SQL NULL is
159620    ** equivalent to an empty rowset.  Or, create an ephemeral index
159621    ** capable of holding primary keys in the case of a WITHOUT ROWID.
159622    **
159623    ** Also initialize regReturn to contain the address of the instruction
159624    ** immediately following the OP_Return at the bottom of the loop. This
159625    ** is required in a few obscure LEFT JOIN cases where control jumps
159626    ** over the top of the loop into the body of it. In this case the
159627    ** correct response for the end-of-loop code (the OP_Return) is to
159628    ** fall through to the next instruction, just as an OP_Next does if
159629    ** called on an uninitialized cursor.
159630    */
159631    if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
159632      if( HasRowid(pTab) ){
159633        regRowset = ++pParse->nMem;
159634        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
159635      }else{
159636        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
159637        regRowset = pParse->nTab++;
159638        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
159639        sqlite3VdbeSetP4KeyInfo(pParse, pPk);
159640      }
159641      regRowid = ++pParse->nMem;
159642    }
159643    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
159644
159645    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
159646    ** Then for every term xN, evaluate as the subexpression: xN AND y
159647    ** That way, terms in y that are factored into the disjunction will
159648    ** be picked up by the recursive calls to sqlite3WhereBegin() below.
159649    **
159650    ** Actually, each subexpression is converted to "xN AND w" where w is
159651    ** the "interesting" terms of z - terms that did not originate in the
159652    ** ON or USING clause of a LEFT JOIN, and terms that are usable as
159653    ** indices.
159654    **
159655    ** This optimization also only applies if the (x1 OR x2 OR ...) term
159656    ** is not contained in the ON clause of a LEFT JOIN.
159657    ** See ticket http://www.sqlite.org/src/info/f2369304e4
159658    **
159659    ** 2022-02-04:  Do not push down slices of a row-value comparison.
159660    ** In other words, "w" or "y" may not be a slice of a vector.  Otherwise,
159661    ** the initialization of the right-hand operand of the vector comparison
159662    ** might not occur, or might occur only in an OR branch that is not
159663    ** taken.  dbsqlfuzz 80a9fade844b4fb43564efc972bcb2c68270f5d1.
159664    **
159665    ** 2022-03-03:  Do not push down expressions that involve subqueries.
159666    ** The subquery might get coded as a subroutine.  Any table-references
159667    ** in the subquery might be resolved to index-references for the index on
159668    ** the OR branch in which the subroutine is coded.  But if the subroutine
159669    ** is invoked from a different OR branch that uses a different index, such
159670    ** index-references will not work.  tag-20220303a
159671    ** https://sqlite.org/forum/forumpost/36937b197273d403
159672    */
159673    if( pWC->nTerm>1 ){
159674      int iTerm;
159675      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
159676        Expr *pExpr = pWC->a[iTerm].pExpr;
159677        if( &pWC->a[iTerm] == pTerm ) continue;
159678        testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
159679        testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
159680        testcase( pWC->a[iTerm].wtFlags & TERM_SLICE );
159681        if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED|TERM_SLICE))!=0 ){
159682          continue;
159683        }
159684        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
159685        if( ExprHasProperty(pExpr, EP_Subquery) ) continue;  /* tag-20220303a */
159686        pExpr = sqlite3ExprDup(db, pExpr, 0);
159687        pAndExpr = sqlite3ExprAnd(pParse, pAndExpr, pExpr);
159688      }
159689      if( pAndExpr ){
159690        /* The extra 0x10000 bit on the opcode is masked off and does not
159691        ** become part of the new Expr.op.  However, it does make the
159692        ** op==TK_AND comparison inside of sqlite3PExpr() false, and this
159693        ** prevents sqlite3PExpr() from applying the AND short-circuit
159694        ** optimization, which we do not want here. */
159695        pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr);
159696      }
159697    }
159698
159699    /* Run a separate WHERE clause for each term of the OR clause.  After
159700    ** eliminating duplicates from other WHERE clauses, the action for each
159701    ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
159702    */
159703    ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
159704    for(ii=0; ii<pOrWc->nTerm; ii++){
159705      WhereTerm *pOrTerm = &pOrWc->a[ii];
159706      if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
159707        WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
159708        Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
159709        Expr *pDelete;                  /* Local copy of OR clause term */
159710        int jmp1 = 0;                   /* Address of jump operation */
159711        testcase( (pTabItem[0].fg.jointype & JT_LEFT)!=0
159712               && !ExprHasProperty(pOrExpr, EP_OuterON)
159713        ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */
159714        pDelete = pOrExpr = sqlite3ExprDup(db, pOrExpr, 0);
159715        if( db->mallocFailed ){
159716          sqlite3ExprDelete(db, pDelete);
159717          continue;
159718        }
159719        if( pAndExpr ){
159720          pAndExpr->pLeft = pOrExpr;
159721          pOrExpr = pAndExpr;
159722        }
159723        /* Loop through table entries that match term pOrTerm. */
159724        ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1));
159725        WHERETRACE(0xffffffff, ("Subplan for OR-clause:\n"));
159726        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, 0,
159727                                      WHERE_OR_SUBCLAUSE, iCovCur);
159728        assert( pSubWInfo || pParse->nErr );
159729        if( pSubWInfo ){
159730          WhereLoop *pSubLoop;
159731          int addrExplain = sqlite3WhereExplainOneScan(
159732              pParse, pOrTab, &pSubWInfo->a[0], 0
159733          );
159734          sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
159735
159736          /* This is the sub-WHERE clause body.  First skip over
159737          ** duplicate rows from prior sub-WHERE clauses, and record the
159738          ** rowid (or PRIMARY KEY) for the current row so that the same
159739          ** row will be skipped in subsequent sub-WHERE clauses.
159740          */
159741          if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
159742            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
159743            if( HasRowid(pTab) ){
159744              sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid);
159745              jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
159746                                          regRowid, iSet);
159747              VdbeCoverage(v);
159748            }else{
159749              Index *pPk = sqlite3PrimaryKeyIndex(pTab);
159750              int nPk = pPk->nKeyCol;
159751              int iPk;
159752              int r;
159753
159754              /* Read the PK into an array of temp registers. */
159755              r = sqlite3GetTempRange(pParse, nPk);
159756              for(iPk=0; iPk<nPk; iPk++){
159757                int iCol = pPk->aiColumn[iPk];
159758                sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk);
159759              }
159760
159761              /* Check if the temp table already contains this key. If so,
159762              ** the row has already been included in the result set and
159763              ** can be ignored (by jumping past the Gosub below). Otherwise,
159764              ** insert the key into the temp table and proceed with processing
159765              ** the row.
159766              **
159767              ** Use some of the same optimizations as OP_RowSetTest: If iSet
159768              ** is zero, assume that the key cannot already be present in
159769              ** the temp table. And if iSet is -1, assume that there is no
159770              ** need to insert the key into the temp table, as it will never
159771              ** be tested for.  */
159772              if( iSet ){
159773                jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
159774                VdbeCoverage(v);
159775              }
159776              if( iSet>=0 ){
159777                sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
159778                sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
159779                                     r, nPk);
159780                if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
159781              }
159782
159783              /* Release the array of temp registers */
159784              sqlite3ReleaseTempRange(pParse, r, nPk);
159785            }
159786          }
159787
159788          /* Invoke the main loop body as a subroutine */
159789          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
159790
159791          /* Jump here (skipping the main loop body subroutine) if the
159792          ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
159793          if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
159794
159795          /* The pSubWInfo->untestedTerms flag means that this OR term
159796          ** contained one or more AND term from a notReady table.  The
159797          ** terms from the notReady table could not be tested and will
159798          ** need to be tested later.
159799          */
159800          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
159801
159802          /* If all of the OR-connected terms are optimized using the same
159803          ** index, and the index is opened using the same cursor number
159804          ** by each call to sqlite3WhereBegin() made by this loop, it may
159805          ** be possible to use that index as a covering index.
159806          **
159807          ** If the call to sqlite3WhereBegin() above resulted in a scan that
159808          ** uses an index, and this is either the first OR-connected term
159809          ** processed or the index is the same as that used by all previous
159810          ** terms, set pCov to the candidate covering index. Otherwise, set
159811          ** pCov to NULL to indicate that no candidate covering index will
159812          ** be available.
159813          */
159814          pSubLoop = pSubWInfo->a[0].pWLoop;
159815          assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
159816          if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
159817           && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
159818           && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
159819          ){
159820            assert( pSubWInfo->a[0].iIdxCur==iCovCur );
159821            pCov = pSubLoop->u.btree.pIndex;
159822          }else{
159823            pCov = 0;
159824          }
159825          if( sqlite3WhereUsesDeferredSeek(pSubWInfo) ){
159826            pWInfo->bDeferredSeek = 1;
159827          }
159828
159829          /* Finish the loop through table entries that match term pOrTerm. */
159830          sqlite3WhereEnd(pSubWInfo);
159831          ExplainQueryPlanPop(pParse);
159832        }
159833        sqlite3ExprDelete(db, pDelete);
159834      }
159835    }
159836    ExplainQueryPlanPop(pParse);
159837    assert( pLevel->pWLoop==pLoop );
159838    assert( (pLoop->wsFlags & WHERE_MULTI_OR)!=0 );
159839    assert( (pLoop->wsFlags & WHERE_IN_ABLE)==0 );
159840    pLevel->u.pCoveringIdx = pCov;
159841    if( pCov ) pLevel->iIdxCur = iCovCur;
159842    if( pAndExpr ){
159843      pAndExpr->pLeft = 0;
159844      sqlite3ExprDelete(db, pAndExpr);
159845    }
159846    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
159847    sqlite3VdbeGoto(v, pLevel->addrBrk);
159848    sqlite3VdbeResolveLabel(v, iLoopBody);
159849
159850    /* Set the P2 operand of the OP_Return opcode that will end the current
159851    ** loop to point to this spot, which is the top of the next containing
159852    ** loop.  The byte-code formatter will use that P2 value as a hint to
159853    ** indent everything in between the this point and the final OP_Return.
159854    ** See tag-20220407a in vdbe.c and shell.c */
159855    assert( pLevel->op==OP_Return );
159856    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
159857
159858    if( pWInfo->nLevel>1 ){ sqlite3DbFreeNN(db, pOrTab); }
159859    if( !untestedTerms ) disableTerm(pLevel, pTerm);
159860  }else
159861#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
159862
159863  {
159864    /* Case 6:  There is no usable index.  We must do a complete
159865    **          scan of the entire table.
159866    */
159867    static const u8 aStep[] = { OP_Next, OP_Prev };
159868    static const u8 aStart[] = { OP_Rewind, OP_Last };
159869    assert( bRev==0 || bRev==1 );
159870    if( pTabItem->fg.isRecursive ){
159871      /* Tables marked isRecursive have only a single row that is stored in
159872      ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
159873      pLevel->op = OP_Noop;
159874    }else{
159875      codeCursorHint(pTabItem, pWInfo, pLevel, 0);
159876      pLevel->op = aStep[bRev];
159877      pLevel->p1 = iCur;
159878      pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
159879      VdbeCoverageIf(v, bRev==0);
159880      VdbeCoverageIf(v, bRev!=0);
159881      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
159882    }
159883  }
159884
159885#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
159886  pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
159887#endif
159888
159889  /* Insert code to test every subexpression that can be completely
159890  ** computed using the current set of tables.
159891  **
159892  ** This loop may run between one and three times, depending on the
159893  ** constraints to be generated. The value of stack variable iLoop
159894  ** determines the constraints coded by each iteration, as follows:
159895  **
159896  ** iLoop==1: Code only expressions that are entirely covered by pIdx.
159897  ** iLoop==2: Code remaining expressions that do not contain correlated
159898  **           sub-queries.
159899  ** iLoop==3: Code all remaining expressions.
159900  **
159901  ** An effort is made to skip unnecessary iterations of the loop.
159902  **
159903  ** This optimization of causing simple query restrictions to occur before
159904  ** more complex one is call the "push-down" optimization in MySQL.  Here
159905  ** in SQLite, the name is "MySQL push-down", since there is also another
159906  ** totally unrelated optimization called "WHERE-clause push-down".
159907  ** Sometimes the qualifier is omitted, resulting in an ambiguity, so beware.
159908  */
159909  iLoop = (pIdx ? 1 : 2);
159910  do{
159911    int iNext = 0;                /* Next value for iLoop */
159912    for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
159913      Expr *pE;
159914      int skipLikeAddr = 0;
159915      testcase( pTerm->wtFlags & TERM_VIRTUAL );
159916      testcase( pTerm->wtFlags & TERM_CODED );
159917      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
159918      if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
159919        testcase( pWInfo->untestedTerms==0
159920            && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
159921        pWInfo->untestedTerms = 1;
159922        continue;
159923      }
159924      pE = pTerm->pExpr;
159925      assert( pE!=0 );
159926      if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT) ){
159927        if( !ExprHasProperty(pE,EP_OuterON|EP_InnerON) ){
159928          /* Defer processing WHERE clause constraints until after outer
159929          ** join processing.  tag-20220513a */
159930          continue;
159931        }else if( (pTabItem->fg.jointype & JT_LEFT)==JT_LEFT
159932               && !ExprHasProperty(pE,EP_OuterON) ){
159933          continue;
159934        }else{
159935          Bitmask m = sqlite3WhereGetMask(&pWInfo->sMaskSet, pE->w.iJoin);
159936          if( m & pLevel->notReady ){
159937            /* An ON clause that is not ripe */
159938            continue;
159939          }
159940        }
159941      }
159942      if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
159943        iNext = 2;
159944        continue;
159945      }
159946      if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
159947        if( iNext==0 ) iNext = 3;
159948        continue;
159949      }
159950
159951      if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){
159952        /* If the TERM_LIKECOND flag is set, that means that the range search
159953        ** is sufficient to guarantee that the LIKE operator is true, so we
159954        ** can skip the call to the like(A,B) function.  But this only works
159955        ** for strings.  So do not skip the call to the function on the pass
159956        ** that compares BLOBs. */
159957#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
159958        continue;
159959#else
159960        u32 x = pLevel->iLikeRepCntr;
159961        if( x>0 ){
159962          skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1));
159963          VdbeCoverageIf(v, (x&1)==1);
159964          VdbeCoverageIf(v, (x&1)==0);
159965        }
159966#endif
159967      }
159968#ifdef WHERETRACE_ENABLED /* 0xffffffff */
159969      if( sqlite3WhereTrace ){
159970        VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
159971                         pWC->nTerm-j, pTerm, iLoop));
159972      }
159973      if( sqlite3WhereTrace & 0x4000 ){
159974        sqlite3DebugPrintf("Coding auxiliary constraint:\n");
159975        sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
159976      }
159977#endif
159978      sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
159979      if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
159980      pTerm->wtFlags |= TERM_CODED;
159981    }
159982    iLoop = iNext;
159983  }while( iLoop>0 );
159984
159985  /* Insert code to test for implied constraints based on transitivity
159986  ** of the "==" operator.
159987  **
159988  ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
159989  ** and we are coding the t1 loop and the t2 loop has not yet coded,
159990  ** then we cannot use the "t1.a=t2.b" constraint, but we can code
159991  ** the implied "t1.a=123" constraint.
159992  */
159993  for(pTerm=pWC->a, j=pWC->nBase; j>0; j--, pTerm++){
159994    Expr *pE, sEAlt;
159995    WhereTerm *pAlt;
159996    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
159997    if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
159998    if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
159999    if( pTerm->leftCursor!=iCur ) continue;
160000    if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT) ) continue;
160001    pE = pTerm->pExpr;
160002#ifdef WHERETRACE_ENABLED /* 0x4001 */
160003    if( (sqlite3WhereTrace & 0x4001)==0x4001 ){
160004      sqlite3DebugPrintf("Coding transitive constraint:\n");
160005      sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
160006    }
160007#endif
160008    assert( !ExprHasProperty(pE, EP_OuterON) );
160009    assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
160010    assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
160011    pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.x.leftColumn, notReady,
160012                    WO_EQ|WO_IN|WO_IS, 0);
160013    if( pAlt==0 ) continue;
160014    if( pAlt->wtFlags & (TERM_CODED) ) continue;
160015    if( (pAlt->eOperator & WO_IN)
160016     && ExprUseXSelect(pAlt->pExpr)
160017     && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
160018    ){
160019      continue;
160020    }
160021    testcase( pAlt->eOperator & WO_EQ );
160022    testcase( pAlt->eOperator & WO_IS );
160023    testcase( pAlt->eOperator & WO_IN );
160024    VdbeModuleComment((v, "begin transitive constraint"));
160025    sEAlt = *pAlt->pExpr;
160026    sEAlt.pLeft = pE->pLeft;
160027    sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
160028    pAlt->wtFlags |= TERM_CODED;
160029  }
160030
160031  /* For a RIGHT OUTER JOIN, record the fact that the current row has
160032  ** been matched at least once.
160033  */
160034  if( pLevel->pRJ ){
160035    Table *pTab;
160036    int nPk;
160037    int r;
160038    int jmp1 = 0;
160039    WhereRightJoin *pRJ = pLevel->pRJ;
160040
160041    /* pTab is the right-hand table of the RIGHT JOIN.  Generate code that
160042    ** will record that the current row of that table has been matched at
160043    ** least once.  This is accomplished by storing the PK for the row in
160044    ** both the iMatch index and the regBloom Bloom filter.
160045    */
160046    pTab = pWInfo->pTabList->a[pLevel->iFrom].pTab;
160047    if( HasRowid(pTab) ){
160048      r = sqlite3GetTempRange(pParse, 2);
160049      sqlite3ExprCodeGetColumnOfTable(v, pTab, pLevel->iTabCur, -1, r+1);
160050      nPk = 1;
160051    }else{
160052      int iPk;
160053      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
160054      nPk = pPk->nKeyCol;
160055      r = sqlite3GetTempRange(pParse, nPk+1);
160056      for(iPk=0; iPk<nPk; iPk++){
160057        int iCol = pPk->aiColumn[iPk];
160058        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+1+iPk);
160059      }
160060    }
160061    jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, 0, r+1, nPk);
160062    VdbeCoverage(v);
160063    VdbeComment((v, "match against %s", pTab->zName));
160064    sqlite3VdbeAddOp3(v, OP_MakeRecord, r+1, nPk, r);
160065    sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pRJ->iMatch, r, r+1, nPk);
160066    sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pRJ->regBloom, 0, r+1, nPk);
160067    sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
160068    sqlite3VdbeJumpHere(v, jmp1);
160069    sqlite3ReleaseTempRange(pParse, r, nPk+1);
160070  }
160071
160072  /* For a LEFT OUTER JOIN, generate code that will record the fact that
160073  ** at least one row of the right table has matched the left table.
160074  */
160075  if( pLevel->iLeftJoin ){
160076    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
160077    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
160078    VdbeComment((v, "record LEFT JOIN hit"));
160079    if( pLevel->pRJ==0 ){
160080      goto code_outer_join_constraints; /* WHERE clause constraints */
160081    }
160082  }
160083
160084  if( pLevel->pRJ ){
160085    /* Create a subroutine used to process all interior loops and code
160086    ** of the RIGHT JOIN.  During normal operation, the subroutine will
160087    ** be in-line with the rest of the code.  But at the end, a separate
160088    ** loop will run that invokes this subroutine for unmatched rows
160089    ** of pTab, with all tables to left begin set to NULL.
160090    */
160091    WhereRightJoin *pRJ = pLevel->pRJ;
160092    sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pRJ->regReturn);
160093    pRJ->addrSubrtn = sqlite3VdbeCurrentAddr(v);
160094    assert( pParse->withinRJSubrtn < 255 );
160095    pParse->withinRJSubrtn++;
160096
160097    /* WHERE clause constraints must be deferred until after outer join
160098    ** row elimination has completed, since WHERE clause constraints apply
160099    ** to the results of the OUTER JOIN.  The following loop generates the
160100    ** appropriate WHERE clause constraint checks.  tag-20220513a.
160101    */
160102  code_outer_join_constraints:
160103    for(pTerm=pWC->a, j=0; j<pWC->nBase; j++, pTerm++){
160104      testcase( pTerm->wtFlags & TERM_VIRTUAL );
160105      testcase( pTerm->wtFlags & TERM_CODED );
160106      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
160107      if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
160108        assert( pWInfo->untestedTerms );
160109        continue;
160110      }
160111      if( pTabItem->fg.jointype & JT_LTORJ ) continue;
160112      assert( pTerm->pExpr );
160113      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
160114      pTerm->wtFlags |= TERM_CODED;
160115    }
160116  }
160117
160118#if WHERETRACE_ENABLED /* 0x4001 */
160119  if( sqlite3WhereTrace & 0x4000 ){
160120    sqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n",
160121                       iLevel);
160122    sqlite3WhereClausePrint(pWC);
160123  }
160124  if( sqlite3WhereTrace & 0x1 ){
160125    sqlite3DebugPrintf("End Coding level %d:  notReady=%llx\n",
160126       iLevel, (u64)pLevel->notReady);
160127  }
160128#endif
160129  return pLevel->notReady;
160130}
160131
160132/*
160133** Generate the code for the loop that finds all non-matched terms
160134** for a RIGHT JOIN.
160135*/
160136SQLITE_PRIVATE SQLITE_NOINLINE void sqlite3WhereRightJoinLoop(
160137  WhereInfo *pWInfo,
160138  int iLevel,
160139  WhereLevel *pLevel
160140){
160141  Parse *pParse = pWInfo->pParse;
160142  Vdbe *v = pParse->pVdbe;
160143  WhereRightJoin *pRJ = pLevel->pRJ;
160144  Expr *pSubWhere = 0;
160145  WhereClause *pWC = &pWInfo->sWC;
160146  WhereInfo *pSubWInfo;
160147  WhereLoop *pLoop = pLevel->pWLoop;
160148  SrcItem *pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
160149  SrcList sFrom;
160150  Bitmask mAll = 0;
160151  int k;
160152
160153  ExplainQueryPlan((pParse, 1, "RIGHT-JOIN %s", pTabItem->pTab->zName));
160154  sqlite3VdbeNoJumpsOutsideSubrtn(v, pRJ->addrSubrtn, pRJ->endSubrtn,
160155                                  pRJ->regReturn);
160156  for(k=0; k<iLevel; k++){
160157    int iIdxCur;
160158    SrcItem *pRight;
160159    assert( pWInfo->a[k].pWLoop->iTab == pWInfo->a[k].iFrom );
160160    pRight = &pWInfo->pTabList->a[pWInfo->a[k].iFrom];
160161    mAll |= pWInfo->a[k].pWLoop->maskSelf;
160162    if( pRight->fg.viaCoroutine ){
160163      sqlite3VdbeAddOp3(
160164          v, OP_Null, 0, pRight->regResult,
160165          pRight->regResult + pRight->pSelect->pEList->nExpr-1
160166      );
160167    }
160168    sqlite3VdbeAddOp1(v, OP_NullRow, pWInfo->a[k].iTabCur);
160169    iIdxCur = pWInfo->a[k].iIdxCur;
160170    if( iIdxCur ){
160171      sqlite3VdbeAddOp1(v, OP_NullRow, iIdxCur);
160172    }
160173  }
160174  if( (pTabItem->fg.jointype & JT_LTORJ)==0 ){
160175    mAll |= pLoop->maskSelf;
160176    for(k=0; k<pWC->nTerm; k++){
160177      WhereTerm *pTerm = &pWC->a[k];
160178      if( (pTerm->wtFlags & (TERM_VIRTUAL|TERM_SLICE))!=0
160179       && pTerm->eOperator!=WO_ROWVAL
160180      ){
160181        break;
160182      }
160183      if( pTerm->prereqAll & ~mAll ) continue;
160184      if( ExprHasProperty(pTerm->pExpr, EP_OuterON|EP_InnerON) ) continue;
160185      pSubWhere = sqlite3ExprAnd(pParse, pSubWhere,
160186                                 sqlite3ExprDup(pParse->db, pTerm->pExpr, 0));
160187    }
160188  }
160189  sFrom.nSrc = 1;
160190  sFrom.nAlloc = 1;
160191  memcpy(&sFrom.a[0], pTabItem, sizeof(SrcItem));
160192  sFrom.a[0].fg.jointype = 0;
160193  assert( pParse->withinRJSubrtn < 100 );
160194  pParse->withinRJSubrtn++;
160195  pSubWInfo = sqlite3WhereBegin(pParse, &sFrom, pSubWhere, 0, 0, 0,
160196                                WHERE_RIGHT_JOIN, 0);
160197  if( pSubWInfo ){
160198    int iCur = pLevel->iTabCur;
160199    int r = ++pParse->nMem;
160200    int nPk;
160201    int jmp;
160202    int addrCont = sqlite3WhereContinueLabel(pSubWInfo);
160203    Table *pTab = pTabItem->pTab;
160204    if( HasRowid(pTab) ){
160205      sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, r);
160206      nPk = 1;
160207    }else{
160208      int iPk;
160209      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
160210      nPk = pPk->nKeyCol;
160211      pParse->nMem += nPk - 1;
160212      for(iPk=0; iPk<nPk; iPk++){
160213        int iCol = pPk->aiColumn[iPk];
160214        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk);
160215      }
160216    }
160217    jmp = sqlite3VdbeAddOp4Int(v, OP_Filter, pRJ->regBloom, 0, r, nPk);
160218    VdbeCoverage(v);
160219    sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, addrCont, r, nPk);
160220    VdbeCoverage(v);
160221    sqlite3VdbeJumpHere(v, jmp);
160222    sqlite3VdbeAddOp2(v, OP_Gosub, pRJ->regReturn, pRJ->addrSubrtn);
160223    sqlite3WhereEnd(pSubWInfo);
160224  }
160225  sqlite3ExprDelete(pParse->db, pSubWhere);
160226  ExplainQueryPlanPop(pParse);
160227  assert( pParse->withinRJSubrtn>0 );
160228  pParse->withinRJSubrtn--;
160229}
160230
160231/************** End of wherecode.c *******************************************/
160232/************** Begin file whereexpr.c ***************************************/
160233/*
160234** 2015-06-08
160235**
160236** The author disclaims copyright to this source code.  In place of
160237** a legal notice, here is a blessing:
160238**
160239**    May you do good and not evil.
160240**    May you find forgiveness for yourself and forgive others.
160241**    May you share freely, never taking more than you give.
160242**
160243*************************************************************************
160244** This module contains C code that generates VDBE code used to process
160245** the WHERE clause of SQL statements.
160246**
160247** This file was originally part of where.c but was split out to improve
160248** readability and editability.  This file contains utility routines for
160249** analyzing Expr objects in the WHERE clause.
160250*/
160251/* #include "sqliteInt.h" */
160252/* #include "whereInt.h" */
160253
160254/* Forward declarations */
160255static void exprAnalyze(SrcList*, WhereClause*, int);
160256
160257/*
160258** Deallocate all memory associated with a WhereOrInfo object.
160259*/
160260static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
160261  sqlite3WhereClauseClear(&p->wc);
160262  sqlite3DbFree(db, p);
160263}
160264
160265/*
160266** Deallocate all memory associated with a WhereAndInfo object.
160267*/
160268static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
160269  sqlite3WhereClauseClear(&p->wc);
160270  sqlite3DbFree(db, p);
160271}
160272
160273/*
160274** Add a single new WhereTerm entry to the WhereClause object pWC.
160275** The new WhereTerm object is constructed from Expr p and with wtFlags.
160276** The index in pWC->a[] of the new WhereTerm is returned on success.
160277** 0 is returned if the new WhereTerm could not be added due to a memory
160278** allocation error.  The memory allocation failure will be recorded in
160279** the db->mallocFailed flag so that higher-level functions can detect it.
160280**
160281** This routine will increase the size of the pWC->a[] array as necessary.
160282**
160283** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
160284** for freeing the expression p is assumed by the WhereClause object pWC.
160285** This is true even if this routine fails to allocate a new WhereTerm.
160286**
160287** WARNING:  This routine might reallocate the space used to store
160288** WhereTerms.  All pointers to WhereTerms should be invalidated after
160289** calling this routine.  Such pointers may be reinitialized by referencing
160290** the pWC->a[] array.
160291*/
160292static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
160293  WhereTerm *pTerm;
160294  int idx;
160295  testcase( wtFlags & TERM_VIRTUAL );
160296  if( pWC->nTerm>=pWC->nSlot ){
160297    WhereTerm *pOld = pWC->a;
160298    sqlite3 *db = pWC->pWInfo->pParse->db;
160299    pWC->a = sqlite3WhereMalloc(pWC->pWInfo, sizeof(pWC->a[0])*pWC->nSlot*2 );
160300    if( pWC->a==0 ){
160301      if( wtFlags & TERM_DYNAMIC ){
160302        sqlite3ExprDelete(db, p);
160303      }
160304      pWC->a = pOld;
160305      return 0;
160306    }
160307    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
160308    pWC->nSlot = pWC->nSlot*2;
160309  }
160310  pTerm = &pWC->a[idx = pWC->nTerm++];
160311  if( (wtFlags & TERM_VIRTUAL)==0 ) pWC->nBase = pWC->nTerm;
160312  if( p && ExprHasProperty(p, EP_Unlikely) ){
160313    pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
160314  }else{
160315    pTerm->truthProb = 1;
160316  }
160317  pTerm->pExpr = sqlite3ExprSkipCollateAndLikely(p);
160318  pTerm->wtFlags = wtFlags;
160319  pTerm->pWC = pWC;
160320  pTerm->iParent = -1;
160321  memset(&pTerm->eOperator, 0,
160322         sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
160323  return idx;
160324}
160325
160326/*
160327** Return TRUE if the given operator is one of the operators that is
160328** allowed for an indexable WHERE clause term.  The allowed operators are
160329** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
160330*/
160331static int allowedOp(int op){
160332  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
160333  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
160334  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
160335  assert( TK_GE==TK_EQ+4 );
160336  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
160337}
160338
160339/*
160340** Commute a comparison operator.  Expressions of the form "X op Y"
160341** are converted into "Y op X".
160342*/
160343static u16 exprCommute(Parse *pParse, Expr *pExpr){
160344  if( pExpr->pLeft->op==TK_VECTOR
160345   || pExpr->pRight->op==TK_VECTOR
160346   || sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight) !=
160347      sqlite3BinaryCompareCollSeq(pParse, pExpr->pRight, pExpr->pLeft)
160348  ){
160349    pExpr->flags ^= EP_Commuted;
160350  }
160351  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
160352  if( pExpr->op>=TK_GT ){
160353    assert( TK_LT==TK_GT+2 );
160354    assert( TK_GE==TK_LE+2 );
160355    assert( TK_GT>TK_EQ );
160356    assert( TK_GT<TK_LE );
160357    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
160358    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
160359  }
160360  return 0;
160361}
160362
160363/*
160364** Translate from TK_xx operator to WO_xx bitmask.
160365*/
160366static u16 operatorMask(int op){
160367  u16 c;
160368  assert( allowedOp(op) );
160369  if( op==TK_IN ){
160370    c = WO_IN;
160371  }else if( op==TK_ISNULL ){
160372    c = WO_ISNULL;
160373  }else if( op==TK_IS ){
160374    c = WO_IS;
160375  }else{
160376    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
160377    c = (u16)(WO_EQ<<(op-TK_EQ));
160378  }
160379  assert( op!=TK_ISNULL || c==WO_ISNULL );
160380  assert( op!=TK_IN || c==WO_IN );
160381  assert( op!=TK_EQ || c==WO_EQ );
160382  assert( op!=TK_LT || c==WO_LT );
160383  assert( op!=TK_LE || c==WO_LE );
160384  assert( op!=TK_GT || c==WO_GT );
160385  assert( op!=TK_GE || c==WO_GE );
160386  assert( op!=TK_IS || c==WO_IS );
160387  return c;
160388}
160389
160390
160391#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
160392/*
160393** Check to see if the given expression is a LIKE or GLOB operator that
160394** can be optimized using inequality constraints.  Return TRUE if it is
160395** so and false if not.
160396**
160397** In order for the operator to be optimizible, the RHS must be a string
160398** literal that does not begin with a wildcard.  The LHS must be a column
160399** that may only be NULL, a string, or a BLOB, never a number. (This means
160400** that virtual tables cannot participate in the LIKE optimization.)  The
160401** collating sequence for the column on the LHS must be appropriate for
160402** the operator.
160403*/
160404static int isLikeOrGlob(
160405  Parse *pParse,    /* Parsing and code generating context */
160406  Expr *pExpr,      /* Test this expression */
160407  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
160408  int *pisComplete, /* True if the only wildcard is % in the last character */
160409  int *pnoCase      /* True if uppercase is equivalent to lowercase */
160410){
160411  const u8 *z = 0;           /* String on RHS of LIKE operator */
160412  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
160413  ExprList *pList;           /* List of operands to the LIKE operator */
160414  u8 c;                      /* One character in z[] */
160415  int cnt;                   /* Number of non-wildcard prefix characters */
160416  u8 wc[4];                  /* Wildcard characters */
160417  sqlite3 *db = pParse->db;  /* Database connection */
160418  sqlite3_value *pVal = 0;
160419  int op;                    /* Opcode of pRight */
160420  int rc;                    /* Result code to return */
160421
160422  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){
160423    return 0;
160424  }
160425#ifdef SQLITE_EBCDIC
160426  if( *pnoCase ) return 0;
160427#endif
160428  assert( ExprUseXList(pExpr) );
160429  pList = pExpr->x.pList;
160430  pLeft = pList->a[1].pExpr;
160431
160432  pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
160433  op = pRight->op;
160434  if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
160435    Vdbe *pReprepare = pParse->pReprepare;
160436    int iCol = pRight->iColumn;
160437    pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
160438    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
160439      z = sqlite3_value_text(pVal);
160440    }
160441    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
160442    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
160443  }else if( op==TK_STRING ){
160444    assert( !ExprHasProperty(pRight, EP_IntValue) );
160445     z = (u8*)pRight->u.zToken;
160446  }
160447  if( z ){
160448
160449    /* Count the number of prefix characters prior to the first wildcard */
160450    cnt = 0;
160451    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
160452      cnt++;
160453      if( c==wc[3] && z[cnt]!=0 ) cnt++;
160454    }
160455
160456    /* The optimization is possible only if (1) the pattern does not begin
160457    ** with a wildcard and if (2) the non-wildcard prefix does not end with
160458    ** an (illegal 0xff) character, or (3) the pattern does not consist of
160459    ** a single escape character. The second condition is necessary so
160460    ** that we can increment the prefix key to find an upper bound for the
160461    ** range search. The third is because the caller assumes that the pattern
160462    ** consists of at least one character after all escapes have been
160463    ** removed.  */
160464    if( (cnt>1 || (cnt>0 && z[0]!=wc[3])) && 255!=(u8)z[cnt-1] ){
160465      Expr *pPrefix;
160466
160467      /* A "complete" match if the pattern ends with "*" or "%" */
160468      *pisComplete = c==wc[0] && z[cnt+1]==0;
160469
160470      /* Get the pattern prefix.  Remove all escapes from the prefix. */
160471      pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
160472      if( pPrefix ){
160473        int iFrom, iTo;
160474        char *zNew;
160475        assert( !ExprHasProperty(pPrefix, EP_IntValue) );
160476        zNew = pPrefix->u.zToken;
160477        zNew[cnt] = 0;
160478        for(iFrom=iTo=0; iFrom<cnt; iFrom++){
160479          if( zNew[iFrom]==wc[3] ) iFrom++;
160480          zNew[iTo++] = zNew[iFrom];
160481        }
160482        zNew[iTo] = 0;
160483        assert( iTo>0 );
160484
160485        /* If the LHS is not an ordinary column with TEXT affinity, then the
160486        ** pattern prefix boundaries (both the start and end boundaries) must
160487        ** not look like a number.  Otherwise the pattern might be treated as
160488        ** a number, which will invalidate the LIKE optimization.
160489        **
160490        ** Getting this right has been a persistent source of bugs in the
160491        ** LIKE optimization.  See, for example:
160492        **    2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1
160493        **    2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28
160494        **    2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07
160495        **    2019-06-14 https://sqlite.org/src/info/ce8717f0885af975
160496        **    2019-09-03 https://sqlite.org/src/info/0f0428096f17252a
160497        */
160498        if( pLeft->op!=TK_COLUMN
160499         || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
160500         || (ALWAYS( ExprUseYTab(pLeft) )
160501             && ALWAYS(pLeft->y.pTab)
160502             && IsVirtual(pLeft->y.pTab))  /* Might be numeric */
160503        ){
160504          int isNum;
160505          double rDummy;
160506          isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
160507          if( isNum<=0 ){
160508            if( iTo==1 && zNew[0]=='-' ){
160509              isNum = +1;
160510            }else{
160511              zNew[iTo-1]++;
160512              isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
160513              zNew[iTo-1]--;
160514            }
160515          }
160516          if( isNum>0 ){
160517            sqlite3ExprDelete(db, pPrefix);
160518            sqlite3ValueFree(pVal);
160519            return 0;
160520          }
160521        }
160522      }
160523      *ppPrefix = pPrefix;
160524
160525      /* If the RHS pattern is a bound parameter, make arrangements to
160526      ** reprepare the statement when that parameter is rebound */
160527      if( op==TK_VARIABLE ){
160528        Vdbe *v = pParse->pVdbe;
160529        sqlite3VdbeSetVarmask(v, pRight->iColumn);
160530        assert( !ExprHasProperty(pRight, EP_IntValue) );
160531        if( *pisComplete && pRight->u.zToken[1] ){
160532          /* If the rhs of the LIKE expression is a variable, and the current
160533          ** value of the variable means there is no need to invoke the LIKE
160534          ** function, then no OP_Variable will be added to the program.
160535          ** This causes problems for the sqlite3_bind_parameter_name()
160536          ** API. To work around them, add a dummy OP_Variable here.
160537          */
160538          int r1 = sqlite3GetTempReg(pParse);
160539          sqlite3ExprCodeTarget(pParse, pRight, r1);
160540          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
160541          sqlite3ReleaseTempReg(pParse, r1);
160542        }
160543      }
160544    }else{
160545      z = 0;
160546    }
160547  }
160548
160549  rc = (z!=0);
160550  sqlite3ValueFree(pVal);
160551  return rc;
160552}
160553#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
160554
160555
160556#ifndef SQLITE_OMIT_VIRTUALTABLE
160557/*
160558** Check to see if the pExpr expression is a form that needs to be passed
160559** to the xBestIndex method of virtual tables.  Forms of interest include:
160560**
160561**          Expression                   Virtual Table Operator
160562**          -----------------------      ---------------------------------
160563**      1.  column MATCH expr            SQLITE_INDEX_CONSTRAINT_MATCH
160564**      2.  column GLOB expr             SQLITE_INDEX_CONSTRAINT_GLOB
160565**      3.  column LIKE expr             SQLITE_INDEX_CONSTRAINT_LIKE
160566**      4.  column REGEXP expr           SQLITE_INDEX_CONSTRAINT_REGEXP
160567**      5.  column != expr               SQLITE_INDEX_CONSTRAINT_NE
160568**      6.  expr != column               SQLITE_INDEX_CONSTRAINT_NE
160569**      7.  column IS NOT expr           SQLITE_INDEX_CONSTRAINT_ISNOT
160570**      8.  expr IS NOT column           SQLITE_INDEX_CONSTRAINT_ISNOT
160571**      9.  column IS NOT NULL           SQLITE_INDEX_CONSTRAINT_ISNOTNULL
160572**
160573** In every case, "column" must be a column of a virtual table.  If there
160574** is a match, set *ppLeft to the "column" expression, set *ppRight to the
160575** "expr" expression (even though in forms (6) and (8) the column is on the
160576** right and the expression is on the left).  Also set *peOp2 to the
160577** appropriate virtual table operator.  The return value is 1 or 2 if there
160578** is a match.  The usual return is 1, but if the RHS is also a column
160579** of virtual table in forms (5) or (7) then return 2.
160580**
160581** If the expression matches none of the patterns above, return 0.
160582*/
160583static int isAuxiliaryVtabOperator(
160584  sqlite3 *db,                    /* Parsing context */
160585  Expr *pExpr,                    /* Test this expression */
160586  unsigned char *peOp2,           /* OUT: 0 for MATCH, or else an op2 value */
160587  Expr **ppLeft,                  /* Column expression to left of MATCH/op2 */
160588  Expr **ppRight                  /* Expression to left of MATCH/op2 */
160589){
160590  if( pExpr->op==TK_FUNCTION ){
160591    static const struct Op2 {
160592      const char *zOp;
160593      unsigned char eOp2;
160594    } aOp[] = {
160595      { "match",  SQLITE_INDEX_CONSTRAINT_MATCH },
160596      { "glob",   SQLITE_INDEX_CONSTRAINT_GLOB },
160597      { "like",   SQLITE_INDEX_CONSTRAINT_LIKE },
160598      { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
160599    };
160600    ExprList *pList;
160601    Expr *pCol;                     /* Column reference */
160602    int i;
160603
160604    assert( ExprUseXList(pExpr) );
160605    pList = pExpr->x.pList;
160606    if( pList==0 || pList->nExpr!=2 ){
160607      return 0;
160608    }
160609
160610    /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
160611    ** virtual table on their second argument, which is the same as
160612    ** the left-hand side operand in their in-fix form.
160613    **
160614    **       vtab_column MATCH expression
160615    **       MATCH(expression,vtab_column)
160616    */
160617    pCol = pList->a[1].pExpr;
160618    assert( pCol->op!=TK_COLUMN || (ExprUseYTab(pCol) && pCol->y.pTab!=0) );
160619    if( ExprIsVtab(pCol) ){
160620      for(i=0; i<ArraySize(aOp); i++){
160621        assert( !ExprHasProperty(pExpr, EP_IntValue) );
160622        if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
160623          *peOp2 = aOp[i].eOp2;
160624          *ppRight = pList->a[0].pExpr;
160625          *ppLeft = pCol;
160626          return 1;
160627        }
160628      }
160629    }
160630
160631    /* We can also match against the first column of overloaded
160632    ** functions where xFindFunction returns a value of at least
160633    ** SQLITE_INDEX_CONSTRAINT_FUNCTION.
160634    **
160635    **      OVERLOADED(vtab_column,expression)
160636    **
160637    ** Historically, xFindFunction expected to see lower-case function
160638    ** names.  But for this use case, xFindFunction is expected to deal
160639    ** with function names in an arbitrary case.
160640    */
160641    pCol = pList->a[0].pExpr;
160642    assert( pCol->op!=TK_COLUMN || ExprUseYTab(pCol) );
160643    assert( pCol->op!=TK_COLUMN || (ExprUseYTab(pCol) && pCol->y.pTab!=0) );
160644    if( ExprIsVtab(pCol) ){
160645      sqlite3_vtab *pVtab;
160646      sqlite3_module *pMod;
160647      void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
160648      void *pNotUsed;
160649      pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;
160650      assert( pVtab!=0 );
160651      assert( pVtab->pModule!=0 );
160652      assert( !ExprHasProperty(pExpr, EP_IntValue) );
160653      pMod = (sqlite3_module *)pVtab->pModule;
160654      if( pMod->xFindFunction!=0 ){
160655        i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
160656        if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
160657          *peOp2 = i;
160658          *ppRight = pList->a[1].pExpr;
160659          *ppLeft = pCol;
160660          return 1;
160661        }
160662      }
160663    }
160664  }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
160665    int res = 0;
160666    Expr *pLeft = pExpr->pLeft;
160667    Expr *pRight = pExpr->pRight;
160668    assert( pLeft->op!=TK_COLUMN || (ExprUseYTab(pLeft) && pLeft->y.pTab!=0) );
160669    if( ExprIsVtab(pLeft) ){
160670      res++;
160671    }
160672    assert( pRight==0 || pRight->op!=TK_COLUMN
160673            || (ExprUseYTab(pRight) && pRight->y.pTab!=0) );
160674    if( pRight && ExprIsVtab(pRight) ){
160675      res++;
160676      SWAP(Expr*, pLeft, pRight);
160677    }
160678    *ppLeft = pLeft;
160679    *ppRight = pRight;
160680    if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
160681    if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
160682    if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
160683    return res;
160684  }
160685  return 0;
160686}
160687#endif /* SQLITE_OMIT_VIRTUALTABLE */
160688
160689/*
160690** If the pBase expression originated in the ON or USING clause of
160691** a join, then transfer the appropriate markings over to derived.
160692*/
160693static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
160694  if( pDerived && ExprHasProperty(pBase, EP_OuterON|EP_InnerON) ){
160695    pDerived->flags |= pBase->flags & (EP_OuterON|EP_InnerON);
160696    pDerived->w.iJoin = pBase->w.iJoin;
160697  }
160698}
160699
160700/*
160701** Mark term iChild as being a child of term iParent
160702*/
160703static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
160704  pWC->a[iChild].iParent = iParent;
160705  pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
160706  pWC->a[iParent].nChild++;
160707}
160708
160709/*
160710** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
160711** a conjunction, then return just pTerm when N==0.  If N is exceeds
160712** the number of available subterms, return NULL.
160713*/
160714static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
160715  if( pTerm->eOperator!=WO_AND ){
160716    return N==0 ? pTerm : 0;
160717  }
160718  if( N<pTerm->u.pAndInfo->wc.nTerm ){
160719    return &pTerm->u.pAndInfo->wc.a[N];
160720  }
160721  return 0;
160722}
160723
160724/*
160725** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
160726** two subterms are in disjunction - they are OR-ed together.
160727**
160728** If these two terms are both of the form:  "A op B" with the same
160729** A and B values but different operators and if the operators are
160730** compatible (if one is = and the other is <, for example) then
160731** add a new virtual AND term to pWC that is the combination of the
160732** two.
160733**
160734** Some examples:
160735**
160736**    x<y OR x=y    -->     x<=y
160737**    x=y OR x=y    -->     x=y
160738**    x<=y OR x<y   -->     x<=y
160739**
160740** The following is NOT generated:
160741**
160742**    x<y OR x>y    -->     x!=y
160743*/
160744static void whereCombineDisjuncts(
160745  SrcList *pSrc,         /* the FROM clause */
160746  WhereClause *pWC,      /* The complete WHERE clause */
160747  WhereTerm *pOne,       /* First disjunct */
160748  WhereTerm *pTwo        /* Second disjunct */
160749){
160750  u16 eOp = pOne->eOperator | pTwo->eOperator;
160751  sqlite3 *db;           /* Database connection (for malloc) */
160752  Expr *pNew;            /* New virtual expression */
160753  int op;                /* Operator for the combined expression */
160754  int idxNew;            /* Index in pWC of the next virtual term */
160755
160756  if( (pOne->wtFlags | pTwo->wtFlags) & TERM_VNULL ) return;
160757  if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
160758  if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
160759  if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
160760   && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
160761  assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
160762  assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
160763  if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
160764  if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
160765  /* If we reach this point, it means the two subterms can be combined */
160766  if( (eOp & (eOp-1))!=0 ){
160767    if( eOp & (WO_LT|WO_LE) ){
160768      eOp = WO_LE;
160769    }else{
160770      assert( eOp & (WO_GT|WO_GE) );
160771      eOp = WO_GE;
160772    }
160773  }
160774  db = pWC->pWInfo->pParse->db;
160775  pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
160776  if( pNew==0 ) return;
160777  for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
160778  pNew->op = op;
160779  idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
160780  exprAnalyze(pSrc, pWC, idxNew);
160781}
160782
160783#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
160784/*
160785** Analyze a term that consists of two or more OR-connected
160786** subterms.  So in:
160787**
160788**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
160789**                          ^^^^^^^^^^^^^^^^^^^^
160790**
160791** This routine analyzes terms such as the middle term in the above example.
160792** A WhereOrTerm object is computed and attached to the term under
160793** analysis, regardless of the outcome of the analysis.  Hence:
160794**
160795**     WhereTerm.wtFlags   |=  TERM_ORINFO
160796**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
160797**
160798** The term being analyzed must have two or more of OR-connected subterms.
160799** A single subterm might be a set of AND-connected sub-subterms.
160800** Examples of terms under analysis:
160801**
160802**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
160803**     (B)     x=expr1 OR expr2=x OR x=expr3
160804**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
160805**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
160806**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
160807**     (F)     x>A OR (x=A AND y>=B)
160808**
160809** CASE 1:
160810**
160811** If all subterms are of the form T.C=expr for some single column of C and
160812** a single table T (as shown in example B above) then create a new virtual
160813** term that is an equivalent IN expression.  In other words, if the term
160814** being analyzed is:
160815**
160816**      x = expr1  OR  expr2 = x  OR  x = expr3
160817**
160818** then create a new virtual term like this:
160819**
160820**      x IN (expr1,expr2,expr3)
160821**
160822** CASE 2:
160823**
160824** If there are exactly two disjuncts and one side has x>A and the other side
160825** has x=A (for the same x and A) then add a new virtual conjunct term to the
160826** WHERE clause of the form "x>=A".  Example:
160827**
160828**      x>A OR (x=A AND y>B)    adds:    x>=A
160829**
160830** The added conjunct can sometimes be helpful in query planning.
160831**
160832** CASE 3:
160833**
160834** If all subterms are indexable by a single table T, then set
160835**
160836**     WhereTerm.eOperator              =  WO_OR
160837**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
160838**
160839** A subterm is "indexable" if it is of the form
160840** "T.C <op> <expr>" where C is any column of table T and
160841** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
160842** A subterm is also indexable if it is an AND of two or more
160843** subsubterms at least one of which is indexable.  Indexable AND
160844** subterms have their eOperator set to WO_AND and they have
160845** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
160846**
160847** From another point of view, "indexable" means that the subterm could
160848** potentially be used with an index if an appropriate index exists.
160849** This analysis does not consider whether or not the index exists; that
160850** is decided elsewhere.  This analysis only looks at whether subterms
160851** appropriate for indexing exist.
160852**
160853** All examples A through E above satisfy case 3.  But if a term
160854** also satisfies case 1 (such as B) we know that the optimizer will
160855** always prefer case 1, so in that case we pretend that case 3 is not
160856** satisfied.
160857**
160858** It might be the case that multiple tables are indexable.  For example,
160859** (E) above is indexable on tables P, Q, and R.
160860**
160861** Terms that satisfy case 3 are candidates for lookup by using
160862** separate indices to find rowids for each subterm and composing
160863** the union of all rowids using a RowSet object.  This is similar
160864** to "bitmap indices" in other database engines.
160865**
160866** OTHERWISE:
160867**
160868** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
160869** zero.  This term is not useful for search.
160870*/
160871static void exprAnalyzeOrTerm(
160872  SrcList *pSrc,            /* the FROM clause */
160873  WhereClause *pWC,         /* the complete WHERE clause */
160874  int idxTerm               /* Index of the OR-term to be analyzed */
160875){
160876  WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
160877  Parse *pParse = pWInfo->pParse;         /* Parser context */
160878  sqlite3 *db = pParse->db;               /* Database connection */
160879  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
160880  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
160881  int i;                                  /* Loop counters */
160882  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
160883  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
160884  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
160885  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
160886  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
160887
160888  /*
160889  ** Break the OR clause into its separate subterms.  The subterms are
160890  ** stored in a WhereClause structure containing within the WhereOrInfo
160891  ** object that is attached to the original OR clause term.
160892  */
160893  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
160894  assert( pExpr->op==TK_OR );
160895  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
160896  if( pOrInfo==0 ) return;
160897  pTerm->wtFlags |= TERM_ORINFO;
160898  pOrWc = &pOrInfo->wc;
160899  memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
160900  sqlite3WhereClauseInit(pOrWc, pWInfo);
160901  sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
160902  sqlite3WhereExprAnalyze(pSrc, pOrWc);
160903  if( db->mallocFailed ) return;
160904  assert( pOrWc->nTerm>=2 );
160905
160906  /*
160907  ** Compute the set of tables that might satisfy cases 1 or 3.
160908  */
160909  indexable = ~(Bitmask)0;
160910  chngToIN = ~(Bitmask)0;
160911  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
160912    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
160913      WhereAndInfo *pAndInfo;
160914      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
160915      chngToIN = 0;
160916      pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
160917      if( pAndInfo ){
160918        WhereClause *pAndWC;
160919        WhereTerm *pAndTerm;
160920        int j;
160921        Bitmask b = 0;
160922        pOrTerm->u.pAndInfo = pAndInfo;
160923        pOrTerm->wtFlags |= TERM_ANDINFO;
160924        pOrTerm->eOperator = WO_AND;
160925        pOrTerm->leftCursor = -1;
160926        pAndWC = &pAndInfo->wc;
160927        memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
160928        sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
160929        sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
160930        sqlite3WhereExprAnalyze(pSrc, pAndWC);
160931        pAndWC->pOuter = pWC;
160932        if( !db->mallocFailed ){
160933          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
160934            assert( pAndTerm->pExpr );
160935            if( allowedOp(pAndTerm->pExpr->op)
160936             || pAndTerm->eOperator==WO_AUX
160937            ){
160938              b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
160939            }
160940          }
160941        }
160942        indexable &= b;
160943      }
160944    }else if( pOrTerm->wtFlags & TERM_COPIED ){
160945      /* Skip this term for now.  We revisit it when we process the
160946      ** corresponding TERM_VIRTUAL term */
160947    }else{
160948      Bitmask b;
160949      b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
160950      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
160951        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
160952        b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
160953      }
160954      indexable &= b;
160955      if( (pOrTerm->eOperator & WO_EQ)==0 ){
160956        chngToIN = 0;
160957      }else{
160958        chngToIN &= b;
160959      }
160960    }
160961  }
160962
160963  /*
160964  ** Record the set of tables that satisfy case 3.  The set might be
160965  ** empty.
160966  */
160967  pOrInfo->indexable = indexable;
160968  pTerm->eOperator = WO_OR;
160969  pTerm->leftCursor = -1;
160970  if( indexable ){
160971    pWC->hasOr = 1;
160972  }
160973
160974  /* For a two-way OR, attempt to implementation case 2.
160975  */
160976  if( indexable && pOrWc->nTerm==2 ){
160977    int iOne = 0;
160978    WhereTerm *pOne;
160979    while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
160980      int iTwo = 0;
160981      WhereTerm *pTwo;
160982      while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
160983        whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
160984      }
160985    }
160986  }
160987
160988  /*
160989  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
160990  ** we have to do some additional checking to see if case 1 really
160991  ** is satisfied.
160992  **
160993  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
160994  ** that there is no possibility of transforming the OR clause into an
160995  ** IN operator because one or more terms in the OR clause contain
160996  ** something other than == on a column in the single table.  The 1-bit
160997  ** case means that every term of the OR clause is of the form
160998  ** "table.column=expr" for some single table.  The one bit that is set
160999  ** will correspond to the common table.  We still need to check to make
161000  ** sure the same column is used on all terms.  The 2-bit case is when
161001  ** the all terms are of the form "table1.column=table2.column".  It
161002  ** might be possible to form an IN operator with either table1.column
161003  ** or table2.column as the LHS if either is common to every term of
161004  ** the OR clause.
161005  **
161006  ** Note that terms of the form "table.column1=table.column2" (the
161007  ** same table on both sizes of the ==) cannot be optimized.
161008  */
161009  if( chngToIN ){
161010    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
161011    int iColumn = -1;         /* Column index on lhs of IN operator */
161012    int iCursor = -1;         /* Table cursor common to all terms */
161013    int j = 0;                /* Loop counter */
161014
161015    /* Search for a table and column that appears on one side or the
161016    ** other of the == operator in every subterm.  That table and column
161017    ** will be recorded in iCursor and iColumn.  There might not be any
161018    ** such table and column.  Set okToChngToIN if an appropriate table
161019    ** and column is found but leave okToChngToIN false if not found.
161020    */
161021    for(j=0; j<2 && !okToChngToIN; j++){
161022      Expr *pLeft = 0;
161023      pOrTerm = pOrWc->a;
161024      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
161025        assert( pOrTerm->eOperator & WO_EQ );
161026        pOrTerm->wtFlags &= ~TERM_OK;
161027        if( pOrTerm->leftCursor==iCursor ){
161028          /* This is the 2-bit case and we are on the second iteration and
161029          ** current term is from the first iteration.  So skip this term. */
161030          assert( j==1 );
161031          continue;
161032        }
161033        if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
161034                                            pOrTerm->leftCursor))==0 ){
161035          /* This term must be of the form t1.a==t2.b where t2 is in the
161036          ** chngToIN set but t1 is not.  This term will be either preceded
161037          ** or followed by an inverted copy (t2.b==t1.a).  Skip this term
161038          ** and use its inversion. */
161039          testcase( pOrTerm->wtFlags & TERM_COPIED );
161040          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
161041          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
161042          continue;
161043        }
161044        assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
161045        iColumn = pOrTerm->u.x.leftColumn;
161046        iCursor = pOrTerm->leftCursor;
161047        pLeft = pOrTerm->pExpr->pLeft;
161048        break;
161049      }
161050      if( i<0 ){
161051        /* No candidate table+column was found.  This can only occur
161052        ** on the second iteration */
161053        assert( j==1 );
161054        assert( IsPowerOfTwo(chngToIN) );
161055        assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
161056        break;
161057      }
161058      testcase( j==1 );
161059
161060      /* We have found a candidate table and column.  Check to see if that
161061      ** table and column is common to every term in the OR clause */
161062      okToChngToIN = 1;
161063      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
161064        assert( pOrTerm->eOperator & WO_EQ );
161065        assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
161066        if( pOrTerm->leftCursor!=iCursor ){
161067          pOrTerm->wtFlags &= ~TERM_OK;
161068        }else if( pOrTerm->u.x.leftColumn!=iColumn || (iColumn==XN_EXPR
161069               && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1)
161070        )){
161071          okToChngToIN = 0;
161072        }else{
161073          int affLeft, affRight;
161074          /* If the right-hand side is also a column, then the affinities
161075          ** of both right and left sides must be such that no type
161076          ** conversions are required on the right.  (Ticket #2249)
161077          */
161078          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
161079          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
161080          if( affRight!=0 && affRight!=affLeft ){
161081            okToChngToIN = 0;
161082          }else{
161083            pOrTerm->wtFlags |= TERM_OK;
161084          }
161085        }
161086      }
161087    }
161088
161089    /* At this point, okToChngToIN is true if original pTerm satisfies
161090    ** case 1.  In that case, construct a new virtual term that is
161091    ** pTerm converted into an IN operator.
161092    */
161093    if( okToChngToIN ){
161094      Expr *pDup;            /* A transient duplicate expression */
161095      ExprList *pList = 0;   /* The RHS of the IN operator */
161096      Expr *pLeft = 0;       /* The LHS of the IN operator */
161097      Expr *pNew;            /* The complete IN operator */
161098
161099      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
161100        if( (pOrTerm->wtFlags & TERM_OK)==0 ) continue;
161101        assert( pOrTerm->eOperator & WO_EQ );
161102        assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
161103        assert( pOrTerm->leftCursor==iCursor );
161104        assert( pOrTerm->u.x.leftColumn==iColumn );
161105        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
161106        pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
161107        pLeft = pOrTerm->pExpr->pLeft;
161108      }
161109      assert( pLeft!=0 );
161110      pDup = sqlite3ExprDup(db, pLeft, 0);
161111      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
161112      if( pNew ){
161113        int idxNew;
161114        transferJoinMarkings(pNew, pExpr);
161115        assert( ExprUseXList(pNew) );
161116        pNew->x.pList = pList;
161117        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
161118        testcase( idxNew==0 );
161119        exprAnalyze(pSrc, pWC, idxNew);
161120        /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where reused */
161121        markTermAsChild(pWC, idxNew, idxTerm);
161122      }else{
161123        sqlite3ExprListDelete(db, pList);
161124      }
161125    }
161126  }
161127}
161128#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
161129
161130/*
161131** We already know that pExpr is a binary operator where both operands are
161132** column references.  This routine checks to see if pExpr is an equivalence
161133** relation:
161134**   1.  The SQLITE_Transitive optimization must be enabled
161135**   2.  Must be either an == or an IS operator
161136**   3.  Not originating in the ON clause of an OUTER JOIN
161137**   4.  The affinities of A and B must be compatible
161138**   5a. Both operands use the same collating sequence OR
161139**   5b. The overall collating sequence is BINARY
161140** If this routine returns TRUE, that means that the RHS can be substituted
161141** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
161142** This is an optimization.  No harm comes from returning 0.  But if 1 is
161143** returned when it should not be, then incorrect answers might result.
161144*/
161145static int termIsEquivalence(Parse *pParse, Expr *pExpr){
161146  char aff1, aff2;
161147  CollSeq *pColl;
161148  if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
161149  if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
161150  if( ExprHasProperty(pExpr, EP_OuterON) ) return 0;
161151  aff1 = sqlite3ExprAffinity(pExpr->pLeft);
161152  aff2 = sqlite3ExprAffinity(pExpr->pRight);
161153  if( aff1!=aff2
161154   && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
161155  ){
161156    return 0;
161157  }
161158  pColl = sqlite3ExprCompareCollSeq(pParse, pExpr);
161159  if( sqlite3IsBinary(pColl) ) return 1;
161160  return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
161161}
161162
161163/*
161164** Recursively walk the expressions of a SELECT statement and generate
161165** a bitmask indicating which tables are used in that expression
161166** tree.
161167*/
161168static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
161169  Bitmask mask = 0;
161170  while( pS ){
161171    SrcList *pSrc = pS->pSrc;
161172    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
161173    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
161174    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
161175    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
161176    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
161177    if( ALWAYS(pSrc!=0) ){
161178      int i;
161179      for(i=0; i<pSrc->nSrc; i++){
161180        mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
161181        if( pSrc->a[i].fg.isUsing==0 ){
161182          mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].u3.pOn);
161183        }
161184        if( pSrc->a[i].fg.isTabFunc ){
161185          mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
161186        }
161187      }
161188    }
161189    pS = pS->pPrior;
161190  }
161191  return mask;
161192}
161193
161194/*
161195** Expression pExpr is one operand of a comparison operator that might
161196** be useful for indexing.  This routine checks to see if pExpr appears
161197** in any index.  Return TRUE (1) if pExpr is an indexed term and return
161198** FALSE (0) if not.  If TRUE is returned, also set aiCurCol[0] to the cursor
161199** number of the table that is indexed and aiCurCol[1] to the column number
161200** of the column that is indexed, or XN_EXPR (-2) if an expression is being
161201** indexed.
161202**
161203** If pExpr is a TK_COLUMN column reference, then this routine always returns
161204** true even if that particular column is not indexed, because the column
161205** might be added to an automatic index later.
161206*/
161207static SQLITE_NOINLINE int exprMightBeIndexed2(
161208  SrcList *pFrom,        /* The FROM clause */
161209  int *aiCurCol,         /* Write the referenced table cursor and column here */
161210  Expr *pExpr,           /* An operand of a comparison operator */
161211  int j                  /* Start looking with the j-th pFrom entry */
161212){
161213  Index *pIdx;
161214  int i;
161215  int iCur;
161216  do{
161217    iCur = pFrom->a[j].iCursor;
161218    for(pIdx=pFrom->a[j].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
161219      if( pIdx->aColExpr==0 ) continue;
161220      for(i=0; i<pIdx->nKeyCol; i++){
161221        if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
161222        assert( pIdx->bHasExpr );
161223        if( sqlite3ExprCompareSkip(pExpr,pIdx->aColExpr->a[i].pExpr,iCur)==0
161224         && !sqlite3ExprIsConstant(0,pIdx->aColExpr->a[i].pExpr)
161225        ){
161226          aiCurCol[0] = iCur;
161227          aiCurCol[1] = XN_EXPR;
161228          return 1;
161229        }
161230      }
161231    }
161232  }while( ++j < pFrom->nSrc );
161233  return 0;
161234}
161235static int exprMightBeIndexed(
161236  SrcList *pFrom,        /* The FROM clause */
161237  int *aiCurCol,         /* Write the referenced table cursor & column here */
161238  Expr *pExpr,           /* An operand of a comparison operator */
161239  int op                 /* The specific comparison operator */
161240){
161241  int i;
161242
161243  /* If this expression is a vector to the left or right of a
161244  ** inequality constraint (>, <, >= or <=), perform the processing
161245  ** on the first element of the vector.  */
161246  assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
161247  assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
161248  assert( op<=TK_GE );
161249  if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
161250    assert( ExprUseXList(pExpr) );
161251    pExpr = pExpr->x.pList->a[0].pExpr;
161252  }
161253
161254  if( pExpr->op==TK_COLUMN ){
161255    aiCurCol[0] = pExpr->iTable;
161256    aiCurCol[1] = pExpr->iColumn;
161257    return 1;
161258  }
161259
161260  for(i=0; i<pFrom->nSrc; i++){
161261    Index *pIdx;
161262    for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
161263      if( pIdx->aColExpr ){
161264        return exprMightBeIndexed2(pFrom,aiCurCol,pExpr,i);
161265      }
161266    }
161267  }
161268  return 0;
161269}
161270
161271
161272/*
161273** The input to this routine is an WhereTerm structure with only the
161274** "pExpr" field filled in.  The job of this routine is to analyze the
161275** subexpression and populate all the other fields of the WhereTerm
161276** structure.
161277**
161278** If the expression is of the form "<expr> <op> X" it gets commuted
161279** to the standard form of "X <op> <expr>".
161280**
161281** If the expression is of the form "X <op> Y" where both X and Y are
161282** columns, then the original expression is unchanged and a new virtual
161283** term of the form "Y <op> X" is added to the WHERE clause and
161284** analyzed separately.  The original term is marked with TERM_COPIED
161285** and the new term is marked with TERM_DYNAMIC (because it's pExpr
161286** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
161287** is a commuted copy of a prior term.)  The original term has nChild=1
161288** and the copy has idxParent set to the index of the original term.
161289*/
161290static void exprAnalyze(
161291  SrcList *pSrc,            /* the FROM clause */
161292  WhereClause *pWC,         /* the WHERE clause */
161293  int idxTerm               /* Index of the term to be analyzed */
161294){
161295  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
161296  WhereTerm *pTerm;                /* The term to be analyzed */
161297  WhereMaskSet *pMaskSet;          /* Set of table index masks */
161298  Expr *pExpr;                     /* The expression to be analyzed */
161299  Bitmask prereqLeft;              /* Prerequisites of the pExpr->pLeft */
161300  Bitmask prereqAll;               /* Prerequisites of pExpr */
161301  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
161302  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
161303  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
161304  int noCase = 0;                  /* uppercase equivalent to lowercase */
161305  int op;                          /* Top-level operator.  pExpr->op */
161306  Parse *pParse = pWInfo->pParse;  /* Parsing context */
161307  sqlite3 *db = pParse->db;        /* Database connection */
161308  unsigned char eOp2 = 0;          /* op2 value for LIKE/REGEXP/GLOB */
161309  int nLeft;                       /* Number of elements on left side vector */
161310
161311  if( db->mallocFailed ){
161312    return;
161313  }
161314  assert( pWC->nTerm > idxTerm );
161315  pTerm = &pWC->a[idxTerm];
161316  pMaskSet = &pWInfo->sMaskSet;
161317  pExpr = pTerm->pExpr;
161318  assert( pExpr!=0 ); /* Because malloc() has not failed */
161319  assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
161320  pMaskSet->bVarSelect = 0;
161321  prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
161322  op = pExpr->op;
161323  if( op==TK_IN ){
161324    assert( pExpr->pRight==0 );
161325    if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
161326    if( ExprUseXSelect(pExpr) ){
161327      pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
161328    }else{
161329      pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
161330    }
161331    prereqAll = prereqLeft | pTerm->prereqRight;
161332  }else{
161333    pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
161334    if( pExpr->pLeft==0
161335     || ExprHasProperty(pExpr, EP_xIsSelect|EP_IfNullRow)
161336     || pExpr->x.pList!=0
161337    ){
161338      prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);
161339    }else{
161340      prereqAll = prereqLeft | pTerm->prereqRight;
161341    }
161342  }
161343  if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
161344
161345#ifdef SQLITE_DEBUG
161346  if( prereqAll!=sqlite3WhereExprUsageNN(pMaskSet, pExpr) ){
161347    printf("\n*** Incorrect prereqAll computed for:\n");
161348    sqlite3TreeViewExpr(0,pExpr,0);
161349    assert( 0 );
161350  }
161351#endif
161352
161353  if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON) ){
161354    Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->w.iJoin);
161355    if( ExprHasProperty(pExpr, EP_OuterON) ){
161356      prereqAll |= x;
161357      extraRight = x-1;  /* ON clause terms may not be used with an index
161358                         ** on left table of a LEFT JOIN.  Ticket #3015 */
161359      if( (prereqAll>>1)>=x ){
161360        sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
161361        return;
161362      }
161363    }else if( (prereqAll>>1)>=x ){
161364      /* The ON clause of an INNER JOIN references a table to its right.
161365      ** Most other SQL database engines raise an error.  But SQLite versions
161366      ** 3.0 through 3.38 just put the ON clause constraint into the WHERE
161367      ** clause and carried on.   Beginning with 3.39, raise an error only
161368      ** if there is a RIGHT or FULL JOIN in the query.  This makes SQLite
161369      ** more like other systems, and also preserves legacy. */
161370      if( ALWAYS(pSrc->nSrc>0) && (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
161371        sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
161372        return;
161373      }
161374      ExprClearProperty(pExpr, EP_InnerON);
161375    }
161376  }
161377  pTerm->prereqAll = prereqAll;
161378  pTerm->leftCursor = -1;
161379  pTerm->iParent = -1;
161380  pTerm->eOperator = 0;
161381  if( allowedOp(op) ){
161382    int aiCurCol[2];
161383    Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
161384    Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
161385    u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
161386
161387    if( pTerm->u.x.iField>0 ){
161388      assert( op==TK_IN );
161389      assert( pLeft->op==TK_VECTOR );
161390      assert( ExprUseXList(pLeft) );
161391      pLeft = pLeft->x.pList->a[pTerm->u.x.iField-1].pExpr;
161392    }
161393
161394    if( exprMightBeIndexed(pSrc, aiCurCol, pLeft, op) ){
161395      pTerm->leftCursor = aiCurCol[0];
161396      assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
161397      pTerm->u.x.leftColumn = aiCurCol[1];
161398      pTerm->eOperator = operatorMask(op) & opMask;
161399    }
161400    if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
161401    if( pRight
161402     && exprMightBeIndexed(pSrc, aiCurCol, pRight, op)
161403     && !ExprHasProperty(pRight, EP_FixedCol)
161404    ){
161405      WhereTerm *pNew;
161406      Expr *pDup;
161407      u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
161408      assert( pTerm->u.x.iField==0 );
161409      if( pTerm->leftCursor>=0 ){
161410        int idxNew;
161411        pDup = sqlite3ExprDup(db, pExpr, 0);
161412        if( db->mallocFailed ){
161413          sqlite3ExprDelete(db, pDup);
161414          return;
161415        }
161416        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
161417        if( idxNew==0 ) return;
161418        pNew = &pWC->a[idxNew];
161419        markTermAsChild(pWC, idxNew, idxTerm);
161420        if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
161421        pTerm = &pWC->a[idxTerm];
161422        pTerm->wtFlags |= TERM_COPIED;
161423
161424        if( termIsEquivalence(pParse, pDup) ){
161425          pTerm->eOperator |= WO_EQUIV;
161426          eExtraOp = WO_EQUIV;
161427        }
161428      }else{
161429        pDup = pExpr;
161430        pNew = pTerm;
161431      }
161432      pNew->wtFlags |= exprCommute(pParse, pDup);
161433      pNew->leftCursor = aiCurCol[0];
161434      assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
161435      pNew->u.x.leftColumn = aiCurCol[1];
161436      testcase( (prereqLeft | extraRight) != prereqLeft );
161437      pNew->prereqRight = prereqLeft | extraRight;
161438      pNew->prereqAll = prereqAll;
161439      pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
161440    }else
161441    if( op==TK_ISNULL
161442     && !ExprHasProperty(pExpr,EP_OuterON)
161443     && 0==sqlite3ExprCanBeNull(pLeft)
161444    ){
161445      assert( !ExprHasProperty(pExpr, EP_IntValue) );
161446      pExpr->op = TK_TRUEFALSE;  /* See tag-20230504-1 */
161447      pExpr->u.zToken = "false";
161448      ExprSetProperty(pExpr, EP_IsFalse);
161449      pTerm->prereqAll = 0;
161450      pTerm->eOperator = 0;
161451    }
161452  }
161453
161454#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
161455  /* If a term is the BETWEEN operator, create two new virtual terms
161456  ** that define the range that the BETWEEN implements.  For example:
161457  **
161458  **      a BETWEEN b AND c
161459  **
161460  ** is converted into:
161461  **
161462  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
161463  **
161464  ** The two new terms are added onto the end of the WhereClause object.
161465  ** The new terms are "dynamic" and are children of the original BETWEEN
161466  ** term.  That means that if the BETWEEN term is coded, the children are
161467  ** skipped.  Or, if the children are satisfied by an index, the original
161468  ** BETWEEN term is skipped.
161469  */
161470  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
161471    ExprList *pList;
161472    int i;
161473    static const u8 ops[] = {TK_GE, TK_LE};
161474    assert( ExprUseXList(pExpr) );
161475    pList = pExpr->x.pList;
161476    assert( pList!=0 );
161477    assert( pList->nExpr==2 );
161478    for(i=0; i<2; i++){
161479      Expr *pNewExpr;
161480      int idxNew;
161481      pNewExpr = sqlite3PExpr(pParse, ops[i],
161482                             sqlite3ExprDup(db, pExpr->pLeft, 0),
161483                             sqlite3ExprDup(db, pList->a[i].pExpr, 0));
161484      transferJoinMarkings(pNewExpr, pExpr);
161485      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
161486      testcase( idxNew==0 );
161487      exprAnalyze(pSrc, pWC, idxNew);
161488      pTerm = &pWC->a[idxTerm];
161489      markTermAsChild(pWC, idxNew, idxTerm);
161490    }
161491  }
161492#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
161493
161494#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
161495  /* Analyze a term that is composed of two or more subterms connected by
161496  ** an OR operator.
161497  */
161498  else if( pExpr->op==TK_OR ){
161499    assert( pWC->op==TK_AND );
161500    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
161501    pTerm = &pWC->a[idxTerm];
161502  }
161503#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
161504  /* The form "x IS NOT NULL" can sometimes be evaluated more efficiently
161505  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
161506  ** virtual term of that form.
161507  **
161508  ** The virtual term must be tagged with TERM_VNULL.
161509  */
161510  else if( pExpr->op==TK_NOTNULL ){
161511    if( pExpr->pLeft->op==TK_COLUMN
161512     && pExpr->pLeft->iColumn>=0
161513     && !ExprHasProperty(pExpr, EP_OuterON)
161514    ){
161515      Expr *pNewExpr;
161516      Expr *pLeft = pExpr->pLeft;
161517      int idxNew;
161518      WhereTerm *pNewTerm;
161519
161520      pNewExpr = sqlite3PExpr(pParse, TK_GT,
161521                              sqlite3ExprDup(db, pLeft, 0),
161522                              sqlite3ExprAlloc(db, TK_NULL, 0, 0));
161523
161524      idxNew = whereClauseInsert(pWC, pNewExpr,
161525                                TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
161526      if( idxNew ){
161527        pNewTerm = &pWC->a[idxNew];
161528        pNewTerm->prereqRight = 0;
161529        pNewTerm->leftCursor = pLeft->iTable;
161530        pNewTerm->u.x.leftColumn = pLeft->iColumn;
161531        pNewTerm->eOperator = WO_GT;
161532        markTermAsChild(pWC, idxNew, idxTerm);
161533        pTerm = &pWC->a[idxTerm];
161534        pTerm->wtFlags |= TERM_COPIED;
161535        pNewTerm->prereqAll = pTerm->prereqAll;
161536      }
161537    }
161538  }
161539
161540
161541#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
161542  /* Add constraints to reduce the search space on a LIKE or GLOB
161543  ** operator.
161544  **
161545  ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
161546  **
161547  **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
161548  **
161549  ** The last character of the prefix "abc" is incremented to form the
161550  ** termination condition "abd".  If case is not significant (the default
161551  ** for LIKE) then the lower-bound is made all uppercase and the upper-
161552  ** bound is made all lowercase so that the bounds also work when comparing
161553  ** BLOBs.
161554  */
161555  else if( pExpr->op==TK_FUNCTION
161556   && pWC->op==TK_AND
161557   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
161558  ){
161559    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
161560    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
161561    Expr *pNewExpr1;
161562    Expr *pNewExpr2;
161563    int idxNew1;
161564    int idxNew2;
161565    const char *zCollSeqName;     /* Name of collating sequence */
161566    const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
161567
161568    assert( ExprUseXList(pExpr) );
161569    pLeft = pExpr->x.pList->a[1].pExpr;
161570    pStr2 = sqlite3ExprDup(db, pStr1, 0);
161571    assert( pStr1==0 || !ExprHasProperty(pStr1, EP_IntValue) );
161572    assert( pStr2==0 || !ExprHasProperty(pStr2, EP_IntValue) );
161573
161574
161575    /* Convert the lower bound to upper-case and the upper bound to
161576    ** lower-case (upper-case is less than lower-case in ASCII) so that
161577    ** the range constraints also work for BLOBs
161578    */
161579    if( noCase && !pParse->db->mallocFailed ){
161580      int i;
161581      char c;
161582      pTerm->wtFlags |= TERM_LIKE;
161583      for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
161584        pStr1->u.zToken[i] = sqlite3Toupper(c);
161585        pStr2->u.zToken[i] = sqlite3Tolower(c);
161586      }
161587    }
161588
161589    if( !db->mallocFailed ){
161590      u8 c, *pC;       /* Last character before the first wildcard */
161591      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
161592      c = *pC;
161593      if( noCase ){
161594        /* The point is to increment the last character before the first
161595        ** wildcard.  But if we increment '@', that will push it into the
161596        ** alphabetic range where case conversions will mess up the
161597        ** inequality.  To avoid this, make sure to also run the full
161598        ** LIKE on all candidate expressions by clearing the isComplete flag
161599        */
161600        if( c=='A'-1 ) isComplete = 0;
161601        c = sqlite3UpperToLower[c];
161602      }
161603      *pC = c + 1;
161604    }
161605    zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY;
161606    pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
161607    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
161608           sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
161609           pStr1);
161610    transferJoinMarkings(pNewExpr1, pExpr);
161611    idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
161612    testcase( idxNew1==0 );
161613    pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
161614    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
161615           sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
161616           pStr2);
161617    transferJoinMarkings(pNewExpr2, pExpr);
161618    idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
161619    testcase( idxNew2==0 );
161620    exprAnalyze(pSrc, pWC, idxNew1);
161621    exprAnalyze(pSrc, pWC, idxNew2);
161622    pTerm = &pWC->a[idxTerm];
161623    if( isComplete ){
161624      markTermAsChild(pWC, idxNew1, idxTerm);
161625      markTermAsChild(pWC, idxNew2, idxTerm);
161626    }
161627  }
161628#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
161629
161630  /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
161631  ** new terms for each component comparison - "a = ?" and "b = ?".  The
161632  ** new terms completely replace the original vector comparison, which is
161633  ** no longer used.
161634  **
161635  ** This is only required if at least one side of the comparison operation
161636  ** is not a sub-select.
161637  **
161638  ** tag-20220128a
161639  */
161640  if( (pExpr->op==TK_EQ || pExpr->op==TK_IS)
161641   && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
161642   && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
161643   && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
161644     || (pExpr->pRight->flags & EP_xIsSelect)==0)
161645   && pWC->op==TK_AND
161646  ){
161647    int i;
161648    for(i=0; i<nLeft; i++){
161649      int idxNew;
161650      Expr *pNew;
161651      Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i, nLeft);
161652      Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i, nLeft);
161653
161654      pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
161655      transferJoinMarkings(pNew, pExpr);
161656      idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC|TERM_SLICE);
161657      exprAnalyze(pSrc, pWC, idxNew);
161658    }
161659    pTerm = &pWC->a[idxTerm];
161660    pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL;  /* Disable the original */
161661    pTerm->eOperator = WO_ROWVAL;
161662  }
161663
161664  /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
161665  ** a virtual term for each vector component. The expression object
161666  ** used by each such virtual term is pExpr (the full vector IN(...)
161667  ** expression). The WhereTerm.u.x.iField variable identifies the index within
161668  ** the vector on the LHS that the virtual term represents.
161669  **
161670  ** This only works if the RHS is a simple SELECT (not a compound) that does
161671  ** not use window functions.
161672  */
161673  else if( pExpr->op==TK_IN
161674   && pTerm->u.x.iField==0
161675   && pExpr->pLeft->op==TK_VECTOR
161676   && ALWAYS( ExprUseXSelect(pExpr) )
161677   && (pExpr->x.pSelect->pPrior==0 || (pExpr->x.pSelect->selFlags & SF_Values))
161678#ifndef SQLITE_OMIT_WINDOWFUNC
161679   && pExpr->x.pSelect->pWin==0
161680#endif
161681   && pWC->op==TK_AND
161682  ){
161683    int i;
161684    for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
161685      int idxNew;
161686      idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL|TERM_SLICE);
161687      pWC->a[idxNew].u.x.iField = i+1;
161688      exprAnalyze(pSrc, pWC, idxNew);
161689      markTermAsChild(pWC, idxNew, idxTerm);
161690    }
161691  }
161692
161693#ifndef SQLITE_OMIT_VIRTUALTABLE
161694  /* Add a WO_AUX auxiliary term to the constraint set if the
161695  ** current expression is of the form "column OP expr" where OP
161696  ** is an operator that gets passed into virtual tables but which is
161697  ** not normally optimized for ordinary tables.  In other words, OP
161698  ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
161699  ** This information is used by the xBestIndex methods of
161700  ** virtual tables.  The native query optimizer does not attempt
161701  ** to do anything with MATCH functions.
161702  */
161703  else if( pWC->op==TK_AND ){
161704    Expr *pRight = 0, *pLeft = 0;
161705    int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);
161706    while( res-- > 0 ){
161707      int idxNew;
161708      WhereTerm *pNewTerm;
161709      Bitmask prereqColumn, prereqExpr;
161710
161711      prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
161712      prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
161713      if( (prereqExpr & prereqColumn)==0 ){
161714        Expr *pNewExpr;
161715        pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
161716            0, sqlite3ExprDup(db, pRight, 0));
161717        if( ExprHasProperty(pExpr, EP_OuterON) && pNewExpr ){
161718          ExprSetProperty(pNewExpr, EP_OuterON);
161719          pNewExpr->w.iJoin = pExpr->w.iJoin;
161720        }
161721        idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
161722        testcase( idxNew==0 );
161723        pNewTerm = &pWC->a[idxNew];
161724        pNewTerm->prereqRight = prereqExpr;
161725        pNewTerm->leftCursor = pLeft->iTable;
161726        pNewTerm->u.x.leftColumn = pLeft->iColumn;
161727        pNewTerm->eOperator = WO_AUX;
161728        pNewTerm->eMatchOp = eOp2;
161729        markTermAsChild(pWC, idxNew, idxTerm);
161730        pTerm = &pWC->a[idxTerm];
161731        pTerm->wtFlags |= TERM_COPIED;
161732        pNewTerm->prereqAll = pTerm->prereqAll;
161733      }
161734      SWAP(Expr*, pLeft, pRight);
161735    }
161736  }
161737#endif /* SQLITE_OMIT_VIRTUALTABLE */
161738
161739  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
161740  ** an index for tables to the left of the join.
161741  */
161742  testcase( pTerm!=&pWC->a[idxTerm] );
161743  pTerm = &pWC->a[idxTerm];
161744  pTerm->prereqRight |= extraRight;
161745}
161746
161747/***************************************************************************
161748** Routines with file scope above.  Interface to the rest of the where.c
161749** subsystem follows.
161750***************************************************************************/
161751
161752/*
161753** This routine identifies subexpressions in the WHERE clause where
161754** each subexpression is separated by the AND operator or some other
161755** operator specified in the op parameter.  The WhereClause structure
161756** is filled with pointers to subexpressions.  For example:
161757**
161758**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
161759**           \________/     \_______________/     \________________/
161760**            slot[0]            slot[1]               slot[2]
161761**
161762** The original WHERE clause in pExpr is unaltered.  All this routine
161763** does is make slot[] entries point to substructure within pExpr.
161764**
161765** In the previous sentence and in the diagram, "slot[]" refers to
161766** the WhereClause.a[] array.  The slot[] array grows as needed to contain
161767** all terms of the WHERE clause.
161768*/
161769SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
161770  Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pExpr);
161771  pWC->op = op;
161772  assert( pE2!=0 || pExpr==0 );
161773  if( pE2==0 ) return;
161774  if( pE2->op!=op ){
161775    whereClauseInsert(pWC, pExpr, 0);
161776  }else{
161777    sqlite3WhereSplit(pWC, pE2->pLeft, op);
161778    sqlite3WhereSplit(pWC, pE2->pRight, op);
161779  }
161780}
161781
161782/*
161783** Add either a LIMIT (if eMatchOp==SQLITE_INDEX_CONSTRAINT_LIMIT) or
161784** OFFSET (if eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET) term to the
161785** where-clause passed as the first argument. The value for the term
161786** is found in register iReg.
161787**
161788** In the common case where the value is a simple integer
161789** (example: "LIMIT 5 OFFSET 10") then the expression codes as a
161790** TK_INTEGER so that it will be available to sqlite3_vtab_rhs_value().
161791** If not, then it codes as a TK_REGISTER expression.
161792*/
161793static void whereAddLimitExpr(
161794  WhereClause *pWC,   /* Add the constraint to this WHERE clause */
161795  int iReg,           /* Register that will hold value of the limit/offset */
161796  Expr *pExpr,        /* Expression that defines the limit/offset */
161797  int iCsr,           /* Cursor to which the constraint applies */
161798  int eMatchOp        /* SQLITE_INDEX_CONSTRAINT_LIMIT or _OFFSET */
161799){
161800  Parse *pParse = pWC->pWInfo->pParse;
161801  sqlite3 *db = pParse->db;
161802  Expr *pNew;
161803  int iVal = 0;
161804
161805  if( sqlite3ExprIsInteger(pExpr, &iVal) && iVal>=0 ){
161806    Expr *pVal = sqlite3Expr(db, TK_INTEGER, 0);
161807    if( pVal==0 ) return;
161808    ExprSetProperty(pVal, EP_IntValue);
161809    pVal->u.iValue = iVal;
161810    pNew = sqlite3PExpr(pParse, TK_MATCH, 0, pVal);
161811  }else{
161812    Expr *pVal = sqlite3Expr(db, TK_REGISTER, 0);
161813    if( pVal==0 ) return;
161814    pVal->iTable = iReg;
161815    pNew = sqlite3PExpr(pParse, TK_MATCH, 0, pVal);
161816  }
161817  if( pNew ){
161818    WhereTerm *pTerm;
161819    int idx;
161820    idx = whereClauseInsert(pWC, pNew, TERM_DYNAMIC|TERM_VIRTUAL);
161821    pTerm = &pWC->a[idx];
161822    pTerm->leftCursor = iCsr;
161823    pTerm->eOperator = WO_AUX;
161824    pTerm->eMatchOp = eMatchOp;
161825  }
161826}
161827
161828/*
161829** Possibly add terms corresponding to the LIMIT and OFFSET clauses of the
161830** SELECT statement passed as the second argument. These terms are only
161831** added if:
161832**
161833**   1. The SELECT statement has a LIMIT clause, and
161834**   2. The SELECT statement is not an aggregate or DISTINCT query, and
161835**   3. The SELECT statement has exactly one object in its from clause, and
161836**      that object is a virtual table, and
161837**   4. There are no terms in the WHERE clause that will not be passed
161838**      to the virtual table xBestIndex method.
161839**   5. The ORDER BY clause, if any, will be made available to the xBestIndex
161840**      method.
161841**
161842** LIMIT and OFFSET terms are ignored by most of the planner code. They
161843** exist only so that they may be passed to the xBestIndex method of the
161844** single virtual table in the FROM clause of the SELECT.
161845*/
161846SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3WhereAddLimit(WhereClause *pWC, Select *p){
161847  assert( p!=0 && p->pLimit!=0 );                 /* 1 -- checked by caller */
161848  if( p->pGroupBy==0
161849   && (p->selFlags & (SF_Distinct|SF_Aggregate))==0             /* 2 */
161850   && (p->pSrc->nSrc==1 && IsVirtual(p->pSrc->a[0].pTab))       /* 3 */
161851  ){
161852    ExprList *pOrderBy = p->pOrderBy;
161853    int iCsr = p->pSrc->a[0].iCursor;
161854    int ii;
161855
161856    /* Check condition (4). Return early if it is not met. */
161857    for(ii=0; ii<pWC->nTerm; ii++){
161858      if( pWC->a[ii].wtFlags & TERM_CODED ){
161859        /* This term is a vector operation that has been decomposed into
161860        ** other, subsequent terms.  It can be ignored. See tag-20220128a */
161861        assert( pWC->a[ii].wtFlags & TERM_VIRTUAL );
161862        assert( pWC->a[ii].eOperator==WO_ROWVAL );
161863        continue;
161864      }
161865      if( pWC->a[ii].nChild ){
161866        /* If this term has child terms, then they are also part of the
161867        ** pWC->a[] array. So this term can be ignored, as a LIMIT clause
161868        ** will only be added if each of the child terms passes the
161869        ** (leftCursor==iCsr) test below.  */
161870        continue;
161871      }
161872      if( pWC->a[ii].leftCursor!=iCsr ) return;
161873      if( pWC->a[ii].prereqRight!=0 ) return;
161874    }
161875
161876    /* Check condition (5). Return early if it is not met. */
161877    if( pOrderBy ){
161878      for(ii=0; ii<pOrderBy->nExpr; ii++){
161879        Expr *pExpr = pOrderBy->a[ii].pExpr;
161880        if( pExpr->op!=TK_COLUMN ) return;
161881        if( pExpr->iTable!=iCsr ) return;
161882        if( pOrderBy->a[ii].fg.sortFlags & KEYINFO_ORDER_BIGNULL ) return;
161883      }
161884    }
161885
161886    /* All conditions are met. Add the terms to the where-clause object. */
161887    assert( p->pLimit->op==TK_LIMIT );
161888    if( p->iOffset!=0 && (p->selFlags & SF_Compound)==0 ){
161889      whereAddLimitExpr(pWC, p->iOffset, p->pLimit->pRight,
161890                        iCsr, SQLITE_INDEX_CONSTRAINT_OFFSET);
161891    }
161892    if( p->iOffset==0 || (p->selFlags & SF_Compound)==0 ){
161893      whereAddLimitExpr(pWC, p->iLimit, p->pLimit->pLeft,
161894                        iCsr, SQLITE_INDEX_CONSTRAINT_LIMIT);
161895    }
161896  }
161897}
161898
161899/*
161900** Initialize a preallocated WhereClause structure.
161901*/
161902SQLITE_PRIVATE void sqlite3WhereClauseInit(
161903  WhereClause *pWC,        /* The WhereClause to be initialized */
161904  WhereInfo *pWInfo        /* The WHERE processing context */
161905){
161906  pWC->pWInfo = pWInfo;
161907  pWC->hasOr = 0;
161908  pWC->pOuter = 0;
161909  pWC->nTerm = 0;
161910  pWC->nBase = 0;
161911  pWC->nSlot = ArraySize(pWC->aStatic);
161912  pWC->a = pWC->aStatic;
161913}
161914
161915/*
161916** Deallocate a WhereClause structure.  The WhereClause structure
161917** itself is not freed.  This routine is the inverse of
161918** sqlite3WhereClauseInit().
161919*/
161920SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
161921  sqlite3 *db = pWC->pWInfo->pParse->db;
161922  assert( pWC->nTerm>=pWC->nBase );
161923  if( pWC->nTerm>0 ){
161924    WhereTerm *a = pWC->a;
161925    WhereTerm *aLast = &pWC->a[pWC->nTerm-1];
161926#ifdef SQLITE_DEBUG
161927    int i;
161928    /* Verify that every term past pWC->nBase is virtual */
161929    for(i=pWC->nBase; i<pWC->nTerm; i++){
161930      assert( (pWC->a[i].wtFlags & TERM_VIRTUAL)!=0 );
161931    }
161932#endif
161933    while(1){
161934      assert( a->eMatchOp==0 || a->eOperator==WO_AUX );
161935      if( a->wtFlags & TERM_DYNAMIC ){
161936        sqlite3ExprDelete(db, a->pExpr);
161937      }
161938      if( a->wtFlags & (TERM_ORINFO|TERM_ANDINFO) ){
161939        if( a->wtFlags & TERM_ORINFO ){
161940          assert( (a->wtFlags & TERM_ANDINFO)==0 );
161941          whereOrInfoDelete(db, a->u.pOrInfo);
161942        }else{
161943          assert( (a->wtFlags & TERM_ANDINFO)!=0 );
161944          whereAndInfoDelete(db, a->u.pAndInfo);
161945        }
161946      }
161947      if( a==aLast ) break;
161948      a++;
161949    }
161950  }
161951}
161952
161953
161954/*
161955** These routines walk (recursively) an expression tree and generate
161956** a bitmask indicating which tables are used in that expression
161957** tree.
161958**
161959** sqlite3WhereExprUsage(MaskSet, Expr) ->
161960**
161961**       Return a Bitmask of all tables referenced by Expr.  Expr can be
161962**       be NULL, in which case 0 is returned.
161963**
161964** sqlite3WhereExprUsageNN(MaskSet, Expr) ->
161965**
161966**       Same as sqlite3WhereExprUsage() except that Expr must not be
161967**       NULL.  The "NN" suffix on the name stands for "Not Null".
161968**
161969** sqlite3WhereExprListUsage(MaskSet, ExprList) ->
161970**
161971**       Return a Bitmask of all tables referenced by every expression
161972**       in the expression list ExprList.  ExprList can be NULL, in which
161973**       case 0 is returned.
161974**
161975** sqlite3WhereExprUsageFull(MaskSet, ExprList) ->
161976**
161977**       Internal use only.  Called only by sqlite3WhereExprUsageNN() for
161978**       complex expressions that require pushing register values onto
161979**       the stack.  Many calls to sqlite3WhereExprUsageNN() do not need
161980**       the more complex analysis done by this routine.  Hence, the
161981**       computations done by this routine are broken out into a separate
161982**       "no-inline" function to avoid the stack push overhead in the
161983**       common case where it is not needed.
161984*/
161985static SQLITE_NOINLINE Bitmask sqlite3WhereExprUsageFull(
161986  WhereMaskSet *pMaskSet,
161987  Expr *p
161988){
161989  Bitmask mask;
161990  mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
161991  if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);
161992  if( p->pRight ){
161993    mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight);
161994    assert( p->x.pList==0 );
161995  }else if( ExprUseXSelect(p) ){
161996    if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
161997    mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
161998  }else if( p->x.pList ){
161999    mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
162000  }
162001#ifndef SQLITE_OMIT_WINDOWFUNC
162002  if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && ExprUseYWin(p) ){
162003    assert( p->y.pWin!=0 );
162004    mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition);
162005    mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy);
162006    mask |= sqlite3WhereExprUsage(pMaskSet, p->y.pWin->pFilter);
162007  }
162008#endif
162009  return mask;
162010}
162011SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
162012  if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
162013    return sqlite3WhereGetMask(pMaskSet, p->iTable);
162014  }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
162015    assert( p->op!=TK_IF_NULL_ROW );
162016    return 0;
162017  }
162018  return sqlite3WhereExprUsageFull(pMaskSet, p);
162019}
162020SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
162021  return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0;
162022}
162023SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
162024  int i;
162025  Bitmask mask = 0;
162026  if( pList ){
162027    for(i=0; i<pList->nExpr; i++){
162028      mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
162029    }
162030  }
162031  return mask;
162032}
162033
162034
162035/*
162036** Call exprAnalyze on all terms in a WHERE clause.
162037**
162038** Note that exprAnalyze() might add new virtual terms onto the
162039** end of the WHERE clause.  We do not want to analyze these new
162040** virtual terms, so start analyzing at the end and work forward
162041** so that the added virtual terms are never processed.
162042*/
162043SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
162044  SrcList *pTabList,       /* the FROM clause */
162045  WhereClause *pWC         /* the WHERE clause to be analyzed */
162046){
162047  int i;
162048  for(i=pWC->nTerm-1; i>=0; i--){
162049    exprAnalyze(pTabList, pWC, i);
162050  }
162051}
162052
162053/*
162054** For table-valued-functions, transform the function arguments into
162055** new WHERE clause terms.
162056**
162057** Each function argument translates into an equality constraint against
162058** a HIDDEN column in the table.
162059*/
162060SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
162061  Parse *pParse,                    /* Parsing context */
162062  SrcItem *pItem,                   /* The FROM clause term to process */
162063  WhereClause *pWC                  /* Xfer function arguments to here */
162064){
162065  Table *pTab;
162066  int j, k;
162067  ExprList *pArgs;
162068  Expr *pColRef;
162069  Expr *pTerm;
162070  if( pItem->fg.isTabFunc==0 ) return;
162071  pTab = pItem->pTab;
162072  assert( pTab!=0 );
162073  pArgs = pItem->u1.pFuncArg;
162074  if( pArgs==0 ) return;
162075  for(j=k=0; j<pArgs->nExpr; j++){
162076    Expr *pRhs;
162077    u32 joinType;
162078    while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
162079    if( k>=pTab->nCol ){
162080      sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
162081                      pTab->zName, j);
162082      return;
162083    }
162084    pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
162085    if( pColRef==0 ) return;
162086    pColRef->iTable = pItem->iCursor;
162087    pColRef->iColumn = k++;
162088    assert( ExprUseYTab(pColRef) );
162089    pColRef->y.pTab = pTab;
162090    pItem->colUsed |= sqlite3ExprColUsed(pColRef);
162091    pRhs = sqlite3PExpr(pParse, TK_UPLUS,
162092        sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
162093    pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
162094    if( pItem->fg.jointype & (JT_LEFT|JT_RIGHT) ){
162095      testcase( pItem->fg.jointype & JT_LEFT );  /* testtag-20230227a */
162096      testcase( pItem->fg.jointype & JT_RIGHT ); /* testtag-20230227b */
162097      joinType = EP_OuterON;
162098    }else{
162099      testcase( pItem->fg.jointype & JT_LTORJ ); /* testtag-20230227c */
162100      joinType = EP_InnerON;
162101    }
162102    sqlite3SetJoinExpr(pTerm, pItem->iCursor, joinType);
162103    whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
162104  }
162105}
162106
162107/************** End of whereexpr.c *******************************************/
162108/************** Begin file where.c *******************************************/
162109/*
162110** 2001 September 15
162111**
162112** The author disclaims copyright to this source code.  In place of
162113** a legal notice, here is a blessing:
162114**
162115**    May you do good and not evil.
162116**    May you find forgiveness for yourself and forgive others.
162117**    May you share freely, never taking more than you give.
162118**
162119*************************************************************************
162120** This module contains C code that generates VDBE code used to process
162121** the WHERE clause of SQL statements.  This module is responsible for
162122** generating the code that loops through a table looking for applicable
162123** rows.  Indices are selected and used to speed the search when doing
162124** so is applicable.  Because this module is responsible for selecting
162125** indices, you might also think of this module as the "query optimizer".
162126*/
162127/* #include "sqliteInt.h" */
162128/* #include "whereInt.h" */
162129
162130/*
162131** Extra information appended to the end of sqlite3_index_info but not
162132** visible to the xBestIndex function, at least not directly.  The
162133** sqlite3_vtab_collation() interface knows how to reach it, however.
162134**
162135** This object is not an API and can be changed from one release to the
162136** next.  As long as allocateIndexInfo() and sqlite3_vtab_collation()
162137** agree on the structure, all will be well.
162138*/
162139typedef struct HiddenIndexInfo HiddenIndexInfo;
162140struct HiddenIndexInfo {
162141  WhereClause *pWC;        /* The Where clause being analyzed */
162142  Parse *pParse;           /* The parsing context */
162143  int eDistinct;           /* Value to return from sqlite3_vtab_distinct() */
162144  u32 mIn;                 /* Mask of terms that are <col> IN (...) */
162145  u32 mHandleIn;           /* Terms that vtab will handle as <col> IN (...) */
162146  sqlite3_value *aRhs[1];  /* RHS values for constraints. MUST BE LAST
162147                           ** because extra space is allocated to hold up
162148                           ** to nTerm such values */
162149};
162150
162151/* Forward declaration of methods */
162152static int whereLoopResize(sqlite3*, WhereLoop*, int);
162153
162154/*
162155** Return the estimated number of output rows from a WHERE clause
162156*/
162157SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
162158  return pWInfo->nRowOut;
162159}
162160
162161/*
162162** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
162163** WHERE clause returns outputs for DISTINCT processing.
162164*/
162165SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
162166  return pWInfo->eDistinct;
162167}
162168
162169/*
162170** Return the number of ORDER BY terms that are satisfied by the
162171** WHERE clause.  A return of 0 means that the output must be
162172** completely sorted.  A return equal to the number of ORDER BY
162173** terms means that no sorting is needed at all.  A return that
162174** is positive but less than the number of ORDER BY terms means that
162175** block sorting is required.
162176*/
162177SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
162178  return pWInfo->nOBSat<0 ? 0 : pWInfo->nOBSat;
162179}
162180
162181/*
162182** In the ORDER BY LIMIT optimization, if the inner-most loop is known
162183** to emit rows in increasing order, and if the last row emitted by the
162184** inner-most loop did not fit within the sorter, then we can skip all
162185** subsequent rows for the current iteration of the inner loop (because they
162186** will not fit in the sorter either) and continue with the second inner
162187** loop - the loop immediately outside the inner-most.
162188**
162189** When a row does not fit in the sorter (because the sorter already
162190** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the
162191** label returned by this function.
162192**
162193** If the ORDER BY LIMIT optimization applies, the jump destination should
162194** be the continuation for the second-inner-most loop.  If the ORDER BY
162195** LIMIT optimization does not apply, then the jump destination should
162196** be the continuation for the inner-most loop.
162197**
162198** It is always safe for this routine to return the continuation of the
162199** inner-most loop, in the sense that a correct answer will result.
162200** Returning the continuation the second inner loop is an optimization
162201** that might make the code run a little faster, but should not change
162202** the final answer.
162203*/
162204SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){
162205  WhereLevel *pInner;
162206  if( !pWInfo->bOrderedInnerLoop ){
162207    /* The ORDER BY LIMIT optimization does not apply.  Jump to the
162208    ** continuation of the inner-most loop. */
162209    return pWInfo->iContinue;
162210  }
162211  pInner = &pWInfo->a[pWInfo->nLevel-1];
162212  assert( pInner->addrNxt!=0 );
162213  return pInner->pRJ ? pWInfo->iContinue : pInner->addrNxt;
162214}
162215
162216/*
162217** While generating code for the min/max optimization, after handling
162218** the aggregate-step call to min() or max(), check to see if any
162219** additional looping is required.  If the output order is such that
162220** we are certain that the correct answer has already been found, then
162221** code an OP_Goto to by pass subsequent processing.
162222**
162223** Any extra OP_Goto that is coded here is an optimization.  The
162224** correct answer should be obtained regardless.  This OP_Goto just
162225** makes the answer appear faster.
162226*/
162227SQLITE_PRIVATE void sqlite3WhereMinMaxOptEarlyOut(Vdbe *v, WhereInfo *pWInfo){
162228  WhereLevel *pInner;
162229  int i;
162230  if( !pWInfo->bOrderedInnerLoop ) return;
162231  if( pWInfo->nOBSat==0 ) return;
162232  for(i=pWInfo->nLevel-1; i>=0; i--){
162233    pInner = &pWInfo->a[i];
162234    if( (pInner->pWLoop->wsFlags & WHERE_COLUMN_IN)!=0 ){
162235      sqlite3VdbeGoto(v, pInner->addrNxt);
162236      return;
162237    }
162238  }
162239  sqlite3VdbeGoto(v, pWInfo->iBreak);
162240}
162241
162242/*
162243** Return the VDBE address or label to jump to in order to continue
162244** immediately with the next row of a WHERE clause.
162245*/
162246SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
162247  assert( pWInfo->iContinue!=0 );
162248  return pWInfo->iContinue;
162249}
162250
162251/*
162252** Return the VDBE address or label to jump to in order to break
162253** out of a WHERE loop.
162254*/
162255SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
162256  return pWInfo->iBreak;
162257}
162258
162259/*
162260** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
162261** operate directly on the rowids returned by a WHERE clause.  Return
162262** ONEPASS_SINGLE (1) if the statement can operation directly because only
162263** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
162264** optimization can be used on multiple
162265**
162266** If the ONEPASS optimization is used (if this routine returns true)
162267** then also write the indices of open cursors used by ONEPASS
162268** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
162269** table and iaCur[1] gets the cursor used by an auxiliary index.
162270** Either value may be -1, indicating that cursor is not used.
162271** Any cursors returned will have been opened for writing.
162272**
162273** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
162274** unable to use the ONEPASS optimization.
162275*/
162276SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
162277  memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
162278#ifdef WHERETRACE_ENABLED
162279  if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
162280    sqlite3DebugPrintf("%s cursors: %d %d\n",
162281         pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
162282         aiCur[0], aiCur[1]);
162283  }
162284#endif
162285  return pWInfo->eOnePass;
162286}
162287
162288/*
162289** Return TRUE if the WHERE loop uses the OP_DeferredSeek opcode to move
162290** the data cursor to the row selected by the index cursor.
162291*/
162292SQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){
162293  return pWInfo->bDeferredSeek;
162294}
162295
162296/*
162297** Move the content of pSrc into pDest
162298*/
162299static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
162300  pDest->n = pSrc->n;
162301  memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
162302}
162303
162304/*
162305** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
162306**
162307** The new entry might overwrite an existing entry, or it might be
162308** appended, or it might be discarded.  Do whatever is the right thing
162309** so that pSet keeps the N_OR_COST best entries seen so far.
162310*/
162311static int whereOrInsert(
162312  WhereOrSet *pSet,      /* The WhereOrSet to be updated */
162313  Bitmask prereq,        /* Prerequisites of the new entry */
162314  LogEst rRun,           /* Run-cost of the new entry */
162315  LogEst nOut            /* Number of outputs for the new entry */
162316){
162317  u16 i;
162318  WhereOrCost *p;
162319  for(i=pSet->n, p=pSet->a; i>0; i--, p++){
162320    if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
162321      goto whereOrInsert_done;
162322    }
162323    if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
162324      return 0;
162325    }
162326  }
162327  if( pSet->n<N_OR_COST ){
162328    p = &pSet->a[pSet->n++];
162329    p->nOut = nOut;
162330  }else{
162331    p = pSet->a;
162332    for(i=1; i<pSet->n; i++){
162333      if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
162334    }
162335    if( p->rRun<=rRun ) return 0;
162336  }
162337whereOrInsert_done:
162338  p->prereq = prereq;
162339  p->rRun = rRun;
162340  if( p->nOut>nOut ) p->nOut = nOut;
162341  return 1;
162342}
162343
162344/*
162345** Return the bitmask for the given cursor number.  Return 0 if
162346** iCursor is not in the set.
162347*/
162348SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
162349  int i;
162350  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
162351  assert( pMaskSet->n>0 || pMaskSet->ix[0]<0 );
162352  assert( iCursor>=-1 );
162353  if( pMaskSet->ix[0]==iCursor ){
162354    return 1;
162355  }
162356  for(i=1; i<pMaskSet->n; i++){
162357    if( pMaskSet->ix[i]==iCursor ){
162358      return MASKBIT(i);
162359    }
162360  }
162361  return 0;
162362}
162363
162364/* Allocate memory that is automatically freed when pWInfo is freed.
162365*/
162366SQLITE_PRIVATE void *sqlite3WhereMalloc(WhereInfo *pWInfo, u64 nByte){
162367  WhereMemBlock *pBlock;
162368  pBlock = sqlite3DbMallocRawNN(pWInfo->pParse->db, nByte+sizeof(*pBlock));
162369  if( pBlock ){
162370    pBlock->pNext = pWInfo->pMemToFree;
162371    pBlock->sz = nByte;
162372    pWInfo->pMemToFree = pBlock;
162373    pBlock++;
162374  }
162375  return (void*)pBlock;
162376}
162377SQLITE_PRIVATE void *sqlite3WhereRealloc(WhereInfo *pWInfo, void *pOld, u64 nByte){
162378  void *pNew = sqlite3WhereMalloc(pWInfo, nByte);
162379  if( pNew && pOld ){
162380    WhereMemBlock *pOldBlk = (WhereMemBlock*)pOld;
162381    pOldBlk--;
162382    assert( pOldBlk->sz<nByte );
162383    memcpy(pNew, pOld, pOldBlk->sz);
162384  }
162385  return pNew;
162386}
162387
162388/*
162389** Create a new mask for cursor iCursor.
162390**
162391** There is one cursor per table in the FROM clause.  The number of
162392** tables in the FROM clause is limited by a test early in the
162393** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
162394** array will never overflow.
162395*/
162396static void createMask(WhereMaskSet *pMaskSet, int iCursor){
162397  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
162398  pMaskSet->ix[pMaskSet->n++] = iCursor;
162399}
162400
162401/*
162402** If the right-hand branch of the expression is a TK_COLUMN, then return
162403** a pointer to the right-hand branch.  Otherwise, return NULL.
162404*/
162405static Expr *whereRightSubexprIsColumn(Expr *p){
162406  p = sqlite3ExprSkipCollateAndLikely(p->pRight);
162407  if( ALWAYS(p!=0) && p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
162408    return p;
162409  }
162410  return 0;
162411}
162412
162413/*
162414** Term pTerm is guaranteed to be a WO_IN term. It may be a component term
162415** of a vector IN expression of the form "(x, y, ...) IN (SELECT ...)".
162416** This function checks to see if the term is compatible with an index
162417** column with affinity idxaff (one of the SQLITE_AFF_XYZ values). If so,
162418** it returns a pointer to the name of the collation sequence (e.g. "BINARY"
162419** or "NOCASE") used by the comparison in pTerm. If it is not compatible
162420** with affinity idxaff, NULL is returned.
162421*/
162422static SQLITE_NOINLINE const char *indexInAffinityOk(
162423  Parse *pParse,
162424  WhereTerm *pTerm,
162425  u8 idxaff
162426){
162427  Expr *pX = pTerm->pExpr;
162428  Expr inexpr;
162429
162430  assert( pTerm->eOperator & WO_IN );
162431
162432  if( sqlite3ExprIsVector(pX->pLeft) ){
162433    int iField = pTerm->u.x.iField - 1;
162434    inexpr.flags = 0;
162435    inexpr.op = TK_EQ;
162436    inexpr.pLeft = pX->pLeft->x.pList->a[iField].pExpr;
162437    assert( ExprUseXSelect(pX) );
162438    inexpr.pRight = pX->x.pSelect->pEList->a[iField].pExpr;
162439    pX = &inexpr;
162440  }
162441
162442  if( sqlite3IndexAffinityOk(pX, idxaff) ){
162443    CollSeq *pRet = sqlite3ExprCompareCollSeq(pParse, pX);
162444    return pRet ? pRet->zName : sqlite3StrBINARY;
162445  }
162446  return 0;
162447}
162448
162449/*
162450** Advance to the next WhereTerm that matches according to the criteria
162451** established when the pScan object was initialized by whereScanInit().
162452** Return NULL if there are no more matching WhereTerms.
162453*/
162454static WhereTerm *whereScanNext(WhereScan *pScan){
162455  int iCur;            /* The cursor on the LHS of the term */
162456  i16 iColumn;         /* The column on the LHS of the term.  -1 for IPK */
162457  Expr *pX;            /* An expression being tested */
162458  WhereClause *pWC;    /* Shorthand for pScan->pWC */
162459  WhereTerm *pTerm;    /* The term being tested */
162460  int k = pScan->k;    /* Where to start scanning */
162461
162462  assert( pScan->iEquiv<=pScan->nEquiv );
162463  pWC = pScan->pWC;
162464  while(1){
162465    iColumn = pScan->aiColumn[pScan->iEquiv-1];
162466    iCur = pScan->aiCur[pScan->iEquiv-1];
162467    assert( pWC!=0 );
162468    assert( iCur>=0 );
162469    do{
162470      for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
162471        assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 || pTerm->leftCursor<0 );
162472        if( pTerm->leftCursor==iCur
162473         && pTerm->u.x.leftColumn==iColumn
162474         && (iColumn!=XN_EXPR
162475             || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
162476                                       pScan->pIdxExpr,iCur)==0)
162477         && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_OuterON))
162478        ){
162479          if( (pTerm->eOperator & WO_EQUIV)!=0
162480           && pScan->nEquiv<ArraySize(pScan->aiCur)
162481           && (pX = whereRightSubexprIsColumn(pTerm->pExpr))!=0
162482          ){
162483            int j;
162484            for(j=0; j<pScan->nEquiv; j++){
162485              if( pScan->aiCur[j]==pX->iTable
162486               && pScan->aiColumn[j]==pX->iColumn ){
162487                  break;
162488              }
162489            }
162490            if( j==pScan->nEquiv ){
162491              pScan->aiCur[j] = pX->iTable;
162492              pScan->aiColumn[j] = pX->iColumn;
162493              pScan->nEquiv++;
162494            }
162495          }
162496          if( (pTerm->eOperator & pScan->opMask)!=0 ){
162497            /* Verify the affinity and collating sequence match */
162498            if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
162499              const char *zCollName;
162500              Parse *pParse = pWC->pWInfo->pParse;
162501              pX = pTerm->pExpr;
162502
162503              if( (pTerm->eOperator & WO_IN) ){
162504                zCollName = indexInAffinityOk(pParse, pTerm, pScan->idxaff);
162505                if( !zCollName ) continue;
162506              }else{
162507                CollSeq *pColl;
162508                if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
162509                  continue;
162510                }
162511                assert(pX->pLeft);
162512                pColl = sqlite3ExprCompareCollSeq(pParse, pX);
162513                zCollName = pColl ? pColl->zName : sqlite3StrBINARY;
162514              }
162515
162516              if( sqlite3StrICmp(zCollName, pScan->zCollName) ){
162517                continue;
162518              }
162519            }
162520            if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
162521             && (pX = pTerm->pExpr->pRight, ALWAYS(pX!=0))
162522             && pX->op==TK_COLUMN
162523             && pX->iTable==pScan->aiCur[0]
162524             && pX->iColumn==pScan->aiColumn[0]
162525            ){
162526              testcase( pTerm->eOperator & WO_IS );
162527              continue;
162528            }
162529            pScan->pWC = pWC;
162530            pScan->k = k+1;
162531#ifdef WHERETRACE_ENABLED
162532            if( sqlite3WhereTrace & 0x20000 ){
162533              int ii;
162534              sqlite3DebugPrintf("SCAN-TERM %p: nEquiv=%d",
162535                 pTerm, pScan->nEquiv);
162536              for(ii=0; ii<pScan->nEquiv; ii++){
162537                sqlite3DebugPrintf(" {%d:%d}",
162538                   pScan->aiCur[ii], pScan->aiColumn[ii]);
162539              }
162540              sqlite3DebugPrintf("\n");
162541            }
162542#endif
162543            return pTerm;
162544          }
162545        }
162546      }
162547      pWC = pWC->pOuter;
162548      k = 0;
162549    }while( pWC!=0 );
162550    if( pScan->iEquiv>=pScan->nEquiv ) break;
162551    pWC = pScan->pOrigWC;
162552    k = 0;
162553    pScan->iEquiv++;
162554  }
162555  return 0;
162556}
162557
162558/*
162559** This is whereScanInit() for the case of an index on an expression.
162560** It is factored out into a separate tail-recursion subroutine so that
162561** the normal whereScanInit() routine, which is a high-runner, does not
162562** need to push registers onto the stack as part of its prologue.
162563*/
162564static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){
162565  pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr);
162566  return whereScanNext(pScan);
162567}
162568
162569/*
162570** Initialize a WHERE clause scanner object.  Return a pointer to the
162571** first match.  Return NULL if there are no matches.
162572**
162573** The scanner will be searching the WHERE clause pWC.  It will look
162574** for terms of the form "X <op> <expr>" where X is column iColumn of table
162575** iCur.   Or if pIdx!=0 then X is column iColumn of index pIdx.  pIdx
162576** must be one of the indexes of table iCur.
162577**
162578** The <op> must be one of the operators described by opMask.
162579**
162580** If the search is for X and the WHERE clause contains terms of the
162581** form X=Y then this routine might also return terms of the form
162582** "Y <op> <expr>".  The number of levels of transitivity is limited,
162583** but is enough to handle most commonly occurring SQL statements.
162584**
162585** If X is not the INTEGER PRIMARY KEY then X must be compatible with
162586** index pIdx.
162587*/
162588static WhereTerm *whereScanInit(
162589  WhereScan *pScan,       /* The WhereScan object being initialized */
162590  WhereClause *pWC,       /* The WHERE clause to be scanned */
162591  int iCur,               /* Cursor to scan for */
162592  int iColumn,            /* Column to scan for */
162593  u32 opMask,             /* Operator(s) to scan for */
162594  Index *pIdx             /* Must be compatible with this index */
162595){
162596  pScan->pOrigWC = pWC;
162597  pScan->pWC = pWC;
162598  pScan->pIdxExpr = 0;
162599  pScan->idxaff = 0;
162600  pScan->zCollName = 0;
162601  pScan->opMask = opMask;
162602  pScan->k = 0;
162603  pScan->aiCur[0] = iCur;
162604  pScan->nEquiv = 1;
162605  pScan->iEquiv = 1;
162606  if( pIdx ){
162607    int j = iColumn;
162608    iColumn = pIdx->aiColumn[j];
162609    if( iColumn==pIdx->pTable->iPKey ){
162610      iColumn = XN_ROWID;
162611    }else if( iColumn>=0 ){
162612      pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
162613      pScan->zCollName = pIdx->azColl[j];
162614    }else if( iColumn==XN_EXPR ){
162615      pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
162616      pScan->zCollName = pIdx->azColl[j];
162617      pScan->aiColumn[0] = XN_EXPR;
162618      return whereScanInitIndexExpr(pScan);
162619    }
162620  }else if( iColumn==XN_EXPR ){
162621    return 0;
162622  }
162623  pScan->aiColumn[0] = iColumn;
162624  return whereScanNext(pScan);
162625}
162626
162627/*
162628** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
162629** where X is a reference to the iColumn of table iCur or of index pIdx
162630** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
162631** the op parameter.  Return a pointer to the term.  Return 0 if not found.
162632**
162633** If pIdx!=0 then it must be one of the indexes of table iCur.
162634** Search for terms matching the iColumn-th column of pIdx
162635** rather than the iColumn-th column of table iCur.
162636**
162637** The term returned might by Y=<expr> if there is another constraint in
162638** the WHERE clause that specifies that X=Y.  Any such constraints will be
162639** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
162640** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
162641** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
162642** other equivalent values.  Hence a search for X will return <expr> if X=A1
162643** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
162644**
162645** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
162646** then try for the one with no dependencies on <expr> - in other words where
162647** <expr> is a constant expression of some kind.  Only return entries of
162648** the form "X <op> Y" where Y is a column in another table if no terms of
162649** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
162650** exist, try to return a term that does not use WO_EQUIV.
162651*/
162652SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
162653  WhereClause *pWC,     /* The WHERE clause to be searched */
162654  int iCur,             /* Cursor number of LHS */
162655  int iColumn,          /* Column number of LHS */
162656  Bitmask notReady,     /* RHS must not overlap with this mask */
162657  u32 op,               /* Mask of WO_xx values describing operator */
162658  Index *pIdx           /* Must be compatible with this index, if not NULL */
162659){
162660  WhereTerm *pResult = 0;
162661  WhereTerm *p;
162662  WhereScan scan;
162663
162664  p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
162665  op &= WO_EQ|WO_IS;
162666  while( p ){
162667    if( (p->prereqRight & notReady)==0 ){
162668      if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
162669        testcase( p->eOperator & WO_IS );
162670        return p;
162671      }
162672      if( pResult==0 ) pResult = p;
162673    }
162674    p = whereScanNext(&scan);
162675  }
162676  return pResult;
162677}
162678
162679/*
162680** This function searches pList for an entry that matches the iCol-th column
162681** of index pIdx.
162682**
162683** If such an expression is found, its index in pList->a[] is returned. If
162684** no expression is found, -1 is returned.
162685*/
162686static int findIndexCol(
162687  Parse *pParse,                  /* Parse context */
162688  ExprList *pList,                /* Expression list to search */
162689  int iBase,                      /* Cursor for table associated with pIdx */
162690  Index *pIdx,                    /* Index to match column of */
162691  int iCol                        /* Column of index to match */
162692){
162693  int i;
162694  const char *zColl = pIdx->azColl[iCol];
162695
162696  for(i=0; i<pList->nExpr; i++){
162697    Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr);
162698    if( ALWAYS(p!=0)
162699     && (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN)
162700     && p->iColumn==pIdx->aiColumn[iCol]
162701     && p->iTable==iBase
162702    ){
162703      CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
162704      if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
162705        return i;
162706      }
162707    }
162708  }
162709
162710  return -1;
162711}
162712
162713/*
162714** Return TRUE if the iCol-th column of index pIdx is NOT NULL
162715*/
162716static int indexColumnNotNull(Index *pIdx, int iCol){
162717  int j;
162718  assert( pIdx!=0 );
162719  assert( iCol>=0 && iCol<pIdx->nColumn );
162720  j = pIdx->aiColumn[iCol];
162721  if( j>=0 ){
162722    return pIdx->pTable->aCol[j].notNull;
162723  }else if( j==(-1) ){
162724    return 1;
162725  }else{
162726    assert( j==(-2) );
162727    return 0;  /* Assume an indexed expression can always yield a NULL */
162728
162729  }
162730}
162731
162732/*
162733** Return true if the DISTINCT expression-list passed as the third argument
162734** is redundant.
162735**
162736** A DISTINCT list is redundant if any subset of the columns in the
162737** DISTINCT list are collectively unique and individually non-null.
162738*/
162739static int isDistinctRedundant(
162740  Parse *pParse,            /* Parsing context */
162741  SrcList *pTabList,        /* The FROM clause */
162742  WhereClause *pWC,         /* The WHERE clause */
162743  ExprList *pDistinct       /* The result set that needs to be DISTINCT */
162744){
162745  Table *pTab;
162746  Index *pIdx;
162747  int i;
162748  int iBase;
162749
162750  /* If there is more than one table or sub-select in the FROM clause of
162751  ** this query, then it will not be possible to show that the DISTINCT
162752  ** clause is redundant. */
162753  if( pTabList->nSrc!=1 ) return 0;
162754  iBase = pTabList->a[0].iCursor;
162755  pTab = pTabList->a[0].pTab;
162756
162757  /* If any of the expressions is an IPK column on table iBase, then return
162758  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
162759  ** current SELECT is a correlated sub-query.
162760  */
162761  for(i=0; i<pDistinct->nExpr; i++){
162762    Expr *p = sqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr);
162763    if( NEVER(p==0) ) continue;
162764    if( p->op!=TK_COLUMN && p->op!=TK_AGG_COLUMN ) continue;
162765    if( p->iTable==iBase && p->iColumn<0 ) return 1;
162766  }
162767
162768  /* Loop through all indices on the table, checking each to see if it makes
162769  ** the DISTINCT qualifier redundant. It does so if:
162770  **
162771  **   1. The index is itself UNIQUE, and
162772  **
162773  **   2. All of the columns in the index are either part of the pDistinct
162774  **      list, or else the WHERE clause contains a term of the form "col=X",
162775  **      where X is a constant value. The collation sequences of the
162776  **      comparison and select-list expressions must match those of the index.
162777  **
162778  **   3. All of those index columns for which the WHERE clause does not
162779  **      contain a "col=X" term are subject to a NOT NULL constraint.
162780  */
162781  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
162782    if( !IsUniqueIndex(pIdx) ) continue;
162783    if( pIdx->pPartIdxWhere ) continue;
162784    for(i=0; i<pIdx->nKeyCol; i++){
162785      if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
162786        if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
162787        if( indexColumnNotNull(pIdx, i)==0 ) break;
162788      }
162789    }
162790    if( i==pIdx->nKeyCol ){
162791      /* This index implies that the DISTINCT qualifier is redundant. */
162792      return 1;
162793    }
162794  }
162795
162796  return 0;
162797}
162798
162799
162800/*
162801** Estimate the logarithm of the input value to base 2.
162802*/
162803static LogEst estLog(LogEst N){
162804  return N<=10 ? 0 : sqlite3LogEst(N) - 33;
162805}
162806
162807/*
162808** Convert OP_Column opcodes to OP_Copy in previously generated code.
162809**
162810** This routine runs over generated VDBE code and translates OP_Column
162811** opcodes into OP_Copy when the table is being accessed via co-routine
162812** instead of via table lookup.
162813**
162814** If the iAutoidxCur is not zero, then any OP_Rowid instructions on
162815** cursor iTabCur are transformed into OP_Sequence opcode for the
162816** iAutoidxCur cursor, in order to generate unique rowids for the
162817** automatic index being generated.
162818*/
162819static void translateColumnToCopy(
162820  Parse *pParse,      /* Parsing context */
162821  int iStart,         /* Translate from this opcode to the end */
162822  int iTabCur,        /* OP_Column/OP_Rowid references to this table */
162823  int iRegister,      /* The first column is in this register */
162824  int iAutoidxCur     /* If non-zero, cursor of autoindex being generated */
162825){
162826  Vdbe *v = pParse->pVdbe;
162827  VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
162828  int iEnd = sqlite3VdbeCurrentAddr(v);
162829  if( pParse->db->mallocFailed ) return;
162830  for(; iStart<iEnd; iStart++, pOp++){
162831    if( pOp->p1!=iTabCur ) continue;
162832    if( pOp->opcode==OP_Column ){
162833#ifdef SQLITE_DEBUG
162834      if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
162835        printf("TRANSLATE OP_Column to OP_Copy at %d\n", iStart);
162836      }
162837#endif
162838      pOp->opcode = OP_Copy;
162839      pOp->p1 = pOp->p2 + iRegister;
162840      pOp->p2 = pOp->p3;
162841      pOp->p3 = 0;
162842      pOp->p5 = 2;  /* Cause the MEM_Subtype flag to be cleared */
162843    }else if( pOp->opcode==OP_Rowid ){
162844#ifdef SQLITE_DEBUG
162845      if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
162846        printf("TRANSLATE OP_Rowid to OP_Sequence at %d\n", iStart);
162847      }
162848#endif
162849      pOp->opcode = OP_Sequence;
162850      pOp->p1 = iAutoidxCur;
162851#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
162852      if( iAutoidxCur==0 ){
162853        pOp->opcode = OP_Null;
162854        pOp->p3 = 0;
162855      }
162856#endif
162857    }
162858  }
162859}
162860
162861/*
162862** Two routines for printing the content of an sqlite3_index_info
162863** structure.  Used for testing and debugging only.  If neither
162864** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
162865** are no-ops.
162866*/
162867#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
162868static void whereTraceIndexInfoInputs(
162869  sqlite3_index_info *p,   /* The IndexInfo object */
162870  Table *pTab              /* The TABLE that is the virtual table */
162871){
162872  int i;
162873  if( (sqlite3WhereTrace & 0x10)==0 ) return;
162874  sqlite3DebugPrintf("sqlite3_index_info inputs for %s:\n", pTab->zName);
162875  for(i=0; i<p->nConstraint; i++){
162876    sqlite3DebugPrintf(
162877       "  constraint[%d]: col=%d termid=%d op=%d usabled=%d collseq=%s\n",
162878       i,
162879       p->aConstraint[i].iColumn,
162880       p->aConstraint[i].iTermOffset,
162881       p->aConstraint[i].op,
162882       p->aConstraint[i].usable,
162883       sqlite3_vtab_collation(p,i));
162884  }
162885  for(i=0; i<p->nOrderBy; i++){
162886    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
162887       i,
162888       p->aOrderBy[i].iColumn,
162889       p->aOrderBy[i].desc);
162890  }
162891}
162892static void whereTraceIndexInfoOutputs(
162893  sqlite3_index_info *p,   /* The IndexInfo object */
162894  Table *pTab              /* The TABLE that is the virtual table */
162895){
162896  int i;
162897  if( (sqlite3WhereTrace & 0x10)==0 ) return;
162898  sqlite3DebugPrintf("sqlite3_index_info outputs for %s:\n", pTab->zName);
162899  for(i=0; i<p->nConstraint; i++){
162900    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
162901       i,
162902       p->aConstraintUsage[i].argvIndex,
162903       p->aConstraintUsage[i].omit);
162904  }
162905  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
162906  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
162907  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
162908  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
162909  sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
162910}
162911#else
162912#define whereTraceIndexInfoInputs(A,B)
162913#define whereTraceIndexInfoOutputs(A,B)
162914#endif
162915
162916/*
162917** We know that pSrc is an operand of an outer join.  Return true if
162918** pTerm is a constraint that is compatible with that join.
162919**
162920** pTerm must be EP_OuterON if pSrc is the right operand of an
162921** outer join.  pTerm can be either EP_OuterON or EP_InnerON if pSrc
162922** is the left operand of a RIGHT join.
162923**
162924** See https://sqlite.org/forum/forumpost/206d99a16dd9212f
162925** for an example of a WHERE clause constraints that may not be used on
162926** the right table of a RIGHT JOIN because the constraint implies a
162927** not-NULL condition on the left table of the RIGHT JOIN.
162928*/
162929static int constraintCompatibleWithOuterJoin(
162930  const WhereTerm *pTerm,       /* WHERE clause term to check */
162931  const SrcItem *pSrc           /* Table we are trying to access */
162932){
162933  assert( (pSrc->fg.jointype&(JT_LEFT|JT_LTORJ|JT_RIGHT))!=0 ); /* By caller */
162934  testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LEFT );
162935  testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LTORJ );
162936  testcase( ExprHasProperty(pTerm->pExpr, EP_OuterON) )
162937  testcase( ExprHasProperty(pTerm->pExpr, EP_InnerON) );
162938  if( !ExprHasProperty(pTerm->pExpr, EP_OuterON|EP_InnerON)
162939   || pTerm->pExpr->w.iJoin != pSrc->iCursor
162940  ){
162941    return 0;
162942  }
162943  if( (pSrc->fg.jointype & (JT_LEFT|JT_RIGHT))!=0
162944   && ExprHasProperty(pTerm->pExpr, EP_InnerON)
162945  ){
162946    return 0;
162947  }
162948  return 1;
162949}
162950
162951
162952
162953#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
162954/*
162955** Return TRUE if the WHERE clause term pTerm is of a form where it
162956** could be used with an index to access pSrc, assuming an appropriate
162957** index existed.
162958*/
162959static int termCanDriveIndex(
162960  const WhereTerm *pTerm,        /* WHERE clause term to check */
162961  const SrcItem *pSrc,           /* Table we are trying to access */
162962  const Bitmask notReady         /* Tables in outer loops of the join */
162963){
162964  char aff;
162965  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
162966  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
162967  assert( (pSrc->fg.jointype & JT_RIGHT)==0 );
162968  if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
162969   && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
162970  ){
162971    return 0;  /* See https://sqlite.org/forum/forumpost/51e6959f61 */
162972  }
162973  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
162974  assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
162975  if( pTerm->u.x.leftColumn<0 ) return 0;
162976  aff = pSrc->pTab->aCol[pTerm->u.x.leftColumn].affinity;
162977  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
162978  testcase( pTerm->pExpr->op==TK_IS );
162979  return 1;
162980}
162981#endif
162982
162983
162984#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
162985
162986#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
162987/*
162988** Argument pIdx represents an automatic index that the current statement
162989** will create and populate. Add an OP_Explain with text of the form:
162990**
162991**     CREATE AUTOMATIC INDEX ON <table>(<cols>) [WHERE <expr>]
162992**
162993** This is only required if sqlite3_stmt_scanstatus() is enabled, to
162994** associate an SQLITE_SCANSTAT_NCYCLE and SQLITE_SCANSTAT_NLOOP
162995** values with. In order to avoid breaking legacy code and test cases,
162996** the OP_Explain is not added if this is an EXPLAIN QUERY PLAN command.
162997*/
162998static void explainAutomaticIndex(
162999  Parse *pParse,
163000  Index *pIdx,                    /* Automatic index to explain */
163001  int bPartial,                   /* True if pIdx is a partial index */
163002  int *pAddrExplain               /* OUT: Address of OP_Explain */
163003){
163004  if( IS_STMT_SCANSTATUS(pParse->db) && pParse->explain!=2 ){
163005    Table *pTab = pIdx->pTable;
163006    const char *zSep = "";
163007    char *zText = 0;
163008    int ii = 0;
163009    sqlite3_str *pStr = sqlite3_str_new(pParse->db);
163010    sqlite3_str_appendf(pStr,"CREATE AUTOMATIC INDEX ON %s(", pTab->zName);
163011    assert( pIdx->nColumn>1 );
163012    assert( pIdx->aiColumn[pIdx->nColumn-1]==XN_ROWID );
163013    for(ii=0; ii<(pIdx->nColumn-1); ii++){
163014      const char *zName = 0;
163015      int iCol = pIdx->aiColumn[ii];
163016
163017      zName = pTab->aCol[iCol].zCnName;
163018      sqlite3_str_appendf(pStr, "%s%s", zSep, zName);
163019      zSep = ", ";
163020    }
163021    zText = sqlite3_str_finish(pStr);
163022    if( zText==0 ){
163023      sqlite3OomFault(pParse->db);
163024    }else{
163025      *pAddrExplain = sqlite3VdbeExplain(
163026          pParse, 0, "%s)%s", zText, (bPartial ? " WHERE <expr>" : "")
163027      );
163028      sqlite3_free(zText);
163029    }
163030  }
163031}
163032#else
163033# define explainAutomaticIndex(a,b,c,d)
163034#endif
163035
163036/*
163037** Generate code to construct the Index object for an automatic index
163038** and to set up the WhereLevel object pLevel so that the code generator
163039** makes use of the automatic index.
163040*/
163041static SQLITE_NOINLINE void constructAutomaticIndex(
163042  Parse *pParse,              /* The parsing context */
163043  WhereClause *pWC,           /* The WHERE clause */
163044  const Bitmask notReady,     /* Mask of cursors that are not available */
163045  WhereLevel *pLevel          /* Write new index here */
163046){
163047  int nKeyCol;                /* Number of columns in the constructed index */
163048  WhereTerm *pTerm;           /* A single term of the WHERE clause */
163049  WhereTerm *pWCEnd;          /* End of pWC->a[] */
163050  Index *pIdx;                /* Object describing the transient index */
163051  Vdbe *v;                    /* Prepared statement under construction */
163052  int addrInit;               /* Address of the initialization bypass jump */
163053  Table *pTable;              /* The table being indexed */
163054  int addrTop;                /* Top of the index fill loop */
163055  int regRecord;              /* Register holding an index record */
163056  int n;                      /* Column counter */
163057  int i;                      /* Loop counter */
163058  int mxBitCol;               /* Maximum column in pSrc->colUsed */
163059  CollSeq *pColl;             /* Collating sequence to on a column */
163060  WhereLoop *pLoop;           /* The Loop object */
163061  char *zNotUsed;             /* Extra space on the end of pIdx */
163062  Bitmask idxCols;            /* Bitmap of columns used for indexing */
163063  Bitmask extraCols;          /* Bitmap of additional columns */
163064  u8 sentWarning = 0;         /* True if a warning has been issued */
163065  u8 useBloomFilter = 0;      /* True to also add a Bloom filter */
163066  Expr *pPartial = 0;         /* Partial Index Expression */
163067  int iContinue = 0;          /* Jump here to skip excluded rows */
163068  SrcList *pTabList;          /* The complete FROM clause */
163069  SrcItem *pSrc;              /* The FROM clause term to get the next index */
163070  int addrCounter = 0;        /* Address where integer counter is initialized */
163071  int regBase;                /* Array of registers where record is assembled */
163072#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
163073  int addrExp = 0;            /* Address of OP_Explain */
163074#endif
163075
163076  /* Generate code to skip over the creation and initialization of the
163077  ** transient index on 2nd and subsequent iterations of the loop. */
163078  v = pParse->pVdbe;
163079  assert( v!=0 );
163080  addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
163081
163082  /* Count the number of columns that will be added to the index
163083  ** and used to match WHERE clause constraints */
163084  nKeyCol = 0;
163085  pTabList = pWC->pWInfo->pTabList;
163086  pSrc = &pTabList->a[pLevel->iFrom];
163087  pTable = pSrc->pTab;
163088  pWCEnd = &pWC->a[pWC->nTerm];
163089  pLoop = pLevel->pWLoop;
163090  idxCols = 0;
163091  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
163092    Expr *pExpr = pTerm->pExpr;
163093    /* Make the automatic index a partial index if there are terms in the
163094    ** WHERE clause (or the ON clause of a LEFT join) that constrain which
163095    ** rows of the target table (pSrc) that can be used. */
163096    if( (pTerm->wtFlags & TERM_VIRTUAL)==0
163097     && sqlite3ExprIsSingleTableConstraint(pExpr, pTabList, pLevel->iFrom, 0)
163098    ){
163099      pPartial = sqlite3ExprAnd(pParse, pPartial,
163100                                sqlite3ExprDup(pParse->db, pExpr, 0));
163101    }
163102    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
163103      int iCol;
163104      Bitmask cMask;
163105      assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
163106      iCol = pTerm->u.x.leftColumn;
163107      cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
163108      testcase( iCol==BMS );
163109      testcase( iCol==BMS-1 );
163110      if( !sentWarning ){
163111        sqlite3_log(SQLITE_WARNING_AUTOINDEX,
163112            "automatic index on %s(%s)", pTable->zName,
163113            pTable->aCol[iCol].zCnName);
163114        sentWarning = 1;
163115      }
163116      if( (idxCols & cMask)==0 ){
163117        if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
163118          goto end_auto_index_create;
163119        }
163120        pLoop->aLTerm[nKeyCol++] = pTerm;
163121        idxCols |= cMask;
163122      }
163123    }
163124  }
163125  assert( nKeyCol>0 || pParse->db->mallocFailed );
163126  pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
163127  pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
163128                     | WHERE_AUTO_INDEX;
163129
163130  /* Count the number of additional columns needed to create a
163131  ** covering index.  A "covering index" is an index that contains all
163132  ** columns that are needed by the query.  With a covering index, the
163133  ** original table never needs to be accessed.  Automatic indices must
163134  ** be a covering index because the index will not be updated if the
163135  ** original table changes and the index and table cannot both be used
163136  ** if they go out of sync.
163137  */
163138  if( IsView(pTable) ){
163139    extraCols = ALLBITS & ~idxCols;
163140  }else{
163141    extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
163142  }
163143  mxBitCol = MIN(BMS-1,pTable->nCol);
163144  testcase( pTable->nCol==BMS-1 );
163145  testcase( pTable->nCol==BMS-2 );
163146  for(i=0; i<mxBitCol; i++){
163147    if( extraCols & MASKBIT(i) ) nKeyCol++;
163148  }
163149  if( pSrc->colUsed & MASKBIT(BMS-1) ){
163150    nKeyCol += pTable->nCol - BMS + 1;
163151  }
163152
163153  /* Construct the Index object to describe this index */
163154  pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
163155  if( pIdx==0 ) goto end_auto_index_create;
163156  pLoop->u.btree.pIndex = pIdx;
163157  pIdx->zName = "auto-index";
163158  pIdx->pTable = pTable;
163159  n = 0;
163160  idxCols = 0;
163161  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
163162    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
163163      int iCol;
163164      Bitmask cMask;
163165      assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
163166      iCol = pTerm->u.x.leftColumn;
163167      cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
163168      testcase( iCol==BMS-1 );
163169      testcase( iCol==BMS );
163170      if( (idxCols & cMask)==0 ){
163171        Expr *pX = pTerm->pExpr;
163172        idxCols |= cMask;
163173        pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
163174        pColl = sqlite3ExprCompareCollSeq(pParse, pX);
163175        assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
163176        pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
163177        n++;
163178        if( ALWAYS(pX->pLeft!=0)
163179         && sqlite3ExprAffinity(pX->pLeft)!=SQLITE_AFF_TEXT
163180        ){
163181          /* TUNING: only use a Bloom filter on an automatic index
163182          ** if one or more key columns has the ability to hold numeric
163183          ** values, since strings all have the same hash in the Bloom
163184          ** filter implementation and hence a Bloom filter on a text column
163185          ** is not usually helpful. */
163186          useBloomFilter = 1;
163187        }
163188      }
163189    }
163190  }
163191  assert( (u32)n==pLoop->u.btree.nEq );
163192
163193  /* Add additional columns needed to make the automatic index into
163194  ** a covering index */
163195  for(i=0; i<mxBitCol; i++){
163196    if( extraCols & MASKBIT(i) ){
163197      pIdx->aiColumn[n] = i;
163198      pIdx->azColl[n] = sqlite3StrBINARY;
163199      n++;
163200    }
163201  }
163202  if( pSrc->colUsed & MASKBIT(BMS-1) ){
163203    for(i=BMS-1; i<pTable->nCol; i++){
163204      pIdx->aiColumn[n] = i;
163205      pIdx->azColl[n] = sqlite3StrBINARY;
163206      n++;
163207    }
163208  }
163209  assert( n==nKeyCol );
163210  pIdx->aiColumn[n] = XN_ROWID;
163211  pIdx->azColl[n] = sqlite3StrBINARY;
163212
163213  /* Create the automatic index */
163214  explainAutomaticIndex(pParse, pIdx, pPartial!=0, &addrExp);
163215  assert( pLevel->iIdxCur>=0 );
163216  pLevel->iIdxCur = pParse->nTab++;
163217  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
163218  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
163219  VdbeComment((v, "for %s", pTable->zName));
163220  if( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) && useBloomFilter ){
163221    sqlite3WhereExplainBloomFilter(pParse, pWC->pWInfo, pLevel);
163222    pLevel->regFilter = ++pParse->nMem;
163223    sqlite3VdbeAddOp2(v, OP_Blob, 10000, pLevel->regFilter);
163224  }
163225
163226  /* Fill the automatic index with content */
163227  assert( pSrc == &pWC->pWInfo->pTabList->a[pLevel->iFrom] );
163228  if( pSrc->fg.viaCoroutine ){
163229    int regYield = pSrc->regReturn;
163230    addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
163231    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pSrc->addrFillSub);
163232    addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
163233    VdbeCoverage(v);
163234    VdbeComment((v, "next row of %s", pSrc->pTab->zName));
163235  }else{
163236    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
163237  }
163238  if( pPartial ){
163239    iContinue = sqlite3VdbeMakeLabel(pParse);
163240    sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
163241    pLoop->wsFlags |= WHERE_PARTIALIDX;
163242  }
163243  regRecord = sqlite3GetTempReg(pParse);
163244  regBase = sqlite3GenerateIndexKey(
163245      pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
163246  );
163247  if( pLevel->regFilter ){
163248    sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0,
163249                         regBase, pLoop->u.btree.nEq);
163250  }
163251  sqlite3VdbeScanStatusCounters(v, addrExp, addrExp, sqlite3VdbeCurrentAddr(v));
163252  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
163253  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
163254  if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
163255  if( pSrc->fg.viaCoroutine ){
163256    sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
163257    testcase( pParse->db->mallocFailed );
163258    assert( pLevel->iIdxCur>0 );
163259    translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
163260                          pSrc->regResult, pLevel->iIdxCur);
163261    sqlite3VdbeGoto(v, addrTop);
163262    pSrc->fg.viaCoroutine = 0;
163263  }else{
163264    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
163265    sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
163266  }
163267  sqlite3VdbeJumpHere(v, addrTop);
163268  sqlite3ReleaseTempReg(pParse, regRecord);
163269
163270  /* Jump here when skipping the initialization */
163271  sqlite3VdbeJumpHere(v, addrInit);
163272  sqlite3VdbeScanStatusRange(v, addrExp, addrExp, -1);
163273
163274end_auto_index_create:
163275  sqlite3ExprDelete(pParse->db, pPartial);
163276}
163277#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
163278
163279/*
163280** Generate bytecode that will initialize a Bloom filter that is appropriate
163281** for pLevel.
163282**
163283** If there are inner loops within pLevel that have the WHERE_BLOOMFILTER
163284** flag set, initialize a Bloomfilter for them as well.  Except don't do
163285** this recursive initialization if the SQLITE_BloomPulldown optimization has
163286** been turned off.
163287**
163288** When the Bloom filter is initialized, the WHERE_BLOOMFILTER flag is cleared
163289** from the loop, but the regFilter value is set to a register that implements
163290** the Bloom filter.  When regFilter is positive, the
163291** sqlite3WhereCodeOneLoopStart() will generate code to test the Bloom filter
163292** and skip the subsequence B-Tree seek if the Bloom filter indicates that
163293** no matching rows exist.
163294**
163295** This routine may only be called if it has previously been determined that
163296** the loop would benefit from a Bloom filter, and the WHERE_BLOOMFILTER bit
163297** is set.
163298*/
163299static SQLITE_NOINLINE void sqlite3ConstructBloomFilter(
163300  WhereInfo *pWInfo,    /* The WHERE clause */
163301  int iLevel,           /* Index in pWInfo->a[] that is pLevel */
163302  WhereLevel *pLevel,   /* Make a Bloom filter for this FROM term */
163303  Bitmask notReady      /* Loops that are not ready */
163304){
163305  int addrOnce;                        /* Address of opening OP_Once */
163306  int addrTop;                         /* Address of OP_Rewind */
163307  int addrCont;                        /* Jump here to skip a row */
163308  const WhereTerm *pTerm;              /* For looping over WHERE clause terms */
163309  const WhereTerm *pWCEnd;             /* Last WHERE clause term */
163310  Parse *pParse = pWInfo->pParse;      /* Parsing context */
163311  Vdbe *v = pParse->pVdbe;             /* VDBE under construction */
163312  WhereLoop *pLoop = pLevel->pWLoop;   /* The loop being coded */
163313  int iCur;                            /* Cursor for table getting the filter */
163314  IndexedExpr *saved_pIdxEpr;          /* saved copy of Parse.pIdxEpr */
163315  IndexedExpr *saved_pIdxPartExpr;     /* saved copy of Parse.pIdxPartExpr */
163316
163317  saved_pIdxEpr = pParse->pIdxEpr;
163318  saved_pIdxPartExpr = pParse->pIdxPartExpr;
163319  pParse->pIdxEpr = 0;
163320  pParse->pIdxPartExpr = 0;
163321
163322  assert( pLoop!=0 );
163323  assert( v!=0 );
163324  assert( pLoop->wsFlags & WHERE_BLOOMFILTER );
163325  assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 );
163326
163327  addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
163328  do{
163329    const SrcList *pTabList;
163330    const SrcItem *pItem;
163331    const Table *pTab;
163332    u64 sz;
163333    int iSrc;
163334    sqlite3WhereExplainBloomFilter(pParse, pWInfo, pLevel);
163335    addrCont = sqlite3VdbeMakeLabel(pParse);
163336    iCur = pLevel->iTabCur;
163337    pLevel->regFilter = ++pParse->nMem;
163338
163339    /* The Bloom filter is a Blob held in a register.  Initialize it
163340    ** to zero-filled blob of at least 80K bits, but maybe more if the
163341    ** estimated size of the table is larger.  We could actually
163342    ** measure the size of the table at run-time using OP_Count with
163343    ** P3==1 and use that value to initialize the blob.  But that makes
163344    ** testing complicated.  By basing the blob size on the value in the
163345    ** sqlite_stat1 table, testing is much easier.
163346    */
163347    pTabList = pWInfo->pTabList;
163348    iSrc = pLevel->iFrom;
163349    pItem = &pTabList->a[iSrc];
163350    assert( pItem!=0 );
163351    pTab = pItem->pTab;
163352    assert( pTab!=0 );
163353    sz = sqlite3LogEstToInt(pTab->nRowLogEst);
163354    if( sz<10000 ){
163355      sz = 10000;
163356    }else if( sz>10000000 ){
163357      sz = 10000000;
163358    }
163359    sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter);
163360
163361    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
163362    pWCEnd = &pWInfo->sWC.a[pWInfo->sWC.nTerm];
163363    for(pTerm=pWInfo->sWC.a; pTerm<pWCEnd; pTerm++){
163364      Expr *pExpr = pTerm->pExpr;
163365      if( (pTerm->wtFlags & TERM_VIRTUAL)==0
163366       && sqlite3ExprIsSingleTableConstraint(pExpr, pTabList, iSrc, 0)
163367      ){
163368        sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
163369      }
163370    }
163371    if( pLoop->wsFlags & WHERE_IPK ){
163372      int r1 = sqlite3GetTempReg(pParse);
163373      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
163374      sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, 1);
163375      sqlite3ReleaseTempReg(pParse, r1);
163376    }else{
163377      Index *pIdx = pLoop->u.btree.pIndex;
163378      int n = pLoop->u.btree.nEq;
163379      int r1 = sqlite3GetTempRange(pParse, n);
163380      int jj;
163381      for(jj=0; jj<n; jj++){
163382        assert( pIdx->pTable==pItem->pTab );
163383        sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iCur, jj, r1+jj);
163384      }
163385      sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, n);
163386      sqlite3ReleaseTempRange(pParse, r1, n);
163387    }
163388    sqlite3VdbeResolveLabel(v, addrCont);
163389    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
163390    VdbeCoverage(v);
163391    sqlite3VdbeJumpHere(v, addrTop);
163392    pLoop->wsFlags &= ~WHERE_BLOOMFILTER;
163393    if( OptimizationDisabled(pParse->db, SQLITE_BloomPulldown) ) break;
163394    while( ++iLevel < pWInfo->nLevel ){
163395      const SrcItem *pTabItem;
163396      pLevel = &pWInfo->a[iLevel];
163397      pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
163398      if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ) ) continue;
163399      pLoop = pLevel->pWLoop;
163400      if( NEVER(pLoop==0) ) continue;
163401      if( pLoop->prereq & notReady ) continue;
163402      if( (pLoop->wsFlags & (WHERE_BLOOMFILTER|WHERE_COLUMN_IN))
163403                 ==WHERE_BLOOMFILTER
163404      ){
163405        /* This is a candidate for bloom-filter pull-down (early evaluation).
163406        ** The test that WHERE_COLUMN_IN is omitted is important, as we are
163407        ** not able to do early evaluation of bloom filters that make use of
163408        ** the IN operator */
163409        break;
163410      }
163411    }
163412  }while( iLevel < pWInfo->nLevel );
163413  sqlite3VdbeJumpHere(v, addrOnce);
163414  pParse->pIdxEpr = saved_pIdxEpr;
163415  pParse->pIdxPartExpr = saved_pIdxPartExpr;
163416}
163417
163418
163419#ifndef SQLITE_OMIT_VIRTUALTABLE
163420/*
163421** Allocate and populate an sqlite3_index_info structure. It is the
163422** responsibility of the caller to eventually release the structure
163423** by passing the pointer returned by this function to freeIndexInfo().
163424*/
163425static sqlite3_index_info *allocateIndexInfo(
163426  WhereInfo *pWInfo,              /* The WHERE clause */
163427  WhereClause *pWC,               /* The WHERE clause being analyzed */
163428  Bitmask mUnusable,              /* Ignore terms with these prereqs */
163429  SrcItem *pSrc,                  /* The FROM clause term that is the vtab */
163430  u16 *pmNoOmit                   /* Mask of terms not to omit */
163431){
163432  int i, j;
163433  int nTerm;
163434  Parse *pParse = pWInfo->pParse;
163435  struct sqlite3_index_constraint *pIdxCons;
163436  struct sqlite3_index_orderby *pIdxOrderBy;
163437  struct sqlite3_index_constraint_usage *pUsage;
163438  struct HiddenIndexInfo *pHidden;
163439  WhereTerm *pTerm;
163440  int nOrderBy;
163441  sqlite3_index_info *pIdxInfo;
163442  u16 mNoOmit = 0;
163443  const Table *pTab;
163444  int eDistinct = 0;
163445  ExprList *pOrderBy = pWInfo->pOrderBy;
163446
163447  assert( pSrc!=0 );
163448  pTab = pSrc->pTab;
163449  assert( pTab!=0 );
163450  assert( IsVirtual(pTab) );
163451
163452  /* Find all WHERE clause constraints referring to this virtual table.
163453  ** Mark each term with the TERM_OK flag.  Set nTerm to the number of
163454  ** terms found.
163455  */
163456  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
163457    pTerm->wtFlags &= ~TERM_OK;
163458    if( pTerm->leftCursor != pSrc->iCursor ) continue;
163459    if( pTerm->prereqRight & mUnusable ) continue;
163460    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
163461    testcase( pTerm->eOperator & WO_IN );
163462    testcase( pTerm->eOperator & WO_ISNULL );
163463    testcase( pTerm->eOperator & WO_IS );
163464    testcase( pTerm->eOperator & WO_ALL );
163465    if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
163466    if( pTerm->wtFlags & TERM_VNULL ) continue;
163467
163468    assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
163469    assert( pTerm->u.x.leftColumn>=XN_ROWID );
163470    assert( pTerm->u.x.leftColumn<pTab->nCol );
163471    if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
163472     && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
163473    ){
163474      continue;
163475    }
163476    nTerm++;
163477    pTerm->wtFlags |= TERM_OK;
163478  }
163479
163480  /* If the ORDER BY clause contains only columns in the current
163481  ** virtual table then allocate space for the aOrderBy part of
163482  ** the sqlite3_index_info structure.
163483  */
163484  nOrderBy = 0;
163485  if( pOrderBy ){
163486    int n = pOrderBy->nExpr;
163487    for(i=0; i<n; i++){
163488      Expr *pExpr = pOrderBy->a[i].pExpr;
163489      Expr *pE2;
163490
163491      /* Skip over constant terms in the ORDER BY clause */
163492      if( sqlite3ExprIsConstant(0, pExpr) ){
163493        continue;
163494      }
163495
163496      /* Virtual tables are unable to deal with NULLS FIRST */
163497      if( pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL ) break;
163498
163499      /* First case - a direct column references without a COLLATE operator */
163500      if( pExpr->op==TK_COLUMN && pExpr->iTable==pSrc->iCursor ){
163501        assert( pExpr->iColumn>=XN_ROWID && pExpr->iColumn<pTab->nCol );
163502        continue;
163503      }
163504
163505      /* 2nd case - a column reference with a COLLATE operator.  Only match
163506      ** of the COLLATE operator matches the collation of the column. */
163507      if( pExpr->op==TK_COLLATE
163508       && (pE2 = pExpr->pLeft)->op==TK_COLUMN
163509       && pE2->iTable==pSrc->iCursor
163510      ){
163511        const char *zColl;  /* The collating sequence name */
163512        assert( !ExprHasProperty(pExpr, EP_IntValue) );
163513        assert( pExpr->u.zToken!=0 );
163514        assert( pE2->iColumn>=XN_ROWID && pE2->iColumn<pTab->nCol );
163515        pExpr->iColumn = pE2->iColumn;
163516        if( pE2->iColumn<0 ) continue;  /* Collseq does not matter for rowid */
163517        zColl = sqlite3ColumnColl(&pTab->aCol[pE2->iColumn]);
163518        if( zColl==0 ) zColl = sqlite3StrBINARY;
163519        if( sqlite3_stricmp(pExpr->u.zToken, zColl)==0 ) continue;
163520      }
163521
163522      /* No matches cause a break out of the loop */
163523      break;
163524    }
163525    if( i==n ){
163526      nOrderBy = n;
163527      if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY) && !pSrc->fg.rowidUsed ){
163528        eDistinct = 2 + ((pWInfo->wctrlFlags & WHERE_SORTBYGROUP)!=0);
163529      }else if( pWInfo->wctrlFlags & WHERE_GROUPBY ){
163530        eDistinct = 1;
163531      }
163532    }
163533  }
163534
163535  /* Allocate the sqlite3_index_info structure
163536  */
163537  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
163538                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
163539                           + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden)
163540                           + sizeof(sqlite3_value*)*nTerm );
163541  if( pIdxInfo==0 ){
163542    sqlite3ErrorMsg(pParse, "out of memory");
163543    return 0;
163544  }
163545  pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
163546  pIdxCons = (struct sqlite3_index_constraint*)&pHidden->aRhs[nTerm];
163547  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
163548  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
163549  pIdxInfo->aConstraint = pIdxCons;
163550  pIdxInfo->aOrderBy = pIdxOrderBy;
163551  pIdxInfo->aConstraintUsage = pUsage;
163552  pHidden->pWC = pWC;
163553  pHidden->pParse = pParse;
163554  pHidden->eDistinct = eDistinct;
163555  pHidden->mIn = 0;
163556  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
163557    u16 op;
163558    if( (pTerm->wtFlags & TERM_OK)==0 ) continue;
163559    pIdxCons[j].iColumn = pTerm->u.x.leftColumn;
163560    pIdxCons[j].iTermOffset = i;
163561    op = pTerm->eOperator & WO_ALL;
163562    if( op==WO_IN ){
163563      if( (pTerm->wtFlags & TERM_SLICE)==0 ){
163564        pHidden->mIn |= SMASKBIT32(j);
163565      }
163566      op = WO_EQ;
163567    }
163568    if( op==WO_AUX ){
163569      pIdxCons[j].op = pTerm->eMatchOp;
163570    }else if( op & (WO_ISNULL|WO_IS) ){
163571      if( op==WO_ISNULL ){
163572        pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
163573      }else{
163574        pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
163575      }
163576    }else{
163577      pIdxCons[j].op = (u8)op;
163578      /* The direct assignment in the previous line is possible only because
163579      ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
163580      ** following asserts verify this fact. */
163581      assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
163582      assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
163583      assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
163584      assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
163585      assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
163586      assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
163587
163588      if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
163589       && sqlite3ExprIsVector(pTerm->pExpr->pRight)
163590      ){
163591        testcase( j!=i );
163592        if( j<16 ) mNoOmit |= (1 << j);
163593        if( op==WO_LT ) pIdxCons[j].op = WO_LE;
163594        if( op==WO_GT ) pIdxCons[j].op = WO_GE;
163595      }
163596    }
163597
163598    j++;
163599  }
163600  assert( j==nTerm );
163601  pIdxInfo->nConstraint = j;
163602  for(i=j=0; i<nOrderBy; i++){
163603    Expr *pExpr = pOrderBy->a[i].pExpr;
163604    if( sqlite3ExprIsConstant(0, pExpr) ) continue;
163605    assert( pExpr->op==TK_COLUMN
163606         || (pExpr->op==TK_COLLATE && pExpr->pLeft->op==TK_COLUMN
163607              && pExpr->iColumn==pExpr->pLeft->iColumn) );
163608    pIdxOrderBy[j].iColumn = pExpr->iColumn;
163609    pIdxOrderBy[j].desc = pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC;
163610    j++;
163611  }
163612  pIdxInfo->nOrderBy = j;
163613
163614  *pmNoOmit = mNoOmit;
163615  return pIdxInfo;
163616}
163617
163618/*
163619** Free an sqlite3_index_info structure allocated by allocateIndexInfo()
163620** and possibly modified by xBestIndex methods.
163621*/
163622static void freeIndexInfo(sqlite3 *db, sqlite3_index_info *pIdxInfo){
163623  HiddenIndexInfo *pHidden;
163624  int i;
163625  assert( pIdxInfo!=0 );
163626  pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
163627  assert( pHidden->pParse!=0 );
163628  assert( pHidden->pParse->db==db );
163629  for(i=0; i<pIdxInfo->nConstraint; i++){
163630    sqlite3ValueFree(pHidden->aRhs[i]); /* IMP: R-14553-25174 */
163631    pHidden->aRhs[i] = 0;
163632  }
163633  sqlite3DbFree(db, pIdxInfo);
163634}
163635
163636/*
163637** The table object reference passed as the second argument to this function
163638** must represent a virtual table. This function invokes the xBestIndex()
163639** method of the virtual table with the sqlite3_index_info object that
163640** comes in as the 3rd argument to this function.
163641**
163642** If an error occurs, pParse is populated with an error message and an
163643** appropriate error code is returned.  A return of SQLITE_CONSTRAINT from
163644** xBestIndex is not considered an error.  SQLITE_CONSTRAINT indicates that
163645** the current configuration of "unusable" flags in sqlite3_index_info can
163646** not result in a valid plan.
163647**
163648** Whether or not an error is returned, it is the responsibility of the
163649** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
163650** that this is required.
163651*/
163652static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
163653  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
163654  int rc;
163655
163656  whereTraceIndexInfoInputs(p, pTab);
163657  pParse->db->nSchemaLock++;
163658  rc = pVtab->pModule->xBestIndex(pVtab, p);
163659  pParse->db->nSchemaLock--;
163660  whereTraceIndexInfoOutputs(p, pTab);
163661
163662  if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
163663    if( rc==SQLITE_NOMEM ){
163664      sqlite3OomFault(pParse->db);
163665    }else if( !pVtab->zErrMsg ){
163666      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
163667    }else{
163668      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
163669    }
163670  }
163671  if( pTab->u.vtab.p->bAllSchemas ){
163672    sqlite3VtabUsesAllSchemas(pParse);
163673  }
163674  sqlite3_free(pVtab->zErrMsg);
163675  pVtab->zErrMsg = 0;
163676  return rc;
163677}
163678#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
163679
163680#ifdef SQLITE_ENABLE_STAT4
163681/*
163682** Estimate the location of a particular key among all keys in an
163683** index.  Store the results in aStat as follows:
163684**
163685**    aStat[0]      Est. number of rows less than pRec
163686**    aStat[1]      Est. number of rows equal to pRec
163687**
163688** Return the index of the sample that is the smallest sample that
163689** is greater than or equal to pRec. Note that this index is not an index
163690** into the aSample[] array - it is an index into a virtual set of samples
163691** based on the contents of aSample[] and the number of fields in record
163692** pRec.
163693*/
163694static int whereKeyStats(
163695  Parse *pParse,              /* Database connection */
163696  Index *pIdx,                /* Index to consider domain of */
163697  UnpackedRecord *pRec,       /* Vector of values to consider */
163698  int roundUp,                /* Round up if true.  Round down if false */
163699  tRowcnt *aStat              /* OUT: stats written here */
163700){
163701  IndexSample *aSample = pIdx->aSample;
163702  int iCol;                   /* Index of required stats in anEq[] etc. */
163703  int i;                      /* Index of first sample >= pRec */
163704  int iSample;                /* Smallest sample larger than or equal to pRec */
163705  int iMin = 0;               /* Smallest sample not yet tested */
163706  int iTest;                  /* Next sample to test */
163707  int res;                    /* Result of comparison operation */
163708  int nField;                 /* Number of fields in pRec */
163709  tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
163710
163711#ifndef SQLITE_DEBUG
163712  UNUSED_PARAMETER( pParse );
163713#endif
163714  assert( pRec!=0 );
163715  assert( pIdx->nSample>0 );
163716  assert( pRec->nField>0 );
163717
163718
163719  /* Do a binary search to find the first sample greater than or equal
163720  ** to pRec. If pRec contains a single field, the set of samples to search
163721  ** is simply the aSample[] array. If the samples in aSample[] contain more
163722  ** than one fields, all fields following the first are ignored.
163723  **
163724  ** If pRec contains N fields, where N is more than one, then as well as the
163725  ** samples in aSample[] (truncated to N fields), the search also has to
163726  ** consider prefixes of those samples. For example, if the set of samples
163727  ** in aSample is:
163728  **
163729  **     aSample[0] = (a, 5)
163730  **     aSample[1] = (a, 10)
163731  **     aSample[2] = (b, 5)
163732  **     aSample[3] = (c, 100)
163733  **     aSample[4] = (c, 105)
163734  **
163735  ** Then the search space should ideally be the samples above and the
163736  ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
163737  ** the code actually searches this set:
163738  **
163739  **     0: (a)
163740  **     1: (a, 5)
163741  **     2: (a, 10)
163742  **     3: (a, 10)
163743  **     4: (b)
163744  **     5: (b, 5)
163745  **     6: (c)
163746  **     7: (c, 100)
163747  **     8: (c, 105)
163748  **     9: (c, 105)
163749  **
163750  ** For each sample in the aSample[] array, N samples are present in the
163751  ** effective sample array. In the above, samples 0 and 1 are based on
163752  ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
163753  **
163754  ** Often, sample i of each block of N effective samples has (i+1) fields.
163755  ** Except, each sample may be extended to ensure that it is greater than or
163756  ** equal to the previous sample in the array. For example, in the above,
163757  ** sample 2 is the first sample of a block of N samples, so at first it
163758  ** appears that it should be 1 field in size. However, that would make it
163759  ** smaller than sample 1, so the binary search would not work. As a result,
163760  ** it is extended to two fields. The duplicates that this creates do not
163761  ** cause any problems.
163762  */
163763  if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
163764    nField = pIdx->nKeyCol;
163765  }else{
163766    nField = pIdx->nColumn;
163767  }
163768  nField = MIN(pRec->nField, nField);
163769  iCol = 0;
163770  iSample = pIdx->nSample * nField;
163771  do{
163772    int iSamp;                    /* Index in aSample[] of test sample */
163773    int n;                        /* Number of fields in test sample */
163774
163775    iTest = (iMin+iSample)/2;
163776    iSamp = iTest / nField;
163777    if( iSamp>0 ){
163778      /* The proposed effective sample is a prefix of sample aSample[iSamp].
163779      ** Specifically, the shortest prefix of at least (1 + iTest%nField)
163780      ** fields that is greater than the previous effective sample.  */
163781      for(n=(iTest % nField) + 1; n<nField; n++){
163782        if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
163783      }
163784    }else{
163785      n = iTest + 1;
163786    }
163787
163788    pRec->nField = n;
163789    res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
163790    if( res<0 ){
163791      iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
163792      iMin = iTest+1;
163793    }else if( res==0 && n<nField ){
163794      iLower = aSample[iSamp].anLt[n-1];
163795      iMin = iTest+1;
163796      res = -1;
163797    }else{
163798      iSample = iTest;
163799      iCol = n-1;
163800    }
163801  }while( res && iMin<iSample );
163802  i = iSample / nField;
163803
163804#ifdef SQLITE_DEBUG
163805  /* The following assert statements check that the binary search code
163806  ** above found the right answer. This block serves no purpose other
163807  ** than to invoke the asserts.  */
163808  if( pParse->db->mallocFailed==0 ){
163809    if( res==0 ){
163810      /* If (res==0) is true, then pRec must be equal to sample i. */
163811      assert( i<pIdx->nSample );
163812      assert( iCol==nField-1 );
163813      pRec->nField = nField;
163814      assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
163815           || pParse->db->mallocFailed
163816      );
163817    }else{
163818      /* Unless i==pIdx->nSample, indicating that pRec is larger than
163819      ** all samples in the aSample[] array, pRec must be smaller than the
163820      ** (iCol+1) field prefix of sample i.  */
163821      assert( i<=pIdx->nSample && i>=0 );
163822      pRec->nField = iCol+1;
163823      assert( i==pIdx->nSample
163824           || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
163825           || pParse->db->mallocFailed );
163826
163827      /* if i==0 and iCol==0, then record pRec is smaller than all samples
163828      ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
163829      ** be greater than or equal to the (iCol) field prefix of sample i.
163830      ** If (i>0), then pRec must also be greater than sample (i-1).  */
163831      if( iCol>0 ){
163832        pRec->nField = iCol;
163833        assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
163834             || pParse->db->mallocFailed || CORRUPT_DB );
163835      }
163836      if( i>0 ){
163837        pRec->nField = nField;
163838        assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
163839             || pParse->db->mallocFailed || CORRUPT_DB );
163840      }
163841    }
163842  }
163843#endif /* ifdef SQLITE_DEBUG */
163844
163845  if( res==0 ){
163846    /* Record pRec is equal to sample i */
163847    assert( iCol==nField-1 );
163848    aStat[0] = aSample[i].anLt[iCol];
163849    aStat[1] = aSample[i].anEq[iCol];
163850  }else{
163851    /* At this point, the (iCol+1) field prefix of aSample[i] is the first
163852    ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
163853    ** is larger than all samples in the array. */
163854    tRowcnt iUpper, iGap;
163855    if( i>=pIdx->nSample ){
163856      iUpper = pIdx->nRowEst0;
163857    }else{
163858      iUpper = aSample[i].anLt[iCol];
163859    }
163860
163861    if( iLower>=iUpper ){
163862      iGap = 0;
163863    }else{
163864      iGap = iUpper - iLower;
163865    }
163866    if( roundUp ){
163867      iGap = (iGap*2)/3;
163868    }else{
163869      iGap = iGap/3;
163870    }
163871    aStat[0] = iLower + iGap;
163872    aStat[1] = pIdx->aAvgEq[nField-1];
163873  }
163874
163875  /* Restore the pRec->nField value before returning.  */
163876  pRec->nField = nField;
163877  return i;
163878}
163879#endif /* SQLITE_ENABLE_STAT4 */
163880
163881/*
163882** If it is not NULL, pTerm is a term that provides an upper or lower
163883** bound on a range scan. Without considering pTerm, it is estimated
163884** that the scan will visit nNew rows. This function returns the number
163885** estimated to be visited after taking pTerm into account.
163886**
163887** If the user explicitly specified a likelihood() value for this term,
163888** then the return value is the likelihood multiplied by the number of
163889** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
163890** has a likelihood of 0.50, and any other term a likelihood of 0.25.
163891*/
163892static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
163893  LogEst nRet = nNew;
163894  if( pTerm ){
163895    if( pTerm->truthProb<=0 ){
163896      nRet += pTerm->truthProb;
163897    }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
163898      nRet -= 20;        assert( 20==sqlite3LogEst(4) );
163899    }
163900  }
163901  return nRet;
163902}
163903
163904
163905#ifdef SQLITE_ENABLE_STAT4
163906/*
163907** Return the affinity for a single column of an index.
163908*/
163909SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
163910  assert( iCol>=0 && iCol<pIdx->nColumn );
163911  if( !pIdx->zColAff ){
163912    if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
163913  }
163914  assert( pIdx->zColAff[iCol]!=0 );
163915  return pIdx->zColAff[iCol];
163916}
163917#endif
163918
163919
163920#ifdef SQLITE_ENABLE_STAT4
163921/*
163922** This function is called to estimate the number of rows visited by a
163923** range-scan on a skip-scan index. For example:
163924**
163925**   CREATE INDEX i1 ON t1(a, b, c);
163926**   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
163927**
163928** Value pLoop->nOut is currently set to the estimated number of rows
163929** visited for scanning (a=? AND b=?). This function reduces that estimate
163930** by some factor to account for the (c BETWEEN ? AND ?) expression based
163931** on the stat4 data for the index. this scan will be performed multiple
163932** times (once for each (a,b) combination that matches a=?) is dealt with
163933** by the caller.
163934**
163935** It does this by scanning through all stat4 samples, comparing values
163936** extracted from pLower and pUpper with the corresponding column in each
163937** sample. If L and U are the number of samples found to be less than or
163938** equal to the values extracted from pLower and pUpper respectively, and
163939** N is the total number of samples, the pLoop->nOut value is adjusted
163940** as follows:
163941**
163942**   nOut = nOut * ( min(U - L, 1) / N )
163943**
163944** If pLower is NULL, or a value cannot be extracted from the term, L is
163945** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
163946** U is set to N.
163947**
163948** Normally, this function sets *pbDone to 1 before returning. However,
163949** if no value can be extracted from either pLower or pUpper (and so the
163950** estimate of the number of rows delivered remains unchanged), *pbDone
163951** is left as is.
163952**
163953** If an error occurs, an SQLite error code is returned. Otherwise,
163954** SQLITE_OK.
163955*/
163956static int whereRangeSkipScanEst(
163957  Parse *pParse,       /* Parsing & code generating context */
163958  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
163959  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
163960  WhereLoop *pLoop,    /* Update the .nOut value of this loop */
163961  int *pbDone          /* Set to true if at least one expr. value extracted */
163962){
163963  Index *p = pLoop->u.btree.pIndex;
163964  int nEq = pLoop->u.btree.nEq;
163965  sqlite3 *db = pParse->db;
163966  int nLower = -1;
163967  int nUpper = p->nSample+1;
163968  int rc = SQLITE_OK;
163969  u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
163970  CollSeq *pColl;
163971
163972  sqlite3_value *p1 = 0;          /* Value extracted from pLower */
163973  sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
163974  sqlite3_value *pVal = 0;        /* Value extracted from record */
163975
163976  pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
163977  if( pLower ){
163978    rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
163979    nLower = 0;
163980  }
163981  if( pUpper && rc==SQLITE_OK ){
163982    rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
163983    nUpper = p2 ? 0 : p->nSample;
163984  }
163985
163986  if( p1 || p2 ){
163987    int i;
163988    int nDiff;
163989    for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
163990      rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
163991      if( rc==SQLITE_OK && p1 ){
163992        int res = sqlite3MemCompare(p1, pVal, pColl);
163993        if( res>=0 ) nLower++;
163994      }
163995      if( rc==SQLITE_OK && p2 ){
163996        int res = sqlite3MemCompare(p2, pVal, pColl);
163997        if( res>=0 ) nUpper++;
163998      }
163999    }
164000    nDiff = (nUpper - nLower);
164001    if( nDiff<=0 ) nDiff = 1;
164002
164003    /* If there is both an upper and lower bound specified, and the
164004    ** comparisons indicate that they are close together, use the fallback
164005    ** method (assume that the scan visits 1/64 of the rows) for estimating
164006    ** the number of rows visited. Otherwise, estimate the number of rows
164007    ** using the method described in the header comment for this function. */
164008    if( nDiff!=1 || pUpper==0 || pLower==0 ){
164009      int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
164010      pLoop->nOut -= nAdjust;
164011      *pbDone = 1;
164012      WHERETRACE(0x20, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
164013                           nLower, nUpper, nAdjust*-1, pLoop->nOut));
164014    }
164015
164016  }else{
164017    assert( *pbDone==0 );
164018  }
164019
164020  sqlite3ValueFree(p1);
164021  sqlite3ValueFree(p2);
164022  sqlite3ValueFree(pVal);
164023
164024  return rc;
164025}
164026#endif /* SQLITE_ENABLE_STAT4 */
164027
164028/*
164029** This function is used to estimate the number of rows that will be visited
164030** by scanning an index for a range of values. The range may have an upper
164031** bound, a lower bound, or both. The WHERE clause terms that set the upper
164032** and lower bounds are represented by pLower and pUpper respectively. For
164033** example, assuming that index p is on t1(a):
164034**
164035**   ... FROM t1 WHERE a > ? AND a < ? ...
164036**                    |_____|   |_____|
164037**                       |         |
164038**                     pLower    pUpper
164039**
164040** If either of the upper or lower bound is not present, then NULL is passed in
164041** place of the corresponding WhereTerm.
164042**
164043** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
164044** column subject to the range constraint. Or, equivalently, the number of
164045** equality constraints optimized by the proposed index scan. For example,
164046** assuming index p is on t1(a, b), and the SQL query is:
164047**
164048**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
164049**
164050** then nEq is set to 1 (as the range restricted column, b, is the second
164051** left-most column of the index). Or, if the query is:
164052**
164053**   ... FROM t1 WHERE a > ? AND a < ? ...
164054**
164055** then nEq is set to 0.
164056**
164057** When this function is called, *pnOut is set to the sqlite3LogEst() of the
164058** number of rows that the index scan is expected to visit without
164059** considering the range constraints. If nEq is 0, then *pnOut is the number of
164060** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
164061** to account for the range constraints pLower and pUpper.
164062**
164063** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
164064** used, a single range inequality reduces the search space by a factor of 4.
164065** and a pair of constraints (x>? AND x<?) reduces the expected number of
164066** rows visited by a factor of 64.
164067*/
164068static int whereRangeScanEst(
164069  Parse *pParse,       /* Parsing & code generating context */
164070  WhereLoopBuilder *pBuilder,
164071  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
164072  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
164073  WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
164074){
164075  int rc = SQLITE_OK;
164076  int nOut = pLoop->nOut;
164077  LogEst nNew;
164078
164079#ifdef SQLITE_ENABLE_STAT4
164080  Index *p = pLoop->u.btree.pIndex;
164081  int nEq = pLoop->u.btree.nEq;
164082
164083  if( p->nSample>0 && ALWAYS(nEq<p->nSampleCol)
164084   && OptimizationEnabled(pParse->db, SQLITE_Stat4)
164085  ){
164086    if( nEq==pBuilder->nRecValid ){
164087      UnpackedRecord *pRec = pBuilder->pRec;
164088      tRowcnt a[2];
164089      int nBtm = pLoop->u.btree.nBtm;
164090      int nTop = pLoop->u.btree.nTop;
164091
164092      /* Variable iLower will be set to the estimate of the number of rows in
164093      ** the index that are less than the lower bound of the range query. The
164094      ** lower bound being the concatenation of $P and $L, where $P is the
164095      ** key-prefix formed by the nEq values matched against the nEq left-most
164096      ** columns of the index, and $L is the value in pLower.
164097      **
164098      ** Or, if pLower is NULL or $L cannot be extracted from it (because it
164099      ** is not a simple variable or literal value), the lower bound of the
164100      ** range is $P. Due to a quirk in the way whereKeyStats() works, even
164101      ** if $L is available, whereKeyStats() is called for both ($P) and
164102      ** ($P:$L) and the larger of the two returned values is used.
164103      **
164104      ** Similarly, iUpper is to be set to the estimate of the number of rows
164105      ** less than the upper bound of the range query. Where the upper bound
164106      ** is either ($P) or ($P:$U). Again, even if $U is available, both values
164107      ** of iUpper are requested of whereKeyStats() and the smaller used.
164108      **
164109      ** The number of rows between the two bounds is then just iUpper-iLower.
164110      */
164111      tRowcnt iLower;     /* Rows less than the lower bound */
164112      tRowcnt iUpper;     /* Rows less than the upper bound */
164113      int iLwrIdx = -2;   /* aSample[] for the lower bound */
164114      int iUprIdx = -1;   /* aSample[] for the upper bound */
164115
164116      if( pRec ){
164117        testcase( pRec->nField!=pBuilder->nRecValid );
164118        pRec->nField = pBuilder->nRecValid;
164119      }
164120      /* Determine iLower and iUpper using ($P) only. */
164121      if( nEq==0 ){
164122        iLower = 0;
164123        iUpper = p->nRowEst0;
164124      }else{
164125        /* Note: this call could be optimized away - since the same values must
164126        ** have been requested when testing key $P in whereEqualScanEst().  */
164127        whereKeyStats(pParse, p, pRec, 0, a);
164128        iLower = a[0];
164129        iUpper = a[0] + a[1];
164130      }
164131
164132      assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
164133      assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
164134      assert( p->aSortOrder!=0 );
164135      if( p->aSortOrder[nEq] ){
164136        /* The roles of pLower and pUpper are swapped for a DESC index */
164137        SWAP(WhereTerm*, pLower, pUpper);
164138        SWAP(int, nBtm, nTop);
164139      }
164140
164141      /* If possible, improve on the iLower estimate using ($P:$L). */
164142      if( pLower ){
164143        int n;                    /* Values extracted from pExpr */
164144        Expr *pExpr = pLower->pExpr->pRight;
164145        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
164146        if( rc==SQLITE_OK && n ){
164147          tRowcnt iNew;
164148          u16 mask = WO_GT|WO_LE;
164149          if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
164150          iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
164151          iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
164152          if( iNew>iLower ) iLower = iNew;
164153          nOut--;
164154          pLower = 0;
164155        }
164156      }
164157
164158      /* If possible, improve on the iUpper estimate using ($P:$U). */
164159      if( pUpper ){
164160        int n;                    /* Values extracted from pExpr */
164161        Expr *pExpr = pUpper->pExpr->pRight;
164162        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
164163        if( rc==SQLITE_OK && n ){
164164          tRowcnt iNew;
164165          u16 mask = WO_GT|WO_LE;
164166          if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
164167          iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
164168          iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
164169          if( iNew<iUpper ) iUpper = iNew;
164170          nOut--;
164171          pUpper = 0;
164172        }
164173      }
164174
164175      pBuilder->pRec = pRec;
164176      if( rc==SQLITE_OK ){
164177        if( iUpper>iLower ){
164178          nNew = sqlite3LogEst(iUpper - iLower);
164179          /* TUNING:  If both iUpper and iLower are derived from the same
164180          ** sample, then assume they are 4x more selective.  This brings
164181          ** the estimated selectivity more in line with what it would be
164182          ** if estimated without the use of STAT4 tables. */
164183          if( iLwrIdx==iUprIdx ){ nNew -= 20; }
164184          assert( 20==sqlite3LogEst(4) );
164185        }else{
164186          nNew = 10;        assert( 10==sqlite3LogEst(2) );
164187        }
164188        if( nNew<nOut ){
164189          nOut = nNew;
164190        }
164191        WHERETRACE(0x20, ("STAT4 range scan: %u..%u  est=%d\n",
164192                           (u32)iLower, (u32)iUpper, nOut));
164193      }
164194    }else{
164195      int bDone = 0;
164196      rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
164197      if( bDone ) return rc;
164198    }
164199  }
164200#else
164201  UNUSED_PARAMETER(pParse);
164202  UNUSED_PARAMETER(pBuilder);
164203  assert( pLower || pUpper );
164204#endif
164205  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 || pParse->nErr>0 );
164206  nNew = whereRangeAdjust(pLower, nOut);
164207  nNew = whereRangeAdjust(pUpper, nNew);
164208
164209  /* TUNING: If there is both an upper and lower limit and neither limit
164210  ** has an application-defined likelihood(), assume the range is
164211  ** reduced by an additional 75%. This means that, by default, an open-ended
164212  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
164213  ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
164214  ** match 1/64 of the index. */
164215  if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
164216    nNew -= 20;
164217  }
164218
164219  nOut -= (pLower!=0) + (pUpper!=0);
164220  if( nNew<10 ) nNew = 10;
164221  if( nNew<nOut ) nOut = nNew;
164222#if defined(WHERETRACE_ENABLED)
164223  if( pLoop->nOut>nOut ){
164224    WHERETRACE(0x20,("Range scan lowers nOut from %d to %d\n",
164225                    pLoop->nOut, nOut));
164226  }
164227#endif
164228  pLoop->nOut = (LogEst)nOut;
164229  return rc;
164230}
164231
164232#ifdef SQLITE_ENABLE_STAT4
164233/*
164234** Estimate the number of rows that will be returned based on
164235** an equality constraint x=VALUE and where that VALUE occurs in
164236** the histogram data.  This only works when x is the left-most
164237** column of an index and sqlite_stat4 histogram data is available
164238** for that index.  When pExpr==NULL that means the constraint is
164239** "x IS NULL" instead of "x=VALUE".
164240**
164241** Write the estimated row count into *pnRow and return SQLITE_OK.
164242** If unable to make an estimate, leave *pnRow unchanged and return
164243** non-zero.
164244**
164245** This routine can fail if it is unable to load a collating sequence
164246** required for string comparison, or if unable to allocate memory
164247** for a UTF conversion required for comparison.  The error is stored
164248** in the pParse structure.
164249*/
164250static int whereEqualScanEst(
164251  Parse *pParse,       /* Parsing & code generating context */
164252  WhereLoopBuilder *pBuilder,
164253  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
164254  tRowcnt *pnRow       /* Write the revised row estimate here */
164255){
164256  Index *p = pBuilder->pNew->u.btree.pIndex;
164257  int nEq = pBuilder->pNew->u.btree.nEq;
164258  UnpackedRecord *pRec = pBuilder->pRec;
164259  int rc;                   /* Subfunction return code */
164260  tRowcnt a[2];             /* Statistics */
164261  int bOk;
164262
164263  assert( nEq>=1 );
164264  assert( nEq<=p->nColumn );
164265  assert( p->aSample!=0 );
164266  assert( p->nSample>0 );
164267  assert( pBuilder->nRecValid<nEq );
164268
164269  /* If values are not available for all fields of the index to the left
164270  ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
164271  if( pBuilder->nRecValid<(nEq-1) ){
164272    return SQLITE_NOTFOUND;
164273  }
164274
164275  /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
164276  ** below would return the same value.  */
164277  if( nEq>=p->nColumn ){
164278    *pnRow = 1;
164279    return SQLITE_OK;
164280  }
164281
164282  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
164283  pBuilder->pRec = pRec;
164284  if( rc!=SQLITE_OK ) return rc;
164285  if( bOk==0 ) return SQLITE_NOTFOUND;
164286  pBuilder->nRecValid = nEq;
164287
164288  whereKeyStats(pParse, p, pRec, 0, a);
164289  WHERETRACE(0x20,("equality scan regions %s(%d): %d\n",
164290                   p->zName, nEq-1, (int)a[1]));
164291  *pnRow = a[1];
164292
164293  return rc;
164294}
164295#endif /* SQLITE_ENABLE_STAT4 */
164296
164297#ifdef SQLITE_ENABLE_STAT4
164298/*
164299** Estimate the number of rows that will be returned based on
164300** an IN constraint where the right-hand side of the IN operator
164301** is a list of values.  Example:
164302**
164303**        WHERE x IN (1,2,3,4)
164304**
164305** Write the estimated row count into *pnRow and return SQLITE_OK.
164306** If unable to make an estimate, leave *pnRow unchanged and return
164307** non-zero.
164308**
164309** This routine can fail if it is unable to load a collating sequence
164310** required for string comparison, or if unable to allocate memory
164311** for a UTF conversion required for comparison.  The error is stored
164312** in the pParse structure.
164313*/
164314static int whereInScanEst(
164315  Parse *pParse,       /* Parsing & code generating context */
164316  WhereLoopBuilder *pBuilder,
164317  ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
164318  tRowcnt *pnRow       /* Write the revised row estimate here */
164319){
164320  Index *p = pBuilder->pNew->u.btree.pIndex;
164321  i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
164322  int nRecValid = pBuilder->nRecValid;
164323  int rc = SQLITE_OK;     /* Subfunction return code */
164324  tRowcnt nEst;           /* Number of rows for a single term */
164325  tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
164326  int i;                  /* Loop counter */
164327
164328  assert( p->aSample!=0 );
164329  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
164330    nEst = nRow0;
164331    rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
164332    nRowEst += nEst;
164333    pBuilder->nRecValid = nRecValid;
164334  }
164335
164336  if( rc==SQLITE_OK ){
164337    if( nRowEst > (tRowcnt)nRow0 ) nRowEst = nRow0;
164338    *pnRow = nRowEst;
164339    WHERETRACE(0x20,("IN row estimate: est=%d\n", nRowEst));
164340  }
164341  assert( pBuilder->nRecValid==nRecValid );
164342  return rc;
164343}
164344#endif /* SQLITE_ENABLE_STAT4 */
164345
164346
164347#ifdef WHERETRACE_ENABLED
164348/*
164349** Print the content of a WhereTerm object
164350*/
164351SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){
164352  if( pTerm==0 ){
164353    sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
164354  }else{
164355    char zType[8];
164356    char zLeft[50];
164357    memcpy(zType, "....", 5);
164358    if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
164359    if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
164360    if( ExprHasProperty(pTerm->pExpr, EP_OuterON) ) zType[2] = 'L';
164361    if( pTerm->wtFlags & TERM_CODED  ) zType[3] = 'C';
164362    if( pTerm->eOperator & WO_SINGLE ){
164363      assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
164364      sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
164365                       pTerm->leftCursor, pTerm->u.x.leftColumn);
164366    }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
164367      sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%llx",
164368                       pTerm->u.pOrInfo->indexable);
164369    }else{
164370      sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
164371    }
164372    sqlite3DebugPrintf(
164373       "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x",
164374       iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags);
164375    /* The 0x10000 .wheretrace flag causes extra information to be
164376    ** shown about each Term */
164377    if( sqlite3WhereTrace & 0x10000 ){
164378      sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx",
164379        pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight);
164380    }
164381    if( (pTerm->eOperator & (WO_OR|WO_AND))==0 && pTerm->u.x.iField ){
164382      sqlite3DebugPrintf(" iField=%d", pTerm->u.x.iField);
164383    }
164384    if( pTerm->iParent>=0 ){
164385      sqlite3DebugPrintf(" iParent=%d", pTerm->iParent);
164386    }
164387    sqlite3DebugPrintf("\n");
164388    sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
164389  }
164390}
164391#endif
164392
164393#ifdef WHERETRACE_ENABLED
164394/*
164395** Show the complete content of a WhereClause
164396*/
164397SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
164398  int i;
164399  for(i=0; i<pWC->nTerm; i++){
164400    sqlite3WhereTermPrint(&pWC->a[i], i);
164401  }
164402}
164403#endif
164404
164405#ifdef WHERETRACE_ENABLED
164406/*
164407** Print a WhereLoop object for debugging purposes
164408**
164409** Format example:
164410**
164411**     .--- Position in WHERE clause           rSetup, rRun, nOut ---.
164412**     |                                                             |
164413**     |  .--- selfMask                       nTerm ------.          |
164414**     |  |                                               |          |
164415**     |  |   .-- prereq    Idx          wsFlags----.     |          |
164416**     |  |   |             Name                    |     |          |
164417**     |  |   |           __|__        nEq ---.  ___|__   |        __|__
164418**     | / \ / \         /     \              | /      \ / \      /     \
164419**     1.002.001         t2.t2xy              2 f 010241 N 2 cost 0,56,31
164420*/
164421SQLITE_PRIVATE void sqlite3WhereLoopPrint(const WhereLoop *p, const WhereClause *pWC){
164422  if( pWC ){
164423    WhereInfo *pWInfo = pWC->pWInfo;
164424    int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
164425    SrcItem *pItem = pWInfo->pTabList->a + p->iTab;
164426    Table *pTab = pItem->pTab;
164427    Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
164428    sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
164429                       p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
164430    sqlite3DebugPrintf(" %12s",
164431                       pItem->zAlias ? pItem->zAlias : pTab->zName);
164432  }else{
164433    sqlite3DebugPrintf("%c%2d.%03llx.%03llx %c%d",
164434         p->cId, p->iTab, p->maskSelf, p->prereq & 0xfff, p->cId, p->iTab);
164435  }
164436  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
164437    const char *zName;
164438    if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
164439      if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
164440        int i = sqlite3Strlen30(zName) - 1;
164441        while( zName[i]!='_' ) i--;
164442        zName += i;
164443      }
164444      sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
164445    }else{
164446      sqlite3DebugPrintf("%20s","");
164447    }
164448  }else{
164449    char *z;
164450    if( p->u.vtab.idxStr ){
164451      z = sqlite3_mprintf("(%d,\"%s\",%#x)",
164452                p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
164453    }else{
164454      z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
164455    }
164456    sqlite3DebugPrintf(" %-19s", z);
164457    sqlite3_free(z);
164458  }
164459  if( p->wsFlags & WHERE_SKIPSCAN ){
164460    sqlite3DebugPrintf(" f %06x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
164461  }else{
164462    sqlite3DebugPrintf(" f %06x N %d", p->wsFlags, p->nLTerm);
164463  }
164464  sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
164465  if( p->nLTerm && (sqlite3WhereTrace & 0x4000)!=0 ){
164466    int i;
164467    for(i=0; i<p->nLTerm; i++){
164468      sqlite3WhereTermPrint(p->aLTerm[i], i);
164469    }
164470  }
164471}
164472SQLITE_PRIVATE void sqlite3ShowWhereLoop(const WhereLoop *p){
164473  if( p ) sqlite3WhereLoopPrint(p, 0);
164474}
164475SQLITE_PRIVATE void sqlite3ShowWhereLoopList(const WhereLoop *p){
164476  while( p ){
164477    sqlite3ShowWhereLoop(p);
164478    p = p->pNextLoop;
164479  }
164480}
164481#endif
164482
164483/*
164484** Convert bulk memory into a valid WhereLoop that can be passed
164485** to whereLoopClear harmlessly.
164486*/
164487static void whereLoopInit(WhereLoop *p){
164488  p->aLTerm = p->aLTermSpace;
164489  p->nLTerm = 0;
164490  p->nLSlot = ArraySize(p->aLTermSpace);
164491  p->wsFlags = 0;
164492}
164493
164494/*
164495** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
164496*/
164497static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
164498  if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
164499    if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
164500      sqlite3_free(p->u.vtab.idxStr);
164501      p->u.vtab.needFree = 0;
164502      p->u.vtab.idxStr = 0;
164503    }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
164504      sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
164505      sqlite3DbFreeNN(db, p->u.btree.pIndex);
164506      p->u.btree.pIndex = 0;
164507    }
164508  }
164509}
164510
164511/*
164512** Deallocate internal memory used by a WhereLoop object.  Leave the
164513** object in an initialized state, as if it had been newly allocated.
164514*/
164515static void whereLoopClear(sqlite3 *db, WhereLoop *p){
164516  if( p->aLTerm!=p->aLTermSpace ){
164517    sqlite3DbFreeNN(db, p->aLTerm);
164518    p->aLTerm = p->aLTermSpace;
164519    p->nLSlot = ArraySize(p->aLTermSpace);
164520  }
164521  whereLoopClearUnion(db, p);
164522  p->nLTerm = 0;
164523  p->wsFlags = 0;
164524}
164525
164526/*
164527** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
164528*/
164529static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
164530  WhereTerm **paNew;
164531  if( p->nLSlot>=n ) return SQLITE_OK;
164532  n = (n+7)&~7;
164533  paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
164534  if( paNew==0 ) return SQLITE_NOMEM_BKPT;
164535  memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
164536  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
164537  p->aLTerm = paNew;
164538  p->nLSlot = n;
164539  return SQLITE_OK;
164540}
164541
164542/*
164543** Transfer content from the second pLoop into the first.
164544*/
164545static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
164546  whereLoopClearUnion(db, pTo);
164547  if( pFrom->nLTerm > pTo->nLSlot
164548   && whereLoopResize(db, pTo, pFrom->nLTerm)
164549  ){
164550    memset(pTo, 0, WHERE_LOOP_XFER_SZ);
164551    return SQLITE_NOMEM_BKPT;
164552  }
164553  memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
164554  memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
164555  if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
164556    pFrom->u.vtab.needFree = 0;
164557  }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
164558    pFrom->u.btree.pIndex = 0;
164559  }
164560  return SQLITE_OK;
164561}
164562
164563/*
164564** Delete a WhereLoop object
164565*/
164566static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
164567  assert( db!=0 );
164568  whereLoopClear(db, p);
164569  sqlite3DbNNFreeNN(db, p);
164570}
164571
164572/*
164573** Free a WhereInfo structure
164574*/
164575static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
164576  assert( pWInfo!=0 );
164577  assert( db!=0 );
164578  sqlite3WhereClauseClear(&pWInfo->sWC);
164579  while( pWInfo->pLoops ){
164580    WhereLoop *p = pWInfo->pLoops;
164581    pWInfo->pLoops = p->pNextLoop;
164582    whereLoopDelete(db, p);
164583  }
164584  while( pWInfo->pMemToFree ){
164585    WhereMemBlock *pNext = pWInfo->pMemToFree->pNext;
164586    sqlite3DbNNFreeNN(db, pWInfo->pMemToFree);
164587    pWInfo->pMemToFree = pNext;
164588  }
164589  sqlite3DbNNFreeNN(db, pWInfo);
164590}
164591
164592/*
164593** Return TRUE if X is a proper subset of Y but is of equal or less cost.
164594** In other words, return true if all constraints of X are also part of Y
164595** and Y has additional constraints that might speed the search that X lacks
164596** but the cost of running X is not more than the cost of running Y.
164597**
164598** In other words, return true if the cost relationwship between X and Y
164599** is inverted and needs to be adjusted.
164600**
164601** Case 1:
164602**
164603**   (1a)  X and Y use the same index.
164604**   (1b)  X has fewer == terms than Y
164605**   (1c)  Neither X nor Y use skip-scan
164606**   (1d)  X does not have a a greater cost than Y
164607**
164608** Case 2:
164609**
164610**   (2a)  X has the same or lower cost, or returns the same or fewer rows,
164611**         than Y.
164612**   (2b)  X uses fewer WHERE clause terms than Y
164613**   (2c)  Every WHERE clause term used by X is also used by Y
164614**   (2d)  X skips at least as many columns as Y
164615**   (2e)  If X is a covering index, than Y is too
164616*/
164617static int whereLoopCheaperProperSubset(
164618  const WhereLoop *pX,       /* First WhereLoop to compare */
164619  const WhereLoop *pY        /* Compare against this WhereLoop */
164620){
164621  int i, j;
164622  if( pX->rRun>pY->rRun && pX->nOut>pY->nOut ) return 0; /* (1d) and (2a) */
164623  assert( (pX->wsFlags & WHERE_VIRTUALTABLE)==0 );
164624  assert( (pY->wsFlags & WHERE_VIRTUALTABLE)==0 );
164625  if( pX->u.btree.nEq < pY->u.btree.nEq                  /* (1b) */
164626   && pX->u.btree.pIndex==pY->u.btree.pIndex             /* (1a) */
164627   && pX->nSkip==0 && pY->nSkip==0                       /* (1c) */
164628  ){
164629    return 1;  /* Case 1 is true */
164630  }
164631  if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
164632    return 0;                                            /* (2b) */
164633  }
164634  if( pY->nSkip > pX->nSkip ) return 0;                  /* (2d) */
164635  for(i=pX->nLTerm-1; i>=0; i--){
164636    if( pX->aLTerm[i]==0 ) continue;
164637    for(j=pY->nLTerm-1; j>=0; j--){
164638      if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
164639    }
164640    if( j<0 ) return 0;                                  /* (2c) */
164641  }
164642  if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
164643   && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
164644    return 0;                                            /* (2e) */
164645  }
164646  return 1;  /* Case 2 is true */
164647}
164648
164649/*
164650** Try to adjust the cost and number of output rows of WhereLoop pTemplate
164651** upwards or downwards so that:
164652**
164653**   (1) pTemplate costs less than any other WhereLoops that are a proper
164654**       subset of pTemplate
164655**
164656**   (2) pTemplate costs more than any other WhereLoops for which pTemplate
164657**       is a proper subset.
164658**
164659** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
164660** WHERE clause terms than Y and that every WHERE clause term used by X is
164661** also used by Y.
164662*/
164663static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
164664  if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
164665  for(; p; p=p->pNextLoop){
164666    if( p->iTab!=pTemplate->iTab ) continue;
164667    if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
164668    if( whereLoopCheaperProperSubset(p, pTemplate) ){
164669      /* Adjust pTemplate cost downward so that it is cheaper than its
164670      ** subset p. */
164671      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
164672                       pTemplate->rRun, pTemplate->nOut,
164673                       MIN(p->rRun, pTemplate->rRun),
164674                       MIN(p->nOut - 1, pTemplate->nOut)));
164675      pTemplate->rRun = MIN(p->rRun, pTemplate->rRun);
164676      pTemplate->nOut = MIN(p->nOut - 1, pTemplate->nOut);
164677    }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
164678      /* Adjust pTemplate cost upward so that it is costlier than p since
164679      ** pTemplate is a proper subset of p */
164680      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
164681                       pTemplate->rRun, pTemplate->nOut,
164682                       MAX(p->rRun, pTemplate->rRun),
164683                       MAX(p->nOut + 1, pTemplate->nOut)));
164684      pTemplate->rRun = MAX(p->rRun, pTemplate->rRun);
164685      pTemplate->nOut = MAX(p->nOut + 1, pTemplate->nOut);
164686    }
164687  }
164688}
164689
164690/*
164691** Search the list of WhereLoops in *ppPrev looking for one that can be
164692** replaced by pTemplate.
164693**
164694** Return NULL if pTemplate does not belong on the WhereLoop list.
164695** In other words if pTemplate ought to be dropped from further consideration.
164696**
164697** If pX is a WhereLoop that pTemplate can replace, then return the
164698** link that points to pX.
164699**
164700** If pTemplate cannot replace any existing element of the list but needs
164701** to be added to the list as a new entry, then return a pointer to the
164702** tail of the list.
164703*/
164704static WhereLoop **whereLoopFindLesser(
164705  WhereLoop **ppPrev,
164706  const WhereLoop *pTemplate
164707){
164708  WhereLoop *p;
164709  for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
164710    if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
164711      /* If either the iTab or iSortIdx values for two WhereLoop are different
164712      ** then those WhereLoops need to be considered separately.  Neither is
164713      ** a candidate to replace the other. */
164714      continue;
164715    }
164716    /* In the current implementation, the rSetup value is either zero
164717    ** or the cost of building an automatic index (NlogN) and the NlogN
164718    ** is the same for compatible WhereLoops. */
164719    assert( p->rSetup==0 || pTemplate->rSetup==0
164720                 || p->rSetup==pTemplate->rSetup );
164721
164722    /* whereLoopAddBtree() always generates and inserts the automatic index
164723    ** case first.  Hence compatible candidate WhereLoops never have a larger
164724    ** rSetup. Call this SETUP-INVARIANT */
164725    assert( p->rSetup>=pTemplate->rSetup );
164726
164727    /* Any loop using an application-defined index (or PRIMARY KEY or
164728    ** UNIQUE constraint) with one or more == constraints is better
164729    ** than an automatic index. Unless it is a skip-scan. */
164730    if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
164731     && (pTemplate->nSkip)==0
164732     && (pTemplate->wsFlags & WHERE_INDEXED)!=0
164733     && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
164734     && (p->prereq & pTemplate->prereq)==pTemplate->prereq
164735    ){
164736      break;
164737    }
164738
164739    /* If existing WhereLoop p is better than pTemplate, pTemplate can be
164740    ** discarded.  WhereLoop p is better if:
164741    **   (1)  p has no more dependencies than pTemplate, and
164742    **   (2)  p has an equal or lower cost than pTemplate
164743    */
164744    if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
164745     && p->rSetup<=pTemplate->rSetup                  /* (2a) */
164746     && p->rRun<=pTemplate->rRun                      /* (2b) */
164747     && p->nOut<=pTemplate->nOut                      /* (2c) */
164748    ){
164749      return 0;  /* Discard pTemplate */
164750    }
164751
164752    /* If pTemplate is always better than p, then cause p to be overwritten
164753    ** with pTemplate.  pTemplate is better than p if:
164754    **   (1)  pTemplate has no more dependencies than p, and
164755    **   (2)  pTemplate has an equal or lower cost than p.
164756    */
164757    if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
164758     && p->rRun>=pTemplate->rRun                             /* (2a) */
164759     && p->nOut>=pTemplate->nOut                             /* (2b) */
164760    ){
164761      assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
164762      break;   /* Cause p to be overwritten by pTemplate */
164763    }
164764  }
164765  return ppPrev;
164766}
164767
164768/*
164769** Insert or replace a WhereLoop entry using the template supplied.
164770**
164771** An existing WhereLoop entry might be overwritten if the new template
164772** is better and has fewer dependencies.  Or the template will be ignored
164773** and no insert will occur if an existing WhereLoop is faster and has
164774** fewer dependencies than the template.  Otherwise a new WhereLoop is
164775** added based on the template.
164776**
164777** If pBuilder->pOrSet is not NULL then we care about only the
164778** prerequisites and rRun and nOut costs of the N best loops.  That
164779** information is gathered in the pBuilder->pOrSet object.  This special
164780** processing mode is used only for OR clause processing.
164781**
164782** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
164783** still might overwrite similar loops with the new template if the
164784** new template is better.  Loops may be overwritten if the following
164785** conditions are met:
164786**
164787**    (1)  They have the same iTab.
164788**    (2)  They have the same iSortIdx.
164789**    (3)  The template has same or fewer dependencies than the current loop
164790**    (4)  The template has the same or lower cost than the current loop
164791*/
164792static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
164793  WhereLoop **ppPrev, *p;
164794  WhereInfo *pWInfo = pBuilder->pWInfo;
164795  sqlite3 *db = pWInfo->pParse->db;
164796  int rc;
164797
164798  /* Stop the search once we hit the query planner search limit */
164799  if( pBuilder->iPlanLimit==0 ){
164800    WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n"));
164801    if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;
164802    return SQLITE_DONE;
164803  }
164804  pBuilder->iPlanLimit--;
164805
164806  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
164807
164808  /* If pBuilder->pOrSet is defined, then only keep track of the costs
164809  ** and prereqs.
164810  */
164811  if( pBuilder->pOrSet!=0 ){
164812    if( pTemplate->nLTerm ){
164813#if WHERETRACE_ENABLED
164814      u16 n = pBuilder->pOrSet->n;
164815      int x =
164816#endif
164817      whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
164818                                    pTemplate->nOut);
164819#if WHERETRACE_ENABLED /* 0x8 */
164820      if( sqlite3WhereTrace & 0x8 ){
164821        sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
164822        sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
164823      }
164824#endif
164825    }
164826    return SQLITE_OK;
164827  }
164828
164829  /* Look for an existing WhereLoop to replace with pTemplate
164830  */
164831  ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
164832
164833  if( ppPrev==0 ){
164834    /* There already exists a WhereLoop on the list that is better
164835    ** than pTemplate, so just ignore pTemplate */
164836#if WHERETRACE_ENABLED /* 0x8 */
164837    if( sqlite3WhereTrace & 0x8 ){
164838      sqlite3DebugPrintf("   skip: ");
164839      sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
164840    }
164841#endif
164842    return SQLITE_OK;
164843  }else{
164844    p = *ppPrev;
164845  }
164846
164847  /* If we reach this point it means that either p[] should be overwritten
164848  ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
164849  ** WhereLoop and insert it.
164850  */
164851#if WHERETRACE_ENABLED /* 0x8 */
164852  if( sqlite3WhereTrace & 0x8 ){
164853    if( p!=0 ){
164854      sqlite3DebugPrintf("replace: ");
164855      sqlite3WhereLoopPrint(p, pBuilder->pWC);
164856      sqlite3DebugPrintf("   with: ");
164857    }else{
164858      sqlite3DebugPrintf("    add: ");
164859    }
164860    sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
164861  }
164862#endif
164863  if( p==0 ){
164864    /* Allocate a new WhereLoop to add to the end of the list */
164865    *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
164866    if( p==0 ) return SQLITE_NOMEM_BKPT;
164867    whereLoopInit(p);
164868    p->pNextLoop = 0;
164869  }else{
164870    /* We will be overwriting WhereLoop p[].  But before we do, first
164871    ** go through the rest of the list and delete any other entries besides
164872    ** p[] that are also supplanted by pTemplate */
164873    WhereLoop **ppTail = &p->pNextLoop;
164874    WhereLoop *pToDel;
164875    while( *ppTail ){
164876      ppTail = whereLoopFindLesser(ppTail, pTemplate);
164877      if( ppTail==0 ) break;
164878      pToDel = *ppTail;
164879      if( pToDel==0 ) break;
164880      *ppTail = pToDel->pNextLoop;
164881#if WHERETRACE_ENABLED /* 0x8 */
164882      if( sqlite3WhereTrace & 0x8 ){
164883        sqlite3DebugPrintf(" delete: ");
164884        sqlite3WhereLoopPrint(pToDel, pBuilder->pWC);
164885      }
164886#endif
164887      whereLoopDelete(db, pToDel);
164888    }
164889  }
164890  rc = whereLoopXfer(db, p, pTemplate);
164891  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
164892    Index *pIndex = p->u.btree.pIndex;
164893    if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){
164894      p->u.btree.pIndex = 0;
164895    }
164896  }
164897  return rc;
164898}
164899
164900/*
164901** Adjust the WhereLoop.nOut value downward to account for terms of the
164902** WHERE clause that reference the loop but which are not used by an
164903** index.
164904*
164905** For every WHERE clause term that is not used by the index
164906** and which has a truth probability assigned by one of the likelihood(),
164907** likely(), or unlikely() SQL functions, reduce the estimated number
164908** of output rows by the probability specified.
164909**
164910** TUNING:  For every WHERE clause term that is not used by the index
164911** and which does not have an assigned truth probability, heuristics
164912** described below are used to try to estimate the truth probability.
164913** TODO --> Perhaps this is something that could be improved by better
164914** table statistics.
164915**
164916** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
164917** value corresponds to -1 in LogEst notation, so this means decrement
164918** the WhereLoop.nOut field for every such WHERE clause term.
164919**
164920** Heuristic 2:  If there exists one or more WHERE clause terms of the
164921** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
164922** final output row estimate is no greater than 1/4 of the total number
164923** of rows in the table.  In other words, assume that x==EXPR will filter
164924** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
164925** "x" column is boolean or else -1 or 0 or 1 is a common default value
164926** on the "x" column and so in that case only cap the output row estimate
164927** at 1/2 instead of 1/4.
164928*/
164929static void whereLoopOutputAdjust(
164930  WhereClause *pWC,      /* The WHERE clause */
164931  WhereLoop *pLoop,      /* The loop to adjust downward */
164932  LogEst nRow            /* Number of rows in the entire table */
164933){
164934  WhereTerm *pTerm, *pX;
164935  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
164936  int i, j;
164937  LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
164938
164939  assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
164940  for(i=pWC->nBase, pTerm=pWC->a; i>0; i--, pTerm++){
164941    assert( pTerm!=0 );
164942    if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
164943    if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
164944    if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) continue;
164945    for(j=pLoop->nLTerm-1; j>=0; j--){
164946      pX = pLoop->aLTerm[j];
164947      if( pX==0 ) continue;
164948      if( pX==pTerm ) break;
164949      if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
164950    }
164951    if( j<0 ){
164952      sqlite3ProgressCheck(pWC->pWInfo->pParse);
164953      if( pLoop->maskSelf==pTerm->prereqAll ){
164954        /* If there are extra terms in the WHERE clause not used by an index
164955        ** that depend only on the table being scanned, and that will tend to
164956        ** cause many rows to be omitted, then mark that table as
164957        ** "self-culling".
164958        **
164959        ** 2022-03-24:  Self-culling only applies if either the extra terms
164960        ** are straight comparison operators that are non-true with NULL
164961        ** operand, or if the loop is not an OUTER JOIN.
164962        */
164963        if( (pTerm->eOperator & 0x3f)!=0
164964         || (pWC->pWInfo->pTabList->a[pLoop->iTab].fg.jointype
164965                  & (JT_LEFT|JT_LTORJ))==0
164966        ){
164967          pLoop->wsFlags |= WHERE_SELFCULL;
164968        }
164969      }
164970      if( pTerm->truthProb<=0 ){
164971        /* If a truth probability is specified using the likelihood() hints,
164972        ** then use the probability provided by the application. */
164973        pLoop->nOut += pTerm->truthProb;
164974      }else{
164975        /* In the absence of explicit truth probabilities, use heuristics to
164976        ** guess a reasonable truth probability. */
164977        pLoop->nOut--;
164978        if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0
164979         && (pTerm->wtFlags & TERM_HIGHTRUTH)==0  /* tag-20200224-1 */
164980        ){
164981          Expr *pRight = pTerm->pExpr->pRight;
164982          int k = 0;
164983          testcase( pTerm->pExpr->op==TK_IS );
164984          if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
164985            k = 10;
164986          }else{
164987            k = 20;
164988          }
164989          if( iReduce<k ){
164990            pTerm->wtFlags |= TERM_HEURTRUTH;
164991            iReduce = k;
164992          }
164993        }
164994      }
164995    }
164996  }
164997  if( pLoop->nOut > nRow-iReduce ){
164998    pLoop->nOut = nRow - iReduce;
164999  }
165000}
165001
165002/*
165003** Term pTerm is a vector range comparison operation. The first comparison
165004** in the vector can be optimized using column nEq of the index. This
165005** function returns the total number of vector elements that can be used
165006** as part of the range comparison.
165007**
165008** For example, if the query is:
165009**
165010**   WHERE a = ? AND (b, c, d) > (?, ?, ?)
165011**
165012** and the index:
165013**
165014**   CREATE INDEX ... ON (a, b, c, d, e)
165015**
165016** then this function would be invoked with nEq=1. The value returned in
165017** this case is 3.
165018*/
165019static int whereRangeVectorLen(
165020  Parse *pParse,       /* Parsing context */
165021  int iCur,            /* Cursor open on pIdx */
165022  Index *pIdx,         /* The index to be used for a inequality constraint */
165023  int nEq,             /* Number of prior equality constraints on same index */
165024  WhereTerm *pTerm     /* The vector inequality constraint */
165025){
165026  int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
165027  int i;
165028
165029  nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
165030  for(i=1; i<nCmp; i++){
165031    /* Test if comparison i of pTerm is compatible with column (i+nEq)
165032    ** of the index. If not, exit the loop.  */
165033    char aff;                     /* Comparison affinity */
165034    char idxaff = 0;              /* Indexed columns affinity */
165035    CollSeq *pColl;               /* Comparison collation sequence */
165036    Expr *pLhs, *pRhs;
165037
165038    assert( ExprUseXList(pTerm->pExpr->pLeft) );
165039    pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
165040    pRhs = pTerm->pExpr->pRight;
165041    if( ExprUseXSelect(pRhs) ){
165042      pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
165043    }else{
165044      pRhs = pRhs->x.pList->a[i].pExpr;
165045    }
165046
165047    /* Check that the LHS of the comparison is a column reference to
165048    ** the right column of the right source table. And that the sort
165049    ** order of the index column is the same as the sort order of the
165050    ** leftmost index column.  */
165051    if( pLhs->op!=TK_COLUMN
165052     || pLhs->iTable!=iCur
165053     || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
165054     || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
165055    ){
165056      break;
165057    }
165058
165059    testcase( pLhs->iColumn==XN_ROWID );
165060    aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
165061    idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
165062    if( aff!=idxaff ) break;
165063
165064    pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
165065    if( pColl==0 ) break;
165066    if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
165067  }
165068  return i;
165069}
165070
165071/*
165072** Adjust the cost C by the costMult factor T.  This only occurs if
165073** compiled with -DSQLITE_ENABLE_COSTMULT
165074*/
165075#ifdef SQLITE_ENABLE_COSTMULT
165076# define ApplyCostMultiplier(C,T)  C += T
165077#else
165078# define ApplyCostMultiplier(C,T)
165079#endif
165080
165081/*
165082** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
165083** index pIndex. Try to match one more.
165084**
165085** When this function is called, pBuilder->pNew->nOut contains the
165086** number of rows expected to be visited by filtering using the nEq
165087** terms only. If it is modified, this value is restored before this
165088** function returns.
165089**
165090** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is
165091** a fake index used for the INTEGER PRIMARY KEY.
165092*/
165093static int whereLoopAddBtreeIndex(
165094  WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
165095  SrcItem *pSrc,                  /* FROM clause term being analyzed */
165096  Index *pProbe,                  /* An index on pSrc */
165097  LogEst nInMul                   /* log(Number of iterations due to IN) */
165098){
165099  WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyze context */
165100  Parse *pParse = pWInfo->pParse;        /* Parsing context */
165101  sqlite3 *db = pParse->db;       /* Database connection malloc context */
165102  WhereLoop *pNew;                /* Template WhereLoop under construction */
165103  WhereTerm *pTerm;               /* A WhereTerm under consideration */
165104  int opMask;                     /* Valid operators for constraints */
165105  WhereScan scan;                 /* Iterator for WHERE terms */
165106  Bitmask saved_prereq;           /* Original value of pNew->prereq */
165107  u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
165108  u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
165109  u16 saved_nBtm;                 /* Original value of pNew->u.btree.nBtm */
165110  u16 saved_nTop;                 /* Original value of pNew->u.btree.nTop */
165111  u16 saved_nSkip;                /* Original value of pNew->nSkip */
165112  u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
165113  LogEst saved_nOut;              /* Original value of pNew->nOut */
165114  int rc = SQLITE_OK;             /* Return code */
165115  LogEst rSize;                   /* Number of rows in the table */
165116  LogEst rLogSize;                /* Logarithm of table size */
165117  WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
165118
165119  pNew = pBuilder->pNew;
165120  assert( db->mallocFailed==0 || pParse->nErr>0 );
165121  if( pParse->nErr ){
165122    return pParse->rc;
165123  }
165124  WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d, rRun=%d\n",
165125                     pProbe->pTable->zName,pProbe->zName,
165126                     pNew->u.btree.nEq, pNew->nSkip, pNew->rRun));
165127
165128  assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
165129  assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
165130  if( pNew->wsFlags & WHERE_BTM_LIMIT ){
165131    opMask = WO_LT|WO_LE;
165132  }else{
165133    assert( pNew->u.btree.nBtm==0 );
165134    opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
165135  }
165136  if( pProbe->bUnordered || pProbe->bLowQual ){
165137    if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
165138    if( pProbe->bLowQual && pSrc->fg.isIndexedBy==0 ){
165139      opMask &= ~(WO_EQ|WO_IN|WO_IS);
165140    }
165141  }
165142
165143  assert( pNew->u.btree.nEq<pProbe->nColumn );
165144  assert( pNew->u.btree.nEq<pProbe->nKeyCol
165145       || pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY );
165146
165147  saved_nEq = pNew->u.btree.nEq;
165148  saved_nBtm = pNew->u.btree.nBtm;
165149  saved_nTop = pNew->u.btree.nTop;
165150  saved_nSkip = pNew->nSkip;
165151  saved_nLTerm = pNew->nLTerm;
165152  saved_wsFlags = pNew->wsFlags;
165153  saved_prereq = pNew->prereq;
165154  saved_nOut = pNew->nOut;
165155  pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
165156                        opMask, pProbe);
165157  pNew->rSetup = 0;
165158  rSize = pProbe->aiRowLogEst[0];
165159  rLogSize = estLog(rSize);
165160  for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
165161    u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
165162    LogEst rCostIdx;
165163    LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
165164    int nIn = 0;
165165#ifdef SQLITE_ENABLE_STAT4
165166    int nRecValid = pBuilder->nRecValid;
165167#endif
165168    if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
165169     && indexColumnNotNull(pProbe, saved_nEq)
165170    ){
165171      continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
165172    }
165173    if( pTerm->prereqRight & pNew->maskSelf ) continue;
165174
165175    /* Do not allow the upper bound of a LIKE optimization range constraint
165176    ** to mix with a lower range bound from some other source */
165177    if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
165178
165179    if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
165180     && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
165181    ){
165182      continue;
165183    }
165184    if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
165185      pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE;
165186    }else{
165187      pBuilder->bldFlags1 |= SQLITE_BLDF1_INDEXED;
165188    }
165189    pNew->wsFlags = saved_wsFlags;
165190    pNew->u.btree.nEq = saved_nEq;
165191    pNew->u.btree.nBtm = saved_nBtm;
165192    pNew->u.btree.nTop = saved_nTop;
165193    pNew->nLTerm = saved_nLTerm;
165194    if( pNew->nLTerm>=pNew->nLSlot
165195     && whereLoopResize(db, pNew, pNew->nLTerm+1)
165196    ){
165197       break; /* OOM while trying to enlarge the pNew->aLTerm array */
165198    }
165199    pNew->aLTerm[pNew->nLTerm++] = pTerm;
165200    pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
165201
165202    assert( nInMul==0
165203        || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
165204        || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
165205        || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
165206    );
165207
165208    if( eOp & WO_IN ){
165209      Expr *pExpr = pTerm->pExpr;
165210      if( ExprUseXSelect(pExpr) ){
165211        /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
165212        int i;
165213        nIn = 46;  assert( 46==sqlite3LogEst(25) );
165214
165215        /* The expression may actually be of the form (x, y) IN (SELECT...).
165216        ** In this case there is a separate term for each of (x) and (y).
165217        ** However, the nIn multiplier should only be applied once, not once
165218        ** for each such term. The following loop checks that pTerm is the
165219        ** first such term in use, and sets nIn back to 0 if it is not. */
165220        for(i=0; i<pNew->nLTerm-1; i++){
165221          if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
165222        }
165223      }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
165224        /* "x IN (value, value, ...)" */
165225        nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
165226      }
165227      if( pProbe->hasStat1 && rLogSize>=10 ){
165228        LogEst M, logK, x;
165229        /* Let:
165230        **   N = the total number of rows in the table
165231        **   K = the number of entries on the RHS of the IN operator
165232        **   M = the number of rows in the table that match terms to the
165233        **       to the left in the same index.  If the IN operator is on
165234        **       the left-most index column, M==N.
165235        **
165236        ** Given the definitions above, it is better to omit the IN operator
165237        ** from the index lookup and instead do a scan of the M elements,
165238        ** testing each scanned row against the IN operator separately, if:
165239        **
165240        **        M*log(K) < K*log(N)
165241        **
165242        ** Our estimates for M, K, and N might be inaccurate, so we build in
165243        ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
165244        ** with the index, as using an index has better worst-case behavior.
165245        ** If we do not have real sqlite_stat1 data, always prefer to use
165246        ** the index.  Do not bother with this optimization on very small
165247        ** tables (less than 2 rows) as it is pointless in that case.
165248        */
165249        M = pProbe->aiRowLogEst[saved_nEq];
165250        logK = estLog(nIn);
165251        /* TUNING      v-----  10 to bias toward indexed IN */
165252        x = M + logK + 10 - (nIn + rLogSize);
165253        if( x>=0 ){
165254          WHERETRACE(0x40,
165255            ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d) "
165256             "prefers indexed lookup\n",
165257             saved_nEq, M, logK, nIn, rLogSize, x));
165258        }else if( nInMul<2 && OptimizationEnabled(db, SQLITE_SeekScan) ){
165259          WHERETRACE(0x40,
165260            ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
165261             " nInMul=%d) prefers skip-scan\n",
165262             saved_nEq, M, logK, nIn, rLogSize, x, nInMul));
165263          pNew->wsFlags |= WHERE_IN_SEEKSCAN;
165264        }else{
165265          WHERETRACE(0x40,
165266            ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
165267             " nInMul=%d) prefers normal scan\n",
165268             saved_nEq, M, logK, nIn, rLogSize, x, nInMul));
165269          continue;
165270        }
165271      }
165272      pNew->wsFlags |= WHERE_COLUMN_IN;
165273    }else if( eOp & (WO_EQ|WO_IS) ){
165274      int iCol = pProbe->aiColumn[saved_nEq];
165275      pNew->wsFlags |= WHERE_COLUMN_EQ;
165276      assert( saved_nEq==pNew->u.btree.nEq );
165277      if( iCol==XN_ROWID
165278       || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
165279      ){
165280        if( iCol==XN_ROWID || pProbe->uniqNotNull
165281         || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
165282        ){
165283          pNew->wsFlags |= WHERE_ONEROW;
165284        }else{
165285          pNew->wsFlags |= WHERE_UNQ_WANTED;
165286        }
165287      }
165288      if( scan.iEquiv>1 ) pNew->wsFlags |= WHERE_TRANSCONS;
165289    }else if( eOp & WO_ISNULL ){
165290      pNew->wsFlags |= WHERE_COLUMN_NULL;
165291    }else{
165292      int nVecLen = whereRangeVectorLen(
165293          pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
165294      );
165295      if( eOp & (WO_GT|WO_GE) ){
165296        testcase( eOp & WO_GT );
165297        testcase( eOp & WO_GE );
165298        pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
165299        pNew->u.btree.nBtm = nVecLen;
165300        pBtm = pTerm;
165301        pTop = 0;
165302        if( pTerm->wtFlags & TERM_LIKEOPT ){
165303          /* Range constraints that come from the LIKE optimization are
165304          ** always used in pairs. */
165305          pTop = &pTerm[1];
165306          assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
165307          assert( pTop->wtFlags & TERM_LIKEOPT );
165308          assert( pTop->eOperator==WO_LT );
165309          if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
165310          pNew->aLTerm[pNew->nLTerm++] = pTop;
165311          pNew->wsFlags |= WHERE_TOP_LIMIT;
165312          pNew->u.btree.nTop = 1;
165313        }
165314      }else{
165315        assert( eOp & (WO_LT|WO_LE) );
165316        testcase( eOp & WO_LT );
165317        testcase( eOp & WO_LE );
165318        pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
165319        pNew->u.btree.nTop = nVecLen;
165320        pTop = pTerm;
165321        pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
165322                       pNew->aLTerm[pNew->nLTerm-2] : 0;
165323      }
165324    }
165325
165326    /* At this point pNew->nOut is set to the number of rows expected to
165327    ** be visited by the index scan before considering term pTerm, or the
165328    ** values of nIn and nInMul. In other words, assuming that all
165329    ** "x IN(...)" terms are replaced with "x = ?". This block updates
165330    ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
165331    assert( pNew->nOut==saved_nOut );
165332    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
165333      /* Adjust nOut using stat4 data. Or, if there is no stat4
165334      ** data, using some other estimate.  */
165335      whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
165336    }else{
165337      int nEq = ++pNew->u.btree.nEq;
165338      assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
165339
165340      assert( pNew->nOut==saved_nOut );
165341      if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
165342        assert( (eOp & WO_IN) || nIn==0 );
165343        testcase( eOp & WO_IN );
165344        pNew->nOut += pTerm->truthProb;
165345        pNew->nOut -= nIn;
165346      }else{
165347#ifdef SQLITE_ENABLE_STAT4
165348        tRowcnt nOut = 0;
165349        if( nInMul==0
165350         && pProbe->nSample
165351         && ALWAYS(pNew->u.btree.nEq<=pProbe->nSampleCol)
165352         && ((eOp & WO_IN)==0 || ExprUseXList(pTerm->pExpr))
165353         && OptimizationEnabled(db, SQLITE_Stat4)
165354        ){
165355          Expr *pExpr = pTerm->pExpr;
165356          if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
165357            testcase( eOp & WO_EQ );
165358            testcase( eOp & WO_IS );
165359            testcase( eOp & WO_ISNULL );
165360            rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
165361          }else{
165362            rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
165363          }
165364          if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
165365          if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
165366          if( nOut ){
165367            pNew->nOut = sqlite3LogEst(nOut);
165368            if( nEq==1
165369             /* TUNING: Mark terms as "low selectivity" if they seem likely
165370             ** to be true for half or more of the rows in the table.
165371             ** See tag-202002240-1 */
165372             && pNew->nOut+10 > pProbe->aiRowLogEst[0]
165373            ){
165374#if WHERETRACE_ENABLED /* 0x01 */
165375              if( sqlite3WhereTrace & 0x20 ){
165376                sqlite3DebugPrintf(
165377                   "STAT4 determines term has low selectivity:\n");
165378                sqlite3WhereTermPrint(pTerm, 999);
165379              }
165380#endif
165381              pTerm->wtFlags |= TERM_HIGHTRUTH;
165382              if( pTerm->wtFlags & TERM_HEURTRUTH ){
165383                /* If the term has previously been used with an assumption of
165384                ** higher selectivity, then set the flag to rerun the
165385                ** loop computations. */
165386                pBuilder->bldFlags2 |= SQLITE_BLDF2_2NDPASS;
165387              }
165388            }
165389            if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
165390            pNew->nOut -= nIn;
165391          }
165392        }
165393        if( nOut==0 )
165394#endif
165395        {
165396          pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
165397          if( eOp & WO_ISNULL ){
165398            /* TUNING: If there is no likelihood() value, assume that a
165399            ** "col IS NULL" expression matches twice as many rows
165400            ** as (col=?). */
165401            pNew->nOut += 10;
165402          }
165403        }
165404      }
165405    }
165406
165407    /* Set rCostIdx to the estimated cost of visiting selected rows in the
165408    ** index.  The estimate is the sum of two values:
165409    **   1.  The cost of doing one search-by-key to find the first matching
165410    **       entry
165411    **   2.  Stepping forward in the index pNew->nOut times to find all
165412    **       additional matching entries.
165413    */
165414    assert( pSrc->pTab->szTabRow>0 );
165415    if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
165416      /* The pProbe->szIdxRow is low for an IPK table since the interior
165417      ** pages are small.  Thus szIdxRow gives a good estimate of seek cost.
165418      ** But the leaf pages are full-size, so pProbe->szIdxRow would badly
165419      ** under-estimate the scanning cost. */
165420      rCostIdx = pNew->nOut + 16;
165421    }else{
165422      rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
165423    }
165424    rCostIdx = sqlite3LogEstAdd(rLogSize, rCostIdx);
165425
165426    /* Estimate the cost of running the loop.  If all data is coming
165427    ** from the index, then this is just the cost of doing the index
165428    ** lookup and scan.  But if some data is coming out of the main table,
165429    ** we also have to add in the cost of doing pNew->nOut searches to
165430    ** locate the row in the main table that corresponds to the index entry.
165431    */
165432    pNew->rRun = rCostIdx;
165433    if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK|WHERE_EXPRIDX))==0 ){
165434      pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
165435    }
165436    ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
165437
165438    nOutUnadjusted = pNew->nOut;
165439    pNew->rRun += nInMul + nIn;
165440    pNew->nOut += nInMul + nIn;
165441    whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
165442    rc = whereLoopInsert(pBuilder, pNew);
165443
165444    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
165445      pNew->nOut = saved_nOut;
165446    }else{
165447      pNew->nOut = nOutUnadjusted;
165448    }
165449
165450    if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
165451     && pNew->u.btree.nEq<pProbe->nColumn
165452     && (pNew->u.btree.nEq<pProbe->nKeyCol ||
165453           pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY)
165454    ){
165455      if( pNew->u.btree.nEq>3 ){
165456        sqlite3ProgressCheck(pParse);
165457      }
165458      whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
165459    }
165460    pNew->nOut = saved_nOut;
165461#ifdef SQLITE_ENABLE_STAT4
165462    pBuilder->nRecValid = nRecValid;
165463#endif
165464  }
165465  pNew->prereq = saved_prereq;
165466  pNew->u.btree.nEq = saved_nEq;
165467  pNew->u.btree.nBtm = saved_nBtm;
165468  pNew->u.btree.nTop = saved_nTop;
165469  pNew->nSkip = saved_nSkip;
165470  pNew->wsFlags = saved_wsFlags;
165471  pNew->nOut = saved_nOut;
165472  pNew->nLTerm = saved_nLTerm;
165473
165474  /* Consider using a skip-scan if there are no WHERE clause constraints
165475  ** available for the left-most terms of the index, and if the average
165476  ** number of repeats in the left-most terms is at least 18.
165477  **
165478  ** The magic number 18 is selected on the basis that scanning 17 rows
165479  ** is almost always quicker than an index seek (even though if the index
165480  ** contains fewer than 2^17 rows we assume otherwise in other parts of
165481  ** the code). And, even if it is not, it should not be too much slower.
165482  ** On the other hand, the extra seeks could end up being significantly
165483  ** more expensive.  */
165484  assert( 42==sqlite3LogEst(18) );
165485  if( saved_nEq==saved_nSkip
165486   && saved_nEq+1<pProbe->nKeyCol
165487   && saved_nEq==pNew->nLTerm
165488   && pProbe->noSkipScan==0
165489   && pProbe->hasStat1!=0
165490   && OptimizationEnabled(db, SQLITE_SkipScan)
165491   && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
165492   && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
165493  ){
165494    LogEst nIter;
165495    pNew->u.btree.nEq++;
165496    pNew->nSkip++;
165497    pNew->aLTerm[pNew->nLTerm++] = 0;
165498    pNew->wsFlags |= WHERE_SKIPSCAN;
165499    nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
165500    pNew->nOut -= nIter;
165501    /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
165502    ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
165503    nIter += 5;
165504    whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
165505    pNew->nOut = saved_nOut;
165506    pNew->u.btree.nEq = saved_nEq;
165507    pNew->nSkip = saved_nSkip;
165508    pNew->wsFlags = saved_wsFlags;
165509  }
165510
165511  WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
165512                      pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
165513  return rc;
165514}
165515
165516/*
165517** Return True if it is possible that pIndex might be useful in
165518** implementing the ORDER BY clause in pBuilder.
165519**
165520** Return False if pBuilder does not contain an ORDER BY clause or
165521** if there is no way for pIndex to be useful in implementing that
165522** ORDER BY clause.
165523*/
165524static int indexMightHelpWithOrderBy(
165525  WhereLoopBuilder *pBuilder,
165526  Index *pIndex,
165527  int iCursor
165528){
165529  ExprList *pOB;
165530  ExprList *aColExpr;
165531  int ii, jj;
165532
165533  if( pIndex->bUnordered ) return 0;
165534  if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
165535  for(ii=0; ii<pOB->nExpr; ii++){
165536    Expr *pExpr = sqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr);
165537    if( NEVER(pExpr==0) ) continue;
165538    if( (pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN)
165539     && pExpr->iTable==iCursor
165540    ){
165541      if( pExpr->iColumn<0 ) return 1;
165542      for(jj=0; jj<pIndex->nKeyCol; jj++){
165543        if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
165544      }
165545    }else if( (aColExpr = pIndex->aColExpr)!=0 ){
165546      for(jj=0; jj<pIndex->nKeyCol; jj++){
165547        if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
165548        if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
165549          return 1;
165550        }
165551      }
165552    }
165553  }
165554  return 0;
165555}
165556
165557/* Check to see if a partial index with pPartIndexWhere can be used
165558** in the current query.  Return true if it can be and false if not.
165559*/
165560static int whereUsablePartialIndex(
165561  int iTab,             /* The table for which we want an index */
165562  u8 jointype,          /* The JT_* flags on the join */
165563  WhereClause *pWC,     /* The WHERE clause of the query */
165564  Expr *pWhere          /* The WHERE clause from the partial index */
165565){
165566  int i;
165567  WhereTerm *pTerm;
165568  Parse *pParse;
165569
165570  if( jointype & JT_LTORJ ) return 0;
165571  pParse = pWC->pWInfo->pParse;
165572  while( pWhere->op==TK_AND ){
165573    if( !whereUsablePartialIndex(iTab,jointype,pWC,pWhere->pLeft) ) return 0;
165574    pWhere = pWhere->pRight;
165575  }
165576  if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
165577  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
165578    Expr *pExpr;
165579    pExpr = pTerm->pExpr;
165580    if( (!ExprHasProperty(pExpr, EP_OuterON) || pExpr->w.iJoin==iTab)
165581     && ((jointype & JT_OUTER)==0 || ExprHasProperty(pExpr, EP_OuterON))
165582     && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
165583     && (pTerm->wtFlags & TERM_VNULL)==0
165584    ){
165585      return 1;
165586    }
165587  }
165588  return 0;
165589}
165590
165591/*
165592** pIdx is an index containing expressions.  Check it see if any of the
165593** expressions in the index match the pExpr expression.
165594*/
165595static int exprIsCoveredByIndex(
165596  const Expr *pExpr,
165597  const Index *pIdx,
165598  int iTabCur
165599){
165600  int i;
165601  for(i=0; i<pIdx->nColumn; i++){
165602    if( pIdx->aiColumn[i]==XN_EXPR
165603     && sqlite3ExprCompare(0, pExpr, pIdx->aColExpr->a[i].pExpr, iTabCur)==0
165604    ){
165605      return 1;
165606    }
165607  }
165608  return 0;
165609}
165610
165611/*
165612** Structure passed to the whereIsCoveringIndex Walker callback.
165613*/
165614typedef struct CoveringIndexCheck CoveringIndexCheck;
165615struct CoveringIndexCheck {
165616  Index *pIdx;       /* The index */
165617  int iTabCur;       /* Cursor number for the corresponding table */
165618  u8 bExpr;          /* Uses an indexed expression */
165619  u8 bUnidx;         /* Uses an unindexed column not within an indexed expr */
165620};
165621
165622/*
165623** Information passed in is pWalk->u.pCovIdxCk.  Call it pCk.
165624**
165625** If the Expr node references the table with cursor pCk->iTabCur, then
165626** make sure that column is covered by the index pCk->pIdx.  We know that
165627** all columns less than 63 (really BMS-1) are covered, so we don't need
165628** to check them.  But we do need to check any column at 63 or greater.
165629**
165630** If the index does not cover the column, then set pWalk->eCode to
165631** non-zero and return WRC_Abort to stop the search.
165632**
165633** If this node does not disprove that the index can be a covering index,
165634** then just return WRC_Continue, to continue the search.
165635**
165636** If pCk->pIdx contains indexed expressions and one of those expressions
165637** matches pExpr, then prune the search.
165638*/
165639static int whereIsCoveringIndexWalkCallback(Walker *pWalk, Expr *pExpr){
165640  int i;                    /* Loop counter */
165641  const Index *pIdx;        /* The index of interest */
165642  const i16 *aiColumn;      /* Columns contained in the index */
165643  u16 nColumn;              /* Number of columns in the index */
165644  CoveringIndexCheck *pCk;  /* Info about this search */
165645
165646  pCk = pWalk->u.pCovIdxCk;
165647  pIdx = pCk->pIdx;
165648  if( (pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN) ){
165649    /* if( pExpr->iColumn<(BMS-1) && pIdx->bHasExpr==0 ) return WRC_Continue;*/
165650    if( pExpr->iTable!=pCk->iTabCur ) return WRC_Continue;
165651    pIdx = pWalk->u.pCovIdxCk->pIdx;
165652    aiColumn = pIdx->aiColumn;
165653    nColumn = pIdx->nColumn;
165654    for(i=0; i<nColumn; i++){
165655      if( aiColumn[i]==pExpr->iColumn ) return WRC_Continue;
165656    }
165657    pCk->bUnidx = 1;
165658    return WRC_Abort;
165659  }else if( pIdx->bHasExpr
165660         && exprIsCoveredByIndex(pExpr, pIdx, pWalk->u.pCovIdxCk->iTabCur) ){
165661    pCk->bExpr = 1;
165662    return WRC_Prune;
165663  }
165664  return WRC_Continue;
165665}
165666
165667
165668/*
165669** pIdx is an index that covers all of the low-number columns used by
165670** pWInfo->pSelect (columns from 0 through 62) or an index that has
165671** expressions terms.  Hence, we cannot determine whether or not it is
165672** a covering index by using the colUsed bitmasks.  We have to do a search
165673** to see if the index is covering.  This routine does that search.
165674**
165675** The return value is one of these:
165676**
165677**      0                The index is definitely not a covering index
165678**
165679**      WHERE_IDX_ONLY   The index is definitely a covering index
165680**
165681**      WHERE_EXPRIDX    The index is likely a covering index, but it is
165682**                       difficult to determine precisely because of the
165683**                       expressions that are indexed.  Score it as a
165684**                       covering index, but still keep the main table open
165685**                       just in case we need it.
165686**
165687** This routine is an optimization.  It is always safe to return zero.
165688** But returning one of the other two values when zero should have been
165689** returned can lead to incorrect bytecode and assertion faults.
165690*/
165691static SQLITE_NOINLINE u32 whereIsCoveringIndex(
165692  WhereInfo *pWInfo,     /* The WHERE clause context */
165693  Index *pIdx,           /* Index that is being tested */
165694  int iTabCur            /* Cursor for the table being indexed */
165695){
165696  int i, rc;
165697  struct CoveringIndexCheck ck;
165698  Walker w;
165699  if( pWInfo->pSelect==0 ){
165700    /* We don't have access to the full query, so we cannot check to see
165701    ** if pIdx is covering.  Assume it is not. */
165702    return 0;
165703  }
165704  if( pIdx->bHasExpr==0 ){
165705    for(i=0; i<pIdx->nColumn; i++){
165706      if( pIdx->aiColumn[i]>=BMS-1 ) break;
165707    }
165708    if( i>=pIdx->nColumn ){
165709      /* pIdx does not index any columns greater than 62, but we know from
165710      ** colMask that columns greater than 62 are used, so this is not a
165711      ** covering index */
165712      return 0;
165713    }
165714  }
165715  ck.pIdx = pIdx;
165716  ck.iTabCur = iTabCur;
165717  ck.bExpr = 0;
165718  ck.bUnidx = 0;
165719  memset(&w, 0, sizeof(w));
165720  w.xExprCallback = whereIsCoveringIndexWalkCallback;
165721  w.xSelectCallback = sqlite3SelectWalkNoop;
165722  w.u.pCovIdxCk = &ck;
165723  sqlite3WalkSelect(&w, pWInfo->pSelect);
165724  if( ck.bUnidx ){
165725    rc = 0;
165726  }else if( ck.bExpr ){
165727    rc = WHERE_EXPRIDX;
165728  }else{
165729    rc = WHERE_IDX_ONLY;
165730  }
165731  return rc;
165732}
165733
165734/*
165735** This is an sqlite3ParserAddCleanup() callback that is invoked to
165736** free the Parse->pIdxEpr list when the Parse object is destroyed.
165737*/
165738static void whereIndexedExprCleanup(sqlite3 *db, void *pObject){
165739  IndexedExpr **pp = (IndexedExpr**)pObject;
165740  while( *pp!=0 ){
165741    IndexedExpr *p = *pp;
165742    *pp = p->pIENext;
165743    sqlite3ExprDelete(db, p->pExpr);
165744    sqlite3DbFreeNN(db, p);
165745  }
165746}
165747
165748/*
165749** This function is called for a partial index - one with a WHERE clause - in
165750** two scenarios. In both cases, it determines whether or not the WHERE
165751** clause on the index implies that a column of the table may be safely
165752** replaced by a constant expression. For example, in the following
165753** SELECT:
165754**
165755**   CREATE INDEX i1 ON t1(b, c) WHERE a=<expr>;
165756**   SELECT a, b, c FROM t1 WHERE a=<expr> AND b=?;
165757**
165758** The "a" in the select-list may be replaced by <expr>, iff:
165759**
165760**    (a) <expr> is a constant expression, and
165761**    (b) The (a=<expr>) comparison uses the BINARY collation sequence, and
165762**    (c) Column "a" has an affinity other than NONE or BLOB.
165763**
165764** If argument pItem is NULL, then pMask must not be NULL. In this case this
165765** function is being called as part of determining whether or not pIdx
165766** is a covering index. This function clears any bits in (*pMask)
165767** corresponding to columns that may be replaced by constants as described
165768** above.
165769**
165770** Otherwise, if pItem is not NULL, then this function is being called
165771** as part of coding a loop that uses index pIdx. In this case, add entries
165772** to the Parse.pIdxPartExpr list for each column that can be replaced
165773** by a constant.
165774*/
165775static void wherePartIdxExpr(
165776  Parse *pParse,                  /* Parse context */
165777  Index *pIdx,                    /* Partial index being processed */
165778  Expr *pPart,                    /* WHERE clause being processed */
165779  Bitmask *pMask,                 /* Mask to clear bits in */
165780  int iIdxCur,                    /* Cursor number for index */
165781  SrcItem *pItem                  /* The FROM clause entry for the table */
165782){
165783  assert( pItem==0 || (pItem->fg.jointype & JT_RIGHT)==0 );
165784  assert( (pItem==0 || pMask==0) && (pMask!=0 || pItem!=0) );
165785
165786  if( pPart->op==TK_AND ){
165787    wherePartIdxExpr(pParse, pIdx, pPart->pRight, pMask, iIdxCur, pItem);
165788    pPart = pPart->pLeft;
165789  }
165790
165791  if( (pPart->op==TK_EQ || pPart->op==TK_IS) ){
165792    Expr *pLeft = pPart->pLeft;
165793    Expr *pRight = pPart->pRight;
165794    u8 aff;
165795
165796    if( pLeft->op!=TK_COLUMN ) return;
165797    if( !sqlite3ExprIsConstant(0, pRight) ) return;
165798    if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pParse, pPart)) ) return;
165799    if( pLeft->iColumn<0 ) return;
165800    aff = pIdx->pTable->aCol[pLeft->iColumn].affinity;
165801    if( aff>=SQLITE_AFF_TEXT ){
165802      if( pItem ){
165803        sqlite3 *db = pParse->db;
165804        IndexedExpr *p = (IndexedExpr*)sqlite3DbMallocRaw(db, sizeof(*p));
165805        if( p ){
165806          int bNullRow = (pItem->fg.jointype&(JT_LEFT|JT_LTORJ))!=0;
165807          p->pExpr = sqlite3ExprDup(db, pRight, 0);
165808          p->iDataCur = pItem->iCursor;
165809          p->iIdxCur = iIdxCur;
165810          p->iIdxCol = pLeft->iColumn;
165811          p->bMaybeNullRow = bNullRow;
165812          p->pIENext = pParse->pIdxPartExpr;
165813          p->aff = aff;
165814          pParse->pIdxPartExpr = p;
165815          if( p->pIENext==0 ){
165816            void *pArg = (void*)&pParse->pIdxPartExpr;
165817            sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pArg);
165818          }
165819        }
165820      }else if( pLeft->iColumn<(BMS-1) ){
165821        *pMask &= ~((Bitmask)1 << pLeft->iColumn);
165822      }
165823    }
165824  }
165825}
165826
165827
165828/*
165829** Add all WhereLoop objects for a single table of the join where the table
165830** is identified by pBuilder->pNew->iTab.  That table is guaranteed to be
165831** a b-tree table, not a virtual table.
165832**
165833** The costs (WhereLoop.rRun) of the b-tree loops added by this function
165834** are calculated as follows:
165835**
165836** For a full scan, assuming the table (or index) contains nRow rows:
165837**
165838**     cost = nRow * 3.0                    // full-table scan
165839**     cost = nRow * K                      // scan of covering index
165840**     cost = nRow * (K+3.0)                // scan of non-covering index
165841**
165842** where K is a value between 1.1 and 3.0 set based on the relative
165843** estimated average size of the index and table records.
165844**
165845** For an index scan, where nVisit is the number of index rows visited
165846** by the scan, and nSeek is the number of seek operations required on
165847** the index b-tree:
165848**
165849**     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
165850**     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
165851**
165852** Normally, nSeek is 1. nSeek values greater than 1 come about if the
165853** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
165854** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
165855**
165856** The estimated values (nRow, nVisit, nSeek) often contain a large amount
165857** of uncertainty.  For this reason, scoring is designed to pick plans that
165858** "do the least harm" if the estimates are inaccurate.  For example, a
165859** log(nRow) factor is omitted from a non-covering index scan in order to
165860** bias the scoring in favor of using an index, since the worst-case
165861** performance of using an index is far better than the worst-case performance
165862** of a full table scan.
165863*/
165864static int whereLoopAddBtree(
165865  WhereLoopBuilder *pBuilder, /* WHERE clause information */
165866  Bitmask mPrereq             /* Extra prerequisites for using this table */
165867){
165868  WhereInfo *pWInfo;          /* WHERE analysis context */
165869  Index *pProbe;              /* An index we are evaluating */
165870  Index sPk;                  /* A fake index object for the primary key */
165871  LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
165872  i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
165873  SrcList *pTabList;          /* The FROM clause */
165874  SrcItem *pSrc;              /* The FROM clause btree term to add */
165875  WhereLoop *pNew;            /* Template WhereLoop object */
165876  int rc = SQLITE_OK;         /* Return code */
165877  int iSortIdx = 1;           /* Index number */
165878  int b;                      /* A boolean value */
165879  LogEst rSize;               /* number of rows in the table */
165880  WhereClause *pWC;           /* The parsed WHERE clause */
165881  Table *pTab;                /* Table being queried */
165882
165883  pNew = pBuilder->pNew;
165884  pWInfo = pBuilder->pWInfo;
165885  pTabList = pWInfo->pTabList;
165886  pSrc = pTabList->a + pNew->iTab;
165887  pTab = pSrc->pTab;
165888  pWC = pBuilder->pWC;
165889  assert( !IsVirtual(pSrc->pTab) );
165890
165891  if( pSrc->fg.isIndexedBy ){
165892    assert( pSrc->fg.isCte==0 );
165893    /* An INDEXED BY clause specifies a particular index to use */
165894    pProbe = pSrc->u2.pIBIndex;
165895  }else if( !HasRowid(pTab) ){
165896    pProbe = pTab->pIndex;
165897  }else{
165898    /* There is no INDEXED BY clause.  Create a fake Index object in local
165899    ** variable sPk to represent the rowid primary key index.  Make this
165900    ** fake index the first in a chain of Index objects with all of the real
165901    ** indices to follow */
165902    Index *pFirst;                  /* First of real indices on the table */
165903    memset(&sPk, 0, sizeof(Index));
165904    sPk.nKeyCol = 1;
165905    sPk.nColumn = 1;
165906    sPk.aiColumn = &aiColumnPk;
165907    sPk.aiRowLogEst = aiRowEstPk;
165908    sPk.onError = OE_Replace;
165909    sPk.pTable = pTab;
165910    sPk.szIdxRow = 3;  /* TUNING: Interior rows of IPK table are very small */
165911    sPk.idxType = SQLITE_IDXTYPE_IPK;
165912    aiRowEstPk[0] = pTab->nRowLogEst;
165913    aiRowEstPk[1] = 0;
165914    pFirst = pSrc->pTab->pIndex;
165915    if( pSrc->fg.notIndexed==0 ){
165916      /* The real indices of the table are only considered if the
165917      ** NOT INDEXED qualifier is omitted from the FROM clause */
165918      sPk.pNext = pFirst;
165919    }
165920    pProbe = &sPk;
165921  }
165922  rSize = pTab->nRowLogEst;
165923
165924#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
165925  /* Automatic indexes */
165926  if( !pBuilder->pOrSet      /* Not part of an OR optimization */
165927   && (pWInfo->wctrlFlags & (WHERE_RIGHT_JOIN|WHERE_OR_SUBCLAUSE))==0
165928   && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
165929   && !pSrc->fg.isIndexedBy  /* Has no INDEXED BY clause */
165930   && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */
165931   && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */
165932   && !pSrc->fg.isCorrelated /* Not a correlated subquery */
165933   && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */
165934   && (pSrc->fg.jointype & JT_RIGHT)==0 /* Not the right tab of a RIGHT JOIN */
165935  ){
165936    /* Generate auto-index WhereLoops */
165937    LogEst rLogSize;         /* Logarithm of the number of rows in the table */
165938    WhereTerm *pTerm;
165939    WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
165940    rLogSize = estLog(rSize);
165941    for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
165942      if( pTerm->prereqRight & pNew->maskSelf ) continue;
165943      if( termCanDriveIndex(pTerm, pSrc, 0) ){
165944        pNew->u.btree.nEq = 1;
165945        pNew->nSkip = 0;
165946        pNew->u.btree.pIndex = 0;
165947        pNew->nLTerm = 1;
165948        pNew->aLTerm[0] = pTerm;
165949        /* TUNING: One-time cost for computing the automatic index is
165950        ** estimated to be X*N*log2(N) where N is the number of rows in
165951        ** the table being indexed and where X is 7 (LogEst=28) for normal
165952        ** tables or 0.5 (LogEst=-10) for views and subqueries.  The value
165953        ** of X is smaller for views and subqueries so that the query planner
165954        ** will be more aggressive about generating automatic indexes for
165955        ** those objects, since there is no opportunity to add schema
165956        ** indexes on subqueries and views. */
165957        pNew->rSetup = rLogSize + rSize;
165958        if( !IsView(pTab) && (pTab->tabFlags & TF_Ephemeral)==0 ){
165959          pNew->rSetup += 28;
165960        }else{
165961          pNew->rSetup -= 25;  /* Greatly reduced setup cost for auto indexes
165962                               ** on ephemeral materializations of views */
165963        }
165964        ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
165965        if( pNew->rSetup<0 ) pNew->rSetup = 0;
165966        /* TUNING: Each index lookup yields 20 rows in the table.  This
165967        ** is more than the usual guess of 10 rows, since we have no way
165968        ** of knowing how selective the index will ultimately be.  It would
165969        ** not be unreasonable to make this value much larger. */
165970        pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
165971        pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
165972        pNew->wsFlags = WHERE_AUTO_INDEX;
165973        pNew->prereq = mPrereq | pTerm->prereqRight;
165974        rc = whereLoopInsert(pBuilder, pNew);
165975      }
165976    }
165977  }
165978#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
165979
165980  /* Loop over all indices. If there was an INDEXED BY clause, then only
165981  ** consider index pProbe.  */
165982  for(; rc==SQLITE_OK && pProbe;
165983      pProbe=(pSrc->fg.isIndexedBy ? 0 : pProbe->pNext), iSortIdx++
165984  ){
165985    if( pProbe->pPartIdxWhere!=0
165986     && !whereUsablePartialIndex(pSrc->iCursor, pSrc->fg.jointype, pWC,
165987                                 pProbe->pPartIdxWhere)
165988    ){
165989      testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
165990      continue;  /* Partial index inappropriate for this query */
165991    }
165992    if( pProbe->bNoQuery ) continue;
165993    rSize = pProbe->aiRowLogEst[0];
165994    pNew->u.btree.nEq = 0;
165995    pNew->u.btree.nBtm = 0;
165996    pNew->u.btree.nTop = 0;
165997    pNew->nSkip = 0;
165998    pNew->nLTerm = 0;
165999    pNew->iSortIdx = 0;
166000    pNew->rSetup = 0;
166001    pNew->prereq = mPrereq;
166002    pNew->nOut = rSize;
166003    pNew->u.btree.pIndex = pProbe;
166004    b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
166005
166006    /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
166007    assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
166008    if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
166009      /* Integer primary key index */
166010      pNew->wsFlags = WHERE_IPK;
166011
166012      /* Full table scan */
166013      pNew->iSortIdx = b ? iSortIdx : 0;
166014      /* TUNING: Cost of full table scan is 3.0*N.  The 3.0 factor is an
166015      ** extra cost designed to discourage the use of full table scans,
166016      ** since index lookups have better worst-case performance if our
166017      ** stat guesses are wrong.  Reduce the 3.0 penalty slightly
166018      ** (to 2.75) if we have valid STAT4 information for the table.
166019      ** At 2.75, a full table scan is preferred over using an index on
166020      ** a column with just two distinct values where each value has about
166021      ** an equal number of appearances.  Without STAT4 data, we still want
166022      ** to use an index in that case, since the constraint might be for
166023      ** the scarcer of the two values, and in that case an index lookup is
166024      ** better.
166025      */
166026#ifdef SQLITE_ENABLE_STAT4
166027      pNew->rRun = rSize + 16 - 2*((pTab->tabFlags & TF_HasStat4)!=0);
166028#else
166029      pNew->rRun = rSize + 16;
166030#endif
166031      ApplyCostMultiplier(pNew->rRun, pTab->costMult);
166032      whereLoopOutputAdjust(pWC, pNew, rSize);
166033      rc = whereLoopInsert(pBuilder, pNew);
166034      pNew->nOut = rSize;
166035      if( rc ) break;
166036    }else{
166037      Bitmask m;
166038      if( pProbe->isCovering ){
166039        m = 0;
166040        pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
166041      }else{
166042        m = pSrc->colUsed & pProbe->colNotIdxed;
166043        if( pProbe->pPartIdxWhere ){
166044          wherePartIdxExpr(
166045              pWInfo->pParse, pProbe, pProbe->pPartIdxWhere, &m, 0, 0
166046          );
166047        }
166048        pNew->wsFlags = WHERE_INDEXED;
166049        if( m==TOPBIT || (pProbe->bHasExpr && !pProbe->bHasVCol && m!=0) ){
166050          u32 isCov = whereIsCoveringIndex(pWInfo, pProbe, pSrc->iCursor);
166051          if( isCov==0 ){
166052            WHERETRACE(0x200,
166053               ("-> %s is not a covering index"
166054                " according to whereIsCoveringIndex()\n", pProbe->zName));
166055            assert( m!=0 );
166056          }else{
166057            m = 0;
166058            pNew->wsFlags |= isCov;
166059            if( isCov & WHERE_IDX_ONLY ){
166060              WHERETRACE(0x200,
166061                 ("-> %s is a covering expression index"
166062                  " according to whereIsCoveringIndex()\n", pProbe->zName));
166063            }else{
166064              assert( isCov==WHERE_EXPRIDX );
166065              WHERETRACE(0x200,
166066                 ("-> %s might be a covering expression index"
166067                  " according to whereIsCoveringIndex()\n", pProbe->zName));
166068            }
166069          }
166070        }else if( m==0 ){
166071          WHERETRACE(0x200,
166072             ("-> %s a covering index according to bitmasks\n",
166073             pProbe->zName, m==0 ? "is" : "is not"));
166074          pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
166075        }
166076      }
166077
166078      /* Full scan via index */
166079      if( b
166080       || !HasRowid(pTab)
166081       || pProbe->pPartIdxWhere!=0
166082       || pSrc->fg.isIndexedBy
166083       || ( m==0
166084         && pProbe->bUnordered==0
166085         && (pProbe->szIdxRow<pTab->szTabRow)
166086         && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
166087         && sqlite3GlobalConfig.bUseCis
166088         && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
166089          )
166090      ){
166091        pNew->iSortIdx = b ? iSortIdx : 0;
166092
166093        /* The cost of visiting the index rows is N*K, where K is
166094        ** between 1.1 and 3.0, depending on the relative sizes of the
166095        ** index and table rows. */
166096        pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
166097        if( m!=0 ){
166098          /* If this is a non-covering index scan, add in the cost of
166099          ** doing table lookups.  The cost will be 3x the number of
166100          ** lookups.  Take into account WHERE clause terms that can be
166101          ** satisfied using just the index, and that do not require a
166102          ** table lookup. */
166103          LogEst nLookup = rSize + 16;  /* Base cost:  N*3 */
166104          int ii;
166105          int iCur = pSrc->iCursor;
166106          WhereClause *pWC2 = &pWInfo->sWC;
166107          for(ii=0; ii<pWC2->nTerm; ii++){
166108            WhereTerm *pTerm = &pWC2->a[ii];
166109            if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
166110              break;
166111            }
166112            /* pTerm can be evaluated using just the index.  So reduce
166113            ** the expected number of table lookups accordingly */
166114            if( pTerm->truthProb<=0 ){
166115              nLookup += pTerm->truthProb;
166116            }else{
166117              nLookup--;
166118              if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
166119            }
166120          }
166121
166122          pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
166123        }
166124        ApplyCostMultiplier(pNew->rRun, pTab->costMult);
166125        whereLoopOutputAdjust(pWC, pNew, rSize);
166126        if( (pSrc->fg.jointype & JT_RIGHT)!=0 && pProbe->aColExpr ){
166127          /* Do not do an SCAN of a index-on-expression in a RIGHT JOIN
166128          ** because the cursor used to access the index might not be
166129          ** positioned to the correct row during the right-join no-match
166130          ** loop. */
166131        }else{
166132          rc = whereLoopInsert(pBuilder, pNew);
166133        }
166134        pNew->nOut = rSize;
166135        if( rc ) break;
166136      }
166137    }
166138
166139    pBuilder->bldFlags1 = 0;
166140    rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
166141    if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){
166142      /* If a non-unique index is used, or if a prefix of the key for
166143      ** unique index is used (making the index functionally non-unique)
166144      ** then the sqlite_stat1 data becomes important for scoring the
166145      ** plan */
166146      pTab->tabFlags |= TF_MaybeReanalyze;
166147    }
166148#ifdef SQLITE_ENABLE_STAT4
166149    sqlite3Stat4ProbeFree(pBuilder->pRec);
166150    pBuilder->nRecValid = 0;
166151    pBuilder->pRec = 0;
166152#endif
166153  }
166154  return rc;
166155}
166156
166157#ifndef SQLITE_OMIT_VIRTUALTABLE
166158
166159/*
166160** Return true if pTerm is a virtual table LIMIT or OFFSET term.
166161*/
166162static int isLimitTerm(WhereTerm *pTerm){
166163  assert( pTerm->eOperator==WO_AUX || pTerm->eMatchOp==0 );
166164  return pTerm->eMatchOp>=SQLITE_INDEX_CONSTRAINT_LIMIT
166165      && pTerm->eMatchOp<=SQLITE_INDEX_CONSTRAINT_OFFSET;
166166}
166167
166168/*
166169** Return true if the first nCons constraints in the pUsage array are
166170** marked as in-use (have argvIndex>0). False otherwise.
166171*/
166172static int allConstraintsUsed(
166173  struct sqlite3_index_constraint_usage *aUsage,
166174  int nCons
166175){
166176  int ii;
166177  for(ii=0; ii<nCons; ii++){
166178    if( aUsage[ii].argvIndex<=0 ) return 0;
166179  }
166180  return 1;
166181}
166182
166183/*
166184** Argument pIdxInfo is already populated with all constraints that may
166185** be used by the virtual table identified by pBuilder->pNew->iTab. This
166186** function marks a subset of those constraints usable, invokes the
166187** xBestIndex method and adds the returned plan to pBuilder.
166188**
166189** A constraint is marked usable if:
166190**
166191**   * Argument mUsable indicates that its prerequisites are available, and
166192**
166193**   * It is not one of the operators specified in the mExclude mask passed
166194**     as the fourth argument (which in practice is either WO_IN or 0).
166195**
166196** Argument mPrereq is a mask of tables that must be scanned before the
166197** virtual table in question. These are added to the plans prerequisites
166198** before it is added to pBuilder.
166199**
166200** Output parameter *pbIn is set to true if the plan added to pBuilder
166201** uses one or more WO_IN terms, or false otherwise.
166202*/
166203static int whereLoopAddVirtualOne(
166204  WhereLoopBuilder *pBuilder,
166205  Bitmask mPrereq,                /* Mask of tables that must be used. */
166206  Bitmask mUsable,                /* Mask of usable tables */
166207  u16 mExclude,                   /* Exclude terms using these operators */
166208  sqlite3_index_info *pIdxInfo,   /* Populated object for xBestIndex */
166209  u16 mNoOmit,                    /* Do not omit these constraints */
166210  int *pbIn,                      /* OUT: True if plan uses an IN(...) op */
166211  int *pbRetryLimit               /* OUT: Retry without LIMIT/OFFSET */
166212){
166213  WhereClause *pWC = pBuilder->pWC;
166214  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
166215  struct sqlite3_index_constraint *pIdxCons;
166216  struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
166217  int i;
166218  int mxTerm;
166219  int rc = SQLITE_OK;
166220  WhereLoop *pNew = pBuilder->pNew;
166221  Parse *pParse = pBuilder->pWInfo->pParse;
166222  SrcItem *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
166223  int nConstraint = pIdxInfo->nConstraint;
166224
166225  assert( (mUsable & mPrereq)==mPrereq );
166226  *pbIn = 0;
166227  pNew->prereq = mPrereq;
166228
166229  /* Set the usable flag on the subset of constraints identified by
166230  ** arguments mUsable and mExclude. */
166231  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
166232  for(i=0; i<nConstraint; i++, pIdxCons++){
166233    WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
166234    pIdxCons->usable = 0;
166235    if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
166236     && (pTerm->eOperator & mExclude)==0
166237     && (pbRetryLimit || !isLimitTerm(pTerm))
166238    ){
166239      pIdxCons->usable = 1;
166240    }
166241  }
166242
166243  /* Initialize the output fields of the sqlite3_index_info structure */
166244  memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
166245  assert( pIdxInfo->needToFreeIdxStr==0 );
166246  pIdxInfo->idxStr = 0;
166247  pIdxInfo->idxNum = 0;
166248  pIdxInfo->orderByConsumed = 0;
166249  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
166250  pIdxInfo->estimatedRows = 25;
166251  pIdxInfo->idxFlags = 0;
166252  pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
166253  pHidden->mHandleIn = 0;
166254
166255  /* Invoke the virtual table xBestIndex() method */
166256  rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
166257  if( rc ){
166258    if( rc==SQLITE_CONSTRAINT ){
166259      /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
166260      ** that the particular combination of parameters provided is unusable.
166261      ** Make no entries in the loop table.
166262      */
166263      WHERETRACE(0xffffffff, ("  ^^^^--- non-viable plan rejected!\n"));
166264      return SQLITE_OK;
166265    }
166266    return rc;
166267  }
166268
166269  mxTerm = -1;
166270  assert( pNew->nLSlot>=nConstraint );
166271  memset(pNew->aLTerm, 0, sizeof(pNew->aLTerm[0])*nConstraint );
166272  memset(&pNew->u.vtab, 0, sizeof(pNew->u.vtab));
166273  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
166274  for(i=0; i<nConstraint; i++, pIdxCons++){
166275    int iTerm;
166276    if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
166277      WhereTerm *pTerm;
166278      int j = pIdxCons->iTermOffset;
166279      if( iTerm>=nConstraint
166280       || j<0
166281       || j>=pWC->nTerm
166282       || pNew->aLTerm[iTerm]!=0
166283       || pIdxCons->usable==0
166284      ){
166285        sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
166286        testcase( pIdxInfo->needToFreeIdxStr );
166287        return SQLITE_ERROR;
166288      }
166289      testcase( iTerm==nConstraint-1 );
166290      testcase( j==0 );
166291      testcase( j==pWC->nTerm-1 );
166292      pTerm = &pWC->a[j];
166293      pNew->prereq |= pTerm->prereqRight;
166294      assert( iTerm<pNew->nLSlot );
166295      pNew->aLTerm[iTerm] = pTerm;
166296      if( iTerm>mxTerm ) mxTerm = iTerm;
166297      testcase( iTerm==15 );
166298      testcase( iTerm==16 );
166299      if( pUsage[i].omit ){
166300        if( i<16 && ((1<<i)&mNoOmit)==0 ){
166301          testcase( i!=iTerm );
166302          pNew->u.vtab.omitMask |= 1<<iTerm;
166303        }else{
166304          testcase( i!=iTerm );
166305        }
166306        if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET ){
166307          pNew->u.vtab.bOmitOffset = 1;
166308        }
166309      }
166310      if( SMASKBIT32(i) & pHidden->mHandleIn ){
166311        pNew->u.vtab.mHandleIn |= MASKBIT32(iTerm);
166312      }else if( (pTerm->eOperator & WO_IN)!=0 ){
166313        /* A virtual table that is constrained by an IN clause may not
166314        ** consume the ORDER BY clause because (1) the order of IN terms
166315        ** is not necessarily related to the order of output terms and
166316        ** (2) Multiple outputs from a single IN value will not merge
166317        ** together.  */
166318        pIdxInfo->orderByConsumed = 0;
166319        pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
166320        *pbIn = 1; assert( (mExclude & WO_IN)==0 );
166321      }
166322
166323      /* Unless pbRetryLimit is non-NULL, there should be no LIMIT/OFFSET
166324      ** terms. And if there are any, they should follow all other terms. */
166325      assert( pbRetryLimit || !isLimitTerm(pTerm) );
166326      assert( !isLimitTerm(pTerm) || i>=nConstraint-2 );
166327      assert( !isLimitTerm(pTerm) || i==nConstraint-1 || isLimitTerm(pTerm+1) );
166328
166329      if( isLimitTerm(pTerm) && (*pbIn || !allConstraintsUsed(pUsage, i)) ){
166330        /* If there is an IN(...) term handled as an == (separate call to
166331        ** xFilter for each value on the RHS of the IN) and a LIMIT or
166332        ** OFFSET term handled as well, the plan is unusable. Similarly,
166333        ** if there is a LIMIT/OFFSET and there are other unused terms,
166334        ** the plan cannot be used. In these cases set variable *pbRetryLimit
166335        ** to true to tell the caller to retry with LIMIT and OFFSET
166336        ** disabled. */
166337        if( pIdxInfo->needToFreeIdxStr ){
166338          sqlite3_free(pIdxInfo->idxStr);
166339          pIdxInfo->idxStr = 0;
166340          pIdxInfo->needToFreeIdxStr = 0;
166341        }
166342        *pbRetryLimit = 1;
166343        return SQLITE_OK;
166344      }
166345    }
166346  }
166347
166348  pNew->nLTerm = mxTerm+1;
166349  for(i=0; i<=mxTerm; i++){
166350    if( pNew->aLTerm[i]==0 ){
166351      /* The non-zero argvIdx values must be contiguous.  Raise an
166352      ** error if they are not */
166353      sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
166354      testcase( pIdxInfo->needToFreeIdxStr );
166355      return SQLITE_ERROR;
166356    }
166357  }
166358  assert( pNew->nLTerm<=pNew->nLSlot );
166359  pNew->u.vtab.idxNum = pIdxInfo->idxNum;
166360  pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
166361  pIdxInfo->needToFreeIdxStr = 0;
166362  pNew->u.vtab.idxStr = pIdxInfo->idxStr;
166363  pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
166364      pIdxInfo->nOrderBy : 0);
166365  pNew->rSetup = 0;
166366  pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
166367  pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
166368
166369  /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
166370  ** that the scan will visit at most one row. Clear it otherwise. */
166371  if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
166372    pNew->wsFlags |= WHERE_ONEROW;
166373  }else{
166374    pNew->wsFlags &= ~WHERE_ONEROW;
166375  }
166376  rc = whereLoopInsert(pBuilder, pNew);
166377  if( pNew->u.vtab.needFree ){
166378    sqlite3_free(pNew->u.vtab.idxStr);
166379    pNew->u.vtab.needFree = 0;
166380  }
166381  WHERETRACE(0xffffffff, ("  bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
166382                      *pbIn, (sqlite3_uint64)mPrereq,
166383                      (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
166384
166385  return rc;
166386}
166387
166388/*
166389** Return the collating sequence for a constraint passed into xBestIndex.
166390**
166391** pIdxInfo must be an sqlite3_index_info structure passed into xBestIndex.
166392** This routine depends on there being a HiddenIndexInfo structure immediately
166393** following the sqlite3_index_info structure.
166394**
166395** Return a pointer to the collation name:
166396**
166397**    1. If there is an explicit COLLATE operator on the constraint, return it.
166398**
166399**    2. Else, if the column has an alternative collation, return that.
166400**
166401**    3. Otherwise, return "BINARY".
166402*/
166403SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
166404  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
166405  const char *zRet = 0;
166406  if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
166407    CollSeq *pC = 0;
166408    int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
166409    Expr *pX = pHidden->pWC->a[iTerm].pExpr;
166410    if( pX->pLeft ){
166411      pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX);
166412    }
166413    zRet = (pC ? pC->zName : sqlite3StrBINARY);
166414  }
166415  return zRet;
166416}
166417
166418/*
166419** Return true if constraint iCons is really an IN(...) constraint, or
166420** false otherwise. If iCons is an IN(...) constraint, set (if bHandle!=0)
166421** or clear (if bHandle==0) the flag to handle it using an iterator.
166422*/
166423SQLITE_API int sqlite3_vtab_in(sqlite3_index_info *pIdxInfo, int iCons, int bHandle){
166424  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
166425  u32 m = SMASKBIT32(iCons);
166426  if( m & pHidden->mIn ){
166427    if( bHandle==0 ){
166428      pHidden->mHandleIn &= ~m;
166429    }else if( bHandle>0 ){
166430      pHidden->mHandleIn |= m;
166431    }
166432    return 1;
166433  }
166434  return 0;
166435}
166436
166437/*
166438** This interface is callable from within the xBestIndex callback only.
166439**
166440** If possible, set (*ppVal) to point to an object containing the value
166441** on the right-hand-side of constraint iCons.
166442*/
166443SQLITE_API int sqlite3_vtab_rhs_value(
166444  sqlite3_index_info *pIdxInfo,   /* Copy of first argument to xBestIndex */
166445  int iCons,                      /* Constraint for which RHS is wanted */
166446  sqlite3_value **ppVal           /* Write value extracted here */
166447){
166448  HiddenIndexInfo *pH = (HiddenIndexInfo*)&pIdxInfo[1];
166449  sqlite3_value *pVal = 0;
166450  int rc = SQLITE_OK;
166451  if( iCons<0 || iCons>=pIdxInfo->nConstraint ){
166452    rc = SQLITE_MISUSE_BKPT; /* EV: R-30545-25046 */
166453  }else{
166454    if( pH->aRhs[iCons]==0 ){
166455      WhereTerm *pTerm = &pH->pWC->a[pIdxInfo->aConstraint[iCons].iTermOffset];
166456      rc = sqlite3ValueFromExpr(
166457          pH->pParse->db, pTerm->pExpr->pRight, ENC(pH->pParse->db),
166458          SQLITE_AFF_BLOB, &pH->aRhs[iCons]
166459      );
166460      testcase( rc!=SQLITE_OK );
166461    }
166462    pVal = pH->aRhs[iCons];
166463  }
166464  *ppVal = pVal;
166465
166466  if( rc==SQLITE_OK && pVal==0 ){  /* IMP: R-19933-32160 */
166467    rc = SQLITE_NOTFOUND;          /* IMP: R-36424-56542 */
166468  }
166469
166470  return rc;
166471}
166472
166473/*
166474** Return true if ORDER BY clause may be handled as DISTINCT.
166475*/
166476SQLITE_API int sqlite3_vtab_distinct(sqlite3_index_info *pIdxInfo){
166477  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
166478  assert( pHidden->eDistinct>=0 && pHidden->eDistinct<=3 );
166479  return pHidden->eDistinct;
166480}
166481
166482/*
166483** Cause the prepared statement that is associated with a call to
166484** xBestIndex to potentially use all schemas.  If the statement being
166485** prepared is read-only, then just start read transactions on all
166486** schemas.  But if this is a write operation, start writes on all
166487** schemas.
166488**
166489** This is used by the (built-in) sqlite_dbpage virtual table.
166490*/
166491SQLITE_PRIVATE void sqlite3VtabUsesAllSchemas(Parse *pParse){
166492  int nDb = pParse->db->nDb;
166493  int i;
166494  for(i=0; i<nDb; i++){
166495    sqlite3CodeVerifySchema(pParse, i);
166496  }
166497  if( DbMaskNonZero(pParse->writeMask) ){
166498    for(i=0; i<nDb; i++){
166499      sqlite3BeginWriteOperation(pParse, 0, i);
166500    }
166501  }
166502}
166503
166504/*
166505** Add all WhereLoop objects for a table of the join identified by
166506** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
166507**
166508** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
166509** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
166510** entries that occur before the virtual table in the FROM clause and are
166511** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
166512** mUnusable mask contains all FROM clause entries that occur after the
166513** virtual table and are separated from it by at least one LEFT or
166514** CROSS JOIN.
166515**
166516** For example, if the query were:
166517**
166518**   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
166519**
166520** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
166521**
166522** All the tables in mPrereq must be scanned before the current virtual
166523** table. So any terms for which all prerequisites are satisfied by
166524** mPrereq may be specified as "usable" in all calls to xBestIndex.
166525** Conversely, all tables in mUnusable must be scanned after the current
166526** virtual table, so any terms for which the prerequisites overlap with
166527** mUnusable should always be configured as "not-usable" for xBestIndex.
166528*/
166529static int whereLoopAddVirtual(
166530  WhereLoopBuilder *pBuilder,  /* WHERE clause information */
166531  Bitmask mPrereq,             /* Tables that must be scanned before this one */
166532  Bitmask mUnusable            /* Tables that must be scanned after this one */
166533){
166534  int rc = SQLITE_OK;          /* Return code */
166535  WhereInfo *pWInfo;           /* WHERE analysis context */
166536  Parse *pParse;               /* The parsing context */
166537  WhereClause *pWC;            /* The WHERE clause */
166538  SrcItem *pSrc;               /* The FROM clause term to search */
166539  sqlite3_index_info *p;       /* Object to pass to xBestIndex() */
166540  int nConstraint;             /* Number of constraints in p */
166541  int bIn;                     /* True if plan uses IN(...) operator */
166542  WhereLoop *pNew;
166543  Bitmask mBest;               /* Tables used by best possible plan */
166544  u16 mNoOmit;
166545  int bRetry = 0;              /* True to retry with LIMIT/OFFSET disabled */
166546
166547  assert( (mPrereq & mUnusable)==0 );
166548  pWInfo = pBuilder->pWInfo;
166549  pParse = pWInfo->pParse;
166550  pWC = pBuilder->pWC;
166551  pNew = pBuilder->pNew;
166552  pSrc = &pWInfo->pTabList->a[pNew->iTab];
166553  assert( IsVirtual(pSrc->pTab) );
166554  p = allocateIndexInfo(pWInfo, pWC, mUnusable, pSrc, &mNoOmit);
166555  if( p==0 ) return SQLITE_NOMEM_BKPT;
166556  pNew->rSetup = 0;
166557  pNew->wsFlags = WHERE_VIRTUALTABLE;
166558  pNew->nLTerm = 0;
166559  pNew->u.vtab.needFree = 0;
166560  nConstraint = p->nConstraint;
166561  if( whereLoopResize(pParse->db, pNew, nConstraint) ){
166562    freeIndexInfo(pParse->db, p);
166563    return SQLITE_NOMEM_BKPT;
166564  }
166565
166566  /* First call xBestIndex() with all constraints usable. */
166567  WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
166568  WHERETRACE(0x800, ("  VirtualOne: all usable\n"));
166569  rc = whereLoopAddVirtualOne(
166570      pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, &bRetry
166571  );
166572  if( bRetry ){
166573    assert( rc==SQLITE_OK );
166574    rc = whereLoopAddVirtualOne(
166575        pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, 0
166576    );
166577  }
166578
166579  /* If the call to xBestIndex() with all terms enabled produced a plan
166580  ** that does not require any source tables (IOW: a plan with mBest==0)
166581  ** and does not use an IN(...) operator, then there is no point in making
166582  ** any further calls to xBestIndex() since they will all return the same
166583  ** result (if the xBestIndex() implementation is sane). */
166584  if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){
166585    int seenZero = 0;             /* True if a plan with no prereqs seen */
166586    int seenZeroNoIN = 0;         /* Plan with no prereqs and no IN(...) seen */
166587    Bitmask mPrev = 0;
166588    Bitmask mBestNoIn = 0;
166589
166590    /* If the plan produced by the earlier call uses an IN(...) term, call
166591    ** xBestIndex again, this time with IN(...) terms disabled. */
166592    if( bIn ){
166593      WHERETRACE(0x800, ("  VirtualOne: all usable w/o IN\n"));
166594      rc = whereLoopAddVirtualOne(
166595          pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn, 0);
166596      assert( bIn==0 );
166597      mBestNoIn = pNew->prereq & ~mPrereq;
166598      if( mBestNoIn==0 ){
166599        seenZero = 1;
166600        seenZeroNoIN = 1;
166601      }
166602    }
166603
166604    /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
166605    ** in the set of terms that apply to the current virtual table.  */
166606    while( rc==SQLITE_OK ){
166607      int i;
166608      Bitmask mNext = ALLBITS;
166609      assert( mNext>0 );
166610      for(i=0; i<nConstraint; i++){
166611        Bitmask mThis = (
166612            pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
166613        );
166614        if( mThis>mPrev && mThis<mNext ) mNext = mThis;
166615      }
166616      mPrev = mNext;
166617      if( mNext==ALLBITS ) break;
166618      if( mNext==mBest || mNext==mBestNoIn ) continue;
166619      WHERETRACE(0x800, ("  VirtualOne: mPrev=%04llx mNext=%04llx\n",
166620                       (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
166621      rc = whereLoopAddVirtualOne(
166622          pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn, 0);
166623      if( pNew->prereq==mPrereq ){
166624        seenZero = 1;
166625        if( bIn==0 ) seenZeroNoIN = 1;
166626      }
166627    }
166628
166629    /* If the calls to xBestIndex() in the above loop did not find a plan
166630    ** that requires no source tables at all (i.e. one guaranteed to be
166631    ** usable), make a call here with all source tables disabled */
166632    if( rc==SQLITE_OK && seenZero==0 ){
166633      WHERETRACE(0x800, ("  VirtualOne: all disabled\n"));
166634      rc = whereLoopAddVirtualOne(
166635          pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn, 0);
166636      if( bIn==0 ) seenZeroNoIN = 1;
166637    }
166638
166639    /* If the calls to xBestIndex() have so far failed to find a plan
166640    ** that requires no source tables at all and does not use an IN(...)
166641    ** operator, make a final call to obtain one here.  */
166642    if( rc==SQLITE_OK && seenZeroNoIN==0 ){
166643      WHERETRACE(0x800, ("  VirtualOne: all disabled and w/o IN\n"));
166644      rc = whereLoopAddVirtualOne(
166645          pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn, 0);
166646    }
166647  }
166648
166649  if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
166650  freeIndexInfo(pParse->db, p);
166651  WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
166652  return rc;
166653}
166654#endif /* SQLITE_OMIT_VIRTUALTABLE */
166655
166656/*
166657** Add WhereLoop entries to handle OR terms.  This works for either
166658** btrees or virtual tables.
166659*/
166660static int whereLoopAddOr(
166661  WhereLoopBuilder *pBuilder,
166662  Bitmask mPrereq,
166663  Bitmask mUnusable
166664){
166665  WhereInfo *pWInfo = pBuilder->pWInfo;
166666  WhereClause *pWC;
166667  WhereLoop *pNew;
166668  WhereTerm *pTerm, *pWCEnd;
166669  int rc = SQLITE_OK;
166670  int iCur;
166671  WhereClause tempWC;
166672  WhereLoopBuilder sSubBuild;
166673  WhereOrSet sSum, sCur;
166674  SrcItem *pItem;
166675
166676  pWC = pBuilder->pWC;
166677  pWCEnd = pWC->a + pWC->nTerm;
166678  pNew = pBuilder->pNew;
166679  memset(&sSum, 0, sizeof(sSum));
166680  pItem = pWInfo->pTabList->a + pNew->iTab;
166681  iCur = pItem->iCursor;
166682
166683  /* The multi-index OR optimization does not work for RIGHT and FULL JOIN */
166684  if( pItem->fg.jointype & JT_RIGHT ) return SQLITE_OK;
166685
166686  for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
166687    if( (pTerm->eOperator & WO_OR)!=0
166688     && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
166689    ){
166690      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
166691      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
166692      WhereTerm *pOrTerm;
166693      int once = 1;
166694      int i, j;
166695
166696      sSubBuild = *pBuilder;
166697      sSubBuild.pOrSet = &sCur;
166698
166699      WHERETRACE(0x400, ("Begin processing OR-clause %p\n", pTerm));
166700      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
166701        if( (pOrTerm->eOperator & WO_AND)!=0 ){
166702          sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
166703        }else if( pOrTerm->leftCursor==iCur ){
166704          tempWC.pWInfo = pWC->pWInfo;
166705          tempWC.pOuter = pWC;
166706          tempWC.op = TK_AND;
166707          tempWC.nTerm = 1;
166708          tempWC.nBase = 1;
166709          tempWC.a = pOrTerm;
166710          sSubBuild.pWC = &tempWC;
166711        }else{
166712          continue;
166713        }
166714        sCur.n = 0;
166715#ifdef WHERETRACE_ENABLED
166716        WHERETRACE(0x400, ("OR-term %d of %p has %d subterms:\n",
166717                   (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
166718        if( sqlite3WhereTrace & 0x20000 ){
166719          sqlite3WhereClausePrint(sSubBuild.pWC);
166720        }
166721#endif
166722#ifndef SQLITE_OMIT_VIRTUALTABLE
166723        if( IsVirtual(pItem->pTab) ){
166724          rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
166725        }else
166726#endif
166727        {
166728          rc = whereLoopAddBtree(&sSubBuild, mPrereq);
166729        }
166730        if( rc==SQLITE_OK ){
166731          rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
166732        }
166733        testcase( rc==SQLITE_NOMEM && sCur.n>0 );
166734        testcase( rc==SQLITE_DONE );
166735        if( sCur.n==0 ){
166736          sSum.n = 0;
166737          break;
166738        }else if( once ){
166739          whereOrMove(&sSum, &sCur);
166740          once = 0;
166741        }else{
166742          WhereOrSet sPrev;
166743          whereOrMove(&sPrev, &sSum);
166744          sSum.n = 0;
166745          for(i=0; i<sPrev.n; i++){
166746            for(j=0; j<sCur.n; j++){
166747              whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
166748                            sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
166749                            sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
166750            }
166751          }
166752        }
166753      }
166754      pNew->nLTerm = 1;
166755      pNew->aLTerm[0] = pTerm;
166756      pNew->wsFlags = WHERE_MULTI_OR;
166757      pNew->rSetup = 0;
166758      pNew->iSortIdx = 0;
166759      memset(&pNew->u, 0, sizeof(pNew->u));
166760      for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
166761        /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
166762        ** of all sub-scans required by the OR-scan. However, due to rounding
166763        ** errors, it may be that the cost of the OR-scan is equal to its
166764        ** most expensive sub-scan. Add the smallest possible penalty
166765        ** (equivalent to multiplying the cost by 1.07) to ensure that
166766        ** this does not happen. Otherwise, for WHERE clauses such as the
166767        ** following where there is an index on "y":
166768        **
166769        **     WHERE likelihood(x=?, 0.99) OR y=?
166770        **
166771        ** the planner may elect to "OR" together a full-table scan and an
166772        ** index lookup. And other similarly odd results.  */
166773        pNew->rRun = sSum.a[i].rRun + 1;
166774        pNew->nOut = sSum.a[i].nOut;
166775        pNew->prereq = sSum.a[i].prereq;
166776        rc = whereLoopInsert(pBuilder, pNew);
166777      }
166778      WHERETRACE(0x400, ("End processing OR-clause %p\n", pTerm));
166779    }
166780  }
166781  return rc;
166782}
166783
166784/*
166785** Add all WhereLoop objects for all tables
166786*/
166787static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
166788  WhereInfo *pWInfo = pBuilder->pWInfo;
166789  Bitmask mPrereq = 0;
166790  Bitmask mPrior = 0;
166791  int iTab;
166792  SrcList *pTabList = pWInfo->pTabList;
166793  SrcItem *pItem;
166794  SrcItem *pEnd = &pTabList->a[pWInfo->nLevel];
166795  sqlite3 *db = pWInfo->pParse->db;
166796  int rc = SQLITE_OK;
166797  int bFirstPastRJ = 0;
166798  int hasRightJoin = 0;
166799  WhereLoop *pNew;
166800
166801
166802  /* Loop over the tables in the join, from left to right */
166803  pNew = pBuilder->pNew;
166804
166805  /* Verify that pNew has already been initialized */
166806  assert( pNew->nLTerm==0 );
166807  assert( pNew->wsFlags==0 );
166808  assert( pNew->nLSlot>=ArraySize(pNew->aLTermSpace) );
166809  assert( pNew->aLTerm!=0 );
166810
166811  pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
166812  for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
166813    Bitmask mUnusable = 0;
166814    pNew->iTab = iTab;
166815    pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
166816    pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
166817    if( bFirstPastRJ
166818     || (pItem->fg.jointype & (JT_OUTER|JT_CROSS|JT_LTORJ))!=0
166819    ){
166820      /* Add prerequisites to prevent reordering of FROM clause terms
166821      ** across CROSS joins and outer joins.  The bFirstPastRJ boolean
166822      ** prevents the right operand of a RIGHT JOIN from being swapped with
166823      ** other elements even further to the right.
166824      **
166825      ** The JT_LTORJ case and the hasRightJoin flag work together to
166826      ** prevent FROM-clause terms from moving from the right side of
166827      ** a LEFT JOIN over to the left side of that join if the LEFT JOIN
166828      ** is itself on the left side of a RIGHT JOIN.
166829      */
166830      if( pItem->fg.jointype & JT_LTORJ ) hasRightJoin = 1;
166831      mPrereq |= mPrior;
166832      bFirstPastRJ = (pItem->fg.jointype & JT_RIGHT)!=0;
166833    }else if( !hasRightJoin ){
166834      mPrereq = 0;
166835    }
166836#ifndef SQLITE_OMIT_VIRTUALTABLE
166837    if( IsVirtual(pItem->pTab) ){
166838      SrcItem *p;
166839      for(p=&pItem[1]; p<pEnd; p++){
166840        if( mUnusable || (p->fg.jointype & (JT_OUTER|JT_CROSS)) ){
166841          mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
166842        }
166843      }
166844      rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
166845    }else
166846#endif /* SQLITE_OMIT_VIRTUALTABLE */
166847    {
166848      rc = whereLoopAddBtree(pBuilder, mPrereq);
166849    }
166850    if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
166851      rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
166852    }
166853    mPrior |= pNew->maskSelf;
166854    if( rc || db->mallocFailed ){
166855      if( rc==SQLITE_DONE ){
166856        /* We hit the query planner search limit set by iPlanLimit */
166857        sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search");
166858        rc = SQLITE_OK;
166859      }else{
166860        break;
166861      }
166862    }
166863  }
166864
166865  whereLoopClear(db, pNew);
166866  return rc;
166867}
166868
166869/*
166870** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
166871** parameters) to see if it outputs rows in the requested ORDER BY
166872** (or GROUP BY) without requiring a separate sort operation.  Return N:
166873**
166874**   N>0:   N terms of the ORDER BY clause are satisfied
166875**   N==0:  No terms of the ORDER BY clause are satisfied
166876**   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
166877**
166878** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
166879** strict.  With GROUP BY and DISTINCT the only requirement is that
166880** equivalent rows appear immediately adjacent to one another.  GROUP BY
166881** and DISTINCT do not require rows to appear in any particular order as long
166882** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
166883** the pOrderBy terms can be matched in any order.  With ORDER BY, the
166884** pOrderBy terms must be matched in strict left-to-right order.
166885*/
166886static i8 wherePathSatisfiesOrderBy(
166887  WhereInfo *pWInfo,    /* The WHERE clause */
166888  ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
166889  WherePath *pPath,     /* The WherePath to check */
166890  u16 wctrlFlags,       /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
166891  u16 nLoop,            /* Number of entries in pPath->aLoop[] */
166892  WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
166893  Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
166894){
166895  u8 revSet;            /* True if rev is known */
166896  u8 rev;               /* Composite sort order */
166897  u8 revIdx;            /* Index sort order */
166898  u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
166899  u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
166900  u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
166901  u16 eqOpMask;         /* Allowed equality operators */
166902  u16 nKeyCol;          /* Number of key columns in pIndex */
166903  u16 nColumn;          /* Total number of ordered columns in the index */
166904  u16 nOrderBy;         /* Number terms in the ORDER BY clause */
166905  int iLoop;            /* Index of WhereLoop in pPath being processed */
166906  int i, j;             /* Loop counters */
166907  int iCur;             /* Cursor number for current WhereLoop */
166908  int iColumn;          /* A column number within table iCur */
166909  WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
166910  WhereTerm *pTerm;     /* A single term of the WHERE clause */
166911  Expr *pOBExpr;        /* An expression from the ORDER BY clause */
166912  CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
166913  Index *pIndex;        /* The index associated with pLoop */
166914  sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
166915  Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
166916  Bitmask obDone;       /* Mask of all ORDER BY terms */
166917  Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
166918  Bitmask ready;              /* Mask of inner loops */
166919
166920  /*
166921  ** We say the WhereLoop is "one-row" if it generates no more than one
166922  ** row of output.  A WhereLoop is one-row if all of the following are true:
166923  **  (a) All index columns match with WHERE_COLUMN_EQ.
166924  **  (b) The index is unique
166925  ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
166926  ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
166927  **
166928  ** We say the WhereLoop is "order-distinct" if the set of columns from
166929  ** that WhereLoop that are in the ORDER BY clause are different for every
166930  ** row of the WhereLoop.  Every one-row WhereLoop is automatically
166931  ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
166932  ** is not order-distinct. To be order-distinct is not quite the same as being
166933  ** UNIQUE since a UNIQUE column or index can have multiple rows that
166934  ** are NULL and NULL values are equivalent for the purpose of order-distinct.
166935  ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
166936  **
166937  ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
166938  ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
166939  ** automatically order-distinct.
166940  */
166941
166942  assert( pOrderBy!=0 );
166943  if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
166944
166945  nOrderBy = pOrderBy->nExpr;
166946  testcase( nOrderBy==BMS-1 );
166947  if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
166948  isOrderDistinct = 1;
166949  obDone = MASKBIT(nOrderBy)-1;
166950  orderDistinctMask = 0;
166951  ready = 0;
166952  eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
166953  if( wctrlFlags & (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MAX|WHERE_ORDERBY_MIN) ){
166954    eqOpMask |= WO_IN;
166955  }
166956  for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
166957    if( iLoop>0 ) ready |= pLoop->maskSelf;
166958    if( iLoop<nLoop ){
166959      pLoop = pPath->aLoop[iLoop];
166960      if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
166961    }else{
166962      pLoop = pLast;
166963    }
166964    if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
166965      if( pLoop->u.vtab.isOrdered
166966       && ((wctrlFlags&(WHERE_DISTINCTBY|WHERE_SORTBYGROUP))!=WHERE_DISTINCTBY)
166967      ){
166968        obSat = obDone;
166969      }
166970      break;
166971    }else if( wctrlFlags & WHERE_DISTINCTBY ){
166972      pLoop->u.btree.nDistinctCol = 0;
166973    }
166974    iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
166975
166976    /* Mark off any ORDER BY term X that is a column in the table of
166977    ** the current loop for which there is term in the WHERE
166978    ** clause of the form X IS NULL or X=? that reference only outer
166979    ** loops.
166980    */
166981    for(i=0; i<nOrderBy; i++){
166982      if( MASKBIT(i) & obSat ) continue;
166983      pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
166984      if( NEVER(pOBExpr==0) ) continue;
166985      if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
166986      if( pOBExpr->iTable!=iCur ) continue;
166987      pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
166988                       ~ready, eqOpMask, 0);
166989      if( pTerm==0 ) continue;
166990      if( pTerm->eOperator==WO_IN ){
166991        /* IN terms are only valid for sorting in the ORDER BY LIMIT
166992        ** optimization, and then only if they are actually used
166993        ** by the query plan */
166994        assert( wctrlFlags &
166995               (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) );
166996        for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
166997        if( j>=pLoop->nLTerm ) continue;
166998      }
166999      if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
167000        Parse *pParse = pWInfo->pParse;
167001        CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr);
167002        CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr);
167003        assert( pColl1 );
167004        if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){
167005          continue;
167006        }
167007        testcase( pTerm->pExpr->op==TK_IS );
167008      }
167009      obSat |= MASKBIT(i);
167010    }
167011
167012    if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
167013      if( pLoop->wsFlags & WHERE_IPK ){
167014        pIndex = 0;
167015        nKeyCol = 0;
167016        nColumn = 1;
167017      }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
167018        return 0;
167019      }else{
167020        nKeyCol = pIndex->nKeyCol;
167021        nColumn = pIndex->nColumn;
167022        assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
167023        assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
167024                          || !HasRowid(pIndex->pTable));
167025        /* All relevant terms of the index must also be non-NULL in order
167026        ** for isOrderDistinct to be true.  So the isOrderDistint value
167027        ** computed here might be a false positive.  Corrections will be
167028        ** made at tag-20210426-1 below */
167029        isOrderDistinct = IsUniqueIndex(pIndex)
167030                          && (pLoop->wsFlags & WHERE_SKIPSCAN)==0;
167031      }
167032
167033      /* Loop through all columns of the index and deal with the ones
167034      ** that are not constrained by == or IN.
167035      */
167036      rev = revSet = 0;
167037      distinctColumns = 0;
167038      for(j=0; j<nColumn; j++){
167039        u8 bOnce = 1; /* True to run the ORDER BY search loop */
167040
167041        assert( j>=pLoop->u.btree.nEq
167042            || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
167043        );
167044        if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
167045          u16 eOp = pLoop->aLTerm[j]->eOperator;
167046
167047          /* Skip over == and IS and ISNULL terms.  (Also skip IN terms when
167048          ** doing WHERE_ORDERBY_LIMIT processing).  Except, IS and ISNULL
167049          ** terms imply that the index is not UNIQUE NOT NULL in which case
167050          ** the loop need to be marked as not order-distinct because it can
167051          ** have repeated NULL rows.
167052          **
167053          ** If the current term is a column of an ((?,?) IN (SELECT...))
167054          ** expression for which the SELECT returns more than one column,
167055          ** check that it is the only column used by this loop. Otherwise,
167056          ** if it is one of two or more, none of the columns can be
167057          ** considered to match an ORDER BY term.
167058          */
167059          if( (eOp & eqOpMask)!=0 ){
167060            if( eOp & (WO_ISNULL|WO_IS) ){
167061              testcase( eOp & WO_ISNULL );
167062              testcase( eOp & WO_IS );
167063              testcase( isOrderDistinct );
167064              isOrderDistinct = 0;
167065            }
167066            continue;
167067          }else if( ALWAYS(eOp & WO_IN) ){
167068            /* ALWAYS() justification: eOp is an equality operator due to the
167069            ** j<pLoop->u.btree.nEq constraint above.  Any equality other
167070            ** than WO_IN is captured by the previous "if".  So this one
167071            ** always has to be WO_IN. */
167072            Expr *pX = pLoop->aLTerm[j]->pExpr;
167073            for(i=j+1; i<pLoop->u.btree.nEq; i++){
167074              if( pLoop->aLTerm[i]->pExpr==pX ){
167075                assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
167076                bOnce = 0;
167077                break;
167078              }
167079            }
167080          }
167081        }
167082
167083        /* Get the column number in the table (iColumn) and sort order
167084        ** (revIdx) for the j-th column of the index.
167085        */
167086        if( pIndex ){
167087          iColumn = pIndex->aiColumn[j];
167088          revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC;
167089          if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
167090        }else{
167091          iColumn = XN_ROWID;
167092          revIdx = 0;
167093        }
167094
167095        /* An unconstrained column that might be NULL means that this
167096        ** WhereLoop is not well-ordered.  tag-20210426-1
167097        */
167098        if( isOrderDistinct ){
167099          if( iColumn>=0
167100           && j>=pLoop->u.btree.nEq
167101           && pIndex->pTable->aCol[iColumn].notNull==0
167102          ){
167103            isOrderDistinct = 0;
167104          }
167105          if( iColumn==XN_EXPR ){
167106            isOrderDistinct = 0;
167107          }
167108        }
167109
167110        /* Find the ORDER BY term that corresponds to the j-th column
167111        ** of the index and mark that ORDER BY term off
167112        */
167113        isMatch = 0;
167114        for(i=0; bOnce && i<nOrderBy; i++){
167115          if( MASKBIT(i) & obSat ) continue;
167116          pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
167117          testcase( wctrlFlags & WHERE_GROUPBY );
167118          testcase( wctrlFlags & WHERE_DISTINCTBY );
167119          if( NEVER(pOBExpr==0) ) continue;
167120          if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
167121          if( iColumn>=XN_ROWID ){
167122            if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
167123            if( pOBExpr->iTable!=iCur ) continue;
167124            if( pOBExpr->iColumn!=iColumn ) continue;
167125          }else{
167126            Expr *pIxExpr = pIndex->aColExpr->a[j].pExpr;
167127            if( sqlite3ExprCompareSkip(pOBExpr, pIxExpr, iCur) ){
167128              continue;
167129            }
167130          }
167131          if( iColumn!=XN_ROWID ){
167132            pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
167133            if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
167134          }
167135          if( wctrlFlags & WHERE_DISTINCTBY ){
167136            pLoop->u.btree.nDistinctCol = j+1;
167137          }
167138          isMatch = 1;
167139          break;
167140        }
167141        if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
167142          /* Make sure the sort order is compatible in an ORDER BY clause.
167143          ** Sort order is irrelevant for a GROUP BY clause. */
167144          if( revSet ){
167145            if( (rev ^ revIdx)
167146                           != (pOrderBy->a[i].fg.sortFlags&KEYINFO_ORDER_DESC)
167147            ){
167148              isMatch = 0;
167149            }
167150          }else{
167151            rev = revIdx ^ (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC);
167152            if( rev ) *pRevMask |= MASKBIT(iLoop);
167153            revSet = 1;
167154          }
167155        }
167156        if( isMatch && (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL) ){
167157          if( j==pLoop->u.btree.nEq ){
167158            pLoop->wsFlags |= WHERE_BIGNULL_SORT;
167159          }else{
167160            isMatch = 0;
167161          }
167162        }
167163        if( isMatch ){
167164          if( iColumn==XN_ROWID ){
167165            testcase( distinctColumns==0 );
167166            distinctColumns = 1;
167167          }
167168          obSat |= MASKBIT(i);
167169        }else{
167170          /* No match found */
167171          if( j==0 || j<nKeyCol ){
167172            testcase( isOrderDistinct!=0 );
167173            isOrderDistinct = 0;
167174          }
167175          break;
167176        }
167177      } /* end Loop over all index columns */
167178      if( distinctColumns ){
167179        testcase( isOrderDistinct==0 );
167180        isOrderDistinct = 1;
167181      }
167182    } /* end-if not one-row */
167183
167184    /* Mark off any other ORDER BY terms that reference pLoop */
167185    if( isOrderDistinct ){
167186      orderDistinctMask |= pLoop->maskSelf;
167187      for(i=0; i<nOrderBy; i++){
167188        Expr *p;
167189        Bitmask mTerm;
167190        if( MASKBIT(i) & obSat ) continue;
167191        p = pOrderBy->a[i].pExpr;
167192        mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
167193        if( mTerm==0 && !sqlite3ExprIsConstant(0,p) ) continue;
167194        if( (mTerm&~orderDistinctMask)==0 ){
167195          obSat |= MASKBIT(i);
167196        }
167197      }
167198    }
167199  } /* End the loop over all WhereLoops from outer-most down to inner-most */
167200  if( obSat==obDone ) return (i8)nOrderBy;
167201  if( !isOrderDistinct ){
167202    for(i=nOrderBy-1; i>0; i--){
167203      Bitmask m = ALWAYS(i<BMS) ? MASKBIT(i) - 1 : 0;
167204      if( (obSat&m)==m ) return i;
167205    }
167206    return 0;
167207  }
167208  return -1;
167209}
167210
167211
167212/*
167213** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
167214** the planner assumes that the specified pOrderBy list is actually a GROUP
167215** BY clause - and so any order that groups rows as required satisfies the
167216** request.
167217**
167218** Normally, in this case it is not possible for the caller to determine
167219** whether or not the rows are really being delivered in sorted order, or
167220** just in some other order that provides the required grouping. However,
167221** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
167222** this function may be called on the returned WhereInfo object. It returns
167223** true if the rows really will be sorted in the specified order, or false
167224** otherwise.
167225**
167226** For example, assuming:
167227**
167228**   CREATE INDEX i1 ON t1(x, Y);
167229**
167230** then
167231**
167232**   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
167233**   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
167234*/
167235SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
167236  assert( pWInfo->wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY) );
167237  assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
167238  return pWInfo->sorted;
167239}
167240
167241#ifdef WHERETRACE_ENABLED
167242/* For debugging use only: */
167243static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
167244  static char zName[65];
167245  int i;
167246  for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
167247  if( pLast ) zName[i++] = pLast->cId;
167248  zName[i] = 0;
167249  return zName;
167250}
167251#endif
167252
167253/*
167254** Return the cost of sorting nRow rows, assuming that the keys have
167255** nOrderby columns and that the first nSorted columns are already in
167256** order.
167257*/
167258static LogEst whereSortingCost(
167259  WhereInfo *pWInfo, /* Query planning context */
167260  LogEst nRow,       /* Estimated number of rows to sort */
167261  int nOrderBy,      /* Number of ORDER BY clause terms */
167262  int nSorted        /* Number of initial ORDER BY terms naturally in order */
167263){
167264  /* Estimated cost of a full external sort, where N is
167265  ** the number of rows to sort is:
167266  **
167267  **   cost = (K * N * log(N)).
167268  **
167269  ** Or, if the order-by clause has X terms but only the last Y
167270  ** terms are out of order, then block-sorting will reduce the
167271  ** sorting cost to:
167272  **
167273  **   cost = (K * N * log(N)) * (Y/X)
167274  **
167275  ** The constant K is at least 2.0 but will be larger if there are a
167276  ** large number of columns to be sorted, as the sorting time is
167277  ** proportional to the amount of content to be sorted.  The algorithm
167278  ** does not currently distinguish between fat columns (BLOBs and TEXTs)
167279  ** and skinny columns (INTs).  It just uses the number of columns as
167280  ** an approximation for the row width.
167281  **
167282  ** And extra factor of 2.0 or 3.0 is added to the sorting cost if the sort
167283  ** is built using OP_IdxInsert and OP_Sort rather than with OP_SorterInsert.
167284  */
167285  LogEst rSortCost, nCol;
167286  assert( pWInfo->pSelect!=0 );
167287  assert( pWInfo->pSelect->pEList!=0 );
167288  /* TUNING: sorting cost proportional to the number of output columns: */
167289  nCol = sqlite3LogEst((pWInfo->pSelect->pEList->nExpr+59)/30);
167290  rSortCost = nRow + nCol;
167291  if( nSorted>0 ){
167292    /* Scale the result by (Y/X) */
167293    rSortCost += sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
167294  }
167295
167296  /* Multiple by log(M) where M is the number of output rows.
167297  ** Use the LIMIT for M if it is smaller.  Or if this sort is for
167298  ** a DISTINCT operator, M will be the number of distinct output
167299  ** rows, so fudge it downwards a bit.
167300  */
167301  if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 ){
167302    rSortCost += 10;       /* TUNING: Extra 2.0x if using LIMIT */
167303    if( nSorted!=0 ){
167304      rSortCost += 6;      /* TUNING: Extra 1.5x if also using partial sort */
167305    }
167306    if( pWInfo->iLimit<nRow ){
167307      nRow = pWInfo->iLimit;
167308    }
167309  }else if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT) ){
167310    /* TUNING: In the sort for a DISTINCT operator, assume that the DISTINCT
167311    ** reduces the number of output rows by a factor of 2 */
167312    if( nRow>10 ){ nRow -= 10;  assert( 10==sqlite3LogEst(2) ); }
167313  }
167314  rSortCost += estLog(nRow);
167315  return rSortCost;
167316}
167317
167318/*
167319** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
167320** attempts to find the lowest cost path that visits each WhereLoop
167321** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
167322**
167323** Assume that the total number of output rows that will need to be sorted
167324** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
167325** costs if nRowEst==0.
167326**
167327** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
167328** error occurs.
167329*/
167330static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
167331  int mxChoice;             /* Maximum number of simultaneous paths tracked */
167332  int nLoop;                /* Number of terms in the join */
167333  Parse *pParse;            /* Parsing context */
167334  int iLoop;                /* Loop counter over the terms of the join */
167335  int ii, jj;               /* Loop counters */
167336  int mxI = 0;              /* Index of next entry to replace */
167337  int nOrderBy;             /* Number of ORDER BY clause terms */
167338  LogEst mxCost = 0;        /* Maximum cost of a set of paths */
167339  LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
167340  int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
167341  WherePath *aFrom;         /* All nFrom paths at the previous level */
167342  WherePath *aTo;           /* The nTo best paths at the current level */
167343  WherePath *pFrom;         /* An element of aFrom[] that we are working on */
167344  WherePath *pTo;           /* An element of aTo[] that we are working on */
167345  WhereLoop *pWLoop;        /* One of the WhereLoop objects */
167346  WhereLoop **pX;           /* Used to divy up the pSpace memory */
167347  LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
167348  char *pSpace;             /* Temporary memory used by this routine */
167349  int nSpace;               /* Bytes of space allocated at pSpace */
167350
167351  pParse = pWInfo->pParse;
167352  nLoop = pWInfo->nLevel;
167353  /* TUNING: For simple queries, only the best path is tracked.
167354  ** For 2-way joins, the 5 best paths are followed.
167355  ** For joins of 3 or more tables, track the 10 best paths */
167356  mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
167357  assert( nLoop<=pWInfo->pTabList->nSrc );
167358  WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d, nQueryLoop=%d)\n",
167359                     nRowEst, pParse->nQueryLoop));
167360
167361  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
167362  ** case the purpose of this call is to estimate the number of rows returned
167363  ** by the overall query. Once this estimate has been obtained, the caller
167364  ** will invoke this function a second time, passing the estimate as the
167365  ** nRowEst parameter.  */
167366  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
167367    nOrderBy = 0;
167368  }else{
167369    nOrderBy = pWInfo->pOrderBy->nExpr;
167370  }
167371
167372  /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
167373  nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
167374  nSpace += sizeof(LogEst) * nOrderBy;
167375  pSpace = sqlite3StackAllocRawNN(pParse->db, nSpace);
167376  if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
167377  aTo = (WherePath*)pSpace;
167378  aFrom = aTo+mxChoice;
167379  memset(aFrom, 0, sizeof(aFrom[0]));
167380  pX = (WhereLoop**)(aFrom+mxChoice);
167381  for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
167382    pFrom->aLoop = pX;
167383  }
167384  if( nOrderBy ){
167385    /* If there is an ORDER BY clause and it is not being ignored, set up
167386    ** space for the aSortCost[] array. Each element of the aSortCost array
167387    ** is either zero - meaning it has not yet been initialized - or the
167388    ** cost of sorting nRowEst rows of data where the first X terms of
167389    ** the ORDER BY clause are already in order, where X is the array
167390    ** index.  */
167391    aSortCost = (LogEst*)pX;
167392    memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
167393  }
167394  assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
167395  assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
167396
167397  /* Seed the search with a single WherePath containing zero WhereLoops.
167398  **
167399  ** TUNING: Do not let the number of iterations go above 28.  If the cost
167400  ** of computing an automatic index is not paid back within the first 28
167401  ** rows, then do not use the automatic index. */
167402  aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
167403  nFrom = 1;
167404  assert( aFrom[0].isOrdered==0 );
167405  if( nOrderBy ){
167406    /* If nLoop is zero, then there are no FROM terms in the query. Since
167407    ** in this case the query may return a maximum of one row, the results
167408    ** are already in the requested order. Set isOrdered to nOrderBy to
167409    ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
167410    ** -1, indicating that the result set may or may not be ordered,
167411    ** depending on the loops added to the current plan.  */
167412    aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
167413  }
167414
167415  /* Compute successively longer WherePaths using the previous generation
167416  ** of WherePaths as the basis for the next.  Keep track of the mxChoice
167417  ** best paths at each generation */
167418  for(iLoop=0; iLoop<nLoop; iLoop++){
167419    nTo = 0;
167420    for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
167421      for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
167422        LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
167423        LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
167424        LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
167425        i8 isOrdered;                     /* isOrdered for (pFrom+pWLoop) */
167426        Bitmask maskNew;                  /* Mask of src visited by (..) */
167427        Bitmask revMask;                  /* Mask of rev-order loops for (..) */
167428
167429        if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
167430        if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
167431        if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
167432          /* Do not use an automatic index if the this loop is expected
167433          ** to run less than 1.25 times.  It is tempting to also exclude
167434          ** automatic index usage on an outer loop, but sometimes an automatic
167435          ** index is useful in the outer loop of a correlated subquery. */
167436          assert( 10==sqlite3LogEst(2) );
167437          continue;
167438        }
167439
167440        /* At this point, pWLoop is a candidate to be the next loop.
167441        ** Compute its cost */
167442        rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
167443        rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
167444        nOut = pFrom->nRow + pWLoop->nOut;
167445        maskNew = pFrom->maskLoop | pWLoop->maskSelf;
167446        isOrdered = pFrom->isOrdered;
167447        if( isOrdered<0 ){
167448          revMask = 0;
167449          isOrdered = wherePathSatisfiesOrderBy(pWInfo,
167450                       pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
167451                       iLoop, pWLoop, &revMask);
167452        }else{
167453          revMask = pFrom->revLoop;
167454        }
167455        if( isOrdered>=0 && isOrdered<nOrderBy ){
167456          if( aSortCost[isOrdered]==0 ){
167457            aSortCost[isOrdered] = whereSortingCost(
167458                pWInfo, nRowEst, nOrderBy, isOrdered
167459            );
167460          }
167461          /* TUNING:  Add a small extra penalty (3) to sorting as an
167462          ** extra encouragement to the query planner to select a plan
167463          ** where the rows emerge in the correct order without any sorting
167464          ** required. */
167465          rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 3;
167466
167467          WHERETRACE(0x002,
167468              ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
167469               aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
167470               rUnsorted, rCost));
167471        }else{
167472          rCost = rUnsorted;
167473          rUnsorted -= 2;  /* TUNING:  Slight bias in favor of no-sort plans */
167474        }
167475
167476        /* Check to see if pWLoop should be added to the set of
167477        ** mxChoice best-so-far paths.
167478        **
167479        ** First look for an existing path among best-so-far paths
167480        ** that covers the same set of loops and has the same isOrdered
167481        ** setting as the current path candidate.
167482        **
167483        ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
167484        ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
167485        ** of legal values for isOrdered, -1..64.
167486        */
167487        for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
167488          if( pTo->maskLoop==maskNew
167489           && ((pTo->isOrdered^isOrdered)&0x80)==0
167490          ){
167491            testcase( jj==nTo-1 );
167492            break;
167493          }
167494        }
167495        if( jj>=nTo ){
167496          /* None of the existing best-so-far paths match the candidate. */
167497          if( nTo>=mxChoice
167498           && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
167499          ){
167500            /* The current candidate is no better than any of the mxChoice
167501            ** paths currently in the best-so-far buffer.  So discard
167502            ** this candidate as not viable. */
167503#ifdef WHERETRACE_ENABLED /* 0x4 */
167504            if( sqlite3WhereTrace&0x4 ){
167505              sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d,%3d order=%c\n",
167506                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
167507                  isOrdered>=0 ? isOrdered+'0' : '?');
167508            }
167509#endif
167510            continue;
167511          }
167512          /* If we reach this points it means that the new candidate path
167513          ** needs to be added to the set of best-so-far paths. */
167514          if( nTo<mxChoice ){
167515            /* Increase the size of the aTo set by one */
167516            jj = nTo++;
167517          }else{
167518            /* New path replaces the prior worst to keep count below mxChoice */
167519            jj = mxI;
167520          }
167521          pTo = &aTo[jj];
167522#ifdef WHERETRACE_ENABLED /* 0x4 */
167523          if( sqlite3WhereTrace&0x4 ){
167524            sqlite3DebugPrintf("New    %s cost=%-3d,%3d,%3d order=%c\n",
167525                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
167526                isOrdered>=0 ? isOrdered+'0' : '?');
167527          }
167528#endif
167529        }else{
167530          /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
167531          ** same set of loops and has the same isOrdered setting as the
167532          ** candidate path.  Check to see if the candidate should replace
167533          ** pTo or if the candidate should be skipped.
167534          **
167535          ** The conditional is an expanded vector comparison equivalent to:
167536          **   (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
167537          */
167538          if( pTo->rCost<rCost
167539           || (pTo->rCost==rCost
167540               && (pTo->nRow<nOut
167541                   || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
167542                  )
167543              )
167544          ){
167545#ifdef WHERETRACE_ENABLED /* 0x4 */
167546            if( sqlite3WhereTrace&0x4 ){
167547              sqlite3DebugPrintf(
167548                  "Skip   %s cost=%-3d,%3d,%3d order=%c",
167549                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
167550                  isOrdered>=0 ? isOrdered+'0' : '?');
167551              sqlite3DebugPrintf("   vs %s cost=%-3d,%3d,%3d order=%c\n",
167552                  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
167553                  pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
167554            }
167555#endif
167556            /* Discard the candidate path from further consideration */
167557            testcase( pTo->rCost==rCost );
167558            continue;
167559          }
167560          testcase( pTo->rCost==rCost+1 );
167561          /* Control reaches here if the candidate path is better than the
167562          ** pTo path.  Replace pTo with the candidate. */
167563#ifdef WHERETRACE_ENABLED /* 0x4 */
167564          if( sqlite3WhereTrace&0x4 ){
167565            sqlite3DebugPrintf(
167566                "Update %s cost=%-3d,%3d,%3d order=%c",
167567                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
167568                isOrdered>=0 ? isOrdered+'0' : '?');
167569            sqlite3DebugPrintf("  was %s cost=%-3d,%3d,%3d order=%c\n",
167570                wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
167571                pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
167572          }
167573#endif
167574        }
167575        /* pWLoop is a winner.  Add it to the set of best so far */
167576        pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
167577        pTo->revLoop = revMask;
167578        pTo->nRow = nOut;
167579        pTo->rCost = rCost;
167580        pTo->rUnsorted = rUnsorted;
167581        pTo->isOrdered = isOrdered;
167582        memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
167583        pTo->aLoop[iLoop] = pWLoop;
167584        if( nTo>=mxChoice ){
167585          mxI = 0;
167586          mxCost = aTo[0].rCost;
167587          mxUnsorted = aTo[0].nRow;
167588          for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
167589            if( pTo->rCost>mxCost
167590             || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
167591            ){
167592              mxCost = pTo->rCost;
167593              mxUnsorted = pTo->rUnsorted;
167594              mxI = jj;
167595            }
167596          }
167597        }
167598      }
167599    }
167600
167601#ifdef WHERETRACE_ENABLED  /* >=2 */
167602    if( sqlite3WhereTrace & 0x02 ){
167603      sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
167604      for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
167605        sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
167606           wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
167607           pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
167608        if( pTo->isOrdered>0 ){
167609          sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
167610        }else{
167611          sqlite3DebugPrintf("\n");
167612        }
167613      }
167614    }
167615#endif
167616
167617    /* Swap the roles of aFrom and aTo for the next generation */
167618    pFrom = aTo;
167619    aTo = aFrom;
167620    aFrom = pFrom;
167621    nFrom = nTo;
167622  }
167623
167624  if( nFrom==0 ){
167625    sqlite3ErrorMsg(pParse, "no query solution");
167626    sqlite3StackFreeNN(pParse->db, pSpace);
167627    return SQLITE_ERROR;
167628  }
167629
167630  /* Find the lowest cost path.  pFrom will be left pointing to that path */
167631  pFrom = aFrom;
167632  for(ii=1; ii<nFrom; ii++){
167633    if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
167634  }
167635  assert( pWInfo->nLevel==nLoop );
167636  /* Load the lowest cost path into pWInfo */
167637  for(iLoop=0; iLoop<nLoop; iLoop++){
167638    WhereLevel *pLevel = pWInfo->a + iLoop;
167639    pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
167640    pLevel->iFrom = pWLoop->iTab;
167641    pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
167642  }
167643  if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
167644   && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
167645   && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
167646   && nRowEst
167647  ){
167648    Bitmask notUsed;
167649    int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
167650                 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
167651    if( rc==pWInfo->pResultSet->nExpr ){
167652      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
167653    }
167654  }
167655  pWInfo->bOrderedInnerLoop = 0;
167656  if( pWInfo->pOrderBy ){
167657    pWInfo->nOBSat = pFrom->isOrdered;
167658    if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
167659      if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
167660        pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
167661      }
167662      /* vvv--- See check-in [12ad822d9b827777] on 2023-03-16 ---vvv */
167663      assert( pWInfo->pSelect->pOrderBy==0
167664           || pWInfo->nOBSat <= pWInfo->pSelect->pOrderBy->nExpr );
167665    }else{
167666      pWInfo->revMask = pFrom->revLoop;
167667      if( pWInfo->nOBSat<=0 ){
167668        pWInfo->nOBSat = 0;
167669        if( nLoop>0 ){
167670          u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
167671          if( (wsFlags & WHERE_ONEROW)==0
167672           && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
167673          ){
167674            Bitmask m = 0;
167675            int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
167676                      WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
167677            testcase( wsFlags & WHERE_IPK );
167678            testcase( wsFlags & WHERE_COLUMN_IN );
167679            if( rc==pWInfo->pOrderBy->nExpr ){
167680              pWInfo->bOrderedInnerLoop = 1;
167681              pWInfo->revMask = m;
167682            }
167683          }
167684        }
167685      }else if( nLoop
167686            && pWInfo->nOBSat==1
167687            && (pWInfo->wctrlFlags & (WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX))!=0
167688            ){
167689        pWInfo->bOrderedInnerLoop = 1;
167690      }
167691    }
167692    if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
167693        && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
167694    ){
167695      Bitmask revMask = 0;
167696      int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
167697          pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
167698      );
167699      assert( pWInfo->sorted==0 );
167700      if( nOrder==pWInfo->pOrderBy->nExpr ){
167701        pWInfo->sorted = 1;
167702        pWInfo->revMask = revMask;
167703      }
167704    }
167705  }
167706
167707  pWInfo->nRowOut = pFrom->nRow;
167708
167709  /* Free temporary memory and return success */
167710  sqlite3StackFreeNN(pParse->db, pSpace);
167711  return SQLITE_OK;
167712}
167713
167714/*
167715** This routine implements a heuristic designed to improve query planning.
167716** This routine is called in between the first and second call to
167717** wherePathSolver().  Hence the name "Interstage" "Heuristic".
167718**
167719** The first call to wherePathSolver() (hereafter just "solver()") computes
167720** the best path without regard to the order of the outputs.  The second call
167721** to the solver() builds upon the first call to try to find an alternative
167722** path that satisfies the ORDER BY clause.
167723**
167724** This routine looks at the results of the first solver() run, and for
167725** every FROM clause term in the resulting query plan that uses an equality
167726** constraint against an index, disable other WhereLoops for that same
167727** FROM clause term that would try to do a full-table scan.  This prevents
167728** an index search from being converted into a full-table scan in order to
167729** satisfy an ORDER BY clause, since even though we might get slightly better
167730** performance using the full-scan without sorting if the output size
167731** estimates are very precise, we might also get severe performance
167732** degradation using the full-scan if the output size estimate is too large.
167733** It is better to err on the side of caution.
167734**
167735** Except, if the first solver() call generated a full-table scan in an outer
167736** loop then stop this analysis at the first full-scan, since the second
167737** solver() run might try to swap that full-scan for another in order to
167738** get the output into the correct order.  In other words, we allow a
167739** rewrite like this:
167740**
167741**     First Solver()                      Second Solver()
167742**       |-- SCAN t1                         |-- SCAN t2
167743**       |-- SEARCH t2                       `-- SEARCH t1
167744**       `-- SORT USING B-TREE
167745**
167746** The purpose of this routine is to disallow rewrites such as:
167747**
167748**     First Solver()                      Second Solver()
167749**       |-- SEARCH t1                       |-- SCAN t2     <--- bad!
167750**       |-- SEARCH t2                       `-- SEARCH t1
167751**       `-- SORT USING B-TREE
167752**
167753** See test cases in test/whereN.test for the real-world query that
167754** originally provoked this heuristic.
167755*/
167756static SQLITE_NOINLINE void whereInterstageHeuristic(WhereInfo *pWInfo){
167757  int i;
167758#ifdef WHERETRACE_ENABLED
167759  int once = 0;
167760#endif
167761  for(i=0; i<pWInfo->nLevel; i++){
167762    WhereLoop *p = pWInfo->a[i].pWLoop;
167763    if( p==0 ) break;
167764    if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 ) continue;
167765    if( (p->wsFlags & (WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0 ){
167766      u8 iTab = p->iTab;
167767      WhereLoop *pLoop;
167768      for(pLoop=pWInfo->pLoops; pLoop; pLoop=pLoop->pNextLoop){
167769        if( pLoop->iTab!=iTab ) continue;
167770        if( (pLoop->wsFlags & (WHERE_CONSTRAINT|WHERE_AUTO_INDEX))!=0 ){
167771          /* Auto-index and index-constrained loops allowed to remain */
167772          continue;
167773        }
167774#ifdef WHERETRACE_ENABLED
167775        if( sqlite3WhereTrace & 0x80 ){
167776          if( once==0 ){
167777            sqlite3DebugPrintf("Loops disabled by interstage heuristic:\n");
167778            once = 1;
167779          }
167780          sqlite3WhereLoopPrint(pLoop, &pWInfo->sWC);
167781        }
167782#endif /* WHERETRACE_ENABLED */
167783        pLoop->prereq = ALLBITS;  /* Prevent 2nd solver() from using this one */
167784      }
167785    }else{
167786      break;
167787    }
167788  }
167789}
167790
167791/*
167792** Most queries use only a single table (they are not joins) and have
167793** simple == constraints against indexed fields.  This routine attempts
167794** to plan those simple cases using much less ceremony than the
167795** general-purpose query planner, and thereby yield faster sqlite3_prepare()
167796** times for the common case.
167797**
167798** Return non-zero on success, if this query can be handled by this
167799** no-frills query planner.  Return zero if this query needs the
167800** general-purpose query planner.
167801*/
167802static int whereShortCut(WhereLoopBuilder *pBuilder){
167803  WhereInfo *pWInfo;
167804  SrcItem *pItem;
167805  WhereClause *pWC;
167806  WhereTerm *pTerm;
167807  WhereLoop *pLoop;
167808  int iCur;
167809  int j;
167810  Table *pTab;
167811  Index *pIdx;
167812  WhereScan scan;
167813
167814  pWInfo = pBuilder->pWInfo;
167815  if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
167816  assert( pWInfo->pTabList->nSrc>=1 );
167817  pItem = pWInfo->pTabList->a;
167818  pTab = pItem->pTab;
167819  if( IsVirtual(pTab) ) return 0;
167820  if( pItem->fg.isIndexedBy || pItem->fg.notIndexed ){
167821    testcase( pItem->fg.isIndexedBy );
167822    testcase( pItem->fg.notIndexed );
167823    return 0;
167824  }
167825  iCur = pItem->iCursor;
167826  pWC = &pWInfo->sWC;
167827  pLoop = pBuilder->pNew;
167828  pLoop->wsFlags = 0;
167829  pLoop->nSkip = 0;
167830  pTerm = whereScanInit(&scan, pWC, iCur, -1, WO_EQ|WO_IS, 0);
167831  while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
167832  if( pTerm ){
167833    testcase( pTerm->eOperator & WO_IS );
167834    pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
167835    pLoop->aLTerm[0] = pTerm;
167836    pLoop->nLTerm = 1;
167837    pLoop->u.btree.nEq = 1;
167838    /* TUNING: Cost of a rowid lookup is 10 */
167839    pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
167840  }else{
167841    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
167842      int opMask;
167843      assert( pLoop->aLTermSpace==pLoop->aLTerm );
167844      if( !IsUniqueIndex(pIdx)
167845       || pIdx->pPartIdxWhere!=0
167846       || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
167847      ) continue;
167848      opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
167849      for(j=0; j<pIdx->nKeyCol; j++){
167850        pTerm = whereScanInit(&scan, pWC, iCur, j, opMask, pIdx);
167851        while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
167852        if( pTerm==0 ) break;
167853        testcase( pTerm->eOperator & WO_IS );
167854        pLoop->aLTerm[j] = pTerm;
167855      }
167856      if( j!=pIdx->nKeyCol ) continue;
167857      pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
167858      if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){
167859        pLoop->wsFlags |= WHERE_IDX_ONLY;
167860      }
167861      pLoop->nLTerm = j;
167862      pLoop->u.btree.nEq = j;
167863      pLoop->u.btree.pIndex = pIdx;
167864      /* TUNING: Cost of a unique index lookup is 15 */
167865      pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
167866      break;
167867    }
167868  }
167869  if( pLoop->wsFlags ){
167870    pLoop->nOut = (LogEst)1;
167871    pWInfo->a[0].pWLoop = pLoop;
167872    assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
167873    pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
167874    pWInfo->a[0].iTabCur = iCur;
167875    pWInfo->nRowOut = 1;
167876    if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
167877    if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
167878      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
167879    }
167880    if( scan.iEquiv>1 ) pLoop->wsFlags |= WHERE_TRANSCONS;
167881#ifdef SQLITE_DEBUG
167882    pLoop->cId = '0';
167883#endif
167884#ifdef WHERETRACE_ENABLED
167885    if( sqlite3WhereTrace & 0x02 ){
167886      sqlite3DebugPrintf("whereShortCut() used to compute solution\n");
167887    }
167888#endif
167889    return 1;
167890  }
167891  return 0;
167892}
167893
167894/*
167895** Helper function for exprIsDeterministic().
167896*/
167897static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
167898  if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
167899    pWalker->eCode = 0;
167900    return WRC_Abort;
167901  }
167902  return WRC_Continue;
167903}
167904
167905/*
167906** Return true if the expression contains no non-deterministic SQL
167907** functions. Do not consider non-deterministic SQL functions that are
167908** part of sub-select statements.
167909*/
167910static int exprIsDeterministic(Expr *p){
167911  Walker w;
167912  memset(&w, 0, sizeof(w));
167913  w.eCode = 1;
167914  w.xExprCallback = exprNodeIsDeterministic;
167915  w.xSelectCallback = sqlite3SelectWalkFail;
167916  sqlite3WalkExpr(&w, p);
167917  return w.eCode;
167918}
167919
167920
167921#ifdef WHERETRACE_ENABLED
167922/*
167923** Display all WhereLoops in pWInfo
167924*/
167925static void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){
167926  if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
167927    WhereLoop *p;
167928    int i;
167929    static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
167930                                           "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
167931    for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
167932      p->cId = zLabel[i%(sizeof(zLabel)-1)];
167933      sqlite3WhereLoopPrint(p, pWC);
167934    }
167935  }
167936}
167937# define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C)
167938#else
167939# define WHERETRACE_ALL_LOOPS(W,C)
167940#endif
167941
167942/* Attempt to omit tables from a join that do not affect the result.
167943** For a table to not affect the result, the following must be true:
167944**
167945**   1) The query must not be an aggregate.
167946**   2) The table must be the RHS of a LEFT JOIN.
167947**   3) Either the query must be DISTINCT, or else the ON or USING clause
167948**      must contain a constraint that limits the scan of the table to
167949**      at most a single row.
167950**   4) The table must not be referenced by any part of the query apart
167951**      from its own USING or ON clause.
167952**   5) The table must not have an inner-join ON or USING clause if there is
167953**      a RIGHT JOIN anywhere in the query.  Otherwise the ON/USING clause
167954**      might move from the right side to the left side of the RIGHT JOIN.
167955**      Note: Due to (2), this condition can only arise if the table is
167956**      the right-most table of a subquery that was flattened into the
167957**      main query and that subquery was the right-hand operand of an
167958**      inner join that held an ON or USING clause.
167959**
167960** For example, given:
167961**
167962**     CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
167963**     CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
167964**     CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
167965**
167966** then table t2 can be omitted from the following:
167967**
167968**     SELECT v1, v3 FROM t1
167969**       LEFT JOIN t2 ON (t1.ipk=t2.ipk)
167970**       LEFT JOIN t3 ON (t1.ipk=t3.ipk)
167971**
167972** or from:
167973**
167974**     SELECT DISTINCT v1, v3 FROM t1
167975**       LEFT JOIN t2
167976**       LEFT JOIN t3 ON (t1.ipk=t3.ipk)
167977*/
167978static SQLITE_NOINLINE Bitmask whereOmitNoopJoin(
167979  WhereInfo *pWInfo,
167980  Bitmask notReady
167981){
167982  int i;
167983  Bitmask tabUsed;
167984  int hasRightJoin;
167985
167986  /* Preconditions checked by the caller */
167987  assert( pWInfo->nLevel>=2 );
167988  assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_OmitNoopJoin) );
167989
167990  /* These two preconditions checked by the caller combine to guarantee
167991  ** condition (1) of the header comment */
167992  assert( pWInfo->pResultSet!=0 );
167993  assert( 0==(pWInfo->wctrlFlags & WHERE_AGG_DISTINCT) );
167994
167995  tabUsed = sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pResultSet);
167996  if( pWInfo->pOrderBy ){
167997    tabUsed |= sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pOrderBy);
167998  }
167999  hasRightJoin = (pWInfo->pTabList->a[0].fg.jointype & JT_LTORJ)!=0;
168000  for(i=pWInfo->nLevel-1; i>=1; i--){
168001    WhereTerm *pTerm, *pEnd;
168002    SrcItem *pItem;
168003    WhereLoop *pLoop;
168004    pLoop = pWInfo->a[i].pWLoop;
168005    pItem = &pWInfo->pTabList->a[pLoop->iTab];
168006    if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ) continue;
168007    if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)==0
168008     && (pLoop->wsFlags & WHERE_ONEROW)==0
168009    ){
168010      continue;
168011    }
168012    if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
168013    pEnd = pWInfo->sWC.a + pWInfo->sWC.nTerm;
168014    for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
168015      if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
168016        if( !ExprHasProperty(pTerm->pExpr, EP_OuterON)
168017         || pTerm->pExpr->w.iJoin!=pItem->iCursor
168018        ){
168019          break;
168020        }
168021      }
168022      if( hasRightJoin
168023       && ExprHasProperty(pTerm->pExpr, EP_InnerON)
168024       && pTerm->pExpr->w.iJoin==pItem->iCursor
168025      ){
168026        break;  /* restriction (5) */
168027      }
168028    }
168029    if( pTerm<pEnd ) continue;
168030    WHERETRACE(0xffffffff, ("-> drop loop %c not used\n", pLoop->cId));
168031    notReady &= ~pLoop->maskSelf;
168032    for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
168033      if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
168034        pTerm->wtFlags |= TERM_CODED;
168035      }
168036    }
168037    if( i!=pWInfo->nLevel-1 ){
168038      int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
168039      memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
168040    }
168041    pWInfo->nLevel--;
168042    assert( pWInfo->nLevel>0 );
168043  }
168044  return notReady;
168045}
168046
168047/*
168048** Check to see if there are any SEARCH loops that might benefit from
168049** using a Bloom filter.  Consider a Bloom filter if:
168050**
168051**   (1)  The SEARCH happens more than N times where N is the number
168052**        of rows in the table that is being considered for the Bloom
168053**        filter.
168054**   (2)  Some searches are expected to find zero rows.  (This is determined
168055**        by the WHERE_SELFCULL flag on the term.)
168056**   (3)  Bloom-filter processing is not disabled.  (Checked by the
168057**        caller.)
168058**   (4)  The size of the table being searched is known by ANALYZE.
168059**
168060** This block of code merely checks to see if a Bloom filter would be
168061** appropriate, and if so sets the WHERE_BLOOMFILTER flag on the
168062** WhereLoop.  The implementation of the Bloom filter comes further
168063** down where the code for each WhereLoop is generated.
168064*/
168065static SQLITE_NOINLINE void whereCheckIfBloomFilterIsUseful(
168066  const WhereInfo *pWInfo
168067){
168068  int i;
168069  LogEst nSearch = 0;
168070
168071  assert( pWInfo->nLevel>=2 );
168072  assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_BloomFilter) );
168073  for(i=0; i<pWInfo->nLevel; i++){
168074    WhereLoop *pLoop = pWInfo->a[i].pWLoop;
168075    const unsigned int reqFlags = (WHERE_SELFCULL|WHERE_COLUMN_EQ);
168076    SrcItem *pItem = &pWInfo->pTabList->a[pLoop->iTab];
168077    Table *pTab = pItem->pTab;
168078    if( (pTab->tabFlags & TF_HasStat1)==0 ) break;
168079    pTab->tabFlags |= TF_MaybeReanalyze;
168080    if( i>=1
168081     && (pLoop->wsFlags & reqFlags)==reqFlags
168082     /* vvvvvv--- Always the case if WHERE_COLUMN_EQ is defined */
168083     && ALWAYS((pLoop->wsFlags & (WHERE_IPK|WHERE_INDEXED))!=0)
168084    ){
168085      if( nSearch > pTab->nRowLogEst ){
168086        testcase( pItem->fg.jointype & JT_LEFT );
168087        pLoop->wsFlags |= WHERE_BLOOMFILTER;
168088        pLoop->wsFlags &= ~WHERE_IDX_ONLY;
168089        WHERETRACE(0xffffffff, (
168090           "-> use Bloom-filter on loop %c because there are ~%.1e "
168091           "lookups into %s which has only ~%.1e rows\n",
168092           pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
168093           (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
168094      }
168095    }
168096    nSearch += pLoop->nOut;
168097  }
168098}
168099
168100/*
168101** Expression Node callback for sqlite3ExprCanReturnSubtype().
168102**
168103** Only a function call is able to return a subtype.  So if the node
168104** is not a function call, return WRC_Prune immediately.
168105**
168106** A function call is able to return a subtype if it has the
168107** SQLITE_RESULT_SUBTYPE property.
168108**
168109** Assume that every function is able to pass-through a subtype from
168110** one of its argument (using sqlite3_result_value()).  Most functions
168111** are not this way, but we don't have a mechanism to distinguish those
168112** that are from those that are not, so assume they all work this way.
168113** That means that if one of its arguments is another function and that
168114** other function is able to return a subtype, then this function is
168115** able to return a subtype.
168116*/
168117static int exprNodeCanReturnSubtype(Walker *pWalker, Expr *pExpr){
168118  int n;
168119  FuncDef *pDef;
168120  sqlite3 *db;
168121  if( pExpr->op!=TK_FUNCTION ){
168122    return WRC_Prune;
168123  }
168124  assert( ExprUseXList(pExpr) );
168125  db = pWalker->pParse->db;
168126  n = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
168127  pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
168128  if( pDef==0 || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){
168129    pWalker->eCode = 1;
168130    return WRC_Prune;
168131  }
168132  return WRC_Continue;
168133}
168134
168135/*
168136** Return TRUE if expression pExpr is able to return a subtype.
168137**
168138** A TRUE return does not guarantee that a subtype will be returned.
168139** It only indicates that a subtype return is possible.  False positives
168140** are acceptable as they only disable an optimization.  False negatives,
168141** on the other hand, can lead to incorrect answers.
168142*/
168143static int sqlite3ExprCanReturnSubtype(Parse *pParse, Expr *pExpr){
168144  Walker w;
168145  memset(&w, 0, sizeof(w));
168146  w.pParse = pParse;
168147  w.xExprCallback = exprNodeCanReturnSubtype;
168148  sqlite3WalkExpr(&w, pExpr);
168149  return w.eCode;
168150}
168151
168152/*
168153** The index pIdx is used by a query and contains one or more expressions.
168154** In other words pIdx is an index on an expression.  iIdxCur is the cursor
168155** number for the index and iDataCur is the cursor number for the corresponding
168156** table.
168157**
168158** This routine adds IndexedExpr entries to the Parse->pIdxEpr field for
168159** each of the expressions in the index so that the expression code generator
168160** will know to replace occurrences of the indexed expression with
168161** references to the corresponding column of the index.
168162*/
168163static SQLITE_NOINLINE void whereAddIndexedExpr(
168164  Parse *pParse,     /* Add IndexedExpr entries to pParse->pIdxEpr */
168165  Index *pIdx,       /* The index-on-expression that contains the expressions */
168166  int iIdxCur,       /* Cursor number for pIdx */
168167  SrcItem *pTabItem  /* The FROM clause entry for the table */
168168){
168169  int i;
168170  IndexedExpr *p;
168171  Table *pTab;
168172  assert( pIdx->bHasExpr );
168173  pTab = pIdx->pTable;
168174  for(i=0; i<pIdx->nColumn; i++){
168175    Expr *pExpr;
168176    int j = pIdx->aiColumn[i];
168177    if( j==XN_EXPR ){
168178      pExpr = pIdx->aColExpr->a[i].pExpr;
168179    }else if( j>=0 && (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)!=0 ){
168180      pExpr = sqlite3ColumnExpr(pTab, &pTab->aCol[j]);
168181    }else{
168182      continue;
168183    }
168184    if( sqlite3ExprIsConstant(0,pExpr) ) continue;
168185    if( pExpr->op==TK_FUNCTION && sqlite3ExprCanReturnSubtype(pParse,pExpr) ){
168186      /* Functions that might set a subtype should not be replaced by the
168187      ** value taken from an expression index since the index omits the
168188      ** subtype.  https://sqlite.org/forum/forumpost/68d284c86b082c3e */
168189      continue;
168190    }
168191    p = sqlite3DbMallocRaw(pParse->db,  sizeof(IndexedExpr));
168192    if( p==0 ) break;
168193    p->pIENext = pParse->pIdxEpr;
168194#ifdef WHERETRACE_ENABLED
168195    if( sqlite3WhereTrace & 0x200 ){
168196      sqlite3DebugPrintf("New pParse->pIdxEpr term {%d,%d}\n", iIdxCur, i);
168197      if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(pExpr);
168198    }
168199#endif
168200    p->pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
168201    p->iDataCur = pTabItem->iCursor;
168202    p->iIdxCur = iIdxCur;
168203    p->iIdxCol = i;
168204    p->bMaybeNullRow = (pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0;
168205    if( sqlite3IndexAffinityStr(pParse->db, pIdx) ){
168206      p->aff = pIdx->zColAff[i];
168207    }
168208#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
168209    p->zIdxName = pIdx->zName;
168210#endif
168211    pParse->pIdxEpr = p;
168212    if( p->pIENext==0 ){
168213      void *pArg = (void*)&pParse->pIdxEpr;
168214      sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pArg);
168215    }
168216  }
168217}
168218
168219/*
168220** Set the reverse-scan order mask to one for all tables in the query
168221** with the exception of MATERIALIZED common table expressions that have
168222** their own internal ORDER BY clauses.
168223**
168224** This implements the PRAGMA reverse_unordered_selects=ON setting.
168225** (Also SQLITE_DBCONFIG_REVERSE_SCANORDER).
168226*/
168227static SQLITE_NOINLINE void whereReverseScanOrder(WhereInfo *pWInfo){
168228  int ii;
168229  for(ii=0; ii<pWInfo->pTabList->nSrc; ii++){
168230    SrcItem *pItem = &pWInfo->pTabList->a[ii];
168231    if( !pItem->fg.isCte
168232     || pItem->u2.pCteUse->eM10d!=M10d_Yes
168233     || NEVER(pItem->pSelect==0)
168234     || pItem->pSelect->pOrderBy==0
168235    ){
168236      pWInfo->revMask |= MASKBIT(ii);
168237    }
168238  }
168239}
168240
168241/*
168242** Generate the beginning of the loop used for WHERE clause processing.
168243** The return value is a pointer to an opaque structure that contains
168244** information needed to terminate the loop.  Later, the calling routine
168245** should invoke sqlite3WhereEnd() with the return value of this function
168246** in order to complete the WHERE clause processing.
168247**
168248** If an error occurs, this routine returns NULL.
168249**
168250** The basic idea is to do a nested loop, one loop for each table in
168251** the FROM clause of a select.  (INSERT and UPDATE statements are the
168252** same as a SELECT with only a single table in the FROM clause.)  For
168253** example, if the SQL is this:
168254**
168255**       SELECT * FROM t1, t2, t3 WHERE ...;
168256**
168257** Then the code generated is conceptually like the following:
168258**
168259**      foreach row1 in t1 do       \    Code generated
168260**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
168261**          foreach row3 in t3 do   /
168262**            ...
168263**          end                     \    Code generated
168264**        end                        |-- by sqlite3WhereEnd()
168265**      end                         /
168266**
168267** Note that the loops might not be nested in the order in which they
168268** appear in the FROM clause if a different order is better able to make
168269** use of indices.  Note also that when the IN operator appears in
168270** the WHERE clause, it might result in additional nested loops for
168271** scanning through all values on the right-hand side of the IN.
168272**
168273** There are Btree cursors associated with each table.  t1 uses cursor
168274** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
168275** And so forth.  This routine generates code to open those VDBE cursors
168276** and sqlite3WhereEnd() generates the code to close them.
168277**
168278** The code that sqlite3WhereBegin() generates leaves the cursors named
168279** in pTabList pointing at their appropriate entries.  The [...] code
168280** can use OP_Column and OP_Rowid opcodes on these cursors to extract
168281** data from the various tables of the loop.
168282**
168283** If the WHERE clause is empty, the foreach loops must each scan their
168284** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
168285** the tables have indices and there are terms in the WHERE clause that
168286** refer to those indices, a complete table scan can be avoided and the
168287** code will run much faster.  Most of the work of this routine is checking
168288** to see if there are indices that can be used to speed up the loop.
168289**
168290** Terms of the WHERE clause are also used to limit which rows actually
168291** make it to the "..." in the middle of the loop.  After each "foreach",
168292** terms of the WHERE clause that use only terms in that loop and outer
168293** loops are evaluated and if false a jump is made around all subsequent
168294** inner loops (or around the "..." if the test occurs within the inner-
168295** most loop)
168296**
168297** OUTER JOINS
168298**
168299** An outer join of tables t1 and t2 is conceptually coded as follows:
168300**
168301**    foreach row1 in t1 do
168302**      flag = 0
168303**      foreach row2 in t2 do
168304**        start:
168305**          ...
168306**          flag = 1
168307**      end
168308**      if flag==0 then
168309**        move the row2 cursor to a null row
168310**        goto start
168311**      fi
168312**    end
168313**
168314** ORDER BY CLAUSE PROCESSING
168315**
168316** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
168317** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
168318** if there is one.  If there is no ORDER BY clause or if this routine
168319** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
168320**
168321** The iIdxCur parameter is the cursor number of an index.  If
168322** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
168323** to use for OR clause processing.  The WHERE clause should use this
168324** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
168325** the first cursor in an array of cursors for all indices.  iIdxCur should
168326** be used to compute the appropriate cursor depending on which index is
168327** used.
168328*/
168329SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
168330  Parse *pParse,          /* The parser context */
168331  SrcList *pTabList,      /* FROM clause: A list of all tables to be scanned */
168332  Expr *pWhere,           /* The WHERE clause */
168333  ExprList *pOrderBy,     /* An ORDER BY (or GROUP BY) clause, or NULL */
168334  ExprList *pResultSet,   /* Query result set.  Req'd for DISTINCT */
168335  Select *pSelect,        /* The entire SELECT statement */
168336  u16 wctrlFlags,         /* The WHERE_* flags defined in sqliteInt.h */
168337  int iAuxArg             /* If WHERE_OR_SUBCLAUSE is set, index cursor number
168338                          ** If WHERE_USE_LIMIT, then the limit amount */
168339){
168340  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
168341  int nTabList;              /* Number of elements in pTabList */
168342  WhereInfo *pWInfo;         /* Will become the return value of this function */
168343  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
168344  Bitmask notReady;          /* Cursors that are not yet positioned */
168345  WhereLoopBuilder sWLB;     /* The WhereLoop builder */
168346  WhereMaskSet *pMaskSet;    /* The expression mask set */
168347  WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
168348  WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
168349  int ii;                    /* Loop counter */
168350  sqlite3 *db;               /* Database connection */
168351  int rc;                    /* Return code */
168352  u8 bFordelete = 0;         /* OPFLAG_FORDELETE or zero, as appropriate */
168353
168354  assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
168355        (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
168356     && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
168357  ));
168358
168359  /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
168360  assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
168361            || (wctrlFlags & WHERE_USE_LIMIT)==0 );
168362
168363  /* Variable initialization */
168364  db = pParse->db;
168365  memset(&sWLB, 0, sizeof(sWLB));
168366
168367  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
168368  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
168369  if( pOrderBy && pOrderBy->nExpr>=BMS ){
168370    pOrderBy = 0;
168371    wctrlFlags &= ~WHERE_WANT_DISTINCT;
168372  }
168373
168374  /* The number of tables in the FROM clause is limited by the number of
168375  ** bits in a Bitmask
168376  */
168377  testcase( pTabList->nSrc==BMS );
168378  if( pTabList->nSrc>BMS ){
168379    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
168380    return 0;
168381  }
168382
168383  /* This function normally generates a nested loop for all tables in
168384  ** pTabList.  But if the WHERE_OR_SUBCLAUSE flag is set, then we should
168385  ** only generate code for the first table in pTabList and assume that
168386  ** any cursors associated with subsequent tables are uninitialized.
168387  */
168388  nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
168389
168390  /* Allocate and initialize the WhereInfo structure that will become the
168391  ** return value. A single allocation is used to store the WhereInfo
168392  ** struct, the contents of WhereInfo.a[], the WhereClause structure
168393  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
168394  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
168395  ** some architectures. Hence the ROUND8() below.
168396  */
168397  nByteWInfo = ROUND8P(sizeof(WhereInfo));
168398  if( nTabList>1 ){
168399    nByteWInfo = ROUND8P(nByteWInfo + (nTabList-1)*sizeof(WhereLevel));
168400  }
168401  pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
168402  if( db->mallocFailed ){
168403    sqlite3DbFree(db, pWInfo);
168404    pWInfo = 0;
168405    goto whereBeginError;
168406  }
168407  pWInfo->pParse = pParse;
168408  pWInfo->pTabList = pTabList;
168409  pWInfo->pOrderBy = pOrderBy;
168410#if WHERETRACE_ENABLED
168411  pWInfo->pWhere = pWhere;
168412#endif
168413  pWInfo->pResultSet = pResultSet;
168414  pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
168415  pWInfo->nLevel = nTabList;
168416  pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse);
168417  pWInfo->wctrlFlags = wctrlFlags;
168418  pWInfo->iLimit = iAuxArg;
168419  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
168420  pWInfo->pSelect = pSelect;
168421  memset(&pWInfo->nOBSat, 0,
168422         offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
168423  memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
168424  assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
168425  pMaskSet = &pWInfo->sMaskSet;
168426  pMaskSet->n = 0;
168427  pMaskSet->ix[0] = -99; /* Initialize ix[0] to a value that can never be
168428                         ** a valid cursor number, to avoid an initial
168429                         ** test for pMaskSet->n==0 in sqlite3WhereGetMask() */
168430  sWLB.pWInfo = pWInfo;
168431  sWLB.pWC = &pWInfo->sWC;
168432  sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
168433  assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
168434  whereLoopInit(sWLB.pNew);
168435#ifdef SQLITE_DEBUG
168436  sWLB.pNew->cId = '*';
168437#endif
168438
168439  /* Split the WHERE clause into separate subexpressions where each
168440  ** subexpression is separated by an AND operator.
168441  */
168442  sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
168443  sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
168444
168445  /* Special case: No FROM clause
168446  */
168447  if( nTabList==0 ){
168448    if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
168449    if( (wctrlFlags & WHERE_WANT_DISTINCT)!=0
168450     && OptimizationEnabled(db, SQLITE_DistinctOpt)
168451    ){
168452      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
168453    }
168454    if( ALWAYS(pWInfo->pSelect)
168455     && (pWInfo->pSelect->selFlags & SF_MultiValue)==0
168456    ){
168457      ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
168458    }
168459  }else{
168460    /* Assign a bit from the bitmask to every term in the FROM clause.
168461    **
168462    ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
168463    **
168464    ** The rule of the previous sentence ensures that if X is the bitmask for
168465    ** a table T, then X-1 is the bitmask for all other tables to the left of T.
168466    ** Knowing the bitmask for all tables to the left of a left join is
168467    ** important.  Ticket #3015.
168468    **
168469    ** Note that bitmasks are created for all pTabList->nSrc tables in
168470    ** pTabList, not just the first nTabList tables.  nTabList is normally
168471    ** equal to pTabList->nSrc but might be shortened to 1 if the
168472    ** WHERE_OR_SUBCLAUSE flag is set.
168473    */
168474    ii = 0;
168475    do{
168476      createMask(pMaskSet, pTabList->a[ii].iCursor);
168477      sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
168478    }while( (++ii)<pTabList->nSrc );
168479  #ifdef SQLITE_DEBUG
168480    {
168481      Bitmask mx = 0;
168482      for(ii=0; ii<pTabList->nSrc; ii++){
168483        Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
168484        assert( m>=mx );
168485        mx = m;
168486      }
168487    }
168488  #endif
168489  }
168490
168491  /* Analyze all of the subexpressions. */
168492  sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
168493  if( pSelect && pSelect->pLimit ){
168494    sqlite3WhereAddLimit(&pWInfo->sWC, pSelect);
168495  }
168496  if( pParse->nErr ) goto whereBeginError;
168497
168498  /* The False-WHERE-Term-Bypass optimization:
168499  **
168500  ** If there are WHERE terms that are false, then no rows will be output,
168501  ** so skip over all of the code generated here.
168502  **
168503  ** Conditions:
168504  **
168505  **   (1)  The WHERE term must not refer to any tables in the join.
168506  **   (2)  The term must not come from an ON clause on the
168507  **        right-hand side of a LEFT or FULL JOIN.
168508  **   (3)  The term must not come from an ON clause, or there must be
168509  **        no RIGHT or FULL OUTER joins in pTabList.
168510  **   (4)  If the expression contains non-deterministic functions
168511  **        that are not within a sub-select. This is not required
168512  **        for correctness but rather to preserves SQLite's legacy
168513  **        behaviour in the following two cases:
168514  **
168515  **          WHERE random()>0;           -- eval random() once per row
168516  **          WHERE (SELECT random())>0;  -- eval random() just once overall
168517  **
168518  ** Note that the Where term need not be a constant in order for this
168519  ** optimization to apply, though it does need to be constant relative to
168520  ** the current subquery (condition 1).  The term might include variables
168521  ** from outer queries so that the value of the term changes from one
168522  ** invocation of the current subquery to the next.
168523  */
168524  for(ii=0; ii<sWLB.pWC->nBase; ii++){
168525    WhereTerm *pT = &sWLB.pWC->a[ii];  /* A term of the WHERE clause */
168526    Expr *pX;                          /* The expression of pT */
168527    if( pT->wtFlags & TERM_VIRTUAL ) continue;
168528    pX = pT->pExpr;
168529    assert( pX!=0 );
168530    assert( pT->prereqAll!=0 || !ExprHasProperty(pX, EP_OuterON) );
168531    if( pT->prereqAll==0                           /* Conditions (1) and (2) */
168532     && (nTabList==0 || exprIsDeterministic(pX))   /* Condition (4) */
168533     && !(ExprHasProperty(pX, EP_InnerON)          /* Condition (3) */
168534          && (pTabList->a[0].fg.jointype & JT_LTORJ)!=0 )
168535    ){
168536      sqlite3ExprIfFalse(pParse, pX, pWInfo->iBreak, SQLITE_JUMPIFNULL);
168537      pT->wtFlags |= TERM_CODED;
168538    }
168539  }
168540
168541  if( wctrlFlags & WHERE_WANT_DISTINCT ){
168542    if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
168543      /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
168544      ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
168545      wctrlFlags &= ~WHERE_WANT_DISTINCT;
168546      pWInfo->wctrlFlags &= ~WHERE_WANT_DISTINCT;
168547    }else if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
168548      /* The DISTINCT marking is pointless.  Ignore it. */
168549      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
168550    }else if( pOrderBy==0 ){
168551      /* Try to ORDER BY the result set to make distinct processing easier */
168552      pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
168553      pWInfo->pOrderBy = pResultSet;
168554    }
168555  }
168556
168557  /* Construct the WhereLoop objects */
168558#if defined(WHERETRACE_ENABLED)
168559  if( sqlite3WhereTrace & 0xffffffff ){
168560    sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
168561    if( wctrlFlags & WHERE_USE_LIMIT ){
168562      sqlite3DebugPrintf(", limit: %d", iAuxArg);
168563    }
168564    sqlite3DebugPrintf(")\n");
168565    if( sqlite3WhereTrace & 0x8000 ){
168566      Select sSelect;
168567      memset(&sSelect, 0, sizeof(sSelect));
168568      sSelect.selFlags = SF_WhereBegin;
168569      sSelect.pSrc = pTabList;
168570      sSelect.pWhere = pWhere;
168571      sSelect.pOrderBy = pOrderBy;
168572      sSelect.pEList = pResultSet;
168573      sqlite3TreeViewSelect(0, &sSelect, 0);
168574    }
168575    if( sqlite3WhereTrace & 0x4000 ){ /* Display all WHERE clause terms */
168576      sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n");
168577      sqlite3WhereClausePrint(sWLB.pWC);
168578    }
168579  }
168580#endif
168581
168582  if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
168583    rc = whereLoopAddAll(&sWLB);
168584    if( rc ) goto whereBeginError;
168585
168586#ifdef SQLITE_ENABLE_STAT4
168587    /* If one or more WhereTerm.truthProb values were used in estimating
168588    ** loop parameters, but then those truthProb values were subsequently
168589    ** changed based on STAT4 information while computing subsequent loops,
168590    ** then we need to rerun the whole loop building process so that all
168591    ** loops will be built using the revised truthProb values. */
168592    if( sWLB.bldFlags2 & SQLITE_BLDF2_2NDPASS ){
168593      WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
168594      WHERETRACE(0xffffffff,
168595           ("**** Redo all loop computations due to"
168596            " TERM_HIGHTRUTH changes ****\n"));
168597      while( pWInfo->pLoops ){
168598        WhereLoop *p = pWInfo->pLoops;
168599        pWInfo->pLoops = p->pNextLoop;
168600        whereLoopDelete(db, p);
168601      }
168602      rc = whereLoopAddAll(&sWLB);
168603      if( rc ) goto whereBeginError;
168604    }
168605#endif
168606    WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
168607
168608    wherePathSolver(pWInfo, 0);
168609    if( db->mallocFailed ) goto whereBeginError;
168610    if( pWInfo->pOrderBy ){
168611       whereInterstageHeuristic(pWInfo);
168612       wherePathSolver(pWInfo, pWInfo->nRowOut+1);
168613       if( db->mallocFailed ) goto whereBeginError;
168614    }
168615
168616    /* TUNING:  Assume that a DISTINCT clause on a subquery reduces
168617    ** the output size by a factor of 8 (LogEst -30).
168618    */
168619    if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
168620      WHERETRACE(0x0080,("nRowOut reduced from %d to %d due to DISTINCT\n",
168621                         pWInfo->nRowOut, pWInfo->nRowOut-30));
168622      pWInfo->nRowOut -= 30;
168623    }
168624
168625  }
168626  assert( pWInfo->pTabList!=0 );
168627  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
168628    whereReverseScanOrder(pWInfo);
168629  }
168630  if( pParse->nErr ){
168631    goto whereBeginError;
168632  }
168633  assert( db->mallocFailed==0 );
168634#ifdef WHERETRACE_ENABLED
168635  if( sqlite3WhereTrace ){
168636    sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
168637    if( pWInfo->nOBSat>0 ){
168638      sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
168639    }
168640    switch( pWInfo->eDistinct ){
168641      case WHERE_DISTINCT_UNIQUE: {
168642        sqlite3DebugPrintf("  DISTINCT=unique");
168643        break;
168644      }
168645      case WHERE_DISTINCT_ORDERED: {
168646        sqlite3DebugPrintf("  DISTINCT=ordered");
168647        break;
168648      }
168649      case WHERE_DISTINCT_UNORDERED: {
168650        sqlite3DebugPrintf("  DISTINCT=unordered");
168651        break;
168652      }
168653    }
168654    sqlite3DebugPrintf("\n");
168655    for(ii=0; ii<pWInfo->nLevel; ii++){
168656      sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
168657    }
168658  }
168659#endif
168660
168661  /* Attempt to omit tables from a join that do not affect the result.
168662  ** See the comment on whereOmitNoopJoin() for further information.
168663  **
168664  ** This query optimization is factored out into a separate "no-inline"
168665  ** procedure to keep the sqlite3WhereBegin() procedure from becoming
168666  ** too large.  If sqlite3WhereBegin() becomes too large, that prevents
168667  ** some C-compiler optimizers from in-lining the
168668  ** sqlite3WhereCodeOneLoopStart() procedure, and it is important to
168669  ** in-line sqlite3WhereCodeOneLoopStart() for performance reasons.
168670  */
168671  notReady = ~(Bitmask)0;
168672  if( pWInfo->nLevel>=2
168673   && pResultSet!=0                         /* these two combine to guarantee */
168674   && 0==(wctrlFlags & WHERE_AGG_DISTINCT)  /* condition (1) above */
168675   && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
168676  ){
168677    notReady = whereOmitNoopJoin(pWInfo, notReady);
168678    nTabList = pWInfo->nLevel;
168679    assert( nTabList>0 );
168680  }
168681
168682  /* Check to see if there are any SEARCH loops that might benefit from
168683  ** using a Bloom filter.
168684  */
168685  if( pWInfo->nLevel>=2
168686   && OptimizationEnabled(db, SQLITE_BloomFilter)
168687  ){
168688    whereCheckIfBloomFilterIsUseful(pWInfo);
168689  }
168690
168691#if defined(WHERETRACE_ENABLED)
168692  if( sqlite3WhereTrace & 0x4000 ){ /* Display all terms of the WHERE clause */
168693    sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n");
168694    sqlite3WhereClausePrint(sWLB.pWC);
168695  }
168696  WHERETRACE(0xffffffff,("*** Optimizer Finished ***\n"));
168697#endif
168698  pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
168699
168700  /* If the caller is an UPDATE or DELETE statement that is requesting
168701  ** to use a one-pass algorithm, determine if this is appropriate.
168702  **
168703  ** A one-pass approach can be used if the caller has requested one
168704  ** and either (a) the scan visits at most one row or (b) each
168705  ** of the following are true:
168706  **
168707  **   * the caller has indicated that a one-pass approach can be used
168708  **     with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
168709  **   * the table is not a virtual table, and
168710  **   * either the scan does not use the OR optimization or the caller
168711  **     is a DELETE operation (WHERE_DUPLICATES_OK is only specified
168712  **     for DELETE).
168713  **
168714  ** The last qualification is because an UPDATE statement uses
168715  ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
168716  ** use a one-pass approach, and this is not set accurately for scans
168717  ** that use the OR optimization.
168718  */
168719  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
168720  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
168721    int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
168722    int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
168723    assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) );
168724    if( bOnerow || (
168725        0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
168726     && !IsVirtual(pTabList->a[0].pTab)
168727     && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
168728     && OptimizationEnabled(db, SQLITE_OnePass)
168729    )){
168730      pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
168731      if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
168732        if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
168733          bFordelete = OPFLAG_FORDELETE;
168734        }
168735        pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
168736      }
168737    }
168738  }
168739
168740  /* Open all tables in the pTabList and any indices selected for
168741  ** searching those tables.
168742  */
168743  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
168744    Table *pTab;     /* Table to open */
168745    int iDb;         /* Index of database containing table/index */
168746    SrcItem *pTabItem;
168747
168748    pTabItem = &pTabList->a[pLevel->iFrom];
168749    pTab = pTabItem->pTab;
168750    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
168751    pLoop = pLevel->pWLoop;
168752    if( (pTab->tabFlags & TF_Ephemeral)!=0 || IsView(pTab) ){
168753      /* Do nothing */
168754    }else
168755#ifndef SQLITE_OMIT_VIRTUALTABLE
168756    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
168757      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
168758      int iCur = pTabItem->iCursor;
168759      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
168760    }else if( IsVirtual(pTab) ){
168761      /* noop */
168762    }else
168763#endif
168764    if( ((pLoop->wsFlags & WHERE_IDX_ONLY)==0
168765         && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0)
168766     || (pTabItem->fg.jointype & (JT_LTORJ|JT_RIGHT))!=0
168767    ){
168768      int op = OP_OpenRead;
168769      if( pWInfo->eOnePass!=ONEPASS_OFF ){
168770        op = OP_OpenWrite;
168771        pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
168772      };
168773      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
168774      assert( pTabItem->iCursor==pLevel->iTabCur );
168775      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
168776      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
168777      if( pWInfo->eOnePass==ONEPASS_OFF
168778       && pTab->nCol<BMS
168779       && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0
168780       && (pLoop->wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))==0
168781      ){
168782        /* If we know that only a prefix of the record will be used,
168783        ** it is advantageous to reduce the "column count" field in
168784        ** the P4 operand of the OP_OpenRead/Write opcode. */
168785        Bitmask b = pTabItem->colUsed;
168786        int n = 0;
168787        for(; b; b=b>>1, n++){}
168788        sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
168789        assert( n<=pTab->nCol );
168790      }
168791#ifdef SQLITE_ENABLE_CURSOR_HINTS
168792      if( pLoop->u.btree.pIndex!=0 && (pTab->tabFlags & TF_WithoutRowid)==0 ){
168793        sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
168794      }else
168795#endif
168796      {
168797        sqlite3VdbeChangeP5(v, bFordelete);
168798      }
168799#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
168800      sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
168801                            (const u8*)&pTabItem->colUsed, P4_INT64);
168802#endif
168803    }else{
168804      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
168805    }
168806    if( pLoop->wsFlags & WHERE_INDEXED ){
168807      Index *pIx = pLoop->u.btree.pIndex;
168808      int iIndexCur;
168809      int op = OP_OpenRead;
168810      /* iAuxArg is always set to a positive value if ONEPASS is possible */
168811      assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
168812      if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
168813       && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
168814      ){
168815        /* This is one term of an OR-optimization using the PRIMARY KEY of a
168816        ** WITHOUT ROWID table.  No need for a separate index */
168817        iIndexCur = pLevel->iTabCur;
168818        op = 0;
168819      }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
168820        Index *pJ = pTabItem->pTab->pIndex;
168821        iIndexCur = iAuxArg;
168822        assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
168823        while( ALWAYS(pJ) && pJ!=pIx ){
168824          iIndexCur++;
168825          pJ = pJ->pNext;
168826        }
168827        op = OP_OpenWrite;
168828        pWInfo->aiCurOnePass[1] = iIndexCur;
168829      }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
168830        iIndexCur = iAuxArg;
168831        op = OP_ReopenIdx;
168832      }else{
168833        iIndexCur = pParse->nTab++;
168834        if( pIx->bHasExpr && OptimizationEnabled(db, SQLITE_IndexedExpr) ){
168835          whereAddIndexedExpr(pParse, pIx, iIndexCur, pTabItem);
168836        }
168837        if( pIx->pPartIdxWhere && (pTabItem->fg.jointype & JT_RIGHT)==0 ){
168838          wherePartIdxExpr(
168839              pParse, pIx, pIx->pPartIdxWhere, 0, iIndexCur, pTabItem
168840          );
168841        }
168842      }
168843      pLevel->iIdxCur = iIndexCur;
168844      assert( pIx!=0 );
168845      assert( pIx->pSchema==pTab->pSchema );
168846      assert( iIndexCur>=0 );
168847      if( op ){
168848        sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
168849        sqlite3VdbeSetP4KeyInfo(pParse, pIx);
168850        if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
168851         && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
168852         && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0
168853         && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
168854         && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
168855         && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
168856        ){
168857          sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ);
168858        }
168859        VdbeComment((v, "%s", pIx->zName));
168860#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
168861        {
168862          u64 colUsed = 0;
168863          int ii, jj;
168864          for(ii=0; ii<pIx->nColumn; ii++){
168865            jj = pIx->aiColumn[ii];
168866            if( jj<0 ) continue;
168867            if( jj>63 ) jj = 63;
168868            if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
168869            colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
168870          }
168871          sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
168872                                (u8*)&colUsed, P4_INT64);
168873        }
168874#endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
168875      }
168876    }
168877    if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
168878    if( (pTabItem->fg.jointype & JT_RIGHT)!=0
168879     && (pLevel->pRJ = sqlite3WhereMalloc(pWInfo, sizeof(WhereRightJoin)))!=0
168880    ){
168881      WhereRightJoin *pRJ = pLevel->pRJ;
168882      pRJ->iMatch = pParse->nTab++;
168883      pRJ->regBloom = ++pParse->nMem;
168884      sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom);
168885      pRJ->regReturn = ++pParse->nMem;
168886      sqlite3VdbeAddOp2(v, OP_Null, 0, pRJ->regReturn);
168887      assert( pTab==pTabItem->pTab );
168888      if( HasRowid(pTab) ){
168889        KeyInfo *pInfo;
168890        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, 1);
168891        pInfo = sqlite3KeyInfoAlloc(pParse->db, 1, 0);
168892        if( pInfo ){
168893          pInfo->aColl[0] = 0;
168894          pInfo->aSortFlags[0] = 0;
168895          sqlite3VdbeAppendP4(v, pInfo, P4_KEYINFO);
168896        }
168897      }else{
168898        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
168899        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, pPk->nKeyCol);
168900        sqlite3VdbeSetP4KeyInfo(pParse, pPk);
168901      }
168902      pLoop->wsFlags &= ~WHERE_IDX_ONLY;
168903      /* The nature of RIGHT JOIN processing is such that it messes up
168904      ** the output order.  So omit any ORDER BY/GROUP BY elimination
168905      ** optimizations.  We need to do an actual sort for RIGHT JOIN. */
168906      pWInfo->nOBSat = 0;
168907      pWInfo->eDistinct = WHERE_DISTINCT_UNORDERED;
168908    }
168909  }
168910  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
168911  if( db->mallocFailed ) goto whereBeginError;
168912
168913  /* Generate the code to do the search.  Each iteration of the for
168914  ** loop below generates code for a single nested loop of the VM
168915  ** program.
168916  */
168917  for(ii=0; ii<nTabList; ii++){
168918    int addrExplain;
168919    int wsFlags;
168920    SrcItem *pSrc;
168921    if( pParse->nErr ) goto whereBeginError;
168922    pLevel = &pWInfo->a[ii];
168923    wsFlags = pLevel->pWLoop->wsFlags;
168924    pSrc = &pTabList->a[pLevel->iFrom];
168925    if( pSrc->fg.isMaterialized ){
168926      if( pSrc->fg.isCorrelated ){
168927        sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
168928      }else{
168929        int iOnce = sqlite3VdbeAddOp0(v, OP_Once);  VdbeCoverage(v);
168930        sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
168931        sqlite3VdbeJumpHere(v, iOnce);
168932      }
168933    }
168934    assert( pTabList == pWInfo->pTabList );
168935    if( (wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))!=0 ){
168936      if( (wsFlags & WHERE_AUTO_INDEX)!=0 ){
168937#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
168938        constructAutomaticIndex(pParse, &pWInfo->sWC, notReady, pLevel);
168939#endif
168940      }else{
168941        sqlite3ConstructBloomFilter(pWInfo, ii, pLevel, notReady);
168942      }
168943      if( db->mallocFailed ) goto whereBeginError;
168944    }
168945    addrExplain = sqlite3WhereExplainOneScan(
168946        pParse, pTabList, pLevel, wctrlFlags
168947    );
168948    pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
168949    notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady);
168950    pWInfo->iContinue = pLevel->addrCont;
168951    if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
168952      sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
168953    }
168954  }
168955
168956  /* Done. */
168957  VdbeModuleComment((v, "Begin WHERE-core"));
168958  pWInfo->iEndWhere = sqlite3VdbeCurrentAddr(v);
168959  return pWInfo;
168960
168961  /* Jump here if malloc fails */
168962whereBeginError:
168963  if( pWInfo ){
168964    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
168965    whereInfoFree(db, pWInfo);
168966  }
168967#ifdef WHERETRACE_ENABLED
168968  /* Prevent harmless compiler warnings about debugging routines
168969  ** being declared but never used */
168970  sqlite3ShowWhereLoopList(0);
168971#endif /* WHERETRACE_ENABLED */
168972  return 0;
168973}
168974
168975/*
168976** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
168977** index rather than the main table.  In SQLITE_DEBUG mode, we want
168978** to trace those changes if PRAGMA vdbe_addoptrace=on.  This routine
168979** does that.
168980*/
168981#ifndef SQLITE_DEBUG
168982# define OpcodeRewriteTrace(D,K,P) /* no-op */
168983#else
168984# define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)
168985  static void sqlite3WhereOpcodeRewriteTrace(
168986    sqlite3 *db,
168987    int pc,
168988    VdbeOp *pOp
168989  ){
168990    if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;
168991    sqlite3VdbePrintOp(0, pc, pOp);
168992  }
168993#endif
168994
168995#ifdef SQLITE_DEBUG
168996/*
168997** Return true if cursor iCur is opened by instruction k of the
168998** bytecode.  Used inside of assert() only.
168999*/
169000static int cursorIsOpen(Vdbe *v, int iCur, int k){
169001  while( k>=0 ){
169002    VdbeOp *pOp = sqlite3VdbeGetOp(v,k--);
169003    if( pOp->p1!=iCur ) continue;
169004    if( pOp->opcode==OP_Close ) return 0;
169005    if( pOp->opcode==OP_OpenRead ) return 1;
169006    if( pOp->opcode==OP_OpenWrite ) return 1;
169007    if( pOp->opcode==OP_OpenDup ) return 1;
169008    if( pOp->opcode==OP_OpenAutoindex ) return 1;
169009    if( pOp->opcode==OP_OpenEphemeral ) return 1;
169010  }
169011  return 0;
169012}
169013#endif /* SQLITE_DEBUG */
169014
169015/*
169016** Generate the end of the WHERE loop.  See comments on
169017** sqlite3WhereBegin() for additional information.
169018*/
169019SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
169020  Parse *pParse = pWInfo->pParse;
169021  Vdbe *v = pParse->pVdbe;
169022  int i;
169023  WhereLevel *pLevel;
169024  WhereLoop *pLoop;
169025  SrcList *pTabList = pWInfo->pTabList;
169026  sqlite3 *db = pParse->db;
169027  int iEnd = sqlite3VdbeCurrentAddr(v);
169028  int nRJ = 0;
169029
169030  /* Generate loop termination code.
169031  */
169032  VdbeModuleComment((v, "End WHERE-core"));
169033  for(i=pWInfo->nLevel-1; i>=0; i--){
169034    int addr;
169035    pLevel = &pWInfo->a[i];
169036    if( pLevel->pRJ ){
169037      /* Terminate the subroutine that forms the interior of the loop of
169038      ** the RIGHT JOIN table */
169039      WhereRightJoin *pRJ = pLevel->pRJ;
169040      sqlite3VdbeResolveLabel(v, pLevel->addrCont);
169041      pLevel->addrCont = 0;
169042      pRJ->endSubrtn = sqlite3VdbeCurrentAddr(v);
169043      sqlite3VdbeAddOp3(v, OP_Return, pRJ->regReturn, pRJ->addrSubrtn, 1);
169044      VdbeCoverage(v);
169045      nRJ++;
169046    }
169047    pLoop = pLevel->pWLoop;
169048    if( pLevel->op!=OP_Noop ){
169049#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
169050      int addrSeek = 0;
169051      Index *pIdx;
169052      int n;
169053      if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
169054       && i==pWInfo->nLevel-1  /* Ticket [ef9318757b152e3] 2017-10-21 */
169055       && (pLoop->wsFlags & WHERE_INDEXED)!=0
169056       && (pIdx = pLoop->u.btree.pIndex)->hasStat1
169057       && (n = pLoop->u.btree.nDistinctCol)>0
169058       && pIdx->aiRowLogEst[n]>=36
169059      ){
169060        int r1 = pParse->nMem+1;
169061        int j, op;
169062        for(j=0; j<n; j++){
169063          sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
169064        }
169065        pParse->nMem += n+1;
169066        op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
169067        addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
169068        VdbeCoverageIf(v, op==OP_SeekLT);
169069        VdbeCoverageIf(v, op==OP_SeekGT);
169070        sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
169071      }
169072#endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
169073      /* The common case: Advance to the next row */
169074      if( pLevel->addrCont ) sqlite3VdbeResolveLabel(v, pLevel->addrCont);
169075      sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
169076      sqlite3VdbeChangeP5(v, pLevel->p5);
169077      VdbeCoverage(v);
169078      VdbeCoverageIf(v, pLevel->op==OP_Next);
169079      VdbeCoverageIf(v, pLevel->op==OP_Prev);
169080      VdbeCoverageIf(v, pLevel->op==OP_VNext);
169081      if( pLevel->regBignull ){
169082        sqlite3VdbeResolveLabel(v, pLevel->addrBignull);
169083        sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1);
169084        VdbeCoverage(v);
169085      }
169086#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
169087      if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
169088#endif
169089    }else if( pLevel->addrCont ){
169090      sqlite3VdbeResolveLabel(v, pLevel->addrCont);
169091    }
169092    if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){
169093      struct InLoop *pIn;
169094      int j;
169095      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
169096      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
169097        assert( sqlite3VdbeGetOp(v, pIn->addrInTop+1)->opcode==OP_IsNull
169098                 || pParse->db->mallocFailed );
169099        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
169100        if( pIn->eEndLoopOp!=OP_Noop ){
169101          if( pIn->nPrefix ){
169102            int bEarlyOut =
169103                (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
169104                 && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0;
169105            if( pLevel->iLeftJoin ){
169106              /* For LEFT JOIN queries, cursor pIn->iCur may not have been
169107              ** opened yet. This occurs for WHERE clauses such as
169108              ** "a = ? AND b IN (...)", where the index is on (a, b). If
169109              ** the RHS of the (a=?) is NULL, then the "b IN (...)" may
169110              ** never have been coded, but the body of the loop run to
169111              ** return the null-row. So, if the cursor is not open yet,
169112              ** jump over the OP_Next or OP_Prev instruction about to
169113              ** be coded.  */
169114              sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur,
169115                  sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut);
169116              VdbeCoverage(v);
169117            }
169118            if( bEarlyOut ){
169119              sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
169120                  sqlite3VdbeCurrentAddr(v)+2,
169121                  pIn->iBase, pIn->nPrefix);
169122              VdbeCoverage(v);
169123              /* Retarget the OP_IsNull against the left operand of IN so
169124              ** it jumps past the OP_IfNoHope.  This is because the
169125              ** OP_IsNull also bypasses the OP_Affinity opcode that is
169126              ** required by OP_IfNoHope. */
169127              sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
169128            }
169129          }
169130          sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
169131          VdbeCoverage(v);
169132          VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
169133          VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
169134        }
169135        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
169136      }
169137    }
169138    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
169139    if( pLevel->pRJ ){
169140      sqlite3VdbeAddOp3(v, OP_Return, pLevel->pRJ->regReturn, 0, 1);
169141      VdbeCoverage(v);
169142    }
169143    if( pLevel->addrSkip ){
169144      sqlite3VdbeGoto(v, pLevel->addrSkip);
169145      VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
169146      sqlite3VdbeJumpHere(v, pLevel->addrSkip);
169147      sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
169148    }
169149#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
169150    if( pLevel->addrLikeRep ){
169151      sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
169152                        pLevel->addrLikeRep);
169153      VdbeCoverage(v);
169154    }
169155#endif
169156    if( pLevel->iLeftJoin ){
169157      int ws = pLoop->wsFlags;
169158      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
169159      assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
169160      if( (ws & WHERE_IDX_ONLY)==0 ){
169161        SrcItem *pSrc = &pTabList->a[pLevel->iFrom];
169162        assert( pLevel->iTabCur==pSrc->iCursor );
169163        if( pSrc->fg.viaCoroutine ){
169164          int m, n;
169165          n = pSrc->regResult;
169166          assert( pSrc->pTab!=0 );
169167          m = pSrc->pTab->nCol;
169168          sqlite3VdbeAddOp3(v, OP_Null, 0, n, n+m-1);
169169        }
169170        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
169171      }
169172      if( (ws & WHERE_INDEXED)
169173       || ((ws & WHERE_MULTI_OR) && pLevel->u.pCoveringIdx)
169174      ){
169175        if( ws & WHERE_MULTI_OR ){
169176          Index *pIx = pLevel->u.pCoveringIdx;
169177          int iDb = sqlite3SchemaToIndex(db, pIx->pSchema);
169178          sqlite3VdbeAddOp3(v, OP_ReopenIdx, pLevel->iIdxCur, pIx->tnum, iDb);
169179          sqlite3VdbeSetP4KeyInfo(pParse, pIx);
169180        }
169181        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
169182      }
169183      if( pLevel->op==OP_Return ){
169184        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
169185      }else{
169186        sqlite3VdbeGoto(v, pLevel->addrFirst);
169187      }
169188      sqlite3VdbeJumpHere(v, addr);
169189    }
169190    VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
169191                     pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
169192  }
169193
169194  assert( pWInfo->nLevel<=pTabList->nSrc );
169195  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
169196    int k, last;
169197    VdbeOp *pOp, *pLastOp;
169198    Index *pIdx = 0;
169199    SrcItem *pTabItem = &pTabList->a[pLevel->iFrom];
169200    Table *pTab = pTabItem->pTab;
169201    assert( pTab!=0 );
169202    pLoop = pLevel->pWLoop;
169203
169204    /* Do RIGHT JOIN processing.  Generate code that will output the
169205    ** unmatched rows of the right operand of the RIGHT JOIN with
169206    ** all of the columns of the left operand set to NULL.
169207    */
169208    if( pLevel->pRJ ){
169209      sqlite3WhereRightJoinLoop(pWInfo, i, pLevel);
169210      continue;
169211    }
169212
169213    /* For a co-routine, change all OP_Column references to the table of
169214    ** the co-routine into OP_Copy of result contained in a register.
169215    ** OP_Rowid becomes OP_Null.
169216    */
169217    if( pTabItem->fg.viaCoroutine ){
169218      testcase( pParse->db->mallocFailed );
169219      assert( pTabItem->regResult>=0 );
169220      translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
169221                            pTabItem->regResult, 0);
169222      continue;
169223    }
169224
169225    /* If this scan uses an index, make VDBE code substitutions to read data
169226    ** from the index instead of from the table where possible.  In some cases
169227    ** this optimization prevents the table from ever being read, which can
169228    ** yield a significant performance boost.
169229    **
169230    ** Calls to the code generator in between sqlite3WhereBegin and
169231    ** sqlite3WhereEnd will have created code that references the table
169232    ** directly.  This loop scans all that code looking for opcodes
169233    ** that reference the table and converts them into opcodes that
169234    ** reference the index.
169235    */
169236    if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
169237      pIdx = pLoop->u.btree.pIndex;
169238    }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
169239      pIdx = pLevel->u.pCoveringIdx;
169240    }
169241    if( pIdx
169242     && !db->mallocFailed
169243    ){
169244      if( pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable) ){
169245        last = iEnd;
169246      }else{
169247        last = pWInfo->iEndWhere;
169248      }
169249      if( pIdx->bHasExpr ){
169250        IndexedExpr *p = pParse->pIdxEpr;
169251        while( p ){
169252          if( p->iIdxCur==pLevel->iIdxCur ){
169253#ifdef WHERETRACE_ENABLED
169254            if( sqlite3WhereTrace & 0x200 ){
169255              sqlite3DebugPrintf("Disable pParse->pIdxEpr term {%d,%d}\n",
169256                                  p->iIdxCur, p->iIdxCol);
169257              if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(p->pExpr);
169258            }
169259#endif
169260            p->iDataCur = -1;
169261            p->iIdxCur = -1;
169262          }
169263          p = p->pIENext;
169264        }
169265      }
169266      k = pLevel->addrBody + 1;
169267#ifdef SQLITE_DEBUG
169268      if( db->flags & SQLITE_VdbeAddopTrace ){
169269        printf("TRANSLATE cursor %d->%d in opcode range %d..%d\n",
169270                pLevel->iTabCur, pLevel->iIdxCur, k, last-1);
169271      }
169272      /* Proof that the "+1" on the k value above is safe */
169273      pOp = sqlite3VdbeGetOp(v, k - 1);
169274      assert( pOp->opcode!=OP_Column || pOp->p1!=pLevel->iTabCur );
169275      assert( pOp->opcode!=OP_Rowid  || pOp->p1!=pLevel->iTabCur );
169276      assert( pOp->opcode!=OP_IfNullRow || pOp->p1!=pLevel->iTabCur );
169277#endif
169278      pOp = sqlite3VdbeGetOp(v, k);
169279      pLastOp = pOp + (last - k);
169280      assert( pOp<=pLastOp );
169281      do{
169282        if( pOp->p1!=pLevel->iTabCur ){
169283          /* no-op */
169284        }else if( pOp->opcode==OP_Column
169285#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
169286         || pOp->opcode==OP_Offset
169287#endif
169288        ){
169289          int x = pOp->p2;
169290          assert( pIdx->pTable==pTab );
169291#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
169292          if( pOp->opcode==OP_Offset ){
169293            /* Do not need to translate the column number */
169294          }else
169295#endif
169296          if( !HasRowid(pTab) ){
169297            Index *pPk = sqlite3PrimaryKeyIndex(pTab);
169298            x = pPk->aiColumn[x];
169299            assert( x>=0 );
169300          }else{
169301            testcase( x!=sqlite3StorageColumnToTable(pTab,x) );
169302            x = sqlite3StorageColumnToTable(pTab,x);
169303          }
169304          x = sqlite3TableColumnToIndex(pIdx, x);
169305          if( x>=0 ){
169306            pOp->p2 = x;
169307            pOp->p1 = pLevel->iIdxCur;
169308            OpcodeRewriteTrace(db, k, pOp);
169309          }else{
169310            /* Unable to translate the table reference into an index
169311            ** reference.  Verify that this is harmless - that the
169312            ** table being referenced really is open.
169313            */
169314#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
169315            assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
169316                 || cursorIsOpen(v,pOp->p1,k)
169317                 || pOp->opcode==OP_Offset
169318            );
169319#else
169320            assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
169321                 || cursorIsOpen(v,pOp->p1,k)
169322            );
169323#endif
169324          }
169325        }else if( pOp->opcode==OP_Rowid ){
169326          pOp->p1 = pLevel->iIdxCur;
169327          pOp->opcode = OP_IdxRowid;
169328          OpcodeRewriteTrace(db, k, pOp);
169329        }else if( pOp->opcode==OP_IfNullRow ){
169330          pOp->p1 = pLevel->iIdxCur;
169331          OpcodeRewriteTrace(db, k, pOp);
169332        }
169333#ifdef SQLITE_DEBUG
169334        k++;
169335#endif
169336      }while( (++pOp)<pLastOp );
169337#ifdef SQLITE_DEBUG
169338      if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
169339#endif
169340    }
169341  }
169342
169343  /* The "break" point is here, just past the end of the outer loop.
169344  ** Set it.
169345  */
169346  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
169347
169348  /* Final cleanup
169349  */
169350  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
169351  whereInfoFree(db, pWInfo);
169352  pParse->withinRJSubrtn -= nRJ;
169353  return;
169354}
169355
169356/************** End of where.c ***********************************************/
169357/************** Begin file window.c ******************************************/
169358/*
169359** 2018 May 08
169360**
169361** The author disclaims copyright to this source code.  In place of
169362** a legal notice, here is a blessing:
169363**
169364**    May you do good and not evil.
169365**    May you find forgiveness for yourself and forgive others.
169366**    May you share freely, never taking more than you give.
169367**
169368*************************************************************************
169369*/
169370/* #include "sqliteInt.h" */
169371
169372#ifndef SQLITE_OMIT_WINDOWFUNC
169373
169374/*
169375** SELECT REWRITING
169376**
169377**   Any SELECT statement that contains one or more window functions in
169378**   either the select list or ORDER BY clause (the only two places window
169379**   functions may be used) is transformed by function sqlite3WindowRewrite()
169380**   in order to support window function processing. For example, with the
169381**   schema:
169382**
169383**     CREATE TABLE t1(a, b, c, d, e, f, g);
169384**
169385**   the statement:
169386**
169387**     SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;
169388**
169389**   is transformed to:
169390**
169391**     SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM (
169392**         SELECT a, e, c, d, b FROM t1 ORDER BY c, d
169393**     ) ORDER BY e;
169394**
169395**   The flattening optimization is disabled when processing this transformed
169396**   SELECT statement. This allows the implementation of the window function
169397**   (in this case max()) to process rows sorted in order of (c, d), which
169398**   makes things easier for obvious reasons. More generally:
169399**
169400**     * FROM, WHERE, GROUP BY and HAVING clauses are all moved to
169401**       the sub-query.
169402**
169403**     * ORDER BY, LIMIT and OFFSET remain part of the parent query.
169404**
169405**     * Terminals from each of the expression trees that make up the
169406**       select-list and ORDER BY expressions in the parent query are
169407**       selected by the sub-query. For the purposes of the transformation,
169408**       terminals are column references and aggregate functions.
169409**
169410**   If there is more than one window function in the SELECT that uses
169411**   the same window declaration (the OVER bit), then a single scan may
169412**   be used to process more than one window function. For example:
169413**
169414**     SELECT max(b) OVER (PARTITION BY c ORDER BY d),
169415**            min(e) OVER (PARTITION BY c ORDER BY d)
169416**     FROM t1;
169417**
169418**   is transformed in the same way as the example above. However:
169419**
169420**     SELECT max(b) OVER (PARTITION BY c ORDER BY d),
169421**            min(e) OVER (PARTITION BY a ORDER BY b)
169422**     FROM t1;
169423**
169424**   Must be transformed to:
169425**
169426**     SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM (
169427**         SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM
169428**           SELECT a, e, c, d, b FROM t1 ORDER BY a, b
169429**         ) ORDER BY c, d
169430**     ) ORDER BY e;
169431**
169432**   so that both min() and max() may process rows in the order defined by
169433**   their respective window declarations.
169434**
169435** INTERFACE WITH SELECT.C
169436**
169437**   When processing the rewritten SELECT statement, code in select.c calls
169438**   sqlite3WhereBegin() to begin iterating through the results of the
169439**   sub-query, which is always implemented as a co-routine. It then calls
169440**   sqlite3WindowCodeStep() to process rows and finish the scan by calling
169441**   sqlite3WhereEnd().
169442**
169443**   sqlite3WindowCodeStep() generates VM code so that, for each row returned
169444**   by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked.
169445**   When the sub-routine is invoked:
169446**
169447**     * The results of all window-functions for the row are stored
169448**       in the associated Window.regResult registers.
169449**
169450**     * The required terminal values are stored in the current row of
169451**       temp table Window.iEphCsr.
169452**
169453**   In some cases, depending on the window frame and the specific window
169454**   functions invoked, sqlite3WindowCodeStep() caches each entire partition
169455**   in a temp table before returning any rows. In other cases it does not.
169456**   This detail is encapsulated within this file, the code generated by
169457**   select.c is the same in either case.
169458**
169459** BUILT-IN WINDOW FUNCTIONS
169460**
169461**   This implementation features the following built-in window functions:
169462**
169463**     row_number()
169464**     rank()
169465**     dense_rank()
169466**     percent_rank()
169467**     cume_dist()
169468**     ntile(N)
169469**     lead(expr [, offset [, default]])
169470**     lag(expr [, offset [, default]])
169471**     first_value(expr)
169472**     last_value(expr)
169473**     nth_value(expr, N)
169474**
169475**   These are the same built-in window functions supported by Postgres.
169476**   Although the behaviour of aggregate window functions (functions that
169477**   can be used as either aggregates or window functions) allows them to
169478**   be implemented using an API, built-in window functions are much more
169479**   esoteric. Additionally, some window functions (e.g. nth_value())
169480**   may only be implemented by caching the entire partition in memory.
169481**   As such, some built-in window functions use the same API as aggregate
169482**   window functions and some are implemented directly using VDBE
169483**   instructions. Additionally, for those functions that use the API, the
169484**   window frame is sometimes modified before the SELECT statement is
169485**   rewritten. For example, regardless of the specified window frame, the
169486**   row_number() function always uses:
169487**
169488**     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
169489**
169490**   See sqlite3WindowUpdate() for details.
169491**
169492**   As well as some of the built-in window functions, aggregate window
169493**   functions min() and max() are implemented using VDBE instructions if
169494**   the start of the window frame is declared as anything other than
169495**   UNBOUNDED PRECEDING.
169496*/
169497
169498/*
169499** Implementation of built-in window function row_number(). Assumes that the
169500** window frame has been coerced to:
169501**
169502**   ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
169503*/
169504static void row_numberStepFunc(
169505  sqlite3_context *pCtx,
169506  int nArg,
169507  sqlite3_value **apArg
169508){
169509  i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169510  if( p ) (*p)++;
169511  UNUSED_PARAMETER(nArg);
169512  UNUSED_PARAMETER(apArg);
169513}
169514static void row_numberValueFunc(sqlite3_context *pCtx){
169515  i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169516  sqlite3_result_int64(pCtx, (p ? *p : 0));
169517}
169518
169519/*
169520** Context object type used by rank(), dense_rank(), percent_rank() and
169521** cume_dist().
169522*/
169523struct CallCount {
169524  i64 nValue;
169525  i64 nStep;
169526  i64 nTotal;
169527};
169528
169529/*
169530** Implementation of built-in window function dense_rank(). Assumes that
169531** the window frame has been set to:
169532**
169533**   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
169534*/
169535static void dense_rankStepFunc(
169536  sqlite3_context *pCtx,
169537  int nArg,
169538  sqlite3_value **apArg
169539){
169540  struct CallCount *p;
169541  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169542  if( p ) p->nStep = 1;
169543  UNUSED_PARAMETER(nArg);
169544  UNUSED_PARAMETER(apArg);
169545}
169546static void dense_rankValueFunc(sqlite3_context *pCtx){
169547  struct CallCount *p;
169548  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169549  if( p ){
169550    if( p->nStep ){
169551      p->nValue++;
169552      p->nStep = 0;
169553    }
169554    sqlite3_result_int64(pCtx, p->nValue);
169555  }
169556}
169557
169558/*
169559** Implementation of built-in window function nth_value(). This
169560** implementation is used in "slow mode" only - when the EXCLUDE clause
169561** is not set to the default value "NO OTHERS".
169562*/
169563struct NthValueCtx {
169564  i64 nStep;
169565  sqlite3_value *pValue;
169566};
169567static void nth_valueStepFunc(
169568  sqlite3_context *pCtx,
169569  int nArg,
169570  sqlite3_value **apArg
169571){
169572  struct NthValueCtx *p;
169573  p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169574  if( p ){
169575    i64 iVal;
169576    switch( sqlite3_value_numeric_type(apArg[1]) ){
169577      case SQLITE_INTEGER:
169578        iVal = sqlite3_value_int64(apArg[1]);
169579        break;
169580      case SQLITE_FLOAT: {
169581        double fVal = sqlite3_value_double(apArg[1]);
169582        if( ((i64)fVal)!=fVal ) goto error_out;
169583        iVal = (i64)fVal;
169584        break;
169585      }
169586      default:
169587        goto error_out;
169588    }
169589    if( iVal<=0 ) goto error_out;
169590
169591    p->nStep++;
169592    if( iVal==p->nStep ){
169593      p->pValue = sqlite3_value_dup(apArg[0]);
169594      if( !p->pValue ){
169595        sqlite3_result_error_nomem(pCtx);
169596      }
169597    }
169598  }
169599  UNUSED_PARAMETER(nArg);
169600  UNUSED_PARAMETER(apArg);
169601  return;
169602
169603 error_out:
169604  sqlite3_result_error(
169605      pCtx, "second argument to nth_value must be a positive integer", -1
169606  );
169607}
169608static void nth_valueFinalizeFunc(sqlite3_context *pCtx){
169609  struct NthValueCtx *p;
169610  p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0);
169611  if( p && p->pValue ){
169612    sqlite3_result_value(pCtx, p->pValue);
169613    sqlite3_value_free(p->pValue);
169614    p->pValue = 0;
169615  }
169616}
169617#define nth_valueInvFunc noopStepFunc
169618#define nth_valueValueFunc noopValueFunc
169619
169620static void first_valueStepFunc(
169621  sqlite3_context *pCtx,
169622  int nArg,
169623  sqlite3_value **apArg
169624){
169625  struct NthValueCtx *p;
169626  p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169627  if( p && p->pValue==0 ){
169628    p->pValue = sqlite3_value_dup(apArg[0]);
169629    if( !p->pValue ){
169630      sqlite3_result_error_nomem(pCtx);
169631    }
169632  }
169633  UNUSED_PARAMETER(nArg);
169634  UNUSED_PARAMETER(apArg);
169635}
169636static void first_valueFinalizeFunc(sqlite3_context *pCtx){
169637  struct NthValueCtx *p;
169638  p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169639  if( p && p->pValue ){
169640    sqlite3_result_value(pCtx, p->pValue);
169641    sqlite3_value_free(p->pValue);
169642    p->pValue = 0;
169643  }
169644}
169645#define first_valueInvFunc noopStepFunc
169646#define first_valueValueFunc noopValueFunc
169647
169648/*
169649** Implementation of built-in window function rank(). Assumes that
169650** the window frame has been set to:
169651**
169652**   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
169653*/
169654static void rankStepFunc(
169655  sqlite3_context *pCtx,
169656  int nArg,
169657  sqlite3_value **apArg
169658){
169659  struct CallCount *p;
169660  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169661  if( p ){
169662    p->nStep++;
169663    if( p->nValue==0 ){
169664      p->nValue = p->nStep;
169665    }
169666  }
169667  UNUSED_PARAMETER(nArg);
169668  UNUSED_PARAMETER(apArg);
169669}
169670static void rankValueFunc(sqlite3_context *pCtx){
169671  struct CallCount *p;
169672  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169673  if( p ){
169674    sqlite3_result_int64(pCtx, p->nValue);
169675    p->nValue = 0;
169676  }
169677}
169678
169679/*
169680** Implementation of built-in window function percent_rank(). Assumes that
169681** the window frame has been set to:
169682**
169683**   GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
169684*/
169685static void percent_rankStepFunc(
169686  sqlite3_context *pCtx,
169687  int nArg,
169688  sqlite3_value **apArg
169689){
169690  struct CallCount *p;
169691  UNUSED_PARAMETER(nArg); assert( nArg==0 );
169692  UNUSED_PARAMETER(apArg);
169693  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169694  if( p ){
169695    p->nTotal++;
169696  }
169697}
169698static void percent_rankInvFunc(
169699  sqlite3_context *pCtx,
169700  int nArg,
169701  sqlite3_value **apArg
169702){
169703  struct CallCount *p;
169704  UNUSED_PARAMETER(nArg); assert( nArg==0 );
169705  UNUSED_PARAMETER(apArg);
169706  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169707  p->nStep++;
169708}
169709static void percent_rankValueFunc(sqlite3_context *pCtx){
169710  struct CallCount *p;
169711  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169712  if( p ){
169713    p->nValue = p->nStep;
169714    if( p->nTotal>1 ){
169715      double r = (double)p->nValue / (double)(p->nTotal-1);
169716      sqlite3_result_double(pCtx, r);
169717    }else{
169718      sqlite3_result_double(pCtx, 0.0);
169719    }
169720  }
169721}
169722#define percent_rankFinalizeFunc percent_rankValueFunc
169723
169724/*
169725** Implementation of built-in window function cume_dist(). Assumes that
169726** the window frame has been set to:
169727**
169728**   GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
169729*/
169730static void cume_distStepFunc(
169731  sqlite3_context *pCtx,
169732  int nArg,
169733  sqlite3_value **apArg
169734){
169735  struct CallCount *p;
169736  UNUSED_PARAMETER(nArg); assert( nArg==0 );
169737  UNUSED_PARAMETER(apArg);
169738  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169739  if( p ){
169740    p->nTotal++;
169741  }
169742}
169743static void cume_distInvFunc(
169744  sqlite3_context *pCtx,
169745  int nArg,
169746  sqlite3_value **apArg
169747){
169748  struct CallCount *p;
169749  UNUSED_PARAMETER(nArg); assert( nArg==0 );
169750  UNUSED_PARAMETER(apArg);
169751  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169752  p->nStep++;
169753}
169754static void cume_distValueFunc(sqlite3_context *pCtx){
169755  struct CallCount *p;
169756  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0);
169757  if( p ){
169758    double r = (double)(p->nStep) / (double)(p->nTotal);
169759    sqlite3_result_double(pCtx, r);
169760  }
169761}
169762#define cume_distFinalizeFunc cume_distValueFunc
169763
169764/*
169765** Context object for ntile() window function.
169766*/
169767struct NtileCtx {
169768  i64 nTotal;                     /* Total rows in partition */
169769  i64 nParam;                     /* Parameter passed to ntile(N) */
169770  i64 iRow;                       /* Current row */
169771};
169772
169773/*
169774** Implementation of ntile(). This assumes that the window frame has
169775** been coerced to:
169776**
169777**   ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
169778*/
169779static void ntileStepFunc(
169780  sqlite3_context *pCtx,
169781  int nArg,
169782  sqlite3_value **apArg
169783){
169784  struct NtileCtx *p;
169785  assert( nArg==1 ); UNUSED_PARAMETER(nArg);
169786  p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169787  if( p ){
169788    if( p->nTotal==0 ){
169789      p->nParam = sqlite3_value_int64(apArg[0]);
169790      if( p->nParam<=0 ){
169791        sqlite3_result_error(
169792            pCtx, "argument of ntile must be a positive integer", -1
169793        );
169794      }
169795    }
169796    p->nTotal++;
169797  }
169798}
169799static void ntileInvFunc(
169800  sqlite3_context *pCtx,
169801  int nArg,
169802  sqlite3_value **apArg
169803){
169804  struct NtileCtx *p;
169805  assert( nArg==1 ); UNUSED_PARAMETER(nArg);
169806  UNUSED_PARAMETER(apArg);
169807  p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169808  p->iRow++;
169809}
169810static void ntileValueFunc(sqlite3_context *pCtx){
169811  struct NtileCtx *p;
169812  p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169813  if( p && p->nParam>0 ){
169814    int nSize = (p->nTotal / p->nParam);
169815    if( nSize==0 ){
169816      sqlite3_result_int64(pCtx, p->iRow+1);
169817    }else{
169818      i64 nLarge = p->nTotal - p->nParam*nSize;
169819      i64 iSmall = nLarge*(nSize+1);
169820      i64 iRow = p->iRow;
169821
169822      assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
169823
169824      if( iRow<iSmall ){
169825        sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
169826      }else{
169827        sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
169828      }
169829    }
169830  }
169831}
169832#define ntileFinalizeFunc ntileValueFunc
169833
169834/*
169835** Context object for last_value() window function.
169836*/
169837struct LastValueCtx {
169838  sqlite3_value *pVal;
169839  int nVal;
169840};
169841
169842/*
169843** Implementation of last_value().
169844*/
169845static void last_valueStepFunc(
169846  sqlite3_context *pCtx,
169847  int nArg,
169848  sqlite3_value **apArg
169849){
169850  struct LastValueCtx *p;
169851  UNUSED_PARAMETER(nArg);
169852  p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169853  if( p ){
169854    sqlite3_value_free(p->pVal);
169855    p->pVal = sqlite3_value_dup(apArg[0]);
169856    if( p->pVal==0 ){
169857      sqlite3_result_error_nomem(pCtx);
169858    }else{
169859      p->nVal++;
169860    }
169861  }
169862}
169863static void last_valueInvFunc(
169864  sqlite3_context *pCtx,
169865  int nArg,
169866  sqlite3_value **apArg
169867){
169868  struct LastValueCtx *p;
169869  UNUSED_PARAMETER(nArg);
169870  UNUSED_PARAMETER(apArg);
169871  p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169872  if( ALWAYS(p) ){
169873    p->nVal--;
169874    if( p->nVal==0 ){
169875      sqlite3_value_free(p->pVal);
169876      p->pVal = 0;
169877    }
169878  }
169879}
169880static void last_valueValueFunc(sqlite3_context *pCtx){
169881  struct LastValueCtx *p;
169882  p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0);
169883  if( p && p->pVal ){
169884    sqlite3_result_value(pCtx, p->pVal);
169885  }
169886}
169887static void last_valueFinalizeFunc(sqlite3_context *pCtx){
169888  struct LastValueCtx *p;
169889  p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
169890  if( p && p->pVal ){
169891    sqlite3_result_value(pCtx, p->pVal);
169892    sqlite3_value_free(p->pVal);
169893    p->pVal = 0;
169894  }
169895}
169896
169897/*
169898** Static names for the built-in window function names.  These static
169899** names are used, rather than string literals, so that FuncDef objects
169900** can be associated with a particular window function by direct
169901** comparison of the zName pointer.  Example:
169902**
169903**       if( pFuncDef->zName==row_valueName ){ ... }
169904*/
169905static const char row_numberName[] =   "row_number";
169906static const char dense_rankName[] =   "dense_rank";
169907static const char rankName[] =         "rank";
169908static const char percent_rankName[] = "percent_rank";
169909static const char cume_distName[] =    "cume_dist";
169910static const char ntileName[] =        "ntile";
169911static const char last_valueName[] =   "last_value";
169912static const char nth_valueName[] =    "nth_value";
169913static const char first_valueName[] =  "first_value";
169914static const char leadName[] =         "lead";
169915static const char lagName[] =          "lag";
169916
169917/*
169918** No-op implementations of xStep() and xFinalize().  Used as place-holders
169919** for built-in window functions that never call those interfaces.
169920**
169921** The noopValueFunc() is called but is expected to do nothing.  The
169922** noopStepFunc() is never called, and so it is marked with NO_TEST to
169923** let the test coverage routine know not to expect this function to be
169924** invoked.
169925*/
169926static void noopStepFunc(    /*NO_TEST*/
169927  sqlite3_context *p,        /*NO_TEST*/
169928  int n,                     /*NO_TEST*/
169929  sqlite3_value **a          /*NO_TEST*/
169930){                           /*NO_TEST*/
169931  UNUSED_PARAMETER(p);       /*NO_TEST*/
169932  UNUSED_PARAMETER(n);       /*NO_TEST*/
169933  UNUSED_PARAMETER(a);       /*NO_TEST*/
169934  assert(0);                 /*NO_TEST*/
169935}                            /*NO_TEST*/
169936static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
169937
169938/* Window functions that use all window interfaces: xStep, xFinal,
169939** xValue, and xInverse */
169940#define WINDOWFUNCALL(name,nArg,extra) {                                   \
169941  nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,  \
169942  name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc,               \
169943  name ## InvFunc, name ## Name, {0}                                       \
169944}
169945
169946/* Window functions that are implemented using bytecode and thus have
169947** no-op routines for their methods */
169948#define WINDOWFUNCNOOP(name,nArg,extra) {                                  \
169949  nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,  \
169950  noopStepFunc, noopValueFunc, noopValueFunc,                              \
169951  noopStepFunc, name ## Name, {0}                                          \
169952}
169953
169954/* Window functions that use all window interfaces: xStep, the
169955** same routine for xFinalize and xValue and which never call
169956** xInverse. */
169957#define WINDOWFUNCX(name,nArg,extra) {                                     \
169958  nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,  \
169959  name ## StepFunc, name ## ValueFunc, name ## ValueFunc,                  \
169960  noopStepFunc, name ## Name, {0}                                          \
169961}
169962
169963
169964/*
169965** Register those built-in window functions that are not also aggregates.
169966*/
169967SQLITE_PRIVATE void sqlite3WindowFunctions(void){
169968  static FuncDef aWindowFuncs[] = {
169969    WINDOWFUNCX(row_number, 0, 0),
169970    WINDOWFUNCX(dense_rank, 0, 0),
169971    WINDOWFUNCX(rank, 0, 0),
169972    WINDOWFUNCALL(percent_rank, 0, 0),
169973    WINDOWFUNCALL(cume_dist, 0, 0),
169974    WINDOWFUNCALL(ntile, 1, 0),
169975    WINDOWFUNCALL(last_value, 1, 0),
169976    WINDOWFUNCALL(nth_value, 2, 0),
169977    WINDOWFUNCALL(first_value, 1, 0),
169978    WINDOWFUNCNOOP(lead, 1, 0),
169979    WINDOWFUNCNOOP(lead, 2, 0),
169980    WINDOWFUNCNOOP(lead, 3, 0),
169981    WINDOWFUNCNOOP(lag, 1, 0),
169982    WINDOWFUNCNOOP(lag, 2, 0),
169983    WINDOWFUNCNOOP(lag, 3, 0),
169984  };
169985  sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
169986}
169987
169988static Window *windowFind(Parse *pParse, Window *pList, const char *zName){
169989  Window *p;
169990  for(p=pList; p; p=p->pNextWin){
169991    if( sqlite3StrICmp(p->zName, zName)==0 ) break;
169992  }
169993  if( p==0 ){
169994    sqlite3ErrorMsg(pParse, "no such window: %s", zName);
169995  }
169996  return p;
169997}
169998
169999/*
170000** This function is called immediately after resolving the function name
170001** for a window function within a SELECT statement. Argument pList is a
170002** linked list of WINDOW definitions for the current SELECT statement.
170003** Argument pFunc is the function definition just resolved and pWin
170004** is the Window object representing the associated OVER clause. This
170005** function updates the contents of pWin as follows:
170006**
170007**   * If the OVER clause referred to a named window (as in "max(x) OVER win"),
170008**     search list pList for a matching WINDOW definition, and update pWin
170009**     accordingly. If no such WINDOW clause can be found, leave an error
170010**     in pParse.
170011**
170012**   * If the function is a built-in window function that requires the
170013**     window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
170014**     of this file), pWin is updated here.
170015*/
170016SQLITE_PRIVATE void sqlite3WindowUpdate(
170017  Parse *pParse,
170018  Window *pList,                  /* List of named windows for this SELECT */
170019  Window *pWin,                   /* Window frame to update */
170020  FuncDef *pFunc                  /* Window function definition */
170021){
170022  if( pWin->zName && pWin->eFrmType==0 ){
170023    Window *p = windowFind(pParse, pList, pWin->zName);
170024    if( p==0 ) return;
170025    pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
170026    pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
170027    pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
170028    pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
170029    pWin->eStart = p->eStart;
170030    pWin->eEnd = p->eEnd;
170031    pWin->eFrmType = p->eFrmType;
170032    pWin->eExclude = p->eExclude;
170033  }else{
170034    sqlite3WindowChain(pParse, pWin, pList);
170035  }
170036  if( (pWin->eFrmType==TK_RANGE)
170037   && (pWin->pStart || pWin->pEnd)
170038   && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
170039  ){
170040    sqlite3ErrorMsg(pParse,
170041      "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
170042    );
170043  }else
170044  if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
170045    sqlite3 *db = pParse->db;
170046    if( pWin->pFilter ){
170047      sqlite3ErrorMsg(pParse,
170048          "FILTER clause may only be used with aggregate window functions"
170049      );
170050    }else{
170051      struct WindowUpdate {
170052        const char *zFunc;
170053        int eFrmType;
170054        int eStart;
170055        int eEnd;
170056      } aUp[] = {
170057        { row_numberName,   TK_ROWS,   TK_UNBOUNDED, TK_CURRENT },
170058        { dense_rankName,   TK_RANGE,  TK_UNBOUNDED, TK_CURRENT },
170059        { rankName,         TK_RANGE,  TK_UNBOUNDED, TK_CURRENT },
170060        { percent_rankName, TK_GROUPS, TK_CURRENT,   TK_UNBOUNDED },
170061        { cume_distName,    TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED },
170062        { ntileName,        TK_ROWS,   TK_CURRENT,   TK_UNBOUNDED },
170063        { leadName,         TK_ROWS,   TK_UNBOUNDED, TK_UNBOUNDED },
170064        { lagName,          TK_ROWS,   TK_UNBOUNDED, TK_CURRENT },
170065      };
170066      int i;
170067      for(i=0; i<ArraySize(aUp); i++){
170068        if( pFunc->zName==aUp[i].zFunc ){
170069          sqlite3ExprDelete(db, pWin->pStart);
170070          sqlite3ExprDelete(db, pWin->pEnd);
170071          pWin->pEnd = pWin->pStart = 0;
170072          pWin->eFrmType = aUp[i].eFrmType;
170073          pWin->eStart = aUp[i].eStart;
170074          pWin->eEnd = aUp[i].eEnd;
170075          pWin->eExclude = 0;
170076          if( pWin->eStart==TK_FOLLOWING ){
170077            pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
170078          }
170079          break;
170080        }
170081      }
170082    }
170083  }
170084  pWin->pWFunc = pFunc;
170085}
170086
170087/*
170088** Context object passed through sqlite3WalkExprList() to
170089** selectWindowRewriteExprCb() by selectWindowRewriteEList().
170090*/
170091typedef struct WindowRewrite WindowRewrite;
170092struct WindowRewrite {
170093  Window *pWin;
170094  SrcList *pSrc;
170095  ExprList *pSub;
170096  Table *pTab;
170097  Select *pSubSelect;             /* Current sub-select, if any */
170098};
170099
170100/*
170101** Callback function used by selectWindowRewriteEList(). If necessary,
170102** this function appends to the output expression-list and updates
170103** expression (*ppExpr) in place.
170104*/
170105static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
170106  struct WindowRewrite *p = pWalker->u.pRewrite;
170107  Parse *pParse = pWalker->pParse;
170108  assert( p!=0 );
170109  assert( p->pWin!=0 );
170110
170111  /* If this function is being called from within a scalar sub-select
170112  ** that used by the SELECT statement being processed, only process
170113  ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
170114  ** not process aggregates or window functions at all, as they belong
170115  ** to the scalar sub-select.  */
170116  if( p->pSubSelect ){
170117    if( pExpr->op!=TK_COLUMN ){
170118      return WRC_Continue;
170119    }else{
170120      int nSrc = p->pSrc->nSrc;
170121      int i;
170122      for(i=0; i<nSrc; i++){
170123        if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
170124      }
170125      if( i==nSrc ) return WRC_Continue;
170126    }
170127  }
170128
170129  switch( pExpr->op ){
170130
170131    case TK_FUNCTION:
170132      if( !ExprHasProperty(pExpr, EP_WinFunc) ){
170133        break;
170134      }else{
170135        Window *pWin;
170136        for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
170137          if( pExpr->y.pWin==pWin ){
170138            assert( pWin->pOwner==pExpr );
170139            return WRC_Prune;
170140          }
170141        }
170142      }
170143      /* no break */ deliberate_fall_through
170144
170145    case TK_IF_NULL_ROW:
170146    case TK_AGG_FUNCTION:
170147    case TK_COLUMN: {
170148      int iCol = -1;
170149      if( pParse->db->mallocFailed ) return WRC_Abort;
170150      if( p->pSub ){
170151        int i;
170152        for(i=0; i<p->pSub->nExpr; i++){
170153          if( 0==sqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){
170154            iCol = i;
170155            break;
170156          }
170157        }
170158      }
170159      if( iCol<0 ){
170160        Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
170161        if( pDup && pDup->op==TK_AGG_FUNCTION ) pDup->op = TK_FUNCTION;
170162        p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
170163      }
170164      if( p->pSub ){
170165        int f = pExpr->flags & EP_Collate;
170166        assert( ExprHasProperty(pExpr, EP_Static)==0 );
170167        ExprSetProperty(pExpr, EP_Static);
170168        sqlite3ExprDelete(pParse->db, pExpr);
170169        ExprClearProperty(pExpr, EP_Static);
170170        memset(pExpr, 0, sizeof(Expr));
170171
170172        pExpr->op = TK_COLUMN;
170173        pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol);
170174        pExpr->iTable = p->pWin->iEphCsr;
170175        pExpr->y.pTab = p->pTab;
170176        pExpr->flags = f;
170177      }
170178      if( pParse->db->mallocFailed ) return WRC_Abort;
170179      break;
170180    }
170181
170182    default: /* no-op */
170183      break;
170184  }
170185
170186  return WRC_Continue;
170187}
170188static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
170189  struct WindowRewrite *p = pWalker->u.pRewrite;
170190  Select *pSave = p->pSubSelect;
170191  if( pSave==pSelect ){
170192    return WRC_Continue;
170193  }else{
170194    p->pSubSelect = pSelect;
170195    sqlite3WalkSelect(pWalker, pSelect);
170196    p->pSubSelect = pSave;
170197  }
170198  return WRC_Prune;
170199}
170200
170201
170202/*
170203** Iterate through each expression in expression-list pEList. For each:
170204**
170205**   * TK_COLUMN,
170206**   * aggregate function, or
170207**   * window function with a Window object that is not a member of the
170208**     Window list passed as the second argument (pWin).
170209**
170210** Append the node to output expression-list (*ppSub). And replace it
170211** with a TK_COLUMN that reads the (N-1)th element of table
170212** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
170213** appending the new one.
170214*/
170215static void selectWindowRewriteEList(
170216  Parse *pParse,
170217  Window *pWin,
170218  SrcList *pSrc,
170219  ExprList *pEList,               /* Rewrite expressions in this list */
170220  Table *pTab,
170221  ExprList **ppSub                /* IN/OUT: Sub-select expression-list */
170222){
170223  Walker sWalker;
170224  WindowRewrite sRewrite;
170225
170226  assert( pWin!=0 );
170227  memset(&sWalker, 0, sizeof(Walker));
170228  memset(&sRewrite, 0, sizeof(WindowRewrite));
170229
170230  sRewrite.pSub = *ppSub;
170231  sRewrite.pWin = pWin;
170232  sRewrite.pSrc = pSrc;
170233  sRewrite.pTab = pTab;
170234
170235  sWalker.pParse = pParse;
170236  sWalker.xExprCallback = selectWindowRewriteExprCb;
170237  sWalker.xSelectCallback = selectWindowRewriteSelectCb;
170238  sWalker.u.pRewrite = &sRewrite;
170239
170240  (void)sqlite3WalkExprList(&sWalker, pEList);
170241
170242  *ppSub = sRewrite.pSub;
170243}
170244
170245/*
170246** Append a copy of each expression in expression-list pAppend to
170247** expression list pList. Return a pointer to the result list.
170248*/
170249static ExprList *exprListAppendList(
170250  Parse *pParse,          /* Parsing context */
170251  ExprList *pList,        /* List to which to append. Might be NULL */
170252  ExprList *pAppend,      /* List of values to append. Might be NULL */
170253  int bIntToNull
170254){
170255  if( pAppend ){
170256    int i;
170257    int nInit = pList ? pList->nExpr : 0;
170258    for(i=0; i<pAppend->nExpr; i++){
170259      sqlite3 *db = pParse->db;
170260      Expr *pDup = sqlite3ExprDup(db, pAppend->a[i].pExpr, 0);
170261      if( db->mallocFailed ){
170262        sqlite3ExprDelete(db, pDup);
170263        break;
170264      }
170265      if( bIntToNull ){
170266        int iDummy;
170267        Expr *pSub;
170268        pSub = sqlite3ExprSkipCollateAndLikely(pDup);
170269        if( sqlite3ExprIsInteger(pSub, &iDummy) ){
170270          pSub->op = TK_NULL;
170271          pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
170272          pSub->u.zToken = 0;
170273        }
170274      }
170275      pList = sqlite3ExprListAppend(pParse, pList, pDup);
170276      if( pList ) pList->a[nInit+i].fg.sortFlags = pAppend->a[i].fg.sortFlags;
170277    }
170278  }
170279  return pList;
170280}
170281
170282/*
170283** When rewriting a query, if the new subquery in the FROM clause
170284** contains TK_AGG_FUNCTION nodes that refer to an outer query,
170285** then we have to increase the Expr->op2 values of those nodes
170286** due to the extra subquery layer that was added.
170287**
170288** See also the incrAggDepth() routine in resolve.c
170289*/
170290static int sqlite3WindowExtraAggFuncDepth(Walker *pWalker, Expr *pExpr){
170291  if( pExpr->op==TK_AGG_FUNCTION
170292   && pExpr->op2>=pWalker->walkerDepth
170293  ){
170294    pExpr->op2++;
170295  }
170296  return WRC_Continue;
170297}
170298
170299static int disallowAggregatesInOrderByCb(Walker *pWalker, Expr *pExpr){
170300  if( pExpr->op==TK_AGG_FUNCTION && pExpr->pAggInfo==0 ){
170301    assert( !ExprHasProperty(pExpr, EP_IntValue) );
170302     sqlite3ErrorMsg(pWalker->pParse,
170303         "misuse of aggregate: %s()", pExpr->u.zToken);
170304  }
170305  return WRC_Continue;
170306}
170307
170308/*
170309** If the SELECT statement passed as the second argument does not invoke
170310** any SQL window functions, this function is a no-op. Otherwise, it
170311** rewrites the SELECT statement so that window function xStep functions
170312** are invoked in the correct order as described under "SELECT REWRITING"
170313** at the top of this file.
170314*/
170315SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
170316  int rc = SQLITE_OK;
170317  if( p->pWin
170318   && p->pPrior==0
170319   && ALWAYS((p->selFlags & SF_WinRewrite)==0)
170320   && ALWAYS(!IN_RENAME_OBJECT)
170321  ){
170322    Vdbe *v = sqlite3GetVdbe(pParse);
170323    sqlite3 *db = pParse->db;
170324    Select *pSub = 0;             /* The subquery */
170325    SrcList *pSrc = p->pSrc;
170326    Expr *pWhere = p->pWhere;
170327    ExprList *pGroupBy = p->pGroupBy;
170328    Expr *pHaving = p->pHaving;
170329    ExprList *pSort = 0;
170330
170331    ExprList *pSublist = 0;       /* Expression list for sub-query */
170332    Window *pMWin = p->pWin;      /* Main window object */
170333    Window *pWin;                 /* Window object iterator */
170334    Table *pTab;
170335    Walker w;
170336
170337    u32 selFlags = p->selFlags;
170338
170339    pTab = sqlite3DbMallocZero(db, sizeof(Table));
170340    if( pTab==0 ){
170341      return sqlite3ErrorToParser(db, SQLITE_NOMEM);
170342    }
170343    sqlite3AggInfoPersistWalkerInit(&w, pParse);
170344    sqlite3WalkSelect(&w, p);
170345    if( (p->selFlags & SF_Aggregate)==0 ){
170346      w.xExprCallback = disallowAggregatesInOrderByCb;
170347      w.xSelectCallback = 0;
170348      sqlite3WalkExprList(&w, p->pOrderBy);
170349    }
170350
170351    p->pSrc = 0;
170352    p->pWhere = 0;
170353    p->pGroupBy = 0;
170354    p->pHaving = 0;
170355    p->selFlags &= ~SF_Aggregate;
170356    p->selFlags |= SF_WinRewrite;
170357
170358    /* Create the ORDER BY clause for the sub-select. This is the concatenation
170359    ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
170360    ** redundant, remove the ORDER BY from the parent SELECT.  */
170361    pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1);
170362    pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
170363    if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){
170364      int nSave = pSort->nExpr;
170365      pSort->nExpr = p->pOrderBy->nExpr;
170366      if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
170367        sqlite3ExprListDelete(db, p->pOrderBy);
170368        p->pOrderBy = 0;
170369      }
170370      pSort->nExpr = nSave;
170371    }
170372
170373    /* Assign a cursor number for the ephemeral table used to buffer rows.
170374    ** The OpenEphemeral instruction is coded later, after it is known how
170375    ** many columns the table will have.  */
170376    pMWin->iEphCsr = pParse->nTab++;
170377    pParse->nTab += 3;
170378
170379    selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
170380    selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
170381    pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
170382
170383    /* Append the PARTITION BY and ORDER BY expressions to the to the
170384    ** sub-select expression list. They are required to figure out where
170385    ** boundaries for partitions and sets of peer rows lie.  */
170386    pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
170387    pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
170388
170389    /* Append the arguments passed to each window function to the
170390    ** sub-select expression list. Also allocate two registers for each
170391    ** window function - one for the accumulator, another for interim
170392    ** results.  */
170393    for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
170394      ExprList *pArgs;
170395      assert( ExprUseXList(pWin->pOwner) );
170396      assert( pWin->pWFunc!=0 );
170397      pArgs = pWin->pOwner->x.pList;
170398      if( pWin->pWFunc->funcFlags & SQLITE_SUBTYPE ){
170399        selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);
170400        pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
170401        pWin->bExprArgs = 1;
170402      }else{
170403        pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
170404        pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);
170405      }
170406      if( pWin->pFilter ){
170407        Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
170408        pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
170409      }
170410      pWin->regAccum = ++pParse->nMem;
170411      pWin->regResult = ++pParse->nMem;
170412      sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
170413    }
170414
170415    /* If there is no ORDER BY or PARTITION BY clause, and the window
170416    ** function accepts zero arguments, and there are no other columns
170417    ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
170418    ** that pSublist is still NULL here. Add a constant expression here to
170419    ** keep everything legal in this case.
170420    */
170421    if( pSublist==0 ){
170422      pSublist = sqlite3ExprListAppend(pParse, 0,
170423        sqlite3Expr(db, TK_INTEGER, "0")
170424      );
170425    }
170426
170427    pSub = sqlite3SelectNew(
170428        pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
170429    );
170430    TREETRACE(0x40,pParse,pSub,
170431       ("New window-function subquery in FROM clause of (%u/%p)\n",
170432       p->selId, p));
170433    p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
170434    assert( pSub!=0 || p->pSrc==0 ); /* Due to db->mallocFailed test inside
170435                                     ** of sqlite3DbMallocRawNN() called from
170436                                     ** sqlite3SrcListAppend() */
170437    if( p->pSrc ){
170438      Table *pTab2;
170439      p->pSrc->a[0].pSelect = pSub;
170440      p->pSrc->a[0].fg.isCorrelated = 1;
170441      sqlite3SrcListAssignCursors(pParse, p->pSrc);
170442      pSub->selFlags |= SF_Expanded|SF_OrderByReqd;
170443      pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);
170444      pSub->selFlags |= (selFlags & SF_Aggregate);
170445      if( pTab2==0 ){
170446        /* Might actually be some other kind of error, but in that case
170447        ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get
170448        ** the correct error message regardless. */
170449        rc = SQLITE_NOMEM;
170450      }else{
170451        memcpy(pTab, pTab2, sizeof(Table));
170452        pTab->tabFlags |= TF_Ephemeral;
170453        p->pSrc->a[0].pTab = pTab;
170454        pTab = pTab2;
170455        memset(&w, 0, sizeof(w));
170456        w.xExprCallback = sqlite3WindowExtraAggFuncDepth;
170457        w.xSelectCallback = sqlite3WalkerDepthIncrease;
170458        w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
170459        sqlite3WalkSelect(&w, pSub);
170460      }
170461    }else{
170462      sqlite3SelectDelete(db, pSub);
170463    }
170464    if( db->mallocFailed ) rc = SQLITE_NOMEM;
170465
170466    /* Defer deleting the temporary table pTab because if an error occurred,
170467    ** there could still be references to that table embedded in the
170468    ** result-set or ORDER BY clause of the SELECT statement p.  */
170469    sqlite3ParserAddCleanup(pParse, sqlite3DbFree, pTab);
170470  }
170471
170472  assert( rc==SQLITE_OK || pParse->nErr!=0 );
170473  return rc;
170474}
170475
170476/*
170477** Unlink the Window object from the Select to which it is attached,
170478** if it is attached.
170479*/
170480SQLITE_PRIVATE void sqlite3WindowUnlinkFromSelect(Window *p){
170481  if( p->ppThis ){
170482    *p->ppThis = p->pNextWin;
170483    if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;
170484    p->ppThis = 0;
170485  }
170486}
170487
170488/*
170489** Free the Window object passed as the second argument.
170490*/
170491SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3 *db, Window *p){
170492  if( p ){
170493    sqlite3WindowUnlinkFromSelect(p);
170494    sqlite3ExprDelete(db, p->pFilter);
170495    sqlite3ExprListDelete(db, p->pPartition);
170496    sqlite3ExprListDelete(db, p->pOrderBy);
170497    sqlite3ExprDelete(db, p->pEnd);
170498    sqlite3ExprDelete(db, p->pStart);
170499    sqlite3DbFree(db, p->zName);
170500    sqlite3DbFree(db, p->zBase);
170501    sqlite3DbFree(db, p);
170502  }
170503}
170504
170505/*
170506** Free the linked list of Window objects starting at the second argument.
170507*/
170508SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p){
170509  while( p ){
170510    Window *pNext = p->pNextWin;
170511    sqlite3WindowDelete(db, p);
170512    p = pNext;
170513  }
170514}
170515
170516/*
170517** The argument expression is an PRECEDING or FOLLOWING offset.  The
170518** value should be a non-negative integer.  If the value is not a
170519** constant, change it to NULL.  The fact that it is then a non-negative
170520** integer will be caught later.  But it is important not to leave
170521** variable values in the expression tree.
170522*/
170523static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
170524  if( 0==sqlite3ExprIsConstant(0,pExpr) ){
170525    if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
170526    sqlite3ExprDelete(pParse->db, pExpr);
170527    pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
170528  }
170529  return pExpr;
170530}
170531
170532/*
170533** Allocate and return a new Window object describing a Window Definition.
170534*/
170535SQLITE_PRIVATE Window *sqlite3WindowAlloc(
170536  Parse *pParse,    /* Parsing context */
170537  int eType,        /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
170538  int eStart,       /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
170539  Expr *pStart,     /* Start window size if TK_PRECEDING or FOLLOWING */
170540  int eEnd,         /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
170541  Expr *pEnd,       /* End window size if TK_FOLLOWING or PRECEDING */
170542  u8 eExclude       /* EXCLUDE clause */
170543){
170544  Window *pWin = 0;
170545  int bImplicitFrame = 0;
170546
170547  /* Parser assures the following: */
170548  assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
170549  assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
170550           || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
170551  assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
170552           || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
170553  assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
170554  assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
170555
170556  if( eType==0 ){
170557    bImplicitFrame = 1;
170558    eType = TK_RANGE;
170559  }
170560
170561  /* Additionally, the
170562  ** starting boundary type may not occur earlier in the following list than
170563  ** the ending boundary type:
170564  **
170565  **   UNBOUNDED PRECEDING
170566  **   <expr> PRECEDING
170567  **   CURRENT ROW
170568  **   <expr> FOLLOWING
170569  **   UNBOUNDED FOLLOWING
170570  **
170571  ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
170572  ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
170573  ** frame boundary.
170574  */
170575  if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
170576   || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
170577  ){
170578    sqlite3ErrorMsg(pParse, "unsupported frame specification");
170579    goto windowAllocErr;
170580  }
170581
170582  pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
170583  if( pWin==0 ) goto windowAllocErr;
170584  pWin->eFrmType = eType;
170585  pWin->eStart = eStart;
170586  pWin->eEnd = eEnd;
170587  if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
170588    eExclude = TK_NO;
170589  }
170590  pWin->eExclude = eExclude;
170591  pWin->bImplicitFrame = bImplicitFrame;
170592  pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
170593  pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
170594  return pWin;
170595
170596windowAllocErr:
170597  sqlite3ExprDelete(pParse->db, pEnd);
170598  sqlite3ExprDelete(pParse->db, pStart);
170599  return 0;
170600}
170601
170602/*
170603** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
170604** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
170605** equivalent nul-terminated string.
170606*/
170607SQLITE_PRIVATE Window *sqlite3WindowAssemble(
170608  Parse *pParse,
170609  Window *pWin,
170610  ExprList *pPartition,
170611  ExprList *pOrderBy,
170612  Token *pBase
170613){
170614  if( pWin ){
170615    pWin->pPartition = pPartition;
170616    pWin->pOrderBy = pOrderBy;
170617    if( pBase ){
170618      pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
170619    }
170620  }else{
170621    sqlite3ExprListDelete(pParse->db, pPartition);
170622    sqlite3ExprListDelete(pParse->db, pOrderBy);
170623  }
170624  return pWin;
170625}
170626
170627/*
170628** Window *pWin has just been created from a WINDOW clause. Token pBase
170629** is the base window. Earlier windows from the same WINDOW clause are
170630** stored in the linked list starting at pWin->pNextWin. This function
170631** either updates *pWin according to the base specification, or else
170632** leaves an error in pParse.
170633*/
170634SQLITE_PRIVATE void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
170635  if( pWin->zBase ){
170636    sqlite3 *db = pParse->db;
170637    Window *pExist = windowFind(pParse, pList, pWin->zBase);
170638    if( pExist ){
170639      const char *zErr = 0;
170640      /* Check for errors */
170641      if( pWin->pPartition ){
170642        zErr = "PARTITION clause";
170643      }else if( pExist->pOrderBy && pWin->pOrderBy ){
170644        zErr = "ORDER BY clause";
170645      }else if( pExist->bImplicitFrame==0 ){
170646        zErr = "frame specification";
170647      }
170648      if( zErr ){
170649        sqlite3ErrorMsg(pParse,
170650            "cannot override %s of window: %s", zErr, pWin->zBase
170651        );
170652      }else{
170653        pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
170654        if( pExist->pOrderBy ){
170655          assert( pWin->pOrderBy==0 );
170656          pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
170657        }
170658        sqlite3DbFree(db, pWin->zBase);
170659        pWin->zBase = 0;
170660      }
170661    }
170662  }
170663}
170664
170665/*
170666** Attach window object pWin to expression p.
170667*/
170668SQLITE_PRIVATE void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
170669  if( p ){
170670    assert( p->op==TK_FUNCTION );
170671    assert( pWin );
170672    assert( ExprIsFullSize(p) );
170673    p->y.pWin = pWin;
170674    ExprSetProperty(p, EP_WinFunc|EP_FullSize);
170675    pWin->pOwner = p;
170676    if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
170677      sqlite3ErrorMsg(pParse,
170678          "DISTINCT is not supported for window functions"
170679      );
170680    }
170681  }else{
170682    sqlite3WindowDelete(pParse->db, pWin);
170683  }
170684}
170685
170686/*
170687** Possibly link window pWin into the list at pSel->pWin (window functions
170688** to be processed as part of SELECT statement pSel). The window is linked
170689** in if either (a) there are no other windows already linked to this
170690** SELECT, or (b) the windows already linked use a compatible window frame.
170691*/
170692SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin){
170693  if( pSel ){
170694    if( 0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0) ){
170695      pWin->pNextWin = pSel->pWin;
170696      if( pSel->pWin ){
170697        pSel->pWin->ppThis = &pWin->pNextWin;
170698      }
170699      pSel->pWin = pWin;
170700      pWin->ppThis = &pSel->pWin;
170701    }else{
170702      if( sqlite3ExprListCompare(pWin->pPartition, pSel->pWin->pPartition,-1) ){
170703        pSel->selFlags |= SF_MultiPart;
170704      }
170705    }
170706  }
170707}
170708
170709/*
170710** Return 0 if the two window objects are identical, 1 if they are
170711** different, or 2 if it cannot be determined if the objects are identical
170712** or not. Identical window objects can be processed in a single scan.
170713*/
170714SQLITE_PRIVATE int sqlite3WindowCompare(
170715  const Parse *pParse,
170716  const Window *p1,
170717  const Window *p2,
170718  int bFilter
170719){
170720  int res;
170721  if( NEVER(p1==0) || NEVER(p2==0) ) return 1;
170722  if( p1->eFrmType!=p2->eFrmType ) return 1;
170723  if( p1->eStart!=p2->eStart ) return 1;
170724  if( p1->eEnd!=p2->eEnd ) return 1;
170725  if( p1->eExclude!=p2->eExclude ) return 1;
170726  if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
170727  if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
170728  if( (res = sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){
170729    return res;
170730  }
170731  if( (res = sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){
170732    return res;
170733  }
170734  if( bFilter ){
170735    if( (res = sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){
170736      return res;
170737    }
170738  }
170739  return 0;
170740}
170741
170742
170743/*
170744** This is called by code in select.c before it calls sqlite3WhereBegin()
170745** to begin iterating through the sub-query results. It is used to allocate
170746** and initialize registers and cursors used by sqlite3WindowCodeStep().
170747*/
170748SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse *pParse, Select *pSelect){
170749  int nEphExpr = pSelect->pSrc->a[0].pSelect->pEList->nExpr;
170750  Window *pMWin = pSelect->pWin;
170751  Window *pWin;
170752  Vdbe *v = sqlite3GetVdbe(pParse);
170753
170754  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);
170755  sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
170756  sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
170757  sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
170758
170759  /* Allocate registers to use for PARTITION BY values, if any. Initialize
170760  ** said registers to NULL.  */
170761  if( pMWin->pPartition ){
170762    int nExpr = pMWin->pPartition->nExpr;
170763    pMWin->regPart = pParse->nMem+1;
170764    pParse->nMem += nExpr;
170765    sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
170766  }
170767
170768  pMWin->regOne = ++pParse->nMem;
170769  sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
170770
170771  if( pMWin->eExclude ){
170772    pMWin->regStartRowid = ++pParse->nMem;
170773    pMWin->regEndRowid = ++pParse->nMem;
170774    pMWin->csrApp = pParse->nTab++;
170775    sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
170776    sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
170777    sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
170778    return;
170779  }
170780
170781  for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
170782    FuncDef *p = pWin->pWFunc;
170783    if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
170784      /* The inline versions of min() and max() require a single ephemeral
170785      ** table and 3 registers. The registers are used as follows:
170786      **
170787      **   regApp+0: slot to copy min()/max() argument to for MakeRecord
170788      **   regApp+1: integer value used to ensure keys are unique
170789      **   regApp+2: output of MakeRecord
170790      */
170791      ExprList *pList;
170792      KeyInfo *pKeyInfo;
170793      assert( ExprUseXList(pWin->pOwner) );
170794      pList = pWin->pOwner->x.pList;
170795      pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
170796      pWin->csrApp = pParse->nTab++;
170797      pWin->regApp = pParse->nMem+1;
170798      pParse->nMem += 3;
170799      if( pKeyInfo && pWin->pWFunc->zName[1]=='i' ){
170800        assert( pKeyInfo->aSortFlags[0]==0 );
170801        pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC;
170802      }
170803      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
170804      sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
170805      sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
170806    }
170807    else if( p->zName==nth_valueName || p->zName==first_valueName ){
170808      /* Allocate two registers at pWin->regApp. These will be used to
170809      ** store the start and end index of the current frame.  */
170810      pWin->regApp = pParse->nMem+1;
170811      pWin->csrApp = pParse->nTab++;
170812      pParse->nMem += 2;
170813      sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
170814    }
170815    else if( p->zName==leadName || p->zName==lagName ){
170816      pWin->csrApp = pParse->nTab++;
170817      sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
170818    }
170819  }
170820}
170821
170822#define WINDOW_STARTING_INT  0
170823#define WINDOW_ENDING_INT    1
170824#define WINDOW_NTH_VALUE_INT 2
170825#define WINDOW_STARTING_NUM  3
170826#define WINDOW_ENDING_NUM    4
170827
170828/*
170829** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
170830** value of the second argument to nth_value() (eCond==2) has just been
170831** evaluated and the result left in register reg. This function generates VM
170832** code to check that the value is a non-negative integer and throws an
170833** exception if it is not.
170834*/
170835static void windowCheckValue(Parse *pParse, int reg, int eCond){
170836  static const char *azErr[] = {
170837    "frame starting offset must be a non-negative integer",
170838    "frame ending offset must be a non-negative integer",
170839    "second argument to nth_value must be a positive integer",
170840    "frame starting offset must be a non-negative number",
170841    "frame ending offset must be a non-negative number",
170842  };
170843  static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
170844  Vdbe *v = sqlite3GetVdbe(pParse);
170845  int regZero = sqlite3GetTempReg(pParse);
170846  assert( eCond>=0 && eCond<ArraySize(azErr) );
170847  sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
170848  if( eCond>=WINDOW_STARTING_NUM ){
170849    int regString = sqlite3GetTempReg(pParse);
170850    sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
170851    sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
170852    sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
170853    VdbeCoverage(v);
170854    assert( eCond==3 || eCond==4 );
170855    VdbeCoverageIf(v, eCond==3);
170856    VdbeCoverageIf(v, eCond==4);
170857  }else{
170858    sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
170859    VdbeCoverage(v);
170860    assert( eCond==0 || eCond==1 || eCond==2 );
170861    VdbeCoverageIf(v, eCond==0);
170862    VdbeCoverageIf(v, eCond==1);
170863    VdbeCoverageIf(v, eCond==2);
170864  }
170865  sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
170866  sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC);
170867  VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
170868  VdbeCoverageNeverNullIf(v, eCond==1); /*   the OP_MustBeInt */
170869  VdbeCoverageNeverNullIf(v, eCond==2);
170870  VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
170871  VdbeCoverageNeverNullIf(v, eCond==4); /*   the OP_Ge */
170872  sqlite3MayAbort(pParse);
170873  sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
170874  sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
170875  sqlite3ReleaseTempReg(pParse, regZero);
170876}
170877
170878/*
170879** Return the number of arguments passed to the window-function associated
170880** with the object passed as the only argument to this function.
170881*/
170882static int windowArgCount(Window *pWin){
170883  const ExprList *pList;
170884  assert( ExprUseXList(pWin->pOwner) );
170885  pList = pWin->pOwner->x.pList;
170886  return (pList ? pList->nExpr : 0);
170887}
170888
170889typedef struct WindowCodeArg WindowCodeArg;
170890typedef struct WindowCsrAndReg WindowCsrAndReg;
170891
170892/*
170893** See comments above struct WindowCodeArg.
170894*/
170895struct WindowCsrAndReg {
170896  int csr;                        /* Cursor number */
170897  int reg;                        /* First in array of peer values */
170898};
170899
170900/*
170901** A single instance of this structure is allocated on the stack by
170902** sqlite3WindowCodeStep() and a pointer to it passed to the various helper
170903** routines. This is to reduce the number of arguments required by each
170904** helper function.
170905**
170906** regArg:
170907**   Each window function requires an accumulator register (just as an
170908**   ordinary aggregate function does). This variable is set to the first
170909**   in an array of accumulator registers - one for each window function
170910**   in the WindowCodeArg.pMWin list.
170911**
170912** eDelete:
170913**   The window functions implementation sometimes caches the input rows
170914**   that it processes in a temporary table. If it is not zero, this
170915**   variable indicates when rows may be removed from the temp table (in
170916**   order to reduce memory requirements - it would always be safe just
170917**   to leave them there). Possible values for eDelete are:
170918**
170919**      WINDOW_RETURN_ROW:
170920**        An input row can be discarded after it is returned to the caller.
170921**
170922**      WINDOW_AGGINVERSE:
170923**        An input row can be discarded after the window functions xInverse()
170924**        callbacks have been invoked in it.
170925**
170926**      WINDOW_AGGSTEP:
170927**        An input row can be discarded after the window functions xStep()
170928**        callbacks have been invoked in it.
170929**
170930** start,current,end
170931**   Consider a window-frame similar to the following:
170932**
170933**     (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING)
170934**
170935**   The windows functions implementation caches the input rows in a temp
170936**   table, sorted by "a, b" (it actually populates the cache lazily, and
170937**   aggressively removes rows once they are no longer required, but that's
170938**   a mere detail). It keeps three cursors open on the temp table. One
170939**   (current) that points to the next row to return to the query engine
170940**   once its window function values have been calculated. Another (end)
170941**   points to the next row to call the xStep() method of each window function
170942**   on (so that it is 2 groups ahead of current). And a third (start) that
170943**   points to the next row to call the xInverse() method of each window
170944**   function on.
170945**
170946**   Each cursor (start, current and end) consists of a VDBE cursor
170947**   (WindowCsrAndReg.csr) and an array of registers (starting at
170948**   WindowCodeArg.reg) that always contains a copy of the peer values
170949**   read from the corresponding cursor.
170950**
170951**   Depending on the window-frame in question, all three cursors may not
170952**   be required. In this case both WindowCodeArg.csr and reg are set to
170953**   0.
170954*/
170955struct WindowCodeArg {
170956  Parse *pParse;             /* Parse context */
170957  Window *pMWin;             /* First in list of functions being processed */
170958  Vdbe *pVdbe;               /* VDBE object */
170959  int addrGosub;             /* OP_Gosub to this address to return one row */
170960  int regGosub;              /* Register used with OP_Gosub(addrGosub) */
170961  int regArg;                /* First in array of accumulator registers */
170962  int eDelete;               /* See above */
170963  int regRowid;
170964
170965  WindowCsrAndReg start;
170966  WindowCsrAndReg current;
170967  WindowCsrAndReg end;
170968};
170969
170970/*
170971** Generate VM code to read the window frames peer values from cursor csr into
170972** an array of registers starting at reg.
170973*/
170974static void windowReadPeerValues(
170975  WindowCodeArg *p,
170976  int csr,
170977  int reg
170978){
170979  Window *pMWin = p->pMWin;
170980  ExprList *pOrderBy = pMWin->pOrderBy;
170981  if( pOrderBy ){
170982    Vdbe *v = sqlite3GetVdbe(p->pParse);
170983    ExprList *pPart = pMWin->pPartition;
170984    int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
170985    int i;
170986    for(i=0; i<pOrderBy->nExpr; i++){
170987      sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
170988    }
170989  }
170990}
170991
170992/*
170993** Generate VM code to invoke either xStep() (if bInverse is 0) or
170994** xInverse (if bInverse is non-zero) for each window function in the
170995** linked list starting at pMWin. Or, for built-in window functions
170996** that do not use the standard function API, generate the required
170997** inline VM code.
170998**
170999** If argument csr is greater than or equal to 0, then argument reg is
171000** the first register in an array of registers guaranteed to be large
171001** enough to hold the array of arguments for each function. In this case
171002** the arguments are extracted from the current row of csr into the
171003** array of registers before invoking OP_AggStep or OP_AggInverse
171004**
171005** Or, if csr is less than zero, then the array of registers at reg is
171006** already populated with all columns from the current row of the sub-query.
171007**
171008** If argument regPartSize is non-zero, then it is a register containing the
171009** number of rows in the current partition.
171010*/
171011static void windowAggStep(
171012  WindowCodeArg *p,
171013  Window *pMWin,                  /* Linked list of window functions */
171014  int csr,                        /* Read arguments from this cursor */
171015  int bInverse,                   /* True to invoke xInverse instead of xStep */
171016  int reg                         /* Array of registers */
171017){
171018  Parse *pParse = p->pParse;
171019  Vdbe *v = sqlite3GetVdbe(pParse);
171020  Window *pWin;
171021  for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
171022    FuncDef *pFunc = pWin->pWFunc;
171023    int regArg;
171024    int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin);
171025    int i;
171026
171027    assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED );
171028
171029    /* All OVER clauses in the same window function aggregate step must
171030    ** be the same. */
171031    assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)!=1 );
171032
171033    for(i=0; i<nArg; i++){
171034      if( i!=1 || pFunc->zName!=nth_valueName ){
171035        sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
171036      }else{
171037        sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
171038      }
171039    }
171040    regArg = reg;
171041
171042    if( pMWin->regStartRowid==0
171043     && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
171044     && (pWin->eStart!=TK_UNBOUNDED)
171045    ){
171046      int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
171047      VdbeCoverage(v);
171048      if( bInverse==0 ){
171049        sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
171050        sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
171051        sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
171052        sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
171053      }else{
171054        sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
171055        VdbeCoverageNeverTaken(v);
171056        sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
171057        sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
171058      }
171059      sqlite3VdbeJumpHere(v, addrIsNull);
171060    }else if( pWin->regApp ){
171061      assert( pFunc->zName==nth_valueName
171062           || pFunc->zName==first_valueName
171063      );
171064      assert( bInverse==0 || bInverse==1 );
171065      sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
171066    }else if( pFunc->xSFunc!=noopStepFunc ){
171067      int addrIf = 0;
171068      if( pWin->pFilter ){
171069        int regTmp;
171070        assert( ExprUseXList(pWin->pOwner) );
171071        assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr );
171072        assert( pWin->bExprArgs || nArg  ||pWin->pOwner->x.pList==0 );
171073        regTmp = sqlite3GetTempReg(pParse);
171074        sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
171075        addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
171076        VdbeCoverage(v);
171077        sqlite3ReleaseTempReg(pParse, regTmp);
171078      }
171079
171080      if( pWin->bExprArgs ){
171081        int iOp = sqlite3VdbeCurrentAddr(v);
171082        int iEnd;
171083
171084        assert( ExprUseXList(pWin->pOwner) );
171085        nArg = pWin->pOwner->x.pList->nExpr;
171086        regArg = sqlite3GetTempRange(pParse, nArg);
171087        sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0);
171088
171089        for(iEnd=sqlite3VdbeCurrentAddr(v); iOp<iEnd; iOp++){
171090          VdbeOp *pOp = sqlite3VdbeGetOp(v, iOp);
171091          if( pOp->opcode==OP_Column && pOp->p1==pMWin->iEphCsr ){
171092            pOp->p1 = csr;
171093          }
171094        }
171095      }
171096      if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
171097        CollSeq *pColl;
171098        assert( nArg>0 );
171099        assert( ExprUseXList(pWin->pOwner) );
171100        pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
171101        sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
171102      }
171103      sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
171104                        bInverse, regArg, pWin->regAccum);
171105      sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
171106      sqlite3VdbeChangeP5(v, (u8)nArg);
171107      if( pWin->bExprArgs ){
171108        sqlite3ReleaseTempRange(pParse, regArg, nArg);
171109      }
171110      if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
171111    }
171112  }
171113}
171114
171115/*
171116** Values that may be passed as the second argument to windowCodeOp().
171117*/
171118#define WINDOW_RETURN_ROW 1
171119#define WINDOW_AGGINVERSE 2
171120#define WINDOW_AGGSTEP    3
171121
171122/*
171123** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
171124** (bFin==1) for each window function in the linked list starting at
171125** pMWin. Or, for built-in window-functions that do not use the standard
171126** API, generate the equivalent VM code.
171127*/
171128static void windowAggFinal(WindowCodeArg *p, int bFin){
171129  Parse *pParse = p->pParse;
171130  Window *pMWin = p->pMWin;
171131  Vdbe *v = sqlite3GetVdbe(pParse);
171132  Window *pWin;
171133
171134  for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
171135    if( pMWin->regStartRowid==0
171136     && (pWin->pWFunc->funcFlags & SQLITE_FUNC_MINMAX)
171137     && (pWin->eStart!=TK_UNBOUNDED)
171138    ){
171139      sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
171140      sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
171141      VdbeCoverage(v);
171142      sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
171143      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
171144    }else if( pWin->regApp ){
171145      assert( pMWin->regStartRowid==0 );
171146    }else{
171147      int nArg = windowArgCount(pWin);
171148      if( bFin ){
171149        sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
171150        sqlite3VdbeAppendP4(v, pWin->pWFunc, P4_FUNCDEF);
171151        sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
171152        sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
171153      }else{
171154        sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
171155        sqlite3VdbeAppendP4(v, pWin->pWFunc, P4_FUNCDEF);
171156      }
171157    }
171158  }
171159}
171160
171161/*
171162** Generate code to calculate the current values of all window functions in the
171163** p->pMWin list by doing a full scan of the current window frame. Store the
171164** results in the Window.regResult registers, ready to return the upper
171165** layer.
171166*/
171167static void windowFullScan(WindowCodeArg *p){
171168  Window *pWin;
171169  Parse *pParse = p->pParse;
171170  Window *pMWin = p->pMWin;
171171  Vdbe *v = p->pVdbe;
171172
171173  int regCRowid = 0;              /* Current rowid value */
171174  int regCPeer = 0;               /* Current peer values */
171175  int regRowid = 0;               /* AggStep rowid value */
171176  int regPeer = 0;                /* AggStep peer values */
171177
171178  int nPeer;
171179  int lblNext;
171180  int lblBrk;
171181  int addrNext;
171182  int csr;
171183
171184  VdbeModuleComment((v, "windowFullScan begin"));
171185
171186  assert( pMWin!=0 );
171187  csr = pMWin->csrApp;
171188  nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
171189
171190  lblNext = sqlite3VdbeMakeLabel(pParse);
171191  lblBrk = sqlite3VdbeMakeLabel(pParse);
171192
171193  regCRowid = sqlite3GetTempReg(pParse);
171194  regRowid = sqlite3GetTempReg(pParse);
171195  if( nPeer ){
171196    regCPeer = sqlite3GetTempRange(pParse, nPeer);
171197    regPeer = sqlite3GetTempRange(pParse, nPeer);
171198  }
171199
171200  sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
171201  windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
171202
171203  for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
171204    sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
171205  }
171206
171207  sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
171208  VdbeCoverage(v);
171209  addrNext = sqlite3VdbeCurrentAddr(v);
171210  sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
171211  sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
171212  VdbeCoverageNeverNull(v);
171213
171214  if( pMWin->eExclude==TK_CURRENT ){
171215    sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
171216    VdbeCoverageNeverNull(v);
171217  }else if( pMWin->eExclude!=TK_NO ){
171218    int addr;
171219    int addrEq = 0;
171220    KeyInfo *pKeyInfo = 0;
171221
171222    if( pMWin->pOrderBy ){
171223      pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
171224    }
171225    if( pMWin->eExclude==TK_TIES ){
171226      addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
171227      VdbeCoverageNeverNull(v);
171228    }
171229    if( pKeyInfo ){
171230      windowReadPeerValues(p, csr, regPeer);
171231      sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
171232      sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
171233      addr = sqlite3VdbeCurrentAddr(v)+1;
171234      sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
171235      VdbeCoverageEqNe(v);
171236    }else{
171237      sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
171238    }
171239    if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
171240  }
171241
171242  windowAggStep(p, pMWin, csr, 0, p->regArg);
171243
171244  sqlite3VdbeResolveLabel(v, lblNext);
171245  sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
171246  VdbeCoverage(v);
171247  sqlite3VdbeJumpHere(v, addrNext-1);
171248  sqlite3VdbeJumpHere(v, addrNext+1);
171249  sqlite3ReleaseTempReg(pParse, regRowid);
171250  sqlite3ReleaseTempReg(pParse, regCRowid);
171251  if( nPeer ){
171252    sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
171253    sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
171254  }
171255
171256  windowAggFinal(p, 1);
171257  VdbeModuleComment((v, "windowFullScan end"));
171258}
171259
171260/*
171261** Invoke the sub-routine at regGosub (generated by code in select.c) to
171262** return the current row of Window.iEphCsr. If all window functions are
171263** aggregate window functions that use the standard API, a single
171264** OP_Gosub instruction is all that this routine generates. Extra VM code
171265** for per-row processing is only generated for the following built-in window
171266** functions:
171267**
171268**   nth_value()
171269**   first_value()
171270**   lag()
171271**   lead()
171272*/
171273static void windowReturnOneRow(WindowCodeArg *p){
171274  Window *pMWin = p->pMWin;
171275  Vdbe *v = p->pVdbe;
171276
171277  if( pMWin->regStartRowid ){
171278    windowFullScan(p);
171279  }else{
171280    Parse *pParse = p->pParse;
171281    Window *pWin;
171282
171283    for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
171284      FuncDef *pFunc = pWin->pWFunc;
171285      assert( ExprUseXList(pWin->pOwner) );
171286      if( pFunc->zName==nth_valueName
171287       || pFunc->zName==first_valueName
171288      ){
171289        int csr = pWin->csrApp;
171290        int lbl = sqlite3VdbeMakeLabel(pParse);
171291        int tmpReg = sqlite3GetTempReg(pParse);
171292        sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
171293
171294        if( pFunc->zName==nth_valueName ){
171295          sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
171296          windowCheckValue(pParse, tmpReg, 2);
171297        }else{
171298          sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
171299        }
171300        sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
171301        sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
171302        VdbeCoverageNeverNull(v);
171303        sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
171304        VdbeCoverageNeverTaken(v);
171305        sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
171306        sqlite3VdbeResolveLabel(v, lbl);
171307        sqlite3ReleaseTempReg(pParse, tmpReg);
171308      }
171309      else if( pFunc->zName==leadName || pFunc->zName==lagName ){
171310        int nArg = pWin->pOwner->x.pList->nExpr;
171311        int csr = pWin->csrApp;
171312        int lbl = sqlite3VdbeMakeLabel(pParse);
171313        int tmpReg = sqlite3GetTempReg(pParse);
171314        int iEph = pMWin->iEphCsr;
171315
171316        if( nArg<3 ){
171317          sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
171318        }else{
171319          sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
171320        }
171321        sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
171322        if( nArg<2 ){
171323          int val = (pFunc->zName==leadName ? 1 : -1);
171324          sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
171325        }else{
171326          int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
171327          int tmpReg2 = sqlite3GetTempReg(pParse);
171328          sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
171329          sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
171330          sqlite3ReleaseTempReg(pParse, tmpReg2);
171331        }
171332
171333        sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
171334        VdbeCoverage(v);
171335        sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
171336        sqlite3VdbeResolveLabel(v, lbl);
171337        sqlite3ReleaseTempReg(pParse, tmpReg);
171338      }
171339    }
171340  }
171341  sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
171342}
171343
171344/*
171345** Generate code to set the accumulator register for each window function
171346** in the linked list passed as the second argument to NULL. And perform
171347** any equivalent initialization required by any built-in window functions
171348** in the list.
171349*/
171350static int windowInitAccum(Parse *pParse, Window *pMWin){
171351  Vdbe *v = sqlite3GetVdbe(pParse);
171352  int regArg;
171353  int nArg = 0;
171354  Window *pWin;
171355  for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
171356    FuncDef *pFunc = pWin->pWFunc;
171357    assert( pWin->regAccum );
171358    sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
171359    nArg = MAX(nArg, windowArgCount(pWin));
171360    if( pMWin->regStartRowid==0 ){
171361      if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
171362        sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
171363        sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
171364      }
171365
171366      if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
171367        assert( pWin->eStart!=TK_UNBOUNDED );
171368        sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
171369        sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
171370      }
171371    }
171372  }
171373  regArg = pParse->nMem+1;
171374  pParse->nMem += nArg;
171375  return regArg;
171376}
171377
171378/*
171379** Return true if the current frame should be cached in the ephemeral table,
171380** even if there are no xInverse() calls required.
171381*/
171382static int windowCacheFrame(Window *pMWin){
171383  Window *pWin;
171384  if( pMWin->regStartRowid ) return 1;
171385  for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
171386    FuncDef *pFunc = pWin->pWFunc;
171387    if( (pFunc->zName==nth_valueName)
171388     || (pFunc->zName==first_valueName)
171389     || (pFunc->zName==leadName)
171390     || (pFunc->zName==lagName)
171391    ){
171392      return 1;
171393    }
171394  }
171395  return 0;
171396}
171397
171398/*
171399** regOld and regNew are each the first register in an array of size
171400** pOrderBy->nExpr. This function generates code to compare the two
171401** arrays of registers using the collation sequences and other comparison
171402** parameters specified by pOrderBy.
171403**
171404** If the two arrays are not equal, the contents of regNew is copied to
171405** regOld and control falls through. Otherwise, if the contents of the arrays
171406** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
171407*/
171408static void windowIfNewPeer(
171409  Parse *pParse,
171410  ExprList *pOrderBy,
171411  int regNew,                     /* First in array of new values */
171412  int regOld,                     /* First in array of old values */
171413  int addr                        /* Jump here */
171414){
171415  Vdbe *v = sqlite3GetVdbe(pParse);
171416  if( pOrderBy ){
171417    int nVal = pOrderBy->nExpr;
171418    KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
171419    sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
171420    sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
171421    sqlite3VdbeAddOp3(v, OP_Jump,
171422      sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
171423    );
171424    VdbeCoverageEqNe(v);
171425    sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
171426  }else{
171427    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
171428  }
171429}
171430
171431/*
171432** This function is called as part of generating VM programs for RANGE
171433** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
171434** the ORDER BY term in the window, and that argument op is OP_Ge, it generates
171435** code equivalent to:
171436**
171437**   if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
171438**
171439** The value of parameter op may also be OP_Gt or OP_Le. In these cases the
171440** operator in the above pseudo-code is replaced with ">" or "<=", respectively.
171441**
171442** If the sort-order for the ORDER BY term in the window is DESC, then the
171443** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
171444** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
171445** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
171446** is OP_Ge, the generated code is equivalent to:
171447**
171448**   if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
171449**
171450** A special type of arithmetic is used such that if csr1.peerVal is not
171451** a numeric type (real or integer), then the result of the addition
171452** or subtraction is a a copy of csr1.peerVal.
171453*/
171454static void windowCodeRangeTest(
171455  WindowCodeArg *p,
171456  int op,                         /* OP_Ge, OP_Gt, or OP_Le */
171457  int csr1,                       /* Cursor number for cursor 1 */
171458  int regVal,                     /* Register containing non-negative number */
171459  int csr2,                       /* Cursor number for cursor 2 */
171460  int lbl                         /* Jump destination if condition is true */
171461){
171462  Parse *pParse = p->pParse;
171463  Vdbe *v = sqlite3GetVdbe(pParse);
171464  ExprList *pOrderBy = p->pMWin->pOrderBy;  /* ORDER BY clause for window */
171465  int reg1 = sqlite3GetTempReg(pParse);     /* Reg. for csr1.peerVal+regVal */
171466  int reg2 = sqlite3GetTempReg(pParse);     /* Reg. for csr2.peerVal */
171467  int regString = ++pParse->nMem;           /* Reg. for constant value '' */
171468  int arith = OP_Add;                       /* OP_Add or OP_Subtract */
171469  int addrGe;                               /* Jump destination */
171470  int addrDone = sqlite3VdbeMakeLabel(pParse);   /* Address past OP_Ge */
171471  CollSeq *pColl;
171472
171473  /* Read the peer-value from each cursor into a register */
171474  windowReadPeerValues(p, csr1, reg1);
171475  windowReadPeerValues(p, csr2, reg2);
171476
171477  assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
171478  assert( pOrderBy && pOrderBy->nExpr==1 );
171479  if( pOrderBy->a[0].fg.sortFlags & KEYINFO_ORDER_DESC ){
171480    switch( op ){
171481      case OP_Ge: op = OP_Le; break;
171482      case OP_Gt: op = OP_Lt; break;
171483      default: assert( op==OP_Le ); op = OP_Ge; break;
171484    }
171485    arith = OP_Subtract;
171486  }
171487
171488  VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
171489      reg1, (arith==OP_Add ? "+" : "-"), regVal,
171490      ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2
171491  ));
171492
171493  /* If the BIGNULL flag is set for the ORDER BY, then it is required to
171494  ** consider NULL values to be larger than all other values, instead of
171495  ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
171496  ** (and adding that capability causes a performance regression), so
171497  ** instead if the BIGNULL flag is set then cases where either reg1 or
171498  ** reg2 are NULL are handled separately in the following block. The code
171499  ** generated is equivalent to:
171500  **
171501  **   if( reg1 IS NULL ){
171502  **     if( op==OP_Ge ) goto lbl;
171503  **     if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl;
171504  **     if( op==OP_Le && reg2 IS NULL ) goto lbl;
171505  **   }else if( reg2 IS NULL ){
171506  **     if( op==OP_Le ) goto lbl;
171507  **   }
171508  **
171509  ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is
171510  ** not taken, control jumps over the comparison operator coded below this
171511  ** block.  */
171512  if( pOrderBy->a[0].fg.sortFlags & KEYINFO_ORDER_BIGNULL ){
171513    /* This block runs if reg1 contains a NULL. */
171514    int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v);
171515    switch( op ){
171516      case OP_Ge:
171517        sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl);
171518        break;
171519      case OP_Gt:
171520        sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl);
171521        VdbeCoverage(v);
171522        break;
171523      case OP_Le:
171524        sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl);
171525        VdbeCoverage(v);
171526        break;
171527      default: assert( op==OP_Lt ); /* no-op */ break;
171528    }
171529    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
171530
171531    /* This block runs if reg1 is not NULL, but reg2 is. */
171532    sqlite3VdbeJumpHere(v, addr);
171533    sqlite3VdbeAddOp2(v, OP_IsNull, reg2,
171534                      (op==OP_Gt || op==OP_Ge) ? addrDone : lbl);
171535    VdbeCoverage(v);
171536  }
171537
171538  /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
171539  ** This block adds (or subtracts for DESC) the numeric value in regVal
171540  ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
171541  ** then leave reg1 as it is. In pseudo-code, this is implemented as:
171542  **
171543  **   if( reg1>='' ) goto addrGe;
171544  **   reg1 = reg1 +/- regVal
171545  **   addrGe:
171546  **
171547  ** Since all strings and blobs are greater-than-or-equal-to an empty string,
171548  ** the add/subtract is skipped for these, as required. If reg1 is a NULL,
171549  ** then the arithmetic is performed, but since adding or subtracting from
171550  ** NULL is always NULL anyway, this case is handled as required too.  */
171551  sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
171552  addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
171553  VdbeCoverage(v);
171554  if( (op==OP_Ge && arith==OP_Add) || (op==OP_Le && arith==OP_Subtract) ){
171555    sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
171556  }
171557  sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
171558  sqlite3VdbeJumpHere(v, addrGe);
171559
171560  /* Compare registers reg2 and reg1, taking the jump if required. Note that
171561  ** control skips over this test if the BIGNULL flag is set and either
171562  ** reg1 or reg2 contain a NULL value.  */
171563  sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
171564  pColl = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[0].pExpr);
171565  sqlite3VdbeAppendP4(v, (void*)pColl, P4_COLLSEQ);
171566  sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
171567  sqlite3VdbeResolveLabel(v, addrDone);
171568
171569  assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
171570  testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
171571  testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
171572  testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
171573  testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
171574  sqlite3ReleaseTempReg(pParse, reg1);
171575  sqlite3ReleaseTempReg(pParse, reg2);
171576
171577  VdbeModuleComment((v, "CodeRangeTest: end"));
171578}
171579
171580/*
171581** Helper function for sqlite3WindowCodeStep(). Each call to this function
171582** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
171583** operation. Refer to the header comment for sqlite3WindowCodeStep() for
171584** details.
171585*/
171586static int windowCodeOp(
171587 WindowCodeArg *p,                /* Context object */
171588 int op,                          /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
171589 int regCountdown,                /* Register for OP_IfPos countdown */
171590 int jumpOnEof                    /* Jump here if stepped cursor reaches EOF */
171591){
171592  int csr, reg;
171593  Parse *pParse = p->pParse;
171594  Window *pMWin = p->pMWin;
171595  int ret = 0;
171596  Vdbe *v = p->pVdbe;
171597  int addrContinue = 0;
171598  int bPeer = (pMWin->eFrmType!=TK_ROWS);
171599
171600  int lblDone = sqlite3VdbeMakeLabel(pParse);
171601  int addrNextRange = 0;
171602
171603  /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
171604  ** starts with UNBOUNDED PRECEDING. */
171605  if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
171606    assert( regCountdown==0 && jumpOnEof==0 );
171607    return 0;
171608  }
171609
171610  if( regCountdown>0 ){
171611    if( pMWin->eFrmType==TK_RANGE ){
171612      addrNextRange = sqlite3VdbeCurrentAddr(v);
171613      assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
171614      if( op==WINDOW_AGGINVERSE ){
171615        if( pMWin->eStart==TK_FOLLOWING ){
171616          windowCodeRangeTest(
171617              p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
171618          );
171619        }else{
171620          windowCodeRangeTest(
171621              p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
171622          );
171623        }
171624      }else{
171625        windowCodeRangeTest(
171626            p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
171627        );
171628      }
171629    }else{
171630      sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1);
171631      VdbeCoverage(v);
171632    }
171633  }
171634
171635  if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
171636    windowAggFinal(p, 0);
171637  }
171638  addrContinue = sqlite3VdbeCurrentAddr(v);
171639
171640  /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or
171641  ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the
171642  ** start cursor does not advance past the end cursor within the
171643  ** temporary table. It otherwise might, if (a>b). Also ensure that,
171644  ** if the input cursor is still finding new rows, that the end
171645  ** cursor does not go past it to EOF. */
171646  if( pMWin->eStart==pMWin->eEnd && regCountdown
171647   && pMWin->eFrmType==TK_RANGE
171648  ){
171649    int regRowid1 = sqlite3GetTempReg(pParse);
171650    int regRowid2 = sqlite3GetTempReg(pParse);
171651    if( op==WINDOW_AGGINVERSE ){
171652      sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);
171653      sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);
171654      sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1);
171655      VdbeCoverage(v);
171656    }else if( p->regRowid ){
171657      sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid1);
171658      sqlite3VdbeAddOp3(v, OP_Ge, p->regRowid, lblDone, regRowid1);
171659      VdbeCoverageNeverNull(v);
171660    }
171661    sqlite3ReleaseTempReg(pParse, regRowid1);
171662    sqlite3ReleaseTempReg(pParse, regRowid2);
171663    assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING );
171664  }
171665
171666  switch( op ){
171667    case WINDOW_RETURN_ROW:
171668      csr = p->current.csr;
171669      reg = p->current.reg;
171670      windowReturnOneRow(p);
171671      break;
171672
171673    case WINDOW_AGGINVERSE:
171674      csr = p->start.csr;
171675      reg = p->start.reg;
171676      if( pMWin->regStartRowid ){
171677        assert( pMWin->regEndRowid );
171678        sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
171679      }else{
171680        windowAggStep(p, pMWin, csr, 1, p->regArg);
171681      }
171682      break;
171683
171684    default:
171685      assert( op==WINDOW_AGGSTEP );
171686      csr = p->end.csr;
171687      reg = p->end.reg;
171688      if( pMWin->regStartRowid ){
171689        assert( pMWin->regEndRowid );
171690        sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
171691      }else{
171692        windowAggStep(p, pMWin, csr, 0, p->regArg);
171693      }
171694      break;
171695  }
171696
171697  if( op==p->eDelete ){
171698    sqlite3VdbeAddOp1(v, OP_Delete, csr);
171699    sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
171700  }
171701
171702  if( jumpOnEof ){
171703    sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
171704    VdbeCoverage(v);
171705    ret = sqlite3VdbeAddOp0(v, OP_Goto);
171706  }else{
171707    sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
171708    VdbeCoverage(v);
171709    if( bPeer ){
171710      sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone);
171711    }
171712  }
171713
171714  if( bPeer ){
171715    int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
171716    int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
171717    windowReadPeerValues(p, csr, regTmp);
171718    windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
171719    sqlite3ReleaseTempRange(pParse, regTmp, nReg);
171720  }
171721
171722  if( addrNextRange ){
171723    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
171724  }
171725  sqlite3VdbeResolveLabel(v, lblDone);
171726  return ret;
171727}
171728
171729
171730/*
171731** Allocate and return a duplicate of the Window object indicated by the
171732** third argument. Set the Window.pOwner field of the new object to
171733** pOwner.
171734*/
171735SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
171736  Window *pNew = 0;
171737  if( ALWAYS(p) ){
171738    pNew = sqlite3DbMallocZero(db, sizeof(Window));
171739    if( pNew ){
171740      pNew->zName = sqlite3DbStrDup(db, p->zName);
171741      pNew->zBase = sqlite3DbStrDup(db, p->zBase);
171742      pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
171743      pNew->pWFunc = p->pWFunc;
171744      pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
171745      pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
171746      pNew->eFrmType = p->eFrmType;
171747      pNew->eEnd = p->eEnd;
171748      pNew->eStart = p->eStart;
171749      pNew->eExclude = p->eExclude;
171750      pNew->regResult = p->regResult;
171751      pNew->regAccum = p->regAccum;
171752      pNew->iArgCol = p->iArgCol;
171753      pNew->iEphCsr = p->iEphCsr;
171754      pNew->bExprArgs = p->bExprArgs;
171755      pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
171756      pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
171757      pNew->pOwner = pOwner;
171758      pNew->bImplicitFrame = p->bImplicitFrame;
171759    }
171760  }
171761  return pNew;
171762}
171763
171764/*
171765** Return a copy of the linked list of Window objects passed as the
171766** second argument.
171767*/
171768SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
171769  Window *pWin;
171770  Window *pRet = 0;
171771  Window **pp = &pRet;
171772
171773  for(pWin=p; pWin; pWin=pWin->pNextWin){
171774    *pp = sqlite3WindowDup(db, 0, pWin);
171775    if( *pp==0 ) break;
171776    pp = &((*pp)->pNextWin);
171777  }
171778
171779  return pRet;
171780}
171781
171782/*
171783** Return true if it can be determined at compile time that expression
171784** pExpr evaluates to a value that, when cast to an integer, is greater
171785** than zero. False otherwise.
171786**
171787** If an OOM error occurs, this function sets the Parse.db.mallocFailed
171788** flag and returns zero.
171789*/
171790static int windowExprGtZero(Parse *pParse, Expr *pExpr){
171791  int ret = 0;
171792  sqlite3 *db = pParse->db;
171793  sqlite3_value *pVal = 0;
171794  sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
171795  if( pVal && sqlite3_value_int(pVal)>0 ){
171796    ret = 1;
171797  }
171798  sqlite3ValueFree(pVal);
171799  return ret;
171800}
171801
171802/*
171803** sqlite3WhereBegin() has already been called for the SELECT statement
171804** passed as the second argument when this function is invoked. It generates
171805** code to populate the Window.regResult register for each window function
171806** and invoke the sub-routine at instruction addrGosub once for each row.
171807** sqlite3WhereEnd() is always called before returning.
171808**
171809** This function handles several different types of window frames, which
171810** require slightly different processing. The following pseudo code is
171811** used to implement window frames of the form:
171812**
171813**   ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
171814**
171815** Other window frame types use variants of the following:
171816**
171817**     ... loop started by sqlite3WhereBegin() ...
171818**       if( new partition ){
171819**         Gosub flush
171820**       }
171821**       Insert new row into eph table.
171822**
171823**       if( first row of partition ){
171824**         // Rewind three cursors, all open on the eph table.
171825**         Rewind(csrEnd);
171826**         Rewind(csrStart);
171827**         Rewind(csrCurrent);
171828**
171829**         regEnd = <expr2>          // FOLLOWING expression
171830**         regStart = <expr1>        // PRECEDING expression
171831**       }else{
171832**         // First time this branch is taken, the eph table contains two
171833**         // rows. The first row in the partition, which all three cursors
171834**         // currently point to, and the following row.
171835**         AGGSTEP
171836**         if( (regEnd--)<=0 ){
171837**           RETURN_ROW
171838**           if( (regStart--)<=0 ){
171839**             AGGINVERSE
171840**           }
171841**         }
171842**       }
171843**     }
171844**     flush:
171845**       AGGSTEP
171846**       while( 1 ){
171847**         RETURN ROW
171848**         if( csrCurrent is EOF ) break;
171849**         if( (regStart--)<=0 ){
171850**           AggInverse(csrStart)
171851**           Next(csrStart)
171852**         }
171853**       }
171854**
171855** The pseudo-code above uses the following shorthand:
171856**
171857**   AGGSTEP:    invoke the aggregate xStep() function for each window function
171858**               with arguments read from the current row of cursor csrEnd, then
171859**               step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
171860**
171861**   RETURN_ROW: return a row to the caller based on the contents of the
171862**               current row of csrCurrent and the current state of all
171863**               aggregates. Then step cursor csrCurrent forward one row.
171864**
171865**   AGGINVERSE: invoke the aggregate xInverse() function for each window
171866**               functions with arguments read from the current row of cursor
171867**               csrStart. Then step csrStart forward one row.
171868**
171869** There are two other ROWS window frames that are handled significantly
171870** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
171871** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
171872** cases because they change the order in which the three cursors (csrStart,
171873** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
171874** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
171875** three.
171876**
171877**   ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
171878**
171879**     ... loop started by sqlite3WhereBegin() ...
171880**       if( new partition ){
171881**         Gosub flush
171882**       }
171883**       Insert new row into eph table.
171884**       if( first row of partition ){
171885**         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
171886**         regEnd = <expr2>
171887**         regStart = <expr1>
171888**       }else{
171889**         if( (regEnd--)<=0 ){
171890**           AGGSTEP
171891**         }
171892**         RETURN_ROW
171893**         if( (regStart--)<=0 ){
171894**           AGGINVERSE
171895**         }
171896**       }
171897**     }
171898**     flush:
171899**       if( (regEnd--)<=0 ){
171900**         AGGSTEP
171901**       }
171902**       RETURN_ROW
171903**
171904**
171905**   ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
171906**
171907**     ... loop started by sqlite3WhereBegin() ...
171908**     if( new partition ){
171909**       Gosub flush
171910**     }
171911**     Insert new row into eph table.
171912**     if( first row of partition ){
171913**       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
171914**       regEnd = <expr2>
171915**       regStart = regEnd - <expr1>
171916**     }else{
171917**       AGGSTEP
171918**       if( (regEnd--)<=0 ){
171919**         RETURN_ROW
171920**       }
171921**       if( (regStart--)<=0 ){
171922**         AGGINVERSE
171923**       }
171924**     }
171925**   }
171926**   flush:
171927**     AGGSTEP
171928**     while( 1 ){
171929**       if( (regEnd--)<=0 ){
171930**         RETURN_ROW
171931**         if( eof ) break;
171932**       }
171933**       if( (regStart--)<=0 ){
171934**         AGGINVERSE
171935**         if( eof ) break
171936**       }
171937**     }
171938**     while( !eof csrCurrent ){
171939**       RETURN_ROW
171940**     }
171941**
171942** For the most part, the patterns above are adapted to support UNBOUNDED by
171943** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
171944** CURRENT ROW by assuming that it is equivalent to "0 PRECEDING/FOLLOWING".
171945** This is optimized of course - branches that will never be taken and
171946** conditions that are always true are omitted from the VM code. The only
171947** exceptional case is:
171948**
171949**   ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
171950**
171951**     ... loop started by sqlite3WhereBegin() ...
171952**     if( new partition ){
171953**       Gosub flush
171954**     }
171955**     Insert new row into eph table.
171956**     if( first row of partition ){
171957**       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
171958**       regStart = <expr1>
171959**     }else{
171960**       AGGSTEP
171961**     }
171962**   }
171963**   flush:
171964**     AGGSTEP
171965**     while( 1 ){
171966**       if( (regStart--)<=0 ){
171967**         AGGINVERSE
171968**         if( eof ) break
171969**       }
171970**       RETURN_ROW
171971**     }
171972**     while( !eof csrCurrent ){
171973**       RETURN_ROW
171974**     }
171975**
171976** Also requiring special handling are the cases:
171977**
171978**   ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
171979**   ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
171980**
171981** when (expr1 < expr2). This is detected at runtime, not by this function.
171982** To handle this case, the pseudo-code programs depicted above are modified
171983** slightly to be:
171984**
171985**     ... loop started by sqlite3WhereBegin() ...
171986**     if( new partition ){
171987**       Gosub flush
171988**     }
171989**     Insert new row into eph table.
171990**     if( first row of partition ){
171991**       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
171992**       regEnd = <expr2>
171993**       regStart = <expr1>
171994**       if( regEnd < regStart ){
171995**         RETURN_ROW
171996**         delete eph table contents
171997**         continue
171998**       }
171999**     ...
172000**
172001** The new "continue" statement in the above jumps to the next iteration
172002** of the outer loop - the one started by sqlite3WhereBegin().
172003**
172004** The various GROUPS cases are implemented using the same patterns as
172005** ROWS. The VM code is modified slightly so that:
172006**
172007**   1. The else branch in the main loop is only taken if the row just
172008**      added to the ephemeral table is the start of a new group. In
172009**      other words, it becomes:
172010**
172011**         ... loop started by sqlite3WhereBegin() ...
172012**         if( new partition ){
172013**           Gosub flush
172014**         }
172015**         Insert new row into eph table.
172016**         if( first row of partition ){
172017**           Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
172018**           regEnd = <expr2>
172019**           regStart = <expr1>
172020**         }else if( new group ){
172021**           ...
172022**         }
172023**       }
172024**
172025**   2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
172026**      AGGINVERSE step processes the current row of the relevant cursor and
172027**      all subsequent rows belonging to the same group.
172028**
172029** RANGE window frames are a little different again. As for GROUPS, the
172030** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
172031** deal in groups instead of rows. As for ROWS and GROUPS, there are three
172032** basic cases:
172033**
172034**   RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
172035**
172036**     ... loop started by sqlite3WhereBegin() ...
172037**       if( new partition ){
172038**         Gosub flush
172039**       }
172040**       Insert new row into eph table.
172041**       if( first row of partition ){
172042**         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
172043**         regEnd = <expr2>
172044**         regStart = <expr1>
172045**       }else{
172046**         AGGSTEP
172047**         while( (csrCurrent.key + regEnd) < csrEnd.key ){
172048**           RETURN_ROW
172049**           while( csrStart.key + regStart) < csrCurrent.key ){
172050**             AGGINVERSE
172051**           }
172052**         }
172053**       }
172054**     }
172055**     flush:
172056**       AGGSTEP
172057**       while( 1 ){
172058**         RETURN ROW
172059**         if( csrCurrent is EOF ) break;
172060**           while( csrStart.key + regStart) < csrCurrent.key ){
172061**             AGGINVERSE
172062**           }
172063**         }
172064**       }
172065**
172066** In the above notation, "csr.key" means the current value of the ORDER BY
172067** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
172068** or <expr PRECEDING) read from cursor csr.
172069**
172070**   RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
172071**
172072**     ... loop started by sqlite3WhereBegin() ...
172073**       if( new partition ){
172074**         Gosub flush
172075**       }
172076**       Insert new row into eph table.
172077**       if( first row of partition ){
172078**         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
172079**         regEnd = <expr2>
172080**         regStart = <expr1>
172081**       }else{
172082**         while( (csrEnd.key + regEnd) <= csrCurrent.key ){
172083**           AGGSTEP
172084**         }
172085**         while( (csrStart.key + regStart) < csrCurrent.key ){
172086**           AGGINVERSE
172087**         }
172088**         RETURN_ROW
172089**       }
172090**     }
172091**     flush:
172092**       while( (csrEnd.key + regEnd) <= csrCurrent.key ){
172093**         AGGSTEP
172094**       }
172095**       while( (csrStart.key + regStart) < csrCurrent.key ){
172096**         AGGINVERSE
172097**       }
172098**       RETURN_ROW
172099**
172100**   RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
172101**
172102**     ... loop started by sqlite3WhereBegin() ...
172103**       if( new partition ){
172104**         Gosub flush
172105**       }
172106**       Insert new row into eph table.
172107**       if( first row of partition ){
172108**         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
172109**         regEnd = <expr2>
172110**         regStart = <expr1>
172111**       }else{
172112**         AGGSTEP
172113**         while( (csrCurrent.key + regEnd) < csrEnd.key ){
172114**           while( (csrCurrent.key + regStart) > csrStart.key ){
172115**             AGGINVERSE
172116**           }
172117**           RETURN_ROW
172118**         }
172119**       }
172120**     }
172121**     flush:
172122**       AGGSTEP
172123**       while( 1 ){
172124**         while( (csrCurrent.key + regStart) > csrStart.key ){
172125**           AGGINVERSE
172126**           if( eof ) break "while( 1 )" loop.
172127**         }
172128**         RETURN_ROW
172129**       }
172130**       while( !eof csrCurrent ){
172131**         RETURN_ROW
172132**       }
172133**
172134** The text above leaves out many details. Refer to the code and comments
172135** below for a more complete picture.
172136*/
172137SQLITE_PRIVATE void sqlite3WindowCodeStep(
172138  Parse *pParse,                  /* Parse context */
172139  Select *p,                      /* Rewritten SELECT statement */
172140  WhereInfo *pWInfo,              /* Context returned by sqlite3WhereBegin() */
172141  int regGosub,                   /* Register for OP_Gosub */
172142  int addrGosub                   /* OP_Gosub here to return each row */
172143){
172144  Window *pMWin = p->pWin;
172145  ExprList *pOrderBy = pMWin->pOrderBy;
172146  Vdbe *v = sqlite3GetVdbe(pParse);
172147  int csrWrite;                   /* Cursor used to write to eph. table */
172148  int csrInput = p->pSrc->a[0].iCursor;     /* Cursor of sub-select */
172149  int nInput = p->pSrc->a[0].pTab->nCol;    /* Number of cols returned by sub */
172150  int iInput;                               /* To iterate through sub cols */
172151  int addrNe;                     /* Address of OP_Ne */
172152  int addrGosubFlush = 0;         /* Address of OP_Gosub to flush: */
172153  int addrInteger = 0;            /* Address of OP_Integer */
172154  int addrEmpty;                  /* Address of OP_Rewind in flush: */
172155  int regNew;                     /* Array of registers holding new input row */
172156  int regRecord;                  /* regNew array in record form */
172157  int regNewPeer = 0;             /* Peer values for new row (part of regNew) */
172158  int regPeer = 0;                /* Peer values for current row */
172159  int regFlushPart = 0;           /* Register for "Gosub flush_partition" */
172160  WindowCodeArg s;                /* Context object for sub-routines */
172161  int lblWhereEnd;                /* Label just before sqlite3WhereEnd() code */
172162  int regStart = 0;               /* Value of <expr> PRECEDING */
172163  int regEnd = 0;                 /* Value of <expr> FOLLOWING */
172164
172165  assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
172166       || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
172167  );
172168  assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
172169       || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
172170  );
172171  assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
172172       || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
172173       || pMWin->eExclude==TK_NO
172174  );
172175
172176  lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
172177
172178  /* Fill in the context object */
172179  memset(&s, 0, sizeof(WindowCodeArg));
172180  s.pParse = pParse;
172181  s.pMWin = pMWin;
172182  s.pVdbe = v;
172183  s.regGosub = regGosub;
172184  s.addrGosub = addrGosub;
172185  s.current.csr = pMWin->iEphCsr;
172186  csrWrite = s.current.csr+1;
172187  s.start.csr = s.current.csr+2;
172188  s.end.csr = s.current.csr+3;
172189
172190  /* Figure out when rows may be deleted from the ephemeral table. There
172191  ** are four options - they may never be deleted (eDelete==0), they may
172192  ** be deleted as soon as they are no longer part of the window frame
172193  ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
172194  ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
172195  ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
172196  switch( pMWin->eStart ){
172197    case TK_FOLLOWING:
172198      if( pMWin->eFrmType!=TK_RANGE
172199       && windowExprGtZero(pParse, pMWin->pStart)
172200      ){
172201        s.eDelete = WINDOW_RETURN_ROW;
172202      }
172203      break;
172204    case TK_UNBOUNDED:
172205      if( windowCacheFrame(pMWin)==0 ){
172206        if( pMWin->eEnd==TK_PRECEDING ){
172207          if( pMWin->eFrmType!=TK_RANGE
172208           && windowExprGtZero(pParse, pMWin->pEnd)
172209          ){
172210            s.eDelete = WINDOW_AGGSTEP;
172211          }
172212        }else{
172213          s.eDelete = WINDOW_RETURN_ROW;
172214        }
172215      }
172216      break;
172217    default:
172218      s.eDelete = WINDOW_AGGINVERSE;
172219      break;
172220  }
172221
172222  /* Allocate registers for the array of values from the sub-query, the
172223  ** same values in record form, and the rowid used to insert said record
172224  ** into the ephemeral table.  */
172225  regNew = pParse->nMem+1;
172226  pParse->nMem += nInput;
172227  regRecord = ++pParse->nMem;
172228  s.regRowid = ++pParse->nMem;
172229
172230  /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
172231  ** clause, allocate registers to store the results of evaluating each
172232  ** <expr>.  */
172233  if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
172234    regStart = ++pParse->nMem;
172235  }
172236  if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
172237    regEnd = ++pParse->nMem;
172238  }
172239
172240  /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
172241  ** registers to store copies of the ORDER BY expressions (peer values)
172242  ** for the main loop, and for each cursor (start, current and end). */
172243  if( pMWin->eFrmType!=TK_ROWS ){
172244    int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
172245    regNewPeer = regNew + pMWin->nBufferCol;
172246    if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
172247    regPeer = pParse->nMem+1;       pParse->nMem += nPeer;
172248    s.start.reg = pParse->nMem+1;   pParse->nMem += nPeer;
172249    s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
172250    s.end.reg = pParse->nMem+1;     pParse->nMem += nPeer;
172251  }
172252
172253  /* Load the column values for the row returned by the sub-select
172254  ** into an array of registers starting at regNew. Assemble them into
172255  ** a record in register regRecord. */
172256  for(iInput=0; iInput<nInput; iInput++){
172257    sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
172258  }
172259  sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
172260
172261  /* An input row has just been read into an array of registers starting
172262  ** at regNew. If the window has a PARTITION clause, this block generates
172263  ** VM code to check if the input row is the start of a new partition.
172264  ** If so, it does an OP_Gosub to an address to be filled in later. The
172265  ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
172266  if( pMWin->pPartition ){
172267    int addr;
172268    ExprList *pPart = pMWin->pPartition;
172269    int nPart = pPart->nExpr;
172270    int regNewPart = regNew + pMWin->nBufferCol;
172271    KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
172272
172273    regFlushPart = ++pParse->nMem;
172274    addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
172275    sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
172276    sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
172277    VdbeCoverageEqNe(v);
172278    addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
172279    VdbeComment((v, "call flush_partition"));
172280    sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
172281  }
172282
172283  /* Insert the new row into the ephemeral table */
172284  sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, s.regRowid);
172285  sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, s.regRowid);
172286  addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, s.regRowid);
172287  VdbeCoverageNeverNull(v);
172288
172289  /* This block is run for the first row of each partition */
172290  s.regArg = windowInitAccum(pParse, pMWin);
172291
172292  if( regStart ){
172293    sqlite3ExprCode(pParse, pMWin->pStart, regStart);
172294    windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0));
172295  }
172296  if( regEnd ){
172297    sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
172298    windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0));
172299  }
172300
172301  if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){
172302    int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
172303    int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
172304    VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
172305    VdbeCoverageNeverNullIf(v, op==OP_Le); /*   values previously checked */
172306    windowAggFinal(&s, 0);
172307    sqlite3VdbeAddOp1(v, OP_Rewind, s.current.csr);
172308    windowReturnOneRow(&s);
172309    sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
172310    sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
172311    sqlite3VdbeJumpHere(v, addrGe);
172312  }
172313  if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
172314    assert( pMWin->eEnd==TK_FOLLOWING );
172315    sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
172316  }
172317
172318  if( pMWin->eStart!=TK_UNBOUNDED ){
172319    sqlite3VdbeAddOp1(v, OP_Rewind, s.start.csr);
172320  }
172321  sqlite3VdbeAddOp1(v, OP_Rewind, s.current.csr);
172322  sqlite3VdbeAddOp1(v, OP_Rewind, s.end.csr);
172323  if( regPeer && pOrderBy ){
172324    sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
172325    sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
172326    sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
172327    sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
172328  }
172329
172330  sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
172331
172332  sqlite3VdbeJumpHere(v, addrNe);
172333
172334  /* Beginning of the block executed for the second and subsequent rows. */
172335  if( regPeer ){
172336    windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
172337  }
172338  if( pMWin->eStart==TK_FOLLOWING ){
172339    windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
172340    if( pMWin->eEnd!=TK_UNBOUNDED ){
172341      if( pMWin->eFrmType==TK_RANGE ){
172342        int lbl = sqlite3VdbeMakeLabel(pParse);
172343        int addrNext = sqlite3VdbeCurrentAddr(v);
172344        windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
172345        windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
172346        windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
172347        sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
172348        sqlite3VdbeResolveLabel(v, lbl);
172349      }else{
172350        windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
172351        windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
172352      }
172353    }
172354  }else
172355  if( pMWin->eEnd==TK_PRECEDING ){
172356    int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
172357    windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
172358    if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
172359    windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
172360    if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
172361  }else{
172362    int addr = 0;
172363    windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
172364    if( pMWin->eEnd!=TK_UNBOUNDED ){
172365      if( pMWin->eFrmType==TK_RANGE ){
172366        int lbl = 0;
172367        addr = sqlite3VdbeCurrentAddr(v);
172368        if( regEnd ){
172369          lbl = sqlite3VdbeMakeLabel(pParse);
172370          windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
172371        }
172372        windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
172373        windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
172374        if( regEnd ){
172375          sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
172376          sqlite3VdbeResolveLabel(v, lbl);
172377        }
172378      }else{
172379        if( regEnd ){
172380          addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
172381          VdbeCoverage(v);
172382        }
172383        windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
172384        windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
172385        if( regEnd ) sqlite3VdbeJumpHere(v, addr);
172386      }
172387    }
172388  }
172389
172390  /* End of the main input loop */
172391  sqlite3VdbeResolveLabel(v, lblWhereEnd);
172392  sqlite3WhereEnd(pWInfo);
172393
172394  /* Fall through */
172395  if( pMWin->pPartition ){
172396    addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
172397    sqlite3VdbeJumpHere(v, addrGosubFlush);
172398  }
172399
172400  s.regRowid = 0;
172401  addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
172402  VdbeCoverage(v);
172403  if( pMWin->eEnd==TK_PRECEDING ){
172404    int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
172405    windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
172406    if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
172407    windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
172408  }else if( pMWin->eStart==TK_FOLLOWING ){
172409    int addrStart;
172410    int addrBreak1;
172411    int addrBreak2;
172412    int addrBreak3;
172413    windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
172414    if( pMWin->eFrmType==TK_RANGE ){
172415      addrStart = sqlite3VdbeCurrentAddr(v);
172416      addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
172417      addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
172418    }else
172419    if( pMWin->eEnd==TK_UNBOUNDED ){
172420      addrStart = sqlite3VdbeCurrentAddr(v);
172421      addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
172422      addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
172423    }else{
172424      assert( pMWin->eEnd==TK_FOLLOWING );
172425      addrStart = sqlite3VdbeCurrentAddr(v);
172426      addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
172427      addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
172428    }
172429    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
172430    sqlite3VdbeJumpHere(v, addrBreak2);
172431    addrStart = sqlite3VdbeCurrentAddr(v);
172432    addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
172433    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
172434    sqlite3VdbeJumpHere(v, addrBreak1);
172435    sqlite3VdbeJumpHere(v, addrBreak3);
172436  }else{
172437    int addrBreak;
172438    int addrStart;
172439    windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
172440    addrStart = sqlite3VdbeCurrentAddr(v);
172441    addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
172442    windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
172443    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
172444    sqlite3VdbeJumpHere(v, addrBreak);
172445  }
172446  sqlite3VdbeJumpHere(v, addrEmpty);
172447
172448  sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
172449  if( pMWin->pPartition ){
172450    if( pMWin->regStartRowid ){
172451      sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
172452      sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
172453    }
172454    sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
172455    sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
172456  }
172457}
172458
172459#endif /* SQLITE_OMIT_WINDOWFUNC */
172460
172461/************** End of window.c **********************************************/
172462/************** Begin file parse.c *******************************************/
172463/* This file is automatically generated by Lemon from input grammar
172464** source file "parse.y".
172465*/
172466/*
172467** 2001-09-15
172468**
172469** The author disclaims copyright to this source code.  In place of
172470** a legal notice, here is a blessing:
172471**
172472**    May you do good and not evil.
172473**    May you find forgiveness for yourself and forgive others.
172474**    May you share freely, never taking more than you give.
172475**
172476*************************************************************************
172477** This file contains SQLite's SQL parser.
172478**
172479** The canonical source code to this file ("parse.y") is a Lemon grammar
172480** file that specifies the input grammar and actions to take while parsing.
172481** That input file is processed by Lemon to generate a C-language
172482** implementation of a parser for the given grammar.  You might be reading
172483** this comment as part of the translated C-code.  Edits should be made
172484** to the original parse.y sources.
172485*/
172486
172487/* #include "sqliteInt.h" */
172488
172489/*
172490** Disable all error recovery processing in the parser push-down
172491** automaton.
172492*/
172493#define YYNOERRORRECOVERY 1
172494
172495/*
172496** Make yytestcase() the same as testcase()
172497*/
172498#define yytestcase(X) testcase(X)
172499
172500/*
172501** Indicate that sqlite3ParserFree() will never be called with a null
172502** pointer.
172503*/
172504#define YYPARSEFREENEVERNULL 1
172505
172506/*
172507** In the amalgamation, the parse.c file generated by lemon and the
172508** tokenize.c file are concatenated.  In that case, sqlite3RunParser()
172509** has access to the the size of the yyParser object and so the parser
172510** engine can be allocated from stack.  In that case, only the
172511** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
172512** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
172513** omitted.
172514*/
172515#ifdef SQLITE_AMALGAMATION
172516# define sqlite3Parser_ENGINEALWAYSONSTACK 1
172517#endif
172518
172519/*
172520** Alternative datatype for the argument to the malloc() routine passed
172521** into sqlite3ParserAlloc().  The default is size_t.
172522*/
172523#define YYMALLOCARGTYPE  u64
172524
172525/*
172526** An instance of the following structure describes the event of a
172527** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
172528** TK_DELETE, or TK_INSTEAD.  If the event is of the form
172529**
172530**      UPDATE ON (a,b,c)
172531**
172532** Then the "b" IdList records the list "a,b,c".
172533*/
172534struct TrigEvent { int a; IdList * b; };
172535
172536struct FrameBound     { int eType; Expr *pExpr; };
172537
172538/*
172539** Disable lookaside memory allocation for objects that might be
172540** shared across database connections.
172541*/
172542static void disableLookaside(Parse *pParse){
172543  sqlite3 *db = pParse->db;
172544  pParse->disableLookaside++;
172545  DisableLookaside;
172546}
172547
172548#if !defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) \
172549 && defined(SQLITE_UDL_CAPABLE_PARSER)
172550/*
172551** Issue an error message if an ORDER BY or LIMIT clause occurs on an
172552** UPDATE or DELETE statement.
172553*/
172554static void updateDeleteLimitError(
172555  Parse *pParse,
172556  ExprList *pOrderBy,
172557  Expr *pLimit
172558){
172559  if( pOrderBy ){
172560    sqlite3ErrorMsg(pParse, "syntax error near \"ORDER BY\"");
172561  }else{
172562    sqlite3ErrorMsg(pParse, "syntax error near \"LIMIT\"");
172563  }
172564  sqlite3ExprListDelete(pParse->db, pOrderBy);
172565  sqlite3ExprDelete(pParse->db, pLimit);
172566}
172567#endif /* SQLITE_ENABLE_UPDATE_DELETE_LIMIT */
172568
172569
172570  /*
172571  ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
172572  ** all elements in the list.  And make sure list length does not exceed
172573  ** SQLITE_LIMIT_COMPOUND_SELECT.
172574  */
172575  static void parserDoubleLinkSelect(Parse *pParse, Select *p){
172576    assert( p!=0 );
172577    if( p->pPrior ){
172578      Select *pNext = 0, *pLoop = p;
172579      int mxSelect, cnt = 1;
172580      while(1){
172581        pLoop->pNext = pNext;
172582        pLoop->selFlags |= SF_Compound;
172583        pNext = pLoop;
172584        pLoop = pLoop->pPrior;
172585        if( pLoop==0 ) break;
172586        cnt++;
172587        if( pLoop->pOrderBy || pLoop->pLimit ){
172588          sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
172589             pLoop->pOrderBy!=0 ? "ORDER BY" : "LIMIT",
172590             sqlite3SelectOpName(pNext->op));
172591          break;
172592        }
172593      }
172594      if( (p->selFlags & SF_MultiValue)==0 &&
172595        (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
172596        cnt>mxSelect
172597      ){
172598        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
172599      }
172600    }
172601  }
172602
172603  /* Attach a With object describing the WITH clause to a Select
172604  ** object describing the query for which the WITH clause is a prefix.
172605  */
172606  static Select *attachWithToSelect(Parse *pParse, Select *pSelect, With *pWith){
172607    if( pSelect ){
172608      pSelect->pWith = pWith;
172609      parserDoubleLinkSelect(pParse, pSelect);
172610    }else{
172611      sqlite3WithDelete(pParse->db, pWith);
172612    }
172613    return pSelect;
172614  }
172615
172616  /* Memory allocator for parser stack resizing.  This is a thin wrapper around
172617  ** sqlite3_realloc() that includes a call to sqlite3FaultSim() to facilitate
172618  ** testing.
172619  */
172620  static void *parserStackRealloc(void *pOld, sqlite3_uint64 newSize){
172621    return sqlite3FaultSim(700) ? 0 : sqlite3_realloc(pOld, newSize);
172622  }
172623
172624
172625  /* Construct a new Expr object from a single token */
172626  static Expr *tokenExpr(Parse *pParse, int op, Token t){
172627    Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
172628    if( p ){
172629      /* memset(p, 0, sizeof(Expr)); */
172630      p->op = (u8)op;
172631      p->affExpr = 0;
172632      p->flags = EP_Leaf;
172633      ExprClearVVAProperties(p);
172634      /* p->iAgg = -1; // Not required */
172635      p->pLeft = p->pRight = 0;
172636      p->pAggInfo = 0;
172637      memset(&p->x, 0, sizeof(p->x));
172638      memset(&p->y, 0, sizeof(p->y));
172639      p->op2 = 0;
172640      p->iTable = 0;
172641      p->iColumn = 0;
172642      p->u.zToken = (char*)&p[1];
172643      memcpy(p->u.zToken, t.z, t.n);
172644      p->u.zToken[t.n] = 0;
172645      p->w.iOfst = (int)(t.z - pParse->zTail);
172646      if( sqlite3Isquote(p->u.zToken[0]) ){
172647        sqlite3DequoteExpr(p);
172648      }
172649#if SQLITE_MAX_EXPR_DEPTH>0
172650      p->nHeight = 1;
172651#endif
172652      if( IN_RENAME_OBJECT ){
172653        return (Expr*)sqlite3RenameTokenMap(pParse, (void*)p, &t);
172654      }
172655    }
172656    return p;
172657  }
172658
172659
172660  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
172661  ** unary TK_ISNULL or TK_NOTNULL expression. */
172662  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
172663    sqlite3 *db = pParse->db;
172664    if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){
172665      pA->op = (u8)op;
172666      sqlite3ExprDelete(db, pA->pRight);
172667      pA->pRight = 0;
172668    }
172669  }
172670
172671  /* Add a single new term to an ExprList that is used to store a
172672  ** list of identifiers.  Report an error if the ID list contains
172673  ** a COLLATE clause or an ASC or DESC keyword, except ignore the
172674  ** error while parsing a legacy schema.
172675  */
172676  static ExprList *parserAddExprIdListTerm(
172677    Parse *pParse,
172678    ExprList *pPrior,
172679    Token *pIdToken,
172680    int hasCollate,
172681    int sortOrder
172682  ){
172683    ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
172684    if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
172685        && pParse->db->init.busy==0
172686    ){
172687      sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
172688                         pIdToken->n, pIdToken->z);
172689    }
172690    sqlite3ExprListSetName(pParse, p, pIdToken, 1);
172691    return p;
172692  }
172693
172694#if TK_SPAN>255
172695# error too many tokens in the grammar
172696#endif
172697/**************** End of %include directives **********************************/
172698/* These constants specify the various numeric values for terminal symbols.
172699***************** Begin token definitions *************************************/
172700#ifndef TK_SEMI
172701#define TK_SEMI                            1
172702#define TK_EXPLAIN                         2
172703#define TK_QUERY                           3
172704#define TK_PLAN                            4
172705#define TK_BEGIN                           5
172706#define TK_TRANSACTION                     6
172707#define TK_DEFERRED                        7
172708#define TK_IMMEDIATE                       8
172709#define TK_EXCLUSIVE                       9
172710#define TK_COMMIT                         10
172711#define TK_END                            11
172712#define TK_ROLLBACK                       12
172713#define TK_SAVEPOINT                      13
172714#define TK_RELEASE                        14
172715#define TK_TO                             15
172716#define TK_TABLE                          16
172717#define TK_CREATE                         17
172718#define TK_IF                             18
172719#define TK_NOT                            19
172720#define TK_EXISTS                         20
172721#define TK_TEMP                           21
172722#define TK_LP                             22
172723#define TK_RP                             23
172724#define TK_AS                             24
172725#define TK_COMMA                          25
172726#define TK_WITHOUT                        26
172727#define TK_ABORT                          27
172728#define TK_ACTION                         28
172729#define TK_AFTER                          29
172730#define TK_ANALYZE                        30
172731#define TK_ASC                            31
172732#define TK_ATTACH                         32
172733#define TK_BEFORE                         33
172734#define TK_BY                             34
172735#define TK_CASCADE                        35
172736#define TK_CAST                           36
172737#define TK_CONFLICT                       37
172738#define TK_DATABASE                       38
172739#define TK_DESC                           39
172740#define TK_DETACH                         40
172741#define TK_EACH                           41
172742#define TK_FAIL                           42
172743#define TK_OR                             43
172744#define TK_AND                            44
172745#define TK_IS                             45
172746#define TK_MATCH                          46
172747#define TK_LIKE_KW                        47
172748#define TK_BETWEEN                        48
172749#define TK_IN                             49
172750#define TK_ISNULL                         50
172751#define TK_NOTNULL                        51
172752#define TK_NE                             52
172753#define TK_EQ                             53
172754#define TK_GT                             54
172755#define TK_LE                             55
172756#define TK_LT                             56
172757#define TK_GE                             57
172758#define TK_ESCAPE                         58
172759#define TK_ID                             59
172760#define TK_COLUMNKW                       60
172761#define TK_DO                             61
172762#define TK_FOR                            62
172763#define TK_IGNORE                         63
172764#define TK_INITIALLY                      64
172765#define TK_INSTEAD                        65
172766#define TK_NO                             66
172767#define TK_KEY                            67
172768#define TK_OF                             68
172769#define TK_OFFSET                         69
172770#define TK_PRAGMA                         70
172771#define TK_RAISE                          71
172772#define TK_RECURSIVE                      72
172773#define TK_REPLACE                        73
172774#define TK_RESTRICT                       74
172775#define TK_ROW                            75
172776#define TK_ROWS                           76
172777#define TK_TRIGGER                        77
172778#define TK_VACUUM                         78
172779#define TK_VIEW                           79
172780#define TK_VIRTUAL                        80
172781#define TK_WITH                           81
172782#define TK_NULLS                          82
172783#define TK_FIRST                          83
172784#define TK_LAST                           84
172785#define TK_CURRENT                        85
172786#define TK_FOLLOWING                      86
172787#define TK_PARTITION                      87
172788#define TK_PRECEDING                      88
172789#define TK_RANGE                          89
172790#define TK_UNBOUNDED                      90
172791#define TK_EXCLUDE                        91
172792#define TK_GROUPS                         92
172793#define TK_OTHERS                         93
172794#define TK_TIES                           94
172795#define TK_GENERATED                      95
172796#define TK_ALWAYS                         96
172797#define TK_MATERIALIZED                   97
172798#define TK_REINDEX                        98
172799#define TK_RENAME                         99
172800#define TK_CTIME_KW                       100
172801#define TK_ANY                            101
172802#define TK_BITAND                         102
172803#define TK_BITOR                          103
172804#define TK_LSHIFT                         104
172805#define TK_RSHIFT                         105
172806#define TK_PLUS                           106
172807#define TK_MINUS                          107
172808#define TK_STAR                           108
172809#define TK_SLASH                          109
172810#define TK_REM                            110
172811#define TK_CONCAT                         111
172812#define TK_PTR                            112
172813#define TK_COLLATE                        113
172814#define TK_BITNOT                         114
172815#define TK_ON                             115
172816#define TK_INDEXED                        116
172817#define TK_STRING                         117
172818#define TK_JOIN_KW                        118
172819#define TK_CONSTRAINT                     119
172820#define TK_DEFAULT                        120
172821#define TK_NULL                           121
172822#define TK_PRIMARY                        122
172823#define TK_UNIQUE                         123
172824#define TK_CHECK                          124
172825#define TK_REFERENCES                     125
172826#define TK_AUTOINCR                       126
172827#define TK_INSERT                         127
172828#define TK_DELETE                         128
172829#define TK_UPDATE                         129
172830#define TK_SET                            130
172831#define TK_DEFERRABLE                     131
172832#define TK_FOREIGN                        132
172833#define TK_DROP                           133
172834#define TK_UNION                          134
172835#define TK_ALL                            135
172836#define TK_EXCEPT                         136
172837#define TK_INTERSECT                      137
172838#define TK_SELECT                         138
172839#define TK_VALUES                         139
172840#define TK_DISTINCT                       140
172841#define TK_DOT                            141
172842#define TK_FROM                           142
172843#define TK_JOIN                           143
172844#define TK_USING                          144
172845#define TK_ORDER                          145
172846#define TK_GROUP                          146
172847#define TK_HAVING                         147
172848#define TK_LIMIT                          148
172849#define TK_WHERE                          149
172850#define TK_RETURNING                      150
172851#define TK_INTO                           151
172852#define TK_NOTHING                        152
172853#define TK_FLOAT                          153
172854#define TK_BLOB                           154
172855#define TK_INTEGER                        155
172856#define TK_VARIABLE                       156
172857#define TK_CASE                           157
172858#define TK_WHEN                           158
172859#define TK_THEN                           159
172860#define TK_ELSE                           160
172861#define TK_INDEX                          161
172862#define TK_ALTER                          162
172863#define TK_ADD                            163
172864#define TK_WINDOW                         164
172865#define TK_OVER                           165
172866#define TK_FILTER                         166
172867#define TK_COLUMN                         167
172868#define TK_AGG_FUNCTION                   168
172869#define TK_AGG_COLUMN                     169
172870#define TK_TRUEFALSE                      170
172871#define TK_ISNOT                          171
172872#define TK_FUNCTION                       172
172873#define TK_UPLUS                          173
172874#define TK_UMINUS                         174
172875#define TK_TRUTH                          175
172876#define TK_REGISTER                       176
172877#define TK_VECTOR                         177
172878#define TK_SELECT_COLUMN                  178
172879#define TK_IF_NULL_ROW                    179
172880#define TK_ASTERISK                       180
172881#define TK_SPAN                           181
172882#define TK_ERROR                          182
172883#define TK_QNUMBER                        183
172884#define TK_SPACE                          184
172885#define TK_ILLEGAL                        185
172886#endif
172887/**************** End token definitions ***************************************/
172888
172889/* The next sections is a series of control #defines.
172890** various aspects of the generated parser.
172891**    YYCODETYPE         is the data type used to store the integer codes
172892**                       that represent terminal and non-terminal symbols.
172893**                       "unsigned char" is used if there are fewer than
172894**                       256 symbols.  Larger types otherwise.
172895**    YYNOCODE           is a number of type YYCODETYPE that is not used for
172896**                       any terminal or nonterminal symbol.
172897**    YYFALLBACK         If defined, this indicates that one or more tokens
172898**                       (also known as: "terminal symbols") have fall-back
172899**                       values which should be used if the original symbol
172900**                       would not parse.  This permits keywords to sometimes
172901**                       be used as identifiers, for example.
172902**    YYACTIONTYPE       is the data type used for "action codes" - numbers
172903**                       that indicate what to do in response to the next
172904**                       token.
172905**    sqlite3ParserTOKENTYPE     is the data type used for minor type for terminal
172906**                       symbols.  Background: A "minor type" is a semantic
172907**                       value associated with a terminal or non-terminal
172908**                       symbols.  For example, for an "ID" terminal symbol,
172909**                       the minor type might be the name of the identifier.
172910**                       Each non-terminal can have a different minor type.
172911**                       Terminal symbols all have the same minor type, though.
172912**                       This macros defines the minor type for terminal
172913**                       symbols.
172914**    YYMINORTYPE        is the data type used for all minor types.
172915**                       This is typically a union of many types, one of
172916**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
172917**                       for terminal symbols is called "yy0".
172918**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
172919**                       zero the stack is dynamically sized using realloc()
172920**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
172921**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
172922**    sqlite3ParserARG_PARAM     Code to pass %extra_argument as a subroutine parameter
172923**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
172924**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
172925**    sqlite3ParserCTX_*         As sqlite3ParserARG_ except for %extra_context
172926**    YYREALLOC          Name of the realloc() function to use
172927**    YYFREE             Name of the free() function to use
172928**    YYDYNSTACK         True if stack space should be extended on heap
172929**    YYERRORSYMBOL      is the code number of the error symbol.  If not
172930**                       defined, then do no error processing.
172931**    YYNSTATE           the combined number of states.
172932**    YYNRULE            the number of rules in the grammar
172933**    YYNTOKEN           Number of terminal symbols
172934**    YY_MAX_SHIFT       Maximum value for shift actions
172935**    YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
172936**    YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
172937**    YY_ERROR_ACTION    The yy_action[] code for syntax error
172938**    YY_ACCEPT_ACTION   The yy_action[] code for accept
172939**    YY_NO_ACTION       The yy_action[] code for no-op
172940**    YY_MIN_REDUCE      Minimum value for reduce actions
172941**    YY_MAX_REDUCE      Maximum value for reduce actions
172942**    YY_MIN_DSTRCTR     Minimum symbol value that has a destructor
172943**    YY_MAX_DSTRCTR     Maximum symbol value that has a destructor
172944*/
172945#ifndef INTERFACE
172946# define INTERFACE 1
172947#endif
172948/************* Begin control #defines *****************************************/
172949#define YYCODETYPE unsigned short int
172950#define YYNOCODE 322
172951#define YYACTIONTYPE unsigned short int
172952#define YYWILDCARD 101
172953#define sqlite3ParserTOKENTYPE Token
172954typedef union {
172955  int yyinit;
172956  sqlite3ParserTOKENTYPE yy0;
172957  ExprList* yy14;
172958  With* yy59;
172959  Cte* yy67;
172960  Upsert* yy122;
172961  IdList* yy132;
172962  int yy144;
172963  const char* yy168;
172964  SrcList* yy203;
172965  Window* yy211;
172966  OnOrUsing yy269;
172967  struct TrigEvent yy286;
172968  struct {int value; int mask;} yy383;
172969  u32 yy391;
172970  TriggerStep* yy427;
172971  Expr* yy454;
172972  u8 yy462;
172973  struct FrameBound yy509;
172974  Select* yy555;
172975} YYMINORTYPE;
172976#ifndef YYSTACKDEPTH
172977#define YYSTACKDEPTH 100
172978#endif
172979#define sqlite3ParserARG_SDECL
172980#define sqlite3ParserARG_PDECL
172981#define sqlite3ParserARG_PARAM
172982#define sqlite3ParserARG_FETCH
172983#define sqlite3ParserARG_STORE
172984#define YYREALLOC parserStackRealloc
172985#define YYFREE sqlite3_free
172986#define YYDYNSTACK 1
172987#define sqlite3ParserCTX_SDECL Parse *pParse;
172988#define sqlite3ParserCTX_PDECL ,Parse *pParse
172989#define sqlite3ParserCTX_PARAM ,pParse
172990#define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
172991#define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
172992#define YYFALLBACK 1
172993#define YYNSTATE             583
172994#define YYNRULE              409
172995#define YYNRULE_WITH_ACTION  344
172996#define YYNTOKEN             186
172997#define YY_MAX_SHIFT         582
172998#define YY_MIN_SHIFTREDUCE   845
172999#define YY_MAX_SHIFTREDUCE   1253
173000#define YY_ERROR_ACTION      1254
173001#define YY_ACCEPT_ACTION     1255
173002#define YY_NO_ACTION         1256
173003#define YY_MIN_REDUCE        1257
173004#define YY_MAX_REDUCE        1665
173005#define YY_MIN_DSTRCTR       205
173006#define YY_MAX_DSTRCTR       319
173007/************* End control #defines *******************************************/
173008#define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))
173009
173010/* Define the yytestcase() macro to be a no-op if is not already defined
173011** otherwise.
173012**
173013** Applications can choose to define yytestcase() in the %include section
173014** to a macro that can assist in verifying code coverage.  For production
173015** code the yytestcase() macro should be turned off.  But it is useful
173016** for testing.
173017*/
173018#ifndef yytestcase
173019# define yytestcase(X)
173020#endif
173021
173022/* Macro to determine if stack space has the ability to grow using
173023** heap memory.
173024*/
173025#if YYSTACKDEPTH<=0 || YYDYNSTACK
173026# define YYGROWABLESTACK 1
173027#else
173028# define YYGROWABLESTACK 0
173029#endif
173030
173031/* Guarantee a minimum number of initial stack slots.
173032*/
173033#if YYSTACKDEPTH<=0
173034# undef YYSTACKDEPTH
173035# define YYSTACKDEPTH 2  /* Need a minimum stack size */
173036#endif
173037
173038
173039/* Next are the tables used to determine what action to take based on the
173040** current state and lookahead token.  These tables are used to implement
173041** functions that take a state number and lookahead value and return an
173042** action integer.
173043**
173044** Suppose the action integer is N.  Then the action is determined as
173045** follows
173046**
173047**   0 <= N <= YY_MAX_SHIFT             Shift N.  That is, push the lookahead
173048**                                      token onto the stack and goto state N.
173049**
173050**   N between YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
173051**     and YY_MAX_SHIFTREDUCE           reduce by rule N-YY_MIN_SHIFTREDUCE.
173052**
173053**   N == YY_ERROR_ACTION               A syntax error has occurred.
173054**
173055**   N == YY_ACCEPT_ACTION              The parser accepts its input.
173056**
173057**   N == YY_NO_ACTION                  No such action.  Denotes unused
173058**                                      slots in the yy_action[] table.
173059**
173060**   N between YY_MIN_REDUCE            Reduce by rule N-YY_MIN_REDUCE
173061**     and YY_MAX_REDUCE
173062**
173063** The action table is constructed as a single large table named yy_action[].
173064** Given state S and lookahead X, the action is computed as either:
173065**
173066**    (A)   N = yy_action[ yy_shift_ofst[S] + X ]
173067**    (B)   N = yy_default[S]
173068**
173069** The (A) formula is preferred.  The B formula is used instead if
173070** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X.
173071**
173072** The formulas above are for computing the action when the lookahead is
173073** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
173074** a reduce action) then the yy_reduce_ofst[] array is used in place of
173075** the yy_shift_ofst[] array.
173076**
173077** The following are the tables generated in this section:
173078**
173079**  yy_action[]        A single table containing all actions.
173080**  yy_lookahead[]     A table containing the lookahead for each entry in
173081**                     yy_action.  Used to detect hash collisions.
173082**  yy_shift_ofst[]    For each state, the offset into yy_action for
173083**                     shifting terminals.
173084**  yy_reduce_ofst[]   For each state, the offset into yy_action for
173085**                     shifting non-terminals after a reduce.
173086**  yy_default[]       Default action for each state.
173087**
173088*********** Begin parsing tables **********************************************/
173089#define YY_ACTTAB_COUNT (2142)
173090static const YYACTIONTYPE yy_action[] = {
173091 /*     0 */   576,  128,  125,  232, 1622,  549,  576, 1290, 1281,  576,
173092 /*    10 */   328,  576, 1300,  212,  576,  128,  125,  232,  578,  412,
173093 /*    20 */   578,  391, 1542,   51,   51,  523,  405, 1293,  529,   51,
173094 /*    30 */    51,  983,   51,   51,   81,   81, 1107,   61,   61,  984,
173095 /*    40 */  1107, 1292,  380,  135,  136,   90, 1228, 1228, 1063, 1066,
173096 /*    50 */  1053, 1053,  133,  133,  134,  134,  134,  134, 1577,  412,
173097 /*    60 */   287,  287,    7,  287,  287,  422, 1050, 1050, 1064, 1067,
173098 /*    70 */   289,  556,  492,  573,  524,  561,  573,  497,  561,  482,
173099 /*    80 */   530,  262,  229,  135,  136,   90, 1228, 1228, 1063, 1066,
173100 /*    90 */  1053, 1053,  133,  133,  134,  134,  134,  134,  128,  125,
173101 /*   100 */   232, 1506,  132,  132,  132,  132,  131,  131,  130,  130,
173102 /*   110 */   130,  129,  126,  450, 1204, 1255,    1,    1,  582,    2,
173103 /*   120 */  1259, 1571,  420, 1582,  379,  320, 1174,  153, 1174, 1584,
173104 /*   130 */   412,  378, 1582,  543, 1341,  330,  111,  570,  570,  570,
173105 /*   140 */   293, 1054,  132,  132,  132,  132,  131,  131,  130,  130,
173106 /*   150 */   130,  129,  126,  450,  135,  136,   90, 1228, 1228, 1063,
173107 /*   160 */  1066, 1053, 1053,  133,  133,  134,  134,  134,  134,  287,
173108 /*   170 */   287, 1204, 1205, 1204,  255,  287,  287,  510,  507,  506,
173109 /*   180 */   137,  455,  573,  212,  561,  447,  446,  505,  573, 1616,
173110 /*   190 */   561,  134,  134,  134,  134,  127,  400,  243,  132,  132,
173111 /*   200 */   132,  132,  131,  131,  130,  130,  130,  129,  126,  450,
173112 /*   210 */   282,  471,  345,  132,  132,  132,  132,  131,  131,  130,
173113 /*   220 */   130,  130,  129,  126,  450,  574,  155,  936,  936,  454,
173114 /*   230 */   227,  521, 1236,  412, 1236,  134,  134,  134,  134,  132,
173115 /*   240 */   132,  132,  132,  131,  131,  130,  130,  130,  129,  126,
173116 /*   250 */   450,  130,  130,  130,  129,  126,  450,  135,  136,   90,
173117 /*   260 */  1228, 1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,
173118 /*   270 */   134,  134,  128,  125,  232,  450,  576,  412,  397, 1249,
173119 /*   280 */   180,   92,   93,  132,  132,  132,  132,  131,  131,  130,
173120 /*   290 */   130,  130,  129,  126,  450,  381,  387, 1204,  383,   81,
173121 /*   300 */    81,  135,  136,   90, 1228, 1228, 1063, 1066, 1053, 1053,
173122 /*   310 */   133,  133,  134,  134,  134,  134,  132,  132,  132,  132,
173123 /*   320 */   131,  131,  130,  130,  130,  129,  126,  450,  131,  131,
173124 /*   330 */   130,  130,  130,  129,  126,  450,  556, 1204,  302,  319,
173125 /*   340 */   567,  121,  568,  480,    4,  555, 1149, 1657, 1628, 1657,
173126 /*   350 */    45,  128,  125,  232, 1204, 1205, 1204, 1250,  571, 1169,
173127 /*   360 */   132,  132,  132,  132,  131,  131,  130,  130,  130,  129,
173128 /*   370 */   126,  450, 1169,  287,  287, 1169, 1019,  576,  422, 1019,
173129 /*   380 */   412,  451, 1602,  582,    2, 1259,  573,   44,  561,   95,
173130 /*   390 */   320,  110,  153,  565, 1204, 1205, 1204,  522,  522, 1341,
173131 /*   400 */    81,   81,    7,   44,  135,  136,   90, 1228, 1228, 1063,
173132 /*   410 */  1066, 1053, 1053,  133,  133,  134,  134,  134,  134,  295,
173133 /*   420 */  1149, 1658, 1040, 1658, 1204, 1147,  319,  567,  119,  119,
173134 /*   430 */   343,  466,  331,  343,  287,  287,  120,  556,  451,  577,
173135 /*   440 */   451, 1169, 1169, 1028,  319,  567,  438,  573,  210,  561,
173136 /*   450 */  1339, 1451,  546,  531, 1169, 1169, 1598, 1169, 1169,  416,
173137 /*   460 */   319,  567,  243,  132,  132,  132,  132,  131,  131,  130,
173138 /*   470 */   130,  130,  129,  126,  450, 1028, 1028, 1030, 1031,   35,
173139 /*   480 */    44, 1204, 1205, 1204,  472,  287,  287, 1328,  412, 1307,
173140 /*   490 */   372, 1595,  359,  225,  454, 1204,  195, 1328,  573, 1147,
173141 /*   500 */   561, 1333, 1333,  274,  576, 1188,  576,  340,   46,  196,
173142 /*   510 */   537,  217,  135,  136,   90, 1228, 1228, 1063, 1066, 1053,
173143 /*   520 */  1053,  133,  133,  134,  134,  134,  134,   19,   19,   19,
173144 /*   530 */    19,  412,  581, 1204, 1259,  511, 1204,  319,  567,  320,
173145 /*   540 */   944,  153,  425,  491,  430,  943, 1204,  488, 1341, 1450,
173146 /*   550 */   532, 1277, 1204, 1205, 1204,  135,  136,   90, 1228, 1228,
173147 /*   560 */  1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,  134,
173148 /*   570 */   575,  132,  132,  132,  132,  131,  131,  130,  130,  130,
173149 /*   580 */   129,  126,  450,  287,  287,  528,  287,  287,  372, 1595,
173150 /*   590 */  1204, 1205, 1204, 1204, 1205, 1204,  573,  486,  561,  573,
173151 /*   600 */   889,  561,  412, 1204, 1205, 1204,  886,   40,   22,   22,
173152 /*   610 */   220,  243,  525, 1449,  132,  132,  132,  132,  131,  131,
173153 /*   620 */   130,  130,  130,  129,  126,  450,  135,  136,   90, 1228,
173154 /*   630 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
173155 /*   640 */   134,  412,  180,  454, 1204,  879,  255,  287,  287,  510,
173156 /*   650 */   507,  506,  372, 1595, 1568, 1331, 1331,  576,  889,  505,
173157 /*   660 */   573,   44,  561,  559, 1207,  135,  136,   90, 1228, 1228,
173158 /*   670 */  1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,  134,
173159 /*   680 */    81,   81,  422,  576,  377,  132,  132,  132,  132,  131,
173160 /*   690 */   131,  130,  130,  130,  129,  126,  450,  297,  287,  287,
173161 /*   700 */   460, 1204, 1205, 1204, 1204,  534,   19,   19,  448,  448,
173162 /*   710 */   448,  573,  412,  561,  230,  436, 1187,  535,  319,  567,
173163 /*   720 */   363,  432, 1207, 1435,  132,  132,  132,  132,  131,  131,
173164 /*   730 */   130,  130,  130,  129,  126,  450,  135,  136,   90, 1228,
173165 /*   740 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
173166 /*   750 */   134,  412,  211,  949, 1169, 1041, 1110, 1110,  494,  547,
173167 /*   760 */   547, 1204, 1205, 1204,    7,  539, 1570, 1169,  376,  576,
173168 /*   770 */  1169,    5, 1204,  486,    3,  135,  136,   90, 1228, 1228,
173169 /*   780 */  1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,  134,
173170 /*   790 */   576,  513,   19,   19,  427,  132,  132,  132,  132,  131,
173171 /*   800 */   131,  130,  130,  130,  129,  126,  450,  305, 1204,  433,
173172 /*   810 */   225, 1204,  385,   19,   19,  273,  290,  371,  516,  366,
173173 /*   820 */   515,  260,  412,  538, 1568,  549, 1024,  362,  437, 1204,
173174 /*   830 */  1205, 1204,  902, 1552,  132,  132,  132,  132,  131,  131,
173175 /*   840 */   130,  130,  130,  129,  126,  450,  135,  136,   90, 1228,
173176 /*   850 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
173177 /*   860 */   134,  412, 1435,  514, 1281, 1204, 1205, 1204, 1204, 1205,
173178 /*   870 */  1204,  903,   48,  342, 1568, 1568, 1279, 1627, 1568,  911,
173179 /*   880 */   576,  129,  126,  450,  110,  135,  136,   90, 1228, 1228,
173180 /*   890 */  1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,  134,
173181 /*   900 */   265,  576,  459,   19,   19,  132,  132,  132,  132,  131,
173182 /*   910 */   131,  130,  130,  130,  129,  126,  450, 1345,  204,  576,
173183 /*   920 */   459,  458,   50,   47,   19,   19,   49,  434, 1105,  573,
173184 /*   930 */   497,  561,  412,  428,  108, 1224, 1569, 1554,  376,  205,
173185 /*   940 */   550,  550,   81,   81,  132,  132,  132,  132,  131,  131,
173186 /*   950 */   130,  130,  130,  129,  126,  450,  135,  136,   90, 1228,
173187 /*   960 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
173188 /*   970 */   134,  480,  576, 1204,  576, 1541,  412, 1435,  969,  315,
173189 /*   980 */  1659,  398,  284,  497,  969,  893, 1569, 1569,  376,  376,
173190 /*   990 */  1569,  461,  376, 1224,  459,   80,   80,   81,   81,  497,
173191 /*  1000 */   374,  114,   90, 1228, 1228, 1063, 1066, 1053, 1053,  133,
173192 /*  1010 */   133,  134,  134,  134,  134,  132,  132,  132,  132,  131,
173193 /*  1020 */   131,  130,  130,  130,  129,  126,  450, 1204, 1505,  576,
173194 /*  1030 */  1204, 1205, 1204, 1366,  316,  486,  281,  281,  497,  431,
173195 /*  1040 */   557,  288,  288,  402, 1340,  471,  345,  298,  429,  573,
173196 /*  1050 */   576,  561,   81,   81,  573,  374,  561,  971,  386,  132,
173197 /*  1060 */   132,  132,  132,  131,  131,  130,  130,  130,  129,  126,
173198 /*  1070 */   450,  231,  117,   81,   81,  287,  287,  231,  287,  287,
173199 /*  1080 */   576, 1511,  576, 1336, 1204, 1205, 1204,  139,  573,  556,
173200 /*  1090 */   561,  573,  412,  561,  441,  456,  969,  213,  558, 1511,
173201 /*  1100 */  1513, 1550,  969,  143,  143,  145,  145, 1368,  314,  478,
173202 /*  1110 */   444,  970,  412,  850,  851,  852,  135,  136,   90, 1228,
173203 /*  1120 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
173204 /*  1130 */   134,  357,  412,  397, 1148,  304,  135,  136,   90, 1228,
173205 /*  1140 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
173206 /*  1150 */   134, 1575,  323,    6,  862,    7,  135,  124,   90, 1228,
173207 /*  1160 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
173208 /*  1170 */   134,  409,  408, 1511,  212,  132,  132,  132,  132,  131,
173209 /*  1180 */   131,  130,  130,  130,  129,  126,  450,  411,  118, 1204,
173210 /*  1190 */   116,   10,  352,  265,  355,  132,  132,  132,  132,  131,
173211 /*  1200 */   131,  130,  130,  130,  129,  126,  450,  576,  324,  306,
173212 /*  1210 */   576,  306, 1250,  469,  158,  132,  132,  132,  132,  131,
173213 /*  1220 */   131,  130,  130,  130,  129,  126,  450,  207, 1224, 1126,
173214 /*  1230 */    65,   65,  470,   66,   66,  412,  447,  446,  882,  531,
173215 /*  1240 */   335,  258,  257,  256, 1127, 1233, 1204, 1205, 1204,  327,
173216 /*  1250 */  1235,  874,  159,  576,   16,  480, 1085, 1040, 1234, 1128,
173217 /*  1260 */   136,   90, 1228, 1228, 1063, 1066, 1053, 1053,  133,  133,
173218 /*  1270 */   134,  134,  134,  134, 1029,  576,   81,   81, 1028, 1040,
173219 /*  1280 */   922,  576,  463, 1236,  576, 1236, 1224,  502,  107, 1435,
173220 /*  1290 */   923,    6,  576,  410, 1498,  882, 1029,  480,   21,   21,
173221 /*  1300 */  1028,  332, 1380,  334,   53,   53,  497,   81,   81,  874,
173222 /*  1310 */  1028, 1028, 1030,  445,  259,   19,   19,  533,  132,  132,
173223 /*  1320 */   132,  132,  131,  131,  130,  130,  130,  129,  126,  450,
173224 /*  1330 */   551,  301, 1028, 1028, 1030,  107,  532,  545,  121,  568,
173225 /*  1340 */  1188,    4, 1126, 1576,  449,  576,  462,    7, 1282,  418,
173226 /*  1350 */   462,  350, 1435,  576,  518,  571,  544, 1127,  121,  568,
173227 /*  1360 */   442,    4, 1188,  464,  533, 1180, 1223,    9,   67,   67,
173228 /*  1370 */   487,  576, 1128,  303,  410,  571,   54,   54,  451,  576,
173229 /*  1380 */   123,  944,  576,  417,  576,  333,  943, 1379,  576,  236,
173230 /*  1390 */   565,  576, 1574,  564,   68,   68,    7,  576,  451,  362,
173231 /*  1400 */   419,  182,   69,   69,  541,   70,   70,   71,   71,  540,
173232 /*  1410 */   565,   72,   72,  484,   55,   55,  473, 1180,  296, 1040,
173233 /*  1420 */    56,   56,  296,  493,  541,  119,  119,  410, 1573,  542,
173234 /*  1430 */   569,  418,    7,  120, 1244,  451,  577,  451,  465, 1040,
173235 /*  1440 */  1028,  576, 1557,  552,  476,  119,  119,  527,  259,  121,
173236 /*  1450 */   568,  240,    4,  120,  576,  451,  577,  451,  576,  477,
173237 /*  1460 */  1028,  576,  156,  576,   57,   57,  571,  576,  286,  229,
173238 /*  1470 */   410,  336, 1028, 1028, 1030, 1031,   35,   59,   59,  219,
173239 /*  1480 */   983,   60,   60,  220,   73,   73,   74,   74,  984,  451,
173240 /*  1490 */    75,   75, 1028, 1028, 1030, 1031,   35,   96,  216,  291,
173241 /*  1500 */   552,  565, 1188,  318,  395,  395,  394,  276,  392,  576,
173242 /*  1510 */   485,  859,  474, 1311,  410,  541,  576,  417, 1530, 1144,
173243 /*  1520 */   540,  399, 1188,  292,  237, 1153,  326,   38,   23,  576,
173244 /*  1530 */  1040,  576,   20,   20,  325,  299,  119,  119,  164,   76,
173245 /*  1540 */    76, 1529,  121,  568,  120,    4,  451,  577,  451,  203,
173246 /*  1550 */   576, 1028,  141,  141,  142,  142,  576,  322,   39,  571,
173247 /*  1560 */   341, 1021,  110,  264,  239,  901,  900,  423,  242,  908,
173248 /*  1570 */   909,  370,  173,   77,   77,   43,  479, 1310,  264,   62,
173249 /*  1580 */    62,  369,  451, 1028, 1028, 1030, 1031,   35, 1601, 1192,
173250 /*  1590 */   453, 1092,  238,  291,  565,  163, 1309,  110,  395,  395,
173251 /*  1600 */   394,  276,  392,  986,  987,  859,  481,  346,  264,  110,
173252 /*  1610 */  1032,  489,  576, 1188,  503, 1088,  261,  261,  237,  576,
173253 /*  1620 */   326,  121,  568, 1040,    4,  347, 1376,  413,  325,  119,
173254 /*  1630 */   119,  948,  319,  567,  351,   78,   78,  120,  571,  451,
173255 /*  1640 */   577,  451,   79,   79, 1028,  354,  356,  576,  360, 1092,
173256 /*  1650 */   110,  576,  974,  942,  264,  123,  457,  358,  239,  576,
173257 /*  1660 */   519,  451,  939, 1104,  123, 1104,  173,  576, 1032,   43,
173258 /*  1670 */    63,   63, 1324,  565,  168,  168, 1028, 1028, 1030, 1031,
173259 /*  1680 */    35,  576,  169,  169, 1308,  872,  238,  157, 1589,  576,
173260 /*  1690 */    86,   86,  365,   89,  568,  375,    4, 1103,  941, 1103,
173261 /*  1700 */   123,  576, 1040, 1389,   64,   64, 1188, 1434,  119,  119,
173262 /*  1710 */   571,  576,   82,   82,  563,  576,  120,  165,  451,  577,
173263 /*  1720 */   451,  413, 1362, 1028,  144,  144,  319,  567,  576, 1374,
173264 /*  1730 */   562,  498,  279,  451,   83,   83, 1439,  576,  166,  166,
173265 /*  1740 */   576, 1289,  554,  576, 1280,  565,  576,   12,  576, 1268,
173266 /*  1750 */   457,  146,  146, 1267,  576, 1028, 1028, 1030, 1031,   35,
173267 /*  1760 */   140,  140, 1269,  167,  167, 1609,  160,  160, 1359,  150,
173268 /*  1770 */   150,  149,  149,  311, 1040,  576,  312,  147,  147,  313,
173269 /*  1780 */   119,  119,  222,  235,  576, 1188,  396,  576,  120,  576,
173270 /*  1790 */   451,  577,  451, 1192,  453, 1028,  508,  291,  148,  148,
173271 /*  1800 */  1421, 1612,  395,  395,  394,  276,  392,   85,   85,  859,
173272 /*  1810 */    87,   87,   84,   84,  553,  576,  294,  576, 1426,  338,
173273 /*  1820 */   339, 1425,  237,  300,  326, 1416, 1409, 1028, 1028, 1030,
173274 /*  1830 */  1031,   35,  325,  344,  403,  483,  226, 1307,   52,   52,
173275 /*  1840 */    58,   58,  368, 1371, 1502,  566, 1501,  121,  568,  221,
173276 /*  1850 */     4,  208,  268,  209,  390, 1244, 1549, 1188, 1372, 1370,
173277 /*  1860 */  1369, 1547,  239,  184,  571,  233,  421, 1241,   95,  218,
173278 /*  1870 */   173, 1507,  193,   43,   91,   94,  178,  186,  467,  188,
173279 /*  1880 */   468, 1422,   13,  189,  190,  191,  501,  451,  245,  108,
173280 /*  1890 */   238,  401, 1428, 1427, 1430,  475,  404, 1496,  197,  565,
173281 /*  1900 */    14,  490,  249,  101, 1518,  496,  349,  280,  251,  201,
173282 /*  1910 */   353,  499,  252,  406, 1270,  253,  517, 1327, 1326,  435,
173283 /*  1920 */  1325, 1318,  103,  893, 1296,  413,  227,  407, 1040, 1626,
173284 /*  1930 */   319,  567, 1625, 1297,  119,  119,  439,  367, 1317, 1295,
173285 /*  1940 */  1624,  526,  120,  440,  451,  577,  451, 1594,  309, 1028,
173286 /*  1950 */   310,  373,  266,  267,  457, 1580, 1579,  443,  138, 1394,
173287 /*  1960 */   552, 1393,   11, 1483,  384,  115,  317, 1350,  109,  536,
173288 /*  1970 */    42,  579,  382,  214, 1349,  388, 1198,  389,  275,  277,
173289 /*  1980 */   278, 1028, 1028, 1030, 1031,   35,  580, 1265,  414, 1260,
173290 /*  1990 */   170,  415,  183, 1534, 1535, 1533,  171,  154,  307, 1532,
173291 /*  2000 */   846,  223,  224,   88,  452,  215,  172,  321,  234, 1102,
173292 /*  2010 */   152, 1188, 1100,  329,  185,  174, 1223,  925,  187,  241,
173293 /*  2020 */   337,  244, 1116,  192,  175,  176,  424,  426,   97,  194,
173294 /*  2030 */    98,   99,  100,  177, 1119, 1115,  246,  247,  161,   24,
173295 /*  2040 */   248,  348, 1238,  264, 1108,  250,  495,  199,  198,   15,
173296 /*  2050 */   861,  500,  369,  254,  504,  509,  512,  200,  102,   25,
173297 /*  2060 */   179,  361,   26,  364,  104,  891,  308,  162,  105,  904,
173298 /*  2070 */   520,  106, 1185, 1069, 1155,   17,  228,   27, 1154,  283,
173299 /*  2080 */   285,  263,  978,  202,  972,  123,   28, 1175,   29,   30,
173300 /*  2090 */  1179, 1171,   31, 1173, 1160,   41,   32,  206,  548,   33,
173301 /*  2100 */   110, 1178, 1083,    8,  112, 1070,  113, 1068, 1072,   34,
173302 /*  2110 */  1073,  560, 1125,  269, 1124,  270,   36,   18, 1194, 1033,
173303 /*  2120 */   873,  151,  122,   37,  393,  271,  272,  572,  181, 1193,
173304 /*  2130 */  1256, 1256, 1256,  935, 1256, 1256, 1256, 1256, 1256, 1256,
173305 /*  2140 */  1256, 1617,
173306};
173307static const YYCODETYPE yy_lookahead[] = {
173308 /*     0 */   194,  276,  277,  278,  216,  194,  194,  217,  194,  194,
173309 /*    10 */   194,  194,  224,  194,  194,  276,  277,  278,  204,   19,
173310 /*    20 */   206,  202,  297,  217,  218,  205,  207,  217,  205,  217,
173311 /*    30 */   218,   31,  217,  218,  217,  218,   29,  217,  218,   39,
173312 /*    40 */    33,  217,  220,   43,   44,   45,   46,   47,   48,   49,
173313 /*    50 */    50,   51,   52,   53,   54,   55,   56,   57,  312,   19,
173314 /*    60 */   240,  241,  316,  240,  241,  194,   46,   47,   48,   49,
173315 /*    70 */    22,  254,   65,  253,  254,  255,  253,  194,  255,  194,
173316 /*    80 */   263,  258,  259,   43,   44,   45,   46,   47,   48,   49,
173317 /*    90 */    50,   51,   52,   53,   54,   55,   56,   57,  276,  277,
173318 /*   100 */   278,  285,  102,  103,  104,  105,  106,  107,  108,  109,
173319 /*   110 */   110,  111,  112,  113,   59,  186,  187,  188,  189,  190,
173320 /*   120 */   191,  310,  239,  317,  318,  196,   86,  198,   88,  317,
173321 /*   130 */    19,  319,  317,  318,  205,  264,   25,  211,  212,  213,
173322 /*   140 */   205,  121,  102,  103,  104,  105,  106,  107,  108,  109,
173323 /*   150 */   110,  111,  112,  113,   43,   44,   45,   46,   47,   48,
173324 /*   160 */    49,   50,   51,   52,   53,   54,   55,   56,   57,  240,
173325 /*   170 */   241,  116,  117,  118,  119,  240,  241,  122,  123,  124,
173326 /*   180 */    69,  298,  253,  194,  255,  106,  107,  132,  253,  141,
173327 /*   190 */   255,   54,   55,   56,   57,   58,  207,  268,  102,  103,
173328 /*   200 */   104,  105,  106,  107,  108,  109,  110,  111,  112,  113,
173329 /*   210 */   214,  128,  129,  102,  103,  104,  105,  106,  107,  108,
173330 /*   220 */   109,  110,  111,  112,  113,  134,   25,  136,  137,  300,
173331 /*   230 */   165,  166,  153,   19,  155,   54,   55,   56,   57,  102,
173332 /*   240 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  112,
173333 /*   250 */   113,  108,  109,  110,  111,  112,  113,   43,   44,   45,
173334 /*   260 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,
173335 /*   270 */    56,   57,  276,  277,  278,  113,  194,   19,   22,   23,
173336 /*   280 */   194,   67,   24,  102,  103,  104,  105,  106,  107,  108,
173337 /*   290 */   109,  110,  111,  112,  113,  220,  250,   59,  252,  217,
173338 /*   300 */   218,   43,   44,   45,   46,   47,   48,   49,   50,   51,
173339 /*   310 */    52,   53,   54,   55,   56,   57,  102,  103,  104,  105,
173340 /*   320 */   106,  107,  108,  109,  110,  111,  112,  113,  106,  107,
173341 /*   330 */   108,  109,  110,  111,  112,  113,  254,   59,  205,  138,
173342 /*   340 */   139,   19,   20,  194,   22,  263,   22,   23,  231,   25,
173343 /*   350 */    72,  276,  277,  278,  116,  117,  118,  101,   36,   76,
173344 /*   360 */   102,  103,  104,  105,  106,  107,  108,  109,  110,  111,
173345 /*   370 */   112,  113,   89,  240,  241,   92,   73,  194,  194,   73,
173346 /*   380 */    19,   59,  188,  189,  190,  191,  253,   81,  255,  151,
173347 /*   390 */   196,   25,  198,   71,  116,  117,  118,  311,  312,  205,
173348 /*   400 */   217,  218,  316,   81,   43,   44,   45,   46,   47,   48,
173349 /*   410 */    49,   50,   51,   52,   53,   54,   55,   56,   57,  270,
173350 /*   420 */    22,   23,  100,   25,   59,  101,  138,  139,  106,  107,
173351 /*   430 */   127,  128,  129,  127,  240,  241,  114,  254,  116,  117,
173352 /*   440 */   118,   76,   76,  121,  138,  139,  263,  253,  264,  255,
173353 /*   450 */   205,  275,   87,   19,   89,   89,  194,   92,   92,  199,
173354 /*   460 */   138,  139,  268,  102,  103,  104,  105,  106,  107,  108,
173355 /*   470 */   109,  110,  111,  112,  113,  153,  154,  155,  156,  157,
173356 /*   480 */    81,  116,  117,  118,  129,  240,  241,  224,   19,  226,
173357 /*   490 */   314,  315,   23,   25,  300,   59,   22,  234,  253,  101,
173358 /*   500 */   255,  236,  237,   26,  194,  183,  194,  152,   72,   22,
173359 /*   510 */   145,  150,   43,   44,   45,   46,   47,   48,   49,   50,
173360 /*   520 */    51,   52,   53,   54,   55,   56,   57,  217,  218,  217,
173361 /*   530 */   218,   19,  189,   59,  191,   23,   59,  138,  139,  196,
173362 /*   540 */   135,  198,  232,  283,  232,  140,   59,  287,  205,  275,
173363 /*   550 */   116,  205,  116,  117,  118,   43,   44,   45,   46,   47,
173364 /*   560 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
173365 /*   570 */   194,  102,  103,  104,  105,  106,  107,  108,  109,  110,
173366 /*   580 */   111,  112,  113,  240,  241,  194,  240,  241,  314,  315,
173367 /*   590 */   116,  117,  118,  116,  117,  118,  253,  194,  255,  253,
173368 /*   600 */    59,  255,   19,  116,  117,  118,   23,   22,  217,  218,
173369 /*   610 */   142,  268,  205,  275,  102,  103,  104,  105,  106,  107,
173370 /*   620 */   108,  109,  110,  111,  112,  113,   43,   44,   45,   46,
173371 /*   630 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
173372 /*   640 */    57,   19,  194,  300,   59,   23,  119,  240,  241,  122,
173373 /*   650 */   123,  124,  314,  315,  194,  236,  237,  194,  117,  132,
173374 /*   660 */   253,   81,  255,  205,   59,   43,   44,   45,   46,   47,
173375 /*   670 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
173376 /*   680 */   217,  218,  194,  194,  194,  102,  103,  104,  105,  106,
173377 /*   690 */   107,  108,  109,  110,  111,  112,  113,  294,  240,  241,
173378 /*   700 */   120,  116,  117,  118,   59,  194,  217,  218,  211,  212,
173379 /*   710 */   213,  253,   19,  255,  194,   19,   23,  254,  138,  139,
173380 /*   720 */    24,  232,  117,  194,  102,  103,  104,  105,  106,  107,
173381 /*   730 */   108,  109,  110,  111,  112,  113,   43,   44,   45,   46,
173382 /*   740 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
173383 /*   750 */    57,   19,  264,  108,   76,   23,  127,  128,  129,  311,
173384 /*   760 */   312,  116,  117,  118,  316,   87,  306,   89,  308,  194,
173385 /*   770 */    92,   22,   59,  194,   22,   43,   44,   45,   46,   47,
173386 /*   780 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
173387 /*   790 */   194,   95,  217,  218,  265,  102,  103,  104,  105,  106,
173388 /*   800 */   107,  108,  109,  110,  111,  112,  113,  232,   59,  113,
173389 /*   810 */    25,   59,  194,  217,  218,  119,  120,  121,  122,  123,
173390 /*   820 */   124,  125,   19,  145,  194,  194,   23,  131,  232,  116,
173391 /*   830 */   117,  118,   35,  194,  102,  103,  104,  105,  106,  107,
173392 /*   840 */   108,  109,  110,  111,  112,  113,   43,   44,   45,   46,
173393 /*   850 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
173394 /*   860 */    57,   19,  194,   66,  194,  116,  117,  118,  116,  117,
173395 /*   870 */   118,   74,  242,  294,  194,  194,  206,   23,  194,   25,
173396 /*   880 */   194,  111,  112,  113,   25,   43,   44,   45,   46,   47,
173397 /*   890 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
173398 /*   900 */    24,  194,  194,  217,  218,  102,  103,  104,  105,  106,
173399 /*   910 */   107,  108,  109,  110,  111,  112,  113,  241,  232,  194,
173400 /*   920 */   212,  213,  242,  242,  217,  218,  242,  130,   11,  253,
173401 /*   930 */   194,  255,   19,  265,  149,   59,  306,  194,  308,  232,
173402 /*   940 */   309,  310,  217,  218,  102,  103,  104,  105,  106,  107,
173403 /*   950 */   108,  109,  110,  111,  112,  113,   43,   44,   45,   46,
173404 /*   960 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
173405 /*   970 */    57,  194,  194,   59,  194,  239,   19,  194,   25,  254,
173406 /*   980 */   303,  304,   23,  194,   25,  126,  306,  306,  308,  308,
173407 /*   990 */   306,  271,  308,  117,  286,  217,  218,  217,  218,  194,
173408 /*  1000 */   194,  159,   45,   46,   47,   48,   49,   50,   51,   52,
173409 /*  1010 */    53,   54,   55,   56,   57,  102,  103,  104,  105,  106,
173410 /*  1020 */   107,  108,  109,  110,  111,  112,  113,   59,  239,  194,
173411 /*  1030 */   116,  117,  118,  260,  254,  194,  240,  241,  194,  233,
173412 /*  1040 */   205,  240,  241,  205,  239,  128,  129,  270,  265,  253,
173413 /*  1050 */   194,  255,  217,  218,  253,  194,  255,  143,  280,  102,
173414 /*  1060 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  112,
173415 /*  1070 */   113,  118,  159,  217,  218,  240,  241,  118,  240,  241,
173416 /*  1080 */   194,  194,  194,  239,  116,  117,  118,   22,  253,  254,
173417 /*  1090 */   255,  253,   19,  255,  233,  194,  143,   24,  263,  212,
173418 /*  1100 */   213,  194,  143,  217,  218,  217,  218,  261,  262,  271,
173419 /*  1110 */   254,  143,   19,    7,    8,    9,   43,   44,   45,   46,
173420 /*  1120 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
173421 /*  1130 */    57,   16,   19,   22,   23,  294,   43,   44,   45,   46,
173422 /*  1140 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
173423 /*  1150 */    57,  312,  194,  214,   21,  316,   43,   44,   45,   46,
173424 /*  1160 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
173425 /*  1170 */    57,  106,  107,  286,  194,  102,  103,  104,  105,  106,
173426 /*  1180 */   107,  108,  109,  110,  111,  112,  113,  207,  158,   59,
173427 /*  1190 */   160,   22,   77,   24,   79,  102,  103,  104,  105,  106,
173428 /*  1200 */   107,  108,  109,  110,  111,  112,  113,  194,  194,  229,
173429 /*  1210 */   194,  231,  101,   80,   22,  102,  103,  104,  105,  106,
173430 /*  1220 */   107,  108,  109,  110,  111,  112,  113,  288,   59,   12,
173431 /*  1230 */   217,  218,  293,  217,  218,   19,  106,  107,   59,   19,
173432 /*  1240 */    16,  127,  128,  129,   27,  115,  116,  117,  118,  194,
173433 /*  1250 */   120,   59,   22,  194,   24,  194,  123,  100,  128,   42,
173434 /*  1260 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
173435 /*  1270 */    54,   55,   56,   57,  117,  194,  217,  218,  121,  100,
173436 /*  1280 */    63,  194,  245,  153,  194,  155,  117,   19,  115,  194,
173437 /*  1290 */    73,  214,  194,  256,  161,  116,  117,  194,  217,  218,
173438 /*  1300 */   121,   77,  194,   79,  217,  218,  194,  217,  218,  117,
173439 /*  1310 */   153,  154,  155,  254,   46,  217,  218,  144,  102,  103,
173440 /*  1320 */   104,  105,  106,  107,  108,  109,  110,  111,  112,  113,
173441 /*  1330 */   232,  270,  153,  154,  155,  115,  116,   66,   19,   20,
173442 /*  1340 */   183,   22,   12,  312,  254,  194,  262,  316,  209,  210,
173443 /*  1350 */   266,  239,  194,  194,  108,   36,   85,   27,   19,   20,
173444 /*  1360 */   265,   22,  183,  245,  144,   94,   25,   48,  217,  218,
173445 /*  1370 */   293,  194,   42,  270,  256,   36,  217,  218,   59,  194,
173446 /*  1380 */    25,  135,  194,  115,  194,  161,  140,  194,  194,   15,
173447 /*  1390 */    71,  194,  312,   63,  217,  218,  316,  194,   59,  131,
173448 /*  1400 */   301,  302,  217,  218,   85,  217,  218,  217,  218,   90,
173449 /*  1410 */    71,  217,  218,   19,  217,  218,  245,  146,  262,  100,
173450 /*  1420 */   217,  218,  266,  265,   85,  106,  107,  256,  312,   90,
173451 /*  1430 */   209,  210,  316,  114,   60,  116,  117,  118,  194,  100,
173452 /*  1440 */   121,  194,  194,  145,  115,  106,  107,   19,   46,   19,
173453 /*  1450 */    20,   24,   22,  114,  194,  116,  117,  118,  194,  245,
173454 /*  1460 */   121,  194,  164,  194,  217,  218,   36,  194,  258,  259,
173455 /*  1470 */   256,  194,  153,  154,  155,  156,  157,  217,  218,  150,
173456 /*  1480 */    31,  217,  218,  142,  217,  218,  217,  218,   39,   59,
173457 /*  1490 */   217,  218,  153,  154,  155,  156,  157,  149,  150,    5,
173458 /*  1500 */   145,   71,  183,  245,   10,   11,   12,   13,   14,  194,
173459 /*  1510 */   116,   17,  129,  227,  256,   85,  194,  115,  194,   23,
173460 /*  1520 */    90,   25,  183,   99,   30,   97,   32,   22,   22,  194,
173461 /*  1530 */   100,  194,  217,  218,   40,  152,  106,  107,   23,  217,
173462 /*  1540 */   218,  194,   19,   20,  114,   22,  116,  117,  118,  257,
173463 /*  1550 */   194,  121,  217,  218,  217,  218,  194,  133,   53,   36,
173464 /*  1560 */    23,   23,   25,   25,   70,  120,  121,   61,  141,    7,
173465 /*  1570 */     8,  121,   78,  217,  218,   81,   23,  227,   25,  217,
173466 /*  1580 */   218,  131,   59,  153,  154,  155,  156,  157,    0,    1,
173467 /*  1590 */     2,   59,   98,    5,   71,   23,  227,   25,   10,   11,
173468 /*  1600 */    12,   13,   14,   83,   84,   17,   23,   23,   25,   25,
173469 /*  1610 */    59,  194,  194,  183,   23,   23,   25,   25,   30,  194,
173470 /*  1620 */    32,   19,   20,  100,   22,  194,  194,  133,   40,  106,
173471 /*  1630 */   107,  108,  138,  139,  194,  217,  218,  114,   36,  116,
173472 /*  1640 */   117,  118,  217,  218,  121,  194,  194,  194,   23,  117,
173473 /*  1650 */    25,  194,   23,   23,   25,   25,  162,  194,   70,  194,
173474 /*  1660 */   145,   59,   23,  153,   25,  155,   78,  194,  117,   81,
173475 /*  1670 */   217,  218,  194,   71,  217,  218,  153,  154,  155,  156,
173476 /*  1680 */   157,  194,  217,  218,  194,   23,   98,   25,  321,  194,
173477 /*  1690 */   217,  218,  194,   19,   20,  194,   22,  153,   23,  155,
173478 /*  1700 */    25,  194,  100,  194,  217,  218,  183,  194,  106,  107,
173479 /*  1710 */    36,  194,  217,  218,  237,  194,  114,  243,  116,  117,
173480 /*  1720 */   118,  133,  194,  121,  217,  218,  138,  139,  194,  194,
173481 /*  1730 */   194,  290,  289,   59,  217,  218,  194,  194,  217,  218,
173482 /*  1740 */   194,  194,  140,  194,  194,   71,  194,  244,  194,  194,
173483 /*  1750 */   162,  217,  218,  194,  194,  153,  154,  155,  156,  157,
173484 /*  1760 */   217,  218,  194,  217,  218,  194,  217,  218,  257,  217,
173485 /*  1770 */   218,  217,  218,  257,  100,  194,  257,  217,  218,  257,
173486 /*  1780 */   106,  107,  215,  299,  194,  183,  192,  194,  114,  194,
173487 /*  1790 */   116,  117,  118,    1,    2,  121,  221,    5,  217,  218,
173488 /*  1800 */   273,  197,   10,   11,   12,   13,   14,  217,  218,   17,
173489 /*  1810 */   217,  218,  217,  218,  140,  194,  246,  194,  273,  295,
173490 /*  1820 */   247,  273,   30,  247,   32,  269,  269,  153,  154,  155,
173491 /*  1830 */   156,  157,   40,  246,  273,  295,  230,  226,  217,  218,
173492 /*  1840 */   217,  218,  220,  261,  220,  282,  220,   19,   20,  244,
173493 /*  1850 */    22,  250,  141,  250,  246,   60,  201,  183,  261,  261,
173494 /*  1860 */   261,  201,   70,  299,   36,  299,  201,   38,  151,  150,
173495 /*  1870 */    78,  285,   22,   81,  296,  296,   43,  235,   18,  238,
173496 /*  1880 */   201,  274,  272,  238,  238,  238,   18,   59,  200,  149,
173497 /*  1890 */    98,  247,  274,  274,  235,  247,  247,  247,  235,   71,
173498 /*  1900 */   272,  201,  200,  158,  292,   62,  291,  201,  200,   22,
173499 /*  1910 */   201,  222,  200,  222,  201,  200,  115,  219,  219,   64,
173500 /*  1920 */   219,  228,   22,  126,  221,  133,  165,  222,  100,  225,
173501 /*  1930 */   138,  139,  225,  219,  106,  107,   24,  219,  228,  219,
173502 /*  1940 */   219,  307,  114,  113,  116,  117,  118,  315,  284,  121,
173503 /*  1950 */   284,  222,  201,   91,  162,  320,  320,   82,  148,  267,
173504 /*  1960 */   145,  267,   22,  279,  201,  158,  281,  251,  147,  146,
173505 /*  1970 */    25,  203,  250,  249,  251,  248,   13,  247,  195,  195,
173506 /*  1980 */     6,  153,  154,  155,  156,  157,  193,  193,  305,  193,
173507 /*  1990 */   208,  305,  302,  214,  214,  214,  208,  223,  223,  214,
173508 /*  2000 */     4,  215,  215,  214,    3,   22,  208,  163,   15,   23,
173509 /*  2010 */    16,  183,   23,  139,  151,  130,   25,   20,  142,   24,
173510 /*  2020 */    16,  144,    1,  142,  130,  130,   61,   37,   53,  151,
173511 /*  2030 */    53,   53,   53,  130,  116,    1,   34,  141,    5,   22,
173512 /*  2040 */   115,  161,   75,   25,   68,  141,   41,  115,   68,   24,
173513 /*  2050 */    20,   19,  131,  125,   67,   67,   96,   22,   22,   22,
173514 /*  2060 */    37,   23,   22,   24,   22,   59,   67,   23,  149,   28,
173515 /*  2070 */    22,   25,   23,   23,   23,   22,  141,   34,   97,   23,
173516 /*  2080 */    23,   34,  116,   22,  143,   25,   34,   75,   34,   34,
173517 /*  2090 */    75,   88,   34,   86,   23,   22,   34,   25,   24,   34,
173518 /*  2100 */    25,   93,   23,   44,  142,   23,  142,   23,   23,   22,
173519 /*  2110 */    11,   25,   23,   25,   23,   22,   22,   22,    1,   23,
173520 /*  2120 */    23,   23,   22,   22,   15,  141,  141,   25,   25,    1,
173521 /*  2130 */   322,  322,  322,  135,  322,  322,  322,  322,  322,  322,
173522 /*  2140 */   322,  141,  322,  322,  322,  322,  322,  322,  322,  322,
173523 /*  2150 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173524 /*  2160 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173525 /*  2170 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173526 /*  2180 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173527 /*  2190 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173528 /*  2200 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173529 /*  2210 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173530 /*  2220 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173531 /*  2230 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173532 /*  2240 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173533 /*  2250 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173534 /*  2260 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173535 /*  2270 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173536 /*  2280 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173537 /*  2290 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173538 /*  2300 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173539 /*  2310 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
173540 /*  2320 */   322,  322,  322,  322,  322,  322,  322,  322,
173541};
173542#define YY_SHIFT_COUNT    (582)
173543#define YY_SHIFT_MIN      (0)
173544#define YY_SHIFT_MAX      (2128)
173545static const unsigned short int yy_shift_ofst[] = {
173546 /*     0 */  1792, 1588, 1494,  322,  322,  399,  306, 1319, 1339, 1430,
173547 /*    10 */  1828, 1828, 1828,  580,  399,  399,  399,  399,  399,    0,
173548 /*    20 */     0,  214, 1093, 1828, 1828, 1828, 1828, 1828, 1828, 1828,
173549 /*    30 */  1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1130, 1130,
173550 /*    40 */   365,  365,   55,  278,  436,  713,  713,  201,  201,  201,
173551 /*    50 */   201,   40,  111,  258,  361,  469,  512,  583,  622,  693,
173552 /*    60 */   732,  803,  842,  913, 1073, 1093, 1093, 1093, 1093, 1093,
173553 /*    70 */  1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093,
173554 /*    80 */  1093, 1093, 1093, 1113, 1093, 1216,  957,  957, 1523, 1602,
173555 /*    90 */  1674, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828,
173556 /*   100 */  1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828,
173557 /*   110 */  1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828,
173558 /*   120 */  1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828,
173559 /*   130 */  1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828,
173560 /*   140 */   137,  181,  181,  181,  181,  181,  181,  181,   96,  222,
173561 /*   150 */   143,  477,  713, 1133, 1268,  713,  713,   79,   79,  713,
173562 /*   160 */   770,   83,   65,   65,   65,  288,  162,  162, 2142, 2142,
173563 /*   170 */   696,  696,  696,  238,  474,  474,  474,  474, 1217, 1217,
173564 /*   180 */   678,  477,  324,  398,  713,  713,  713,  713,  713,  713,
173565 /*   190 */   713,  713,  713,  713,  713,  713,  713,  713,  713,  713,
173566 /*   200 */   713,  713,  713, 1220,  366,  366,  713,  917,  283,  283,
173567 /*   210 */   434,  434,  605,  605, 1298, 2142, 2142, 2142, 2142, 2142,
173568 /*   220 */  2142, 2142, 1179, 1157, 1157,  487,  527,  585,  645,  749,
173569 /*   230 */   914,  968,  752,  713,  713,  713,  713,  713,  713,  713,
173570 /*   240 */   713,  713,  713,  303,  713,  713,  713,  713,  713,  713,
173571 /*   250 */   713,  713,  713,  713,  713,  713,  797,  797,  797,  713,
173572 /*   260 */   713,  713,  959,  713,  713,  713, 1169, 1271,  713,  713,
173573 /*   270 */  1330,  713,  713,  713,  713,  713,  713,  713,  713,  629,
173574 /*   280 */     7,   91,  876,  876,  876,  876,  953,   91,   91, 1246,
173575 /*   290 */  1065, 1106, 1374, 1329, 1348,  468, 1348, 1394,  785, 1329,
173576 /*   300 */  1329,  785, 1329,  468, 1394,  859,  854, 1402, 1449, 1449,
173577 /*   310 */  1449, 1173, 1173, 1173, 1173, 1355, 1355, 1030, 1341,  405,
173578 /*   320 */  1230, 1795, 1795, 1711, 1711, 1829, 1829, 1711, 1717, 1719,
173579 /*   330 */  1850, 1833, 1860, 1860, 1860, 1860, 1711, 1868, 1740, 1719,
173580 /*   340 */  1719, 1740, 1850, 1833, 1740, 1833, 1740, 1711, 1868, 1745,
173581 /*   350 */  1843, 1711, 1868, 1887, 1711, 1868, 1711, 1868, 1887, 1801,
173582 /*   360 */  1801, 1801, 1855, 1900, 1900, 1887, 1801, 1797, 1801, 1855,
173583 /*   370 */  1801, 1801, 1761, 1912, 1830, 1830, 1887, 1711, 1862, 1862,
173584 /*   380 */  1875, 1875, 1810, 1815, 1940, 1711, 1807, 1810, 1821, 1823,
173585 /*   390 */  1740, 1945, 1963, 1963, 1974, 1974, 1974, 2142, 2142, 2142,
173586 /*   400 */  2142, 2142, 2142, 2142, 2142, 2142, 2142, 2142, 2142, 2142,
173587 /*   410 */  2142, 2142,   20, 1224,  256, 1111, 1115, 1114, 1192, 1496,
173588 /*   420 */  1424, 1505, 1427,  355, 1383, 1537, 1506, 1538, 1553, 1583,
173589 /*   430 */  1584, 1591, 1625,  541, 1445, 1562, 1450, 1572, 1515, 1428,
173590 /*   440 */  1532, 1592, 1629, 1520, 1630, 1639, 1510, 1544, 1662, 1675,
173591 /*   450 */  1551,   48, 1996, 2001, 1983, 1844, 1993, 1994, 1986, 1989,
173592 /*   460 */  1874, 1863, 1885, 1991, 1991, 1995, 1876, 1997, 1877, 2004,
173593 /*   470 */  2021, 1881, 1894, 1991, 1895, 1965, 1990, 1991, 1878, 1975,
173594 /*   480 */  1977, 1978, 1979, 1903, 1918, 2002, 1896, 2034, 2033, 2017,
173595 /*   490 */  1925, 1880, 1976, 2018, 1980, 1967, 2005, 1904, 1932, 2025,
173596 /*   500 */  2030, 2032, 1921, 1928, 2035, 1987, 2036, 2037, 2038, 2040,
173597 /*   510 */  1988, 2006, 2039, 1960, 2041, 2042, 1999, 2023, 2044, 2043,
173598 /*   520 */  1919, 2048, 2049, 2050, 2046, 2051, 2053, 1981, 1935, 2056,
173599 /*   530 */  2057, 1966, 2047, 2061, 1941, 2060, 2052, 2054, 2055, 2058,
173600 /*   540 */  2003, 2012, 2007, 2059, 2015, 2008, 2062, 2071, 2073, 2074,
173601 /*   550 */  2072, 2075, 2065, 1962, 1964, 2079, 2060, 2082, 2084, 2085,
173602 /*   560 */  2087, 2086, 2089, 2088, 2091, 2093, 2099, 2094, 2095, 2096,
173603 /*   570 */  2097, 2100, 2101, 2102, 1998, 1984, 1985, 2000, 2103, 2098,
173604 /*   580 */  2109, 2117, 2128,
173605};
173606#define YY_REDUCE_COUNT (411)
173607#define YY_REDUCE_MIN   (-275)
173608#define YY_REDUCE_MAX   (1798)
173609static const short yy_reduce_ofst[] = {
173610 /*     0 */   -71,  194,  343,  835, -180, -177,  838, -194, -188, -185,
173611 /*    10 */  -183,   82,  183,  -65,  133,  245,  346,  407,  458, -178,
173612 /*    20 */    75, -275,   -4,  310,  312,  489,  575,  596,  463,  686,
173613 /*    30 */   707,  725,  780, 1098,  856,  778, 1059, 1090,  708,  887,
173614 /*    40 */    86,  448,  980,  630,  680,  681,  684,  796,  801,  796,
173615 /*    50 */   801, -261, -261, -261, -261, -261, -261, -261, -261, -261,
173616 /*    60 */  -261, -261, -261, -261, -261, -261, -261, -261, -261, -261,
173617 /*    70 */  -261, -261, -261, -261, -261, -261, -261, -261, -261, -261,
173618 /*    80 */  -261, -261, -261, -261, -261, -261, -261, -261,  391,  886,
173619 /*    90 */   888, 1013, 1016, 1081, 1087, 1151, 1159, 1177, 1185, 1188,
173620 /*   100 */  1190, 1194, 1197, 1203, 1247, 1260, 1264, 1267, 1269, 1273,
173621 /*   110 */  1315, 1322, 1335, 1337, 1356, 1362, 1418, 1425, 1453, 1457,
173622 /*   120 */  1465, 1473, 1487, 1495, 1507, 1517, 1521, 1534, 1543, 1546,
173623 /*   130 */  1549, 1552, 1554, 1560, 1581, 1590, 1593, 1595, 1621, 1623,
173624 /*   140 */  -261, -261, -261, -261, -261, -261, -261, -261, -261, -261,
173625 /*   150 */  -261, -186, -117,  260,  263,  460,  631,  -74,  497, -181,
173626 /*   160 */  -261,  939,  176,  274,  338,  676, -261, -261, -261, -261,
173627 /*   170 */  -212, -212, -212, -184,  149,  777, 1061, 1103,  265,  419,
173628 /*   180 */  -254,  670,  677,  677,  -11, -129,  184,  488,  736,  789,
173629 /*   190 */   805,  844,  403,  529,  579,  668,  783,  841, 1158, 1112,
173630 /*   200 */   806,  861, 1095,  846,  839, 1031, -189, 1077, 1080, 1116,
173631 /*   210 */  1084, 1156, 1139, 1221,   46, 1099, 1037, 1118, 1171, 1214,
173632 /*   220 */  1210, 1258, -210, -190, -176, -115,  117,  262,  376,  490,
173633 /*   230 */   511,  520,  618,  639,  743,  901,  907,  958, 1014, 1055,
173634 /*   240 */  1108, 1193, 1244,  720, 1248, 1277, 1324, 1347, 1417, 1431,
173635 /*   250 */  1432, 1440, 1451, 1452, 1463, 1478, 1286, 1350, 1369, 1490,
173636 /*   260 */  1498, 1501,  773, 1509, 1513, 1528, 1292, 1367, 1535, 1536,
173637 /*   270 */  1477, 1542,  376, 1547, 1550, 1555, 1559, 1568, 1571, 1441,
173638 /*   280 */  1443, 1474, 1511, 1516, 1519, 1522,  773, 1474, 1474, 1503,
173639 /*   290 */  1567, 1594, 1484, 1527, 1556, 1570, 1557, 1524, 1573, 1545,
173640 /*   300 */  1548, 1576, 1561, 1587, 1540, 1575, 1606, 1611, 1622, 1624,
173641 /*   310 */  1626, 1582, 1597, 1598, 1599, 1601, 1603, 1563, 1608, 1605,
173642 /*   320 */  1604, 1564, 1566, 1655, 1660, 1578, 1579, 1665, 1586, 1607,
173643 /*   330 */  1610, 1642, 1641, 1645, 1646, 1647, 1679, 1688, 1644, 1618,
173644 /*   340 */  1619, 1648, 1628, 1659, 1649, 1663, 1650, 1700, 1702, 1612,
173645 /*   350 */  1615, 1706, 1708, 1689, 1709, 1712, 1713, 1715, 1691, 1698,
173646 /*   360 */  1699, 1701, 1693, 1704, 1707, 1705, 1714, 1703, 1718, 1710,
173647 /*   370 */  1720, 1721, 1632, 1634, 1664, 1666, 1729, 1751, 1635, 1636,
173648 /*   380 */  1692, 1694, 1716, 1722, 1684, 1763, 1685, 1723, 1724, 1727,
173649 /*   390 */  1730, 1768, 1783, 1784, 1793, 1794, 1796, 1683, 1686, 1690,
173650 /*   400 */  1782, 1779, 1780, 1781, 1785, 1788, 1774, 1775, 1786, 1787,
173651 /*   410 */  1789, 1798,
173652};
173653static const YYACTIONTYPE yy_default[] = {
173654 /*     0 */  1663, 1663, 1663, 1491, 1254, 1367, 1254, 1254, 1254, 1254,
173655 /*    10 */  1491, 1491, 1491, 1254, 1254, 1254, 1254, 1254, 1254, 1397,
173656 /*    20 */  1397, 1544, 1287, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173657 /*    30 */  1254, 1254, 1254, 1254, 1254, 1490, 1254, 1254, 1254, 1254,
173658 /*    40 */  1578, 1578, 1254, 1254, 1254, 1254, 1254, 1563, 1562, 1254,
173659 /*    50 */  1254, 1254, 1406, 1254, 1413, 1254, 1254, 1254, 1254, 1254,
173660 /*    60 */  1492, 1493, 1254, 1254, 1254, 1543, 1545, 1508, 1420, 1419,
173661 /*    70 */  1418, 1417, 1526, 1385, 1411, 1404, 1408, 1487, 1488, 1486,
173662 /*    80 */  1641, 1493, 1492, 1254, 1407, 1455, 1471, 1454, 1254, 1254,
173663 /*    90 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173664 /*   100 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173665 /*   110 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173666 /*   120 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173667 /*   130 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173668 /*   140 */  1463, 1470, 1469, 1468, 1477, 1467, 1464, 1457, 1456, 1458,
173669 /*   150 */  1459, 1278, 1254, 1275, 1329, 1254, 1254, 1254, 1254, 1254,
173670 /*   160 */  1460, 1287, 1448, 1447, 1446, 1254, 1474, 1461, 1473, 1472,
173671 /*   170 */  1551, 1615, 1614, 1509, 1254, 1254, 1254, 1254, 1254, 1254,
173672 /*   180 */  1578, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173673 /*   190 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173674 /*   200 */  1254, 1254, 1254, 1387, 1578, 1578, 1254, 1287, 1578, 1578,
173675 /*   210 */  1388, 1388, 1283, 1283, 1391, 1558, 1358, 1358, 1358, 1358,
173676 /*   220 */  1367, 1358, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173677 /*   230 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1548, 1546, 1254,
173678 /*   240 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173679 /*   250 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173680 /*   260 */  1254, 1254, 1254, 1254, 1254, 1254, 1363, 1254, 1254, 1254,
173681 /*   270 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1608, 1254,
173682 /*   280 */  1521, 1343, 1363, 1363, 1363, 1363, 1365, 1344, 1342, 1357,
173683 /*   290 */  1288, 1261, 1655, 1423, 1412, 1364, 1412, 1652, 1410, 1423,
173684 /*   300 */  1423, 1410, 1423, 1364, 1652, 1304, 1630, 1299, 1397, 1397,
173685 /*   310 */  1397, 1387, 1387, 1387, 1387, 1391, 1391, 1489, 1364, 1357,
173686 /*   320 */  1254, 1655, 1655, 1373, 1373, 1654, 1654, 1373, 1509, 1638,
173687 /*   330 */  1432, 1332, 1338, 1338, 1338, 1338, 1373, 1272, 1410, 1638,
173688 /*   340 */  1638, 1410, 1432, 1332, 1410, 1332, 1410, 1373, 1272, 1525,
173689 /*   350 */  1649, 1373, 1272, 1499, 1373, 1272, 1373, 1272, 1499, 1330,
173690 /*   360 */  1330, 1330, 1319, 1254, 1254, 1499, 1330, 1304, 1330, 1319,
173691 /*   370 */  1330, 1330, 1596, 1254, 1503, 1503, 1499, 1373, 1588, 1588,
173692 /*   380 */  1400, 1400, 1405, 1391, 1494, 1373, 1254, 1405, 1403, 1401,
173693 /*   390 */  1410, 1322, 1611, 1611, 1607, 1607, 1607, 1660, 1660, 1558,
173694 /*   400 */  1623, 1287, 1287, 1287, 1287, 1623, 1306, 1306, 1288, 1288,
173695 /*   410 */  1287, 1623, 1254, 1254, 1254, 1254, 1254, 1254, 1618, 1254,
173696 /*   420 */  1553, 1510, 1377, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173697 /*   430 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1564,
173698 /*   440 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173699 /*   450 */  1254, 1437, 1254, 1257, 1555, 1254, 1254, 1254, 1254, 1254,
173700 /*   460 */  1254, 1254, 1254, 1414, 1415, 1378, 1254, 1254, 1254, 1254,
173701 /*   470 */  1254, 1254, 1254, 1429, 1254, 1254, 1254, 1424, 1254, 1254,
173702 /*   480 */  1254, 1254, 1254, 1254, 1254, 1254, 1651, 1254, 1254, 1254,
173703 /*   490 */  1254, 1254, 1254, 1524, 1523, 1254, 1254, 1375, 1254, 1254,
173704 /*   500 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173705 /*   510 */  1254, 1302, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173706 /*   520 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173707 /*   530 */  1254, 1254, 1254, 1254, 1254, 1402, 1254, 1254, 1254, 1254,
173708 /*   540 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173709 /*   550 */  1593, 1392, 1254, 1254, 1254, 1254, 1642, 1254, 1254, 1254,
173710 /*   560 */  1254, 1352, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
173711 /*   570 */  1254, 1254, 1254, 1634, 1346, 1438, 1254, 1441, 1276, 1254,
173712 /*   580 */  1266, 1254, 1254,
173713};
173714/********** End of lemon-generated parsing tables *****************************/
173715
173716/* The next table maps tokens (terminal symbols) into fallback tokens.
173717** If a construct like the following:
173718**
173719**      %fallback ID X Y Z.
173720**
173721** appears in the grammar, then ID becomes a fallback token for X, Y,
173722** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
173723** but it does not parse, the type of the token is changed to ID and
173724** the parse is retried before an error is thrown.
173725**
173726** This feature can be used, for example, to cause some keywords in a language
173727** to revert to identifiers if they keyword does not apply in the context where
173728** it appears.
173729*/
173730#ifdef YYFALLBACK
173731static const YYCODETYPE yyFallback[] = {
173732    0,  /*          $ => nothing */
173733    0,  /*       SEMI => nothing */
173734   59,  /*    EXPLAIN => ID */
173735   59,  /*      QUERY => ID */
173736   59,  /*       PLAN => ID */
173737   59,  /*      BEGIN => ID */
173738    0,  /* TRANSACTION => nothing */
173739   59,  /*   DEFERRED => ID */
173740   59,  /*  IMMEDIATE => ID */
173741   59,  /*  EXCLUSIVE => ID */
173742    0,  /*     COMMIT => nothing */
173743   59,  /*        END => ID */
173744   59,  /*   ROLLBACK => ID */
173745   59,  /*  SAVEPOINT => ID */
173746   59,  /*    RELEASE => ID */
173747    0,  /*         TO => nothing */
173748    0,  /*      TABLE => nothing */
173749    0,  /*     CREATE => nothing */
173750   59,  /*         IF => ID */
173751    0,  /*        NOT => nothing */
173752    0,  /*     EXISTS => nothing */
173753   59,  /*       TEMP => ID */
173754    0,  /*         LP => nothing */
173755    0,  /*         RP => nothing */
173756    0,  /*         AS => nothing */
173757    0,  /*      COMMA => nothing */
173758   59,  /*    WITHOUT => ID */
173759   59,  /*      ABORT => ID */
173760   59,  /*     ACTION => ID */
173761   59,  /*      AFTER => ID */
173762   59,  /*    ANALYZE => ID */
173763   59,  /*        ASC => ID */
173764   59,  /*     ATTACH => ID */
173765   59,  /*     BEFORE => ID */
173766   59,  /*         BY => ID */
173767   59,  /*    CASCADE => ID */
173768   59,  /*       CAST => ID */
173769   59,  /*   CONFLICT => ID */
173770   59,  /*   DATABASE => ID */
173771   59,  /*       DESC => ID */
173772   59,  /*     DETACH => ID */
173773   59,  /*       EACH => ID */
173774   59,  /*       FAIL => ID */
173775    0,  /*         OR => nothing */
173776    0,  /*        AND => nothing */
173777    0,  /*         IS => nothing */
173778   59,  /*      MATCH => ID */
173779   59,  /*    LIKE_KW => ID */
173780    0,  /*    BETWEEN => nothing */
173781    0,  /*         IN => nothing */
173782    0,  /*     ISNULL => nothing */
173783    0,  /*    NOTNULL => nothing */
173784    0,  /*         NE => nothing */
173785    0,  /*         EQ => nothing */
173786    0,  /*         GT => nothing */
173787    0,  /*         LE => nothing */
173788    0,  /*         LT => nothing */
173789    0,  /*         GE => nothing */
173790    0,  /*     ESCAPE => nothing */
173791    0,  /*         ID => nothing */
173792   59,  /*   COLUMNKW => ID */
173793   59,  /*         DO => ID */
173794   59,  /*        FOR => ID */
173795   59,  /*     IGNORE => ID */
173796   59,  /*  INITIALLY => ID */
173797   59,  /*    INSTEAD => ID */
173798   59,  /*         NO => ID */
173799   59,  /*        KEY => ID */
173800   59,  /*         OF => ID */
173801   59,  /*     OFFSET => ID */
173802   59,  /*     PRAGMA => ID */
173803   59,  /*      RAISE => ID */
173804   59,  /*  RECURSIVE => ID */
173805   59,  /*    REPLACE => ID */
173806   59,  /*   RESTRICT => ID */
173807   59,  /*        ROW => ID */
173808   59,  /*       ROWS => ID */
173809   59,  /*    TRIGGER => ID */
173810   59,  /*     VACUUM => ID */
173811   59,  /*       VIEW => ID */
173812   59,  /*    VIRTUAL => ID */
173813   59,  /*       WITH => ID */
173814   59,  /*      NULLS => ID */
173815   59,  /*      FIRST => ID */
173816   59,  /*       LAST => ID */
173817   59,  /*    CURRENT => ID */
173818   59,  /*  FOLLOWING => ID */
173819   59,  /*  PARTITION => ID */
173820   59,  /*  PRECEDING => ID */
173821   59,  /*      RANGE => ID */
173822   59,  /*  UNBOUNDED => ID */
173823   59,  /*    EXCLUDE => ID */
173824   59,  /*     GROUPS => ID */
173825   59,  /*     OTHERS => ID */
173826   59,  /*       TIES => ID */
173827   59,  /*  GENERATED => ID */
173828   59,  /*     ALWAYS => ID */
173829   59,  /* MATERIALIZED => ID */
173830   59,  /*    REINDEX => ID */
173831   59,  /*     RENAME => ID */
173832   59,  /*   CTIME_KW => ID */
173833    0,  /*        ANY => nothing */
173834    0,  /*     BITAND => nothing */
173835    0,  /*      BITOR => nothing */
173836    0,  /*     LSHIFT => nothing */
173837    0,  /*     RSHIFT => nothing */
173838    0,  /*       PLUS => nothing */
173839    0,  /*      MINUS => nothing */
173840    0,  /*       STAR => nothing */
173841    0,  /*      SLASH => nothing */
173842    0,  /*        REM => nothing */
173843    0,  /*     CONCAT => nothing */
173844    0,  /*        PTR => nothing */
173845    0,  /*    COLLATE => nothing */
173846    0,  /*     BITNOT => nothing */
173847    0,  /*         ON => nothing */
173848    0,  /*    INDEXED => nothing */
173849    0,  /*     STRING => nothing */
173850    0,  /*    JOIN_KW => nothing */
173851    0,  /* CONSTRAINT => nothing */
173852    0,  /*    DEFAULT => nothing */
173853    0,  /*       NULL => nothing */
173854    0,  /*    PRIMARY => nothing */
173855    0,  /*     UNIQUE => nothing */
173856    0,  /*      CHECK => nothing */
173857    0,  /* REFERENCES => nothing */
173858    0,  /*   AUTOINCR => nothing */
173859    0,  /*     INSERT => nothing */
173860    0,  /*     DELETE => nothing */
173861    0,  /*     UPDATE => nothing */
173862    0,  /*        SET => nothing */
173863    0,  /* DEFERRABLE => nothing */
173864    0,  /*    FOREIGN => nothing */
173865    0,  /*       DROP => nothing */
173866    0,  /*      UNION => nothing */
173867    0,  /*        ALL => nothing */
173868    0,  /*     EXCEPT => nothing */
173869    0,  /*  INTERSECT => nothing */
173870    0,  /*     SELECT => nothing */
173871    0,  /*     VALUES => nothing */
173872    0,  /*   DISTINCT => nothing */
173873    0,  /*        DOT => nothing */
173874    0,  /*       FROM => nothing */
173875    0,  /*       JOIN => nothing */
173876    0,  /*      USING => nothing */
173877    0,  /*      ORDER => nothing */
173878    0,  /*      GROUP => nothing */
173879    0,  /*     HAVING => nothing */
173880    0,  /*      LIMIT => nothing */
173881    0,  /*      WHERE => nothing */
173882    0,  /*  RETURNING => nothing */
173883    0,  /*       INTO => nothing */
173884    0,  /*    NOTHING => nothing */
173885    0,  /*      FLOAT => nothing */
173886    0,  /*       BLOB => nothing */
173887    0,  /*    INTEGER => nothing */
173888    0,  /*   VARIABLE => nothing */
173889    0,  /*       CASE => nothing */
173890    0,  /*       WHEN => nothing */
173891    0,  /*       THEN => nothing */
173892    0,  /*       ELSE => nothing */
173893    0,  /*      INDEX => nothing */
173894    0,  /*      ALTER => nothing */
173895    0,  /*        ADD => nothing */
173896    0,  /*     WINDOW => nothing */
173897    0,  /*       OVER => nothing */
173898    0,  /*     FILTER => nothing */
173899    0,  /*     COLUMN => nothing */
173900    0,  /* AGG_FUNCTION => nothing */
173901    0,  /* AGG_COLUMN => nothing */
173902    0,  /*  TRUEFALSE => nothing */
173903    0,  /*      ISNOT => nothing */
173904    0,  /*   FUNCTION => nothing */
173905    0,  /*      UPLUS => nothing */
173906    0,  /*     UMINUS => nothing */
173907    0,  /*      TRUTH => nothing */
173908    0,  /*   REGISTER => nothing */
173909    0,  /*     VECTOR => nothing */
173910    0,  /* SELECT_COLUMN => nothing */
173911    0,  /* IF_NULL_ROW => nothing */
173912    0,  /*   ASTERISK => nothing */
173913    0,  /*       SPAN => nothing */
173914    0,  /*      ERROR => nothing */
173915    0,  /*    QNUMBER => nothing */
173916    0,  /*      SPACE => nothing */
173917    0,  /*    ILLEGAL => nothing */
173918};
173919#endif /* YYFALLBACK */
173920
173921/* The following structure represents a single element of the
173922** parser's stack.  Information stored includes:
173923**
173924**   +  The state number for the parser at this level of the stack.
173925**
173926**   +  The value of the token stored at this level of the stack.
173927**      (In other words, the "major" token.)
173928**
173929**   +  The semantic value stored at this level of the stack.  This is
173930**      the information used by the action routines in the grammar.
173931**      It is sometimes called the "minor" token.
173932**
173933** After the "shift" half of a SHIFTREDUCE action, the stateno field
173934** actually contains the reduce action for the second half of the
173935** SHIFTREDUCE.
173936*/
173937struct yyStackEntry {
173938  YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
173939  YYCODETYPE major;      /* The major token value.  This is the code
173940                         ** number for the token at this stack level */
173941  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
173942                         ** is the value of the token  */
173943};
173944typedef struct yyStackEntry yyStackEntry;
173945
173946/* The state of the parser is completely contained in an instance of
173947** the following structure */
173948struct yyParser {
173949  yyStackEntry *yytos;          /* Pointer to top element of the stack */
173950#ifdef YYTRACKMAXSTACKDEPTH
173951  int yyhwm;                    /* High-water mark of the stack */
173952#endif
173953#ifndef YYNOERRORRECOVERY
173954  int yyerrcnt;                 /* Shifts left before out of the error */
173955#endif
173956  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
173957  sqlite3ParserCTX_SDECL                /* A place to hold %extra_context */
173958  yyStackEntry *yystackEnd;           /* Last entry in the stack */
173959  yyStackEntry *yystack;              /* The parser stack */
173960  yyStackEntry yystk0[YYSTACKDEPTH];  /* Initial stack space */
173961};
173962typedef struct yyParser yyParser;
173963
173964/* #include <assert.h> */
173965#ifndef NDEBUG
173966/* #include <stdio.h> */
173967static FILE *yyTraceFILE = 0;
173968static char *yyTracePrompt = 0;
173969#endif /* NDEBUG */
173970
173971#ifndef NDEBUG
173972/*
173973** Turn parser tracing on by giving a stream to which to write the trace
173974** and a prompt to preface each trace message.  Tracing is turned off
173975** by making either argument NULL
173976**
173977** Inputs:
173978** <ul>
173979** <li> A FILE* to which trace output should be written.
173980**      If NULL, then tracing is turned off.
173981** <li> A prefix string written at the beginning of every
173982**      line of trace output.  If NULL, then tracing is
173983**      turned off.
173984** </ul>
173985**
173986** Outputs:
173987** None.
173988*/
173989SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
173990  yyTraceFILE = TraceFILE;
173991  yyTracePrompt = zTracePrompt;
173992  if( yyTraceFILE==0 ) yyTracePrompt = 0;
173993  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
173994}
173995#endif /* NDEBUG */
173996
173997#if defined(YYCOVERAGE) || !defined(NDEBUG)
173998/* For tracing shifts, the names of all terminals and nonterminals
173999** are required.  The following table supplies these names */
174000static const char *const yyTokenName[] = {
174001  /*    0 */ "$",
174002  /*    1 */ "SEMI",
174003  /*    2 */ "EXPLAIN",
174004  /*    3 */ "QUERY",
174005  /*    4 */ "PLAN",
174006  /*    5 */ "BEGIN",
174007  /*    6 */ "TRANSACTION",
174008  /*    7 */ "DEFERRED",
174009  /*    8 */ "IMMEDIATE",
174010  /*    9 */ "EXCLUSIVE",
174011  /*   10 */ "COMMIT",
174012  /*   11 */ "END",
174013  /*   12 */ "ROLLBACK",
174014  /*   13 */ "SAVEPOINT",
174015  /*   14 */ "RELEASE",
174016  /*   15 */ "TO",
174017  /*   16 */ "TABLE",
174018  /*   17 */ "CREATE",
174019  /*   18 */ "IF",
174020  /*   19 */ "NOT",
174021  /*   20 */ "EXISTS",
174022  /*   21 */ "TEMP",
174023  /*   22 */ "LP",
174024  /*   23 */ "RP",
174025  /*   24 */ "AS",
174026  /*   25 */ "COMMA",
174027  /*   26 */ "WITHOUT",
174028  /*   27 */ "ABORT",
174029  /*   28 */ "ACTION",
174030  /*   29 */ "AFTER",
174031  /*   30 */ "ANALYZE",
174032  /*   31 */ "ASC",
174033  /*   32 */ "ATTACH",
174034  /*   33 */ "BEFORE",
174035  /*   34 */ "BY",
174036  /*   35 */ "CASCADE",
174037  /*   36 */ "CAST",
174038  /*   37 */ "CONFLICT",
174039  /*   38 */ "DATABASE",
174040  /*   39 */ "DESC",
174041  /*   40 */ "DETACH",
174042  /*   41 */ "EACH",
174043  /*   42 */ "FAIL",
174044  /*   43 */ "OR",
174045  /*   44 */ "AND",
174046  /*   45 */ "IS",
174047  /*   46 */ "MATCH",
174048  /*   47 */ "LIKE_KW",
174049  /*   48 */ "BETWEEN",
174050  /*   49 */ "IN",
174051  /*   50 */ "ISNULL",
174052  /*   51 */ "NOTNULL",
174053  /*   52 */ "NE",
174054  /*   53 */ "EQ",
174055  /*   54 */ "GT",
174056  /*   55 */ "LE",
174057  /*   56 */ "LT",
174058  /*   57 */ "GE",
174059  /*   58 */ "ESCAPE",
174060  /*   59 */ "ID",
174061  /*   60 */ "COLUMNKW",
174062  /*   61 */ "DO",
174063  /*   62 */ "FOR",
174064  /*   63 */ "IGNORE",
174065  /*   64 */ "INITIALLY",
174066  /*   65 */ "INSTEAD",
174067  /*   66 */ "NO",
174068  /*   67 */ "KEY",
174069  /*   68 */ "OF",
174070  /*   69 */ "OFFSET",
174071  /*   70 */ "PRAGMA",
174072  /*   71 */ "RAISE",
174073  /*   72 */ "RECURSIVE",
174074  /*   73 */ "REPLACE",
174075  /*   74 */ "RESTRICT",
174076  /*   75 */ "ROW",
174077  /*   76 */ "ROWS",
174078  /*   77 */ "TRIGGER",
174079  /*   78 */ "VACUUM",
174080  /*   79 */ "VIEW",
174081  /*   80 */ "VIRTUAL",
174082  /*   81 */ "WITH",
174083  /*   82 */ "NULLS",
174084  /*   83 */ "FIRST",
174085  /*   84 */ "LAST",
174086  /*   85 */ "CURRENT",
174087  /*   86 */ "FOLLOWING",
174088  /*   87 */ "PARTITION",
174089  /*   88 */ "PRECEDING",
174090  /*   89 */ "RANGE",
174091  /*   90 */ "UNBOUNDED",
174092  /*   91 */ "EXCLUDE",
174093  /*   92 */ "GROUPS",
174094  /*   93 */ "OTHERS",
174095  /*   94 */ "TIES",
174096  /*   95 */ "GENERATED",
174097  /*   96 */ "ALWAYS",
174098  /*   97 */ "MATERIALIZED",
174099  /*   98 */ "REINDEX",
174100  /*   99 */ "RENAME",
174101  /*  100 */ "CTIME_KW",
174102  /*  101 */ "ANY",
174103  /*  102 */ "BITAND",
174104  /*  103 */ "BITOR",
174105  /*  104 */ "LSHIFT",
174106  /*  105 */ "RSHIFT",
174107  /*  106 */ "PLUS",
174108  /*  107 */ "MINUS",
174109  /*  108 */ "STAR",
174110  /*  109 */ "SLASH",
174111  /*  110 */ "REM",
174112  /*  111 */ "CONCAT",
174113  /*  112 */ "PTR",
174114  /*  113 */ "COLLATE",
174115  /*  114 */ "BITNOT",
174116  /*  115 */ "ON",
174117  /*  116 */ "INDEXED",
174118  /*  117 */ "STRING",
174119  /*  118 */ "JOIN_KW",
174120  /*  119 */ "CONSTRAINT",
174121  /*  120 */ "DEFAULT",
174122  /*  121 */ "NULL",
174123  /*  122 */ "PRIMARY",
174124  /*  123 */ "UNIQUE",
174125  /*  124 */ "CHECK",
174126  /*  125 */ "REFERENCES",
174127  /*  126 */ "AUTOINCR",
174128  /*  127 */ "INSERT",
174129  /*  128 */ "DELETE",
174130  /*  129 */ "UPDATE",
174131  /*  130 */ "SET",
174132  /*  131 */ "DEFERRABLE",
174133  /*  132 */ "FOREIGN",
174134  /*  133 */ "DROP",
174135  /*  134 */ "UNION",
174136  /*  135 */ "ALL",
174137  /*  136 */ "EXCEPT",
174138  /*  137 */ "INTERSECT",
174139  /*  138 */ "SELECT",
174140  /*  139 */ "VALUES",
174141  /*  140 */ "DISTINCT",
174142  /*  141 */ "DOT",
174143  /*  142 */ "FROM",
174144  /*  143 */ "JOIN",
174145  /*  144 */ "USING",
174146  /*  145 */ "ORDER",
174147  /*  146 */ "GROUP",
174148  /*  147 */ "HAVING",
174149  /*  148 */ "LIMIT",
174150  /*  149 */ "WHERE",
174151  /*  150 */ "RETURNING",
174152  /*  151 */ "INTO",
174153  /*  152 */ "NOTHING",
174154  /*  153 */ "FLOAT",
174155  /*  154 */ "BLOB",
174156  /*  155 */ "INTEGER",
174157  /*  156 */ "VARIABLE",
174158  /*  157 */ "CASE",
174159  /*  158 */ "WHEN",
174160  /*  159 */ "THEN",
174161  /*  160 */ "ELSE",
174162  /*  161 */ "INDEX",
174163  /*  162 */ "ALTER",
174164  /*  163 */ "ADD",
174165  /*  164 */ "WINDOW",
174166  /*  165 */ "OVER",
174167  /*  166 */ "FILTER",
174168  /*  167 */ "COLUMN",
174169  /*  168 */ "AGG_FUNCTION",
174170  /*  169 */ "AGG_COLUMN",
174171  /*  170 */ "TRUEFALSE",
174172  /*  171 */ "ISNOT",
174173  /*  172 */ "FUNCTION",
174174  /*  173 */ "UPLUS",
174175  /*  174 */ "UMINUS",
174176  /*  175 */ "TRUTH",
174177  /*  176 */ "REGISTER",
174178  /*  177 */ "VECTOR",
174179  /*  178 */ "SELECT_COLUMN",
174180  /*  179 */ "IF_NULL_ROW",
174181  /*  180 */ "ASTERISK",
174182  /*  181 */ "SPAN",
174183  /*  182 */ "ERROR",
174184  /*  183 */ "QNUMBER",
174185  /*  184 */ "SPACE",
174186  /*  185 */ "ILLEGAL",
174187  /*  186 */ "input",
174188  /*  187 */ "cmdlist",
174189  /*  188 */ "ecmd",
174190  /*  189 */ "cmdx",
174191  /*  190 */ "explain",
174192  /*  191 */ "cmd",
174193  /*  192 */ "transtype",
174194  /*  193 */ "trans_opt",
174195  /*  194 */ "nm",
174196  /*  195 */ "savepoint_opt",
174197  /*  196 */ "create_table",
174198  /*  197 */ "create_table_args",
174199  /*  198 */ "createkw",
174200  /*  199 */ "temp",
174201  /*  200 */ "ifnotexists",
174202  /*  201 */ "dbnm",
174203  /*  202 */ "columnlist",
174204  /*  203 */ "conslist_opt",
174205  /*  204 */ "table_option_set",
174206  /*  205 */ "select",
174207  /*  206 */ "table_option",
174208  /*  207 */ "columnname",
174209  /*  208 */ "carglist",
174210  /*  209 */ "typetoken",
174211  /*  210 */ "typename",
174212  /*  211 */ "signed",
174213  /*  212 */ "plus_num",
174214  /*  213 */ "minus_num",
174215  /*  214 */ "scanpt",
174216  /*  215 */ "scantok",
174217  /*  216 */ "ccons",
174218  /*  217 */ "term",
174219  /*  218 */ "expr",
174220  /*  219 */ "onconf",
174221  /*  220 */ "sortorder",
174222  /*  221 */ "autoinc",
174223  /*  222 */ "eidlist_opt",
174224  /*  223 */ "refargs",
174225  /*  224 */ "defer_subclause",
174226  /*  225 */ "generated",
174227  /*  226 */ "refarg",
174228  /*  227 */ "refact",
174229  /*  228 */ "init_deferred_pred_opt",
174230  /*  229 */ "conslist",
174231  /*  230 */ "tconscomma",
174232  /*  231 */ "tcons",
174233  /*  232 */ "sortlist",
174234  /*  233 */ "eidlist",
174235  /*  234 */ "defer_subclause_opt",
174236  /*  235 */ "orconf",
174237  /*  236 */ "resolvetype",
174238  /*  237 */ "raisetype",
174239  /*  238 */ "ifexists",
174240  /*  239 */ "fullname",
174241  /*  240 */ "selectnowith",
174242  /*  241 */ "oneselect",
174243  /*  242 */ "wqlist",
174244  /*  243 */ "multiselect_op",
174245  /*  244 */ "distinct",
174246  /*  245 */ "selcollist",
174247  /*  246 */ "from",
174248  /*  247 */ "where_opt",
174249  /*  248 */ "groupby_opt",
174250  /*  249 */ "having_opt",
174251  /*  250 */ "orderby_opt",
174252  /*  251 */ "limit_opt",
174253  /*  252 */ "window_clause",
174254  /*  253 */ "values",
174255  /*  254 */ "nexprlist",
174256  /*  255 */ "mvalues",
174257  /*  256 */ "sclp",
174258  /*  257 */ "as",
174259  /*  258 */ "seltablist",
174260  /*  259 */ "stl_prefix",
174261  /*  260 */ "joinop",
174262  /*  261 */ "on_using",
174263  /*  262 */ "indexed_by",
174264  /*  263 */ "exprlist",
174265  /*  264 */ "xfullname",
174266  /*  265 */ "idlist",
174267  /*  266 */ "indexed_opt",
174268  /*  267 */ "nulls",
174269  /*  268 */ "with",
174270  /*  269 */ "where_opt_ret",
174271  /*  270 */ "setlist",
174272  /*  271 */ "insert_cmd",
174273  /*  272 */ "idlist_opt",
174274  /*  273 */ "upsert",
174275  /*  274 */ "returning",
174276  /*  275 */ "filter_over",
174277  /*  276 */ "likeop",
174278  /*  277 */ "between_op",
174279  /*  278 */ "in_op",
174280  /*  279 */ "paren_exprlist",
174281  /*  280 */ "case_operand",
174282  /*  281 */ "case_exprlist",
174283  /*  282 */ "case_else",
174284  /*  283 */ "uniqueflag",
174285  /*  284 */ "collate",
174286  /*  285 */ "vinto",
174287  /*  286 */ "nmnum",
174288  /*  287 */ "trigger_decl",
174289  /*  288 */ "trigger_cmd_list",
174290  /*  289 */ "trigger_time",
174291  /*  290 */ "trigger_event",
174292  /*  291 */ "foreach_clause",
174293  /*  292 */ "when_clause",
174294  /*  293 */ "trigger_cmd",
174295  /*  294 */ "trnm",
174296  /*  295 */ "tridxby",
174297  /*  296 */ "database_kw_opt",
174298  /*  297 */ "key_opt",
174299  /*  298 */ "add_column_fullname",
174300  /*  299 */ "kwcolumn_opt",
174301  /*  300 */ "create_vtab",
174302  /*  301 */ "vtabarglist",
174303  /*  302 */ "vtabarg",
174304  /*  303 */ "vtabargtoken",
174305  /*  304 */ "lp",
174306  /*  305 */ "anylist",
174307  /*  306 */ "wqitem",
174308  /*  307 */ "wqas",
174309  /*  308 */ "withnm",
174310  /*  309 */ "windowdefn_list",
174311  /*  310 */ "windowdefn",
174312  /*  311 */ "window",
174313  /*  312 */ "frame_opt",
174314  /*  313 */ "part_opt",
174315  /*  314 */ "filter_clause",
174316  /*  315 */ "over_clause",
174317  /*  316 */ "range_or_rows",
174318  /*  317 */ "frame_bound",
174319  /*  318 */ "frame_bound_s",
174320  /*  319 */ "frame_bound_e",
174321  /*  320 */ "frame_exclude_opt",
174322  /*  321 */ "frame_exclude",
174323};
174324#endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */
174325
174326#ifndef NDEBUG
174327/* For tracing reduce actions, the names of all rules are required.
174328*/
174329static const char *const yyRuleName[] = {
174330 /*   0 */ "explain ::= EXPLAIN",
174331 /*   1 */ "explain ::= EXPLAIN QUERY PLAN",
174332 /*   2 */ "cmdx ::= cmd",
174333 /*   3 */ "cmd ::= BEGIN transtype trans_opt",
174334 /*   4 */ "transtype ::=",
174335 /*   5 */ "transtype ::= DEFERRED",
174336 /*   6 */ "transtype ::= IMMEDIATE",
174337 /*   7 */ "transtype ::= EXCLUSIVE",
174338 /*   8 */ "cmd ::= COMMIT|END trans_opt",
174339 /*   9 */ "cmd ::= ROLLBACK trans_opt",
174340 /*  10 */ "cmd ::= SAVEPOINT nm",
174341 /*  11 */ "cmd ::= RELEASE savepoint_opt nm",
174342 /*  12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
174343 /*  13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
174344 /*  14 */ "createkw ::= CREATE",
174345 /*  15 */ "ifnotexists ::=",
174346 /*  16 */ "ifnotexists ::= IF NOT EXISTS",
174347 /*  17 */ "temp ::= TEMP",
174348 /*  18 */ "temp ::=",
174349 /*  19 */ "create_table_args ::= LP columnlist conslist_opt RP table_option_set",
174350 /*  20 */ "create_table_args ::= AS select",
174351 /*  21 */ "table_option_set ::=",
174352 /*  22 */ "table_option_set ::= table_option_set COMMA table_option",
174353 /*  23 */ "table_option ::= WITHOUT nm",
174354 /*  24 */ "table_option ::= nm",
174355 /*  25 */ "columnname ::= nm typetoken",
174356 /*  26 */ "typetoken ::=",
174357 /*  27 */ "typetoken ::= typename LP signed RP",
174358 /*  28 */ "typetoken ::= typename LP signed COMMA signed RP",
174359 /*  29 */ "typename ::= typename ID|STRING",
174360 /*  30 */ "scanpt ::=",
174361 /*  31 */ "scantok ::=",
174362 /*  32 */ "ccons ::= CONSTRAINT nm",
174363 /*  33 */ "ccons ::= DEFAULT scantok term",
174364 /*  34 */ "ccons ::= DEFAULT LP expr RP",
174365 /*  35 */ "ccons ::= DEFAULT PLUS scantok term",
174366 /*  36 */ "ccons ::= DEFAULT MINUS scantok term",
174367 /*  37 */ "ccons ::= DEFAULT scantok ID|INDEXED",
174368 /*  38 */ "ccons ::= NOT NULL onconf",
174369 /*  39 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
174370 /*  40 */ "ccons ::= UNIQUE onconf",
174371 /*  41 */ "ccons ::= CHECK LP expr RP",
174372 /*  42 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
174373 /*  43 */ "ccons ::= defer_subclause",
174374 /*  44 */ "ccons ::= COLLATE ID|STRING",
174375 /*  45 */ "generated ::= LP expr RP",
174376 /*  46 */ "generated ::= LP expr RP ID",
174377 /*  47 */ "autoinc ::=",
174378 /*  48 */ "autoinc ::= AUTOINCR",
174379 /*  49 */ "refargs ::=",
174380 /*  50 */ "refargs ::= refargs refarg",
174381 /*  51 */ "refarg ::= MATCH nm",
174382 /*  52 */ "refarg ::= ON INSERT refact",
174383 /*  53 */ "refarg ::= ON DELETE refact",
174384 /*  54 */ "refarg ::= ON UPDATE refact",
174385 /*  55 */ "refact ::= SET NULL",
174386 /*  56 */ "refact ::= SET DEFAULT",
174387 /*  57 */ "refact ::= CASCADE",
174388 /*  58 */ "refact ::= RESTRICT",
174389 /*  59 */ "refact ::= NO ACTION",
174390 /*  60 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
174391 /*  61 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
174392 /*  62 */ "init_deferred_pred_opt ::=",
174393 /*  63 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
174394 /*  64 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
174395 /*  65 */ "conslist_opt ::=",
174396 /*  66 */ "tconscomma ::= COMMA",
174397 /*  67 */ "tcons ::= CONSTRAINT nm",
174398 /*  68 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
174399 /*  69 */ "tcons ::= UNIQUE LP sortlist RP onconf",
174400 /*  70 */ "tcons ::= CHECK LP expr RP onconf",
174401 /*  71 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
174402 /*  72 */ "defer_subclause_opt ::=",
174403 /*  73 */ "onconf ::=",
174404 /*  74 */ "onconf ::= ON CONFLICT resolvetype",
174405 /*  75 */ "orconf ::=",
174406 /*  76 */ "orconf ::= OR resolvetype",
174407 /*  77 */ "resolvetype ::= IGNORE",
174408 /*  78 */ "resolvetype ::= REPLACE",
174409 /*  79 */ "cmd ::= DROP TABLE ifexists fullname",
174410 /*  80 */ "ifexists ::= IF EXISTS",
174411 /*  81 */ "ifexists ::=",
174412 /*  82 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
174413 /*  83 */ "cmd ::= DROP VIEW ifexists fullname",
174414 /*  84 */ "cmd ::= select",
174415 /*  85 */ "select ::= WITH wqlist selectnowith",
174416 /*  86 */ "select ::= WITH RECURSIVE wqlist selectnowith",
174417 /*  87 */ "select ::= selectnowith",
174418 /*  88 */ "selectnowith ::= selectnowith multiselect_op oneselect",
174419 /*  89 */ "multiselect_op ::= UNION",
174420 /*  90 */ "multiselect_op ::= UNION ALL",
174421 /*  91 */ "multiselect_op ::= EXCEPT|INTERSECT",
174422 /*  92 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
174423 /*  93 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt",
174424 /*  94 */ "values ::= VALUES LP nexprlist RP",
174425 /*  95 */ "oneselect ::= mvalues",
174426 /*  96 */ "mvalues ::= values COMMA LP nexprlist RP",
174427 /*  97 */ "mvalues ::= mvalues COMMA LP nexprlist RP",
174428 /*  98 */ "distinct ::= DISTINCT",
174429 /*  99 */ "distinct ::= ALL",
174430 /* 100 */ "distinct ::=",
174431 /* 101 */ "sclp ::=",
174432 /* 102 */ "selcollist ::= sclp scanpt expr scanpt as",
174433 /* 103 */ "selcollist ::= sclp scanpt STAR",
174434 /* 104 */ "selcollist ::= sclp scanpt nm DOT STAR",
174435 /* 105 */ "as ::= AS nm",
174436 /* 106 */ "as ::=",
174437 /* 107 */ "from ::=",
174438 /* 108 */ "from ::= FROM seltablist",
174439 /* 109 */ "stl_prefix ::= seltablist joinop",
174440 /* 110 */ "stl_prefix ::=",
174441 /* 111 */ "seltablist ::= stl_prefix nm dbnm as on_using",
174442 /* 112 */ "seltablist ::= stl_prefix nm dbnm as indexed_by on_using",
174443 /* 113 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_using",
174444 /* 114 */ "seltablist ::= stl_prefix LP select RP as on_using",
174445 /* 115 */ "seltablist ::= stl_prefix LP seltablist RP as on_using",
174446 /* 116 */ "dbnm ::=",
174447 /* 117 */ "dbnm ::= DOT nm",
174448 /* 118 */ "fullname ::= nm",
174449 /* 119 */ "fullname ::= nm DOT nm",
174450 /* 120 */ "xfullname ::= nm",
174451 /* 121 */ "xfullname ::= nm DOT nm",
174452 /* 122 */ "xfullname ::= nm DOT nm AS nm",
174453 /* 123 */ "xfullname ::= nm AS nm",
174454 /* 124 */ "joinop ::= COMMA|JOIN",
174455 /* 125 */ "joinop ::= JOIN_KW JOIN",
174456 /* 126 */ "joinop ::= JOIN_KW nm JOIN",
174457 /* 127 */ "joinop ::= JOIN_KW nm nm JOIN",
174458 /* 128 */ "on_using ::= ON expr",
174459 /* 129 */ "on_using ::= USING LP idlist RP",
174460 /* 130 */ "on_using ::=",
174461 /* 131 */ "indexed_opt ::=",
174462 /* 132 */ "indexed_by ::= INDEXED BY nm",
174463 /* 133 */ "indexed_by ::= NOT INDEXED",
174464 /* 134 */ "orderby_opt ::=",
174465 /* 135 */ "orderby_opt ::= ORDER BY sortlist",
174466 /* 136 */ "sortlist ::= sortlist COMMA expr sortorder nulls",
174467 /* 137 */ "sortlist ::= expr sortorder nulls",
174468 /* 138 */ "sortorder ::= ASC",
174469 /* 139 */ "sortorder ::= DESC",
174470 /* 140 */ "sortorder ::=",
174471 /* 141 */ "nulls ::= NULLS FIRST",
174472 /* 142 */ "nulls ::= NULLS LAST",
174473 /* 143 */ "nulls ::=",
174474 /* 144 */ "groupby_opt ::=",
174475 /* 145 */ "groupby_opt ::= GROUP BY nexprlist",
174476 /* 146 */ "having_opt ::=",
174477 /* 147 */ "having_opt ::= HAVING expr",
174478 /* 148 */ "limit_opt ::=",
174479 /* 149 */ "limit_opt ::= LIMIT expr",
174480 /* 150 */ "limit_opt ::= LIMIT expr OFFSET expr",
174481 /* 151 */ "limit_opt ::= LIMIT expr COMMA expr",
174482 /* 152 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret",
174483 /* 153 */ "where_opt ::=",
174484 /* 154 */ "where_opt ::= WHERE expr",
174485 /* 155 */ "where_opt_ret ::=",
174486 /* 156 */ "where_opt_ret ::= WHERE expr",
174487 /* 157 */ "where_opt_ret ::= RETURNING selcollist",
174488 /* 158 */ "where_opt_ret ::= WHERE expr RETURNING selcollist",
174489 /* 159 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret",
174490 /* 160 */ "setlist ::= setlist COMMA nm EQ expr",
174491 /* 161 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
174492 /* 162 */ "setlist ::= nm EQ expr",
174493 /* 163 */ "setlist ::= LP idlist RP EQ expr",
174494 /* 164 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert",
174495 /* 165 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning",
174496 /* 166 */ "upsert ::=",
174497 /* 167 */ "upsert ::= RETURNING selcollist",
174498 /* 168 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert",
174499 /* 169 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert",
174500 /* 170 */ "upsert ::= ON CONFLICT DO NOTHING returning",
174501 /* 171 */ "upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning",
174502 /* 172 */ "returning ::= RETURNING selcollist",
174503 /* 173 */ "insert_cmd ::= INSERT orconf",
174504 /* 174 */ "insert_cmd ::= REPLACE",
174505 /* 175 */ "idlist_opt ::=",
174506 /* 176 */ "idlist_opt ::= LP idlist RP",
174507 /* 177 */ "idlist ::= idlist COMMA nm",
174508 /* 178 */ "idlist ::= nm",
174509 /* 179 */ "expr ::= LP expr RP",
174510 /* 180 */ "expr ::= ID|INDEXED|JOIN_KW",
174511 /* 181 */ "expr ::= nm DOT nm",
174512 /* 182 */ "expr ::= nm DOT nm DOT nm",
174513 /* 183 */ "term ::= NULL|FLOAT|BLOB",
174514 /* 184 */ "term ::= STRING",
174515 /* 185 */ "term ::= INTEGER",
174516 /* 186 */ "expr ::= VARIABLE",
174517 /* 187 */ "expr ::= expr COLLATE ID|STRING",
174518 /* 188 */ "expr ::= CAST LP expr AS typetoken RP",
174519 /* 189 */ "expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP",
174520 /* 190 */ "expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP",
174521 /* 191 */ "expr ::= ID|INDEXED|JOIN_KW LP STAR RP",
174522 /* 192 */ "expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over",
174523 /* 193 */ "expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP filter_over",
174524 /* 194 */ "expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over",
174525 /* 195 */ "term ::= CTIME_KW",
174526 /* 196 */ "expr ::= LP nexprlist COMMA expr RP",
174527 /* 197 */ "expr ::= expr AND expr",
174528 /* 198 */ "expr ::= expr OR expr",
174529 /* 199 */ "expr ::= expr LT|GT|GE|LE expr",
174530 /* 200 */ "expr ::= expr EQ|NE expr",
174531 /* 201 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
174532 /* 202 */ "expr ::= expr PLUS|MINUS expr",
174533 /* 203 */ "expr ::= expr STAR|SLASH|REM expr",
174534 /* 204 */ "expr ::= expr CONCAT expr",
174535 /* 205 */ "likeop ::= NOT LIKE_KW|MATCH",
174536 /* 206 */ "expr ::= expr likeop expr",
174537 /* 207 */ "expr ::= expr likeop expr ESCAPE expr",
174538 /* 208 */ "expr ::= expr ISNULL|NOTNULL",
174539 /* 209 */ "expr ::= expr NOT NULL",
174540 /* 210 */ "expr ::= expr IS expr",
174541 /* 211 */ "expr ::= expr IS NOT expr",
174542 /* 212 */ "expr ::= expr IS NOT DISTINCT FROM expr",
174543 /* 213 */ "expr ::= expr IS DISTINCT FROM expr",
174544 /* 214 */ "expr ::= NOT expr",
174545 /* 215 */ "expr ::= BITNOT expr",
174546 /* 216 */ "expr ::= PLUS|MINUS expr",
174547 /* 217 */ "expr ::= expr PTR expr",
174548 /* 218 */ "between_op ::= BETWEEN",
174549 /* 219 */ "between_op ::= NOT BETWEEN",
174550 /* 220 */ "expr ::= expr between_op expr AND expr",
174551 /* 221 */ "in_op ::= IN",
174552 /* 222 */ "in_op ::= NOT IN",
174553 /* 223 */ "expr ::= expr in_op LP exprlist RP",
174554 /* 224 */ "expr ::= LP select RP",
174555 /* 225 */ "expr ::= expr in_op LP select RP",
174556 /* 226 */ "expr ::= expr in_op nm dbnm paren_exprlist",
174557 /* 227 */ "expr ::= EXISTS LP select RP",
174558 /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
174559 /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
174560 /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
174561 /* 231 */ "case_else ::= ELSE expr",
174562 /* 232 */ "case_else ::=",
174563 /* 233 */ "case_operand ::=",
174564 /* 234 */ "exprlist ::=",
174565 /* 235 */ "nexprlist ::= nexprlist COMMA expr",
174566 /* 236 */ "nexprlist ::= expr",
174567 /* 237 */ "paren_exprlist ::=",
174568 /* 238 */ "paren_exprlist ::= LP exprlist RP",
174569 /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
174570 /* 240 */ "uniqueflag ::= UNIQUE",
174571 /* 241 */ "uniqueflag ::=",
174572 /* 242 */ "eidlist_opt ::=",
174573 /* 243 */ "eidlist_opt ::= LP eidlist RP",
174574 /* 244 */ "eidlist ::= eidlist COMMA nm collate sortorder",
174575 /* 245 */ "eidlist ::= nm collate sortorder",
174576 /* 246 */ "collate ::=",
174577 /* 247 */ "collate ::= COLLATE ID|STRING",
174578 /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
174579 /* 249 */ "cmd ::= VACUUM vinto",
174580 /* 250 */ "cmd ::= VACUUM nm vinto",
174581 /* 251 */ "vinto ::= INTO expr",
174582 /* 252 */ "vinto ::=",
174583 /* 253 */ "cmd ::= PRAGMA nm dbnm",
174584 /* 254 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
174585 /* 255 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
174586 /* 256 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
174587 /* 257 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
174588 /* 258 */ "plus_num ::= PLUS INTEGER|FLOAT",
174589 /* 259 */ "minus_num ::= MINUS INTEGER|FLOAT",
174590 /* 260 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
174591 /* 261 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
174592 /* 262 */ "trigger_time ::= BEFORE|AFTER",
174593 /* 263 */ "trigger_time ::= INSTEAD OF",
174594 /* 264 */ "trigger_time ::=",
174595 /* 265 */ "trigger_event ::= DELETE|INSERT",
174596 /* 266 */ "trigger_event ::= UPDATE",
174597 /* 267 */ "trigger_event ::= UPDATE OF idlist",
174598 /* 268 */ "when_clause ::=",
174599 /* 269 */ "when_clause ::= WHEN expr",
174600 /* 270 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
174601 /* 271 */ "trigger_cmd_list ::= trigger_cmd SEMI",
174602 /* 272 */ "trnm ::= nm DOT nm",
174603 /* 273 */ "tridxby ::= INDEXED BY nm",
174604 /* 274 */ "tridxby ::= NOT INDEXED",
174605 /* 275 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt",
174606 /* 276 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
174607 /* 277 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
174608 /* 278 */ "trigger_cmd ::= scanpt select scanpt",
174609 /* 279 */ "expr ::= RAISE LP IGNORE RP",
174610 /* 280 */ "expr ::= RAISE LP raisetype COMMA nm RP",
174611 /* 281 */ "raisetype ::= ROLLBACK",
174612 /* 282 */ "raisetype ::= ABORT",
174613 /* 283 */ "raisetype ::= FAIL",
174614 /* 284 */ "cmd ::= DROP TRIGGER ifexists fullname",
174615 /* 285 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
174616 /* 286 */ "cmd ::= DETACH database_kw_opt expr",
174617 /* 287 */ "key_opt ::=",
174618 /* 288 */ "key_opt ::= KEY expr",
174619 /* 289 */ "cmd ::= REINDEX",
174620 /* 290 */ "cmd ::= REINDEX nm dbnm",
174621 /* 291 */ "cmd ::= ANALYZE",
174622 /* 292 */ "cmd ::= ANALYZE nm dbnm",
174623 /* 293 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
174624 /* 294 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
174625 /* 295 */ "cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm",
174626 /* 296 */ "add_column_fullname ::= fullname",
174627 /* 297 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
174628 /* 298 */ "cmd ::= create_vtab",
174629 /* 299 */ "cmd ::= create_vtab LP vtabarglist RP",
174630 /* 300 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
174631 /* 301 */ "vtabarg ::=",
174632 /* 302 */ "vtabargtoken ::= ANY",
174633 /* 303 */ "vtabargtoken ::= lp anylist RP",
174634 /* 304 */ "lp ::= LP",
174635 /* 305 */ "with ::= WITH wqlist",
174636 /* 306 */ "with ::= WITH RECURSIVE wqlist",
174637 /* 307 */ "wqas ::= AS",
174638 /* 308 */ "wqas ::= AS MATERIALIZED",
174639 /* 309 */ "wqas ::= AS NOT MATERIALIZED",
174640 /* 310 */ "wqitem ::= withnm eidlist_opt wqas LP select RP",
174641 /* 311 */ "withnm ::= nm",
174642 /* 312 */ "wqlist ::= wqitem",
174643 /* 313 */ "wqlist ::= wqlist COMMA wqitem",
174644 /* 314 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
174645 /* 315 */ "windowdefn ::= nm AS LP window RP",
174646 /* 316 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt",
174647 /* 317 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt",
174648 /* 318 */ "window ::= ORDER BY sortlist frame_opt",
174649 /* 319 */ "window ::= nm ORDER BY sortlist frame_opt",
174650 /* 320 */ "window ::= nm frame_opt",
174651 /* 321 */ "frame_opt ::=",
174652 /* 322 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt",
174653 /* 323 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt",
174654 /* 324 */ "range_or_rows ::= RANGE|ROWS|GROUPS",
174655 /* 325 */ "frame_bound_s ::= frame_bound",
174656 /* 326 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
174657 /* 327 */ "frame_bound_e ::= frame_bound",
174658 /* 328 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
174659 /* 329 */ "frame_bound ::= expr PRECEDING|FOLLOWING",
174660 /* 330 */ "frame_bound ::= CURRENT ROW",
174661 /* 331 */ "frame_exclude_opt ::=",
174662 /* 332 */ "frame_exclude_opt ::= EXCLUDE frame_exclude",
174663 /* 333 */ "frame_exclude ::= NO OTHERS",
174664 /* 334 */ "frame_exclude ::= CURRENT ROW",
174665 /* 335 */ "frame_exclude ::= GROUP|TIES",
174666 /* 336 */ "window_clause ::= WINDOW windowdefn_list",
174667 /* 337 */ "filter_over ::= filter_clause over_clause",
174668 /* 338 */ "filter_over ::= over_clause",
174669 /* 339 */ "filter_over ::= filter_clause",
174670 /* 340 */ "over_clause ::= OVER LP window RP",
174671 /* 341 */ "over_clause ::= OVER nm",
174672 /* 342 */ "filter_clause ::= FILTER LP WHERE expr RP",
174673 /* 343 */ "term ::= QNUMBER",
174674 /* 344 */ "input ::= cmdlist",
174675 /* 345 */ "cmdlist ::= cmdlist ecmd",
174676 /* 346 */ "cmdlist ::= ecmd",
174677 /* 347 */ "ecmd ::= SEMI",
174678 /* 348 */ "ecmd ::= cmdx SEMI",
174679 /* 349 */ "ecmd ::= explain cmdx SEMI",
174680 /* 350 */ "trans_opt ::=",
174681 /* 351 */ "trans_opt ::= TRANSACTION",
174682 /* 352 */ "trans_opt ::= TRANSACTION nm",
174683 /* 353 */ "savepoint_opt ::= SAVEPOINT",
174684 /* 354 */ "savepoint_opt ::=",
174685 /* 355 */ "cmd ::= create_table create_table_args",
174686 /* 356 */ "table_option_set ::= table_option",
174687 /* 357 */ "columnlist ::= columnlist COMMA columnname carglist",
174688 /* 358 */ "columnlist ::= columnname carglist",
174689 /* 359 */ "nm ::= ID|INDEXED|JOIN_KW",
174690 /* 360 */ "nm ::= STRING",
174691 /* 361 */ "typetoken ::= typename",
174692 /* 362 */ "typename ::= ID|STRING",
174693 /* 363 */ "signed ::= plus_num",
174694 /* 364 */ "signed ::= minus_num",
174695 /* 365 */ "carglist ::= carglist ccons",
174696 /* 366 */ "carglist ::=",
174697 /* 367 */ "ccons ::= NULL onconf",
174698 /* 368 */ "ccons ::= GENERATED ALWAYS AS generated",
174699 /* 369 */ "ccons ::= AS generated",
174700 /* 370 */ "conslist_opt ::= COMMA conslist",
174701 /* 371 */ "conslist ::= conslist tconscomma tcons",
174702 /* 372 */ "conslist ::= tcons",
174703 /* 373 */ "tconscomma ::=",
174704 /* 374 */ "defer_subclause_opt ::= defer_subclause",
174705 /* 375 */ "resolvetype ::= raisetype",
174706 /* 376 */ "selectnowith ::= oneselect",
174707 /* 377 */ "oneselect ::= values",
174708 /* 378 */ "sclp ::= selcollist COMMA",
174709 /* 379 */ "as ::= ID|STRING",
174710 /* 380 */ "indexed_opt ::= indexed_by",
174711 /* 381 */ "returning ::=",
174712 /* 382 */ "expr ::= term",
174713 /* 383 */ "likeop ::= LIKE_KW|MATCH",
174714 /* 384 */ "case_operand ::= expr",
174715 /* 385 */ "exprlist ::= nexprlist",
174716 /* 386 */ "nmnum ::= plus_num",
174717 /* 387 */ "nmnum ::= nm",
174718 /* 388 */ "nmnum ::= ON",
174719 /* 389 */ "nmnum ::= DELETE",
174720 /* 390 */ "nmnum ::= DEFAULT",
174721 /* 391 */ "plus_num ::= INTEGER|FLOAT",
174722 /* 392 */ "foreach_clause ::=",
174723 /* 393 */ "foreach_clause ::= FOR EACH ROW",
174724 /* 394 */ "trnm ::= nm",
174725 /* 395 */ "tridxby ::=",
174726 /* 396 */ "database_kw_opt ::= DATABASE",
174727 /* 397 */ "database_kw_opt ::=",
174728 /* 398 */ "kwcolumn_opt ::=",
174729 /* 399 */ "kwcolumn_opt ::= COLUMNKW",
174730 /* 400 */ "vtabarglist ::= vtabarg",
174731 /* 401 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
174732 /* 402 */ "vtabarg ::= vtabarg vtabargtoken",
174733 /* 403 */ "anylist ::=",
174734 /* 404 */ "anylist ::= anylist LP anylist RP",
174735 /* 405 */ "anylist ::= anylist ANY",
174736 /* 406 */ "with ::=",
174737 /* 407 */ "windowdefn_list ::= windowdefn",
174738 /* 408 */ "window ::= frame_opt",
174739};
174740#endif /* NDEBUG */
174741
174742
174743#if YYGROWABLESTACK
174744/*
174745** Try to increase the size of the parser stack.  Return the number
174746** of errors.  Return 0 on success.
174747*/
174748static int yyGrowStack(yyParser *p){
174749  int oldSize = 1 + (int)(p->yystackEnd - p->yystack);
174750  int newSize;
174751  int idx;
174752  yyStackEntry *pNew;
174753
174754  newSize = oldSize*2 + 100;
174755  idx = (int)(p->yytos - p->yystack);
174756  if( p->yystack==p->yystk0 ){
174757    pNew = YYREALLOC(0, newSize*sizeof(pNew[0]));
174758    if( pNew==0 ) return 1;
174759    memcpy(pNew, p->yystack, oldSize*sizeof(pNew[0]));
174760  }else{
174761    pNew = YYREALLOC(p->yystack, newSize*sizeof(pNew[0]));
174762    if( pNew==0 ) return 1;
174763  }
174764  p->yystack = pNew;
174765  p->yytos = &p->yystack[idx];
174766#ifndef NDEBUG
174767  if( yyTraceFILE ){
174768    fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
174769            yyTracePrompt, oldSize, newSize);
174770  }
174771#endif
174772  p->yystackEnd = &p->yystack[newSize-1];
174773  return 0;
174774}
174775#endif /* YYGROWABLESTACK */
174776
174777#if !YYGROWABLESTACK
174778/* For builds that do no have a growable stack, yyGrowStack always
174779** returns an error.
174780*/
174781# define yyGrowStack(X) 1
174782#endif
174783
174784/* Datatype of the argument to the memory allocated passed as the
174785** second argument to sqlite3ParserAlloc() below.  This can be changed by
174786** putting an appropriate #define in the %include section of the input
174787** grammar.
174788*/
174789#ifndef YYMALLOCARGTYPE
174790# define YYMALLOCARGTYPE size_t
174791#endif
174792
174793/* Initialize a new parser that has already been allocated.
174794*/
174795SQLITE_PRIVATE void sqlite3ParserInit(void *yypRawParser sqlite3ParserCTX_PDECL){
174796  yyParser *yypParser = (yyParser*)yypRawParser;
174797  sqlite3ParserCTX_STORE
174798#ifdef YYTRACKMAXSTACKDEPTH
174799  yypParser->yyhwm = 0;
174800#endif
174801  yypParser->yystack = yypParser->yystk0;
174802  yypParser->yystackEnd = &yypParser->yystack[YYSTACKDEPTH-1];
174803#ifndef YYNOERRORRECOVERY
174804  yypParser->yyerrcnt = -1;
174805#endif
174806  yypParser->yytos = yypParser->yystack;
174807  yypParser->yystack[0].stateno = 0;
174808  yypParser->yystack[0].major = 0;
174809}
174810
174811#ifndef sqlite3Parser_ENGINEALWAYSONSTACK
174812/*
174813** This function allocates a new parser.
174814** The only argument is a pointer to a function which works like
174815** malloc.
174816**
174817** Inputs:
174818** A pointer to the function used to allocate memory.
174819**
174820** Outputs:
174821** A pointer to a parser.  This pointer is used in subsequent calls
174822** to sqlite3Parser and sqlite3ParserFree.
174823*/
174824SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE) sqlite3ParserCTX_PDECL){
174825  yyParser *yypParser;
174826  yypParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
174827  if( yypParser ){
174828    sqlite3ParserCTX_STORE
174829    sqlite3ParserInit(yypParser sqlite3ParserCTX_PARAM);
174830  }
174831  return (void*)yypParser;
174832}
174833#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
174834
174835
174836/* The following function deletes the "minor type" or semantic value
174837** associated with a symbol.  The symbol can be either a terminal
174838** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
174839** a pointer to the value to be deleted.  The code used to do the
174840** deletions is derived from the %destructor and/or %token_destructor
174841** directives of the input grammar.
174842*/
174843static void yy_destructor(
174844  yyParser *yypParser,    /* The parser */
174845  YYCODETYPE yymajor,     /* Type code for object to destroy */
174846  YYMINORTYPE *yypminor   /* The object to be destroyed */
174847){
174848  sqlite3ParserARG_FETCH
174849  sqlite3ParserCTX_FETCH
174850  switch( yymajor ){
174851    /* Here is inserted the actions which take place when a
174852    ** terminal or non-terminal is destroyed.  This can happen
174853    ** when the symbol is popped from the stack during a
174854    ** reduce or during error processing or when a parser is
174855    ** being destroyed before it is finished parsing.
174856    **
174857    ** Note: during a reduce, the only symbols destroyed are those
174858    ** which appear on the RHS of the rule, but which are *not* used
174859    ** inside the C code.
174860    */
174861/********* Begin destructor definitions ***************************************/
174862    case 205: /* select */
174863    case 240: /* selectnowith */
174864    case 241: /* oneselect */
174865    case 253: /* values */
174866    case 255: /* mvalues */
174867{
174868sqlite3SelectDelete(pParse->db, (yypminor->yy555));
174869}
174870      break;
174871    case 217: /* term */
174872    case 218: /* expr */
174873    case 247: /* where_opt */
174874    case 249: /* having_opt */
174875    case 269: /* where_opt_ret */
174876    case 280: /* case_operand */
174877    case 282: /* case_else */
174878    case 285: /* vinto */
174879    case 292: /* when_clause */
174880    case 297: /* key_opt */
174881    case 314: /* filter_clause */
174882{
174883sqlite3ExprDelete(pParse->db, (yypminor->yy454));
174884}
174885      break;
174886    case 222: /* eidlist_opt */
174887    case 232: /* sortlist */
174888    case 233: /* eidlist */
174889    case 245: /* selcollist */
174890    case 248: /* groupby_opt */
174891    case 250: /* orderby_opt */
174892    case 254: /* nexprlist */
174893    case 256: /* sclp */
174894    case 263: /* exprlist */
174895    case 270: /* setlist */
174896    case 279: /* paren_exprlist */
174897    case 281: /* case_exprlist */
174898    case 313: /* part_opt */
174899{
174900sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
174901}
174902      break;
174903    case 239: /* fullname */
174904    case 246: /* from */
174905    case 258: /* seltablist */
174906    case 259: /* stl_prefix */
174907    case 264: /* xfullname */
174908{
174909sqlite3SrcListDelete(pParse->db, (yypminor->yy203));
174910}
174911      break;
174912    case 242: /* wqlist */
174913{
174914sqlite3WithDelete(pParse->db, (yypminor->yy59));
174915}
174916      break;
174917    case 252: /* window_clause */
174918    case 309: /* windowdefn_list */
174919{
174920sqlite3WindowListDelete(pParse->db, (yypminor->yy211));
174921}
174922      break;
174923    case 265: /* idlist */
174924    case 272: /* idlist_opt */
174925{
174926sqlite3IdListDelete(pParse->db, (yypminor->yy132));
174927}
174928      break;
174929    case 275: /* filter_over */
174930    case 310: /* windowdefn */
174931    case 311: /* window */
174932    case 312: /* frame_opt */
174933    case 315: /* over_clause */
174934{
174935sqlite3WindowDelete(pParse->db, (yypminor->yy211));
174936}
174937      break;
174938    case 288: /* trigger_cmd_list */
174939    case 293: /* trigger_cmd */
174940{
174941sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy427));
174942}
174943      break;
174944    case 290: /* trigger_event */
174945{
174946sqlite3IdListDelete(pParse->db, (yypminor->yy286).b);
174947}
174948      break;
174949    case 317: /* frame_bound */
174950    case 318: /* frame_bound_s */
174951    case 319: /* frame_bound_e */
174952{
174953sqlite3ExprDelete(pParse->db, (yypminor->yy509).pExpr);
174954}
174955      break;
174956/********* End destructor definitions *****************************************/
174957    default:  break;   /* If no destructor action specified: do nothing */
174958  }
174959}
174960
174961/*
174962** Pop the parser's stack once.
174963**
174964** If there is a destructor routine associated with the token which
174965** is popped from the stack, then call it.
174966*/
174967static void yy_pop_parser_stack(yyParser *pParser){
174968  yyStackEntry *yytos;
174969  assert( pParser->yytos!=0 );
174970  assert( pParser->yytos > pParser->yystack );
174971  yytos = pParser->yytos--;
174972#ifndef NDEBUG
174973  if( yyTraceFILE ){
174974    fprintf(yyTraceFILE,"%sPopping %s\n",
174975      yyTracePrompt,
174976      yyTokenName[yytos->major]);
174977  }
174978#endif
174979  yy_destructor(pParser, yytos->major, &yytos->minor);
174980}
174981
174982/*
174983** Clear all secondary memory allocations from the parser
174984*/
174985SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
174986  yyParser *pParser = (yyParser*)p;
174987
174988  /* In-lined version of calling yy_pop_parser_stack() for each
174989  ** element left in the stack */
174990  yyStackEntry *yytos = pParser->yytos;
174991  while( yytos>pParser->yystack ){
174992#ifndef NDEBUG
174993    if( yyTraceFILE ){
174994      fprintf(yyTraceFILE,"%sPopping %s\n",
174995        yyTracePrompt,
174996        yyTokenName[yytos->major]);
174997    }
174998#endif
174999    if( yytos->major>=YY_MIN_DSTRCTR ){
175000      yy_destructor(pParser, yytos->major, &yytos->minor);
175001    }
175002    yytos--;
175003  }
175004
175005#if YYGROWABLESTACK
175006  if( pParser->yystack!=pParser->yystk0 ) YYFREE(pParser->yystack);
175007#endif
175008}
175009
175010#ifndef sqlite3Parser_ENGINEALWAYSONSTACK
175011/*
175012** Deallocate and destroy a parser.  Destructors are called for
175013** all stack elements before shutting the parser down.
175014**
175015** If the YYPARSEFREENEVERNULL macro exists (for example because it
175016** is defined in a %include section of the input grammar) then it is
175017** assumed that the input pointer is never NULL.
175018*/
175019SQLITE_PRIVATE void sqlite3ParserFree(
175020  void *p,                    /* The parser to be deleted */
175021  void (*freeProc)(void*)     /* Function used to reclaim memory */
175022){
175023#ifndef YYPARSEFREENEVERNULL
175024  if( p==0 ) return;
175025#endif
175026  sqlite3ParserFinalize(p);
175027  (*freeProc)(p);
175028}
175029#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
175030
175031/*
175032** Return the peak depth of the stack for a parser.
175033*/
175034#ifdef YYTRACKMAXSTACKDEPTH
175035SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
175036  yyParser *pParser = (yyParser*)p;
175037  return pParser->yyhwm;
175038}
175039#endif
175040
175041/* This array of booleans keeps track of the parser statement
175042** coverage.  The element yycoverage[X][Y] is set when the parser
175043** is in state X and has a lookahead token Y.  In a well-tested
175044** systems, every element of this matrix should end up being set.
175045*/
175046#if defined(YYCOVERAGE)
175047static unsigned char yycoverage[YYNSTATE][YYNTOKEN];
175048#endif
175049
175050/*
175051** Write into out a description of every state/lookahead combination that
175052**
175053**   (1)  has not been used by the parser, and
175054**   (2)  is not a syntax error.
175055**
175056** Return the number of missed state/lookahead combinations.
175057*/
175058#if defined(YYCOVERAGE)
175059SQLITE_PRIVATE int sqlite3ParserCoverage(FILE *out){
175060  int stateno, iLookAhead, i;
175061  int nMissed = 0;
175062  for(stateno=0; stateno<YYNSTATE; stateno++){
175063    i = yy_shift_ofst[stateno];
175064    for(iLookAhead=0; iLookAhead<YYNTOKEN; iLookAhead++){
175065      if( yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
175066      if( yycoverage[stateno][iLookAhead]==0 ) nMissed++;
175067      if( out ){
175068        fprintf(out,"State %d lookahead %s %s\n", stateno,
175069                yyTokenName[iLookAhead],
175070                yycoverage[stateno][iLookAhead] ? "ok" : "missed");
175071      }
175072    }
175073  }
175074  return nMissed;
175075}
175076#endif
175077
175078/*
175079** Find the appropriate action for a parser given the terminal
175080** look-ahead token iLookAhead.
175081*/
175082static YYACTIONTYPE yy_find_shift_action(
175083  YYCODETYPE iLookAhead,    /* The look-ahead token */
175084  YYACTIONTYPE stateno      /* Current state number */
175085){
175086  int i;
175087
175088  if( stateno>YY_MAX_SHIFT ) return stateno;
175089  assert( stateno <= YY_SHIFT_COUNT );
175090#if defined(YYCOVERAGE)
175091  yycoverage[stateno][iLookAhead] = 1;
175092#endif
175093  do{
175094    i = yy_shift_ofst[stateno];
175095    assert( i>=0 );
175096    assert( i<=YY_ACTTAB_COUNT );
175097    assert( i+YYNTOKEN<=(int)YY_NLOOKAHEAD );
175098    assert( iLookAhead!=YYNOCODE );
175099    assert( iLookAhead < YYNTOKEN );
175100    i += iLookAhead;
175101    assert( i<(int)YY_NLOOKAHEAD );
175102    if( yy_lookahead[i]!=iLookAhead ){
175103#ifdef YYFALLBACK
175104      YYCODETYPE iFallback;            /* Fallback token */
175105      assert( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0]) );
175106      iFallback = yyFallback[iLookAhead];
175107      if( iFallback!=0 ){
175108#ifndef NDEBUG
175109        if( yyTraceFILE ){
175110          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
175111             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
175112        }
175113#endif
175114        assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
175115        iLookAhead = iFallback;
175116        continue;
175117      }
175118#endif
175119#ifdef YYWILDCARD
175120      {
175121        int j = i - iLookAhead + YYWILDCARD;
175122        assert( j<(int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])) );
175123        if( yy_lookahead[j]==YYWILDCARD && iLookAhead>0 ){
175124#ifndef NDEBUG
175125          if( yyTraceFILE ){
175126            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
175127               yyTracePrompt, yyTokenName[iLookAhead],
175128               yyTokenName[YYWILDCARD]);
175129          }
175130#endif /* NDEBUG */
175131          return yy_action[j];
175132        }
175133      }
175134#endif /* YYWILDCARD */
175135      return yy_default[stateno];
175136    }else{
175137      assert( i>=0 && i<(int)(sizeof(yy_action)/sizeof(yy_action[0])) );
175138      return yy_action[i];
175139    }
175140  }while(1);
175141}
175142
175143/*
175144** Find the appropriate action for a parser given the non-terminal
175145** look-ahead token iLookAhead.
175146*/
175147static YYACTIONTYPE yy_find_reduce_action(
175148  YYACTIONTYPE stateno,     /* Current state number */
175149  YYCODETYPE iLookAhead     /* The look-ahead token */
175150){
175151  int i;
175152#ifdef YYERRORSYMBOL
175153  if( stateno>YY_REDUCE_COUNT ){
175154    return yy_default[stateno];
175155  }
175156#else
175157  assert( stateno<=YY_REDUCE_COUNT );
175158#endif
175159  i = yy_reduce_ofst[stateno];
175160  assert( iLookAhead!=YYNOCODE );
175161  i += iLookAhead;
175162#ifdef YYERRORSYMBOL
175163  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
175164    return yy_default[stateno];
175165  }
175166#else
175167  assert( i>=0 && i<YY_ACTTAB_COUNT );
175168  assert( yy_lookahead[i]==iLookAhead );
175169#endif
175170  return yy_action[i];
175171}
175172
175173/*
175174** The following routine is called if the stack overflows.
175175*/
175176static void yyStackOverflow(yyParser *yypParser){
175177   sqlite3ParserARG_FETCH
175178   sqlite3ParserCTX_FETCH
175179#ifndef NDEBUG
175180   if( yyTraceFILE ){
175181     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
175182   }
175183#endif
175184   while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
175185   /* Here code is inserted which will execute if the parser
175186   ** stack every overflows */
175187/******** Begin %stack_overflow code ******************************************/
175188
175189  sqlite3OomFault(pParse->db);
175190/******** End %stack_overflow code ********************************************/
175191   sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument var */
175192   sqlite3ParserCTX_STORE
175193}
175194
175195/*
175196** Print tracing information for a SHIFT action
175197*/
175198#ifndef NDEBUG
175199static void yyTraceShift(yyParser *yypParser, int yyNewState, const char *zTag){
175200  if( yyTraceFILE ){
175201    if( yyNewState<YYNSTATE ){
175202      fprintf(yyTraceFILE,"%s%s '%s', go to state %d\n",
175203         yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
175204         yyNewState);
175205    }else{
175206      fprintf(yyTraceFILE,"%s%s '%s', pending reduce %d\n",
175207         yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
175208         yyNewState - YY_MIN_REDUCE);
175209    }
175210  }
175211}
175212#else
175213# define yyTraceShift(X,Y,Z)
175214#endif
175215
175216/*
175217** Perform a shift action.
175218*/
175219static void yy_shift(
175220  yyParser *yypParser,          /* The parser to be shifted */
175221  YYACTIONTYPE yyNewState,      /* The new state to shift in */
175222  YYCODETYPE yyMajor,           /* The major token to shift in */
175223  sqlite3ParserTOKENTYPE yyMinor        /* The minor token to shift in */
175224){
175225  yyStackEntry *yytos;
175226  yypParser->yytos++;
175227#ifdef YYTRACKMAXSTACKDEPTH
175228  if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
175229    yypParser->yyhwm++;
175230    assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
175231  }
175232#endif
175233  yytos = yypParser->yytos;
175234  if( yytos>yypParser->yystackEnd ){
175235    if( yyGrowStack(yypParser) ){
175236      yypParser->yytos--;
175237      yyStackOverflow(yypParser);
175238      return;
175239    }
175240    yytos = yypParser->yytos;
175241    assert( yytos <= yypParser->yystackEnd );
175242  }
175243  if( yyNewState > YY_MAX_SHIFT ){
175244    yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
175245  }
175246  yytos->stateno = yyNewState;
175247  yytos->major = yyMajor;
175248  yytos->minor.yy0 = yyMinor;
175249  yyTraceShift(yypParser, yyNewState, "Shift");
175250}
175251
175252/* For rule J, yyRuleInfoLhs[J] contains the symbol on the left-hand side
175253** of that rule */
175254static const YYCODETYPE yyRuleInfoLhs[] = {
175255   190,  /* (0) explain ::= EXPLAIN */
175256   190,  /* (1) explain ::= EXPLAIN QUERY PLAN */
175257   189,  /* (2) cmdx ::= cmd */
175258   191,  /* (3) cmd ::= BEGIN transtype trans_opt */
175259   192,  /* (4) transtype ::= */
175260   192,  /* (5) transtype ::= DEFERRED */
175261   192,  /* (6) transtype ::= IMMEDIATE */
175262   192,  /* (7) transtype ::= EXCLUSIVE */
175263   191,  /* (8) cmd ::= COMMIT|END trans_opt */
175264   191,  /* (9) cmd ::= ROLLBACK trans_opt */
175265   191,  /* (10) cmd ::= SAVEPOINT nm */
175266   191,  /* (11) cmd ::= RELEASE savepoint_opt nm */
175267   191,  /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
175268   196,  /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
175269   198,  /* (14) createkw ::= CREATE */
175270   200,  /* (15) ifnotexists ::= */
175271   200,  /* (16) ifnotexists ::= IF NOT EXISTS */
175272   199,  /* (17) temp ::= TEMP */
175273   199,  /* (18) temp ::= */
175274   197,  /* (19) create_table_args ::= LP columnlist conslist_opt RP table_option_set */
175275   197,  /* (20) create_table_args ::= AS select */
175276   204,  /* (21) table_option_set ::= */
175277   204,  /* (22) table_option_set ::= table_option_set COMMA table_option */
175278   206,  /* (23) table_option ::= WITHOUT nm */
175279   206,  /* (24) table_option ::= nm */
175280   207,  /* (25) columnname ::= nm typetoken */
175281   209,  /* (26) typetoken ::= */
175282   209,  /* (27) typetoken ::= typename LP signed RP */
175283   209,  /* (28) typetoken ::= typename LP signed COMMA signed RP */
175284   210,  /* (29) typename ::= typename ID|STRING */
175285   214,  /* (30) scanpt ::= */
175286   215,  /* (31) scantok ::= */
175287   216,  /* (32) ccons ::= CONSTRAINT nm */
175288   216,  /* (33) ccons ::= DEFAULT scantok term */
175289   216,  /* (34) ccons ::= DEFAULT LP expr RP */
175290   216,  /* (35) ccons ::= DEFAULT PLUS scantok term */
175291   216,  /* (36) ccons ::= DEFAULT MINUS scantok term */
175292   216,  /* (37) ccons ::= DEFAULT scantok ID|INDEXED */
175293   216,  /* (38) ccons ::= NOT NULL onconf */
175294   216,  /* (39) ccons ::= PRIMARY KEY sortorder onconf autoinc */
175295   216,  /* (40) ccons ::= UNIQUE onconf */
175296   216,  /* (41) ccons ::= CHECK LP expr RP */
175297   216,  /* (42) ccons ::= REFERENCES nm eidlist_opt refargs */
175298   216,  /* (43) ccons ::= defer_subclause */
175299   216,  /* (44) ccons ::= COLLATE ID|STRING */
175300   225,  /* (45) generated ::= LP expr RP */
175301   225,  /* (46) generated ::= LP expr RP ID */
175302   221,  /* (47) autoinc ::= */
175303   221,  /* (48) autoinc ::= AUTOINCR */
175304   223,  /* (49) refargs ::= */
175305   223,  /* (50) refargs ::= refargs refarg */
175306   226,  /* (51) refarg ::= MATCH nm */
175307   226,  /* (52) refarg ::= ON INSERT refact */
175308   226,  /* (53) refarg ::= ON DELETE refact */
175309   226,  /* (54) refarg ::= ON UPDATE refact */
175310   227,  /* (55) refact ::= SET NULL */
175311   227,  /* (56) refact ::= SET DEFAULT */
175312   227,  /* (57) refact ::= CASCADE */
175313   227,  /* (58) refact ::= RESTRICT */
175314   227,  /* (59) refact ::= NO ACTION */
175315   224,  /* (60) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
175316   224,  /* (61) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
175317   228,  /* (62) init_deferred_pred_opt ::= */
175318   228,  /* (63) init_deferred_pred_opt ::= INITIALLY DEFERRED */
175319   228,  /* (64) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
175320   203,  /* (65) conslist_opt ::= */
175321   230,  /* (66) tconscomma ::= COMMA */
175322   231,  /* (67) tcons ::= CONSTRAINT nm */
175323   231,  /* (68) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
175324   231,  /* (69) tcons ::= UNIQUE LP sortlist RP onconf */
175325   231,  /* (70) tcons ::= CHECK LP expr RP onconf */
175326   231,  /* (71) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
175327   234,  /* (72) defer_subclause_opt ::= */
175328   219,  /* (73) onconf ::= */
175329   219,  /* (74) onconf ::= ON CONFLICT resolvetype */
175330   235,  /* (75) orconf ::= */
175331   235,  /* (76) orconf ::= OR resolvetype */
175332   236,  /* (77) resolvetype ::= IGNORE */
175333   236,  /* (78) resolvetype ::= REPLACE */
175334   191,  /* (79) cmd ::= DROP TABLE ifexists fullname */
175335   238,  /* (80) ifexists ::= IF EXISTS */
175336   238,  /* (81) ifexists ::= */
175337   191,  /* (82) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
175338   191,  /* (83) cmd ::= DROP VIEW ifexists fullname */
175339   191,  /* (84) cmd ::= select */
175340   205,  /* (85) select ::= WITH wqlist selectnowith */
175341   205,  /* (86) select ::= WITH RECURSIVE wqlist selectnowith */
175342   205,  /* (87) select ::= selectnowith */
175343   240,  /* (88) selectnowith ::= selectnowith multiselect_op oneselect */
175344   243,  /* (89) multiselect_op ::= UNION */
175345   243,  /* (90) multiselect_op ::= UNION ALL */
175346   243,  /* (91) multiselect_op ::= EXCEPT|INTERSECT */
175347   241,  /* (92) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
175348   241,  /* (93) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
175349   253,  /* (94) values ::= VALUES LP nexprlist RP */
175350   241,  /* (95) oneselect ::= mvalues */
175351   255,  /* (96) mvalues ::= values COMMA LP nexprlist RP */
175352   255,  /* (97) mvalues ::= mvalues COMMA LP nexprlist RP */
175353   244,  /* (98) distinct ::= DISTINCT */
175354   244,  /* (99) distinct ::= ALL */
175355   244,  /* (100) distinct ::= */
175356   256,  /* (101) sclp ::= */
175357   245,  /* (102) selcollist ::= sclp scanpt expr scanpt as */
175358   245,  /* (103) selcollist ::= sclp scanpt STAR */
175359   245,  /* (104) selcollist ::= sclp scanpt nm DOT STAR */
175360   257,  /* (105) as ::= AS nm */
175361   257,  /* (106) as ::= */
175362   246,  /* (107) from ::= */
175363   246,  /* (108) from ::= FROM seltablist */
175364   259,  /* (109) stl_prefix ::= seltablist joinop */
175365   259,  /* (110) stl_prefix ::= */
175366   258,  /* (111) seltablist ::= stl_prefix nm dbnm as on_using */
175367   258,  /* (112) seltablist ::= stl_prefix nm dbnm as indexed_by on_using */
175368   258,  /* (113) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_using */
175369   258,  /* (114) seltablist ::= stl_prefix LP select RP as on_using */
175370   258,  /* (115) seltablist ::= stl_prefix LP seltablist RP as on_using */
175371   201,  /* (116) dbnm ::= */
175372   201,  /* (117) dbnm ::= DOT nm */
175373   239,  /* (118) fullname ::= nm */
175374   239,  /* (119) fullname ::= nm DOT nm */
175375   264,  /* (120) xfullname ::= nm */
175376   264,  /* (121) xfullname ::= nm DOT nm */
175377   264,  /* (122) xfullname ::= nm DOT nm AS nm */
175378   264,  /* (123) xfullname ::= nm AS nm */
175379   260,  /* (124) joinop ::= COMMA|JOIN */
175380   260,  /* (125) joinop ::= JOIN_KW JOIN */
175381   260,  /* (126) joinop ::= JOIN_KW nm JOIN */
175382   260,  /* (127) joinop ::= JOIN_KW nm nm JOIN */
175383   261,  /* (128) on_using ::= ON expr */
175384   261,  /* (129) on_using ::= USING LP idlist RP */
175385   261,  /* (130) on_using ::= */
175386   266,  /* (131) indexed_opt ::= */
175387   262,  /* (132) indexed_by ::= INDEXED BY nm */
175388   262,  /* (133) indexed_by ::= NOT INDEXED */
175389   250,  /* (134) orderby_opt ::= */
175390   250,  /* (135) orderby_opt ::= ORDER BY sortlist */
175391   232,  /* (136) sortlist ::= sortlist COMMA expr sortorder nulls */
175392   232,  /* (137) sortlist ::= expr sortorder nulls */
175393   220,  /* (138) sortorder ::= ASC */
175394   220,  /* (139) sortorder ::= DESC */
175395   220,  /* (140) sortorder ::= */
175396   267,  /* (141) nulls ::= NULLS FIRST */
175397   267,  /* (142) nulls ::= NULLS LAST */
175398   267,  /* (143) nulls ::= */
175399   248,  /* (144) groupby_opt ::= */
175400   248,  /* (145) groupby_opt ::= GROUP BY nexprlist */
175401   249,  /* (146) having_opt ::= */
175402   249,  /* (147) having_opt ::= HAVING expr */
175403   251,  /* (148) limit_opt ::= */
175404   251,  /* (149) limit_opt ::= LIMIT expr */
175405   251,  /* (150) limit_opt ::= LIMIT expr OFFSET expr */
175406   251,  /* (151) limit_opt ::= LIMIT expr COMMA expr */
175407   191,  /* (152) cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret */
175408   247,  /* (153) where_opt ::= */
175409   247,  /* (154) where_opt ::= WHERE expr */
175410   269,  /* (155) where_opt_ret ::= */
175411   269,  /* (156) where_opt_ret ::= WHERE expr */
175412   269,  /* (157) where_opt_ret ::= RETURNING selcollist */
175413   269,  /* (158) where_opt_ret ::= WHERE expr RETURNING selcollist */
175414   191,  /* (159) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret */
175415   270,  /* (160) setlist ::= setlist COMMA nm EQ expr */
175416   270,  /* (161) setlist ::= setlist COMMA LP idlist RP EQ expr */
175417   270,  /* (162) setlist ::= nm EQ expr */
175418   270,  /* (163) setlist ::= LP idlist RP EQ expr */
175419   191,  /* (164) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
175420   191,  /* (165) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning */
175421   273,  /* (166) upsert ::= */
175422   273,  /* (167) upsert ::= RETURNING selcollist */
175423   273,  /* (168) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert */
175424   273,  /* (169) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert */
175425   273,  /* (170) upsert ::= ON CONFLICT DO NOTHING returning */
175426   273,  /* (171) upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning */
175427   274,  /* (172) returning ::= RETURNING selcollist */
175428   271,  /* (173) insert_cmd ::= INSERT orconf */
175429   271,  /* (174) insert_cmd ::= REPLACE */
175430   272,  /* (175) idlist_opt ::= */
175431   272,  /* (176) idlist_opt ::= LP idlist RP */
175432   265,  /* (177) idlist ::= idlist COMMA nm */
175433   265,  /* (178) idlist ::= nm */
175434   218,  /* (179) expr ::= LP expr RP */
175435   218,  /* (180) expr ::= ID|INDEXED|JOIN_KW */
175436   218,  /* (181) expr ::= nm DOT nm */
175437   218,  /* (182) expr ::= nm DOT nm DOT nm */
175438   217,  /* (183) term ::= NULL|FLOAT|BLOB */
175439   217,  /* (184) term ::= STRING */
175440   217,  /* (185) term ::= INTEGER */
175441   218,  /* (186) expr ::= VARIABLE */
175442   218,  /* (187) expr ::= expr COLLATE ID|STRING */
175443   218,  /* (188) expr ::= CAST LP expr AS typetoken RP */
175444   218,  /* (189) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP */
175445   218,  /* (190) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP */
175446   218,  /* (191) expr ::= ID|INDEXED|JOIN_KW LP STAR RP */
175447   218,  /* (192) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */
175448   218,  /* (193) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP filter_over */
175449   218,  /* (194) expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */
175450   217,  /* (195) term ::= CTIME_KW */
175451   218,  /* (196) expr ::= LP nexprlist COMMA expr RP */
175452   218,  /* (197) expr ::= expr AND expr */
175453   218,  /* (198) expr ::= expr OR expr */
175454   218,  /* (199) expr ::= expr LT|GT|GE|LE expr */
175455   218,  /* (200) expr ::= expr EQ|NE expr */
175456   218,  /* (201) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
175457   218,  /* (202) expr ::= expr PLUS|MINUS expr */
175458   218,  /* (203) expr ::= expr STAR|SLASH|REM expr */
175459   218,  /* (204) expr ::= expr CONCAT expr */
175460   276,  /* (205) likeop ::= NOT LIKE_KW|MATCH */
175461   218,  /* (206) expr ::= expr likeop expr */
175462   218,  /* (207) expr ::= expr likeop expr ESCAPE expr */
175463   218,  /* (208) expr ::= expr ISNULL|NOTNULL */
175464   218,  /* (209) expr ::= expr NOT NULL */
175465   218,  /* (210) expr ::= expr IS expr */
175466   218,  /* (211) expr ::= expr IS NOT expr */
175467   218,  /* (212) expr ::= expr IS NOT DISTINCT FROM expr */
175468   218,  /* (213) expr ::= expr IS DISTINCT FROM expr */
175469   218,  /* (214) expr ::= NOT expr */
175470   218,  /* (215) expr ::= BITNOT expr */
175471   218,  /* (216) expr ::= PLUS|MINUS expr */
175472   218,  /* (217) expr ::= expr PTR expr */
175473   277,  /* (218) between_op ::= BETWEEN */
175474   277,  /* (219) between_op ::= NOT BETWEEN */
175475   218,  /* (220) expr ::= expr between_op expr AND expr */
175476   278,  /* (221) in_op ::= IN */
175477   278,  /* (222) in_op ::= NOT IN */
175478   218,  /* (223) expr ::= expr in_op LP exprlist RP */
175479   218,  /* (224) expr ::= LP select RP */
175480   218,  /* (225) expr ::= expr in_op LP select RP */
175481   218,  /* (226) expr ::= expr in_op nm dbnm paren_exprlist */
175482   218,  /* (227) expr ::= EXISTS LP select RP */
175483   218,  /* (228) expr ::= CASE case_operand case_exprlist case_else END */
175484   281,  /* (229) case_exprlist ::= case_exprlist WHEN expr THEN expr */
175485   281,  /* (230) case_exprlist ::= WHEN expr THEN expr */
175486   282,  /* (231) case_else ::= ELSE expr */
175487   282,  /* (232) case_else ::= */
175488   280,  /* (233) case_operand ::= */
175489   263,  /* (234) exprlist ::= */
175490   254,  /* (235) nexprlist ::= nexprlist COMMA expr */
175491   254,  /* (236) nexprlist ::= expr */
175492   279,  /* (237) paren_exprlist ::= */
175493   279,  /* (238) paren_exprlist ::= LP exprlist RP */
175494   191,  /* (239) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
175495   283,  /* (240) uniqueflag ::= UNIQUE */
175496   283,  /* (241) uniqueflag ::= */
175497   222,  /* (242) eidlist_opt ::= */
175498   222,  /* (243) eidlist_opt ::= LP eidlist RP */
175499   233,  /* (244) eidlist ::= eidlist COMMA nm collate sortorder */
175500   233,  /* (245) eidlist ::= nm collate sortorder */
175501   284,  /* (246) collate ::= */
175502   284,  /* (247) collate ::= COLLATE ID|STRING */
175503   191,  /* (248) cmd ::= DROP INDEX ifexists fullname */
175504   191,  /* (249) cmd ::= VACUUM vinto */
175505   191,  /* (250) cmd ::= VACUUM nm vinto */
175506   285,  /* (251) vinto ::= INTO expr */
175507   285,  /* (252) vinto ::= */
175508   191,  /* (253) cmd ::= PRAGMA nm dbnm */
175509   191,  /* (254) cmd ::= PRAGMA nm dbnm EQ nmnum */
175510   191,  /* (255) cmd ::= PRAGMA nm dbnm LP nmnum RP */
175511   191,  /* (256) cmd ::= PRAGMA nm dbnm EQ minus_num */
175512   191,  /* (257) cmd ::= PRAGMA nm dbnm LP minus_num RP */
175513   212,  /* (258) plus_num ::= PLUS INTEGER|FLOAT */
175514   213,  /* (259) minus_num ::= MINUS INTEGER|FLOAT */
175515   191,  /* (260) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
175516   287,  /* (261) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
175517   289,  /* (262) trigger_time ::= BEFORE|AFTER */
175518   289,  /* (263) trigger_time ::= INSTEAD OF */
175519   289,  /* (264) trigger_time ::= */
175520   290,  /* (265) trigger_event ::= DELETE|INSERT */
175521   290,  /* (266) trigger_event ::= UPDATE */
175522   290,  /* (267) trigger_event ::= UPDATE OF idlist */
175523   292,  /* (268) when_clause ::= */
175524   292,  /* (269) when_clause ::= WHEN expr */
175525   288,  /* (270) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
175526   288,  /* (271) trigger_cmd_list ::= trigger_cmd SEMI */
175527   294,  /* (272) trnm ::= nm DOT nm */
175528   295,  /* (273) tridxby ::= INDEXED BY nm */
175529   295,  /* (274) tridxby ::= NOT INDEXED */
175530   293,  /* (275) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
175531   293,  /* (276) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
175532   293,  /* (277) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
175533   293,  /* (278) trigger_cmd ::= scanpt select scanpt */
175534   218,  /* (279) expr ::= RAISE LP IGNORE RP */
175535   218,  /* (280) expr ::= RAISE LP raisetype COMMA nm RP */
175536   237,  /* (281) raisetype ::= ROLLBACK */
175537   237,  /* (282) raisetype ::= ABORT */
175538   237,  /* (283) raisetype ::= FAIL */
175539   191,  /* (284) cmd ::= DROP TRIGGER ifexists fullname */
175540   191,  /* (285) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
175541   191,  /* (286) cmd ::= DETACH database_kw_opt expr */
175542   297,  /* (287) key_opt ::= */
175543   297,  /* (288) key_opt ::= KEY expr */
175544   191,  /* (289) cmd ::= REINDEX */
175545   191,  /* (290) cmd ::= REINDEX nm dbnm */
175546   191,  /* (291) cmd ::= ANALYZE */
175547   191,  /* (292) cmd ::= ANALYZE nm dbnm */
175548   191,  /* (293) cmd ::= ALTER TABLE fullname RENAME TO nm */
175549   191,  /* (294) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
175550   191,  /* (295) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
175551   298,  /* (296) add_column_fullname ::= fullname */
175552   191,  /* (297) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
175553   191,  /* (298) cmd ::= create_vtab */
175554   191,  /* (299) cmd ::= create_vtab LP vtabarglist RP */
175555   300,  /* (300) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
175556   302,  /* (301) vtabarg ::= */
175557   303,  /* (302) vtabargtoken ::= ANY */
175558   303,  /* (303) vtabargtoken ::= lp anylist RP */
175559   304,  /* (304) lp ::= LP */
175560   268,  /* (305) with ::= WITH wqlist */
175561   268,  /* (306) with ::= WITH RECURSIVE wqlist */
175562   307,  /* (307) wqas ::= AS */
175563   307,  /* (308) wqas ::= AS MATERIALIZED */
175564   307,  /* (309) wqas ::= AS NOT MATERIALIZED */
175565   306,  /* (310) wqitem ::= withnm eidlist_opt wqas LP select RP */
175566   308,  /* (311) withnm ::= nm */
175567   242,  /* (312) wqlist ::= wqitem */
175568   242,  /* (313) wqlist ::= wqlist COMMA wqitem */
175569   309,  /* (314) windowdefn_list ::= windowdefn_list COMMA windowdefn */
175570   310,  /* (315) windowdefn ::= nm AS LP window RP */
175571   311,  /* (316) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
175572   311,  /* (317) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
175573   311,  /* (318) window ::= ORDER BY sortlist frame_opt */
175574   311,  /* (319) window ::= nm ORDER BY sortlist frame_opt */
175575   311,  /* (320) window ::= nm frame_opt */
175576   312,  /* (321) frame_opt ::= */
175577   312,  /* (322) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
175578   312,  /* (323) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
175579   316,  /* (324) range_or_rows ::= RANGE|ROWS|GROUPS */
175580   318,  /* (325) frame_bound_s ::= frame_bound */
175581   318,  /* (326) frame_bound_s ::= UNBOUNDED PRECEDING */
175582   319,  /* (327) frame_bound_e ::= frame_bound */
175583   319,  /* (328) frame_bound_e ::= UNBOUNDED FOLLOWING */
175584   317,  /* (329) frame_bound ::= expr PRECEDING|FOLLOWING */
175585   317,  /* (330) frame_bound ::= CURRENT ROW */
175586   320,  /* (331) frame_exclude_opt ::= */
175587   320,  /* (332) frame_exclude_opt ::= EXCLUDE frame_exclude */
175588   321,  /* (333) frame_exclude ::= NO OTHERS */
175589   321,  /* (334) frame_exclude ::= CURRENT ROW */
175590   321,  /* (335) frame_exclude ::= GROUP|TIES */
175591   252,  /* (336) window_clause ::= WINDOW windowdefn_list */
175592   275,  /* (337) filter_over ::= filter_clause over_clause */
175593   275,  /* (338) filter_over ::= over_clause */
175594   275,  /* (339) filter_over ::= filter_clause */
175595   315,  /* (340) over_clause ::= OVER LP window RP */
175596   315,  /* (341) over_clause ::= OVER nm */
175597   314,  /* (342) filter_clause ::= FILTER LP WHERE expr RP */
175598   217,  /* (343) term ::= QNUMBER */
175599   186,  /* (344) input ::= cmdlist */
175600   187,  /* (345) cmdlist ::= cmdlist ecmd */
175601   187,  /* (346) cmdlist ::= ecmd */
175602   188,  /* (347) ecmd ::= SEMI */
175603   188,  /* (348) ecmd ::= cmdx SEMI */
175604   188,  /* (349) ecmd ::= explain cmdx SEMI */
175605   193,  /* (350) trans_opt ::= */
175606   193,  /* (351) trans_opt ::= TRANSACTION */
175607   193,  /* (352) trans_opt ::= TRANSACTION nm */
175608   195,  /* (353) savepoint_opt ::= SAVEPOINT */
175609   195,  /* (354) savepoint_opt ::= */
175610   191,  /* (355) cmd ::= create_table create_table_args */
175611   204,  /* (356) table_option_set ::= table_option */
175612   202,  /* (357) columnlist ::= columnlist COMMA columnname carglist */
175613   202,  /* (358) columnlist ::= columnname carglist */
175614   194,  /* (359) nm ::= ID|INDEXED|JOIN_KW */
175615   194,  /* (360) nm ::= STRING */
175616   209,  /* (361) typetoken ::= typename */
175617   210,  /* (362) typename ::= ID|STRING */
175618   211,  /* (363) signed ::= plus_num */
175619   211,  /* (364) signed ::= minus_num */
175620   208,  /* (365) carglist ::= carglist ccons */
175621   208,  /* (366) carglist ::= */
175622   216,  /* (367) ccons ::= NULL onconf */
175623   216,  /* (368) ccons ::= GENERATED ALWAYS AS generated */
175624   216,  /* (369) ccons ::= AS generated */
175625   203,  /* (370) conslist_opt ::= COMMA conslist */
175626   229,  /* (371) conslist ::= conslist tconscomma tcons */
175627   229,  /* (372) conslist ::= tcons */
175628   230,  /* (373) tconscomma ::= */
175629   234,  /* (374) defer_subclause_opt ::= defer_subclause */
175630   236,  /* (375) resolvetype ::= raisetype */
175631   240,  /* (376) selectnowith ::= oneselect */
175632   241,  /* (377) oneselect ::= values */
175633   256,  /* (378) sclp ::= selcollist COMMA */
175634   257,  /* (379) as ::= ID|STRING */
175635   266,  /* (380) indexed_opt ::= indexed_by */
175636   274,  /* (381) returning ::= */
175637   218,  /* (382) expr ::= term */
175638   276,  /* (383) likeop ::= LIKE_KW|MATCH */
175639   280,  /* (384) case_operand ::= expr */
175640   263,  /* (385) exprlist ::= nexprlist */
175641   286,  /* (386) nmnum ::= plus_num */
175642   286,  /* (387) nmnum ::= nm */
175643   286,  /* (388) nmnum ::= ON */
175644   286,  /* (389) nmnum ::= DELETE */
175645   286,  /* (390) nmnum ::= DEFAULT */
175646   212,  /* (391) plus_num ::= INTEGER|FLOAT */
175647   291,  /* (392) foreach_clause ::= */
175648   291,  /* (393) foreach_clause ::= FOR EACH ROW */
175649   294,  /* (394) trnm ::= nm */
175650   295,  /* (395) tridxby ::= */
175651   296,  /* (396) database_kw_opt ::= DATABASE */
175652   296,  /* (397) database_kw_opt ::= */
175653   299,  /* (398) kwcolumn_opt ::= */
175654   299,  /* (399) kwcolumn_opt ::= COLUMNKW */
175655   301,  /* (400) vtabarglist ::= vtabarg */
175656   301,  /* (401) vtabarglist ::= vtabarglist COMMA vtabarg */
175657   302,  /* (402) vtabarg ::= vtabarg vtabargtoken */
175658   305,  /* (403) anylist ::= */
175659   305,  /* (404) anylist ::= anylist LP anylist RP */
175660   305,  /* (405) anylist ::= anylist ANY */
175661   268,  /* (406) with ::= */
175662   309,  /* (407) windowdefn_list ::= windowdefn */
175663   311,  /* (408) window ::= frame_opt */
175664};
175665
175666/* For rule J, yyRuleInfoNRhs[J] contains the negative of the number
175667** of symbols on the right-hand side of that rule. */
175668static const signed char yyRuleInfoNRhs[] = {
175669   -1,  /* (0) explain ::= EXPLAIN */
175670   -3,  /* (1) explain ::= EXPLAIN QUERY PLAN */
175671   -1,  /* (2) cmdx ::= cmd */
175672   -3,  /* (3) cmd ::= BEGIN transtype trans_opt */
175673    0,  /* (4) transtype ::= */
175674   -1,  /* (5) transtype ::= DEFERRED */
175675   -1,  /* (6) transtype ::= IMMEDIATE */
175676   -1,  /* (7) transtype ::= EXCLUSIVE */
175677   -2,  /* (8) cmd ::= COMMIT|END trans_opt */
175678   -2,  /* (9) cmd ::= ROLLBACK trans_opt */
175679   -2,  /* (10) cmd ::= SAVEPOINT nm */
175680   -3,  /* (11) cmd ::= RELEASE savepoint_opt nm */
175681   -5,  /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
175682   -6,  /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
175683   -1,  /* (14) createkw ::= CREATE */
175684    0,  /* (15) ifnotexists ::= */
175685   -3,  /* (16) ifnotexists ::= IF NOT EXISTS */
175686   -1,  /* (17) temp ::= TEMP */
175687    0,  /* (18) temp ::= */
175688   -5,  /* (19) create_table_args ::= LP columnlist conslist_opt RP table_option_set */
175689   -2,  /* (20) create_table_args ::= AS select */
175690    0,  /* (21) table_option_set ::= */
175691   -3,  /* (22) table_option_set ::= table_option_set COMMA table_option */
175692   -2,  /* (23) table_option ::= WITHOUT nm */
175693   -1,  /* (24) table_option ::= nm */
175694   -2,  /* (25) columnname ::= nm typetoken */
175695    0,  /* (26) typetoken ::= */
175696   -4,  /* (27) typetoken ::= typename LP signed RP */
175697   -6,  /* (28) typetoken ::= typename LP signed COMMA signed RP */
175698   -2,  /* (29) typename ::= typename ID|STRING */
175699    0,  /* (30) scanpt ::= */
175700    0,  /* (31) scantok ::= */
175701   -2,  /* (32) ccons ::= CONSTRAINT nm */
175702   -3,  /* (33) ccons ::= DEFAULT scantok term */
175703   -4,  /* (34) ccons ::= DEFAULT LP expr RP */
175704   -4,  /* (35) ccons ::= DEFAULT PLUS scantok term */
175705   -4,  /* (36) ccons ::= DEFAULT MINUS scantok term */
175706   -3,  /* (37) ccons ::= DEFAULT scantok ID|INDEXED */
175707   -3,  /* (38) ccons ::= NOT NULL onconf */
175708   -5,  /* (39) ccons ::= PRIMARY KEY sortorder onconf autoinc */
175709   -2,  /* (40) ccons ::= UNIQUE onconf */
175710   -4,  /* (41) ccons ::= CHECK LP expr RP */
175711   -4,  /* (42) ccons ::= REFERENCES nm eidlist_opt refargs */
175712   -1,  /* (43) ccons ::= defer_subclause */
175713   -2,  /* (44) ccons ::= COLLATE ID|STRING */
175714   -3,  /* (45) generated ::= LP expr RP */
175715   -4,  /* (46) generated ::= LP expr RP ID */
175716    0,  /* (47) autoinc ::= */
175717   -1,  /* (48) autoinc ::= AUTOINCR */
175718    0,  /* (49) refargs ::= */
175719   -2,  /* (50) refargs ::= refargs refarg */
175720   -2,  /* (51) refarg ::= MATCH nm */
175721   -3,  /* (52) refarg ::= ON INSERT refact */
175722   -3,  /* (53) refarg ::= ON DELETE refact */
175723   -3,  /* (54) refarg ::= ON UPDATE refact */
175724   -2,  /* (55) refact ::= SET NULL */
175725   -2,  /* (56) refact ::= SET DEFAULT */
175726   -1,  /* (57) refact ::= CASCADE */
175727   -1,  /* (58) refact ::= RESTRICT */
175728   -2,  /* (59) refact ::= NO ACTION */
175729   -3,  /* (60) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
175730   -2,  /* (61) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
175731    0,  /* (62) init_deferred_pred_opt ::= */
175732   -2,  /* (63) init_deferred_pred_opt ::= INITIALLY DEFERRED */
175733   -2,  /* (64) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
175734    0,  /* (65) conslist_opt ::= */
175735   -1,  /* (66) tconscomma ::= COMMA */
175736   -2,  /* (67) tcons ::= CONSTRAINT nm */
175737   -7,  /* (68) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
175738   -5,  /* (69) tcons ::= UNIQUE LP sortlist RP onconf */
175739   -5,  /* (70) tcons ::= CHECK LP expr RP onconf */
175740  -10,  /* (71) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
175741    0,  /* (72) defer_subclause_opt ::= */
175742    0,  /* (73) onconf ::= */
175743   -3,  /* (74) onconf ::= ON CONFLICT resolvetype */
175744    0,  /* (75) orconf ::= */
175745   -2,  /* (76) orconf ::= OR resolvetype */
175746   -1,  /* (77) resolvetype ::= IGNORE */
175747   -1,  /* (78) resolvetype ::= REPLACE */
175748   -4,  /* (79) cmd ::= DROP TABLE ifexists fullname */
175749   -2,  /* (80) ifexists ::= IF EXISTS */
175750    0,  /* (81) ifexists ::= */
175751   -9,  /* (82) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
175752   -4,  /* (83) cmd ::= DROP VIEW ifexists fullname */
175753   -1,  /* (84) cmd ::= select */
175754   -3,  /* (85) select ::= WITH wqlist selectnowith */
175755   -4,  /* (86) select ::= WITH RECURSIVE wqlist selectnowith */
175756   -1,  /* (87) select ::= selectnowith */
175757   -3,  /* (88) selectnowith ::= selectnowith multiselect_op oneselect */
175758   -1,  /* (89) multiselect_op ::= UNION */
175759   -2,  /* (90) multiselect_op ::= UNION ALL */
175760   -1,  /* (91) multiselect_op ::= EXCEPT|INTERSECT */
175761   -9,  /* (92) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
175762  -10,  /* (93) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
175763   -4,  /* (94) values ::= VALUES LP nexprlist RP */
175764   -1,  /* (95) oneselect ::= mvalues */
175765   -5,  /* (96) mvalues ::= values COMMA LP nexprlist RP */
175766   -5,  /* (97) mvalues ::= mvalues COMMA LP nexprlist RP */
175767   -1,  /* (98) distinct ::= DISTINCT */
175768   -1,  /* (99) distinct ::= ALL */
175769    0,  /* (100) distinct ::= */
175770    0,  /* (101) sclp ::= */
175771   -5,  /* (102) selcollist ::= sclp scanpt expr scanpt as */
175772   -3,  /* (103) selcollist ::= sclp scanpt STAR */
175773   -5,  /* (104) selcollist ::= sclp scanpt nm DOT STAR */
175774   -2,  /* (105) as ::= AS nm */
175775    0,  /* (106) as ::= */
175776    0,  /* (107) from ::= */
175777   -2,  /* (108) from ::= FROM seltablist */
175778   -2,  /* (109) stl_prefix ::= seltablist joinop */
175779    0,  /* (110) stl_prefix ::= */
175780   -5,  /* (111) seltablist ::= stl_prefix nm dbnm as on_using */
175781   -6,  /* (112) seltablist ::= stl_prefix nm dbnm as indexed_by on_using */
175782   -8,  /* (113) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_using */
175783   -6,  /* (114) seltablist ::= stl_prefix LP select RP as on_using */
175784   -6,  /* (115) seltablist ::= stl_prefix LP seltablist RP as on_using */
175785    0,  /* (116) dbnm ::= */
175786   -2,  /* (117) dbnm ::= DOT nm */
175787   -1,  /* (118) fullname ::= nm */
175788   -3,  /* (119) fullname ::= nm DOT nm */
175789   -1,  /* (120) xfullname ::= nm */
175790   -3,  /* (121) xfullname ::= nm DOT nm */
175791   -5,  /* (122) xfullname ::= nm DOT nm AS nm */
175792   -3,  /* (123) xfullname ::= nm AS nm */
175793   -1,  /* (124) joinop ::= COMMA|JOIN */
175794   -2,  /* (125) joinop ::= JOIN_KW JOIN */
175795   -3,  /* (126) joinop ::= JOIN_KW nm JOIN */
175796   -4,  /* (127) joinop ::= JOIN_KW nm nm JOIN */
175797   -2,  /* (128) on_using ::= ON expr */
175798   -4,  /* (129) on_using ::= USING LP idlist RP */
175799    0,  /* (130) on_using ::= */
175800    0,  /* (131) indexed_opt ::= */
175801   -3,  /* (132) indexed_by ::= INDEXED BY nm */
175802   -2,  /* (133) indexed_by ::= NOT INDEXED */
175803    0,  /* (134) orderby_opt ::= */
175804   -3,  /* (135) orderby_opt ::= ORDER BY sortlist */
175805   -5,  /* (136) sortlist ::= sortlist COMMA expr sortorder nulls */
175806   -3,  /* (137) sortlist ::= expr sortorder nulls */
175807   -1,  /* (138) sortorder ::= ASC */
175808   -1,  /* (139) sortorder ::= DESC */
175809    0,  /* (140) sortorder ::= */
175810   -2,  /* (141) nulls ::= NULLS FIRST */
175811   -2,  /* (142) nulls ::= NULLS LAST */
175812    0,  /* (143) nulls ::= */
175813    0,  /* (144) groupby_opt ::= */
175814   -3,  /* (145) groupby_opt ::= GROUP BY nexprlist */
175815    0,  /* (146) having_opt ::= */
175816   -2,  /* (147) having_opt ::= HAVING expr */
175817    0,  /* (148) limit_opt ::= */
175818   -2,  /* (149) limit_opt ::= LIMIT expr */
175819   -4,  /* (150) limit_opt ::= LIMIT expr OFFSET expr */
175820   -4,  /* (151) limit_opt ::= LIMIT expr COMMA expr */
175821   -6,  /* (152) cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret */
175822    0,  /* (153) where_opt ::= */
175823   -2,  /* (154) where_opt ::= WHERE expr */
175824    0,  /* (155) where_opt_ret ::= */
175825   -2,  /* (156) where_opt_ret ::= WHERE expr */
175826   -2,  /* (157) where_opt_ret ::= RETURNING selcollist */
175827   -4,  /* (158) where_opt_ret ::= WHERE expr RETURNING selcollist */
175828   -9,  /* (159) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret */
175829   -5,  /* (160) setlist ::= setlist COMMA nm EQ expr */
175830   -7,  /* (161) setlist ::= setlist COMMA LP idlist RP EQ expr */
175831   -3,  /* (162) setlist ::= nm EQ expr */
175832   -5,  /* (163) setlist ::= LP idlist RP EQ expr */
175833   -7,  /* (164) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
175834   -8,  /* (165) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning */
175835    0,  /* (166) upsert ::= */
175836   -2,  /* (167) upsert ::= RETURNING selcollist */
175837  -12,  /* (168) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert */
175838   -9,  /* (169) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert */
175839   -5,  /* (170) upsert ::= ON CONFLICT DO NOTHING returning */
175840   -8,  /* (171) upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning */
175841   -2,  /* (172) returning ::= RETURNING selcollist */
175842   -2,  /* (173) insert_cmd ::= INSERT orconf */
175843   -1,  /* (174) insert_cmd ::= REPLACE */
175844    0,  /* (175) idlist_opt ::= */
175845   -3,  /* (176) idlist_opt ::= LP idlist RP */
175846   -3,  /* (177) idlist ::= idlist COMMA nm */
175847   -1,  /* (178) idlist ::= nm */
175848   -3,  /* (179) expr ::= LP expr RP */
175849   -1,  /* (180) expr ::= ID|INDEXED|JOIN_KW */
175850   -3,  /* (181) expr ::= nm DOT nm */
175851   -5,  /* (182) expr ::= nm DOT nm DOT nm */
175852   -1,  /* (183) term ::= NULL|FLOAT|BLOB */
175853   -1,  /* (184) term ::= STRING */
175854   -1,  /* (185) term ::= INTEGER */
175855   -1,  /* (186) expr ::= VARIABLE */
175856   -3,  /* (187) expr ::= expr COLLATE ID|STRING */
175857   -6,  /* (188) expr ::= CAST LP expr AS typetoken RP */
175858   -5,  /* (189) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP */
175859   -8,  /* (190) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP */
175860   -4,  /* (191) expr ::= ID|INDEXED|JOIN_KW LP STAR RP */
175861   -6,  /* (192) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */
175862   -9,  /* (193) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP filter_over */
175863   -5,  /* (194) expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */
175864   -1,  /* (195) term ::= CTIME_KW */
175865   -5,  /* (196) expr ::= LP nexprlist COMMA expr RP */
175866   -3,  /* (197) expr ::= expr AND expr */
175867   -3,  /* (198) expr ::= expr OR expr */
175868   -3,  /* (199) expr ::= expr LT|GT|GE|LE expr */
175869   -3,  /* (200) expr ::= expr EQ|NE expr */
175870   -3,  /* (201) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
175871   -3,  /* (202) expr ::= expr PLUS|MINUS expr */
175872   -3,  /* (203) expr ::= expr STAR|SLASH|REM expr */
175873   -3,  /* (204) expr ::= expr CONCAT expr */
175874   -2,  /* (205) likeop ::= NOT LIKE_KW|MATCH */
175875   -3,  /* (206) expr ::= expr likeop expr */
175876   -5,  /* (207) expr ::= expr likeop expr ESCAPE expr */
175877   -2,  /* (208) expr ::= expr ISNULL|NOTNULL */
175878   -3,  /* (209) expr ::= expr NOT NULL */
175879   -3,  /* (210) expr ::= expr IS expr */
175880   -4,  /* (211) expr ::= expr IS NOT expr */
175881   -6,  /* (212) expr ::= expr IS NOT DISTINCT FROM expr */
175882   -5,  /* (213) expr ::= expr IS DISTINCT FROM expr */
175883   -2,  /* (214) expr ::= NOT expr */
175884   -2,  /* (215) expr ::= BITNOT expr */
175885   -2,  /* (216) expr ::= PLUS|MINUS expr */
175886   -3,  /* (217) expr ::= expr PTR expr */
175887   -1,  /* (218) between_op ::= BETWEEN */
175888   -2,  /* (219) between_op ::= NOT BETWEEN */
175889   -5,  /* (220) expr ::= expr between_op expr AND expr */
175890   -1,  /* (221) in_op ::= IN */
175891   -2,  /* (222) in_op ::= NOT IN */
175892   -5,  /* (223) expr ::= expr in_op LP exprlist RP */
175893   -3,  /* (224) expr ::= LP select RP */
175894   -5,  /* (225) expr ::= expr in_op LP select RP */
175895   -5,  /* (226) expr ::= expr in_op nm dbnm paren_exprlist */
175896   -4,  /* (227) expr ::= EXISTS LP select RP */
175897   -5,  /* (228) expr ::= CASE case_operand case_exprlist case_else END */
175898   -5,  /* (229) case_exprlist ::= case_exprlist WHEN expr THEN expr */
175899   -4,  /* (230) case_exprlist ::= WHEN expr THEN expr */
175900   -2,  /* (231) case_else ::= ELSE expr */
175901    0,  /* (232) case_else ::= */
175902    0,  /* (233) case_operand ::= */
175903    0,  /* (234) exprlist ::= */
175904   -3,  /* (235) nexprlist ::= nexprlist COMMA expr */
175905   -1,  /* (236) nexprlist ::= expr */
175906    0,  /* (237) paren_exprlist ::= */
175907   -3,  /* (238) paren_exprlist ::= LP exprlist RP */
175908  -12,  /* (239) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
175909   -1,  /* (240) uniqueflag ::= UNIQUE */
175910    0,  /* (241) uniqueflag ::= */
175911    0,  /* (242) eidlist_opt ::= */
175912   -3,  /* (243) eidlist_opt ::= LP eidlist RP */
175913   -5,  /* (244) eidlist ::= eidlist COMMA nm collate sortorder */
175914   -3,  /* (245) eidlist ::= nm collate sortorder */
175915    0,  /* (246) collate ::= */
175916   -2,  /* (247) collate ::= COLLATE ID|STRING */
175917   -4,  /* (248) cmd ::= DROP INDEX ifexists fullname */
175918   -2,  /* (249) cmd ::= VACUUM vinto */
175919   -3,  /* (250) cmd ::= VACUUM nm vinto */
175920   -2,  /* (251) vinto ::= INTO expr */
175921    0,  /* (252) vinto ::= */
175922   -3,  /* (253) cmd ::= PRAGMA nm dbnm */
175923   -5,  /* (254) cmd ::= PRAGMA nm dbnm EQ nmnum */
175924   -6,  /* (255) cmd ::= PRAGMA nm dbnm LP nmnum RP */
175925   -5,  /* (256) cmd ::= PRAGMA nm dbnm EQ minus_num */
175926   -6,  /* (257) cmd ::= PRAGMA nm dbnm LP minus_num RP */
175927   -2,  /* (258) plus_num ::= PLUS INTEGER|FLOAT */
175928   -2,  /* (259) minus_num ::= MINUS INTEGER|FLOAT */
175929   -5,  /* (260) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
175930  -11,  /* (261) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
175931   -1,  /* (262) trigger_time ::= BEFORE|AFTER */
175932   -2,  /* (263) trigger_time ::= INSTEAD OF */
175933    0,  /* (264) trigger_time ::= */
175934   -1,  /* (265) trigger_event ::= DELETE|INSERT */
175935   -1,  /* (266) trigger_event ::= UPDATE */
175936   -3,  /* (267) trigger_event ::= UPDATE OF idlist */
175937    0,  /* (268) when_clause ::= */
175938   -2,  /* (269) when_clause ::= WHEN expr */
175939   -3,  /* (270) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
175940   -2,  /* (271) trigger_cmd_list ::= trigger_cmd SEMI */
175941   -3,  /* (272) trnm ::= nm DOT nm */
175942   -3,  /* (273) tridxby ::= INDEXED BY nm */
175943   -2,  /* (274) tridxby ::= NOT INDEXED */
175944   -9,  /* (275) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
175945   -8,  /* (276) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
175946   -6,  /* (277) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
175947   -3,  /* (278) trigger_cmd ::= scanpt select scanpt */
175948   -4,  /* (279) expr ::= RAISE LP IGNORE RP */
175949   -6,  /* (280) expr ::= RAISE LP raisetype COMMA nm RP */
175950   -1,  /* (281) raisetype ::= ROLLBACK */
175951   -1,  /* (282) raisetype ::= ABORT */
175952   -1,  /* (283) raisetype ::= FAIL */
175953   -4,  /* (284) cmd ::= DROP TRIGGER ifexists fullname */
175954   -6,  /* (285) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
175955   -3,  /* (286) cmd ::= DETACH database_kw_opt expr */
175956    0,  /* (287) key_opt ::= */
175957   -2,  /* (288) key_opt ::= KEY expr */
175958   -1,  /* (289) cmd ::= REINDEX */
175959   -3,  /* (290) cmd ::= REINDEX nm dbnm */
175960   -1,  /* (291) cmd ::= ANALYZE */
175961   -3,  /* (292) cmd ::= ANALYZE nm dbnm */
175962   -6,  /* (293) cmd ::= ALTER TABLE fullname RENAME TO nm */
175963   -7,  /* (294) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
175964   -6,  /* (295) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
175965   -1,  /* (296) add_column_fullname ::= fullname */
175966   -8,  /* (297) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
175967   -1,  /* (298) cmd ::= create_vtab */
175968   -4,  /* (299) cmd ::= create_vtab LP vtabarglist RP */
175969   -8,  /* (300) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
175970    0,  /* (301) vtabarg ::= */
175971   -1,  /* (302) vtabargtoken ::= ANY */
175972   -3,  /* (303) vtabargtoken ::= lp anylist RP */
175973   -1,  /* (304) lp ::= LP */
175974   -2,  /* (305) with ::= WITH wqlist */
175975   -3,  /* (306) with ::= WITH RECURSIVE wqlist */
175976   -1,  /* (307) wqas ::= AS */
175977   -2,  /* (308) wqas ::= AS MATERIALIZED */
175978   -3,  /* (309) wqas ::= AS NOT MATERIALIZED */
175979   -6,  /* (310) wqitem ::= withnm eidlist_opt wqas LP select RP */
175980   -1,  /* (311) withnm ::= nm */
175981   -1,  /* (312) wqlist ::= wqitem */
175982   -3,  /* (313) wqlist ::= wqlist COMMA wqitem */
175983   -3,  /* (314) windowdefn_list ::= windowdefn_list COMMA windowdefn */
175984   -5,  /* (315) windowdefn ::= nm AS LP window RP */
175985   -5,  /* (316) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
175986   -6,  /* (317) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
175987   -4,  /* (318) window ::= ORDER BY sortlist frame_opt */
175988   -5,  /* (319) window ::= nm ORDER BY sortlist frame_opt */
175989   -2,  /* (320) window ::= nm frame_opt */
175990    0,  /* (321) frame_opt ::= */
175991   -3,  /* (322) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
175992   -6,  /* (323) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
175993   -1,  /* (324) range_or_rows ::= RANGE|ROWS|GROUPS */
175994   -1,  /* (325) frame_bound_s ::= frame_bound */
175995   -2,  /* (326) frame_bound_s ::= UNBOUNDED PRECEDING */
175996   -1,  /* (327) frame_bound_e ::= frame_bound */
175997   -2,  /* (328) frame_bound_e ::= UNBOUNDED FOLLOWING */
175998   -2,  /* (329) frame_bound ::= expr PRECEDING|FOLLOWING */
175999   -2,  /* (330) frame_bound ::= CURRENT ROW */
176000    0,  /* (331) frame_exclude_opt ::= */
176001   -2,  /* (332) frame_exclude_opt ::= EXCLUDE frame_exclude */
176002   -2,  /* (333) frame_exclude ::= NO OTHERS */
176003   -2,  /* (334) frame_exclude ::= CURRENT ROW */
176004   -1,  /* (335) frame_exclude ::= GROUP|TIES */
176005   -2,  /* (336) window_clause ::= WINDOW windowdefn_list */
176006   -2,  /* (337) filter_over ::= filter_clause over_clause */
176007   -1,  /* (338) filter_over ::= over_clause */
176008   -1,  /* (339) filter_over ::= filter_clause */
176009   -4,  /* (340) over_clause ::= OVER LP window RP */
176010   -2,  /* (341) over_clause ::= OVER nm */
176011   -5,  /* (342) filter_clause ::= FILTER LP WHERE expr RP */
176012   -1,  /* (343) term ::= QNUMBER */
176013   -1,  /* (344) input ::= cmdlist */
176014   -2,  /* (345) cmdlist ::= cmdlist ecmd */
176015   -1,  /* (346) cmdlist ::= ecmd */
176016   -1,  /* (347) ecmd ::= SEMI */
176017   -2,  /* (348) ecmd ::= cmdx SEMI */
176018   -3,  /* (349) ecmd ::= explain cmdx SEMI */
176019    0,  /* (350) trans_opt ::= */
176020   -1,  /* (351) trans_opt ::= TRANSACTION */
176021   -2,  /* (352) trans_opt ::= TRANSACTION nm */
176022   -1,  /* (353) savepoint_opt ::= SAVEPOINT */
176023    0,  /* (354) savepoint_opt ::= */
176024   -2,  /* (355) cmd ::= create_table create_table_args */
176025   -1,  /* (356) table_option_set ::= table_option */
176026   -4,  /* (357) columnlist ::= columnlist COMMA columnname carglist */
176027   -2,  /* (358) columnlist ::= columnname carglist */
176028   -1,  /* (359) nm ::= ID|INDEXED|JOIN_KW */
176029   -1,  /* (360) nm ::= STRING */
176030   -1,  /* (361) typetoken ::= typename */
176031   -1,  /* (362) typename ::= ID|STRING */
176032   -1,  /* (363) signed ::= plus_num */
176033   -1,  /* (364) signed ::= minus_num */
176034   -2,  /* (365) carglist ::= carglist ccons */
176035    0,  /* (366) carglist ::= */
176036   -2,  /* (367) ccons ::= NULL onconf */
176037   -4,  /* (368) ccons ::= GENERATED ALWAYS AS generated */
176038   -2,  /* (369) ccons ::= AS generated */
176039   -2,  /* (370) conslist_opt ::= COMMA conslist */
176040   -3,  /* (371) conslist ::= conslist tconscomma tcons */
176041   -1,  /* (372) conslist ::= tcons */
176042    0,  /* (373) tconscomma ::= */
176043   -1,  /* (374) defer_subclause_opt ::= defer_subclause */
176044   -1,  /* (375) resolvetype ::= raisetype */
176045   -1,  /* (376) selectnowith ::= oneselect */
176046   -1,  /* (377) oneselect ::= values */
176047   -2,  /* (378) sclp ::= selcollist COMMA */
176048   -1,  /* (379) as ::= ID|STRING */
176049   -1,  /* (380) indexed_opt ::= indexed_by */
176050    0,  /* (381) returning ::= */
176051   -1,  /* (382) expr ::= term */
176052   -1,  /* (383) likeop ::= LIKE_KW|MATCH */
176053   -1,  /* (384) case_operand ::= expr */
176054   -1,  /* (385) exprlist ::= nexprlist */
176055   -1,  /* (386) nmnum ::= plus_num */
176056   -1,  /* (387) nmnum ::= nm */
176057   -1,  /* (388) nmnum ::= ON */
176058   -1,  /* (389) nmnum ::= DELETE */
176059   -1,  /* (390) nmnum ::= DEFAULT */
176060   -1,  /* (391) plus_num ::= INTEGER|FLOAT */
176061    0,  /* (392) foreach_clause ::= */
176062   -3,  /* (393) foreach_clause ::= FOR EACH ROW */
176063   -1,  /* (394) trnm ::= nm */
176064    0,  /* (395) tridxby ::= */
176065   -1,  /* (396) database_kw_opt ::= DATABASE */
176066    0,  /* (397) database_kw_opt ::= */
176067    0,  /* (398) kwcolumn_opt ::= */
176068   -1,  /* (399) kwcolumn_opt ::= COLUMNKW */
176069   -1,  /* (400) vtabarglist ::= vtabarg */
176070   -3,  /* (401) vtabarglist ::= vtabarglist COMMA vtabarg */
176071   -2,  /* (402) vtabarg ::= vtabarg vtabargtoken */
176072    0,  /* (403) anylist ::= */
176073   -4,  /* (404) anylist ::= anylist LP anylist RP */
176074   -2,  /* (405) anylist ::= anylist ANY */
176075    0,  /* (406) with ::= */
176076   -1,  /* (407) windowdefn_list ::= windowdefn */
176077   -1,  /* (408) window ::= frame_opt */
176078};
176079
176080static void yy_accept(yyParser*);  /* Forward Declaration */
176081
176082/*
176083** Perform a reduce action and the shift that must immediately
176084** follow the reduce.
176085**
176086** The yyLookahead and yyLookaheadToken parameters provide reduce actions
176087** access to the lookahead token (if any).  The yyLookahead will be YYNOCODE
176088** if the lookahead token has already been consumed.  As this procedure is
176089** only called from one place, optimizing compilers will in-line it, which
176090** means that the extra parameters have no performance impact.
176091*/
176092static YYACTIONTYPE yy_reduce(
176093  yyParser *yypParser,         /* The parser */
176094  unsigned int yyruleno,       /* Number of the rule by which to reduce */
176095  int yyLookahead,             /* Lookahead token, or YYNOCODE if none */
176096  sqlite3ParserTOKENTYPE yyLookaheadToken  /* Value of the lookahead token */
176097  sqlite3ParserCTX_PDECL                   /* %extra_context */
176098){
176099  int yygoto;                     /* The next state */
176100  YYACTIONTYPE yyact;             /* The next action */
176101  yyStackEntry *yymsp;            /* The top of the parser's stack */
176102  int yysize;                     /* Amount to pop the stack */
176103  sqlite3ParserARG_FETCH
176104  (void)yyLookahead;
176105  (void)yyLookaheadToken;
176106  yymsp = yypParser->yytos;
176107
176108  switch( yyruleno ){
176109  /* Beginning here are the reduction cases.  A typical example
176110  ** follows:
176111  **   case 0:
176112  **  #line <lineno> <grammarfile>
176113  **     { ... }           // User supplied code
176114  **  #line <lineno> <thisfile>
176115  **     break;
176116  */
176117/********** Begin reduce actions **********************************************/
176118        YYMINORTYPE yylhsminor;
176119      case 0: /* explain ::= EXPLAIN */
176120{ if( pParse->pReprepare==0 ) pParse->explain = 1; }
176121        break;
176122      case 1: /* explain ::= EXPLAIN QUERY PLAN */
176123{ if( pParse->pReprepare==0 ) pParse->explain = 2; }
176124        break;
176125      case 2: /* cmdx ::= cmd */
176126{ sqlite3FinishCoding(pParse); }
176127        break;
176128      case 3: /* cmd ::= BEGIN transtype trans_opt */
176129{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy144);}
176130        break;
176131      case 4: /* transtype ::= */
176132{yymsp[1].minor.yy144 = TK_DEFERRED;}
176133        break;
176134      case 5: /* transtype ::= DEFERRED */
176135      case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
176136      case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
176137      case 324: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==324);
176138{yymsp[0].minor.yy144 = yymsp[0].major; /*A-overwrites-X*/}
176139        break;
176140      case 8: /* cmd ::= COMMIT|END trans_opt */
176141      case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
176142{sqlite3EndTransaction(pParse,yymsp[-1].major);}
176143        break;
176144      case 10: /* cmd ::= SAVEPOINT nm */
176145{
176146  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
176147}
176148        break;
176149      case 11: /* cmd ::= RELEASE savepoint_opt nm */
176150{
176151  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
176152}
176153        break;
176154      case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
176155{
176156  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
176157}
176158        break;
176159      case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
176160{
176161   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy144,0,0,yymsp[-2].minor.yy144);
176162}
176163        break;
176164      case 14: /* createkw ::= CREATE */
176165{disableLookaside(pParse);}
176166        break;
176167      case 15: /* ifnotexists ::= */
176168      case 18: /* temp ::= */ yytestcase(yyruleno==18);
176169      case 47: /* autoinc ::= */ yytestcase(yyruleno==47);
176170      case 62: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==62);
176171      case 72: /* defer_subclause_opt ::= */ yytestcase(yyruleno==72);
176172      case 81: /* ifexists ::= */ yytestcase(yyruleno==81);
176173      case 100: /* distinct ::= */ yytestcase(yyruleno==100);
176174      case 246: /* collate ::= */ yytestcase(yyruleno==246);
176175{yymsp[1].minor.yy144 = 0;}
176176        break;
176177      case 16: /* ifnotexists ::= IF NOT EXISTS */
176178{yymsp[-2].minor.yy144 = 1;}
176179        break;
176180      case 17: /* temp ::= TEMP */
176181{yymsp[0].minor.yy144 = pParse->db->init.busy==0;}
176182        break;
176183      case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_option_set */
176184{
176185  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy391,0);
176186}
176187        break;
176188      case 20: /* create_table_args ::= AS select */
176189{
176190  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy555);
176191  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy555);
176192}
176193        break;
176194      case 21: /* table_option_set ::= */
176195{yymsp[1].minor.yy391 = 0;}
176196        break;
176197      case 22: /* table_option_set ::= table_option_set COMMA table_option */
176198{yylhsminor.yy391 = yymsp[-2].minor.yy391|yymsp[0].minor.yy391;}
176199  yymsp[-2].minor.yy391 = yylhsminor.yy391;
176200        break;
176201      case 23: /* table_option ::= WITHOUT nm */
176202{
176203  if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
176204    yymsp[-1].minor.yy391 = TF_WithoutRowid | TF_NoVisibleRowid;
176205  }else{
176206    yymsp[-1].minor.yy391 = 0;
176207    sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
176208  }
176209}
176210        break;
176211      case 24: /* table_option ::= nm */
176212{
176213  if( yymsp[0].minor.yy0.n==6 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"strict",6)==0 ){
176214    yylhsminor.yy391 = TF_Strict;
176215  }else{
176216    yylhsminor.yy391 = 0;
176217    sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
176218  }
176219}
176220  yymsp[0].minor.yy391 = yylhsminor.yy391;
176221        break;
176222      case 25: /* columnname ::= nm typetoken */
176223{sqlite3AddColumn(pParse,yymsp[-1].minor.yy0,yymsp[0].minor.yy0);}
176224        break;
176225      case 26: /* typetoken ::= */
176226      case 65: /* conslist_opt ::= */ yytestcase(yyruleno==65);
176227      case 106: /* as ::= */ yytestcase(yyruleno==106);
176228{yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
176229        break;
176230      case 27: /* typetoken ::= typename LP signed RP */
176231{
176232  yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
176233}
176234        break;
176235      case 28: /* typetoken ::= typename LP signed COMMA signed RP */
176236{
176237  yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
176238}
176239        break;
176240      case 29: /* typename ::= typename ID|STRING */
176241{yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
176242        break;
176243      case 30: /* scanpt ::= */
176244{
176245  assert( yyLookahead!=YYNOCODE );
176246  yymsp[1].minor.yy168 = yyLookaheadToken.z;
176247}
176248        break;
176249      case 31: /* scantok ::= */
176250{
176251  assert( yyLookahead!=YYNOCODE );
176252  yymsp[1].minor.yy0 = yyLookaheadToken;
176253}
176254        break;
176255      case 32: /* ccons ::= CONSTRAINT nm */
176256      case 67: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==67);
176257{pParse->constraintName = yymsp[0].minor.yy0;}
176258        break;
176259      case 33: /* ccons ::= DEFAULT scantok term */
176260{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy454,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
176261        break;
176262      case 34: /* ccons ::= DEFAULT LP expr RP */
176263{sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy454,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
176264        break;
176265      case 35: /* ccons ::= DEFAULT PLUS scantok term */
176266{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy454,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
176267        break;
176268      case 36: /* ccons ::= DEFAULT MINUS scantok term */
176269{
176270  Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy454, 0);
176271  sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);
176272}
176273        break;
176274      case 37: /* ccons ::= DEFAULT scantok ID|INDEXED */
176275{
176276  Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0);
176277  if( p ){
176278    sqlite3ExprIdToTrueFalse(p);
176279    testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );
176280  }
176281    sqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n);
176282}
176283        break;
176284      case 38: /* ccons ::= NOT NULL onconf */
176285{sqlite3AddNotNull(pParse, yymsp[0].minor.yy144);}
176286        break;
176287      case 39: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
176288{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy144,yymsp[0].minor.yy144,yymsp[-2].minor.yy144);}
176289        break;
176290      case 40: /* ccons ::= UNIQUE onconf */
176291{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy144,0,0,0,0,
176292                                   SQLITE_IDXTYPE_UNIQUE);}
176293        break;
176294      case 41: /* ccons ::= CHECK LP expr RP */
176295{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy454,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy0.z);}
176296        break;
176297      case 42: /* ccons ::= REFERENCES nm eidlist_opt refargs */
176298{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy144);}
176299        break;
176300      case 43: /* ccons ::= defer_subclause */
176301{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy144);}
176302        break;
176303      case 44: /* ccons ::= COLLATE ID|STRING */
176304{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
176305        break;
176306      case 45: /* generated ::= LP expr RP */
176307{sqlite3AddGenerated(pParse,yymsp[-1].minor.yy454,0);}
176308        break;
176309      case 46: /* generated ::= LP expr RP ID */
176310{sqlite3AddGenerated(pParse,yymsp[-2].minor.yy454,&yymsp[0].minor.yy0);}
176311        break;
176312      case 48: /* autoinc ::= AUTOINCR */
176313{yymsp[0].minor.yy144 = 1;}
176314        break;
176315      case 49: /* refargs ::= */
176316{ yymsp[1].minor.yy144 = OE_None*0x0101; /* EV: R-19803-45884 */}
176317        break;
176318      case 50: /* refargs ::= refargs refarg */
176319{ yymsp[-1].minor.yy144 = (yymsp[-1].minor.yy144 & ~yymsp[0].minor.yy383.mask) | yymsp[0].minor.yy383.value; }
176320        break;
176321      case 51: /* refarg ::= MATCH nm */
176322{ yymsp[-1].minor.yy383.value = 0;     yymsp[-1].minor.yy383.mask = 0x000000; }
176323        break;
176324      case 52: /* refarg ::= ON INSERT refact */
176325{ yymsp[-2].minor.yy383.value = 0;     yymsp[-2].minor.yy383.mask = 0x000000; }
176326        break;
176327      case 53: /* refarg ::= ON DELETE refact */
176328{ yymsp[-2].minor.yy383.value = yymsp[0].minor.yy144;     yymsp[-2].minor.yy383.mask = 0x0000ff; }
176329        break;
176330      case 54: /* refarg ::= ON UPDATE refact */
176331{ yymsp[-2].minor.yy383.value = yymsp[0].minor.yy144<<8;  yymsp[-2].minor.yy383.mask = 0x00ff00; }
176332        break;
176333      case 55: /* refact ::= SET NULL */
176334{ yymsp[-1].minor.yy144 = OE_SetNull;  /* EV: R-33326-45252 */}
176335        break;
176336      case 56: /* refact ::= SET DEFAULT */
176337{ yymsp[-1].minor.yy144 = OE_SetDflt;  /* EV: R-33326-45252 */}
176338        break;
176339      case 57: /* refact ::= CASCADE */
176340{ yymsp[0].minor.yy144 = OE_Cascade;  /* EV: R-33326-45252 */}
176341        break;
176342      case 58: /* refact ::= RESTRICT */
176343{ yymsp[0].minor.yy144 = OE_Restrict; /* EV: R-33326-45252 */}
176344        break;
176345      case 59: /* refact ::= NO ACTION */
176346{ yymsp[-1].minor.yy144 = OE_None;     /* EV: R-33326-45252 */}
176347        break;
176348      case 60: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
176349{yymsp[-2].minor.yy144 = 0;}
176350        break;
176351      case 61: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
176352      case 76: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==76);
176353      case 173: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==173);
176354{yymsp[-1].minor.yy144 = yymsp[0].minor.yy144;}
176355        break;
176356      case 63: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
176357      case 80: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==80);
176358      case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
176359      case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
176360      case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
176361{yymsp[-1].minor.yy144 = 1;}
176362        break;
176363      case 64: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
176364{yymsp[-1].minor.yy144 = 0;}
176365        break;
176366      case 66: /* tconscomma ::= COMMA */
176367{pParse->constraintName.n = 0;}
176368        break;
176369      case 68: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
176370{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy144,yymsp[-2].minor.yy144,0);}
176371        break;
176372      case 69: /* tcons ::= UNIQUE LP sortlist RP onconf */
176373{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy144,0,0,0,0,
176374                                       SQLITE_IDXTYPE_UNIQUE);}
176375        break;
176376      case 70: /* tcons ::= CHECK LP expr RP onconf */
176377{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy454,yymsp[-3].minor.yy0.z,yymsp[-1].minor.yy0.z);}
176378        break;
176379      case 71: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
176380{
176381    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy144);
176382    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy144);
176383}
176384        break;
176385      case 73: /* onconf ::= */
176386      case 75: /* orconf ::= */ yytestcase(yyruleno==75);
176387{yymsp[1].minor.yy144 = OE_Default;}
176388        break;
176389      case 74: /* onconf ::= ON CONFLICT resolvetype */
176390{yymsp[-2].minor.yy144 = yymsp[0].minor.yy144;}
176391        break;
176392      case 77: /* resolvetype ::= IGNORE */
176393{yymsp[0].minor.yy144 = OE_Ignore;}
176394        break;
176395      case 78: /* resolvetype ::= REPLACE */
176396      case 174: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==174);
176397{yymsp[0].minor.yy144 = OE_Replace;}
176398        break;
176399      case 79: /* cmd ::= DROP TABLE ifexists fullname */
176400{
176401  sqlite3DropTable(pParse, yymsp[0].minor.yy203, 0, yymsp[-1].minor.yy144);
176402}
176403        break;
176404      case 82: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
176405{
176406  sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[0].minor.yy555, yymsp[-7].minor.yy144, yymsp[-5].minor.yy144);
176407}
176408        break;
176409      case 83: /* cmd ::= DROP VIEW ifexists fullname */
176410{
176411  sqlite3DropTable(pParse, yymsp[0].minor.yy203, 1, yymsp[-1].minor.yy144);
176412}
176413        break;
176414      case 84: /* cmd ::= select */
176415{
176416  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0, 0};
176417  sqlite3Select(pParse, yymsp[0].minor.yy555, &dest);
176418  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy555);
176419}
176420        break;
176421      case 85: /* select ::= WITH wqlist selectnowith */
176422{yymsp[-2].minor.yy555 = attachWithToSelect(pParse,yymsp[0].minor.yy555,yymsp[-1].minor.yy59);}
176423        break;
176424      case 86: /* select ::= WITH RECURSIVE wqlist selectnowith */
176425{yymsp[-3].minor.yy555 = attachWithToSelect(pParse,yymsp[0].minor.yy555,yymsp[-1].minor.yy59);}
176426        break;
176427      case 87: /* select ::= selectnowith */
176428{
176429  Select *p = yymsp[0].minor.yy555;
176430  if( p ){
176431    parserDoubleLinkSelect(pParse, p);
176432  }
176433}
176434        break;
176435      case 88: /* selectnowith ::= selectnowith multiselect_op oneselect */
176436{
176437  Select *pRhs = yymsp[0].minor.yy555;
176438  Select *pLhs = yymsp[-2].minor.yy555;
176439  if( pRhs && pRhs->pPrior ){
176440    SrcList *pFrom;
176441    Token x;
176442    x.n = 0;
176443    parserDoubleLinkSelect(pParse, pRhs);
176444    pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0);
176445    pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
176446  }
176447  if( pRhs ){
176448    pRhs->op = (u8)yymsp[-1].minor.yy144;
176449    pRhs->pPrior = pLhs;
176450    if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
176451    pRhs->selFlags &= ~SF_MultiValue;
176452    if( yymsp[-1].minor.yy144!=TK_ALL ) pParse->hasCompound = 1;
176453  }else{
176454    sqlite3SelectDelete(pParse->db, pLhs);
176455  }
176456  yymsp[-2].minor.yy555 = pRhs;
176457}
176458        break;
176459      case 89: /* multiselect_op ::= UNION */
176460      case 91: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==91);
176461{yymsp[0].minor.yy144 = yymsp[0].major; /*A-overwrites-OP*/}
176462        break;
176463      case 90: /* multiselect_op ::= UNION ALL */
176464{yymsp[-1].minor.yy144 = TK_ALL;}
176465        break;
176466      case 92: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
176467{
176468  yymsp[-8].minor.yy555 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy14,yymsp[-5].minor.yy203,yymsp[-4].minor.yy454,yymsp[-3].minor.yy14,yymsp[-2].minor.yy454,yymsp[-1].minor.yy14,yymsp[-7].minor.yy144,yymsp[0].minor.yy454);
176469}
176470        break;
176471      case 93: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
176472{
176473  yymsp[-9].minor.yy555 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy14,yymsp[-6].minor.yy203,yymsp[-5].minor.yy454,yymsp[-4].minor.yy14,yymsp[-3].minor.yy454,yymsp[-1].minor.yy14,yymsp[-8].minor.yy144,yymsp[0].minor.yy454);
176474  if( yymsp[-9].minor.yy555 ){
176475    yymsp[-9].minor.yy555->pWinDefn = yymsp[-2].minor.yy211;
176476  }else{
176477    sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy211);
176478  }
176479}
176480        break;
176481      case 94: /* values ::= VALUES LP nexprlist RP */
176482{
176483  yymsp[-3].minor.yy555 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0);
176484}
176485        break;
176486      case 95: /* oneselect ::= mvalues */
176487{
176488  sqlite3MultiValuesEnd(pParse, yymsp[0].minor.yy555);
176489}
176490        break;
176491      case 96: /* mvalues ::= values COMMA LP nexprlist RP */
176492      case 97: /* mvalues ::= mvalues COMMA LP nexprlist RP */ yytestcase(yyruleno==97);
176493{
176494  yymsp[-4].minor.yy555 = sqlite3MultiValues(pParse, yymsp[-4].minor.yy555, yymsp[-1].minor.yy14);
176495}
176496        break;
176497      case 98: /* distinct ::= DISTINCT */
176498{yymsp[0].minor.yy144 = SF_Distinct;}
176499        break;
176500      case 99: /* distinct ::= ALL */
176501{yymsp[0].minor.yy144 = SF_All;}
176502        break;
176503      case 101: /* sclp ::= */
176504      case 134: /* orderby_opt ::= */ yytestcase(yyruleno==134);
176505      case 144: /* groupby_opt ::= */ yytestcase(yyruleno==144);
176506      case 234: /* exprlist ::= */ yytestcase(yyruleno==234);
176507      case 237: /* paren_exprlist ::= */ yytestcase(yyruleno==237);
176508      case 242: /* eidlist_opt ::= */ yytestcase(yyruleno==242);
176509{yymsp[1].minor.yy14 = 0;}
176510        break;
176511      case 102: /* selcollist ::= sclp scanpt expr scanpt as */
176512{
176513   yymsp[-4].minor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[-2].minor.yy454);
176514   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy14, &yymsp[0].minor.yy0, 1);
176515   sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy14,yymsp[-3].minor.yy168,yymsp[-1].minor.yy168);
176516}
176517        break;
176518      case 103: /* selcollist ::= sclp scanpt STAR */
176519{
176520  Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
176521  sqlite3ExprSetErrorOffset(p, (int)(yymsp[0].minor.yy0.z - pParse->zTail));
176522  yymsp[-2].minor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, p);
176523}
176524        break;
176525      case 104: /* selcollist ::= sclp scanpt nm DOT STAR */
176526{
176527  Expr *pRight, *pLeft, *pDot;
176528  pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
176529  sqlite3ExprSetErrorOffset(pRight, (int)(yymsp[0].minor.yy0.z - pParse->zTail));
176530  pLeft = tokenExpr(pParse, TK_ID, yymsp[-2].minor.yy0);
176531  pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
176532  yymsp[-4].minor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, pDot);
176533}
176534        break;
176535      case 105: /* as ::= AS nm */
176536      case 117: /* dbnm ::= DOT nm */ yytestcase(yyruleno==117);
176537      case 258: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==258);
176538      case 259: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==259);
176539{yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
176540        break;
176541      case 107: /* from ::= */
176542      case 110: /* stl_prefix ::= */ yytestcase(yyruleno==110);
176543{yymsp[1].minor.yy203 = 0;}
176544        break;
176545      case 108: /* from ::= FROM seltablist */
176546{
176547  yymsp[-1].minor.yy203 = yymsp[0].minor.yy203;
176548  sqlite3SrcListShiftJoinType(pParse,yymsp[-1].minor.yy203);
176549}
176550        break;
176551      case 109: /* stl_prefix ::= seltablist joinop */
176552{
176553   if( ALWAYS(yymsp[-1].minor.yy203 && yymsp[-1].minor.yy203->nSrc>0) ) yymsp[-1].minor.yy203->a[yymsp[-1].minor.yy203->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy144;
176554}
176555        break;
176556      case 111: /* seltablist ::= stl_prefix nm dbnm as on_using */
176557{
176558  yymsp[-4].minor.yy203 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-4].minor.yy203,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0,&yymsp[0].minor.yy269);
176559}
176560        break;
176561      case 112: /* seltablist ::= stl_prefix nm dbnm as indexed_by on_using */
176562{
176563  yymsp[-5].minor.yy203 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy203,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,0,&yymsp[0].minor.yy269);
176564  sqlite3SrcListIndexedBy(pParse, yymsp[-5].minor.yy203, &yymsp[-1].minor.yy0);
176565}
176566        break;
176567      case 113: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_using */
176568{
176569  yymsp[-7].minor.yy203 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-7].minor.yy203,&yymsp[-6].minor.yy0,&yymsp[-5].minor.yy0,&yymsp[-1].minor.yy0,0,&yymsp[0].minor.yy269);
176570  sqlite3SrcListFuncArgs(pParse, yymsp[-7].minor.yy203, yymsp[-3].minor.yy14);
176571}
176572        break;
176573      case 114: /* seltablist ::= stl_prefix LP select RP as on_using */
176574{
176575    yymsp[-5].minor.yy203 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy203,0,0,&yymsp[-1].minor.yy0,yymsp[-3].minor.yy555,&yymsp[0].minor.yy269);
176576  }
176577        break;
176578      case 115: /* seltablist ::= stl_prefix LP seltablist RP as on_using */
176579{
176580    if( yymsp[-5].minor.yy203==0 && yymsp[-1].minor.yy0.n==0 && yymsp[0].minor.yy269.pOn==0 && yymsp[0].minor.yy269.pUsing==0 ){
176581      yymsp[-5].minor.yy203 = yymsp[-3].minor.yy203;
176582    }else if( ALWAYS(yymsp[-3].minor.yy203!=0) && yymsp[-3].minor.yy203->nSrc==1 ){
176583      yymsp[-5].minor.yy203 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy203,0,0,&yymsp[-1].minor.yy0,0,&yymsp[0].minor.yy269);
176584      if( yymsp[-5].minor.yy203 ){
176585        SrcItem *pNew = &yymsp[-5].minor.yy203->a[yymsp[-5].minor.yy203->nSrc-1];
176586        SrcItem *pOld = yymsp[-3].minor.yy203->a;
176587        pNew->zName = pOld->zName;
176588        pNew->zDatabase = pOld->zDatabase;
176589        pNew->pSelect = pOld->pSelect;
176590        if( pNew->pSelect && (pNew->pSelect->selFlags & SF_NestedFrom)!=0 ){
176591          pNew->fg.isNestedFrom = 1;
176592        }
176593        if( pOld->fg.isTabFunc ){
176594          pNew->u1.pFuncArg = pOld->u1.pFuncArg;
176595          pOld->u1.pFuncArg = 0;
176596          pOld->fg.isTabFunc = 0;
176597          pNew->fg.isTabFunc = 1;
176598        }
176599        pOld->zName = pOld->zDatabase = 0;
176600        pOld->pSelect = 0;
176601      }
176602      sqlite3SrcListDelete(pParse->db, yymsp[-3].minor.yy203);
176603    }else{
176604      Select *pSubquery;
176605      sqlite3SrcListShiftJoinType(pParse,yymsp[-3].minor.yy203);
176606      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-3].minor.yy203,0,0,0,0,SF_NestedFrom,0);
176607      yymsp[-5].minor.yy203 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy203,0,0,&yymsp[-1].minor.yy0,pSubquery,&yymsp[0].minor.yy269);
176608    }
176609  }
176610        break;
176611      case 116: /* dbnm ::= */
176612      case 131: /* indexed_opt ::= */ yytestcase(yyruleno==131);
176613{yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
176614        break;
176615      case 118: /* fullname ::= nm */
176616{
176617  yylhsminor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0);
176618  if( IN_RENAME_OBJECT && yylhsminor.yy203 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy203->a[0].zName, &yymsp[0].minor.yy0);
176619}
176620  yymsp[0].minor.yy203 = yylhsminor.yy203;
176621        break;
176622      case 119: /* fullname ::= nm DOT nm */
176623{
176624  yylhsminor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
176625  if( IN_RENAME_OBJECT && yylhsminor.yy203 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy203->a[0].zName, &yymsp[0].minor.yy0);
176626}
176627  yymsp[-2].minor.yy203 = yylhsminor.yy203;
176628        break;
176629      case 120: /* xfullname ::= nm */
176630{yymsp[0].minor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
176631        break;
176632      case 121: /* xfullname ::= nm DOT nm */
176633{yymsp[-2].minor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
176634        break;
176635      case 122: /* xfullname ::= nm DOT nm AS nm */
176636{
176637   yymsp[-4].minor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/
176638   if( yymsp[-4].minor.yy203 ) yymsp[-4].minor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
176639}
176640        break;
176641      case 123: /* xfullname ::= nm AS nm */
176642{
176643   yymsp[-2].minor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/
176644   if( yymsp[-2].minor.yy203 ) yymsp[-2].minor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
176645}
176646        break;
176647      case 124: /* joinop ::= COMMA|JOIN */
176648{ yymsp[0].minor.yy144 = JT_INNER; }
176649        break;
176650      case 125: /* joinop ::= JOIN_KW JOIN */
176651{yymsp[-1].minor.yy144 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}
176652        break;
176653      case 126: /* joinop ::= JOIN_KW nm JOIN */
176654{yymsp[-2].minor.yy144 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
176655        break;
176656      case 127: /* joinop ::= JOIN_KW nm nm JOIN */
176657{yymsp[-3].minor.yy144 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
176658        break;
176659      case 128: /* on_using ::= ON expr */
176660{yymsp[-1].minor.yy269.pOn = yymsp[0].minor.yy454; yymsp[-1].minor.yy269.pUsing = 0;}
176661        break;
176662      case 129: /* on_using ::= USING LP idlist RP */
176663{yymsp[-3].minor.yy269.pOn = 0; yymsp[-3].minor.yy269.pUsing = yymsp[-1].minor.yy132;}
176664        break;
176665      case 130: /* on_using ::= */
176666{yymsp[1].minor.yy269.pOn = 0; yymsp[1].minor.yy269.pUsing = 0;}
176667        break;
176668      case 132: /* indexed_by ::= INDEXED BY nm */
176669{yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
176670        break;
176671      case 133: /* indexed_by ::= NOT INDEXED */
176672{yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
176673        break;
176674      case 135: /* orderby_opt ::= ORDER BY sortlist */
176675      case 145: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==145);
176676{yymsp[-2].minor.yy14 = yymsp[0].minor.yy14;}
176677        break;
176678      case 136: /* sortlist ::= sortlist COMMA expr sortorder nulls */
176679{
176680  yymsp[-4].minor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14,yymsp[-2].minor.yy454);
176681  sqlite3ExprListSetSortOrder(yymsp[-4].minor.yy14,yymsp[-1].minor.yy144,yymsp[0].minor.yy144);
176682}
176683        break;
176684      case 137: /* sortlist ::= expr sortorder nulls */
176685{
176686  yymsp[-2].minor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-2].minor.yy454); /*A-overwrites-Y*/
176687  sqlite3ExprListSetSortOrder(yymsp[-2].minor.yy14,yymsp[-1].minor.yy144,yymsp[0].minor.yy144);
176688}
176689        break;
176690      case 138: /* sortorder ::= ASC */
176691{yymsp[0].minor.yy144 = SQLITE_SO_ASC;}
176692        break;
176693      case 139: /* sortorder ::= DESC */
176694{yymsp[0].minor.yy144 = SQLITE_SO_DESC;}
176695        break;
176696      case 140: /* sortorder ::= */
176697      case 143: /* nulls ::= */ yytestcase(yyruleno==143);
176698{yymsp[1].minor.yy144 = SQLITE_SO_UNDEFINED;}
176699        break;
176700      case 141: /* nulls ::= NULLS FIRST */
176701{yymsp[-1].minor.yy144 = SQLITE_SO_ASC;}
176702        break;
176703      case 142: /* nulls ::= NULLS LAST */
176704{yymsp[-1].minor.yy144 = SQLITE_SO_DESC;}
176705        break;
176706      case 146: /* having_opt ::= */
176707      case 148: /* limit_opt ::= */ yytestcase(yyruleno==148);
176708      case 153: /* where_opt ::= */ yytestcase(yyruleno==153);
176709      case 155: /* where_opt_ret ::= */ yytestcase(yyruleno==155);
176710      case 232: /* case_else ::= */ yytestcase(yyruleno==232);
176711      case 233: /* case_operand ::= */ yytestcase(yyruleno==233);
176712      case 252: /* vinto ::= */ yytestcase(yyruleno==252);
176713{yymsp[1].minor.yy454 = 0;}
176714        break;
176715      case 147: /* having_opt ::= HAVING expr */
176716      case 154: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==154);
176717      case 156: /* where_opt_ret ::= WHERE expr */ yytestcase(yyruleno==156);
176718      case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
176719      case 251: /* vinto ::= INTO expr */ yytestcase(yyruleno==251);
176720{yymsp[-1].minor.yy454 = yymsp[0].minor.yy454;}
176721        break;
176722      case 149: /* limit_opt ::= LIMIT expr */
176723{yymsp[-1].minor.yy454 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy454,0);}
176724        break;
176725      case 150: /* limit_opt ::= LIMIT expr OFFSET expr */
176726{yymsp[-3].minor.yy454 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy454,yymsp[0].minor.yy454);}
176727        break;
176728      case 151: /* limit_opt ::= LIMIT expr COMMA expr */
176729{yymsp[-3].minor.yy454 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy454,yymsp[-2].minor.yy454);}
176730        break;
176731      case 152: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret */
176732{
176733  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy203, &yymsp[-1].minor.yy0);
176734  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy203,yymsp[0].minor.yy454,0,0);
176735}
176736        break;
176737      case 157: /* where_opt_ret ::= RETURNING selcollist */
176738{sqlite3AddReturning(pParse,yymsp[0].minor.yy14); yymsp[-1].minor.yy454 = 0;}
176739        break;
176740      case 158: /* where_opt_ret ::= WHERE expr RETURNING selcollist */
176741{sqlite3AddReturning(pParse,yymsp[0].minor.yy14); yymsp[-3].minor.yy454 = yymsp[-2].minor.yy454;}
176742        break;
176743      case 159: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret */
176744{
176745  sqlite3SrcListIndexedBy(pParse, yymsp[-5].minor.yy203, &yymsp[-4].minor.yy0);
176746  sqlite3ExprListCheckLength(pParse,yymsp[-2].minor.yy14,"set list");
176747  if( yymsp[-1].minor.yy203 ){
176748    SrcList *pFromClause = yymsp[-1].minor.yy203;
176749    if( pFromClause->nSrc>1 ){
176750      Select *pSubquery;
176751      Token as;
176752      pSubquery = sqlite3SelectNew(pParse,0,pFromClause,0,0,0,0,SF_NestedFrom,0);
176753      as.n = 0;
176754      as.z = 0;
176755      pFromClause = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&as,pSubquery,0);
176756    }
176757    yymsp[-5].minor.yy203 = sqlite3SrcListAppendList(pParse, yymsp[-5].minor.yy203, pFromClause);
176758  }
176759  sqlite3Update(pParse,yymsp[-5].minor.yy203,yymsp[-2].minor.yy14,yymsp[0].minor.yy454,yymsp[-6].minor.yy144,0,0,0);
176760}
176761        break;
176762      case 160: /* setlist ::= setlist COMMA nm EQ expr */
176763{
176764  yymsp[-4].minor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy454);
176765  sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy14, &yymsp[-2].minor.yy0, 1);
176766}
176767        break;
176768      case 161: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
176769{
176770  yymsp[-6].minor.yy14 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy14, yymsp[-3].minor.yy132, yymsp[0].minor.yy454);
176771}
176772        break;
176773      case 162: /* setlist ::= nm EQ expr */
176774{
176775  yylhsminor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy454);
176776  sqlite3ExprListSetName(pParse, yylhsminor.yy14, &yymsp[-2].minor.yy0, 1);
176777}
176778  yymsp[-2].minor.yy14 = yylhsminor.yy14;
176779        break;
176780      case 163: /* setlist ::= LP idlist RP EQ expr */
176781{
176782  yymsp[-4].minor.yy14 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy132, yymsp[0].minor.yy454);
176783}
176784        break;
176785      case 164: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
176786{
176787  sqlite3Insert(pParse, yymsp[-3].minor.yy203, yymsp[-1].minor.yy555, yymsp[-2].minor.yy132, yymsp[-5].minor.yy144, yymsp[0].minor.yy122);
176788}
176789        break;
176790      case 165: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning */
176791{
176792  sqlite3Insert(pParse, yymsp[-4].minor.yy203, 0, yymsp[-3].minor.yy132, yymsp[-6].minor.yy144, 0);
176793}
176794        break;
176795      case 166: /* upsert ::= */
176796{ yymsp[1].minor.yy122 = 0; }
176797        break;
176798      case 167: /* upsert ::= RETURNING selcollist */
176799{ yymsp[-1].minor.yy122 = 0; sqlite3AddReturning(pParse,yymsp[0].minor.yy14); }
176800        break;
176801      case 168: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert */
176802{ yymsp[-11].minor.yy122 = sqlite3UpsertNew(pParse->db,yymsp[-8].minor.yy14,yymsp[-6].minor.yy454,yymsp[-2].minor.yy14,yymsp[-1].minor.yy454,yymsp[0].minor.yy122);}
176803        break;
176804      case 169: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert */
176805{ yymsp[-8].minor.yy122 = sqlite3UpsertNew(pParse->db,yymsp[-5].minor.yy14,yymsp[-3].minor.yy454,0,0,yymsp[0].minor.yy122); }
176806        break;
176807      case 170: /* upsert ::= ON CONFLICT DO NOTHING returning */
176808{ yymsp[-4].minor.yy122 = sqlite3UpsertNew(pParse->db,0,0,0,0,0); }
176809        break;
176810      case 171: /* upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning */
176811{ yymsp[-7].minor.yy122 = sqlite3UpsertNew(pParse->db,0,0,yymsp[-2].minor.yy14,yymsp[-1].minor.yy454,0);}
176812        break;
176813      case 172: /* returning ::= RETURNING selcollist */
176814{sqlite3AddReturning(pParse,yymsp[0].minor.yy14);}
176815        break;
176816      case 175: /* idlist_opt ::= */
176817{yymsp[1].minor.yy132 = 0;}
176818        break;
176819      case 176: /* idlist_opt ::= LP idlist RP */
176820{yymsp[-2].minor.yy132 = yymsp[-1].minor.yy132;}
176821        break;
176822      case 177: /* idlist ::= idlist COMMA nm */
176823{yymsp[-2].minor.yy132 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy132,&yymsp[0].minor.yy0);}
176824        break;
176825      case 178: /* idlist ::= nm */
176826{yymsp[0].minor.yy132 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
176827        break;
176828      case 179: /* expr ::= LP expr RP */
176829{yymsp[-2].minor.yy454 = yymsp[-1].minor.yy454;}
176830        break;
176831      case 180: /* expr ::= ID|INDEXED|JOIN_KW */
176832{yymsp[0].minor.yy454=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
176833        break;
176834      case 181: /* expr ::= nm DOT nm */
176835{
176836  Expr *temp1 = tokenExpr(pParse,TK_ID,yymsp[-2].minor.yy0);
176837  Expr *temp2 = tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0);
176838  yylhsminor.yy454 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
176839}
176840  yymsp[-2].minor.yy454 = yylhsminor.yy454;
176841        break;
176842      case 182: /* expr ::= nm DOT nm DOT nm */
176843{
176844  Expr *temp1 = tokenExpr(pParse,TK_ID,yymsp[-4].minor.yy0);
176845  Expr *temp2 = tokenExpr(pParse,TK_ID,yymsp[-2].minor.yy0);
176846  Expr *temp3 = tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0);
176847  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
176848  if( IN_RENAME_OBJECT ){
176849    sqlite3RenameTokenRemap(pParse, 0, temp1);
176850  }
176851  yylhsminor.yy454 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
176852}
176853  yymsp[-4].minor.yy454 = yylhsminor.yy454;
176854        break;
176855      case 183: /* term ::= NULL|FLOAT|BLOB */
176856      case 184: /* term ::= STRING */ yytestcase(yyruleno==184);
176857{yymsp[0].minor.yy454=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
176858        break;
176859      case 185: /* term ::= INTEGER */
176860{
176861  yylhsminor.yy454 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
176862  if( yylhsminor.yy454 ) yylhsminor.yy454->w.iOfst = (int)(yymsp[0].minor.yy0.z - pParse->zTail);
176863}
176864  yymsp[0].minor.yy454 = yylhsminor.yy454;
176865        break;
176866      case 186: /* expr ::= VARIABLE */
176867{
176868  if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
176869    u32 n = yymsp[0].minor.yy0.n;
176870    yymsp[0].minor.yy454 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
176871    sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy454, n);
176872  }else{
176873    /* When doing a nested parse, one can include terms in an expression
176874    ** that look like this:   #1 #2 ...  These terms refer to registers
176875    ** in the virtual machine.  #N is the N-th register. */
176876    Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
176877    assert( t.n>=2 );
176878    if( pParse->nested==0 ){
176879      sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
176880      yymsp[0].minor.yy454 = 0;
176881    }else{
176882      yymsp[0].minor.yy454 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
176883      if( yymsp[0].minor.yy454 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy454->iTable);
176884    }
176885  }
176886}
176887        break;
176888      case 187: /* expr ::= expr COLLATE ID|STRING */
176889{
176890  yymsp[-2].minor.yy454 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy454, &yymsp[0].minor.yy0, 1);
176891}
176892        break;
176893      case 188: /* expr ::= CAST LP expr AS typetoken RP */
176894{
176895  yymsp[-5].minor.yy454 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
176896  sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy454, yymsp[-3].minor.yy454, 0);
176897}
176898        break;
176899      case 189: /* expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP */
176900{
176901  yylhsminor.yy454 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy144);
176902}
176903  yymsp[-4].minor.yy454 = yylhsminor.yy454;
176904        break;
176905      case 190: /* expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP */
176906{
176907  yylhsminor.yy454 = sqlite3ExprFunction(pParse, yymsp[-4].minor.yy14, &yymsp[-7].minor.yy0, yymsp[-5].minor.yy144);
176908  sqlite3ExprAddFunctionOrderBy(pParse, yylhsminor.yy454, yymsp[-1].minor.yy14);
176909}
176910  yymsp[-7].minor.yy454 = yylhsminor.yy454;
176911        break;
176912      case 191: /* expr ::= ID|INDEXED|JOIN_KW LP STAR RP */
176913{
176914  yylhsminor.yy454 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
176915}
176916  yymsp[-3].minor.yy454 = yylhsminor.yy454;
176917        break;
176918      case 192: /* expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */
176919{
176920  yylhsminor.yy454 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy14, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy144);
176921  sqlite3WindowAttach(pParse, yylhsminor.yy454, yymsp[0].minor.yy211);
176922}
176923  yymsp[-5].minor.yy454 = yylhsminor.yy454;
176924        break;
176925      case 193: /* expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP filter_over */
176926{
176927  yylhsminor.yy454 = sqlite3ExprFunction(pParse, yymsp[-5].minor.yy14, &yymsp[-8].minor.yy0, yymsp[-6].minor.yy144);
176928  sqlite3WindowAttach(pParse, yylhsminor.yy454, yymsp[0].minor.yy211);
176929  sqlite3ExprAddFunctionOrderBy(pParse, yylhsminor.yy454, yymsp[-2].minor.yy14);
176930}
176931  yymsp[-8].minor.yy454 = yylhsminor.yy454;
176932        break;
176933      case 194: /* expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */
176934{
176935  yylhsminor.yy454 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
176936  sqlite3WindowAttach(pParse, yylhsminor.yy454, yymsp[0].minor.yy211);
176937}
176938  yymsp[-4].minor.yy454 = yylhsminor.yy454;
176939        break;
176940      case 195: /* term ::= CTIME_KW */
176941{
176942  yylhsminor.yy454 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
176943}
176944  yymsp[0].minor.yy454 = yylhsminor.yy454;
176945        break;
176946      case 196: /* expr ::= LP nexprlist COMMA expr RP */
176947{
176948  ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy14, yymsp[-1].minor.yy454);
176949  yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
176950  if( yymsp[-4].minor.yy454 ){
176951    yymsp[-4].minor.yy454->x.pList = pList;
176952    if( ALWAYS(pList->nExpr) ){
176953      yymsp[-4].minor.yy454->flags |= pList->a[0].pExpr->flags & EP_Propagate;
176954    }
176955  }else{
176956    sqlite3ExprListDelete(pParse->db, pList);
176957  }
176958}
176959        break;
176960      case 197: /* expr ::= expr AND expr */
176961{yymsp[-2].minor.yy454=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy454,yymsp[0].minor.yy454);}
176962        break;
176963      case 198: /* expr ::= expr OR expr */
176964      case 199: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==199);
176965      case 200: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==200);
176966      case 201: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==201);
176967      case 202: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==202);
176968      case 203: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==203);
176969      case 204: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==204);
176970{yymsp[-2].minor.yy454=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy454,yymsp[0].minor.yy454);}
176971        break;
176972      case 205: /* likeop ::= NOT LIKE_KW|MATCH */
176973{yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
176974        break;
176975      case 206: /* expr ::= expr likeop expr */
176976{
176977  ExprList *pList;
176978  int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
176979  yymsp[-1].minor.yy0.n &= 0x7fffffff;
176980  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy454);
176981  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy454);
176982  yymsp[-2].minor.yy454 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
176983  if( bNot ) yymsp[-2].minor.yy454 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy454, 0);
176984  if( yymsp[-2].minor.yy454 ) yymsp[-2].minor.yy454->flags |= EP_InfixFunc;
176985}
176986        break;
176987      case 207: /* expr ::= expr likeop expr ESCAPE expr */
176988{
176989  ExprList *pList;
176990  int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
176991  yymsp[-3].minor.yy0.n &= 0x7fffffff;
176992  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy454);
176993  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy454);
176994  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy454);
176995  yymsp[-4].minor.yy454 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
176996  if( bNot ) yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy454, 0);
176997  if( yymsp[-4].minor.yy454 ) yymsp[-4].minor.yy454->flags |= EP_InfixFunc;
176998}
176999        break;
177000      case 208: /* expr ::= expr ISNULL|NOTNULL */
177001{yymsp[-1].minor.yy454 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy454,0);}
177002        break;
177003      case 209: /* expr ::= expr NOT NULL */
177004{yymsp[-2].minor.yy454 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy454,0);}
177005        break;
177006      case 210: /* expr ::= expr IS expr */
177007{
177008  yymsp[-2].minor.yy454 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy454,yymsp[0].minor.yy454);
177009  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy454, yymsp[-2].minor.yy454, TK_ISNULL);
177010}
177011        break;
177012      case 211: /* expr ::= expr IS NOT expr */
177013{
177014  yymsp[-3].minor.yy454 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy454,yymsp[0].minor.yy454);
177015  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy454, yymsp[-3].minor.yy454, TK_NOTNULL);
177016}
177017        break;
177018      case 212: /* expr ::= expr IS NOT DISTINCT FROM expr */
177019{
177020  yymsp[-5].minor.yy454 = sqlite3PExpr(pParse,TK_IS,yymsp[-5].minor.yy454,yymsp[0].minor.yy454);
177021  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy454, yymsp[-5].minor.yy454, TK_ISNULL);
177022}
177023        break;
177024      case 213: /* expr ::= expr IS DISTINCT FROM expr */
177025{
177026  yymsp[-4].minor.yy454 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-4].minor.yy454,yymsp[0].minor.yy454);
177027  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy454, yymsp[-4].minor.yy454, TK_NOTNULL);
177028}
177029        break;
177030      case 214: /* expr ::= NOT expr */
177031      case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
177032{yymsp[-1].minor.yy454 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy454, 0);/*A-overwrites-B*/}
177033        break;
177034      case 216: /* expr ::= PLUS|MINUS expr */
177035{
177036  Expr *p = yymsp[0].minor.yy454;
177037  u8 op = yymsp[-1].major + (TK_UPLUS-TK_PLUS);
177038  assert( TK_UPLUS>TK_PLUS );
177039  assert( TK_UMINUS == TK_MINUS + (TK_UPLUS - TK_PLUS) );
177040  if( p && p->op==TK_UPLUS ){
177041    p->op = op;
177042    yymsp[-1].minor.yy454 = p;
177043  }else{
177044    yymsp[-1].minor.yy454 = sqlite3PExpr(pParse, op, p, 0);
177045    /*A-overwrites-B*/
177046  }
177047}
177048        break;
177049      case 217: /* expr ::= expr PTR expr */
177050{
177051  ExprList *pList = sqlite3ExprListAppend(pParse, 0, yymsp[-2].minor.yy454);
177052  pList = sqlite3ExprListAppend(pParse, pList, yymsp[0].minor.yy454);
177053  yylhsminor.yy454 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
177054}
177055  yymsp[-2].minor.yy454 = yylhsminor.yy454;
177056        break;
177057      case 218: /* between_op ::= BETWEEN */
177058      case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
177059{yymsp[0].minor.yy144 = 0;}
177060        break;
177061      case 220: /* expr ::= expr between_op expr AND expr */
177062{
177063  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy454);
177064  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy454);
177065  yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy454, 0);
177066  if( yymsp[-4].minor.yy454 ){
177067    yymsp[-4].minor.yy454->x.pList = pList;
177068  }else{
177069    sqlite3ExprListDelete(pParse->db, pList);
177070  }
177071  if( yymsp[-3].minor.yy144 ) yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy454, 0);
177072}
177073        break;
177074      case 223: /* expr ::= expr in_op LP exprlist RP */
177075{
177076    if( yymsp[-1].minor.yy14==0 ){
177077      /* Expressions of the form
177078      **
177079      **      expr1 IN ()
177080      **      expr1 NOT IN ()
177081      **
177082      ** simplify to constants 0 (false) and 1 (true), respectively,
177083      ** regardless of the value of expr1.
177084      */
177085      sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy454);
177086      yymsp[-4].minor.yy454 = sqlite3Expr(pParse->db, TK_STRING, yymsp[-3].minor.yy144 ? "true" : "false");
177087      if( yymsp[-4].minor.yy454 ) sqlite3ExprIdToTrueFalse(yymsp[-4].minor.yy454);
177088    }else{
177089      Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
177090      if( yymsp[-1].minor.yy14->nExpr==1 && sqlite3ExprIsConstant(pParse,pRHS) && yymsp[-4].minor.yy454->op!=TK_VECTOR ){
177091        yymsp[-1].minor.yy14->a[0].pExpr = 0;
177092        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
177093        pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0);
177094        yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_EQ, yymsp[-4].minor.yy454, pRHS);
177095      }else if( yymsp[-1].minor.yy14->nExpr==1 && pRHS->op==TK_SELECT ){
177096        yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy454, 0);
177097        sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy454, pRHS->x.pSelect);
177098        pRHS->x.pSelect = 0;
177099        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
177100      }else{
177101        yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy454, 0);
177102        if( yymsp[-4].minor.yy454==0 ){
177103          sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
177104        }else if( yymsp[-4].minor.yy454->pLeft->op==TK_VECTOR ){
177105          int nExpr = yymsp[-4].minor.yy454->pLeft->x.pList->nExpr;
177106          Select *pSelectRHS = sqlite3ExprListToValues(pParse, nExpr, yymsp[-1].minor.yy14);
177107          if( pSelectRHS ){
177108            parserDoubleLinkSelect(pParse, pSelectRHS);
177109            sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy454, pSelectRHS);
177110          }
177111        }else{
177112          yymsp[-4].minor.yy454->x.pList = yymsp[-1].minor.yy14;
177113          sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy454);
177114        }
177115      }
177116      if( yymsp[-3].minor.yy144 ) yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy454, 0);
177117    }
177118  }
177119        break;
177120      case 224: /* expr ::= LP select RP */
177121{
177122    yymsp[-2].minor.yy454 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
177123    sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy454, yymsp[-1].minor.yy555);
177124  }
177125        break;
177126      case 225: /* expr ::= expr in_op LP select RP */
177127{
177128    yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy454, 0);
177129    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy454, yymsp[-1].minor.yy555);
177130    if( yymsp[-3].minor.yy144 ) yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy454, 0);
177131  }
177132        break;
177133      case 226: /* expr ::= expr in_op nm dbnm paren_exprlist */
177134{
177135    SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
177136    Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
177137    if( yymsp[0].minor.yy14 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy14);
177138    yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy454, 0);
177139    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy454, pSelect);
177140    if( yymsp[-3].minor.yy144 ) yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy454, 0);
177141  }
177142        break;
177143      case 227: /* expr ::= EXISTS LP select RP */
177144{
177145    Expr *p;
177146    p = yymsp[-3].minor.yy454 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
177147    sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy555);
177148  }
177149        break;
177150      case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
177151{
177152  yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy454, 0);
177153  if( yymsp[-4].minor.yy454 ){
177154    yymsp[-4].minor.yy454->x.pList = yymsp[-1].minor.yy454 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy454) : yymsp[-2].minor.yy14;
177155    sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy454);
177156  }else{
177157    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
177158    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy454);
177159  }
177160}
177161        break;
177162      case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
177163{
177164  yymsp[-4].minor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy454);
177165  yymsp[-4].minor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[0].minor.yy454);
177166}
177167        break;
177168      case 230: /* case_exprlist ::= WHEN expr THEN expr */
177169{
177170  yymsp[-3].minor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy454);
177171  yymsp[-3].minor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, yymsp[0].minor.yy454);
177172}
177173        break;
177174      case 235: /* nexprlist ::= nexprlist COMMA expr */
177175{yymsp[-2].minor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy454);}
177176        break;
177177      case 236: /* nexprlist ::= expr */
177178{yymsp[0].minor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy454); /*A-overwrites-Y*/}
177179        break;
177180      case 238: /* paren_exprlist ::= LP exprlist RP */
177181      case 243: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==243);
177182{yymsp[-2].minor.yy14 = yymsp[-1].minor.yy14;}
177183        break;
177184      case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
177185{
177186  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
177187                     sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy144,
177188                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy454, SQLITE_SO_ASC, yymsp[-8].minor.yy144, SQLITE_IDXTYPE_APPDEF);
177189  if( IN_RENAME_OBJECT && pParse->pNewIndex ){
177190    sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0);
177191  }
177192}
177193        break;
177194      case 240: /* uniqueflag ::= UNIQUE */
177195      case 282: /* raisetype ::= ABORT */ yytestcase(yyruleno==282);
177196{yymsp[0].minor.yy144 = OE_Abort;}
177197        break;
177198      case 241: /* uniqueflag ::= */
177199{yymsp[1].minor.yy144 = OE_None;}
177200        break;
177201      case 244: /* eidlist ::= eidlist COMMA nm collate sortorder */
177202{
177203  yymsp[-4].minor.yy14 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy14, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy144, yymsp[0].minor.yy144);
177204}
177205        break;
177206      case 245: /* eidlist ::= nm collate sortorder */
177207{
177208  yymsp[-2].minor.yy14 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy144, yymsp[0].minor.yy144); /*A-overwrites-Y*/
177209}
177210        break;
177211      case 248: /* cmd ::= DROP INDEX ifexists fullname */
177212{sqlite3DropIndex(pParse, yymsp[0].minor.yy203, yymsp[-1].minor.yy144);}
177213        break;
177214      case 249: /* cmd ::= VACUUM vinto */
177215{sqlite3Vacuum(pParse,0,yymsp[0].minor.yy454);}
177216        break;
177217      case 250: /* cmd ::= VACUUM nm vinto */
177218{sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy454);}
177219        break;
177220      case 253: /* cmd ::= PRAGMA nm dbnm */
177221{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
177222        break;
177223      case 254: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
177224{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
177225        break;
177226      case 255: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
177227{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
177228        break;
177229      case 256: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
177230{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
177231        break;
177232      case 257: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
177233{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
177234        break;
177235      case 260: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
177236{
177237  Token all;
177238  all.z = yymsp[-3].minor.yy0.z;
177239  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
177240  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy427, &all);
177241}
177242        break;
177243      case 261: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
177244{
177245  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy144, yymsp[-4].minor.yy286.a, yymsp[-4].minor.yy286.b, yymsp[-2].minor.yy203, yymsp[0].minor.yy454, yymsp[-10].minor.yy144, yymsp[-8].minor.yy144);
177246  yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
177247}
177248        break;
177249      case 262: /* trigger_time ::= BEFORE|AFTER */
177250{ yymsp[0].minor.yy144 = yymsp[0].major; /*A-overwrites-X*/ }
177251        break;
177252      case 263: /* trigger_time ::= INSTEAD OF */
177253{ yymsp[-1].minor.yy144 = TK_INSTEAD;}
177254        break;
177255      case 264: /* trigger_time ::= */
177256{ yymsp[1].minor.yy144 = TK_BEFORE; }
177257        break;
177258      case 265: /* trigger_event ::= DELETE|INSERT */
177259      case 266: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==266);
177260{yymsp[0].minor.yy286.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy286.b = 0;}
177261        break;
177262      case 267: /* trigger_event ::= UPDATE OF idlist */
177263{yymsp[-2].minor.yy286.a = TK_UPDATE; yymsp[-2].minor.yy286.b = yymsp[0].minor.yy132;}
177264        break;
177265      case 268: /* when_clause ::= */
177266      case 287: /* key_opt ::= */ yytestcase(yyruleno==287);
177267{ yymsp[1].minor.yy454 = 0; }
177268        break;
177269      case 269: /* when_clause ::= WHEN expr */
177270      case 288: /* key_opt ::= KEY expr */ yytestcase(yyruleno==288);
177271{ yymsp[-1].minor.yy454 = yymsp[0].minor.yy454; }
177272        break;
177273      case 270: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
177274{
177275  assert( yymsp[-2].minor.yy427!=0 );
177276  yymsp[-2].minor.yy427->pLast->pNext = yymsp[-1].minor.yy427;
177277  yymsp[-2].minor.yy427->pLast = yymsp[-1].minor.yy427;
177278}
177279        break;
177280      case 271: /* trigger_cmd_list ::= trigger_cmd SEMI */
177281{
177282  assert( yymsp[-1].minor.yy427!=0 );
177283  yymsp[-1].minor.yy427->pLast = yymsp[-1].minor.yy427;
177284}
177285        break;
177286      case 272: /* trnm ::= nm DOT nm */
177287{
177288  yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
177289  sqlite3ErrorMsg(pParse,
177290        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
177291        "statements within triggers");
177292}
177293        break;
177294      case 273: /* tridxby ::= INDEXED BY nm */
177295{
177296  sqlite3ErrorMsg(pParse,
177297        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
177298        "within triggers");
177299}
177300        break;
177301      case 274: /* tridxby ::= NOT INDEXED */
177302{
177303  sqlite3ErrorMsg(pParse,
177304        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
177305        "within triggers");
177306}
177307        break;
177308      case 275: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
177309{yylhsminor.yy427 = sqlite3TriggerUpdateStep(pParse, &yymsp[-6].minor.yy0, yymsp[-2].minor.yy203, yymsp[-3].minor.yy14, yymsp[-1].minor.yy454, yymsp[-7].minor.yy144, yymsp[-8].minor.yy0.z, yymsp[0].minor.yy168);}
177310  yymsp[-8].minor.yy427 = yylhsminor.yy427;
177311        break;
177312      case 276: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
177313{
177314   yylhsminor.yy427 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy132,yymsp[-2].minor.yy555,yymsp[-6].minor.yy144,yymsp[-1].minor.yy122,yymsp[-7].minor.yy168,yymsp[0].minor.yy168);/*yylhsminor.yy427-overwrites-yymsp[-6].minor.yy144*/
177315}
177316  yymsp[-7].minor.yy427 = yylhsminor.yy427;
177317        break;
177318      case 277: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
177319{yylhsminor.yy427 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy454, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy168);}
177320  yymsp[-5].minor.yy427 = yylhsminor.yy427;
177321        break;
177322      case 278: /* trigger_cmd ::= scanpt select scanpt */
177323{yylhsminor.yy427 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy555, yymsp[-2].minor.yy168, yymsp[0].minor.yy168); /*yylhsminor.yy427-overwrites-yymsp[-1].minor.yy555*/}
177324  yymsp[-2].minor.yy427 = yylhsminor.yy427;
177325        break;
177326      case 279: /* expr ::= RAISE LP IGNORE RP */
177327{
177328  yymsp[-3].minor.yy454 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
177329  if( yymsp[-3].minor.yy454 ){
177330    yymsp[-3].minor.yy454->affExpr = OE_Ignore;
177331  }
177332}
177333        break;
177334      case 280: /* expr ::= RAISE LP raisetype COMMA nm RP */
177335{
177336  yymsp[-5].minor.yy454 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
177337  if( yymsp[-5].minor.yy454 ) {
177338    yymsp[-5].minor.yy454->affExpr = (char)yymsp[-3].minor.yy144;
177339  }
177340}
177341        break;
177342      case 281: /* raisetype ::= ROLLBACK */
177343{yymsp[0].minor.yy144 = OE_Rollback;}
177344        break;
177345      case 283: /* raisetype ::= FAIL */
177346{yymsp[0].minor.yy144 = OE_Fail;}
177347        break;
177348      case 284: /* cmd ::= DROP TRIGGER ifexists fullname */
177349{
177350  sqlite3DropTrigger(pParse,yymsp[0].minor.yy203,yymsp[-1].minor.yy144);
177351}
177352        break;
177353      case 285: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
177354{
177355  sqlite3Attach(pParse, yymsp[-3].minor.yy454, yymsp[-1].minor.yy454, yymsp[0].minor.yy454);
177356}
177357        break;
177358      case 286: /* cmd ::= DETACH database_kw_opt expr */
177359{
177360  sqlite3Detach(pParse, yymsp[0].minor.yy454);
177361}
177362        break;
177363      case 289: /* cmd ::= REINDEX */
177364{sqlite3Reindex(pParse, 0, 0);}
177365        break;
177366      case 290: /* cmd ::= REINDEX nm dbnm */
177367{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
177368        break;
177369      case 291: /* cmd ::= ANALYZE */
177370{sqlite3Analyze(pParse, 0, 0);}
177371        break;
177372      case 292: /* cmd ::= ANALYZE nm dbnm */
177373{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
177374        break;
177375      case 293: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
177376{
177377  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy203,&yymsp[0].minor.yy0);
177378}
177379        break;
177380      case 294: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
177381{
177382  yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
177383  sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
177384}
177385        break;
177386      case 295: /* cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
177387{
177388  sqlite3AlterDropColumn(pParse, yymsp[-3].minor.yy203, &yymsp[0].minor.yy0);
177389}
177390        break;
177391      case 296: /* add_column_fullname ::= fullname */
177392{
177393  disableLookaside(pParse);
177394  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy203);
177395}
177396        break;
177397      case 297: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
177398{
177399  sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy203, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
177400}
177401        break;
177402      case 298: /* cmd ::= create_vtab */
177403{sqlite3VtabFinishParse(pParse,0);}
177404        break;
177405      case 299: /* cmd ::= create_vtab LP vtabarglist RP */
177406{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
177407        break;
177408      case 300: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
177409{
177410    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy144);
177411}
177412        break;
177413      case 301: /* vtabarg ::= */
177414{sqlite3VtabArgInit(pParse);}
177415        break;
177416      case 302: /* vtabargtoken ::= ANY */
177417      case 303: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==303);
177418      case 304: /* lp ::= LP */ yytestcase(yyruleno==304);
177419{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
177420        break;
177421      case 305: /* with ::= WITH wqlist */
177422      case 306: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==306);
177423{ sqlite3WithPush(pParse, yymsp[0].minor.yy59, 1); }
177424        break;
177425      case 307: /* wqas ::= AS */
177426{yymsp[0].minor.yy462 = M10d_Any;}
177427        break;
177428      case 308: /* wqas ::= AS MATERIALIZED */
177429{yymsp[-1].minor.yy462 = M10d_Yes;}
177430        break;
177431      case 309: /* wqas ::= AS NOT MATERIALIZED */
177432{yymsp[-2].minor.yy462 = M10d_No;}
177433        break;
177434      case 310: /* wqitem ::= withnm eidlist_opt wqas LP select RP */
177435{
177436  yymsp[-5].minor.yy67 = sqlite3CteNew(pParse, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy555, yymsp[-3].minor.yy462); /*A-overwrites-X*/
177437}
177438        break;
177439      case 311: /* withnm ::= nm */
177440{pParse->bHasWith = 1;}
177441        break;
177442      case 312: /* wqlist ::= wqitem */
177443{
177444  yymsp[0].minor.yy59 = sqlite3WithAdd(pParse, 0, yymsp[0].minor.yy67); /*A-overwrites-X*/
177445}
177446        break;
177447      case 313: /* wqlist ::= wqlist COMMA wqitem */
177448{
177449  yymsp[-2].minor.yy59 = sqlite3WithAdd(pParse, yymsp[-2].minor.yy59, yymsp[0].minor.yy67);
177450}
177451        break;
177452      case 314: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
177453{
177454  assert( yymsp[0].minor.yy211!=0 );
177455  sqlite3WindowChain(pParse, yymsp[0].minor.yy211, yymsp[-2].minor.yy211);
177456  yymsp[0].minor.yy211->pNextWin = yymsp[-2].minor.yy211;
177457  yylhsminor.yy211 = yymsp[0].minor.yy211;
177458}
177459  yymsp[-2].minor.yy211 = yylhsminor.yy211;
177460        break;
177461      case 315: /* windowdefn ::= nm AS LP window RP */
177462{
177463  if( ALWAYS(yymsp[-1].minor.yy211) ){
177464    yymsp[-1].minor.yy211->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n);
177465  }
177466  yylhsminor.yy211 = yymsp[-1].minor.yy211;
177467}
177468  yymsp[-4].minor.yy211 = yylhsminor.yy211;
177469        break;
177470      case 316: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */
177471{
177472  yymsp[-4].minor.yy211 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy211, yymsp[-2].minor.yy14, yymsp[-1].minor.yy14, 0);
177473}
177474        break;
177475      case 317: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
177476{
177477  yylhsminor.yy211 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy211, yymsp[-2].minor.yy14, yymsp[-1].minor.yy14, &yymsp[-5].minor.yy0);
177478}
177479  yymsp[-5].minor.yy211 = yylhsminor.yy211;
177480        break;
177481      case 318: /* window ::= ORDER BY sortlist frame_opt */
177482{
177483  yymsp[-3].minor.yy211 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy211, 0, yymsp[-1].minor.yy14, 0);
177484}
177485        break;
177486      case 319: /* window ::= nm ORDER BY sortlist frame_opt */
177487{
177488  yylhsminor.yy211 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy211, 0, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
177489}
177490  yymsp[-4].minor.yy211 = yylhsminor.yy211;
177491        break;
177492      case 320: /* window ::= nm frame_opt */
177493{
177494  yylhsminor.yy211 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy211, 0, 0, &yymsp[-1].minor.yy0);
177495}
177496  yymsp[-1].minor.yy211 = yylhsminor.yy211;
177497        break;
177498      case 321: /* frame_opt ::= */
177499{
177500  yymsp[1].minor.yy211 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
177501}
177502        break;
177503      case 322: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
177504{
177505  yylhsminor.yy211 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy144, yymsp[-1].minor.yy509.eType, yymsp[-1].minor.yy509.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy462);
177506}
177507  yymsp[-2].minor.yy211 = yylhsminor.yy211;
177508        break;
177509      case 323: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
177510{
177511  yylhsminor.yy211 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy144, yymsp[-3].minor.yy509.eType, yymsp[-3].minor.yy509.pExpr, yymsp[-1].minor.yy509.eType, yymsp[-1].minor.yy509.pExpr, yymsp[0].minor.yy462);
177512}
177513  yymsp[-5].minor.yy211 = yylhsminor.yy211;
177514        break;
177515      case 325: /* frame_bound_s ::= frame_bound */
177516      case 327: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==327);
177517{yylhsminor.yy509 = yymsp[0].minor.yy509;}
177518  yymsp[0].minor.yy509 = yylhsminor.yy509;
177519        break;
177520      case 326: /* frame_bound_s ::= UNBOUNDED PRECEDING */
177521      case 328: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==328);
177522      case 330: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==330);
177523{yylhsminor.yy509.eType = yymsp[-1].major; yylhsminor.yy509.pExpr = 0;}
177524  yymsp[-1].minor.yy509 = yylhsminor.yy509;
177525        break;
177526      case 329: /* frame_bound ::= expr PRECEDING|FOLLOWING */
177527{yylhsminor.yy509.eType = yymsp[0].major; yylhsminor.yy509.pExpr = yymsp[-1].minor.yy454;}
177528  yymsp[-1].minor.yy509 = yylhsminor.yy509;
177529        break;
177530      case 331: /* frame_exclude_opt ::= */
177531{yymsp[1].minor.yy462 = 0;}
177532        break;
177533      case 332: /* frame_exclude_opt ::= EXCLUDE frame_exclude */
177534{yymsp[-1].minor.yy462 = yymsp[0].minor.yy462;}
177535        break;
177536      case 333: /* frame_exclude ::= NO OTHERS */
177537      case 334: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==334);
177538{yymsp[-1].minor.yy462 = yymsp[-1].major; /*A-overwrites-X*/}
177539        break;
177540      case 335: /* frame_exclude ::= GROUP|TIES */
177541{yymsp[0].minor.yy462 = yymsp[0].major; /*A-overwrites-X*/}
177542        break;
177543      case 336: /* window_clause ::= WINDOW windowdefn_list */
177544{ yymsp[-1].minor.yy211 = yymsp[0].minor.yy211; }
177545        break;
177546      case 337: /* filter_over ::= filter_clause over_clause */
177547{
177548  if( yymsp[0].minor.yy211 ){
177549    yymsp[0].minor.yy211->pFilter = yymsp[-1].minor.yy454;
177550  }else{
177551    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy454);
177552  }
177553  yylhsminor.yy211 = yymsp[0].minor.yy211;
177554}
177555  yymsp[-1].minor.yy211 = yylhsminor.yy211;
177556        break;
177557      case 338: /* filter_over ::= over_clause */
177558{
177559  yylhsminor.yy211 = yymsp[0].minor.yy211;
177560}
177561  yymsp[0].minor.yy211 = yylhsminor.yy211;
177562        break;
177563      case 339: /* filter_over ::= filter_clause */
177564{
177565  yylhsminor.yy211 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
177566  if( yylhsminor.yy211 ){
177567    yylhsminor.yy211->eFrmType = TK_FILTER;
177568    yylhsminor.yy211->pFilter = yymsp[0].minor.yy454;
177569  }else{
177570    sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy454);
177571  }
177572}
177573  yymsp[0].minor.yy211 = yylhsminor.yy211;
177574        break;
177575      case 340: /* over_clause ::= OVER LP window RP */
177576{
177577  yymsp[-3].minor.yy211 = yymsp[-1].minor.yy211;
177578  assert( yymsp[-3].minor.yy211!=0 );
177579}
177580        break;
177581      case 341: /* over_clause ::= OVER nm */
177582{
177583  yymsp[-1].minor.yy211 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
177584  if( yymsp[-1].minor.yy211 ){
177585    yymsp[-1].minor.yy211->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);
177586  }
177587}
177588        break;
177589      case 342: /* filter_clause ::= FILTER LP WHERE expr RP */
177590{ yymsp[-4].minor.yy454 = yymsp[-1].minor.yy454; }
177591        break;
177592      case 343: /* term ::= QNUMBER */
177593{
177594  yylhsminor.yy454=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0);
177595  sqlite3DequoteNumber(pParse, yylhsminor.yy454);
177596}
177597  yymsp[0].minor.yy454 = yylhsminor.yy454;
177598        break;
177599      default:
177600      /* (344) input ::= cmdlist */ yytestcase(yyruleno==344);
177601      /* (345) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==345);
177602      /* (346) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=346);
177603      /* (347) ecmd ::= SEMI */ yytestcase(yyruleno==347);
177604      /* (348) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==348);
177605      /* (349) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=349);
177606      /* (350) trans_opt ::= */ yytestcase(yyruleno==350);
177607      /* (351) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==351);
177608      /* (352) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==352);
177609      /* (353) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==353);
177610      /* (354) savepoint_opt ::= */ yytestcase(yyruleno==354);
177611      /* (355) cmd ::= create_table create_table_args */ yytestcase(yyruleno==355);
177612      /* (356) table_option_set ::= table_option (OPTIMIZED OUT) */ assert(yyruleno!=356);
177613      /* (357) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==357);
177614      /* (358) columnlist ::= columnname carglist */ yytestcase(yyruleno==358);
177615      /* (359) nm ::= ID|INDEXED|JOIN_KW */ yytestcase(yyruleno==359);
177616      /* (360) nm ::= STRING */ yytestcase(yyruleno==360);
177617      /* (361) typetoken ::= typename */ yytestcase(yyruleno==361);
177618      /* (362) typename ::= ID|STRING */ yytestcase(yyruleno==362);
177619      /* (363) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=363);
177620      /* (364) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=364);
177621      /* (365) carglist ::= carglist ccons */ yytestcase(yyruleno==365);
177622      /* (366) carglist ::= */ yytestcase(yyruleno==366);
177623      /* (367) ccons ::= NULL onconf */ yytestcase(yyruleno==367);
177624      /* (368) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==368);
177625      /* (369) ccons ::= AS generated */ yytestcase(yyruleno==369);
177626      /* (370) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==370);
177627      /* (371) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==371);
177628      /* (372) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=372);
177629      /* (373) tconscomma ::= */ yytestcase(yyruleno==373);
177630      /* (374) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=374);
177631      /* (375) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=375);
177632      /* (376) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=376);
177633      /* (377) oneselect ::= values */ yytestcase(yyruleno==377);
177634      /* (378) sclp ::= selcollist COMMA */ yytestcase(yyruleno==378);
177635      /* (379) as ::= ID|STRING */ yytestcase(yyruleno==379);
177636      /* (380) indexed_opt ::= indexed_by (OPTIMIZED OUT) */ assert(yyruleno!=380);
177637      /* (381) returning ::= */ yytestcase(yyruleno==381);
177638      /* (382) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=382);
177639      /* (383) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==383);
177640      /* (384) case_operand ::= expr */ yytestcase(yyruleno==384);
177641      /* (385) exprlist ::= nexprlist */ yytestcase(yyruleno==385);
177642      /* (386) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=386);
177643      /* (387) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=387);
177644      /* (388) nmnum ::= ON */ yytestcase(yyruleno==388);
177645      /* (389) nmnum ::= DELETE */ yytestcase(yyruleno==389);
177646      /* (390) nmnum ::= DEFAULT */ yytestcase(yyruleno==390);
177647      /* (391) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==391);
177648      /* (392) foreach_clause ::= */ yytestcase(yyruleno==392);
177649      /* (393) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==393);
177650      /* (394) trnm ::= nm */ yytestcase(yyruleno==394);
177651      /* (395) tridxby ::= */ yytestcase(yyruleno==395);
177652      /* (396) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==396);
177653      /* (397) database_kw_opt ::= */ yytestcase(yyruleno==397);
177654      /* (398) kwcolumn_opt ::= */ yytestcase(yyruleno==398);
177655      /* (399) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==399);
177656      /* (400) vtabarglist ::= vtabarg */ yytestcase(yyruleno==400);
177657      /* (401) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==401);
177658      /* (402) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==402);
177659      /* (403) anylist ::= */ yytestcase(yyruleno==403);
177660      /* (404) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==404);
177661      /* (405) anylist ::= anylist ANY */ yytestcase(yyruleno==405);
177662      /* (406) with ::= */ yytestcase(yyruleno==406);
177663      /* (407) windowdefn_list ::= windowdefn (OPTIMIZED OUT) */ assert(yyruleno!=407);
177664      /* (408) window ::= frame_opt (OPTIMIZED OUT) */ assert(yyruleno!=408);
177665        break;
177666/********** End reduce actions ************************************************/
177667  };
177668  assert( yyruleno<sizeof(yyRuleInfoLhs)/sizeof(yyRuleInfoLhs[0]) );
177669  yygoto = yyRuleInfoLhs[yyruleno];
177670  yysize = yyRuleInfoNRhs[yyruleno];
177671  yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
177672
177673  /* There are no SHIFTREDUCE actions on nonterminals because the table
177674  ** generator has simplified them to pure REDUCE actions. */
177675  assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
177676
177677  /* It is not possible for a REDUCE to be followed by an error */
177678  assert( yyact!=YY_ERROR_ACTION );
177679
177680  yymsp += yysize+1;
177681  yypParser->yytos = yymsp;
177682  yymsp->stateno = (YYACTIONTYPE)yyact;
177683  yymsp->major = (YYCODETYPE)yygoto;
177684  yyTraceShift(yypParser, yyact, "... then shift");
177685  return yyact;
177686}
177687
177688/*
177689** The following code executes when the parse fails
177690*/
177691#ifndef YYNOERRORRECOVERY
177692static void yy_parse_failed(
177693  yyParser *yypParser           /* The parser */
177694){
177695  sqlite3ParserARG_FETCH
177696  sqlite3ParserCTX_FETCH
177697#ifndef NDEBUG
177698  if( yyTraceFILE ){
177699    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
177700  }
177701#endif
177702  while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
177703  /* Here code is inserted which will be executed whenever the
177704  ** parser fails */
177705/************ Begin %parse_failure code ***************************************/
177706/************ End %parse_failure code *****************************************/
177707  sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
177708  sqlite3ParserCTX_STORE
177709}
177710#endif /* YYNOERRORRECOVERY */
177711
177712/*
177713** The following code executes when a syntax error first occurs.
177714*/
177715static void yy_syntax_error(
177716  yyParser *yypParser,           /* The parser */
177717  int yymajor,                   /* The major type of the error token */
177718  sqlite3ParserTOKENTYPE yyminor         /* The minor type of the error token */
177719){
177720  sqlite3ParserARG_FETCH
177721  sqlite3ParserCTX_FETCH
177722#define TOKEN yyminor
177723/************ Begin %syntax_error code ****************************************/
177724
177725  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
177726  if( TOKEN.z[0] ){
177727    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
177728  }else{
177729    sqlite3ErrorMsg(pParse, "incomplete input");
177730  }
177731/************ End %syntax_error code ******************************************/
177732  sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
177733  sqlite3ParserCTX_STORE
177734}
177735
177736/*
177737** The following is executed when the parser accepts
177738*/
177739static void yy_accept(
177740  yyParser *yypParser           /* The parser */
177741){
177742  sqlite3ParserARG_FETCH
177743  sqlite3ParserCTX_FETCH
177744#ifndef NDEBUG
177745  if( yyTraceFILE ){
177746    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
177747  }
177748#endif
177749#ifndef YYNOERRORRECOVERY
177750  yypParser->yyerrcnt = -1;
177751#endif
177752  assert( yypParser->yytos==yypParser->yystack );
177753  /* Here code is inserted which will be executed whenever the
177754  ** parser accepts */
177755/*********** Begin %parse_accept code *****************************************/
177756/*********** End %parse_accept code *******************************************/
177757  sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
177758  sqlite3ParserCTX_STORE
177759}
177760
177761/* The main parser program.
177762** The first argument is a pointer to a structure obtained from
177763** "sqlite3ParserAlloc" which describes the current state of the parser.
177764** The second argument is the major token number.  The third is
177765** the minor token.  The fourth optional argument is whatever the
177766** user wants (and specified in the grammar) and is available for
177767** use by the action routines.
177768**
177769** Inputs:
177770** <ul>
177771** <li> A pointer to the parser (an opaque structure.)
177772** <li> The major token number.
177773** <li> The minor token number.
177774** <li> An option argument of a grammar-specified type.
177775** </ul>
177776**
177777** Outputs:
177778** None.
177779*/
177780SQLITE_PRIVATE void sqlite3Parser(
177781  void *yyp,                   /* The parser */
177782  int yymajor,                 /* The major token code number */
177783  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
177784  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
177785){
177786  YYMINORTYPE yyminorunion;
177787  YYACTIONTYPE yyact;   /* The parser action. */
177788#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
177789  int yyendofinput;     /* True if we are at the end of input */
177790#endif
177791#ifdef YYERRORSYMBOL
177792  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
177793#endif
177794  yyParser *yypParser = (yyParser*)yyp;  /* The parser */
177795  sqlite3ParserCTX_FETCH
177796  sqlite3ParserARG_STORE
177797
177798  assert( yypParser->yytos!=0 );
177799#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
177800  yyendofinput = (yymajor==0);
177801#endif
177802
177803  yyact = yypParser->yytos->stateno;
177804#ifndef NDEBUG
177805  if( yyTraceFILE ){
177806    if( yyact < YY_MIN_REDUCE ){
177807      fprintf(yyTraceFILE,"%sInput '%s' in state %d\n",
177808              yyTracePrompt,yyTokenName[yymajor],yyact);
177809    }else{
177810      fprintf(yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
177811              yyTracePrompt,yyTokenName[yymajor],yyact-YY_MIN_REDUCE);
177812    }
177813  }
177814#endif
177815
177816  while(1){ /* Exit by "break" */
177817    assert( yypParser->yytos>=yypParser->yystack );
177818    assert( yyact==yypParser->yytos->stateno );
177819    yyact = yy_find_shift_action((YYCODETYPE)yymajor,yyact);
177820    if( yyact >= YY_MIN_REDUCE ){
177821      unsigned int yyruleno = yyact - YY_MIN_REDUCE; /* Reduce by this rule */
177822#ifndef NDEBUG
177823      assert( yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) );
177824      if( yyTraceFILE ){
177825        int yysize = yyRuleInfoNRhs[yyruleno];
177826        if( yysize ){
177827          fprintf(yyTraceFILE, "%sReduce %d [%s]%s, pop back to state %d.\n",
177828            yyTracePrompt,
177829            yyruleno, yyRuleName[yyruleno],
177830            yyruleno<YYNRULE_WITH_ACTION ? "" : " without external action",
177831            yypParser->yytos[yysize].stateno);
177832        }else{
177833          fprintf(yyTraceFILE, "%sReduce %d [%s]%s.\n",
177834            yyTracePrompt, yyruleno, yyRuleName[yyruleno],
177835            yyruleno<YYNRULE_WITH_ACTION ? "" : " without external action");
177836        }
177837      }
177838#endif /* NDEBUG */
177839
177840      /* Check that the stack is large enough to grow by a single entry
177841      ** if the RHS of the rule is empty.  This ensures that there is room
177842      ** enough on the stack to push the LHS value */
177843      if( yyRuleInfoNRhs[yyruleno]==0 ){
177844#ifdef YYTRACKMAXSTACKDEPTH
177845        if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
177846          yypParser->yyhwm++;
177847          assert( yypParser->yyhwm ==
177848                  (int)(yypParser->yytos - yypParser->yystack));
177849        }
177850#endif
177851        if( yypParser->yytos>=yypParser->yystackEnd ){
177852          if( yyGrowStack(yypParser) ){
177853            yyStackOverflow(yypParser);
177854            break;
177855          }
177856        }
177857      }
177858      yyact = yy_reduce(yypParser,yyruleno,yymajor,yyminor sqlite3ParserCTX_PARAM);
177859    }else if( yyact <= YY_MAX_SHIFTREDUCE ){
177860      yy_shift(yypParser,yyact,(YYCODETYPE)yymajor,yyminor);
177861#ifndef YYNOERRORRECOVERY
177862      yypParser->yyerrcnt--;
177863#endif
177864      break;
177865    }else if( yyact==YY_ACCEPT_ACTION ){
177866      yypParser->yytos--;
177867      yy_accept(yypParser);
177868      return;
177869    }else{
177870      assert( yyact == YY_ERROR_ACTION );
177871      yyminorunion.yy0 = yyminor;
177872#ifdef YYERRORSYMBOL
177873      int yymx;
177874#endif
177875#ifndef NDEBUG
177876      if( yyTraceFILE ){
177877        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
177878      }
177879#endif
177880#ifdef YYERRORSYMBOL
177881      /* A syntax error has occurred.
177882      ** The response to an error depends upon whether or not the
177883      ** grammar defines an error token "ERROR".
177884      **
177885      ** This is what we do if the grammar does define ERROR:
177886      **
177887      **  * Call the %syntax_error function.
177888      **
177889      **  * Begin popping the stack until we enter a state where
177890      **    it is legal to shift the error symbol, then shift
177891      **    the error symbol.
177892      **
177893      **  * Set the error count to three.
177894      **
177895      **  * Begin accepting and shifting new tokens.  No new error
177896      **    processing will occur until three tokens have been
177897      **    shifted successfully.
177898      **
177899      */
177900      if( yypParser->yyerrcnt<0 ){
177901        yy_syntax_error(yypParser,yymajor,yyminor);
177902      }
177903      yymx = yypParser->yytos->major;
177904      if( yymx==YYERRORSYMBOL || yyerrorhit ){
177905#ifndef NDEBUG
177906        if( yyTraceFILE ){
177907          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
177908             yyTracePrompt,yyTokenName[yymajor]);
177909        }
177910#endif
177911        yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
177912        yymajor = YYNOCODE;
177913      }else{
177914        while( yypParser->yytos > yypParser->yystack ){
177915          yyact = yy_find_reduce_action(yypParser->yytos->stateno,
177916                                        YYERRORSYMBOL);
177917          if( yyact<=YY_MAX_SHIFTREDUCE ) break;
177918          yy_pop_parser_stack(yypParser);
177919        }
177920        if( yypParser->yytos <= yypParser->yystack || yymajor==0 ){
177921          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
177922          yy_parse_failed(yypParser);
177923#ifndef YYNOERRORRECOVERY
177924          yypParser->yyerrcnt = -1;
177925#endif
177926          yymajor = YYNOCODE;
177927        }else if( yymx!=YYERRORSYMBOL ){
177928          yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
177929        }
177930      }
177931      yypParser->yyerrcnt = 3;
177932      yyerrorhit = 1;
177933      if( yymajor==YYNOCODE ) break;
177934      yyact = yypParser->yytos->stateno;
177935#elif defined(YYNOERRORRECOVERY)
177936      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
177937      ** do any kind of error recovery.  Instead, simply invoke the syntax
177938      ** error routine and continue going as if nothing had happened.
177939      **
177940      ** Applications can set this macro (for example inside %include) if
177941      ** they intend to abandon the parse upon the first syntax error seen.
177942      */
177943      yy_syntax_error(yypParser,yymajor, yyminor);
177944      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
177945      break;
177946#else  /* YYERRORSYMBOL is not defined */
177947      /* This is what we do if the grammar does not define ERROR:
177948      **
177949      **  * Report an error message, and throw away the input token.
177950      **
177951      **  * If the input token is $, then fail the parse.
177952      **
177953      ** As before, subsequent error messages are suppressed until
177954      ** three input tokens have been successfully shifted.
177955      */
177956      if( yypParser->yyerrcnt<=0 ){
177957        yy_syntax_error(yypParser,yymajor, yyminor);
177958      }
177959      yypParser->yyerrcnt = 3;
177960      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
177961      if( yyendofinput ){
177962        yy_parse_failed(yypParser);
177963#ifndef YYNOERRORRECOVERY
177964        yypParser->yyerrcnt = -1;
177965#endif
177966      }
177967      break;
177968#endif
177969    }
177970  }
177971#ifndef NDEBUG
177972  if( yyTraceFILE ){
177973    yyStackEntry *i;
177974    char cDiv = '[';
177975    fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
177976    for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
177977      fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
177978      cDiv = ' ';
177979    }
177980    fprintf(yyTraceFILE,"]\n");
177981  }
177982#endif
177983  return;
177984}
177985
177986/*
177987** Return the fallback token corresponding to canonical token iToken, or
177988** 0 if iToken has no fallback.
177989*/
177990SQLITE_PRIVATE int sqlite3ParserFallback(int iToken){
177991#ifdef YYFALLBACK
177992  assert( iToken<(int)(sizeof(yyFallback)/sizeof(yyFallback[0])) );
177993  return yyFallback[iToken];
177994#else
177995  (void)iToken;
177996  return 0;
177997#endif
177998}
177999
178000/************** End of parse.c ***********************************************/
178001/************** Begin file tokenize.c ****************************************/
178002/*
178003** 2001 September 15
178004**
178005** The author disclaims copyright to this source code.  In place of
178006** a legal notice, here is a blessing:
178007**
178008**    May you do good and not evil.
178009**    May you find forgiveness for yourself and forgive others.
178010**    May you share freely, never taking more than you give.
178011**
178012*************************************************************************
178013** An tokenizer for SQL
178014**
178015** This file contains C code that splits an SQL input string up into
178016** individual tokens and sends those tokens one-by-one over to the
178017** parser for analysis.
178018*/
178019/* #include "sqliteInt.h" */
178020/* #include <stdlib.h> */
178021
178022/* Character classes for tokenizing
178023**
178024** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
178025** using a lookup table, whereas a switch() directly on c uses a binary search.
178026** The lookup table is much faster.  To maximize speed, and to ensure that
178027** a lookup table is used, all of the classes need to be small integers and
178028** all of them need to be used within the switch.
178029*/
178030#define CC_X          0    /* The letter 'x', or start of BLOB literal */
178031#define CC_KYWD0      1    /* First letter of a keyword */
178032#define CC_KYWD       2    /* Alphabetics or '_'.  Usable in a keyword */
178033#define CC_DIGIT      3    /* Digits */
178034#define CC_DOLLAR     4    /* '$' */
178035#define CC_VARALPHA   5    /* '@', '#', ':'.  Alphabetic SQL variables */
178036#define CC_VARNUM     6    /* '?'.  Numeric SQL variables */
178037#define CC_SPACE      7    /* Space characters */
178038#define CC_QUOTE      8    /* '"', '\'', or '`'.  String literals, quoted ids */
178039#define CC_QUOTE2     9    /* '['.   [...] style quoted ids */
178040#define CC_PIPE      10    /* '|'.   Bitwise OR or concatenate */
178041#define CC_MINUS     11    /* '-'.  Minus or SQL-style comment */
178042#define CC_LT        12    /* '<'.  Part of < or <= or <> */
178043#define CC_GT        13    /* '>'.  Part of > or >= */
178044#define CC_EQ        14    /* '='.  Part of = or == */
178045#define CC_BANG      15    /* '!'.  Part of != */
178046#define CC_SLASH     16    /* '/'.  / or c-style comment */
178047#define CC_LP        17    /* '(' */
178048#define CC_RP        18    /* ')' */
178049#define CC_SEMI      19    /* ';' */
178050#define CC_PLUS      20    /* '+' */
178051#define CC_STAR      21    /* '*' */
178052#define CC_PERCENT   22    /* '%' */
178053#define CC_COMMA     23    /* ',' */
178054#define CC_AND       24    /* '&' */
178055#define CC_TILDA     25    /* '~' */
178056#define CC_DOT       26    /* '.' */
178057#define CC_ID        27    /* unicode characters usable in IDs */
178058#define CC_ILLEGAL   28    /* Illegal character */
178059#define CC_NUL       29    /* 0x00 */
178060#define CC_BOM       30    /* First byte of UTF8 BOM:  0xEF 0xBB 0xBF */
178061
178062static const unsigned char aiClass[] = {
178063#ifdef SQLITE_ASCII
178064/*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
178065/* 0x */   29, 28, 28, 28, 28, 28, 28, 28, 28,  7,  7, 28,  7,  7, 28, 28,
178066/* 1x */   28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
178067/* 2x */    7, 15,  8,  5,  4, 22, 24,  8, 17, 18, 21, 20, 23, 11, 26, 16,
178068/* 3x */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  5, 19, 12, 14, 13,  6,
178069/* 4x */    5,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
178070/* 5x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  2,  2,  9, 28, 28, 28,  2,
178071/* 6x */    8,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
178072/* 7x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  2,  2, 28, 10, 28, 25, 28,
178073/* 8x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
178074/* 9x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
178075/* Ax */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
178076/* Bx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
178077/* Cx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
178078/* Dx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
178079/* Ex */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 30,
178080/* Fx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27
178081#endif
178082#ifdef SQLITE_EBCDIC
178083/*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
178084/* 0x */   29, 28, 28, 28, 28,  7, 28, 28, 28, 28, 28, 28,  7,  7, 28, 28,
178085/* 1x */   28, 28, 28, 28, 28,  7, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
178086/* 2x */   28, 28, 28, 28, 28,  7, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
178087/* 3x */   28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
178088/* 4x */    7, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 26, 12, 17, 20, 10,
178089/* 5x */   24, 28, 28, 28, 28, 28, 28, 28, 28, 28, 15,  4, 21, 18, 19, 28,
178090/* 6x */   11, 16, 28, 28, 28, 28, 28, 28, 28, 28, 28, 23, 22,  2, 13,  6,
178091/* 7x */   28, 28, 28, 28, 28, 28, 28, 28, 28,  8,  5,  5,  5,  8, 14,  8,
178092/* 8x */   28,  1,  1,  1,  1,  1,  1,  1,  1,  1, 28, 28, 28, 28, 28, 28,
178093/* 9x */   28,  1,  1,  1,  1,  1,  1,  1,  1,  1, 28, 28, 28, 28, 28, 28,
178094/* Ax */   28, 25,  1,  1,  1,  1,  1,  0,  2,  2, 28, 28, 28, 28, 28, 28,
178095/* Bx */   28, 28, 28, 28, 28, 28, 28, 28, 28, 28,  9, 28, 28, 28, 28, 28,
178096/* Cx */   28,  1,  1,  1,  1,  1,  1,  1,  1,  1, 28, 28, 28, 28, 28, 28,
178097/* Dx */   28,  1,  1,  1,  1,  1,  1,  1,  1,  1, 28, 28, 28, 28, 28, 28,
178098/* Ex */   28, 28,  1,  1,  1,  1,  1,  0,  2,  2, 28, 28, 28, 28, 28, 28,
178099/* Fx */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3, 28, 28, 28, 28, 28, 28,
178100#endif
178101};
178102
178103/*
178104** The charMap() macro maps alphabetic characters (only) into their
178105** lower-case ASCII equivalent.  On ASCII machines, this is just
178106** an upper-to-lower case map.  On EBCDIC machines we also need
178107** to adjust the encoding.  The mapping is only valid for alphabetics
178108** which are the only characters for which this feature is used.
178109**
178110** Used by keywordhash.h
178111*/
178112#ifdef SQLITE_ASCII
178113# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
178114#endif
178115#ifdef SQLITE_EBCDIC
178116# define charMap(X) ebcdicToAscii[(unsigned char)X]
178117const unsigned char ebcdicToAscii[] = {
178118/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
178119   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
178120   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
178121   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
178122   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
178123   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
178124   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
178125   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
178126   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
178127   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
178128   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
178129   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
178130   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
178131   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
178132   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
178133   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
178134   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
178135};
178136#endif
178137
178138/*
178139** The sqlite3KeywordCode function looks up an identifier to determine if
178140** it is a keyword.  If it is a keyword, the token code of that keyword is
178141** returned.  If the input is not a keyword, TK_ID is returned.
178142**
178143** The implementation of this routine was generated by a program,
178144** mkkeywordhash.c, located in the tool subdirectory of the distribution.
178145** The output of the mkkeywordhash.c program is written into a file
178146** named keywordhash.h and then included into this source file by
178147** the #include below.
178148*/
178149/************** Include keywordhash.h in the middle of tokenize.c ************/
178150/************** Begin file keywordhash.h *************************************/
178151/***** This file contains automatically generated code ******
178152**
178153** The code in this file has been automatically generated by
178154**
178155**   sqlite/tool/mkkeywordhash.c
178156**
178157** The code in this file implements a function that determines whether
178158** or not a given identifier is really an SQL keyword.  The same thing
178159** might be implemented more directly using a hand-written hash table.
178160** But by using this automatically generated code, the size of the code
178161** is substantially reduced.  This is important for embedded applications
178162** on platforms with limited memory.
178163*/
178164/* Hash score: 231 */
178165/* zKWText[] encodes 1007 bytes of keyword text in 667 bytes */
178166/*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
178167/*   ABLEFTHENDEFERRABLELSEXCLUDELETEMPORARYISNULLSAVEPOINTERSECT       */
178168/*   IESNOTNULLIKEXCEPTRANSACTIONATURALTERAISEXCLUSIVEXISTS             */
178169/*   CONSTRAINTOFFSETRIGGERANGENERATEDETACHAVINGLOBEGINNEREFERENCES     */
178170/*   UNIQUERYWITHOUTERELEASEATTACHBETWEENOTHINGROUPSCASCADEFAULT        */
178171/*   CASECOLLATECREATECURRENT_DATEIMMEDIATEJOINSERTMATCHPLANALYZE       */
178172/*   PRAGMATERIALIZEDEFERREDISTINCTUPDATEVALUESVIRTUALWAYSWHENWHERE     */
178173/*   CURSIVEABORTAFTERENAMEANDROPARTITIONAUTOINCREMENTCASTCOLUMN        */
178174/*   COMMITCONFLICTCROSSCURRENT_TIMESTAMPRECEDINGFAILASTFILTER          */
178175/*   EPLACEFIRSTFOLLOWINGFROMFULLIMITIFORDERESTRICTOTHERSOVER           */
178176/*   ETURNINGRIGHTROLLBACKROWSUNBOUNDEDUNIONUSINGVACUUMVIEWINDOWBY      */
178177/*   INITIALLYPRIMARY                                                   */
178178static const char zKWText[666] = {
178179  'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
178180  'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
178181  'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
178182  'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
178183  'E','R','R','A','B','L','E','L','S','E','X','C','L','U','D','E','L','E',
178184  'T','E','M','P','O','R','A','R','Y','I','S','N','U','L','L','S','A','V',
178185  'E','P','O','I','N','T','E','R','S','E','C','T','I','E','S','N','O','T',
178186  'N','U','L','L','I','K','E','X','C','E','P','T','R','A','N','S','A','C',
178187  'T','I','O','N','A','T','U','R','A','L','T','E','R','A','I','S','E','X',
178188  'C','L','U','S','I','V','E','X','I','S','T','S','C','O','N','S','T','R',
178189  'A','I','N','T','O','F','F','S','E','T','R','I','G','G','E','R','A','N',
178190  'G','E','N','E','R','A','T','E','D','E','T','A','C','H','A','V','I','N',
178191  'G','L','O','B','E','G','I','N','N','E','R','E','F','E','R','E','N','C',
178192  'E','S','U','N','I','Q','U','E','R','Y','W','I','T','H','O','U','T','E',
178193  'R','E','L','E','A','S','E','A','T','T','A','C','H','B','E','T','W','E',
178194  'E','N','O','T','H','I','N','G','R','O','U','P','S','C','A','S','C','A',
178195  'D','E','F','A','U','L','T','C','A','S','E','C','O','L','L','A','T','E',
178196  'C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A','T','E',
178197  'I','M','M','E','D','I','A','T','E','J','O','I','N','S','E','R','T','M',
178198  'A','T','C','H','P','L','A','N','A','L','Y','Z','E','P','R','A','G','M',
178199  'A','T','E','R','I','A','L','I','Z','E','D','E','F','E','R','R','E','D',
178200  'I','S','T','I','N','C','T','U','P','D','A','T','E','V','A','L','U','E',
178201  'S','V','I','R','T','U','A','L','W','A','Y','S','W','H','E','N','W','H',
178202  'E','R','E','C','U','R','S','I','V','E','A','B','O','R','T','A','F','T',
178203  'E','R','E','N','A','M','E','A','N','D','R','O','P','A','R','T','I','T',
178204  'I','O','N','A','U','T','O','I','N','C','R','E','M','E','N','T','C','A',
178205  'S','T','C','O','L','U','M','N','C','O','M','M','I','T','C','O','N','F',
178206  'L','I','C','T','C','R','O','S','S','C','U','R','R','E','N','T','_','T',
178207  'I','M','E','S','T','A','M','P','R','E','C','E','D','I','N','G','F','A',
178208  'I','L','A','S','T','F','I','L','T','E','R','E','P','L','A','C','E','F',
178209  'I','R','S','T','F','O','L','L','O','W','I','N','G','F','R','O','M','F',
178210  'U','L','L','I','M','I','T','I','F','O','R','D','E','R','E','S','T','R',
178211  'I','C','T','O','T','H','E','R','S','O','V','E','R','E','T','U','R','N',
178212  'I','N','G','R','I','G','H','T','R','O','L','L','B','A','C','K','R','O',
178213  'W','S','U','N','B','O','U','N','D','E','D','U','N','I','O','N','U','S',
178214  'I','N','G','V','A','C','U','U','M','V','I','E','W','I','N','D','O','W',
178215  'B','Y','I','N','I','T','I','A','L','L','Y','P','R','I','M','A','R','Y',
178216};
178217/* aKWHash[i] is the hash value for the i-th keyword */
178218static const unsigned char aKWHash[127] = {
178219    84,  92, 134,  82, 105,  29,   0,   0,  94,   0,  85,  72,   0,
178220    53,  35,  86,  15,   0,  42,  97,  54,  89, 135,  19,   0,   0,
178221   140,   0,  40, 129,   0,  22, 107,   0,   9,   0,   0, 123,  80,
178222     0,  78,   6,   0,  65, 103, 147,   0, 136, 115,   0,   0,  48,
178223     0,  90,  24,   0,  17,   0,  27,  70,  23,  26,   5,  60, 142,
178224   110, 122,   0,  73,  91,  71, 145,  61, 120,  74,   0,  49,   0,
178225    11,  41,   0, 113,   0,   0,   0, 109,  10, 111, 116, 125,  14,
178226    50, 124,   0, 100,   0,  18, 121, 144,  56, 130, 139,  88,  83,
178227    37,  30, 126,   0,   0, 108,  51, 131, 128,   0,  34,   0,   0,
178228   132,   0,  98,  38,  39,   0,  20,  45, 117,  93,
178229};
178230/* aKWNext[] forms the hash collision chain.  If aKWHash[i]==0
178231** then the i-th keyword has no more hash collisions.  Otherwise,
178232** the next keyword with the same hash is aKWHash[i]-1. */
178233static const unsigned char aKWNext[148] = {0,
178234     0,   0,   0,   0,   4,   0,  43,   0,   0, 106, 114,   0,   0,
178235     0,   2,   0,   0, 143,   0,   0,   0,  13,   0,   0,   0,   0,
178236   141,   0,   0, 119,  52,   0,   0, 137,  12,   0,   0,  62,   0,
178237   138,   0, 133,   0,   0,  36,   0,   0,  28,  77,   0,   0,   0,
178238     0,  59,   0,  47,   0,   0,   0,   0,   0,   0,   0,   0,   0,
178239     0,  69,   0,   0,   0,   0,   0, 146,   3,   0,  58,   0,   1,
178240    75,   0,   0,   0,  31,   0,   0,   0,   0,   0, 127,   0, 104,
178241     0,  64,  66,  63,   0,   0,   0,   0,   0,  46,   0,  16,   8,
178242     0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  81, 101,   0,
178243   112,  21,   7,  67,   0,  79,  96, 118,   0,   0,  68,   0,   0,
178244    99,  44,   0,  55,   0,  76,   0,  95,  32,  33,  57,  25,   0,
178245   102,   0,   0,  87,
178246};
178247/* aKWLen[i] is the length (in bytes) of the i-th keyword */
178248static const unsigned char aKWLen[148] = {0,
178249     7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
178250     7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   7,
178251     6,   9,   4,   2,   6,   5,   9,   9,   4,   7,   3,   2,   4,
178252     4,   6,  11,   6,   2,   7,   5,   5,   9,   6,  10,   4,   6,
178253     2,   3,   7,   5,   9,   6,   6,   4,   5,   5,  10,   6,   5,
178254     7,   4,   5,   7,   6,   7,   7,   6,   5,   7,   3,   7,   4,
178255     7,   6,  12,   9,   4,   6,   5,   4,   7,   6,  12,   8,   8,
178256     2,   6,   6,   7,   6,   4,   5,   9,   5,   5,   6,   3,   4,
178257     9,  13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   9,
178258     4,   4,   6,   7,   5,   9,   4,   4,   5,   2,   5,   8,   6,
178259     4,   9,   5,   8,   4,   3,   9,   5,   5,   6,   4,   6,   2,
178260     2,   9,   3,   7,
178261};
178262/* aKWOffset[i] is the index into zKWText[] of the start of
178263** the text for the i-th keyword. */
178264static const unsigned short int aKWOffset[148] = {0,
178265     0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
178266    36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
178267    86,  90,  90,  94,  99, 101, 105, 111, 119, 123, 123, 123, 126,
178268   129, 132, 137, 142, 146, 147, 152, 156, 160, 168, 174, 181, 184,
178269   184, 187, 189, 195, 198, 206, 211, 216, 219, 222, 226, 236, 239,
178270   244, 244, 248, 252, 259, 265, 271, 277, 277, 283, 284, 288, 295,
178271   299, 306, 312, 324, 333, 335, 341, 346, 348, 355, 359, 370, 377,
178272   378, 385, 391, 397, 402, 408, 412, 415, 424, 429, 433, 439, 441,
178273   444, 453, 455, 457, 466, 470, 476, 482, 490, 495, 495, 495, 511,
178274   520, 523, 527, 532, 539, 544, 553, 557, 560, 565, 567, 571, 579,
178275   585, 588, 597, 602, 610, 610, 614, 623, 628, 633, 639, 642, 645,
178276   648, 650, 655, 659,
178277};
178278/* aKWCode[i] is the parser symbol code for the i-th keyword */
178279static const unsigned char aKWCode[148] = {0,
178280  TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
178281  TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
178282  TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
178283  TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
178284  TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
178285  TK_EXCLUDE,    TK_DELETE,     TK_TEMP,       TK_TEMP,       TK_OR,
178286  TK_ISNULL,     TK_NULLS,      TK_SAVEPOINT,  TK_INTERSECT,  TK_TIES,
178287  TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
178288  TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
178289  TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_CONSTRAINT,
178290  TK_INTO,       TK_OFFSET,     TK_OF,         TK_SET,        TK_TRIGGER,
178291  TK_RANGE,      TK_GENERATED,  TK_DETACH,     TK_HAVING,     TK_LIKE_KW,
178292  TK_BEGIN,      TK_JOIN_KW,    TK_REFERENCES, TK_UNIQUE,     TK_QUERY,
178293  TK_WITHOUT,    TK_WITH,       TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,
178294  TK_BETWEEN,    TK_NOTHING,    TK_GROUPS,     TK_GROUP,      TK_CASCADE,
178295  TK_ASC,        TK_DEFAULT,    TK_CASE,       TK_COLLATE,    TK_CREATE,
178296  TK_CTIME_KW,   TK_IMMEDIATE,  TK_JOIN,       TK_INSERT,     TK_MATCH,
178297  TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,     TK_MATERIALIZED, TK_DEFERRED,
178298  TK_DISTINCT,   TK_IS,         TK_UPDATE,     TK_VALUES,     TK_VIRTUAL,
178299  TK_ALWAYS,     TK_WHEN,       TK_WHERE,      TK_RECURSIVE,  TK_ABORT,
178300  TK_AFTER,      TK_RENAME,     TK_AND,        TK_DROP,       TK_PARTITION,
178301  TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,       TK_COLUMNKW,
178302  TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,
178303  TK_CURRENT,    TK_PRECEDING,  TK_FAIL,       TK_LAST,       TK_FILTER,
178304  TK_REPLACE,    TK_FIRST,      TK_FOLLOWING,  TK_FROM,       TK_JOIN_KW,
178305  TK_LIMIT,      TK_IF,         TK_ORDER,      TK_RESTRICT,   TK_OTHERS,
178306  TK_OVER,       TK_RETURNING,  TK_JOIN_KW,    TK_ROLLBACK,   TK_ROWS,
178307  TK_ROW,        TK_UNBOUNDED,  TK_UNION,      TK_USING,      TK_VACUUM,
178308  TK_VIEW,       TK_WINDOW,     TK_DO,         TK_BY,         TK_INITIALLY,
178309  TK_ALL,        TK_PRIMARY,
178310};
178311/* Hash table decoded:
178312**   0: INSERT
178313**   1: IS
178314**   2: ROLLBACK TRIGGER
178315**   3: IMMEDIATE
178316**   4: PARTITION
178317**   5: TEMP
178318**   6:
178319**   7:
178320**   8: VALUES WITHOUT
178321**   9:
178322**  10: MATCH
178323**  11: NOTHING
178324**  12:
178325**  13: OF
178326**  14: TIES IGNORE
178327**  15: PLAN
178328**  16: INSTEAD INDEXED
178329**  17:
178330**  18: TRANSACTION RIGHT
178331**  19: WHEN
178332**  20: SET HAVING
178333**  21: MATERIALIZED IF
178334**  22: ROWS
178335**  23: SELECT
178336**  24:
178337**  25:
178338**  26: VACUUM SAVEPOINT
178339**  27:
178340**  28: LIKE UNION VIRTUAL REFERENCES
178341**  29: RESTRICT
178342**  30:
178343**  31: THEN REGEXP
178344**  32: TO
178345**  33:
178346**  34: BEFORE
178347**  35:
178348**  36:
178349**  37: FOLLOWING COLLATE CASCADE
178350**  38: CREATE
178351**  39:
178352**  40: CASE REINDEX
178353**  41: EACH
178354**  42:
178355**  43: QUERY
178356**  44: AND ADD
178357**  45: PRIMARY ANALYZE
178358**  46:
178359**  47: ROW ASC DETACH
178360**  48: CURRENT_TIME CURRENT_DATE
178361**  49:
178362**  50:
178363**  51: EXCLUSIVE TEMPORARY
178364**  52:
178365**  53: DEFERRED
178366**  54: DEFERRABLE
178367**  55:
178368**  56: DATABASE
178369**  57:
178370**  58: DELETE VIEW GENERATED
178371**  59: ATTACH
178372**  60: END
178373**  61: EXCLUDE
178374**  62: ESCAPE DESC
178375**  63: GLOB
178376**  64: WINDOW ELSE
178377**  65: COLUMN
178378**  66: FIRST
178379**  67:
178380**  68: GROUPS ALL
178381**  69: DISTINCT DROP KEY
178382**  70: BETWEEN
178383**  71: INITIALLY
178384**  72: BEGIN
178385**  73: FILTER CHECK ACTION
178386**  74: GROUP INDEX
178387**  75:
178388**  76: EXISTS DEFAULT
178389**  77:
178390**  78: FOR CURRENT_TIMESTAMP
178391**  79: EXCEPT
178392**  80:
178393**  81: CROSS
178394**  82:
178395**  83:
178396**  84:
178397**  85: CAST
178398**  86: FOREIGN AUTOINCREMENT
178399**  87: COMMIT
178400**  88: CURRENT AFTER ALTER
178401**  89: FULL FAIL CONFLICT
178402**  90: EXPLAIN
178403**  91: CONSTRAINT
178404**  92: FROM ALWAYS
178405**  93:
178406**  94: ABORT
178407**  95:
178408**  96: AS DO
178409**  97: REPLACE WITH RELEASE
178410**  98: BY RENAME
178411**  99: RANGE RAISE
178412** 100: OTHERS
178413** 101: USING NULLS
178414** 102: PRAGMA
178415** 103: JOIN ISNULL OFFSET
178416** 104: NOT
178417** 105: OR LAST LEFT
178418** 106: LIMIT
178419** 107:
178420** 108:
178421** 109: IN
178422** 110: INTO
178423** 111: OVER RECURSIVE
178424** 112: ORDER OUTER
178425** 113:
178426** 114: INTERSECT UNBOUNDED
178427** 115:
178428** 116:
178429** 117: RETURNING ON
178430** 118:
178431** 119: WHERE
178432** 120: NO INNER
178433** 121: NULL
178434** 122:
178435** 123: TABLE
178436** 124: NATURAL NOTNULL
178437** 125: PRECEDING
178438** 126: UPDATE UNIQUE
178439*/
178440/* Check to see if z[0..n-1] is a keyword. If it is, write the
178441** parser symbol code for that keyword into *pType.  Always
178442** return the integer n (the length of the token). */
178443static int keywordCode(const char *z, int n, int *pType){
178444  int i, j;
178445  const char *zKW;
178446  assert( n>=2 );
178447  i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n*1) % 127;
178448  for(i=(int)aKWHash[i]; i>0; i=aKWNext[i]){
178449    if( aKWLen[i]!=n ) continue;
178450    zKW = &zKWText[aKWOffset[i]];
178451#ifdef SQLITE_ASCII
178452    if( (z[0]&~0x20)!=zKW[0] ) continue;
178453    if( (z[1]&~0x20)!=zKW[1] ) continue;
178454    j = 2;
178455    while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
178456#endif
178457#ifdef SQLITE_EBCDIC
178458    if( toupper(z[0])!=zKW[0] ) continue;
178459    if( toupper(z[1])!=zKW[1] ) continue;
178460    j = 2;
178461    while( j<n && toupper(z[j])==zKW[j] ){ j++; }
178462#endif
178463    if( j<n ) continue;
178464    testcase( i==1 ); /* REINDEX */
178465    testcase( i==2 ); /* INDEXED */
178466    testcase( i==3 ); /* INDEX */
178467    testcase( i==4 ); /* DESC */
178468    testcase( i==5 ); /* ESCAPE */
178469    testcase( i==6 ); /* EACH */
178470    testcase( i==7 ); /* CHECK */
178471    testcase( i==8 ); /* KEY */
178472    testcase( i==9 ); /* BEFORE */
178473    testcase( i==10 ); /* FOREIGN */
178474    testcase( i==11 ); /* FOR */
178475    testcase( i==12 ); /* IGNORE */
178476    testcase( i==13 ); /* REGEXP */
178477    testcase( i==14 ); /* EXPLAIN */
178478    testcase( i==15 ); /* INSTEAD */
178479    testcase( i==16 ); /* ADD */
178480    testcase( i==17 ); /* DATABASE */
178481    testcase( i==18 ); /* AS */
178482    testcase( i==19 ); /* SELECT */
178483    testcase( i==20 ); /* TABLE */
178484    testcase( i==21 ); /* LEFT */
178485    testcase( i==22 ); /* THEN */
178486    testcase( i==23 ); /* END */
178487    testcase( i==24 ); /* DEFERRABLE */
178488    testcase( i==25 ); /* ELSE */
178489    testcase( i==26 ); /* EXCLUDE */
178490    testcase( i==27 ); /* DELETE */
178491    testcase( i==28 ); /* TEMPORARY */
178492    testcase( i==29 ); /* TEMP */
178493    testcase( i==30 ); /* OR */
178494    testcase( i==31 ); /* ISNULL */
178495    testcase( i==32 ); /* NULLS */
178496    testcase( i==33 ); /* SAVEPOINT */
178497    testcase( i==34 ); /* INTERSECT */
178498    testcase( i==35 ); /* TIES */
178499    testcase( i==36 ); /* NOTNULL */
178500    testcase( i==37 ); /* NOT */
178501    testcase( i==38 ); /* NO */
178502    testcase( i==39 ); /* NULL */
178503    testcase( i==40 ); /* LIKE */
178504    testcase( i==41 ); /* EXCEPT */
178505    testcase( i==42 ); /* TRANSACTION */
178506    testcase( i==43 ); /* ACTION */
178507    testcase( i==44 ); /* ON */
178508    testcase( i==45 ); /* NATURAL */
178509    testcase( i==46 ); /* ALTER */
178510    testcase( i==47 ); /* RAISE */
178511    testcase( i==48 ); /* EXCLUSIVE */
178512    testcase( i==49 ); /* EXISTS */
178513    testcase( i==50 ); /* CONSTRAINT */
178514    testcase( i==51 ); /* INTO */
178515    testcase( i==52 ); /* OFFSET */
178516    testcase( i==53 ); /* OF */
178517    testcase( i==54 ); /* SET */
178518    testcase( i==55 ); /* TRIGGER */
178519    testcase( i==56 ); /* RANGE */
178520    testcase( i==57 ); /* GENERATED */
178521    testcase( i==58 ); /* DETACH */
178522    testcase( i==59 ); /* HAVING */
178523    testcase( i==60 ); /* GLOB */
178524    testcase( i==61 ); /* BEGIN */
178525    testcase( i==62 ); /* INNER */
178526    testcase( i==63 ); /* REFERENCES */
178527    testcase( i==64 ); /* UNIQUE */
178528    testcase( i==65 ); /* QUERY */
178529    testcase( i==66 ); /* WITHOUT */
178530    testcase( i==67 ); /* WITH */
178531    testcase( i==68 ); /* OUTER */
178532    testcase( i==69 ); /* RELEASE */
178533    testcase( i==70 ); /* ATTACH */
178534    testcase( i==71 ); /* BETWEEN */
178535    testcase( i==72 ); /* NOTHING */
178536    testcase( i==73 ); /* GROUPS */
178537    testcase( i==74 ); /* GROUP */
178538    testcase( i==75 ); /* CASCADE */
178539    testcase( i==76 ); /* ASC */
178540    testcase( i==77 ); /* DEFAULT */
178541    testcase( i==78 ); /* CASE */
178542    testcase( i==79 ); /* COLLATE */
178543    testcase( i==80 ); /* CREATE */
178544    testcase( i==81 ); /* CURRENT_DATE */
178545    testcase( i==82 ); /* IMMEDIATE */
178546    testcase( i==83 ); /* JOIN */
178547    testcase( i==84 ); /* INSERT */
178548    testcase( i==85 ); /* MATCH */
178549    testcase( i==86 ); /* PLAN */
178550    testcase( i==87 ); /* ANALYZE */
178551    testcase( i==88 ); /* PRAGMA */
178552    testcase( i==89 ); /* MATERIALIZED */
178553    testcase( i==90 ); /* DEFERRED */
178554    testcase( i==91 ); /* DISTINCT */
178555    testcase( i==92 ); /* IS */
178556    testcase( i==93 ); /* UPDATE */
178557    testcase( i==94 ); /* VALUES */
178558    testcase( i==95 ); /* VIRTUAL */
178559    testcase( i==96 ); /* ALWAYS */
178560    testcase( i==97 ); /* WHEN */
178561    testcase( i==98 ); /* WHERE */
178562    testcase( i==99 ); /* RECURSIVE */
178563    testcase( i==100 ); /* ABORT */
178564    testcase( i==101 ); /* AFTER */
178565    testcase( i==102 ); /* RENAME */
178566    testcase( i==103 ); /* AND */
178567    testcase( i==104 ); /* DROP */
178568    testcase( i==105 ); /* PARTITION */
178569    testcase( i==106 ); /* AUTOINCREMENT */
178570    testcase( i==107 ); /* TO */
178571    testcase( i==108 ); /* IN */
178572    testcase( i==109 ); /* CAST */
178573    testcase( i==110 ); /* COLUMN */
178574    testcase( i==111 ); /* COMMIT */
178575    testcase( i==112 ); /* CONFLICT */
178576    testcase( i==113 ); /* CROSS */
178577    testcase( i==114 ); /* CURRENT_TIMESTAMP */
178578    testcase( i==115 ); /* CURRENT_TIME */
178579    testcase( i==116 ); /* CURRENT */
178580    testcase( i==117 ); /* PRECEDING */
178581    testcase( i==118 ); /* FAIL */
178582    testcase( i==119 ); /* LAST */
178583    testcase( i==120 ); /* FILTER */
178584    testcase( i==121 ); /* REPLACE */
178585    testcase( i==122 ); /* FIRST */
178586    testcase( i==123 ); /* FOLLOWING */
178587    testcase( i==124 ); /* FROM */
178588    testcase( i==125 ); /* FULL */
178589    testcase( i==126 ); /* LIMIT */
178590    testcase( i==127 ); /* IF */
178591    testcase( i==128 ); /* ORDER */
178592    testcase( i==129 ); /* RESTRICT */
178593    testcase( i==130 ); /* OTHERS */
178594    testcase( i==131 ); /* OVER */
178595    testcase( i==132 ); /* RETURNING */
178596    testcase( i==133 ); /* RIGHT */
178597    testcase( i==134 ); /* ROLLBACK */
178598    testcase( i==135 ); /* ROWS */
178599    testcase( i==136 ); /* ROW */
178600    testcase( i==137 ); /* UNBOUNDED */
178601    testcase( i==138 ); /* UNION */
178602    testcase( i==139 ); /* USING */
178603    testcase( i==140 ); /* VACUUM */
178604    testcase( i==141 ); /* VIEW */
178605    testcase( i==142 ); /* WINDOW */
178606    testcase( i==143 ); /* DO */
178607    testcase( i==144 ); /* BY */
178608    testcase( i==145 ); /* INITIALLY */
178609    testcase( i==146 ); /* ALL */
178610    testcase( i==147 ); /* PRIMARY */
178611    *pType = aKWCode[i];
178612    break;
178613  }
178614  return n;
178615}
178616SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
178617  int id = TK_ID;
178618  if( n>=2 ) keywordCode((char*)z, n, &id);
178619  return id;
178620}
178621#define SQLITE_N_KEYWORD 147
178622SQLITE_API int sqlite3_keyword_name(int i,const char **pzName,int *pnName){
178623  if( i<0 || i>=SQLITE_N_KEYWORD ) return SQLITE_ERROR;
178624  i++;
178625  *pzName = zKWText + aKWOffset[i];
178626  *pnName = aKWLen[i];
178627  return SQLITE_OK;
178628}
178629SQLITE_API int sqlite3_keyword_count(void){ return SQLITE_N_KEYWORD; }
178630SQLITE_API int sqlite3_keyword_check(const char *zName, int nName){
178631  return TK_ID!=sqlite3KeywordCode((const u8*)zName, nName);
178632}
178633
178634/************** End of keywordhash.h *****************************************/
178635/************** Continuing where we left off in tokenize.c *******************/
178636
178637
178638/*
178639** If X is a character that can be used in an identifier then
178640** IdChar(X) will be true.  Otherwise it is false.
178641**
178642** For ASCII, any character with the high-order bit set is
178643** allowed in an identifier.  For 7-bit characters,
178644** sqlite3IsIdChar[X] must be 1.
178645**
178646** For EBCDIC, the rules are more complex but have the same
178647** end result.
178648**
178649** Ticket #1066.  the SQL standard does not allow '$' in the
178650** middle of identifiers.  But many SQL implementations do.
178651** SQLite will allow '$' in identifiers for compatibility.
178652** But the feature is undocumented.
178653*/
178654#ifdef SQLITE_ASCII
178655#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
178656#endif
178657#ifdef SQLITE_EBCDIC
178658SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
178659/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
178660    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
178661    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
178662    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
178663    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
178664    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
178665    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
178666    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
178667    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
178668    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
178669    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
178670    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
178671    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
178672};
178673#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
178674#endif
178675
178676/* Make the IdChar function accessible from ctime.c and alter.c */
178677SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
178678
178679#ifndef SQLITE_OMIT_WINDOWFUNC
178680/*
178681** Return the id of the next token in string (*pz). Before returning, set
178682** (*pz) to point to the byte following the parsed token.
178683*/
178684static int getToken(const unsigned char **pz){
178685  const unsigned char *z = *pz;
178686  int t;                          /* Token type to return */
178687  do {
178688    z += sqlite3GetToken(z, &t);
178689  }while( t==TK_SPACE );
178690  if( t==TK_ID
178691   || t==TK_STRING
178692   || t==TK_JOIN_KW
178693   || t==TK_WINDOW
178694   || t==TK_OVER
178695   || sqlite3ParserFallback(t)==TK_ID
178696  ){
178697    t = TK_ID;
178698  }
178699  *pz = z;
178700  return t;
178701}
178702
178703/*
178704** The following three functions are called immediately after the tokenizer
178705** reads the keywords WINDOW, OVER and FILTER, respectively, to determine
178706** whether the token should be treated as a keyword or an SQL identifier.
178707** This cannot be handled by the usual lemon %fallback method, due to
178708** the ambiguity in some constructions. e.g.
178709**
178710**   SELECT sum(x) OVER ...
178711**
178712** In the above, "OVER" might be a keyword, or it might be an alias for the
178713** sum(x) expression. If a "%fallback ID OVER" directive were added to
178714** grammar, then SQLite would always treat "OVER" as an alias, making it
178715** impossible to call a window-function without a FILTER clause.
178716**
178717** WINDOW is treated as a keyword if:
178718**
178719**   * the following token is an identifier, or a keyword that can fallback
178720**     to being an identifier, and
178721**   * the token after than one is TK_AS.
178722**
178723** OVER is a keyword if:
178724**
178725**   * the previous token was TK_RP, and
178726**   * the next token is either TK_LP or an identifier.
178727**
178728** FILTER is a keyword if:
178729**
178730**   * the previous token was TK_RP, and
178731**   * the next token is TK_LP.
178732*/
178733static int analyzeWindowKeyword(const unsigned char *z){
178734  int t;
178735  t = getToken(&z);
178736  if( t!=TK_ID ) return TK_ID;
178737  t = getToken(&z);
178738  if( t!=TK_AS ) return TK_ID;
178739  return TK_WINDOW;
178740}
178741static int analyzeOverKeyword(const unsigned char *z, int lastToken){
178742  if( lastToken==TK_RP ){
178743    int t = getToken(&z);
178744    if( t==TK_LP || t==TK_ID ) return TK_OVER;
178745  }
178746  return TK_ID;
178747}
178748static int analyzeFilterKeyword(const unsigned char *z, int lastToken){
178749  if( lastToken==TK_RP && getToken(&z)==TK_LP ){
178750    return TK_FILTER;
178751  }
178752  return TK_ID;
178753}
178754#endif /* SQLITE_OMIT_WINDOWFUNC */
178755
178756/*
178757** Return the length (in bytes) of the token that begins at z[0].
178758** Store the token type in *tokenType before returning.
178759*/
178760SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
178761  int i, c;
178762  switch( aiClass[*z] ){  /* Switch on the character-class of the first byte
178763                          ** of the token. See the comment on the CC_ defines
178764                          ** above. */
178765    case CC_SPACE: {
178766      testcase( z[0]==' ' );
178767      testcase( z[0]=='\t' );
178768      testcase( z[0]=='\n' );
178769      testcase( z[0]=='\f' );
178770      testcase( z[0]=='\r' );
178771      for(i=1; sqlite3Isspace(z[i]); i++){}
178772      *tokenType = TK_SPACE;
178773      return i;
178774    }
178775    case CC_MINUS: {
178776      if( z[1]=='-' ){
178777        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
178778        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
178779        return i;
178780      }else if( z[1]=='>' ){
178781        *tokenType = TK_PTR;
178782        return 2 + (z[2]=='>');
178783      }
178784      *tokenType = TK_MINUS;
178785      return 1;
178786    }
178787    case CC_LP: {
178788      *tokenType = TK_LP;
178789      return 1;
178790    }
178791    case CC_RP: {
178792      *tokenType = TK_RP;
178793      return 1;
178794    }
178795    case CC_SEMI: {
178796      *tokenType = TK_SEMI;
178797      return 1;
178798    }
178799    case CC_PLUS: {
178800      *tokenType = TK_PLUS;
178801      return 1;
178802    }
178803    case CC_STAR: {
178804      *tokenType = TK_STAR;
178805      return 1;
178806    }
178807    case CC_SLASH: {
178808      if( z[1]!='*' || z[2]==0 ){
178809        *tokenType = TK_SLASH;
178810        return 1;
178811      }
178812      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
178813      if( c ) i++;
178814      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
178815      return i;
178816    }
178817    case CC_PERCENT: {
178818      *tokenType = TK_REM;
178819      return 1;
178820    }
178821    case CC_EQ: {
178822      *tokenType = TK_EQ;
178823      return 1 + (z[1]=='=');
178824    }
178825    case CC_LT: {
178826      if( (c=z[1])=='=' ){
178827        *tokenType = TK_LE;
178828        return 2;
178829      }else if( c=='>' ){
178830        *tokenType = TK_NE;
178831        return 2;
178832      }else if( c=='<' ){
178833        *tokenType = TK_LSHIFT;
178834        return 2;
178835      }else{
178836        *tokenType = TK_LT;
178837        return 1;
178838      }
178839    }
178840    case CC_GT: {
178841      if( (c=z[1])=='=' ){
178842        *tokenType = TK_GE;
178843        return 2;
178844      }else if( c=='>' ){
178845        *tokenType = TK_RSHIFT;
178846        return 2;
178847      }else{
178848        *tokenType = TK_GT;
178849        return 1;
178850      }
178851    }
178852    case CC_BANG: {
178853      if( z[1]!='=' ){
178854        *tokenType = TK_ILLEGAL;
178855        return 1;
178856      }else{
178857        *tokenType = TK_NE;
178858        return 2;
178859      }
178860    }
178861    case CC_PIPE: {
178862      if( z[1]!='|' ){
178863        *tokenType = TK_BITOR;
178864        return 1;
178865      }else{
178866        *tokenType = TK_CONCAT;
178867        return 2;
178868      }
178869    }
178870    case CC_COMMA: {
178871      *tokenType = TK_COMMA;
178872      return 1;
178873    }
178874    case CC_AND: {
178875      *tokenType = TK_BITAND;
178876      return 1;
178877    }
178878    case CC_TILDA: {
178879      *tokenType = TK_BITNOT;
178880      return 1;
178881    }
178882    case CC_QUOTE: {
178883      int delim = z[0];
178884      testcase( delim=='`' );
178885      testcase( delim=='\'' );
178886      testcase( delim=='"' );
178887      for(i=1; (c=z[i])!=0; i++){
178888        if( c==delim ){
178889          if( z[i+1]==delim ){
178890            i++;
178891          }else{
178892            break;
178893          }
178894        }
178895      }
178896      if( c=='\'' ){
178897        *tokenType = TK_STRING;
178898        return i+1;
178899      }else if( c!=0 ){
178900        *tokenType = TK_ID;
178901        return i+1;
178902      }else{
178903        *tokenType = TK_ILLEGAL;
178904        return i;
178905      }
178906    }
178907    case CC_DOT: {
178908#ifndef SQLITE_OMIT_FLOATING_POINT
178909      if( !sqlite3Isdigit(z[1]) )
178910#endif
178911      {
178912        *tokenType = TK_DOT;
178913        return 1;
178914      }
178915      /* If the next character is a digit, this is a floating point
178916      ** number that begins with ".".  Fall thru into the next case */
178917      /* no break */ deliberate_fall_through
178918    }
178919    case CC_DIGIT: {
178920      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
178921      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
178922      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
178923      testcase( z[0]=='9' );  testcase( z[0]=='.' );
178924      *tokenType = TK_INTEGER;
178925#ifndef SQLITE_OMIT_HEX_INTEGER
178926      if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
178927        for(i=3; 1; i++){
178928          if( sqlite3Isxdigit(z[i])==0 ){
178929            if( z[i]==SQLITE_DIGIT_SEPARATOR ){
178930              *tokenType = TK_QNUMBER;
178931            }else{
178932              break;
178933            }
178934          }
178935        }
178936      }else
178937#endif
178938        {
178939        for(i=0; 1; i++){
178940          if( sqlite3Isdigit(z[i])==0 ){
178941            if( z[i]==SQLITE_DIGIT_SEPARATOR ){
178942              *tokenType = TK_QNUMBER;
178943            }else{
178944              break;
178945            }
178946          }
178947        }
178948#ifndef SQLITE_OMIT_FLOATING_POINT
178949        if( z[i]=='.' ){
178950          if( *tokenType==TK_INTEGER ) *tokenType = TK_FLOAT;
178951          for(i++; 1; i++){
178952            if( sqlite3Isdigit(z[i])==0 ){
178953              if( z[i]==SQLITE_DIGIT_SEPARATOR ){
178954                *tokenType = TK_QNUMBER;
178955              }else{
178956                break;
178957              }
178958            }
178959          }
178960        }
178961        if( (z[i]=='e' || z[i]=='E') &&
178962             ( sqlite3Isdigit(z[i+1])
178963              || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
178964             )
178965        ){
178966          if( *tokenType==TK_INTEGER ) *tokenType = TK_FLOAT;
178967          for(i+=2; 1; i++){
178968            if( sqlite3Isdigit(z[i])==0 ){
178969              if( z[i]==SQLITE_DIGIT_SEPARATOR ){
178970                *tokenType = TK_QNUMBER;
178971              }else{
178972                break;
178973              }
178974            }
178975          }
178976        }
178977#endif
178978      }
178979      while( IdChar(z[i]) ){
178980        *tokenType = TK_ILLEGAL;
178981        i++;
178982      }
178983      return i;
178984    }
178985    case CC_QUOTE2: {
178986      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
178987      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
178988      return i;
178989    }
178990    case CC_VARNUM: {
178991      *tokenType = TK_VARIABLE;
178992      for(i=1; sqlite3Isdigit(z[i]); i++){}
178993      return i;
178994    }
178995    case CC_DOLLAR:
178996    case CC_VARALPHA: {
178997      int n = 0;
178998      testcase( z[0]=='$' );  testcase( z[0]=='@' );
178999      testcase( z[0]==':' );  testcase( z[0]=='#' );
179000      *tokenType = TK_VARIABLE;
179001      for(i=1; (c=z[i])!=0; i++){
179002        if( IdChar(c) ){
179003          n++;
179004#ifndef SQLITE_OMIT_TCL_VARIABLE
179005        }else if( c=='(' && n>0 ){
179006          do{
179007            i++;
179008          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
179009          if( c==')' ){
179010            i++;
179011          }else{
179012            *tokenType = TK_ILLEGAL;
179013          }
179014          break;
179015        }else if( c==':' && z[i+1]==':' ){
179016          i++;
179017#endif
179018        }else{
179019          break;
179020        }
179021      }
179022      if( n==0 ) *tokenType = TK_ILLEGAL;
179023      return i;
179024    }
179025    case CC_KYWD0: {
179026      if( aiClass[z[1]]>CC_KYWD ){ i = 1;  break; }
179027      for(i=2; aiClass[z[i]]<=CC_KYWD; i++){}
179028      if( IdChar(z[i]) ){
179029        /* This token started out using characters that can appear in keywords,
179030        ** but z[i] is a character not allowed within keywords, so this must
179031        ** be an identifier instead */
179032        i++;
179033        break;
179034      }
179035      *tokenType = TK_ID;
179036      return keywordCode((char*)z, i, tokenType);
179037    }
179038    case CC_X: {
179039#ifndef SQLITE_OMIT_BLOB_LITERAL
179040      testcase( z[0]=='x' ); testcase( z[0]=='X' );
179041      if( z[1]=='\'' ){
179042        *tokenType = TK_BLOB;
179043        for(i=2; sqlite3Isxdigit(z[i]); i++){}
179044        if( z[i]!='\'' || i%2 ){
179045          *tokenType = TK_ILLEGAL;
179046          while( z[i] && z[i]!='\'' ){ i++; }
179047        }
179048        if( z[i] ) i++;
179049        return i;
179050      }
179051#endif
179052      /* If it is not a BLOB literal, then it must be an ID, since no
179053      ** SQL keywords start with the letter 'x'.  Fall through */
179054      /* no break */ deliberate_fall_through
179055    }
179056    case CC_KYWD:
179057    case CC_ID: {
179058      i = 1;
179059      break;
179060    }
179061    case CC_BOM: {
179062      if( z[1]==0xbb && z[2]==0xbf ){
179063        *tokenType = TK_SPACE;
179064        return 3;
179065      }
179066      i = 1;
179067      break;
179068    }
179069    case CC_NUL: {
179070      *tokenType = TK_ILLEGAL;
179071      return 0;
179072    }
179073    default: {
179074      *tokenType = TK_ILLEGAL;
179075      return 1;
179076    }
179077  }
179078  while( IdChar(z[i]) ){ i++; }
179079  *tokenType = TK_ID;
179080  return i;
179081}
179082
179083/*
179084** Run the parser on the given SQL string.
179085*/
179086SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql){
179087  int nErr = 0;                   /* Number of errors encountered */
179088  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
179089  int n = 0;                      /* Length of the next token token */
179090  int tokenType;                  /* type of the next token */
179091  int lastTokenParsed = -1;       /* type of the previous token */
179092  sqlite3 *db = pParse->db;       /* The database connection */
179093  int mxSqlLen;                   /* Max length of an SQL string */
179094  Parse *pParentParse = 0;        /* Outer parse context, if any */
179095#ifdef sqlite3Parser_ENGINEALWAYSONSTACK
179096  yyParser sEngine;    /* Space to hold the Lemon-generated Parser object */
179097#endif
179098  VVA_ONLY( u8 startedWithOom = db->mallocFailed );
179099
179100  assert( zSql!=0 );
179101  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
179102  if( db->nVdbeActive==0 ){
179103    AtomicStore(&db->u1.isInterrupted, 0);
179104  }
179105  pParse->rc = SQLITE_OK;
179106  pParse->zTail = zSql;
179107#ifdef SQLITE_DEBUG
179108  if( db->flags & SQLITE_ParserTrace ){
179109    printf("parser: [[[%s]]]\n", zSql);
179110    sqlite3ParserTrace(stdout, "parser: ");
179111  }else{
179112    sqlite3ParserTrace(0, 0);
179113  }
179114#endif
179115#ifdef sqlite3Parser_ENGINEALWAYSONSTACK
179116  pEngine = &sEngine;
179117  sqlite3ParserInit(pEngine, pParse);
179118#else
179119  pEngine = sqlite3ParserAlloc(sqlite3Malloc, pParse);
179120  if( pEngine==0 ){
179121    sqlite3OomFault(db);
179122    return SQLITE_NOMEM_BKPT;
179123  }
179124#endif
179125  assert( pParse->pNewTable==0 );
179126  assert( pParse->pNewTrigger==0 );
179127  assert( pParse->nVar==0 );
179128  assert( pParse->pVList==0 );
179129  pParentParse = db->pParse;
179130  db->pParse = pParse;
179131  while( 1 ){
179132    n = sqlite3GetToken((u8*)zSql, &tokenType);
179133    mxSqlLen -= n;
179134    if( mxSqlLen<0 ){
179135      pParse->rc = SQLITE_TOOBIG;
179136      pParse->nErr++;
179137      break;
179138    }
179139#ifndef SQLITE_OMIT_WINDOWFUNC
179140    if( tokenType>=TK_WINDOW ){
179141      assert( tokenType==TK_SPACE || tokenType==TK_OVER || tokenType==TK_FILTER
179142           || tokenType==TK_ILLEGAL || tokenType==TK_WINDOW
179143           || tokenType==TK_QNUMBER
179144      );
179145#else
179146    if( tokenType>=TK_SPACE ){
179147      assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL
179148           || tokenType==TK_QNUMBER
179149      );
179150#endif /* SQLITE_OMIT_WINDOWFUNC */
179151      if( AtomicLoad(&db->u1.isInterrupted) ){
179152        pParse->rc = SQLITE_INTERRUPT;
179153        pParse->nErr++;
179154        break;
179155      }
179156      if( tokenType==TK_SPACE ){
179157        zSql += n;
179158        continue;
179159      }
179160      if( zSql[0]==0 ){
179161        /* Upon reaching the end of input, call the parser two more times
179162        ** with tokens TK_SEMI and 0, in that order. */
179163        if( lastTokenParsed==TK_SEMI ){
179164          tokenType = 0;
179165        }else if( lastTokenParsed==0 ){
179166          break;
179167        }else{
179168          tokenType = TK_SEMI;
179169        }
179170        n = 0;
179171#ifndef SQLITE_OMIT_WINDOWFUNC
179172      }else if( tokenType==TK_WINDOW ){
179173        assert( n==6 );
179174        tokenType = analyzeWindowKeyword((const u8*)&zSql[6]);
179175      }else if( tokenType==TK_OVER ){
179176        assert( n==4 );
179177        tokenType = analyzeOverKeyword((const u8*)&zSql[4], lastTokenParsed);
179178      }else if( tokenType==TK_FILTER ){
179179        assert( n==6 );
179180        tokenType = analyzeFilterKeyword((const u8*)&zSql[6], lastTokenParsed);
179181#endif /* SQLITE_OMIT_WINDOWFUNC */
179182      }else if( tokenType!=TK_QNUMBER ){
179183        Token x;
179184        x.z = zSql;
179185        x.n = n;
179186        sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"", &x);
179187        break;
179188      }
179189    }
179190    pParse->sLastToken.z = zSql;
179191    pParse->sLastToken.n = n;
179192    sqlite3Parser(pEngine, tokenType, pParse->sLastToken);
179193    lastTokenParsed = tokenType;
179194    zSql += n;
179195    assert( db->mallocFailed==0 || pParse->rc!=SQLITE_OK || startedWithOom );
179196    if( pParse->rc!=SQLITE_OK ) break;
179197  }
179198  assert( nErr==0 );
179199#ifdef YYTRACKMAXSTACKDEPTH
179200  sqlite3_mutex_enter(sqlite3MallocMutex());
179201  sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
179202      sqlite3ParserStackPeak(pEngine)
179203  );
179204  sqlite3_mutex_leave(sqlite3MallocMutex());
179205#endif /* YYDEBUG */
179206#ifdef sqlite3Parser_ENGINEALWAYSONSTACK
179207  sqlite3ParserFinalize(pEngine);
179208#else
179209  sqlite3ParserFree(pEngine, sqlite3_free);
179210#endif
179211  if( db->mallocFailed ){
179212    pParse->rc = SQLITE_NOMEM_BKPT;
179213  }
179214  if( pParse->zErrMsg || (pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE) ){
179215    if( pParse->zErrMsg==0 ){
179216      pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
179217    }
179218    sqlite3_log(pParse->rc, "%s in \"%s\"", pParse->zErrMsg, pParse->zTail);
179219    nErr++;
179220  }
179221  pParse->zTail = zSql;
179222#ifndef SQLITE_OMIT_VIRTUALTABLE
179223  sqlite3_free(pParse->apVtabLock);
179224#endif
179225
179226  if( pParse->pNewTable && !IN_SPECIAL_PARSE ){
179227    /* If the pParse->declareVtab flag is set, do not delete any table
179228    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
179229    ** will take responsibility for freeing the Table structure.
179230    */
179231    sqlite3DeleteTable(db, pParse->pNewTable);
179232  }
179233  if( pParse->pNewTrigger && !IN_RENAME_OBJECT ){
179234    sqlite3DeleteTrigger(db, pParse->pNewTrigger);
179235  }
179236  if( pParse->pVList ) sqlite3DbNNFreeNN(db, pParse->pVList);
179237  db->pParse = pParentParse;
179238  assert( nErr==0 || pParse->rc!=SQLITE_OK );
179239  return nErr;
179240}
179241
179242
179243#ifdef SQLITE_ENABLE_NORMALIZE
179244/*
179245** Insert a single space character into pStr if the current string
179246** ends with an identifier
179247*/
179248static void addSpaceSeparator(sqlite3_str *pStr){
179249  if( pStr->nChar && sqlite3IsIdChar(pStr->zText[pStr->nChar-1]) ){
179250    sqlite3_str_append(pStr, " ", 1);
179251  }
179252}
179253
179254/*
179255** Compute a normalization of the SQL given by zSql[0..nSql-1].  Return
179256** the normalization in space obtained from sqlite3DbMalloc().  Or return
179257** NULL if anything goes wrong or if zSql is NULL.
179258*/
179259SQLITE_PRIVATE char *sqlite3Normalize(
179260  Vdbe *pVdbe,       /* VM being reprepared */
179261  const char *zSql   /* The original SQL string */
179262){
179263  sqlite3 *db;       /* The database connection */
179264  int i;             /* Next unread byte of zSql[] */
179265  int n;             /* length of current token */
179266  int tokenType;     /* type of current token */
179267  int prevType = 0;  /* Previous non-whitespace token */
179268  int nParen;        /* Number of nested levels of parentheses */
179269  int iStartIN;      /* Start of RHS of IN operator in z[] */
179270  int nParenAtIN;    /* Value of nParent at start of RHS of IN operator */
179271  u32 j;             /* Bytes of normalized SQL generated so far */
179272  sqlite3_str *pStr; /* The normalized SQL string under construction */
179273
179274  db = sqlite3VdbeDb(pVdbe);
179275  tokenType = -1;
179276  nParen = iStartIN = nParenAtIN = 0;
179277  pStr = sqlite3_str_new(db);
179278  assert( pStr!=0 );  /* sqlite3_str_new() never returns NULL */
179279  for(i=0; zSql[i] && pStr->accError==0; i+=n){
179280    if( tokenType!=TK_SPACE ){
179281      prevType = tokenType;
179282    }
179283    n = sqlite3GetToken((unsigned char*)zSql+i, &tokenType);
179284    if( NEVER(n<=0) ) break;
179285    switch( tokenType ){
179286      case TK_SPACE: {
179287        break;
179288      }
179289      case TK_NULL: {
179290        if( prevType==TK_IS || prevType==TK_NOT ){
179291          sqlite3_str_append(pStr, " NULL", 5);
179292          break;
179293        }
179294        /* Fall through */
179295      }
179296      case TK_STRING:
179297      case TK_INTEGER:
179298      case TK_FLOAT:
179299      case TK_VARIABLE:
179300      case TK_BLOB: {
179301        sqlite3_str_append(pStr, "?", 1);
179302        break;
179303      }
179304      case TK_LP: {
179305        nParen++;
179306        if( prevType==TK_IN ){
179307          iStartIN = pStr->nChar;
179308          nParenAtIN = nParen;
179309        }
179310        sqlite3_str_append(pStr, "(", 1);
179311        break;
179312      }
179313      case TK_RP: {
179314        if( iStartIN>0 && nParen==nParenAtIN ){
179315          assert( pStr->nChar>=(u32)iStartIN );
179316          pStr->nChar = iStartIN+1;
179317          sqlite3_str_append(pStr, "?,?,?", 5);
179318          iStartIN = 0;
179319        }
179320        nParen--;
179321        sqlite3_str_append(pStr, ")", 1);
179322        break;
179323      }
179324      case TK_ID: {
179325        iStartIN = 0;
179326        j = pStr->nChar;
179327        if( sqlite3Isquote(zSql[i]) ){
179328          char *zId = sqlite3DbStrNDup(db, zSql+i, n);
179329          int nId;
179330          int eType = 0;
179331          if( zId==0 ) break;
179332          sqlite3Dequote(zId);
179333          if( zSql[i]=='"' && sqlite3VdbeUsesDoubleQuotedString(pVdbe, zId) ){
179334            sqlite3_str_append(pStr, "?", 1);
179335            sqlite3DbFree(db, zId);
179336            break;
179337          }
179338          nId = sqlite3Strlen30(zId);
179339          if( sqlite3GetToken((u8*)zId, &eType)==nId && eType==TK_ID ){
179340            addSpaceSeparator(pStr);
179341            sqlite3_str_append(pStr, zId, nId);
179342          }else{
179343            sqlite3_str_appendf(pStr, "\"%w\"", zId);
179344          }
179345          sqlite3DbFree(db, zId);
179346        }else{
179347          addSpaceSeparator(pStr);
179348          sqlite3_str_append(pStr, zSql+i, n);
179349        }
179350        while( j<pStr->nChar ){
179351          pStr->zText[j] = sqlite3Tolower(pStr->zText[j]);
179352          j++;
179353        }
179354        break;
179355      }
179356      case TK_SELECT: {
179357        iStartIN = 0;
179358        /* fall through */
179359      }
179360      default: {
179361        if( sqlite3IsIdChar(zSql[i]) ) addSpaceSeparator(pStr);
179362        j = pStr->nChar;
179363        sqlite3_str_append(pStr, zSql+i, n);
179364        while( j<pStr->nChar ){
179365          pStr->zText[j] = sqlite3Toupper(pStr->zText[j]);
179366          j++;
179367        }
179368        break;
179369      }
179370    }
179371  }
179372  if( tokenType!=TK_SEMI ) sqlite3_str_append(pStr, ";", 1);
179373  return sqlite3_str_finish(pStr);
179374}
179375#endif /* SQLITE_ENABLE_NORMALIZE */
179376
179377/************** End of tokenize.c ********************************************/
179378/************** Begin file complete.c ****************************************/
179379/*
179380** 2001 September 15
179381**
179382** The author disclaims copyright to this source code.  In place of
179383** a legal notice, here is a blessing:
179384**
179385**    May you do good and not evil.
179386**    May you find forgiveness for yourself and forgive others.
179387**    May you share freely, never taking more than you give.
179388**
179389*************************************************************************
179390** An tokenizer for SQL
179391**
179392** This file contains C code that implements the sqlite3_complete() API.
179393** This code used to be part of the tokenizer.c source file.  But by
179394** separating it out, the code will be automatically omitted from
179395** static links that do not use it.
179396*/
179397/* #include "sqliteInt.h" */
179398#ifndef SQLITE_OMIT_COMPLETE
179399
179400/*
179401** This is defined in tokenize.c.  We just have to import the definition.
179402*/
179403#ifndef SQLITE_AMALGAMATION
179404#ifdef SQLITE_ASCII
179405#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
179406#endif
179407#ifdef SQLITE_EBCDIC
179408SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
179409#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
179410#endif
179411#endif /* SQLITE_AMALGAMATION */
179412
179413
179414/*
179415** Token types used by the sqlite3_complete() routine.  See the header
179416** comments on that procedure for additional information.
179417*/
179418#define tkSEMI    0
179419#define tkWS      1
179420#define tkOTHER   2
179421#ifndef SQLITE_OMIT_TRIGGER
179422#define tkEXPLAIN 3
179423#define tkCREATE  4
179424#define tkTEMP    5
179425#define tkTRIGGER 6
179426#define tkEND     7
179427#endif
179428
179429/*
179430** Return TRUE if the given SQL string ends in a semicolon.
179431**
179432** Special handling is require for CREATE TRIGGER statements.
179433** Whenever the CREATE TRIGGER keywords are seen, the statement
179434** must end with ";END;".
179435**
179436** This implementation uses a state machine with 8 states:
179437**
179438**   (0) INVALID   We have not yet seen a non-whitespace character.
179439**
179440**   (1) START     At the beginning or end of an SQL statement.  This routine
179441**                 returns 1 if it ends in the START state and 0 if it ends
179442**                 in any other state.
179443**
179444**   (2) NORMAL    We are in the middle of statement which ends with a single
179445**                 semicolon.
179446**
179447**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
179448**                 a statement.
179449**
179450**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
179451**                 statement, possibly preceded by EXPLAIN and/or followed by
179452**                 TEMP or TEMPORARY
179453**
179454**   (5) TRIGGER   We are in the middle of a trigger definition that must be
179455**                 ended by a semicolon, the keyword END, and another semicolon.
179456**
179457**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
179458**                 the end of a trigger definition.
179459**
179460**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
179461**                 of a trigger definition.
179462**
179463** Transitions between states above are determined by tokens extracted
179464** from the input.  The following tokens are significant:
179465**
179466**   (0) tkSEMI      A semicolon.
179467**   (1) tkWS        Whitespace.
179468**   (2) tkOTHER     Any other SQL token.
179469**   (3) tkEXPLAIN   The "explain" keyword.
179470**   (4) tkCREATE    The "create" keyword.
179471**   (5) tkTEMP      The "temp" or "temporary" keyword.
179472**   (6) tkTRIGGER   The "trigger" keyword.
179473**   (7) tkEND       The "end" keyword.
179474**
179475** Whitespace never causes a state transition and is always ignored.
179476** This means that a SQL string of all whitespace is invalid.
179477**
179478** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
179479** to recognize the end of a trigger can be omitted.  All we have to do
179480** is look for a semicolon that is not part of an string or comment.
179481*/
179482SQLITE_API int sqlite3_complete(const char *zSql){
179483  u8 state = 0;   /* Current state, using numbers defined in header comment */
179484  u8 token;       /* Value of the next token */
179485
179486#ifndef SQLITE_OMIT_TRIGGER
179487  /* A complex statement machine used to detect the end of a CREATE TRIGGER
179488  ** statement.  This is the normal case.
179489  */
179490  static const u8 trans[8][8] = {
179491                     /* Token:                                                */
179492     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
179493     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
179494     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
179495     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
179496     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
179497     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
179498     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
179499     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
179500     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
179501  };
179502#else
179503  /* If triggers are not supported by this compile then the statement machine
179504  ** used to detect the end of a statement is much simpler
179505  */
179506  static const u8 trans[3][3] = {
179507                     /* Token:           */
179508     /* State:       **  SEMI  WS  OTHER */
179509     /* 0 INVALID: */ {    1,  0,     2, },
179510     /* 1   START: */ {    1,  1,     2, },
179511     /* 2  NORMAL: */ {    1,  2,     2, },
179512  };
179513#endif /* SQLITE_OMIT_TRIGGER */
179514
179515#ifdef SQLITE_ENABLE_API_ARMOR
179516  if( zSql==0 ){
179517    (void)SQLITE_MISUSE_BKPT;
179518    return 0;
179519  }
179520#endif
179521
179522  while( *zSql ){
179523    switch( *zSql ){
179524      case ';': {  /* A semicolon */
179525        token = tkSEMI;
179526        break;
179527      }
179528      case ' ':
179529      case '\r':
179530      case '\t':
179531      case '\n':
179532      case '\f': {  /* White space is ignored */
179533        token = tkWS;
179534        break;
179535      }
179536      case '/': {   /* C-style comments */
179537        if( zSql[1]!='*' ){
179538          token = tkOTHER;
179539          break;
179540        }
179541        zSql += 2;
179542        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
179543        if( zSql[0]==0 ) return 0;
179544        zSql++;
179545        token = tkWS;
179546        break;
179547      }
179548      case '-': {   /* SQL-style comments from "--" to end of line */
179549        if( zSql[1]!='-' ){
179550          token = tkOTHER;
179551          break;
179552        }
179553        while( *zSql && *zSql!='\n' ){ zSql++; }
179554        if( *zSql==0 ) return state==1;
179555        token = tkWS;
179556        break;
179557      }
179558      case '[': {   /* Microsoft-style identifiers in [...] */
179559        zSql++;
179560        while( *zSql && *zSql!=']' ){ zSql++; }
179561        if( *zSql==0 ) return 0;
179562        token = tkOTHER;
179563        break;
179564      }
179565      case '`':     /* Grave-accent quoted symbols used by MySQL */
179566      case '"':     /* single- and double-quoted strings */
179567      case '\'': {
179568        int c = *zSql;
179569        zSql++;
179570        while( *zSql && *zSql!=c ){ zSql++; }
179571        if( *zSql==0 ) return 0;
179572        token = tkOTHER;
179573        break;
179574      }
179575      default: {
179576#ifdef SQLITE_EBCDIC
179577        unsigned char c;
179578#endif
179579        if( IdChar((u8)*zSql) ){
179580          /* Keywords and unquoted identifiers */
179581          int nId;
179582          for(nId=1; IdChar(zSql[nId]); nId++){}
179583#ifdef SQLITE_OMIT_TRIGGER
179584          token = tkOTHER;
179585#else
179586          switch( *zSql ){
179587            case 'c': case 'C': {
179588              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
179589                token = tkCREATE;
179590              }else{
179591                token = tkOTHER;
179592              }
179593              break;
179594            }
179595            case 't': case 'T': {
179596              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
179597                token = tkTRIGGER;
179598              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
179599                token = tkTEMP;
179600              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
179601                token = tkTEMP;
179602              }else{
179603                token = tkOTHER;
179604              }
179605              break;
179606            }
179607            case 'e':  case 'E': {
179608              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
179609                token = tkEND;
179610              }else
179611#ifndef SQLITE_OMIT_EXPLAIN
179612              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
179613                token = tkEXPLAIN;
179614              }else
179615#endif
179616              {
179617                token = tkOTHER;
179618              }
179619              break;
179620            }
179621            default: {
179622              token = tkOTHER;
179623              break;
179624            }
179625          }
179626#endif /* SQLITE_OMIT_TRIGGER */
179627          zSql += nId-1;
179628        }else{
179629          /* Operators and special symbols */
179630          token = tkOTHER;
179631        }
179632        break;
179633      }
179634    }
179635    state = trans[state][token];
179636    zSql++;
179637  }
179638  return state==1;
179639}
179640
179641#ifndef SQLITE_OMIT_UTF16
179642/*
179643** This routine is the same as the sqlite3_complete() routine described
179644** above, except that the parameter is required to be UTF-16 encoded, not
179645** UTF-8.
179646*/
179647SQLITE_API int sqlite3_complete16(const void *zSql){
179648  sqlite3_value *pVal;
179649  char const *zSql8;
179650  int rc;
179651
179652#ifndef SQLITE_OMIT_AUTOINIT
179653  rc = sqlite3_initialize();
179654  if( rc ) return rc;
179655#endif
179656  pVal = sqlite3ValueNew(0);
179657  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
179658  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
179659  if( zSql8 ){
179660    rc = sqlite3_complete(zSql8);
179661  }else{
179662    rc = SQLITE_NOMEM_BKPT;
179663  }
179664  sqlite3ValueFree(pVal);
179665  return rc & 0xff;
179666}
179667#endif /* SQLITE_OMIT_UTF16 */
179668#endif /* SQLITE_OMIT_COMPLETE */
179669
179670/************** End of complete.c ********************************************/
179671/************** Begin file main.c ********************************************/
179672/*
179673** 2001 September 15
179674**
179675** The author disclaims copyright to this source code.  In place of
179676** a legal notice, here is a blessing:
179677**
179678**    May you do good and not evil.
179679**    May you find forgiveness for yourself and forgive others.
179680**    May you share freely, never taking more than you give.
179681**
179682*************************************************************************
179683** Main file for the SQLite library.  The routines in this file
179684** implement the programmer interface to the library.  Routines in
179685** other files are for internal use by SQLite and should not be
179686** accessed by users of the library.
179687*/
179688/* #include "sqliteInt.h" */
179689
179690#ifdef SQLITE_ENABLE_FTS3
179691/************** Include fts3.h in the middle of main.c ***********************/
179692/************** Begin file fts3.h ********************************************/
179693/*
179694** 2006 Oct 10
179695**
179696** The author disclaims copyright to this source code.  In place of
179697** a legal notice, here is a blessing:
179698**
179699**    May you do good and not evil.
179700**    May you find forgiveness for yourself and forgive others.
179701**    May you share freely, never taking more than you give.
179702**
179703******************************************************************************
179704**
179705** This header file is used by programs that want to link against the
179706** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
179707*/
179708/* #include "sqlite3.h" */
179709
179710#if 0
179711extern "C" {
179712#endif  /* __cplusplus */
179713
179714SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
179715
179716#if 0
179717}  /* extern "C" */
179718#endif  /* __cplusplus */
179719
179720/************** End of fts3.h ************************************************/
179721/************** Continuing where we left off in main.c ***********************/
179722#endif
179723#ifdef SQLITE_ENABLE_RTREE
179724/************** Include rtree.h in the middle of main.c **********************/
179725/************** Begin file rtree.h *******************************************/
179726/*
179727** 2008 May 26
179728**
179729** The author disclaims copyright to this source code.  In place of
179730** a legal notice, here is a blessing:
179731**
179732**    May you do good and not evil.
179733**    May you find forgiveness for yourself and forgive others.
179734**    May you share freely, never taking more than you give.
179735**
179736******************************************************************************
179737**
179738** This header file is used by programs that want to link against the
179739** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
179740*/
179741/* #include "sqlite3.h" */
179742
179743#ifdef SQLITE_OMIT_VIRTUALTABLE
179744# undef SQLITE_ENABLE_RTREE
179745#endif
179746
179747#if 0
179748extern "C" {
179749#endif  /* __cplusplus */
179750
179751SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
179752
179753#if 0
179754}  /* extern "C" */
179755#endif  /* __cplusplus */
179756
179757/************** End of rtree.h ***********************************************/
179758/************** Continuing where we left off in main.c ***********************/
179759#endif
179760#if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
179761/************** Include sqliteicu.h in the middle of main.c ******************/
179762/************** Begin file sqliteicu.h ***************************************/
179763/*
179764** 2008 May 26
179765**
179766** The author disclaims copyright to this source code.  In place of
179767** a legal notice, here is a blessing:
179768**
179769**    May you do good and not evil.
179770**    May you find forgiveness for yourself and forgive others.
179771**    May you share freely, never taking more than you give.
179772**
179773******************************************************************************
179774**
179775** This header file is used by programs that want to link against the
179776** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
179777*/
179778/* #include "sqlite3.h" */
179779
179780#if 0
179781extern "C" {
179782#endif  /* __cplusplus */
179783
179784SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
179785
179786#if 0
179787}  /* extern "C" */
179788#endif  /* __cplusplus */
179789
179790/************** End of sqliteicu.h *******************************************/
179791/************** Continuing where we left off in main.c ***********************/
179792#endif
179793
179794/*
179795** This is an extension initializer that is a no-op and always
179796** succeeds, except that it fails if the fault-simulation is set
179797** to 500.
179798*/
179799static int sqlite3TestExtInit(sqlite3 *db){
179800  (void)db;
179801  return sqlite3FaultSim(500);
179802}
179803
179804
179805/*
179806** Forward declarations of external module initializer functions
179807** for modules that need them.
179808*/
179809#ifdef SQLITE_ENABLE_FTS5
179810SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
179811#endif
179812#ifdef SQLITE_ENABLE_STMTVTAB
179813SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
179814#endif
179815#ifdef SQLITE_EXTRA_AUTOEXT
179816int SQLITE_EXTRA_AUTOEXT(sqlite3*);
179817#endif
179818/*
179819** An array of pointers to extension initializer functions for
179820** built-in extensions.
179821*/
179822static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {
179823#ifdef SQLITE_ENABLE_FTS3
179824  sqlite3Fts3Init,
179825#endif
179826#ifdef SQLITE_ENABLE_FTS5
179827  sqlite3Fts5Init,
179828#endif
179829#if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
179830  sqlite3IcuInit,
179831#endif
179832#ifdef SQLITE_ENABLE_RTREE
179833  sqlite3RtreeInit,
179834#endif
179835#ifdef SQLITE_ENABLE_DBPAGE_VTAB
179836  sqlite3DbpageRegister,
179837#endif
179838#ifdef SQLITE_ENABLE_DBSTAT_VTAB
179839  sqlite3DbstatRegister,
179840#endif
179841  sqlite3TestExtInit,
179842#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
179843  sqlite3JsonTableFunctions,
179844#endif
179845#ifdef SQLITE_ENABLE_STMTVTAB
179846  sqlite3StmtVtabInit,
179847#endif
179848#ifdef SQLITE_ENABLE_BYTECODE_VTAB
179849  sqlite3VdbeBytecodeVtabInit,
179850#endif
179851#ifdef SQLITE_EXTRA_AUTOEXT
179852  SQLITE_EXTRA_AUTOEXT,
179853#endif
179854};
179855
179856#ifndef SQLITE_AMALGAMATION
179857/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
179858** contains the text of SQLITE_VERSION macro.
179859*/
179860SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
179861#endif
179862
179863/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
179864** a pointer to the to the sqlite3_version[] string constant.
179865*/
179866SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
179867
179868/* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
179869** pointer to a string constant whose value is the same as the
179870** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
179871** an edited copy of the amalgamation, then the last four characters of
179872** the hash might be different from SQLITE_SOURCE_ID.
179873*/
179874/* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */
179875
179876/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
179877** returns an integer equal to SQLITE_VERSION_NUMBER.
179878*/
179879SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
179880
179881/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
179882** zero if and only if SQLite was compiled with mutexing code omitted due to
179883** the SQLITE_THREADSAFE compile-time option being set to 0.
179884*/
179885SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
179886
179887/*
179888** When compiling the test fixture or with debugging enabled (on Win32),
179889** this variable being set to non-zero will cause OSTRACE macros to emit
179890** extra diagnostic information.
179891*/
179892#ifdef SQLITE_HAVE_OS_TRACE
179893# ifndef SQLITE_DEBUG_OS_TRACE
179894#   define SQLITE_DEBUG_OS_TRACE 0
179895# endif
179896  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
179897#endif
179898
179899#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
179900/*
179901** If the following function pointer is not NULL and if
179902** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
179903** I/O active are written using this function.  These messages
179904** are intended for debugging activity only.
179905*/
179906SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
179907#endif
179908
179909/*
179910** If the following global variable points to a string which is the
179911** name of a directory, then that directory will be used to store
179912** temporary files.
179913**
179914** See also the "PRAGMA temp_store_directory" SQL command.
179915*/
179916SQLITE_API char *sqlite3_temp_directory = 0;
179917
179918/*
179919** If the following global variable points to a string which is the
179920** name of a directory, then that directory will be used to store
179921** all database files specified with a relative pathname.
179922**
179923** See also the "PRAGMA data_store_directory" SQL command.
179924*/
179925SQLITE_API char *sqlite3_data_directory = 0;
179926
179927/*
179928** Determine whether or not high-precision (long double) floating point
179929** math works correctly on CPU currently running.
179930*/
179931static SQLITE_NOINLINE int hasHighPrecisionDouble(int rc){
179932  if( sizeof(LONGDOUBLE_TYPE)<=8 ){
179933    /* If the size of "long double" is not more than 8, then
179934    ** high-precision math is not possible. */
179935    return 0;
179936  }else{
179937    /* Just because sizeof(long double)>8 does not mean that the underlying
179938    ** hardware actually supports high-precision floating point.  For example,
179939    ** clearing the 0x100 bit in the floating-point control word on Intel
179940    ** processors will make long double work like double, even though long
179941    ** double takes up more space.  The only way to determine if long double
179942    ** actually works is to run an experiment. */
179943    LONGDOUBLE_TYPE a, b, c;
179944    rc++;
179945    a = 1.0+rc*0.1;
179946    b = 1.0e+18+rc*25.0;
179947    c = a+b;
179948    return b!=c;
179949  }
179950}
179951
179952
179953/*
179954** Initialize SQLite.
179955**
179956** This routine must be called to initialize the memory allocation,
179957** VFS, and mutex subsystems prior to doing any serious work with
179958** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
179959** this routine will be called automatically by key routines such as
179960** sqlite3_open().
179961**
179962** This routine is a no-op except on its very first call for the process,
179963** or for the first call after a call to sqlite3_shutdown.
179964**
179965** The first thread to call this routine runs the initialization to
179966** completion.  If subsequent threads call this routine before the first
179967** thread has finished the initialization process, then the subsequent
179968** threads must block until the first thread finishes with the initialization.
179969**
179970** The first thread might call this routine recursively.  Recursive
179971** calls to this routine should not block, of course.  Otherwise the
179972** initialization process would never complete.
179973**
179974** Let X be the first thread to enter this routine.  Let Y be some other
179975** thread.  Then while the initial invocation of this routine by X is
179976** incomplete, it is required that:
179977**
179978**    *  Calls to this routine from Y must block until the outer-most
179979**       call by X completes.
179980**
179981**    *  Recursive calls to this routine from thread X return immediately
179982**       without blocking.
179983*/
179984SQLITE_API int sqlite3_initialize(void){
179985  MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )      /* The main static mutex */
179986  int rc;                                      /* Result code */
179987#ifdef SQLITE_EXTRA_INIT
179988  int bRunExtraInit = 0;                       /* Extra initialization needed */
179989#endif
179990
179991#ifdef SQLITE_OMIT_WSD
179992  rc = sqlite3_wsd_init(4096, 24);
179993  if( rc!=SQLITE_OK ){
179994    return rc;
179995  }
179996#endif
179997
179998  /* If the following assert() fails on some obscure processor/compiler
179999  ** combination, the work-around is to set the correct pointer
180000  ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
180001  assert( SQLITE_PTRSIZE==sizeof(char*) );
180002
180003  /* If SQLite is already completely initialized, then this call
180004  ** to sqlite3_initialize() should be a no-op.  But the initialization
180005  ** must be complete.  So isInit must not be set until the very end
180006  ** of this routine.
180007  */
180008  if( sqlite3GlobalConfig.isInit ){
180009    sqlite3MemoryBarrier();
180010    return SQLITE_OK;
180011  }
180012
180013  /* Make sure the mutex subsystem is initialized.  If unable to
180014  ** initialize the mutex subsystem, return early with the error.
180015  ** If the system is so sick that we are unable to allocate a mutex,
180016  ** there is not much SQLite is going to be able to do.
180017  **
180018  ** The mutex subsystem must take care of serializing its own
180019  ** initialization.
180020  */
180021  rc = sqlite3MutexInit();
180022  if( rc ) return rc;
180023
180024  /* Initialize the malloc() system and the recursive pInitMutex mutex.
180025  ** This operation is protected by the STATIC_MAIN mutex.  Note that
180026  ** MutexAlloc() is called for a static mutex prior to initializing the
180027  ** malloc subsystem - this implies that the allocation of a static
180028  ** mutex must not require support from the malloc subsystem.
180029  */
180030  MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
180031  sqlite3_mutex_enter(pMainMtx);
180032  sqlite3GlobalConfig.isMutexInit = 1;
180033  if( !sqlite3GlobalConfig.isMallocInit ){
180034    rc = sqlite3MallocInit();
180035  }
180036  if( rc==SQLITE_OK ){
180037    sqlite3GlobalConfig.isMallocInit = 1;
180038    if( !sqlite3GlobalConfig.pInitMutex ){
180039      sqlite3GlobalConfig.pInitMutex =
180040           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
180041      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
180042        rc = SQLITE_NOMEM_BKPT;
180043      }
180044    }
180045  }
180046  if( rc==SQLITE_OK ){
180047    sqlite3GlobalConfig.nRefInitMutex++;
180048  }
180049  sqlite3_mutex_leave(pMainMtx);
180050
180051  /* If rc is not SQLITE_OK at this point, then either the malloc
180052  ** subsystem could not be initialized or the system failed to allocate
180053  ** the pInitMutex mutex. Return an error in either case.  */
180054  if( rc!=SQLITE_OK ){
180055    return rc;
180056  }
180057
180058  /* Do the rest of the initialization under the recursive mutex so
180059  ** that we will be able to handle recursive calls into
180060  ** sqlite3_initialize().  The recursive calls normally come through
180061  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
180062  ** recursive calls might also be possible.
180063  **
180064  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
180065  ** to the xInit method, so the xInit method need not be threadsafe.
180066  **
180067  ** The following mutex is what serializes access to the appdef pcache xInit
180068  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
180069  ** call to sqlite3PcacheInitialize().
180070  */
180071  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
180072  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
180073    sqlite3GlobalConfig.inProgress = 1;
180074#ifdef SQLITE_ENABLE_SQLLOG
180075    {
180076      extern void sqlite3_init_sqllog(void);
180077      sqlite3_init_sqllog();
180078    }
180079#endif
180080    memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
180081    sqlite3RegisterBuiltinFunctions();
180082    if( sqlite3GlobalConfig.isPCacheInit==0 ){
180083      rc = sqlite3PcacheInitialize();
180084    }
180085    if( rc==SQLITE_OK ){
180086      sqlite3GlobalConfig.isPCacheInit = 1;
180087      rc = sqlite3OsInit();
180088    }
180089#ifndef SQLITE_OMIT_DESERIALIZE
180090    if( rc==SQLITE_OK ){
180091      rc = sqlite3MemdbInit();
180092    }
180093#endif
180094    if( rc==SQLITE_OK ){
180095      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
180096          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
180097      sqlite3MemoryBarrier();
180098      sqlite3GlobalConfig.isInit = 1;
180099#ifdef SQLITE_EXTRA_INIT
180100      bRunExtraInit = 1;
180101#endif
180102    }
180103    sqlite3GlobalConfig.inProgress = 0;
180104  }
180105  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
180106
180107  /* Go back under the static mutex and clean up the recursive
180108  ** mutex to prevent a resource leak.
180109  */
180110  sqlite3_mutex_enter(pMainMtx);
180111  sqlite3GlobalConfig.nRefInitMutex--;
180112  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
180113    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
180114    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
180115    sqlite3GlobalConfig.pInitMutex = 0;
180116  }
180117  sqlite3_mutex_leave(pMainMtx);
180118
180119  /* The following is just a sanity check to make sure SQLite has
180120  ** been compiled correctly.  It is important to run this code, but
180121  ** we don't want to run it too often and soak up CPU cycles for no
180122  ** reason.  So we run it once during initialization.
180123  */
180124#ifndef NDEBUG
180125#ifndef SQLITE_OMIT_FLOATING_POINT
180126  /* This section of code's only "output" is via assert() statements. */
180127  if( rc==SQLITE_OK ){
180128    u64 x = (((u64)1)<<63)-1;
180129    double y;
180130    assert(sizeof(x)==8);
180131    assert(sizeof(x)==sizeof(y));
180132    memcpy(&y, &x, 8);
180133    assert( sqlite3IsNaN(y) );
180134  }
180135#endif
180136#endif
180137
180138  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
180139  ** compile-time option.
180140  */
180141#ifdef SQLITE_EXTRA_INIT
180142  if( bRunExtraInit ){
180143    int SQLITE_EXTRA_INIT(const char*);
180144    rc = SQLITE_EXTRA_INIT(0);
180145  }
180146#endif
180147
180148  /* Experimentally determine if high-precision floating point is
180149  ** available. */
180150#ifndef SQLITE_OMIT_WSD
180151  sqlite3Config.bUseLongDouble = hasHighPrecisionDouble(rc);
180152#endif
180153
180154  return rc;
180155}
180156
180157/*
180158** Undo the effects of sqlite3_initialize().  Must not be called while
180159** there are outstanding database connections or memory allocations or
180160** while any part of SQLite is otherwise in use in any thread.  This
180161** routine is not threadsafe.  But it is safe to invoke this routine
180162** on when SQLite is already shut down.  If SQLite is already shut down
180163** when this routine is invoked, then this routine is a harmless no-op.
180164*/
180165SQLITE_API int sqlite3_shutdown(void){
180166#ifdef SQLITE_OMIT_WSD
180167  int rc = sqlite3_wsd_init(4096, 24);
180168  if( rc!=SQLITE_OK ){
180169    return rc;
180170  }
180171#endif
180172
180173  if( sqlite3GlobalConfig.isInit ){
180174#ifdef SQLITE_EXTRA_SHUTDOWN
180175    void SQLITE_EXTRA_SHUTDOWN(void);
180176    SQLITE_EXTRA_SHUTDOWN();
180177#endif
180178    sqlite3_os_end();
180179    sqlite3_reset_auto_extension();
180180    sqlite3GlobalConfig.isInit = 0;
180181  }
180182  if( sqlite3GlobalConfig.isPCacheInit ){
180183    sqlite3PcacheShutdown();
180184    sqlite3GlobalConfig.isPCacheInit = 0;
180185  }
180186  if( sqlite3GlobalConfig.isMallocInit ){
180187    sqlite3MallocEnd();
180188    sqlite3GlobalConfig.isMallocInit = 0;
180189
180190#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
180191    /* The heap subsystem has now been shutdown and these values are supposed
180192    ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
180193    ** which would rely on that heap subsystem; therefore, make sure these
180194    ** values cannot refer to heap memory that was just invalidated when the
180195    ** heap subsystem was shutdown.  This is only done if the current call to
180196    ** this function resulted in the heap subsystem actually being shutdown.
180197    */
180198    sqlite3_data_directory = 0;
180199    sqlite3_temp_directory = 0;
180200#endif
180201  }
180202  if( sqlite3GlobalConfig.isMutexInit ){
180203    sqlite3MutexEnd();
180204    sqlite3GlobalConfig.isMutexInit = 0;
180205  }
180206
180207  return SQLITE_OK;
180208}
180209
180210/*
180211** This API allows applications to modify the global configuration of
180212** the SQLite library at run-time.
180213**
180214** This routine should only be called when there are no outstanding
180215** database connections or memory allocations.  This routine is not
180216** threadsafe.  Failure to heed these warnings can lead to unpredictable
180217** behavior.
180218*/
180219SQLITE_API int sqlite3_config(int op, ...){
180220  va_list ap;
180221  int rc = SQLITE_OK;
180222
180223  /* sqlite3_config() normally returns SQLITE_MISUSE if it is invoked while
180224  ** the SQLite library is in use.  Except, a few selected opcodes
180225  ** are allowed.
180226  */
180227  if( sqlite3GlobalConfig.isInit ){
180228    static const u64 mAnytimeConfigOption = 0
180229       | MASKBIT64( SQLITE_CONFIG_LOG )
180230       | MASKBIT64( SQLITE_CONFIG_PCACHE_HDRSZ )
180231    ;
180232    if( op<0 || op>63 || (MASKBIT64(op) & mAnytimeConfigOption)==0 ){
180233      return SQLITE_MISUSE_BKPT;
180234    }
180235    testcase( op==SQLITE_CONFIG_LOG );
180236    testcase( op==SQLITE_CONFIG_PCACHE_HDRSZ );
180237  }
180238
180239  va_start(ap, op);
180240  switch( op ){
180241
180242    /* Mutex configuration options are only available in a threadsafe
180243    ** compile.
180244    */
180245#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
180246    case SQLITE_CONFIG_SINGLETHREAD: {
180247      /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
180248      ** Single-thread. */
180249      sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
180250      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
180251      break;
180252    }
180253#endif
180254#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
180255    case SQLITE_CONFIG_MULTITHREAD: {
180256      /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
180257      ** Multi-thread. */
180258      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
180259      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
180260      break;
180261    }
180262#endif
180263#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
180264    case SQLITE_CONFIG_SERIALIZED: {
180265      /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
180266      ** Serialized. */
180267      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
180268      sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
180269      break;
180270    }
180271#endif
180272#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
180273    case SQLITE_CONFIG_MUTEX: {
180274      /* Specify an alternative mutex implementation */
180275      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
180276      break;
180277    }
180278#endif
180279#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
180280    case SQLITE_CONFIG_GETMUTEX: {
180281      /* Retrieve the current mutex implementation */
180282      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
180283      break;
180284    }
180285#endif
180286
180287    case SQLITE_CONFIG_MALLOC: {
180288      /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
180289      ** single argument which is a pointer to an instance of the
180290      ** sqlite3_mem_methods structure. The argument specifies alternative
180291      ** low-level memory allocation routines to be used in place of the memory
180292      ** allocation routines built into SQLite. */
180293      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
180294      break;
180295    }
180296    case SQLITE_CONFIG_GETMALLOC: {
180297      /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
180298      ** single argument which is a pointer to an instance of the
180299      ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
180300      ** filled with the currently defined memory allocation routines. */
180301      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
180302      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
180303      break;
180304    }
180305    case SQLITE_CONFIG_MEMSTATUS: {
180306      assert( !sqlite3GlobalConfig.isInit );  /* Cannot change at runtime */
180307      /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
180308      ** single argument of type int, interpreted as a boolean, which enables
180309      ** or disables the collection of memory allocation statistics. */
180310      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
180311      break;
180312    }
180313    case SQLITE_CONFIG_SMALL_MALLOC: {
180314      sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
180315      break;
180316    }
180317    case SQLITE_CONFIG_PAGECACHE: {
180318      /* EVIDENCE-OF: R-18761-36601 There are three arguments to
180319      ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
180320      ** the size of each page cache line (sz), and the number of cache lines
180321      ** (N). */
180322      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
180323      sqlite3GlobalConfig.szPage = va_arg(ap, int);
180324      sqlite3GlobalConfig.nPage = va_arg(ap, int);
180325      break;
180326    }
180327    case SQLITE_CONFIG_PCACHE_HDRSZ: {
180328      /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
180329      ** a single parameter which is a pointer to an integer and writes into
180330      ** that integer the number of extra bytes per page required for each page
180331      ** in SQLITE_CONFIG_PAGECACHE. */
180332      *va_arg(ap, int*) =
180333          sqlite3HeaderSizeBtree() +
180334          sqlite3HeaderSizePcache() +
180335          sqlite3HeaderSizePcache1();
180336      break;
180337    }
180338
180339    case SQLITE_CONFIG_PCACHE: {
180340      /* no-op */
180341      break;
180342    }
180343    case SQLITE_CONFIG_GETPCACHE: {
180344      /* now an error */
180345      rc = SQLITE_ERROR;
180346      break;
180347    }
180348
180349    case SQLITE_CONFIG_PCACHE2: {
180350      /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
180351      ** single argument which is a pointer to an sqlite3_pcache_methods2
180352      ** object. This object specifies the interface to a custom page cache
180353      ** implementation. */
180354      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
180355      break;
180356    }
180357    case SQLITE_CONFIG_GETPCACHE2: {
180358      /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
180359      ** single argument which is a pointer to an sqlite3_pcache_methods2
180360      ** object. SQLite copies of the current page cache implementation into
180361      ** that object. */
180362      if( sqlite3GlobalConfig.pcache2.xInit==0 ){
180363        sqlite3PCacheSetDefault();
180364      }
180365      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
180366      break;
180367    }
180368
180369/* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
180370** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
180371** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
180372#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
180373    case SQLITE_CONFIG_HEAP: {
180374      /* EVIDENCE-OF: R-19854-42126 There are three arguments to
180375      ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
180376      ** number of bytes in the memory buffer, and the minimum allocation size.
180377      */
180378      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
180379      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
180380      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
180381
180382      if( sqlite3GlobalConfig.mnReq<1 ){
180383        sqlite3GlobalConfig.mnReq = 1;
180384      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
180385        /* cap min request size at 2^12 */
180386        sqlite3GlobalConfig.mnReq = (1<<12);
180387      }
180388
180389      if( sqlite3GlobalConfig.pHeap==0 ){
180390        /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
180391        ** is NULL, then SQLite reverts to using its default memory allocator
180392        ** (the system malloc() implementation), undoing any prior invocation of
180393        ** SQLITE_CONFIG_MALLOC.
180394        **
180395        ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
180396        ** revert to its default implementation when sqlite3_initialize() is run
180397        */
180398        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
180399      }else{
180400        /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
180401        ** alternative memory allocator is engaged to handle all of SQLites
180402        ** memory allocation needs. */
180403#ifdef SQLITE_ENABLE_MEMSYS3
180404        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
180405#endif
180406#ifdef SQLITE_ENABLE_MEMSYS5
180407        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
180408#endif
180409      }
180410      break;
180411    }
180412#endif
180413
180414    case SQLITE_CONFIG_LOOKASIDE: {
180415      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
180416      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
180417      break;
180418    }
180419
180420    /* Record a pointer to the logger function and its first argument.
180421    ** The default is NULL.  Logging is disabled if the function pointer is
180422    ** NULL.
180423    */
180424    case SQLITE_CONFIG_LOG: {
180425      /* MSVC is picky about pulling func ptrs from va lists.
180426      ** http://support.microsoft.com/kb/47961
180427      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
180428      */
180429      typedef void(*LOGFUNC_t)(void*,int,const char*);
180430      LOGFUNC_t xLog = va_arg(ap, LOGFUNC_t);
180431      void *pLogArg = va_arg(ap, void*);
180432      AtomicStore(&sqlite3GlobalConfig.xLog, xLog);
180433      AtomicStore(&sqlite3GlobalConfig.pLogArg, pLogArg);
180434      break;
180435    }
180436
180437    /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
180438    ** can be changed at start-time using the
180439    ** sqlite3_config(SQLITE_CONFIG_URI,1) or
180440    ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
180441    */
180442    case SQLITE_CONFIG_URI: {
180443      /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
180444      ** argument of type int. If non-zero, then URI handling is globally
180445      ** enabled. If the parameter is zero, then URI handling is globally
180446      ** disabled. */
180447      int bOpenUri = va_arg(ap, int);
180448      AtomicStore(&sqlite3GlobalConfig.bOpenUri, bOpenUri);
180449      break;
180450    }
180451
180452    case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
180453      /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
180454      ** option takes a single integer argument which is interpreted as a
180455      ** boolean in order to enable or disable the use of covering indices for
180456      ** full table scans in the query optimizer. */
180457      sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
180458      break;
180459    }
180460
180461#ifdef SQLITE_ENABLE_SQLLOG
180462    case SQLITE_CONFIG_SQLLOG: {
180463      typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
180464      sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
180465      sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
180466      break;
180467    }
180468#endif
180469
180470    case SQLITE_CONFIG_MMAP_SIZE: {
180471      /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
180472      ** integer (sqlite3_int64) values that are the default mmap size limit
180473      ** (the default setting for PRAGMA mmap_size) and the maximum allowed
180474      ** mmap size limit. */
180475      sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
180476      sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
180477      /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
180478      ** negative, then that argument is changed to its compile-time default.
180479      **
180480      ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
180481      ** silently truncated if necessary so that it does not exceed the
180482      ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
180483      ** compile-time option.
180484      */
180485      if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
180486        mxMmap = SQLITE_MAX_MMAP_SIZE;
180487      }
180488      if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
180489      if( szMmap>mxMmap) szMmap = mxMmap;
180490      sqlite3GlobalConfig.mxMmap = mxMmap;
180491      sqlite3GlobalConfig.szMmap = szMmap;
180492      break;
180493    }
180494
180495#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
180496    case SQLITE_CONFIG_WIN32_HEAPSIZE: {
180497      /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
180498      ** unsigned integer value that specifies the maximum size of the created
180499      ** heap. */
180500      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
180501      break;
180502    }
180503#endif
180504
180505    case SQLITE_CONFIG_PMASZ: {
180506      sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
180507      break;
180508    }
180509
180510    case SQLITE_CONFIG_STMTJRNL_SPILL: {
180511      sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
180512      break;
180513    }
180514
180515#ifdef SQLITE_ENABLE_SORTER_REFERENCES
180516    case SQLITE_CONFIG_SORTERREF_SIZE: {
180517      int iVal = va_arg(ap, int);
180518      if( iVal<0 ){
180519        iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
180520      }
180521      sqlite3GlobalConfig.szSorterRef = (u32)iVal;
180522      break;
180523    }
180524#endif /* SQLITE_ENABLE_SORTER_REFERENCES */
180525
180526#ifndef SQLITE_OMIT_DESERIALIZE
180527    case SQLITE_CONFIG_MEMDB_MAXSIZE: {
180528      sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
180529      break;
180530    }
180531#endif /* SQLITE_OMIT_DESERIALIZE */
180532
180533    case SQLITE_CONFIG_ROWID_IN_VIEW: {
180534      int *pVal = va_arg(ap,int*);
180535#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
180536      if( 0==*pVal ) sqlite3GlobalConfig.mNoVisibleRowid = TF_NoVisibleRowid;
180537      if( 1==*pVal ) sqlite3GlobalConfig.mNoVisibleRowid = 0;
180538      *pVal = (sqlite3GlobalConfig.mNoVisibleRowid==0);
180539#else
180540      *pVal = 0;
180541#endif
180542      break;
180543    }
180544
180545    default: {
180546      rc = SQLITE_ERROR;
180547      break;
180548    }
180549  }
180550  va_end(ap);
180551  return rc;
180552}
180553
180554/*
180555** Set up the lookaside buffers for a database connection.
180556** Return SQLITE_OK on success.
180557** If lookaside is already active, return SQLITE_BUSY.
180558**
180559** The sz parameter is the number of bytes in each lookaside slot.
180560** The cnt parameter is the number of slots.  If pStart is NULL the
180561** space for the lookaside memory is obtained from sqlite3_malloc().
180562** If pStart is not NULL then it is sz*cnt bytes of memory to use for
180563** the lookaside memory.
180564*/
180565static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
180566#ifndef SQLITE_OMIT_LOOKASIDE
180567  void *pStart;
180568  sqlite3_int64 szAlloc = sz*(sqlite3_int64)cnt;
180569  int nBig;   /* Number of full-size slots */
180570  int nSm;    /* Number smaller LOOKASIDE_SMALL-byte slots */
180571
180572  if( sqlite3LookasideUsed(db,0)>0 ){
180573    return SQLITE_BUSY;
180574  }
180575  /* Free any existing lookaside buffer for this handle before
180576  ** allocating a new one so we don't have to have space for
180577  ** both at the same time.
180578  */
180579  if( db->lookaside.bMalloced ){
180580    sqlite3_free(db->lookaside.pStart);
180581  }
180582  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
180583  ** than a pointer to be useful.
180584  */
180585  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
180586  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
180587  if( cnt<0 ) cnt = 0;
180588  if( sz==0 || cnt==0 ){
180589    sz = 0;
180590    pStart = 0;
180591  }else if( pBuf==0 ){
180592    sqlite3BeginBenignMalloc();
180593    pStart = sqlite3Malloc( szAlloc );  /* IMP: R-61949-35727 */
180594    sqlite3EndBenignMalloc();
180595    if( pStart ) szAlloc = sqlite3MallocSize(pStart);
180596  }else{
180597    pStart = pBuf;
180598  }
180599#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
180600  if( sz>=LOOKASIDE_SMALL*3 ){
180601    nBig = szAlloc/(3*LOOKASIDE_SMALL+sz);
180602    nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
180603  }else if( sz>=LOOKASIDE_SMALL*2 ){
180604    nBig = szAlloc/(LOOKASIDE_SMALL+sz);
180605    nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
180606  }else
180607#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
180608  if( sz>0 ){
180609    nBig = szAlloc/sz;
180610    nSm = 0;
180611  }else{
180612    nBig = nSm = 0;
180613  }
180614  db->lookaside.pStart = pStart;
180615  db->lookaside.pInit = 0;
180616  db->lookaside.pFree = 0;
180617  db->lookaside.sz = (u16)sz;
180618  db->lookaside.szTrue = (u16)sz;
180619  if( pStart ){
180620    int i;
180621    LookasideSlot *p;
180622    assert( sz > (int)sizeof(LookasideSlot*) );
180623    p = (LookasideSlot*)pStart;
180624    for(i=0; i<nBig; i++){
180625      p->pNext = db->lookaside.pInit;
180626      db->lookaside.pInit = p;
180627      p = (LookasideSlot*)&((u8*)p)[sz];
180628    }
180629#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
180630    db->lookaside.pSmallInit = 0;
180631    db->lookaside.pSmallFree = 0;
180632    db->lookaside.pMiddle = p;
180633    for(i=0; i<nSm; i++){
180634      p->pNext = db->lookaside.pSmallInit;
180635      db->lookaside.pSmallInit = p;
180636      p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL];
180637    }
180638#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
180639    assert( ((uptr)p)<=szAlloc + (uptr)pStart );
180640    db->lookaside.pEnd = p;
180641    db->lookaside.bDisable = 0;
180642    db->lookaside.bMalloced = pBuf==0 ?1:0;
180643    db->lookaside.nSlot = nBig+nSm;
180644  }else{
180645    db->lookaside.pStart = 0;
180646#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
180647    db->lookaside.pSmallInit = 0;
180648    db->lookaside.pSmallFree = 0;
180649    db->lookaside.pMiddle = 0;
180650#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
180651    db->lookaside.pEnd = 0;
180652    db->lookaside.bDisable = 1;
180653    db->lookaside.sz = 0;
180654    db->lookaside.bMalloced = 0;
180655    db->lookaside.nSlot = 0;
180656  }
180657  db->lookaside.pTrueEnd = db->lookaside.pEnd;
180658  assert( sqlite3LookasideUsed(db,0)==0 );
180659#endif /* SQLITE_OMIT_LOOKASIDE */
180660  return SQLITE_OK;
180661}
180662
180663/*
180664** Return the mutex associated with a database connection.
180665*/
180666SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
180667#ifdef SQLITE_ENABLE_API_ARMOR
180668  if( !sqlite3SafetyCheckOk(db) ){
180669    (void)SQLITE_MISUSE_BKPT;
180670    return 0;
180671  }
180672#endif
180673  return db->mutex;
180674}
180675
180676/*
180677** Free up as much memory as we can from the given database
180678** connection.
180679*/
180680SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
180681  int i;
180682
180683#ifdef SQLITE_ENABLE_API_ARMOR
180684  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
180685#endif
180686  sqlite3_mutex_enter(db->mutex);
180687  sqlite3BtreeEnterAll(db);
180688  for(i=0; i<db->nDb; i++){
180689    Btree *pBt = db->aDb[i].pBt;
180690    if( pBt ){
180691      Pager *pPager = sqlite3BtreePager(pBt);
180692      sqlite3PagerShrink(pPager);
180693    }
180694  }
180695  sqlite3BtreeLeaveAll(db);
180696  sqlite3_mutex_leave(db->mutex);
180697  return SQLITE_OK;
180698}
180699
180700/*
180701** Flush any dirty pages in the pager-cache for any attached database
180702** to disk.
180703*/
180704SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
180705  int i;
180706  int rc = SQLITE_OK;
180707  int bSeenBusy = 0;
180708
180709#ifdef SQLITE_ENABLE_API_ARMOR
180710  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
180711#endif
180712  sqlite3_mutex_enter(db->mutex);
180713  sqlite3BtreeEnterAll(db);
180714  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
180715    Btree *pBt = db->aDb[i].pBt;
180716    if( pBt && sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
180717      Pager *pPager = sqlite3BtreePager(pBt);
180718      rc = sqlite3PagerFlush(pPager);
180719      if( rc==SQLITE_BUSY ){
180720        bSeenBusy = 1;
180721        rc = SQLITE_OK;
180722      }
180723    }
180724  }
180725  sqlite3BtreeLeaveAll(db);
180726  sqlite3_mutex_leave(db->mutex);
180727  return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
180728}
180729
180730/*
180731** Configuration settings for an individual database connection
180732*/
180733SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
180734  va_list ap;
180735  int rc;
180736
180737#ifdef SQLITE_ENABLE_API_ARMOR
180738  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
180739#endif
180740  sqlite3_mutex_enter(db->mutex);
180741  va_start(ap, op);
180742  switch( op ){
180743    case SQLITE_DBCONFIG_MAINDBNAME: {
180744      /* IMP: R-06824-28531 */
180745      /* IMP: R-36257-52125 */
180746      db->aDb[0].zDbSName = va_arg(ap,char*);
180747      rc = SQLITE_OK;
180748      break;
180749    }
180750    case SQLITE_DBCONFIG_LOOKASIDE: {
180751      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
180752      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
180753      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
180754      rc = setupLookaside(db, pBuf, sz, cnt);
180755      break;
180756    }
180757    default: {
180758      static const struct {
180759        int op;      /* The opcode */
180760        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
180761      } aFlagOp[] = {
180762        { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
180763        { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
180764        { SQLITE_DBCONFIG_ENABLE_VIEW,           SQLITE_EnableView     },
180765        { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
180766        { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
180767        { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,      SQLITE_NoCkptOnClose  },
180768        { SQLITE_DBCONFIG_ENABLE_QPSG,           SQLITE_EnableQPSG     },
180769        { SQLITE_DBCONFIG_TRIGGER_EQP,           SQLITE_TriggerEQP     },
180770        { SQLITE_DBCONFIG_RESET_DATABASE,        SQLITE_ResetDatabase  },
180771        { SQLITE_DBCONFIG_DEFENSIVE,             SQLITE_Defensive      },
180772        { SQLITE_DBCONFIG_WRITABLE_SCHEMA,       SQLITE_WriteSchema|
180773                                                 SQLITE_NoSchemaError  },
180774        { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE,    SQLITE_LegacyAlter    },
180775        { SQLITE_DBCONFIG_DQS_DDL,               SQLITE_DqsDDL         },
180776        { SQLITE_DBCONFIG_DQS_DML,               SQLITE_DqsDML         },
180777        { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT,    SQLITE_LegacyFileFmt  },
180778        { SQLITE_DBCONFIG_TRUSTED_SCHEMA,        SQLITE_TrustedSchema  },
180779        { SQLITE_DBCONFIG_STMT_SCANSTATUS,       SQLITE_StmtScanStatus },
180780        { SQLITE_DBCONFIG_REVERSE_SCANORDER,     SQLITE_ReverseOrder   },
180781      };
180782      unsigned int i;
180783      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
180784      for(i=0; i<ArraySize(aFlagOp); i++){
180785        if( aFlagOp[i].op==op ){
180786          int onoff = va_arg(ap, int);
180787          int *pRes = va_arg(ap, int*);
180788          u64 oldFlags = db->flags;
180789          if( onoff>0 ){
180790            db->flags |= aFlagOp[i].mask;
180791          }else if( onoff==0 ){
180792            db->flags &= ~(u64)aFlagOp[i].mask;
180793          }
180794          if( oldFlags!=db->flags ){
180795            sqlite3ExpirePreparedStatements(db, 0);
180796          }
180797          if( pRes ){
180798            *pRes = (db->flags & aFlagOp[i].mask)!=0;
180799          }
180800          rc = SQLITE_OK;
180801          break;
180802        }
180803      }
180804      break;
180805    }
180806  }
180807  va_end(ap);
180808  sqlite3_mutex_leave(db->mutex);
180809  return rc;
180810}
180811
180812/*
180813** This is the default collating function named "BINARY" which is always
180814** available.
180815*/
180816static int binCollFunc(
180817  void *NotUsed,
180818  int nKey1, const void *pKey1,
180819  int nKey2, const void *pKey2
180820){
180821  int rc, n;
180822  UNUSED_PARAMETER(NotUsed);
180823  n = nKey1<nKey2 ? nKey1 : nKey2;
180824  /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
180825  ** strings byte by byte using the memcmp() function from the standard C
180826  ** library. */
180827  assert( pKey1 && pKey2 );
180828  rc = memcmp(pKey1, pKey2, n);
180829  if( rc==0 ){
180830    rc = nKey1 - nKey2;
180831  }
180832  return rc;
180833}
180834
180835/*
180836** This is the collating function named "RTRIM" which is always
180837** available.  Ignore trailing spaces.
180838*/
180839static int rtrimCollFunc(
180840  void *pUser,
180841  int nKey1, const void *pKey1,
180842  int nKey2, const void *pKey2
180843){
180844  const u8 *pK1 = (const u8*)pKey1;
180845  const u8 *pK2 = (const u8*)pKey2;
180846  while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--;
180847  while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--;
180848  return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2);
180849}
180850
180851/*
180852** Return true if CollSeq is the default built-in BINARY.
180853*/
180854SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq *p){
180855  assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 );
180856  return p==0 || p->xCmp==binCollFunc;
180857}
180858
180859/*
180860** Another built-in collating sequence: NOCASE.
180861**
180862** This collating sequence is intended to be used for "case independent
180863** comparison". SQLite's knowledge of upper and lower case equivalents
180864** extends only to the 26 characters used in the English language.
180865**
180866** At the moment there is only a UTF-8 implementation.
180867*/
180868static int nocaseCollatingFunc(
180869  void *NotUsed,
180870  int nKey1, const void *pKey1,
180871  int nKey2, const void *pKey2
180872){
180873  int r = sqlite3StrNICmp(
180874      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
180875  UNUSED_PARAMETER(NotUsed);
180876  if( 0==r ){
180877    r = nKey1-nKey2;
180878  }
180879  return r;
180880}
180881
180882/*
180883** Return the ROWID of the most recent insert
180884*/
180885SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
180886#ifdef SQLITE_ENABLE_API_ARMOR
180887  if( !sqlite3SafetyCheckOk(db) ){
180888    (void)SQLITE_MISUSE_BKPT;
180889    return 0;
180890  }
180891#endif
180892  return db->lastRowid;
180893}
180894
180895/*
180896** Set the value returned by the sqlite3_last_insert_rowid() API function.
180897*/
180898SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
180899#ifdef SQLITE_ENABLE_API_ARMOR
180900  if( !sqlite3SafetyCheckOk(db) ){
180901    (void)SQLITE_MISUSE_BKPT;
180902    return;
180903  }
180904#endif
180905  sqlite3_mutex_enter(db->mutex);
180906  db->lastRowid = iRowid;
180907  sqlite3_mutex_leave(db->mutex);
180908}
180909
180910/*
180911** Return the number of changes in the most recent call to sqlite3_exec().
180912*/
180913SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3 *db){
180914#ifdef SQLITE_ENABLE_API_ARMOR
180915  if( !sqlite3SafetyCheckOk(db) ){
180916    (void)SQLITE_MISUSE_BKPT;
180917    return 0;
180918  }
180919#endif
180920  return db->nChange;
180921}
180922SQLITE_API int sqlite3_changes(sqlite3 *db){
180923  return (int)sqlite3_changes64(db);
180924}
180925
180926/*
180927** Return the number of changes since the database handle was opened.
180928*/
180929SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3 *db){
180930#ifdef SQLITE_ENABLE_API_ARMOR
180931  if( !sqlite3SafetyCheckOk(db) ){
180932    (void)SQLITE_MISUSE_BKPT;
180933    return 0;
180934  }
180935#endif
180936  return db->nTotalChange;
180937}
180938SQLITE_API int sqlite3_total_changes(sqlite3 *db){
180939  return (int)sqlite3_total_changes64(db);
180940}
180941
180942/*
180943** Close all open savepoints. This function only manipulates fields of the
180944** database handle object, it does not close any savepoints that may be open
180945** at the b-tree/pager level.
180946*/
180947SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
180948  while( db->pSavepoint ){
180949    Savepoint *pTmp = db->pSavepoint;
180950    db->pSavepoint = pTmp->pNext;
180951    sqlite3DbFree(db, pTmp);
180952  }
180953  db->nSavepoint = 0;
180954  db->nStatement = 0;
180955  db->isTransactionSavepoint = 0;
180956}
180957
180958/*
180959** Invoke the destructor function associated with FuncDef p, if any. Except,
180960** if this is not the last copy of the function, do not invoke it. Multiple
180961** copies of a single function are created when create_function() is called
180962** with SQLITE_ANY as the encoding.
180963*/
180964static void functionDestroy(sqlite3 *db, FuncDef *p){
180965  FuncDestructor *pDestructor;
180966  assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
180967  pDestructor = p->u.pDestructor;
180968  if( pDestructor ){
180969    pDestructor->nRef--;
180970    if( pDestructor->nRef==0 ){
180971      pDestructor->xDestroy(pDestructor->pUserData);
180972      sqlite3DbFree(db, pDestructor);
180973    }
180974  }
180975}
180976
180977/*
180978** Disconnect all sqlite3_vtab objects that belong to database connection
180979** db. This is called when db is being closed.
180980*/
180981static void disconnectAllVtab(sqlite3 *db){
180982#ifndef SQLITE_OMIT_VIRTUALTABLE
180983  int i;
180984  HashElem *p;
180985  sqlite3BtreeEnterAll(db);
180986  for(i=0; i<db->nDb; i++){
180987    Schema *pSchema = db->aDb[i].pSchema;
180988    if( pSchema ){
180989      for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
180990        Table *pTab = (Table *)sqliteHashData(p);
180991        if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
180992      }
180993    }
180994  }
180995  for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
180996    Module *pMod = (Module *)sqliteHashData(p);
180997    if( pMod->pEpoTab ){
180998      sqlite3VtabDisconnect(db, pMod->pEpoTab);
180999    }
181000  }
181001  sqlite3VtabUnlockList(db);
181002  sqlite3BtreeLeaveAll(db);
181003#else
181004  UNUSED_PARAMETER(db);
181005#endif
181006}
181007
181008/*
181009** Return TRUE if database connection db has unfinalized prepared
181010** statements or unfinished sqlite3_backup objects.
181011*/
181012static int connectionIsBusy(sqlite3 *db){
181013  int j;
181014  assert( sqlite3_mutex_held(db->mutex) );
181015  if( db->pVdbe ) return 1;
181016  for(j=0; j<db->nDb; j++){
181017    Btree *pBt = db->aDb[j].pBt;
181018    if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
181019  }
181020  return 0;
181021}
181022
181023/*
181024** Close an existing SQLite database
181025*/
181026static int sqlite3Close(sqlite3 *db, int forceZombie){
181027  if( !db ){
181028    /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
181029    ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
181030    return SQLITE_OK;
181031  }
181032  if( !sqlite3SafetyCheckSickOrOk(db) ){
181033    return SQLITE_MISUSE_BKPT;
181034  }
181035  sqlite3_mutex_enter(db->mutex);
181036  if( db->mTrace & SQLITE_TRACE_CLOSE ){
181037    db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
181038  }
181039
181040  /* Force xDisconnect calls on all virtual tables */
181041  disconnectAllVtab(db);
181042
181043  /* If a transaction is open, the disconnectAllVtab() call above
181044  ** will not have called the xDisconnect() method on any virtual
181045  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
181046  ** call will do so. We need to do this before the check for active
181047  ** SQL statements below, as the v-table implementation may be storing
181048  ** some prepared statements internally.
181049  */
181050  sqlite3VtabRollback(db);
181051
181052  /* Legacy behavior (sqlite3_close() behavior) is to return
181053  ** SQLITE_BUSY if the connection can not be closed immediately.
181054  */
181055  if( !forceZombie && connectionIsBusy(db) ){
181056    sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
181057       "statements or unfinished backups");
181058    sqlite3_mutex_leave(db->mutex);
181059    return SQLITE_BUSY;
181060  }
181061
181062#ifdef SQLITE_ENABLE_SQLLOG
181063  if( sqlite3GlobalConfig.xSqllog ){
181064    /* Closing the handle. Fourth parameter is passed the value 2. */
181065    sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
181066  }
181067#endif
181068
181069  while( db->pDbData ){
181070    DbClientData *p = db->pDbData;
181071    db->pDbData = p->pNext;
181072    assert( p->pData!=0 );
181073    if( p->xDestructor ) p->xDestructor(p->pData);
181074    sqlite3_free(p);
181075  }
181076
181077  /* Convert the connection into a zombie and then close it.
181078  */
181079  db->eOpenState = SQLITE_STATE_ZOMBIE;
181080  sqlite3LeaveMutexAndCloseZombie(db);
181081  return SQLITE_OK;
181082}
181083
181084/*
181085** Return the transaction state for a single databse, or the maximum
181086** transaction state over all attached databases if zSchema is null.
181087*/
181088SQLITE_API int sqlite3_txn_state(sqlite3 *db, const char *zSchema){
181089  int iDb, nDb;
181090  int iTxn = -1;
181091#ifdef SQLITE_ENABLE_API_ARMOR
181092  if( !sqlite3SafetyCheckOk(db) ){
181093    (void)SQLITE_MISUSE_BKPT;
181094    return -1;
181095  }
181096#endif
181097  sqlite3_mutex_enter(db->mutex);
181098  if( zSchema ){
181099    nDb = iDb = sqlite3FindDbName(db, zSchema);
181100    if( iDb<0 ) nDb--;
181101  }else{
181102    iDb = 0;
181103    nDb = db->nDb-1;
181104  }
181105  for(; iDb<=nDb; iDb++){
181106    Btree *pBt = db->aDb[iDb].pBt;
181107    int x = pBt!=0 ? sqlite3BtreeTxnState(pBt) : SQLITE_TXN_NONE;
181108    if( x>iTxn ) iTxn = x;
181109  }
181110  sqlite3_mutex_leave(db->mutex);
181111  return iTxn;
181112}
181113
181114/*
181115** Two variations on the public interface for closing a database
181116** connection. The sqlite3_close() version returns SQLITE_BUSY and
181117** leaves the connection open if there are unfinalized prepared
181118** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
181119** version forces the connection to become a zombie if there are
181120** unclosed resources, and arranges for deallocation when the last
181121** prepare statement or sqlite3_backup closes.
181122*/
181123SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
181124SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
181125
181126
181127/*
181128** Close the mutex on database connection db.
181129**
181130** Furthermore, if database connection db is a zombie (meaning that there
181131** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
181132** every sqlite3_stmt has now been finalized and every sqlite3_backup has
181133** finished, then free all resources.
181134*/
181135SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
181136  HashElem *i;                    /* Hash table iterator */
181137  int j;
181138
181139  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
181140  ** or if the connection has not yet been closed by sqlite3_close_v2(),
181141  ** then just leave the mutex and return.
181142  */
181143  if( db->eOpenState!=SQLITE_STATE_ZOMBIE || connectionIsBusy(db) ){
181144    sqlite3_mutex_leave(db->mutex);
181145    return;
181146  }
181147
181148  /* If we reach this point, it means that the database connection has
181149  ** closed all sqlite3_stmt and sqlite3_backup objects and has been
181150  ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
181151  ** go ahead and free all resources.
181152  */
181153
181154  /* If a transaction is open, roll it back. This also ensures that if
181155  ** any database schemas have been modified by an uncommitted transaction
181156  ** they are reset. And that the required b-tree mutex is held to make
181157  ** the pager rollback and schema reset an atomic operation. */
181158  sqlite3RollbackAll(db, SQLITE_OK);
181159
181160  /* Free any outstanding Savepoint structures. */
181161  sqlite3CloseSavepoints(db);
181162
181163  /* Close all database connections */
181164  for(j=0; j<db->nDb; j++){
181165    struct Db *pDb = &db->aDb[j];
181166    if( pDb->pBt ){
181167      sqlite3BtreeClose(pDb->pBt);
181168      pDb->pBt = 0;
181169      if( j!=1 ){
181170        pDb->pSchema = 0;
181171      }
181172    }
181173  }
181174  /* Clear the TEMP schema separately and last */
181175  if( db->aDb[1].pSchema ){
181176    sqlite3SchemaClear(db->aDb[1].pSchema);
181177  }
181178  sqlite3VtabUnlockList(db);
181179
181180  /* Free up the array of auxiliary databases */
181181  sqlite3CollapseDatabaseArray(db);
181182  assert( db->nDb<=2 );
181183  assert( db->aDb==db->aDbStatic );
181184
181185  /* Tell the code in notify.c that the connection no longer holds any
181186  ** locks and does not require any further unlock-notify callbacks.
181187  */
181188  sqlite3ConnectionClosed(db);
181189
181190  for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
181191    FuncDef *pNext, *p;
181192    p = sqliteHashData(i);
181193    do{
181194      functionDestroy(db, p);
181195      pNext = p->pNext;
181196      sqlite3DbFree(db, p);
181197      p = pNext;
181198    }while( p );
181199  }
181200  sqlite3HashClear(&db->aFunc);
181201  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
181202    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
181203    /* Invoke any destructors registered for collation sequence user data. */
181204    for(j=0; j<3; j++){
181205      if( pColl[j].xDel ){
181206        pColl[j].xDel(pColl[j].pUser);
181207      }
181208    }
181209    sqlite3DbFree(db, pColl);
181210  }
181211  sqlite3HashClear(&db->aCollSeq);
181212#ifndef SQLITE_OMIT_VIRTUALTABLE
181213  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
181214    Module *pMod = (Module *)sqliteHashData(i);
181215    sqlite3VtabEponymousTableClear(db, pMod);
181216    sqlite3VtabModuleUnref(db, pMod);
181217  }
181218  sqlite3HashClear(&db->aModule);
181219#endif
181220
181221  sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
181222  sqlite3ValueFree(db->pErr);
181223  sqlite3CloseExtensions(db);
181224#if SQLITE_USER_AUTHENTICATION
181225  sqlite3_free(db->auth.zAuthUser);
181226  sqlite3_free(db->auth.zAuthPW);
181227#endif
181228
181229  db->eOpenState = SQLITE_STATE_ERROR;
181230
181231  /* The temp-database schema is allocated differently from the other schema
181232  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
181233  ** So it needs to be freed here. Todo: Why not roll the temp schema into
181234  ** the same sqliteMalloc() as the one that allocates the database
181235  ** structure?
181236  */
181237  sqlite3DbFree(db, db->aDb[1].pSchema);
181238  if( db->xAutovacDestr ){
181239    db->xAutovacDestr(db->pAutovacPagesArg);
181240  }
181241  sqlite3_mutex_leave(db->mutex);
181242  db->eOpenState = SQLITE_STATE_CLOSED;
181243  sqlite3_mutex_free(db->mutex);
181244  assert( sqlite3LookasideUsed(db,0)==0 );
181245  if( db->lookaside.bMalloced ){
181246    sqlite3_free(db->lookaside.pStart);
181247  }
181248  sqlite3_free(db);
181249}
181250
181251/*
181252** Rollback all database files.  If tripCode is not SQLITE_OK, then
181253** any write cursors are invalidated ("tripped" - as in "tripping a circuit
181254** breaker") and made to return tripCode if there are any further
181255** attempts to use that cursor.  Read cursors remain open and valid
181256** but are "saved" in case the table pages are moved around.
181257*/
181258SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
181259  int i;
181260  int inTrans = 0;
181261  int schemaChange;
181262  assert( sqlite3_mutex_held(db->mutex) );
181263  sqlite3BeginBenignMalloc();
181264
181265  /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
181266  ** This is important in case the transaction being rolled back has
181267  ** modified the database schema. If the b-tree mutexes are not taken
181268  ** here, then another shared-cache connection might sneak in between
181269  ** the database rollback and schema reset, which can cause false
181270  ** corruption reports in some cases.  */
181271  sqlite3BtreeEnterAll(db);
181272  schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
181273
181274  for(i=0; i<db->nDb; i++){
181275    Btree *p = db->aDb[i].pBt;
181276    if( p ){
181277      if( sqlite3BtreeTxnState(p)==SQLITE_TXN_WRITE ){
181278        inTrans = 1;
181279      }
181280      sqlite3BtreeRollback(p, tripCode, !schemaChange);
181281    }
181282  }
181283  sqlite3VtabRollback(db);
181284  sqlite3EndBenignMalloc();
181285
181286  if( schemaChange ){
181287    sqlite3ExpirePreparedStatements(db, 0);
181288    sqlite3ResetAllSchemasOfConnection(db);
181289  }
181290  sqlite3BtreeLeaveAll(db);
181291
181292  /* Any deferred constraint violations have now been resolved. */
181293  db->nDeferredCons = 0;
181294  db->nDeferredImmCons = 0;
181295  db->flags &= ~(u64)(SQLITE_DeferFKs|SQLITE_CorruptRdOnly);
181296
181297  /* If one has been configured, invoke the rollback-hook callback */
181298  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
181299    db->xRollbackCallback(db->pRollbackArg);
181300  }
181301}
181302
181303/*
181304** Return a static string containing the name corresponding to the error code
181305** specified in the argument.
181306*/
181307#if defined(SQLITE_NEED_ERR_NAME)
181308SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
181309  const char *zName = 0;
181310  int i, origRc = rc;
181311  for(i=0; i<2 && zName==0; i++, rc &= 0xff){
181312    switch( rc ){
181313      case SQLITE_OK:                 zName = "SQLITE_OK";                break;
181314      case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
181315      case SQLITE_ERROR_SNAPSHOT:     zName = "SQLITE_ERROR_SNAPSHOT";    break;
181316      case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
181317      case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
181318      case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
181319      case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
181320      case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
181321      case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
181322      case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
181323      case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
181324      case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
181325      case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
181326      case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
181327      case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
181328      case SQLITE_READONLY_CANTINIT:  zName = "SQLITE_READONLY_CANTINIT"; break;
181329      case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
181330      case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
181331      case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
181332      case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
181333      case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
181334      case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
181335      case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
181336      case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
181337      case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
181338      case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
181339      case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
181340      case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
181341      case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
181342      case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
181343      case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
181344      case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
181345      case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
181346      case SQLITE_IOERR_CHECKRESERVEDLOCK:
181347                                zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
181348      case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
181349      case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
181350      case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
181351      case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
181352      case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
181353      case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
181354      case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
181355      case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
181356      case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
181357      case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
181358      case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
181359      case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
181360      case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
181361      case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
181362      case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
181363      case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
181364      case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
181365      case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
181366      case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
181367      case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
181368      case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
181369      case SQLITE_CANTOPEN_SYMLINK:   zName = "SQLITE_CANTOPEN_SYMLINK";  break;
181370      case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
181371      case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
181372      case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
181373      case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
181374      case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
181375      case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
181376      case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
181377      case SQLITE_CONSTRAINT_FOREIGNKEY:
181378                                zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
181379      case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
181380      case SQLITE_CONSTRAINT_PRIMARYKEY:
181381                                zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
181382      case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
181383      case SQLITE_CONSTRAINT_COMMITHOOK:
181384                                zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
181385      case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
181386      case SQLITE_CONSTRAINT_FUNCTION:
181387                                zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
181388      case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
181389      case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
181390      case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
181391      case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
181392      case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
181393      case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
181394      case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
181395      case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
181396      case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
181397      case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
181398      case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
181399      case SQLITE_NOTICE_RECOVER_ROLLBACK:
181400                                zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
181401      case SQLITE_NOTICE_RBU:         zName = "SQLITE_NOTICE_RBU"; break;
181402      case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
181403      case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
181404      case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
181405    }
181406  }
181407  if( zName==0 ){
181408    static char zBuf[50];
181409    sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
181410    zName = zBuf;
181411  }
181412  return zName;
181413}
181414#endif
181415
181416/*
181417** Return a static string that describes the kind of error specified in the
181418** argument.
181419*/
181420SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
181421  static const char* const aMsg[] = {
181422    /* SQLITE_OK          */ "not an error",
181423    /* SQLITE_ERROR       */ "SQL logic error",
181424    /* SQLITE_INTERNAL    */ 0,
181425    /* SQLITE_PERM        */ "access permission denied",
181426    /* SQLITE_ABORT       */ "query aborted",
181427    /* SQLITE_BUSY        */ "database is locked",
181428    /* SQLITE_LOCKED      */ "database table is locked",
181429    /* SQLITE_NOMEM       */ "out of memory",
181430    /* SQLITE_READONLY    */ "attempt to write a readonly database",
181431    /* SQLITE_INTERRUPT   */ "interrupted",
181432    /* SQLITE_IOERR       */ "disk I/O error",
181433    /* SQLITE_CORRUPT     */ "database disk image is malformed",
181434    /* SQLITE_NOTFOUND    */ "unknown operation",
181435    /* SQLITE_FULL        */ "database or disk is full",
181436    /* SQLITE_CANTOPEN    */ "unable to open database file",
181437    /* SQLITE_PROTOCOL    */ "locking protocol",
181438    /* SQLITE_EMPTY       */ 0,
181439    /* SQLITE_SCHEMA      */ "database schema has changed",
181440    /* SQLITE_TOOBIG      */ "string or blob too big",
181441    /* SQLITE_CONSTRAINT  */ "constraint failed",
181442    /* SQLITE_MISMATCH    */ "datatype mismatch",
181443    /* SQLITE_MISUSE      */ "bad parameter or other API misuse",
181444#ifdef SQLITE_DISABLE_LFS
181445    /* SQLITE_NOLFS       */ "large file support is disabled",
181446#else
181447    /* SQLITE_NOLFS       */ 0,
181448#endif
181449    /* SQLITE_AUTH        */ "authorization denied",
181450    /* SQLITE_FORMAT      */ 0,
181451    /* SQLITE_RANGE       */ "column index out of range",
181452    /* SQLITE_NOTADB      */ "file is not a database",
181453    /* SQLITE_NOTICE      */ "notification message",
181454    /* SQLITE_WARNING     */ "warning message",
181455  };
181456  const char *zErr = "unknown error";
181457  switch( rc ){
181458    case SQLITE_ABORT_ROLLBACK: {
181459      zErr = "abort due to ROLLBACK";
181460      break;
181461    }
181462    case SQLITE_ROW: {
181463      zErr = "another row available";
181464      break;
181465    }
181466    case SQLITE_DONE: {
181467      zErr = "no more rows available";
181468      break;
181469    }
181470    default: {
181471      rc &= 0xff;
181472      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
181473        zErr = aMsg[rc];
181474      }
181475      break;
181476    }
181477  }
181478  return zErr;
181479}
181480
181481/*
181482** This routine implements a busy callback that sleeps and tries
181483** again until a timeout value is reached.  The timeout value is
181484** an integer number of milliseconds passed in as the first
181485** argument.
181486**
181487** Return non-zero to retry the lock.  Return zero to stop trying
181488** and cause SQLite to return SQLITE_BUSY.
181489*/
181490static int sqliteDefaultBusyCallback(
181491  void *ptr,               /* Database connection */
181492  int count                /* Number of times table has been busy */
181493){
181494#if SQLITE_OS_WIN || !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP
181495  /* This case is for systems that have support for sleeping for fractions of
181496  ** a second.  Examples:  All windows systems, unix systems with nanosleep() */
181497  static const u8 delays[] =
181498     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
181499  static const u8 totals[] =
181500     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
181501# define NDELAY ArraySize(delays)
181502  sqlite3 *db = (sqlite3 *)ptr;
181503  int tmout = db->busyTimeout;
181504  int delay, prior;
181505
181506  assert( count>=0 );
181507  if( count < NDELAY ){
181508    delay = delays[count];
181509    prior = totals[count];
181510  }else{
181511    delay = delays[NDELAY-1];
181512    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
181513  }
181514  if( prior + delay > tmout ){
181515    delay = tmout - prior;
181516    if( delay<=0 ) return 0;
181517  }
181518  sqlite3OsSleep(db->pVfs, delay*1000);
181519  return 1;
181520#else
181521  /* This case for unix systems that lack usleep() support.  Sleeping
181522  ** must be done in increments of whole seconds */
181523  sqlite3 *db = (sqlite3 *)ptr;
181524  int tmout = ((sqlite3 *)ptr)->busyTimeout;
181525  if( (count+1)*1000 > tmout ){
181526    return 0;
181527  }
181528  sqlite3OsSleep(db->pVfs, 1000000);
181529  return 1;
181530#endif
181531}
181532
181533/*
181534** Invoke the given busy handler.
181535**
181536** This routine is called when an operation failed to acquire a
181537** lock on VFS file pFile.
181538**
181539** If this routine returns non-zero, the lock is retried.  If it
181540** returns 0, the operation aborts with an SQLITE_BUSY error.
181541*/
181542SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
181543  int rc;
181544  if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
181545  rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
181546  if( rc==0 ){
181547    p->nBusy = -1;
181548  }else{
181549    p->nBusy++;
181550  }
181551  return rc;
181552}
181553
181554/*
181555** This routine sets the busy callback for an Sqlite database to the
181556** given callback function with the given argument.
181557*/
181558SQLITE_API int sqlite3_busy_handler(
181559  sqlite3 *db,
181560  int (*xBusy)(void*,int),
181561  void *pArg
181562){
181563#ifdef SQLITE_ENABLE_API_ARMOR
181564  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
181565#endif
181566  sqlite3_mutex_enter(db->mutex);
181567  db->busyHandler.xBusyHandler = xBusy;
181568  db->busyHandler.pBusyArg = pArg;
181569  db->busyHandler.nBusy = 0;
181570  db->busyTimeout = 0;
181571  sqlite3_mutex_leave(db->mutex);
181572  return SQLITE_OK;
181573}
181574
181575#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
181576/*
181577** This routine sets the progress callback for an Sqlite database to the
181578** given callback function with the given argument. The progress callback will
181579** be invoked every nOps opcodes.
181580*/
181581SQLITE_API void sqlite3_progress_handler(
181582  sqlite3 *db,
181583  int nOps,
181584  int (*xProgress)(void*),
181585  void *pArg
181586){
181587#ifdef SQLITE_ENABLE_API_ARMOR
181588  if( !sqlite3SafetyCheckOk(db) ){
181589    (void)SQLITE_MISUSE_BKPT;
181590    return;
181591  }
181592#endif
181593  sqlite3_mutex_enter(db->mutex);
181594  if( nOps>0 ){
181595    db->xProgress = xProgress;
181596    db->nProgressOps = (unsigned)nOps;
181597    db->pProgressArg = pArg;
181598  }else{
181599    db->xProgress = 0;
181600    db->nProgressOps = 0;
181601    db->pProgressArg = 0;
181602  }
181603  sqlite3_mutex_leave(db->mutex);
181604}
181605#endif
181606
181607
181608/*
181609** This routine installs a default busy handler that waits for the
181610** specified number of milliseconds before returning 0.
181611*/
181612SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
181613#ifdef SQLITE_ENABLE_API_ARMOR
181614  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
181615#endif
181616  if( ms>0 ){
181617    sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
181618                             (void*)db);
181619    db->busyTimeout = ms;
181620  }else{
181621    sqlite3_busy_handler(db, 0, 0);
181622  }
181623  return SQLITE_OK;
181624}
181625
181626/*
181627** Cause any pending operation to stop at its earliest opportunity.
181628*/
181629SQLITE_API void sqlite3_interrupt(sqlite3 *db){
181630#ifdef SQLITE_ENABLE_API_ARMOR
181631  if( !sqlite3SafetyCheckOk(db)
181632   && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE)
181633  ){
181634    (void)SQLITE_MISUSE_BKPT;
181635    return;
181636  }
181637#endif
181638  AtomicStore(&db->u1.isInterrupted, 1);
181639}
181640
181641/*
181642** Return true or false depending on whether or not an interrupt is
181643** pending on connection db.
181644*/
181645SQLITE_API int sqlite3_is_interrupted(sqlite3 *db){
181646#ifdef SQLITE_ENABLE_API_ARMOR
181647  if( !sqlite3SafetyCheckOk(db)
181648   && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE)
181649  ){
181650    (void)SQLITE_MISUSE_BKPT;
181651    return 0;
181652  }
181653#endif
181654  return AtomicLoad(&db->u1.isInterrupted)!=0;
181655}
181656
181657/*
181658** This function is exactly the same as sqlite3_create_function(), except
181659** that it is designed to be called by internal code. The difference is
181660** that if a malloc() fails in sqlite3_create_function(), an error code
181661** is returned and the mallocFailed flag cleared.
181662*/
181663SQLITE_PRIVATE int sqlite3CreateFunc(
181664  sqlite3 *db,
181665  const char *zFunctionName,
181666  int nArg,
181667  int enc,
181668  void *pUserData,
181669  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
181670  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
181671  void (*xFinal)(sqlite3_context*),
181672  void (*xValue)(sqlite3_context*),
181673  void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
181674  FuncDestructor *pDestructor
181675){
181676  FuncDef *p;
181677  int extraFlags;
181678
181679  assert( sqlite3_mutex_held(db->mutex) );
181680  assert( xValue==0 || xSFunc==0 );
181681  if( zFunctionName==0                /* Must have a valid name */
181682   || (xSFunc!=0 && xFinal!=0)        /* Not both xSFunc and xFinal */
181683   || ((xFinal==0)!=(xStep==0))       /* Both or neither of xFinal and xStep */
181684   || ((xValue==0)!=(xInverse==0))    /* Both or neither of xValue, xInverse */
181685   || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
181686   || (255<sqlite3Strlen30(zFunctionName))
181687  ){
181688    return SQLITE_MISUSE_BKPT;
181689  }
181690
181691  assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
181692  assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY );
181693  extraFlags = enc &  (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|
181694                       SQLITE_SUBTYPE|SQLITE_INNOCUOUS|SQLITE_RESULT_SUBTYPE);
181695  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
181696
181697  /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE.  But
181698  ** the meaning is inverted.  So flip the bit. */
181699  assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS );
181700  extraFlags ^= SQLITE_FUNC_UNSAFE;  /* tag-20230109-1 */
181701
181702
181703#ifndef SQLITE_OMIT_UTF16
181704  /* If SQLITE_UTF16 is specified as the encoding type, transform this
181705  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
181706  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
181707  **
181708  ** If SQLITE_ANY is specified, add three versions of the function
181709  ** to the hash table.
181710  */
181711  switch( enc ){
181712    case SQLITE_UTF16:
181713      enc = SQLITE_UTF16NATIVE;
181714      break;
181715    case SQLITE_ANY: {
181716      int rc;
181717      rc = sqlite3CreateFunc(db, zFunctionName, nArg,
181718           (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE, /* tag-20230109-1 */
181719           pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
181720      if( rc==SQLITE_OK ){
181721        rc = sqlite3CreateFunc(db, zFunctionName, nArg,
181722             (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE, /* tag-20230109-1*/
181723             pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
181724      }
181725      if( rc!=SQLITE_OK ){
181726        return rc;
181727      }
181728      enc = SQLITE_UTF16BE;
181729      break;
181730    }
181731    case SQLITE_UTF8:
181732    case SQLITE_UTF16LE:
181733    case SQLITE_UTF16BE:
181734      break;
181735    default:
181736      enc = SQLITE_UTF8;
181737      break;
181738  }
181739#else
181740  enc = SQLITE_UTF8;
181741#endif
181742
181743  /* Check if an existing function is being overridden or deleted. If so,
181744  ** and there are active VMs, then return SQLITE_BUSY. If a function
181745  ** is being overridden/deleted but there are no active VMs, allow the
181746  ** operation to continue but invalidate all precompiled statements.
181747  */
181748  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
181749  if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
181750    if( db->nVdbeActive ){
181751      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
181752        "unable to delete/modify user-function due to active statements");
181753      assert( !db->mallocFailed );
181754      return SQLITE_BUSY;
181755    }else{
181756      sqlite3ExpirePreparedStatements(db, 0);
181757    }
181758  }else if( xSFunc==0 && xFinal==0 ){
181759    /* Trying to delete a function that does not exist.  This is a no-op.
181760    ** https://sqlite.org/forum/forumpost/726219164b */
181761    return SQLITE_OK;
181762  }
181763
181764  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
181765  assert(p || db->mallocFailed);
181766  if( !p ){
181767    return SQLITE_NOMEM_BKPT;
181768  }
181769
181770  /* If an older version of the function with a configured destructor is
181771  ** being replaced invoke the destructor function here. */
181772  functionDestroy(db, p);
181773
181774  if( pDestructor ){
181775    pDestructor->nRef++;
181776  }
181777  p->u.pDestructor = pDestructor;
181778  p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
181779  testcase( p->funcFlags & SQLITE_DETERMINISTIC );
181780  testcase( p->funcFlags & SQLITE_DIRECTONLY );
181781  p->xSFunc = xSFunc ? xSFunc : xStep;
181782  p->xFinalize = xFinal;
181783  p->xValue = xValue;
181784  p->xInverse = xInverse;
181785  p->pUserData = pUserData;
181786  p->nArg = (u16)nArg;
181787  return SQLITE_OK;
181788}
181789
181790/*
181791** Worker function used by utf-8 APIs that create new functions:
181792**
181793**    sqlite3_create_function()
181794**    sqlite3_create_function_v2()
181795**    sqlite3_create_window_function()
181796*/
181797static int createFunctionApi(
181798  sqlite3 *db,
181799  const char *zFunc,
181800  int nArg,
181801  int enc,
181802  void *p,
181803  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
181804  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
181805  void (*xFinal)(sqlite3_context*),
181806  void (*xValue)(sqlite3_context*),
181807  void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
181808  void(*xDestroy)(void*)
181809){
181810  int rc = SQLITE_ERROR;
181811  FuncDestructor *pArg = 0;
181812
181813#ifdef SQLITE_ENABLE_API_ARMOR
181814  if( !sqlite3SafetyCheckOk(db) ){
181815    return SQLITE_MISUSE_BKPT;
181816  }
181817#endif
181818  sqlite3_mutex_enter(db->mutex);
181819  if( xDestroy ){
181820    pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
181821    if( !pArg ){
181822      sqlite3OomFault(db);
181823      xDestroy(p);
181824      goto out;
181825    }
181826    pArg->nRef = 0;
181827    pArg->xDestroy = xDestroy;
181828    pArg->pUserData = p;
181829  }
181830  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
181831      xSFunc, xStep, xFinal, xValue, xInverse, pArg
181832  );
181833  if( pArg && pArg->nRef==0 ){
181834    assert( rc!=SQLITE_OK || (xStep==0 && xFinal==0) );
181835    xDestroy(p);
181836    sqlite3_free(pArg);
181837  }
181838
181839 out:
181840  rc = sqlite3ApiExit(db, rc);
181841  sqlite3_mutex_leave(db->mutex);
181842  return rc;
181843}
181844
181845/*
181846** Create new user functions.
181847*/
181848SQLITE_API int sqlite3_create_function(
181849  sqlite3 *db,
181850  const char *zFunc,
181851  int nArg,
181852  int enc,
181853  void *p,
181854  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
181855  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
181856  void (*xFinal)(sqlite3_context*)
181857){
181858  return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
181859                                    xFinal, 0, 0, 0);
181860}
181861SQLITE_API int sqlite3_create_function_v2(
181862  sqlite3 *db,
181863  const char *zFunc,
181864  int nArg,
181865  int enc,
181866  void *p,
181867  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
181868  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
181869  void (*xFinal)(sqlite3_context*),
181870  void (*xDestroy)(void *)
181871){
181872  return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
181873                                    xFinal, 0, 0, xDestroy);
181874}
181875SQLITE_API int sqlite3_create_window_function(
181876  sqlite3 *db,
181877  const char *zFunc,
181878  int nArg,
181879  int enc,
181880  void *p,
181881  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
181882  void (*xFinal)(sqlite3_context*),
181883  void (*xValue)(sqlite3_context*),
181884  void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
181885  void (*xDestroy)(void *)
181886){
181887  return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
181888                                    xFinal, xValue, xInverse, xDestroy);
181889}
181890
181891#ifndef SQLITE_OMIT_UTF16
181892SQLITE_API int sqlite3_create_function16(
181893  sqlite3 *db,
181894  const void *zFunctionName,
181895  int nArg,
181896  int eTextRep,
181897  void *p,
181898  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
181899  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
181900  void (*xFinal)(sqlite3_context*)
181901){
181902  int rc;
181903  char *zFunc8;
181904
181905#ifdef SQLITE_ENABLE_API_ARMOR
181906  if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
181907#endif
181908  sqlite3_mutex_enter(db->mutex);
181909  assert( !db->mallocFailed );
181910  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
181911  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
181912  sqlite3DbFree(db, zFunc8);
181913  rc = sqlite3ApiExit(db, rc);
181914  sqlite3_mutex_leave(db->mutex);
181915  return rc;
181916}
181917#endif
181918
181919
181920/*
181921** The following is the implementation of an SQL function that always
181922** fails with an error message stating that the function is used in the
181923** wrong context.  The sqlite3_overload_function() API might construct
181924** SQL function that use this routine so that the functions will exist
181925** for name resolution but are actually overloaded by the xFindFunction
181926** method of virtual tables.
181927*/
181928static void sqlite3InvalidFunction(
181929  sqlite3_context *context,  /* The function calling context */
181930  int NotUsed,               /* Number of arguments to the function */
181931  sqlite3_value **NotUsed2   /* Value of each argument */
181932){
181933  const char *zName = (const char*)sqlite3_user_data(context);
181934  char *zErr;
181935  UNUSED_PARAMETER2(NotUsed, NotUsed2);
181936  zErr = sqlite3_mprintf(
181937      "unable to use function %s in the requested context", zName);
181938  sqlite3_result_error(context, zErr, -1);
181939  sqlite3_free(zErr);
181940}
181941
181942/*
181943** Declare that a function has been overloaded by a virtual table.
181944**
181945** If the function already exists as a regular global function, then
181946** this routine is a no-op.  If the function does not exist, then create
181947** a new one that always throws a run-time error.
181948**
181949** When virtual tables intend to provide an overloaded function, they
181950** should call this routine to make sure the global function exists.
181951** A global function must exist in order for name resolution to work
181952** properly.
181953*/
181954SQLITE_API int sqlite3_overload_function(
181955  sqlite3 *db,
181956  const char *zName,
181957  int nArg
181958){
181959  int rc;
181960  char *zCopy;
181961
181962#ifdef SQLITE_ENABLE_API_ARMOR
181963  if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
181964    return SQLITE_MISUSE_BKPT;
181965  }
181966#endif
181967  sqlite3_mutex_enter(db->mutex);
181968  rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
181969  sqlite3_mutex_leave(db->mutex);
181970  if( rc ) return SQLITE_OK;
181971  zCopy = sqlite3_mprintf("%s", zName);
181972  if( zCopy==0 ) return SQLITE_NOMEM;
181973  return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
181974                           zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
181975}
181976
181977#ifndef SQLITE_OMIT_TRACE
181978/*
181979** Register a trace function.  The pArg from the previously registered trace
181980** is returned.
181981**
181982** A NULL trace function means that no tracing is executes.  A non-NULL
181983** trace is a pointer to a function that is invoked at the start of each
181984** SQL statement.
181985*/
181986#ifndef SQLITE_OMIT_DEPRECATED
181987SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
181988  void *pOld;
181989
181990#ifdef SQLITE_ENABLE_API_ARMOR
181991  if( !sqlite3SafetyCheckOk(db) ){
181992    (void)SQLITE_MISUSE_BKPT;
181993    return 0;
181994  }
181995#endif
181996  sqlite3_mutex_enter(db->mutex);
181997  pOld = db->pTraceArg;
181998  db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
181999  db->trace.xLegacy = xTrace;
182000  db->pTraceArg = pArg;
182001  sqlite3_mutex_leave(db->mutex);
182002  return pOld;
182003}
182004#endif /* SQLITE_OMIT_DEPRECATED */
182005
182006/* Register a trace callback using the version-2 interface.
182007*/
182008SQLITE_API int sqlite3_trace_v2(
182009  sqlite3 *db,                               /* Trace this connection */
182010  unsigned mTrace,                           /* Mask of events to be traced */
182011  int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
182012  void *pArg                                 /* Context */
182013){
182014#ifdef SQLITE_ENABLE_API_ARMOR
182015  if( !sqlite3SafetyCheckOk(db) ){
182016    return SQLITE_MISUSE_BKPT;
182017  }
182018#endif
182019  sqlite3_mutex_enter(db->mutex);
182020  if( mTrace==0 ) xTrace = 0;
182021  if( xTrace==0 ) mTrace = 0;
182022  db->mTrace = mTrace;
182023  db->trace.xV2 = xTrace;
182024  db->pTraceArg = pArg;
182025  sqlite3_mutex_leave(db->mutex);
182026  return SQLITE_OK;
182027}
182028
182029#ifndef SQLITE_OMIT_DEPRECATED
182030/*
182031** Register a profile function.  The pArg from the previously registered
182032** profile function is returned.
182033**
182034** A NULL profile function means that no profiling is executes.  A non-NULL
182035** profile is a pointer to a function that is invoked at the conclusion of
182036** each SQL statement that is run.
182037*/
182038SQLITE_API void *sqlite3_profile(
182039  sqlite3 *db,
182040  void (*xProfile)(void*,const char*,sqlite_uint64),
182041  void *pArg
182042){
182043  void *pOld;
182044
182045#ifdef SQLITE_ENABLE_API_ARMOR
182046  if( !sqlite3SafetyCheckOk(db) ){
182047    (void)SQLITE_MISUSE_BKPT;
182048    return 0;
182049  }
182050#endif
182051  sqlite3_mutex_enter(db->mutex);
182052  pOld = db->pProfileArg;
182053  db->xProfile = xProfile;
182054  db->pProfileArg = pArg;
182055  db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
182056  if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
182057  sqlite3_mutex_leave(db->mutex);
182058  return pOld;
182059}
182060#endif /* SQLITE_OMIT_DEPRECATED */
182061#endif /* SQLITE_OMIT_TRACE */
182062
182063/*
182064** Register a function to be invoked when a transaction commits.
182065** If the invoked function returns non-zero, then the commit becomes a
182066** rollback.
182067*/
182068SQLITE_API void *sqlite3_commit_hook(
182069  sqlite3 *db,              /* Attach the hook to this database */
182070  int (*xCallback)(void*),  /* Function to invoke on each commit */
182071  void *pArg                /* Argument to the function */
182072){
182073  void *pOld;
182074
182075#ifdef SQLITE_ENABLE_API_ARMOR
182076  if( !sqlite3SafetyCheckOk(db) ){
182077    (void)SQLITE_MISUSE_BKPT;
182078    return 0;
182079  }
182080#endif
182081  sqlite3_mutex_enter(db->mutex);
182082  pOld = db->pCommitArg;
182083  db->xCommitCallback = xCallback;
182084  db->pCommitArg = pArg;
182085  sqlite3_mutex_leave(db->mutex);
182086  return pOld;
182087}
182088
182089/*
182090** Register a callback to be invoked each time a row is updated,
182091** inserted or deleted using this database connection.
182092*/
182093SQLITE_API void *sqlite3_update_hook(
182094  sqlite3 *db,              /* Attach the hook to this database */
182095  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
182096  void *pArg                /* Argument to the function */
182097){
182098  void *pRet;
182099
182100#ifdef SQLITE_ENABLE_API_ARMOR
182101  if( !sqlite3SafetyCheckOk(db) ){
182102    (void)SQLITE_MISUSE_BKPT;
182103    return 0;
182104  }
182105#endif
182106  sqlite3_mutex_enter(db->mutex);
182107  pRet = db->pUpdateArg;
182108  db->xUpdateCallback = xCallback;
182109  db->pUpdateArg = pArg;
182110  sqlite3_mutex_leave(db->mutex);
182111  return pRet;
182112}
182113
182114/*
182115** Register a callback to be invoked each time a transaction is rolled
182116** back by this database connection.
182117*/
182118SQLITE_API void *sqlite3_rollback_hook(
182119  sqlite3 *db,              /* Attach the hook to this database */
182120  void (*xCallback)(void*), /* Callback function */
182121  void *pArg                /* Argument to the function */
182122){
182123  void *pRet;
182124
182125#ifdef SQLITE_ENABLE_API_ARMOR
182126  if( !sqlite3SafetyCheckOk(db) ){
182127    (void)SQLITE_MISUSE_BKPT;
182128    return 0;
182129  }
182130#endif
182131  sqlite3_mutex_enter(db->mutex);
182132  pRet = db->pRollbackArg;
182133  db->xRollbackCallback = xCallback;
182134  db->pRollbackArg = pArg;
182135  sqlite3_mutex_leave(db->mutex);
182136  return pRet;
182137}
182138
182139#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
182140/*
182141** Register a callback to be invoked each time a row is updated,
182142** inserted or deleted using this database connection.
182143*/
182144SQLITE_API void *sqlite3_preupdate_hook(
182145  sqlite3 *db,              /* Attach the hook to this database */
182146  void(*xCallback)(         /* Callback function */
182147    void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
182148  void *pArg                /* First callback argument */
182149){
182150  void *pRet;
182151
182152#ifdef SQLITE_ENABLE_API_ARMOR
182153  if( db==0 ){
182154    return 0;
182155  }
182156#endif
182157  sqlite3_mutex_enter(db->mutex);
182158  pRet = db->pPreUpdateArg;
182159  db->xPreUpdateCallback = xCallback;
182160  db->pPreUpdateArg = pArg;
182161  sqlite3_mutex_leave(db->mutex);
182162  return pRet;
182163}
182164#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
182165
182166/*
182167** Register a function to be invoked prior to each autovacuum that
182168** determines the number of pages to vacuum.
182169*/
182170SQLITE_API int sqlite3_autovacuum_pages(
182171  sqlite3 *db,                 /* Attach the hook to this database */
182172  unsigned int (*xCallback)(void*,const char*,u32,u32,u32),
182173  void *pArg,                  /* Argument to the function */
182174  void (*xDestructor)(void*)   /* Destructor for pArg */
182175){
182176#ifdef SQLITE_ENABLE_API_ARMOR
182177  if( !sqlite3SafetyCheckOk(db) ){
182178    if( xDestructor ) xDestructor(pArg);
182179    return SQLITE_MISUSE_BKPT;
182180  }
182181#endif
182182  sqlite3_mutex_enter(db->mutex);
182183  if( db->xAutovacDestr ){
182184    db->xAutovacDestr(db->pAutovacPagesArg);
182185  }
182186  db->xAutovacPages = xCallback;
182187  db->pAutovacPagesArg = pArg;
182188  db->xAutovacDestr = xDestructor;
182189  sqlite3_mutex_leave(db->mutex);
182190  return SQLITE_OK;
182191}
182192
182193
182194#ifndef SQLITE_OMIT_WAL
182195/*
182196** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
182197** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
182198** is greater than sqlite3.pWalArg cast to an integer (the value configured by
182199** wal_autocheckpoint()).
182200*/
182201SQLITE_PRIVATE int sqlite3WalDefaultHook(
182202  void *pClientData,     /* Argument */
182203  sqlite3 *db,           /* Connection */
182204  const char *zDb,       /* Database */
182205  int nFrame             /* Size of WAL */
182206){
182207  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
182208    sqlite3BeginBenignMalloc();
182209    sqlite3_wal_checkpoint(db, zDb);
182210    sqlite3EndBenignMalloc();
182211  }
182212  return SQLITE_OK;
182213}
182214#endif /* SQLITE_OMIT_WAL */
182215
182216/*
182217** Configure an sqlite3_wal_hook() callback to automatically checkpoint
182218** a database after committing a transaction if there are nFrame or
182219** more frames in the log file. Passing zero or a negative value as the
182220** nFrame parameter disables automatic checkpoints entirely.
182221**
182222** The callback registered by this function replaces any existing callback
182223** registered using sqlite3_wal_hook(). Likewise, registering a callback
182224** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
182225** configured by this function.
182226*/
182227SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
182228#ifdef SQLITE_OMIT_WAL
182229  UNUSED_PARAMETER(db);
182230  UNUSED_PARAMETER(nFrame);
182231#else
182232#ifdef SQLITE_ENABLE_API_ARMOR
182233  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
182234#endif
182235  if( nFrame>0 ){
182236    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
182237  }else{
182238    sqlite3_wal_hook(db, 0, 0);
182239  }
182240#endif
182241  return SQLITE_OK;
182242}
182243
182244/*
182245** Register a callback to be invoked each time a transaction is written
182246** into the write-ahead-log by this database connection.
182247*/
182248SQLITE_API void *sqlite3_wal_hook(
182249  sqlite3 *db,                    /* Attach the hook to this db handle */
182250  int(*xCallback)(void *, sqlite3*, const char*, int),
182251  void *pArg                      /* First argument passed to xCallback() */
182252){
182253#ifndef SQLITE_OMIT_WAL
182254  void *pRet;
182255#ifdef SQLITE_ENABLE_API_ARMOR
182256  if( !sqlite3SafetyCheckOk(db) ){
182257    (void)SQLITE_MISUSE_BKPT;
182258    return 0;
182259  }
182260#endif
182261  sqlite3_mutex_enter(db->mutex);
182262  pRet = db->pWalArg;
182263  db->xWalCallback = xCallback;
182264  db->pWalArg = pArg;
182265  sqlite3_mutex_leave(db->mutex);
182266  return pRet;
182267#else
182268  return 0;
182269#endif
182270}
182271
182272/*
182273** Checkpoint database zDb.
182274*/
182275SQLITE_API int sqlite3_wal_checkpoint_v2(
182276  sqlite3 *db,                    /* Database handle */
182277  const char *zDb,                /* Name of attached database (or NULL) */
182278  int eMode,                      /* SQLITE_CHECKPOINT_* value */
182279  int *pnLog,                     /* OUT: Size of WAL log in frames */
182280  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
182281){
182282#ifdef SQLITE_OMIT_WAL
182283  return SQLITE_OK;
182284#else
182285  int rc;                         /* Return code */
182286  int iDb;                        /* Schema to checkpoint */
182287
182288#ifdef SQLITE_ENABLE_API_ARMOR
182289  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
182290#endif
182291
182292  /* Initialize the output variables to -1 in case an error occurs. */
182293  if( pnLog ) *pnLog = -1;
182294  if( pnCkpt ) *pnCkpt = -1;
182295
182296  assert( SQLITE_CHECKPOINT_PASSIVE==0 );
182297  assert( SQLITE_CHECKPOINT_FULL==1 );
182298  assert( SQLITE_CHECKPOINT_RESTART==2 );
182299  assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
182300  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
182301    /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
182302    ** mode: */
182303    return SQLITE_MISUSE_BKPT;
182304  }
182305
182306  sqlite3_mutex_enter(db->mutex);
182307  if( zDb && zDb[0] ){
182308    iDb = sqlite3FindDbName(db, zDb);
182309  }else{
182310    iDb = SQLITE_MAX_DB;   /* This means process all schemas */
182311  }
182312  if( iDb<0 ){
182313    rc = SQLITE_ERROR;
182314    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
182315  }else{
182316    db->busyHandler.nBusy = 0;
182317    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
182318    sqlite3Error(db, rc);
182319  }
182320  rc = sqlite3ApiExit(db, rc);
182321
182322  /* If there are no active statements, clear the interrupt flag at this
182323  ** point.  */
182324  if( db->nVdbeActive==0 ){
182325    AtomicStore(&db->u1.isInterrupted, 0);
182326  }
182327
182328  sqlite3_mutex_leave(db->mutex);
182329  return rc;
182330#endif
182331}
182332
182333
182334/*
182335** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
182336** to contains a zero-length string, all attached databases are
182337** checkpointed.
182338*/
182339SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
182340  /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
182341  ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
182342  return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
182343}
182344
182345#ifndef SQLITE_OMIT_WAL
182346/*
182347** Run a checkpoint on database iDb. This is a no-op if database iDb is
182348** not currently open in WAL mode.
182349**
182350** If a transaction is open on the database being checkpointed, this
182351** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
182352** an error occurs while running the checkpoint, an SQLite error code is
182353** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
182354**
182355** The mutex on database handle db should be held by the caller. The mutex
182356** associated with the specific b-tree being checkpointed is taken by
182357** this function while the checkpoint is running.
182358**
182359** If iDb is passed SQLITE_MAX_DB then all attached databases are
182360** checkpointed. If an error is encountered it is returned immediately -
182361** no attempt is made to checkpoint any remaining databases.
182362**
182363** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
182364** or TRUNCATE.
182365*/
182366SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
182367  int rc = SQLITE_OK;             /* Return code */
182368  int i;                          /* Used to iterate through attached dbs */
182369  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
182370
182371  assert( sqlite3_mutex_held(db->mutex) );
182372  assert( !pnLog || *pnLog==-1 );
182373  assert( !pnCkpt || *pnCkpt==-1 );
182374  testcase( iDb==SQLITE_MAX_ATTACHED ); /* See forum post a006d86f72 */
182375  testcase( iDb==SQLITE_MAX_DB );
182376
182377  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
182378    if( i==iDb || iDb==SQLITE_MAX_DB ){
182379      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
182380      pnLog = 0;
182381      pnCkpt = 0;
182382      if( rc==SQLITE_BUSY ){
182383        bBusy = 1;
182384        rc = SQLITE_OK;
182385      }
182386    }
182387  }
182388
182389  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
182390}
182391#endif /* SQLITE_OMIT_WAL */
182392
182393/*
182394** This function returns true if main-memory should be used instead of
182395** a temporary file for transient pager files and statement journals.
182396** The value returned depends on the value of db->temp_store (runtime
182397** parameter) and the compile time value of SQLITE_TEMP_STORE. The
182398** following table describes the relationship between these two values
182399** and this functions return value.
182400**
182401**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
182402**   -----------------     --------------     ------------------------------
182403**   0                     any                file      (return 0)
182404**   1                     1                  file      (return 0)
182405**   1                     2                  memory    (return 1)
182406**   1                     0                  file      (return 0)
182407**   2                     1                  file      (return 0)
182408**   2                     2                  memory    (return 1)
182409**   2                     0                  memory    (return 1)
182410**   3                     any                memory    (return 1)
182411*/
182412SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
182413#if SQLITE_TEMP_STORE==1
182414  return ( db->temp_store==2 );
182415#endif
182416#if SQLITE_TEMP_STORE==2
182417  return ( db->temp_store!=1 );
182418#endif
182419#if SQLITE_TEMP_STORE==3
182420  UNUSED_PARAMETER(db);
182421  return 1;
182422#endif
182423#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
182424  UNUSED_PARAMETER(db);
182425  return 0;
182426#endif
182427}
182428
182429/*
182430** Return UTF-8 encoded English language explanation of the most recent
182431** error.
182432*/
182433SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
182434  const char *z;
182435  if( !db ){
182436    return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
182437  }
182438  if( !sqlite3SafetyCheckSickOrOk(db) ){
182439    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
182440  }
182441  sqlite3_mutex_enter(db->mutex);
182442  if( db->mallocFailed ){
182443    z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
182444  }else{
182445    testcase( db->pErr==0 );
182446    z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
182447    assert( !db->mallocFailed );
182448    if( z==0 ){
182449      z = sqlite3ErrStr(db->errCode);
182450    }
182451  }
182452  sqlite3_mutex_leave(db->mutex);
182453  return z;
182454}
182455
182456/*
182457** Return the byte offset of the most recent error
182458*/
182459SQLITE_API int sqlite3_error_offset(sqlite3 *db){
182460  int iOffset = -1;
182461  if( db && sqlite3SafetyCheckSickOrOk(db) && db->errCode ){
182462    sqlite3_mutex_enter(db->mutex);
182463    iOffset = db->errByteOffset;
182464    sqlite3_mutex_leave(db->mutex);
182465  }
182466  return iOffset;
182467}
182468
182469#ifndef SQLITE_OMIT_UTF16
182470/*
182471** Return UTF-16 encoded English language explanation of the most recent
182472** error.
182473*/
182474SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
182475  static const u16 outOfMem[] = {
182476    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
182477  };
182478  static const u16 misuse[] = {
182479    'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
182480    'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
182481    'm', 'i', 's', 'u', 's', 'e', 0
182482  };
182483
182484  const void *z;
182485  if( !db ){
182486    return (void *)outOfMem;
182487  }
182488  if( !sqlite3SafetyCheckSickOrOk(db) ){
182489    return (void *)misuse;
182490  }
182491  sqlite3_mutex_enter(db->mutex);
182492  if( db->mallocFailed ){
182493    z = (void *)outOfMem;
182494  }else{
182495    z = sqlite3_value_text16(db->pErr);
182496    if( z==0 ){
182497      sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
182498      z = sqlite3_value_text16(db->pErr);
182499    }
182500    /* A malloc() may have failed within the call to sqlite3_value_text16()
182501    ** above. If this is the case, then the db->mallocFailed flag needs to
182502    ** be cleared before returning. Do this directly, instead of via
182503    ** sqlite3ApiExit(), to avoid setting the database handle error message.
182504    */
182505    sqlite3OomClear(db);
182506  }
182507  sqlite3_mutex_leave(db->mutex);
182508  return z;
182509}
182510#endif /* SQLITE_OMIT_UTF16 */
182511
182512/*
182513** Return the most recent error code generated by an SQLite routine. If NULL is
182514** passed to this function, we assume a malloc() failed during sqlite3_open().
182515*/
182516SQLITE_API int sqlite3_errcode(sqlite3 *db){
182517  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
182518    return SQLITE_MISUSE_BKPT;
182519  }
182520  if( !db || db->mallocFailed ){
182521    return SQLITE_NOMEM_BKPT;
182522  }
182523  return db->errCode & db->errMask;
182524}
182525SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
182526  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
182527    return SQLITE_MISUSE_BKPT;
182528  }
182529  if( !db || db->mallocFailed ){
182530    return SQLITE_NOMEM_BKPT;
182531  }
182532  return db->errCode;
182533}
182534SQLITE_API int sqlite3_system_errno(sqlite3 *db){
182535  return db ? db->iSysErrno : 0;
182536}
182537
182538/*
182539** Return a string that describes the kind of error specified in the
182540** argument.  For now, this simply calls the internal sqlite3ErrStr()
182541** function.
182542*/
182543SQLITE_API const char *sqlite3_errstr(int rc){
182544  return sqlite3ErrStr(rc);
182545}
182546
182547/*
182548** Create a new collating function for database "db".  The name is zName
182549** and the encoding is enc.
182550*/
182551static int createCollation(
182552  sqlite3* db,
182553  const char *zName,
182554  u8 enc,
182555  void* pCtx,
182556  int(*xCompare)(void*,int,const void*,int,const void*),
182557  void(*xDel)(void*)
182558){
182559  CollSeq *pColl;
182560  int enc2;
182561
182562  assert( sqlite3_mutex_held(db->mutex) );
182563
182564  /* If SQLITE_UTF16 is specified as the encoding type, transform this
182565  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
182566  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
182567  */
182568  enc2 = enc;
182569  testcase( enc2==SQLITE_UTF16 );
182570  testcase( enc2==SQLITE_UTF16_ALIGNED );
182571  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
182572    enc2 = SQLITE_UTF16NATIVE;
182573  }
182574  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
182575    return SQLITE_MISUSE_BKPT;
182576  }
182577
182578  /* Check if this call is removing or replacing an existing collation
182579  ** sequence. If so, and there are active VMs, return busy. If there
182580  ** are no active VMs, invalidate any pre-compiled statements.
182581  */
182582  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
182583  if( pColl && pColl->xCmp ){
182584    if( db->nVdbeActive ){
182585      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
182586        "unable to delete/modify collation sequence due to active statements");
182587      return SQLITE_BUSY;
182588    }
182589    sqlite3ExpirePreparedStatements(db, 0);
182590
182591    /* If collation sequence pColl was created directly by a call to
182592    ** sqlite3_create_collation, and not generated by synthCollSeq(),
182593    ** then any copies made by synthCollSeq() need to be invalidated.
182594    ** Also, collation destructor - CollSeq.xDel() - function may need
182595    ** to be called.
182596    */
182597    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
182598      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
182599      int j;
182600      for(j=0; j<3; j++){
182601        CollSeq *p = &aColl[j];
182602        if( p->enc==pColl->enc ){
182603          if( p->xDel ){
182604            p->xDel(p->pUser);
182605          }
182606          p->xCmp = 0;
182607        }
182608      }
182609    }
182610  }
182611
182612  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
182613  if( pColl==0 ) return SQLITE_NOMEM_BKPT;
182614  pColl->xCmp = xCompare;
182615  pColl->pUser = pCtx;
182616  pColl->xDel = xDel;
182617  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
182618  sqlite3Error(db, SQLITE_OK);
182619  return SQLITE_OK;
182620}
182621
182622
182623/*
182624** This array defines hard upper bounds on limit values.  The
182625** initializer must be kept in sync with the SQLITE_LIMIT_*
182626** #defines in sqlite3.h.
182627*/
182628static const int aHardLimit[] = {
182629  SQLITE_MAX_LENGTH,
182630  SQLITE_MAX_SQL_LENGTH,
182631  SQLITE_MAX_COLUMN,
182632  SQLITE_MAX_EXPR_DEPTH,
182633  SQLITE_MAX_COMPOUND_SELECT,
182634  SQLITE_MAX_VDBE_OP,
182635  SQLITE_MAX_FUNCTION_ARG,
182636  SQLITE_MAX_ATTACHED,
182637  SQLITE_MAX_LIKE_PATTERN_LENGTH,
182638  SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
182639  SQLITE_MAX_TRIGGER_DEPTH,
182640  SQLITE_MAX_WORKER_THREADS,
182641};
182642
182643/*
182644** Make sure the hard limits are set to reasonable values
182645*/
182646#if SQLITE_MAX_LENGTH<100
182647# error SQLITE_MAX_LENGTH must be at least 100
182648#endif
182649#if SQLITE_MAX_SQL_LENGTH<100
182650# error SQLITE_MAX_SQL_LENGTH must be at least 100
182651#endif
182652#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
182653# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
182654#endif
182655#if SQLITE_MAX_COMPOUND_SELECT<2
182656# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
182657#endif
182658#if SQLITE_MAX_VDBE_OP<40
182659# error SQLITE_MAX_VDBE_OP must be at least 40
182660#endif
182661#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
182662# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
182663#endif
182664#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
182665# error SQLITE_MAX_ATTACHED must be between 0 and 125
182666#endif
182667#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
182668# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
182669#endif
182670#if SQLITE_MAX_COLUMN>32767
182671# error SQLITE_MAX_COLUMN must not exceed 32767
182672#endif
182673#if SQLITE_MAX_TRIGGER_DEPTH<1
182674# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
182675#endif
182676#if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
182677# error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
182678#endif
182679
182680
182681/*
182682** Change the value of a limit.  Report the old value.
182683** If an invalid limit index is supplied, report -1.
182684** Make no changes but still report the old value if the
182685** new limit is negative.
182686**
182687** A new lower limit does not shrink existing constructs.
182688** It merely prevents new constructs that exceed the limit
182689** from forming.
182690*/
182691SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
182692  int oldLimit;
182693
182694#ifdef SQLITE_ENABLE_API_ARMOR
182695  if( !sqlite3SafetyCheckOk(db) ){
182696    (void)SQLITE_MISUSE_BKPT;
182697    return -1;
182698  }
182699#endif
182700
182701  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
182702  ** there is a hard upper bound set at compile-time by a C preprocessor
182703  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
182704  ** "_MAX_".)
182705  */
182706  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
182707  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
182708  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
182709  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
182710  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
182711  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
182712  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
182713  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
182714  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
182715                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );
182716  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
182717  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
182718  assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
182719  assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
182720
182721
182722  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
182723    return -1;
182724  }
182725  oldLimit = db->aLimit[limitId];
182726  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
182727    if( newLimit>aHardLimit[limitId] ){
182728      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
182729    }else if( newLimit<1 && limitId==SQLITE_LIMIT_LENGTH ){
182730      newLimit = 1;
182731    }
182732    db->aLimit[limitId] = newLimit;
182733  }
182734  return oldLimit;                     /* IMP: R-53341-35419 */
182735}
182736
182737/*
182738** This function is used to parse both URIs and non-URI filenames passed by the
182739** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
182740** URIs specified as part of ATTACH statements.
182741**
182742** The first argument to this function is the name of the VFS to use (or
182743** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
182744** query parameter. The second argument contains the URI (or non-URI filename)
182745** itself. When this function is called the *pFlags variable should contain
182746** the default flags to open the database handle with. The value stored in
182747** *pFlags may be updated before returning if the URI filename contains
182748** "cache=xxx" or "mode=xxx" query parameters.
182749**
182750** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
182751** the VFS that should be used to open the database file. *pzFile is set to
182752** point to a buffer containing the name of the file to open.  The value
182753** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()
182754** and is in the same format as names created using sqlite3_create_filename().
182755** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on
182756** the value returned in *pzFile to avoid a memory leak.
182757**
182758** If an error occurs, then an SQLite error code is returned and *pzErrMsg
182759** may be set to point to a buffer containing an English language error
182760** message. It is the responsibility of the caller to eventually release
182761** this buffer by calling sqlite3_free().
182762*/
182763SQLITE_PRIVATE int sqlite3ParseUri(
182764  const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
182765  const char *zUri,               /* Nul-terminated URI to parse */
182766  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
182767  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
182768  char **pzFile,                  /* OUT: Filename component of URI */
182769  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
182770){
182771  int rc = SQLITE_OK;
182772  unsigned int flags = *pFlags;
182773  const char *zVfs = zDefaultVfs;
182774  char *zFile;
182775  char c;
182776  int nUri = sqlite3Strlen30(zUri);
182777
182778  assert( *pzErrMsg==0 );
182779
182780  if( ((flags & SQLITE_OPEN_URI)                     /* IMP: R-48725-32206 */
182781       || AtomicLoad(&sqlite3GlobalConfig.bOpenUri)) /* IMP: R-51689-46548 */
182782   && nUri>=5 && memcmp(zUri, "file:", 5)==0         /* IMP: R-57884-37496 */
182783  ){
182784    char *zOpt;
182785    int eState;                   /* Parser state when parsing URI */
182786    int iIn;                      /* Input character index */
182787    int iOut = 0;                 /* Output character index */
182788    u64 nByte = nUri+8;           /* Bytes of space to allocate */
182789
182790    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
182791    ** method that there may be extra parameters following the file-name.  */
182792    flags |= SQLITE_OPEN_URI;
182793
182794    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
182795    zFile = sqlite3_malloc64(nByte);
182796    if( !zFile ) return SQLITE_NOMEM_BKPT;
182797
182798    memset(zFile, 0, 4);  /* 4-byte of 0x00 is the start of DB name marker */
182799    zFile += 4;
182800
182801    iIn = 5;
182802#ifdef SQLITE_ALLOW_URI_AUTHORITY
182803    if( strncmp(zUri+5, "///", 3)==0 ){
182804      iIn = 7;
182805      /* The following condition causes URIs with five leading / characters
182806      ** like file://///host/path to be converted into UNCs like //host/path.
182807      ** The correct URI for that UNC has only two or four leading / characters
182808      ** file://host/path or file:////host/path.  But 5 leading slashes is a
182809      ** common error, we are told, so we handle it as a special case. */
182810      if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
182811    }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
182812      iIn = 16;
182813    }
182814#else
182815    /* Discard the scheme and authority segments of the URI. */
182816    if( zUri[5]=='/' && zUri[6]=='/' ){
182817      iIn = 7;
182818      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
182819      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
182820        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
182821            iIn-7, &zUri[7]);
182822        rc = SQLITE_ERROR;
182823        goto parse_uri_out;
182824      }
182825    }
182826#endif
182827
182828    /* Copy the filename and any query parameters into the zFile buffer.
182829    ** Decode %HH escape codes along the way.
182830    **
182831    ** Within this loop, variable eState may be set to 0, 1 or 2, depending
182832    ** on the parsing context. As follows:
182833    **
182834    **   0: Parsing file-name.
182835    **   1: Parsing name section of a name=value query parameter.
182836    **   2: Parsing value section of a name=value query parameter.
182837    */
182838    eState = 0;
182839    while( (c = zUri[iIn])!=0 && c!='#' ){
182840      iIn++;
182841      if( c=='%'
182842       && sqlite3Isxdigit(zUri[iIn])
182843       && sqlite3Isxdigit(zUri[iIn+1])
182844      ){
182845        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
182846        octet += sqlite3HexToInt(zUri[iIn++]);
182847
182848        assert( octet>=0 && octet<256 );
182849        if( octet==0 ){
182850#ifndef SQLITE_ENABLE_URI_00_ERROR
182851          /* This branch is taken when "%00" appears within the URI. In this
182852          ** case we ignore all text in the remainder of the path, name or
182853          ** value currently being parsed. So ignore the current character
182854          ** and skip to the next "?", "=" or "&", as appropriate. */
182855          while( (c = zUri[iIn])!=0 && c!='#'
182856              && (eState!=0 || c!='?')
182857              && (eState!=1 || (c!='=' && c!='&'))
182858              && (eState!=2 || c!='&')
182859          ){
182860            iIn++;
182861          }
182862          continue;
182863#else
182864          /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
182865          *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
182866          rc = SQLITE_ERROR;
182867          goto parse_uri_out;
182868#endif
182869        }
182870        c = octet;
182871      }else if( eState==1 && (c=='&' || c=='=') ){
182872        if( zFile[iOut-1]==0 ){
182873          /* An empty option name. Ignore this option altogether. */
182874          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
182875          continue;
182876        }
182877        if( c=='&' ){
182878          zFile[iOut++] = '\0';
182879        }else{
182880          eState = 2;
182881        }
182882        c = 0;
182883      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
182884        c = 0;
182885        eState = 1;
182886      }
182887      zFile[iOut++] = c;
182888    }
182889    if( eState==1 ) zFile[iOut++] = '\0';
182890    memset(zFile+iOut, 0, 4); /* end-of-options + empty journal filenames */
182891
182892    /* Check if there were any options specified that should be interpreted
182893    ** here. Options that are interpreted here include "vfs" and those that
182894    ** correspond to flags that may be passed to the sqlite3_open_v2()
182895    ** method. */
182896    zOpt = &zFile[sqlite3Strlen30(zFile)+1];
182897    while( zOpt[0] ){
182898      int nOpt = sqlite3Strlen30(zOpt);
182899      char *zVal = &zOpt[nOpt+1];
182900      int nVal = sqlite3Strlen30(zVal);
182901
182902      if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
182903        zVfs = zVal;
182904      }else{
182905        struct OpenMode {
182906          const char *z;
182907          int mode;
182908        } *aMode = 0;
182909        char *zModeType = 0;
182910        int mask = 0;
182911        int limit = 0;
182912
182913        if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
182914          static struct OpenMode aCacheMode[] = {
182915            { "shared",  SQLITE_OPEN_SHAREDCACHE },
182916            { "private", SQLITE_OPEN_PRIVATECACHE },
182917            { 0, 0 }
182918          };
182919
182920          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
182921          aMode = aCacheMode;
182922          limit = mask;
182923          zModeType = "cache";
182924        }
182925        if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
182926          static struct OpenMode aOpenMode[] = {
182927            { "ro",  SQLITE_OPEN_READONLY },
182928            { "rw",  SQLITE_OPEN_READWRITE },
182929            { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
182930            { "memory", SQLITE_OPEN_MEMORY },
182931            { 0, 0 }
182932          };
182933
182934          mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
182935                   | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
182936          aMode = aOpenMode;
182937          limit = mask & flags;
182938          zModeType = "access";
182939        }
182940
182941        if( aMode ){
182942          int i;
182943          int mode = 0;
182944          for(i=0; aMode[i].z; i++){
182945            const char *z = aMode[i].z;
182946            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
182947              mode = aMode[i].mode;
182948              break;
182949            }
182950          }
182951          if( mode==0 ){
182952            *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
182953            rc = SQLITE_ERROR;
182954            goto parse_uri_out;
182955          }
182956          if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
182957            *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
182958                                        zModeType, zVal);
182959            rc = SQLITE_PERM;
182960            goto parse_uri_out;
182961          }
182962          flags = (flags & ~mask) | mode;
182963        }
182964      }
182965
182966      zOpt = &zVal[nVal+1];
182967    }
182968
182969  }else{
182970    zFile = sqlite3_malloc64(nUri+8);
182971    if( !zFile ) return SQLITE_NOMEM_BKPT;
182972    memset(zFile, 0, 4);
182973    zFile += 4;
182974    if( nUri ){
182975      memcpy(zFile, zUri, nUri);
182976    }
182977    memset(zFile+nUri, 0, 4);
182978    flags &= ~SQLITE_OPEN_URI;
182979  }
182980
182981  *ppVfs = sqlite3_vfs_find(zVfs);
182982  if( *ppVfs==0 ){
182983    *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
182984    rc = SQLITE_ERROR;
182985  }
182986 parse_uri_out:
182987  if( rc!=SQLITE_OK ){
182988    sqlite3_free_filename(zFile);
182989    zFile = 0;
182990  }
182991  *pFlags = flags;
182992  *pzFile = zFile;
182993  return rc;
182994}
182995
182996/*
182997** This routine does the core work of extracting URI parameters from a
182998** database filename for the sqlite3_uri_parameter() interface.
182999*/
183000static const char *uriParameter(const char *zFilename, const char *zParam){
183001  zFilename += sqlite3Strlen30(zFilename) + 1;
183002  while( ALWAYS(zFilename!=0) && zFilename[0] ){
183003    int x = strcmp(zFilename, zParam);
183004    zFilename += sqlite3Strlen30(zFilename) + 1;
183005    if( x==0 ) return zFilename;
183006    zFilename += sqlite3Strlen30(zFilename) + 1;
183007  }
183008  return 0;
183009}
183010
183011
183012
183013/*
183014** This routine does the work of opening a database on behalf of
183015** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
183016** is UTF-8 encoded.
183017*/
183018static int openDatabase(
183019  const char *zFilename, /* Database filename UTF-8 encoded */
183020  sqlite3 **ppDb,        /* OUT: Returned database handle */
183021  unsigned int flags,    /* Operational flags */
183022  const char *zVfs       /* Name of the VFS to use */
183023){
183024  sqlite3 *db;                    /* Store allocated handle here */
183025  int rc;                         /* Return code */
183026  int isThreadsafe;               /* True for threadsafe connections */
183027  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
183028  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
183029  int i;                          /* Loop counter */
183030
183031#ifdef SQLITE_ENABLE_API_ARMOR
183032  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
183033#endif
183034  *ppDb = 0;
183035#ifndef SQLITE_OMIT_AUTOINIT
183036  rc = sqlite3_initialize();
183037  if( rc ) return rc;
183038#endif
183039
183040  if( sqlite3GlobalConfig.bCoreMutex==0 ){
183041    isThreadsafe = 0;
183042  }else if( flags & SQLITE_OPEN_NOMUTEX ){
183043    isThreadsafe = 0;
183044  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
183045    isThreadsafe = 1;
183046  }else{
183047    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
183048  }
183049
183050  if( flags & SQLITE_OPEN_PRIVATECACHE ){
183051    flags &= ~SQLITE_OPEN_SHAREDCACHE;
183052  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
183053    flags |= SQLITE_OPEN_SHAREDCACHE;
183054  }
183055
183056  /* Remove harmful bits from the flags parameter
183057  **
183058  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
183059  ** dealt with in the previous code block.  Besides these, the only
183060  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
183061  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
183062  ** SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_EXRESCODE, and some reserved
183063  ** bits.  Silently mask off all other flags.
183064  */
183065  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
183066               SQLITE_OPEN_EXCLUSIVE |
183067               SQLITE_OPEN_MAIN_DB |
183068               SQLITE_OPEN_TEMP_DB |
183069               SQLITE_OPEN_TRANSIENT_DB |
183070               SQLITE_OPEN_MAIN_JOURNAL |
183071               SQLITE_OPEN_TEMP_JOURNAL |
183072               SQLITE_OPEN_SUBJOURNAL |
183073               SQLITE_OPEN_SUPER_JOURNAL |
183074               SQLITE_OPEN_NOMUTEX |
183075               SQLITE_OPEN_FULLMUTEX |
183076               SQLITE_OPEN_WAL
183077             );
183078
183079  /* Allocate the sqlite data structure */
183080  db = sqlite3MallocZero( sizeof(sqlite3) );
183081  if( db==0 ) goto opendb_out;
183082  if( isThreadsafe
183083#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
183084   || sqlite3GlobalConfig.bCoreMutex
183085#endif
183086  ){
183087    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
183088    if( db->mutex==0 ){
183089      sqlite3_free(db);
183090      db = 0;
183091      goto opendb_out;
183092    }
183093    if( isThreadsafe==0 ){
183094      sqlite3MutexWarnOnContention(db->mutex);
183095    }
183096  }
183097  sqlite3_mutex_enter(db->mutex);
183098  db->errMask = (flags & SQLITE_OPEN_EXRESCODE)!=0 ? 0xffffffff : 0xff;
183099  db->nDb = 2;
183100  db->eOpenState = SQLITE_STATE_BUSY;
183101  db->aDb = db->aDbStatic;
183102  db->lookaside.bDisable = 1;
183103  db->lookaside.sz = 0;
183104
183105  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
183106  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
183107  db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
183108  db->autoCommit = 1;
183109  db->nextAutovac = -1;
183110  db->szMmap = sqlite3GlobalConfig.szMmap;
183111  db->nextPagesize = 0;
183112  db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
183113#ifdef SQLITE_ENABLE_SORTER_MMAP
183114  /* Beginning with version 3.37.0, using the VFS xFetch() API to memory-map
183115  ** the temporary files used to do external sorts (see code in vdbesort.c)
183116  ** is disabled. It can still be used either by defining
183117  ** SQLITE_ENABLE_SORTER_MMAP at compile time or by using the
183118  ** SQLITE_TESTCTRL_SORTER_MMAP test-control at runtime. */
183119  db->nMaxSorterMmap = 0x7FFFFFFF;
183120#endif
183121  db->flags |= SQLITE_ShortColNames
183122                 | SQLITE_EnableTrigger
183123                 | SQLITE_EnableView
183124                 | SQLITE_CacheSpill
183125#if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
183126                 | SQLITE_TrustedSchema
183127#endif
183128/* The SQLITE_DQS compile-time option determines the default settings
183129** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
183130**
183131**    SQLITE_DQS     SQLITE_DBCONFIG_DQS_DDL    SQLITE_DBCONFIG_DQS_DML
183132**    ----------     -----------------------    -----------------------
183133**     undefined               on                          on
183134**         3                   on                          on
183135**         2                   on                         off
183136**         1                  off                          on
183137**         0                  off                         off
183138**
183139** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
183140** and so that is the default.  But developers are encouraged to use
183141** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
183142*/
183143#if !defined(SQLITE_DQS)
183144# define SQLITE_DQS 3
183145#endif
183146#if (SQLITE_DQS&1)==1
183147                 | SQLITE_DqsDML
183148#endif
183149#if (SQLITE_DQS&2)==2
183150                 | SQLITE_DqsDDL
183151#endif
183152
183153#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
183154                 | SQLITE_AutoIndex
183155#endif
183156#if SQLITE_DEFAULT_CKPTFULLFSYNC
183157                 | SQLITE_CkptFullFSync
183158#endif
183159#if SQLITE_DEFAULT_FILE_FORMAT<4
183160                 | SQLITE_LegacyFileFmt
183161#endif
183162#ifdef SQLITE_ENABLE_LOAD_EXTENSION
183163                 | SQLITE_LoadExtension
183164#endif
183165#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
183166                 | SQLITE_RecTriggers
183167#endif
183168#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
183169                 | SQLITE_ForeignKeys
183170#endif
183171#if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
183172                 | SQLITE_ReverseOrder
183173#endif
183174#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
183175                 | SQLITE_CellSizeCk
183176#endif
183177#if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
183178                 | SQLITE_Fts3Tokenizer
183179#endif
183180#if defined(SQLITE_ENABLE_QPSG)
183181                 | SQLITE_EnableQPSG
183182#endif
183183#if defined(SQLITE_DEFAULT_DEFENSIVE)
183184                 | SQLITE_Defensive
183185#endif
183186#if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
183187                 | SQLITE_LegacyAlter
183188#endif
183189#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
183190                 | SQLITE_StmtScanStatus
183191#endif
183192      ;
183193  sqlite3HashInit(&db->aCollSeq);
183194#ifndef SQLITE_OMIT_VIRTUALTABLE
183195  sqlite3HashInit(&db->aModule);
183196#endif
183197
183198  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
183199  ** and UTF-16, so add a version for each to avoid any unnecessary
183200  ** conversions. The only error that can occur here is a malloc() failure.
183201  **
183202  ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
183203  ** functions:
183204  */
183205  createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
183206  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
183207  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
183208  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
183209  createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0);
183210  if( db->mallocFailed ){
183211    goto opendb_out;
183212  }
183213
183214#if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
183215  /* Process magic filenames ":localStorage:" and ":sessionStorage:" */
183216  if( zFilename && zFilename[0]==':' ){
183217    if( strcmp(zFilename, ":localStorage:")==0 ){
183218      zFilename = "file:local?vfs=kvvfs";
183219      flags |= SQLITE_OPEN_URI;
183220    }else if( strcmp(zFilename, ":sessionStorage:")==0 ){
183221      zFilename = "file:session?vfs=kvvfs";
183222      flags |= SQLITE_OPEN_URI;
183223    }
183224  }
183225#endif /* SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL) */
183226
183227  /* Parse the filename/URI argument
183228  **
183229  ** Only allow sensible combinations of bits in the flags argument.
183230  ** Throw an error if any non-sense combination is used.  If we
183231  ** do not block illegal combinations here, it could trigger
183232  ** assert() statements in deeper layers.  Sensible combinations
183233  ** are:
183234  **
183235  **  1:  SQLITE_OPEN_READONLY
183236  **  2:  SQLITE_OPEN_READWRITE
183237  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
183238  */
183239  db->openFlags = flags;
183240  assert( SQLITE_OPEN_READONLY  == 0x01 );
183241  assert( SQLITE_OPEN_READWRITE == 0x02 );
183242  assert( SQLITE_OPEN_CREATE    == 0x04 );
183243  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
183244  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
183245  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
183246  if( ((1<<(flags&7)) & 0x46)==0 ){
183247    rc = SQLITE_MISUSE_BKPT;  /* IMP: R-18321-05872 */
183248  }else{
183249    rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
183250  }
183251  if( rc!=SQLITE_OK ){
183252    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
183253    sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
183254    sqlite3_free(zErrMsg);
183255    goto opendb_out;
183256  }
183257  assert( db->pVfs!=0 );
183258#if SQLITE_OS_KV || defined(SQLITE_OS_KV_OPTIONAL)
183259  if( sqlite3_stricmp(db->pVfs->zName, "kvvfs")==0 ){
183260    db->temp_store = 2;
183261  }
183262#endif
183263
183264  /* Open the backend database driver */
183265  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
183266                        flags | SQLITE_OPEN_MAIN_DB);
183267  if( rc!=SQLITE_OK ){
183268    if( rc==SQLITE_IOERR_NOMEM ){
183269      rc = SQLITE_NOMEM_BKPT;
183270    }
183271    sqlite3Error(db, rc);
183272    goto opendb_out;
183273  }
183274  sqlite3BtreeEnter(db->aDb[0].pBt);
183275  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
183276  if( !db->mallocFailed ){
183277    sqlite3SetTextEncoding(db, SCHEMA_ENC(db));
183278  }
183279  sqlite3BtreeLeave(db->aDb[0].pBt);
183280  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
183281
183282  /* The default safety_level for the main database is FULL; for the temp
183283  ** database it is OFF. This matches the pager layer defaults.
183284  */
183285  db->aDb[0].zDbSName = "main";
183286  db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
183287  db->aDb[1].zDbSName = "temp";
183288  db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
183289
183290  db->eOpenState = SQLITE_STATE_OPEN;
183291  if( db->mallocFailed ){
183292    goto opendb_out;
183293  }
183294
183295  /* Register all built-in functions, but do not attempt to read the
183296  ** database schema yet. This is delayed until the first time the database
183297  ** is accessed.
183298  */
183299  sqlite3Error(db, SQLITE_OK);
183300  sqlite3RegisterPerConnectionBuiltinFunctions(db);
183301  rc = sqlite3_errcode(db);
183302
183303
183304  /* Load compiled-in extensions */
183305  for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){
183306    rc = sqlite3BuiltinExtensions[i](db);
183307  }
183308
183309  /* Load automatic extensions - extensions that have been registered
183310  ** using the sqlite3_automatic_extension() API.
183311  */
183312  if( rc==SQLITE_OK ){
183313    sqlite3AutoLoadExtensions(db);
183314    rc = sqlite3_errcode(db);
183315    if( rc!=SQLITE_OK ){
183316      goto opendb_out;
183317    }
183318  }
183319
183320#ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
183321  /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
183322  ** option gives access to internal functions by default.
183323  ** Testing use only!!! */
183324  db->mDbFlags |= DBFLAG_InternalFunc;
183325#endif
183326
183327  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
183328  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
183329  ** mode.  Doing nothing at all also makes NORMAL the default.
183330  */
183331#ifdef SQLITE_DEFAULT_LOCKING_MODE
183332  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
183333  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
183334                          SQLITE_DEFAULT_LOCKING_MODE);
183335#endif
183336
183337  if( rc ) sqlite3Error(db, rc);
183338
183339  /* Enable the lookaside-malloc subsystem */
183340  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
183341                        sqlite3GlobalConfig.nLookaside);
183342
183343  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
183344
183345opendb_out:
183346  if( db ){
183347    assert( db->mutex!=0 || isThreadsafe==0
183348           || sqlite3GlobalConfig.bFullMutex==0 );
183349    sqlite3_mutex_leave(db->mutex);
183350  }
183351  rc = sqlite3_errcode(db);
183352  assert( db!=0 || (rc&0xff)==SQLITE_NOMEM );
183353  if( (rc&0xff)==SQLITE_NOMEM ){
183354    sqlite3_close(db);
183355    db = 0;
183356  }else if( rc!=SQLITE_OK ){
183357    db->eOpenState = SQLITE_STATE_SICK;
183358  }
183359  *ppDb = db;
183360#ifdef SQLITE_ENABLE_SQLLOG
183361  if( sqlite3GlobalConfig.xSqllog ){
183362    /* Opening a db handle. Fourth parameter is passed 0. */
183363    void *pArg = sqlite3GlobalConfig.pSqllogArg;
183364    sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
183365  }
183366#endif
183367  sqlite3_free_filename(zOpen);
183368  return rc;
183369}
183370
183371
183372/*
183373** Open a new database handle.
183374*/
183375SQLITE_API int sqlite3_open(
183376  const char *zFilename,
183377  sqlite3 **ppDb
183378){
183379  return openDatabase(zFilename, ppDb,
183380                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
183381}
183382SQLITE_API int sqlite3_open_v2(
183383  const char *filename,   /* Database filename (UTF-8) */
183384  sqlite3 **ppDb,         /* OUT: SQLite db handle */
183385  int flags,              /* Flags */
183386  const char *zVfs        /* Name of VFS module to use */
183387){
183388  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
183389}
183390
183391#ifndef SQLITE_OMIT_UTF16
183392/*
183393** Open a new database handle.
183394*/
183395SQLITE_API int sqlite3_open16(
183396  const void *zFilename,
183397  sqlite3 **ppDb
183398){
183399  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
183400  sqlite3_value *pVal;
183401  int rc;
183402
183403#ifdef SQLITE_ENABLE_API_ARMOR
183404  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
183405#endif
183406  *ppDb = 0;
183407#ifndef SQLITE_OMIT_AUTOINIT
183408  rc = sqlite3_initialize();
183409  if( rc ) return rc;
183410#endif
183411  if( zFilename==0 ) zFilename = "\000\000";
183412  pVal = sqlite3ValueNew(0);
183413  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
183414  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
183415  if( zFilename8 ){
183416    rc = openDatabase(zFilename8, ppDb,
183417                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
183418    assert( *ppDb || rc==SQLITE_NOMEM );
183419    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
183420      SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
183421    }
183422  }else{
183423    rc = SQLITE_NOMEM_BKPT;
183424  }
183425  sqlite3ValueFree(pVal);
183426
183427  return rc & 0xff;
183428}
183429#endif /* SQLITE_OMIT_UTF16 */
183430
183431/*
183432** Register a new collation sequence with the database handle db.
183433*/
183434SQLITE_API int sqlite3_create_collation(
183435  sqlite3* db,
183436  const char *zName,
183437  int enc,
183438  void* pCtx,
183439  int(*xCompare)(void*,int,const void*,int,const void*)
183440){
183441  return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
183442}
183443
183444/*
183445** Register a new collation sequence with the database handle db.
183446*/
183447SQLITE_API int sqlite3_create_collation_v2(
183448  sqlite3* db,
183449  const char *zName,
183450  int enc,
183451  void* pCtx,
183452  int(*xCompare)(void*,int,const void*,int,const void*),
183453  void(*xDel)(void*)
183454){
183455  int rc;
183456
183457#ifdef SQLITE_ENABLE_API_ARMOR
183458  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
183459#endif
183460  sqlite3_mutex_enter(db->mutex);
183461  assert( !db->mallocFailed );
183462  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
183463  rc = sqlite3ApiExit(db, rc);
183464  sqlite3_mutex_leave(db->mutex);
183465  return rc;
183466}
183467
183468#ifndef SQLITE_OMIT_UTF16
183469/*
183470** Register a new collation sequence with the database handle db.
183471*/
183472SQLITE_API int sqlite3_create_collation16(
183473  sqlite3* db,
183474  const void *zName,
183475  int enc,
183476  void* pCtx,
183477  int(*xCompare)(void*,int,const void*,int,const void*)
183478){
183479  int rc = SQLITE_OK;
183480  char *zName8;
183481
183482#ifdef SQLITE_ENABLE_API_ARMOR
183483  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
183484#endif
183485  sqlite3_mutex_enter(db->mutex);
183486  assert( !db->mallocFailed );
183487  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
183488  if( zName8 ){
183489    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
183490    sqlite3DbFree(db, zName8);
183491  }
183492  rc = sqlite3ApiExit(db, rc);
183493  sqlite3_mutex_leave(db->mutex);
183494  return rc;
183495}
183496#endif /* SQLITE_OMIT_UTF16 */
183497
183498/*
183499** Register a collation sequence factory callback with the database handle
183500** db. Replace any previously installed collation sequence factory.
183501*/
183502SQLITE_API int sqlite3_collation_needed(
183503  sqlite3 *db,
183504  void *pCollNeededArg,
183505  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
183506){
183507#ifdef SQLITE_ENABLE_API_ARMOR
183508  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
183509#endif
183510  sqlite3_mutex_enter(db->mutex);
183511  db->xCollNeeded = xCollNeeded;
183512  db->xCollNeeded16 = 0;
183513  db->pCollNeededArg = pCollNeededArg;
183514  sqlite3_mutex_leave(db->mutex);
183515  return SQLITE_OK;
183516}
183517
183518#ifndef SQLITE_OMIT_UTF16
183519/*
183520** Register a collation sequence factory callback with the database handle
183521** db. Replace any previously installed collation sequence factory.
183522*/
183523SQLITE_API int sqlite3_collation_needed16(
183524  sqlite3 *db,
183525  void *pCollNeededArg,
183526  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
183527){
183528#ifdef SQLITE_ENABLE_API_ARMOR
183529  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
183530#endif
183531  sqlite3_mutex_enter(db->mutex);
183532  db->xCollNeeded = 0;
183533  db->xCollNeeded16 = xCollNeeded16;
183534  db->pCollNeededArg = pCollNeededArg;
183535  sqlite3_mutex_leave(db->mutex);
183536  return SQLITE_OK;
183537}
183538#endif /* SQLITE_OMIT_UTF16 */
183539
183540/*
183541** Find existing client data.
183542*/
183543SQLITE_API void *sqlite3_get_clientdata(sqlite3 *db, const char *zName){
183544  DbClientData *p;
183545  sqlite3_mutex_enter(db->mutex);
183546  for(p=db->pDbData; p; p=p->pNext){
183547    if( strcmp(p->zName, zName)==0 ){
183548      void *pResult = p->pData;
183549      sqlite3_mutex_leave(db->mutex);
183550      return pResult;
183551    }
183552  }
183553  sqlite3_mutex_leave(db->mutex);
183554  return 0;
183555}
183556
183557/*
183558** Add new client data to a database connection.
183559*/
183560SQLITE_API int sqlite3_set_clientdata(
183561  sqlite3 *db,                   /* Attach client data to this connection */
183562  const char *zName,             /* Name of the client data */
183563  void *pData,                   /* The client data itself */
183564  void (*xDestructor)(void*)     /* Destructor */
183565){
183566  DbClientData *p, **pp;
183567  sqlite3_mutex_enter(db->mutex);
183568  pp = &db->pDbData;
183569  for(p=db->pDbData; p && strcmp(p->zName,zName); p=p->pNext){
183570    pp = &p->pNext;
183571  }
183572  if( p ){
183573    assert( p->pData!=0 );
183574    if( p->xDestructor ) p->xDestructor(p->pData);
183575    if( pData==0 ){
183576      *pp = p->pNext;
183577      sqlite3_free(p);
183578      sqlite3_mutex_leave(db->mutex);
183579      return SQLITE_OK;
183580    }
183581  }else if( pData==0 ){
183582    sqlite3_mutex_leave(db->mutex);
183583    return SQLITE_OK;
183584  }else{
183585    size_t n = strlen(zName);
183586    p = sqlite3_malloc64( sizeof(DbClientData)+n+1 );
183587    if( p==0 ){
183588      if( xDestructor ) xDestructor(pData);
183589      sqlite3_mutex_leave(db->mutex);
183590      return SQLITE_NOMEM;
183591    }
183592    memcpy(p->zName, zName, n+1);
183593    p->pNext = db->pDbData;
183594    db->pDbData = p;
183595  }
183596  p->pData = pData;
183597  p->xDestructor = xDestructor;
183598  sqlite3_mutex_leave(db->mutex);
183599  return SQLITE_OK;
183600}
183601
183602
183603#ifndef SQLITE_OMIT_DEPRECATED
183604/*
183605** This function is now an anachronism. It used to be used to recover from a
183606** malloc() failure, but SQLite now does this automatically.
183607*/
183608SQLITE_API int sqlite3_global_recover(void){
183609  return SQLITE_OK;
183610}
183611#endif
183612
183613/*
183614** Test to see whether or not the database connection is in autocommit
183615** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
183616** by default.  Autocommit is disabled by a BEGIN statement and reenabled
183617** by the next COMMIT or ROLLBACK.
183618*/
183619SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
183620#ifdef SQLITE_ENABLE_API_ARMOR
183621  if( !sqlite3SafetyCheckOk(db) ){
183622    (void)SQLITE_MISUSE_BKPT;
183623    return 0;
183624  }
183625#endif
183626  return db->autoCommit;
183627}
183628
183629/*
183630** The following routines are substitutes for constants SQLITE_CORRUPT,
183631** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
183632** constants.  They serve two purposes:
183633**
183634**   1.  Serve as a convenient place to set a breakpoint in a debugger
183635**       to detect when version error conditions occurs.
183636**
183637**   2.  Invoke sqlite3_log() to provide the source code location where
183638**       a low-level error is first detected.
183639*/
183640SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType){
183641  sqlite3_log(iErr, "%s at line %d of [%.10s]",
183642              zType, lineno, 20+sqlite3_sourceid());
183643  return iErr;
183644}
183645SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
183646  testcase( sqlite3GlobalConfig.xLog!=0 );
183647  return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
183648}
183649SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
183650  testcase( sqlite3GlobalConfig.xLog!=0 );
183651  return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
183652}
183653SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
183654  testcase( sqlite3GlobalConfig.xLog!=0 );
183655  return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
183656}
183657#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
183658SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
183659  char zMsg[100];
183660  sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
183661  testcase( sqlite3GlobalConfig.xLog!=0 );
183662  return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
183663}
183664#endif
183665#ifdef SQLITE_DEBUG
183666SQLITE_PRIVATE int sqlite3NomemError(int lineno){
183667  testcase( sqlite3GlobalConfig.xLog!=0 );
183668  return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
183669}
183670SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
183671  testcase( sqlite3GlobalConfig.xLog!=0 );
183672  return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
183673}
183674#endif
183675
183676#ifndef SQLITE_OMIT_DEPRECATED
183677/*
183678** This is a convenience routine that makes sure that all thread-specific
183679** data for this thread has been deallocated.
183680**
183681** SQLite no longer uses thread-specific data so this routine is now a
183682** no-op.  It is retained for historical compatibility.
183683*/
183684SQLITE_API void sqlite3_thread_cleanup(void){
183685}
183686#endif
183687
183688/*
183689** Return meta information about a specific column of a database table.
183690** See comment in sqlite3.h (sqlite.h.in) for details.
183691*/
183692SQLITE_API int sqlite3_table_column_metadata(
183693  sqlite3 *db,                /* Connection handle */
183694  const char *zDbName,        /* Database name or NULL */
183695  const char *zTableName,     /* Table name */
183696  const char *zColumnName,    /* Column name */
183697  char const **pzDataType,    /* OUTPUT: Declared data type */
183698  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
183699  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
183700  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
183701  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
183702){
183703  int rc;
183704  char *zErrMsg = 0;
183705  Table *pTab = 0;
183706  Column *pCol = 0;
183707  int iCol = 0;
183708  char const *zDataType = 0;
183709  char const *zCollSeq = 0;
183710  int notnull = 0;
183711  int primarykey = 0;
183712  int autoinc = 0;
183713
183714
183715#ifdef SQLITE_ENABLE_API_ARMOR
183716  if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
183717    return SQLITE_MISUSE_BKPT;
183718  }
183719#endif
183720
183721  /* Ensure the database schema has been loaded */
183722  sqlite3_mutex_enter(db->mutex);
183723  sqlite3BtreeEnterAll(db);
183724  rc = sqlite3Init(db, &zErrMsg);
183725  if( SQLITE_OK!=rc ){
183726    goto error_out;
183727  }
183728
183729  /* Locate the table in question */
183730  pTab = sqlite3FindTable(db, zTableName, zDbName);
183731  if( !pTab || IsView(pTab) ){
183732    pTab = 0;
183733    goto error_out;
183734  }
183735
183736  /* Find the column for which info is requested */
183737  if( zColumnName==0 ){
183738    /* Query for existence of table only */
183739  }else{
183740    for(iCol=0; iCol<pTab->nCol; iCol++){
183741      pCol = &pTab->aCol[iCol];
183742      if( 0==sqlite3StrICmp(pCol->zCnName, zColumnName) ){
183743        break;
183744      }
183745    }
183746    if( iCol==pTab->nCol ){
183747      if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
183748        iCol = pTab->iPKey;
183749        pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
183750      }else{
183751        pTab = 0;
183752        goto error_out;
183753      }
183754    }
183755  }
183756
183757  /* The following block stores the meta information that will be returned
183758  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
183759  ** and autoinc. At this point there are two possibilities:
183760  **
183761  **     1. The specified column name was rowid", "oid" or "_rowid_"
183762  **        and there is no explicitly declared IPK column.
183763  **
183764  **     2. The table is not a view and the column name identified an
183765  **        explicitly declared column. Copy meta information from *pCol.
183766  */
183767  if( pCol ){
183768    zDataType = sqlite3ColumnType(pCol,0);
183769    zCollSeq = sqlite3ColumnColl(pCol);
183770    notnull = pCol->notNull!=0;
183771    primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
183772    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
183773  }else{
183774    zDataType = "INTEGER";
183775    primarykey = 1;
183776  }
183777  if( !zCollSeq ){
183778    zCollSeq = sqlite3StrBINARY;
183779  }
183780
183781error_out:
183782  sqlite3BtreeLeaveAll(db);
183783
183784  /* Whether the function call succeeded or failed, set the output parameters
183785  ** to whatever their local counterparts contain. If an error did occur,
183786  ** this has the effect of zeroing all output parameters.
183787  */
183788  if( pzDataType ) *pzDataType = zDataType;
183789  if( pzCollSeq ) *pzCollSeq = zCollSeq;
183790  if( pNotNull ) *pNotNull = notnull;
183791  if( pPrimaryKey ) *pPrimaryKey = primarykey;
183792  if( pAutoinc ) *pAutoinc = autoinc;
183793
183794  if( SQLITE_OK==rc && !pTab ){
183795    sqlite3DbFree(db, zErrMsg);
183796    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
183797        zColumnName);
183798    rc = SQLITE_ERROR;
183799  }
183800  sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
183801  sqlite3DbFree(db, zErrMsg);
183802  rc = sqlite3ApiExit(db, rc);
183803  sqlite3_mutex_leave(db->mutex);
183804  return rc;
183805}
183806
183807/*
183808** Sleep for a little while.  Return the amount of time slept.
183809*/
183810SQLITE_API int sqlite3_sleep(int ms){
183811  sqlite3_vfs *pVfs;
183812  int rc;
183813  pVfs = sqlite3_vfs_find(0);
183814  if( pVfs==0 ) return 0;
183815
183816  /* This function works in milliseconds, but the underlying OsSleep()
183817  ** API uses microseconds. Hence the 1000's.
183818  */
183819  rc = (sqlite3OsSleep(pVfs, ms<0 ? 0 : 1000*ms)/1000);
183820  return rc;
183821}
183822
183823/*
183824** Enable or disable the extended result codes.
183825*/
183826SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
183827#ifdef SQLITE_ENABLE_API_ARMOR
183828  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
183829#endif
183830  sqlite3_mutex_enter(db->mutex);
183831  db->errMask = onoff ? 0xffffffff : 0xff;
183832  sqlite3_mutex_leave(db->mutex);
183833  return SQLITE_OK;
183834}
183835
183836/*
183837** Invoke the xFileControl method on a particular database.
183838*/
183839SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
183840  int rc = SQLITE_ERROR;
183841  Btree *pBtree;
183842
183843#ifdef SQLITE_ENABLE_API_ARMOR
183844  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
183845#endif
183846  sqlite3_mutex_enter(db->mutex);
183847  pBtree = sqlite3DbNameToBtree(db, zDbName);
183848  if( pBtree ){
183849    Pager *pPager;
183850    sqlite3_file *fd;
183851    sqlite3BtreeEnter(pBtree);
183852    pPager = sqlite3BtreePager(pBtree);
183853    assert( pPager!=0 );
183854    fd = sqlite3PagerFile(pPager);
183855    assert( fd!=0 );
183856    if( op==SQLITE_FCNTL_FILE_POINTER ){
183857      *(sqlite3_file**)pArg = fd;
183858      rc = SQLITE_OK;
183859    }else if( op==SQLITE_FCNTL_VFS_POINTER ){
183860      *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
183861      rc = SQLITE_OK;
183862    }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
183863      *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
183864      rc = SQLITE_OK;
183865    }else if( op==SQLITE_FCNTL_DATA_VERSION ){
183866      *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
183867      rc = SQLITE_OK;
183868    }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){
183869      int iNew = *(int*)pArg;
183870      *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);
183871      if( iNew>=0 && iNew<=255 ){
183872        sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);
183873      }
183874      rc = SQLITE_OK;
183875    }else if( op==SQLITE_FCNTL_RESET_CACHE ){
183876      sqlite3BtreeClearCache(pBtree);
183877      rc = SQLITE_OK;
183878    }else{
183879      int nSave = db->busyHandler.nBusy;
183880      rc = sqlite3OsFileControl(fd, op, pArg);
183881      db->busyHandler.nBusy = nSave;
183882    }
183883    sqlite3BtreeLeave(pBtree);
183884  }
183885  sqlite3_mutex_leave(db->mutex);
183886  return rc;
183887}
183888
183889/*
183890** Interface to the testing logic.
183891*/
183892SQLITE_API int sqlite3_test_control(int op, ...){
183893  int rc = 0;
183894#ifdef SQLITE_UNTESTABLE
183895  UNUSED_PARAMETER(op);
183896#else
183897  va_list ap;
183898  va_start(ap, op);
183899  switch( op ){
183900
183901    /*
183902    ** Save the current state of the PRNG.
183903    */
183904    case SQLITE_TESTCTRL_PRNG_SAVE: {
183905      sqlite3PrngSaveState();
183906      break;
183907    }
183908
183909    /*
183910    ** Restore the state of the PRNG to the last state saved using
183911    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
183912    ** this verb acts like PRNG_RESET.
183913    */
183914    case SQLITE_TESTCTRL_PRNG_RESTORE: {
183915      sqlite3PrngRestoreState();
183916      break;
183917    }
183918
183919    /*  sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
183920    **
183921    ** Control the seed for the pseudo-random number generator (PRNG) that
183922    ** is built into SQLite.  Cases:
183923    **
183924    **    x!=0 && db!=0       Seed the PRNG to the current value of the
183925    **                        schema cookie in the main database for db, or
183926    **                        x if the schema cookie is zero.  This case
183927    **                        is convenient to use with database fuzzers
183928    **                        as it allows the fuzzer some control over the
183929    **                        the PRNG seed.
183930    **
183931    **    x!=0 && db==0       Seed the PRNG to the value of x.
183932    **
183933    **    x==0 && db==0       Revert to default behavior of using the
183934    **                        xRandomness method on the primary VFS.
183935    **
183936    ** This test-control also resets the PRNG so that the new seed will
183937    ** be used for the next call to sqlite3_randomness().
183938    */
183939#ifndef SQLITE_OMIT_WSD
183940    case SQLITE_TESTCTRL_PRNG_SEED: {
183941      int x = va_arg(ap, int);
183942      int y;
183943      sqlite3 *db = va_arg(ap, sqlite3*);
183944      assert( db==0 || db->aDb[0].pSchema!=0 );
183945      if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; }
183946      sqlite3Config.iPrngSeed = x;
183947      sqlite3_randomness(0,0);
183948      break;
183949    }
183950#endif
183951
183952    /*  sqlite3_test_control(SQLITE_TESTCTRL_FK_NO_ACTION, sqlite3 *db, int b);
183953    **
183954    ** If b is true, then activate the SQLITE_FkNoAction setting.  If b is
183955    ** false then clearn that setting.  If the SQLITE_FkNoAction setting is
183956    ** abled, all foreign key ON DELETE and ON UPDATE actions behave as if
183957    ** they were NO ACTION, regardless of how they are defined.
183958    **
183959    ** NB:  One must usually run "PRAGMA writable_schema=RESET" after
183960    ** using this test-control, before it will take full effect.  failing
183961    ** to reset the schema can result in some unexpected behavior.
183962    */
183963    case SQLITE_TESTCTRL_FK_NO_ACTION: {
183964      sqlite3 *db = va_arg(ap, sqlite3*);
183965      int b = va_arg(ap, int);
183966      if( b ){
183967        db->flags |= SQLITE_FkNoAction;
183968      }else{
183969        db->flags &= ~SQLITE_FkNoAction;
183970      }
183971      break;
183972    }
183973
183974    /*
183975    **  sqlite3_test_control(BITVEC_TEST, size, program)
183976    **
183977    ** Run a test against a Bitvec object of size.  The program argument
183978    ** is an array of integers that defines the test.  Return -1 on a
183979    ** memory allocation error, 0 on success, or non-zero for an error.
183980    ** See the sqlite3BitvecBuiltinTest() for additional information.
183981    */
183982    case SQLITE_TESTCTRL_BITVEC_TEST: {
183983      int sz = va_arg(ap, int);
183984      int *aProg = va_arg(ap, int*);
183985      rc = sqlite3BitvecBuiltinTest(sz, aProg);
183986      break;
183987    }
183988
183989    /*
183990    **  sqlite3_test_control(FAULT_INSTALL, xCallback)
183991    **
183992    ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
183993    ** if xCallback is not NULL.
183994    **
183995    ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
183996    ** is called immediately after installing the new callback and the return
183997    ** value from sqlite3FaultSim(0) becomes the return from
183998    ** sqlite3_test_control().
183999    */
184000    case SQLITE_TESTCTRL_FAULT_INSTALL: {
184001      /* A bug in MSVC prevents it from understanding pointers to functions
184002      ** types in the second argument to va_arg().  Work around the problem
184003      ** using a typedef.
184004      ** http://support.microsoft.com/kb/47961  <-- dead hyperlink
184005      ** Search at http://web.archive.org/ to find the 2015-03-16 archive
184006      ** of the link above to see the original text.
184007      ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
184008      */
184009      typedef int(*sqlite3FaultFuncType)(int);
184010      sqlite3GlobalConfig.xTestCallback = va_arg(ap, sqlite3FaultFuncType);
184011      rc = sqlite3FaultSim(0);
184012      break;
184013    }
184014
184015    /*
184016    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
184017    **
184018    ** Register hooks to call to indicate which malloc() failures
184019    ** are benign.
184020    */
184021    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
184022      typedef void (*void_function)(void);
184023      void_function xBenignBegin;
184024      void_function xBenignEnd;
184025      xBenignBegin = va_arg(ap, void_function);
184026      xBenignEnd = va_arg(ap, void_function);
184027      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
184028      break;
184029    }
184030
184031    /*
184032    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
184033    **
184034    ** Set the PENDING byte to the value in the argument, if X>0.
184035    ** Make no changes if X==0.  Return the value of the pending byte
184036    ** as it existing before this routine was called.
184037    **
184038    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
184039    ** an incompatible database file format.  Changing the PENDING byte
184040    ** while any database connection is open results in undefined and
184041    ** deleterious behavior.
184042    */
184043    case SQLITE_TESTCTRL_PENDING_BYTE: {
184044      rc = PENDING_BYTE;
184045#ifndef SQLITE_OMIT_WSD
184046      {
184047        unsigned int newVal = va_arg(ap, unsigned int);
184048        if( newVal ) sqlite3PendingByte = newVal;
184049      }
184050#endif
184051      break;
184052    }
184053
184054    /*
184055    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
184056    **
184057    ** This action provides a run-time test to see whether or not
184058    ** assert() was enabled at compile-time.  If X is true and assert()
184059    ** is enabled, then the return value is true.  If X is true and
184060    ** assert() is disabled, then the return value is zero.  If X is
184061    ** false and assert() is enabled, then the assertion fires and the
184062    ** process aborts.  If X is false and assert() is disabled, then the
184063    ** return value is zero.
184064    */
184065    case SQLITE_TESTCTRL_ASSERT: {
184066      volatile int x = 0;
184067      assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
184068      rc = x;
184069#if defined(SQLITE_DEBUG)
184070      /* Invoke these debugging routines so that the compiler does not
184071      ** issue "defined but not used" warnings. */
184072      if( x==9999 ){
184073        sqlite3ShowExpr(0);
184074        sqlite3ShowExpr(0);
184075        sqlite3ShowExprList(0);
184076        sqlite3ShowIdList(0);
184077        sqlite3ShowSrcList(0);
184078        sqlite3ShowWith(0);
184079        sqlite3ShowUpsert(0);
184080#ifndef SQLITE_OMIT_TRIGGER
184081        sqlite3ShowTriggerStep(0);
184082        sqlite3ShowTriggerStepList(0);
184083        sqlite3ShowTrigger(0);
184084        sqlite3ShowTriggerList(0);
184085#endif
184086#ifndef SQLITE_OMIT_WINDOWFUNC
184087        sqlite3ShowWindow(0);
184088        sqlite3ShowWinFunc(0);
184089#endif
184090        sqlite3ShowSelect(0);
184091      }
184092#endif
184093      break;
184094    }
184095
184096
184097    /*
184098    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
184099    **
184100    ** This action provides a run-time test to see how the ALWAYS and
184101    ** NEVER macros were defined at compile-time.
184102    **
184103    ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
184104    **
184105    ** The recommended test is X==2.  If the return value is 2, that means
184106    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
184107    ** default setting.  If the return value is 1, then ALWAYS() is either
184108    ** hard-coded to true or else it asserts if its argument is false.
184109    ** The first behavior (hard-coded to true) is the case if
184110    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
184111    ** behavior (assert if the argument to ALWAYS() is false) is the case if
184112    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
184113    **
184114    ** The run-time test procedure might look something like this:
184115    **
184116    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
184117    **      // ALWAYS() and NEVER() are no-op pass-through macros
184118    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
184119    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
184120    **    }else{
184121    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
184122    **    }
184123    */
184124    case SQLITE_TESTCTRL_ALWAYS: {
184125      int x = va_arg(ap,int);
184126      rc = x ? ALWAYS(x) : 0;
184127      break;
184128    }
184129
184130    /*
184131    **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
184132    **
184133    ** The integer returned reveals the byte-order of the computer on which
184134    ** SQLite is running:
184135    **
184136    **       1     big-endian,    determined at run-time
184137    **      10     little-endian, determined at run-time
184138    **  432101     big-endian,    determined at compile-time
184139    **  123410     little-endian, determined at compile-time
184140    */
184141    case SQLITE_TESTCTRL_BYTEORDER: {
184142      rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
184143      break;
184144    }
184145
184146    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
184147    **
184148    ** Enable or disable various optimizations for testing purposes.  The
184149    ** argument N is a bitmask of optimizations to be disabled.  For normal
184150    ** operation N should be 0.  The idea is that a test program (like the
184151    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
184152    ** with various optimizations disabled to verify that the same answer
184153    ** is obtained in every case.
184154    */
184155    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
184156      sqlite3 *db = va_arg(ap, sqlite3*);
184157      db->dbOptFlags = va_arg(ap, u32);
184158      break;
184159    }
184160
184161    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
184162    **
184163    ** If parameter onoff is 1, subsequent calls to localtime() fail.
184164    ** If 2, then invoke xAlt() instead of localtime().  If 0, normal
184165    ** processing.
184166    **
184167    ** xAlt arguments are void pointers, but they really want to be:
184168    **
184169    **    int xAlt(const time_t*, struct tm*);
184170    **
184171    ** xAlt should write results in to struct tm object of its 2nd argument
184172    ** and return zero on success, or return non-zero on failure.
184173    */
184174    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
184175      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
184176      if( sqlite3GlobalConfig.bLocaltimeFault==2 ){
184177        typedef int(*sqlite3LocaltimeType)(const void*,void*);
184178        sqlite3GlobalConfig.xAltLocaltime = va_arg(ap, sqlite3LocaltimeType);
184179      }else{
184180        sqlite3GlobalConfig.xAltLocaltime = 0;
184181      }
184182      break;
184183    }
184184
184185    /*   sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
184186    **
184187    ** Toggle the ability to use internal functions on or off for
184188    ** the database connection given in the argument.
184189    */
184190    case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
184191      sqlite3 *db = va_arg(ap, sqlite3*);
184192      db->mDbFlags ^= DBFLAG_InternalFunc;
184193      break;
184194    }
184195
184196    /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
184197    **
184198    ** Set or clear a flag that indicates that the database file is always well-
184199    ** formed and never corrupt.  This flag is clear by default, indicating that
184200    ** database files might have arbitrary corruption.  Setting the flag during
184201    ** testing causes certain assert() statements in the code to be activated
184202    ** that demonstrate invariants on well-formed database files.
184203    */
184204    case SQLITE_TESTCTRL_NEVER_CORRUPT: {
184205      sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
184206      break;
184207    }
184208
184209    /*   sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
184210    **
184211    ** Set or clear a flag that causes SQLite to verify that type, name,
184212    ** and tbl_name fields of the sqlite_schema table.  This is normally
184213    ** on, but it is sometimes useful to turn it off for testing.
184214    **
184215    ** 2020-07-22:  Disabling EXTRA_SCHEMA_CHECKS also disables the
184216    ** verification of rootpage numbers when parsing the schema.  This
184217    ** is useful to make it easier to reach strange internal error states
184218    ** during testing.  The EXTRA_SCHEMA_CHECKS setting is always enabled
184219    ** in production.
184220    */
184221    case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {
184222      sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);
184223      break;
184224    }
184225
184226    /* Set the threshold at which OP_Once counters reset back to zero.
184227    ** By default this is 0x7ffffffe (over 2 billion), but that value is
184228    ** too big to test in a reasonable amount of time, so this control is
184229    ** provided to set a small and easily reachable reset value.
184230    */
184231    case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
184232      sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
184233      break;
184234    }
184235
184236    /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
184237    **
184238    ** Set the VDBE coverage callback function to xCallback with context
184239    ** pointer ptr.
184240    */
184241    case SQLITE_TESTCTRL_VDBE_COVERAGE: {
184242#ifdef SQLITE_VDBE_COVERAGE
184243      typedef void (*branch_callback)(void*,unsigned int,
184244                                      unsigned char,unsigned char);
184245      sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
184246      sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
184247#endif
184248      break;
184249    }
184250
184251    /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
184252    case SQLITE_TESTCTRL_SORTER_MMAP: {
184253      sqlite3 *db = va_arg(ap, sqlite3*);
184254      db->nMaxSorterMmap = va_arg(ap, int);
184255      break;
184256    }
184257
184258    /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
184259    **
184260    ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
184261    ** not.
184262    */
184263    case SQLITE_TESTCTRL_ISINIT: {
184264      if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
184265      break;
184266    }
184267
184268    /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
184269    **
184270    ** This test control is used to create imposter tables.  "db" is a pointer
184271    ** to the database connection.  dbName is the database name (ex: "main" or
184272    ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
184273    ** or off.  "tnum" is the root page of the b-tree to which the imposter
184274    ** table should connect.
184275    **
184276    ** Enable imposter mode only when the schema has already been parsed.  Then
184277    ** run a single CREATE TABLE statement to construct the imposter table in
184278    ** the parsed schema.  Then turn imposter mode back off again.
184279    **
184280    ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
184281    ** the schema to be reparsed the next time it is needed.  This has the
184282    ** effect of erasing all imposter tables.
184283    */
184284    case SQLITE_TESTCTRL_IMPOSTER: {
184285      sqlite3 *db = va_arg(ap, sqlite3*);
184286      int iDb;
184287      sqlite3_mutex_enter(db->mutex);
184288      iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
184289      if( iDb>=0 ){
184290        db->init.iDb = iDb;
184291        db->init.busy = db->init.imposterTable = va_arg(ap,int);
184292        db->init.newTnum = va_arg(ap,int);
184293        if( db->init.busy==0 && db->init.newTnum>0 ){
184294          sqlite3ResetAllSchemasOfConnection(db);
184295        }
184296      }
184297      sqlite3_mutex_leave(db->mutex);
184298      break;
184299    }
184300
184301#if defined(YYCOVERAGE)
184302    /*  sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
184303    **
184304    ** This test control (only available when SQLite is compiled with
184305    ** -DYYCOVERAGE) writes a report onto "out" that shows all
184306    ** state/lookahead combinations in the parser state machine
184307    ** which are never exercised.  If any state is missed, make the
184308    ** return code SQLITE_ERROR.
184309    */
184310    case SQLITE_TESTCTRL_PARSER_COVERAGE: {
184311      FILE *out = va_arg(ap, FILE*);
184312      if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
184313      break;
184314    }
184315#endif /* defined(YYCOVERAGE) */
184316
184317    /*  sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
184318    **
184319    ** This test-control causes the most recent sqlite3_result_int64() value
184320    ** to be interpreted as a MEM_IntReal instead of as an MEM_Int.  Normally,
184321    ** MEM_IntReal values only arise during an INSERT operation of integer
184322    ** values into a REAL column, so they can be challenging to test.  This
184323    ** test-control enables us to write an intreal() SQL function that can
184324    ** inject an intreal() value at arbitrary places in an SQL statement,
184325    ** for testing purposes.
184326    */
184327    case SQLITE_TESTCTRL_RESULT_INTREAL: {
184328      sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);
184329      sqlite3ResultIntReal(pCtx);
184330      break;
184331    }
184332
184333    /*  sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
184334    **    sqlite3 *db,    // Database connection
184335    **    u64 *pnSeek     // Write seek count here
184336    **  );
184337    **
184338    ** This test-control queries the seek-counter on the "main" database
184339    ** file.  The seek-counter is written into *pnSeek and is then reset.
184340    ** The seek-count is only available if compiled with SQLITE_DEBUG.
184341    */
184342    case SQLITE_TESTCTRL_SEEK_COUNT: {
184343      sqlite3 *db = va_arg(ap, sqlite3*);
184344      u64 *pn = va_arg(ap, sqlite3_uint64*);
184345      *pn = sqlite3BtreeSeekCount(db->aDb->pBt);
184346      (void)db;  /* Silence harmless unused variable warning */
184347      break;
184348    }
184349
184350    /*  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, op, ptr)
184351    **
184352    **  "ptr" is a pointer to a u32.
184353    **
184354    **   op==0       Store the current sqlite3TreeTrace in *ptr
184355    **   op==1       Set sqlite3TreeTrace to the value *ptr
184356    **   op==2       Store the current sqlite3WhereTrace in *ptr
184357    **   op==3       Set sqlite3WhereTrace to the value *ptr
184358    */
184359    case SQLITE_TESTCTRL_TRACEFLAGS: {
184360       int opTrace = va_arg(ap, int);
184361       u32 *ptr = va_arg(ap, u32*);
184362       switch( opTrace ){
184363         case 0:   *ptr = sqlite3TreeTrace;      break;
184364         case 1:   sqlite3TreeTrace = *ptr;      break;
184365         case 2:   *ptr = sqlite3WhereTrace;     break;
184366         case 3:   sqlite3WhereTrace = *ptr;     break;
184367       }
184368       break;
184369    }
184370
184371    /* sqlite3_test_control(SQLITE_TESTCTRL_LOGEST,
184372    **      double fIn,     // Input value
184373    **      int *pLogEst,   // sqlite3LogEstFromDouble(fIn)
184374    **      u64 *pInt,      // sqlite3LogEstToInt(*pLogEst)
184375    **      int *pLogEst2   // sqlite3LogEst(*pInt)
184376    ** );
184377    **
184378    ** Test access for the LogEst conversion routines.
184379    */
184380    case SQLITE_TESTCTRL_LOGEST: {
184381      double rIn = va_arg(ap, double);
184382      LogEst rLogEst = sqlite3LogEstFromDouble(rIn);
184383      int *pI1 = va_arg(ap,int*);
184384      u64 *pU64 = va_arg(ap,u64*);
184385      int *pI2 = va_arg(ap,int*);
184386      *pI1 = rLogEst;
184387      *pU64 = sqlite3LogEstToInt(rLogEst);
184388      *pI2 = sqlite3LogEst(*pU64);
184389      break;
184390    }
184391
184392#if !defined(SQLITE_OMIT_WSD)
184393    /* sqlite3_test_control(SQLITE_TESTCTRL_USELONGDOUBLE, int X);
184394    **
184395    **   X<0     Make no changes to the bUseLongDouble.  Just report value.
184396    **   X==0    Disable bUseLongDouble
184397    **   X==1    Enable bUseLongDouble
184398    **   X>=2    Set bUseLongDouble to its default value for this platform
184399    */
184400    case SQLITE_TESTCTRL_USELONGDOUBLE: {
184401      int b = va_arg(ap, int);
184402      if( b>=2 ) b = hasHighPrecisionDouble(b);
184403      if( b>=0 ) sqlite3Config.bUseLongDouble = b>0;
184404      rc = sqlite3Config.bUseLongDouble!=0;
184405      break;
184406    }
184407#endif
184408
184409
184410#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
184411    /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
184412    **
184413    ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
184414    ** of the id-th tuning parameter to *piValue.  If "id" is between -1
184415    ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
184416    ** tuning parameter into *piValue.
184417    **
184418    ** Tuning parameters are for use during transient development builds,
184419    ** to help find the best values for constants in the query planner.
184420    ** Access tuning parameters using the Tuning(ID) macro.  Set the
184421    ** parameters in the CLI using ".testctrl tune ID VALUE".
184422    **
184423    ** Transient use only.  Tuning parameters should not be used in
184424    ** checked-in code.
184425    */
184426    case SQLITE_TESTCTRL_TUNE: {
184427      int id = va_arg(ap, int);
184428      int *piValue = va_arg(ap, int*);
184429      if( id>0 && id<=SQLITE_NTUNE ){
184430        Tuning(id) = *piValue;
184431      }else if( id<0 && id>=-SQLITE_NTUNE ){
184432        *piValue = Tuning(-id);
184433      }else{
184434        rc = SQLITE_NOTFOUND;
184435      }
184436      break;
184437    }
184438#endif
184439
184440    /* sqlite3_test_control(SQLITE_TESTCTRL_JSON_SELFCHECK, &onOff);
184441    **
184442    ** Activate or deactivate validation of JSONB that is generated from
184443    ** text.  Off by default, as the validation is slow.  Validation is
184444    ** only available if compiled using SQLITE_DEBUG.
184445    **
184446    ** If onOff is initially 1, then turn it on.  If onOff is initially
184447    ** off, turn it off.  If onOff is initially -1, then change onOff
184448    ** to be the current setting.
184449    */
184450    case SQLITE_TESTCTRL_JSON_SELFCHECK: {
184451#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
184452      int *pOnOff = va_arg(ap, int*);
184453      if( *pOnOff<0 ){
184454        *pOnOff = sqlite3Config.bJsonSelfcheck;
184455      }else{
184456        sqlite3Config.bJsonSelfcheck = (u8)((*pOnOff)&0xff);
184457      }
184458#endif
184459      break;
184460    }
184461  }
184462  va_end(ap);
184463#endif /* SQLITE_UNTESTABLE */
184464  return rc;
184465}
184466
184467/*
184468** The Pager stores the Database filename, Journal filename, and WAL filename
184469** consecutively in memory, in that order.  The database filename is prefixed
184470** by four zero bytes.  Locate the start of the database filename by searching
184471** backwards for the first byte following four consecutive zero bytes.
184472**
184473** This only works if the filename passed in was obtained from the Pager.
184474*/
184475static const char *databaseName(const char *zName){
184476  while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
184477    zName--;
184478  }
184479  return zName;
184480}
184481
184482/*
184483** Append text z[] to the end of p[].  Return a pointer to the first
184484** character after then zero terminator on the new text in p[].
184485*/
184486static char *appendText(char *p, const char *z){
184487  size_t n = strlen(z);
184488  memcpy(p, z, n+1);
184489  return p+n+1;
184490}
184491
184492/*
184493** Allocate memory to hold names for a database, journal file, WAL file,
184494** and query parameters.  The pointer returned is valid for use by
184495** sqlite3_filename_database() and sqlite3_uri_parameter() and related
184496** functions.
184497**
184498** Memory layout must be compatible with that generated by the pager
184499** and expected by sqlite3_uri_parameter() and databaseName().
184500*/
184501SQLITE_API const char *sqlite3_create_filename(
184502  const char *zDatabase,
184503  const char *zJournal,
184504  const char *zWal,
184505  int nParam,
184506  const char **azParam
184507){
184508  sqlite3_int64 nByte;
184509  int i;
184510  char *pResult, *p;
184511  nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;
184512  for(i=0; i<nParam*2; i++){
184513    nByte += strlen(azParam[i])+1;
184514  }
184515  pResult = p = sqlite3_malloc64( nByte );
184516  if( p==0 ) return 0;
184517  memset(p, 0, 4);
184518  p += 4;
184519  p = appendText(p, zDatabase);
184520  for(i=0; i<nParam*2; i++){
184521    p = appendText(p, azParam[i]);
184522  }
184523  *(p++) = 0;
184524  p = appendText(p, zJournal);
184525  p = appendText(p, zWal);
184526  *(p++) = 0;
184527  *(p++) = 0;
184528  assert( (sqlite3_int64)(p - pResult)==nByte );
184529  return pResult + 4;
184530}
184531
184532/*
184533** Free memory obtained from sqlite3_create_filename().  It is a severe
184534** error to call this routine with any parameter other than a pointer
184535** previously obtained from sqlite3_create_filename() or a NULL pointer.
184536*/
184537SQLITE_API void sqlite3_free_filename(const char *p){
184538  if( p==0 ) return;
184539  p = databaseName(p);
184540  sqlite3_free((char*)p - 4);
184541}
184542
184543
184544/*
184545** This is a utility routine, useful to VFS implementations, that checks
184546** to see if a database file was a URI that contained a specific query
184547** parameter, and if so obtains the value of the query parameter.
184548**
184549** The zFilename argument is the filename pointer passed into the xOpen()
184550** method of a VFS implementation.  The zParam argument is the name of the
184551** query parameter we seek.  This routine returns the value of the zParam
184552** parameter if it exists.  If the parameter does not exist, this routine
184553** returns a NULL pointer.
184554*/
184555SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
184556  if( zFilename==0 || zParam==0 ) return 0;
184557  zFilename = databaseName(zFilename);
184558  return uriParameter(zFilename, zParam);
184559}
184560
184561/*
184562** Return a pointer to the name of Nth query parameter of the filename.
184563*/
184564SQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N){
184565  if( zFilename==0 || N<0 ) return 0;
184566  zFilename = databaseName(zFilename);
184567  zFilename += sqlite3Strlen30(zFilename) + 1;
184568  while( ALWAYS(zFilename) && zFilename[0] && (N--)>0 ){
184569    zFilename += sqlite3Strlen30(zFilename) + 1;
184570    zFilename += sqlite3Strlen30(zFilename) + 1;
184571  }
184572  return zFilename[0] ? zFilename : 0;
184573}
184574
184575/*
184576** Return a boolean value for a query parameter.
184577*/
184578SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
184579  const char *z = sqlite3_uri_parameter(zFilename, zParam);
184580  bDflt = bDflt!=0;
184581  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
184582}
184583
184584/*
184585** Return a 64-bit integer value for a query parameter.
184586*/
184587SQLITE_API sqlite3_int64 sqlite3_uri_int64(
184588  const char *zFilename,    /* Filename as passed to xOpen */
184589  const char *zParam,       /* URI parameter sought */
184590  sqlite3_int64 bDflt       /* return if parameter is missing */
184591){
184592  const char *z = sqlite3_uri_parameter(zFilename, zParam);
184593  sqlite3_int64 v;
184594  if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
184595    bDflt = v;
184596  }
184597  return bDflt;
184598}
184599
184600/*
184601** Translate a filename that was handed to a VFS routine into the corresponding
184602** database, journal, or WAL file.
184603**
184604** It is an error to pass this routine a filename string that was not
184605** passed into the VFS from the SQLite core.  Doing so is similar to
184606** passing free() a pointer that was not obtained from malloc() - it is
184607** an error that we cannot easily detect but that will likely cause memory
184608** corruption.
184609*/
184610SQLITE_API const char *sqlite3_filename_database(const char *zFilename){
184611  if( zFilename==0 ) return 0;
184612  return databaseName(zFilename);
184613}
184614SQLITE_API const char *sqlite3_filename_journal(const char *zFilename){
184615  if( zFilename==0 ) return 0;
184616  zFilename = databaseName(zFilename);
184617  zFilename += sqlite3Strlen30(zFilename) + 1;
184618  while( ALWAYS(zFilename) && zFilename[0] ){
184619    zFilename += sqlite3Strlen30(zFilename) + 1;
184620    zFilename += sqlite3Strlen30(zFilename) + 1;
184621  }
184622  return zFilename + 1;
184623}
184624SQLITE_API const char *sqlite3_filename_wal(const char *zFilename){
184625#ifdef SQLITE_OMIT_WAL
184626  return 0;
184627#else
184628  zFilename = sqlite3_filename_journal(zFilename);
184629  if( zFilename ) zFilename += sqlite3Strlen30(zFilename) + 1;
184630  return zFilename;
184631#endif
184632}
184633
184634/*
184635** Return the Btree pointer identified by zDbName.  Return NULL if not found.
184636*/
184637SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
184638  int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
184639  return iDb<0 ? 0 : db->aDb[iDb].pBt;
184640}
184641
184642/*
184643** Return the name of the N-th database schema.  Return NULL if N is out
184644** of range.
184645*/
184646SQLITE_API const char *sqlite3_db_name(sqlite3 *db, int N){
184647#ifdef SQLITE_ENABLE_API_ARMOR
184648  if( !sqlite3SafetyCheckOk(db) ){
184649    (void)SQLITE_MISUSE_BKPT;
184650    return 0;
184651  }
184652#endif
184653  if( N<0 || N>=db->nDb ){
184654    return 0;
184655  }else{
184656    return db->aDb[N].zDbSName;
184657  }
184658}
184659
184660/*
184661** Return the filename of the database associated with a database
184662** connection.
184663*/
184664SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
184665  Btree *pBt;
184666#ifdef SQLITE_ENABLE_API_ARMOR
184667  if( !sqlite3SafetyCheckOk(db) ){
184668    (void)SQLITE_MISUSE_BKPT;
184669    return 0;
184670  }
184671#endif
184672  pBt = sqlite3DbNameToBtree(db, zDbName);
184673  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
184674}
184675
184676/*
184677** Return 1 if database is read-only or 0 if read/write.  Return -1 if
184678** no such database exists.
184679*/
184680SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
184681  Btree *pBt;
184682#ifdef SQLITE_ENABLE_API_ARMOR
184683  if( !sqlite3SafetyCheckOk(db) ){
184684    (void)SQLITE_MISUSE_BKPT;
184685    return -1;
184686  }
184687#endif
184688  pBt = sqlite3DbNameToBtree(db, zDbName);
184689  return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
184690}
184691
184692#ifdef SQLITE_ENABLE_SNAPSHOT
184693/*
184694** Obtain a snapshot handle for the snapshot of database zDb currently
184695** being read by handle db.
184696*/
184697SQLITE_API int sqlite3_snapshot_get(
184698  sqlite3 *db,
184699  const char *zDb,
184700  sqlite3_snapshot **ppSnapshot
184701){
184702  int rc = SQLITE_ERROR;
184703#ifndef SQLITE_OMIT_WAL
184704
184705#ifdef SQLITE_ENABLE_API_ARMOR
184706  if( !sqlite3SafetyCheckOk(db) ){
184707    return SQLITE_MISUSE_BKPT;
184708  }
184709#endif
184710  sqlite3_mutex_enter(db->mutex);
184711
184712  if( db->autoCommit==0 ){
184713    int iDb = sqlite3FindDbName(db, zDb);
184714    if( iDb==0 || iDb>1 ){
184715      Btree *pBt = db->aDb[iDb].pBt;
184716      if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){
184717        rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
184718        if( rc==SQLITE_OK ){
184719          rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
184720        }
184721      }
184722    }
184723  }
184724
184725  sqlite3_mutex_leave(db->mutex);
184726#endif   /* SQLITE_OMIT_WAL */
184727  return rc;
184728}
184729
184730/*
184731** Open a read-transaction on the snapshot identified by pSnapshot.
184732*/
184733SQLITE_API int sqlite3_snapshot_open(
184734  sqlite3 *db,
184735  const char *zDb,
184736  sqlite3_snapshot *pSnapshot
184737){
184738  int rc = SQLITE_ERROR;
184739#ifndef SQLITE_OMIT_WAL
184740
184741#ifdef SQLITE_ENABLE_API_ARMOR
184742  if( !sqlite3SafetyCheckOk(db) ){
184743    return SQLITE_MISUSE_BKPT;
184744  }
184745#endif
184746  sqlite3_mutex_enter(db->mutex);
184747  if( db->autoCommit==0 ){
184748    int iDb;
184749    iDb = sqlite3FindDbName(db, zDb);
184750    if( iDb==0 || iDb>1 ){
184751      Btree *pBt = db->aDb[iDb].pBt;
184752      if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE ){
184753        Pager *pPager = sqlite3BtreePager(pBt);
184754        int bUnlock = 0;
184755        if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_NONE ){
184756          if( db->nVdbeActive==0 ){
184757            rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
184758            if( rc==SQLITE_OK ){
184759              bUnlock = 1;
184760              rc = sqlite3BtreeCommit(pBt);
184761            }
184762          }
184763        }else{
184764          rc = SQLITE_OK;
184765        }
184766        if( rc==SQLITE_OK ){
184767          rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
184768        }
184769        if( rc==SQLITE_OK ){
184770          rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
184771          sqlite3PagerSnapshotOpen(pPager, 0);
184772        }
184773        if( bUnlock ){
184774          sqlite3PagerSnapshotUnlock(pPager);
184775        }
184776      }
184777    }
184778  }
184779
184780  sqlite3_mutex_leave(db->mutex);
184781#endif   /* SQLITE_OMIT_WAL */
184782  return rc;
184783}
184784
184785/*
184786** Recover as many snapshots as possible from the wal file associated with
184787** schema zDb of database db.
184788*/
184789SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
184790  int rc = SQLITE_ERROR;
184791#ifndef SQLITE_OMIT_WAL
184792  int iDb;
184793
184794#ifdef SQLITE_ENABLE_API_ARMOR
184795  if( !sqlite3SafetyCheckOk(db) ){
184796    return SQLITE_MISUSE_BKPT;
184797  }
184798#endif
184799
184800  sqlite3_mutex_enter(db->mutex);
184801  iDb = sqlite3FindDbName(db, zDb);
184802  if( iDb==0 || iDb>1 ){
184803    Btree *pBt = db->aDb[iDb].pBt;
184804    if( SQLITE_TXN_NONE==sqlite3BtreeTxnState(pBt) ){
184805      rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
184806      if( rc==SQLITE_OK ){
184807        rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
184808        sqlite3BtreeCommit(pBt);
184809      }
184810    }
184811  }
184812  sqlite3_mutex_leave(db->mutex);
184813#endif   /* SQLITE_OMIT_WAL */
184814  return rc;
184815}
184816
184817/*
184818** Free a snapshot handle obtained from sqlite3_snapshot_get().
184819*/
184820SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
184821  sqlite3_free(pSnapshot);
184822}
184823#endif /* SQLITE_ENABLE_SNAPSHOT */
184824
184825#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
184826/*
184827** Given the name of a compile-time option, return true if that option
184828** was used and false if not.
184829**
184830** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
184831** is not required for a match.
184832*/
184833SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
184834  int i, n;
184835  int nOpt;
184836  const char **azCompileOpt;
184837
184838#ifdef SQLITE_ENABLE_API_ARMOR
184839  if( zOptName==0 ){
184840    (void)SQLITE_MISUSE_BKPT;
184841    return 0;
184842  }
184843#endif
184844
184845  azCompileOpt = sqlite3CompileOptions(&nOpt);
184846
184847  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
184848  n = sqlite3Strlen30(zOptName);
184849
184850  /* Since nOpt is normally in single digits, a linear search is
184851  ** adequate. No need for a binary search. */
184852  for(i=0; i<nOpt; i++){
184853    if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
184854     && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
184855    ){
184856      return 1;
184857    }
184858  }
184859  return 0;
184860}
184861
184862/*
184863** Return the N-th compile-time option string.  If N is out of range,
184864** return a NULL pointer.
184865*/
184866SQLITE_API const char *sqlite3_compileoption_get(int N){
184867  int nOpt;
184868  const char **azCompileOpt;
184869  azCompileOpt = sqlite3CompileOptions(&nOpt);
184870  if( N>=0 && N<nOpt ){
184871    return azCompileOpt[N];
184872  }
184873  return 0;
184874}
184875#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
184876
184877/************** End of main.c ************************************************/
184878/************** Begin file notify.c ******************************************/
184879/*
184880** 2009 March 3
184881**
184882** The author disclaims copyright to this source code.  In place of
184883** a legal notice, here is a blessing:
184884**
184885**    May you do good and not evil.
184886**    May you find forgiveness for yourself and forgive others.
184887**    May you share freely, never taking more than you give.
184888**
184889*************************************************************************
184890**
184891** This file contains the implementation of the sqlite3_unlock_notify()
184892** API method and its associated functionality.
184893*/
184894/* #include "sqliteInt.h" */
184895/* #include "btreeInt.h" */
184896
184897/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
184898#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
184899
184900/*
184901** Public interfaces:
184902**
184903**   sqlite3ConnectionBlocked()
184904**   sqlite3ConnectionUnlocked()
184905**   sqlite3ConnectionClosed()
184906**   sqlite3_unlock_notify()
184907*/
184908
184909#define assertMutexHeld() \
184910  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN)) )
184911
184912/*
184913** Head of a linked list of all sqlite3 objects created by this process
184914** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
184915** is not NULL. This variable may only accessed while the STATIC_MAIN
184916** mutex is held.
184917*/
184918static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
184919
184920#ifndef NDEBUG
184921/*
184922** This function is a complex assert() that verifies the following
184923** properties of the blocked connections list:
184924**
184925**   1) Each entry in the list has a non-NULL value for either
184926**      pUnlockConnection or pBlockingConnection, or both.
184927**
184928**   2) All entries in the list that share a common value for
184929**      xUnlockNotify are grouped together.
184930**
184931**   3) If the argument db is not NULL, then none of the entries in the
184932**      blocked connections list have pUnlockConnection or pBlockingConnection
184933**      set to db. This is used when closing connection db.
184934*/
184935static void checkListProperties(sqlite3 *db){
184936  sqlite3 *p;
184937  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
184938    int seen = 0;
184939    sqlite3 *p2;
184940
184941    /* Verify property (1) */
184942    assert( p->pUnlockConnection || p->pBlockingConnection );
184943
184944    /* Verify property (2) */
184945    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
184946      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
184947      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
184948      assert( db==0 || p->pUnlockConnection!=db );
184949      assert( db==0 || p->pBlockingConnection!=db );
184950    }
184951  }
184952}
184953#else
184954# define checkListProperties(x)
184955#endif
184956
184957/*
184958** Remove connection db from the blocked connections list. If connection
184959** db is not currently a part of the list, this function is a no-op.
184960*/
184961static void removeFromBlockedList(sqlite3 *db){
184962  sqlite3 **pp;
184963  assertMutexHeld();
184964  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
184965    if( *pp==db ){
184966      *pp = (*pp)->pNextBlocked;
184967      break;
184968    }
184969  }
184970}
184971
184972/*
184973** Add connection db to the blocked connections list. It is assumed
184974** that it is not already a part of the list.
184975*/
184976static void addToBlockedList(sqlite3 *db){
184977  sqlite3 **pp;
184978  assertMutexHeld();
184979  for(
184980    pp=&sqlite3BlockedList;
184981    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
184982    pp=&(*pp)->pNextBlocked
184983  );
184984  db->pNextBlocked = *pp;
184985  *pp = db;
184986}
184987
184988/*
184989** Obtain the STATIC_MAIN mutex.
184990*/
184991static void enterMutex(void){
184992  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
184993  checkListProperties(0);
184994}
184995
184996/*
184997** Release the STATIC_MAIN mutex.
184998*/
184999static void leaveMutex(void){
185000  assertMutexHeld();
185001  checkListProperties(0);
185002  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
185003}
185004
185005/*
185006** Register an unlock-notify callback.
185007**
185008** This is called after connection "db" has attempted some operation
185009** but has received an SQLITE_LOCKED error because another connection
185010** (call it pOther) in the same process was busy using the same shared
185011** cache.  pOther is found by looking at db->pBlockingConnection.
185012**
185013** If there is no blocking connection, the callback is invoked immediately,
185014** before this routine returns.
185015**
185016** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
185017** a deadlock.
185018**
185019** Otherwise, make arrangements to invoke xNotify when pOther drops
185020** its locks.
185021**
185022** Each call to this routine overrides any prior callbacks registered
185023** on the same "db".  If xNotify==0 then any prior callbacks are immediately
185024** cancelled.
185025*/
185026SQLITE_API int sqlite3_unlock_notify(
185027  sqlite3 *db,
185028  void (*xNotify)(void **, int),
185029  void *pArg
185030){
185031  int rc = SQLITE_OK;
185032
185033#ifdef SQLITE_ENABLE_API_ARMOR
185034  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
185035#endif
185036  sqlite3_mutex_enter(db->mutex);
185037  enterMutex();
185038
185039  if( xNotify==0 ){
185040    removeFromBlockedList(db);
185041    db->pBlockingConnection = 0;
185042    db->pUnlockConnection = 0;
185043    db->xUnlockNotify = 0;
185044    db->pUnlockArg = 0;
185045  }else if( 0==db->pBlockingConnection ){
185046    /* The blocking transaction has been concluded. Or there never was a
185047    ** blocking transaction. In either case, invoke the notify callback
185048    ** immediately.
185049    */
185050    xNotify(&pArg, 1);
185051  }else{
185052    sqlite3 *p;
185053
185054    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
185055    if( p ){
185056      rc = SQLITE_LOCKED;              /* Deadlock detected. */
185057    }else{
185058      db->pUnlockConnection = db->pBlockingConnection;
185059      db->xUnlockNotify = xNotify;
185060      db->pUnlockArg = pArg;
185061      removeFromBlockedList(db);
185062      addToBlockedList(db);
185063    }
185064  }
185065
185066  leaveMutex();
185067  assert( !db->mallocFailed );
185068  sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
185069  sqlite3_mutex_leave(db->mutex);
185070  return rc;
185071}
185072
185073/*
185074** This function is called while stepping or preparing a statement
185075** associated with connection db. The operation will return SQLITE_LOCKED
185076** to the user because it requires a lock that will not be available
185077** until connection pBlocker concludes its current transaction.
185078*/
185079SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
185080  enterMutex();
185081  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
185082    addToBlockedList(db);
185083  }
185084  db->pBlockingConnection = pBlocker;
185085  leaveMutex();
185086}
185087
185088/*
185089** This function is called when
185090** the transaction opened by database db has just finished. Locks held
185091** by database connection db have been released.
185092**
185093** This function loops through each entry in the blocked connections
185094** list and does the following:
185095**
185096**   1) If the sqlite3.pBlockingConnection member of a list entry is
185097**      set to db, then set pBlockingConnection=0.
185098**
185099**   2) If the sqlite3.pUnlockConnection member of a list entry is
185100**      set to db, then invoke the configured unlock-notify callback and
185101**      set pUnlockConnection=0.
185102**
185103**   3) If the two steps above mean that pBlockingConnection==0 and
185104**      pUnlockConnection==0, remove the entry from the blocked connections
185105**      list.
185106*/
185107SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
185108  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
185109  int nArg = 0;                            /* Number of entries in aArg[] */
185110  sqlite3 **pp;                            /* Iterator variable */
185111  void **aArg;               /* Arguments to the unlock callback */
185112  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
185113  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
185114
185115  aArg = aStatic;
185116  enterMutex();         /* Enter STATIC_MAIN mutex */
185117
185118  /* This loop runs once for each entry in the blocked-connections list. */
185119  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
185120    sqlite3 *p = *pp;
185121
185122    /* Step 1. */
185123    if( p->pBlockingConnection==db ){
185124      p->pBlockingConnection = 0;
185125    }
185126
185127    /* Step 2. */
185128    if( p->pUnlockConnection==db ){
185129      assert( p->xUnlockNotify );
185130      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
185131        xUnlockNotify(aArg, nArg);
185132        nArg = 0;
185133      }
185134
185135      sqlite3BeginBenignMalloc();
185136      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
185137      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
185138      if( (!aDyn && nArg==(int)ArraySize(aStatic))
185139       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
185140      ){
185141        /* The aArg[] array needs to grow. */
185142        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
185143        if( pNew ){
185144          memcpy(pNew, aArg, nArg*sizeof(void *));
185145          sqlite3_free(aDyn);
185146          aDyn = aArg = pNew;
185147        }else{
185148          /* This occurs when the array of context pointers that need to
185149          ** be passed to the unlock-notify callback is larger than the
185150          ** aStatic[] array allocated on the stack and the attempt to
185151          ** allocate a larger array from the heap has failed.
185152          **
185153          ** This is a difficult situation to handle. Returning an error
185154          ** code to the caller is insufficient, as even if an error code
185155          ** is returned the transaction on connection db will still be
185156          ** closed and the unlock-notify callbacks on blocked connections
185157          ** will go unissued. This might cause the application to wait
185158          ** indefinitely for an unlock-notify callback that will never
185159          ** arrive.
185160          **
185161          ** Instead, invoke the unlock-notify callback with the context
185162          ** array already accumulated. We can then clear the array and
185163          ** begin accumulating any further context pointers without
185164          ** requiring any dynamic allocation. This is sub-optimal because
185165          ** it means that instead of one callback with a large array of
185166          ** context pointers the application will receive two or more
185167          ** callbacks with smaller arrays of context pointers, which will
185168          ** reduce the applications ability to prioritize multiple
185169          ** connections. But it is the best that can be done under the
185170          ** circumstances.
185171          */
185172          xUnlockNotify(aArg, nArg);
185173          nArg = 0;
185174        }
185175      }
185176      sqlite3EndBenignMalloc();
185177
185178      aArg[nArg++] = p->pUnlockArg;
185179      xUnlockNotify = p->xUnlockNotify;
185180      p->pUnlockConnection = 0;
185181      p->xUnlockNotify = 0;
185182      p->pUnlockArg = 0;
185183    }
185184
185185    /* Step 3. */
185186    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
185187      /* Remove connection p from the blocked connections list. */
185188      *pp = p->pNextBlocked;
185189      p->pNextBlocked = 0;
185190    }else{
185191      pp = &p->pNextBlocked;
185192    }
185193  }
185194
185195  if( nArg!=0 ){
185196    xUnlockNotify(aArg, nArg);
185197  }
185198  sqlite3_free(aDyn);
185199  leaveMutex();         /* Leave STATIC_MAIN mutex */
185200}
185201
185202/*
185203** This is called when the database connection passed as an argument is
185204** being closed. The connection is removed from the blocked list.
185205*/
185206SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
185207  sqlite3ConnectionUnlocked(db);
185208  enterMutex();
185209  removeFromBlockedList(db);
185210  checkListProperties(db);
185211  leaveMutex();
185212}
185213#endif
185214
185215/************** End of notify.c **********************************************/
185216/************** Begin file fts3.c ********************************************/
185217/*
185218** 2006 Oct 10
185219**
185220** The author disclaims copyright to this source code.  In place of
185221** a legal notice, here is a blessing:
185222**
185223**    May you do good and not evil.
185224**    May you find forgiveness for yourself and forgive others.
185225**    May you share freely, never taking more than you give.
185226**
185227******************************************************************************
185228**
185229** This is an SQLite module implementing full-text search.
185230*/
185231
185232/*
185233** The code in this file is only compiled if:
185234**
185235**     * The FTS3 module is being built as an extension
185236**       (in which case SQLITE_CORE is not defined), or
185237**
185238**     * The FTS3 module is being built into the core of
185239**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
185240*/
185241
185242/* The full-text index is stored in a series of b+tree (-like)
185243** structures called segments which map terms to doclists.  The
185244** structures are like b+trees in layout, but are constructed from the
185245** bottom up in optimal fashion and are not updatable.  Since trees
185246** are built from the bottom up, things will be described from the
185247** bottom up.
185248**
185249**
185250**** Varints ****
185251** The basic unit of encoding is a variable-length integer called a
185252** varint.  We encode variable-length integers in little-endian order
185253** using seven bits * per byte as follows:
185254**
185255** KEY:
185256**         A = 0xxxxxxx    7 bits of data and one flag bit
185257**         B = 1xxxxxxx    7 bits of data and one flag bit
185258**
185259**  7 bits - A
185260** 14 bits - BA
185261** 21 bits - BBA
185262** and so on.
185263**
185264** This is similar in concept to how sqlite encodes "varints" but
185265** the encoding is not the same.  SQLite varints are big-endian
185266** are are limited to 9 bytes in length whereas FTS3 varints are
185267** little-endian and can be up to 10 bytes in length (in theory).
185268**
185269** Example encodings:
185270**
185271**     1:    0x01
185272**   127:    0x7f
185273**   128:    0x81 0x00
185274**
185275**
185276**** Document lists ****
185277** A doclist (document list) holds a docid-sorted list of hits for a
185278** given term.  Doclists hold docids and associated token positions.
185279** A docid is the unique integer identifier for a single document.
185280** A position is the index of a word within the document.  The first
185281** word of the document has a position of 0.
185282**
185283** FTS3 used to optionally store character offsets using a compile-time
185284** option.  But that functionality is no longer supported.
185285**
185286** A doclist is stored like this:
185287**
185288** array {
185289**   varint docid;          (delta from previous doclist)
185290**   array {                (position list for column 0)
185291**     varint position;     (2 more than the delta from previous position)
185292**   }
185293**   array {
185294**     varint POS_COLUMN;   (marks start of position list for new column)
185295**     varint column;       (index of new column)
185296**     array {
185297**       varint position;   (2 more than the delta from previous position)
185298**     }
185299**   }
185300**   varint POS_END;        (marks end of positions for this document.
185301** }
185302**
185303** Here, array { X } means zero or more occurrences of X, adjacent in
185304** memory.  A "position" is an index of a token in the token stream
185305** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
185306** in the same logical place as the position element, and act as sentinals
185307** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
185308** The positions numbers are not stored literally but rather as two more
185309** than the difference from the prior position, or the just the position plus
185310** 2 for the first position.  Example:
185311**
185312**   label:       A B C D E  F  G H   I  J K
185313**   value:     123 5 9 1 1 14 35 0 234 72 0
185314**
185315** The 123 value is the first docid.  For column zero in this document
185316** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
185317** at D signals the start of a new column; the 1 at E indicates that the
185318** new column is column number 1.  There are two positions at 12 and 45
185319** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
185320** 234 at I is the delta to next docid (357).  It has one position 70
185321** (72-2) and then terminates with the 0 at K.
185322**
185323** A "position-list" is the list of positions for multiple columns for
185324** a single docid.  A "column-list" is the set of positions for a single
185325** column.  Hence, a position-list consists of one or more column-lists,
185326** a document record consists of a docid followed by a position-list and
185327** a doclist consists of one or more document records.
185328**
185329** A bare doclist omits the position information, becoming an
185330** array of varint-encoded docids.
185331**
185332**** Segment leaf nodes ****
185333** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
185334** nodes are written using LeafWriter, and read using LeafReader (to
185335** iterate through a single leaf node's data) and LeavesReader (to
185336** iterate through a segment's entire leaf layer).  Leaf nodes have
185337** the format:
185338**
185339** varint iHeight;             (height from leaf level, always 0)
185340** varint nTerm;               (length of first term)
185341** char pTerm[nTerm];          (content of first term)
185342** varint nDoclist;            (length of term's associated doclist)
185343** char pDoclist[nDoclist];    (content of doclist)
185344** array {
185345**                             (further terms are delta-encoded)
185346**   varint nPrefix;           (length of prefix shared with previous term)
185347**   varint nSuffix;           (length of unshared suffix)
185348**   char pTermSuffix[nSuffix];(unshared suffix of next term)
185349**   varint nDoclist;          (length of term's associated doclist)
185350**   char pDoclist[nDoclist];  (content of doclist)
185351** }
185352**
185353** Here, array { X } means zero or more occurrences of X, adjacent in
185354** memory.
185355**
185356** Leaf nodes are broken into blocks which are stored contiguously in
185357** the %_segments table in sorted order.  This means that when the end
185358** of a node is reached, the next term is in the node with the next
185359** greater node id.
185360**
185361** New data is spilled to a new leaf node when the current node
185362** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
185363** larger than STANDALONE_MIN (default 1024) is placed in a standalone
185364** node (a leaf node with a single term and doclist).  The goal of
185365** these settings is to pack together groups of small doclists while
185366** making it efficient to directly access large doclists.  The
185367** assumption is that large doclists represent terms which are more
185368** likely to be query targets.
185369**
185370** TODO(shess) It may be useful for blocking decisions to be more
185371** dynamic.  For instance, it may make more sense to have a 2.5k leaf
185372** node rather than splitting into 2k and .5k nodes.  My intuition is
185373** that this might extend through 2x or 4x the pagesize.
185374**
185375**
185376**** Segment interior nodes ****
185377** Segment interior nodes store blockids for subtree nodes and terms
185378** to describe what data is stored by the each subtree.  Interior
185379** nodes are written using InteriorWriter, and read using
185380** InteriorReader.  InteriorWriters are created as needed when
185381** SegmentWriter creates new leaf nodes, or when an interior node
185382** itself grows too big and must be split.  The format of interior
185383** nodes:
185384**
185385** varint iHeight;           (height from leaf level, always >0)
185386** varint iBlockid;          (block id of node's leftmost subtree)
185387** optional {
185388**   varint nTerm;           (length of first term)
185389**   char pTerm[nTerm];      (content of first term)
185390**   array {
185391**                                (further terms are delta-encoded)
185392**     varint nPrefix;            (length of shared prefix with previous term)
185393**     varint nSuffix;            (length of unshared suffix)
185394**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
185395**   }
185396** }
185397**
185398** Here, optional { X } means an optional element, while array { X }
185399** means zero or more occurrences of X, adjacent in memory.
185400**
185401** An interior node encodes n terms separating n+1 subtrees.  The
185402** subtree blocks are contiguous, so only the first subtree's blockid
185403** is encoded.  The subtree at iBlockid will contain all terms less
185404** than the first term encoded (or all terms if no term is encoded).
185405** Otherwise, for terms greater than or equal to pTerm[i] but less
185406** than pTerm[i+1], the subtree for that term will be rooted at
185407** iBlockid+i.  Interior nodes only store enough term data to
185408** distinguish adjacent children (if the rightmost term of the left
185409** child is "something", and the leftmost term of the right child is
185410** "wicked", only "w" is stored).
185411**
185412** New data is spilled to a new interior node at the same height when
185413** the current node exceeds INTERIOR_MAX bytes (default 2048).
185414** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
185415** interior nodes and making the tree too skinny.  The interior nodes
185416** at a given height are naturally tracked by interior nodes at
185417** height+1, and so on.
185418**
185419**
185420**** Segment directory ****
185421** The segment directory in table %_segdir stores meta-information for
185422** merging and deleting segments, and also the root node of the
185423** segment's tree.
185424**
185425** The root node is the top node of the segment's tree after encoding
185426** the entire segment, restricted to ROOT_MAX bytes (default 1024).
185427** This could be either a leaf node or an interior node.  If the top
185428** node requires more than ROOT_MAX bytes, it is flushed to %_segments
185429** and a new root interior node is generated (which should always fit
185430** within ROOT_MAX because it only needs space for 2 varints, the
185431** height and the blockid of the previous root).
185432**
185433** The meta-information in the segment directory is:
185434**   level               - segment level (see below)
185435**   idx                 - index within level
185436**                       - (level,idx uniquely identify a segment)
185437**   start_block         - first leaf node
185438**   leaves_end_block    - last leaf node
185439**   end_block           - last block (including interior nodes)
185440**   root                - contents of root node
185441**
185442** If the root node is a leaf node, then start_block,
185443** leaves_end_block, and end_block are all 0.
185444**
185445**
185446**** Segment merging ****
185447** To amortize update costs, segments are grouped into levels and
185448** merged in batches.  Each increase in level represents exponentially
185449** more documents.
185450**
185451** New documents (actually, document updates) are tokenized and
185452** written individually (using LeafWriter) to a level 0 segment, with
185453** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
185454** level 0 segments are merged into a single level 1 segment.  Level 1
185455** is populated like level 0, and eventually MERGE_COUNT level 1
185456** segments are merged to a single level 2 segment (representing
185457** MERGE_COUNT^2 updates), and so on.
185458**
185459** A segment merge traverses all segments at a given level in
185460** parallel, performing a straightforward sorted merge.  Since segment
185461** leaf nodes are written in to the %_segments table in order, this
185462** merge traverses the underlying sqlite disk structures efficiently.
185463** After the merge, all segment blocks from the merged level are
185464** deleted.
185465**
185466** MERGE_COUNT controls how often we merge segments.  16 seems to be
185467** somewhat of a sweet spot for insertion performance.  32 and 64 show
185468** very similar performance numbers to 16 on insertion, though they're
185469** a tiny bit slower (perhaps due to more overhead in merge-time
185470** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
185471** 16, 2 about 66% slower than 16.
185472**
185473** At query time, high MERGE_COUNT increases the number of segments
185474** which need to be scanned and merged.  For instance, with 100k docs
185475** inserted:
185476**
185477**    MERGE_COUNT   segments
185478**       16           25
185479**        8           12
185480**        4           10
185481**        2            6
185482**
185483** This appears to have only a moderate impact on queries for very
185484** frequent terms (which are somewhat dominated by segment merge
185485** costs), and infrequent and non-existent terms still seem to be fast
185486** even with many segments.
185487**
185488** TODO(shess) That said, it would be nice to have a better query-side
185489** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
185490** optimizations to things like doclist merging will swing the sweet
185491** spot around.
185492**
185493**
185494**
185495**** Handling of deletions and updates ****
185496** Since we're using a segmented structure, with no docid-oriented
185497** index into the term index, we clearly cannot simply update the term
185498** index when a document is deleted or updated.  For deletions, we
185499** write an empty doclist (varint(docid) varint(POS_END)), for updates
185500** we simply write the new doclist.  Segment merges overwrite older
185501** data for a particular docid with newer data, so deletes or updates
185502** will eventually overtake the earlier data and knock it out.  The
185503** query logic likewise merges doclists so that newer data knocks out
185504** older data.
185505*/
185506
185507/************** Include fts3Int.h in the middle of fts3.c ********************/
185508/************** Begin file fts3Int.h *****************************************/
185509/*
185510** 2009 Nov 12
185511**
185512** The author disclaims copyright to this source code.  In place of
185513** a legal notice, here is a blessing:
185514**
185515**    May you do good and not evil.
185516**    May you find forgiveness for yourself and forgive others.
185517**    May you share freely, never taking more than you give.
185518**
185519******************************************************************************
185520**
185521*/
185522#ifndef _FTSINT_H
185523#define _FTSINT_H
185524
185525#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
185526# define NDEBUG 1
185527#endif
185528
185529/* FTS3/FTS4 require virtual tables */
185530#ifdef SQLITE_OMIT_VIRTUALTABLE
185531# undef SQLITE_ENABLE_FTS3
185532# undef SQLITE_ENABLE_FTS4
185533#endif
185534
185535/*
185536** FTS4 is really an extension for FTS3.  It is enabled using the
185537** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
185538** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
185539*/
185540#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
185541# define SQLITE_ENABLE_FTS3
185542#endif
185543
185544#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
185545
185546/* If not building as part of the core, include sqlite3ext.h. */
185547#ifndef SQLITE_CORE
185548/* # include "sqlite3ext.h" */
185549SQLITE_EXTENSION_INIT3
185550#endif
185551
185552/* #include "sqlite3.h" */
185553/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
185554/************** Begin file fts3_tokenizer.h **********************************/
185555/*
185556** 2006 July 10
185557**
185558** The author disclaims copyright to this source code.
185559**
185560*************************************************************************
185561** Defines the interface to tokenizers used by fulltext-search.  There
185562** are three basic components:
185563**
185564** sqlite3_tokenizer_module is a singleton defining the tokenizer
185565** interface functions.  This is essentially the class structure for
185566** tokenizers.
185567**
185568** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
185569** including customization information defined at creation time.
185570**
185571** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
185572** tokens from a particular input.
185573*/
185574#ifndef _FTS3_TOKENIZER_H_
185575#define _FTS3_TOKENIZER_H_
185576
185577/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
185578** If tokenizers are to be allowed to call sqlite3_*() functions, then
185579** we will need a way to register the API consistently.
185580*/
185581/* #include "sqlite3.h" */
185582
185583/*
185584** Structures used by the tokenizer interface. When a new tokenizer
185585** implementation is registered, the caller provides a pointer to
185586** an sqlite3_tokenizer_module containing pointers to the callback
185587** functions that make up an implementation.
185588**
185589** When an fts3 table is created, it passes any arguments passed to
185590** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
185591** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
185592** implementation. The xCreate() function in turn returns an
185593** sqlite3_tokenizer structure representing the specific tokenizer to
185594** be used for the fts3 table (customized by the tokenizer clause arguments).
185595**
185596** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
185597** method is called. It returns an sqlite3_tokenizer_cursor object
185598** that may be used to tokenize a specific input buffer based on
185599** the tokenization rules supplied by a specific sqlite3_tokenizer
185600** object.
185601*/
185602typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
185603typedef struct sqlite3_tokenizer sqlite3_tokenizer;
185604typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
185605
185606struct sqlite3_tokenizer_module {
185607
185608  /*
185609  ** Structure version. Should always be set to 0 or 1.
185610  */
185611  int iVersion;
185612
185613  /*
185614  ** Create a new tokenizer. The values in the argv[] array are the
185615  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
185616  ** TABLE statement that created the fts3 table. For example, if
185617  ** the following SQL is executed:
185618  **
185619  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
185620  **
185621  ** then argc is set to 2, and the argv[] array contains pointers
185622  ** to the strings "arg1" and "arg2".
185623  **
185624  ** This method should return either SQLITE_OK (0), or an SQLite error
185625  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
185626  ** to point at the newly created tokenizer structure. The generic
185627  ** sqlite3_tokenizer.pModule variable should not be initialized by
185628  ** this callback. The caller will do so.
185629  */
185630  int (*xCreate)(
185631    int argc,                           /* Size of argv array */
185632    const char *const*argv,             /* Tokenizer argument strings */
185633    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
185634  );
185635
185636  /*
185637  ** Destroy an existing tokenizer. The fts3 module calls this method
185638  ** exactly once for each successful call to xCreate().
185639  */
185640  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
185641
185642  /*
185643  ** Create a tokenizer cursor to tokenize an input buffer. The caller
185644  ** is responsible for ensuring that the input buffer remains valid
185645  ** until the cursor is closed (using the xClose() method).
185646  */
185647  int (*xOpen)(
185648    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
185649    const char *pInput, int nBytes,      /* Input buffer */
185650    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
185651  );
185652
185653  /*
185654  ** Destroy an existing tokenizer cursor. The fts3 module calls this
185655  ** method exactly once for each successful call to xOpen().
185656  */
185657  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
185658
185659  /*
185660  ** Retrieve the next token from the tokenizer cursor pCursor. This
185661  ** method should either return SQLITE_OK and set the values of the
185662  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
185663  ** the end of the buffer has been reached, or an SQLite error code.
185664  **
185665  ** *ppToken should be set to point at a buffer containing the
185666  ** normalized version of the token (i.e. after any case-folding and/or
185667  ** stemming has been performed). *pnBytes should be set to the length
185668  ** of this buffer in bytes. The input text that generated the token is
185669  ** identified by the byte offsets returned in *piStartOffset and
185670  ** *piEndOffset. *piStartOffset should be set to the index of the first
185671  ** byte of the token in the input buffer. *piEndOffset should be set
185672  ** to the index of the first byte just past the end of the token in
185673  ** the input buffer.
185674  **
185675  ** The buffer *ppToken is set to point at is managed by the tokenizer
185676  ** implementation. It is only required to be valid until the next call
185677  ** to xNext() or xClose().
185678  */
185679  /* TODO(shess) current implementation requires pInput to be
185680  ** nul-terminated.  This should either be fixed, or pInput/nBytes
185681  ** should be converted to zInput.
185682  */
185683  int (*xNext)(
185684    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
185685    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
185686    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
185687    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
185688    int *piPosition      /* OUT: Number of tokens returned before this one */
185689  );
185690
185691  /***********************************************************************
185692  ** Methods below this point are only available if iVersion>=1.
185693  */
185694
185695  /*
185696  ** Configure the language id of a tokenizer cursor.
185697  */
185698  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
185699};
185700
185701struct sqlite3_tokenizer {
185702  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
185703  /* Tokenizer implementations will typically add additional fields */
185704};
185705
185706struct sqlite3_tokenizer_cursor {
185707  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
185708  /* Tokenizer implementations will typically add additional fields */
185709};
185710
185711int fts3_global_term_cnt(int iTerm, int iCol);
185712int fts3_term_cnt(int iTerm, int iCol);
185713
185714
185715#endif /* _FTS3_TOKENIZER_H_ */
185716
185717/************** End of fts3_tokenizer.h **************************************/
185718/************** Continuing where we left off in fts3Int.h ********************/
185719/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
185720/************** Begin file fts3_hash.h ***************************************/
185721/*
185722** 2001 September 22
185723**
185724** The author disclaims copyright to this source code.  In place of
185725** a legal notice, here is a blessing:
185726**
185727**    May you do good and not evil.
185728**    May you find forgiveness for yourself and forgive others.
185729**    May you share freely, never taking more than you give.
185730**
185731*************************************************************************
185732** This is the header file for the generic hash-table implementation
185733** used in SQLite.  We've modified it slightly to serve as a standalone
185734** hash table implementation for the full-text indexing module.
185735**
185736*/
185737#ifndef _FTS3_HASH_H_
185738#define _FTS3_HASH_H_
185739
185740/* Forward declarations of structures. */
185741typedef struct Fts3Hash Fts3Hash;
185742typedef struct Fts3HashElem Fts3HashElem;
185743
185744/* A complete hash table is an instance of the following structure.
185745** The internals of this structure are intended to be opaque -- client
185746** code should not attempt to access or modify the fields of this structure
185747** directly.  Change this structure only by using the routines below.
185748** However, many of the "procedures" and "functions" for modifying and
185749** accessing this structure are really macros, so we can't really make
185750** this structure opaque.
185751*/
185752struct Fts3Hash {
185753  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
185754  char copyKey;           /* True if copy of key made on insert */
185755  int count;              /* Number of entries in this table */
185756  Fts3HashElem *first;    /* The first element of the array */
185757  int htsize;             /* Number of buckets in the hash table */
185758  struct _fts3ht {        /* the hash table */
185759    int count;               /* Number of entries with this hash */
185760    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
185761  } *ht;
185762};
185763
185764/* Each element in the hash table is an instance of the following
185765** structure.  All elements are stored on a single doubly-linked list.
185766**
185767** Again, this structure is intended to be opaque, but it can't really
185768** be opaque because it is used by macros.
185769*/
185770struct Fts3HashElem {
185771  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
185772  void *data;                /* Data associated with this element */
185773  void *pKey; int nKey;      /* Key associated with this element */
185774};
185775
185776/*
185777** There are 2 different modes of operation for a hash table:
185778**
185779**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
185780**                           (including the null-terminator, if any).  Case
185781**                           is respected in comparisons.
185782**
185783**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
185784**                           memcmp() is used to compare keys.
185785**
185786** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
185787*/
185788#define FTS3_HASH_STRING    1
185789#define FTS3_HASH_BINARY    2
185790
185791/*
185792** Access routines.  To delete, insert a NULL pointer.
185793*/
185794SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
185795SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
185796SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
185797SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
185798SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
185799
185800/*
185801** Shorthand for the functions above
185802*/
185803#define fts3HashInit     sqlite3Fts3HashInit
185804#define fts3HashInsert   sqlite3Fts3HashInsert
185805#define fts3HashFind     sqlite3Fts3HashFind
185806#define fts3HashClear    sqlite3Fts3HashClear
185807#define fts3HashFindElem sqlite3Fts3HashFindElem
185808
185809/*
185810** Macros for looping over all elements of a hash table.  The idiom is
185811** like this:
185812**
185813**   Fts3Hash h;
185814**   Fts3HashElem *p;
185815**   ...
185816**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
185817**     SomeStructure *pData = fts3HashData(p);
185818**     // do something with pData
185819**   }
185820*/
185821#define fts3HashFirst(H)  ((H)->first)
185822#define fts3HashNext(E)   ((E)->next)
185823#define fts3HashData(E)   ((E)->data)
185824#define fts3HashKey(E)    ((E)->pKey)
185825#define fts3HashKeysize(E) ((E)->nKey)
185826
185827/*
185828** Number of entries in a hash table
185829*/
185830#define fts3HashCount(H)  ((H)->count)
185831
185832#endif /* _FTS3_HASH_H_ */
185833
185834/************** End of fts3_hash.h *******************************************/
185835/************** Continuing where we left off in fts3Int.h ********************/
185836
185837/*
185838** This constant determines the maximum depth of an FTS expression tree
185839** that the library will create and use. FTS uses recursion to perform
185840** various operations on the query tree, so the disadvantage of a large
185841** limit is that it may allow very large queries to use large amounts
185842** of stack space (perhaps causing a stack overflow).
185843*/
185844#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
185845# define SQLITE_FTS3_MAX_EXPR_DEPTH 12
185846#endif
185847
185848
185849/*
185850** This constant controls how often segments are merged. Once there are
185851** FTS3_MERGE_COUNT segments of level N, they are merged into a single
185852** segment of level N+1.
185853*/
185854#define FTS3_MERGE_COUNT 16
185855
185856/*
185857** This is the maximum amount of data (in bytes) to store in the
185858** Fts3Table.pendingTerms hash table. Normally, the hash table is
185859** populated as documents are inserted/updated/deleted in a transaction
185860** and used to create a new segment when the transaction is committed.
185861** However if this limit is reached midway through a transaction, a new
185862** segment is created and the hash table cleared immediately.
185863*/
185864#define FTS3_MAX_PENDING_DATA (1*1024*1024)
185865
185866/*
185867** Macro to return the number of elements in an array. SQLite has a
185868** similar macro called ArraySize(). Use a different name to avoid
185869** a collision when building an amalgamation with built-in FTS3.
185870*/
185871#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
185872
185873
185874#ifndef MIN
185875# define MIN(x,y) ((x)<(y)?(x):(y))
185876#endif
185877#ifndef MAX
185878# define MAX(x,y) ((x)>(y)?(x):(y))
185879#endif
185880
185881/*
185882** Maximum length of a varint encoded integer. The varint format is different
185883** from that used by SQLite, so the maximum length is 10, not 9.
185884*/
185885#define FTS3_VARINT_MAX 10
185886
185887#define FTS3_BUFFER_PADDING 8
185888
185889/*
185890** FTS4 virtual tables may maintain multiple indexes - one index of all terms
185891** in the document set and zero or more prefix indexes. All indexes are stored
185892** as one or more b+-trees in the %_segments and %_segdir tables.
185893**
185894** It is possible to determine which index a b+-tree belongs to based on the
185895** value stored in the "%_segdir.level" column. Given this value L, the index
185896** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
185897** level values between 0 and 1023 (inclusive) belong to index 0, all levels
185898** between 1024 and 2047 to index 1, and so on.
185899**
185900** It is considered impossible for an index to use more than 1024 levels. In
185901** theory though this may happen, but only after at least
185902** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
185903*/
185904#define FTS3_SEGDIR_MAXLEVEL      1024
185905#define FTS3_SEGDIR_MAXLEVEL_STR "1024"
185906
185907/*
185908** The testcase() macro is only used by the amalgamation.  If undefined,
185909** make it a no-op.
185910*/
185911#ifndef testcase
185912# define testcase(X)
185913#endif
185914
185915/*
185916** Terminator values for position-lists and column-lists.
185917*/
185918#define POS_COLUMN  (1)     /* Column-list terminator */
185919#define POS_END     (0)     /* Position-list terminator */
185920
185921/*
185922** The assert_fts3_nc() macro is similar to the assert() macro, except that it
185923** is used for assert() conditions that are true only if it can be
185924** guranteed that the database is not corrupt.
185925*/
185926#ifdef SQLITE_DEBUG
185927SQLITE_API extern int sqlite3_fts3_may_be_corrupt;
185928# define assert_fts3_nc(x) assert(sqlite3_fts3_may_be_corrupt || (x))
185929#else
185930# define assert_fts3_nc(x) assert(x)
185931#endif
185932
185933/*
185934** This section provides definitions to allow the
185935** FTS3 extension to be compiled outside of the
185936** amalgamation.
185937*/
185938#ifndef SQLITE_AMALGAMATION
185939/*
185940** Macros indicating that conditional expressions are always true or
185941** false.
185942*/
185943#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
185944# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
185945#endif
185946#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
185947# define ALWAYS(X)      (1)
185948# define NEVER(X)       (0)
185949#elif !defined(NDEBUG)
185950# define ALWAYS(X)      ((X)?1:(assert(0),0))
185951# define NEVER(X)       ((X)?(assert(0),1):0)
185952#else
185953# define ALWAYS(X)      (X)
185954# define NEVER(X)       (X)
185955#endif
185956
185957/*
185958** Internal types used by SQLite.
185959*/
185960typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
185961typedef short int i16;            /* 2-byte (or larger) signed integer */
185962typedef unsigned int u32;         /* 4-byte unsigned integer */
185963typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
185964typedef sqlite3_int64 i64;        /* 8-byte signed integer */
185965
185966/*
185967** Macro used to suppress compiler warnings for unused parameters.
185968*/
185969#define UNUSED_PARAMETER(x) (void)(x)
185970
185971/*
185972** Activate assert() only if SQLITE_TEST is enabled.
185973*/
185974#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
185975# define NDEBUG 1
185976#endif
185977
185978/*
185979** The TESTONLY macro is used to enclose variable declarations or
185980** other bits of code that are needed to support the arguments
185981** within testcase() and assert() macros.
185982*/
185983#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
185984# define TESTONLY(X)  X
185985#else
185986# define TESTONLY(X)
185987#endif
185988
185989#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
185990#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
185991
185992#define deliberate_fall_through
185993
185994#endif /* SQLITE_AMALGAMATION */
185995
185996#ifdef SQLITE_DEBUG
185997SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
185998# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
185999#else
186000# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
186001#endif
186002
186003typedef struct Fts3Table Fts3Table;
186004typedef struct Fts3Cursor Fts3Cursor;
186005typedef struct Fts3Expr Fts3Expr;
186006typedef struct Fts3Phrase Fts3Phrase;
186007typedef struct Fts3PhraseToken Fts3PhraseToken;
186008
186009typedef struct Fts3Doclist Fts3Doclist;
186010typedef struct Fts3SegFilter Fts3SegFilter;
186011typedef struct Fts3DeferredToken Fts3DeferredToken;
186012typedef struct Fts3SegReader Fts3SegReader;
186013typedef struct Fts3MultiSegReader Fts3MultiSegReader;
186014
186015typedef struct MatchinfoBuffer MatchinfoBuffer;
186016
186017/*
186018** A connection to a fulltext index is an instance of the following
186019** structure. The xCreate and xConnect methods create an instance
186020** of this structure and xDestroy and xDisconnect free that instance.
186021** All other methods receive a pointer to the structure as one of their
186022** arguments.
186023*/
186024struct Fts3Table {
186025  sqlite3_vtab base;              /* Base class used by SQLite core */
186026  sqlite3 *db;                    /* The database connection */
186027  const char *zDb;                /* logical database name */
186028  const char *zName;              /* virtual table name */
186029  int nColumn;                    /* number of named columns in virtual table */
186030  char **azColumn;                /* column names.  malloced */
186031  u8 *abNotindexed;               /* True for 'notindexed' columns */
186032  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
186033  char *zContentTbl;              /* content=xxx option, or NULL */
186034  char *zLanguageid;              /* languageid=xxx option, or NULL */
186035  int nAutoincrmerge;             /* Value configured by 'automerge' */
186036  u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
186037  int bLock;                      /* Used to prevent recursive content= tbls */
186038
186039  /* Precompiled statements used by the implementation. Each of these
186040  ** statements is run and reset within a single virtual table API call.
186041  */
186042  sqlite3_stmt *aStmt[40];
186043  sqlite3_stmt *pSeekStmt;        /* Cache for fts3CursorSeekStmt() */
186044
186045  char *zReadExprlist;
186046  char *zWriteExprlist;
186047
186048  int nNodeSize;                  /* Soft limit for node size */
186049  u8 bFts4;                       /* True for FTS4, false for FTS3 */
186050  u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
186051  u8 bHasDocsize;                 /* True if %_docsize table exists */
186052  u8 bDescIdx;                    /* True if doclists are in reverse order */
186053  u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
186054  int nPgsz;                      /* Page size for host database */
186055  char *zSegmentsTbl;             /* Name of %_segments table */
186056  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
186057  int iSavepoint;
186058
186059  /*
186060  ** The following array of hash tables is used to buffer pending index
186061  ** updates during transactions. All pending updates buffered at any one
186062  ** time must share a common language-id (see the FTS4 langid= feature).
186063  ** The current language id is stored in variable iPrevLangid.
186064  **
186065  ** A single FTS4 table may have multiple full-text indexes. For each index
186066  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
186067  ** terms that appear in the document set. Each subsequent index in aIndex[]
186068  ** is an index of prefixes of a specific length.
186069  **
186070  ** Variable nPendingData contains an estimate the memory consumed by the
186071  ** pending data structures, including hash table overhead, but not including
186072  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
186073  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
186074  ** recently inserted record.
186075  */
186076  int nIndex;                     /* Size of aIndex[] */
186077  struct Fts3Index {
186078    int nPrefix;                  /* Prefix length (0 for main terms index) */
186079    Fts3Hash hPending;            /* Pending terms table for this index */
186080  } *aIndex;
186081  int nMaxPendingData;            /* Max pending data before flush to disk */
186082  int nPendingData;               /* Current bytes of pending data */
186083  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
186084  int iPrevLangid;                /* Langid of recently inserted document */
186085  int bPrevDelete;                /* True if last operation was a delete */
186086
186087#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
186088  /* State variables used for validating that the transaction control
186089  ** methods of the virtual table are called at appropriate times.  These
186090  ** values do not contribute to FTS functionality; they are used for
186091  ** verifying the operation of the SQLite core.
186092  */
186093  int inTransaction;     /* True after xBegin but before xCommit/xRollback */
186094  int mxSavepoint;       /* Largest valid xSavepoint integer */
186095#endif
186096
186097#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
186098  /* True to disable the incremental doclist optimization. This is controled
186099  ** by special insert command 'test-no-incr-doclist'.  */
186100  int bNoIncrDoclist;
186101
186102  /* Number of segments in a level */
186103  int nMergeCount;
186104#endif
186105};
186106
186107/* Macro to find the number of segments to merge */
186108#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
186109# define MergeCount(P) ((P)->nMergeCount)
186110#else
186111# define MergeCount(P) FTS3_MERGE_COUNT
186112#endif
186113
186114/*
186115** When the core wants to read from the virtual table, it creates a
186116** virtual table cursor (an instance of the following structure) using
186117** the xOpen method. Cursors are destroyed using the xClose method.
186118*/
186119struct Fts3Cursor {
186120  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
186121  i16 eSearch;                    /* Search strategy (see below) */
186122  u8 isEof;                       /* True if at End Of Results */
186123  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
186124  u8 bSeekStmt;                   /* True if pStmt is a seek */
186125  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
186126  Fts3Expr *pExpr;                /* Parsed MATCH query string */
186127  int iLangid;                    /* Language being queried for */
186128  int nPhrase;                    /* Number of matchable phrases in query */
186129  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
186130  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
186131  char *pNextId;                  /* Pointer into the body of aDoclist */
186132  char *aDoclist;                 /* List of docids for full-text queries */
186133  int nDoclist;                   /* Size of buffer at aDoclist */
186134  u8 bDesc;                       /* True to sort in descending order */
186135  int eEvalmode;                  /* An FTS3_EVAL_XX constant */
186136  int nRowAvg;                    /* Average size of database rows, in pages */
186137  sqlite3_int64 nDoc;             /* Documents in table */
186138  i64 iMinDocid;                  /* Minimum docid to return */
186139  i64 iMaxDocid;                  /* Maximum docid to return */
186140  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
186141  MatchinfoBuffer *pMIBuffer;     /* Buffer for matchinfo data */
186142};
186143
186144#define FTS3_EVAL_FILTER    0
186145#define FTS3_EVAL_NEXT      1
186146#define FTS3_EVAL_MATCHINFO 2
186147
186148/*
186149** The Fts3Cursor.eSearch member is always set to one of the following.
186150** Actualy, Fts3Cursor.eSearch can be greater than or equal to
186151** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
186152** of the column to be searched.  For example, in
186153**
186154**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
186155**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
186156**
186157** Because the LHS of the MATCH operator is 2nd column "b",
186158** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
186159** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
186160** indicating that all columns should be searched,
186161** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
186162*/
186163#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
186164#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
186165#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
186166
186167/*
186168** The lower 16-bits of the sqlite3_index_info.idxNum value set by
186169** the xBestIndex() method contains the Fts3Cursor.eSearch value described
186170** above. The upper 16-bits contain a combination of the following
186171** bits, used to describe extra constraints on full-text searches.
186172*/
186173#define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
186174#define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
186175#define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
186176
186177struct Fts3Doclist {
186178  char *aAll;                    /* Array containing doclist (or NULL) */
186179  int nAll;                      /* Size of a[] in bytes */
186180  char *pNextDocid;              /* Pointer to next docid */
186181
186182  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
186183  int bFreeList;                 /* True if pList should be sqlite3_free()d */
186184  char *pList;                   /* Pointer to position list following iDocid */
186185  int nList;                     /* Length of position list */
186186};
186187
186188/*
186189** A "phrase" is a sequence of one or more tokens that must match in
186190** sequence.  A single token is the base case and the most common case.
186191** For a sequence of tokens contained in double-quotes (i.e. "one two three")
186192** nToken will be the number of tokens in the string.
186193*/
186194struct Fts3PhraseToken {
186195  char *z;                        /* Text of the token */
186196  int n;                          /* Number of bytes in buffer z */
186197  int isPrefix;                   /* True if token ends with a "*" character */
186198  int bFirst;                     /* True if token must appear at position 0 */
186199
186200  /* Variables above this point are populated when the expression is
186201  ** parsed (by code in fts3_expr.c). Below this point the variables are
186202  ** used when evaluating the expression. */
186203  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
186204  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
186205};
186206
186207struct Fts3Phrase {
186208  /* Cache of doclist for this phrase. */
186209  Fts3Doclist doclist;
186210  int bIncr;                 /* True if doclist is loaded incrementally */
186211  int iDoclistToken;
186212
186213  /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
186214  ** OR condition.  */
186215  char *pOrPoslist;
186216  i64 iOrDocid;
186217
186218  /* Variables below this point are populated by fts3_expr.c when parsing
186219  ** a MATCH expression. Everything above is part of the evaluation phase.
186220  */
186221  int nToken;                /* Number of tokens in the phrase */
186222  int iColumn;               /* Index of column this phrase must match */
186223  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
186224};
186225
186226/*
186227** A tree of these objects forms the RHS of a MATCH operator.
186228**
186229** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
186230** points to a malloced buffer, size nDoclist bytes, containing the results
186231** of this phrase query in FTS3 doclist format. As usual, the initial
186232** "Length" field found in doclists stored on disk is omitted from this
186233** buffer.
186234**
186235** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
186236** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
186237** where nCol is the number of columns in the queried FTS table. The array
186238** is populated as follows:
186239**
186240**   aMI[iCol*3 + 0] = Undefined
186241**   aMI[iCol*3 + 1] = Number of occurrences
186242**   aMI[iCol*3 + 2] = Number of rows containing at least one instance
186243**
186244** The aMI array is allocated using sqlite3_malloc(). It should be freed
186245** when the expression node is.
186246*/
186247struct Fts3Expr {
186248  int eType;                 /* One of the FTSQUERY_XXX values defined below */
186249  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
186250  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
186251  Fts3Expr *pLeft;           /* Left operand */
186252  Fts3Expr *pRight;          /* Right operand */
186253  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
186254
186255  /* The following are used by the fts3_eval.c module. */
186256  sqlite3_int64 iDocid;      /* Current docid */
186257  u8 bEof;                   /* True this expression is at EOF already */
186258  u8 bStart;                 /* True if iDocid is valid */
186259  u8 bDeferred;              /* True if this expression is entirely deferred */
186260
186261  /* The following are used by the fts3_snippet.c module. */
186262  int iPhrase;               /* Index of this phrase in matchinfo() results */
186263  u32 *aMI;                  /* See above */
186264};
186265
186266/*
186267** Candidate values for Fts3Query.eType. Note that the order of the first
186268** four values is in order of precedence when parsing expressions. For
186269** example, the following:
186270**
186271**   "a OR b AND c NOT d NEAR e"
186272**
186273** is equivalent to:
186274**
186275**   "a OR (b AND (c NOT (d NEAR e)))"
186276*/
186277#define FTSQUERY_NEAR   1
186278#define FTSQUERY_NOT    2
186279#define FTSQUERY_AND    3
186280#define FTSQUERY_OR     4
186281#define FTSQUERY_PHRASE 5
186282
186283
186284/* fts3_write.c */
186285SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
186286SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
186287SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
186288SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
186289SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
186290  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
186291SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
186292  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
186293SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
186294SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
186295SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
186296
186297SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
186298SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
186299
186300#ifndef SQLITE_DISABLE_FTS4_DEFERRED
186301SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
186302SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
186303SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
186304SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
186305SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
186306#else
186307# define sqlite3Fts3FreeDeferredTokens(x)
186308# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
186309# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
186310# define sqlite3Fts3FreeDeferredDoclists(x)
186311# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
186312#endif
186313
186314SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
186315SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
186316
186317/* Special values interpreted by sqlite3SegReaderCursor() */
186318#define FTS3_SEGCURSOR_PENDING        -1
186319#define FTS3_SEGCURSOR_ALL            -2
186320
186321SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
186322SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
186323SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
186324
186325SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
186326    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
186327
186328/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
186329#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
186330#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
186331#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
186332#define FTS3_SEGMENT_PREFIX        0x00000008
186333#define FTS3_SEGMENT_SCAN          0x00000010
186334#define FTS3_SEGMENT_FIRST         0x00000020
186335
186336/* Type passed as 4th argument to SegmentReaderIterate() */
186337struct Fts3SegFilter {
186338  const char *zTerm;
186339  int nTerm;
186340  int iCol;
186341  int flags;
186342};
186343
186344struct Fts3MultiSegReader {
186345  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
186346  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
186347  int nSegment;                   /* Size of apSegment array */
186348  int nAdvance;                   /* How many seg-readers to advance */
186349  Fts3SegFilter *pFilter;         /* Pointer to filter object */
186350  char *aBuffer;                  /* Buffer to merge doclists in */
186351  i64 nBuffer;                    /* Allocated size of aBuffer[] in bytes */
186352
186353  int iColFilter;                 /* If >=0, filter for this column */
186354  int bRestart;
186355
186356  /* Used by fts3.c only. */
186357  int nCost;                      /* Cost of running iterator */
186358  int bLookup;                    /* True if a lookup of a single entry. */
186359
186360  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
186361  char *zTerm;                    /* Pointer to term buffer */
186362  int nTerm;                      /* Size of zTerm in bytes */
186363  char *aDoclist;                 /* Pointer to doclist buffer */
186364  int nDoclist;                   /* Size of aDoclist[] in bytes */
186365};
186366
186367SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
186368
186369#define fts3GetVarint32(p, piVal) (                                           \
186370  (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
186371)
186372
186373/* fts3.c */
186374SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
186375SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
186376SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
186377SQLITE_PRIVATE int sqlite3Fts3GetVarintU(const char *, sqlite_uint64 *);
186378SQLITE_PRIVATE int sqlite3Fts3GetVarintBounded(const char*,const char*,sqlite3_int64*);
186379SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
186380SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
186381SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
186382SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
186383SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
186384SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
186385SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
186386SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
186387SQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut);
186388
186389/* fts3_tokenizer.c */
186390SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
186391SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
186392SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
186393    sqlite3_tokenizer **, char **
186394);
186395SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
186396
186397/* fts3_snippet.c */
186398SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
186399SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
186400  const char *, const char *, int, int
186401);
186402SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
186403SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
186404
186405/* fts3_expr.c */
186406SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
186407  char **, int, int, int, const char *, int, Fts3Expr **, char **
186408);
186409SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
186410#ifdef SQLITE_TEST
186411SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash*);
186412SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
186413#endif
186414SQLITE_PRIVATE void *sqlite3Fts3MallocZero(i64 nByte);
186415
186416SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
186417  sqlite3_tokenizer_cursor **
186418);
186419
186420/* fts3_aux.c */
186421SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
186422
186423SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
186424
186425SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
186426    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
186427SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
186428    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
186429SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
186430SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
186431SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
186432
186433/* fts3_tokenize_vtab.c */
186434SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *, void(*xDestroy)(void*));
186435
186436/* fts3_unicode2.c (functions generated by parsing unicode text files) */
186437#ifndef SQLITE_DISABLE_FTS3_UNICODE
186438SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
186439SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
186440SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
186441#endif
186442
186443SQLITE_PRIVATE int sqlite3Fts3ExprIterate(Fts3Expr*, int (*x)(Fts3Expr*,int,void*), void*);
186444
186445SQLITE_PRIVATE int sqlite3Fts3IntegrityCheck(Fts3Table *p, int *pbOk);
186446
186447#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
186448#endif /* _FTSINT_H */
186449
186450/************** End of fts3Int.h *********************************************/
186451/************** Continuing where we left off in fts3.c ***********************/
186452#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
186453
186454#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
186455# define SQLITE_CORE 1
186456#endif
186457
186458/* #include <assert.h> */
186459/* #include <stdlib.h> */
186460/* #include <stddef.h> */
186461/* #include <stdio.h> */
186462/* #include <string.h> */
186463/* #include <stdarg.h> */
186464
186465/* #include "fts3.h" */
186466#ifndef SQLITE_CORE
186467/* # include "sqlite3ext.h" */
186468  SQLITE_EXTENSION_INIT1
186469#endif
186470
186471typedef struct Fts3HashWrapper Fts3HashWrapper;
186472struct Fts3HashWrapper {
186473  Fts3Hash hash;                  /* Hash table */
186474  int nRef;                       /* Number of pointers to this object */
186475};
186476
186477static int fts3EvalNext(Fts3Cursor *pCsr);
186478static int fts3EvalStart(Fts3Cursor *pCsr);
186479static int fts3TermSegReaderCursor(
186480    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
186481
186482/*
186483** This variable is set to false when running tests for which the on disk
186484** structures should not be corrupt. Otherwise, true. If it is false, extra
186485** assert() conditions in the fts3 code are activated - conditions that are
186486** only true if it is guaranteed that the fts3 database is not corrupt.
186487*/
186488#ifdef SQLITE_DEBUG
186489SQLITE_API int sqlite3_fts3_may_be_corrupt = 1;
186490#endif
186491
186492/*
186493** Write a 64-bit variable-length integer to memory starting at p[0].
186494** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
186495** The number of bytes written is returned.
186496*/
186497SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
186498  unsigned char *q = (unsigned char *) p;
186499  sqlite_uint64 vu = v;
186500  do{
186501    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
186502    vu >>= 7;
186503  }while( vu!=0 );
186504  q[-1] &= 0x7f;  /* turn off high bit in final byte */
186505  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
186506  return (int) (q - (unsigned char *)p);
186507}
186508
186509#define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
186510  v = (v & mask1) | ( (*(const unsigned char*)(ptr++)) << shift );  \
186511  if( (v & mask2)==0 ){ var = v; return ret; }
186512#define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
186513  v = (*ptr++);                                               \
186514  if( (v & mask2)==0 ){ var = v; return ret; }
186515
186516SQLITE_PRIVATE int sqlite3Fts3GetVarintU(const char *pBuf, sqlite_uint64 *v){
186517  const unsigned char *p = (const unsigned char*)pBuf;
186518  const unsigned char *pStart = p;
186519  u32 a;
186520  u64 b;
186521  int shift;
186522
186523  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
186524  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
186525  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
186526  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
186527  b = (a & 0x0FFFFFFF );
186528
186529  for(shift=28; shift<=63; shift+=7){
186530    u64 c = *p++;
186531    b += (c&0x7F) << shift;
186532    if( (c & 0x80)==0 ) break;
186533  }
186534  *v = b;
186535  return (int)(p - pStart);
186536}
186537
186538/*
186539** Read a 64-bit variable-length integer from memory starting at p[0].
186540** Return the number of bytes read, or 0 on error.
186541** The value is stored in *v.
186542*/
186543SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
186544  return sqlite3Fts3GetVarintU(pBuf, (sqlite3_uint64*)v);
186545}
186546
186547/*
186548** Read a 64-bit variable-length integer from memory starting at p[0] and
186549** not extending past pEnd[-1].
186550** Return the number of bytes read, or 0 on error.
186551** The value is stored in *v.
186552*/
186553SQLITE_PRIVATE int sqlite3Fts3GetVarintBounded(
186554  const char *pBuf,
186555  const char *pEnd,
186556  sqlite_int64 *v
186557){
186558  const unsigned char *p = (const unsigned char*)pBuf;
186559  const unsigned char *pStart = p;
186560  const unsigned char *pX = (const unsigned char*)pEnd;
186561  u64 b = 0;
186562  int shift;
186563  for(shift=0; shift<=63; shift+=7){
186564    u64 c = p<pX ? *p : 0;
186565    p++;
186566    b += (c&0x7F) << shift;
186567    if( (c & 0x80)==0 ) break;
186568  }
186569  *v = b;
186570  return (int)(p - pStart);
186571}
186572
186573/*
186574** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
186575** a non-negative 32-bit integer before it is returned.
186576*/
186577SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
186578  const unsigned char *ptr = (const unsigned char*)p;
186579  u32 a;
186580
186581#ifndef fts3GetVarint32
186582  GETVARINT_INIT(a, ptr, 0,  0x00,     0x80, *pi, 1);
186583#else
186584  a = (*ptr++);
186585  assert( a & 0x80 );
186586#endif
186587
186588  GETVARINT_STEP(a, ptr, 7,  0x7F,     0x4000, *pi, 2);
186589  GETVARINT_STEP(a, ptr, 14, 0x3FFF,   0x200000, *pi, 3);
186590  GETVARINT_STEP(a, ptr, 21, 0x1FFFFF, 0x10000000, *pi, 4);
186591  a = (a & 0x0FFFFFFF );
186592  *pi = (int)(a | ((u32)(*ptr & 0x07) << 28));
186593  assert( 0==(a & 0x80000000) );
186594  assert( *pi>=0 );
186595  return 5;
186596}
186597
186598/*
186599** Return the number of bytes required to encode v as a varint
186600*/
186601SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
186602  int i = 0;
186603  do{
186604    i++;
186605    v >>= 7;
186606  }while( v!=0 );
186607  return i;
186608}
186609
186610/*
186611** Convert an SQL-style quoted string into a normal string by removing
186612** the quote characters.  The conversion is done in-place.  If the
186613** input does not begin with a quote character, then this routine
186614** is a no-op.
186615**
186616** Examples:
186617**
186618**     "abc"   becomes   abc
186619**     'xyz'   becomes   xyz
186620**     [pqr]   becomes   pqr
186621**     `mno`   becomes   mno
186622**
186623*/
186624SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
186625  char quote;                     /* Quote character (if any ) */
186626
186627  quote = z[0];
186628  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
186629    int iIn = 1;                  /* Index of next byte to read from input */
186630    int iOut = 0;                 /* Index of next byte to write to output */
186631
186632    /* If the first byte was a '[', then the close-quote character is a ']' */
186633    if( quote=='[' ) quote = ']';
186634
186635    while( z[iIn] ){
186636      if( z[iIn]==quote ){
186637        if( z[iIn+1]!=quote ) break;
186638        z[iOut++] = quote;
186639        iIn += 2;
186640      }else{
186641        z[iOut++] = z[iIn++];
186642      }
186643    }
186644    z[iOut] = '\0';
186645  }
186646}
186647
186648/*
186649** Read a single varint from the doclist at *pp and advance *pp to point
186650** to the first byte past the end of the varint.  Add the value of the varint
186651** to *pVal.
186652*/
186653static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
186654  sqlite3_int64 iVal;
186655  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
186656  *pVal += iVal;
186657}
186658
186659/*
186660** When this function is called, *pp points to the first byte following a
186661** varint that is part of a doclist (or position-list, or any other list
186662** of varints). This function moves *pp to point to the start of that varint,
186663** and sets *pVal by the varint value.
186664**
186665** Argument pStart points to the first byte of the doclist that the
186666** varint is part of.
186667*/
186668static void fts3GetReverseVarint(
186669  char **pp,
186670  char *pStart,
186671  sqlite3_int64 *pVal
186672){
186673  sqlite3_int64 iVal;
186674  char *p;
186675
186676  /* Pointer p now points at the first byte past the varint we are
186677  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
186678  ** clear on character p[-1]. */
186679  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
186680  p++;
186681  *pp = p;
186682
186683  sqlite3Fts3GetVarint(p, &iVal);
186684  *pVal = iVal;
186685}
186686
186687/*
186688** The xDisconnect() virtual table method.
186689*/
186690static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
186691  Fts3Table *p = (Fts3Table *)pVtab;
186692  int i;
186693
186694  assert( p->nPendingData==0 );
186695  assert( p->pSegments==0 );
186696
186697  /* Free any prepared statements held */
186698  sqlite3_finalize(p->pSeekStmt);
186699  for(i=0; i<SizeofArray(p->aStmt); i++){
186700    sqlite3_finalize(p->aStmt[i]);
186701  }
186702  sqlite3_free(p->zSegmentsTbl);
186703  sqlite3_free(p->zReadExprlist);
186704  sqlite3_free(p->zWriteExprlist);
186705  sqlite3_free(p->zContentTbl);
186706  sqlite3_free(p->zLanguageid);
186707
186708  /* Invoke the tokenizer destructor to free the tokenizer. */
186709  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
186710
186711  sqlite3_free(p);
186712  return SQLITE_OK;
186713}
186714
186715/*
186716** Write an error message into *pzErr
186717*/
186718SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
186719  va_list ap;
186720  sqlite3_free(*pzErr);
186721  va_start(ap, zFormat);
186722  *pzErr = sqlite3_vmprintf(zFormat, ap);
186723  va_end(ap);
186724}
186725
186726/*
186727** Construct one or more SQL statements from the format string given
186728** and then evaluate those statements. The success code is written
186729** into *pRc.
186730**
186731** If *pRc is initially non-zero then this routine is a no-op.
186732*/
186733static void fts3DbExec(
186734  int *pRc,              /* Success code */
186735  sqlite3 *db,           /* Database in which to run SQL */
186736  const char *zFormat,   /* Format string for SQL */
186737  ...                    /* Arguments to the format string */
186738){
186739  va_list ap;
186740  char *zSql;
186741  if( *pRc ) return;
186742  va_start(ap, zFormat);
186743  zSql = sqlite3_vmprintf(zFormat, ap);
186744  va_end(ap);
186745  if( zSql==0 ){
186746    *pRc = SQLITE_NOMEM;
186747  }else{
186748    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
186749    sqlite3_free(zSql);
186750  }
186751}
186752
186753/*
186754** The xDestroy() virtual table method.
186755*/
186756static int fts3DestroyMethod(sqlite3_vtab *pVtab){
186757  Fts3Table *p = (Fts3Table *)pVtab;
186758  int rc = SQLITE_OK;              /* Return code */
186759  const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
186760  sqlite3 *db = p->db;             /* Database handle */
186761
186762  /* Drop the shadow tables */
186763  fts3DbExec(&rc, db,
186764    "DROP TABLE IF EXISTS %Q.'%q_segments';"
186765    "DROP TABLE IF EXISTS %Q.'%q_segdir';"
186766    "DROP TABLE IF EXISTS %Q.'%q_docsize';"
186767    "DROP TABLE IF EXISTS %Q.'%q_stat';"
186768    "%s DROP TABLE IF EXISTS %Q.'%q_content';",
186769    zDb, p->zName,
186770    zDb, p->zName,
186771    zDb, p->zName,
186772    zDb, p->zName,
186773    (p->zContentTbl ? "--" : ""), zDb,p->zName
186774  );
186775
186776  /* If everything has worked, invoke fts3DisconnectMethod() to free the
186777  ** memory associated with the Fts3Table structure and return SQLITE_OK.
186778  ** Otherwise, return an SQLite error code.
186779  */
186780  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
186781}
186782
186783
186784/*
186785** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
186786** passed as the first argument. This is done as part of the xConnect()
186787** and xCreate() methods.
186788**
186789** If *pRc is non-zero when this function is called, it is a no-op.
186790** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
186791** before returning.
186792*/
186793static void fts3DeclareVtab(int *pRc, Fts3Table *p){
186794  if( *pRc==SQLITE_OK ){
186795    int i;                        /* Iterator variable */
186796    int rc;                       /* Return code */
186797    char *zSql;                   /* SQL statement passed to declare_vtab() */
186798    char *zCols;                  /* List of user defined columns */
186799    const char *zLanguageid;
186800
186801    zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
186802    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
186803    sqlite3_vtab_config(p->db, SQLITE_VTAB_INNOCUOUS);
186804
186805    /* Create a list of user columns for the virtual table */
186806    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
186807    for(i=1; zCols && i<p->nColumn; i++){
186808      zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
186809    }
186810
186811    /* Create the whole "CREATE TABLE" statement to pass to SQLite */
186812    zSql = sqlite3_mprintf(
186813        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
186814        zCols, p->zName, zLanguageid
186815    );
186816    if( !zCols || !zSql ){
186817      rc = SQLITE_NOMEM;
186818    }else{
186819      rc = sqlite3_declare_vtab(p->db, zSql);
186820    }
186821
186822    sqlite3_free(zSql);
186823    sqlite3_free(zCols);
186824    *pRc = rc;
186825  }
186826}
186827
186828/*
186829** Create the %_stat table if it does not already exist.
186830*/
186831SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
186832  fts3DbExec(pRc, p->db,
186833      "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
186834          "(id INTEGER PRIMARY KEY, value BLOB);",
186835      p->zDb, p->zName
186836  );
186837  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
186838}
186839
186840/*
186841** Create the backing store tables (%_content, %_segments and %_segdir)
186842** required by the FTS3 table passed as the only argument. This is done
186843** as part of the vtab xCreate() method.
186844**
186845** If the p->bHasDocsize boolean is true (indicating that this is an
186846** FTS4 table, not an FTS3 table) then also create the %_docsize and
186847** %_stat tables required by FTS4.
186848*/
186849static int fts3CreateTables(Fts3Table *p){
186850  int rc = SQLITE_OK;             /* Return code */
186851  int i;                          /* Iterator variable */
186852  sqlite3 *db = p->db;            /* The database connection */
186853
186854  if( p->zContentTbl==0 ){
186855    const char *zLanguageid = p->zLanguageid;
186856    char *zContentCols;           /* Columns of %_content table */
186857
186858    /* Create a list of user columns for the content table */
186859    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
186860    for(i=0; zContentCols && i<p->nColumn; i++){
186861      char *z = p->azColumn[i];
186862      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
186863    }
186864    if( zLanguageid && zContentCols ){
186865      zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
186866    }
186867    if( zContentCols==0 ) rc = SQLITE_NOMEM;
186868
186869    /* Create the content table */
186870    fts3DbExec(&rc, db,
186871       "CREATE TABLE %Q.'%q_content'(%s)",
186872       p->zDb, p->zName, zContentCols
186873    );
186874    sqlite3_free(zContentCols);
186875  }
186876
186877  /* Create other tables */
186878  fts3DbExec(&rc, db,
186879      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
186880      p->zDb, p->zName
186881  );
186882  fts3DbExec(&rc, db,
186883      "CREATE TABLE %Q.'%q_segdir'("
186884        "level INTEGER,"
186885        "idx INTEGER,"
186886        "start_block INTEGER,"
186887        "leaves_end_block INTEGER,"
186888        "end_block INTEGER,"
186889        "root BLOB,"
186890        "PRIMARY KEY(level, idx)"
186891      ");",
186892      p->zDb, p->zName
186893  );
186894  if( p->bHasDocsize ){
186895    fts3DbExec(&rc, db,
186896        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
186897        p->zDb, p->zName
186898    );
186899  }
186900  assert( p->bHasStat==p->bFts4 );
186901  if( p->bHasStat ){
186902    sqlite3Fts3CreateStatTable(&rc, p);
186903  }
186904  return rc;
186905}
186906
186907/*
186908** Store the current database page-size in bytes in p->nPgsz.
186909**
186910** If *pRc is non-zero when this function is called, it is a no-op.
186911** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
186912** before returning.
186913*/
186914static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
186915  if( *pRc==SQLITE_OK ){
186916    int rc;                       /* Return code */
186917    char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
186918    sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
186919
186920    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
186921    if( !zSql ){
186922      rc = SQLITE_NOMEM;
186923    }else{
186924      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
186925      if( rc==SQLITE_OK ){
186926        sqlite3_step(pStmt);
186927        p->nPgsz = sqlite3_column_int(pStmt, 0);
186928        rc = sqlite3_finalize(pStmt);
186929      }else if( rc==SQLITE_AUTH ){
186930        p->nPgsz = 1024;
186931        rc = SQLITE_OK;
186932      }
186933    }
186934    assert( p->nPgsz>0 || rc!=SQLITE_OK );
186935    sqlite3_free(zSql);
186936    *pRc = rc;
186937  }
186938}
186939
186940/*
186941** "Special" FTS4 arguments are column specifications of the following form:
186942**
186943**   <key> = <value>
186944**
186945** There may not be whitespace surrounding the "=" character. The <value>
186946** term may be quoted, but the <key> may not.
186947*/
186948static int fts3IsSpecialColumn(
186949  const char *z,
186950  int *pnKey,
186951  char **pzValue
186952){
186953  char *zValue;
186954  const char *zCsr = z;
186955
186956  while( *zCsr!='=' ){
186957    if( *zCsr=='\0' ) return 0;
186958    zCsr++;
186959  }
186960
186961  *pnKey = (int)(zCsr-z);
186962  zValue = sqlite3_mprintf("%s", &zCsr[1]);
186963  if( zValue ){
186964    sqlite3Fts3Dequote(zValue);
186965  }
186966  *pzValue = zValue;
186967  return 1;
186968}
186969
186970/*
186971** Append the output of a printf() style formatting to an existing string.
186972*/
186973static void fts3Appendf(
186974  int *pRc,                       /* IN/OUT: Error code */
186975  char **pz,                      /* IN/OUT: Pointer to string buffer */
186976  const char *zFormat,            /* Printf format string to append */
186977  ...                             /* Arguments for printf format string */
186978){
186979  if( *pRc==SQLITE_OK ){
186980    va_list ap;
186981    char *z;
186982    va_start(ap, zFormat);
186983    z = sqlite3_vmprintf(zFormat, ap);
186984    va_end(ap);
186985    if( z && *pz ){
186986      char *z2 = sqlite3_mprintf("%s%s", *pz, z);
186987      sqlite3_free(z);
186988      z = z2;
186989    }
186990    if( z==0 ) *pRc = SQLITE_NOMEM;
186991    sqlite3_free(*pz);
186992    *pz = z;
186993  }
186994}
186995
186996/*
186997** Return a copy of input string zInput enclosed in double-quotes (") and
186998** with all double quote characters escaped. For example:
186999**
187000**     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
187001**
187002** The pointer returned points to memory obtained from sqlite3_malloc(). It
187003** is the callers responsibility to call sqlite3_free() to release this
187004** memory.
187005*/
187006static char *fts3QuoteId(char const *zInput){
187007  sqlite3_int64 nRet;
187008  char *zRet;
187009  nRet = 2 + (int)strlen(zInput)*2 + 1;
187010  zRet = sqlite3_malloc64(nRet);
187011  if( zRet ){
187012    int i;
187013    char *z = zRet;
187014    *(z++) = '"';
187015    for(i=0; zInput[i]; i++){
187016      if( zInput[i]=='"' ) *(z++) = '"';
187017      *(z++) = zInput[i];
187018    }
187019    *(z++) = '"';
187020    *(z++) = '\0';
187021  }
187022  return zRet;
187023}
187024
187025/*
187026** Return a list of comma separated SQL expressions and a FROM clause that
187027** could be used in a SELECT statement such as the following:
187028**
187029**     SELECT <list of expressions> FROM %_content AS x ...
187030**
187031** to return the docid, followed by each column of text data in order
187032** from left to write. If parameter zFunc is not NULL, then instead of
187033** being returned directly each column of text data is passed to an SQL
187034** function named zFunc first. For example, if zFunc is "unzip" and the
187035** table has the three user-defined columns "a", "b", and "c", the following
187036** string is returned:
187037**
187038**     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
187039**
187040** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
187041** is the responsibility of the caller to eventually free it.
187042**
187043** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
187044** a NULL pointer is returned). Otherwise, if an OOM error is encountered
187045** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
187046** no error occurs, *pRc is left unmodified.
187047*/
187048static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
187049  char *zRet = 0;
187050  char *zFree = 0;
187051  char *zFunction;
187052  int i;
187053
187054  if( p->zContentTbl==0 ){
187055    if( !zFunc ){
187056      zFunction = "";
187057    }else{
187058      zFree = zFunction = fts3QuoteId(zFunc);
187059    }
187060    fts3Appendf(pRc, &zRet, "docid");
187061    for(i=0; i<p->nColumn; i++){
187062      fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
187063    }
187064    if( p->zLanguageid ){
187065      fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
187066    }
187067    sqlite3_free(zFree);
187068  }else{
187069    fts3Appendf(pRc, &zRet, "rowid");
187070    for(i=0; i<p->nColumn; i++){
187071      fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
187072    }
187073    if( p->zLanguageid ){
187074      fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
187075    }
187076  }
187077  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
187078      p->zDb,
187079      (p->zContentTbl ? p->zContentTbl : p->zName),
187080      (p->zContentTbl ? "" : "_content")
187081  );
187082  return zRet;
187083}
187084
187085/*
187086** Return a list of N comma separated question marks, where N is the number
187087** of columns in the %_content table (one for the docid plus one for each
187088** user-defined text column).
187089**
187090** If argument zFunc is not NULL, then all but the first question mark
187091** is preceded by zFunc and an open bracket, and followed by a closed
187092** bracket. For example, if zFunc is "zip" and the FTS3 table has three
187093** user-defined text columns, the following string is returned:
187094**
187095**     "?, zip(?), zip(?), zip(?)"
187096**
187097** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
187098** is the responsibility of the caller to eventually free it.
187099**
187100** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
187101** a NULL pointer is returned). Otherwise, if an OOM error is encountered
187102** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
187103** no error occurs, *pRc is left unmodified.
187104*/
187105static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
187106  char *zRet = 0;
187107  char *zFree = 0;
187108  char *zFunction;
187109  int i;
187110
187111  if( !zFunc ){
187112    zFunction = "";
187113  }else{
187114    zFree = zFunction = fts3QuoteId(zFunc);
187115  }
187116  fts3Appendf(pRc, &zRet, "?");
187117  for(i=0; i<p->nColumn; i++){
187118    fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
187119  }
187120  if( p->zLanguageid ){
187121    fts3Appendf(pRc, &zRet, ", ?");
187122  }
187123  sqlite3_free(zFree);
187124  return zRet;
187125}
187126
187127/*
187128** Buffer z contains a positive integer value encoded as utf-8 text.
187129** Decode this value and store it in *pnOut, returning the number of bytes
187130** consumed. If an overflow error occurs return a negative value.
187131*/
187132SQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut){
187133  u64 iVal = 0;
187134  int i;
187135  for(i=0; z[i]>='0' && z[i]<='9'; i++){
187136    iVal = iVal*10 + (z[i] - '0');
187137    if( iVal>0x7FFFFFFF ) return -1;
187138  }
187139  *pnOut = (int)iVal;
187140  return i;
187141}
187142
187143/*
187144** This function interprets the string at (*pp) as a non-negative integer
187145** value. It reads the integer and sets *pnOut to the value read, then
187146** sets *pp to point to the byte immediately following the last byte of
187147** the integer value.
187148**
187149** Only decimal digits ('0'..'9') may be part of an integer value.
187150**
187151** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
187152** the output value undefined. Otherwise SQLITE_OK is returned.
187153**
187154** This function is used when parsing the "prefix=" FTS4 parameter.
187155*/
187156static int fts3GobbleInt(const char **pp, int *pnOut){
187157  const int MAX_NPREFIX = 10000000;
187158  int nInt = 0;                   /* Output value */
187159  int nByte;
187160  nByte = sqlite3Fts3ReadInt(*pp, &nInt);
187161  if( nInt>MAX_NPREFIX ){
187162    nInt = 0;
187163  }
187164  if( nByte==0 ){
187165    return SQLITE_ERROR;
187166  }
187167  *pnOut = nInt;
187168  *pp += nByte;
187169  return SQLITE_OK;
187170}
187171
187172/*
187173** This function is called to allocate an array of Fts3Index structures
187174** representing the indexes maintained by the current FTS table. FTS tables
187175** always maintain the main "terms" index, but may also maintain one or
187176** more "prefix" indexes, depending on the value of the "prefix=" parameter
187177** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
187178**
187179** Argument zParam is passed the value of the "prefix=" option if one was
187180** specified, or NULL otherwise.
187181**
187182** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
187183** the allocated array. *pnIndex is set to the number of elements in the
187184** array. If an error does occur, an SQLite error code is returned.
187185**
187186** Regardless of whether or not an error is returned, it is the responsibility
187187** of the caller to call sqlite3_free() on the output array to free it.
187188*/
187189static int fts3PrefixParameter(
187190  const char *zParam,             /* ABC in prefix=ABC parameter to parse */
187191  int *pnIndex,                   /* OUT: size of *apIndex[] array */
187192  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
187193){
187194  struct Fts3Index *aIndex;       /* Allocated array */
187195  int nIndex = 1;                 /* Number of entries in array */
187196
187197  if( zParam && zParam[0] ){
187198    const char *p;
187199    nIndex++;
187200    for(p=zParam; *p; p++){
187201      if( *p==',' ) nIndex++;
187202    }
187203  }
187204
187205  aIndex = sqlite3_malloc64(sizeof(struct Fts3Index) * nIndex);
187206  *apIndex = aIndex;
187207  if( !aIndex ){
187208    return SQLITE_NOMEM;
187209  }
187210
187211  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
187212  if( zParam ){
187213    const char *p = zParam;
187214    int i;
187215    for(i=1; i<nIndex; i++){
187216      int nPrefix = 0;
187217      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
187218      assert( nPrefix>=0 );
187219      if( nPrefix==0 ){
187220        nIndex--;
187221        i--;
187222      }else{
187223        aIndex[i].nPrefix = nPrefix;
187224      }
187225      p++;
187226    }
187227  }
187228
187229  *pnIndex = nIndex;
187230  return SQLITE_OK;
187231}
187232
187233/*
187234** This function is called when initializing an FTS4 table that uses the
187235** content=xxx option. It determines the number of and names of the columns
187236** of the new FTS4 table.
187237**
187238** The third argument passed to this function is the value passed to the
187239** config=xxx option (i.e. "xxx"). This function queries the database for
187240** a table of that name. If found, the output variables are populated
187241** as follows:
187242**
187243**   *pnCol:   Set to the number of columns table xxx has,
187244**
187245**   *pnStr:   Set to the total amount of space required to store a copy
187246**             of each columns name, including the nul-terminator.
187247**
187248**   *pazCol:  Set to point to an array of *pnCol strings. Each string is
187249**             the name of the corresponding column in table xxx. The array
187250**             and its contents are allocated using a single allocation. It
187251**             is the responsibility of the caller to free this allocation
187252**             by eventually passing the *pazCol value to sqlite3_free().
187253**
187254** If the table cannot be found, an error code is returned and the output
187255** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
187256** returned (and the output variables are undefined).
187257*/
187258static int fts3ContentColumns(
187259  sqlite3 *db,                    /* Database handle */
187260  const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
187261  const char *zTbl,               /* Name of content table */
187262  const char ***pazCol,           /* OUT: Malloc'd array of column names */
187263  int *pnCol,                     /* OUT: Size of array *pazCol */
187264  int *pnStr,                     /* OUT: Bytes of string content */
187265  char **pzErr                    /* OUT: error message */
187266){
187267  int rc = SQLITE_OK;             /* Return code */
187268  char *zSql;                     /* "SELECT *" statement on zTbl */
187269  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
187270
187271  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
187272  if( !zSql ){
187273    rc = SQLITE_NOMEM;
187274  }else{
187275    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
187276    if( rc!=SQLITE_OK ){
187277      sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
187278    }
187279  }
187280  sqlite3_free(zSql);
187281
187282  if( rc==SQLITE_OK ){
187283    const char **azCol;           /* Output array */
187284    sqlite3_int64 nStr = 0;       /* Size of all column names (incl. 0x00) */
187285    int nCol;                     /* Number of table columns */
187286    int i;                        /* Used to iterate through columns */
187287
187288    /* Loop through the returned columns. Set nStr to the number of bytes of
187289    ** space required to store a copy of each column name, including the
187290    ** nul-terminator byte.  */
187291    nCol = sqlite3_column_count(pStmt);
187292    for(i=0; i<nCol; i++){
187293      const char *zCol = sqlite3_column_name(pStmt, i);
187294      nStr += strlen(zCol) + 1;
187295    }
187296
187297    /* Allocate and populate the array to return. */
187298    azCol = (const char **)sqlite3_malloc64(sizeof(char *) * nCol + nStr);
187299    if( azCol==0 ){
187300      rc = SQLITE_NOMEM;
187301    }else{
187302      char *p = (char *)&azCol[nCol];
187303      for(i=0; i<nCol; i++){
187304        const char *zCol = sqlite3_column_name(pStmt, i);
187305        int n = (int)strlen(zCol)+1;
187306        memcpy(p, zCol, n);
187307        azCol[i] = p;
187308        p += n;
187309      }
187310    }
187311    sqlite3_finalize(pStmt);
187312
187313    /* Set the output variables. */
187314    *pnCol = nCol;
187315    *pnStr = nStr;
187316    *pazCol = azCol;
187317  }
187318
187319  return rc;
187320}
187321
187322/*
187323** This function is the implementation of both the xConnect and xCreate
187324** methods of the FTS3 virtual table.
187325**
187326** The argv[] array contains the following:
187327**
187328**   argv[0]   -> module name  ("fts3" or "fts4")
187329**   argv[1]   -> database name
187330**   argv[2]   -> table name
187331**   argv[...] -> "column name" and other module argument fields.
187332*/
187333static int fts3InitVtab(
187334  int isCreate,                   /* True for xCreate, false for xConnect */
187335  sqlite3 *db,                    /* The SQLite database connection */
187336  void *pAux,                     /* Hash table containing tokenizers */
187337  int argc,                       /* Number of elements in argv array */
187338  const char * const *argv,       /* xCreate/xConnect argument array */
187339  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
187340  char **pzErr                    /* Write any error message here */
187341){
187342  Fts3Hash *pHash = &((Fts3HashWrapper*)pAux)->hash;
187343  Fts3Table *p = 0;               /* Pointer to allocated vtab */
187344  int rc = SQLITE_OK;             /* Return code */
187345  int i;                          /* Iterator variable */
187346  sqlite3_int64 nByte;            /* Size of allocation used for *p */
187347  int iCol;                       /* Column index */
187348  int nString = 0;                /* Bytes required to hold all column names */
187349  int nCol = 0;                   /* Number of columns in the FTS table */
187350  char *zCsr;                     /* Space for holding column names */
187351  int nDb;                        /* Bytes required to hold database name */
187352  int nName;                      /* Bytes required to hold table name */
187353  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
187354  const char **aCol;              /* Array of column names */
187355  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
187356
187357  int nIndex = 0;                 /* Size of aIndex[] array */
187358  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
187359
187360  /* The results of parsing supported FTS4 key=value options: */
187361  int bNoDocsize = 0;             /* True to omit %_docsize table */
187362  int bDescIdx = 0;               /* True to store descending indexes */
187363  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
187364  char *zCompress = 0;            /* compress=? parameter (or NULL) */
187365  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
187366  char *zContent = 0;             /* content=? parameter (or NULL) */
187367  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
187368  char **azNotindexed = 0;        /* The set of notindexed= columns */
187369  int nNotindexed = 0;            /* Size of azNotindexed[] array */
187370
187371  assert( strlen(argv[0])==4 );
187372  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
187373       || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
187374  );
187375
187376  nDb = (int)strlen(argv[1]) + 1;
187377  nName = (int)strlen(argv[2]) + 1;
187378
187379  nByte = sizeof(const char *) * (argc-2);
187380  aCol = (const char **)sqlite3_malloc64(nByte);
187381  if( aCol ){
187382    memset((void*)aCol, 0, nByte);
187383    azNotindexed = (char **)sqlite3_malloc64(nByte);
187384  }
187385  if( azNotindexed ){
187386    memset(azNotindexed, 0, nByte);
187387  }
187388  if( !aCol || !azNotindexed ){
187389    rc = SQLITE_NOMEM;
187390    goto fts3_init_out;
187391  }
187392
187393  /* Loop through all of the arguments passed by the user to the FTS3/4
187394  ** module (i.e. all the column names and special arguments). This loop
187395  ** does the following:
187396  **
187397  **   + Figures out the number of columns the FTSX table will have, and
187398  **     the number of bytes of space that must be allocated to store copies
187399  **     of the column names.
187400  **
187401  **   + If there is a tokenizer specification included in the arguments,
187402  **     initializes the tokenizer pTokenizer.
187403  */
187404  for(i=3; rc==SQLITE_OK && i<argc; i++){
187405    char const *z = argv[i];
187406    int nKey;
187407    char *zVal;
187408
187409    /* Check if this is a tokenizer specification */
187410    if( !pTokenizer
187411     && strlen(z)>8
187412     && 0==sqlite3_strnicmp(z, "tokenize", 8)
187413     && 0==sqlite3Fts3IsIdChar(z[8])
187414    ){
187415      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
187416    }
187417
187418    /* Check if it is an FTS4 special argument. */
187419    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
187420      struct Fts4Option {
187421        const char *zOpt;
187422        int nOpt;
187423      } aFts4Opt[] = {
187424        { "matchinfo",   9 },     /* 0 -> MATCHINFO */
187425        { "prefix",      6 },     /* 1 -> PREFIX */
187426        { "compress",    8 },     /* 2 -> COMPRESS */
187427        { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
187428        { "order",       5 },     /* 4 -> ORDER */
187429        { "content",     7 },     /* 5 -> CONTENT */
187430        { "languageid", 10 },     /* 6 -> LANGUAGEID */
187431        { "notindexed", 10 }      /* 7 -> NOTINDEXED */
187432      };
187433
187434      int iOpt;
187435      if( !zVal ){
187436        rc = SQLITE_NOMEM;
187437      }else{
187438        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
187439          struct Fts4Option *pOp = &aFts4Opt[iOpt];
187440          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
187441            break;
187442          }
187443        }
187444        switch( iOpt ){
187445          case 0:               /* MATCHINFO */
187446            if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
187447              sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
187448              rc = SQLITE_ERROR;
187449            }
187450            bNoDocsize = 1;
187451            break;
187452
187453          case 1:               /* PREFIX */
187454            sqlite3_free(zPrefix);
187455            zPrefix = zVal;
187456            zVal = 0;
187457            break;
187458
187459          case 2:               /* COMPRESS */
187460            sqlite3_free(zCompress);
187461            zCompress = zVal;
187462            zVal = 0;
187463            break;
187464
187465          case 3:               /* UNCOMPRESS */
187466            sqlite3_free(zUncompress);
187467            zUncompress = zVal;
187468            zVal = 0;
187469            break;
187470
187471          case 4:               /* ORDER */
187472            if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
187473             && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
187474            ){
187475              sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
187476              rc = SQLITE_ERROR;
187477            }
187478            bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
187479            break;
187480
187481          case 5:              /* CONTENT */
187482            sqlite3_free(zContent);
187483            zContent = zVal;
187484            zVal = 0;
187485            break;
187486
187487          case 6:              /* LANGUAGEID */
187488            assert( iOpt==6 );
187489            sqlite3_free(zLanguageid);
187490            zLanguageid = zVal;
187491            zVal = 0;
187492            break;
187493
187494          case 7:              /* NOTINDEXED */
187495            azNotindexed[nNotindexed++] = zVal;
187496            zVal = 0;
187497            break;
187498
187499          default:
187500            assert( iOpt==SizeofArray(aFts4Opt) );
187501            sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
187502            rc = SQLITE_ERROR;
187503            break;
187504        }
187505        sqlite3_free(zVal);
187506      }
187507    }
187508
187509    /* Otherwise, the argument is a column name. */
187510    else {
187511      nString += (int)(strlen(z) + 1);
187512      aCol[nCol++] = z;
187513    }
187514  }
187515
187516  /* If a content=xxx option was specified, the following:
187517  **
187518  **   1. Ignore any compress= and uncompress= options.
187519  **
187520  **   2. If no column names were specified as part of the CREATE VIRTUAL
187521  **      TABLE statement, use all columns from the content table.
187522  */
187523  if( rc==SQLITE_OK && zContent ){
187524    sqlite3_free(zCompress);
187525    sqlite3_free(zUncompress);
187526    zCompress = 0;
187527    zUncompress = 0;
187528    if( nCol==0 ){
187529      sqlite3_free((void*)aCol);
187530      aCol = 0;
187531      rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
187532
187533      /* If a languageid= option was specified, remove the language id
187534      ** column from the aCol[] array. */
187535      if( rc==SQLITE_OK && zLanguageid ){
187536        int j;
187537        for(j=0; j<nCol; j++){
187538          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
187539            int k;
187540            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
187541            nCol--;
187542            break;
187543          }
187544        }
187545      }
187546    }
187547  }
187548  if( rc!=SQLITE_OK ) goto fts3_init_out;
187549
187550  if( nCol==0 ){
187551    assert( nString==0 );
187552    aCol[0] = "content";
187553    nString = 8;
187554    nCol = 1;
187555  }
187556
187557  if( pTokenizer==0 ){
187558    rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
187559    if( rc!=SQLITE_OK ) goto fts3_init_out;
187560  }
187561  assert( pTokenizer );
187562
187563  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
187564  if( rc==SQLITE_ERROR ){
187565    assert( zPrefix );
187566    sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
187567  }
187568  if( rc!=SQLITE_OK ) goto fts3_init_out;
187569
187570  /* Allocate and populate the Fts3Table structure. */
187571  nByte = sizeof(Fts3Table) +                  /* Fts3Table */
187572          nCol * sizeof(char *) +              /* azColumn */
187573          nIndex * sizeof(struct Fts3Index) +  /* aIndex */
187574          nCol * sizeof(u8) +                  /* abNotindexed */
187575          nName +                              /* zName */
187576          nDb +                                /* zDb */
187577          nString;                             /* Space for azColumn strings */
187578  p = (Fts3Table*)sqlite3_malloc64(nByte);
187579  if( p==0 ){
187580    rc = SQLITE_NOMEM;
187581    goto fts3_init_out;
187582  }
187583  memset(p, 0, nByte);
187584  p->db = db;
187585  p->nColumn = nCol;
187586  p->nPendingData = 0;
187587  p->azColumn = (char **)&p[1];
187588  p->pTokenizer = pTokenizer;
187589  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
187590  p->bHasDocsize = (isFts4 && bNoDocsize==0);
187591  p->bHasStat = (u8)isFts4;
187592  p->bFts4 = (u8)isFts4;
187593  p->bDescIdx = (u8)bDescIdx;
187594  p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
187595  p->zContentTbl = zContent;
187596  p->zLanguageid = zLanguageid;
187597  zContent = 0;
187598  zLanguageid = 0;
187599  TESTONLY( p->inTransaction = -1 );
187600  TESTONLY( p->mxSavepoint = -1 );
187601
187602  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
187603  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
187604  p->nIndex = nIndex;
187605  for(i=0; i<nIndex; i++){
187606    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
187607  }
187608  p->abNotindexed = (u8 *)&p->aIndex[nIndex];
187609
187610  /* Fill in the zName and zDb fields of the vtab structure. */
187611  zCsr = (char *)&p->abNotindexed[nCol];
187612  p->zName = zCsr;
187613  memcpy(zCsr, argv[2], nName);
187614  zCsr += nName;
187615  p->zDb = zCsr;
187616  memcpy(zCsr, argv[1], nDb);
187617  zCsr += nDb;
187618
187619  /* Fill in the azColumn array */
187620  for(iCol=0; iCol<nCol; iCol++){
187621    char *z;
187622    int n = 0;
187623    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
187624    if( n>0 ){
187625      memcpy(zCsr, z, n);
187626    }
187627    zCsr[n] = '\0';
187628    sqlite3Fts3Dequote(zCsr);
187629    p->azColumn[iCol] = zCsr;
187630    zCsr += n+1;
187631    assert( zCsr <= &((char *)p)[nByte] );
187632  }
187633
187634  /* Fill in the abNotindexed array */
187635  for(iCol=0; iCol<nCol; iCol++){
187636    int n = (int)strlen(p->azColumn[iCol]);
187637    for(i=0; i<nNotindexed; i++){
187638      char *zNot = azNotindexed[i];
187639      if( zNot && n==(int)strlen(zNot)
187640       && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
187641      ){
187642        p->abNotindexed[iCol] = 1;
187643        sqlite3_free(zNot);
187644        azNotindexed[i] = 0;
187645      }
187646    }
187647  }
187648  for(i=0; i<nNotindexed; i++){
187649    if( azNotindexed[i] ){
187650      sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
187651      rc = SQLITE_ERROR;
187652    }
187653  }
187654
187655  if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
187656    char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
187657    rc = SQLITE_ERROR;
187658    sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
187659  }
187660  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
187661  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
187662  if( rc!=SQLITE_OK ) goto fts3_init_out;
187663
187664  /* If this is an xCreate call, create the underlying tables in the
187665  ** database. TODO: For xConnect(), it could verify that said tables exist.
187666  */
187667  if( isCreate ){
187668    rc = fts3CreateTables(p);
187669  }
187670
187671  /* Check to see if a legacy fts3 table has been "upgraded" by the
187672  ** addition of a %_stat table so that it can use incremental merge.
187673  */
187674  if( !isFts4 && !isCreate ){
187675    p->bHasStat = 2;
187676  }
187677
187678  /* Figure out the page-size for the database. This is required in order to
187679  ** estimate the cost of loading large doclists from the database.  */
187680  fts3DatabasePageSize(&rc, p);
187681  p->nNodeSize = p->nPgsz-35;
187682
187683#if defined(SQLITE_DEBUG)||defined(SQLITE_TEST)
187684  p->nMergeCount = FTS3_MERGE_COUNT;
187685#endif
187686
187687  /* Declare the table schema to SQLite. */
187688  fts3DeclareVtab(&rc, p);
187689
187690fts3_init_out:
187691  sqlite3_free(zPrefix);
187692  sqlite3_free(aIndex);
187693  sqlite3_free(zCompress);
187694  sqlite3_free(zUncompress);
187695  sqlite3_free(zContent);
187696  sqlite3_free(zLanguageid);
187697  for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
187698  sqlite3_free((void *)aCol);
187699  sqlite3_free((void *)azNotindexed);
187700  if( rc!=SQLITE_OK ){
187701    if( p ){
187702      fts3DisconnectMethod((sqlite3_vtab *)p);
187703    }else if( pTokenizer ){
187704      pTokenizer->pModule->xDestroy(pTokenizer);
187705    }
187706  }else{
187707    assert( p->pSegments==0 );
187708    *ppVTab = &p->base;
187709  }
187710  return rc;
187711}
187712
187713/*
187714** The xConnect() and xCreate() methods for the virtual table. All the
187715** work is done in function fts3InitVtab().
187716*/
187717static int fts3ConnectMethod(
187718  sqlite3 *db,                    /* Database connection */
187719  void *pAux,                     /* Pointer to tokenizer hash table */
187720  int argc,                       /* Number of elements in argv array */
187721  const char * const *argv,       /* xCreate/xConnect argument array */
187722  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
187723  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
187724){
187725  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
187726}
187727static int fts3CreateMethod(
187728  sqlite3 *db,                    /* Database connection */
187729  void *pAux,                     /* Pointer to tokenizer hash table */
187730  int argc,                       /* Number of elements in argv array */
187731  const char * const *argv,       /* xCreate/xConnect argument array */
187732  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
187733  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
187734){
187735  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
187736}
187737
187738/*
187739** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
187740** extension is currently being used by a version of SQLite too old to
187741** support estimatedRows. In that case this function is a no-op.
187742*/
187743static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
187744#if SQLITE_VERSION_NUMBER>=3008002
187745  if( sqlite3_libversion_number()>=3008002 ){
187746    pIdxInfo->estimatedRows = nRow;
187747  }
187748#endif
187749}
187750
187751/*
187752** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
187753** extension is currently being used by a version of SQLite too old to
187754** support index-info flags. In that case this function is a no-op.
187755*/
187756static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
187757#if SQLITE_VERSION_NUMBER>=3008012
187758  if( sqlite3_libversion_number()>=3008012 ){
187759    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
187760  }
187761#endif
187762}
187763
187764/*
187765** Implementation of the xBestIndex method for FTS3 tables. There
187766** are three possible strategies, in order of preference:
187767**
187768**   1. Direct lookup by rowid or docid.
187769**   2. Full-text search using a MATCH operator on a non-docid column.
187770**   3. Linear scan of %_content table.
187771*/
187772static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
187773  Fts3Table *p = (Fts3Table *)pVTab;
187774  int i;                          /* Iterator variable */
187775  int iCons = -1;                 /* Index of constraint to use */
187776
187777  int iLangidCons = -1;           /* Index of langid=x constraint, if present */
187778  int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
187779  int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
187780  int iIdx;
187781
187782  if( p->bLock ){
187783    return SQLITE_ERROR;
187784  }
187785
187786  /* By default use a full table scan. This is an expensive option,
187787  ** so search through the constraints to see if a more efficient
187788  ** strategy is possible.
187789  */
187790  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
187791  pInfo->estimatedCost = 5000000;
187792  for(i=0; i<pInfo->nConstraint; i++){
187793    int bDocid;                 /* True if this constraint is on docid */
187794    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
187795    if( pCons->usable==0 ){
187796      if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
187797        /* There exists an unusable MATCH constraint. This means that if
187798        ** the planner does elect to use the results of this call as part
187799        ** of the overall query plan the user will see an "unable to use
187800        ** function MATCH in the requested context" error. To discourage
187801        ** this, return a very high cost here.  */
187802        pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
187803        pInfo->estimatedCost = 1e50;
187804        fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
187805        return SQLITE_OK;
187806      }
187807      continue;
187808    }
187809
187810    bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
187811
187812    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
187813    if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
187814      pInfo->idxNum = FTS3_DOCID_SEARCH;
187815      pInfo->estimatedCost = 1.0;
187816      iCons = i;
187817    }
187818
187819    /* A MATCH constraint. Use a full-text search.
187820    **
187821    ** If there is more than one MATCH constraint available, use the first
187822    ** one encountered. If there is both a MATCH constraint and a direct
187823    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
187824    ** though the rowid/docid lookup is faster than a MATCH query, selecting
187825    ** it would lead to an "unable to use function MATCH in the requested
187826    ** context" error.
187827    */
187828    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
187829     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
187830    ){
187831      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
187832      pInfo->estimatedCost = 2.0;
187833      iCons = i;
187834    }
187835
187836    /* Equality constraint on the langid column */
187837    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
187838     && pCons->iColumn==p->nColumn + 2
187839    ){
187840      iLangidCons = i;
187841    }
187842
187843    if( bDocid ){
187844      switch( pCons->op ){
187845        case SQLITE_INDEX_CONSTRAINT_GE:
187846        case SQLITE_INDEX_CONSTRAINT_GT:
187847          iDocidGe = i;
187848          break;
187849
187850        case SQLITE_INDEX_CONSTRAINT_LE:
187851        case SQLITE_INDEX_CONSTRAINT_LT:
187852          iDocidLe = i;
187853          break;
187854      }
187855    }
187856  }
187857
187858  /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
187859  if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
187860
187861  iIdx = 1;
187862  if( iCons>=0 ){
187863    pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
187864    pInfo->aConstraintUsage[iCons].omit = 1;
187865  }
187866  if( iLangidCons>=0 ){
187867    pInfo->idxNum |= FTS3_HAVE_LANGID;
187868    pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
187869  }
187870  if( iDocidGe>=0 ){
187871    pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
187872    pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
187873  }
187874  if( iDocidLe>=0 ){
187875    pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
187876    pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
187877  }
187878
187879  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
187880  ** docid) order. Both ascending and descending are possible.
187881  */
187882  if( pInfo->nOrderBy==1 ){
187883    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
187884    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
187885      if( pOrder->desc ){
187886        pInfo->idxStr = "DESC";
187887      }else{
187888        pInfo->idxStr = "ASC";
187889      }
187890      pInfo->orderByConsumed = 1;
187891    }
187892  }
187893
187894  assert( p->pSegments==0 );
187895  return SQLITE_OK;
187896}
187897
187898/*
187899** Implementation of xOpen method.
187900*/
187901static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
187902  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
187903
187904  UNUSED_PARAMETER(pVTab);
187905
187906  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
187907  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
187908  ** if the allocation fails, return SQLITE_NOMEM.
187909  */
187910  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
187911  if( !pCsr ){
187912    return SQLITE_NOMEM;
187913  }
187914  memset(pCsr, 0, sizeof(Fts3Cursor));
187915  return SQLITE_OK;
187916}
187917
187918/*
187919** Finalize the statement handle at pCsr->pStmt.
187920**
187921** Or, if that statement handle is one created by fts3CursorSeekStmt(),
187922** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
187923** pointer there instead of finalizing it.
187924*/
187925static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
187926  if( pCsr->bSeekStmt ){
187927    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
187928    if( p->pSeekStmt==0 ){
187929      p->pSeekStmt = pCsr->pStmt;
187930      sqlite3_reset(pCsr->pStmt);
187931      pCsr->pStmt = 0;
187932    }
187933    pCsr->bSeekStmt = 0;
187934  }
187935  sqlite3_finalize(pCsr->pStmt);
187936}
187937
187938/*
187939** Free all resources currently held by the cursor passed as the only
187940** argument.
187941*/
187942static void fts3ClearCursor(Fts3Cursor *pCsr){
187943  fts3CursorFinalizeStmt(pCsr);
187944  sqlite3Fts3FreeDeferredTokens(pCsr);
187945  sqlite3_free(pCsr->aDoclist);
187946  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
187947  sqlite3Fts3ExprFree(pCsr->pExpr);
187948  memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
187949}
187950
187951/*
187952** Close the cursor.  For additional information see the documentation
187953** on the xClose method of the virtual table interface.
187954*/
187955static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
187956  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
187957  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
187958  fts3ClearCursor(pCsr);
187959  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
187960  sqlite3_free(pCsr);
187961  return SQLITE_OK;
187962}
187963
187964/*
187965** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
187966** compose and prepare an SQL statement of the form:
187967**
187968**    "SELECT <columns> FROM %_content WHERE rowid = ?"
187969**
187970** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
187971** it. If an error occurs, return an SQLite error code.
187972*/
187973static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
187974  int rc = SQLITE_OK;
187975  if( pCsr->pStmt==0 ){
187976    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
187977    char *zSql;
187978    if( p->pSeekStmt ){
187979      pCsr->pStmt = p->pSeekStmt;
187980      p->pSeekStmt = 0;
187981    }else{
187982      zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
187983      if( !zSql ) return SQLITE_NOMEM;
187984      p->bLock++;
187985      rc = sqlite3_prepare_v3(
187986          p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0
187987      );
187988      p->bLock--;
187989      sqlite3_free(zSql);
187990    }
187991    if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
187992  }
187993  return rc;
187994}
187995
187996/*
187997** Position the pCsr->pStmt statement so that it is on the row
187998** of the %_content table that contains the last match.  Return
187999** SQLITE_OK on success.
188000*/
188001static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
188002  int rc = SQLITE_OK;
188003  if( pCsr->isRequireSeek ){
188004    rc = fts3CursorSeekStmt(pCsr);
188005    if( rc==SQLITE_OK ){
188006      Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab;
188007      pTab->bLock++;
188008      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
188009      pCsr->isRequireSeek = 0;
188010      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
188011        pTab->bLock--;
188012        return SQLITE_OK;
188013      }else{
188014        pTab->bLock--;
188015        rc = sqlite3_reset(pCsr->pStmt);
188016        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
188017          /* If no row was found and no error has occurred, then the %_content
188018          ** table is missing a row that is present in the full-text index.
188019          ** The data structures are corrupt.  */
188020          rc = FTS_CORRUPT_VTAB;
188021          pCsr->isEof = 1;
188022        }
188023      }
188024    }
188025  }
188026
188027  if( rc!=SQLITE_OK && pContext ){
188028    sqlite3_result_error_code(pContext, rc);
188029  }
188030  return rc;
188031}
188032
188033/*
188034** This function is used to process a single interior node when searching
188035** a b-tree for a term or term prefix. The node data is passed to this
188036** function via the zNode/nNode parameters. The term to search for is
188037** passed in zTerm/nTerm.
188038**
188039** If piFirst is not NULL, then this function sets *piFirst to the blockid
188040** of the child node that heads the sub-tree that may contain the term.
188041**
188042** If piLast is not NULL, then *piLast is set to the right-most child node
188043** that heads a sub-tree that may contain a term for which zTerm/nTerm is
188044** a prefix.
188045**
188046** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
188047*/
188048static int fts3ScanInteriorNode(
188049  const char *zTerm,              /* Term to select leaves for */
188050  int nTerm,                      /* Size of term zTerm in bytes */
188051  const char *zNode,              /* Buffer containing segment interior node */
188052  int nNode,                      /* Size of buffer at zNode */
188053  sqlite3_int64 *piFirst,         /* OUT: Selected child node */
188054  sqlite3_int64 *piLast           /* OUT: Selected child node */
188055){
188056  int rc = SQLITE_OK;             /* Return code */
188057  const char *zCsr = zNode;       /* Cursor to iterate through node */
188058  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
188059  char *zBuffer = 0;              /* Buffer to load terms into */
188060  i64 nAlloc = 0;                 /* Size of allocated buffer */
188061  int isFirstTerm = 1;            /* True when processing first term on page */
188062  u64 iChild;                     /* Block id of child node to descend to */
188063  int nBuffer = 0;                /* Total term size */
188064
188065  /* Skip over the 'height' varint that occurs at the start of every
188066  ** interior node. Then load the blockid of the left-child of the b-tree
188067  ** node into variable iChild.
188068  **
188069  ** Even if the data structure on disk is corrupted, this (reading two
188070  ** varints from the buffer) does not risk an overread. If zNode is a
188071  ** root node, then the buffer comes from a SELECT statement. SQLite does
188072  ** not make this guarantee explicitly, but in practice there are always
188073  ** either more than 20 bytes of allocated space following the nNode bytes of
188074  ** contents, or two zero bytes. Or, if the node is read from the %_segments
188075  ** table, then there are always 20 bytes of zeroed padding following the
188076  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
188077  */
188078  zCsr += sqlite3Fts3GetVarintU(zCsr, &iChild);
188079  zCsr += sqlite3Fts3GetVarintU(zCsr, &iChild);
188080  if( zCsr>zEnd ){
188081    return FTS_CORRUPT_VTAB;
188082  }
188083
188084  while( zCsr<zEnd && (piFirst || piLast) ){
188085    int cmp;                      /* memcmp() result */
188086    int nSuffix;                  /* Size of term suffix */
188087    int nPrefix = 0;              /* Size of term prefix */
188088
188089    /* Load the next term on the node into zBuffer. Use realloc() to expand
188090    ** the size of zBuffer if required.  */
188091    if( !isFirstTerm ){
188092      zCsr += fts3GetVarint32(zCsr, &nPrefix);
188093      if( nPrefix>nBuffer ){
188094        rc = FTS_CORRUPT_VTAB;
188095        goto finish_scan;
188096      }
188097    }
188098    isFirstTerm = 0;
188099    zCsr += fts3GetVarint32(zCsr, &nSuffix);
188100
188101    assert( nPrefix>=0 && nSuffix>=0 );
188102    if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr || nSuffix==0 ){
188103      rc = FTS_CORRUPT_VTAB;
188104      goto finish_scan;
188105    }
188106    if( (i64)nPrefix+nSuffix>nAlloc ){
188107      char *zNew;
188108      nAlloc = ((i64)nPrefix+nSuffix) * 2;
188109      zNew = (char *)sqlite3_realloc64(zBuffer, nAlloc);
188110      if( !zNew ){
188111        rc = SQLITE_NOMEM;
188112        goto finish_scan;
188113      }
188114      zBuffer = zNew;
188115    }
188116    assert( zBuffer );
188117    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
188118    nBuffer = nPrefix + nSuffix;
188119    zCsr += nSuffix;
188120
188121    /* Compare the term we are searching for with the term just loaded from
188122    ** the interior node. If the specified term is greater than or equal
188123    ** to the term from the interior node, then all terms on the sub-tree
188124    ** headed by node iChild are smaller than zTerm. No need to search
188125    ** iChild.
188126    **
188127    ** If the interior node term is larger than the specified term, then
188128    ** the tree headed by iChild may contain the specified term.
188129    */
188130    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
188131    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
188132      *piFirst = (i64)iChild;
188133      piFirst = 0;
188134    }
188135
188136    if( piLast && cmp<0 ){
188137      *piLast = (i64)iChild;
188138      piLast = 0;
188139    }
188140
188141    iChild++;
188142  };
188143
188144  if( piFirst ) *piFirst = (i64)iChild;
188145  if( piLast ) *piLast = (i64)iChild;
188146
188147 finish_scan:
188148  sqlite3_free(zBuffer);
188149  return rc;
188150}
188151
188152
188153/*
188154** The buffer pointed to by argument zNode (size nNode bytes) contains an
188155** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
188156** contains a term. This function searches the sub-tree headed by the zNode
188157** node for the range of leaf nodes that may contain the specified term
188158** or terms for which the specified term is a prefix.
188159**
188160** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
188161** left-most leaf node in the tree that may contain the specified term.
188162** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
188163** right-most leaf node that may contain a term for which the specified
188164** term is a prefix.
188165**
188166** It is possible that the range of returned leaf nodes does not contain
188167** the specified term or any terms for which it is a prefix. However, if the
188168** segment does contain any such terms, they are stored within the identified
188169** range. Because this function only inspects interior segment nodes (and
188170** never loads leaf nodes into memory), it is not possible to be sure.
188171**
188172** If an error occurs, an error code other than SQLITE_OK is returned.
188173*/
188174static int fts3SelectLeaf(
188175  Fts3Table *p,                   /* Virtual table handle */
188176  const char *zTerm,              /* Term to select leaves for */
188177  int nTerm,                      /* Size of term zTerm in bytes */
188178  const char *zNode,              /* Buffer containing segment interior node */
188179  int nNode,                      /* Size of buffer at zNode */
188180  sqlite3_int64 *piLeaf,          /* Selected leaf node */
188181  sqlite3_int64 *piLeaf2          /* Selected leaf node */
188182){
188183  int rc = SQLITE_OK;             /* Return code */
188184  int iHeight;                    /* Height of this node in tree */
188185
188186  assert( piLeaf || piLeaf2 );
188187
188188  fts3GetVarint32(zNode, &iHeight);
188189  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
188190  assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
188191
188192  if( rc==SQLITE_OK && iHeight>1 ){
188193    char *zBlob = 0;              /* Blob read from %_segments table */
188194    int nBlob = 0;                /* Size of zBlob in bytes */
188195
188196    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
188197      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
188198      if( rc==SQLITE_OK ){
188199        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
188200      }
188201      sqlite3_free(zBlob);
188202      piLeaf = 0;
188203      zBlob = 0;
188204    }
188205
188206    if( rc==SQLITE_OK ){
188207      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
188208    }
188209    if( rc==SQLITE_OK ){
188210      int iNewHeight = 0;
188211      fts3GetVarint32(zBlob, &iNewHeight);
188212      if( iNewHeight>=iHeight ){
188213        rc = FTS_CORRUPT_VTAB;
188214      }else{
188215        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
188216      }
188217    }
188218    sqlite3_free(zBlob);
188219  }
188220
188221  return rc;
188222}
188223
188224/*
188225** This function is used to create delta-encoded serialized lists of FTS3
188226** varints. Each call to this function appends a single varint to a list.
188227*/
188228static void fts3PutDeltaVarint(
188229  char **pp,                      /* IN/OUT: Output pointer */
188230  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
188231  sqlite3_int64 iVal              /* Write this value to the list */
188232){
188233  assert_fts3_nc( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
188234  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
188235  *piPrev = iVal;
188236}
188237
188238/*
188239** When this function is called, *ppPoslist is assumed to point to the
188240** start of a position-list. After it returns, *ppPoslist points to the
188241** first byte after the position-list.
188242**
188243** A position list is list of positions (delta encoded) and columns for
188244** a single document record of a doclist.  So, in other words, this
188245** routine advances *ppPoslist so that it points to the next docid in
188246** the doclist, or to the first byte past the end of the doclist.
188247**
188248** If pp is not NULL, then the contents of the position list are copied
188249** to *pp. *pp is set to point to the first byte past the last byte copied
188250** before this function returns.
188251*/
188252static void fts3PoslistCopy(char **pp, char **ppPoslist){
188253  char *pEnd = *ppPoslist;
188254  char c = 0;
188255
188256  /* The end of a position list is marked by a zero encoded as an FTS3
188257  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
188258  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
188259  ** of some other, multi-byte, value.
188260  **
188261  ** The following while-loop moves pEnd to point to the first byte that is not
188262  ** immediately preceded by a byte with the 0x80 bit set. Then increments
188263  ** pEnd once more so that it points to the byte immediately following the
188264  ** last byte in the position-list.
188265  */
188266  while( *pEnd | c ){
188267    c = *pEnd++ & 0x80;
188268    testcase( c!=0 && (*pEnd)==0 );
188269  }
188270  pEnd++;  /* Advance past the POS_END terminator byte */
188271
188272  if( pp ){
188273    int n = (int)(pEnd - *ppPoslist);
188274    char *p = *pp;
188275    memcpy(p, *ppPoslist, n);
188276    p += n;
188277    *pp = p;
188278  }
188279  *ppPoslist = pEnd;
188280}
188281
188282/*
188283** When this function is called, *ppPoslist is assumed to point to the
188284** start of a column-list. After it returns, *ppPoslist points to the
188285** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
188286**
188287** A column-list is list of delta-encoded positions for a single column
188288** within a single document within a doclist.
188289**
188290** The column-list is terminated either by a POS_COLUMN varint (1) or
188291** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
188292** the POS_COLUMN or POS_END that terminates the column-list.
188293**
188294** If pp is not NULL, then the contents of the column-list are copied
188295** to *pp. *pp is set to point to the first byte past the last byte copied
188296** before this function returns.  The POS_COLUMN or POS_END terminator
188297** is not copied into *pp.
188298*/
188299static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
188300  char *pEnd = *ppPoslist;
188301  char c = 0;
188302
188303  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
188304  ** not part of a multi-byte varint.
188305  */
188306  while( 0xFE & (*pEnd | c) ){
188307    c = *pEnd++ & 0x80;
188308    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
188309  }
188310  if( pp ){
188311    int n = (int)(pEnd - *ppPoslist);
188312    char *p = *pp;
188313    memcpy(p, *ppPoslist, n);
188314    p += n;
188315    *pp = p;
188316  }
188317  *ppPoslist = pEnd;
188318}
188319
188320/*
188321** Value used to signify the end of an position-list. This must be
188322** as large or larger than any value that might appear on the
188323** position-list, even a position list that has been corrupted.
188324*/
188325#define POSITION_LIST_END LARGEST_INT64
188326
188327/*
188328** This function is used to help parse position-lists. When this function is
188329** called, *pp may point to the start of the next varint in the position-list
188330** being parsed, or it may point to 1 byte past the end of the position-list
188331** (in which case **pp will be a terminator bytes POS_END (0) or
188332** (1)).
188333**
188334** If *pp points past the end of the current position-list, set *pi to
188335** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
188336** increment the current value of *pi by the value read, and set *pp to
188337** point to the next value before returning.
188338**
188339** Before calling this routine *pi must be initialized to the value of
188340** the previous position, or zero if we are reading the first position
188341** in the position-list.  Because positions are delta-encoded, the value
188342** of the previous position is needed in order to compute the value of
188343** the next position.
188344*/
188345static void fts3ReadNextPos(
188346  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
188347  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
188348){
188349  if( (**pp)&0xFE ){
188350    int iVal;
188351    *pp += fts3GetVarint32((*pp), &iVal);
188352    *pi += iVal;
188353    *pi -= 2;
188354  }else{
188355    *pi = POSITION_LIST_END;
188356  }
188357}
188358
188359/*
188360** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
188361** the value of iCol encoded as a varint to *pp.   This will start a new
188362** column list.
188363**
188364** Set *pp to point to the byte just after the last byte written before
188365** returning (do not modify it if iCol==0). Return the total number of bytes
188366** written (0 if iCol==0).
188367*/
188368static int fts3PutColNumber(char **pp, int iCol){
188369  int n = 0;                      /* Number of bytes written */
188370  if( iCol ){
188371    char *p = *pp;                /* Output pointer */
188372    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
188373    *p = 0x01;
188374    *pp = &p[n];
188375  }
188376  return n;
188377}
188378
188379/*
188380** Compute the union of two position lists.  The output written
188381** into *pp contains all positions of both *pp1 and *pp2 in sorted
188382** order and with any duplicates removed.  All pointers are
188383** updated appropriately.   The caller is responsible for insuring
188384** that there is enough space in *pp to hold the complete output.
188385*/
188386static int fts3PoslistMerge(
188387  char **pp,                      /* Output buffer */
188388  char **pp1,                     /* Left input list */
188389  char **pp2                      /* Right input list */
188390){
188391  char *p = *pp;
188392  char *p1 = *pp1;
188393  char *p2 = *pp2;
188394
188395  while( *p1 || *p2 ){
188396    int iCol1;         /* The current column index in pp1 */
188397    int iCol2;         /* The current column index in pp2 */
188398
188399    if( *p1==POS_COLUMN ){
188400      fts3GetVarint32(&p1[1], &iCol1);
188401      if( iCol1==0 ) return FTS_CORRUPT_VTAB;
188402    }
188403    else if( *p1==POS_END ) iCol1 = 0x7fffffff;
188404    else iCol1 = 0;
188405
188406    if( *p2==POS_COLUMN ){
188407      fts3GetVarint32(&p2[1], &iCol2);
188408      if( iCol2==0 ) return FTS_CORRUPT_VTAB;
188409    }
188410    else if( *p2==POS_END ) iCol2 = 0x7fffffff;
188411    else iCol2 = 0;
188412
188413    if( iCol1==iCol2 ){
188414      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
188415      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
188416      sqlite3_int64 iPrev = 0;
188417      int n = fts3PutColNumber(&p, iCol1);
188418      p1 += n;
188419      p2 += n;
188420
188421      /* At this point, both p1 and p2 point to the start of column-lists
188422      ** for the same column (the column with index iCol1 and iCol2).
188423      ** A column-list is a list of non-negative delta-encoded varints, each
188424      ** incremented by 2 before being stored. Each list is terminated by a
188425      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
188426      ** and writes the results to buffer p. p is left pointing to the byte
188427      ** after the list written. No terminator (POS_END or POS_COLUMN) is
188428      ** written to the output.
188429      */
188430      fts3GetDeltaVarint(&p1, &i1);
188431      fts3GetDeltaVarint(&p2, &i2);
188432      if( i1<2 || i2<2 ){
188433        break;
188434      }
188435      do {
188436        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
188437        iPrev -= 2;
188438        if( i1==i2 ){
188439          fts3ReadNextPos(&p1, &i1);
188440          fts3ReadNextPos(&p2, &i2);
188441        }else if( i1<i2 ){
188442          fts3ReadNextPos(&p1, &i1);
188443        }else{
188444          fts3ReadNextPos(&p2, &i2);
188445        }
188446      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
188447    }else if( iCol1<iCol2 ){
188448      p1 += fts3PutColNumber(&p, iCol1);
188449      fts3ColumnlistCopy(&p, &p1);
188450    }else{
188451      p2 += fts3PutColNumber(&p, iCol2);
188452      fts3ColumnlistCopy(&p, &p2);
188453    }
188454  }
188455
188456  *p++ = POS_END;
188457  *pp = p;
188458  *pp1 = p1 + 1;
188459  *pp2 = p2 + 1;
188460  return SQLITE_OK;
188461}
188462
188463/*
188464** This function is used to merge two position lists into one. When it is
188465** called, *pp1 and *pp2 must both point to position lists. A position-list is
188466** the part of a doclist that follows each document id. For example, if a row
188467** contains:
188468**
188469**     'a b c'|'x y z'|'a b b a'
188470**
188471** Then the position list for this row for token 'b' would consist of:
188472**
188473**     0x02 0x01 0x02 0x03 0x03 0x00
188474**
188475** When this function returns, both *pp1 and *pp2 are left pointing to the
188476** byte following the 0x00 terminator of their respective position lists.
188477**
188478** If isSaveLeft is 0, an entry is added to the output position list for
188479** each position in *pp2 for which there exists one or more positions in
188480** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
188481** when the *pp1 token appears before the *pp2 token, but not more than nToken
188482** slots before it.
188483**
188484** e.g. nToken==1 searches for adjacent positions.
188485*/
188486static int fts3PoslistPhraseMerge(
188487  char **pp,                      /* IN/OUT: Preallocated output buffer */
188488  int nToken,                     /* Maximum difference in token positions */
188489  int isSaveLeft,                 /* Save the left position */
188490  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
188491  char **pp1,                     /* IN/OUT: Left input list */
188492  char **pp2                      /* IN/OUT: Right input list */
188493){
188494  char *p = *pp;
188495  char *p1 = *pp1;
188496  char *p2 = *pp2;
188497  int iCol1 = 0;
188498  int iCol2 = 0;
188499
188500  /* Never set both isSaveLeft and isExact for the same invocation. */
188501  assert( isSaveLeft==0 || isExact==0 );
188502
188503  assert_fts3_nc( p!=0 && *p1!=0 && *p2!=0 );
188504  if( *p1==POS_COLUMN ){
188505    p1++;
188506    p1 += fts3GetVarint32(p1, &iCol1);
188507  }
188508  if( *p2==POS_COLUMN ){
188509    p2++;
188510    p2 += fts3GetVarint32(p2, &iCol2);
188511  }
188512
188513  while( 1 ){
188514    if( iCol1==iCol2 ){
188515      char *pSave = p;
188516      sqlite3_int64 iPrev = 0;
188517      sqlite3_int64 iPos1 = 0;
188518      sqlite3_int64 iPos2 = 0;
188519
188520      if( iCol1 ){
188521        *p++ = POS_COLUMN;
188522        p += sqlite3Fts3PutVarint(p, iCol1);
188523      }
188524
188525      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
188526      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
188527      if( iPos1<0 || iPos2<0 ) break;
188528
188529      while( 1 ){
188530        if( iPos2==iPos1+nToken
188531         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
188532        ){
188533          sqlite3_int64 iSave;
188534          iSave = isSaveLeft ? iPos1 : iPos2;
188535          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
188536          pSave = 0;
188537          assert( p );
188538        }
188539        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
188540          if( (*p2&0xFE)==0 ) break;
188541          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
188542        }else{
188543          if( (*p1&0xFE)==0 ) break;
188544          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
188545        }
188546      }
188547
188548      if( pSave ){
188549        assert( pp && p );
188550        p = pSave;
188551      }
188552
188553      fts3ColumnlistCopy(0, &p1);
188554      fts3ColumnlistCopy(0, &p2);
188555      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
188556      if( 0==*p1 || 0==*p2 ) break;
188557
188558      p1++;
188559      p1 += fts3GetVarint32(p1, &iCol1);
188560      p2++;
188561      p2 += fts3GetVarint32(p2, &iCol2);
188562    }
188563
188564    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
188565    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
188566    ** end of the position list, or the 0x01 that precedes the next
188567    ** column-number in the position list.
188568    */
188569    else if( iCol1<iCol2 ){
188570      fts3ColumnlistCopy(0, &p1);
188571      if( 0==*p1 ) break;
188572      p1++;
188573      p1 += fts3GetVarint32(p1, &iCol1);
188574    }else{
188575      fts3ColumnlistCopy(0, &p2);
188576      if( 0==*p2 ) break;
188577      p2++;
188578      p2 += fts3GetVarint32(p2, &iCol2);
188579    }
188580  }
188581
188582  fts3PoslistCopy(0, &p2);
188583  fts3PoslistCopy(0, &p1);
188584  *pp1 = p1;
188585  *pp2 = p2;
188586  if( *pp==p ){
188587    return 0;
188588  }
188589  *p++ = 0x00;
188590  *pp = p;
188591  return 1;
188592}
188593
188594/*
188595** Merge two position-lists as required by the NEAR operator. The argument
188596** position lists correspond to the left and right phrases of an expression
188597** like:
188598**
188599**     "phrase 1" NEAR "phrase number 2"
188600**
188601** Position list *pp1 corresponds to the left-hand side of the NEAR
188602** expression and *pp2 to the right. As usual, the indexes in the position
188603** lists are the offsets of the last token in each phrase (tokens "1" and "2"
188604** in the example above).
188605**
188606** The output position list - written to *pp - is a copy of *pp2 with those
188607** entries that are not sufficiently NEAR entries in *pp1 removed.
188608*/
188609static int fts3PoslistNearMerge(
188610  char **pp,                      /* Output buffer */
188611  char *aTmp,                     /* Temporary buffer space */
188612  int nRight,                     /* Maximum difference in token positions */
188613  int nLeft,                      /* Maximum difference in token positions */
188614  char **pp1,                     /* IN/OUT: Left input list */
188615  char **pp2                      /* IN/OUT: Right input list */
188616){
188617  char *p1 = *pp1;
188618  char *p2 = *pp2;
188619
188620  char *pTmp1 = aTmp;
188621  char *pTmp2;
188622  char *aTmp2;
188623  int res = 1;
188624
188625  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
188626  aTmp2 = pTmp2 = pTmp1;
188627  *pp1 = p1;
188628  *pp2 = p2;
188629  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
188630  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
188631    fts3PoslistMerge(pp, &aTmp, &aTmp2);
188632  }else if( pTmp1!=aTmp ){
188633    fts3PoslistCopy(pp, &aTmp);
188634  }else if( pTmp2!=aTmp2 ){
188635    fts3PoslistCopy(pp, &aTmp2);
188636  }else{
188637    res = 0;
188638  }
188639
188640  return res;
188641}
188642
188643/*
188644** An instance of this function is used to merge together the (potentially
188645** large number of) doclists for each term that matches a prefix query.
188646** See function fts3TermSelectMerge() for details.
188647*/
188648typedef struct TermSelect TermSelect;
188649struct TermSelect {
188650  char *aaOutput[16];             /* Malloc'd output buffers */
188651  int anOutput[16];               /* Size each output buffer in bytes */
188652};
188653
188654/*
188655** This function is used to read a single varint from a buffer. Parameter
188656** pEnd points 1 byte past the end of the buffer. When this function is
188657** called, if *pp points to pEnd or greater, then the end of the buffer
188658** has been reached. In this case *pp is set to 0 and the function returns.
188659**
188660** If *pp does not point to or past pEnd, then a single varint is read
188661** from *pp. *pp is then set to point 1 byte past the end of the read varint.
188662**
188663** If bDescIdx is false, the value read is added to *pVal before returning.
188664** If it is true, the value read is subtracted from *pVal before this
188665** function returns.
188666*/
188667static void fts3GetDeltaVarint3(
188668  char **pp,                      /* IN/OUT: Point to read varint from */
188669  char *pEnd,                     /* End of buffer */
188670  int bDescIdx,                   /* True if docids are descending */
188671  sqlite3_int64 *pVal             /* IN/OUT: Integer value */
188672){
188673  if( *pp>=pEnd ){
188674    *pp = 0;
188675  }else{
188676    u64 iVal;
188677    *pp += sqlite3Fts3GetVarintU(*pp, &iVal);
188678    if( bDescIdx ){
188679      *pVal = (i64)((u64)*pVal - iVal);
188680    }else{
188681      *pVal = (i64)((u64)*pVal + iVal);
188682    }
188683  }
188684}
188685
188686/*
188687** This function is used to write a single varint to a buffer. The varint
188688** is written to *pp. Before returning, *pp is set to point 1 byte past the
188689** end of the value written.
188690**
188691** If *pbFirst is zero when this function is called, the value written to
188692** the buffer is that of parameter iVal.
188693**
188694** If *pbFirst is non-zero when this function is called, then the value
188695** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
188696** (if bDescIdx is non-zero).
188697**
188698** Before returning, this function always sets *pbFirst to 1 and *piPrev
188699** to the value of parameter iVal.
188700*/
188701static void fts3PutDeltaVarint3(
188702  char **pp,                      /* IN/OUT: Output pointer */
188703  int bDescIdx,                   /* True for descending docids */
188704  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
188705  int *pbFirst,                   /* IN/OUT: True after first int written */
188706  sqlite3_int64 iVal              /* Write this value to the list */
188707){
188708  sqlite3_uint64 iWrite;
188709  if( bDescIdx==0 || *pbFirst==0 ){
188710    assert_fts3_nc( *pbFirst==0 || iVal>=*piPrev );
188711    iWrite = (u64)iVal - (u64)*piPrev;
188712  }else{
188713    assert_fts3_nc( *piPrev>=iVal );
188714    iWrite = (u64)*piPrev - (u64)iVal;
188715  }
188716  assert( *pbFirst || *piPrev==0 );
188717  assert_fts3_nc( *pbFirst==0 || iWrite>0 );
188718  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
188719  *piPrev = iVal;
188720  *pbFirst = 1;
188721}
188722
188723
188724/*
188725** This macro is used by various functions that merge doclists. The two
188726** arguments are 64-bit docid values. If the value of the stack variable
188727** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
188728** Otherwise, (i2-i1).
188729**
188730** Using this makes it easier to write code that can merge doclists that are
188731** sorted in either ascending or descending order.
188732*/
188733/* #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i64)((u64)i1-i2)) */
188734#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1>i2?1:((i1==i2)?0:-1)))
188735
188736/*
188737** This function does an "OR" merge of two doclists (output contains all
188738** positions contained in either argument doclist). If the docids in the
188739** input doclists are sorted in ascending order, parameter bDescDoclist
188740** should be false. If they are sorted in ascending order, it should be
188741** passed a non-zero value.
188742**
188743** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
188744** containing the output doclist and SQLITE_OK is returned. In this case
188745** *pnOut is set to the number of bytes in the output doclist.
188746**
188747** If an error occurs, an SQLite error code is returned. The output values
188748** are undefined in this case.
188749*/
188750static int fts3DoclistOrMerge(
188751  int bDescDoclist,               /* True if arguments are desc */
188752  char *a1, int n1,               /* First doclist */
188753  char *a2, int n2,               /* Second doclist */
188754  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
188755){
188756  int rc = SQLITE_OK;
188757  sqlite3_int64 i1 = 0;
188758  sqlite3_int64 i2 = 0;
188759  sqlite3_int64 iPrev = 0;
188760  char *pEnd1 = &a1[n1];
188761  char *pEnd2 = &a2[n2];
188762  char *p1 = a1;
188763  char *p2 = a2;
188764  char *p;
188765  char *aOut;
188766  int bFirstOut = 0;
188767
188768  *paOut = 0;
188769  *pnOut = 0;
188770
188771  /* Allocate space for the output. Both the input and output doclists
188772  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
188773  ** then the first docid in each list is simply encoded as a varint. For
188774  ** each subsequent docid, the varint stored is the difference between the
188775  ** current and previous docid (a positive number - since the list is in
188776  ** ascending order).
188777  **
188778  ** The first docid written to the output is therefore encoded using the
188779  ** same number of bytes as it is in whichever of the input lists it is
188780  ** read from. And each subsequent docid read from the same input list
188781  ** consumes either the same or less bytes as it did in the input (since
188782  ** the difference between it and the previous value in the output must
188783  ** be a positive value less than or equal to the delta value read from
188784  ** the input list). The same argument applies to all but the first docid
188785  ** read from the 'other' list. And to the contents of all position lists
188786  ** that will be copied and merged from the input to the output.
188787  **
188788  ** However, if the first docid copied to the output is a negative number,
188789  ** then the encoding of the first docid from the 'other' input list may
188790  ** be larger in the output than it was in the input (since the delta value
188791  ** may be a larger positive integer than the actual docid).
188792  **
188793  ** The space required to store the output is therefore the sum of the
188794  ** sizes of the two inputs, plus enough space for exactly one of the input
188795  ** docids to grow.
188796  **
188797  ** A symetric argument may be made if the doclists are in descending
188798  ** order.
188799  */
188800  aOut = sqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING);
188801  if( !aOut ) return SQLITE_NOMEM;
188802
188803  p = aOut;
188804  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
188805  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
188806  while( p1 || p2 ){
188807    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
188808
188809    if( p2 && p1 && iDiff==0 ){
188810      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
188811      rc = fts3PoslistMerge(&p, &p1, &p2);
188812      if( rc ) break;
188813      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
188814      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
188815    }else if( !p2 || (p1 && iDiff<0) ){
188816      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
188817      fts3PoslistCopy(&p, &p1);
188818      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
188819    }else{
188820      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
188821      fts3PoslistCopy(&p, &p2);
188822      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
188823    }
188824
188825    assert( (p-aOut)<=((p1?(p1-a1):n1)+(p2?(p2-a2):n2)+FTS3_VARINT_MAX-1) );
188826  }
188827
188828  if( rc!=SQLITE_OK ){
188829    sqlite3_free(aOut);
188830    p = aOut = 0;
188831  }else{
188832    assert( (p-aOut)<=n1+n2+FTS3_VARINT_MAX-1 );
188833    memset(&aOut[(p-aOut)], 0, FTS3_BUFFER_PADDING);
188834  }
188835  *paOut = aOut;
188836  *pnOut = (int)(p-aOut);
188837  return rc;
188838}
188839
188840/*
188841** This function does a "phrase" merge of two doclists. In a phrase merge,
188842** the output contains a copy of each position from the right-hand input
188843** doclist for which there is a position in the left-hand input doclist
188844** exactly nDist tokens before it.
188845**
188846** If the docids in the input doclists are sorted in ascending order,
188847** parameter bDescDoclist should be false. If they are sorted in ascending
188848** order, it should be passed a non-zero value.
188849**
188850** The right-hand input doclist is overwritten by this function.
188851*/
188852static int fts3DoclistPhraseMerge(
188853  int bDescDoclist,               /* True if arguments are desc */
188854  int nDist,                      /* Distance from left to right (1=adjacent) */
188855  char *aLeft, int nLeft,         /* Left doclist */
188856  char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
188857){
188858  sqlite3_int64 i1 = 0;
188859  sqlite3_int64 i2 = 0;
188860  sqlite3_int64 iPrev = 0;
188861  char *aRight = *paRight;
188862  char *pEnd1 = &aLeft[nLeft];
188863  char *pEnd2 = &aRight[*pnRight];
188864  char *p1 = aLeft;
188865  char *p2 = aRight;
188866  char *p;
188867  int bFirstOut = 0;
188868  char *aOut;
188869
188870  assert( nDist>0 );
188871  if( bDescDoclist ){
188872    aOut = sqlite3_malloc64((sqlite3_int64)*pnRight + FTS3_VARINT_MAX);
188873    if( aOut==0 ) return SQLITE_NOMEM;
188874  }else{
188875    aOut = aRight;
188876  }
188877  p = aOut;
188878
188879  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
188880  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
188881
188882  while( p1 && p2 ){
188883    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
188884    if( iDiff==0 ){
188885      char *pSave = p;
188886      sqlite3_int64 iPrevSave = iPrev;
188887      int bFirstOutSave = bFirstOut;
188888
188889      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
188890      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
188891        p = pSave;
188892        iPrev = iPrevSave;
188893        bFirstOut = bFirstOutSave;
188894      }
188895      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
188896      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
188897    }else if( iDiff<0 ){
188898      fts3PoslistCopy(0, &p1);
188899      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
188900    }else{
188901      fts3PoslistCopy(0, &p2);
188902      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
188903    }
188904  }
188905
188906  *pnRight = (int)(p - aOut);
188907  if( bDescDoclist ){
188908    sqlite3_free(aRight);
188909    *paRight = aOut;
188910  }
188911
188912  return SQLITE_OK;
188913}
188914
188915/*
188916** Argument pList points to a position list nList bytes in size. This
188917** function checks to see if the position list contains any entries for
188918** a token in position 0 (of any column). If so, it writes argument iDelta
188919** to the output buffer pOut, followed by a position list consisting only
188920** of the entries from pList at position 0, and terminated by an 0x00 byte.
188921** The value returned is the number of bytes written to pOut (if any).
188922*/
188923SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
188924  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
188925  char *pList,                    /* Position list (no 0x00 term) */
188926  int nList,                      /* Size of pList in bytes */
188927  char *pOut                      /* Write output here */
188928){
188929  int nOut = 0;
188930  int bWritten = 0;               /* True once iDelta has been written */
188931  char *p = pList;
188932  char *pEnd = &pList[nList];
188933
188934  if( *p!=0x01 ){
188935    if( *p==0x02 ){
188936      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
188937      pOut[nOut++] = 0x02;
188938      bWritten = 1;
188939    }
188940    fts3ColumnlistCopy(0, &p);
188941  }
188942
188943  while( p<pEnd ){
188944    sqlite3_int64 iCol;
188945    p++;
188946    p += sqlite3Fts3GetVarint(p, &iCol);
188947    if( *p==0x02 ){
188948      if( bWritten==0 ){
188949        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
188950        bWritten = 1;
188951      }
188952      pOut[nOut++] = 0x01;
188953      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
188954      pOut[nOut++] = 0x02;
188955    }
188956    fts3ColumnlistCopy(0, &p);
188957  }
188958  if( bWritten ){
188959    pOut[nOut++] = 0x00;
188960  }
188961
188962  return nOut;
188963}
188964
188965
188966/*
188967** Merge all doclists in the TermSelect.aaOutput[] array into a single
188968** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
188969** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
188970**
188971** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
188972** the responsibility of the caller to free any doclists left in the
188973** TermSelect.aaOutput[] array.
188974*/
188975static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
188976  char *aOut = 0;
188977  int nOut = 0;
188978  int i;
188979
188980  /* Loop through the doclists in the aaOutput[] array. Merge them all
188981  ** into a single doclist.
188982  */
188983  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
188984    if( pTS->aaOutput[i] ){
188985      if( !aOut ){
188986        aOut = pTS->aaOutput[i];
188987        nOut = pTS->anOutput[i];
188988        pTS->aaOutput[i] = 0;
188989      }else{
188990        int nNew;
188991        char *aNew;
188992
188993        int rc = fts3DoclistOrMerge(p->bDescIdx,
188994            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
188995        );
188996        if( rc!=SQLITE_OK ){
188997          sqlite3_free(aOut);
188998          return rc;
188999        }
189000
189001        sqlite3_free(pTS->aaOutput[i]);
189002        sqlite3_free(aOut);
189003        pTS->aaOutput[i] = 0;
189004        aOut = aNew;
189005        nOut = nNew;
189006      }
189007    }
189008  }
189009
189010  pTS->aaOutput[0] = aOut;
189011  pTS->anOutput[0] = nOut;
189012  return SQLITE_OK;
189013}
189014
189015/*
189016** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
189017** as the first argument. The merge is an "OR" merge (see function
189018** fts3DoclistOrMerge() for details).
189019**
189020** This function is called with the doclist for each term that matches
189021** a queried prefix. It merges all these doclists into one, the doclist
189022** for the specified prefix. Since there can be a very large number of
189023** doclists to merge, the merging is done pair-wise using the TermSelect
189024** object.
189025**
189026** This function returns SQLITE_OK if the merge is successful, or an
189027** SQLite error code (SQLITE_NOMEM) if an error occurs.
189028*/
189029static int fts3TermSelectMerge(
189030  Fts3Table *p,                   /* FTS table handle */
189031  TermSelect *pTS,                /* TermSelect object to merge into */
189032  char *aDoclist,                 /* Pointer to doclist */
189033  int nDoclist                    /* Size of aDoclist in bytes */
189034){
189035  if( pTS->aaOutput[0]==0 ){
189036    /* If this is the first term selected, copy the doclist to the output
189037    ** buffer using memcpy().
189038    **
189039    ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
189040    ** allocation. This is so as to ensure that the buffer is big enough
189041    ** to hold the current doclist AND'd with any other doclist. If the
189042    ** doclists are stored in order=ASC order, this padding would not be
189043    ** required (since the size of [doclistA AND doclistB] is always less
189044    ** than or equal to the size of [doclistA] in that case). But this is
189045    ** not true for order=DESC. For example, a doclist containing (1, -1)
189046    ** may be smaller than (-1), as in the first example the -1 may be stored
189047    ** as a single-byte delta, whereas in the second it must be stored as a
189048    ** FTS3_VARINT_MAX byte varint.
189049    **
189050    ** Similar padding is added in the fts3DoclistOrMerge() function.
189051    */
189052    pTS->aaOutput[0] = sqlite3_malloc64((i64)nDoclist + FTS3_VARINT_MAX + 1);
189053    pTS->anOutput[0] = nDoclist;
189054    if( pTS->aaOutput[0] ){
189055      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
189056      memset(&pTS->aaOutput[0][nDoclist], 0, FTS3_VARINT_MAX);
189057    }else{
189058      return SQLITE_NOMEM;
189059    }
189060  }else{
189061    char *aMerge = aDoclist;
189062    int nMerge = nDoclist;
189063    int iOut;
189064
189065    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
189066      if( pTS->aaOutput[iOut]==0 ){
189067        assert( iOut>0 );
189068        pTS->aaOutput[iOut] = aMerge;
189069        pTS->anOutput[iOut] = nMerge;
189070        break;
189071      }else{
189072        char *aNew;
189073        int nNew;
189074
189075        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
189076            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
189077        );
189078        if( rc!=SQLITE_OK ){
189079          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
189080          return rc;
189081        }
189082
189083        if( aMerge!=aDoclist ) sqlite3_free(aMerge);
189084        sqlite3_free(pTS->aaOutput[iOut]);
189085        pTS->aaOutput[iOut] = 0;
189086
189087        aMerge = aNew;
189088        nMerge = nNew;
189089        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
189090          pTS->aaOutput[iOut] = aMerge;
189091          pTS->anOutput[iOut] = nMerge;
189092        }
189093      }
189094    }
189095  }
189096  return SQLITE_OK;
189097}
189098
189099/*
189100** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
189101*/
189102static int fts3SegReaderCursorAppend(
189103  Fts3MultiSegReader *pCsr,
189104  Fts3SegReader *pNew
189105){
189106  if( (pCsr->nSegment%16)==0 ){
189107    Fts3SegReader **apNew;
189108    sqlite3_int64 nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
189109    apNew = (Fts3SegReader **)sqlite3_realloc64(pCsr->apSegment, nByte);
189110    if( !apNew ){
189111      sqlite3Fts3SegReaderFree(pNew);
189112      return SQLITE_NOMEM;
189113    }
189114    pCsr->apSegment = apNew;
189115  }
189116  pCsr->apSegment[pCsr->nSegment++] = pNew;
189117  return SQLITE_OK;
189118}
189119
189120/*
189121** Add seg-reader objects to the Fts3MultiSegReader object passed as the
189122** 8th argument.
189123**
189124** This function returns SQLITE_OK if successful, or an SQLite error code
189125** otherwise.
189126*/
189127static int fts3SegReaderCursor(
189128  Fts3Table *p,                   /* FTS3 table handle */
189129  int iLangid,                    /* Language id */
189130  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
189131  int iLevel,                     /* Level of segments to scan */
189132  const char *zTerm,              /* Term to query for */
189133  int nTerm,                      /* Size of zTerm in bytes */
189134  int isPrefix,                   /* True for a prefix search */
189135  int isScan,                     /* True to scan from zTerm to EOF */
189136  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
189137){
189138  int rc = SQLITE_OK;             /* Error code */
189139  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
189140  int rc2;                        /* Result of sqlite3_reset() */
189141
189142  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
189143  ** for the pending-terms. If this is a scan, then this call must be being
189144  ** made by an fts4aux module, not an FTS table. In this case calling
189145  ** Fts3SegReaderPending might segfault, as the data structures used by
189146  ** fts4aux are not completely populated. So it's easiest to filter these
189147  ** calls out here.  */
189148  if( iLevel<0 && p->aIndex && p->iPrevLangid==iLangid ){
189149    Fts3SegReader *pSeg = 0;
189150    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
189151    if( rc==SQLITE_OK && pSeg ){
189152      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
189153    }
189154  }
189155
189156  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
189157    if( rc==SQLITE_OK ){
189158      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
189159    }
189160
189161    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
189162      Fts3SegReader *pSeg = 0;
189163
189164      /* Read the values returned by the SELECT into local variables. */
189165      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
189166      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
189167      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
189168      int nRoot = sqlite3_column_bytes(pStmt, 4);
189169      char const *zRoot = sqlite3_column_blob(pStmt, 4);
189170
189171      /* If zTerm is not NULL, and this segment is not stored entirely on its
189172      ** root node, the range of leaves scanned can be reduced. Do this. */
189173      if( iStartBlock && zTerm && zRoot ){
189174        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
189175        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
189176        if( rc!=SQLITE_OK ) goto finished;
189177        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
189178      }
189179
189180      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
189181          (isPrefix==0 && isScan==0),
189182          iStartBlock, iLeavesEndBlock,
189183          iEndBlock, zRoot, nRoot, &pSeg
189184      );
189185      if( rc!=SQLITE_OK ) goto finished;
189186      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
189187    }
189188  }
189189
189190 finished:
189191  rc2 = sqlite3_reset(pStmt);
189192  if( rc==SQLITE_DONE ) rc = rc2;
189193
189194  return rc;
189195}
189196
189197/*
189198** Set up a cursor object for iterating through a full-text index or a
189199** single level therein.
189200*/
189201SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
189202  Fts3Table *p,                   /* FTS3 table handle */
189203  int iLangid,                    /* Language-id to search */
189204  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
189205  int iLevel,                     /* Level of segments to scan */
189206  const char *zTerm,              /* Term to query for */
189207  int nTerm,                      /* Size of zTerm in bytes */
189208  int isPrefix,                   /* True for a prefix search */
189209  int isScan,                     /* True to scan from zTerm to EOF */
189210  Fts3MultiSegReader *pCsr       /* Cursor object to populate */
189211){
189212  assert( iIndex>=0 && iIndex<p->nIndex );
189213  assert( iLevel==FTS3_SEGCURSOR_ALL
189214      ||  iLevel==FTS3_SEGCURSOR_PENDING
189215      ||  iLevel>=0
189216  );
189217  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
189218  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
189219  assert( isPrefix==0 || isScan==0 );
189220
189221  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
189222  return fts3SegReaderCursor(
189223      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
189224  );
189225}
189226
189227/*
189228** In addition to its current configuration, have the Fts3MultiSegReader
189229** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
189230**
189231** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
189232*/
189233static int fts3SegReaderCursorAddZero(
189234  Fts3Table *p,                   /* FTS virtual table handle */
189235  int iLangid,
189236  const char *zTerm,              /* Term to scan doclist of */
189237  int nTerm,                      /* Number of bytes in zTerm */
189238  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
189239){
189240  return fts3SegReaderCursor(p,
189241      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
189242  );
189243}
189244
189245/*
189246** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
189247** if isPrefix is true, to scan the doclist for all terms for which
189248** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
189249** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
189250** an SQLite error code.
189251**
189252** It is the responsibility of the caller to free this object by eventually
189253** passing it to fts3SegReaderCursorFree()
189254**
189255** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
189256** Output parameter *ppSegcsr is set to 0 if an error occurs.
189257*/
189258static int fts3TermSegReaderCursor(
189259  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
189260  const char *zTerm,              /* Term to query for */
189261  int nTerm,                      /* Size of zTerm in bytes */
189262  int isPrefix,                   /* True for a prefix search */
189263  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
189264){
189265  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
189266  int rc = SQLITE_NOMEM;          /* Return code */
189267
189268  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
189269  if( pSegcsr ){
189270    int i;
189271    int bFound = 0;               /* True once an index has been found */
189272    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
189273
189274    if( isPrefix ){
189275      for(i=1; bFound==0 && i<p->nIndex; i++){
189276        if( p->aIndex[i].nPrefix==nTerm ){
189277          bFound = 1;
189278          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
189279              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
189280          );
189281          pSegcsr->bLookup = 1;
189282        }
189283      }
189284
189285      for(i=1; bFound==0 && i<p->nIndex; i++){
189286        if( p->aIndex[i].nPrefix==nTerm+1 ){
189287          bFound = 1;
189288          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
189289              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
189290          );
189291          if( rc==SQLITE_OK ){
189292            rc = fts3SegReaderCursorAddZero(
189293                p, pCsr->iLangid, zTerm, nTerm, pSegcsr
189294            );
189295          }
189296        }
189297      }
189298    }
189299
189300    if( bFound==0 ){
189301      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
189302          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
189303      );
189304      pSegcsr->bLookup = !isPrefix;
189305    }
189306  }
189307
189308  *ppSegcsr = pSegcsr;
189309  return rc;
189310}
189311
189312/*
189313** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
189314*/
189315static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
189316  sqlite3Fts3SegReaderFinish(pSegcsr);
189317  sqlite3_free(pSegcsr);
189318}
189319
189320/*
189321** This function retrieves the doclist for the specified term (or term
189322** prefix) from the database.
189323*/
189324static int fts3TermSelect(
189325  Fts3Table *p,                   /* Virtual table handle */
189326  Fts3PhraseToken *pTok,          /* Token to query for */
189327  int iColumn,                    /* Column to query (or -ve for all columns) */
189328  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
189329  char **ppOut                    /* OUT: Malloced result buffer */
189330){
189331  int rc;                         /* Return code */
189332  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
189333  TermSelect tsc;                 /* Object for pair-wise doclist merging */
189334  Fts3SegFilter filter;           /* Segment term filter configuration */
189335
189336  pSegcsr = pTok->pSegcsr;
189337  memset(&tsc, 0, sizeof(TermSelect));
189338
189339  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
189340        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
189341        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
189342        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
189343  filter.iCol = iColumn;
189344  filter.zTerm = pTok->z;
189345  filter.nTerm = pTok->n;
189346
189347  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
189348  while( SQLITE_OK==rc
189349      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
189350  ){
189351    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
189352  }
189353
189354  if( rc==SQLITE_OK ){
189355    rc = fts3TermSelectFinishMerge(p, &tsc);
189356  }
189357  if( rc==SQLITE_OK ){
189358    *ppOut = tsc.aaOutput[0];
189359    *pnOut = tsc.anOutput[0];
189360  }else{
189361    int i;
189362    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
189363      sqlite3_free(tsc.aaOutput[i]);
189364    }
189365  }
189366
189367  fts3SegReaderCursorFree(pSegcsr);
189368  pTok->pSegcsr = 0;
189369  return rc;
189370}
189371
189372/*
189373** This function counts the total number of docids in the doclist stored
189374** in buffer aList[], size nList bytes.
189375**
189376** If the isPoslist argument is true, then it is assumed that the doclist
189377** contains a position-list following each docid. Otherwise, it is assumed
189378** that the doclist is simply a list of docids stored as delta encoded
189379** varints.
189380*/
189381static int fts3DoclistCountDocids(char *aList, int nList){
189382  int nDoc = 0;                   /* Return value */
189383  if( aList ){
189384    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
189385    char *p = aList;              /* Cursor */
189386    while( p<aEnd ){
189387      nDoc++;
189388      while( (*p++)&0x80 );     /* Skip docid varint */
189389      fts3PoslistCopy(0, &p);   /* Skip over position list */
189390    }
189391  }
189392
189393  return nDoc;
189394}
189395
189396/*
189397** Advance the cursor to the next row in the %_content table that
189398** matches the search criteria.  For a MATCH search, this will be
189399** the next row that matches. For a full-table scan, this will be
189400** simply the next row in the %_content table.  For a docid lookup,
189401** this routine simply sets the EOF flag.
189402**
189403** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
189404** even if we reach end-of-file.  The fts3EofMethod() will be called
189405** subsequently to determine whether or not an EOF was hit.
189406*/
189407static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
189408  int rc;
189409  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
189410  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
189411    Fts3Table *pTab = (Fts3Table*)pCursor->pVtab;
189412    pTab->bLock++;
189413    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
189414      pCsr->isEof = 1;
189415      rc = sqlite3_reset(pCsr->pStmt);
189416    }else{
189417      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
189418      rc = SQLITE_OK;
189419    }
189420    pTab->bLock--;
189421  }else{
189422    rc = fts3EvalNext((Fts3Cursor *)pCursor);
189423  }
189424  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
189425  return rc;
189426}
189427
189428/*
189429** If the numeric type of argument pVal is "integer", then return it
189430** converted to a 64-bit signed integer. Otherwise, return a copy of
189431** the second parameter, iDefault.
189432*/
189433static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
189434  if( pVal ){
189435    int eType = sqlite3_value_numeric_type(pVal);
189436    if( eType==SQLITE_INTEGER ){
189437      return sqlite3_value_int64(pVal);
189438    }
189439  }
189440  return iDefault;
189441}
189442
189443/*
189444** This is the xFilter interface for the virtual table.  See
189445** the virtual table xFilter method documentation for additional
189446** information.
189447**
189448** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
189449** the %_content table.
189450**
189451** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
189452** in the %_content table.
189453**
189454** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
189455** column on the left-hand side of the MATCH operator is column
189456** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
189457** side of the MATCH operator.
189458*/
189459static int fts3FilterMethod(
189460  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
189461  int idxNum,                     /* Strategy index */
189462  const char *idxStr,             /* Unused */
189463  int nVal,                       /* Number of elements in apVal */
189464  sqlite3_value **apVal           /* Arguments for the indexing scheme */
189465){
189466  int rc = SQLITE_OK;
189467  char *zSql;                     /* SQL statement used to access %_content */
189468  int eSearch;
189469  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
189470  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
189471
189472  sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
189473  sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
189474  sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
189475  sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
189476  int iIdx;
189477
189478  UNUSED_PARAMETER(idxStr);
189479  UNUSED_PARAMETER(nVal);
189480
189481  if( p->bLock ){
189482    return SQLITE_ERROR;
189483  }
189484
189485  eSearch = (idxNum & 0x0000FFFF);
189486  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
189487  assert( p->pSegments==0 );
189488
189489  /* Collect arguments into local variables */
189490  iIdx = 0;
189491  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
189492  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
189493  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
189494  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
189495  assert( iIdx==nVal );
189496
189497  /* In case the cursor has been used before, clear it now. */
189498  fts3ClearCursor(pCsr);
189499
189500  /* Set the lower and upper bounds on docids to return */
189501  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
189502  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
189503
189504  if( idxStr ){
189505    pCsr->bDesc = (idxStr[0]=='D');
189506  }else{
189507    pCsr->bDesc = p->bDescIdx;
189508  }
189509  pCsr->eSearch = (i16)eSearch;
189510
189511  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
189512    int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
189513    const char *zQuery = (const char *)sqlite3_value_text(pCons);
189514
189515    if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
189516      return SQLITE_NOMEM;
189517    }
189518
189519    pCsr->iLangid = 0;
189520    if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
189521
189522    assert( p->base.zErrMsg==0 );
189523    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
189524        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
189525        &p->base.zErrMsg
189526    );
189527    if( rc!=SQLITE_OK ){
189528      return rc;
189529    }
189530
189531    rc = fts3EvalStart(pCsr);
189532    sqlite3Fts3SegmentsClose(p);
189533    if( rc!=SQLITE_OK ) return rc;
189534    pCsr->pNextId = pCsr->aDoclist;
189535    pCsr->iPrevId = 0;
189536  }
189537
189538  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
189539  ** statement loops through all rows of the %_content table. For a
189540  ** full-text query or docid lookup, the statement retrieves a single
189541  ** row by docid.
189542  */
189543  if( eSearch==FTS3_FULLSCAN_SEARCH ){
189544    if( pDocidGe || pDocidLe ){
189545      zSql = sqlite3_mprintf(
189546          "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
189547          p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
189548          (pCsr->bDesc ? "DESC" : "ASC")
189549      );
189550    }else{
189551      zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
189552          p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
189553      );
189554    }
189555    if( zSql ){
189556      p->bLock++;
189557      rc = sqlite3_prepare_v3(
189558          p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0
189559      );
189560      p->bLock--;
189561      sqlite3_free(zSql);
189562    }else{
189563      rc = SQLITE_NOMEM;
189564    }
189565  }else if( eSearch==FTS3_DOCID_SEARCH ){
189566    rc = fts3CursorSeekStmt(pCsr);
189567    if( rc==SQLITE_OK ){
189568      rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
189569    }
189570  }
189571  if( rc!=SQLITE_OK ) return rc;
189572
189573  return fts3NextMethod(pCursor);
189574}
189575
189576/*
189577** This is the xEof method of the virtual table. SQLite calls this
189578** routine to find out if it has reached the end of a result set.
189579*/
189580static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
189581  Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
189582  if( pCsr->isEof ){
189583    fts3ClearCursor(pCsr);
189584    pCsr->isEof = 1;
189585  }
189586  return pCsr->isEof;
189587}
189588
189589/*
189590** This is the xRowid method. The SQLite core calls this routine to
189591** retrieve the rowid for the current row of the result set. fts3
189592** exposes %_content.docid as the rowid for the virtual table. The
189593** rowid should be written to *pRowid.
189594*/
189595static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
189596  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
189597  *pRowid = pCsr->iPrevId;
189598  return SQLITE_OK;
189599}
189600
189601/*
189602** This is the xColumn method, called by SQLite to request a value from
189603** the row that the supplied cursor currently points to.
189604**
189605** If:
189606**
189607**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
189608**   (iCol == p->nColumn)   -> Magic column with the same name as the table.
189609**   (iCol == p->nColumn+1) -> Docid column
189610**   (iCol == p->nColumn+2) -> Langid column
189611*/
189612static int fts3ColumnMethod(
189613  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
189614  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
189615  int iCol                        /* Index of column to read value from */
189616){
189617  int rc = SQLITE_OK;             /* Return Code */
189618  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
189619  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
189620
189621  /* The column value supplied by SQLite must be in range. */
189622  assert( iCol>=0 && iCol<=p->nColumn+2 );
189623
189624  switch( iCol-p->nColumn ){
189625    case 0:
189626      /* The special 'table-name' column */
189627      sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
189628      break;
189629
189630    case 1:
189631      /* The docid column */
189632      sqlite3_result_int64(pCtx, pCsr->iPrevId);
189633      break;
189634
189635    case 2:
189636      if( pCsr->pExpr ){
189637        sqlite3_result_int64(pCtx, pCsr->iLangid);
189638        break;
189639      }else if( p->zLanguageid==0 ){
189640        sqlite3_result_int(pCtx, 0);
189641        break;
189642      }else{
189643        iCol = p->nColumn;
189644        /* no break */ deliberate_fall_through
189645      }
189646
189647    default:
189648      /* A user column. Or, if this is a full-table scan, possibly the
189649      ** language-id column. Seek the cursor. */
189650      rc = fts3CursorSeek(0, pCsr);
189651      if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
189652        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
189653      }
189654      break;
189655  }
189656
189657  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
189658  return rc;
189659}
189660
189661/*
189662** This function is the implementation of the xUpdate callback used by
189663** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
189664** inserted, updated or deleted.
189665*/
189666static int fts3UpdateMethod(
189667  sqlite3_vtab *pVtab,            /* Virtual table handle */
189668  int nArg,                       /* Size of argument array */
189669  sqlite3_value **apVal,          /* Array of arguments */
189670  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
189671){
189672  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
189673}
189674
189675/*
189676** Implementation of xSync() method. Flush the contents of the pending-terms
189677** hash-table to the database.
189678*/
189679static int fts3SyncMethod(sqlite3_vtab *pVtab){
189680
189681  /* Following an incremental-merge operation, assuming that the input
189682  ** segments are not completely consumed (the usual case), they are updated
189683  ** in place to remove the entries that have already been merged. This
189684  ** involves updating the leaf block that contains the smallest unmerged
189685  ** entry and each block (if any) between the leaf and the root node. So
189686  ** if the height of the input segment b-trees is N, and input segments
189687  ** are merged eight at a time, updating the input segments at the end
189688  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
189689  ** small - often between 0 and 2. So the overhead of the incremental
189690  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
189691  ** dwarfing the actual productive work accomplished, the incremental merge
189692  ** is only attempted if it will write at least 64 leaf blocks. Hence
189693  ** nMinMerge.
189694  **
189695  ** Of course, updating the input segments also involves deleting a bunch
189696  ** of blocks from the segments table. But this is not considered overhead
189697  ** as it would also be required by a crisis-merge that used the same input
189698  ** segments.
189699  */
189700  const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
189701
189702  Fts3Table *p = (Fts3Table*)pVtab;
189703  int rc;
189704  i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
189705
189706  rc = sqlite3Fts3PendingTermsFlush(p);
189707  if( rc==SQLITE_OK
189708   && p->nLeafAdd>(nMinMerge/16)
189709   && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
189710  ){
189711    int mxLevel = 0;              /* Maximum relative level value in db */
189712    int A;                        /* Incr-merge parameter A */
189713
189714    rc = sqlite3Fts3MaxLevel(p, &mxLevel);
189715    assert( rc==SQLITE_OK || mxLevel==0 );
189716    A = p->nLeafAdd * mxLevel;
189717    A += (A/2);
189718    if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
189719  }
189720  sqlite3Fts3SegmentsClose(p);
189721  sqlite3_set_last_insert_rowid(p->db, iLastRowid);
189722  return rc;
189723}
189724
189725/*
189726** If it is currently unknown whether or not the FTS table has an %_stat
189727** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
189728** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
189729** if an error occurs.
189730*/
189731static int fts3SetHasStat(Fts3Table *p){
189732  int rc = SQLITE_OK;
189733  if( p->bHasStat==2 ){
189734    char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
189735    if( zTbl ){
189736      int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
189737      sqlite3_free(zTbl);
189738      p->bHasStat = (res==SQLITE_OK);
189739    }else{
189740      rc = SQLITE_NOMEM;
189741    }
189742  }
189743  return rc;
189744}
189745
189746/*
189747** Implementation of xBegin() method.
189748*/
189749static int fts3BeginMethod(sqlite3_vtab *pVtab){
189750  Fts3Table *p = (Fts3Table*)pVtab;
189751  int rc;
189752  UNUSED_PARAMETER(pVtab);
189753  assert( p->pSegments==0 );
189754  assert( p->nPendingData==0 );
189755  assert( p->inTransaction!=1 );
189756  p->nLeafAdd = 0;
189757  rc = fts3SetHasStat(p);
189758#ifdef SQLITE_DEBUG
189759  if( rc==SQLITE_OK ){
189760    p->inTransaction = 1;
189761    p->mxSavepoint = -1;
189762  }
189763#endif
189764  return rc;
189765}
189766
189767/*
189768** Implementation of xCommit() method. This is a no-op. The contents of
189769** the pending-terms hash-table have already been flushed into the database
189770** by fts3SyncMethod().
189771*/
189772static int fts3CommitMethod(sqlite3_vtab *pVtab){
189773  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
189774  UNUSED_PARAMETER(pVtab);
189775  assert( p->nPendingData==0 );
189776  assert( p->inTransaction!=0 );
189777  assert( p->pSegments==0 );
189778  TESTONLY( p->inTransaction = 0 );
189779  TESTONLY( p->mxSavepoint = -1; );
189780  return SQLITE_OK;
189781}
189782
189783/*
189784** Implementation of xRollback(). Discard the contents of the pending-terms
189785** hash-table. Any changes made to the database are reverted by SQLite.
189786*/
189787static int fts3RollbackMethod(sqlite3_vtab *pVtab){
189788  Fts3Table *p = (Fts3Table*)pVtab;
189789  sqlite3Fts3PendingTermsClear(p);
189790  assert( p->inTransaction!=0 );
189791  TESTONLY( p->inTransaction = 0 );
189792  TESTONLY( p->mxSavepoint = -1; );
189793  return SQLITE_OK;
189794}
189795
189796/*
189797** When called, *ppPoslist must point to the byte immediately following the
189798** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
189799** moves *ppPoslist so that it instead points to the first byte of the
189800** same position list.
189801*/
189802static void fts3ReversePoslist(char *pStart, char **ppPoslist){
189803  char *p = &(*ppPoslist)[-2];
189804  char c = 0;
189805
189806  /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
189807  while( p>pStart && (c=*p--)==0 );
189808
189809  /* Search backwards for a varint with value zero (the end of the previous
189810  ** poslist). This is an 0x00 byte preceded by some byte that does not
189811  ** have the 0x80 bit set.  */
189812  while( p>pStart && (*p & 0x80) | c ){
189813    c = *p--;
189814  }
189815  assert( p==pStart || c==0 );
189816
189817  /* At this point p points to that preceding byte without the 0x80 bit
189818  ** set. So to find the start of the poslist, skip forward 2 bytes then
189819  ** over a varint.
189820  **
189821  ** Normally. The other case is that p==pStart and the poslist to return
189822  ** is the first in the doclist. In this case do not skip forward 2 bytes.
189823  ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
189824  ** is required for cases where the first byte of a doclist and the
189825  ** doclist is empty. For example, if the first docid is 10, a doclist
189826  ** that begins with:
189827  **
189828  **   0x0A 0x00 <next docid delta varint>
189829  */
189830  if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
189831  while( *p++&0x80 );
189832  *ppPoslist = p;
189833}
189834
189835/*
189836** Helper function used by the implementation of the overloaded snippet(),
189837** offsets() and optimize() SQL functions.
189838**
189839** If the value passed as the third argument is a blob of size
189840** sizeof(Fts3Cursor*), then the blob contents are copied to the
189841** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
189842** message is written to context pContext and SQLITE_ERROR returned. The
189843** string passed via zFunc is used as part of the error message.
189844*/
189845static int fts3FunctionArg(
189846  sqlite3_context *pContext,      /* SQL function call context */
189847  const char *zFunc,              /* Function name */
189848  sqlite3_value *pVal,            /* argv[0] passed to function */
189849  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
189850){
189851  int rc;
189852  *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
189853  if( (*ppCsr)!=0 ){
189854    rc = SQLITE_OK;
189855  }else{
189856    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
189857    sqlite3_result_error(pContext, zErr, -1);
189858    sqlite3_free(zErr);
189859    rc = SQLITE_ERROR;
189860  }
189861  return rc;
189862}
189863
189864/*
189865** Implementation of the snippet() function for FTS3
189866*/
189867static void fts3SnippetFunc(
189868  sqlite3_context *pContext,      /* SQLite function call context */
189869  int nVal,                       /* Size of apVal[] array */
189870  sqlite3_value **apVal           /* Array of arguments */
189871){
189872  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
189873  const char *zStart = "<b>";
189874  const char *zEnd = "</b>";
189875  const char *zEllipsis = "<b>...</b>";
189876  int iCol = -1;
189877  int nToken = 15;                /* Default number of tokens in snippet */
189878
189879  /* There must be at least one argument passed to this function (otherwise
189880  ** the non-overloaded version would have been called instead of this one).
189881  */
189882  assert( nVal>=1 );
189883
189884  if( nVal>6 ){
189885    sqlite3_result_error(pContext,
189886        "wrong number of arguments to function snippet()", -1);
189887    return;
189888  }
189889  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
189890
189891  switch( nVal ){
189892    case 6: nToken = sqlite3_value_int(apVal[5]);
189893            /* no break */ deliberate_fall_through
189894    case 5: iCol = sqlite3_value_int(apVal[4]);
189895            /* no break */ deliberate_fall_through
189896    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
189897            /* no break */ deliberate_fall_through
189898    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
189899            /* no break */ deliberate_fall_through
189900    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
189901  }
189902  if( !zEllipsis || !zEnd || !zStart ){
189903    sqlite3_result_error_nomem(pContext);
189904  }else if( nToken==0 ){
189905    sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
189906  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
189907    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
189908  }
189909}
189910
189911/*
189912** Implementation of the offsets() function for FTS3
189913*/
189914static void fts3OffsetsFunc(
189915  sqlite3_context *pContext,      /* SQLite function call context */
189916  int nVal,                       /* Size of argument array */
189917  sqlite3_value **apVal           /* Array of arguments */
189918){
189919  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
189920
189921  UNUSED_PARAMETER(nVal);
189922
189923  assert( nVal==1 );
189924  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
189925  assert( pCsr );
189926  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
189927    sqlite3Fts3Offsets(pContext, pCsr);
189928  }
189929}
189930
189931/*
189932** Implementation of the special optimize() function for FTS3. This
189933** function merges all segments in the database to a single segment.
189934** Example usage is:
189935**
189936**   SELECT optimize(t) FROM t LIMIT 1;
189937**
189938** where 't' is the name of an FTS3 table.
189939*/
189940static void fts3OptimizeFunc(
189941  sqlite3_context *pContext,      /* SQLite function call context */
189942  int nVal,                       /* Size of argument array */
189943  sqlite3_value **apVal           /* Array of arguments */
189944){
189945  int rc;                         /* Return code */
189946  Fts3Table *p;                   /* Virtual table handle */
189947  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
189948
189949  UNUSED_PARAMETER(nVal);
189950
189951  assert( nVal==1 );
189952  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
189953  p = (Fts3Table *)pCursor->base.pVtab;
189954  assert( p );
189955
189956  rc = sqlite3Fts3Optimize(p);
189957
189958  switch( rc ){
189959    case SQLITE_OK:
189960      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
189961      break;
189962    case SQLITE_DONE:
189963      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
189964      break;
189965    default:
189966      sqlite3_result_error_code(pContext, rc);
189967      break;
189968  }
189969}
189970
189971/*
189972** Implementation of the matchinfo() function for FTS3
189973*/
189974static void fts3MatchinfoFunc(
189975  sqlite3_context *pContext,      /* SQLite function call context */
189976  int nVal,                       /* Size of argument array */
189977  sqlite3_value **apVal           /* Array of arguments */
189978){
189979  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
189980  assert( nVal==1 || nVal==2 );
189981  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
189982    const char *zArg = 0;
189983    if( nVal>1 ){
189984      zArg = (const char *)sqlite3_value_text(apVal[1]);
189985    }
189986    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
189987  }
189988}
189989
189990/*
189991** This routine implements the xFindFunction method for the FTS3
189992** virtual table.
189993*/
189994static int fts3FindFunctionMethod(
189995  sqlite3_vtab *pVtab,            /* Virtual table handle */
189996  int nArg,                       /* Number of SQL function arguments */
189997  const char *zName,              /* Name of SQL function */
189998  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
189999  void **ppArg                    /* Unused */
190000){
190001  struct Overloaded {
190002    const char *zName;
190003    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
190004  } aOverload[] = {
190005    { "snippet", fts3SnippetFunc },
190006    { "offsets", fts3OffsetsFunc },
190007    { "optimize", fts3OptimizeFunc },
190008    { "matchinfo", fts3MatchinfoFunc },
190009  };
190010  int i;                          /* Iterator variable */
190011
190012  UNUSED_PARAMETER(pVtab);
190013  UNUSED_PARAMETER(nArg);
190014  UNUSED_PARAMETER(ppArg);
190015
190016  for(i=0; i<SizeofArray(aOverload); i++){
190017    if( strcmp(zName, aOverload[i].zName)==0 ){
190018      *pxFunc = aOverload[i].xFunc;
190019      return 1;
190020    }
190021  }
190022
190023  /* No function of the specified name was found. Return 0. */
190024  return 0;
190025}
190026
190027/*
190028** Implementation of FTS3 xRename method. Rename an fts3 table.
190029*/
190030static int fts3RenameMethod(
190031  sqlite3_vtab *pVtab,            /* Virtual table handle */
190032  const char *zName               /* New name of table */
190033){
190034  Fts3Table *p = (Fts3Table *)pVtab;
190035  sqlite3 *db = p->db;            /* Database connection */
190036  int rc;                         /* Return Code */
190037
190038  /* At this point it must be known if the %_stat table exists or not.
190039  ** So bHasStat may not be 2.  */
190040  rc = fts3SetHasStat(p);
190041
190042  /* As it happens, the pending terms table is always empty here. This is
190043  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
190044  ** always opens a savepoint transaction. And the xSavepoint() method
190045  ** flushes the pending terms table. But leave the (no-op) call to
190046  ** PendingTermsFlush() in in case that changes.
190047  */
190048  assert( p->nPendingData==0 );
190049  if( rc==SQLITE_OK ){
190050    rc = sqlite3Fts3PendingTermsFlush(p);
190051  }
190052
190053  p->bIgnoreSavepoint = 1;
190054
190055  if( p->zContentTbl==0 ){
190056    fts3DbExec(&rc, db,
190057      "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
190058      p->zDb, p->zName, zName
190059    );
190060  }
190061
190062  if( p->bHasDocsize ){
190063    fts3DbExec(&rc, db,
190064      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
190065      p->zDb, p->zName, zName
190066    );
190067  }
190068  if( p->bHasStat ){
190069    fts3DbExec(&rc, db,
190070      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
190071      p->zDb, p->zName, zName
190072    );
190073  }
190074  fts3DbExec(&rc, db,
190075    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
190076    p->zDb, p->zName, zName
190077  );
190078  fts3DbExec(&rc, db,
190079    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
190080    p->zDb, p->zName, zName
190081  );
190082
190083  p->bIgnoreSavepoint = 0;
190084  return rc;
190085}
190086
190087/*
190088** The xSavepoint() method.
190089**
190090** Flush the contents of the pending-terms table to disk.
190091*/
190092static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
190093  int rc = SQLITE_OK;
190094  Fts3Table *pTab = (Fts3Table*)pVtab;
190095  assert( pTab->inTransaction );
190096  assert( pTab->mxSavepoint<=iSavepoint );
190097  TESTONLY( pTab->mxSavepoint = iSavepoint );
190098
190099  if( pTab->bIgnoreSavepoint==0 ){
190100    if( fts3HashCount(&pTab->aIndex[0].hPending)>0 ){
190101      char *zSql = sqlite3_mprintf("INSERT INTO %Q.%Q(%Q) VALUES('flush')",
190102          pTab->zDb, pTab->zName, pTab->zName
190103          );
190104      if( zSql ){
190105        pTab->bIgnoreSavepoint = 1;
190106        rc = sqlite3_exec(pTab->db, zSql, 0, 0, 0);
190107        pTab->bIgnoreSavepoint = 0;
190108        sqlite3_free(zSql);
190109      }else{
190110        rc = SQLITE_NOMEM;
190111      }
190112    }
190113    if( rc==SQLITE_OK ){
190114      pTab->iSavepoint = iSavepoint+1;
190115    }
190116  }
190117  return rc;
190118}
190119
190120/*
190121** The xRelease() method.
190122**
190123** This is a no-op.
190124*/
190125static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
190126  Fts3Table *pTab = (Fts3Table*)pVtab;
190127  assert( pTab->inTransaction );
190128  assert( pTab->mxSavepoint >= iSavepoint );
190129  TESTONLY( pTab->mxSavepoint = iSavepoint-1 );
190130  pTab->iSavepoint = iSavepoint;
190131  return SQLITE_OK;
190132}
190133
190134/*
190135** The xRollbackTo() method.
190136**
190137** Discard the contents of the pending terms table.
190138*/
190139static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
190140  Fts3Table *pTab = (Fts3Table*)pVtab;
190141  UNUSED_PARAMETER(iSavepoint);
190142  assert( pTab->inTransaction );
190143  TESTONLY( pTab->mxSavepoint = iSavepoint );
190144  if( (iSavepoint+1)<=pTab->iSavepoint ){
190145    sqlite3Fts3PendingTermsClear(pTab);
190146  }
190147  return SQLITE_OK;
190148}
190149
190150/*
190151** Return true if zName is the extension on one of the shadow tables used
190152** by this module.
190153*/
190154static int fts3ShadowName(const char *zName){
190155  static const char *azName[] = {
190156    "content", "docsize", "segdir", "segments", "stat",
190157  };
190158  unsigned int i;
190159  for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
190160    if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
190161  }
190162  return 0;
190163}
190164
190165/*
190166** Implementation of the xIntegrity() method on the FTS3/FTS4 virtual
190167** table.
190168*/
190169static int fts3IntegrityMethod(
190170  sqlite3_vtab *pVtab,      /* The virtual table to be checked */
190171  const char *zSchema,      /* Name of schema in which pVtab lives */
190172  const char *zTabname,     /* Name of the pVTab table */
190173  int isQuick,              /* True if this is a quick_check */
190174  char **pzErr              /* Write error message here */
190175){
190176  Fts3Table *p = (Fts3Table*)pVtab;
190177  int rc = SQLITE_OK;
190178  int bOk = 0;
190179
190180  UNUSED_PARAMETER(isQuick);
190181  rc = sqlite3Fts3IntegrityCheck(p, &bOk);
190182  assert( rc!=SQLITE_CORRUPT_VTAB );
190183  if( rc==SQLITE_ERROR || (rc&0xFF)==SQLITE_CORRUPT ){
190184    *pzErr = sqlite3_mprintf("unable to validate the inverted index for"
190185                             " FTS%d table %s.%s: %s",
190186                p->bFts4 ? 4 : 3, zSchema, zTabname, sqlite3_errstr(rc));
190187    if( *pzErr ) rc = SQLITE_OK;
190188  }else if( rc==SQLITE_OK && bOk==0 ){
190189    *pzErr = sqlite3_mprintf("malformed inverted index for FTS%d table %s.%s",
190190                p->bFts4 ? 4 : 3, zSchema, zTabname);
190191    if( *pzErr==0 ) rc = SQLITE_NOMEM;
190192  }
190193  sqlite3Fts3SegmentsClose(p);
190194  return rc;
190195}
190196
190197
190198
190199static const sqlite3_module fts3Module = {
190200  /* iVersion      */ 4,
190201  /* xCreate       */ fts3CreateMethod,
190202  /* xConnect      */ fts3ConnectMethod,
190203  /* xBestIndex    */ fts3BestIndexMethod,
190204  /* xDisconnect   */ fts3DisconnectMethod,
190205  /* xDestroy      */ fts3DestroyMethod,
190206  /* xOpen         */ fts3OpenMethod,
190207  /* xClose        */ fts3CloseMethod,
190208  /* xFilter       */ fts3FilterMethod,
190209  /* xNext         */ fts3NextMethod,
190210  /* xEof          */ fts3EofMethod,
190211  /* xColumn       */ fts3ColumnMethod,
190212  /* xRowid        */ fts3RowidMethod,
190213  /* xUpdate       */ fts3UpdateMethod,
190214  /* xBegin        */ fts3BeginMethod,
190215  /* xSync         */ fts3SyncMethod,
190216  /* xCommit       */ fts3CommitMethod,
190217  /* xRollback     */ fts3RollbackMethod,
190218  /* xFindFunction */ fts3FindFunctionMethod,
190219  /* xRename */       fts3RenameMethod,
190220  /* xSavepoint    */ fts3SavepointMethod,
190221  /* xRelease      */ fts3ReleaseMethod,
190222  /* xRollbackTo   */ fts3RollbackToMethod,
190223  /* xShadowName   */ fts3ShadowName,
190224  /* xIntegrity    */ fts3IntegrityMethod,
190225};
190226
190227/*
190228** This function is registered as the module destructor (called when an
190229** FTS3 enabled database connection is closed). It frees the memory
190230** allocated for the tokenizer hash table.
190231*/
190232static void hashDestroy(void *p){
190233  Fts3HashWrapper *pHash = (Fts3HashWrapper *)p;
190234  pHash->nRef--;
190235  if( pHash->nRef<=0 ){
190236    sqlite3Fts3HashClear(&pHash->hash);
190237    sqlite3_free(pHash);
190238  }
190239}
190240
190241/*
190242** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
190243** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
190244** respectively. The following three forward declarations are for functions
190245** declared in these files used to retrieve the respective implementations.
190246**
190247** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
190248** to by the argument to point to the "simple" tokenizer implementation.
190249** And so on.
190250*/
190251SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
190252SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
190253#ifndef SQLITE_DISABLE_FTS3_UNICODE
190254SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
190255#endif
190256#ifdef SQLITE_ENABLE_ICU
190257SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
190258#endif
190259
190260/*
190261** Initialize the fts3 extension. If this extension is built as part
190262** of the sqlite library, then this function is called directly by
190263** SQLite. If fts3 is built as a dynamically loadable extension, this
190264** function is called by the sqlite3_extension_init() entry point.
190265*/
190266SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
190267  int rc = SQLITE_OK;
190268  Fts3HashWrapper *pHash = 0;
190269  const sqlite3_tokenizer_module *pSimple = 0;
190270  const sqlite3_tokenizer_module *pPorter = 0;
190271#ifndef SQLITE_DISABLE_FTS3_UNICODE
190272  const sqlite3_tokenizer_module *pUnicode = 0;
190273#endif
190274
190275#ifdef SQLITE_ENABLE_ICU
190276  const sqlite3_tokenizer_module *pIcu = 0;
190277  sqlite3Fts3IcuTokenizerModule(&pIcu);
190278#endif
190279
190280#ifndef SQLITE_DISABLE_FTS3_UNICODE
190281  sqlite3Fts3UnicodeTokenizer(&pUnicode);
190282#endif
190283
190284#ifdef SQLITE_TEST
190285  rc = sqlite3Fts3InitTerm(db);
190286  if( rc!=SQLITE_OK ) return rc;
190287#endif
190288
190289  rc = sqlite3Fts3InitAux(db);
190290  if( rc!=SQLITE_OK ) return rc;
190291
190292  sqlite3Fts3SimpleTokenizerModule(&pSimple);
190293  sqlite3Fts3PorterTokenizerModule(&pPorter);
190294
190295  /* Allocate and initialize the hash-table used to store tokenizers. */
190296  pHash = sqlite3_malloc(sizeof(Fts3HashWrapper));
190297  if( !pHash ){
190298    rc = SQLITE_NOMEM;
190299  }else{
190300    sqlite3Fts3HashInit(&pHash->hash, FTS3_HASH_STRING, 1);
190301    pHash->nRef = 0;
190302  }
190303
190304  /* Load the built-in tokenizers into the hash table */
190305  if( rc==SQLITE_OK ){
190306    if( sqlite3Fts3HashInsert(&pHash->hash, "simple", 7, (void *)pSimple)
190307     || sqlite3Fts3HashInsert(&pHash->hash, "porter", 7, (void *)pPorter)
190308
190309#ifndef SQLITE_DISABLE_FTS3_UNICODE
190310     || sqlite3Fts3HashInsert(&pHash->hash, "unicode61", 10, (void *)pUnicode)
190311#endif
190312#ifdef SQLITE_ENABLE_ICU
190313     || (pIcu && sqlite3Fts3HashInsert(&pHash->hash, "icu", 4, (void *)pIcu))
190314#endif
190315    ){
190316      rc = SQLITE_NOMEM;
190317    }
190318  }
190319
190320#ifdef SQLITE_TEST
190321  if( rc==SQLITE_OK ){
190322    rc = sqlite3Fts3ExprInitTestInterface(db, &pHash->hash);
190323  }
190324#endif
190325
190326  /* Create the virtual table wrapper around the hash-table and overload
190327  ** the four scalar functions. If this is successful, register the
190328  ** module with sqlite.
190329  */
190330  if( SQLITE_OK==rc
190331   && SQLITE_OK==(rc=sqlite3Fts3InitHashTable(db,&pHash->hash,"fts3_tokenizer"))
190332   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
190333   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
190334   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
190335   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
190336   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
190337  ){
190338    pHash->nRef++;
190339    rc = sqlite3_create_module_v2(
190340        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
190341    );
190342    if( rc==SQLITE_OK ){
190343      pHash->nRef++;
190344      rc = sqlite3_create_module_v2(
190345          db, "fts4", &fts3Module, (void *)pHash, hashDestroy
190346      );
190347    }
190348    if( rc==SQLITE_OK ){
190349      pHash->nRef++;
190350      rc = sqlite3Fts3InitTok(db, (void *)pHash, hashDestroy);
190351    }
190352    return rc;
190353  }
190354
190355
190356  /* An error has occurred. Delete the hash table and return the error code. */
190357  assert( rc!=SQLITE_OK );
190358  if( pHash ){
190359    sqlite3Fts3HashClear(&pHash->hash);
190360    sqlite3_free(pHash);
190361  }
190362  return rc;
190363}
190364
190365/*
190366** Allocate an Fts3MultiSegReader for each token in the expression headed
190367** by pExpr.
190368**
190369** An Fts3SegReader object is a cursor that can seek or scan a range of
190370** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
190371** Fts3SegReader objects internally to provide an interface to seek or scan
190372** within the union of all segments of a b-tree. Hence the name.
190373**
190374** If the allocated Fts3MultiSegReader just seeks to a single entry in a
190375** segment b-tree (if the term is not a prefix or it is a prefix for which
190376** there exists prefix b-tree of the right length) then it may be traversed
190377** and merged incrementally. Otherwise, it has to be merged into an in-memory
190378** doclist and then traversed.
190379*/
190380static void fts3EvalAllocateReaders(
190381  Fts3Cursor *pCsr,               /* FTS cursor handle */
190382  Fts3Expr *pExpr,                /* Allocate readers for this expression */
190383  int *pnToken,                   /* OUT: Total number of tokens in phrase. */
190384  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
190385  int *pRc                        /* IN/OUT: Error code */
190386){
190387  if( pExpr && SQLITE_OK==*pRc ){
190388    if( pExpr->eType==FTSQUERY_PHRASE ){
190389      int i;
190390      int nToken = pExpr->pPhrase->nToken;
190391      *pnToken += nToken;
190392      for(i=0; i<nToken; i++){
190393        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
190394        int rc = fts3TermSegReaderCursor(pCsr,
190395            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
190396        );
190397        if( rc!=SQLITE_OK ){
190398          *pRc = rc;
190399          return;
190400        }
190401      }
190402      assert( pExpr->pPhrase->iDoclistToken==0 );
190403      pExpr->pPhrase->iDoclistToken = -1;
190404    }else{
190405      *pnOr += (pExpr->eType==FTSQUERY_OR);
190406      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
190407      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
190408    }
190409  }
190410}
190411
190412/*
190413** Arguments pList/nList contain the doclist for token iToken of phrase p.
190414** It is merged into the main doclist stored in p->doclist.aAll/nAll.
190415**
190416** This function assumes that pList points to a buffer allocated using
190417** sqlite3_malloc(). This function takes responsibility for eventually
190418** freeing the buffer.
190419**
190420** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
190421*/
190422static int fts3EvalPhraseMergeToken(
190423  Fts3Table *pTab,                /* FTS Table pointer */
190424  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
190425  int iToken,                     /* Token pList/nList corresponds to */
190426  char *pList,                    /* Pointer to doclist */
190427  int nList                       /* Number of bytes in pList */
190428){
190429  int rc = SQLITE_OK;
190430  assert( iToken!=p->iDoclistToken );
190431
190432  if( pList==0 ){
190433    sqlite3_free(p->doclist.aAll);
190434    p->doclist.aAll = 0;
190435    p->doclist.nAll = 0;
190436  }
190437
190438  else if( p->iDoclistToken<0 ){
190439    p->doclist.aAll = pList;
190440    p->doclist.nAll = nList;
190441  }
190442
190443  else if( p->doclist.aAll==0 ){
190444    sqlite3_free(pList);
190445  }
190446
190447  else {
190448    char *pLeft;
190449    char *pRight;
190450    int nLeft;
190451    int nRight;
190452    int nDiff;
190453
190454    if( p->iDoclistToken<iToken ){
190455      pLeft = p->doclist.aAll;
190456      nLeft = p->doclist.nAll;
190457      pRight = pList;
190458      nRight = nList;
190459      nDiff = iToken - p->iDoclistToken;
190460    }else{
190461      pRight = p->doclist.aAll;
190462      nRight = p->doclist.nAll;
190463      pLeft = pList;
190464      nLeft = nList;
190465      nDiff = p->iDoclistToken - iToken;
190466    }
190467
190468    rc = fts3DoclistPhraseMerge(
190469        pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
190470    );
190471    sqlite3_free(pLeft);
190472    p->doclist.aAll = pRight;
190473    p->doclist.nAll = nRight;
190474  }
190475
190476  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
190477  return rc;
190478}
190479
190480/*
190481** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
190482** does not take deferred tokens into account.
190483**
190484** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
190485*/
190486static int fts3EvalPhraseLoad(
190487  Fts3Cursor *pCsr,               /* FTS Cursor handle */
190488  Fts3Phrase *p                   /* Phrase object */
190489){
190490  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
190491  int iToken;
190492  int rc = SQLITE_OK;
190493
190494  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
190495    Fts3PhraseToken *pToken = &p->aToken[iToken];
190496    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
190497
190498    if( pToken->pSegcsr ){
190499      int nThis = 0;
190500      char *pThis = 0;
190501      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
190502      if( rc==SQLITE_OK ){
190503        rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
190504      }
190505    }
190506    assert( pToken->pSegcsr==0 );
190507  }
190508
190509  return rc;
190510}
190511
190512#ifndef SQLITE_DISABLE_FTS4_DEFERRED
190513/*
190514** This function is called on each phrase after the position lists for
190515** any deferred tokens have been loaded into memory. It updates the phrases
190516** current position list to include only those positions that are really
190517** instances of the phrase (after considering deferred tokens). If this
190518** means that the phrase does not appear in the current row, doclist.pList
190519** and doclist.nList are both zeroed.
190520**
190521** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
190522*/
190523static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
190524  int iToken;                     /* Used to iterate through phrase tokens */
190525  char *aPoslist = 0;             /* Position list for deferred tokens */
190526  int nPoslist = 0;               /* Number of bytes in aPoslist */
190527  int iPrev = -1;                 /* Token number of previous deferred token */
190528  char *aFree = (pPhrase->doclist.bFreeList ? pPhrase->doclist.pList : 0);
190529
190530  for(iToken=0; iToken<pPhrase->nToken; iToken++){
190531    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
190532    Fts3DeferredToken *pDeferred = pToken->pDeferred;
190533
190534    if( pDeferred ){
190535      char *pList;
190536      int nList;
190537      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
190538      if( rc!=SQLITE_OK ) return rc;
190539
190540      if( pList==0 ){
190541        sqlite3_free(aPoslist);
190542        sqlite3_free(aFree);
190543        pPhrase->doclist.pList = 0;
190544        pPhrase->doclist.nList = 0;
190545        return SQLITE_OK;
190546
190547      }else if( aPoslist==0 ){
190548        aPoslist = pList;
190549        nPoslist = nList;
190550
190551      }else{
190552        char *aOut = pList;
190553        char *p1 = aPoslist;
190554        char *p2 = aOut;
190555
190556        assert( iPrev>=0 );
190557        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
190558        sqlite3_free(aPoslist);
190559        aPoslist = pList;
190560        nPoslist = (int)(aOut - aPoslist);
190561        if( nPoslist==0 ){
190562          sqlite3_free(aPoslist);
190563          sqlite3_free(aFree);
190564          pPhrase->doclist.pList = 0;
190565          pPhrase->doclist.nList = 0;
190566          return SQLITE_OK;
190567        }
190568      }
190569      iPrev = iToken;
190570    }
190571  }
190572
190573  if( iPrev>=0 ){
190574    int nMaxUndeferred = pPhrase->iDoclistToken;
190575    if( nMaxUndeferred<0 ){
190576      pPhrase->doclist.pList = aPoslist;
190577      pPhrase->doclist.nList = nPoslist;
190578      pPhrase->doclist.iDocid = pCsr->iPrevId;
190579      pPhrase->doclist.bFreeList = 1;
190580    }else{
190581      int nDistance;
190582      char *p1;
190583      char *p2;
190584      char *aOut;
190585
190586      if( nMaxUndeferred>iPrev ){
190587        p1 = aPoslist;
190588        p2 = pPhrase->doclist.pList;
190589        nDistance = nMaxUndeferred - iPrev;
190590      }else{
190591        p1 = pPhrase->doclist.pList;
190592        p2 = aPoslist;
190593        nDistance = iPrev - nMaxUndeferred;
190594      }
190595
190596      aOut = (char *)sqlite3Fts3MallocZero(nPoslist+FTS3_BUFFER_PADDING);
190597      if( !aOut ){
190598        sqlite3_free(aPoslist);
190599        return SQLITE_NOMEM;
190600      }
190601
190602      pPhrase->doclist.pList = aOut;
190603      assert( p1 && p2 );
190604      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
190605        pPhrase->doclist.bFreeList = 1;
190606        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
190607      }else{
190608        sqlite3_free(aOut);
190609        pPhrase->doclist.pList = 0;
190610        pPhrase->doclist.nList = 0;
190611      }
190612      sqlite3_free(aPoslist);
190613    }
190614  }
190615
190616  if( pPhrase->doclist.pList!=aFree ) sqlite3_free(aFree);
190617  return SQLITE_OK;
190618}
190619#endif /* SQLITE_DISABLE_FTS4_DEFERRED */
190620
190621/*
190622** Maximum number of tokens a phrase may have to be considered for the
190623** incremental doclists strategy.
190624*/
190625#define MAX_INCR_PHRASE_TOKENS 4
190626
190627/*
190628** This function is called for each Fts3Phrase in a full-text query
190629** expression to initialize the mechanism for returning rows. Once this
190630** function has been called successfully on an Fts3Phrase, it may be
190631** used with fts3EvalPhraseNext() to iterate through the matching docids.
190632**
190633** If parameter bOptOk is true, then the phrase may (or may not) use the
190634** incremental loading strategy. Otherwise, the entire doclist is loaded into
190635** memory within this call.
190636**
190637** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
190638*/
190639static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
190640  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
190641  int rc = SQLITE_OK;             /* Error code */
190642  int i;
190643
190644  /* Determine if doclists may be loaded from disk incrementally. This is
190645  ** possible if the bOptOk argument is true, the FTS doclists will be
190646  ** scanned in forward order, and the phrase consists of
190647  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
190648  ** tokens or prefix tokens that cannot use a prefix-index.  */
190649  int bHaveIncr = 0;
190650  int bIncrOk = (bOptOk
190651   && pCsr->bDesc==pTab->bDescIdx
190652   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
190653#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
190654   && pTab->bNoIncrDoclist==0
190655#endif
190656  );
190657  for(i=0; bIncrOk==1 && i<p->nToken; i++){
190658    Fts3PhraseToken *pToken = &p->aToken[i];
190659    if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
190660      bIncrOk = 0;
190661    }
190662    if( pToken->pSegcsr ) bHaveIncr = 1;
190663  }
190664
190665  if( bIncrOk && bHaveIncr ){
190666    /* Use the incremental approach. */
190667    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
190668    for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
190669      Fts3PhraseToken *pToken = &p->aToken[i];
190670      Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
190671      if( pSegcsr ){
190672        rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
190673      }
190674    }
190675    p->bIncr = 1;
190676  }else{
190677    /* Load the full doclist for the phrase into memory. */
190678    rc = fts3EvalPhraseLoad(pCsr, p);
190679    p->bIncr = 0;
190680  }
190681
190682  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
190683  return rc;
190684}
190685
190686/*
190687** This function is used to iterate backwards (from the end to start)
190688** through doclists. It is used by this module to iterate through phrase
190689** doclists in reverse and by the fts3_write.c module to iterate through
190690** pending-terms lists when writing to databases with "order=desc".
190691**
190692** The doclist may be sorted in ascending (parameter bDescIdx==0) or
190693** descending (parameter bDescIdx==1) order of docid. Regardless, this
190694** function iterates from the end of the doclist to the beginning.
190695*/
190696SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
190697  int bDescIdx,                   /* True if the doclist is desc */
190698  char *aDoclist,                 /* Pointer to entire doclist */
190699  int nDoclist,                   /* Length of aDoclist in bytes */
190700  char **ppIter,                  /* IN/OUT: Iterator pointer */
190701  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
190702  int *pnList,                    /* OUT: List length pointer */
190703  u8 *pbEof                       /* OUT: End-of-file flag */
190704){
190705  char *p = *ppIter;
190706
190707  assert( nDoclist>0 );
190708  assert( *pbEof==0 );
190709  assert_fts3_nc( p || *piDocid==0 );
190710  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
190711
190712  if( p==0 ){
190713    sqlite3_int64 iDocid = 0;
190714    char *pNext = 0;
190715    char *pDocid = aDoclist;
190716    char *pEnd = &aDoclist[nDoclist];
190717    int iMul = 1;
190718
190719    while( pDocid<pEnd ){
190720      sqlite3_int64 iDelta;
190721      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
190722      iDocid += (iMul * iDelta);
190723      pNext = pDocid;
190724      fts3PoslistCopy(0, &pDocid);
190725      while( pDocid<pEnd && *pDocid==0 ) pDocid++;
190726      iMul = (bDescIdx ? -1 : 1);
190727    }
190728
190729    *pnList = (int)(pEnd - pNext);
190730    *ppIter = pNext;
190731    *piDocid = iDocid;
190732  }else{
190733    int iMul = (bDescIdx ? -1 : 1);
190734    sqlite3_int64 iDelta;
190735    fts3GetReverseVarint(&p, aDoclist, &iDelta);
190736    *piDocid -= (iMul * iDelta);
190737
190738    if( p==aDoclist ){
190739      *pbEof = 1;
190740    }else{
190741      char *pSave = p;
190742      fts3ReversePoslist(aDoclist, &p);
190743      *pnList = (int)(pSave - p);
190744    }
190745    *ppIter = p;
190746  }
190747}
190748
190749/*
190750** Iterate forwards through a doclist.
190751*/
190752SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
190753  int bDescIdx,                   /* True if the doclist is desc */
190754  char *aDoclist,                 /* Pointer to entire doclist */
190755  int nDoclist,                   /* Length of aDoclist in bytes */
190756  char **ppIter,                  /* IN/OUT: Iterator pointer */
190757  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
190758  u8 *pbEof                       /* OUT: End-of-file flag */
190759){
190760  char *p = *ppIter;
190761
190762  assert( nDoclist>0 );
190763  assert( *pbEof==0 );
190764  assert_fts3_nc( p || *piDocid==0 );
190765  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
190766
190767  if( p==0 ){
190768    p = aDoclist;
190769    p += sqlite3Fts3GetVarint(p, piDocid);
190770  }else{
190771    fts3PoslistCopy(0, &p);
190772    while( p<&aDoclist[nDoclist] && *p==0 ) p++;
190773    if( p>=&aDoclist[nDoclist] ){
190774      *pbEof = 1;
190775    }else{
190776      sqlite3_int64 iVar;
190777      p += sqlite3Fts3GetVarint(p, &iVar);
190778      *piDocid += ((bDescIdx ? -1 : 1) * iVar);
190779    }
190780  }
190781
190782  *ppIter = p;
190783}
190784
190785/*
190786** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
190787** to true if EOF is reached.
190788*/
190789static void fts3EvalDlPhraseNext(
190790  Fts3Table *pTab,
190791  Fts3Doclist *pDL,
190792  u8 *pbEof
190793){
190794  char *pIter;                            /* Used to iterate through aAll */
190795  char *pEnd;                             /* 1 byte past end of aAll */
190796
190797  if( pDL->pNextDocid ){
190798    pIter = pDL->pNextDocid;
190799    assert( pDL->aAll!=0 || pIter==0 );
190800  }else{
190801    pIter = pDL->aAll;
190802  }
190803
190804  if( pIter==0 || pIter>=(pEnd = pDL->aAll + pDL->nAll) ){
190805    /* We have already reached the end of this doclist. EOF. */
190806    *pbEof = 1;
190807  }else{
190808    sqlite3_int64 iDelta;
190809    pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
190810    if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
190811      pDL->iDocid += iDelta;
190812    }else{
190813      pDL->iDocid -= iDelta;
190814    }
190815    pDL->pList = pIter;
190816    fts3PoslistCopy(0, &pIter);
190817    pDL->nList = (int)(pIter - pDL->pList);
190818
190819    /* pIter now points just past the 0x00 that terminates the position-
190820    ** list for document pDL->iDocid. However, if this position-list was
190821    ** edited in place by fts3EvalNearTrim(), then pIter may not actually
190822    ** point to the start of the next docid value. The following line deals
190823    ** with this case by advancing pIter past the zero-padding added by
190824    ** fts3EvalNearTrim().  */
190825    while( pIter<pEnd && *pIter==0 ) pIter++;
190826
190827    pDL->pNextDocid = pIter;
190828    assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
190829    *pbEof = 0;
190830  }
190831}
190832
190833/*
190834** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
190835*/
190836typedef struct TokenDoclist TokenDoclist;
190837struct TokenDoclist {
190838  int bIgnore;
190839  sqlite3_int64 iDocid;
190840  char *pList;
190841  int nList;
190842};
190843
190844/*
190845** Token pToken is an incrementally loaded token that is part of a
190846** multi-token phrase. Advance it to the next matching document in the
190847** database and populate output variable *p with the details of the new
190848** entry. Or, if the iterator has reached EOF, set *pbEof to true.
190849**
190850** If an error occurs, return an SQLite error code. Otherwise, return
190851** SQLITE_OK.
190852*/
190853static int incrPhraseTokenNext(
190854  Fts3Table *pTab,                /* Virtual table handle */
190855  Fts3Phrase *pPhrase,            /* Phrase to advance token of */
190856  int iToken,                     /* Specific token to advance */
190857  TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
190858  u8 *pbEof                       /* OUT: True if iterator is at EOF */
190859){
190860  int rc = SQLITE_OK;
190861
190862  if( pPhrase->iDoclistToken==iToken ){
190863    assert( p->bIgnore==0 );
190864    assert( pPhrase->aToken[iToken].pSegcsr==0 );
190865    fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
190866    p->pList = pPhrase->doclist.pList;
190867    p->nList = pPhrase->doclist.nList;
190868    p->iDocid = pPhrase->doclist.iDocid;
190869  }else{
190870    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
190871    assert( pToken->pDeferred==0 );
190872    assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
190873    if( pToken->pSegcsr ){
190874      assert( p->bIgnore==0 );
190875      rc = sqlite3Fts3MsrIncrNext(
190876          pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
190877      );
190878      if( p->pList==0 ) *pbEof = 1;
190879    }else{
190880      p->bIgnore = 1;
190881    }
190882  }
190883
190884  return rc;
190885}
190886
190887
190888/*
190889** The phrase iterator passed as the second argument:
190890**
190891**   * features at least one token that uses an incremental doclist, and
190892**
190893**   * does not contain any deferred tokens.
190894**
190895** Advance it to the next matching documnent in the database and populate
190896** the Fts3Doclist.pList and nList fields.
190897**
190898** If there is no "next" entry and no error occurs, then *pbEof is set to
190899** 1 before returning. Otherwise, if no error occurs and the iterator is
190900** successfully advanced, *pbEof is set to 0.
190901**
190902** If an error occurs, return an SQLite error code. Otherwise, return
190903** SQLITE_OK.
190904*/
190905static int fts3EvalIncrPhraseNext(
190906  Fts3Cursor *pCsr,               /* FTS Cursor handle */
190907  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
190908  u8 *pbEof                       /* OUT: Set to 1 if EOF */
190909){
190910  int rc = SQLITE_OK;
190911  Fts3Doclist *pDL = &p->doclist;
190912  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
190913  u8 bEof = 0;
190914
190915  /* This is only called if it is guaranteed that the phrase has at least
190916  ** one incremental token. In which case the bIncr flag is set. */
190917  assert( p->bIncr==1 );
190918
190919  if( p->nToken==1 ){
190920    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
190921        &pDL->iDocid, &pDL->pList, &pDL->nList
190922    );
190923    if( pDL->pList==0 ) bEof = 1;
190924  }else{
190925    int bDescDoclist = pCsr->bDesc;
190926    struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
190927
190928    memset(a, 0, sizeof(a));
190929    assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
190930    assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
190931
190932    while( bEof==0 ){
190933      int bMaxSet = 0;
190934      sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
190935      int i;                      /* Used to iterate through tokens */
190936
190937      /* Advance the iterator for each token in the phrase once. */
190938      for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
190939        rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
190940        if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
190941          iMax = a[i].iDocid;
190942          bMaxSet = 1;
190943        }
190944      }
190945      assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
190946      assert( rc!=SQLITE_OK || bMaxSet );
190947
190948      /* Keep advancing iterators until they all point to the same document */
190949      for(i=0; i<p->nToken; i++){
190950        while( rc==SQLITE_OK && bEof==0
190951            && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
190952        ){
190953          rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
190954          if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
190955            iMax = a[i].iDocid;
190956            i = 0;
190957          }
190958        }
190959      }
190960
190961      /* Check if the current entries really are a phrase match */
190962      if( bEof==0 ){
190963        int nList = 0;
190964        int nByte = a[p->nToken-1].nList;
190965        char *aDoclist = sqlite3_malloc64((i64)nByte+FTS3_BUFFER_PADDING);
190966        if( !aDoclist ) return SQLITE_NOMEM;
190967        memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
190968        memset(&aDoclist[nByte], 0, FTS3_BUFFER_PADDING);
190969
190970        for(i=0; i<(p->nToken-1); i++){
190971          if( a[i].bIgnore==0 ){
190972            char *pL = a[i].pList;
190973            char *pR = aDoclist;
190974            char *pOut = aDoclist;
190975            int nDist = p->nToken-1-i;
190976            int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
190977            if( res==0 ) break;
190978            nList = (int)(pOut - aDoclist);
190979          }
190980        }
190981        if( i==(p->nToken-1) ){
190982          pDL->iDocid = iMax;
190983          pDL->pList = aDoclist;
190984          pDL->nList = nList;
190985          pDL->bFreeList = 1;
190986          break;
190987        }
190988        sqlite3_free(aDoclist);
190989      }
190990    }
190991  }
190992
190993  *pbEof = bEof;
190994  return rc;
190995}
190996
190997/*
190998** Attempt to move the phrase iterator to point to the next matching docid.
190999** If an error occurs, return an SQLite error code. Otherwise, return
191000** SQLITE_OK.
191001**
191002** If there is no "next" entry and no error occurs, then *pbEof is set to
191003** 1 before returning. Otherwise, if no error occurs and the iterator is
191004** successfully advanced, *pbEof is set to 0.
191005*/
191006static int fts3EvalPhraseNext(
191007  Fts3Cursor *pCsr,               /* FTS Cursor handle */
191008  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
191009  u8 *pbEof                       /* OUT: Set to 1 if EOF */
191010){
191011  int rc = SQLITE_OK;
191012  Fts3Doclist *pDL = &p->doclist;
191013  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
191014
191015  if( p->bIncr ){
191016    rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
191017  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
191018    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
191019        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
191020    );
191021    pDL->pList = pDL->pNextDocid;
191022  }else{
191023    fts3EvalDlPhraseNext(pTab, pDL, pbEof);
191024  }
191025
191026  return rc;
191027}
191028
191029/*
191030**
191031** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
191032** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
191033** expression. Also the Fts3Expr.bDeferred variable is set to true for any
191034** expressions for which all descendent tokens are deferred.
191035**
191036** If parameter bOptOk is zero, then it is guaranteed that the
191037** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
191038** each phrase in the expression (subject to deferred token processing).
191039** Or, if bOptOk is non-zero, then one or more tokens within the expression
191040** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
191041**
191042** If an error occurs within this function, *pRc is set to an SQLite error
191043** code before returning.
191044*/
191045static void fts3EvalStartReaders(
191046  Fts3Cursor *pCsr,               /* FTS Cursor handle */
191047  Fts3Expr *pExpr,                /* Expression to initialize phrases in */
191048  int *pRc                        /* IN/OUT: Error code */
191049){
191050  if( pExpr && SQLITE_OK==*pRc ){
191051    if( pExpr->eType==FTSQUERY_PHRASE ){
191052      int nToken = pExpr->pPhrase->nToken;
191053      if( nToken ){
191054        int i;
191055        for(i=0; i<nToken; i++){
191056          if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
191057        }
191058        pExpr->bDeferred = (i==nToken);
191059      }
191060      *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
191061    }else{
191062      fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
191063      fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
191064      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
191065    }
191066  }
191067}
191068
191069/*
191070** An array of the following structures is assembled as part of the process
191071** of selecting tokens to defer before the query starts executing (as part
191072** of the xFilter() method). There is one element in the array for each
191073** token in the FTS expression.
191074**
191075** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
191076** to phrases that are connected only by AND and NEAR operators (not OR or
191077** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
191078** separately. The root of a tokens AND/NEAR cluster is stored in
191079** Fts3TokenAndCost.pRoot.
191080*/
191081typedef struct Fts3TokenAndCost Fts3TokenAndCost;
191082struct Fts3TokenAndCost {
191083  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
191084  int iToken;                     /* Position of token in phrase */
191085  Fts3PhraseToken *pToken;        /* The token itself */
191086  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
191087  int nOvfl;                      /* Number of overflow pages to load doclist */
191088  int iCol;                       /* The column the token must match */
191089};
191090
191091/*
191092** This function is used to populate an allocated Fts3TokenAndCost array.
191093**
191094** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
191095** Otherwise, if an error occurs during execution, *pRc is set to an
191096** SQLite error code.
191097*/
191098static void fts3EvalTokenCosts(
191099  Fts3Cursor *pCsr,               /* FTS Cursor handle */
191100  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
191101  Fts3Expr *pExpr,                /* Expression to consider */
191102  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
191103  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
191104  int *pRc                        /* IN/OUT: Error code */
191105){
191106  if( *pRc==SQLITE_OK ){
191107    if( pExpr->eType==FTSQUERY_PHRASE ){
191108      Fts3Phrase *pPhrase = pExpr->pPhrase;
191109      int i;
191110      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
191111        Fts3TokenAndCost *pTC = (*ppTC)++;
191112        pTC->pPhrase = pPhrase;
191113        pTC->iToken = i;
191114        pTC->pRoot = pRoot;
191115        pTC->pToken = &pPhrase->aToken[i];
191116        pTC->iCol = pPhrase->iColumn;
191117        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
191118      }
191119    }else if( pExpr->eType!=FTSQUERY_NOT ){
191120      assert( pExpr->eType==FTSQUERY_OR
191121           || pExpr->eType==FTSQUERY_AND
191122           || pExpr->eType==FTSQUERY_NEAR
191123      );
191124      assert( pExpr->pLeft && pExpr->pRight );
191125      if( pExpr->eType==FTSQUERY_OR ){
191126        pRoot = pExpr->pLeft;
191127        **ppOr = pRoot;
191128        (*ppOr)++;
191129      }
191130      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
191131      if( pExpr->eType==FTSQUERY_OR ){
191132        pRoot = pExpr->pRight;
191133        **ppOr = pRoot;
191134        (*ppOr)++;
191135      }
191136      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
191137    }
191138  }
191139}
191140
191141/*
191142** Determine the average document (row) size in pages. If successful,
191143** write this value to *pnPage and return SQLITE_OK. Otherwise, return
191144** an SQLite error code.
191145**
191146** The average document size in pages is calculated by first calculating
191147** determining the average size in bytes, B. If B is less than the amount
191148** of data that will fit on a single leaf page of an intkey table in
191149** this database, then the average docsize is 1. Otherwise, it is 1 plus
191150** the number of overflow pages consumed by a record B bytes in size.
191151*/
191152static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
191153  int rc = SQLITE_OK;
191154  if( pCsr->nRowAvg==0 ){
191155    /* The average document size, which is required to calculate the cost
191156    ** of each doclist, has not yet been determined. Read the required
191157    ** data from the %_stat table to calculate it.
191158    **
191159    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
191160    ** varints, where nCol is the number of columns in the FTS3 table.
191161    ** The first varint is the number of documents currently stored in
191162    ** the table. The following nCol varints contain the total amount of
191163    ** data stored in all rows of each column of the table, from left
191164    ** to right.
191165    */
191166    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
191167    sqlite3_stmt *pStmt;
191168    sqlite3_int64 nDoc = 0;
191169    sqlite3_int64 nByte = 0;
191170    const char *pEnd;
191171    const char *a;
191172
191173    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
191174    if( rc!=SQLITE_OK ) return rc;
191175    a = sqlite3_column_blob(pStmt, 0);
191176    testcase( a==0 );  /* If %_stat.value set to X'' */
191177    if( a ){
191178      pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
191179      a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc);
191180      while( a<pEnd ){
191181        a += sqlite3Fts3GetVarintBounded(a, pEnd, &nByte);
191182      }
191183    }
191184    if( nDoc==0 || nByte==0 ){
191185      sqlite3_reset(pStmt);
191186      return FTS_CORRUPT_VTAB;
191187    }
191188
191189    pCsr->nDoc = nDoc;
191190    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
191191    assert( pCsr->nRowAvg>0 );
191192    rc = sqlite3_reset(pStmt);
191193  }
191194
191195  *pnPage = pCsr->nRowAvg;
191196  return rc;
191197}
191198
191199/*
191200** This function is called to select the tokens (if any) that will be
191201** deferred. The array aTC[] has already been populated when this is
191202** called.
191203**
191204** This function is called once for each AND/NEAR cluster in the
191205** expression. Each invocation determines which tokens to defer within
191206** the cluster with root node pRoot. See comments above the definition
191207** of struct Fts3TokenAndCost for more details.
191208**
191209** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
191210** called on each token to defer. Otherwise, an SQLite error code is
191211** returned.
191212*/
191213static int fts3EvalSelectDeferred(
191214  Fts3Cursor *pCsr,               /* FTS Cursor handle */
191215  Fts3Expr *pRoot,                /* Consider tokens with this root node */
191216  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
191217  int nTC                         /* Number of entries in aTC[] */
191218){
191219  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
191220  int nDocSize = 0;               /* Number of pages per doc loaded */
191221  int rc = SQLITE_OK;             /* Return code */
191222  int ii;                         /* Iterator variable for various purposes */
191223  int nOvfl = 0;                  /* Total overflow pages used by doclists */
191224  int nToken = 0;                 /* Total number of tokens in cluster */
191225
191226  int nMinEst = 0;                /* The minimum count for any phrase so far. */
191227  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
191228
191229  /* Tokens are never deferred for FTS tables created using the content=xxx
191230  ** option. The reason being that it is not guaranteed that the content
191231  ** table actually contains the same data as the index. To prevent this from
191232  ** causing any problems, the deferred token optimization is completely
191233  ** disabled for content=xxx tables. */
191234  if( pTab->zContentTbl ){
191235    return SQLITE_OK;
191236  }
191237
191238  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
191239  ** associated with the tokens spill onto overflow pages, or if there is
191240  ** only 1 token, exit early. No tokens to defer in this case. */
191241  for(ii=0; ii<nTC; ii++){
191242    if( aTC[ii].pRoot==pRoot ){
191243      nOvfl += aTC[ii].nOvfl;
191244      nToken++;
191245    }
191246  }
191247  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
191248
191249  /* Obtain the average docsize (in pages). */
191250  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
191251  assert( rc!=SQLITE_OK || nDocSize>0 );
191252
191253
191254  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
191255  ** of the number of overflow pages that will be loaded by the pager layer
191256  ** to retrieve the entire doclist for the token from the full-text index.
191257  ** Load the doclists for tokens that are either:
191258  **
191259  **   a. The cheapest token in the entire query (i.e. the one visited by the
191260  **      first iteration of this loop), or
191261  **
191262  **   b. Part of a multi-token phrase.
191263  **
191264  ** After each token doclist is loaded, merge it with the others from the
191265  ** same phrase and count the number of documents that the merged doclist
191266  ** contains. Set variable "nMinEst" to the smallest number of documents in
191267  ** any phrase doclist for which 1 or more token doclists have been loaded.
191268  ** Let nOther be the number of other phrases for which it is certain that
191269  ** one or more tokens will not be deferred.
191270  **
191271  ** Then, for each token, defer it if loading the doclist would result in
191272  ** loading N or more overflow pages into memory, where N is computed as:
191273  **
191274  **    (nMinEst + 4^nOther - 1) / (4^nOther)
191275  */
191276  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
191277    int iTC;                      /* Used to iterate through aTC[] array. */
191278    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
191279
191280    /* Set pTC to point to the cheapest remaining token. */
191281    for(iTC=0; iTC<nTC; iTC++){
191282      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
191283       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
191284      ){
191285        pTC = &aTC[iTC];
191286      }
191287    }
191288    assert( pTC );
191289
191290    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
191291      /* The number of overflow pages to load for this (and therefore all
191292      ** subsequent) tokens is greater than the estimated number of pages
191293      ** that will be loaded if all subsequent tokens are deferred.
191294      */
191295      Fts3PhraseToken *pToken = pTC->pToken;
191296      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
191297      fts3SegReaderCursorFree(pToken->pSegcsr);
191298      pToken->pSegcsr = 0;
191299    }else{
191300      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
191301      ** for-loop. Except, limit the value to 2^24 to prevent it from
191302      ** overflowing the 32-bit integer it is stored in. */
191303      if( ii<12 ) nLoad4 = nLoad4*4;
191304
191305      if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
191306        /* Either this is the cheapest token in the entire query, or it is
191307        ** part of a multi-token phrase. Either way, the entire doclist will
191308        ** (eventually) be loaded into memory. It may as well be now. */
191309        Fts3PhraseToken *pToken = pTC->pToken;
191310        int nList = 0;
191311        char *pList = 0;
191312        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
191313        assert( rc==SQLITE_OK || pList==0 );
191314        if( rc==SQLITE_OK ){
191315          rc = fts3EvalPhraseMergeToken(
191316              pTab, pTC->pPhrase, pTC->iToken,pList,nList
191317          );
191318        }
191319        if( rc==SQLITE_OK ){
191320          int nCount;
191321          nCount = fts3DoclistCountDocids(
191322              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
191323          );
191324          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
191325        }
191326      }
191327    }
191328    pTC->pToken = 0;
191329  }
191330
191331  return rc;
191332}
191333
191334/*
191335** This function is called from within the xFilter method. It initializes
191336** the full-text query currently stored in pCsr->pExpr. To iterate through
191337** the results of a query, the caller does:
191338**
191339**    fts3EvalStart(pCsr);
191340**    while( 1 ){
191341**      fts3EvalNext(pCsr);
191342**      if( pCsr->bEof ) break;
191343**      ... return row pCsr->iPrevId to the caller ...
191344**    }
191345*/
191346static int fts3EvalStart(Fts3Cursor *pCsr){
191347  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
191348  int rc = SQLITE_OK;
191349  int nToken = 0;
191350  int nOr = 0;
191351
191352  /* Allocate a MultiSegReader for each token in the expression. */
191353  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
191354
191355  /* Determine which, if any, tokens in the expression should be deferred. */
191356#ifndef SQLITE_DISABLE_FTS4_DEFERRED
191357  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
191358    Fts3TokenAndCost *aTC;
191359    aTC = (Fts3TokenAndCost *)sqlite3_malloc64(
191360        sizeof(Fts3TokenAndCost) * nToken
191361      + sizeof(Fts3Expr *) * nOr * 2
191362    );
191363
191364    if( !aTC ){
191365      rc = SQLITE_NOMEM;
191366    }else{
191367      Fts3Expr **apOr = (Fts3Expr **)&aTC[nToken];
191368      int ii;
191369      Fts3TokenAndCost *pTC = aTC;
191370      Fts3Expr **ppOr = apOr;
191371
191372      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
191373      nToken = (int)(pTC-aTC);
191374      nOr = (int)(ppOr-apOr);
191375
191376      if( rc==SQLITE_OK ){
191377        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
191378        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
191379          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
191380        }
191381      }
191382
191383      sqlite3_free(aTC);
191384    }
191385  }
191386#endif
191387
191388  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
191389  return rc;
191390}
191391
191392/*
191393** Invalidate the current position list for phrase pPhrase.
191394*/
191395static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
191396  if( pPhrase->doclist.bFreeList ){
191397    sqlite3_free(pPhrase->doclist.pList);
191398  }
191399  pPhrase->doclist.pList = 0;
191400  pPhrase->doclist.nList = 0;
191401  pPhrase->doclist.bFreeList = 0;
191402}
191403
191404/*
191405** This function is called to edit the position list associated with
191406** the phrase object passed as the fifth argument according to a NEAR
191407** condition. For example:
191408**
191409**     abc NEAR/5 "def ghi"
191410**
191411** Parameter nNear is passed the NEAR distance of the expression (5 in
191412** the example above). When this function is called, *paPoslist points to
191413** the position list, and *pnToken is the number of phrase tokens in the
191414** phrase on the other side of the NEAR operator to pPhrase. For example,
191415** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
191416** the position list associated with phrase "abc".
191417**
191418** All positions in the pPhrase position list that are not sufficiently
191419** close to a position in the *paPoslist position list are removed. If this
191420** leaves 0 positions, zero is returned. Otherwise, non-zero.
191421**
191422** Before returning, *paPoslist is set to point to the position lsit
191423** associated with pPhrase. And *pnToken is set to the number of tokens in
191424** pPhrase.
191425*/
191426static int fts3EvalNearTrim(
191427  int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
191428  char *aTmp,                     /* Temporary space to use */
191429  char **paPoslist,               /* IN/OUT: Position list */
191430  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
191431  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
191432){
191433  int nParam1 = nNear + pPhrase->nToken;
191434  int nParam2 = nNear + *pnToken;
191435  int nNew;
191436  char *p2;
191437  char *pOut;
191438  int res;
191439
191440  assert( pPhrase->doclist.pList );
191441
191442  p2 = pOut = pPhrase->doclist.pList;
191443  res = fts3PoslistNearMerge(
191444    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
191445  );
191446  if( res ){
191447    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
191448    assert_fts3_nc( nNew<=pPhrase->doclist.nList && nNew>0 );
191449    if( nNew>=0 && nNew<=pPhrase->doclist.nList ){
191450      assert( pPhrase->doclist.pList[nNew]=='\0' );
191451      memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
191452      pPhrase->doclist.nList = nNew;
191453    }
191454    *paPoslist = pPhrase->doclist.pList;
191455    *pnToken = pPhrase->nToken;
191456  }
191457
191458  return res;
191459}
191460
191461/*
191462** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
191463** Otherwise, it advances the expression passed as the second argument to
191464** point to the next matching row in the database. Expressions iterate through
191465** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
191466** or descending if it is non-zero.
191467**
191468** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
191469** successful, the following variables in pExpr are set:
191470**
191471**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
191472**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
191473**
191474** If the expression is of type FTSQUERY_PHRASE, and the expression is not
191475** at EOF, then the following variables are populated with the position list
191476** for the phrase for the visited row:
191477**
191478**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
191479**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
191480**
191481** It says above that this function advances the expression to the next
191482** matching row. This is usually true, but there are the following exceptions:
191483**
191484**   1. Deferred tokens are not taken into account. If a phrase consists
191485**      entirely of deferred tokens, it is assumed to match every row in
191486**      the db. In this case the position-list is not populated at all.
191487**
191488**      Or, if a phrase contains one or more deferred tokens and one or
191489**      more non-deferred tokens, then the expression is advanced to the
191490**      next possible match, considering only non-deferred tokens. In other
191491**      words, if the phrase is "A B C", and "B" is deferred, the expression
191492**      is advanced to the next row that contains an instance of "A * C",
191493**      where "*" may match any single token. The position list in this case
191494**      is populated as for "A * C" before returning.
191495**
191496**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
191497**      advanced to point to the next row that matches "x AND y".
191498**
191499** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
191500** really a match, taking into account deferred tokens and NEAR operators.
191501*/
191502static void fts3EvalNextRow(
191503  Fts3Cursor *pCsr,               /* FTS Cursor handle */
191504  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
191505  int *pRc                        /* IN/OUT: Error code */
191506){
191507  if( *pRc==SQLITE_OK && pExpr->bEof==0 ){
191508    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
191509    pExpr->bStart = 1;
191510
191511    switch( pExpr->eType ){
191512      case FTSQUERY_NEAR:
191513      case FTSQUERY_AND: {
191514        Fts3Expr *pLeft = pExpr->pLeft;
191515        Fts3Expr *pRight = pExpr->pRight;
191516        assert( !pLeft->bDeferred || !pRight->bDeferred );
191517
191518        if( pLeft->bDeferred ){
191519          /* LHS is entirely deferred. So we assume it matches every row.
191520          ** Advance the RHS iterator to find the next row visited. */
191521          fts3EvalNextRow(pCsr, pRight, pRc);
191522          pExpr->iDocid = pRight->iDocid;
191523          pExpr->bEof = pRight->bEof;
191524        }else if( pRight->bDeferred ){
191525          /* RHS is entirely deferred. So we assume it matches every row.
191526          ** Advance the LHS iterator to find the next row visited. */
191527          fts3EvalNextRow(pCsr, pLeft, pRc);
191528          pExpr->iDocid = pLeft->iDocid;
191529          pExpr->bEof = pLeft->bEof;
191530        }else{
191531          /* Neither the RHS or LHS are deferred. */
191532          fts3EvalNextRow(pCsr, pLeft, pRc);
191533          fts3EvalNextRow(pCsr, pRight, pRc);
191534          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
191535            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
191536            if( iDiff==0 ) break;
191537            if( iDiff<0 ){
191538              fts3EvalNextRow(pCsr, pLeft, pRc);
191539            }else{
191540              fts3EvalNextRow(pCsr, pRight, pRc);
191541            }
191542          }
191543          pExpr->iDocid = pLeft->iDocid;
191544          pExpr->bEof = (pLeft->bEof || pRight->bEof);
191545          if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
191546            assert( pRight->eType==FTSQUERY_PHRASE );
191547            if( pRight->pPhrase->doclist.aAll ){
191548              Fts3Doclist *pDl = &pRight->pPhrase->doclist;
191549              while( *pRc==SQLITE_OK && pRight->bEof==0 ){
191550                memset(pDl->pList, 0, pDl->nList);
191551                fts3EvalNextRow(pCsr, pRight, pRc);
191552              }
191553            }
191554            if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
191555              Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
191556              while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
191557                memset(pDl->pList, 0, pDl->nList);
191558                fts3EvalNextRow(pCsr, pLeft, pRc);
191559              }
191560            }
191561            pRight->bEof = pLeft->bEof = 1;
191562          }
191563        }
191564        break;
191565      }
191566
191567      case FTSQUERY_OR: {
191568        Fts3Expr *pLeft = pExpr->pLeft;
191569        Fts3Expr *pRight = pExpr->pRight;
191570        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
191571
191572        assert_fts3_nc( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
191573        assert_fts3_nc( pRight->bStart || pLeft->iDocid==pRight->iDocid );
191574
191575        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
191576          fts3EvalNextRow(pCsr, pLeft, pRc);
191577        }else if( pLeft->bEof || iCmp>0 ){
191578          fts3EvalNextRow(pCsr, pRight, pRc);
191579        }else{
191580          fts3EvalNextRow(pCsr, pLeft, pRc);
191581          fts3EvalNextRow(pCsr, pRight, pRc);
191582        }
191583
191584        pExpr->bEof = (pLeft->bEof && pRight->bEof);
191585        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
191586        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
191587          pExpr->iDocid = pLeft->iDocid;
191588        }else{
191589          pExpr->iDocid = pRight->iDocid;
191590        }
191591
191592        break;
191593      }
191594
191595      case FTSQUERY_NOT: {
191596        Fts3Expr *pLeft = pExpr->pLeft;
191597        Fts3Expr *pRight = pExpr->pRight;
191598
191599        if( pRight->bStart==0 ){
191600          fts3EvalNextRow(pCsr, pRight, pRc);
191601          assert( *pRc!=SQLITE_OK || pRight->bStart );
191602        }
191603
191604        fts3EvalNextRow(pCsr, pLeft, pRc);
191605        if( pLeft->bEof==0 ){
191606          while( !*pRc
191607              && !pRight->bEof
191608              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
191609          ){
191610            fts3EvalNextRow(pCsr, pRight, pRc);
191611          }
191612        }
191613        pExpr->iDocid = pLeft->iDocid;
191614        pExpr->bEof = pLeft->bEof;
191615        break;
191616      }
191617
191618      default: {
191619        Fts3Phrase *pPhrase = pExpr->pPhrase;
191620        fts3EvalInvalidatePoslist(pPhrase);
191621        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
191622        pExpr->iDocid = pPhrase->doclist.iDocid;
191623        break;
191624      }
191625    }
191626  }
191627}
191628
191629/*
191630** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
191631** cluster, then this function returns 1 immediately.
191632**
191633** Otherwise, it checks if the current row really does match the NEAR
191634** expression, using the data currently stored in the position lists
191635** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
191636**
191637** If the current row is a match, the position list associated with each
191638** phrase in the NEAR expression is edited in place to contain only those
191639** phrase instances sufficiently close to their peers to satisfy all NEAR
191640** constraints. In this case it returns 1. If the NEAR expression does not
191641** match the current row, 0 is returned. The position lists may or may not
191642** be edited if 0 is returned.
191643*/
191644static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
191645  int res = 1;
191646
191647  /* The following block runs if pExpr is the root of a NEAR query.
191648  ** For example, the query:
191649  **
191650  **         "w" NEAR "x" NEAR "y" NEAR "z"
191651  **
191652  ** which is represented in tree form as:
191653  **
191654  **                               |
191655  **                          +--NEAR--+      <-- root of NEAR query
191656  **                          |        |
191657  **                     +--NEAR--+   "z"
191658  **                     |        |
191659  **                +--NEAR--+   "y"
191660  **                |        |
191661  **               "w"      "x"
191662  **
191663  ** The right-hand child of a NEAR node is always a phrase. The
191664  ** left-hand child may be either a phrase or a NEAR node. There are
191665  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
191666  */
191667  if( *pRc==SQLITE_OK
191668   && pExpr->eType==FTSQUERY_NEAR
191669   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
191670  ){
191671    Fts3Expr *p;
191672    sqlite3_int64 nTmp = 0;       /* Bytes of temp space */
191673    char *aTmp;                   /* Temp space for PoslistNearMerge() */
191674
191675    /* Allocate temporary working space. */
191676    for(p=pExpr; p->pLeft; p=p->pLeft){
191677      assert( p->pRight->pPhrase->doclist.nList>0 );
191678      nTmp += p->pRight->pPhrase->doclist.nList;
191679    }
191680    nTmp += p->pPhrase->doclist.nList;
191681    aTmp = sqlite3_malloc64(nTmp*2);
191682    if( !aTmp ){
191683      *pRc = SQLITE_NOMEM;
191684      res = 0;
191685    }else{
191686      char *aPoslist = p->pPhrase->doclist.pList;
191687      int nToken = p->pPhrase->nToken;
191688
191689      for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
191690        Fts3Phrase *pPhrase = p->pRight->pPhrase;
191691        int nNear = p->nNear;
191692        res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
191693      }
191694
191695      aPoslist = pExpr->pRight->pPhrase->doclist.pList;
191696      nToken = pExpr->pRight->pPhrase->nToken;
191697      for(p=pExpr->pLeft; p && res; p=p->pLeft){
191698        int nNear;
191699        Fts3Phrase *pPhrase;
191700        assert( p->pParent && p->pParent->pLeft==p );
191701        nNear = p->pParent->nNear;
191702        pPhrase = (
191703            p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
191704        );
191705        res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
191706      }
191707    }
191708
191709    sqlite3_free(aTmp);
191710  }
191711
191712  return res;
191713}
191714
191715/*
191716** This function is a helper function for sqlite3Fts3EvalTestDeferred().
191717** Assuming no error occurs or has occurred, It returns non-zero if the
191718** expression passed as the second argument matches the row that pCsr
191719** currently points to, or zero if it does not.
191720**
191721** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
191722** If an error occurs during execution of this function, *pRc is set to
191723** the appropriate SQLite error code. In this case the returned value is
191724** undefined.
191725*/
191726static int fts3EvalTestExpr(
191727  Fts3Cursor *pCsr,               /* FTS cursor handle */
191728  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
191729  int *pRc                        /* IN/OUT: Error code */
191730){
191731  int bHit = 1;                   /* Return value */
191732  if( *pRc==SQLITE_OK ){
191733    switch( pExpr->eType ){
191734      case FTSQUERY_NEAR:
191735      case FTSQUERY_AND:
191736        bHit = (
191737            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
191738         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
191739         && fts3EvalNearTest(pExpr, pRc)
191740        );
191741
191742        /* If the NEAR expression does not match any rows, zero the doclist for
191743        ** all phrases involved in the NEAR. This is because the snippet(),
191744        ** offsets() and matchinfo() functions are not supposed to recognize
191745        ** any instances of phrases that are part of unmatched NEAR queries.
191746        ** For example if this expression:
191747        **
191748        **    ... MATCH 'a OR (b NEAR c)'
191749        **
191750        ** is matched against a row containing:
191751        **
191752        **        'a b d e'
191753        **
191754        ** then any snippet() should ony highlight the "a" term, not the "b"
191755        ** (as "b" is part of a non-matching NEAR clause).
191756        */
191757        if( bHit==0
191758         && pExpr->eType==FTSQUERY_NEAR
191759         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
191760        ){
191761          Fts3Expr *p;
191762          for(p=pExpr; p->pPhrase==0; p=p->pLeft){
191763            if( p->pRight->iDocid==pCsr->iPrevId ){
191764              fts3EvalInvalidatePoslist(p->pRight->pPhrase);
191765            }
191766          }
191767          if( p->iDocid==pCsr->iPrevId ){
191768            fts3EvalInvalidatePoslist(p->pPhrase);
191769          }
191770        }
191771
191772        break;
191773
191774      case FTSQUERY_OR: {
191775        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
191776        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
191777        bHit = bHit1 || bHit2;
191778        break;
191779      }
191780
191781      case FTSQUERY_NOT:
191782        bHit = (
191783            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
191784         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
191785        );
191786        break;
191787
191788      default: {
191789#ifndef SQLITE_DISABLE_FTS4_DEFERRED
191790        if( pCsr->pDeferred && (pExpr->bDeferred || (
191791            pExpr->iDocid==pCsr->iPrevId && pExpr->pPhrase->doclist.pList
191792        ))){
191793          Fts3Phrase *pPhrase = pExpr->pPhrase;
191794          if( pExpr->bDeferred ){
191795            fts3EvalInvalidatePoslist(pPhrase);
191796          }
191797          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
191798          bHit = (pPhrase->doclist.pList!=0);
191799          pExpr->iDocid = pCsr->iPrevId;
191800        }else
191801#endif
191802        {
191803          bHit = (
191804              pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId
191805           && pExpr->pPhrase->doclist.nList>0
191806          );
191807        }
191808        break;
191809      }
191810    }
191811  }
191812  return bHit;
191813}
191814
191815/*
191816** This function is called as the second part of each xNext operation when
191817** iterating through the results of a full-text query. At this point the
191818** cursor points to a row that matches the query expression, with the
191819** following caveats:
191820**
191821**   * Up until this point, "NEAR" operators in the expression have been
191822**     treated as "AND".
191823**
191824**   * Deferred tokens have not yet been considered.
191825**
191826** If *pRc is not SQLITE_OK when this function is called, it immediately
191827** returns 0. Otherwise, it tests whether or not after considering NEAR
191828** operators and deferred tokens the current row is still a match for the
191829** expression. It returns 1 if both of the following are true:
191830**
191831**   1. *pRc is SQLITE_OK when this function returns, and
191832**
191833**   2. After scanning the current FTS table row for the deferred tokens,
191834**      it is determined that the row does *not* match the query.
191835**
191836** Or, if no error occurs and it seems the current row does match the FTS
191837** query, return 0.
191838*/
191839SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
191840  int rc = *pRc;
191841  int bMiss = 0;
191842  if( rc==SQLITE_OK ){
191843
191844    /* If there are one or more deferred tokens, load the current row into
191845    ** memory and scan it to determine the position list for each deferred
191846    ** token. Then, see if this row is really a match, considering deferred
191847    ** tokens and NEAR operators (neither of which were taken into account
191848    ** earlier, by fts3EvalNextRow()).
191849    */
191850    if( pCsr->pDeferred ){
191851      rc = fts3CursorSeek(0, pCsr);
191852      if( rc==SQLITE_OK ){
191853        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
191854      }
191855    }
191856    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
191857
191858    /* Free the position-lists accumulated for each deferred token above. */
191859    sqlite3Fts3FreeDeferredDoclists(pCsr);
191860    *pRc = rc;
191861  }
191862  return (rc==SQLITE_OK && bMiss);
191863}
191864
191865/*
191866** Advance to the next document that matches the FTS expression in
191867** Fts3Cursor.pExpr.
191868*/
191869static int fts3EvalNext(Fts3Cursor *pCsr){
191870  int rc = SQLITE_OK;             /* Return Code */
191871  Fts3Expr *pExpr = pCsr->pExpr;
191872  assert( pCsr->isEof==0 );
191873  if( pExpr==0 ){
191874    pCsr->isEof = 1;
191875  }else{
191876    do {
191877      if( pCsr->isRequireSeek==0 ){
191878        sqlite3_reset(pCsr->pStmt);
191879      }
191880      assert( sqlite3_data_count(pCsr->pStmt)==0 );
191881      fts3EvalNextRow(pCsr, pExpr, &rc);
191882      pCsr->isEof = pExpr->bEof;
191883      pCsr->isRequireSeek = 1;
191884      pCsr->isMatchinfoNeeded = 1;
191885      pCsr->iPrevId = pExpr->iDocid;
191886    }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
191887  }
191888
191889  /* Check if the cursor is past the end of the docid range specified
191890  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
191891  if( rc==SQLITE_OK && (
191892        (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
191893     || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
191894  )){
191895    pCsr->isEof = 1;
191896  }
191897
191898  return rc;
191899}
191900
191901/*
191902** Restart interation for expression pExpr so that the next call to
191903** fts3EvalNext() visits the first row. Do not allow incremental
191904** loading or merging of phrase doclists for this iteration.
191905**
191906** If *pRc is other than SQLITE_OK when this function is called, it is
191907** a no-op. If an error occurs within this function, *pRc is set to an
191908** SQLite error code before returning.
191909*/
191910static void fts3EvalRestart(
191911  Fts3Cursor *pCsr,
191912  Fts3Expr *pExpr,
191913  int *pRc
191914){
191915  if( pExpr && *pRc==SQLITE_OK ){
191916    Fts3Phrase *pPhrase = pExpr->pPhrase;
191917
191918    if( pPhrase ){
191919      fts3EvalInvalidatePoslist(pPhrase);
191920      if( pPhrase->bIncr ){
191921        int i;
191922        for(i=0; i<pPhrase->nToken; i++){
191923          Fts3PhraseToken *pToken = &pPhrase->aToken[i];
191924          assert( pToken->pDeferred==0 );
191925          if( pToken->pSegcsr ){
191926            sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
191927          }
191928        }
191929        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
191930      }
191931      pPhrase->doclist.pNextDocid = 0;
191932      pPhrase->doclist.iDocid = 0;
191933      pPhrase->pOrPoslist = 0;
191934    }
191935
191936    pExpr->iDocid = 0;
191937    pExpr->bEof = 0;
191938    pExpr->bStart = 0;
191939
191940    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
191941    fts3EvalRestart(pCsr, pExpr->pRight, pRc);
191942  }
191943}
191944
191945/*
191946** After allocating the Fts3Expr.aMI[] array for each phrase in the
191947** expression rooted at pExpr, the cursor iterates through all rows matched
191948** by pExpr, calling this function for each row. This function increments
191949** the values in Fts3Expr.aMI[] according to the position-list currently
191950** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
191951** expression nodes.
191952*/
191953static void fts3EvalUpdateCounts(Fts3Expr *pExpr, int nCol){
191954  if( pExpr ){
191955    Fts3Phrase *pPhrase = pExpr->pPhrase;
191956    if( pPhrase && pPhrase->doclist.pList ){
191957      int iCol = 0;
191958      char *p = pPhrase->doclist.pList;
191959
191960      do{
191961        u8 c = 0;
191962        int iCnt = 0;
191963        while( 0xFE & (*p | c) ){
191964          if( (c&0x80)==0 ) iCnt++;
191965          c = *p++ & 0x80;
191966        }
191967
191968        /* aMI[iCol*3 + 1] = Number of occurrences
191969        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
191970        */
191971        pExpr->aMI[iCol*3 + 1] += iCnt;
191972        pExpr->aMI[iCol*3 + 2] += (iCnt>0);
191973        if( *p==0x00 ) break;
191974        p++;
191975        p += fts3GetVarint32(p, &iCol);
191976      }while( iCol<nCol );
191977    }
191978
191979    fts3EvalUpdateCounts(pExpr->pLeft, nCol);
191980    fts3EvalUpdateCounts(pExpr->pRight, nCol);
191981  }
191982}
191983
191984/*
191985** This is an sqlite3Fts3ExprIterate() callback. If the Fts3Expr.aMI[] array
191986** has not yet been allocated, allocate and zero it. Otherwise, just zero
191987** it.
191988*/
191989static int fts3AllocateMSI(Fts3Expr *pExpr, int iPhrase, void *pCtx){
191990  Fts3Table *pTab = (Fts3Table*)pCtx;
191991  UNUSED_PARAMETER(iPhrase);
191992  if( pExpr->aMI==0 ){
191993    pExpr->aMI = (u32 *)sqlite3_malloc64(pTab->nColumn * 3 * sizeof(u32));
191994    if( pExpr->aMI==0 ) return SQLITE_NOMEM;
191995  }
191996  memset(pExpr->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
191997  return SQLITE_OK;
191998}
191999
192000/*
192001** Expression pExpr must be of type FTSQUERY_PHRASE.
192002**
192003** If it is not already allocated and populated, this function allocates and
192004** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
192005** of a NEAR expression, then it also allocates and populates the same array
192006** for all other phrases that are part of the NEAR expression.
192007**
192008** SQLITE_OK is returned if the aMI[] array is successfully allocated and
192009** populated. Otherwise, if an error occurs, an SQLite error code is returned.
192010*/
192011static int fts3EvalGatherStats(
192012  Fts3Cursor *pCsr,               /* Cursor object */
192013  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
192014){
192015  int rc = SQLITE_OK;             /* Return code */
192016
192017  assert( pExpr->eType==FTSQUERY_PHRASE );
192018  if( pExpr->aMI==0 ){
192019    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
192020    Fts3Expr *pRoot;                /* Root of NEAR expression */
192021
192022    sqlite3_int64 iPrevId = pCsr->iPrevId;
192023    sqlite3_int64 iDocid;
192024    u8 bEof;
192025
192026    /* Find the root of the NEAR expression */
192027    pRoot = pExpr;
192028    while( pRoot->pParent
192029        && (pRoot->pParent->eType==FTSQUERY_NEAR || pRoot->bDeferred)
192030    ){
192031      pRoot = pRoot->pParent;
192032    }
192033    iDocid = pRoot->iDocid;
192034    bEof = pRoot->bEof;
192035    assert( pRoot->bStart );
192036
192037    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
192038    rc = sqlite3Fts3ExprIterate(pRoot, fts3AllocateMSI, (void*)pTab);
192039    if( rc!=SQLITE_OK ) return rc;
192040    fts3EvalRestart(pCsr, pRoot, &rc);
192041
192042    while( pCsr->isEof==0 && rc==SQLITE_OK ){
192043
192044      do {
192045        /* Ensure the %_content statement is reset. */
192046        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
192047        assert( sqlite3_data_count(pCsr->pStmt)==0 );
192048
192049        /* Advance to the next document */
192050        fts3EvalNextRow(pCsr, pRoot, &rc);
192051        pCsr->isEof = pRoot->bEof;
192052        pCsr->isRequireSeek = 1;
192053        pCsr->isMatchinfoNeeded = 1;
192054        pCsr->iPrevId = pRoot->iDocid;
192055      }while( pCsr->isEof==0
192056           && pRoot->eType==FTSQUERY_NEAR
192057           && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
192058      );
192059
192060      if( rc==SQLITE_OK && pCsr->isEof==0 ){
192061        fts3EvalUpdateCounts(pRoot, pTab->nColumn);
192062      }
192063    }
192064
192065    pCsr->isEof = 0;
192066    pCsr->iPrevId = iPrevId;
192067
192068    if( bEof ){
192069      pRoot->bEof = bEof;
192070    }else{
192071      /* Caution: pRoot may iterate through docids in ascending or descending
192072      ** order. For this reason, even though it seems more defensive, the
192073      ** do loop can not be written:
192074      **
192075      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
192076      */
192077      fts3EvalRestart(pCsr, pRoot, &rc);
192078      do {
192079        fts3EvalNextRow(pCsr, pRoot, &rc);
192080        assert_fts3_nc( pRoot->bEof==0 );
192081        if( pRoot->bEof ) rc = FTS_CORRUPT_VTAB;
192082      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
192083    }
192084  }
192085  return rc;
192086}
192087
192088/*
192089** This function is used by the matchinfo() module to query a phrase
192090** expression node for the following information:
192091**
192092**   1. The total number of occurrences of the phrase in each column of
192093**      the FTS table (considering all rows), and
192094**
192095**   2. For each column, the number of rows in the table for which the
192096**      column contains at least one instance of the phrase.
192097**
192098** If no error occurs, SQLITE_OK is returned and the values for each column
192099** written into the array aiOut as follows:
192100**
192101**   aiOut[iCol*3 + 1] = Number of occurrences
192102**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
192103**
192104** Caveats:
192105**
192106**   * If a phrase consists entirely of deferred tokens, then all output
192107**     values are set to the number of documents in the table. In other
192108**     words we assume that very common tokens occur exactly once in each
192109**     column of each row of the table.
192110**
192111**   * If a phrase contains some deferred tokens (and some non-deferred
192112**     tokens), count the potential occurrence identified by considering
192113**     the non-deferred tokens instead of actual phrase occurrences.
192114**
192115**   * If the phrase is part of a NEAR expression, then only phrase instances
192116**     that meet the NEAR constraint are included in the counts.
192117*/
192118SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
192119  Fts3Cursor *pCsr,               /* FTS cursor handle */
192120  Fts3Expr *pExpr,                /* Phrase expression */
192121  u32 *aiOut                      /* Array to write results into (see above) */
192122){
192123  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
192124  int rc = SQLITE_OK;
192125  int iCol;
192126
192127  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
192128    assert( pCsr->nDoc>0 );
192129    for(iCol=0; iCol<pTab->nColumn; iCol++){
192130      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
192131      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
192132    }
192133  }else{
192134    rc = fts3EvalGatherStats(pCsr, pExpr);
192135    if( rc==SQLITE_OK ){
192136      assert( pExpr->aMI );
192137      for(iCol=0; iCol<pTab->nColumn; iCol++){
192138        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
192139        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
192140      }
192141    }
192142  }
192143
192144  return rc;
192145}
192146
192147/*
192148** The expression pExpr passed as the second argument to this function
192149** must be of type FTSQUERY_PHRASE.
192150**
192151** The returned value is either NULL or a pointer to a buffer containing
192152** a position-list indicating the occurrences of the phrase in column iCol
192153** of the current row.
192154**
192155** More specifically, the returned buffer contains 1 varint for each
192156** occurrence of the phrase in the column, stored using the normal (delta+2)
192157** compression and is terminated by either an 0x01 or 0x00 byte. For example,
192158** if the requested column contains "a b X c d X X" and the position-list
192159** for 'X' is requested, the buffer returned may contain:
192160**
192161**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
192162**
192163** This function works regardless of whether or not the phrase is deferred,
192164** incremental, or neither.
192165*/
192166SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
192167  Fts3Cursor *pCsr,               /* FTS3 cursor object */
192168  Fts3Expr *pExpr,                /* Phrase to return doclist for */
192169  int iCol,                       /* Column to return position list for */
192170  char **ppOut                    /* OUT: Pointer to position list */
192171){
192172  Fts3Phrase *pPhrase = pExpr->pPhrase;
192173  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
192174  char *pIter;
192175  int iThis;
192176  sqlite3_int64 iDocid;
192177
192178  /* If this phrase is applies specifically to some column other than
192179  ** column iCol, return a NULL pointer.  */
192180  *ppOut = 0;
192181  assert( iCol>=0 && iCol<pTab->nColumn );
192182  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
192183    return SQLITE_OK;
192184  }
192185
192186  iDocid = pExpr->iDocid;
192187  pIter = pPhrase->doclist.pList;
192188  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
192189    int rc = SQLITE_OK;
192190    int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
192191    int bOr = 0;
192192    u8 bTreeEof = 0;
192193    Fts3Expr *p;                  /* Used to iterate from pExpr to root */
192194    Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
192195    Fts3Expr *pRun;               /* Closest non-deferred ancestor of pNear */
192196    int bMatch;
192197
192198    /* Check if this phrase descends from an OR expression node. If not,
192199    ** return NULL. Otherwise, the entry that corresponds to docid
192200    ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
192201    ** tree that the node is part of has been marked as EOF, but the node
192202    ** itself is not EOF, then it may point to an earlier entry. */
192203    pNear = pExpr;
192204    for(p=pExpr->pParent; p; p=p->pParent){
192205      if( p->eType==FTSQUERY_OR ) bOr = 1;
192206      if( p->eType==FTSQUERY_NEAR ) pNear = p;
192207      if( p->bEof ) bTreeEof = 1;
192208    }
192209    if( bOr==0 ) return SQLITE_OK;
192210    pRun = pNear;
192211    while( pRun->bDeferred ){
192212      assert( pRun->pParent );
192213      pRun = pRun->pParent;
192214    }
192215
192216    /* This is the descendent of an OR node. In this case we cannot use
192217    ** an incremental phrase. Load the entire doclist for the phrase
192218    ** into memory in this case.  */
192219    if( pPhrase->bIncr ){
192220      int bEofSave = pRun->bEof;
192221      fts3EvalRestart(pCsr, pRun, &rc);
192222      while( rc==SQLITE_OK && !pRun->bEof ){
192223        fts3EvalNextRow(pCsr, pRun, &rc);
192224        if( bEofSave==0 && pRun->iDocid==iDocid ) break;
192225      }
192226      assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
192227      if( rc==SQLITE_OK && pRun->bEof!=bEofSave ){
192228        rc = FTS_CORRUPT_VTAB;
192229      }
192230    }
192231    if( bTreeEof ){
192232      while( rc==SQLITE_OK && !pRun->bEof ){
192233        fts3EvalNextRow(pCsr, pRun, &rc);
192234      }
192235    }
192236    if( rc!=SQLITE_OK ) return rc;
192237
192238    bMatch = 1;
192239    for(p=pNear; p; p=p->pLeft){
192240      u8 bEof = 0;
192241      Fts3Expr *pTest = p;
192242      Fts3Phrase *pPh;
192243      assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
192244      if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
192245      assert( pTest->eType==FTSQUERY_PHRASE );
192246      pPh = pTest->pPhrase;
192247
192248      pIter = pPh->pOrPoslist;
192249      iDocid = pPh->iOrDocid;
192250      if( pCsr->bDesc==bDescDoclist ){
192251        bEof = !pPh->doclist.nAll ||
192252          (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
192253        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
192254          sqlite3Fts3DoclistNext(
192255              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
192256              &pIter, &iDocid, &bEof
192257          );
192258        }
192259      }else{
192260        bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
192261        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
192262          int dummy;
192263          sqlite3Fts3DoclistPrev(
192264              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
192265              &pIter, &iDocid, &dummy, &bEof
192266              );
192267        }
192268      }
192269      pPh->pOrPoslist = pIter;
192270      pPh->iOrDocid = iDocid;
192271      if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
192272    }
192273
192274    if( bMatch ){
192275      pIter = pPhrase->pOrPoslist;
192276    }else{
192277      pIter = 0;
192278    }
192279  }
192280  if( pIter==0 ) return SQLITE_OK;
192281
192282  if( *pIter==0x01 ){
192283    pIter++;
192284    pIter += fts3GetVarint32(pIter, &iThis);
192285  }else{
192286    iThis = 0;
192287  }
192288  while( iThis<iCol ){
192289    fts3ColumnlistCopy(0, &pIter);
192290    if( *pIter==0x00 ) return SQLITE_OK;
192291    pIter++;
192292    pIter += fts3GetVarint32(pIter, &iThis);
192293  }
192294  if( *pIter==0x00 ){
192295    pIter = 0;
192296  }
192297
192298  *ppOut = ((iCol==iThis)?pIter:0);
192299  return SQLITE_OK;
192300}
192301
192302/*
192303** Free all components of the Fts3Phrase structure that were allocated by
192304** the eval module. Specifically, this means to free:
192305**
192306**   * the contents of pPhrase->doclist, and
192307**   * any Fts3MultiSegReader objects held by phrase tokens.
192308*/
192309SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
192310  if( pPhrase ){
192311    int i;
192312    sqlite3_free(pPhrase->doclist.aAll);
192313    fts3EvalInvalidatePoslist(pPhrase);
192314    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
192315    for(i=0; i<pPhrase->nToken; i++){
192316      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
192317      pPhrase->aToken[i].pSegcsr = 0;
192318    }
192319  }
192320}
192321
192322
192323/*
192324** Return SQLITE_CORRUPT_VTAB.
192325*/
192326#ifdef SQLITE_DEBUG
192327SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
192328  return SQLITE_CORRUPT_VTAB;
192329}
192330#endif
192331
192332#if !SQLITE_CORE
192333/*
192334** Initialize API pointer table, if required.
192335*/
192336#ifdef _WIN32
192337__declspec(dllexport)
192338#endif
192339SQLITE_API int sqlite3_fts3_init(
192340  sqlite3 *db,
192341  char **pzErrMsg,
192342  const sqlite3_api_routines *pApi
192343){
192344  SQLITE_EXTENSION_INIT2(pApi)
192345  return sqlite3Fts3Init(db);
192346}
192347#endif
192348
192349#endif
192350
192351/************** End of fts3.c ************************************************/
192352/************** Begin file fts3_aux.c ****************************************/
192353/*
192354** 2011 Jan 27
192355**
192356** The author disclaims copyright to this source code.  In place of
192357** a legal notice, here is a blessing:
192358**
192359**    May you do good and not evil.
192360**    May you find forgiveness for yourself and forgive others.
192361**    May you share freely, never taking more than you give.
192362**
192363******************************************************************************
192364**
192365*/
192366/* #include "fts3Int.h" */
192367#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
192368
192369/* #include <string.h> */
192370/* #include <assert.h> */
192371
192372typedef struct Fts3auxTable Fts3auxTable;
192373typedef struct Fts3auxCursor Fts3auxCursor;
192374
192375struct Fts3auxTable {
192376  sqlite3_vtab base;              /* Base class used by SQLite core */
192377  Fts3Table *pFts3Tab;
192378};
192379
192380struct Fts3auxCursor {
192381  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
192382  Fts3MultiSegReader csr;        /* Must be right after "base" */
192383  Fts3SegFilter filter;
192384  char *zStop;
192385  int nStop;                      /* Byte-length of string zStop */
192386  int iLangid;                    /* Language id to query */
192387  int isEof;                      /* True if cursor is at EOF */
192388  sqlite3_int64 iRowid;           /* Current rowid */
192389
192390  int iCol;                       /* Current value of 'col' column */
192391  int nStat;                      /* Size of aStat[] array */
192392  struct Fts3auxColstats {
192393    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
192394    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
192395  } *aStat;
192396};
192397
192398/*
192399** Schema of the terms table.
192400*/
192401#define FTS3_AUX_SCHEMA \
192402  "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
192403
192404/*
192405** This function does all the work for both the xConnect and xCreate methods.
192406** These tables have no persistent representation of their own, so xConnect
192407** and xCreate are identical operations.
192408*/
192409static int fts3auxConnectMethod(
192410  sqlite3 *db,                    /* Database connection */
192411  void *pUnused,                  /* Unused */
192412  int argc,                       /* Number of elements in argv array */
192413  const char * const *argv,       /* xCreate/xConnect argument array */
192414  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
192415  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
192416){
192417  char const *zDb;                /* Name of database (e.g. "main") */
192418  char const *zFts3;              /* Name of fts3 table */
192419  int nDb;                        /* Result of strlen(zDb) */
192420  int nFts3;                      /* Result of strlen(zFts3) */
192421  sqlite3_int64 nByte;            /* Bytes of space to allocate here */
192422  int rc;                         /* value returned by declare_vtab() */
192423  Fts3auxTable *p;                /* Virtual table object to return */
192424
192425  UNUSED_PARAMETER(pUnused);
192426
192427  /* The user should invoke this in one of two forms:
192428  **
192429  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
192430  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
192431  */
192432  if( argc!=4 && argc!=5 ) goto bad_args;
192433
192434  zDb = argv[1];
192435  nDb = (int)strlen(zDb);
192436  if( argc==5 ){
192437    if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
192438      zDb = argv[3];
192439      nDb = (int)strlen(zDb);
192440      zFts3 = argv[4];
192441    }else{
192442      goto bad_args;
192443    }
192444  }else{
192445    zFts3 = argv[3];
192446  }
192447  nFts3 = (int)strlen(zFts3);
192448
192449  rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
192450  if( rc!=SQLITE_OK ) return rc;
192451
192452  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
192453  p = (Fts3auxTable *)sqlite3_malloc64(nByte);
192454  if( !p ) return SQLITE_NOMEM;
192455  memset(p, 0, nByte);
192456
192457  p->pFts3Tab = (Fts3Table *)&p[1];
192458  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
192459  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
192460  p->pFts3Tab->db = db;
192461  p->pFts3Tab->nIndex = 1;
192462
192463  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
192464  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
192465  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
192466
192467  *ppVtab = (sqlite3_vtab *)p;
192468  return SQLITE_OK;
192469
192470 bad_args:
192471  sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
192472  return SQLITE_ERROR;
192473}
192474
192475/*
192476** This function does the work for both the xDisconnect and xDestroy methods.
192477** These tables have no persistent representation of their own, so xDisconnect
192478** and xDestroy are identical operations.
192479*/
192480static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
192481  Fts3auxTable *p = (Fts3auxTable *)pVtab;
192482  Fts3Table *pFts3 = p->pFts3Tab;
192483  int i;
192484
192485  /* Free any prepared statements held */
192486  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
192487    sqlite3_finalize(pFts3->aStmt[i]);
192488  }
192489  sqlite3_free(pFts3->zSegmentsTbl);
192490  sqlite3_free(p);
192491  return SQLITE_OK;
192492}
192493
192494#define FTS4AUX_EQ_CONSTRAINT 1
192495#define FTS4AUX_GE_CONSTRAINT 2
192496#define FTS4AUX_LE_CONSTRAINT 4
192497
192498/*
192499** xBestIndex - Analyze a WHERE and ORDER BY clause.
192500*/
192501static int fts3auxBestIndexMethod(
192502  sqlite3_vtab *pVTab,
192503  sqlite3_index_info *pInfo
192504){
192505  int i;
192506  int iEq = -1;
192507  int iGe = -1;
192508  int iLe = -1;
192509  int iLangid = -1;
192510  int iNext = 1;                  /* Next free argvIndex value */
192511
192512  UNUSED_PARAMETER(pVTab);
192513
192514  /* This vtab delivers always results in "ORDER BY term ASC" order. */
192515  if( pInfo->nOrderBy==1
192516   && pInfo->aOrderBy[0].iColumn==0
192517   && pInfo->aOrderBy[0].desc==0
192518  ){
192519    pInfo->orderByConsumed = 1;
192520  }
192521
192522  /* Search for equality and range constraints on the "term" column.
192523  ** And equality constraints on the hidden "languageid" column. */
192524  for(i=0; i<pInfo->nConstraint; i++){
192525    if( pInfo->aConstraint[i].usable ){
192526      int op = pInfo->aConstraint[i].op;
192527      int iCol = pInfo->aConstraint[i].iColumn;
192528
192529      if( iCol==0 ){
192530        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
192531        if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
192532        if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
192533        if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
192534        if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
192535      }
192536      if( iCol==4 ){
192537        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
192538      }
192539    }
192540  }
192541
192542  if( iEq>=0 ){
192543    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
192544    pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
192545    pInfo->estimatedCost = 5;
192546  }else{
192547    pInfo->idxNum = 0;
192548    pInfo->estimatedCost = 20000;
192549    if( iGe>=0 ){
192550      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
192551      pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
192552      pInfo->estimatedCost /= 2;
192553    }
192554    if( iLe>=0 ){
192555      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
192556      pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
192557      pInfo->estimatedCost /= 2;
192558    }
192559  }
192560  if( iLangid>=0 ){
192561    pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
192562    pInfo->estimatedCost--;
192563  }
192564
192565  return SQLITE_OK;
192566}
192567
192568/*
192569** xOpen - Open a cursor.
192570*/
192571static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
192572  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
192573
192574  UNUSED_PARAMETER(pVTab);
192575
192576  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
192577  if( !pCsr ) return SQLITE_NOMEM;
192578  memset(pCsr, 0, sizeof(Fts3auxCursor));
192579
192580  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
192581  return SQLITE_OK;
192582}
192583
192584/*
192585** xClose - Close a cursor.
192586*/
192587static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
192588  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
192589  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
192590
192591  sqlite3Fts3SegmentsClose(pFts3);
192592  sqlite3Fts3SegReaderFinish(&pCsr->csr);
192593  sqlite3_free((void *)pCsr->filter.zTerm);
192594  sqlite3_free(pCsr->zStop);
192595  sqlite3_free(pCsr->aStat);
192596  sqlite3_free(pCsr);
192597  return SQLITE_OK;
192598}
192599
192600static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
192601  if( nSize>pCsr->nStat ){
192602    struct Fts3auxColstats *aNew;
192603    aNew = (struct Fts3auxColstats *)sqlite3_realloc64(pCsr->aStat,
192604        sizeof(struct Fts3auxColstats) * nSize
192605    );
192606    if( aNew==0 ) return SQLITE_NOMEM;
192607    memset(&aNew[pCsr->nStat], 0,
192608        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
192609    );
192610    pCsr->aStat = aNew;
192611    pCsr->nStat = nSize;
192612  }
192613  return SQLITE_OK;
192614}
192615
192616/*
192617** xNext - Advance the cursor to the next row, if any.
192618*/
192619static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
192620  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
192621  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
192622  int rc;
192623
192624  /* Increment our pretend rowid value. */
192625  pCsr->iRowid++;
192626
192627  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
192628    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
192629  }
192630
192631  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
192632  if( rc==SQLITE_ROW ){
192633    int i = 0;
192634    int nDoclist = pCsr->csr.nDoclist;
192635    char *aDoclist = pCsr->csr.aDoclist;
192636    int iCol;
192637
192638    int eState = 0;
192639
192640    if( pCsr->zStop ){
192641      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
192642      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
192643      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
192644        pCsr->isEof = 1;
192645        return SQLITE_OK;
192646      }
192647    }
192648
192649    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
192650    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
192651    iCol = 0;
192652    rc = SQLITE_OK;
192653
192654    while( i<nDoclist ){
192655      sqlite3_int64 v = 0;
192656
192657      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
192658      switch( eState ){
192659        /* State 0. In this state the integer just read was a docid. */
192660        case 0:
192661          pCsr->aStat[0].nDoc++;
192662          eState = 1;
192663          iCol = 0;
192664          break;
192665
192666        /* State 1. In this state we are expecting either a 1, indicating
192667        ** that the following integer will be a column number, or the
192668        ** start of a position list for column 0.
192669        **
192670        ** The only difference between state 1 and state 2 is that if the
192671        ** integer encountered in state 1 is not 0 or 1, then we need to
192672        ** increment the column 0 "nDoc" count for this term.
192673        */
192674        case 1:
192675          assert( iCol==0 );
192676          if( v>1 ){
192677            pCsr->aStat[1].nDoc++;
192678          }
192679          eState = 2;
192680          /* fall through */
192681
192682        case 2:
192683          if( v==0 ){       /* 0x00. Next integer will be a docid. */
192684            eState = 0;
192685          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
192686            eState = 3;
192687          }else{            /* 2 or greater. A position. */
192688            pCsr->aStat[iCol+1].nOcc++;
192689            pCsr->aStat[0].nOcc++;
192690          }
192691          break;
192692
192693        /* State 3. The integer just read is a column number. */
192694        default: assert( eState==3 );
192695          iCol = (int)v;
192696          if( iCol<1 ){
192697            rc = SQLITE_CORRUPT_VTAB;
192698            break;
192699          }
192700          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
192701          pCsr->aStat[iCol+1].nDoc++;
192702          eState = 2;
192703          break;
192704      }
192705    }
192706
192707    pCsr->iCol = 0;
192708  }else{
192709    pCsr->isEof = 1;
192710  }
192711  return rc;
192712}
192713
192714/*
192715** xFilter - Initialize a cursor to point at the start of its data.
192716*/
192717static int fts3auxFilterMethod(
192718  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
192719  int idxNum,                     /* Strategy index */
192720  const char *idxStr,             /* Unused */
192721  int nVal,                       /* Number of elements in apVal */
192722  sqlite3_value **apVal           /* Arguments for the indexing scheme */
192723){
192724  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
192725  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
192726  int rc;
192727  int isScan = 0;
192728  int iLangVal = 0;               /* Language id to query */
192729
192730  int iEq = -1;                   /* Index of term=? value in apVal */
192731  int iGe = -1;                   /* Index of term>=? value in apVal */
192732  int iLe = -1;                   /* Index of term<=? value in apVal */
192733  int iLangid = -1;               /* Index of languageid=? value in apVal */
192734  int iNext = 0;
192735
192736  UNUSED_PARAMETER(nVal);
192737  UNUSED_PARAMETER(idxStr);
192738
192739  assert( idxStr==0 );
192740  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
192741       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
192742       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
192743  );
192744
192745  if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
192746    iEq = iNext++;
192747  }else{
192748    isScan = 1;
192749    if( idxNum & FTS4AUX_GE_CONSTRAINT ){
192750      iGe = iNext++;
192751    }
192752    if( idxNum & FTS4AUX_LE_CONSTRAINT ){
192753      iLe = iNext++;
192754    }
192755  }
192756  if( iNext<nVal ){
192757    iLangid = iNext++;
192758  }
192759
192760  /* In case this cursor is being reused, close and zero it. */
192761  testcase(pCsr->filter.zTerm);
192762  sqlite3Fts3SegReaderFinish(&pCsr->csr);
192763  sqlite3_free((void *)pCsr->filter.zTerm);
192764  sqlite3_free(pCsr->aStat);
192765  sqlite3_free(pCsr->zStop);
192766  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
192767
192768  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
192769  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
192770
192771  if( iEq>=0 || iGe>=0 ){
192772    const unsigned char *zStr = sqlite3_value_text(apVal[0]);
192773    assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
192774    if( zStr ){
192775      pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
192776      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
192777      pCsr->filter.nTerm = (int)strlen(pCsr->filter.zTerm);
192778    }
192779  }
192780
192781  if( iLe>=0 ){
192782    pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
192783    if( pCsr->zStop==0 ) return SQLITE_NOMEM;
192784    pCsr->nStop = (int)strlen(pCsr->zStop);
192785  }
192786
192787  if( iLangid>=0 ){
192788    iLangVal = sqlite3_value_int(apVal[iLangid]);
192789
192790    /* If the user specified a negative value for the languageid, use zero
192791    ** instead. This works, as the "languageid=?" constraint will also
192792    ** be tested by the VDBE layer. The test will always be false (since
192793    ** this module will not return a row with a negative languageid), and
192794    ** so the overall query will return zero rows.  */
192795    if( iLangVal<0 ) iLangVal = 0;
192796  }
192797  pCsr->iLangid = iLangVal;
192798
192799  rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
192800      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
192801  );
192802  if( rc==SQLITE_OK ){
192803    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
192804  }
192805
192806  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
192807  return rc;
192808}
192809
192810/*
192811** xEof - Return true if the cursor is at EOF, or false otherwise.
192812*/
192813static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
192814  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
192815  return pCsr->isEof;
192816}
192817
192818/*
192819** xColumn - Return a column value.
192820*/
192821static int fts3auxColumnMethod(
192822  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
192823  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
192824  int iCol                        /* Index of column to read value from */
192825){
192826  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
192827
192828  assert( p->isEof==0 );
192829  switch( iCol ){
192830    case 0: /* term */
192831      sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
192832      break;
192833
192834    case 1: /* col */
192835      if( p->iCol ){
192836        sqlite3_result_int(pCtx, p->iCol-1);
192837      }else{
192838        sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
192839      }
192840      break;
192841
192842    case 2: /* documents */
192843      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
192844      break;
192845
192846    case 3: /* occurrences */
192847      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
192848      break;
192849
192850    default: /* languageid */
192851      assert( iCol==4 );
192852      sqlite3_result_int(pCtx, p->iLangid);
192853      break;
192854  }
192855
192856  return SQLITE_OK;
192857}
192858
192859/*
192860** xRowid - Return the current rowid for the cursor.
192861*/
192862static int fts3auxRowidMethod(
192863  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
192864  sqlite_int64 *pRowid            /* OUT: Rowid value */
192865){
192866  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
192867  *pRowid = pCsr->iRowid;
192868  return SQLITE_OK;
192869}
192870
192871/*
192872** Register the fts3aux module with database connection db. Return SQLITE_OK
192873** if successful or an error code if sqlite3_create_module() fails.
192874*/
192875SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
192876  static const sqlite3_module fts3aux_module = {
192877     0,                           /* iVersion      */
192878     fts3auxConnectMethod,        /* xCreate       */
192879     fts3auxConnectMethod,        /* xConnect      */
192880     fts3auxBestIndexMethod,      /* xBestIndex    */
192881     fts3auxDisconnectMethod,     /* xDisconnect   */
192882     fts3auxDisconnectMethod,     /* xDestroy      */
192883     fts3auxOpenMethod,           /* xOpen         */
192884     fts3auxCloseMethod,          /* xClose        */
192885     fts3auxFilterMethod,         /* xFilter       */
192886     fts3auxNextMethod,           /* xNext         */
192887     fts3auxEofMethod,            /* xEof          */
192888     fts3auxColumnMethod,         /* xColumn       */
192889     fts3auxRowidMethod,          /* xRowid        */
192890     0,                           /* xUpdate       */
192891     0,                           /* xBegin        */
192892     0,                           /* xSync         */
192893     0,                           /* xCommit       */
192894     0,                           /* xRollback     */
192895     0,                           /* xFindFunction */
192896     0,                           /* xRename       */
192897     0,                           /* xSavepoint    */
192898     0,                           /* xRelease      */
192899     0,                           /* xRollbackTo   */
192900     0,                           /* xShadowName   */
192901     0                            /* xIntegrity    */
192902  };
192903  int rc;                         /* Return code */
192904
192905  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
192906  return rc;
192907}
192908
192909#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
192910
192911/************** End of fts3_aux.c ********************************************/
192912/************** Begin file fts3_expr.c ***************************************/
192913/*
192914** 2008 Nov 28
192915**
192916** The author disclaims copyright to this source code.  In place of
192917** a legal notice, here is a blessing:
192918**
192919**    May you do good and not evil.
192920**    May you find forgiveness for yourself and forgive others.
192921**    May you share freely, never taking more than you give.
192922**
192923******************************************************************************
192924**
192925** This module contains code that implements a parser for fts3 query strings
192926** (the right-hand argument to the MATCH operator). Because the supported
192927** syntax is relatively simple, the whole tokenizer/parser system is
192928** hand-coded.
192929*/
192930/* #include "fts3Int.h" */
192931#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
192932
192933/*
192934** By default, this module parses the legacy syntax that has been
192935** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
192936** is defined, then it uses the new syntax. The differences between
192937** the new and the old syntaxes are:
192938**
192939**  a) The new syntax supports parenthesis. The old does not.
192940**
192941**  b) The new syntax supports the AND and NOT operators. The old does not.
192942**
192943**  c) The old syntax supports the "-" token qualifier. This is not
192944**     supported by the new syntax (it is replaced by the NOT operator).
192945**
192946**  d) When using the old syntax, the OR operator has a greater precedence
192947**     than an implicit AND. When using the new, both implicity and explicit
192948**     AND operators have a higher precedence than OR.
192949**
192950** If compiled with SQLITE_TEST defined, then this module exports the
192951** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
192952** to zero causes the module to use the old syntax. If it is set to
192953** non-zero the new syntax is activated. This is so both syntaxes can
192954** be tested using a single build of testfixture.
192955**
192956** The following describes the syntax supported by the fts3 MATCH
192957** operator in a similar format to that used by the lemon parser
192958** generator. This module does not use actually lemon, it uses a
192959** custom parser.
192960**
192961**   query ::= andexpr (OR andexpr)*.
192962**
192963**   andexpr ::= notexpr (AND? notexpr)*.
192964**
192965**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
192966**   notexpr ::= LP query RP.
192967**
192968**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
192969**
192970**   distance_opt ::= .
192971**   distance_opt ::= / INTEGER.
192972**
192973**   phrase ::= TOKEN.
192974**   phrase ::= COLUMN:TOKEN.
192975**   phrase ::= "TOKEN TOKEN TOKEN...".
192976*/
192977
192978#ifdef SQLITE_TEST
192979SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
192980#else
192981# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
192982#  define sqlite3_fts3_enable_parentheses 1
192983# else
192984#  define sqlite3_fts3_enable_parentheses 0
192985# endif
192986#endif
192987
192988/*
192989** Default span for NEAR operators.
192990*/
192991#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
192992
192993/* #include <string.h> */
192994/* #include <assert.h> */
192995
192996/*
192997** isNot:
192998**   This variable is used by function getNextNode(). When getNextNode() is
192999**   called, it sets ParseContext.isNot to true if the 'next node' is a
193000**   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
193001**   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
193002**   zero.
193003*/
193004typedef struct ParseContext ParseContext;
193005struct ParseContext {
193006  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
193007  int iLangid;                        /* Language id used with tokenizer */
193008  const char **azCol;                 /* Array of column names for fts3 table */
193009  int bFts4;                          /* True to allow FTS4-only syntax */
193010  int nCol;                           /* Number of entries in azCol[] */
193011  int iDefaultCol;                    /* Default column to query */
193012  int isNot;                          /* True if getNextNode() sees a unary - */
193013  sqlite3_context *pCtx;              /* Write error message here */
193014  int nNest;                          /* Number of nested brackets */
193015};
193016
193017/*
193018** This function is equivalent to the standard isspace() function.
193019**
193020** The standard isspace() can be awkward to use safely, because although it
193021** is defined to accept an argument of type int, its behavior when passed
193022** an integer that falls outside of the range of the unsigned char type
193023** is undefined (and sometimes, "undefined" means segfault). This wrapper
193024** is defined to accept an argument of type char, and always returns 0 for
193025** any values that fall outside of the range of the unsigned char type (i.e.
193026** negative values).
193027*/
193028static int fts3isspace(char c){
193029  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
193030}
193031
193032/*
193033** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
193034** zero the memory before returning a pointer to it. If unsuccessful,
193035** return NULL.
193036*/
193037SQLITE_PRIVATE void *sqlite3Fts3MallocZero(sqlite3_int64 nByte){
193038  void *pRet = sqlite3_malloc64(nByte);
193039  if( pRet ) memset(pRet, 0, nByte);
193040  return pRet;
193041}
193042
193043SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
193044  sqlite3_tokenizer *pTokenizer,
193045  int iLangid,
193046  const char *z,
193047  int n,
193048  sqlite3_tokenizer_cursor **ppCsr
193049){
193050  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
193051  sqlite3_tokenizer_cursor *pCsr = 0;
193052  int rc;
193053
193054  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
193055  assert( rc==SQLITE_OK || pCsr==0 );
193056  if( rc==SQLITE_OK ){
193057    pCsr->pTokenizer = pTokenizer;
193058    if( pModule->iVersion>=1 ){
193059      rc = pModule->xLanguageid(pCsr, iLangid);
193060      if( rc!=SQLITE_OK ){
193061        pModule->xClose(pCsr);
193062        pCsr = 0;
193063      }
193064    }
193065  }
193066  *ppCsr = pCsr;
193067  return rc;
193068}
193069
193070/*
193071** Function getNextNode(), which is called by fts3ExprParse(), may itself
193072** call fts3ExprParse(). So this forward declaration is required.
193073*/
193074static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
193075
193076/*
193077** Extract the next token from buffer z (length n) using the tokenizer
193078** and other information (column names etc.) in pParse. Create an Fts3Expr
193079** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
193080** single token and set *ppExpr to point to it. If the end of the buffer is
193081** reached before a token is found, set *ppExpr to zero. It is the
193082** responsibility of the caller to eventually deallocate the allocated
193083** Fts3Expr structure (if any) by passing it to sqlite3_free().
193084**
193085** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
193086** fails.
193087*/
193088static int getNextToken(
193089  ParseContext *pParse,                   /* fts3 query parse context */
193090  int iCol,                               /* Value for Fts3Phrase.iColumn */
193091  const char *z, int n,                   /* Input string */
193092  Fts3Expr **ppExpr,                      /* OUT: expression */
193093  int *pnConsumed                         /* OUT: Number of bytes consumed */
193094){
193095  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
193096  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
193097  int rc;
193098  sqlite3_tokenizer_cursor *pCursor;
193099  Fts3Expr *pRet = 0;
193100  int i = 0;
193101
193102  /* Set variable i to the maximum number of bytes of input to tokenize. */
193103  for(i=0; i<n; i++){
193104    if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
193105    if( z[i]=='"' ) break;
193106  }
193107
193108  *pnConsumed = i;
193109  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
193110  if( rc==SQLITE_OK ){
193111    const char *zToken;
193112    int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
193113    sqlite3_int64 nByte;                    /* total space to allocate */
193114
193115    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
193116    if( rc==SQLITE_OK ){
193117      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
193118      pRet = (Fts3Expr *)sqlite3Fts3MallocZero(nByte);
193119      if( !pRet ){
193120        rc = SQLITE_NOMEM;
193121      }else{
193122        pRet->eType = FTSQUERY_PHRASE;
193123        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
193124        pRet->pPhrase->nToken = 1;
193125        pRet->pPhrase->iColumn = iCol;
193126        pRet->pPhrase->aToken[0].n = nToken;
193127        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
193128        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
193129
193130        if( iEnd<n && z[iEnd]=='*' ){
193131          pRet->pPhrase->aToken[0].isPrefix = 1;
193132          iEnd++;
193133        }
193134
193135        while( 1 ){
193136          if( !sqlite3_fts3_enable_parentheses
193137           && iStart>0 && z[iStart-1]=='-'
193138          ){
193139            pParse->isNot = 1;
193140            iStart--;
193141          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
193142            pRet->pPhrase->aToken[0].bFirst = 1;
193143            iStart--;
193144          }else{
193145            break;
193146          }
193147        }
193148
193149      }
193150      *pnConsumed = iEnd;
193151    }else if( i && rc==SQLITE_DONE ){
193152      rc = SQLITE_OK;
193153    }
193154
193155    pModule->xClose(pCursor);
193156  }
193157
193158  *ppExpr = pRet;
193159  return rc;
193160}
193161
193162
193163/*
193164** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
193165** then free the old allocation.
193166*/
193167static void *fts3ReallocOrFree(void *pOrig, sqlite3_int64 nNew){
193168  void *pRet = sqlite3_realloc64(pOrig, nNew);
193169  if( !pRet ){
193170    sqlite3_free(pOrig);
193171  }
193172  return pRet;
193173}
193174
193175/*
193176** Buffer zInput, length nInput, contains the contents of a quoted string
193177** that appeared as part of an fts3 query expression. Neither quote character
193178** is included in the buffer. This function attempts to tokenize the entire
193179** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
193180** containing the results.
193181**
193182** If successful, SQLITE_OK is returned and *ppExpr set to point at the
193183** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
193184** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
193185** to 0.
193186*/
193187static int getNextString(
193188  ParseContext *pParse,                   /* fts3 query parse context */
193189  const char *zInput, int nInput,         /* Input string */
193190  Fts3Expr **ppExpr                       /* OUT: expression */
193191){
193192  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
193193  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
193194  int rc;
193195  Fts3Expr *p = 0;
193196  sqlite3_tokenizer_cursor *pCursor = 0;
193197  char *zTemp = 0;
193198  int nTemp = 0;
193199
193200  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
193201  int nToken = 0;
193202
193203  /* The final Fts3Expr data structure, including the Fts3Phrase,
193204  ** Fts3PhraseToken structures token buffers are all stored as a single
193205  ** allocation so that the expression can be freed with a single call to
193206  ** sqlite3_free(). Setting this up requires a two pass approach.
193207  **
193208  ** The first pass, in the block below, uses a tokenizer cursor to iterate
193209  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
193210  ** to assemble data in two dynamic buffers:
193211  **
193212  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
193213  **             structure, followed by the array of Fts3PhraseToken
193214  **             structures. This pass only populates the Fts3PhraseToken array.
193215  **
193216  **   Buffer zTemp: Contains copies of all tokens.
193217  **
193218  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
193219  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
193220  ** structures.
193221  */
193222  rc = sqlite3Fts3OpenTokenizer(
193223      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
193224  if( rc==SQLITE_OK ){
193225    int ii;
193226    for(ii=0; rc==SQLITE_OK; ii++){
193227      const char *zByte;
193228      int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
193229      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
193230      if( rc==SQLITE_OK ){
193231        Fts3PhraseToken *pToken;
193232
193233        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
193234        if( !p ) goto no_mem;
193235
193236        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
193237        if( !zTemp ) goto no_mem;
193238
193239        assert( nToken==ii );
193240        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
193241        memset(pToken, 0, sizeof(Fts3PhraseToken));
193242
193243        memcpy(&zTemp[nTemp], zByte, nByte);
193244        nTemp += nByte;
193245
193246        pToken->n = nByte;
193247        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
193248        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
193249        nToken = ii+1;
193250      }
193251    }
193252
193253    pModule->xClose(pCursor);
193254    pCursor = 0;
193255  }
193256
193257  if( rc==SQLITE_DONE ){
193258    int jj;
193259    char *zBuf = 0;
193260
193261    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
193262    if( !p ) goto no_mem;
193263    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
193264    p->eType = FTSQUERY_PHRASE;
193265    p->pPhrase = (Fts3Phrase *)&p[1];
193266    p->pPhrase->iColumn = pParse->iDefaultCol;
193267    p->pPhrase->nToken = nToken;
193268
193269    zBuf = (char *)&p->pPhrase->aToken[nToken];
193270    if( zTemp ){
193271      memcpy(zBuf, zTemp, nTemp);
193272      sqlite3_free(zTemp);
193273    }else{
193274      assert( nTemp==0 );
193275    }
193276
193277    for(jj=0; jj<p->pPhrase->nToken; jj++){
193278      p->pPhrase->aToken[jj].z = zBuf;
193279      zBuf += p->pPhrase->aToken[jj].n;
193280    }
193281    rc = SQLITE_OK;
193282  }
193283
193284  *ppExpr = p;
193285  return rc;
193286no_mem:
193287
193288  if( pCursor ){
193289    pModule->xClose(pCursor);
193290  }
193291  sqlite3_free(zTemp);
193292  sqlite3_free(p);
193293  *ppExpr = 0;
193294  return SQLITE_NOMEM;
193295}
193296
193297/*
193298** The output variable *ppExpr is populated with an allocated Fts3Expr
193299** structure, or set to 0 if the end of the input buffer is reached.
193300**
193301** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
193302** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
193303** If SQLITE_ERROR is returned, pContext is populated with an error message.
193304*/
193305static int getNextNode(
193306  ParseContext *pParse,                   /* fts3 query parse context */
193307  const char *z, int n,                   /* Input string */
193308  Fts3Expr **ppExpr,                      /* OUT: expression */
193309  int *pnConsumed                         /* OUT: Number of bytes consumed */
193310){
193311  static const struct Fts3Keyword {
193312    char *z;                              /* Keyword text */
193313    unsigned char n;                      /* Length of the keyword */
193314    unsigned char parenOnly;              /* Only valid in paren mode */
193315    unsigned char eType;                  /* Keyword code */
193316  } aKeyword[] = {
193317    { "OR" ,  2, 0, FTSQUERY_OR   },
193318    { "AND",  3, 1, FTSQUERY_AND  },
193319    { "NOT",  3, 1, FTSQUERY_NOT  },
193320    { "NEAR", 4, 0, FTSQUERY_NEAR }
193321  };
193322  int ii;
193323  int iCol;
193324  int iColLen;
193325  int rc;
193326  Fts3Expr *pRet = 0;
193327
193328  const char *zInput = z;
193329  int nInput = n;
193330
193331  pParse->isNot = 0;
193332
193333  /* Skip over any whitespace before checking for a keyword, an open or
193334  ** close bracket, or a quoted string.
193335  */
193336  while( nInput>0 && fts3isspace(*zInput) ){
193337    nInput--;
193338    zInput++;
193339  }
193340  if( nInput==0 ){
193341    return SQLITE_DONE;
193342  }
193343
193344  /* See if we are dealing with a keyword. */
193345  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
193346    const struct Fts3Keyword *pKey = &aKeyword[ii];
193347
193348    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
193349      continue;
193350    }
193351
193352    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
193353      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
193354      int nKey = pKey->n;
193355      char cNext;
193356
193357      /* If this is a "NEAR" keyword, check for an explicit nearness. */
193358      if( pKey->eType==FTSQUERY_NEAR ){
193359        assert( nKey==4 );
193360        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
193361          nKey += 1+sqlite3Fts3ReadInt(&zInput[nKey+1], &nNear);
193362        }
193363      }
193364
193365      /* At this point this is probably a keyword. But for that to be true,
193366      ** the next byte must contain either whitespace, an open or close
193367      ** parenthesis, a quote character, or EOF.
193368      */
193369      cNext = zInput[nKey];
193370      if( fts3isspace(cNext)
193371       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
193372      ){
193373        pRet = (Fts3Expr *)sqlite3Fts3MallocZero(sizeof(Fts3Expr));
193374        if( !pRet ){
193375          return SQLITE_NOMEM;
193376        }
193377        pRet->eType = pKey->eType;
193378        pRet->nNear = nNear;
193379        *ppExpr = pRet;
193380        *pnConsumed = (int)((zInput - z) + nKey);
193381        return SQLITE_OK;
193382      }
193383
193384      /* Turns out that wasn't a keyword after all. This happens if the
193385      ** user has supplied a token such as "ORacle". Continue.
193386      */
193387    }
193388  }
193389
193390  /* See if we are dealing with a quoted phrase. If this is the case, then
193391  ** search for the closing quote and pass the whole string to getNextString()
193392  ** for processing. This is easy to do, as fts3 has no syntax for escaping
193393  ** a quote character embedded in a string.
193394  */
193395  if( *zInput=='"' ){
193396    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
193397    *pnConsumed = (int)((zInput - z) + ii + 1);
193398    if( ii==nInput ){
193399      return SQLITE_ERROR;
193400    }
193401    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
193402  }
193403
193404  if( sqlite3_fts3_enable_parentheses ){
193405    if( *zInput=='(' ){
193406      int nConsumed = 0;
193407      pParse->nNest++;
193408#if !defined(SQLITE_MAX_EXPR_DEPTH)
193409      if( pParse->nNest>1000 ) return SQLITE_ERROR;
193410#elif SQLITE_MAX_EXPR_DEPTH>0
193411      if( pParse->nNest>SQLITE_MAX_EXPR_DEPTH ) return SQLITE_ERROR;
193412#endif
193413      rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
193414      *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
193415      return rc;
193416    }else if( *zInput==')' ){
193417      pParse->nNest--;
193418      *pnConsumed = (int)((zInput - z) + 1);
193419      *ppExpr = 0;
193420      return SQLITE_DONE;
193421    }
193422  }
193423
193424  /* If control flows to this point, this must be a regular token, or
193425  ** the end of the input. Read a regular token using the sqlite3_tokenizer
193426  ** interface. Before doing so, figure out if there is an explicit
193427  ** column specifier for the token.
193428  **
193429  ** TODO: Strangely, it is not possible to associate a column specifier
193430  ** with a quoted phrase, only with a single token. Not sure if this was
193431  ** an implementation artifact or an intentional decision when fts3 was
193432  ** first implemented. Whichever it was, this module duplicates the
193433  ** limitation.
193434  */
193435  iCol = pParse->iDefaultCol;
193436  iColLen = 0;
193437  for(ii=0; ii<pParse->nCol; ii++){
193438    const char *zStr = pParse->azCol[ii];
193439    int nStr = (int)strlen(zStr);
193440    if( nInput>nStr && zInput[nStr]==':'
193441     && sqlite3_strnicmp(zStr, zInput, nStr)==0
193442    ){
193443      iCol = ii;
193444      iColLen = (int)((zInput - z) + nStr + 1);
193445      break;
193446    }
193447  }
193448  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
193449  *pnConsumed += iColLen;
193450  return rc;
193451}
193452
193453/*
193454** The argument is an Fts3Expr structure for a binary operator (any type
193455** except an FTSQUERY_PHRASE). Return an integer value representing the
193456** precedence of the operator. Lower values have a higher precedence (i.e.
193457** group more tightly). For example, in the C language, the == operator
193458** groups more tightly than ||, and would therefore have a higher precedence.
193459**
193460** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
193461** is defined), the order of the operators in precedence from highest to
193462** lowest is:
193463**
193464**   NEAR
193465**   NOT
193466**   AND (including implicit ANDs)
193467**   OR
193468**
193469** Note that when using the old query syntax, the OR operator has a higher
193470** precedence than the AND operator.
193471*/
193472static int opPrecedence(Fts3Expr *p){
193473  assert( p->eType!=FTSQUERY_PHRASE );
193474  if( sqlite3_fts3_enable_parentheses ){
193475    return p->eType;
193476  }else if( p->eType==FTSQUERY_NEAR ){
193477    return 1;
193478  }else if( p->eType==FTSQUERY_OR ){
193479    return 2;
193480  }
193481  assert( p->eType==FTSQUERY_AND );
193482  return 3;
193483}
193484
193485/*
193486** Argument ppHead contains a pointer to the current head of a query
193487** expression tree being parsed. pPrev is the expression node most recently
193488** inserted into the tree. This function adds pNew, which is always a binary
193489** operator node, into the expression tree based on the relative precedence
193490** of pNew and the existing nodes of the tree. This may result in the head
193491** of the tree changing, in which case *ppHead is set to the new root node.
193492*/
193493static void insertBinaryOperator(
193494  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
193495  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
193496  Fts3Expr *pNew           /* New binary node to insert into expression tree */
193497){
193498  Fts3Expr *pSplit = pPrev;
193499  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
193500    pSplit = pSplit->pParent;
193501  }
193502
193503  if( pSplit->pParent ){
193504    assert( pSplit->pParent->pRight==pSplit );
193505    pSplit->pParent->pRight = pNew;
193506    pNew->pParent = pSplit->pParent;
193507  }else{
193508    *ppHead = pNew;
193509  }
193510  pNew->pLeft = pSplit;
193511  pSplit->pParent = pNew;
193512}
193513
193514/*
193515** Parse the fts3 query expression found in buffer z, length n. This function
193516** returns either when the end of the buffer is reached or an unmatched
193517** closing bracket - ')' - is encountered.
193518**
193519** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
193520** parsed form of the expression and *pnConsumed is set to the number of
193521** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
193522** (out of memory error) or SQLITE_ERROR (parse error) is returned.
193523*/
193524static int fts3ExprParse(
193525  ParseContext *pParse,                   /* fts3 query parse context */
193526  const char *z, int n,                   /* Text of MATCH query */
193527  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
193528  int *pnConsumed                         /* OUT: Number of bytes consumed */
193529){
193530  Fts3Expr *pRet = 0;
193531  Fts3Expr *pPrev = 0;
193532  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
193533  int nIn = n;
193534  const char *zIn = z;
193535  int rc = SQLITE_OK;
193536  int isRequirePhrase = 1;
193537
193538  while( rc==SQLITE_OK ){
193539    Fts3Expr *p = 0;
193540    int nByte = 0;
193541
193542    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
193543    assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
193544    if( rc==SQLITE_OK ){
193545      if( p ){
193546        int isPhrase;
193547
193548        if( !sqlite3_fts3_enable_parentheses
193549            && p->eType==FTSQUERY_PHRASE && pParse->isNot
193550        ){
193551          /* Create an implicit NOT operator. */
193552          Fts3Expr *pNot = sqlite3Fts3MallocZero(sizeof(Fts3Expr));
193553          if( !pNot ){
193554            sqlite3Fts3ExprFree(p);
193555            rc = SQLITE_NOMEM;
193556            goto exprparse_out;
193557          }
193558          pNot->eType = FTSQUERY_NOT;
193559          pNot->pRight = p;
193560          p->pParent = pNot;
193561          if( pNotBranch ){
193562            pNot->pLeft = pNotBranch;
193563            pNotBranch->pParent = pNot;
193564          }
193565          pNotBranch = pNot;
193566          p = pPrev;
193567        }else{
193568          int eType = p->eType;
193569          isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
193570
193571          /* The isRequirePhrase variable is set to true if a phrase or
193572          ** an expression contained in parenthesis is required. If a
193573          ** binary operator (AND, OR, NOT or NEAR) is encounted when
193574          ** isRequirePhrase is set, this is a syntax error.
193575          */
193576          if( !isPhrase && isRequirePhrase ){
193577            sqlite3Fts3ExprFree(p);
193578            rc = SQLITE_ERROR;
193579            goto exprparse_out;
193580          }
193581
193582          if( isPhrase && !isRequirePhrase ){
193583            /* Insert an implicit AND operator. */
193584            Fts3Expr *pAnd;
193585            assert( pRet && pPrev );
193586            pAnd = sqlite3Fts3MallocZero(sizeof(Fts3Expr));
193587            if( !pAnd ){
193588              sqlite3Fts3ExprFree(p);
193589              rc = SQLITE_NOMEM;
193590              goto exprparse_out;
193591            }
193592            pAnd->eType = FTSQUERY_AND;
193593            insertBinaryOperator(&pRet, pPrev, pAnd);
193594            pPrev = pAnd;
193595          }
193596
193597          /* This test catches attempts to make either operand of a NEAR
193598           ** operator something other than a phrase. For example, either of
193599           ** the following:
193600           **
193601           **    (bracketed expression) NEAR phrase
193602           **    phrase NEAR (bracketed expression)
193603           **
193604           ** Return an error in either case.
193605           */
193606          if( pPrev && (
193607            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
193608         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
193609          )){
193610            sqlite3Fts3ExprFree(p);
193611            rc = SQLITE_ERROR;
193612            goto exprparse_out;
193613          }
193614
193615          if( isPhrase ){
193616            if( pRet ){
193617              assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
193618              pPrev->pRight = p;
193619              p->pParent = pPrev;
193620            }else{
193621              pRet = p;
193622            }
193623          }else{
193624            insertBinaryOperator(&pRet, pPrev, p);
193625          }
193626          isRequirePhrase = !isPhrase;
193627        }
193628        pPrev = p;
193629      }
193630      assert( nByte>0 );
193631    }
193632    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
193633    nIn -= nByte;
193634    zIn += nByte;
193635  }
193636
193637  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
193638    rc = SQLITE_ERROR;
193639  }
193640
193641  if( rc==SQLITE_DONE ){
193642    rc = SQLITE_OK;
193643    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
193644      if( !pRet ){
193645        rc = SQLITE_ERROR;
193646      }else{
193647        Fts3Expr *pIter = pNotBranch;
193648        while( pIter->pLeft ){
193649          pIter = pIter->pLeft;
193650        }
193651        pIter->pLeft = pRet;
193652        pRet->pParent = pIter;
193653        pRet = pNotBranch;
193654      }
193655    }
193656  }
193657  *pnConsumed = n - nIn;
193658
193659exprparse_out:
193660  if( rc!=SQLITE_OK ){
193661    sqlite3Fts3ExprFree(pRet);
193662    sqlite3Fts3ExprFree(pNotBranch);
193663    pRet = 0;
193664  }
193665  *ppExpr = pRet;
193666  return rc;
193667}
193668
193669/*
193670** Return SQLITE_ERROR if the maximum depth of the expression tree passed
193671** as the only argument is more than nMaxDepth.
193672*/
193673static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
193674  int rc = SQLITE_OK;
193675  if( p ){
193676    if( nMaxDepth<0 ){
193677      rc = SQLITE_TOOBIG;
193678    }else{
193679      rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
193680      if( rc==SQLITE_OK ){
193681        rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
193682      }
193683    }
193684  }
193685  return rc;
193686}
193687
193688/*
193689** This function attempts to transform the expression tree at (*pp) to
193690** an equivalent but more balanced form. The tree is modified in place.
193691** If successful, SQLITE_OK is returned and (*pp) set to point to the
193692** new root expression node.
193693**
193694** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
193695**
193696** Otherwise, if an error occurs, an SQLite error code is returned and
193697** expression (*pp) freed.
193698*/
193699static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
193700  int rc = SQLITE_OK;             /* Return code */
193701  Fts3Expr *pRoot = *pp;          /* Initial root node */
193702  Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
193703  int eType = pRoot->eType;       /* Type of node in this tree */
193704
193705  if( nMaxDepth==0 ){
193706    rc = SQLITE_ERROR;
193707  }
193708
193709  if( rc==SQLITE_OK ){
193710    if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
193711      Fts3Expr **apLeaf;
193712      apLeaf = (Fts3Expr **)sqlite3_malloc64(sizeof(Fts3Expr *) * nMaxDepth);
193713      if( 0==apLeaf ){
193714        rc = SQLITE_NOMEM;
193715      }else{
193716        memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
193717      }
193718
193719      if( rc==SQLITE_OK ){
193720        int i;
193721        Fts3Expr *p;
193722
193723        /* Set $p to point to the left-most leaf in the tree of eType nodes. */
193724        for(p=pRoot; p->eType==eType; p=p->pLeft){
193725          assert( p->pParent==0 || p->pParent->pLeft==p );
193726          assert( p->pLeft && p->pRight );
193727        }
193728
193729        /* This loop runs once for each leaf in the tree of eType nodes. */
193730        while( 1 ){
193731          int iLvl;
193732          Fts3Expr *pParent = p->pParent;     /* Current parent of p */
193733
193734          assert( pParent==0 || pParent->pLeft==p );
193735          p->pParent = 0;
193736          if( pParent ){
193737            pParent->pLeft = 0;
193738          }else{
193739            pRoot = 0;
193740          }
193741          rc = fts3ExprBalance(&p, nMaxDepth-1);
193742          if( rc!=SQLITE_OK ) break;
193743
193744          for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
193745            if( apLeaf[iLvl]==0 ){
193746              apLeaf[iLvl] = p;
193747              p = 0;
193748            }else{
193749              assert( pFree );
193750              pFree->pLeft = apLeaf[iLvl];
193751              pFree->pRight = p;
193752              pFree->pLeft->pParent = pFree;
193753              pFree->pRight->pParent = pFree;
193754
193755              p = pFree;
193756              pFree = pFree->pParent;
193757              p->pParent = 0;
193758              apLeaf[iLvl] = 0;
193759            }
193760          }
193761          if( p ){
193762            sqlite3Fts3ExprFree(p);
193763            rc = SQLITE_TOOBIG;
193764            break;
193765          }
193766
193767          /* If that was the last leaf node, break out of the loop */
193768          if( pParent==0 ) break;
193769
193770          /* Set $p to point to the next leaf in the tree of eType nodes */
193771          for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
193772
193773          /* Remove pParent from the original tree. */
193774          assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
193775          pParent->pRight->pParent = pParent->pParent;
193776          if( pParent->pParent ){
193777            pParent->pParent->pLeft = pParent->pRight;
193778          }else{
193779            assert( pParent==pRoot );
193780            pRoot = pParent->pRight;
193781          }
193782
193783          /* Link pParent into the free node list. It will be used as an
193784          ** internal node of the new tree.  */
193785          pParent->pParent = pFree;
193786          pFree = pParent;
193787        }
193788
193789        if( rc==SQLITE_OK ){
193790          p = 0;
193791          for(i=0; i<nMaxDepth; i++){
193792            if( apLeaf[i] ){
193793              if( p==0 ){
193794                p = apLeaf[i];
193795                p->pParent = 0;
193796              }else{
193797                assert( pFree!=0 );
193798                pFree->pRight = p;
193799                pFree->pLeft = apLeaf[i];
193800                pFree->pLeft->pParent = pFree;
193801                pFree->pRight->pParent = pFree;
193802
193803                p = pFree;
193804                pFree = pFree->pParent;
193805                p->pParent = 0;
193806              }
193807            }
193808          }
193809          pRoot = p;
193810        }else{
193811          /* An error occurred. Delete the contents of the apLeaf[] array
193812          ** and pFree list. Everything else is cleaned up by the call to
193813          ** sqlite3Fts3ExprFree(pRoot) below.  */
193814          Fts3Expr *pDel;
193815          for(i=0; i<nMaxDepth; i++){
193816            sqlite3Fts3ExprFree(apLeaf[i]);
193817          }
193818          while( (pDel=pFree)!=0 ){
193819            pFree = pDel->pParent;
193820            sqlite3_free(pDel);
193821          }
193822        }
193823
193824        assert( pFree==0 );
193825        sqlite3_free( apLeaf );
193826      }
193827    }else if( eType==FTSQUERY_NOT ){
193828      Fts3Expr *pLeft = pRoot->pLeft;
193829      Fts3Expr *pRight = pRoot->pRight;
193830
193831      pRoot->pLeft = 0;
193832      pRoot->pRight = 0;
193833      pLeft->pParent = 0;
193834      pRight->pParent = 0;
193835
193836      rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
193837      if( rc==SQLITE_OK ){
193838        rc = fts3ExprBalance(&pRight, nMaxDepth-1);
193839      }
193840
193841      if( rc!=SQLITE_OK ){
193842        sqlite3Fts3ExprFree(pRight);
193843        sqlite3Fts3ExprFree(pLeft);
193844      }else{
193845        assert( pLeft && pRight );
193846        pRoot->pLeft = pLeft;
193847        pLeft->pParent = pRoot;
193848        pRoot->pRight = pRight;
193849        pRight->pParent = pRoot;
193850      }
193851    }
193852  }
193853
193854  if( rc!=SQLITE_OK ){
193855    sqlite3Fts3ExprFree(pRoot);
193856    pRoot = 0;
193857  }
193858  *pp = pRoot;
193859  return rc;
193860}
193861
193862/*
193863** This function is similar to sqlite3Fts3ExprParse(), with the following
193864** differences:
193865**
193866**   1. It does not do expression rebalancing.
193867**   2. It does not check that the expression does not exceed the
193868**      maximum allowable depth.
193869**   3. Even if it fails, *ppExpr may still be set to point to an
193870**      expression tree. It should be deleted using sqlite3Fts3ExprFree()
193871**      in this case.
193872*/
193873static int fts3ExprParseUnbalanced(
193874  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
193875  int iLangid,                        /* Language id for tokenizer */
193876  char **azCol,                       /* Array of column names for fts3 table */
193877  int bFts4,                          /* True to allow FTS4-only syntax */
193878  int nCol,                           /* Number of entries in azCol[] */
193879  int iDefaultCol,                    /* Default column to query */
193880  const char *z, int n,               /* Text of MATCH query */
193881  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
193882){
193883  int nParsed;
193884  int rc;
193885  ParseContext sParse;
193886
193887  memset(&sParse, 0, sizeof(ParseContext));
193888  sParse.pTokenizer = pTokenizer;
193889  sParse.iLangid = iLangid;
193890  sParse.azCol = (const char **)azCol;
193891  sParse.nCol = nCol;
193892  sParse.iDefaultCol = iDefaultCol;
193893  sParse.bFts4 = bFts4;
193894  if( z==0 ){
193895    *ppExpr = 0;
193896    return SQLITE_OK;
193897  }
193898  if( n<0 ){
193899    n = (int)strlen(z);
193900  }
193901  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
193902  assert( rc==SQLITE_OK || *ppExpr==0 );
193903
193904  /* Check for mismatched parenthesis */
193905  if( rc==SQLITE_OK && sParse.nNest ){
193906    rc = SQLITE_ERROR;
193907  }
193908
193909  return rc;
193910}
193911
193912/*
193913** Parameters z and n contain a pointer to and length of a buffer containing
193914** an fts3 query expression, respectively. This function attempts to parse the
193915** query expression and create a tree of Fts3Expr structures representing the
193916** parsed expression. If successful, *ppExpr is set to point to the head
193917** of the parsed expression tree and SQLITE_OK is returned. If an error
193918** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
193919** error) is returned and *ppExpr is set to 0.
193920**
193921** If parameter n is a negative number, then z is assumed to point to a
193922** nul-terminated string and the length is determined using strlen().
193923**
193924** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
193925** use to normalize query tokens while parsing the expression. The azCol[]
193926** array, which is assumed to contain nCol entries, should contain the names
193927** of each column in the target fts3 table, in order from left to right.
193928** Column names must be nul-terminated strings.
193929**
193930** The iDefaultCol parameter should be passed the index of the table column
193931** that appears on the left-hand-side of the MATCH operator (the default
193932** column to match against for tokens for which a column name is not explicitly
193933** specified as part of the query string), or -1 if tokens may by default
193934** match any table column.
193935*/
193936SQLITE_PRIVATE int sqlite3Fts3ExprParse(
193937  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
193938  int iLangid,                        /* Language id for tokenizer */
193939  char **azCol,                       /* Array of column names for fts3 table */
193940  int bFts4,                          /* True to allow FTS4-only syntax */
193941  int nCol,                           /* Number of entries in azCol[] */
193942  int iDefaultCol,                    /* Default column to query */
193943  const char *z, int n,               /* Text of MATCH query */
193944  Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
193945  char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
193946){
193947  int rc = fts3ExprParseUnbalanced(
193948      pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
193949  );
193950
193951  /* Rebalance the expression. And check that its depth does not exceed
193952  ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
193953  if( rc==SQLITE_OK && *ppExpr ){
193954    rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
193955    if( rc==SQLITE_OK ){
193956      rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
193957    }
193958  }
193959
193960  if( rc!=SQLITE_OK ){
193961    sqlite3Fts3ExprFree(*ppExpr);
193962    *ppExpr = 0;
193963    if( rc==SQLITE_TOOBIG ){
193964      sqlite3Fts3ErrMsg(pzErr,
193965          "FTS expression tree is too large (maximum depth %d)",
193966          SQLITE_FTS3_MAX_EXPR_DEPTH
193967      );
193968      rc = SQLITE_ERROR;
193969    }else if( rc==SQLITE_ERROR ){
193970      sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
193971    }
193972  }
193973
193974  return rc;
193975}
193976
193977/*
193978** Free a single node of an expression tree.
193979*/
193980static void fts3FreeExprNode(Fts3Expr *p){
193981  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
193982  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
193983  sqlite3_free(p->aMI);
193984  sqlite3_free(p);
193985}
193986
193987/*
193988** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
193989**
193990** This function would be simpler if it recursively called itself. But
193991** that would mean passing a sufficiently large expression to ExprParse()
193992** could cause a stack overflow.
193993*/
193994SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
193995  Fts3Expr *p;
193996  assert( pDel==0 || pDel->pParent==0 );
193997  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
193998    assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
193999  }
194000  while( p ){
194001    Fts3Expr *pParent = p->pParent;
194002    fts3FreeExprNode(p);
194003    if( pParent && p==pParent->pLeft && pParent->pRight ){
194004      p = pParent->pRight;
194005      while( p && (p->pLeft || p->pRight) ){
194006        assert( p==p->pParent->pRight || p==p->pParent->pLeft );
194007        p = (p->pLeft ? p->pLeft : p->pRight);
194008      }
194009    }else{
194010      p = pParent;
194011    }
194012  }
194013}
194014
194015/****************************************************************************
194016*****************************************************************************
194017** Everything after this point is just test code.
194018*/
194019
194020#ifdef SQLITE_TEST
194021
194022/* #include <stdio.h> */
194023
194024/*
194025** Return a pointer to a buffer containing a text representation of the
194026** expression passed as the first argument. The buffer is obtained from
194027** sqlite3_malloc(). It is the responsibility of the caller to use
194028** sqlite3_free() to release the memory. If an OOM condition is encountered,
194029** NULL is returned.
194030**
194031** If the second argument is not NULL, then its contents are prepended to
194032** the returned expression text and then freed using sqlite3_free().
194033*/
194034static char *exprToString(Fts3Expr *pExpr, char *zBuf){
194035  if( pExpr==0 ){
194036    return sqlite3_mprintf("");
194037  }
194038  switch( pExpr->eType ){
194039    case FTSQUERY_PHRASE: {
194040      Fts3Phrase *pPhrase = pExpr->pPhrase;
194041      int i;
194042      zBuf = sqlite3_mprintf(
194043          "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
194044      for(i=0; zBuf && i<pPhrase->nToken; i++){
194045        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
194046            pPhrase->aToken[i].n, pPhrase->aToken[i].z,
194047            (pPhrase->aToken[i].isPrefix?"+":"")
194048        );
194049      }
194050      return zBuf;
194051    }
194052
194053    case FTSQUERY_NEAR:
194054      zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
194055      break;
194056    case FTSQUERY_NOT:
194057      zBuf = sqlite3_mprintf("%zNOT ", zBuf);
194058      break;
194059    case FTSQUERY_AND:
194060      zBuf = sqlite3_mprintf("%zAND ", zBuf);
194061      break;
194062    case FTSQUERY_OR:
194063      zBuf = sqlite3_mprintf("%zOR ", zBuf);
194064      break;
194065  }
194066
194067  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
194068  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
194069  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
194070
194071  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
194072  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
194073
194074  return zBuf;
194075}
194076
194077/*
194078** This is the implementation of a scalar SQL function used to test the
194079** expression parser. It should be called as follows:
194080**
194081**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
194082**
194083** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
194084** to parse the query expression (see README.tokenizers). The second argument
194085** is the query expression to parse. Each subsequent argument is the name
194086** of a column of the fts3 table that the query expression may refer to.
194087** For example:
194088**
194089**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
194090*/
194091static void fts3ExprTestCommon(
194092  int bRebalance,
194093  sqlite3_context *context,
194094  int argc,
194095  sqlite3_value **argv
194096){
194097  sqlite3_tokenizer *pTokenizer = 0;
194098  int rc;
194099  char **azCol = 0;
194100  const char *zExpr;
194101  int nExpr;
194102  int nCol;
194103  int ii;
194104  Fts3Expr *pExpr;
194105  char *zBuf = 0;
194106  Fts3Hash *pHash = (Fts3Hash*)sqlite3_user_data(context);
194107  const char *zTokenizer = 0;
194108  char *zErr = 0;
194109
194110  if( argc<3 ){
194111    sqlite3_result_error(context,
194112        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
194113    );
194114    return;
194115  }
194116
194117  zTokenizer = (const char*)sqlite3_value_text(argv[0]);
194118  rc = sqlite3Fts3InitTokenizer(pHash, zTokenizer, &pTokenizer, &zErr);
194119  if( rc!=SQLITE_OK ){
194120    if( rc==SQLITE_NOMEM ){
194121      sqlite3_result_error_nomem(context);
194122    }else{
194123      sqlite3_result_error(context, zErr, -1);
194124    }
194125    sqlite3_free(zErr);
194126    return;
194127  }
194128
194129  zExpr = (const char *)sqlite3_value_text(argv[1]);
194130  nExpr = sqlite3_value_bytes(argv[1]);
194131  nCol = argc-2;
194132  azCol = (char **)sqlite3_malloc64(nCol*sizeof(char *));
194133  if( !azCol ){
194134    sqlite3_result_error_nomem(context);
194135    goto exprtest_out;
194136  }
194137  for(ii=0; ii<nCol; ii++){
194138    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
194139  }
194140
194141  if( bRebalance ){
194142    char *zDummy = 0;
194143    rc = sqlite3Fts3ExprParse(
194144        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
194145    );
194146    assert( rc==SQLITE_OK || pExpr==0 );
194147    sqlite3_free(zDummy);
194148  }else{
194149    rc = fts3ExprParseUnbalanced(
194150        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
194151    );
194152  }
194153
194154  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
194155    sqlite3Fts3ExprFree(pExpr);
194156    sqlite3_result_error(context, "Error parsing expression", -1);
194157  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
194158    sqlite3_result_error_nomem(context);
194159  }else{
194160    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
194161    sqlite3_free(zBuf);
194162  }
194163
194164  sqlite3Fts3ExprFree(pExpr);
194165
194166exprtest_out:
194167  if( pTokenizer ){
194168    rc = pTokenizer->pModule->xDestroy(pTokenizer);
194169  }
194170  sqlite3_free(azCol);
194171}
194172
194173static void fts3ExprTest(
194174  sqlite3_context *context,
194175  int argc,
194176  sqlite3_value **argv
194177){
194178  fts3ExprTestCommon(0, context, argc, argv);
194179}
194180static void fts3ExprTestRebalance(
194181  sqlite3_context *context,
194182  int argc,
194183  sqlite3_value **argv
194184){
194185  fts3ExprTestCommon(1, context, argc, argv);
194186}
194187
194188/*
194189** Register the query expression parser test function fts3_exprtest()
194190** with database connection db.
194191*/
194192SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){
194193  int rc = sqlite3_create_function(
194194      db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0
194195  );
194196  if( rc==SQLITE_OK ){
194197    rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
194198        -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0
194199    );
194200  }
194201  return rc;
194202}
194203
194204#endif
194205#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
194206
194207/************** End of fts3_expr.c *******************************************/
194208/************** Begin file fts3_hash.c ***************************************/
194209/*
194210** 2001 September 22
194211**
194212** The author disclaims copyright to this source code.  In place of
194213** a legal notice, here is a blessing:
194214**
194215**    May you do good and not evil.
194216**    May you find forgiveness for yourself and forgive others.
194217**    May you share freely, never taking more than you give.
194218**
194219*************************************************************************
194220** This is the implementation of generic hash-tables used in SQLite.
194221** We've modified it slightly to serve as a standalone hash table
194222** implementation for the full-text indexing module.
194223*/
194224
194225/*
194226** The code in this file is only compiled if:
194227**
194228**     * The FTS3 module is being built as an extension
194229**       (in which case SQLITE_CORE is not defined), or
194230**
194231**     * The FTS3 module is being built into the core of
194232**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
194233*/
194234/* #include "fts3Int.h" */
194235#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
194236
194237/* #include <assert.h> */
194238/* #include <stdlib.h> */
194239/* #include <string.h> */
194240
194241/* #include "fts3_hash.h" */
194242
194243/*
194244** Malloc and Free functions
194245*/
194246static void *fts3HashMalloc(sqlite3_int64 n){
194247  void *p = sqlite3_malloc64(n);
194248  if( p ){
194249    memset(p, 0, n);
194250  }
194251  return p;
194252}
194253static void fts3HashFree(void *p){
194254  sqlite3_free(p);
194255}
194256
194257/* Turn bulk memory into a hash table object by initializing the
194258** fields of the Hash structure.
194259**
194260** "pNew" is a pointer to the hash table that is to be initialized.
194261** keyClass is one of the constants
194262** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
194263** determines what kind of key the hash table will use.  "copyKey" is
194264** true if the hash table should make its own private copy of keys and
194265** false if it should just use the supplied pointer.
194266*/
194267SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
194268  assert( pNew!=0 );
194269  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
194270  pNew->keyClass = keyClass;
194271  pNew->copyKey = copyKey;
194272  pNew->first = 0;
194273  pNew->count = 0;
194274  pNew->htsize = 0;
194275  pNew->ht = 0;
194276}
194277
194278/* Remove all entries from a hash table.  Reclaim all memory.
194279** Call this routine to delete a hash table or to reset a hash table
194280** to the empty state.
194281*/
194282SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
194283  Fts3HashElem *elem;         /* For looping over all elements of the table */
194284
194285  assert( pH!=0 );
194286  elem = pH->first;
194287  pH->first = 0;
194288  fts3HashFree(pH->ht);
194289  pH->ht = 0;
194290  pH->htsize = 0;
194291  while( elem ){
194292    Fts3HashElem *next_elem = elem->next;
194293    if( pH->copyKey && elem->pKey ){
194294      fts3HashFree(elem->pKey);
194295    }
194296    fts3HashFree(elem);
194297    elem = next_elem;
194298  }
194299  pH->count = 0;
194300}
194301
194302/*
194303** Hash and comparison functions when the mode is FTS3_HASH_STRING
194304*/
194305static int fts3StrHash(const void *pKey, int nKey){
194306  const char *z = (const char *)pKey;
194307  unsigned h = 0;
194308  if( nKey<=0 ) nKey = (int) strlen(z);
194309  while( nKey > 0  ){
194310    h = (h<<3) ^ h ^ *z++;
194311    nKey--;
194312  }
194313  return (int)(h & 0x7fffffff);
194314}
194315static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
194316  if( n1!=n2 ) return 1;
194317  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
194318}
194319
194320/*
194321** Hash and comparison functions when the mode is FTS3_HASH_BINARY
194322*/
194323static int fts3BinHash(const void *pKey, int nKey){
194324  int h = 0;
194325  const char *z = (const char *)pKey;
194326  while( nKey-- > 0 ){
194327    h = (h<<3) ^ h ^ *(z++);
194328  }
194329  return h & 0x7fffffff;
194330}
194331static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
194332  if( n1!=n2 ) return 1;
194333  return memcmp(pKey1,pKey2,n1);
194334}
194335
194336/*
194337** Return a pointer to the appropriate hash function given the key class.
194338**
194339** The C syntax in this function definition may be unfamilar to some
194340** programmers, so we provide the following additional explanation:
194341**
194342** The name of the function is "ftsHashFunction".  The function takes a
194343** single parameter "keyClass".  The return value of ftsHashFunction()
194344** is a pointer to another function.  Specifically, the return value
194345** of ftsHashFunction() is a pointer to a function that takes two parameters
194346** with types "const void*" and "int" and returns an "int".
194347*/
194348static int (*ftsHashFunction(int keyClass))(const void*,int){
194349  if( keyClass==FTS3_HASH_STRING ){
194350    return &fts3StrHash;
194351  }else{
194352    assert( keyClass==FTS3_HASH_BINARY );
194353    return &fts3BinHash;
194354  }
194355}
194356
194357/*
194358** Return a pointer to the appropriate hash function given the key class.
194359**
194360** For help in interpreted the obscure C code in the function definition,
194361** see the header comment on the previous function.
194362*/
194363static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
194364  if( keyClass==FTS3_HASH_STRING ){
194365    return &fts3StrCompare;
194366  }else{
194367    assert( keyClass==FTS3_HASH_BINARY );
194368    return &fts3BinCompare;
194369  }
194370}
194371
194372/* Link an element into the hash table
194373*/
194374static void fts3HashInsertElement(
194375  Fts3Hash *pH,            /* The complete hash table */
194376  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
194377  Fts3HashElem *pNew       /* The element to be inserted */
194378){
194379  Fts3HashElem *pHead;     /* First element already in pEntry */
194380  pHead = pEntry->chain;
194381  if( pHead ){
194382    pNew->next = pHead;
194383    pNew->prev = pHead->prev;
194384    if( pHead->prev ){ pHead->prev->next = pNew; }
194385    else             { pH->first = pNew; }
194386    pHead->prev = pNew;
194387  }else{
194388    pNew->next = pH->first;
194389    if( pH->first ){ pH->first->prev = pNew; }
194390    pNew->prev = 0;
194391    pH->first = pNew;
194392  }
194393  pEntry->count++;
194394  pEntry->chain = pNew;
194395}
194396
194397
194398/* Resize the hash table so that it cantains "new_size" buckets.
194399** "new_size" must be a power of 2.  The hash table might fail
194400** to resize if sqliteMalloc() fails.
194401**
194402** Return non-zero if a memory allocation error occurs.
194403*/
194404static int fts3Rehash(Fts3Hash *pH, int new_size){
194405  struct _fts3ht *new_ht;          /* The new hash table */
194406  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
194407  int (*xHash)(const void*,int);   /* The hash function */
194408
194409  assert( (new_size & (new_size-1))==0 );
194410  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
194411  if( new_ht==0 ) return 1;
194412  fts3HashFree(pH->ht);
194413  pH->ht = new_ht;
194414  pH->htsize = new_size;
194415  xHash = ftsHashFunction(pH->keyClass);
194416  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
194417    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
194418    next_elem = elem->next;
194419    fts3HashInsertElement(pH, &new_ht[h], elem);
194420  }
194421  return 0;
194422}
194423
194424/* This function (for internal use only) locates an element in an
194425** hash table that matches the given key.  The hash for this key has
194426** already been computed and is passed as the 4th parameter.
194427*/
194428static Fts3HashElem *fts3FindElementByHash(
194429  const Fts3Hash *pH, /* The pH to be searched */
194430  const void *pKey,   /* The key we are searching for */
194431  int nKey,
194432  int h               /* The hash for this key. */
194433){
194434  Fts3HashElem *elem;            /* Used to loop thru the element list */
194435  int count;                     /* Number of elements left to test */
194436  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
194437
194438  if( pH->ht ){
194439    struct _fts3ht *pEntry = &pH->ht[h];
194440    elem = pEntry->chain;
194441    count = pEntry->count;
194442    xCompare = ftsCompareFunction(pH->keyClass);
194443    while( count-- && elem ){
194444      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
194445        return elem;
194446      }
194447      elem = elem->next;
194448    }
194449  }
194450  return 0;
194451}
194452
194453/* Remove a single entry from the hash table given a pointer to that
194454** element and a hash on the element's key.
194455*/
194456static void fts3RemoveElementByHash(
194457  Fts3Hash *pH,         /* The pH containing "elem" */
194458  Fts3HashElem* elem,   /* The element to be removed from the pH */
194459  int h                 /* Hash value for the element */
194460){
194461  struct _fts3ht *pEntry;
194462  if( elem->prev ){
194463    elem->prev->next = elem->next;
194464  }else{
194465    pH->first = elem->next;
194466  }
194467  if( elem->next ){
194468    elem->next->prev = elem->prev;
194469  }
194470  pEntry = &pH->ht[h];
194471  if( pEntry->chain==elem ){
194472    pEntry->chain = elem->next;
194473  }
194474  pEntry->count--;
194475  if( pEntry->count<=0 ){
194476    pEntry->chain = 0;
194477  }
194478  if( pH->copyKey && elem->pKey ){
194479    fts3HashFree(elem->pKey);
194480  }
194481  fts3HashFree( elem );
194482  pH->count--;
194483  if( pH->count<=0 ){
194484    assert( pH->first==0 );
194485    assert( pH->count==0 );
194486    fts3HashClear(pH);
194487  }
194488}
194489
194490SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
194491  const Fts3Hash *pH,
194492  const void *pKey,
194493  int nKey
194494){
194495  int h;                          /* A hash on key */
194496  int (*xHash)(const void*,int);  /* The hash function */
194497
194498  if( pH==0 || pH->ht==0 ) return 0;
194499  xHash = ftsHashFunction(pH->keyClass);
194500  assert( xHash!=0 );
194501  h = (*xHash)(pKey,nKey);
194502  assert( (pH->htsize & (pH->htsize-1))==0 );
194503  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
194504}
194505
194506/*
194507** Attempt to locate an element of the hash table pH with a key
194508** that matches pKey,nKey.  Return the data for this element if it is
194509** found, or NULL if there is no match.
194510*/
194511SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
194512  Fts3HashElem *pElem;            /* The element that matches key (if any) */
194513
194514  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
194515  return pElem ? pElem->data : 0;
194516}
194517
194518/* Insert an element into the hash table pH.  The key is pKey,nKey
194519** and the data is "data".
194520**
194521** If no element exists with a matching key, then a new
194522** element is created.  A copy of the key is made if the copyKey
194523** flag is set.  NULL is returned.
194524**
194525** If another element already exists with the same key, then the
194526** new data replaces the old data and the old data is returned.
194527** The key is not copied in this instance.  If a malloc fails, then
194528** the new data is returned and the hash table is unchanged.
194529**
194530** If the "data" parameter to this function is NULL, then the
194531** element corresponding to "key" is removed from the hash table.
194532*/
194533SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
194534  Fts3Hash *pH,        /* The hash table to insert into */
194535  const void *pKey,    /* The key */
194536  int nKey,            /* Number of bytes in the key */
194537  void *data           /* The data */
194538){
194539  int hraw;                 /* Raw hash value of the key */
194540  int h;                    /* the hash of the key modulo hash table size */
194541  Fts3HashElem *elem;       /* Used to loop thru the element list */
194542  Fts3HashElem *new_elem;   /* New element added to the pH */
194543  int (*xHash)(const void*,int);  /* The hash function */
194544
194545  assert( pH!=0 );
194546  xHash = ftsHashFunction(pH->keyClass);
194547  assert( xHash!=0 );
194548  hraw = (*xHash)(pKey, nKey);
194549  assert( (pH->htsize & (pH->htsize-1))==0 );
194550  h = hraw & (pH->htsize-1);
194551  elem = fts3FindElementByHash(pH,pKey,nKey,h);
194552  if( elem ){
194553    void *old_data = elem->data;
194554    if( data==0 ){
194555      fts3RemoveElementByHash(pH,elem,h);
194556    }else{
194557      elem->data = data;
194558    }
194559    return old_data;
194560  }
194561  if( data==0 ) return 0;
194562  if( (pH->htsize==0 && fts3Rehash(pH,8))
194563   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
194564  ){
194565    pH->count = 0;
194566    return data;
194567  }
194568  assert( pH->htsize>0 );
194569  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
194570  if( new_elem==0 ) return data;
194571  if( pH->copyKey && pKey!=0 ){
194572    new_elem->pKey = fts3HashMalloc( nKey );
194573    if( new_elem->pKey==0 ){
194574      fts3HashFree(new_elem);
194575      return data;
194576    }
194577    memcpy((void*)new_elem->pKey, pKey, nKey);
194578  }else{
194579    new_elem->pKey = (void*)pKey;
194580  }
194581  new_elem->nKey = nKey;
194582  pH->count++;
194583  assert( pH->htsize>0 );
194584  assert( (pH->htsize & (pH->htsize-1))==0 );
194585  h = hraw & (pH->htsize-1);
194586  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
194587  new_elem->data = data;
194588  return 0;
194589}
194590
194591#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
194592
194593/************** End of fts3_hash.c *******************************************/
194594/************** Begin file fts3_porter.c *************************************/
194595/*
194596** 2006 September 30
194597**
194598** The author disclaims copyright to this source code.  In place of
194599** a legal notice, here is a blessing:
194600**
194601**    May you do good and not evil.
194602**    May you find forgiveness for yourself and forgive others.
194603**    May you share freely, never taking more than you give.
194604**
194605*************************************************************************
194606** Implementation of the full-text-search tokenizer that implements
194607** a Porter stemmer.
194608*/
194609
194610/*
194611** The code in this file is only compiled if:
194612**
194613**     * The FTS3 module is being built as an extension
194614**       (in which case SQLITE_CORE is not defined), or
194615**
194616**     * The FTS3 module is being built into the core of
194617**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
194618*/
194619/* #include "fts3Int.h" */
194620#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
194621
194622/* #include <assert.h> */
194623/* #include <stdlib.h> */
194624/* #include <stdio.h> */
194625/* #include <string.h> */
194626
194627/* #include "fts3_tokenizer.h" */
194628
194629/*
194630** Class derived from sqlite3_tokenizer
194631*/
194632typedef struct porter_tokenizer {
194633  sqlite3_tokenizer base;      /* Base class */
194634} porter_tokenizer;
194635
194636/*
194637** Class derived from sqlite3_tokenizer_cursor
194638*/
194639typedef struct porter_tokenizer_cursor {
194640  sqlite3_tokenizer_cursor base;
194641  const char *zInput;          /* input we are tokenizing */
194642  int nInput;                  /* size of the input */
194643  int iOffset;                 /* current position in zInput */
194644  int iToken;                  /* index of next token to be returned */
194645  char *zToken;                /* storage for current token */
194646  int nAllocated;              /* space allocated to zToken buffer */
194647} porter_tokenizer_cursor;
194648
194649
194650/*
194651** Create a new tokenizer instance.
194652*/
194653static int porterCreate(
194654  int argc, const char * const *argv,
194655  sqlite3_tokenizer **ppTokenizer
194656){
194657  porter_tokenizer *t;
194658
194659  UNUSED_PARAMETER(argc);
194660  UNUSED_PARAMETER(argv);
194661
194662  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
194663  if( t==NULL ) return SQLITE_NOMEM;
194664  memset(t, 0, sizeof(*t));
194665  *ppTokenizer = &t->base;
194666  return SQLITE_OK;
194667}
194668
194669/*
194670** Destroy a tokenizer
194671*/
194672static int porterDestroy(sqlite3_tokenizer *pTokenizer){
194673  sqlite3_free(pTokenizer);
194674  return SQLITE_OK;
194675}
194676
194677/*
194678** Prepare to begin tokenizing a particular string.  The input
194679** string to be tokenized is zInput[0..nInput-1].  A cursor
194680** used to incrementally tokenize this string is returned in
194681** *ppCursor.
194682*/
194683static int porterOpen(
194684  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
194685  const char *zInput, int nInput,        /* String to be tokenized */
194686  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
194687){
194688  porter_tokenizer_cursor *c;
194689
194690  UNUSED_PARAMETER(pTokenizer);
194691
194692  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
194693  if( c==NULL ) return SQLITE_NOMEM;
194694
194695  c->zInput = zInput;
194696  if( zInput==0 ){
194697    c->nInput = 0;
194698  }else if( nInput<0 ){
194699    c->nInput = (int)strlen(zInput);
194700  }else{
194701    c->nInput = nInput;
194702  }
194703  c->iOffset = 0;                 /* start tokenizing at the beginning */
194704  c->iToken = 0;
194705  c->zToken = NULL;               /* no space allocated, yet. */
194706  c->nAllocated = 0;
194707
194708  *ppCursor = &c->base;
194709  return SQLITE_OK;
194710}
194711
194712/*
194713** Close a tokenization cursor previously opened by a call to
194714** porterOpen() above.
194715*/
194716static int porterClose(sqlite3_tokenizer_cursor *pCursor){
194717  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
194718  sqlite3_free(c->zToken);
194719  sqlite3_free(c);
194720  return SQLITE_OK;
194721}
194722/*
194723** Vowel or consonant
194724*/
194725static const char cType[] = {
194726   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
194727   1, 1, 1, 2, 1
194728};
194729
194730/*
194731** isConsonant() and isVowel() determine if their first character in
194732** the string they point to is a consonant or a vowel, according
194733** to Porter ruls.
194734**
194735** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
194736** 'Y' is a consonant unless it follows another consonant,
194737** in which case it is a vowel.
194738**
194739** In these routine, the letters are in reverse order.  So the 'y' rule
194740** is that 'y' is a consonant unless it is followed by another
194741** consonent.
194742*/
194743static int isVowel(const char*);
194744static int isConsonant(const char *z){
194745  int j;
194746  char x = *z;
194747  if( x==0 ) return 0;
194748  assert( x>='a' && x<='z' );
194749  j = cType[x-'a'];
194750  if( j<2 ) return j;
194751  return z[1]==0 || isVowel(z + 1);
194752}
194753static int isVowel(const char *z){
194754  int j;
194755  char x = *z;
194756  if( x==0 ) return 0;
194757  assert( x>='a' && x<='z' );
194758  j = cType[x-'a'];
194759  if( j<2 ) return 1-j;
194760  return isConsonant(z + 1);
194761}
194762
194763/*
194764** Let any sequence of one or more vowels be represented by V and let
194765** C be sequence of one or more consonants.  Then every word can be
194766** represented as:
194767**
194768**           [C] (VC){m} [V]
194769**
194770** In prose:  A word is an optional consonant followed by zero or
194771** vowel-consonant pairs followed by an optional vowel.  "m" is the
194772** number of vowel consonant pairs.  This routine computes the value
194773** of m for the first i bytes of a word.
194774**
194775** Return true if the m-value for z is 1 or more.  In other words,
194776** return true if z contains at least one vowel that is followed
194777** by a consonant.
194778**
194779** In this routine z[] is in reverse order.  So we are really looking
194780** for an instance of a consonant followed by a vowel.
194781*/
194782static int m_gt_0(const char *z){
194783  while( isVowel(z) ){ z++; }
194784  if( *z==0 ) return 0;
194785  while( isConsonant(z) ){ z++; }
194786  return *z!=0;
194787}
194788
194789/* Like mgt0 above except we are looking for a value of m which is
194790** exactly 1
194791*/
194792static int m_eq_1(const char *z){
194793  while( isVowel(z) ){ z++; }
194794  if( *z==0 ) return 0;
194795  while( isConsonant(z) ){ z++; }
194796  if( *z==0 ) return 0;
194797  while( isVowel(z) ){ z++; }
194798  if( *z==0 ) return 1;
194799  while( isConsonant(z) ){ z++; }
194800  return *z==0;
194801}
194802
194803/* Like mgt0 above except we are looking for a value of m>1 instead
194804** or m>0
194805*/
194806static int m_gt_1(const char *z){
194807  while( isVowel(z) ){ z++; }
194808  if( *z==0 ) return 0;
194809  while( isConsonant(z) ){ z++; }
194810  if( *z==0 ) return 0;
194811  while( isVowel(z) ){ z++; }
194812  if( *z==0 ) return 0;
194813  while( isConsonant(z) ){ z++; }
194814  return *z!=0;
194815}
194816
194817/*
194818** Return TRUE if there is a vowel anywhere within z[0..n-1]
194819*/
194820static int hasVowel(const char *z){
194821  while( isConsonant(z) ){ z++; }
194822  return *z!=0;
194823}
194824
194825/*
194826** Return TRUE if the word ends in a double consonant.
194827**
194828** The text is reversed here. So we are really looking at
194829** the first two characters of z[].
194830*/
194831static int doubleConsonant(const char *z){
194832  return isConsonant(z) && z[0]==z[1];
194833}
194834
194835/*
194836** Return TRUE if the word ends with three letters which
194837** are consonant-vowel-consonent and where the final consonant
194838** is not 'w', 'x', or 'y'.
194839**
194840** The word is reversed here.  So we are really checking the
194841** first three letters and the first one cannot be in [wxy].
194842*/
194843static int star_oh(const char *z){
194844  return
194845    isConsonant(z) &&
194846    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
194847    isVowel(z+1) &&
194848    isConsonant(z+2);
194849}
194850
194851/*
194852** If the word ends with zFrom and xCond() is true for the stem
194853** of the word that preceeds the zFrom ending, then change the
194854** ending to zTo.
194855**
194856** The input word *pz and zFrom are both in reverse order.  zTo
194857** is in normal order.
194858**
194859** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
194860** match.  Not that TRUE is returned even if xCond() fails and
194861** no substitution occurs.
194862*/
194863static int stem(
194864  char **pz,             /* The word being stemmed (Reversed) */
194865  const char *zFrom,     /* If the ending matches this... (Reversed) */
194866  const char *zTo,       /* ... change the ending to this (not reversed) */
194867  int (*xCond)(const char*)   /* Condition that must be true */
194868){
194869  char *z = *pz;
194870  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
194871  if( *zFrom!=0 ) return 0;
194872  if( xCond && !xCond(z) ) return 1;
194873  while( *zTo ){
194874    *(--z) = *(zTo++);
194875  }
194876  *pz = z;
194877  return 1;
194878}
194879
194880/*
194881** This is the fallback stemmer used when the porter stemmer is
194882** inappropriate.  The input word is copied into the output with
194883** US-ASCII case folding.  If the input word is too long (more
194884** than 20 bytes if it contains no digits or more than 6 bytes if
194885** it contains digits) then word is truncated to 20 or 6 bytes
194886** by taking 10 or 3 bytes from the beginning and end.
194887*/
194888static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
194889  int i, mx, j;
194890  int hasDigit = 0;
194891  for(i=0; i<nIn; i++){
194892    char c = zIn[i];
194893    if( c>='A' && c<='Z' ){
194894      zOut[i] = c - 'A' + 'a';
194895    }else{
194896      if( c>='0' && c<='9' ) hasDigit = 1;
194897      zOut[i] = c;
194898    }
194899  }
194900  mx = hasDigit ? 3 : 10;
194901  if( nIn>mx*2 ){
194902    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
194903      zOut[j] = zOut[i];
194904    }
194905    i = j;
194906  }
194907  zOut[i] = 0;
194908  *pnOut = i;
194909}
194910
194911
194912/*
194913** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
194914** zOut is at least big enough to hold nIn bytes.  Write the actual
194915** size of the output word (exclusive of the '\0' terminator) into *pnOut.
194916**
194917** Any upper-case characters in the US-ASCII character set ([A-Z])
194918** are converted to lower case.  Upper-case UTF characters are
194919** unchanged.
194920**
194921** Words that are longer than about 20 bytes are stemmed by retaining
194922** a few bytes from the beginning and the end of the word.  If the
194923** word contains digits, 3 bytes are taken from the beginning and
194924** 3 bytes from the end.  For long words without digits, 10 bytes
194925** are taken from each end.  US-ASCII case folding still applies.
194926**
194927** If the input word contains not digits but does characters not
194928** in [a-zA-Z] then no stemming is attempted and this routine just
194929** copies the input into the input into the output with US-ASCII
194930** case folding.
194931**
194932** Stemming never increases the length of the word.  So there is
194933** no chance of overflowing the zOut buffer.
194934*/
194935static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
194936  int i, j;
194937  char zReverse[28];
194938  char *z, *z2;
194939  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
194940    /* The word is too big or too small for the porter stemmer.
194941    ** Fallback to the copy stemmer */
194942    copy_stemmer(zIn, nIn, zOut, pnOut);
194943    return;
194944  }
194945  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
194946    char c = zIn[i];
194947    if( c>='A' && c<='Z' ){
194948      zReverse[j] = c + 'a' - 'A';
194949    }else if( c>='a' && c<='z' ){
194950      zReverse[j] = c;
194951    }else{
194952      /* The use of a character not in [a-zA-Z] means that we fallback
194953      ** to the copy stemmer */
194954      copy_stemmer(zIn, nIn, zOut, pnOut);
194955      return;
194956    }
194957  }
194958  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
194959  z = &zReverse[j+1];
194960
194961
194962  /* Step 1a */
194963  if( z[0]=='s' ){
194964    if(
194965     !stem(&z, "sess", "ss", 0) &&
194966     !stem(&z, "sei", "i", 0)  &&
194967     !stem(&z, "ss", "ss", 0)
194968    ){
194969      z++;
194970    }
194971  }
194972
194973  /* Step 1b */
194974  z2 = z;
194975  if( stem(&z, "dee", "ee", m_gt_0) ){
194976    /* Do nothing.  The work was all in the test */
194977  }else if(
194978     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
194979      && z!=z2
194980  ){
194981     if( stem(&z, "ta", "ate", 0) ||
194982         stem(&z, "lb", "ble", 0) ||
194983         stem(&z, "zi", "ize", 0) ){
194984       /* Do nothing.  The work was all in the test */
194985     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
194986       z++;
194987     }else if( m_eq_1(z) && star_oh(z) ){
194988       *(--z) = 'e';
194989     }
194990  }
194991
194992  /* Step 1c */
194993  if( z[0]=='y' && hasVowel(z+1) ){
194994    z[0] = 'i';
194995  }
194996
194997  /* Step 2 */
194998  switch( z[1] ){
194999   case 'a':
195000     if( !stem(&z, "lanoita", "ate", m_gt_0) ){
195001       stem(&z, "lanoit", "tion", m_gt_0);
195002     }
195003     break;
195004   case 'c':
195005     if( !stem(&z, "icne", "ence", m_gt_0) ){
195006       stem(&z, "icna", "ance", m_gt_0);
195007     }
195008     break;
195009   case 'e':
195010     stem(&z, "rezi", "ize", m_gt_0);
195011     break;
195012   case 'g':
195013     stem(&z, "igol", "log", m_gt_0);
195014     break;
195015   case 'l':
195016     if( !stem(&z, "ilb", "ble", m_gt_0)
195017      && !stem(&z, "illa", "al", m_gt_0)
195018      && !stem(&z, "iltne", "ent", m_gt_0)
195019      && !stem(&z, "ile", "e", m_gt_0)
195020     ){
195021       stem(&z, "ilsuo", "ous", m_gt_0);
195022     }
195023     break;
195024   case 'o':
195025     if( !stem(&z, "noitazi", "ize", m_gt_0)
195026      && !stem(&z, "noita", "ate", m_gt_0)
195027     ){
195028       stem(&z, "rota", "ate", m_gt_0);
195029     }
195030     break;
195031   case 's':
195032     if( !stem(&z, "msila", "al", m_gt_0)
195033      && !stem(&z, "ssenevi", "ive", m_gt_0)
195034      && !stem(&z, "ssenluf", "ful", m_gt_0)
195035     ){
195036       stem(&z, "ssensuo", "ous", m_gt_0);
195037     }
195038     break;
195039   case 't':
195040     if( !stem(&z, "itila", "al", m_gt_0)
195041      && !stem(&z, "itivi", "ive", m_gt_0)
195042     ){
195043       stem(&z, "itilib", "ble", m_gt_0);
195044     }
195045     break;
195046  }
195047
195048  /* Step 3 */
195049  switch( z[0] ){
195050   case 'e':
195051     if( !stem(&z, "etaci", "ic", m_gt_0)
195052      && !stem(&z, "evita", "", m_gt_0)
195053     ){
195054       stem(&z, "ezila", "al", m_gt_0);
195055     }
195056     break;
195057   case 'i':
195058     stem(&z, "itici", "ic", m_gt_0);
195059     break;
195060   case 'l':
195061     if( !stem(&z, "laci", "ic", m_gt_0) ){
195062       stem(&z, "luf", "", m_gt_0);
195063     }
195064     break;
195065   case 's':
195066     stem(&z, "ssen", "", m_gt_0);
195067     break;
195068  }
195069
195070  /* Step 4 */
195071  switch( z[1] ){
195072   case 'a':
195073     if( z[0]=='l' && m_gt_1(z+2) ){
195074       z += 2;
195075     }
195076     break;
195077   case 'c':
195078     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
195079       z += 4;
195080     }
195081     break;
195082   case 'e':
195083     if( z[0]=='r' && m_gt_1(z+2) ){
195084       z += 2;
195085     }
195086     break;
195087   case 'i':
195088     if( z[0]=='c' && m_gt_1(z+2) ){
195089       z += 2;
195090     }
195091     break;
195092   case 'l':
195093     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
195094       z += 4;
195095     }
195096     break;
195097   case 'n':
195098     if( z[0]=='t' ){
195099       if( z[2]=='a' ){
195100         if( m_gt_1(z+3) ){
195101           z += 3;
195102         }
195103       }else if( z[2]=='e' ){
195104         if( !stem(&z, "tneme", "", m_gt_1)
195105          && !stem(&z, "tnem", "", m_gt_1)
195106         ){
195107           stem(&z, "tne", "", m_gt_1);
195108         }
195109       }
195110     }
195111     break;
195112   case 'o':
195113     if( z[0]=='u' ){
195114       if( m_gt_1(z+2) ){
195115         z += 2;
195116       }
195117     }else if( z[3]=='s' || z[3]=='t' ){
195118       stem(&z, "noi", "", m_gt_1);
195119     }
195120     break;
195121   case 's':
195122     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
195123       z += 3;
195124     }
195125     break;
195126   case 't':
195127     if( !stem(&z, "eta", "", m_gt_1) ){
195128       stem(&z, "iti", "", m_gt_1);
195129     }
195130     break;
195131   case 'u':
195132     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
195133       z += 3;
195134     }
195135     break;
195136   case 'v':
195137   case 'z':
195138     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
195139       z += 3;
195140     }
195141     break;
195142  }
195143
195144  /* Step 5a */
195145  if( z[0]=='e' ){
195146    if( m_gt_1(z+1) ){
195147      z++;
195148    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
195149      z++;
195150    }
195151  }
195152
195153  /* Step 5b */
195154  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
195155    z++;
195156  }
195157
195158  /* z[] is now the stemmed word in reverse order.  Flip it back
195159  ** around into forward order and return.
195160  */
195161  *pnOut = i = (int)strlen(z);
195162  zOut[i] = 0;
195163  while( *z ){
195164    zOut[--i] = *(z++);
195165  }
195166}
195167
195168/*
195169** Characters that can be part of a token.  We assume any character
195170** whose value is greater than 0x80 (any UTF character) can be
195171** part of a token.  In other words, delimiters all must have
195172** values of 0x7f or lower.
195173*/
195174static const char porterIdChar[] = {
195175/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
195176    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
195177    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
195178    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
195179    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
195180    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
195181};
195182#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
195183
195184/*
195185** Extract the next token from a tokenization cursor.  The cursor must
195186** have been opened by a prior call to porterOpen().
195187*/
195188static int porterNext(
195189  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
195190  const char **pzToken,               /* OUT: *pzToken is the token text */
195191  int *pnBytes,                       /* OUT: Number of bytes in token */
195192  int *piStartOffset,                 /* OUT: Starting offset of token */
195193  int *piEndOffset,                   /* OUT: Ending offset of token */
195194  int *piPosition                     /* OUT: Position integer of token */
195195){
195196  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
195197  const char *z = c->zInput;
195198
195199  while( c->iOffset<c->nInput ){
195200    int iStartOffset, ch;
195201
195202    /* Scan past delimiter characters */
195203    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
195204      c->iOffset++;
195205    }
195206
195207    /* Count non-delimiter characters. */
195208    iStartOffset = c->iOffset;
195209    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
195210      c->iOffset++;
195211    }
195212
195213    if( c->iOffset>iStartOffset ){
195214      int n = c->iOffset-iStartOffset;
195215      if( n>c->nAllocated ){
195216        char *pNew;
195217        c->nAllocated = n+20;
195218        pNew = sqlite3_realloc64(c->zToken, c->nAllocated);
195219        if( !pNew ) return SQLITE_NOMEM;
195220        c->zToken = pNew;
195221      }
195222      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
195223      *pzToken = c->zToken;
195224      *piStartOffset = iStartOffset;
195225      *piEndOffset = c->iOffset;
195226      *piPosition = c->iToken++;
195227      return SQLITE_OK;
195228    }
195229  }
195230  return SQLITE_DONE;
195231}
195232
195233/*
195234** The set of routines that implement the porter-stemmer tokenizer
195235*/
195236static const sqlite3_tokenizer_module porterTokenizerModule = {
195237  0,
195238  porterCreate,
195239  porterDestroy,
195240  porterOpen,
195241  porterClose,
195242  porterNext,
195243  0
195244};
195245
195246/*
195247** Allocate a new porter tokenizer.  Return a pointer to the new
195248** tokenizer in *ppModule
195249*/
195250SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
195251  sqlite3_tokenizer_module const**ppModule
195252){
195253  *ppModule = &porterTokenizerModule;
195254}
195255
195256#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
195257
195258/************** End of fts3_porter.c *****************************************/
195259/************** Begin file fts3_tokenizer.c **********************************/
195260/*
195261** 2007 June 22
195262**
195263** The author disclaims copyright to this source code.  In place of
195264** a legal notice, here is a blessing:
195265**
195266**    May you do good and not evil.
195267**    May you find forgiveness for yourself and forgive others.
195268**    May you share freely, never taking more than you give.
195269**
195270******************************************************************************
195271**
195272** This is part of an SQLite module implementing full-text search.
195273** This particular file implements the generic tokenizer interface.
195274*/
195275
195276/*
195277** The code in this file is only compiled if:
195278**
195279**     * The FTS3 module is being built as an extension
195280**       (in which case SQLITE_CORE is not defined), or
195281**
195282**     * The FTS3 module is being built into the core of
195283**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
195284*/
195285/* #include "fts3Int.h" */
195286#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
195287
195288/* #include <assert.h> */
195289/* #include <string.h> */
195290
195291/*
195292** Return true if the two-argument version of fts3_tokenizer()
195293** has been activated via a prior call to sqlite3_db_config(db,
195294** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
195295*/
195296static int fts3TokenizerEnabled(sqlite3_context *context){
195297  sqlite3 *db = sqlite3_context_db_handle(context);
195298  int isEnabled = 0;
195299  sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
195300  return isEnabled;
195301}
195302
195303/*
195304** Implementation of the SQL scalar function for accessing the underlying
195305** hash table. This function may be called as follows:
195306**
195307**   SELECT <function-name>(<key-name>);
195308**   SELECT <function-name>(<key-name>, <pointer>);
195309**
195310** where <function-name> is the name passed as the second argument
195311** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
195312**
195313** If the <pointer> argument is specified, it must be a blob value
195314** containing a pointer to be stored as the hash data corresponding
195315** to the string <key-name>. If <pointer> is not specified, then
195316** the string <key-name> must already exist in the has table. Otherwise,
195317** an error is returned.
195318**
195319** Whether or not the <pointer> argument is specified, the value returned
195320** is a blob containing the pointer stored as the hash data corresponding
195321** to string <key-name> (after the hash-table is updated, if applicable).
195322*/
195323static void fts3TokenizerFunc(
195324  sqlite3_context *context,
195325  int argc,
195326  sqlite3_value **argv
195327){
195328  Fts3Hash *pHash;
195329  void *pPtr = 0;
195330  const unsigned char *zName;
195331  int nName;
195332
195333  assert( argc==1 || argc==2 );
195334
195335  pHash = (Fts3Hash *)sqlite3_user_data(context);
195336
195337  zName = sqlite3_value_text(argv[0]);
195338  nName = sqlite3_value_bytes(argv[0])+1;
195339
195340  if( argc==2 ){
195341    if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[1]) ){
195342      void *pOld;
195343      int n = sqlite3_value_bytes(argv[1]);
195344      if( zName==0 || n!=sizeof(pPtr) ){
195345        sqlite3_result_error(context, "argument type mismatch", -1);
195346        return;
195347      }
195348      pPtr = *(void **)sqlite3_value_blob(argv[1]);
195349      pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
195350      if( pOld==pPtr ){
195351        sqlite3_result_error(context, "out of memory", -1);
195352      }
195353    }else{
195354      sqlite3_result_error(context, "fts3tokenize disabled", -1);
195355      return;
195356    }
195357  }else{
195358    if( zName ){
195359      pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
195360    }
195361    if( !pPtr ){
195362      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
195363      sqlite3_result_error(context, zErr, -1);
195364      sqlite3_free(zErr);
195365      return;
195366    }
195367  }
195368  if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[0]) ){
195369    sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
195370  }
195371}
195372
195373SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
195374  static const char isFtsIdChar[] = {
195375      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
195376      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
195377      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
195378      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
195379      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
195380      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
195381      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
195382      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
195383  };
195384  return (c&0x80 || isFtsIdChar[(int)(c)]);
195385}
195386
195387SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
195388  const char *z1;
195389  const char *z2 = 0;
195390
195391  /* Find the start of the next token. */
195392  z1 = zStr;
195393  while( z2==0 ){
195394    char c = *z1;
195395    switch( c ){
195396      case '\0': return 0;        /* No more tokens here */
195397      case '\'':
195398      case '"':
195399      case '`': {
195400        z2 = z1;
195401        while( *++z2 && (*z2!=c || *++z2==c) );
195402        break;
195403      }
195404      case '[':
195405        z2 = &z1[1];
195406        while( *z2 && z2[0]!=']' ) z2++;
195407        if( *z2 ) z2++;
195408        break;
195409
195410      default:
195411        if( sqlite3Fts3IsIdChar(*z1) ){
195412          z2 = &z1[1];
195413          while( sqlite3Fts3IsIdChar(*z2) ) z2++;
195414        }else{
195415          z1++;
195416        }
195417    }
195418  }
195419
195420  *pn = (int)(z2-z1);
195421  return z1;
195422}
195423
195424SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
195425  Fts3Hash *pHash,                /* Tokenizer hash table */
195426  const char *zArg,               /* Tokenizer name */
195427  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
195428  char **pzErr                    /* OUT: Set to malloced error message */
195429){
195430  int rc;
195431  char *z = (char *)zArg;
195432  int n = 0;
195433  char *zCopy;
195434  char *zEnd;                     /* Pointer to nul-term of zCopy */
195435  sqlite3_tokenizer_module *m;
195436
195437  zCopy = sqlite3_mprintf("%s", zArg);
195438  if( !zCopy ) return SQLITE_NOMEM;
195439  zEnd = &zCopy[strlen(zCopy)];
195440
195441  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
195442  if( z==0 ){
195443    assert( n==0 );
195444    z = zCopy;
195445  }
195446  z[n] = '\0';
195447  sqlite3Fts3Dequote(z);
195448
195449  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
195450  if( !m ){
195451    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
195452    rc = SQLITE_ERROR;
195453  }else{
195454    char const **aArg = 0;
195455    int iArg = 0;
195456    z = &z[n+1];
195457    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
195458      sqlite3_int64 nNew = sizeof(char *)*(iArg+1);
195459      char const **aNew = (const char **)sqlite3_realloc64((void *)aArg, nNew);
195460      if( !aNew ){
195461        sqlite3_free(zCopy);
195462        sqlite3_free((void *)aArg);
195463        return SQLITE_NOMEM;
195464      }
195465      aArg = aNew;
195466      aArg[iArg++] = z;
195467      z[n] = '\0';
195468      sqlite3Fts3Dequote(z);
195469      z = &z[n+1];
195470    }
195471    rc = m->xCreate(iArg, aArg, ppTok);
195472    assert( rc!=SQLITE_OK || *ppTok );
195473    if( rc!=SQLITE_OK ){
195474      sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
195475    }else{
195476      (*ppTok)->pModule = m;
195477    }
195478    sqlite3_free((void *)aArg);
195479  }
195480
195481  sqlite3_free(zCopy);
195482  return rc;
195483}
195484
195485
195486#ifdef SQLITE_TEST
195487
195488#if defined(INCLUDE_SQLITE_TCL_H)
195489#  include "sqlite_tcl.h"
195490#else
195491#  include "tcl.h"
195492#endif
195493/* #include <string.h> */
195494
195495/*
195496** Implementation of a special SQL scalar function for testing tokenizers
195497** designed to be used in concert with the Tcl testing framework. This
195498** function must be called with two or more arguments:
195499**
195500**   SELECT <function-name>(<key-name>, ..., <input-string>);
195501**
195502** where <function-name> is the name passed as the second argument
195503** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
195504** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
195505**
195506** The return value is a string that may be interpreted as a Tcl
195507** list. For each token in the <input-string>, three elements are
195508** added to the returned list. The first is the token position, the
195509** second is the token text (folded, stemmed, etc.) and the third is the
195510** substring of <input-string> associated with the token. For example,
195511** using the built-in "simple" tokenizer:
195512**
195513**   SELECT fts_tokenizer_test('simple', 'I don't see how');
195514**
195515** will return the string:
195516**
195517**   "{0 i I 1 dont don't 2 see see 3 how how}"
195518**
195519*/
195520static void testFunc(
195521  sqlite3_context *context,
195522  int argc,
195523  sqlite3_value **argv
195524){
195525  Fts3Hash *pHash;
195526  sqlite3_tokenizer_module *p;
195527  sqlite3_tokenizer *pTokenizer = 0;
195528  sqlite3_tokenizer_cursor *pCsr = 0;
195529
195530  const char *zErr = 0;
195531
195532  const char *zName;
195533  int nName;
195534  const char *zInput;
195535  int nInput;
195536
195537  const char *azArg[64];
195538
195539  const char *zToken;
195540  int nToken = 0;
195541  int iStart = 0;
195542  int iEnd = 0;
195543  int iPos = 0;
195544  int i;
195545
195546  Tcl_Obj *pRet;
195547
195548  if( argc<2 ){
195549    sqlite3_result_error(context, "insufficient arguments", -1);
195550    return;
195551  }
195552
195553  nName = sqlite3_value_bytes(argv[0]);
195554  zName = (const char *)sqlite3_value_text(argv[0]);
195555  nInput = sqlite3_value_bytes(argv[argc-1]);
195556  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
195557
195558  pHash = (Fts3Hash *)sqlite3_user_data(context);
195559  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
195560
195561  if( !p ){
195562    char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
195563    sqlite3_result_error(context, zErr2, -1);
195564    sqlite3_free(zErr2);
195565    return;
195566  }
195567
195568  pRet = Tcl_NewObj();
195569  Tcl_IncrRefCount(pRet);
195570
195571  for(i=1; i<argc-1; i++){
195572    azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
195573  }
195574
195575  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
195576    zErr = "error in xCreate()";
195577    goto finish;
195578  }
195579  pTokenizer->pModule = p;
195580  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
195581    zErr = "error in xOpen()";
195582    goto finish;
195583  }
195584
195585  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
195586    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
195587    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
195588    zToken = &zInput[iStart];
195589    nToken = iEnd-iStart;
195590    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
195591  }
195592
195593  if( SQLITE_OK!=p->xClose(pCsr) ){
195594    zErr = "error in xClose()";
195595    goto finish;
195596  }
195597  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
195598    zErr = "error in xDestroy()";
195599    goto finish;
195600  }
195601
195602finish:
195603  if( zErr ){
195604    sqlite3_result_error(context, zErr, -1);
195605  }else{
195606    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
195607  }
195608  Tcl_DecrRefCount(pRet);
195609}
195610
195611static
195612int registerTokenizer(
195613  sqlite3 *db,
195614  char *zName,
195615  const sqlite3_tokenizer_module *p
195616){
195617  int rc;
195618  sqlite3_stmt *pStmt;
195619  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
195620
195621  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
195622  if( rc!=SQLITE_OK ){
195623    return rc;
195624  }
195625
195626  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
195627  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
195628  sqlite3_step(pStmt);
195629
195630  return sqlite3_finalize(pStmt);
195631}
195632
195633
195634static
195635int queryTokenizer(
195636  sqlite3 *db,
195637  char *zName,
195638  const sqlite3_tokenizer_module **pp
195639){
195640  int rc;
195641  sqlite3_stmt *pStmt;
195642  const char zSql[] = "SELECT fts3_tokenizer(?)";
195643
195644  *pp = 0;
195645  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
195646  if( rc!=SQLITE_OK ){
195647    return rc;
195648  }
195649
195650  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
195651  if( SQLITE_ROW==sqlite3_step(pStmt) ){
195652    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB
195653     && sqlite3_column_bytes(pStmt, 0)==sizeof(*pp)
195654    ){
195655      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
195656    }
195657  }
195658
195659  return sqlite3_finalize(pStmt);
195660}
195661
195662SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
195663
195664/*
195665** Implementation of the scalar function fts3_tokenizer_internal_test().
195666** This function is used for testing only, it is not included in the
195667** build unless SQLITE_TEST is defined.
195668**
195669** The purpose of this is to test that the fts3_tokenizer() function
195670** can be used as designed by the C-code in the queryTokenizer and
195671** registerTokenizer() functions above. These two functions are repeated
195672** in the README.tokenizer file as an example, so it is important to
195673** test them.
195674**
195675** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
195676** function with no arguments. An assert() will fail if a problem is
195677** detected. i.e.:
195678**
195679**     SELECT fts3_tokenizer_internal_test();
195680**
195681*/
195682static void intTestFunc(
195683  sqlite3_context *context,
195684  int argc,
195685  sqlite3_value **argv
195686){
195687  int rc;
195688  const sqlite3_tokenizer_module *p1;
195689  const sqlite3_tokenizer_module *p2;
195690  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
195691
195692  UNUSED_PARAMETER(argc);
195693  UNUSED_PARAMETER(argv);
195694
195695  /* Test the query function */
195696  sqlite3Fts3SimpleTokenizerModule(&p1);
195697  rc = queryTokenizer(db, "simple", &p2);
195698  assert( rc==SQLITE_OK );
195699  assert( p1==p2 );
195700  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
195701  assert( rc==SQLITE_ERROR );
195702  assert( p2==0 );
195703  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
195704
195705  /* Test the storage function */
195706  if( fts3TokenizerEnabled(context) ){
195707    rc = registerTokenizer(db, "nosuchtokenizer", p1);
195708    assert( rc==SQLITE_OK );
195709    rc = queryTokenizer(db, "nosuchtokenizer", &p2);
195710    assert( rc==SQLITE_OK );
195711    assert( p2==p1 );
195712  }
195713
195714  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
195715}
195716
195717#endif
195718
195719/*
195720** Set up SQL objects in database db used to access the contents of
195721** the hash table pointed to by argument pHash. The hash table must
195722** been initialized to use string keys, and to take a private copy
195723** of the key when a value is inserted. i.e. by a call similar to:
195724**
195725**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
195726**
195727** This function adds a scalar function (see header comment above
195728** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
195729** defined at compilation time, a temporary virtual table (see header
195730** comment above struct HashTableVtab) to the database schema. Both
195731** provide read/write access to the contents of *pHash.
195732**
195733** The third argument to this function, zName, is used as the name
195734** of both the scalar and, if created, the virtual table.
195735*/
195736SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
195737  sqlite3 *db,
195738  Fts3Hash *pHash,
195739  const char *zName
195740){
195741  int rc = SQLITE_OK;
195742  void *p = (void *)pHash;
195743  const int any = SQLITE_UTF8|SQLITE_DIRECTONLY;
195744
195745#ifdef SQLITE_TEST
195746  char *zTest = 0;
195747  char *zTest2 = 0;
195748  void *pdb = (void *)db;
195749  zTest = sqlite3_mprintf("%s_test", zName);
195750  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
195751  if( !zTest || !zTest2 ){
195752    rc = SQLITE_NOMEM;
195753  }
195754#endif
195755
195756  if( SQLITE_OK==rc ){
195757    rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
195758  }
195759  if( SQLITE_OK==rc ){
195760    rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
195761  }
195762#ifdef SQLITE_TEST
195763  if( SQLITE_OK==rc ){
195764    rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
195765  }
195766  if( SQLITE_OK==rc ){
195767    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
195768  }
195769#endif
195770
195771#ifdef SQLITE_TEST
195772  sqlite3_free(zTest);
195773  sqlite3_free(zTest2);
195774#endif
195775
195776  return rc;
195777}
195778
195779#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
195780
195781/************** End of fts3_tokenizer.c **************************************/
195782/************** Begin file fts3_tokenizer1.c *********************************/
195783/*
195784** 2006 Oct 10
195785**
195786** The author disclaims copyright to this source code.  In place of
195787** a legal notice, here is a blessing:
195788**
195789**    May you do good and not evil.
195790**    May you find forgiveness for yourself and forgive others.
195791**    May you share freely, never taking more than you give.
195792**
195793******************************************************************************
195794**
195795** Implementation of the "simple" full-text-search tokenizer.
195796*/
195797
195798/*
195799** The code in this file is only compiled if:
195800**
195801**     * The FTS3 module is being built as an extension
195802**       (in which case SQLITE_CORE is not defined), or
195803**
195804**     * The FTS3 module is being built into the core of
195805**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
195806*/
195807/* #include "fts3Int.h" */
195808#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
195809
195810/* #include <assert.h> */
195811/* #include <stdlib.h> */
195812/* #include <stdio.h> */
195813/* #include <string.h> */
195814
195815/* #include "fts3_tokenizer.h" */
195816
195817typedef struct simple_tokenizer {
195818  sqlite3_tokenizer base;
195819  char delim[128];             /* flag ASCII delimiters */
195820} simple_tokenizer;
195821
195822typedef struct simple_tokenizer_cursor {
195823  sqlite3_tokenizer_cursor base;
195824  const char *pInput;          /* input we are tokenizing */
195825  int nBytes;                  /* size of the input */
195826  int iOffset;                 /* current position in pInput */
195827  int iToken;                  /* index of next token to be returned */
195828  char *pToken;                /* storage for current token */
195829  int nTokenAllocated;         /* space allocated to zToken buffer */
195830} simple_tokenizer_cursor;
195831
195832
195833static int simpleDelim(simple_tokenizer *t, unsigned char c){
195834  return c<0x80 && t->delim[c];
195835}
195836static int fts3_isalnum(int x){
195837  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
195838}
195839
195840/*
195841** Create a new tokenizer instance.
195842*/
195843static int simpleCreate(
195844  int argc, const char * const *argv,
195845  sqlite3_tokenizer **ppTokenizer
195846){
195847  simple_tokenizer *t;
195848
195849  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
195850  if( t==NULL ) return SQLITE_NOMEM;
195851  memset(t, 0, sizeof(*t));
195852
195853  /* TODO(shess) Delimiters need to remain the same from run to run,
195854  ** else we need to reindex.  One solution would be a meta-table to
195855  ** track such information in the database, then we'd only want this
195856  ** information on the initial create.
195857  */
195858  if( argc>1 ){
195859    int i, n = (int)strlen(argv[1]);
195860    for(i=0; i<n; i++){
195861      unsigned char ch = argv[1][i];
195862      /* We explicitly don't support UTF-8 delimiters for now. */
195863      if( ch>=0x80 ){
195864        sqlite3_free(t);
195865        return SQLITE_ERROR;
195866      }
195867      t->delim[ch] = 1;
195868    }
195869  } else {
195870    /* Mark non-alphanumeric ASCII characters as delimiters */
195871    int i;
195872    for(i=1; i<0x80; i++){
195873      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
195874    }
195875  }
195876
195877  *ppTokenizer = &t->base;
195878  return SQLITE_OK;
195879}
195880
195881/*
195882** Destroy a tokenizer
195883*/
195884static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
195885  sqlite3_free(pTokenizer);
195886  return SQLITE_OK;
195887}
195888
195889/*
195890** Prepare to begin tokenizing a particular string.  The input
195891** string to be tokenized is pInput[0..nBytes-1].  A cursor
195892** used to incrementally tokenize this string is returned in
195893** *ppCursor.
195894*/
195895static int simpleOpen(
195896  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
195897  const char *pInput, int nBytes,        /* String to be tokenized */
195898  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
195899){
195900  simple_tokenizer_cursor *c;
195901
195902  UNUSED_PARAMETER(pTokenizer);
195903
195904  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
195905  if( c==NULL ) return SQLITE_NOMEM;
195906
195907  c->pInput = pInput;
195908  if( pInput==0 ){
195909    c->nBytes = 0;
195910  }else if( nBytes<0 ){
195911    c->nBytes = (int)strlen(pInput);
195912  }else{
195913    c->nBytes = nBytes;
195914  }
195915  c->iOffset = 0;                 /* start tokenizing at the beginning */
195916  c->iToken = 0;
195917  c->pToken = NULL;               /* no space allocated, yet. */
195918  c->nTokenAllocated = 0;
195919
195920  *ppCursor = &c->base;
195921  return SQLITE_OK;
195922}
195923
195924/*
195925** Close a tokenization cursor previously opened by a call to
195926** simpleOpen() above.
195927*/
195928static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
195929  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
195930  sqlite3_free(c->pToken);
195931  sqlite3_free(c);
195932  return SQLITE_OK;
195933}
195934
195935/*
195936** Extract the next token from a tokenization cursor.  The cursor must
195937** have been opened by a prior call to simpleOpen().
195938*/
195939static int simpleNext(
195940  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
195941  const char **ppToken,               /* OUT: *ppToken is the token text */
195942  int *pnBytes,                       /* OUT: Number of bytes in token */
195943  int *piStartOffset,                 /* OUT: Starting offset of token */
195944  int *piEndOffset,                   /* OUT: Ending offset of token */
195945  int *piPosition                     /* OUT: Position integer of token */
195946){
195947  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
195948  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
195949  unsigned char *p = (unsigned char *)c->pInput;
195950
195951  while( c->iOffset<c->nBytes ){
195952    int iStartOffset;
195953
195954    /* Scan past delimiter characters */
195955    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
195956      c->iOffset++;
195957    }
195958
195959    /* Count non-delimiter characters. */
195960    iStartOffset = c->iOffset;
195961    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
195962      c->iOffset++;
195963    }
195964
195965    if( c->iOffset>iStartOffset ){
195966      int i, n = c->iOffset-iStartOffset;
195967      if( n>c->nTokenAllocated ){
195968        char *pNew;
195969        c->nTokenAllocated = n+20;
195970        pNew = sqlite3_realloc64(c->pToken, c->nTokenAllocated);
195971        if( !pNew ) return SQLITE_NOMEM;
195972        c->pToken = pNew;
195973      }
195974      for(i=0; i<n; i++){
195975        /* TODO(shess) This needs expansion to handle UTF-8
195976        ** case-insensitivity.
195977        */
195978        unsigned char ch = p[iStartOffset+i];
195979        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
195980      }
195981      *ppToken = c->pToken;
195982      *pnBytes = n;
195983      *piStartOffset = iStartOffset;
195984      *piEndOffset = c->iOffset;
195985      *piPosition = c->iToken++;
195986
195987      return SQLITE_OK;
195988    }
195989  }
195990  return SQLITE_DONE;
195991}
195992
195993/*
195994** The set of routines that implement the simple tokenizer
195995*/
195996static const sqlite3_tokenizer_module simpleTokenizerModule = {
195997  0,
195998  simpleCreate,
195999  simpleDestroy,
196000  simpleOpen,
196001  simpleClose,
196002  simpleNext,
196003  0,
196004};
196005
196006/*
196007** Allocate a new simple tokenizer.  Return a pointer to the new
196008** tokenizer in *ppModule
196009*/
196010SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
196011  sqlite3_tokenizer_module const**ppModule
196012){
196013  *ppModule = &simpleTokenizerModule;
196014}
196015
196016#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
196017
196018/************** End of fts3_tokenizer1.c *************************************/
196019/************** Begin file fts3_tokenize_vtab.c ******************************/
196020/*
196021** 2013 Apr 22
196022**
196023** The author disclaims copyright to this source code.  In place of
196024** a legal notice, here is a blessing:
196025**
196026**    May you do good and not evil.
196027**    May you find forgiveness for yourself and forgive others.
196028**    May you share freely, never taking more than you give.
196029**
196030******************************************************************************
196031**
196032** This file contains code for the "fts3tokenize" virtual table module.
196033** An fts3tokenize virtual table is created as follows:
196034**
196035**   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
196036**       <tokenizer-name>, <arg-1>, ...
196037**   );
196038**
196039** The table created has the following schema:
196040**
196041**   CREATE TABLE <tbl>(input, token, start, end, position)
196042**
196043** When queried, the query must include a WHERE clause of type:
196044**
196045**   input = <string>
196046**
196047** The virtual table module tokenizes this <string>, using the FTS3
196048** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
196049** statement and returns one row for each token in the result. With
196050** fields set as follows:
196051**
196052**   input:   Always set to a copy of <string>
196053**   token:   A token from the input.
196054**   start:   Byte offset of the token within the input <string>.
196055**   end:     Byte offset of the byte immediately following the end of the
196056**            token within the input string.
196057**   pos:     Token offset of token within input.
196058**
196059*/
196060/* #include "fts3Int.h" */
196061#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
196062
196063/* #include <string.h> */
196064/* #include <assert.h> */
196065
196066typedef struct Fts3tokTable Fts3tokTable;
196067typedef struct Fts3tokCursor Fts3tokCursor;
196068
196069/*
196070** Virtual table structure.
196071*/
196072struct Fts3tokTable {
196073  sqlite3_vtab base;              /* Base class used by SQLite core */
196074  const sqlite3_tokenizer_module *pMod;
196075  sqlite3_tokenizer *pTok;
196076};
196077
196078/*
196079** Virtual table cursor structure.
196080*/
196081struct Fts3tokCursor {
196082  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
196083  char *zInput;                   /* Input string */
196084  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
196085  int iRowid;                     /* Current 'rowid' value */
196086  const char *zToken;             /* Current 'token' value */
196087  int nToken;                     /* Size of zToken in bytes */
196088  int iStart;                     /* Current 'start' value */
196089  int iEnd;                       /* Current 'end' value */
196090  int iPos;                       /* Current 'pos' value */
196091};
196092
196093/*
196094** Query FTS for the tokenizer implementation named zName.
196095*/
196096static int fts3tokQueryTokenizer(
196097  Fts3Hash *pHash,
196098  const char *zName,
196099  const sqlite3_tokenizer_module **pp,
196100  char **pzErr
196101){
196102  sqlite3_tokenizer_module *p;
196103  int nName = (int)strlen(zName);
196104
196105  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
196106  if( !p ){
196107    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
196108    return SQLITE_ERROR;
196109  }
196110
196111  *pp = p;
196112  return SQLITE_OK;
196113}
196114
196115/*
196116** The second argument, argv[], is an array of pointers to nul-terminated
196117** strings. This function makes a copy of the array and strings into a
196118** single block of memory. It then dequotes any of the strings that appear
196119** to be quoted.
196120**
196121** If successful, output parameter *pazDequote is set to point at the
196122** array of dequoted strings and SQLITE_OK is returned. The caller is
196123** responsible for eventually calling sqlite3_free() to free the array
196124** in this case. Or, if an error occurs, an SQLite error code is returned.
196125** The final value of *pazDequote is undefined in this case.
196126*/
196127static int fts3tokDequoteArray(
196128  int argc,                       /* Number of elements in argv[] */
196129  const char * const *argv,       /* Input array */
196130  char ***pazDequote              /* Output array */
196131){
196132  int rc = SQLITE_OK;             /* Return code */
196133  if( argc==0 ){
196134    *pazDequote = 0;
196135  }else{
196136    int i;
196137    int nByte = 0;
196138    char **azDequote;
196139
196140    for(i=0; i<argc; i++){
196141      nByte += (int)(strlen(argv[i]) + 1);
196142    }
196143
196144    *pazDequote = azDequote = sqlite3_malloc64(sizeof(char *)*argc + nByte);
196145    if( azDequote==0 ){
196146      rc = SQLITE_NOMEM;
196147    }else{
196148      char *pSpace = (char *)&azDequote[argc];
196149      for(i=0; i<argc; i++){
196150        int n = (int)strlen(argv[i]);
196151        azDequote[i] = pSpace;
196152        memcpy(pSpace, argv[i], n+1);
196153        sqlite3Fts3Dequote(pSpace);
196154        pSpace += (n+1);
196155      }
196156    }
196157  }
196158
196159  return rc;
196160}
196161
196162/*
196163** Schema of the tokenizer table.
196164*/
196165#define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
196166
196167/*
196168** This function does all the work for both the xConnect and xCreate methods.
196169** These tables have no persistent representation of their own, so xConnect
196170** and xCreate are identical operations.
196171**
196172**   argv[0]: module name
196173**   argv[1]: database name
196174**   argv[2]: table name
196175**   argv[3]: first argument (tokenizer name)
196176*/
196177static int fts3tokConnectMethod(
196178  sqlite3 *db,                    /* Database connection */
196179  void *pHash,                    /* Hash table of tokenizers */
196180  int argc,                       /* Number of elements in argv array */
196181  const char * const *argv,       /* xCreate/xConnect argument array */
196182  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
196183  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
196184){
196185  Fts3tokTable *pTab = 0;
196186  const sqlite3_tokenizer_module *pMod = 0;
196187  sqlite3_tokenizer *pTok = 0;
196188  int rc;
196189  char **azDequote = 0;
196190  int nDequote;
196191
196192  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
196193  if( rc!=SQLITE_OK ) return rc;
196194
196195  nDequote = argc-3;
196196  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
196197
196198  if( rc==SQLITE_OK ){
196199    const char *zModule;
196200    if( nDequote<1 ){
196201      zModule = "simple";
196202    }else{
196203      zModule = azDequote[0];
196204    }
196205    rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
196206  }
196207
196208  assert( (rc==SQLITE_OK)==(pMod!=0) );
196209  if( rc==SQLITE_OK ){
196210    const char * const *azArg = 0;
196211    if( nDequote>1 ) azArg = (const char * const *)&azDequote[1];
196212    rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
196213  }
196214
196215  if( rc==SQLITE_OK ){
196216    pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
196217    if( pTab==0 ){
196218      rc = SQLITE_NOMEM;
196219    }
196220  }
196221
196222  if( rc==SQLITE_OK ){
196223    memset(pTab, 0, sizeof(Fts3tokTable));
196224    pTab->pMod = pMod;
196225    pTab->pTok = pTok;
196226    *ppVtab = &pTab->base;
196227  }else{
196228    if( pTok ){
196229      pMod->xDestroy(pTok);
196230    }
196231  }
196232
196233  sqlite3_free(azDequote);
196234  return rc;
196235}
196236
196237/*
196238** This function does the work for both the xDisconnect and xDestroy methods.
196239** These tables have no persistent representation of their own, so xDisconnect
196240** and xDestroy are identical operations.
196241*/
196242static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
196243  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
196244
196245  pTab->pMod->xDestroy(pTab->pTok);
196246  sqlite3_free(pTab);
196247  return SQLITE_OK;
196248}
196249
196250/*
196251** xBestIndex - Analyze a WHERE and ORDER BY clause.
196252*/
196253static int fts3tokBestIndexMethod(
196254  sqlite3_vtab *pVTab,
196255  sqlite3_index_info *pInfo
196256){
196257  int i;
196258  UNUSED_PARAMETER(pVTab);
196259
196260  for(i=0; i<pInfo->nConstraint; i++){
196261    if( pInfo->aConstraint[i].usable
196262     && pInfo->aConstraint[i].iColumn==0
196263     && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
196264    ){
196265      pInfo->idxNum = 1;
196266      pInfo->aConstraintUsage[i].argvIndex = 1;
196267      pInfo->aConstraintUsage[i].omit = 1;
196268      pInfo->estimatedCost = 1;
196269      return SQLITE_OK;
196270    }
196271  }
196272
196273  pInfo->idxNum = 0;
196274  assert( pInfo->estimatedCost>1000000.0 );
196275
196276  return SQLITE_OK;
196277}
196278
196279/*
196280** xOpen - Open a cursor.
196281*/
196282static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
196283  Fts3tokCursor *pCsr;
196284  UNUSED_PARAMETER(pVTab);
196285
196286  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
196287  if( pCsr==0 ){
196288    return SQLITE_NOMEM;
196289  }
196290  memset(pCsr, 0, sizeof(Fts3tokCursor));
196291
196292  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
196293  return SQLITE_OK;
196294}
196295
196296/*
196297** Reset the tokenizer cursor passed as the only argument. As if it had
196298** just been returned by fts3tokOpenMethod().
196299*/
196300static void fts3tokResetCursor(Fts3tokCursor *pCsr){
196301  if( pCsr->pCsr ){
196302    Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
196303    pTab->pMod->xClose(pCsr->pCsr);
196304    pCsr->pCsr = 0;
196305  }
196306  sqlite3_free(pCsr->zInput);
196307  pCsr->zInput = 0;
196308  pCsr->zToken = 0;
196309  pCsr->nToken = 0;
196310  pCsr->iStart = 0;
196311  pCsr->iEnd = 0;
196312  pCsr->iPos = 0;
196313  pCsr->iRowid = 0;
196314}
196315
196316/*
196317** xClose - Close a cursor.
196318*/
196319static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
196320  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
196321
196322  fts3tokResetCursor(pCsr);
196323  sqlite3_free(pCsr);
196324  return SQLITE_OK;
196325}
196326
196327/*
196328** xNext - Advance the cursor to the next row, if any.
196329*/
196330static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
196331  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
196332  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
196333  int rc;                         /* Return code */
196334
196335  pCsr->iRowid++;
196336  rc = pTab->pMod->xNext(pCsr->pCsr,
196337      &pCsr->zToken, &pCsr->nToken,
196338      &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
196339  );
196340
196341  if( rc!=SQLITE_OK ){
196342    fts3tokResetCursor(pCsr);
196343    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
196344  }
196345
196346  return rc;
196347}
196348
196349/*
196350** xFilter - Initialize a cursor to point at the start of its data.
196351*/
196352static int fts3tokFilterMethod(
196353  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
196354  int idxNum,                     /* Strategy index */
196355  const char *idxStr,             /* Unused */
196356  int nVal,                       /* Number of elements in apVal */
196357  sqlite3_value **apVal           /* Arguments for the indexing scheme */
196358){
196359  int rc = SQLITE_ERROR;
196360  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
196361  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
196362  UNUSED_PARAMETER(idxStr);
196363  UNUSED_PARAMETER(nVal);
196364
196365  fts3tokResetCursor(pCsr);
196366  if( idxNum==1 ){
196367    const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
196368    int nByte = sqlite3_value_bytes(apVal[0]);
196369    pCsr->zInput = sqlite3_malloc64(nByte+1);
196370    if( pCsr->zInput==0 ){
196371      rc = SQLITE_NOMEM;
196372    }else{
196373      if( nByte>0 ) memcpy(pCsr->zInput, zByte, nByte);
196374      pCsr->zInput[nByte] = 0;
196375      rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
196376      if( rc==SQLITE_OK ){
196377        pCsr->pCsr->pTokenizer = pTab->pTok;
196378      }
196379    }
196380  }
196381
196382  if( rc!=SQLITE_OK ) return rc;
196383  return fts3tokNextMethod(pCursor);
196384}
196385
196386/*
196387** xEof - Return true if the cursor is at EOF, or false otherwise.
196388*/
196389static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
196390  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
196391  return (pCsr->zToken==0);
196392}
196393
196394/*
196395** xColumn - Return a column value.
196396*/
196397static int fts3tokColumnMethod(
196398  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
196399  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
196400  int iCol                        /* Index of column to read value from */
196401){
196402  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
196403
196404  /* CREATE TABLE x(input, token, start, end, position) */
196405  switch( iCol ){
196406    case 0:
196407      sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
196408      break;
196409    case 1:
196410      sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
196411      break;
196412    case 2:
196413      sqlite3_result_int(pCtx, pCsr->iStart);
196414      break;
196415    case 3:
196416      sqlite3_result_int(pCtx, pCsr->iEnd);
196417      break;
196418    default:
196419      assert( iCol==4 );
196420      sqlite3_result_int(pCtx, pCsr->iPos);
196421      break;
196422  }
196423  return SQLITE_OK;
196424}
196425
196426/*
196427** xRowid - Return the current rowid for the cursor.
196428*/
196429static int fts3tokRowidMethod(
196430  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
196431  sqlite_int64 *pRowid            /* OUT: Rowid value */
196432){
196433  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
196434  *pRowid = (sqlite3_int64)pCsr->iRowid;
196435  return SQLITE_OK;
196436}
196437
196438/*
196439** Register the fts3tok module with database connection db. Return SQLITE_OK
196440** if successful or an error code if sqlite3_create_module() fails.
196441*/
196442SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash, void(*xDestroy)(void*)){
196443  static const sqlite3_module fts3tok_module = {
196444     0,                           /* iVersion      */
196445     fts3tokConnectMethod,        /* xCreate       */
196446     fts3tokConnectMethod,        /* xConnect      */
196447     fts3tokBestIndexMethod,      /* xBestIndex    */
196448     fts3tokDisconnectMethod,     /* xDisconnect   */
196449     fts3tokDisconnectMethod,     /* xDestroy      */
196450     fts3tokOpenMethod,           /* xOpen         */
196451     fts3tokCloseMethod,          /* xClose        */
196452     fts3tokFilterMethod,         /* xFilter       */
196453     fts3tokNextMethod,           /* xNext         */
196454     fts3tokEofMethod,            /* xEof          */
196455     fts3tokColumnMethod,         /* xColumn       */
196456     fts3tokRowidMethod,          /* xRowid        */
196457     0,                           /* xUpdate       */
196458     0,                           /* xBegin        */
196459     0,                           /* xSync         */
196460     0,                           /* xCommit       */
196461     0,                           /* xRollback     */
196462     0,                           /* xFindFunction */
196463     0,                           /* xRename       */
196464     0,                           /* xSavepoint    */
196465     0,                           /* xRelease      */
196466     0,                           /* xRollbackTo   */
196467     0,                           /* xShadowName   */
196468     0                            /* xIntegrity    */
196469  };
196470  int rc;                         /* Return code */
196471
196472  rc = sqlite3_create_module_v2(
196473      db, "fts3tokenize", &fts3tok_module, (void*)pHash, xDestroy
196474  );
196475  return rc;
196476}
196477
196478#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
196479
196480/************** End of fts3_tokenize_vtab.c **********************************/
196481/************** Begin file fts3_write.c **************************************/
196482/*
196483** 2009 Oct 23
196484**
196485** The author disclaims copyright to this source code.  In place of
196486** a legal notice, here is a blessing:
196487**
196488**    May you do good and not evil.
196489**    May you find forgiveness for yourself and forgive others.
196490**    May you share freely, never taking more than you give.
196491**
196492******************************************************************************
196493**
196494** This file is part of the SQLite FTS3 extension module. Specifically,
196495** this file contains code to insert, update and delete rows from FTS3
196496** tables. It also contains code to merge FTS3 b-tree segments. Some
196497** of the sub-routines used to merge segments are also used by the query
196498** code in fts3.c.
196499*/
196500
196501/* #include "fts3Int.h" */
196502#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
196503
196504/* #include <string.h> */
196505/* #include <assert.h> */
196506/* #include <stdlib.h> */
196507/* #include <stdio.h> */
196508
196509#define FTS_MAX_APPENDABLE_HEIGHT 16
196510
196511/*
196512** When full-text index nodes are loaded from disk, the buffer that they
196513** are loaded into has the following number of bytes of padding at the end
196514** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
196515** of 920 bytes is allocated for it.
196516**
196517** This means that if we have a pointer into a buffer containing node data,
196518** it is always safe to read up to two varints from it without risking an
196519** overread, even if the node data is corrupted.
196520*/
196521#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
196522
196523/*
196524** Under certain circumstances, b-tree nodes (doclists) can be loaded into
196525** memory incrementally instead of all at once. This can be a big performance
196526** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
196527** method before retrieving all query results (as may happen, for example,
196528** if a query has a LIMIT clause).
196529**
196530** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
196531** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
196532** The code is written so that the hard lower-limit for each of these values
196533** is 1. Clearly such small values would be inefficient, but can be useful
196534** for testing purposes.
196535**
196536** If this module is built with SQLITE_TEST defined, these constants may
196537** be overridden at runtime for testing purposes. File fts3_test.c contains
196538** a Tcl interface to read and write the values.
196539*/
196540#ifdef SQLITE_TEST
196541int test_fts3_node_chunksize = (4*1024);
196542int test_fts3_node_chunk_threshold = (4*1024)*4;
196543# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
196544# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
196545#else
196546# define FTS3_NODE_CHUNKSIZE (4*1024)
196547# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
196548#endif
196549
196550/*
196551** The values that may be meaningfully bound to the :1 parameter in
196552** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
196553*/
196554#define FTS_STAT_DOCTOTAL      0
196555#define FTS_STAT_INCRMERGEHINT 1
196556#define FTS_STAT_AUTOINCRMERGE 2
196557
196558/*
196559** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
196560** and incremental merge operation that takes place. This is used for
196561** debugging FTS only, it should not usually be turned on in production
196562** systems.
196563*/
196564#ifdef FTS3_LOG_MERGES
196565static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
196566  sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
196567}
196568#else
196569#define fts3LogMerge(x, y)
196570#endif
196571
196572
196573typedef struct PendingList PendingList;
196574typedef struct SegmentNode SegmentNode;
196575typedef struct SegmentWriter SegmentWriter;
196576
196577/*
196578** An instance of the following data structure is used to build doclists
196579** incrementally. See function fts3PendingListAppend() for details.
196580*/
196581struct PendingList {
196582  int nData;
196583  char *aData;
196584  int nSpace;
196585  sqlite3_int64 iLastDocid;
196586  sqlite3_int64 iLastCol;
196587  sqlite3_int64 iLastPos;
196588};
196589
196590
196591/*
196592** Each cursor has a (possibly empty) linked list of the following objects.
196593*/
196594struct Fts3DeferredToken {
196595  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
196596  int iCol;                       /* Column token must occur in */
196597  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
196598  PendingList *pList;             /* Doclist is assembled here */
196599};
196600
196601/*
196602** An instance of this structure is used to iterate through the terms on
196603** a contiguous set of segment b-tree leaf nodes. Although the details of
196604** this structure are only manipulated by code in this file, opaque handles
196605** of type Fts3SegReader* are also used by code in fts3.c to iterate through
196606** terms when querying the full-text index. See functions:
196607**
196608**   sqlite3Fts3SegReaderNew()
196609**   sqlite3Fts3SegReaderFree()
196610**   sqlite3Fts3SegReaderIterate()
196611**
196612** Methods used to manipulate Fts3SegReader structures:
196613**
196614**   fts3SegReaderNext()
196615**   fts3SegReaderFirstDocid()
196616**   fts3SegReaderNextDocid()
196617*/
196618struct Fts3SegReader {
196619  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
196620  u8 bLookup;                     /* True for a lookup only */
196621  u8 rootOnly;                    /* True for a root-only reader */
196622
196623  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
196624  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
196625  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
196626  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
196627
196628  char *aNode;                    /* Pointer to node data (or NULL) */
196629  int nNode;                      /* Size of buffer at aNode (or 0) */
196630  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
196631  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
196632
196633  Fts3HashElem **ppNextElem;
196634
196635  /* Variables set by fts3SegReaderNext(). These may be read directly
196636  ** by the caller. They are valid from the time SegmentReaderNew() returns
196637  ** until SegmentReaderNext() returns something other than SQLITE_OK
196638  ** (i.e. SQLITE_DONE).
196639  */
196640  int nTerm;                      /* Number of bytes in current term */
196641  char *zTerm;                    /* Pointer to current term */
196642  int nTermAlloc;                 /* Allocated size of zTerm buffer */
196643  char *aDoclist;                 /* Pointer to doclist of current entry */
196644  int nDoclist;                   /* Size of doclist in current entry */
196645
196646  /* The following variables are used by fts3SegReaderNextDocid() to iterate
196647  ** through the current doclist (aDoclist/nDoclist).
196648  */
196649  char *pOffsetList;
196650  int nOffsetList;                /* For descending pending seg-readers only */
196651  sqlite3_int64 iDocid;
196652};
196653
196654#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
196655#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
196656
196657/*
196658** An instance of this structure is used to create a segment b-tree in the
196659** database. The internal details of this type are only accessed by the
196660** following functions:
196661**
196662**   fts3SegWriterAdd()
196663**   fts3SegWriterFlush()
196664**   fts3SegWriterFree()
196665*/
196666struct SegmentWriter {
196667  SegmentNode *pTree;             /* Pointer to interior tree structure */
196668  sqlite3_int64 iFirst;           /* First slot in %_segments written */
196669  sqlite3_int64 iFree;            /* Next free slot in %_segments */
196670  char *zTerm;                    /* Pointer to previous term buffer */
196671  int nTerm;                      /* Number of bytes in zTerm */
196672  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
196673  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
196674  int nSize;                      /* Size of allocation at aData */
196675  int nData;                      /* Bytes of data in aData */
196676  char *aData;                    /* Pointer to block from malloc() */
196677  i64 nLeafData;                  /* Number of bytes of leaf data written */
196678};
196679
196680/*
196681** Type SegmentNode is used by the following three functions to create
196682** the interior part of the segment b+-tree structures (everything except
196683** the leaf nodes). These functions and type are only ever used by code
196684** within the fts3SegWriterXXX() family of functions described above.
196685**
196686**   fts3NodeAddTerm()
196687**   fts3NodeWrite()
196688**   fts3NodeFree()
196689**
196690** When a b+tree is written to the database (either as a result of a merge
196691** or the pending-terms table being flushed), leaves are written into the
196692** database file as soon as they are completely populated. The interior of
196693** the tree is assembled in memory and written out only once all leaves have
196694** been populated and stored. This is Ok, as the b+-tree fanout is usually
196695** very large, meaning that the interior of the tree consumes relatively
196696** little memory.
196697*/
196698struct SegmentNode {
196699  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
196700  SegmentNode *pRight;            /* Pointer to right-sibling */
196701  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
196702  int nEntry;                     /* Number of terms written to node so far */
196703  char *zTerm;                    /* Pointer to previous term buffer */
196704  int nTerm;                      /* Number of bytes in zTerm */
196705  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
196706  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
196707  int nData;                      /* Bytes of valid data so far */
196708  char *aData;                    /* Node data */
196709};
196710
196711/*
196712** Valid values for the second argument to fts3SqlStmt().
196713*/
196714#define SQL_DELETE_CONTENT             0
196715#define SQL_IS_EMPTY                   1
196716#define SQL_DELETE_ALL_CONTENT         2
196717#define SQL_DELETE_ALL_SEGMENTS        3
196718#define SQL_DELETE_ALL_SEGDIR          4
196719#define SQL_DELETE_ALL_DOCSIZE         5
196720#define SQL_DELETE_ALL_STAT            6
196721#define SQL_SELECT_CONTENT_BY_ROWID    7
196722#define SQL_NEXT_SEGMENT_INDEX         8
196723#define SQL_INSERT_SEGMENTS            9
196724#define SQL_NEXT_SEGMENTS_ID          10
196725#define SQL_INSERT_SEGDIR             11
196726#define SQL_SELECT_LEVEL              12
196727#define SQL_SELECT_LEVEL_RANGE        13
196728#define SQL_SELECT_LEVEL_COUNT        14
196729#define SQL_SELECT_SEGDIR_MAX_LEVEL   15
196730#define SQL_DELETE_SEGDIR_LEVEL       16
196731#define SQL_DELETE_SEGMENTS_RANGE     17
196732#define SQL_CONTENT_INSERT            18
196733#define SQL_DELETE_DOCSIZE            19
196734#define SQL_REPLACE_DOCSIZE           20
196735#define SQL_SELECT_DOCSIZE            21
196736#define SQL_SELECT_STAT               22
196737#define SQL_REPLACE_STAT              23
196738
196739#define SQL_SELECT_ALL_PREFIX_LEVEL   24
196740#define SQL_DELETE_ALL_TERMS_SEGDIR   25
196741#define SQL_DELETE_SEGDIR_RANGE       26
196742#define SQL_SELECT_ALL_LANGID         27
196743#define SQL_FIND_MERGE_LEVEL          28
196744#define SQL_MAX_LEAF_NODE_ESTIMATE    29
196745#define SQL_DELETE_SEGDIR_ENTRY       30
196746#define SQL_SHIFT_SEGDIR_ENTRY        31
196747#define SQL_SELECT_SEGDIR             32
196748#define SQL_CHOMP_SEGDIR              33
196749#define SQL_SEGMENT_IS_APPENDABLE     34
196750#define SQL_SELECT_INDEXES            35
196751#define SQL_SELECT_MXLEVEL            36
196752
196753#define SQL_SELECT_LEVEL_RANGE2       37
196754#define SQL_UPDATE_LEVEL_IDX          38
196755#define SQL_UPDATE_LEVEL              39
196756
196757/*
196758** This function is used to obtain an SQLite prepared statement handle
196759** for the statement identified by the second argument. If successful,
196760** *pp is set to the requested statement handle and SQLITE_OK returned.
196761** Otherwise, an SQLite error code is returned and *pp is set to 0.
196762**
196763** If argument apVal is not NULL, then it must point to an array with
196764** at least as many entries as the requested statement has bound
196765** parameters. The values are bound to the statements parameters before
196766** returning.
196767*/
196768static int fts3SqlStmt(
196769  Fts3Table *p,                   /* Virtual table handle */
196770  int eStmt,                      /* One of the SQL_XXX constants above */
196771  sqlite3_stmt **pp,              /* OUT: Statement handle */
196772  sqlite3_value **apVal           /* Values to bind to statement */
196773){
196774  const char *azSql[] = {
196775/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
196776/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
196777/* 2  */  "DELETE FROM %Q.'%q_content'",
196778/* 3  */  "DELETE FROM %Q.'%q_segments'",
196779/* 4  */  "DELETE FROM %Q.'%q_segdir'",
196780/* 5  */  "DELETE FROM %Q.'%q_docsize'",
196781/* 6  */  "DELETE FROM %Q.'%q_stat'",
196782/* 7  */  "SELECT %s WHERE rowid=?",
196783/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
196784/* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
196785/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
196786/* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
196787
196788          /* Return segments in order from oldest to newest.*/
196789/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
196790            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
196791/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
196792            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
196793            "ORDER BY level DESC, idx ASC",
196794
196795/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
196796/* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
196797
196798/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
196799/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
196800/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
196801/* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
196802/* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
196803/* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
196804/* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
196805/* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
196806/* 24 */  "",
196807/* 25 */  "",
196808
196809/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
196810/* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
196811
196812/* This statement is used to determine which level to read the input from
196813** when performing an incremental merge. It returns the absolute level number
196814** of the oldest level in the db that contains at least ? segments. Or,
196815** if no level in the FTS index contains more than ? segments, the statement
196816** returns zero rows.  */
196817/* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
196818         "  GROUP BY level HAVING cnt>=?"
196819         "  ORDER BY (level %% 1024) ASC, 2 DESC LIMIT 1",
196820
196821/* Estimate the upper limit on the number of leaf nodes in a new segment
196822** created by merging the oldest :2 segments from absolute level :1. See
196823** function sqlite3Fts3Incrmerge() for details.  */
196824/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
196825         "  FROM (SELECT * FROM %Q.'%q_segdir' "
196826         "        WHERE level = ? ORDER BY idx ASC LIMIT ?"
196827         "  )",
196828
196829/* SQL_DELETE_SEGDIR_ENTRY
196830**   Delete the %_segdir entry on absolute level :1 with index :2.  */
196831/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
196832
196833/* SQL_SHIFT_SEGDIR_ENTRY
196834**   Modify the idx value for the segment with idx=:3 on absolute level :2
196835**   to :1.  */
196836/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
196837
196838/* SQL_SELECT_SEGDIR
196839**   Read a single entry from the %_segdir table. The entry from absolute
196840**   level :1 with index value :2.  */
196841/* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
196842            "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
196843
196844/* SQL_CHOMP_SEGDIR
196845**   Update the start_block (:1) and root (:2) fields of the %_segdir
196846**   entry located on absolute level :3 with index :4.  */
196847/* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
196848            "WHERE level = ? AND idx = ?",
196849
196850/* SQL_SEGMENT_IS_APPENDABLE
196851**   Return a single row if the segment with end_block=? is appendable. Or
196852**   no rows otherwise.  */
196853/* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
196854
196855/* SQL_SELECT_INDEXES
196856**   Return the list of valid segment indexes for absolute level ?  */
196857/* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
196858
196859/* SQL_SELECT_MXLEVEL
196860**   Return the largest relative level in the FTS index or indexes.  */
196861/* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
196862
196863          /* Return segments in order from oldest to newest.*/
196864/* 37 */  "SELECT level, idx, end_block "
196865            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
196866            "ORDER BY level DESC, idx ASC",
196867
196868          /* Update statements used while promoting segments */
196869/* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
196870            "WHERE level=? AND idx=?",
196871/* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
196872
196873  };
196874  int rc = SQLITE_OK;
196875  sqlite3_stmt *pStmt;
196876
196877  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
196878  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
196879
196880  pStmt = p->aStmt[eStmt];
196881  if( !pStmt ){
196882    int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
196883    char *zSql;
196884    if( eStmt==SQL_CONTENT_INSERT ){
196885      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
196886    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
196887      f &= ~SQLITE_PREPARE_NO_VTAB;
196888      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
196889    }else{
196890      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
196891    }
196892    if( !zSql ){
196893      rc = SQLITE_NOMEM;
196894    }else{
196895      rc = sqlite3_prepare_v3(p->db, zSql, -1, f, &pStmt, NULL);
196896      sqlite3_free(zSql);
196897      assert( rc==SQLITE_OK || pStmt==0 );
196898      p->aStmt[eStmt] = pStmt;
196899    }
196900  }
196901  if( apVal ){
196902    int i;
196903    int nParam = sqlite3_bind_parameter_count(pStmt);
196904    for(i=0; rc==SQLITE_OK && i<nParam; i++){
196905      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
196906    }
196907  }
196908  *pp = pStmt;
196909  return rc;
196910}
196911
196912
196913static int fts3SelectDocsize(
196914  Fts3Table *pTab,                /* FTS3 table handle */
196915  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
196916  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
196917){
196918  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
196919  int rc;                         /* Return code */
196920
196921  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
196922  if( rc==SQLITE_OK ){
196923    sqlite3_bind_int64(pStmt, 1, iDocid);
196924    rc = sqlite3_step(pStmt);
196925    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
196926      rc = sqlite3_reset(pStmt);
196927      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
196928      pStmt = 0;
196929    }else{
196930      rc = SQLITE_OK;
196931    }
196932  }
196933
196934  *ppStmt = pStmt;
196935  return rc;
196936}
196937
196938SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
196939  Fts3Table *pTab,                /* Fts3 table handle */
196940  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
196941){
196942  sqlite3_stmt *pStmt = 0;
196943  int rc;
196944  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
196945  if( rc==SQLITE_OK ){
196946    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
196947    if( sqlite3_step(pStmt)!=SQLITE_ROW
196948     || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
196949    ){
196950      rc = sqlite3_reset(pStmt);
196951      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
196952      pStmt = 0;
196953    }
196954  }
196955  *ppStmt = pStmt;
196956  return rc;
196957}
196958
196959SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
196960  Fts3Table *pTab,                /* Fts3 table handle */
196961  sqlite3_int64 iDocid,           /* Docid to read size data for */
196962  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
196963){
196964  return fts3SelectDocsize(pTab, iDocid, ppStmt);
196965}
196966
196967/*
196968** Similar to fts3SqlStmt(). Except, after binding the parameters in
196969** array apVal[] to the SQL statement identified by eStmt, the statement
196970** is executed.
196971**
196972** Returns SQLITE_OK if the statement is successfully executed, or an
196973** SQLite error code otherwise.
196974*/
196975static void fts3SqlExec(
196976  int *pRC,                /* Result code */
196977  Fts3Table *p,            /* The FTS3 table */
196978  int eStmt,               /* Index of statement to evaluate */
196979  sqlite3_value **apVal    /* Parameters to bind */
196980){
196981  sqlite3_stmt *pStmt;
196982  int rc;
196983  if( *pRC ) return;
196984  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
196985  if( rc==SQLITE_OK ){
196986    sqlite3_step(pStmt);
196987    rc = sqlite3_reset(pStmt);
196988  }
196989  *pRC = rc;
196990}
196991
196992
196993/*
196994** This function ensures that the caller has obtained an exclusive
196995** shared-cache table-lock on the %_segdir table. This is required before
196996** writing data to the fts3 table. If this lock is not acquired first, then
196997** the caller may end up attempting to take this lock as part of committing
196998** a transaction, causing SQLite to return SQLITE_LOCKED or
196999** LOCKED_SHAREDCACHEto a COMMIT command.
197000**
197001** It is best to avoid this because if FTS3 returns any error when
197002** committing a transaction, the whole transaction will be rolled back.
197003** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
197004** It can still happen if the user locks the underlying tables directly
197005** instead of accessing them via FTS.
197006*/
197007static int fts3Writelock(Fts3Table *p){
197008  int rc = SQLITE_OK;
197009
197010  if( p->nPendingData==0 ){
197011    sqlite3_stmt *pStmt;
197012    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
197013    if( rc==SQLITE_OK ){
197014      sqlite3_bind_null(pStmt, 1);
197015      sqlite3_step(pStmt);
197016      rc = sqlite3_reset(pStmt);
197017    }
197018  }
197019
197020  return rc;
197021}
197022
197023/*
197024** FTS maintains a separate indexes for each language-id (a 32-bit integer).
197025** Within each language id, a separate index is maintained to store the
197026** document terms, and each configured prefix size (configured the FTS
197027** "prefix=" option). And each index consists of multiple levels ("relative
197028** levels").
197029**
197030** All three of these values (the language id, the specific index and the
197031** level within the index) are encoded in 64-bit integer values stored
197032** in the %_segdir table on disk. This function is used to convert three
197033** separate component values into the single 64-bit integer value that
197034** can be used to query the %_segdir table.
197035**
197036** Specifically, each language-id/index combination is allocated 1024
197037** 64-bit integer level values ("absolute levels"). The main terms index
197038** for language-id 0 is allocate values 0-1023. The first prefix index
197039** (if any) for language-id 0 is allocated values 1024-2047. And so on.
197040** Language 1 indexes are allocated immediately following language 0.
197041**
197042** So, for a system with nPrefix prefix indexes configured, the block of
197043** absolute levels that corresponds to language-id iLangid and index
197044** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
197045*/
197046static sqlite3_int64 getAbsoluteLevel(
197047  Fts3Table *p,                   /* FTS3 table handle */
197048  int iLangid,                    /* Language id */
197049  int iIndex,                     /* Index in p->aIndex[] */
197050  int iLevel                      /* Level of segments */
197051){
197052  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
197053  assert_fts3_nc( iLangid>=0 );
197054  assert( p->nIndex>0 );
197055  assert( iIndex>=0 && iIndex<p->nIndex );
197056
197057  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
197058  return iBase + iLevel;
197059}
197060
197061/*
197062** Set *ppStmt to a statement handle that may be used to iterate through
197063** all rows in the %_segdir table, from oldest to newest. If successful,
197064** return SQLITE_OK. If an error occurs while preparing the statement,
197065** return an SQLite error code.
197066**
197067** There is only ever one instance of this SQL statement compiled for
197068** each FTS3 table.
197069**
197070** The statement returns the following columns from the %_segdir table:
197071**
197072**   0: idx
197073**   1: start_block
197074**   2: leaves_end_block
197075**   3: end_block
197076**   4: root
197077*/
197078SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
197079  Fts3Table *p,                   /* FTS3 table */
197080  int iLangid,                    /* Language being queried */
197081  int iIndex,                     /* Index for p->aIndex[] */
197082  int iLevel,                     /* Level to select (relative level) */
197083  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
197084){
197085  int rc;
197086  sqlite3_stmt *pStmt = 0;
197087
197088  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
197089  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
197090  assert( iIndex>=0 && iIndex<p->nIndex );
197091
197092  if( iLevel<0 ){
197093    /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
197094    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
197095    if( rc==SQLITE_OK ){
197096      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
197097      sqlite3_bind_int64(pStmt, 2,
197098          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
197099      );
197100    }
197101  }else{
197102    /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
197103    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
197104    if( rc==SQLITE_OK ){
197105      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
197106    }
197107  }
197108  *ppStmt = pStmt;
197109  return rc;
197110}
197111
197112
197113/*
197114** Append a single varint to a PendingList buffer. SQLITE_OK is returned
197115** if successful, or an SQLite error code otherwise.
197116**
197117** This function also serves to allocate the PendingList structure itself.
197118** For example, to create a new PendingList structure containing two
197119** varints:
197120**
197121**   PendingList *p = 0;
197122**   fts3PendingListAppendVarint(&p, 1);
197123**   fts3PendingListAppendVarint(&p, 2);
197124*/
197125static int fts3PendingListAppendVarint(
197126  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
197127  sqlite3_int64 i                 /* Value to append to data */
197128){
197129  PendingList *p = *pp;
197130
197131  /* Allocate or grow the PendingList as required. */
197132  if( !p ){
197133    p = sqlite3_malloc64(sizeof(*p) + 100);
197134    if( !p ){
197135      return SQLITE_NOMEM;
197136    }
197137    p->nSpace = 100;
197138    p->aData = (char *)&p[1];
197139    p->nData = 0;
197140  }
197141  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
197142    i64 nNew = p->nSpace * 2;
197143    p = sqlite3_realloc64(p, sizeof(*p) + nNew);
197144    if( !p ){
197145      sqlite3_free(*pp);
197146      *pp = 0;
197147      return SQLITE_NOMEM;
197148    }
197149    p->nSpace = (int)nNew;
197150    p->aData = (char *)&p[1];
197151  }
197152
197153  /* Append the new serialized varint to the end of the list. */
197154  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
197155  p->aData[p->nData] = '\0';
197156  *pp = p;
197157  return SQLITE_OK;
197158}
197159
197160/*
197161** Add a docid/column/position entry to a PendingList structure. Non-zero
197162** is returned if the structure is sqlite3_realloced as part of adding
197163** the entry. Otherwise, zero.
197164**
197165** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
197166** Zero is always returned in this case. Otherwise, if no OOM error occurs,
197167** it is set to SQLITE_OK.
197168*/
197169static int fts3PendingListAppend(
197170  PendingList **pp,               /* IN/OUT: PendingList structure */
197171  sqlite3_int64 iDocid,           /* Docid for entry to add */
197172  sqlite3_int64 iCol,             /* Column for entry to add */
197173  sqlite3_int64 iPos,             /* Position of term for entry to add */
197174  int *pRc                        /* OUT: Return code */
197175){
197176  PendingList *p = *pp;
197177  int rc = SQLITE_OK;
197178
197179  assert( !p || p->iLastDocid<=iDocid );
197180
197181  if( !p || p->iLastDocid!=iDocid ){
197182    u64 iDelta = (u64)iDocid - (u64)(p ? p->iLastDocid : 0);
197183    if( p ){
197184      assert( p->nData<p->nSpace );
197185      assert( p->aData[p->nData]==0 );
197186      p->nData++;
197187    }
197188    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
197189      goto pendinglistappend_out;
197190    }
197191    p->iLastCol = -1;
197192    p->iLastPos = 0;
197193    p->iLastDocid = iDocid;
197194  }
197195  if( iCol>0 && p->iLastCol!=iCol ){
197196    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
197197     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
197198    ){
197199      goto pendinglistappend_out;
197200    }
197201    p->iLastCol = iCol;
197202    p->iLastPos = 0;
197203  }
197204  if( iCol>=0 ){
197205    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
197206    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
197207    if( rc==SQLITE_OK ){
197208      p->iLastPos = iPos;
197209    }
197210  }
197211
197212 pendinglistappend_out:
197213  *pRc = rc;
197214  if( p!=*pp ){
197215    *pp = p;
197216    return 1;
197217  }
197218  return 0;
197219}
197220
197221/*
197222** Free a PendingList object allocated by fts3PendingListAppend().
197223*/
197224static void fts3PendingListDelete(PendingList *pList){
197225  sqlite3_free(pList);
197226}
197227
197228/*
197229** Add an entry to one of the pending-terms hash tables.
197230*/
197231static int fts3PendingTermsAddOne(
197232  Fts3Table *p,
197233  int iCol,
197234  int iPos,
197235  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
197236  const char *zToken,
197237  int nToken
197238){
197239  PendingList *pList;
197240  int rc = SQLITE_OK;
197241
197242  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
197243  if( pList ){
197244    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
197245  }
197246  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
197247    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
197248      /* Malloc failed while inserting the new entry. This can only
197249      ** happen if there was no previous entry for this token.
197250      */
197251      assert( 0==fts3HashFind(pHash, zToken, nToken) );
197252      sqlite3_free(pList);
197253      rc = SQLITE_NOMEM;
197254    }
197255  }
197256  if( rc==SQLITE_OK ){
197257    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
197258  }
197259  return rc;
197260}
197261
197262/*
197263** Tokenize the nul-terminated string zText and add all tokens to the
197264** pending-terms hash-table. The docid used is that currently stored in
197265** p->iPrevDocid, and the column is specified by argument iCol.
197266**
197267** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
197268*/
197269static int fts3PendingTermsAdd(
197270  Fts3Table *p,                   /* Table into which text will be inserted */
197271  int iLangid,                    /* Language id to use */
197272  const char *zText,              /* Text of document to be inserted */
197273  int iCol,                       /* Column into which text is being inserted */
197274  u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
197275){
197276  int rc;
197277  int iStart = 0;
197278  int iEnd = 0;
197279  int iPos = 0;
197280  int nWord = 0;
197281
197282  char const *zToken;
197283  int nToken = 0;
197284
197285  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
197286  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
197287  sqlite3_tokenizer_cursor *pCsr;
197288  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
197289      const char**,int*,int*,int*,int*);
197290
197291  assert( pTokenizer && pModule );
197292
197293  /* If the user has inserted a NULL value, this function may be called with
197294  ** zText==0. In this case, add zero token entries to the hash table and
197295  ** return early. */
197296  if( zText==0 ){
197297    *pnWord = 0;
197298    return SQLITE_OK;
197299  }
197300
197301  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
197302  if( rc!=SQLITE_OK ){
197303    return rc;
197304  }
197305
197306  xNext = pModule->xNext;
197307  while( SQLITE_OK==rc
197308      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
197309  ){
197310    int i;
197311    if( iPos>=nWord ) nWord = iPos+1;
197312
197313    /* Positions cannot be negative; we use -1 as a terminator internally.
197314    ** Tokens must have a non-zero length.
197315    */
197316    if( iPos<0 || !zToken || nToken<=0 ){
197317      rc = SQLITE_ERROR;
197318      break;
197319    }
197320
197321    /* Add the term to the terms index */
197322    rc = fts3PendingTermsAddOne(
197323        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
197324    );
197325
197326    /* Add the term to each of the prefix indexes that it is not too
197327    ** short for. */
197328    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
197329      struct Fts3Index *pIndex = &p->aIndex[i];
197330      if( nToken<pIndex->nPrefix ) continue;
197331      rc = fts3PendingTermsAddOne(
197332          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
197333      );
197334    }
197335  }
197336
197337  pModule->xClose(pCsr);
197338  *pnWord += nWord;
197339  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
197340}
197341
197342/*
197343** Calling this function indicates that subsequent calls to
197344** fts3PendingTermsAdd() are to add term/position-list pairs for the
197345** contents of the document with docid iDocid.
197346*/
197347static int fts3PendingTermsDocid(
197348  Fts3Table *p,                   /* Full-text table handle */
197349  int bDelete,                    /* True if this op is a delete */
197350  int iLangid,                    /* Language id of row being written */
197351  sqlite_int64 iDocid             /* Docid of row being written */
197352){
197353  assert( iLangid>=0 );
197354  assert( bDelete==1 || bDelete==0 );
197355
197356  /* TODO(shess) Explore whether partially flushing the buffer on
197357  ** forced-flush would provide better performance.  I suspect that if
197358  ** we ordered the doclists by size and flushed the largest until the
197359  ** buffer was half empty, that would let the less frequent terms
197360  ** generate longer doclists.
197361  */
197362  if( iDocid<p->iPrevDocid
197363   || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
197364   || p->iPrevLangid!=iLangid
197365   || p->nPendingData>p->nMaxPendingData
197366  ){
197367    int rc = sqlite3Fts3PendingTermsFlush(p);
197368    if( rc!=SQLITE_OK ) return rc;
197369  }
197370  p->iPrevDocid = iDocid;
197371  p->iPrevLangid = iLangid;
197372  p->bPrevDelete = bDelete;
197373  return SQLITE_OK;
197374}
197375
197376/*
197377** Discard the contents of the pending-terms hash tables.
197378*/
197379SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
197380  int i;
197381  for(i=0; i<p->nIndex; i++){
197382    Fts3HashElem *pElem;
197383    Fts3Hash *pHash = &p->aIndex[i].hPending;
197384    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
197385      PendingList *pList = (PendingList *)fts3HashData(pElem);
197386      fts3PendingListDelete(pList);
197387    }
197388    fts3HashClear(pHash);
197389  }
197390  p->nPendingData = 0;
197391}
197392
197393/*
197394** This function is called by the xUpdate() method as part of an INSERT
197395** operation. It adds entries for each term in the new record to the
197396** pendingTerms hash table.
197397**
197398** Argument apVal is the same as the similarly named argument passed to
197399** fts3InsertData(). Parameter iDocid is the docid of the new row.
197400*/
197401static int fts3InsertTerms(
197402  Fts3Table *p,
197403  int iLangid,
197404  sqlite3_value **apVal,
197405  u32 *aSz
197406){
197407  int i;                          /* Iterator variable */
197408  for(i=2; i<p->nColumn+2; i++){
197409    int iCol = i-2;
197410    if( p->abNotindexed[iCol]==0 ){
197411      const char *zText = (const char *)sqlite3_value_text(apVal[i]);
197412      int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
197413      if( rc!=SQLITE_OK ){
197414        return rc;
197415      }
197416      aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
197417    }
197418  }
197419  return SQLITE_OK;
197420}
197421
197422/*
197423** This function is called by the xUpdate() method for an INSERT operation.
197424** The apVal parameter is passed a copy of the apVal argument passed by
197425** SQLite to the xUpdate() method. i.e:
197426**
197427**   apVal[0]                Not used for INSERT.
197428**   apVal[1]                rowid
197429**   apVal[2]                Left-most user-defined column
197430**   ...
197431**   apVal[p->nColumn+1]     Right-most user-defined column
197432**   apVal[p->nColumn+2]     Hidden column with same name as table
197433**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
197434**   apVal[p->nColumn+4]     Hidden languageid column
197435*/
197436static int fts3InsertData(
197437  Fts3Table *p,                   /* Full-text table */
197438  sqlite3_value **apVal,          /* Array of values to insert */
197439  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
197440){
197441  int rc;                         /* Return code */
197442  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
197443
197444  if( p->zContentTbl ){
197445    sqlite3_value *pRowid = apVal[p->nColumn+3];
197446    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
197447      pRowid = apVal[1];
197448    }
197449    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
197450      return SQLITE_CONSTRAINT;
197451    }
197452    *piDocid = sqlite3_value_int64(pRowid);
197453    return SQLITE_OK;
197454  }
197455
197456  /* Locate the statement handle used to insert data into the %_content
197457  ** table. The SQL for this statement is:
197458  **
197459  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
197460  **
197461  ** The statement features N '?' variables, where N is the number of user
197462  ** defined columns in the FTS3 table, plus one for the docid field.
197463  */
197464  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
197465  if( rc==SQLITE_OK && p->zLanguageid ){
197466    rc = sqlite3_bind_int(
197467        pContentInsert, p->nColumn+2,
197468        sqlite3_value_int(apVal[p->nColumn+4])
197469    );
197470  }
197471  if( rc!=SQLITE_OK ) return rc;
197472
197473  /* There is a quirk here. The users INSERT statement may have specified
197474  ** a value for the "rowid" field, for the "docid" field, or for both.
197475  ** Which is a problem, since "rowid" and "docid" are aliases for the
197476  ** same value. For example:
197477  **
197478  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
197479  **
197480  ** In FTS3, this is an error. It is an error to specify non-NULL values
197481  ** for both docid and some other rowid alias.
197482  */
197483  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
197484    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
197485     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
197486    ){
197487      /* A rowid/docid conflict. */
197488      return SQLITE_ERROR;
197489    }
197490    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
197491    if( rc!=SQLITE_OK ) return rc;
197492  }
197493
197494  /* Execute the statement to insert the record. Set *piDocid to the
197495  ** new docid value.
197496  */
197497  sqlite3_step(pContentInsert);
197498  rc = sqlite3_reset(pContentInsert);
197499
197500  *piDocid = sqlite3_last_insert_rowid(p->db);
197501  return rc;
197502}
197503
197504
197505
197506/*
197507** Remove all data from the FTS3 table. Clear the hash table containing
197508** pending terms.
197509*/
197510static int fts3DeleteAll(Fts3Table *p, int bContent){
197511  int rc = SQLITE_OK;             /* Return code */
197512
197513  /* Discard the contents of the pending-terms hash table. */
197514  sqlite3Fts3PendingTermsClear(p);
197515
197516  /* Delete everything from the shadow tables. Except, leave %_content as
197517  ** is if bContent is false.  */
197518  assert( p->zContentTbl==0 || bContent==0 );
197519  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
197520  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
197521  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
197522  if( p->bHasDocsize ){
197523    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
197524  }
197525  if( p->bHasStat ){
197526    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
197527  }
197528  return rc;
197529}
197530
197531/*
197532**
197533*/
197534static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
197535  int iLangid = 0;
197536  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
197537  return iLangid;
197538}
197539
197540/*
197541** The first element in the apVal[] array is assumed to contain the docid
197542** (an integer) of a row about to be deleted. Remove all terms from the
197543** full-text index.
197544*/
197545static void fts3DeleteTerms(
197546  int *pRC,               /* Result code */
197547  Fts3Table *p,           /* The FTS table to delete from */
197548  sqlite3_value *pRowid,  /* The docid to be deleted */
197549  u32 *aSz,               /* Sizes of deleted document written here */
197550  int *pbFound            /* OUT: Set to true if row really does exist */
197551){
197552  int rc;
197553  sqlite3_stmt *pSelect;
197554
197555  assert( *pbFound==0 );
197556  if( *pRC ) return;
197557  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
197558  if( rc==SQLITE_OK ){
197559    if( SQLITE_ROW==sqlite3_step(pSelect) ){
197560      int i;
197561      int iLangid = langidFromSelect(p, pSelect);
197562      i64 iDocid = sqlite3_column_int64(pSelect, 0);
197563      rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
197564      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
197565        int iCol = i-1;
197566        if( p->abNotindexed[iCol]==0 ){
197567          const char *zText = (const char *)sqlite3_column_text(pSelect, i);
197568          rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
197569          aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
197570        }
197571      }
197572      if( rc!=SQLITE_OK ){
197573        sqlite3_reset(pSelect);
197574        *pRC = rc;
197575        return;
197576      }
197577      *pbFound = 1;
197578    }
197579    rc = sqlite3_reset(pSelect);
197580  }else{
197581    sqlite3_reset(pSelect);
197582  }
197583  *pRC = rc;
197584}
197585
197586/*
197587** Forward declaration to account for the circular dependency between
197588** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
197589*/
197590static int fts3SegmentMerge(Fts3Table *, int, int, int);
197591
197592/*
197593** This function allocates a new level iLevel index in the segdir table.
197594** Usually, indexes are allocated within a level sequentially starting
197595** with 0, so the allocated index is one greater than the value returned
197596** by:
197597**
197598**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
197599**
197600** However, if there are already FTS3_MERGE_COUNT indexes at the requested
197601** level, they are merged into a single level (iLevel+1) segment and the
197602** allocated index is 0.
197603**
197604** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
197605** returned. Otherwise, an SQLite error code is returned.
197606*/
197607static int fts3AllocateSegdirIdx(
197608  Fts3Table *p,
197609  int iLangid,                    /* Language id */
197610  int iIndex,                     /* Index for p->aIndex */
197611  int iLevel,
197612  int *piIdx
197613){
197614  int rc;                         /* Return Code */
197615  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
197616  int iNext = 0;                  /* Result of query pNextIdx */
197617
197618  assert( iLangid>=0 );
197619  assert( p->nIndex>=1 );
197620
197621  /* Set variable iNext to the next available segdir index at level iLevel. */
197622  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
197623  if( rc==SQLITE_OK ){
197624    sqlite3_bind_int64(
197625        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
197626    );
197627    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
197628      iNext = sqlite3_column_int(pNextIdx, 0);
197629    }
197630    rc = sqlite3_reset(pNextIdx);
197631  }
197632
197633  if( rc==SQLITE_OK ){
197634    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
197635    ** full, merge all segments in level iLevel into a single iLevel+1
197636    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
197637    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
197638    */
197639    if( iNext>=MergeCount(p) ){
197640      fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
197641      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
197642      *piIdx = 0;
197643    }else{
197644      *piIdx = iNext;
197645    }
197646  }
197647
197648  return rc;
197649}
197650
197651/*
197652** The %_segments table is declared as follows:
197653**
197654**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
197655**
197656** This function reads data from a single row of the %_segments table. The
197657** specific row is identified by the iBlockid parameter. If paBlob is not
197658** NULL, then a buffer is allocated using sqlite3_malloc() and populated
197659** with the contents of the blob stored in the "block" column of the
197660** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
197661** to the size of the blob in bytes before returning.
197662**
197663** If an error occurs, or the table does not contain the specified row,
197664** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
197665** paBlob is non-NULL, then it is the responsibility of the caller to
197666** eventually free the returned buffer.
197667**
197668** This function may leave an open sqlite3_blob* handle in the
197669** Fts3Table.pSegments variable. This handle is reused by subsequent calls
197670** to this function. The handle may be closed by calling the
197671** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
197672** performance improvement, but the blob handle should always be closed
197673** before control is returned to the user (to prevent a lock being held
197674** on the database file for longer than necessary). Thus, any virtual table
197675** method (xFilter etc.) that may directly or indirectly call this function
197676** must call sqlite3Fts3SegmentsClose() before returning.
197677*/
197678SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
197679  Fts3Table *p,                   /* FTS3 table handle */
197680  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
197681  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
197682  int *pnBlob,                    /* OUT: Size of blob data */
197683  int *pnLoad                     /* OUT: Bytes actually loaded */
197684){
197685  int rc;                         /* Return code */
197686
197687  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
197688  assert( pnBlob );
197689
197690  if( p->pSegments ){
197691    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
197692  }else{
197693    if( 0==p->zSegmentsTbl ){
197694      p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
197695      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
197696    }
197697    rc = sqlite3_blob_open(
197698       p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
197699    );
197700  }
197701
197702  if( rc==SQLITE_OK ){
197703    int nByte = sqlite3_blob_bytes(p->pSegments);
197704    *pnBlob = nByte;
197705    if( paBlob ){
197706      char *aByte = sqlite3_malloc64((i64)nByte + FTS3_NODE_PADDING);
197707      if( !aByte ){
197708        rc = SQLITE_NOMEM;
197709      }else{
197710        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
197711          nByte = FTS3_NODE_CHUNKSIZE;
197712          *pnLoad = nByte;
197713        }
197714        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
197715        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
197716        if( rc!=SQLITE_OK ){
197717          sqlite3_free(aByte);
197718          aByte = 0;
197719        }
197720      }
197721      *paBlob = aByte;
197722    }
197723  }else if( rc==SQLITE_ERROR ){
197724    rc = FTS_CORRUPT_VTAB;
197725  }
197726
197727  return rc;
197728}
197729
197730/*
197731** Close the blob handle at p->pSegments, if it is open. See comments above
197732** the sqlite3Fts3ReadBlock() function for details.
197733*/
197734SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
197735  sqlite3_blob_close(p->pSegments);
197736  p->pSegments = 0;
197737}
197738
197739static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
197740  int nRead;                      /* Number of bytes to read */
197741  int rc;                         /* Return code */
197742
197743  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
197744  rc = sqlite3_blob_read(
197745      pReader->pBlob,
197746      &pReader->aNode[pReader->nPopulate],
197747      nRead,
197748      pReader->nPopulate
197749  );
197750
197751  if( rc==SQLITE_OK ){
197752    pReader->nPopulate += nRead;
197753    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
197754    if( pReader->nPopulate==pReader->nNode ){
197755      sqlite3_blob_close(pReader->pBlob);
197756      pReader->pBlob = 0;
197757      pReader->nPopulate = 0;
197758    }
197759  }
197760  return rc;
197761}
197762
197763static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
197764  int rc = SQLITE_OK;
197765  assert( !pReader->pBlob
197766       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
197767  );
197768  while( pReader->pBlob && rc==SQLITE_OK
197769     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
197770  ){
197771    rc = fts3SegReaderIncrRead(pReader);
197772  }
197773  return rc;
197774}
197775
197776/*
197777** Set an Fts3SegReader cursor to point at EOF.
197778*/
197779static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
197780  if( !fts3SegReaderIsRootOnly(pSeg) ){
197781    sqlite3_free(pSeg->aNode);
197782    sqlite3_blob_close(pSeg->pBlob);
197783    pSeg->pBlob = 0;
197784  }
197785  pSeg->aNode = 0;
197786}
197787
197788/*
197789** Move the iterator passed as the first argument to the next term in the
197790** segment. If successful, SQLITE_OK is returned. If there is no next term,
197791** SQLITE_DONE. Otherwise, an SQLite error code.
197792*/
197793static int fts3SegReaderNext(
197794  Fts3Table *p,
197795  Fts3SegReader *pReader,
197796  int bIncr
197797){
197798  int rc;                         /* Return code of various sub-routines */
197799  char *pNext;                    /* Cursor variable */
197800  int nPrefix;                    /* Number of bytes in term prefix */
197801  int nSuffix;                    /* Number of bytes in term suffix */
197802
197803  if( !pReader->aDoclist ){
197804    pNext = pReader->aNode;
197805  }else{
197806    pNext = &pReader->aDoclist[pReader->nDoclist];
197807  }
197808
197809  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
197810
197811    if( fts3SegReaderIsPending(pReader) ){
197812      Fts3HashElem *pElem = *(pReader->ppNextElem);
197813      sqlite3_free(pReader->aNode);
197814      pReader->aNode = 0;
197815      if( pElem ){
197816        char *aCopy;
197817        PendingList *pList = (PendingList *)fts3HashData(pElem);
197818        int nCopy = pList->nData+1;
197819
197820        int nTerm = fts3HashKeysize(pElem);
197821        if( (nTerm+1)>pReader->nTermAlloc ){
197822          sqlite3_free(pReader->zTerm);
197823          pReader->zTerm = (char*)sqlite3_malloc64(((i64)nTerm+1)*2);
197824          if( !pReader->zTerm ) return SQLITE_NOMEM;
197825          pReader->nTermAlloc = (nTerm+1)*2;
197826        }
197827        memcpy(pReader->zTerm, fts3HashKey(pElem), nTerm);
197828        pReader->zTerm[nTerm] = '\0';
197829        pReader->nTerm = nTerm;
197830
197831        aCopy = (char*)sqlite3_malloc64(nCopy);
197832        if( !aCopy ) return SQLITE_NOMEM;
197833        memcpy(aCopy, pList->aData, nCopy);
197834        pReader->nNode = pReader->nDoclist = nCopy;
197835        pReader->aNode = pReader->aDoclist = aCopy;
197836        pReader->ppNextElem++;
197837        assert( pReader->aNode );
197838      }
197839      return SQLITE_OK;
197840    }
197841
197842    fts3SegReaderSetEof(pReader);
197843
197844    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
197845    ** blocks have already been traversed.  */
197846#ifdef CORRUPT_DB
197847    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock || CORRUPT_DB );
197848#endif
197849    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
197850      return SQLITE_OK;
197851    }
197852
197853    rc = sqlite3Fts3ReadBlock(
197854        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
197855        (bIncr ? &pReader->nPopulate : 0)
197856    );
197857    if( rc!=SQLITE_OK ) return rc;
197858    assert( pReader->pBlob==0 );
197859    if( bIncr && pReader->nPopulate<pReader->nNode ){
197860      pReader->pBlob = p->pSegments;
197861      p->pSegments = 0;
197862    }
197863    pNext = pReader->aNode;
197864  }
197865
197866  assert( !fts3SegReaderIsPending(pReader) );
197867
197868  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
197869  if( rc!=SQLITE_OK ) return rc;
197870
197871  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
197872  ** safe (no risk of overread) even if the node data is corrupted. */
197873  pNext += fts3GetVarint32(pNext, &nPrefix);
197874  pNext += fts3GetVarint32(pNext, &nSuffix);
197875  if( nSuffix<=0
197876   || (&pReader->aNode[pReader->nNode] - pNext)<nSuffix
197877   || nPrefix>pReader->nTerm
197878  ){
197879    return FTS_CORRUPT_VTAB;
197880  }
197881
197882  /* Both nPrefix and nSuffix were read by fts3GetVarint32() and so are
197883  ** between 0 and 0x7FFFFFFF. But the sum of the two may cause integer
197884  ** overflow - hence the (i64) casts.  */
197885  if( (i64)nPrefix+nSuffix>(i64)pReader->nTermAlloc ){
197886    i64 nNew = ((i64)nPrefix+nSuffix)*2;
197887    char *zNew = sqlite3_realloc64(pReader->zTerm, nNew);
197888    if( !zNew ){
197889      return SQLITE_NOMEM;
197890    }
197891    pReader->zTerm = zNew;
197892    pReader->nTermAlloc = nNew;
197893  }
197894
197895  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
197896  if( rc!=SQLITE_OK ) return rc;
197897
197898  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
197899  pReader->nTerm = nPrefix+nSuffix;
197900  pNext += nSuffix;
197901  pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
197902  pReader->aDoclist = pNext;
197903  pReader->pOffsetList = 0;
197904
197905  /* Check that the doclist does not appear to extend past the end of the
197906  ** b-tree node. And that the final byte of the doclist is 0x00. If either
197907  ** of these statements is untrue, then the data structure is corrupt.
197908  */
197909  if( pReader->nDoclist > pReader->nNode-(pReader->aDoclist-pReader->aNode)
197910   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
197911   || pReader->nDoclist==0
197912  ){
197913    return FTS_CORRUPT_VTAB;
197914  }
197915  return SQLITE_OK;
197916}
197917
197918/*
197919** Set the SegReader to point to the first docid in the doclist associated
197920** with the current term.
197921*/
197922static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
197923  int rc = SQLITE_OK;
197924  assert( pReader->aDoclist );
197925  assert( !pReader->pOffsetList );
197926  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
197927    u8 bEof = 0;
197928    pReader->iDocid = 0;
197929    pReader->nOffsetList = 0;
197930    sqlite3Fts3DoclistPrev(0,
197931        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
197932        &pReader->iDocid, &pReader->nOffsetList, &bEof
197933    );
197934  }else{
197935    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
197936    if( rc==SQLITE_OK ){
197937      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
197938      pReader->pOffsetList = &pReader->aDoclist[n];
197939    }
197940  }
197941  return rc;
197942}
197943
197944/*
197945** Advance the SegReader to point to the next docid in the doclist
197946** associated with the current term.
197947**
197948** If arguments ppOffsetList and pnOffsetList are not NULL, then
197949** *ppOffsetList is set to point to the first column-offset list
197950** in the doclist entry (i.e. immediately past the docid varint).
197951** *pnOffsetList is set to the length of the set of column-offset
197952** lists, not including the nul-terminator byte. For example:
197953*/
197954static int fts3SegReaderNextDocid(
197955  Fts3Table *pTab,
197956  Fts3SegReader *pReader,         /* Reader to advance to next docid */
197957  char **ppOffsetList,            /* OUT: Pointer to current position-list */
197958  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
197959){
197960  int rc = SQLITE_OK;
197961  char *p = pReader->pOffsetList;
197962  char c = 0;
197963
197964  assert( p );
197965
197966  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
197967    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
197968    ** Pending-terms doclists are always built up in ascending order, so
197969    ** we have to iterate through them backwards here. */
197970    u8 bEof = 0;
197971    if( ppOffsetList ){
197972      *ppOffsetList = pReader->pOffsetList;
197973      *pnOffsetList = pReader->nOffsetList - 1;
197974    }
197975    sqlite3Fts3DoclistPrev(0,
197976        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
197977        &pReader->nOffsetList, &bEof
197978    );
197979    if( bEof ){
197980      pReader->pOffsetList = 0;
197981    }else{
197982      pReader->pOffsetList = p;
197983    }
197984  }else{
197985    char *pEnd = &pReader->aDoclist[pReader->nDoclist];
197986
197987    /* Pointer p currently points at the first byte of an offset list. The
197988    ** following block advances it to point one byte past the end of
197989    ** the same offset list. */
197990    while( 1 ){
197991
197992      /* The following line of code (and the "p++" below the while() loop) is
197993      ** normally all that is required to move pointer p to the desired
197994      ** position. The exception is if this node is being loaded from disk
197995      ** incrementally and pointer "p" now points to the first byte past
197996      ** the populated part of pReader->aNode[].
197997      */
197998      while( *p | c ) c = *p++ & 0x80;
197999      assert( *p==0 );
198000
198001      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
198002      rc = fts3SegReaderIncrRead(pReader);
198003      if( rc!=SQLITE_OK ) return rc;
198004    }
198005    p++;
198006
198007    /* If required, populate the output variables with a pointer to and the
198008    ** size of the previous offset-list.
198009    */
198010    if( ppOffsetList ){
198011      *ppOffsetList = pReader->pOffsetList;
198012      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
198013    }
198014
198015    /* List may have been edited in place by fts3EvalNearTrim() */
198016    while( p<pEnd && *p==0 ) p++;
198017
198018    /* If there are no more entries in the doclist, set pOffsetList to
198019    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
198020    ** Fts3SegReader.pOffsetList to point to the next offset list before
198021    ** returning.
198022    */
198023    if( p>=pEnd ){
198024      pReader->pOffsetList = 0;
198025    }else{
198026      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
198027      if( rc==SQLITE_OK ){
198028        u64 iDelta;
198029        pReader->pOffsetList = p + sqlite3Fts3GetVarintU(p, &iDelta);
198030        if( pTab->bDescIdx ){
198031          pReader->iDocid = (i64)((u64)pReader->iDocid - iDelta);
198032        }else{
198033          pReader->iDocid = (i64)((u64)pReader->iDocid + iDelta);
198034        }
198035      }
198036    }
198037  }
198038
198039  return rc;
198040}
198041
198042
198043SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
198044  Fts3Cursor *pCsr,
198045  Fts3MultiSegReader *pMsr,
198046  int *pnOvfl
198047){
198048  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
198049  int nOvfl = 0;
198050  int ii;
198051  int rc = SQLITE_OK;
198052  int pgsz = p->nPgsz;
198053
198054  assert( p->bFts4 );
198055  assert( pgsz>0 );
198056
198057  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
198058    Fts3SegReader *pReader = pMsr->apSegment[ii];
198059    if( !fts3SegReaderIsPending(pReader)
198060     && !fts3SegReaderIsRootOnly(pReader)
198061    ){
198062      sqlite3_int64 jj;
198063      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
198064        int nBlob;
198065        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
198066        if( rc!=SQLITE_OK ) break;
198067        if( (nBlob+35)>pgsz ){
198068          nOvfl += (nBlob + 34)/pgsz;
198069        }
198070      }
198071    }
198072  }
198073  *pnOvfl = nOvfl;
198074  return rc;
198075}
198076
198077/*
198078** Free all allocations associated with the iterator passed as the
198079** second argument.
198080*/
198081SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
198082  if( pReader ){
198083    sqlite3_free(pReader->zTerm);
198084    if( !fts3SegReaderIsRootOnly(pReader) ){
198085      sqlite3_free(pReader->aNode);
198086    }
198087    sqlite3_blob_close(pReader->pBlob);
198088  }
198089  sqlite3_free(pReader);
198090}
198091
198092/*
198093** Allocate a new SegReader object.
198094*/
198095SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
198096  int iAge,                       /* Segment "age". */
198097  int bLookup,                    /* True for a lookup only */
198098  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
198099  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
198100  sqlite3_int64 iEndBlock,        /* Final block of segment */
198101  const char *zRoot,              /* Buffer containing root node */
198102  int nRoot,                      /* Size of buffer containing root node */
198103  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
198104){
198105  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
198106  int nExtra = 0;                 /* Bytes to allocate segment root node */
198107
198108  assert( zRoot!=0 || nRoot==0 );
198109#ifdef CORRUPT_DB
198110  assert( zRoot!=0 || CORRUPT_DB );
198111#endif
198112
198113  if( iStartLeaf==0 ){
198114    if( iEndLeaf!=0 ) return FTS_CORRUPT_VTAB;
198115    nExtra = nRoot + FTS3_NODE_PADDING;
198116  }
198117
198118  pReader = (Fts3SegReader *)sqlite3_malloc64(sizeof(Fts3SegReader) + nExtra);
198119  if( !pReader ){
198120    return SQLITE_NOMEM;
198121  }
198122  memset(pReader, 0, sizeof(Fts3SegReader));
198123  pReader->iIdx = iAge;
198124  pReader->bLookup = bLookup!=0;
198125  pReader->iStartBlock = iStartLeaf;
198126  pReader->iLeafEndBlock = iEndLeaf;
198127  pReader->iEndBlock = iEndBlock;
198128
198129  if( nExtra ){
198130    /* The entire segment is stored in the root node. */
198131    pReader->aNode = (char *)&pReader[1];
198132    pReader->rootOnly = 1;
198133    pReader->nNode = nRoot;
198134    if( nRoot ) memcpy(pReader->aNode, zRoot, nRoot);
198135    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
198136  }else{
198137    pReader->iCurrentBlock = iStartLeaf-1;
198138  }
198139  *ppReader = pReader;
198140  return SQLITE_OK;
198141}
198142
198143/*
198144** This is a comparison function used as a qsort() callback when sorting
198145** an array of pending terms by term. This occurs as part of flushing
198146** the contents of the pending-terms hash table to the database.
198147*/
198148static int SQLITE_CDECL fts3CompareElemByTerm(
198149  const void *lhs,
198150  const void *rhs
198151){
198152  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
198153  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
198154  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
198155  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
198156
198157  int n = (n1<n2 ? n1 : n2);
198158  int c = memcmp(z1, z2, n);
198159  if( c==0 ){
198160    c = n1 - n2;
198161  }
198162  return c;
198163}
198164
198165/*
198166** This function is used to allocate an Fts3SegReader that iterates through
198167** a subset of the terms stored in the Fts3Table.pendingTerms array.
198168**
198169** If the isPrefixIter parameter is zero, then the returned SegReader iterates
198170** through each term in the pending-terms table. Or, if isPrefixIter is
198171** non-zero, it iterates through each term and its prefixes. For example, if
198172** the pending terms hash table contains the terms "sqlite", "mysql" and
198173** "firebird", then the iterator visits the following 'terms' (in the order
198174** shown):
198175**
198176**   f fi fir fire fireb firebi firebir firebird
198177**   m my mys mysq mysql
198178**   s sq sql sqli sqlit sqlite
198179**
198180** Whereas if isPrefixIter is zero, the terms visited are:
198181**
198182**   firebird mysql sqlite
198183*/
198184SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
198185  Fts3Table *p,                   /* Virtual table handle */
198186  int iIndex,                     /* Index for p->aIndex */
198187  const char *zTerm,              /* Term to search for */
198188  int nTerm,                      /* Size of buffer zTerm */
198189  int bPrefix,                    /* True for a prefix iterator */
198190  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
198191){
198192  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
198193  Fts3HashElem *pE;               /* Iterator variable */
198194  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
198195  int nElem = 0;                  /* Size of array at aElem */
198196  int rc = SQLITE_OK;             /* Return Code */
198197  Fts3Hash *pHash;
198198
198199  pHash = &p->aIndex[iIndex].hPending;
198200  if( bPrefix ){
198201    int nAlloc = 0;               /* Size of allocated array at aElem */
198202
198203    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
198204      char *zKey = (char *)fts3HashKey(pE);
198205      int nKey = fts3HashKeysize(pE);
198206      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
198207        if( nElem==nAlloc ){
198208          Fts3HashElem **aElem2;
198209          nAlloc += 16;
198210          aElem2 = (Fts3HashElem **)sqlite3_realloc64(
198211              aElem, nAlloc*sizeof(Fts3HashElem *)
198212          );
198213          if( !aElem2 ){
198214            rc = SQLITE_NOMEM;
198215            nElem = 0;
198216            break;
198217          }
198218          aElem = aElem2;
198219        }
198220
198221        aElem[nElem++] = pE;
198222      }
198223    }
198224
198225    /* If more than one term matches the prefix, sort the Fts3HashElem
198226    ** objects in term order using qsort(). This uses the same comparison
198227    ** callback as is used when flushing terms to disk.
198228    */
198229    if( nElem>1 ){
198230      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
198231    }
198232
198233  }else{
198234    /* The query is a simple term lookup that matches at most one term in
198235    ** the index. All that is required is a straight hash-lookup.
198236    **
198237    ** Because the stack address of pE may be accessed via the aElem pointer
198238    ** below, the "Fts3HashElem *pE" must be declared so that it is valid
198239    ** within this entire function, not just this "else{...}" block.
198240    */
198241    pE = fts3HashFindElem(pHash, zTerm, nTerm);
198242    if( pE ){
198243      aElem = &pE;
198244      nElem = 1;
198245    }
198246  }
198247
198248  if( nElem>0 ){
198249    sqlite3_int64 nByte;
198250    nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
198251    pReader = (Fts3SegReader *)sqlite3_malloc64(nByte);
198252    if( !pReader ){
198253      rc = SQLITE_NOMEM;
198254    }else{
198255      memset(pReader, 0, nByte);
198256      pReader->iIdx = 0x7FFFFFFF;
198257      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
198258      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
198259    }
198260  }
198261
198262  if( bPrefix ){
198263    sqlite3_free(aElem);
198264  }
198265  *ppReader = pReader;
198266  return rc;
198267}
198268
198269/*
198270** Compare the entries pointed to by two Fts3SegReader structures.
198271** Comparison is as follows:
198272**
198273**   1) EOF is greater than not EOF.
198274**
198275**   2) The current terms (if any) are compared using memcmp(). If one
198276**      term is a prefix of another, the longer term is considered the
198277**      larger.
198278**
198279**   3) By segment age. An older segment is considered larger.
198280*/
198281static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
198282  int rc;
198283  if( pLhs->aNode && pRhs->aNode ){
198284    int rc2 = pLhs->nTerm - pRhs->nTerm;
198285    if( rc2<0 ){
198286      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
198287    }else{
198288      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
198289    }
198290    if( rc==0 ){
198291      rc = rc2;
198292    }
198293  }else{
198294    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
198295  }
198296  if( rc==0 ){
198297    rc = pRhs->iIdx - pLhs->iIdx;
198298  }
198299  assert_fts3_nc( rc!=0 );
198300  return rc;
198301}
198302
198303/*
198304** A different comparison function for SegReader structures. In this
198305** version, it is assumed that each SegReader points to an entry in
198306** a doclist for identical terms. Comparison is made as follows:
198307**
198308**   1) EOF (end of doclist in this case) is greater than not EOF.
198309**
198310**   2) By current docid.
198311**
198312**   3) By segment age. An older segment is considered larger.
198313*/
198314static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
198315  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
198316  if( rc==0 ){
198317    if( pLhs->iDocid==pRhs->iDocid ){
198318      rc = pRhs->iIdx - pLhs->iIdx;
198319    }else{
198320      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
198321    }
198322  }
198323  assert( pLhs->aNode && pRhs->aNode );
198324  return rc;
198325}
198326static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
198327  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
198328  if( rc==0 ){
198329    if( pLhs->iDocid==pRhs->iDocid ){
198330      rc = pRhs->iIdx - pLhs->iIdx;
198331    }else{
198332      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
198333    }
198334  }
198335  assert( pLhs->aNode && pRhs->aNode );
198336  return rc;
198337}
198338
198339/*
198340** Compare the term that the Fts3SegReader object passed as the first argument
198341** points to with the term specified by arguments zTerm and nTerm.
198342**
198343** If the pSeg iterator is already at EOF, return 0. Otherwise, return
198344** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
198345** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
198346*/
198347static int fts3SegReaderTermCmp(
198348  Fts3SegReader *pSeg,            /* Segment reader object */
198349  const char *zTerm,              /* Term to compare to */
198350  int nTerm                       /* Size of term zTerm in bytes */
198351){
198352  int res = 0;
198353  if( pSeg->aNode ){
198354    if( pSeg->nTerm>nTerm ){
198355      res = memcmp(pSeg->zTerm, zTerm, nTerm);
198356    }else{
198357      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
198358    }
198359    if( res==0 ){
198360      res = pSeg->nTerm-nTerm;
198361    }
198362  }
198363  return res;
198364}
198365
198366/*
198367** Argument apSegment is an array of nSegment elements. It is known that
198368** the final (nSegment-nSuspect) members are already in sorted order
198369** (according to the comparison function provided). This function shuffles
198370** the array around until all entries are in sorted order.
198371*/
198372static void fts3SegReaderSort(
198373  Fts3SegReader **apSegment,                     /* Array to sort entries of */
198374  int nSegment,                                  /* Size of apSegment array */
198375  int nSuspect,                                  /* Unsorted entry count */
198376  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
198377){
198378  int i;                          /* Iterator variable */
198379
198380  assert( nSuspect<=nSegment );
198381
198382  if( nSuspect==nSegment ) nSuspect--;
198383  for(i=nSuspect-1; i>=0; i--){
198384    int j;
198385    for(j=i; j<(nSegment-1); j++){
198386      Fts3SegReader *pTmp;
198387      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
198388      pTmp = apSegment[j+1];
198389      apSegment[j+1] = apSegment[j];
198390      apSegment[j] = pTmp;
198391    }
198392  }
198393
198394#ifndef NDEBUG
198395  /* Check that the list really is sorted now. */
198396  for(i=0; i<(nSuspect-1); i++){
198397    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
198398  }
198399#endif
198400}
198401
198402/*
198403** Insert a record into the %_segments table.
198404*/
198405static int fts3WriteSegment(
198406  Fts3Table *p,                   /* Virtual table handle */
198407  sqlite3_int64 iBlock,           /* Block id for new block */
198408  char *z,                        /* Pointer to buffer containing block data */
198409  int n                           /* Size of buffer z in bytes */
198410){
198411  sqlite3_stmt *pStmt;
198412  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
198413  if( rc==SQLITE_OK ){
198414    sqlite3_bind_int64(pStmt, 1, iBlock);
198415    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
198416    sqlite3_step(pStmt);
198417    rc = sqlite3_reset(pStmt);
198418    sqlite3_bind_null(pStmt, 2);
198419  }
198420  return rc;
198421}
198422
198423/*
198424** Find the largest relative level number in the table. If successful, set
198425** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
198426** set *pnMax to zero and return an SQLite error code.
198427*/
198428SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
198429  int rc;
198430  int mxLevel = 0;
198431  sqlite3_stmt *pStmt = 0;
198432
198433  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
198434  if( rc==SQLITE_OK ){
198435    if( SQLITE_ROW==sqlite3_step(pStmt) ){
198436      mxLevel = sqlite3_column_int(pStmt, 0);
198437    }
198438    rc = sqlite3_reset(pStmt);
198439  }
198440  *pnMax = mxLevel;
198441  return rc;
198442}
198443
198444/*
198445** Insert a record into the %_segdir table.
198446*/
198447static int fts3WriteSegdir(
198448  Fts3Table *p,                   /* Virtual table handle */
198449  sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
198450  int iIdx,                       /* Value for "idx" field */
198451  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
198452  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
198453  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
198454  sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
198455  char *zRoot,                    /* Blob value for "root" field */
198456  int nRoot                       /* Number of bytes in buffer zRoot */
198457){
198458  sqlite3_stmt *pStmt;
198459  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
198460  if( rc==SQLITE_OK ){
198461    sqlite3_bind_int64(pStmt, 1, iLevel);
198462    sqlite3_bind_int(pStmt, 2, iIdx);
198463    sqlite3_bind_int64(pStmt, 3, iStartBlock);
198464    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
198465    if( nLeafData==0 ){
198466      sqlite3_bind_int64(pStmt, 5, iEndBlock);
198467    }else{
198468      char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
198469      if( !zEnd ) return SQLITE_NOMEM;
198470      sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
198471    }
198472    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
198473    sqlite3_step(pStmt);
198474    rc = sqlite3_reset(pStmt);
198475    sqlite3_bind_null(pStmt, 6);
198476  }
198477  return rc;
198478}
198479
198480/*
198481** Return the size of the common prefix (if any) shared by zPrev and
198482** zNext, in bytes. For example,
198483**
198484**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
198485**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
198486**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
198487*/
198488static int fts3PrefixCompress(
198489  const char *zPrev,              /* Buffer containing previous term */
198490  int nPrev,                      /* Size of buffer zPrev in bytes */
198491  const char *zNext,              /* Buffer containing next term */
198492  int nNext                       /* Size of buffer zNext in bytes */
198493){
198494  int n;
198495  for(n=0; n<nPrev && n<nNext && zPrev[n]==zNext[n]; n++);
198496  assert_fts3_nc( n<nNext );
198497  return n;
198498}
198499
198500/*
198501** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
198502** (according to memcmp) than the previous term.
198503*/
198504static int fts3NodeAddTerm(
198505  Fts3Table *p,                   /* Virtual table handle */
198506  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
198507  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
198508  const char *zTerm,              /* Pointer to buffer containing term */
198509  int nTerm                       /* Size of term in bytes */
198510){
198511  SegmentNode *pTree = *ppTree;
198512  int rc;
198513  SegmentNode *pNew;
198514
198515  /* First try to append the term to the current node. Return early if
198516  ** this is possible.
198517  */
198518  if( pTree ){
198519    int nData = pTree->nData;     /* Current size of node in bytes */
198520    int nReq = nData;             /* Required space after adding zTerm */
198521    int nPrefix;                  /* Number of bytes of prefix compression */
198522    int nSuffix;                  /* Suffix length */
198523
198524    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
198525    nSuffix = nTerm-nPrefix;
198526
198527    /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of
198528    ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when
198529    ** compared with BINARY collation. This indicates corruption.  */
198530    if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
198531
198532    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
198533    if( nReq<=p->nNodeSize || !pTree->zTerm ){
198534
198535      if( nReq>p->nNodeSize ){
198536        /* An unusual case: this is the first term to be added to the node
198537        ** and the static node buffer (p->nNodeSize bytes) is not large
198538        ** enough. Use a separately malloced buffer instead This wastes
198539        ** p->nNodeSize bytes, but since this scenario only comes about when
198540        ** the database contain two terms that share a prefix of almost 2KB,
198541        ** this is not expected to be a serious problem.
198542        */
198543        assert( pTree->aData==(char *)&pTree[1] );
198544        pTree->aData = (char *)sqlite3_malloc64(nReq);
198545        if( !pTree->aData ){
198546          return SQLITE_NOMEM;
198547        }
198548      }
198549
198550      if( pTree->zTerm ){
198551        /* There is no prefix-length field for first term in a node */
198552        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
198553      }
198554
198555      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
198556      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
198557      pTree->nData = nData + nSuffix;
198558      pTree->nEntry++;
198559
198560      if( isCopyTerm ){
198561        if( pTree->nMalloc<nTerm ){
198562          char *zNew = sqlite3_realloc64(pTree->zMalloc, (i64)nTerm*2);
198563          if( !zNew ){
198564            return SQLITE_NOMEM;
198565          }
198566          pTree->nMalloc = nTerm*2;
198567          pTree->zMalloc = zNew;
198568        }
198569        pTree->zTerm = pTree->zMalloc;
198570        memcpy(pTree->zTerm, zTerm, nTerm);
198571        pTree->nTerm = nTerm;
198572      }else{
198573        pTree->zTerm = (char *)zTerm;
198574        pTree->nTerm = nTerm;
198575      }
198576      return SQLITE_OK;
198577    }
198578  }
198579
198580  /* If control flows to here, it was not possible to append zTerm to the
198581  ** current node. Create a new node (a right-sibling of the current node).
198582  ** If this is the first node in the tree, the term is added to it.
198583  **
198584  ** Otherwise, the term is not added to the new node, it is left empty for
198585  ** now. Instead, the term is inserted into the parent of pTree. If pTree
198586  ** has no parent, one is created here.
198587  */
198588  pNew = (SegmentNode *)sqlite3_malloc64(sizeof(SegmentNode) + p->nNodeSize);
198589  if( !pNew ){
198590    return SQLITE_NOMEM;
198591  }
198592  memset(pNew, 0, sizeof(SegmentNode));
198593  pNew->nData = 1 + FTS3_VARINT_MAX;
198594  pNew->aData = (char *)&pNew[1];
198595
198596  if( pTree ){
198597    SegmentNode *pParent = pTree->pParent;
198598    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
198599    if( pTree->pParent==0 ){
198600      pTree->pParent = pParent;
198601    }
198602    pTree->pRight = pNew;
198603    pNew->pLeftmost = pTree->pLeftmost;
198604    pNew->pParent = pParent;
198605    pNew->zMalloc = pTree->zMalloc;
198606    pNew->nMalloc = pTree->nMalloc;
198607    pTree->zMalloc = 0;
198608  }else{
198609    pNew->pLeftmost = pNew;
198610    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
198611  }
198612
198613  *ppTree = pNew;
198614  return rc;
198615}
198616
198617/*
198618** Helper function for fts3NodeWrite().
198619*/
198620static int fts3TreeFinishNode(
198621  SegmentNode *pTree,
198622  int iHeight,
198623  sqlite3_int64 iLeftChild
198624){
198625  int nStart;
198626  assert( iHeight>=1 && iHeight<128 );
198627  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
198628  pTree->aData[nStart] = (char)iHeight;
198629  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
198630  return nStart;
198631}
198632
198633/*
198634** Write the buffer for the segment node pTree and all of its peers to the
198635** database. Then call this function recursively to write the parent of
198636** pTree and its peers to the database.
198637**
198638** Except, if pTree is a root node, do not write it to the database. Instead,
198639** set output variables *paRoot and *pnRoot to contain the root node.
198640**
198641** If successful, SQLITE_OK is returned and output variable *piLast is
198642** set to the largest blockid written to the database (or zero if no
198643** blocks were written to the db). Otherwise, an SQLite error code is
198644** returned.
198645*/
198646static int fts3NodeWrite(
198647  Fts3Table *p,                   /* Virtual table handle */
198648  SegmentNode *pTree,             /* SegmentNode handle */
198649  int iHeight,                    /* Height of this node in tree */
198650  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
198651  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
198652  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
198653  char **paRoot,                  /* OUT: Data for root node */
198654  int *pnRoot                     /* OUT: Size of root node in bytes */
198655){
198656  int rc = SQLITE_OK;
198657
198658  if( !pTree->pParent ){
198659    /* Root node of the tree. */
198660    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
198661    *piLast = iFree-1;
198662    *pnRoot = pTree->nData - nStart;
198663    *paRoot = &pTree->aData[nStart];
198664  }else{
198665    SegmentNode *pIter;
198666    sqlite3_int64 iNextFree = iFree;
198667    sqlite3_int64 iNextLeaf = iLeaf;
198668    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
198669      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
198670      int nWrite = pIter->nData - nStart;
198671
198672      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
198673      iNextFree++;
198674      iNextLeaf += (pIter->nEntry+1);
198675    }
198676    if( rc==SQLITE_OK ){
198677      assert( iNextLeaf==iFree );
198678      rc = fts3NodeWrite(
198679          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
198680      );
198681    }
198682  }
198683
198684  return rc;
198685}
198686
198687/*
198688** Free all memory allocations associated with the tree pTree.
198689*/
198690static void fts3NodeFree(SegmentNode *pTree){
198691  if( pTree ){
198692    SegmentNode *p = pTree->pLeftmost;
198693    fts3NodeFree(p->pParent);
198694    while( p ){
198695      SegmentNode *pRight = p->pRight;
198696      if( p->aData!=(char *)&p[1] ){
198697        sqlite3_free(p->aData);
198698      }
198699      assert( pRight==0 || p->zMalloc==0 );
198700      sqlite3_free(p->zMalloc);
198701      sqlite3_free(p);
198702      p = pRight;
198703    }
198704  }
198705}
198706
198707/*
198708** Add a term to the segment being constructed by the SegmentWriter object
198709** *ppWriter. When adding the first term to a segment, *ppWriter should
198710** be passed NULL. This function will allocate a new SegmentWriter object
198711** and return it via the input/output variable *ppWriter in this case.
198712**
198713** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
198714*/
198715static int fts3SegWriterAdd(
198716  Fts3Table *p,                   /* Virtual table handle */
198717  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
198718  int isCopyTerm,                 /* True if buffer zTerm must be copied */
198719  const char *zTerm,              /* Pointer to buffer containing term */
198720  int nTerm,                      /* Size of term in bytes */
198721  const char *aDoclist,           /* Pointer to buffer containing doclist */
198722  int nDoclist                    /* Size of doclist in bytes */
198723){
198724  int nPrefix;                    /* Size of term prefix in bytes */
198725  int nSuffix;                    /* Size of term suffix in bytes */
198726  i64 nReq;                       /* Number of bytes required on leaf page */
198727  int nData;
198728  SegmentWriter *pWriter = *ppWriter;
198729
198730  if( !pWriter ){
198731    int rc;
198732    sqlite3_stmt *pStmt;
198733
198734    /* Allocate the SegmentWriter structure */
198735    pWriter = (SegmentWriter *)sqlite3_malloc64(sizeof(SegmentWriter));
198736    if( !pWriter ) return SQLITE_NOMEM;
198737    memset(pWriter, 0, sizeof(SegmentWriter));
198738    *ppWriter = pWriter;
198739
198740    /* Allocate a buffer in which to accumulate data */
198741    pWriter->aData = (char *)sqlite3_malloc64(p->nNodeSize);
198742    if( !pWriter->aData ) return SQLITE_NOMEM;
198743    pWriter->nSize = p->nNodeSize;
198744
198745    /* Find the next free blockid in the %_segments table */
198746    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
198747    if( rc!=SQLITE_OK ) return rc;
198748    if( SQLITE_ROW==sqlite3_step(pStmt) ){
198749      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
198750      pWriter->iFirst = pWriter->iFree;
198751    }
198752    rc = sqlite3_reset(pStmt);
198753    if( rc!=SQLITE_OK ) return rc;
198754  }
198755  nData = pWriter->nData;
198756
198757  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
198758  nSuffix = nTerm-nPrefix;
198759
198760  /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of
198761  ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when
198762  ** compared with BINARY collation. This indicates corruption.  */
198763  if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
198764
198765  /* Figure out how many bytes are required by this new entry */
198766  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
198767    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
198768    nSuffix +                               /* Term suffix */
198769    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
198770    nDoclist;                               /* Doclist data */
198771
198772  if( nData>0 && nData+nReq>p->nNodeSize ){
198773    int rc;
198774
198775    /* The current leaf node is full. Write it out to the database. */
198776    if( pWriter->iFree==LARGEST_INT64 ) return FTS_CORRUPT_VTAB;
198777    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
198778    if( rc!=SQLITE_OK ) return rc;
198779    p->nLeafAdd++;
198780
198781    /* Add the current term to the interior node tree. The term added to
198782    ** the interior tree must:
198783    **
198784    **   a) be greater than the largest term on the leaf node just written
198785    **      to the database (still available in pWriter->zTerm), and
198786    **
198787    **   b) be less than or equal to the term about to be added to the new
198788    **      leaf node (zTerm/nTerm).
198789    **
198790    ** In other words, it must be the prefix of zTerm 1 byte longer than
198791    ** the common prefix (if any) of zTerm and pWriter->zTerm.
198792    */
198793    assert( nPrefix<nTerm );
198794    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
198795    if( rc!=SQLITE_OK ) return rc;
198796
198797    nData = 0;
198798    pWriter->nTerm = 0;
198799
198800    nPrefix = 0;
198801    nSuffix = nTerm;
198802    nReq = 1 +                              /* varint containing prefix size */
198803      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
198804      nTerm +                               /* Term suffix */
198805      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
198806      nDoclist;                             /* Doclist data */
198807  }
198808
198809  /* Increase the total number of bytes written to account for the new entry. */
198810  pWriter->nLeafData += nReq;
198811
198812  /* If the buffer currently allocated is too small for this entry, realloc
198813  ** the buffer to make it large enough.
198814  */
198815  if( nReq>pWriter->nSize ){
198816    char *aNew = sqlite3_realloc64(pWriter->aData, nReq);
198817    if( !aNew ) return SQLITE_NOMEM;
198818    pWriter->aData = aNew;
198819    pWriter->nSize = nReq;
198820  }
198821  assert( nData+nReq<=pWriter->nSize );
198822
198823  /* Append the prefix-compressed term and doclist to the buffer. */
198824  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
198825  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
198826  assert( nSuffix>0 );
198827  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
198828  nData += nSuffix;
198829  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
198830  assert( nDoclist>0 );
198831  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
198832  pWriter->nData = nData + nDoclist;
198833
198834  /* Save the current term so that it can be used to prefix-compress the next.
198835  ** If the isCopyTerm parameter is true, then the buffer pointed to by
198836  ** zTerm is transient, so take a copy of the term data. Otherwise, just
198837  ** store a copy of the pointer.
198838  */
198839  if( isCopyTerm ){
198840    if( nTerm>pWriter->nMalloc ){
198841      char *zNew = sqlite3_realloc64(pWriter->zMalloc, (i64)nTerm*2);
198842      if( !zNew ){
198843        return SQLITE_NOMEM;
198844      }
198845      pWriter->nMalloc = nTerm*2;
198846      pWriter->zMalloc = zNew;
198847      pWriter->zTerm = zNew;
198848    }
198849    assert( pWriter->zTerm==pWriter->zMalloc );
198850    assert( nTerm>0 );
198851    memcpy(pWriter->zTerm, zTerm, nTerm);
198852  }else{
198853    pWriter->zTerm = (char *)zTerm;
198854  }
198855  pWriter->nTerm = nTerm;
198856
198857  return SQLITE_OK;
198858}
198859
198860/*
198861** Flush all data associated with the SegmentWriter object pWriter to the
198862** database. This function must be called after all terms have been added
198863** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
198864** returned. Otherwise, an SQLite error code.
198865*/
198866static int fts3SegWriterFlush(
198867  Fts3Table *p,                   /* Virtual table handle */
198868  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
198869  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
198870  int iIdx                        /* Value for 'idx' column of %_segdir */
198871){
198872  int rc;                         /* Return code */
198873  if( pWriter->pTree ){
198874    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
198875    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
198876    char *zRoot = NULL;           /* Pointer to buffer containing root node */
198877    int nRoot = 0;                /* Size of buffer zRoot */
198878
198879    iLastLeaf = pWriter->iFree;
198880    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
198881    if( rc==SQLITE_OK ){
198882      rc = fts3NodeWrite(p, pWriter->pTree, 1,
198883          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
198884    }
198885    if( rc==SQLITE_OK ){
198886      rc = fts3WriteSegdir(p, iLevel, iIdx,
198887          pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
198888    }
198889  }else{
198890    /* The entire tree fits on the root node. Write it to the segdir table. */
198891    rc = fts3WriteSegdir(p, iLevel, iIdx,
198892        0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
198893  }
198894  p->nLeafAdd++;
198895  return rc;
198896}
198897
198898/*
198899** Release all memory held by the SegmentWriter object passed as the
198900** first argument.
198901*/
198902static void fts3SegWriterFree(SegmentWriter *pWriter){
198903  if( pWriter ){
198904    sqlite3_free(pWriter->aData);
198905    sqlite3_free(pWriter->zMalloc);
198906    fts3NodeFree(pWriter->pTree);
198907    sqlite3_free(pWriter);
198908  }
198909}
198910
198911/*
198912** The first value in the apVal[] array is assumed to contain an integer.
198913** This function tests if there exist any documents with docid values that
198914** are different from that integer. i.e. if deleting the document with docid
198915** pRowid would mean the FTS3 table were empty.
198916**
198917** If successful, *pisEmpty is set to true if the table is empty except for
198918** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
198919** error occurs, an SQLite error code is returned.
198920*/
198921static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
198922  sqlite3_stmt *pStmt;
198923  int rc;
198924  if( p->zContentTbl ){
198925    /* If using the content=xxx option, assume the table is never empty */
198926    *pisEmpty = 0;
198927    rc = SQLITE_OK;
198928  }else{
198929    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
198930    if( rc==SQLITE_OK ){
198931      if( SQLITE_ROW==sqlite3_step(pStmt) ){
198932        *pisEmpty = sqlite3_column_int(pStmt, 0);
198933      }
198934      rc = sqlite3_reset(pStmt);
198935    }
198936  }
198937  return rc;
198938}
198939
198940/*
198941** Set *pnMax to the largest segment level in the database for the index
198942** iIndex.
198943**
198944** Segment levels are stored in the 'level' column of the %_segdir table.
198945**
198946** Return SQLITE_OK if successful, or an SQLite error code if not.
198947*/
198948static int fts3SegmentMaxLevel(
198949  Fts3Table *p,
198950  int iLangid,
198951  int iIndex,
198952  sqlite3_int64 *pnMax
198953){
198954  sqlite3_stmt *pStmt;
198955  int rc;
198956  assert( iIndex>=0 && iIndex<p->nIndex );
198957
198958  /* Set pStmt to the compiled version of:
198959  **
198960  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
198961  **
198962  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
198963  */
198964  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
198965  if( rc!=SQLITE_OK ) return rc;
198966  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
198967  sqlite3_bind_int64(pStmt, 2,
198968      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
198969  );
198970  if( SQLITE_ROW==sqlite3_step(pStmt) ){
198971    *pnMax = sqlite3_column_int64(pStmt, 0);
198972  }
198973  return sqlite3_reset(pStmt);
198974}
198975
198976/*
198977** iAbsLevel is an absolute level that may be assumed to exist within
198978** the database. This function checks if it is the largest level number
198979** within its index. Assuming no error occurs, *pbMax is set to 1 if
198980** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
198981** is returned. If an error occurs, an error code is returned and the
198982** final value of *pbMax is undefined.
198983*/
198984static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
198985
198986  /* Set pStmt to the compiled version of:
198987  **
198988  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
198989  **
198990  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
198991  */
198992  sqlite3_stmt *pStmt;
198993  int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
198994  if( rc!=SQLITE_OK ) return rc;
198995  sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
198996  sqlite3_bind_int64(pStmt, 2,
198997      (((u64)iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
198998  );
198999
199000  *pbMax = 0;
199001  if( SQLITE_ROW==sqlite3_step(pStmt) ){
199002    *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
199003  }
199004  return sqlite3_reset(pStmt);
199005}
199006
199007/*
199008** Delete all entries in the %_segments table associated with the segment
199009** opened with seg-reader pSeg. This function does not affect the contents
199010** of the %_segdir table.
199011*/
199012static int fts3DeleteSegment(
199013  Fts3Table *p,                   /* FTS table handle */
199014  Fts3SegReader *pSeg             /* Segment to delete */
199015){
199016  int rc = SQLITE_OK;             /* Return code */
199017  if( pSeg->iStartBlock ){
199018    sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
199019    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
199020    if( rc==SQLITE_OK ){
199021      sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
199022      sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
199023      sqlite3_step(pDelete);
199024      rc = sqlite3_reset(pDelete);
199025    }
199026  }
199027  return rc;
199028}
199029
199030/*
199031** This function is used after merging multiple segments into a single large
199032** segment to delete the old, now redundant, segment b-trees. Specifically,
199033** it:
199034**
199035**   1) Deletes all %_segments entries for the segments associated with
199036**      each of the SegReader objects in the array passed as the third
199037**      argument, and
199038**
199039**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
199040**      entries regardless of level if (iLevel<0).
199041**
199042** SQLITE_OK is returned if successful, otherwise an SQLite error code.
199043*/
199044static int fts3DeleteSegdir(
199045  Fts3Table *p,                   /* Virtual table handle */
199046  int iLangid,                    /* Language id */
199047  int iIndex,                     /* Index for p->aIndex */
199048  int iLevel,                     /* Level of %_segdir entries to delete */
199049  Fts3SegReader **apSegment,      /* Array of SegReader objects */
199050  int nReader                     /* Size of array apSegment */
199051){
199052  int rc = SQLITE_OK;             /* Return Code */
199053  int i;                          /* Iterator variable */
199054  sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
199055
199056  for(i=0; rc==SQLITE_OK && i<nReader; i++){
199057    rc = fts3DeleteSegment(p, apSegment[i]);
199058  }
199059  if( rc!=SQLITE_OK ){
199060    return rc;
199061  }
199062
199063  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
199064  if( iLevel==FTS3_SEGCURSOR_ALL ){
199065    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
199066    if( rc==SQLITE_OK ){
199067      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
199068      sqlite3_bind_int64(pDelete, 2,
199069          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
199070      );
199071    }
199072  }else{
199073    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
199074    if( rc==SQLITE_OK ){
199075      sqlite3_bind_int64(
199076          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
199077      );
199078    }
199079  }
199080
199081  if( rc==SQLITE_OK ){
199082    sqlite3_step(pDelete);
199083    rc = sqlite3_reset(pDelete);
199084  }
199085
199086  return rc;
199087}
199088
199089/*
199090** When this function is called, buffer *ppList (size *pnList bytes) contains
199091** a position list that may (or may not) feature multiple columns. This
199092** function adjusts the pointer *ppList and the length *pnList so that they
199093** identify the subset of the position list that corresponds to column iCol.
199094**
199095** If there are no entries in the input position list for column iCol, then
199096** *pnList is set to zero before returning.
199097**
199098** If parameter bZero is non-zero, then any part of the input list following
199099** the end of the output list is zeroed before returning.
199100*/
199101static void fts3ColumnFilter(
199102  int iCol,                       /* Column to filter on */
199103  int bZero,                      /* Zero out anything following *ppList */
199104  char **ppList,                  /* IN/OUT: Pointer to position list */
199105  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
199106){
199107  char *pList = *ppList;
199108  int nList = *pnList;
199109  char *pEnd = &pList[nList];
199110  int iCurrent = 0;
199111  char *p = pList;
199112
199113  assert( iCol>=0 );
199114  while( 1 ){
199115    char c = 0;
199116    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
199117
199118    if( iCol==iCurrent ){
199119      nList = (int)(p - pList);
199120      break;
199121    }
199122
199123    nList -= (int)(p - pList);
199124    pList = p;
199125    if( nList<=0 ){
199126      break;
199127    }
199128    p = &pList[1];
199129    p += fts3GetVarint32(p, &iCurrent);
199130  }
199131
199132  if( bZero && (pEnd - &pList[nList])>0){
199133    memset(&pList[nList], 0, pEnd - &pList[nList]);
199134  }
199135  *ppList = pList;
199136  *pnList = nList;
199137}
199138
199139/*
199140** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
199141** existing data). Grow the buffer if required.
199142**
199143** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
199144** trying to resize the buffer, return SQLITE_NOMEM.
199145*/
199146static int fts3MsrBufferData(
199147  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
199148  char *pList,
199149  i64 nList
199150){
199151  if( (nList+FTS3_NODE_PADDING)>pMsr->nBuffer ){
199152    char *pNew;
199153    int nNew = nList*2 + FTS3_NODE_PADDING;
199154    pNew = (char *)sqlite3_realloc64(pMsr->aBuffer, nNew);
199155    if( !pNew ) return SQLITE_NOMEM;
199156    pMsr->aBuffer = pNew;
199157    pMsr->nBuffer = nNew;
199158  }
199159
199160  assert( nList>0 );
199161  memcpy(pMsr->aBuffer, pList, nList);
199162  memset(&pMsr->aBuffer[nList], 0, FTS3_NODE_PADDING);
199163  return SQLITE_OK;
199164}
199165
199166SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
199167  Fts3Table *p,                   /* Virtual table handle */
199168  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
199169  sqlite3_int64 *piDocid,         /* OUT: Docid value */
199170  char **paPoslist,               /* OUT: Pointer to position list */
199171  int *pnPoslist                  /* OUT: Size of position list in bytes */
199172){
199173  int nMerge = pMsr->nAdvance;
199174  Fts3SegReader **apSegment = pMsr->apSegment;
199175  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
199176    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
199177  );
199178
199179  if( nMerge==0 ){
199180    *paPoslist = 0;
199181    return SQLITE_OK;
199182  }
199183
199184  while( 1 ){
199185    Fts3SegReader *pSeg;
199186    pSeg = pMsr->apSegment[0];
199187
199188    if( pSeg->pOffsetList==0 ){
199189      *paPoslist = 0;
199190      break;
199191    }else{
199192      int rc;
199193      char *pList;
199194      int nList;
199195      int j;
199196      sqlite3_int64 iDocid = apSegment[0]->iDocid;
199197
199198      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
199199      j = 1;
199200      while( rc==SQLITE_OK
199201        && j<nMerge
199202        && apSegment[j]->pOffsetList
199203        && apSegment[j]->iDocid==iDocid
199204      ){
199205        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
199206        j++;
199207      }
199208      if( rc!=SQLITE_OK ) return rc;
199209      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
199210
199211      if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
199212        rc = fts3MsrBufferData(pMsr, pList, (i64)nList+1);
199213        if( rc!=SQLITE_OK ) return rc;
199214        assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
199215        pList = pMsr->aBuffer;
199216      }
199217
199218      if( pMsr->iColFilter>=0 ){
199219        fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
199220      }
199221
199222      if( nList>0 ){
199223        *paPoslist = pList;
199224        *piDocid = iDocid;
199225        *pnPoslist = nList;
199226        break;
199227      }
199228    }
199229  }
199230
199231  return SQLITE_OK;
199232}
199233
199234static int fts3SegReaderStart(
199235  Fts3Table *p,                   /* Virtual table handle */
199236  Fts3MultiSegReader *pCsr,       /* Cursor object */
199237  const char *zTerm,              /* Term searched for (or NULL) */
199238  int nTerm                       /* Length of zTerm in bytes */
199239){
199240  int i;
199241  int nSeg = pCsr->nSegment;
199242
199243  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
199244  ** for, then advance each segment iterator until it points to a term of
199245  ** equal or greater value than the specified term. This prevents many
199246  ** unnecessary merge/sort operations for the case where single segment
199247  ** b-tree leaf nodes contain more than one term.
199248  */
199249  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
199250    int res = 0;
199251    Fts3SegReader *pSeg = pCsr->apSegment[i];
199252    do {
199253      int rc = fts3SegReaderNext(p, pSeg, 0);
199254      if( rc!=SQLITE_OK ) return rc;
199255    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
199256
199257    if( pSeg->bLookup && res!=0 ){
199258      fts3SegReaderSetEof(pSeg);
199259    }
199260  }
199261  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
199262
199263  return SQLITE_OK;
199264}
199265
199266SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
199267  Fts3Table *p,                   /* Virtual table handle */
199268  Fts3MultiSegReader *pCsr,       /* Cursor object */
199269  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
199270){
199271  pCsr->pFilter = pFilter;
199272  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
199273}
199274
199275SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
199276  Fts3Table *p,                   /* Virtual table handle */
199277  Fts3MultiSegReader *pCsr,       /* Cursor object */
199278  int iCol,                       /* Column to match on. */
199279  const char *zTerm,              /* Term to iterate through a doclist for */
199280  int nTerm                       /* Number of bytes in zTerm */
199281){
199282  int i;
199283  int rc;
199284  int nSegment = pCsr->nSegment;
199285  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
199286    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
199287  );
199288
199289  assert( pCsr->pFilter==0 );
199290  assert( zTerm && nTerm>0 );
199291
199292  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
199293  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
199294  if( rc!=SQLITE_OK ) return rc;
199295
199296  /* Determine how many of the segments actually point to zTerm/nTerm. */
199297  for(i=0; i<nSegment; i++){
199298    Fts3SegReader *pSeg = pCsr->apSegment[i];
199299    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
199300      break;
199301    }
199302  }
199303  pCsr->nAdvance = i;
199304
199305  /* Advance each of the segments to point to the first docid. */
199306  for(i=0; i<pCsr->nAdvance; i++){
199307    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
199308    if( rc!=SQLITE_OK ) return rc;
199309  }
199310  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
199311
199312  assert( iCol<0 || iCol<p->nColumn );
199313  pCsr->iColFilter = iCol;
199314
199315  return SQLITE_OK;
199316}
199317
199318/*
199319** This function is called on a MultiSegReader that has been started using
199320** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
199321** have been made. Calling this function puts the MultiSegReader in such
199322** a state that if the next two calls are:
199323**
199324**   sqlite3Fts3SegReaderStart()
199325**   sqlite3Fts3SegReaderStep()
199326**
199327** then the entire doclist for the term is available in
199328** MultiSegReader.aDoclist/nDoclist.
199329*/
199330SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
199331  int i;                          /* Used to iterate through segment-readers */
199332
199333  assert( pCsr->zTerm==0 );
199334  assert( pCsr->nTerm==0 );
199335  assert( pCsr->aDoclist==0 );
199336  assert( pCsr->nDoclist==0 );
199337
199338  pCsr->nAdvance = 0;
199339  pCsr->bRestart = 1;
199340  for(i=0; i<pCsr->nSegment; i++){
199341    pCsr->apSegment[i]->pOffsetList = 0;
199342    pCsr->apSegment[i]->nOffsetList = 0;
199343    pCsr->apSegment[i]->iDocid = 0;
199344  }
199345
199346  return SQLITE_OK;
199347}
199348
199349static int fts3GrowSegReaderBuffer(Fts3MultiSegReader *pCsr, i64 nReq){
199350  if( nReq>pCsr->nBuffer ){
199351    char *aNew;
199352    pCsr->nBuffer = nReq*2;
199353    aNew = sqlite3_realloc64(pCsr->aBuffer, pCsr->nBuffer);
199354    if( !aNew ){
199355      return SQLITE_NOMEM;
199356    }
199357    pCsr->aBuffer = aNew;
199358  }
199359  return SQLITE_OK;
199360}
199361
199362
199363SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
199364  Fts3Table *p,                   /* Virtual table handle */
199365  Fts3MultiSegReader *pCsr        /* Cursor object */
199366){
199367  int rc = SQLITE_OK;
199368
199369  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
199370  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
199371  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
199372  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
199373  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
199374  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
199375
199376  Fts3SegReader **apSegment = pCsr->apSegment;
199377  int nSegment = pCsr->nSegment;
199378  Fts3SegFilter *pFilter = pCsr->pFilter;
199379  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
199380    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
199381  );
199382
199383  if( pCsr->nSegment==0 ) return SQLITE_OK;
199384
199385  do {
199386    int nMerge;
199387    int i;
199388
199389    /* Advance the first pCsr->nAdvance entries in the apSegment[] array
199390    ** forward. Then sort the list in order of current term again.
199391    */
199392    for(i=0; i<pCsr->nAdvance; i++){
199393      Fts3SegReader *pSeg = apSegment[i];
199394      if( pSeg->bLookup ){
199395        fts3SegReaderSetEof(pSeg);
199396      }else{
199397        rc = fts3SegReaderNext(p, pSeg, 0);
199398      }
199399      if( rc!=SQLITE_OK ) return rc;
199400    }
199401    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
199402    pCsr->nAdvance = 0;
199403
199404    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
199405    assert( rc==SQLITE_OK );
199406    if( apSegment[0]->aNode==0 ) break;
199407
199408    pCsr->nTerm = apSegment[0]->nTerm;
199409    pCsr->zTerm = apSegment[0]->zTerm;
199410
199411    /* If this is a prefix-search, and if the term that apSegment[0] points
199412    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
199413    ** required callbacks have been made. In this case exit early.
199414    **
199415    ** Similarly, if this is a search for an exact match, and the first term
199416    ** of segment apSegment[0] is not a match, exit early.
199417    */
199418    if( pFilter->zTerm && !isScan ){
199419      if( pCsr->nTerm<pFilter->nTerm
199420       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
199421       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
199422      ){
199423        break;
199424      }
199425    }
199426
199427    nMerge = 1;
199428    while( nMerge<nSegment
199429        && apSegment[nMerge]->aNode
199430        && apSegment[nMerge]->nTerm==pCsr->nTerm
199431        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
199432    ){
199433      nMerge++;
199434    }
199435
199436    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
199437    if( nMerge==1
199438     && !isIgnoreEmpty
199439     && !isFirst
199440     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
199441    ){
199442      pCsr->nDoclist = apSegment[0]->nDoclist;
199443      if( fts3SegReaderIsPending(apSegment[0]) ){
199444        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist,
199445                               (i64)pCsr->nDoclist);
199446        pCsr->aDoclist = pCsr->aBuffer;
199447      }else{
199448        pCsr->aDoclist = apSegment[0]->aDoclist;
199449      }
199450      if( rc==SQLITE_OK ) rc = SQLITE_ROW;
199451    }else{
199452      int nDoclist = 0;           /* Size of doclist */
199453      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
199454
199455      /* The current term of the first nMerge entries in the array
199456      ** of Fts3SegReader objects is the same. The doclists must be merged
199457      ** and a single term returned with the merged doclist.
199458      */
199459      for(i=0; i<nMerge; i++){
199460        fts3SegReaderFirstDocid(p, apSegment[i]);
199461      }
199462      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
199463      while( apSegment[0]->pOffsetList ){
199464        int j;                    /* Number of segments that share a docid */
199465        char *pList = 0;
199466        int nList = 0;
199467        int nByte;
199468        sqlite3_int64 iDocid = apSegment[0]->iDocid;
199469        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
199470        j = 1;
199471        while( j<nMerge
199472            && apSegment[j]->pOffsetList
199473            && apSegment[j]->iDocid==iDocid
199474        ){
199475          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
199476          j++;
199477        }
199478
199479        if( isColFilter ){
199480          fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
199481        }
199482
199483        if( !isIgnoreEmpty || nList>0 ){
199484
199485          /* Calculate the 'docid' delta value to write into the merged
199486          ** doclist. */
199487          sqlite3_int64 iDelta;
199488          if( p->bDescIdx && nDoclist>0 ){
199489            if( iPrev<=iDocid ) return FTS_CORRUPT_VTAB;
199490            iDelta = (i64)((u64)iPrev - (u64)iDocid);
199491          }else{
199492            if( nDoclist>0 && iPrev>=iDocid ) return FTS_CORRUPT_VTAB;
199493            iDelta = (i64)((u64)iDocid - (u64)iPrev);
199494          }
199495
199496          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
199497
199498          rc = fts3GrowSegReaderBuffer(pCsr,
199499                                   (i64)nByte+nDoclist+FTS3_NODE_PADDING);
199500          if( rc ) return rc;
199501
199502          if( isFirst ){
199503            char *a = &pCsr->aBuffer[nDoclist];
199504            int nWrite;
199505
199506            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
199507            if( nWrite ){
199508              iPrev = iDocid;
199509              nDoclist += nWrite;
199510            }
199511          }else{
199512            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
199513            iPrev = iDocid;
199514            if( isRequirePos ){
199515              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
199516              nDoclist += nList;
199517              pCsr->aBuffer[nDoclist++] = '\0';
199518            }
199519          }
199520        }
199521
199522        fts3SegReaderSort(apSegment, nMerge, j, xCmp);
199523      }
199524      if( nDoclist>0 ){
199525        rc = fts3GrowSegReaderBuffer(pCsr, (i64)nDoclist+FTS3_NODE_PADDING);
199526        if( rc ) return rc;
199527        memset(&pCsr->aBuffer[nDoclist], 0, FTS3_NODE_PADDING);
199528        pCsr->aDoclist = pCsr->aBuffer;
199529        pCsr->nDoclist = nDoclist;
199530        rc = SQLITE_ROW;
199531      }
199532    }
199533    pCsr->nAdvance = nMerge;
199534  }while( rc==SQLITE_OK );
199535
199536  return rc;
199537}
199538
199539
199540SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
199541  Fts3MultiSegReader *pCsr       /* Cursor object */
199542){
199543  if( pCsr ){
199544    int i;
199545    for(i=0; i<pCsr->nSegment; i++){
199546      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
199547    }
199548    sqlite3_free(pCsr->apSegment);
199549    sqlite3_free(pCsr->aBuffer);
199550
199551    pCsr->nSegment = 0;
199552    pCsr->apSegment = 0;
199553    pCsr->aBuffer = 0;
199554  }
199555}
199556
199557/*
199558** Decode the "end_block" field, selected by column iCol of the SELECT
199559** statement passed as the first argument.
199560**
199561** The "end_block" field may contain either an integer, or a text field
199562** containing the text representation of two non-negative integers separated
199563** by one or more space (0x20) characters. In the first case, set *piEndBlock
199564** to the integer value and *pnByte to zero before returning. In the second,
199565** set *piEndBlock to the first value and *pnByte to the second.
199566*/
199567static void fts3ReadEndBlockField(
199568  sqlite3_stmt *pStmt,
199569  int iCol,
199570  i64 *piEndBlock,
199571  i64 *pnByte
199572){
199573  const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
199574  if( zText ){
199575    int i;
199576    int iMul = 1;
199577    u64 iVal = 0;
199578    for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
199579      iVal = iVal*10 + (zText[i] - '0');
199580    }
199581    *piEndBlock = (i64)iVal;
199582    while( zText[i]==' ' ) i++;
199583    iVal = 0;
199584    if( zText[i]=='-' ){
199585      i++;
199586      iMul = -1;
199587    }
199588    for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
199589      iVal = iVal*10 + (zText[i] - '0');
199590    }
199591    *pnByte = ((i64)iVal * (i64)iMul);
199592  }
199593}
199594
199595
199596/*
199597** A segment of size nByte bytes has just been written to absolute level
199598** iAbsLevel. Promote any segments that should be promoted as a result.
199599*/
199600static int fts3PromoteSegments(
199601  Fts3Table *p,                   /* FTS table handle */
199602  sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
199603  sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
199604){
199605  int rc = SQLITE_OK;
199606  sqlite3_stmt *pRange;
199607
199608  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
199609
199610  if( rc==SQLITE_OK ){
199611    int bOk = 0;
199612    i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
199613    i64 nLimit = (nByte*3)/2;
199614
199615    /* Loop through all entries in the %_segdir table corresponding to
199616    ** segments in this index on levels greater than iAbsLevel. If there is
199617    ** at least one such segment, and it is possible to determine that all
199618    ** such segments are smaller than nLimit bytes in size, they will be
199619    ** promoted to level iAbsLevel.  */
199620    sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
199621    sqlite3_bind_int64(pRange, 2, iLast);
199622    while( SQLITE_ROW==sqlite3_step(pRange) ){
199623      i64 nSize = 0, dummy;
199624      fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
199625      if( nSize<=0 || nSize>nLimit ){
199626        /* If nSize==0, then the %_segdir.end_block field does not not
199627        ** contain a size value. This happens if it was written by an
199628        ** old version of FTS. In this case it is not possible to determine
199629        ** the size of the segment, and so segment promotion does not
199630        ** take place.  */
199631        bOk = 0;
199632        break;
199633      }
199634      bOk = 1;
199635    }
199636    rc = sqlite3_reset(pRange);
199637
199638    if( bOk ){
199639      int iIdx = 0;
199640      sqlite3_stmt *pUpdate1 = 0;
199641      sqlite3_stmt *pUpdate2 = 0;
199642
199643      if( rc==SQLITE_OK ){
199644        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
199645      }
199646      if( rc==SQLITE_OK ){
199647        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
199648      }
199649
199650      if( rc==SQLITE_OK ){
199651
199652        /* Loop through all %_segdir entries for segments in this index with
199653        ** levels equal to or greater than iAbsLevel. As each entry is visited,
199654        ** updated it to set (level = -1) and (idx = N), where N is 0 for the
199655        ** oldest segment in the range, 1 for the next oldest, and so on.
199656        **
199657        ** In other words, move all segments being promoted to level -1,
199658        ** setting the "idx" fields as appropriate to keep them in the same
199659        ** order. The contents of level -1 (which is never used, except
199660        ** transiently here), will be moved back to level iAbsLevel below.  */
199661        sqlite3_bind_int64(pRange, 1, iAbsLevel);
199662        while( SQLITE_ROW==sqlite3_step(pRange) ){
199663          sqlite3_bind_int(pUpdate1, 1, iIdx++);
199664          sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
199665          sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
199666          sqlite3_step(pUpdate1);
199667          rc = sqlite3_reset(pUpdate1);
199668          if( rc!=SQLITE_OK ){
199669            sqlite3_reset(pRange);
199670            break;
199671          }
199672        }
199673      }
199674      if( rc==SQLITE_OK ){
199675        rc = sqlite3_reset(pRange);
199676      }
199677
199678      /* Move level -1 to level iAbsLevel */
199679      if( rc==SQLITE_OK ){
199680        sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
199681        sqlite3_step(pUpdate2);
199682        rc = sqlite3_reset(pUpdate2);
199683      }
199684    }
199685  }
199686
199687
199688  return rc;
199689}
199690
199691/*
199692** Merge all level iLevel segments in the database into a single
199693** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
199694** single segment with a level equal to the numerically largest level
199695** currently present in the database.
199696**
199697** If this function is called with iLevel<0, but there is only one
199698** segment in the database, SQLITE_DONE is returned immediately.
199699** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
199700** an SQLite error code is returned.
199701*/
199702static int fts3SegmentMerge(
199703  Fts3Table *p,
199704  int iLangid,                    /* Language id to merge */
199705  int iIndex,                     /* Index in p->aIndex[] to merge */
199706  int iLevel                      /* Level to merge */
199707){
199708  int rc;                         /* Return code */
199709  int iIdx = 0;                   /* Index of new segment */
199710  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
199711  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
199712  Fts3SegFilter filter;           /* Segment term filter condition */
199713  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
199714  int bIgnoreEmpty = 0;           /* True to ignore empty segments */
199715  i64 iMaxLevel = 0;              /* Max level number for this index/langid */
199716
199717  assert( iLevel==FTS3_SEGCURSOR_ALL
199718       || iLevel==FTS3_SEGCURSOR_PENDING
199719       || iLevel>=0
199720  );
199721  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
199722  assert( iIndex>=0 && iIndex<p->nIndex );
199723
199724  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
199725  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
199726
199727  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
199728    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
199729    if( rc!=SQLITE_OK ) goto finished;
199730  }
199731
199732  if( iLevel==FTS3_SEGCURSOR_ALL ){
199733    /* This call is to merge all segments in the database to a single
199734    ** segment. The level of the new segment is equal to the numerically
199735    ** greatest segment level currently present in the database for this
199736    ** index. The idx of the new segment is always 0.  */
199737    if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
199738      rc = SQLITE_DONE;
199739      goto finished;
199740    }
199741    iNewLevel = iMaxLevel;
199742    bIgnoreEmpty = 1;
199743
199744  }else{
199745    /* This call is to merge all segments at level iLevel. find the next
199746    ** available segment index at level iLevel+1. The call to
199747    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
199748    ** a single iLevel+2 segment if necessary.  */
199749    assert( FTS3_SEGCURSOR_PENDING==-1 );
199750    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
199751    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
199752    bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
199753  }
199754  if( rc!=SQLITE_OK ) goto finished;
199755
199756  assert( csr.nSegment>0 );
199757  assert_fts3_nc( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
199758  assert_fts3_nc(
199759    iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL)
199760  );
199761
199762  memset(&filter, 0, sizeof(Fts3SegFilter));
199763  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
199764  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
199765
199766  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
199767  while( SQLITE_OK==rc ){
199768    rc = sqlite3Fts3SegReaderStep(p, &csr);
199769    if( rc!=SQLITE_ROW ) break;
199770    rc = fts3SegWriterAdd(p, &pWriter, 1,
199771        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
199772  }
199773  if( rc!=SQLITE_OK ) goto finished;
199774  assert_fts3_nc( pWriter || bIgnoreEmpty );
199775
199776  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
199777    rc = fts3DeleteSegdir(
199778        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
199779    );
199780    if( rc!=SQLITE_OK ) goto finished;
199781  }
199782  if( pWriter ){
199783    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
199784    if( rc==SQLITE_OK ){
199785      if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
199786        rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
199787      }
199788    }
199789  }
199790
199791 finished:
199792  fts3SegWriterFree(pWriter);
199793  sqlite3Fts3SegReaderFinish(&csr);
199794  return rc;
199795}
199796
199797
199798/*
199799** Flush the contents of pendingTerms to level 0 segments.
199800*/
199801SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
199802  int rc = SQLITE_OK;
199803  int i;
199804
199805  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
199806    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
199807    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
199808  }
199809
199810  /* Determine the auto-incr-merge setting if unknown.  If enabled,
199811  ** estimate the number of leaf blocks of content to be written
199812  */
199813  if( rc==SQLITE_OK && p->bHasStat
199814   && p->nAutoincrmerge==0xff && p->nLeafAdd>0
199815  ){
199816    sqlite3_stmt *pStmt = 0;
199817    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
199818    if( rc==SQLITE_OK ){
199819      sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
199820      rc = sqlite3_step(pStmt);
199821      if( rc==SQLITE_ROW ){
199822        p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
199823        if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
199824      }else if( rc==SQLITE_DONE ){
199825        p->nAutoincrmerge = 0;
199826      }
199827      rc = sqlite3_reset(pStmt);
199828    }
199829  }
199830
199831  if( rc==SQLITE_OK ){
199832    sqlite3Fts3PendingTermsClear(p);
199833  }
199834  return rc;
199835}
199836
199837/*
199838** Encode N integers as varints into a blob.
199839*/
199840static void fts3EncodeIntArray(
199841  int N,             /* The number of integers to encode */
199842  u32 *a,            /* The integer values */
199843  char *zBuf,        /* Write the BLOB here */
199844  int *pNBuf         /* Write number of bytes if zBuf[] used here */
199845){
199846  int i, j;
199847  for(i=j=0; i<N; i++){
199848    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
199849  }
199850  *pNBuf = j;
199851}
199852
199853/*
199854** Decode a blob of varints into N integers
199855*/
199856static void fts3DecodeIntArray(
199857  int N,             /* The number of integers to decode */
199858  u32 *a,            /* Write the integer values */
199859  const char *zBuf,  /* The BLOB containing the varints */
199860  int nBuf           /* size of the BLOB */
199861){
199862  int i = 0;
199863  if( nBuf && (zBuf[nBuf-1]&0x80)==0 ){
199864    int j;
199865    for(i=j=0; i<N && j<nBuf; i++){
199866      sqlite3_int64 x;
199867      j += sqlite3Fts3GetVarint(&zBuf[j], &x);
199868      a[i] = (u32)(x & 0xffffffff);
199869    }
199870  }
199871  while( i<N ) a[i++] = 0;
199872}
199873
199874/*
199875** Insert the sizes (in tokens) for each column of the document
199876** with docid equal to p->iPrevDocid.  The sizes are encoded as
199877** a blob of varints.
199878*/
199879static void fts3InsertDocsize(
199880  int *pRC,                       /* Result code */
199881  Fts3Table *p,                   /* Table into which to insert */
199882  u32 *aSz                        /* Sizes of each column, in tokens */
199883){
199884  char *pBlob;             /* The BLOB encoding of the document size */
199885  int nBlob;               /* Number of bytes in the BLOB */
199886  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
199887  int rc;                  /* Result code from subfunctions */
199888
199889  if( *pRC ) return;
199890  pBlob = sqlite3_malloc64( 10*(sqlite3_int64)p->nColumn );
199891  if( pBlob==0 ){
199892    *pRC = SQLITE_NOMEM;
199893    return;
199894  }
199895  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
199896  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
199897  if( rc ){
199898    sqlite3_free(pBlob);
199899    *pRC = rc;
199900    return;
199901  }
199902  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
199903  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
199904  sqlite3_step(pStmt);
199905  *pRC = sqlite3_reset(pStmt);
199906}
199907
199908/*
199909** Record 0 of the %_stat table contains a blob consisting of N varints,
199910** where N is the number of user defined columns in the fts3 table plus
199911** two. If nCol is the number of user defined columns, then values of the
199912** varints are set as follows:
199913**
199914**   Varint 0:       Total number of rows in the table.
199915**
199916**   Varint 1..nCol: For each column, the total number of tokens stored in
199917**                   the column for all rows of the table.
199918**
199919**   Varint 1+nCol:  The total size, in bytes, of all text values in all
199920**                   columns of all rows of the table.
199921**
199922*/
199923static void fts3UpdateDocTotals(
199924  int *pRC,                       /* The result code */
199925  Fts3Table *p,                   /* Table being updated */
199926  u32 *aSzIns,                    /* Size increases */
199927  u32 *aSzDel,                    /* Size decreases */
199928  int nChng                       /* Change in the number of documents */
199929){
199930  char *pBlob;             /* Storage for BLOB written into %_stat */
199931  int nBlob;               /* Size of BLOB written into %_stat */
199932  u32 *a;                  /* Array of integers that becomes the BLOB */
199933  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
199934  int i;                   /* Loop counter */
199935  int rc;                  /* Result code from subfunctions */
199936
199937  const int nStat = p->nColumn+2;
199938
199939  if( *pRC ) return;
199940  a = sqlite3_malloc64( (sizeof(u32)+10)*(sqlite3_int64)nStat );
199941  if( a==0 ){
199942    *pRC = SQLITE_NOMEM;
199943    return;
199944  }
199945  pBlob = (char*)&a[nStat];
199946  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
199947  if( rc ){
199948    sqlite3_free(a);
199949    *pRC = rc;
199950    return;
199951  }
199952  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
199953  if( sqlite3_step(pStmt)==SQLITE_ROW ){
199954    fts3DecodeIntArray(nStat, a,
199955         sqlite3_column_blob(pStmt, 0),
199956         sqlite3_column_bytes(pStmt, 0));
199957  }else{
199958    memset(a, 0, sizeof(u32)*(nStat) );
199959  }
199960  rc = sqlite3_reset(pStmt);
199961  if( rc!=SQLITE_OK ){
199962    sqlite3_free(a);
199963    *pRC = rc;
199964    return;
199965  }
199966  if( nChng<0 && a[0]<(u32)(-nChng) ){
199967    a[0] = 0;
199968  }else{
199969    a[0] += nChng;
199970  }
199971  for(i=0; i<p->nColumn+1; i++){
199972    u32 x = a[i+1];
199973    if( x+aSzIns[i] < aSzDel[i] ){
199974      x = 0;
199975    }else{
199976      x = x + aSzIns[i] - aSzDel[i];
199977    }
199978    a[i+1] = x;
199979  }
199980  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
199981  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
199982  if( rc ){
199983    sqlite3_free(a);
199984    *pRC = rc;
199985    return;
199986  }
199987  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
199988  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
199989  sqlite3_step(pStmt);
199990  *pRC = sqlite3_reset(pStmt);
199991  sqlite3_bind_null(pStmt, 2);
199992  sqlite3_free(a);
199993}
199994
199995/*
199996** Merge the entire database so that there is one segment for each
199997** iIndex/iLangid combination.
199998*/
199999static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
200000  int bSeenDone = 0;
200001  int rc;
200002  sqlite3_stmt *pAllLangid = 0;
200003
200004  rc = sqlite3Fts3PendingTermsFlush(p);
200005  if( rc==SQLITE_OK ){
200006    rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
200007  }
200008  if( rc==SQLITE_OK ){
200009    int rc2;
200010    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
200011    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
200012    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
200013      int i;
200014      int iLangid = sqlite3_column_int(pAllLangid, 0);
200015      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
200016        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
200017        if( rc==SQLITE_DONE ){
200018          bSeenDone = 1;
200019          rc = SQLITE_OK;
200020        }
200021      }
200022    }
200023    rc2 = sqlite3_reset(pAllLangid);
200024    if( rc==SQLITE_OK ) rc = rc2;
200025  }
200026
200027  sqlite3Fts3SegmentsClose(p);
200028
200029  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
200030}
200031
200032/*
200033** This function is called when the user executes the following statement:
200034**
200035**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
200036**
200037** The entire FTS index is discarded and rebuilt. If the table is one
200038** created using the content=xxx option, then the new index is based on
200039** the current contents of the xxx table. Otherwise, it is rebuilt based
200040** on the contents of the %_content table.
200041*/
200042static int fts3DoRebuild(Fts3Table *p){
200043  int rc;                         /* Return Code */
200044
200045  rc = fts3DeleteAll(p, 0);
200046  if( rc==SQLITE_OK ){
200047    u32 *aSz = 0;
200048    u32 *aSzIns = 0;
200049    u32 *aSzDel = 0;
200050    sqlite3_stmt *pStmt = 0;
200051    int nEntry = 0;
200052
200053    /* Compose and prepare an SQL statement to loop through the content table */
200054    char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
200055    if( !zSql ){
200056      rc = SQLITE_NOMEM;
200057    }else{
200058      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
200059      sqlite3_free(zSql);
200060    }
200061
200062    if( rc==SQLITE_OK ){
200063      sqlite3_int64 nByte = sizeof(u32) * ((sqlite3_int64)p->nColumn+1)*3;
200064      aSz = (u32 *)sqlite3_malloc64(nByte);
200065      if( aSz==0 ){
200066        rc = SQLITE_NOMEM;
200067      }else{
200068        memset(aSz, 0, nByte);
200069        aSzIns = &aSz[p->nColumn+1];
200070        aSzDel = &aSzIns[p->nColumn+1];
200071      }
200072    }
200073
200074    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
200075      int iCol;
200076      int iLangid = langidFromSelect(p, pStmt);
200077      rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
200078      memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
200079      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
200080        if( p->abNotindexed[iCol]==0 ){
200081          const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
200082          rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
200083          aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
200084        }
200085      }
200086      if( p->bHasDocsize ){
200087        fts3InsertDocsize(&rc, p, aSz);
200088      }
200089      if( rc!=SQLITE_OK ){
200090        sqlite3_finalize(pStmt);
200091        pStmt = 0;
200092      }else{
200093        nEntry++;
200094        for(iCol=0; iCol<=p->nColumn; iCol++){
200095          aSzIns[iCol] += aSz[iCol];
200096        }
200097      }
200098    }
200099    if( p->bFts4 ){
200100      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
200101    }
200102    sqlite3_free(aSz);
200103
200104    if( pStmt ){
200105      int rc2 = sqlite3_finalize(pStmt);
200106      if( rc==SQLITE_OK ){
200107        rc = rc2;
200108      }
200109    }
200110  }
200111
200112  return rc;
200113}
200114
200115
200116/*
200117** This function opens a cursor used to read the input data for an
200118** incremental merge operation. Specifically, it opens a cursor to scan
200119** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
200120** level iAbsLevel.
200121*/
200122static int fts3IncrmergeCsr(
200123  Fts3Table *p,                   /* FTS3 table handle */
200124  sqlite3_int64 iAbsLevel,        /* Absolute level to open */
200125  int nSeg,                       /* Number of segments to merge */
200126  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
200127){
200128  int rc;                         /* Return Code */
200129  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
200130  sqlite3_int64 nByte;            /* Bytes allocated at pCsr->apSegment[] */
200131
200132  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
200133  memset(pCsr, 0, sizeof(*pCsr));
200134  nByte = sizeof(Fts3SegReader *) * nSeg;
200135  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc64(nByte);
200136
200137  if( pCsr->apSegment==0 ){
200138    rc = SQLITE_NOMEM;
200139  }else{
200140    memset(pCsr->apSegment, 0, nByte);
200141    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
200142  }
200143  if( rc==SQLITE_OK ){
200144    int i;
200145    int rc2;
200146    sqlite3_bind_int64(pStmt, 1, iAbsLevel);
200147    assert( pCsr->nSegment==0 );
200148    for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
200149      rc = sqlite3Fts3SegReaderNew(i, 0,
200150          sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
200151          sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
200152          sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
200153          sqlite3_column_blob(pStmt, 4),         /* segdir.root */
200154          sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
200155          &pCsr->apSegment[i]
200156      );
200157      pCsr->nSegment++;
200158    }
200159    rc2 = sqlite3_reset(pStmt);
200160    if( rc==SQLITE_OK ) rc = rc2;
200161  }
200162
200163  return rc;
200164}
200165
200166typedef struct IncrmergeWriter IncrmergeWriter;
200167typedef struct NodeWriter NodeWriter;
200168typedef struct Blob Blob;
200169typedef struct NodeReader NodeReader;
200170
200171/*
200172** An instance of the following structure is used as a dynamic buffer
200173** to build up nodes or other blobs of data in.
200174**
200175** The function blobGrowBuffer() is used to extend the allocation.
200176*/
200177struct Blob {
200178  char *a;                        /* Pointer to allocation */
200179  int n;                          /* Number of valid bytes of data in a[] */
200180  int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
200181};
200182
200183/*
200184** This structure is used to build up buffers containing segment b-tree
200185** nodes (blocks).
200186*/
200187struct NodeWriter {
200188  sqlite3_int64 iBlock;           /* Current block id */
200189  Blob key;                       /* Last key written to the current block */
200190  Blob block;                     /* Current block image */
200191};
200192
200193/*
200194** An object of this type contains the state required to create or append
200195** to an appendable b-tree segment.
200196*/
200197struct IncrmergeWriter {
200198  int nLeafEst;                   /* Space allocated for leaf blocks */
200199  int nWork;                      /* Number of leaf pages flushed */
200200  sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
200201  int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
200202  sqlite3_int64 iStart;           /* Block number of first allocated block */
200203  sqlite3_int64 iEnd;             /* Block number of last allocated block */
200204  sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
200205  u8 bNoLeafData;                 /* If true, store 0 for segment size */
200206  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
200207};
200208
200209/*
200210** An object of the following type is used to read data from a single
200211** FTS segment node. See the following functions:
200212**
200213**     nodeReaderInit()
200214**     nodeReaderNext()
200215**     nodeReaderRelease()
200216*/
200217struct NodeReader {
200218  const char *aNode;
200219  int nNode;
200220  int iOff;                       /* Current offset within aNode[] */
200221
200222  /* Output variables. Containing the current node entry. */
200223  sqlite3_int64 iChild;           /* Pointer to child node */
200224  Blob term;                      /* Current term */
200225  const char *aDoclist;           /* Pointer to doclist */
200226  int nDoclist;                   /* Size of doclist in bytes */
200227};
200228
200229/*
200230** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
200231** Otherwise, if the allocation at pBlob->a is not already at least nMin
200232** bytes in size, extend (realloc) it to be so.
200233**
200234** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
200235** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
200236** to reflect the new size of the pBlob->a[] buffer.
200237*/
200238static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
200239  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
200240    int nAlloc = nMin;
200241    char *a = (char *)sqlite3_realloc64(pBlob->a, nAlloc);
200242    if( a ){
200243      pBlob->nAlloc = nAlloc;
200244      pBlob->a = a;
200245    }else{
200246      *pRc = SQLITE_NOMEM;
200247    }
200248  }
200249}
200250
200251/*
200252** Attempt to advance the node-reader object passed as the first argument to
200253** the next entry on the node.
200254**
200255** Return an error code if an error occurs (SQLITE_NOMEM is possible).
200256** Otherwise return SQLITE_OK. If there is no next entry on the node
200257** (e.g. because the current entry is the last) set NodeReader->aNode to
200258** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
200259** variables for the new entry.
200260*/
200261static int nodeReaderNext(NodeReader *p){
200262  int bFirst = (p->term.n==0);    /* True for first term on the node */
200263  int nPrefix = 0;                /* Bytes to copy from previous term */
200264  int nSuffix = 0;                /* Bytes to append to the prefix */
200265  int rc = SQLITE_OK;             /* Return code */
200266
200267  assert( p->aNode );
200268  if( p->iChild && bFirst==0 ) p->iChild++;
200269  if( p->iOff>=p->nNode ){
200270    /* EOF */
200271    p->aNode = 0;
200272  }else{
200273    if( bFirst==0 ){
200274      p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
200275    }
200276    p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
200277
200278    if( nPrefix>p->term.n || nSuffix>p->nNode-p->iOff || nSuffix==0 ){
200279      return FTS_CORRUPT_VTAB;
200280    }
200281    blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
200282    if( rc==SQLITE_OK && ALWAYS(p->term.a!=0) ){
200283      memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
200284      p->term.n = nPrefix+nSuffix;
200285      p->iOff += nSuffix;
200286      if( p->iChild==0 ){
200287        p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
200288        if( (p->nNode-p->iOff)<p->nDoclist ){
200289          return FTS_CORRUPT_VTAB;
200290        }
200291        p->aDoclist = &p->aNode[p->iOff];
200292        p->iOff += p->nDoclist;
200293      }
200294    }
200295  }
200296
200297  assert_fts3_nc( p->iOff<=p->nNode );
200298  return rc;
200299}
200300
200301/*
200302** Release all dynamic resources held by node-reader object *p.
200303*/
200304static void nodeReaderRelease(NodeReader *p){
200305  sqlite3_free(p->term.a);
200306}
200307
200308/*
200309** Initialize a node-reader object to read the node in buffer aNode/nNode.
200310**
200311** If successful, SQLITE_OK is returned and the NodeReader object set to
200312** point to the first entry on the node (if any). Otherwise, an SQLite
200313** error code is returned.
200314*/
200315static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
200316  memset(p, 0, sizeof(NodeReader));
200317  p->aNode = aNode;
200318  p->nNode = nNode;
200319
200320  /* Figure out if this is a leaf or an internal node. */
200321  if( aNode && aNode[0] ){
200322    /* An internal node. */
200323    p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
200324  }else{
200325    p->iOff = 1;
200326  }
200327
200328  return aNode ? nodeReaderNext(p) : SQLITE_OK;
200329}
200330
200331/*
200332** This function is called while writing an FTS segment each time a leaf o
200333** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
200334** to be greater than the largest key on the node just written, but smaller
200335** than or equal to the first key that will be written to the next leaf
200336** node.
200337**
200338** The block id of the leaf node just written to disk may be found in
200339** (pWriter->aNodeWriter[0].iBlock) when this function is called.
200340*/
200341static int fts3IncrmergePush(
200342  Fts3Table *p,                   /* Fts3 table handle */
200343  IncrmergeWriter *pWriter,       /* Writer object */
200344  const char *zTerm,              /* Term to write to internal node */
200345  int nTerm                       /* Bytes at zTerm */
200346){
200347  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
200348  int iLayer;
200349
200350  assert( nTerm>0 );
200351  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
200352    sqlite3_int64 iNextPtr = 0;
200353    NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
200354    int rc = SQLITE_OK;
200355    int nPrefix;
200356    int nSuffix;
200357    int nSpace;
200358
200359    /* Figure out how much space the key will consume if it is written to
200360    ** the current node of layer iLayer. Due to the prefix compression,
200361    ** the space required changes depending on which node the key is to
200362    ** be added to.  */
200363    nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
200364    nSuffix = nTerm - nPrefix;
200365    if(nSuffix<=0 ) return FTS_CORRUPT_VTAB;
200366    nSpace  = sqlite3Fts3VarintLen(nPrefix);
200367    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
200368
200369    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
200370      /* If the current node of layer iLayer contains zero keys, or if adding
200371      ** the key to it will not cause it to grow to larger than nNodeSize
200372      ** bytes in size, write the key here.  */
200373
200374      Blob *pBlk = &pNode->block;
200375      if( pBlk->n==0 ){
200376        blobGrowBuffer(pBlk, p->nNodeSize, &rc);
200377        if( rc==SQLITE_OK ){
200378          pBlk->a[0] = (char)iLayer;
200379          pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
200380        }
200381      }
200382      blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
200383      blobGrowBuffer(&pNode->key, nTerm, &rc);
200384
200385      if( rc==SQLITE_OK ){
200386        if( pNode->key.n ){
200387          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
200388        }
200389        pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
200390        assert( nPrefix+nSuffix<=nTerm );
200391        assert( nPrefix>=0 );
200392        memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
200393        pBlk->n += nSuffix;
200394
200395        memcpy(pNode->key.a, zTerm, nTerm);
200396        pNode->key.n = nTerm;
200397      }
200398    }else{
200399      /* Otherwise, flush the current node of layer iLayer to disk.
200400      ** Then allocate a new, empty sibling node. The key will be written
200401      ** into the parent of this node. */
200402      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
200403
200404      assert( pNode->block.nAlloc>=p->nNodeSize );
200405      pNode->block.a[0] = (char)iLayer;
200406      pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
200407
200408      iNextPtr = pNode->iBlock;
200409      pNode->iBlock++;
200410      pNode->key.n = 0;
200411    }
200412
200413    if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
200414    iPtr = iNextPtr;
200415  }
200416
200417  assert( 0 );
200418  return 0;
200419}
200420
200421/*
200422** Append a term and (optionally) doclist to the FTS segment node currently
200423** stored in blob *pNode. The node need not contain any terms, but the
200424** header must be written before this function is called.
200425**
200426** A node header is a single 0x00 byte for a leaf node, or a height varint
200427** followed by the left-hand-child varint for an internal node.
200428**
200429** The term to be appended is passed via arguments zTerm/nTerm. For a
200430** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
200431** node, both aDoclist and nDoclist must be passed 0.
200432**
200433** If the size of the value in blob pPrev is zero, then this is the first
200434** term written to the node. Otherwise, pPrev contains a copy of the
200435** previous term. Before this function returns, it is updated to contain a
200436** copy of zTerm/nTerm.
200437**
200438** It is assumed that the buffer associated with pNode is already large
200439** enough to accommodate the new entry. The buffer associated with pPrev
200440** is extended by this function if requrired.
200441**
200442** If an error (i.e. OOM condition) occurs, an SQLite error code is
200443** returned. Otherwise, SQLITE_OK.
200444*/
200445static int fts3AppendToNode(
200446  Blob *pNode,                    /* Current node image to append to */
200447  Blob *pPrev,                    /* Buffer containing previous term written */
200448  const char *zTerm,              /* New term to write */
200449  int nTerm,                      /* Size of zTerm in bytes */
200450  const char *aDoclist,           /* Doclist (or NULL) to write */
200451  int nDoclist                    /* Size of aDoclist in bytes */
200452){
200453  int rc = SQLITE_OK;             /* Return code */
200454  int bFirst = (pPrev->n==0);     /* True if this is the first term written */
200455  int nPrefix;                    /* Size of term prefix in bytes */
200456  int nSuffix;                    /* Size of term suffix in bytes */
200457
200458  /* Node must have already been started. There must be a doclist for a
200459  ** leaf node, and there must not be a doclist for an internal node.  */
200460  assert( pNode->n>0 );
200461  assert_fts3_nc( (pNode->a[0]=='\0')==(aDoclist!=0) );
200462
200463  blobGrowBuffer(pPrev, nTerm, &rc);
200464  if( rc!=SQLITE_OK ) return rc;
200465  assert( pPrev!=0 );
200466  assert( pPrev->a!=0 );
200467
200468  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
200469  nSuffix = nTerm - nPrefix;
200470  if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
200471  memcpy(pPrev->a, zTerm, nTerm);
200472  pPrev->n = nTerm;
200473
200474  if( bFirst==0 ){
200475    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
200476  }
200477  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
200478  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
200479  pNode->n += nSuffix;
200480
200481  if( aDoclist ){
200482    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
200483    memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
200484    pNode->n += nDoclist;
200485  }
200486
200487  assert( pNode->n<=pNode->nAlloc );
200488
200489  return SQLITE_OK;
200490}
200491
200492/*
200493** Append the current term and doclist pointed to by cursor pCsr to the
200494** appendable b-tree segment opened for writing by pWriter.
200495**
200496** Return SQLITE_OK if successful, or an SQLite error code otherwise.
200497*/
200498static int fts3IncrmergeAppend(
200499  Fts3Table *p,                   /* Fts3 table handle */
200500  IncrmergeWriter *pWriter,       /* Writer object */
200501  Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
200502){
200503  const char *zTerm = pCsr->zTerm;
200504  int nTerm = pCsr->nTerm;
200505  const char *aDoclist = pCsr->aDoclist;
200506  int nDoclist = pCsr->nDoclist;
200507  int rc = SQLITE_OK;           /* Return code */
200508  int nSpace;                   /* Total space in bytes required on leaf */
200509  int nPrefix;                  /* Size of prefix shared with previous term */
200510  int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
200511  NodeWriter *pLeaf;            /* Object used to write leaf nodes */
200512
200513  pLeaf = &pWriter->aNodeWriter[0];
200514  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
200515  nSuffix = nTerm - nPrefix;
200516  if(nSuffix<=0 ) return FTS_CORRUPT_VTAB;
200517
200518  nSpace  = sqlite3Fts3VarintLen(nPrefix);
200519  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
200520  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
200521
200522  /* If the current block is not empty, and if adding this term/doclist
200523  ** to the current block would make it larger than Fts3Table.nNodeSize bytes,
200524  ** and if there is still room for another leaf page, write this block out to
200525  ** the database. */
200526  if( pLeaf->block.n>0
200527   && (pLeaf->block.n + nSpace)>p->nNodeSize
200528   && pLeaf->iBlock < (pWriter->iStart + pWriter->nLeafEst)
200529  ){
200530    rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
200531    pWriter->nWork++;
200532
200533    /* Add the current term to the parent node. The term added to the
200534    ** parent must:
200535    **
200536    **   a) be greater than the largest term on the leaf node just written
200537    **      to the database (still available in pLeaf->key), and
200538    **
200539    **   b) be less than or equal to the term about to be added to the new
200540    **      leaf node (zTerm/nTerm).
200541    **
200542    ** In other words, it must be the prefix of zTerm 1 byte longer than
200543    ** the common prefix (if any) of zTerm and pWriter->zTerm.
200544    */
200545    if( rc==SQLITE_OK ){
200546      rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
200547    }
200548
200549    /* Advance to the next output block */
200550    pLeaf->iBlock++;
200551    pLeaf->key.n = 0;
200552    pLeaf->block.n = 0;
200553
200554    nSuffix = nTerm;
200555    nSpace  = 1;
200556    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
200557    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
200558  }
200559
200560  pWriter->nLeafData += nSpace;
200561  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
200562  if( rc==SQLITE_OK ){
200563    if( pLeaf->block.n==0 ){
200564      pLeaf->block.n = 1;
200565      pLeaf->block.a[0] = '\0';
200566    }
200567    rc = fts3AppendToNode(
200568        &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
200569    );
200570  }
200571
200572  return rc;
200573}
200574
200575/*
200576** This function is called to release all dynamic resources held by the
200577** merge-writer object pWriter, and if no error has occurred, to flush
200578** all outstanding node buffers held by pWriter to disk.
200579**
200580** If *pRc is not SQLITE_OK when this function is called, then no attempt
200581** is made to write any data to disk. Instead, this function serves only
200582** to release outstanding resources.
200583**
200584** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
200585** flushing buffers to disk, *pRc is set to an SQLite error code before
200586** returning.
200587*/
200588static void fts3IncrmergeRelease(
200589  Fts3Table *p,                   /* FTS3 table handle */
200590  IncrmergeWriter *pWriter,       /* Merge-writer object */
200591  int *pRc                        /* IN/OUT: Error code */
200592){
200593  int i;                          /* Used to iterate through non-root layers */
200594  int iRoot;                      /* Index of root in pWriter->aNodeWriter */
200595  NodeWriter *pRoot;              /* NodeWriter for root node */
200596  int rc = *pRc;                  /* Error code */
200597
200598  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
200599  ** root node. If the segment fits entirely on a single leaf node, iRoot
200600  ** will be set to 0. If the root node is the parent of the leaves, iRoot
200601  ** will be 1. And so on.  */
200602  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
200603    NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
200604    if( pNode->block.n>0 ) break;
200605    assert( *pRc || pNode->block.nAlloc==0 );
200606    assert( *pRc || pNode->key.nAlloc==0 );
200607    sqlite3_free(pNode->block.a);
200608    sqlite3_free(pNode->key.a);
200609  }
200610
200611  /* Empty output segment. This is a no-op. */
200612  if( iRoot<0 ) return;
200613
200614  /* The entire output segment fits on a single node. Normally, this means
200615  ** the node would be stored as a blob in the "root" column of the %_segdir
200616  ** table. However, this is not permitted in this case. The problem is that
200617  ** space has already been reserved in the %_segments table, and so the
200618  ** start_block and end_block fields of the %_segdir table must be populated.
200619  ** And, by design or by accident, released versions of FTS cannot handle
200620  ** segments that fit entirely on the root node with start_block!=0.
200621  **
200622  ** Instead, create a synthetic root node that contains nothing but a
200623  ** pointer to the single content node. So that the segment consists of a
200624  ** single leaf and a single interior (root) node.
200625  **
200626  ** Todo: Better might be to defer allocating space in the %_segments
200627  ** table until we are sure it is needed.
200628  */
200629  if( iRoot==0 ){
200630    Blob *pBlock = &pWriter->aNodeWriter[1].block;
200631    blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
200632    if( rc==SQLITE_OK ){
200633      pBlock->a[0] = 0x01;
200634      pBlock->n = 1 + sqlite3Fts3PutVarint(
200635          &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
200636      );
200637    }
200638    iRoot = 1;
200639  }
200640  pRoot = &pWriter->aNodeWriter[iRoot];
200641
200642  /* Flush all currently outstanding nodes to disk. */
200643  for(i=0; i<iRoot; i++){
200644    NodeWriter *pNode = &pWriter->aNodeWriter[i];
200645    if( pNode->block.n>0 && rc==SQLITE_OK ){
200646      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
200647    }
200648    sqlite3_free(pNode->block.a);
200649    sqlite3_free(pNode->key.a);
200650  }
200651
200652  /* Write the %_segdir record. */
200653  if( rc==SQLITE_OK ){
200654    rc = fts3WriteSegdir(p,
200655        pWriter->iAbsLevel+1,               /* level */
200656        pWriter->iIdx,                      /* idx */
200657        pWriter->iStart,                    /* start_block */
200658        pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
200659        pWriter->iEnd,                      /* end_block */
200660        (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
200661        pRoot->block.a, pRoot->block.n      /* root */
200662    );
200663  }
200664  sqlite3_free(pRoot->block.a);
200665  sqlite3_free(pRoot->key.a);
200666
200667  *pRc = rc;
200668}
200669
200670/*
200671** Compare the term in buffer zLhs (size in bytes nLhs) with that in
200672** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
200673** the other, it is considered to be smaller than the other.
200674**
200675** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
200676** if it is greater.
200677*/
200678static int fts3TermCmp(
200679  const char *zLhs, int nLhs,     /* LHS of comparison */
200680  const char *zRhs, int nRhs      /* RHS of comparison */
200681){
200682  int nCmp = MIN(nLhs, nRhs);
200683  int res;
200684
200685  if( nCmp && ALWAYS(zLhs) && ALWAYS(zRhs) ){
200686    res = memcmp(zLhs, zRhs, nCmp);
200687  }else{
200688    res = 0;
200689  }
200690  if( res==0 ) res = nLhs - nRhs;
200691
200692  return res;
200693}
200694
200695
200696/*
200697** Query to see if the entry in the %_segments table with blockid iEnd is
200698** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
200699** returning. Otherwise, set *pbRes to 0.
200700**
200701** Or, if an error occurs while querying the database, return an SQLite
200702** error code. The final value of *pbRes is undefined in this case.
200703**
200704** This is used to test if a segment is an "appendable" segment. If it
200705** is, then a NULL entry has been inserted into the %_segments table
200706** with blockid %_segdir.end_block.
200707*/
200708static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
200709  int bRes = 0;                   /* Result to set *pbRes to */
200710  sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
200711  int rc;                         /* Return code */
200712
200713  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
200714  if( rc==SQLITE_OK ){
200715    sqlite3_bind_int64(pCheck, 1, iEnd);
200716    if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
200717    rc = sqlite3_reset(pCheck);
200718  }
200719
200720  *pbRes = bRes;
200721  return rc;
200722}
200723
200724/*
200725** This function is called when initializing an incremental-merge operation.
200726** It checks if the existing segment with index value iIdx at absolute level
200727** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
200728** merge-writer object *pWriter is initialized to write to it.
200729**
200730** An existing segment can be appended to by an incremental merge if:
200731**
200732**   * It was initially created as an appendable segment (with all required
200733**     space pre-allocated), and
200734**
200735**   * The first key read from the input (arguments zKey and nKey) is
200736**     greater than the largest key currently stored in the potential
200737**     output segment.
200738*/
200739static int fts3IncrmergeLoad(
200740  Fts3Table *p,                   /* Fts3 table handle */
200741  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
200742  int iIdx,                       /* Index of candidate output segment */
200743  const char *zKey,               /* First key to write */
200744  int nKey,                       /* Number of bytes in nKey */
200745  IncrmergeWriter *pWriter        /* Populate this object */
200746){
200747  int rc;                         /* Return code */
200748  sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
200749
200750  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
200751  if( rc==SQLITE_OK ){
200752    sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
200753    sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
200754    sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
200755    const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
200756    int nRoot = 0;                /* Size of aRoot[] in bytes */
200757    int rc2;                      /* Return code from sqlite3_reset() */
200758    int bAppendable = 0;          /* Set to true if segment is appendable */
200759
200760    /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
200761    sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
200762    sqlite3_bind_int(pSelect, 2, iIdx);
200763    if( sqlite3_step(pSelect)==SQLITE_ROW ){
200764      iStart = sqlite3_column_int64(pSelect, 1);
200765      iLeafEnd = sqlite3_column_int64(pSelect, 2);
200766      fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
200767      if( pWriter->nLeafData<0 ){
200768        pWriter->nLeafData = pWriter->nLeafData * -1;
200769      }
200770      pWriter->bNoLeafData = (pWriter->nLeafData==0);
200771      nRoot = sqlite3_column_bytes(pSelect, 4);
200772      aRoot = sqlite3_column_blob(pSelect, 4);
200773      if( aRoot==0 ){
200774        sqlite3_reset(pSelect);
200775        return nRoot ? SQLITE_NOMEM : FTS_CORRUPT_VTAB;
200776      }
200777    }else{
200778      return sqlite3_reset(pSelect);
200779    }
200780
200781    /* Check for the zero-length marker in the %_segments table */
200782    rc = fts3IsAppendable(p, iEnd, &bAppendable);
200783
200784    /* Check that zKey/nKey is larger than the largest key the candidate */
200785    if( rc==SQLITE_OK && bAppendable ){
200786      char *aLeaf = 0;
200787      int nLeaf = 0;
200788
200789      rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
200790      if( rc==SQLITE_OK ){
200791        NodeReader reader;
200792        for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
200793            rc==SQLITE_OK && reader.aNode;
200794            rc = nodeReaderNext(&reader)
200795        ){
200796          assert( reader.aNode );
200797        }
200798        if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
200799          bAppendable = 0;
200800        }
200801        nodeReaderRelease(&reader);
200802      }
200803      sqlite3_free(aLeaf);
200804    }
200805
200806    if( rc==SQLITE_OK && bAppendable ){
200807      /* It is possible to append to this segment. Set up the IncrmergeWriter
200808      ** object to do so.  */
200809      int i;
200810      int nHeight = (int)aRoot[0];
200811      NodeWriter *pNode;
200812      if( nHeight<1 || nHeight>=FTS_MAX_APPENDABLE_HEIGHT ){
200813        sqlite3_reset(pSelect);
200814        return FTS_CORRUPT_VTAB;
200815      }
200816
200817      pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
200818      pWriter->iStart = iStart;
200819      pWriter->iEnd = iEnd;
200820      pWriter->iAbsLevel = iAbsLevel;
200821      pWriter->iIdx = iIdx;
200822
200823      for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
200824        pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
200825      }
200826
200827      pNode = &pWriter->aNodeWriter[nHeight];
200828      pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
200829      blobGrowBuffer(&pNode->block,
200830          MAX(nRoot, p->nNodeSize)+FTS3_NODE_PADDING, &rc
200831      );
200832      if( rc==SQLITE_OK ){
200833        memcpy(pNode->block.a, aRoot, nRoot);
200834        pNode->block.n = nRoot;
200835        memset(&pNode->block.a[nRoot], 0, FTS3_NODE_PADDING);
200836      }
200837
200838      for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
200839        NodeReader reader;
200840        memset(&reader, 0, sizeof(reader));
200841        pNode = &pWriter->aNodeWriter[i];
200842
200843        if( pNode->block.a){
200844          rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
200845          while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
200846          blobGrowBuffer(&pNode->key, reader.term.n, &rc);
200847          if( rc==SQLITE_OK ){
200848            assert_fts3_nc( reader.term.n>0 || reader.aNode==0 );
200849            if( reader.term.n>0 ){
200850              memcpy(pNode->key.a, reader.term.a, reader.term.n);
200851            }
200852            pNode->key.n = reader.term.n;
200853            if( i>0 ){
200854              char *aBlock = 0;
200855              int nBlock = 0;
200856              pNode = &pWriter->aNodeWriter[i-1];
200857              pNode->iBlock = reader.iChild;
200858              rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock,0);
200859              blobGrowBuffer(&pNode->block,
200860                  MAX(nBlock, p->nNodeSize)+FTS3_NODE_PADDING, &rc
200861              );
200862              if( rc==SQLITE_OK ){
200863                memcpy(pNode->block.a, aBlock, nBlock);
200864                pNode->block.n = nBlock;
200865                memset(&pNode->block.a[nBlock], 0, FTS3_NODE_PADDING);
200866              }
200867              sqlite3_free(aBlock);
200868            }
200869          }
200870        }
200871        nodeReaderRelease(&reader);
200872      }
200873    }
200874
200875    rc2 = sqlite3_reset(pSelect);
200876    if( rc==SQLITE_OK ) rc = rc2;
200877  }
200878
200879  return rc;
200880}
200881
200882/*
200883** Determine the largest segment index value that exists within absolute
200884** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
200885** one before returning SQLITE_OK. Or, if there are no segments at all
200886** within level iAbsLevel, set *piIdx to zero.
200887**
200888** If an error occurs, return an SQLite error code. The final value of
200889** *piIdx is undefined in this case.
200890*/
200891static int fts3IncrmergeOutputIdx(
200892  Fts3Table *p,                   /* FTS Table handle */
200893  sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
200894  int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
200895){
200896  int rc;
200897  sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
200898
200899  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
200900  if( rc==SQLITE_OK ){
200901    sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
200902    sqlite3_step(pOutputIdx);
200903    *piIdx = sqlite3_column_int(pOutputIdx, 0);
200904    rc = sqlite3_reset(pOutputIdx);
200905  }
200906
200907  return rc;
200908}
200909
200910/*
200911** Allocate an appendable output segment on absolute level iAbsLevel+1
200912** with idx value iIdx.
200913**
200914** In the %_segdir table, a segment is defined by the values in three
200915** columns:
200916**
200917**     start_block
200918**     leaves_end_block
200919**     end_block
200920**
200921** When an appendable segment is allocated, it is estimated that the
200922** maximum number of leaf blocks that may be required is the sum of the
200923** number of leaf blocks consumed by the input segments, plus the number
200924** of input segments, multiplied by two. This value is stored in stack
200925** variable nLeafEst.
200926**
200927** A total of 16*nLeafEst blocks are allocated when an appendable segment
200928** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
200929** array of leaf nodes starts at the first block allocated. The array
200930** of interior nodes that are parents of the leaf nodes start at block
200931** (start_block + (1 + end_block - start_block) / 16). And so on.
200932**
200933** In the actual code below, the value "16" is replaced with the
200934** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
200935*/
200936static int fts3IncrmergeWriter(
200937  Fts3Table *p,                   /* Fts3 table handle */
200938  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
200939  int iIdx,                       /* Index of new output segment */
200940  Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
200941  IncrmergeWriter *pWriter        /* Populate this object */
200942){
200943  int rc;                         /* Return Code */
200944  int i;                          /* Iterator variable */
200945  int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
200946  sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
200947  sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
200948
200949  /* Calculate nLeafEst. */
200950  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
200951  if( rc==SQLITE_OK ){
200952    sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
200953    sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
200954    if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
200955      nLeafEst = sqlite3_column_int(pLeafEst, 0);
200956    }
200957    rc = sqlite3_reset(pLeafEst);
200958  }
200959  if( rc!=SQLITE_OK ) return rc;
200960
200961  /* Calculate the first block to use in the output segment */
200962  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
200963  if( rc==SQLITE_OK ){
200964    if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
200965      pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
200966      pWriter->iEnd = pWriter->iStart - 1;
200967      pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
200968    }
200969    rc = sqlite3_reset(pFirstBlock);
200970  }
200971  if( rc!=SQLITE_OK ) return rc;
200972
200973  /* Insert the marker in the %_segments table to make sure nobody tries
200974  ** to steal the space just allocated. This is also used to identify
200975  ** appendable segments.  */
200976  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
200977  if( rc!=SQLITE_OK ) return rc;
200978
200979  pWriter->iAbsLevel = iAbsLevel;
200980  pWriter->nLeafEst = nLeafEst;
200981  pWriter->iIdx = iIdx;
200982
200983  /* Set up the array of NodeWriter objects */
200984  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
200985    pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
200986  }
200987  return SQLITE_OK;
200988}
200989
200990/*
200991** Remove an entry from the %_segdir table. This involves running the
200992** following two statements:
200993**
200994**   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
200995**   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
200996**
200997** The DELETE statement removes the specific %_segdir level. The UPDATE
200998** statement ensures that the remaining segments have contiguously allocated
200999** idx values.
201000*/
201001static int fts3RemoveSegdirEntry(
201002  Fts3Table *p,                   /* FTS3 table handle */
201003  sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
201004  int iIdx                        /* Index of %_segdir entry to delete */
201005){
201006  int rc;                         /* Return code */
201007  sqlite3_stmt *pDelete = 0;      /* DELETE statement */
201008
201009  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
201010  if( rc==SQLITE_OK ){
201011    sqlite3_bind_int64(pDelete, 1, iAbsLevel);
201012    sqlite3_bind_int(pDelete, 2, iIdx);
201013    sqlite3_step(pDelete);
201014    rc = sqlite3_reset(pDelete);
201015  }
201016
201017  return rc;
201018}
201019
201020/*
201021** One or more segments have just been removed from absolute level iAbsLevel.
201022** Update the 'idx' values of the remaining segments in the level so that
201023** the idx values are a contiguous sequence starting from 0.
201024*/
201025static int fts3RepackSegdirLevel(
201026  Fts3Table *p,                   /* FTS3 table handle */
201027  sqlite3_int64 iAbsLevel         /* Absolute level to repack */
201028){
201029  int rc;                         /* Return code */
201030  int *aIdx = 0;                  /* Array of remaining idx values */
201031  int nIdx = 0;                   /* Valid entries in aIdx[] */
201032  int nAlloc = 0;                 /* Allocated size of aIdx[] */
201033  int i;                          /* Iterator variable */
201034  sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
201035  sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
201036
201037  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
201038  if( rc==SQLITE_OK ){
201039    int rc2;
201040    sqlite3_bind_int64(pSelect, 1, iAbsLevel);
201041    while( SQLITE_ROW==sqlite3_step(pSelect) ){
201042      if( nIdx>=nAlloc ){
201043        int *aNew;
201044        nAlloc += 16;
201045        aNew = sqlite3_realloc64(aIdx, nAlloc*sizeof(int));
201046        if( !aNew ){
201047          rc = SQLITE_NOMEM;
201048          break;
201049        }
201050        aIdx = aNew;
201051      }
201052      aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
201053    }
201054    rc2 = sqlite3_reset(pSelect);
201055    if( rc==SQLITE_OK ) rc = rc2;
201056  }
201057
201058  if( rc==SQLITE_OK ){
201059    rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
201060  }
201061  if( rc==SQLITE_OK ){
201062    sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
201063  }
201064
201065  assert( p->bIgnoreSavepoint==0 );
201066  p->bIgnoreSavepoint = 1;
201067  for(i=0; rc==SQLITE_OK && i<nIdx; i++){
201068    if( aIdx[i]!=i ){
201069      sqlite3_bind_int(pUpdate, 3, aIdx[i]);
201070      sqlite3_bind_int(pUpdate, 1, i);
201071      sqlite3_step(pUpdate);
201072      rc = sqlite3_reset(pUpdate);
201073    }
201074  }
201075  p->bIgnoreSavepoint = 0;
201076
201077  sqlite3_free(aIdx);
201078  return rc;
201079}
201080
201081static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
201082  pNode->a[0] = (char)iHeight;
201083  if( iChild ){
201084    assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
201085    pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
201086  }else{
201087    assert( pNode->nAlloc>=1 );
201088    pNode->n = 1;
201089  }
201090}
201091
201092/*
201093** The first two arguments are a pointer to and the size of a segment b-tree
201094** node. The node may be a leaf or an internal node.
201095**
201096** This function creates a new node image in blob object *pNew by copying
201097** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
201098** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
201099*/
201100static int fts3TruncateNode(
201101  const char *aNode,              /* Current node image */
201102  int nNode,                      /* Size of aNode in bytes */
201103  Blob *pNew,                     /* OUT: Write new node image here */
201104  const char *zTerm,              /* Omit all terms smaller than this */
201105  int nTerm,                      /* Size of zTerm in bytes */
201106  sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
201107){
201108  NodeReader reader;              /* Reader object */
201109  Blob prev = {0, 0, 0};          /* Previous term written to new node */
201110  int rc = SQLITE_OK;             /* Return code */
201111  int bLeaf;                       /* True for a leaf node */
201112
201113  if( nNode<1 ) return FTS_CORRUPT_VTAB;
201114  bLeaf = aNode[0]=='\0';
201115
201116  /* Allocate required output space */
201117  blobGrowBuffer(pNew, nNode, &rc);
201118  if( rc!=SQLITE_OK ) return rc;
201119  pNew->n = 0;
201120
201121  /* Populate new node buffer */
201122  for(rc = nodeReaderInit(&reader, aNode, nNode);
201123      rc==SQLITE_OK && reader.aNode;
201124      rc = nodeReaderNext(&reader)
201125  ){
201126    if( pNew->n==0 ){
201127      int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
201128      if( res<0 || (bLeaf==0 && res==0) ) continue;
201129      fts3StartNode(pNew, (int)aNode[0], reader.iChild);
201130      *piBlock = reader.iChild;
201131    }
201132    rc = fts3AppendToNode(
201133        pNew, &prev, reader.term.a, reader.term.n,
201134        reader.aDoclist, reader.nDoclist
201135    );
201136    if( rc!=SQLITE_OK ) break;
201137  }
201138  if( pNew->n==0 ){
201139    fts3StartNode(pNew, (int)aNode[0], reader.iChild);
201140    *piBlock = reader.iChild;
201141  }
201142  assert( pNew->n<=pNew->nAlloc );
201143
201144  nodeReaderRelease(&reader);
201145  sqlite3_free(prev.a);
201146  return rc;
201147}
201148
201149/*
201150** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
201151** level iAbsLevel. This may involve deleting entries from the %_segments
201152** table, and modifying existing entries in both the %_segments and %_segdir
201153** tables.
201154**
201155** SQLITE_OK is returned if the segment is updated successfully. Or an
201156** SQLite error code otherwise.
201157*/
201158static int fts3TruncateSegment(
201159  Fts3Table *p,                   /* FTS3 table handle */
201160  sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
201161  int iIdx,                       /* Index within level of segment to modify */
201162  const char *zTerm,              /* Remove terms smaller than this */
201163  int nTerm                      /* Number of bytes in buffer zTerm */
201164){
201165  int rc = SQLITE_OK;             /* Return code */
201166  Blob root = {0,0,0};            /* New root page image */
201167  Blob block = {0,0,0};           /* Buffer used for any other block */
201168  sqlite3_int64 iBlock = 0;       /* Block id */
201169  sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
201170  sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
201171  sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
201172
201173  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
201174  if( rc==SQLITE_OK ){
201175    int rc2;                      /* sqlite3_reset() return code */
201176    sqlite3_bind_int64(pFetch, 1, iAbsLevel);
201177    sqlite3_bind_int(pFetch, 2, iIdx);
201178    if( SQLITE_ROW==sqlite3_step(pFetch) ){
201179      const char *aRoot = sqlite3_column_blob(pFetch, 4);
201180      int nRoot = sqlite3_column_bytes(pFetch, 4);
201181      iOldStart = sqlite3_column_int64(pFetch, 1);
201182      rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
201183    }
201184    rc2 = sqlite3_reset(pFetch);
201185    if( rc==SQLITE_OK ) rc = rc2;
201186  }
201187
201188  while( rc==SQLITE_OK && iBlock ){
201189    char *aBlock = 0;
201190    int nBlock = 0;
201191    iNewStart = iBlock;
201192
201193    rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
201194    if( rc==SQLITE_OK ){
201195      rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
201196    }
201197    if( rc==SQLITE_OK ){
201198      rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
201199    }
201200    sqlite3_free(aBlock);
201201  }
201202
201203  /* Variable iNewStart now contains the first valid leaf node. */
201204  if( rc==SQLITE_OK && iNewStart ){
201205    sqlite3_stmt *pDel = 0;
201206    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
201207    if( rc==SQLITE_OK ){
201208      sqlite3_bind_int64(pDel, 1, iOldStart);
201209      sqlite3_bind_int64(pDel, 2, iNewStart-1);
201210      sqlite3_step(pDel);
201211      rc = sqlite3_reset(pDel);
201212    }
201213  }
201214
201215  if( rc==SQLITE_OK ){
201216    sqlite3_stmt *pChomp = 0;
201217    rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
201218    if( rc==SQLITE_OK ){
201219      sqlite3_bind_int64(pChomp, 1, iNewStart);
201220      sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
201221      sqlite3_bind_int64(pChomp, 3, iAbsLevel);
201222      sqlite3_bind_int(pChomp, 4, iIdx);
201223      sqlite3_step(pChomp);
201224      rc = sqlite3_reset(pChomp);
201225      sqlite3_bind_null(pChomp, 2);
201226    }
201227  }
201228
201229  sqlite3_free(root.a);
201230  sqlite3_free(block.a);
201231  return rc;
201232}
201233
201234/*
201235** This function is called after an incrmental-merge operation has run to
201236** merge (or partially merge) two or more segments from absolute level
201237** iAbsLevel.
201238**
201239** Each input segment is either removed from the db completely (if all of
201240** its data was copied to the output segment by the incrmerge operation)
201241** or modified in place so that it no longer contains those entries that
201242** have been duplicated in the output segment.
201243*/
201244static int fts3IncrmergeChomp(
201245  Fts3Table *p,                   /* FTS table handle */
201246  sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
201247  Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
201248  int *pnRem                      /* Number of segments not deleted */
201249){
201250  int i;
201251  int nRem = 0;
201252  int rc = SQLITE_OK;
201253
201254  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
201255    Fts3SegReader *pSeg = 0;
201256    int j;
201257
201258    /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
201259    ** somewhere in the pCsr->apSegment[] array.  */
201260    for(j=0; ALWAYS(j<pCsr->nSegment); j++){
201261      pSeg = pCsr->apSegment[j];
201262      if( pSeg->iIdx==i ) break;
201263    }
201264    assert( j<pCsr->nSegment && pSeg->iIdx==i );
201265
201266    if( pSeg->aNode==0 ){
201267      /* Seg-reader is at EOF. Remove the entire input segment. */
201268      rc = fts3DeleteSegment(p, pSeg);
201269      if( rc==SQLITE_OK ){
201270        rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
201271      }
201272      *pnRem = 0;
201273    }else{
201274      /* The incremental merge did not copy all the data from this
201275      ** segment to the upper level. The segment is modified in place
201276      ** so that it contains no keys smaller than zTerm/nTerm. */
201277      const char *zTerm = pSeg->zTerm;
201278      int nTerm = pSeg->nTerm;
201279      rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
201280      nRem++;
201281    }
201282  }
201283
201284  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
201285    rc = fts3RepackSegdirLevel(p, iAbsLevel);
201286  }
201287
201288  *pnRem = nRem;
201289  return rc;
201290}
201291
201292/*
201293** Store an incr-merge hint in the database.
201294*/
201295static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
201296  sqlite3_stmt *pReplace = 0;
201297  int rc;                         /* Return code */
201298
201299  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
201300  if( rc==SQLITE_OK ){
201301    sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
201302    sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
201303    sqlite3_step(pReplace);
201304    rc = sqlite3_reset(pReplace);
201305    sqlite3_bind_null(pReplace, 2);
201306  }
201307
201308  return rc;
201309}
201310
201311/*
201312** Load an incr-merge hint from the database. The incr-merge hint, if one
201313** exists, is stored in the rowid==1 row of the %_stat table.
201314**
201315** If successful, populate blob *pHint with the value read from the %_stat
201316** table and return SQLITE_OK. Otherwise, if an error occurs, return an
201317** SQLite error code.
201318*/
201319static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
201320  sqlite3_stmt *pSelect = 0;
201321  int rc;
201322
201323  pHint->n = 0;
201324  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
201325  if( rc==SQLITE_OK ){
201326    int rc2;
201327    sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
201328    if( SQLITE_ROW==sqlite3_step(pSelect) ){
201329      const char *aHint = sqlite3_column_blob(pSelect, 0);
201330      int nHint = sqlite3_column_bytes(pSelect, 0);
201331      if( aHint ){
201332        blobGrowBuffer(pHint, nHint, &rc);
201333        if( rc==SQLITE_OK ){
201334          if( ALWAYS(pHint->a!=0) ) memcpy(pHint->a, aHint, nHint);
201335          pHint->n = nHint;
201336        }
201337      }
201338    }
201339    rc2 = sqlite3_reset(pSelect);
201340    if( rc==SQLITE_OK ) rc = rc2;
201341  }
201342
201343  return rc;
201344}
201345
201346/*
201347** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
201348** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
201349** consists of two varints, the absolute level number of the input segments
201350** and the number of input segments.
201351**
201352** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
201353** set *pRc to an SQLite error code before returning.
201354*/
201355static void fts3IncrmergeHintPush(
201356  Blob *pHint,                    /* Hint blob to append to */
201357  i64 iAbsLevel,                  /* First varint to store in hint */
201358  int nInput,                     /* Second varint to store in hint */
201359  int *pRc                        /* IN/OUT: Error code */
201360){
201361  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
201362  if( *pRc==SQLITE_OK ){
201363    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
201364    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
201365  }
201366}
201367
201368/*
201369** Read the last entry (most recently pushed) from the hint blob *pHint
201370** and then remove the entry. Write the two values read to *piAbsLevel and
201371** *pnInput before returning.
201372**
201373** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
201374** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
201375*/
201376static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
201377  const int nHint = pHint->n;
201378  int i;
201379
201380  i = pHint->n-1;
201381  if( (pHint->a[i] & 0x80) ) return FTS_CORRUPT_VTAB;
201382  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
201383  if( i==0 ) return FTS_CORRUPT_VTAB;
201384  i--;
201385  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
201386
201387  pHint->n = i;
201388  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
201389  i += fts3GetVarint32(&pHint->a[i], pnInput);
201390  assert( i<=nHint );
201391  if( i!=nHint ) return FTS_CORRUPT_VTAB;
201392
201393  return SQLITE_OK;
201394}
201395
201396
201397/*
201398** Attempt an incremental merge that writes nMerge leaf blocks.
201399**
201400** Incremental merges happen nMin segments at a time. The segments
201401** to be merged are the nMin oldest segments (the ones with the smallest
201402** values for the _segdir.idx field) in the highest level that contains
201403** at least nMin segments. Multiple merges might occur in an attempt to
201404** write the quota of nMerge leaf blocks.
201405*/
201406SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
201407  int rc;                         /* Return code */
201408  int nRem = nMerge;              /* Number of leaf pages yet to  be written */
201409  Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
201410  Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
201411  IncrmergeWriter *pWriter;       /* Writer object */
201412  int nSeg = 0;                   /* Number of input segments */
201413  sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
201414  Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
201415  int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
201416
201417  /* Allocate space for the cursor, filter and writer objects */
201418  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
201419  pWriter = (IncrmergeWriter *)sqlite3_malloc64(nAlloc);
201420  if( !pWriter ) return SQLITE_NOMEM;
201421  pFilter = (Fts3SegFilter *)&pWriter[1];
201422  pCsr = (Fts3MultiSegReader *)&pFilter[1];
201423
201424  rc = fts3IncrmergeHintLoad(p, &hint);
201425  while( rc==SQLITE_OK && nRem>0 ){
201426    const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
201427    sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
201428    int bUseHint = 0;             /* True if attempting to append */
201429    int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
201430
201431    /* Search the %_segdir table for the absolute level with the smallest
201432    ** relative level number that contains at least nMin segments, if any.
201433    ** If one is found, set iAbsLevel to the absolute level number and
201434    ** nSeg to nMin. If no level with at least nMin segments can be found,
201435    ** set nSeg to -1.
201436    */
201437    rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
201438    sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
201439    if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
201440      iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
201441      nSeg = sqlite3_column_int(pFindLevel, 1);
201442      assert( nSeg>=2 );
201443    }else{
201444      nSeg = -1;
201445    }
201446    rc = sqlite3_reset(pFindLevel);
201447
201448    /* If the hint read from the %_stat table is not empty, check if the
201449    ** last entry in it specifies a relative level smaller than or equal
201450    ** to the level identified by the block above (if any). If so, this
201451    ** iteration of the loop will work on merging at the hinted level.
201452    */
201453    if( rc==SQLITE_OK && hint.n ){
201454      int nHint = hint.n;
201455      sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
201456      int nHintSeg = 0;                     /* Hint number of segments */
201457
201458      rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
201459      if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
201460        /* Based on the scan in the block above, it is known that there
201461        ** are no levels with a relative level smaller than that of
201462        ** iAbsLevel with more than nSeg segments, or if nSeg is -1,
201463        ** no levels with more than nMin segments. Use this to limit the
201464        ** value of nHintSeg to avoid a large memory allocation in case the
201465        ** merge-hint is corrupt*/
201466        iAbsLevel = iHintAbsLevel;
201467        nSeg = MIN(MAX(nMin,nSeg), nHintSeg);
201468        bUseHint = 1;
201469        bDirtyHint = 1;
201470      }else{
201471        /* This undoes the effect of the HintPop() above - so that no entry
201472        ** is removed from the hint blob.  */
201473        hint.n = nHint;
201474      }
201475    }
201476
201477    /* If nSeg is less that zero, then there is no level with at least
201478    ** nMin segments and no hint in the %_stat table. No work to do.
201479    ** Exit early in this case.  */
201480    if( nSeg<=0 ) break;
201481
201482    assert( nMod<=0x7FFFFFFF );
201483    if( iAbsLevel<0 || iAbsLevel>(nMod<<32) ){
201484      rc = FTS_CORRUPT_VTAB;
201485      break;
201486    }
201487
201488    /* Open a cursor to iterate through the contents of the oldest nSeg
201489    ** indexes of absolute level iAbsLevel. If this cursor is opened using
201490    ** the 'hint' parameters, it is possible that there are less than nSeg
201491    ** segments available in level iAbsLevel. In this case, no work is
201492    ** done on iAbsLevel - fall through to the next iteration of the loop
201493    ** to start work on some other level.  */
201494    memset(pWriter, 0, nAlloc);
201495    pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
201496
201497    if( rc==SQLITE_OK ){
201498      rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
201499      assert( bUseHint==1 || bUseHint==0 );
201500      if( iIdx==0 || (bUseHint && iIdx==1) ){
201501        int bIgnore = 0;
201502        rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
201503        if( bIgnore ){
201504          pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
201505        }
201506      }
201507    }
201508
201509    if( rc==SQLITE_OK ){
201510      rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
201511    }
201512    if( SQLITE_OK==rc && pCsr->nSegment==nSeg
201513     && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
201514    ){
201515      int bEmpty = 0;
201516      rc = sqlite3Fts3SegReaderStep(p, pCsr);
201517      if( rc==SQLITE_OK ){
201518        bEmpty = 1;
201519      }else if( rc!=SQLITE_ROW ){
201520        sqlite3Fts3SegReaderFinish(pCsr);
201521        break;
201522      }
201523      if( bUseHint && iIdx>0 ){
201524        const char *zKey = pCsr->zTerm;
201525        int nKey = pCsr->nTerm;
201526        rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
201527      }else{
201528        rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
201529      }
201530
201531      if( rc==SQLITE_OK && pWriter->nLeafEst ){
201532        fts3LogMerge(nSeg, iAbsLevel);
201533        if( bEmpty==0 ){
201534          do {
201535            rc = fts3IncrmergeAppend(p, pWriter, pCsr);
201536            if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
201537            if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
201538          }while( rc==SQLITE_ROW );
201539        }
201540
201541        /* Update or delete the input segments */
201542        if( rc==SQLITE_OK ){
201543          nRem -= (1 + pWriter->nWork);
201544          rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
201545          if( nSeg!=0 ){
201546            bDirtyHint = 1;
201547            fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
201548          }
201549        }
201550      }
201551
201552      if( nSeg!=0 ){
201553        pWriter->nLeafData = pWriter->nLeafData * -1;
201554      }
201555      fts3IncrmergeRelease(p, pWriter, &rc);
201556      if( nSeg==0 && pWriter->bNoLeafData==0 ){
201557        fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
201558      }
201559    }
201560
201561    sqlite3Fts3SegReaderFinish(pCsr);
201562  }
201563
201564  /* Write the hint values into the %_stat table for the next incr-merger */
201565  if( bDirtyHint && rc==SQLITE_OK ){
201566    rc = fts3IncrmergeHintStore(p, &hint);
201567  }
201568
201569  sqlite3_free(pWriter);
201570  sqlite3_free(hint.a);
201571  return rc;
201572}
201573
201574/*
201575** Convert the text beginning at *pz into an integer and return
201576** its value.  Advance *pz to point to the first character past
201577** the integer.
201578**
201579** This function used for parameters to merge= and incrmerge=
201580** commands.
201581*/
201582static int fts3Getint(const char **pz){
201583  const char *z = *pz;
201584  int i = 0;
201585  while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
201586  *pz = z;
201587  return i;
201588}
201589
201590/*
201591** Process statements of the form:
201592**
201593**    INSERT INTO table(table) VALUES('merge=A,B');
201594**
201595** A and B are integers that decode to be the number of leaf pages
201596** written for the merge, and the minimum number of segments on a level
201597** before it will be selected for a merge, respectively.
201598*/
201599static int fts3DoIncrmerge(
201600  Fts3Table *p,                   /* FTS3 table handle */
201601  const char *zParam              /* Nul-terminated string containing "A,B" */
201602){
201603  int rc;
201604  int nMin = (MergeCount(p) / 2);
201605  int nMerge = 0;
201606  const char *z = zParam;
201607
201608  /* Read the first integer value */
201609  nMerge = fts3Getint(&z);
201610
201611  /* If the first integer value is followed by a ',',  read the second
201612  ** integer value. */
201613  if( z[0]==',' && z[1]!='\0' ){
201614    z++;
201615    nMin = fts3Getint(&z);
201616  }
201617
201618  if( z[0]!='\0' || nMin<2 ){
201619    rc = SQLITE_ERROR;
201620  }else{
201621    rc = SQLITE_OK;
201622    if( !p->bHasStat ){
201623      assert( p->bFts4==0 );
201624      sqlite3Fts3CreateStatTable(&rc, p);
201625    }
201626    if( rc==SQLITE_OK ){
201627      rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
201628    }
201629    sqlite3Fts3SegmentsClose(p);
201630  }
201631  return rc;
201632}
201633
201634/*
201635** Process statements of the form:
201636**
201637**    INSERT INTO table(table) VALUES('automerge=X');
201638**
201639** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
201640** turn it on.  The setting is persistent.
201641*/
201642static int fts3DoAutoincrmerge(
201643  Fts3Table *p,                   /* FTS3 table handle */
201644  const char *zParam              /* Nul-terminated string containing boolean */
201645){
201646  int rc = SQLITE_OK;
201647  sqlite3_stmt *pStmt = 0;
201648  p->nAutoincrmerge = fts3Getint(&zParam);
201649  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>MergeCount(p) ){
201650    p->nAutoincrmerge = 8;
201651  }
201652  if( !p->bHasStat ){
201653    assert( p->bFts4==0 );
201654    sqlite3Fts3CreateStatTable(&rc, p);
201655    if( rc ) return rc;
201656  }
201657  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
201658  if( rc ) return rc;
201659  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
201660  sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
201661  sqlite3_step(pStmt);
201662  rc = sqlite3_reset(pStmt);
201663  return rc;
201664}
201665
201666/*
201667** Return a 64-bit checksum for the FTS index entry specified by the
201668** arguments to this function.
201669*/
201670static u64 fts3ChecksumEntry(
201671  const char *zTerm,              /* Pointer to buffer containing term */
201672  int nTerm,                      /* Size of zTerm in bytes */
201673  int iLangid,                    /* Language id for current row */
201674  int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
201675  i64 iDocid,                     /* Docid for current row. */
201676  int iCol,                       /* Column number */
201677  int iPos                        /* Position */
201678){
201679  int i;
201680  u64 ret = (u64)iDocid;
201681
201682  ret += (ret<<3) + iLangid;
201683  ret += (ret<<3) + iIndex;
201684  ret += (ret<<3) + iCol;
201685  ret += (ret<<3) + iPos;
201686  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
201687
201688  return ret;
201689}
201690
201691/*
201692** Return a checksum of all entries in the FTS index that correspond to
201693** language id iLangid. The checksum is calculated by XORing the checksums
201694** of each individual entry (see fts3ChecksumEntry()) together.
201695**
201696** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
201697** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
201698** return value is undefined in this case.
201699*/
201700static u64 fts3ChecksumIndex(
201701  Fts3Table *p,                   /* FTS3 table handle */
201702  int iLangid,                    /* Language id to return cksum for */
201703  int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
201704  int *pRc                        /* OUT: Return code */
201705){
201706  Fts3SegFilter filter;
201707  Fts3MultiSegReader csr;
201708  int rc;
201709  u64 cksum = 0;
201710
201711  if( *pRc ) return 0;
201712
201713  memset(&filter, 0, sizeof(filter));
201714  memset(&csr, 0, sizeof(csr));
201715  filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
201716  filter.flags |= FTS3_SEGMENT_SCAN;
201717
201718  rc = sqlite3Fts3SegReaderCursor(
201719      p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
201720  );
201721  if( rc==SQLITE_OK ){
201722    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
201723  }
201724
201725  if( rc==SQLITE_OK ){
201726    while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
201727      char *pCsr = csr.aDoclist;
201728      char *pEnd = &pCsr[csr.nDoclist];
201729
201730      i64 iDocid = 0;
201731      i64 iCol = 0;
201732      u64 iPos = 0;
201733
201734      pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
201735      while( pCsr<pEnd ){
201736        u64 iVal = 0;
201737        pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);
201738        if( pCsr<pEnd ){
201739          if( iVal==0 || iVal==1 ){
201740            iCol = 0;
201741            iPos = 0;
201742            if( iVal ){
201743              pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
201744            }else{
201745              pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);
201746              if( p->bDescIdx ){
201747                iDocid = (i64)((u64)iDocid - iVal);
201748              }else{
201749                iDocid = (i64)((u64)iDocid + iVal);
201750              }
201751            }
201752          }else{
201753            iPos += (iVal - 2);
201754            cksum = cksum ^ fts3ChecksumEntry(
201755                csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
201756                (int)iCol, (int)iPos
201757            );
201758          }
201759        }
201760      }
201761    }
201762  }
201763  sqlite3Fts3SegReaderFinish(&csr);
201764
201765  *pRc = rc;
201766  return cksum;
201767}
201768
201769/*
201770** Check if the contents of the FTS index match the current contents of the
201771** content table. If no error occurs and the contents do match, set *pbOk
201772** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
201773** to false before returning.
201774**
201775** If an error occurs (e.g. an OOM or IO error), return an SQLite error
201776** code. The final value of *pbOk is undefined in this case.
201777*/
201778SQLITE_PRIVATE int sqlite3Fts3IntegrityCheck(Fts3Table *p, int *pbOk){
201779  int rc = SQLITE_OK;             /* Return code */
201780  u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
201781  u64 cksum2 = 0;                 /* Checksum based on %_content contents */
201782  sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
201783
201784  /* This block calculates the checksum according to the FTS index. */
201785  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
201786  if( rc==SQLITE_OK ){
201787    int rc2;
201788    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
201789    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
201790    while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
201791      int iLangid = sqlite3_column_int(pAllLangid, 0);
201792      int i;
201793      for(i=0; i<p->nIndex; i++){
201794        cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
201795      }
201796    }
201797    rc2 = sqlite3_reset(pAllLangid);
201798    if( rc==SQLITE_OK ) rc = rc2;
201799  }
201800
201801  /* This block calculates the checksum according to the %_content table */
201802  if( rc==SQLITE_OK ){
201803    sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
201804    sqlite3_stmt *pStmt = 0;
201805    char *zSql;
201806
201807    zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
201808    if( !zSql ){
201809      rc = SQLITE_NOMEM;
201810    }else{
201811      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
201812      sqlite3_free(zSql);
201813    }
201814
201815    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
201816      i64 iDocid = sqlite3_column_int64(pStmt, 0);
201817      int iLang = langidFromSelect(p, pStmt);
201818      int iCol;
201819
201820      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
201821        if( p->abNotindexed[iCol]==0 ){
201822          const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
201823          sqlite3_tokenizer_cursor *pT = 0;
201824
201825          rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, -1, &pT);
201826          while( rc==SQLITE_OK ){
201827            char const *zToken;       /* Buffer containing token */
201828            int nToken = 0;           /* Number of bytes in token */
201829            int iDum1 = 0, iDum2 = 0; /* Dummy variables */
201830            int iPos = 0;             /* Position of token in zText */
201831
201832            rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
201833            if( rc==SQLITE_OK ){
201834              int i;
201835              cksum2 = cksum2 ^ fts3ChecksumEntry(
201836                  zToken, nToken, iLang, 0, iDocid, iCol, iPos
201837              );
201838              for(i=1; i<p->nIndex; i++){
201839                if( p->aIndex[i].nPrefix<=nToken ){
201840                  cksum2 = cksum2 ^ fts3ChecksumEntry(
201841                      zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
201842                  );
201843                }
201844              }
201845            }
201846          }
201847          if( pT ) pModule->xClose(pT);
201848          if( rc==SQLITE_DONE ) rc = SQLITE_OK;
201849        }
201850      }
201851    }
201852
201853    sqlite3_finalize(pStmt);
201854  }
201855
201856  if( rc==SQLITE_CORRUPT_VTAB ){
201857    rc = SQLITE_OK;
201858    *pbOk = 0;
201859  }else{
201860    *pbOk = (rc==SQLITE_OK && cksum1==cksum2);
201861  }
201862  return rc;
201863}
201864
201865/*
201866** Run the integrity-check. If no error occurs and the current contents of
201867** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
201868** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
201869**
201870** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
201871** error code.
201872**
201873** The integrity-check works as follows. For each token and indexed token
201874** prefix in the document set, a 64-bit checksum is calculated (by code
201875** in fts3ChecksumEntry()) based on the following:
201876**
201877**     + The index number (0 for the main index, 1 for the first prefix
201878**       index etc.),
201879**     + The token (or token prefix) text itself,
201880**     + The language-id of the row it appears in,
201881**     + The docid of the row it appears in,
201882**     + The column it appears in, and
201883**     + The tokens position within that column.
201884**
201885** The checksums for all entries in the index are XORed together to create
201886** a single checksum for the entire index.
201887**
201888** The integrity-check code calculates the same checksum in two ways:
201889**
201890**     1. By scanning the contents of the FTS index, and
201891**     2. By scanning and tokenizing the content table.
201892**
201893** If the two checksums are identical, the integrity-check is deemed to have
201894** passed.
201895*/
201896static int fts3DoIntegrityCheck(
201897  Fts3Table *p                    /* FTS3 table handle */
201898){
201899  int rc;
201900  int bOk = 0;
201901  rc = sqlite3Fts3IntegrityCheck(p, &bOk);
201902  if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
201903  return rc;
201904}
201905
201906/*
201907** Handle a 'special' INSERT of the form:
201908**
201909**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
201910**
201911** Argument pVal contains the result of <expr>. Currently the only
201912** meaningful value to insert is the text 'optimize'.
201913*/
201914static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
201915  int rc = SQLITE_ERROR;           /* Return Code */
201916  const char *zVal = (const char *)sqlite3_value_text(pVal);
201917  int nVal = sqlite3_value_bytes(pVal);
201918
201919  if( !zVal ){
201920    return SQLITE_NOMEM;
201921  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
201922    rc = fts3DoOptimize(p, 0);
201923  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
201924    rc = fts3DoRebuild(p);
201925  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
201926    rc = fts3DoIntegrityCheck(p);
201927  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
201928    rc = fts3DoIncrmerge(p, &zVal[6]);
201929  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
201930    rc = fts3DoAutoincrmerge(p, &zVal[10]);
201931  }else if( nVal==5 && 0==sqlite3_strnicmp(zVal, "flush", 5) ){
201932    rc = sqlite3Fts3PendingTermsFlush(p);
201933  }
201934#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
201935  else{
201936    int v;
201937    if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
201938      v = atoi(&zVal[9]);
201939      if( v>=24 && v<=p->nPgsz-35 ) p->nNodeSize = v;
201940      rc = SQLITE_OK;
201941    }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
201942      v = atoi(&zVal[11]);
201943      if( v>=64 && v<=FTS3_MAX_PENDING_DATA ) p->nMaxPendingData = v;
201944      rc = SQLITE_OK;
201945    }else if( nVal>21 && 0==sqlite3_strnicmp(zVal,"test-no-incr-doclist=",21) ){
201946      p->bNoIncrDoclist = atoi(&zVal[21]);
201947      rc = SQLITE_OK;
201948    }else if( nVal>11 && 0==sqlite3_strnicmp(zVal,"mergecount=",11) ){
201949      v = atoi(&zVal[11]);
201950      if( v>=4 && v<=FTS3_MERGE_COUNT && (v&1)==0 ) p->nMergeCount = v;
201951      rc = SQLITE_OK;
201952    }
201953  }
201954#endif
201955  return rc;
201956}
201957
201958#ifndef SQLITE_DISABLE_FTS4_DEFERRED
201959/*
201960** Delete all cached deferred doclists. Deferred doclists are cached
201961** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
201962*/
201963SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
201964  Fts3DeferredToken *pDef;
201965  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
201966    fts3PendingListDelete(pDef->pList);
201967    pDef->pList = 0;
201968  }
201969}
201970
201971/*
201972** Free all entries in the pCsr->pDeffered list. Entries are added to
201973** this list using sqlite3Fts3DeferToken().
201974*/
201975SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
201976  Fts3DeferredToken *pDef;
201977  Fts3DeferredToken *pNext;
201978  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
201979    pNext = pDef->pNext;
201980    fts3PendingListDelete(pDef->pList);
201981    sqlite3_free(pDef);
201982  }
201983  pCsr->pDeferred = 0;
201984}
201985
201986/*
201987** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
201988** based on the row that pCsr currently points to.
201989**
201990** A deferred-doclist is like any other doclist with position information
201991** included, except that it only contains entries for a single row of the
201992** table, not for all rows.
201993*/
201994SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
201995  int rc = SQLITE_OK;             /* Return code */
201996  if( pCsr->pDeferred ){
201997    int i;                        /* Used to iterate through table columns */
201998    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
201999    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
202000
202001    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
202002    sqlite3_tokenizer *pT = p->pTokenizer;
202003    sqlite3_tokenizer_module const *pModule = pT->pModule;
202004
202005    assert( pCsr->isRequireSeek==0 );
202006    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
202007
202008    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
202009      if( p->abNotindexed[i]==0 ){
202010        const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
202011        sqlite3_tokenizer_cursor *pTC = 0;
202012
202013        rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
202014        while( rc==SQLITE_OK ){
202015          char const *zToken;       /* Buffer containing token */
202016          int nToken = 0;           /* Number of bytes in token */
202017          int iDum1 = 0, iDum2 = 0; /* Dummy variables */
202018          int iPos = 0;             /* Position of token in zText */
202019
202020          rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
202021          for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
202022            Fts3PhraseToken *pPT = pDef->pToken;
202023            if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
202024                && (pPT->bFirst==0 || iPos==0)
202025                && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
202026                && (0==memcmp(zToken, pPT->z, pPT->n))
202027              ){
202028              fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
202029            }
202030          }
202031        }
202032        if( pTC ) pModule->xClose(pTC);
202033        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
202034      }
202035    }
202036
202037    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
202038      if( pDef->pList ){
202039        rc = fts3PendingListAppendVarint(&pDef->pList, 0);
202040      }
202041    }
202042  }
202043
202044  return rc;
202045}
202046
202047SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
202048  Fts3DeferredToken *p,
202049  char **ppData,
202050  int *pnData
202051){
202052  char *pRet;
202053  int nSkip;
202054  sqlite3_int64 dummy;
202055
202056  *ppData = 0;
202057  *pnData = 0;
202058
202059  if( p->pList==0 ){
202060    return SQLITE_OK;
202061  }
202062
202063  pRet = (char *)sqlite3_malloc64(p->pList->nData);
202064  if( !pRet ) return SQLITE_NOMEM;
202065
202066  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
202067  *pnData = p->pList->nData - nSkip;
202068  *ppData = pRet;
202069
202070  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
202071  return SQLITE_OK;
202072}
202073
202074/*
202075** Add an entry for token pToken to the pCsr->pDeferred list.
202076*/
202077SQLITE_PRIVATE int sqlite3Fts3DeferToken(
202078  Fts3Cursor *pCsr,               /* Fts3 table cursor */
202079  Fts3PhraseToken *pToken,        /* Token to defer */
202080  int iCol                        /* Column that token must appear in (or -1) */
202081){
202082  Fts3DeferredToken *pDeferred;
202083  pDeferred = sqlite3_malloc64(sizeof(*pDeferred));
202084  if( !pDeferred ){
202085    return SQLITE_NOMEM;
202086  }
202087  memset(pDeferred, 0, sizeof(*pDeferred));
202088  pDeferred->pToken = pToken;
202089  pDeferred->pNext = pCsr->pDeferred;
202090  pDeferred->iCol = iCol;
202091  pCsr->pDeferred = pDeferred;
202092
202093  assert( pToken->pDeferred==0 );
202094  pToken->pDeferred = pDeferred;
202095
202096  return SQLITE_OK;
202097}
202098#endif
202099
202100/*
202101** SQLite value pRowid contains the rowid of a row that may or may not be
202102** present in the FTS3 table. If it is, delete it and adjust the contents
202103** of subsiduary data structures accordingly.
202104*/
202105static int fts3DeleteByRowid(
202106  Fts3Table *p,
202107  sqlite3_value *pRowid,
202108  int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
202109  u32 *aSzDel
202110){
202111  int rc = SQLITE_OK;             /* Return code */
202112  int bFound = 0;                 /* True if *pRowid really is in the table */
202113
202114  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
202115  if( bFound && rc==SQLITE_OK ){
202116    int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
202117    rc = fts3IsEmpty(p, pRowid, &isEmpty);
202118    if( rc==SQLITE_OK ){
202119      if( isEmpty ){
202120        /* Deleting this row means the whole table is empty. In this case
202121        ** delete the contents of all three tables and throw away any
202122        ** data in the pendingTerms hash table.  */
202123        rc = fts3DeleteAll(p, 1);
202124        *pnChng = 0;
202125        memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
202126      }else{
202127        *pnChng = *pnChng - 1;
202128        if( p->zContentTbl==0 ){
202129          fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
202130        }
202131        if( p->bHasDocsize ){
202132          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
202133        }
202134      }
202135    }
202136  }
202137
202138  return rc;
202139}
202140
202141/*
202142** This function does the work for the xUpdate method of FTS3 virtual
202143** tables. The schema of the virtual table being:
202144**
202145**     CREATE TABLE <table name>(
202146**       <user columns>,
202147**       <table name> HIDDEN,
202148**       docid HIDDEN,
202149**       <langid> HIDDEN
202150**     );
202151**
202152**
202153*/
202154SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
202155  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
202156  int nArg,                       /* Size of argument array */
202157  sqlite3_value **apVal,          /* Array of arguments */
202158  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
202159){
202160  Fts3Table *p = (Fts3Table *)pVtab;
202161  int rc = SQLITE_OK;             /* Return Code */
202162  u32 *aSzIns = 0;                /* Sizes of inserted documents */
202163  u32 *aSzDel = 0;                /* Sizes of deleted documents */
202164  int nChng = 0;                  /* Net change in number of documents */
202165  int bInsertDone = 0;
202166
202167  /* At this point it must be known if the %_stat table exists or not.
202168  ** So bHasStat may not be 2.  */
202169  assert( p->bHasStat==0 || p->bHasStat==1 );
202170
202171  assert( p->pSegments==0 );
202172  assert(
202173      nArg==1                     /* DELETE operations */
202174   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
202175  );
202176
202177  /* Check for a "special" INSERT operation. One of the form:
202178  **
202179  **   INSERT INTO xyz(xyz) VALUES('command');
202180  */
202181  if( nArg>1
202182   && sqlite3_value_type(apVal[0])==SQLITE_NULL
202183   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
202184  ){
202185    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
202186    goto update_out;
202187  }
202188
202189  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
202190    rc = SQLITE_CONSTRAINT;
202191    goto update_out;
202192  }
202193
202194  /* Allocate space to hold the change in document sizes */
202195  aSzDel = sqlite3_malloc64(sizeof(aSzDel[0])*((sqlite3_int64)p->nColumn+1)*2);
202196  if( aSzDel==0 ){
202197    rc = SQLITE_NOMEM;
202198    goto update_out;
202199  }
202200  aSzIns = &aSzDel[p->nColumn+1];
202201  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
202202
202203  rc = fts3Writelock(p);
202204  if( rc!=SQLITE_OK ) goto update_out;
202205
202206  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
202207  ** value, then this operation requires constraint handling.
202208  **
202209  ** If the on-conflict mode is REPLACE, this means that the existing row
202210  ** should be deleted from the database before inserting the new row. Or,
202211  ** if the on-conflict mode is other than REPLACE, then this method must
202212  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
202213  ** modify the database file.
202214  */
202215  if( nArg>1 && p->zContentTbl==0 ){
202216    /* Find the value object that holds the new rowid value. */
202217    sqlite3_value *pNewRowid = apVal[3+p->nColumn];
202218    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
202219      pNewRowid = apVal[1];
202220    }
202221
202222    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
202223        sqlite3_value_type(apVal[0])==SQLITE_NULL
202224     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
202225    )){
202226      /* The new rowid is not NULL (in this case the rowid will be
202227      ** automatically assigned and there is no chance of a conflict), and
202228      ** the statement is either an INSERT or an UPDATE that modifies the
202229      ** rowid column. So if the conflict mode is REPLACE, then delete any
202230      ** existing row with rowid=pNewRowid.
202231      **
202232      ** Or, if the conflict mode is not REPLACE, insert the new record into
202233      ** the %_content table. If we hit the duplicate rowid constraint (or any
202234      ** other error) while doing so, return immediately.
202235      **
202236      ** This branch may also run if pNewRowid contains a value that cannot
202237      ** be losslessly converted to an integer. In this case, the eventual
202238      ** call to fts3InsertData() (either just below or further on in this
202239      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
202240      ** invoked, it will delete zero rows (since no row will have
202241      ** docid=$pNewRowid if $pNewRowid is not an integer value).
202242      */
202243      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
202244        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
202245      }else{
202246        rc = fts3InsertData(p, apVal, pRowid);
202247        bInsertDone = 1;
202248      }
202249    }
202250  }
202251  if( rc!=SQLITE_OK ){
202252    goto update_out;
202253  }
202254
202255  /* If this is a DELETE or UPDATE operation, remove the old record. */
202256  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
202257    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
202258    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
202259  }
202260
202261  /* If this is an INSERT or UPDATE operation, insert the new record. */
202262  if( nArg>1 && rc==SQLITE_OK ){
202263    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
202264    if( bInsertDone==0 ){
202265      rc = fts3InsertData(p, apVal, pRowid);
202266      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
202267        rc = FTS_CORRUPT_VTAB;
202268      }
202269    }
202270    if( rc==SQLITE_OK ){
202271      rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
202272    }
202273    if( rc==SQLITE_OK ){
202274      assert( p->iPrevDocid==*pRowid );
202275      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
202276    }
202277    if( p->bHasDocsize ){
202278      fts3InsertDocsize(&rc, p, aSzIns);
202279    }
202280    nChng++;
202281  }
202282
202283  if( p->bFts4 ){
202284    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
202285  }
202286
202287 update_out:
202288  sqlite3_free(aSzDel);
202289  sqlite3Fts3SegmentsClose(p);
202290  return rc;
202291}
202292
202293/*
202294** Flush any data in the pending-terms hash table to disk. If successful,
202295** merge all segments in the database (including the new segment, if
202296** there was any data to flush) into a single segment.
202297*/
202298SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
202299  int rc;
202300  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
202301  if( rc==SQLITE_OK ){
202302    rc = fts3DoOptimize(p, 1);
202303    if( rc==SQLITE_OK || rc==SQLITE_DONE ){
202304      int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
202305      if( rc2!=SQLITE_OK ) rc = rc2;
202306    }else{
202307      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
202308      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
202309    }
202310  }
202311  sqlite3Fts3SegmentsClose(p);
202312  return rc;
202313}
202314
202315#endif
202316
202317/************** End of fts3_write.c ******************************************/
202318/************** Begin file fts3_snippet.c ************************************/
202319/*
202320** 2009 Oct 23
202321**
202322** The author disclaims copyright to this source code.  In place of
202323** a legal notice, here is a blessing:
202324**
202325**    May you do good and not evil.
202326**    May you find forgiveness for yourself and forgive others.
202327**    May you share freely, never taking more than you give.
202328**
202329******************************************************************************
202330*/
202331
202332/* #include "fts3Int.h" */
202333#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
202334
202335/* #include <string.h> */
202336/* #include <assert.h> */
202337
202338#ifndef SQLITE_AMALGAMATION
202339typedef sqlite3_int64 i64;
202340#endif
202341
202342/*
202343** Characters that may appear in the second argument to matchinfo().
202344*/
202345#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
202346#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
202347#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
202348#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
202349#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
202350#define FTS3_MATCHINFO_LCS       's'        /* nCol values */
202351#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
202352#define FTS3_MATCHINFO_LHITS     'y'        /* nCol*nPhrase values */
202353#define FTS3_MATCHINFO_LHITS_BM  'b'        /* nCol*nPhrase values */
202354
202355/*
202356** The default value for the second argument to matchinfo().
202357*/
202358#define FTS3_MATCHINFO_DEFAULT   "pcx"
202359
202360
202361/*
202362** Used as an sqlite3Fts3ExprIterate() context when loading phrase doclists to
202363** Fts3Expr.aDoclist[]/nDoclist.
202364*/
202365typedef struct LoadDoclistCtx LoadDoclistCtx;
202366struct LoadDoclistCtx {
202367  Fts3Cursor *pCsr;               /* FTS3 Cursor */
202368  int nPhrase;                    /* Number of phrases seen so far */
202369  int nToken;                     /* Number of tokens seen so far */
202370};
202371
202372/*
202373** The following types are used as part of the implementation of the
202374** fts3BestSnippet() routine.
202375*/
202376typedef struct SnippetIter SnippetIter;
202377typedef struct SnippetPhrase SnippetPhrase;
202378typedef struct SnippetFragment SnippetFragment;
202379
202380struct SnippetIter {
202381  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
202382  int iCol;                       /* Extract snippet from this column */
202383  int nSnippet;                   /* Requested snippet length (in tokens) */
202384  int nPhrase;                    /* Number of phrases in query */
202385  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
202386  int iCurrent;                   /* First token of current snippet */
202387};
202388
202389struct SnippetPhrase {
202390  int nToken;                     /* Number of tokens in phrase */
202391  char *pList;                    /* Pointer to start of phrase position list */
202392  i64 iHead;                      /* Next value in position list */
202393  char *pHead;                    /* Position list data following iHead */
202394  i64 iTail;                      /* Next value in trailing position list */
202395  char *pTail;                    /* Position list data following iTail */
202396};
202397
202398struct SnippetFragment {
202399  int iCol;                       /* Column snippet is extracted from */
202400  int iPos;                       /* Index of first token in snippet */
202401  u64 covered;                    /* Mask of query phrases covered */
202402  u64 hlmask;                     /* Mask of snippet terms to highlight */
202403};
202404
202405/*
202406** This type is used as an sqlite3Fts3ExprIterate() context object while
202407** accumulating the data returned by the matchinfo() function.
202408*/
202409typedef struct MatchInfo MatchInfo;
202410struct MatchInfo {
202411  Fts3Cursor *pCursor;            /* FTS3 Cursor */
202412  int nCol;                       /* Number of columns in table */
202413  int nPhrase;                    /* Number of matchable phrases in query */
202414  sqlite3_int64 nDoc;             /* Number of docs in database */
202415  char flag;
202416  u32 *aMatchinfo;                /* Pre-allocated buffer */
202417};
202418
202419/*
202420** An instance of this structure is used to manage a pair of buffers, each
202421** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
202422** for details.
202423*/
202424struct MatchinfoBuffer {
202425  u8 aRef[3];
202426  int nElem;
202427  int bGlobal;                    /* Set if global data is loaded */
202428  char *zMatchinfo;
202429  u32 aMatchinfo[1];
202430};
202431
202432
202433/*
202434** The snippet() and offsets() functions both return text values. An instance
202435** of the following structure is used to accumulate those values while the
202436** functions are running. See fts3StringAppend() for details.
202437*/
202438typedef struct StrBuffer StrBuffer;
202439struct StrBuffer {
202440  char *z;                        /* Pointer to buffer containing string */
202441  int n;                          /* Length of z in bytes (excl. nul-term) */
202442  int nAlloc;                     /* Allocated size of buffer z in bytes */
202443};
202444
202445
202446/*************************************************************************
202447** Start of MatchinfoBuffer code.
202448*/
202449
202450/*
202451** Allocate a two-slot MatchinfoBuffer object.
202452*/
202453static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){
202454  MatchinfoBuffer *pRet;
202455  sqlite3_int64 nByte = sizeof(u32) * (2*(sqlite3_int64)nElem + 1)
202456                           + sizeof(MatchinfoBuffer);
202457  sqlite3_int64 nStr = strlen(zMatchinfo);
202458
202459  pRet = sqlite3Fts3MallocZero(nByte + nStr+1);
202460  if( pRet ){
202461    pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
202462    pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0]
202463                                      + sizeof(u32)*((int)nElem+1);
202464    pRet->nElem = (int)nElem;
202465    pRet->zMatchinfo = ((char*)pRet) + nByte;
202466    memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
202467    pRet->aRef[0] = 1;
202468  }
202469
202470  return pRet;
202471}
202472
202473static void fts3MIBufferFree(void *p){
202474  MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
202475
202476  assert( (u32*)p==&pBuf->aMatchinfo[1]
202477       || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
202478  );
202479  if( (u32*)p==&pBuf->aMatchinfo[1] ){
202480    pBuf->aRef[1] = 0;
202481  }else{
202482    pBuf->aRef[2] = 0;
202483  }
202484
202485  if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
202486    sqlite3_free(pBuf);
202487  }
202488}
202489
202490static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
202491  void (*xRet)(void*) = 0;
202492  u32 *aOut = 0;
202493
202494  if( p->aRef[1]==0 ){
202495    p->aRef[1] = 1;
202496    aOut = &p->aMatchinfo[1];
202497    xRet = fts3MIBufferFree;
202498  }
202499  else if( p->aRef[2]==0 ){
202500    p->aRef[2] = 1;
202501    aOut = &p->aMatchinfo[p->nElem+2];
202502    xRet = fts3MIBufferFree;
202503  }else{
202504    aOut = (u32*)sqlite3_malloc64(p->nElem * sizeof(u32));
202505    if( aOut ){
202506      xRet = sqlite3_free;
202507      if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
202508    }
202509  }
202510
202511  *paOut = aOut;
202512  return xRet;
202513}
202514
202515static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
202516  p->bGlobal = 1;
202517  memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
202518}
202519
202520/*
202521** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
202522*/
202523SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
202524  if( p ){
202525    assert( p->aRef[0]==1 );
202526    p->aRef[0] = 0;
202527    if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
202528      sqlite3_free(p);
202529    }
202530  }
202531}
202532
202533/*
202534** End of MatchinfoBuffer code.
202535*************************************************************************/
202536
202537
202538/*
202539** This function is used to help iterate through a position-list. A position
202540** list is a list of unique integers, sorted from smallest to largest. Each
202541** element of the list is represented by an FTS3 varint that takes the value
202542** of the difference between the current element and the previous one plus
202543** two. For example, to store the position-list:
202544**
202545**     4 9 113
202546**
202547** the three varints:
202548**
202549**     6 7 106
202550**
202551** are encoded.
202552**
202553** When this function is called, *pp points to the start of an element of
202554** the list. *piPos contains the value of the previous entry in the list.
202555** After it returns, *piPos contains the value of the next element of the
202556** list and *pp is advanced to the following varint.
202557*/
202558static void fts3GetDeltaPosition(char **pp, i64 *piPos){
202559  int iVal;
202560  *pp += fts3GetVarint32(*pp, &iVal);
202561  *piPos += (iVal-2);
202562}
202563
202564/*
202565** Helper function for sqlite3Fts3ExprIterate() (see below).
202566*/
202567static int fts3ExprIterate2(
202568  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
202569  int *piPhrase,                  /* Pointer to phrase counter */
202570  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
202571  void *pCtx                      /* Second argument to pass to callback */
202572){
202573  int rc;                         /* Return code */
202574  int eType = pExpr->eType;     /* Type of expression node pExpr */
202575
202576  if( eType!=FTSQUERY_PHRASE ){
202577    assert( pExpr->pLeft && pExpr->pRight );
202578    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
202579    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
202580      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
202581    }
202582  }else{
202583    rc = x(pExpr, *piPhrase, pCtx);
202584    (*piPhrase)++;
202585  }
202586  return rc;
202587}
202588
202589/*
202590** Iterate through all phrase nodes in an FTS3 query, except those that
202591** are part of a sub-tree that is the right-hand-side of a NOT operator.
202592** For each phrase node found, the supplied callback function is invoked.
202593**
202594** If the callback function returns anything other than SQLITE_OK,
202595** the iteration is abandoned and the error code returned immediately.
202596** Otherwise, SQLITE_OK is returned after a callback has been made for
202597** all eligible phrase nodes.
202598*/
202599SQLITE_PRIVATE int sqlite3Fts3ExprIterate(
202600  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
202601  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
202602  void *pCtx                      /* Second argument to pass to callback */
202603){
202604  int iPhrase = 0;                /* Variable used as the phrase counter */
202605  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
202606}
202607
202608/*
202609** This is an sqlite3Fts3ExprIterate() callback used while loading the
202610** doclists for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
202611** fts3ExprLoadDoclists().
202612*/
202613static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
202614  int rc = SQLITE_OK;
202615  Fts3Phrase *pPhrase = pExpr->pPhrase;
202616  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
202617
202618  UNUSED_PARAMETER(iPhrase);
202619
202620  p->nPhrase++;
202621  p->nToken += pPhrase->nToken;
202622
202623  return rc;
202624}
202625
202626/*
202627** Load the doclists for each phrase in the query associated with FTS3 cursor
202628** pCsr.
202629**
202630** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
202631** phrases in the expression (all phrases except those directly or
202632** indirectly descended from the right-hand-side of a NOT operator). If
202633** pnToken is not NULL, then it is set to the number of tokens in all
202634** matchable phrases of the expression.
202635*/
202636static int fts3ExprLoadDoclists(
202637  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
202638  int *pnPhrase,                  /* OUT: Number of phrases in query */
202639  int *pnToken                    /* OUT: Number of tokens in query */
202640){
202641  int rc;                         /* Return Code */
202642  LoadDoclistCtx sCtx = {0,0,0};  /* Context for sqlite3Fts3ExprIterate() */
202643  sCtx.pCsr = pCsr;
202644  rc = sqlite3Fts3ExprIterate(pCsr->pExpr,fts3ExprLoadDoclistsCb,(void*)&sCtx);
202645  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
202646  if( pnToken ) *pnToken = sCtx.nToken;
202647  return rc;
202648}
202649
202650static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
202651  (*(int *)ctx)++;
202652  pExpr->iPhrase = iPhrase;
202653  return SQLITE_OK;
202654}
202655static int fts3ExprPhraseCount(Fts3Expr *pExpr){
202656  int nPhrase = 0;
202657  (void)sqlite3Fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
202658  return nPhrase;
202659}
202660
202661/*
202662** Advance the position list iterator specified by the first two
202663** arguments so that it points to the first element with a value greater
202664** than or equal to parameter iNext.
202665*/
202666static void fts3SnippetAdvance(char **ppIter, i64 *piIter, int iNext){
202667  char *pIter = *ppIter;
202668  if( pIter ){
202669    i64 iIter = *piIter;
202670
202671    while( iIter<iNext ){
202672      if( 0==(*pIter & 0xFE) ){
202673        iIter = -1;
202674        pIter = 0;
202675        break;
202676      }
202677      fts3GetDeltaPosition(&pIter, &iIter);
202678    }
202679
202680    *piIter = iIter;
202681    *ppIter = pIter;
202682  }
202683}
202684
202685/*
202686** Advance the snippet iterator to the next candidate snippet.
202687*/
202688static int fts3SnippetNextCandidate(SnippetIter *pIter){
202689  int i;                          /* Loop counter */
202690
202691  if( pIter->iCurrent<0 ){
202692    /* The SnippetIter object has just been initialized. The first snippet
202693    ** candidate always starts at offset 0 (even if this candidate has a
202694    ** score of 0.0).
202695    */
202696    pIter->iCurrent = 0;
202697
202698    /* Advance the 'head' iterator of each phrase to the first offset that
202699    ** is greater than or equal to (iNext+nSnippet).
202700    */
202701    for(i=0; i<pIter->nPhrase; i++){
202702      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
202703      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
202704    }
202705  }else{
202706    int iStart;
202707    int iEnd = 0x7FFFFFFF;
202708
202709    for(i=0; i<pIter->nPhrase; i++){
202710      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
202711      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
202712        iEnd = pPhrase->iHead;
202713      }
202714    }
202715    if( iEnd==0x7FFFFFFF ){
202716      return 1;
202717    }
202718
202719    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
202720    for(i=0; i<pIter->nPhrase; i++){
202721      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
202722      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
202723      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
202724    }
202725  }
202726
202727  return 0;
202728}
202729
202730/*
202731** Retrieve information about the current candidate snippet of snippet
202732** iterator pIter.
202733*/
202734static void fts3SnippetDetails(
202735  SnippetIter *pIter,             /* Snippet iterator */
202736  u64 mCovered,                   /* Bitmask of phrases already covered */
202737  int *piToken,                   /* OUT: First token of proposed snippet */
202738  int *piScore,                   /* OUT: "Score" for this snippet */
202739  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
202740  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
202741){
202742  int iStart = pIter->iCurrent;   /* First token of snippet */
202743  int iScore = 0;                 /* Score of this snippet */
202744  int i;                          /* Loop counter */
202745  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
202746  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
202747
202748  for(i=0; i<pIter->nPhrase; i++){
202749    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
202750    if( pPhrase->pTail ){
202751      char *pCsr = pPhrase->pTail;
202752      i64 iCsr = pPhrase->iTail;
202753
202754      while( iCsr<(iStart+pIter->nSnippet) && iCsr>=iStart ){
202755        int j;
202756        u64 mPhrase = (u64)1 << (i%64);
202757        u64 mPos = (u64)1 << (iCsr - iStart);
202758        assert( iCsr>=iStart && (iCsr - iStart)<=64 );
202759        assert( i>=0 );
202760        if( (mCover|mCovered)&mPhrase ){
202761          iScore++;
202762        }else{
202763          iScore += 1000;
202764        }
202765        mCover |= mPhrase;
202766
202767        for(j=0; j<pPhrase->nToken && j<pIter->nSnippet; j++){
202768          mHighlight |= (mPos>>j);
202769        }
202770
202771        if( 0==(*pCsr & 0x0FE) ) break;
202772        fts3GetDeltaPosition(&pCsr, &iCsr);
202773      }
202774    }
202775  }
202776
202777  /* Set the output variables before returning. */
202778  *piToken = iStart;
202779  *piScore = iScore;
202780  *pmCover = mCover;
202781  *pmHighlight = mHighlight;
202782}
202783
202784/*
202785** This function is an sqlite3Fts3ExprIterate() callback used by
202786** fts3BestSnippet().  Each invocation populates an element of the
202787** SnippetIter.aPhrase[] array.
202788*/
202789static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
202790  SnippetIter *p = (SnippetIter *)ctx;
202791  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
202792  char *pCsr;
202793  int rc;
202794
202795  pPhrase->nToken = pExpr->pPhrase->nToken;
202796  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
202797  assert( rc==SQLITE_OK || pCsr==0 );
202798  if( pCsr ){
202799    i64 iFirst = 0;
202800    pPhrase->pList = pCsr;
202801    fts3GetDeltaPosition(&pCsr, &iFirst);
202802    if( iFirst<0 ){
202803      rc = FTS_CORRUPT_VTAB;
202804    }else{
202805      pPhrase->pHead = pCsr;
202806      pPhrase->pTail = pCsr;
202807      pPhrase->iHead = iFirst;
202808      pPhrase->iTail = iFirst;
202809    }
202810  }else{
202811    assert( rc!=SQLITE_OK || (
202812       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
202813    ));
202814  }
202815
202816  return rc;
202817}
202818
202819/*
202820** Select the fragment of text consisting of nFragment contiguous tokens
202821** from column iCol that represent the "best" snippet. The best snippet
202822** is the snippet with the highest score, where scores are calculated
202823** by adding:
202824**
202825**   (a) +1 point for each occurrence of a matchable phrase in the snippet.
202826**
202827**   (b) +1000 points for the first occurrence of each matchable phrase in
202828**       the snippet for which the corresponding mCovered bit is not set.
202829**
202830** The selected snippet parameters are stored in structure *pFragment before
202831** returning. The score of the selected snippet is stored in *piScore
202832** before returning.
202833*/
202834static int fts3BestSnippet(
202835  int nSnippet,                   /* Desired snippet length */
202836  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
202837  int iCol,                       /* Index of column to create snippet from */
202838  u64 mCovered,                   /* Mask of phrases already covered */
202839  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
202840  SnippetFragment *pFragment,     /* OUT: Best snippet found */
202841  int *piScore                    /* OUT: Score of snippet pFragment */
202842){
202843  int rc;                         /* Return Code */
202844  int nList;                      /* Number of phrases in expression */
202845  SnippetIter sIter;              /* Iterates through snippet candidates */
202846  sqlite3_int64 nByte;            /* Number of bytes of space to allocate */
202847  int iBestScore = -1;            /* Best snippet score found so far */
202848  int i;                          /* Loop counter */
202849
202850  memset(&sIter, 0, sizeof(sIter));
202851
202852  /* Iterate through the phrases in the expression to count them. The same
202853  ** callback makes sure the doclists are loaded for each phrase.
202854  */
202855  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
202856  if( rc!=SQLITE_OK ){
202857    return rc;
202858  }
202859
202860  /* Now that it is known how many phrases there are, allocate and zero
202861  ** the required space using malloc().
202862  */
202863  nByte = sizeof(SnippetPhrase) * nList;
202864  sIter.aPhrase = (SnippetPhrase *)sqlite3Fts3MallocZero(nByte);
202865  if( !sIter.aPhrase ){
202866    return SQLITE_NOMEM;
202867  }
202868
202869  /* Initialize the contents of the SnippetIter object. Then iterate through
202870  ** the set of phrases in the expression to populate the aPhrase[] array.
202871  */
202872  sIter.pCsr = pCsr;
202873  sIter.iCol = iCol;
202874  sIter.nSnippet = nSnippet;
202875  sIter.nPhrase = nList;
202876  sIter.iCurrent = -1;
202877  rc = sqlite3Fts3ExprIterate(
202878      pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter
202879  );
202880  if( rc==SQLITE_OK ){
202881
202882    /* Set the *pmSeen output variable. */
202883    for(i=0; i<nList; i++){
202884      if( sIter.aPhrase[i].pHead ){
202885        *pmSeen |= (u64)1 << (i%64);
202886      }
202887    }
202888
202889    /* Loop through all candidate snippets. Store the best snippet in
202890     ** *pFragment. Store its associated 'score' in iBestScore.
202891     */
202892    pFragment->iCol = iCol;
202893    while( !fts3SnippetNextCandidate(&sIter) ){
202894      int iPos;
202895      int iScore;
202896      u64 mCover;
202897      u64 mHighlite;
202898      fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
202899      assert( iScore>=0 );
202900      if( iScore>iBestScore ){
202901        pFragment->iPos = iPos;
202902        pFragment->hlmask = mHighlite;
202903        pFragment->covered = mCover;
202904        iBestScore = iScore;
202905      }
202906    }
202907
202908    *piScore = iBestScore;
202909  }
202910  sqlite3_free(sIter.aPhrase);
202911  return rc;
202912}
202913
202914
202915/*
202916** Append a string to the string-buffer passed as the first argument.
202917**
202918** If nAppend is negative, then the length of the string zAppend is
202919** determined using strlen().
202920*/
202921static int fts3StringAppend(
202922  StrBuffer *pStr,                /* Buffer to append to */
202923  const char *zAppend,            /* Pointer to data to append to buffer */
202924  int nAppend                     /* Size of zAppend in bytes (or -1) */
202925){
202926  if( nAppend<0 ){
202927    nAppend = (int)strlen(zAppend);
202928  }
202929
202930  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
202931  ** to grow the buffer until so that it is big enough to accomadate the
202932  ** appended data.
202933  */
202934  if( pStr->n+nAppend+1>=pStr->nAlloc ){
202935    sqlite3_int64 nAlloc = pStr->nAlloc+(sqlite3_int64)nAppend+100;
202936    char *zNew = sqlite3_realloc64(pStr->z, nAlloc);
202937    if( !zNew ){
202938      return SQLITE_NOMEM;
202939    }
202940    pStr->z = zNew;
202941    pStr->nAlloc = nAlloc;
202942  }
202943  assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
202944
202945  /* Append the data to the string buffer. */
202946  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
202947  pStr->n += nAppend;
202948  pStr->z[pStr->n] = '\0';
202949
202950  return SQLITE_OK;
202951}
202952
202953/*
202954** The fts3BestSnippet() function often selects snippets that end with a
202955** query term. That is, the final term of the snippet is always a term
202956** that requires highlighting. For example, if 'X' is a highlighted term
202957** and '.' is a non-highlighted term, BestSnippet() may select:
202958**
202959**     ........X.....X
202960**
202961** This function "shifts" the beginning of the snippet forward in the
202962** document so that there are approximately the same number of
202963** non-highlighted terms to the right of the final highlighted term as there
202964** are to the left of the first highlighted term. For example, to this:
202965**
202966**     ....X.....X....
202967**
202968** This is done as part of extracting the snippet text, not when selecting
202969** the snippet. Snippet selection is done based on doclists only, so there
202970** is no way for fts3BestSnippet() to know whether or not the document
202971** actually contains terms that follow the final highlighted term.
202972*/
202973static int fts3SnippetShift(
202974  Fts3Table *pTab,                /* FTS3 table snippet comes from */
202975  int iLangid,                    /* Language id to use in tokenizing */
202976  int nSnippet,                   /* Number of tokens desired for snippet */
202977  const char *zDoc,               /* Document text to extract snippet from */
202978  int nDoc,                       /* Size of buffer zDoc in bytes */
202979  int *piPos,                     /* IN/OUT: First token of snippet */
202980  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
202981){
202982  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
202983
202984  if( hlmask ){
202985    int nLeft;                    /* Tokens to the left of first highlight */
202986    int nRight;                   /* Tokens to the right of last highlight */
202987    int nDesired;                 /* Ideal number of tokens to shift forward */
202988
202989    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
202990    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
202991    assert( (nSnippet-1-nRight)<=63 && (nSnippet-1-nRight)>=0 );
202992    nDesired = (nLeft-nRight)/2;
202993
202994    /* Ideally, the start of the snippet should be pushed forward in the
202995    ** document nDesired tokens. This block checks if there are actually
202996    ** nDesired tokens to the right of the snippet. If so, *piPos and
202997    ** *pHlMask are updated to shift the snippet nDesired tokens to the
202998    ** right. Otherwise, the snippet is shifted by the number of tokens
202999    ** available.
203000    */
203001    if( nDesired>0 ){
203002      int nShift;                 /* Number of tokens to shift snippet by */
203003      int iCurrent = 0;           /* Token counter */
203004      int rc;                     /* Return Code */
203005      sqlite3_tokenizer_module *pMod;
203006      sqlite3_tokenizer_cursor *pC;
203007      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
203008
203009      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
203010      ** or more tokens in zDoc/nDoc.
203011      */
203012      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
203013      if( rc!=SQLITE_OK ){
203014        return rc;
203015      }
203016      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
203017        const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
203018        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
203019      }
203020      pMod->xClose(pC);
203021      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
203022
203023      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
203024      assert( nShift<=nDesired );
203025      if( nShift>0 ){
203026        *piPos += nShift;
203027        *pHlmask = hlmask >> nShift;
203028      }
203029    }
203030  }
203031  return SQLITE_OK;
203032}
203033
203034/*
203035** Extract the snippet text for fragment pFragment from cursor pCsr and
203036** append it to string buffer pOut.
203037*/
203038static int fts3SnippetText(
203039  Fts3Cursor *pCsr,               /* FTS3 Cursor */
203040  SnippetFragment *pFragment,     /* Snippet to extract */
203041  int iFragment,                  /* Fragment number */
203042  int isLast,                     /* True for final fragment in snippet */
203043  int nSnippet,                   /* Number of tokens in extracted snippet */
203044  const char *zOpen,              /* String inserted before highlighted term */
203045  const char *zClose,             /* String inserted after highlighted term */
203046  const char *zEllipsis,          /* String inserted between snippets */
203047  StrBuffer *pOut                 /* Write output here */
203048){
203049  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
203050  int rc;                         /* Return code */
203051  const char *zDoc;               /* Document text to extract snippet from */
203052  int nDoc;                       /* Size of zDoc in bytes */
203053  int iCurrent = 0;               /* Current token number of document */
203054  int iEnd = 0;                   /* Byte offset of end of current token */
203055  int isShiftDone = 0;            /* True after snippet is shifted */
203056  int iPos = pFragment->iPos;     /* First token of snippet */
203057  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
203058  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
203059  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
203060  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
203061
203062  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
203063  if( zDoc==0 ){
203064    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
203065      return SQLITE_NOMEM;
203066    }
203067    return SQLITE_OK;
203068  }
203069  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
203070
203071  /* Open a token cursor on the document. */
203072  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
203073  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
203074  if( rc!=SQLITE_OK ){
203075    return rc;
203076  }
203077
203078  while( rc==SQLITE_OK ){
203079    const char *ZDUMMY;           /* Dummy argument used with tokenizer */
203080    int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
203081    int iBegin = 0;               /* Offset in zDoc of start of token */
203082    int iFin = 0;                 /* Offset in zDoc of end of token */
203083    int isHighlight = 0;          /* True for highlighted terms */
203084
203085    /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
203086    ** in the FTS code the variable that the third argument to xNext points to
203087    ** is initialized to zero before the first (*but not necessarily
203088    ** subsequent*) call to xNext(). This is done for a particular application
203089    ** that needs to know whether or not the tokenizer is being used for
203090    ** snippet generation or for some other purpose.
203091    **
203092    ** Extreme care is required when writing code to depend on this
203093    ** initialization. It is not a documented part of the tokenizer interface.
203094    ** If a tokenizer is used directly by any code outside of FTS, this
203095    ** convention might not be respected.  */
203096    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
203097    if( rc!=SQLITE_OK ){
203098      if( rc==SQLITE_DONE ){
203099        /* Special case - the last token of the snippet is also the last token
203100        ** of the column. Append any punctuation that occurred between the end
203101        ** of the previous token and the end of the document to the output.
203102        ** Then break out of the loop. */
203103        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
203104      }
203105      break;
203106    }
203107    if( iCurrent<iPos ){ continue; }
203108
203109    if( !isShiftDone ){
203110      int n = nDoc - iBegin;
203111      rc = fts3SnippetShift(
203112          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
203113      );
203114      isShiftDone = 1;
203115
203116      /* Now that the shift has been done, check if the initial "..." are
203117      ** required. They are required if (a) this is not the first fragment,
203118      ** or (b) this fragment does not begin at position 0 of its column.
203119      */
203120      if( rc==SQLITE_OK ){
203121        if( iPos>0 || iFragment>0 ){
203122          rc = fts3StringAppend(pOut, zEllipsis, -1);
203123        }else if( iBegin ){
203124          rc = fts3StringAppend(pOut, zDoc, iBegin);
203125        }
203126      }
203127      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
203128    }
203129
203130    if( iCurrent>=(iPos+nSnippet) ){
203131      if( isLast ){
203132        rc = fts3StringAppend(pOut, zEllipsis, -1);
203133      }
203134      break;
203135    }
203136
203137    /* Set isHighlight to true if this term should be highlighted. */
203138    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
203139
203140    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
203141    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
203142    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
203143    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
203144
203145    iEnd = iFin;
203146  }
203147
203148  pMod->xClose(pC);
203149  return rc;
203150}
203151
203152
203153/*
203154** This function is used to count the entries in a column-list (a
203155** delta-encoded list of term offsets within a single column of a single
203156** row). When this function is called, *ppCollist should point to the
203157** beginning of the first varint in the column-list (the varint that
203158** contains the position of the first matching term in the column data).
203159** Before returning, *ppCollist is set to point to the first byte after
203160** the last varint in the column-list (either the 0x00 signifying the end
203161** of the position-list, or the 0x01 that precedes the column number of
203162** the next column in the position-list).
203163**
203164** The number of elements in the column-list is returned.
203165*/
203166static int fts3ColumnlistCount(char **ppCollist){
203167  char *pEnd = *ppCollist;
203168  char c = 0;
203169  int nEntry = 0;
203170
203171  /* A column-list is terminated by either a 0x01 or 0x00. */
203172  while( 0xFE & (*pEnd | c) ){
203173    c = *pEnd++ & 0x80;
203174    if( !c ) nEntry++;
203175  }
203176
203177  *ppCollist = pEnd;
203178  return nEntry;
203179}
203180
203181/*
203182** This function gathers 'y' or 'b' data for a single phrase.
203183*/
203184static int fts3ExprLHits(
203185  Fts3Expr *pExpr,                /* Phrase expression node */
203186  MatchInfo *p                    /* Matchinfo context */
203187){
203188  Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
203189  int iStart;
203190  Fts3Phrase *pPhrase = pExpr->pPhrase;
203191  char *pIter = pPhrase->doclist.pList;
203192  int iCol = 0;
203193
203194  assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
203195  if( p->flag==FTS3_MATCHINFO_LHITS ){
203196    iStart = pExpr->iPhrase * p->nCol;
203197  }else{
203198    iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
203199  }
203200
203201  if( pIter ) while( 1 ){
203202    int nHit = fts3ColumnlistCount(&pIter);
203203    if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
203204      if( p->flag==FTS3_MATCHINFO_LHITS ){
203205        p->aMatchinfo[iStart + iCol] = (u32)nHit;
203206      }else if( nHit ){
203207        p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
203208      }
203209    }
203210    assert( *pIter==0x00 || *pIter==0x01 );
203211    if( *pIter!=0x01 ) break;
203212    pIter++;
203213    pIter += fts3GetVarint32(pIter, &iCol);
203214    if( iCol>=p->nCol ) return FTS_CORRUPT_VTAB;
203215  }
203216  return SQLITE_OK;
203217}
203218
203219/*
203220** Gather the results for matchinfo directives 'y' and 'b'.
203221*/
203222static int fts3ExprLHitGather(
203223  Fts3Expr *pExpr,
203224  MatchInfo *p
203225){
203226  int rc = SQLITE_OK;
203227  assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
203228  if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
203229    if( pExpr->pLeft ){
203230      rc = fts3ExprLHitGather(pExpr->pLeft, p);
203231      if( rc==SQLITE_OK ) rc = fts3ExprLHitGather(pExpr->pRight, p);
203232    }else{
203233      rc = fts3ExprLHits(pExpr, p);
203234    }
203235  }
203236  return rc;
203237}
203238
203239/*
203240** sqlite3Fts3ExprIterate() callback used to collect the "global" matchinfo
203241** stats for a single query.
203242**
203243** sqlite3Fts3ExprIterate() callback to load the 'global' elements of a
203244** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
203245** of the matchinfo array that are constant for all rows returned by the
203246** current query.
203247**
203248** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
203249** function populates Matchinfo.aMatchinfo[] as follows:
203250**
203251**   for(iCol=0; iCol<nCol; iCol++){
203252**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
203253**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
203254**   }
203255**
203256** where X is the number of matches for phrase iPhrase is column iCol of all
203257** rows of the table. Y is the number of rows for which column iCol contains
203258** at least one instance of phrase iPhrase.
203259**
203260** If the phrase pExpr consists entirely of deferred tokens, then all X and
203261** Y values are set to nDoc, where nDoc is the number of documents in the
203262** file system. This is done because the full-text index doclist is required
203263** to calculate these values properly, and the full-text index doclist is
203264** not available for deferred tokens.
203265*/
203266static int fts3ExprGlobalHitsCb(
203267  Fts3Expr *pExpr,                /* Phrase expression node */
203268  int iPhrase,                    /* Phrase number (numbered from zero) */
203269  void *pCtx                      /* Pointer to MatchInfo structure */
203270){
203271  MatchInfo *p = (MatchInfo *)pCtx;
203272  return sqlite3Fts3EvalPhraseStats(
203273      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
203274  );
203275}
203276
203277/*
203278** sqlite3Fts3ExprIterate() callback used to collect the "local" part of the
203279** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
203280** array that are different for each row returned by the query.
203281*/
203282static int fts3ExprLocalHitsCb(
203283  Fts3Expr *pExpr,                /* Phrase expression node */
203284  int iPhrase,                    /* Phrase number */
203285  void *pCtx                      /* Pointer to MatchInfo structure */
203286){
203287  int rc = SQLITE_OK;
203288  MatchInfo *p = (MatchInfo *)pCtx;
203289  int iStart = iPhrase * p->nCol * 3;
203290  int i;
203291
203292  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
203293    char *pCsr;
203294    rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
203295    if( pCsr ){
203296      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
203297    }else{
203298      p->aMatchinfo[iStart+i*3] = 0;
203299    }
203300  }
203301
203302  return rc;
203303}
203304
203305static int fts3MatchinfoCheck(
203306  Fts3Table *pTab,
203307  char cArg,
203308  char **pzErr
203309){
203310  if( (cArg==FTS3_MATCHINFO_NPHRASE)
203311   || (cArg==FTS3_MATCHINFO_NCOL)
203312   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
203313   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
203314   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
203315   || (cArg==FTS3_MATCHINFO_LCS)
203316   || (cArg==FTS3_MATCHINFO_HITS)
203317   || (cArg==FTS3_MATCHINFO_LHITS)
203318   || (cArg==FTS3_MATCHINFO_LHITS_BM)
203319  ){
203320    return SQLITE_OK;
203321  }
203322  sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
203323  return SQLITE_ERROR;
203324}
203325
203326static size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
203327  size_t nVal;                      /* Number of integers output by cArg */
203328
203329  switch( cArg ){
203330    case FTS3_MATCHINFO_NDOC:
203331    case FTS3_MATCHINFO_NPHRASE:
203332    case FTS3_MATCHINFO_NCOL:
203333      nVal = 1;
203334      break;
203335
203336    case FTS3_MATCHINFO_AVGLENGTH:
203337    case FTS3_MATCHINFO_LENGTH:
203338    case FTS3_MATCHINFO_LCS:
203339      nVal = pInfo->nCol;
203340      break;
203341
203342    case FTS3_MATCHINFO_LHITS:
203343      nVal = pInfo->nCol * pInfo->nPhrase;
203344      break;
203345
203346    case FTS3_MATCHINFO_LHITS_BM:
203347      nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
203348      break;
203349
203350    default:
203351      assert( cArg==FTS3_MATCHINFO_HITS );
203352      nVal = pInfo->nCol * pInfo->nPhrase * 3;
203353      break;
203354  }
203355
203356  return nVal;
203357}
203358
203359static int fts3MatchinfoSelectDoctotal(
203360  Fts3Table *pTab,
203361  sqlite3_stmt **ppStmt,
203362  sqlite3_int64 *pnDoc,
203363  const char **paLen,
203364  const char **ppEnd
203365){
203366  sqlite3_stmt *pStmt;
203367  const char *a;
203368  const char *pEnd;
203369  sqlite3_int64 nDoc;
203370  int n;
203371
203372
203373  if( !*ppStmt ){
203374    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
203375    if( rc!=SQLITE_OK ) return rc;
203376  }
203377  pStmt = *ppStmt;
203378  assert( sqlite3_data_count(pStmt)==1 );
203379
203380  n = sqlite3_column_bytes(pStmt, 0);
203381  a = sqlite3_column_blob(pStmt, 0);
203382  if( a==0 ){
203383    return FTS_CORRUPT_VTAB;
203384  }
203385  pEnd = a + n;
203386  a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc);
203387  if( nDoc<=0 || a>pEnd ){
203388    return FTS_CORRUPT_VTAB;
203389  }
203390  *pnDoc = nDoc;
203391
203392  if( paLen ) *paLen = a;
203393  if( ppEnd ) *ppEnd = pEnd;
203394  return SQLITE_OK;
203395}
203396
203397/*
203398** An instance of the following structure is used to store state while
203399** iterating through a multi-column position-list corresponding to the
203400** hits for a single phrase on a single row in order to calculate the
203401** values for a matchinfo() FTS3_MATCHINFO_LCS request.
203402*/
203403typedef struct LcsIterator LcsIterator;
203404struct LcsIterator {
203405  Fts3Expr *pExpr;                /* Pointer to phrase expression */
203406  int iPosOffset;                 /* Tokens count up to end of this phrase */
203407  char *pRead;                    /* Cursor used to iterate through aDoclist */
203408  int iPos;                       /* Current position */
203409};
203410
203411/*
203412** If LcsIterator.iCol is set to the following value, the iterator has
203413** finished iterating through all offsets for all columns.
203414*/
203415#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
203416
203417static int fts3MatchinfoLcsCb(
203418  Fts3Expr *pExpr,                /* Phrase expression node */
203419  int iPhrase,                    /* Phrase number (numbered from zero) */
203420  void *pCtx                      /* Pointer to MatchInfo structure */
203421){
203422  LcsIterator *aIter = (LcsIterator *)pCtx;
203423  aIter[iPhrase].pExpr = pExpr;
203424  return SQLITE_OK;
203425}
203426
203427/*
203428** Advance the iterator passed as an argument to the next position. Return
203429** 1 if the iterator is at EOF or if it now points to the start of the
203430** position list for the next column.
203431*/
203432static int fts3LcsIteratorAdvance(LcsIterator *pIter){
203433  char *pRead;
203434  sqlite3_int64 iRead;
203435  int rc = 0;
203436
203437  if( NEVER(pIter==0) ) return 1;
203438  pRead = pIter->pRead;
203439  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
203440  if( iRead==0 || iRead==1 ){
203441    pRead = 0;
203442    rc = 1;
203443  }else{
203444    pIter->iPos += (int)(iRead-2);
203445  }
203446
203447  pIter->pRead = pRead;
203448  return rc;
203449}
203450
203451/*
203452** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
203453**
203454** If the call is successful, the longest-common-substring lengths for each
203455** column are written into the first nCol elements of the pInfo->aMatchinfo[]
203456** array before returning. SQLITE_OK is returned in this case.
203457**
203458** Otherwise, if an error occurs, an SQLite error code is returned and the
203459** data written to the first nCol elements of pInfo->aMatchinfo[] is
203460** undefined.
203461*/
203462static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
203463  LcsIterator *aIter;
203464  int i;
203465  int iCol;
203466  int nToken = 0;
203467  int rc = SQLITE_OK;
203468
203469  /* Allocate and populate the array of LcsIterator objects. The array
203470  ** contains one element for each matchable phrase in the query.
203471  **/
203472  aIter = sqlite3Fts3MallocZero(sizeof(LcsIterator) * pCsr->nPhrase);
203473  if( !aIter ) return SQLITE_NOMEM;
203474  (void)sqlite3Fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
203475
203476  for(i=0; i<pInfo->nPhrase; i++){
203477    LcsIterator *pIter = &aIter[i];
203478    nToken -= pIter->pExpr->pPhrase->nToken;
203479    pIter->iPosOffset = nToken;
203480  }
203481
203482  for(iCol=0; iCol<pInfo->nCol; iCol++){
203483    int nLcs = 0;                 /* LCS value for this column */
203484    int nLive = 0;                /* Number of iterators in aIter not at EOF */
203485
203486    for(i=0; i<pInfo->nPhrase; i++){
203487      LcsIterator *pIt = &aIter[i];
203488      rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
203489      if( rc!=SQLITE_OK ) goto matchinfo_lcs_out;
203490      if( pIt->pRead ){
203491        pIt->iPos = pIt->iPosOffset;
203492        fts3LcsIteratorAdvance(pIt);
203493        if( pIt->pRead==0 ){
203494          rc = FTS_CORRUPT_VTAB;
203495          goto matchinfo_lcs_out;
203496        }
203497        nLive++;
203498      }
203499    }
203500
203501    while( nLive>0 ){
203502      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
203503      int nThisLcs = 0;           /* LCS for the current iterator positions */
203504
203505      for(i=0; i<pInfo->nPhrase; i++){
203506        LcsIterator *pIter = &aIter[i];
203507        if( pIter->pRead==0 ){
203508          /* This iterator is already at EOF for this column. */
203509          nThisLcs = 0;
203510        }else{
203511          if( pAdv==0 || pIter->iPos<pAdv->iPos ){
203512            pAdv = pIter;
203513          }
203514          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
203515            nThisLcs++;
203516          }else{
203517            nThisLcs = 1;
203518          }
203519          if( nThisLcs>nLcs ) nLcs = nThisLcs;
203520        }
203521      }
203522      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
203523    }
203524
203525    pInfo->aMatchinfo[iCol] = nLcs;
203526  }
203527
203528 matchinfo_lcs_out:
203529  sqlite3_free(aIter);
203530  return rc;
203531}
203532
203533/*
203534** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
203535** be returned by the matchinfo() function. Argument zArg contains the
203536** format string passed as the second argument to matchinfo (or the
203537** default value "pcx" if no second argument was specified). The format
203538** string has already been validated and the pInfo->aMatchinfo[] array
203539** is guaranteed to be large enough for the output.
203540**
203541** If bGlobal is true, then populate all fields of the matchinfo() output.
203542** If it is false, then assume that those fields that do not change between
203543** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
203544** have already been populated.
203545**
203546** Return SQLITE_OK if successful, or an SQLite error code if an error
203547** occurs. If a value other than SQLITE_OK is returned, the state the
203548** pInfo->aMatchinfo[] buffer is left in is undefined.
203549*/
203550static int fts3MatchinfoValues(
203551  Fts3Cursor *pCsr,               /* FTS3 cursor object */
203552  int bGlobal,                    /* True to grab the global stats */
203553  MatchInfo *pInfo,               /* Matchinfo context object */
203554  const char *zArg                /* Matchinfo format string */
203555){
203556  int rc = SQLITE_OK;
203557  int i;
203558  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
203559  sqlite3_stmt *pSelect = 0;
203560
203561  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
203562    pInfo->flag = zArg[i];
203563    switch( zArg[i] ){
203564      case FTS3_MATCHINFO_NPHRASE:
203565        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
203566        break;
203567
203568      case FTS3_MATCHINFO_NCOL:
203569        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
203570        break;
203571
203572      case FTS3_MATCHINFO_NDOC:
203573        if( bGlobal ){
203574          sqlite3_int64 nDoc = 0;
203575          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0, 0);
203576          pInfo->aMatchinfo[0] = (u32)nDoc;
203577        }
203578        break;
203579
203580      case FTS3_MATCHINFO_AVGLENGTH:
203581        if( bGlobal ){
203582          sqlite3_int64 nDoc;     /* Number of rows in table */
203583          const char *a;          /* Aggregate column length array */
203584          const char *pEnd;       /* First byte past end of length array */
203585
203586          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a, &pEnd);
203587          if( rc==SQLITE_OK ){
203588            int iCol;
203589            for(iCol=0; iCol<pInfo->nCol; iCol++){
203590              u32 iVal;
203591              sqlite3_int64 nToken;
203592              a += sqlite3Fts3GetVarint(a, &nToken);
203593              if( a>pEnd ){
203594                rc = SQLITE_CORRUPT_VTAB;
203595                break;
203596              }
203597              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
203598              pInfo->aMatchinfo[iCol] = iVal;
203599            }
203600          }
203601        }
203602        break;
203603
203604      case FTS3_MATCHINFO_LENGTH: {
203605        sqlite3_stmt *pSelectDocsize = 0;
203606        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
203607        if( rc==SQLITE_OK ){
203608          int iCol;
203609          const char *a = sqlite3_column_blob(pSelectDocsize, 0);
203610          const char *pEnd = a + sqlite3_column_bytes(pSelectDocsize, 0);
203611          for(iCol=0; iCol<pInfo->nCol; iCol++){
203612            sqlite3_int64 nToken;
203613            a += sqlite3Fts3GetVarintBounded(a, pEnd, &nToken);
203614            if( a>pEnd ){
203615              rc = SQLITE_CORRUPT_VTAB;
203616              break;
203617            }
203618            pInfo->aMatchinfo[iCol] = (u32)nToken;
203619          }
203620        }
203621        sqlite3_reset(pSelectDocsize);
203622        break;
203623      }
203624
203625      case FTS3_MATCHINFO_LCS:
203626        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
203627        if( rc==SQLITE_OK ){
203628          rc = fts3MatchinfoLcs(pCsr, pInfo);
203629        }
203630        break;
203631
203632      case FTS3_MATCHINFO_LHITS_BM:
203633      case FTS3_MATCHINFO_LHITS: {
203634        size_t nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
203635        memset(pInfo->aMatchinfo, 0, nZero);
203636        rc = fts3ExprLHitGather(pCsr->pExpr, pInfo);
203637        break;
203638      }
203639
203640      default: {
203641        Fts3Expr *pExpr;
203642        assert( zArg[i]==FTS3_MATCHINFO_HITS );
203643        pExpr = pCsr->pExpr;
203644        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
203645        if( rc!=SQLITE_OK ) break;
203646        if( bGlobal ){
203647          if( pCsr->pDeferred ){
203648            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc,0,0);
203649            if( rc!=SQLITE_OK ) break;
203650          }
203651          rc = sqlite3Fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
203652          sqlite3Fts3EvalTestDeferred(pCsr, &rc);
203653          if( rc!=SQLITE_OK ) break;
203654        }
203655        (void)sqlite3Fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
203656        break;
203657      }
203658    }
203659
203660    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
203661  }
203662
203663  sqlite3_reset(pSelect);
203664  return rc;
203665}
203666
203667
203668/*
203669** Populate pCsr->aMatchinfo[] with data for the current row. The
203670** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
203671*/
203672static void fts3GetMatchinfo(
203673  sqlite3_context *pCtx,        /* Return results here */
203674  Fts3Cursor *pCsr,               /* FTS3 Cursor object */
203675  const char *zArg                /* Second argument to matchinfo() function */
203676){
203677  MatchInfo sInfo;
203678  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
203679  int rc = SQLITE_OK;
203680  int bGlobal = 0;                /* Collect 'global' stats as well as local */
203681
203682  u32 *aOut = 0;
203683  void (*xDestroyOut)(void*) = 0;
203684
203685  memset(&sInfo, 0, sizeof(MatchInfo));
203686  sInfo.pCursor = pCsr;
203687  sInfo.nCol = pTab->nColumn;
203688
203689  /* If there is cached matchinfo() data, but the format string for the
203690  ** cache does not match the format string for this request, discard
203691  ** the cached data. */
203692  if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
203693    sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
203694    pCsr->pMIBuffer = 0;
203695  }
203696
203697  /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
203698  ** matchinfo function has been called for this query. In this case
203699  ** allocate the array used to accumulate the matchinfo data and
203700  ** initialize those elements that are constant for every row.
203701  */
203702  if( pCsr->pMIBuffer==0 ){
203703    size_t nMatchinfo = 0;        /* Number of u32 elements in match-info */
203704    int i;                        /* Used to iterate through zArg */
203705
203706    /* Determine the number of phrases in the query */
203707    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
203708    sInfo.nPhrase = pCsr->nPhrase;
203709
203710    /* Determine the number of integers in the buffer returned by this call. */
203711    for(i=0; zArg[i]; i++){
203712      char *zErr = 0;
203713      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
203714        sqlite3_result_error(pCtx, zErr, -1);
203715        sqlite3_free(zErr);
203716        return;
203717      }
203718      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
203719    }
203720
203721    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
203722    pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
203723    if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
203724
203725    pCsr->isMatchinfoNeeded = 1;
203726    bGlobal = 1;
203727  }
203728
203729  if( rc==SQLITE_OK ){
203730    xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
203731    if( xDestroyOut==0 ){
203732      rc = SQLITE_NOMEM;
203733    }
203734  }
203735
203736  if( rc==SQLITE_OK ){
203737    sInfo.aMatchinfo = aOut;
203738    sInfo.nPhrase = pCsr->nPhrase;
203739    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
203740    if( bGlobal ){
203741      fts3MIBufferSetGlobal(pCsr->pMIBuffer);
203742    }
203743  }
203744
203745  if( rc!=SQLITE_OK ){
203746    sqlite3_result_error_code(pCtx, rc);
203747    if( xDestroyOut ) xDestroyOut(aOut);
203748  }else{
203749    int n = pCsr->pMIBuffer->nElem * sizeof(u32);
203750    sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
203751  }
203752}
203753
203754/*
203755** Implementation of snippet() function.
203756*/
203757SQLITE_PRIVATE void sqlite3Fts3Snippet(
203758  sqlite3_context *pCtx,          /* SQLite function call context */
203759  Fts3Cursor *pCsr,               /* Cursor object */
203760  const char *zStart,             /* Snippet start text - "<b>" */
203761  const char *zEnd,               /* Snippet end text - "</b>" */
203762  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
203763  int iCol,                       /* Extract snippet from this column */
203764  int nToken                      /* Approximate number of tokens in snippet */
203765){
203766  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
203767  int rc = SQLITE_OK;
203768  int i;
203769  StrBuffer res = {0, 0, 0};
203770
203771  /* The returned text includes up to four fragments of text extracted from
203772  ** the data in the current row. The first iteration of the for(...) loop
203773  ** below attempts to locate a single fragment of text nToken tokens in
203774  ** size that contains at least one instance of all phrases in the query
203775  ** expression that appear in the current row. If such a fragment of text
203776  ** cannot be found, the second iteration of the loop attempts to locate
203777  ** a pair of fragments, and so on.
203778  */
203779  int nSnippet = 0;               /* Number of fragments in this snippet */
203780  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
203781  int nFToken = -1;               /* Number of tokens in each fragment */
203782
203783  if( !pCsr->pExpr ){
203784    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
203785    return;
203786  }
203787
203788  /* Limit the snippet length to 64 tokens. */
203789  if( nToken<-64 ) nToken = -64;
203790  if( nToken>+64 ) nToken = +64;
203791
203792  for(nSnippet=1; 1; nSnippet++){
203793
203794    int iSnip;                    /* Loop counter 0..nSnippet-1 */
203795    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
203796    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
203797
203798    if( nToken>=0 ){
203799      nFToken = (nToken+nSnippet-1) / nSnippet;
203800    }else{
203801      nFToken = -1 * nToken;
203802    }
203803
203804    for(iSnip=0; iSnip<nSnippet; iSnip++){
203805      int iBestScore = -1;        /* Best score of columns checked so far */
203806      int iRead;                  /* Used to iterate through columns */
203807      SnippetFragment *pFragment = &aSnippet[iSnip];
203808
203809      memset(pFragment, 0, sizeof(*pFragment));
203810
203811      /* Loop through all columns of the table being considered for snippets.
203812      ** If the iCol argument to this function was negative, this means all
203813      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
203814      */
203815      for(iRead=0; iRead<pTab->nColumn; iRead++){
203816        SnippetFragment sF = {0, 0, 0, 0};
203817        int iS = 0;
203818        if( iCol>=0 && iRead!=iCol ) continue;
203819
203820        /* Find the best snippet of nFToken tokens in column iRead. */
203821        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
203822        if( rc!=SQLITE_OK ){
203823          goto snippet_out;
203824        }
203825        if( iS>iBestScore ){
203826          *pFragment = sF;
203827          iBestScore = iS;
203828        }
203829      }
203830
203831      mCovered |= pFragment->covered;
203832    }
203833
203834    /* If all query phrases seen by fts3BestSnippet() are present in at least
203835    ** one of the nSnippet snippet fragments, break out of the loop.
203836    */
203837    assert( (mCovered&mSeen)==mCovered );
203838    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
203839  }
203840
203841  assert( nFToken>0 );
203842
203843  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
203844    rc = fts3SnippetText(pCsr, &aSnippet[i],
203845        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
203846    );
203847  }
203848
203849 snippet_out:
203850  sqlite3Fts3SegmentsClose(pTab);
203851  if( rc!=SQLITE_OK ){
203852    sqlite3_result_error_code(pCtx, rc);
203853    sqlite3_free(res.z);
203854  }else{
203855    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
203856  }
203857}
203858
203859
203860typedef struct TermOffset TermOffset;
203861typedef struct TermOffsetCtx TermOffsetCtx;
203862
203863struct TermOffset {
203864  char *pList;                    /* Position-list */
203865  i64 iPos;                       /* Position just read from pList */
203866  i64 iOff;                       /* Offset of this term from read positions */
203867};
203868
203869struct TermOffsetCtx {
203870  Fts3Cursor *pCsr;
203871  int iCol;                       /* Column of table to populate aTerm for */
203872  int iTerm;
203873  sqlite3_int64 iDocid;
203874  TermOffset *aTerm;
203875};
203876
203877/*
203878** This function is an sqlite3Fts3ExprIterate() callback used by sqlite3Fts3Offsets().
203879*/
203880static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
203881  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
203882  int nTerm;                      /* Number of tokens in phrase */
203883  int iTerm;                      /* For looping through nTerm phrase terms */
203884  char *pList;                    /* Pointer to position list for phrase */
203885  i64 iPos = 0;                   /* First position in position-list */
203886  int rc;
203887
203888  UNUSED_PARAMETER(iPhrase);
203889  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
203890  nTerm = pExpr->pPhrase->nToken;
203891  if( pList ){
203892    fts3GetDeltaPosition(&pList, &iPos);
203893    assert_fts3_nc( iPos>=0 );
203894  }
203895
203896  for(iTerm=0; iTerm<nTerm; iTerm++){
203897    TermOffset *pT = &p->aTerm[p->iTerm++];
203898    pT->iOff = nTerm-iTerm-1;
203899    pT->pList = pList;
203900    pT->iPos = iPos;
203901  }
203902
203903  return rc;
203904}
203905
203906/*
203907** Implementation of offsets() function.
203908*/
203909SQLITE_PRIVATE void sqlite3Fts3Offsets(
203910  sqlite3_context *pCtx,          /* SQLite function call context */
203911  Fts3Cursor *pCsr                /* Cursor object */
203912){
203913  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
203914  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
203915  int rc;                         /* Return Code */
203916  int nToken;                     /* Number of tokens in query */
203917  int iCol;                       /* Column currently being processed */
203918  StrBuffer res = {0, 0, 0};      /* Result string */
203919  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
203920
203921  if( !pCsr->pExpr ){
203922    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
203923    return;
203924  }
203925
203926  memset(&sCtx, 0, sizeof(sCtx));
203927  assert( pCsr->isRequireSeek==0 );
203928
203929  /* Count the number of terms in the query */
203930  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
203931  if( rc!=SQLITE_OK ) goto offsets_out;
203932
203933  /* Allocate the array of TermOffset iterators. */
203934  sCtx.aTerm = (TermOffset *)sqlite3Fts3MallocZero(sizeof(TermOffset)*nToken);
203935  if( 0==sCtx.aTerm ){
203936    rc = SQLITE_NOMEM;
203937    goto offsets_out;
203938  }
203939  sCtx.iDocid = pCsr->iPrevId;
203940  sCtx.pCsr = pCsr;
203941
203942  /* Loop through the table columns, appending offset information to
203943  ** string-buffer res for each column.
203944  */
203945  for(iCol=0; iCol<pTab->nColumn; iCol++){
203946    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
203947    const char *ZDUMMY;           /* Dummy argument used with xNext() */
203948    int NDUMMY = 0;               /* Dummy argument used with xNext() */
203949    int iStart = 0;
203950    int iEnd = 0;
203951    int iCurrent = 0;
203952    const char *zDoc;
203953    int nDoc;
203954
203955    /* Initialize the contents of sCtx.aTerm[] for column iCol. This
203956    ** operation may fail if the database contains corrupt records.
203957    */
203958    sCtx.iCol = iCol;
203959    sCtx.iTerm = 0;
203960    rc = sqlite3Fts3ExprIterate(
203961        pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx
203962    );
203963    if( rc!=SQLITE_OK ) goto offsets_out;
203964
203965    /* Retreive the text stored in column iCol. If an SQL NULL is stored
203966    ** in column iCol, jump immediately to the next iteration of the loop.
203967    ** If an OOM occurs while retrieving the data (this can happen if SQLite
203968    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
203969    ** to the caller.
203970    */
203971    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
203972    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
203973    if( zDoc==0 ){
203974      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
203975        continue;
203976      }
203977      rc = SQLITE_NOMEM;
203978      goto offsets_out;
203979    }
203980
203981    /* Initialize a tokenizer iterator to iterate through column iCol. */
203982    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
203983        zDoc, nDoc, &pC
203984    );
203985    if( rc!=SQLITE_OK ) goto offsets_out;
203986
203987    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
203988    while( rc==SQLITE_OK ){
203989      int i;                      /* Used to loop through terms */
203990      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
203991      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
203992
203993      for(i=0; i<nToken; i++){
203994        TermOffset *pT = &sCtx.aTerm[i];
203995        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
203996          iMinPos = pT->iPos-pT->iOff;
203997          pTerm = pT;
203998        }
203999      }
204000
204001      if( !pTerm ){
204002        /* All offsets for this column have been gathered. */
204003        rc = SQLITE_DONE;
204004      }else{
204005        assert_fts3_nc( iCurrent<=iMinPos );
204006        if( 0==(0xFE&*pTerm->pList) ){
204007          pTerm->pList = 0;
204008        }else{
204009          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
204010        }
204011        while( rc==SQLITE_OK && iCurrent<iMinPos ){
204012          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
204013        }
204014        if( rc==SQLITE_OK ){
204015          char aBuffer[64];
204016          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
204017              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
204018          );
204019          rc = fts3StringAppend(&res, aBuffer, -1);
204020        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
204021          rc = FTS_CORRUPT_VTAB;
204022        }
204023      }
204024    }
204025    if( rc==SQLITE_DONE ){
204026      rc = SQLITE_OK;
204027    }
204028
204029    pMod->xClose(pC);
204030    if( rc!=SQLITE_OK ) goto offsets_out;
204031  }
204032
204033 offsets_out:
204034  sqlite3_free(sCtx.aTerm);
204035  assert( rc!=SQLITE_DONE );
204036  sqlite3Fts3SegmentsClose(pTab);
204037  if( rc!=SQLITE_OK ){
204038    sqlite3_result_error_code(pCtx,  rc);
204039    sqlite3_free(res.z);
204040  }else{
204041    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
204042  }
204043  return;
204044}
204045
204046/*
204047** Implementation of matchinfo() function.
204048*/
204049SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
204050  sqlite3_context *pContext,      /* Function call context */
204051  Fts3Cursor *pCsr,               /* FTS3 table cursor */
204052  const char *zArg                /* Second arg to matchinfo() function */
204053){
204054  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
204055  const char *zFormat;
204056
204057  if( zArg ){
204058    zFormat = zArg;
204059  }else{
204060    zFormat = FTS3_MATCHINFO_DEFAULT;
204061  }
204062
204063  if( !pCsr->pExpr ){
204064    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
204065    return;
204066  }else{
204067    /* Retrieve matchinfo() data. */
204068    fts3GetMatchinfo(pContext, pCsr, zFormat);
204069    sqlite3Fts3SegmentsClose(pTab);
204070  }
204071}
204072
204073#endif
204074
204075/************** End of fts3_snippet.c ****************************************/
204076/************** Begin file fts3_unicode.c ************************************/
204077/*
204078** 2012 May 24
204079**
204080** The author disclaims copyright to this source code.  In place of
204081** a legal notice, here is a blessing:
204082**
204083**    May you do good and not evil.
204084**    May you find forgiveness for yourself and forgive others.
204085**    May you share freely, never taking more than you give.
204086**
204087******************************************************************************
204088**
204089** Implementation of the "unicode" full-text-search tokenizer.
204090*/
204091
204092#ifndef SQLITE_DISABLE_FTS3_UNICODE
204093
204094/* #include "fts3Int.h" */
204095#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
204096
204097/* #include <assert.h> */
204098/* #include <stdlib.h> */
204099/* #include <stdio.h> */
204100/* #include <string.h> */
204101
204102/* #include "fts3_tokenizer.h" */
204103
204104/*
204105** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
204106** from the sqlite3 source file utf.c. If this file is compiled as part
204107** of the amalgamation, they are not required.
204108*/
204109#ifndef SQLITE_AMALGAMATION
204110
204111static const unsigned char sqlite3Utf8Trans1[] = {
204112  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
204113  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
204114  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
204115  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
204116  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
204117  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
204118  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
204119  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
204120};
204121
204122#define READ_UTF8(zIn, zTerm, c)                           \
204123  c = *(zIn++);                                            \
204124  if( c>=0xc0 ){                                           \
204125    c = sqlite3Utf8Trans1[c-0xc0];                         \
204126    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
204127      c = (c<<6) + (0x3f & *(zIn++));                      \
204128    }                                                      \
204129    if( c<0x80                                             \
204130        || (c&0xFFFFF800)==0xD800                          \
204131        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
204132  }
204133
204134#define WRITE_UTF8(zOut, c) {                          \
204135  if( c<0x00080 ){                                     \
204136    *zOut++ = (u8)(c&0xFF);                            \
204137  }                                                    \
204138  else if( c<0x00800 ){                                \
204139    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
204140    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
204141  }                                                    \
204142  else if( c<0x10000 ){                                \
204143    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
204144    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
204145    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
204146  }else{                                               \
204147    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
204148    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
204149    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
204150    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
204151  }                                                    \
204152}
204153
204154#endif /* ifndef SQLITE_AMALGAMATION */
204155
204156typedef struct unicode_tokenizer unicode_tokenizer;
204157typedef struct unicode_cursor unicode_cursor;
204158
204159struct unicode_tokenizer {
204160  sqlite3_tokenizer base;
204161  int eRemoveDiacritic;
204162  int nException;
204163  int *aiException;
204164};
204165
204166struct unicode_cursor {
204167  sqlite3_tokenizer_cursor base;
204168  const unsigned char *aInput;    /* Input text being tokenized */
204169  int nInput;                     /* Size of aInput[] in bytes */
204170  int iOff;                       /* Current offset within aInput[] */
204171  int iToken;                     /* Index of next token to be returned */
204172  char *zToken;                   /* storage for current token */
204173  int nAlloc;                     /* space allocated at zToken */
204174};
204175
204176
204177/*
204178** Destroy a tokenizer allocated by unicodeCreate().
204179*/
204180static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
204181  if( pTokenizer ){
204182    unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
204183    sqlite3_free(p->aiException);
204184    sqlite3_free(p);
204185  }
204186  return SQLITE_OK;
204187}
204188
204189/*
204190** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
204191** statement has specified that the tokenizer for this table shall consider
204192** all characters in string zIn/nIn to be separators (if bAlnum==0) or
204193** token characters (if bAlnum==1).
204194**
204195** For each codepoint in the zIn/nIn string, this function checks if the
204196** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
204197** If so, no action is taken. Otherwise, the codepoint is added to the
204198** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
204199** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
204200** codepoints in the aiException[] array.
204201**
204202** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
204203** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
204204** It is not possible to change the behavior of the tokenizer with respect
204205** to these codepoints.
204206*/
204207static int unicodeAddExceptions(
204208  unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
204209  int bAlnum,                     /* Replace Isalnum() return value with this */
204210  const char *zIn,                /* Array of characters to make exceptions */
204211  int nIn                         /* Length of z in bytes */
204212){
204213  const unsigned char *z = (const unsigned char *)zIn;
204214  const unsigned char *zTerm = &z[nIn];
204215  unsigned int iCode;
204216  int nEntry = 0;
204217
204218  assert( bAlnum==0 || bAlnum==1 );
204219
204220  while( z<zTerm ){
204221    READ_UTF8(z, zTerm, iCode);
204222    assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
204223    if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
204224     && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
204225    ){
204226      nEntry++;
204227    }
204228  }
204229
204230  if( nEntry ){
204231    int *aNew;                    /* New aiException[] array */
204232    int nNew;                     /* Number of valid entries in array aNew[] */
204233
204234    aNew = sqlite3_realloc64(p->aiException,(p->nException+nEntry)*sizeof(int));
204235    if( aNew==0 ) return SQLITE_NOMEM;
204236    nNew = p->nException;
204237
204238    z = (const unsigned char *)zIn;
204239    while( z<zTerm ){
204240      READ_UTF8(z, zTerm, iCode);
204241      if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
204242       && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
204243      ){
204244        int i, j;
204245        for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
204246        for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
204247        aNew[i] = (int)iCode;
204248        nNew++;
204249      }
204250    }
204251    p->aiException = aNew;
204252    p->nException = nNew;
204253  }
204254
204255  return SQLITE_OK;
204256}
204257
204258/*
204259** Return true if the p->aiException[] array contains the value iCode.
204260*/
204261static int unicodeIsException(unicode_tokenizer *p, int iCode){
204262  if( p->nException>0 ){
204263    int *a = p->aiException;
204264    int iLo = 0;
204265    int iHi = p->nException-1;
204266
204267    while( iHi>=iLo ){
204268      int iTest = (iHi + iLo) / 2;
204269      if( iCode==a[iTest] ){
204270        return 1;
204271      }else if( iCode>a[iTest] ){
204272        iLo = iTest+1;
204273      }else{
204274        iHi = iTest-1;
204275      }
204276    }
204277  }
204278
204279  return 0;
204280}
204281
204282/*
204283** Return true if, for the purposes of tokenization, codepoint iCode is
204284** considered a token character (not a separator).
204285*/
204286static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
204287  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
204288  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
204289}
204290
204291/*
204292** Create a new tokenizer instance.
204293*/
204294static int unicodeCreate(
204295  int nArg,                       /* Size of array argv[] */
204296  const char * const *azArg,      /* Tokenizer creation arguments */
204297  sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
204298){
204299  unicode_tokenizer *pNew;        /* New tokenizer object */
204300  int i;
204301  int rc = SQLITE_OK;
204302
204303  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
204304  if( pNew==NULL ) return SQLITE_NOMEM;
204305  memset(pNew, 0, sizeof(unicode_tokenizer));
204306  pNew->eRemoveDiacritic = 1;
204307
204308  for(i=0; rc==SQLITE_OK && i<nArg; i++){
204309    const char *z = azArg[i];
204310    int n = (int)strlen(z);
204311
204312    if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
204313      pNew->eRemoveDiacritic = 1;
204314    }
204315    else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
204316      pNew->eRemoveDiacritic = 0;
204317    }
204318    else if( n==19 && memcmp("remove_diacritics=2", z, 19)==0 ){
204319      pNew->eRemoveDiacritic = 2;
204320    }
204321    else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
204322      rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
204323    }
204324    else if( n>=11 && memcmp("separators=", z, 11)==0 ){
204325      rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
204326    }
204327    else{
204328      /* Unrecognized argument */
204329      rc  = SQLITE_ERROR;
204330    }
204331  }
204332
204333  if( rc!=SQLITE_OK ){
204334    unicodeDestroy((sqlite3_tokenizer *)pNew);
204335    pNew = 0;
204336  }
204337  *pp = (sqlite3_tokenizer *)pNew;
204338  return rc;
204339}
204340
204341/*
204342** Prepare to begin tokenizing a particular string.  The input
204343** string to be tokenized is pInput[0..nBytes-1].  A cursor
204344** used to incrementally tokenize this string is returned in
204345** *ppCursor.
204346*/
204347static int unicodeOpen(
204348  sqlite3_tokenizer *p,           /* The tokenizer */
204349  const char *aInput,             /* Input string */
204350  int nInput,                     /* Size of string aInput in bytes */
204351  sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
204352){
204353  unicode_cursor *pCsr;
204354
204355  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
204356  if( pCsr==0 ){
204357    return SQLITE_NOMEM;
204358  }
204359  memset(pCsr, 0, sizeof(unicode_cursor));
204360
204361  pCsr->aInput = (const unsigned char *)aInput;
204362  if( aInput==0 ){
204363    pCsr->nInput = 0;
204364    pCsr->aInput = (const unsigned char*)"";
204365  }else if( nInput<0 ){
204366    pCsr->nInput = (int)strlen(aInput);
204367  }else{
204368    pCsr->nInput = nInput;
204369  }
204370
204371  *pp = &pCsr->base;
204372  UNUSED_PARAMETER(p);
204373  return SQLITE_OK;
204374}
204375
204376/*
204377** Close a tokenization cursor previously opened by a call to
204378** simpleOpen() above.
204379*/
204380static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
204381  unicode_cursor *pCsr = (unicode_cursor *) pCursor;
204382  sqlite3_free(pCsr->zToken);
204383  sqlite3_free(pCsr);
204384  return SQLITE_OK;
204385}
204386
204387/*
204388** Extract the next token from a tokenization cursor.  The cursor must
204389** have been opened by a prior call to simpleOpen().
204390*/
204391static int unicodeNext(
204392  sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
204393  const char **paToken,           /* OUT: Token text */
204394  int *pnToken,                   /* OUT: Number of bytes at *paToken */
204395  int *piStart,                   /* OUT: Starting offset of token */
204396  int *piEnd,                     /* OUT: Ending offset of token */
204397  int *piPos                      /* OUT: Position integer of token */
204398){
204399  unicode_cursor *pCsr = (unicode_cursor *)pC;
204400  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
204401  unsigned int iCode = 0;
204402  char *zOut;
204403  const unsigned char *z = &pCsr->aInput[pCsr->iOff];
204404  const unsigned char *zStart = z;
204405  const unsigned char *zEnd;
204406  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
204407
204408  /* Scan past any delimiter characters before the start of the next token.
204409  ** Return SQLITE_DONE early if this takes us all the way to the end of
204410  ** the input.  */
204411  while( z<zTerm ){
204412    READ_UTF8(z, zTerm, iCode);
204413    if( unicodeIsAlnum(p, (int)iCode) ) break;
204414    zStart = z;
204415  }
204416  if( zStart>=zTerm ) return SQLITE_DONE;
204417
204418  zOut = pCsr->zToken;
204419  do {
204420    int iOut;
204421
204422    /* Grow the output buffer if required. */
204423    if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
204424      char *zNew = sqlite3_realloc64(pCsr->zToken, pCsr->nAlloc+64);
204425      if( !zNew ) return SQLITE_NOMEM;
204426      zOut = &zNew[zOut - pCsr->zToken];
204427      pCsr->zToken = zNew;
204428      pCsr->nAlloc += 64;
204429    }
204430
204431    /* Write the folded case of the last character read to the output */
204432    zEnd = z;
204433    iOut = sqlite3FtsUnicodeFold((int)iCode, p->eRemoveDiacritic);
204434    if( iOut ){
204435      WRITE_UTF8(zOut, iOut);
204436    }
204437
204438    /* If the cursor is not at EOF, read the next character */
204439    if( z>=zTerm ) break;
204440    READ_UTF8(z, zTerm, iCode);
204441  }while( unicodeIsAlnum(p, (int)iCode)
204442       || sqlite3FtsUnicodeIsdiacritic((int)iCode)
204443  );
204444
204445  /* Set the output variables and return. */
204446  pCsr->iOff = (int)(z - pCsr->aInput);
204447  *paToken = pCsr->zToken;
204448  *pnToken = (int)(zOut - pCsr->zToken);
204449  *piStart = (int)(zStart - pCsr->aInput);
204450  *piEnd = (int)(zEnd - pCsr->aInput);
204451  *piPos = pCsr->iToken++;
204452  return SQLITE_OK;
204453}
204454
204455/*
204456** Set *ppModule to a pointer to the sqlite3_tokenizer_module
204457** structure for the unicode tokenizer.
204458*/
204459SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
204460  static const sqlite3_tokenizer_module module = {
204461    0,
204462    unicodeCreate,
204463    unicodeDestroy,
204464    unicodeOpen,
204465    unicodeClose,
204466    unicodeNext,
204467    0,
204468  };
204469  *ppModule = &module;
204470}
204471
204472#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
204473#endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
204474
204475/************** End of fts3_unicode.c ****************************************/
204476/************** Begin file fts3_unicode2.c ***********************************/
204477/*
204478** 2012-05-25
204479**
204480** The author disclaims copyright to this source code.  In place of
204481** a legal notice, here is a blessing:
204482**
204483**    May you do good and not evil.
204484**    May you find forgiveness for yourself and forgive others.
204485**    May you share freely, never taking more than you give.
204486**
204487******************************************************************************
204488*/
204489
204490/*
204491** DO NOT EDIT THIS MACHINE GENERATED FILE.
204492*/
204493
204494#ifndef SQLITE_DISABLE_FTS3_UNICODE
204495#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
204496
204497/* #include <assert.h> */
204498
204499/*
204500** Return true if the argument corresponds to a unicode codepoint
204501** classified as either a letter or a number. Otherwise false.
204502**
204503** The results are undefined if the value passed to this function
204504** is less than zero.
204505*/
204506SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
204507  /* Each unsigned integer in the following array corresponds to a contiguous
204508  ** range of unicode codepoints that are not either letters or numbers (i.e.
204509  ** codepoints for which this function should return 0).
204510  **
204511  ** The most significant 22 bits in each 32-bit value contain the first
204512  ** codepoint in the range. The least significant 10 bits are used to store
204513  ** the size of the range (always at least 1). In other words, the value
204514  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
204515  ** C. It is not possible to represent a range larger than 1023 codepoints
204516  ** using this format.
204517  */
204518  static const unsigned int aEntry[] = {
204519    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
204520    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
204521    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
204522    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
204523    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
204524    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
204525    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
204526    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
204527    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
204528    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
204529    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
204530    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
204531    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
204532    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
204533    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
204534    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
204535    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
204536    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
204537    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
204538    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
204539    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
204540    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
204541    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
204542    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
204543    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
204544    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
204545    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
204546    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
204547    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
204548    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
204549    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
204550    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
204551    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
204552    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
204553    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
204554    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
204555    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
204556    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
204557    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
204558    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
204559    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
204560    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
204561    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
204562    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
204563    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
204564    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
204565    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
204566    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
204567    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
204568    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
204569    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
204570    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
204571    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
204572    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
204573    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
204574    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
204575    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
204576    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
204577    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
204578    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
204579    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
204580    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
204581    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
204582    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
204583    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
204584    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
204585    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
204586    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
204587    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
204588    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
204589    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
204590    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
204591    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
204592    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
204593    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
204594    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
204595    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
204596    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
204597    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
204598    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
204599    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
204600    0x380400F0,
204601  };
204602  static const unsigned int aAscii[4] = {
204603    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
204604  };
204605
204606  if( (unsigned int)c<128 ){
204607    return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
204608  }else if( (unsigned int)c<(1<<22) ){
204609    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
204610    int iRes = 0;
204611    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
204612    int iLo = 0;
204613    while( iHi>=iLo ){
204614      int iTest = (iHi + iLo) / 2;
204615      if( key >= aEntry[iTest] ){
204616        iRes = iTest;
204617        iLo = iTest+1;
204618      }else{
204619        iHi = iTest-1;
204620      }
204621    }
204622    assert( aEntry[0]<key );
204623    assert( key>=aEntry[iRes] );
204624    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
204625  }
204626  return 1;
204627}
204628
204629
204630/*
204631** If the argument is a codepoint corresponding to a lowercase letter
204632** in the ASCII range with a diacritic added, return the codepoint
204633** of the ASCII letter only. For example, if passed 235 - "LATIN
204634** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
204635** E"). The resuls of passing a codepoint that corresponds to an
204636** uppercase letter are undefined.
204637*/
204638static int remove_diacritic(int c, int bComplex){
204639  unsigned short aDia[] = {
204640        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
204641     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
204642     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
204643     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
204644     3456,  3696,  3712,  3728,  3744,  3766,  3832,  3896,
204645     3912,  3928,  3944,  3968,  4008,  4040,  4056,  4106,
204646     4138,  4170,  4202,  4234,  4266,  4296,  4312,  4344,
204647     4408,  4424,  4442,  4472,  4488,  4504,  6148,  6198,
204648     6264,  6280,  6360,  6429,  6505,  6529, 61448, 61468,
204649    61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704,
204650    61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914,
204651    61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218,
204652    62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554,
204653    62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766,
204654    62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118,
204655    63182, 63242, 63274, 63310, 63368, 63390,
204656  };
204657#define HIBIT ((unsigned char)0x80)
204658  unsigned char aChar[] = {
204659    '\0',      'a',       'c',       'e',       'i',       'n',
204660    'o',       'u',       'y',       'y',       'a',       'c',
204661    'd',       'e',       'e',       'g',       'h',       'i',
204662    'j',       'k',       'l',       'n',       'o',       'r',
204663    's',       't',       'u',       'u',       'w',       'y',
204664    'z',       'o',       'u',       'a',       'i',       'o',
204665    'u',       'u'|HIBIT, 'a'|HIBIT, 'g',       'k',       'o',
204666    'o'|HIBIT, 'j',       'g',       'n',       'a'|HIBIT, 'a',
204667    'e',       'i',       'o',       'r',       'u',       's',
204668    't',       'h',       'a',       'e',       'o'|HIBIT, 'o',
204669    'o'|HIBIT, 'y',       '\0',      '\0',      '\0',      '\0',
204670    '\0',      '\0',      '\0',      '\0',      'a',       'b',
204671    'c'|HIBIT, 'd',       'd',       'e'|HIBIT, 'e',       'e'|HIBIT,
204672    'f',       'g',       'h',       'h',       'i',       'i'|HIBIT,
204673    'k',       'l',       'l'|HIBIT, 'l',       'm',       'n',
204674    'o'|HIBIT, 'p',       'r',       'r'|HIBIT, 'r',       's',
204675    's'|HIBIT, 't',       'u',       'u'|HIBIT, 'v',       'w',
204676    'w',       'x',       'y',       'z',       'h',       't',
204677    'w',       'y',       'a',       'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT,
204678    'e',       'e'|HIBIT, 'e'|HIBIT, 'i',       'o',       'o'|HIBIT,
204679    'o'|HIBIT, 'o'|HIBIT, 'u',       'u'|HIBIT, 'u'|HIBIT, 'y',
204680  };
204681
204682  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
204683  int iRes = 0;
204684  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
204685  int iLo = 0;
204686  while( iHi>=iLo ){
204687    int iTest = (iHi + iLo) / 2;
204688    if( key >= aDia[iTest] ){
204689      iRes = iTest;
204690      iLo = iTest+1;
204691    }else{
204692      iHi = iTest-1;
204693    }
204694  }
204695  assert( key>=aDia[iRes] );
204696  if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;
204697  return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);
204698}
204699
204700
204701/*
204702** Return true if the argument interpreted as a unicode codepoint
204703** is a diacritical modifier character.
204704*/
204705SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
204706  unsigned int mask0 = 0x08029FDF;
204707  unsigned int mask1 = 0x000361F8;
204708  if( c<768 || c>817 ) return 0;
204709  return (c < 768+32) ?
204710      (mask0 & ((unsigned int)1 << (c-768))) :
204711      (mask1 & ((unsigned int)1 << (c-768-32)));
204712}
204713
204714
204715/*
204716** Interpret the argument as a unicode codepoint. If the codepoint
204717** is an upper case character that has a lower case equivalent,
204718** return the codepoint corresponding to the lower case version.
204719** Otherwise, return a copy of the argument.
204720**
204721** The results are undefined if the value passed to this function
204722** is less than zero.
204723*/
204724SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){
204725  /* Each entry in the following array defines a rule for folding a range
204726  ** of codepoints to lower case. The rule applies to a range of nRange
204727  ** codepoints starting at codepoint iCode.
204728  **
204729  ** If the least significant bit in flags is clear, then the rule applies
204730  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
204731  ** need to be folded). Or, if it is set, then the rule only applies to
204732  ** every second codepoint in the range, starting with codepoint C.
204733  **
204734  ** The 7 most significant bits in flags are an index into the aiOff[]
204735  ** array. If a specific codepoint C does require folding, then its lower
204736  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
204737  **
204738  ** The contents of this array are generated by parsing the CaseFolding.txt
204739  ** file distributed as part of the "Unicode Character Database". See
204740  ** http://www.unicode.org for details.
204741  */
204742  static const struct TableEntry {
204743    unsigned short iCode;
204744    unsigned char flags;
204745    unsigned char nRange;
204746  } aEntry[] = {
204747    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
204748    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
204749    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
204750    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
204751    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
204752    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
204753    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
204754    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
204755    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
204756    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
204757    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
204758    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
204759    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
204760    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
204761    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
204762    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
204763    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
204764    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
204765    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
204766    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
204767    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
204768    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
204769    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
204770    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
204771    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
204772    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
204773    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
204774    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
204775    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
204776    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
204777    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
204778    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
204779    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
204780    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
204781    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
204782    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
204783    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
204784    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
204785    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
204786    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
204787    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
204788    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
204789    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
204790    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
204791    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
204792    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
204793    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
204794    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
204795    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
204796    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
204797    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
204798    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
204799    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
204800    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
204801    {65313, 14, 26},
204802  };
204803  static const unsigned short aiOff[] = {
204804   1,     2,     8,     15,    16,    26,    28,    32,
204805   37,    38,    40,    48,    63,    64,    69,    71,
204806   79,    80,    116,   202,   203,   205,   206,   207,
204807   209,   210,   211,   213,   214,   217,   218,   219,
204808   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
204809   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
204810   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
204811   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
204812   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
204813   65514, 65521, 65527, 65528, 65529,
204814  };
204815
204816  int ret = c;
204817
204818  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
204819
204820  if( c<128 ){
204821    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
204822  }else if( c<65536 ){
204823    const struct TableEntry *p;
204824    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
204825    int iLo = 0;
204826    int iRes = -1;
204827
204828    assert( c>aEntry[0].iCode );
204829    while( iHi>=iLo ){
204830      int iTest = (iHi + iLo) / 2;
204831      int cmp = (c - aEntry[iTest].iCode);
204832      if( cmp>=0 ){
204833        iRes = iTest;
204834        iLo = iTest+1;
204835      }else{
204836        iHi = iTest-1;
204837      }
204838    }
204839
204840    assert( iRes>=0 && c>=aEntry[iRes].iCode );
204841    p = &aEntry[iRes];
204842    if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
204843      ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
204844      assert( ret>0 );
204845    }
204846
204847    if( eRemoveDiacritic ){
204848      ret = remove_diacritic(ret, eRemoveDiacritic==2);
204849    }
204850  }
204851
204852  else if( c>=66560 && c<66600 ){
204853    ret = c + 40;
204854  }
204855
204856  return ret;
204857}
204858#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
204859#endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
204860
204861/************** End of fts3_unicode2.c ***************************************/
204862/************** Begin file json.c ********************************************/
204863/*
204864** 2015-08-12
204865**
204866** The author disclaims copyright to this source code.  In place of
204867** a legal notice, here is a blessing:
204868**
204869**    May you do good and not evil.
204870**    May you find forgiveness for yourself and forgive others.
204871**    May you share freely, never taking more than you give.
204872**
204873******************************************************************************
204874**
204875** SQLite JSON functions.
204876**
204877** This file began as an extension in ext/misc/json1.c in 2015.  That
204878** extension proved so useful that it has now been moved into the core.
204879**
204880** The original design stored all JSON as pure text, canonical RFC-8259.
204881** Support for JSON-5 extensions was added with version 3.42.0 (2023-05-16).
204882** All generated JSON text still conforms strictly to RFC-8259, but text
204883** with JSON-5 extensions is accepted as input.
204884**
204885** Beginning with version 3.45.0 (circa 2024-01-01), these routines also
204886** accept BLOB values that have JSON encoded using a binary representation
204887** called "JSONB".  The name JSONB comes from PostgreSQL, however the on-disk
204888** format SQLite JSONB is completely different and incompatible with
204889** PostgreSQL JSONB.
204890**
204891** Decoding and interpreting JSONB is still O(N) where N is the size of
204892** the input, the same as text JSON.  However, the constant of proportionality
204893** for JSONB is much smaller due to faster parsing.  The size of each
204894** element in JSONB is encoded in its header, so there is no need to search
204895** for delimiters using persnickety syntax rules.  JSONB seems to be about
204896** 3x faster than text JSON as a result.  JSONB is also tends to be slightly
204897** smaller than text JSON, by 5% or 10%, but there are corner cases where
204898** JSONB can be slightly larger.  So you are not far mistaken to say that
204899** a JSONB blob is the same size as the equivalent RFC-8259 text.
204900**
204901**
204902** THE JSONB ENCODING:
204903**
204904** Every JSON element is encoded in JSONB as a header and a payload.
204905** The header is between 1 and 9 bytes in size.  The payload is zero
204906** or more bytes.
204907**
204908** The lower 4 bits of the first byte of the header determines the
204909** element type:
204910**
204911**    0:   NULL
204912**    1:   TRUE
204913**    2:   FALSE
204914**    3:   INT        -- RFC-8259 integer literal
204915**    4:   INT5       -- JSON5 integer literal
204916**    5:   FLOAT      -- RFC-8259 floating point literal
204917**    6:   FLOAT5     -- JSON5 floating point literal
204918**    7:   TEXT       -- Text literal acceptable to both SQL and JSON
204919**    8:   TEXTJ      -- Text containing RFC-8259 escapes
204920**    9:   TEXT5      -- Text containing JSON5 and/or RFC-8259 escapes
204921**   10:   TEXTRAW    -- Text containing unescaped syntax characters
204922**   11:   ARRAY
204923**   12:   OBJECT
204924**
204925** The other three possible values (13-15) are reserved for future
204926** enhancements.
204927**
204928** The upper 4 bits of the first byte determine the size of the header
204929** and sometimes also the size of the payload.  If X is the first byte
204930** of the element and if X>>4 is between 0 and 11, then the payload
204931** will be that many bytes in size and the header is exactly one byte
204932** in size.  Other four values for X>>4 (12-15) indicate that the header
204933** is more than one byte in size and that the payload size is determined
204934** by the remainder of the header, interpreted as a unsigned big-endian
204935** integer.
204936**
204937**   Value of X>>4         Size integer        Total header size
204938**   -------------     --------------------    -----------------
204939**        12           1 byte (0-255)                2
204940**        13           2 byte (0-65535)              3
204941**        14           4 byte (0-4294967295)         5
204942**        15           8 byte (0-1.8e19)             9
204943**
204944** The payload size need not be expressed in its minimal form.  For example,
204945** if the payload size is 10, the size can be expressed in any of 5 different
204946** ways: (1) (X>>4)==10, (2) (X>>4)==12 following by on 0x0a byte,
204947** (3) (X>>4)==13 followed by 0x00 and 0x0a, (4) (X>>4)==14 followed by
204948** 0x00 0x00 0x00 0x0a, or (5) (X>>4)==15 followed by 7 bytes of 0x00 and
204949** a single byte of 0x0a.  The shorter forms are preferred, of course, but
204950** sometimes when generating JSONB, the payload size is not known in advance
204951** and it is convenient to reserve sufficient header space to cover the
204952** largest possible payload size and then come back later and patch up
204953** the size when it becomes known, resulting in a non-minimal encoding.
204954**
204955** The value (X>>4)==15 is not actually used in the current implementation
204956** (as SQLite is currently unable handle BLOBs larger than about 2GB)
204957** but is included in the design to allow for future enhancements.
204958**
204959** The payload follows the header.  NULL, TRUE, and FALSE have no payload and
204960** their payload size must always be zero.  The payload for INT, INT5,
204961** FLOAT, FLOAT5, TEXT, TEXTJ, TEXT5, and TEXTROW is text.  Note that the
204962** "..." or '...' delimiters are omitted from the various text encodings.
204963** The payload for ARRAY and OBJECT is a list of additional elements that
204964** are the content for the array or object.  The payload for an OBJECT
204965** must be an even number of elements.  The first element of each pair is
204966** the label and must be of type TEXT, TEXTJ, TEXT5, or TEXTRAW.
204967**
204968** A valid JSONB blob consists of a single element, as described above.
204969** Usually this will be an ARRAY or OBJECT element which has many more
204970** elements as its content.  But the overall blob is just a single element.
204971**
204972** Input validation for JSONB blobs simply checks that the element type
204973** code is between 0 and 12 and that the total size of the element
204974** (header plus payload) is the same as the size of the BLOB.  If those
204975** checks are true, the BLOB is assumed to be JSONB and processing continues.
204976** Errors are only raised if some other miscoding is discovered during
204977** processing.
204978**
204979** Additional information can be found in the doc/jsonb.md file of the
204980** canonical SQLite source tree.
204981*/
204982#ifndef SQLITE_OMIT_JSON
204983/* #include "sqliteInt.h" */
204984
204985/* JSONB element types
204986*/
204987#define JSONB_NULL     0   /* "null" */
204988#define JSONB_TRUE     1   /* "true" */
204989#define JSONB_FALSE    2   /* "false" */
204990#define JSONB_INT      3   /* integer acceptable to JSON and SQL */
204991#define JSONB_INT5     4   /* integer in 0x000 notation */
204992#define JSONB_FLOAT    5   /* float acceptable to JSON and SQL */
204993#define JSONB_FLOAT5   6   /* float with JSON5 extensions */
204994#define JSONB_TEXT     7   /* Text compatible with both JSON and SQL */
204995#define JSONB_TEXTJ    8   /* Text with JSON escapes */
204996#define JSONB_TEXT5    9   /* Text with JSON-5 escape */
204997#define JSONB_TEXTRAW 10   /* SQL text that needs escaping for JSON */
204998#define JSONB_ARRAY   11   /* An array */
204999#define JSONB_OBJECT  12   /* An object */
205000
205001/* Human-readable names for the JSONB values.  The index for each
205002** string must correspond to the JSONB_* integer above.
205003*/
205004static const char * const jsonbType[] = {
205005  "null", "true", "false", "integer", "integer",
205006  "real", "real", "text",  "text",    "text",
205007  "text", "array", "object", "", "", "", ""
205008};
205009
205010/*
205011** Growing our own isspace() routine this way is twice as fast as
205012** the library isspace() function, resulting in a 7% overall performance
205013** increase for the text-JSON parser.  (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
205014*/
205015static const char jsonIsSpace[] = {
205016  0, 0, 0, 0, 0, 0, 0, 0,  0, 1, 1, 0, 0, 1, 0, 0,
205017  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205018  1, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205019  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205020  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205021  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205022  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205023  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205024
205025  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205026  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205027  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205028  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205029  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205030  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205031  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205032  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205033};
205034#define jsonIsspace(x) (jsonIsSpace[(unsigned char)x])
205035
205036/*
205037** The set of all space characters recognized by jsonIsspace().
205038** Useful as the second argument to strspn().
205039*/
205040static const char jsonSpaces[] = "\011\012\015\040";
205041
205042/*
205043** Characters that are special to JSON.  Control characters,
205044** '"' and '\\' and '\''.  Actually, '\'' is not special to
205045** canonical JSON, but it is special in JSON-5, so we include
205046** it in the set of special characters.
205047*/
205048static const char jsonIsOk[256] = {
205049  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205050  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
205051  1, 1, 0, 1, 1, 1, 1, 0,  1, 1, 1, 1, 1, 1, 1, 1,
205052  1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 1, 1, 1, 1,
205053  1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 1, 1, 1, 1,
205054  1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 0, 1, 1, 1,
205055  1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 1, 1, 1, 1,
205056  1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 1, 1, 1, 1,
205057
205058  1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 1, 1, 1, 1,
205059  1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 1, 1, 1, 1,
205060  1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 1, 1, 1, 1,
205061  1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 1, 1, 1, 1,
205062  1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 1, 1, 1, 1,
205063  1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 1, 1, 1, 1,
205064  1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 1, 1, 1, 1,
205065  1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 1, 1, 1, 1
205066};
205067
205068/* Objects */
205069typedef struct JsonCache JsonCache;
205070typedef struct JsonString JsonString;
205071typedef struct JsonParse JsonParse;
205072
205073/*
205074** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
205075*/
205076#define JSON_CACHE_ID    (-429938)  /* Cache entry */
205077#define JSON_CACHE_SIZE  4          /* Max number of cache entries */
205078
205079/*
205080** jsonUnescapeOneChar() returns this invalid code point if it encounters
205081** a syntax error.
205082*/
205083#define JSON_INVALID_CHAR 0x99999
205084
205085/* A cache mapping JSON text into JSONB blobs.
205086**
205087** Each cache entry is a JsonParse object with the following restrictions:
205088**
205089**    *   The bReadOnly flag must be set
205090**
205091**    *   The aBlob[] array must be owned by the JsonParse object.  In other
205092**        words, nBlobAlloc must be non-zero.
205093**
205094**    *   eEdit and delta must be zero.
205095**
205096**    *   zJson must be an RCStr.  In other words bJsonIsRCStr must be true.
205097*/
205098struct JsonCache {
205099  sqlite3 *db;                    /* Database connection */
205100  int nUsed;                      /* Number of active entries in the cache */
205101  JsonParse *a[JSON_CACHE_SIZE];  /* One line for each cache entry */
205102};
205103
205104/* An instance of this object represents a JSON string
205105** under construction.  Really, this is a generic string accumulator
205106** that can be and is used to create strings other than JSON.
205107**
205108** If the generated string is longer than will fit into the zSpace[] buffer,
205109** then it will be an RCStr string.  This aids with caching of large
205110** JSON strings.
205111*/
205112struct JsonString {
205113  sqlite3_context *pCtx;   /* Function context - put error messages here */
205114  char *zBuf;              /* Append JSON content here */
205115  u64 nAlloc;              /* Bytes of storage available in zBuf[] */
205116  u64 nUsed;               /* Bytes of zBuf[] currently used */
205117  u8 bStatic;              /* True if zBuf is static space */
205118  u8 eErr;                 /* True if an error has been encountered */
205119  char zSpace[100];        /* Initial static space */
205120};
205121
205122/* Allowed values for JsonString.eErr */
205123#define JSTRING_OOM         0x01   /* Out of memory */
205124#define JSTRING_MALFORMED   0x02   /* Malformed JSONB */
205125#define JSTRING_ERR         0x04   /* Error already sent to sqlite3_result */
205126
205127/* The "subtype" set for text JSON values passed through using
205128** sqlite3_result_subtype() and sqlite3_value_subtype().
205129*/
205130#define JSON_SUBTYPE  74    /* Ascii for "J" */
205131
205132/*
205133** Bit values for the flags passed into various SQL function implementations
205134** via the sqlite3_user_data() value.
205135*/
205136#define JSON_JSON      0x01        /* Result is always JSON */
205137#define JSON_SQL       0x02        /* Result is always SQL */
205138#define JSON_ABPATH    0x03        /* Allow abbreviated JSON path specs */
205139#define JSON_ISSET     0x04        /* json_set(), not json_insert() */
205140#define JSON_BLOB      0x08        /* Use the BLOB output format */
205141
205142
205143/* A parsed JSON value.  Lifecycle:
205144**
205145**   1.  JSON comes in and is parsed into a JSONB value in aBlob.  The
205146**       original text is stored in zJson.  This step is skipped if the
205147**       input is JSONB instead of text JSON.
205148**
205149**   2.  The aBlob[] array is searched using the JSON path notation, if needed.
205150**
205151**   3.  Zero or more changes are made to aBlob[] (via json_remove() or
205152**       json_replace() or json_patch() or similar).
205153**
205154**   4.  New JSON text is generated from the aBlob[] for output.  This step
205155**       is skipped if the function is one of the jsonb_* functions that
205156**       returns JSONB instead of text JSON.
205157*/
205158struct JsonParse {
205159  u8 *aBlob;         /* JSONB representation of JSON value */
205160  u32 nBlob;         /* Bytes of aBlob[] actually used */
205161  u32 nBlobAlloc;    /* Bytes allocated to aBlob[].  0 if aBlob is external */
205162  char *zJson;       /* Json text used for parsing */
205163  sqlite3 *db;       /* The database connection to which this object belongs */
205164  int nJson;         /* Length of the zJson string in bytes */
205165  u32 nJPRef;        /* Number of references to this object */
205166  u32 iErr;          /* Error location in zJson[] */
205167  u16 iDepth;        /* Nesting depth */
205168  u8 nErr;           /* Number of errors seen */
205169  u8 oom;            /* Set to true if out of memory */
205170  u8 bJsonIsRCStr;   /* True if zJson is an RCStr */
205171  u8 hasNonstd;      /* True if input uses non-standard features like JSON5 */
205172  u8 bReadOnly;      /* Do not modify. */
205173  /* Search and edit information.  See jsonLookupStep() */
205174  u8 eEdit;          /* Edit operation to apply */
205175  int delta;         /* Size change due to the edit */
205176  u32 nIns;          /* Number of bytes to insert */
205177  u32 iLabel;        /* Location of label if search landed on an object value */
205178  u8 *aIns;          /* Content to be inserted */
205179};
205180
205181/* Allowed values for JsonParse.eEdit */
205182#define JEDIT_DEL   1   /* Delete if exists */
205183#define JEDIT_REPL  2   /* Overwrite if exists */
205184#define JEDIT_INS   3   /* Insert if not exists */
205185#define JEDIT_SET   4   /* Insert or overwrite */
205186
205187/*
205188** Maximum nesting depth of JSON for this implementation.
205189**
205190** This limit is needed to avoid a stack overflow in the recursive
205191** descent parser.  A depth of 1000 is far deeper than any sane JSON
205192** should go.  Historical note: This limit was 2000 prior to version 3.42.0
205193*/
205194#ifndef SQLITE_JSON_MAX_DEPTH
205195# define JSON_MAX_DEPTH  1000
205196#else
205197# define JSON_MAX_DEPTH SQLITE_JSON_MAX_DEPTH
205198#endif
205199
205200/*
205201** Allowed values for the flgs argument to jsonParseFuncArg();
205202*/
205203#define JSON_EDITABLE  0x01   /* Generate a writable JsonParse object */
205204#define JSON_KEEPERROR 0x02   /* Return non-NULL even if there is an error */
205205
205206/**************************************************************************
205207** Forward references
205208**************************************************************************/
205209static void jsonReturnStringAsBlob(JsonString*);
205210static int jsonFuncArgMightBeBinary(sqlite3_value *pJson);
205211static u32 jsonTranslateBlobToText(const JsonParse*,u32,JsonString*);
205212static void jsonReturnParse(sqlite3_context*,JsonParse*);
205213static JsonParse *jsonParseFuncArg(sqlite3_context*,sqlite3_value*,u32);
205214static void jsonParseFree(JsonParse*);
205215static u32 jsonbPayloadSize(const JsonParse*, u32, u32*);
205216static u32 jsonUnescapeOneChar(const char*, u32, u32*);
205217
205218/**************************************************************************
205219** Utility routines for dealing with JsonCache objects
205220**************************************************************************/
205221
205222/*
205223** Free a JsonCache object.
205224*/
205225static void jsonCacheDelete(JsonCache *p){
205226  int i;
205227  for(i=0; i<p->nUsed; i++){
205228    jsonParseFree(p->a[i]);
205229  }
205230  sqlite3DbFree(p->db, p);
205231}
205232static void jsonCacheDeleteGeneric(void *p){
205233  jsonCacheDelete((JsonCache*)p);
205234}
205235
205236/*
205237** Insert a new entry into the cache.  If the cache is full, expel
205238** the least recently used entry.  Return SQLITE_OK on success or a
205239** result code otherwise.
205240**
205241** Cache entries are stored in age order, oldest first.
205242*/
205243static int jsonCacheInsert(
205244  sqlite3_context *ctx,   /* The SQL statement context holding the cache */
205245  JsonParse *pParse       /* The parse object to be added to the cache */
205246){
205247  JsonCache *p;
205248
205249  assert( pParse->zJson!=0 );
205250  assert( pParse->bJsonIsRCStr );
205251  assert( pParse->delta==0 );
205252  p = sqlite3_get_auxdata(ctx, JSON_CACHE_ID);
205253  if( p==0 ){
205254    sqlite3 *db = sqlite3_context_db_handle(ctx);
205255    p = sqlite3DbMallocZero(db, sizeof(*p));
205256    if( p==0 ) return SQLITE_NOMEM;
205257    p->db = db;
205258    sqlite3_set_auxdata(ctx, JSON_CACHE_ID, p, jsonCacheDeleteGeneric);
205259    p = sqlite3_get_auxdata(ctx, JSON_CACHE_ID);
205260    if( p==0 ) return SQLITE_NOMEM;
205261  }
205262  if( p->nUsed >= JSON_CACHE_SIZE ){
205263    jsonParseFree(p->a[0]);
205264    memmove(p->a, &p->a[1], (JSON_CACHE_SIZE-1)*sizeof(p->a[0]));
205265    p->nUsed = JSON_CACHE_SIZE-1;
205266  }
205267  assert( pParse->nBlobAlloc>0 );
205268  pParse->eEdit = 0;
205269  pParse->nJPRef++;
205270  pParse->bReadOnly = 1;
205271  p->a[p->nUsed] = pParse;
205272  p->nUsed++;
205273  return SQLITE_OK;
205274}
205275
205276/*
205277** Search for a cached translation the json text supplied by pArg.  Return
205278** the JsonParse object if found.  Return NULL if not found.
205279**
205280** When a match if found, the matching entry is moved to become the
205281** most-recently used entry if it isn't so already.
205282**
205283** The JsonParse object returned still belongs to the Cache and might
205284** be deleted at any moment.  If the caller whants the JsonParse to
205285** linger, it needs to increment the nPJRef reference counter.
205286*/
205287static JsonParse *jsonCacheSearch(
205288  sqlite3_context *ctx,    /* The SQL statement context holding the cache */
205289  sqlite3_value *pArg      /* Function argument containing SQL text */
205290){
205291  JsonCache *p;
205292  int i;
205293  const char *zJson;
205294  int nJson;
205295
205296  if( sqlite3_value_type(pArg)!=SQLITE_TEXT ){
205297    return 0;
205298  }
205299  zJson = (const char*)sqlite3_value_text(pArg);
205300  if( zJson==0 ) return 0;
205301  nJson = sqlite3_value_bytes(pArg);
205302
205303  p = sqlite3_get_auxdata(ctx, JSON_CACHE_ID);
205304  if( p==0 ){
205305    return 0;
205306  }
205307  for(i=0; i<p->nUsed; i++){
205308    if( p->a[i]->zJson==zJson ) break;
205309  }
205310  if( i>=p->nUsed ){
205311    for(i=0; i<p->nUsed; i++){
205312      if( p->a[i]->nJson!=nJson ) continue;
205313      if( memcmp(p->a[i]->zJson, zJson, nJson)==0 ) break;
205314    }
205315  }
205316  if( i<p->nUsed ){
205317    if( i<p->nUsed-1 ){
205318      /* Make the matching entry the most recently used entry */
205319      JsonParse *tmp = p->a[i];
205320      memmove(&p->a[i], &p->a[i+1], (p->nUsed-i-1)*sizeof(tmp));
205321      p->a[p->nUsed-1] = tmp;
205322      i = p->nUsed - 1;
205323    }
205324    assert( p->a[i]->delta==0 );
205325    return p->a[i];
205326  }else{
205327    return 0;
205328  }
205329}
205330
205331/**************************************************************************
205332** Utility routines for dealing with JsonString objects
205333**************************************************************************/
205334
205335/* Turn uninitialized bulk memory into a valid JsonString object
205336** holding a zero-length string.
205337*/
205338static void jsonStringZero(JsonString *p){
205339  p->zBuf = p->zSpace;
205340  p->nAlloc = sizeof(p->zSpace);
205341  p->nUsed = 0;
205342  p->bStatic = 1;
205343}
205344
205345/* Initialize the JsonString object
205346*/
205347static void jsonStringInit(JsonString *p, sqlite3_context *pCtx){
205348  p->pCtx = pCtx;
205349  p->eErr = 0;
205350  jsonStringZero(p);
205351}
205352
205353/* Free all allocated memory and reset the JsonString object back to its
205354** initial state.
205355*/
205356static void jsonStringReset(JsonString *p){
205357  if( !p->bStatic ) sqlite3RCStrUnref(p->zBuf);
205358  jsonStringZero(p);
205359}
205360
205361/* Report an out-of-memory (OOM) condition
205362*/
205363static void jsonStringOom(JsonString *p){
205364  p->eErr |= JSTRING_OOM;
205365  if( p->pCtx ) sqlite3_result_error_nomem(p->pCtx);
205366  jsonStringReset(p);
205367}
205368
205369/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
205370** Return zero on success.  Return non-zero on an OOM error
205371*/
205372static int jsonStringGrow(JsonString *p, u32 N){
205373  u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
205374  char *zNew;
205375  if( p->bStatic ){
205376    if( p->eErr ) return 1;
205377    zNew = sqlite3RCStrNew(nTotal);
205378    if( zNew==0 ){
205379      jsonStringOom(p);
205380      return SQLITE_NOMEM;
205381    }
205382    memcpy(zNew, p->zBuf, (size_t)p->nUsed);
205383    p->zBuf = zNew;
205384    p->bStatic = 0;
205385  }else{
205386    p->zBuf = sqlite3RCStrResize(p->zBuf, nTotal);
205387    if( p->zBuf==0 ){
205388      p->eErr |= JSTRING_OOM;
205389      jsonStringZero(p);
205390      return SQLITE_NOMEM;
205391    }
205392  }
205393  p->nAlloc = nTotal;
205394  return SQLITE_OK;
205395}
205396
205397/* Append N bytes from zIn onto the end of the JsonString string.
205398*/
205399static SQLITE_NOINLINE void jsonStringExpandAndAppend(
205400  JsonString *p,
205401  const char *zIn,
205402  u32 N
205403){
205404  assert( N>0 );
205405  if( jsonStringGrow(p,N) ) return;
205406  memcpy(p->zBuf+p->nUsed, zIn, N);
205407  p->nUsed += N;
205408}
205409static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
205410  if( N==0 ) return;
205411  if( N+p->nUsed >= p->nAlloc ){
205412    jsonStringExpandAndAppend(p,zIn,N);
205413  }else{
205414    memcpy(p->zBuf+p->nUsed, zIn, N);
205415    p->nUsed += N;
205416  }
205417}
205418static void jsonAppendRawNZ(JsonString *p, const char *zIn, u32 N){
205419  assert( N>0 );
205420  if( N+p->nUsed >= p->nAlloc ){
205421    jsonStringExpandAndAppend(p,zIn,N);
205422  }else{
205423    memcpy(p->zBuf+p->nUsed, zIn, N);
205424    p->nUsed += N;
205425  }
205426}
205427
205428/* Append formatted text (not to exceed N bytes) to the JsonString.
205429*/
205430static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
205431  va_list ap;
205432  if( (p->nUsed + N >= p->nAlloc) && jsonStringGrow(p, N) ) return;
205433  va_start(ap, zFormat);
205434  sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
205435  va_end(ap);
205436  p->nUsed += (int)strlen(p->zBuf+p->nUsed);
205437}
205438
205439/* Append a single character
205440*/
205441static SQLITE_NOINLINE void jsonAppendCharExpand(JsonString *p, char c){
205442  if( jsonStringGrow(p,1) ) return;
205443  p->zBuf[p->nUsed++] = c;
205444}
205445static void jsonAppendChar(JsonString *p, char c){
205446  if( p->nUsed>=p->nAlloc ){
205447    jsonAppendCharExpand(p,c);
205448  }else{
205449    p->zBuf[p->nUsed++] = c;
205450  }
205451}
205452
205453/* Remove a single character from the end of the string
205454*/
205455static void jsonStringTrimOneChar(JsonString *p){
205456  if( p->eErr==0 ){
205457    assert( p->nUsed>0 );
205458    p->nUsed--;
205459  }
205460}
205461
205462
205463/* Make sure there is a zero terminator on p->zBuf[]
205464**
205465** Return true on success.  Return false if an OOM prevents this
205466** from happening.
205467*/
205468static int jsonStringTerminate(JsonString *p){
205469  jsonAppendChar(p, 0);
205470  jsonStringTrimOneChar(p);
205471  return p->eErr==0;
205472}
205473
205474/* Append a comma separator to the output buffer, if the previous
205475** character is not '[' or '{'.
205476*/
205477static void jsonAppendSeparator(JsonString *p){
205478  char c;
205479  if( p->nUsed==0 ) return;
205480  c = p->zBuf[p->nUsed-1];
205481  if( c=='[' || c=='{' ) return;
205482  jsonAppendChar(p, ',');
205483}
205484
205485/* c is a control character.  Append the canonical JSON representation
205486** of that control character to p.
205487**
205488** This routine assumes that the output buffer has already been enlarged
205489** sufficiently to hold the worst-case encoding plus a nul terminator.
205490*/
205491static void jsonAppendControlChar(JsonString *p, u8 c){
205492  static const char aSpecial[] = {
205493     0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
205494     0, 0, 0, 0, 0, 0, 0, 0,   0,   0,   0, 0,   0,   0, 0, 0
205495  };
205496  assert( sizeof(aSpecial)==32 );
205497  assert( aSpecial['\b']=='b' );
205498  assert( aSpecial['\f']=='f' );
205499  assert( aSpecial['\n']=='n' );
205500  assert( aSpecial['\r']=='r' );
205501  assert( aSpecial['\t']=='t' );
205502  assert( c>=0 && c<sizeof(aSpecial) );
205503  assert( p->nUsed+7 <= p->nAlloc );
205504  if( aSpecial[c] ){
205505    p->zBuf[p->nUsed] = '\\';
205506    p->zBuf[p->nUsed+1] = aSpecial[c];
205507    p->nUsed += 2;
205508  }else{
205509    p->zBuf[p->nUsed] = '\\';
205510    p->zBuf[p->nUsed+1] = 'u';
205511    p->zBuf[p->nUsed+2] = '0';
205512    p->zBuf[p->nUsed+3] = '0';
205513    p->zBuf[p->nUsed+4] = "0123456789abcdef"[c>>4];
205514    p->zBuf[p->nUsed+5] = "0123456789abcdef"[c&0xf];
205515    p->nUsed += 6;
205516  }
205517}
205518
205519/* Append the N-byte string in zIn to the end of the JsonString string
205520** under construction.  Enclose the string in double-quotes ("...") and
205521** escape any double-quotes or backslash characters contained within the
205522** string.
205523**
205524** This routine is a high-runner.  There is a measurable performance
205525** increase associated with unwinding the jsonIsOk[] loop.
205526*/
205527static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
205528  u32 k;
205529  u8 c;
205530  const u8 *z = (const u8*)zIn;
205531  if( z==0 ) return;
205532  if( (N+p->nUsed+2 >= p->nAlloc) && jsonStringGrow(p,N+2)!=0 ) return;
205533  p->zBuf[p->nUsed++] = '"';
205534  while( 1 /*exit-by-break*/ ){
205535    k = 0;
205536    /* The following while() is the 4-way unwound equivalent of
205537    **
205538    **     while( k<N && jsonIsOk[z[k]] ){ k++; }
205539    */
205540    while( 1 /* Exit by break */ ){
205541      if( k+3>=N ){
205542        while( k<N && jsonIsOk[z[k]] ){ k++; }
205543        break;
205544      }
205545      if( !jsonIsOk[z[k]] ){
205546        break;
205547      }
205548      if( !jsonIsOk[z[k+1]] ){
205549        k += 1;
205550        break;
205551      }
205552      if( !jsonIsOk[z[k+2]] ){
205553        k += 2;
205554        break;
205555      }
205556      if( !jsonIsOk[z[k+3]] ){
205557        k += 3;
205558        break;
205559      }else{
205560        k += 4;
205561      }
205562    }
205563    if( k>=N ){
205564      if( k>0 ){
205565        memcpy(&p->zBuf[p->nUsed], z, k);
205566        p->nUsed += k;
205567      }
205568      break;
205569    }
205570    if( k>0 ){
205571      memcpy(&p->zBuf[p->nUsed], z, k);
205572      p->nUsed += k;
205573      z += k;
205574      N -= k;
205575    }
205576    c = z[0];
205577    if( c=='"' || c=='\\' ){
205578      if( (p->nUsed+N+3 > p->nAlloc) && jsonStringGrow(p,N+3)!=0 ) return;
205579      p->zBuf[p->nUsed++] = '\\';
205580      p->zBuf[p->nUsed++] = c;
205581    }else if( c=='\'' ){
205582      p->zBuf[p->nUsed++] = c;
205583    }else{
205584      if( (p->nUsed+N+7 > p->nAlloc) && jsonStringGrow(p,N+7)!=0 ) return;
205585      jsonAppendControlChar(p, c);
205586    }
205587    z++;
205588    N--;
205589  }
205590  p->zBuf[p->nUsed++] = '"';
205591  assert( p->nUsed<p->nAlloc );
205592}
205593
205594/*
205595** Append an sqlite3_value (such as a function parameter) to the JSON
205596** string under construction in p.
205597*/
205598static void jsonAppendSqlValue(
205599  JsonString *p,                 /* Append to this JSON string */
205600  sqlite3_value *pValue          /* Value to append */
205601){
205602  switch( sqlite3_value_type(pValue) ){
205603    case SQLITE_NULL: {
205604      jsonAppendRawNZ(p, "null", 4);
205605      break;
205606    }
205607    case SQLITE_FLOAT: {
205608      jsonPrintf(100, p, "%!0.15g", sqlite3_value_double(pValue));
205609      break;
205610    }
205611    case SQLITE_INTEGER: {
205612      const char *z = (const char*)sqlite3_value_text(pValue);
205613      u32 n = (u32)sqlite3_value_bytes(pValue);
205614      jsonAppendRaw(p, z, n);
205615      break;
205616    }
205617    case SQLITE_TEXT: {
205618      const char *z = (const char*)sqlite3_value_text(pValue);
205619      u32 n = (u32)sqlite3_value_bytes(pValue);
205620      if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
205621        jsonAppendRaw(p, z, n);
205622      }else{
205623        jsonAppendString(p, z, n);
205624      }
205625      break;
205626    }
205627    default: {
205628      if( jsonFuncArgMightBeBinary(pValue) ){
205629        JsonParse px;
205630        memset(&px, 0, sizeof(px));
205631        px.aBlob = (u8*)sqlite3_value_blob(pValue);
205632        px.nBlob = sqlite3_value_bytes(pValue);
205633        jsonTranslateBlobToText(&px, 0, p);
205634      }else if( p->eErr==0 ){
205635        sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
205636        p->eErr = JSTRING_ERR;
205637        jsonStringReset(p);
205638      }
205639      break;
205640    }
205641  }
205642}
205643
205644/* Make the text in p (which is probably a generated JSON text string)
205645** the result of the SQL function.
205646**
205647** The JsonString is reset.
205648**
205649** If pParse and ctx are both non-NULL, then the SQL string in p is
205650** loaded into the zJson field of the pParse object as a RCStr and the
205651** pParse is added to the cache.
205652*/
205653static void jsonReturnString(
205654  JsonString *p,            /* String to return */
205655  JsonParse *pParse,        /* JSONB source or NULL */
205656  sqlite3_context *ctx      /* Where to cache */
205657){
205658  assert( (pParse!=0)==(ctx!=0) );
205659  assert( ctx==0 || ctx==p->pCtx );
205660  if( p->eErr==0 ){
205661    int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(p->pCtx));
205662    if( flags & JSON_BLOB ){
205663      jsonReturnStringAsBlob(p);
205664    }else if( p->bStatic ){
205665      sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
205666                            SQLITE_TRANSIENT, SQLITE_UTF8);
205667    }else if( jsonStringTerminate(p) ){
205668      if( pParse && pParse->bJsonIsRCStr==0 && pParse->nBlobAlloc>0 ){
205669        int rc;
205670        pParse->zJson = sqlite3RCStrRef(p->zBuf);
205671        pParse->nJson = p->nUsed;
205672        pParse->bJsonIsRCStr = 1;
205673        rc = jsonCacheInsert(ctx, pParse);
205674        if( rc==SQLITE_NOMEM ){
205675          sqlite3_result_error_nomem(ctx);
205676          jsonStringReset(p);
205677          return;
205678        }
205679      }
205680      sqlite3_result_text64(p->pCtx, sqlite3RCStrRef(p->zBuf), p->nUsed,
205681                            sqlite3RCStrUnref,
205682                            SQLITE_UTF8);
205683    }else{
205684      sqlite3_result_error_nomem(p->pCtx);
205685    }
205686  }else if( p->eErr & JSTRING_OOM ){
205687    sqlite3_result_error_nomem(p->pCtx);
205688  }else if( p->eErr & JSTRING_MALFORMED ){
205689    sqlite3_result_error(p->pCtx, "malformed JSON", -1);
205690  }
205691  jsonStringReset(p);
205692}
205693
205694/**************************************************************************
205695** Utility routines for dealing with JsonParse objects
205696**************************************************************************/
205697
205698/*
205699** Reclaim all memory allocated by a JsonParse object.  But do not
205700** delete the JsonParse object itself.
205701*/
205702static void jsonParseReset(JsonParse *pParse){
205703  assert( pParse->nJPRef<=1 );
205704  if( pParse->bJsonIsRCStr ){
205705    sqlite3RCStrUnref(pParse->zJson);
205706    pParse->zJson = 0;
205707    pParse->nJson = 0;
205708    pParse->bJsonIsRCStr = 0;
205709  }
205710  if( pParse->nBlobAlloc ){
205711    sqlite3DbFree(pParse->db, pParse->aBlob);
205712    pParse->aBlob = 0;
205713    pParse->nBlob = 0;
205714    pParse->nBlobAlloc = 0;
205715  }
205716}
205717
205718/*
205719** Decrement the reference count on the JsonParse object.  When the
205720** count reaches zero, free the object.
205721*/
205722static void jsonParseFree(JsonParse *pParse){
205723  if( pParse ){
205724    if( pParse->nJPRef>1 ){
205725      pParse->nJPRef--;
205726    }else{
205727      jsonParseReset(pParse);
205728      sqlite3DbFree(pParse->db, pParse);
205729    }
205730  }
205731}
205732
205733/**************************************************************************
205734** Utility routines for the JSON text parser
205735**************************************************************************/
205736
205737/*
205738** Translate a single byte of Hex into an integer.
205739** This routine only gives a correct answer if h really is a valid hexadecimal
205740** character:  0..9a..fA..F.  But unlike sqlite3HexToInt(), it does not
205741** assert() if the digit is not hex.
205742*/
205743static u8 jsonHexToInt(int h){
205744#ifdef SQLITE_ASCII
205745  h += 9*(1&(h>>6));
205746#endif
205747#ifdef SQLITE_EBCDIC
205748  h += 9*(1&~(h>>4));
205749#endif
205750  return (u8)(h & 0xf);
205751}
205752
205753/*
205754** Convert a 4-byte hex string into an integer
205755*/
205756static u32 jsonHexToInt4(const char *z){
205757  u32 v;
205758  v = (jsonHexToInt(z[0])<<12)
205759    + (jsonHexToInt(z[1])<<8)
205760    + (jsonHexToInt(z[2])<<4)
205761    + jsonHexToInt(z[3]);
205762  return v;
205763}
205764
205765/*
205766** Return true if z[] begins with 2 (or more) hexadecimal digits
205767*/
205768static int jsonIs2Hex(const char *z){
205769  return sqlite3Isxdigit(z[0]) && sqlite3Isxdigit(z[1]);
205770}
205771
205772/*
205773** Return true if z[] begins with 4 (or more) hexadecimal digits
205774*/
205775static int jsonIs4Hex(const char *z){
205776  return jsonIs2Hex(z) && jsonIs2Hex(&z[2]);
205777}
205778
205779/*
205780** Return the number of bytes of JSON5 whitespace at the beginning of
205781** the input string z[].
205782**
205783** JSON5 whitespace consists of any of the following characters:
205784**
205785**    Unicode  UTF-8         Name
205786**    U+0009   09            horizontal tab
205787**    U+000a   0a            line feed
205788**    U+000b   0b            vertical tab
205789**    U+000c   0c            form feed
205790**    U+000d   0d            carriage return
205791**    U+0020   20            space
205792**    U+00a0   c2 a0         non-breaking space
205793**    U+1680   e1 9a 80      ogham space mark
205794**    U+2000   e2 80 80      en quad
205795**    U+2001   e2 80 81      em quad
205796**    U+2002   e2 80 82      en space
205797**    U+2003   e2 80 83      em space
205798**    U+2004   e2 80 84      three-per-em space
205799**    U+2005   e2 80 85      four-per-em space
205800**    U+2006   e2 80 86      six-per-em space
205801**    U+2007   e2 80 87      figure space
205802**    U+2008   e2 80 88      punctuation space
205803**    U+2009   e2 80 89      thin space
205804**    U+200a   e2 80 8a      hair space
205805**    U+2028   e2 80 a8      line separator
205806**    U+2029   e2 80 a9      paragraph separator
205807**    U+202f   e2 80 af      narrow no-break space (NNBSP)
205808**    U+205f   e2 81 9f      medium mathematical space (MMSP)
205809**    U+3000   e3 80 80      ideographical space
205810**    U+FEFF   ef bb bf      byte order mark
205811**
205812** In addition, comments between '/', '*' and '*', '/' and
205813** from '/', '/' to end-of-line are also considered to be whitespace.
205814*/
205815static int json5Whitespace(const char *zIn){
205816  int n = 0;
205817  const u8 *z = (u8*)zIn;
205818  while( 1 /*exit by "goto whitespace_done"*/ ){
205819    switch( z[n] ){
205820      case 0x09:
205821      case 0x0a:
205822      case 0x0b:
205823      case 0x0c:
205824      case 0x0d:
205825      case 0x20: {
205826        n++;
205827        break;
205828      }
205829      case '/': {
205830        if( z[n+1]=='*' && z[n+2]!=0 ){
205831          int j;
205832          for(j=n+3; z[j]!='/' || z[j-1]!='*'; j++){
205833            if( z[j]==0 ) goto whitespace_done;
205834          }
205835          n = j+1;
205836          break;
205837        }else if( z[n+1]=='/' ){
205838          int j;
205839          char c;
205840          for(j=n+2; (c = z[j])!=0; j++){
205841            if( c=='\n' || c=='\r' ) break;
205842            if( 0xe2==(u8)c && 0x80==(u8)z[j+1]
205843             && (0xa8==(u8)z[j+2] || 0xa9==(u8)z[j+2])
205844            ){
205845              j += 2;
205846              break;
205847            }
205848          }
205849          n = j;
205850          if( z[n] ) n++;
205851          break;
205852        }
205853        goto whitespace_done;
205854      }
205855      case 0xc2: {
205856        if( z[n+1]==0xa0 ){
205857          n += 2;
205858          break;
205859        }
205860        goto whitespace_done;
205861      }
205862      case 0xe1: {
205863        if( z[n+1]==0x9a && z[n+2]==0x80 ){
205864          n += 3;
205865          break;
205866        }
205867        goto whitespace_done;
205868      }
205869      case 0xe2: {
205870        if( z[n+1]==0x80 ){
205871          u8 c = z[n+2];
205872          if( c<0x80 ) goto whitespace_done;
205873          if( c<=0x8a || c==0xa8 || c==0xa9 || c==0xaf ){
205874            n += 3;
205875            break;
205876          }
205877        }else if( z[n+1]==0x81 && z[n+2]==0x9f ){
205878          n += 3;
205879          break;
205880        }
205881        goto whitespace_done;
205882      }
205883      case 0xe3: {
205884        if( z[n+1]==0x80 && z[n+2]==0x80 ){
205885          n += 3;
205886          break;
205887        }
205888        goto whitespace_done;
205889      }
205890      case 0xef: {
205891        if( z[n+1]==0xbb && z[n+2]==0xbf ){
205892          n += 3;
205893          break;
205894        }
205895        goto whitespace_done;
205896      }
205897      default: {
205898        goto whitespace_done;
205899      }
205900    }
205901  }
205902  whitespace_done:
205903  return n;
205904}
205905
205906/*
205907** Extra floating-point literals to allow in JSON.
205908*/
205909static const struct NanInfName {
205910  char c1;
205911  char c2;
205912  char n;
205913  char eType;
205914  char nRepl;
205915  char *zMatch;
205916  char *zRepl;
205917} aNanInfName[] = {
205918  { 'i', 'I', 3, JSONB_FLOAT, 7, "inf", "9.0e999" },
205919  { 'i', 'I', 8, JSONB_FLOAT, 7, "infinity", "9.0e999" },
205920  { 'n', 'N', 3, JSONB_NULL, 4, "NaN", "null" },
205921  { 'q', 'Q', 4, JSONB_NULL, 4, "QNaN", "null" },
205922  { 's', 'S', 4, JSONB_NULL, 4, "SNaN", "null" },
205923};
205924
205925
205926/*
205927** Report the wrong number of arguments for json_insert(), json_replace()
205928** or json_set().
205929*/
205930static void jsonWrongNumArgs(
205931  sqlite3_context *pCtx,
205932  const char *zFuncName
205933){
205934  char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
205935                               zFuncName);
205936  sqlite3_result_error(pCtx, zMsg, -1);
205937  sqlite3_free(zMsg);
205938}
205939
205940/****************************************************************************
205941** Utility routines for dealing with the binary BLOB representation of JSON
205942****************************************************************************/
205943
205944/*
205945** Expand pParse->aBlob so that it holds at least N bytes.
205946**
205947** Return the number of errors.
205948*/
205949static int jsonBlobExpand(JsonParse *pParse, u32 N){
205950  u8 *aNew;
205951  u32 t;
205952  assert( N>pParse->nBlobAlloc );
205953  if( pParse->nBlobAlloc==0 ){
205954    t = 100;
205955  }else{
205956    t = pParse->nBlobAlloc*2;
205957  }
205958  if( t<N ) t = N+100;
205959  aNew = sqlite3DbRealloc(pParse->db, pParse->aBlob, t);
205960  if( aNew==0 ){ pParse->oom = 1; return 1; }
205961  pParse->aBlob = aNew;
205962  pParse->nBlobAlloc = t;
205963  return 0;
205964}
205965
205966/*
205967** If pParse->aBlob is not previously editable (because it is taken
205968** from sqlite3_value_blob(), as indicated by the fact that
205969** pParse->nBlobAlloc==0 and pParse->nBlob>0) then make it editable
205970** by making a copy into space obtained from malloc.
205971**
205972** Return true on success.  Return false on OOM.
205973*/
205974static int jsonBlobMakeEditable(JsonParse *pParse, u32 nExtra){
205975  u8 *aOld;
205976  u32 nSize;
205977  assert( !pParse->bReadOnly );
205978  if( pParse->oom ) return 0;
205979  if( pParse->nBlobAlloc>0 ) return 1;
205980  aOld = pParse->aBlob;
205981  nSize = pParse->nBlob + nExtra;
205982  pParse->aBlob = 0;
205983  if( jsonBlobExpand(pParse, nSize) ){
205984    return 0;
205985  }
205986  assert( pParse->nBlobAlloc >= pParse->nBlob + nExtra );
205987  memcpy(pParse->aBlob, aOld, pParse->nBlob);
205988  return 1;
205989}
205990
205991/* Expand pParse->aBlob and append one bytes.
205992*/
205993static SQLITE_NOINLINE void jsonBlobExpandAndAppendOneByte(
205994  JsonParse *pParse,
205995  u8 c
205996){
205997  jsonBlobExpand(pParse, pParse->nBlob+1);
205998  if( pParse->oom==0 ){
205999    assert( pParse->nBlob+1<=pParse->nBlobAlloc );
206000    pParse->aBlob[pParse->nBlob++] = c;
206001  }
206002}
206003
206004/* Append a single character.
206005*/
206006static void jsonBlobAppendOneByte(JsonParse *pParse, u8 c){
206007  if( pParse->nBlob >= pParse->nBlobAlloc ){
206008    jsonBlobExpandAndAppendOneByte(pParse, c);
206009  }else{
206010    pParse->aBlob[pParse->nBlob++] = c;
206011  }
206012}
206013
206014/* Slow version of jsonBlobAppendNode() that first resizes the
206015** pParse->aBlob structure.
206016*/
206017static void jsonBlobAppendNode(JsonParse*,u8,u32,const void*);
206018static SQLITE_NOINLINE void jsonBlobExpandAndAppendNode(
206019  JsonParse *pParse,
206020  u8 eType,
206021  u32 szPayload,
206022  const void *aPayload
206023){
206024  if( jsonBlobExpand(pParse, pParse->nBlob+szPayload+9) ) return;
206025  jsonBlobAppendNode(pParse, eType, szPayload, aPayload);
206026}
206027
206028
206029/* Append an node type byte together with the payload size and
206030** possibly also the payload.
206031**
206032** If aPayload is not NULL, then it is a pointer to the payload which
206033** is also appended.  If aPayload is NULL, the pParse->aBlob[] array
206034** is resized (if necessary) so that it is big enough to hold the
206035** payload, but the payload is not appended and pParse->nBlob is left
206036** pointing to where the first byte of payload will eventually be.
206037*/
206038static void jsonBlobAppendNode(
206039  JsonParse *pParse,          /* The JsonParse object under construction */
206040  u8 eType,                   /* Node type.  One of JSONB_* */
206041  u32 szPayload,              /* Number of bytes of payload */
206042  const void *aPayload        /* The payload.  Might be NULL */
206043){
206044  u8 *a;
206045  if( pParse->nBlob+szPayload+9 > pParse->nBlobAlloc ){
206046    jsonBlobExpandAndAppendNode(pParse,eType,szPayload,aPayload);
206047    return;
206048  }
206049  assert( pParse->aBlob!=0 );
206050  a = &pParse->aBlob[pParse->nBlob];
206051  if( szPayload<=11 ){
206052    a[0] = eType | (szPayload<<4);
206053    pParse->nBlob += 1;
206054  }else if( szPayload<=0xff ){
206055    a[0] = eType | 0xc0;
206056    a[1] = szPayload & 0xff;
206057    pParse->nBlob += 2;
206058  }else if( szPayload<=0xffff ){
206059    a[0] = eType | 0xd0;
206060    a[1] = (szPayload >> 8) & 0xff;
206061    a[2] = szPayload & 0xff;
206062    pParse->nBlob += 3;
206063  }else{
206064    a[0] = eType | 0xe0;
206065    a[1] = (szPayload >> 24) & 0xff;
206066    a[2] = (szPayload >> 16) & 0xff;
206067    a[3] = (szPayload >> 8) & 0xff;
206068    a[4] = szPayload & 0xff;
206069    pParse->nBlob += 5;
206070  }
206071  if( aPayload ){
206072    pParse->nBlob += szPayload;
206073    memcpy(&pParse->aBlob[pParse->nBlob-szPayload], aPayload, szPayload);
206074  }
206075}
206076
206077/* Change the payload size for the node at index i to be szPayload.
206078*/
206079static int jsonBlobChangePayloadSize(
206080  JsonParse *pParse,
206081  u32 i,
206082  u32 szPayload
206083){
206084  u8 *a;
206085  u8 szType;
206086  u8 nExtra;
206087  u8 nNeeded;
206088  int delta;
206089  if( pParse->oom ) return 0;
206090  a = &pParse->aBlob[i];
206091  szType = a[0]>>4;
206092  if( szType<=11 ){
206093    nExtra = 0;
206094  }else if( szType==12 ){
206095    nExtra = 1;
206096  }else if( szType==13 ){
206097    nExtra = 2;
206098  }else{
206099    nExtra = 4;
206100  }
206101  if( szPayload<=11 ){
206102    nNeeded = 0;
206103  }else if( szPayload<=0xff ){
206104    nNeeded = 1;
206105  }else if( szPayload<=0xffff ){
206106    nNeeded = 2;
206107  }else{
206108    nNeeded = 4;
206109  }
206110  delta = nNeeded - nExtra;
206111  if( delta ){
206112    u32 newSize = pParse->nBlob + delta;
206113    if( delta>0 ){
206114      if( newSize>pParse->nBlobAlloc && jsonBlobExpand(pParse, newSize) ){
206115        return 0;  /* OOM error.  Error state recorded in pParse->oom. */
206116      }
206117      a = &pParse->aBlob[i];
206118      memmove(&a[1+delta], &a[1], pParse->nBlob - (i+1));
206119    }else{
206120      memmove(&a[1], &a[1-delta], pParse->nBlob - (i+1-delta));
206121    }
206122    pParse->nBlob = newSize;
206123  }
206124  if( nNeeded==0 ){
206125    a[0] = (a[0] & 0x0f) | (szPayload<<4);
206126  }else if( nNeeded==1 ){
206127    a[0] = (a[0] & 0x0f) | 0xc0;
206128    a[1] = szPayload & 0xff;
206129  }else if( nNeeded==2 ){
206130    a[0] = (a[0] & 0x0f) | 0xd0;
206131    a[1] = (szPayload >> 8) & 0xff;
206132    a[2] = szPayload & 0xff;
206133  }else{
206134    a[0] = (a[0] & 0x0f) | 0xe0;
206135    a[1] = (szPayload >> 24) & 0xff;
206136    a[2] = (szPayload >> 16) & 0xff;
206137    a[3] = (szPayload >> 8) & 0xff;
206138    a[4] = szPayload & 0xff;
206139  }
206140  return delta;
206141}
206142
206143/*
206144** If z[0] is 'u' and is followed by exactly 4 hexadecimal character,
206145** then set *pOp to JSONB_TEXTJ and return true.  If not, do not make
206146** any changes to *pOp and return false.
206147*/
206148static int jsonIs4HexB(const char *z, int *pOp){
206149  if( z[0]!='u' ) return 0;
206150  if( !jsonIs4Hex(&z[1]) ) return 0;
206151  *pOp = JSONB_TEXTJ;
206152  return 1;
206153}
206154
206155/*
206156** Check a single element of the JSONB in pParse for validity.
206157**
206158** The element to be checked starts at offset i and must end at on the
206159** last byte before iEnd.
206160**
206161** Return 0 if everything is correct.  Return the 1-based byte offset of the
206162** error if a problem is detected.  (In other words, if the error is at offset
206163** 0, return 1).
206164*/
206165static u32 jsonbValidityCheck(
206166  const JsonParse *pParse,    /* Input JSONB.  Only aBlob and nBlob are used */
206167  u32 i,                      /* Start of element as pParse->aBlob[i] */
206168  u32 iEnd,                   /* One more than the last byte of the element */
206169  u32 iDepth                  /* Current nesting depth */
206170){
206171  u32 n, sz, j, k;
206172  const u8 *z;
206173  u8 x;
206174  if( iDepth>JSON_MAX_DEPTH ) return i+1;
206175  sz = 0;
206176  n = jsonbPayloadSize(pParse, i, &sz);
206177  if( NEVER(n==0) ) return i+1;          /* Checked by caller */
206178  if( NEVER(i+n+sz!=iEnd) ) return i+1;  /* Checked by caller */
206179  z = pParse->aBlob;
206180  x = z[i] & 0x0f;
206181  switch( x ){
206182    case JSONB_NULL:
206183    case JSONB_TRUE:
206184    case JSONB_FALSE: {
206185      return n+sz==1 ? 0 : i+1;
206186    }
206187    case JSONB_INT: {
206188      if( sz<1 ) return i+1;
206189      j = i+n;
206190      if( z[j]=='-' ){
206191        j++;
206192        if( sz<2 ) return i+1;
206193      }
206194      k = i+n+sz;
206195      while( j<k ){
206196        if( sqlite3Isdigit(z[j]) ){
206197          j++;
206198        }else{
206199          return j+1;
206200        }
206201      }
206202      return 0;
206203    }
206204    case JSONB_INT5: {
206205      if( sz<3 ) return i+1;
206206      j = i+n;
206207      if( z[j]=='-' ){
206208        if( sz<4 ) return i+1;
206209        j++;
206210      }
206211      if( z[j]!='0' ) return i+1;
206212      if( z[j+1]!='x' && z[j+1]!='X' ) return j+2;
206213      j += 2;
206214      k = i+n+sz;
206215      while( j<k ){
206216        if( sqlite3Isxdigit(z[j]) ){
206217          j++;
206218        }else{
206219          return j+1;
206220        }
206221      }
206222      return 0;
206223    }
206224    case JSONB_FLOAT:
206225    case JSONB_FLOAT5: {
206226      u8 seen = 0;   /* 0: initial.  1: '.' seen  2: 'e' seen */
206227      if( sz<2 ) return i+1;
206228      j = i+n;
206229      k = j+sz;
206230      if( z[j]=='-' ){
206231        j++;
206232        if( sz<3 ) return i+1;
206233      }
206234      if( z[j]=='.' ){
206235        if( x==JSONB_FLOAT ) return j+1;
206236        if( !sqlite3Isdigit(z[j+1]) ) return j+1;
206237        j += 2;
206238        seen = 1;
206239      }else if( z[j]=='0' && x==JSONB_FLOAT ){
206240        if( j+3>k ) return j+1;
206241        if( z[j+1]!='.' && z[j+1]!='e' && z[j+1]!='E' ) return j+1;
206242        j++;
206243      }
206244      for(; j<k; j++){
206245        if( sqlite3Isdigit(z[j]) ) continue;
206246        if( z[j]=='.' ){
206247          if( seen>0 ) return j+1;
206248          if( x==JSONB_FLOAT && (j==k-1 || !sqlite3Isdigit(z[j+1])) ){
206249            return j+1;
206250          }
206251          seen = 1;
206252          continue;
206253        }
206254        if( z[j]=='e' || z[j]=='E' ){
206255          if( seen==2 ) return j+1;
206256          if( j==k-1 ) return j+1;
206257          if( z[j+1]=='+' || z[j+1]=='-' ){
206258            j++;
206259            if( j==k-1 ) return j+1;
206260          }
206261          seen = 2;
206262          continue;
206263        }
206264        return j+1;
206265      }
206266      if( seen==0 ) return i+1;
206267      return 0;
206268    }
206269    case JSONB_TEXT: {
206270      j = i+n;
206271      k = j+sz;
206272      while( j<k ){
206273        if( !jsonIsOk[z[j]] && z[j]!='\'' ) return j+1;
206274        j++;
206275      }
206276      return 0;
206277    }
206278    case JSONB_TEXTJ:
206279    case JSONB_TEXT5: {
206280      j = i+n;
206281      k = j+sz;
206282      while( j<k ){
206283        if( !jsonIsOk[z[j]] && z[j]!='\'' ){
206284          if( z[j]=='"' ){
206285            if( x==JSONB_TEXTJ ) return j+1;
206286          }else if( z[j]<=0x1f ){
206287            /* Control characters in JSON5 string literals are ok */
206288            if( x==JSONB_TEXTJ ) return j+1;
206289          }else if( NEVER(z[j]!='\\') || j+1>=k ){
206290            return j+1;
206291          }else if( strchr("\"\\/bfnrt",z[j+1])!=0 ){
206292            j++;
206293          }else if( z[j+1]=='u' ){
206294            if( j+5>=k ) return j+1;
206295            if( !jsonIs4Hex((const char*)&z[j+2]) ) return j+1;
206296            j++;
206297          }else if( x!=JSONB_TEXT5 ){
206298            return j+1;
206299          }else{
206300            u32 c = 0;
206301            u32 szC = jsonUnescapeOneChar((const char*)&z[j], k-j, &c);
206302            if( c==JSON_INVALID_CHAR ) return j+1;
206303            j += szC - 1;
206304          }
206305        }
206306        j++;
206307      }
206308      return 0;
206309    }
206310    case JSONB_TEXTRAW: {
206311      return 0;
206312    }
206313    case JSONB_ARRAY: {
206314      u32 sub;
206315      j = i+n;
206316      k = j+sz;
206317      while( j<k ){
206318        sz = 0;
206319        n = jsonbPayloadSize(pParse, j, &sz);
206320        if( n==0 ) return j+1;
206321        if( j+n+sz>k ) return j+1;
206322        sub = jsonbValidityCheck(pParse, j, j+n+sz, iDepth+1);
206323        if( sub ) return sub;
206324        j += n + sz;
206325      }
206326      assert( j==k );
206327      return 0;
206328    }
206329    case JSONB_OBJECT: {
206330      u32 cnt = 0;
206331      u32 sub;
206332      j = i+n;
206333      k = j+sz;
206334      while( j<k ){
206335        sz = 0;
206336        n = jsonbPayloadSize(pParse, j, &sz);
206337        if( n==0 ) return j+1;
206338        if( j+n+sz>k ) return j+1;
206339        if( (cnt & 1)==0 ){
206340          x = z[j] & 0x0f;
206341          if( x<JSONB_TEXT || x>JSONB_TEXTRAW ) return j+1;
206342        }
206343        sub = jsonbValidityCheck(pParse, j, j+n+sz, iDepth+1);
206344        if( sub ) return sub;
206345        cnt++;
206346        j += n + sz;
206347      }
206348      assert( j==k );
206349      if( (cnt & 1)!=0 ) return j+1;
206350      return 0;
206351    }
206352    default: {
206353      return i+1;
206354    }
206355  }
206356}
206357
206358/*
206359** Translate a single element of JSON text at pParse->zJson[i] into
206360** its equivalent binary JSONB representation.  Append the translation into
206361** pParse->aBlob[] beginning at pParse->nBlob.  The size of
206362** pParse->aBlob[] is increased as necessary.
206363**
206364** Return the index of the first character past the end of the element parsed,
206365** or one of the following special result codes:
206366**
206367**      0    End of input
206368**     -1    Syntax error or OOM
206369**     -2    '}' seen   \
206370**     -3    ']' seen    \___  For these returns, pParse->iErr is set to
206371**     -4    ',' seen    /     the index in zJson[] of the seen character
206372**     -5    ':' seen   /
206373*/
206374static int jsonTranslateTextToBlob(JsonParse *pParse, u32 i){
206375  char c;
206376  u32 j;
206377  u32 iThis, iStart;
206378  int x;
206379  u8 t;
206380  const char *z = pParse->zJson;
206381json_parse_restart:
206382  switch( (u8)z[i] ){
206383  case '{': {
206384    /* Parse object */
206385    iThis = pParse->nBlob;
206386    jsonBlobAppendNode(pParse, JSONB_OBJECT, pParse->nJson-i, 0);
206387    if( ++pParse->iDepth > JSON_MAX_DEPTH ){
206388      pParse->iErr = i;
206389      return -1;
206390    }
206391    iStart = pParse->nBlob;
206392    for(j=i+1;;j++){
206393      u32 iBlob = pParse->nBlob;
206394      x = jsonTranslateTextToBlob(pParse, j);
206395      if( x<=0 ){
206396        int op;
206397        if( x==(-2) ){
206398          j = pParse->iErr;
206399          if( pParse->nBlob!=(u32)iStart ) pParse->hasNonstd = 1;
206400          break;
206401        }
206402        j += json5Whitespace(&z[j]);
206403        op = JSONB_TEXT;
206404        if( sqlite3JsonId1(z[j])
206405         || (z[j]=='\\' && jsonIs4HexB(&z[j+1], &op))
206406        ){
206407          int k = j+1;
206408          while( (sqlite3JsonId2(z[k]) && json5Whitespace(&z[k])==0)
206409            || (z[k]=='\\' && jsonIs4HexB(&z[k+1], &op))
206410          ){
206411            k++;
206412          }
206413          assert( iBlob==pParse->nBlob );
206414          jsonBlobAppendNode(pParse, op, k-j, &z[j]);
206415          pParse->hasNonstd = 1;
206416          x = k;
206417        }else{
206418          if( x!=-1 ) pParse->iErr = j;
206419          return -1;
206420        }
206421      }
206422      if( pParse->oom ) return -1;
206423      t = pParse->aBlob[iBlob] & 0x0f;
206424      if( t<JSONB_TEXT || t>JSONB_TEXTRAW ){
206425        pParse->iErr = j;
206426        return -1;
206427      }
206428      j = x;
206429      if( z[j]==':' ){
206430        j++;
206431      }else{
206432        if( jsonIsspace(z[j]) ){
206433          /* strspn() is not helpful here */
206434          do{ j++; }while( jsonIsspace(z[j]) );
206435          if( z[j]==':' ){
206436            j++;
206437            goto parse_object_value;
206438          }
206439        }
206440        x = jsonTranslateTextToBlob(pParse, j);
206441        if( x!=(-5) ){
206442          if( x!=(-1) ) pParse->iErr = j;
206443          return -1;
206444        }
206445        j = pParse->iErr+1;
206446      }
206447    parse_object_value:
206448      x = jsonTranslateTextToBlob(pParse, j);
206449      if( x<=0 ){
206450        if( x!=(-1) ) pParse->iErr = j;
206451        return -1;
206452      }
206453      j = x;
206454      if( z[j]==',' ){
206455        continue;
206456      }else if( z[j]=='}' ){
206457        break;
206458      }else{
206459        if( jsonIsspace(z[j]) ){
206460          j += 1 + (u32)strspn(&z[j+1], jsonSpaces);
206461          if( z[j]==',' ){
206462            continue;
206463          }else if( z[j]=='}' ){
206464            break;
206465          }
206466        }
206467        x = jsonTranslateTextToBlob(pParse, j);
206468        if( x==(-4) ){
206469          j = pParse->iErr;
206470          continue;
206471        }
206472        if( x==(-2) ){
206473          j = pParse->iErr;
206474          break;
206475        }
206476      }
206477      pParse->iErr = j;
206478      return -1;
206479    }
206480    jsonBlobChangePayloadSize(pParse, iThis, pParse->nBlob - iStart);
206481    pParse->iDepth--;
206482    return j+1;
206483  }
206484  case '[': {
206485    /* Parse array */
206486    iThis = pParse->nBlob;
206487    assert( i<=(u32)pParse->nJson );
206488    jsonBlobAppendNode(pParse, JSONB_ARRAY, pParse->nJson - i, 0);
206489    iStart = pParse->nBlob;
206490    if( pParse->oom ) return -1;
206491    if( ++pParse->iDepth > JSON_MAX_DEPTH ){
206492      pParse->iErr = i;
206493      return -1;
206494    }
206495    for(j=i+1;;j++){
206496      x = jsonTranslateTextToBlob(pParse, j);
206497      if( x<=0 ){
206498        if( x==(-3) ){
206499          j = pParse->iErr;
206500          if( pParse->nBlob!=iStart ) pParse->hasNonstd = 1;
206501          break;
206502        }
206503        if( x!=(-1) ) pParse->iErr = j;
206504        return -1;
206505      }
206506      j = x;
206507      if( z[j]==',' ){
206508        continue;
206509      }else if( z[j]==']' ){
206510        break;
206511      }else{
206512        if( jsonIsspace(z[j]) ){
206513          j += 1 + (u32)strspn(&z[j+1], jsonSpaces);
206514          if( z[j]==',' ){
206515            continue;
206516          }else if( z[j]==']' ){
206517            break;
206518          }
206519        }
206520        x = jsonTranslateTextToBlob(pParse, j);
206521        if( x==(-4) ){
206522          j = pParse->iErr;
206523          continue;
206524        }
206525        if( x==(-3) ){
206526          j = pParse->iErr;
206527          break;
206528        }
206529      }
206530      pParse->iErr = j;
206531      return -1;
206532    }
206533    jsonBlobChangePayloadSize(pParse, iThis, pParse->nBlob - iStart);
206534    pParse->iDepth--;
206535    return j+1;
206536  }
206537  case '\'': {
206538    u8 opcode;
206539    char cDelim;
206540    pParse->hasNonstd = 1;
206541    opcode = JSONB_TEXT;
206542    goto parse_string;
206543  case '"':
206544    /* Parse string */
206545    opcode = JSONB_TEXT;
206546  parse_string:
206547    cDelim = z[i];
206548    j = i+1;
206549    while( 1 /*exit-by-break*/ ){
206550      if( jsonIsOk[(u8)z[j]] ){
206551        if( !jsonIsOk[(u8)z[j+1]] ){
206552          j += 1;
206553        }else if( !jsonIsOk[(u8)z[j+2]] ){
206554          j += 2;
206555        }else{
206556          j += 3;
206557          continue;
206558        }
206559      }
206560      c = z[j];
206561      if( c==cDelim ){
206562        break;
206563      }else if( c=='\\' ){
206564        c = z[++j];
206565        if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
206566           || c=='n' || c=='r' || c=='t'
206567           || (c=='u' && jsonIs4Hex(&z[j+1])) ){
206568          if( opcode==JSONB_TEXT ) opcode = JSONB_TEXTJ;
206569        }else if( c=='\'' || c=='0' || c=='v' || c=='\n'
206570           || (0xe2==(u8)c && 0x80==(u8)z[j+1]
206571                && (0xa8==(u8)z[j+2] || 0xa9==(u8)z[j+2]))
206572           || (c=='x' && jsonIs2Hex(&z[j+1])) ){
206573          opcode = JSONB_TEXT5;
206574          pParse->hasNonstd = 1;
206575        }else if( c=='\r' ){
206576          if( z[j+1]=='\n' ) j++;
206577          opcode = JSONB_TEXT5;
206578          pParse->hasNonstd = 1;
206579        }else{
206580          pParse->iErr = j;
206581          return -1;
206582        }
206583      }else if( c<=0x1f ){
206584        if( c==0 ){
206585          pParse->iErr = j;
206586          return -1;
206587        }
206588        /* Control characters are not allowed in canonical JSON string
206589        ** literals, but are allowed in JSON5 string literals. */
206590        opcode = JSONB_TEXT5;
206591        pParse->hasNonstd = 1;
206592      }else if( c=='"' ){
206593        opcode = JSONB_TEXT5;
206594      }
206595      j++;
206596    }
206597    jsonBlobAppendNode(pParse, opcode, j-1-i, &z[i+1]);
206598    return j+1;
206599  }
206600  case 't': {
206601    if( strncmp(z+i,"true",4)==0 && !sqlite3Isalnum(z[i+4]) ){
206602      jsonBlobAppendOneByte(pParse, JSONB_TRUE);
206603      return i+4;
206604    }
206605    pParse->iErr = i;
206606    return -1;
206607  }
206608  case 'f': {
206609    if( strncmp(z+i,"false",5)==0 && !sqlite3Isalnum(z[i+5]) ){
206610      jsonBlobAppendOneByte(pParse, JSONB_FALSE);
206611      return i+5;
206612    }
206613    pParse->iErr = i;
206614    return -1;
206615  }
206616  case '+': {
206617    u8 seenE;
206618    pParse->hasNonstd = 1;
206619    t = 0x00;            /* Bit 0x01:  JSON5.   Bit 0x02:  FLOAT */
206620    goto parse_number;
206621  case '.':
206622    if( sqlite3Isdigit(z[i+1]) ){
206623      pParse->hasNonstd = 1;
206624      t = 0x03;          /* Bit 0x01:  JSON5.   Bit 0x02:  FLOAT */
206625      seenE = 0;
206626      goto parse_number_2;
206627    }
206628    pParse->iErr = i;
206629    return -1;
206630  case '-':
206631  case '0':
206632  case '1':
206633  case '2':
206634  case '3':
206635  case '4':
206636  case '5':
206637  case '6':
206638  case '7':
206639  case '8':
206640  case '9':
206641    /* Parse number */
206642    t = 0x00;            /* Bit 0x01:  JSON5.   Bit 0x02:  FLOAT */
206643  parse_number:
206644    seenE = 0;
206645    assert( '-' < '0' );
206646    assert( '+' < '0' );
206647    assert( '.' < '0' );
206648    c = z[i];
206649
206650    if( c<='0' ){
206651      if( c=='0' ){
206652        if( (z[i+1]=='x' || z[i+1]=='X') && sqlite3Isxdigit(z[i+2]) ){
206653          assert( t==0x00 );
206654          pParse->hasNonstd = 1;
206655          t = 0x01;
206656          for(j=i+3; sqlite3Isxdigit(z[j]); j++){}
206657          goto parse_number_finish;
206658        }else if( sqlite3Isdigit(z[i+1]) ){
206659          pParse->iErr = i+1;
206660          return -1;
206661        }
206662      }else{
206663        if( !sqlite3Isdigit(z[i+1]) ){
206664          /* JSON5 allows for "+Infinity" and "-Infinity" using exactly
206665          ** that case.  SQLite also allows these in any case and it allows
206666          ** "+inf" and "-inf". */
206667          if( (z[i+1]=='I' || z[i+1]=='i')
206668           && sqlite3StrNICmp(&z[i+1], "inf",3)==0
206669          ){
206670            pParse->hasNonstd = 1;
206671            if( z[i]=='-' ){
206672              jsonBlobAppendNode(pParse, JSONB_FLOAT, 6, "-9e999");
206673            }else{
206674              jsonBlobAppendNode(pParse, JSONB_FLOAT, 5, "9e999");
206675            }
206676            return i + (sqlite3StrNICmp(&z[i+4],"inity",5)==0 ? 9 : 4);
206677          }
206678          if( z[i+1]=='.' ){
206679            pParse->hasNonstd = 1;
206680            t |= 0x01;
206681            goto parse_number_2;
206682          }
206683          pParse->iErr = i;
206684          return -1;
206685        }
206686        if( z[i+1]=='0' ){
206687          if( sqlite3Isdigit(z[i+2]) ){
206688            pParse->iErr = i+1;
206689            return -1;
206690          }else if( (z[i+2]=='x' || z[i+2]=='X') && sqlite3Isxdigit(z[i+3]) ){
206691            pParse->hasNonstd = 1;
206692            t |= 0x01;
206693            for(j=i+4; sqlite3Isxdigit(z[j]); j++){}
206694            goto parse_number_finish;
206695          }
206696        }
206697      }
206698    }
206699
206700  parse_number_2:
206701    for(j=i+1;; j++){
206702      c = z[j];
206703      if( sqlite3Isdigit(c) ) continue;
206704      if( c=='.' ){
206705        if( (t & 0x02)!=0 ){
206706          pParse->iErr = j;
206707          return -1;
206708        }
206709        t |= 0x02;
206710        continue;
206711      }
206712      if( c=='e' || c=='E' ){
206713        if( z[j-1]<'0' ){
206714          if( ALWAYS(z[j-1]=='.') && ALWAYS(j-2>=i) && sqlite3Isdigit(z[j-2]) ){
206715            pParse->hasNonstd = 1;
206716            t |= 0x01;
206717          }else{
206718            pParse->iErr = j;
206719            return -1;
206720          }
206721        }
206722        if( seenE ){
206723          pParse->iErr = j;
206724          return -1;
206725        }
206726        t |= 0x02;
206727        seenE = 1;
206728        c = z[j+1];
206729        if( c=='+' || c=='-' ){
206730          j++;
206731          c = z[j+1];
206732        }
206733        if( c<'0' || c>'9' ){
206734          pParse->iErr = j;
206735          return -1;
206736        }
206737        continue;
206738      }
206739      break;
206740    }
206741    if( z[j-1]<'0' ){
206742      if( ALWAYS(z[j-1]=='.') && ALWAYS(j-2>=i) && sqlite3Isdigit(z[j-2]) ){
206743        pParse->hasNonstd = 1;
206744        t |= 0x01;
206745      }else{
206746        pParse->iErr = j;
206747        return -1;
206748      }
206749    }
206750  parse_number_finish:
206751    assert( JSONB_INT+0x01==JSONB_INT5 );
206752    assert( JSONB_FLOAT+0x01==JSONB_FLOAT5 );
206753    assert( JSONB_INT+0x02==JSONB_FLOAT );
206754    if( z[i]=='+' ) i++;
206755    jsonBlobAppendNode(pParse, JSONB_INT+t, j-i, &z[i]);
206756    return j;
206757  }
206758  case '}': {
206759    pParse->iErr = i;
206760    return -2;  /* End of {...} */
206761  }
206762  case ']': {
206763    pParse->iErr = i;
206764    return -3;  /* End of [...] */
206765  }
206766  case ',': {
206767    pParse->iErr = i;
206768    return -4;  /* List separator */
206769  }
206770  case ':': {
206771    pParse->iErr = i;
206772    return -5;  /* Object label/value separator */
206773  }
206774  case 0: {
206775    return 0;   /* End of file */
206776  }
206777  case 0x09:
206778  case 0x0a:
206779  case 0x0d:
206780  case 0x20: {
206781    i += 1 + (u32)strspn(&z[i+1], jsonSpaces);
206782    goto json_parse_restart;
206783  }
206784  case 0x0b:
206785  case 0x0c:
206786  case '/':
206787  case 0xc2:
206788  case 0xe1:
206789  case 0xe2:
206790  case 0xe3:
206791  case 0xef: {
206792    j = json5Whitespace(&z[i]);
206793    if( j>0 ){
206794      i += j;
206795      pParse->hasNonstd = 1;
206796      goto json_parse_restart;
206797    }
206798    pParse->iErr = i;
206799    return -1;
206800  }
206801  case 'n': {
206802    if( strncmp(z+i,"null",4)==0 && !sqlite3Isalnum(z[i+4]) ){
206803      jsonBlobAppendOneByte(pParse, JSONB_NULL);
206804      return i+4;
206805    }
206806    /* fall-through into the default case that checks for NaN */
206807    /* no break */ deliberate_fall_through
206808  }
206809  default: {
206810    u32 k;
206811    int nn;
206812    c = z[i];
206813    for(k=0; k<sizeof(aNanInfName)/sizeof(aNanInfName[0]); k++){
206814      if( c!=aNanInfName[k].c1 && c!=aNanInfName[k].c2 ) continue;
206815      nn = aNanInfName[k].n;
206816      if( sqlite3StrNICmp(&z[i], aNanInfName[k].zMatch, nn)!=0 ){
206817        continue;
206818      }
206819      if( sqlite3Isalnum(z[i+nn]) ) continue;
206820      if( aNanInfName[k].eType==JSONB_FLOAT ){
206821        jsonBlobAppendNode(pParse, JSONB_FLOAT, 5, "9e999");
206822      }else{
206823        jsonBlobAppendOneByte(pParse, JSONB_NULL);
206824      }
206825      pParse->hasNonstd = 1;
206826      return i + nn;
206827    }
206828    pParse->iErr = i;
206829    return -1;  /* Syntax error */
206830  }
206831  } /* End switch(z[i]) */
206832}
206833
206834
206835/*
206836** Parse a complete JSON string.  Return 0 on success or non-zero if there
206837** are any errors.  If an error occurs, free all memory held by pParse,
206838** but not pParse itself.
206839**
206840** pParse must be initialized to an empty parse object prior to calling
206841** this routine.
206842*/
206843static int jsonConvertTextToBlob(
206844  JsonParse *pParse,           /* Initialize and fill this JsonParse object */
206845  sqlite3_context *pCtx        /* Report errors here */
206846){
206847  int i;
206848  const char *zJson = pParse->zJson;
206849  i = jsonTranslateTextToBlob(pParse, 0);
206850  if( pParse->oom ) i = -1;
206851  if( i>0 ){
206852#ifdef SQLITE_DEBUG
206853    assert( pParse->iDepth==0 );
206854    if( sqlite3Config.bJsonSelfcheck ){
206855      assert( jsonbValidityCheck(pParse, 0, pParse->nBlob, 0)==0 );
206856    }
206857#endif
206858    while( jsonIsspace(zJson[i]) ) i++;
206859    if( zJson[i] ){
206860      i += json5Whitespace(&zJson[i]);
206861      if( zJson[i] ){
206862        if( pCtx ) sqlite3_result_error(pCtx, "malformed JSON", -1);
206863        jsonParseReset(pParse);
206864        return 1;
206865      }
206866      pParse->hasNonstd = 1;
206867    }
206868  }
206869  if( i<=0 ){
206870    if( pCtx!=0 ){
206871      if( pParse->oom ){
206872        sqlite3_result_error_nomem(pCtx);
206873      }else{
206874        sqlite3_result_error(pCtx, "malformed JSON", -1);
206875      }
206876    }
206877    jsonParseReset(pParse);
206878    return 1;
206879  }
206880  return 0;
206881}
206882
206883/*
206884** The input string pStr is a well-formed JSON text string.  Convert
206885** this into the JSONB format and make it the return value of the
206886** SQL function.
206887*/
206888static void jsonReturnStringAsBlob(JsonString *pStr){
206889  JsonParse px;
206890  memset(&px, 0, sizeof(px));
206891  jsonStringTerminate(pStr);
206892  if( pStr->eErr ){
206893    sqlite3_result_error_nomem(pStr->pCtx);
206894    return;
206895  }
206896  px.zJson = pStr->zBuf;
206897  px.nJson = pStr->nUsed;
206898  px.db = sqlite3_context_db_handle(pStr->pCtx);
206899  (void)jsonTranslateTextToBlob(&px, 0);
206900  if( px.oom ){
206901    sqlite3DbFree(px.db, px.aBlob);
206902    sqlite3_result_error_nomem(pStr->pCtx);
206903  }else{
206904    assert( px.nBlobAlloc>0 );
206905    assert( !px.bReadOnly );
206906    sqlite3_result_blob(pStr->pCtx, px.aBlob, px.nBlob, SQLITE_DYNAMIC);
206907  }
206908}
206909
206910/* The byte at index i is a node type-code.  This routine
206911** determines the payload size for that node and writes that
206912** payload size in to *pSz.  It returns the offset from i to the
206913** beginning of the payload.  Return 0 on error.
206914*/
206915static u32 jsonbPayloadSize(const JsonParse *pParse, u32 i, u32 *pSz){
206916  u8 x;
206917  u32 sz;
206918  u32 n;
206919  if( NEVER(i>pParse->nBlob) ){
206920    *pSz = 0;
206921    return 0;
206922  }
206923  x = pParse->aBlob[i]>>4;
206924  if( x<=11 ){
206925    sz = x;
206926    n = 1;
206927  }else if( x==12 ){
206928    if( i+1>=pParse->nBlob ){
206929      *pSz = 0;
206930      return 0;
206931    }
206932    sz = pParse->aBlob[i+1];
206933    n = 2;
206934  }else if( x==13 ){
206935    if( i+2>=pParse->nBlob ){
206936      *pSz = 0;
206937      return 0;
206938    }
206939    sz = (pParse->aBlob[i+1]<<8) + pParse->aBlob[i+2];
206940    n = 3;
206941  }else if( x==14 ){
206942    if( i+4>=pParse->nBlob ){
206943      *pSz = 0;
206944      return 0;
206945    }
206946    sz = ((u32)pParse->aBlob[i+1]<<24) + (pParse->aBlob[i+2]<<16) +
206947         (pParse->aBlob[i+3]<<8) + pParse->aBlob[i+4];
206948    n = 5;
206949  }else{
206950    if( i+8>=pParse->nBlob
206951     || pParse->aBlob[i+1]!=0
206952     || pParse->aBlob[i+2]!=0
206953     || pParse->aBlob[i+3]!=0
206954     || pParse->aBlob[i+4]!=0
206955    ){
206956      *pSz = 0;
206957      return 0;
206958    }
206959    sz = (pParse->aBlob[i+5]<<24) + (pParse->aBlob[i+6]<<16) +
206960         (pParse->aBlob[i+7]<<8) + pParse->aBlob[i+8];
206961    n = 9;
206962  }
206963  if( (i64)i+sz+n > pParse->nBlob
206964   && (i64)i+sz+n > pParse->nBlob-pParse->delta
206965  ){
206966    sz = 0;
206967    n = 0;
206968  }
206969  *pSz = sz;
206970  return n;
206971}
206972
206973
206974/*
206975** Translate the binary JSONB representation of JSON beginning at
206976** pParse->aBlob[i] into a JSON text string.  Append the JSON
206977** text onto the end of pOut.  Return the index in pParse->aBlob[]
206978** of the first byte past the end of the element that is translated.
206979**
206980** If an error is detected in the BLOB input, the pOut->eErr flag
206981** might get set to JSTRING_MALFORMED.  But not all BLOB input errors
206982** are detected.  So a malformed JSONB input might either result
206983** in an error, or in incorrect JSON.
206984**
206985** The pOut->eErr JSTRING_OOM flag is set on a OOM.
206986*/
206987static u32 jsonTranslateBlobToText(
206988  const JsonParse *pParse,       /* the complete parse of the JSON */
206989  u32 i,                         /* Start rendering at this index */
206990  JsonString *pOut               /* Write JSON here */
206991){
206992  u32 sz, n, j, iEnd;
206993
206994  n = jsonbPayloadSize(pParse, i, &sz);
206995  if( n==0 ){
206996    pOut->eErr |= JSTRING_MALFORMED;
206997    return pParse->nBlob+1;
206998  }
206999  switch( pParse->aBlob[i] & 0x0f ){
207000    case JSONB_NULL: {
207001      jsonAppendRawNZ(pOut, "null", 4);
207002      return i+1;
207003    }
207004    case JSONB_TRUE: {
207005      jsonAppendRawNZ(pOut, "true", 4);
207006      return i+1;
207007    }
207008    case JSONB_FALSE: {
207009      jsonAppendRawNZ(pOut, "false", 5);
207010      return i+1;
207011    }
207012    case JSONB_INT:
207013    case JSONB_FLOAT: {
207014      if( sz==0 ) goto malformed_jsonb;
207015      jsonAppendRaw(pOut, (const char*)&pParse->aBlob[i+n], sz);
207016      break;
207017    }
207018    case JSONB_INT5: {  /* Integer literal in hexadecimal notation */
207019      u32 k = 2;
207020      sqlite3_uint64 u = 0;
207021      const char *zIn = (const char*)&pParse->aBlob[i+n];
207022      int bOverflow = 0;
207023      if( sz==0 ) goto malformed_jsonb;
207024      if( zIn[0]=='-' ){
207025        jsonAppendChar(pOut, '-');
207026        k++;
207027      }else if( zIn[0]=='+' ){
207028        k++;
207029      }
207030      for(; k<sz; k++){
207031        if( !sqlite3Isxdigit(zIn[k]) ){
207032          pOut->eErr |= JSTRING_MALFORMED;
207033          break;
207034        }else if( (u>>60)!=0 ){
207035          bOverflow = 1;
207036        }else{
207037          u = u*16 + sqlite3HexToInt(zIn[k]);
207038        }
207039      }
207040      jsonPrintf(100,pOut,bOverflow?"9.0e999":"%llu", u);
207041      break;
207042    }
207043    case JSONB_FLOAT5: { /* Float literal missing digits beside "." */
207044      u32 k = 0;
207045      const char *zIn = (const char*)&pParse->aBlob[i+n];
207046      if( sz==0 ) goto malformed_jsonb;
207047      if( zIn[0]=='-' ){
207048        jsonAppendChar(pOut, '-');
207049        k++;
207050      }
207051      if( zIn[k]=='.' ){
207052        jsonAppendChar(pOut, '0');
207053      }
207054      for(; k<sz; k++){
207055        jsonAppendChar(pOut, zIn[k]);
207056        if( zIn[k]=='.' && (k+1==sz || !sqlite3Isdigit(zIn[k+1])) ){
207057          jsonAppendChar(pOut, '0');
207058        }
207059      }
207060      break;
207061    }
207062    case JSONB_TEXT:
207063    case JSONB_TEXTJ: {
207064      jsonAppendChar(pOut, '"');
207065      jsonAppendRaw(pOut, (const char*)&pParse->aBlob[i+n], sz);
207066      jsonAppendChar(pOut, '"');
207067      break;
207068    }
207069    case JSONB_TEXT5: {
207070      const char *zIn;
207071      u32 k;
207072      u32 sz2 = sz;
207073      zIn = (const char*)&pParse->aBlob[i+n];
207074      jsonAppendChar(pOut, '"');
207075      while( sz2>0 ){
207076        for(k=0; k<sz2 && (jsonIsOk[(u8)zIn[k]] || zIn[k]=='\''); k++){}
207077        if( k>0 ){
207078          jsonAppendRawNZ(pOut, zIn, k);
207079          if( k>=sz2 ){
207080            break;
207081          }
207082          zIn += k;
207083          sz2 -= k;
207084        }
207085        if( zIn[0]=='"' ){
207086          jsonAppendRawNZ(pOut, "\\\"", 2);
207087          zIn++;
207088          sz2--;
207089          continue;
207090        }
207091        if( zIn[0]<=0x1f ){
207092          if( pOut->nUsed+7>pOut->nAlloc && jsonStringGrow(pOut,7) ) break;
207093          jsonAppendControlChar(pOut, zIn[0]);
207094          zIn++;
207095          sz2--;
207096          continue;
207097        }
207098        assert( zIn[0]=='\\' );
207099        assert( sz2>=1 );
207100        if( sz2<2 ){
207101          pOut->eErr |= JSTRING_MALFORMED;
207102          break;
207103        }
207104        switch( (u8)zIn[1] ){
207105          case '\'':
207106            jsonAppendChar(pOut, '\'');
207107            break;
207108          case 'v':
207109            jsonAppendRawNZ(pOut, "\\u0009", 6);
207110            break;
207111          case 'x':
207112            if( sz2<4 ){
207113              pOut->eErr |= JSTRING_MALFORMED;
207114              sz2 = 2;
207115              break;
207116            }
207117            jsonAppendRawNZ(pOut, "\\u00", 4);
207118            jsonAppendRawNZ(pOut, &zIn[2], 2);
207119            zIn += 2;
207120            sz2 -= 2;
207121            break;
207122          case '0':
207123            jsonAppendRawNZ(pOut, "\\u0000", 6);
207124            break;
207125          case '\r':
207126            if( sz2>2 && zIn[2]=='\n' ){
207127              zIn++;
207128              sz2--;
207129            }
207130            break;
207131          case '\n':
207132            break;
207133          case 0xe2:
207134            /* '\' followed by either U+2028 or U+2029 is ignored as
207135            ** whitespace.  Not that in UTF8, U+2028 is 0xe2 0x80 0x29.
207136            ** U+2029 is the same except for the last byte */
207137            if( sz2<4
207138             || 0x80!=(u8)zIn[2]
207139             || (0xa8!=(u8)zIn[3] && 0xa9!=(u8)zIn[3])
207140            ){
207141              pOut->eErr |= JSTRING_MALFORMED;
207142              sz2 = 2;
207143              break;
207144            }
207145            zIn += 2;
207146            sz2 -= 2;
207147            break;
207148          default:
207149            jsonAppendRawNZ(pOut, zIn, 2);
207150            break;
207151        }
207152        assert( sz2>=2 );
207153        zIn += 2;
207154        sz2 -= 2;
207155      }
207156      jsonAppendChar(pOut, '"');
207157      break;
207158    }
207159    case JSONB_TEXTRAW: {
207160      jsonAppendString(pOut, (const char*)&pParse->aBlob[i+n], sz);
207161      break;
207162    }
207163    case JSONB_ARRAY: {
207164      jsonAppendChar(pOut, '[');
207165      j = i+n;
207166      iEnd = j+sz;
207167      while( j<iEnd && pOut->eErr==0 ){
207168        j = jsonTranslateBlobToText(pParse, j, pOut);
207169        jsonAppendChar(pOut, ',');
207170      }
207171      if( j>iEnd ) pOut->eErr |= JSTRING_MALFORMED;
207172      if( sz>0 ) jsonStringTrimOneChar(pOut);
207173      jsonAppendChar(pOut, ']');
207174      break;
207175    }
207176    case JSONB_OBJECT: {
207177      int x = 0;
207178      jsonAppendChar(pOut, '{');
207179      j = i+n;
207180      iEnd = j+sz;
207181      while( j<iEnd && pOut->eErr==0 ){
207182        j = jsonTranslateBlobToText(pParse, j, pOut);
207183        jsonAppendChar(pOut, (x++ & 1) ? ',' : ':');
207184      }
207185      if( (x & 1)!=0 || j>iEnd ) pOut->eErr |= JSTRING_MALFORMED;
207186      if( sz>0 ) jsonStringTrimOneChar(pOut);
207187      jsonAppendChar(pOut, '}');
207188      break;
207189    }
207190
207191    default: {
207192      malformed_jsonb:
207193      pOut->eErr |= JSTRING_MALFORMED;
207194      break;
207195    }
207196  }
207197  return i+n+sz;
207198}
207199
207200/* Context for recursion of json_pretty()
207201*/
207202typedef struct JsonPretty JsonPretty;
207203struct JsonPretty {
207204  JsonParse *pParse;        /* The BLOB being rendered */
207205  JsonString *pOut;         /* Generate pretty output into this string */
207206  const char *zIndent;      /* Use this text for indentation */
207207  u32 szIndent;             /* Bytes in zIndent[] */
207208  u32 nIndent;              /* Current level of indentation */
207209};
207210
207211/* Append indentation to the pretty JSON under construction */
207212static void jsonPrettyIndent(JsonPretty *pPretty){
207213  u32 jj;
207214  for(jj=0; jj<pPretty->nIndent; jj++){
207215    jsonAppendRaw(pPretty->pOut, pPretty->zIndent, pPretty->szIndent);
207216  }
207217}
207218
207219/*
207220** Translate the binary JSONB representation of JSON beginning at
207221** pParse->aBlob[i] into a JSON text string.  Append the JSON
207222** text onto the end of pOut.  Return the index in pParse->aBlob[]
207223** of the first byte past the end of the element that is translated.
207224**
207225** This is a variant of jsonTranslateBlobToText() that "pretty-prints"
207226** the output.  Extra whitespace is inserted to make the JSON easier
207227** for humans to read.
207228**
207229** If an error is detected in the BLOB input, the pOut->eErr flag
207230** might get set to JSTRING_MALFORMED.  But not all BLOB input errors
207231** are detected.  So a malformed JSONB input might either result
207232** in an error, or in incorrect JSON.
207233**
207234** The pOut->eErr JSTRING_OOM flag is set on a OOM.
207235*/
207236static u32 jsonTranslateBlobToPrettyText(
207237  JsonPretty *pPretty,       /* Pretty-printing context */
207238  u32 i                      /* Start rendering at this index */
207239){
207240  u32 sz, n, j, iEnd;
207241  const JsonParse *pParse = pPretty->pParse;
207242  JsonString *pOut = pPretty->pOut;
207243  n = jsonbPayloadSize(pParse, i, &sz);
207244  if( n==0 ){
207245    pOut->eErr |= JSTRING_MALFORMED;
207246    return pParse->nBlob+1;
207247  }
207248  switch( pParse->aBlob[i] & 0x0f ){
207249    case JSONB_ARRAY: {
207250      j = i+n;
207251      iEnd = j+sz;
207252      jsonAppendChar(pOut, '[');
207253      if( j<iEnd ){
207254        jsonAppendChar(pOut, '\n');
207255        pPretty->nIndent++;
207256        while( pOut->eErr==0 ){
207257          jsonPrettyIndent(pPretty);
207258          j = jsonTranslateBlobToPrettyText(pPretty, j);
207259          if( j>=iEnd ) break;
207260          jsonAppendRawNZ(pOut, ",\n", 2);
207261        }
207262        jsonAppendChar(pOut, '\n');
207263        pPretty->nIndent--;
207264        jsonPrettyIndent(pPretty);
207265      }
207266      jsonAppendChar(pOut, ']');
207267      i = iEnd;
207268      break;
207269    }
207270    case JSONB_OBJECT: {
207271      j = i+n;
207272      iEnd = j+sz;
207273      jsonAppendChar(pOut, '{');
207274      if( j<iEnd ){
207275        jsonAppendChar(pOut, '\n');
207276        pPretty->nIndent++;
207277        while( pOut->eErr==0 ){
207278          jsonPrettyIndent(pPretty);
207279          j = jsonTranslateBlobToText(pParse, j, pOut);
207280          if( j>iEnd ){
207281            pOut->eErr |= JSTRING_MALFORMED;
207282            break;
207283          }
207284          jsonAppendRawNZ(pOut, ": ", 2);
207285          j = jsonTranslateBlobToPrettyText(pPretty, j);
207286          if( j>=iEnd ) break;
207287          jsonAppendRawNZ(pOut, ",\n", 2);
207288        }
207289        jsonAppendChar(pOut, '\n');
207290        pPretty->nIndent--;
207291        jsonPrettyIndent(pPretty);
207292      }
207293      jsonAppendChar(pOut, '}');
207294      i = iEnd;
207295      break;
207296    }
207297    default: {
207298      i = jsonTranslateBlobToText(pParse, i, pOut);
207299      break;
207300    }
207301  }
207302  return i;
207303}
207304
207305
207306/* Return true if the input pJson
207307**
207308** For performance reasons, this routine does not do a detailed check of the
207309** input BLOB to ensure that it is well-formed.  Hence, false positives are
207310** possible.  False negatives should never occur, however.
207311*/
207312static int jsonFuncArgMightBeBinary(sqlite3_value *pJson){
207313  u32 sz, n;
207314  const u8 *aBlob;
207315  int nBlob;
207316  JsonParse s;
207317  if( sqlite3_value_type(pJson)!=SQLITE_BLOB ) return 0;
207318  aBlob = sqlite3_value_blob(pJson);
207319  nBlob = sqlite3_value_bytes(pJson);
207320  if( nBlob<1 ) return 0;
207321  if( NEVER(aBlob==0) || (aBlob[0] & 0x0f)>JSONB_OBJECT ) return 0;
207322  memset(&s, 0, sizeof(s));
207323  s.aBlob = (u8*)aBlob;
207324  s.nBlob = nBlob;
207325  n = jsonbPayloadSize(&s, 0, &sz);
207326  if( n==0 ) return 0;
207327  if( sz+n!=(u32)nBlob ) return 0;
207328  if( (aBlob[0] & 0x0f)<=JSONB_FALSE && sz>0 ) return 0;
207329  return sz+n==(u32)nBlob;
207330}
207331
207332/*
207333** Given that a JSONB_ARRAY object starts at offset i, return
207334** the number of entries in that array.
207335*/
207336static u32 jsonbArrayCount(JsonParse *pParse, u32 iRoot){
207337  u32 n, sz, i, iEnd;
207338  u32 k = 0;
207339  n = jsonbPayloadSize(pParse, iRoot, &sz);
207340  iEnd = iRoot+n+sz;
207341  for(i=iRoot+n; n>0 && i<iEnd; i+=sz+n, k++){
207342    n = jsonbPayloadSize(pParse, i, &sz);
207343  }
207344  return k;
207345}
207346
207347/*
207348** Edit the payload size of the element at iRoot by the amount in
207349** pParse->delta.
207350*/
207351static void jsonAfterEditSizeAdjust(JsonParse *pParse, u32 iRoot){
207352  u32 sz = 0;
207353  u32 nBlob;
207354  assert( pParse->delta!=0 );
207355  assert( pParse->nBlobAlloc >= pParse->nBlob );
207356  nBlob = pParse->nBlob;
207357  pParse->nBlob = pParse->nBlobAlloc;
207358  (void)jsonbPayloadSize(pParse, iRoot, &sz);
207359  pParse->nBlob = nBlob;
207360  sz += pParse->delta;
207361  pParse->delta += jsonBlobChangePayloadSize(pParse, iRoot, sz);
207362}
207363
207364/*
207365** Modify the JSONB blob at pParse->aBlob by removing nDel bytes of
207366** content beginning at iDel, and replacing them with nIns bytes of
207367** content given by aIns.
207368**
207369** nDel may be zero, in which case no bytes are removed.  But iDel is
207370** still important as new bytes will be insert beginning at iDel.
207371**
207372** aIns may be zero, in which case space is created to hold nIns bytes
207373** beginning at iDel, but that space is uninitialized.
207374**
207375** Set pParse->oom if an OOM occurs.
207376*/
207377static void jsonBlobEdit(
207378  JsonParse *pParse,     /* The JSONB to be modified is in pParse->aBlob */
207379  u32 iDel,              /* First byte to be removed */
207380  u32 nDel,              /* Number of bytes to remove */
207381  const u8 *aIns,        /* Content to insert */
207382  u32 nIns               /* Bytes of content to insert */
207383){
207384  i64 d = (i64)nIns - (i64)nDel;
207385  if( d!=0 ){
207386    if( pParse->nBlob + d > pParse->nBlobAlloc ){
207387      jsonBlobExpand(pParse, pParse->nBlob+d);
207388      if( pParse->oom ) return;
207389    }
207390    memmove(&pParse->aBlob[iDel+nIns],
207391            &pParse->aBlob[iDel+nDel],
207392            pParse->nBlob - (iDel+nDel));
207393    pParse->nBlob += d;
207394    pParse->delta += d;
207395  }
207396  if( nIns && aIns ) memcpy(&pParse->aBlob[iDel], aIns, nIns);
207397}
207398
207399/*
207400** Return the number of escaped newlines to be ignored.
207401** An escaped newline is a one of the following byte sequences:
207402**
207403**    0x5c 0x0a
207404**    0x5c 0x0d
207405**    0x5c 0x0d 0x0a
207406**    0x5c 0xe2 0x80 0xa8
207407**    0x5c 0xe2 0x80 0xa9
207408*/
207409static u32 jsonBytesToBypass(const char *z, u32 n){
207410  u32 i = 0;
207411  while( i+1<n ){
207412    if( z[i]!='\\' ) return i;
207413    if( z[i+1]=='\n' ){
207414      i += 2;
207415      continue;
207416    }
207417    if( z[i+1]=='\r' ){
207418      if( i+2<n && z[i+2]=='\n' ){
207419        i += 3;
207420      }else{
207421        i += 2;
207422      }
207423      continue;
207424    }
207425    if( 0xe2==(u8)z[i+1]
207426     && i+3<n
207427     && 0x80==(u8)z[i+2]
207428     && (0xa8==(u8)z[i+3] || 0xa9==(u8)z[i+3])
207429    ){
207430      i += 4;
207431      continue;
207432    }
207433    break;
207434  }
207435  return i;
207436}
207437
207438/*
207439** Input z[0..n] defines JSON escape sequence including the leading '\\'.
207440** Decode that escape sequence into a single character.  Write that
207441** character into *piOut.  Return the number of bytes in the escape sequence.
207442**
207443** If there is a syntax error of some kind (for example too few characters
207444** after the '\\' to complete the encoding) then *piOut is set to
207445** JSON_INVALID_CHAR.
207446*/
207447static u32 jsonUnescapeOneChar(const char *z, u32 n, u32 *piOut){
207448  assert( n>0 );
207449  assert( z[0]=='\\' );
207450  if( n<2 ){
207451    *piOut = JSON_INVALID_CHAR;
207452    return n;
207453  }
207454  switch( (u8)z[1] ){
207455    case 'u': {
207456      u32 v, vlo;
207457      if( n<6 ){
207458        *piOut = JSON_INVALID_CHAR;
207459        return n;
207460      }
207461      v = jsonHexToInt4(&z[2]);
207462      if( (v & 0xfc00)==0xd800
207463       && n>=12
207464       && z[6]=='\\'
207465       && z[7]=='u'
207466       && ((vlo = jsonHexToInt4(&z[8]))&0xfc00)==0xdc00
207467      ){
207468        *piOut = ((v&0x3ff)<<10) + (vlo&0x3ff) + 0x10000;
207469        return 12;
207470      }else{
207471        *piOut = v;
207472        return 6;
207473      }
207474    }
207475    case 'b': {   *piOut = '\b';  return 2; }
207476    case 'f': {   *piOut = '\f';  return 2; }
207477    case 'n': {   *piOut = '\n';  return 2; }
207478    case 'r': {   *piOut = '\r';  return 2; }
207479    case 't': {   *piOut = '\t';  return 2; }
207480    case 'v': {   *piOut = '\v';  return 2; }
207481    case '0': {   *piOut = 0;     return 2; }
207482    case '\'':
207483    case '"':
207484    case '/':
207485    case '\\':{   *piOut = z[1];  return 2; }
207486    case 'x': {
207487      if( n<4 ){
207488        *piOut = JSON_INVALID_CHAR;
207489        return n;
207490      }
207491      *piOut = (jsonHexToInt(z[2])<<4) | jsonHexToInt(z[3]);
207492      return 4;
207493    }
207494    case 0xe2:
207495    case '\r':
207496    case '\n': {
207497      u32 nSkip = jsonBytesToBypass(z, n);
207498      if( nSkip==0 ){
207499        *piOut = JSON_INVALID_CHAR;
207500        return n;
207501      }else if( nSkip==n ){
207502        *piOut = 0;
207503        return n;
207504      }else if( z[nSkip]=='\\' ){
207505        return nSkip + jsonUnescapeOneChar(&z[nSkip], n-nSkip, piOut);
207506      }else{
207507        int sz = sqlite3Utf8ReadLimited((u8*)&z[nSkip], n-nSkip, piOut);
207508        return nSkip + sz;
207509      }
207510    }
207511    default: {
207512      *piOut = JSON_INVALID_CHAR;
207513      return 2;
207514    }
207515  }
207516}
207517
207518
207519/*
207520** Compare two object labels.  Return 1 if they are equal and
207521** 0 if they differ.
207522**
207523** In this version, we know that one or the other or both of the
207524** two comparands contains an escape sequence.
207525*/
207526static SQLITE_NOINLINE int jsonLabelCompareEscaped(
207527  const char *zLeft,          /* The left label */
207528  u32 nLeft,                  /* Size of the left label in bytes */
207529  int rawLeft,                /* True if zLeft contains no escapes */
207530  const char *zRight,         /* The right label */
207531  u32 nRight,                 /* Size of the right label in bytes */
207532  int rawRight                /* True if zRight is escape-free */
207533){
207534  u32 cLeft, cRight;
207535  assert( rawLeft==0 || rawRight==0 );
207536  while( 1 /*exit-by-return*/ ){
207537    if( nLeft==0 ){
207538      cLeft = 0;
207539    }else if( rawLeft || zLeft[0]!='\\' ){
207540      cLeft = ((u8*)zLeft)[0];
207541      if( cLeft>=0xc0 ){
207542        int sz = sqlite3Utf8ReadLimited((u8*)zLeft, nLeft, &cLeft);
207543        zLeft += sz;
207544        nLeft -= sz;
207545      }else{
207546        zLeft++;
207547        nLeft--;
207548      }
207549    }else{
207550      u32 n = jsonUnescapeOneChar(zLeft, nLeft, &cLeft);
207551      zLeft += n;
207552      assert( n<=nLeft );
207553      nLeft -= n;
207554    }
207555    if( nRight==0 ){
207556      cRight = 0;
207557    }else if( rawRight || zRight[0]!='\\' ){
207558      cRight = ((u8*)zRight)[0];
207559      if( cRight>=0xc0 ){
207560        int sz = sqlite3Utf8ReadLimited((u8*)zRight, nRight, &cRight);
207561        zRight += sz;
207562        nRight -= sz;
207563      }else{
207564        zRight++;
207565        nRight--;
207566      }
207567    }else{
207568      u32 n = jsonUnescapeOneChar(zRight, nRight, &cRight);
207569      zRight += n;
207570      assert( n<=nRight );
207571      nRight -= n;
207572    }
207573    if( cLeft!=cRight ) return 0;
207574    if( cLeft==0 ) return 1;
207575  }
207576}
207577
207578/*
207579** Compare two object labels.  Return 1 if they are equal and
207580** 0 if they differ.  Return -1 if an OOM occurs.
207581*/
207582static int jsonLabelCompare(
207583  const char *zLeft,          /* The left label */
207584  u32 nLeft,                  /* Size of the left label in bytes */
207585  int rawLeft,                /* True if zLeft contains no escapes */
207586  const char *zRight,         /* The right label */
207587  u32 nRight,                 /* Size of the right label in bytes */
207588  int rawRight                /* True if zRight is escape-free */
207589){
207590  if( rawLeft && rawRight ){
207591    /* Simpliest case:  Neither label contains escapes.  A simple
207592    ** memcmp() is sufficient. */
207593    if( nLeft!=nRight ) return 0;
207594    return memcmp(zLeft, zRight, nLeft)==0;
207595  }else{
207596    return jsonLabelCompareEscaped(zLeft, nLeft, rawLeft,
207597                                   zRight, nRight, rawRight);
207598  }
207599}
207600
207601/*
207602** Error returns from jsonLookupStep()
207603*/
207604#define JSON_LOOKUP_ERROR      0xffffffff
207605#define JSON_LOOKUP_NOTFOUND   0xfffffffe
207606#define JSON_LOOKUP_PATHERROR  0xfffffffd
207607#define JSON_LOOKUP_ISERROR(x) ((x)>=JSON_LOOKUP_PATHERROR)
207608
207609/* Forward declaration */
207610static u32 jsonLookupStep(JsonParse*,u32,const char*,u32);
207611
207612
207613/* This helper routine for jsonLookupStep() populates pIns with
207614** binary data that is to be inserted into pParse.
207615**
207616** In the common case, pIns just points to pParse->aIns and pParse->nIns.
207617** But if the zPath of the original edit operation includes path elements
207618** that go deeper, additional substructure must be created.
207619**
207620** For example:
207621**
207622**     json_insert('{}', '$.a.b.c', 123);
207623**
207624** The search stops at '$.a'  But additional substructure must be
207625** created for the ".b.c" part of the patch so that the final result
207626** is:  {"a":{"b":{"c"::123}}}.  This routine populates pIns with
207627** the binary equivalent of {"b":{"c":123}} so that it can be inserted.
207628**
207629** The caller is responsible for resetting pIns when it has finished
207630** using the substructure.
207631*/
207632static u32 jsonCreateEditSubstructure(
207633  JsonParse *pParse,  /* The original JSONB that is being edited */
207634  JsonParse *pIns,    /* Populate this with the blob data to insert */
207635  const char *zTail   /* Tail of the path that determins substructure */
207636){
207637  static const u8 emptyObject[] = { JSONB_ARRAY, JSONB_OBJECT };
207638  int rc;
207639  memset(pIns, 0, sizeof(*pIns));
207640  pIns->db = pParse->db;
207641  if( zTail[0]==0 ){
207642    /* No substructure.  Just insert what is given in pParse. */
207643    pIns->aBlob = pParse->aIns;
207644    pIns->nBlob = pParse->nIns;
207645    rc = 0;
207646  }else{
207647    /* Construct the binary substructure */
207648    pIns->nBlob = 1;
207649    pIns->aBlob = (u8*)&emptyObject[zTail[0]=='.'];
207650    pIns->eEdit = pParse->eEdit;
207651    pIns->nIns = pParse->nIns;
207652    pIns->aIns = pParse->aIns;
207653    rc = jsonLookupStep(pIns, 0, zTail, 0);
207654    pParse->oom |= pIns->oom;
207655  }
207656  return rc;  /* Error code only */
207657}
207658
207659/*
207660** Search along zPath to find the Json element specified.  Return an
207661** index into pParse->aBlob[] for the start of that element's value.
207662**
207663** If the value found by this routine is the value half of label/value pair
207664** within an object, then set pPath->iLabel to the start of the corresponding
207665** label, before returning.
207666**
207667** Return one of the JSON_LOOKUP error codes if problems are seen.
207668**
207669** This routine will also modify the blob.  If pParse->eEdit is one of
207670** JEDIT_DEL, JEDIT_REPL, JEDIT_INS, or JEDIT_SET, then changes might be
207671** made to the selected value.  If an edit is performed, then the return
207672** value does not necessarily point to the select element.  If an edit
207673** is performed, the return value is only useful for detecting error
207674** conditions.
207675*/
207676static u32 jsonLookupStep(
207677  JsonParse *pParse,      /* The JSON to search */
207678  u32 iRoot,              /* Begin the search at this element of aBlob[] */
207679  const char *zPath,      /* The path to search */
207680  u32 iLabel              /* Label if iRoot is a value of in an object */
207681){
207682  u32 i, j, k, nKey, sz, n, iEnd, rc;
207683  const char *zKey;
207684  u8 x;
207685
207686  if( zPath[0]==0 ){
207687    if( pParse->eEdit && jsonBlobMakeEditable(pParse, pParse->nIns) ){
207688      n = jsonbPayloadSize(pParse, iRoot, &sz);
207689      sz += n;
207690      if( pParse->eEdit==JEDIT_DEL ){
207691        if( iLabel>0 ){
207692          sz += iRoot - iLabel;
207693          iRoot = iLabel;
207694        }
207695        jsonBlobEdit(pParse, iRoot, sz, 0, 0);
207696      }else if( pParse->eEdit==JEDIT_INS ){
207697        /* Already exists, so json_insert() is a no-op */
207698      }else{
207699        /* json_set() or json_replace() */
207700        jsonBlobEdit(pParse, iRoot, sz, pParse->aIns, pParse->nIns);
207701      }
207702    }
207703    pParse->iLabel = iLabel;
207704    return iRoot;
207705  }
207706  if( zPath[0]=='.' ){
207707    int rawKey = 1;
207708    x = pParse->aBlob[iRoot];
207709    zPath++;
207710    if( zPath[0]=='"' ){
207711      zKey = zPath + 1;
207712      for(i=1; zPath[i] && zPath[i]!='"'; i++){}
207713      nKey = i-1;
207714      if( zPath[i] ){
207715        i++;
207716      }else{
207717        return JSON_LOOKUP_PATHERROR;
207718      }
207719      testcase( nKey==0 );
207720      rawKey = memchr(zKey, '\\', nKey)==0;
207721    }else{
207722      zKey = zPath;
207723      for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
207724      nKey = i;
207725      if( nKey==0 ){
207726        return JSON_LOOKUP_PATHERROR;
207727      }
207728    }
207729    if( (x & 0x0f)!=JSONB_OBJECT ) return JSON_LOOKUP_NOTFOUND;
207730    n = jsonbPayloadSize(pParse, iRoot, &sz);
207731    j = iRoot + n;  /* j is the index of a label */
207732    iEnd = j+sz;
207733    while( j<iEnd ){
207734      int rawLabel;
207735      const char *zLabel;
207736      x = pParse->aBlob[j] & 0x0f;
207737      if( x<JSONB_TEXT || x>JSONB_TEXTRAW ) return JSON_LOOKUP_ERROR;
207738      n = jsonbPayloadSize(pParse, j, &sz);
207739      if( n==0 ) return JSON_LOOKUP_ERROR;
207740      k = j+n;  /* k is the index of the label text */
207741      if( k+sz>=iEnd ) return JSON_LOOKUP_ERROR;
207742      zLabel = (const char*)&pParse->aBlob[k];
207743      rawLabel = x==JSONB_TEXT || x==JSONB_TEXTRAW;
207744      if( jsonLabelCompare(zKey, nKey, rawKey, zLabel, sz, rawLabel) ){
207745        u32 v = k+sz;  /* v is the index of the value */
207746        if( ((pParse->aBlob[v])&0x0f)>JSONB_OBJECT ) return JSON_LOOKUP_ERROR;
207747        n = jsonbPayloadSize(pParse, v, &sz);
207748        if( n==0 || v+n+sz>iEnd ) return JSON_LOOKUP_ERROR;
207749        assert( j>0 );
207750        rc = jsonLookupStep(pParse, v, &zPath[i], j);
207751        if( pParse->delta ) jsonAfterEditSizeAdjust(pParse, iRoot);
207752        return rc;
207753      }
207754      j = k+sz;
207755      if( ((pParse->aBlob[j])&0x0f)>JSONB_OBJECT ) return JSON_LOOKUP_ERROR;
207756      n = jsonbPayloadSize(pParse, j, &sz);
207757      if( n==0 ) return JSON_LOOKUP_ERROR;
207758      j += n+sz;
207759    }
207760    if( j>iEnd ) return JSON_LOOKUP_ERROR;
207761    if( pParse->eEdit>=JEDIT_INS ){
207762      u32 nIns;          /* Total bytes to insert (label+value) */
207763      JsonParse v;       /* BLOB encoding of the value to be inserted */
207764      JsonParse ix;      /* Header of the label to be inserted */
207765      testcase( pParse->eEdit==JEDIT_INS );
207766      testcase( pParse->eEdit==JEDIT_SET );
207767      memset(&ix, 0, sizeof(ix));
207768      ix.db = pParse->db;
207769      jsonBlobAppendNode(&ix, rawKey?JSONB_TEXTRAW:JSONB_TEXT5, nKey, 0);
207770      pParse->oom |= ix.oom;
207771      rc = jsonCreateEditSubstructure(pParse, &v, &zPath[i]);
207772      if( !JSON_LOOKUP_ISERROR(rc)
207773       && jsonBlobMakeEditable(pParse, ix.nBlob+nKey+v.nBlob)
207774      ){
207775        assert( !pParse->oom );
207776        nIns = ix.nBlob + nKey + v.nBlob;
207777        jsonBlobEdit(pParse, j, 0, 0, nIns);
207778        if( !pParse->oom ){
207779          assert( pParse->aBlob!=0 ); /* Because pParse->oom!=0 */
207780          assert( ix.aBlob!=0 );      /* Because pPasre->oom!=0 */
207781          memcpy(&pParse->aBlob[j], ix.aBlob, ix.nBlob);
207782          k = j + ix.nBlob;
207783          memcpy(&pParse->aBlob[k], zKey, nKey);
207784          k += nKey;
207785          memcpy(&pParse->aBlob[k], v.aBlob, v.nBlob);
207786          if( ALWAYS(pParse->delta) ) jsonAfterEditSizeAdjust(pParse, iRoot);
207787        }
207788      }
207789      jsonParseReset(&v);
207790      jsonParseReset(&ix);
207791      return rc;
207792    }
207793  }else if( zPath[0]=='[' ){
207794    x = pParse->aBlob[iRoot] & 0x0f;
207795    if( x!=JSONB_ARRAY )  return JSON_LOOKUP_NOTFOUND;
207796    n = jsonbPayloadSize(pParse, iRoot, &sz);
207797    k = 0;
207798    i = 1;
207799    while( sqlite3Isdigit(zPath[i]) ){
207800      k = k*10 + zPath[i] - '0';
207801      i++;
207802    }
207803    if( i<2 || zPath[i]!=']' ){
207804      if( zPath[1]=='#' ){
207805        k = jsonbArrayCount(pParse, iRoot);
207806        i = 2;
207807        if( zPath[2]=='-' && sqlite3Isdigit(zPath[3]) ){
207808          unsigned int nn = 0;
207809          i = 3;
207810          do{
207811            nn = nn*10 + zPath[i] - '0';
207812            i++;
207813          }while( sqlite3Isdigit(zPath[i]) );
207814          if( nn>k ) return JSON_LOOKUP_NOTFOUND;
207815          k -= nn;
207816        }
207817        if( zPath[i]!=']' ){
207818          return JSON_LOOKUP_PATHERROR;
207819        }
207820      }else{
207821        return JSON_LOOKUP_PATHERROR;
207822      }
207823    }
207824    j = iRoot+n;
207825    iEnd = j+sz;
207826    while( j<iEnd ){
207827      if( k==0 ){
207828        rc = jsonLookupStep(pParse, j, &zPath[i+1], 0);
207829        if( pParse->delta ) jsonAfterEditSizeAdjust(pParse, iRoot);
207830        return rc;
207831      }
207832      k--;
207833      n = jsonbPayloadSize(pParse, j, &sz);
207834      if( n==0 ) return JSON_LOOKUP_ERROR;
207835      j += n+sz;
207836    }
207837    if( j>iEnd ) return JSON_LOOKUP_ERROR;
207838    if( k>0 ) return JSON_LOOKUP_NOTFOUND;
207839    if( pParse->eEdit>=JEDIT_INS ){
207840      JsonParse v;
207841      testcase( pParse->eEdit==JEDIT_INS );
207842      testcase( pParse->eEdit==JEDIT_SET );
207843      rc = jsonCreateEditSubstructure(pParse, &v, &zPath[i+1]);
207844      if( !JSON_LOOKUP_ISERROR(rc)
207845       && jsonBlobMakeEditable(pParse, v.nBlob)
207846      ){
207847        assert( !pParse->oom );
207848        jsonBlobEdit(pParse, j, 0, v.aBlob, v.nBlob);
207849      }
207850      jsonParseReset(&v);
207851      if( pParse->delta ) jsonAfterEditSizeAdjust(pParse, iRoot);
207852      return rc;
207853    }
207854  }else{
207855    return JSON_LOOKUP_PATHERROR;
207856  }
207857  return JSON_LOOKUP_NOTFOUND;
207858}
207859
207860/*
207861** Convert a JSON BLOB into text and make that text the return value
207862** of an SQL function.
207863*/
207864static void jsonReturnTextJsonFromBlob(
207865  sqlite3_context *ctx,
207866  const u8 *aBlob,
207867  u32 nBlob
207868){
207869  JsonParse x;
207870  JsonString s;
207871
207872  if( NEVER(aBlob==0) ) return;
207873  memset(&x, 0, sizeof(x));
207874  x.aBlob = (u8*)aBlob;
207875  x.nBlob = nBlob;
207876  jsonStringInit(&s, ctx);
207877  jsonTranslateBlobToText(&x, 0, &s);
207878  jsonReturnString(&s, 0, 0);
207879}
207880
207881
207882/*
207883** Return the value of the BLOB node at index i.
207884**
207885** If the value is a primitive, return it as an SQL value.
207886** If the value is an array or object, return it as either
207887** JSON text or the BLOB encoding, depending on the JSON_B flag
207888** on the userdata.
207889*/
207890static void jsonReturnFromBlob(
207891  JsonParse *pParse,          /* Complete JSON parse tree */
207892  u32 i,                      /* Index of the node */
207893  sqlite3_context *pCtx,      /* Return value for this function */
207894  int textOnly                /* return text JSON.  Disregard user-data */
207895){
207896  u32 n, sz;
207897  int rc;
207898  sqlite3 *db = sqlite3_context_db_handle(pCtx);
207899
207900  n = jsonbPayloadSize(pParse, i, &sz);
207901  if( n==0 ){
207902    sqlite3_result_error(pCtx, "malformed JSON", -1);
207903    return;
207904  }
207905  switch( pParse->aBlob[i] & 0x0f ){
207906    case JSONB_NULL: {
207907      if( sz ) goto returnfromblob_malformed;
207908      sqlite3_result_null(pCtx);
207909      break;
207910    }
207911    case JSONB_TRUE: {
207912      if( sz ) goto returnfromblob_malformed;
207913      sqlite3_result_int(pCtx, 1);
207914      break;
207915    }
207916    case JSONB_FALSE: {
207917      if( sz ) goto returnfromblob_malformed;
207918      sqlite3_result_int(pCtx, 0);
207919      break;
207920    }
207921    case JSONB_INT5:
207922    case JSONB_INT: {
207923      sqlite3_int64 iRes = 0;
207924      char *z;
207925      int bNeg = 0;
207926      char x;
207927      if( sz==0 ) goto returnfromblob_malformed;
207928      x = (char)pParse->aBlob[i+n];
207929      if( x=='-' ){
207930        if( sz<2 ) goto returnfromblob_malformed;
207931        n++;
207932        sz--;
207933        bNeg = 1;
207934      }
207935      z = sqlite3DbStrNDup(db, (const char*)&pParse->aBlob[i+n], (int)sz);
207936      if( z==0 ) goto returnfromblob_oom;
207937      rc = sqlite3DecOrHexToI64(z, &iRes);
207938      sqlite3DbFree(db, z);
207939      if( rc==0 ){
207940        sqlite3_result_int64(pCtx, bNeg ? -iRes : iRes);
207941      }else if( rc==3 && bNeg ){
207942        sqlite3_result_int64(pCtx, SMALLEST_INT64);
207943      }else if( rc==1 ){
207944        goto returnfromblob_malformed;
207945      }else{
207946        if( bNeg ){ n--; sz++; }
207947        goto to_double;
207948      }
207949      break;
207950    }
207951    case JSONB_FLOAT5:
207952    case JSONB_FLOAT: {
207953      double r;
207954      char *z;
207955      if( sz==0 ) goto returnfromblob_malformed;
207956    to_double:
207957      z = sqlite3DbStrNDup(db, (const char*)&pParse->aBlob[i+n], (int)sz);
207958      if( z==0 ) goto returnfromblob_oom;
207959      rc = sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
207960      sqlite3DbFree(db, z);
207961      if( rc<=0 ) goto returnfromblob_malformed;
207962      sqlite3_result_double(pCtx, r);
207963      break;
207964    }
207965    case JSONB_TEXTRAW:
207966    case JSONB_TEXT: {
207967      sqlite3_result_text(pCtx, (char*)&pParse->aBlob[i+n], sz,
207968                          SQLITE_TRANSIENT);
207969      break;
207970    }
207971    case JSONB_TEXT5:
207972    case JSONB_TEXTJ: {
207973      /* Translate JSON formatted string into raw text */
207974      u32 iIn, iOut;
207975      const char *z;
207976      char *zOut;
207977      u32 nOut = sz;
207978      z = (const char*)&pParse->aBlob[i+n];
207979      zOut = sqlite3DbMallocRaw(db, nOut+1);
207980      if( zOut==0 ) goto returnfromblob_oom;
207981      for(iIn=iOut=0; iIn<sz; iIn++){
207982        char c = z[iIn];
207983        if( c=='\\' ){
207984          u32 v;
207985          u32 szEscape = jsonUnescapeOneChar(&z[iIn], sz-iIn, &v);
207986          if( v<=0x7f ){
207987            zOut[iOut++] = (char)v;
207988          }else if( v<=0x7ff ){
207989            assert( szEscape>=2 );
207990            zOut[iOut++] = (char)(0xc0 | (v>>6));
207991            zOut[iOut++] = 0x80 | (v&0x3f);
207992          }else if( v<0x10000 ){
207993            assert( szEscape>=3 );
207994            zOut[iOut++] = 0xe0 | (v>>12);
207995            zOut[iOut++] = 0x80 | ((v>>6)&0x3f);
207996            zOut[iOut++] = 0x80 | (v&0x3f);
207997          }else if( v==JSON_INVALID_CHAR ){
207998            /* Silently ignore illegal unicode */
207999          }else{
208000            assert( szEscape>=4 );
208001            zOut[iOut++] = 0xf0 | (v>>18);
208002            zOut[iOut++] = 0x80 | ((v>>12)&0x3f);
208003            zOut[iOut++] = 0x80 | ((v>>6)&0x3f);
208004            zOut[iOut++] = 0x80 | (v&0x3f);
208005          }
208006          iIn += szEscape - 1;
208007        }else{
208008          zOut[iOut++] = c;
208009        }
208010      } /* end for() */
208011      assert( iOut<=nOut );
208012      zOut[iOut] = 0;
208013      sqlite3_result_text(pCtx, zOut, iOut, SQLITE_DYNAMIC);
208014      break;
208015    }
208016    case JSONB_ARRAY:
208017    case JSONB_OBJECT: {
208018      int flags = textOnly ? 0 : SQLITE_PTR_TO_INT(sqlite3_user_data(pCtx));
208019      if( flags & JSON_BLOB ){
208020        sqlite3_result_blob(pCtx, &pParse->aBlob[i], sz+n, SQLITE_TRANSIENT);
208021      }else{
208022        jsonReturnTextJsonFromBlob(pCtx, &pParse->aBlob[i], sz+n);
208023      }
208024      break;
208025    }
208026    default: {
208027      goto returnfromblob_malformed;
208028    }
208029  }
208030  return;
208031
208032returnfromblob_oom:
208033  sqlite3_result_error_nomem(pCtx);
208034  return;
208035
208036returnfromblob_malformed:
208037  sqlite3_result_error(pCtx, "malformed JSON", -1);
208038  return;
208039}
208040
208041/*
208042** pArg is a function argument that might be an SQL value or a JSON
208043** value.  Figure out what it is and encode it as a JSONB blob.
208044** Return the results in pParse.
208045**
208046** pParse is uninitialized upon entry.  This routine will handle the
208047** initialization of pParse.  The result will be contained in
208048** pParse->aBlob and pParse->nBlob.  pParse->aBlob might be dynamically
208049** allocated (if pParse->nBlobAlloc is greater than zero) in which case
208050** the caller is responsible for freeing the space allocated to pParse->aBlob
208051** when it has finished with it.  Or pParse->aBlob might be a static string
208052** or a value obtained from sqlite3_value_blob(pArg).
208053**
208054** If the argument is a BLOB that is clearly not a JSONB, then this
208055** function might set an error message in ctx and return non-zero.
208056** It might also set an error message and return non-zero on an OOM error.
208057*/
208058static int jsonFunctionArgToBlob(
208059  sqlite3_context *ctx,
208060  sqlite3_value *pArg,
208061  JsonParse *pParse
208062){
208063  int eType = sqlite3_value_type(pArg);
208064  static u8 aNull[] = { 0x00 };
208065  memset(pParse, 0, sizeof(pParse[0]));
208066  pParse->db = sqlite3_context_db_handle(ctx);
208067  switch( eType ){
208068    default: {
208069      pParse->aBlob = aNull;
208070      pParse->nBlob = 1;
208071      return 0;
208072    }
208073    case SQLITE_BLOB: {
208074      if( jsonFuncArgMightBeBinary(pArg) ){
208075        pParse->aBlob = (u8*)sqlite3_value_blob(pArg);
208076        pParse->nBlob = sqlite3_value_bytes(pArg);
208077      }else{
208078        sqlite3_result_error(ctx, "JSON cannot hold BLOB values", -1);
208079        return 1;
208080      }
208081      break;
208082    }
208083    case SQLITE_TEXT: {
208084      const char *zJson = (const char*)sqlite3_value_text(pArg);
208085      int nJson = sqlite3_value_bytes(pArg);
208086      if( zJson==0 ) return 1;
208087      if( sqlite3_value_subtype(pArg)==JSON_SUBTYPE ){
208088        pParse->zJson = (char*)zJson;
208089        pParse->nJson = nJson;
208090        if( jsonConvertTextToBlob(pParse, ctx) ){
208091          sqlite3_result_error(ctx, "malformed JSON", -1);
208092          sqlite3DbFree(pParse->db, pParse->aBlob);
208093          memset(pParse, 0, sizeof(pParse[0]));
208094          return 1;
208095        }
208096      }else{
208097        jsonBlobAppendNode(pParse, JSONB_TEXTRAW, nJson, zJson);
208098      }
208099      break;
208100    }
208101    case SQLITE_FLOAT: {
208102      double r = sqlite3_value_double(pArg);
208103      if( NEVER(sqlite3IsNaN(r)) ){
208104        jsonBlobAppendNode(pParse, JSONB_NULL, 0, 0);
208105      }else{
208106        int n = sqlite3_value_bytes(pArg);
208107        const char *z = (const char*)sqlite3_value_text(pArg);
208108        if( z==0 ) return 1;
208109        if( z[0]=='I' ){
208110          jsonBlobAppendNode(pParse, JSONB_FLOAT, 5, "9e999");
208111        }else if( z[0]=='-' && z[1]=='I' ){
208112          jsonBlobAppendNode(pParse, JSONB_FLOAT, 6, "-9e999");
208113        }else{
208114          jsonBlobAppendNode(pParse, JSONB_FLOAT, n, z);
208115        }
208116      }
208117      break;
208118    }
208119    case SQLITE_INTEGER: {
208120      int n = sqlite3_value_bytes(pArg);
208121      const char *z = (const char*)sqlite3_value_text(pArg);
208122      if( z==0 ) return 1;
208123      jsonBlobAppendNode(pParse, JSONB_INT, n, z);
208124      break;
208125    }
208126  }
208127  if( pParse->oom ){
208128    sqlite3_result_error_nomem(ctx);
208129    return 1;
208130  }else{
208131    return 0;
208132  }
208133}
208134
208135/*
208136** Generate a bad path error.
208137**
208138** If ctx is not NULL then push the error message into ctx and return NULL.
208139** If ctx is NULL, then return the text of the error message.
208140*/
208141static char *jsonBadPathError(
208142  sqlite3_context *ctx,     /* The function call containing the error */
208143  const char *zPath         /* The path with the problem */
208144){
208145  char *zMsg = sqlite3_mprintf("bad JSON path: %Q", zPath);
208146  if( ctx==0 ) return zMsg;
208147  if( zMsg ){
208148    sqlite3_result_error(ctx, zMsg, -1);
208149    sqlite3_free(zMsg);
208150  }else{
208151    sqlite3_result_error_nomem(ctx);
208152  }
208153  return 0;
208154}
208155
208156/* argv[0] is a BLOB that seems likely to be a JSONB.  Subsequent
208157** arguments come in parse where each pair contains a JSON path and
208158** content to insert or set at that patch.  Do the updates
208159** and return the result.
208160**
208161** The specific operation is determined by eEdit, which can be one
208162** of JEDIT_INS, JEDIT_REPL, or JEDIT_SET.
208163*/
208164static void jsonInsertIntoBlob(
208165  sqlite3_context *ctx,
208166  int argc,
208167  sqlite3_value **argv,
208168  int eEdit                /* JEDIT_INS, JEDIT_REPL, or JEDIT_SET */
208169){
208170  int i;
208171  u32 rc = 0;
208172  const char *zPath = 0;
208173  int flgs;
208174  JsonParse *p;
208175  JsonParse ax;
208176
208177  assert( (argc&1)==1 );
208178  flgs = argc==1 ? 0 : JSON_EDITABLE;
208179  p = jsonParseFuncArg(ctx, argv[0], flgs);
208180  if( p==0 ) return;
208181  for(i=1; i<argc-1; i+=2){
208182    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) continue;
208183    zPath = (const char*)sqlite3_value_text(argv[i]);
208184    if( zPath==0 ){
208185      sqlite3_result_error_nomem(ctx);
208186      jsonParseFree(p);
208187      return;
208188    }
208189    if( zPath[0]!='$' ) goto jsonInsertIntoBlob_patherror;
208190    if( jsonFunctionArgToBlob(ctx, argv[i+1], &ax) ){
208191      jsonParseReset(&ax);
208192      jsonParseFree(p);
208193      return;
208194    }
208195    if( zPath[1]==0 ){
208196      if( eEdit==JEDIT_REPL || eEdit==JEDIT_SET ){
208197        jsonBlobEdit(p, 0, p->nBlob, ax.aBlob, ax.nBlob);
208198      }
208199      rc = 0;
208200   }else{
208201      p->eEdit = eEdit;
208202      p->nIns = ax.nBlob;
208203      p->aIns = ax.aBlob;
208204      p->delta = 0;
208205      rc = jsonLookupStep(p, 0, zPath+1, 0);
208206    }
208207    jsonParseReset(&ax);
208208    if( rc==JSON_LOOKUP_NOTFOUND ) continue;
208209    if( JSON_LOOKUP_ISERROR(rc) ) goto jsonInsertIntoBlob_patherror;
208210  }
208211  jsonReturnParse(ctx, p);
208212  jsonParseFree(p);
208213  return;
208214
208215jsonInsertIntoBlob_patherror:
208216  jsonParseFree(p);
208217  if( rc==JSON_LOOKUP_ERROR ){
208218    sqlite3_result_error(ctx, "malformed JSON", -1);
208219  }else{
208220    jsonBadPathError(ctx, zPath);
208221  }
208222  return;
208223}
208224
208225/*
208226** If pArg is a blob that seems like a JSONB blob, then initialize
208227** p to point to that JSONB and return TRUE.  If pArg does not seem like
208228** a JSONB blob, then return FALSE;
208229**
208230** This routine is only called if it is already known that pArg is a
208231** blob.  The only open question is whether or not the blob appears
208232** to be a JSONB blob.
208233*/
208234static int jsonArgIsJsonb(sqlite3_value *pArg, JsonParse *p){
208235  u32 n, sz = 0;
208236  p->aBlob = (u8*)sqlite3_value_blob(pArg);
208237  p->nBlob = (u32)sqlite3_value_bytes(pArg);
208238  if( p->nBlob==0 ){
208239    p->aBlob = 0;
208240    return 0;
208241  }
208242  if( NEVER(p->aBlob==0) ){
208243    return 0;
208244  }
208245  if( (p->aBlob[0] & 0x0f)<=JSONB_OBJECT
208246   && (n = jsonbPayloadSize(p, 0, &sz))>0
208247   && sz+n==p->nBlob
208248   && ((p->aBlob[0] & 0x0f)>JSONB_FALSE || sz==0)
208249  ){
208250    return 1;
208251  }
208252  p->aBlob = 0;
208253  p->nBlob = 0;
208254  return 0;
208255}
208256
208257/*
208258** Generate a JsonParse object, containing valid JSONB in aBlob and nBlob,
208259** from the SQL function argument pArg.  Return a pointer to the new
208260** JsonParse object.
208261**
208262** Ownership of the new JsonParse object is passed to the caller.  The
208263** caller should invoke jsonParseFree() on the return value when it
208264** has finished using it.
208265**
208266** If any errors are detected, an appropriate error messages is set
208267** using sqlite3_result_error() or the equivalent and this routine
208268** returns NULL.  This routine also returns NULL if the pArg argument
208269** is an SQL NULL value, but no error message is set in that case.  This
208270** is so that SQL functions that are given NULL arguments will return
208271** a NULL value.
208272*/
208273static JsonParse *jsonParseFuncArg(
208274  sqlite3_context *ctx,
208275  sqlite3_value *pArg,
208276  u32 flgs
208277){
208278  int eType;                   /* Datatype of pArg */
208279  JsonParse *p = 0;            /* Value to be returned */
208280  JsonParse *pFromCache = 0;   /* Value taken from cache */
208281  sqlite3 *db;                 /* The database connection */
208282
208283  assert( ctx!=0 );
208284  eType = sqlite3_value_type(pArg);
208285  if( eType==SQLITE_NULL ){
208286    return 0;
208287  }
208288  pFromCache = jsonCacheSearch(ctx, pArg);
208289  if( pFromCache ){
208290    pFromCache->nJPRef++;
208291    if( (flgs & JSON_EDITABLE)==0 ){
208292      return pFromCache;
208293    }
208294  }
208295  db = sqlite3_context_db_handle(ctx);
208296rebuild_from_cache:
208297  p = sqlite3DbMallocZero(db, sizeof(*p));
208298  if( p==0 ) goto json_pfa_oom;
208299  memset(p, 0, sizeof(*p));
208300  p->db = db;
208301  p->nJPRef = 1;
208302  if( pFromCache!=0 ){
208303    u32 nBlob = pFromCache->nBlob;
208304    p->aBlob = sqlite3DbMallocRaw(db, nBlob);
208305    if( p->aBlob==0 ) goto json_pfa_oom;
208306    memcpy(p->aBlob, pFromCache->aBlob, nBlob);
208307    p->nBlobAlloc = p->nBlob = nBlob;
208308    p->hasNonstd = pFromCache->hasNonstd;
208309    jsonParseFree(pFromCache);
208310    return p;
208311  }
208312  if( eType==SQLITE_BLOB ){
208313    if( jsonArgIsJsonb(pArg,p) ){
208314      if( (flgs & JSON_EDITABLE)!=0 && jsonBlobMakeEditable(p, 0)==0 ){
208315        goto json_pfa_oom;
208316      }
208317      return p;
208318    }
208319    /* If the blob is not valid JSONB, fall through into trying to cast
208320    ** the blob into text which is then interpreted as JSON.  (tag-20240123-a)
208321    **
208322    ** This goes against all historical documentation about how the SQLite
208323    ** JSON functions were suppose to work.  From the beginning, blob was
208324    ** reserved for expansion and a blob value should have raised an error.
208325    ** But it did not, due to a bug.  And many applications came to depend
208326    ** upon this buggy behavior, espeically when using the CLI and reading
208327    ** JSON text using readfile(), which returns a blob.  For this reason
208328    ** we will continue to support the bug moving forward.
208329    ** See for example https://sqlite.org/forum/forumpost/012136abd5292b8d
208330    */
208331  }
208332  p->zJson = (char*)sqlite3_value_text(pArg);
208333  p->nJson = sqlite3_value_bytes(pArg);
208334  if( db->mallocFailed ) goto json_pfa_oom;
208335  if( p->nJson==0 ) goto json_pfa_malformed;
208336  assert( p->zJson!=0 );
208337  if( jsonConvertTextToBlob(p, (flgs & JSON_KEEPERROR) ? 0 : ctx) ){
208338    if( flgs & JSON_KEEPERROR ){
208339      p->nErr = 1;
208340      return p;
208341    }else{
208342      jsonParseFree(p);
208343      return 0;
208344    }
208345  }else{
208346    int isRCStr = sqlite3ValueIsOfClass(pArg, sqlite3RCStrUnref);
208347    int rc;
208348    if( !isRCStr ){
208349      char *zNew = sqlite3RCStrNew( p->nJson );
208350      if( zNew==0 ) goto json_pfa_oom;
208351      memcpy(zNew, p->zJson, p->nJson);
208352      p->zJson = zNew;
208353      p->zJson[p->nJson] = 0;
208354    }else{
208355      sqlite3RCStrRef(p->zJson);
208356    }
208357    p->bJsonIsRCStr = 1;
208358    rc = jsonCacheInsert(ctx, p);
208359    if( rc==SQLITE_NOMEM ) goto json_pfa_oom;
208360    if( flgs & JSON_EDITABLE ){
208361      pFromCache = p;
208362      p = 0;
208363      goto rebuild_from_cache;
208364    }
208365  }
208366  return p;
208367
208368json_pfa_malformed:
208369  if( flgs & JSON_KEEPERROR ){
208370    p->nErr = 1;
208371    return p;
208372  }else{
208373    jsonParseFree(p);
208374    sqlite3_result_error(ctx, "malformed JSON", -1);
208375    return 0;
208376  }
208377
208378json_pfa_oom:
208379  jsonParseFree(pFromCache);
208380  jsonParseFree(p);
208381  sqlite3_result_error_nomem(ctx);
208382  return 0;
208383}
208384
208385/*
208386** Make the return value of a JSON function either the raw JSONB blob
208387** or make it JSON text, depending on whether the JSON_BLOB flag is
208388** set on the function.
208389*/
208390static void jsonReturnParse(
208391  sqlite3_context *ctx,
208392  JsonParse *p
208393){
208394  int flgs;
208395  if( p->oom ){
208396    sqlite3_result_error_nomem(ctx);
208397    return;
208398  }
208399  flgs = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx));
208400  if( flgs & JSON_BLOB ){
208401    if( p->nBlobAlloc>0 && !p->bReadOnly ){
208402      sqlite3_result_blob(ctx, p->aBlob, p->nBlob, SQLITE_DYNAMIC);
208403      p->nBlobAlloc = 0;
208404    }else{
208405      sqlite3_result_blob(ctx, p->aBlob, p->nBlob, SQLITE_TRANSIENT);
208406    }
208407  }else{
208408    JsonString s;
208409    jsonStringInit(&s, ctx);
208410    p->delta = 0;
208411    jsonTranslateBlobToText(p, 0, &s);
208412    jsonReturnString(&s, p, ctx);
208413    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
208414  }
208415}
208416
208417/****************************************************************************
208418** SQL functions used for testing and debugging
208419****************************************************************************/
208420
208421#if SQLITE_DEBUG
208422/*
208423** Decode JSONB bytes in aBlob[] starting at iStart through but not
208424** including iEnd.  Indent the
208425** content by nIndent spaces.
208426*/
208427static void jsonDebugPrintBlob(
208428  JsonParse *pParse, /* JSON content */
208429  u32 iStart,        /* Start rendering here */
208430  u32 iEnd,          /* Do not render this byte or any byte after this one */
208431  int nIndent,       /* Indent by this many spaces */
208432  sqlite3_str *pOut  /* Generate output into this sqlite3_str object */
208433){
208434  while( iStart<iEnd ){
208435    u32 i, n, nn, sz = 0;
208436    int showContent = 1;
208437    u8 x = pParse->aBlob[iStart] & 0x0f;
208438    u32 savedNBlob = pParse->nBlob;
208439    sqlite3_str_appendf(pOut, "%5d:%*s", iStart, nIndent, "");
208440    if( pParse->nBlobAlloc>pParse->nBlob ){
208441      pParse->nBlob = pParse->nBlobAlloc;
208442    }
208443    nn = n = jsonbPayloadSize(pParse, iStart, &sz);
208444    if( nn==0 ) nn = 1;
208445    if( sz>0 && x<JSONB_ARRAY ){
208446      nn += sz;
208447    }
208448    for(i=0; i<nn; i++){
208449      sqlite3_str_appendf(pOut, " %02x", pParse->aBlob[iStart+i]);
208450    }
208451    if( n==0 ){
208452      sqlite3_str_appendf(pOut, "   ERROR invalid node size\n");
208453      iStart = n==0 ? iStart+1 : iEnd;
208454      continue;
208455    }
208456    pParse->nBlob = savedNBlob;
208457    if( iStart+n+sz>iEnd ){
208458      iEnd = iStart+n+sz;
208459      if( iEnd>pParse->nBlob ){
208460        if( pParse->nBlobAlloc>0 && iEnd>pParse->nBlobAlloc ){
208461          iEnd = pParse->nBlobAlloc;
208462        }else{
208463          iEnd = pParse->nBlob;
208464        }
208465      }
208466    }
208467    sqlite3_str_appendall(pOut,"  <-- ");
208468    switch( x ){
208469      case JSONB_NULL:     sqlite3_str_appendall(pOut,"null"); break;
208470      case JSONB_TRUE:     sqlite3_str_appendall(pOut,"true"); break;
208471      case JSONB_FALSE:    sqlite3_str_appendall(pOut,"false"); break;
208472      case JSONB_INT:      sqlite3_str_appendall(pOut,"int"); break;
208473      case JSONB_INT5:     sqlite3_str_appendall(pOut,"int5"); break;
208474      case JSONB_FLOAT:    sqlite3_str_appendall(pOut,"float"); break;
208475      case JSONB_FLOAT5:   sqlite3_str_appendall(pOut,"float5"); break;
208476      case JSONB_TEXT:     sqlite3_str_appendall(pOut,"text"); break;
208477      case JSONB_TEXTJ:    sqlite3_str_appendall(pOut,"textj"); break;
208478      case JSONB_TEXT5:    sqlite3_str_appendall(pOut,"text5"); break;
208479      case JSONB_TEXTRAW:  sqlite3_str_appendall(pOut,"textraw"); break;
208480      case JSONB_ARRAY: {
208481        sqlite3_str_appendf(pOut,"array, %u bytes\n", sz);
208482        jsonDebugPrintBlob(pParse, iStart+n, iStart+n+sz, nIndent+2, pOut);
208483        showContent = 0;
208484        break;
208485      }
208486      case JSONB_OBJECT: {
208487        sqlite3_str_appendf(pOut, "object, %u bytes\n", sz);
208488        jsonDebugPrintBlob(pParse, iStart+n, iStart+n+sz, nIndent+2, pOut);
208489        showContent = 0;
208490        break;
208491      }
208492      default: {
208493        sqlite3_str_appendall(pOut, "ERROR: unknown node type\n");
208494        showContent = 0;
208495        break;
208496      }
208497    }
208498    if( showContent ){
208499      if( sz==0 && x<=JSONB_FALSE ){
208500        sqlite3_str_append(pOut, "\n", 1);
208501      }else{
208502        u32 j;
208503        sqlite3_str_appendall(pOut, ": \"");
208504        for(j=iStart+n; j<iStart+n+sz; j++){
208505          u8 c = pParse->aBlob[j];
208506          if( c<0x20 || c>=0x7f ) c = '.';
208507          sqlite3_str_append(pOut, (char*)&c, 1);
208508        }
208509        sqlite3_str_append(pOut, "\"\n", 2);
208510      }
208511    }
208512    iStart += n + sz;
208513  }
208514}
208515static void jsonShowParse(JsonParse *pParse){
208516  sqlite3_str out;
208517  char zBuf[1000];
208518  if( pParse==0 ){
208519    printf("NULL pointer\n");
208520    return;
208521  }else{
208522    printf("nBlobAlloc = %u\n", pParse->nBlobAlloc);
208523    printf("nBlob = %u\n", pParse->nBlob);
208524    printf("delta = %d\n", pParse->delta);
208525    if( pParse->nBlob==0 ) return;
208526    printf("content (bytes 0..%u):\n", pParse->nBlob-1);
208527  }
208528  sqlite3StrAccumInit(&out, 0, zBuf, sizeof(zBuf), 1000000);
208529  jsonDebugPrintBlob(pParse, 0, pParse->nBlob, 0, &out);
208530  printf("%s", sqlite3_str_value(&out));
208531  sqlite3_str_reset(&out);
208532}
208533#endif /* SQLITE_DEBUG */
208534
208535#ifdef SQLITE_DEBUG
208536/*
208537** SQL function:   json_parse(JSON)
208538**
208539** Parse JSON using jsonParseFuncArg().  Return text that is a
208540** human-readable dump of the binary JSONB for the input parameter.
208541*/
208542static void jsonParseFunc(
208543  sqlite3_context *ctx,
208544  int argc,
208545  sqlite3_value **argv
208546){
208547  JsonParse *p;        /* The parse */
208548  sqlite3_str out;
208549
208550  assert( argc>=1 );
208551  sqlite3StrAccumInit(&out, 0, 0, 0, 1000000);
208552  p = jsonParseFuncArg(ctx, argv[0], 0);
208553  if( p==0 ) return;
208554  if( argc==1 ){
208555    jsonDebugPrintBlob(p, 0, p->nBlob, 0, &out);
208556    sqlite3_result_text64(ctx,out.zText,out.nChar,SQLITE_TRANSIENT,SQLITE_UTF8);
208557  }else{
208558    jsonShowParse(p);
208559  }
208560  jsonParseFree(p);
208561  sqlite3_str_reset(&out);
208562}
208563#endif /* SQLITE_DEBUG */
208564
208565/****************************************************************************
208566** Scalar SQL function implementations
208567****************************************************************************/
208568
208569/*
208570** Implementation of the json_quote(VALUE) function.  Return a JSON value
208571** corresponding to the SQL value input.  Mostly this means putting
208572** double-quotes around strings and returning the unquoted string "null"
208573** when given a NULL input.
208574*/
208575static void jsonQuoteFunc(
208576  sqlite3_context *ctx,
208577  int argc,
208578  sqlite3_value **argv
208579){
208580  JsonString jx;
208581  UNUSED_PARAMETER(argc);
208582
208583  jsonStringInit(&jx, ctx);
208584  jsonAppendSqlValue(&jx, argv[0]);
208585  jsonReturnString(&jx, 0, 0);
208586  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
208587}
208588
208589/*
208590** Implementation of the json_array(VALUE,...) function.  Return a JSON
208591** array that contains all values given in arguments.  Or if any argument
208592** is a BLOB, throw an error.
208593*/
208594static void jsonArrayFunc(
208595  sqlite3_context *ctx,
208596  int argc,
208597  sqlite3_value **argv
208598){
208599  int i;
208600  JsonString jx;
208601
208602  jsonStringInit(&jx, ctx);
208603  jsonAppendChar(&jx, '[');
208604  for(i=0; i<argc; i++){
208605    jsonAppendSeparator(&jx);
208606    jsonAppendSqlValue(&jx, argv[i]);
208607  }
208608  jsonAppendChar(&jx, ']');
208609  jsonReturnString(&jx, 0, 0);
208610  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
208611}
208612
208613/*
208614** json_array_length(JSON)
208615** json_array_length(JSON, PATH)
208616**
208617** Return the number of elements in the top-level JSON array.
208618** Return 0 if the input is not a well-formed JSON array.
208619*/
208620static void jsonArrayLengthFunc(
208621  sqlite3_context *ctx,
208622  int argc,
208623  sqlite3_value **argv
208624){
208625  JsonParse *p;          /* The parse */
208626  sqlite3_int64 cnt = 0;
208627  u32 i;
208628  u8 eErr = 0;
208629
208630  p = jsonParseFuncArg(ctx, argv[0], 0);
208631  if( p==0 ) return;
208632  if( argc==2 ){
208633    const char *zPath = (const char*)sqlite3_value_text(argv[1]);
208634    if( zPath==0 ){
208635      jsonParseFree(p);
208636      return;
208637    }
208638    i = jsonLookupStep(p, 0, zPath[0]=='$' ? zPath+1 : "@", 0);
208639    if( JSON_LOOKUP_ISERROR(i) ){
208640      if( i==JSON_LOOKUP_NOTFOUND ){
208641        /* no-op */
208642      }else if( i==JSON_LOOKUP_PATHERROR ){
208643        jsonBadPathError(ctx, zPath);
208644      }else{
208645        sqlite3_result_error(ctx, "malformed JSON", -1);
208646      }
208647      eErr = 1;
208648      i = 0;
208649    }
208650  }else{
208651    i = 0;
208652  }
208653  if( (p->aBlob[i] & 0x0f)==JSONB_ARRAY ){
208654    cnt = jsonbArrayCount(p, i);
208655  }
208656  if( !eErr ) sqlite3_result_int64(ctx, cnt);
208657  jsonParseFree(p);
208658}
208659
208660/* True if the string is all alphanumerics and underscores */
208661static int jsonAllAlphanum(const char *z, int n){
208662  int i;
208663  for(i=0; i<n && (sqlite3Isalnum(z[i]) || z[i]=='_'); i++){}
208664  return i==n;
208665}
208666
208667/*
208668** json_extract(JSON, PATH, ...)
208669** "->"(JSON,PATH)
208670** "->>"(JSON,PATH)
208671**
208672** Return the element described by PATH.  Return NULL if that PATH element
208673** is not found.
208674**
208675** If JSON_JSON is set or if more that one PATH argument is supplied then
208676** always return a JSON representation of the result.  If JSON_SQL is set,
208677** then always return an SQL representation of the result.  If neither flag
208678** is present and argc==2, then return JSON for objects and arrays and SQL
208679** for all other values.
208680**
208681** When multiple PATH arguments are supplied, the result is a JSON array
208682** containing the result of each PATH.
208683**
208684** Abbreviated JSON path expressions are allows if JSON_ABPATH, for
208685** compatibility with PG.
208686*/
208687static void jsonExtractFunc(
208688  sqlite3_context *ctx,
208689  int argc,
208690  sqlite3_value **argv
208691){
208692  JsonParse *p = 0;      /* The parse */
208693  int flags;             /* Flags associated with the function */
208694  int i;                 /* Loop counter */
208695  JsonString jx;         /* String for array result */
208696
208697  if( argc<2 ) return;
208698  p = jsonParseFuncArg(ctx, argv[0], 0);
208699  if( p==0 ) return;
208700  flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx));
208701  jsonStringInit(&jx, ctx);
208702  if( argc>2 ){
208703    jsonAppendChar(&jx, '[');
208704  }
208705  for(i=1; i<argc; i++){
208706    /* With a single PATH argument */
208707    const char *zPath = (const char*)sqlite3_value_text(argv[i]);
208708    int nPath;
208709    u32 j;
208710    if( zPath==0 ) goto json_extract_error;
208711    nPath = sqlite3Strlen30(zPath);
208712    if( zPath[0]=='$' ){
208713      j = jsonLookupStep(p, 0, zPath+1, 0);
208714    }else if( (flags & JSON_ABPATH) ){
208715      /* The -> and ->> operators accept abbreviated PATH arguments.  This
208716      ** is mostly for compatibility with PostgreSQL, but also for
208717      ** convenience.
208718      **
208719      **     NUMBER   ==>  $[NUMBER]     // PG compatible
208720      **     LABEL    ==>  $.LABEL       // PG compatible
208721      **     [NUMBER] ==>  $[NUMBER]     // Not PG.  Purely for convenience
208722      */
208723      jsonStringInit(&jx, ctx);
208724      if( sqlite3_value_type(argv[i])==SQLITE_INTEGER ){
208725        jsonAppendRawNZ(&jx, "[", 1);
208726        jsonAppendRaw(&jx, zPath, nPath);
208727        jsonAppendRawNZ(&jx, "]", 2);
208728      }else if( jsonAllAlphanum(zPath, nPath) ){
208729        jsonAppendRawNZ(&jx, ".", 1);
208730        jsonAppendRaw(&jx, zPath, nPath);
208731      }else if( zPath[0]=='[' && nPath>=3 && zPath[nPath-1]==']' ){
208732        jsonAppendRaw(&jx, zPath, nPath);
208733      }else{
208734        jsonAppendRawNZ(&jx, ".\"", 2);
208735        jsonAppendRaw(&jx, zPath, nPath);
208736        jsonAppendRawNZ(&jx, "\"", 1);
208737      }
208738      jsonStringTerminate(&jx);
208739      j = jsonLookupStep(p, 0, jx.zBuf, 0);
208740      jsonStringReset(&jx);
208741    }else{
208742      jsonBadPathError(ctx, zPath);
208743      goto json_extract_error;
208744    }
208745    if( j<p->nBlob ){
208746      if( argc==2 ){
208747        if( flags & JSON_JSON ){
208748          jsonStringInit(&jx, ctx);
208749          jsonTranslateBlobToText(p, j, &jx);
208750          jsonReturnString(&jx, 0, 0);
208751          jsonStringReset(&jx);
208752          assert( (flags & JSON_BLOB)==0 );
208753          sqlite3_result_subtype(ctx, JSON_SUBTYPE);
208754        }else{
208755          jsonReturnFromBlob(p, j, ctx, 0);
208756          if( (flags & (JSON_SQL|JSON_BLOB))==0
208757           && (p->aBlob[j]&0x0f)>=JSONB_ARRAY
208758          ){
208759            sqlite3_result_subtype(ctx, JSON_SUBTYPE);
208760          }
208761        }
208762      }else{
208763        jsonAppendSeparator(&jx);
208764        jsonTranslateBlobToText(p, j, &jx);
208765      }
208766    }else if( j==JSON_LOOKUP_NOTFOUND ){
208767      if( argc==2 ){
208768        goto json_extract_error;  /* Return NULL if not found */
208769      }else{
208770        jsonAppendSeparator(&jx);
208771        jsonAppendRawNZ(&jx, "null", 4);
208772      }
208773    }else if( j==JSON_LOOKUP_ERROR ){
208774      sqlite3_result_error(ctx, "malformed JSON", -1);
208775      goto json_extract_error;
208776    }else{
208777      jsonBadPathError(ctx, zPath);
208778      goto json_extract_error;
208779    }
208780  }
208781  if( argc>2 ){
208782    jsonAppendChar(&jx, ']');
208783    jsonReturnString(&jx, 0, 0);
208784    if( (flags & JSON_BLOB)==0 ){
208785      sqlite3_result_subtype(ctx, JSON_SUBTYPE);
208786    }
208787  }
208788json_extract_error:
208789  jsonStringReset(&jx);
208790  jsonParseFree(p);
208791  return;
208792}
208793
208794/*
208795** Return codes for jsonMergePatch()
208796*/
208797#define JSON_MERGE_OK          0     /* Success */
208798#define JSON_MERGE_BADTARGET   1     /* Malformed TARGET blob */
208799#define JSON_MERGE_BADPATCH    2     /* Malformed PATCH blob */
208800#define JSON_MERGE_OOM         3     /* Out-of-memory condition */
208801
208802/*
208803** RFC-7396 MergePatch for two JSONB blobs.
208804**
208805** pTarget is the target. pPatch is the patch.  The target is updated
208806** in place.  The patch is read-only.
208807**
208808** The original RFC-7396 algorithm is this:
208809**
208810**   define MergePatch(Target, Patch):
208811**     if Patch is an Object:
208812**       if Target is not an Object:
208813**         Target = {} # Ignore the contents and set it to an empty Object
208814**     for each Name/Value pair in Patch:
208815**         if Value is null:
208816**           if Name exists in Target:
208817**             remove the Name/Value pair from Target
208818**         else:
208819**           Target[Name] = MergePatch(Target[Name], Value)
208820**       return Target
208821**     else:
208822**       return Patch
208823**
208824** Here is an equivalent algorithm restructured to show the actual
208825** implementation:
208826**
208827** 01   define MergePatch(Target, Patch):
208828** 02      if Patch is not an Object:
208829** 03         return Patch
208830** 04      else: // if Patch is an Object
208831** 05         if Target is not an Object:
208832** 06            Target = {}
208833** 07      for each Name/Value pair in Patch:
208834** 08         if Name exists in Target:
208835** 09            if Value is null:
208836** 10               remove the Name/Value pair from Target
208837** 11            else
208838** 12               Target[name] = MergePatch(Target[Name], Value)
208839** 13         else if Value is not NULL:
208840** 14            if Value is not an Object:
208841** 15               Target[name] = Value
208842** 16            else:
208843** 17               Target[name] = MergePatch('{}',value)
208844** 18      return Target
208845**  |
208846**  ^---- Line numbers referenced in comments in the implementation
208847*/
208848static int jsonMergePatch(
208849  JsonParse *pTarget,      /* The JSON parser that contains the TARGET */
208850  u32 iTarget,             /* Index of TARGET in pTarget->aBlob[] */
208851  const JsonParse *pPatch, /* The PATCH */
208852  u32 iPatch               /* Index of PATCH in pPatch->aBlob[] */
208853){
208854  u8 x;             /* Type of a single node */
208855  u32 n, sz=0;      /* Return values from jsonbPayloadSize() */
208856  u32 iTCursor;     /* Cursor position while scanning the target object */
208857  u32 iTStart;      /* First label in the target object */
208858  u32 iTEndBE;      /* Original first byte past end of target, before edit */
208859  u32 iTEnd;        /* Current first byte past end of target */
208860  u8 eTLabel;       /* Node type of the target label */
208861  u32 iTLabel = 0;  /* Index of the label */
208862  u32 nTLabel = 0;  /* Header size in bytes for the target label */
208863  u32 szTLabel = 0; /* Size of the target label payload */
208864  u32 iTValue = 0;  /* Index of the target value */
208865  u32 nTValue = 0;  /* Header size of the target value */
208866  u32 szTValue = 0; /* Payload size for the target value */
208867
208868  u32 iPCursor;     /* Cursor position while scanning the patch */
208869  u32 iPEnd;        /* First byte past the end of the patch */
208870  u8 ePLabel;       /* Node type of the patch label */
208871  u32 iPLabel;      /* Start of patch label */
208872  u32 nPLabel;      /* Size of header on the patch label */
208873  u32 szPLabel;     /* Payload size of the patch label */
208874  u32 iPValue;      /* Start of patch value */
208875  u32 nPValue;      /* Header size for the patch value */
208876  u32 szPValue;     /* Payload size of the patch value */
208877
208878  assert( iTarget>=0 && iTarget<pTarget->nBlob );
208879  assert( iPatch>=0 && iPatch<pPatch->nBlob );
208880  x = pPatch->aBlob[iPatch] & 0x0f;
208881  if( x!=JSONB_OBJECT ){  /* Algorithm line 02 */
208882    u32 szPatch;        /* Total size of the patch, header+payload */
208883    u32 szTarget;       /* Total size of the target, header+payload */
208884    n = jsonbPayloadSize(pPatch, iPatch, &sz);
208885    szPatch = n+sz;
208886    sz = 0;
208887    n = jsonbPayloadSize(pTarget, iTarget, &sz);
208888    szTarget = n+sz;
208889    jsonBlobEdit(pTarget, iTarget, szTarget, pPatch->aBlob+iPatch, szPatch);
208890    return pTarget->oom ? JSON_MERGE_OOM : JSON_MERGE_OK;  /* Line 03 */
208891  }
208892  x = pTarget->aBlob[iTarget] & 0x0f;
208893  if( x!=JSONB_OBJECT ){  /* Algorithm line 05 */
208894    n = jsonbPayloadSize(pTarget, iTarget, &sz);
208895    jsonBlobEdit(pTarget, iTarget+n, sz, 0, 0);
208896    x = pTarget->aBlob[iTarget];
208897    pTarget->aBlob[iTarget] = (x & 0xf0) | JSONB_OBJECT;
208898  }
208899  n = jsonbPayloadSize(pPatch, iPatch, &sz);
208900  if( NEVER(n==0) ) return JSON_MERGE_BADPATCH;
208901  iPCursor = iPatch+n;
208902  iPEnd = iPCursor+sz;
208903  n = jsonbPayloadSize(pTarget, iTarget, &sz);
208904  if( NEVER(n==0) ) return JSON_MERGE_BADTARGET;
208905  iTStart = iTarget+n;
208906  iTEndBE = iTStart+sz;
208907
208908  while( iPCursor<iPEnd ){  /* Algorithm line 07 */
208909    iPLabel = iPCursor;
208910    ePLabel = pPatch->aBlob[iPCursor] & 0x0f;
208911    if( ePLabel<JSONB_TEXT || ePLabel>JSONB_TEXTRAW ){
208912      return JSON_MERGE_BADPATCH;
208913    }
208914    nPLabel = jsonbPayloadSize(pPatch, iPCursor, &szPLabel);
208915    if( nPLabel==0 ) return JSON_MERGE_BADPATCH;
208916    iPValue = iPCursor + nPLabel + szPLabel;
208917    if( iPValue>=iPEnd ) return JSON_MERGE_BADPATCH;
208918    nPValue = jsonbPayloadSize(pPatch, iPValue, &szPValue);
208919    if( nPValue==0 ) return JSON_MERGE_BADPATCH;
208920    iPCursor = iPValue + nPValue + szPValue;
208921    if( iPCursor>iPEnd ) return JSON_MERGE_BADPATCH;
208922
208923    iTCursor = iTStart;
208924    iTEnd = iTEndBE + pTarget->delta;
208925    while( iTCursor<iTEnd ){
208926      int isEqual;   /* true if the patch and target labels match */
208927      iTLabel = iTCursor;
208928      eTLabel = pTarget->aBlob[iTCursor] & 0x0f;
208929      if( eTLabel<JSONB_TEXT || eTLabel>JSONB_TEXTRAW ){
208930        return JSON_MERGE_BADTARGET;
208931      }
208932      nTLabel = jsonbPayloadSize(pTarget, iTCursor, &szTLabel);
208933      if( nTLabel==0 ) return JSON_MERGE_BADTARGET;
208934      iTValue = iTLabel + nTLabel + szTLabel;
208935      if( iTValue>=iTEnd ) return JSON_MERGE_BADTARGET;
208936      nTValue = jsonbPayloadSize(pTarget, iTValue, &szTValue);
208937      if( nTValue==0 ) return JSON_MERGE_BADTARGET;
208938      if( iTValue + nTValue + szTValue > iTEnd ) return JSON_MERGE_BADTARGET;
208939      isEqual = jsonLabelCompare(
208940                   (const char*)&pPatch->aBlob[iPLabel+nPLabel],
208941                   szPLabel,
208942                   (ePLabel==JSONB_TEXT || ePLabel==JSONB_TEXTRAW),
208943                   (const char*)&pTarget->aBlob[iTLabel+nTLabel],
208944                   szTLabel,
208945                   (eTLabel==JSONB_TEXT || eTLabel==JSONB_TEXTRAW));
208946      if( isEqual ) break;
208947      iTCursor = iTValue + nTValue + szTValue;
208948    }
208949    x = pPatch->aBlob[iPValue] & 0x0f;
208950    if( iTCursor<iTEnd ){
208951      /* A match was found.  Algorithm line 08 */
208952      if( x==0 ){
208953        /* Patch value is NULL.  Algorithm line 09 */
208954        jsonBlobEdit(pTarget, iTLabel, nTLabel+szTLabel+nTValue+szTValue, 0,0);
208955        /*  vvvvvv----- No OOM on a delete-only edit */
208956        if( NEVER(pTarget->oom) ) return JSON_MERGE_OOM;
208957      }else{
208958        /* Algorithm line 12 */
208959        int rc, savedDelta = pTarget->delta;
208960        pTarget->delta = 0;
208961        rc = jsonMergePatch(pTarget, iTValue, pPatch, iPValue);
208962        if( rc ) return rc;
208963        pTarget->delta += savedDelta;
208964      }
208965    }else if( x>0 ){  /* Algorithm line 13 */
208966      /* No match and patch value is not NULL */
208967      u32 szNew = szPLabel+nPLabel;
208968      if( (pPatch->aBlob[iPValue] & 0x0f)!=JSONB_OBJECT ){  /* Line 14 */
208969        jsonBlobEdit(pTarget, iTEnd, 0, 0, szPValue+nPValue+szNew);
208970        if( pTarget->oom ) return JSON_MERGE_OOM;
208971        memcpy(&pTarget->aBlob[iTEnd], &pPatch->aBlob[iPLabel], szNew);
208972        memcpy(&pTarget->aBlob[iTEnd+szNew],
208973               &pPatch->aBlob[iPValue], szPValue+nPValue);
208974      }else{
208975        int rc, savedDelta;
208976        jsonBlobEdit(pTarget, iTEnd, 0, 0, szNew+1);
208977        if( pTarget->oom ) return JSON_MERGE_OOM;
208978        memcpy(&pTarget->aBlob[iTEnd], &pPatch->aBlob[iPLabel], szNew);
208979        pTarget->aBlob[iTEnd+szNew] = 0x00;
208980        savedDelta = pTarget->delta;
208981        pTarget->delta = 0;
208982        rc = jsonMergePatch(pTarget, iTEnd+szNew,pPatch,iPValue);
208983        if( rc ) return rc;
208984        pTarget->delta += savedDelta;
208985      }
208986    }
208987  }
208988  if( pTarget->delta ) jsonAfterEditSizeAdjust(pTarget, iTarget);
208989  return pTarget->oom ? JSON_MERGE_OOM : JSON_MERGE_OK;
208990}
208991
208992
208993/*
208994** Implementation of the json_mergepatch(JSON1,JSON2) function.  Return a JSON
208995** object that is the result of running the RFC 7396 MergePatch() algorithm
208996** on the two arguments.
208997*/
208998static void jsonPatchFunc(
208999  sqlite3_context *ctx,
209000  int argc,
209001  sqlite3_value **argv
209002){
209003  JsonParse *pTarget;    /* The TARGET */
209004  JsonParse *pPatch;     /* The PATCH */
209005  int rc;                /* Result code */
209006
209007  UNUSED_PARAMETER(argc);
209008  assert( argc==2 );
209009  pTarget = jsonParseFuncArg(ctx, argv[0], JSON_EDITABLE);
209010  if( pTarget==0 ) return;
209011  pPatch = jsonParseFuncArg(ctx, argv[1], 0);
209012  if( pPatch ){
209013    rc = jsonMergePatch(pTarget, 0, pPatch, 0);
209014    if( rc==JSON_MERGE_OK ){
209015      jsonReturnParse(ctx, pTarget);
209016    }else if( rc==JSON_MERGE_OOM ){
209017      sqlite3_result_error_nomem(ctx);
209018    }else{
209019      sqlite3_result_error(ctx, "malformed JSON", -1);
209020    }
209021    jsonParseFree(pPatch);
209022  }
209023  jsonParseFree(pTarget);
209024}
209025
209026
209027/*
209028** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON
209029** object that contains all name/value given in arguments.  Or if any name
209030** is not a string or if any value is a BLOB, throw an error.
209031*/
209032static void jsonObjectFunc(
209033  sqlite3_context *ctx,
209034  int argc,
209035  sqlite3_value **argv
209036){
209037  int i;
209038  JsonString jx;
209039  const char *z;
209040  u32 n;
209041
209042  if( argc&1 ){
209043    sqlite3_result_error(ctx, "json_object() requires an even number "
209044                                  "of arguments", -1);
209045    return;
209046  }
209047  jsonStringInit(&jx, ctx);
209048  jsonAppendChar(&jx, '{');
209049  for(i=0; i<argc; i+=2){
209050    if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
209051      sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
209052      jsonStringReset(&jx);
209053      return;
209054    }
209055    jsonAppendSeparator(&jx);
209056    z = (const char*)sqlite3_value_text(argv[i]);
209057    n = sqlite3_value_bytes(argv[i]);
209058    jsonAppendString(&jx, z, n);
209059    jsonAppendChar(&jx, ':');
209060    jsonAppendSqlValue(&jx, argv[i+1]);
209061  }
209062  jsonAppendChar(&jx, '}');
209063  jsonReturnString(&jx, 0, 0);
209064  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
209065}
209066
209067
209068/*
209069** json_remove(JSON, PATH, ...)
209070**
209071** Remove the named elements from JSON and return the result.  malformed
209072** JSON or PATH arguments result in an error.
209073*/
209074static void jsonRemoveFunc(
209075  sqlite3_context *ctx,
209076  int argc,
209077  sqlite3_value **argv
209078){
209079  JsonParse *p;          /* The parse */
209080  const char *zPath = 0; /* Path of element to be removed */
209081  int i;                 /* Loop counter */
209082  u32 rc;                /* Subroutine return code */
209083
209084  if( argc<1 ) return;
209085  p = jsonParseFuncArg(ctx, argv[0], argc>1 ? JSON_EDITABLE : 0);
209086  if( p==0 ) return;
209087  for(i=1; i<argc; i++){
209088    zPath = (const char*)sqlite3_value_text(argv[i]);
209089    if( zPath==0 ){
209090      goto json_remove_done;
209091    }
209092    if( zPath[0]!='$' ){
209093      goto json_remove_patherror;
209094    }
209095    if( zPath[1]==0 ){
209096      /* json_remove(j,'$') returns NULL */
209097      goto json_remove_done;
209098    }
209099    p->eEdit = JEDIT_DEL;
209100    p->delta = 0;
209101    rc = jsonLookupStep(p, 0, zPath+1, 0);
209102    if( JSON_LOOKUP_ISERROR(rc) ){
209103      if( rc==JSON_LOOKUP_NOTFOUND ){
209104        continue;  /* No-op */
209105      }else if( rc==JSON_LOOKUP_PATHERROR ){
209106        jsonBadPathError(ctx, zPath);
209107      }else{
209108        sqlite3_result_error(ctx, "malformed JSON", -1);
209109      }
209110      goto json_remove_done;
209111    }
209112  }
209113  jsonReturnParse(ctx, p);
209114  jsonParseFree(p);
209115  return;
209116
209117json_remove_patherror:
209118  jsonBadPathError(ctx, zPath);
209119
209120json_remove_done:
209121  jsonParseFree(p);
209122  return;
209123}
209124
209125/*
209126** json_replace(JSON, PATH, VALUE, ...)
209127**
209128** Replace the value at PATH with VALUE.  If PATH does not already exist,
209129** this routine is a no-op.  If JSON or PATH is malformed, throw an error.
209130*/
209131static void jsonReplaceFunc(
209132  sqlite3_context *ctx,
209133  int argc,
209134  sqlite3_value **argv
209135){
209136  if( argc<1 ) return;
209137  if( (argc&1)==0 ) {
209138    jsonWrongNumArgs(ctx, "replace");
209139    return;
209140  }
209141  jsonInsertIntoBlob(ctx, argc, argv, JEDIT_REPL);
209142}
209143
209144
209145/*
209146** json_set(JSON, PATH, VALUE, ...)
209147**
209148** Set the value at PATH to VALUE.  Create the PATH if it does not already
209149** exist.  Overwrite existing values that do exist.
209150** If JSON or PATH is malformed, throw an error.
209151**
209152** json_insert(JSON, PATH, VALUE, ...)
209153**
209154** Create PATH and initialize it to VALUE.  If PATH already exists, this
209155** routine is a no-op.  If JSON or PATH is malformed, throw an error.
209156*/
209157static void jsonSetFunc(
209158  sqlite3_context *ctx,
209159  int argc,
209160  sqlite3_value **argv
209161){
209162
209163  int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx));
209164  int bIsSet = (flags&JSON_ISSET)!=0;
209165
209166  if( argc<1 ) return;
209167  if( (argc&1)==0 ) {
209168    jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
209169    return;
209170  }
209171  jsonInsertIntoBlob(ctx, argc, argv, bIsSet ? JEDIT_SET : JEDIT_INS);
209172}
209173
209174/*
209175** json_type(JSON)
209176** json_type(JSON, PATH)
209177**
209178** Return the top-level "type" of a JSON string.  json_type() raises an
209179** error if either the JSON or PATH inputs are not well-formed.
209180*/
209181static void jsonTypeFunc(
209182  sqlite3_context *ctx,
209183  int argc,
209184  sqlite3_value **argv
209185){
209186  JsonParse *p;          /* The parse */
209187  const char *zPath = 0;
209188  u32 i;
209189
209190  p = jsonParseFuncArg(ctx, argv[0], 0);
209191  if( p==0 ) return;
209192  if( argc==2 ){
209193    zPath = (const char*)sqlite3_value_text(argv[1]);
209194    if( zPath==0 ) goto json_type_done;
209195    if( zPath[0]!='$' ){
209196      jsonBadPathError(ctx, zPath);
209197      goto json_type_done;
209198    }
209199    i = jsonLookupStep(p, 0, zPath+1, 0);
209200    if( JSON_LOOKUP_ISERROR(i) ){
209201      if( i==JSON_LOOKUP_NOTFOUND ){
209202        /* no-op */
209203      }else if( i==JSON_LOOKUP_PATHERROR ){
209204        jsonBadPathError(ctx, zPath);
209205      }else{
209206        sqlite3_result_error(ctx, "malformed JSON", -1);
209207      }
209208      goto json_type_done;
209209    }
209210  }else{
209211    i = 0;
209212  }
209213  sqlite3_result_text(ctx, jsonbType[p->aBlob[i]&0x0f], -1, SQLITE_STATIC);
209214json_type_done:
209215  jsonParseFree(p);
209216}
209217
209218/*
209219** json_pretty(JSON)
209220** json_pretty(JSON, INDENT)
209221**
209222** Return text that is a pretty-printed rendering of the input JSON.
209223** If the argument is not valid JSON, return NULL.
209224**
209225** The INDENT argument is text that is used for indentation.  If omitted,
209226** it defaults to four spaces (the same as PostgreSQL).
209227*/
209228static void jsonPrettyFunc(
209229  sqlite3_context *ctx,
209230  int argc,
209231  sqlite3_value **argv
209232){
209233  JsonString s;          /* The output string */
209234  JsonPretty x;          /* Pretty printing context */
209235
209236  memset(&x, 0, sizeof(x));
209237  x.pParse = jsonParseFuncArg(ctx, argv[0], 0);
209238  if( x.pParse==0 ) return;
209239  x.pOut = &s;
209240  jsonStringInit(&s, ctx);
209241  if( argc==1 || (x.zIndent = (const char*)sqlite3_value_text(argv[1]))==0 ){
209242    x.zIndent = "    ";
209243    x.szIndent = 4;
209244  }else{
209245    x.szIndent = (u32)strlen(x.zIndent);
209246  }
209247  jsonTranslateBlobToPrettyText(&x, 0);
209248  jsonReturnString(&s, 0, 0);
209249  jsonParseFree(x.pParse);
209250}
209251
209252/*
209253** json_valid(JSON)
209254** json_valid(JSON, FLAGS)
209255**
209256** Check the JSON argument to see if it is well-formed.  The FLAGS argument
209257** encodes the various constraints on what is meant by "well-formed":
209258**
209259**     0x01      Canonical RFC-8259 JSON text
209260**     0x02      JSON text with optional JSON-5 extensions
209261**     0x04      Superficially appears to be JSONB
209262**     0x08      Strictly well-formed JSONB
209263**
209264** If the FLAGS argument is omitted, it defaults to 1.  Useful values for
209265** FLAGS include:
209266**
209267**    1          Strict canonical JSON text
209268**    2          JSON text perhaps with JSON-5 extensions
209269**    4          Superficially appears to be JSONB
209270**    5          Canonical JSON text or superficial JSONB
209271**    6          JSON-5 text or superficial JSONB
209272**    8          Strict JSONB
209273**    9          Canonical JSON text or strict JSONB
209274**    10         JSON-5 text or strict JSONB
209275**
209276** Other flag combinations are redundant.  For example, every canonical
209277** JSON text is also well-formed JSON-5 text, so FLAG values 2 and 3
209278** are the same.  Similarly, any input that passes a strict JSONB validation
209279** will also pass the superficial validation so 12 through 15 are the same
209280** as 8 through 11 respectively.
209281**
209282** This routine runs in linear time to validate text and when doing strict
209283** JSONB validation.  Superficial JSONB validation is constant time,
209284** assuming the BLOB is already in memory.  The performance advantage
209285** of superficial JSONB validation is why that option is provided.
209286** Application developers can choose to do fast superficial validation or
209287** slower strict validation, according to their specific needs.
209288**
209289** Only the lower four bits of the FLAGS argument are currently used.
209290** Higher bits are reserved for future expansion.   To facilitate
209291** compatibility, the current implementation raises an error if any bit
209292** in FLAGS is set other than the lower four bits.
209293**
209294** The original circa 2015 implementation of the JSON routines in
209295** SQLite only supported canonical RFC-8259 JSON text and the json_valid()
209296** function only accepted one argument.  That is why the default value
209297** for the FLAGS argument is 1, since FLAGS=1 causes this routine to only
209298** recognize canonical RFC-8259 JSON text as valid.  The extra FLAGS
209299** argument was added when the JSON routines were extended to support
209300** JSON5-like extensions and binary JSONB stored in BLOBs.
209301**
209302** Return Values:
209303**
209304**   *   Raise an error if FLAGS is outside the range of 1 to 15.
209305**   *   Return NULL if the input is NULL
209306**   *   Return 1 if the input is well-formed.
209307**   *   Return 0 if the input is not well-formed.
209308*/
209309static void jsonValidFunc(
209310  sqlite3_context *ctx,
209311  int argc,
209312  sqlite3_value **argv
209313){
209314  JsonParse *p;          /* The parse */
209315  u8 flags = 1;
209316  u8 res = 0;
209317  if( argc==2 ){
209318    i64 f = sqlite3_value_int64(argv[1]);
209319    if( f<1 || f>15 ){
209320      sqlite3_result_error(ctx, "FLAGS parameter to json_valid() must be"
209321                                " between 1 and 15", -1);
209322      return;
209323    }
209324    flags = f & 0x0f;
209325  }
209326  switch( sqlite3_value_type(argv[0]) ){
209327    case SQLITE_NULL: {
209328#ifdef SQLITE_LEGACY_JSON_VALID
209329      /* Incorrect legacy behavior was to return FALSE for a NULL input */
209330      sqlite3_result_int(ctx, 0);
209331#endif
209332      return;
209333    }
209334    case SQLITE_BLOB: {
209335      if( jsonFuncArgMightBeBinary(argv[0]) ){
209336        if( flags & 0x04 ){
209337          /* Superficial checking only - accomplished by the
209338          ** jsonFuncArgMightBeBinary() call above. */
209339          res = 1;
209340        }else if( flags & 0x08 ){
209341          /* Strict checking.  Check by translating BLOB->TEXT->BLOB.  If
209342          ** no errors occur, call that a "strict check". */
209343          JsonParse px;
209344          u32 iErr;
209345          memset(&px, 0, sizeof(px));
209346          px.aBlob = (u8*)sqlite3_value_blob(argv[0]);
209347          px.nBlob = sqlite3_value_bytes(argv[0]);
209348          iErr = jsonbValidityCheck(&px, 0, px.nBlob, 1);
209349          res = iErr==0;
209350        }
209351        break;
209352      }
209353      /* Fall through into interpreting the input as text.  See note
209354      ** above at tag-20240123-a. */
209355      /* no break */ deliberate_fall_through
209356    }
209357    default: {
209358      JsonParse px;
209359      if( (flags & 0x3)==0 ) break;
209360      memset(&px, 0, sizeof(px));
209361
209362      p = jsonParseFuncArg(ctx, argv[0], JSON_KEEPERROR);
209363      if( p ){
209364        if( p->oom ){
209365          sqlite3_result_error_nomem(ctx);
209366        }else if( p->nErr ){
209367          /* no-op */
209368        }else if( (flags & 0x02)!=0 || p->hasNonstd==0 ){
209369          res = 1;
209370        }
209371        jsonParseFree(p);
209372      }else{
209373        sqlite3_result_error_nomem(ctx);
209374      }
209375      break;
209376    }
209377  }
209378  sqlite3_result_int(ctx, res);
209379}
209380
209381/*
209382** json_error_position(JSON)
209383**
209384** If the argument is NULL, return NULL
209385**
209386** If the argument is BLOB, do a full validity check and return non-zero
209387** if the check fails.  The return value is the approximate 1-based offset
209388** to the byte of the element that contains the first error.
209389**
209390** Otherwise interpret the argument is TEXT (even if it is numeric) and
209391** return the 1-based character position for where the parser first recognized
209392** that the input was not valid JSON, or return 0 if the input text looks
209393** ok.  JSON-5 extensions are accepted.
209394*/
209395static void jsonErrorFunc(
209396  sqlite3_context *ctx,
209397  int argc,
209398  sqlite3_value **argv
209399){
209400  i64 iErrPos = 0;       /* Error position to be returned */
209401  JsonParse s;
209402
209403  assert( argc==1 );
209404  UNUSED_PARAMETER(argc);
209405  memset(&s, 0, sizeof(s));
209406  s.db = sqlite3_context_db_handle(ctx);
209407  if( jsonFuncArgMightBeBinary(argv[0]) ){
209408    s.aBlob = (u8*)sqlite3_value_blob(argv[0]);
209409    s.nBlob = sqlite3_value_bytes(argv[0]);
209410    iErrPos = (i64)jsonbValidityCheck(&s, 0, s.nBlob, 1);
209411  }else{
209412    s.zJson = (char*)sqlite3_value_text(argv[0]);
209413    if( s.zJson==0 ) return;  /* NULL input or OOM */
209414    s.nJson = sqlite3_value_bytes(argv[0]);
209415    if( jsonConvertTextToBlob(&s,0) ){
209416      if( s.oom ){
209417        iErrPos = -1;
209418      }else{
209419        /* Convert byte-offset s.iErr into a character offset */
209420        u32 k;
209421        assert( s.zJson!=0 );  /* Because s.oom is false */
209422        for(k=0; k<s.iErr && ALWAYS(s.zJson[k]); k++){
209423          if( (s.zJson[k] & 0xc0)!=0x80 ) iErrPos++;
209424        }
209425        iErrPos++;
209426      }
209427    }
209428  }
209429  jsonParseReset(&s);
209430  if( iErrPos<0 ){
209431    sqlite3_result_error_nomem(ctx);
209432  }else{
209433    sqlite3_result_int64(ctx, iErrPos);
209434  }
209435}
209436
209437/****************************************************************************
209438** Aggregate SQL function implementations
209439****************************************************************************/
209440/*
209441** json_group_array(VALUE)
209442**
209443** Return a JSON array composed of all values in the aggregate.
209444*/
209445static void jsonArrayStep(
209446  sqlite3_context *ctx,
209447  int argc,
209448  sqlite3_value **argv
209449){
209450  JsonString *pStr;
209451  UNUSED_PARAMETER(argc);
209452  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
209453  if( pStr ){
209454    if( pStr->zBuf==0 ){
209455      jsonStringInit(pStr, ctx);
209456      jsonAppendChar(pStr, '[');
209457    }else if( pStr->nUsed>1 ){
209458      jsonAppendChar(pStr, ',');
209459    }
209460    pStr->pCtx = ctx;
209461    jsonAppendSqlValue(pStr, argv[0]);
209462  }
209463}
209464static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
209465  JsonString *pStr;
209466  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
209467  if( pStr ){
209468    int flags;
209469    pStr->pCtx = ctx;
209470    jsonAppendChar(pStr, ']');
209471    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx));
209472    if( pStr->eErr ){
209473      jsonReturnString(pStr, 0, 0);
209474      return;
209475    }else if( flags & JSON_BLOB ){
209476      jsonReturnStringAsBlob(pStr);
209477      if( isFinal ){
209478        if( !pStr->bStatic ) sqlite3RCStrUnref(pStr->zBuf);
209479      }else{
209480        jsonStringTrimOneChar(pStr);
209481      }
209482      return;
209483    }else if( isFinal ){
209484      sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
209485                          pStr->bStatic ? SQLITE_TRANSIENT :
209486                              sqlite3RCStrUnref);
209487      pStr->bStatic = 1;
209488    }else{
209489      sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
209490      jsonStringTrimOneChar(pStr);
209491    }
209492  }else{
209493    sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
209494  }
209495  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
209496}
209497static void jsonArrayValue(sqlite3_context *ctx){
209498  jsonArrayCompute(ctx, 0);
209499}
209500static void jsonArrayFinal(sqlite3_context *ctx){
209501  jsonArrayCompute(ctx, 1);
209502}
209503
209504#ifndef SQLITE_OMIT_WINDOWFUNC
209505/*
209506** This method works for both json_group_array() and json_group_object().
209507** It works by removing the first element of the group by searching forward
209508** to the first comma (",") that is not within a string and deleting all
209509** text through that comma.
209510*/
209511static void jsonGroupInverse(
209512  sqlite3_context *ctx,
209513  int argc,
209514  sqlite3_value **argv
209515){
209516  unsigned int i;
209517  int inStr = 0;
209518  int nNest = 0;
209519  char *z;
209520  char c;
209521  JsonString *pStr;
209522  UNUSED_PARAMETER(argc);
209523  UNUSED_PARAMETER(argv);
209524  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
209525#ifdef NEVER
209526  /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
209527  ** always have been called to initialize it */
209528  if( NEVER(!pStr) ) return;
209529#endif
209530  z = pStr->zBuf;
209531  for(i=1; i<pStr->nUsed && ((c = z[i])!=',' || inStr || nNest); i++){
209532    if( c=='"' ){
209533      inStr = !inStr;
209534    }else if( c=='\\' ){
209535      i++;
209536    }else if( !inStr ){
209537      if( c=='{' || c=='[' ) nNest++;
209538      if( c=='}' || c==']' ) nNest--;
209539    }
209540  }
209541  if( i<pStr->nUsed ){
209542    pStr->nUsed -= i;
209543    memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
209544    z[pStr->nUsed] = 0;
209545  }else{
209546    pStr->nUsed = 1;
209547  }
209548}
209549#else
209550# define jsonGroupInverse 0
209551#endif
209552
209553
209554/*
209555** json_group_obj(NAME,VALUE)
209556**
209557** Return a JSON object composed of all names and values in the aggregate.
209558*/
209559static void jsonObjectStep(
209560  sqlite3_context *ctx,
209561  int argc,
209562  sqlite3_value **argv
209563){
209564  JsonString *pStr;
209565  const char *z;
209566  u32 n;
209567  UNUSED_PARAMETER(argc);
209568  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
209569  if( pStr ){
209570    if( pStr->zBuf==0 ){
209571      jsonStringInit(pStr, ctx);
209572      jsonAppendChar(pStr, '{');
209573    }else if( pStr->nUsed>1 ){
209574      jsonAppendChar(pStr, ',');
209575    }
209576    pStr->pCtx = ctx;
209577    z = (const char*)sqlite3_value_text(argv[0]);
209578    n = sqlite3Strlen30(z);
209579    jsonAppendString(pStr, z, n);
209580    jsonAppendChar(pStr, ':');
209581    jsonAppendSqlValue(pStr, argv[1]);
209582  }
209583}
209584static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
209585  JsonString *pStr;
209586  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
209587  if( pStr ){
209588    int flags;
209589    jsonAppendChar(pStr, '}');
209590    pStr->pCtx = ctx;
209591    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx));
209592    if( pStr->eErr ){
209593      jsonReturnString(pStr, 0, 0);
209594      return;
209595    }else if( flags & JSON_BLOB ){
209596      jsonReturnStringAsBlob(pStr);
209597      if( isFinal ){
209598        if( !pStr->bStatic ) sqlite3RCStrUnref(pStr->zBuf);
209599      }else{
209600        jsonStringTrimOneChar(pStr);
209601      }
209602      return;
209603    }else if( isFinal ){
209604      sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
209605                          pStr->bStatic ? SQLITE_TRANSIENT :
209606                          sqlite3RCStrUnref);
209607      pStr->bStatic = 1;
209608    }else{
209609      sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
209610      jsonStringTrimOneChar(pStr);
209611    }
209612  }else{
209613    sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
209614  }
209615  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
209616}
209617static void jsonObjectValue(sqlite3_context *ctx){
209618  jsonObjectCompute(ctx, 0);
209619}
209620static void jsonObjectFinal(sqlite3_context *ctx){
209621  jsonObjectCompute(ctx, 1);
209622}
209623
209624
209625
209626#ifndef SQLITE_OMIT_VIRTUALTABLE
209627/****************************************************************************
209628** The json_each virtual table
209629****************************************************************************/
209630typedef struct JsonParent JsonParent;
209631struct JsonParent {
209632  u32 iHead;                 /* Start of object or array */
209633  u32 iValue;                /* Start of the value */
209634  u32 iEnd;                  /* First byte past the end */
209635  u32 nPath;                 /* Length of path */
209636  i64 iKey;                  /* Key for JSONB_ARRAY */
209637};
209638
209639typedef struct JsonEachCursor JsonEachCursor;
209640struct JsonEachCursor {
209641  sqlite3_vtab_cursor base;  /* Base class - must be first */
209642  u32 iRowid;                /* The rowid */
209643  u32 i;                     /* Index in sParse.aBlob[] of current row */
209644  u32 iEnd;                  /* EOF when i equals or exceeds this value */
209645  u32 nRoot;                 /* Size of the root path in bytes */
209646  u8 eType;                  /* Type of the container for element i */
209647  u8 bRecursive;             /* True for json_tree().  False for json_each() */
209648  u32 nParent;               /* Current nesting depth */
209649  u32 nParentAlloc;          /* Space allocated for aParent[] */
209650  JsonParent *aParent;       /* Parent elements of i */
209651  sqlite3 *db;               /* Database connection */
209652  JsonString path;           /* Current path */
209653  JsonParse sParse;          /* Parse of the input JSON */
209654};
209655typedef struct JsonEachConnection JsonEachConnection;
209656struct JsonEachConnection {
209657  sqlite3_vtab base;         /* Base class - must be first */
209658  sqlite3 *db;               /* Database connection */
209659};
209660
209661
209662/* Constructor for the json_each virtual table */
209663static int jsonEachConnect(
209664  sqlite3 *db,
209665  void *pAux,
209666  int argc, const char *const*argv,
209667  sqlite3_vtab **ppVtab,
209668  char **pzErr
209669){
209670  JsonEachConnection *pNew;
209671  int rc;
209672
209673/* Column numbers */
209674#define JEACH_KEY     0
209675#define JEACH_VALUE   1
209676#define JEACH_TYPE    2
209677#define JEACH_ATOM    3
209678#define JEACH_ID      4
209679#define JEACH_PARENT  5
209680#define JEACH_FULLKEY 6
209681#define JEACH_PATH    7
209682/* The xBestIndex method assumes that the JSON and ROOT columns are
209683** the last two columns in the table.  Should this ever changes, be
209684** sure to update the xBestIndex method. */
209685#define JEACH_JSON    8
209686#define JEACH_ROOT    9
209687
209688  UNUSED_PARAMETER(pzErr);
209689  UNUSED_PARAMETER(argv);
209690  UNUSED_PARAMETER(argc);
209691  UNUSED_PARAMETER(pAux);
209692  rc = sqlite3_declare_vtab(db,
209693     "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
209694                    "json HIDDEN,root HIDDEN)");
209695  if( rc==SQLITE_OK ){
209696    pNew = (JsonEachConnection*)sqlite3DbMallocZero(db, sizeof(*pNew));
209697    *ppVtab = (sqlite3_vtab*)pNew;
209698    if( pNew==0 ) return SQLITE_NOMEM;
209699    sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
209700    pNew->db = db;
209701  }
209702  return rc;
209703}
209704
209705/* destructor for json_each virtual table */
209706static int jsonEachDisconnect(sqlite3_vtab *pVtab){
209707  JsonEachConnection *p = (JsonEachConnection*)pVtab;
209708  sqlite3DbFree(p->db, pVtab);
209709  return SQLITE_OK;
209710}
209711
209712/* constructor for a JsonEachCursor object for json_each(). */
209713static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
209714  JsonEachConnection *pVtab = (JsonEachConnection*)p;
209715  JsonEachCursor *pCur;
209716
209717  UNUSED_PARAMETER(p);
209718  pCur = sqlite3DbMallocZero(pVtab->db, sizeof(*pCur));
209719  if( pCur==0 ) return SQLITE_NOMEM;
209720  pCur->db = pVtab->db;
209721  jsonStringZero(&pCur->path);
209722  *ppCursor = &pCur->base;
209723  return SQLITE_OK;
209724}
209725
209726/* constructor for a JsonEachCursor object for json_tree(). */
209727static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
209728  int rc = jsonEachOpenEach(p, ppCursor);
209729  if( rc==SQLITE_OK ){
209730    JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
209731    pCur->bRecursive = 1;
209732  }
209733  return rc;
209734}
209735
209736/* Reset a JsonEachCursor back to its original state.  Free any memory
209737** held. */
209738static void jsonEachCursorReset(JsonEachCursor *p){
209739  jsonParseReset(&p->sParse);
209740  jsonStringReset(&p->path);
209741  sqlite3DbFree(p->db, p->aParent);
209742  p->iRowid = 0;
209743  p->i = 0;
209744  p->aParent = 0;
209745  p->nParent = 0;
209746  p->nParentAlloc = 0;
209747  p->iEnd = 0;
209748  p->eType = 0;
209749}
209750
209751/* Destructor for a jsonEachCursor object */
209752static int jsonEachClose(sqlite3_vtab_cursor *cur){
209753  JsonEachCursor *p = (JsonEachCursor*)cur;
209754  jsonEachCursorReset(p);
209755
209756  sqlite3DbFree(p->db, cur);
209757  return SQLITE_OK;
209758}
209759
209760/* Return TRUE if the jsonEachCursor object has been advanced off the end
209761** of the JSON object */
209762static int jsonEachEof(sqlite3_vtab_cursor *cur){
209763  JsonEachCursor *p = (JsonEachCursor*)cur;
209764  return p->i >= p->iEnd;
209765}
209766
209767/*
209768** If the cursor is currently pointing at the label of a object entry,
209769** then return the index of the value.  For all other cases, return the
209770** current pointer position, which is the value.
209771*/
209772static int jsonSkipLabel(JsonEachCursor *p){
209773  if( p->eType==JSONB_OBJECT ){
209774    u32 sz = 0;
209775    u32 n = jsonbPayloadSize(&p->sParse, p->i, &sz);
209776    return p->i + n + sz;
209777  }else{
209778    return p->i;
209779  }
209780}
209781
209782/*
209783** Append the path name for the current element.
209784*/
209785static void jsonAppendPathName(JsonEachCursor *p){
209786  assert( p->nParent>0 );
209787  assert( p->eType==JSONB_ARRAY || p->eType==JSONB_OBJECT );
209788  if( p->eType==JSONB_ARRAY ){
209789    jsonPrintf(30, &p->path, "[%lld]", p->aParent[p->nParent-1].iKey);
209790  }else{
209791    u32 n, sz = 0, k, i;
209792    const char *z;
209793    int needQuote = 0;
209794    n = jsonbPayloadSize(&p->sParse, p->i, &sz);
209795    k = p->i + n;
209796    z = (const char*)&p->sParse.aBlob[k];
209797    if( sz==0 || !sqlite3Isalpha(z[0]) ){
209798      needQuote = 1;
209799    }else{
209800      for(i=0; i<sz; i++){
209801        if( !sqlite3Isalnum(z[i]) ){
209802          needQuote = 1;
209803          break;
209804        }
209805      }
209806    }
209807    if( needQuote ){
209808      jsonPrintf(sz+4,&p->path,".\"%.*s\"", sz, z);
209809    }else{
209810      jsonPrintf(sz+2,&p->path,".%.*s", sz, z);
209811    }
209812  }
209813}
209814
209815/* Advance the cursor to the next element for json_tree() */
209816static int jsonEachNext(sqlite3_vtab_cursor *cur){
209817  JsonEachCursor *p = (JsonEachCursor*)cur;
209818  int rc = SQLITE_OK;
209819  if( p->bRecursive ){
209820    u8 x;
209821    u8 levelChange = 0;
209822    u32 n, sz = 0;
209823    u32 i = jsonSkipLabel(p);
209824    x = p->sParse.aBlob[i] & 0x0f;
209825    n = jsonbPayloadSize(&p->sParse, i, &sz);
209826    if( x==JSONB_OBJECT || x==JSONB_ARRAY ){
209827      JsonParent *pParent;
209828      if( p->nParent>=p->nParentAlloc ){
209829        JsonParent *pNew;
209830        u64 nNew;
209831        nNew = p->nParentAlloc*2 + 3;
209832        pNew = sqlite3DbRealloc(p->db, p->aParent, sizeof(JsonParent)*nNew);
209833        if( pNew==0 ) return SQLITE_NOMEM;
209834        p->nParentAlloc = (u32)nNew;
209835        p->aParent = pNew;
209836      }
209837      levelChange = 1;
209838      pParent = &p->aParent[p->nParent];
209839      pParent->iHead = p->i;
209840      pParent->iValue = i;
209841      pParent->iEnd = i + n + sz;
209842      pParent->iKey = -1;
209843      pParent->nPath = (u32)p->path.nUsed;
209844      if( p->eType && p->nParent ){
209845        jsonAppendPathName(p);
209846        if( p->path.eErr ) rc = SQLITE_NOMEM;
209847      }
209848      p->nParent++;
209849      p->i = i + n;
209850    }else{
209851      p->i = i + n + sz;
209852    }
209853    while( p->nParent>0 && p->i >= p->aParent[p->nParent-1].iEnd ){
209854      p->nParent--;
209855      p->path.nUsed = p->aParent[p->nParent].nPath;
209856      levelChange = 1;
209857    }
209858    if( levelChange ){
209859      if( p->nParent>0 ){
209860        JsonParent *pParent = &p->aParent[p->nParent-1];
209861        u32 iVal = pParent->iValue;
209862        p->eType = p->sParse.aBlob[iVal] & 0x0f;
209863      }else{
209864        p->eType = 0;
209865      }
209866    }
209867  }else{
209868    u32 n, sz = 0;
209869    u32 i = jsonSkipLabel(p);
209870    n = jsonbPayloadSize(&p->sParse, i, &sz);
209871    p->i = i + n + sz;
209872  }
209873  if( p->eType==JSONB_ARRAY && p->nParent ){
209874    p->aParent[p->nParent-1].iKey++;
209875  }
209876  p->iRowid++;
209877  return rc;
209878}
209879
209880/* Length of the path for rowid==0 in bRecursive mode.
209881*/
209882static int jsonEachPathLength(JsonEachCursor *p){
209883  u32 n = p->path.nUsed;
209884  char *z = p->path.zBuf;
209885  if( p->iRowid==0 && p->bRecursive && n>=2 ){
209886    while( n>1 ){
209887      n--;
209888      if( z[n]=='[' || z[n]=='.' ){
209889        u32 x, sz = 0;
209890        char cSaved = z[n];
209891        z[n] = 0;
209892        assert( p->sParse.eEdit==0 );
209893        x = jsonLookupStep(&p->sParse, 0, z+1, 0);
209894        z[n] = cSaved;
209895        if( JSON_LOOKUP_ISERROR(x) ) continue;
209896        if( x + jsonbPayloadSize(&p->sParse, x, &sz) == p->i ) break;
209897      }
209898    }
209899  }
209900  return n;
209901}
209902
209903/* Return the value of a column */
209904static int jsonEachColumn(
209905  sqlite3_vtab_cursor *cur,   /* The cursor */
209906  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
209907  int iColumn                 /* Which column to return */
209908){
209909  JsonEachCursor *p = (JsonEachCursor*)cur;
209910  switch( iColumn ){
209911    case JEACH_KEY: {
209912      if( p->nParent==0 ){
209913        u32 n, j;
209914        if( p->nRoot==1 ) break;
209915        j = jsonEachPathLength(p);
209916        n = p->nRoot - j;
209917        if( n==0 ){
209918          break;
209919        }else if( p->path.zBuf[j]=='[' ){
209920          i64 x;
209921          sqlite3Atoi64(&p->path.zBuf[j+1], &x, n-1, SQLITE_UTF8);
209922          sqlite3_result_int64(ctx, x);
209923        }else if( p->path.zBuf[j+1]=='"' ){
209924          sqlite3_result_text(ctx, &p->path.zBuf[j+2], n-3, SQLITE_TRANSIENT);
209925        }else{
209926          sqlite3_result_text(ctx, &p->path.zBuf[j+1], n-1, SQLITE_TRANSIENT);
209927        }
209928        break;
209929      }
209930      if( p->eType==JSONB_OBJECT ){
209931        jsonReturnFromBlob(&p->sParse, p->i, ctx, 1);
209932      }else{
209933        assert( p->eType==JSONB_ARRAY );
209934        sqlite3_result_int64(ctx, p->aParent[p->nParent-1].iKey);
209935      }
209936      break;
209937    }
209938    case JEACH_VALUE: {
209939      u32 i = jsonSkipLabel(p);
209940      jsonReturnFromBlob(&p->sParse, i, ctx, 1);
209941      if( (p->sParse.aBlob[i] & 0x0f)>=JSONB_ARRAY ){
209942        sqlite3_result_subtype(ctx, JSON_SUBTYPE);
209943      }
209944      break;
209945    }
209946    case JEACH_TYPE: {
209947      u32 i = jsonSkipLabel(p);
209948      u8 eType = p->sParse.aBlob[i] & 0x0f;
209949      sqlite3_result_text(ctx, jsonbType[eType], -1, SQLITE_STATIC);
209950      break;
209951    }
209952    case JEACH_ATOM: {
209953      u32 i = jsonSkipLabel(p);
209954      if( (p->sParse.aBlob[i] & 0x0f)<JSONB_ARRAY ){
209955        jsonReturnFromBlob(&p->sParse, i, ctx, 1);
209956      }
209957      break;
209958    }
209959    case JEACH_ID: {
209960      sqlite3_result_int64(ctx, (sqlite3_int64)p->i);
209961      break;
209962    }
209963    case JEACH_PARENT: {
209964      if( p->nParent>0 && p->bRecursive ){
209965        sqlite3_result_int64(ctx, p->aParent[p->nParent-1].iHead);
209966      }
209967      break;
209968    }
209969    case JEACH_FULLKEY: {
209970      u64 nBase = p->path.nUsed;
209971      if( p->nParent ) jsonAppendPathName(p);
209972      sqlite3_result_text64(ctx, p->path.zBuf, p->path.nUsed,
209973                            SQLITE_TRANSIENT, SQLITE_UTF8);
209974      p->path.nUsed = nBase;
209975      break;
209976    }
209977    case JEACH_PATH: {
209978      u32 n = jsonEachPathLength(p);
209979      sqlite3_result_text64(ctx, p->path.zBuf, n,
209980                            SQLITE_TRANSIENT, SQLITE_UTF8);
209981      break;
209982    }
209983    default: {
209984      sqlite3_result_text(ctx, p->path.zBuf, p->nRoot, SQLITE_STATIC);
209985      break;
209986    }
209987    case JEACH_JSON: {
209988      if( p->sParse.zJson==0 ){
209989        sqlite3_result_blob(ctx, p->sParse.aBlob, p->sParse.nBlob,
209990                            SQLITE_TRANSIENT);
209991      }else{
209992        sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_TRANSIENT);
209993      }
209994      break;
209995    }
209996  }
209997  return SQLITE_OK;
209998}
209999
210000/* Return the current rowid value */
210001static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
210002  JsonEachCursor *p = (JsonEachCursor*)cur;
210003  *pRowid = p->iRowid;
210004  return SQLITE_OK;
210005}
210006
210007/* The query strategy is to look for an equality constraint on the json
210008** column.  Without such a constraint, the table cannot operate.  idxNum is
210009** 1 if the constraint is found, 3 if the constraint and zRoot are found,
210010** and 0 otherwise.
210011*/
210012static int jsonEachBestIndex(
210013  sqlite3_vtab *tab,
210014  sqlite3_index_info *pIdxInfo
210015){
210016  int i;                     /* Loop counter or computed array index */
210017  int aIdx[2];               /* Index of constraints for JSON and ROOT */
210018  int unusableMask = 0;      /* Mask of unusable JSON and ROOT constraints */
210019  int idxMask = 0;           /* Mask of usable == constraints JSON and ROOT */
210020  const struct sqlite3_index_constraint *pConstraint;
210021
210022  /* This implementation assumes that JSON and ROOT are the last two
210023  ** columns in the table */
210024  assert( JEACH_ROOT == JEACH_JSON+1 );
210025  UNUSED_PARAMETER(tab);
210026  aIdx[0] = aIdx[1] = -1;
210027  pConstraint = pIdxInfo->aConstraint;
210028  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
210029    int iCol;
210030    int iMask;
210031    if( pConstraint->iColumn < JEACH_JSON ) continue;
210032    iCol = pConstraint->iColumn - JEACH_JSON;
210033    assert( iCol==0 || iCol==1 );
210034    testcase( iCol==0 );
210035    iMask = 1 << iCol;
210036    if( pConstraint->usable==0 ){
210037      unusableMask |= iMask;
210038    }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
210039      aIdx[iCol] = i;
210040      idxMask |= iMask;
210041    }
210042  }
210043  if( pIdxInfo->nOrderBy>0
210044   && pIdxInfo->aOrderBy[0].iColumn<0
210045   && pIdxInfo->aOrderBy[0].desc==0
210046  ){
210047    pIdxInfo->orderByConsumed = 1;
210048  }
210049
210050  if( (unusableMask & ~idxMask)!=0 ){
210051    /* If there are any unusable constraints on JSON or ROOT, then reject
210052    ** this entire plan */
210053    return SQLITE_CONSTRAINT;
210054  }
210055  if( aIdx[0]<0 ){
210056    /* No JSON input.  Leave estimatedCost at the huge value that it was
210057    ** initialized to to discourage the query planner from selecting this
210058    ** plan. */
210059    pIdxInfo->idxNum = 0;
210060  }else{
210061    pIdxInfo->estimatedCost = 1.0;
210062    i = aIdx[0];
210063    pIdxInfo->aConstraintUsage[i].argvIndex = 1;
210064    pIdxInfo->aConstraintUsage[i].omit = 1;
210065    if( aIdx[1]<0 ){
210066      pIdxInfo->idxNum = 1;  /* Only JSON supplied.  Plan 1 */
210067    }else{
210068      i = aIdx[1];
210069      pIdxInfo->aConstraintUsage[i].argvIndex = 2;
210070      pIdxInfo->aConstraintUsage[i].omit = 1;
210071      pIdxInfo->idxNum = 3;  /* Both JSON and ROOT are supplied.  Plan 3 */
210072    }
210073  }
210074  return SQLITE_OK;
210075}
210076
210077/* Start a search on a new JSON string */
210078static int jsonEachFilter(
210079  sqlite3_vtab_cursor *cur,
210080  int idxNum, const char *idxStr,
210081  int argc, sqlite3_value **argv
210082){
210083  JsonEachCursor *p = (JsonEachCursor*)cur;
210084  const char *zRoot = 0;
210085  u32 i, n, sz;
210086
210087  UNUSED_PARAMETER(idxStr);
210088  UNUSED_PARAMETER(argc);
210089  jsonEachCursorReset(p);
210090  if( idxNum==0 ) return SQLITE_OK;
210091  memset(&p->sParse, 0, sizeof(p->sParse));
210092  p->sParse.nJPRef = 1;
210093  p->sParse.db = p->db;
210094  if( jsonFuncArgMightBeBinary(argv[0]) ){
210095    p->sParse.nBlob = sqlite3_value_bytes(argv[0]);
210096    p->sParse.aBlob = (u8*)sqlite3_value_blob(argv[0]);
210097  }else{
210098    p->sParse.zJson = (char*)sqlite3_value_text(argv[0]);
210099    p->sParse.nJson = sqlite3_value_bytes(argv[0]);
210100    if( p->sParse.zJson==0 ){
210101      p->i = p->iEnd = 0;
210102      return SQLITE_OK;
210103    }
210104    if( jsonConvertTextToBlob(&p->sParse, 0) ){
210105      if( p->sParse.oom ){
210106        return SQLITE_NOMEM;
210107      }
210108      goto json_each_malformed_input;
210109    }
210110  }
210111  if( idxNum==3 ){
210112    zRoot = (const char*)sqlite3_value_text(argv[1]);
210113    if( zRoot==0 ) return SQLITE_OK;
210114    if( zRoot[0]!='$' ){
210115      sqlite3_free(cur->pVtab->zErrMsg);
210116      cur->pVtab->zErrMsg = jsonBadPathError(0, zRoot);
210117      jsonEachCursorReset(p);
210118      return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
210119    }
210120    p->nRoot = sqlite3Strlen30(zRoot);
210121    if( zRoot[1]==0 ){
210122      i = p->i = 0;
210123      p->eType = 0;
210124    }else{
210125      i = jsonLookupStep(&p->sParse, 0, zRoot+1, 0);
210126      if( JSON_LOOKUP_ISERROR(i) ){
210127        if( i==JSON_LOOKUP_NOTFOUND ){
210128          p->i = 0;
210129          p->eType = 0;
210130          p->iEnd = 0;
210131          return SQLITE_OK;
210132        }
210133        sqlite3_free(cur->pVtab->zErrMsg);
210134        cur->pVtab->zErrMsg = jsonBadPathError(0, zRoot);
210135        jsonEachCursorReset(p);
210136        return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
210137      }
210138      if( p->sParse.iLabel ){
210139        p->i = p->sParse.iLabel;
210140        p->eType = JSONB_OBJECT;
210141      }else{
210142        p->i = i;
210143        p->eType = JSONB_ARRAY;
210144      }
210145    }
210146    jsonAppendRaw(&p->path, zRoot, p->nRoot);
210147  }else{
210148    i = p->i = 0;
210149    p->eType = 0;
210150    p->nRoot = 1;
210151    jsonAppendRaw(&p->path, "$", 1);
210152  }
210153  p->nParent = 0;
210154  n = jsonbPayloadSize(&p->sParse, i, &sz);
210155  p->iEnd = i+n+sz;
210156  if( (p->sParse.aBlob[i] & 0x0f)>=JSONB_ARRAY && !p->bRecursive ){
210157    p->i = i + n;
210158    p->eType = p->sParse.aBlob[i] & 0x0f;
210159    p->aParent = sqlite3DbMallocZero(p->db, sizeof(JsonParent));
210160    if( p->aParent==0 ) return SQLITE_NOMEM;
210161    p->nParent = 1;
210162    p->nParentAlloc = 1;
210163    p->aParent[0].iKey = 0;
210164    p->aParent[0].iEnd = p->iEnd;
210165    p->aParent[0].iHead = p->i;
210166    p->aParent[0].iValue = i;
210167  }
210168  return SQLITE_OK;
210169
210170json_each_malformed_input:
210171  sqlite3_free(cur->pVtab->zErrMsg);
210172  cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
210173  jsonEachCursorReset(p);
210174  return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
210175}
210176
210177/* The methods of the json_each virtual table */
210178static sqlite3_module jsonEachModule = {
210179  0,                         /* iVersion */
210180  0,                         /* xCreate */
210181  jsonEachConnect,           /* xConnect */
210182  jsonEachBestIndex,         /* xBestIndex */
210183  jsonEachDisconnect,        /* xDisconnect */
210184  0,                         /* xDestroy */
210185  jsonEachOpenEach,          /* xOpen - open a cursor */
210186  jsonEachClose,             /* xClose - close a cursor */
210187  jsonEachFilter,            /* xFilter - configure scan constraints */
210188  jsonEachNext,              /* xNext - advance a cursor */
210189  jsonEachEof,               /* xEof - check for end of scan */
210190  jsonEachColumn,            /* xColumn - read data */
210191  jsonEachRowid,             /* xRowid - read data */
210192  0,                         /* xUpdate */
210193  0,                         /* xBegin */
210194  0,                         /* xSync */
210195  0,                         /* xCommit */
210196  0,                         /* xRollback */
210197  0,                         /* xFindMethod */
210198  0,                         /* xRename */
210199  0,                         /* xSavepoint */
210200  0,                         /* xRelease */
210201  0,                         /* xRollbackTo */
210202  0,                         /* xShadowName */
210203  0                          /* xIntegrity */
210204};
210205
210206/* The methods of the json_tree virtual table. */
210207static sqlite3_module jsonTreeModule = {
210208  0,                         /* iVersion */
210209  0,                         /* xCreate */
210210  jsonEachConnect,           /* xConnect */
210211  jsonEachBestIndex,         /* xBestIndex */
210212  jsonEachDisconnect,        /* xDisconnect */
210213  0,                         /* xDestroy */
210214  jsonEachOpenTree,          /* xOpen - open a cursor */
210215  jsonEachClose,             /* xClose - close a cursor */
210216  jsonEachFilter,            /* xFilter - configure scan constraints */
210217  jsonEachNext,              /* xNext - advance a cursor */
210218  jsonEachEof,               /* xEof - check for end of scan */
210219  jsonEachColumn,            /* xColumn - read data */
210220  jsonEachRowid,             /* xRowid - read data */
210221  0,                         /* xUpdate */
210222  0,                         /* xBegin */
210223  0,                         /* xSync */
210224  0,                         /* xCommit */
210225  0,                         /* xRollback */
210226  0,                         /* xFindMethod */
210227  0,                         /* xRename */
210228  0,                         /* xSavepoint */
210229  0,                         /* xRelease */
210230  0,                         /* xRollbackTo */
210231  0,                         /* xShadowName */
210232  0                          /* xIntegrity */
210233};
210234#endif /* SQLITE_OMIT_VIRTUALTABLE */
210235#endif /* !defined(SQLITE_OMIT_JSON) */
210236
210237/*
210238** Register JSON functions.
210239*/
210240SQLITE_PRIVATE void sqlite3RegisterJsonFunctions(void){
210241#ifndef SQLITE_OMIT_JSON
210242  static FuncDef aJsonFunc[] = {
210243    /*   sqlite3_result_subtype() ----,  ,--- sqlite3_value_subtype()       */
210244    /*                                |  |                                  */
210245    /*             Uses cache ------, |  | ,---- Returns JSONB              */
210246    /*                              | |  | |                                */
210247    /*     Number of arguments ---, | |  | | ,--- Flags                     */
210248    /*                            | | |  | | |                              */
210249    JFUNCTION(json,               1,1,1, 0,0,0,          jsonRemoveFunc),
210250    JFUNCTION(jsonb,              1,1,0, 0,1,0,          jsonRemoveFunc),
210251    JFUNCTION(json_array,        -1,0,1, 1,0,0,          jsonArrayFunc),
210252    JFUNCTION(jsonb_array,       -1,0,1, 1,1,0,          jsonArrayFunc),
210253    JFUNCTION(json_array_length,  1,1,0, 0,0,0,          jsonArrayLengthFunc),
210254    JFUNCTION(json_array_length,  2,1,0, 0,0,0,          jsonArrayLengthFunc),
210255    JFUNCTION(json_error_position,1,1,0, 0,0,0,          jsonErrorFunc),
210256    JFUNCTION(json_extract,      -1,1,1, 0,0,0,          jsonExtractFunc),
210257    JFUNCTION(jsonb_extract,     -1,1,0, 0,1,0,          jsonExtractFunc),
210258    JFUNCTION(->,                 2,1,1, 0,0,JSON_JSON,  jsonExtractFunc),
210259    JFUNCTION(->>,                2,1,0, 0,0,JSON_SQL,   jsonExtractFunc),
210260    JFUNCTION(json_insert,       -1,1,1, 1,0,0,          jsonSetFunc),
210261    JFUNCTION(jsonb_insert,      -1,1,0, 1,1,0,          jsonSetFunc),
210262    JFUNCTION(json_object,       -1,0,1, 1,0,0,          jsonObjectFunc),
210263    JFUNCTION(jsonb_object,      -1,0,1, 1,1,0,          jsonObjectFunc),
210264    JFUNCTION(json_patch,         2,1,1, 0,0,0,          jsonPatchFunc),
210265    JFUNCTION(jsonb_patch,        2,1,0, 0,1,0,          jsonPatchFunc),
210266    JFUNCTION(json_pretty,        1,1,0, 0,0,0,          jsonPrettyFunc),
210267    JFUNCTION(json_pretty,        2,1,0, 0,0,0,          jsonPrettyFunc),
210268    JFUNCTION(json_quote,         1,0,1, 1,0,0,          jsonQuoteFunc),
210269    JFUNCTION(json_remove,       -1,1,1, 0,0,0,          jsonRemoveFunc),
210270    JFUNCTION(jsonb_remove,      -1,1,0, 0,1,0,          jsonRemoveFunc),
210271    JFUNCTION(json_replace,      -1,1,1, 1,0,0,          jsonReplaceFunc),
210272    JFUNCTION(jsonb_replace,     -1,1,0, 1,1,0,          jsonReplaceFunc),
210273    JFUNCTION(json_set,          -1,1,1, 1,0,JSON_ISSET, jsonSetFunc),
210274    JFUNCTION(jsonb_set,         -1,1,0, 1,1,JSON_ISSET, jsonSetFunc),
210275    JFUNCTION(json_type,          1,1,0, 0,0,0,          jsonTypeFunc),
210276    JFUNCTION(json_type,          2,1,0, 0,0,0,          jsonTypeFunc),
210277    JFUNCTION(json_valid,         1,1,0, 0,0,0,          jsonValidFunc),
210278    JFUNCTION(json_valid,         2,1,0, 0,0,0,          jsonValidFunc),
210279#if SQLITE_DEBUG
210280    JFUNCTION(json_parse,         1,1,0, 0,0,0,          jsonParseFunc),
210281#endif
210282    WAGGREGATE(json_group_array,  1, 0, 0,
210283       jsonArrayStep, jsonArrayFinal, jsonArrayValue, jsonGroupInverse,
210284       SQLITE_SUBTYPE|SQLITE_RESULT_SUBTYPE|SQLITE_UTF8|
210285       SQLITE_DETERMINISTIC),
210286    WAGGREGATE(jsonb_group_array, 1, JSON_BLOB, 0,
210287       jsonArrayStep, jsonArrayFinal, jsonArrayValue, jsonGroupInverse,
210288       SQLITE_SUBTYPE|SQLITE_RESULT_SUBTYPE|SQLITE_UTF8|SQLITE_DETERMINISTIC),
210289    WAGGREGATE(json_group_object, 2, 0, 0,
210290       jsonObjectStep, jsonObjectFinal, jsonObjectValue, jsonGroupInverse,
210291       SQLITE_SUBTYPE|SQLITE_RESULT_SUBTYPE|SQLITE_UTF8|SQLITE_DETERMINISTIC),
210292    WAGGREGATE(jsonb_group_object,2, JSON_BLOB, 0,
210293       jsonObjectStep, jsonObjectFinal, jsonObjectValue, jsonGroupInverse,
210294       SQLITE_SUBTYPE|SQLITE_RESULT_SUBTYPE|SQLITE_UTF8|
210295       SQLITE_DETERMINISTIC)
210296  };
210297  sqlite3InsertBuiltinFuncs(aJsonFunc, ArraySize(aJsonFunc));
210298#endif
210299}
210300
210301#if  !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
210302/*
210303** Register the JSON table-valued functions
210304*/
210305SQLITE_PRIVATE int sqlite3JsonTableFunctions(sqlite3 *db){
210306  int rc = SQLITE_OK;
210307  static const struct {
210308    const char *zName;
210309    sqlite3_module *pModule;
210310  } aMod[] = {
210311    { "json_each",            &jsonEachModule               },
210312    { "json_tree",            &jsonTreeModule               },
210313  };
210314  unsigned int i;
210315  for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
210316    rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
210317  }
210318  return rc;
210319}
210320#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON) */
210321
210322/************** End of json.c ************************************************/
210323/************** Begin file rtree.c *******************************************/
210324/*
210325** 2001 September 15
210326**
210327** The author disclaims copyright to this source code.  In place of
210328** a legal notice, here is a blessing:
210329**
210330**    May you do good and not evil.
210331**    May you find forgiveness for yourself and forgive others.
210332**    May you share freely, never taking more than you give.
210333**
210334*************************************************************************
210335** This file contains code for implementations of the r-tree and r*-tree
210336** algorithms packaged as an SQLite virtual table module.
210337*/
210338
210339/*
210340** Database Format of R-Tree Tables
210341** --------------------------------
210342**
210343** The data structure for a single virtual r-tree table is stored in three
210344** native SQLite tables declared as follows. In each case, the '%' character
210345** in the table name is replaced with the user-supplied name of the r-tree
210346** table.
210347**
210348**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
210349**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
210350**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
210351**
210352** The data for each node of the r-tree structure is stored in the %_node
210353** table. For each node that is not the root node of the r-tree, there is
210354** an entry in the %_parent table associating the node with its parent.
210355** And for each row of data in the table, there is an entry in the %_rowid
210356** table that maps from the entries rowid to the id of the node that it
210357** is stored on.  If the r-tree contains auxiliary columns, those are stored
210358** on the end of the %_rowid table.
210359**
210360** The root node of an r-tree always exists, even if the r-tree table is
210361** empty. The nodeno of the root node is always 1. All other nodes in the
210362** table must be the same size as the root node. The content of each node
210363** is formatted as follows:
210364**
210365**   1. If the node is the root node (node 1), then the first 2 bytes
210366**      of the node contain the tree depth as a big-endian integer.
210367**      For non-root nodes, the first 2 bytes are left unused.
210368**
210369**   2. The next 2 bytes contain the number of entries currently
210370**      stored in the node.
210371**
210372**   3. The remainder of the node contains the node entries. Each entry
210373**      consists of a single 8-byte integer followed by an even number
210374**      of 4-byte coordinates. For leaf nodes the integer is the rowid
210375**      of a record. For internal nodes it is the node number of a
210376**      child page.
210377*/
210378
210379#if !defined(SQLITE_CORE) \
210380  || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE))
210381
210382#ifndef SQLITE_CORE
210383/*   #include "sqlite3ext.h" */
210384  SQLITE_EXTENSION_INIT1
210385#else
210386/*   #include "sqlite3.h" */
210387#endif
210388SQLITE_PRIVATE int sqlite3GetToken(const unsigned char*,int*); /* In the SQLite core */
210389
210390/*
210391** If building separately, we will need some setup that is normally
210392** found in sqliteInt.h
210393*/
210394#if !defined(SQLITE_AMALGAMATION)
210395#include "sqlite3rtree.h"
210396typedef sqlite3_int64 i64;
210397typedef sqlite3_uint64 u64;
210398typedef unsigned char u8;
210399typedef unsigned short u16;
210400typedef unsigned int u32;
210401#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
210402# define NDEBUG 1
210403#endif
210404#if defined(NDEBUG) && defined(SQLITE_DEBUG)
210405# undef NDEBUG
210406#endif
210407#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
210408# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
210409#endif
210410#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
210411# define ALWAYS(X)      (1)
210412# define NEVER(X)       (0)
210413#elif !defined(NDEBUG)
210414# define ALWAYS(X)      ((X)?1:(assert(0),0))
210415# define NEVER(X)       ((X)?(assert(0),1):0)
210416#else
210417# define ALWAYS(X)      (X)
210418# define NEVER(X)       (X)
210419#endif
210420#endif /* !defined(SQLITE_AMALGAMATION) */
210421
210422/* Macro to check for 4-byte alignment.  Only used inside of assert() */
210423#ifdef SQLITE_DEBUG
210424# define FOUR_BYTE_ALIGNED(X)  ((((char*)(X) - (char*)0) & 3)==0)
210425#endif
210426
210427/* #include <string.h> */
210428/* #include <stdio.h> */
210429/* #include <assert.h> */
210430/* #include <stdlib.h> */
210431
210432/*  The following macro is used to suppress compiler warnings.
210433*/
210434#ifndef UNUSED_PARAMETER
210435# define UNUSED_PARAMETER(x) (void)(x)
210436#endif
210437
210438typedef struct Rtree Rtree;
210439typedef struct RtreeCursor RtreeCursor;
210440typedef struct RtreeNode RtreeNode;
210441typedef struct RtreeCell RtreeCell;
210442typedef struct RtreeConstraint RtreeConstraint;
210443typedef struct RtreeMatchArg RtreeMatchArg;
210444typedef struct RtreeGeomCallback RtreeGeomCallback;
210445typedef union RtreeCoord RtreeCoord;
210446typedef struct RtreeSearchPoint RtreeSearchPoint;
210447
210448/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
210449#define RTREE_MAX_DIMENSIONS 5
210450
210451/* Maximum number of auxiliary columns */
210452#define RTREE_MAX_AUX_COLUMN 100
210453
210454/* Size of hash table Rtree.aHash. This hash table is not expected to
210455** ever contain very many entries, so a fixed number of buckets is
210456** used.
210457*/
210458#define HASHSIZE 97
210459
210460/* The xBestIndex method of this virtual table requires an estimate of
210461** the number of rows in the virtual table to calculate the costs of
210462** various strategies. If possible, this estimate is loaded from the
210463** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
210464** Otherwise, if no sqlite_stat1 entry is available, use
210465** RTREE_DEFAULT_ROWEST.
210466*/
210467#define RTREE_DEFAULT_ROWEST 1048576
210468#define RTREE_MIN_ROWEST         100
210469
210470/*
210471** An rtree virtual-table object.
210472*/
210473struct Rtree {
210474  sqlite3_vtab base;          /* Base class.  Must be first */
210475  sqlite3 *db;                /* Host database connection */
210476  int iNodeSize;              /* Size in bytes of each node in the node table */
210477  u8 nDim;                    /* Number of dimensions */
210478  u8 nDim2;                   /* Twice the number of dimensions */
210479  u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
210480  u8 nBytesPerCell;           /* Bytes consumed per cell */
210481  u8 inWrTrans;               /* True if inside write transaction */
210482  u8 nAux;                    /* # of auxiliary columns in %_rowid */
210483#ifdef SQLITE_ENABLE_GEOPOLY
210484  u8 nAuxNotNull;             /* Number of initial not-null aux columns */
210485#endif
210486#ifdef SQLITE_DEBUG
210487  u8 bCorrupt;                /* Shadow table corruption detected */
210488#endif
210489  int iDepth;                 /* Current depth of the r-tree structure */
210490  char *zDb;                  /* Name of database containing r-tree table */
210491  char *zName;                /* Name of r-tree table */
210492  char *zNodeName;            /* Name of the %_node table */
210493  u32 nBusy;                  /* Current number of users of this structure */
210494  i64 nRowEst;                /* Estimated number of rows in this table */
210495  u32 nCursor;                /* Number of open cursors */
210496  u32 nNodeRef;               /* Number RtreeNodes with positive nRef */
210497  char *zReadAuxSql;          /* SQL for statement to read aux data */
210498
210499  /* List of nodes removed during a CondenseTree operation. List is
210500  ** linked together via the pointer normally used for hash chains -
210501  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
210502  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
210503  */
210504  RtreeNode *pDeleted;
210505
210506  /* Blob I/O on xxx_node */
210507  sqlite3_blob *pNodeBlob;
210508
210509  /* Statements to read/write/delete a record from xxx_node */
210510  sqlite3_stmt *pWriteNode;
210511  sqlite3_stmt *pDeleteNode;
210512
210513  /* Statements to read/write/delete a record from xxx_rowid */
210514  sqlite3_stmt *pReadRowid;
210515  sqlite3_stmt *pWriteRowid;
210516  sqlite3_stmt *pDeleteRowid;
210517
210518  /* Statements to read/write/delete a record from xxx_parent */
210519  sqlite3_stmt *pReadParent;
210520  sqlite3_stmt *pWriteParent;
210521  sqlite3_stmt *pDeleteParent;
210522
210523  /* Statement for writing to the "aux:" fields, if there are any */
210524  sqlite3_stmt *pWriteAux;
210525
210526  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
210527};
210528
210529/* Possible values for Rtree.eCoordType: */
210530#define RTREE_COORD_REAL32 0
210531#define RTREE_COORD_INT32  1
210532
210533/*
210534** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
210535** only deal with integer coordinates.  No floating point operations
210536** will be done.
210537*/
210538#ifdef SQLITE_RTREE_INT_ONLY
210539  typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
210540  typedef int RtreeValue;                  /* Low accuracy coordinate */
210541# define RTREE_ZERO 0
210542#else
210543  typedef double RtreeDValue;              /* High accuracy coordinate */
210544  typedef float RtreeValue;                /* Low accuracy coordinate */
210545# define RTREE_ZERO 0.0
210546#endif
210547
210548/*
210549** Set the Rtree.bCorrupt flag
210550*/
210551#ifdef SQLITE_DEBUG
210552# define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1)
210553#else
210554# define RTREE_IS_CORRUPT(X)
210555#endif
210556
210557/*
210558** When doing a search of an r-tree, instances of the following structure
210559** record intermediate results from the tree walk.
210560**
210561** The id is always a node-id.  For iLevel>=1 the id is the node-id of
210562** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
210563** the id is of the parent node and the cell that RtreeSearchPoint
210564** represents is the iCell-th entry in the parent node.
210565*/
210566struct RtreeSearchPoint {
210567  RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
210568  sqlite3_int64 id;      /* Node ID */
210569  u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
210570  u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
210571  u8 iCell;              /* Cell index within the node */
210572};
210573
210574/*
210575** The minimum number of cells allowed for a node is a third of the
210576** maximum. In Gutman's notation:
210577**
210578**     m = M/3
210579**
210580** If an R*-tree "Reinsert" operation is required, the same number of
210581** cells are removed from the overfull node and reinserted into the tree.
210582*/
210583#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
210584#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
210585#define RTREE_MAXCELLS 51
210586
210587/*
210588** The smallest possible node-size is (512-64)==448 bytes. And the largest
210589** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
210590** Therefore all non-root nodes must contain at least 3 entries. Since
210591** 3^40 is greater than 2^64, an r-tree structure always has a depth of
210592** 40 or less.
210593*/
210594#define RTREE_MAX_DEPTH 40
210595
210596
210597/*
210598** Number of entries in the cursor RtreeNode cache.  The first entry is
210599** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
210600** entries cache the RtreeNode for the first elements of the priority queue.
210601*/
210602#define RTREE_CACHE_SZ  5
210603
210604/*
210605** An rtree cursor object.
210606*/
210607struct RtreeCursor {
210608  sqlite3_vtab_cursor base;         /* Base class.  Must be first */
210609  u8 atEOF;                         /* True if at end of search */
210610  u8 bPoint;                        /* True if sPoint is valid */
210611  u8 bAuxValid;                     /* True if pReadAux is valid */
210612  int iStrategy;                    /* Copy of idxNum search parameter */
210613  int nConstraint;                  /* Number of entries in aConstraint */
210614  RtreeConstraint *aConstraint;     /* Search constraints. */
210615  int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
210616  int nPoint;                       /* Number of slots used in aPoint[] */
210617  int mxLevel;                      /* iLevel value for root of the tree */
210618  RtreeSearchPoint *aPoint;         /* Priority queue for search points */
210619  sqlite3_stmt *pReadAux;           /* Statement to read aux-data */
210620  RtreeSearchPoint sPoint;          /* Cached next search point */
210621  RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
210622  u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
210623};
210624
210625/* Return the Rtree of a RtreeCursor */
210626#define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
210627
210628/*
210629** A coordinate can be either a floating point number or a integer.  All
210630** coordinates within a single R-Tree are always of the same time.
210631*/
210632union RtreeCoord {
210633  RtreeValue f;      /* Floating point value */
210634  int i;             /* Integer value */
210635  u32 u;             /* Unsigned for byte-order conversions */
210636};
210637
210638/*
210639** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
210640** formatted as a RtreeDValue (double or int64). This macro assumes that local
210641** variable pRtree points to the Rtree structure associated with the
210642** RtreeCoord.
210643*/
210644#ifdef SQLITE_RTREE_INT_ONLY
210645# define DCOORD(coord) ((RtreeDValue)coord.i)
210646#else
210647# define DCOORD(coord) (                           \
210648    (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
210649      ((double)coord.f) :                           \
210650      ((double)coord.i)                             \
210651  )
210652#endif
210653
210654/*
210655** A search constraint.
210656*/
210657struct RtreeConstraint {
210658  int iCoord;                     /* Index of constrained coordinate */
210659  int op;                         /* Constraining operation */
210660  union {
210661    RtreeDValue rValue;             /* Constraint value. */
210662    int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
210663    int (*xQueryFunc)(sqlite3_rtree_query_info*);
210664  } u;
210665  sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
210666};
210667
210668/* Possible values for RtreeConstraint.op */
210669#define RTREE_EQ    0x41  /* A */
210670#define RTREE_LE    0x42  /* B */
210671#define RTREE_LT    0x43  /* C */
210672#define RTREE_GE    0x44  /* D */
210673#define RTREE_GT    0x45  /* E */
210674#define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
210675#define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
210676
210677/* Special operators available only on cursors.  Needs to be consecutive
210678** with the normal values above, but must be less than RTREE_MATCH.  These
210679** are used in the cursor for contraints such as x=NULL (RTREE_FALSE) or
210680** x<'xyz' (RTREE_TRUE) */
210681#define RTREE_TRUE  0x3f  /* ? */
210682#define RTREE_FALSE 0x40  /* @ */
210683
210684/*
210685** An rtree structure node.
210686*/
210687struct RtreeNode {
210688  RtreeNode *pParent;         /* Parent node */
210689  i64 iNode;                  /* The node number */
210690  int nRef;                   /* Number of references to this node */
210691  int isDirty;                /* True if the node needs to be written to disk */
210692  u8 *zData;                  /* Content of the node, as should be on disk */
210693  RtreeNode *pNext;           /* Next node in this hash collision chain */
210694};
210695
210696/* Return the number of cells in a node  */
210697#define NCELL(pNode) readInt16(&(pNode)->zData[2])
210698
210699/*
210700** A single cell from a node, deserialized
210701*/
210702struct RtreeCell {
210703  i64 iRowid;                                 /* Node or entry ID */
210704  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
210705};
210706
210707
210708/*
210709** This object becomes the sqlite3_user_data() for the SQL functions
210710** that are created by sqlite3_rtree_geometry_callback() and
210711** sqlite3_rtree_query_callback() and which appear on the right of MATCH
210712** operators in order to constrain a search.
210713**
210714** xGeom and xQueryFunc are the callback functions.  Exactly one of
210715** xGeom and xQueryFunc fields is non-NULL, depending on whether the
210716** SQL function was created using sqlite3_rtree_geometry_callback() or
210717** sqlite3_rtree_query_callback().
210718**
210719** This object is deleted automatically by the destructor mechanism in
210720** sqlite3_create_function_v2().
210721*/
210722struct RtreeGeomCallback {
210723  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
210724  int (*xQueryFunc)(sqlite3_rtree_query_info*);
210725  void (*xDestructor)(void*);
210726  void *pContext;
210727};
210728
210729/*
210730** An instance of this structure (in the form of a BLOB) is returned by
210731** the SQL functions that sqlite3_rtree_geometry_callback() and
210732** sqlite3_rtree_query_callback() create, and is read as the right-hand
210733** operand to the MATCH operator of an R-Tree.
210734*/
210735struct RtreeMatchArg {
210736  u32 iSize;                  /* Size of this object */
210737  RtreeGeomCallback cb;       /* Info about the callback functions */
210738  int nParam;                 /* Number of parameters to the SQL function */
210739  sqlite3_value **apSqlParam; /* Original SQL parameter values */
210740  RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
210741};
210742
210743#ifndef MAX
210744# define MAX(x,y) ((x) < (y) ? (y) : (x))
210745#endif
210746#ifndef MIN
210747# define MIN(x,y) ((x) > (y) ? (y) : (x))
210748#endif
210749
210750/* What version of GCC is being used.  0 means GCC is not being used .
210751** Note that the GCC_VERSION macro will also be set correctly when using
210752** clang, since clang works hard to be gcc compatible.  So the gcc
210753** optimizations will also work when compiling with clang.
210754*/
210755#ifndef GCC_VERSION
210756#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
210757# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
210758#else
210759# define GCC_VERSION 0
210760#endif
210761#endif
210762
210763/* The testcase() macro should already be defined in the amalgamation.  If
210764** it is not, make it a no-op.
210765*/
210766#ifndef SQLITE_AMALGAMATION
210767# if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
210768    unsigned int sqlite3RtreeTestcase = 0;
210769#   define testcase(X)  if( X ){ sqlite3RtreeTestcase += __LINE__; }
210770# else
210771#   define testcase(X)
210772# endif
210773#endif
210774
210775/*
210776** Make sure that the compiler intrinsics we desire are enabled when
210777** compiling with an appropriate version of MSVC unless prevented by
210778** the SQLITE_DISABLE_INTRINSIC define.
210779*/
210780#if !defined(SQLITE_DISABLE_INTRINSIC)
210781#  if defined(_MSC_VER) && _MSC_VER>=1400
210782#    if !defined(_WIN32_WCE)
210783/* #      include <intrin.h> */
210784#      pragma intrinsic(_byteswap_ulong)
210785#      pragma intrinsic(_byteswap_uint64)
210786#    else
210787/* #      include <cmnintrin.h> */
210788#    endif
210789#  endif
210790#endif
210791
210792/*
210793** Macros to determine whether the machine is big or little endian,
210794** and whether or not that determination is run-time or compile-time.
210795**
210796** For best performance, an attempt is made to guess at the byte-order
210797** using C-preprocessor macros.  If that is unsuccessful, or if
210798** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
210799** at run-time.
210800*/
210801#ifndef SQLITE_BYTEORDER /* Replicate changes at tag-20230904a */
210802# if defined(__BYTE_ORDER__) && __BYTE_ORDER__==__ORDER_BIG_ENDIAN__
210803#   define SQLITE_BYTEORDER 4321
210804# elif defined(__BYTE_ORDER__) && __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__
210805#   define SQLITE_BYTEORDER 1234
210806# elif defined(__BIG_ENDIAN__) && __BIG_ENDIAN__==1
210807#   define SQLITE_BYTEORDER 4321
210808# elif defined(i386)    || defined(__i386__)      || defined(_M_IX86) ||    \
210809     defined(__x86_64)  || defined(__x86_64__)    || defined(_M_X64)  ||    \
210810     defined(_M_AMD64)  || defined(_M_ARM)        || defined(__x86)   ||    \
210811     defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
210812#   define SQLITE_BYTEORDER 1234
210813# elif defined(sparc)   || defined(__ARMEB__)     || defined(__AARCH64EB__)
210814#   define SQLITE_BYTEORDER 4321
210815# else
210816#   define SQLITE_BYTEORDER 0
210817# endif
210818#endif
210819
210820
210821/* What version of MSVC is being used.  0 means MSVC is not being used */
210822#ifndef MSVC_VERSION
210823#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
210824# define MSVC_VERSION _MSC_VER
210825#else
210826# define MSVC_VERSION 0
210827#endif
210828#endif
210829
210830/*
210831** Functions to deserialize a 16 bit integer, 32 bit real number and
210832** 64 bit integer. The deserialized value is returned.
210833*/
210834static int readInt16(u8 *p){
210835  return (p[0]<<8) + p[1];
210836}
210837static void readCoord(u8 *p, RtreeCoord *pCoord){
210838  assert( FOUR_BYTE_ALIGNED(p) );
210839#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
210840  pCoord->u = _byteswap_ulong(*(u32*)p);
210841#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
210842  pCoord->u = __builtin_bswap32(*(u32*)p);
210843#elif SQLITE_BYTEORDER==4321
210844  pCoord->u = *(u32*)p;
210845#else
210846  pCoord->u = (
210847    (((u32)p[0]) << 24) +
210848    (((u32)p[1]) << 16) +
210849    (((u32)p[2]) <<  8) +
210850    (((u32)p[3]) <<  0)
210851  );
210852#endif
210853}
210854static i64 readInt64(u8 *p){
210855#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
210856  u64 x;
210857  memcpy(&x, p, 8);
210858  return (i64)_byteswap_uint64(x);
210859#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
210860  u64 x;
210861  memcpy(&x, p, 8);
210862  return (i64)__builtin_bswap64(x);
210863#elif SQLITE_BYTEORDER==4321
210864  i64 x;
210865  memcpy(&x, p, 8);
210866  return x;
210867#else
210868  return (i64)(
210869    (((u64)p[0]) << 56) +
210870    (((u64)p[1]) << 48) +
210871    (((u64)p[2]) << 40) +
210872    (((u64)p[3]) << 32) +
210873    (((u64)p[4]) << 24) +
210874    (((u64)p[5]) << 16) +
210875    (((u64)p[6]) <<  8) +
210876    (((u64)p[7]) <<  0)
210877  );
210878#endif
210879}
210880
210881/*
210882** Functions to serialize a 16 bit integer, 32 bit real number and
210883** 64 bit integer. The value returned is the number of bytes written
210884** to the argument buffer (always 2, 4 and 8 respectively).
210885*/
210886static void writeInt16(u8 *p, int i){
210887  p[0] = (i>> 8)&0xFF;
210888  p[1] = (i>> 0)&0xFF;
210889}
210890static int writeCoord(u8 *p, RtreeCoord *pCoord){
210891  u32 i;
210892  assert( FOUR_BYTE_ALIGNED(p) );
210893  assert( sizeof(RtreeCoord)==4 );
210894  assert( sizeof(u32)==4 );
210895#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
210896  i = __builtin_bswap32(pCoord->u);
210897  memcpy(p, &i, 4);
210898#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
210899  i = _byteswap_ulong(pCoord->u);
210900  memcpy(p, &i, 4);
210901#elif SQLITE_BYTEORDER==4321
210902  i = pCoord->u;
210903  memcpy(p, &i, 4);
210904#else
210905  i = pCoord->u;
210906  p[0] = (i>>24)&0xFF;
210907  p[1] = (i>>16)&0xFF;
210908  p[2] = (i>> 8)&0xFF;
210909  p[3] = (i>> 0)&0xFF;
210910#endif
210911  return 4;
210912}
210913static int writeInt64(u8 *p, i64 i){
210914#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
210915  i = (i64)__builtin_bswap64((u64)i);
210916  memcpy(p, &i, 8);
210917#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
210918  i = (i64)_byteswap_uint64((u64)i);
210919  memcpy(p, &i, 8);
210920#elif SQLITE_BYTEORDER==4321
210921  memcpy(p, &i, 8);
210922#else
210923  p[0] = (i>>56)&0xFF;
210924  p[1] = (i>>48)&0xFF;
210925  p[2] = (i>>40)&0xFF;
210926  p[3] = (i>>32)&0xFF;
210927  p[4] = (i>>24)&0xFF;
210928  p[5] = (i>>16)&0xFF;
210929  p[6] = (i>> 8)&0xFF;
210930  p[7] = (i>> 0)&0xFF;
210931#endif
210932  return 8;
210933}
210934
210935/*
210936** Increment the reference count of node p.
210937*/
210938static void nodeReference(RtreeNode *p){
210939  if( p ){
210940    assert( p->nRef>0 );
210941    p->nRef++;
210942  }
210943}
210944
210945/*
210946** Clear the content of node p (set all bytes to 0x00).
210947*/
210948static void nodeZero(Rtree *pRtree, RtreeNode *p){
210949  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
210950  p->isDirty = 1;
210951}
210952
210953/*
210954** Given a node number iNode, return the corresponding key to use
210955** in the Rtree.aHash table.
210956*/
210957static unsigned int nodeHash(i64 iNode){
210958  return ((unsigned)iNode) % HASHSIZE;
210959}
210960
210961/*
210962** Search the node hash table for node iNode. If found, return a pointer
210963** to it. Otherwise, return 0.
210964*/
210965static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
210966  RtreeNode *p;
210967  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
210968  return p;
210969}
210970
210971/*
210972** Add node pNode to the node hash table.
210973*/
210974static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
210975  int iHash;
210976  assert( pNode->pNext==0 );
210977  iHash = nodeHash(pNode->iNode);
210978  pNode->pNext = pRtree->aHash[iHash];
210979  pRtree->aHash[iHash] = pNode;
210980}
210981
210982/*
210983** Remove node pNode from the node hash table.
210984*/
210985static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
210986  RtreeNode **pp;
210987  if( pNode->iNode!=0 ){
210988    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
210989    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
210990    *pp = pNode->pNext;
210991    pNode->pNext = 0;
210992  }
210993}
210994
210995/*
210996** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
210997** indicating that node has not yet been assigned a node number. It is
210998** assigned a node number when nodeWrite() is called to write the
210999** node contents out to the database.
211000*/
211001static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
211002  RtreeNode *pNode;
211003  pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize);
211004  if( pNode ){
211005    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
211006    pNode->zData = (u8 *)&pNode[1];
211007    pNode->nRef = 1;
211008    pRtree->nNodeRef++;
211009    pNode->pParent = pParent;
211010    pNode->isDirty = 1;
211011    nodeReference(pParent);
211012  }
211013  return pNode;
211014}
211015
211016/*
211017** Clear the Rtree.pNodeBlob object
211018*/
211019static void nodeBlobReset(Rtree *pRtree){
211020  sqlite3_blob *pBlob = pRtree->pNodeBlob;
211021  pRtree->pNodeBlob = 0;
211022  sqlite3_blob_close(pBlob);
211023}
211024
211025/*
211026** Obtain a reference to an r-tree node.
211027*/
211028static int nodeAcquire(
211029  Rtree *pRtree,             /* R-tree structure */
211030  i64 iNode,                 /* Node number to load */
211031  RtreeNode *pParent,        /* Either the parent node or NULL */
211032  RtreeNode **ppNode         /* OUT: Acquired node */
211033){
211034  int rc = SQLITE_OK;
211035  RtreeNode *pNode = 0;
211036
211037  /* Check if the requested node is already in the hash table. If so,
211038  ** increase its reference count and return it.
211039  */
211040  if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
211041    if( pParent && ALWAYS(pParent!=pNode->pParent) ){
211042      RTREE_IS_CORRUPT(pRtree);
211043      return SQLITE_CORRUPT_VTAB;
211044    }
211045    pNode->nRef++;
211046    *ppNode = pNode;
211047    return SQLITE_OK;
211048  }
211049
211050  if( pRtree->pNodeBlob ){
211051    sqlite3_blob *pBlob = pRtree->pNodeBlob;
211052    pRtree->pNodeBlob = 0;
211053    rc = sqlite3_blob_reopen(pBlob, iNode);
211054    pRtree->pNodeBlob = pBlob;
211055    if( rc ){
211056      nodeBlobReset(pRtree);
211057      if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
211058    }
211059  }
211060  if( pRtree->pNodeBlob==0 ){
211061    rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, pRtree->zNodeName,
211062                           "data", iNode, 0,
211063                           &pRtree->pNodeBlob);
211064  }
211065  if( rc ){
211066    *ppNode = 0;
211067    /* If unable to open an sqlite3_blob on the desired row, that can only
211068    ** be because the shadow tables hold erroneous data. */
211069    if( rc==SQLITE_ERROR ){
211070      rc = SQLITE_CORRUPT_VTAB;
211071      RTREE_IS_CORRUPT(pRtree);
211072    }
211073  }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
211074    pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);
211075    if( !pNode ){
211076      rc = SQLITE_NOMEM;
211077    }else{
211078      pNode->pParent = pParent;
211079      pNode->zData = (u8 *)&pNode[1];
211080      pNode->nRef = 1;
211081      pRtree->nNodeRef++;
211082      pNode->iNode = iNode;
211083      pNode->isDirty = 0;
211084      pNode->pNext = 0;
211085      rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
211086                             pRtree->iNodeSize, 0);
211087    }
211088  }
211089
211090  /* If the root node was just loaded, set pRtree->iDepth to the height
211091  ** of the r-tree structure. A height of zero means all data is stored on
211092  ** the root node. A height of one means the children of the root node
211093  ** are the leaves, and so on. If the depth as specified on the root node
211094  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
211095  */
211096  if( rc==SQLITE_OK && pNode && iNode==1 ){
211097    pRtree->iDepth = readInt16(pNode->zData);
211098    if( pRtree->iDepth>RTREE_MAX_DEPTH ){
211099      rc = SQLITE_CORRUPT_VTAB;
211100      RTREE_IS_CORRUPT(pRtree);
211101    }
211102  }
211103
211104  /* If no error has occurred so far, check if the "number of entries"
211105  ** field on the node is too large. If so, set the return code to
211106  ** SQLITE_CORRUPT_VTAB.
211107  */
211108  if( pNode && rc==SQLITE_OK ){
211109    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
211110      rc = SQLITE_CORRUPT_VTAB;
211111      RTREE_IS_CORRUPT(pRtree);
211112    }
211113  }
211114
211115  if( rc==SQLITE_OK ){
211116    if( pNode!=0 ){
211117      nodeReference(pParent);
211118      nodeHashInsert(pRtree, pNode);
211119    }else{
211120      rc = SQLITE_CORRUPT_VTAB;
211121      RTREE_IS_CORRUPT(pRtree);
211122    }
211123    *ppNode = pNode;
211124  }else{
211125    nodeBlobReset(pRtree);
211126    if( pNode ){
211127      pRtree->nNodeRef--;
211128      sqlite3_free(pNode);
211129    }
211130    *ppNode = 0;
211131  }
211132
211133  return rc;
211134}
211135
211136/*
211137** Overwrite cell iCell of node pNode with the contents of pCell.
211138*/
211139static void nodeOverwriteCell(
211140  Rtree *pRtree,             /* The overall R-Tree */
211141  RtreeNode *pNode,          /* The node into which the cell is to be written */
211142  RtreeCell *pCell,          /* The cell to write */
211143  int iCell                  /* Index into pNode into which pCell is written */
211144){
211145  int ii;
211146  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
211147  p += writeInt64(p, pCell->iRowid);
211148  for(ii=0; ii<pRtree->nDim2; ii++){
211149    p += writeCoord(p, &pCell->aCoord[ii]);
211150  }
211151  pNode->isDirty = 1;
211152}
211153
211154/*
211155** Remove the cell with index iCell from node pNode.
211156*/
211157static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
211158  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
211159  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
211160  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
211161  memmove(pDst, pSrc, nByte);
211162  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
211163  pNode->isDirty = 1;
211164}
211165
211166/*
211167** Insert the contents of cell pCell into node pNode. If the insert
211168** is successful, return SQLITE_OK.
211169**
211170** If there is not enough free space in pNode, return SQLITE_FULL.
211171*/
211172static int nodeInsertCell(
211173  Rtree *pRtree,                /* The overall R-Tree */
211174  RtreeNode *pNode,             /* Write new cell into this node */
211175  RtreeCell *pCell              /* The cell to be inserted */
211176){
211177  int nCell;                    /* Current number of cells in pNode */
211178  int nMaxCell;                 /* Maximum number of cells for pNode */
211179
211180  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
211181  nCell = NCELL(pNode);
211182
211183  assert( nCell<=nMaxCell );
211184  if( nCell<nMaxCell ){
211185    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
211186    writeInt16(&pNode->zData[2], nCell+1);
211187    pNode->isDirty = 1;
211188  }
211189
211190  return (nCell==nMaxCell);
211191}
211192
211193/*
211194** If the node is dirty, write it out to the database.
211195*/
211196static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
211197  int rc = SQLITE_OK;
211198  if( pNode->isDirty ){
211199    sqlite3_stmt *p = pRtree->pWriteNode;
211200    if( pNode->iNode ){
211201      sqlite3_bind_int64(p, 1, pNode->iNode);
211202    }else{
211203      sqlite3_bind_null(p, 1);
211204    }
211205    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
211206    sqlite3_step(p);
211207    pNode->isDirty = 0;
211208    rc = sqlite3_reset(p);
211209    sqlite3_bind_null(p, 2);
211210    if( pNode->iNode==0 && rc==SQLITE_OK ){
211211      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
211212      nodeHashInsert(pRtree, pNode);
211213    }
211214  }
211215  return rc;
211216}
211217
211218/*
211219** Release a reference to a node. If the node is dirty and the reference
211220** count drops to zero, the node data is written to the database.
211221*/
211222static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
211223  int rc = SQLITE_OK;
211224  if( pNode ){
211225    assert( pNode->nRef>0 );
211226    assert( pRtree->nNodeRef>0 );
211227    pNode->nRef--;
211228    if( pNode->nRef==0 ){
211229      pRtree->nNodeRef--;
211230      if( pNode->iNode==1 ){
211231        pRtree->iDepth = -1;
211232      }
211233      if( pNode->pParent ){
211234        rc = nodeRelease(pRtree, pNode->pParent);
211235      }
211236      if( rc==SQLITE_OK ){
211237        rc = nodeWrite(pRtree, pNode);
211238      }
211239      nodeHashDelete(pRtree, pNode);
211240      sqlite3_free(pNode);
211241    }
211242  }
211243  return rc;
211244}
211245
211246/*
211247** Return the 64-bit integer value associated with cell iCell of
211248** node pNode. If pNode is a leaf node, this is a rowid. If it is
211249** an internal node, then the 64-bit integer is a child page number.
211250*/
211251static i64 nodeGetRowid(
211252  Rtree *pRtree,       /* The overall R-Tree */
211253  RtreeNode *pNode,    /* The node from which to extract the ID */
211254  int iCell            /* The cell index from which to extract the ID */
211255){
211256  assert( iCell<NCELL(pNode) );
211257  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
211258}
211259
211260/*
211261** Return coordinate iCoord from cell iCell in node pNode.
211262*/
211263static void nodeGetCoord(
211264  Rtree *pRtree,               /* The overall R-Tree */
211265  RtreeNode *pNode,            /* The node from which to extract a coordinate */
211266  int iCell,                   /* The index of the cell within the node */
211267  int iCoord,                  /* Which coordinate to extract */
211268  RtreeCoord *pCoord           /* OUT: Space to write result to */
211269){
211270  assert( iCell<NCELL(pNode) );
211271  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
211272}
211273
211274/*
211275** Deserialize cell iCell of node pNode. Populate the structure pointed
211276** to by pCell with the results.
211277*/
211278static void nodeGetCell(
211279  Rtree *pRtree,               /* The overall R-Tree */
211280  RtreeNode *pNode,            /* The node containing the cell to be read */
211281  int iCell,                   /* Index of the cell within the node */
211282  RtreeCell *pCell             /* OUT: Write the cell contents here */
211283){
211284  u8 *pData;
211285  RtreeCoord *pCoord;
211286  int ii = 0;
211287  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
211288  pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
211289  pCoord = pCell->aCoord;
211290  do{
211291    readCoord(pData, &pCoord[ii]);
211292    readCoord(pData+4, &pCoord[ii+1]);
211293    pData += 8;
211294    ii += 2;
211295  }while( ii<pRtree->nDim2 );
211296}
211297
211298
211299/* Forward declaration for the function that does the work of
211300** the virtual table module xCreate() and xConnect() methods.
211301*/
211302static int rtreeInit(
211303  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
211304);
211305
211306/*
211307** Rtree virtual table module xCreate method.
211308*/
211309static int rtreeCreate(
211310  sqlite3 *db,
211311  void *pAux,
211312  int argc, const char *const*argv,
211313  sqlite3_vtab **ppVtab,
211314  char **pzErr
211315){
211316  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
211317}
211318
211319/*
211320** Rtree virtual table module xConnect method.
211321*/
211322static int rtreeConnect(
211323  sqlite3 *db,
211324  void *pAux,
211325  int argc, const char *const*argv,
211326  sqlite3_vtab **ppVtab,
211327  char **pzErr
211328){
211329  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
211330}
211331
211332/*
211333** Increment the r-tree reference count.
211334*/
211335static void rtreeReference(Rtree *pRtree){
211336  pRtree->nBusy++;
211337}
211338
211339/*
211340** Decrement the r-tree reference count. When the reference count reaches
211341** zero the structure is deleted.
211342*/
211343static void rtreeRelease(Rtree *pRtree){
211344  pRtree->nBusy--;
211345  if( pRtree->nBusy==0 ){
211346    pRtree->inWrTrans = 0;
211347    assert( pRtree->nCursor==0 );
211348    nodeBlobReset(pRtree);
211349    assert( pRtree->nNodeRef==0 || pRtree->bCorrupt );
211350    sqlite3_finalize(pRtree->pWriteNode);
211351    sqlite3_finalize(pRtree->pDeleteNode);
211352    sqlite3_finalize(pRtree->pReadRowid);
211353    sqlite3_finalize(pRtree->pWriteRowid);
211354    sqlite3_finalize(pRtree->pDeleteRowid);
211355    sqlite3_finalize(pRtree->pReadParent);
211356    sqlite3_finalize(pRtree->pWriteParent);
211357    sqlite3_finalize(pRtree->pDeleteParent);
211358    sqlite3_finalize(pRtree->pWriteAux);
211359    sqlite3_free(pRtree->zReadAuxSql);
211360    sqlite3_free(pRtree);
211361  }
211362}
211363
211364/*
211365** Rtree virtual table module xDisconnect method.
211366*/
211367static int rtreeDisconnect(sqlite3_vtab *pVtab){
211368  rtreeRelease((Rtree *)pVtab);
211369  return SQLITE_OK;
211370}
211371
211372/*
211373** Rtree virtual table module xDestroy method.
211374*/
211375static int rtreeDestroy(sqlite3_vtab *pVtab){
211376  Rtree *pRtree = (Rtree *)pVtab;
211377  int rc;
211378  char *zCreate = sqlite3_mprintf(
211379    "DROP TABLE '%q'.'%q_node';"
211380    "DROP TABLE '%q'.'%q_rowid';"
211381    "DROP TABLE '%q'.'%q_parent';",
211382    pRtree->zDb, pRtree->zName,
211383    pRtree->zDb, pRtree->zName,
211384    pRtree->zDb, pRtree->zName
211385  );
211386  if( !zCreate ){
211387    rc = SQLITE_NOMEM;
211388  }else{
211389    nodeBlobReset(pRtree);
211390    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
211391    sqlite3_free(zCreate);
211392  }
211393  if( rc==SQLITE_OK ){
211394    rtreeRelease(pRtree);
211395  }
211396
211397  return rc;
211398}
211399
211400/*
211401** Rtree virtual table module xOpen method.
211402*/
211403static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
211404  int rc = SQLITE_NOMEM;
211405  Rtree *pRtree = (Rtree *)pVTab;
211406  RtreeCursor *pCsr;
211407
211408  pCsr = (RtreeCursor *)sqlite3_malloc64(sizeof(RtreeCursor));
211409  if( pCsr ){
211410    memset(pCsr, 0, sizeof(RtreeCursor));
211411    pCsr->base.pVtab = pVTab;
211412    rc = SQLITE_OK;
211413    pRtree->nCursor++;
211414  }
211415  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
211416
211417  return rc;
211418}
211419
211420
211421/*
211422** Reset a cursor back to its initial state.
211423*/
211424static void resetCursor(RtreeCursor *pCsr){
211425  Rtree *pRtree = (Rtree *)(pCsr->base.pVtab);
211426  int ii;
211427  sqlite3_stmt *pStmt;
211428  if( pCsr->aConstraint ){
211429    int i;                        /* Used to iterate through constraint array */
211430    for(i=0; i<pCsr->nConstraint; i++){
211431      sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
211432      if( pInfo ){
211433        if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
211434        sqlite3_free(pInfo);
211435      }
211436    }
211437    sqlite3_free(pCsr->aConstraint);
211438    pCsr->aConstraint = 0;
211439  }
211440  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
211441  sqlite3_free(pCsr->aPoint);
211442  pStmt = pCsr->pReadAux;
211443  memset(pCsr, 0, sizeof(RtreeCursor));
211444  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
211445  pCsr->pReadAux = pStmt;
211446
211447}
211448
211449/*
211450** Rtree virtual table module xClose method.
211451*/
211452static int rtreeClose(sqlite3_vtab_cursor *cur){
211453  Rtree *pRtree = (Rtree *)(cur->pVtab);
211454  RtreeCursor *pCsr = (RtreeCursor *)cur;
211455  assert( pRtree->nCursor>0 );
211456  resetCursor(pCsr);
211457  sqlite3_finalize(pCsr->pReadAux);
211458  sqlite3_free(pCsr);
211459  pRtree->nCursor--;
211460  if( pRtree->nCursor==0 && pRtree->inWrTrans==0 ){
211461    nodeBlobReset(pRtree);
211462  }
211463  return SQLITE_OK;
211464}
211465
211466/*
211467** Rtree virtual table module xEof method.
211468**
211469** Return non-zero if the cursor does not currently point to a valid
211470** record (i.e if the scan has finished), or zero otherwise.
211471*/
211472static int rtreeEof(sqlite3_vtab_cursor *cur){
211473  RtreeCursor *pCsr = (RtreeCursor *)cur;
211474  return pCsr->atEOF;
211475}
211476
211477/*
211478** Convert raw bits from the on-disk RTree record into a coordinate value.
211479** The on-disk format is big-endian and needs to be converted for little-
211480** endian platforms.  The on-disk record stores integer coordinates if
211481** eInt is true and it stores 32-bit floating point records if eInt is
211482** false.  a[] is the four bytes of the on-disk record to be decoded.
211483** Store the results in "r".
211484**
211485** There are five versions of this macro.  The last one is generic.  The
211486** other four are various architectures-specific optimizations.
211487*/
211488#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
211489#define RTREE_DECODE_COORD(eInt, a, r) {                        \
211490    RtreeCoord c;    /* Coordinate decoded */                   \
211491    c.u = _byteswap_ulong(*(u32*)a);                            \
211492    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
211493}
211494#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
211495#define RTREE_DECODE_COORD(eInt, a, r) {                        \
211496    RtreeCoord c;    /* Coordinate decoded */                   \
211497    c.u = __builtin_bswap32(*(u32*)a);                          \
211498    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
211499}
211500#elif SQLITE_BYTEORDER==1234
211501#define RTREE_DECODE_COORD(eInt, a, r) {                        \
211502    RtreeCoord c;    /* Coordinate decoded */                   \
211503    memcpy(&c.u,a,4);                                           \
211504    c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
211505          ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
211506    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
211507}
211508#elif SQLITE_BYTEORDER==4321
211509#define RTREE_DECODE_COORD(eInt, a, r) {                        \
211510    RtreeCoord c;    /* Coordinate decoded */                   \
211511    memcpy(&c.u,a,4);                                           \
211512    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
211513}
211514#else
211515#define RTREE_DECODE_COORD(eInt, a, r) {                        \
211516    RtreeCoord c;    /* Coordinate decoded */                   \
211517    c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
211518           +((u32)a[2]<<8) + a[3];                              \
211519    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
211520}
211521#endif
211522
211523/*
211524** Check the RTree node or entry given by pCellData and p against the MATCH
211525** constraint pConstraint.
211526*/
211527static int rtreeCallbackConstraint(
211528  RtreeConstraint *pConstraint,  /* The constraint to test */
211529  int eInt,                      /* True if RTree holding integer coordinates */
211530  u8 *pCellData,                 /* Raw cell content */
211531  RtreeSearchPoint *pSearch,     /* Container of this cell */
211532  sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
211533  int *peWithin                  /* OUT: visibility of the cell */
211534){
211535  sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
211536  int nCoord = pInfo->nCoord;                           /* No. of coordinates */
211537  int rc;                                             /* Callback return code */
211538  RtreeCoord c;                                       /* Translator union */
211539  sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
211540
211541  assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
211542  assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
211543
211544  if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
211545    pInfo->iRowid = readInt64(pCellData);
211546  }
211547  pCellData += 8;
211548#ifndef SQLITE_RTREE_INT_ONLY
211549  if( eInt==0 ){
211550    switch( nCoord ){
211551      case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.f;
211552                readCoord(pCellData+32, &c); aCoord[8] = c.f;
211553      case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.f;
211554                readCoord(pCellData+24, &c); aCoord[6] = c.f;
211555      case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.f;
211556                readCoord(pCellData+16, &c); aCoord[4] = c.f;
211557      case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.f;
211558                readCoord(pCellData+8,  &c); aCoord[2] = c.f;
211559      default:  readCoord(pCellData+4,  &c); aCoord[1] = c.f;
211560                readCoord(pCellData,    &c); aCoord[0] = c.f;
211561    }
211562  }else
211563#endif
211564  {
211565    switch( nCoord ){
211566      case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.i;
211567                readCoord(pCellData+32, &c); aCoord[8] = c.i;
211568      case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.i;
211569                readCoord(pCellData+24, &c); aCoord[6] = c.i;
211570      case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.i;
211571                readCoord(pCellData+16, &c); aCoord[4] = c.i;
211572      case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.i;
211573                readCoord(pCellData+8,  &c); aCoord[2] = c.i;
211574      default:  readCoord(pCellData+4,  &c); aCoord[1] = c.i;
211575                readCoord(pCellData,    &c); aCoord[0] = c.i;
211576    }
211577  }
211578  if( pConstraint->op==RTREE_MATCH ){
211579    int eWithin = 0;
211580    rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
211581                              nCoord, aCoord, &eWithin);
211582    if( eWithin==0 ) *peWithin = NOT_WITHIN;
211583    *prScore = RTREE_ZERO;
211584  }else{
211585    pInfo->aCoord = aCoord;
211586    pInfo->iLevel = pSearch->iLevel - 1;
211587    pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
211588    pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
211589    rc = pConstraint->u.xQueryFunc(pInfo);
211590    if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
211591    if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
211592      *prScore = pInfo->rScore;
211593    }
211594  }
211595  return rc;
211596}
211597
211598/*
211599** Check the internal RTree node given by pCellData against constraint p.
211600** If this constraint cannot be satisfied by any child within the node,
211601** set *peWithin to NOT_WITHIN.
211602*/
211603static void rtreeNonleafConstraint(
211604  RtreeConstraint *p,        /* The constraint to test */
211605  int eInt,                  /* True if RTree holds integer coordinates */
211606  u8 *pCellData,             /* Raw cell content as appears on disk */
211607  int *peWithin              /* Adjust downward, as appropriate */
211608){
211609  sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
211610
211611  /* p->iCoord might point to either a lower or upper bound coordinate
211612  ** in a coordinate pair.  But make pCellData point to the lower bound.
211613  */
211614  pCellData += 8 + 4*(p->iCoord&0xfe);
211615
211616  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
211617      || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
211618      || p->op==RTREE_FALSE );
211619  assert( FOUR_BYTE_ALIGNED(pCellData) );
211620  switch( p->op ){
211621    case RTREE_TRUE:  return;   /* Always satisfied */
211622    case RTREE_FALSE: break;    /* Never satisfied */
211623    case RTREE_EQ:
211624      RTREE_DECODE_COORD(eInt, pCellData, val);
211625      /* val now holds the lower bound of the coordinate pair */
211626      if( p->u.rValue>=val ){
211627        pCellData += 4;
211628        RTREE_DECODE_COORD(eInt, pCellData, val);
211629        /* val now holds the upper bound of the coordinate pair */
211630        if( p->u.rValue<=val ) return;
211631      }
211632      break;
211633    case RTREE_LE:
211634    case RTREE_LT:
211635      RTREE_DECODE_COORD(eInt, pCellData, val);
211636      /* val now holds the lower bound of the coordinate pair */
211637      if( p->u.rValue>=val ) return;
211638      break;
211639
211640    default:
211641      pCellData += 4;
211642      RTREE_DECODE_COORD(eInt, pCellData, val);
211643      /* val now holds the upper bound of the coordinate pair */
211644      if( p->u.rValue<=val ) return;
211645      break;
211646  }
211647  *peWithin = NOT_WITHIN;
211648}
211649
211650/*
211651** Check the leaf RTree cell given by pCellData against constraint p.
211652** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
211653** If the constraint is satisfied, leave *peWithin unchanged.
211654**
211655** The constraint is of the form:  xN op $val
211656**
211657** The op is given by p->op.  The xN is p->iCoord-th coordinate in
211658** pCellData.  $val is given by p->u.rValue.
211659*/
211660static void rtreeLeafConstraint(
211661  RtreeConstraint *p,        /* The constraint to test */
211662  int eInt,                  /* True if RTree holds integer coordinates */
211663  u8 *pCellData,             /* Raw cell content as appears on disk */
211664  int *peWithin              /* Adjust downward, as appropriate */
211665){
211666  RtreeDValue xN;      /* Coordinate value converted to a double */
211667
211668  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
211669      || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
211670      || p->op==RTREE_FALSE );
211671  pCellData += 8 + p->iCoord*4;
211672  assert( FOUR_BYTE_ALIGNED(pCellData) );
211673  RTREE_DECODE_COORD(eInt, pCellData, xN);
211674  switch( p->op ){
211675    case RTREE_TRUE:  return;   /* Always satisfied */
211676    case RTREE_FALSE: break;    /* Never satisfied */
211677    case RTREE_LE:    if( xN <= p->u.rValue ) return;  break;
211678    case RTREE_LT:    if( xN <  p->u.rValue ) return;  break;
211679    case RTREE_GE:    if( xN >= p->u.rValue ) return;  break;
211680    case RTREE_GT:    if( xN >  p->u.rValue ) return;  break;
211681    default:          if( xN == p->u.rValue ) return;  break;
211682  }
211683  *peWithin = NOT_WITHIN;
211684}
211685
211686/*
211687** One of the cells in node pNode is guaranteed to have a 64-bit
211688** integer value equal to iRowid. Return the index of this cell.
211689*/
211690static int nodeRowidIndex(
211691  Rtree *pRtree,
211692  RtreeNode *pNode,
211693  i64 iRowid,
211694  int *piIndex
211695){
211696  int ii;
211697  int nCell = NCELL(pNode);
211698  assert( nCell<200 );
211699  for(ii=0; ii<nCell; ii++){
211700    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
211701      *piIndex = ii;
211702      return SQLITE_OK;
211703    }
211704  }
211705  RTREE_IS_CORRUPT(pRtree);
211706  return SQLITE_CORRUPT_VTAB;
211707}
211708
211709/*
211710** Return the index of the cell containing a pointer to node pNode
211711** in its parent. If pNode is the root node, return -1.
211712*/
211713static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
211714  RtreeNode *pParent = pNode->pParent;
211715  if( ALWAYS(pParent) ){
211716    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
211717  }else{
211718    *piIndex = -1;
211719    return SQLITE_OK;
211720  }
211721}
211722
211723/*
211724** Compare two search points.  Return negative, zero, or positive if the first
211725** is less than, equal to, or greater than the second.
211726**
211727** The rScore is the primary key.  Smaller rScore values come first.
211728** If the rScore is a tie, then use iLevel as the tie breaker with smaller
211729** iLevel values coming first.  In this way, if rScore is the same for all
211730** SearchPoints, then iLevel becomes the deciding factor and the result
211731** is a depth-first search, which is the desired default behavior.
211732*/
211733static int rtreeSearchPointCompare(
211734  const RtreeSearchPoint *pA,
211735  const RtreeSearchPoint *pB
211736){
211737  if( pA->rScore<pB->rScore ) return -1;
211738  if( pA->rScore>pB->rScore ) return +1;
211739  if( pA->iLevel<pB->iLevel ) return -1;
211740  if( pA->iLevel>pB->iLevel ) return +1;
211741  return 0;
211742}
211743
211744/*
211745** Interchange two search points in a cursor.
211746*/
211747static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
211748  RtreeSearchPoint t = p->aPoint[i];
211749  assert( i<j );
211750  p->aPoint[i] = p->aPoint[j];
211751  p->aPoint[j] = t;
211752  i++; j++;
211753  if( i<RTREE_CACHE_SZ ){
211754    if( j>=RTREE_CACHE_SZ ){
211755      nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
211756      p->aNode[i] = 0;
211757    }else{
211758      RtreeNode *pTemp = p->aNode[i];
211759      p->aNode[i] = p->aNode[j];
211760      p->aNode[j] = pTemp;
211761    }
211762  }
211763}
211764
211765/*
211766** Return the search point with the lowest current score.
211767*/
211768static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
211769  return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
211770}
211771
211772/*
211773** Get the RtreeNode for the search point with the lowest score.
211774*/
211775static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
211776  sqlite3_int64 id;
211777  int ii = 1 - pCur->bPoint;
211778  assert( ii==0 || ii==1 );
211779  assert( pCur->bPoint || pCur->nPoint );
211780  if( pCur->aNode[ii]==0 ){
211781    assert( pRC!=0 );
211782    id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
211783    *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
211784  }
211785  return pCur->aNode[ii];
211786}
211787
211788/*
211789** Push a new element onto the priority queue
211790*/
211791static RtreeSearchPoint *rtreeEnqueue(
211792  RtreeCursor *pCur,    /* The cursor */
211793  RtreeDValue rScore,   /* Score for the new search point */
211794  u8 iLevel             /* Level for the new search point */
211795){
211796  int i, j;
211797  RtreeSearchPoint *pNew;
211798  if( pCur->nPoint>=pCur->nPointAlloc ){
211799    int nNew = pCur->nPointAlloc*2 + 8;
211800    pNew = sqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
211801    if( pNew==0 ) return 0;
211802    pCur->aPoint = pNew;
211803    pCur->nPointAlloc = nNew;
211804  }
211805  i = pCur->nPoint++;
211806  pNew = pCur->aPoint + i;
211807  pNew->rScore = rScore;
211808  pNew->iLevel = iLevel;
211809  assert( iLevel<=RTREE_MAX_DEPTH );
211810  while( i>0 ){
211811    RtreeSearchPoint *pParent;
211812    j = (i-1)/2;
211813    pParent = pCur->aPoint + j;
211814    if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
211815    rtreeSearchPointSwap(pCur, j, i);
211816    i = j;
211817    pNew = pParent;
211818  }
211819  return pNew;
211820}
211821
211822/*
211823** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
211824** NULL if malloc fails.
211825*/
211826static RtreeSearchPoint *rtreeSearchPointNew(
211827  RtreeCursor *pCur,    /* The cursor */
211828  RtreeDValue rScore,   /* Score for the new search point */
211829  u8 iLevel             /* Level for the new search point */
211830){
211831  RtreeSearchPoint *pNew, *pFirst;
211832  pFirst = rtreeSearchPointFirst(pCur);
211833  pCur->anQueue[iLevel]++;
211834  if( pFirst==0
211835   || pFirst->rScore>rScore
211836   || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
211837  ){
211838    if( pCur->bPoint ){
211839      int ii;
211840      pNew = rtreeEnqueue(pCur, rScore, iLevel);
211841      if( pNew==0 ) return 0;
211842      ii = (int)(pNew - pCur->aPoint) + 1;
211843      assert( ii==1 );
211844      if( ALWAYS(ii<RTREE_CACHE_SZ) ){
211845        assert( pCur->aNode[ii]==0 );
211846        pCur->aNode[ii] = pCur->aNode[0];
211847      }else{
211848        nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
211849      }
211850      pCur->aNode[0] = 0;
211851      *pNew = pCur->sPoint;
211852    }
211853    pCur->sPoint.rScore = rScore;
211854    pCur->sPoint.iLevel = iLevel;
211855    pCur->bPoint = 1;
211856    return &pCur->sPoint;
211857  }else{
211858    return rtreeEnqueue(pCur, rScore, iLevel);
211859  }
211860}
211861
211862#if 0
211863/* Tracing routines for the RtreeSearchPoint queue */
211864static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
211865  if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
211866  printf(" %d.%05lld.%02d %g %d",
211867    p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
211868  );
211869  idx++;
211870  if( idx<RTREE_CACHE_SZ ){
211871    printf(" %p\n", pCur->aNode[idx]);
211872  }else{
211873    printf("\n");
211874  }
211875}
211876static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
211877  int ii;
211878  printf("=== %9s ", zPrefix);
211879  if( pCur->bPoint ){
211880    tracePoint(&pCur->sPoint, -1, pCur);
211881  }
211882  for(ii=0; ii<pCur->nPoint; ii++){
211883    if( ii>0 || pCur->bPoint ) printf("              ");
211884    tracePoint(&pCur->aPoint[ii], ii, pCur);
211885  }
211886}
211887# define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
211888#else
211889# define RTREE_QUEUE_TRACE(A,B)   /* no-op */
211890#endif
211891
211892/* Remove the search point with the lowest current score.
211893*/
211894static void rtreeSearchPointPop(RtreeCursor *p){
211895  int i, j, k, n;
211896  i = 1 - p->bPoint;
211897  assert( i==0 || i==1 );
211898  if( p->aNode[i] ){
211899    nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
211900    p->aNode[i] = 0;
211901  }
211902  if( p->bPoint ){
211903    p->anQueue[p->sPoint.iLevel]--;
211904    p->bPoint = 0;
211905  }else if( ALWAYS(p->nPoint) ){
211906    p->anQueue[p->aPoint[0].iLevel]--;
211907    n = --p->nPoint;
211908    p->aPoint[0] = p->aPoint[n];
211909    if( n<RTREE_CACHE_SZ-1 ){
211910      p->aNode[1] = p->aNode[n+1];
211911      p->aNode[n+1] = 0;
211912    }
211913    i = 0;
211914    while( (j = i*2+1)<n ){
211915      k = j+1;
211916      if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
211917        if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
211918          rtreeSearchPointSwap(p, i, k);
211919          i = k;
211920        }else{
211921          break;
211922        }
211923      }else{
211924        if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
211925          rtreeSearchPointSwap(p, i, j);
211926          i = j;
211927        }else{
211928          break;
211929        }
211930      }
211931    }
211932  }
211933}
211934
211935
211936/*
211937** Continue the search on cursor pCur until the front of the queue
211938** contains an entry suitable for returning as a result-set row,
211939** or until the RtreeSearchPoint queue is empty, indicating that the
211940** query has completed.
211941*/
211942static int rtreeStepToLeaf(RtreeCursor *pCur){
211943  RtreeSearchPoint *p;
211944  Rtree *pRtree = RTREE_OF_CURSOR(pCur);
211945  RtreeNode *pNode;
211946  int eWithin;
211947  int rc = SQLITE_OK;
211948  int nCell;
211949  int nConstraint = pCur->nConstraint;
211950  int ii;
211951  int eInt;
211952  RtreeSearchPoint x;
211953
211954  eInt = pRtree->eCoordType==RTREE_COORD_INT32;
211955  while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
211956    u8 *pCellData;
211957    pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
211958    if( rc ) return rc;
211959    nCell = NCELL(pNode);
211960    assert( nCell<200 );
211961    pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
211962    while( p->iCell<nCell ){
211963      sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
211964      eWithin = FULLY_WITHIN;
211965      for(ii=0; ii<nConstraint; ii++){
211966        RtreeConstraint *pConstraint = pCur->aConstraint + ii;
211967        if( pConstraint->op>=RTREE_MATCH ){
211968          rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
211969                                       &rScore, &eWithin);
211970          if( rc ) return rc;
211971        }else if( p->iLevel==1 ){
211972          rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
211973        }else{
211974          rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
211975        }
211976        if( eWithin==NOT_WITHIN ){
211977          p->iCell++;
211978          pCellData += pRtree->nBytesPerCell;
211979          break;
211980        }
211981      }
211982      if( eWithin==NOT_WITHIN ) continue;
211983      p->iCell++;
211984      x.iLevel = p->iLevel - 1;
211985      if( x.iLevel ){
211986        x.id = readInt64(pCellData);
211987        for(ii=0; ii<pCur->nPoint; ii++){
211988          if( pCur->aPoint[ii].id==x.id ){
211989            RTREE_IS_CORRUPT(pRtree);
211990            return SQLITE_CORRUPT_VTAB;
211991          }
211992        }
211993        x.iCell = 0;
211994      }else{
211995        x.id = p->id;
211996        x.iCell = p->iCell - 1;
211997      }
211998      if( p->iCell>=nCell ){
211999        RTREE_QUEUE_TRACE(pCur, "POP-S:");
212000        rtreeSearchPointPop(pCur);
212001      }
212002      if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
212003      p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
212004      if( p==0 ) return SQLITE_NOMEM;
212005      p->eWithin = (u8)eWithin;
212006      p->id = x.id;
212007      p->iCell = x.iCell;
212008      RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
212009      break;
212010    }
212011    if( p->iCell>=nCell ){
212012      RTREE_QUEUE_TRACE(pCur, "POP-Se:");
212013      rtreeSearchPointPop(pCur);
212014    }
212015  }
212016  pCur->atEOF = p==0;
212017  return SQLITE_OK;
212018}
212019
212020/*
212021** Rtree virtual table module xNext method.
212022*/
212023static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
212024  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
212025  int rc = SQLITE_OK;
212026
212027  /* Move to the next entry that matches the configured constraints. */
212028  RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
212029  if( pCsr->bAuxValid ){
212030    pCsr->bAuxValid = 0;
212031    sqlite3_reset(pCsr->pReadAux);
212032  }
212033  rtreeSearchPointPop(pCsr);
212034  rc = rtreeStepToLeaf(pCsr);
212035  return rc;
212036}
212037
212038/*
212039** Rtree virtual table module xRowid method.
212040*/
212041static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
212042  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
212043  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
212044  int rc = SQLITE_OK;
212045  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
212046  if( rc==SQLITE_OK && ALWAYS(p) ){
212047    if( p->iCell>=NCELL(pNode) ){
212048      rc = SQLITE_ABORT;
212049    }else{
212050      *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
212051    }
212052  }
212053  return rc;
212054}
212055
212056/*
212057** Rtree virtual table module xColumn method.
212058*/
212059static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
212060  Rtree *pRtree = (Rtree *)cur->pVtab;
212061  RtreeCursor *pCsr = (RtreeCursor *)cur;
212062  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
212063  RtreeCoord c;
212064  int rc = SQLITE_OK;
212065  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
212066
212067  if( rc ) return rc;
212068  if( NEVER(p==0) ) return SQLITE_OK;
212069  if( p->iCell>=NCELL(pNode) ) return SQLITE_ABORT;
212070  if( i==0 ){
212071    sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
212072  }else if( i<=pRtree->nDim2 ){
212073    nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
212074#ifndef SQLITE_RTREE_INT_ONLY
212075    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
212076      sqlite3_result_double(ctx, c.f);
212077    }else
212078#endif
212079    {
212080      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
212081      sqlite3_result_int(ctx, c.i);
212082    }
212083  }else{
212084    if( !pCsr->bAuxValid ){
212085      if( pCsr->pReadAux==0 ){
212086        rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
212087                                &pCsr->pReadAux, 0);
212088        if( rc ) return rc;
212089      }
212090      sqlite3_bind_int64(pCsr->pReadAux, 1,
212091          nodeGetRowid(pRtree, pNode, p->iCell));
212092      rc = sqlite3_step(pCsr->pReadAux);
212093      if( rc==SQLITE_ROW ){
212094        pCsr->bAuxValid = 1;
212095      }else{
212096        sqlite3_reset(pCsr->pReadAux);
212097        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
212098        return rc;
212099      }
212100    }
212101    sqlite3_result_value(ctx,
212102         sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
212103  }
212104  return SQLITE_OK;
212105}
212106
212107/*
212108** Use nodeAcquire() to obtain the leaf node containing the record with
212109** rowid iRowid. If successful, set *ppLeaf to point to the node and
212110** return SQLITE_OK. If there is no such record in the table, set
212111** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
212112** to zero and return an SQLite error code.
212113*/
212114static int findLeafNode(
212115  Rtree *pRtree,              /* RTree to search */
212116  i64 iRowid,                 /* The rowid searching for */
212117  RtreeNode **ppLeaf,         /* Write the node here */
212118  sqlite3_int64 *piNode       /* Write the node-id here */
212119){
212120  int rc;
212121  *ppLeaf = 0;
212122  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
212123  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
212124    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
212125    if( piNode ) *piNode = iNode;
212126    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
212127    sqlite3_reset(pRtree->pReadRowid);
212128  }else{
212129    rc = sqlite3_reset(pRtree->pReadRowid);
212130  }
212131  return rc;
212132}
212133
212134/*
212135** This function is called to configure the RtreeConstraint object passed
212136** as the second argument for a MATCH constraint. The value passed as the
212137** first argument to this function is the right-hand operand to the MATCH
212138** operator.
212139*/
212140static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
212141  RtreeMatchArg *pBlob, *pSrc;       /* BLOB returned by geometry function */
212142  sqlite3_rtree_query_info *pInfo;   /* Callback information */
212143
212144  pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
212145  if( pSrc==0 ) return SQLITE_ERROR;
212146  pInfo = (sqlite3_rtree_query_info*)
212147                sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
212148  if( !pInfo ) return SQLITE_NOMEM;
212149  memset(pInfo, 0, sizeof(*pInfo));
212150  pBlob = (RtreeMatchArg*)&pInfo[1];
212151  memcpy(pBlob, pSrc, pSrc->iSize);
212152  pInfo->pContext = pBlob->cb.pContext;
212153  pInfo->nParam = pBlob->nParam;
212154  pInfo->aParam = pBlob->aParam;
212155  pInfo->apSqlParam = pBlob->apSqlParam;
212156
212157  if( pBlob->cb.xGeom ){
212158    pCons->u.xGeom = pBlob->cb.xGeom;
212159  }else{
212160    pCons->op = RTREE_QUERY;
212161    pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
212162  }
212163  pCons->pInfo = pInfo;
212164  return SQLITE_OK;
212165}
212166
212167SQLITE_PRIVATE int sqlite3IntFloatCompare(i64,double);
212168
212169/*
212170** Rtree virtual table module xFilter method.
212171*/
212172static int rtreeFilter(
212173  sqlite3_vtab_cursor *pVtabCursor,
212174  int idxNum, const char *idxStr,
212175  int argc, sqlite3_value **argv
212176){
212177  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
212178  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
212179  RtreeNode *pRoot = 0;
212180  int ii;
212181  int rc = SQLITE_OK;
212182  int iCell = 0;
212183
212184  rtreeReference(pRtree);
212185
212186  /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
212187  resetCursor(pCsr);
212188
212189  pCsr->iStrategy = idxNum;
212190  if( idxNum==1 ){
212191    /* Special case - lookup by rowid. */
212192    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
212193    RtreeSearchPoint *p;     /* Search point for the leaf */
212194    i64 iRowid = sqlite3_value_int64(argv[0]);
212195    i64 iNode = 0;
212196    int eType = sqlite3_value_numeric_type(argv[0]);
212197    if( eType==SQLITE_INTEGER
212198     || (eType==SQLITE_FLOAT
212199         && 0==sqlite3IntFloatCompare(iRowid,sqlite3_value_double(argv[0])))
212200    ){
212201      rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
212202    }else{
212203      rc = SQLITE_OK;
212204      pLeaf = 0;
212205    }
212206    if( rc==SQLITE_OK && pLeaf!=0 ){
212207      p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
212208      assert( p!=0 );  /* Always returns pCsr->sPoint */
212209      pCsr->aNode[0] = pLeaf;
212210      p->id = iNode;
212211      p->eWithin = PARTLY_WITHIN;
212212      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
212213      p->iCell = (u8)iCell;
212214      RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
212215    }else{
212216      pCsr->atEOF = 1;
212217    }
212218  }else{
212219    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
212220    ** with the configured constraints.
212221    */
212222    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
212223    if( rc==SQLITE_OK && argc>0 ){
212224      pCsr->aConstraint = sqlite3_malloc64(sizeof(RtreeConstraint)*argc);
212225      pCsr->nConstraint = argc;
212226      if( !pCsr->aConstraint ){
212227        rc = SQLITE_NOMEM;
212228      }else{
212229        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
212230        memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
212231        assert( (idxStr==0 && argc==0)
212232                || (idxStr && (int)strlen(idxStr)==argc*2) );
212233        for(ii=0; ii<argc; ii++){
212234          RtreeConstraint *p = &pCsr->aConstraint[ii];
212235          int eType = sqlite3_value_numeric_type(argv[ii]);
212236          p->op = idxStr[ii*2];
212237          p->iCoord = idxStr[ii*2+1]-'0';
212238          if( p->op>=RTREE_MATCH ){
212239            /* A MATCH operator. The right-hand-side must be a blob that
212240            ** can be cast into an RtreeMatchArg object. One created using
212241            ** an sqlite3_rtree_geometry_callback() SQL user function.
212242            */
212243            rc = deserializeGeometry(argv[ii], p);
212244            if( rc!=SQLITE_OK ){
212245              break;
212246            }
212247            p->pInfo->nCoord = pRtree->nDim2;
212248            p->pInfo->anQueue = pCsr->anQueue;
212249            p->pInfo->mxLevel = pRtree->iDepth + 1;
212250          }else if( eType==SQLITE_INTEGER ){
212251            sqlite3_int64 iVal = sqlite3_value_int64(argv[ii]);
212252#ifdef SQLITE_RTREE_INT_ONLY
212253            p->u.rValue = iVal;
212254#else
212255            p->u.rValue = (double)iVal;
212256            if( iVal>=((sqlite3_int64)1)<<48
212257             || iVal<=-(((sqlite3_int64)1)<<48)
212258            ){
212259              if( p->op==RTREE_LT ) p->op = RTREE_LE;
212260              if( p->op==RTREE_GT ) p->op = RTREE_GE;
212261            }
212262#endif
212263          }else if( eType==SQLITE_FLOAT ){
212264#ifdef SQLITE_RTREE_INT_ONLY
212265            p->u.rValue = sqlite3_value_int64(argv[ii]);
212266#else
212267            p->u.rValue = sqlite3_value_double(argv[ii]);
212268#endif
212269          }else{
212270            p->u.rValue = RTREE_ZERO;
212271            if( eType==SQLITE_NULL ){
212272              p->op = RTREE_FALSE;
212273            }else if( p->op==RTREE_LT || p->op==RTREE_LE ){
212274              p->op = RTREE_TRUE;
212275            }else{
212276              p->op = RTREE_FALSE;
212277            }
212278          }
212279        }
212280      }
212281    }
212282    if( rc==SQLITE_OK ){
212283      RtreeSearchPoint *pNew;
212284      assert( pCsr->bPoint==0 );  /* Due to the resetCursor() call above */
212285      pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
212286      if( NEVER(pNew==0) ){       /* Because pCsr->bPoint was FALSE */
212287        return SQLITE_NOMEM;
212288      }
212289      pNew->id = 1;
212290      pNew->iCell = 0;
212291      pNew->eWithin = PARTLY_WITHIN;
212292      assert( pCsr->bPoint==1 );
212293      pCsr->aNode[0] = pRoot;
212294      pRoot = 0;
212295      RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
212296      rc = rtreeStepToLeaf(pCsr);
212297    }
212298  }
212299
212300  nodeRelease(pRtree, pRoot);
212301  rtreeRelease(pRtree);
212302  return rc;
212303}
212304
212305/*
212306** Rtree virtual table module xBestIndex method. There are three
212307** table scan strategies to choose from (in order from most to
212308** least desirable):
212309**
212310**   idxNum     idxStr        Strategy
212311**   ------------------------------------------------
212312**     1        Unused        Direct lookup by rowid.
212313**     2        See below     R-tree query or full-table scan.
212314**   ------------------------------------------------
212315**
212316** If strategy 1 is used, then idxStr is not meaningful. If strategy
212317** 2 is used, idxStr is formatted to contain 2 bytes for each
212318** constraint used. The first two bytes of idxStr correspond to
212319** the constraint in sqlite3_index_info.aConstraintUsage[] with
212320** (argvIndex==1) etc.
212321**
212322** The first of each pair of bytes in idxStr identifies the constraint
212323** operator as follows:
212324**
212325**   Operator    Byte Value
212326**   ----------------------
212327**      =        0x41 ('A')
212328**     <=        0x42 ('B')
212329**      <        0x43 ('C')
212330**     >=        0x44 ('D')
212331**      >        0x45 ('E')
212332**   MATCH       0x46 ('F')
212333**   ----------------------
212334**
212335** The second of each pair of bytes identifies the coordinate column
212336** to which the constraint applies. The leftmost coordinate column
212337** is 'a', the second from the left 'b' etc.
212338*/
212339static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
212340  Rtree *pRtree = (Rtree*)tab;
212341  int rc = SQLITE_OK;
212342  int ii;
212343  int bMatch = 0;                 /* True if there exists a MATCH constraint */
212344  i64 nRow;                       /* Estimated rows returned by this scan */
212345
212346  int iIdx = 0;
212347  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
212348  memset(zIdxStr, 0, sizeof(zIdxStr));
212349
212350  /* Check if there exists a MATCH constraint - even an unusable one. If there
212351  ** is, do not consider the lookup-by-rowid plan as using such a plan would
212352  ** require the VDBE to evaluate the MATCH constraint, which is not currently
212353  ** possible. */
212354  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
212355    if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
212356      bMatch = 1;
212357    }
212358  }
212359
212360  assert( pIdxInfo->idxStr==0 );
212361  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
212362    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
212363
212364    if( bMatch==0 && p->usable
212365     && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
212366    ){
212367      /* We have an equality constraint on the rowid. Use strategy 1. */
212368      int jj;
212369      for(jj=0; jj<ii; jj++){
212370        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
212371        pIdxInfo->aConstraintUsage[jj].omit = 0;
212372      }
212373      pIdxInfo->idxNum = 1;
212374      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
212375      pIdxInfo->aConstraintUsage[jj].omit = 1;
212376
212377      /* This strategy involves a two rowid lookups on an B-Tree structures
212378      ** and then a linear search of an R-Tree node. This should be
212379      ** considered almost as quick as a direct rowid lookup (for which
212380      ** sqlite uses an internal cost of 0.0). It is expected to return
212381      ** a single row.
212382      */
212383      pIdxInfo->estimatedCost = 30.0;
212384      pIdxInfo->estimatedRows = 1;
212385      pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
212386      return SQLITE_OK;
212387    }
212388
212389    if( p->usable
212390    && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)
212391        || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)
212392    ){
212393      u8 op;
212394      u8 doOmit = 1;
212395      switch( p->op ){
212396        case SQLITE_INDEX_CONSTRAINT_EQ:    op = RTREE_EQ;    doOmit = 0; break;
212397        case SQLITE_INDEX_CONSTRAINT_GT:    op = RTREE_GT;    doOmit = 0; break;
212398        case SQLITE_INDEX_CONSTRAINT_LE:    op = RTREE_LE;    break;
212399        case SQLITE_INDEX_CONSTRAINT_LT:    op = RTREE_LT;    doOmit = 0; break;
212400        case SQLITE_INDEX_CONSTRAINT_GE:    op = RTREE_GE;    break;
212401        case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break;
212402        default:                            op = 0;           break;
212403      }
212404      if( op ){
212405        zIdxStr[iIdx++] = op;
212406        zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
212407        pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
212408        pIdxInfo->aConstraintUsage[ii].omit = doOmit;
212409      }
212410    }
212411  }
212412
212413  pIdxInfo->idxNum = 2;
212414  pIdxInfo->needToFreeIdxStr = 1;
212415  if( iIdx>0 ){
212416    pIdxInfo->idxStr = sqlite3_malloc( iIdx+1 );
212417    if( pIdxInfo->idxStr==0 ){
212418      return SQLITE_NOMEM;
212419    }
212420    memcpy(pIdxInfo->idxStr, zIdxStr, iIdx+1);
212421  }
212422
212423  nRow = pRtree->nRowEst >> (iIdx/2);
212424  pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
212425  pIdxInfo->estimatedRows = nRow;
212426
212427  return rc;
212428}
212429
212430/*
212431** Return the N-dimensional volumn of the cell stored in *p.
212432*/
212433static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
212434  RtreeDValue area = (RtreeDValue)1;
212435  assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
212436#ifndef SQLITE_RTREE_INT_ONLY
212437  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
212438    switch( pRtree->nDim ){
212439      case 5:  area  = p->aCoord[9].f - p->aCoord[8].f;
212440      case 4:  area *= p->aCoord[7].f - p->aCoord[6].f;
212441      case 3:  area *= p->aCoord[5].f - p->aCoord[4].f;
212442      case 2:  area *= p->aCoord[3].f - p->aCoord[2].f;
212443      default: area *= p->aCoord[1].f - p->aCoord[0].f;
212444    }
212445  }else
212446#endif
212447  {
212448    switch( pRtree->nDim ){
212449      case 5:  area  = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i;
212450      case 4:  area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i;
212451      case 3:  area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i;
212452      case 2:  area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i;
212453      default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i;
212454    }
212455  }
212456  return area;
212457}
212458
212459/*
212460** Return the margin length of cell p. The margin length is the sum
212461** of the objects size in each dimension.
212462*/
212463static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
212464  RtreeDValue margin = 0;
212465  int ii = pRtree->nDim2 - 2;
212466  do{
212467    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
212468    ii -= 2;
212469  }while( ii>=0 );
212470  return margin;
212471}
212472
212473/*
212474** Store the union of cells p1 and p2 in p1.
212475*/
212476static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
212477  int ii = 0;
212478  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
212479    do{
212480      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
212481      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
212482      ii += 2;
212483    }while( ii<pRtree->nDim2 );
212484  }else{
212485    do{
212486      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
212487      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
212488      ii += 2;
212489    }while( ii<pRtree->nDim2 );
212490  }
212491}
212492
212493/*
212494** Return true if the area covered by p2 is a subset of the area covered
212495** by p1. False otherwise.
212496*/
212497static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
212498  int ii;
212499  if( pRtree->eCoordType==RTREE_COORD_INT32 ){
212500    for(ii=0; ii<pRtree->nDim2; ii+=2){
212501      RtreeCoord *a1 = &p1->aCoord[ii];
212502      RtreeCoord *a2 = &p2->aCoord[ii];
212503      if( a2[0].i<a1[0].i || a2[1].i>a1[1].i ) return 0;
212504    }
212505  }else{
212506    for(ii=0; ii<pRtree->nDim2; ii+=2){
212507      RtreeCoord *a1 = &p1->aCoord[ii];
212508      RtreeCoord *a2 = &p2->aCoord[ii];
212509      if( a2[0].f<a1[0].f || a2[1].f>a1[1].f ) return 0;
212510    }
212511  }
212512  return 1;
212513}
212514
212515static RtreeDValue cellOverlap(
212516  Rtree *pRtree,
212517  RtreeCell *p,
212518  RtreeCell *aCell,
212519  int nCell
212520){
212521  int ii;
212522  RtreeDValue overlap = RTREE_ZERO;
212523  for(ii=0; ii<nCell; ii++){
212524    int jj;
212525    RtreeDValue o = (RtreeDValue)1;
212526    for(jj=0; jj<pRtree->nDim2; jj+=2){
212527      RtreeDValue x1, x2;
212528      x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
212529      x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
212530      if( x2<x1 ){
212531        o = (RtreeDValue)0;
212532        break;
212533      }else{
212534        o = o * (x2-x1);
212535      }
212536    }
212537    overlap += o;
212538  }
212539  return overlap;
212540}
212541
212542
212543/*
212544** This function implements the ChooseLeaf algorithm from Gutman[84].
212545** ChooseSubTree in r*tree terminology.
212546*/
212547static int ChooseLeaf(
212548  Rtree *pRtree,               /* Rtree table */
212549  RtreeCell *pCell,            /* Cell to insert into rtree */
212550  int iHeight,                 /* Height of sub-tree rooted at pCell */
212551  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
212552){
212553  int rc;
212554  int ii;
212555  RtreeNode *pNode = 0;
212556  rc = nodeAcquire(pRtree, 1, 0, &pNode);
212557
212558  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
212559    int iCell;
212560    sqlite3_int64 iBest = 0;
212561    int bFound = 0;
212562    RtreeDValue fMinGrowth = RTREE_ZERO;
212563    RtreeDValue fMinArea = RTREE_ZERO;
212564    int nCell = NCELL(pNode);
212565    RtreeNode *pChild = 0;
212566
212567    /* First check to see if there is are any cells in pNode that completely
212568    ** contains pCell.  If two or more cells in pNode completely contain pCell
212569    ** then pick the smallest.
212570    */
212571    for(iCell=0; iCell<nCell; iCell++){
212572      RtreeCell cell;
212573      nodeGetCell(pRtree, pNode, iCell, &cell);
212574      if( cellContains(pRtree, &cell, pCell) ){
212575        RtreeDValue area = cellArea(pRtree, &cell);
212576        if( bFound==0 || area<fMinArea ){
212577          iBest = cell.iRowid;
212578          fMinArea = area;
212579          bFound = 1;
212580        }
212581      }
212582    }
212583    if( !bFound ){
212584      /* No cells of pNode will completely contain pCell.  So pick the
212585      ** cell of pNode that grows by the least amount when pCell is added.
212586      ** Break ties by selecting the smaller cell.
212587      */
212588      for(iCell=0; iCell<nCell; iCell++){
212589        RtreeCell cell;
212590        RtreeDValue growth;
212591        RtreeDValue area;
212592        nodeGetCell(pRtree, pNode, iCell, &cell);
212593        area = cellArea(pRtree, &cell);
212594        cellUnion(pRtree, &cell, pCell);
212595        growth = cellArea(pRtree, &cell)-area;
212596        if( iCell==0
212597         || growth<fMinGrowth
212598         || (growth==fMinGrowth && area<fMinArea)
212599        ){
212600          fMinGrowth = growth;
212601          fMinArea = area;
212602          iBest = cell.iRowid;
212603        }
212604      }
212605    }
212606
212607    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
212608    nodeRelease(pRtree, pNode);
212609    pNode = pChild;
212610  }
212611
212612  *ppLeaf = pNode;
212613  return rc;
212614}
212615
212616/*
212617** A cell with the same content as pCell has just been inserted into
212618** the node pNode. This function updates the bounding box cells in
212619** all ancestor elements.
212620*/
212621static int AdjustTree(
212622  Rtree *pRtree,                    /* Rtree table */
212623  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
212624  RtreeCell *pCell                  /* This cell was just inserted */
212625){
212626  RtreeNode *p = pNode;
212627  int cnt = 0;
212628  int rc;
212629  while( p->pParent ){
212630    RtreeNode *pParent = p->pParent;
212631    RtreeCell cell;
212632    int iCell;
212633
212634    cnt++;
212635    if( NEVER(cnt>100) ){
212636      RTREE_IS_CORRUPT(pRtree);
212637      return SQLITE_CORRUPT_VTAB;
212638    }
212639    rc = nodeParentIndex(pRtree, p, &iCell);
212640    if( NEVER(rc!=SQLITE_OK) ){
212641      RTREE_IS_CORRUPT(pRtree);
212642      return SQLITE_CORRUPT_VTAB;
212643    }
212644
212645    nodeGetCell(pRtree, pParent, iCell, &cell);
212646    if( !cellContains(pRtree, &cell, pCell) ){
212647      cellUnion(pRtree, &cell, pCell);
212648      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
212649    }
212650
212651    p = pParent;
212652  }
212653  return SQLITE_OK;
212654}
212655
212656/*
212657** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
212658*/
212659static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
212660  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
212661  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
212662  sqlite3_step(pRtree->pWriteRowid);
212663  return sqlite3_reset(pRtree->pWriteRowid);
212664}
212665
212666/*
212667** Write mapping (iNode->iPar) to the <rtree>_parent table.
212668*/
212669static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
212670  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
212671  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
212672  sqlite3_step(pRtree->pWriteParent);
212673  return sqlite3_reset(pRtree->pWriteParent);
212674}
212675
212676static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
212677
212678
212679
212680/*
212681** Arguments aIdx, aCell and aSpare all point to arrays of size
212682** nIdx. The aIdx array contains the set of integers from 0 to
212683** (nIdx-1) in no particular order. This function sorts the values
212684** in aIdx according to dimension iDim of the cells in aCell. The
212685** minimum value of dimension iDim is considered first, the
212686** maximum used to break ties.
212687**
212688** The aSpare array is used as temporary working space by the
212689** sorting algorithm.
212690*/
212691static void SortByDimension(
212692  Rtree *pRtree,
212693  int *aIdx,
212694  int nIdx,
212695  int iDim,
212696  RtreeCell *aCell,
212697  int *aSpare
212698){
212699  if( nIdx>1 ){
212700
212701    int iLeft = 0;
212702    int iRight = 0;
212703
212704    int nLeft = nIdx/2;
212705    int nRight = nIdx-nLeft;
212706    int *aLeft = aIdx;
212707    int *aRight = &aIdx[nLeft];
212708
212709    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
212710    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
212711
212712    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
212713    aLeft = aSpare;
212714    while( iLeft<nLeft || iRight<nRight ){
212715      RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
212716      RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
212717      RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
212718      RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
212719      if( (iLeft!=nLeft) && ((iRight==nRight)
212720       || (xleft1<xright1)
212721       || (xleft1==xright1 && xleft2<xright2)
212722      )){
212723        aIdx[iLeft+iRight] = aLeft[iLeft];
212724        iLeft++;
212725      }else{
212726        aIdx[iLeft+iRight] = aRight[iRight];
212727        iRight++;
212728      }
212729    }
212730
212731#if 0
212732    /* Check that the sort worked */
212733    {
212734      int jj;
212735      for(jj=1; jj<nIdx; jj++){
212736        RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
212737        RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
212738        RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
212739        RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
212740        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
212741      }
212742    }
212743#endif
212744  }
212745}
212746
212747/*
212748** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
212749*/
212750static int splitNodeStartree(
212751  Rtree *pRtree,
212752  RtreeCell *aCell,
212753  int nCell,
212754  RtreeNode *pLeft,
212755  RtreeNode *pRight,
212756  RtreeCell *pBboxLeft,
212757  RtreeCell *pBboxRight
212758){
212759  int **aaSorted;
212760  int *aSpare;
212761  int ii;
212762
212763  int iBestDim = 0;
212764  int iBestSplit = 0;
212765  RtreeDValue fBestMargin = RTREE_ZERO;
212766
212767  sqlite3_int64 nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
212768
212769  aaSorted = (int **)sqlite3_malloc64(nByte);
212770  if( !aaSorted ){
212771    return SQLITE_NOMEM;
212772  }
212773
212774  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
212775  memset(aaSorted, 0, nByte);
212776  for(ii=0; ii<pRtree->nDim; ii++){
212777    int jj;
212778    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
212779    for(jj=0; jj<nCell; jj++){
212780      aaSorted[ii][jj] = jj;
212781    }
212782    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
212783  }
212784
212785  for(ii=0; ii<pRtree->nDim; ii++){
212786    RtreeDValue margin = RTREE_ZERO;
212787    RtreeDValue fBestOverlap = RTREE_ZERO;
212788    RtreeDValue fBestArea = RTREE_ZERO;
212789    int iBestLeft = 0;
212790    int nLeft;
212791
212792    for(
212793      nLeft=RTREE_MINCELLS(pRtree);
212794      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
212795      nLeft++
212796    ){
212797      RtreeCell left;
212798      RtreeCell right;
212799      int kk;
212800      RtreeDValue overlap;
212801      RtreeDValue area;
212802
212803      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
212804      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
212805      for(kk=1; kk<(nCell-1); kk++){
212806        if( kk<nLeft ){
212807          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
212808        }else{
212809          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
212810        }
212811      }
212812      margin += cellMargin(pRtree, &left);
212813      margin += cellMargin(pRtree, &right);
212814      overlap = cellOverlap(pRtree, &left, &right, 1);
212815      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
212816      if( (nLeft==RTREE_MINCELLS(pRtree))
212817       || (overlap<fBestOverlap)
212818       || (overlap==fBestOverlap && area<fBestArea)
212819      ){
212820        iBestLeft = nLeft;
212821        fBestOverlap = overlap;
212822        fBestArea = area;
212823      }
212824    }
212825
212826    if( ii==0 || margin<fBestMargin ){
212827      iBestDim = ii;
212828      fBestMargin = margin;
212829      iBestSplit = iBestLeft;
212830    }
212831  }
212832
212833  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
212834  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
212835  for(ii=0; ii<nCell; ii++){
212836    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
212837    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
212838    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
212839    nodeInsertCell(pRtree, pTarget, pCell);
212840    cellUnion(pRtree, pBbox, pCell);
212841  }
212842
212843  sqlite3_free(aaSorted);
212844  return SQLITE_OK;
212845}
212846
212847
212848static int updateMapping(
212849  Rtree *pRtree,
212850  i64 iRowid,
212851  RtreeNode *pNode,
212852  int iHeight
212853){
212854  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
212855  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
212856  if( iHeight>0 ){
212857    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
212858    RtreeNode *p;
212859    for(p=pNode; p; p=p->pParent){
212860      if( p==pChild ) return SQLITE_CORRUPT_VTAB;
212861    }
212862    if( pChild ){
212863      nodeRelease(pRtree, pChild->pParent);
212864      nodeReference(pNode);
212865      pChild->pParent = pNode;
212866    }
212867  }
212868  if( NEVER(pNode==0) ) return SQLITE_ERROR;
212869  return xSetMapping(pRtree, iRowid, pNode->iNode);
212870}
212871
212872static int SplitNode(
212873  Rtree *pRtree,
212874  RtreeNode *pNode,
212875  RtreeCell *pCell,
212876  int iHeight
212877){
212878  int i;
212879  int newCellIsRight = 0;
212880
212881  int rc = SQLITE_OK;
212882  int nCell = NCELL(pNode);
212883  RtreeCell *aCell;
212884  int *aiUsed;
212885
212886  RtreeNode *pLeft = 0;
212887  RtreeNode *pRight = 0;
212888
212889  RtreeCell leftbbox;
212890  RtreeCell rightbbox;
212891
212892  /* Allocate an array and populate it with a copy of pCell and
212893  ** all cells from node pLeft. Then zero the original node.
212894  */
212895  aCell = sqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
212896  if( !aCell ){
212897    rc = SQLITE_NOMEM;
212898    goto splitnode_out;
212899  }
212900  aiUsed = (int *)&aCell[nCell+1];
212901  memset(aiUsed, 0, sizeof(int)*(nCell+1));
212902  for(i=0; i<nCell; i++){
212903    nodeGetCell(pRtree, pNode, i, &aCell[i]);
212904  }
212905  nodeZero(pRtree, pNode);
212906  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
212907  nCell++;
212908
212909  if( pNode->iNode==1 ){
212910    pRight = nodeNew(pRtree, pNode);
212911    pLeft = nodeNew(pRtree, pNode);
212912    pRtree->iDepth++;
212913    pNode->isDirty = 1;
212914    writeInt16(pNode->zData, pRtree->iDepth);
212915  }else{
212916    pLeft = pNode;
212917    pRight = nodeNew(pRtree, pLeft->pParent);
212918    pLeft->nRef++;
212919  }
212920
212921  if( !pLeft || !pRight ){
212922    rc = SQLITE_NOMEM;
212923    goto splitnode_out;
212924  }
212925
212926  memset(pLeft->zData, 0, pRtree->iNodeSize);
212927  memset(pRight->zData, 0, pRtree->iNodeSize);
212928
212929  rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
212930                         &leftbbox, &rightbbox);
212931  if( rc!=SQLITE_OK ){
212932    goto splitnode_out;
212933  }
212934
212935  /* Ensure both child nodes have node numbers assigned to them by calling
212936  ** nodeWrite(). Node pRight always needs a node number, as it was created
212937  ** by nodeNew() above. But node pLeft sometimes already has a node number.
212938  ** In this case avoid the all to nodeWrite().
212939  */
212940  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
212941   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
212942  ){
212943    goto splitnode_out;
212944  }
212945
212946  rightbbox.iRowid = pRight->iNode;
212947  leftbbox.iRowid = pLeft->iNode;
212948
212949  if( pNode->iNode==1 ){
212950    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
212951    if( rc!=SQLITE_OK ){
212952      goto splitnode_out;
212953    }
212954  }else{
212955    RtreeNode *pParent = pLeft->pParent;
212956    int iCell;
212957    rc = nodeParentIndex(pRtree, pLeft, &iCell);
212958    if( ALWAYS(rc==SQLITE_OK) ){
212959      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
212960      rc = AdjustTree(pRtree, pParent, &leftbbox);
212961      assert( rc==SQLITE_OK );
212962    }
212963    if( NEVER(rc!=SQLITE_OK) ){
212964      goto splitnode_out;
212965    }
212966  }
212967  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
212968    goto splitnode_out;
212969  }
212970
212971  for(i=0; i<NCELL(pRight); i++){
212972    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
212973    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
212974    if( iRowid==pCell->iRowid ){
212975      newCellIsRight = 1;
212976    }
212977    if( rc!=SQLITE_OK ){
212978      goto splitnode_out;
212979    }
212980  }
212981  if( pNode->iNode==1 ){
212982    for(i=0; i<NCELL(pLeft); i++){
212983      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
212984      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
212985      if( rc!=SQLITE_OK ){
212986        goto splitnode_out;
212987      }
212988    }
212989  }else if( newCellIsRight==0 ){
212990    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
212991  }
212992
212993  if( rc==SQLITE_OK ){
212994    rc = nodeRelease(pRtree, pRight);
212995    pRight = 0;
212996  }
212997  if( rc==SQLITE_OK ){
212998    rc = nodeRelease(pRtree, pLeft);
212999    pLeft = 0;
213000  }
213001
213002splitnode_out:
213003  nodeRelease(pRtree, pRight);
213004  nodeRelease(pRtree, pLeft);
213005  sqlite3_free(aCell);
213006  return rc;
213007}
213008
213009/*
213010** If node pLeaf is not the root of the r-tree and its pParent pointer is
213011** still NULL, load all ancestor nodes of pLeaf into memory and populate
213012** the pLeaf->pParent chain all the way up to the root node.
213013**
213014** This operation is required when a row is deleted (or updated - an update
213015** is implemented as a delete followed by an insert). SQLite provides the
213016** rowid of the row to delete, which can be used to find the leaf on which
213017** the entry resides (argument pLeaf). Once the leaf is located, this
213018** function is called to determine its ancestry.
213019*/
213020static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
213021  int rc = SQLITE_OK;
213022  RtreeNode *pChild = pLeaf;
213023  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
213024    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
213025    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
213026    rc = sqlite3_step(pRtree->pReadParent);
213027    if( rc==SQLITE_ROW ){
213028      RtreeNode *pTest;           /* Used to test for reference loops */
213029      i64 iNode;                  /* Node number of parent node */
213030
213031      /* Before setting pChild->pParent, test that we are not creating a
213032      ** loop of references (as we would if, say, pChild==pParent). We don't
213033      ** want to do this as it leads to a memory leak when trying to delete
213034      ** the referenced counted node structures.
213035      */
213036      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
213037      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
213038      if( pTest==0 ){
213039        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
213040      }
213041    }
213042    rc = sqlite3_reset(pRtree->pReadParent);
213043    if( rc==SQLITE_OK ) rc = rc2;
213044    if( rc==SQLITE_OK && !pChild->pParent ){
213045      RTREE_IS_CORRUPT(pRtree);
213046      rc = SQLITE_CORRUPT_VTAB;
213047    }
213048    pChild = pChild->pParent;
213049  }
213050  return rc;
213051}
213052
213053static int deleteCell(Rtree *, RtreeNode *, int, int);
213054
213055static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
213056  int rc;
213057  int rc2;
213058  RtreeNode *pParent = 0;
213059  int iCell;
213060
213061  assert( pNode->nRef==1 );
213062
213063  /* Remove the entry in the parent cell. */
213064  rc = nodeParentIndex(pRtree, pNode, &iCell);
213065  if( rc==SQLITE_OK ){
213066    pParent = pNode->pParent;
213067    pNode->pParent = 0;
213068    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
213069    testcase( rc!=SQLITE_OK );
213070  }
213071  rc2 = nodeRelease(pRtree, pParent);
213072  if( rc==SQLITE_OK ){
213073    rc = rc2;
213074  }
213075  if( rc!=SQLITE_OK ){
213076    return rc;
213077  }
213078
213079  /* Remove the xxx_node entry. */
213080  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
213081  sqlite3_step(pRtree->pDeleteNode);
213082  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
213083    return rc;
213084  }
213085
213086  /* Remove the xxx_parent entry. */
213087  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
213088  sqlite3_step(pRtree->pDeleteParent);
213089  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
213090    return rc;
213091  }
213092
213093  /* Remove the node from the in-memory hash table and link it into
213094  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
213095  */
213096  nodeHashDelete(pRtree, pNode);
213097  pNode->iNode = iHeight;
213098  pNode->pNext = pRtree->pDeleted;
213099  pNode->nRef++;
213100  pRtree->pDeleted = pNode;
213101
213102  return SQLITE_OK;
213103}
213104
213105static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
213106  RtreeNode *pParent = pNode->pParent;
213107  int rc = SQLITE_OK;
213108  if( pParent ){
213109    int ii;
213110    int nCell = NCELL(pNode);
213111    RtreeCell box;                            /* Bounding box for pNode */
213112    nodeGetCell(pRtree, pNode, 0, &box);
213113    for(ii=1; ii<nCell; ii++){
213114      RtreeCell cell;
213115      nodeGetCell(pRtree, pNode, ii, &cell);
213116      cellUnion(pRtree, &box, &cell);
213117    }
213118    box.iRowid = pNode->iNode;
213119    rc = nodeParentIndex(pRtree, pNode, &ii);
213120    if( rc==SQLITE_OK ){
213121      nodeOverwriteCell(pRtree, pParent, &box, ii);
213122      rc = fixBoundingBox(pRtree, pParent);
213123    }
213124  }
213125  return rc;
213126}
213127
213128/*
213129** Delete the cell at index iCell of node pNode. After removing the
213130** cell, adjust the r-tree data structure if required.
213131*/
213132static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
213133  RtreeNode *pParent;
213134  int rc;
213135
213136  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
213137    return rc;
213138  }
213139
213140  /* Remove the cell from the node. This call just moves bytes around
213141  ** the in-memory node image, so it cannot fail.
213142  */
213143  nodeDeleteCell(pRtree, pNode, iCell);
213144
213145  /* If the node is not the tree root and now has less than the minimum
213146  ** number of cells, remove it from the tree. Otherwise, update the
213147  ** cell in the parent node so that it tightly contains the updated
213148  ** node.
213149  */
213150  pParent = pNode->pParent;
213151  assert( pParent || pNode->iNode==1 );
213152  if( pParent ){
213153    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
213154      rc = removeNode(pRtree, pNode, iHeight);
213155    }else{
213156      rc = fixBoundingBox(pRtree, pNode);
213157    }
213158  }
213159
213160  return rc;
213161}
213162
213163/*
213164** Insert cell pCell into node pNode. Node pNode is the head of a
213165** subtree iHeight high (leaf nodes have iHeight==0).
213166*/
213167static int rtreeInsertCell(
213168  Rtree *pRtree,
213169  RtreeNode *pNode,
213170  RtreeCell *pCell,
213171  int iHeight
213172){
213173  int rc = SQLITE_OK;
213174  if( iHeight>0 ){
213175    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
213176    if( pChild ){
213177      nodeRelease(pRtree, pChild->pParent);
213178      nodeReference(pNode);
213179      pChild->pParent = pNode;
213180    }
213181  }
213182  if( nodeInsertCell(pRtree, pNode, pCell) ){
213183    rc = SplitNode(pRtree, pNode, pCell, iHeight);
213184  }else{
213185    rc = AdjustTree(pRtree, pNode, pCell);
213186    if( ALWAYS(rc==SQLITE_OK) ){
213187      if( iHeight==0 ){
213188        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
213189      }else{
213190        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
213191      }
213192    }
213193  }
213194  return rc;
213195}
213196
213197static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
213198  int ii;
213199  int rc = SQLITE_OK;
213200  int nCell = NCELL(pNode);
213201
213202  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
213203    RtreeNode *pInsert;
213204    RtreeCell cell;
213205    nodeGetCell(pRtree, pNode, ii, &cell);
213206
213207    /* Find a node to store this cell in. pNode->iNode currently contains
213208    ** the height of the sub-tree headed by the cell.
213209    */
213210    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
213211    if( rc==SQLITE_OK ){
213212      int rc2;
213213      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
213214      rc2 = nodeRelease(pRtree, pInsert);
213215      if( rc==SQLITE_OK ){
213216        rc = rc2;
213217      }
213218    }
213219  }
213220  return rc;
213221}
213222
213223/*
213224** Select a currently unused rowid for a new r-tree record.
213225*/
213226static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){
213227  int rc;
213228  sqlite3_bind_null(pRtree->pWriteRowid, 1);
213229  sqlite3_bind_null(pRtree->pWriteRowid, 2);
213230  sqlite3_step(pRtree->pWriteRowid);
213231  rc = sqlite3_reset(pRtree->pWriteRowid);
213232  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
213233  return rc;
213234}
213235
213236/*
213237** Remove the entry with rowid=iDelete from the r-tree structure.
213238*/
213239static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
213240  int rc;                         /* Return code */
213241  RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
213242  int iCell;                      /* Index of iDelete cell in pLeaf */
213243  RtreeNode *pRoot = 0;           /* Root node of rtree structure */
213244
213245
213246  /* Obtain a reference to the root node to initialize Rtree.iDepth */
213247  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
213248
213249  /* Obtain a reference to the leaf node that contains the entry
213250  ** about to be deleted.
213251  */
213252  if( rc==SQLITE_OK ){
213253    rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
213254  }
213255
213256#ifdef CORRUPT_DB
213257  assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB );
213258#endif
213259
213260  /* Delete the cell in question from the leaf node. */
213261  if( rc==SQLITE_OK && pLeaf ){
213262    int rc2;
213263    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
213264    if( rc==SQLITE_OK ){
213265      rc = deleteCell(pRtree, pLeaf, iCell, 0);
213266    }
213267    rc2 = nodeRelease(pRtree, pLeaf);
213268    if( rc==SQLITE_OK ){
213269      rc = rc2;
213270    }
213271  }
213272
213273  /* Delete the corresponding entry in the <rtree>_rowid table. */
213274  if( rc==SQLITE_OK ){
213275    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
213276    sqlite3_step(pRtree->pDeleteRowid);
213277    rc = sqlite3_reset(pRtree->pDeleteRowid);
213278  }
213279
213280  /* Check if the root node now has exactly one child. If so, remove
213281  ** it, schedule the contents of the child for reinsertion and
213282  ** reduce the tree height by one.
213283  **
213284  ** This is equivalent to copying the contents of the child into
213285  ** the root node (the operation that Gutman's paper says to perform
213286  ** in this scenario).
213287  */
213288  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
213289    int rc2;
213290    RtreeNode *pChild = 0;
213291    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
213292    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);  /* tag-20210916a */
213293    if( rc==SQLITE_OK ){
213294      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
213295    }
213296    rc2 = nodeRelease(pRtree, pChild);
213297    if( rc==SQLITE_OK ) rc = rc2;
213298    if( rc==SQLITE_OK ){
213299      pRtree->iDepth--;
213300      writeInt16(pRoot->zData, pRtree->iDepth);
213301      pRoot->isDirty = 1;
213302    }
213303  }
213304
213305  /* Re-insert the contents of any underfull nodes removed from the tree. */
213306  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
213307    if( rc==SQLITE_OK ){
213308      rc = reinsertNodeContent(pRtree, pLeaf);
213309    }
213310    pRtree->pDeleted = pLeaf->pNext;
213311    pRtree->nNodeRef--;
213312    sqlite3_free(pLeaf);
213313  }
213314
213315  /* Release the reference to the root node. */
213316  if( rc==SQLITE_OK ){
213317    rc = nodeRelease(pRtree, pRoot);
213318  }else{
213319    nodeRelease(pRtree, pRoot);
213320  }
213321
213322  return rc;
213323}
213324
213325/*
213326** Rounding constants for float->double conversion.
213327*/
213328#define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
213329#define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
213330
213331#if !defined(SQLITE_RTREE_INT_ONLY)
213332/*
213333** Convert an sqlite3_value into an RtreeValue (presumably a float)
213334** while taking care to round toward negative or positive, respectively.
213335*/
213336static RtreeValue rtreeValueDown(sqlite3_value *v){
213337  double d = sqlite3_value_double(v);
213338  float f = (float)d;
213339  if( f>d ){
213340    f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
213341  }
213342  return f;
213343}
213344static RtreeValue rtreeValueUp(sqlite3_value *v){
213345  double d = sqlite3_value_double(v);
213346  float f = (float)d;
213347  if( f<d ){
213348    f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
213349  }
213350  return f;
213351}
213352#endif /* !defined(SQLITE_RTREE_INT_ONLY) */
213353
213354/*
213355** A constraint has failed while inserting a row into an rtree table.
213356** Assuming no OOM error occurs, this function sets the error message
213357** (at pRtree->base.zErrMsg) to an appropriate value and returns
213358** SQLITE_CONSTRAINT.
213359**
213360** Parameter iCol is the index of the leftmost column involved in the
213361** constraint failure. If it is 0, then the constraint that failed is
213362** the unique constraint on the id column. Otherwise, it is the rtree
213363** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
213364**
213365** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
213366*/
213367static int rtreeConstraintError(Rtree *pRtree, int iCol){
213368  sqlite3_stmt *pStmt = 0;
213369  char *zSql;
213370  int rc;
213371
213372  assert( iCol==0 || iCol%2 );
213373  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
213374  if( zSql ){
213375    rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
213376  }else{
213377    rc = SQLITE_NOMEM;
213378  }
213379  sqlite3_free(zSql);
213380
213381  if( rc==SQLITE_OK ){
213382    if( iCol==0 ){
213383      const char *zCol = sqlite3_column_name(pStmt, 0);
213384      pRtree->base.zErrMsg = sqlite3_mprintf(
213385          "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
213386      );
213387    }else{
213388      const char *zCol1 = sqlite3_column_name(pStmt, iCol);
213389      const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
213390      pRtree->base.zErrMsg = sqlite3_mprintf(
213391          "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
213392      );
213393    }
213394  }
213395
213396  sqlite3_finalize(pStmt);
213397  return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
213398}
213399
213400
213401
213402/*
213403** The xUpdate method for rtree module virtual tables.
213404*/
213405static int rtreeUpdate(
213406  sqlite3_vtab *pVtab,
213407  int nData,
213408  sqlite3_value **aData,
213409  sqlite_int64 *pRowid
213410){
213411  Rtree *pRtree = (Rtree *)pVtab;
213412  int rc = SQLITE_OK;
213413  RtreeCell cell;                 /* New cell to insert if nData>1 */
213414  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
213415
213416  if( pRtree->nNodeRef ){
213417    /* Unable to write to the btree while another cursor is reading from it,
213418    ** since the write might do a rebalance which would disrupt the read
213419    ** cursor. */
213420    return SQLITE_LOCKED_VTAB;
213421  }
213422  rtreeReference(pRtree);
213423  assert(nData>=1);
213424
213425  memset(&cell, 0, sizeof(cell));
213426
213427  /* Constraint handling. A write operation on an r-tree table may return
213428  ** SQLITE_CONSTRAINT for two reasons:
213429  **
213430  **   1. A duplicate rowid value, or
213431  **   2. The supplied data violates the "x2>=x1" constraint.
213432  **
213433  ** In the first case, if the conflict-handling mode is REPLACE, then
213434  ** the conflicting row can be removed before proceeding. In the second
213435  ** case, SQLITE_CONSTRAINT must be returned regardless of the
213436  ** conflict-handling mode specified by the user.
213437  */
213438  if( nData>1 ){
213439    int ii;
213440    int nn = nData - 4;
213441
213442    if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;
213443    /* Populate the cell.aCoord[] array. The first coordinate is aData[3].
213444    **
213445    ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
213446    ** with "column" that are interpreted as table constraints.
213447    ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
213448    ** This problem was discovered after years of use, so we silently ignore
213449    ** these kinds of misdeclared tables to avoid breaking any legacy.
213450    */
213451
213452#ifndef SQLITE_RTREE_INT_ONLY
213453    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
213454      for(ii=0; ii<nn; ii+=2){
213455        cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);
213456        cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);
213457        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
213458          rc = rtreeConstraintError(pRtree, ii+1);
213459          goto constraint;
213460        }
213461      }
213462    }else
213463#endif
213464    {
213465      for(ii=0; ii<nn; ii+=2){
213466        cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]);
213467        cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]);
213468        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
213469          rc = rtreeConstraintError(pRtree, ii+1);
213470          goto constraint;
213471        }
213472      }
213473    }
213474
213475    /* If a rowid value was supplied, check if it is already present in
213476    ** the table. If so, the constraint has failed. */
213477    if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){
213478      cell.iRowid = sqlite3_value_int64(aData[2]);
213479      if( sqlite3_value_type(aData[0])==SQLITE_NULL
213480       || sqlite3_value_int64(aData[0])!=cell.iRowid
213481      ){
213482        int steprc;
213483        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
213484        steprc = sqlite3_step(pRtree->pReadRowid);
213485        rc = sqlite3_reset(pRtree->pReadRowid);
213486        if( SQLITE_ROW==steprc ){
213487          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
213488            rc = rtreeDeleteRowid(pRtree, cell.iRowid);
213489          }else{
213490            rc = rtreeConstraintError(pRtree, 0);
213491            goto constraint;
213492          }
213493        }
213494      }
213495      bHaveRowid = 1;
213496    }
213497  }
213498
213499  /* If aData[0] is not an SQL NULL value, it is the rowid of a
213500  ** record to delete from the r-tree table. The following block does
213501  ** just that.
213502  */
213503  if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){
213504    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));
213505  }
213506
213507  /* If the aData[] array contains more than one element, elements
213508  ** (aData[2]..aData[argc-1]) contain a new record to insert into
213509  ** the r-tree structure.
213510  */
213511  if( rc==SQLITE_OK && nData>1 ){
213512    /* Insert the new record into the r-tree */
213513    RtreeNode *pLeaf = 0;
213514
213515    /* Figure out the rowid of the new row. */
213516    if( bHaveRowid==0 ){
213517      rc = rtreeNewRowid(pRtree, &cell.iRowid);
213518    }
213519    *pRowid = cell.iRowid;
213520
213521    if( rc==SQLITE_OK ){
213522      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
213523    }
213524    if( rc==SQLITE_OK ){
213525      int rc2;
213526      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
213527      rc2 = nodeRelease(pRtree, pLeaf);
213528      if( rc==SQLITE_OK ){
213529        rc = rc2;
213530      }
213531    }
213532    if( rc==SQLITE_OK && pRtree->nAux ){
213533      sqlite3_stmt *pUp = pRtree->pWriteAux;
213534      int jj;
213535      sqlite3_bind_int64(pUp, 1, *pRowid);
213536      for(jj=0; jj<pRtree->nAux; jj++){
213537        sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);
213538      }
213539      sqlite3_step(pUp);
213540      rc = sqlite3_reset(pUp);
213541    }
213542  }
213543
213544constraint:
213545  rtreeRelease(pRtree);
213546  return rc;
213547}
213548
213549/*
213550** Called when a transaction starts.
213551*/
213552static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
213553  Rtree *pRtree = (Rtree *)pVtab;
213554  assert( pRtree->inWrTrans==0 );
213555  pRtree->inWrTrans = 1;
213556  return SQLITE_OK;
213557}
213558
213559/*
213560** Called when a transaction completes (either by COMMIT or ROLLBACK).
213561** The sqlite3_blob object should be released at this point.
213562*/
213563static int rtreeEndTransaction(sqlite3_vtab *pVtab){
213564  Rtree *pRtree = (Rtree *)pVtab;
213565  pRtree->inWrTrans = 0;
213566  nodeBlobReset(pRtree);
213567  return SQLITE_OK;
213568}
213569static int rtreeRollback(sqlite3_vtab *pVtab){
213570  return rtreeEndTransaction(pVtab);
213571}
213572
213573/*
213574** The xRename method for rtree module virtual tables.
213575*/
213576static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
213577  Rtree *pRtree = (Rtree *)pVtab;
213578  int rc = SQLITE_NOMEM;
213579  char *zSql = sqlite3_mprintf(
213580    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
213581    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
213582    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
213583    , pRtree->zDb, pRtree->zName, zNewName
213584    , pRtree->zDb, pRtree->zName, zNewName
213585    , pRtree->zDb, pRtree->zName, zNewName
213586  );
213587  if( zSql ){
213588    nodeBlobReset(pRtree);
213589    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
213590    sqlite3_free(zSql);
213591  }
213592  return rc;
213593}
213594
213595/*
213596** The xSavepoint method.
213597**
213598** This module does not need to do anything to support savepoints. However,
213599** it uses this hook to close any open blob handle. This is done because a
213600** DROP TABLE command - which fortunately always opens a savepoint - cannot
213601** succeed if there are any open blob handles. i.e. if the blob handle were
213602** not closed here, the following would fail:
213603**
213604**   BEGIN;
213605**     INSERT INTO rtree...
213606**     DROP TABLE <tablename>;    -- Would fail with SQLITE_LOCKED
213607**   COMMIT;
213608*/
213609static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
213610  Rtree *pRtree = (Rtree *)pVtab;
213611  u8 iwt = pRtree->inWrTrans;
213612  UNUSED_PARAMETER(iSavepoint);
213613  pRtree->inWrTrans = 0;
213614  nodeBlobReset(pRtree);
213615  pRtree->inWrTrans = iwt;
213616  return SQLITE_OK;
213617}
213618
213619/*
213620** This function populates the pRtree->nRowEst variable with an estimate
213621** of the number of rows in the virtual table. If possible, this is based
213622** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
213623*/
213624static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
213625  const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
213626  char *zSql;
213627  sqlite3_stmt *p;
213628  int rc;
213629  i64 nRow = RTREE_MIN_ROWEST;
213630
213631  rc = sqlite3_table_column_metadata(
213632      db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
213633  );
213634  if( rc!=SQLITE_OK ){
213635    pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
213636    return rc==SQLITE_ERROR ? SQLITE_OK : rc;
213637  }
213638  zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
213639  if( zSql==0 ){
213640    rc = SQLITE_NOMEM;
213641  }else{
213642    rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
213643    if( rc==SQLITE_OK ){
213644      if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
213645      rc = sqlite3_finalize(p);
213646    }
213647    sqlite3_free(zSql);
213648  }
213649  pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
213650  return rc;
213651}
213652
213653
213654/*
213655** Return true if zName is the extension on one of the shadow tables used
213656** by this module.
213657*/
213658static int rtreeShadowName(const char *zName){
213659  static const char *azName[] = {
213660    "node", "parent", "rowid"
213661  };
213662  unsigned int i;
213663  for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
213664    if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
213665  }
213666  return 0;
213667}
213668
213669/* Forward declaration */
213670static int rtreeIntegrity(sqlite3_vtab*, const char*, const char*, int, char**);
213671
213672static sqlite3_module rtreeModule = {
213673  4,                          /* iVersion */
213674  rtreeCreate,                /* xCreate - create a table */
213675  rtreeConnect,               /* xConnect - connect to an existing table */
213676  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
213677  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
213678  rtreeDestroy,               /* xDestroy - Drop a table */
213679  rtreeOpen,                  /* xOpen - open a cursor */
213680  rtreeClose,                 /* xClose - close a cursor */
213681  rtreeFilter,                /* xFilter - configure scan constraints */
213682  rtreeNext,                  /* xNext - advance a cursor */
213683  rtreeEof,                   /* xEof */
213684  rtreeColumn,                /* xColumn - read data */
213685  rtreeRowid,                 /* xRowid - read data */
213686  rtreeUpdate,                /* xUpdate - write data */
213687  rtreeBeginTransaction,      /* xBegin - begin transaction */
213688  rtreeEndTransaction,        /* xSync - sync transaction */
213689  rtreeEndTransaction,        /* xCommit - commit transaction */
213690  rtreeRollback,              /* xRollback - rollback transaction */
213691  0,                          /* xFindFunction - function overloading */
213692  rtreeRename,                /* xRename - rename the table */
213693  rtreeSavepoint,             /* xSavepoint */
213694  0,                          /* xRelease */
213695  0,                          /* xRollbackTo */
213696  rtreeShadowName,            /* xShadowName */
213697  rtreeIntegrity              /* xIntegrity */
213698};
213699
213700static int rtreeSqlInit(
213701  Rtree *pRtree,
213702  sqlite3 *db,
213703  const char *zDb,
213704  const char *zPrefix,
213705  int isCreate
213706){
213707  int rc = SQLITE_OK;
213708
213709  #define N_STATEMENT 8
213710  static const char *azSql[N_STATEMENT] = {
213711    /* Write the xxx_node table */
213712    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)",
213713    "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1",
213714
213715    /* Read and write the xxx_rowid table */
213716    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1",
213717    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)",
213718    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1",
213719
213720    /* Read and write the xxx_parent table */
213721    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1",
213722    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)",
213723    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1"
213724  };
213725  sqlite3_stmt **appStmt[N_STATEMENT];
213726  int i;
213727  const int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
213728
213729  pRtree->db = db;
213730
213731  if( isCreate ){
213732    char *zCreate;
213733    sqlite3_str *p = sqlite3_str_new(db);
213734    int ii;
213735    sqlite3_str_appendf(p,
213736       "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno",
213737       zDb, zPrefix);
213738    for(ii=0; ii<pRtree->nAux; ii++){
213739      sqlite3_str_appendf(p,",a%d",ii);
213740    }
213741    sqlite3_str_appendf(p,
213742      ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);",
213743      zDb, zPrefix);
213744    sqlite3_str_appendf(p,
213745    "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);",
213746      zDb, zPrefix);
213747    sqlite3_str_appendf(p,
213748       "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))",
213749       zDb, zPrefix, pRtree->iNodeSize);
213750    zCreate = sqlite3_str_finish(p);
213751    if( !zCreate ){
213752      return SQLITE_NOMEM;
213753    }
213754    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
213755    sqlite3_free(zCreate);
213756    if( rc!=SQLITE_OK ){
213757      return rc;
213758    }
213759  }
213760
213761  appStmt[0] = &pRtree->pWriteNode;
213762  appStmt[1] = &pRtree->pDeleteNode;
213763  appStmt[2] = &pRtree->pReadRowid;
213764  appStmt[3] = &pRtree->pWriteRowid;
213765  appStmt[4] = &pRtree->pDeleteRowid;
213766  appStmt[5] = &pRtree->pReadParent;
213767  appStmt[6] = &pRtree->pWriteParent;
213768  appStmt[7] = &pRtree->pDeleteParent;
213769
213770  rc = rtreeQueryStat1(db, pRtree);
213771  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
213772    char *zSql;
213773    const char *zFormat;
213774    if( i!=3 || pRtree->nAux==0 ){
213775       zFormat = azSql[i];
213776    }else {
213777       /* An UPSERT is very slightly slower than REPLACE, but it is needed
213778       ** if there are auxiliary columns */
213779       zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)"
213780                  "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno";
213781    }
213782    zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
213783    if( zSql ){
213784      rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0);
213785    }else{
213786      rc = SQLITE_NOMEM;
213787    }
213788    sqlite3_free(zSql);
213789  }
213790  if( pRtree->nAux && rc!=SQLITE_NOMEM ){
213791    pRtree->zReadAuxSql = sqlite3_mprintf(
213792       "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1",
213793       zDb, zPrefix);
213794    if( pRtree->zReadAuxSql==0 ){
213795      rc = SQLITE_NOMEM;
213796    }else{
213797      sqlite3_str *p = sqlite3_str_new(db);
213798      int ii;
213799      char *zSql;
213800      sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
213801      for(ii=0; ii<pRtree->nAux; ii++){
213802        if( ii ) sqlite3_str_append(p, ",", 1);
213803#ifdef SQLITE_ENABLE_GEOPOLY
213804        if( ii<pRtree->nAuxNotNull ){
213805          sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii);
213806        }else
213807#endif
213808        {
213809          sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
213810        }
213811      }
213812      sqlite3_str_appendf(p, " WHERE rowid=?1");
213813      zSql = sqlite3_str_finish(p);
213814      if( zSql==0 ){
213815        rc = SQLITE_NOMEM;
213816      }else{
213817        rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0);
213818        sqlite3_free(zSql);
213819      }
213820    }
213821  }
213822
213823  return rc;
213824}
213825
213826/*
213827** The second argument to this function contains the text of an SQL statement
213828** that returns a single integer value. The statement is compiled and executed
213829** using database connection db. If successful, the integer value returned
213830** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
213831** code is returned and the value of *piVal after returning is not defined.
213832*/
213833static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
213834  int rc = SQLITE_NOMEM;
213835  if( zSql ){
213836    sqlite3_stmt *pStmt = 0;
213837    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
213838    if( rc==SQLITE_OK ){
213839      if( SQLITE_ROW==sqlite3_step(pStmt) ){
213840        *piVal = sqlite3_column_int(pStmt, 0);
213841      }
213842      rc = sqlite3_finalize(pStmt);
213843    }
213844  }
213845  return rc;
213846}
213847
213848/*
213849** This function is called from within the xConnect() or xCreate() method to
213850** determine the node-size used by the rtree table being created or connected
213851** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
213852** Otherwise, an SQLite error code is returned.
213853**
213854** If this function is being called as part of an xConnect(), then the rtree
213855** table already exists. In this case the node-size is determined by inspecting
213856** the root node of the tree.
213857**
213858** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
213859** This ensures that each node is stored on a single database page. If the
213860** database page-size is so large that more than RTREE_MAXCELLS entries
213861** would fit in a single node, use a smaller node-size.
213862*/
213863static int getNodeSize(
213864  sqlite3 *db,                    /* Database handle */
213865  Rtree *pRtree,                  /* Rtree handle */
213866  int isCreate,                   /* True for xCreate, false for xConnect */
213867  char **pzErr                    /* OUT: Error message, if any */
213868){
213869  int rc;
213870  char *zSql;
213871  if( isCreate ){
213872    int iPageSize = 0;
213873    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
213874    rc = getIntFromStmt(db, zSql, &iPageSize);
213875    if( rc==SQLITE_OK ){
213876      pRtree->iNodeSize = iPageSize-64;
213877      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
213878        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
213879      }
213880    }else{
213881      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
213882    }
213883  }else{
213884    zSql = sqlite3_mprintf(
213885        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
213886        pRtree->zDb, pRtree->zName
213887    );
213888    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
213889    if( rc!=SQLITE_OK ){
213890      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
213891    }else if( pRtree->iNodeSize<(512-64) ){
213892      rc = SQLITE_CORRUPT_VTAB;
213893      RTREE_IS_CORRUPT(pRtree);
213894      *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
213895                               pRtree->zName);
213896    }
213897  }
213898
213899  sqlite3_free(zSql);
213900  return rc;
213901}
213902
213903/*
213904** Return the length of a token
213905*/
213906static int rtreeTokenLength(const char *z){
213907  int dummy = 0;
213908  return sqlite3GetToken((const unsigned char*)z,&dummy);
213909}
213910
213911/*
213912** This function is the implementation of both the xConnect and xCreate
213913** methods of the r-tree virtual table.
213914**
213915**   argv[0]   -> module name
213916**   argv[1]   -> database name
213917**   argv[2]   -> table name
213918**   argv[...] -> column names...
213919*/
213920static int rtreeInit(
213921  sqlite3 *db,                        /* Database connection */
213922  void *pAux,                         /* One of the RTREE_COORD_* constants */
213923  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
213924  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
213925  char **pzErr,                       /* OUT: Error message, if any */
213926  int isCreate                        /* True for xCreate, false for xConnect */
213927){
213928  int rc = SQLITE_OK;
213929  Rtree *pRtree;
213930  int nDb;              /* Length of string argv[1] */
213931  int nName;            /* Length of string argv[2] */
213932  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
213933  sqlite3_str *pSql;
213934  char *zSql;
213935  int ii = 4;
213936  int iErr;
213937
213938  const char *aErrMsg[] = {
213939    0,                                                    /* 0 */
213940    "Wrong number of columns for an rtree table",         /* 1 */
213941    "Too few columns for an rtree table",                 /* 2 */
213942    "Too many columns for an rtree table",                /* 3 */
213943    "Auxiliary rtree columns must be last"                /* 4 */
213944  };
213945
213946  assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */
213947  if( argc<6 || argc>RTREE_MAX_AUX_COLUMN+3 ){
213948    *pzErr = sqlite3_mprintf("%s", aErrMsg[2 + (argc>=6)]);
213949    return SQLITE_ERROR;
213950  }
213951
213952  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
213953  sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
213954
213955
213956  /* Allocate the sqlite3_vtab structure */
213957  nDb = (int)strlen(argv[1]);
213958  nName = (int)strlen(argv[2]);
213959  pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName*2+8);
213960  if( !pRtree ){
213961    return SQLITE_NOMEM;
213962  }
213963  memset(pRtree, 0, sizeof(Rtree)+nDb+nName*2+8);
213964  pRtree->nBusy = 1;
213965  pRtree->base.pModule = &rtreeModule;
213966  pRtree->zDb = (char *)&pRtree[1];
213967  pRtree->zName = &pRtree->zDb[nDb+1];
213968  pRtree->zNodeName = &pRtree->zName[nName+1];
213969  pRtree->eCoordType = (u8)eCoordType;
213970  memcpy(pRtree->zDb, argv[1], nDb);
213971  memcpy(pRtree->zName, argv[2], nName);
213972  memcpy(pRtree->zNodeName, argv[2], nName);
213973  memcpy(&pRtree->zNodeName[nName], "_node", 6);
213974
213975
213976  /* Create/Connect to the underlying relational database schema. If
213977  ** that is successful, call sqlite3_declare_vtab() to configure
213978  ** the r-tree table schema.
213979  */
213980  pSql = sqlite3_str_new(db);
213981  sqlite3_str_appendf(pSql, "CREATE TABLE x(%.*s INT",
213982                      rtreeTokenLength(argv[3]), argv[3]);
213983  for(ii=4; ii<argc; ii++){
213984    const char *zArg = argv[ii];
213985    if( zArg[0]=='+' ){
213986      pRtree->nAux++;
213987      sqlite3_str_appendf(pSql, ",%.*s", rtreeTokenLength(zArg+1), zArg+1);
213988    }else if( pRtree->nAux>0 ){
213989      break;
213990    }else{
213991      static const char *azFormat[] = {",%.*s REAL", ",%.*s INT"};
213992      pRtree->nDim2++;
213993      sqlite3_str_appendf(pSql, azFormat[eCoordType],
213994                          rtreeTokenLength(zArg), zArg);
213995    }
213996  }
213997  sqlite3_str_appendf(pSql, ");");
213998  zSql = sqlite3_str_finish(pSql);
213999  if( !zSql ){
214000    rc = SQLITE_NOMEM;
214001  }else if( ii<argc ){
214002    *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
214003    rc = SQLITE_ERROR;
214004  }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
214005    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
214006  }
214007  sqlite3_free(zSql);
214008  if( rc ) goto rtreeInit_fail;
214009  pRtree->nDim = pRtree->nDim2/2;
214010  if( pRtree->nDim<1 ){
214011    iErr = 2;
214012  }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
214013    iErr = 3;
214014  }else if( pRtree->nDim2 % 2 ){
214015    iErr = 1;
214016  }else{
214017    iErr = 0;
214018  }
214019  if( iErr ){
214020    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
214021    goto rtreeInit_fail;
214022  }
214023  pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
214024
214025  /* Figure out the node size to use. */
214026  rc = getNodeSize(db, pRtree, isCreate, pzErr);
214027  if( rc ) goto rtreeInit_fail;
214028  rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
214029  if( rc ){
214030    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
214031    goto rtreeInit_fail;
214032  }
214033
214034  *ppVtab = (sqlite3_vtab *)pRtree;
214035  return SQLITE_OK;
214036
214037rtreeInit_fail:
214038  if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
214039  assert( *ppVtab==0 );
214040  assert( pRtree->nBusy==1 );
214041  rtreeRelease(pRtree);
214042  return rc;
214043}
214044
214045
214046/*
214047** Implementation of a scalar function that decodes r-tree nodes to
214048** human readable strings. This can be used for debugging and analysis.
214049**
214050** The scalar function takes two arguments: (1) the number of dimensions
214051** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
214052** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
214053** deserialize all nodes, a statement like:
214054**
214055**   SELECT rtreenode(2, data) FROM rt_node;
214056**
214057** The human readable string takes the form of a Tcl list with one
214058** entry for each cell in the r-tree node. Each entry is itself a
214059** list, containing the 8-byte rowid/pageno followed by the
214060** <num-dimension>*2 coordinates.
214061*/
214062static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
214063  RtreeNode node;
214064  Rtree tree;
214065  int ii;
214066  int nData;
214067  int errCode;
214068  sqlite3_str *pOut;
214069
214070  UNUSED_PARAMETER(nArg);
214071  memset(&node, 0, sizeof(RtreeNode));
214072  memset(&tree, 0, sizeof(Rtree));
214073  tree.nDim = (u8)sqlite3_value_int(apArg[0]);
214074  if( tree.nDim<1 || tree.nDim>5 ) return;
214075  tree.nDim2 = tree.nDim*2;
214076  tree.nBytesPerCell = 8 + 8 * tree.nDim;
214077  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
214078  if( node.zData==0 ) return;
214079  nData = sqlite3_value_bytes(apArg[1]);
214080  if( nData<4 ) return;
214081  if( nData<NCELL(&node)*tree.nBytesPerCell ) return;
214082
214083  pOut = sqlite3_str_new(0);
214084  for(ii=0; ii<NCELL(&node); ii++){
214085    RtreeCell cell;
214086    int jj;
214087
214088    nodeGetCell(&tree, &node, ii, &cell);
214089    if( ii>0 ) sqlite3_str_append(pOut, " ", 1);
214090    sqlite3_str_appendf(pOut, "{%lld", cell.iRowid);
214091    for(jj=0; jj<tree.nDim2; jj++){
214092#ifndef SQLITE_RTREE_INT_ONLY
214093      sqlite3_str_appendf(pOut, " %g", (double)cell.aCoord[jj].f);
214094#else
214095      sqlite3_str_appendf(pOut, " %d", cell.aCoord[jj].i);
214096#endif
214097    }
214098    sqlite3_str_append(pOut, "}", 1);
214099  }
214100  errCode = sqlite3_str_errcode(pOut);
214101  sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free);
214102  sqlite3_result_error_code(ctx, errCode);
214103}
214104
214105/* This routine implements an SQL function that returns the "depth" parameter
214106** from the front of a blob that is an r-tree node.  For example:
214107**
214108**     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
214109**
214110** The depth value is 0 for all nodes other than the root node, and the root
214111** node always has nodeno=1, so the example above is the primary use for this
214112** routine.  This routine is intended for testing and analysis only.
214113*/
214114static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
214115  UNUSED_PARAMETER(nArg);
214116  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
214117   || sqlite3_value_bytes(apArg[0])<2
214118
214119  ){
214120    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
214121  }else{
214122    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
214123    if( zBlob ){
214124      sqlite3_result_int(ctx, readInt16(zBlob));
214125    }else{
214126      sqlite3_result_error_nomem(ctx);
214127    }
214128  }
214129}
214130
214131/*
214132** Context object passed between the various routines that make up the
214133** implementation of integrity-check function rtreecheck().
214134*/
214135typedef struct RtreeCheck RtreeCheck;
214136struct RtreeCheck {
214137  sqlite3 *db;                    /* Database handle */
214138  const char *zDb;                /* Database containing rtree table */
214139  const char *zTab;               /* Name of rtree table */
214140  int bInt;                       /* True for rtree_i32 table */
214141  int nDim;                       /* Number of dimensions for this rtree tbl */
214142  sqlite3_stmt *pGetNode;         /* Statement used to retrieve nodes */
214143  sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
214144  int nLeaf;                      /* Number of leaf cells in table */
214145  int nNonLeaf;                   /* Number of non-leaf cells in table */
214146  int rc;                         /* Return code */
214147  char *zReport;                  /* Message to report */
214148  int nErr;                       /* Number of lines in zReport */
214149};
214150
214151#define RTREE_CHECK_MAX_ERROR 100
214152
214153/*
214154** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
214155** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
214156*/
214157static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
214158  int rc = sqlite3_reset(pStmt);
214159  if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
214160}
214161
214162/*
214163** The second and subsequent arguments to this function are a format string
214164** and printf style arguments. This function formats the string and attempts
214165** to compile it as an SQL statement.
214166**
214167** If successful, a pointer to the new SQL statement is returned. Otherwise,
214168** NULL is returned and an error code left in RtreeCheck.rc.
214169*/
214170static sqlite3_stmt *rtreeCheckPrepare(
214171  RtreeCheck *pCheck,             /* RtreeCheck object */
214172  const char *zFmt, ...           /* Format string and trailing args */
214173){
214174  va_list ap;
214175  char *z;
214176  sqlite3_stmt *pRet = 0;
214177
214178  va_start(ap, zFmt);
214179  z = sqlite3_vmprintf(zFmt, ap);
214180
214181  if( pCheck->rc==SQLITE_OK ){
214182    if( z==0 ){
214183      pCheck->rc = SQLITE_NOMEM;
214184    }else{
214185      pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
214186    }
214187  }
214188
214189  sqlite3_free(z);
214190  va_end(ap);
214191  return pRet;
214192}
214193
214194/*
214195** The second and subsequent arguments to this function are a printf()
214196** style format string and arguments. This function formats the string and
214197** appends it to the report being accumuated in pCheck.
214198*/
214199static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
214200  va_list ap;
214201  va_start(ap, zFmt);
214202  if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
214203    char *z = sqlite3_vmprintf(zFmt, ap);
214204    if( z==0 ){
214205      pCheck->rc = SQLITE_NOMEM;
214206    }else{
214207      pCheck->zReport = sqlite3_mprintf("%z%s%z",
214208          pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
214209      );
214210      if( pCheck->zReport==0 ){
214211        pCheck->rc = SQLITE_NOMEM;
214212      }
214213    }
214214    pCheck->nErr++;
214215  }
214216  va_end(ap);
214217}
214218
214219/*
214220** This function is a no-op if there is already an error code stored
214221** in the RtreeCheck object indicated by the first argument. NULL is
214222** returned in this case.
214223**
214224** Otherwise, the contents of rtree table node iNode are loaded from
214225** the database and copied into a buffer obtained from sqlite3_malloc().
214226** If no error occurs, a pointer to the buffer is returned and (*pnNode)
214227** is set to the size of the buffer in bytes.
214228**
214229** Or, if an error does occur, NULL is returned and an error code left
214230** in the RtreeCheck object. The final value of *pnNode is undefined in
214231** this case.
214232*/
214233static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
214234  u8 *pRet = 0;                   /* Return value */
214235
214236  if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){
214237    pCheck->pGetNode = rtreeCheckPrepare(pCheck,
214238        "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
214239        pCheck->zDb, pCheck->zTab
214240    );
214241  }
214242
214243  if( pCheck->rc==SQLITE_OK ){
214244    sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
214245    if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
214246      int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
214247      const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
214248      pRet = sqlite3_malloc64(nNode);
214249      if( pRet==0 ){
214250        pCheck->rc = SQLITE_NOMEM;
214251      }else{
214252        memcpy(pRet, pNode, nNode);
214253        *pnNode = nNode;
214254      }
214255    }
214256    rtreeCheckReset(pCheck, pCheck->pGetNode);
214257    if( pCheck->rc==SQLITE_OK && pRet==0 ){
214258      rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
214259    }
214260  }
214261
214262  return pRet;
214263}
214264
214265/*
214266** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
214267** (if bLeaf==1) table contains a specified entry. The schemas of the
214268** two tables are:
214269**
214270**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
214271**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
214272**
214273** In both cases, this function checks that there exists an entry with
214274** IPK value iKey and the second column set to iVal.
214275**
214276*/
214277static void rtreeCheckMapping(
214278  RtreeCheck *pCheck,             /* RtreeCheck object */
214279  int bLeaf,                      /* True for a leaf cell, false for interior */
214280  i64 iKey,                       /* Key for mapping */
214281  i64 iVal                        /* Expected value for mapping */
214282){
214283  int rc;
214284  sqlite3_stmt *pStmt;
214285  const char *azSql[2] = {
214286    "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
214287    "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
214288  };
214289
214290  assert( bLeaf==0 || bLeaf==1 );
214291  if( pCheck->aCheckMapping[bLeaf]==0 ){
214292    pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
214293        azSql[bLeaf], pCheck->zDb, pCheck->zTab
214294    );
214295  }
214296  if( pCheck->rc!=SQLITE_OK ) return;
214297
214298  pStmt = pCheck->aCheckMapping[bLeaf];
214299  sqlite3_bind_int64(pStmt, 1, iKey);
214300  rc = sqlite3_step(pStmt);
214301  if( rc==SQLITE_DONE ){
214302    rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
214303        iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
214304    );
214305  }else if( rc==SQLITE_ROW ){
214306    i64 ii = sqlite3_column_int64(pStmt, 0);
214307    if( ii!=iVal ){
214308      rtreeCheckAppendMsg(pCheck,
214309          "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
214310          iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
214311      );
214312    }
214313  }
214314  rtreeCheckReset(pCheck, pStmt);
214315}
214316
214317/*
214318** Argument pCell points to an array of coordinates stored on an rtree page.
214319** This function checks that the coordinates are internally consistent (no
214320** x1>x2 conditions) and adds an error message to the RtreeCheck object
214321** if they are not.
214322**
214323** Additionally, if pParent is not NULL, then it is assumed to point to
214324** the array of coordinates on the parent page that bound the page
214325** containing pCell. In this case it is also verified that the two
214326** sets of coordinates are mutually consistent and an error message added
214327** to the RtreeCheck object if they are not.
214328*/
214329static void rtreeCheckCellCoord(
214330  RtreeCheck *pCheck,
214331  i64 iNode,                      /* Node id to use in error messages */
214332  int iCell,                      /* Cell number to use in error messages */
214333  u8 *pCell,                      /* Pointer to cell coordinates */
214334  u8 *pParent                     /* Pointer to parent coordinates */
214335){
214336  RtreeCoord c1, c2;
214337  RtreeCoord p1, p2;
214338  int i;
214339
214340  for(i=0; i<pCheck->nDim; i++){
214341    readCoord(&pCell[4*2*i], &c1);
214342    readCoord(&pCell[4*(2*i + 1)], &c2);
214343
214344    /* printf("%e, %e\n", c1.u.f, c2.u.f); */
214345    if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
214346      rtreeCheckAppendMsg(pCheck,
214347          "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
214348      );
214349    }
214350
214351    if( pParent ){
214352      readCoord(&pParent[4*2*i], &p1);
214353      readCoord(&pParent[4*(2*i + 1)], &p2);
214354
214355      if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
214356       || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
214357      ){
214358        rtreeCheckAppendMsg(pCheck,
214359            "Dimension %d of cell %d on node %lld is corrupt relative to parent"
214360            , i, iCell, iNode
214361        );
214362      }
214363    }
214364  }
214365}
214366
214367/*
214368** Run rtreecheck() checks on node iNode, which is at depth iDepth within
214369** the r-tree structure. Argument aParent points to the array of coordinates
214370** that bound node iNode on the parent node.
214371**
214372** If any problems are discovered, an error message is appended to the
214373** report accumulated in the RtreeCheck object.
214374*/
214375static void rtreeCheckNode(
214376  RtreeCheck *pCheck,
214377  int iDepth,                     /* Depth of iNode (0==leaf) */
214378  u8 *aParent,                    /* Buffer containing parent coords */
214379  i64 iNode                       /* Node to check */
214380){
214381  u8 *aNode = 0;
214382  int nNode = 0;
214383
214384  assert( iNode==1 || aParent!=0 );
214385  assert( pCheck->nDim>0 );
214386
214387  aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
214388  if( aNode ){
214389    if( nNode<4 ){
214390      rtreeCheckAppendMsg(pCheck,
214391          "Node %lld is too small (%d bytes)", iNode, nNode
214392      );
214393    }else{
214394      int nCell;                  /* Number of cells on page */
214395      int i;                      /* Used to iterate through cells */
214396      if( aParent==0 ){
214397        iDepth = readInt16(aNode);
214398        if( iDepth>RTREE_MAX_DEPTH ){
214399          rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
214400          sqlite3_free(aNode);
214401          return;
214402        }
214403      }
214404      nCell = readInt16(&aNode[2]);
214405      if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
214406        rtreeCheckAppendMsg(pCheck,
214407            "Node %lld is too small for cell count of %d (%d bytes)",
214408            iNode, nCell, nNode
214409        );
214410      }else{
214411        for(i=0; i<nCell; i++){
214412          u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
214413          i64 iVal = readInt64(pCell);
214414          rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
214415
214416          if( iDepth>0 ){
214417            rtreeCheckMapping(pCheck, 0, iVal, iNode);
214418            rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
214419            pCheck->nNonLeaf++;
214420          }else{
214421            rtreeCheckMapping(pCheck, 1, iVal, iNode);
214422            pCheck->nLeaf++;
214423          }
214424        }
214425      }
214426    }
214427    sqlite3_free(aNode);
214428  }
214429}
214430
214431/*
214432** The second argument to this function must be either "_rowid" or
214433** "_parent". This function checks that the number of entries in the
214434** %_rowid or %_parent table is exactly nExpect. If not, it adds
214435** an error message to the report in the RtreeCheck object indicated
214436** by the first argument.
214437*/
214438static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
214439  if( pCheck->rc==SQLITE_OK ){
214440    sqlite3_stmt *pCount;
214441    pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
214442        pCheck->zDb, pCheck->zTab, zTbl
214443    );
214444    if( pCount ){
214445      if( sqlite3_step(pCount)==SQLITE_ROW ){
214446        i64 nActual = sqlite3_column_int64(pCount, 0);
214447        if( nActual!=nExpect ){
214448          rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
214449              " - expected %lld, actual %lld" , zTbl, nExpect, nActual
214450          );
214451        }
214452      }
214453      pCheck->rc = sqlite3_finalize(pCount);
214454    }
214455  }
214456}
214457
214458/*
214459** This function does the bulk of the work for the rtree integrity-check.
214460** It is called by rtreecheck(), which is the SQL function implementation.
214461*/
214462static int rtreeCheckTable(
214463  sqlite3 *db,                    /* Database handle to access db through */
214464  const char *zDb,                /* Name of db ("main", "temp" etc.) */
214465  const char *zTab,               /* Name of rtree table to check */
214466  char **pzReport                 /* OUT: sqlite3_malloc'd report text */
214467){
214468  RtreeCheck check;               /* Common context for various routines */
214469  sqlite3_stmt *pStmt = 0;        /* Used to find column count of rtree table */
214470  int nAux = 0;                   /* Number of extra columns. */
214471
214472  /* Initialize the context object */
214473  memset(&check, 0, sizeof(check));
214474  check.db = db;
214475  check.zDb = zDb;
214476  check.zTab = zTab;
214477
214478  /* Find the number of auxiliary columns */
214479  pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
214480  if( pStmt ){
214481    nAux = sqlite3_column_count(pStmt) - 2;
214482    sqlite3_finalize(pStmt);
214483  }else
214484  if( check.rc!=SQLITE_NOMEM ){
214485    check.rc = SQLITE_OK;
214486  }
214487
214488  /* Find number of dimensions in the rtree table. */
214489  pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
214490  if( pStmt ){
214491    int rc;
214492    check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
214493    if( check.nDim<1 ){
214494      rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
214495    }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
214496      check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
214497    }
214498    rc = sqlite3_finalize(pStmt);
214499    if( rc!=SQLITE_CORRUPT ) check.rc = rc;
214500  }
214501
214502  /* Do the actual integrity-check */
214503  if( check.nDim>=1 ){
214504    if( check.rc==SQLITE_OK ){
214505      rtreeCheckNode(&check, 0, 0, 1);
214506    }
214507    rtreeCheckCount(&check, "_rowid", check.nLeaf);
214508    rtreeCheckCount(&check, "_parent", check.nNonLeaf);
214509  }
214510
214511  /* Finalize SQL statements used by the integrity-check */
214512  sqlite3_finalize(check.pGetNode);
214513  sqlite3_finalize(check.aCheckMapping[0]);
214514  sqlite3_finalize(check.aCheckMapping[1]);
214515
214516  *pzReport = check.zReport;
214517  return check.rc;
214518}
214519
214520/*
214521** Implementation of the xIntegrity method for Rtree.
214522*/
214523static int rtreeIntegrity(
214524  sqlite3_vtab *pVtab,   /* The virtual table to check */
214525  const char *zSchema,   /* Schema in which the virtual table lives */
214526  const char *zName,     /* Name of the virtual table */
214527  int isQuick,           /* True for a quick_check */
214528  char **pzErr           /* Write results here */
214529){
214530  Rtree *pRtree = (Rtree*)pVtab;
214531  int rc;
214532  assert( pzErr!=0 && *pzErr==0 );
214533  UNUSED_PARAMETER(zSchema);
214534  UNUSED_PARAMETER(zName);
214535  UNUSED_PARAMETER(isQuick);
214536  rc = rtreeCheckTable(pRtree->db, pRtree->zDb, pRtree->zName, pzErr);
214537  if( rc==SQLITE_OK && *pzErr ){
214538    *pzErr = sqlite3_mprintf("In RTree %s.%s:\n%z",
214539                 pRtree->zDb, pRtree->zName, *pzErr);
214540    if( (*pzErr)==0 ) rc = SQLITE_NOMEM;
214541  }
214542  return rc;
214543}
214544
214545/*
214546** Usage:
214547**
214548**   rtreecheck(<rtree-table>);
214549**   rtreecheck(<database>, <rtree-table>);
214550**
214551** Invoking this SQL function runs an integrity-check on the named rtree
214552** table. The integrity-check verifies the following:
214553**
214554**   1. For each cell in the r-tree structure (%_node table), that:
214555**
214556**       a) for each dimension, (coord1 <= coord2).
214557**
214558**       b) unless the cell is on the root node, that the cell is bounded
214559**          by the parent cell on the parent node.
214560**
214561**       c) for leaf nodes, that there is an entry in the %_rowid
214562**          table corresponding to the cell's rowid value that
214563**          points to the correct node.
214564**
214565**       d) for cells on non-leaf nodes, that there is an entry in the
214566**          %_parent table mapping from the cell's child node to the
214567**          node that it resides on.
214568**
214569**   2. That there are the same number of entries in the %_rowid table
214570**      as there are leaf cells in the r-tree structure, and that there
214571**      is a leaf cell that corresponds to each entry in the %_rowid table.
214572**
214573**   3. That there are the same number of entries in the %_parent table
214574**      as there are non-leaf cells in the r-tree structure, and that
214575**      there is a non-leaf cell that corresponds to each entry in the
214576**      %_parent table.
214577*/
214578static void rtreecheck(
214579  sqlite3_context *ctx,
214580  int nArg,
214581  sqlite3_value **apArg
214582){
214583  if( nArg!=1 && nArg!=2 ){
214584    sqlite3_result_error(ctx,
214585        "wrong number of arguments to function rtreecheck()", -1
214586    );
214587  }else{
214588    int rc;
214589    char *zReport = 0;
214590    const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
214591    const char *zTab;
214592    if( nArg==1 ){
214593      zTab = zDb;
214594      zDb = "main";
214595    }else{
214596      zTab = (const char*)sqlite3_value_text(apArg[1]);
214597    }
214598    rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
214599    if( rc==SQLITE_OK ){
214600      sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
214601    }else{
214602      sqlite3_result_error_code(ctx, rc);
214603    }
214604    sqlite3_free(zReport);
214605  }
214606}
214607
214608/* Conditionally include the geopoly code */
214609#ifdef SQLITE_ENABLE_GEOPOLY
214610/************** Include geopoly.c in the middle of rtree.c *******************/
214611/************** Begin file geopoly.c *****************************************/
214612/*
214613** 2018-05-25
214614**
214615** The author disclaims copyright to this source code.  In place of
214616** a legal notice, here is a blessing:
214617**
214618**    May you do good and not evil.
214619**    May you find forgiveness for yourself and forgive others.
214620**    May you share freely, never taking more than you give.
214621**
214622******************************************************************************
214623**
214624** This file implements an alternative R-Tree virtual table that
214625** uses polygons to express the boundaries of 2-dimensional objects.
214626**
214627** This file is #include-ed onto the end of "rtree.c" so that it has
214628** access to all of the R-Tree internals.
214629*/
214630/* #include <stdlib.h> */
214631
214632/* Enable -DGEOPOLY_ENABLE_DEBUG for debugging facilities */
214633#ifdef GEOPOLY_ENABLE_DEBUG
214634  static int geo_debug = 0;
214635# define GEODEBUG(X) if(geo_debug)printf X
214636#else
214637# define GEODEBUG(X)
214638#endif
214639
214640/* Character class routines */
214641#ifdef sqlite3Isdigit
214642   /* Use the SQLite core versions if this routine is part of the
214643   ** SQLite amalgamation */
214644#  define safe_isdigit(x)  sqlite3Isdigit(x)
214645#  define safe_isalnum(x)  sqlite3Isalnum(x)
214646#  define safe_isxdigit(x) sqlite3Isxdigit(x)
214647#else
214648   /* Use the standard library for separate compilation */
214649#include <ctype.h>  /* amalgamator: keep */
214650#  define safe_isdigit(x)  isdigit((unsigned char)(x))
214651#  define safe_isalnum(x)  isalnum((unsigned char)(x))
214652#  define safe_isxdigit(x) isxdigit((unsigned char)(x))
214653#endif
214654
214655#ifndef JSON_NULL   /* The following stuff repeats things found in json1 */
214656/*
214657** Growing our own isspace() routine this way is twice as fast as
214658** the library isspace() function.
214659*/
214660static const char geopolyIsSpace[] = {
214661  0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,
214662  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214663  1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214664  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214665  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214666  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214667  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214668  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214669  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214670  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214671  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214672  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214673  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214674  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214675  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214676  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
214677};
214678#define fast_isspace(x) (geopolyIsSpace[(unsigned char)x])
214679#endif /* JSON NULL - back to original code */
214680
214681/* Compiler and version */
214682#ifndef GCC_VERSION
214683#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
214684# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
214685#else
214686# define GCC_VERSION 0
214687#endif
214688#endif
214689#ifndef MSVC_VERSION
214690#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
214691# define MSVC_VERSION _MSC_VER
214692#else
214693# define MSVC_VERSION 0
214694#endif
214695#endif
214696
214697/* Datatype for coordinates
214698*/
214699typedef float GeoCoord;
214700
214701/*
214702** Internal representation of a polygon.
214703**
214704** The polygon consists of a sequence of vertexes.  There is a line
214705** segment between each pair of vertexes, and one final segment from
214706** the last vertex back to the first.  (This differs from the GeoJSON
214707** standard in which the final vertex is a repeat of the first.)
214708**
214709** The polygon follows the right-hand rule.  The area to the right of
214710** each segment is "outside" and the area to the left is "inside".
214711**
214712** The on-disk representation consists of a 4-byte header followed by
214713** the values.  The 4-byte header is:
214714**
214715**      encoding    (1 byte)   0=big-endian, 1=little-endian
214716**      nvertex     (3 bytes)  Number of vertexes as a big-endian integer
214717**
214718** Enough space is allocated for 4 coordinates, to work around over-zealous
214719** warnings coming from some compiler (notably, clang). In reality, the size
214720** of each GeoPoly memory allocate is adjusted as necessary so that the
214721** GeoPoly.a[] array at the end is the appropriate size.
214722*/
214723typedef struct GeoPoly GeoPoly;
214724struct GeoPoly {
214725  int nVertex;          /* Number of vertexes */
214726  unsigned char hdr[4]; /* Header for on-disk representation */
214727  GeoCoord a[8];        /* 2*nVertex values. X (longitude) first, then Y */
214728};
214729
214730/* The size of a memory allocation needed for a GeoPoly object sufficient
214731** to hold N coordinate pairs.
214732*/
214733#define GEOPOLY_SZ(N)  (sizeof(GeoPoly) + sizeof(GeoCoord)*2*((N)-4))
214734
214735/* Macros to access coordinates of a GeoPoly.
214736** We have to use these macros, rather than just say p->a[i] in order
214737** to silence (incorrect) UBSAN warnings if the array index is too large.
214738*/
214739#define GeoX(P,I)  (((GeoCoord*)(P)->a)[(I)*2])
214740#define GeoY(P,I)  (((GeoCoord*)(P)->a)[(I)*2+1])
214741
214742
214743/*
214744** State of a parse of a GeoJSON input.
214745*/
214746typedef struct GeoParse GeoParse;
214747struct GeoParse {
214748  const unsigned char *z;   /* Unparsed input */
214749  int nVertex;              /* Number of vertexes in a[] */
214750  int nAlloc;               /* Space allocated to a[] */
214751  int nErr;                 /* Number of errors encountered */
214752  GeoCoord *a;          /* Array of vertexes.  From sqlite3_malloc64() */
214753};
214754
214755/* Do a 4-byte byte swap */
214756static void geopolySwab32(unsigned char *a){
214757  unsigned char t = a[0];
214758  a[0] = a[3];
214759  a[3] = t;
214760  t = a[1];
214761  a[1] = a[2];
214762  a[2] = t;
214763}
214764
214765/* Skip whitespace.  Return the next non-whitespace character. */
214766static char geopolySkipSpace(GeoParse *p){
214767  while( fast_isspace(p->z[0]) ) p->z++;
214768  return p->z[0];
214769}
214770
214771/* Parse out a number.  Write the value into *pVal if pVal!=0.
214772** return non-zero on success and zero if the next token is not a number.
214773*/
214774static int geopolyParseNumber(GeoParse *p, GeoCoord *pVal){
214775  char c = geopolySkipSpace(p);
214776  const unsigned char *z = p->z;
214777  int j = 0;
214778  int seenDP = 0;
214779  int seenE = 0;
214780  if( c=='-' ){
214781    j = 1;
214782    c = z[j];
214783  }
214784  if( c=='0' && z[j+1]>='0' && z[j+1]<='9' ) return 0;
214785  for(;; j++){
214786    c = z[j];
214787    if( safe_isdigit(c) ) continue;
214788    if( c=='.' ){
214789      if( z[j-1]=='-' ) return 0;
214790      if( seenDP ) return 0;
214791      seenDP = 1;
214792      continue;
214793    }
214794    if( c=='e' || c=='E' ){
214795      if( z[j-1]<'0' ) return 0;
214796      if( seenE ) return -1;
214797      seenDP = seenE = 1;
214798      c = z[j+1];
214799      if( c=='+' || c=='-' ){
214800        j++;
214801        c = z[j+1];
214802      }
214803      if( c<'0' || c>'9' ) return 0;
214804      continue;
214805    }
214806    break;
214807  }
214808  if( z[j-1]<'0' ) return 0;
214809  if( pVal ){
214810#ifdef SQLITE_AMALGAMATION
214811     /* The sqlite3AtoF() routine is much much faster than atof(), if it
214812     ** is available */
214813     double r;
214814     (void)sqlite3AtoF((const char*)p->z, &r, j, SQLITE_UTF8);
214815     *pVal = r;
214816#else
214817     *pVal = (GeoCoord)atof((const char*)p->z);
214818#endif
214819  }
214820  p->z += j;
214821  return 1;
214822}
214823
214824/*
214825** If the input is a well-formed JSON array of coordinates with at least
214826** four coordinates and where each coordinate is itself a two-value array,
214827** then convert the JSON into a GeoPoly object and return a pointer to
214828** that object.
214829**
214830** If any error occurs, return NULL.
214831*/
214832static GeoPoly *geopolyParseJson(const unsigned char *z, int *pRc){
214833  GeoParse s;
214834  int rc = SQLITE_OK;
214835  memset(&s, 0, sizeof(s));
214836  s.z = z;
214837  if( geopolySkipSpace(&s)=='[' ){
214838    s.z++;
214839    while( geopolySkipSpace(&s)=='[' ){
214840      int ii = 0;
214841      char c;
214842      s.z++;
214843      if( s.nVertex>=s.nAlloc ){
214844        GeoCoord *aNew;
214845        s.nAlloc = s.nAlloc*2 + 16;
214846        aNew = sqlite3_realloc64(s.a, s.nAlloc*sizeof(GeoCoord)*2 );
214847        if( aNew==0 ){
214848          rc = SQLITE_NOMEM;
214849          s.nErr++;
214850          break;
214851        }
214852        s.a = aNew;
214853      }
214854      while( geopolyParseNumber(&s, ii<=1 ? &s.a[s.nVertex*2+ii] : 0) ){
214855        ii++;
214856        if( ii==2 ) s.nVertex++;
214857        c = geopolySkipSpace(&s);
214858        s.z++;
214859        if( c==',' ) continue;
214860        if( c==']' && ii>=2 ) break;
214861        s.nErr++;
214862        rc = SQLITE_ERROR;
214863        goto parse_json_err;
214864      }
214865      if( geopolySkipSpace(&s)==',' ){
214866        s.z++;
214867        continue;
214868      }
214869      break;
214870    }
214871    if( geopolySkipSpace(&s)==']'
214872     && s.nVertex>=4
214873     && s.a[0]==s.a[s.nVertex*2-2]
214874     && s.a[1]==s.a[s.nVertex*2-1]
214875     && (s.z++, geopolySkipSpace(&s)==0)
214876    ){
214877      GeoPoly *pOut;
214878      int x = 1;
214879      s.nVertex--;  /* Remove the redundant vertex at the end */
214880      pOut = sqlite3_malloc64( GEOPOLY_SZ((sqlite3_int64)s.nVertex) );
214881      x = 1;
214882      if( pOut==0 ) goto parse_json_err;
214883      pOut->nVertex = s.nVertex;
214884      memcpy(pOut->a, s.a, s.nVertex*2*sizeof(GeoCoord));
214885      pOut->hdr[0] = *(unsigned char*)&x;
214886      pOut->hdr[1] = (s.nVertex>>16)&0xff;
214887      pOut->hdr[2] = (s.nVertex>>8)&0xff;
214888      pOut->hdr[3] = s.nVertex&0xff;
214889      sqlite3_free(s.a);
214890      if( pRc ) *pRc = SQLITE_OK;
214891      return pOut;
214892    }else{
214893      s.nErr++;
214894      rc = SQLITE_ERROR;
214895    }
214896  }
214897parse_json_err:
214898  if( pRc ) *pRc = rc;
214899  sqlite3_free(s.a);
214900  return 0;
214901}
214902
214903/*
214904** Given a function parameter, try to interpret it as a polygon, either
214905** in the binary format or JSON text.  Compute a GeoPoly object and
214906** return a pointer to that object.  Or if the input is not a well-formed
214907** polygon, put an error message in sqlite3_context and return NULL.
214908*/
214909static GeoPoly *geopolyFuncParam(
214910  sqlite3_context *pCtx,      /* Context for error messages */
214911  sqlite3_value *pVal,        /* The value to decode */
214912  int *pRc                    /* Write error here */
214913){
214914  GeoPoly *p = 0;
214915  int nByte;
214916  testcase( pCtx==0 );
214917  if( sqlite3_value_type(pVal)==SQLITE_BLOB
214918   && (nByte = sqlite3_value_bytes(pVal))>=(int)(4+6*sizeof(GeoCoord))
214919  ){
214920    const unsigned char *a = sqlite3_value_blob(pVal);
214921    int nVertex;
214922    if( a==0 ){
214923      if( pCtx ) sqlite3_result_error_nomem(pCtx);
214924      return 0;
214925    }
214926    nVertex = (a[1]<<16) + (a[2]<<8) + a[3];
214927    if( (a[0]==0 || a[0]==1)
214928     && (nVertex*2*sizeof(GeoCoord) + 4)==(unsigned int)nByte
214929    ){
214930      p = sqlite3_malloc64( sizeof(*p) + (nVertex-1)*2*sizeof(GeoCoord) );
214931      if( p==0 ){
214932        if( pRc ) *pRc = SQLITE_NOMEM;
214933        if( pCtx ) sqlite3_result_error_nomem(pCtx);
214934      }else{
214935        int x = 1;
214936        p->nVertex = nVertex;
214937        memcpy(p->hdr, a, nByte);
214938        if( a[0] != *(unsigned char*)&x ){
214939          int ii;
214940          for(ii=0; ii<nVertex; ii++){
214941            geopolySwab32((unsigned char*)&GeoX(p,ii));
214942            geopolySwab32((unsigned char*)&GeoY(p,ii));
214943          }
214944          p->hdr[0] ^= 1;
214945        }
214946      }
214947    }
214948    if( pRc ) *pRc = SQLITE_OK;
214949    return p;
214950  }else if( sqlite3_value_type(pVal)==SQLITE_TEXT ){
214951    const unsigned char *zJson = sqlite3_value_text(pVal);
214952    if( zJson==0 ){
214953      if( pRc ) *pRc = SQLITE_NOMEM;
214954      return 0;
214955    }
214956    return geopolyParseJson(zJson, pRc);
214957  }else{
214958    if( pRc ) *pRc = SQLITE_ERROR;
214959    return 0;
214960  }
214961}
214962
214963/*
214964** Implementation of the geopoly_blob(X) function.
214965**
214966** If the input is a well-formed Geopoly BLOB or JSON string
214967** then return the BLOB representation of the polygon.  Otherwise
214968** return NULL.
214969*/
214970static void geopolyBlobFunc(
214971  sqlite3_context *context,
214972  int argc,
214973  sqlite3_value **argv
214974){
214975  GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
214976  (void)argc;
214977  if( p ){
214978    sqlite3_result_blob(context, p->hdr,
214979       4+8*p->nVertex, SQLITE_TRANSIENT);
214980    sqlite3_free(p);
214981  }
214982}
214983
214984/*
214985** SQL function:     geopoly_json(X)
214986**
214987** Interpret X as a polygon and render it as a JSON array
214988** of coordinates.  Or, if X is not a valid polygon, return NULL.
214989*/
214990static void geopolyJsonFunc(
214991  sqlite3_context *context,
214992  int argc,
214993  sqlite3_value **argv
214994){
214995  GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
214996  (void)argc;
214997  if( p ){
214998    sqlite3 *db = sqlite3_context_db_handle(context);
214999    sqlite3_str *x = sqlite3_str_new(db);
215000    int i;
215001    sqlite3_str_append(x, "[", 1);
215002    for(i=0; i<p->nVertex; i++){
215003      sqlite3_str_appendf(x, "[%!g,%!g],", GeoX(p,i), GeoY(p,i));
215004    }
215005    sqlite3_str_appendf(x, "[%!g,%!g]]", GeoX(p,0), GeoY(p,0));
215006    sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
215007    sqlite3_free(p);
215008  }
215009}
215010
215011/*
215012** SQL function:     geopoly_svg(X, ....)
215013**
215014** Interpret X as a polygon and render it as a SVG <polyline>.
215015** Additional arguments are added as attributes to the <polyline>.
215016*/
215017static void geopolySvgFunc(
215018  sqlite3_context *context,
215019  int argc,
215020  sqlite3_value **argv
215021){
215022  GeoPoly *p;
215023  if( argc<1 ) return;
215024  p = geopolyFuncParam(context, argv[0], 0);
215025  if( p ){
215026    sqlite3 *db = sqlite3_context_db_handle(context);
215027    sqlite3_str *x = sqlite3_str_new(db);
215028    int i;
215029    char cSep = '\'';
215030    sqlite3_str_appendf(x, "<polyline points=");
215031    for(i=0; i<p->nVertex; i++){
215032      sqlite3_str_appendf(x, "%c%g,%g", cSep, GeoX(p,i), GeoY(p,i));
215033      cSep = ' ';
215034    }
215035    sqlite3_str_appendf(x, " %g,%g'", GeoX(p,0), GeoY(p,0));
215036    for(i=1; i<argc; i++){
215037      const char *z = (const char*)sqlite3_value_text(argv[i]);
215038      if( z && z[0] ){
215039        sqlite3_str_appendf(x, " %s", z);
215040      }
215041    }
215042    sqlite3_str_appendf(x, "></polyline>");
215043    sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
215044    sqlite3_free(p);
215045  }
215046}
215047
215048/*
215049** SQL Function:      geopoly_xform(poly, A, B, C, D, E, F)
215050**
215051** Transform and/or translate a polygon as follows:
215052**
215053**      x1 = A*x0 + B*y0 + E
215054**      y1 = C*x0 + D*y0 + F
215055**
215056** For a translation:
215057**
215058**      geopoly_xform(poly, 1, 0, 0, 1, x-offset, y-offset)
215059**
215060** Rotate by R around the point (0,0):
215061**
215062**      geopoly_xform(poly, cos(R), sin(R), -sin(R), cos(R), 0, 0)
215063*/
215064static void geopolyXformFunc(
215065  sqlite3_context *context,
215066  int argc,
215067  sqlite3_value **argv
215068){
215069  GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
215070  double A = sqlite3_value_double(argv[1]);
215071  double B = sqlite3_value_double(argv[2]);
215072  double C = sqlite3_value_double(argv[3]);
215073  double D = sqlite3_value_double(argv[4]);
215074  double E = sqlite3_value_double(argv[5]);
215075  double F = sqlite3_value_double(argv[6]);
215076  GeoCoord x1, y1, x0, y0;
215077  int ii;
215078  (void)argc;
215079  if( p ){
215080    for(ii=0; ii<p->nVertex; ii++){
215081      x0 = GeoX(p,ii);
215082      y0 = GeoY(p,ii);
215083      x1 = (GeoCoord)(A*x0 + B*y0 + E);
215084      y1 = (GeoCoord)(C*x0 + D*y0 + F);
215085      GeoX(p,ii) = x1;
215086      GeoY(p,ii) = y1;
215087    }
215088    sqlite3_result_blob(context, p->hdr,
215089       4+8*p->nVertex, SQLITE_TRANSIENT);
215090    sqlite3_free(p);
215091  }
215092}
215093
215094/*
215095** Compute the area enclosed by the polygon.
215096**
215097** This routine can also be used to detect polygons that rotate in
215098** the wrong direction.  Polygons are suppose to be counter-clockwise (CCW).
215099** This routine returns a negative value for clockwise (CW) polygons.
215100*/
215101static double geopolyArea(GeoPoly *p){
215102  double rArea = 0.0;
215103  int ii;
215104  for(ii=0; ii<p->nVertex-1; ii++){
215105    rArea += (GeoX(p,ii) - GeoX(p,ii+1))           /* (x0 - x1) */
215106              * (GeoY(p,ii) + GeoY(p,ii+1))        /* (y0 + y1) */
215107              * 0.5;
215108  }
215109  rArea += (GeoX(p,ii) - GeoX(p,0))                /* (xN - x0) */
215110           * (GeoY(p,ii) + GeoY(p,0))              /* (yN + y0) */
215111           * 0.5;
215112  return rArea;
215113}
215114
215115/*
215116** Implementation of the geopoly_area(X) function.
215117**
215118** If the input is a well-formed Geopoly BLOB then return the area
215119** enclosed by the polygon.  If the polygon circulates clockwise instead
215120** of counterclockwise (as it should) then return the negative of the
215121** enclosed area.  Otherwise return NULL.
215122*/
215123static void geopolyAreaFunc(
215124  sqlite3_context *context,
215125  int argc,
215126  sqlite3_value **argv
215127){
215128  GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
215129  (void)argc;
215130  if( p ){
215131    sqlite3_result_double(context, geopolyArea(p));
215132    sqlite3_free(p);
215133  }
215134}
215135
215136/*
215137** Implementation of the geopoly_ccw(X) function.
215138**
215139** If the rotation of polygon X is clockwise (incorrect) instead of
215140** counter-clockwise (the correct winding order according to RFC7946)
215141** then reverse the order of the vertexes in polygon X.
215142**
215143** In other words, this routine returns a CCW polygon regardless of the
215144** winding order of its input.
215145**
215146** Use this routine to sanitize historical inputs that that sometimes
215147** contain polygons that wind in the wrong direction.
215148*/
215149static void geopolyCcwFunc(
215150  sqlite3_context *context,
215151  int argc,
215152  sqlite3_value **argv
215153){
215154  GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
215155  (void)argc;
215156  if( p ){
215157    if( geopolyArea(p)<0.0 ){
215158      int ii, jj;
215159      for(ii=1, jj=p->nVertex-1; ii<jj; ii++, jj--){
215160        GeoCoord t = GeoX(p,ii);
215161        GeoX(p,ii) = GeoX(p,jj);
215162        GeoX(p,jj) = t;
215163        t = GeoY(p,ii);
215164        GeoY(p,ii) = GeoY(p,jj);
215165        GeoY(p,jj) = t;
215166      }
215167    }
215168    sqlite3_result_blob(context, p->hdr,
215169       4+8*p->nVertex, SQLITE_TRANSIENT);
215170    sqlite3_free(p);
215171  }
215172}
215173
215174#define GEOPOLY_PI 3.1415926535897932385
215175
215176/* Fast approximation for sine(X) for X between -0.5*pi and 2*pi
215177*/
215178static double geopolySine(double r){
215179  assert( r>=-0.5*GEOPOLY_PI && r<=2.0*GEOPOLY_PI );
215180  if( r>=1.5*GEOPOLY_PI ){
215181    r -= 2.0*GEOPOLY_PI;
215182  }
215183  if( r>=0.5*GEOPOLY_PI ){
215184    return -geopolySine(r-GEOPOLY_PI);
215185  }else{
215186    double r2 = r*r;
215187    double r3 = r2*r;
215188    double r5 = r3*r2;
215189    return 0.9996949*r - 0.1656700*r3 + 0.0075134*r5;
215190  }
215191}
215192
215193/*
215194** Function:   geopoly_regular(X,Y,R,N)
215195**
215196** Construct a simple, convex, regular polygon centered at X, Y
215197** with circumradius R and with N sides.
215198*/
215199static void geopolyRegularFunc(
215200  sqlite3_context *context,
215201  int argc,
215202  sqlite3_value **argv
215203){
215204  double x = sqlite3_value_double(argv[0]);
215205  double y = sqlite3_value_double(argv[1]);
215206  double r = sqlite3_value_double(argv[2]);
215207  int n = sqlite3_value_int(argv[3]);
215208  int i;
215209  GeoPoly *p;
215210  (void)argc;
215211
215212  if( n<3 || r<=0.0 ) return;
215213  if( n>1000 ) n = 1000;
215214  p = sqlite3_malloc64( sizeof(*p) + (n-1)*2*sizeof(GeoCoord) );
215215  if( p==0 ){
215216    sqlite3_result_error_nomem(context);
215217    return;
215218  }
215219  i = 1;
215220  p->hdr[0] = *(unsigned char*)&i;
215221  p->hdr[1] = 0;
215222  p->hdr[2] = (n>>8)&0xff;
215223  p->hdr[3] = n&0xff;
215224  for(i=0; i<n; i++){
215225    double rAngle = 2.0*GEOPOLY_PI*i/n;
215226    GeoX(p,i) = x - r*geopolySine(rAngle-0.5*GEOPOLY_PI);
215227    GeoY(p,i) = y + r*geopolySine(rAngle);
215228  }
215229  sqlite3_result_blob(context, p->hdr, 4+8*n, SQLITE_TRANSIENT);
215230  sqlite3_free(p);
215231}
215232
215233/*
215234** If pPoly is a polygon, compute its bounding box. Then:
215235**
215236**    (1) if aCoord!=0 store the bounding box in aCoord, returning NULL
215237**    (2) otherwise, compute a GeoPoly for the bounding box and return the
215238**        new GeoPoly
215239**
215240** If pPoly is NULL but aCoord is not NULL, then compute a new GeoPoly from
215241** the bounding box in aCoord and return a pointer to that GeoPoly.
215242*/
215243static GeoPoly *geopolyBBox(
215244  sqlite3_context *context,   /* For recording the error */
215245  sqlite3_value *pPoly,       /* The polygon */
215246  RtreeCoord *aCoord,         /* Results here */
215247  int *pRc                    /* Error code here */
215248){
215249  GeoPoly *pOut = 0;
215250  GeoPoly *p;
215251  float mnX, mxX, mnY, mxY;
215252  if( pPoly==0 && aCoord!=0 ){
215253    p = 0;
215254    mnX = aCoord[0].f;
215255    mxX = aCoord[1].f;
215256    mnY = aCoord[2].f;
215257    mxY = aCoord[3].f;
215258    goto geopolyBboxFill;
215259  }else{
215260    p = geopolyFuncParam(context, pPoly, pRc);
215261  }
215262  if( p ){
215263    int ii;
215264    mnX = mxX = GeoX(p,0);
215265    mnY = mxY = GeoY(p,0);
215266    for(ii=1; ii<p->nVertex; ii++){
215267      double r = GeoX(p,ii);
215268      if( r<mnX ) mnX = (float)r;
215269      else if( r>mxX ) mxX = (float)r;
215270      r = GeoY(p,ii);
215271      if( r<mnY ) mnY = (float)r;
215272      else if( r>mxY ) mxY = (float)r;
215273    }
215274    if( pRc ) *pRc = SQLITE_OK;
215275    if( aCoord==0 ){
215276      geopolyBboxFill:
215277      pOut = sqlite3_realloc64(p, GEOPOLY_SZ(4));
215278      if( pOut==0 ){
215279        sqlite3_free(p);
215280        if( context ) sqlite3_result_error_nomem(context);
215281        if( pRc ) *pRc = SQLITE_NOMEM;
215282        return 0;
215283      }
215284      pOut->nVertex = 4;
215285      ii = 1;
215286      pOut->hdr[0] = *(unsigned char*)&ii;
215287      pOut->hdr[1] = 0;
215288      pOut->hdr[2] = 0;
215289      pOut->hdr[3] = 4;
215290      GeoX(pOut,0) = mnX;
215291      GeoY(pOut,0) = mnY;
215292      GeoX(pOut,1) = mxX;
215293      GeoY(pOut,1) = mnY;
215294      GeoX(pOut,2) = mxX;
215295      GeoY(pOut,2) = mxY;
215296      GeoX(pOut,3) = mnX;
215297      GeoY(pOut,3) = mxY;
215298    }else{
215299      sqlite3_free(p);
215300      aCoord[0].f = mnX;
215301      aCoord[1].f = mxX;
215302      aCoord[2].f = mnY;
215303      aCoord[3].f = mxY;
215304    }
215305  }else if( aCoord ){
215306    memset(aCoord, 0, sizeof(RtreeCoord)*4);
215307  }
215308  return pOut;
215309}
215310
215311/*
215312** Implementation of the geopoly_bbox(X) SQL function.
215313*/
215314static void geopolyBBoxFunc(
215315  sqlite3_context *context,
215316  int argc,
215317  sqlite3_value **argv
215318){
215319  GeoPoly *p = geopolyBBox(context, argv[0], 0, 0);
215320  (void)argc;
215321  if( p ){
215322    sqlite3_result_blob(context, p->hdr,
215323       4+8*p->nVertex, SQLITE_TRANSIENT);
215324    sqlite3_free(p);
215325  }
215326}
215327
215328/*
215329** State vector for the geopoly_group_bbox() aggregate function.
215330*/
215331typedef struct GeoBBox GeoBBox;
215332struct GeoBBox {
215333  int isInit;
215334  RtreeCoord a[4];
215335};
215336
215337
215338/*
215339** Implementation of the geopoly_group_bbox(X) aggregate SQL function.
215340*/
215341static void geopolyBBoxStep(
215342  sqlite3_context *context,
215343  int argc,
215344  sqlite3_value **argv
215345){
215346  RtreeCoord a[4];
215347  int rc = SQLITE_OK;
215348  (void)argc;
215349  (void)geopolyBBox(context, argv[0], a, &rc);
215350  if( rc==SQLITE_OK ){
215351    GeoBBox *pBBox;
215352    pBBox = (GeoBBox*)sqlite3_aggregate_context(context, sizeof(*pBBox));
215353    if( pBBox==0 ) return;
215354    if( pBBox->isInit==0 ){
215355      pBBox->isInit = 1;
215356      memcpy(pBBox->a, a, sizeof(RtreeCoord)*4);
215357    }else{
215358      if( a[0].f < pBBox->a[0].f ) pBBox->a[0] = a[0];
215359      if( a[1].f > pBBox->a[1].f ) pBBox->a[1] = a[1];
215360      if( a[2].f < pBBox->a[2].f ) pBBox->a[2] = a[2];
215361      if( a[3].f > pBBox->a[3].f ) pBBox->a[3] = a[3];
215362    }
215363  }
215364}
215365static void geopolyBBoxFinal(
215366  sqlite3_context *context
215367){
215368  GeoPoly *p;
215369  GeoBBox *pBBox;
215370  pBBox = (GeoBBox*)sqlite3_aggregate_context(context, 0);
215371  if( pBBox==0 ) return;
215372  p = geopolyBBox(context, 0, pBBox->a, 0);
215373  if( p ){
215374    sqlite3_result_blob(context, p->hdr,
215375       4+8*p->nVertex, SQLITE_TRANSIENT);
215376    sqlite3_free(p);
215377  }
215378}
215379
215380
215381/*
215382** Determine if point (x0,y0) is beneath line segment (x1,y1)->(x2,y2).
215383** Returns:
215384**
215385**    +2  x0,y0 is on the line segement
215386**
215387**    +1  x0,y0 is beneath line segment
215388**
215389**    0   x0,y0 is not on or beneath the line segment or the line segment
215390**        is vertical and x0,y0 is not on the line segment
215391**
215392** The left-most coordinate min(x1,x2) is not considered to be part of
215393** the line segment for the purposes of this analysis.
215394*/
215395static int pointBeneathLine(
215396  double x0, double y0,
215397  double x1, double y1,
215398  double x2, double y2
215399){
215400  double y;
215401  if( x0==x1 && y0==y1 ) return 2;
215402  if( x1<x2 ){
215403    if( x0<=x1 || x0>x2 ) return 0;
215404  }else if( x1>x2 ){
215405    if( x0<=x2 || x0>x1 ) return 0;
215406  }else{
215407    /* Vertical line segment */
215408    if( x0!=x1 ) return 0;
215409    if( y0<y1 && y0<y2 ) return 0;
215410    if( y0>y1 && y0>y2 ) return 0;
215411    return 2;
215412  }
215413  y = y1 + (y2-y1)*(x0-x1)/(x2-x1);
215414  if( y0==y ) return 2;
215415  if( y0<y ) return 1;
215416  return 0;
215417}
215418
215419/*
215420** SQL function:    geopoly_contains_point(P,X,Y)
215421**
215422** Return +2 if point X,Y is within polygon P.
215423** Return +1 if point X,Y is on the polygon boundary.
215424** Return 0 if point X,Y is outside the polygon
215425*/
215426static void geopolyContainsPointFunc(
215427  sqlite3_context *context,
215428  int argc,
215429  sqlite3_value **argv
215430){
215431  GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
215432  double x0 = sqlite3_value_double(argv[1]);
215433  double y0 = sqlite3_value_double(argv[2]);
215434  int v = 0;
215435  int cnt = 0;
215436  int ii;
215437  (void)argc;
215438
215439  if( p1==0 ) return;
215440  for(ii=0; ii<p1->nVertex-1; ii++){
215441    v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),
215442                               GeoX(p1,ii+1),GeoY(p1,ii+1));
215443    if( v==2 ) break;
215444    cnt += v;
215445  }
215446  if( v!=2 ){
215447    v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),
215448                               GeoX(p1,0),  GeoY(p1,0));
215449  }
215450  if( v==2 ){
215451    sqlite3_result_int(context, 1);
215452  }else if( ((v+cnt)&1)==0 ){
215453    sqlite3_result_int(context, 0);
215454  }else{
215455    sqlite3_result_int(context, 2);
215456  }
215457  sqlite3_free(p1);
215458}
215459
215460/* Forward declaration */
215461static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2);
215462
215463/*
215464** SQL function:    geopoly_within(P1,P2)
215465**
215466** Return +2 if P1 and P2 are the same polygon
215467** Return +1 if P2 is contained within P1
215468** Return 0 if any part of P2 is on the outside of P1
215469**
215470*/
215471static void geopolyWithinFunc(
215472  sqlite3_context *context,
215473  int argc,
215474  sqlite3_value **argv
215475){
215476  GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
215477  GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
215478  (void)argc;
215479  if( p1 && p2 ){
215480    int x = geopolyOverlap(p1, p2);
215481    if( x<0 ){
215482      sqlite3_result_error_nomem(context);
215483    }else{
215484      sqlite3_result_int(context, x==2 ? 1 : x==4 ? 2 : 0);
215485    }
215486  }
215487  sqlite3_free(p1);
215488  sqlite3_free(p2);
215489}
215490
215491/* Objects used by the overlap algorihm. */
215492typedef struct GeoEvent GeoEvent;
215493typedef struct GeoSegment GeoSegment;
215494typedef struct GeoOverlap GeoOverlap;
215495struct GeoEvent {
215496  double x;              /* X coordinate at which event occurs */
215497  int eType;             /* 0 for ADD, 1 for REMOVE */
215498  GeoSegment *pSeg;      /* The segment to be added or removed */
215499  GeoEvent *pNext;       /* Next event in the sorted list */
215500};
215501struct GeoSegment {
215502  double C, B;           /* y = C*x + B */
215503  double y;              /* Current y value */
215504  float y0;              /* Initial y value */
215505  unsigned char side;    /* 1 for p1, 2 for p2 */
215506  unsigned int idx;      /* Which segment within the side */
215507  GeoSegment *pNext;     /* Next segment in a list sorted by y */
215508};
215509struct GeoOverlap {
215510  GeoEvent *aEvent;          /* Array of all events */
215511  GeoSegment *aSegment;      /* Array of all segments */
215512  int nEvent;                /* Number of events */
215513  int nSegment;              /* Number of segments */
215514};
215515
215516/*
215517** Add a single segment and its associated events.
215518*/
215519static void geopolyAddOneSegment(
215520  GeoOverlap *p,
215521  GeoCoord x0,
215522  GeoCoord y0,
215523  GeoCoord x1,
215524  GeoCoord y1,
215525  unsigned char side,
215526  unsigned int idx
215527){
215528  GeoSegment *pSeg;
215529  GeoEvent *pEvent;
215530  if( x0==x1 ) return;  /* Ignore vertical segments */
215531  if( x0>x1 ){
215532    GeoCoord t = x0;
215533    x0 = x1;
215534    x1 = t;
215535    t = y0;
215536    y0 = y1;
215537    y1 = t;
215538  }
215539  pSeg = p->aSegment + p->nSegment;
215540  p->nSegment++;
215541  pSeg->C = (y1-y0)/(x1-x0);
215542  pSeg->B = y1 - x1*pSeg->C;
215543  pSeg->y0 = y0;
215544  pSeg->side = side;
215545  pSeg->idx = idx;
215546  pEvent = p->aEvent + p->nEvent;
215547  p->nEvent++;
215548  pEvent->x = x0;
215549  pEvent->eType = 0;
215550  pEvent->pSeg = pSeg;
215551  pEvent = p->aEvent + p->nEvent;
215552  p->nEvent++;
215553  pEvent->x = x1;
215554  pEvent->eType = 1;
215555  pEvent->pSeg = pSeg;
215556}
215557
215558
215559
215560/*
215561** Insert all segments and events for polygon pPoly.
215562*/
215563static void geopolyAddSegments(
215564  GeoOverlap *p,          /* Add segments to this Overlap object */
215565  GeoPoly *pPoly,         /* Take all segments from this polygon */
215566  unsigned char side      /* The side of pPoly */
215567){
215568  unsigned int i;
215569  GeoCoord *x;
215570  for(i=0; i<(unsigned)pPoly->nVertex-1; i++){
215571    x = &GeoX(pPoly,i);
215572    geopolyAddOneSegment(p, x[0], x[1], x[2], x[3], side, i);
215573  }
215574  x = &GeoX(pPoly,i);
215575  geopolyAddOneSegment(p, x[0], x[1], pPoly->a[0], pPoly->a[1], side, i);
215576}
215577
215578/*
215579** Merge two lists of sorted events by X coordinate
215580*/
215581static GeoEvent *geopolyEventMerge(GeoEvent *pLeft, GeoEvent *pRight){
215582  GeoEvent head, *pLast;
215583  head.pNext = 0;
215584  pLast = &head;
215585  while( pRight && pLeft ){
215586    if( pRight->x <= pLeft->x ){
215587      pLast->pNext = pRight;
215588      pLast = pRight;
215589      pRight = pRight->pNext;
215590    }else{
215591      pLast->pNext = pLeft;
215592      pLast = pLeft;
215593      pLeft = pLeft->pNext;
215594    }
215595  }
215596  pLast->pNext = pRight ? pRight : pLeft;
215597  return head.pNext;
215598}
215599
215600/*
215601** Sort an array of nEvent event objects into a list.
215602*/
215603static GeoEvent *geopolySortEventsByX(GeoEvent *aEvent, int nEvent){
215604  int mx = 0;
215605  int i, j;
215606  GeoEvent *p;
215607  GeoEvent *a[50];
215608  for(i=0; i<nEvent; i++){
215609    p = &aEvent[i];
215610    p->pNext = 0;
215611    for(j=0; j<mx && a[j]; j++){
215612      p = geopolyEventMerge(a[j], p);
215613      a[j] = 0;
215614    }
215615    a[j] = p;
215616    if( j>=mx ) mx = j+1;
215617  }
215618  p = 0;
215619  for(i=0; i<mx; i++){
215620    p = geopolyEventMerge(a[i], p);
215621  }
215622  return p;
215623}
215624
215625/*
215626** Merge two lists of sorted segments by Y, and then by C.
215627*/
215628static GeoSegment *geopolySegmentMerge(GeoSegment *pLeft, GeoSegment *pRight){
215629  GeoSegment head, *pLast;
215630  head.pNext = 0;
215631  pLast = &head;
215632  while( pRight && pLeft ){
215633    double r = pRight->y - pLeft->y;
215634    if( r==0.0 ) r = pRight->C - pLeft->C;
215635    if( r<0.0 ){
215636      pLast->pNext = pRight;
215637      pLast = pRight;
215638      pRight = pRight->pNext;
215639    }else{
215640      pLast->pNext = pLeft;
215641      pLast = pLeft;
215642      pLeft = pLeft->pNext;
215643    }
215644  }
215645  pLast->pNext = pRight ? pRight : pLeft;
215646  return head.pNext;
215647}
215648
215649/*
215650** Sort a list of GeoSegments in order of increasing Y and in the event of
215651** a tie, increasing C (slope).
215652*/
215653static GeoSegment *geopolySortSegmentsByYAndC(GeoSegment *pList){
215654  int mx = 0;
215655  int i;
215656  GeoSegment *p;
215657  GeoSegment *a[50];
215658  while( pList ){
215659    p = pList;
215660    pList = pList->pNext;
215661    p->pNext = 0;
215662    for(i=0; i<mx && a[i]; i++){
215663      p = geopolySegmentMerge(a[i], p);
215664      a[i] = 0;
215665    }
215666    a[i] = p;
215667    if( i>=mx ) mx = i+1;
215668  }
215669  p = 0;
215670  for(i=0; i<mx; i++){
215671    p = geopolySegmentMerge(a[i], p);
215672  }
215673  return p;
215674}
215675
215676/*
215677** Determine the overlap between two polygons
215678*/
215679static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){
215680  sqlite3_int64 nVertex = p1->nVertex + p2->nVertex + 2;
215681  GeoOverlap *p;
215682  sqlite3_int64 nByte;
215683  GeoEvent *pThisEvent;
215684  double rX;
215685  int rc = 0;
215686  int needSort = 0;
215687  GeoSegment *pActive = 0;
215688  GeoSegment *pSeg;
215689  unsigned char aOverlap[4];
215690
215691  nByte = sizeof(GeoEvent)*nVertex*2
215692           + sizeof(GeoSegment)*nVertex
215693           + sizeof(GeoOverlap);
215694  p = sqlite3_malloc64( nByte );
215695  if( p==0 ) return -1;
215696  p->aEvent = (GeoEvent*)&p[1];
215697  p->aSegment = (GeoSegment*)&p->aEvent[nVertex*2];
215698  p->nEvent = p->nSegment = 0;
215699  geopolyAddSegments(p, p1, 1);
215700  geopolyAddSegments(p, p2, 2);
215701  pThisEvent = geopolySortEventsByX(p->aEvent, p->nEvent);
215702  rX = pThisEvent && pThisEvent->x==0.0 ? -1.0 : 0.0;
215703  memset(aOverlap, 0, sizeof(aOverlap));
215704  while( pThisEvent ){
215705    if( pThisEvent->x!=rX ){
215706      GeoSegment *pPrev = 0;
215707      int iMask = 0;
215708      GEODEBUG(("Distinct X: %g\n", pThisEvent->x));
215709      rX = pThisEvent->x;
215710      if( needSort ){
215711        GEODEBUG(("SORT\n"));
215712        pActive = geopolySortSegmentsByYAndC(pActive);
215713        needSort = 0;
215714      }
215715      for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
215716        if( pPrev ){
215717          if( pPrev->y!=pSeg->y ){
215718            GEODEBUG(("MASK: %d\n", iMask));
215719            aOverlap[iMask] = 1;
215720          }
215721        }
215722        iMask ^= pSeg->side;
215723        pPrev = pSeg;
215724      }
215725      pPrev = 0;
215726      for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
215727        double y = pSeg->C*rX + pSeg->B;
215728        GEODEBUG(("Segment %d.%d %g->%g\n", pSeg->side, pSeg->idx, pSeg->y, y));
215729        pSeg->y = y;
215730        if( pPrev ){
215731          if( pPrev->y>pSeg->y && pPrev->side!=pSeg->side ){
215732            rc = 1;
215733            GEODEBUG(("Crossing: %d.%d and %d.%d\n",
215734                    pPrev->side, pPrev->idx,
215735                    pSeg->side, pSeg->idx));
215736            goto geopolyOverlapDone;
215737          }else if( pPrev->y!=pSeg->y ){
215738            GEODEBUG(("MASK: %d\n", iMask));
215739            aOverlap[iMask] = 1;
215740          }
215741        }
215742        iMask ^= pSeg->side;
215743        pPrev = pSeg;
215744      }
215745    }
215746    GEODEBUG(("%s %d.%d C=%g B=%g\n",
215747      pThisEvent->eType ? "RM " : "ADD",
215748      pThisEvent->pSeg->side, pThisEvent->pSeg->idx,
215749      pThisEvent->pSeg->C,
215750      pThisEvent->pSeg->B));
215751    if( pThisEvent->eType==0 ){
215752      /* Add a segment */
215753      pSeg = pThisEvent->pSeg;
215754      pSeg->y = pSeg->y0;
215755      pSeg->pNext = pActive;
215756      pActive = pSeg;
215757      needSort = 1;
215758    }else{
215759      /* Remove a segment */
215760      if( pActive==pThisEvent->pSeg ){
215761        pActive = ALWAYS(pActive) ? pActive->pNext : 0;
215762      }else{
215763        for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
215764          if( pSeg->pNext==pThisEvent->pSeg ){
215765            pSeg->pNext = ALWAYS(pSeg->pNext) ? pSeg->pNext->pNext : 0;
215766            break;
215767          }
215768        }
215769      }
215770    }
215771    pThisEvent = pThisEvent->pNext;
215772  }
215773  if( aOverlap[3]==0 ){
215774    rc = 0;
215775  }else if( aOverlap[1]!=0 && aOverlap[2]==0 ){
215776    rc = 3;
215777  }else if( aOverlap[1]==0 && aOverlap[2]!=0 ){
215778    rc = 2;
215779  }else if( aOverlap[1]==0 && aOverlap[2]==0 ){
215780    rc = 4;
215781  }else{
215782    rc = 1;
215783  }
215784
215785geopolyOverlapDone:
215786  sqlite3_free(p);
215787  return rc;
215788}
215789
215790/*
215791** SQL function:    geopoly_overlap(P1,P2)
215792**
215793** Determine whether or not P1 and P2 overlap. Return value:
215794**
215795**   0     The two polygons are disjoint
215796**   1     They overlap
215797**   2     P1 is completely contained within P2
215798**   3     P2 is completely contained within P1
215799**   4     P1 and P2 are the same polygon
215800**   NULL  Either P1 or P2 or both are not valid polygons
215801*/
215802static void geopolyOverlapFunc(
215803  sqlite3_context *context,
215804  int argc,
215805  sqlite3_value **argv
215806){
215807  GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
215808  GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
215809  (void)argc;
215810  if( p1 && p2 ){
215811    int x = geopolyOverlap(p1, p2);
215812    if( x<0 ){
215813      sqlite3_result_error_nomem(context);
215814    }else{
215815      sqlite3_result_int(context, x);
215816    }
215817  }
215818  sqlite3_free(p1);
215819  sqlite3_free(p2);
215820}
215821
215822/*
215823** Enable or disable debugging output
215824*/
215825static void geopolyDebugFunc(
215826  sqlite3_context *context,
215827  int argc,
215828  sqlite3_value **argv
215829){
215830  (void)context;
215831  (void)argc;
215832#ifdef GEOPOLY_ENABLE_DEBUG
215833  geo_debug = sqlite3_value_int(argv[0]);
215834#else
215835  (void)argv;
215836#endif
215837}
215838
215839/*
215840** This function is the implementation of both the xConnect and xCreate
215841** methods of the geopoly virtual table.
215842**
215843**   argv[0]   -> module name
215844**   argv[1]   -> database name
215845**   argv[2]   -> table name
215846**   argv[...] -> column names...
215847*/
215848static int geopolyInit(
215849  sqlite3 *db,                        /* Database connection */
215850  void *pAux,                         /* One of the RTREE_COORD_* constants */
215851  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
215852  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
215853  char **pzErr,                       /* OUT: Error message, if any */
215854  int isCreate                        /* True for xCreate, false for xConnect */
215855){
215856  int rc = SQLITE_OK;
215857  Rtree *pRtree;
215858  sqlite3_int64 nDb;              /* Length of string argv[1] */
215859  sqlite3_int64 nName;            /* Length of string argv[2] */
215860  sqlite3_str *pSql;
215861  char *zSql;
215862  int ii;
215863  (void)pAux;
215864
215865  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
215866  sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
215867
215868  /* Allocate the sqlite3_vtab structure */
215869  nDb = strlen(argv[1]);
215870  nName = strlen(argv[2]);
215871  pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName*2+8);
215872  if( !pRtree ){
215873    return SQLITE_NOMEM;
215874  }
215875  memset(pRtree, 0, sizeof(Rtree)+nDb+nName*2+8);
215876  pRtree->nBusy = 1;
215877  pRtree->base.pModule = &rtreeModule;
215878  pRtree->zDb = (char *)&pRtree[1];
215879  pRtree->zName = &pRtree->zDb[nDb+1];
215880  pRtree->zNodeName = &pRtree->zName[nName+1];
215881  pRtree->eCoordType = RTREE_COORD_REAL32;
215882  pRtree->nDim = 2;
215883  pRtree->nDim2 = 4;
215884  memcpy(pRtree->zDb, argv[1], nDb);
215885  memcpy(pRtree->zName, argv[2], nName);
215886  memcpy(pRtree->zNodeName, argv[2], nName);
215887  memcpy(&pRtree->zNodeName[nName], "_node", 6);
215888
215889
215890  /* Create/Connect to the underlying relational database schema. If
215891  ** that is successful, call sqlite3_declare_vtab() to configure
215892  ** the r-tree table schema.
215893  */
215894  pSql = sqlite3_str_new(db);
215895  sqlite3_str_appendf(pSql, "CREATE TABLE x(_shape");
215896  pRtree->nAux = 1;         /* Add one for _shape */
215897  pRtree->nAuxNotNull = 1;  /* The _shape column is always not-null */
215898  for(ii=3; ii<argc; ii++){
215899    pRtree->nAux++;
215900    sqlite3_str_appendf(pSql, ",%s", argv[ii]);
215901  }
215902  sqlite3_str_appendf(pSql, ");");
215903  zSql = sqlite3_str_finish(pSql);
215904  if( !zSql ){
215905    rc = SQLITE_NOMEM;
215906  }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
215907    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
215908  }
215909  sqlite3_free(zSql);
215910  if( rc ) goto geopolyInit_fail;
215911  pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
215912
215913  /* Figure out the node size to use. */
215914  rc = getNodeSize(db, pRtree, isCreate, pzErr);
215915  if( rc ) goto geopolyInit_fail;
215916  rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
215917  if( rc ){
215918    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
215919    goto geopolyInit_fail;
215920  }
215921
215922  *ppVtab = (sqlite3_vtab *)pRtree;
215923  return SQLITE_OK;
215924
215925geopolyInit_fail:
215926  if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
215927  assert( *ppVtab==0 );
215928  assert( pRtree->nBusy==1 );
215929  rtreeRelease(pRtree);
215930  return rc;
215931}
215932
215933
215934/*
215935** GEOPOLY virtual table module xCreate method.
215936*/
215937static int geopolyCreate(
215938  sqlite3 *db,
215939  void *pAux,
215940  int argc, const char *const*argv,
215941  sqlite3_vtab **ppVtab,
215942  char **pzErr
215943){
215944  return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
215945}
215946
215947/*
215948** GEOPOLY virtual table module xConnect method.
215949*/
215950static int geopolyConnect(
215951  sqlite3 *db,
215952  void *pAux,
215953  int argc, const char *const*argv,
215954  sqlite3_vtab **ppVtab,
215955  char **pzErr
215956){
215957  return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
215958}
215959
215960
215961/*
215962** GEOPOLY virtual table module xFilter method.
215963**
215964** Query plans:
215965**
215966**      1         rowid lookup
215967**      2         search for objects overlapping the same bounding box
215968**                that contains polygon argv[0]
215969**      3         search for objects overlapping the same bounding box
215970**                that contains polygon argv[0]
215971**      4         full table scan
215972*/
215973static int geopolyFilter(
215974  sqlite3_vtab_cursor *pVtabCursor,     /* The cursor to initialize */
215975  int idxNum,                           /* Query plan */
215976  const char *idxStr,                   /* Not Used */
215977  int argc, sqlite3_value **argv        /* Parameters to the query plan */
215978){
215979  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
215980  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
215981  RtreeNode *pRoot = 0;
215982  int rc = SQLITE_OK;
215983  int iCell = 0;
215984  (void)idxStr;
215985
215986  rtreeReference(pRtree);
215987
215988  /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
215989  resetCursor(pCsr);
215990
215991  pCsr->iStrategy = idxNum;
215992  if( idxNum==1 ){
215993    /* Special case - lookup by rowid. */
215994    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
215995    RtreeSearchPoint *p;     /* Search point for the leaf */
215996    i64 iRowid = sqlite3_value_int64(argv[0]);
215997    i64 iNode = 0;
215998    rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
215999    if( rc==SQLITE_OK && pLeaf!=0 ){
216000      p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
216001      assert( p!=0 );  /* Always returns pCsr->sPoint */
216002      pCsr->aNode[0] = pLeaf;
216003      p->id = iNode;
216004      p->eWithin = PARTLY_WITHIN;
216005      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
216006      p->iCell = (u8)iCell;
216007      RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
216008    }else{
216009      pCsr->atEOF = 1;
216010    }
216011  }else{
216012    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
216013    ** with the configured constraints.
216014    */
216015    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
216016    if( rc==SQLITE_OK && idxNum<=3 ){
216017      RtreeCoord bbox[4];
216018      RtreeConstraint *p;
216019      assert( argc==1 );
216020      assert( argv[0]!=0 );
216021      geopolyBBox(0, argv[0], bbox, &rc);
216022      if( rc ){
216023        goto geopoly_filter_end;
216024      }
216025      pCsr->aConstraint = p = sqlite3_malloc(sizeof(RtreeConstraint)*4);
216026      pCsr->nConstraint = 4;
216027      if( p==0 ){
216028        rc = SQLITE_NOMEM;
216029      }else{
216030        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*4);
216031        memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
216032        if( idxNum==2 ){
216033          /* Overlap query */
216034          p->op = 'B';
216035          p->iCoord = 0;
216036          p->u.rValue = bbox[1].f;
216037          p++;
216038          p->op = 'D';
216039          p->iCoord = 1;
216040          p->u.rValue = bbox[0].f;
216041          p++;
216042          p->op = 'B';
216043          p->iCoord = 2;
216044          p->u.rValue = bbox[3].f;
216045          p++;
216046          p->op = 'D';
216047          p->iCoord = 3;
216048          p->u.rValue = bbox[2].f;
216049        }else{
216050          /* Within query */
216051          p->op = 'D';
216052          p->iCoord = 0;
216053          p->u.rValue = bbox[0].f;
216054          p++;
216055          p->op = 'B';
216056          p->iCoord = 1;
216057          p->u.rValue = bbox[1].f;
216058          p++;
216059          p->op = 'D';
216060          p->iCoord = 2;
216061          p->u.rValue = bbox[2].f;
216062          p++;
216063          p->op = 'B';
216064          p->iCoord = 3;
216065          p->u.rValue = bbox[3].f;
216066        }
216067      }
216068    }
216069    if( rc==SQLITE_OK ){
216070      RtreeSearchPoint *pNew;
216071      pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
216072      if( pNew==0 ){
216073        rc = SQLITE_NOMEM;
216074        goto geopoly_filter_end;
216075      }
216076      pNew->id = 1;
216077      pNew->iCell = 0;
216078      pNew->eWithin = PARTLY_WITHIN;
216079      assert( pCsr->bPoint==1 );
216080      pCsr->aNode[0] = pRoot;
216081      pRoot = 0;
216082      RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
216083      rc = rtreeStepToLeaf(pCsr);
216084    }
216085  }
216086
216087geopoly_filter_end:
216088  nodeRelease(pRtree, pRoot);
216089  rtreeRelease(pRtree);
216090  return rc;
216091}
216092
216093/*
216094** Rtree virtual table module xBestIndex method. There are three
216095** table scan strategies to choose from (in order from most to
216096** least desirable):
216097**
216098**   idxNum     idxStr        Strategy
216099**   ------------------------------------------------
216100**     1        "rowid"       Direct lookup by rowid.
216101**     2        "rtree"       R-tree overlap query using geopoly_overlap()
216102**     3        "rtree"       R-tree within query using geopoly_within()
216103**     4        "fullscan"    full-table scan.
216104**   ------------------------------------------------
216105*/
216106static int geopolyBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
216107  int ii;
216108  int iRowidTerm = -1;
216109  int iFuncTerm = -1;
216110  int idxNum = 0;
216111  (void)tab;
216112
216113  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
216114    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
216115    if( !p->usable ) continue;
216116    if( p->iColumn<0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ  ){
216117      iRowidTerm = ii;
216118      break;
216119    }
216120    if( p->iColumn==0 && p->op>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
216121      /* p->op==SQLITE_INDEX_CONSTRAINT_FUNCTION for geopoly_overlap()
216122      ** p->op==(SQLITE_INDEX_CONTRAINT_FUNCTION+1) for geopoly_within().
216123      ** See geopolyFindFunction() */
216124      iFuncTerm = ii;
216125      idxNum = p->op - SQLITE_INDEX_CONSTRAINT_FUNCTION + 2;
216126    }
216127  }
216128
216129  if( iRowidTerm>=0 ){
216130    pIdxInfo->idxNum = 1;
216131    pIdxInfo->idxStr = "rowid";
216132    pIdxInfo->aConstraintUsage[iRowidTerm].argvIndex = 1;
216133    pIdxInfo->aConstraintUsage[iRowidTerm].omit = 1;
216134    pIdxInfo->estimatedCost = 30.0;
216135    pIdxInfo->estimatedRows = 1;
216136    pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
216137    return SQLITE_OK;
216138  }
216139  if( iFuncTerm>=0 ){
216140    pIdxInfo->idxNum = idxNum;
216141    pIdxInfo->idxStr = "rtree";
216142    pIdxInfo->aConstraintUsage[iFuncTerm].argvIndex = 1;
216143    pIdxInfo->aConstraintUsage[iFuncTerm].omit = 0;
216144    pIdxInfo->estimatedCost = 300.0;
216145    pIdxInfo->estimatedRows = 10;
216146    return SQLITE_OK;
216147  }
216148  pIdxInfo->idxNum = 4;
216149  pIdxInfo->idxStr = "fullscan";
216150  pIdxInfo->estimatedCost = 3000000.0;
216151  pIdxInfo->estimatedRows = 100000;
216152  return SQLITE_OK;
216153}
216154
216155
216156/*
216157** GEOPOLY virtual table module xColumn method.
216158*/
216159static int geopolyColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
216160  Rtree *pRtree = (Rtree *)cur->pVtab;
216161  RtreeCursor *pCsr = (RtreeCursor *)cur;
216162  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
216163  int rc = SQLITE_OK;
216164  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
216165
216166  if( rc ) return rc;
216167  if( p==0 ) return SQLITE_OK;
216168  if( i==0 && sqlite3_vtab_nochange(ctx) ) return SQLITE_OK;
216169  if( i<=pRtree->nAux ){
216170    if( !pCsr->bAuxValid ){
216171      if( pCsr->pReadAux==0 ){
216172        rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
216173                                &pCsr->pReadAux, 0);
216174        if( rc ) return rc;
216175      }
216176      sqlite3_bind_int64(pCsr->pReadAux, 1,
216177          nodeGetRowid(pRtree, pNode, p->iCell));
216178      rc = sqlite3_step(pCsr->pReadAux);
216179      if( rc==SQLITE_ROW ){
216180        pCsr->bAuxValid = 1;
216181      }else{
216182        sqlite3_reset(pCsr->pReadAux);
216183        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
216184        return rc;
216185      }
216186    }
216187    sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pReadAux, i+2));
216188  }
216189  return SQLITE_OK;
216190}
216191
216192
216193/*
216194** The xUpdate method for GEOPOLY module virtual tables.
216195**
216196** For DELETE:
216197**
216198**     argv[0] = the rowid to be deleted
216199**
216200** For INSERT:
216201**
216202**     argv[0] = SQL NULL
216203**     argv[1] = rowid to insert, or an SQL NULL to select automatically
216204**     argv[2] = _shape column
216205**     argv[3] = first application-defined column....
216206**
216207** For UPDATE:
216208**
216209**     argv[0] = rowid to modify.  Never NULL
216210**     argv[1] = rowid after the change.  Never NULL
216211**     argv[2] = new value for _shape
216212**     argv[3] = new value for first application-defined column....
216213*/
216214static int geopolyUpdate(
216215  sqlite3_vtab *pVtab,
216216  int nData,
216217  sqlite3_value **aData,
216218  sqlite_int64 *pRowid
216219){
216220  Rtree *pRtree = (Rtree *)pVtab;
216221  int rc = SQLITE_OK;
216222  RtreeCell cell;                 /* New cell to insert if nData>1 */
216223  i64 oldRowid;                   /* The old rowid */
216224  int oldRowidValid;              /* True if oldRowid is valid */
216225  i64 newRowid;                   /* The new rowid */
216226  int newRowidValid;              /* True if newRowid is valid */
216227  int coordChange = 0;            /* Change in coordinates */
216228
216229  if( pRtree->nNodeRef ){
216230    /* Unable to write to the btree while another cursor is reading from it,
216231    ** since the write might do a rebalance which would disrupt the read
216232    ** cursor. */
216233    return SQLITE_LOCKED_VTAB;
216234  }
216235  rtreeReference(pRtree);
216236  assert(nData>=1);
216237
216238  oldRowidValid = sqlite3_value_type(aData[0])!=SQLITE_NULL;;
216239  oldRowid = oldRowidValid ? sqlite3_value_int64(aData[0]) : 0;
216240  newRowidValid = nData>1 && sqlite3_value_type(aData[1])!=SQLITE_NULL;
216241  newRowid = newRowidValid ? sqlite3_value_int64(aData[1]) : 0;
216242  cell.iRowid = newRowid;
216243
216244  if( nData>1                                 /* not a DELETE */
216245   && (!oldRowidValid                         /* INSERT */
216246        || !sqlite3_value_nochange(aData[2])  /* UPDATE _shape */
216247        || oldRowid!=newRowid)                /* Rowid change */
216248  ){
216249    assert( aData[2]!=0 );
216250    geopolyBBox(0, aData[2], cell.aCoord, &rc);
216251    if( rc ){
216252      if( rc==SQLITE_ERROR ){
216253        pVtab->zErrMsg =
216254          sqlite3_mprintf("_shape does not contain a valid polygon");
216255      }
216256      goto geopoly_update_end;
216257    }
216258    coordChange = 1;
216259
216260    /* If a rowid value was supplied, check if it is already present in
216261    ** the table. If so, the constraint has failed. */
216262    if( newRowidValid && (!oldRowidValid || oldRowid!=newRowid) ){
216263      int steprc;
216264      sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
216265      steprc = sqlite3_step(pRtree->pReadRowid);
216266      rc = sqlite3_reset(pRtree->pReadRowid);
216267      if( SQLITE_ROW==steprc ){
216268        if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
216269          rc = rtreeDeleteRowid(pRtree, cell.iRowid);
216270        }else{
216271          rc = rtreeConstraintError(pRtree, 0);
216272        }
216273      }
216274    }
216275  }
216276
216277  /* If aData[0] is not an SQL NULL value, it is the rowid of a
216278  ** record to delete from the r-tree table. The following block does
216279  ** just that.
216280  */
216281  if( rc==SQLITE_OK && (nData==1 || (coordChange && oldRowidValid)) ){
216282    rc = rtreeDeleteRowid(pRtree, oldRowid);
216283  }
216284
216285  /* If the aData[] array contains more than one element, elements
216286  ** (aData[2]..aData[argc-1]) contain a new record to insert into
216287  ** the r-tree structure.
216288  */
216289  if( rc==SQLITE_OK && nData>1 && coordChange ){
216290    /* Insert the new record into the r-tree */
216291    RtreeNode *pLeaf = 0;
216292    if( !newRowidValid ){
216293      rc = rtreeNewRowid(pRtree, &cell.iRowid);
216294    }
216295    *pRowid = cell.iRowid;
216296    if( rc==SQLITE_OK ){
216297      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
216298    }
216299    if( rc==SQLITE_OK ){
216300      int rc2;
216301      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
216302      rc2 = nodeRelease(pRtree, pLeaf);
216303      if( rc==SQLITE_OK ){
216304        rc = rc2;
216305      }
216306    }
216307  }
216308
216309  /* Change the data */
216310  if( rc==SQLITE_OK && nData>1 ){
216311    sqlite3_stmt *pUp = pRtree->pWriteAux;
216312    int jj;
216313    int nChange = 0;
216314    sqlite3_bind_int64(pUp, 1, cell.iRowid);
216315    assert( pRtree->nAux>=1 );
216316    if( sqlite3_value_nochange(aData[2]) ){
216317      sqlite3_bind_null(pUp, 2);
216318    }else{
216319      GeoPoly *p = 0;
216320      if( sqlite3_value_type(aData[2])==SQLITE_TEXT
216321       && (p = geopolyFuncParam(0, aData[2], &rc))!=0
216322       && rc==SQLITE_OK
216323      ){
216324        sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex, SQLITE_TRANSIENT);
216325      }else{
216326        sqlite3_bind_value(pUp, 2, aData[2]);
216327      }
216328      sqlite3_free(p);
216329      nChange = 1;
216330    }
216331    for(jj=1; jj<nData-2; jj++){
216332      nChange++;
216333      sqlite3_bind_value(pUp, jj+2, aData[jj+2]);
216334    }
216335    if( nChange ){
216336      sqlite3_step(pUp);
216337      rc = sqlite3_reset(pUp);
216338    }
216339  }
216340
216341geopoly_update_end:
216342  rtreeRelease(pRtree);
216343  return rc;
216344}
216345
216346/*
216347** Report that geopoly_overlap() is an overloaded function suitable
216348** for use in xBestIndex.
216349*/
216350static int geopolyFindFunction(
216351  sqlite3_vtab *pVtab,
216352  int nArg,
216353  const char *zName,
216354  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
216355  void **ppArg
216356){
216357  (void)pVtab;
216358  (void)nArg;
216359  if( sqlite3_stricmp(zName, "geopoly_overlap")==0 ){
216360    *pxFunc = geopolyOverlapFunc;
216361    *ppArg = 0;
216362    return SQLITE_INDEX_CONSTRAINT_FUNCTION;
216363  }
216364  if( sqlite3_stricmp(zName, "geopoly_within")==0 ){
216365    *pxFunc = geopolyWithinFunc;
216366    *ppArg = 0;
216367    return SQLITE_INDEX_CONSTRAINT_FUNCTION+1;
216368  }
216369  return 0;
216370}
216371
216372
216373static sqlite3_module geopolyModule = {
216374  3,                          /* iVersion */
216375  geopolyCreate,              /* xCreate - create a table */
216376  geopolyConnect,             /* xConnect - connect to an existing table */
216377  geopolyBestIndex,           /* xBestIndex - Determine search strategy */
216378  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
216379  rtreeDestroy,               /* xDestroy - Drop a table */
216380  rtreeOpen,                  /* xOpen - open a cursor */
216381  rtreeClose,                 /* xClose - close a cursor */
216382  geopolyFilter,              /* xFilter - configure scan constraints */
216383  rtreeNext,                  /* xNext - advance a cursor */
216384  rtreeEof,                   /* xEof */
216385  geopolyColumn,              /* xColumn - read data */
216386  rtreeRowid,                 /* xRowid - read data */
216387  geopolyUpdate,              /* xUpdate - write data */
216388  rtreeBeginTransaction,      /* xBegin - begin transaction */
216389  rtreeEndTransaction,        /* xSync - sync transaction */
216390  rtreeEndTransaction,        /* xCommit - commit transaction */
216391  rtreeEndTransaction,        /* xRollback - rollback transaction */
216392  geopolyFindFunction,        /* xFindFunction - function overloading */
216393  rtreeRename,                /* xRename - rename the table */
216394  rtreeSavepoint,             /* xSavepoint */
216395  0,                          /* xRelease */
216396  0,                          /* xRollbackTo */
216397  rtreeShadowName,            /* xShadowName */
216398  rtreeIntegrity              /* xIntegrity */
216399};
216400
216401static int sqlite3_geopoly_init(sqlite3 *db){
216402  int rc = SQLITE_OK;
216403  static const struct {
216404    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
216405    signed char nArg;
216406    unsigned char bPure;
216407    const char *zName;
216408  } aFunc[] = {
216409     { geopolyAreaFunc,          1, 1,    "geopoly_area"             },
216410     { geopolyBlobFunc,          1, 1,    "geopoly_blob"             },
216411     { geopolyJsonFunc,          1, 1,    "geopoly_json"             },
216412     { geopolySvgFunc,          -1, 1,    "geopoly_svg"              },
216413     { geopolyWithinFunc,        2, 1,    "geopoly_within"           },
216414     { geopolyContainsPointFunc, 3, 1,    "geopoly_contains_point"   },
216415     { geopolyOverlapFunc,       2, 1,    "geopoly_overlap"          },
216416     { geopolyDebugFunc,         1, 0,    "geopoly_debug"            },
216417     { geopolyBBoxFunc,          1, 1,    "geopoly_bbox"             },
216418     { geopolyXformFunc,         7, 1,    "geopoly_xform"            },
216419     { geopolyRegularFunc,       4, 1,    "geopoly_regular"          },
216420     { geopolyCcwFunc,           1, 1,    "geopoly_ccw"              },
216421  };
216422  static const struct {
216423    void (*xStep)(sqlite3_context*,int,sqlite3_value**);
216424    void (*xFinal)(sqlite3_context*);
216425    const char *zName;
216426  } aAgg[] = {
216427     { geopolyBBoxStep, geopolyBBoxFinal, "geopoly_group_bbox"    },
216428  };
216429  unsigned int i;
216430  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
216431    int enc;
216432    if( aFunc[i].bPure ){
216433      enc = SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS;
216434    }else{
216435      enc = SQLITE_UTF8|SQLITE_DIRECTONLY;
216436    }
216437    rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
216438                                 enc, 0,
216439                                 aFunc[i].xFunc, 0, 0);
216440  }
216441  for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
216442    rc = sqlite3_create_function(db, aAgg[i].zName, 1,
216443              SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS, 0,
216444              0, aAgg[i].xStep, aAgg[i].xFinal);
216445  }
216446  if( rc==SQLITE_OK ){
216447    rc = sqlite3_create_module_v2(db, "geopoly", &geopolyModule, 0, 0);
216448  }
216449  return rc;
216450}
216451
216452/************** End of geopoly.c *********************************************/
216453/************** Continuing where we left off in rtree.c **********************/
216454#endif
216455
216456/*
216457** Register the r-tree module with database handle db. This creates the
216458** virtual table module "rtree" and the debugging/analysis scalar
216459** function "rtreenode".
216460*/
216461SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
216462  const int utf8 = SQLITE_UTF8;
216463  int rc;
216464
216465  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
216466  if( rc==SQLITE_OK ){
216467    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
216468  }
216469  if( rc==SQLITE_OK ){
216470    rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
216471  }
216472  if( rc==SQLITE_OK ){
216473#ifdef SQLITE_RTREE_INT_ONLY
216474    void *c = (void *)RTREE_COORD_INT32;
216475#else
216476    void *c = (void *)RTREE_COORD_REAL32;
216477#endif
216478    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
216479  }
216480  if( rc==SQLITE_OK ){
216481    void *c = (void *)RTREE_COORD_INT32;
216482    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
216483  }
216484#ifdef SQLITE_ENABLE_GEOPOLY
216485  if( rc==SQLITE_OK ){
216486    rc = sqlite3_geopoly_init(db);
216487  }
216488#endif
216489
216490  return rc;
216491}
216492
216493/*
216494** This routine deletes the RtreeGeomCallback object that was attached
216495** one of the SQL functions create by sqlite3_rtree_geometry_callback()
216496** or sqlite3_rtree_query_callback().  In other words, this routine is the
216497** destructor for an RtreeGeomCallback objecct.  This routine is called when
216498** the corresponding SQL function is deleted.
216499*/
216500static void rtreeFreeCallback(void *p){
216501  RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
216502  if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
216503  sqlite3_free(p);
216504}
216505
216506/*
216507** This routine frees the BLOB that is returned by geomCallback().
216508*/
216509static void rtreeMatchArgFree(void *pArg){
216510  int i;
216511  RtreeMatchArg *p = (RtreeMatchArg*)pArg;
216512  for(i=0; i<p->nParam; i++){
216513    sqlite3_value_free(p->apSqlParam[i]);
216514  }
216515  sqlite3_free(p);
216516}
216517
216518/*
216519** Each call to sqlite3_rtree_geometry_callback() or
216520** sqlite3_rtree_query_callback() creates an ordinary SQLite
216521** scalar function that is implemented by this routine.
216522**
216523** All this function does is construct an RtreeMatchArg object that
216524** contains the geometry-checking callback routines and a list of
216525** parameters to this function, then return that RtreeMatchArg object
216526** as a BLOB.
216527**
216528** The R-Tree MATCH operator will read the returned BLOB, deserialize
216529** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
216530** out which elements of the R-Tree should be returned by the query.
216531*/
216532static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
216533  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
216534  RtreeMatchArg *pBlob;
216535  sqlite3_int64 nBlob;
216536  int memErr = 0;
216537
216538  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
216539           + nArg*sizeof(sqlite3_value*);
216540  pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob);
216541  if( !pBlob ){
216542    sqlite3_result_error_nomem(ctx);
216543  }else{
216544    int i;
216545    pBlob->iSize = nBlob;
216546    pBlob->cb = pGeomCtx[0];
216547    pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
216548    pBlob->nParam = nArg;
216549    for(i=0; i<nArg; i++){
216550      pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
216551      if( pBlob->apSqlParam[i]==0 ) memErr = 1;
216552#ifdef SQLITE_RTREE_INT_ONLY
216553      pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
216554#else
216555      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
216556#endif
216557    }
216558    if( memErr ){
216559      sqlite3_result_error_nomem(ctx);
216560      rtreeMatchArgFree(pBlob);
216561    }else{
216562      sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
216563    }
216564  }
216565}
216566
216567/*
216568** Register a new geometry function for use with the r-tree MATCH operator.
216569*/
216570SQLITE_API int sqlite3_rtree_geometry_callback(
216571  sqlite3 *db,                  /* Register SQL function on this connection */
216572  const char *zGeom,            /* Name of the new SQL function */
216573  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
216574  void *pContext                /* Extra data associated with the callback */
216575){
216576  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
216577
216578  /* Allocate and populate the context object. */
216579  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
216580  if( !pGeomCtx ) return SQLITE_NOMEM;
216581  pGeomCtx->xGeom = xGeom;
216582  pGeomCtx->xQueryFunc = 0;
216583  pGeomCtx->xDestructor = 0;
216584  pGeomCtx->pContext = pContext;
216585  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
216586      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
216587  );
216588}
216589
216590/*
216591** Register a new 2nd-generation geometry function for use with the
216592** r-tree MATCH operator.
216593*/
216594SQLITE_API int sqlite3_rtree_query_callback(
216595  sqlite3 *db,                 /* Register SQL function on this connection */
216596  const char *zQueryFunc,      /* Name of new SQL function */
216597  int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
216598  void *pContext,              /* Extra data passed into the callback */
216599  void (*xDestructor)(void*)   /* Destructor for the extra data */
216600){
216601  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
216602
216603  /* Allocate and populate the context object. */
216604  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
216605  if( !pGeomCtx ){
216606    if( xDestructor ) xDestructor(pContext);
216607    return SQLITE_NOMEM;
216608  }
216609  pGeomCtx->xGeom = 0;
216610  pGeomCtx->xQueryFunc = xQueryFunc;
216611  pGeomCtx->xDestructor = xDestructor;
216612  pGeomCtx->pContext = pContext;
216613  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
216614      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
216615  );
216616}
216617
216618#if !SQLITE_CORE
216619#ifdef _WIN32
216620__declspec(dllexport)
216621#endif
216622SQLITE_API int sqlite3_rtree_init(
216623  sqlite3 *db,
216624  char **pzErrMsg,
216625  const sqlite3_api_routines *pApi
216626){
216627  SQLITE_EXTENSION_INIT2(pApi)
216628  return sqlite3RtreeInit(db);
216629}
216630#endif
216631
216632#endif
216633
216634/************** End of rtree.c ***********************************************/
216635/************** Begin file icu.c *********************************************/
216636/*
216637** 2007 May 6
216638**
216639** The author disclaims copyright to this source code.  In place of
216640** a legal notice, here is a blessing:
216641**
216642**    May you do good and not evil.
216643**    May you find forgiveness for yourself and forgive others.
216644**    May you share freely, never taking more than you give.
216645**
216646*************************************************************************
216647** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
216648**
216649** This file implements an integration between the ICU library
216650** ("International Components for Unicode", an open-source library
216651** for handling unicode data) and SQLite. The integration uses
216652** ICU to provide the following to SQLite:
216653**
216654**   * An implementation of the SQL regexp() function (and hence REGEXP
216655**     operator) using the ICU uregex_XX() APIs.
216656**
216657**   * Implementations of the SQL scalar upper() and lower() functions
216658**     for case mapping.
216659**
216660**   * Integration of ICU and SQLite collation sequences.
216661**
216662**   * An implementation of the LIKE operator that uses ICU to
216663**     provide case-independent matching.
216664*/
216665
216666#if !defined(SQLITE_CORE)                  \
216667 || defined(SQLITE_ENABLE_ICU)             \
216668 || defined(SQLITE_ENABLE_ICU_COLLATIONS)
216669
216670/* Include ICU headers */
216671#include <unicode/utypes.h>
216672#include <unicode/uregex.h>
216673#include <unicode/ustring.h>
216674#include <unicode/ucol.h>
216675
216676/* #include <assert.h> */
216677
216678#ifndef SQLITE_CORE
216679/*   #include "sqlite3ext.h" */
216680  SQLITE_EXTENSION_INIT1
216681#else
216682/*   #include "sqlite3.h" */
216683#endif
216684
216685/*
216686** This function is called when an ICU function called from within
216687** the implementation of an SQL scalar function returns an error.
216688**
216689** The scalar function context passed as the first argument is
216690** loaded with an error message based on the following two args.
216691*/
216692static void icuFunctionError(
216693  sqlite3_context *pCtx,       /* SQLite scalar function context */
216694  const char *zName,           /* Name of ICU function that failed */
216695  UErrorCode e                 /* Error code returned by ICU function */
216696){
216697  char zBuf[128];
216698  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
216699  zBuf[127] = '\0';
216700  sqlite3_result_error(pCtx, zBuf, -1);
216701}
216702
216703#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
216704
216705/*
216706** Maximum length (in bytes) of the pattern in a LIKE or GLOB
216707** operator.
216708*/
216709#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
216710# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
216711#endif
216712
216713/*
216714** Version of sqlite3_free() that is always a function, never a macro.
216715*/
216716static void xFree(void *p){
216717  sqlite3_free(p);
216718}
216719
216720/*
216721** This lookup table is used to help decode the first byte of
216722** a multi-byte UTF8 character. It is copied here from SQLite source
216723** code file utf8.c.
216724*/
216725static const unsigned char icuUtf8Trans1[] = {
216726  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
216727  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
216728  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
216729  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
216730  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
216731  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
216732  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
216733  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
216734};
216735
216736#define SQLITE_ICU_READ_UTF8(zIn, c)                       \
216737  c = *(zIn++);                                            \
216738  if( c>=0xc0 ){                                           \
216739    c = icuUtf8Trans1[c-0xc0];                             \
216740    while( (*zIn & 0xc0)==0x80 ){                          \
216741      c = (c<<6) + (0x3f & *(zIn++));                      \
216742    }                                                      \
216743  }
216744
216745#define SQLITE_ICU_SKIP_UTF8(zIn)                          \
216746  assert( *zIn );                                          \
216747  if( *(zIn++)>=0xc0 ){                                    \
216748    while( (*zIn & 0xc0)==0x80 ){zIn++;}                   \
216749  }
216750
216751
216752/*
216753** Compare two UTF-8 strings for equality where the first string is
216754** a "LIKE" expression. Return true (1) if they are the same and
216755** false (0) if they are different.
216756*/
216757static int icuLikeCompare(
216758  const uint8_t *zPattern,   /* LIKE pattern */
216759  const uint8_t *zString,    /* The UTF-8 string to compare against */
216760  const UChar32 uEsc         /* The escape character */
216761){
216762  static const uint32_t MATCH_ONE = (uint32_t)'_';
216763  static const uint32_t MATCH_ALL = (uint32_t)'%';
216764
216765  int prevEscape = 0;     /* True if the previous character was uEsc */
216766
216767  while( 1 ){
216768
216769    /* Read (and consume) the next character from the input pattern. */
216770    uint32_t uPattern;
216771    SQLITE_ICU_READ_UTF8(zPattern, uPattern);
216772    if( uPattern==0 ) break;
216773
216774    /* There are now 4 possibilities:
216775    **
216776    **     1. uPattern is an unescaped match-all character "%",
216777    **     2. uPattern is an unescaped match-one character "_",
216778    **     3. uPattern is an unescaped escape character, or
216779    **     4. uPattern is to be handled as an ordinary character
216780    */
216781    if( uPattern==MATCH_ALL && !prevEscape && uPattern!=(uint32_t)uEsc ){
216782      /* Case 1. */
216783      uint8_t c;
216784
216785      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
216786      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
216787      ** test string.
216788      */
216789      while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
216790        if( c==MATCH_ONE ){
216791          if( *zString==0 ) return 0;
216792          SQLITE_ICU_SKIP_UTF8(zString);
216793        }
216794        zPattern++;
216795      }
216796
216797      if( *zPattern==0 ) return 1;
216798
216799      while( *zString ){
216800        if( icuLikeCompare(zPattern, zString, uEsc) ){
216801          return 1;
216802        }
216803        SQLITE_ICU_SKIP_UTF8(zString);
216804      }
216805      return 0;
216806
216807    }else if( uPattern==MATCH_ONE && !prevEscape && uPattern!=(uint32_t)uEsc ){
216808      /* Case 2. */
216809      if( *zString==0 ) return 0;
216810      SQLITE_ICU_SKIP_UTF8(zString);
216811
216812    }else if( uPattern==(uint32_t)uEsc && !prevEscape ){
216813      /* Case 3. */
216814      prevEscape = 1;
216815
216816    }else{
216817      /* Case 4. */
216818      uint32_t uString;
216819      SQLITE_ICU_READ_UTF8(zString, uString);
216820      uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
216821      uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
216822      if( uString!=uPattern ){
216823        return 0;
216824      }
216825      prevEscape = 0;
216826    }
216827  }
216828
216829  return *zString==0;
216830}
216831
216832/*
216833** Implementation of the like() SQL function.  This function implements
216834** the build-in LIKE operator.  The first argument to the function is the
216835** pattern and the second argument is the string.  So, the SQL statements:
216836**
216837**       A LIKE B
216838**
216839** is implemented as like(B, A). If there is an escape character E,
216840**
216841**       A LIKE B ESCAPE E
216842**
216843** is mapped to like(B, A, E).
216844*/
216845static void icuLikeFunc(
216846  sqlite3_context *context,
216847  int argc,
216848  sqlite3_value **argv
216849){
216850  const unsigned char *zA = sqlite3_value_text(argv[0]);
216851  const unsigned char *zB = sqlite3_value_text(argv[1]);
216852  UChar32 uEsc = 0;
216853
216854  /* Limit the length of the LIKE or GLOB pattern to avoid problems
216855  ** of deep recursion and N*N behavior in patternCompare().
216856  */
216857  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
216858    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
216859    return;
216860  }
216861
216862
216863  if( argc==3 ){
216864    /* The escape character string must consist of a single UTF-8 character.
216865    ** Otherwise, return an error.
216866    */
216867    int nE= sqlite3_value_bytes(argv[2]);
216868    const unsigned char *zE = sqlite3_value_text(argv[2]);
216869    int i = 0;
216870    if( zE==0 ) return;
216871    U8_NEXT(zE, i, nE, uEsc);
216872    if( i!=nE){
216873      sqlite3_result_error(context,
216874          "ESCAPE expression must be a single character", -1);
216875      return;
216876    }
216877  }
216878
216879  if( zA && zB ){
216880    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
216881  }
216882}
216883
216884/*
216885** Function to delete compiled regexp objects. Registered as
216886** a destructor function with sqlite3_set_auxdata().
216887*/
216888static void icuRegexpDelete(void *p){
216889  URegularExpression *pExpr = (URegularExpression *)p;
216890  uregex_close(pExpr);
216891}
216892
216893/*
216894** Implementation of SQLite REGEXP operator. This scalar function takes
216895** two arguments. The first is a regular expression pattern to compile
216896** the second is a string to match against that pattern. If either
216897** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
216898** is 1 if the string matches the pattern, or 0 otherwise.
216899**
216900** SQLite maps the regexp() function to the regexp() operator such
216901** that the following two are equivalent:
216902**
216903**     zString REGEXP zPattern
216904**     regexp(zPattern, zString)
216905**
216906** Uses the following ICU regexp APIs:
216907**
216908**     uregex_open()
216909**     uregex_matches()
216910**     uregex_close()
216911*/
216912static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
216913  UErrorCode status = U_ZERO_ERROR;
216914  URegularExpression *pExpr;
216915  UBool res;
216916  const UChar *zString = sqlite3_value_text16(apArg[1]);
216917
216918  (void)nArg;  /* Unused parameter */
216919
216920  /* If the left hand side of the regexp operator is NULL,
216921  ** then the result is also NULL.
216922  */
216923  if( !zString ){
216924    return;
216925  }
216926
216927  pExpr = sqlite3_get_auxdata(p, 0);
216928  if( !pExpr ){
216929    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
216930    if( !zPattern ){
216931      return;
216932    }
216933    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
216934
216935    if( U_SUCCESS(status) ){
216936      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
216937      pExpr = sqlite3_get_auxdata(p, 0);
216938    }
216939    if( !pExpr ){
216940      icuFunctionError(p, "uregex_open", status);
216941      return;
216942    }
216943  }
216944
216945  /* Configure the text that the regular expression operates on. */
216946  uregex_setText(pExpr, zString, -1, &status);
216947  if( !U_SUCCESS(status) ){
216948    icuFunctionError(p, "uregex_setText", status);
216949    return;
216950  }
216951
216952  /* Attempt the match */
216953  res = uregex_matches(pExpr, 0, &status);
216954  if( !U_SUCCESS(status) ){
216955    icuFunctionError(p, "uregex_matches", status);
216956    return;
216957  }
216958
216959  /* Set the text that the regular expression operates on to a NULL
216960  ** pointer. This is not really necessary, but it is tidier than
216961  ** leaving the regular expression object configured with an invalid
216962  ** pointer after this function returns.
216963  */
216964  uregex_setText(pExpr, 0, 0, &status);
216965
216966  /* Return 1 or 0. */
216967  sqlite3_result_int(p, res ? 1 : 0);
216968}
216969
216970/*
216971** Implementations of scalar functions for case mapping - upper() and
216972** lower(). Function upper() converts its input to upper-case (ABC).
216973** Function lower() converts to lower-case (abc).
216974**
216975** ICU provides two types of case mapping, "general" case mapping and
216976** "language specific". Refer to ICU documentation for the differences
216977** between the two.
216978**
216979** To utilise "general" case mapping, the upper() or lower() scalar
216980** functions are invoked with one argument:
216981**
216982**     upper('ABC') -> 'abc'
216983**     lower('abc') -> 'ABC'
216984**
216985** To access ICU "language specific" case mapping, upper() or lower()
216986** should be invoked with two arguments. The second argument is the name
216987** of the locale to use. Passing an empty string ("") or SQL NULL value
216988** as the second argument is the same as invoking the 1 argument version
216989** of upper() or lower().
216990**
216991**     lower('I', 'en_us') -> 'i'
216992**     lower('I', 'tr_tr') -> '\u131' (small dotless i)
216993**
216994** http://www.icu-project.org/userguide/posix.html#case_mappings
216995*/
216996static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
216997  const UChar *zInput;            /* Pointer to input string */
216998  UChar *zOutput = 0;             /* Pointer to output buffer */
216999  int nInput;                     /* Size of utf-16 input string in bytes */
217000  int nOut;                       /* Size of output buffer in bytes */
217001  int cnt;
217002  int bToUpper;                   /* True for toupper(), false for tolower() */
217003  UErrorCode status;
217004  const char *zLocale = 0;
217005
217006  assert(nArg==1 || nArg==2);
217007  bToUpper = (sqlite3_user_data(p)!=0);
217008  if( nArg==2 ){
217009    zLocale = (const char *)sqlite3_value_text(apArg[1]);
217010  }
217011
217012  zInput = sqlite3_value_text16(apArg[0]);
217013  if( !zInput ){
217014    return;
217015  }
217016  nOut = nInput = sqlite3_value_bytes16(apArg[0]);
217017  if( nOut==0 ){
217018    sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
217019    return;
217020  }
217021
217022  for(cnt=0; cnt<2; cnt++){
217023    UChar *zNew = sqlite3_realloc(zOutput, nOut);
217024    if( zNew==0 ){
217025      sqlite3_free(zOutput);
217026      sqlite3_result_error_nomem(p);
217027      return;
217028    }
217029    zOutput = zNew;
217030    status = U_ZERO_ERROR;
217031    if( bToUpper ){
217032      nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
217033    }else{
217034      nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
217035    }
217036
217037    if( U_SUCCESS(status) ){
217038      sqlite3_result_text16(p, zOutput, nOut, xFree);
217039    }else if( status==U_BUFFER_OVERFLOW_ERROR ){
217040      assert( cnt==0 );
217041      continue;
217042    }else{
217043      icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
217044    }
217045    return;
217046  }
217047  assert( 0 );     /* Unreachable */
217048}
217049
217050#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
217051
217052/*
217053** Collation sequence destructor function. The pCtx argument points to
217054** a UCollator structure previously allocated using ucol_open().
217055*/
217056static void icuCollationDel(void *pCtx){
217057  UCollator *p = (UCollator *)pCtx;
217058  ucol_close(p);
217059}
217060
217061/*
217062** Collation sequence comparison function. The pCtx argument points to
217063** a UCollator structure previously allocated using ucol_open().
217064*/
217065static int icuCollationColl(
217066  void *pCtx,
217067  int nLeft,
217068  const void *zLeft,
217069  int nRight,
217070  const void *zRight
217071){
217072  UCollationResult res;
217073  UCollator *p = (UCollator *)pCtx;
217074  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
217075  switch( res ){
217076    case UCOL_LESS:    return -1;
217077    case UCOL_GREATER: return +1;
217078    case UCOL_EQUAL:   return 0;
217079  }
217080  assert(!"Unexpected return value from ucol_strcoll()");
217081  return 0;
217082}
217083
217084/*
217085** Implementation of the scalar function icu_load_collation().
217086**
217087** This scalar function is used to add ICU collation based collation
217088** types to an SQLite database connection. It is intended to be called
217089** as follows:
217090**
217091**     SELECT icu_load_collation(<locale>, <collation-name>);
217092**
217093** Where <locale> is a string containing an ICU locale identifier (i.e.
217094** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
217095** collation sequence to create.
217096*/
217097static void icuLoadCollation(
217098  sqlite3_context *p,
217099  int nArg,
217100  sqlite3_value **apArg
217101){
217102  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
217103  UErrorCode status = U_ZERO_ERROR;
217104  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
217105  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
217106  UCollator *pUCollator;    /* ICU library collation object */
217107  int rc;                   /* Return code from sqlite3_create_collation_x() */
217108
217109  assert(nArg==2 || nArg==3);
217110  (void)nArg; /* Unused parameter */
217111  zLocale = (const char *)sqlite3_value_text(apArg[0]);
217112  zName = (const char *)sqlite3_value_text(apArg[1]);
217113
217114  if( !zLocale || !zName ){
217115    return;
217116  }
217117
217118  pUCollator = ucol_open(zLocale, &status);
217119  if( !U_SUCCESS(status) ){
217120    icuFunctionError(p, "ucol_open", status);
217121    return;
217122  }
217123  assert(p);
217124  if(nArg==3){
217125    const char *zOption = (const char*)sqlite3_value_text(apArg[2]);
217126    static const struct {
217127       const char *zName;
217128       UColAttributeValue val;
217129    } aStrength[] = {
217130      {  "PRIMARY",      UCOL_PRIMARY           },
217131      {  "SECONDARY",    UCOL_SECONDARY         },
217132      {  "TERTIARY",     UCOL_TERTIARY          },
217133      {  "DEFAULT",      UCOL_DEFAULT_STRENGTH  },
217134      {  "QUARTERNARY",  UCOL_QUATERNARY        },
217135      {  "IDENTICAL",    UCOL_IDENTICAL         },
217136    };
217137    unsigned int i;
217138    for(i=0; i<sizeof(aStrength)/sizeof(aStrength[0]); i++){
217139      if( sqlite3_stricmp(zOption,aStrength[i].zName)==0 ){
217140        ucol_setStrength(pUCollator, aStrength[i].val);
217141        break;
217142      }
217143    }
217144    if( i>=sizeof(aStrength)/sizeof(aStrength[0]) ){
217145      sqlite3_str *pStr = sqlite3_str_new(sqlite3_context_db_handle(p));
217146      sqlite3_str_appendf(pStr,
217147         "unknown collation strength \"%s\" - should be one of:",
217148         zOption);
217149      for(i=0; i<sizeof(aStrength)/sizeof(aStrength[0]); i++){
217150         sqlite3_str_appendf(pStr, " %s", aStrength[i].zName);
217151      }
217152      sqlite3_result_error(p, sqlite3_str_value(pStr), -1);
217153      sqlite3_free(sqlite3_str_finish(pStr));
217154      return;
217155    }
217156  }
217157  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
217158      icuCollationColl, icuCollationDel
217159  );
217160  if( rc!=SQLITE_OK ){
217161    ucol_close(pUCollator);
217162    sqlite3_result_error(p, "Error registering collation function", -1);
217163  }
217164}
217165
217166/*
217167** Register the ICU extension functions with database db.
217168*/
217169SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
217170# define SQLITEICU_EXTRAFLAGS (SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS)
217171  static const struct IcuScalar {
217172    const char *zName;                        /* Function name */
217173    unsigned char nArg;                       /* Number of arguments */
217174    unsigned int enc;                         /* Optimal text encoding */
217175    unsigned char iContext;                   /* sqlite3_user_data() context */
217176    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
217177  } scalars[] = {
217178    {"icu_load_collation",2,SQLITE_UTF8|SQLITE_DIRECTONLY,1, icuLoadCollation},
217179    {"icu_load_collation",3,SQLITE_UTF8|SQLITE_DIRECTONLY,1, icuLoadCollation},
217180#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
217181    {"regexp", 2, SQLITE_ANY|SQLITEICU_EXTRAFLAGS,         0, icuRegexpFunc},
217182    {"lower",  1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS,       0, icuCaseFunc16},
217183    {"lower",  2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS,       0, icuCaseFunc16},
217184    {"upper",  1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS,       1, icuCaseFunc16},
217185    {"upper",  2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS,       1, icuCaseFunc16},
217186    {"lower",  1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        0, icuCaseFunc16},
217187    {"lower",  2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        0, icuCaseFunc16},
217188    {"upper",  1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        1, icuCaseFunc16},
217189    {"upper",  2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        1, icuCaseFunc16},
217190    {"like",   2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        0, icuLikeFunc},
217191    {"like",   3, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        0, icuLikeFunc},
217192#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
217193  };
217194  int rc = SQLITE_OK;
217195  int i;
217196
217197  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
217198    const struct IcuScalar *p = &scalars[i];
217199    rc = sqlite3_create_function(
217200        db, p->zName, p->nArg, p->enc,
217201        p->iContext ? (void*)db : (void*)0,
217202        p->xFunc, 0, 0
217203    );
217204  }
217205
217206  return rc;
217207}
217208
217209#if !SQLITE_CORE
217210#ifdef _WIN32
217211__declspec(dllexport)
217212#endif
217213SQLITE_API int sqlite3_icu_init(
217214  sqlite3 *db,
217215  char **pzErrMsg,
217216  const sqlite3_api_routines *pApi
217217){
217218  SQLITE_EXTENSION_INIT2(pApi)
217219  return sqlite3IcuInit(db);
217220}
217221#endif
217222
217223#endif
217224
217225/************** End of icu.c *************************************************/
217226/************** Begin file fts3_icu.c ****************************************/
217227/*
217228** 2007 June 22
217229**
217230** The author disclaims copyright to this source code.  In place of
217231** a legal notice, here is a blessing:
217232**
217233**    May you do good and not evil.
217234**    May you find forgiveness for yourself and forgive others.
217235**    May you share freely, never taking more than you give.
217236**
217237*************************************************************************
217238** This file implements a tokenizer for fts3 based on the ICU library.
217239*/
217240/* #include "fts3Int.h" */
217241#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
217242#ifdef SQLITE_ENABLE_ICU
217243
217244/* #include <assert.h> */
217245/* #include <string.h> */
217246/* #include "fts3_tokenizer.h" */
217247
217248#include <unicode/ubrk.h>
217249/* #include <unicode/ucol.h> */
217250/* #include <unicode/ustring.h> */
217251#include <unicode/utf16.h>
217252
217253typedef struct IcuTokenizer IcuTokenizer;
217254typedef struct IcuCursor IcuCursor;
217255
217256struct IcuTokenizer {
217257  sqlite3_tokenizer base;
217258  char *zLocale;
217259};
217260
217261struct IcuCursor {
217262  sqlite3_tokenizer_cursor base;
217263
217264  UBreakIterator *pIter;      /* ICU break-iterator object */
217265  int nChar;                  /* Number of UChar elements in pInput */
217266  UChar *aChar;               /* Copy of input using utf-16 encoding */
217267  int *aOffset;               /* Offsets of each character in utf-8 input */
217268
217269  int nBuffer;
217270  char *zBuffer;
217271
217272  int iToken;
217273};
217274
217275/*
217276** Create a new tokenizer instance.
217277*/
217278static int icuCreate(
217279  int argc,                            /* Number of entries in argv[] */
217280  const char * const *argv,            /* Tokenizer creation arguments */
217281  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
217282){
217283  IcuTokenizer *p;
217284  int n = 0;
217285
217286  if( argc>0 ){
217287    n = strlen(argv[0])+1;
217288  }
217289  p = (IcuTokenizer *)sqlite3_malloc64(sizeof(IcuTokenizer)+n);
217290  if( !p ){
217291    return SQLITE_NOMEM;
217292  }
217293  memset(p, 0, sizeof(IcuTokenizer));
217294
217295  if( n ){
217296    p->zLocale = (char *)&p[1];
217297    memcpy(p->zLocale, argv[0], n);
217298  }
217299
217300  *ppTokenizer = (sqlite3_tokenizer *)p;
217301
217302  return SQLITE_OK;
217303}
217304
217305/*
217306** Destroy a tokenizer
217307*/
217308static int icuDestroy(sqlite3_tokenizer *pTokenizer){
217309  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
217310  sqlite3_free(p);
217311  return SQLITE_OK;
217312}
217313
217314/*
217315** Prepare to begin tokenizing a particular string.  The input
217316** string to be tokenized is pInput[0..nBytes-1].  A cursor
217317** used to incrementally tokenize this string is returned in
217318** *ppCursor.
217319*/
217320static int icuOpen(
217321  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
217322  const char *zInput,                    /* Input string */
217323  int nInput,                            /* Length of zInput in bytes */
217324  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
217325){
217326  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
217327  IcuCursor *pCsr;
217328
217329  const int32_t opt = U_FOLD_CASE_DEFAULT;
217330  UErrorCode status = U_ZERO_ERROR;
217331  int nChar;
217332
217333  UChar32 c;
217334  int iInput = 0;
217335  int iOut = 0;
217336
217337  *ppCursor = 0;
217338
217339  if( zInput==0 ){
217340    nInput = 0;
217341    zInput = "";
217342  }else if( nInput<0 ){
217343    nInput = strlen(zInput);
217344  }
217345  nChar = nInput+1;
217346  pCsr = (IcuCursor *)sqlite3_malloc64(
217347      sizeof(IcuCursor) +                /* IcuCursor */
217348      ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
217349      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
217350  );
217351  if( !pCsr ){
217352    return SQLITE_NOMEM;
217353  }
217354  memset(pCsr, 0, sizeof(IcuCursor));
217355  pCsr->aChar = (UChar *)&pCsr[1];
217356  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
217357
217358  pCsr->aOffset[iOut] = iInput;
217359  U8_NEXT(zInput, iInput, nInput, c);
217360  while( c>0 ){
217361    int isError = 0;
217362    c = u_foldCase(c, opt);
217363    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
217364    if( isError ){
217365      sqlite3_free(pCsr);
217366      return SQLITE_ERROR;
217367    }
217368    pCsr->aOffset[iOut] = iInput;
217369
217370    if( iInput<nInput ){
217371      U8_NEXT(zInput, iInput, nInput, c);
217372    }else{
217373      c = 0;
217374    }
217375  }
217376
217377  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
217378  if( !U_SUCCESS(status) ){
217379    sqlite3_free(pCsr);
217380    return SQLITE_ERROR;
217381  }
217382  pCsr->nChar = iOut;
217383
217384  ubrk_first(pCsr->pIter);
217385  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
217386  return SQLITE_OK;
217387}
217388
217389/*
217390** Close a tokenization cursor previously opened by a call to icuOpen().
217391*/
217392static int icuClose(sqlite3_tokenizer_cursor *pCursor){
217393  IcuCursor *pCsr = (IcuCursor *)pCursor;
217394  ubrk_close(pCsr->pIter);
217395  sqlite3_free(pCsr->zBuffer);
217396  sqlite3_free(pCsr);
217397  return SQLITE_OK;
217398}
217399
217400/*
217401** Extract the next token from a tokenization cursor.
217402*/
217403static int icuNext(
217404  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
217405  const char **ppToken,               /* OUT: *ppToken is the token text */
217406  int *pnBytes,                       /* OUT: Number of bytes in token */
217407  int *piStartOffset,                 /* OUT: Starting offset of token */
217408  int *piEndOffset,                   /* OUT: Ending offset of token */
217409  int *piPosition                     /* OUT: Position integer of token */
217410){
217411  IcuCursor *pCsr = (IcuCursor *)pCursor;
217412
217413  int iStart = 0;
217414  int iEnd = 0;
217415  int nByte = 0;
217416
217417  while( iStart==iEnd ){
217418    UChar32 c;
217419
217420    iStart = ubrk_current(pCsr->pIter);
217421    iEnd = ubrk_next(pCsr->pIter);
217422    if( iEnd==UBRK_DONE ){
217423      return SQLITE_DONE;
217424    }
217425
217426    while( iStart<iEnd ){
217427      int iWhite = iStart;
217428      U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
217429      if( u_isspace(c) ){
217430        iStart = iWhite;
217431      }else{
217432        break;
217433      }
217434    }
217435    assert(iStart<=iEnd);
217436  }
217437
217438  do {
217439    UErrorCode status = U_ZERO_ERROR;
217440    if( nByte ){
217441      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
217442      if( !zNew ){
217443        return SQLITE_NOMEM;
217444      }
217445      pCsr->zBuffer = zNew;
217446      pCsr->nBuffer = nByte;
217447    }
217448
217449    u_strToUTF8(
217450        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
217451        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
217452        &status                                  /* Output success/failure */
217453    );
217454  } while( nByte>pCsr->nBuffer );
217455
217456  *ppToken = pCsr->zBuffer;
217457  *pnBytes = nByte;
217458  *piStartOffset = pCsr->aOffset[iStart];
217459  *piEndOffset = pCsr->aOffset[iEnd];
217460  *piPosition = pCsr->iToken++;
217461
217462  return SQLITE_OK;
217463}
217464
217465/*
217466** The set of routines that implement the simple tokenizer
217467*/
217468static const sqlite3_tokenizer_module icuTokenizerModule = {
217469  0,                           /* iVersion    */
217470  icuCreate,                   /* xCreate     */
217471  icuDestroy,                  /* xCreate     */
217472  icuOpen,                     /* xOpen       */
217473  icuClose,                    /* xClose      */
217474  icuNext,                     /* xNext       */
217475  0,                           /* xLanguageid */
217476};
217477
217478/*
217479** Set *ppModule to point at the implementation of the ICU tokenizer.
217480*/
217481SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
217482  sqlite3_tokenizer_module const**ppModule
217483){
217484  *ppModule = &icuTokenizerModule;
217485}
217486
217487#endif /* defined(SQLITE_ENABLE_ICU) */
217488#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
217489
217490/************** End of fts3_icu.c ********************************************/
217491/************** Begin file sqlite3rbu.c **************************************/
217492/*
217493** 2014 August 30
217494**
217495** The author disclaims copyright to this source code.  In place of
217496** a legal notice, here is a blessing:
217497**
217498**    May you do good and not evil.
217499**    May you find forgiveness for yourself and forgive others.
217500**    May you share freely, never taking more than you give.
217501**
217502*************************************************************************
217503**
217504**
217505** OVERVIEW
217506**
217507**  The RBU extension requires that the RBU update be packaged as an
217508**  SQLite database. The tables it expects to find are described in
217509**  sqlite3rbu.h.  Essentially, for each table xyz in the target database
217510**  that the user wishes to write to, a corresponding data_xyz table is
217511**  created in the RBU database and populated with one row for each row to
217512**  update, insert or delete from the target table.
217513**
217514**  The update proceeds in three stages:
217515**
217516**  1) The database is updated. The modified database pages are written
217517**     to a *-oal file. A *-oal file is just like a *-wal file, except
217518**     that it is named "<database>-oal" instead of "<database>-wal".
217519**     Because regular SQLite clients do not look for file named
217520**     "<database>-oal", they go on using the original database in
217521**     rollback mode while the *-oal file is being generated.
217522**
217523**     During this stage RBU does not update the database by writing
217524**     directly to the target tables. Instead it creates "imposter"
217525**     tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
217526**     to update each b-tree individually. All updates required by each
217527**     b-tree are completed before moving on to the next, and all
217528**     updates are done in sorted key order.
217529**
217530**  2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
217531**     location using a call to rename(2). Before doing this the RBU
217532**     module takes an EXCLUSIVE lock on the database file, ensuring
217533**     that there are no other active readers.
217534**
217535**     Once the EXCLUSIVE lock is released, any other database readers
217536**     detect the new *-wal file and read the database in wal mode. At
217537**     this point they see the new version of the database - including
217538**     the updates made as part of the RBU update.
217539**
217540**  3) The new *-wal file is checkpointed. This proceeds in the same way
217541**     as a regular database checkpoint, except that a single frame is
217542**     checkpointed each time sqlite3rbu_step() is called. If the RBU
217543**     handle is closed before the entire *-wal file is checkpointed,
217544**     the checkpoint progress is saved in the RBU database and the
217545**     checkpoint can be resumed by another RBU client at some point in
217546**     the future.
217547**
217548** POTENTIAL PROBLEMS
217549**
217550**  The rename() call might not be portable. And RBU is not currently
217551**  syncing the directory after renaming the file.
217552**
217553**  When state is saved, any commit to the *-oal file and the commit to
217554**  the RBU update database are not atomic. So if the power fails at the
217555**  wrong moment they might get out of sync. As the main database will be
217556**  committed before the RBU update database this will likely either just
217557**  pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
217558**  constraint violations).
217559**
217560**  If some client does modify the target database mid RBU update, or some
217561**  other error occurs, the RBU extension will keep throwing errors. It's
217562**  not really clear how to get out of this state. The system could just
217563**  by delete the RBU update database and *-oal file and have the device
217564**  download the update again and start over.
217565**
217566**  At present, for an UPDATE, both the new.* and old.* records are
217567**  collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
217568**  fields are collected.  This means we're probably writing a lot more
217569**  data to disk when saving the state of an ongoing update to the RBU
217570**  update database than is strictly necessary.
217571**
217572*/
217573
217574/* #include <assert.h> */
217575/* #include <string.h> */
217576/* #include <stdio.h> */
217577
217578/* #include "sqlite3.h" */
217579
217580#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
217581/************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
217582/************** Begin file sqlite3rbu.h **************************************/
217583/*
217584** 2014 August 30
217585**
217586** The author disclaims copyright to this source code.  In place of
217587** a legal notice, here is a blessing:
217588**
217589**    May you do good and not evil.
217590**    May you find forgiveness for yourself and forgive others.
217591**    May you share freely, never taking more than you give.
217592**
217593*************************************************************************
217594**
217595** This file contains the public interface for the RBU extension.
217596*/
217597
217598/*
217599** SUMMARY
217600**
217601** Writing a transaction containing a large number of operations on
217602** b-tree indexes that are collectively larger than the available cache
217603** memory can be very inefficient.
217604**
217605** The problem is that in order to update a b-tree, the leaf page (at least)
217606** containing the entry being inserted or deleted must be modified. If the
217607** working set of leaves is larger than the available cache memory, then a
217608** single leaf that is modified more than once as part of the transaction
217609** may be loaded from or written to the persistent media multiple times.
217610** Additionally, because the index updates are likely to be applied in
217611** random order, access to pages within the database is also likely to be in
217612** random order, which is itself quite inefficient.
217613**
217614** One way to improve the situation is to sort the operations on each index
217615** by index key before applying them to the b-tree. This leads to an IO
217616** pattern that resembles a single linear scan through the index b-tree,
217617** and all but guarantees each modified leaf page is loaded and stored
217618** exactly once. SQLite uses this trick to improve the performance of
217619** CREATE INDEX commands. This extension allows it to be used to improve
217620** the performance of large transactions on existing databases.
217621**
217622** Additionally, this extension allows the work involved in writing the
217623** large transaction to be broken down into sub-transactions performed
217624** sequentially by separate processes. This is useful if the system cannot
217625** guarantee that a single update process will run for long enough to apply
217626** the entire update, for example because the update is being applied on a
217627** mobile device that is frequently rebooted. Even after the writer process
217628** has committed one or more sub-transactions, other database clients continue
217629** to read from the original database snapshot. In other words, partially
217630** applied transactions are not visible to other clients.
217631**
217632** "RBU" stands for "Resumable Bulk Update". As in a large database update
217633** transmitted via a wireless network to a mobile device. A transaction
217634** applied using this extension is hence refered to as an "RBU update".
217635**
217636**
217637** LIMITATIONS
217638**
217639** An "RBU update" transaction is subject to the following limitations:
217640**
217641**   * The transaction must consist of INSERT, UPDATE and DELETE operations
217642**     only.
217643**
217644**   * INSERT statements may not use any default values.
217645**
217646**   * UPDATE and DELETE statements must identify their target rows by
217647**     non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
217648**     KEY fields may not be updated or deleted. If the table being written
217649**     has no PRIMARY KEY, affected rows must be identified by rowid.
217650**
217651**   * UPDATE statements may not modify PRIMARY KEY columns.
217652**
217653**   * No triggers will be fired.
217654**
217655**   * No foreign key violations are detected or reported.
217656**
217657**   * CHECK constraints are not enforced.
217658**
217659**   * No constraint handling mode except for "OR ROLLBACK" is supported.
217660**
217661**
217662** PREPARATION
217663**
217664** An "RBU update" is stored as a separate SQLite database. A database
217665** containing an RBU update is an "RBU database". For each table in the
217666** target database to be updated, the RBU database should contain a table
217667** named "data_<target name>" containing the same set of columns as the
217668** target table, and one more - "rbu_control". The data_% table should
217669** have no PRIMARY KEY or UNIQUE constraints, but each column should have
217670** the same type as the corresponding column in the target database.
217671** The "rbu_control" column should have no type at all. For example, if
217672** the target database contains:
217673**
217674**   CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
217675**
217676** Then the RBU database should contain:
217677**
217678**   CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
217679**
217680** The order of the columns in the data_% table does not matter.
217681**
217682** Instead of a regular table, the RBU database may also contain virtual
217683** tables or views named using the data_<target> naming scheme.
217684**
217685** Instead of the plain data_<target> naming scheme, RBU database tables
217686** may also be named data<integer>_<target>, where <integer> is any sequence
217687** of zero or more numeric characters (0-9). This can be significant because
217688** tables within the RBU database are always processed in order sorted by
217689** name. By judicious selection of the <integer> portion of the names
217690** of the RBU tables the user can therefore control the order in which they
217691** are processed. This can be useful, for example, to ensure that "external
217692** content" FTS4 tables are updated before their underlying content tables.
217693**
217694** If the target database table is a virtual table or a table that has no
217695** PRIMARY KEY declaration, the data_% table must also contain a column
217696** named "rbu_rowid". This column is mapped to the table's implicit primary
217697** key column - "rowid". Virtual tables for which the "rowid" column does
217698** not function like a primary key value cannot be updated using RBU. For
217699** example, if the target db contains either of the following:
217700**
217701**   CREATE VIRTUAL TABLE x1 USING fts3(a, b);
217702**   CREATE TABLE x1(a, b)
217703**
217704** then the RBU database should contain:
217705**
217706**   CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
217707**
217708** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
217709** target table must be present in the input table. For virtual tables,
217710** hidden columns are optional - they are updated by RBU if present in
217711** the input table, or not otherwise. For example, to write to an fts4
217712** table with a hidden languageid column such as:
217713**
217714**   CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
217715**
217716** Either of the following input table schemas may be used:
217717**
217718**   CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
217719**   CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
217720**
217721** For each row to INSERT into the target database as part of the RBU
217722** update, the corresponding data_% table should contain a single record
217723** with the "rbu_control" column set to contain integer value 0. The
217724** other columns should be set to the values that make up the new record
217725** to insert.
217726**
217727** If the target database table has an INTEGER PRIMARY KEY, it is not
217728** possible to insert a NULL value into the IPK column. Attempting to
217729** do so results in an SQLITE_MISMATCH error.
217730**
217731** For each row to DELETE from the target database as part of the RBU
217732** update, the corresponding data_% table should contain a single record
217733** with the "rbu_control" column set to contain integer value 1. The
217734** real primary key values of the row to delete should be stored in the
217735** corresponding columns of the data_% table. The values stored in the
217736** other columns are not used.
217737**
217738** For each row to UPDATE from the target database as part of the RBU
217739** update, the corresponding data_% table should contain a single record
217740** with the "rbu_control" column set to contain a value of type text.
217741** The real primary key values identifying the row to update should be
217742** stored in the corresponding columns of the data_% table row, as should
217743** the new values of all columns being update. The text value in the
217744** "rbu_control" column must contain the same number of characters as
217745** there are columns in the target database table, and must consist entirely
217746** of 'x' and '.' characters (or in some special cases 'd' - see below). For
217747** each column that is being updated, the corresponding character is set to
217748** 'x'. For those that remain as they are, the corresponding character of the
217749** rbu_control value should be set to '.'. For example, given the tables
217750** above, the update statement:
217751**
217752**   UPDATE t1 SET c = 'usa' WHERE a = 4;
217753**
217754** is represented by the data_t1 row created by:
217755**
217756**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
217757**
217758** Instead of an 'x' character, characters of the rbu_control value specified
217759** for UPDATEs may also be set to 'd'. In this case, instead of updating the
217760** target table with the value stored in the corresponding data_% column, the
217761** user-defined SQL function "rbu_delta()" is invoked and the result stored in
217762** the target table column. rbu_delta() is invoked with two arguments - the
217763** original value currently stored in the target table column and the
217764** value specified in the data_xxx table.
217765**
217766** For example, this row:
217767**
217768**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
217769**
217770** is similar to an UPDATE statement such as:
217771**
217772**   UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
217773**
217774** Finally, if an 'f' character appears in place of a 'd' or 's' in an
217775** ota_control string, the contents of the data_xxx table column is assumed
217776** to be a "fossil delta" - a patch to be applied to a blob value in the
217777** format used by the fossil source-code management system. In this case
217778** the existing value within the target database table must be of type BLOB.
217779** It is replaced by the result of applying the specified fossil delta to
217780** itself.
217781**
217782** If the target database table is a virtual table or a table with no PRIMARY
217783** KEY, the rbu_control value should not include a character corresponding
217784** to the rbu_rowid value. For example, this:
217785**
217786**   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
217787**       VALUES(NULL, 'usa', 12, '.x');
217788**
217789** causes a result similar to:
217790**
217791**   UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
217792**
217793** The data_xxx tables themselves should have no PRIMARY KEY declarations.
217794** However, RBU is more efficient if reading the rows in from each data_xxx
217795** table in "rowid" order is roughly the same as reading them sorted by
217796** the PRIMARY KEY of the corresponding target database table. In other
217797** words, rows should be sorted using the destination table PRIMARY KEY
217798** fields before they are inserted into the data_xxx tables.
217799**
217800** USAGE
217801**
217802** The API declared below allows an application to apply an RBU update
217803** stored on disk to an existing target database. Essentially, the
217804** application:
217805**
217806**     1) Opens an RBU handle using the sqlite3rbu_open() function.
217807**
217808**     2) Registers any required virtual table modules with the database
217809**        handle returned by sqlite3rbu_db(). Also, if required, register
217810**        the rbu_delta() implementation.
217811**
217812**     3) Calls the sqlite3rbu_step() function one or more times on
217813**        the new handle. Each call to sqlite3rbu_step() performs a single
217814**        b-tree operation, so thousands of calls may be required to apply
217815**        a complete update.
217816**
217817**     4) Calls sqlite3rbu_close() to close the RBU update handle. If
217818**        sqlite3rbu_step() has been called enough times to completely
217819**        apply the update to the target database, then the RBU database
217820**        is marked as fully applied. Otherwise, the state of the RBU
217821**        update application is saved in the RBU database for later
217822**        resumption.
217823**
217824** See comments below for more detail on APIs.
217825**
217826** If an update is only partially applied to the target database by the
217827** time sqlite3rbu_close() is called, various state information is saved
217828** within the RBU database. This allows subsequent processes to automatically
217829** resume the RBU update from where it left off.
217830**
217831** To remove all RBU extension state information, returning an RBU database
217832** to its original contents, it is sufficient to drop all tables that begin
217833** with the prefix "rbu_"
217834**
217835** DATABASE LOCKING
217836**
217837** An RBU update may not be applied to a database in WAL mode. Attempting
217838** to do so is an error (SQLITE_ERROR).
217839**
217840** While an RBU handle is open, a SHARED lock may be held on the target
217841** database file. This means it is possible for other clients to read the
217842** database, but not to write it.
217843**
217844** If an RBU update is started and then suspended before it is completed,
217845** then an external client writes to the database, then attempting to resume
217846** the suspended RBU update is also an error (SQLITE_BUSY).
217847*/
217848
217849#ifndef _SQLITE3RBU_H
217850#define _SQLITE3RBU_H
217851
217852/* #include "sqlite3.h"              ** Required for error code definitions ** */
217853
217854#if 0
217855extern "C" {
217856#endif
217857
217858typedef struct sqlite3rbu sqlite3rbu;
217859
217860/*
217861** Open an RBU handle.
217862**
217863** Argument zTarget is the path to the target database. Argument zRbu is
217864** the path to the RBU database. Each call to this function must be matched
217865** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
217866** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
217867** or zRbu begin with "file:", it will be interpreted as an SQLite
217868** database URI, not a regular file name.
217869**
217870** If the zState argument is passed a NULL value, the RBU extension stores
217871** the current state of the update (how many rows have been updated, which
217872** indexes are yet to be updated etc.) within the RBU database itself. This
217873** can be convenient, as it means that the RBU application does not need to
217874** organize removing a separate state file after the update is concluded.
217875** Or, if zState is non-NULL, it must be a path to a database file in which
217876** the RBU extension can store the state of the update.
217877**
217878** When resuming an RBU update, the zState argument must be passed the same
217879** value as when the RBU update was started.
217880**
217881** Once the RBU update is finished, the RBU extension does not
217882** automatically remove any zState database file, even if it created it.
217883**
217884** By default, RBU uses the default VFS to access the files on disk. To
217885** use a VFS other than the default, an SQLite "file:" URI containing a
217886** "vfs=..." option may be passed as the zTarget option.
217887**
217888** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
217889** SQLite's built-in VFSs, including the multiplexor VFS. However it does
217890** not work out of the box with zipvfs. Refer to the comment describing
217891** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
217892*/
217893SQLITE_API sqlite3rbu *sqlite3rbu_open(
217894  const char *zTarget,
217895  const char *zRbu,
217896  const char *zState
217897);
217898
217899/*
217900** Open an RBU handle to perform an RBU vacuum on database file zTarget.
217901** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
217902** that it can be suspended and resumed like an RBU update.
217903**
217904** The second argument to this function identifies a database in which
217905** to store the state of the RBU vacuum operation if it is suspended. The
217906** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
217907** operation, the state database should either not exist or be empty
217908** (contain no tables). If an RBU vacuum is suspended by calling
217909** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
217910** returned SQLITE_DONE, the vacuum state is stored in the state database.
217911** The vacuum can be resumed by calling this function to open a new RBU
217912** handle specifying the same target and state databases.
217913**
217914** If the second argument passed to this function is NULL, then the
217915** name of the state database is "<database>-vacuum", where <database>
217916** is the name of the target database file. In this case, on UNIX, if the
217917** state database is not already present in the file-system, it is created
217918** with the same permissions as the target db is made.
217919**
217920** With an RBU vacuum, it is an SQLITE_MISUSE error if the name of the
217921** state database ends with "-vactmp". This name is reserved for internal
217922** use.
217923**
217924** This function does not delete the state database after an RBU vacuum
217925** is completed, even if it created it. However, if the call to
217926** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
217927** of the state tables within the state database are zeroed. This way,
217928** the next call to sqlite3rbu_vacuum() opens a handle that starts a
217929** new RBU vacuum operation.
217930**
217931** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
217932** describing the sqlite3rbu_create_vfs() API function below for
217933** a description of the complications associated with using RBU with
217934** zipvfs databases.
217935*/
217936SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
217937  const char *zTarget,
217938  const char *zState
217939);
217940
217941/*
217942** Configure a limit for the amount of temp space that may be used by
217943** the RBU handle passed as the first argument. The new limit is specified
217944** in bytes by the second parameter. If it is positive, the limit is updated.
217945** If the second parameter to this function is passed zero, then the limit
217946** is removed entirely. If the second parameter is negative, the limit is
217947** not modified (this is useful for querying the current limit).
217948**
217949** In all cases the returned value is the current limit in bytes (zero
217950** indicates unlimited).
217951**
217952** If the temp space limit is exceeded during operation, an SQLITE_FULL
217953** error is returned.
217954*/
217955SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
217956
217957/*
217958** Return the current amount of temp file space, in bytes, currently used by
217959** the RBU handle passed as the only argument.
217960*/
217961SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
217962
217963/*
217964** Internally, each RBU connection uses a separate SQLite database
217965** connection to access the target and rbu update databases. This
217966** API allows the application direct access to these database handles.
217967**
217968** The first argument passed to this function must be a valid, open, RBU
217969** handle. The second argument should be passed zero to access the target
217970** database handle, or non-zero to access the rbu update database handle.
217971** Accessing the underlying database handles may be useful in the
217972** following scenarios:
217973**
217974**   * If any target tables are virtual tables, it may be necessary to
217975**     call sqlite3_create_module() on the target database handle to
217976**     register the required virtual table implementations.
217977**
217978**   * If the data_xxx tables in the RBU source database are virtual
217979**     tables, the application may need to call sqlite3_create_module() on
217980**     the rbu update db handle to any required virtual table
217981**     implementations.
217982**
217983**   * If the application uses the "rbu_delta()" feature described above,
217984**     it must use sqlite3_create_function() or similar to register the
217985**     rbu_delta() implementation with the target database handle.
217986**
217987** If an error has occurred, either while opening or stepping the RBU object,
217988** this function may return NULL. The error code and message may be collected
217989** when sqlite3rbu_close() is called.
217990**
217991** Database handles returned by this function remain valid until the next
217992** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
217993*/
217994SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
217995
217996/*
217997** Do some work towards applying the RBU update to the target db.
217998**
217999** Return SQLITE_DONE if the update has been completely applied, or
218000** SQLITE_OK if no error occurs but there remains work to do to apply
218001** the RBU update. If an error does occur, some other error code is
218002** returned.
218003**
218004** Once a call to sqlite3rbu_step() has returned a value other than
218005** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
218006** that immediately return the same value.
218007*/
218008SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
218009
218010/*
218011** Force RBU to save its state to disk.
218012**
218013** If a power failure or application crash occurs during an update, following
218014** system recovery RBU may resume the update from the point at which the state
218015** was last saved. In other words, from the most recent successful call to
218016** sqlite3rbu_close() or this function.
218017**
218018** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
218019*/
218020SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
218021
218022/*
218023** Close an RBU handle.
218024**
218025** If the RBU update has been completely applied, mark the RBU database
218026** as fully applied. Otherwise, assuming no error has occurred, save the
218027** current state of the RBU update appliation to the RBU database.
218028**
218029** If an error has already occurred as part of an sqlite3rbu_step()
218030** or sqlite3rbu_open() call, or if one occurs within this function, an
218031** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
218032** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
218033** English language error message. It is the responsibility of the caller to
218034** eventually free any such buffer using sqlite3_free().
218035**
218036** Otherwise, if no error occurs, this function returns SQLITE_OK if the
218037** update has been partially applied, or SQLITE_DONE if it has been
218038** completely applied.
218039*/
218040SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
218041
218042/*
218043** Return the total number of key-value operations (inserts, deletes or
218044** updates) that have been performed on the target database since the
218045** current RBU update was started.
218046*/
218047SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
218048
218049/*
218050** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
218051** progress indications for the two stages of an RBU update. This API may
218052** be useful for driving GUI progress indicators and similar.
218053**
218054** An RBU update is divided into two stages:
218055**
218056**   * Stage 1, in which changes are accumulated in an oal/wal file, and
218057**   * Stage 2, in which the contents of the wal file are copied into the
218058**     main database.
218059**
218060** The update is visible to non-RBU clients during stage 2. During stage 1
218061** non-RBU reader clients may see the original database.
218062**
218063** If this API is called during stage 2 of the update, output variable
218064** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
218065** to a value between 0 and 10000 to indicate the permyriadage progress of
218066** stage 2. A value of 5000 indicates that stage 2 is half finished,
218067** 9000 indicates that it is 90% finished, and so on.
218068**
218069** If this API is called during stage 1 of the update, output variable
218070** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
218071** value to which (*pnOne) is set depends on whether or not the RBU
218072** database contains an "rbu_count" table. The rbu_count table, if it
218073** exists, must contain the same columns as the following:
218074**
218075**   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
218076**
218077** There must be one row in the table for each source (data_xxx) table within
218078** the RBU database. The 'tbl' column should contain the name of the source
218079** table. The 'cnt' column should contain the number of rows within the
218080** source table.
218081**
218082** If the rbu_count table is present and populated correctly and this
218083** API is called during stage 1, the *pnOne output variable is set to the
218084** permyriadage progress of the same stage. If the rbu_count table does
218085** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
218086** table exists but is not correctly populated, the value of the *pnOne
218087** output variable during stage 1 is undefined.
218088*/
218089SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
218090
218091/*
218092** Obtain an indication as to the current stage of an RBU update or vacuum.
218093** This function always returns one of the SQLITE_RBU_STATE_XXX constants
218094** defined in this file. Return values should be interpreted as follows:
218095**
218096** SQLITE_RBU_STATE_OAL:
218097**   RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
218098**   may either add further data to the *-oal file, or compute data that will
218099**   be added by a subsequent call.
218100**
218101** SQLITE_RBU_STATE_MOVE:
218102**   RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
218103**   will move the *-oal file to the equivalent *-wal path. If the current
218104**   operation is an RBU update, then the updated version of the database
218105**   file will become visible to ordinary SQLite clients following the next
218106**   call to sqlite3rbu_step().
218107**
218108** SQLITE_RBU_STATE_CHECKPOINT:
218109**   RBU is currently performing an incremental checkpoint. The next call to
218110**   sqlite3rbu_step() will copy a page of data from the *-wal file into
218111**   the target database file.
218112**
218113** SQLITE_RBU_STATE_DONE:
218114**   The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
218115**   will immediately return SQLITE_DONE.
218116**
218117** SQLITE_RBU_STATE_ERROR:
218118**   An error has occurred. Any subsequent calls to sqlite3rbu_step() will
218119**   immediately return the SQLite error code associated with the error.
218120*/
218121#define SQLITE_RBU_STATE_OAL        1
218122#define SQLITE_RBU_STATE_MOVE       2
218123#define SQLITE_RBU_STATE_CHECKPOINT 3
218124#define SQLITE_RBU_STATE_DONE       4
218125#define SQLITE_RBU_STATE_ERROR      5
218126
218127SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
218128
218129/*
218130** As part of applying an RBU update or performing an RBU vacuum operation,
218131** the system must at one point move the *-oal file to the equivalent *-wal
218132** path. Normally, it does this by invoking POSIX function rename(2) directly.
218133** Except on WINCE platforms, where it uses win32 API MoveFileW(). This
218134** function may be used to register a callback that the RBU module will invoke
218135** instead of one of these APIs.
218136**
218137** If a callback is registered with an RBU handle, it invokes it instead
218138** of rename(2) when it needs to move a file within the file-system. The
218139** first argument passed to the xRename() callback is a copy of the second
218140** argument (pArg) passed to this function. The second is the full path
218141** to the file to move and the third the full path to which it should be
218142** moved. The callback function should return SQLITE_OK to indicate
218143** success. If an error occurs, it should return an SQLite error code.
218144** In this case the RBU operation will be abandoned and the error returned
218145** to the RBU user.
218146**
218147** Passing a NULL pointer in place of the xRename argument to this function
218148** restores the default behaviour.
218149*/
218150SQLITE_API void sqlite3rbu_rename_handler(
218151  sqlite3rbu *pRbu,
218152  void *pArg,
218153  int (*xRename)(void *pArg, const char *zOld, const char *zNew)
218154);
218155
218156
218157/*
218158** Create an RBU VFS named zName that accesses the underlying file-system
218159** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
218160** then the new RBU VFS uses the default system VFS to access the file-system.
218161** The new object is registered as a non-default VFS with SQLite before
218162** returning.
218163**
218164** Part of the RBU implementation uses a custom VFS object. Usually, this
218165** object is created and deleted automatically by RBU.
218166**
218167** The exception is for applications that also use zipvfs. In this case,
218168** the custom VFS must be explicitly created by the user before the RBU
218169** handle is opened. The RBU VFS should be installed so that the zipvfs
218170** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
218171** (for example multiplexor) to access the file-system. For example,
218172** to assemble an RBU enabled VFS stack that uses both zipvfs and
218173** multiplexor (error checking omitted):
218174**
218175**     // Create a VFS named "multiplex" (not the default).
218176**     sqlite3_multiplex_initialize(0, 0);
218177**
218178**     // Create an rbu VFS named "rbu" that uses multiplexor. If the
218179**     // second argument were replaced with NULL, the "rbu" VFS would
218180**     // access the file-system via the system default VFS, bypassing the
218181**     // multiplexor.
218182**     sqlite3rbu_create_vfs("rbu", "multiplex");
218183**
218184**     // Create a zipvfs VFS named "zipvfs" that uses rbu.
218185**     zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
218186**
218187**     // Make zipvfs the default VFS.
218188**     sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
218189**
218190** Because the default VFS created above includes a RBU functionality, it
218191** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
218192** that does not include the RBU layer results in an error.
218193**
218194** The overhead of adding the "rbu" VFS to the system is negligible for
218195** non-RBU users. There is no harm in an application accessing the
218196** file-system via "rbu" all the time, even if it only uses RBU functionality
218197** occasionally.
218198*/
218199SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
218200
218201/*
218202** Deregister and destroy an RBU vfs created by an earlier call to
218203** sqlite3rbu_create_vfs().
218204**
218205** VFS objects are not reference counted. If a VFS object is destroyed
218206** before all database handles that use it have been closed, the results
218207** are undefined.
218208*/
218209SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
218210
218211#if 0
218212}  /* end of the 'extern "C"' block */
218213#endif
218214
218215#endif /* _SQLITE3RBU_H */
218216
218217/************** End of sqlite3rbu.h ******************************************/
218218/************** Continuing where we left off in sqlite3rbu.c *****************/
218219
218220#if defined(_WIN32_WCE)
218221/* #include "windows.h" */
218222#endif
218223
218224/* Maximum number of prepared UPDATE statements held by this module */
218225#define SQLITE_RBU_UPDATE_CACHESIZE 16
218226
218227/* Delta checksums disabled by default.  Compile with -DRBU_ENABLE_DELTA_CKSUM
218228** to enable checksum verification.
218229*/
218230#ifndef RBU_ENABLE_DELTA_CKSUM
218231# define RBU_ENABLE_DELTA_CKSUM 0
218232#endif
218233
218234/*
218235** Swap two objects of type TYPE.
218236*/
218237#if !defined(SQLITE_AMALGAMATION)
218238# define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
218239#endif
218240
218241/*
218242** Name of the URI option that causes RBU to take an exclusive lock as
218243** part of the incremental checkpoint operation.
218244*/
218245#define RBU_EXCLUSIVE_CHECKPOINT "rbu_exclusive_checkpoint"
218246
218247
218248/*
218249** The rbu_state table is used to save the state of a partially applied
218250** update so that it can be resumed later. The table consists of integer
218251** keys mapped to values as follows:
218252**
218253** RBU_STATE_STAGE:
218254**   May be set to integer values 1, 2, 4 or 5. As follows:
218255**       1: the *-rbu file is currently under construction.
218256**       2: the *-rbu file has been constructed, but not yet moved
218257**          to the *-wal path.
218258**       4: the checkpoint is underway.
218259**       5: the rbu update has been checkpointed.
218260**
218261** RBU_STATE_TBL:
218262**   Only valid if STAGE==1. The target database name of the table
218263**   currently being written.
218264**
218265** RBU_STATE_IDX:
218266**   Only valid if STAGE==1. The target database name of the index
218267**   currently being written, or NULL if the main table is currently being
218268**   updated.
218269**
218270** RBU_STATE_ROW:
218271**   Only valid if STAGE==1. Number of rows already processed for the current
218272**   table/index.
218273**
218274** RBU_STATE_PROGRESS:
218275**   Trbul number of sqlite3rbu_step() calls made so far as part of this
218276**   rbu update.
218277**
218278** RBU_STATE_CKPT:
218279**   Valid if STAGE==4. The 64-bit checksum associated with the wal-index
218280**   header created by recovering the *-wal file. This is used to detect
218281**   cases when another client appends frames to the *-wal file in the
218282**   middle of an incremental checkpoint (an incremental checkpoint cannot
218283**   be continued if this happens).
218284**
218285** RBU_STATE_COOKIE:
218286**   Valid if STAGE==1. The current change-counter cookie value in the
218287**   target db file.
218288**
218289** RBU_STATE_OALSZ:
218290**   Valid if STAGE==1. The size in bytes of the *-oal file.
218291**
218292** RBU_STATE_DATATBL:
218293**   Only valid if STAGE==1. The RBU database name of the table
218294**   currently being read.
218295*/
218296#define RBU_STATE_STAGE        1
218297#define RBU_STATE_TBL          2
218298#define RBU_STATE_IDX          3
218299#define RBU_STATE_ROW          4
218300#define RBU_STATE_PROGRESS     5
218301#define RBU_STATE_CKPT         6
218302#define RBU_STATE_COOKIE       7
218303#define RBU_STATE_OALSZ        8
218304#define RBU_STATE_PHASEONESTEP 9
218305#define RBU_STATE_DATATBL     10
218306
218307#define RBU_STAGE_OAL         1
218308#define RBU_STAGE_MOVE        2
218309#define RBU_STAGE_CAPTURE     3
218310#define RBU_STAGE_CKPT        4
218311#define RBU_STAGE_DONE        5
218312
218313
218314#define RBU_CREATE_STATE \
218315  "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
218316
218317typedef struct RbuFrame RbuFrame;
218318typedef struct RbuObjIter RbuObjIter;
218319typedef struct RbuState RbuState;
218320typedef struct RbuSpan RbuSpan;
218321typedef struct rbu_vfs rbu_vfs;
218322typedef struct rbu_file rbu_file;
218323typedef struct RbuUpdateStmt RbuUpdateStmt;
218324
218325#if !defined(SQLITE_AMALGAMATION)
218326typedef unsigned int u32;
218327typedef unsigned short u16;
218328typedef unsigned char u8;
218329typedef sqlite3_int64 i64;
218330typedef sqlite3_uint64 u64;
218331#endif
218332
218333/*
218334** These values must match the values defined in wal.c for the equivalent
218335** locks. These are not magic numbers as they are part of the SQLite file
218336** format.
218337*/
218338#define WAL_LOCK_WRITE  0
218339#define WAL_LOCK_CKPT   1
218340#define WAL_LOCK_READ0  3
218341
218342#define SQLITE_FCNTL_RBUCNT    5149216
218343
218344/*
218345** A structure to store values read from the rbu_state table in memory.
218346*/
218347struct RbuState {
218348  int eStage;
218349  char *zTbl;
218350  char *zDataTbl;
218351  char *zIdx;
218352  i64 iWalCksum;
218353  int nRow;
218354  i64 nProgress;
218355  u32 iCookie;
218356  i64 iOalSz;
218357  i64 nPhaseOneStep;
218358};
218359
218360struct RbuUpdateStmt {
218361  char *zMask;                    /* Copy of update mask used with pUpdate */
218362  sqlite3_stmt *pUpdate;          /* Last update statement (or NULL) */
218363  RbuUpdateStmt *pNext;
218364};
218365
218366struct RbuSpan {
218367  const char *zSpan;
218368  int nSpan;
218369};
218370
218371/*
218372** An iterator of this type is used to iterate through all objects in
218373** the target database that require updating. For each such table, the
218374** iterator visits, in order:
218375**
218376**     * the table itself,
218377**     * each index of the table (zero or more points to visit), and
218378**     * a special "cleanup table" state.
218379**
218380** abIndexed:
218381**   If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
218382**   it points to an array of flags nTblCol elements in size. The flag is
218383**   set for each column that is either a part of the PK or a part of an
218384**   index. Or clear otherwise.
218385**
218386**   If there are one or more partial indexes on the table, all fields of
218387**   this array set set to 1. This is because in that case, the module has
218388**   no way to tell which fields will be required to add and remove entries
218389**   from the partial indexes.
218390**
218391*/
218392struct RbuObjIter {
218393  sqlite3_stmt *pTblIter;         /* Iterate through tables */
218394  sqlite3_stmt *pIdxIter;         /* Index iterator */
218395  int nTblCol;                    /* Size of azTblCol[] array */
218396  char **azTblCol;                /* Array of unquoted target column names */
218397  char **azTblType;               /* Array of target column types */
218398  int *aiSrcOrder;                /* src table col -> target table col */
218399  u8 *abTblPk;                    /* Array of flags, set on target PK columns */
218400  u8 *abNotNull;                  /* Array of flags, set on NOT NULL columns */
218401  u8 *abIndexed;                  /* Array of flags, set on indexed & PK cols */
218402  int eType;                      /* Table type - an RBU_PK_XXX value */
218403
218404  /* Output variables. zTbl==0 implies EOF. */
218405  int bCleanup;                   /* True in "cleanup" state */
218406  const char *zTbl;               /* Name of target db table */
218407  const char *zDataTbl;           /* Name of rbu db table (or null) */
218408  const char *zIdx;               /* Name of target db index (or null) */
218409  int iTnum;                      /* Root page of current object */
218410  int iPkTnum;                    /* If eType==EXTERNAL, root of PK index */
218411  int bUnique;                    /* Current index is unique */
218412  int nIndex;                     /* Number of aux. indexes on table zTbl */
218413
218414  /* Statements created by rbuObjIterPrepareAll() */
218415  int nCol;                       /* Number of columns in current object */
218416  sqlite3_stmt *pSelect;          /* Source data */
218417  sqlite3_stmt *pInsert;          /* Statement for INSERT operations */
218418  sqlite3_stmt *pDelete;          /* Statement for DELETE ops */
218419  sqlite3_stmt *pTmpInsert;       /* Insert into rbu_tmp_$zDataTbl */
218420  int nIdxCol;
218421  RbuSpan *aIdxCol;
218422  char *zIdxSql;
218423
218424  /* Last UPDATE used (for PK b-tree updates only), or NULL. */
218425  RbuUpdateStmt *pRbuUpdate;
218426};
218427
218428/*
218429** Values for RbuObjIter.eType
218430**
218431**     0: Table does not exist (error)
218432**     1: Table has an implicit rowid.
218433**     2: Table has an explicit IPK column.
218434**     3: Table has an external PK index.
218435**     4: Table is WITHOUT ROWID.
218436**     5: Table is a virtual table.
218437*/
218438#define RBU_PK_NOTABLE        0
218439#define RBU_PK_NONE           1
218440#define RBU_PK_IPK            2
218441#define RBU_PK_EXTERNAL       3
218442#define RBU_PK_WITHOUT_ROWID  4
218443#define RBU_PK_VTAB           5
218444
218445
218446/*
218447** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
218448** one of the following operations.
218449*/
218450#define RBU_INSERT     1          /* Insert on a main table b-tree */
218451#define RBU_DELETE     2          /* Delete a row from a main table b-tree */
218452#define RBU_REPLACE    3          /* Delete and then insert a row */
218453#define RBU_IDX_DELETE 4          /* Delete a row from an aux. index b-tree */
218454#define RBU_IDX_INSERT 5          /* Insert on an aux. index b-tree */
218455
218456#define RBU_UPDATE     6          /* Update a row in a main table b-tree */
218457
218458/*
218459** A single step of an incremental checkpoint - frame iWalFrame of the wal
218460** file should be copied to page iDbPage of the database file.
218461*/
218462struct RbuFrame {
218463  u32 iDbPage;
218464  u32 iWalFrame;
218465};
218466
218467/*
218468** RBU handle.
218469**
218470** nPhaseOneStep:
218471**   If the RBU database contains an rbu_count table, this value is set to
218472**   a running estimate of the number of b-tree operations required to
218473**   finish populating the *-oal file. This allows the sqlite3_bp_progress()
218474**   API to calculate the permyriadage progress of populating the *-oal file
218475**   using the formula:
218476**
218477**     permyriadage = (10000 * nProgress) / nPhaseOneStep
218478**
218479**   nPhaseOneStep is initialized to the sum of:
218480**
218481**     nRow * (nIndex + 1)
218482**
218483**   for all source tables in the RBU database, where nRow is the number
218484**   of rows in the source table and nIndex the number of indexes on the
218485**   corresponding target database table.
218486**
218487**   This estimate is accurate if the RBU update consists entirely of
218488**   INSERT operations. However, it is inaccurate if:
218489**
218490**     * the RBU update contains any UPDATE operations. If the PK specified
218491**       for an UPDATE operation does not exist in the target table, then
218492**       no b-tree operations are required on index b-trees. Or if the
218493**       specified PK does exist, then (nIndex*2) such operations are
218494**       required (one delete and one insert on each index b-tree).
218495**
218496**     * the RBU update contains any DELETE operations for which the specified
218497**       PK does not exist. In this case no operations are required on index
218498**       b-trees.
218499**
218500**     * the RBU update contains REPLACE operations. These are similar to
218501**       UPDATE operations.
218502**
218503**   nPhaseOneStep is updated to account for the conditions above during the
218504**   first pass of each source table. The updated nPhaseOneStep value is
218505**   stored in the rbu_state table if the RBU update is suspended.
218506*/
218507struct sqlite3rbu {
218508  int eStage;                     /* Value of RBU_STATE_STAGE field */
218509  sqlite3 *dbMain;                /* target database handle */
218510  sqlite3 *dbRbu;                 /* rbu database handle */
218511  char *zTarget;                  /* Path to target db */
218512  char *zRbu;                     /* Path to rbu db */
218513  char *zState;                   /* Path to state db (or NULL if zRbu) */
218514  char zStateDb[5];               /* Db name for state ("stat" or "main") */
218515  int rc;                         /* Value returned by last rbu_step() call */
218516  char *zErrmsg;                  /* Error message if rc!=SQLITE_OK */
218517  int nStep;                      /* Rows processed for current object */
218518  int nProgress;                  /* Rows processed for all objects */
218519  RbuObjIter objiter;             /* Iterator for skipping through tbl/idx */
218520  const char *zVfsName;           /* Name of automatically created rbu vfs */
218521  rbu_file *pTargetFd;            /* File handle open on target db */
218522  int nPagePerSector;             /* Pages per sector for pTargetFd */
218523  i64 iOalSz;
218524  i64 nPhaseOneStep;
218525  void *pRenameArg;
218526  int (*xRename)(void*, const char*, const char*);
218527
218528  /* The following state variables are used as part of the incremental
218529  ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
218530  ** function rbuSetupCheckpoint() for details.  */
218531  u32 iMaxFrame;                  /* Largest iWalFrame value in aFrame[] */
218532  u32 mLock;
218533  int nFrame;                     /* Entries in aFrame[] array */
218534  int nFrameAlloc;                /* Allocated size of aFrame[] array */
218535  RbuFrame *aFrame;
218536  int pgsz;
218537  u8 *aBuf;
218538  i64 iWalCksum;
218539  i64 szTemp;                     /* Current size of all temp files in use */
218540  i64 szTempLimit;                /* Total size limit for temp files */
218541
218542  /* Used in RBU vacuum mode only */
218543  int nRbu;                       /* Number of RBU VFS in the stack */
218544  rbu_file *pRbuFd;               /* Fd for main db of dbRbu */
218545};
218546
218547/*
218548** An rbu VFS is implemented using an instance of this structure.
218549**
218550** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
218551** It is NULL for RBU VFS objects created explicitly using
218552** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
218553** space used by the RBU handle.
218554*/
218555struct rbu_vfs {
218556  sqlite3_vfs base;               /* rbu VFS shim methods */
218557  sqlite3_vfs *pRealVfs;          /* Underlying VFS */
218558  sqlite3_mutex *mutex;           /* Mutex to protect pMain */
218559  sqlite3rbu *pRbu;               /* Owner RBU object */
218560  rbu_file *pMain;                /* List of main db files */
218561  rbu_file *pMainRbu;             /* List of main db files with pRbu!=0 */
218562};
218563
218564/*
218565** Each file opened by an rbu VFS is represented by an instance of
218566** the following structure.
218567**
218568** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
218569** "sz" is set to the current size of the database file.
218570*/
218571struct rbu_file {
218572  sqlite3_file base;              /* sqlite3_file methods */
218573  sqlite3_file *pReal;            /* Underlying file handle */
218574  rbu_vfs *pRbuVfs;               /* Pointer to the rbu_vfs object */
218575  sqlite3rbu *pRbu;               /* Pointer to rbu object (rbu target only) */
218576  i64 sz;                         /* Size of file in bytes (temp only) */
218577
218578  int openFlags;                  /* Flags this file was opened with */
218579  u32 iCookie;                    /* Cookie value for main db files */
218580  u8 iWriteVer;                   /* "write-version" value for main db files */
218581  u8 bNolock;                     /* True to fail EXCLUSIVE locks */
218582
218583  int nShm;                       /* Number of entries in apShm[] array */
218584  char **apShm;                   /* Array of mmap'd *-shm regions */
218585  char *zDel;                     /* Delete this when closing file */
218586
218587  const char *zWal;               /* Wal filename for this main db file */
218588  rbu_file *pWalFd;               /* Wal file descriptor for this main db */
218589  rbu_file *pMainNext;            /* Next MAIN_DB file */
218590  rbu_file *pMainRbuNext;         /* Next MAIN_DB file with pRbu!=0 */
218591};
218592
218593/*
218594** True for an RBU vacuum handle, or false otherwise.
218595*/
218596#define rbuIsVacuum(p) ((p)->zTarget==0)
218597
218598
218599/*************************************************************************
218600** The following three functions, found below:
218601**
218602**   rbuDeltaGetInt()
218603**   rbuDeltaChecksum()
218604**   rbuDeltaApply()
218605**
218606** are lifted from the fossil source code (http://fossil-scm.org). They
218607** are used to implement the scalar SQL function rbu_fossil_delta().
218608*/
218609
218610/*
218611** Read bytes from *pz and convert them into a positive integer.  When
218612** finished, leave *pz pointing to the first character past the end of
218613** the integer.  The *pLen parameter holds the length of the string
218614** in *pz and is decremented once for each character in the integer.
218615*/
218616static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
218617  static const signed char zValue[] = {
218618    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
218619    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
218620    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
218621     0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,
218622    -1, 10, 11, 12, 13, 14, 15, 16,   17, 18, 19, 20, 21, 22, 23, 24,
218623    25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, -1, -1, -1, -1, 36,
218624    -1, 37, 38, 39, 40, 41, 42, 43,   44, 45, 46, 47, 48, 49, 50, 51,
218625    52, 53, 54, 55, 56, 57, 58, 59,   60, 61, 62, -1, -1, -1, 63, -1,
218626  };
218627  unsigned int v = 0;
218628  int c;
218629  unsigned char *z = (unsigned char*)*pz;
218630  unsigned char *zStart = z;
218631  while( (c = zValue[0x7f&*(z++)])>=0 ){
218632     v = (v<<6) + c;
218633  }
218634  z--;
218635  *pLen -= z - zStart;
218636  *pz = (char*)z;
218637  return v;
218638}
218639
218640#if RBU_ENABLE_DELTA_CKSUM
218641/*
218642** Compute a 32-bit checksum on the N-byte buffer.  Return the result.
218643*/
218644static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
218645  const unsigned char *z = (const unsigned char *)zIn;
218646  unsigned sum0 = 0;
218647  unsigned sum1 = 0;
218648  unsigned sum2 = 0;
218649  unsigned sum3 = 0;
218650  while(N >= 16){
218651    sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
218652    sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
218653    sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
218654    sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
218655    z += 16;
218656    N -= 16;
218657  }
218658  while(N >= 4){
218659    sum0 += z[0];
218660    sum1 += z[1];
218661    sum2 += z[2];
218662    sum3 += z[3];
218663    z += 4;
218664    N -= 4;
218665  }
218666  sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
218667  switch(N){
218668    case 3:   sum3 += (z[2] << 8);
218669    case 2:   sum3 += (z[1] << 16);
218670    case 1:   sum3 += (z[0] << 24);
218671    default:  ;
218672  }
218673  return sum3;
218674}
218675#endif
218676
218677/*
218678** Apply a delta.
218679**
218680** The output buffer should be big enough to hold the whole output
218681** file and a NUL terminator at the end.  The delta_output_size()
218682** routine will determine this size for you.
218683**
218684** The delta string should be null-terminated.  But the delta string
218685** may contain embedded NUL characters (if the input and output are
218686** binary files) so we also have to pass in the length of the delta in
218687** the lenDelta parameter.
218688**
218689** This function returns the size of the output file in bytes (excluding
218690** the final NUL terminator character).  Except, if the delta string is
218691** malformed or intended for use with a source file other than zSrc,
218692** then this routine returns -1.
218693**
218694** Refer to the delta_create() documentation above for a description
218695** of the delta file format.
218696*/
218697static int rbuDeltaApply(
218698  const char *zSrc,      /* The source or pattern file */
218699  int lenSrc,            /* Length of the source file */
218700  const char *zDelta,    /* Delta to apply to the pattern */
218701  int lenDelta,          /* Length of the delta */
218702  char *zOut             /* Write the output into this preallocated buffer */
218703){
218704  unsigned int limit;
218705  unsigned int total = 0;
218706#if RBU_ENABLE_DELTA_CKSUM
218707  char *zOrigOut = zOut;
218708#endif
218709
218710  limit = rbuDeltaGetInt(&zDelta, &lenDelta);
218711  if( *zDelta!='\n' ){
218712    /* ERROR: size integer not terminated by "\n" */
218713    return -1;
218714  }
218715  zDelta++; lenDelta--;
218716  while( *zDelta && lenDelta>0 ){
218717    unsigned int cnt, ofst;
218718    cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
218719    switch( zDelta[0] ){
218720      case '@': {
218721        zDelta++; lenDelta--;
218722        ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
218723        if( lenDelta>0 && zDelta[0]!=',' ){
218724          /* ERROR: copy command not terminated by ',' */
218725          return -1;
218726        }
218727        zDelta++; lenDelta--;
218728        total += cnt;
218729        if( total>limit ){
218730          /* ERROR: copy exceeds output file size */
218731          return -1;
218732        }
218733        if( (int)(ofst+cnt) > lenSrc ){
218734          /* ERROR: copy extends past end of input */
218735          return -1;
218736        }
218737        memcpy(zOut, &zSrc[ofst], cnt);
218738        zOut += cnt;
218739        break;
218740      }
218741      case ':': {
218742        zDelta++; lenDelta--;
218743        total += cnt;
218744        if( total>limit ){
218745          /* ERROR:  insert command gives an output larger than predicted */
218746          return -1;
218747        }
218748        if( (int)cnt>lenDelta ){
218749          /* ERROR: insert count exceeds size of delta */
218750          return -1;
218751        }
218752        memcpy(zOut, zDelta, cnt);
218753        zOut += cnt;
218754        zDelta += cnt;
218755        lenDelta -= cnt;
218756        break;
218757      }
218758      case ';': {
218759        zDelta++; lenDelta--;
218760        zOut[0] = 0;
218761#if RBU_ENABLE_DELTA_CKSUM
218762        if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
218763          /* ERROR:  bad checksum */
218764          return -1;
218765        }
218766#endif
218767        if( total!=limit ){
218768          /* ERROR: generated size does not match predicted size */
218769          return -1;
218770        }
218771        return total;
218772      }
218773      default: {
218774        /* ERROR: unknown delta operator */
218775        return -1;
218776      }
218777    }
218778  }
218779  /* ERROR: unterminated delta */
218780  return -1;
218781}
218782
218783static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
218784  int size;
218785  size = rbuDeltaGetInt(&zDelta, &lenDelta);
218786  if( *zDelta!='\n' ){
218787    /* ERROR: size integer not terminated by "\n" */
218788    return -1;
218789  }
218790  return size;
218791}
218792
218793/*
218794** End of code taken from fossil.
218795*************************************************************************/
218796
218797/*
218798** Implementation of SQL scalar function rbu_fossil_delta().
218799**
218800** This function applies a fossil delta patch to a blob. Exactly two
218801** arguments must be passed to this function. The first is the blob to
218802** patch and the second the patch to apply. If no error occurs, this
218803** function returns the patched blob.
218804*/
218805static void rbuFossilDeltaFunc(
218806  sqlite3_context *context,
218807  int argc,
218808  sqlite3_value **argv
218809){
218810  const char *aDelta;
218811  int nDelta;
218812  const char *aOrig;
218813  int nOrig;
218814
218815  int nOut;
218816  int nOut2;
218817  char *aOut;
218818
218819  assert( argc==2 );
218820
218821  nOrig = sqlite3_value_bytes(argv[0]);
218822  aOrig = (const char*)sqlite3_value_blob(argv[0]);
218823  nDelta = sqlite3_value_bytes(argv[1]);
218824  aDelta = (const char*)sqlite3_value_blob(argv[1]);
218825
218826  /* Figure out the size of the output */
218827  nOut = rbuDeltaOutputSize(aDelta, nDelta);
218828  if( nOut<0 ){
218829    sqlite3_result_error(context, "corrupt fossil delta", -1);
218830    return;
218831  }
218832
218833  aOut = sqlite3_malloc(nOut+1);
218834  if( aOut==0 ){
218835    sqlite3_result_error_nomem(context);
218836  }else{
218837    nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
218838    if( nOut2!=nOut ){
218839      sqlite3_free(aOut);
218840      sqlite3_result_error(context, "corrupt fossil delta", -1);
218841    }else{
218842      sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
218843    }
218844  }
218845}
218846
218847
218848/*
218849** Prepare the SQL statement in buffer zSql against database handle db.
218850** If successful, set *ppStmt to point to the new statement and return
218851** SQLITE_OK.
218852**
218853** Otherwise, if an error does occur, set *ppStmt to NULL and return
218854** an SQLite error code. Additionally, set output variable *pzErrmsg to
218855** point to a buffer containing an error message. It is the responsibility
218856** of the caller to (eventually) free this buffer using sqlite3_free().
218857*/
218858static int prepareAndCollectError(
218859  sqlite3 *db,
218860  sqlite3_stmt **ppStmt,
218861  char **pzErrmsg,
218862  const char *zSql
218863){
218864  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
218865  if( rc!=SQLITE_OK ){
218866    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
218867    *ppStmt = 0;
218868  }
218869  return rc;
218870}
218871
218872/*
218873** Reset the SQL statement passed as the first argument. Return a copy
218874** of the value returned by sqlite3_reset().
218875**
218876** If an error has occurred, then set *pzErrmsg to point to a buffer
218877** containing an error message. It is the responsibility of the caller
218878** to eventually free this buffer using sqlite3_free().
218879*/
218880static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
218881  int rc = sqlite3_reset(pStmt);
218882  if( rc!=SQLITE_OK ){
218883    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
218884  }
218885  return rc;
218886}
218887
218888/*
218889** Unless it is NULL, argument zSql points to a buffer allocated using
218890** sqlite3_malloc containing an SQL statement. This function prepares the SQL
218891** statement against database db and frees the buffer. If statement
218892** compilation is successful, *ppStmt is set to point to the new statement
218893** handle and SQLITE_OK is returned.
218894**
218895** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
218896** returned. In this case, *pzErrmsg may also be set to point to an error
218897** message. It is the responsibility of the caller to free this error message
218898** buffer using sqlite3_free().
218899**
218900** If argument zSql is NULL, this function assumes that an OOM has occurred.
218901** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
218902*/
218903static int prepareFreeAndCollectError(
218904  sqlite3 *db,
218905  sqlite3_stmt **ppStmt,
218906  char **pzErrmsg,
218907  char *zSql
218908){
218909  int rc;
218910  assert( *pzErrmsg==0 );
218911  if( zSql==0 ){
218912    rc = SQLITE_NOMEM;
218913    *ppStmt = 0;
218914  }else{
218915    rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
218916    sqlite3_free(zSql);
218917  }
218918  return rc;
218919}
218920
218921/*
218922** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
218923** by an earlier call to rbuObjIterCacheTableInfo().
218924*/
218925static void rbuObjIterFreeCols(RbuObjIter *pIter){
218926  int i;
218927  for(i=0; i<pIter->nTblCol; i++){
218928    sqlite3_free(pIter->azTblCol[i]);
218929    sqlite3_free(pIter->azTblType[i]);
218930  }
218931  sqlite3_free(pIter->azTblCol);
218932  pIter->azTblCol = 0;
218933  pIter->azTblType = 0;
218934  pIter->aiSrcOrder = 0;
218935  pIter->abTblPk = 0;
218936  pIter->abNotNull = 0;
218937  pIter->nTblCol = 0;
218938  pIter->eType = 0;               /* Invalid value */
218939}
218940
218941/*
218942** Finalize all statements and free all allocations that are specific to
218943** the current object (table/index pair).
218944*/
218945static void rbuObjIterClearStatements(RbuObjIter *pIter){
218946  RbuUpdateStmt *pUp;
218947
218948  sqlite3_finalize(pIter->pSelect);
218949  sqlite3_finalize(pIter->pInsert);
218950  sqlite3_finalize(pIter->pDelete);
218951  sqlite3_finalize(pIter->pTmpInsert);
218952  pUp = pIter->pRbuUpdate;
218953  while( pUp ){
218954    RbuUpdateStmt *pTmp = pUp->pNext;
218955    sqlite3_finalize(pUp->pUpdate);
218956    sqlite3_free(pUp);
218957    pUp = pTmp;
218958  }
218959  sqlite3_free(pIter->aIdxCol);
218960  sqlite3_free(pIter->zIdxSql);
218961
218962  pIter->pSelect = 0;
218963  pIter->pInsert = 0;
218964  pIter->pDelete = 0;
218965  pIter->pRbuUpdate = 0;
218966  pIter->pTmpInsert = 0;
218967  pIter->nCol = 0;
218968  pIter->nIdxCol = 0;
218969  pIter->aIdxCol = 0;
218970  pIter->zIdxSql = 0;
218971}
218972
218973/*
218974** Clean up any resources allocated as part of the iterator object passed
218975** as the only argument.
218976*/
218977static void rbuObjIterFinalize(RbuObjIter *pIter){
218978  rbuObjIterClearStatements(pIter);
218979  sqlite3_finalize(pIter->pTblIter);
218980  sqlite3_finalize(pIter->pIdxIter);
218981  rbuObjIterFreeCols(pIter);
218982  memset(pIter, 0, sizeof(RbuObjIter));
218983}
218984
218985/*
218986** Advance the iterator to the next position.
218987**
218988** If no error occurs, SQLITE_OK is returned and the iterator is left
218989** pointing to the next entry. Otherwise, an error code and message is
218990** left in the RBU handle passed as the first argument. A copy of the
218991** error code is returned.
218992*/
218993static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
218994  int rc = p->rc;
218995  if( rc==SQLITE_OK ){
218996
218997    /* Free any SQLite statements used while processing the previous object */
218998    rbuObjIterClearStatements(pIter);
218999    if( pIter->zIdx==0 ){
219000      rc = sqlite3_exec(p->dbMain,
219001          "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
219002          "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
219003          "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
219004          "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
219005          , 0, 0, &p->zErrmsg
219006      );
219007    }
219008
219009    if( rc==SQLITE_OK ){
219010      if( pIter->bCleanup ){
219011        rbuObjIterFreeCols(pIter);
219012        pIter->bCleanup = 0;
219013        rc = sqlite3_step(pIter->pTblIter);
219014        if( rc!=SQLITE_ROW ){
219015          rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
219016          pIter->zTbl = 0;
219017          pIter->zDataTbl = 0;
219018        }else{
219019          pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
219020          pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
219021          rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
219022        }
219023      }else{
219024        if( pIter->zIdx==0 ){
219025          sqlite3_stmt *pIdx = pIter->pIdxIter;
219026          rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
219027        }
219028        if( rc==SQLITE_OK ){
219029          rc = sqlite3_step(pIter->pIdxIter);
219030          if( rc!=SQLITE_ROW ){
219031            rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
219032            pIter->bCleanup = 1;
219033            pIter->zIdx = 0;
219034          }else{
219035            pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
219036            pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
219037            pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
219038            rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
219039          }
219040        }
219041      }
219042    }
219043  }
219044
219045  if( rc!=SQLITE_OK ){
219046    rbuObjIterFinalize(pIter);
219047    p->rc = rc;
219048  }
219049  return rc;
219050}
219051
219052
219053/*
219054** The implementation of the rbu_target_name() SQL function. This function
219055** accepts one or two arguments. The first argument is the name of a table -
219056** the name of a table in the RBU database.  The second, if it is present, is 1
219057** for a view or 0 for a table.
219058**
219059** For a non-vacuum RBU handle, if the table name matches the pattern:
219060**
219061**     data[0-9]_<name>
219062**
219063** where <name> is any sequence of 1 or more characters, <name> is returned.
219064** Otherwise, if the only argument does not match the above pattern, an SQL
219065** NULL is returned.
219066**
219067**     "data_t1"     -> "t1"
219068**     "data0123_t2" -> "t2"
219069**     "dataAB_t3"   -> NULL
219070**
219071** For an rbu vacuum handle, a copy of the first argument is returned if
219072** the second argument is either missing or 0 (not a view).
219073*/
219074static void rbuTargetNameFunc(
219075  sqlite3_context *pCtx,
219076  int argc,
219077  sqlite3_value **argv
219078){
219079  sqlite3rbu *p = sqlite3_user_data(pCtx);
219080  const char *zIn;
219081  assert( argc==1 || argc==2 );
219082
219083  zIn = (const char*)sqlite3_value_text(argv[0]);
219084  if( zIn ){
219085    if( rbuIsVacuum(p) ){
219086      assert( argc==2 || argc==1 );
219087      if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
219088        sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
219089      }
219090    }else{
219091      if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
219092        int i;
219093        for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
219094        if( zIn[i]=='_' && zIn[i+1] ){
219095          sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
219096        }
219097      }
219098    }
219099  }
219100}
219101
219102/*
219103** Initialize the iterator structure passed as the second argument.
219104**
219105** If no error occurs, SQLITE_OK is returned and the iterator is left
219106** pointing to the first entry. Otherwise, an error code and message is
219107** left in the RBU handle passed as the first argument. A copy of the
219108** error code is returned.
219109*/
219110static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
219111  int rc;
219112  memset(pIter, 0, sizeof(RbuObjIter));
219113
219114  rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
219115    sqlite3_mprintf(
219116      "SELECT rbu_target_name(name, type='view') AS target, name "
219117      "FROM sqlite_schema "
219118      "WHERE type IN ('table', 'view') AND target IS NOT NULL "
219119      " %s "
219120      "ORDER BY name"
219121  , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
219122
219123  if( rc==SQLITE_OK ){
219124    rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
219125        "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
219126        "  FROM main.sqlite_schema "
219127        "  WHERE type='index' AND tbl_name = ?"
219128    );
219129  }
219130
219131  pIter->bCleanup = 1;
219132  p->rc = rc;
219133  return rbuObjIterNext(p, pIter);
219134}
219135
219136/*
219137** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
219138** an error code is stored in the RBU handle passed as the first argument.
219139**
219140** If an error has already occurred (p->rc is already set to something other
219141** than SQLITE_OK), then this function returns NULL without modifying the
219142** stored error code. In this case it still calls sqlite3_free() on any
219143** printf() parameters associated with %z conversions.
219144*/
219145static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
219146  char *zSql = 0;
219147  va_list ap;
219148  va_start(ap, zFmt);
219149  zSql = sqlite3_vmprintf(zFmt, ap);
219150  if( p->rc==SQLITE_OK ){
219151    if( zSql==0 ) p->rc = SQLITE_NOMEM;
219152  }else{
219153    sqlite3_free(zSql);
219154    zSql = 0;
219155  }
219156  va_end(ap);
219157  return zSql;
219158}
219159
219160/*
219161** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
219162** arguments are the usual subsitution values. This function performs
219163** the printf() style substitutions and executes the result as an SQL
219164** statement on the RBU handles database.
219165**
219166** If an error occurs, an error code and error message is stored in the
219167** RBU handle. If an error has already occurred when this function is
219168** called, it is a no-op.
219169*/
219170static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
219171  va_list ap;
219172  char *zSql;
219173  va_start(ap, zFmt);
219174  zSql = sqlite3_vmprintf(zFmt, ap);
219175  if( p->rc==SQLITE_OK ){
219176    if( zSql==0 ){
219177      p->rc = SQLITE_NOMEM;
219178    }else{
219179      p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
219180    }
219181  }
219182  sqlite3_free(zSql);
219183  va_end(ap);
219184  return p->rc;
219185}
219186
219187/*
219188** Attempt to allocate and return a pointer to a zeroed block of nByte
219189** bytes.
219190**
219191** If an error (i.e. an OOM condition) occurs, return NULL and leave an
219192** error code in the rbu handle passed as the first argument. Or, if an
219193** error has already occurred when this function is called, return NULL
219194** immediately without attempting the allocation or modifying the stored
219195** error code.
219196*/
219197static void *rbuMalloc(sqlite3rbu *p, sqlite3_int64 nByte){
219198  void *pRet = 0;
219199  if( p->rc==SQLITE_OK ){
219200    assert( nByte>0 );
219201    pRet = sqlite3_malloc64(nByte);
219202    if( pRet==0 ){
219203      p->rc = SQLITE_NOMEM;
219204    }else{
219205      memset(pRet, 0, nByte);
219206    }
219207  }
219208  return pRet;
219209}
219210
219211
219212/*
219213** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
219214** there is room for at least nCol elements. If an OOM occurs, store an
219215** error code in the RBU handle passed as the first argument.
219216*/
219217static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
219218  sqlite3_int64 nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
219219  char **azNew;
219220
219221  azNew = (char**)rbuMalloc(p, nByte);
219222  if( azNew ){
219223    pIter->azTblCol = azNew;
219224    pIter->azTblType = &azNew[nCol];
219225    pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
219226    pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
219227    pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
219228    pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
219229  }
219230}
219231
219232/*
219233** The first argument must be a nul-terminated string. This function
219234** returns a copy of the string in memory obtained from sqlite3_malloc().
219235** It is the responsibility of the caller to eventually free this memory
219236** using sqlite3_free().
219237**
219238** If an OOM condition is encountered when attempting to allocate memory,
219239** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
219240** if the allocation succeeds, (*pRc) is left unchanged.
219241*/
219242static char *rbuStrndup(const char *zStr, int *pRc){
219243  char *zRet = 0;
219244
219245  if( *pRc==SQLITE_OK ){
219246    if( zStr ){
219247      size_t nCopy = strlen(zStr) + 1;
219248      zRet = (char*)sqlite3_malloc64(nCopy);
219249      if( zRet ){
219250        memcpy(zRet, zStr, nCopy);
219251      }else{
219252        *pRc = SQLITE_NOMEM;
219253      }
219254    }
219255  }
219256
219257  return zRet;
219258}
219259
219260/*
219261** Finalize the statement passed as the second argument.
219262**
219263** If the sqlite3_finalize() call indicates that an error occurs, and the
219264** rbu handle error code is not already set, set the error code and error
219265** message accordingly.
219266*/
219267static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
219268  sqlite3 *db = sqlite3_db_handle(pStmt);
219269  int rc = sqlite3_finalize(pStmt);
219270  if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
219271    p->rc = rc;
219272    p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
219273  }
219274}
219275
219276/* Determine the type of a table.
219277**
219278**   peType is of type (int*), a pointer to an output parameter of type
219279**   (int). This call sets the output parameter as follows, depending
219280**   on the type of the table specified by parameters dbName and zTbl.
219281**
219282**     RBU_PK_NOTABLE:       No such table.
219283**     RBU_PK_NONE:          Table has an implicit rowid.
219284**     RBU_PK_IPK:           Table has an explicit IPK column.
219285**     RBU_PK_EXTERNAL:      Table has an external PK index.
219286**     RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
219287**     RBU_PK_VTAB:          Table is a virtual table.
219288**
219289**   Argument *piPk is also of type (int*), and also points to an output
219290**   parameter. Unless the table has an external primary key index
219291**   (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
219292**   if the table does have an external primary key index, then *piPk
219293**   is set to the root page number of the primary key index before
219294**   returning.
219295**
219296** ALGORITHM:
219297**
219298**   if( no entry exists in sqlite_schema ){
219299**     return RBU_PK_NOTABLE
219300**   }else if( sql for the entry starts with "CREATE VIRTUAL" ){
219301**     return RBU_PK_VTAB
219302**   }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
219303**     if( the index that is the pk exists in sqlite_schema ){
219304**       *piPK = rootpage of that index.
219305**       return RBU_PK_EXTERNAL
219306**     }else{
219307**       return RBU_PK_WITHOUT_ROWID
219308**     }
219309**   }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
219310**     return RBU_PK_IPK
219311**   }else{
219312**     return RBU_PK_NONE
219313**   }
219314*/
219315static void rbuTableType(
219316  sqlite3rbu *p,
219317  const char *zTab,
219318  int *peType,
219319  int *piTnum,
219320  int *piPk
219321){
219322  /*
219323  ** 0) SELECT count(*) FROM sqlite_schema where name=%Q AND IsVirtual(%Q)
219324  ** 1) PRAGMA index_list = ?
219325  ** 2) SELECT count(*) FROM sqlite_schema where name=%Q
219326  ** 3) PRAGMA table_info = ?
219327  */
219328  sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
219329
219330  *peType = RBU_PK_NOTABLE;
219331  *piPk = 0;
219332
219333  assert( p->rc==SQLITE_OK );
219334  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
219335    sqlite3_mprintf(
219336          "SELECT "
219337          " (sql COLLATE nocase BETWEEN 'CREATE VIRTUAL' AND 'CREATE VIRTUAM'),"
219338          " rootpage"
219339          "  FROM sqlite_schema"
219340          " WHERE name=%Q", zTab
219341  ));
219342  if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
219343    /* Either an error, or no such table. */
219344    goto rbuTableType_end;
219345  }
219346  if( sqlite3_column_int(aStmt[0], 0) ){
219347    *peType = RBU_PK_VTAB;                     /* virtual table */
219348    goto rbuTableType_end;
219349  }
219350  *piTnum = sqlite3_column_int(aStmt[0], 1);
219351
219352  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
219353    sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
219354  );
219355  if( p->rc ) goto rbuTableType_end;
219356  while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
219357    const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
219358    const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
219359    if( zOrig && zIdx && zOrig[0]=='p' ){
219360      p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
219361          sqlite3_mprintf(
219362            "SELECT rootpage FROM sqlite_schema WHERE name = %Q", zIdx
219363      ));
219364      if( p->rc==SQLITE_OK ){
219365        if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
219366          *piPk = sqlite3_column_int(aStmt[2], 0);
219367          *peType = RBU_PK_EXTERNAL;
219368        }else{
219369          *peType = RBU_PK_WITHOUT_ROWID;
219370        }
219371      }
219372      goto rbuTableType_end;
219373    }
219374  }
219375
219376  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
219377    sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
219378  );
219379  if( p->rc==SQLITE_OK ){
219380    while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
219381      if( sqlite3_column_int(aStmt[3],5)>0 ){
219382        *peType = RBU_PK_IPK;                /* explicit IPK column */
219383        goto rbuTableType_end;
219384      }
219385    }
219386    *peType = RBU_PK_NONE;
219387  }
219388
219389rbuTableType_end: {
219390    unsigned int i;
219391    for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
219392      rbuFinalize(p, aStmt[i]);
219393    }
219394  }
219395}
219396
219397/*
219398** This is a helper function for rbuObjIterCacheTableInfo(). It populates
219399** the pIter->abIndexed[] array.
219400*/
219401static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
219402  sqlite3_stmt *pList = 0;
219403  int bIndex = 0;
219404
219405  if( p->rc==SQLITE_OK ){
219406    memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
219407    p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
219408        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
219409    );
219410  }
219411
219412  pIter->nIndex = 0;
219413  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
219414    const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
219415    int bPartial = sqlite3_column_int(pList, 4);
219416    sqlite3_stmt *pXInfo = 0;
219417    if( zIdx==0 ) break;
219418    if( bPartial ){
219419      memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);
219420    }
219421    p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
219422        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
219423    );
219424    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
219425      int iCid = sqlite3_column_int(pXInfo, 1);
219426      if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
219427      if( iCid==-2 ){
219428        memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);
219429      }
219430    }
219431    rbuFinalize(p, pXInfo);
219432    bIndex = 1;
219433    pIter->nIndex++;
219434  }
219435
219436  if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
219437    /* "PRAGMA index_list" includes the main PK b-tree */
219438    pIter->nIndex--;
219439  }
219440
219441  rbuFinalize(p, pList);
219442  if( bIndex==0 ) pIter->abIndexed = 0;
219443}
219444
219445
219446/*
219447** If they are not already populated, populate the pIter->azTblCol[],
219448** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
219449** the table (not index) that the iterator currently points to.
219450**
219451** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
219452** an error does occur, an error code and error message are also left in
219453** the RBU handle.
219454*/
219455static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
219456  if( pIter->azTblCol==0 ){
219457    sqlite3_stmt *pStmt = 0;
219458    int nCol = 0;
219459    int i;                        /* for() loop iterator variable */
219460    int bRbuRowid = 0;            /* If input table has column "rbu_rowid" */
219461    int iOrder = 0;
219462    int iTnum = 0;
219463
219464    /* Figure out the type of table this step will deal with. */
219465    assert( pIter->eType==0 );
219466    rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
219467    if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
219468      p->rc = SQLITE_ERROR;
219469      p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
219470    }
219471    if( p->rc ) return p->rc;
219472    if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
219473
219474    assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
219475         || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
219476         || pIter->eType==RBU_PK_VTAB
219477    );
219478
219479    /* Populate the azTblCol[] and nTblCol variables based on the columns
219480    ** of the input table. Ignore any input table columns that begin with
219481    ** "rbu_".  */
219482    p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
219483        sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
219484    );
219485    if( p->rc==SQLITE_OK ){
219486      nCol = sqlite3_column_count(pStmt);
219487      rbuAllocateIterArrays(p, pIter, nCol);
219488    }
219489    for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
219490      const char *zName = (const char*)sqlite3_column_name(pStmt, i);
219491      if( sqlite3_strnicmp("rbu_", zName, 4) ){
219492        char *zCopy = rbuStrndup(zName, &p->rc);
219493        pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
219494        pIter->azTblCol[pIter->nTblCol++] = zCopy;
219495      }
219496      else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
219497        bRbuRowid = 1;
219498      }
219499    }
219500    sqlite3_finalize(pStmt);
219501    pStmt = 0;
219502
219503    if( p->rc==SQLITE_OK
219504     && rbuIsVacuum(p)==0
219505     && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
219506    ){
219507      p->rc = SQLITE_ERROR;
219508      p->zErrmsg = sqlite3_mprintf(
219509          "table %q %s rbu_rowid column", pIter->zDataTbl,
219510          (bRbuRowid ? "may not have" : "requires")
219511      );
219512    }
219513
219514    /* Check that all non-HIDDEN columns in the destination table are also
219515    ** present in the input table. Populate the abTblPk[], azTblType[] and
219516    ** aiTblOrder[] arrays at the same time.  */
219517    if( p->rc==SQLITE_OK ){
219518      p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
219519          sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
219520      );
219521    }
219522    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
219523      const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
219524      if( zName==0 ) break;  /* An OOM - finalize() below returns S_NOMEM */
219525      for(i=iOrder; i<pIter->nTblCol; i++){
219526        if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
219527      }
219528      if( i==pIter->nTblCol ){
219529        p->rc = SQLITE_ERROR;
219530        p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
219531            pIter->zDataTbl, zName
219532        );
219533      }else{
219534        int iPk = sqlite3_column_int(pStmt, 5);
219535        int bNotNull = sqlite3_column_int(pStmt, 3);
219536        const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
219537
219538        if( i!=iOrder ){
219539          SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
219540          SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
219541        }
219542
219543        pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
219544        assert( iPk>=0 );
219545        pIter->abTblPk[iOrder] = (u8)iPk;
219546        pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
219547        iOrder++;
219548      }
219549    }
219550
219551    rbuFinalize(p, pStmt);
219552    rbuObjIterCacheIndexedCols(p, pIter);
219553    assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
219554    assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
219555  }
219556
219557  return p->rc;
219558}
219559
219560/*
219561** This function constructs and returns a pointer to a nul-terminated
219562** string containing some SQL clause or list based on one or more of the
219563** column names currently stored in the pIter->azTblCol[] array.
219564*/
219565static char *rbuObjIterGetCollist(
219566  sqlite3rbu *p,                  /* RBU object */
219567  RbuObjIter *pIter               /* Object iterator for column names */
219568){
219569  char *zList = 0;
219570  const char *zSep = "";
219571  int i;
219572  for(i=0; i<pIter->nTblCol; i++){
219573    const char *z = pIter->azTblCol[i];
219574    zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
219575    zSep = ", ";
219576  }
219577  return zList;
219578}
219579
219580/*
219581** Return a comma separated list of the quoted PRIMARY KEY column names,
219582** in order, for the current table. Before each column name, add the text
219583** zPre. After each column name, add the zPost text. Use zSeparator as
219584** the separator text (usually ", ").
219585*/
219586static char *rbuObjIterGetPkList(
219587  sqlite3rbu *p,                  /* RBU object */
219588  RbuObjIter *pIter,              /* Object iterator for column names */
219589  const char *zPre,               /* Before each quoted column name */
219590  const char *zSeparator,         /* Separator to use between columns */
219591  const char *zPost               /* After each quoted column name */
219592){
219593  int iPk = 1;
219594  char *zRet = 0;
219595  const char *zSep = "";
219596  while( 1 ){
219597    int i;
219598    for(i=0; i<pIter->nTblCol; i++){
219599      if( (int)pIter->abTblPk[i]==iPk ){
219600        const char *zCol = pIter->azTblCol[i];
219601        zRet = rbuMPrintf(p, "%z%s%s\"%w\"%s", zRet, zSep, zPre, zCol, zPost);
219602        zSep = zSeparator;
219603        break;
219604      }
219605    }
219606    if( i==pIter->nTblCol ) break;
219607    iPk++;
219608  }
219609  return zRet;
219610}
219611
219612/*
219613** This function is called as part of restarting an RBU vacuum within
219614** stage 1 of the process (while the *-oal file is being built) while
219615** updating a table (not an index). The table may be a rowid table or
219616** a WITHOUT ROWID table. It queries the target database to find the
219617** largest key that has already been written to the target table and
219618** constructs a WHERE clause that can be used to extract the remaining
219619** rows from the source table. For a rowid table, the WHERE clause
219620** is of the form:
219621**
219622**     "WHERE _rowid_ > ?"
219623**
219624** and for WITHOUT ROWID tables:
219625**
219626**     "WHERE (key1, key2) > (?, ?)"
219627**
219628** Instead of "?" placeholders, the actual WHERE clauses created by
219629** this function contain literal SQL values.
219630*/
219631static char *rbuVacuumTableStart(
219632  sqlite3rbu *p,                  /* RBU handle */
219633  RbuObjIter *pIter,              /* RBU iterator object */
219634  int bRowid,                     /* True for a rowid table */
219635  const char *zWrite              /* Target table name prefix */
219636){
219637  sqlite3_stmt *pMax = 0;
219638  char *zRet = 0;
219639  if( bRowid ){
219640    p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
219641        sqlite3_mprintf(
219642          "SELECT max(_rowid_) FROM \"%s%w\"", zWrite, pIter->zTbl
219643        )
219644    );
219645    if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
219646      sqlite3_int64 iMax = sqlite3_column_int64(pMax, 0);
219647      zRet = rbuMPrintf(p, " WHERE _rowid_ > %lld ", iMax);
219648    }
219649    rbuFinalize(p, pMax);
219650  }else{
219651    char *zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", " DESC");
219652    char *zSelect = rbuObjIterGetPkList(p, pIter, "quote(", "||','||", ")");
219653    char *zList = rbuObjIterGetPkList(p, pIter, "", ", ", "");
219654
219655    if( p->rc==SQLITE_OK ){
219656      p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
219657          sqlite3_mprintf(
219658            "SELECT %s FROM \"%s%w\" ORDER BY %s LIMIT 1",
219659                zSelect, zWrite, pIter->zTbl, zOrder
219660          )
219661      );
219662      if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
219663        const char *zVal = (const char*)sqlite3_column_text(pMax, 0);
219664        zRet = rbuMPrintf(p, " WHERE (%s) > (%s) ", zList, zVal);
219665      }
219666      rbuFinalize(p, pMax);
219667    }
219668
219669    sqlite3_free(zOrder);
219670    sqlite3_free(zSelect);
219671    sqlite3_free(zList);
219672  }
219673  return zRet;
219674}
219675
219676/*
219677** This function is called as part of restating an RBU vacuum when the
219678** current operation is writing content to an index. If possible, it
219679** queries the target index b-tree for the largest key already written to
219680** it, then composes and returns an expression that can be used in a WHERE
219681** clause to select the remaining required rows from the source table.
219682** It is only possible to return such an expression if:
219683**
219684**   * The index contains no DESC columns, and
219685**   * The last key written to the index before the operation was
219686**     suspended does not contain any NULL values.
219687**
219688** The expression is of the form:
219689**
219690**   (index-field1, index-field2, ...) > (?, ?, ...)
219691**
219692** except that the "?" placeholders are replaced with literal values.
219693**
219694** If the expression cannot be created, NULL is returned. In this case,
219695** the caller has to use an OFFSET clause to extract only the required
219696** rows from the sourct table, just as it does for an RBU update operation.
219697*/
219698static char *rbuVacuumIndexStart(
219699  sqlite3rbu *p,                  /* RBU handle */
219700  RbuObjIter *pIter               /* RBU iterator object */
219701){
219702  char *zOrder = 0;
219703  char *zLhs = 0;
219704  char *zSelect = 0;
219705  char *zVector = 0;
219706  char *zRet = 0;
219707  int bFailed = 0;
219708  const char *zSep = "";
219709  int iCol = 0;
219710  sqlite3_stmt *pXInfo = 0;
219711
219712  p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
219713      sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
219714  );
219715  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
219716    int iCid = sqlite3_column_int(pXInfo, 1);
219717    const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
219718    const char *zCol;
219719    if( sqlite3_column_int(pXInfo, 3) ){
219720      bFailed = 1;
219721      break;
219722    }
219723
219724    if( iCid<0 ){
219725      if( pIter->eType==RBU_PK_IPK ){
219726        int i;
219727        for(i=0; pIter->abTblPk[i]==0; i++);
219728        assert( i<pIter->nTblCol );
219729        zCol = pIter->azTblCol[i];
219730      }else{
219731        zCol = "_rowid_";
219732      }
219733    }else{
219734      zCol = pIter->azTblCol[iCid];
219735    }
219736
219737    zLhs = rbuMPrintf(p, "%z%s \"%w\" COLLATE %Q",
219738        zLhs, zSep, zCol, zCollate
219739        );
219740    zOrder = rbuMPrintf(p, "%z%s \"rbu_imp_%d%w\" COLLATE %Q DESC",
219741        zOrder, zSep, iCol, zCol, zCollate
219742        );
219743    zSelect = rbuMPrintf(p, "%z%s quote(\"rbu_imp_%d%w\")",
219744        zSelect, zSep, iCol, zCol
219745        );
219746    zSep = ", ";
219747    iCol++;
219748  }
219749  rbuFinalize(p, pXInfo);
219750  if( bFailed ) goto index_start_out;
219751
219752  if( p->rc==SQLITE_OK ){
219753    sqlite3_stmt *pSel = 0;
219754
219755    p->rc = prepareFreeAndCollectError(p->dbMain, &pSel, &p->zErrmsg,
219756        sqlite3_mprintf("SELECT %s FROM \"rbu_imp_%w\" ORDER BY %s LIMIT 1",
219757          zSelect, pIter->zTbl, zOrder
219758        )
219759    );
219760    if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSel) ){
219761      zSep = "";
219762      for(iCol=0; iCol<pIter->nCol; iCol++){
219763        const char *zQuoted = (const char*)sqlite3_column_text(pSel, iCol);
219764        if( zQuoted==0 ){
219765          p->rc = SQLITE_NOMEM;
219766        }else if( zQuoted[0]=='N' ){
219767          bFailed = 1;
219768          break;
219769        }
219770        zVector = rbuMPrintf(p, "%z%s%s", zVector, zSep, zQuoted);
219771        zSep = ", ";
219772      }
219773
219774      if( !bFailed ){
219775        zRet = rbuMPrintf(p, "(%s) > (%s)", zLhs, zVector);
219776      }
219777    }
219778    rbuFinalize(p, pSel);
219779  }
219780
219781 index_start_out:
219782  sqlite3_free(zOrder);
219783  sqlite3_free(zSelect);
219784  sqlite3_free(zVector);
219785  sqlite3_free(zLhs);
219786  return zRet;
219787}
219788
219789/*
219790** This function is used to create a SELECT list (the list of SQL
219791** expressions that follows a SELECT keyword) for a SELECT statement
219792** used to read from an data_xxx or rbu_tmp_xxx table while updating the
219793** index object currently indicated by the iterator object passed as the
219794** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
219795** to obtain the required information.
219796**
219797** If the index is of the following form:
219798**
219799**   CREATE INDEX i1 ON t1(c, b COLLATE nocase);
219800**
219801** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
219802** "ipk", the returned string is:
219803**
219804**   "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
219805**
219806** As well as the returned string, three other malloc'd strings are
219807** returned via output parameters. As follows:
219808**
219809**   pzImposterCols: ...
219810**   pzImposterPk: ...
219811**   pzWhere: ...
219812*/
219813static char *rbuObjIterGetIndexCols(
219814  sqlite3rbu *p,                  /* RBU object */
219815  RbuObjIter *pIter,              /* Object iterator for column names */
219816  char **pzImposterCols,          /* OUT: Columns for imposter table */
219817  char **pzImposterPk,            /* OUT: Imposter PK clause */
219818  char **pzWhere,                 /* OUT: WHERE clause */
219819  int *pnBind                     /* OUT: Trbul number of columns */
219820){
219821  int rc = p->rc;                 /* Error code */
219822  int rc2;                        /* sqlite3_finalize() return code */
219823  char *zRet = 0;                 /* String to return */
219824  char *zImpCols = 0;             /* String to return via *pzImposterCols */
219825  char *zImpPK = 0;               /* String to return via *pzImposterPK */
219826  char *zWhere = 0;               /* String to return via *pzWhere */
219827  int nBind = 0;                  /* Value to return via *pnBind */
219828  const char *zCom = "";          /* Set to ", " later on */
219829  const char *zAnd = "";          /* Set to " AND " later on */
219830  sqlite3_stmt *pXInfo = 0;       /* PRAGMA index_xinfo = ? */
219831
219832  if( rc==SQLITE_OK ){
219833    assert( p->zErrmsg==0 );
219834    rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
219835        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
219836    );
219837  }
219838
219839  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
219840    int iCid = sqlite3_column_int(pXInfo, 1);
219841    int bDesc = sqlite3_column_int(pXInfo, 3);
219842    const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
219843    const char *zCol = 0;
219844    const char *zType;
219845
219846    if( iCid==-2 ){
219847      int iSeq = sqlite3_column_int(pXInfo, 0);
219848      zRet = sqlite3_mprintf("%z%s(%.*s) COLLATE %Q", zRet, zCom,
219849          pIter->aIdxCol[iSeq].nSpan, pIter->aIdxCol[iSeq].zSpan, zCollate
219850      );
219851      zType = "";
219852    }else {
219853      if( iCid<0 ){
219854        /* An integer primary key. If the table has an explicit IPK, use
219855        ** its name. Otherwise, use "rbu_rowid".  */
219856        if( pIter->eType==RBU_PK_IPK ){
219857          int i;
219858          for(i=0; pIter->abTblPk[i]==0; i++);
219859          assert( i<pIter->nTblCol );
219860          zCol = pIter->azTblCol[i];
219861        }else if( rbuIsVacuum(p) ){
219862          zCol = "_rowid_";
219863        }else{
219864          zCol = "rbu_rowid";
219865        }
219866        zType = "INTEGER";
219867      }else{
219868        zCol = pIter->azTblCol[iCid];
219869        zType = pIter->azTblType[iCid];
219870      }
219871      zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom,zCol,zCollate);
219872    }
219873
219874    if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
219875      const char *zOrder = (bDesc ? " DESC" : "");
219876      zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
219877          zImpPK, zCom, nBind, zCol, zOrder
219878      );
219879    }
219880    zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
219881        zImpCols, zCom, nBind, zCol, zType, zCollate
219882    );
219883    zWhere = sqlite3_mprintf(
219884        "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
219885    );
219886    if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
219887    zCom = ", ";
219888    zAnd = " AND ";
219889    nBind++;
219890  }
219891
219892  rc2 = sqlite3_finalize(pXInfo);
219893  if( rc==SQLITE_OK ) rc = rc2;
219894
219895  if( rc!=SQLITE_OK ){
219896    sqlite3_free(zRet);
219897    sqlite3_free(zImpCols);
219898    sqlite3_free(zImpPK);
219899    sqlite3_free(zWhere);
219900    zRet = 0;
219901    zImpCols = 0;
219902    zImpPK = 0;
219903    zWhere = 0;
219904    p->rc = rc;
219905  }
219906
219907  *pzImposterCols = zImpCols;
219908  *pzImposterPk = zImpPK;
219909  *pzWhere = zWhere;
219910  *pnBind = nBind;
219911  return zRet;
219912}
219913
219914/*
219915** Assuming the current table columns are "a", "b" and "c", and the zObj
219916** paramter is passed "old", return a string of the form:
219917**
219918**     "old.a, old.b, old.b"
219919**
219920** With the column names escaped.
219921**
219922** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
219923** the text ", old._rowid_" to the returned value.
219924*/
219925static char *rbuObjIterGetOldlist(
219926  sqlite3rbu *p,
219927  RbuObjIter *pIter,
219928  const char *zObj
219929){
219930  char *zList = 0;
219931  if( p->rc==SQLITE_OK && pIter->abIndexed ){
219932    const char *zS = "";
219933    int i;
219934    for(i=0; i<pIter->nTblCol; i++){
219935      if( pIter->abIndexed[i] ){
219936        const char *zCol = pIter->azTblCol[i];
219937        zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
219938      }else{
219939        zList = sqlite3_mprintf("%z%sNULL", zList, zS);
219940      }
219941      zS = ", ";
219942      if( zList==0 ){
219943        p->rc = SQLITE_NOMEM;
219944        break;
219945      }
219946    }
219947
219948    /* For a table with implicit rowids, append "old._rowid_" to the list. */
219949    if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
219950      zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
219951    }
219952  }
219953  return zList;
219954}
219955
219956/*
219957** Return an expression that can be used in a WHERE clause to match the
219958** primary key of the current table. For example, if the table is:
219959**
219960**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
219961**
219962** Return the string:
219963**
219964**   "b = ?1 AND c = ?2"
219965*/
219966static char *rbuObjIterGetWhere(
219967  sqlite3rbu *p,
219968  RbuObjIter *pIter
219969){
219970  char *zList = 0;
219971  if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
219972    zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
219973  }else if( pIter->eType==RBU_PK_EXTERNAL ){
219974    const char *zSep = "";
219975    int i;
219976    for(i=0; i<pIter->nTblCol; i++){
219977      if( pIter->abTblPk[i] ){
219978        zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
219979        zSep = " AND ";
219980      }
219981    }
219982    zList = rbuMPrintf(p,
219983        "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
219984    );
219985
219986  }else{
219987    const char *zSep = "";
219988    int i;
219989    for(i=0; i<pIter->nTblCol; i++){
219990      if( pIter->abTblPk[i] ){
219991        const char *zCol = pIter->azTblCol[i];
219992        zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
219993        zSep = " AND ";
219994      }
219995    }
219996  }
219997  return zList;
219998}
219999
220000/*
220001** The SELECT statement iterating through the keys for the current object
220002** (p->objiter.pSelect) currently points to a valid row. However, there
220003** is something wrong with the rbu_control value in the rbu_control value
220004** stored in the (p->nCol+1)'th column. Set the error code and error message
220005** of the RBU handle to something reflecting this.
220006*/
220007static void rbuBadControlError(sqlite3rbu *p){
220008  p->rc = SQLITE_ERROR;
220009  p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
220010}
220011
220012
220013/*
220014** Return a nul-terminated string containing the comma separated list of
220015** assignments that should be included following the "SET" keyword of
220016** an UPDATE statement used to update the table object that the iterator
220017** passed as the second argument currently points to if the rbu_control
220018** column of the data_xxx table entry is set to zMask.
220019**
220020** The memory for the returned string is obtained from sqlite3_malloc().
220021** It is the responsibility of the caller to eventually free it using
220022** sqlite3_free().
220023**
220024** If an OOM error is encountered when allocating space for the new
220025** string, an error code is left in the rbu handle passed as the first
220026** argument and NULL is returned. Or, if an error has already occurred
220027** when this function is called, NULL is returned immediately, without
220028** attempting the allocation or modifying the stored error code.
220029*/
220030static char *rbuObjIterGetSetlist(
220031  sqlite3rbu *p,
220032  RbuObjIter *pIter,
220033  const char *zMask
220034){
220035  char *zList = 0;
220036  if( p->rc==SQLITE_OK ){
220037    int i;
220038
220039    if( (int)strlen(zMask)!=pIter->nTblCol ){
220040      rbuBadControlError(p);
220041    }else{
220042      const char *zSep = "";
220043      for(i=0; i<pIter->nTblCol; i++){
220044        char c = zMask[pIter->aiSrcOrder[i]];
220045        if( c=='x' ){
220046          zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
220047              zList, zSep, pIter->azTblCol[i], i+1
220048          );
220049          zSep = ", ";
220050        }
220051        else if( c=='d' ){
220052          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
220053              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
220054          );
220055          zSep = ", ";
220056        }
220057        else if( c=='f' ){
220058          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
220059              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
220060          );
220061          zSep = ", ";
220062        }
220063      }
220064    }
220065  }
220066  return zList;
220067}
220068
220069/*
220070** Return a nul-terminated string consisting of nByte comma separated
220071** "?" expressions. For example, if nByte is 3, return a pointer to
220072** a buffer containing the string "?,?,?".
220073**
220074** The memory for the returned string is obtained from sqlite3_malloc().
220075** It is the responsibility of the caller to eventually free it using
220076** sqlite3_free().
220077**
220078** If an OOM error is encountered when allocating space for the new
220079** string, an error code is left in the rbu handle passed as the first
220080** argument and NULL is returned. Or, if an error has already occurred
220081** when this function is called, NULL is returned immediately, without
220082** attempting the allocation or modifying the stored error code.
220083*/
220084static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
220085  char *zRet = 0;
220086  sqlite3_int64 nByte = 2*(sqlite3_int64)nBind + 1;
220087
220088  zRet = (char*)rbuMalloc(p, nByte);
220089  if( zRet ){
220090    int i;
220091    for(i=0; i<nBind; i++){
220092      zRet[i*2] = '?';
220093      zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
220094    }
220095  }
220096  return zRet;
220097}
220098
220099/*
220100** The iterator currently points to a table (not index) of type
220101** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
220102** declaration for the corresponding imposter table. For example,
220103** if the iterator points to a table created as:
220104**
220105**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
220106**
220107** this function returns:
220108**
220109**   PRIMARY KEY("b", "a" DESC)
220110*/
220111static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
220112  char *z = 0;
220113  assert( pIter->zIdx==0 );
220114  if( p->rc==SQLITE_OK ){
220115    const char *zSep = "PRIMARY KEY(";
220116    sqlite3_stmt *pXList = 0;     /* PRAGMA index_list = (pIter->zTbl) */
220117    sqlite3_stmt *pXInfo = 0;     /* PRAGMA index_xinfo = <pk-index> */
220118
220119    p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
220120        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
220121    );
220122    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
220123      const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
220124      if( zOrig && strcmp(zOrig, "pk")==0 ){
220125        const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
220126        if( zIdx ){
220127          p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
220128              sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
220129          );
220130        }
220131        break;
220132      }
220133    }
220134    rbuFinalize(p, pXList);
220135
220136    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
220137      if( sqlite3_column_int(pXInfo, 5) ){
220138        /* int iCid = sqlite3_column_int(pXInfo, 0); */
220139        const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
220140        const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
220141        z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
220142        zSep = ", ";
220143      }
220144    }
220145    z = rbuMPrintf(p, "%z)", z);
220146    rbuFinalize(p, pXInfo);
220147  }
220148  return z;
220149}
220150
220151/*
220152** This function creates the second imposter table used when writing to
220153** a table b-tree where the table has an external primary key. If the
220154** iterator passed as the second argument does not currently point to
220155** a table (not index) with an external primary key, this function is a
220156** no-op.
220157**
220158** Assuming the iterator does point to a table with an external PK, this
220159** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
220160** used to access that PK index. For example, if the target table is
220161** declared as follows:
220162**
220163**   CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
220164**
220165** then the imposter table schema is:
220166**
220167**   CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
220168**
220169*/
220170static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
220171  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
220172    int tnum = pIter->iPkTnum;    /* Root page of PK index */
220173    sqlite3_stmt *pQuery = 0;     /* SELECT name ... WHERE rootpage = $tnum */
220174    const char *zIdx = 0;         /* Name of PK index */
220175    sqlite3_stmt *pXInfo = 0;     /* PRAGMA main.index_xinfo = $zIdx */
220176    const char *zComma = "";
220177    char *zCols = 0;              /* Used to build up list of table cols */
220178    char *zPk = 0;                /* Used to build up table PK declaration */
220179
220180    /* Figure out the name of the primary key index for the current table.
220181    ** This is needed for the argument to "PRAGMA index_xinfo". Set
220182    ** zIdx to point to a nul-terminated string containing this name. */
220183    p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
220184        "SELECT name FROM sqlite_schema WHERE rootpage = ?"
220185    );
220186    if( p->rc==SQLITE_OK ){
220187      sqlite3_bind_int(pQuery, 1, tnum);
220188      if( SQLITE_ROW==sqlite3_step(pQuery) ){
220189        zIdx = (const char*)sqlite3_column_text(pQuery, 0);
220190      }
220191    }
220192    if( zIdx ){
220193      p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
220194          sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
220195      );
220196    }
220197    rbuFinalize(p, pQuery);
220198
220199    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
220200      int bKey = sqlite3_column_int(pXInfo, 5);
220201      if( bKey ){
220202        int iCid = sqlite3_column_int(pXInfo, 1);
220203        int bDesc = sqlite3_column_int(pXInfo, 3);
220204        const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
220205        zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma,
220206            iCid, pIter->azTblType[iCid], zCollate
220207        );
220208        zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
220209        zComma = ", ";
220210      }
220211    }
220212    zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
220213    rbuFinalize(p, pXInfo);
220214
220215    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
220216    rbuMPrintfExec(p, p->dbMain,
220217        "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
220218        zCols, zPk
220219    );
220220    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
220221  }
220222}
220223
220224/*
220225** If an error has already occurred when this function is called, it
220226** immediately returns zero (without doing any work). Or, if an error
220227** occurs during the execution of this function, it sets the error code
220228** in the sqlite3rbu object indicated by the first argument and returns
220229** zero.
220230**
220231** The iterator passed as the second argument is guaranteed to point to
220232** a table (not an index) when this function is called. This function
220233** attempts to create any imposter table required to write to the main
220234** table b-tree of the table before returning. Non-zero is returned if
220235** an imposter table are created, or zero otherwise.
220236**
220237** An imposter table is required in all cases except RBU_PK_VTAB. Only
220238** virtual tables are written to directly. The imposter table has the
220239** same schema as the actual target table (less any UNIQUE constraints).
220240** More precisely, the "same schema" means the same columns, types,
220241** collation sequences. For tables that do not have an external PRIMARY
220242** KEY, it also means the same PRIMARY KEY declaration.
220243*/
220244static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
220245  if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
220246    int tnum = pIter->iTnum;
220247    const char *zComma = "";
220248    char *zSql = 0;
220249    int iCol;
220250    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
220251
220252    for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
220253      const char *zPk = "";
220254      const char *zCol = pIter->azTblCol[iCol];
220255      const char *zColl = 0;
220256
220257      p->rc = sqlite3_table_column_metadata(
220258          p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
220259      );
220260
220261      if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
220262        /* If the target table column is an "INTEGER PRIMARY KEY", add
220263        ** "PRIMARY KEY" to the imposter table column declaration. */
220264        zPk = "PRIMARY KEY ";
220265      }
220266      zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s",
220267          zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
220268          (pIter->abNotNull[iCol] ? " NOT NULL" : "")
220269      );
220270      zComma = ", ";
220271    }
220272
220273    if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
220274      char *zPk = rbuWithoutRowidPK(p, pIter);
220275      if( zPk ){
220276        zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
220277      }
220278    }
220279
220280    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
220281    rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
220282        pIter->zTbl, zSql,
220283        (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
220284    );
220285    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
220286  }
220287}
220288
220289/*
220290** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
220291** Specifically a statement of the form:
220292**
220293**     INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
220294**
220295** The number of bound variables is equal to the number of columns in
220296** the target table, plus one (for the rbu_control column), plus one more
220297** (for the rbu_rowid column) if the target table is an implicit IPK or
220298** virtual table.
220299*/
220300static void rbuObjIterPrepareTmpInsert(
220301  sqlite3rbu *p,
220302  RbuObjIter *pIter,
220303  const char *zCollist,
220304  const char *zRbuRowid
220305){
220306  int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
220307  char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
220308  if( zBind ){
220309    assert( pIter->pTmpInsert==0 );
220310    p->rc = prepareFreeAndCollectError(
220311        p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
220312          "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
220313          p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
220314    ));
220315  }
220316}
220317
220318static void rbuTmpInsertFunc(
220319  sqlite3_context *pCtx,
220320  int nVal,
220321  sqlite3_value **apVal
220322){
220323  sqlite3rbu *p = sqlite3_user_data(pCtx);
220324  int rc = SQLITE_OK;
220325  int i;
220326
220327  assert( sqlite3_value_int(apVal[0])!=0
220328      || p->objiter.eType==RBU_PK_EXTERNAL
220329      || p->objiter.eType==RBU_PK_NONE
220330  );
220331  if( sqlite3_value_int(apVal[0])!=0 ){
220332    p->nPhaseOneStep += p->objiter.nIndex;
220333  }
220334
220335  for(i=0; rc==SQLITE_OK && i<nVal; i++){
220336    rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
220337  }
220338  if( rc==SQLITE_OK ){
220339    sqlite3_step(p->objiter.pTmpInsert);
220340    rc = sqlite3_reset(p->objiter.pTmpInsert);
220341  }
220342
220343  if( rc!=SQLITE_OK ){
220344    sqlite3_result_error_code(pCtx, rc);
220345  }
220346}
220347
220348static char *rbuObjIterGetIndexWhere(sqlite3rbu *p, RbuObjIter *pIter){
220349  sqlite3_stmt *pStmt = 0;
220350  int rc = p->rc;
220351  char *zRet = 0;
220352
220353  assert( pIter->zIdxSql==0 && pIter->nIdxCol==0 && pIter->aIdxCol==0 );
220354
220355  if( rc==SQLITE_OK ){
220356    rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
220357        "SELECT trim(sql) FROM sqlite_schema WHERE type='index' AND name=?"
220358    );
220359  }
220360  if( rc==SQLITE_OK ){
220361    int rc2;
220362    rc = sqlite3_bind_text(pStmt, 1, pIter->zIdx, -1, SQLITE_STATIC);
220363    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
220364      char *zSql = (char*)sqlite3_column_text(pStmt, 0);
220365      if( zSql ){
220366        pIter->zIdxSql = zSql = rbuStrndup(zSql, &rc);
220367      }
220368      if( zSql ){
220369        int nParen = 0;           /* Number of open parenthesis */
220370        int i;
220371        int iIdxCol = 0;
220372        int nIdxAlloc = 0;
220373        for(i=0; zSql[i]; i++){
220374          char c = zSql[i];
220375
220376          /* If necessary, grow the pIter->aIdxCol[] array */
220377          if( iIdxCol==nIdxAlloc ){
220378            RbuSpan *aIdxCol = (RbuSpan*)sqlite3_realloc(
220379                pIter->aIdxCol, (nIdxAlloc+16)*sizeof(RbuSpan)
220380            );
220381            if( aIdxCol==0 ){
220382              rc = SQLITE_NOMEM;
220383              break;
220384            }
220385            pIter->aIdxCol = aIdxCol;
220386            nIdxAlloc += 16;
220387          }
220388
220389          if( c=='(' ){
220390            if( nParen==0 ){
220391              assert( iIdxCol==0 );
220392              pIter->aIdxCol[0].zSpan = &zSql[i+1];
220393            }
220394            nParen++;
220395          }
220396          else if( c==')' ){
220397            nParen--;
220398            if( nParen==0 ){
220399              int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan;
220400              pIter->aIdxCol[iIdxCol++].nSpan = nSpan;
220401              i++;
220402              break;
220403            }
220404          }else if( c==',' && nParen==1 ){
220405            int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan;
220406            pIter->aIdxCol[iIdxCol++].nSpan = nSpan;
220407            pIter->aIdxCol[iIdxCol].zSpan = &zSql[i+1];
220408          }else if( c=='"' || c=='\'' || c=='`' ){
220409            for(i++; 1; i++){
220410              if( zSql[i]==c ){
220411                if( zSql[i+1]!=c ) break;
220412                i++;
220413              }
220414            }
220415          }else if( c=='[' ){
220416            for(i++; 1; i++){
220417              if( zSql[i]==']' ) break;
220418            }
220419          }else if( c=='-' && zSql[i+1]=='-' ){
220420            for(i=i+2; zSql[i] && zSql[i]!='\n'; i++);
220421            if( zSql[i]=='\0' ) break;
220422          }else if( c=='/' && zSql[i+1]=='*' ){
220423            for(i=i+2; zSql[i] && (zSql[i]!='*' || zSql[i+1]!='/'); i++);
220424            if( zSql[i]=='\0' ) break;
220425            i++;
220426          }
220427        }
220428        if( zSql[i] ){
220429          zRet = rbuStrndup(&zSql[i], &rc);
220430        }
220431        pIter->nIdxCol = iIdxCol;
220432      }
220433    }
220434
220435    rc2 = sqlite3_finalize(pStmt);
220436    if( rc==SQLITE_OK ) rc = rc2;
220437  }
220438
220439  p->rc = rc;
220440  return zRet;
220441}
220442
220443/*
220444** Ensure that the SQLite statement handles required to update the
220445** target database object currently indicated by the iterator passed
220446** as the second argument are available.
220447*/
220448static int rbuObjIterPrepareAll(
220449  sqlite3rbu *p,
220450  RbuObjIter *pIter,
220451  int nOffset                     /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
220452){
220453  assert( pIter->bCleanup==0 );
220454  if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
220455    const int tnum = pIter->iTnum;
220456    char *zCollist = 0;           /* List of indexed columns */
220457    char **pz = &p->zErrmsg;
220458    const char *zIdx = pIter->zIdx;
220459    char *zLimit = 0;
220460
220461    if( nOffset ){
220462      zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
220463      if( !zLimit ) p->rc = SQLITE_NOMEM;
220464    }
220465
220466    if( zIdx ){
220467      const char *zTbl = pIter->zTbl;
220468      char *zImposterCols = 0;    /* Columns for imposter table */
220469      char *zImposterPK = 0;      /* Primary key declaration for imposter */
220470      char *zWhere = 0;           /* WHERE clause on PK columns */
220471      char *zBind = 0;
220472      char *zPart = 0;
220473      int nBind = 0;
220474
220475      assert( pIter->eType!=RBU_PK_VTAB );
220476      zPart = rbuObjIterGetIndexWhere(p, pIter);
220477      zCollist = rbuObjIterGetIndexCols(
220478          p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
220479      );
220480      zBind = rbuObjIterGetBindlist(p, nBind);
220481
220482      /* Create the imposter table used to write to this index. */
220483      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
220484      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
220485      rbuMPrintfExec(p, p->dbMain,
220486          "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
220487          zTbl, zImposterCols, zImposterPK
220488      );
220489      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
220490
220491      /* Create the statement to insert index entries */
220492      pIter->nCol = nBind;
220493      if( p->rc==SQLITE_OK ){
220494        p->rc = prepareFreeAndCollectError(
220495            p->dbMain, &pIter->pInsert, &p->zErrmsg,
220496          sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
220497        );
220498      }
220499
220500      /* And to delete index entries */
220501      if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
220502        p->rc = prepareFreeAndCollectError(
220503            p->dbMain, &pIter->pDelete, &p->zErrmsg,
220504          sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
220505        );
220506      }
220507
220508      /* Create the SELECT statement to read keys in sorted order */
220509      if( p->rc==SQLITE_OK ){
220510        char *zSql;
220511        if( rbuIsVacuum(p) ){
220512          char *zStart = 0;
220513          if( nOffset ){
220514            zStart = rbuVacuumIndexStart(p, pIter);
220515            if( zStart ){
220516              sqlite3_free(zLimit);
220517              zLimit = 0;
220518            }
220519          }
220520
220521          zSql = sqlite3_mprintf(
220522              "SELECT %s, 0 AS rbu_control FROM '%q' %s %s %s ORDER BY %s%s",
220523              zCollist,
220524              pIter->zDataTbl,
220525              zPart,
220526              (zStart ? (zPart ? "AND" : "WHERE") : ""), zStart,
220527              zCollist, zLimit
220528          );
220529          sqlite3_free(zStart);
220530        }else
220531
220532        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
220533          zSql = sqlite3_mprintf(
220534              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s ORDER BY %s%s",
220535              zCollist, p->zStateDb, pIter->zDataTbl,
220536              zPart, zCollist, zLimit
220537          );
220538        }else{
220539          zSql = sqlite3_mprintf(
220540              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s "
220541              "UNION ALL "
220542              "SELECT %s, rbu_control FROM '%q' "
220543              "%s %s typeof(rbu_control)='integer' AND rbu_control!=1 "
220544              "ORDER BY %s%s",
220545              zCollist, p->zStateDb, pIter->zDataTbl, zPart,
220546              zCollist, pIter->zDataTbl,
220547              zPart,
220548              (zPart ? "AND" : "WHERE"),
220549              zCollist, zLimit
220550          );
220551        }
220552        if( p->rc==SQLITE_OK ){
220553          p->rc = prepareFreeAndCollectError(p->dbRbu,&pIter->pSelect,pz,zSql);
220554        }else{
220555          sqlite3_free(zSql);
220556        }
220557      }
220558
220559      sqlite3_free(zImposterCols);
220560      sqlite3_free(zImposterPK);
220561      sqlite3_free(zWhere);
220562      sqlite3_free(zBind);
220563      sqlite3_free(zPart);
220564    }else{
220565      int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
220566                    ||(pIter->eType==RBU_PK_NONE)
220567                    ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
220568      const char *zTbl = pIter->zTbl;       /* Table this step applies to */
220569      const char *zWrite;                   /* Imposter table name */
220570
220571      char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
220572      char *zWhere = rbuObjIterGetWhere(p, pIter);
220573      char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
220574      char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
220575
220576      zCollist = rbuObjIterGetCollist(p, pIter);
220577      pIter->nCol = pIter->nTblCol;
220578
220579      /* Create the imposter table or tables (if required). */
220580      rbuCreateImposterTable(p, pIter);
220581      rbuCreateImposterTable2(p, pIter);
220582      zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
220583
220584      /* Create the INSERT statement to write to the target PK b-tree */
220585      if( p->rc==SQLITE_OK ){
220586        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
220587            sqlite3_mprintf(
220588              "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
220589              zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
220590            )
220591        );
220592      }
220593
220594      /* Create the DELETE statement to write to the target PK b-tree.
220595      ** Because it only performs INSERT operations, this is not required for
220596      ** an rbu vacuum handle.  */
220597      if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
220598        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
220599            sqlite3_mprintf(
220600              "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
220601            )
220602        );
220603      }
220604
220605      if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
220606        const char *zRbuRowid = "";
220607        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
220608          zRbuRowid = ", rbu_rowid";
220609        }
220610
220611        /* Create the rbu_tmp_xxx table and the triggers to populate it. */
220612        rbuMPrintfExec(p, p->dbRbu,
220613            "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
220614            "SELECT *%s FROM '%q' WHERE 0;"
220615            , p->zStateDb, pIter->zDataTbl
220616            , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
220617            , pIter->zDataTbl
220618        );
220619
220620        rbuMPrintfExec(p, p->dbMain,
220621            "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
220622            "BEGIN "
220623            "  SELECT rbu_tmp_insert(3, %s);"
220624            "END;"
220625
220626            "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
220627            "BEGIN "
220628            "  SELECT rbu_tmp_insert(3, %s);"
220629            "END;"
220630
220631            "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
220632            "BEGIN "
220633            "  SELECT rbu_tmp_insert(4, %s);"
220634            "END;",
220635            zWrite, zTbl, zOldlist,
220636            zWrite, zTbl, zOldlist,
220637            zWrite, zTbl, zNewlist
220638        );
220639
220640        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
220641          rbuMPrintfExec(p, p->dbMain,
220642              "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
220643              "BEGIN "
220644              "  SELECT rbu_tmp_insert(0, %s);"
220645              "END;",
220646              zWrite, zTbl, zNewlist
220647          );
220648        }
220649
220650        rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
220651      }
220652
220653      /* Create the SELECT statement to read keys from data_xxx */
220654      if( p->rc==SQLITE_OK ){
220655        const char *zRbuRowid = "";
220656        char *zStart = 0;
220657        char *zOrder = 0;
220658        if( bRbuRowid ){
220659          zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
220660        }
220661
220662        if( rbuIsVacuum(p) ){
220663          if( nOffset ){
220664            zStart = rbuVacuumTableStart(p, pIter, bRbuRowid, zWrite);
220665            if( zStart ){
220666              sqlite3_free(zLimit);
220667              zLimit = 0;
220668            }
220669          }
220670          if( bRbuRowid ){
220671            zOrder = rbuMPrintf(p, "_rowid_");
220672          }else{
220673            zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", "");
220674          }
220675        }
220676
220677        if( p->rc==SQLITE_OK ){
220678          p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
220679              sqlite3_mprintf(
220680                "SELECT %s,%s rbu_control%s FROM '%q'%s %s %s %s",
220681                zCollist,
220682                (rbuIsVacuum(p) ? "0 AS " : ""),
220683                zRbuRowid,
220684                pIter->zDataTbl, (zStart ? zStart : ""),
220685                (zOrder ? "ORDER BY" : ""), zOrder,
220686                zLimit
220687              )
220688          );
220689        }
220690        sqlite3_free(zStart);
220691        sqlite3_free(zOrder);
220692      }
220693
220694      sqlite3_free(zWhere);
220695      sqlite3_free(zOldlist);
220696      sqlite3_free(zNewlist);
220697      sqlite3_free(zBindings);
220698    }
220699    sqlite3_free(zCollist);
220700    sqlite3_free(zLimit);
220701  }
220702
220703  return p->rc;
220704}
220705
220706/*
220707** Set output variable *ppStmt to point to an UPDATE statement that may
220708** be used to update the imposter table for the main table b-tree of the
220709** table object that pIter currently points to, assuming that the
220710** rbu_control column of the data_xyz table contains zMask.
220711**
220712** If the zMask string does not specify any columns to update, then this
220713** is not an error. Output variable *ppStmt is set to NULL in this case.
220714*/
220715static int rbuGetUpdateStmt(
220716  sqlite3rbu *p,                  /* RBU handle */
220717  RbuObjIter *pIter,              /* Object iterator */
220718  const char *zMask,              /* rbu_control value ('x.x.') */
220719  sqlite3_stmt **ppStmt           /* OUT: UPDATE statement handle */
220720){
220721  RbuUpdateStmt **pp;
220722  RbuUpdateStmt *pUp = 0;
220723  int nUp = 0;
220724
220725  /* In case an error occurs */
220726  *ppStmt = 0;
220727
220728  /* Search for an existing statement. If one is found, shift it to the front
220729  ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
220730  ** to the number of statements currently in the cache and pUp to the
220731  ** last object in the list.  */
220732  for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
220733    pUp = *pp;
220734    if( strcmp(pUp->zMask, zMask)==0 ){
220735      *pp = pUp->pNext;
220736      pUp->pNext = pIter->pRbuUpdate;
220737      pIter->pRbuUpdate = pUp;
220738      *ppStmt = pUp->pUpdate;
220739      return SQLITE_OK;
220740    }
220741    nUp++;
220742  }
220743  assert( pUp==0 || pUp->pNext==0 );
220744
220745  if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
220746    for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
220747    *pp = 0;
220748    sqlite3_finalize(pUp->pUpdate);
220749    pUp->pUpdate = 0;
220750  }else{
220751    pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
220752  }
220753
220754  if( pUp ){
220755    char *zWhere = rbuObjIterGetWhere(p, pIter);
220756    char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
220757    char *zUpdate = 0;
220758
220759    pUp->zMask = (char*)&pUp[1];
220760    memcpy(pUp->zMask, zMask, pIter->nTblCol);
220761    pUp->pNext = pIter->pRbuUpdate;
220762    pIter->pRbuUpdate = pUp;
220763
220764    if( zSet ){
220765      const char *zPrefix = "";
220766
220767      if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
220768      zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
220769          zPrefix, pIter->zTbl, zSet, zWhere
220770      );
220771      p->rc = prepareFreeAndCollectError(
220772          p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
220773      );
220774      *ppStmt = pUp->pUpdate;
220775    }
220776    sqlite3_free(zWhere);
220777    sqlite3_free(zSet);
220778  }
220779
220780  return p->rc;
220781}
220782
220783static sqlite3 *rbuOpenDbhandle(
220784  sqlite3rbu *p,
220785  const char *zName,
220786  int bUseVfs
220787){
220788  sqlite3 *db = 0;
220789  if( p->rc==SQLITE_OK ){
220790    const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
220791    p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
220792    if( p->rc ){
220793      p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
220794      sqlite3_close(db);
220795      db = 0;
220796    }
220797  }
220798  return db;
220799}
220800
220801/*
220802** Free an RbuState object allocated by rbuLoadState().
220803*/
220804static void rbuFreeState(RbuState *p){
220805  if( p ){
220806    sqlite3_free(p->zTbl);
220807    sqlite3_free(p->zDataTbl);
220808    sqlite3_free(p->zIdx);
220809    sqlite3_free(p);
220810  }
220811}
220812
220813/*
220814** Allocate an RbuState object and load the contents of the rbu_state
220815** table into it. Return a pointer to the new object. It is the
220816** responsibility of the caller to eventually free the object using
220817** sqlite3_free().
220818**
220819** If an error occurs, leave an error code and message in the rbu handle
220820** and return NULL.
220821*/
220822static RbuState *rbuLoadState(sqlite3rbu *p){
220823  RbuState *pRet = 0;
220824  sqlite3_stmt *pStmt = 0;
220825  int rc;
220826  int rc2;
220827
220828  pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
220829  if( pRet==0 ) return 0;
220830
220831  rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
220832      sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
220833  );
220834  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
220835    switch( sqlite3_column_int(pStmt, 0) ){
220836      case RBU_STATE_STAGE:
220837        pRet->eStage = sqlite3_column_int(pStmt, 1);
220838        if( pRet->eStage!=RBU_STAGE_OAL
220839         && pRet->eStage!=RBU_STAGE_MOVE
220840         && pRet->eStage!=RBU_STAGE_CKPT
220841        ){
220842          p->rc = SQLITE_CORRUPT;
220843        }
220844        break;
220845
220846      case RBU_STATE_TBL:
220847        pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
220848        break;
220849
220850      case RBU_STATE_IDX:
220851        pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
220852        break;
220853
220854      case RBU_STATE_ROW:
220855        pRet->nRow = sqlite3_column_int(pStmt, 1);
220856        break;
220857
220858      case RBU_STATE_PROGRESS:
220859        pRet->nProgress = sqlite3_column_int64(pStmt, 1);
220860        break;
220861
220862      case RBU_STATE_CKPT:
220863        pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
220864        break;
220865
220866      case RBU_STATE_COOKIE:
220867        pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
220868        break;
220869
220870      case RBU_STATE_OALSZ:
220871        pRet->iOalSz = sqlite3_column_int64(pStmt, 1);
220872        break;
220873
220874      case RBU_STATE_PHASEONESTEP:
220875        pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
220876        break;
220877
220878      case RBU_STATE_DATATBL:
220879        pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
220880        break;
220881
220882      default:
220883        rc = SQLITE_CORRUPT;
220884        break;
220885    }
220886  }
220887  rc2 = sqlite3_finalize(pStmt);
220888  if( rc==SQLITE_OK ) rc = rc2;
220889
220890  p->rc = rc;
220891  return pRet;
220892}
220893
220894
220895/*
220896** Open the database handle and attach the RBU database as "rbu". If an
220897** error occurs, leave an error code and message in the RBU handle.
220898**
220899** If argument dbMain is not NULL, then it is a database handle already
220900** open on the target database. Use this handle instead of opening a new
220901** one.
220902*/
220903static void rbuOpenDatabase(sqlite3rbu *p, sqlite3 *dbMain, int *pbRetry){
220904  assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
220905  assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
220906  assert( dbMain==0 || rbuIsVacuum(p)==0 );
220907
220908  /* Open the RBU database */
220909  p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
220910  p->dbMain = dbMain;
220911
220912  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
220913    sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
220914    if( p->zState==0 ){
220915      const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
220916      p->zState = rbuMPrintf(p, "file:///%s-vacuum?modeof=%s", zFile, zFile);
220917    }
220918  }
220919
220920  /* If using separate RBU and state databases, attach the state database to
220921  ** the RBU db handle now.  */
220922  if( p->zState ){
220923    rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
220924    memcpy(p->zStateDb, "stat", 4);
220925  }else{
220926    memcpy(p->zStateDb, "main", 4);
220927  }
220928
220929#if 0
220930  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
220931    p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
220932  }
220933#endif
220934
220935  /* If it has not already been created, create the rbu_state table */
220936  rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
220937
220938#if 0
220939  if( rbuIsVacuum(p) ){
220940    if( p->rc==SQLITE_OK ){
220941      int rc2;
220942      int bOk = 0;
220943      sqlite3_stmt *pCnt = 0;
220944      p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
220945          "SELECT count(*) FROM stat.sqlite_schema"
220946      );
220947      if( p->rc==SQLITE_OK
220948       && sqlite3_step(pCnt)==SQLITE_ROW
220949       && 1==sqlite3_column_int(pCnt, 0)
220950      ){
220951        bOk = 1;
220952      }
220953      rc2 = sqlite3_finalize(pCnt);
220954      if( p->rc==SQLITE_OK ) p->rc = rc2;
220955
220956      if( p->rc==SQLITE_OK && bOk==0 ){
220957        p->rc = SQLITE_ERROR;
220958        p->zErrmsg = sqlite3_mprintf("invalid state database");
220959      }
220960
220961      if( p->rc==SQLITE_OK ){
220962        p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
220963      }
220964    }
220965  }
220966#endif
220967
220968  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
220969    int bOpen = 0;
220970    int rc;
220971    p->nRbu = 0;
220972    p->pRbuFd = 0;
220973    rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
220974    if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
220975    if( p->eStage>=RBU_STAGE_MOVE ){
220976      bOpen = 1;
220977    }else{
220978      RbuState *pState = rbuLoadState(p);
220979      if( pState ){
220980        bOpen = (pState->eStage>=RBU_STAGE_MOVE);
220981        rbuFreeState(pState);
220982      }
220983    }
220984    if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
220985  }
220986
220987  p->eStage = 0;
220988  if( p->rc==SQLITE_OK && p->dbMain==0 ){
220989    if( !rbuIsVacuum(p) ){
220990      p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
220991    }else if( p->pRbuFd->pWalFd ){
220992      if( pbRetry ){
220993        p->pRbuFd->bNolock = 0;
220994        sqlite3_close(p->dbRbu);
220995        sqlite3_close(p->dbMain);
220996        p->dbMain = 0;
220997        p->dbRbu = 0;
220998        *pbRetry = 1;
220999        return;
221000      }
221001      p->rc = SQLITE_ERROR;
221002      p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
221003    }else{
221004      char *zTarget;
221005      char *zExtra = 0;
221006      if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
221007        zExtra = &p->zRbu[5];
221008        while( *zExtra ){
221009          if( *zExtra++=='?' ) break;
221010        }
221011        if( *zExtra=='\0' ) zExtra = 0;
221012      }
221013
221014      zTarget = sqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s",
221015          sqlite3_db_filename(p->dbRbu, "main"),
221016          (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
221017      );
221018
221019      if( zTarget==0 ){
221020        p->rc = SQLITE_NOMEM;
221021        return;
221022      }
221023      p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
221024      sqlite3_free(zTarget);
221025    }
221026  }
221027
221028  if( p->rc==SQLITE_OK ){
221029    p->rc = sqlite3_create_function(p->dbMain,
221030        "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
221031    );
221032  }
221033
221034  if( p->rc==SQLITE_OK ){
221035    p->rc = sqlite3_create_function(p->dbMain,
221036        "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
221037    );
221038  }
221039
221040  if( p->rc==SQLITE_OK ){
221041    p->rc = sqlite3_create_function(p->dbRbu,
221042        "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
221043    );
221044  }
221045
221046  if( p->rc==SQLITE_OK ){
221047    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
221048  }
221049  rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_schema");
221050
221051  /* Mark the database file just opened as an RBU target database. If
221052  ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
221053  ** This is an error.  */
221054  if( p->rc==SQLITE_OK ){
221055    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
221056  }
221057
221058  if( p->rc==SQLITE_NOTFOUND ){
221059    p->rc = SQLITE_ERROR;
221060    p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
221061  }
221062}
221063
221064/*
221065** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
221066** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
221067**
221068** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
221069** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
221070** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
221071** three characters, then shorten the suffix on z[] to be the last three
221072** characters of the original suffix.
221073**
221074** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
221075** do the suffix shortening regardless of URI parameter.
221076**
221077** Examples:
221078**
221079**     test.db-journal    =>   test.nal
221080**     test.db-wal        =>   test.wal
221081**     test.db-shm        =>   test.shm
221082**     test.db-mj7f3319fa =>   test.9fa
221083*/
221084static void rbuFileSuffix3(const char *zBase, char *z){
221085#ifdef SQLITE_ENABLE_8_3_NAMES
221086#if SQLITE_ENABLE_8_3_NAMES<2
221087  if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
221088#endif
221089  {
221090    int i, sz;
221091    sz = (int)strlen(z)&0xffffff;
221092    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
221093    if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
221094  }
221095#endif
221096}
221097
221098/*
221099** Return the current wal-index header checksum for the target database
221100** as a 64-bit integer.
221101**
221102** The checksum is store in the first page of xShmMap memory as an 8-byte
221103** blob starting at byte offset 40.
221104*/
221105static i64 rbuShmChecksum(sqlite3rbu *p){
221106  i64 iRet = 0;
221107  if( p->rc==SQLITE_OK ){
221108    sqlite3_file *pDb = p->pTargetFd->pReal;
221109    u32 volatile *ptr;
221110    p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
221111    if( p->rc==SQLITE_OK ){
221112      iRet = (i64)(((u64)ptr[10] << 32) + ptr[11]);
221113    }
221114  }
221115  return iRet;
221116}
221117
221118/*
221119** This function is called as part of initializing or reinitializing an
221120** incremental checkpoint.
221121**
221122** It populates the sqlite3rbu.aFrame[] array with the set of
221123** (wal frame -> db page) copy operations required to checkpoint the
221124** current wal file, and obtains the set of shm locks required to safely
221125** perform the copy operations directly on the file-system.
221126**
221127** If argument pState is not NULL, then the incremental checkpoint is
221128** being resumed. In this case, if the checksum of the wal-index-header
221129** following recovery is not the same as the checksum saved in the RbuState
221130** object, then the rbu handle is set to DONE state. This occurs if some
221131** other client appends a transaction to the wal file in the middle of
221132** an incremental checkpoint.
221133*/
221134static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
221135
221136  /* If pState is NULL, then the wal file may not have been opened and
221137  ** recovered. Running a read-statement here to ensure that doing so
221138  ** does not interfere with the "capture" process below.  */
221139  if( pState==0 ){
221140    p->eStage = 0;
221141    if( p->rc==SQLITE_OK ){
221142      p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_schema", 0, 0, 0);
221143    }
221144  }
221145
221146  /* Assuming no error has occurred, run a "restart" checkpoint with the
221147  ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
221148  ** special behaviour in the rbu VFS:
221149  **
221150  **   * If the exclusive shm WRITER or READ0 lock cannot be obtained,
221151  **     the checkpoint fails with SQLITE_BUSY (normally SQLite would
221152  **     proceed with running a passive checkpoint instead of failing).
221153  **
221154  **   * Attempts to read from the *-wal file or write to the database file
221155  **     do not perform any IO. Instead, the frame/page combinations that
221156  **     would be read/written are recorded in the sqlite3rbu.aFrame[]
221157  **     array.
221158  **
221159  **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
221160  **     READ0 and CHECKPOINT locks taken as part of the checkpoint are
221161  **     no-ops. These locks will not be released until the connection
221162  **     is closed.
221163  **
221164  **   * Attempting to xSync() the database file causes an SQLITE_NOTICE
221165  **     error.
221166  **
221167  ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
221168  ** checkpoint below fails with SQLITE_NOTICE, and leaves the aFrame[]
221169  ** array populated with a set of (frame -> page) mappings. Because the
221170  ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
221171  ** data from the wal file into the database file according to the
221172  ** contents of aFrame[].
221173  */
221174  if( p->rc==SQLITE_OK ){
221175    int rc2;
221176    p->eStage = RBU_STAGE_CAPTURE;
221177    rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
221178    if( rc2!=SQLITE_NOTICE ) p->rc = rc2;
221179  }
221180
221181  if( p->rc==SQLITE_OK && p->nFrame>0 ){
221182    p->eStage = RBU_STAGE_CKPT;
221183    p->nStep = (pState ? pState->nRow : 0);
221184    p->aBuf = rbuMalloc(p, p->pgsz);
221185    p->iWalCksum = rbuShmChecksum(p);
221186  }
221187
221188  if( p->rc==SQLITE_OK ){
221189    if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
221190      p->rc = SQLITE_DONE;
221191      p->eStage = RBU_STAGE_DONE;
221192    }else{
221193      int nSectorSize;
221194      sqlite3_file *pDb = p->pTargetFd->pReal;
221195      sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
221196      assert( p->nPagePerSector==0 );
221197      nSectorSize = pDb->pMethods->xSectorSize(pDb);
221198      if( nSectorSize>p->pgsz ){
221199        p->nPagePerSector = nSectorSize / p->pgsz;
221200      }else{
221201        p->nPagePerSector = 1;
221202      }
221203
221204      /* Call xSync() on the wal file. This causes SQLite to sync the
221205      ** directory in which the target database and the wal file reside, in
221206      ** case it has not been synced since the rename() call in
221207      ** rbuMoveOalFile(). */
221208      p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
221209    }
221210  }
221211}
221212
221213/*
221214** Called when iAmt bytes are read from offset iOff of the wal file while
221215** the rbu object is in capture mode. Record the frame number of the frame
221216** being read in the aFrame[] array.
221217*/
221218static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
221219  const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
221220  u32 iFrame;
221221
221222  if( pRbu->mLock!=mReq ){
221223    pRbu->rc = SQLITE_BUSY;
221224    return SQLITE_NOTICE_RBU;
221225  }
221226
221227  pRbu->pgsz = iAmt;
221228  if( pRbu->nFrame==pRbu->nFrameAlloc ){
221229    int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
221230    RbuFrame *aNew;
221231    aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
221232    if( aNew==0 ) return SQLITE_NOMEM;
221233    pRbu->aFrame = aNew;
221234    pRbu->nFrameAlloc = nNew;
221235  }
221236
221237  iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
221238  if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
221239  pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
221240  pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
221241  pRbu->nFrame++;
221242  return SQLITE_OK;
221243}
221244
221245/*
221246** Called when a page of data is written to offset iOff of the database
221247** file while the rbu handle is in capture mode. Record the page number
221248** of the page being written in the aFrame[] array.
221249*/
221250static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
221251  pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
221252  return SQLITE_OK;
221253}
221254
221255/*
221256** This is called as part of an incremental checkpoint operation. Copy
221257** a single frame of data from the wal file into the database file, as
221258** indicated by the RbuFrame object.
221259*/
221260static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
221261  sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
221262  sqlite3_file *pDb = p->pTargetFd->pReal;
221263  i64 iOff;
221264
221265  assert( p->rc==SQLITE_OK );
221266  iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
221267  p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
221268  if( p->rc ) return;
221269
221270  iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
221271  p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
221272}
221273
221274/*
221275** This value is copied from the definition of ZIPVFS_CTRL_FILE_POINTER
221276** in zipvfs.h.
221277*/
221278#define RBU_ZIPVFS_CTRL_FILE_POINTER 230439
221279
221280/*
221281** Take an EXCLUSIVE lock on the database file. Return SQLITE_OK if
221282** successful, or an SQLite error code otherwise.
221283*/
221284static int rbuLockDatabase(sqlite3 *db){
221285  int rc = SQLITE_OK;
221286  sqlite3_file *fd = 0;
221287
221288  sqlite3_file_control(db, "main", RBU_ZIPVFS_CTRL_FILE_POINTER, &fd);
221289  if( fd ){
221290    sqlite3_file_control(db, "main", SQLITE_FCNTL_FILE_POINTER, &fd);
221291    rc = fd->pMethods->xLock(fd, SQLITE_LOCK_SHARED);
221292    if( rc==SQLITE_OK ){
221293      rc = fd->pMethods->xUnlock(fd, SQLITE_LOCK_NONE);
221294    }
221295    sqlite3_file_control(db, "main", RBU_ZIPVFS_CTRL_FILE_POINTER, &fd);
221296  }else{
221297    sqlite3_file_control(db, "main", SQLITE_FCNTL_FILE_POINTER, &fd);
221298  }
221299
221300  if( rc==SQLITE_OK && fd->pMethods ){
221301    rc = fd->pMethods->xLock(fd, SQLITE_LOCK_SHARED);
221302    if( rc==SQLITE_OK ){
221303      rc = fd->pMethods->xLock(fd, SQLITE_LOCK_EXCLUSIVE);
221304    }
221305  }
221306  return rc;
221307}
221308
221309/*
221310** Return true if the database handle passed as the only argument
221311** was opened with the rbu_exclusive_checkpoint=1 URI parameter
221312** specified. Or false otherwise.
221313*/
221314static int rbuExclusiveCheckpoint(sqlite3 *db){
221315  const char *zUri = sqlite3_db_filename(db, 0);
221316  return sqlite3_uri_boolean(zUri, RBU_EXCLUSIVE_CHECKPOINT, 0);
221317}
221318
221319#if defined(_WIN32_WCE)
221320static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
221321  int nChar;
221322  LPWSTR zWideFilename;
221323
221324  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
221325  if( nChar==0 ){
221326    return 0;
221327  }
221328  zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
221329  if( zWideFilename==0 ){
221330    return 0;
221331  }
221332  memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
221333  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
221334                                nChar);
221335  if( nChar==0 ){
221336    sqlite3_free(zWideFilename);
221337    zWideFilename = 0;
221338  }
221339  return zWideFilename;
221340}
221341#endif
221342
221343/*
221344** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
221345** on the database file. This proc moves the *-oal file to the *-wal path,
221346** then reopens the database file (this time in vanilla, non-oal, WAL mode).
221347** If an error occurs, leave an error code and error message in the rbu
221348** handle.
221349*/
221350static void rbuMoveOalFile(sqlite3rbu *p){
221351  const char *zBase = sqlite3_db_filename(p->dbMain, "main");
221352  const char *zMove = zBase;
221353  char *zOal;
221354  char *zWal;
221355
221356  if( rbuIsVacuum(p) ){
221357    zMove = sqlite3_db_filename(p->dbRbu, "main");
221358  }
221359  zOal = sqlite3_mprintf("%s-oal", zMove);
221360  zWal = sqlite3_mprintf("%s-wal", zMove);
221361
221362  assert( p->eStage==RBU_STAGE_MOVE );
221363  assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
221364  if( zWal==0 || zOal==0 ){
221365    p->rc = SQLITE_NOMEM;
221366  }else{
221367    /* Move the *-oal file to *-wal. At this point connection p->db is
221368    ** holding a SHARED lock on the target database file (because it is
221369    ** in WAL mode). So no other connection may be writing the db.
221370    **
221371    ** In order to ensure that there are no database readers, an EXCLUSIVE
221372    ** lock is obtained here before the *-oal is moved to *-wal.
221373    */
221374    sqlite3 *dbMain = 0;
221375    rbuFileSuffix3(zBase, zWal);
221376    rbuFileSuffix3(zBase, zOal);
221377
221378    /* Re-open the databases. */
221379    rbuObjIterFinalize(&p->objiter);
221380    sqlite3_close(p->dbRbu);
221381    sqlite3_close(p->dbMain);
221382    p->dbMain = 0;
221383    p->dbRbu = 0;
221384
221385    dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
221386    if( dbMain ){
221387      assert( p->rc==SQLITE_OK );
221388      p->rc = rbuLockDatabase(dbMain);
221389    }
221390
221391    if( p->rc==SQLITE_OK ){
221392      p->rc = p->xRename(p->pRenameArg, zOal, zWal);
221393    }
221394
221395    if( p->rc!=SQLITE_OK
221396     || rbuIsVacuum(p)
221397     || rbuExclusiveCheckpoint(dbMain)==0
221398    ){
221399      sqlite3_close(dbMain);
221400      dbMain = 0;
221401    }
221402
221403    if( p->rc==SQLITE_OK ){
221404      rbuOpenDatabase(p, dbMain, 0);
221405      rbuSetupCheckpoint(p, 0);
221406    }
221407  }
221408
221409  sqlite3_free(zWal);
221410  sqlite3_free(zOal);
221411}
221412
221413/*
221414** The SELECT statement iterating through the keys for the current object
221415** (p->objiter.pSelect) currently points to a valid row. This function
221416** determines the type of operation requested by this row and returns
221417** one of the following values to indicate the result:
221418**
221419**     * RBU_INSERT
221420**     * RBU_DELETE
221421**     * RBU_IDX_DELETE
221422**     * RBU_UPDATE
221423**
221424** If RBU_UPDATE is returned, then output variable *pzMask is set to
221425** point to the text value indicating the columns to update.
221426**
221427** If the rbu_control field contains an invalid value, an error code and
221428** message are left in the RBU handle and zero returned.
221429*/
221430static int rbuStepType(sqlite3rbu *p, const char **pzMask){
221431  int iCol = p->objiter.nCol;     /* Index of rbu_control column */
221432  int res = 0;                    /* Return value */
221433
221434  switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
221435    case SQLITE_INTEGER: {
221436      int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
221437      switch( iVal ){
221438        case 0: res = RBU_INSERT;     break;
221439        case 1: res = RBU_DELETE;     break;
221440        case 2: res = RBU_REPLACE;    break;
221441        case 3: res = RBU_IDX_DELETE; break;
221442        case 4: res = RBU_IDX_INSERT; break;
221443      }
221444      break;
221445    }
221446
221447    case SQLITE_TEXT: {
221448      const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
221449      if( z==0 ){
221450        p->rc = SQLITE_NOMEM;
221451      }else{
221452        *pzMask = (const char*)z;
221453      }
221454      res = RBU_UPDATE;
221455
221456      break;
221457    }
221458
221459    default:
221460      break;
221461  }
221462
221463  if( res==0 ){
221464    rbuBadControlError(p);
221465  }
221466  return res;
221467}
221468
221469#ifdef SQLITE_DEBUG
221470/*
221471** Assert that column iCol of statement pStmt is named zName.
221472*/
221473static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
221474  const char *zCol = sqlite3_column_name(pStmt, iCol);
221475  assert( 0==sqlite3_stricmp(zName, zCol) );
221476}
221477#else
221478# define assertColumnName(x,y,z)
221479#endif
221480
221481/*
221482** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
221483** RBU_IDX_DELETE. This function performs the work of a single
221484** sqlite3rbu_step() call for the type of operation specified by eType.
221485*/
221486static void rbuStepOneOp(sqlite3rbu *p, int eType){
221487  RbuObjIter *pIter = &p->objiter;
221488  sqlite3_value *pVal;
221489  sqlite3_stmt *pWriter;
221490  int i;
221491
221492  assert( p->rc==SQLITE_OK );
221493  assert( eType!=RBU_DELETE || pIter->zIdx==0 );
221494  assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
221495       || eType==RBU_INSERT || eType==RBU_IDX_INSERT
221496  );
221497
221498  /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
221499  ** statement below does actually delete a row, nPhaseOneStep will be
221500  ** incremented by the same amount when SQL function rbu_tmp_insert()
221501  ** is invoked by the trigger.  */
221502  if( eType==RBU_DELETE ){
221503    p->nPhaseOneStep -= p->objiter.nIndex;
221504  }
221505
221506  if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
221507    pWriter = pIter->pDelete;
221508  }else{
221509    pWriter = pIter->pInsert;
221510  }
221511
221512  for(i=0; i<pIter->nCol; i++){
221513    /* If this is an INSERT into a table b-tree and the table has an
221514    ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
221515    ** to write a NULL into the IPK column. That is not permitted.  */
221516    if( eType==RBU_INSERT
221517     && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
221518     && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
221519    ){
221520      p->rc = SQLITE_MISMATCH;
221521      p->zErrmsg = sqlite3_mprintf("datatype mismatch");
221522      return;
221523    }
221524
221525    if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
221526      continue;
221527    }
221528
221529    pVal = sqlite3_column_value(pIter->pSelect, i);
221530    p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
221531    if( p->rc ) return;
221532  }
221533  if( pIter->zIdx==0 ){
221534    if( pIter->eType==RBU_PK_VTAB
221535     || pIter->eType==RBU_PK_NONE
221536     || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
221537    ){
221538      /* For a virtual table, or a table with no primary key, the
221539      ** SELECT statement is:
221540      **
221541      **   SELECT <cols>, rbu_control, rbu_rowid FROM ....
221542      **
221543      ** Hence column_value(pIter->nCol+1).
221544      */
221545      assertColumnName(pIter->pSelect, pIter->nCol+1,
221546          rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
221547      );
221548      pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
221549      p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
221550    }
221551  }
221552  if( p->rc==SQLITE_OK ){
221553    sqlite3_step(pWriter);
221554    p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
221555  }
221556}
221557
221558/*
221559** This function does the work for an sqlite3rbu_step() call.
221560**
221561** The object-iterator (p->objiter) currently points to a valid object,
221562** and the input cursor (p->objiter.pSelect) currently points to a valid
221563** input row. Perform whatever processing is required and return.
221564**
221565** If no  error occurs, SQLITE_OK is returned. Otherwise, an error code
221566** and message is left in the RBU handle and a copy of the error code
221567** returned.
221568*/
221569static int rbuStep(sqlite3rbu *p){
221570  RbuObjIter *pIter = &p->objiter;
221571  const char *zMask = 0;
221572  int eType = rbuStepType(p, &zMask);
221573
221574  if( eType ){
221575    assert( eType==RBU_INSERT     || eType==RBU_DELETE
221576         || eType==RBU_REPLACE    || eType==RBU_IDX_DELETE
221577         || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
221578    );
221579    assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
221580
221581    if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
221582      rbuBadControlError(p);
221583    }
221584    else if( eType==RBU_REPLACE ){
221585      if( pIter->zIdx==0 ){
221586        p->nPhaseOneStep += p->objiter.nIndex;
221587        rbuStepOneOp(p, RBU_DELETE);
221588      }
221589      if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
221590    }
221591    else if( eType!=RBU_UPDATE ){
221592      rbuStepOneOp(p, eType);
221593    }
221594    else{
221595      sqlite3_value *pVal;
221596      sqlite3_stmt *pUpdate = 0;
221597      assert( eType==RBU_UPDATE );
221598      p->nPhaseOneStep -= p->objiter.nIndex;
221599      rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
221600      if( pUpdate ){
221601        int i;
221602        for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
221603          char c = zMask[pIter->aiSrcOrder[i]];
221604          pVal = sqlite3_column_value(pIter->pSelect, i);
221605          if( pIter->abTblPk[i] || c!='.' ){
221606            p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
221607          }
221608        }
221609        if( p->rc==SQLITE_OK
221610         && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
221611        ){
221612          /* Bind the rbu_rowid value to column _rowid_ */
221613          assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
221614          pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
221615          p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
221616        }
221617        if( p->rc==SQLITE_OK ){
221618          sqlite3_step(pUpdate);
221619          p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
221620        }
221621      }
221622    }
221623  }
221624  return p->rc;
221625}
221626
221627/*
221628** Increment the schema cookie of the main database opened by p->dbMain.
221629**
221630** Or, if this is an RBU vacuum, set the schema cookie of the main db
221631** opened by p->dbMain to one more than the schema cookie of the main
221632** db opened by p->dbRbu.
221633*/
221634static void rbuIncrSchemaCookie(sqlite3rbu *p){
221635  if( p->rc==SQLITE_OK ){
221636    sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
221637    int iCookie = 1000000;
221638    sqlite3_stmt *pStmt;
221639
221640    p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
221641        "PRAGMA schema_version"
221642    );
221643    if( p->rc==SQLITE_OK ){
221644      /* Coverage: it may be that this sqlite3_step() cannot fail. There
221645      ** is already a transaction open, so the prepared statement cannot
221646      ** throw an SQLITE_SCHEMA exception. The only database page the
221647      ** statement reads is page 1, which is guaranteed to be in the cache.
221648      ** And no memory allocations are required.  */
221649      if( SQLITE_ROW==sqlite3_step(pStmt) ){
221650        iCookie = sqlite3_column_int(pStmt, 0);
221651      }
221652      rbuFinalize(p, pStmt);
221653    }
221654    if( p->rc==SQLITE_OK ){
221655      rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
221656    }
221657  }
221658}
221659
221660/*
221661** Update the contents of the rbu_state table within the rbu database. The
221662** value stored in the RBU_STATE_STAGE column is eStage. All other values
221663** are determined by inspecting the rbu handle passed as the first argument.
221664*/
221665static void rbuSaveState(sqlite3rbu *p, int eStage){
221666  if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
221667    sqlite3_stmt *pInsert = 0;
221668    rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
221669    int rc;
221670
221671    assert( p->zErrmsg==0 );
221672    rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
221673        sqlite3_mprintf(
221674          "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
221675          "(%d, %d), "
221676          "(%d, %Q), "
221677          "(%d, %Q), "
221678          "(%d, %d), "
221679          "(%d, %d), "
221680          "(%d, %lld), "
221681          "(%d, %lld), "
221682          "(%d, %lld), "
221683          "(%d, %lld), "
221684          "(%d, %Q)  ",
221685          p->zStateDb,
221686          RBU_STATE_STAGE, eStage,
221687          RBU_STATE_TBL, p->objiter.zTbl,
221688          RBU_STATE_IDX, p->objiter.zIdx,
221689          RBU_STATE_ROW, p->nStep,
221690          RBU_STATE_PROGRESS, p->nProgress,
221691          RBU_STATE_CKPT, p->iWalCksum,
221692          RBU_STATE_COOKIE, (i64)pFd->iCookie,
221693          RBU_STATE_OALSZ, p->iOalSz,
221694          RBU_STATE_PHASEONESTEP, p->nPhaseOneStep,
221695          RBU_STATE_DATATBL, p->objiter.zDataTbl
221696      )
221697    );
221698    assert( pInsert==0 || rc==SQLITE_OK );
221699
221700    if( rc==SQLITE_OK ){
221701      sqlite3_step(pInsert);
221702      rc = sqlite3_finalize(pInsert);
221703    }
221704    if( rc!=SQLITE_OK ) p->rc = rc;
221705  }
221706}
221707
221708
221709/*
221710** The second argument passed to this function is the name of a PRAGMA
221711** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
221712** This function executes the following on sqlite3rbu.dbRbu:
221713**
221714**   "PRAGMA main.$zPragma"
221715**
221716** where $zPragma is the string passed as the second argument, then
221717** on sqlite3rbu.dbMain:
221718**
221719**   "PRAGMA main.$zPragma = $val"
221720**
221721** where $val is the value returned by the first PRAGMA invocation.
221722**
221723** In short, it copies the value  of the specified PRAGMA setting from
221724** dbRbu to dbMain.
221725*/
221726static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
221727  if( p->rc==SQLITE_OK ){
221728    sqlite3_stmt *pPragma = 0;
221729    p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
221730        sqlite3_mprintf("PRAGMA main.%s", zPragma)
221731    );
221732    if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
221733      p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
221734          zPragma, sqlite3_column_int(pPragma, 0)
221735      );
221736    }
221737    rbuFinalize(p, pPragma);
221738  }
221739}
221740
221741/*
221742** The RBU handle passed as the only argument has just been opened and
221743** the state database is empty. If this RBU handle was opened for an
221744** RBU vacuum operation, create the schema in the target db.
221745*/
221746static void rbuCreateTargetSchema(sqlite3rbu *p){
221747  sqlite3_stmt *pSql = 0;
221748  sqlite3_stmt *pInsert = 0;
221749
221750  assert( rbuIsVacuum(p) );
221751  p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
221752  if( p->rc==SQLITE_OK ){
221753    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
221754      "SELECT sql FROM sqlite_schema WHERE sql!='' AND rootpage!=0"
221755      " AND name!='sqlite_sequence' "
221756      " ORDER BY type DESC"
221757    );
221758  }
221759
221760  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
221761    const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
221762    p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
221763  }
221764  rbuFinalize(p, pSql);
221765  if( p->rc!=SQLITE_OK ) return;
221766
221767  if( p->rc==SQLITE_OK ){
221768    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
221769        "SELECT * FROM sqlite_schema WHERE rootpage=0 OR rootpage IS NULL"
221770    );
221771  }
221772
221773  if( p->rc==SQLITE_OK ){
221774    p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
221775        "INSERT INTO sqlite_schema VALUES(?,?,?,?,?)"
221776    );
221777  }
221778
221779  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
221780    int i;
221781    for(i=0; i<5; i++){
221782      sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
221783    }
221784    sqlite3_step(pInsert);
221785    p->rc = sqlite3_reset(pInsert);
221786  }
221787  if( p->rc==SQLITE_OK ){
221788    p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
221789  }
221790
221791  rbuFinalize(p, pSql);
221792  rbuFinalize(p, pInsert);
221793}
221794
221795/*
221796** Step the RBU object.
221797*/
221798SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
221799  if( p ){
221800    switch( p->eStage ){
221801      case RBU_STAGE_OAL: {
221802        RbuObjIter *pIter = &p->objiter;
221803
221804        /* If this is an RBU vacuum operation and the state table was empty
221805        ** when this handle was opened, create the target database schema. */
221806        if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
221807          rbuCreateTargetSchema(p);
221808          rbuCopyPragma(p, "user_version");
221809          rbuCopyPragma(p, "application_id");
221810        }
221811
221812        while( p->rc==SQLITE_OK && pIter->zTbl ){
221813
221814          if( pIter->bCleanup ){
221815            /* Clean up the rbu_tmp_xxx table for the previous table. It
221816            ** cannot be dropped as there are currently active SQL statements.
221817            ** But the contents can be deleted.  */
221818            if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
221819              rbuMPrintfExec(p, p->dbRbu,
221820                  "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
221821              );
221822            }
221823          }else{
221824            rbuObjIterPrepareAll(p, pIter, 0);
221825
221826            /* Advance to the next row to process. */
221827            if( p->rc==SQLITE_OK ){
221828              int rc = sqlite3_step(pIter->pSelect);
221829              if( rc==SQLITE_ROW ){
221830                p->nProgress++;
221831                p->nStep++;
221832                return rbuStep(p);
221833              }
221834              p->rc = sqlite3_reset(pIter->pSelect);
221835              p->nStep = 0;
221836            }
221837          }
221838
221839          rbuObjIterNext(p, pIter);
221840        }
221841
221842        if( p->rc==SQLITE_OK ){
221843          assert( pIter->zTbl==0 );
221844          rbuSaveState(p, RBU_STAGE_MOVE);
221845          rbuIncrSchemaCookie(p);
221846          if( p->rc==SQLITE_OK ){
221847            p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
221848          }
221849          if( p->rc==SQLITE_OK ){
221850            p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
221851          }
221852          p->eStage = RBU_STAGE_MOVE;
221853        }
221854        break;
221855      }
221856
221857      case RBU_STAGE_MOVE: {
221858        if( p->rc==SQLITE_OK ){
221859          rbuMoveOalFile(p);
221860          p->nProgress++;
221861        }
221862        break;
221863      }
221864
221865      case RBU_STAGE_CKPT: {
221866        if( p->rc==SQLITE_OK ){
221867          if( p->nStep>=p->nFrame ){
221868            sqlite3_file *pDb = p->pTargetFd->pReal;
221869
221870            /* Sync the db file */
221871            p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
221872
221873            /* Update nBackfill */
221874            if( p->rc==SQLITE_OK ){
221875              void volatile *ptr;
221876              p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
221877              if( p->rc==SQLITE_OK ){
221878                ((u32 volatile*)ptr)[24] = p->iMaxFrame;
221879              }
221880            }
221881
221882            if( p->rc==SQLITE_OK ){
221883              p->eStage = RBU_STAGE_DONE;
221884              p->rc = SQLITE_DONE;
221885            }
221886          }else{
221887            /* At one point the following block copied a single frame from the
221888            ** wal file to the database file. So that one call to sqlite3rbu_step()
221889            ** checkpointed a single frame.
221890            **
221891            ** However, if the sector-size is larger than the page-size, and the
221892            ** application calls sqlite3rbu_savestate() or close() immediately
221893            ** after this step, then rbu_step() again, then a power failure occurs,
221894            ** then the database page written here may be damaged. Work around
221895            ** this by checkpointing frames until the next page in the aFrame[]
221896            ** lies on a different disk sector to the current one. */
221897            u32 iSector;
221898            do{
221899              RbuFrame *pFrame = &p->aFrame[p->nStep];
221900              iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
221901              rbuCheckpointFrame(p, pFrame);
221902              p->nStep++;
221903            }while( p->nStep<p->nFrame
221904                 && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
221905                 && p->rc==SQLITE_OK
221906            );
221907          }
221908          p->nProgress++;
221909        }
221910        break;
221911      }
221912
221913      default:
221914        break;
221915    }
221916    return p->rc;
221917  }else{
221918    return SQLITE_NOMEM;
221919  }
221920}
221921
221922/*
221923** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
221924** otherwise. Either or both argument may be NULL. Two NULL values are
221925** considered equal, and NULL is considered distinct from all other values.
221926*/
221927static int rbuStrCompare(const char *z1, const char *z2){
221928  if( z1==0 && z2==0 ) return 0;
221929  if( z1==0 || z2==0 ) return 1;
221930  return (sqlite3_stricmp(z1, z2)!=0);
221931}
221932
221933/*
221934** This function is called as part of sqlite3rbu_open() when initializing
221935** an rbu handle in OAL stage. If the rbu update has not started (i.e.
221936** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
221937** things so that the next call to sqlite3rbu_step() continues on from
221938** where the previous rbu handle left off.
221939**
221940** If an error occurs, an error code and error message are left in the
221941** rbu handle passed as the first argument.
221942*/
221943static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
221944  assert( p->rc==SQLITE_OK );
221945  if( pState->zTbl ){
221946    RbuObjIter *pIter = &p->objiter;
221947    int rc = SQLITE_OK;
221948
221949    while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
221950       || rbuStrCompare(pIter->zIdx, pState->zIdx)
221951       || (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl))
221952       || (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl))
221953    )){
221954      rc = rbuObjIterNext(p, pIter);
221955    }
221956
221957    if( rc==SQLITE_OK && !pIter->zTbl ){
221958      rc = SQLITE_ERROR;
221959      p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
221960    }
221961
221962    if( rc==SQLITE_OK ){
221963      p->nStep = pState->nRow;
221964      rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
221965    }
221966
221967    p->rc = rc;
221968  }
221969}
221970
221971/*
221972** If there is a "*-oal" file in the file-system corresponding to the
221973** target database in the file-system, delete it. If an error occurs,
221974** leave an error code and error message in the rbu handle.
221975*/
221976static void rbuDeleteOalFile(sqlite3rbu *p){
221977  char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
221978  if( zOal ){
221979    sqlite3_vfs *pVfs = 0;
221980    sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_VFS_POINTER, &pVfs);
221981    assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
221982    pVfs->xDelete(pVfs, zOal, 0);
221983    sqlite3_free(zOal);
221984  }
221985}
221986
221987/*
221988** Allocate a private rbu VFS for the rbu handle passed as the only
221989** argument. This VFS will be used unless the call to sqlite3rbu_open()
221990** specified a URI with a vfs=? option in place of a target database
221991** file name.
221992*/
221993static void rbuCreateVfs(sqlite3rbu *p){
221994  int rnd;
221995  char zRnd[64];
221996
221997  assert( p->rc==SQLITE_OK );
221998  sqlite3_randomness(sizeof(int), (void*)&rnd);
221999  sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
222000  p->rc = sqlite3rbu_create_vfs(zRnd, 0);
222001  if( p->rc==SQLITE_OK ){
222002    sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
222003    assert( pVfs );
222004    p->zVfsName = pVfs->zName;
222005    ((rbu_vfs*)pVfs)->pRbu = p;
222006  }
222007}
222008
222009/*
222010** Destroy the private VFS created for the rbu handle passed as the only
222011** argument by an earlier call to rbuCreateVfs().
222012*/
222013static void rbuDeleteVfs(sqlite3rbu *p){
222014  if( p->zVfsName ){
222015    sqlite3rbu_destroy_vfs(p->zVfsName);
222016    p->zVfsName = 0;
222017  }
222018}
222019
222020/*
222021** This user-defined SQL function is invoked with a single argument - the
222022** name of a table expected to appear in the target database. It returns
222023** the number of auxilliary indexes on the table.
222024*/
222025static void rbuIndexCntFunc(
222026  sqlite3_context *pCtx,
222027  int nVal,
222028  sqlite3_value **apVal
222029){
222030  sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
222031  sqlite3_stmt *pStmt = 0;
222032  char *zErrmsg = 0;
222033  int rc;
222034  sqlite3 *db = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
222035
222036  assert( nVal==1 );
222037
222038  rc = prepareFreeAndCollectError(db, &pStmt, &zErrmsg,
222039      sqlite3_mprintf("SELECT count(*) FROM sqlite_schema "
222040        "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
222041  );
222042  if( rc!=SQLITE_OK ){
222043    sqlite3_result_error(pCtx, zErrmsg, -1);
222044  }else{
222045    int nIndex = 0;
222046    if( SQLITE_ROW==sqlite3_step(pStmt) ){
222047      nIndex = sqlite3_column_int(pStmt, 0);
222048    }
222049    rc = sqlite3_finalize(pStmt);
222050    if( rc==SQLITE_OK ){
222051      sqlite3_result_int(pCtx, nIndex);
222052    }else{
222053      sqlite3_result_error(pCtx, sqlite3_errmsg(db), -1);
222054    }
222055  }
222056
222057  sqlite3_free(zErrmsg);
222058}
222059
222060/*
222061** If the RBU database contains the rbu_count table, use it to initialize
222062** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
222063** is assumed to contain the same columns as:
222064**
222065**   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
222066**
222067** There should be one row in the table for each data_xxx table in the
222068** database. The 'tbl' column should contain the name of a data_xxx table,
222069** and the cnt column the number of rows it contains.
222070**
222071** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
222072** for all rows in the rbu_count table, where nIndex is the number of
222073** indexes on the corresponding target database table.
222074*/
222075static void rbuInitPhaseOneSteps(sqlite3rbu *p){
222076  if( p->rc==SQLITE_OK ){
222077    sqlite3_stmt *pStmt = 0;
222078    int bExists = 0;                /* True if rbu_count exists */
222079
222080    p->nPhaseOneStep = -1;
222081
222082    p->rc = sqlite3_create_function(p->dbRbu,
222083        "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
222084    );
222085
222086    /* Check for the rbu_count table. If it does not exist, or if an error
222087    ** occurs, nPhaseOneStep will be left set to -1. */
222088    if( p->rc==SQLITE_OK ){
222089      p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
222090          "SELECT 1 FROM sqlite_schema WHERE tbl_name = 'rbu_count'"
222091      );
222092    }
222093    if( p->rc==SQLITE_OK ){
222094      if( SQLITE_ROW==sqlite3_step(pStmt) ){
222095        bExists = 1;
222096      }
222097      p->rc = sqlite3_finalize(pStmt);
222098    }
222099
222100    if( p->rc==SQLITE_OK && bExists ){
222101      p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
222102          "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
222103          "FROM rbu_count"
222104      );
222105      if( p->rc==SQLITE_OK ){
222106        if( SQLITE_ROW==sqlite3_step(pStmt) ){
222107          p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
222108        }
222109        p->rc = sqlite3_finalize(pStmt);
222110      }
222111    }
222112  }
222113}
222114
222115
222116static sqlite3rbu *openRbuHandle(
222117  const char *zTarget,
222118  const char *zRbu,
222119  const char *zState
222120){
222121  sqlite3rbu *p;
222122  size_t nTarget = zTarget ? strlen(zTarget) : 0;
222123  size_t nRbu = strlen(zRbu);
222124  size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
222125
222126  p = (sqlite3rbu*)sqlite3_malloc64(nByte);
222127  if( p ){
222128    RbuState *pState = 0;
222129
222130    /* Create the custom VFS. */
222131    memset(p, 0, sizeof(sqlite3rbu));
222132    sqlite3rbu_rename_handler(p, 0, 0);
222133    rbuCreateVfs(p);
222134
222135    /* Open the target, RBU and state databases */
222136    if( p->rc==SQLITE_OK ){
222137      char *pCsr = (char*)&p[1];
222138      int bRetry = 0;
222139      if( zTarget ){
222140        p->zTarget = pCsr;
222141        memcpy(p->zTarget, zTarget, nTarget+1);
222142        pCsr += nTarget+1;
222143      }
222144      p->zRbu = pCsr;
222145      memcpy(p->zRbu, zRbu, nRbu+1);
222146      pCsr += nRbu+1;
222147      if( zState ){
222148        p->zState = rbuMPrintf(p, "%s", zState);
222149      }
222150
222151      /* If the first attempt to open the database file fails and the bRetry
222152      ** flag it set, this means that the db was not opened because it seemed
222153      ** to be a wal-mode db. But, this may have happened due to an earlier
222154      ** RBU vacuum operation leaving an old wal file in the directory.
222155      ** If this is the case, it will have been checkpointed and deleted
222156      ** when the handle was closed and a second attempt to open the
222157      ** database may succeed.  */
222158      rbuOpenDatabase(p, 0, &bRetry);
222159      if( bRetry ){
222160        rbuOpenDatabase(p, 0, 0);
222161      }
222162    }
222163
222164    if( p->rc==SQLITE_OK ){
222165      pState = rbuLoadState(p);
222166      assert( pState || p->rc!=SQLITE_OK );
222167      if( p->rc==SQLITE_OK ){
222168
222169        if( pState->eStage==0 ){
222170          rbuDeleteOalFile(p);
222171          rbuInitPhaseOneSteps(p);
222172          p->eStage = RBU_STAGE_OAL;
222173        }else{
222174          p->eStage = pState->eStage;
222175          p->nPhaseOneStep = pState->nPhaseOneStep;
222176        }
222177        p->nProgress = pState->nProgress;
222178        p->iOalSz = pState->iOalSz;
222179      }
222180    }
222181    assert( p->rc!=SQLITE_OK || p->eStage!=0 );
222182
222183    if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
222184      if( p->eStage==RBU_STAGE_OAL ){
222185        p->rc = SQLITE_ERROR;
222186        p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
222187      }else if( p->eStage==RBU_STAGE_MOVE ){
222188        p->eStage = RBU_STAGE_CKPT;
222189        p->nStep = 0;
222190      }
222191    }
222192
222193    if( p->rc==SQLITE_OK
222194     && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
222195     && pState->eStage!=0
222196    ){
222197      rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
222198      if( pFd->iCookie!=pState->iCookie ){
222199        /* At this point (pTargetFd->iCookie) contains the value of the
222200        ** change-counter cookie (the thing that gets incremented when a
222201        ** transaction is committed in rollback mode) currently stored on
222202        ** page 1 of the database file. */
222203        p->rc = SQLITE_BUSY;
222204        p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
222205            (rbuIsVacuum(p) ? "vacuum" : "update")
222206        );
222207      }
222208    }
222209
222210    if( p->rc==SQLITE_OK ){
222211      if( p->eStage==RBU_STAGE_OAL ){
222212        sqlite3 *db = p->dbMain;
222213        p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
222214
222215        /* Point the object iterator at the first object */
222216        if( p->rc==SQLITE_OK ){
222217          p->rc = rbuObjIterFirst(p, &p->objiter);
222218        }
222219
222220        /* If the RBU database contains no data_xxx tables, declare the RBU
222221        ** update finished.  */
222222        if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
222223          p->rc = SQLITE_DONE;
222224          p->eStage = RBU_STAGE_DONE;
222225        }else{
222226          if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
222227            rbuCopyPragma(p, "page_size");
222228            rbuCopyPragma(p, "auto_vacuum");
222229          }
222230
222231          /* Open transactions both databases. The *-oal file is opened or
222232          ** created at this point. */
222233          if( p->rc==SQLITE_OK ){
222234            p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
222235          }
222236
222237          /* Check if the main database is a zipvfs db. If it is, set the upper
222238          ** level pager to use "journal_mode=off". This prevents it from
222239          ** generating a large journal using a temp file.  */
222240          if( p->rc==SQLITE_OK ){
222241            int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
222242            if( frc==SQLITE_OK ){
222243              p->rc = sqlite3_exec(
222244                db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
222245            }
222246          }
222247
222248          if( p->rc==SQLITE_OK ){
222249            rbuSetupOal(p, pState);
222250          }
222251        }
222252      }else if( p->eStage==RBU_STAGE_MOVE ){
222253        /* no-op */
222254      }else if( p->eStage==RBU_STAGE_CKPT ){
222255        if( !rbuIsVacuum(p) && rbuExclusiveCheckpoint(p->dbMain) ){
222256          /* If the rbu_exclusive_checkpoint=1 URI parameter was specified
222257          ** and an incremental checkpoint is being resumed, attempt an
222258          ** exclusive lock on the db file. If this fails, so be it.  */
222259          p->eStage = RBU_STAGE_DONE;
222260          rbuLockDatabase(p->dbMain);
222261          p->eStage = RBU_STAGE_CKPT;
222262        }
222263        rbuSetupCheckpoint(p, pState);
222264      }else if( p->eStage==RBU_STAGE_DONE ){
222265        p->rc = SQLITE_DONE;
222266      }else{
222267        p->rc = SQLITE_CORRUPT;
222268      }
222269    }
222270
222271    rbuFreeState(pState);
222272  }
222273
222274  return p;
222275}
222276
222277/*
222278** Allocate and return an RBU handle with all fields zeroed except for the
222279** error code, which is set to SQLITE_MISUSE.
222280*/
222281static sqlite3rbu *rbuMisuseError(void){
222282  sqlite3rbu *pRet;
222283  pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
222284  if( pRet ){
222285    memset(pRet, 0, sizeof(sqlite3rbu));
222286    pRet->rc = SQLITE_MISUSE;
222287  }
222288  return pRet;
222289}
222290
222291/*
222292** Open and return a new RBU handle.
222293*/
222294SQLITE_API sqlite3rbu *sqlite3rbu_open(
222295  const char *zTarget,
222296  const char *zRbu,
222297  const char *zState
222298){
222299  if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
222300  return openRbuHandle(zTarget, zRbu, zState);
222301}
222302
222303/*
222304** Open a handle to begin or resume an RBU VACUUM operation.
222305*/
222306SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
222307  const char *zTarget,
222308  const char *zState
222309){
222310  if( zTarget==0 ){ return rbuMisuseError(); }
222311  if( zState ){
222312    int n = strlen(zState);
222313    if( n>=7 && 0==memcmp("-vactmp", &zState[n-7], 7) ){
222314      return rbuMisuseError();
222315    }
222316  }
222317  /* TODO: Check that both arguments are non-NULL */
222318  return openRbuHandle(0, zTarget, zState);
222319}
222320
222321/*
222322** Return the database handle used by pRbu.
222323*/
222324SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
222325  sqlite3 *db = 0;
222326  if( pRbu ){
222327    db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
222328  }
222329  return db;
222330}
222331
222332
222333/*
222334** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
222335** then edit any error message string so as to remove all occurrences of
222336** the pattern "rbu_imp_[0-9]*".
222337*/
222338static void rbuEditErrmsg(sqlite3rbu *p){
222339  if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
222340    unsigned int i;
222341    size_t nErrmsg = strlen(p->zErrmsg);
222342    for(i=0; i<(nErrmsg-8); i++){
222343      if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
222344        int nDel = 8;
222345        while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
222346        memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
222347        nErrmsg -= nDel;
222348      }
222349    }
222350  }
222351}
222352
222353/*
222354** Close the RBU handle.
222355*/
222356SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
222357  int rc;
222358  if( p ){
222359
222360    /* Commit the transaction to the *-oal file. */
222361    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
222362      p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
222363    }
222364
222365    /* Sync the db file if currently doing an incremental checkpoint */
222366    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
222367      sqlite3_file *pDb = p->pTargetFd->pReal;
222368      p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
222369    }
222370
222371    rbuSaveState(p, p->eStage);
222372
222373    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
222374      p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
222375    }
222376
222377    /* Close any open statement handles. */
222378    rbuObjIterFinalize(&p->objiter);
222379
222380    /* If this is an RBU vacuum handle and the vacuum has either finished
222381    ** successfully or encountered an error, delete the contents of the
222382    ** state table. This causes the next call to sqlite3rbu_vacuum()
222383    ** specifying the current target and state databases to start a new
222384    ** vacuum from scratch.  */
222385    if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
222386      int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
222387      if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
222388    }
222389
222390    /* Close the open database handle and VFS object. */
222391    sqlite3_close(p->dbRbu);
222392    sqlite3_close(p->dbMain);
222393    assert( p->szTemp==0 );
222394    rbuDeleteVfs(p);
222395    sqlite3_free(p->aBuf);
222396    sqlite3_free(p->aFrame);
222397
222398    rbuEditErrmsg(p);
222399    rc = p->rc;
222400    if( pzErrmsg ){
222401      *pzErrmsg = p->zErrmsg;
222402    }else{
222403      sqlite3_free(p->zErrmsg);
222404    }
222405    sqlite3_free(p->zState);
222406    sqlite3_free(p);
222407  }else{
222408    rc = SQLITE_NOMEM;
222409    *pzErrmsg = 0;
222410  }
222411  return rc;
222412}
222413
222414/*
222415** Return the total number of key-value operations (inserts, deletes or
222416** updates) that have been performed on the target database since the
222417** current RBU update was started.
222418*/
222419SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
222420  return pRbu->nProgress;
222421}
222422
222423/*
222424** Return permyriadage progress indications for the two main stages of
222425** an RBU update.
222426*/
222427SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
222428  const int MAX_PROGRESS = 10000;
222429  switch( p->eStage ){
222430    case RBU_STAGE_OAL:
222431      if( p->nPhaseOneStep>0 ){
222432        *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
222433      }else{
222434        *pnOne = -1;
222435      }
222436      *pnTwo = 0;
222437      break;
222438
222439    case RBU_STAGE_MOVE:
222440      *pnOne = MAX_PROGRESS;
222441      *pnTwo = 0;
222442      break;
222443
222444    case RBU_STAGE_CKPT:
222445      *pnOne = MAX_PROGRESS;
222446      *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
222447      break;
222448
222449    case RBU_STAGE_DONE:
222450      *pnOne = MAX_PROGRESS;
222451      *pnTwo = MAX_PROGRESS;
222452      break;
222453
222454    default:
222455      assert( 0 );
222456  }
222457}
222458
222459/*
222460** Return the current state of the RBU vacuum or update operation.
222461*/
222462SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
222463  int aRes[] = {
222464    0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
222465    0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
222466  };
222467
222468  assert( RBU_STAGE_OAL==1 );
222469  assert( RBU_STAGE_MOVE==2 );
222470  assert( RBU_STAGE_CKPT==4 );
222471  assert( RBU_STAGE_DONE==5 );
222472  assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
222473  assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
222474  assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
222475  assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
222476
222477  if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
222478    return SQLITE_RBU_STATE_ERROR;
222479  }else{
222480    assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
222481    assert( p->eStage==RBU_STAGE_OAL
222482         || p->eStage==RBU_STAGE_MOVE
222483         || p->eStage==RBU_STAGE_CKPT
222484         || p->eStage==RBU_STAGE_DONE
222485    );
222486    return aRes[p->eStage];
222487  }
222488}
222489
222490SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
222491  int rc = p->rc;
222492  if( rc==SQLITE_DONE ) return SQLITE_OK;
222493
222494  assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
222495  if( p->eStage==RBU_STAGE_OAL ){
222496    assert( rc!=SQLITE_DONE );
222497    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
222498  }
222499
222500  /* Sync the db file */
222501  if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
222502    sqlite3_file *pDb = p->pTargetFd->pReal;
222503    rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
222504  }
222505
222506  p->rc = rc;
222507  rbuSaveState(p, p->eStage);
222508  rc = p->rc;
222509
222510  if( p->eStage==RBU_STAGE_OAL ){
222511    assert( rc!=SQLITE_DONE );
222512    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
222513    if( rc==SQLITE_OK ){
222514      const char *zBegin = rbuIsVacuum(p) ? "BEGIN" : "BEGIN IMMEDIATE";
222515      rc = sqlite3_exec(p->dbRbu, zBegin, 0, 0, 0);
222516    }
222517    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
222518  }
222519
222520  p->rc = rc;
222521  return rc;
222522}
222523
222524/*
222525** Default xRename callback for RBU.
222526*/
222527static int xDefaultRename(void *pArg, const char *zOld, const char *zNew){
222528  int rc = SQLITE_OK;
222529#if defined(_WIN32_WCE)
222530  {
222531    LPWSTR zWideOld;
222532    LPWSTR zWideNew;
222533
222534    zWideOld = rbuWinUtf8ToUnicode(zOld);
222535    if( zWideOld ){
222536      zWideNew = rbuWinUtf8ToUnicode(zNew);
222537      if( zWideNew ){
222538        if( MoveFileW(zWideOld, zWideNew) ){
222539          rc = SQLITE_OK;
222540        }else{
222541          rc = SQLITE_IOERR;
222542        }
222543        sqlite3_free(zWideNew);
222544      }else{
222545        rc = SQLITE_IOERR_NOMEM;
222546      }
222547      sqlite3_free(zWideOld);
222548    }else{
222549      rc = SQLITE_IOERR_NOMEM;
222550    }
222551  }
222552#else
222553  rc = rename(zOld, zNew) ? SQLITE_IOERR : SQLITE_OK;
222554#endif
222555  return rc;
222556}
222557
222558SQLITE_API void sqlite3rbu_rename_handler(
222559  sqlite3rbu *pRbu,
222560  void *pArg,
222561  int (*xRename)(void *pArg, const char *zOld, const char *zNew)
222562){
222563  if( xRename ){
222564    pRbu->xRename = xRename;
222565    pRbu->pRenameArg = pArg;
222566  }else{
222567    pRbu->xRename = xDefaultRename;
222568    pRbu->pRenameArg = 0;
222569  }
222570}
222571
222572/**************************************************************************
222573** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
222574** of a standard VFS in the following ways:
222575**
222576** 1. Whenever the first page of a main database file is read or
222577**    written, the value of the change-counter cookie is stored in
222578**    rbu_file.iCookie. Similarly, the value of the "write-version"
222579**    database header field is stored in rbu_file.iWriteVer. This ensures
222580**    that the values are always trustworthy within an open transaction.
222581**
222582** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
222583**    member variable of the associated database file descriptor is set
222584**    to point to the new file. A mutex protected linked list of all main
222585**    db fds opened using a particular RBU VFS is maintained at
222586**    rbu_vfs.pMain to facilitate this.
222587**
222588** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
222589**    object can be marked as the target database of an RBU update. This
222590**    turns on the following extra special behaviour:
222591**
222592** 3a. If xAccess() is called to check if there exists a *-wal file
222593**     associated with an RBU target database currently in RBU_STAGE_OAL
222594**     stage (preparing the *-oal file), the following special handling
222595**     applies:
222596**
222597**      * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
222598**        target database may not be in wal mode already.
222599**
222600**      * if the *-wal file does not exist, set the output parameter to
222601**        non-zero (to tell SQLite that it does exist) anyway.
222602**
222603**     Then, when xOpen() is called to open the *-wal file associated with
222604**     the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
222605**     file, the rbu vfs opens the corresponding *-oal file instead.
222606**
222607** 3b. The *-shm pages returned by xShmMap() for a target db file in
222608**     RBU_STAGE_OAL mode are actually stored in heap memory. This is to
222609**     avoid creating a *-shm file on disk. Additionally, xShmLock() calls
222610**     are no-ops on target database files in RBU_STAGE_OAL mode. This is
222611**     because assert() statements in some VFS implementations fail if
222612**     xShmLock() is called before xShmMap().
222613**
222614** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
222615**     mode except RBU_STAGE_DONE (all work completed and checkpointed), it
222616**     fails with an SQLITE_BUSY error. This is to stop RBU connections
222617**     from automatically checkpointing a *-wal (or *-oal) file from within
222618**     sqlite3_close().
222619**
222620** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
222621**     all xWrite() calls on the target database file perform no IO.
222622**     Instead the frame and page numbers that would be read and written
222623**     are recorded. Additionally, successful attempts to obtain exclusive
222624**     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
222625**     database file are recorded. xShmLock() calls to unlock the same
222626**     locks are no-ops (so that once obtained, these locks are never
222627**     relinquished). Finally, calls to xSync() on the target database
222628**     file fail with SQLITE_NOTICE errors.
222629*/
222630
222631static void rbuUnlockShm(rbu_file *p){
222632  assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
222633  if( p->pRbu ){
222634    int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
222635    int i;
222636    for(i=0; i<SQLITE_SHM_NLOCK;i++){
222637      if( (1<<i) & p->pRbu->mLock ){
222638        xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
222639      }
222640    }
222641    p->pRbu->mLock = 0;
222642  }
222643}
222644
222645/*
222646*/
222647static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
222648  sqlite3rbu *pRbu = pFd->pRbu;
222649  i64 nDiff = nNew - pFd->sz;
222650  pRbu->szTemp += nDiff;
222651  pFd->sz = nNew;
222652  assert( pRbu->szTemp>=0 );
222653  if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
222654  return SQLITE_OK;
222655}
222656
222657/*
222658** Add an item to the main-db lists, if it is not already present.
222659**
222660** There are two main-db lists. One for all file descriptors, and one
222661** for all file descriptors with rbu_file.pDb!=0. If the argument has
222662** rbu_file.pDb!=0, then it is assumed to already be present on the
222663** main list and is only added to the pDb!=0 list.
222664*/
222665static void rbuMainlistAdd(rbu_file *p){
222666  rbu_vfs *pRbuVfs = p->pRbuVfs;
222667  rbu_file *pIter;
222668  assert( (p->openFlags & SQLITE_OPEN_MAIN_DB) );
222669  sqlite3_mutex_enter(pRbuVfs->mutex);
222670  if( p->pRbu==0 ){
222671    for(pIter=pRbuVfs->pMain; pIter; pIter=pIter->pMainNext);
222672    p->pMainNext = pRbuVfs->pMain;
222673    pRbuVfs->pMain = p;
222674  }else{
222675    for(pIter=pRbuVfs->pMainRbu; pIter && pIter!=p; pIter=pIter->pMainRbuNext){}
222676    if( pIter==0 ){
222677      p->pMainRbuNext = pRbuVfs->pMainRbu;
222678      pRbuVfs->pMainRbu = p;
222679    }
222680  }
222681  sqlite3_mutex_leave(pRbuVfs->mutex);
222682}
222683
222684/*
222685** Remove an item from the main-db lists.
222686*/
222687static void rbuMainlistRemove(rbu_file *p){
222688  rbu_file **pp;
222689  sqlite3_mutex_enter(p->pRbuVfs->mutex);
222690  for(pp=&p->pRbuVfs->pMain; *pp && *pp!=p; pp=&((*pp)->pMainNext)){}
222691  if( *pp ) *pp = p->pMainNext;
222692  p->pMainNext = 0;
222693  for(pp=&p->pRbuVfs->pMainRbu; *pp && *pp!=p; pp=&((*pp)->pMainRbuNext)){}
222694  if( *pp ) *pp = p->pMainRbuNext;
222695  p->pMainRbuNext = 0;
222696  sqlite3_mutex_leave(p->pRbuVfs->mutex);
222697}
222698
222699/*
222700** Given that zWal points to a buffer containing a wal file name passed to
222701** either the xOpen() or xAccess() VFS method, search the main-db list for
222702** a file-handle opened by the same database connection on the corresponding
222703** database file.
222704**
222705** If parameter bRbu is true, only search for file-descriptors with
222706** rbu_file.pDb!=0.
222707*/
222708static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal, int bRbu){
222709  rbu_file *pDb;
222710  sqlite3_mutex_enter(pRbuVfs->mutex);
222711  if( bRbu ){
222712    for(pDb=pRbuVfs->pMainRbu; pDb && pDb->zWal!=zWal; pDb=pDb->pMainRbuNext){}
222713  }else{
222714    for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
222715  }
222716  sqlite3_mutex_leave(pRbuVfs->mutex);
222717  return pDb;
222718}
222719
222720/*
222721** Close an rbu file.
222722*/
222723static int rbuVfsClose(sqlite3_file *pFile){
222724  rbu_file *p = (rbu_file*)pFile;
222725  int rc;
222726  int i;
222727
222728  /* Free the contents of the apShm[] array. And the array itself. */
222729  for(i=0; i<p->nShm; i++){
222730    sqlite3_free(p->apShm[i]);
222731  }
222732  sqlite3_free(p->apShm);
222733  p->apShm = 0;
222734  sqlite3_free(p->zDel);
222735
222736  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
222737    const sqlite3_io_methods *pMeth = p->pReal->pMethods;
222738    rbuMainlistRemove(p);
222739    rbuUnlockShm(p);
222740    if( pMeth->iVersion>1 && pMeth->xShmUnmap ){
222741      pMeth->xShmUnmap(p->pReal, 0);
222742    }
222743  }
222744  else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
222745    rbuUpdateTempSize(p, 0);
222746  }
222747  assert( p->pMainNext==0 && p->pRbuVfs->pMain!=p );
222748
222749  /* Close the underlying file handle */
222750  rc = p->pReal->pMethods->xClose(p->pReal);
222751  return rc;
222752}
222753
222754
222755/*
222756** Read and return an unsigned 32-bit big-endian integer from the buffer
222757** passed as the only argument.
222758*/
222759static u32 rbuGetU32(u8 *aBuf){
222760  return ((u32)aBuf[0] << 24)
222761       + ((u32)aBuf[1] << 16)
222762       + ((u32)aBuf[2] <<  8)
222763       + ((u32)aBuf[3]);
222764}
222765
222766/*
222767** Write an unsigned 32-bit value in big-endian format to the supplied
222768** buffer.
222769*/
222770static void rbuPutU32(u8 *aBuf, u32 iVal){
222771  aBuf[0] = (iVal >> 24) & 0xFF;
222772  aBuf[1] = (iVal >> 16) & 0xFF;
222773  aBuf[2] = (iVal >>  8) & 0xFF;
222774  aBuf[3] = (iVal >>  0) & 0xFF;
222775}
222776
222777static void rbuPutU16(u8 *aBuf, u16 iVal){
222778  aBuf[0] = (iVal >>  8) & 0xFF;
222779  aBuf[1] = (iVal >>  0) & 0xFF;
222780}
222781
222782/*
222783** Read data from an rbuVfs-file.
222784*/
222785static int rbuVfsRead(
222786  sqlite3_file *pFile,
222787  void *zBuf,
222788  int iAmt,
222789  sqlite_int64 iOfst
222790){
222791  rbu_file *p = (rbu_file*)pFile;
222792  sqlite3rbu *pRbu = p->pRbu;
222793  int rc;
222794
222795  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
222796    assert( p->openFlags & SQLITE_OPEN_WAL );
222797    rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
222798  }else{
222799    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
222800     && (p->openFlags & SQLITE_OPEN_WAL)
222801     && iOfst>=pRbu->iOalSz
222802    ){
222803      rc = SQLITE_OK;
222804      memset(zBuf, 0, iAmt);
222805    }else{
222806      rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
222807#if 1
222808      /* If this is being called to read the first page of the target
222809      ** database as part of an rbu vacuum operation, synthesize the
222810      ** contents of the first page if it does not yet exist. Otherwise,
222811      ** SQLite will not check for a *-wal file.  */
222812      if( pRbu && rbuIsVacuum(pRbu)
222813          && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
222814          && (p->openFlags & SQLITE_OPEN_MAIN_DB)
222815          && pRbu->rc==SQLITE_OK
222816      ){
222817        sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
222818        rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
222819        if( rc==SQLITE_OK ){
222820          u8 *aBuf = (u8*)zBuf;
222821          u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
222822          rbuPutU32(&aBuf[52], iRoot);      /* largest root page number */
222823          rbuPutU32(&aBuf[36], 0);          /* number of free pages */
222824          rbuPutU32(&aBuf[32], 0);          /* first page on free list trunk */
222825          rbuPutU32(&aBuf[28], 1);          /* size of db file in pages */
222826          rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1);  /* Change counter */
222827
222828          if( iAmt>100 ){
222829            memset(&aBuf[100], 0, iAmt-100);
222830            rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
222831            aBuf[100] = 0x0D;
222832          }
222833        }
222834      }
222835#endif
222836    }
222837    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
222838      /* These look like magic numbers. But they are stable, as they are part
222839       ** of the definition of the SQLite file format, which may not change. */
222840      u8 *pBuf = (u8*)zBuf;
222841      p->iCookie = rbuGetU32(&pBuf[24]);
222842      p->iWriteVer = pBuf[19];
222843    }
222844  }
222845  return rc;
222846}
222847
222848/*
222849** Write data to an rbuVfs-file.
222850*/
222851static int rbuVfsWrite(
222852  sqlite3_file *pFile,
222853  const void *zBuf,
222854  int iAmt,
222855  sqlite_int64 iOfst
222856){
222857  rbu_file *p = (rbu_file*)pFile;
222858  sqlite3rbu *pRbu = p->pRbu;
222859  int rc;
222860
222861  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
222862    assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
222863    rc = rbuCaptureDbWrite(p->pRbu, iOfst);
222864  }else{
222865    if( pRbu ){
222866      if( pRbu->eStage==RBU_STAGE_OAL
222867       && (p->openFlags & SQLITE_OPEN_WAL)
222868       && iOfst>=pRbu->iOalSz
222869      ){
222870        pRbu->iOalSz = iAmt + iOfst;
222871      }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
222872        i64 szNew = iAmt+iOfst;
222873        if( szNew>p->sz ){
222874          rc = rbuUpdateTempSize(p, szNew);
222875          if( rc!=SQLITE_OK ) return rc;
222876        }
222877      }
222878    }
222879    rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
222880    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
222881      /* These look like magic numbers. But they are stable, as they are part
222882      ** of the definition of the SQLite file format, which may not change. */
222883      u8 *pBuf = (u8*)zBuf;
222884      p->iCookie = rbuGetU32(&pBuf[24]);
222885      p->iWriteVer = pBuf[19];
222886    }
222887  }
222888  return rc;
222889}
222890
222891/*
222892** Truncate an rbuVfs-file.
222893*/
222894static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
222895  rbu_file *p = (rbu_file*)pFile;
222896  if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
222897    int rc = rbuUpdateTempSize(p, size);
222898    if( rc!=SQLITE_OK ) return rc;
222899  }
222900  return p->pReal->pMethods->xTruncate(p->pReal, size);
222901}
222902
222903/*
222904** Sync an rbuVfs-file.
222905*/
222906static int rbuVfsSync(sqlite3_file *pFile, int flags){
222907  rbu_file *p = (rbu_file *)pFile;
222908  if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
222909    if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
222910      return SQLITE_NOTICE_RBU;
222911    }
222912    return SQLITE_OK;
222913  }
222914  return p->pReal->pMethods->xSync(p->pReal, flags);
222915}
222916
222917/*
222918** Return the current file-size of an rbuVfs-file.
222919*/
222920static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
222921  rbu_file *p = (rbu_file *)pFile;
222922  int rc;
222923  rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
222924
222925  /* If this is an RBU vacuum operation and this is the target database,
222926  ** pretend that it has at least one page. Otherwise, SQLite will not
222927  ** check for the existance of a *-wal file. rbuVfsRead() contains
222928  ** similar logic.  */
222929  if( rc==SQLITE_OK && *pSize==0
222930   && p->pRbu && rbuIsVacuum(p->pRbu)
222931   && (p->openFlags & SQLITE_OPEN_MAIN_DB)
222932  ){
222933    *pSize = 1024;
222934  }
222935  return rc;
222936}
222937
222938/*
222939** Lock an rbuVfs-file.
222940*/
222941static int rbuVfsLock(sqlite3_file *pFile, int eLock){
222942  rbu_file *p = (rbu_file*)pFile;
222943  sqlite3rbu *pRbu = p->pRbu;
222944  int rc = SQLITE_OK;
222945
222946  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
222947  if( eLock==SQLITE_LOCK_EXCLUSIVE
222948   && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
222949  ){
222950    /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
222951    ** prevents it from checkpointing the database from sqlite3_close(). */
222952    rc = SQLITE_BUSY;
222953  }else{
222954    rc = p->pReal->pMethods->xLock(p->pReal, eLock);
222955  }
222956
222957  return rc;
222958}
222959
222960/*
222961** Unlock an rbuVfs-file.
222962*/
222963static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
222964  rbu_file *p = (rbu_file *)pFile;
222965  return p->pReal->pMethods->xUnlock(p->pReal, eLock);
222966}
222967
222968/*
222969** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
222970*/
222971static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
222972  rbu_file *p = (rbu_file *)pFile;
222973  return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
222974}
222975
222976/*
222977** File control method. For custom operations on an rbuVfs-file.
222978*/
222979static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
222980  rbu_file *p = (rbu_file *)pFile;
222981  int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
222982  int rc;
222983
222984  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
222985       || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
222986  );
222987  if( op==SQLITE_FCNTL_RBU ){
222988    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
222989
222990    /* First try to find another RBU vfs lower down in the vfs stack. If
222991    ** one is found, this vfs will operate in pass-through mode. The lower
222992    ** level vfs will do the special RBU handling.  */
222993    rc = xControl(p->pReal, op, pArg);
222994
222995    if( rc==SQLITE_NOTFOUND ){
222996      /* Now search for a zipvfs instance lower down in the VFS stack. If
222997      ** one is found, this is an error.  */
222998      void *dummy = 0;
222999      rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
223000      if( rc==SQLITE_OK ){
223001        rc = SQLITE_ERROR;
223002        pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
223003      }else if( rc==SQLITE_NOTFOUND ){
223004        pRbu->pTargetFd = p;
223005        p->pRbu = pRbu;
223006        rbuMainlistAdd(p);
223007        if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
223008        rc = SQLITE_OK;
223009      }
223010    }
223011    return rc;
223012  }
223013  else if( op==SQLITE_FCNTL_RBUCNT ){
223014    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
223015    pRbu->nRbu++;
223016    pRbu->pRbuFd = p;
223017    p->bNolock = 1;
223018  }
223019
223020  rc = xControl(p->pReal, op, pArg);
223021  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
223022    rbu_vfs *pRbuVfs = p->pRbuVfs;
223023    char *zIn = *(char**)pArg;
223024    char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
223025    *(char**)pArg = zOut;
223026    if( zOut==0 ) rc = SQLITE_NOMEM;
223027  }
223028
223029  return rc;
223030}
223031
223032/*
223033** Return the sector-size in bytes for an rbuVfs-file.
223034*/
223035static int rbuVfsSectorSize(sqlite3_file *pFile){
223036  rbu_file *p = (rbu_file *)pFile;
223037  return p->pReal->pMethods->xSectorSize(p->pReal);
223038}
223039
223040/*
223041** Return the device characteristic flags supported by an rbuVfs-file.
223042*/
223043static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
223044  rbu_file *p = (rbu_file *)pFile;
223045  return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
223046}
223047
223048/*
223049** Take or release a shared-memory lock.
223050*/
223051static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
223052  rbu_file *p = (rbu_file*)pFile;
223053  sqlite3rbu *pRbu = p->pRbu;
223054  int rc = SQLITE_OK;
223055
223056#ifdef SQLITE_AMALGAMATION
223057    assert( WAL_CKPT_LOCK==1 );
223058#endif
223059
223060  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
223061  if( pRbu && (
223062       pRbu->eStage==RBU_STAGE_OAL
223063    || pRbu->eStage==RBU_STAGE_MOVE
223064    || pRbu->eStage==RBU_STAGE_DONE
223065  )){
223066    /* Prevent SQLite from taking a shm-lock on the target file when it
223067    ** is supplying heap memory to the upper layer in place of *-shm
223068    ** segments. */
223069    if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
223070  }else{
223071    int bCapture = 0;
223072    if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
223073      bCapture = 1;
223074    }
223075    if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
223076      rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
223077      if( bCapture && rc==SQLITE_OK ){
223078        pRbu->mLock |= ((1<<n) - 1) << ofst;
223079      }
223080    }
223081  }
223082
223083  return rc;
223084}
223085
223086/*
223087** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
223088*/
223089static int rbuVfsShmMap(
223090  sqlite3_file *pFile,
223091  int iRegion,
223092  int szRegion,
223093  int isWrite,
223094  void volatile **pp
223095){
223096  rbu_file *p = (rbu_file*)pFile;
223097  int rc = SQLITE_OK;
223098  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
223099
223100  /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
223101  ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
223102  ** instead of a file on disk.  */
223103  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
223104  if( eStage==RBU_STAGE_OAL ){
223105    sqlite3_int64 nByte = (iRegion+1) * sizeof(char*);
223106    char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
223107
223108    /* This is an RBU connection that uses its own heap memory for the
223109    ** pages of the *-shm file. Since no other process can have run
223110    ** recovery, the connection must request *-shm pages in order
223111    ** from start to finish.  */
223112    assert( iRegion==p->nShm );
223113    if( apNew==0 ){
223114      rc = SQLITE_NOMEM;
223115    }else{
223116      memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
223117      p->apShm = apNew;
223118      p->nShm = iRegion+1;
223119    }
223120
223121    if( rc==SQLITE_OK ){
223122      char *pNew = (char*)sqlite3_malloc64(szRegion);
223123      if( pNew==0 ){
223124        rc = SQLITE_NOMEM;
223125      }else{
223126        memset(pNew, 0, szRegion);
223127        p->apShm[iRegion] = pNew;
223128      }
223129    }
223130
223131    if( rc==SQLITE_OK ){
223132      *pp = p->apShm[iRegion];
223133    }else{
223134      *pp = 0;
223135    }
223136  }else{
223137    assert( p->apShm==0 );
223138    rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
223139  }
223140
223141  return rc;
223142}
223143
223144/*
223145** Memory barrier.
223146*/
223147static void rbuVfsShmBarrier(sqlite3_file *pFile){
223148  rbu_file *p = (rbu_file *)pFile;
223149  p->pReal->pMethods->xShmBarrier(p->pReal);
223150}
223151
223152/*
223153** The xShmUnmap method.
223154*/
223155static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
223156  rbu_file *p = (rbu_file*)pFile;
223157  int rc = SQLITE_OK;
223158  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
223159
223160  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
223161  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
223162    /* no-op */
223163  }else{
223164    /* Release the checkpointer and writer locks */
223165    rbuUnlockShm(p);
223166    rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
223167  }
223168  return rc;
223169}
223170
223171/*
223172** Open an rbu file handle.
223173*/
223174static int rbuVfsOpen(
223175  sqlite3_vfs *pVfs,
223176  const char *zName,
223177  sqlite3_file *pFile,
223178  int flags,
223179  int *pOutFlags
223180){
223181  static sqlite3_io_methods rbuvfs_io_methods = {
223182    2,                            /* iVersion */
223183    rbuVfsClose,                  /* xClose */
223184    rbuVfsRead,                   /* xRead */
223185    rbuVfsWrite,                  /* xWrite */
223186    rbuVfsTruncate,               /* xTruncate */
223187    rbuVfsSync,                   /* xSync */
223188    rbuVfsFileSize,               /* xFileSize */
223189    rbuVfsLock,                   /* xLock */
223190    rbuVfsUnlock,                 /* xUnlock */
223191    rbuVfsCheckReservedLock,      /* xCheckReservedLock */
223192    rbuVfsFileControl,            /* xFileControl */
223193    rbuVfsSectorSize,             /* xSectorSize */
223194    rbuVfsDeviceCharacteristics,  /* xDeviceCharacteristics */
223195    rbuVfsShmMap,                 /* xShmMap */
223196    rbuVfsShmLock,                /* xShmLock */
223197    rbuVfsShmBarrier,             /* xShmBarrier */
223198    rbuVfsShmUnmap,               /* xShmUnmap */
223199    0, 0                          /* xFetch, xUnfetch */
223200  };
223201  static sqlite3_io_methods rbuvfs_io_methods1 = {
223202    1,                            /* iVersion */
223203    rbuVfsClose,                  /* xClose */
223204    rbuVfsRead,                   /* xRead */
223205    rbuVfsWrite,                  /* xWrite */
223206    rbuVfsTruncate,               /* xTruncate */
223207    rbuVfsSync,                   /* xSync */
223208    rbuVfsFileSize,               /* xFileSize */
223209    rbuVfsLock,                   /* xLock */
223210    rbuVfsUnlock,                 /* xUnlock */
223211    rbuVfsCheckReservedLock,      /* xCheckReservedLock */
223212    rbuVfsFileControl,            /* xFileControl */
223213    rbuVfsSectorSize,             /* xSectorSize */
223214    rbuVfsDeviceCharacteristics,  /* xDeviceCharacteristics */
223215    0, 0, 0, 0, 0, 0
223216  };
223217
223218
223219
223220  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
223221  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
223222  rbu_file *pFd = (rbu_file *)pFile;
223223  int rc = SQLITE_OK;
223224  const char *zOpen = zName;
223225  int oflags = flags;
223226
223227  memset(pFd, 0, sizeof(rbu_file));
223228  pFd->pReal = (sqlite3_file*)&pFd[1];
223229  pFd->pRbuVfs = pRbuVfs;
223230  pFd->openFlags = flags;
223231  if( zName ){
223232    if( flags & SQLITE_OPEN_MAIN_DB ){
223233      /* A main database has just been opened. The following block sets
223234      ** (pFd->zWal) to point to a buffer owned by SQLite that contains
223235      ** the name of the *-wal file this db connection will use. SQLite
223236      ** happens to pass a pointer to this buffer when using xAccess()
223237      ** or xOpen() to operate on the *-wal file.  */
223238      pFd->zWal = sqlite3_filename_wal(zName);
223239    }
223240    else if( flags & SQLITE_OPEN_WAL ){
223241      rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName, 0);
223242      if( pDb ){
223243        if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
223244          /* This call is to open a *-wal file. Intead, open the *-oal. */
223245          size_t nOpen;
223246          if( rbuIsVacuum(pDb->pRbu) ){
223247            zOpen = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
223248            zOpen = sqlite3_filename_wal(zOpen);
223249          }
223250          nOpen = strlen(zOpen);
223251          ((char*)zOpen)[nOpen-3] = 'o';
223252          pFd->pRbu = pDb->pRbu;
223253        }
223254        pDb->pWalFd = pFd;
223255      }
223256    }
223257  }else{
223258    pFd->pRbu = pRbuVfs->pRbu;
223259  }
223260
223261  if( oflags & SQLITE_OPEN_MAIN_DB
223262   && sqlite3_uri_boolean(zName, "rbu_memory", 0)
223263  ){
223264    assert( oflags & SQLITE_OPEN_MAIN_DB );
223265    oflags =  SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
223266              SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
223267    zOpen = 0;
223268  }
223269
223270  if( rc==SQLITE_OK ){
223271    rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
223272  }
223273  if( pFd->pReal->pMethods ){
223274    const sqlite3_io_methods *pMeth = pFd->pReal->pMethods;
223275    /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
223276    ** pointer and, if the file is a main database file, link it into the
223277    ** mutex protected linked list of all such files.  */
223278    if( pMeth->iVersion<2 || pMeth->xShmLock==0 ){
223279      pFile->pMethods = &rbuvfs_io_methods1;
223280    }else{
223281      pFile->pMethods = &rbuvfs_io_methods;
223282    }
223283    if( flags & SQLITE_OPEN_MAIN_DB ){
223284      rbuMainlistAdd(pFd);
223285    }
223286  }else{
223287    sqlite3_free(pFd->zDel);
223288  }
223289
223290  return rc;
223291}
223292
223293/*
223294** Delete the file located at zPath.
223295*/
223296static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
223297  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
223298  return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
223299}
223300
223301/*
223302** Test for access permissions. Return true if the requested permission
223303** is available, or false otherwise.
223304*/
223305static int rbuVfsAccess(
223306  sqlite3_vfs *pVfs,
223307  const char *zPath,
223308  int flags,
223309  int *pResOut
223310){
223311  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
223312  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
223313  int rc;
223314
223315  rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
223316
223317  /* If this call is to check if a *-wal file associated with an RBU target
223318  ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
223319  ** the following special handling is activated:
223320  **
223321  **   a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
223322  **      ensures that the RBU extension never tries to update a database
223323  **      in wal mode, even if the first page of the database file has
223324  **      been damaged.
223325  **
223326  **   b) if the *-wal file does not exist, claim that it does anyway,
223327  **      causing SQLite to call xOpen() to open it. This call will also
223328  **      be intercepted (see the rbuVfsOpen() function) and the *-oal
223329  **      file opened instead.
223330  */
223331  if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
223332    rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath, 1);
223333    if( pDb && pDb->pRbu->eStage==RBU_STAGE_OAL ){
223334      assert( pDb->pRbu );
223335      if( *pResOut ){
223336        rc = SQLITE_CANTOPEN;
223337      }else{
223338        sqlite3_int64 sz = 0;
223339        rc = rbuVfsFileSize(&pDb->base, &sz);
223340        *pResOut = (sz>0);
223341      }
223342    }
223343  }
223344
223345  return rc;
223346}
223347
223348/*
223349** Populate buffer zOut with the full canonical pathname corresponding
223350** to the pathname in zPath. zOut is guaranteed to point to a buffer
223351** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
223352*/
223353static int rbuVfsFullPathname(
223354  sqlite3_vfs *pVfs,
223355  const char *zPath,
223356  int nOut,
223357  char *zOut
223358){
223359  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
223360  return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
223361}
223362
223363#ifndef SQLITE_OMIT_LOAD_EXTENSION
223364/*
223365** Open the dynamic library located at zPath and return a handle.
223366*/
223367static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
223368  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
223369  return pRealVfs->xDlOpen(pRealVfs, zPath);
223370}
223371
223372/*
223373** Populate the buffer zErrMsg (size nByte bytes) with a human readable
223374** utf-8 string describing the most recent error encountered associated
223375** with dynamic libraries.
223376*/
223377static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
223378  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
223379  pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
223380}
223381
223382/*
223383** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
223384*/
223385static void (*rbuVfsDlSym(
223386  sqlite3_vfs *pVfs,
223387  void *pArg,
223388  const char *zSym
223389))(void){
223390  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
223391  return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
223392}
223393
223394/*
223395** Close the dynamic library handle pHandle.
223396*/
223397static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
223398  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
223399  pRealVfs->xDlClose(pRealVfs, pHandle);
223400}
223401#endif /* SQLITE_OMIT_LOAD_EXTENSION */
223402
223403/*
223404** Populate the buffer pointed to by zBufOut with nByte bytes of
223405** random data.
223406*/
223407static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
223408  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
223409  return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
223410}
223411
223412/*
223413** Sleep for nMicro microseconds. Return the number of microseconds
223414** actually slept.
223415*/
223416static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
223417  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
223418  return pRealVfs->xSleep(pRealVfs, nMicro);
223419}
223420
223421/*
223422** Return the current time as a Julian Day number in *pTimeOut.
223423*/
223424static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
223425  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
223426  return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
223427}
223428
223429/*
223430** No-op.
223431*/
223432static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
223433  return 0;
223434}
223435
223436/*
223437** Deregister and destroy an RBU vfs created by an earlier call to
223438** sqlite3rbu_create_vfs().
223439*/
223440SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
223441  sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
223442  if( pVfs && pVfs->xOpen==rbuVfsOpen ){
223443    sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
223444    sqlite3_vfs_unregister(pVfs);
223445    sqlite3_free(pVfs);
223446  }
223447}
223448
223449/*
223450** Create an RBU VFS named zName that accesses the underlying file-system
223451** via existing VFS zParent. The new object is registered as a non-default
223452** VFS with SQLite before returning.
223453*/
223454SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
223455
223456  /* Template for VFS */
223457  static sqlite3_vfs vfs_template = {
223458    1,                            /* iVersion */
223459    0,                            /* szOsFile */
223460    0,                            /* mxPathname */
223461    0,                            /* pNext */
223462    0,                            /* zName */
223463    0,                            /* pAppData */
223464    rbuVfsOpen,                   /* xOpen */
223465    rbuVfsDelete,                 /* xDelete */
223466    rbuVfsAccess,                 /* xAccess */
223467    rbuVfsFullPathname,           /* xFullPathname */
223468
223469#ifndef SQLITE_OMIT_LOAD_EXTENSION
223470    rbuVfsDlOpen,                 /* xDlOpen */
223471    rbuVfsDlError,                /* xDlError */
223472    rbuVfsDlSym,                  /* xDlSym */
223473    rbuVfsDlClose,                /* xDlClose */
223474#else
223475    0, 0, 0, 0,
223476#endif
223477
223478    rbuVfsRandomness,             /* xRandomness */
223479    rbuVfsSleep,                  /* xSleep */
223480    rbuVfsCurrentTime,            /* xCurrentTime */
223481    rbuVfsGetLastError,           /* xGetLastError */
223482    0,                            /* xCurrentTimeInt64 (version 2) */
223483    0, 0, 0                       /* Unimplemented version 3 methods */
223484  };
223485
223486  rbu_vfs *pNew = 0;              /* Newly allocated VFS */
223487  int rc = SQLITE_OK;
223488  size_t nName;
223489  size_t nByte;
223490
223491  nName = strlen(zName);
223492  nByte = sizeof(rbu_vfs) + nName + 1;
223493  pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
223494  if( pNew==0 ){
223495    rc = SQLITE_NOMEM;
223496  }else{
223497    sqlite3_vfs *pParent;           /* Parent VFS */
223498    memset(pNew, 0, nByte);
223499    pParent = sqlite3_vfs_find(zParent);
223500    if( pParent==0 ){
223501      rc = SQLITE_NOTFOUND;
223502    }else{
223503      char *zSpace;
223504      memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
223505      pNew->base.mxPathname = pParent->mxPathname;
223506      pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
223507      pNew->pRealVfs = pParent;
223508      pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
223509      memcpy(zSpace, zName, nName);
223510
223511      /* Allocate the mutex and register the new VFS (not as the default) */
223512      pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
223513      if( pNew->mutex==0 ){
223514        rc = SQLITE_NOMEM;
223515      }else{
223516        rc = sqlite3_vfs_register(&pNew->base, 0);
223517      }
223518    }
223519
223520    if( rc!=SQLITE_OK ){
223521      sqlite3_mutex_free(pNew->mutex);
223522      sqlite3_free(pNew);
223523    }
223524  }
223525
223526  return rc;
223527}
223528
223529/*
223530** Configure the aggregate temp file size limit for this RBU handle.
223531*/
223532SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
223533  if( n>=0 ){
223534    pRbu->szTempLimit = n;
223535  }
223536  return pRbu->szTempLimit;
223537}
223538
223539SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
223540  return pRbu->szTemp;
223541}
223542
223543
223544/**************************************************************************/
223545
223546#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
223547
223548/************** End of sqlite3rbu.c ******************************************/
223549/************** Begin file dbstat.c ******************************************/
223550/*
223551** 2010 July 12
223552**
223553** The author disclaims copyright to this source code.  In place of
223554** a legal notice, here is a blessing:
223555**
223556**    May you do good and not evil.
223557**    May you find forgiveness for yourself and forgive others.
223558**    May you share freely, never taking more than you give.
223559**
223560******************************************************************************
223561**
223562** This file contains an implementation of the "dbstat" virtual table.
223563**
223564** The dbstat virtual table is used to extract low-level storage
223565** information from an SQLite database in order to implement the
223566** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
223567** for an example implementation.
223568**
223569** Additional information is available on the "dbstat.html" page of the
223570** official SQLite documentation.
223571*/
223572
223573/* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
223574#if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
223575    && !defined(SQLITE_OMIT_VIRTUALTABLE)
223576
223577/*
223578** The pager and btree modules arrange objects in memory so that there are
223579** always approximately 200 bytes of addressable memory following each page
223580** buffer. This way small buffer overreads caused by corrupt database pages
223581** do not cause undefined behaviour. This module pads each page buffer
223582** by the following number of bytes for the same purpose.
223583*/
223584#define DBSTAT_PAGE_PADDING_BYTES 256
223585
223586/*
223587** Page paths:
223588**
223589**   The value of the 'path' column describes the path taken from the
223590**   root-node of the b-tree structure to each page. The value of the
223591**   root-node path is '/'.
223592**
223593**   The value of the path for the left-most child page of the root of
223594**   a b-tree is '/000/'. (Btrees store content ordered from left to right
223595**   so the pages to the left have smaller keys than the pages to the right.)
223596**   The next to left-most child of the root page is
223597**   '/001', and so on, each sibling page identified by a 3-digit hex
223598**   value. The children of the 451st left-most sibling have paths such
223599**   as '/1c2/000/, '/1c2/001/' etc.
223600**
223601**   Overflow pages are specified by appending a '+' character and a
223602**   six-digit hexadecimal value to the path to the cell they are linked
223603**   from. For example, the three overflow pages in a chain linked from
223604**   the left-most cell of the 450th child of the root page are identified
223605**   by the paths:
223606**
223607**      '/1c2/000+000000'         // First page in overflow chain
223608**      '/1c2/000+000001'         // Second page in overflow chain
223609**      '/1c2/000+000002'         // Third page in overflow chain
223610**
223611**   If the paths are sorted using the BINARY collation sequence, then
223612**   the overflow pages associated with a cell will appear earlier in the
223613**   sort-order than its child page:
223614**
223615**      '/1c2/000/'               // Left-most child of 451st child of root
223616*/
223617static const char zDbstatSchema[] =
223618  "CREATE TABLE x("
223619  " name       TEXT,"          /*  0 Name of table or index */
223620  " path       TEXT,"          /*  1 Path to page from root (NULL for agg) */
223621  " pageno     INTEGER,"       /*  2 Page number (page count for aggregates) */
223622  " pagetype   TEXT,"          /*  3 'internal', 'leaf', 'overflow', or NULL */
223623  " ncell      INTEGER,"       /*  4 Cells on page (0 for overflow) */
223624  " payload    INTEGER,"       /*  5 Bytes of payload on this page */
223625  " unused     INTEGER,"       /*  6 Bytes of unused space on this page */
223626  " mx_payload INTEGER,"       /*  7 Largest payload size of all cells */
223627  " pgoffset   INTEGER,"       /*  8 Offset of page in file (NULL for agg) */
223628  " pgsize     INTEGER,"       /*  9 Size of the page (sum for aggregate) */
223629  " schema     TEXT HIDDEN,"   /* 10 Database schema being analyzed */
223630  " aggregate  BOOLEAN HIDDEN" /* 11 aggregate info for each table */
223631  ")"
223632;
223633
223634/* Forward reference to data structured used in this module */
223635typedef struct StatTable StatTable;
223636typedef struct StatCursor StatCursor;
223637typedef struct StatPage StatPage;
223638typedef struct StatCell StatCell;
223639
223640/* Size information for a single cell within a btree page */
223641struct StatCell {
223642  int nLocal;                     /* Bytes of local payload */
223643  u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
223644  int nOvfl;                      /* Entries in aOvfl[] */
223645  u32 *aOvfl;                     /* Array of overflow page numbers */
223646  int nLastOvfl;                  /* Bytes of payload on final overflow page */
223647  int iOvfl;                      /* Iterates through aOvfl[] */
223648};
223649
223650/* Size information for a single btree page */
223651struct StatPage {
223652  u32 iPgno;                      /* Page number */
223653  u8 *aPg;                        /* Page buffer from sqlite3_malloc() */
223654  int iCell;                      /* Current cell */
223655  char *zPath;                    /* Path to this page */
223656
223657  /* Variables populated by statDecodePage(): */
223658  u8 flags;                       /* Copy of flags byte */
223659  int nCell;                      /* Number of cells on page */
223660  int nUnused;                    /* Number of unused bytes on page */
223661  StatCell *aCell;                /* Array of parsed cells */
223662  u32 iRightChildPg;              /* Right-child page number (or 0) */
223663  int nMxPayload;                 /* Largest payload of any cell on the page */
223664};
223665
223666/* The cursor for scanning the dbstat virtual table */
223667struct StatCursor {
223668  sqlite3_vtab_cursor base;       /* base class.  MUST BE FIRST! */
223669  sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
223670  u8 isEof;                       /* After pStmt has returned SQLITE_DONE */
223671  u8 isAgg;                       /* Aggregate results for each table */
223672  int iDb;                        /* Schema used for this query */
223673
223674  StatPage aPage[32];             /* Pages in path to current page */
223675  int iPage;                      /* Current entry in aPage[] */
223676
223677  /* Values to return. */
223678  u32 iPageno;                    /* Value of 'pageno' column */
223679  char *zName;                    /* Value of 'name' column */
223680  char *zPath;                    /* Value of 'path' column */
223681  char *zPagetype;                /* Value of 'pagetype' column */
223682  int nPage;                      /* Number of pages in current btree */
223683  int nCell;                      /* Value of 'ncell' column */
223684  int nMxPayload;                 /* Value of 'mx_payload' column */
223685  i64 nUnused;                    /* Value of 'unused' column */
223686  i64 nPayload;                   /* Value of 'payload' column */
223687  i64 iOffset;                    /* Value of 'pgOffset' column */
223688  i64 szPage;                     /* Value of 'pgSize' column */
223689};
223690
223691/* An instance of the DBSTAT virtual table */
223692struct StatTable {
223693  sqlite3_vtab base;              /* base class.  MUST BE FIRST! */
223694  sqlite3 *db;                    /* Database connection that owns this vtab */
223695  int iDb;                        /* Index of database to analyze */
223696};
223697
223698#ifndef get2byte
223699# define get2byte(x)   ((x)[0]<<8 | (x)[1])
223700#endif
223701
223702/*
223703** Connect to or create a new DBSTAT virtual table.
223704*/
223705static int statConnect(
223706  sqlite3 *db,
223707  void *pAux,
223708  int argc, const char *const*argv,
223709  sqlite3_vtab **ppVtab,
223710  char **pzErr
223711){
223712  StatTable *pTab = 0;
223713  int rc = SQLITE_OK;
223714  int iDb;
223715  (void)pAux;
223716
223717  if( argc>=4 ){
223718    Token nm;
223719    sqlite3TokenInit(&nm, (char*)argv[3]);
223720    iDb = sqlite3FindDb(db, &nm);
223721    if( iDb<0 ){
223722      *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
223723      return SQLITE_ERROR;
223724    }
223725  }else{
223726    iDb = 0;
223727  }
223728  sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
223729  rc = sqlite3_declare_vtab(db, zDbstatSchema);
223730  if( rc==SQLITE_OK ){
223731    pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
223732    if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
223733  }
223734
223735  assert( rc==SQLITE_OK || pTab==0 );
223736  if( rc==SQLITE_OK ){
223737    memset(pTab, 0, sizeof(StatTable));
223738    pTab->db = db;
223739    pTab->iDb = iDb;
223740  }
223741
223742  *ppVtab = (sqlite3_vtab*)pTab;
223743  return rc;
223744}
223745
223746/*
223747** Disconnect from or destroy the DBSTAT virtual table.
223748*/
223749static int statDisconnect(sqlite3_vtab *pVtab){
223750  sqlite3_free(pVtab);
223751  return SQLITE_OK;
223752}
223753
223754/*
223755** Compute the best query strategy and return the result in idxNum.
223756**
223757**   idxNum-Bit        Meaning
223758**   ----------        ----------------------------------------------
223759**      0x01           There is a schema=? term in the WHERE clause
223760**      0x02           There is a name=? term in the WHERE clause
223761**      0x04           There is an aggregate=? term in the WHERE clause
223762**      0x08           Output should be ordered by name and path
223763*/
223764static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
223765  int i;
223766  int iSchema = -1;
223767  int iName = -1;
223768  int iAgg = -1;
223769  (void)tab;
223770
223771  /* Look for a valid schema=? constraint.  If found, change the idxNum to
223772  ** 1 and request the value of that constraint be sent to xFilter.  And
223773  ** lower the cost estimate to encourage the constrained version to be
223774  ** used.
223775  */
223776  for(i=0; i<pIdxInfo->nConstraint; i++){
223777    if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
223778    if( pIdxInfo->aConstraint[i].usable==0 ){
223779      /* Force DBSTAT table should always be the right-most table in a join */
223780      return SQLITE_CONSTRAINT;
223781    }
223782    switch( pIdxInfo->aConstraint[i].iColumn ){
223783      case 0: {    /* name */
223784        iName = i;
223785        break;
223786      }
223787      case 10: {   /* schema */
223788        iSchema = i;
223789        break;
223790      }
223791      case 11: {   /* aggregate */
223792        iAgg = i;
223793        break;
223794      }
223795    }
223796  }
223797  i = 0;
223798  if( iSchema>=0 ){
223799    pIdxInfo->aConstraintUsage[iSchema].argvIndex = ++i;
223800    pIdxInfo->aConstraintUsage[iSchema].omit = 1;
223801    pIdxInfo->idxNum |= 0x01;
223802  }
223803  if( iName>=0 ){
223804    pIdxInfo->aConstraintUsage[iName].argvIndex = ++i;
223805    pIdxInfo->idxNum |= 0x02;
223806  }
223807  if( iAgg>=0 ){
223808    pIdxInfo->aConstraintUsage[iAgg].argvIndex = ++i;
223809    pIdxInfo->idxNum |= 0x04;
223810  }
223811  pIdxInfo->estimatedCost = 1.0;
223812
223813  /* Records are always returned in ascending order of (name, path).
223814  ** If this will satisfy the client, set the orderByConsumed flag so that
223815  ** SQLite does not do an external sort.
223816  */
223817  if( ( pIdxInfo->nOrderBy==1
223818     && pIdxInfo->aOrderBy[0].iColumn==0
223819     && pIdxInfo->aOrderBy[0].desc==0
223820     ) ||
223821      ( pIdxInfo->nOrderBy==2
223822     && pIdxInfo->aOrderBy[0].iColumn==0
223823     && pIdxInfo->aOrderBy[0].desc==0
223824     && pIdxInfo->aOrderBy[1].iColumn==1
223825     && pIdxInfo->aOrderBy[1].desc==0
223826     )
223827  ){
223828    pIdxInfo->orderByConsumed = 1;
223829    pIdxInfo->idxNum |= 0x08;
223830  }
223831
223832  return SQLITE_OK;
223833}
223834
223835/*
223836** Open a new DBSTAT cursor.
223837*/
223838static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
223839  StatTable *pTab = (StatTable *)pVTab;
223840  StatCursor *pCsr;
223841
223842  pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
223843  if( pCsr==0 ){
223844    return SQLITE_NOMEM_BKPT;
223845  }else{
223846    memset(pCsr, 0, sizeof(StatCursor));
223847    pCsr->base.pVtab = pVTab;
223848    pCsr->iDb = pTab->iDb;
223849  }
223850
223851  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
223852  return SQLITE_OK;
223853}
223854
223855static void statClearCells(StatPage *p){
223856  int i;
223857  if( p->aCell ){
223858    for(i=0; i<p->nCell; i++){
223859      sqlite3_free(p->aCell[i].aOvfl);
223860    }
223861    sqlite3_free(p->aCell);
223862  }
223863  p->nCell = 0;
223864  p->aCell = 0;
223865}
223866
223867static void statClearPage(StatPage *p){
223868  u8 *aPg = p->aPg;
223869  statClearCells(p);
223870  sqlite3_free(p->zPath);
223871  memset(p, 0, sizeof(StatPage));
223872  p->aPg = aPg;
223873}
223874
223875static void statResetCsr(StatCursor *pCsr){
223876  int i;
223877  /* In some circumstances, specifically if an OOM has occurred, the call
223878  ** to sqlite3_reset() may cause the pager to be reset (emptied). It is
223879  ** important that statClearPage() is called to free any page refs before
223880  ** this happens. dbsqlfuzz 9ed3e4e3816219d3509d711636c38542bf3f40b1. */
223881  for(i=0; i<ArraySize(pCsr->aPage); i++){
223882    statClearPage(&pCsr->aPage[i]);
223883    sqlite3_free(pCsr->aPage[i].aPg);
223884    pCsr->aPage[i].aPg = 0;
223885  }
223886  sqlite3_reset(pCsr->pStmt);
223887  pCsr->iPage = 0;
223888  sqlite3_free(pCsr->zPath);
223889  pCsr->zPath = 0;
223890  pCsr->isEof = 0;
223891}
223892
223893/* Resize the space-used counters inside of the cursor */
223894static void statResetCounts(StatCursor *pCsr){
223895  pCsr->nCell = 0;
223896  pCsr->nMxPayload = 0;
223897  pCsr->nUnused = 0;
223898  pCsr->nPayload = 0;
223899  pCsr->szPage = 0;
223900  pCsr->nPage = 0;
223901}
223902
223903/*
223904** Close a DBSTAT cursor.
223905*/
223906static int statClose(sqlite3_vtab_cursor *pCursor){
223907  StatCursor *pCsr = (StatCursor *)pCursor;
223908  statResetCsr(pCsr);
223909  sqlite3_finalize(pCsr->pStmt);
223910  sqlite3_free(pCsr);
223911  return SQLITE_OK;
223912}
223913
223914/*
223915** For a single cell on a btree page, compute the number of bytes of
223916** content (payload) stored on that page.  That is to say, compute the
223917** number of bytes of content not found on overflow pages.
223918*/
223919static int getLocalPayload(
223920  int nUsable,                    /* Usable bytes per page */
223921  u8 flags,                       /* Page flags */
223922  int nTotal                      /* Total record (payload) size */
223923){
223924  int nLocal;
223925  int nMinLocal;
223926  int nMaxLocal;
223927
223928  if( flags==0x0D ){              /* Table leaf node */
223929    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
223930    nMaxLocal = nUsable - 35;
223931  }else{                          /* Index interior and leaf nodes */
223932    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
223933    nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
223934  }
223935
223936  nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
223937  if( nLocal>nMaxLocal ) nLocal = nMinLocal;
223938  return nLocal;
223939}
223940
223941/* Populate the StatPage object with information about the all
223942** cells found on the page currently under analysis.
223943*/
223944static int statDecodePage(Btree *pBt, StatPage *p){
223945  int nUnused;
223946  int iOff;
223947  int nHdr;
223948  int isLeaf;
223949  int szPage;
223950
223951  u8 *aData = p->aPg;
223952  u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
223953
223954  p->flags = aHdr[0];
223955  if( p->flags==0x0A || p->flags==0x0D ){
223956    isLeaf = 1;
223957    nHdr = 8;
223958  }else if( p->flags==0x05 || p->flags==0x02 ){
223959    isLeaf = 0;
223960    nHdr = 12;
223961  }else{
223962    goto statPageIsCorrupt;
223963  }
223964  if( p->iPgno==1 ) nHdr += 100;
223965  p->nCell = get2byte(&aHdr[3]);
223966  p->nMxPayload = 0;
223967  szPage = sqlite3BtreeGetPageSize(pBt);
223968
223969  nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
223970  nUnused += (int)aHdr[7];
223971  iOff = get2byte(&aHdr[1]);
223972  while( iOff ){
223973    int iNext;
223974    if( iOff>=szPage ) goto statPageIsCorrupt;
223975    nUnused += get2byte(&aData[iOff+2]);
223976    iNext = get2byte(&aData[iOff]);
223977    if( iNext<iOff+4 && iNext>0 ) goto statPageIsCorrupt;
223978    iOff = iNext;
223979  }
223980  p->nUnused = nUnused;
223981  p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
223982
223983  if( p->nCell ){
223984    int i;                        /* Used to iterate through cells */
223985    int nUsable;                  /* Usable bytes per page */
223986
223987    sqlite3BtreeEnter(pBt);
223988    nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
223989    sqlite3BtreeLeave(pBt);
223990    p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
223991    if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
223992    memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
223993
223994    for(i=0; i<p->nCell; i++){
223995      StatCell *pCell = &p->aCell[i];
223996
223997      iOff = get2byte(&aData[nHdr+i*2]);
223998      if( iOff<nHdr || iOff>=szPage ) goto statPageIsCorrupt;
223999      if( !isLeaf ){
224000        pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
224001        iOff += 4;
224002      }
224003      if( p->flags==0x05 ){
224004        /* A table interior node. nPayload==0. */
224005      }else{
224006        u32 nPayload;             /* Bytes of payload total (local+overflow) */
224007        int nLocal;               /* Bytes of payload stored locally */
224008        iOff += getVarint32(&aData[iOff], nPayload);
224009        if( p->flags==0x0D ){
224010          u64 dummy;
224011          iOff += sqlite3GetVarint(&aData[iOff], &dummy);
224012        }
224013        if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
224014        nLocal = getLocalPayload(nUsable, p->flags, nPayload);
224015        if( nLocal<0 ) goto statPageIsCorrupt;
224016        pCell->nLocal = nLocal;
224017        assert( nPayload>=(u32)nLocal );
224018        assert( nLocal<=(nUsable-35) );
224019        if( nPayload>(u32)nLocal ){
224020          int j;
224021          int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
224022          if( iOff+nLocal+4>nUsable || nPayload>0x7fffffff ){
224023            goto statPageIsCorrupt;
224024          }
224025          pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
224026          pCell->nOvfl = nOvfl;
224027          pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
224028          if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
224029          pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
224030          for(j=1; j<nOvfl; j++){
224031            int rc;
224032            u32 iPrev = pCell->aOvfl[j-1];
224033            DbPage *pPg = 0;
224034            rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
224035            if( rc!=SQLITE_OK ){
224036              assert( pPg==0 );
224037              return rc;
224038            }
224039            pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
224040            sqlite3PagerUnref(pPg);
224041          }
224042        }
224043      }
224044    }
224045  }
224046
224047  return SQLITE_OK;
224048
224049statPageIsCorrupt:
224050  p->flags = 0;
224051  statClearCells(p);
224052  return SQLITE_OK;
224053}
224054
224055/*
224056** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
224057** the current value of pCsr->iPageno.
224058*/
224059static void statSizeAndOffset(StatCursor *pCsr){
224060  StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
224061  Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
224062  Pager *pPager = sqlite3BtreePager(pBt);
224063  sqlite3_file *fd;
224064  sqlite3_int64 x[2];
224065
224066  /* If connected to a ZIPVFS backend, find the page size and
224067  ** offset from ZIPVFS.
224068  */
224069  fd = sqlite3PagerFile(pPager);
224070  x[0] = pCsr->iPageno;
224071  if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
224072    pCsr->iOffset = x[0];
224073    pCsr->szPage += x[1];
224074  }else{
224075    /* Not ZIPVFS: The default page size and offset */
224076    pCsr->szPage += sqlite3BtreeGetPageSize(pBt);
224077    pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
224078  }
224079}
224080
224081/*
224082** Load a copy of the page data for page iPg into the buffer belonging
224083** to page object pPg. Allocate the buffer if necessary. Return SQLITE_OK
224084** if successful, or an SQLite error code otherwise.
224085*/
224086static int statGetPage(
224087  Btree *pBt,                     /* Load page from this b-tree */
224088  u32 iPg,                        /* Page number to load */
224089  StatPage *pPg                   /* Load page into this object */
224090){
224091  int pgsz = sqlite3BtreeGetPageSize(pBt);
224092  DbPage *pDbPage = 0;
224093  int rc;
224094
224095  if( pPg->aPg==0 ){
224096    pPg->aPg = (u8*)sqlite3_malloc(pgsz + DBSTAT_PAGE_PADDING_BYTES);
224097    if( pPg->aPg==0 ){
224098      return SQLITE_NOMEM_BKPT;
224099    }
224100    memset(&pPg->aPg[pgsz], 0, DBSTAT_PAGE_PADDING_BYTES);
224101  }
224102
224103  rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPg, &pDbPage, 0);
224104  if( rc==SQLITE_OK ){
224105    const u8 *a = sqlite3PagerGetData(pDbPage);
224106    memcpy(pPg->aPg, a, pgsz);
224107    sqlite3PagerUnref(pDbPage);
224108  }
224109
224110  return rc;
224111}
224112
224113/*
224114** Move a DBSTAT cursor to the next entry.  Normally, the next
224115** entry will be the next page, but in aggregated mode (pCsr->isAgg!=0),
224116** the next entry is the next btree.
224117*/
224118static int statNext(sqlite3_vtab_cursor *pCursor){
224119  int rc;
224120  int nPayload;
224121  char *z;
224122  StatCursor *pCsr = (StatCursor *)pCursor;
224123  StatTable *pTab = (StatTable *)pCursor->pVtab;
224124  Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
224125  Pager *pPager = sqlite3BtreePager(pBt);
224126
224127  sqlite3_free(pCsr->zPath);
224128  pCsr->zPath = 0;
224129
224130statNextRestart:
224131  if( pCsr->iPage<0 ){
224132    /* Start measuring space on the next btree */
224133    statResetCounts(pCsr);
224134    rc = sqlite3_step(pCsr->pStmt);
224135    if( rc==SQLITE_ROW ){
224136      int nPage;
224137      u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
224138      sqlite3PagerPagecount(pPager, &nPage);
224139      if( nPage==0 ){
224140        pCsr->isEof = 1;
224141        return sqlite3_reset(pCsr->pStmt);
224142      }
224143      rc = statGetPage(pBt, iRoot, &pCsr->aPage[0]);
224144      pCsr->aPage[0].iPgno = iRoot;
224145      pCsr->aPage[0].iCell = 0;
224146      if( !pCsr->isAgg ){
224147        pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
224148        if( z==0 ) rc = SQLITE_NOMEM_BKPT;
224149      }
224150      pCsr->iPage = 0;
224151      pCsr->nPage = 1;
224152    }else{
224153      pCsr->isEof = 1;
224154      return sqlite3_reset(pCsr->pStmt);
224155    }
224156  }else{
224157    /* Continue analyzing the btree previously started */
224158    StatPage *p = &pCsr->aPage[pCsr->iPage];
224159    if( !pCsr->isAgg ) statResetCounts(pCsr);
224160    while( p->iCell<p->nCell ){
224161      StatCell *pCell = &p->aCell[p->iCell];
224162      while( pCell->iOvfl<pCell->nOvfl ){
224163        int nUsable, iOvfl;
224164        sqlite3BtreeEnter(pBt);
224165        nUsable = sqlite3BtreeGetPageSize(pBt) -
224166                        sqlite3BtreeGetReserveNoMutex(pBt);
224167        sqlite3BtreeLeave(pBt);
224168        pCsr->nPage++;
224169        statSizeAndOffset(pCsr);
224170        if( pCell->iOvfl<pCell->nOvfl-1 ){
224171          pCsr->nPayload += nUsable - 4;
224172        }else{
224173          pCsr->nPayload += pCell->nLastOvfl;
224174          pCsr->nUnused += nUsable - 4 - pCell->nLastOvfl;
224175        }
224176        iOvfl = pCell->iOvfl;
224177        pCell->iOvfl++;
224178        if( !pCsr->isAgg ){
224179          pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
224180          pCsr->iPageno = pCell->aOvfl[iOvfl];
224181          pCsr->zPagetype = "overflow";
224182          pCsr->zPath = z = sqlite3_mprintf(
224183              "%s%.3x+%.6x", p->zPath, p->iCell, iOvfl
224184          );
224185          return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
224186        }
224187      }
224188      if( p->iRightChildPg ) break;
224189      p->iCell++;
224190    }
224191
224192    if( !p->iRightChildPg || p->iCell>p->nCell ){
224193      statClearPage(p);
224194      pCsr->iPage--;
224195      if( pCsr->isAgg && pCsr->iPage<0 ){
224196        /* label-statNext-done:  When computing aggregate space usage over
224197        ** an entire btree, this is the exit point from this function */
224198        return SQLITE_OK;
224199      }
224200      goto statNextRestart; /* Tail recursion */
224201    }
224202    pCsr->iPage++;
224203    if( pCsr->iPage>=ArraySize(pCsr->aPage) ){
224204      statResetCsr(pCsr);
224205      return SQLITE_CORRUPT_BKPT;
224206    }
224207    assert( p==&pCsr->aPage[pCsr->iPage-1] );
224208
224209    if( p->iCell==p->nCell ){
224210      p[1].iPgno = p->iRightChildPg;
224211    }else{
224212      p[1].iPgno = p->aCell[p->iCell].iChildPg;
224213    }
224214    rc = statGetPage(pBt, p[1].iPgno, &p[1]);
224215    pCsr->nPage++;
224216    p[1].iCell = 0;
224217    if( !pCsr->isAgg ){
224218      p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
224219      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
224220    }
224221    p->iCell++;
224222  }
224223
224224
224225  /* Populate the StatCursor fields with the values to be returned
224226  ** by the xColumn() and xRowid() methods.
224227  */
224228  if( rc==SQLITE_OK ){
224229    int i;
224230    StatPage *p = &pCsr->aPage[pCsr->iPage];
224231    pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
224232    pCsr->iPageno = p->iPgno;
224233
224234    rc = statDecodePage(pBt, p);
224235    if( rc==SQLITE_OK ){
224236      statSizeAndOffset(pCsr);
224237
224238      switch( p->flags ){
224239        case 0x05:             /* table internal */
224240        case 0x02:             /* index internal */
224241          pCsr->zPagetype = "internal";
224242          break;
224243        case 0x0D:             /* table leaf */
224244        case 0x0A:             /* index leaf */
224245          pCsr->zPagetype = "leaf";
224246          break;
224247        default:
224248          pCsr->zPagetype = "corrupted";
224249          break;
224250      }
224251      pCsr->nCell += p->nCell;
224252      pCsr->nUnused += p->nUnused;
224253      if( p->nMxPayload>pCsr->nMxPayload ) pCsr->nMxPayload = p->nMxPayload;
224254      if( !pCsr->isAgg ){
224255        pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
224256        if( z==0 ) rc = SQLITE_NOMEM_BKPT;
224257      }
224258      nPayload = 0;
224259      for(i=0; i<p->nCell; i++){
224260        nPayload += p->aCell[i].nLocal;
224261      }
224262      pCsr->nPayload += nPayload;
224263
224264      /* If computing aggregate space usage by btree, continue with the
224265      ** next page.  The loop will exit via the return at label-statNext-done
224266      */
224267      if( pCsr->isAgg ) goto statNextRestart;
224268    }
224269  }
224270
224271  return rc;
224272}
224273
224274static int statEof(sqlite3_vtab_cursor *pCursor){
224275  StatCursor *pCsr = (StatCursor *)pCursor;
224276  return pCsr->isEof;
224277}
224278
224279/* Initialize a cursor according to the query plan idxNum using the
224280** arguments in argv[0].  See statBestIndex() for a description of the
224281** meaning of the bits in idxNum.
224282*/
224283static int statFilter(
224284  sqlite3_vtab_cursor *pCursor,
224285  int idxNum, const char *idxStr,
224286  int argc, sqlite3_value **argv
224287){
224288  StatCursor *pCsr = (StatCursor *)pCursor;
224289  StatTable *pTab = (StatTable*)(pCursor->pVtab);
224290  sqlite3_str *pSql;      /* Query of btrees to analyze */
224291  char *zSql;             /* String value of pSql */
224292  int iArg = 0;           /* Count of argv[] parameters used so far */
224293  int rc = SQLITE_OK;     /* Result of this operation */
224294  const char *zName = 0;  /* Only provide analysis of this table */
224295  (void)argc;
224296  (void)idxStr;
224297
224298  statResetCsr(pCsr);
224299  sqlite3_finalize(pCsr->pStmt);
224300  pCsr->pStmt = 0;
224301  if( idxNum & 0x01 ){
224302    /* schema=? constraint is present.  Get its value */
224303    const char *zDbase = (const char*)sqlite3_value_text(argv[iArg++]);
224304    pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
224305    if( pCsr->iDb<0 ){
224306      pCsr->iDb = 0;
224307      pCsr->isEof = 1;
224308      return SQLITE_OK;
224309    }
224310  }else{
224311    pCsr->iDb = pTab->iDb;
224312  }
224313  if( idxNum & 0x02 ){
224314    /* name=? constraint is present */
224315    zName = (const char*)sqlite3_value_text(argv[iArg++]);
224316  }
224317  if( idxNum & 0x04 ){
224318    /* aggregate=? constraint is present */
224319    pCsr->isAgg = sqlite3_value_double(argv[iArg++])!=0.0;
224320  }else{
224321    pCsr->isAgg = 0;
224322  }
224323  pSql = sqlite3_str_new(pTab->db);
224324  sqlite3_str_appendf(pSql,
224325      "SELECT * FROM ("
224326        "SELECT 'sqlite_schema' AS name,1 AS rootpage,'table' AS type"
224327        " UNION ALL "
224328        "SELECT name,rootpage,type"
224329        " FROM \"%w\".sqlite_schema WHERE rootpage!=0)",
224330      pTab->db->aDb[pCsr->iDb].zDbSName);
224331  if( zName ){
224332    sqlite3_str_appendf(pSql, "WHERE name=%Q", zName);
224333  }
224334  if( idxNum & 0x08 ){
224335    sqlite3_str_appendf(pSql, " ORDER BY name");
224336  }
224337  zSql = sqlite3_str_finish(pSql);
224338  if( zSql==0 ){
224339    return SQLITE_NOMEM_BKPT;
224340  }else{
224341    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
224342    sqlite3_free(zSql);
224343  }
224344
224345  if( rc==SQLITE_OK ){
224346    pCsr->iPage = -1;
224347    rc = statNext(pCursor);
224348  }
224349  return rc;
224350}
224351
224352static int statColumn(
224353  sqlite3_vtab_cursor *pCursor,
224354  sqlite3_context *ctx,
224355  int i
224356){
224357  StatCursor *pCsr = (StatCursor *)pCursor;
224358  switch( i ){
224359    case 0:            /* name */
224360      sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
224361      break;
224362    case 1:            /* path */
224363      if( !pCsr->isAgg ){
224364        sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
224365      }
224366      break;
224367    case 2:            /* pageno */
224368      if( pCsr->isAgg ){
224369        sqlite3_result_int64(ctx, pCsr->nPage);
224370      }else{
224371        sqlite3_result_int64(ctx, pCsr->iPageno);
224372      }
224373      break;
224374    case 3:            /* pagetype */
224375      if( !pCsr->isAgg ){
224376        sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
224377      }
224378      break;
224379    case 4:            /* ncell */
224380      sqlite3_result_int64(ctx, pCsr->nCell);
224381      break;
224382    case 5:            /* payload */
224383      sqlite3_result_int64(ctx, pCsr->nPayload);
224384      break;
224385    case 6:            /* unused */
224386      sqlite3_result_int64(ctx, pCsr->nUnused);
224387      break;
224388    case 7:            /* mx_payload */
224389      sqlite3_result_int64(ctx, pCsr->nMxPayload);
224390      break;
224391    case 8:            /* pgoffset */
224392      if( !pCsr->isAgg ){
224393        sqlite3_result_int64(ctx, pCsr->iOffset);
224394      }
224395      break;
224396    case 9:            /* pgsize */
224397      sqlite3_result_int64(ctx, pCsr->szPage);
224398      break;
224399    case 10: {         /* schema */
224400      sqlite3 *db = sqlite3_context_db_handle(ctx);
224401      int iDb = pCsr->iDb;
224402      sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
224403      break;
224404    }
224405    default: {         /* aggregate */
224406      sqlite3_result_int(ctx, pCsr->isAgg);
224407      break;
224408    }
224409  }
224410  return SQLITE_OK;
224411}
224412
224413static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
224414  StatCursor *pCsr = (StatCursor *)pCursor;
224415  *pRowid = pCsr->iPageno;
224416  return SQLITE_OK;
224417}
224418
224419/*
224420** Invoke this routine to register the "dbstat" virtual table module
224421*/
224422SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
224423  static sqlite3_module dbstat_module = {
224424    0,                            /* iVersion */
224425    statConnect,                  /* xCreate */
224426    statConnect,                  /* xConnect */
224427    statBestIndex,                /* xBestIndex */
224428    statDisconnect,               /* xDisconnect */
224429    statDisconnect,               /* xDestroy */
224430    statOpen,                     /* xOpen - open a cursor */
224431    statClose,                    /* xClose - close a cursor */
224432    statFilter,                   /* xFilter - configure scan constraints */
224433    statNext,                     /* xNext - advance a cursor */
224434    statEof,                      /* xEof - check for end of scan */
224435    statColumn,                   /* xColumn - read data */
224436    statRowid,                    /* xRowid - read data */
224437    0,                            /* xUpdate */
224438    0,                            /* xBegin */
224439    0,                            /* xSync */
224440    0,                            /* xCommit */
224441    0,                            /* xRollback */
224442    0,                            /* xFindMethod */
224443    0,                            /* xRename */
224444    0,                            /* xSavepoint */
224445    0,                            /* xRelease */
224446    0,                            /* xRollbackTo */
224447    0,                            /* xShadowName */
224448    0                             /* xIntegrity */
224449  };
224450  return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
224451}
224452#elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
224453SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
224454#endif /* SQLITE_ENABLE_DBSTAT_VTAB */
224455
224456/************** End of dbstat.c **********************************************/
224457/************** Begin file dbpage.c ******************************************/
224458/*
224459** 2017-10-11
224460**
224461** The author disclaims copyright to this source code.  In place of
224462** a legal notice, here is a blessing:
224463**
224464**    May you do good and not evil.
224465**    May you find forgiveness for yourself and forgive others.
224466**    May you share freely, never taking more than you give.
224467**
224468******************************************************************************
224469**
224470** This file contains an implementation of the "sqlite_dbpage" virtual table.
224471**
224472** The sqlite_dbpage virtual table is used to read or write whole raw
224473** pages of the database file.  The pager interface is used so that
224474** uncommitted changes and changes recorded in the WAL file are correctly
224475** retrieved.
224476**
224477** Usage example:
224478**
224479**    SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;
224480**
224481** This is an eponymous virtual table so it does not need to be created before
224482** use.  The optional argument to the sqlite_dbpage() table name is the
224483** schema for the database file that is to be read.  The default schema is
224484** "main".
224485**
224486** The data field of sqlite_dbpage table can be updated.  The new
224487** value must be a BLOB which is the correct page size, otherwise the
224488** update fails.  Rows may not be deleted or inserted.
224489*/
224490
224491/* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
224492#if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
224493    && !defined(SQLITE_OMIT_VIRTUALTABLE)
224494
224495typedef struct DbpageTable DbpageTable;
224496typedef struct DbpageCursor DbpageCursor;
224497
224498struct DbpageCursor {
224499  sqlite3_vtab_cursor base;       /* Base class.  Must be first */
224500  int pgno;                       /* Current page number */
224501  int mxPgno;                     /* Last page to visit on this scan */
224502  Pager *pPager;                  /* Pager being read/written */
224503  DbPage *pPage1;                 /* Page 1 of the database */
224504  int iDb;                        /* Index of database to analyze */
224505  int szPage;                     /* Size of each page in bytes */
224506};
224507
224508struct DbpageTable {
224509  sqlite3_vtab base;              /* Base class.  Must be first */
224510  sqlite3 *db;                    /* The database */
224511};
224512
224513/* Columns */
224514#define DBPAGE_COLUMN_PGNO    0
224515#define DBPAGE_COLUMN_DATA    1
224516#define DBPAGE_COLUMN_SCHEMA  2
224517
224518
224519
224520/*
224521** Connect to or create a dbpagevfs virtual table.
224522*/
224523static int dbpageConnect(
224524  sqlite3 *db,
224525  void *pAux,
224526  int argc, const char *const*argv,
224527  sqlite3_vtab **ppVtab,
224528  char **pzErr
224529){
224530  DbpageTable *pTab = 0;
224531  int rc = SQLITE_OK;
224532  (void)pAux;
224533  (void)argc;
224534  (void)argv;
224535  (void)pzErr;
224536
224537  sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
224538  sqlite3_vtab_config(db, SQLITE_VTAB_USES_ALL_SCHEMAS);
224539  rc = sqlite3_declare_vtab(db,
224540          "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
224541  if( rc==SQLITE_OK ){
224542    pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
224543    if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
224544  }
224545
224546  assert( rc==SQLITE_OK || pTab==0 );
224547  if( rc==SQLITE_OK ){
224548    memset(pTab, 0, sizeof(DbpageTable));
224549    pTab->db = db;
224550  }
224551
224552  *ppVtab = (sqlite3_vtab*)pTab;
224553  return rc;
224554}
224555
224556/*
224557** Disconnect from or destroy a dbpagevfs virtual table.
224558*/
224559static int dbpageDisconnect(sqlite3_vtab *pVtab){
224560  sqlite3_free(pVtab);
224561  return SQLITE_OK;
224562}
224563
224564/*
224565** idxNum:
224566**
224567**     0     schema=main, full table scan
224568**     1     schema=main, pgno=?1
224569**     2     schema=?1, full table scan
224570**     3     schema=?1, pgno=?2
224571*/
224572static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
224573  int i;
224574  int iPlan = 0;
224575  (void)tab;
224576
224577  /* If there is a schema= constraint, it must be honored.  Report a
224578  ** ridiculously large estimated cost if the schema= constraint is
224579  ** unavailable
224580  */
224581  for(i=0; i<pIdxInfo->nConstraint; i++){
224582    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
224583    if( p->iColumn!=DBPAGE_COLUMN_SCHEMA ) continue;
224584    if( p->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
224585    if( !p->usable ){
224586      /* No solution. */
224587      return SQLITE_CONSTRAINT;
224588    }
224589    iPlan = 2;
224590    pIdxInfo->aConstraintUsage[i].argvIndex = 1;
224591    pIdxInfo->aConstraintUsage[i].omit = 1;
224592    break;
224593  }
224594
224595  /* If we reach this point, it means that either there is no schema=
224596  ** constraint (in which case we use the "main" schema) or else the
224597  ** schema constraint was accepted.  Lower the estimated cost accordingly
224598  */
224599  pIdxInfo->estimatedCost = 1.0e6;
224600
224601  /* Check for constraints against pgno */
224602  for(i=0; i<pIdxInfo->nConstraint; i++){
224603    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
224604    if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
224605      pIdxInfo->estimatedRows = 1;
224606      pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
224607      pIdxInfo->estimatedCost = 1.0;
224608      pIdxInfo->aConstraintUsage[i].argvIndex = iPlan ? 2 : 1;
224609      pIdxInfo->aConstraintUsage[i].omit = 1;
224610      iPlan |= 1;
224611      break;
224612    }
224613  }
224614  pIdxInfo->idxNum = iPlan;
224615
224616  if( pIdxInfo->nOrderBy>=1
224617   && pIdxInfo->aOrderBy[0].iColumn<=0
224618   && pIdxInfo->aOrderBy[0].desc==0
224619  ){
224620    pIdxInfo->orderByConsumed = 1;
224621  }
224622  return SQLITE_OK;
224623}
224624
224625/*
224626** Open a new dbpagevfs cursor.
224627*/
224628static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
224629  DbpageCursor *pCsr;
224630
224631  pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));
224632  if( pCsr==0 ){
224633    return SQLITE_NOMEM_BKPT;
224634  }else{
224635    memset(pCsr, 0, sizeof(DbpageCursor));
224636    pCsr->base.pVtab = pVTab;
224637    pCsr->pgno = -1;
224638  }
224639
224640  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
224641  return SQLITE_OK;
224642}
224643
224644/*
224645** Close a dbpagevfs cursor.
224646*/
224647static int dbpageClose(sqlite3_vtab_cursor *pCursor){
224648  DbpageCursor *pCsr = (DbpageCursor *)pCursor;
224649  if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
224650  sqlite3_free(pCsr);
224651  return SQLITE_OK;
224652}
224653
224654/*
224655** Move a dbpagevfs cursor to the next entry in the file.
224656*/
224657static int dbpageNext(sqlite3_vtab_cursor *pCursor){
224658  int rc = SQLITE_OK;
224659  DbpageCursor *pCsr = (DbpageCursor *)pCursor;
224660  pCsr->pgno++;
224661  return rc;
224662}
224663
224664static int dbpageEof(sqlite3_vtab_cursor *pCursor){
224665  DbpageCursor *pCsr = (DbpageCursor *)pCursor;
224666  return pCsr->pgno > pCsr->mxPgno;
224667}
224668
224669/*
224670** idxNum:
224671**
224672**     0     schema=main, full table scan
224673**     1     schema=main, pgno=?1
224674**     2     schema=?1, full table scan
224675**     3     schema=?1, pgno=?2
224676**
224677** idxStr is not used
224678*/
224679static int dbpageFilter(
224680  sqlite3_vtab_cursor *pCursor,
224681  int idxNum, const char *idxStr,
224682  int argc, sqlite3_value **argv
224683){
224684  DbpageCursor *pCsr = (DbpageCursor *)pCursor;
224685  DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
224686  int rc;
224687  sqlite3 *db = pTab->db;
224688  Btree *pBt;
224689
224690  (void)idxStr;
224691
224692  /* Default setting is no rows of result */
224693  pCsr->pgno = 1;
224694  pCsr->mxPgno = 0;
224695
224696  if( idxNum & 2 ){
224697    const char *zSchema;
224698    assert( argc>=1 );
224699    zSchema = (const char*)sqlite3_value_text(argv[0]);
224700    pCsr->iDb = sqlite3FindDbName(db, zSchema);
224701    if( pCsr->iDb<0 ) return SQLITE_OK;
224702  }else{
224703    pCsr->iDb = 0;
224704  }
224705  pBt = db->aDb[pCsr->iDb].pBt;
224706  if( NEVER(pBt==0) ) return SQLITE_OK;
224707  pCsr->pPager = sqlite3BtreePager(pBt);
224708  pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
224709  pCsr->mxPgno = sqlite3BtreeLastPage(pBt);
224710  if( idxNum & 1 ){
224711    assert( argc>(idxNum>>1) );
224712    pCsr->pgno = sqlite3_value_int(argv[idxNum>>1]);
224713    if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){
224714      pCsr->pgno = 1;
224715      pCsr->mxPgno = 0;
224716    }else{
224717      pCsr->mxPgno = pCsr->pgno;
224718    }
224719  }else{
224720    assert( pCsr->pgno==1 );
224721  }
224722  if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
224723  rc = sqlite3PagerGet(pCsr->pPager, 1, &pCsr->pPage1, 0);
224724  return rc;
224725}
224726
224727static int dbpageColumn(
224728  sqlite3_vtab_cursor *pCursor,
224729  sqlite3_context *ctx,
224730  int i
224731){
224732  DbpageCursor *pCsr = (DbpageCursor *)pCursor;
224733  int rc = SQLITE_OK;
224734  switch( i ){
224735    case 0: {           /* pgno */
224736      sqlite3_result_int(ctx, pCsr->pgno);
224737      break;
224738    }
224739    case 1: {           /* data */
224740      DbPage *pDbPage = 0;
224741      if( pCsr->pgno==((PENDING_BYTE/pCsr->szPage)+1) ){
224742        /* The pending byte page. Assume it is zeroed out. Attempting to
224743        ** request this page from the page is an SQLITE_CORRUPT error. */
224744        sqlite3_result_zeroblob(ctx, pCsr->szPage);
224745      }else{
224746        rc = sqlite3PagerGet(pCsr->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
224747        if( rc==SQLITE_OK ){
224748          sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pCsr->szPage,
224749              SQLITE_TRANSIENT);
224750        }
224751        sqlite3PagerUnref(pDbPage);
224752      }
224753      break;
224754    }
224755    default: {          /* schema */
224756      sqlite3 *db = sqlite3_context_db_handle(ctx);
224757      sqlite3_result_text(ctx, db->aDb[pCsr->iDb].zDbSName, -1, SQLITE_STATIC);
224758      break;
224759    }
224760  }
224761  return rc;
224762}
224763
224764static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
224765  DbpageCursor *pCsr = (DbpageCursor *)pCursor;
224766  *pRowid = pCsr->pgno;
224767  return SQLITE_OK;
224768}
224769
224770static int dbpageUpdate(
224771  sqlite3_vtab *pVtab,
224772  int argc,
224773  sqlite3_value **argv,
224774  sqlite_int64 *pRowid
224775){
224776  DbpageTable *pTab = (DbpageTable *)pVtab;
224777  Pgno pgno;
224778  DbPage *pDbPage = 0;
224779  int rc = SQLITE_OK;
224780  char *zErr = 0;
224781  const char *zSchema;
224782  int iDb;
224783  Btree *pBt;
224784  Pager *pPager;
224785  int szPage;
224786
224787  (void)pRowid;
224788  if( pTab->db->flags & SQLITE_Defensive ){
224789    zErr = "read-only";
224790    goto update_fail;
224791  }
224792  if( argc==1 ){
224793    zErr = "cannot delete";
224794    goto update_fail;
224795  }
224796  pgno = sqlite3_value_int(argv[0]);
224797  if( sqlite3_value_type(argv[0])==SQLITE_NULL
224798   || (Pgno)sqlite3_value_int(argv[1])!=pgno
224799  ){
224800    zErr = "cannot insert";
224801    goto update_fail;
224802  }
224803  zSchema = (const char*)sqlite3_value_text(argv[4]);
224804  iDb = ALWAYS(zSchema) ? sqlite3FindDbName(pTab->db, zSchema) : -1;
224805  if( NEVER(iDb<0) ){
224806    zErr = "no such schema";
224807    goto update_fail;
224808  }
224809  pBt = pTab->db->aDb[iDb].pBt;
224810  if( NEVER(pgno<1) || NEVER(pBt==0) || NEVER(pgno>sqlite3BtreeLastPage(pBt)) ){
224811    zErr = "bad page number";
224812    goto update_fail;
224813  }
224814  szPage = sqlite3BtreeGetPageSize(pBt);
224815  if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
224816   || sqlite3_value_bytes(argv[3])!=szPage
224817  ){
224818    zErr = "bad page value";
224819    goto update_fail;
224820  }
224821  pPager = sqlite3BtreePager(pBt);
224822  rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0);
224823  if( rc==SQLITE_OK ){
224824    const void *pData = sqlite3_value_blob(argv[3]);
224825    assert( pData!=0 || pTab->db->mallocFailed );
224826    if( pData
224827     && (rc = sqlite3PagerWrite(pDbPage))==SQLITE_OK
224828    ){
224829      memcpy(sqlite3PagerGetData(pDbPage), pData, szPage);
224830    }
224831  }
224832  sqlite3PagerUnref(pDbPage);
224833  return rc;
224834
224835update_fail:
224836  sqlite3_free(pVtab->zErrMsg);
224837  pVtab->zErrMsg = sqlite3_mprintf("%s", zErr);
224838  return SQLITE_ERROR;
224839}
224840
224841/* Since we do not know in advance which database files will be
224842** written by the sqlite_dbpage virtual table, start a write transaction
224843** on them all.
224844*/
224845static int dbpageBegin(sqlite3_vtab *pVtab){
224846  DbpageTable *pTab = (DbpageTable *)pVtab;
224847  sqlite3 *db = pTab->db;
224848  int i;
224849  for(i=0; i<db->nDb; i++){
224850    Btree *pBt = db->aDb[i].pBt;
224851    if( pBt ) (void)sqlite3BtreeBeginTrans(pBt, 1, 0);
224852  }
224853  return SQLITE_OK;
224854}
224855
224856
224857/*
224858** Invoke this routine to register the "dbpage" virtual table module
224859*/
224860SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
224861  static sqlite3_module dbpage_module = {
224862    0,                            /* iVersion */
224863    dbpageConnect,                /* xCreate */
224864    dbpageConnect,                /* xConnect */
224865    dbpageBestIndex,              /* xBestIndex */
224866    dbpageDisconnect,             /* xDisconnect */
224867    dbpageDisconnect,             /* xDestroy */
224868    dbpageOpen,                   /* xOpen - open a cursor */
224869    dbpageClose,                  /* xClose - close a cursor */
224870    dbpageFilter,                 /* xFilter - configure scan constraints */
224871    dbpageNext,                   /* xNext - advance a cursor */
224872    dbpageEof,                    /* xEof - check for end of scan */
224873    dbpageColumn,                 /* xColumn - read data */
224874    dbpageRowid,                  /* xRowid - read data */
224875    dbpageUpdate,                 /* xUpdate */
224876    dbpageBegin,                  /* xBegin */
224877    0,                            /* xSync */
224878    0,                            /* xCommit */
224879    0,                            /* xRollback */
224880    0,                            /* xFindMethod */
224881    0,                            /* xRename */
224882    0,                            /* xSavepoint */
224883    0,                            /* xRelease */
224884    0,                            /* xRollbackTo */
224885    0,                            /* xShadowName */
224886    0                             /* xIntegrity */
224887  };
224888  return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
224889}
224890#elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
224891SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
224892#endif /* SQLITE_ENABLE_DBSTAT_VTAB */
224893
224894/************** End of dbpage.c **********************************************/
224895/************** Begin file sqlite3session.c **********************************/
224896
224897#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
224898/* #include "sqlite3session.h" */
224899/* #include <assert.h> */
224900/* #include <string.h> */
224901
224902#ifndef SQLITE_AMALGAMATION
224903/* # include "sqliteInt.h" */
224904/* # include "vdbeInt.h" */
224905#endif
224906
224907typedef struct SessionTable SessionTable;
224908typedef struct SessionChange SessionChange;
224909typedef struct SessionBuffer SessionBuffer;
224910typedef struct SessionInput SessionInput;
224911
224912/*
224913** Minimum chunk size used by streaming versions of functions.
224914*/
224915#ifndef SESSIONS_STRM_CHUNK_SIZE
224916# ifdef SQLITE_TEST
224917#   define SESSIONS_STRM_CHUNK_SIZE 64
224918# else
224919#   define SESSIONS_STRM_CHUNK_SIZE 1024
224920# endif
224921#endif
224922
224923#define SESSIONS_ROWID "_rowid_"
224924
224925static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE;
224926
224927typedef struct SessionHook SessionHook;
224928struct SessionHook {
224929  void *pCtx;
224930  int (*xOld)(void*,int,sqlite3_value**);
224931  int (*xNew)(void*,int,sqlite3_value**);
224932  int (*xCount)(void*);
224933  int (*xDepth)(void*);
224934};
224935
224936/*
224937** Session handle structure.
224938*/
224939struct sqlite3_session {
224940  sqlite3 *db;                    /* Database handle session is attached to */
224941  char *zDb;                      /* Name of database session is attached to */
224942  int bEnableSize;                /* True if changeset_size() enabled */
224943  int bEnable;                    /* True if currently recording */
224944  int bIndirect;                  /* True if all changes are indirect */
224945  int bAutoAttach;                /* True to auto-attach tables */
224946  int bImplicitPK;                /* True to handle tables with implicit PK */
224947  int rc;                         /* Non-zero if an error has occurred */
224948  void *pFilterCtx;               /* First argument to pass to xTableFilter */
224949  int (*xTableFilter)(void *pCtx, const char *zTab);
224950  i64 nMalloc;                    /* Number of bytes of data allocated */
224951  i64 nMaxChangesetSize;
224952  sqlite3_value *pZeroBlob;       /* Value containing X'' */
224953  sqlite3_session *pNext;         /* Next session object on same db. */
224954  SessionTable *pTable;           /* List of attached tables */
224955  SessionHook hook;               /* APIs to grab new and old data with */
224956};
224957
224958/*
224959** Instances of this structure are used to build strings or binary records.
224960*/
224961struct SessionBuffer {
224962  u8 *aBuf;                       /* Pointer to changeset buffer */
224963  int nBuf;                       /* Size of buffer aBuf */
224964  int nAlloc;                     /* Size of allocation containing aBuf */
224965};
224966
224967/*
224968** An object of this type is used internally as an abstraction for
224969** input data. Input data may be supplied either as a single large buffer
224970** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
224971**  sqlite3changeset_start_strm()).
224972*/
224973struct SessionInput {
224974  int bNoDiscard;                 /* If true, do not discard in InputBuffer() */
224975  int iCurrent;                   /* Offset in aData[] of current change */
224976  int iNext;                      /* Offset in aData[] of next change */
224977  u8 *aData;                      /* Pointer to buffer containing changeset */
224978  int nData;                      /* Number of bytes in aData */
224979
224980  SessionBuffer buf;              /* Current read buffer */
224981  int (*xInput)(void*, void*, int*);        /* Input stream call (or NULL) */
224982  void *pIn;                                /* First argument to xInput */
224983  int bEof;                       /* Set to true after xInput finished */
224984};
224985
224986/*
224987** Structure for changeset iterators.
224988*/
224989struct sqlite3_changeset_iter {
224990  SessionInput in;                /* Input buffer or stream */
224991  SessionBuffer tblhdr;           /* Buffer to hold apValue/zTab/abPK/ */
224992  int bPatchset;                  /* True if this is a patchset */
224993  int bInvert;                    /* True to invert changeset */
224994  int bSkipEmpty;                 /* Skip noop UPDATE changes */
224995  int rc;                         /* Iterator error code */
224996  sqlite3_stmt *pConflict;        /* Points to conflicting row, if any */
224997  char *zTab;                     /* Current table */
224998  int nCol;                       /* Number of columns in zTab */
224999  int op;                         /* Current operation */
225000  int bIndirect;                  /* True if current change was indirect */
225001  u8 *abPK;                       /* Primary key array */
225002  sqlite3_value **apValue;        /* old.* and new.* values */
225003};
225004
225005/*
225006** Each session object maintains a set of the following structures, one
225007** for each table the session object is monitoring. The structures are
225008** stored in a linked list starting at sqlite3_session.pTable.
225009**
225010** The keys of the SessionTable.aChange[] hash table are all rows that have
225011** been modified in any way since the session object was attached to the
225012** table.
225013**
225014** The data associated with each hash-table entry is a structure containing
225015** a subset of the initial values that the modified row contained at the
225016** start of the session. Or no initial values if the row was inserted.
225017**
225018** pDfltStmt:
225019**   This is only used by the sqlite3changegroup_xxx() APIs, not by
225020**   regular sqlite3_session objects. It is a SELECT statement that
225021**   selects the default value for each table column. For example,
225022**   if the table is
225023**
225024**      CREATE TABLE xx(a DEFAULT 1, b, c DEFAULT 'abc')
225025**
225026**   then this variable is the compiled version of:
225027**
225028**      SELECT 1, NULL, 'abc'
225029*/
225030struct SessionTable {
225031  SessionTable *pNext;
225032  char *zName;                    /* Local name of table */
225033  int nCol;                       /* Number of columns in table zName */
225034  int bStat1;                     /* True if this is sqlite_stat1 */
225035  int bRowid;                     /* True if this table uses rowid for PK */
225036  const char **azCol;             /* Column names */
225037  const char **azDflt;            /* Default value expressions */
225038  u8 *abPK;                       /* Array of primary key flags */
225039  int nEntry;                     /* Total number of entries in hash table */
225040  int nChange;                    /* Size of apChange[] array */
225041  SessionChange **apChange;       /* Hash table buckets */
225042  sqlite3_stmt *pDfltStmt;
225043};
225044
225045/*
225046** RECORD FORMAT:
225047**
225048** The following record format is similar to (but not compatible with) that
225049** used in SQLite database files. This format is used as part of the
225050** change-set binary format, and so must be architecture independent.
225051**
225052** Unlike the SQLite database record format, each field is self-contained -
225053** there is no separation of header and data. Each field begins with a
225054** single byte describing its type, as follows:
225055**
225056**       0x00: Undefined value.
225057**       0x01: Integer value.
225058**       0x02: Real value.
225059**       0x03: Text value.
225060**       0x04: Blob value.
225061**       0x05: SQL NULL value.
225062**
225063** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
225064** and so on in sqlite3.h. For undefined and NULL values, the field consists
225065** only of the single type byte. For other types of values, the type byte
225066** is followed by:
225067**
225068**   Text values:
225069**     A varint containing the number of bytes in the value (encoded using
225070**     UTF-8). Followed by a buffer containing the UTF-8 representation
225071**     of the text value. There is no nul terminator.
225072**
225073**   Blob values:
225074**     A varint containing the number of bytes in the value, followed by
225075**     a buffer containing the value itself.
225076**
225077**   Integer values:
225078**     An 8-byte big-endian integer value.
225079**
225080**   Real values:
225081**     An 8-byte big-endian IEEE 754-2008 real value.
225082**
225083** Varint values are encoded in the same way as varints in the SQLite
225084** record format.
225085**
225086** CHANGESET FORMAT:
225087**
225088** A changeset is a collection of DELETE, UPDATE and INSERT operations on
225089** one or more tables. Operations on a single table are grouped together,
225090** but may occur in any order (i.e. deletes, updates and inserts are all
225091** mixed together).
225092**
225093** Each group of changes begins with a table header:
225094**
225095**   1 byte: Constant 0x54 (capital 'T')
225096**   Varint: Number of columns in the table.
225097**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
225098**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
225099**
225100** Followed by one or more changes to the table.
225101**
225102**   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
225103**   1 byte: The "indirect-change" flag.
225104**   old.* record: (delete and update only)
225105**   new.* record: (insert and update only)
225106**
225107** The "old.*" and "new.*" records, if present, are N field records in the
225108** format described above under "RECORD FORMAT", where N is the number of
225109** columns in the table. The i'th field of each record is associated with
225110** the i'th column of the table, counting from left to right in the order
225111** in which columns were declared in the CREATE TABLE statement.
225112**
225113** The new.* record that is part of each INSERT change contains the values
225114** that make up the new row. Similarly, the old.* record that is part of each
225115** DELETE change contains the values that made up the row that was deleted
225116** from the database. In the changeset format, the records that are part
225117** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
225118** fields.
225119**
225120** Within the old.* record associated with an UPDATE change, all fields
225121** associated with table columns that are not PRIMARY KEY columns and are
225122** not modified by the UPDATE change are set to "undefined". Other fields
225123** are set to the values that made up the row before the UPDATE that the
225124** change records took place. Within the new.* record, fields associated
225125** with table columns modified by the UPDATE change contain the new
225126** values. Fields associated with table columns that are not modified
225127** are set to "undefined".
225128**
225129** PATCHSET FORMAT:
225130**
225131** A patchset is also a collection of changes. It is similar to a changeset,
225132** but leaves undefined those fields that are not useful if no conflict
225133** resolution is required when applying the changeset.
225134**
225135** Each group of changes begins with a table header:
225136**
225137**   1 byte: Constant 0x50 (capital 'P')
225138**   Varint: Number of columns in the table.
225139**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
225140**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
225141**
225142** Followed by one or more changes to the table.
225143**
225144**   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
225145**   1 byte: The "indirect-change" flag.
225146**   single record: (PK fields for DELETE, PK and modified fields for UPDATE,
225147**                   full record for INSERT).
225148**
225149** As in the changeset format, each field of the single record that is part
225150** of a patchset change is associated with the correspondingly positioned
225151** table column, counting from left to right within the CREATE TABLE
225152** statement.
225153**
225154** For a DELETE change, all fields within the record except those associated
225155** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the
225156** values identifying the row to delete.
225157**
225158** For an UPDATE change, all fields except those associated with PRIMARY KEY
225159** columns and columns that are modified by the UPDATE are set to "undefined".
225160** PRIMARY KEY fields contain the values identifying the table row to update,
225161** and fields associated with modified columns contain the new column values.
225162**
225163** The records associated with INSERT changes are in the same format as for
225164** changesets. It is not possible for a record associated with an INSERT
225165** change to contain a field set to "undefined".
225166**
225167** REBASE BLOB FORMAT:
225168**
225169** A rebase blob may be output by sqlite3changeset_apply_v2() and its
225170** streaming equivalent for use with the sqlite3_rebaser APIs to rebase
225171** existing changesets. A rebase blob contains one entry for each conflict
225172** resolved using either the OMIT or REPLACE strategies within the apply_v2()
225173** call.
225174**
225175** The format used for a rebase blob is very similar to that used for
225176** changesets. All entries related to a single table are grouped together.
225177**
225178** Each group of entries begins with a table header in changeset format:
225179**
225180**   1 byte: Constant 0x54 (capital 'T')
225181**   Varint: Number of columns in the table.
225182**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
225183**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
225184**
225185** Followed by one or more entries associated with the table.
225186**
225187**   1 byte: Either SQLITE_INSERT (0x12), DELETE (0x09).
225188**   1 byte: Flag. 0x01 for REPLACE, 0x00 for OMIT.
225189**   record: (in the record format defined above).
225190**
225191** In a rebase blob, the first field is set to SQLITE_INSERT if the change
225192** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if
225193** it was a DELETE. The second field is set to 0x01 if the conflict
225194** resolution strategy was REPLACE, or 0x00 if it was OMIT.
225195**
225196** If the change that caused the conflict was a DELETE, then the single
225197** record is a copy of the old.* record from the original changeset. If it
225198** was an INSERT, then the single record is a copy of the new.* record. If
225199** the conflicting change was an UPDATE, then the single record is a copy
225200** of the new.* record with the PK fields filled in based on the original
225201** old.* record.
225202*/
225203
225204/*
225205** For each row modified during a session, there exists a single instance of
225206** this structure stored in a SessionTable.aChange[] hash table.
225207*/
225208struct SessionChange {
225209  u8 op;                          /* One of UPDATE, DELETE, INSERT */
225210  u8 bIndirect;                   /* True if this change is "indirect" */
225211  u16 nRecordField;               /* Number of fields in aRecord[] */
225212  int nMaxSize;                   /* Max size of eventual changeset record */
225213  int nRecord;                    /* Number of bytes in buffer aRecord[] */
225214  u8 *aRecord;                    /* Buffer containing old.* record */
225215  SessionChange *pNext;           /* For hash-table collisions */
225216};
225217
225218/*
225219** Write a varint with value iVal into the buffer at aBuf. Return the
225220** number of bytes written.
225221*/
225222static int sessionVarintPut(u8 *aBuf, int iVal){
225223  return putVarint32(aBuf, iVal);
225224}
225225
225226/*
225227** Return the number of bytes required to store value iVal as a varint.
225228*/
225229static int sessionVarintLen(int iVal){
225230  return sqlite3VarintLen(iVal);
225231}
225232
225233/*
225234** Read a varint value from aBuf[] into *piVal. Return the number of
225235** bytes read.
225236*/
225237static int sessionVarintGet(const u8 *aBuf, int *piVal){
225238  return getVarint32(aBuf, *piVal);
225239}
225240
225241/* Load an unaligned and unsigned 32-bit integer */
225242#define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
225243
225244/*
225245** Read a 64-bit big-endian integer value from buffer aRec[]. Return
225246** the value read.
225247*/
225248static sqlite3_int64 sessionGetI64(u8 *aRec){
225249  u64 x = SESSION_UINT32(aRec);
225250  u32 y = SESSION_UINT32(aRec+4);
225251  x = (x<<32) + y;
225252  return (sqlite3_int64)x;
225253}
225254
225255/*
225256** Write a 64-bit big-endian integer value to the buffer aBuf[].
225257*/
225258static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
225259  aBuf[0] = (i>>56) & 0xFF;
225260  aBuf[1] = (i>>48) & 0xFF;
225261  aBuf[2] = (i>>40) & 0xFF;
225262  aBuf[3] = (i>>32) & 0xFF;
225263  aBuf[4] = (i>>24) & 0xFF;
225264  aBuf[5] = (i>>16) & 0xFF;
225265  aBuf[6] = (i>> 8) & 0xFF;
225266  aBuf[7] = (i>> 0) & 0xFF;
225267}
225268
225269/*
225270** This function is used to serialize the contents of value pValue (see
225271** comment titled "RECORD FORMAT" above).
225272**
225273** If it is non-NULL, the serialized form of the value is written to
225274** buffer aBuf. *pnWrite is set to the number of bytes written before
225275** returning. Or, if aBuf is NULL, the only thing this function does is
225276** set *pnWrite.
225277**
225278** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
225279** within a call to sqlite3_value_text() (may fail if the db is utf-16))
225280** SQLITE_NOMEM is returned.
225281*/
225282static int sessionSerializeValue(
225283  u8 *aBuf,                       /* If non-NULL, write serialized value here */
225284  sqlite3_value *pValue,          /* Value to serialize */
225285  sqlite3_int64 *pnWrite          /* IN/OUT: Increment by bytes written */
225286){
225287  int nByte;                      /* Size of serialized value in bytes */
225288
225289  if( pValue ){
225290    int eType;                    /* Value type (SQLITE_NULL, TEXT etc.) */
225291
225292    eType = sqlite3_value_type(pValue);
225293    if( aBuf ) aBuf[0] = eType;
225294
225295    switch( eType ){
225296      case SQLITE_NULL:
225297        nByte = 1;
225298        break;
225299
225300      case SQLITE_INTEGER:
225301      case SQLITE_FLOAT:
225302        if( aBuf ){
225303          /* TODO: SQLite does something special to deal with mixed-endian
225304          ** floating point values (e.g. ARM7). This code probably should
225305          ** too.  */
225306          u64 i;
225307          if( eType==SQLITE_INTEGER ){
225308            i = (u64)sqlite3_value_int64(pValue);
225309          }else{
225310            double r;
225311            assert( sizeof(double)==8 && sizeof(u64)==8 );
225312            r = sqlite3_value_double(pValue);
225313            memcpy(&i, &r, 8);
225314          }
225315          sessionPutI64(&aBuf[1], i);
225316        }
225317        nByte = 9;
225318        break;
225319
225320      default: {
225321        u8 *z;
225322        int n;
225323        int nVarint;
225324
225325        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
225326        if( eType==SQLITE_TEXT ){
225327          z = (u8 *)sqlite3_value_text(pValue);
225328        }else{
225329          z = (u8 *)sqlite3_value_blob(pValue);
225330        }
225331        n = sqlite3_value_bytes(pValue);
225332        if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
225333        nVarint = sessionVarintLen(n);
225334
225335        if( aBuf ){
225336          sessionVarintPut(&aBuf[1], n);
225337          if( n>0 ) memcpy(&aBuf[nVarint + 1], z, n);
225338        }
225339
225340        nByte = 1 + nVarint + n;
225341        break;
225342      }
225343    }
225344  }else{
225345    nByte = 1;
225346    if( aBuf ) aBuf[0] = '\0';
225347  }
225348
225349  if( pnWrite ) *pnWrite += nByte;
225350  return SQLITE_OK;
225351}
225352
225353/*
225354** Allocate and return a pointer to a buffer nByte bytes in size. If
225355** pSession is not NULL, increase the sqlite3_session.nMalloc variable
225356** by the number of bytes allocated.
225357*/
225358static void *sessionMalloc64(sqlite3_session *pSession, i64 nByte){
225359  void *pRet = sqlite3_malloc64(nByte);
225360  if( pSession ) pSession->nMalloc += sqlite3_msize(pRet);
225361  return pRet;
225362}
225363
225364/*
225365** Free buffer pFree, which must have been allocated by an earlier
225366** call to sessionMalloc64(). If pSession is not NULL, decrease the
225367** sqlite3_session.nMalloc counter by the number of bytes freed.
225368*/
225369static void sessionFree(sqlite3_session *pSession, void *pFree){
225370  if( pSession ) pSession->nMalloc -= sqlite3_msize(pFree);
225371  sqlite3_free(pFree);
225372}
225373
225374/*
225375** This macro is used to calculate hash key values for data structures. In
225376** order to use this macro, the entire data structure must be represented
225377** as a series of unsigned integers. In order to calculate a hash-key value
225378** for a data structure represented as three such integers, the macro may
225379** then be used as follows:
225380**
225381**    int hash_key_value;
225382**    hash_key_value = HASH_APPEND(0, <value 1>);
225383**    hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
225384**    hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
225385**
225386** In practice, the data structures this macro is used for are the primary
225387** key values of modified rows.
225388*/
225389#define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
225390
225391/*
225392** Append the hash of the 64-bit integer passed as the second argument to the
225393** hash-key value passed as the first. Return the new hash-key value.
225394*/
225395static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
225396  h = HASH_APPEND(h, i & 0xFFFFFFFF);
225397  return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
225398}
225399
225400/*
225401** Append the hash of the blob passed via the second and third arguments to
225402** the hash-key value passed as the first. Return the new hash-key value.
225403*/
225404static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
225405  int i;
225406  for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
225407  return h;
225408}
225409
225410/*
225411** Append the hash of the data type passed as the second argument to the
225412** hash-key value passed as the first. Return the new hash-key value.
225413*/
225414static unsigned int sessionHashAppendType(unsigned int h, int eType){
225415  return HASH_APPEND(h, eType);
225416}
225417
225418/*
225419** This function may only be called from within a pre-update callback.
225420** It calculates a hash based on the primary key values of the old.* or
225421** new.* row currently available and, assuming no error occurs, writes it to
225422** *piHash before returning. If the primary key contains one or more NULL
225423** values, *pbNullPK is set to true before returning.
225424**
225425** If an error occurs, an SQLite error code is returned and the final values
225426** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
225427** and the output variables are set as described above.
225428*/
225429static int sessionPreupdateHash(
225430  sqlite3_session *pSession,      /* Session object that owns pTab */
225431  i64 iRowid,
225432  SessionTable *pTab,             /* Session table handle */
225433  int bNew,                       /* True to hash the new.* PK */
225434  int *piHash,                    /* OUT: Hash value */
225435  int *pbNullPK                   /* OUT: True if there are NULL values in PK */
225436){
225437  unsigned int h = 0;             /* Hash value to return */
225438  int i;                          /* Used to iterate through columns */
225439
225440  if( pTab->bRowid ){
225441    assert( pTab->nCol-1==pSession->hook.xCount(pSession->hook.pCtx) );
225442    h = sessionHashAppendI64(h, iRowid);
225443  }else{
225444    assert( *pbNullPK==0 );
225445    assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
225446    for(i=0; i<pTab->nCol; i++){
225447      if( pTab->abPK[i] ){
225448        int rc;
225449        int eType;
225450        sqlite3_value *pVal;
225451
225452        if( bNew ){
225453          rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
225454        }else{
225455          rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
225456        }
225457        if( rc!=SQLITE_OK ) return rc;
225458
225459        eType = sqlite3_value_type(pVal);
225460        h = sessionHashAppendType(h, eType);
225461        if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
225462          i64 iVal;
225463          if( eType==SQLITE_INTEGER ){
225464            iVal = sqlite3_value_int64(pVal);
225465          }else{
225466            double rVal = sqlite3_value_double(pVal);
225467            assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
225468            memcpy(&iVal, &rVal, 8);
225469          }
225470          h = sessionHashAppendI64(h, iVal);
225471        }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
225472          const u8 *z;
225473          int n;
225474          if( eType==SQLITE_TEXT ){
225475            z = (const u8 *)sqlite3_value_text(pVal);
225476          }else{
225477            z = (const u8 *)sqlite3_value_blob(pVal);
225478          }
225479          n = sqlite3_value_bytes(pVal);
225480          if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
225481          h = sessionHashAppendBlob(h, n, z);
225482        }else{
225483          assert( eType==SQLITE_NULL );
225484          assert( pTab->bStat1==0 || i!=1 );
225485          *pbNullPK = 1;
225486        }
225487      }
225488    }
225489  }
225490
225491  *piHash = (h % pTab->nChange);
225492  return SQLITE_OK;
225493}
225494
225495/*
225496** The buffer that the argument points to contains a serialized SQL value.
225497** Return the number of bytes of space occupied by the value (including
225498** the type byte).
225499*/
225500static int sessionSerialLen(const u8 *a){
225501  int e;
225502  int n;
225503  assert( a!=0 );
225504  e = *a;
225505  if( e==0 || e==0xFF ) return 1;
225506  if( e==SQLITE_NULL ) return 1;
225507  if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
225508  return sessionVarintGet(&a[1], &n) + 1 + n;
225509}
225510
225511/*
225512** Based on the primary key values stored in change aRecord, calculate a
225513** hash key. Assume the has table has nBucket buckets. The hash keys
225514** calculated by this function are compatible with those calculated by
225515** sessionPreupdateHash().
225516**
225517** The bPkOnly argument is non-zero if the record at aRecord[] is from
225518** a patchset DELETE. In this case the non-PK fields are omitted entirely.
225519*/
225520static unsigned int sessionChangeHash(
225521  SessionTable *pTab,             /* Table handle */
225522  int bPkOnly,                    /* Record consists of PK fields only */
225523  u8 *aRecord,                    /* Change record */
225524  int nBucket                     /* Assume this many buckets in hash table */
225525){
225526  unsigned int h = 0;             /* Value to return */
225527  int i;                          /* Used to iterate through columns */
225528  u8 *a = aRecord;                /* Used to iterate through change record */
225529
225530  for(i=0; i<pTab->nCol; i++){
225531    int eType = *a;
225532    int isPK = pTab->abPK[i];
225533    if( bPkOnly && isPK==0 ) continue;
225534
225535    /* It is not possible for eType to be SQLITE_NULL here. The session
225536    ** module does not record changes for rows with NULL values stored in
225537    ** primary key columns. */
225538    assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
225539         || eType==SQLITE_TEXT || eType==SQLITE_BLOB
225540         || eType==SQLITE_NULL || eType==0
225541    );
225542    assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
225543
225544    if( isPK ){
225545      a++;
225546      h = sessionHashAppendType(h, eType);
225547      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
225548        h = sessionHashAppendI64(h, sessionGetI64(a));
225549        a += 8;
225550      }else{
225551        int n;
225552        a += sessionVarintGet(a, &n);
225553        h = sessionHashAppendBlob(h, n, a);
225554        a += n;
225555      }
225556    }else{
225557      a += sessionSerialLen(a);
225558    }
225559  }
225560  return (h % nBucket);
225561}
225562
225563/*
225564** Arguments aLeft and aRight are pointers to change records for table pTab.
225565** This function returns true if the two records apply to the same row (i.e.
225566** have the same values stored in the primary key columns), or false
225567** otherwise.
225568*/
225569static int sessionChangeEqual(
225570  SessionTable *pTab,             /* Table used for PK definition */
225571  int bLeftPkOnly,                /* True if aLeft[] contains PK fields only */
225572  u8 *aLeft,                      /* Change record */
225573  int bRightPkOnly,               /* True if aRight[] contains PK fields only */
225574  u8 *aRight                      /* Change record */
225575){
225576  u8 *a1 = aLeft;                 /* Cursor to iterate through aLeft */
225577  u8 *a2 = aRight;                /* Cursor to iterate through aRight */
225578  int iCol;                       /* Used to iterate through table columns */
225579
225580  for(iCol=0; iCol<pTab->nCol; iCol++){
225581    if( pTab->abPK[iCol] ){
225582      int n1 = sessionSerialLen(a1);
225583      int n2 = sessionSerialLen(a2);
225584
225585      if( n1!=n2 || memcmp(a1, a2, n1) ){
225586        return 0;
225587      }
225588      a1 += n1;
225589      a2 += n2;
225590    }else{
225591      if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
225592      if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
225593    }
225594  }
225595
225596  return 1;
225597}
225598
225599/*
225600** Arguments aLeft and aRight both point to buffers containing change
225601** records with nCol columns. This function "merges" the two records into
225602** a single records which is written to the buffer at *paOut. *paOut is
225603** then set to point to one byte after the last byte written before
225604** returning.
225605**
225606** The merging of records is done as follows: For each column, if the
225607** aRight record contains a value for the column, copy the value from
225608** their. Otherwise, if aLeft contains a value, copy it. If neither
225609** record contains a value for a given column, then neither does the
225610** output record.
225611*/
225612static void sessionMergeRecord(
225613  u8 **paOut,
225614  int nCol,
225615  u8 *aLeft,
225616  u8 *aRight
225617){
225618  u8 *a1 = aLeft;                 /* Cursor used to iterate through aLeft */
225619  u8 *a2 = aRight;                /* Cursor used to iterate through aRight */
225620  u8 *aOut = *paOut;              /* Output cursor */
225621  int iCol;                       /* Used to iterate from 0 to nCol */
225622
225623  for(iCol=0; iCol<nCol; iCol++){
225624    int n1 = sessionSerialLen(a1);
225625    int n2 = sessionSerialLen(a2);
225626    if( *a2 ){
225627      memcpy(aOut, a2, n2);
225628      aOut += n2;
225629    }else{
225630      memcpy(aOut, a1, n1);
225631      aOut += n1;
225632    }
225633    a1 += n1;
225634    a2 += n2;
225635  }
225636
225637  *paOut = aOut;
225638}
225639
225640/*
225641** This is a helper function used by sessionMergeUpdate().
225642**
225643** When this function is called, both *paOne and *paTwo point to a value
225644** within a change record. Before it returns, both have been advanced so
225645** as to point to the next value in the record.
225646**
225647** If, when this function is called, *paTwo points to a valid value (i.e.
225648** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
225649** pointer is returned and *pnVal is set to the number of bytes in the
225650** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
225651** set to the number of bytes in the value at *paOne. If *paOne points
225652** to the "no value" placeholder, *pnVal is set to 1. In other words:
225653**
225654**   if( *paTwo is valid ) return *paTwo;
225655**   return *paOne;
225656**
225657*/
225658static u8 *sessionMergeValue(
225659  u8 **paOne,                     /* IN/OUT: Left-hand buffer pointer */
225660  u8 **paTwo,                     /* IN/OUT: Right-hand buffer pointer */
225661  int *pnVal                      /* OUT: Bytes in returned value */
225662){
225663  u8 *a1 = *paOne;
225664  u8 *a2 = *paTwo;
225665  u8 *pRet = 0;
225666  int n1;
225667
225668  assert( a1 );
225669  if( a2 ){
225670    int n2 = sessionSerialLen(a2);
225671    if( *a2 ){
225672      *pnVal = n2;
225673      pRet = a2;
225674    }
225675    *paTwo = &a2[n2];
225676  }
225677
225678  n1 = sessionSerialLen(a1);
225679  if( pRet==0 ){
225680    *pnVal = n1;
225681    pRet = a1;
225682  }
225683  *paOne = &a1[n1];
225684
225685  return pRet;
225686}
225687
225688/*
225689** This function is used by changeset_concat() to merge two UPDATE changes
225690** on the same row.
225691*/
225692static int sessionMergeUpdate(
225693  u8 **paOut,                     /* IN/OUT: Pointer to output buffer */
225694  SessionTable *pTab,             /* Table change pertains to */
225695  int bPatchset,                  /* True if records are patchset records */
225696  u8 *aOldRecord1,                /* old.* record for first change */
225697  u8 *aOldRecord2,                /* old.* record for second change */
225698  u8 *aNewRecord1,                /* new.* record for first change */
225699  u8 *aNewRecord2                 /* new.* record for second change */
225700){
225701  u8 *aOld1 = aOldRecord1;
225702  u8 *aOld2 = aOldRecord2;
225703  u8 *aNew1 = aNewRecord1;
225704  u8 *aNew2 = aNewRecord2;
225705
225706  u8 *aOut = *paOut;
225707  int i;
225708
225709  if( bPatchset==0 ){
225710    int bRequired = 0;
225711
225712    assert( aOldRecord1 && aNewRecord1 );
225713
225714    /* Write the old.* vector first. */
225715    for(i=0; i<pTab->nCol; i++){
225716      int nOld;
225717      u8 *aOld;
225718      int nNew;
225719      u8 *aNew;
225720
225721      aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
225722      aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
225723      if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
225724        if( pTab->abPK[i]==0 ) bRequired = 1;
225725        memcpy(aOut, aOld, nOld);
225726        aOut += nOld;
225727      }else{
225728        *(aOut++) = '\0';
225729      }
225730    }
225731
225732    if( !bRequired ) return 0;
225733  }
225734
225735  /* Write the new.* vector */
225736  aOld1 = aOldRecord1;
225737  aOld2 = aOldRecord2;
225738  aNew1 = aNewRecord1;
225739  aNew2 = aNewRecord2;
225740  for(i=0; i<pTab->nCol; i++){
225741    int nOld;
225742    u8 *aOld;
225743    int nNew;
225744    u8 *aNew;
225745
225746    aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
225747    aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
225748    if( bPatchset==0
225749     && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
225750    ){
225751      *(aOut++) = '\0';
225752    }else{
225753      memcpy(aOut, aNew, nNew);
225754      aOut += nNew;
225755    }
225756  }
225757
225758  *paOut = aOut;
225759  return 1;
225760}
225761
225762/*
225763** This function is only called from within a pre-update-hook callback.
225764** It determines if the current pre-update-hook change affects the same row
225765** as the change stored in argument pChange. If so, it returns true. Otherwise
225766** if the pre-update-hook does not affect the same row as pChange, it returns
225767** false.
225768*/
225769static int sessionPreupdateEqual(
225770  sqlite3_session *pSession,      /* Session object that owns SessionTable */
225771  i64 iRowid,                     /* Rowid value if pTab->bRowid */
225772  SessionTable *pTab,             /* Table associated with change */
225773  SessionChange *pChange,         /* Change to compare to */
225774  int op                          /* Current pre-update operation */
225775){
225776  int iCol;                       /* Used to iterate through columns */
225777  u8 *a = pChange->aRecord;       /* Cursor used to scan change record */
225778
225779  if( pTab->bRowid ){
225780    if( a[0]!=SQLITE_INTEGER ) return 0;
225781    return sessionGetI64(&a[1])==iRowid;
225782  }
225783
225784  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
225785  for(iCol=0; iCol<pTab->nCol; iCol++){
225786    if( !pTab->abPK[iCol] ){
225787      a += sessionSerialLen(a);
225788    }else{
225789      sqlite3_value *pVal;        /* Value returned by preupdate_new/old */
225790      int rc;                     /* Error code from preupdate_new/old */
225791      int eType = *a++;           /* Type of value from change record */
225792
225793      /* The following calls to preupdate_new() and preupdate_old() can not
225794      ** fail. This is because they cache their return values, and by the
225795      ** time control flows to here they have already been called once from
225796      ** within sessionPreupdateHash(). The first two asserts below verify
225797      ** this (that the method has already been called). */
225798      if( op==SQLITE_INSERT ){
225799        /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
225800        rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
225801      }else{
225802        /* assert( db->pPreUpdate->pUnpacked ); */
225803        rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
225804      }
225805      assert( rc==SQLITE_OK );
225806      (void)rc;                   /* Suppress warning about unused variable */
225807      if( sqlite3_value_type(pVal)!=eType ) return 0;
225808
225809      /* A SessionChange object never has a NULL value in a PK column */
225810      assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
225811           || eType==SQLITE_BLOB    || eType==SQLITE_TEXT
225812      );
225813
225814      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
225815        i64 iVal = sessionGetI64(a);
225816        a += 8;
225817        if( eType==SQLITE_INTEGER ){
225818          if( sqlite3_value_int64(pVal)!=iVal ) return 0;
225819        }else{
225820          double rVal;
225821          assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
225822          memcpy(&rVal, &iVal, 8);
225823          if( sqlite3_value_double(pVal)!=rVal ) return 0;
225824        }
225825      }else{
225826        int n;
225827        const u8 *z;
225828        a += sessionVarintGet(a, &n);
225829        if( sqlite3_value_bytes(pVal)!=n ) return 0;
225830        if( eType==SQLITE_TEXT ){
225831          z = sqlite3_value_text(pVal);
225832        }else{
225833          z = sqlite3_value_blob(pVal);
225834        }
225835        if( n>0 && memcmp(a, z, n) ) return 0;
225836        a += n;
225837      }
225838    }
225839  }
225840
225841  return 1;
225842}
225843
225844/*
225845** If required, grow the hash table used to store changes on table pTab
225846** (part of the session pSession). If a fatal OOM error occurs, set the
225847** session object to failed and return SQLITE_ERROR. Otherwise, return
225848** SQLITE_OK.
225849**
225850** It is possible that a non-fatal OOM error occurs in this function. In
225851** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
225852** Growing the hash table in this case is a performance optimization only,
225853** it is not required for correct operation.
225854*/
225855static int sessionGrowHash(
225856  sqlite3_session *pSession,      /* For memory accounting. May be NULL */
225857  int bPatchset,
225858  SessionTable *pTab
225859){
225860  if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
225861    int i;
225862    SessionChange **apNew;
225863    sqlite3_int64 nNew = 2*(sqlite3_int64)(pTab->nChange ? pTab->nChange : 128);
225864
225865    apNew = (SessionChange**)sessionMalloc64(
225866        pSession, sizeof(SessionChange*) * nNew
225867    );
225868    if( apNew==0 ){
225869      if( pTab->nChange==0 ){
225870        return SQLITE_ERROR;
225871      }
225872      return SQLITE_OK;
225873    }
225874    memset(apNew, 0, sizeof(SessionChange *) * nNew);
225875
225876    for(i=0; i<pTab->nChange; i++){
225877      SessionChange *p;
225878      SessionChange *pNext;
225879      for(p=pTab->apChange[i]; p; p=pNext){
225880        int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
225881        int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
225882        pNext = p->pNext;
225883        p->pNext = apNew[iHash];
225884        apNew[iHash] = p;
225885      }
225886    }
225887
225888    sessionFree(pSession, pTab->apChange);
225889    pTab->nChange = nNew;
225890    pTab->apChange = apNew;
225891  }
225892
225893  return SQLITE_OK;
225894}
225895
225896/*
225897** This function queries the database for the names of the columns of table
225898** zThis, in schema zDb.
225899**
225900** Otherwise, if they are not NULL, variable *pnCol is set to the number
225901** of columns in the database table and variable *pzTab is set to point to a
225902** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
225903** point to an array of pointers to column names. And *pabPK (again, if not
225904** NULL) is set to point to an array of booleans - true if the corresponding
225905** column is part of the primary key.
225906**
225907** For example, if the table is declared as:
225908**
225909**     CREATE TABLE tbl1(w, x DEFAULT 'abc', y, z, PRIMARY KEY(w, z));
225910**
225911** Then the five output variables are populated as follows:
225912**
225913**     *pnCol  = 4
225914**     *pzTab  = "tbl1"
225915**     *pazCol = {"w", "x", "y", "z"}
225916**     *pazDflt = {NULL, 'abc', NULL, NULL}
225917**     *pabPK  = {1, 0, 0, 1}
225918**
225919** All returned buffers are part of the same single allocation, which must
225920** be freed using sqlite3_free() by the caller
225921*/
225922static int sessionTableInfo(
225923  sqlite3_session *pSession,      /* For memory accounting. May be NULL */
225924  sqlite3 *db,                    /* Database connection */
225925  const char *zDb,                /* Name of attached database (e.g. "main") */
225926  const char *zThis,              /* Table name */
225927  int *pnCol,                     /* OUT: number of columns */
225928  const char **pzTab,             /* OUT: Copy of zThis */
225929  const char ***pazCol,           /* OUT: Array of column names for table */
225930  const char ***pazDflt,          /* OUT: Array of default value expressions */
225931  u8 **pabPK,                     /* OUT: Array of booleans - true for PK col */
225932  int *pbRowid                    /* OUT: True if only PK is a rowid */
225933){
225934  char *zPragma;
225935  sqlite3_stmt *pStmt;
225936  int rc;
225937  sqlite3_int64 nByte;
225938  int nDbCol = 0;
225939  int nThis;
225940  int i;
225941  u8 *pAlloc = 0;
225942  char **azCol = 0;
225943  char **azDflt = 0;
225944  u8 *abPK = 0;
225945  int bRowid = 0;                 /* Set to true to use rowid as PK */
225946
225947  assert( pazCol && pabPK );
225948
225949  *pazCol = 0;
225950  *pabPK = 0;
225951  *pnCol = 0;
225952  if( pzTab ) *pzTab = 0;
225953  if( pazDflt ) *pazDflt = 0;
225954
225955  nThis = sqlite3Strlen30(zThis);
225956  if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
225957    rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
225958    if( rc==SQLITE_OK ){
225959      /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
225960      zPragma = sqlite3_mprintf(
225961          "SELECT 0, 'tbl',  '', 0, '', 1     UNION ALL "
225962          "SELECT 1, 'idx',  '', 0, '', 2     UNION ALL "
225963          "SELECT 2, 'stat', '', 0, '', 0"
225964      );
225965    }else if( rc==SQLITE_ERROR ){
225966      zPragma = sqlite3_mprintf("");
225967    }else{
225968      return rc;
225969    }
225970  }else{
225971    zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
225972  }
225973  if( !zPragma ){
225974    return SQLITE_NOMEM;
225975  }
225976
225977  rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
225978  sqlite3_free(zPragma);
225979  if( rc!=SQLITE_OK ){
225980    return rc;
225981  }
225982
225983  nByte = nThis + 1;
225984  bRowid = (pbRowid!=0);
225985  while( SQLITE_ROW==sqlite3_step(pStmt) ){
225986    nByte += sqlite3_column_bytes(pStmt, 1);          /* name */
225987    nByte += sqlite3_column_bytes(pStmt, 4);          /* dflt_value */
225988    nDbCol++;
225989    if( sqlite3_column_int(pStmt, 5) ) bRowid = 0;    /* pk */
225990  }
225991  if( nDbCol==0 ) bRowid = 0;
225992  nDbCol += bRowid;
225993  nByte += strlen(SESSIONS_ROWID);
225994  rc = sqlite3_reset(pStmt);
225995
225996  if( rc==SQLITE_OK ){
225997    nByte += nDbCol * (sizeof(const char *)*2 + sizeof(u8) + 1 + 1);
225998    pAlloc = sessionMalloc64(pSession, nByte);
225999    if( pAlloc==0 ){
226000      rc = SQLITE_NOMEM;
226001    }else{
226002      memset(pAlloc, 0, nByte);
226003    }
226004  }
226005  if( rc==SQLITE_OK ){
226006    azCol = (char **)pAlloc;
226007    azDflt = (char**)&azCol[nDbCol];
226008    pAlloc = (u8 *)&azDflt[nDbCol];
226009    abPK = (u8 *)pAlloc;
226010    pAlloc = &abPK[nDbCol];
226011    if( pzTab ){
226012      memcpy(pAlloc, zThis, nThis+1);
226013      *pzTab = (char *)pAlloc;
226014      pAlloc += nThis+1;
226015    }
226016
226017    i = 0;
226018    if( bRowid ){
226019      size_t nName = strlen(SESSIONS_ROWID);
226020      memcpy(pAlloc, SESSIONS_ROWID, nName+1);
226021      azCol[i] = (char*)pAlloc;
226022      pAlloc += nName+1;
226023      abPK[i] = 1;
226024      i++;
226025    }
226026    while( SQLITE_ROW==sqlite3_step(pStmt) ){
226027      int nName = sqlite3_column_bytes(pStmt, 1);
226028      int nDflt = sqlite3_column_bytes(pStmt, 4);
226029      const unsigned char *zName = sqlite3_column_text(pStmt, 1);
226030      const unsigned char *zDflt = sqlite3_column_text(pStmt, 4);
226031
226032      if( zName==0 ) break;
226033      memcpy(pAlloc, zName, nName+1);
226034      azCol[i] = (char *)pAlloc;
226035      pAlloc += nName+1;
226036      if( zDflt ){
226037        memcpy(pAlloc, zDflt, nDflt+1);
226038        azDflt[i] = (char *)pAlloc;
226039        pAlloc += nDflt+1;
226040      }else{
226041        azDflt[i] = 0;
226042      }
226043      abPK[i] = sqlite3_column_int(pStmt, 5);
226044      i++;
226045    }
226046    rc = sqlite3_reset(pStmt);
226047  }
226048
226049  /* If successful, populate the output variables. Otherwise, zero them and
226050  ** free any allocation made. An error code will be returned in this case.
226051  */
226052  if( rc==SQLITE_OK ){
226053    *pazCol = (const char**)azCol;
226054    if( pazDflt ) *pazDflt = (const char**)azDflt;
226055    *pabPK = abPK;
226056    *pnCol = nDbCol;
226057  }else{
226058    sessionFree(pSession, azCol);
226059  }
226060  if( pbRowid ) *pbRowid = bRowid;
226061  sqlite3_finalize(pStmt);
226062  return rc;
226063}
226064
226065/*
226066** This function is called to initialize the SessionTable.nCol, azCol[]
226067** abPK[] and azDflt[] members of SessionTable object pTab. If these
226068** fields are already initilialized, this function is a no-op.
226069**
226070** If an error occurs, an error code is stored in sqlite3_session.rc and
226071** non-zero returned. Or, if no error occurs but the table has no primary
226072** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
226073** indicate that updates on this table should be ignored. SessionTable.abPK
226074** is set to NULL in this case.
226075*/
226076static int sessionInitTable(
226077  sqlite3_session *pSession,      /* Optional session handle */
226078  SessionTable *pTab,             /* Table object to initialize */
226079  sqlite3 *db,                    /* Database handle to read schema from */
226080  const char *zDb                 /* Name of db - "main", "temp" etc. */
226081){
226082  int rc = SQLITE_OK;
226083
226084  if( pTab->nCol==0 ){
226085    u8 *abPK;
226086    assert( pTab->azCol==0 || pTab->abPK==0 );
226087    rc = sessionTableInfo(pSession, db, zDb,
226088        pTab->zName, &pTab->nCol, 0, &pTab->azCol, &pTab->azDflt, &abPK,
226089        ((pSession==0 || pSession->bImplicitPK) ? &pTab->bRowid : 0)
226090    );
226091    if( rc==SQLITE_OK ){
226092      int i;
226093      for(i=0; i<pTab->nCol; i++){
226094        if( abPK[i] ){
226095          pTab->abPK = abPK;
226096          break;
226097        }
226098      }
226099      if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
226100        pTab->bStat1 = 1;
226101      }
226102
226103      if( pSession && pSession->bEnableSize ){
226104        pSession->nMaxChangesetSize += (
226105          1 + sessionVarintLen(pTab->nCol) + pTab->nCol + strlen(pTab->zName)+1
226106        );
226107      }
226108    }
226109  }
226110
226111  if( pSession ){
226112    pSession->rc = rc;
226113    return (rc || pTab->abPK==0);
226114  }
226115  return rc;
226116}
226117
226118/*
226119** Re-initialize table object pTab.
226120*/
226121static int sessionReinitTable(sqlite3_session *pSession, SessionTable *pTab){
226122  int nCol = 0;
226123  const char **azCol = 0;
226124  const char **azDflt = 0;
226125  u8 *abPK = 0;
226126  int bRowid = 0;
226127
226128  assert( pSession->rc==SQLITE_OK );
226129
226130  pSession->rc = sessionTableInfo(pSession, pSession->db, pSession->zDb,
226131      pTab->zName, &nCol, 0, &azCol, &azDflt, &abPK,
226132      (pSession->bImplicitPK ? &bRowid : 0)
226133  );
226134  if( pSession->rc==SQLITE_OK ){
226135    if( pTab->nCol>nCol || pTab->bRowid!=bRowid ){
226136      pSession->rc = SQLITE_SCHEMA;
226137    }else{
226138      int ii;
226139      int nOldCol = pTab->nCol;
226140      for(ii=0; ii<nCol; ii++){
226141        if( ii<pTab->nCol ){
226142          if( pTab->abPK[ii]!=abPK[ii] ){
226143            pSession->rc = SQLITE_SCHEMA;
226144          }
226145        }else if( abPK[ii] ){
226146          pSession->rc = SQLITE_SCHEMA;
226147        }
226148      }
226149
226150      if( pSession->rc==SQLITE_OK ){
226151        const char **a = pTab->azCol;
226152        pTab->azCol = azCol;
226153        pTab->nCol = nCol;
226154        pTab->azDflt = azDflt;
226155        pTab->abPK = abPK;
226156        azCol = a;
226157      }
226158      if( pSession->bEnableSize ){
226159        pSession->nMaxChangesetSize += (nCol - nOldCol);
226160        pSession->nMaxChangesetSize += sessionVarintLen(nCol);
226161        pSession->nMaxChangesetSize -= sessionVarintLen(nOldCol);
226162      }
226163    }
226164  }
226165
226166  sqlite3_free((char*)azCol);
226167  return pSession->rc;
226168}
226169
226170/*
226171** Session-change object (*pp) contains an old.* record with fewer than
226172** nCol fields. This function updates it with the default values for
226173** the missing fields.
226174*/
226175static void sessionUpdateOneChange(
226176  sqlite3_session *pSession,      /* For memory accounting */
226177  int *pRc,                       /* IN/OUT: Error code */
226178  SessionChange **pp,             /* IN/OUT: Change object to update */
226179  int nCol,                       /* Number of columns now in table */
226180  sqlite3_stmt *pDflt             /* SELECT <default-values...> */
226181){
226182  SessionChange *pOld = *pp;
226183
226184  while( pOld->nRecordField<nCol ){
226185    SessionChange *pNew = 0;
226186    int nByte = 0;
226187    int nIncr = 0;
226188    int iField = pOld->nRecordField;
226189    int eType = sqlite3_column_type(pDflt, iField);
226190    switch( eType ){
226191      case SQLITE_NULL:
226192        nIncr = 1;
226193        break;
226194      case SQLITE_INTEGER:
226195      case SQLITE_FLOAT:
226196        nIncr = 9;
226197        break;
226198      default: {
226199        int n = sqlite3_column_bytes(pDflt, iField);
226200        nIncr = 1 + sessionVarintLen(n) + n;
226201        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
226202        break;
226203      }
226204    }
226205
226206    nByte = nIncr + (sizeof(SessionChange) + pOld->nRecord);
226207    pNew = sessionMalloc64(pSession, nByte);
226208    if( pNew==0 ){
226209      *pRc = SQLITE_NOMEM;
226210      return;
226211    }else{
226212      memcpy(pNew, pOld, sizeof(SessionChange));
226213      pNew->aRecord = (u8*)&pNew[1];
226214      memcpy(pNew->aRecord, pOld->aRecord, pOld->nRecord);
226215      pNew->aRecord[pNew->nRecord++] = (u8)eType;
226216      switch( eType ){
226217        case SQLITE_INTEGER: {
226218          i64 iVal = sqlite3_column_int64(pDflt, iField);
226219          sessionPutI64(&pNew->aRecord[pNew->nRecord], iVal);
226220          pNew->nRecord += 8;
226221          break;
226222        }
226223
226224        case SQLITE_FLOAT: {
226225          double rVal = sqlite3_column_double(pDflt, iField);
226226          i64 iVal = 0;
226227          memcpy(&iVal, &rVal, sizeof(rVal));
226228          sessionPutI64(&pNew->aRecord[pNew->nRecord], iVal);
226229          pNew->nRecord += 8;
226230          break;
226231        }
226232
226233        case SQLITE_TEXT: {
226234          int n = sqlite3_column_bytes(pDflt, iField);
226235          const char *z = (const char*)sqlite3_column_text(pDflt, iField);
226236          pNew->nRecord += sessionVarintPut(&pNew->aRecord[pNew->nRecord], n);
226237          memcpy(&pNew->aRecord[pNew->nRecord], z, n);
226238          pNew->nRecord += n;
226239          break;
226240        }
226241
226242        case SQLITE_BLOB: {
226243          int n = sqlite3_column_bytes(pDflt, iField);
226244          const u8 *z = (const u8*)sqlite3_column_blob(pDflt, iField);
226245          pNew->nRecord += sessionVarintPut(&pNew->aRecord[pNew->nRecord], n);
226246          memcpy(&pNew->aRecord[pNew->nRecord], z, n);
226247          pNew->nRecord += n;
226248          break;
226249        }
226250
226251        default:
226252          assert( eType==SQLITE_NULL );
226253          break;
226254      }
226255
226256      sessionFree(pSession, pOld);
226257      *pp = pOld = pNew;
226258      pNew->nRecordField++;
226259      pNew->nMaxSize += nIncr;
226260      if( pSession ){
226261        pSession->nMaxChangesetSize += nIncr;
226262      }
226263    }
226264  }
226265}
226266
226267/*
226268** Ensure that there is room in the buffer to append nByte bytes of data.
226269** If not, use sqlite3_realloc() to grow the buffer so that there is.
226270**
226271** If successful, return zero. Otherwise, if an OOM condition is encountered,
226272** set *pRc to SQLITE_NOMEM and return non-zero.
226273*/
226274static int sessionBufferGrow(SessionBuffer *p, i64 nByte, int *pRc){
226275#define SESSION_MAX_BUFFER_SZ (0x7FFFFF00 - 1)
226276  i64 nReq = p->nBuf + nByte;
226277  if( *pRc==SQLITE_OK && nReq>p->nAlloc ){
226278    u8 *aNew;
226279    i64 nNew = p->nAlloc ? p->nAlloc : 128;
226280
226281    do {
226282      nNew = nNew*2;
226283    }while( nNew<nReq );
226284
226285    /* The value of SESSION_MAX_BUFFER_SZ is copied from the implementation
226286    ** of sqlite3_realloc64(). Allocations greater than this size in bytes
226287    ** always fail. It is used here to ensure that this routine can always
226288    ** allocate up to this limit - instead of up to the largest power of
226289    ** two smaller than the limit.  */
226290    if( nNew>SESSION_MAX_BUFFER_SZ ){
226291      nNew = SESSION_MAX_BUFFER_SZ;
226292      if( nNew<nReq ){
226293        *pRc = SQLITE_NOMEM;
226294        return 1;
226295      }
226296    }
226297
226298    aNew = (u8 *)sqlite3_realloc64(p->aBuf, nNew);
226299    if( 0==aNew ){
226300      *pRc = SQLITE_NOMEM;
226301    }else{
226302      p->aBuf = aNew;
226303      p->nAlloc = nNew;
226304    }
226305  }
226306  return (*pRc!=SQLITE_OK);
226307}
226308
226309
226310/*
226311** This function is a no-op if *pRc is other than SQLITE_OK when it is
226312** called. Otherwise, append a string to the buffer. All bytes in the string
226313** up to (but not including) the nul-terminator are written to the buffer.
226314**
226315** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
226316** returning.
226317*/
226318static void sessionAppendStr(
226319  SessionBuffer *p,
226320  const char *zStr,
226321  int *pRc
226322){
226323  int nStr = sqlite3Strlen30(zStr);
226324  if( 0==sessionBufferGrow(p, nStr+1, pRc) ){
226325    memcpy(&p->aBuf[p->nBuf], zStr, nStr);
226326    p->nBuf += nStr;
226327    p->aBuf[p->nBuf] = 0x00;
226328  }
226329}
226330
226331/*
226332** Format a string using printf() style formatting and then append it to the
226333** buffer using sessionAppendString().
226334*/
226335static void sessionAppendPrintf(
226336  SessionBuffer *p,               /* Buffer to append to */
226337  int *pRc,
226338  const char *zFmt,
226339  ...
226340){
226341  if( *pRc==SQLITE_OK ){
226342    char *zApp = 0;
226343    va_list ap;
226344    va_start(ap, zFmt);
226345    zApp = sqlite3_vmprintf(zFmt, ap);
226346    if( zApp==0 ){
226347      *pRc = SQLITE_NOMEM;
226348    }else{
226349      sessionAppendStr(p, zApp, pRc);
226350    }
226351    va_end(ap);
226352    sqlite3_free(zApp);
226353  }
226354}
226355
226356/*
226357** Prepare a statement against database handle db that SELECTs a single
226358** row containing the default values for each column in table pTab. For
226359** example, if pTab is declared as:
226360**
226361**   CREATE TABLE pTab(a PRIMARY KEY, b DEFAULT 123, c DEFAULT 'abcd');
226362**
226363** Then this function prepares and returns the SQL statement:
226364**
226365**   SELECT NULL, 123, 'abcd';
226366*/
226367static int sessionPrepareDfltStmt(
226368  sqlite3 *db,                    /* Database handle */
226369  SessionTable *pTab,             /* Table to prepare statement for */
226370  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
226371){
226372  SessionBuffer sql = {0,0,0};
226373  int rc = SQLITE_OK;
226374  const char *zSep = " ";
226375  int ii = 0;
226376
226377  *ppStmt = 0;
226378  sessionAppendPrintf(&sql, &rc, "SELECT");
226379  for(ii=0; ii<pTab->nCol; ii++){
226380    const char *zDflt = pTab->azDflt[ii] ? pTab->azDflt[ii] : "NULL";
226381    sessionAppendPrintf(&sql, &rc, "%s%s", zSep, zDflt);
226382    zSep = ", ";
226383  }
226384  if( rc==SQLITE_OK ){
226385    rc = sqlite3_prepare_v2(db, (const char*)sql.aBuf, -1, ppStmt, 0);
226386  }
226387  sqlite3_free(sql.aBuf);
226388
226389  return rc;
226390}
226391
226392/*
226393** Table pTab has one or more existing change-records with old.* records
226394** with fewer than pTab->nCol columns. This function updates all such
226395** change-records with the default values for the missing columns.
226396*/
226397static int sessionUpdateChanges(sqlite3_session *pSession, SessionTable *pTab){
226398  sqlite3_stmt *pStmt = 0;
226399  int rc = pSession->rc;
226400
226401  rc = sessionPrepareDfltStmt(pSession->db, pTab, &pStmt);
226402  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
226403    int ii = 0;
226404    SessionChange **pp = 0;
226405    for(ii=0; ii<pTab->nChange; ii++){
226406      for(pp=&pTab->apChange[ii]; *pp; pp=&((*pp)->pNext)){
226407        if( (*pp)->nRecordField!=pTab->nCol ){
226408          sessionUpdateOneChange(pSession, &rc, pp, pTab->nCol, pStmt);
226409        }
226410      }
226411    }
226412  }
226413
226414  pSession->rc = rc;
226415  rc = sqlite3_finalize(pStmt);
226416  if( pSession->rc==SQLITE_OK ) pSession->rc = rc;
226417  return pSession->rc;
226418}
226419
226420/*
226421** Versions of the four methods in object SessionHook for use with the
226422** sqlite_stat1 table. The purpose of this is to substitute a zero-length
226423** blob each time a NULL value is read from the "idx" column of the
226424** sqlite_stat1 table.
226425*/
226426typedef struct SessionStat1Ctx SessionStat1Ctx;
226427struct SessionStat1Ctx {
226428  SessionHook hook;
226429  sqlite3_session *pSession;
226430};
226431static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){
226432  SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
226433  sqlite3_value *pVal = 0;
226434  int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);
226435  if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
226436    pVal = p->pSession->pZeroBlob;
226437  }
226438  *ppVal = pVal;
226439  return rc;
226440}
226441static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){
226442  SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
226443  sqlite3_value *pVal = 0;
226444  int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);
226445  if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
226446    pVal = p->pSession->pZeroBlob;
226447  }
226448  *ppVal = pVal;
226449  return rc;
226450}
226451static int sessionStat1Count(void *pCtx){
226452  SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
226453  return p->hook.xCount(p->hook.pCtx);
226454}
226455static int sessionStat1Depth(void *pCtx){
226456  SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
226457  return p->hook.xDepth(p->hook.pCtx);
226458}
226459
226460static int sessionUpdateMaxSize(
226461  int op,
226462  sqlite3_session *pSession,      /* Session object pTab is attached to */
226463  SessionTable *pTab,             /* Table that change applies to */
226464  SessionChange *pC               /* Update pC->nMaxSize */
226465){
226466  i64 nNew = 2;
226467  if( pC->op==SQLITE_INSERT ){
226468    if( pTab->bRowid ) nNew += 9;
226469    if( op!=SQLITE_DELETE ){
226470      int ii;
226471      for(ii=0; ii<pTab->nCol; ii++){
226472        sqlite3_value *p = 0;
226473        pSession->hook.xNew(pSession->hook.pCtx, ii, &p);
226474        sessionSerializeValue(0, p, &nNew);
226475      }
226476    }
226477  }else if( op==SQLITE_DELETE ){
226478    nNew += pC->nRecord;
226479    if( sqlite3_preupdate_blobwrite(pSession->db)>=0 ){
226480      nNew += pC->nRecord;
226481    }
226482  }else{
226483    int ii;
226484    u8 *pCsr = pC->aRecord;
226485    if( pTab->bRowid ){
226486      nNew += 9 + 1;
226487      pCsr += 9;
226488    }
226489    for(ii=pTab->bRowid; ii<pTab->nCol; ii++){
226490      int bChanged = 1;
226491      int nOld = 0;
226492      int eType;
226493      sqlite3_value *p = 0;
226494      pSession->hook.xNew(pSession->hook.pCtx, ii-pTab->bRowid, &p);
226495      if( p==0 ){
226496        return SQLITE_NOMEM;
226497      }
226498
226499      eType = *pCsr++;
226500      switch( eType ){
226501        case SQLITE_NULL:
226502          bChanged = sqlite3_value_type(p)!=SQLITE_NULL;
226503          break;
226504
226505        case SQLITE_FLOAT:
226506        case SQLITE_INTEGER: {
226507          if( eType==sqlite3_value_type(p) ){
226508            sqlite3_int64 iVal = sessionGetI64(pCsr);
226509            if( eType==SQLITE_INTEGER ){
226510              bChanged = (iVal!=sqlite3_value_int64(p));
226511            }else{
226512              double dVal;
226513              memcpy(&dVal, &iVal, 8);
226514              bChanged = (dVal!=sqlite3_value_double(p));
226515            }
226516          }
226517          nOld = 8;
226518          pCsr += 8;
226519          break;
226520        }
226521
226522        default: {
226523          int nByte;
226524          nOld = sessionVarintGet(pCsr, &nByte);
226525          pCsr += nOld;
226526          nOld += nByte;
226527          assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
226528          if( eType==sqlite3_value_type(p)
226529           && nByte==sqlite3_value_bytes(p)
226530           && (nByte==0 || 0==memcmp(pCsr, sqlite3_value_blob(p), nByte))
226531          ){
226532            bChanged = 0;
226533          }
226534          pCsr += nByte;
226535          break;
226536        }
226537      }
226538
226539      if( bChanged && pTab->abPK[ii] ){
226540        nNew = pC->nRecord + 2;
226541        break;
226542      }
226543
226544      if( bChanged ){
226545        nNew += 1 + nOld;
226546        sessionSerializeValue(0, p, &nNew);
226547      }else if( pTab->abPK[ii] ){
226548        nNew += 2 + nOld;
226549      }else{
226550        nNew += 2;
226551      }
226552    }
226553  }
226554
226555  if( nNew>pC->nMaxSize ){
226556    int nIncr = nNew - pC->nMaxSize;
226557    pC->nMaxSize = nNew;
226558    pSession->nMaxChangesetSize += nIncr;
226559  }
226560  return SQLITE_OK;
226561}
226562
226563/*
226564** This function is only called from with a pre-update-hook reporting a
226565** change on table pTab (attached to session pSession). The type of change
226566** (UPDATE, INSERT, DELETE) is specified by the first argument.
226567**
226568** Unless one is already present or an error occurs, an entry is added
226569** to the changed-rows hash table associated with table pTab.
226570*/
226571static void sessionPreupdateOneChange(
226572  int op,                         /* One of SQLITE_UPDATE, INSERT, DELETE */
226573  i64 iRowid,
226574  sqlite3_session *pSession,      /* Session object pTab is attached to */
226575  SessionTable *pTab              /* Table that change applies to */
226576){
226577  int iHash;
226578  int bNull = 0;
226579  int rc = SQLITE_OK;
226580  int nExpect = 0;
226581  SessionStat1Ctx stat1 = {{0,0,0,0,0},0};
226582
226583  if( pSession->rc ) return;
226584
226585  /* Load table details if required */
226586  if( sessionInitTable(pSession, pTab, pSession->db, pSession->zDb) ) return;
226587
226588  /* Check the number of columns in this xPreUpdate call matches the
226589  ** number of columns in the table.  */
226590  nExpect = pSession->hook.xCount(pSession->hook.pCtx);
226591  if( (pTab->nCol-pTab->bRowid)<nExpect ){
226592    if( sessionReinitTable(pSession, pTab) ) return;
226593    if( sessionUpdateChanges(pSession, pTab) ) return;
226594  }
226595  if( (pTab->nCol-pTab->bRowid)!=nExpect ){
226596    pSession->rc = SQLITE_SCHEMA;
226597    return;
226598  }
226599
226600  /* Grow the hash table if required */
226601  if( sessionGrowHash(pSession, 0, pTab) ){
226602    pSession->rc = SQLITE_NOMEM;
226603    return;
226604  }
226605
226606  if( pTab->bStat1 ){
226607    stat1.hook = pSession->hook;
226608    stat1.pSession = pSession;
226609    pSession->hook.pCtx = (void*)&stat1;
226610    pSession->hook.xNew = sessionStat1New;
226611    pSession->hook.xOld = sessionStat1Old;
226612    pSession->hook.xCount = sessionStat1Count;
226613    pSession->hook.xDepth = sessionStat1Depth;
226614    if( pSession->pZeroBlob==0 ){
226615      sqlite3_value *p = sqlite3ValueNew(0);
226616      if( p==0 ){
226617        rc = SQLITE_NOMEM;
226618        goto error_out;
226619      }
226620      sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC);
226621      pSession->pZeroBlob = p;
226622    }
226623  }
226624
226625  /* Calculate the hash-key for this change. If the primary key of the row
226626  ** includes a NULL value, exit early. Such changes are ignored by the
226627  ** session module. */
226628  rc = sessionPreupdateHash(
226629      pSession, iRowid, pTab, op==SQLITE_INSERT, &iHash, &bNull
226630  );
226631  if( rc!=SQLITE_OK ) goto error_out;
226632
226633  if( bNull==0 ){
226634    /* Search the hash table for an existing record for this row. */
226635    SessionChange *pC;
226636    for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
226637      if( sessionPreupdateEqual(pSession, iRowid, pTab, pC, op) ) break;
226638    }
226639
226640    if( pC==0 ){
226641      /* Create a new change object containing all the old values (if
226642      ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
226643      ** values (if this is an INSERT). */
226644      sqlite3_int64 nByte;    /* Number of bytes to allocate */
226645      int i;                  /* Used to iterate through columns */
226646
226647      assert( rc==SQLITE_OK );
226648      pTab->nEntry++;
226649
226650      /* Figure out how large an allocation is required */
226651      nByte = sizeof(SessionChange);
226652      for(i=0; i<(pTab->nCol-pTab->bRowid); i++){
226653        sqlite3_value *p = 0;
226654        if( op!=SQLITE_INSERT ){
226655          TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
226656          assert( trc==SQLITE_OK );
226657        }else if( pTab->abPK[i] ){
226658          TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
226659          assert( trc==SQLITE_OK );
226660        }
226661
226662        /* This may fail if SQLite value p contains a utf-16 string that must
226663        ** be converted to utf-8 and an OOM error occurs while doing so. */
226664        rc = sessionSerializeValue(0, p, &nByte);
226665        if( rc!=SQLITE_OK ) goto error_out;
226666      }
226667      if( pTab->bRowid ){
226668        nByte += 9;               /* Size of rowid field - an integer */
226669      }
226670
226671      /* Allocate the change object */
226672      pC = (SessionChange*)sessionMalloc64(pSession, nByte);
226673      if( !pC ){
226674        rc = SQLITE_NOMEM;
226675        goto error_out;
226676      }else{
226677        memset(pC, 0, sizeof(SessionChange));
226678        pC->aRecord = (u8 *)&pC[1];
226679      }
226680
226681      /* Populate the change object. None of the preupdate_old(),
226682      ** preupdate_new() or SerializeValue() calls below may fail as all
226683      ** required values and encodings have already been cached in memory.
226684      ** It is not possible for an OOM to occur in this block. */
226685      nByte = 0;
226686      if( pTab->bRowid ){
226687        pC->aRecord[0] = SQLITE_INTEGER;
226688        sessionPutI64(&pC->aRecord[1], iRowid);
226689        nByte = 9;
226690      }
226691      for(i=0; i<(pTab->nCol-pTab->bRowid); i++){
226692        sqlite3_value *p = 0;
226693        if( op!=SQLITE_INSERT ){
226694          pSession->hook.xOld(pSession->hook.pCtx, i, &p);
226695        }else if( pTab->abPK[i] ){
226696          pSession->hook.xNew(pSession->hook.pCtx, i, &p);
226697        }
226698        sessionSerializeValue(&pC->aRecord[nByte], p, &nByte);
226699      }
226700
226701      /* Add the change to the hash-table */
226702      if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
226703        pC->bIndirect = 1;
226704      }
226705      pC->nRecordField = pTab->nCol;
226706      pC->nRecord = nByte;
226707      pC->op = op;
226708      pC->pNext = pTab->apChange[iHash];
226709      pTab->apChange[iHash] = pC;
226710
226711    }else if( pC->bIndirect ){
226712      /* If the existing change is considered "indirect", but this current
226713      ** change is "direct", mark the change object as direct. */
226714      if( pSession->hook.xDepth(pSession->hook.pCtx)==0
226715       && pSession->bIndirect==0
226716      ){
226717        pC->bIndirect = 0;
226718      }
226719    }
226720
226721    assert( rc==SQLITE_OK );
226722    if( pSession->bEnableSize ){
226723      rc = sessionUpdateMaxSize(op, pSession, pTab, pC);
226724    }
226725  }
226726
226727
226728  /* If an error has occurred, mark the session object as failed. */
226729 error_out:
226730  if( pTab->bStat1 ){
226731    pSession->hook = stat1.hook;
226732  }
226733  if( rc!=SQLITE_OK ){
226734    pSession->rc = rc;
226735  }
226736}
226737
226738static int sessionFindTable(
226739  sqlite3_session *pSession,
226740  const char *zName,
226741  SessionTable **ppTab
226742){
226743  int rc = SQLITE_OK;
226744  int nName = sqlite3Strlen30(zName);
226745  SessionTable *pRet;
226746
226747  /* Search for an existing table */
226748  for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
226749    if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
226750  }
226751
226752  if( pRet==0 && pSession->bAutoAttach ){
226753    /* If there is a table-filter configured, invoke it. If it returns 0,
226754    ** do not automatically add the new table. */
226755    if( pSession->xTableFilter==0
226756     || pSession->xTableFilter(pSession->pFilterCtx, zName)
226757    ){
226758      rc = sqlite3session_attach(pSession, zName);
226759      if( rc==SQLITE_OK ){
226760        pRet = pSession->pTable;
226761        while( ALWAYS(pRet) && pRet->pNext ){
226762          pRet = pRet->pNext;
226763        }
226764        assert( pRet!=0 );
226765        assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
226766      }
226767    }
226768  }
226769
226770  assert( rc==SQLITE_OK || pRet==0 );
226771  *ppTab = pRet;
226772  return rc;
226773}
226774
226775/*
226776** The 'pre-update' hook registered by this module with SQLite databases.
226777*/
226778static void xPreUpdate(
226779  void *pCtx,                     /* Copy of third arg to preupdate_hook() */
226780  sqlite3 *db,                    /* Database handle */
226781  int op,                         /* SQLITE_UPDATE, DELETE or INSERT */
226782  char const *zDb,                /* Database name */
226783  char const *zName,              /* Table name */
226784  sqlite3_int64 iKey1,            /* Rowid of row about to be deleted/updated */
226785  sqlite3_int64 iKey2             /* New rowid value (for a rowid UPDATE) */
226786){
226787  sqlite3_session *pSession;
226788  int nDb = sqlite3Strlen30(zDb);
226789
226790  assert( sqlite3_mutex_held(db->mutex) );
226791  (void)iKey1;
226792  (void)iKey2;
226793
226794  for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
226795    SessionTable *pTab;
226796
226797    /* If this session is attached to a different database ("main", "temp"
226798    ** etc.), or if it is not currently enabled, there is nothing to do. Skip
226799    ** to the next session object attached to this database. */
226800    if( pSession->bEnable==0 ) continue;
226801    if( pSession->rc ) continue;
226802    if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
226803
226804    pSession->rc = sessionFindTable(pSession, zName, &pTab);
226805    if( pTab ){
226806      assert( pSession->rc==SQLITE_OK );
226807      assert( op==SQLITE_UPDATE || iKey1==iKey2 );
226808      sessionPreupdateOneChange(op, iKey1, pSession, pTab);
226809      if( op==SQLITE_UPDATE ){
226810        sessionPreupdateOneChange(SQLITE_INSERT, iKey2, pSession, pTab);
226811      }
226812    }
226813  }
226814}
226815
226816/*
226817** The pre-update hook implementations.
226818*/
226819static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
226820  return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
226821}
226822static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
226823  return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
226824}
226825static int sessionPreupdateCount(void *pCtx){
226826  return sqlite3_preupdate_count((sqlite3*)pCtx);
226827}
226828static int sessionPreupdateDepth(void *pCtx){
226829  return sqlite3_preupdate_depth((sqlite3*)pCtx);
226830}
226831
226832/*
226833** Install the pre-update hooks on the session object passed as the only
226834** argument.
226835*/
226836static void sessionPreupdateHooks(
226837  sqlite3_session *pSession
226838){
226839  pSession->hook.pCtx = (void*)pSession->db;
226840  pSession->hook.xOld = sessionPreupdateOld;
226841  pSession->hook.xNew = sessionPreupdateNew;
226842  pSession->hook.xCount = sessionPreupdateCount;
226843  pSession->hook.xDepth = sessionPreupdateDepth;
226844}
226845
226846typedef struct SessionDiffCtx SessionDiffCtx;
226847struct SessionDiffCtx {
226848  sqlite3_stmt *pStmt;
226849  int bRowid;
226850  int nOldOff;
226851};
226852
226853/*
226854** The diff hook implementations.
226855*/
226856static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
226857  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
226858  *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff+p->bRowid);
226859  return SQLITE_OK;
226860}
226861static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
226862  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
226863  *ppVal = sqlite3_column_value(p->pStmt, iVal+p->bRowid);
226864   return SQLITE_OK;
226865}
226866static int sessionDiffCount(void *pCtx){
226867  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
226868  return (p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt)) - p->bRowid;
226869}
226870static int sessionDiffDepth(void *pCtx){
226871  (void)pCtx;
226872  return 0;
226873}
226874
226875/*
226876** Install the diff hooks on the session object passed as the only
226877** argument.
226878*/
226879static void sessionDiffHooks(
226880  sqlite3_session *pSession,
226881  SessionDiffCtx *pDiffCtx
226882){
226883  pSession->hook.pCtx = (void*)pDiffCtx;
226884  pSession->hook.xOld = sessionDiffOld;
226885  pSession->hook.xNew = sessionDiffNew;
226886  pSession->hook.xCount = sessionDiffCount;
226887  pSession->hook.xDepth = sessionDiffDepth;
226888}
226889
226890static char *sessionExprComparePK(
226891  int nCol,
226892  const char *zDb1, const char *zDb2,
226893  const char *zTab,
226894  const char **azCol, u8 *abPK
226895){
226896  int i;
226897  const char *zSep = "";
226898  char *zRet = 0;
226899
226900  for(i=0; i<nCol; i++){
226901    if( abPK[i] ){
226902      zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
226903          zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
226904      );
226905      zSep = " AND ";
226906      if( zRet==0 ) break;
226907    }
226908  }
226909
226910  return zRet;
226911}
226912
226913static char *sessionExprCompareOther(
226914  int nCol,
226915  const char *zDb1, const char *zDb2,
226916  const char *zTab,
226917  const char **azCol, u8 *abPK
226918){
226919  int i;
226920  const char *zSep = "";
226921  char *zRet = 0;
226922  int bHave = 0;
226923
226924  for(i=0; i<nCol; i++){
226925    if( abPK[i]==0 ){
226926      bHave = 1;
226927      zRet = sqlite3_mprintf(
226928          "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
226929          zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
226930      );
226931      zSep = " OR ";
226932      if( zRet==0 ) break;
226933    }
226934  }
226935
226936  if( bHave==0 ){
226937    assert( zRet==0 );
226938    zRet = sqlite3_mprintf("0");
226939  }
226940
226941  return zRet;
226942}
226943
226944static char *sessionSelectFindNew(
226945  const char *zDb1,      /* Pick rows in this db only */
226946  const char *zDb2,      /* But not in this one */
226947  int bRowid,
226948  const char *zTbl,      /* Table name */
226949  const char *zExpr
226950){
226951  const char *zSel = (bRowid ? SESSIONS_ROWID ", *" : "*");
226952  char *zRet = sqlite3_mprintf(
226953      "SELECT %s FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
226954      "  SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
226955      ")",
226956      zSel, zDb1, zTbl, zDb2, zTbl, zExpr
226957  );
226958  return zRet;
226959}
226960
226961static int sessionDiffFindNew(
226962  int op,
226963  sqlite3_session *pSession,
226964  SessionTable *pTab,
226965  const char *zDb1,
226966  const char *zDb2,
226967  char *zExpr
226968){
226969  int rc = SQLITE_OK;
226970  char *zStmt = sessionSelectFindNew(
226971      zDb1, zDb2, pTab->bRowid, pTab->zName, zExpr
226972  );
226973
226974  if( zStmt==0 ){
226975    rc = SQLITE_NOMEM;
226976  }else{
226977    sqlite3_stmt *pStmt;
226978    rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
226979    if( rc==SQLITE_OK ){
226980      SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
226981      pDiffCtx->pStmt = pStmt;
226982      pDiffCtx->nOldOff = 0;
226983      pDiffCtx->bRowid = pTab->bRowid;
226984      while( SQLITE_ROW==sqlite3_step(pStmt) ){
226985        i64 iRowid = (pTab->bRowid ? sqlite3_column_int64(pStmt, 0) : 0);
226986        sessionPreupdateOneChange(op, iRowid, pSession, pTab);
226987      }
226988      rc = sqlite3_finalize(pStmt);
226989    }
226990    sqlite3_free(zStmt);
226991  }
226992
226993  return rc;
226994}
226995
226996/*
226997** Return a comma-separated list of the fully-qualified (with both database
226998** and table name) column names from table pTab. e.g.
226999**
227000**    "main"."t1"."a", "main"."t1"."b", "main"."t1"."c"
227001*/
227002static char *sessionAllCols(
227003  const char *zDb,
227004  SessionTable *pTab
227005){
227006  int ii;
227007  char *zRet = 0;
227008  for(ii=0; ii<pTab->nCol; ii++){
227009    zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"",
227010        zRet, (zRet ? ", " : ""), zDb, pTab->zName, pTab->azCol[ii]
227011    );
227012    if( !zRet ) break;
227013  }
227014  return zRet;
227015}
227016
227017static int sessionDiffFindModified(
227018  sqlite3_session *pSession,
227019  SessionTable *pTab,
227020  const char *zFrom,
227021  const char *zExpr
227022){
227023  int rc = SQLITE_OK;
227024
227025  char *zExpr2 = sessionExprCompareOther(pTab->nCol,
227026      pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
227027  );
227028  if( zExpr2==0 ){
227029    rc = SQLITE_NOMEM;
227030  }else{
227031    char *z1 = sessionAllCols(pSession->zDb, pTab);
227032    char *z2 = sessionAllCols(zFrom, pTab);
227033    char *zStmt = sqlite3_mprintf(
227034        "SELECT %s,%s FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
227035        z1, z2, pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
227036    );
227037    if( zStmt==0 || z1==0 || z2==0 ){
227038      rc = SQLITE_NOMEM;
227039    }else{
227040      sqlite3_stmt *pStmt;
227041      rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
227042
227043      if( rc==SQLITE_OK ){
227044        SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
227045        pDiffCtx->pStmt = pStmt;
227046        pDiffCtx->nOldOff = pTab->nCol;
227047        while( SQLITE_ROW==sqlite3_step(pStmt) ){
227048          i64 iRowid = (pTab->bRowid ? sqlite3_column_int64(pStmt, 0) : 0);
227049          sessionPreupdateOneChange(SQLITE_UPDATE, iRowid, pSession, pTab);
227050        }
227051        rc = sqlite3_finalize(pStmt);
227052      }
227053    }
227054    sqlite3_free(zStmt);
227055    sqlite3_free(z1);
227056    sqlite3_free(z2);
227057  }
227058
227059  return rc;
227060}
227061
227062SQLITE_API int sqlite3session_diff(
227063  sqlite3_session *pSession,
227064  const char *zFrom,
227065  const char *zTbl,
227066  char **pzErrMsg
227067){
227068  const char *zDb = pSession->zDb;
227069  int rc = pSession->rc;
227070  SessionDiffCtx d;
227071
227072  memset(&d, 0, sizeof(d));
227073  sessionDiffHooks(pSession, &d);
227074
227075  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
227076  if( pzErrMsg ) *pzErrMsg = 0;
227077  if( rc==SQLITE_OK ){
227078    char *zExpr = 0;
227079    sqlite3 *db = pSession->db;
227080    SessionTable *pTo;            /* Table zTbl */
227081
227082    /* Locate and if necessary initialize the target table object */
227083    rc = sessionFindTable(pSession, zTbl, &pTo);
227084    if( pTo==0 ) goto diff_out;
227085    if( sessionInitTable(pSession, pTo, pSession->db, pSession->zDb) ){
227086      rc = pSession->rc;
227087      goto diff_out;
227088    }
227089
227090    /* Check the table schemas match */
227091    if( rc==SQLITE_OK ){
227092      int bHasPk = 0;
227093      int bMismatch = 0;
227094      int nCol;                   /* Columns in zFrom.zTbl */
227095      int bRowid = 0;
227096      u8 *abPK;
227097      const char **azCol = 0;
227098      rc = sessionTableInfo(0, db, zFrom, zTbl, &nCol, 0, &azCol, 0, &abPK,
227099          pSession->bImplicitPK ? &bRowid : 0
227100      );
227101      if( rc==SQLITE_OK ){
227102        if( pTo->nCol!=nCol ){
227103          bMismatch = 1;
227104        }else{
227105          int i;
227106          for(i=0; i<nCol; i++){
227107            if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
227108            if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
227109            if( abPK[i] ) bHasPk = 1;
227110          }
227111        }
227112      }
227113      sqlite3_free((char*)azCol);
227114      if( bMismatch ){
227115        if( pzErrMsg ){
227116          *pzErrMsg = sqlite3_mprintf("table schemas do not match");
227117        }
227118        rc = SQLITE_SCHEMA;
227119      }
227120      if( bHasPk==0 ){
227121        /* Ignore tables with no primary keys */
227122        goto diff_out;
227123      }
227124    }
227125
227126    if( rc==SQLITE_OK ){
227127      zExpr = sessionExprComparePK(pTo->nCol,
227128          zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
227129      );
227130    }
227131
227132    /* Find new rows */
227133    if( rc==SQLITE_OK ){
227134      rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
227135    }
227136
227137    /* Find old rows */
227138    if( rc==SQLITE_OK ){
227139      rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
227140    }
227141
227142    /* Find modified rows */
227143    if( rc==SQLITE_OK ){
227144      rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
227145    }
227146
227147    sqlite3_free(zExpr);
227148  }
227149
227150 diff_out:
227151  sessionPreupdateHooks(pSession);
227152  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
227153  return rc;
227154}
227155
227156/*
227157** Create a session object. This session object will record changes to
227158** database zDb attached to connection db.
227159*/
227160SQLITE_API int sqlite3session_create(
227161  sqlite3 *db,                    /* Database handle */
227162  const char *zDb,                /* Name of db (e.g. "main") */
227163  sqlite3_session **ppSession     /* OUT: New session object */
227164){
227165  sqlite3_session *pNew;          /* Newly allocated session object */
227166  sqlite3_session *pOld;          /* Session object already attached to db */
227167  int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
227168
227169  /* Zero the output value in case an error occurs. */
227170  *ppSession = 0;
227171
227172  /* Allocate and populate the new session object. */
227173  pNew = (sqlite3_session *)sqlite3_malloc64(sizeof(sqlite3_session) + nDb + 1);
227174  if( !pNew ) return SQLITE_NOMEM;
227175  memset(pNew, 0, sizeof(sqlite3_session));
227176  pNew->db = db;
227177  pNew->zDb = (char *)&pNew[1];
227178  pNew->bEnable = 1;
227179  memcpy(pNew->zDb, zDb, nDb+1);
227180  sessionPreupdateHooks(pNew);
227181
227182  /* Add the new session object to the linked list of session objects
227183  ** attached to database handle $db. Do this under the cover of the db
227184  ** handle mutex.  */
227185  sqlite3_mutex_enter(sqlite3_db_mutex(db));
227186  pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
227187  pNew->pNext = pOld;
227188  sqlite3_mutex_leave(sqlite3_db_mutex(db));
227189
227190  *ppSession = pNew;
227191  return SQLITE_OK;
227192}
227193
227194/*
227195** Free the list of table objects passed as the first argument. The contents
227196** of the changed-rows hash tables are also deleted.
227197*/
227198static void sessionDeleteTable(sqlite3_session *pSession, SessionTable *pList){
227199  SessionTable *pNext;
227200  SessionTable *pTab;
227201
227202  for(pTab=pList; pTab; pTab=pNext){
227203    int i;
227204    pNext = pTab->pNext;
227205    for(i=0; i<pTab->nChange; i++){
227206      SessionChange *p;
227207      SessionChange *pNextChange;
227208      for(p=pTab->apChange[i]; p; p=pNextChange){
227209        pNextChange = p->pNext;
227210        sessionFree(pSession, p);
227211      }
227212    }
227213    sqlite3_finalize(pTab->pDfltStmt);
227214    sessionFree(pSession, (char*)pTab->azCol);  /* cast works around VC++ bug */
227215    sessionFree(pSession, pTab->apChange);
227216    sessionFree(pSession, pTab);
227217  }
227218}
227219
227220/*
227221** Delete a session object previously allocated using sqlite3session_create().
227222*/
227223SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
227224  sqlite3 *db = pSession->db;
227225  sqlite3_session *pHead;
227226  sqlite3_session **pp;
227227
227228  /* Unlink the session from the linked list of sessions attached to the
227229  ** database handle. Hold the db mutex while doing so.  */
227230  sqlite3_mutex_enter(sqlite3_db_mutex(db));
227231  pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
227232  for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
227233    if( (*pp)==pSession ){
227234      *pp = (*pp)->pNext;
227235      if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
227236      break;
227237    }
227238  }
227239  sqlite3_mutex_leave(sqlite3_db_mutex(db));
227240  sqlite3ValueFree(pSession->pZeroBlob);
227241
227242  /* Delete all attached table objects. And the contents of their
227243  ** associated hash-tables. */
227244  sessionDeleteTable(pSession, pSession->pTable);
227245
227246  /* Free the session object. */
227247  sqlite3_free(pSession);
227248}
227249
227250/*
227251** Set a table filter on a Session Object.
227252*/
227253SQLITE_API void sqlite3session_table_filter(
227254  sqlite3_session *pSession,
227255  int(*xFilter)(void*, const char*),
227256  void *pCtx                      /* First argument passed to xFilter */
227257){
227258  pSession->bAutoAttach = 1;
227259  pSession->pFilterCtx = pCtx;
227260  pSession->xTableFilter = xFilter;
227261}
227262
227263/*
227264** Attach a table to a session. All subsequent changes made to the table
227265** while the session object is enabled will be recorded.
227266**
227267** Only tables that have a PRIMARY KEY defined may be attached. It does
227268** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
227269** or not.
227270*/
227271SQLITE_API int sqlite3session_attach(
227272  sqlite3_session *pSession,      /* Session object */
227273  const char *zName               /* Table name */
227274){
227275  int rc = SQLITE_OK;
227276  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
227277
227278  if( !zName ){
227279    pSession->bAutoAttach = 1;
227280  }else{
227281    SessionTable *pTab;           /* New table object (if required) */
227282    int nName;                    /* Number of bytes in string zName */
227283
227284    /* First search for an existing entry. If one is found, this call is
227285    ** a no-op. Return early. */
227286    nName = sqlite3Strlen30(zName);
227287    for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
227288      if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
227289    }
227290
227291    if( !pTab ){
227292      /* Allocate new SessionTable object. */
227293      int nByte = sizeof(SessionTable) + nName + 1;
227294      pTab = (SessionTable*)sessionMalloc64(pSession, nByte);
227295      if( !pTab ){
227296        rc = SQLITE_NOMEM;
227297      }else{
227298        /* Populate the new SessionTable object and link it into the list.
227299        ** The new object must be linked onto the end of the list, not
227300        ** simply added to the start of it in order to ensure that tables
227301        ** appear in the correct order when a changeset or patchset is
227302        ** eventually generated. */
227303        SessionTable **ppTab;
227304        memset(pTab, 0, sizeof(SessionTable));
227305        pTab->zName = (char *)&pTab[1];
227306        memcpy(pTab->zName, zName, nName+1);
227307        for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
227308        *ppTab = pTab;
227309      }
227310    }
227311  }
227312
227313  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
227314  return rc;
227315}
227316
227317/*
227318** Append the value passed as the second argument to the buffer passed
227319** as the first.
227320**
227321** This function is a no-op if *pRc is non-zero when it is called.
227322** Otherwise, if an error occurs, *pRc is set to an SQLite error code
227323** before returning.
227324*/
227325static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
227326  int rc = *pRc;
227327  if( rc==SQLITE_OK ){
227328    sqlite3_int64 nByte = 0;
227329    rc = sessionSerializeValue(0, pVal, &nByte);
227330    sessionBufferGrow(p, nByte, &rc);
227331    if( rc==SQLITE_OK ){
227332      rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
227333      p->nBuf += nByte;
227334    }else{
227335      *pRc = rc;
227336    }
227337  }
227338}
227339
227340/*
227341** This function is a no-op if *pRc is other than SQLITE_OK when it is
227342** called. Otherwise, append a single byte to the buffer.
227343**
227344** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
227345** returning.
227346*/
227347static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
227348  if( 0==sessionBufferGrow(p, 1, pRc) ){
227349    p->aBuf[p->nBuf++] = v;
227350  }
227351}
227352
227353/*
227354** This function is a no-op if *pRc is other than SQLITE_OK when it is
227355** called. Otherwise, append a single varint to the buffer.
227356**
227357** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
227358** returning.
227359*/
227360static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
227361  if( 0==sessionBufferGrow(p, 9, pRc) ){
227362    p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
227363  }
227364}
227365
227366/*
227367** This function is a no-op if *pRc is other than SQLITE_OK when it is
227368** called. Otherwise, append a blob of data to the buffer.
227369**
227370** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
227371** returning.
227372*/
227373static void sessionAppendBlob(
227374  SessionBuffer *p,
227375  const u8 *aBlob,
227376  int nBlob,
227377  int *pRc
227378){
227379  if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
227380    memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
227381    p->nBuf += nBlob;
227382  }
227383}
227384
227385/*
227386** This function is a no-op if *pRc is other than SQLITE_OK when it is
227387** called. Otherwise, append the string representation of integer iVal
227388** to the buffer. No nul-terminator is written.
227389**
227390** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
227391** returning.
227392*/
227393static void sessionAppendInteger(
227394  SessionBuffer *p,               /* Buffer to append to */
227395  int iVal,                       /* Value to write the string rep. of */
227396  int *pRc                        /* IN/OUT: Error code */
227397){
227398  char aBuf[24];
227399  sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
227400  sessionAppendStr(p, aBuf, pRc);
227401}
227402
227403/*
227404** This function is a no-op if *pRc is other than SQLITE_OK when it is
227405** called. Otherwise, append the string zStr enclosed in quotes (") and
227406** with any embedded quote characters escaped to the buffer. No
227407** nul-terminator byte is written.
227408**
227409** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
227410** returning.
227411*/
227412static void sessionAppendIdent(
227413  SessionBuffer *p,               /* Buffer to a append to */
227414  const char *zStr,               /* String to quote, escape and append */
227415  int *pRc                        /* IN/OUT: Error code */
227416){
227417  int nStr = sqlite3Strlen30(zStr)*2 + 2 + 2;
227418  if( 0==sessionBufferGrow(p, nStr, pRc) ){
227419    char *zOut = (char *)&p->aBuf[p->nBuf];
227420    const char *zIn = zStr;
227421    *zOut++ = '"';
227422    while( *zIn ){
227423      if( *zIn=='"' ) *zOut++ = '"';
227424      *zOut++ = *(zIn++);
227425    }
227426    *zOut++ = '"';
227427    p->nBuf = (int)((u8 *)zOut - p->aBuf);
227428    p->aBuf[p->nBuf] = 0x00;
227429  }
227430}
227431
227432/*
227433** This function is a no-op if *pRc is other than SQLITE_OK when it is
227434** called. Otherwse, it appends the serialized version of the value stored
227435** in column iCol of the row that SQL statement pStmt currently points
227436** to to the buffer.
227437*/
227438static void sessionAppendCol(
227439  SessionBuffer *p,               /* Buffer to append to */
227440  sqlite3_stmt *pStmt,            /* Handle pointing to row containing value */
227441  int iCol,                       /* Column to read value from */
227442  int *pRc                        /* IN/OUT: Error code */
227443){
227444  if( *pRc==SQLITE_OK ){
227445    int eType = sqlite3_column_type(pStmt, iCol);
227446    sessionAppendByte(p, (u8)eType, pRc);
227447    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
227448      sqlite3_int64 i;
227449      u8 aBuf[8];
227450      if( eType==SQLITE_INTEGER ){
227451        i = sqlite3_column_int64(pStmt, iCol);
227452      }else{
227453        double r = sqlite3_column_double(pStmt, iCol);
227454        memcpy(&i, &r, 8);
227455      }
227456      sessionPutI64(aBuf, i);
227457      sessionAppendBlob(p, aBuf, 8, pRc);
227458    }
227459    if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
227460      u8 *z;
227461      int nByte;
227462      if( eType==SQLITE_BLOB ){
227463        z = (u8 *)sqlite3_column_blob(pStmt, iCol);
227464      }else{
227465        z = (u8 *)sqlite3_column_text(pStmt, iCol);
227466      }
227467      nByte = sqlite3_column_bytes(pStmt, iCol);
227468      if( z || (eType==SQLITE_BLOB && nByte==0) ){
227469        sessionAppendVarint(p, nByte, pRc);
227470        sessionAppendBlob(p, z, nByte, pRc);
227471      }else{
227472        *pRc = SQLITE_NOMEM;
227473      }
227474    }
227475  }
227476}
227477
227478/*
227479**
227480** This function appends an update change to the buffer (see the comments
227481** under "CHANGESET FORMAT" at the top of the file). An update change
227482** consists of:
227483**
227484**   1 byte:  SQLITE_UPDATE (0x17)
227485**   n bytes: old.* record (see RECORD FORMAT)
227486**   m bytes: new.* record (see RECORD FORMAT)
227487**
227488** The SessionChange object passed as the third argument contains the
227489** values that were stored in the row when the session began (the old.*
227490** values). The statement handle passed as the second argument points
227491** at the current version of the row (the new.* values).
227492**
227493** If all of the old.* values are equal to their corresponding new.* value
227494** (i.e. nothing has changed), then no data at all is appended to the buffer.
227495**
227496** Otherwise, the old.* record contains all primary key values and the
227497** original values of any fields that have been modified. The new.* record
227498** contains the new values of only those fields that have been modified.
227499*/
227500static int sessionAppendUpdate(
227501  SessionBuffer *pBuf,            /* Buffer to append to */
227502  int bPatchset,                  /* True for "patchset", 0 for "changeset" */
227503  sqlite3_stmt *pStmt,            /* Statement handle pointing at new row */
227504  SessionChange *p,               /* Object containing old values */
227505  u8 *abPK                        /* Boolean array - true for PK columns */
227506){
227507  int rc = SQLITE_OK;
227508  SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
227509  int bNoop = 1;                /* Set to zero if any values are modified */
227510  int nRewind = pBuf->nBuf;     /* Set to zero if any values are modified */
227511  int i;                        /* Used to iterate through columns */
227512  u8 *pCsr = p->aRecord;        /* Used to iterate through old.* values */
227513
227514  assert( abPK!=0 );
227515  sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
227516  sessionAppendByte(pBuf, p->bIndirect, &rc);
227517  for(i=0; i<sqlite3_column_count(pStmt); i++){
227518    int bChanged = 0;
227519    int nAdvance;
227520    int eType = *pCsr;
227521    switch( eType ){
227522      case SQLITE_NULL:
227523        nAdvance = 1;
227524        if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
227525          bChanged = 1;
227526        }
227527        break;
227528
227529      case SQLITE_FLOAT:
227530      case SQLITE_INTEGER: {
227531        nAdvance = 9;
227532        if( eType==sqlite3_column_type(pStmt, i) ){
227533          sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
227534          if( eType==SQLITE_INTEGER ){
227535            if( iVal==sqlite3_column_int64(pStmt, i) ) break;
227536          }else{
227537            double dVal;
227538            memcpy(&dVal, &iVal, 8);
227539            if( dVal==sqlite3_column_double(pStmt, i) ) break;
227540          }
227541        }
227542        bChanged = 1;
227543        break;
227544      }
227545
227546      default: {
227547        int n;
227548        int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
227549        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
227550        nAdvance = nHdr + n;
227551        if( eType==sqlite3_column_type(pStmt, i)
227552         && n==sqlite3_column_bytes(pStmt, i)
227553         && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
227554        ){
227555          break;
227556        }
227557        bChanged = 1;
227558      }
227559    }
227560
227561    /* If at least one field has been modified, this is not a no-op. */
227562    if( bChanged ) bNoop = 0;
227563
227564    /* Add a field to the old.* record. This is omitted if this module is
227565    ** currently generating a patchset. */
227566    if( bPatchset==0 ){
227567      if( bChanged || abPK[i] ){
227568        sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
227569      }else{
227570        sessionAppendByte(pBuf, 0, &rc);
227571      }
227572    }
227573
227574    /* Add a field to the new.* record. Or the only record if currently
227575    ** generating a patchset.  */
227576    if( bChanged || (bPatchset && abPK[i]) ){
227577      sessionAppendCol(&buf2, pStmt, i, &rc);
227578    }else{
227579      sessionAppendByte(&buf2, 0, &rc);
227580    }
227581
227582    pCsr += nAdvance;
227583  }
227584
227585  if( bNoop ){
227586    pBuf->nBuf = nRewind;
227587  }else{
227588    sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
227589  }
227590  sqlite3_free(buf2.aBuf);
227591
227592  return rc;
227593}
227594
227595/*
227596** Append a DELETE change to the buffer passed as the first argument. Use
227597** the changeset format if argument bPatchset is zero, or the patchset
227598** format otherwise.
227599*/
227600static int sessionAppendDelete(
227601  SessionBuffer *pBuf,            /* Buffer to append to */
227602  int bPatchset,                  /* True for "patchset", 0 for "changeset" */
227603  SessionChange *p,               /* Object containing old values */
227604  int nCol,                       /* Number of columns in table */
227605  u8 *abPK                        /* Boolean array - true for PK columns */
227606){
227607  int rc = SQLITE_OK;
227608
227609  sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
227610  sessionAppendByte(pBuf, p->bIndirect, &rc);
227611
227612  if( bPatchset==0 ){
227613    sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
227614  }else{
227615    int i;
227616    u8 *a = p->aRecord;
227617    for(i=0; i<nCol; i++){
227618      u8 *pStart = a;
227619      int eType = *a++;
227620
227621      switch( eType ){
227622        case 0:
227623        case SQLITE_NULL:
227624          assert( abPK[i]==0 );
227625          break;
227626
227627        case SQLITE_FLOAT:
227628        case SQLITE_INTEGER:
227629          a += 8;
227630          break;
227631
227632        default: {
227633          int n;
227634          a += sessionVarintGet(a, &n);
227635          a += n;
227636          break;
227637        }
227638      }
227639      if( abPK[i] ){
227640        sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
227641      }
227642    }
227643    assert( (a - p->aRecord)==p->nRecord );
227644  }
227645
227646  return rc;
227647}
227648
227649/*
227650** Formulate and prepare a SELECT statement to retrieve a row from table
227651** zTab in database zDb based on its primary key. i.e.
227652**
227653**   SELECT *, <noop-test> FROM zDb.zTab WHERE (pk1, pk2,...) IS (?1, ?2,...)
227654**
227655** where <noop-test> is:
227656**
227657**   1 AND (?A OR ?1 IS <column>) AND ...
227658**
227659** for each non-pk <column>.
227660*/
227661static int sessionSelectStmt(
227662  sqlite3 *db,                    /* Database handle */
227663  int bIgnoreNoop,
227664  const char *zDb,                /* Database name */
227665  const char *zTab,               /* Table name */
227666  int bRowid,
227667  int nCol,                       /* Number of columns in table */
227668  const char **azCol,             /* Names of table columns */
227669  u8 *abPK,                       /* PRIMARY KEY  array */
227670  sqlite3_stmt **ppStmt           /* OUT: Prepared SELECT statement */
227671){
227672  int rc = SQLITE_OK;
227673  char *zSql = 0;
227674  const char *zSep = "";
227675  const char *zCols = bRowid ? SESSIONS_ROWID ", *" : "*";
227676  int nSql = -1;
227677  int i;
227678
227679  SessionBuffer nooptest = {0, 0, 0};
227680  SessionBuffer pkfield = {0, 0, 0};
227681  SessionBuffer pkvar = {0, 0, 0};
227682
227683  sessionAppendStr(&nooptest, ", 1", &rc);
227684
227685  if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
227686    sessionAppendStr(&nooptest, " AND (?6 OR ?3 IS stat)", &rc);
227687    sessionAppendStr(&pkfield, "tbl, idx", &rc);
227688    sessionAppendStr(&pkvar,
227689        "?1, (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", &rc
227690    );
227691    zCols = "tbl, ?2, stat";
227692  }else{
227693    for(i=0; i<nCol; i++){
227694      if( abPK[i] ){
227695        sessionAppendStr(&pkfield, zSep, &rc);
227696        sessionAppendStr(&pkvar, zSep, &rc);
227697        zSep = ", ";
227698        sessionAppendIdent(&pkfield, azCol[i], &rc);
227699        sessionAppendPrintf(&pkvar, &rc, "?%d", i+1);
227700      }else{
227701        sessionAppendPrintf(&nooptest, &rc,
227702            " AND (?%d OR ?%d IS %w.%w)", i+1+nCol, i+1, zTab, azCol[i]
227703        );
227704      }
227705    }
227706  }
227707
227708  if( rc==SQLITE_OK ){
227709    zSql = sqlite3_mprintf(
227710        "SELECT %s%s FROM %Q.%Q WHERE (%s) IS (%s)",
227711        zCols, (bIgnoreNoop ? (char*)nooptest.aBuf : ""),
227712        zDb, zTab, (char*)pkfield.aBuf, (char*)pkvar.aBuf
227713    );
227714    if( zSql==0 ) rc = SQLITE_NOMEM;
227715  }
227716
227717#if 0
227718  if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
227719    zSql = sqlite3_mprintf(
227720        "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
227721        "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
227722    );
227723    if( zSql==0 ) rc = SQLITE_NOMEM;
227724  }else{
227725    const char *zSep = "";
227726    SessionBuffer buf = {0, 0, 0};
227727
227728    sessionAppendStr(&buf, "SELECT * FROM ", &rc);
227729    sessionAppendIdent(&buf, zDb, &rc);
227730    sessionAppendStr(&buf, ".", &rc);
227731    sessionAppendIdent(&buf, zTab, &rc);
227732    sessionAppendStr(&buf, " WHERE ", &rc);
227733    for(i=0; i<nCol; i++){
227734      if( abPK[i] ){
227735        sessionAppendStr(&buf, zSep, &rc);
227736        sessionAppendIdent(&buf, azCol[i], &rc);
227737        sessionAppendStr(&buf, " IS ?", &rc);
227738        sessionAppendInteger(&buf, i+1, &rc);
227739        zSep = " AND ";
227740      }
227741    }
227742    zSql = (char*)buf.aBuf;
227743    nSql = buf.nBuf;
227744  }
227745#endif
227746
227747  if( rc==SQLITE_OK ){
227748    rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
227749  }
227750  sqlite3_free(zSql);
227751  sqlite3_free(nooptest.aBuf);
227752  sqlite3_free(pkfield.aBuf);
227753  sqlite3_free(pkvar.aBuf);
227754  return rc;
227755}
227756
227757/*
227758** Bind the PRIMARY KEY values from the change passed in argument pChange
227759** to the SELECT statement passed as the first argument. The SELECT statement
227760** is as prepared by function sessionSelectStmt().
227761**
227762** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
227763** error code (e.g. SQLITE_NOMEM) otherwise.
227764*/
227765static int sessionSelectBind(
227766  sqlite3_stmt *pSelect,          /* SELECT from sessionSelectStmt() */
227767  int nCol,                       /* Number of columns in table */
227768  u8 *abPK,                       /* PRIMARY KEY array */
227769  SessionChange *pChange          /* Change structure */
227770){
227771  int i;
227772  int rc = SQLITE_OK;
227773  u8 *a = pChange->aRecord;
227774
227775  for(i=0; i<nCol && rc==SQLITE_OK; i++){
227776    int eType = *a++;
227777
227778    switch( eType ){
227779      case 0:
227780      case SQLITE_NULL:
227781        assert( abPK[i]==0 );
227782        break;
227783
227784      case SQLITE_INTEGER: {
227785        if( abPK[i] ){
227786          i64 iVal = sessionGetI64(a);
227787          rc = sqlite3_bind_int64(pSelect, i+1, iVal);
227788        }
227789        a += 8;
227790        break;
227791      }
227792
227793      case SQLITE_FLOAT: {
227794        if( abPK[i] ){
227795          double rVal;
227796          i64 iVal = sessionGetI64(a);
227797          memcpy(&rVal, &iVal, 8);
227798          rc = sqlite3_bind_double(pSelect, i+1, rVal);
227799        }
227800        a += 8;
227801        break;
227802      }
227803
227804      case SQLITE_TEXT: {
227805        int n;
227806        a += sessionVarintGet(a, &n);
227807        if( abPK[i] ){
227808          rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
227809        }
227810        a += n;
227811        break;
227812      }
227813
227814      default: {
227815        int n;
227816        assert( eType==SQLITE_BLOB );
227817        a += sessionVarintGet(a, &n);
227818        if( abPK[i] ){
227819          rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
227820        }
227821        a += n;
227822        break;
227823      }
227824    }
227825  }
227826
227827  return rc;
227828}
227829
227830/*
227831** This function is a no-op if *pRc is set to other than SQLITE_OK when it
227832** is called. Otherwise, append a serialized table header (part of the binary
227833** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
227834** SQLite error code before returning.
227835*/
227836static void sessionAppendTableHdr(
227837  SessionBuffer *pBuf,            /* Append header to this buffer */
227838  int bPatchset,                  /* Use the patchset format if true */
227839  SessionTable *pTab,             /* Table object to append header for */
227840  int *pRc                        /* IN/OUT: Error code */
227841){
227842  /* Write a table header */
227843  sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
227844  sessionAppendVarint(pBuf, pTab->nCol, pRc);
227845  sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
227846  sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
227847}
227848
227849/*
227850** Generate either a changeset (if argument bPatchset is zero) or a patchset
227851** (if it is non-zero) based on the current contents of the session object
227852** passed as the first argument.
227853**
227854** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
227855** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
227856** occurs, an SQLite error code is returned and both output variables set
227857** to 0.
227858*/
227859static int sessionGenerateChangeset(
227860  sqlite3_session *pSession,      /* Session object */
227861  int bPatchset,                  /* True for patchset, false for changeset */
227862  int (*xOutput)(void *pOut, const void *pData, int nData),
227863  void *pOut,                     /* First argument for xOutput */
227864  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
227865  void **ppChangeset              /* OUT: Buffer containing changeset */
227866){
227867  sqlite3 *db = pSession->db;     /* Source database handle */
227868  SessionTable *pTab;             /* Used to iterate through attached tables */
227869  SessionBuffer buf = {0,0,0};    /* Buffer in which to accumlate changeset */
227870  int rc;                         /* Return code */
227871
227872  assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0) );
227873  assert( xOutput!=0 || (pnChangeset!=0 && ppChangeset!=0) );
227874
227875  /* Zero the output variables in case an error occurs. If this session
227876  ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
227877  ** this call will be a no-op.  */
227878  if( xOutput==0 ){
227879    assert( pnChangeset!=0  && ppChangeset!=0 );
227880    *pnChangeset = 0;
227881    *ppChangeset = 0;
227882  }
227883
227884  if( pSession->rc ) return pSession->rc;
227885  rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
227886  if( rc!=SQLITE_OK ) return rc;
227887
227888  sqlite3_mutex_enter(sqlite3_db_mutex(db));
227889
227890  for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
227891    if( pTab->nEntry ){
227892      const char *zName = pTab->zName;
227893      int i;                      /* Used to iterate through hash buckets */
227894      sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
227895      int nRewind = buf.nBuf;     /* Initial size of write buffer */
227896      int nNoop;                  /* Size of buffer after writing tbl header */
227897      int nOldCol = pTab->nCol;
227898
227899      /* Check the table schema is still Ok. */
227900      rc = sessionReinitTable(pSession, pTab);
227901      if( rc==SQLITE_OK && pTab->nCol!=nOldCol ){
227902        rc = sessionUpdateChanges(pSession, pTab);
227903      }
227904
227905      /* Write a table header */
227906      sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
227907
227908      /* Build and compile a statement to execute: */
227909      if( rc==SQLITE_OK ){
227910        rc = sessionSelectStmt(db, 0, pSession->zDb,
227911            zName, pTab->bRowid, pTab->nCol, pTab->azCol, pTab->abPK, &pSel
227912        );
227913      }
227914
227915      nNoop = buf.nBuf;
227916      for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
227917        SessionChange *p;         /* Used to iterate through changes */
227918
227919        for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
227920          rc = sessionSelectBind(pSel, pTab->nCol, pTab->abPK, p);
227921          if( rc!=SQLITE_OK ) continue;
227922          if( sqlite3_step(pSel)==SQLITE_ROW ){
227923            if( p->op==SQLITE_INSERT ){
227924              int iCol;
227925              sessionAppendByte(&buf, SQLITE_INSERT, &rc);
227926              sessionAppendByte(&buf, p->bIndirect, &rc);
227927              for(iCol=0; iCol<pTab->nCol; iCol++){
227928                sessionAppendCol(&buf, pSel, iCol, &rc);
227929              }
227930            }else{
227931              assert( pTab->abPK!=0 );
227932              rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, pTab->abPK);
227933            }
227934          }else if( p->op!=SQLITE_INSERT ){
227935            rc = sessionAppendDelete(&buf, bPatchset, p, pTab->nCol,pTab->abPK);
227936          }
227937          if( rc==SQLITE_OK ){
227938            rc = sqlite3_reset(pSel);
227939          }
227940
227941          /* If the buffer is now larger than sessions_strm_chunk_size, pass
227942          ** its contents to the xOutput() callback. */
227943          if( xOutput
227944           && rc==SQLITE_OK
227945           && buf.nBuf>nNoop
227946           && buf.nBuf>sessions_strm_chunk_size
227947          ){
227948            rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
227949            nNoop = -1;
227950            buf.nBuf = 0;
227951          }
227952
227953        }
227954      }
227955
227956      sqlite3_finalize(pSel);
227957      if( buf.nBuf==nNoop ){
227958        buf.nBuf = nRewind;
227959      }
227960    }
227961  }
227962
227963  if( rc==SQLITE_OK ){
227964    if( xOutput==0 ){
227965      *pnChangeset = buf.nBuf;
227966      *ppChangeset = buf.aBuf;
227967      buf.aBuf = 0;
227968    }else if( buf.nBuf>0 ){
227969      rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
227970    }
227971  }
227972
227973  sqlite3_free(buf.aBuf);
227974  sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
227975  sqlite3_mutex_leave(sqlite3_db_mutex(db));
227976  return rc;
227977}
227978
227979/*
227980** Obtain a changeset object containing all changes recorded by the
227981** session object passed as the first argument.
227982**
227983** It is the responsibility of the caller to eventually free the buffer
227984** using sqlite3_free().
227985*/
227986SQLITE_API int sqlite3session_changeset(
227987  sqlite3_session *pSession,      /* Session object */
227988  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
227989  void **ppChangeset              /* OUT: Buffer containing changeset */
227990){
227991  int rc;
227992
227993  if( pnChangeset==0 || ppChangeset==0 ) return SQLITE_MISUSE;
227994  rc = sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
227995  assert( rc || pnChangeset==0
227996       || pSession->bEnableSize==0 || *pnChangeset<=pSession->nMaxChangesetSize
227997  );
227998  return rc;
227999}
228000
228001/*
228002** Streaming version of sqlite3session_changeset().
228003*/
228004SQLITE_API int sqlite3session_changeset_strm(
228005  sqlite3_session *pSession,
228006  int (*xOutput)(void *pOut, const void *pData, int nData),
228007  void *pOut
228008){
228009  if( xOutput==0 ) return SQLITE_MISUSE;
228010  return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
228011}
228012
228013/*
228014** Streaming version of sqlite3session_patchset().
228015*/
228016SQLITE_API int sqlite3session_patchset_strm(
228017  sqlite3_session *pSession,
228018  int (*xOutput)(void *pOut, const void *pData, int nData),
228019  void *pOut
228020){
228021  if( xOutput==0 ) return SQLITE_MISUSE;
228022  return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
228023}
228024
228025/*
228026** Obtain a patchset object containing all changes recorded by the
228027** session object passed as the first argument.
228028**
228029** It is the responsibility of the caller to eventually free the buffer
228030** using sqlite3_free().
228031*/
228032SQLITE_API int sqlite3session_patchset(
228033  sqlite3_session *pSession,      /* Session object */
228034  int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
228035  void **ppPatchset               /* OUT: Buffer containing changeset */
228036){
228037  if( pnPatchset==0 || ppPatchset==0 ) return SQLITE_MISUSE;
228038  return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
228039}
228040
228041/*
228042** Enable or disable the session object passed as the first argument.
228043*/
228044SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
228045  int ret;
228046  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
228047  if( bEnable>=0 ){
228048    pSession->bEnable = bEnable;
228049  }
228050  ret = pSession->bEnable;
228051  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
228052  return ret;
228053}
228054
228055/*
228056** Enable or disable the session object passed as the first argument.
228057*/
228058SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
228059  int ret;
228060  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
228061  if( bIndirect>=0 ){
228062    pSession->bIndirect = bIndirect;
228063  }
228064  ret = pSession->bIndirect;
228065  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
228066  return ret;
228067}
228068
228069/*
228070** Return true if there have been no changes to monitored tables recorded
228071** by the session object passed as the only argument.
228072*/
228073SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
228074  int ret = 0;
228075  SessionTable *pTab;
228076
228077  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
228078  for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
228079    ret = (pTab->nEntry>0);
228080  }
228081  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
228082
228083  return (ret==0);
228084}
228085
228086/*
228087** Return the amount of heap memory in use.
228088*/
228089SQLITE_API sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession){
228090  return pSession->nMalloc;
228091}
228092
228093/*
228094** Configure the session object passed as the first argument.
228095*/
228096SQLITE_API int sqlite3session_object_config(sqlite3_session *pSession, int op, void *pArg){
228097  int rc = SQLITE_OK;
228098  switch( op ){
228099    case SQLITE_SESSION_OBJCONFIG_SIZE: {
228100      int iArg = *(int*)pArg;
228101      if( iArg>=0 ){
228102        if( pSession->pTable ){
228103          rc = SQLITE_MISUSE;
228104        }else{
228105          pSession->bEnableSize = (iArg!=0);
228106        }
228107      }
228108      *(int*)pArg = pSession->bEnableSize;
228109      break;
228110    }
228111
228112    case SQLITE_SESSION_OBJCONFIG_ROWID: {
228113      int iArg = *(int*)pArg;
228114      if( iArg>=0 ){
228115        if( pSession->pTable ){
228116          rc = SQLITE_MISUSE;
228117        }else{
228118          pSession->bImplicitPK = (iArg!=0);
228119        }
228120      }
228121      *(int*)pArg = pSession->bImplicitPK;
228122      break;
228123    }
228124
228125    default:
228126      rc = SQLITE_MISUSE;
228127  }
228128
228129  return rc;
228130}
228131
228132/*
228133** Return the maximum size of sqlite3session_changeset() output.
228134*/
228135SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession){
228136  return pSession->nMaxChangesetSize;
228137}
228138
228139/*
228140** Do the work for either sqlite3changeset_start() or start_strm().
228141*/
228142static int sessionChangesetStart(
228143  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
228144  int (*xInput)(void *pIn, void *pData, int *pnData),
228145  void *pIn,
228146  int nChangeset,                 /* Size of buffer pChangeset in bytes */
228147  void *pChangeset,               /* Pointer to buffer containing changeset */
228148  int bInvert,                    /* True to invert changeset */
228149  int bSkipEmpty                  /* True to skip empty UPDATE changes */
228150){
228151  sqlite3_changeset_iter *pRet;   /* Iterator to return */
228152  int nByte;                      /* Number of bytes to allocate for iterator */
228153
228154  assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
228155
228156  /* Zero the output variable in case an error occurs. */
228157  *pp = 0;
228158
228159  /* Allocate and initialize the iterator structure. */
228160  nByte = sizeof(sqlite3_changeset_iter);
228161  pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
228162  if( !pRet ) return SQLITE_NOMEM;
228163  memset(pRet, 0, sizeof(sqlite3_changeset_iter));
228164  pRet->in.aData = (u8 *)pChangeset;
228165  pRet->in.nData = nChangeset;
228166  pRet->in.xInput = xInput;
228167  pRet->in.pIn = pIn;
228168  pRet->in.bEof = (xInput ? 0 : 1);
228169  pRet->bInvert = bInvert;
228170  pRet->bSkipEmpty = bSkipEmpty;
228171
228172  /* Populate the output variable and return success. */
228173  *pp = pRet;
228174  return SQLITE_OK;
228175}
228176
228177/*
228178** Create an iterator used to iterate through the contents of a changeset.
228179*/
228180SQLITE_API int sqlite3changeset_start(
228181  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
228182  int nChangeset,                 /* Size of buffer pChangeset in bytes */
228183  void *pChangeset                /* Pointer to buffer containing changeset */
228184){
228185  return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, 0, 0);
228186}
228187SQLITE_API int sqlite3changeset_start_v2(
228188  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
228189  int nChangeset,                 /* Size of buffer pChangeset in bytes */
228190  void *pChangeset,               /* Pointer to buffer containing changeset */
228191  int flags
228192){
228193  int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
228194  return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, bInvert, 0);
228195}
228196
228197/*
228198** Streaming version of sqlite3changeset_start().
228199*/
228200SQLITE_API int sqlite3changeset_start_strm(
228201  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
228202  int (*xInput)(void *pIn, void *pData, int *pnData),
228203  void *pIn
228204){
228205  return sessionChangesetStart(pp, xInput, pIn, 0, 0, 0, 0);
228206}
228207SQLITE_API int sqlite3changeset_start_v2_strm(
228208  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
228209  int (*xInput)(void *pIn, void *pData, int *pnData),
228210  void *pIn,
228211  int flags
228212){
228213  int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
228214  return sessionChangesetStart(pp, xInput, pIn, 0, 0, bInvert, 0);
228215}
228216
228217/*
228218** If the SessionInput object passed as the only argument is a streaming
228219** object and the buffer is full, discard some data to free up space.
228220*/
228221static void sessionDiscardData(SessionInput *pIn){
228222  if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){
228223    int nMove = pIn->buf.nBuf - pIn->iNext;
228224    assert( nMove>=0 );
228225    if( nMove>0 ){
228226      memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
228227    }
228228    pIn->buf.nBuf -= pIn->iNext;
228229    pIn->iNext = 0;
228230    pIn->nData = pIn->buf.nBuf;
228231  }
228232}
228233
228234/*
228235** Ensure that there are at least nByte bytes available in the buffer. Or,
228236** if there are not nByte bytes remaining in the input, that all available
228237** data is in the buffer.
228238**
228239** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
228240*/
228241static int sessionInputBuffer(SessionInput *pIn, int nByte){
228242  int rc = SQLITE_OK;
228243  if( pIn->xInput ){
228244    while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
228245      int nNew = sessions_strm_chunk_size;
228246
228247      if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
228248      if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
228249        rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
228250        if( nNew==0 ){
228251          pIn->bEof = 1;
228252        }else{
228253          pIn->buf.nBuf += nNew;
228254        }
228255      }
228256
228257      pIn->aData = pIn->buf.aBuf;
228258      pIn->nData = pIn->buf.nBuf;
228259    }
228260  }
228261  return rc;
228262}
228263
228264/*
228265** When this function is called, *ppRec points to the start of a record
228266** that contains nCol values. This function advances the pointer *ppRec
228267** until it points to the byte immediately following that record.
228268*/
228269static void sessionSkipRecord(
228270  u8 **ppRec,                     /* IN/OUT: Record pointer */
228271  int nCol                        /* Number of values in record */
228272){
228273  u8 *aRec = *ppRec;
228274  int i;
228275  for(i=0; i<nCol; i++){
228276    int eType = *aRec++;
228277    if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
228278      int nByte;
228279      aRec += sessionVarintGet((u8*)aRec, &nByte);
228280      aRec += nByte;
228281    }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
228282      aRec += 8;
228283    }
228284  }
228285
228286  *ppRec = aRec;
228287}
228288
228289/*
228290** This function sets the value of the sqlite3_value object passed as the
228291** first argument to a copy of the string or blob held in the aData[]
228292** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
228293** error occurs.
228294*/
228295static int sessionValueSetStr(
228296  sqlite3_value *pVal,            /* Set the value of this object */
228297  u8 *aData,                      /* Buffer containing string or blob data */
228298  int nData,                      /* Size of buffer aData[] in bytes */
228299  u8 enc                          /* String encoding (0 for blobs) */
228300){
228301  /* In theory this code could just pass SQLITE_TRANSIENT as the final
228302  ** argument to sqlite3ValueSetStr() and have the copy created
228303  ** automatically. But doing so makes it difficult to detect any OOM
228304  ** error. Hence the code to create the copy externally. */
228305  u8 *aCopy = sqlite3_malloc64((sqlite3_int64)nData+1);
228306  if( aCopy==0 ) return SQLITE_NOMEM;
228307  memcpy(aCopy, aData, nData);
228308  sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
228309  return SQLITE_OK;
228310}
228311
228312/*
228313** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
228314** for details.
228315**
228316** When this function is called, *paChange points to the start of the record
228317** to deserialize. Assuming no error occurs, *paChange is set to point to
228318** one byte after the end of the same record before this function returns.
228319** If the argument abPK is NULL, then the record contains nCol values. Or,
228320** if abPK is other than NULL, then the record contains only the PK fields
228321** (in other words, it is a patchset DELETE record).
228322**
228323** If successful, each element of the apOut[] array (allocated by the caller)
228324** is set to point to an sqlite3_value object containing the value read
228325** from the corresponding position in the record. If that value is not
228326** included in the record (i.e. because the record is part of an UPDATE change
228327** and the field was not modified), the corresponding element of apOut[] is
228328** set to NULL.
228329**
228330** It is the responsibility of the caller to free all sqlite_value structures
228331** using sqlite3_free().
228332**
228333** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
228334** The apOut[] array may have been partially populated in this case.
228335*/
228336static int sessionReadRecord(
228337  SessionInput *pIn,              /* Input data */
228338  int nCol,                       /* Number of values in record */
228339  u8 *abPK,                       /* Array of primary key flags, or NULL */
228340  sqlite3_value **apOut,          /* Write values to this array */
228341  int *pbEmpty
228342){
228343  int i;                          /* Used to iterate through columns */
228344  int rc = SQLITE_OK;
228345
228346  assert( pbEmpty==0 || *pbEmpty==0 );
228347  if( pbEmpty ) *pbEmpty = 1;
228348  for(i=0; i<nCol && rc==SQLITE_OK; i++){
228349    int eType = 0;                /* Type of value (SQLITE_NULL, TEXT etc.) */
228350    if( abPK && abPK[i]==0 ) continue;
228351    rc = sessionInputBuffer(pIn, 9);
228352    if( rc==SQLITE_OK ){
228353      if( pIn->iNext>=pIn->nData ){
228354        rc = SQLITE_CORRUPT_BKPT;
228355      }else{
228356        eType = pIn->aData[pIn->iNext++];
228357        assert( apOut[i]==0 );
228358        if( eType ){
228359          if( pbEmpty ) *pbEmpty = 0;
228360          apOut[i] = sqlite3ValueNew(0);
228361          if( !apOut[i] ) rc = SQLITE_NOMEM;
228362        }
228363      }
228364    }
228365
228366    if( rc==SQLITE_OK ){
228367      u8 *aVal = &pIn->aData[pIn->iNext];
228368      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
228369        int nByte;
228370        pIn->iNext += sessionVarintGet(aVal, &nByte);
228371        rc = sessionInputBuffer(pIn, nByte);
228372        if( rc==SQLITE_OK ){
228373          if( nByte<0 || nByte>pIn->nData-pIn->iNext ){
228374            rc = SQLITE_CORRUPT_BKPT;
228375          }else{
228376            u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
228377            rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
228378            pIn->iNext += nByte;
228379          }
228380        }
228381      }
228382      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
228383        if( (pIn->nData-pIn->iNext)<8 ){
228384          rc = SQLITE_CORRUPT_BKPT;
228385        }else{
228386          sqlite3_int64 v = sessionGetI64(aVal);
228387          if( eType==SQLITE_INTEGER ){
228388            sqlite3VdbeMemSetInt64(apOut[i], v);
228389          }else{
228390            double d;
228391            memcpy(&d, &v, 8);
228392            sqlite3VdbeMemSetDouble(apOut[i], d);
228393          }
228394          pIn->iNext += 8;
228395        }
228396      }
228397    }
228398  }
228399
228400  return rc;
228401}
228402
228403/*
228404** The input pointer currently points to the second byte of a table-header.
228405** Specifically, to the following:
228406**
228407**   + number of columns in table (varint)
228408**   + array of PK flags (1 byte per column),
228409**   + table name (nul terminated).
228410**
228411** This function ensures that all of the above is present in the input
228412** buffer (i.e. that it can be accessed without any calls to xInput()).
228413** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
228414** The input pointer is not moved.
228415*/
228416static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
228417  int rc = SQLITE_OK;
228418  int nCol = 0;
228419  int nRead = 0;
228420
228421  rc = sessionInputBuffer(pIn, 9);
228422  if( rc==SQLITE_OK ){
228423    nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
228424    /* The hard upper limit for the number of columns in an SQLite
228425    ** database table is, according to sqliteLimit.h, 32676. So
228426    ** consider any table-header that purports to have more than 65536
228427    ** columns to be corrupt. This is convenient because otherwise,
228428    ** if the (nCol>65536) condition below were omitted, a sufficiently
228429    ** large value for nCol may cause nRead to wrap around and become
228430    ** negative. Leading to a crash. */
228431    if( nCol<0 || nCol>65536 ){
228432      rc = SQLITE_CORRUPT_BKPT;
228433    }else{
228434      rc = sessionInputBuffer(pIn, nRead+nCol+100);
228435      nRead += nCol;
228436    }
228437  }
228438
228439  while( rc==SQLITE_OK ){
228440    while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
228441      nRead++;
228442    }
228443    if( (pIn->iNext + nRead)<pIn->nData ) break;
228444    rc = sessionInputBuffer(pIn, nRead + 100);
228445  }
228446  *pnByte = nRead+1;
228447  return rc;
228448}
228449
228450/*
228451** The input pointer currently points to the first byte of the first field
228452** of a record consisting of nCol columns. This function ensures the entire
228453** record is buffered. It does not move the input pointer.
228454**
228455** If successful, SQLITE_OK is returned and *pnByte is set to the size of
228456** the record in bytes. Otherwise, an SQLite error code is returned. The
228457** final value of *pnByte is undefined in this case.
228458*/
228459static int sessionChangesetBufferRecord(
228460  SessionInput *pIn,              /* Input data */
228461  int nCol,                       /* Number of columns in record */
228462  int *pnByte                     /* OUT: Size of record in bytes */
228463){
228464  int rc = SQLITE_OK;
228465  int nByte = 0;
228466  int i;
228467  for(i=0; rc==SQLITE_OK && i<nCol; i++){
228468    int eType;
228469    rc = sessionInputBuffer(pIn, nByte + 10);
228470    if( rc==SQLITE_OK ){
228471      eType = pIn->aData[pIn->iNext + nByte++];
228472      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
228473        int n;
228474        nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
228475        nByte += n;
228476        rc = sessionInputBuffer(pIn, nByte);
228477      }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
228478        nByte += 8;
228479      }
228480    }
228481  }
228482  *pnByte = nByte;
228483  return rc;
228484}
228485
228486/*
228487** The input pointer currently points to the second byte of a table-header.
228488** Specifically, to the following:
228489**
228490**   + number of columns in table (varint)
228491**   + array of PK flags (1 byte per column),
228492**   + table name (nul terminated).
228493**
228494** This function decodes the table-header and populates the p->nCol,
228495** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
228496** also allocated or resized according to the new value of p->nCol. The
228497** input pointer is left pointing to the byte following the table header.
228498**
228499** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
228500** is returned and the final values of the various fields enumerated above
228501** are undefined.
228502*/
228503static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
228504  int rc;
228505  int nCopy;
228506  assert( p->rc==SQLITE_OK );
228507
228508  rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
228509  if( rc==SQLITE_OK ){
228510    int nByte;
228511    int nVarint;
228512    nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
228513    if( p->nCol>0 ){
228514      nCopy -= nVarint;
228515      p->in.iNext += nVarint;
228516      nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
228517      p->tblhdr.nBuf = 0;
228518      sessionBufferGrow(&p->tblhdr, nByte, &rc);
228519    }else{
228520      rc = SQLITE_CORRUPT_BKPT;
228521    }
228522  }
228523
228524  if( rc==SQLITE_OK ){
228525    size_t iPK = sizeof(sqlite3_value*)*p->nCol*2;
228526    memset(p->tblhdr.aBuf, 0, iPK);
228527    memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
228528    p->in.iNext += nCopy;
228529  }
228530
228531  p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
228532  if( p->apValue==0 ){
228533    p->abPK = 0;
228534    p->zTab = 0;
228535  }else{
228536    p->abPK = (u8*)&p->apValue[p->nCol*2];
228537    p->zTab = p->abPK ? (char*)&p->abPK[p->nCol] : 0;
228538  }
228539  return (p->rc = rc);
228540}
228541
228542/*
228543** Advance the changeset iterator to the next change. The differences between
228544** this function and sessionChangesetNext() are that
228545**
228546**   * If pbEmpty is not NULL and the change is a no-op UPDATE (an UPDATE
228547**     that modifies no columns), this function sets (*pbEmpty) to 1.
228548**
228549**   * If the iterator is configured to skip no-op UPDATEs,
228550**     sessionChangesetNext() does that. This function does not.
228551*/
228552static int sessionChangesetNextOne(
228553  sqlite3_changeset_iter *p,      /* Changeset iterator */
228554  u8 **paRec,                     /* If non-NULL, store record pointer here */
228555  int *pnRec,                     /* If non-NULL, store size of record here */
228556  int *pbNew,                     /* If non-NULL, true if new table */
228557  int *pbEmpty
228558){
228559  int i;
228560  u8 op;
228561
228562  assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
228563  assert( pbEmpty==0 || *pbEmpty==0 );
228564
228565  /* If the iterator is in the error-state, return immediately. */
228566  if( p->rc!=SQLITE_OK ) return p->rc;
228567
228568  /* Free the current contents of p->apValue[], if any. */
228569  if( p->apValue ){
228570    for(i=0; i<p->nCol*2; i++){
228571      sqlite3ValueFree(p->apValue[i]);
228572    }
228573    memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
228574  }
228575
228576  /* Make sure the buffer contains at least 10 bytes of input data, or all
228577  ** remaining data if there are less than 10 bytes available. This is
228578  ** sufficient either for the 'T' or 'P' byte and the varint that follows
228579  ** it, or for the two single byte values otherwise. */
228580  p->rc = sessionInputBuffer(&p->in, 2);
228581  if( p->rc!=SQLITE_OK ) return p->rc;
228582
228583  sessionDiscardData(&p->in);
228584  p->in.iCurrent = p->in.iNext;
228585
228586  /* If the iterator is already at the end of the changeset, return DONE. */
228587  if( p->in.iNext>=p->in.nData ){
228588    return SQLITE_DONE;
228589  }
228590
228591  op = p->in.aData[p->in.iNext++];
228592  while( op=='T' || op=='P' ){
228593    if( pbNew ) *pbNew = 1;
228594    p->bPatchset = (op=='P');
228595    if( sessionChangesetReadTblhdr(p) ) return p->rc;
228596    if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
228597    p->in.iCurrent = p->in.iNext;
228598    if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
228599    op = p->in.aData[p->in.iNext++];
228600  }
228601
228602  if( p->zTab==0 || (p->bPatchset && p->bInvert) ){
228603    /* The first record in the changeset is not a table header. Must be a
228604    ** corrupt changeset. */
228605    assert( p->in.iNext==1 || p->zTab );
228606    return (p->rc = SQLITE_CORRUPT_BKPT);
228607  }
228608
228609  p->op = op;
228610  p->bIndirect = p->in.aData[p->in.iNext++];
228611  if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
228612    return (p->rc = SQLITE_CORRUPT_BKPT);
228613  }
228614
228615  if( paRec ){
228616    int nVal;                     /* Number of values to buffer */
228617    if( p->bPatchset==0 && op==SQLITE_UPDATE ){
228618      nVal = p->nCol * 2;
228619    }else if( p->bPatchset && op==SQLITE_DELETE ){
228620      nVal = 0;
228621      for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
228622    }else{
228623      nVal = p->nCol;
228624    }
228625    p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
228626    if( p->rc!=SQLITE_OK ) return p->rc;
228627    *paRec = &p->in.aData[p->in.iNext];
228628    p->in.iNext += *pnRec;
228629  }else{
228630    sqlite3_value **apOld = (p->bInvert ? &p->apValue[p->nCol] : p->apValue);
228631    sqlite3_value **apNew = (p->bInvert ? p->apValue : &p->apValue[p->nCol]);
228632
228633    /* If this is an UPDATE or DELETE, read the old.* record. */
228634    if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
228635      u8 *abPK = p->bPatchset ? p->abPK : 0;
228636      p->rc = sessionReadRecord(&p->in, p->nCol, abPK, apOld, 0);
228637      if( p->rc!=SQLITE_OK ) return p->rc;
228638    }
228639
228640    /* If this is an INSERT or UPDATE, read the new.* record. */
228641    if( p->op!=SQLITE_DELETE ){
228642      p->rc = sessionReadRecord(&p->in, p->nCol, 0, apNew, pbEmpty);
228643      if( p->rc!=SQLITE_OK ) return p->rc;
228644    }
228645
228646    if( (p->bPatchset || p->bInvert) && p->op==SQLITE_UPDATE ){
228647      /* If this is an UPDATE that is part of a patchset, then all PK and
228648      ** modified fields are present in the new.* record. The old.* record
228649      ** is currently completely empty. This block shifts the PK fields from
228650      ** new.* to old.*, to accommodate the code that reads these arrays.  */
228651      for(i=0; i<p->nCol; i++){
228652        assert( p->bPatchset==0 || p->apValue[i]==0 );
228653        if( p->abPK[i] ){
228654          assert( p->apValue[i]==0 );
228655          p->apValue[i] = p->apValue[i+p->nCol];
228656          if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT);
228657          p->apValue[i+p->nCol] = 0;
228658        }
228659      }
228660    }else if( p->bInvert ){
228661      if( p->op==SQLITE_INSERT ) p->op = SQLITE_DELETE;
228662      else if( p->op==SQLITE_DELETE ) p->op = SQLITE_INSERT;
228663    }
228664
228665    /* If this is an UPDATE that is part of a changeset, then check that
228666    ** there are no fields in the old.* record that are not (a) PK fields,
228667    ** or (b) also present in the new.* record.
228668    **
228669    ** Such records are technically corrupt, but the rebaser was at one
228670    ** point generating them. Under most circumstances this is benign, but
228671    ** can cause spurious SQLITE_RANGE errors when applying the changeset. */
228672    if( p->bPatchset==0 && p->op==SQLITE_UPDATE){
228673      for(i=0; i<p->nCol; i++){
228674        if( p->abPK[i]==0 && p->apValue[i+p->nCol]==0 ){
228675          sqlite3ValueFree(p->apValue[i]);
228676          p->apValue[i] = 0;
228677        }
228678      }
228679    }
228680  }
228681
228682  return SQLITE_ROW;
228683}
228684
228685/*
228686** Advance the changeset iterator to the next change.
228687**
228688** If both paRec and pnRec are NULL, then this function works like the public
228689** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
228690** sqlite3changeset_new() and old() APIs may be used to query for values.
228691**
228692** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
228693** record is written to *paRec before returning and the number of bytes in
228694** the record to *pnRec.
228695**
228696** Either way, this function returns SQLITE_ROW if the iterator is
228697** successfully advanced to the next change in the changeset, an SQLite
228698** error code if an error occurs, or SQLITE_DONE if there are no further
228699** changes in the changeset.
228700*/
228701static int sessionChangesetNext(
228702  sqlite3_changeset_iter *p,      /* Changeset iterator */
228703  u8 **paRec,                     /* If non-NULL, store record pointer here */
228704  int *pnRec,                     /* If non-NULL, store size of record here */
228705  int *pbNew                      /* If non-NULL, true if new table */
228706){
228707  int bEmpty;
228708  int rc;
228709  do {
228710    bEmpty = 0;
228711    rc = sessionChangesetNextOne(p, paRec, pnRec, pbNew, &bEmpty);
228712  }while( rc==SQLITE_ROW && p->bSkipEmpty && bEmpty);
228713  return rc;
228714}
228715
228716/*
228717** Advance an iterator created by sqlite3changeset_start() to the next
228718** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
228719** or SQLITE_CORRUPT.
228720**
228721** This function may not be called on iterators passed to a conflict handler
228722** callback by changeset_apply().
228723*/
228724SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
228725  return sessionChangesetNext(p, 0, 0, 0);
228726}
228727
228728/*
228729** The following function extracts information on the current change
228730** from a changeset iterator. It may only be called after changeset_next()
228731** has returned SQLITE_ROW.
228732*/
228733SQLITE_API int sqlite3changeset_op(
228734  sqlite3_changeset_iter *pIter,  /* Iterator handle */
228735  const char **pzTab,             /* OUT: Pointer to table name */
228736  int *pnCol,                     /* OUT: Number of columns in table */
228737  int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
228738  int *pbIndirect                 /* OUT: True if change is indirect */
228739){
228740  *pOp = pIter->op;
228741  *pnCol = pIter->nCol;
228742  *pzTab = pIter->zTab;
228743  if( pbIndirect ) *pbIndirect = pIter->bIndirect;
228744  return SQLITE_OK;
228745}
228746
228747/*
228748** Return information regarding the PRIMARY KEY and number of columns in
228749** the database table affected by the change that pIter currently points
228750** to. This function may only be called after changeset_next() returns
228751** SQLITE_ROW.
228752*/
228753SQLITE_API int sqlite3changeset_pk(
228754  sqlite3_changeset_iter *pIter,  /* Iterator object */
228755  unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
228756  int *pnCol                      /* OUT: Number of entries in output array */
228757){
228758  *pabPK = pIter->abPK;
228759  if( pnCol ) *pnCol = pIter->nCol;
228760  return SQLITE_OK;
228761}
228762
228763/*
228764** This function may only be called while the iterator is pointing to an
228765** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
228766** Otherwise, SQLITE_MISUSE is returned.
228767**
228768** It sets *ppValue to point to an sqlite3_value structure containing the
228769** iVal'th value in the old.* record. Or, if that particular value is not
228770** included in the record (because the change is an UPDATE and the field
228771** was not modified and is not a PK column), set *ppValue to NULL.
228772**
228773** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
228774** not modified. Otherwise, SQLITE_OK.
228775*/
228776SQLITE_API int sqlite3changeset_old(
228777  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
228778  int iVal,                       /* Index of old.* value to retrieve */
228779  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
228780){
228781  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
228782    return SQLITE_MISUSE;
228783  }
228784  if( iVal<0 || iVal>=pIter->nCol ){
228785    return SQLITE_RANGE;
228786  }
228787  *ppValue = pIter->apValue[iVal];
228788  return SQLITE_OK;
228789}
228790
228791/*
228792** This function may only be called while the iterator is pointing to an
228793** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
228794** Otherwise, SQLITE_MISUSE is returned.
228795**
228796** It sets *ppValue to point to an sqlite3_value structure containing the
228797** iVal'th value in the new.* record. Or, if that particular value is not
228798** included in the record (because the change is an UPDATE and the field
228799** was not modified), set *ppValue to NULL.
228800**
228801** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
228802** not modified. Otherwise, SQLITE_OK.
228803*/
228804SQLITE_API int sqlite3changeset_new(
228805  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
228806  int iVal,                       /* Index of new.* value to retrieve */
228807  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
228808){
228809  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
228810    return SQLITE_MISUSE;
228811  }
228812  if( iVal<0 || iVal>=pIter->nCol ){
228813    return SQLITE_RANGE;
228814  }
228815  *ppValue = pIter->apValue[pIter->nCol+iVal];
228816  return SQLITE_OK;
228817}
228818
228819/*
228820** The following two macros are used internally. They are similar to the
228821** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
228822** they omit all error checking and return a pointer to the requested value.
228823*/
228824#define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
228825#define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
228826
228827/*
228828** This function may only be called with a changeset iterator that has been
228829** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
228830** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
228831**
228832** If successful, *ppValue is set to point to an sqlite3_value structure
228833** containing the iVal'th value of the conflicting record.
228834**
228835** If value iVal is out-of-range or some other error occurs, an SQLite error
228836** code is returned. Otherwise, SQLITE_OK.
228837*/
228838SQLITE_API int sqlite3changeset_conflict(
228839  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
228840  int iVal,                       /* Index of conflict record value to fetch */
228841  sqlite3_value **ppValue         /* OUT: Value from conflicting row */
228842){
228843  if( !pIter->pConflict ){
228844    return SQLITE_MISUSE;
228845  }
228846  if( iVal<0 || iVal>=pIter->nCol ){
228847    return SQLITE_RANGE;
228848  }
228849  *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
228850  return SQLITE_OK;
228851}
228852
228853/*
228854** This function may only be called with an iterator passed to an
228855** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
228856** it sets the output variable to the total number of known foreign key
228857** violations in the destination database and returns SQLITE_OK.
228858**
228859** In all other cases this function returns SQLITE_MISUSE.
228860*/
228861SQLITE_API int sqlite3changeset_fk_conflicts(
228862  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
228863  int *pnOut                      /* OUT: Number of FK violations */
228864){
228865  if( pIter->pConflict || pIter->apValue ){
228866    return SQLITE_MISUSE;
228867  }
228868  *pnOut = pIter->nCol;
228869  return SQLITE_OK;
228870}
228871
228872
228873/*
228874** Finalize an iterator allocated with sqlite3changeset_start().
228875**
228876** This function may not be called on iterators passed to a conflict handler
228877** callback by changeset_apply().
228878*/
228879SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
228880  int rc = SQLITE_OK;
228881  if( p ){
228882    int i;                        /* Used to iterate through p->apValue[] */
228883    rc = p->rc;
228884    if( p->apValue ){
228885      for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
228886    }
228887    sqlite3_free(p->tblhdr.aBuf);
228888    sqlite3_free(p->in.buf.aBuf);
228889    sqlite3_free(p);
228890  }
228891  return rc;
228892}
228893
228894static int sessionChangesetInvert(
228895  SessionInput *pInput,           /* Input changeset */
228896  int (*xOutput)(void *pOut, const void *pData, int nData),
228897  void *pOut,
228898  int *pnInverted,                /* OUT: Number of bytes in output changeset */
228899  void **ppInverted               /* OUT: Inverse of pChangeset */
228900){
228901  int rc = SQLITE_OK;             /* Return value */
228902  SessionBuffer sOut;             /* Output buffer */
228903  int nCol = 0;                   /* Number of cols in current table */
228904  u8 *abPK = 0;                   /* PK array for current table */
228905  sqlite3_value **apVal = 0;      /* Space for values for UPDATE inversion */
228906  SessionBuffer sPK = {0, 0, 0};  /* PK array for current table */
228907
228908  /* Initialize the output buffer */
228909  memset(&sOut, 0, sizeof(SessionBuffer));
228910
228911  /* Zero the output variables in case an error occurs. */
228912  if( ppInverted ){
228913    *ppInverted = 0;
228914    *pnInverted = 0;
228915  }
228916
228917  while( 1 ){
228918    u8 eType;
228919
228920    /* Test for EOF. */
228921    if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
228922    if( pInput->iNext>=pInput->nData ) break;
228923    eType = pInput->aData[pInput->iNext];
228924
228925    switch( eType ){
228926      case 'T': {
228927        /* A 'table' record consists of:
228928        **
228929        **   * A constant 'T' character,
228930        **   * Number of columns in said table (a varint),
228931        **   * An array of nCol bytes (sPK),
228932        **   * A nul-terminated table name.
228933        */
228934        int nByte;
228935        int nVar;
228936        pInput->iNext++;
228937        if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
228938          goto finished_invert;
228939        }
228940        nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
228941        sPK.nBuf = 0;
228942        sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
228943        sessionAppendByte(&sOut, eType, &rc);
228944        sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
228945        if( rc ) goto finished_invert;
228946
228947        pInput->iNext += nByte;
228948        sqlite3_free(apVal);
228949        apVal = 0;
228950        abPK = sPK.aBuf;
228951        break;
228952      }
228953
228954      case SQLITE_INSERT:
228955      case SQLITE_DELETE: {
228956        int nByte;
228957        int bIndirect = pInput->aData[pInput->iNext+1];
228958        int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
228959        pInput->iNext += 2;
228960        assert( rc==SQLITE_OK );
228961        rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
228962        sessionAppendByte(&sOut, eType2, &rc);
228963        sessionAppendByte(&sOut, bIndirect, &rc);
228964        sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
228965        pInput->iNext += nByte;
228966        if( rc ) goto finished_invert;
228967        break;
228968      }
228969
228970      case SQLITE_UPDATE: {
228971        int iCol;
228972
228973        if( 0==apVal ){
228974          apVal = (sqlite3_value **)sqlite3_malloc64(sizeof(apVal[0])*nCol*2);
228975          if( 0==apVal ){
228976            rc = SQLITE_NOMEM;
228977            goto finished_invert;
228978          }
228979          memset(apVal, 0, sizeof(apVal[0])*nCol*2);
228980        }
228981
228982        /* Write the header for the new UPDATE change. Same as the original. */
228983        sessionAppendByte(&sOut, eType, &rc);
228984        sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
228985
228986        /* Read the old.* and new.* records for the update change. */
228987        pInput->iNext += 2;
228988        rc = sessionReadRecord(pInput, nCol, 0, &apVal[0], 0);
228989        if( rc==SQLITE_OK ){
228990          rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol], 0);
228991        }
228992
228993        /* Write the new old.* record. Consists of the PK columns from the
228994        ** original old.* record, and the other values from the original
228995        ** new.* record. */
228996        for(iCol=0; iCol<nCol; iCol++){
228997          sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
228998          sessionAppendValue(&sOut, pVal, &rc);
228999        }
229000
229001        /* Write the new new.* record. Consists of a copy of all values
229002        ** from the original old.* record, except for the PK columns, which
229003        ** are set to "undefined". */
229004        for(iCol=0; iCol<nCol; iCol++){
229005          sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
229006          sessionAppendValue(&sOut, pVal, &rc);
229007        }
229008
229009        for(iCol=0; iCol<nCol*2; iCol++){
229010          sqlite3ValueFree(apVal[iCol]);
229011        }
229012        memset(apVal, 0, sizeof(apVal[0])*nCol*2);
229013        if( rc!=SQLITE_OK ){
229014          goto finished_invert;
229015        }
229016
229017        break;
229018      }
229019
229020      default:
229021        rc = SQLITE_CORRUPT_BKPT;
229022        goto finished_invert;
229023    }
229024
229025    assert( rc==SQLITE_OK );
229026    if( xOutput && sOut.nBuf>=sessions_strm_chunk_size ){
229027      rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
229028      sOut.nBuf = 0;
229029      if( rc!=SQLITE_OK ) goto finished_invert;
229030    }
229031  }
229032
229033  assert( rc==SQLITE_OK );
229034  if( pnInverted && ALWAYS(ppInverted) ){
229035    *pnInverted = sOut.nBuf;
229036    *ppInverted = sOut.aBuf;
229037    sOut.aBuf = 0;
229038  }else if( sOut.nBuf>0 && ALWAYS(xOutput!=0) ){
229039    rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
229040  }
229041
229042 finished_invert:
229043  sqlite3_free(sOut.aBuf);
229044  sqlite3_free(apVal);
229045  sqlite3_free(sPK.aBuf);
229046  return rc;
229047}
229048
229049
229050/*
229051** Invert a changeset object.
229052*/
229053SQLITE_API int sqlite3changeset_invert(
229054  int nChangeset,                 /* Number of bytes in input */
229055  const void *pChangeset,         /* Input changeset */
229056  int *pnInverted,                /* OUT: Number of bytes in output changeset */
229057  void **ppInverted               /* OUT: Inverse of pChangeset */
229058){
229059  SessionInput sInput;
229060
229061  /* Set up the input stream */
229062  memset(&sInput, 0, sizeof(SessionInput));
229063  sInput.nData = nChangeset;
229064  sInput.aData = (u8*)pChangeset;
229065
229066  return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
229067}
229068
229069/*
229070** Streaming version of sqlite3changeset_invert().
229071*/
229072SQLITE_API int sqlite3changeset_invert_strm(
229073  int (*xInput)(void *pIn, void *pData, int *pnData),
229074  void *pIn,
229075  int (*xOutput)(void *pOut, const void *pData, int nData),
229076  void *pOut
229077){
229078  SessionInput sInput;
229079  int rc;
229080
229081  /* Set up the input stream */
229082  memset(&sInput, 0, sizeof(SessionInput));
229083  sInput.xInput = xInput;
229084  sInput.pIn = pIn;
229085
229086  rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
229087  sqlite3_free(sInput.buf.aBuf);
229088  return rc;
229089}
229090
229091
229092typedef struct SessionUpdate SessionUpdate;
229093struct SessionUpdate {
229094  sqlite3_stmt *pStmt;
229095  u32 *aMask;
229096  SessionUpdate *pNext;
229097};
229098
229099typedef struct SessionApplyCtx SessionApplyCtx;
229100struct SessionApplyCtx {
229101  sqlite3 *db;
229102  sqlite3_stmt *pDelete;          /* DELETE statement */
229103  sqlite3_stmt *pInsert;          /* INSERT statement */
229104  sqlite3_stmt *pSelect;          /* SELECT statement */
229105  int nCol;                       /* Size of azCol[] and abPK[] arrays */
229106  const char **azCol;             /* Array of column names */
229107  u8 *abPK;                       /* Boolean array - true if column is in PK */
229108  u32 *aUpdateMask;               /* Used by sessionUpdateFind */
229109  SessionUpdate *pUp;
229110  int bStat1;                     /* True if table is sqlite_stat1 */
229111  int bDeferConstraints;          /* True to defer constraints */
229112  int bInvertConstraints;         /* Invert when iterating constraints buffer */
229113  SessionBuffer constraints;      /* Deferred constraints are stored here */
229114  SessionBuffer rebase;           /* Rebase information (if any) here */
229115  u8 bRebaseStarted;              /* If table header is already in rebase */
229116  u8 bRebase;                     /* True to collect rebase information */
229117  u8 bIgnoreNoop;                 /* True to ignore no-op conflicts */
229118  int bRowid;
229119};
229120
229121/* Number of prepared UPDATE statements to cache. */
229122#define SESSION_UPDATE_CACHE_SZ 12
229123
229124/*
229125** Find a prepared UPDATE statement suitable for the UPDATE step currently
229126** being visited by the iterator. The UPDATE is of the form:
229127**
229128**   UPDATE tbl SET col = ?, col2 = ? WHERE pk1 IS ? AND pk2 IS ?
229129*/
229130static int sessionUpdateFind(
229131  sqlite3_changeset_iter *pIter,
229132  SessionApplyCtx *p,
229133  int bPatchset,
229134  sqlite3_stmt **ppStmt
229135){
229136  int rc = SQLITE_OK;
229137  SessionUpdate *pUp = 0;
229138  int nCol = pIter->nCol;
229139  int nU32 = (pIter->nCol+33)/32;
229140  int ii;
229141
229142  if( p->aUpdateMask==0 ){
229143    p->aUpdateMask = sqlite3_malloc(nU32*sizeof(u32));
229144    if( p->aUpdateMask==0 ){
229145      rc = SQLITE_NOMEM;
229146    }
229147  }
229148
229149  if( rc==SQLITE_OK ){
229150    memset(p->aUpdateMask, 0, nU32*sizeof(u32));
229151    rc = SQLITE_CORRUPT;
229152    for(ii=0; ii<pIter->nCol; ii++){
229153      if( sessionChangesetNew(pIter, ii) ){
229154        p->aUpdateMask[ii/32] |= (1<<(ii%32));
229155        rc = SQLITE_OK;
229156      }
229157    }
229158  }
229159
229160  if( rc==SQLITE_OK ){
229161    if( bPatchset ) p->aUpdateMask[nCol/32] |= (1<<(nCol%32));
229162
229163    if( p->pUp ){
229164      int nUp = 0;
229165      SessionUpdate **pp = &p->pUp;
229166      while( 1 ){
229167        nUp++;
229168        if( 0==memcmp(p->aUpdateMask, (*pp)->aMask, nU32*sizeof(u32)) ){
229169          pUp = *pp;
229170          *pp = pUp->pNext;
229171          pUp->pNext = p->pUp;
229172          p->pUp = pUp;
229173          break;
229174        }
229175
229176        if( (*pp)->pNext ){
229177          pp = &(*pp)->pNext;
229178        }else{
229179          if( nUp>=SESSION_UPDATE_CACHE_SZ ){
229180            sqlite3_finalize((*pp)->pStmt);
229181            sqlite3_free(*pp);
229182            *pp = 0;
229183          }
229184          break;
229185        }
229186      }
229187    }
229188
229189    if( pUp==0 ){
229190      int nByte = sizeof(SessionUpdate) * nU32*sizeof(u32);
229191      int bStat1 = (sqlite3_stricmp(pIter->zTab, "sqlite_stat1")==0);
229192      pUp = (SessionUpdate*)sqlite3_malloc(nByte);
229193      if( pUp==0 ){
229194        rc = SQLITE_NOMEM;
229195      }else{
229196        const char *zSep = "";
229197        SessionBuffer buf;
229198
229199        memset(&buf, 0, sizeof(buf));
229200        pUp->aMask = (u32*)&pUp[1];
229201        memcpy(pUp->aMask, p->aUpdateMask, nU32*sizeof(u32));
229202
229203        sessionAppendStr(&buf, "UPDATE main.", &rc);
229204        sessionAppendIdent(&buf, pIter->zTab, &rc);
229205        sessionAppendStr(&buf, " SET ", &rc);
229206
229207        /* Create the assignments part of the UPDATE */
229208        for(ii=0; ii<pIter->nCol; ii++){
229209          if( p->abPK[ii]==0 && sessionChangesetNew(pIter, ii) ){
229210            sessionAppendStr(&buf, zSep, &rc);
229211            sessionAppendIdent(&buf, p->azCol[ii], &rc);
229212            sessionAppendStr(&buf, " = ?", &rc);
229213            sessionAppendInteger(&buf, ii*2+1, &rc);
229214            zSep = ", ";
229215          }
229216        }
229217
229218        /* Create the WHERE clause part of the UPDATE */
229219        zSep = "";
229220        sessionAppendStr(&buf, " WHERE ", &rc);
229221        for(ii=0; ii<pIter->nCol; ii++){
229222          if( p->abPK[ii] || (bPatchset==0 && sessionChangesetOld(pIter, ii)) ){
229223            sessionAppendStr(&buf, zSep, &rc);
229224            if( bStat1 && ii==1 ){
229225              assert( sqlite3_stricmp(p->azCol[ii], "idx")==0 );
229226              sessionAppendStr(&buf,
229227                  "idx IS CASE "
229228                  "WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL "
229229                  "ELSE ?4 END ", &rc
229230              );
229231            }else{
229232              sessionAppendIdent(&buf, p->azCol[ii], &rc);
229233              sessionAppendStr(&buf, " IS ?", &rc);
229234              sessionAppendInteger(&buf, ii*2+2, &rc);
229235            }
229236            zSep = " AND ";
229237          }
229238        }
229239
229240        if( rc==SQLITE_OK ){
229241          char *zSql = (char*)buf.aBuf;
229242          rc = sqlite3_prepare_v2(p->db, zSql, buf.nBuf, &pUp->pStmt, 0);
229243        }
229244
229245        if( rc!=SQLITE_OK ){
229246          sqlite3_free(pUp);
229247          pUp = 0;
229248        }else{
229249          pUp->pNext = p->pUp;
229250          p->pUp = pUp;
229251        }
229252        sqlite3_free(buf.aBuf);
229253      }
229254    }
229255  }
229256
229257  assert( (rc==SQLITE_OK)==(pUp!=0) );
229258  if( pUp ){
229259    *ppStmt = pUp->pStmt;
229260  }else{
229261    *ppStmt = 0;
229262  }
229263  return rc;
229264}
229265
229266/*
229267** Free all cached UPDATE statements.
229268*/
229269static void sessionUpdateFree(SessionApplyCtx *p){
229270  SessionUpdate *pUp;
229271  SessionUpdate *pNext;
229272  for(pUp=p->pUp; pUp; pUp=pNext){
229273    pNext = pUp->pNext;
229274    sqlite3_finalize(pUp->pStmt);
229275    sqlite3_free(pUp);
229276  }
229277  p->pUp = 0;
229278  sqlite3_free(p->aUpdateMask);
229279  p->aUpdateMask = 0;
229280}
229281
229282/*
229283** Formulate a statement to DELETE a row from database db. Assuming a table
229284** structure like this:
229285**
229286**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
229287**
229288** The DELETE statement looks like this:
229289**
229290**     DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
229291**
229292** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
229293** matching b and d values, or 1 otherwise. The second case comes up if the
229294** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
229295**
229296** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
229297** pointing to the prepared version of the SQL statement.
229298*/
229299static int sessionDeleteRow(
229300  sqlite3 *db,                    /* Database handle */
229301  const char *zTab,               /* Table name */
229302  SessionApplyCtx *p              /* Session changeset-apply context */
229303){
229304  int i;
229305  const char *zSep = "";
229306  int rc = SQLITE_OK;
229307  SessionBuffer buf = {0, 0, 0};
229308  int nPk = 0;
229309
229310  sessionAppendStr(&buf, "DELETE FROM main.", &rc);
229311  sessionAppendIdent(&buf, zTab, &rc);
229312  sessionAppendStr(&buf, " WHERE ", &rc);
229313
229314  for(i=0; i<p->nCol; i++){
229315    if( p->abPK[i] ){
229316      nPk++;
229317      sessionAppendStr(&buf, zSep, &rc);
229318      sessionAppendIdent(&buf, p->azCol[i], &rc);
229319      sessionAppendStr(&buf, " = ?", &rc);
229320      sessionAppendInteger(&buf, i+1, &rc);
229321      zSep = " AND ";
229322    }
229323  }
229324
229325  if( nPk<p->nCol ){
229326    sessionAppendStr(&buf, " AND (?", &rc);
229327    sessionAppendInteger(&buf, p->nCol+1, &rc);
229328    sessionAppendStr(&buf, " OR ", &rc);
229329
229330    zSep = "";
229331    for(i=0; i<p->nCol; i++){
229332      if( !p->abPK[i] ){
229333        sessionAppendStr(&buf, zSep, &rc);
229334        sessionAppendIdent(&buf, p->azCol[i], &rc);
229335        sessionAppendStr(&buf, " IS ?", &rc);
229336        sessionAppendInteger(&buf, i+1, &rc);
229337        zSep = "AND ";
229338      }
229339    }
229340    sessionAppendStr(&buf, ")", &rc);
229341  }
229342
229343  if( rc==SQLITE_OK ){
229344    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
229345  }
229346  sqlite3_free(buf.aBuf);
229347
229348  return rc;
229349}
229350
229351/*
229352** Formulate and prepare an SQL statement to query table zTab by primary
229353** key. Assuming the following table structure:
229354**
229355**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
229356**
229357** The SELECT statement looks like this:
229358**
229359**     SELECT * FROM x WHERE a = ?1 AND c = ?3
229360**
229361** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
229362** pointing to the prepared version of the SQL statement.
229363*/
229364static int sessionSelectRow(
229365  sqlite3 *db,                    /* Database handle */
229366  const char *zTab,               /* Table name */
229367  SessionApplyCtx *p              /* Session changeset-apply context */
229368){
229369  /* TODO */
229370  return sessionSelectStmt(db, p->bIgnoreNoop,
229371      "main", zTab, p->bRowid, p->nCol, p->azCol, p->abPK, &p->pSelect
229372  );
229373}
229374
229375/*
229376** Formulate and prepare an INSERT statement to add a record to table zTab.
229377** For example:
229378**
229379**     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
229380**
229381** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
229382** pointing to the prepared version of the SQL statement.
229383*/
229384static int sessionInsertRow(
229385  sqlite3 *db,                    /* Database handle */
229386  const char *zTab,               /* Table name */
229387  SessionApplyCtx *p              /* Session changeset-apply context */
229388){
229389  int rc = SQLITE_OK;
229390  int i;
229391  SessionBuffer buf = {0, 0, 0};
229392
229393  sessionAppendStr(&buf, "INSERT INTO main.", &rc);
229394  sessionAppendIdent(&buf, zTab, &rc);
229395  sessionAppendStr(&buf, "(", &rc);
229396  for(i=0; i<p->nCol; i++){
229397    if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
229398    sessionAppendIdent(&buf, p->azCol[i], &rc);
229399  }
229400
229401  sessionAppendStr(&buf, ") VALUES(?", &rc);
229402  for(i=1; i<p->nCol; i++){
229403    sessionAppendStr(&buf, ", ?", &rc);
229404  }
229405  sessionAppendStr(&buf, ")", &rc);
229406
229407  if( rc==SQLITE_OK ){
229408    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
229409  }
229410  sqlite3_free(buf.aBuf);
229411  return rc;
229412}
229413
229414static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
229415  return sqlite3_prepare_v2(db, zSql, -1, pp, 0);
229416}
229417
229418/*
229419** Prepare statements for applying changes to the sqlite_stat1 table.
229420** These are similar to those created by sessionSelectRow(),
229421** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for
229422** other tables.
229423*/
229424static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
229425  int rc = sessionSelectRow(db, "sqlite_stat1", p);
229426  if( rc==SQLITE_OK ){
229427    rc = sessionPrepare(db, &p->pInsert,
229428        "INSERT INTO main.sqlite_stat1 VALUES(?1, "
229429        "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, "
229430        "?3)"
229431    );
229432  }
229433  if( rc==SQLITE_OK ){
229434    rc = sessionPrepare(db, &p->pDelete,
229435        "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS "
229436        "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END "
229437        "AND (?4 OR stat IS ?3)"
229438    );
229439  }
229440  return rc;
229441}
229442
229443/*
229444** A wrapper around sqlite3_bind_value() that detects an extra problem.
229445** See comments in the body of this function for details.
229446*/
229447static int sessionBindValue(
229448  sqlite3_stmt *pStmt,            /* Statement to bind value to */
229449  int i,                          /* Parameter number to bind to */
229450  sqlite3_value *pVal             /* Value to bind */
229451){
229452  int eType = sqlite3_value_type(pVal);
229453  /* COVERAGE: The (pVal->z==0) branch is never true using current versions
229454  ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
229455  ** the (pVal->z) variable remains as it was or the type of the value is
229456  ** set to SQLITE_NULL.  */
229457  if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
229458    /* This condition occurs when an earlier OOM in a call to
229459    ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
229460    ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
229461    return SQLITE_NOMEM;
229462  }
229463  return sqlite3_bind_value(pStmt, i, pVal);
229464}
229465
229466/*
229467** Iterator pIter must point to an SQLITE_INSERT entry. This function
229468** transfers new.* values from the current iterator entry to statement
229469** pStmt. The table being inserted into has nCol columns.
229470**
229471** New.* value $i from the iterator is bound to variable ($i+1) of
229472** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
229473** are transfered to the statement. Otherwise, if abPK is not NULL, it points
229474** to an array nCol elements in size. In this case only those values for
229475** which abPK[$i] is true are read from the iterator and bound to the
229476** statement.
229477**
229478** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
229479*/
229480static int sessionBindRow(
229481  sqlite3_changeset_iter *pIter,  /* Iterator to read values from */
229482  int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
229483  int nCol,                       /* Number of columns */
229484  u8 *abPK,                       /* If not NULL, bind only if true */
229485  sqlite3_stmt *pStmt             /* Bind values to this statement */
229486){
229487  int i;
229488  int rc = SQLITE_OK;
229489
229490  /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
229491  ** argument iterator points to a suitable entry. Make sure that xValue
229492  ** is one of these to guarantee that it is safe to ignore the return
229493  ** in the code below. */
229494  assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
229495
229496  for(i=0; rc==SQLITE_OK && i<nCol; i++){
229497    if( !abPK || abPK[i] ){
229498      sqlite3_value *pVal = 0;
229499      (void)xValue(pIter, i, &pVal);
229500      if( pVal==0 ){
229501        /* The value in the changeset was "undefined". This indicates a
229502        ** corrupt changeset blob.  */
229503        rc = SQLITE_CORRUPT_BKPT;
229504      }else{
229505        rc = sessionBindValue(pStmt, i+1, pVal);
229506      }
229507    }
229508  }
229509  return rc;
229510}
229511
229512/*
229513** SQL statement pSelect is as generated by the sessionSelectRow() function.
229514** This function binds the primary key values from the change that changeset
229515** iterator pIter points to to the SELECT and attempts to seek to the table
229516** entry. If a row is found, the SELECT statement left pointing at the row
229517** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
229518** has occured, the statement is reset and SQLITE_OK is returned. If an
229519** error occurs, the statement is reset and an SQLite error code is returned.
229520**
229521** If this function returns SQLITE_ROW, the caller must eventually reset()
229522** statement pSelect. If any other value is returned, the statement does
229523** not require a reset().
229524**
229525** If the iterator currently points to an INSERT record, bind values from the
229526** new.* record to the SELECT statement. Or, if it points to a DELETE or
229527** UPDATE, bind values from the old.* record.
229528*/
229529static int sessionSeekToRow(
229530  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
229531  SessionApplyCtx *p
229532){
229533  sqlite3_stmt *pSelect = p->pSelect;
229534  int rc;                         /* Return code */
229535  int nCol;                       /* Number of columns in table */
229536  int op;                         /* Changset operation (SQLITE_UPDATE etc.) */
229537  const char *zDummy;             /* Unused */
229538
229539  sqlite3_clear_bindings(pSelect);
229540  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
229541  rc = sessionBindRow(pIter,
229542      op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
229543      nCol, p->abPK, pSelect
229544  );
229545
229546  if( op!=SQLITE_DELETE && p->bIgnoreNoop ){
229547    int ii;
229548    for(ii=0; rc==SQLITE_OK && ii<nCol; ii++){
229549      if( p->abPK[ii]==0 ){
229550        sqlite3_value *pVal = 0;
229551        sqlite3changeset_new(pIter, ii, &pVal);
229552        sqlite3_bind_int(pSelect, ii+1+nCol, (pVal==0));
229553        if( pVal ) rc = sessionBindValue(pSelect, ii+1, pVal);
229554      }
229555    }
229556  }
229557
229558  if( rc==SQLITE_OK ){
229559    rc = sqlite3_step(pSelect);
229560    if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
229561  }
229562
229563  return rc;
229564}
229565
229566/*
229567** This function is called from within sqlite3changeset_apply_v2() when
229568** a conflict is encountered and resolved using conflict resolution
229569** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..
229570** It adds a conflict resolution record to the buffer in
229571** SessionApplyCtx.rebase, which will eventually be returned to the caller
229572** of apply_v2() as the "rebase" buffer.
229573**
229574** Return SQLITE_OK if successful, or an SQLite error code otherwise.
229575*/
229576static int sessionRebaseAdd(
229577  SessionApplyCtx *p,             /* Apply context */
229578  int eType,                      /* Conflict resolution (OMIT or REPLACE) */
229579  sqlite3_changeset_iter *pIter   /* Iterator pointing at current change */
229580){
229581  int rc = SQLITE_OK;
229582  if( p->bRebase ){
229583    int i;
229584    int eOp = pIter->op;
229585    if( p->bRebaseStarted==0 ){
229586      /* Append a table-header to the rebase buffer */
229587      const char *zTab = pIter->zTab;
229588      sessionAppendByte(&p->rebase, 'T', &rc);
229589      sessionAppendVarint(&p->rebase, p->nCol, &rc);
229590      sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc);
229591      sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc);
229592      p->bRebaseStarted = 1;
229593    }
229594
229595    assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT );
229596    assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE );
229597
229598    sessionAppendByte(&p->rebase,
229599        (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc
229600        );
229601    sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc);
229602    for(i=0; i<p->nCol; i++){
229603      sqlite3_value *pVal = 0;
229604      if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){
229605        sqlite3changeset_old(pIter, i, &pVal);
229606      }else{
229607        sqlite3changeset_new(pIter, i, &pVal);
229608      }
229609      sessionAppendValue(&p->rebase, pVal, &rc);
229610    }
229611  }
229612  return rc;
229613}
229614
229615/*
229616** Invoke the conflict handler for the change that the changeset iterator
229617** currently points to.
229618**
229619** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
229620** If argument pbReplace is NULL, then the type of conflict handler invoked
229621** depends solely on eType, as follows:
229622**
229623**    eType value                 Value passed to xConflict
229624**    -------------------------------------------------
229625**    CHANGESET_DATA              CHANGESET_NOTFOUND
229626**    CHANGESET_CONFLICT          CHANGESET_CONSTRAINT
229627**
229628** Or, if pbReplace is not NULL, then an attempt is made to find an existing
229629** record with the same primary key as the record about to be deleted, updated
229630** or inserted. If such a record can be found, it is available to the conflict
229631** handler as the "conflicting" record. In this case the type of conflict
229632** handler invoked is as follows:
229633**
229634**    eType value         PK Record found?   Value passed to xConflict
229635**    ----------------------------------------------------------------
229636**    CHANGESET_DATA      Yes                CHANGESET_DATA
229637**    CHANGESET_DATA      No                 CHANGESET_NOTFOUND
229638**    CHANGESET_CONFLICT  Yes                CHANGESET_CONFLICT
229639**    CHANGESET_CONFLICT  No                 CHANGESET_CONSTRAINT
229640**
229641** If pbReplace is not NULL, and a record with a matching PK is found, and
229642** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
229643** is set to non-zero before returning SQLITE_OK.
229644**
229645** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
229646** returned. Or, if the conflict handler returns an invalid value,
229647** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
229648** this function returns SQLITE_OK.
229649*/
229650static int sessionConflictHandler(
229651  int eType,                      /* Either CHANGESET_DATA or CONFLICT */
229652  SessionApplyCtx *p,             /* changeset_apply() context */
229653  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
229654  int(*xConflict)(void *, int, sqlite3_changeset_iter*),
229655  void *pCtx,                     /* First argument for conflict handler */
229656  int *pbReplace                  /* OUT: Set to true if PK row is found */
229657){
229658  int res = 0;                    /* Value returned by conflict handler */
229659  int rc;
229660  int nCol;
229661  int op;
229662  const char *zDummy;
229663
229664  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
229665
229666  assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
229667  assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
229668  assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
229669
229670  /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
229671  if( pbReplace ){
229672    rc = sessionSeekToRow(pIter, p);
229673  }else{
229674    rc = SQLITE_OK;
229675  }
229676
229677  if( rc==SQLITE_ROW ){
229678    /* There exists another row with the new.* primary key. */
229679    if( p->bIgnoreNoop
229680     && sqlite3_column_int(p->pSelect, sqlite3_column_count(p->pSelect)-1)
229681    ){
229682      res = SQLITE_CHANGESET_OMIT;
229683    }else{
229684      pIter->pConflict = p->pSelect;
229685      res = xConflict(pCtx, eType, pIter);
229686      pIter->pConflict = 0;
229687    }
229688    rc = sqlite3_reset(p->pSelect);
229689  }else if( rc==SQLITE_OK ){
229690    if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
229691      /* Instead of invoking the conflict handler, append the change blob
229692      ** to the SessionApplyCtx.constraints buffer. */
229693      u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
229694      int nBlob = pIter->in.iNext - pIter->in.iCurrent;
229695      sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
229696      return SQLITE_OK;
229697    }else{
229698      /* No other row with the new.* primary key. */
229699      res = xConflict(pCtx, eType+1, pIter);
229700      if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
229701    }
229702  }
229703
229704  if( rc==SQLITE_OK ){
229705    switch( res ){
229706      case SQLITE_CHANGESET_REPLACE:
229707        assert( pbReplace );
229708        *pbReplace = 1;
229709        break;
229710
229711      case SQLITE_CHANGESET_OMIT:
229712        break;
229713
229714      case SQLITE_CHANGESET_ABORT:
229715        rc = SQLITE_ABORT;
229716        break;
229717
229718      default:
229719        rc = SQLITE_MISUSE;
229720        break;
229721    }
229722    if( rc==SQLITE_OK ){
229723      rc = sessionRebaseAdd(p, res, pIter);
229724    }
229725  }
229726
229727  return rc;
229728}
229729
229730/*
229731** Attempt to apply the change that the iterator passed as the first argument
229732** currently points to to the database. If a conflict is encountered, invoke
229733** the conflict handler callback.
229734**
229735** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
229736** one is encountered, update or delete the row with the matching primary key
229737** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
229738** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
229739** to true before returning. In this case the caller will invoke this function
229740** again, this time with pbRetry set to NULL.
229741**
229742** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
229743** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
229744** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
229745** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
229746** before retrying. In this case the caller attempts to remove the conflicting
229747** row before invoking this function again, this time with pbReplace set
229748** to NULL.
229749**
229750** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
229751** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
229752** returned.
229753*/
229754static int sessionApplyOneOp(
229755  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
229756  SessionApplyCtx *p,             /* changeset_apply() context */
229757  int(*xConflict)(void *, int, sqlite3_changeset_iter *),
229758  void *pCtx,                     /* First argument for the conflict handler */
229759  int *pbReplace,                 /* OUT: True to remove PK row and retry */
229760  int *pbRetry                    /* OUT: True to retry. */
229761){
229762  const char *zDummy;
229763  int op;
229764  int nCol;
229765  int rc = SQLITE_OK;
229766
229767  assert( p->pDelete && p->pInsert && p->pSelect );
229768  assert( p->azCol && p->abPK );
229769  assert( !pbReplace || *pbReplace==0 );
229770
229771  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
229772
229773  if( op==SQLITE_DELETE ){
229774
229775    /* Bind values to the DELETE statement. If conflict handling is required,
229776    ** bind values for all columns and set bound variable (nCol+1) to true.
229777    ** Or, if conflict handling is not required, bind just the PK column
229778    ** values and, if it exists, set (nCol+1) to false. Conflict handling
229779    ** is not required if:
229780    **
229781    **   * this is a patchset, or
229782    **   * (pbRetry==0), or
229783    **   * all columns of the table are PK columns (in this case there is
229784    **     no (nCol+1) variable to bind to).
229785    */
229786    u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
229787    rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
229788    if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
229789      rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
229790    }
229791    if( rc!=SQLITE_OK ) return rc;
229792
229793    sqlite3_step(p->pDelete);
229794    rc = sqlite3_reset(p->pDelete);
229795    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 && p->bIgnoreNoop==0 ){
229796      rc = sessionConflictHandler(
229797          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
229798      );
229799    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
229800      rc = sessionConflictHandler(
229801          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
229802      );
229803    }
229804
229805  }else if( op==SQLITE_UPDATE ){
229806    int i;
229807    sqlite3_stmt *pUp = 0;
229808    int bPatchset = (pbRetry==0 || pIter->bPatchset);
229809
229810    rc = sessionUpdateFind(pIter, p, bPatchset, &pUp);
229811
229812    /* Bind values to the UPDATE statement. */
229813    for(i=0; rc==SQLITE_OK && i<nCol; i++){
229814      sqlite3_value *pOld = sessionChangesetOld(pIter, i);
229815      sqlite3_value *pNew = sessionChangesetNew(pIter, i);
229816      if( p->abPK[i] || (bPatchset==0 && pOld) ){
229817        rc = sessionBindValue(pUp, i*2+2, pOld);
229818      }
229819      if( rc==SQLITE_OK && pNew ){
229820        rc = sessionBindValue(pUp, i*2+1, pNew);
229821      }
229822    }
229823    if( rc!=SQLITE_OK ) return rc;
229824
229825    /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
229826    ** the result will be SQLITE_OK with 0 rows modified. */
229827    sqlite3_step(pUp);
229828    rc = sqlite3_reset(pUp);
229829
229830    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
229831      /* A NOTFOUND or DATA error. Search the table to see if it contains
229832      ** a row with a matching primary key. If so, this is a DATA conflict.
229833      ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
229834
229835      rc = sessionConflictHandler(
229836          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
229837      );
229838
229839    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
229840      /* This is always a CONSTRAINT conflict. */
229841      rc = sessionConflictHandler(
229842          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
229843      );
229844    }
229845
229846  }else{
229847    assert( op==SQLITE_INSERT );
229848    if( p->bStat1 ){
229849      /* Check if there is a conflicting row. For sqlite_stat1, this needs
229850      ** to be done using a SELECT, as there is no PRIMARY KEY in the
229851      ** database schema to throw an exception if a duplicate is inserted.  */
229852      rc = sessionSeekToRow(pIter, p);
229853      if( rc==SQLITE_ROW ){
229854        rc = SQLITE_CONSTRAINT;
229855        sqlite3_reset(p->pSelect);
229856      }
229857    }
229858
229859    if( rc==SQLITE_OK ){
229860      rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
229861      if( rc!=SQLITE_OK ) return rc;
229862
229863      sqlite3_step(p->pInsert);
229864      rc = sqlite3_reset(p->pInsert);
229865    }
229866
229867    if( (rc&0xff)==SQLITE_CONSTRAINT ){
229868      rc = sessionConflictHandler(
229869          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
229870      );
229871    }
229872  }
229873
229874  return rc;
229875}
229876
229877/*
229878** Attempt to apply the change that the iterator passed as the first argument
229879** currently points to to the database. If a conflict is encountered, invoke
229880** the conflict handler callback.
229881**
229882** The difference between this function and sessionApplyOne() is that this
229883** function handles the case where the conflict-handler is invoked and
229884** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
229885** retried in some manner.
229886*/
229887static int sessionApplyOneWithRetry(
229888  sqlite3 *db,                    /* Apply change to "main" db of this handle */
229889  sqlite3_changeset_iter *pIter,  /* Changeset iterator to read change from */
229890  SessionApplyCtx *pApply,        /* Apply context */
229891  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
229892  void *pCtx                      /* First argument passed to xConflict */
229893){
229894  int bReplace = 0;
229895  int bRetry = 0;
229896  int rc;
229897
229898  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
229899  if( rc==SQLITE_OK ){
229900    /* If the bRetry flag is set, the change has not been applied due to an
229901    ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
229902    ** a row with the correct PK is present in the db, but one or more other
229903    ** fields do not contain the expected values) and the conflict handler
229904    ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
229905    ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
229906    ** the SQLITE_CHANGESET_DATA problem.  */
229907    if( bRetry ){
229908      assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
229909      rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
229910    }
229911
229912    /* If the bReplace flag is set, the change is an INSERT that has not
229913    ** been performed because the database already contains a row with the
229914    ** specified primary key and the conflict handler returned
229915    ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
229916    ** before reattempting the INSERT.  */
229917    else if( bReplace ){
229918      assert( pIter->op==SQLITE_INSERT );
229919      rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
229920      if( rc==SQLITE_OK ){
229921        rc = sessionBindRow(pIter,
229922            sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
229923        sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
229924      }
229925      if( rc==SQLITE_OK ){
229926        sqlite3_step(pApply->pDelete);
229927        rc = sqlite3_reset(pApply->pDelete);
229928      }
229929      if( rc==SQLITE_OK ){
229930        rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
229931      }
229932      if( rc==SQLITE_OK ){
229933        rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
229934      }
229935    }
229936  }
229937
229938  return rc;
229939}
229940
229941/*
229942** Retry the changes accumulated in the pApply->constraints buffer.
229943*/
229944static int sessionRetryConstraints(
229945  sqlite3 *db,
229946  int bPatchset,
229947  const char *zTab,
229948  SessionApplyCtx *pApply,
229949  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
229950  void *pCtx                      /* First argument passed to xConflict */
229951){
229952  int rc = SQLITE_OK;
229953
229954  while( pApply->constraints.nBuf ){
229955    sqlite3_changeset_iter *pIter2 = 0;
229956    SessionBuffer cons = pApply->constraints;
229957    memset(&pApply->constraints, 0, sizeof(SessionBuffer));
229958
229959    rc = sessionChangesetStart(
229960        &pIter2, 0, 0, cons.nBuf, cons.aBuf, pApply->bInvertConstraints, 1
229961    );
229962    if( rc==SQLITE_OK ){
229963      size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
229964      int rc2;
229965      pIter2->bPatchset = bPatchset;
229966      pIter2->zTab = (char*)zTab;
229967      pIter2->nCol = pApply->nCol;
229968      pIter2->abPK = pApply->abPK;
229969      sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
229970      pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
229971      if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
229972
229973      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
229974        rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
229975      }
229976
229977      rc2 = sqlite3changeset_finalize(pIter2);
229978      if( rc==SQLITE_OK ) rc = rc2;
229979    }
229980    assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
229981
229982    sqlite3_free(cons.aBuf);
229983    if( rc!=SQLITE_OK ) break;
229984    if( pApply->constraints.nBuf>=cons.nBuf ){
229985      /* No progress was made on the last round. */
229986      pApply->bDeferConstraints = 0;
229987    }
229988  }
229989
229990  return rc;
229991}
229992
229993/*
229994** Argument pIter is a changeset iterator that has been initialized, but
229995** not yet passed to sqlite3changeset_next(). This function applies the
229996** changeset to the main database attached to handle "db". The supplied
229997** conflict handler callback is invoked to resolve any conflicts encountered
229998** while applying the change.
229999*/
230000static int sessionChangesetApply(
230001  sqlite3 *db,                    /* Apply change to "main" db of this handle */
230002  sqlite3_changeset_iter *pIter,  /* Changeset to apply */
230003  int(*xFilter)(
230004    void *pCtx,                   /* Copy of sixth arg to _apply() */
230005    const char *zTab              /* Table name */
230006  ),
230007  int(*xConflict)(
230008    void *pCtx,                   /* Copy of fifth arg to _apply() */
230009    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
230010    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
230011  ),
230012  void *pCtx,                     /* First argument passed to xConflict */
230013  void **ppRebase, int *pnRebase, /* OUT: Rebase information */
230014  int flags                       /* SESSION_APPLY_XXX flags */
230015){
230016  int schemaMismatch = 0;
230017  int rc = SQLITE_OK;             /* Return code */
230018  const char *zTab = 0;           /* Name of current table */
230019  int nTab = 0;                   /* Result of sqlite3Strlen30(zTab) */
230020  SessionApplyCtx sApply;         /* changeset_apply() context object */
230021  int bPatchset;
230022
230023  assert( xConflict!=0 );
230024
230025  pIter->in.bNoDiscard = 1;
230026  memset(&sApply, 0, sizeof(sApply));
230027  sApply.bRebase = (ppRebase && pnRebase);
230028  sApply.bInvertConstraints = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
230029  sApply.bIgnoreNoop = !!(flags & SQLITE_CHANGESETAPPLY_IGNORENOOP);
230030  sqlite3_mutex_enter(sqlite3_db_mutex(db));
230031  if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
230032    rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
230033  }
230034  if( rc==SQLITE_OK ){
230035    rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
230036  }
230037  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
230038    int nCol;
230039    int op;
230040    const char *zNew;
230041
230042    sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
230043
230044    if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
230045      u8 *abPK;
230046
230047      rc = sessionRetryConstraints(
230048          db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
230049      );
230050      if( rc!=SQLITE_OK ) break;
230051
230052      sessionUpdateFree(&sApply);
230053      sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
230054      sqlite3_finalize(sApply.pDelete);
230055      sqlite3_finalize(sApply.pInsert);
230056      sqlite3_finalize(sApply.pSelect);
230057      sApply.db = db;
230058      sApply.pDelete = 0;
230059      sApply.pInsert = 0;
230060      sApply.pSelect = 0;
230061      sApply.nCol = 0;
230062      sApply.azCol = 0;
230063      sApply.abPK = 0;
230064      sApply.bStat1 = 0;
230065      sApply.bDeferConstraints = 1;
230066      sApply.bRebaseStarted = 0;
230067      sApply.bRowid = 0;
230068      memset(&sApply.constraints, 0, sizeof(SessionBuffer));
230069
230070      /* If an xFilter() callback was specified, invoke it now. If the
230071      ** xFilter callback returns zero, skip this table. If it returns
230072      ** non-zero, proceed. */
230073      schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
230074      if( schemaMismatch ){
230075        zTab = sqlite3_mprintf("%s", zNew);
230076        if( zTab==0 ){
230077          rc = SQLITE_NOMEM;
230078          break;
230079        }
230080        nTab = (int)strlen(zTab);
230081        sApply.azCol = (const char **)zTab;
230082      }else{
230083        int nMinCol = 0;
230084        int i;
230085
230086        sqlite3changeset_pk(pIter, &abPK, 0);
230087        rc = sessionTableInfo(0, db, "main", zNew,
230088            &sApply.nCol, &zTab, &sApply.azCol, 0, &sApply.abPK, &sApply.bRowid
230089        );
230090        if( rc!=SQLITE_OK ) break;
230091        for(i=0; i<sApply.nCol; i++){
230092          if( sApply.abPK[i] ) nMinCol = i+1;
230093        }
230094
230095        if( sApply.nCol==0 ){
230096          schemaMismatch = 1;
230097          sqlite3_log(SQLITE_SCHEMA,
230098              "sqlite3changeset_apply(): no such table: %s", zTab
230099          );
230100        }
230101        else if( sApply.nCol<nCol ){
230102          schemaMismatch = 1;
230103          sqlite3_log(SQLITE_SCHEMA,
230104              "sqlite3changeset_apply(): table %s has %d columns, "
230105              "expected %d or more",
230106              zTab, sApply.nCol, nCol
230107          );
230108        }
230109        else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
230110          schemaMismatch = 1;
230111          sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
230112              "primary key mismatch for table %s", zTab
230113          );
230114        }
230115        else{
230116          sApply.nCol = nCol;
230117          if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){
230118            if( (rc = sessionStat1Sql(db, &sApply) ) ){
230119              break;
230120            }
230121            sApply.bStat1 = 1;
230122          }else{
230123            if( (rc = sessionSelectRow(db, zTab, &sApply))
230124             || (rc = sessionDeleteRow(db, zTab, &sApply))
230125             || (rc = sessionInsertRow(db, zTab, &sApply))
230126            ){
230127              break;
230128            }
230129            sApply.bStat1 = 0;
230130          }
230131        }
230132        nTab = sqlite3Strlen30(zTab);
230133      }
230134    }
230135
230136    /* If there is a schema mismatch on the current table, proceed to the
230137    ** next change. A log message has already been issued. */
230138    if( schemaMismatch ) continue;
230139
230140    rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
230141  }
230142
230143  bPatchset = pIter->bPatchset;
230144  if( rc==SQLITE_OK ){
230145    rc = sqlite3changeset_finalize(pIter);
230146  }else{
230147    sqlite3changeset_finalize(pIter);
230148  }
230149
230150  if( rc==SQLITE_OK ){
230151    rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
230152  }
230153
230154  if( rc==SQLITE_OK ){
230155    int nFk, notUsed;
230156    sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
230157    if( nFk!=0 ){
230158      int res = SQLITE_CHANGESET_ABORT;
230159      sqlite3_changeset_iter sIter;
230160      memset(&sIter, 0, sizeof(sIter));
230161      sIter.nCol = nFk;
230162      res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
230163      if( res!=SQLITE_CHANGESET_OMIT ){
230164        rc = SQLITE_CONSTRAINT;
230165      }
230166    }
230167  }
230168  sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
230169
230170  if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
230171    if( rc==SQLITE_OK ){
230172      rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
230173    }else{
230174      sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
230175      sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
230176    }
230177  }
230178
230179  assert( sApply.bRebase || sApply.rebase.nBuf==0 );
230180  if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){
230181    *ppRebase = (void*)sApply.rebase.aBuf;
230182    *pnRebase = sApply.rebase.nBuf;
230183    sApply.rebase.aBuf = 0;
230184  }
230185  sessionUpdateFree(&sApply);
230186  sqlite3_finalize(sApply.pInsert);
230187  sqlite3_finalize(sApply.pDelete);
230188  sqlite3_finalize(sApply.pSelect);
230189  sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
230190  sqlite3_free((char*)sApply.constraints.aBuf);
230191  sqlite3_free((char*)sApply.rebase.aBuf);
230192  sqlite3_mutex_leave(sqlite3_db_mutex(db));
230193  return rc;
230194}
230195
230196/*
230197** Apply the changeset passed via pChangeset/nChangeset to the main
230198** database attached to handle "db".
230199*/
230200SQLITE_API int sqlite3changeset_apply_v2(
230201  sqlite3 *db,                    /* Apply change to "main" db of this handle */
230202  int nChangeset,                 /* Size of changeset in bytes */
230203  void *pChangeset,               /* Changeset blob */
230204  int(*xFilter)(
230205    void *pCtx,                   /* Copy of sixth arg to _apply() */
230206    const char *zTab              /* Table name */
230207  ),
230208  int(*xConflict)(
230209    void *pCtx,                   /* Copy of sixth arg to _apply() */
230210    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
230211    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
230212  ),
230213  void *pCtx,                     /* First argument passed to xConflict */
230214  void **ppRebase, int *pnRebase,
230215  int flags
230216){
230217  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
230218  int bInv = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
230219  int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset, bInv, 1);
230220  u64 savedFlag = db->flags & SQLITE_FkNoAction;
230221
230222  if( flags & SQLITE_CHANGESETAPPLY_FKNOACTION ){
230223    db->flags |= ((u64)SQLITE_FkNoAction);
230224    db->aDb[0].pSchema->schema_cookie -= 32;
230225  }
230226
230227  if( rc==SQLITE_OK ){
230228    rc = sessionChangesetApply(
230229        db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
230230    );
230231  }
230232
230233  if( (flags & SQLITE_CHANGESETAPPLY_FKNOACTION) && savedFlag==0 ){
230234    assert( db->flags & SQLITE_FkNoAction );
230235    db->flags &= ~((u64)SQLITE_FkNoAction);
230236    db->aDb[0].pSchema->schema_cookie -= 32;
230237  }
230238  return rc;
230239}
230240
230241/*
230242** Apply the changeset passed via pChangeset/nChangeset to the main database
230243** attached to handle "db". Invoke the supplied conflict handler callback
230244** to resolve any conflicts encountered while applying the change.
230245*/
230246SQLITE_API int sqlite3changeset_apply(
230247  sqlite3 *db,                    /* Apply change to "main" db of this handle */
230248  int nChangeset,                 /* Size of changeset in bytes */
230249  void *pChangeset,               /* Changeset blob */
230250  int(*xFilter)(
230251    void *pCtx,                   /* Copy of sixth arg to _apply() */
230252    const char *zTab              /* Table name */
230253  ),
230254  int(*xConflict)(
230255    void *pCtx,                   /* Copy of fifth arg to _apply() */
230256    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
230257    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
230258  ),
230259  void *pCtx                      /* First argument passed to xConflict */
230260){
230261  return sqlite3changeset_apply_v2(
230262      db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0
230263  );
230264}
230265
230266/*
230267** Apply the changeset passed via xInput/pIn to the main database
230268** attached to handle "db". Invoke the supplied conflict handler callback
230269** to resolve any conflicts encountered while applying the change.
230270*/
230271SQLITE_API int sqlite3changeset_apply_v2_strm(
230272  sqlite3 *db,                    /* Apply change to "main" db of this handle */
230273  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
230274  void *pIn,                                          /* First arg for xInput */
230275  int(*xFilter)(
230276    void *pCtx,                   /* Copy of sixth arg to _apply() */
230277    const char *zTab              /* Table name */
230278  ),
230279  int(*xConflict)(
230280    void *pCtx,                   /* Copy of sixth arg to _apply() */
230281    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
230282    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
230283  ),
230284  void *pCtx,                     /* First argument passed to xConflict */
230285  void **ppRebase, int *pnRebase,
230286  int flags
230287){
230288  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
230289  int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
230290  int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse, 1);
230291  if( rc==SQLITE_OK ){
230292    rc = sessionChangesetApply(
230293        db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
230294    );
230295  }
230296  return rc;
230297}
230298SQLITE_API int sqlite3changeset_apply_strm(
230299  sqlite3 *db,                    /* Apply change to "main" db of this handle */
230300  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
230301  void *pIn,                                          /* First arg for xInput */
230302  int(*xFilter)(
230303    void *pCtx,                   /* Copy of sixth arg to _apply() */
230304    const char *zTab              /* Table name */
230305  ),
230306  int(*xConflict)(
230307    void *pCtx,                   /* Copy of sixth arg to _apply() */
230308    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
230309    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
230310  ),
230311  void *pCtx                      /* First argument passed to xConflict */
230312){
230313  return sqlite3changeset_apply_v2_strm(
230314      db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0
230315  );
230316}
230317
230318/*
230319** sqlite3_changegroup handle.
230320*/
230321struct sqlite3_changegroup {
230322  int rc;                         /* Error code */
230323  int bPatch;                     /* True to accumulate patchsets */
230324  SessionTable *pList;            /* List of tables in current patch */
230325  SessionBuffer rec;
230326
230327  sqlite3 *db;                    /* Configured by changegroup_schema() */
230328  char *zDb;                      /* Configured by changegroup_schema() */
230329};
230330
230331/*
230332** This function is called to merge two changes to the same row together as
230333** part of an sqlite3changeset_concat() operation. A new change object is
230334** allocated and a pointer to it stored in *ppNew.
230335*/
230336static int sessionChangeMerge(
230337  SessionTable *pTab,             /* Table structure */
230338  int bRebase,                    /* True for a rebase hash-table */
230339  int bPatchset,                  /* True for patchsets */
230340  SessionChange *pExist,          /* Existing change */
230341  int op2,                        /* Second change operation */
230342  int bIndirect,                  /* True if second change is indirect */
230343  u8 *aRec,                       /* Second change record */
230344  int nRec,                       /* Number of bytes in aRec */
230345  SessionChange **ppNew           /* OUT: Merged change */
230346){
230347  SessionChange *pNew = 0;
230348  int rc = SQLITE_OK;
230349  assert( aRec!=0 );
230350
230351  if( !pExist ){
230352    pNew = (SessionChange *)sqlite3_malloc64(sizeof(SessionChange) + nRec);
230353    if( !pNew ){
230354      return SQLITE_NOMEM;
230355    }
230356    memset(pNew, 0, sizeof(SessionChange));
230357    pNew->op = op2;
230358    pNew->bIndirect = bIndirect;
230359    pNew->aRecord = (u8*)&pNew[1];
230360    if( bIndirect==0 || bRebase==0 ){
230361      pNew->nRecord = nRec;
230362      memcpy(pNew->aRecord, aRec, nRec);
230363    }else{
230364      int i;
230365      u8 *pIn = aRec;
230366      u8 *pOut = pNew->aRecord;
230367      for(i=0; i<pTab->nCol; i++){
230368        int nIn = sessionSerialLen(pIn);
230369        if( *pIn==0 ){
230370          *pOut++ = 0;
230371        }else if( pTab->abPK[i]==0 ){
230372          *pOut++ = 0xFF;
230373        }else{
230374          memcpy(pOut, pIn, nIn);
230375          pOut += nIn;
230376        }
230377        pIn += nIn;
230378      }
230379      pNew->nRecord = pOut - pNew->aRecord;
230380    }
230381  }else if( bRebase ){
230382    if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){
230383      *ppNew = pExist;
230384    }else{
230385      sqlite3_int64 nByte = nRec + pExist->nRecord + sizeof(SessionChange);
230386      pNew = (SessionChange*)sqlite3_malloc64(nByte);
230387      if( pNew==0 ){
230388        rc = SQLITE_NOMEM;
230389      }else{
230390        int i;
230391        u8 *a1 = pExist->aRecord;
230392        u8 *a2 = aRec;
230393        u8 *pOut;
230394
230395        memset(pNew, 0, nByte);
230396        pNew->bIndirect = bIndirect || pExist->bIndirect;
230397        pNew->op = op2;
230398        pOut = pNew->aRecord = (u8*)&pNew[1];
230399
230400        for(i=0; i<pTab->nCol; i++){
230401          int n1 = sessionSerialLen(a1);
230402          int n2 = sessionSerialLen(a2);
230403          if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){
230404            *pOut++ = 0xFF;
230405          }else if( *a2==0 ){
230406            memcpy(pOut, a1, n1);
230407            pOut += n1;
230408          }else{
230409            memcpy(pOut, a2, n2);
230410            pOut += n2;
230411          }
230412          a1 += n1;
230413          a2 += n2;
230414        }
230415        pNew->nRecord = pOut - pNew->aRecord;
230416      }
230417      sqlite3_free(pExist);
230418    }
230419  }else{
230420    int op1 = pExist->op;
230421
230422    /*
230423    **   op1=INSERT, op2=INSERT      ->      Unsupported. Discard op2.
230424    **   op1=INSERT, op2=UPDATE      ->      INSERT.
230425    **   op1=INSERT, op2=DELETE      ->      (none)
230426    **
230427    **   op1=UPDATE, op2=INSERT      ->      Unsupported. Discard op2.
230428    **   op1=UPDATE, op2=UPDATE      ->      UPDATE.
230429    **   op1=UPDATE, op2=DELETE      ->      DELETE.
230430    **
230431    **   op1=DELETE, op2=INSERT      ->      UPDATE.
230432    **   op1=DELETE, op2=UPDATE      ->      Unsupported. Discard op2.
230433    **   op1=DELETE, op2=DELETE      ->      Unsupported. Discard op2.
230434    */
230435    if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
230436     || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
230437     || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
230438     || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
230439    ){
230440      pNew = pExist;
230441    }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
230442      sqlite3_free(pExist);
230443      assert( pNew==0 );
230444    }else{
230445      u8 *aExist = pExist->aRecord;
230446      sqlite3_int64 nByte;
230447      u8 *aCsr;
230448
230449      /* Allocate a new SessionChange object. Ensure that the aRecord[]
230450      ** buffer of the new object is large enough to hold any record that
230451      ** may be generated by combining the input records.  */
230452      nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
230453      pNew = (SessionChange *)sqlite3_malloc64(nByte);
230454      if( !pNew ){
230455        sqlite3_free(pExist);
230456        return SQLITE_NOMEM;
230457      }
230458      memset(pNew, 0, sizeof(SessionChange));
230459      pNew->bIndirect = (bIndirect && pExist->bIndirect);
230460      aCsr = pNew->aRecord = (u8 *)&pNew[1];
230461
230462      if( op1==SQLITE_INSERT ){             /* INSERT + UPDATE */
230463        u8 *a1 = aRec;
230464        assert( op2==SQLITE_UPDATE );
230465        pNew->op = SQLITE_INSERT;
230466        if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
230467        sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
230468      }else if( op1==SQLITE_DELETE ){       /* DELETE + INSERT */
230469        assert( op2==SQLITE_INSERT );
230470        pNew->op = SQLITE_UPDATE;
230471        if( bPatchset ){
230472          memcpy(aCsr, aRec, nRec);
230473          aCsr += nRec;
230474        }else{
230475          if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
230476            sqlite3_free(pNew);
230477            pNew = 0;
230478          }
230479        }
230480      }else if( op2==SQLITE_UPDATE ){       /* UPDATE + UPDATE */
230481        u8 *a1 = aExist;
230482        u8 *a2 = aRec;
230483        assert( op1==SQLITE_UPDATE );
230484        if( bPatchset==0 ){
230485          sessionSkipRecord(&a1, pTab->nCol);
230486          sessionSkipRecord(&a2, pTab->nCol);
230487        }
230488        pNew->op = SQLITE_UPDATE;
230489        if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
230490          sqlite3_free(pNew);
230491          pNew = 0;
230492        }
230493      }else{                                /* UPDATE + DELETE */
230494        assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
230495        pNew->op = SQLITE_DELETE;
230496        if( bPatchset ){
230497          memcpy(aCsr, aRec, nRec);
230498          aCsr += nRec;
230499        }else{
230500          sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
230501        }
230502      }
230503
230504      if( pNew ){
230505        pNew->nRecord = (int)(aCsr - pNew->aRecord);
230506      }
230507      sqlite3_free(pExist);
230508    }
230509  }
230510
230511  *ppNew = pNew;
230512  return rc;
230513}
230514
230515/*
230516** Check if a changeset entry with nCol columns and the PK array passed
230517** as the final argument to this function is compatible with SessionTable
230518** pTab. If so, return 1. Otherwise, if they are incompatible in some way,
230519** return 0.
230520*/
230521static int sessionChangesetCheckCompat(
230522  SessionTable *pTab,
230523  int nCol,
230524  u8 *abPK
230525){
230526  if( pTab->azCol && nCol<pTab->nCol ){
230527    int ii;
230528    for(ii=0; ii<pTab->nCol; ii++){
230529      u8 bPK = (ii < nCol) ? abPK[ii] : 0;
230530      if( pTab->abPK[ii]!=bPK ) return 0;
230531    }
230532    return 1;
230533  }
230534  return (pTab->nCol==nCol && 0==memcmp(abPK, pTab->abPK, nCol));
230535}
230536
230537static int sessionChangesetExtendRecord(
230538  sqlite3_changegroup *pGrp,
230539  SessionTable *pTab,
230540  int nCol,
230541  int op,
230542  const u8 *aRec,
230543  int nRec,
230544  SessionBuffer *pOut
230545){
230546  int rc = SQLITE_OK;
230547  int ii = 0;
230548
230549  assert( pTab->azCol );
230550  assert( nCol<pTab->nCol );
230551
230552  pOut->nBuf = 0;
230553  if( op==SQLITE_INSERT || (op==SQLITE_DELETE && pGrp->bPatch==0) ){
230554    /* Append the missing default column values to the record. */
230555    sessionAppendBlob(pOut, aRec, nRec, &rc);
230556    if( rc==SQLITE_OK && pTab->pDfltStmt==0 ){
230557      rc = sessionPrepareDfltStmt(pGrp->db, pTab, &pTab->pDfltStmt);
230558    }
230559    for(ii=nCol; rc==SQLITE_OK && ii<pTab->nCol; ii++){
230560      int eType = sqlite3_column_type(pTab->pDfltStmt, ii);
230561      sessionAppendByte(pOut, eType, &rc);
230562      switch( eType ){
230563        case SQLITE_FLOAT:
230564        case SQLITE_INTEGER: {
230565          i64 iVal;
230566          if( eType==SQLITE_INTEGER ){
230567            iVal = sqlite3_column_int64(pTab->pDfltStmt, ii);
230568          }else{
230569            double rVal = sqlite3_column_int64(pTab->pDfltStmt, ii);
230570            memcpy(&iVal, &rVal, sizeof(i64));
230571          }
230572          if( SQLITE_OK==sessionBufferGrow(pOut, 8, &rc) ){
230573            sessionPutI64(&pOut->aBuf[pOut->nBuf], iVal);
230574          }
230575          break;
230576        }
230577
230578        case SQLITE_BLOB:
230579        case SQLITE_TEXT: {
230580          int n = sqlite3_column_bytes(pTab->pDfltStmt, ii);
230581          sessionAppendVarint(pOut, n, &rc);
230582          if( eType==SQLITE_TEXT ){
230583            const u8 *z = (const u8*)sqlite3_column_text(pTab->pDfltStmt, ii);
230584            sessionAppendBlob(pOut, z, n, &rc);
230585          }else{
230586            const u8 *z = (const u8*)sqlite3_column_blob(pTab->pDfltStmt, ii);
230587            sessionAppendBlob(pOut, z, n, &rc);
230588          }
230589          break;
230590        }
230591
230592        default:
230593          assert( eType==SQLITE_NULL );
230594          break;
230595      }
230596    }
230597  }else if( op==SQLITE_UPDATE ){
230598    /* Append missing "undefined" entries to the old.* record. And, if this
230599    ** is an UPDATE, to the new.* record as well.  */
230600    int iOff = 0;
230601    if( pGrp->bPatch==0 ){
230602      for(ii=0; ii<nCol; ii++){
230603        iOff += sessionSerialLen(&aRec[iOff]);
230604      }
230605      sessionAppendBlob(pOut, aRec, iOff, &rc);
230606      for(ii=0; ii<(pTab->nCol-nCol); ii++){
230607        sessionAppendByte(pOut, 0x00, &rc);
230608      }
230609    }
230610
230611    sessionAppendBlob(pOut, &aRec[iOff], nRec-iOff, &rc);
230612    for(ii=0; ii<(pTab->nCol-nCol); ii++){
230613      sessionAppendByte(pOut, 0x00, &rc);
230614    }
230615  }else{
230616    assert( op==SQLITE_DELETE && pGrp->bPatch );
230617    sessionAppendBlob(pOut, aRec, nRec, &rc);
230618  }
230619
230620  return rc;
230621}
230622
230623/*
230624** Locate or create a SessionTable object that may be used to add the
230625** change currently pointed to by iterator pIter to changegroup pGrp.
230626** If successful, set output variable (*ppTab) to point to the table
230627** object and return SQLITE_OK. Otherwise, if some error occurs, return
230628** an SQLite error code and leave (*ppTab) set to NULL.
230629*/
230630static int sessionChangesetFindTable(
230631  sqlite3_changegroup *pGrp,
230632  const char *zTab,
230633  sqlite3_changeset_iter *pIter,
230634  SessionTable **ppTab
230635){
230636  int rc = SQLITE_OK;
230637  SessionTable *pTab = 0;
230638  int nTab = (int)strlen(zTab);
230639  u8 *abPK = 0;
230640  int nCol = 0;
230641
230642  *ppTab = 0;
230643  sqlite3changeset_pk(pIter, &abPK, &nCol);
230644
230645  /* Search the list for an existing table */
230646  for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
230647    if( 0==sqlite3_strnicmp(pTab->zName, zTab, nTab+1) ) break;
230648  }
230649
230650  /* If one was not found above, create a new table now */
230651  if( !pTab ){
230652    SessionTable **ppNew;
230653
230654    pTab = sqlite3_malloc64(sizeof(SessionTable) + nCol + nTab+1);
230655    if( !pTab ){
230656      return SQLITE_NOMEM;
230657    }
230658    memset(pTab, 0, sizeof(SessionTable));
230659    pTab->nCol = nCol;
230660    pTab->abPK = (u8*)&pTab[1];
230661    memcpy(pTab->abPK, abPK, nCol);
230662    pTab->zName = (char*)&pTab->abPK[nCol];
230663    memcpy(pTab->zName, zTab, nTab+1);
230664
230665    if( pGrp->db ){
230666      pTab->nCol = 0;
230667      rc = sessionInitTable(0, pTab, pGrp->db, pGrp->zDb);
230668      if( rc ){
230669        assert( pTab->azCol==0 );
230670        sqlite3_free(pTab);
230671        return rc;
230672      }
230673    }
230674
230675    /* The new object must be linked on to the end of the list, not
230676    ** simply added to the start of it. This is to ensure that the
230677    ** tables within the output of sqlite3changegroup_output() are in
230678    ** the right order.  */
230679    for(ppNew=&pGrp->pList; *ppNew; ppNew=&(*ppNew)->pNext);
230680    *ppNew = pTab;
230681  }
230682
230683  /* Check that the table is compatible. */
230684  if( !sessionChangesetCheckCompat(pTab, nCol, abPK) ){
230685    rc = SQLITE_SCHEMA;
230686  }
230687
230688  *ppTab = pTab;
230689  return rc;
230690}
230691
230692/*
230693** Add the change currently indicated by iterator pIter to the hash table
230694** belonging to changegroup pGrp.
230695*/
230696static int sessionOneChangeToHash(
230697  sqlite3_changegroup *pGrp,
230698  sqlite3_changeset_iter *pIter,
230699  int bRebase
230700){
230701  int rc = SQLITE_OK;
230702  int nCol = 0;
230703  int op = 0;
230704  int iHash = 0;
230705  int bIndirect = 0;
230706  SessionChange *pChange = 0;
230707  SessionChange *pExist = 0;
230708  SessionChange **pp = 0;
230709  SessionTable *pTab = 0;
230710  u8 *aRec = &pIter->in.aData[pIter->in.iCurrent + 2];
230711  int nRec = (pIter->in.iNext - pIter->in.iCurrent) - 2;
230712
230713  /* Ensure that only changesets, or only patchsets, but not a mixture
230714  ** of both, are being combined. It is an error to try to combine a
230715  ** changeset and a patchset.  */
230716  if( pGrp->pList==0 ){
230717    pGrp->bPatch = pIter->bPatchset;
230718  }else if( pIter->bPatchset!=pGrp->bPatch ){
230719    rc = SQLITE_ERROR;
230720  }
230721
230722  if( rc==SQLITE_OK ){
230723    const char *zTab = 0;
230724    sqlite3changeset_op(pIter, &zTab, &nCol, &op, &bIndirect);
230725    rc = sessionChangesetFindTable(pGrp, zTab, pIter, &pTab);
230726  }
230727
230728  if( rc==SQLITE_OK && nCol<pTab->nCol ){
230729    SessionBuffer *pBuf = &pGrp->rec;
230730    rc = sessionChangesetExtendRecord(pGrp, pTab, nCol, op, aRec, nRec, pBuf);
230731    aRec = pBuf->aBuf;
230732    nRec = pBuf->nBuf;
230733    assert( pGrp->db );
230734  }
230735
230736  if( rc==SQLITE_OK && sessionGrowHash(0, pIter->bPatchset, pTab) ){
230737    rc = SQLITE_NOMEM;
230738  }
230739
230740  if( rc==SQLITE_OK ){
230741    /* Search for existing entry. If found, remove it from the hash table.
230742    ** Code below may link it back in.  */
230743    iHash = sessionChangeHash(
230744        pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
230745    );
230746    for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
230747      int bPkOnly1 = 0;
230748      int bPkOnly2 = 0;
230749      if( pIter->bPatchset ){
230750        bPkOnly1 = (*pp)->op==SQLITE_DELETE;
230751        bPkOnly2 = op==SQLITE_DELETE;
230752      }
230753      if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
230754        pExist = *pp;
230755        *pp = (*pp)->pNext;
230756        pTab->nEntry--;
230757        break;
230758      }
230759    }
230760  }
230761
230762  if( rc==SQLITE_OK ){
230763    rc = sessionChangeMerge(pTab, bRebase,
230764        pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
230765    );
230766  }
230767  if( rc==SQLITE_OK && pChange ){
230768    pChange->pNext = pTab->apChange[iHash];
230769    pTab->apChange[iHash] = pChange;
230770    pTab->nEntry++;
230771  }
230772
230773  if( rc==SQLITE_OK ) rc = pIter->rc;
230774  return rc;
230775}
230776
230777/*
230778** Add all changes in the changeset traversed by the iterator passed as
230779** the first argument to the changegroup hash tables.
230780*/
230781static int sessionChangesetToHash(
230782  sqlite3_changeset_iter *pIter,   /* Iterator to read from */
230783  sqlite3_changegroup *pGrp,       /* Changegroup object to add changeset to */
230784  int bRebase                      /* True if hash table is for rebasing */
230785){
230786  u8 *aRec;
230787  int nRec;
230788  int rc = SQLITE_OK;
230789
230790  while( SQLITE_ROW==(sessionChangesetNext(pIter, &aRec, &nRec, 0)) ){
230791    rc = sessionOneChangeToHash(pGrp, pIter, bRebase);
230792    if( rc!=SQLITE_OK ) break;
230793  }
230794
230795  if( rc==SQLITE_OK ) rc = pIter->rc;
230796  return rc;
230797}
230798
230799/*
230800** Serialize a changeset (or patchset) based on all changesets (or patchsets)
230801** added to the changegroup object passed as the first argument.
230802**
230803** If xOutput is not NULL, then the changeset/patchset is returned to the
230804** user via one or more calls to xOutput, as with the other streaming
230805** interfaces.
230806**
230807** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
230808** buffer containing the output changeset before this function returns. In
230809** this case (*pnOut) is set to the size of the output buffer in bytes. It
230810** is the responsibility of the caller to free the output buffer using
230811** sqlite3_free() when it is no longer required.
230812**
230813** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
230814** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
230815** are both set to 0 before returning.
230816*/
230817static int sessionChangegroupOutput(
230818  sqlite3_changegroup *pGrp,
230819  int (*xOutput)(void *pOut, const void *pData, int nData),
230820  void *pOut,
230821  int *pnOut,
230822  void **ppOut
230823){
230824  int rc = SQLITE_OK;
230825  SessionBuffer buf = {0, 0, 0};
230826  SessionTable *pTab;
230827  assert( xOutput==0 || (ppOut==0 && pnOut==0) );
230828
230829  /* Create the serialized output changeset based on the contents of the
230830  ** hash tables attached to the SessionTable objects in list p->pList.
230831  */
230832  for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
230833    int i;
230834    if( pTab->nEntry==0 ) continue;
230835
230836    sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
230837    for(i=0; i<pTab->nChange; i++){
230838      SessionChange *p;
230839      for(p=pTab->apChange[i]; p; p=p->pNext){
230840        sessionAppendByte(&buf, p->op, &rc);
230841        sessionAppendByte(&buf, p->bIndirect, &rc);
230842        sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
230843        if( rc==SQLITE_OK && xOutput && buf.nBuf>=sessions_strm_chunk_size ){
230844          rc = xOutput(pOut, buf.aBuf, buf.nBuf);
230845          buf.nBuf = 0;
230846        }
230847      }
230848    }
230849  }
230850
230851  if( rc==SQLITE_OK ){
230852    if( xOutput ){
230853      if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
230854    }else if( ppOut ){
230855      *ppOut = buf.aBuf;
230856      if( pnOut ) *pnOut = buf.nBuf;
230857      buf.aBuf = 0;
230858    }
230859  }
230860  sqlite3_free(buf.aBuf);
230861
230862  return rc;
230863}
230864
230865/*
230866** Allocate a new, empty, sqlite3_changegroup.
230867*/
230868SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
230869  int rc = SQLITE_OK;             /* Return code */
230870  sqlite3_changegroup *p;         /* New object */
230871  p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
230872  if( p==0 ){
230873    rc = SQLITE_NOMEM;
230874  }else{
230875    memset(p, 0, sizeof(sqlite3_changegroup));
230876  }
230877  *pp = p;
230878  return rc;
230879}
230880
230881/*
230882** Provide a database schema to the changegroup object.
230883*/
230884SQLITE_API int sqlite3changegroup_schema(
230885  sqlite3_changegroup *pGrp,
230886  sqlite3 *db,
230887  const char *zDb
230888){
230889  int rc = SQLITE_OK;
230890
230891  if( pGrp->pList || pGrp->db ){
230892    /* Cannot add a schema after one or more calls to sqlite3changegroup_add(),
230893    ** or after sqlite3changegroup_schema() has already been called. */
230894    rc = SQLITE_MISUSE;
230895  }else{
230896    pGrp->zDb = sqlite3_mprintf("%s", zDb);
230897    if( pGrp->zDb==0 ){
230898      rc = SQLITE_NOMEM;
230899    }else{
230900      pGrp->db = db;
230901    }
230902  }
230903  return rc;
230904}
230905
230906/*
230907** Add the changeset currently stored in buffer pData, size nData bytes,
230908** to changeset-group p.
230909*/
230910SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
230911  sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
230912  int rc;                         /* Return code */
230913
230914  rc = sqlite3changeset_start(&pIter, nData, pData);
230915  if( rc==SQLITE_OK ){
230916    rc = sessionChangesetToHash(pIter, pGrp, 0);
230917  }
230918  sqlite3changeset_finalize(pIter);
230919  return rc;
230920}
230921
230922/*
230923** Add a single change to a changeset-group.
230924*/
230925SQLITE_API int sqlite3changegroup_add_change(
230926  sqlite3_changegroup *pGrp,
230927  sqlite3_changeset_iter *pIter
230928){
230929  if( pIter->in.iCurrent==pIter->in.iNext
230930   || pIter->rc!=SQLITE_OK
230931   || pIter->bInvert
230932  ){
230933    /* Iterator does not point to any valid entry or is an INVERT iterator. */
230934    return SQLITE_ERROR;
230935  }
230936  return sessionOneChangeToHash(pGrp, pIter, 0);
230937}
230938
230939/*
230940** Obtain a buffer containing a changeset representing the concatenation
230941** of all changesets added to the group so far.
230942*/
230943SQLITE_API int sqlite3changegroup_output(
230944    sqlite3_changegroup *pGrp,
230945    int *pnData,
230946    void **ppData
230947){
230948  return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
230949}
230950
230951/*
230952** Streaming versions of changegroup_add().
230953*/
230954SQLITE_API int sqlite3changegroup_add_strm(
230955  sqlite3_changegroup *pGrp,
230956  int (*xInput)(void *pIn, void *pData, int *pnData),
230957  void *pIn
230958){
230959  sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
230960  int rc;                         /* Return code */
230961
230962  rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
230963  if( rc==SQLITE_OK ){
230964    rc = sessionChangesetToHash(pIter, pGrp, 0);
230965  }
230966  sqlite3changeset_finalize(pIter);
230967  return rc;
230968}
230969
230970/*
230971** Streaming versions of changegroup_output().
230972*/
230973SQLITE_API int sqlite3changegroup_output_strm(
230974  sqlite3_changegroup *pGrp,
230975  int (*xOutput)(void *pOut, const void *pData, int nData),
230976  void *pOut
230977){
230978  return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
230979}
230980
230981/*
230982** Delete a changegroup object.
230983*/
230984SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
230985  if( pGrp ){
230986    sqlite3_free(pGrp->zDb);
230987    sessionDeleteTable(0, pGrp->pList);
230988    sqlite3_free(pGrp->rec.aBuf);
230989    sqlite3_free(pGrp);
230990  }
230991}
230992
230993/*
230994** Combine two changesets together.
230995*/
230996SQLITE_API int sqlite3changeset_concat(
230997  int nLeft,                      /* Number of bytes in lhs input */
230998  void *pLeft,                    /* Lhs input changeset */
230999  int nRight                      /* Number of bytes in rhs input */,
231000  void *pRight,                   /* Rhs input changeset */
231001  int *pnOut,                     /* OUT: Number of bytes in output changeset */
231002  void **ppOut                    /* OUT: changeset (left <concat> right) */
231003){
231004  sqlite3_changegroup *pGrp;
231005  int rc;
231006
231007  rc = sqlite3changegroup_new(&pGrp);
231008  if( rc==SQLITE_OK ){
231009    rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
231010  }
231011  if( rc==SQLITE_OK ){
231012    rc = sqlite3changegroup_add(pGrp, nRight, pRight);
231013  }
231014  if( rc==SQLITE_OK ){
231015    rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
231016  }
231017  sqlite3changegroup_delete(pGrp);
231018
231019  return rc;
231020}
231021
231022/*
231023** Streaming version of sqlite3changeset_concat().
231024*/
231025SQLITE_API int sqlite3changeset_concat_strm(
231026  int (*xInputA)(void *pIn, void *pData, int *pnData),
231027  void *pInA,
231028  int (*xInputB)(void *pIn, void *pData, int *pnData),
231029  void *pInB,
231030  int (*xOutput)(void *pOut, const void *pData, int nData),
231031  void *pOut
231032){
231033  sqlite3_changegroup *pGrp;
231034  int rc;
231035
231036  rc = sqlite3changegroup_new(&pGrp);
231037  if( rc==SQLITE_OK ){
231038    rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
231039  }
231040  if( rc==SQLITE_OK ){
231041    rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
231042  }
231043  if( rc==SQLITE_OK ){
231044    rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
231045  }
231046  sqlite3changegroup_delete(pGrp);
231047
231048  return rc;
231049}
231050
231051/*
231052** Changeset rebaser handle.
231053*/
231054struct sqlite3_rebaser {
231055  sqlite3_changegroup grp;        /* Hash table */
231056};
231057
231058/*
231059** Buffers a1 and a2 must both contain a sessions module record nCol
231060** fields in size. This function appends an nCol sessions module
231061** record to buffer pBuf that is a copy of a1, except that for
231062** each field that is undefined in a1[], swap in the field from a2[].
231063*/
231064static void sessionAppendRecordMerge(
231065  SessionBuffer *pBuf,            /* Buffer to append to */
231066  int nCol,                       /* Number of columns in each record */
231067  u8 *a1, int n1,                 /* Record 1 */
231068  u8 *a2, int n2,                 /* Record 2 */
231069  int *pRc                        /* IN/OUT: error code */
231070){
231071  sessionBufferGrow(pBuf, n1+n2, pRc);
231072  if( *pRc==SQLITE_OK ){
231073    int i;
231074    u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
231075    for(i=0; i<nCol; i++){
231076      int nn1 = sessionSerialLen(a1);
231077      int nn2 = sessionSerialLen(a2);
231078      if( *a1==0 || *a1==0xFF ){
231079        memcpy(pOut, a2, nn2);
231080        pOut += nn2;
231081      }else{
231082        memcpy(pOut, a1, nn1);
231083        pOut += nn1;
231084      }
231085      a1 += nn1;
231086      a2 += nn2;
231087    }
231088
231089    pBuf->nBuf = pOut-pBuf->aBuf;
231090    assert( pBuf->nBuf<=pBuf->nAlloc );
231091  }
231092}
231093
231094/*
231095** This function is called when rebasing a local UPDATE change against one
231096** or more remote UPDATE changes. The aRec/nRec buffer contains the current
231097** old.* and new.* records for the change. The rebase buffer (a single
231098** record) is in aChange/nChange. The rebased change is appended to buffer
231099** pBuf.
231100**
231101** Rebasing the UPDATE involves:
231102**
231103**   * Removing any changes to fields for which the corresponding field
231104**     in the rebase buffer is set to "replaced" (type 0xFF). If this
231105**     means the UPDATE change updates no fields, nothing is appended
231106**     to the output buffer.
231107**
231108**   * For each field modified by the local change for which the
231109**     corresponding field in the rebase buffer is not "undefined" (0x00)
231110**     or "replaced" (0xFF), the old.* value is replaced by the value
231111**     in the rebase buffer.
231112*/
231113static void sessionAppendPartialUpdate(
231114  SessionBuffer *pBuf,            /* Append record here */
231115  sqlite3_changeset_iter *pIter,  /* Iterator pointed at local change */
231116  u8 *aRec, int nRec,             /* Local change */
231117  u8 *aChange, int nChange,       /* Record to rebase against */
231118  int *pRc                        /* IN/OUT: Return Code */
231119){
231120  sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);
231121  if( *pRc==SQLITE_OK ){
231122    int bData = 0;
231123    u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
231124    int i;
231125    u8 *a1 = aRec;
231126    u8 *a2 = aChange;
231127
231128    *pOut++ = SQLITE_UPDATE;
231129    *pOut++ = pIter->bIndirect;
231130    for(i=0; i<pIter->nCol; i++){
231131      int n1 = sessionSerialLen(a1);
231132      int n2 = sessionSerialLen(a2);
231133      if( pIter->abPK[i] || a2[0]==0 ){
231134        if( !pIter->abPK[i] && a1[0] ) bData = 1;
231135        memcpy(pOut, a1, n1);
231136        pOut += n1;
231137      }else if( a2[0]!=0xFF && a1[0] ){
231138        bData = 1;
231139        memcpy(pOut, a2, n2);
231140        pOut += n2;
231141      }else{
231142        *pOut++ = '\0';
231143      }
231144      a1 += n1;
231145      a2 += n2;
231146    }
231147    if( bData ){
231148      a2 = aChange;
231149      for(i=0; i<pIter->nCol; i++){
231150        int n1 = sessionSerialLen(a1);
231151        int n2 = sessionSerialLen(a2);
231152        if( pIter->abPK[i] || a2[0]!=0xFF ){
231153          memcpy(pOut, a1, n1);
231154          pOut += n1;
231155        }else{
231156          *pOut++ = '\0';
231157        }
231158        a1 += n1;
231159        a2 += n2;
231160      }
231161      pBuf->nBuf = (pOut - pBuf->aBuf);
231162    }
231163  }
231164}
231165
231166/*
231167** pIter is configured to iterate through a changeset. This function rebases
231168** that changeset according to the current configuration of the rebaser
231169** object passed as the first argument. If no error occurs and argument xOutput
231170** is not NULL, then the changeset is returned to the caller by invoking
231171** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,
231172** then (*ppOut) is set to point to a buffer containing the rebased changeset
231173** before this function returns. In this case (*pnOut) is set to the size of
231174** the buffer in bytes.  It is the responsibility of the caller to eventually
231175** free the (*ppOut) buffer using sqlite3_free().
231176**
231177** If an error occurs, an SQLite error code is returned. If ppOut and
231178** pnOut are not NULL, then the two output parameters are set to 0 before
231179** returning.
231180*/
231181static int sessionRebase(
231182  sqlite3_rebaser *p,             /* Rebaser hash table */
231183  sqlite3_changeset_iter *pIter,  /* Input data */
231184  int (*xOutput)(void *pOut, const void *pData, int nData),
231185  void *pOut,                     /* Context for xOutput callback */
231186  int *pnOut,                     /* OUT: Number of bytes in output changeset */
231187  void **ppOut                    /* OUT: Inverse of pChangeset */
231188){
231189  int rc = SQLITE_OK;
231190  u8 *aRec = 0;
231191  int nRec = 0;
231192  int bNew = 0;
231193  SessionTable *pTab = 0;
231194  SessionBuffer sOut = {0,0,0};
231195
231196  while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){
231197    SessionChange *pChange = 0;
231198    int bDone = 0;
231199
231200    if( bNew ){
231201      const char *zTab = pIter->zTab;
231202      for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){
231203        if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break;
231204      }
231205      bNew = 0;
231206
231207      /* A patchset may not be rebased */
231208      if( pIter->bPatchset ){
231209        rc = SQLITE_ERROR;
231210      }
231211
231212      /* Append a table header to the output for this new table */
231213      sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc);
231214      sessionAppendVarint(&sOut, pIter->nCol, &rc);
231215      sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc);
231216      sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc);
231217    }
231218
231219    if( pTab && rc==SQLITE_OK ){
231220      int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange);
231221
231222      for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){
231223        if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){
231224          break;
231225        }
231226      }
231227    }
231228
231229    if( pChange ){
231230      assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT );
231231      switch( pIter->op ){
231232        case SQLITE_INSERT:
231233          if( pChange->op==SQLITE_INSERT ){
231234            bDone = 1;
231235            if( pChange->bIndirect==0 ){
231236              sessionAppendByte(&sOut, SQLITE_UPDATE, &rc);
231237              sessionAppendByte(&sOut, pIter->bIndirect, &rc);
231238              sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc);
231239              sessionAppendBlob(&sOut, aRec, nRec, &rc);
231240            }
231241          }
231242          break;
231243
231244        case SQLITE_UPDATE:
231245          bDone = 1;
231246          if( pChange->op==SQLITE_DELETE ){
231247            if( pChange->bIndirect==0 ){
231248              u8 *pCsr = aRec;
231249              sessionSkipRecord(&pCsr, pIter->nCol);
231250              sessionAppendByte(&sOut, SQLITE_INSERT, &rc);
231251              sessionAppendByte(&sOut, pIter->bIndirect, &rc);
231252              sessionAppendRecordMerge(&sOut, pIter->nCol,
231253                  pCsr, nRec-(pCsr-aRec),
231254                  pChange->aRecord, pChange->nRecord, &rc
231255              );
231256            }
231257          }else{
231258            sessionAppendPartialUpdate(&sOut, pIter,
231259                aRec, nRec, pChange->aRecord, pChange->nRecord, &rc
231260            );
231261          }
231262          break;
231263
231264        default:
231265          assert( pIter->op==SQLITE_DELETE );
231266          bDone = 1;
231267          if( pChange->op==SQLITE_INSERT ){
231268            sessionAppendByte(&sOut, SQLITE_DELETE, &rc);
231269            sessionAppendByte(&sOut, pIter->bIndirect, &rc);
231270            sessionAppendRecordMerge(&sOut, pIter->nCol,
231271                pChange->aRecord, pChange->nRecord, aRec, nRec, &rc
231272            );
231273          }
231274          break;
231275      }
231276    }
231277
231278    if( bDone==0 ){
231279      sessionAppendByte(&sOut, pIter->op, &rc);
231280      sessionAppendByte(&sOut, pIter->bIndirect, &rc);
231281      sessionAppendBlob(&sOut, aRec, nRec, &rc);
231282    }
231283    if( rc==SQLITE_OK && xOutput && sOut.nBuf>sessions_strm_chunk_size ){
231284      rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
231285      sOut.nBuf = 0;
231286    }
231287    if( rc ) break;
231288  }
231289
231290  if( rc!=SQLITE_OK ){
231291    sqlite3_free(sOut.aBuf);
231292    memset(&sOut, 0, sizeof(sOut));
231293  }
231294
231295  if( rc==SQLITE_OK ){
231296    if( xOutput ){
231297      if( sOut.nBuf>0 ){
231298        rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
231299      }
231300    }else if( ppOut ){
231301      *ppOut = (void*)sOut.aBuf;
231302      *pnOut = sOut.nBuf;
231303      sOut.aBuf = 0;
231304    }
231305  }
231306  sqlite3_free(sOut.aBuf);
231307  return rc;
231308}
231309
231310/*
231311** Create a new rebaser object.
231312*/
231313SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew){
231314  int rc = SQLITE_OK;
231315  sqlite3_rebaser *pNew;
231316
231317  pNew = sqlite3_malloc(sizeof(sqlite3_rebaser));
231318  if( pNew==0 ){
231319    rc = SQLITE_NOMEM;
231320  }else{
231321    memset(pNew, 0, sizeof(sqlite3_rebaser));
231322  }
231323  *ppNew = pNew;
231324  return rc;
231325}
231326
231327/*
231328** Call this one or more times to configure a rebaser.
231329*/
231330SQLITE_API int sqlite3rebaser_configure(
231331  sqlite3_rebaser *p,
231332  int nRebase, const void *pRebase
231333){
231334  sqlite3_changeset_iter *pIter = 0;   /* Iterator opened on pData/nData */
231335  int rc;                              /* Return code */
231336  rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
231337  if( rc==SQLITE_OK ){
231338    rc = sessionChangesetToHash(pIter, &p->grp, 1);
231339  }
231340  sqlite3changeset_finalize(pIter);
231341  return rc;
231342}
231343
231344/*
231345** Rebase a changeset according to current rebaser configuration
231346*/
231347SQLITE_API int sqlite3rebaser_rebase(
231348  sqlite3_rebaser *p,
231349  int nIn, const void *pIn,
231350  int *pnOut, void **ppOut
231351){
231352  sqlite3_changeset_iter *pIter = 0;   /* Iterator to skip through input */
231353  int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn);
231354
231355  if( rc==SQLITE_OK ){
231356    rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut);
231357    sqlite3changeset_finalize(pIter);
231358  }
231359
231360  return rc;
231361}
231362
231363/*
231364** Rebase a changeset according to current rebaser configuration
231365*/
231366SQLITE_API int sqlite3rebaser_rebase_strm(
231367  sqlite3_rebaser *p,
231368  int (*xInput)(void *pIn, void *pData, int *pnData),
231369  void *pIn,
231370  int (*xOutput)(void *pOut, const void *pData, int nData),
231371  void *pOut
231372){
231373  sqlite3_changeset_iter *pIter = 0;   /* Iterator to skip through input */
231374  int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
231375
231376  if( rc==SQLITE_OK ){
231377    rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0);
231378    sqlite3changeset_finalize(pIter);
231379  }
231380
231381  return rc;
231382}
231383
231384/*
231385** Destroy a rebaser object
231386*/
231387SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p){
231388  if( p ){
231389    sessionDeleteTable(0, p->grp.pList);
231390    sqlite3_free(p->grp.rec.aBuf);
231391    sqlite3_free(p);
231392  }
231393}
231394
231395/*
231396** Global configuration
231397*/
231398SQLITE_API int sqlite3session_config(int op, void *pArg){
231399  int rc = SQLITE_OK;
231400  switch( op ){
231401    case SQLITE_SESSION_CONFIG_STRMSIZE: {
231402      int *pInt = (int*)pArg;
231403      if( *pInt>0 ){
231404        sessions_strm_chunk_size = *pInt;
231405      }
231406      *pInt = sessions_strm_chunk_size;
231407      break;
231408    }
231409    default:
231410      rc = SQLITE_MISUSE;
231411      break;
231412  }
231413  return rc;
231414}
231415
231416#endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
231417
231418/************** End of sqlite3session.c **************************************/
231419/************** Begin file fts5.c ********************************************/
231420
231421
231422#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
231423
231424#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
231425# define NDEBUG 1
231426#endif
231427#if defined(NDEBUG) && defined(SQLITE_DEBUG)
231428# undef NDEBUG
231429#endif
231430
231431/*
231432** 2014 May 31
231433**
231434** The author disclaims copyright to this source code.  In place of
231435** a legal notice, here is a blessing:
231436**
231437**    May you do good and not evil.
231438**    May you find forgiveness for yourself and forgive others.
231439**    May you share freely, never taking more than you give.
231440**
231441******************************************************************************
231442**
231443** Interfaces to extend FTS5. Using the interfaces defined in this file,
231444** FTS5 may be extended with:
231445**
231446**     * custom tokenizers, and
231447**     * custom auxiliary functions.
231448*/
231449
231450
231451#ifndef _FTS5_H
231452#define _FTS5_H
231453
231454/* #include "sqlite3.h" */
231455
231456#if 0
231457extern "C" {
231458#endif
231459
231460/*************************************************************************
231461** CUSTOM AUXILIARY FUNCTIONS
231462**
231463** Virtual table implementations may overload SQL functions by implementing
231464** the sqlite3_module.xFindFunction() method.
231465*/
231466
231467typedef struct Fts5ExtensionApi Fts5ExtensionApi;
231468typedef struct Fts5Context Fts5Context;
231469typedef struct Fts5PhraseIter Fts5PhraseIter;
231470
231471typedef void (*fts5_extension_function)(
231472  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
231473  Fts5Context *pFts,              /* First arg to pass to pApi functions */
231474  sqlite3_context *pCtx,          /* Context for returning result/error */
231475  int nVal,                       /* Number of values in apVal[] array */
231476  sqlite3_value **apVal           /* Array of trailing arguments */
231477);
231478
231479struct Fts5PhraseIter {
231480  const unsigned char *a;
231481  const unsigned char *b;
231482};
231483
231484/*
231485** EXTENSION API FUNCTIONS
231486**
231487** xUserData(pFts):
231488**   Return a copy of the pUserData pointer passed to the xCreateFunction()
231489**   API when the extension function was registered.
231490**
231491** xColumnTotalSize(pFts, iCol, pnToken):
231492**   If parameter iCol is less than zero, set output variable *pnToken
231493**   to the total number of tokens in the FTS5 table. Or, if iCol is
231494**   non-negative but less than the number of columns in the table, return
231495**   the total number of tokens in column iCol, considering all rows in
231496**   the FTS5 table.
231497**
231498**   If parameter iCol is greater than or equal to the number of columns
231499**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
231500**   an OOM condition or IO error), an appropriate SQLite error code is
231501**   returned.
231502**
231503** xColumnCount(pFts):
231504**   Return the number of columns in the table.
231505**
231506** xColumnSize(pFts, iCol, pnToken):
231507**   If parameter iCol is less than zero, set output variable *pnToken
231508**   to the total number of tokens in the current row. Or, if iCol is
231509**   non-negative but less than the number of columns in the table, set
231510**   *pnToken to the number of tokens in column iCol of the current row.
231511**
231512**   If parameter iCol is greater than or equal to the number of columns
231513**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
231514**   an OOM condition or IO error), an appropriate SQLite error code is
231515**   returned.
231516**
231517**   This function may be quite inefficient if used with an FTS5 table
231518**   created with the "columnsize=0" option.
231519**
231520** xColumnText:
231521**   If parameter iCol is less than zero, or greater than or equal to the
231522**   number of columns in the table, SQLITE_RANGE is returned.
231523**
231524**   Otherwise, this function attempts to retrieve the text of column iCol of
231525**   the current document. If successful, (*pz) is set to point to a buffer
231526**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
231527**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
231528**   if an error occurs, an SQLite error code is returned and the final values
231529**   of (*pz) and (*pn) are undefined.
231530**
231531** xPhraseCount:
231532**   Returns the number of phrases in the current query expression.
231533**
231534** xPhraseSize:
231535**   If parameter iCol is less than zero, or greater than or equal to the
231536**   number of phrases in the current query, as returned by xPhraseCount,
231537**   0 is returned. Otherwise, this function returns the number of tokens in
231538**   phrase iPhrase of the query. Phrases are numbered starting from zero.
231539**
231540** xInstCount:
231541**   Set *pnInst to the total number of occurrences of all phrases within
231542**   the query within the current row. Return SQLITE_OK if successful, or
231543**   an error code (i.e. SQLITE_NOMEM) if an error occurs.
231544**
231545**   This API can be quite slow if used with an FTS5 table created with the
231546**   "detail=none" or "detail=column" option. If the FTS5 table is created
231547**   with either "detail=none" or "detail=column" and "content=" option
231548**   (i.e. if it is a contentless table), then this API always returns 0.
231549**
231550** xInst:
231551**   Query for the details of phrase match iIdx within the current row.
231552**   Phrase matches are numbered starting from zero, so the iIdx argument
231553**   should be greater than or equal to zero and smaller than the value
231554**   output by xInstCount(). If iIdx is less than zero or greater than
231555**   or equal to the value returned by xInstCount(), SQLITE_RANGE is returned.
231556**
231557**   Otherwise, output parameter *piPhrase is set to the phrase number, *piCol
231558**   to the column in which it occurs and *piOff the token offset of the
231559**   first token of the phrase. SQLITE_OK is returned if successful, or an
231560**   error code (i.e. SQLITE_NOMEM) if an error occurs.
231561**
231562**   This API can be quite slow if used with an FTS5 table created with the
231563**   "detail=none" or "detail=column" option.
231564**
231565** xRowid:
231566**   Returns the rowid of the current row.
231567**
231568** xTokenize:
231569**   Tokenize text using the tokenizer belonging to the FTS5 table.
231570**
231571** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
231572**   This API function is used to query the FTS table for phrase iPhrase
231573**   of the current query. Specifically, a query equivalent to:
231574**
231575**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
231576**
231577**   with $p set to a phrase equivalent to the phrase iPhrase of the
231578**   current query is executed. Any column filter that applies to
231579**   phrase iPhrase of the current query is included in $p. For each
231580**   row visited, the callback function passed as the fourth argument
231581**   is invoked. The context and API objects passed to the callback
231582**   function may be used to access the properties of each matched row.
231583**   Invoking Api.xUserData() returns a copy of the pointer passed as
231584**   the third argument to pUserData.
231585**
231586**   If parameter iPhrase is less than zero, or greater than or equal to
231587**   the number of phrases in the query, as returned by xPhraseCount(),
231588**   this function returns SQLITE_RANGE.
231589**
231590**   If the callback function returns any value other than SQLITE_OK, the
231591**   query is abandoned and the xQueryPhrase function returns immediately.
231592**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
231593**   Otherwise, the error code is propagated upwards.
231594**
231595**   If the query runs to completion without incident, SQLITE_OK is returned.
231596**   Or, if some error occurs before the query completes or is aborted by
231597**   the callback, an SQLite error code is returned.
231598**
231599**
231600** xSetAuxdata(pFts5, pAux, xDelete)
231601**
231602**   Save the pointer passed as the second argument as the extension function's
231603**   "auxiliary data". The pointer may then be retrieved by the current or any
231604**   future invocation of the same fts5 extension function made as part of
231605**   the same MATCH query using the xGetAuxdata() API.
231606**
231607**   Each extension function is allocated a single auxiliary data slot for
231608**   each FTS query (MATCH expression). If the extension function is invoked
231609**   more than once for a single FTS query, then all invocations share a
231610**   single auxiliary data context.
231611**
231612**   If there is already an auxiliary data pointer when this function is
231613**   invoked, then it is replaced by the new pointer. If an xDelete callback
231614**   was specified along with the original pointer, it is invoked at this
231615**   point.
231616**
231617**   The xDelete callback, if one is specified, is also invoked on the
231618**   auxiliary data pointer after the FTS5 query has finished.
231619**
231620**   If an error (e.g. an OOM condition) occurs within this function,
231621**   the auxiliary data is set to NULL and an error code returned. If the
231622**   xDelete parameter was not NULL, it is invoked on the auxiliary data
231623**   pointer before returning.
231624**
231625**
231626** xGetAuxdata(pFts5, bClear)
231627**
231628**   Returns the current auxiliary data pointer for the fts5 extension
231629**   function. See the xSetAuxdata() method for details.
231630**
231631**   If the bClear argument is non-zero, then the auxiliary data is cleared
231632**   (set to NULL) before this function returns. In this case the xDelete,
231633**   if any, is not invoked.
231634**
231635**
231636** xRowCount(pFts5, pnRow)
231637**
231638**   This function is used to retrieve the total number of rows in the table.
231639**   In other words, the same value that would be returned by:
231640**
231641**        SELECT count(*) FROM ftstable;
231642**
231643** xPhraseFirst()
231644**   This function is used, along with type Fts5PhraseIter and the xPhraseNext
231645**   method, to iterate through all instances of a single query phrase within
231646**   the current row. This is the same information as is accessible via the
231647**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
231648**   to use, this API may be faster under some circumstances. To iterate
231649**   through instances of phrase iPhrase, use the following code:
231650**
231651**       Fts5PhraseIter iter;
231652**       int iCol, iOff;
231653**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
231654**           iCol>=0;
231655**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
231656**       ){
231657**         // An instance of phrase iPhrase at offset iOff of column iCol
231658**       }
231659**
231660**   The Fts5PhraseIter structure is defined above. Applications should not
231661**   modify this structure directly - it should only be used as shown above
231662**   with the xPhraseFirst() and xPhraseNext() API methods (and by
231663**   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
231664**
231665**   This API can be quite slow if used with an FTS5 table created with the
231666**   "detail=none" or "detail=column" option. If the FTS5 table is created
231667**   with either "detail=none" or "detail=column" and "content=" option
231668**   (i.e. if it is a contentless table), then this API always iterates
231669**   through an empty set (all calls to xPhraseFirst() set iCol to -1).
231670**
231671** xPhraseNext()
231672**   See xPhraseFirst above.
231673**
231674** xPhraseFirstColumn()
231675**   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
231676**   and xPhraseNext() APIs described above. The difference is that instead
231677**   of iterating through all instances of a phrase in the current row, these
231678**   APIs are used to iterate through the set of columns in the current row
231679**   that contain one or more instances of a specified phrase. For example:
231680**
231681**       Fts5PhraseIter iter;
231682**       int iCol;
231683**       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
231684**           iCol>=0;
231685**           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
231686**       ){
231687**         // Column iCol contains at least one instance of phrase iPhrase
231688**       }
231689**
231690**   This API can be quite slow if used with an FTS5 table created with the
231691**   "detail=none" option. If the FTS5 table is created with either
231692**   "detail=none" "content=" option (i.e. if it is a contentless table),
231693**   then this API always iterates through an empty set (all calls to
231694**   xPhraseFirstColumn() set iCol to -1).
231695**
231696**   The information accessed using this API and its companion
231697**   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
231698**   (or xInst/xInstCount). The chief advantage of this API is that it is
231699**   significantly more efficient than those alternatives when used with
231700**   "detail=column" tables.
231701**
231702** xPhraseNextColumn()
231703**   See xPhraseFirstColumn above.
231704**
231705** xQueryToken(pFts5, iPhrase, iToken, ppToken, pnToken)
231706**   This is used to access token iToken of phrase iPhrase of the current
231707**   query. Before returning, output parameter *ppToken is set to point
231708**   to a buffer containing the requested token, and *pnToken to the
231709**   size of this buffer in bytes.
231710**
231711**   If iPhrase or iToken are less than zero, or if iPhrase is greater than
231712**   or equal to the number of phrases in the query as reported by
231713**   xPhraseCount(), or if iToken is equal to or greater than the number of
231714**   tokens in the phrase, SQLITE_RANGE is returned and *ppToken and *pnToken
231715     are both zeroed.
231716**
231717**   The output text is not a copy of the query text that specified the
231718**   token. It is the output of the tokenizer module. For tokendata=1
231719**   tables, this includes any embedded 0x00 and trailing data.
231720**
231721** xInstToken(pFts5, iIdx, iToken, ppToken, pnToken)
231722**   This is used to access token iToken of phrase hit iIdx within the
231723**   current row. If iIdx is less than zero or greater than or equal to the
231724**   value returned by xInstCount(), SQLITE_RANGE is returned.  Otherwise,
231725**   output variable (*ppToken) is set to point to a buffer containing the
231726**   matching document token, and (*pnToken) to the size of that buffer in
231727**   bytes. This API is not available if the specified token matches a
231728**   prefix query term. In that case both output variables are always set
231729**   to 0.
231730**
231731**   The output text is not a copy of the document text that was tokenized.
231732**   It is the output of the tokenizer module. For tokendata=1 tables, this
231733**   includes any embedded 0x00 and trailing data.
231734**
231735**   This API can be quite slow if used with an FTS5 table created with the
231736**   "detail=none" or "detail=column" option.
231737*/
231738struct Fts5ExtensionApi {
231739  int iVersion;                   /* Currently always set to 3 */
231740
231741  void *(*xUserData)(Fts5Context*);
231742
231743  int (*xColumnCount)(Fts5Context*);
231744  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
231745  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
231746
231747  int (*xTokenize)(Fts5Context*,
231748    const char *pText, int nText, /* Text to tokenize */
231749    void *pCtx,                   /* Context passed to xToken() */
231750    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
231751  );
231752
231753  int (*xPhraseCount)(Fts5Context*);
231754  int (*xPhraseSize)(Fts5Context*, int iPhrase);
231755
231756  int (*xInstCount)(Fts5Context*, int *pnInst);
231757  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
231758
231759  sqlite3_int64 (*xRowid)(Fts5Context*);
231760  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
231761  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
231762
231763  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
231764    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
231765  );
231766  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
231767  void *(*xGetAuxdata)(Fts5Context*, int bClear);
231768
231769  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
231770  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
231771
231772  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
231773  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
231774
231775  /* Below this point are iVersion>=3 only */
231776  int (*xQueryToken)(Fts5Context*,
231777      int iPhrase, int iToken,
231778      const char **ppToken, int *pnToken
231779  );
231780  int (*xInstToken)(Fts5Context*, int iIdx, int iToken, const char**, int*);
231781};
231782
231783/*
231784** CUSTOM AUXILIARY FUNCTIONS
231785*************************************************************************/
231786
231787/*************************************************************************
231788** CUSTOM TOKENIZERS
231789**
231790** Applications may also register custom tokenizer types. A tokenizer
231791** is registered by providing fts5 with a populated instance of the
231792** following structure. All structure methods must be defined, setting
231793** any member of the fts5_tokenizer struct to NULL leads to undefined
231794** behaviour. The structure methods are expected to function as follows:
231795**
231796** xCreate:
231797**   This function is used to allocate and initialize a tokenizer instance.
231798**   A tokenizer instance is required to actually tokenize text.
231799**
231800**   The first argument passed to this function is a copy of the (void*)
231801**   pointer provided by the application when the fts5_tokenizer object
231802**   was registered with FTS5 (the third argument to xCreateTokenizer()).
231803**   The second and third arguments are an array of nul-terminated strings
231804**   containing the tokenizer arguments, if any, specified following the
231805**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
231806**   to create the FTS5 table.
231807**
231808**   The final argument is an output variable. If successful, (*ppOut)
231809**   should be set to point to the new tokenizer handle and SQLITE_OK
231810**   returned. If an error occurs, some value other than SQLITE_OK should
231811**   be returned. In this case, fts5 assumes that the final value of *ppOut
231812**   is undefined.
231813**
231814** xDelete:
231815**   This function is invoked to delete a tokenizer handle previously
231816**   allocated using xCreate(). Fts5 guarantees that this function will
231817**   be invoked exactly once for each successful call to xCreate().
231818**
231819** xTokenize:
231820**   This function is expected to tokenize the nText byte string indicated
231821**   by argument pText. pText may or may not be nul-terminated. The first
231822**   argument passed to this function is a pointer to an Fts5Tokenizer object
231823**   returned by an earlier call to xCreate().
231824**
231825**   The second argument indicates the reason that FTS5 is requesting
231826**   tokenization of the supplied text. This is always one of the following
231827**   four values:
231828**
231829**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
231830**            or removed from the FTS table. The tokenizer is being invoked to
231831**            determine the set of tokens to add to (or delete from) the
231832**            FTS index.
231833**
231834**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
231835**            against the FTS index. The tokenizer is being called to tokenize
231836**            a bareword or quoted string specified as part of the query.
231837**
231838**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
231839**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
231840**            followed by a "*" character, indicating that the last token
231841**            returned by the tokenizer will be treated as a token prefix.
231842**
231843**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
231844**            satisfy an fts5_api.xTokenize() request made by an auxiliary
231845**            function. Or an fts5_api.xColumnSize() request made by the same
231846**            on a columnsize=0 database.
231847**   </ul>
231848**
231849**   For each token in the input string, the supplied callback xToken() must
231850**   be invoked. The first argument to it should be a copy of the pointer
231851**   passed as the second argument to xTokenize(). The third and fourth
231852**   arguments are a pointer to a buffer containing the token text, and the
231853**   size of the token in bytes. The 4th and 5th arguments are the byte offsets
231854**   of the first byte of and first byte immediately following the text from
231855**   which the token is derived within the input.
231856**
231857**   The second argument passed to the xToken() callback ("tflags") should
231858**   normally be set to 0. The exception is if the tokenizer supports
231859**   synonyms. In this case see the discussion below for details.
231860**
231861**   FTS5 assumes the xToken() callback is invoked for each token in the
231862**   order that they occur within the input text.
231863**
231864**   If an xToken() callback returns any value other than SQLITE_OK, then
231865**   the tokenization should be abandoned and the xTokenize() method should
231866**   immediately return a copy of the xToken() return value. Or, if the
231867**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
231868**   if an error occurs with the xTokenize() implementation itself, it
231869**   may abandon the tokenization and return any error code other than
231870**   SQLITE_OK or SQLITE_DONE.
231871**
231872** SYNONYM SUPPORT
231873**
231874**   Custom tokenizers may also support synonyms. Consider a case in which a
231875**   user wishes to query for a phrase such as "first place". Using the
231876**   built-in tokenizers, the FTS5 query 'first + place' will match instances
231877**   of "first place" within the document set, but not alternative forms
231878**   such as "1st place". In some applications, it would be better to match
231879**   all instances of "first place" or "1st place" regardless of which form
231880**   the user specified in the MATCH query text.
231881**
231882**   There are several ways to approach this in FTS5:
231883**
231884**   <ol><li> By mapping all synonyms to a single token. In this case, using
231885**            the above example, this means that the tokenizer returns the
231886**            same token for inputs "first" and "1st". Say that token is in
231887**            fact "first", so that when the user inserts the document "I won
231888**            1st place" entries are added to the index for tokens "i", "won",
231889**            "first" and "place". If the user then queries for '1st + place',
231890**            the tokenizer substitutes "first" for "1st" and the query works
231891**            as expected.
231892**
231893**       <li> By querying the index for all synonyms of each query term
231894**            separately. In this case, when tokenizing query text, the
231895**            tokenizer may provide multiple synonyms for a single term
231896**            within the document. FTS5 then queries the index for each
231897**            synonym individually. For example, faced with the query:
231898**
231899**   <codeblock>
231900**     ... MATCH 'first place'</codeblock>
231901**
231902**            the tokenizer offers both "1st" and "first" as synonyms for the
231903**            first token in the MATCH query and FTS5 effectively runs a query
231904**            similar to:
231905**
231906**   <codeblock>
231907**     ... MATCH '(first OR 1st) place'</codeblock>
231908**
231909**            except that, for the purposes of auxiliary functions, the query
231910**            still appears to contain just two phrases - "(first OR 1st)"
231911**            being treated as a single phrase.
231912**
231913**       <li> By adding multiple synonyms for a single term to the FTS index.
231914**            Using this method, when tokenizing document text, the tokenizer
231915**            provides multiple synonyms for each token. So that when a
231916**            document such as "I won first place" is tokenized, entries are
231917**            added to the FTS index for "i", "won", "first", "1st" and
231918**            "place".
231919**
231920**            This way, even if the tokenizer does not provide synonyms
231921**            when tokenizing query text (it should not - to do so would be
231922**            inefficient), it doesn't matter if the user queries for
231923**            'first + place' or '1st + place', as there are entries in the
231924**            FTS index corresponding to both forms of the first token.
231925**   </ol>
231926**
231927**   Whether it is parsing document or query text, any call to xToken that
231928**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
231929**   is considered to supply a synonym for the previous token. For example,
231930**   when parsing the document "I won first place", a tokenizer that supports
231931**   synonyms would call xToken() 5 times, as follows:
231932**
231933**   <codeblock>
231934**       xToken(pCtx, 0, "i",                      1,  0,  1);
231935**       xToken(pCtx, 0, "won",                    3,  2,  5);
231936**       xToken(pCtx, 0, "first",                  5,  6, 11);
231937**       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
231938**       xToken(pCtx, 0, "place",                  5, 12, 17);
231939**</codeblock>
231940**
231941**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
231942**   xToken() is called. Multiple synonyms may be specified for a single token
231943**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
231944**   There is no limit to the number of synonyms that may be provided for a
231945**   single token.
231946**
231947**   In many cases, method (1) above is the best approach. It does not add
231948**   extra data to the FTS index or require FTS5 to query for multiple terms,
231949**   so it is efficient in terms of disk space and query speed. However, it
231950**   does not support prefix queries very well. If, as suggested above, the
231951**   token "first" is substituted for "1st" by the tokenizer, then the query:
231952**
231953**   <codeblock>
231954**     ... MATCH '1s*'</codeblock>
231955**
231956**   will not match documents that contain the token "1st" (as the tokenizer
231957**   will probably not map "1s" to any prefix of "first").
231958**
231959**   For full prefix support, method (3) may be preferred. In this case,
231960**   because the index contains entries for both "first" and "1st", prefix
231961**   queries such as 'fi*' or '1s*' will match correctly. However, because
231962**   extra entries are added to the FTS index, this method uses more space
231963**   within the database.
231964**
231965**   Method (2) offers a midpoint between (1) and (3). Using this method,
231966**   a query such as '1s*' will match documents that contain the literal
231967**   token "1st", but not "first" (assuming the tokenizer is not able to
231968**   provide synonyms for prefixes). However, a non-prefix query like '1st'
231969**   will match against "1st" and "first". This method does not require
231970**   extra disk space, as no extra entries are added to the FTS index.
231971**   On the other hand, it may require more CPU cycles to run MATCH queries,
231972**   as separate queries of the FTS index are required for each synonym.
231973**
231974**   When using methods (2) or (3), it is important that the tokenizer only
231975**   provide synonyms when tokenizing document text (method (3)) or query
231976**   text (method (2)), not both. Doing so will not cause any errors, but is
231977**   inefficient.
231978*/
231979typedef struct Fts5Tokenizer Fts5Tokenizer;
231980typedef struct fts5_tokenizer fts5_tokenizer;
231981struct fts5_tokenizer {
231982  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
231983  void (*xDelete)(Fts5Tokenizer*);
231984  int (*xTokenize)(Fts5Tokenizer*,
231985      void *pCtx,
231986      int flags,            /* Mask of FTS5_TOKENIZE_* flags */
231987      const char *pText, int nText,
231988      int (*xToken)(
231989        void *pCtx,         /* Copy of 2nd argument to xTokenize() */
231990        int tflags,         /* Mask of FTS5_TOKEN_* flags */
231991        const char *pToken, /* Pointer to buffer containing token */
231992        int nToken,         /* Size of token in bytes */
231993        int iStart,         /* Byte offset of token within input text */
231994        int iEnd            /* Byte offset of end of token within input text */
231995      )
231996  );
231997};
231998
231999/* Flags that may be passed as the third argument to xTokenize() */
232000#define FTS5_TOKENIZE_QUERY     0x0001
232001#define FTS5_TOKENIZE_PREFIX    0x0002
232002#define FTS5_TOKENIZE_DOCUMENT  0x0004
232003#define FTS5_TOKENIZE_AUX       0x0008
232004
232005/* Flags that may be passed by the tokenizer implementation back to FTS5
232006** as the third argument to the supplied xToken callback. */
232007#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
232008
232009/*
232010** END OF CUSTOM TOKENIZERS
232011*************************************************************************/
232012
232013/*************************************************************************
232014** FTS5 EXTENSION REGISTRATION API
232015*/
232016typedef struct fts5_api fts5_api;
232017struct fts5_api {
232018  int iVersion;                   /* Currently always set to 2 */
232019
232020  /* Create a new tokenizer */
232021  int (*xCreateTokenizer)(
232022    fts5_api *pApi,
232023    const char *zName,
232024    void *pUserData,
232025    fts5_tokenizer *pTokenizer,
232026    void (*xDestroy)(void*)
232027  );
232028
232029  /* Find an existing tokenizer */
232030  int (*xFindTokenizer)(
232031    fts5_api *pApi,
232032    const char *zName,
232033    void **ppUserData,
232034    fts5_tokenizer *pTokenizer
232035  );
232036
232037  /* Create a new auxiliary function */
232038  int (*xCreateFunction)(
232039    fts5_api *pApi,
232040    const char *zName,
232041    void *pUserData,
232042    fts5_extension_function xFunction,
232043    void (*xDestroy)(void*)
232044  );
232045};
232046
232047/*
232048** END OF REGISTRATION API
232049*************************************************************************/
232050
232051#if 0
232052}  /* end of the 'extern "C"' block */
232053#endif
232054
232055#endif /* _FTS5_H */
232056
232057/*
232058** 2014 May 31
232059**
232060** The author disclaims copyright to this source code.  In place of
232061** a legal notice, here is a blessing:
232062**
232063**    May you do good and not evil.
232064**    May you find forgiveness for yourself and forgive others.
232065**    May you share freely, never taking more than you give.
232066**
232067******************************************************************************
232068**
232069*/
232070#ifndef _FTS5INT_H
232071#define _FTS5INT_H
232072
232073/* #include "fts5.h" */
232074/* #include "sqlite3ext.h" */
232075SQLITE_EXTENSION_INIT1
232076
232077/* #include <string.h> */
232078/* #include <assert.h> */
232079
232080#ifndef SQLITE_AMALGAMATION
232081
232082typedef unsigned char  u8;
232083typedef unsigned int   u32;
232084typedef unsigned short u16;
232085typedef short i16;
232086typedef sqlite3_int64 i64;
232087typedef sqlite3_uint64 u64;
232088
232089#ifndef ArraySize
232090# define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
232091#endif
232092
232093#define testcase(x)
232094
232095#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
232096# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
232097#endif
232098#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
232099# define ALWAYS(X)      (1)
232100# define NEVER(X)       (0)
232101#elif !defined(NDEBUG)
232102# define ALWAYS(X)      ((X)?1:(assert(0),0))
232103# define NEVER(X)       ((X)?(assert(0),1):0)
232104#else
232105# define ALWAYS(X)      (X)
232106# define NEVER(X)       (X)
232107#endif
232108
232109#define MIN(x,y) (((x) < (y)) ? (x) : (y))
232110#define MAX(x,y) (((x) > (y)) ? (x) : (y))
232111
232112/*
232113** Constants for the largest and smallest possible 64-bit signed integers.
232114*/
232115# define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
232116# define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
232117
232118#endif
232119
232120/* Truncate very long tokens to this many bytes. Hard limit is
232121** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
232122** field that occurs at the start of each leaf page (see fts5_index.c). */
232123#define FTS5_MAX_TOKEN_SIZE 32768
232124
232125/*
232126** Maximum number of prefix indexes on single FTS5 table. This must be
232127** less than 32. If it is set to anything large than that, an #error
232128** directive in fts5_index.c will cause the build to fail.
232129*/
232130#define FTS5_MAX_PREFIX_INDEXES 31
232131
232132/*
232133** Maximum segments permitted in a single index
232134*/
232135#define FTS5_MAX_SEGMENT 2000
232136
232137#define FTS5_DEFAULT_NEARDIST 10
232138#define FTS5_DEFAULT_RANK     "bm25"
232139
232140/* Name of rank and rowid columns */
232141#define FTS5_RANK_NAME "rank"
232142#define FTS5_ROWID_NAME "rowid"
232143
232144#ifdef SQLITE_DEBUG
232145# define FTS5_CORRUPT sqlite3Fts5Corrupt()
232146static int sqlite3Fts5Corrupt(void);
232147#else
232148# define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
232149#endif
232150
232151/*
232152** The assert_nc() macro is similar to the assert() macro, except that it
232153** is used for assert() conditions that are true only if it can be
232154** guranteed that the database is not corrupt.
232155*/
232156#ifdef SQLITE_DEBUG
232157SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
232158# define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
232159#else
232160# define assert_nc(x) assert(x)
232161#endif
232162
232163/*
232164** A version of memcmp() that does not cause asan errors if one of the pointer
232165** parameters is NULL and the number of bytes to compare is zero.
232166*/
232167#define fts5Memcmp(s1, s2, n) ((n)<=0 ? 0 : memcmp((s1), (s2), (n)))
232168
232169/* Mark a function parameter as unused, to suppress nuisance compiler
232170** warnings. */
232171#ifndef UNUSED_PARAM
232172# define UNUSED_PARAM(X)  (void)(X)
232173#endif
232174
232175#ifndef UNUSED_PARAM2
232176# define UNUSED_PARAM2(X, Y)  (void)(X), (void)(Y)
232177#endif
232178
232179typedef struct Fts5Global Fts5Global;
232180typedef struct Fts5Colset Fts5Colset;
232181
232182/* If a NEAR() clump or phrase may only match a specific set of columns,
232183** then an object of the following type is used to record the set of columns.
232184** Each entry in the aiCol[] array is a column that may be matched.
232185**
232186** This object is used by fts5_expr.c and fts5_index.c.
232187*/
232188struct Fts5Colset {
232189  int nCol;
232190  int aiCol[1];
232191};
232192
232193
232194
232195/**************************************************************************
232196** Interface to code in fts5_config.c. fts5_config.c contains contains code
232197** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
232198*/
232199
232200typedef struct Fts5Config Fts5Config;
232201
232202/*
232203** An instance of the following structure encodes all information that can
232204** be gleaned from the CREATE VIRTUAL TABLE statement.
232205**
232206** And all information loaded from the %_config table.
232207**
232208** nAutomerge:
232209**   The minimum number of segments that an auto-merge operation should
232210**   attempt to merge together. A value of 1 sets the object to use the
232211**   compile time default. Zero disables auto-merge altogether.
232212**
232213** bContentlessDelete:
232214**   True if the contentless_delete option was present in the CREATE
232215**   VIRTUAL TABLE statement.
232216**
232217** zContent:
232218**
232219** zContentRowid:
232220**   The value of the content_rowid= option, if one was specified. Or
232221**   the string "rowid" otherwise. This text is not quoted - if it is
232222**   used as part of an SQL statement it needs to be quoted appropriately.
232223**
232224** zContentExprlist:
232225**
232226** pzErrmsg:
232227**   This exists in order to allow the fts5_index.c module to return a
232228**   decent error message if it encounters a file-format version it does
232229**   not understand.
232230**
232231** bColumnsize:
232232**   True if the %_docsize table is created.
232233**
232234** bPrefixIndex:
232235**   This is only used for debugging. If set to false, any prefix indexes
232236**   are ignored. This value is configured using:
232237**
232238**       INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
232239**
232240*/
232241struct Fts5Config {
232242  sqlite3 *db;                    /* Database handle */
232243  char *zDb;                      /* Database holding FTS index (e.g. "main") */
232244  char *zName;                    /* Name of FTS index */
232245  int nCol;                       /* Number of columns */
232246  char **azCol;                   /* Column names */
232247  u8 *abUnindexed;                /* True for unindexed columns */
232248  int nPrefix;                    /* Number of prefix indexes */
232249  int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
232250  int eContent;                   /* An FTS5_CONTENT value */
232251  int bContentlessDelete;         /* "contentless_delete=" option (dflt==0) */
232252  char *zContent;                 /* content table */
232253  char *zContentRowid;            /* "content_rowid=" option value */
232254  int bColumnsize;                /* "columnsize=" option value (dflt==1) */
232255  int bTokendata;                 /* "tokendata=" option value (dflt==0) */
232256  int eDetail;                    /* FTS5_DETAIL_XXX value */
232257  char *zContentExprlist;
232258  Fts5Tokenizer *pTok;
232259  fts5_tokenizer *pTokApi;
232260  int bLock;                      /* True when table is preparing statement */
232261  int ePattern;                   /* FTS_PATTERN_XXX constant */
232262
232263  /* Values loaded from the %_config table */
232264  int iVersion;                   /* fts5 file format 'version' */
232265  int iCookie;                    /* Incremented when %_config is modified */
232266  int pgsz;                       /* Approximate page size used in %_data */
232267  int nAutomerge;                 /* 'automerge' setting */
232268  int nCrisisMerge;               /* Maximum allowed segments per level */
232269  int nUsermerge;                 /* 'usermerge' setting */
232270  int nHashSize;                  /* Bytes of memory for in-memory hash */
232271  char *zRank;                    /* Name of rank function */
232272  char *zRankArgs;                /* Arguments to rank function */
232273  int bSecureDelete;              /* 'secure-delete' */
232274  int nDeleteMerge;           /* 'deletemerge' */
232275
232276  /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
232277  char **pzErrmsg;
232278
232279#ifdef SQLITE_DEBUG
232280  int bPrefixIndex;               /* True to use prefix-indexes */
232281#endif
232282};
232283
232284/* Current expected value of %_config table 'version' field. And
232285** the expected version if the 'secure-delete' option has ever been
232286** set on the table.  */
232287#define FTS5_CURRENT_VERSION               4
232288#define FTS5_CURRENT_VERSION_SECUREDELETE  5
232289
232290#define FTS5_CONTENT_NORMAL   0
232291#define FTS5_CONTENT_NONE     1
232292#define FTS5_CONTENT_EXTERNAL 2
232293
232294#define FTS5_DETAIL_FULL      0
232295#define FTS5_DETAIL_NONE      1
232296#define FTS5_DETAIL_COLUMNS   2
232297
232298#define FTS5_PATTERN_NONE     0
232299#define FTS5_PATTERN_LIKE     65  /* matches SQLITE_INDEX_CONSTRAINT_LIKE */
232300#define FTS5_PATTERN_GLOB     66  /* matches SQLITE_INDEX_CONSTRAINT_GLOB */
232301
232302static int sqlite3Fts5ConfigParse(
232303    Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
232304);
232305static void sqlite3Fts5ConfigFree(Fts5Config*);
232306
232307static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
232308
232309static int sqlite3Fts5Tokenize(
232310  Fts5Config *pConfig,            /* FTS5 Configuration object */
232311  int flags,                      /* FTS5_TOKENIZE_* flags */
232312  const char *pText, int nText,   /* Text to tokenize */
232313  void *pCtx,                     /* Context passed to xToken() */
232314  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
232315);
232316
232317static void sqlite3Fts5Dequote(char *z);
232318
232319/* Load the contents of the %_config table */
232320static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
232321
232322/* Set the value of a single config attribute */
232323static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
232324
232325static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
232326
232327/*
232328** End of interface to code in fts5_config.c.
232329**************************************************************************/
232330
232331/**************************************************************************
232332** Interface to code in fts5_buffer.c.
232333*/
232334
232335/*
232336** Buffer object for the incremental building of string data.
232337*/
232338typedef struct Fts5Buffer Fts5Buffer;
232339struct Fts5Buffer {
232340  u8 *p;
232341  int n;
232342  int nSpace;
232343};
232344
232345static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
232346static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
232347static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
232348static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
232349static void sqlite3Fts5BufferFree(Fts5Buffer*);
232350static void sqlite3Fts5BufferZero(Fts5Buffer*);
232351static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
232352static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
232353
232354static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
232355
232356#define fts5BufferZero(x)             sqlite3Fts5BufferZero(x)
232357#define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,(i64)c)
232358#define fts5BufferFree(a)             sqlite3Fts5BufferFree(a)
232359#define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
232360#define fts5BufferSet(a,b,c,d)        sqlite3Fts5BufferSet(a,b,c,d)
232361
232362#define fts5BufferGrow(pRc,pBuf,nn) ( \
232363  (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
232364    sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
232365)
232366
232367/* Write and decode big-endian 32-bit integer values */
232368static void sqlite3Fts5Put32(u8*, int);
232369static int sqlite3Fts5Get32(const u8*);
232370
232371#define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
232372#define FTS5_POS2OFFSET(iPos) (int)(iPos & 0x7FFFFFFF)
232373
232374typedef struct Fts5PoslistReader Fts5PoslistReader;
232375struct Fts5PoslistReader {
232376  /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
232377  const u8 *a;                    /* Position list to iterate through */
232378  int n;                          /* Size of buffer at a[] in bytes */
232379  int i;                          /* Current offset in a[] */
232380
232381  u8 bFlag;                       /* For client use (any custom purpose) */
232382
232383  /* Output variables */
232384  u8 bEof;                        /* Set to true at EOF */
232385  i64 iPos;                       /* (iCol<<32) + iPos */
232386};
232387static int sqlite3Fts5PoslistReaderInit(
232388  const u8 *a, int n,             /* Poslist buffer to iterate through */
232389  Fts5PoslistReader *pIter        /* Iterator object to initialize */
232390);
232391static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
232392
232393typedef struct Fts5PoslistWriter Fts5PoslistWriter;
232394struct Fts5PoslistWriter {
232395  i64 iPrev;
232396};
232397static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
232398static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
232399
232400static int sqlite3Fts5PoslistNext64(
232401  const u8 *a, int n,             /* Buffer containing poslist */
232402  int *pi,                        /* IN/OUT: Offset within a[] */
232403  i64 *piOff                      /* IN/OUT: Current offset */
232404);
232405
232406/* Malloc utility */
232407static void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte);
232408static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
232409
232410/* Character set tests (like isspace(), isalpha() etc.) */
232411static int sqlite3Fts5IsBareword(char t);
232412
232413
232414/* Bucket of terms object used by the integrity-check in offsets=0 mode. */
232415typedef struct Fts5Termset Fts5Termset;
232416static int sqlite3Fts5TermsetNew(Fts5Termset**);
232417static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
232418static void sqlite3Fts5TermsetFree(Fts5Termset*);
232419
232420/*
232421** End of interface to code in fts5_buffer.c.
232422**************************************************************************/
232423
232424/**************************************************************************
232425** Interface to code in fts5_index.c. fts5_index.c contains contains code
232426** to access the data stored in the %_data table.
232427*/
232428
232429typedef struct Fts5Index Fts5Index;
232430typedef struct Fts5IndexIter Fts5IndexIter;
232431
232432struct Fts5IndexIter {
232433  i64 iRowid;
232434  const u8 *pData;
232435  int nData;
232436  u8 bEof;
232437};
232438
232439#define sqlite3Fts5IterEof(x) ((x)->bEof)
232440
232441/*
232442** Values used as part of the flags argument passed to IndexQuery().
232443*/
232444#define FTS5INDEX_QUERY_PREFIX      0x0001  /* Prefix query */
232445#define FTS5INDEX_QUERY_DESC        0x0002  /* Docs in descending rowid order */
232446#define FTS5INDEX_QUERY_TEST_NOIDX  0x0004  /* Do not use prefix index */
232447#define FTS5INDEX_QUERY_SCAN        0x0008  /* Scan query (fts5vocab) */
232448
232449/* The following are used internally by the fts5_index.c module. They are
232450** defined here only to make it easier to avoid clashes with the flags
232451** above. */
232452#define FTS5INDEX_QUERY_SKIPEMPTY   0x0010
232453#define FTS5INDEX_QUERY_NOOUTPUT    0x0020
232454#define FTS5INDEX_QUERY_SKIPHASH    0x0040
232455#define FTS5INDEX_QUERY_NOTOKENDATA 0x0080
232456#define FTS5INDEX_QUERY_SCANONETERM 0x0100
232457
232458/*
232459** Create/destroy an Fts5Index object.
232460*/
232461static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
232462static int sqlite3Fts5IndexClose(Fts5Index *p);
232463
232464/*
232465** Return a simple checksum value based on the arguments.
232466*/
232467static u64 sqlite3Fts5IndexEntryCksum(
232468  i64 iRowid,
232469  int iCol,
232470  int iPos,
232471  int iIdx,
232472  const char *pTerm,
232473  int nTerm
232474);
232475
232476/*
232477** Argument p points to a buffer containing utf-8 text that is n bytes in
232478** size. Return the number of bytes in the nChar character prefix of the
232479** buffer, or 0 if there are less than nChar characters in total.
232480*/
232481static int sqlite3Fts5IndexCharlenToBytelen(
232482  const char *p,
232483  int nByte,
232484  int nChar
232485);
232486
232487/*
232488** Open a new iterator to iterate though all rowids that match the
232489** specified token or token prefix.
232490*/
232491static int sqlite3Fts5IndexQuery(
232492  Fts5Index *p,                   /* FTS index to query */
232493  const char *pToken, int nToken, /* Token (or prefix) to query for */
232494  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
232495  Fts5Colset *pColset,            /* Match these columns only */
232496  Fts5IndexIter **ppIter          /* OUT: New iterator object */
232497);
232498
232499/*
232500** The various operations on open token or token prefix iterators opened
232501** using sqlite3Fts5IndexQuery().
232502*/
232503static int sqlite3Fts5IterNext(Fts5IndexIter*);
232504static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
232505
232506/*
232507** Close an iterator opened by sqlite3Fts5IndexQuery().
232508*/
232509static void sqlite3Fts5IterClose(Fts5IndexIter*);
232510
232511/*
232512** Close the reader blob handle, if it is open.
232513*/
232514static void sqlite3Fts5IndexCloseReader(Fts5Index*);
232515
232516/*
232517** This interface is used by the fts5vocab module.
232518*/
232519static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
232520static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
232521static void *sqlite3Fts5StructureRef(Fts5Index*);
232522static void sqlite3Fts5StructureRelease(void*);
232523static int sqlite3Fts5StructureTest(Fts5Index*, void*);
232524
232525/*
232526** Used by xInstToken():
232527*/
232528static int sqlite3Fts5IterToken(Fts5IndexIter*, i64, int, int, const char**, int*);
232529
232530/*
232531** Insert or remove data to or from the index. Each time a document is
232532** added to or removed from the index, this function is called one or more
232533** times.
232534**
232535** For an insert, it must be called once for each token in the new document.
232536** If the operation is a delete, it must be called (at least) once for each
232537** unique token in the document with an iCol value less than zero. The iPos
232538** argument is ignored for a delete.
232539*/
232540static int sqlite3Fts5IndexWrite(
232541  Fts5Index *p,                   /* Index to write to */
232542  int iCol,                       /* Column token appears in (-ve -> delete) */
232543  int iPos,                       /* Position of token within column */
232544  const char *pToken, int nToken  /* Token to add or remove to or from index */
232545);
232546
232547/*
232548** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
232549** document iDocid.
232550*/
232551static int sqlite3Fts5IndexBeginWrite(
232552  Fts5Index *p,                   /* Index to write to */
232553  int bDelete,                    /* True if current operation is a delete */
232554  i64 iDocid                      /* Docid to add or remove data from */
232555);
232556
232557/*
232558** Flush any data stored in the in-memory hash tables to the database.
232559** Also close any open blob handles.
232560*/
232561static int sqlite3Fts5IndexSync(Fts5Index *p);
232562
232563/*
232564** Discard any data stored in the in-memory hash tables. Do not write it
232565** to the database. Additionally, assume that the contents of the %_data
232566** table may have changed on disk. So any in-memory caches of %_data
232567** records must be invalidated.
232568*/
232569static int sqlite3Fts5IndexRollback(Fts5Index *p);
232570
232571/*
232572** Get or set the "averages" values.
232573*/
232574static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
232575static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
232576
232577/*
232578** Functions called by the storage module as part of integrity-check.
232579*/
232580static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum, int bUseCksum);
232581
232582/*
232583** Called during virtual module initialization to register UDF
232584** fts5_decode() with SQLite
232585*/
232586static int sqlite3Fts5IndexInit(sqlite3*);
232587
232588static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
232589
232590/*
232591** Return the total number of entries read from the %_data table by
232592** this connection since it was created.
232593*/
232594static int sqlite3Fts5IndexReads(Fts5Index *p);
232595
232596static int sqlite3Fts5IndexReinit(Fts5Index *p);
232597static int sqlite3Fts5IndexOptimize(Fts5Index *p);
232598static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
232599static int sqlite3Fts5IndexReset(Fts5Index *p);
232600
232601static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
232602
232603static int sqlite3Fts5IndexGetOrigin(Fts5Index *p, i64 *piOrigin);
232604static int sqlite3Fts5IndexContentlessDelete(Fts5Index *p, i64 iOrigin, i64 iRowid);
232605
232606static void sqlite3Fts5IndexIterClearTokendata(Fts5IndexIter*);
232607
232608/* Used to populate hash tables for xInstToken in detail=none/column mode. */
232609static int sqlite3Fts5IndexIterWriteTokendata(
232610    Fts5IndexIter*, const char*, int, i64 iRowid, int iCol, int iOff
232611);
232612
232613/*
232614** End of interface to code in fts5_index.c.
232615**************************************************************************/
232616
232617/**************************************************************************
232618** Interface to code in fts5_varint.c.
232619*/
232620static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
232621static int sqlite3Fts5GetVarintLen(u32 iVal);
232622static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
232623static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
232624
232625#define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&(b))
232626#define fts5GetVarint    sqlite3Fts5GetVarint
232627
232628#define fts5FastGetVarint32(a, iOff, nVal) {      \
232629  nVal = (a)[iOff++];                             \
232630  if( nVal & 0x80 ){                              \
232631    iOff--;                                       \
232632    iOff += fts5GetVarint32(&(a)[iOff], nVal);    \
232633  }                                               \
232634}
232635
232636
232637/*
232638** End of interface to code in fts5_varint.c.
232639**************************************************************************/
232640
232641
232642/**************************************************************************
232643** Interface to code in fts5_main.c.
232644*/
232645
232646/*
232647** Virtual-table object.
232648*/
232649typedef struct Fts5Table Fts5Table;
232650struct Fts5Table {
232651  sqlite3_vtab base;              /* Base class used by SQLite core */
232652  Fts5Config *pConfig;            /* Virtual table configuration */
232653  Fts5Index *pIndex;              /* Full-text index */
232654};
232655
232656static int sqlite3Fts5GetTokenizer(
232657  Fts5Global*,
232658  const char **azArg,
232659  int nArg,
232660  Fts5Config*,
232661  char **pzErr
232662);
232663
232664static Fts5Table *sqlite3Fts5TableFromCsrid(Fts5Global*, i64);
232665
232666static int sqlite3Fts5FlushToDisk(Fts5Table*);
232667
232668/*
232669** End of interface to code in fts5.c.
232670**************************************************************************/
232671
232672/**************************************************************************
232673** Interface to code in fts5_hash.c.
232674*/
232675typedef struct Fts5Hash Fts5Hash;
232676
232677/*
232678** Create a hash table, free a hash table.
232679*/
232680static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
232681static void sqlite3Fts5HashFree(Fts5Hash*);
232682
232683static int sqlite3Fts5HashWrite(
232684  Fts5Hash*,
232685  i64 iRowid,                     /* Rowid for this entry */
232686  int iCol,                       /* Column token appears in (-ve -> delete) */
232687  int iPos,                       /* Position of token within column */
232688  char bByte,
232689  const char *pToken, int nToken  /* Token to add or remove to or from index */
232690);
232691
232692/*
232693** Empty (but do not delete) a hash table.
232694*/
232695static void sqlite3Fts5HashClear(Fts5Hash*);
232696
232697/*
232698** Return true if the hash is empty, false otherwise.
232699*/
232700static int sqlite3Fts5HashIsEmpty(Fts5Hash*);
232701
232702static int sqlite3Fts5HashQuery(
232703  Fts5Hash*,                      /* Hash table to query */
232704  int nPre,
232705  const char *pTerm, int nTerm,   /* Query term */
232706  void **ppObj,                   /* OUT: Pointer to doclist for pTerm */
232707  int *pnDoclist                  /* OUT: Size of doclist in bytes */
232708);
232709
232710static int sqlite3Fts5HashScanInit(
232711  Fts5Hash*,                      /* Hash table to query */
232712  const char *pTerm, int nTerm    /* Query prefix */
232713);
232714static void sqlite3Fts5HashScanNext(Fts5Hash*);
232715static int sqlite3Fts5HashScanEof(Fts5Hash*);
232716static void sqlite3Fts5HashScanEntry(Fts5Hash *,
232717  const char **pzTerm,            /* OUT: term (nul-terminated) */
232718  int *pnTerm,                    /* OUT: Size of term in bytes */
232719  const u8 **ppDoclist,           /* OUT: pointer to doclist */
232720  int *pnDoclist                  /* OUT: size of doclist in bytes */
232721);
232722
232723
232724
232725/*
232726** End of interface to code in fts5_hash.c.
232727**************************************************************************/
232728
232729/**************************************************************************
232730** Interface to code in fts5_storage.c. fts5_storage.c contains contains
232731** code to access the data stored in the %_content and %_docsize tables.
232732*/
232733
232734#define FTS5_STMT_SCAN_ASC  0     /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
232735#define FTS5_STMT_SCAN_DESC 1     /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
232736#define FTS5_STMT_LOOKUP    2     /* SELECT rowid, * FROM ... WHERE rowid=? */
232737
232738typedef struct Fts5Storage Fts5Storage;
232739
232740static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
232741static int sqlite3Fts5StorageClose(Fts5Storage *p);
232742static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
232743
232744static int sqlite3Fts5DropAll(Fts5Config*);
232745static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
232746
232747static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
232748static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
232749static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
232750
232751static int sqlite3Fts5StorageIntegrity(Fts5Storage *p, int iArg);
232752
232753static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
232754static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
232755
232756static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
232757static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
232758static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
232759
232760static int sqlite3Fts5StorageSync(Fts5Storage *p);
232761static int sqlite3Fts5StorageRollback(Fts5Storage *p);
232762
232763static int sqlite3Fts5StorageConfigValue(
232764    Fts5Storage *p, const char*, sqlite3_value*, int
232765);
232766
232767static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
232768static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
232769static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
232770static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
232771static int sqlite3Fts5StorageReset(Fts5Storage *p);
232772
232773/*
232774** End of interface to code in fts5_storage.c.
232775**************************************************************************/
232776
232777
232778/**************************************************************************
232779** Interface to code in fts5_expr.c.
232780*/
232781typedef struct Fts5Expr Fts5Expr;
232782typedef struct Fts5ExprNode Fts5ExprNode;
232783typedef struct Fts5Parse Fts5Parse;
232784typedef struct Fts5Token Fts5Token;
232785typedef struct Fts5ExprPhrase Fts5ExprPhrase;
232786typedef struct Fts5ExprNearset Fts5ExprNearset;
232787
232788struct Fts5Token {
232789  const char *p;                  /* Token text (not NULL terminated) */
232790  int n;                          /* Size of buffer p in bytes */
232791};
232792
232793/* Parse a MATCH expression. */
232794static int sqlite3Fts5ExprNew(
232795  Fts5Config *pConfig,
232796  int bPhraseToAnd,
232797  int iCol,                       /* Column on LHS of MATCH operator */
232798  const char *zExpr,
232799  Fts5Expr **ppNew,
232800  char **pzErr
232801);
232802static int sqlite3Fts5ExprPattern(
232803  Fts5Config *pConfig,
232804  int bGlob,
232805  int iCol,
232806  const char *zText,
232807  Fts5Expr **pp
232808);
232809
232810/*
232811** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
232812**     rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
232813**     rc = sqlite3Fts5ExprNext(pExpr)
232814** ){
232815**   // The document with rowid iRowid matches the expression!
232816**   i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
232817** }
232818*/
232819static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
232820static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
232821static int sqlite3Fts5ExprEof(Fts5Expr*);
232822static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
232823
232824static void sqlite3Fts5ExprFree(Fts5Expr*);
232825static int sqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2);
232826
232827/* Called during startup to register a UDF with SQLite */
232828static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
232829
232830static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
232831static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
232832static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
232833
232834typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
232835static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
232836static int sqlite3Fts5ExprPopulatePoslists(
232837    Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
232838);
232839static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
232840
232841static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
232842
232843static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
232844
232845static int sqlite3Fts5ExprQueryToken(Fts5Expr*, int, int, const char**, int*);
232846static int sqlite3Fts5ExprInstToken(Fts5Expr*, i64, int, int, int, int, const char**, int*);
232847static void sqlite3Fts5ExprClearTokens(Fts5Expr*);
232848
232849/*******************************************
232850** The fts5_expr.c API above this point is used by the other hand-written
232851** C code in this module. The interfaces below this point are called by
232852** the parser code in fts5parse.y.  */
232853
232854static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
232855
232856static Fts5ExprNode *sqlite3Fts5ParseNode(
232857  Fts5Parse *pParse,
232858  int eType,
232859  Fts5ExprNode *pLeft,
232860  Fts5ExprNode *pRight,
232861  Fts5ExprNearset *pNear
232862);
232863
232864static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
232865  Fts5Parse *pParse,
232866  Fts5ExprNode *pLeft,
232867  Fts5ExprNode *pRight
232868);
232869
232870static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
232871  Fts5Parse *pParse,
232872  Fts5ExprPhrase *pPhrase,
232873  Fts5Token *pToken,
232874  int bPrefix
232875);
232876
232877static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase*);
232878
232879static Fts5ExprNearset *sqlite3Fts5ParseNearset(
232880  Fts5Parse*,
232881  Fts5ExprNearset*,
232882  Fts5ExprPhrase*
232883);
232884
232885static Fts5Colset *sqlite3Fts5ParseColset(
232886  Fts5Parse*,
232887  Fts5Colset*,
232888  Fts5Token *
232889);
232890
232891static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
232892static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
232893static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
232894
232895static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
232896static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
232897static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
232898static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
232899static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
232900
232901/*
232902** End of interface to code in fts5_expr.c.
232903**************************************************************************/
232904
232905
232906
232907/**************************************************************************
232908** Interface to code in fts5_aux.c.
232909*/
232910
232911static int sqlite3Fts5AuxInit(fts5_api*);
232912/*
232913** End of interface to code in fts5_aux.c.
232914**************************************************************************/
232915
232916/**************************************************************************
232917** Interface to code in fts5_tokenizer.c.
232918*/
232919
232920static int sqlite3Fts5TokenizerInit(fts5_api*);
232921static int sqlite3Fts5TokenizerPattern(
232922    int (*xCreate)(void*, const char**, int, Fts5Tokenizer**),
232923    Fts5Tokenizer *pTok
232924);
232925/*
232926** End of interface to code in fts5_tokenizer.c.
232927**************************************************************************/
232928
232929/**************************************************************************
232930** Interface to code in fts5_vocab.c.
232931*/
232932
232933static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
232934
232935/*
232936** End of interface to code in fts5_vocab.c.
232937**************************************************************************/
232938
232939
232940/**************************************************************************
232941** Interface to automatically generated code in fts5_unicode2.c.
232942*/
232943static int sqlite3Fts5UnicodeIsdiacritic(int c);
232944static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
232945
232946static int sqlite3Fts5UnicodeCatParse(const char*, u8*);
232947static int sqlite3Fts5UnicodeCategory(u32 iCode);
232948static void sqlite3Fts5UnicodeAscii(u8*, u8*);
232949/*
232950** End of interface to code in fts5_unicode2.c.
232951**************************************************************************/
232952
232953#endif
232954
232955#define FTS5_OR                               1
232956#define FTS5_AND                              2
232957#define FTS5_NOT                              3
232958#define FTS5_TERM                             4
232959#define FTS5_COLON                            5
232960#define FTS5_MINUS                            6
232961#define FTS5_LCP                              7
232962#define FTS5_RCP                              8
232963#define FTS5_STRING                           9
232964#define FTS5_LP                              10
232965#define FTS5_RP                              11
232966#define FTS5_CARET                           12
232967#define FTS5_COMMA                           13
232968#define FTS5_PLUS                            14
232969#define FTS5_STAR                            15
232970
232971/* This file is automatically generated by Lemon from input grammar
232972** source file "fts5parse.y".
232973*/
232974/*
232975** 2000-05-29
232976**
232977** The author disclaims copyright to this source code.  In place of
232978** a legal notice, here is a blessing:
232979**
232980**    May you do good and not evil.
232981**    May you find forgiveness for yourself and forgive others.
232982**    May you share freely, never taking more than you give.
232983**
232984*************************************************************************
232985** Driver template for the LEMON parser generator.
232986**
232987** The "lemon" program processes an LALR(1) input grammar file, then uses
232988** this template to construct a parser.  The "lemon" program inserts text
232989** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
232990** interstitial "-" characters) contained in this template is changed into
232991** the value of the %name directive from the grammar.  Otherwise, the content
232992** of this template is copied straight through into the generate parser
232993** source file.
232994**
232995** The following is the concatenation of all %include directives from the
232996** input grammar file:
232997*/
232998/************ Begin %include sections from the grammar ************************/
232999
233000/* #include "fts5Int.h" */
233001/* #include "fts5parse.h" */
233002
233003/*
233004** Disable all error recovery processing in the parser push-down
233005** automaton.
233006*/
233007#define fts5YYNOERRORRECOVERY 1
233008
233009/*
233010** Make fts5yytestcase() the same as testcase()
233011*/
233012#define fts5yytestcase(X) testcase(X)
233013
233014/*
233015** Indicate that sqlite3ParserFree() will never be called with a null
233016** pointer.
233017*/
233018#define fts5YYPARSEFREENOTNULL 1
233019
233020/*
233021** Alternative datatype for the argument to the malloc() routine passed
233022** into sqlite3ParserAlloc().  The default is size_t.
233023*/
233024#define fts5YYMALLOCARGTYPE  u64
233025
233026/**************** End of %include directives **********************************/
233027/* These constants specify the various numeric values for terminal symbols.
233028***************** Begin token definitions *************************************/
233029#ifndef FTS5_OR
233030#define FTS5_OR                              1
233031#define FTS5_AND                             2
233032#define FTS5_NOT                             3
233033#define FTS5_TERM                            4
233034#define FTS5_COLON                           5
233035#define FTS5_MINUS                           6
233036#define FTS5_LCP                             7
233037#define FTS5_RCP                             8
233038#define FTS5_STRING                          9
233039#define FTS5_LP                             10
233040#define FTS5_RP                             11
233041#define FTS5_CARET                          12
233042#define FTS5_COMMA                          13
233043#define FTS5_PLUS                           14
233044#define FTS5_STAR                           15
233045#endif
233046/**************** End token definitions ***************************************/
233047
233048/* The next sections is a series of control #defines.
233049** various aspects of the generated parser.
233050**    fts5YYCODETYPE         is the data type used to store the integer codes
233051**                       that represent terminal and non-terminal symbols.
233052**                       "unsigned char" is used if there are fewer than
233053**                       256 symbols.  Larger types otherwise.
233054**    fts5YYNOCODE           is a number of type fts5YYCODETYPE that is not used for
233055**                       any terminal or nonterminal symbol.
233056**    fts5YYFALLBACK         If defined, this indicates that one or more tokens
233057**                       (also known as: "terminal symbols") have fall-back
233058**                       values which should be used if the original symbol
233059**                       would not parse.  This permits keywords to sometimes
233060**                       be used as identifiers, for example.
233061**    fts5YYACTIONTYPE       is the data type used for "action codes" - numbers
233062**                       that indicate what to do in response to the next
233063**                       token.
233064**    sqlite3Fts5ParserFTS5TOKENTYPE     is the data type used for minor type for terminal
233065**                       symbols.  Background: A "minor type" is a semantic
233066**                       value associated with a terminal or non-terminal
233067**                       symbols.  For example, for an "ID" terminal symbol,
233068**                       the minor type might be the name of the identifier.
233069**                       Each non-terminal can have a different minor type.
233070**                       Terminal symbols all have the same minor type, though.
233071**                       This macros defines the minor type for terminal
233072**                       symbols.
233073**    fts5YYMINORTYPE        is the data type used for all minor types.
233074**                       This is typically a union of many types, one of
233075**                       which is sqlite3Fts5ParserFTS5TOKENTYPE.  The entry in the union
233076**                       for terminal symbols is called "fts5yy0".
233077**    fts5YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
233078**                       zero the stack is dynamically sized using realloc()
233079**    sqlite3Fts5ParserARG_SDECL     A static variable declaration for the %extra_argument
233080**    sqlite3Fts5ParserARG_PDECL     A parameter declaration for the %extra_argument
233081**    sqlite3Fts5ParserARG_PARAM     Code to pass %extra_argument as a subroutine parameter
233082**    sqlite3Fts5ParserARG_STORE     Code to store %extra_argument into fts5yypParser
233083**    sqlite3Fts5ParserARG_FETCH     Code to extract %extra_argument from fts5yypParser
233084**    sqlite3Fts5ParserCTX_*         As sqlite3Fts5ParserARG_ except for %extra_context
233085**    fts5YYREALLOC          Name of the realloc() function to use
233086**    fts5YYFREE             Name of the free() function to use
233087**    fts5YYDYNSTACK         True if stack space should be extended on heap
233088**    fts5YYERRORSYMBOL      is the code number of the error symbol.  If not
233089**                       defined, then do no error processing.
233090**    fts5YYNSTATE           the combined number of states.
233091**    fts5YYNRULE            the number of rules in the grammar
233092**    fts5YYNFTS5TOKEN           Number of terminal symbols
233093**    fts5YY_MAX_SHIFT       Maximum value for shift actions
233094**    fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
233095**    fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
233096**    fts5YY_ERROR_ACTION    The fts5yy_action[] code for syntax error
233097**    fts5YY_ACCEPT_ACTION   The fts5yy_action[] code for accept
233098**    fts5YY_NO_ACTION       The fts5yy_action[] code for no-op
233099**    fts5YY_MIN_REDUCE      Minimum value for reduce actions
233100**    fts5YY_MAX_REDUCE      Maximum value for reduce actions
233101**    fts5YY_MIN_DSTRCTR     Minimum symbol value that has a destructor
233102**    fts5YY_MAX_DSTRCTR     Maximum symbol value that has a destructor
233103*/
233104#ifndef INTERFACE
233105# define INTERFACE 1
233106#endif
233107/************* Begin control #defines *****************************************/
233108#define fts5YYCODETYPE unsigned char
233109#define fts5YYNOCODE 27
233110#define fts5YYACTIONTYPE unsigned char
233111#define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
233112typedef union {
233113  int fts5yyinit;
233114  sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
233115  int fts5yy4;
233116  Fts5Colset* fts5yy11;
233117  Fts5ExprNode* fts5yy24;
233118  Fts5ExprNearset* fts5yy46;
233119  Fts5ExprPhrase* fts5yy53;
233120} fts5YYMINORTYPE;
233121#ifndef fts5YYSTACKDEPTH
233122#define fts5YYSTACKDEPTH 100
233123#endif
233124#define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
233125#define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
233126#define sqlite3Fts5ParserARG_PARAM ,pParse
233127#define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse=fts5yypParser->pParse;
233128#define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse=pParse;
233129#define fts5YYREALLOC realloc
233130#define fts5YYFREE free
233131#define fts5YYDYNSTACK 0
233132#define sqlite3Fts5ParserCTX_SDECL
233133#define sqlite3Fts5ParserCTX_PDECL
233134#define sqlite3Fts5ParserCTX_PARAM
233135#define sqlite3Fts5ParserCTX_FETCH
233136#define sqlite3Fts5ParserCTX_STORE
233137#define fts5YYNSTATE             35
233138#define fts5YYNRULE              28
233139#define fts5YYNRULE_WITH_ACTION  28
233140#define fts5YYNFTS5TOKEN             16
233141#define fts5YY_MAX_SHIFT         34
233142#define fts5YY_MIN_SHIFTREDUCE   52
233143#define fts5YY_MAX_SHIFTREDUCE   79
233144#define fts5YY_ERROR_ACTION      80
233145#define fts5YY_ACCEPT_ACTION     81
233146#define fts5YY_NO_ACTION         82
233147#define fts5YY_MIN_REDUCE        83
233148#define fts5YY_MAX_REDUCE        110
233149#define fts5YY_MIN_DSTRCTR       16
233150#define fts5YY_MAX_DSTRCTR       24
233151/************* End control #defines *******************************************/
233152#define fts5YY_NLOOKAHEAD ((int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])))
233153
233154/* Define the fts5yytestcase() macro to be a no-op if is not already defined
233155** otherwise.
233156**
233157** Applications can choose to define fts5yytestcase() in the %include section
233158** to a macro that can assist in verifying code coverage.  For production
233159** code the fts5yytestcase() macro should be turned off.  But it is useful
233160** for testing.
233161*/
233162#ifndef fts5yytestcase
233163# define fts5yytestcase(X)
233164#endif
233165
233166/* Macro to determine if stack space has the ability to grow using
233167** heap memory.
233168*/
233169#if fts5YYSTACKDEPTH<=0 || fts5YYDYNSTACK
233170# define fts5YYGROWABLESTACK 1
233171#else
233172# define fts5YYGROWABLESTACK 0
233173#endif
233174
233175/* Guarantee a minimum number of initial stack slots.
233176*/
233177#if fts5YYSTACKDEPTH<=0
233178# undef fts5YYSTACKDEPTH
233179# define fts5YYSTACKDEPTH 2  /* Need a minimum stack size */
233180#endif
233181
233182
233183/* Next are the tables used to determine what action to take based on the
233184** current state and lookahead token.  These tables are used to implement
233185** functions that take a state number and lookahead value and return an
233186** action integer.
233187**
233188** Suppose the action integer is N.  Then the action is determined as
233189** follows
233190**
233191**   0 <= N <= fts5YY_MAX_SHIFT             Shift N.  That is, push the lookahead
233192**                                      token onto the stack and goto state N.
233193**
233194**   N between fts5YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
233195**     and fts5YY_MAX_SHIFTREDUCE           reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
233196**
233197**   N == fts5YY_ERROR_ACTION               A syntax error has occurred.
233198**
233199**   N == fts5YY_ACCEPT_ACTION              The parser accepts its input.
233200**
233201**   N == fts5YY_NO_ACTION                  No such action.  Denotes unused
233202**                                      slots in the fts5yy_action[] table.
233203**
233204**   N between fts5YY_MIN_REDUCE            Reduce by rule N-fts5YY_MIN_REDUCE
233205**     and fts5YY_MAX_REDUCE
233206**
233207** The action table is constructed as a single large table named fts5yy_action[].
233208** Given state S and lookahead X, the action is computed as either:
233209**
233210**    (A)   N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
233211**    (B)   N = fts5yy_default[S]
233212**
233213** The (A) formula is preferred.  The B formula is used instead if
233214** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X.
233215**
233216** The formulas above are for computing the action when the lookahead is
233217** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
233218** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
233219** the fts5yy_shift_ofst[] array.
233220**
233221** The following are the tables generated in this section:
233222**
233223**  fts5yy_action[]        A single table containing all actions.
233224**  fts5yy_lookahead[]     A table containing the lookahead for each entry in
233225**                     fts5yy_action.  Used to detect hash collisions.
233226**  fts5yy_shift_ofst[]    For each state, the offset into fts5yy_action for
233227**                     shifting terminals.
233228**  fts5yy_reduce_ofst[]   For each state, the offset into fts5yy_action for
233229**                     shifting non-terminals after a reduce.
233230**  fts5yy_default[]       Default action for each state.
233231**
233232*********** Begin parsing tables **********************************************/
233233#define fts5YY_ACTTAB_COUNT (105)
233234static const fts5YYACTIONTYPE fts5yy_action[] = {
233235 /*     0 */    81,   20,   96,    6,   28,   99,   98,   26,   26,   18,
233236 /*    10 */    96,    6,   28,   17,   98,   56,   26,   19,   96,    6,
233237 /*    20 */    28,   14,   98,   14,   26,   31,   92,   96,    6,   28,
233238 /*    30 */   108,   98,   25,   26,   21,   96,    6,   28,   78,   98,
233239 /*    40 */    58,   26,   29,   96,    6,   28,  107,   98,   22,   26,
233240 /*    50 */    24,   16,   12,   11,    1,   13,   13,   24,   16,   23,
233241 /*    60 */    11,   33,   34,   13,   97,    8,   27,   32,   98,    7,
233242 /*    70 */    26,    3,    4,    5,    3,    4,    5,    3,   83,    4,
233243 /*    80 */     5,    3,   63,    5,    3,   62,   12,    2,   86,   13,
233244 /*    90 */     9,   30,   10,   10,   54,   57,   75,   78,   78,   53,
233245 /*   100 */    57,   15,   82,   82,   71,
233246};
233247static const fts5YYCODETYPE fts5yy_lookahead[] = {
233248 /*     0 */    16,   17,   18,   19,   20,   22,   22,   24,   24,   17,
233249 /*    10 */    18,   19,   20,    7,   22,    9,   24,   17,   18,   19,
233250 /*    20 */    20,    9,   22,    9,   24,   13,   17,   18,   19,   20,
233251 /*    30 */    26,   22,   24,   24,   17,   18,   19,   20,   15,   22,
233252 /*    40 */     9,   24,   17,   18,   19,   20,   26,   22,   21,   24,
233253 /*    50 */     6,    7,    9,    9,   10,   12,   12,    6,    7,   21,
233254 /*    60 */     9,   24,   25,   12,   18,    5,   20,   14,   22,    5,
233255 /*    70 */    24,    3,    1,    2,    3,    1,    2,    3,    0,    1,
233256 /*    80 */     2,    3,   11,    2,    3,   11,    9,   10,    5,   12,
233257 /*    90 */    23,   24,   10,   10,    8,    9,    9,   15,   15,    8,
233258 /*   100 */     9,    9,   27,   27,   11,   27,   27,   27,   27,   27,
233259 /*   110 */    27,   27,   27,   27,   27,   27,   27,   27,   27,   27,
233260 /*   120 */    27,
233261};
233262#define fts5YY_SHIFT_COUNT    (34)
233263#define fts5YY_SHIFT_MIN      (0)
233264#define fts5YY_SHIFT_MAX      (93)
233265static const unsigned char fts5yy_shift_ofst[] = {
233266 /*     0 */    44,   44,   44,   44,   44,   44,   51,   77,   43,   12,
233267 /*    10 */    14,   83,   82,   14,   23,   23,   31,   31,   71,   74,
233268 /*    20 */    78,   81,   86,   91,    6,   53,   53,   60,   64,   68,
233269 /*    30 */    53,   87,   92,   53,   93,
233270};
233271#define fts5YY_REDUCE_COUNT (17)
233272#define fts5YY_REDUCE_MIN   (-17)
233273#define fts5YY_REDUCE_MAX   (67)
233274static const signed char fts5yy_reduce_ofst[] = {
233275 /*     0 */   -16,   -8,    0,    9,   17,   25,   46,  -17,  -17,   37,
233276 /*    10 */    67,    4,    4,    8,    4,   20,   27,   38,
233277};
233278static const fts5YYACTIONTYPE fts5yy_default[] = {
233279 /*     0 */    80,   80,   80,   80,   80,   80,   95,   80,   80,  105,
233280 /*    10 */    80,  110,  110,   80,  110,  110,   80,   80,   80,   80,
233281 /*    20 */    80,   91,   80,   80,   80,  101,  100,   80,   80,   90,
233282 /*    30 */   103,   80,   80,  104,   80,
233283};
233284/********** End of lemon-generated parsing tables *****************************/
233285
233286/* The next table maps tokens (terminal symbols) into fallback tokens.
233287** If a construct like the following:
233288**
233289**      %fallback ID X Y Z.
233290**
233291** appears in the grammar, then ID becomes a fallback token for X, Y,
233292** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
233293** but it does not parse, the type of the token is changed to ID and
233294** the parse is retried before an error is thrown.
233295**
233296** This feature can be used, for example, to cause some keywords in a language
233297** to revert to identifiers if they keyword does not apply in the context where
233298** it appears.
233299*/
233300#ifdef fts5YYFALLBACK
233301static const fts5YYCODETYPE fts5yyFallback[] = {
233302};
233303#endif /* fts5YYFALLBACK */
233304
233305/* The following structure represents a single element of the
233306** parser's stack.  Information stored includes:
233307**
233308**   +  The state number for the parser at this level of the stack.
233309**
233310**   +  The value of the token stored at this level of the stack.
233311**      (In other words, the "major" token.)
233312**
233313**   +  The semantic value stored at this level of the stack.  This is
233314**      the information used by the action routines in the grammar.
233315**      It is sometimes called the "minor" token.
233316**
233317** After the "shift" half of a SHIFTREDUCE action, the stateno field
233318** actually contains the reduce action for the second half of the
233319** SHIFTREDUCE.
233320*/
233321struct fts5yyStackEntry {
233322  fts5YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
233323  fts5YYCODETYPE major;      /* The major token value.  This is the code
233324                         ** number for the token at this stack level */
233325  fts5YYMINORTYPE minor;     /* The user-supplied minor token value.  This
233326                         ** is the value of the token  */
233327};
233328typedef struct fts5yyStackEntry fts5yyStackEntry;
233329
233330/* The state of the parser is completely contained in an instance of
233331** the following structure */
233332struct fts5yyParser {
233333  fts5yyStackEntry *fts5yytos;          /* Pointer to top element of the stack */
233334#ifdef fts5YYTRACKMAXSTACKDEPTH
233335  int fts5yyhwm;                    /* High-water mark of the stack */
233336#endif
233337#ifndef fts5YYNOERRORRECOVERY
233338  int fts5yyerrcnt;                 /* Shifts left before out of the error */
233339#endif
233340  sqlite3Fts5ParserARG_SDECL                /* A place to hold %extra_argument */
233341  sqlite3Fts5ParserCTX_SDECL                /* A place to hold %extra_context */
233342  fts5yyStackEntry *fts5yystackEnd;           /* Last entry in the stack */
233343  fts5yyStackEntry *fts5yystack;              /* The parser stack */
233344  fts5yyStackEntry fts5yystk0[fts5YYSTACKDEPTH];  /* Initial stack space */
233345};
233346typedef struct fts5yyParser fts5yyParser;
233347
233348/* #include <assert.h> */
233349#ifndef NDEBUG
233350/* #include <stdio.h> */
233351static FILE *fts5yyTraceFILE = 0;
233352static char *fts5yyTracePrompt = 0;
233353#endif /* NDEBUG */
233354
233355#ifndef NDEBUG
233356/*
233357** Turn parser tracing on by giving a stream to which to write the trace
233358** and a prompt to preface each trace message.  Tracing is turned off
233359** by making either argument NULL
233360**
233361** Inputs:
233362** <ul>
233363** <li> A FILE* to which trace output should be written.
233364**      If NULL, then tracing is turned off.
233365** <li> A prefix string written at the beginning of every
233366**      line of trace output.  If NULL, then tracing is
233367**      turned off.
233368** </ul>
233369**
233370** Outputs:
233371** None.
233372*/
233373static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
233374  fts5yyTraceFILE = TraceFILE;
233375  fts5yyTracePrompt = zTracePrompt;
233376  if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
233377  else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
233378}
233379#endif /* NDEBUG */
233380
233381#if defined(fts5YYCOVERAGE) || !defined(NDEBUG)
233382/* For tracing shifts, the names of all terminals and nonterminals
233383** are required.  The following table supplies these names */
233384static const char *const fts5yyTokenName[] = {
233385  /*    0 */ "$",
233386  /*    1 */ "OR",
233387  /*    2 */ "AND",
233388  /*    3 */ "NOT",
233389  /*    4 */ "TERM",
233390  /*    5 */ "COLON",
233391  /*    6 */ "MINUS",
233392  /*    7 */ "LCP",
233393  /*    8 */ "RCP",
233394  /*    9 */ "STRING",
233395  /*   10 */ "LP",
233396  /*   11 */ "RP",
233397  /*   12 */ "CARET",
233398  /*   13 */ "COMMA",
233399  /*   14 */ "PLUS",
233400  /*   15 */ "STAR",
233401  /*   16 */ "input",
233402  /*   17 */ "expr",
233403  /*   18 */ "cnearset",
233404  /*   19 */ "exprlist",
233405  /*   20 */ "colset",
233406  /*   21 */ "colsetlist",
233407  /*   22 */ "nearset",
233408  /*   23 */ "nearphrases",
233409  /*   24 */ "phrase",
233410  /*   25 */ "neardist_opt",
233411  /*   26 */ "star_opt",
233412};
233413#endif /* defined(fts5YYCOVERAGE) || !defined(NDEBUG) */
233414
233415#ifndef NDEBUG
233416/* For tracing reduce actions, the names of all rules are required.
233417*/
233418static const char *const fts5yyRuleName[] = {
233419 /*   0 */ "input ::= expr",
233420 /*   1 */ "colset ::= MINUS LCP colsetlist RCP",
233421 /*   2 */ "colset ::= LCP colsetlist RCP",
233422 /*   3 */ "colset ::= STRING",
233423 /*   4 */ "colset ::= MINUS STRING",
233424 /*   5 */ "colsetlist ::= colsetlist STRING",
233425 /*   6 */ "colsetlist ::= STRING",
233426 /*   7 */ "expr ::= expr AND expr",
233427 /*   8 */ "expr ::= expr OR expr",
233428 /*   9 */ "expr ::= expr NOT expr",
233429 /*  10 */ "expr ::= colset COLON LP expr RP",
233430 /*  11 */ "expr ::= LP expr RP",
233431 /*  12 */ "expr ::= exprlist",
233432 /*  13 */ "exprlist ::= cnearset",
233433 /*  14 */ "exprlist ::= exprlist cnearset",
233434 /*  15 */ "cnearset ::= nearset",
233435 /*  16 */ "cnearset ::= colset COLON nearset",
233436 /*  17 */ "nearset ::= phrase",
233437 /*  18 */ "nearset ::= CARET phrase",
233438 /*  19 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
233439 /*  20 */ "nearphrases ::= phrase",
233440 /*  21 */ "nearphrases ::= nearphrases phrase",
233441 /*  22 */ "neardist_opt ::=",
233442 /*  23 */ "neardist_opt ::= COMMA STRING",
233443 /*  24 */ "phrase ::= phrase PLUS STRING star_opt",
233444 /*  25 */ "phrase ::= STRING star_opt",
233445 /*  26 */ "star_opt ::= STAR",
233446 /*  27 */ "star_opt ::=",
233447};
233448#endif /* NDEBUG */
233449
233450
233451#if fts5YYGROWABLESTACK
233452/*
233453** Try to increase the size of the parser stack.  Return the number
233454** of errors.  Return 0 on success.
233455*/
233456static int fts5yyGrowStack(fts5yyParser *p){
233457  int oldSize = 1 + (int)(p->fts5yystackEnd - p->fts5yystack);
233458  int newSize;
233459  int idx;
233460  fts5yyStackEntry *pNew;
233461
233462  newSize = oldSize*2 + 100;
233463  idx = (int)(p->fts5yytos - p->fts5yystack);
233464  if( p->fts5yystack==p->fts5yystk0 ){
233465    pNew = fts5YYREALLOC(0, newSize*sizeof(pNew[0]));
233466    if( pNew==0 ) return 1;
233467    memcpy(pNew, p->fts5yystack, oldSize*sizeof(pNew[0]));
233468  }else{
233469    pNew = fts5YYREALLOC(p->fts5yystack, newSize*sizeof(pNew[0]));
233470    if( pNew==0 ) return 1;
233471  }
233472  p->fts5yystack = pNew;
233473  p->fts5yytos = &p->fts5yystack[idx];
233474#ifndef NDEBUG
233475  if( fts5yyTraceFILE ){
233476    fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
233477            fts5yyTracePrompt, oldSize, newSize);
233478  }
233479#endif
233480  p->fts5yystackEnd = &p->fts5yystack[newSize-1];
233481  return 0;
233482}
233483#endif /* fts5YYGROWABLESTACK */
233484
233485#if !fts5YYGROWABLESTACK
233486/* For builds that do no have a growable stack, fts5yyGrowStack always
233487** returns an error.
233488*/
233489# define fts5yyGrowStack(X) 1
233490#endif
233491
233492/* Datatype of the argument to the memory allocated passed as the
233493** second argument to sqlite3Fts5ParserAlloc() below.  This can be changed by
233494** putting an appropriate #define in the %include section of the input
233495** grammar.
233496*/
233497#ifndef fts5YYMALLOCARGTYPE
233498# define fts5YYMALLOCARGTYPE size_t
233499#endif
233500
233501/* Initialize a new parser that has already been allocated.
233502*/
233503static void sqlite3Fts5ParserInit(void *fts5yypRawParser sqlite3Fts5ParserCTX_PDECL){
233504  fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yypRawParser;
233505  sqlite3Fts5ParserCTX_STORE
233506#ifdef fts5YYTRACKMAXSTACKDEPTH
233507  fts5yypParser->fts5yyhwm = 0;
233508#endif
233509  fts5yypParser->fts5yystack = fts5yypParser->fts5yystk0;
233510  fts5yypParser->fts5yystackEnd = &fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1];
233511#ifndef fts5YYNOERRORRECOVERY
233512  fts5yypParser->fts5yyerrcnt = -1;
233513#endif
233514  fts5yypParser->fts5yytos = fts5yypParser->fts5yystack;
233515  fts5yypParser->fts5yystack[0].stateno = 0;
233516  fts5yypParser->fts5yystack[0].major = 0;
233517}
233518
233519#ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
233520/*
233521** This function allocates a new parser.
233522** The only argument is a pointer to a function which works like
233523** malloc.
233524**
233525** Inputs:
233526** A pointer to the function used to allocate memory.
233527**
233528** Outputs:
233529** A pointer to a parser.  This pointer is used in subsequent calls
233530** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
233531*/
233532static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE) sqlite3Fts5ParserCTX_PDECL){
233533  fts5yyParser *fts5yypParser;
233534  fts5yypParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
233535  if( fts5yypParser ){
233536    sqlite3Fts5ParserCTX_STORE
233537    sqlite3Fts5ParserInit(fts5yypParser sqlite3Fts5ParserCTX_PARAM);
233538  }
233539  return (void*)fts5yypParser;
233540}
233541#endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
233542
233543
233544/* The following function deletes the "minor type" or semantic value
233545** associated with a symbol.  The symbol can be either a terminal
233546** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
233547** a pointer to the value to be deleted.  The code used to do the
233548** deletions is derived from the %destructor and/or %token_destructor
233549** directives of the input grammar.
233550*/
233551static void fts5yy_destructor(
233552  fts5yyParser *fts5yypParser,    /* The parser */
233553  fts5YYCODETYPE fts5yymajor,     /* Type code for object to destroy */
233554  fts5YYMINORTYPE *fts5yypminor   /* The object to be destroyed */
233555){
233556  sqlite3Fts5ParserARG_FETCH
233557  sqlite3Fts5ParserCTX_FETCH
233558  switch( fts5yymajor ){
233559    /* Here is inserted the actions which take place when a
233560    ** terminal or non-terminal is destroyed.  This can happen
233561    ** when the symbol is popped from the stack during a
233562    ** reduce or during error processing or when a parser is
233563    ** being destroyed before it is finished parsing.
233564    **
233565    ** Note: during a reduce, the only symbols destroyed are those
233566    ** which appear on the RHS of the rule, but which are *not* used
233567    ** inside the C code.
233568    */
233569/********* Begin destructor definitions ***************************************/
233570    case 16: /* input */
233571{
233572 (void)pParse;
233573}
233574      break;
233575    case 17: /* expr */
233576    case 18: /* cnearset */
233577    case 19: /* exprlist */
233578{
233579 sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
233580}
233581      break;
233582    case 20: /* colset */
233583    case 21: /* colsetlist */
233584{
233585 sqlite3_free((fts5yypminor->fts5yy11));
233586}
233587      break;
233588    case 22: /* nearset */
233589    case 23: /* nearphrases */
233590{
233591 sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
233592}
233593      break;
233594    case 24: /* phrase */
233595{
233596 sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
233597}
233598      break;
233599/********* End destructor definitions *****************************************/
233600    default:  break;   /* If no destructor action specified: do nothing */
233601  }
233602}
233603
233604/*
233605** Pop the parser's stack once.
233606**
233607** If there is a destructor routine associated with the token which
233608** is popped from the stack, then call it.
233609*/
233610static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
233611  fts5yyStackEntry *fts5yytos;
233612  assert( pParser->fts5yytos!=0 );
233613  assert( pParser->fts5yytos > pParser->fts5yystack );
233614  fts5yytos = pParser->fts5yytos--;
233615#ifndef NDEBUG
233616  if( fts5yyTraceFILE ){
233617    fprintf(fts5yyTraceFILE,"%sPopping %s\n",
233618      fts5yyTracePrompt,
233619      fts5yyTokenName[fts5yytos->major]);
233620  }
233621#endif
233622  fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
233623}
233624
233625/*
233626** Clear all secondary memory allocations from the parser
233627*/
233628static void sqlite3Fts5ParserFinalize(void *p){
233629  fts5yyParser *pParser = (fts5yyParser*)p;
233630
233631  /* In-lined version of calling fts5yy_pop_parser_stack() for each
233632  ** element left in the stack */
233633  fts5yyStackEntry *fts5yytos = pParser->fts5yytos;
233634  while( fts5yytos>pParser->fts5yystack ){
233635#ifndef NDEBUG
233636    if( fts5yyTraceFILE ){
233637      fprintf(fts5yyTraceFILE,"%sPopping %s\n",
233638        fts5yyTracePrompt,
233639        fts5yyTokenName[fts5yytos->major]);
233640    }
233641#endif
233642    if( fts5yytos->major>=fts5YY_MIN_DSTRCTR ){
233643      fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
233644    }
233645    fts5yytos--;
233646  }
233647
233648#if fts5YYGROWABLESTACK
233649  if( pParser->fts5yystack!=pParser->fts5yystk0 ) fts5YYFREE(pParser->fts5yystack);
233650#endif
233651}
233652
233653#ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
233654/*
233655** Deallocate and destroy a parser.  Destructors are called for
233656** all stack elements before shutting the parser down.
233657**
233658** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
233659** is defined in a %include section of the input grammar) then it is
233660** assumed that the input pointer is never NULL.
233661*/
233662static void sqlite3Fts5ParserFree(
233663  void *p,                    /* The parser to be deleted */
233664  void (*freeProc)(void*)     /* Function used to reclaim memory */
233665){
233666#ifndef fts5YYPARSEFREENEVERNULL
233667  if( p==0 ) return;
233668#endif
233669  sqlite3Fts5ParserFinalize(p);
233670  (*freeProc)(p);
233671}
233672#endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
233673
233674/*
233675** Return the peak depth of the stack for a parser.
233676*/
233677#ifdef fts5YYTRACKMAXSTACKDEPTH
233678static int sqlite3Fts5ParserStackPeak(void *p){
233679  fts5yyParser *pParser = (fts5yyParser*)p;
233680  return pParser->fts5yyhwm;
233681}
233682#endif
233683
233684/* This array of booleans keeps track of the parser statement
233685** coverage.  The element fts5yycoverage[X][Y] is set when the parser
233686** is in state X and has a lookahead token Y.  In a well-tested
233687** systems, every element of this matrix should end up being set.
233688*/
233689#if defined(fts5YYCOVERAGE)
233690static unsigned char fts5yycoverage[fts5YYNSTATE][fts5YYNFTS5TOKEN];
233691#endif
233692
233693/*
233694** Write into out a description of every state/lookahead combination that
233695**
233696**   (1)  has not been used by the parser, and
233697**   (2)  is not a syntax error.
233698**
233699** Return the number of missed state/lookahead combinations.
233700*/
233701#if defined(fts5YYCOVERAGE)
233702static int sqlite3Fts5ParserCoverage(FILE *out){
233703  int stateno, iLookAhead, i;
233704  int nMissed = 0;
233705  for(stateno=0; stateno<fts5YYNSTATE; stateno++){
233706    i = fts5yy_shift_ofst[stateno];
233707    for(iLookAhead=0; iLookAhead<fts5YYNFTS5TOKEN; iLookAhead++){
233708      if( fts5yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
233709      if( fts5yycoverage[stateno][iLookAhead]==0 ) nMissed++;
233710      if( out ){
233711        fprintf(out,"State %d lookahead %s %s\n", stateno,
233712                fts5yyTokenName[iLookAhead],
233713                fts5yycoverage[stateno][iLookAhead] ? "ok" : "missed");
233714      }
233715    }
233716  }
233717  return nMissed;
233718}
233719#endif
233720
233721/*
233722** Find the appropriate action for a parser given the terminal
233723** look-ahead token iLookAhead.
233724*/
233725static fts5YYACTIONTYPE fts5yy_find_shift_action(
233726  fts5YYCODETYPE iLookAhead,    /* The look-ahead token */
233727  fts5YYACTIONTYPE stateno      /* Current state number */
233728){
233729  int i;
233730
233731  if( stateno>fts5YY_MAX_SHIFT ) return stateno;
233732  assert( stateno <= fts5YY_SHIFT_COUNT );
233733#if defined(fts5YYCOVERAGE)
233734  fts5yycoverage[stateno][iLookAhead] = 1;
233735#endif
233736  do{
233737    i = fts5yy_shift_ofst[stateno];
233738    assert( i>=0 );
233739    assert( i<=fts5YY_ACTTAB_COUNT );
233740    assert( i+fts5YYNFTS5TOKEN<=(int)fts5YY_NLOOKAHEAD );
233741    assert( iLookAhead!=fts5YYNOCODE );
233742    assert( iLookAhead < fts5YYNFTS5TOKEN );
233743    i += iLookAhead;
233744    assert( i<(int)fts5YY_NLOOKAHEAD );
233745    if( fts5yy_lookahead[i]!=iLookAhead ){
233746#ifdef fts5YYFALLBACK
233747      fts5YYCODETYPE iFallback;            /* Fallback token */
233748      assert( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0]) );
233749      iFallback = fts5yyFallback[iLookAhead];
233750      if( iFallback!=0 ){
233751#ifndef NDEBUG
233752        if( fts5yyTraceFILE ){
233753          fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
233754             fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
233755        }
233756#endif
233757        assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
233758        iLookAhead = iFallback;
233759        continue;
233760      }
233761#endif
233762#ifdef fts5YYWILDCARD
233763      {
233764        int j = i - iLookAhead + fts5YYWILDCARD;
233765        assert( j<(int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])) );
233766        if( fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0 ){
233767#ifndef NDEBUG
233768          if( fts5yyTraceFILE ){
233769            fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
233770               fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
233771               fts5yyTokenName[fts5YYWILDCARD]);
233772          }
233773#endif /* NDEBUG */
233774          return fts5yy_action[j];
233775        }
233776      }
233777#endif /* fts5YYWILDCARD */
233778      return fts5yy_default[stateno];
233779    }else{
233780      assert( i>=0 && i<(int)(sizeof(fts5yy_action)/sizeof(fts5yy_action[0])) );
233781      return fts5yy_action[i];
233782    }
233783  }while(1);
233784}
233785
233786/*
233787** Find the appropriate action for a parser given the non-terminal
233788** look-ahead token iLookAhead.
233789*/
233790static fts5YYACTIONTYPE fts5yy_find_reduce_action(
233791  fts5YYACTIONTYPE stateno,     /* Current state number */
233792  fts5YYCODETYPE iLookAhead     /* The look-ahead token */
233793){
233794  int i;
233795#ifdef fts5YYERRORSYMBOL
233796  if( stateno>fts5YY_REDUCE_COUNT ){
233797    return fts5yy_default[stateno];
233798  }
233799#else
233800  assert( stateno<=fts5YY_REDUCE_COUNT );
233801#endif
233802  i = fts5yy_reduce_ofst[stateno];
233803  assert( iLookAhead!=fts5YYNOCODE );
233804  i += iLookAhead;
233805#ifdef fts5YYERRORSYMBOL
233806  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
233807    return fts5yy_default[stateno];
233808  }
233809#else
233810  assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
233811  assert( fts5yy_lookahead[i]==iLookAhead );
233812#endif
233813  return fts5yy_action[i];
233814}
233815
233816/*
233817** The following routine is called if the stack overflows.
233818*/
233819static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
233820   sqlite3Fts5ParserARG_FETCH
233821   sqlite3Fts5ParserCTX_FETCH
233822#ifndef NDEBUG
233823   if( fts5yyTraceFILE ){
233824     fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
233825   }
233826#endif
233827   while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
233828   /* Here code is inserted which will execute if the parser
233829   ** stack every overflows */
233830/******** Begin %stack_overflow code ******************************************/
233831
233832  sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
233833/******** End %stack_overflow code ********************************************/
233834   sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument var */
233835   sqlite3Fts5ParserCTX_STORE
233836}
233837
233838/*
233839** Print tracing information for a SHIFT action
233840*/
233841#ifndef NDEBUG
233842static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState, const char *zTag){
233843  if( fts5yyTraceFILE ){
233844    if( fts5yyNewState<fts5YYNSTATE ){
233845      fprintf(fts5yyTraceFILE,"%s%s '%s', go to state %d\n",
233846         fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
233847         fts5yyNewState);
233848    }else{
233849      fprintf(fts5yyTraceFILE,"%s%s '%s', pending reduce %d\n",
233850         fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
233851         fts5yyNewState - fts5YY_MIN_REDUCE);
233852    }
233853  }
233854}
233855#else
233856# define fts5yyTraceShift(X,Y,Z)
233857#endif
233858
233859/*
233860** Perform a shift action.
233861*/
233862static void fts5yy_shift(
233863  fts5yyParser *fts5yypParser,          /* The parser to be shifted */
233864  fts5YYACTIONTYPE fts5yyNewState,      /* The new state to shift in */
233865  fts5YYCODETYPE fts5yyMajor,           /* The major token to shift in */
233866  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor        /* The minor token to shift in */
233867){
233868  fts5yyStackEntry *fts5yytos;
233869  fts5yypParser->fts5yytos++;
233870#ifdef fts5YYTRACKMAXSTACKDEPTH
233871  if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
233872    fts5yypParser->fts5yyhwm++;
233873    assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
233874  }
233875#endif
233876  fts5yytos = fts5yypParser->fts5yytos;
233877  if( fts5yytos>fts5yypParser->fts5yystackEnd ){
233878    if( fts5yyGrowStack(fts5yypParser) ){
233879      fts5yypParser->fts5yytos--;
233880      fts5yyStackOverflow(fts5yypParser);
233881      return;
233882    }
233883    fts5yytos = fts5yypParser->fts5yytos;
233884    assert( fts5yytos <= fts5yypParser->fts5yystackEnd );
233885  }
233886  if( fts5yyNewState > fts5YY_MAX_SHIFT ){
233887    fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
233888  }
233889  fts5yytos->stateno = fts5yyNewState;
233890  fts5yytos->major = fts5yyMajor;
233891  fts5yytos->minor.fts5yy0 = fts5yyMinor;
233892  fts5yyTraceShift(fts5yypParser, fts5yyNewState, "Shift");
233893}
233894
233895/* For rule J, fts5yyRuleInfoLhs[J] contains the symbol on the left-hand side
233896** of that rule */
233897static const fts5YYCODETYPE fts5yyRuleInfoLhs[] = {
233898    16,  /* (0) input ::= expr */
233899    20,  /* (1) colset ::= MINUS LCP colsetlist RCP */
233900    20,  /* (2) colset ::= LCP colsetlist RCP */
233901    20,  /* (3) colset ::= STRING */
233902    20,  /* (4) colset ::= MINUS STRING */
233903    21,  /* (5) colsetlist ::= colsetlist STRING */
233904    21,  /* (6) colsetlist ::= STRING */
233905    17,  /* (7) expr ::= expr AND expr */
233906    17,  /* (8) expr ::= expr OR expr */
233907    17,  /* (9) expr ::= expr NOT expr */
233908    17,  /* (10) expr ::= colset COLON LP expr RP */
233909    17,  /* (11) expr ::= LP expr RP */
233910    17,  /* (12) expr ::= exprlist */
233911    19,  /* (13) exprlist ::= cnearset */
233912    19,  /* (14) exprlist ::= exprlist cnearset */
233913    18,  /* (15) cnearset ::= nearset */
233914    18,  /* (16) cnearset ::= colset COLON nearset */
233915    22,  /* (17) nearset ::= phrase */
233916    22,  /* (18) nearset ::= CARET phrase */
233917    22,  /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
233918    23,  /* (20) nearphrases ::= phrase */
233919    23,  /* (21) nearphrases ::= nearphrases phrase */
233920    25,  /* (22) neardist_opt ::= */
233921    25,  /* (23) neardist_opt ::= COMMA STRING */
233922    24,  /* (24) phrase ::= phrase PLUS STRING star_opt */
233923    24,  /* (25) phrase ::= STRING star_opt */
233924    26,  /* (26) star_opt ::= STAR */
233925    26,  /* (27) star_opt ::= */
233926};
233927
233928/* For rule J, fts5yyRuleInfoNRhs[J] contains the negative of the number
233929** of symbols on the right-hand side of that rule. */
233930static const signed char fts5yyRuleInfoNRhs[] = {
233931   -1,  /* (0) input ::= expr */
233932   -4,  /* (1) colset ::= MINUS LCP colsetlist RCP */
233933   -3,  /* (2) colset ::= LCP colsetlist RCP */
233934   -1,  /* (3) colset ::= STRING */
233935   -2,  /* (4) colset ::= MINUS STRING */
233936   -2,  /* (5) colsetlist ::= colsetlist STRING */
233937   -1,  /* (6) colsetlist ::= STRING */
233938   -3,  /* (7) expr ::= expr AND expr */
233939   -3,  /* (8) expr ::= expr OR expr */
233940   -3,  /* (9) expr ::= expr NOT expr */
233941   -5,  /* (10) expr ::= colset COLON LP expr RP */
233942   -3,  /* (11) expr ::= LP expr RP */
233943   -1,  /* (12) expr ::= exprlist */
233944   -1,  /* (13) exprlist ::= cnearset */
233945   -2,  /* (14) exprlist ::= exprlist cnearset */
233946   -1,  /* (15) cnearset ::= nearset */
233947   -3,  /* (16) cnearset ::= colset COLON nearset */
233948   -1,  /* (17) nearset ::= phrase */
233949   -2,  /* (18) nearset ::= CARET phrase */
233950   -5,  /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
233951   -1,  /* (20) nearphrases ::= phrase */
233952   -2,  /* (21) nearphrases ::= nearphrases phrase */
233953    0,  /* (22) neardist_opt ::= */
233954   -2,  /* (23) neardist_opt ::= COMMA STRING */
233955   -4,  /* (24) phrase ::= phrase PLUS STRING star_opt */
233956   -2,  /* (25) phrase ::= STRING star_opt */
233957   -1,  /* (26) star_opt ::= STAR */
233958    0,  /* (27) star_opt ::= */
233959};
233960
233961static void fts5yy_accept(fts5yyParser*);  /* Forward Declaration */
233962
233963/*
233964** Perform a reduce action and the shift that must immediately
233965** follow the reduce.
233966**
233967** The fts5yyLookahead and fts5yyLookaheadToken parameters provide reduce actions
233968** access to the lookahead token (if any).  The fts5yyLookahead will be fts5YYNOCODE
233969** if the lookahead token has already been consumed.  As this procedure is
233970** only called from one place, optimizing compilers will in-line it, which
233971** means that the extra parameters have no performance impact.
233972*/
233973static fts5YYACTIONTYPE fts5yy_reduce(
233974  fts5yyParser *fts5yypParser,         /* The parser */
233975  unsigned int fts5yyruleno,       /* Number of the rule by which to reduce */
233976  int fts5yyLookahead,             /* Lookahead token, or fts5YYNOCODE if none */
233977  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyLookaheadToken  /* Value of the lookahead token */
233978  sqlite3Fts5ParserCTX_PDECL                   /* %extra_context */
233979){
233980  int fts5yygoto;                     /* The next state */
233981  fts5YYACTIONTYPE fts5yyact;             /* The next action */
233982  fts5yyStackEntry *fts5yymsp;            /* The top of the parser's stack */
233983  int fts5yysize;                     /* Amount to pop the stack */
233984  sqlite3Fts5ParserARG_FETCH
233985  (void)fts5yyLookahead;
233986  (void)fts5yyLookaheadToken;
233987  fts5yymsp = fts5yypParser->fts5yytos;
233988
233989  switch( fts5yyruleno ){
233990  /* Beginning here are the reduction cases.  A typical example
233991  ** follows:
233992  **   case 0:
233993  **  #line <lineno> <grammarfile>
233994  **     { ... }           // User supplied code
233995  **  #line <lineno> <thisfile>
233996  **     break;
233997  */
233998/********** Begin reduce actions **********************************************/
233999        fts5YYMINORTYPE fts5yylhsminor;
234000      case 0: /* input ::= expr */
234001{ sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
234002        break;
234003      case 1: /* colset ::= MINUS LCP colsetlist RCP */
234004{
234005    fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
234006}
234007        break;
234008      case 2: /* colset ::= LCP colsetlist RCP */
234009{ fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
234010        break;
234011      case 3: /* colset ::= STRING */
234012{
234013  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
234014}
234015  fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
234016        break;
234017      case 4: /* colset ::= MINUS STRING */
234018{
234019  fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
234020  fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
234021}
234022        break;
234023      case 5: /* colsetlist ::= colsetlist STRING */
234024{
234025  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
234026  fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
234027        break;
234028      case 6: /* colsetlist ::= STRING */
234029{
234030  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
234031}
234032  fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
234033        break;
234034      case 7: /* expr ::= expr AND expr */
234035{
234036  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
234037}
234038  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
234039        break;
234040      case 8: /* expr ::= expr OR expr */
234041{
234042  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
234043}
234044  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
234045        break;
234046      case 9: /* expr ::= expr NOT expr */
234047{
234048  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
234049}
234050  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
234051        break;
234052      case 10: /* expr ::= colset COLON LP expr RP */
234053{
234054  sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
234055  fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
234056}
234057  fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
234058        break;
234059      case 11: /* expr ::= LP expr RP */
234060{fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
234061        break;
234062      case 12: /* expr ::= exprlist */
234063      case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
234064{fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
234065  fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
234066        break;
234067      case 14: /* exprlist ::= exprlist cnearset */
234068{
234069  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
234070}
234071  fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
234072        break;
234073      case 15: /* cnearset ::= nearset */
234074{
234075  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
234076}
234077  fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
234078        break;
234079      case 16: /* cnearset ::= colset COLON nearset */
234080{
234081  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
234082  sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
234083}
234084  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
234085        break;
234086      case 17: /* nearset ::= phrase */
234087{ fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
234088  fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
234089        break;
234090      case 18: /* nearset ::= CARET phrase */
234091{
234092  sqlite3Fts5ParseSetCaret(fts5yymsp[0].minor.fts5yy53);
234093  fts5yymsp[-1].minor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
234094}
234095        break;
234096      case 19: /* nearset ::= STRING LP nearphrases neardist_opt RP */
234097{
234098  sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
234099  sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
234100  fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
234101}
234102  fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
234103        break;
234104      case 20: /* nearphrases ::= phrase */
234105{
234106  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
234107}
234108  fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
234109        break;
234110      case 21: /* nearphrases ::= nearphrases phrase */
234111{
234112  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
234113}
234114  fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
234115        break;
234116      case 22: /* neardist_opt ::= */
234117{ fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
234118        break;
234119      case 23: /* neardist_opt ::= COMMA STRING */
234120{ fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
234121        break;
234122      case 24: /* phrase ::= phrase PLUS STRING star_opt */
234123{
234124  fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
234125}
234126  fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
234127        break;
234128      case 25: /* phrase ::= STRING star_opt */
234129{
234130  fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
234131}
234132  fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
234133        break;
234134      case 26: /* star_opt ::= STAR */
234135{ fts5yymsp[0].minor.fts5yy4 = 1; }
234136        break;
234137      case 27: /* star_opt ::= */
234138{ fts5yymsp[1].minor.fts5yy4 = 0; }
234139        break;
234140      default:
234141        break;
234142/********** End reduce actions ************************************************/
234143  };
234144  assert( fts5yyruleno<sizeof(fts5yyRuleInfoLhs)/sizeof(fts5yyRuleInfoLhs[0]) );
234145  fts5yygoto = fts5yyRuleInfoLhs[fts5yyruleno];
234146  fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
234147  fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
234148
234149  /* There are no SHIFTREDUCE actions on nonterminals because the table
234150  ** generator has simplified them to pure REDUCE actions. */
234151  assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
234152
234153  /* It is not possible for a REDUCE to be followed by an error */
234154  assert( fts5yyact!=fts5YY_ERROR_ACTION );
234155
234156  fts5yymsp += fts5yysize+1;
234157  fts5yypParser->fts5yytos = fts5yymsp;
234158  fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
234159  fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
234160  fts5yyTraceShift(fts5yypParser, fts5yyact, "... then shift");
234161  return fts5yyact;
234162}
234163
234164/*
234165** The following code executes when the parse fails
234166*/
234167#ifndef fts5YYNOERRORRECOVERY
234168static void fts5yy_parse_failed(
234169  fts5yyParser *fts5yypParser           /* The parser */
234170){
234171  sqlite3Fts5ParserARG_FETCH
234172  sqlite3Fts5ParserCTX_FETCH
234173#ifndef NDEBUG
234174  if( fts5yyTraceFILE ){
234175    fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
234176  }
234177#endif
234178  while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
234179  /* Here code is inserted which will be executed whenever the
234180  ** parser fails */
234181/************ Begin %parse_failure code ***************************************/
234182/************ End %parse_failure code *****************************************/
234183  sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
234184  sqlite3Fts5ParserCTX_STORE
234185}
234186#endif /* fts5YYNOERRORRECOVERY */
234187
234188/*
234189** The following code executes when a syntax error first occurs.
234190*/
234191static void fts5yy_syntax_error(
234192  fts5yyParser *fts5yypParser,           /* The parser */
234193  int fts5yymajor,                   /* The major type of the error token */
234194  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor         /* The minor type of the error token */
234195){
234196  sqlite3Fts5ParserARG_FETCH
234197  sqlite3Fts5ParserCTX_FETCH
234198#define FTS5TOKEN fts5yyminor
234199/************ Begin %syntax_error code ****************************************/
234200
234201  UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
234202  sqlite3Fts5ParseError(
234203    pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
234204  );
234205/************ End %syntax_error code ******************************************/
234206  sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
234207  sqlite3Fts5ParserCTX_STORE
234208}
234209
234210/*
234211** The following is executed when the parser accepts
234212*/
234213static void fts5yy_accept(
234214  fts5yyParser *fts5yypParser           /* The parser */
234215){
234216  sqlite3Fts5ParserARG_FETCH
234217  sqlite3Fts5ParserCTX_FETCH
234218#ifndef NDEBUG
234219  if( fts5yyTraceFILE ){
234220    fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
234221  }
234222#endif
234223#ifndef fts5YYNOERRORRECOVERY
234224  fts5yypParser->fts5yyerrcnt = -1;
234225#endif
234226  assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
234227  /* Here code is inserted which will be executed whenever the
234228  ** parser accepts */
234229/*********** Begin %parse_accept code *****************************************/
234230/*********** End %parse_accept code *******************************************/
234231  sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
234232  sqlite3Fts5ParserCTX_STORE
234233}
234234
234235/* The main parser program.
234236** The first argument is a pointer to a structure obtained from
234237** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
234238** The second argument is the major token number.  The third is
234239** the minor token.  The fourth optional argument is whatever the
234240** user wants (and specified in the grammar) and is available for
234241** use by the action routines.
234242**
234243** Inputs:
234244** <ul>
234245** <li> A pointer to the parser (an opaque structure.)
234246** <li> The major token number.
234247** <li> The minor token number.
234248** <li> An option argument of a grammar-specified type.
234249** </ul>
234250**
234251** Outputs:
234252** None.
234253*/
234254static void sqlite3Fts5Parser(
234255  void *fts5yyp,                   /* The parser */
234256  int fts5yymajor,                 /* The major token code number */
234257  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor       /* The value for the token */
234258  sqlite3Fts5ParserARG_PDECL               /* Optional %extra_argument parameter */
234259){
234260  fts5YYMINORTYPE fts5yyminorunion;
234261  fts5YYACTIONTYPE fts5yyact;   /* The parser action. */
234262#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
234263  int fts5yyendofinput;     /* True if we are at the end of input */
234264#endif
234265#ifdef fts5YYERRORSYMBOL
234266  int fts5yyerrorhit = 0;   /* True if fts5yymajor has invoked an error */
234267#endif
234268  fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yyp;  /* The parser */
234269  sqlite3Fts5ParserCTX_FETCH
234270  sqlite3Fts5ParserARG_STORE
234271
234272  assert( fts5yypParser->fts5yytos!=0 );
234273#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
234274  fts5yyendofinput = (fts5yymajor==0);
234275#endif
234276
234277  fts5yyact = fts5yypParser->fts5yytos->stateno;
234278#ifndef NDEBUG
234279  if( fts5yyTraceFILE ){
234280    if( fts5yyact < fts5YY_MIN_REDUCE ){
234281      fprintf(fts5yyTraceFILE,"%sInput '%s' in state %d\n",
234282              fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact);
234283    }else{
234284      fprintf(fts5yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
234285              fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact-fts5YY_MIN_REDUCE);
234286    }
234287  }
234288#endif
234289
234290  while(1){ /* Exit by "break" */
234291    assert( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystack );
234292    assert( fts5yyact==fts5yypParser->fts5yytos->stateno );
234293    fts5yyact = fts5yy_find_shift_action((fts5YYCODETYPE)fts5yymajor,fts5yyact);
234294    if( fts5yyact >= fts5YY_MIN_REDUCE ){
234295      unsigned int fts5yyruleno = fts5yyact - fts5YY_MIN_REDUCE; /* Reduce by this rule */
234296#ifndef NDEBUG
234297      assert( fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) );
234298      if( fts5yyTraceFILE ){
234299        int fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
234300        if( fts5yysize ){
234301          fprintf(fts5yyTraceFILE, "%sReduce %d [%s]%s, pop back to state %d.\n",
234302            fts5yyTracePrompt,
234303            fts5yyruleno, fts5yyRuleName[fts5yyruleno],
234304            fts5yyruleno<fts5YYNRULE_WITH_ACTION ? "" : " without external action",
234305            fts5yypParser->fts5yytos[fts5yysize].stateno);
234306        }else{
234307          fprintf(fts5yyTraceFILE, "%sReduce %d [%s]%s.\n",
234308            fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno],
234309            fts5yyruleno<fts5YYNRULE_WITH_ACTION ? "" : " without external action");
234310        }
234311      }
234312#endif /* NDEBUG */
234313
234314      /* Check that the stack is large enough to grow by a single entry
234315      ** if the RHS of the rule is empty.  This ensures that there is room
234316      ** enough on the stack to push the LHS value */
234317      if( fts5yyRuleInfoNRhs[fts5yyruleno]==0 ){
234318#ifdef fts5YYTRACKMAXSTACKDEPTH
234319        if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
234320          fts5yypParser->fts5yyhwm++;
234321          assert( fts5yypParser->fts5yyhwm ==
234322                  (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
234323        }
234324#endif
234325        if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
234326          if( fts5yyGrowStack(fts5yypParser) ){
234327            fts5yyStackOverflow(fts5yypParser);
234328            break;
234329          }
234330        }
234331      }
234332      fts5yyact = fts5yy_reduce(fts5yypParser,fts5yyruleno,fts5yymajor,fts5yyminor sqlite3Fts5ParserCTX_PARAM);
234333    }else if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
234334      fts5yy_shift(fts5yypParser,fts5yyact,(fts5YYCODETYPE)fts5yymajor,fts5yyminor);
234335#ifndef fts5YYNOERRORRECOVERY
234336      fts5yypParser->fts5yyerrcnt--;
234337#endif
234338      break;
234339    }else if( fts5yyact==fts5YY_ACCEPT_ACTION ){
234340      fts5yypParser->fts5yytos--;
234341      fts5yy_accept(fts5yypParser);
234342      return;
234343    }else{
234344      assert( fts5yyact == fts5YY_ERROR_ACTION );
234345      fts5yyminorunion.fts5yy0 = fts5yyminor;
234346#ifdef fts5YYERRORSYMBOL
234347      int fts5yymx;
234348#endif
234349#ifndef NDEBUG
234350      if( fts5yyTraceFILE ){
234351        fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
234352      }
234353#endif
234354#ifdef fts5YYERRORSYMBOL
234355      /* A syntax error has occurred.
234356      ** The response to an error depends upon whether or not the
234357      ** grammar defines an error token "ERROR".
234358      **
234359      ** This is what we do if the grammar does define ERROR:
234360      **
234361      **  * Call the %syntax_error function.
234362      **
234363      **  * Begin popping the stack until we enter a state where
234364      **    it is legal to shift the error symbol, then shift
234365      **    the error symbol.
234366      **
234367      **  * Set the error count to three.
234368      **
234369      **  * Begin accepting and shifting new tokens.  No new error
234370      **    processing will occur until three tokens have been
234371      **    shifted successfully.
234372      **
234373      */
234374      if( fts5yypParser->fts5yyerrcnt<0 ){
234375        fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
234376      }
234377      fts5yymx = fts5yypParser->fts5yytos->major;
234378      if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
234379#ifndef NDEBUG
234380        if( fts5yyTraceFILE ){
234381          fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
234382             fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
234383        }
234384#endif
234385        fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
234386        fts5yymajor = fts5YYNOCODE;
234387      }else{
234388        while( fts5yypParser->fts5yytos > fts5yypParser->fts5yystack ){
234389          fts5yyact = fts5yy_find_reduce_action(fts5yypParser->fts5yytos->stateno,
234390                                        fts5YYERRORSYMBOL);
234391          if( fts5yyact<=fts5YY_MAX_SHIFTREDUCE ) break;
234392          fts5yy_pop_parser_stack(fts5yypParser);
234393        }
234394        if( fts5yypParser->fts5yytos <= fts5yypParser->fts5yystack || fts5yymajor==0 ){
234395          fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
234396          fts5yy_parse_failed(fts5yypParser);
234397#ifndef fts5YYNOERRORRECOVERY
234398          fts5yypParser->fts5yyerrcnt = -1;
234399#endif
234400          fts5yymajor = fts5YYNOCODE;
234401        }else if( fts5yymx!=fts5YYERRORSYMBOL ){
234402          fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
234403        }
234404      }
234405      fts5yypParser->fts5yyerrcnt = 3;
234406      fts5yyerrorhit = 1;
234407      if( fts5yymajor==fts5YYNOCODE ) break;
234408      fts5yyact = fts5yypParser->fts5yytos->stateno;
234409#elif defined(fts5YYNOERRORRECOVERY)
234410      /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
234411      ** do any kind of error recovery.  Instead, simply invoke the syntax
234412      ** error routine and continue going as if nothing had happened.
234413      **
234414      ** Applications can set this macro (for example inside %include) if
234415      ** they intend to abandon the parse upon the first syntax error seen.
234416      */
234417      fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
234418      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
234419      break;
234420#else  /* fts5YYERRORSYMBOL is not defined */
234421      /* This is what we do if the grammar does not define ERROR:
234422      **
234423      **  * Report an error message, and throw away the input token.
234424      **
234425      **  * If the input token is $, then fail the parse.
234426      **
234427      ** As before, subsequent error messages are suppressed until
234428      ** three input tokens have been successfully shifted.
234429      */
234430      if( fts5yypParser->fts5yyerrcnt<=0 ){
234431        fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
234432      }
234433      fts5yypParser->fts5yyerrcnt = 3;
234434      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
234435      if( fts5yyendofinput ){
234436        fts5yy_parse_failed(fts5yypParser);
234437#ifndef fts5YYNOERRORRECOVERY
234438        fts5yypParser->fts5yyerrcnt = -1;
234439#endif
234440      }
234441      break;
234442#endif
234443    }
234444  }
234445#ifndef NDEBUG
234446  if( fts5yyTraceFILE ){
234447    fts5yyStackEntry *i;
234448    char cDiv = '[';
234449    fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
234450    for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
234451      fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
234452      cDiv = ' ';
234453    }
234454    fprintf(fts5yyTraceFILE,"]\n");
234455  }
234456#endif
234457  return;
234458}
234459
234460/*
234461** Return the fallback token corresponding to canonical token iToken, or
234462** 0 if iToken has no fallback.
234463*/
234464static int sqlite3Fts5ParserFallback(int iToken){
234465#ifdef fts5YYFALLBACK
234466  assert( iToken<(int)(sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])) );
234467  return fts5yyFallback[iToken];
234468#else
234469  (void)iToken;
234470  return 0;
234471#endif
234472}
234473
234474/*
234475** 2014 May 31
234476**
234477** The author disclaims copyright to this source code.  In place of
234478** a legal notice, here is a blessing:
234479**
234480**    May you do good and not evil.
234481**    May you find forgiveness for yourself and forgive others.
234482**    May you share freely, never taking more than you give.
234483**
234484******************************************************************************
234485*/
234486
234487
234488/* #include "fts5Int.h" */
234489#include <math.h>                 /* amalgamator: keep */
234490
234491/*
234492** Object used to iterate through all "coalesced phrase instances" in
234493** a single column of the current row. If the phrase instances in the
234494** column being considered do not overlap, this object simply iterates
234495** through them. Or, if they do overlap (share one or more tokens in
234496** common), each set of overlapping instances is treated as a single
234497** match. See documentation for the highlight() auxiliary function for
234498** details.
234499**
234500** Usage is:
234501**
234502**   for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
234503**      (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
234504**      rc = fts5CInstIterNext(&iter)
234505**   ){
234506**     printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
234507**   }
234508**
234509*/
234510typedef struct CInstIter CInstIter;
234511struct CInstIter {
234512  const Fts5ExtensionApi *pApi;   /* API offered by current FTS version */
234513  Fts5Context *pFts;              /* First arg to pass to pApi functions */
234514  int iCol;                       /* Column to search */
234515  int iInst;                      /* Next phrase instance index */
234516  int nInst;                      /* Total number of phrase instances */
234517
234518  /* Output variables */
234519  int iStart;                     /* First token in coalesced phrase instance */
234520  int iEnd;                       /* Last token in coalesced phrase instance */
234521};
234522
234523/*
234524** Advance the iterator to the next coalesced phrase instance. Return
234525** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
234526*/
234527static int fts5CInstIterNext(CInstIter *pIter){
234528  int rc = SQLITE_OK;
234529  pIter->iStart = -1;
234530  pIter->iEnd = -1;
234531
234532  while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
234533    int ip; int ic; int io;
234534    rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
234535    if( rc==SQLITE_OK ){
234536      if( ic==pIter->iCol ){
234537        int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
234538        if( pIter->iStart<0 ){
234539          pIter->iStart = io;
234540          pIter->iEnd = iEnd;
234541        }else if( io<=pIter->iEnd ){
234542          if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
234543        }else{
234544          break;
234545        }
234546      }
234547      pIter->iInst++;
234548    }
234549  }
234550
234551  return rc;
234552}
234553
234554/*
234555** Initialize the iterator object indicated by the final parameter to
234556** iterate through coalesced phrase instances in column iCol.
234557*/
234558static int fts5CInstIterInit(
234559  const Fts5ExtensionApi *pApi,
234560  Fts5Context *pFts,
234561  int iCol,
234562  CInstIter *pIter
234563){
234564  int rc;
234565
234566  memset(pIter, 0, sizeof(CInstIter));
234567  pIter->pApi = pApi;
234568  pIter->pFts = pFts;
234569  pIter->iCol = iCol;
234570  rc = pApi->xInstCount(pFts, &pIter->nInst);
234571
234572  if( rc==SQLITE_OK ){
234573    rc = fts5CInstIterNext(pIter);
234574  }
234575
234576  return rc;
234577}
234578
234579
234580
234581/*************************************************************************
234582** Start of highlight() implementation.
234583*/
234584typedef struct HighlightContext HighlightContext;
234585struct HighlightContext {
234586  /* Constant parameters to fts5HighlightCb() */
234587  int iRangeStart;                /* First token to include */
234588  int iRangeEnd;                  /* If non-zero, last token to include */
234589  const char *zOpen;              /* Opening highlight */
234590  const char *zClose;             /* Closing highlight */
234591  const char *zIn;                /* Input text */
234592  int nIn;                        /* Size of input text in bytes */
234593
234594  /* Variables modified by fts5HighlightCb() */
234595  CInstIter iter;                 /* Coalesced Instance Iterator */
234596  int iPos;                       /* Current token offset in zIn[] */
234597  int iOff;                       /* Have copied up to this offset in zIn[] */
234598  int bOpen;                      /* True if highlight is open */
234599  char *zOut;                     /* Output value */
234600};
234601
234602/*
234603** Append text to the HighlightContext output string - p->zOut. Argument
234604** z points to a buffer containing n bytes of text to append. If n is
234605** negative, everything up until the first '\0' is appended to the output.
234606**
234607** If *pRc is set to any value other than SQLITE_OK when this function is
234608** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
234609** *pRc is set to an error code before returning.
234610*/
234611static void fts5HighlightAppend(
234612  int *pRc,
234613  HighlightContext *p,
234614  const char *z, int n
234615){
234616  if( *pRc==SQLITE_OK && z ){
234617    if( n<0 ) n = (int)strlen(z);
234618    p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
234619    if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
234620  }
234621}
234622
234623/*
234624** Tokenizer callback used by implementation of highlight() function.
234625*/
234626static int fts5HighlightCb(
234627  void *pContext,                 /* Pointer to HighlightContext object */
234628  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
234629  const char *pToken,             /* Buffer containing token */
234630  int nToken,                     /* Size of token in bytes */
234631  int iStartOff,                  /* Start byte offset of token */
234632  int iEndOff                     /* End byte offset of token */
234633){
234634  HighlightContext *p = (HighlightContext*)pContext;
234635  int rc = SQLITE_OK;
234636  int iPos;
234637
234638  UNUSED_PARAM2(pToken, nToken);
234639
234640  if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
234641  iPos = p->iPos++;
234642
234643  if( p->iRangeEnd>=0 ){
234644    if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
234645    if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
234646  }
234647
234648  /* If the parenthesis is open, and this token is not part of the current
234649  ** phrase, and the starting byte offset of this token is past the point
234650  ** that has currently been copied into the output buffer, close the
234651  ** parenthesis. */
234652  if( p->bOpen
234653   && (iPos<=p->iter.iStart || p->iter.iStart<0)
234654   && iStartOff>p->iOff
234655  ){
234656    fts5HighlightAppend(&rc, p, p->zClose, -1);
234657    p->bOpen = 0;
234658  }
234659
234660  /* If this is the start of a new phrase, and the highlight is not open:
234661  **
234662  **   * copy text from the input up to the start of the phrase, and
234663  **   * open the highlight.
234664  */
234665  if( iPos==p->iter.iStart && p->bOpen==0 ){
234666    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
234667    fts5HighlightAppend(&rc, p, p->zOpen, -1);
234668    p->iOff = iStartOff;
234669    p->bOpen = 1;
234670  }
234671
234672  if( iPos==p->iter.iEnd ){
234673    if( p->bOpen==0 ){
234674      assert( p->iRangeEnd>=0 );
234675      fts5HighlightAppend(&rc, p, p->zOpen, -1);
234676      p->bOpen = 1;
234677    }
234678    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
234679    p->iOff = iEndOff;
234680
234681    if( rc==SQLITE_OK ){
234682      rc = fts5CInstIterNext(&p->iter);
234683    }
234684  }
234685
234686  if( iPos==p->iRangeEnd ){
234687    if( p->bOpen ){
234688      if( p->iter.iStart>=0 && iPos>=p->iter.iStart ){
234689        fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
234690        p->iOff = iEndOff;
234691      }
234692      fts5HighlightAppend(&rc, p, p->zClose, -1);
234693      p->bOpen = 0;
234694    }
234695    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
234696    p->iOff = iEndOff;
234697  }
234698
234699  return rc;
234700}
234701
234702/*
234703** Implementation of highlight() function.
234704*/
234705static void fts5HighlightFunction(
234706  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
234707  Fts5Context *pFts,              /* First arg to pass to pApi functions */
234708  sqlite3_context *pCtx,          /* Context for returning result/error */
234709  int nVal,                       /* Number of values in apVal[] array */
234710  sqlite3_value **apVal           /* Array of trailing arguments */
234711){
234712  HighlightContext ctx;
234713  int rc;
234714  int iCol;
234715
234716  if( nVal!=3 ){
234717    const char *zErr = "wrong number of arguments to function highlight()";
234718    sqlite3_result_error(pCtx, zErr, -1);
234719    return;
234720  }
234721
234722  iCol = sqlite3_value_int(apVal[0]);
234723  memset(&ctx, 0, sizeof(HighlightContext));
234724  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
234725  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
234726  ctx.iRangeEnd = -1;
234727  rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
234728  if( rc==SQLITE_RANGE ){
234729    sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
234730    rc = SQLITE_OK;
234731  }else if( ctx.zIn ){
234732    if( rc==SQLITE_OK ){
234733      rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
234734    }
234735
234736    if( rc==SQLITE_OK ){
234737      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
234738    }
234739    if( ctx.bOpen ){
234740      fts5HighlightAppend(&rc, &ctx, ctx.zClose, -1);
234741    }
234742    fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
234743
234744    if( rc==SQLITE_OK ){
234745      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
234746    }
234747    sqlite3_free(ctx.zOut);
234748  }
234749  if( rc!=SQLITE_OK ){
234750    sqlite3_result_error_code(pCtx, rc);
234751  }
234752}
234753/*
234754** End of highlight() implementation.
234755**************************************************************************/
234756
234757/*
234758** Context object passed to the fts5SentenceFinderCb() function.
234759*/
234760typedef struct Fts5SFinder Fts5SFinder;
234761struct Fts5SFinder {
234762  int iPos;                       /* Current token position */
234763  int nFirstAlloc;                /* Allocated size of aFirst[] */
234764  int nFirst;                     /* Number of entries in aFirst[] */
234765  int *aFirst;                    /* Array of first token in each sentence */
234766  const char *zDoc;               /* Document being tokenized */
234767};
234768
234769/*
234770** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
234771** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
234772** error occurs.
234773*/
234774static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
234775  if( p->nFirstAlloc==p->nFirst ){
234776    int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
234777    int *aNew;
234778
234779    aNew = (int*)sqlite3_realloc64(p->aFirst, nNew*sizeof(int));
234780    if( aNew==0 ) return SQLITE_NOMEM;
234781    p->aFirst = aNew;
234782    p->nFirstAlloc = nNew;
234783  }
234784  p->aFirst[p->nFirst++] = iAdd;
234785  return SQLITE_OK;
234786}
234787
234788/*
234789** This function is an xTokenize() callback used by the auxiliary snippet()
234790** function. Its job is to identify tokens that are the first in a sentence.
234791** For each such token, an entry is added to the SFinder.aFirst[] array.
234792*/
234793static int fts5SentenceFinderCb(
234794  void *pContext,                 /* Pointer to HighlightContext object */
234795  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
234796  const char *pToken,             /* Buffer containing token */
234797  int nToken,                     /* Size of token in bytes */
234798  int iStartOff,                  /* Start offset of token */
234799  int iEndOff                     /* End offset of token */
234800){
234801  int rc = SQLITE_OK;
234802
234803  UNUSED_PARAM2(pToken, nToken);
234804  UNUSED_PARAM(iEndOff);
234805
234806  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
234807    Fts5SFinder *p = (Fts5SFinder*)pContext;
234808    if( p->iPos>0 ){
234809      int i;
234810      char c = 0;
234811      for(i=iStartOff-1; i>=0; i--){
234812        c = p->zDoc[i];
234813        if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
234814      }
234815      if( i!=iStartOff-1 && (c=='.' || c==':') ){
234816        rc = fts5SentenceFinderAdd(p, p->iPos);
234817      }
234818    }else{
234819      rc = fts5SentenceFinderAdd(p, 0);
234820    }
234821    p->iPos++;
234822  }
234823  return rc;
234824}
234825
234826static int fts5SnippetScore(
234827  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
234828  Fts5Context *pFts,              /* First arg to pass to pApi functions */
234829  int nDocsize,                   /* Size of column in tokens */
234830  unsigned char *aSeen,           /* Array with one element per query phrase */
234831  int iCol,                       /* Column to score */
234832  int iPos,                       /* Starting offset to score */
234833  int nToken,                     /* Max tokens per snippet */
234834  int *pnScore,                   /* OUT: Score */
234835  int *piPos                      /* OUT: Adjusted offset */
234836){
234837  int rc;
234838  int i;
234839  int ip = 0;
234840  int ic = 0;
234841  int iOff = 0;
234842  int iFirst = -1;
234843  int nInst;
234844  int nScore = 0;
234845  int iLast = 0;
234846  sqlite3_int64 iEnd = (sqlite3_int64)iPos + nToken;
234847
234848  rc = pApi->xInstCount(pFts, &nInst);
234849  for(i=0; i<nInst && rc==SQLITE_OK; i++){
234850    rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
234851    if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<iEnd ){
234852      nScore += (aSeen[ip] ? 1 : 1000);
234853      aSeen[ip] = 1;
234854      if( iFirst<0 ) iFirst = iOff;
234855      iLast = iOff + pApi->xPhraseSize(pFts, ip);
234856    }
234857  }
234858
234859  *pnScore = nScore;
234860  if( piPos ){
234861    sqlite3_int64 iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
234862    if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
234863    if( iAdj<0 ) iAdj = 0;
234864    *piPos = (int)iAdj;
234865  }
234866
234867  return rc;
234868}
234869
234870/*
234871** Return the value in pVal interpreted as utf-8 text. Except, if pVal
234872** contains a NULL value, return a pointer to a static string zero
234873** bytes in length instead of a NULL pointer.
234874*/
234875static const char *fts5ValueToText(sqlite3_value *pVal){
234876  const char *zRet = (const char*)sqlite3_value_text(pVal);
234877  return zRet ? zRet : "";
234878}
234879
234880/*
234881** Implementation of snippet() function.
234882*/
234883static void fts5SnippetFunction(
234884  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
234885  Fts5Context *pFts,              /* First arg to pass to pApi functions */
234886  sqlite3_context *pCtx,          /* Context for returning result/error */
234887  int nVal,                       /* Number of values in apVal[] array */
234888  sqlite3_value **apVal           /* Array of trailing arguments */
234889){
234890  HighlightContext ctx;
234891  int rc = SQLITE_OK;             /* Return code */
234892  int iCol;                       /* 1st argument to snippet() */
234893  const char *zEllips;            /* 4th argument to snippet() */
234894  int nToken;                     /* 5th argument to snippet() */
234895  int nInst = 0;                  /* Number of instance matches this row */
234896  int i;                          /* Used to iterate through instances */
234897  int nPhrase;                    /* Number of phrases in query */
234898  unsigned char *aSeen;           /* Array of "seen instance" flags */
234899  int iBestCol;                   /* Column containing best snippet */
234900  int iBestStart = 0;             /* First token of best snippet */
234901  int nBestScore = 0;             /* Score of best snippet */
234902  int nColSize = 0;               /* Total size of iBestCol in tokens */
234903  Fts5SFinder sFinder;            /* Used to find the beginnings of sentences */
234904  int nCol;
234905
234906  if( nVal!=5 ){
234907    const char *zErr = "wrong number of arguments to function snippet()";
234908    sqlite3_result_error(pCtx, zErr, -1);
234909    return;
234910  }
234911
234912  nCol = pApi->xColumnCount(pFts);
234913  memset(&ctx, 0, sizeof(HighlightContext));
234914  iCol = sqlite3_value_int(apVal[0]);
234915  ctx.zOpen = fts5ValueToText(apVal[1]);
234916  ctx.zClose = fts5ValueToText(apVal[2]);
234917  ctx.iRangeEnd = -1;
234918  zEllips = fts5ValueToText(apVal[3]);
234919  nToken = sqlite3_value_int(apVal[4]);
234920
234921  iBestCol = (iCol>=0 ? iCol : 0);
234922  nPhrase = pApi->xPhraseCount(pFts);
234923  aSeen = sqlite3_malloc(nPhrase);
234924  if( aSeen==0 ){
234925    rc = SQLITE_NOMEM;
234926  }
234927  if( rc==SQLITE_OK ){
234928    rc = pApi->xInstCount(pFts, &nInst);
234929  }
234930
234931  memset(&sFinder, 0, sizeof(Fts5SFinder));
234932  for(i=0; i<nCol; i++){
234933    if( iCol<0 || iCol==i ){
234934      int nDoc;
234935      int nDocsize;
234936      int ii;
234937      sFinder.iPos = 0;
234938      sFinder.nFirst = 0;
234939      rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
234940      if( rc!=SQLITE_OK ) break;
234941      rc = pApi->xTokenize(pFts,
234942          sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
234943      );
234944      if( rc!=SQLITE_OK ) break;
234945      rc = pApi->xColumnSize(pFts, i, &nDocsize);
234946      if( rc!=SQLITE_OK ) break;
234947
234948      for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
234949        int ip, ic, io;
234950        int iAdj;
234951        int nScore;
234952        int jj;
234953
234954        rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
234955        if( ic!=i ) continue;
234956        if( io>nDocsize ) rc = FTS5_CORRUPT;
234957        if( rc!=SQLITE_OK ) continue;
234958        memset(aSeen, 0, nPhrase);
234959        rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
234960            io, nToken, &nScore, &iAdj
234961        );
234962        if( rc==SQLITE_OK && nScore>nBestScore ){
234963          nBestScore = nScore;
234964          iBestCol = i;
234965          iBestStart = iAdj;
234966          nColSize = nDocsize;
234967        }
234968
234969        if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
234970          for(jj=0; jj<(sFinder.nFirst-1); jj++){
234971            if( sFinder.aFirst[jj+1]>io ) break;
234972          }
234973
234974          if( sFinder.aFirst[jj]<io ){
234975            memset(aSeen, 0, nPhrase);
234976            rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
234977              sFinder.aFirst[jj], nToken, &nScore, 0
234978            );
234979
234980            nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
234981            if( rc==SQLITE_OK && nScore>nBestScore ){
234982              nBestScore = nScore;
234983              iBestCol = i;
234984              iBestStart = sFinder.aFirst[jj];
234985              nColSize = nDocsize;
234986            }
234987          }
234988        }
234989      }
234990    }
234991  }
234992
234993  if( rc==SQLITE_OK ){
234994    rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
234995  }
234996  if( rc==SQLITE_OK && nColSize==0 ){
234997    rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
234998  }
234999  if( ctx.zIn ){
235000    if( rc==SQLITE_OK ){
235001      rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
235002    }
235003
235004    ctx.iRangeStart = iBestStart;
235005    ctx.iRangeEnd = iBestStart + nToken - 1;
235006
235007    if( iBestStart>0 ){
235008      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
235009    }
235010
235011    /* Advance iterator ctx.iter so that it points to the first coalesced
235012    ** phrase instance at or following position iBestStart. */
235013    while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
235014      rc = fts5CInstIterNext(&ctx.iter);
235015    }
235016
235017    if( rc==SQLITE_OK ){
235018      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
235019    }
235020    if( ctx.bOpen ){
235021      fts5HighlightAppend(&rc, &ctx, ctx.zClose, -1);
235022    }
235023    if( ctx.iRangeEnd>=(nColSize-1) ){
235024      fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
235025    }else{
235026      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
235027    }
235028  }
235029  if( rc==SQLITE_OK ){
235030    sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
235031  }else{
235032    sqlite3_result_error_code(pCtx, rc);
235033  }
235034  sqlite3_free(ctx.zOut);
235035  sqlite3_free(aSeen);
235036  sqlite3_free(sFinder.aFirst);
235037}
235038
235039/************************************************************************/
235040
235041/*
235042** The first time the bm25() function is called for a query, an instance
235043** of the following structure is allocated and populated.
235044*/
235045typedef struct Fts5Bm25Data Fts5Bm25Data;
235046struct Fts5Bm25Data {
235047  int nPhrase;                    /* Number of phrases in query */
235048  double avgdl;                   /* Average number of tokens in each row */
235049  double *aIDF;                   /* IDF for each phrase */
235050  double *aFreq;                  /* Array used to calculate phrase freq. */
235051};
235052
235053/*
235054** Callback used by fts5Bm25GetData() to count the number of rows in the
235055** table matched by each individual phrase within the query.
235056*/
235057static int fts5CountCb(
235058  const Fts5ExtensionApi *pApi,
235059  Fts5Context *pFts,
235060  void *pUserData                 /* Pointer to sqlite3_int64 variable */
235061){
235062  sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
235063  UNUSED_PARAM2(pApi, pFts);
235064  (*pn)++;
235065  return SQLITE_OK;
235066}
235067
235068/*
235069** Set *ppData to point to the Fts5Bm25Data object for the current query.
235070** If the object has not already been allocated, allocate and populate it
235071** now.
235072*/
235073static int fts5Bm25GetData(
235074  const Fts5ExtensionApi *pApi,
235075  Fts5Context *pFts,
235076  Fts5Bm25Data **ppData           /* OUT: bm25-data object for this query */
235077){
235078  int rc = SQLITE_OK;             /* Return code */
235079  Fts5Bm25Data *p;                /* Object to return */
235080
235081  p = (Fts5Bm25Data*)pApi->xGetAuxdata(pFts, 0);
235082  if( p==0 ){
235083    int nPhrase;                  /* Number of phrases in query */
235084    sqlite3_int64 nRow = 0;       /* Number of rows in table */
235085    sqlite3_int64 nToken = 0;     /* Number of tokens in table */
235086    sqlite3_int64 nByte;          /* Bytes of space to allocate */
235087    int i;
235088
235089    /* Allocate the Fts5Bm25Data object */
235090    nPhrase = pApi->xPhraseCount(pFts);
235091    nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
235092    p = (Fts5Bm25Data*)sqlite3_malloc64(nByte);
235093    if( p==0 ){
235094      rc = SQLITE_NOMEM;
235095    }else{
235096      memset(p, 0, (size_t)nByte);
235097      p->nPhrase = nPhrase;
235098      p->aIDF = (double*)&p[1];
235099      p->aFreq = &p->aIDF[nPhrase];
235100    }
235101
235102    /* Calculate the average document length for this FTS5 table */
235103    if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
235104    assert( rc!=SQLITE_OK || nRow>0 );
235105    if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
235106    if( rc==SQLITE_OK ) p->avgdl = (double)nToken  / (double)nRow;
235107
235108    /* Calculate an IDF for each phrase in the query */
235109    for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
235110      sqlite3_int64 nHit = 0;
235111      rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
235112      if( rc==SQLITE_OK ){
235113        /* Calculate the IDF (Inverse Document Frequency) for phrase i.
235114        ** This is done using the standard BM25 formula as found on wikipedia:
235115        **
235116        **   IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
235117        **
235118        ** where "N" is the total number of documents in the set and nHit
235119        ** is the number that contain at least one instance of the phrase
235120        ** under consideration.
235121        **
235122        ** The problem with this is that if (N < 2*nHit), the IDF is
235123        ** negative. Which is undesirable. So the mimimum allowable IDF is
235124        ** (1e-6) - roughly the same as a term that appears in just over
235125        ** half of set of 5,000,000 documents.  */
235126        double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
235127        if( idf<=0.0 ) idf = 1e-6;
235128        p->aIDF[i] = idf;
235129      }
235130    }
235131
235132    if( rc!=SQLITE_OK ){
235133      sqlite3_free(p);
235134    }else{
235135      rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
235136    }
235137    if( rc!=SQLITE_OK ) p = 0;
235138  }
235139  *ppData = p;
235140  return rc;
235141}
235142
235143/*
235144** Implementation of bm25() function.
235145*/
235146static void fts5Bm25Function(
235147  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
235148  Fts5Context *pFts,              /* First arg to pass to pApi functions */
235149  sqlite3_context *pCtx,          /* Context for returning result/error */
235150  int nVal,                       /* Number of values in apVal[] array */
235151  sqlite3_value **apVal           /* Array of trailing arguments */
235152){
235153  const double k1 = 1.2;          /* Constant "k1" from BM25 formula */
235154  const double b = 0.75;          /* Constant "b" from BM25 formula */
235155  int rc;                         /* Error code */
235156  double score = 0.0;             /* SQL function return value */
235157  Fts5Bm25Data *pData;            /* Values allocated/calculated once only */
235158  int i;                          /* Iterator variable */
235159  int nInst = 0;                  /* Value returned by xInstCount() */
235160  double D = 0.0;                 /* Total number of tokens in row */
235161  double *aFreq = 0;              /* Array of phrase freq. for current row */
235162
235163  /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
235164  ** for each phrase in the query for the current row. */
235165  rc = fts5Bm25GetData(pApi, pFts, &pData);
235166  if( rc==SQLITE_OK ){
235167    aFreq = pData->aFreq;
235168    memset(aFreq, 0, sizeof(double) * pData->nPhrase);
235169    rc = pApi->xInstCount(pFts, &nInst);
235170  }
235171  for(i=0; rc==SQLITE_OK && i<nInst; i++){
235172    int ip; int ic; int io;
235173    rc = pApi->xInst(pFts, i, &ip, &ic, &io);
235174    if( rc==SQLITE_OK ){
235175      double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
235176      aFreq[ip] += w;
235177    }
235178  }
235179
235180  /* Figure out the total size of the current row in tokens. */
235181  if( rc==SQLITE_OK ){
235182    int nTok;
235183    rc = pApi->xColumnSize(pFts, -1, &nTok);
235184    D = (double)nTok;
235185  }
235186
235187  /* Determine and return the BM25 score for the current row. Or, if an
235188  ** error has occurred, throw an exception. */
235189  if( rc==SQLITE_OK ){
235190    for(i=0; i<pData->nPhrase; i++){
235191      score += pData->aIDF[i] * (
235192          ( aFreq[i] * (k1 + 1.0) ) /
235193          ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
235194      );
235195    }
235196    sqlite3_result_double(pCtx, -1.0 * score);
235197  }else{
235198    sqlite3_result_error_code(pCtx, rc);
235199  }
235200}
235201
235202static int sqlite3Fts5AuxInit(fts5_api *pApi){
235203  struct Builtin {
235204    const char *zFunc;            /* Function name (nul-terminated) */
235205    void *pUserData;              /* User-data pointer */
235206    fts5_extension_function xFunc;/* Callback function */
235207    void (*xDestroy)(void*);      /* Destructor function */
235208  } aBuiltin [] = {
235209    { "snippet",   0, fts5SnippetFunction, 0 },
235210    { "highlight", 0, fts5HighlightFunction, 0 },
235211    { "bm25",      0, fts5Bm25Function,    0 },
235212  };
235213  int rc = SQLITE_OK;             /* Return code */
235214  int i;                          /* To iterate through builtin functions */
235215
235216  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
235217    rc = pApi->xCreateFunction(pApi,
235218        aBuiltin[i].zFunc,
235219        aBuiltin[i].pUserData,
235220        aBuiltin[i].xFunc,
235221        aBuiltin[i].xDestroy
235222    );
235223  }
235224
235225  return rc;
235226}
235227
235228/*
235229** 2014 May 31
235230**
235231** The author disclaims copyright to this source code.  In place of
235232** a legal notice, here is a blessing:
235233**
235234**    May you do good and not evil.
235235**    May you find forgiveness for yourself and forgive others.
235236**    May you share freely, never taking more than you give.
235237**
235238******************************************************************************
235239*/
235240
235241
235242
235243/* #include "fts5Int.h" */
235244
235245static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
235246  if( (u32)pBuf->nSpace<nByte ){
235247    u64 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
235248    u8 *pNew;
235249    while( nNew<nByte ){
235250      nNew = nNew * 2;
235251    }
235252    pNew = sqlite3_realloc64(pBuf->p, nNew);
235253    if( pNew==0 ){
235254      *pRc = SQLITE_NOMEM;
235255      return 1;
235256    }else{
235257      pBuf->nSpace = (int)nNew;
235258      pBuf->p = pNew;
235259    }
235260  }
235261  return 0;
235262}
235263
235264
235265/*
235266** Encode value iVal as an SQLite varint and append it to the buffer object
235267** pBuf. If an OOM error occurs, set the error code in p.
235268*/
235269static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
235270  if( fts5BufferGrow(pRc, pBuf, 9) ) return;
235271  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
235272}
235273
235274static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
235275  aBuf[0] = (iVal>>24) & 0x00FF;
235276  aBuf[1] = (iVal>>16) & 0x00FF;
235277  aBuf[2] = (iVal>> 8) & 0x00FF;
235278  aBuf[3] = (iVal>> 0) & 0x00FF;
235279}
235280
235281static int sqlite3Fts5Get32(const u8 *aBuf){
235282  return (int)((((u32)aBuf[0])<<24) + (aBuf[1]<<16) + (aBuf[2]<<8) + aBuf[3]);
235283}
235284
235285/*
235286** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
235287** the error code in p. If an error has already occurred when this function
235288** is called, it is a no-op.
235289*/
235290static void sqlite3Fts5BufferAppendBlob(
235291  int *pRc,
235292  Fts5Buffer *pBuf,
235293  u32 nData,
235294  const u8 *pData
235295){
235296  if( nData ){
235297    if( fts5BufferGrow(pRc, pBuf, nData) ) return;
235298    assert( pBuf->p!=0 );
235299    memcpy(&pBuf->p[pBuf->n], pData, nData);
235300    pBuf->n += nData;
235301  }
235302}
235303
235304/*
235305** Append the nul-terminated string zStr to the buffer pBuf. This function
235306** ensures that the byte following the buffer data is set to 0x00, even
235307** though this byte is not included in the pBuf->n count.
235308*/
235309static void sqlite3Fts5BufferAppendString(
235310  int *pRc,
235311  Fts5Buffer *pBuf,
235312  const char *zStr
235313){
235314  int nStr = (int)strlen(zStr);
235315  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
235316  pBuf->n--;
235317}
235318
235319/*
235320** Argument zFmt is a printf() style format string. This function performs
235321** the printf() style processing, then appends the results to buffer pBuf.
235322**
235323** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
235324** following the buffer data is set to 0x00, even though this byte is not
235325** included in the pBuf->n count.
235326*/
235327static void sqlite3Fts5BufferAppendPrintf(
235328  int *pRc,
235329  Fts5Buffer *pBuf,
235330  char *zFmt, ...
235331){
235332  if( *pRc==SQLITE_OK ){
235333    char *zTmp;
235334    va_list ap;
235335    va_start(ap, zFmt);
235336    zTmp = sqlite3_vmprintf(zFmt, ap);
235337    va_end(ap);
235338
235339    if( zTmp==0 ){
235340      *pRc = SQLITE_NOMEM;
235341    }else{
235342      sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
235343      sqlite3_free(zTmp);
235344    }
235345  }
235346}
235347
235348static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
235349  char *zRet = 0;
235350  if( *pRc==SQLITE_OK ){
235351    va_list ap;
235352    va_start(ap, zFmt);
235353    zRet = sqlite3_vmprintf(zFmt, ap);
235354    va_end(ap);
235355    if( zRet==0 ){
235356      *pRc = SQLITE_NOMEM;
235357    }
235358  }
235359  return zRet;
235360}
235361
235362
235363/*
235364** Free any buffer allocated by pBuf. Zero the structure before returning.
235365*/
235366static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
235367  sqlite3_free(pBuf->p);
235368  memset(pBuf, 0, sizeof(Fts5Buffer));
235369}
235370
235371/*
235372** Zero the contents of the buffer object. But do not free the associated
235373** memory allocation.
235374*/
235375static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
235376  pBuf->n = 0;
235377}
235378
235379/*
235380** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
235381** the error code in p. If an error has already occurred when this function
235382** is called, it is a no-op.
235383*/
235384static void sqlite3Fts5BufferSet(
235385  int *pRc,
235386  Fts5Buffer *pBuf,
235387  int nData,
235388  const u8 *pData
235389){
235390  pBuf->n = 0;
235391  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
235392}
235393
235394static int sqlite3Fts5PoslistNext64(
235395  const u8 *a, int n,             /* Buffer containing poslist */
235396  int *pi,                        /* IN/OUT: Offset within a[] */
235397  i64 *piOff                      /* IN/OUT: Current offset */
235398){
235399  int i = *pi;
235400  assert( a!=0 || i==0 );
235401  if( i>=n ){
235402    /* EOF */
235403    *piOff = -1;
235404    return 1;
235405  }else{
235406    i64 iOff = *piOff;
235407    u32 iVal;
235408    assert( a!=0 );
235409    fts5FastGetVarint32(a, i, iVal);
235410    if( iVal<=1 ){
235411      if( iVal==0 ){
235412        *pi = i;
235413        return 0;
235414      }
235415      fts5FastGetVarint32(a, i, iVal);
235416      iOff = ((i64)iVal) << 32;
235417      assert( iOff>=0 );
235418      fts5FastGetVarint32(a, i, iVal);
235419      if( iVal<2 ){
235420        /* This is a corrupt record. So stop parsing it here. */
235421        *piOff = -1;
235422        return 1;
235423      }
235424      *piOff = iOff + ((iVal-2) & 0x7FFFFFFF);
235425    }else{
235426      *piOff = (iOff & (i64)0x7FFFFFFF<<32)+((iOff + (iVal-2)) & 0x7FFFFFFF);
235427    }
235428    *pi = i;
235429    assert_nc( *piOff>=iOff );
235430    return 0;
235431  }
235432}
235433
235434
235435/*
235436** Advance the iterator object passed as the only argument. Return true
235437** if the iterator reaches EOF, or false otherwise.
235438*/
235439static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
235440  if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
235441    pIter->bEof = 1;
235442  }
235443  return pIter->bEof;
235444}
235445
235446static int sqlite3Fts5PoslistReaderInit(
235447  const u8 *a, int n,             /* Poslist buffer to iterate through */
235448  Fts5PoslistReader *pIter        /* Iterator object to initialize */
235449){
235450  memset(pIter, 0, sizeof(*pIter));
235451  pIter->a = a;
235452  pIter->n = n;
235453  sqlite3Fts5PoslistReaderNext(pIter);
235454  return pIter->bEof;
235455}
235456
235457/*
235458** Append position iPos to the position list being accumulated in buffer
235459** pBuf, which must be already be large enough to hold the new data.
235460** The previous position written to this list is *piPrev. *piPrev is set
235461** to iPos before returning.
235462*/
235463static void sqlite3Fts5PoslistSafeAppend(
235464  Fts5Buffer *pBuf,
235465  i64 *piPrev,
235466  i64 iPos
235467){
235468  if( iPos>=*piPrev ){
235469    static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
235470    if( (iPos & colmask) != (*piPrev & colmask) ){
235471      pBuf->p[pBuf->n++] = 1;
235472      pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
235473      *piPrev = (iPos & colmask);
235474    }
235475    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
235476    *piPrev = iPos;
235477  }
235478}
235479
235480static int sqlite3Fts5PoslistWriterAppend(
235481  Fts5Buffer *pBuf,
235482  Fts5PoslistWriter *pWriter,
235483  i64 iPos
235484){
235485  int rc = 0;   /* Initialized only to suppress erroneous warning from Clang */
235486  if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
235487  sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
235488  return SQLITE_OK;
235489}
235490
235491static void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte){
235492  void *pRet = 0;
235493  if( *pRc==SQLITE_OK ){
235494    pRet = sqlite3_malloc64(nByte);
235495    if( pRet==0 ){
235496      if( nByte>0 ) *pRc = SQLITE_NOMEM;
235497    }else{
235498      memset(pRet, 0, (size_t)nByte);
235499    }
235500  }
235501  return pRet;
235502}
235503
235504/*
235505** Return a nul-terminated copy of the string indicated by pIn. If nIn
235506** is non-negative, then it is the length of the string in bytes. Otherwise,
235507** the length of the string is determined using strlen().
235508**
235509** It is the responsibility of the caller to eventually free the returned
235510** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
235511*/
235512static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
235513  char *zRet = 0;
235514  if( *pRc==SQLITE_OK ){
235515    if( nIn<0 ){
235516      nIn = (int)strlen(pIn);
235517    }
235518    zRet = (char*)sqlite3_malloc(nIn+1);
235519    if( zRet ){
235520      memcpy(zRet, pIn, nIn);
235521      zRet[nIn] = '\0';
235522    }else{
235523      *pRc = SQLITE_NOMEM;
235524    }
235525  }
235526  return zRet;
235527}
235528
235529
235530/*
235531** Return true if character 't' may be part of an FTS5 bareword, or false
235532** otherwise. Characters that may be part of barewords:
235533**
235534**   * All non-ASCII characters,
235535**   * The 52 upper and lower case ASCII characters, and
235536**   * The 10 integer ASCII characters.
235537**   * The underscore character "_" (0x5F).
235538**   * The unicode "subsitute" character (0x1A).
235539*/
235540static int sqlite3Fts5IsBareword(char t){
235541  u8 aBareword[128] = {
235542    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00 .. 0x0F */
235543    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 1, 0, 0, 0, 0, 0,   /* 0x10 .. 0x1F */
235544    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20 .. 0x2F */
235545    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30 .. 0x3F */
235546    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40 .. 0x4F */
235547    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 1,   /* 0x50 .. 0x5F */
235548    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60 .. 0x6F */
235549    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 0    /* 0x70 .. 0x7F */
235550  };
235551
235552  return (t & 0x80) || aBareword[(int)t];
235553}
235554
235555
235556/*************************************************************************
235557*/
235558typedef struct Fts5TermsetEntry Fts5TermsetEntry;
235559struct Fts5TermsetEntry {
235560  char *pTerm;
235561  int nTerm;
235562  int iIdx;                       /* Index (main or aPrefix[] entry) */
235563  Fts5TermsetEntry *pNext;
235564};
235565
235566struct Fts5Termset {
235567  Fts5TermsetEntry *apHash[512];
235568};
235569
235570static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
235571  int rc = SQLITE_OK;
235572  *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
235573  return rc;
235574}
235575
235576static int sqlite3Fts5TermsetAdd(
235577  Fts5Termset *p,
235578  int iIdx,
235579  const char *pTerm, int nTerm,
235580  int *pbPresent
235581){
235582  int rc = SQLITE_OK;
235583  *pbPresent = 0;
235584  if( p ){
235585    int i;
235586    u32 hash = 13;
235587    Fts5TermsetEntry *pEntry;
235588
235589    /* Calculate a hash value for this term. This is the same hash checksum
235590    ** used by the fts5_hash.c module. This is not important for correct
235591    ** operation of the module, but is necessary to ensure that some tests
235592    ** designed to produce hash table collisions really do work.  */
235593    for(i=nTerm-1; i>=0; i--){
235594      hash = (hash << 3) ^ hash ^ pTerm[i];
235595    }
235596    hash = (hash << 3) ^ hash ^ iIdx;
235597    hash = hash % ArraySize(p->apHash);
235598
235599    for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
235600      if( pEntry->iIdx==iIdx
235601          && pEntry->nTerm==nTerm
235602          && memcmp(pEntry->pTerm, pTerm, nTerm)==0
235603      ){
235604        *pbPresent = 1;
235605        break;
235606      }
235607    }
235608
235609    if( pEntry==0 ){
235610      pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
235611      if( pEntry ){
235612        pEntry->pTerm = (char*)&pEntry[1];
235613        pEntry->nTerm = nTerm;
235614        pEntry->iIdx = iIdx;
235615        memcpy(pEntry->pTerm, pTerm, nTerm);
235616        pEntry->pNext = p->apHash[hash];
235617        p->apHash[hash] = pEntry;
235618      }
235619    }
235620  }
235621
235622  return rc;
235623}
235624
235625static void sqlite3Fts5TermsetFree(Fts5Termset *p){
235626  if( p ){
235627    u32 i;
235628    for(i=0; i<ArraySize(p->apHash); i++){
235629      Fts5TermsetEntry *pEntry = p->apHash[i];
235630      while( pEntry ){
235631        Fts5TermsetEntry *pDel = pEntry;
235632        pEntry = pEntry->pNext;
235633        sqlite3_free(pDel);
235634      }
235635    }
235636    sqlite3_free(p);
235637  }
235638}
235639
235640/*
235641** 2014 Jun 09
235642**
235643** The author disclaims copyright to this source code.  In place of
235644** a legal notice, here is a blessing:
235645**
235646**    May you do good and not evil.
235647**    May you find forgiveness for yourself and forgive others.
235648**    May you share freely, never taking more than you give.
235649**
235650******************************************************************************
235651**
235652** This is an SQLite module implementing full-text search.
235653*/
235654
235655
235656/* #include "fts5Int.h" */
235657
235658#define FTS5_DEFAULT_PAGE_SIZE   4050
235659#define FTS5_DEFAULT_AUTOMERGE      4
235660#define FTS5_DEFAULT_USERMERGE      4
235661#define FTS5_DEFAULT_CRISISMERGE   16
235662#define FTS5_DEFAULT_HASHSIZE    (1024*1024)
235663
235664#define FTS5_DEFAULT_DELETE_AUTOMERGE 10      /* default 10% */
235665
235666/* Maximum allowed page size */
235667#define FTS5_MAX_PAGE_SIZE (64*1024)
235668
235669static int fts5_iswhitespace(char x){
235670  return (x==' ');
235671}
235672
235673static int fts5_isopenquote(char x){
235674  return (x=='"' || x=='\'' || x=='[' || x=='`');
235675}
235676
235677/*
235678** Argument pIn points to a character that is part of a nul-terminated
235679** string. Return a pointer to the first character following *pIn in
235680** the string that is not a white-space character.
235681*/
235682static const char *fts5ConfigSkipWhitespace(const char *pIn){
235683  const char *p = pIn;
235684  if( p ){
235685    while( fts5_iswhitespace(*p) ){ p++; }
235686  }
235687  return p;
235688}
235689
235690/*
235691** Argument pIn points to a character that is part of a nul-terminated
235692** string. Return a pointer to the first character following *pIn in
235693** the string that is not a "bareword" character.
235694*/
235695static const char *fts5ConfigSkipBareword(const char *pIn){
235696  const char *p = pIn;
235697  while ( sqlite3Fts5IsBareword(*p) ) p++;
235698  if( p==pIn ) p = 0;
235699  return p;
235700}
235701
235702static int fts5_isdigit(char a){
235703  return (a>='0' && a<='9');
235704}
235705
235706
235707
235708static const char *fts5ConfigSkipLiteral(const char *pIn){
235709  const char *p = pIn;
235710  switch( *p ){
235711    case 'n': case 'N':
235712      if( sqlite3_strnicmp("null", p, 4)==0 ){
235713        p = &p[4];
235714      }else{
235715        p = 0;
235716      }
235717      break;
235718
235719    case 'x': case 'X':
235720      p++;
235721      if( *p=='\'' ){
235722        p++;
235723        while( (*p>='a' && *p<='f')
235724            || (*p>='A' && *p<='F')
235725            || (*p>='0' && *p<='9')
235726            ){
235727          p++;
235728        }
235729        if( *p=='\'' && 0==((p-pIn)%2) ){
235730          p++;
235731        }else{
235732          p = 0;
235733        }
235734      }else{
235735        p = 0;
235736      }
235737      break;
235738
235739    case '\'':
235740      p++;
235741      while( p ){
235742        if( *p=='\'' ){
235743          p++;
235744          if( *p!='\'' ) break;
235745        }
235746        p++;
235747        if( *p==0 ) p = 0;
235748      }
235749      break;
235750
235751    default:
235752      /* maybe a number */
235753      if( *p=='+' || *p=='-' ) p++;
235754      while( fts5_isdigit(*p) ) p++;
235755
235756      /* At this point, if the literal was an integer, the parse is
235757      ** finished. Or, if it is a floating point value, it may continue
235758      ** with either a decimal point or an 'E' character. */
235759      if( *p=='.' && fts5_isdigit(p[1]) ){
235760        p += 2;
235761        while( fts5_isdigit(*p) ) p++;
235762      }
235763      if( p==pIn ) p = 0;
235764
235765      break;
235766  }
235767
235768  return p;
235769}
235770
235771/*
235772** The first character of the string pointed to by argument z is guaranteed
235773** to be an open-quote character (see function fts5_isopenquote()).
235774**
235775** This function searches for the corresponding close-quote character within
235776** the string and, if found, dequotes the string in place and adds a new
235777** nul-terminator byte.
235778**
235779** If the close-quote is found, the value returned is the byte offset of
235780** the character immediately following it. Or, if the close-quote is not
235781** found, -1 is returned. If -1 is returned, the buffer is left in an
235782** undefined state.
235783*/
235784static int fts5Dequote(char *z){
235785  char q;
235786  int iIn = 1;
235787  int iOut = 0;
235788  q = z[0];
235789
235790  /* Set stack variable q to the close-quote character */
235791  assert( q=='[' || q=='\'' || q=='"' || q=='`' );
235792  if( q=='[' ) q = ']';
235793
235794  while( z[iIn] ){
235795    if( z[iIn]==q ){
235796      if( z[iIn+1]!=q ){
235797        /* Character iIn was the close quote. */
235798        iIn++;
235799        break;
235800      }else{
235801        /* Character iIn and iIn+1 form an escaped quote character. Skip
235802        ** the input cursor past both and copy a single quote character
235803        ** to the output buffer. */
235804        iIn += 2;
235805        z[iOut++] = q;
235806      }
235807    }else{
235808      z[iOut++] = z[iIn++];
235809    }
235810  }
235811
235812  z[iOut] = '\0';
235813  return iIn;
235814}
235815
235816/*
235817** Convert an SQL-style quoted string into a normal string by removing
235818** the quote characters.  The conversion is done in-place.  If the
235819** input does not begin with a quote character, then this routine
235820** is a no-op.
235821**
235822** Examples:
235823**
235824**     "abc"   becomes   abc
235825**     'xyz'   becomes   xyz
235826**     [pqr]   becomes   pqr
235827**     `mno`   becomes   mno
235828*/
235829static void sqlite3Fts5Dequote(char *z){
235830  char quote;                     /* Quote character (if any ) */
235831
235832  assert( 0==fts5_iswhitespace(z[0]) );
235833  quote = z[0];
235834  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
235835    fts5Dequote(z);
235836  }
235837}
235838
235839
235840struct Fts5Enum {
235841  const char *zName;
235842  int eVal;
235843};
235844typedef struct Fts5Enum Fts5Enum;
235845
235846static int fts5ConfigSetEnum(
235847  const Fts5Enum *aEnum,
235848  const char *zEnum,
235849  int *peVal
235850){
235851  int nEnum = (int)strlen(zEnum);
235852  int i;
235853  int iVal = -1;
235854
235855  for(i=0; aEnum[i].zName; i++){
235856    if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
235857      if( iVal>=0 ) return SQLITE_ERROR;
235858      iVal = aEnum[i].eVal;
235859    }
235860  }
235861
235862  *peVal = iVal;
235863  return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
235864}
235865
235866/*
235867** Parse a "special" CREATE VIRTUAL TABLE directive and update
235868** configuration object pConfig as appropriate.
235869**
235870** If successful, object pConfig is updated and SQLITE_OK returned. If
235871** an error occurs, an SQLite error code is returned and an error message
235872** may be left in *pzErr. It is the responsibility of the caller to
235873** eventually free any such error message using sqlite3_free().
235874*/
235875static int fts5ConfigParseSpecial(
235876  Fts5Global *pGlobal,
235877  Fts5Config *pConfig,            /* Configuration object to update */
235878  const char *zCmd,               /* Special command to parse */
235879  const char *zArg,               /* Argument to parse */
235880  char **pzErr                    /* OUT: Error message */
235881){
235882  int rc = SQLITE_OK;
235883  int nCmd = (int)strlen(zCmd);
235884  if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
235885    const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
235886    const char *p;
235887    int bFirst = 1;
235888    if( pConfig->aPrefix==0 ){
235889      pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
235890      if( rc ) return rc;
235891    }
235892
235893    p = zArg;
235894    while( 1 ){
235895      int nPre = 0;
235896
235897      while( p[0]==' ' ) p++;
235898      if( bFirst==0 && p[0]==',' ){
235899        p++;
235900        while( p[0]==' ' ) p++;
235901      }else if( p[0]=='\0' ){
235902        break;
235903      }
235904      if( p[0]<'0' || p[0]>'9' ){
235905        *pzErr = sqlite3_mprintf("malformed prefix=... directive");
235906        rc = SQLITE_ERROR;
235907        break;
235908      }
235909
235910      if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
235911        *pzErr = sqlite3_mprintf(
235912            "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
235913        );
235914        rc = SQLITE_ERROR;
235915        break;
235916      }
235917
235918      while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
235919        nPre = nPre*10 + (p[0] - '0');
235920        p++;
235921      }
235922
235923      if( nPre<=0 || nPre>=1000 ){
235924        *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
235925        rc = SQLITE_ERROR;
235926        break;
235927      }
235928
235929      pConfig->aPrefix[pConfig->nPrefix] = nPre;
235930      pConfig->nPrefix++;
235931      bFirst = 0;
235932    }
235933    assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
235934    return rc;
235935  }
235936
235937  if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
235938    const char *p = (const char*)zArg;
235939    sqlite3_int64 nArg = strlen(zArg) + 1;
235940    char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
235941    char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
235942    char *pSpace = pDel;
235943
235944    if( azArg && pSpace ){
235945      if( pConfig->pTok ){
235946        *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
235947        rc = SQLITE_ERROR;
235948      }else{
235949        for(nArg=0; p && *p; nArg++){
235950          const char *p2 = fts5ConfigSkipWhitespace(p);
235951          if( *p2=='\'' ){
235952            p = fts5ConfigSkipLiteral(p2);
235953          }else{
235954            p = fts5ConfigSkipBareword(p2);
235955          }
235956          if( p ){
235957            memcpy(pSpace, p2, p-p2);
235958            azArg[nArg] = pSpace;
235959            sqlite3Fts5Dequote(pSpace);
235960            pSpace += (p - p2) + 1;
235961            p = fts5ConfigSkipWhitespace(p);
235962          }
235963        }
235964        if( p==0 ){
235965          *pzErr = sqlite3_mprintf("parse error in tokenize directive");
235966          rc = SQLITE_ERROR;
235967        }else{
235968          rc = sqlite3Fts5GetTokenizer(pGlobal,
235969              (const char**)azArg, (int)nArg, pConfig,
235970              pzErr
235971          );
235972        }
235973      }
235974    }
235975
235976    sqlite3_free(azArg);
235977    sqlite3_free(pDel);
235978    return rc;
235979  }
235980
235981  if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
235982    if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
235983      *pzErr = sqlite3_mprintf("multiple content=... directives");
235984      rc = SQLITE_ERROR;
235985    }else{
235986      if( zArg[0] ){
235987        pConfig->eContent = FTS5_CONTENT_EXTERNAL;
235988        pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
235989      }else{
235990        pConfig->eContent = FTS5_CONTENT_NONE;
235991      }
235992    }
235993    return rc;
235994  }
235995
235996  if( sqlite3_strnicmp("contentless_delete", zCmd, nCmd)==0 ){
235997    if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
235998      *pzErr = sqlite3_mprintf("malformed contentless_delete=... directive");
235999      rc = SQLITE_ERROR;
236000    }else{
236001      pConfig->bContentlessDelete = (zArg[0]=='1');
236002    }
236003    return rc;
236004  }
236005
236006  if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
236007    if( pConfig->zContentRowid ){
236008      *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
236009      rc = SQLITE_ERROR;
236010    }else{
236011      pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
236012    }
236013    return rc;
236014  }
236015
236016  if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
236017    if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
236018      *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
236019      rc = SQLITE_ERROR;
236020    }else{
236021      pConfig->bColumnsize = (zArg[0]=='1');
236022    }
236023    return rc;
236024  }
236025
236026  if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
236027    const Fts5Enum aDetail[] = {
236028      { "none", FTS5_DETAIL_NONE },
236029      { "full", FTS5_DETAIL_FULL },
236030      { "columns", FTS5_DETAIL_COLUMNS },
236031      { 0, 0 }
236032    };
236033
236034    if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
236035      *pzErr = sqlite3_mprintf("malformed detail=... directive");
236036    }
236037    return rc;
236038  }
236039
236040  if( sqlite3_strnicmp("tokendata", zCmd, nCmd)==0 ){
236041    if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
236042      *pzErr = sqlite3_mprintf("malformed tokendata=... directive");
236043      rc = SQLITE_ERROR;
236044    }else{
236045      pConfig->bTokendata = (zArg[0]=='1');
236046    }
236047    return rc;
236048  }
236049
236050  *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
236051  return SQLITE_ERROR;
236052}
236053
236054/*
236055** Allocate an instance of the default tokenizer ("simple") at
236056** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
236057** code if an error occurs.
236058*/
236059static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
236060  assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
236061  return sqlite3Fts5GetTokenizer(pGlobal, 0, 0, pConfig, 0);
236062}
236063
236064/*
236065** Gobble up the first bareword or quoted word from the input buffer zIn.
236066** Return a pointer to the character immediately following the last in
236067** the gobbled word if successful, or a NULL pointer otherwise (failed
236068** to find close-quote character).
236069**
236070** Before returning, set pzOut to point to a new buffer containing a
236071** nul-terminated, dequoted copy of the gobbled word. If the word was
236072** quoted, *pbQuoted is also set to 1 before returning.
236073**
236074** If *pRc is other than SQLITE_OK when this function is called, it is
236075** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
236076** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
236077** set if a parse error (failed to find close quote) occurs.
236078*/
236079static const char *fts5ConfigGobbleWord(
236080  int *pRc,                       /* IN/OUT: Error code */
236081  const char *zIn,                /* Buffer to gobble string/bareword from */
236082  char **pzOut,                   /* OUT: malloc'd buffer containing str/bw */
236083  int *pbQuoted                   /* OUT: Set to true if dequoting required */
236084){
236085  const char *zRet = 0;
236086
236087  sqlite3_int64 nIn = strlen(zIn);
236088  char *zOut = sqlite3_malloc64(nIn+1);
236089
236090  assert( *pRc==SQLITE_OK );
236091  *pbQuoted = 0;
236092  *pzOut = 0;
236093
236094  if( zOut==0 ){
236095    *pRc = SQLITE_NOMEM;
236096  }else{
236097    memcpy(zOut, zIn, (size_t)(nIn+1));
236098    if( fts5_isopenquote(zOut[0]) ){
236099      int ii = fts5Dequote(zOut);
236100      zRet = &zIn[ii];
236101      *pbQuoted = 1;
236102    }else{
236103      zRet = fts5ConfigSkipBareword(zIn);
236104      if( zRet ){
236105        zOut[zRet-zIn] = '\0';
236106      }
236107    }
236108  }
236109
236110  if( zRet==0 ){
236111    sqlite3_free(zOut);
236112  }else{
236113    *pzOut = zOut;
236114  }
236115
236116  return zRet;
236117}
236118
236119static int fts5ConfigParseColumn(
236120  Fts5Config *p,
236121  char *zCol,
236122  char *zArg,
236123  char **pzErr
236124){
236125  int rc = SQLITE_OK;
236126  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
236127   || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
236128  ){
236129    *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
236130    rc = SQLITE_ERROR;
236131  }else if( zArg ){
236132    if( 0==sqlite3_stricmp(zArg, "unindexed") ){
236133      p->abUnindexed[p->nCol] = 1;
236134    }else{
236135      *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
236136      rc = SQLITE_ERROR;
236137    }
236138  }
236139
236140  p->azCol[p->nCol++] = zCol;
236141  return rc;
236142}
236143
236144/*
236145** Populate the Fts5Config.zContentExprlist string.
236146*/
236147static int fts5ConfigMakeExprlist(Fts5Config *p){
236148  int i;
236149  int rc = SQLITE_OK;
236150  Fts5Buffer buf = {0, 0, 0};
236151
236152  sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
236153  if( p->eContent!=FTS5_CONTENT_NONE ){
236154    for(i=0; i<p->nCol; i++){
236155      if( p->eContent==FTS5_CONTENT_EXTERNAL ){
236156        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
236157      }else{
236158        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
236159      }
236160    }
236161  }
236162
236163  assert( p->zContentExprlist==0 );
236164  p->zContentExprlist = (char*)buf.p;
236165  return rc;
236166}
236167
236168/*
236169** Arguments nArg/azArg contain the string arguments passed to the xCreate
236170** or xConnect method of the virtual table. This function attempts to
236171** allocate an instance of Fts5Config containing the results of parsing
236172** those arguments.
236173**
236174** If successful, SQLITE_OK is returned and *ppOut is set to point to the
236175** new Fts5Config object. If an error occurs, an SQLite error code is
236176** returned, *ppOut is set to NULL and an error message may be left in
236177** *pzErr. It is the responsibility of the caller to eventually free any
236178** such error message using sqlite3_free().
236179*/
236180static int sqlite3Fts5ConfigParse(
236181  Fts5Global *pGlobal,
236182  sqlite3 *db,
236183  int nArg,                       /* Number of arguments */
236184  const char **azArg,             /* Array of nArg CREATE VIRTUAL TABLE args */
236185  Fts5Config **ppOut,             /* OUT: Results of parse */
236186  char **pzErr                    /* OUT: Error message */
236187){
236188  int rc = SQLITE_OK;             /* Return code */
236189  Fts5Config *pRet;               /* New object to return */
236190  int i;
236191  sqlite3_int64 nByte;
236192
236193  *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
236194  if( pRet==0 ) return SQLITE_NOMEM;
236195  memset(pRet, 0, sizeof(Fts5Config));
236196  pRet->db = db;
236197  pRet->iCookie = -1;
236198
236199  nByte = nArg * (sizeof(char*) + sizeof(u8));
236200  pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
236201  pRet->abUnindexed = pRet->azCol ? (u8*)&pRet->azCol[nArg] : 0;
236202  pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
236203  pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
236204  pRet->bColumnsize = 1;
236205  pRet->eDetail = FTS5_DETAIL_FULL;
236206#ifdef SQLITE_DEBUG
236207  pRet->bPrefixIndex = 1;
236208#endif
236209  if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
236210    *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
236211    rc = SQLITE_ERROR;
236212  }
236213
236214  assert( (pRet->abUnindexed && pRet->azCol) || rc!=SQLITE_OK );
236215  for(i=3; rc==SQLITE_OK && i<nArg; i++){
236216    const char *zOrig = azArg[i];
236217    const char *z;
236218    char *zOne = 0;
236219    char *zTwo = 0;
236220    int bOption = 0;
236221    int bMustBeCol = 0;
236222
236223    z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
236224    z = fts5ConfigSkipWhitespace(z);
236225    if( z && *z=='=' ){
236226      bOption = 1;
236227      assert( zOne!=0 );
236228      z++;
236229      if( bMustBeCol ) z = 0;
236230    }
236231    z = fts5ConfigSkipWhitespace(z);
236232    if( z && z[0] ){
236233      int bDummy;
236234      z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
236235      if( z && z[0] ) z = 0;
236236    }
236237
236238    if( rc==SQLITE_OK ){
236239      if( z==0 ){
236240        *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
236241        rc = SQLITE_ERROR;
236242      }else{
236243        if( bOption ){
236244          rc = fts5ConfigParseSpecial(pGlobal, pRet,
236245            ALWAYS(zOne)?zOne:"",
236246            zTwo?zTwo:"",
236247            pzErr
236248          );
236249        }else{
236250          rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
236251          zOne = 0;
236252        }
236253      }
236254    }
236255
236256    sqlite3_free(zOne);
236257    sqlite3_free(zTwo);
236258  }
236259
236260  /* We only allow contentless_delete=1 if the table is indeed contentless. */
236261  if( rc==SQLITE_OK
236262   && pRet->bContentlessDelete
236263   && pRet->eContent!=FTS5_CONTENT_NONE
236264  ){
236265    *pzErr = sqlite3_mprintf(
236266        "contentless_delete=1 requires a contentless table"
236267    );
236268    rc = SQLITE_ERROR;
236269  }
236270
236271  /* We only allow contentless_delete=1 if columnsize=0 is not present.
236272  **
236273  ** This restriction may be removed at some point.
236274  */
236275  if( rc==SQLITE_OK && pRet->bContentlessDelete && pRet->bColumnsize==0 ){
236276    *pzErr = sqlite3_mprintf(
236277        "contentless_delete=1 is incompatible with columnsize=0"
236278    );
236279    rc = SQLITE_ERROR;
236280  }
236281
236282  /* If a tokenizer= option was successfully parsed, the tokenizer has
236283  ** already been allocated. Otherwise, allocate an instance of the default
236284  ** tokenizer (unicode61) now.  */
236285  if( rc==SQLITE_OK && pRet->pTok==0 ){
236286    rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
236287  }
236288
236289  /* If no zContent option was specified, fill in the default values. */
236290  if( rc==SQLITE_OK && pRet->zContent==0 ){
236291    const char *zTail = 0;
236292    assert( pRet->eContent==FTS5_CONTENT_NORMAL
236293         || pRet->eContent==FTS5_CONTENT_NONE
236294    );
236295    if( pRet->eContent==FTS5_CONTENT_NORMAL ){
236296      zTail = "content";
236297    }else if( pRet->bColumnsize ){
236298      zTail = "docsize";
236299    }
236300
236301    if( zTail ){
236302      pRet->zContent = sqlite3Fts5Mprintf(
236303          &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
236304      );
236305    }
236306  }
236307
236308  if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
236309    pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
236310  }
236311
236312  /* Formulate the zContentExprlist text */
236313  if( rc==SQLITE_OK ){
236314    rc = fts5ConfigMakeExprlist(pRet);
236315  }
236316
236317  if( rc!=SQLITE_OK ){
236318    sqlite3Fts5ConfigFree(pRet);
236319    *ppOut = 0;
236320  }
236321  return rc;
236322}
236323
236324/*
236325** Free the configuration object passed as the only argument.
236326*/
236327static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
236328  if( pConfig ){
236329    int i;
236330    if( pConfig->pTok ){
236331      pConfig->pTokApi->xDelete(pConfig->pTok);
236332    }
236333    sqlite3_free(pConfig->zDb);
236334    sqlite3_free(pConfig->zName);
236335    for(i=0; i<pConfig->nCol; i++){
236336      sqlite3_free(pConfig->azCol[i]);
236337    }
236338    sqlite3_free(pConfig->azCol);
236339    sqlite3_free(pConfig->aPrefix);
236340    sqlite3_free(pConfig->zRank);
236341    sqlite3_free(pConfig->zRankArgs);
236342    sqlite3_free(pConfig->zContent);
236343    sqlite3_free(pConfig->zContentRowid);
236344    sqlite3_free(pConfig->zContentExprlist);
236345    sqlite3_free(pConfig);
236346  }
236347}
236348
236349/*
236350** Call sqlite3_declare_vtab() based on the contents of the configuration
236351** object passed as the only argument. Return SQLITE_OK if successful, or
236352** an SQLite error code if an error occurs.
236353*/
236354static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
236355  int i;
236356  int rc = SQLITE_OK;
236357  char *zSql;
236358
236359  zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
236360  for(i=0; zSql && i<pConfig->nCol; i++){
236361    const char *zSep = (i==0?"":", ");
236362    zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
236363  }
236364  zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
236365      zSql, pConfig->zName, FTS5_RANK_NAME
236366  );
236367
236368  assert( zSql || rc==SQLITE_NOMEM );
236369  if( zSql ){
236370    rc = sqlite3_declare_vtab(pConfig->db, zSql);
236371    sqlite3_free(zSql);
236372  }
236373
236374  return rc;
236375}
236376
236377/*
236378** Tokenize the text passed via the second and third arguments.
236379**
236380** The callback is invoked once for each token in the input text. The
236381** arguments passed to it are, in order:
236382**
236383**     void *pCtx          // Copy of 4th argument to sqlite3Fts5Tokenize()
236384**     const char *pToken  // Pointer to buffer containing token
236385**     int nToken          // Size of token in bytes
236386**     int iStart          // Byte offset of start of token within input text
236387**     int iEnd            // Byte offset of end of token within input text
236388**     int iPos            // Position of token in input (first token is 0)
236389**
236390** If the callback returns a non-zero value the tokenization is abandoned
236391** and no further callbacks are issued.
236392**
236393** This function returns SQLITE_OK if successful or an SQLite error code
236394** if an error occurs. If the tokenization was abandoned early because
236395** the callback returned SQLITE_DONE, this is not an error and this function
236396** still returns SQLITE_OK. Or, if the tokenization was abandoned early
236397** because the callback returned another non-zero value, it is assumed
236398** to be an SQLite error code and returned to the caller.
236399*/
236400static int sqlite3Fts5Tokenize(
236401  Fts5Config *pConfig,            /* FTS5 Configuration object */
236402  int flags,                      /* FTS5_TOKENIZE_* flags */
236403  const char *pText, int nText,   /* Text to tokenize */
236404  void *pCtx,                     /* Context passed to xToken() */
236405  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
236406){
236407  if( pText==0 ) return SQLITE_OK;
236408  return pConfig->pTokApi->xTokenize(
236409      pConfig->pTok, pCtx, flags, pText, nText, xToken
236410  );
236411}
236412
236413/*
236414** Argument pIn points to the first character in what is expected to be
236415** a comma-separated list of SQL literals followed by a ')' character.
236416** If it actually is this, return a pointer to the ')'. Otherwise, return
236417** NULL to indicate a parse error.
236418*/
236419static const char *fts5ConfigSkipArgs(const char *pIn){
236420  const char *p = pIn;
236421
236422  while( 1 ){
236423    p = fts5ConfigSkipWhitespace(p);
236424    p = fts5ConfigSkipLiteral(p);
236425    p = fts5ConfigSkipWhitespace(p);
236426    if( p==0 || *p==')' ) break;
236427    if( *p!=',' ){
236428      p = 0;
236429      break;
236430    }
236431    p++;
236432  }
236433
236434  return p;
236435}
236436
236437/*
236438** Parameter zIn contains a rank() function specification. The format of
236439** this is:
236440**
236441**   + Bareword (function name)
236442**   + Open parenthesis - "("
236443**   + Zero or more SQL literals in a comma separated list
236444**   + Close parenthesis - ")"
236445*/
236446static int sqlite3Fts5ConfigParseRank(
236447  const char *zIn,                /* Input string */
236448  char **pzRank,                  /* OUT: Rank function name */
236449  char **pzRankArgs               /* OUT: Rank function arguments */
236450){
236451  const char *p = zIn;
236452  const char *pRank;
236453  char *zRank = 0;
236454  char *zRankArgs = 0;
236455  int rc = SQLITE_OK;
236456
236457  *pzRank = 0;
236458  *pzRankArgs = 0;
236459
236460  if( p==0 ){
236461    rc = SQLITE_ERROR;
236462  }else{
236463    p = fts5ConfigSkipWhitespace(p);
236464    pRank = p;
236465    p = fts5ConfigSkipBareword(p);
236466
236467    if( p ){
236468      zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
236469      if( zRank ) memcpy(zRank, pRank, p-pRank);
236470    }else{
236471      rc = SQLITE_ERROR;
236472    }
236473
236474    if( rc==SQLITE_OK ){
236475      p = fts5ConfigSkipWhitespace(p);
236476      if( *p!='(' ) rc = SQLITE_ERROR;
236477      p++;
236478    }
236479    if( rc==SQLITE_OK ){
236480      const char *pArgs;
236481      p = fts5ConfigSkipWhitespace(p);
236482      pArgs = p;
236483      if( *p!=')' ){
236484        p = fts5ConfigSkipArgs(p);
236485        if( p==0 ){
236486          rc = SQLITE_ERROR;
236487        }else{
236488          zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
236489          if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
236490        }
236491      }
236492    }
236493  }
236494
236495  if( rc!=SQLITE_OK ){
236496    sqlite3_free(zRank);
236497    assert( zRankArgs==0 );
236498  }else{
236499    *pzRank = zRank;
236500    *pzRankArgs = zRankArgs;
236501  }
236502  return rc;
236503}
236504
236505static int sqlite3Fts5ConfigSetValue(
236506  Fts5Config *pConfig,
236507  const char *zKey,
236508  sqlite3_value *pVal,
236509  int *pbBadkey
236510){
236511  int rc = SQLITE_OK;
236512
236513  if( 0==sqlite3_stricmp(zKey, "pgsz") ){
236514    int pgsz = 0;
236515    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
236516      pgsz = sqlite3_value_int(pVal);
236517    }
236518    if( pgsz<32 || pgsz>FTS5_MAX_PAGE_SIZE ){
236519      *pbBadkey = 1;
236520    }else{
236521      pConfig->pgsz = pgsz;
236522    }
236523  }
236524
236525  else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
236526    int nHashSize = -1;
236527    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
236528      nHashSize = sqlite3_value_int(pVal);
236529    }
236530    if( nHashSize<=0 ){
236531      *pbBadkey = 1;
236532    }else{
236533      pConfig->nHashSize = nHashSize;
236534    }
236535  }
236536
236537  else if( 0==sqlite3_stricmp(zKey, "automerge") ){
236538    int nAutomerge = -1;
236539    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
236540      nAutomerge = sqlite3_value_int(pVal);
236541    }
236542    if( nAutomerge<0 || nAutomerge>64 ){
236543      *pbBadkey = 1;
236544    }else{
236545      if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
236546      pConfig->nAutomerge = nAutomerge;
236547    }
236548  }
236549
236550  else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
236551    int nUsermerge = -1;
236552    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
236553      nUsermerge = sqlite3_value_int(pVal);
236554    }
236555    if( nUsermerge<2 || nUsermerge>16 ){
236556      *pbBadkey = 1;
236557    }else{
236558      pConfig->nUsermerge = nUsermerge;
236559    }
236560  }
236561
236562  else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
236563    int nCrisisMerge = -1;
236564    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
236565      nCrisisMerge = sqlite3_value_int(pVal);
236566    }
236567    if( nCrisisMerge<0 ){
236568      *pbBadkey = 1;
236569    }else{
236570      if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
236571      if( nCrisisMerge>=FTS5_MAX_SEGMENT ) nCrisisMerge = FTS5_MAX_SEGMENT-1;
236572      pConfig->nCrisisMerge = nCrisisMerge;
236573    }
236574  }
236575
236576  else if( 0==sqlite3_stricmp(zKey, "deletemerge") ){
236577    int nVal = -1;
236578    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
236579      nVal = sqlite3_value_int(pVal);
236580    }else{
236581      *pbBadkey = 1;
236582    }
236583    if( nVal<0 ) nVal = FTS5_DEFAULT_DELETE_AUTOMERGE;
236584    if( nVal>100 ) nVal = 0;
236585    pConfig->nDeleteMerge = nVal;
236586  }
236587
236588  else if( 0==sqlite3_stricmp(zKey, "rank") ){
236589    const char *zIn = (const char*)sqlite3_value_text(pVal);
236590    char *zRank;
236591    char *zRankArgs;
236592    rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
236593    if( rc==SQLITE_OK ){
236594      sqlite3_free(pConfig->zRank);
236595      sqlite3_free(pConfig->zRankArgs);
236596      pConfig->zRank = zRank;
236597      pConfig->zRankArgs = zRankArgs;
236598    }else if( rc==SQLITE_ERROR ){
236599      rc = SQLITE_OK;
236600      *pbBadkey = 1;
236601    }
236602  }
236603
236604  else if( 0==sqlite3_stricmp(zKey, "secure-delete") ){
236605    int bVal = -1;
236606    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
236607      bVal = sqlite3_value_int(pVal);
236608    }
236609    if( bVal<0 ){
236610      *pbBadkey = 1;
236611    }else{
236612      pConfig->bSecureDelete = (bVal ? 1 : 0);
236613    }
236614  }else{
236615    *pbBadkey = 1;
236616  }
236617  return rc;
236618}
236619
236620/*
236621** Load the contents of the %_config table into memory.
236622*/
236623static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
236624  const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
236625  char *zSql;
236626  sqlite3_stmt *p = 0;
236627  int rc = SQLITE_OK;
236628  int iVersion = 0;
236629
236630  /* Set default values */
236631  pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
236632  pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
236633  pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
236634  pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
236635  pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
236636  pConfig->nDeleteMerge = FTS5_DEFAULT_DELETE_AUTOMERGE;
236637
236638  zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
236639  if( zSql ){
236640    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
236641    sqlite3_free(zSql);
236642  }
236643
236644  assert( rc==SQLITE_OK || p==0 );
236645  if( rc==SQLITE_OK ){
236646    while( SQLITE_ROW==sqlite3_step(p) ){
236647      const char *zK = (const char*)sqlite3_column_text(p, 0);
236648      sqlite3_value *pVal = sqlite3_column_value(p, 1);
236649      if( 0==sqlite3_stricmp(zK, "version") ){
236650        iVersion = sqlite3_value_int(pVal);
236651      }else{
236652        int bDummy = 0;
236653        sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
236654      }
236655    }
236656    rc = sqlite3_finalize(p);
236657  }
236658
236659  if( rc==SQLITE_OK
236660   && iVersion!=FTS5_CURRENT_VERSION
236661   && iVersion!=FTS5_CURRENT_VERSION_SECUREDELETE
236662  ){
236663    rc = SQLITE_ERROR;
236664    if( pConfig->pzErrmsg ){
236665      assert( 0==*pConfig->pzErrmsg );
236666      *pConfig->pzErrmsg = sqlite3_mprintf("invalid fts5 file format "
236667          "(found %d, expected %d or %d) - run 'rebuild'",
236668          iVersion, FTS5_CURRENT_VERSION, FTS5_CURRENT_VERSION_SECUREDELETE
236669      );
236670    }
236671  }else{
236672    pConfig->iVersion = iVersion;
236673  }
236674
236675  if( rc==SQLITE_OK ){
236676    pConfig->iCookie = iCookie;
236677  }
236678  return rc;
236679}
236680
236681/*
236682** 2014 May 31
236683**
236684** The author disclaims copyright to this source code.  In place of
236685** a legal notice, here is a blessing:
236686**
236687**    May you do good and not evil.
236688**    May you find forgiveness for yourself and forgive others.
236689**    May you share freely, never taking more than you give.
236690**
236691******************************************************************************
236692**
236693*/
236694
236695
236696
236697/* #include "fts5Int.h" */
236698/* #include "fts5parse.h" */
236699
236700#ifndef SQLITE_FTS5_MAX_EXPR_DEPTH
236701# define SQLITE_FTS5_MAX_EXPR_DEPTH 256
236702#endif
236703
236704/*
236705** All token types in the generated fts5parse.h file are greater than 0.
236706*/
236707#define FTS5_EOF 0
236708
236709#define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
236710
236711typedef struct Fts5ExprTerm Fts5ExprTerm;
236712
236713/*
236714** Functions generated by lemon from fts5parse.y.
236715*/
236716static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
236717static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
236718static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
236719#ifndef NDEBUG
236720/* #include <stdio.h> */
236721static void sqlite3Fts5ParserTrace(FILE*, char*);
236722#endif
236723static int sqlite3Fts5ParserFallback(int);
236724
236725
236726struct Fts5Expr {
236727  Fts5Index *pIndex;
236728  Fts5Config *pConfig;
236729  Fts5ExprNode *pRoot;
236730  int bDesc;                      /* Iterate in descending rowid order */
236731  int nPhrase;                    /* Number of phrases in expression */
236732  Fts5ExprPhrase **apExprPhrase;  /* Pointers to phrase objects */
236733};
236734
236735/*
236736** eType:
236737**   Expression node type. Always one of:
236738**
236739**       FTS5_AND                 (nChild, apChild valid)
236740**       FTS5_OR                  (nChild, apChild valid)
236741**       FTS5_NOT                 (nChild, apChild valid)
236742**       FTS5_STRING              (pNear valid)
236743**       FTS5_TERM                (pNear valid)
236744**
236745** iHeight:
236746**   Distance from this node to furthest leaf. This is always 0 for nodes
236747**   of type FTS5_STRING and FTS5_TERM. For all other nodes it is one
236748**   greater than the largest child value.
236749*/
236750struct Fts5ExprNode {
236751  int eType;                      /* Node type */
236752  int bEof;                       /* True at EOF */
236753  int bNomatch;                   /* True if entry is not a match */
236754  int iHeight;                    /* Distance to tree leaf nodes */
236755
236756  /* Next method for this node. */
236757  int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
236758
236759  i64 iRowid;                     /* Current rowid */
236760  Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */
236761
236762  /* Child nodes. For a NOT node, this array always contains 2 entries. For
236763  ** AND or OR nodes, it contains 2 or more entries.  */
236764  int nChild;                     /* Number of child nodes */
236765  Fts5ExprNode *apChild[1];       /* Array of child nodes */
236766};
236767
236768#define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
236769
236770/*
236771** Invoke the xNext method of an Fts5ExprNode object. This macro should be
236772** used as if it has the same signature as the xNext() methods themselves.
236773*/
236774#define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
236775
236776/*
236777** An instance of the following structure represents a single search term
236778** or term prefix.
236779*/
236780struct Fts5ExprTerm {
236781  u8 bPrefix;                     /* True for a prefix term */
236782  u8 bFirst;                      /* True if token must be first in column */
236783  char *pTerm;                    /* Term data */
236784  int nQueryTerm;                 /* Effective size of term in bytes */
236785  int nFullTerm;                  /* Size of term in bytes incl. tokendata */
236786  Fts5IndexIter *pIter;           /* Iterator for this term */
236787  Fts5ExprTerm *pSynonym;         /* Pointer to first in list of synonyms */
236788};
236789
236790/*
236791** A phrase. One or more terms that must appear in a contiguous sequence
236792** within a document for it to match.
236793*/
236794struct Fts5ExprPhrase {
236795  Fts5ExprNode *pNode;            /* FTS5_STRING node this phrase is part of */
236796  Fts5Buffer poslist;             /* Current position list */
236797  int nTerm;                      /* Number of entries in aTerm[] */
236798  Fts5ExprTerm aTerm[1];          /* Terms that make up this phrase */
236799};
236800
236801/*
236802** One or more phrases that must appear within a certain token distance of
236803** each other within each matching document.
236804*/
236805struct Fts5ExprNearset {
236806  int nNear;                      /* NEAR parameter */
236807  Fts5Colset *pColset;            /* Columns to search (NULL -> all columns) */
236808  int nPhrase;                    /* Number of entries in aPhrase[] array */
236809  Fts5ExprPhrase *apPhrase[1];    /* Array of phrase pointers */
236810};
236811
236812
236813/*
236814** Parse context.
236815*/
236816struct Fts5Parse {
236817  Fts5Config *pConfig;
236818  char *zErr;
236819  int rc;
236820  int nPhrase;                    /* Size of apPhrase array */
236821  Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
236822  Fts5ExprNode *pExpr;            /* Result of a successful parse */
236823  int bPhraseToAnd;               /* Convert "a+b" to "a AND b" */
236824};
236825
236826/*
236827** Check that the Fts5ExprNode.iHeight variables are set correctly in
236828** the expression tree passed as the only argument.
236829*/
236830#ifndef NDEBUG
236831static void assert_expr_depth_ok(int rc, Fts5ExprNode *p){
236832  if( rc==SQLITE_OK ){
236833    if( p->eType==FTS5_TERM || p->eType==FTS5_STRING || p->eType==0 ){
236834      assert( p->iHeight==0 );
236835    }else{
236836      int ii;
236837      int iMaxChild = 0;
236838      for(ii=0; ii<p->nChild; ii++){
236839        Fts5ExprNode *pChild = p->apChild[ii];
236840        iMaxChild = MAX(iMaxChild, pChild->iHeight);
236841        assert_expr_depth_ok(SQLITE_OK, pChild);
236842      }
236843      assert( p->iHeight==iMaxChild+1 );
236844    }
236845  }
236846}
236847#else
236848# define assert_expr_depth_ok(rc, p)
236849#endif
236850
236851static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
236852  va_list ap;
236853  va_start(ap, zFmt);
236854  if( pParse->rc==SQLITE_OK ){
236855    assert( pParse->zErr==0 );
236856    pParse->zErr = sqlite3_vmprintf(zFmt, ap);
236857    pParse->rc = SQLITE_ERROR;
236858  }
236859  va_end(ap);
236860}
236861
236862static int fts5ExprIsspace(char t){
236863  return t==' ' || t=='\t' || t=='\n' || t=='\r';
236864}
236865
236866/*
236867** Read the first token from the nul-terminated string at *pz.
236868*/
236869static int fts5ExprGetToken(
236870  Fts5Parse *pParse,
236871  const char **pz,                /* IN/OUT: Pointer into buffer */
236872  Fts5Token *pToken
236873){
236874  const char *z = *pz;
236875  int tok;
236876
236877  /* Skip past any whitespace */
236878  while( fts5ExprIsspace(*z) ) z++;
236879
236880  pToken->p = z;
236881  pToken->n = 1;
236882  switch( *z ){
236883    case '(':  tok = FTS5_LP;    break;
236884    case ')':  tok = FTS5_RP;    break;
236885    case '{':  tok = FTS5_LCP;   break;
236886    case '}':  tok = FTS5_RCP;   break;
236887    case ':':  tok = FTS5_COLON; break;
236888    case ',':  tok = FTS5_COMMA; break;
236889    case '+':  tok = FTS5_PLUS;  break;
236890    case '*':  tok = FTS5_STAR;  break;
236891    case '-':  tok = FTS5_MINUS; break;
236892    case '^':  tok = FTS5_CARET; break;
236893    case '\0': tok = FTS5_EOF;   break;
236894
236895    case '"': {
236896      const char *z2;
236897      tok = FTS5_STRING;
236898
236899      for(z2=&z[1]; 1; z2++){
236900        if( z2[0]=='"' ){
236901          z2++;
236902          if( z2[0]!='"' ) break;
236903        }
236904        if( z2[0]=='\0' ){
236905          sqlite3Fts5ParseError(pParse, "unterminated string");
236906          return FTS5_EOF;
236907        }
236908      }
236909      pToken->n = (z2 - z);
236910      break;
236911    }
236912
236913    default: {
236914      const char *z2;
236915      if( sqlite3Fts5IsBareword(z[0])==0 ){
236916        sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
236917        return FTS5_EOF;
236918      }
236919      tok = FTS5_STRING;
236920      for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
236921      pToken->n = (z2 - z);
236922      if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 )  tok = FTS5_OR;
236923      if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
236924      if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
236925      break;
236926    }
236927  }
236928
236929  *pz = &pToken->p[pToken->n];
236930  return tok;
236931}
236932
236933static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc64((sqlite3_int64)t);}
236934static void fts5ParseFree(void *p){ sqlite3_free(p); }
236935
236936static int sqlite3Fts5ExprNew(
236937  Fts5Config *pConfig,            /* FTS5 Configuration */
236938  int bPhraseToAnd,
236939  int iCol,
236940  const char *zExpr,              /* Expression text */
236941  Fts5Expr **ppNew,
236942  char **pzErr
236943){
236944  Fts5Parse sParse;
236945  Fts5Token token;
236946  const char *z = zExpr;
236947  int t;                          /* Next token type */
236948  void *pEngine;
236949  Fts5Expr *pNew;
236950
236951  *ppNew = 0;
236952  *pzErr = 0;
236953  memset(&sParse, 0, sizeof(sParse));
236954  sParse.bPhraseToAnd = bPhraseToAnd;
236955  pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
236956  if( pEngine==0 ){ return SQLITE_NOMEM; }
236957  sParse.pConfig = pConfig;
236958
236959  do {
236960    t = fts5ExprGetToken(&sParse, &z, &token);
236961    sqlite3Fts5Parser(pEngine, t, token, &sParse);
236962  }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
236963  sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
236964
236965  assert_expr_depth_ok(sParse.rc, sParse.pExpr);
236966
236967  /* If the LHS of the MATCH expression was a user column, apply the
236968  ** implicit column-filter.  */
236969  if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
236970    int n = sizeof(Fts5Colset);
236971    Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
236972    if( pColset ){
236973      pColset->nCol = 1;
236974      pColset->aiCol[0] = iCol;
236975      sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
236976    }
236977  }
236978
236979  assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
236980  if( sParse.rc==SQLITE_OK ){
236981    *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
236982    if( pNew==0 ){
236983      sParse.rc = SQLITE_NOMEM;
236984      sqlite3Fts5ParseNodeFree(sParse.pExpr);
236985    }else{
236986      if( !sParse.pExpr ){
236987        const int nByte = sizeof(Fts5ExprNode);
236988        pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
236989        if( pNew->pRoot ){
236990          pNew->pRoot->bEof = 1;
236991        }
236992      }else{
236993        pNew->pRoot = sParse.pExpr;
236994      }
236995      pNew->pIndex = 0;
236996      pNew->pConfig = pConfig;
236997      pNew->apExprPhrase = sParse.apPhrase;
236998      pNew->nPhrase = sParse.nPhrase;
236999      pNew->bDesc = 0;
237000      sParse.apPhrase = 0;
237001    }
237002  }else{
237003    sqlite3Fts5ParseNodeFree(sParse.pExpr);
237004  }
237005
237006  sqlite3_free(sParse.apPhrase);
237007  *pzErr = sParse.zErr;
237008  return sParse.rc;
237009}
237010
237011/*
237012** Assuming that buffer z is at least nByte bytes in size and contains a
237013** valid utf-8 string, return the number of characters in the string.
237014*/
237015static int fts5ExprCountChar(const char *z, int nByte){
237016  int nRet = 0;
237017  int ii;
237018  for(ii=0; ii<nByte; ii++){
237019    if( (z[ii] & 0xC0)!=0x80 ) nRet++;
237020  }
237021  return nRet;
237022}
237023
237024/*
237025** This function is only called when using the special 'trigram' tokenizer.
237026** Argument zText contains the text of a LIKE or GLOB pattern matched
237027** against column iCol. This function creates and compiles an FTS5 MATCH
237028** expression that will match a superset of the rows matched by the LIKE or
237029** GLOB. If successful, SQLITE_OK is returned. Otherwise, an SQLite error
237030** code.
237031*/
237032static int sqlite3Fts5ExprPattern(
237033  Fts5Config *pConfig, int bGlob, int iCol, const char *zText, Fts5Expr **pp
237034){
237035  i64 nText = strlen(zText);
237036  char *zExpr = (char*)sqlite3_malloc64(nText*4 + 1);
237037  int rc = SQLITE_OK;
237038
237039  if( zExpr==0 ){
237040    rc = SQLITE_NOMEM;
237041  }else{
237042    char aSpec[3];
237043    int iOut = 0;
237044    int i = 0;
237045    int iFirst = 0;
237046
237047    if( bGlob==0 ){
237048      aSpec[0] = '_';
237049      aSpec[1] = '%';
237050      aSpec[2] = 0;
237051    }else{
237052      aSpec[0] = '*';
237053      aSpec[1] = '?';
237054      aSpec[2] = '[';
237055    }
237056
237057    while( i<=nText ){
237058      if( i==nText
237059       || zText[i]==aSpec[0] || zText[i]==aSpec[1] || zText[i]==aSpec[2]
237060      ){
237061
237062        if( fts5ExprCountChar(&zText[iFirst], i-iFirst)>=3 ){
237063          int jj;
237064          zExpr[iOut++] = '"';
237065          for(jj=iFirst; jj<i; jj++){
237066            zExpr[iOut++] = zText[jj];
237067            if( zText[jj]=='"' ) zExpr[iOut++] = '"';
237068          }
237069          zExpr[iOut++] = '"';
237070          zExpr[iOut++] = ' ';
237071        }
237072        if( zText[i]==aSpec[2] ){
237073          i += 2;
237074          if( zText[i-1]=='^' ) i++;
237075          while( i<nText && zText[i]!=']' ) i++;
237076        }
237077        iFirst = i+1;
237078      }
237079      i++;
237080    }
237081    if( iOut>0 ){
237082      int bAnd = 0;
237083      if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
237084        bAnd = 1;
237085        if( pConfig->eDetail==FTS5_DETAIL_NONE ){
237086          iCol = pConfig->nCol;
237087        }
237088      }
237089      zExpr[iOut] = '\0';
237090      rc = sqlite3Fts5ExprNew(pConfig, bAnd, iCol, zExpr, pp,pConfig->pzErrmsg);
237091    }else{
237092      *pp = 0;
237093    }
237094    sqlite3_free(zExpr);
237095  }
237096
237097  return rc;
237098}
237099
237100/*
237101** Free the expression node object passed as the only argument.
237102*/
237103static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
237104  if( p ){
237105    int i;
237106    for(i=0; i<p->nChild; i++){
237107      sqlite3Fts5ParseNodeFree(p->apChild[i]);
237108    }
237109    sqlite3Fts5ParseNearsetFree(p->pNear);
237110    sqlite3_free(p);
237111  }
237112}
237113
237114/*
237115** Free the expression object passed as the only argument.
237116*/
237117static void sqlite3Fts5ExprFree(Fts5Expr *p){
237118  if( p ){
237119    sqlite3Fts5ParseNodeFree(p->pRoot);
237120    sqlite3_free(p->apExprPhrase);
237121    sqlite3_free(p);
237122  }
237123}
237124
237125static int sqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2){
237126  Fts5Parse sParse;
237127  memset(&sParse, 0, sizeof(sParse));
237128
237129  if( *pp1 && p2 ){
237130    Fts5Expr *p1 = *pp1;
237131    int nPhrase = p1->nPhrase + p2->nPhrase;
237132
237133    p1->pRoot = sqlite3Fts5ParseNode(&sParse, FTS5_AND, p1->pRoot, p2->pRoot,0);
237134    p2->pRoot = 0;
237135
237136    if( sParse.rc==SQLITE_OK ){
237137      Fts5ExprPhrase **ap = (Fts5ExprPhrase**)sqlite3_realloc(
237138          p1->apExprPhrase, nPhrase * sizeof(Fts5ExprPhrase*)
237139      );
237140      if( ap==0 ){
237141        sParse.rc = SQLITE_NOMEM;
237142      }else{
237143        int i;
237144        memmove(&ap[p2->nPhrase], ap, p1->nPhrase*sizeof(Fts5ExprPhrase*));
237145        for(i=0; i<p2->nPhrase; i++){
237146          ap[i] = p2->apExprPhrase[i];
237147        }
237148        p1->nPhrase = nPhrase;
237149        p1->apExprPhrase = ap;
237150      }
237151    }
237152    sqlite3_free(p2->apExprPhrase);
237153    sqlite3_free(p2);
237154  }else if( p2 ){
237155    *pp1 = p2;
237156  }
237157
237158  return sParse.rc;
237159}
237160
237161/*
237162** Argument pTerm must be a synonym iterator. Return the current rowid
237163** that it points to.
237164*/
237165static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
237166  i64 iRet = 0;
237167  int bRetValid = 0;
237168  Fts5ExprTerm *p;
237169
237170  assert( pTerm );
237171  assert( pTerm->pSynonym );
237172  assert( bDesc==0 || bDesc==1 );
237173  for(p=pTerm; p; p=p->pSynonym){
237174    if( 0==sqlite3Fts5IterEof(p->pIter) ){
237175      i64 iRowid = p->pIter->iRowid;
237176      if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
237177        iRet = iRowid;
237178        bRetValid = 1;
237179      }
237180    }
237181  }
237182
237183  if( pbEof && bRetValid==0 ) *pbEof = 1;
237184  return iRet;
237185}
237186
237187/*
237188** Argument pTerm must be a synonym iterator.
237189*/
237190static int fts5ExprSynonymList(
237191  Fts5ExprTerm *pTerm,
237192  i64 iRowid,
237193  Fts5Buffer *pBuf,               /* Use this buffer for space if required */
237194  u8 **pa, int *pn
237195){
237196  Fts5PoslistReader aStatic[4];
237197  Fts5PoslistReader *aIter = aStatic;
237198  int nIter = 0;
237199  int nAlloc = 4;
237200  int rc = SQLITE_OK;
237201  Fts5ExprTerm *p;
237202
237203  assert( pTerm->pSynonym );
237204  for(p=pTerm; p; p=p->pSynonym){
237205    Fts5IndexIter *pIter = p->pIter;
237206    if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
237207      if( pIter->nData==0 ) continue;
237208      if( nIter==nAlloc ){
237209        sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
237210        Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
237211        if( aNew==0 ){
237212          rc = SQLITE_NOMEM;
237213          goto synonym_poslist_out;
237214        }
237215        memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
237216        nAlloc = nAlloc*2;
237217        if( aIter!=aStatic ) sqlite3_free(aIter);
237218        aIter = aNew;
237219      }
237220      sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
237221      assert( aIter[nIter].bEof==0 );
237222      nIter++;
237223    }
237224  }
237225
237226  if( nIter==1 ){
237227    *pa = (u8*)aIter[0].a;
237228    *pn = aIter[0].n;
237229  }else{
237230    Fts5PoslistWriter writer = {0};
237231    i64 iPrev = -1;
237232    fts5BufferZero(pBuf);
237233    while( 1 ){
237234      int i;
237235      i64 iMin = FTS5_LARGEST_INT64;
237236      for(i=0; i<nIter; i++){
237237        if( aIter[i].bEof==0 ){
237238          if( aIter[i].iPos==iPrev ){
237239            if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
237240          }
237241          if( aIter[i].iPos<iMin ){
237242            iMin = aIter[i].iPos;
237243          }
237244        }
237245      }
237246      if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
237247      rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
237248      iPrev = iMin;
237249    }
237250    if( rc==SQLITE_OK ){
237251      *pa = pBuf->p;
237252      *pn = pBuf->n;
237253    }
237254  }
237255
237256 synonym_poslist_out:
237257  if( aIter!=aStatic ) sqlite3_free(aIter);
237258  return rc;
237259}
237260
237261
237262/*
237263** All individual term iterators in pPhrase are guaranteed to be valid and
237264** pointing to the same rowid when this function is called. This function
237265** checks if the current rowid really is a match, and if so populates
237266** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
237267** is set to true if this is really a match, or false otherwise.
237268**
237269** SQLITE_OK is returned if an error occurs, or an SQLite error code
237270** otherwise. It is not considered an error code if the current rowid is
237271** not a match.
237272*/
237273static int fts5ExprPhraseIsMatch(
237274  Fts5ExprNode *pNode,            /* Node pPhrase belongs to */
237275  Fts5ExprPhrase *pPhrase,        /* Phrase object to initialize */
237276  int *pbMatch                    /* OUT: Set to true if really a match */
237277){
237278  Fts5PoslistWriter writer = {0};
237279  Fts5PoslistReader aStatic[4];
237280  Fts5PoslistReader *aIter = aStatic;
237281  int i;
237282  int rc = SQLITE_OK;
237283  int bFirst = pPhrase->aTerm[0].bFirst;
237284
237285  fts5BufferZero(&pPhrase->poslist);
237286
237287  /* If the aStatic[] array is not large enough, allocate a large array
237288  ** using sqlite3_malloc(). This approach could be improved upon. */
237289  if( pPhrase->nTerm>ArraySize(aStatic) ){
237290    sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
237291    aIter = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
237292    if( !aIter ) return SQLITE_NOMEM;
237293  }
237294  memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
237295
237296  /* Initialize a term iterator for each term in the phrase */
237297  for(i=0; i<pPhrase->nTerm; i++){
237298    Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
237299    int n = 0;
237300    int bFlag = 0;
237301    u8 *a = 0;
237302    if( pTerm->pSynonym ){
237303      Fts5Buffer buf = {0, 0, 0};
237304      rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
237305      if( rc ){
237306        sqlite3_free(a);
237307        goto ismatch_out;
237308      }
237309      if( a==buf.p ) bFlag = 1;
237310    }else{
237311      a = (u8*)pTerm->pIter->pData;
237312      n = pTerm->pIter->nData;
237313    }
237314    sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
237315    aIter[i].bFlag = (u8)bFlag;
237316    if( aIter[i].bEof ) goto ismatch_out;
237317  }
237318
237319  while( 1 ){
237320    int bMatch;
237321    i64 iPos = aIter[0].iPos;
237322    do {
237323      bMatch = 1;
237324      for(i=0; i<pPhrase->nTerm; i++){
237325        Fts5PoslistReader *pPos = &aIter[i];
237326        i64 iAdj = iPos + i;
237327        if( pPos->iPos!=iAdj ){
237328          bMatch = 0;
237329          while( pPos->iPos<iAdj ){
237330            if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
237331          }
237332          if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
237333        }
237334      }
237335    }while( bMatch==0 );
237336
237337    /* Append position iPos to the output */
237338    if( bFirst==0 || FTS5_POS2OFFSET(iPos)==0 ){
237339      rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
237340      if( rc!=SQLITE_OK ) goto ismatch_out;
237341    }
237342
237343    for(i=0; i<pPhrase->nTerm; i++){
237344      if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
237345    }
237346  }
237347
237348 ismatch_out:
237349  *pbMatch = (pPhrase->poslist.n>0);
237350  for(i=0; i<pPhrase->nTerm; i++){
237351    if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
237352  }
237353  if( aIter!=aStatic ) sqlite3_free(aIter);
237354  return rc;
237355}
237356
237357typedef struct Fts5LookaheadReader Fts5LookaheadReader;
237358struct Fts5LookaheadReader {
237359  const u8 *a;                    /* Buffer containing position list */
237360  int n;                          /* Size of buffer a[] in bytes */
237361  int i;                          /* Current offset in position list */
237362  i64 iPos;                       /* Current position */
237363  i64 iLookahead;                 /* Next position */
237364};
237365
237366#define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
237367
237368static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
237369  p->iPos = p->iLookahead;
237370  if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
237371    p->iLookahead = FTS5_LOOKAHEAD_EOF;
237372  }
237373  return (p->iPos==FTS5_LOOKAHEAD_EOF);
237374}
237375
237376static int fts5LookaheadReaderInit(
237377  const u8 *a, int n,             /* Buffer to read position list from */
237378  Fts5LookaheadReader *p          /* Iterator object to initialize */
237379){
237380  memset(p, 0, sizeof(Fts5LookaheadReader));
237381  p->a = a;
237382  p->n = n;
237383  fts5LookaheadReaderNext(p);
237384  return fts5LookaheadReaderNext(p);
237385}
237386
237387typedef struct Fts5NearTrimmer Fts5NearTrimmer;
237388struct Fts5NearTrimmer {
237389  Fts5LookaheadReader reader;     /* Input iterator */
237390  Fts5PoslistWriter writer;       /* Writer context */
237391  Fts5Buffer *pOut;               /* Output poslist */
237392};
237393
237394/*
237395** The near-set object passed as the first argument contains more than
237396** one phrase. All phrases currently point to the same row. The
237397** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
237398** tests if the current row contains instances of each phrase sufficiently
237399** close together to meet the NEAR constraint. Non-zero is returned if it
237400** does, or zero otherwise.
237401**
237402** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
237403** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
237404** occurs within this function (*pRc) is set accordingly before returning.
237405** The return value is undefined in both these cases.
237406**
237407** If no error occurs and non-zero (a match) is returned, the position-list
237408** of each phrase object is edited to contain only those entries that
237409** meet the constraint before returning.
237410*/
237411static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
237412  Fts5NearTrimmer aStatic[4];
237413  Fts5NearTrimmer *a = aStatic;
237414  Fts5ExprPhrase **apPhrase = pNear->apPhrase;
237415
237416  int i;
237417  int rc = *pRc;
237418  int bMatch;
237419
237420  assert( pNear->nPhrase>1 );
237421
237422  /* If the aStatic[] array is not large enough, allocate a large array
237423  ** using sqlite3_malloc(). This approach could be improved upon. */
237424  if( pNear->nPhrase>ArraySize(aStatic) ){
237425    sqlite3_int64 nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
237426    a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
237427  }else{
237428    memset(aStatic, 0, sizeof(aStatic));
237429  }
237430  if( rc!=SQLITE_OK ){
237431    *pRc = rc;
237432    return 0;
237433  }
237434
237435  /* Initialize a lookahead iterator for each phrase. After passing the
237436  ** buffer and buffer size to the lookaside-reader init function, zero
237437  ** the phrase poslist buffer. The new poslist for the phrase (containing
237438  ** the same entries as the original with some entries removed on account
237439  ** of the NEAR constraint) is written over the original even as it is
237440  ** being read. This is safe as the entries for the new poslist are a
237441  ** subset of the old, so it is not possible for data yet to be read to
237442  ** be overwritten.  */
237443  for(i=0; i<pNear->nPhrase; i++){
237444    Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
237445    fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
237446    pPoslist->n = 0;
237447    a[i].pOut = pPoslist;
237448  }
237449
237450  while( 1 ){
237451    int iAdv;
237452    i64 iMin;
237453    i64 iMax;
237454
237455    /* This block advances the phrase iterators until they point to a set of
237456    ** entries that together comprise a match.  */
237457    iMax = a[0].reader.iPos;
237458    do {
237459      bMatch = 1;
237460      for(i=0; i<pNear->nPhrase; i++){
237461        Fts5LookaheadReader *pPos = &a[i].reader;
237462        iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
237463        if( pPos->iPos<iMin || pPos->iPos>iMax ){
237464          bMatch = 0;
237465          while( pPos->iPos<iMin ){
237466            if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
237467          }
237468          if( pPos->iPos>iMax ) iMax = pPos->iPos;
237469        }
237470      }
237471    }while( bMatch==0 );
237472
237473    /* Add an entry to each output position list */
237474    for(i=0; i<pNear->nPhrase; i++){
237475      i64 iPos = a[i].reader.iPos;
237476      Fts5PoslistWriter *pWriter = &a[i].writer;
237477      if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
237478        sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
237479      }
237480    }
237481
237482    iAdv = 0;
237483    iMin = a[0].reader.iLookahead;
237484    for(i=0; i<pNear->nPhrase; i++){
237485      if( a[i].reader.iLookahead < iMin ){
237486        iMin = a[i].reader.iLookahead;
237487        iAdv = i;
237488      }
237489    }
237490    if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
237491  }
237492
237493  ismatch_out: {
237494    int bRet = a[0].pOut->n>0;
237495    *pRc = rc;
237496    if( a!=aStatic ) sqlite3_free(a);
237497    return bRet;
237498  }
237499}
237500
237501/*
237502** Advance iterator pIter until it points to a value equal to or laster
237503** than the initial value of *piLast. If this means the iterator points
237504** to a value laster than *piLast, update *piLast to the new lastest value.
237505**
237506** If the iterator reaches EOF, set *pbEof to true before returning. If
237507** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
237508** are set, return a non-zero value. Otherwise, return zero.
237509*/
237510static int fts5ExprAdvanceto(
237511  Fts5IndexIter *pIter,           /* Iterator to advance */
237512  int bDesc,                      /* True if iterator is "rowid DESC" */
237513  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
237514  int *pRc,                       /* OUT: Error code */
237515  int *pbEof                      /* OUT: Set to true if EOF */
237516){
237517  i64 iLast = *piLast;
237518  i64 iRowid;
237519
237520  iRowid = pIter->iRowid;
237521  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
237522    int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
237523    if( rc || sqlite3Fts5IterEof(pIter) ){
237524      *pRc = rc;
237525      *pbEof = 1;
237526      return 1;
237527    }
237528    iRowid = pIter->iRowid;
237529    assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
237530  }
237531  *piLast = iRowid;
237532
237533  return 0;
237534}
237535
237536static int fts5ExprSynonymAdvanceto(
237537  Fts5ExprTerm *pTerm,            /* Term iterator to advance */
237538  int bDesc,                      /* True if iterator is "rowid DESC" */
237539  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
237540  int *pRc                        /* OUT: Error code */
237541){
237542  int rc = SQLITE_OK;
237543  i64 iLast = *piLast;
237544  Fts5ExprTerm *p;
237545  int bEof = 0;
237546
237547  for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
237548    if( sqlite3Fts5IterEof(p->pIter)==0 ){
237549      i64 iRowid = p->pIter->iRowid;
237550      if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
237551        rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
237552      }
237553    }
237554  }
237555
237556  if( rc!=SQLITE_OK ){
237557    *pRc = rc;
237558    bEof = 1;
237559  }else{
237560    *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
237561  }
237562  return bEof;
237563}
237564
237565
237566static int fts5ExprNearTest(
237567  int *pRc,
237568  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
237569  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_STRING) */
237570){
237571  Fts5ExprNearset *pNear = pNode->pNear;
237572  int rc = *pRc;
237573
237574  if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
237575    Fts5ExprTerm *pTerm;
237576    Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
237577    pPhrase->poslist.n = 0;
237578    for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
237579      Fts5IndexIter *pIter = pTerm->pIter;
237580      if( sqlite3Fts5IterEof(pIter)==0 ){
237581        if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
237582          pPhrase->poslist.n = 1;
237583        }
237584      }
237585    }
237586    return pPhrase->poslist.n;
237587  }else{
237588    int i;
237589
237590    /* Check that each phrase in the nearset matches the current row.
237591    ** Populate the pPhrase->poslist buffers at the same time. If any
237592    ** phrase is not a match, break out of the loop early.  */
237593    for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
237594      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
237595      if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym
237596       || pNear->pColset || pPhrase->aTerm[0].bFirst
237597      ){
237598        int bMatch = 0;
237599        rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
237600        if( bMatch==0 ) break;
237601      }else{
237602        Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
237603        fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
237604      }
237605    }
237606
237607    *pRc = rc;
237608    if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
237609      return 1;
237610    }
237611    return 0;
237612  }
237613}
237614
237615
237616/*
237617** Initialize all term iterators in the pNear object. If any term is found
237618** to match no documents at all, return immediately without initializing any
237619** further iterators.
237620**
237621** If an error occurs, return an SQLite error code. Otherwise, return
237622** SQLITE_OK. It is not considered an error if some term matches zero
237623** documents.
237624*/
237625static int fts5ExprNearInitAll(
237626  Fts5Expr *pExpr,
237627  Fts5ExprNode *pNode
237628){
237629  Fts5ExprNearset *pNear = pNode->pNear;
237630  int i;
237631
237632  assert( pNode->bNomatch==0 );
237633  for(i=0; i<pNear->nPhrase; i++){
237634    Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
237635    if( pPhrase->nTerm==0 ){
237636      pNode->bEof = 1;
237637      return SQLITE_OK;
237638    }else{
237639      int j;
237640      for(j=0; j<pPhrase->nTerm; j++){
237641        Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
237642        Fts5ExprTerm *p;
237643        int bHit = 0;
237644
237645        for(p=pTerm; p; p=p->pSynonym){
237646          int rc;
237647          if( p->pIter ){
237648            sqlite3Fts5IterClose(p->pIter);
237649            p->pIter = 0;
237650          }
237651          rc = sqlite3Fts5IndexQuery(
237652              pExpr->pIndex, p->pTerm, p->nQueryTerm,
237653              (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
237654              (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
237655              pNear->pColset,
237656              &p->pIter
237657          );
237658          assert( (rc==SQLITE_OK)==(p->pIter!=0) );
237659          if( rc!=SQLITE_OK ) return rc;
237660          if( 0==sqlite3Fts5IterEof(p->pIter) ){
237661            bHit = 1;
237662          }
237663        }
237664
237665        if( bHit==0 ){
237666          pNode->bEof = 1;
237667          return SQLITE_OK;
237668        }
237669      }
237670    }
237671  }
237672
237673  pNode->bEof = 0;
237674  return SQLITE_OK;
237675}
237676
237677/*
237678** If pExpr is an ASC iterator, this function returns a value with the
237679** same sign as:
237680**
237681**   (iLhs - iRhs)
237682**
237683** Otherwise, if this is a DESC iterator, the opposite is returned:
237684**
237685**   (iRhs - iLhs)
237686*/
237687static int fts5RowidCmp(
237688  Fts5Expr *pExpr,
237689  i64 iLhs,
237690  i64 iRhs
237691){
237692  assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
237693  if( pExpr->bDesc==0 ){
237694    if( iLhs<iRhs ) return -1;
237695    return (iLhs > iRhs);
237696  }else{
237697    if( iLhs>iRhs ) return -1;
237698    return (iLhs < iRhs);
237699  }
237700}
237701
237702static void fts5ExprSetEof(Fts5ExprNode *pNode){
237703  int i;
237704  pNode->bEof = 1;
237705  pNode->bNomatch = 0;
237706  for(i=0; i<pNode->nChild; i++){
237707    fts5ExprSetEof(pNode->apChild[i]);
237708  }
237709}
237710
237711static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
237712  if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
237713    Fts5ExprNearset *pNear = pNode->pNear;
237714    int i;
237715    for(i=0; i<pNear->nPhrase; i++){
237716      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
237717      pPhrase->poslist.n = 0;
237718    }
237719  }else{
237720    int i;
237721    for(i=0; i<pNode->nChild; i++){
237722      fts5ExprNodeZeroPoslist(pNode->apChild[i]);
237723    }
237724  }
237725}
237726
237727
237728
237729/*
237730** Compare the values currently indicated by the two nodes as follows:
237731**
237732**    res = (*p1) - (*p2)
237733**
237734** Nodes that point to values that come later in the iteration order are
237735** considered to be larger. Nodes at EOF are the largest of all.
237736**
237737** This means that if the iteration order is ASC, then numerically larger
237738** rowids are considered larger. Or if it is the default DESC, numerically
237739** smaller rowids are larger.
237740*/
237741static int fts5NodeCompare(
237742  Fts5Expr *pExpr,
237743  Fts5ExprNode *p1,
237744  Fts5ExprNode *p2
237745){
237746  if( p2->bEof ) return -1;
237747  if( p1->bEof ) return +1;
237748  return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
237749}
237750
237751/*
237752** All individual term iterators in pNear are guaranteed to be valid when
237753** this function is called. This function checks if all term iterators
237754** point to the same rowid, and if not, advances them until they do.
237755** If an EOF is reached before this happens, *pbEof is set to true before
237756** returning.
237757**
237758** SQLITE_OK is returned if an error occurs, or an SQLite error code
237759** otherwise. It is not considered an error code if an iterator reaches
237760** EOF.
237761*/
237762static int fts5ExprNodeTest_STRING(
237763  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
237764  Fts5ExprNode *pNode
237765){
237766  Fts5ExprNearset *pNear = pNode->pNear;
237767  Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
237768  int rc = SQLITE_OK;
237769  i64 iLast;                      /* Lastest rowid any iterator points to */
237770  int i, j;                       /* Phrase and token index, respectively */
237771  int bMatch;                     /* True if all terms are at the same rowid */
237772  const int bDesc = pExpr->bDesc;
237773
237774  /* Check that this node should not be FTS5_TERM */
237775  assert( pNear->nPhrase>1
237776       || pNear->apPhrase[0]->nTerm>1
237777       || pNear->apPhrase[0]->aTerm[0].pSynonym
237778       || pNear->apPhrase[0]->aTerm[0].bFirst
237779  );
237780
237781  /* Initialize iLast, the "lastest" rowid any iterator points to. If the
237782  ** iterator skips through rowids in the default ascending order, this means
237783  ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
237784  ** means the minimum rowid.  */
237785  if( pLeft->aTerm[0].pSynonym ){
237786    iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
237787  }else{
237788    iLast = pLeft->aTerm[0].pIter->iRowid;
237789  }
237790
237791  do {
237792    bMatch = 1;
237793    for(i=0; i<pNear->nPhrase; i++){
237794      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
237795      for(j=0; j<pPhrase->nTerm; j++){
237796        Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
237797        if( pTerm->pSynonym ){
237798          i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
237799          if( iRowid==iLast ) continue;
237800          bMatch = 0;
237801          if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
237802            pNode->bNomatch = 0;
237803            pNode->bEof = 1;
237804            return rc;
237805          }
237806        }else{
237807          Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
237808          if( pIter->iRowid==iLast || pIter->bEof ) continue;
237809          bMatch = 0;
237810          if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
237811            return rc;
237812          }
237813        }
237814      }
237815    }
237816  }while( bMatch==0 );
237817
237818  pNode->iRowid = iLast;
237819  pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
237820  assert( pNode->bEof==0 || pNode->bNomatch==0 );
237821
237822  return rc;
237823}
237824
237825/*
237826** Advance the first term iterator in the first phrase of pNear. Set output
237827** variable *pbEof to true if it reaches EOF or if an error occurs.
237828**
237829** Return SQLITE_OK if successful, or an SQLite error code if an error
237830** occurs.
237831*/
237832static int fts5ExprNodeNext_STRING(
237833  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
237834  Fts5ExprNode *pNode,            /* FTS5_STRING or FTS5_TERM node */
237835  int bFromValid,
237836  i64 iFrom
237837){
237838  Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
237839  int rc = SQLITE_OK;
237840
237841  pNode->bNomatch = 0;
237842  if( pTerm->pSynonym ){
237843    int bEof = 1;
237844    Fts5ExprTerm *p;
237845
237846    /* Find the firstest rowid any synonym points to. */
237847    i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
237848
237849    /* Advance each iterator that currently points to iRowid. Or, if iFrom
237850    ** is valid - each iterator that points to a rowid before iFrom.  */
237851    for(p=pTerm; p; p=p->pSynonym){
237852      if( sqlite3Fts5IterEof(p->pIter)==0 ){
237853        i64 ii = p->pIter->iRowid;
237854        if( ii==iRowid
237855         || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
237856        ){
237857          if( bFromValid ){
237858            rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
237859          }else{
237860            rc = sqlite3Fts5IterNext(p->pIter);
237861          }
237862          if( rc!=SQLITE_OK ) break;
237863          if( sqlite3Fts5IterEof(p->pIter)==0 ){
237864            bEof = 0;
237865          }
237866        }else{
237867          bEof = 0;
237868        }
237869      }
237870    }
237871
237872    /* Set the EOF flag if either all synonym iterators are at EOF or an
237873    ** error has occurred.  */
237874    pNode->bEof = (rc || bEof);
237875  }else{
237876    Fts5IndexIter *pIter = pTerm->pIter;
237877
237878    assert( Fts5NodeIsString(pNode) );
237879    if( bFromValid ){
237880      rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
237881    }else{
237882      rc = sqlite3Fts5IterNext(pIter);
237883    }
237884
237885    pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
237886  }
237887
237888  if( pNode->bEof==0 ){
237889    assert( rc==SQLITE_OK );
237890    rc = fts5ExprNodeTest_STRING(pExpr, pNode);
237891  }
237892
237893  return rc;
237894}
237895
237896
237897static int fts5ExprNodeTest_TERM(
237898  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
237899  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_TERM) */
237900){
237901  /* As this "NEAR" object is actually a single phrase that consists
237902  ** of a single term only, grab pointers into the poslist managed by the
237903  ** fts5_index.c iterator object. This is much faster than synthesizing
237904  ** a new poslist the way we have to for more complicated phrase or NEAR
237905  ** expressions.  */
237906  Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
237907  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
237908
237909  assert( pNode->eType==FTS5_TERM );
237910  assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
237911  assert( pPhrase->aTerm[0].pSynonym==0 );
237912
237913  pPhrase->poslist.n = pIter->nData;
237914  if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
237915    pPhrase->poslist.p = (u8*)pIter->pData;
237916  }
237917  pNode->iRowid = pIter->iRowid;
237918  pNode->bNomatch = (pPhrase->poslist.n==0);
237919  return SQLITE_OK;
237920}
237921
237922/*
237923** xNext() method for a node of type FTS5_TERM.
237924*/
237925static int fts5ExprNodeNext_TERM(
237926  Fts5Expr *pExpr,
237927  Fts5ExprNode *pNode,
237928  int bFromValid,
237929  i64 iFrom
237930){
237931  int rc;
237932  Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
237933
237934  assert( pNode->bEof==0 );
237935  if( bFromValid ){
237936    rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
237937  }else{
237938    rc = sqlite3Fts5IterNext(pIter);
237939  }
237940  if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
237941    rc = fts5ExprNodeTest_TERM(pExpr, pNode);
237942  }else{
237943    pNode->bEof = 1;
237944    pNode->bNomatch = 0;
237945  }
237946  return rc;
237947}
237948
237949static void fts5ExprNodeTest_OR(
237950  Fts5Expr *pExpr,                /* Expression of which pNode is a part */
237951  Fts5ExprNode *pNode             /* Expression node to test */
237952){
237953  Fts5ExprNode *pNext = pNode->apChild[0];
237954  int i;
237955
237956  for(i=1; i<pNode->nChild; i++){
237957    Fts5ExprNode *pChild = pNode->apChild[i];
237958    int cmp = fts5NodeCompare(pExpr, pNext, pChild);
237959    if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
237960      pNext = pChild;
237961    }
237962  }
237963  pNode->iRowid = pNext->iRowid;
237964  pNode->bEof = pNext->bEof;
237965  pNode->bNomatch = pNext->bNomatch;
237966}
237967
237968static int fts5ExprNodeNext_OR(
237969  Fts5Expr *pExpr,
237970  Fts5ExprNode *pNode,
237971  int bFromValid,
237972  i64 iFrom
237973){
237974  int i;
237975  i64 iLast = pNode->iRowid;
237976
237977  for(i=0; i<pNode->nChild; i++){
237978    Fts5ExprNode *p1 = pNode->apChild[i];
237979    assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
237980    if( p1->bEof==0 ){
237981      if( (p1->iRowid==iLast)
237982       || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
237983      ){
237984        int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
237985        if( rc!=SQLITE_OK ){
237986          pNode->bNomatch = 0;
237987          return rc;
237988        }
237989      }
237990    }
237991  }
237992
237993  fts5ExprNodeTest_OR(pExpr, pNode);
237994  return SQLITE_OK;
237995}
237996
237997/*
237998** Argument pNode is an FTS5_AND node.
237999*/
238000static int fts5ExprNodeTest_AND(
238001  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
238002  Fts5ExprNode *pAnd              /* FTS5_AND node to advance */
238003){
238004  int iChild;
238005  i64 iLast = pAnd->iRowid;
238006  int rc = SQLITE_OK;
238007  int bMatch;
238008
238009  assert( pAnd->bEof==0 );
238010  do {
238011    pAnd->bNomatch = 0;
238012    bMatch = 1;
238013    for(iChild=0; iChild<pAnd->nChild; iChild++){
238014      Fts5ExprNode *pChild = pAnd->apChild[iChild];
238015      int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
238016      if( cmp>0 ){
238017        /* Advance pChild until it points to iLast or laster */
238018        rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
238019        if( rc!=SQLITE_OK ){
238020          pAnd->bNomatch = 0;
238021          return rc;
238022        }
238023      }
238024
238025      /* If the child node is now at EOF, so is the parent AND node. Otherwise,
238026      ** the child node is guaranteed to have advanced at least as far as
238027      ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
238028      ** new lastest rowid seen so far.  */
238029      assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
238030      if( pChild->bEof ){
238031        fts5ExprSetEof(pAnd);
238032        bMatch = 1;
238033        break;
238034      }else if( iLast!=pChild->iRowid ){
238035        bMatch = 0;
238036        iLast = pChild->iRowid;
238037      }
238038
238039      if( pChild->bNomatch ){
238040        pAnd->bNomatch = 1;
238041      }
238042    }
238043  }while( bMatch==0 );
238044
238045  if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
238046    fts5ExprNodeZeroPoslist(pAnd);
238047  }
238048  pAnd->iRowid = iLast;
238049  return SQLITE_OK;
238050}
238051
238052static int fts5ExprNodeNext_AND(
238053  Fts5Expr *pExpr,
238054  Fts5ExprNode *pNode,
238055  int bFromValid,
238056  i64 iFrom
238057){
238058  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
238059  if( rc==SQLITE_OK ){
238060    rc = fts5ExprNodeTest_AND(pExpr, pNode);
238061  }else{
238062    pNode->bNomatch = 0;
238063  }
238064  return rc;
238065}
238066
238067static int fts5ExprNodeTest_NOT(
238068  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
238069  Fts5ExprNode *pNode             /* FTS5_NOT node to advance */
238070){
238071  int rc = SQLITE_OK;
238072  Fts5ExprNode *p1 = pNode->apChild[0];
238073  Fts5ExprNode *p2 = pNode->apChild[1];
238074  assert( pNode->nChild==2 );
238075
238076  while( rc==SQLITE_OK && p1->bEof==0 ){
238077    int cmp = fts5NodeCompare(pExpr, p1, p2);
238078    if( cmp>0 ){
238079      rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
238080      cmp = fts5NodeCompare(pExpr, p1, p2);
238081    }
238082    assert( rc!=SQLITE_OK || cmp<=0 );
238083    if( cmp || p2->bNomatch ) break;
238084    rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
238085  }
238086  pNode->bEof = p1->bEof;
238087  pNode->bNomatch = p1->bNomatch;
238088  pNode->iRowid = p1->iRowid;
238089  if( p1->bEof ){
238090    fts5ExprNodeZeroPoslist(p2);
238091  }
238092  return rc;
238093}
238094
238095static int fts5ExprNodeNext_NOT(
238096  Fts5Expr *pExpr,
238097  Fts5ExprNode *pNode,
238098  int bFromValid,
238099  i64 iFrom
238100){
238101  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
238102  if( rc==SQLITE_OK ){
238103    rc = fts5ExprNodeTest_NOT(pExpr, pNode);
238104  }
238105  if( rc!=SQLITE_OK ){
238106    pNode->bNomatch = 0;
238107  }
238108  return rc;
238109}
238110
238111/*
238112** If pNode currently points to a match, this function returns SQLITE_OK
238113** without modifying it. Otherwise, pNode is advanced until it does point
238114** to a match or EOF is reached.
238115*/
238116static int fts5ExprNodeTest(
238117  Fts5Expr *pExpr,                /* Expression of which pNode is a part */
238118  Fts5ExprNode *pNode             /* Expression node to test */
238119){
238120  int rc = SQLITE_OK;
238121  if( pNode->bEof==0 ){
238122    switch( pNode->eType ){
238123
238124      case FTS5_STRING: {
238125        rc = fts5ExprNodeTest_STRING(pExpr, pNode);
238126        break;
238127      }
238128
238129      case FTS5_TERM: {
238130        rc = fts5ExprNodeTest_TERM(pExpr, pNode);
238131        break;
238132      }
238133
238134      case FTS5_AND: {
238135        rc = fts5ExprNodeTest_AND(pExpr, pNode);
238136        break;
238137      }
238138
238139      case FTS5_OR: {
238140        fts5ExprNodeTest_OR(pExpr, pNode);
238141        break;
238142      }
238143
238144      default: assert( pNode->eType==FTS5_NOT ); {
238145        rc = fts5ExprNodeTest_NOT(pExpr, pNode);
238146        break;
238147      }
238148    }
238149  }
238150  return rc;
238151}
238152
238153
238154/*
238155** Set node pNode, which is part of expression pExpr, to point to the first
238156** match. If there are no matches, set the Node.bEof flag to indicate EOF.
238157**
238158** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
238159** It is not an error if there are no matches.
238160*/
238161static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
238162  int rc = SQLITE_OK;
238163  pNode->bEof = 0;
238164  pNode->bNomatch = 0;
238165
238166  if( Fts5NodeIsString(pNode) ){
238167    /* Initialize all term iterators in the NEAR object. */
238168    rc = fts5ExprNearInitAll(pExpr, pNode);
238169  }else if( pNode->xNext==0 ){
238170    pNode->bEof = 1;
238171  }else{
238172    int i;
238173    int nEof = 0;
238174    for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
238175      Fts5ExprNode *pChild = pNode->apChild[i];
238176      rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
238177      assert( pChild->bEof==0 || pChild->bEof==1 );
238178      nEof += pChild->bEof;
238179    }
238180    pNode->iRowid = pNode->apChild[0]->iRowid;
238181
238182    switch( pNode->eType ){
238183      case FTS5_AND:
238184        if( nEof>0 ) fts5ExprSetEof(pNode);
238185        break;
238186
238187      case FTS5_OR:
238188        if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
238189        break;
238190
238191      default:
238192        assert( pNode->eType==FTS5_NOT );
238193        pNode->bEof = pNode->apChild[0]->bEof;
238194        break;
238195    }
238196  }
238197
238198  if( rc==SQLITE_OK ){
238199    rc = fts5ExprNodeTest(pExpr, pNode);
238200  }
238201  return rc;
238202}
238203
238204
238205/*
238206** Begin iterating through the set of documents in index pIdx matched by
238207** the MATCH expression passed as the first argument. If the "bDesc"
238208** parameter is passed a non-zero value, iteration is in descending rowid
238209** order. Or, if it is zero, in ascending order.
238210**
238211** If iterating in ascending rowid order (bDesc==0), the first document
238212** visited is that with the smallest rowid that is larger than or equal
238213** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
238214** then the first document visited must have a rowid smaller than or
238215** equal to iFirst.
238216**
238217** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
238218** is not considered an error if the query does not match any documents.
238219*/
238220static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
238221  Fts5ExprNode *pRoot = p->pRoot;
238222  int rc;                         /* Return code */
238223
238224  p->pIndex = pIdx;
238225  p->bDesc = bDesc;
238226  rc = fts5ExprNodeFirst(p, pRoot);
238227
238228  /* If not at EOF but the current rowid occurs earlier than iFirst in
238229  ** the iteration order, move to document iFirst or later. */
238230  if( rc==SQLITE_OK
238231   && 0==pRoot->bEof
238232   && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
238233  ){
238234    rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
238235  }
238236
238237  /* If the iterator is not at a real match, skip forward until it is. */
238238  while( pRoot->bNomatch && rc==SQLITE_OK ){
238239    assert( pRoot->bEof==0 );
238240    rc = fts5ExprNodeNext(p, pRoot, 0, 0);
238241  }
238242  return rc;
238243}
238244
238245/*
238246** Move to the next document
238247**
238248** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
238249** is not considered an error if the query does not match any documents.
238250*/
238251static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
238252  int rc;
238253  Fts5ExprNode *pRoot = p->pRoot;
238254  assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
238255  do {
238256    rc = fts5ExprNodeNext(p, pRoot, 0, 0);
238257    assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
238258  }while( pRoot->bNomatch );
238259  if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
238260    pRoot->bEof = 1;
238261  }
238262  return rc;
238263}
238264
238265static int sqlite3Fts5ExprEof(Fts5Expr *p){
238266  return p->pRoot->bEof;
238267}
238268
238269static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
238270  return p->pRoot->iRowid;
238271}
238272
238273static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
238274  int rc = SQLITE_OK;
238275  *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
238276  return rc;
238277}
238278
238279/*
238280** Free the phrase object passed as the only argument.
238281*/
238282static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
238283  if( pPhrase ){
238284    int i;
238285    for(i=0; i<pPhrase->nTerm; i++){
238286      Fts5ExprTerm *pSyn;
238287      Fts5ExprTerm *pNext;
238288      Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
238289      sqlite3_free(pTerm->pTerm);
238290      sqlite3Fts5IterClose(pTerm->pIter);
238291      for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
238292        pNext = pSyn->pSynonym;
238293        sqlite3Fts5IterClose(pSyn->pIter);
238294        fts5BufferFree((Fts5Buffer*)&pSyn[1]);
238295        sqlite3_free(pSyn);
238296      }
238297    }
238298    if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
238299    sqlite3_free(pPhrase);
238300  }
238301}
238302
238303/*
238304** Set the "bFirst" flag on the first token of the phrase passed as the
238305** only argument.
238306*/
238307static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase *pPhrase){
238308  if( pPhrase && pPhrase->nTerm ){
238309    pPhrase->aTerm[0].bFirst = 1;
238310  }
238311}
238312
238313/*
238314** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
238315** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
238316** appended to it and the results returned.
238317**
238318** If an OOM error occurs, both the pNear and pPhrase objects are freed and
238319** NULL returned.
238320*/
238321static Fts5ExprNearset *sqlite3Fts5ParseNearset(
238322  Fts5Parse *pParse,              /* Parse context */
238323  Fts5ExprNearset *pNear,         /* Existing nearset, or NULL */
238324  Fts5ExprPhrase *pPhrase         /* Recently parsed phrase */
238325){
238326  const int SZALLOC = 8;
238327  Fts5ExprNearset *pRet = 0;
238328
238329  if( pParse->rc==SQLITE_OK ){
238330    if( pPhrase==0 ){
238331      return pNear;
238332    }
238333    if( pNear==0 ){
238334      sqlite3_int64 nByte;
238335      nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
238336      pRet = sqlite3_malloc64(nByte);
238337      if( pRet==0 ){
238338        pParse->rc = SQLITE_NOMEM;
238339      }else{
238340        memset(pRet, 0, (size_t)nByte);
238341      }
238342    }else if( (pNear->nPhrase % SZALLOC)==0 ){
238343      int nNew = pNear->nPhrase + SZALLOC;
238344      sqlite3_int64 nByte;
238345
238346      nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
238347      pRet = (Fts5ExprNearset*)sqlite3_realloc64(pNear, nByte);
238348      if( pRet==0 ){
238349        pParse->rc = SQLITE_NOMEM;
238350      }
238351    }else{
238352      pRet = pNear;
238353    }
238354  }
238355
238356  if( pRet==0 ){
238357    assert( pParse->rc!=SQLITE_OK );
238358    sqlite3Fts5ParseNearsetFree(pNear);
238359    sqlite3Fts5ParsePhraseFree(pPhrase);
238360  }else{
238361    if( pRet->nPhrase>0 ){
238362      Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
238363      assert( pParse!=0 );
238364      assert( pParse->apPhrase!=0 );
238365      assert( pParse->nPhrase>=2 );
238366      assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
238367      if( pPhrase->nTerm==0 ){
238368        fts5ExprPhraseFree(pPhrase);
238369        pRet->nPhrase--;
238370        pParse->nPhrase--;
238371        pPhrase = pLast;
238372      }else if( pLast->nTerm==0 ){
238373        fts5ExprPhraseFree(pLast);
238374        pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
238375        pParse->nPhrase--;
238376        pRet->nPhrase--;
238377      }
238378    }
238379    pRet->apPhrase[pRet->nPhrase++] = pPhrase;
238380  }
238381  return pRet;
238382}
238383
238384typedef struct TokenCtx TokenCtx;
238385struct TokenCtx {
238386  Fts5ExprPhrase *pPhrase;
238387  Fts5Config *pConfig;
238388  int rc;
238389};
238390
238391/*
238392** Callback for tokenizing terms used by ParseTerm().
238393*/
238394static int fts5ParseTokenize(
238395  void *pContext,                 /* Pointer to Fts5InsertCtx object */
238396  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
238397  const char *pToken,             /* Buffer containing token */
238398  int nToken,                     /* Size of token in bytes */
238399  int iUnused1,                   /* Start offset of token */
238400  int iUnused2                    /* End offset of token */
238401){
238402  int rc = SQLITE_OK;
238403  const int SZALLOC = 8;
238404  TokenCtx *pCtx = (TokenCtx*)pContext;
238405  Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
238406
238407  UNUSED_PARAM2(iUnused1, iUnused2);
238408
238409  /* If an error has already occurred, this is a no-op */
238410  if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
238411  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
238412
238413  if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
238414    Fts5ExprTerm *pSyn;
238415    sqlite3_int64 nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
238416    pSyn = (Fts5ExprTerm*)sqlite3_malloc64(nByte);
238417    if( pSyn==0 ){
238418      rc = SQLITE_NOMEM;
238419    }else{
238420      memset(pSyn, 0, (size_t)nByte);
238421      pSyn->pTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
238422      pSyn->nFullTerm = pSyn->nQueryTerm = nToken;
238423      if( pCtx->pConfig->bTokendata ){
238424        pSyn->nQueryTerm = (int)strlen(pSyn->pTerm);
238425      }
238426      memcpy(pSyn->pTerm, pToken, nToken);
238427      pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
238428      pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
238429    }
238430  }else{
238431    Fts5ExprTerm *pTerm;
238432    if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
238433      Fts5ExprPhrase *pNew;
238434      int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
238435
238436      pNew = (Fts5ExprPhrase*)sqlite3_realloc64(pPhrase,
238437          sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
238438      );
238439      if( pNew==0 ){
238440        rc = SQLITE_NOMEM;
238441      }else{
238442        if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
238443        pCtx->pPhrase = pPhrase = pNew;
238444        pNew->nTerm = nNew - SZALLOC;
238445      }
238446    }
238447
238448    if( rc==SQLITE_OK ){
238449      pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
238450      memset(pTerm, 0, sizeof(Fts5ExprTerm));
238451      pTerm->pTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
238452      pTerm->nFullTerm = pTerm->nQueryTerm = nToken;
238453      if( pCtx->pConfig->bTokendata && rc==SQLITE_OK ){
238454        pTerm->nQueryTerm = (int)strlen(pTerm->pTerm);
238455      }
238456    }
238457  }
238458
238459  pCtx->rc = rc;
238460  return rc;
238461}
238462
238463
238464/*
238465** Free the phrase object passed as the only argument.
238466*/
238467static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
238468  fts5ExprPhraseFree(pPhrase);
238469}
238470
238471/*
238472** Free the phrase object passed as the second argument.
238473*/
238474static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
238475  if( pNear ){
238476    int i;
238477    for(i=0; i<pNear->nPhrase; i++){
238478      fts5ExprPhraseFree(pNear->apPhrase[i]);
238479    }
238480    sqlite3_free(pNear->pColset);
238481    sqlite3_free(pNear);
238482  }
238483}
238484
238485static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
238486  assert( pParse->pExpr==0 );
238487  pParse->pExpr = p;
238488}
238489
238490static int parseGrowPhraseArray(Fts5Parse *pParse){
238491  if( (pParse->nPhrase % 8)==0 ){
238492    sqlite3_int64 nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
238493    Fts5ExprPhrase **apNew;
238494    apNew = (Fts5ExprPhrase**)sqlite3_realloc64(pParse->apPhrase, nByte);
238495    if( apNew==0 ){
238496      pParse->rc = SQLITE_NOMEM;
238497      return SQLITE_NOMEM;
238498    }
238499    pParse->apPhrase = apNew;
238500  }
238501  return SQLITE_OK;
238502}
238503
238504/*
238505** This function is called by the parser to process a string token. The
238506** string may or may not be quoted. In any case it is tokenized and a
238507** phrase object consisting of all tokens returned.
238508*/
238509static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
238510  Fts5Parse *pParse,              /* Parse context */
238511  Fts5ExprPhrase *pAppend,        /* Phrase to append to */
238512  Fts5Token *pToken,              /* String to tokenize */
238513  int bPrefix                     /* True if there is a trailing "*" */
238514){
238515  Fts5Config *pConfig = pParse->pConfig;
238516  TokenCtx sCtx;                  /* Context object passed to callback */
238517  int rc;                         /* Tokenize return code */
238518  char *z = 0;
238519
238520  memset(&sCtx, 0, sizeof(TokenCtx));
238521  sCtx.pPhrase = pAppend;
238522  sCtx.pConfig = pConfig;
238523
238524  rc = fts5ParseStringFromToken(pToken, &z);
238525  if( rc==SQLITE_OK ){
238526    int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
238527    int n;
238528    sqlite3Fts5Dequote(z);
238529    n = (int)strlen(z);
238530    rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
238531  }
238532  sqlite3_free(z);
238533  if( rc || (rc = sCtx.rc) ){
238534    pParse->rc = rc;
238535    fts5ExprPhraseFree(sCtx.pPhrase);
238536    sCtx.pPhrase = 0;
238537  }else{
238538
238539    if( pAppend==0 ){
238540      if( parseGrowPhraseArray(pParse) ){
238541        fts5ExprPhraseFree(sCtx.pPhrase);
238542        return 0;
238543      }
238544      pParse->nPhrase++;
238545    }
238546
238547    if( sCtx.pPhrase==0 ){
238548      /* This happens when parsing a token or quoted phrase that contains
238549      ** no token characters at all. (e.g ... MATCH '""'). */
238550      sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
238551    }else if( sCtx.pPhrase->nTerm ){
238552      sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix;
238553    }
238554    pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
238555  }
238556
238557  return sCtx.pPhrase;
238558}
238559
238560/*
238561** Create a new FTS5 expression by cloning phrase iPhrase of the
238562** expression passed as the second argument.
238563*/
238564static int sqlite3Fts5ExprClonePhrase(
238565  Fts5Expr *pExpr,
238566  int iPhrase,
238567  Fts5Expr **ppNew
238568){
238569  int rc = SQLITE_OK;             /* Return code */
238570  Fts5ExprPhrase *pOrig = 0;      /* The phrase extracted from pExpr */
238571  Fts5Expr *pNew = 0;             /* Expression to return via *ppNew */
238572  TokenCtx sCtx = {0,0,0};        /* Context object for fts5ParseTokenize */
238573  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ){
238574    rc = SQLITE_RANGE;
238575  }else{
238576    pOrig = pExpr->apExprPhrase[iPhrase];
238577    pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
238578  }
238579  if( rc==SQLITE_OK ){
238580    pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
238581        sizeof(Fts5ExprPhrase*));
238582  }
238583  if( rc==SQLITE_OK ){
238584    pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
238585        sizeof(Fts5ExprNode));
238586  }
238587  if( rc==SQLITE_OK ){
238588    pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
238589        sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
238590  }
238591  if( rc==SQLITE_OK && ALWAYS(pOrig!=0) ){
238592    Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
238593    if( pColsetOrig ){
238594      sqlite3_int64 nByte;
238595      Fts5Colset *pColset;
238596      nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
238597      pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
238598      if( pColset ){
238599        memcpy(pColset, pColsetOrig, (size_t)nByte);
238600      }
238601      pNew->pRoot->pNear->pColset = pColset;
238602    }
238603  }
238604
238605  if( rc==SQLITE_OK ){
238606    if( pOrig->nTerm ){
238607      int i;                          /* Used to iterate through phrase terms */
238608      sCtx.pConfig = pExpr->pConfig;
238609      for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
238610        int tflags = 0;
238611        Fts5ExprTerm *p;
238612        for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
238613          rc = fts5ParseTokenize((void*)&sCtx,tflags,p->pTerm,p->nFullTerm,0,0);
238614          tflags = FTS5_TOKEN_COLOCATED;
238615        }
238616        if( rc==SQLITE_OK ){
238617          sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
238618          sCtx.pPhrase->aTerm[i].bFirst = pOrig->aTerm[i].bFirst;
238619        }
238620      }
238621    }else{
238622      /* This happens when parsing a token or quoted phrase that contains
238623      ** no token characters at all. (e.g ... MATCH '""'). */
238624      sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
238625    }
238626  }
238627
238628  if( rc==SQLITE_OK && ALWAYS(sCtx.pPhrase) ){
238629    /* All the allocations succeeded. Put the expression object together. */
238630    pNew->pIndex = pExpr->pIndex;
238631    pNew->pConfig = pExpr->pConfig;
238632    pNew->nPhrase = 1;
238633    pNew->apExprPhrase[0] = sCtx.pPhrase;
238634    pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
238635    pNew->pRoot->pNear->nPhrase = 1;
238636    sCtx.pPhrase->pNode = pNew->pRoot;
238637
238638    if( pOrig->nTerm==1
238639     && pOrig->aTerm[0].pSynonym==0
238640     && pOrig->aTerm[0].bFirst==0
238641    ){
238642      pNew->pRoot->eType = FTS5_TERM;
238643      pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
238644    }else{
238645      pNew->pRoot->eType = FTS5_STRING;
238646      pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
238647    }
238648  }else{
238649    sqlite3Fts5ExprFree(pNew);
238650    fts5ExprPhraseFree(sCtx.pPhrase);
238651    pNew = 0;
238652  }
238653
238654  *ppNew = pNew;
238655  return rc;
238656}
238657
238658
238659/*
238660** Token pTok has appeared in a MATCH expression where the NEAR operator
238661** is expected. If token pTok does not contain "NEAR", store an error
238662** in the pParse object.
238663*/
238664static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
238665  if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
238666    sqlite3Fts5ParseError(
238667        pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
238668    );
238669  }
238670}
238671
238672static void sqlite3Fts5ParseSetDistance(
238673  Fts5Parse *pParse,
238674  Fts5ExprNearset *pNear,
238675  Fts5Token *p
238676){
238677  if( pNear ){
238678    int nNear = 0;
238679    int i;
238680    if( p->n ){
238681      for(i=0; i<p->n; i++){
238682        char c = (char)p->p[i];
238683        if( c<'0' || c>'9' ){
238684          sqlite3Fts5ParseError(
238685              pParse, "expected integer, got \"%.*s\"", p->n, p->p
238686              );
238687          return;
238688        }
238689        nNear = nNear * 10 + (p->p[i] - '0');
238690      }
238691    }else{
238692      nNear = FTS5_DEFAULT_NEARDIST;
238693    }
238694    pNear->nNear = nNear;
238695  }
238696}
238697
238698/*
238699** The second argument passed to this function may be NULL, or it may be
238700** an existing Fts5Colset object. This function returns a pointer to
238701** a new colset object containing the contents of (p) with new value column
238702** number iCol appended.
238703**
238704** If an OOM error occurs, store an error code in pParse and return NULL.
238705** The old colset object (if any) is not freed in this case.
238706*/
238707static Fts5Colset *fts5ParseColset(
238708  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
238709  Fts5Colset *p,                  /* Existing colset object */
238710  int iCol                        /* New column to add to colset object */
238711){
238712  int nCol = p ? p->nCol : 0;     /* Num. columns already in colset object */
238713  Fts5Colset *pNew;               /* New colset object to return */
238714
238715  assert( pParse->rc==SQLITE_OK );
238716  assert( iCol>=0 && iCol<pParse->pConfig->nCol );
238717
238718  pNew = sqlite3_realloc64(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
238719  if( pNew==0 ){
238720    pParse->rc = SQLITE_NOMEM;
238721  }else{
238722    int *aiCol = pNew->aiCol;
238723    int i, j;
238724    for(i=0; i<nCol; i++){
238725      if( aiCol[i]==iCol ) return pNew;
238726      if( aiCol[i]>iCol ) break;
238727    }
238728    for(j=nCol; j>i; j--){
238729      aiCol[j] = aiCol[j-1];
238730    }
238731    aiCol[i] = iCol;
238732    pNew->nCol = nCol+1;
238733
238734#ifndef NDEBUG
238735    /* Check that the array is in order and contains no duplicate entries. */
238736    for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
238737#endif
238738  }
238739
238740  return pNew;
238741}
238742
238743/*
238744** Allocate and return an Fts5Colset object specifying the inverse of
238745** the colset passed as the second argument. Free the colset passed
238746** as the second argument before returning.
238747*/
238748static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
238749  Fts5Colset *pRet;
238750  int nCol = pParse->pConfig->nCol;
238751
238752  pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
238753      sizeof(Fts5Colset) + sizeof(int)*nCol
238754  );
238755  if( pRet ){
238756    int i;
238757    int iOld = 0;
238758    for(i=0; i<nCol; i++){
238759      if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
238760        pRet->aiCol[pRet->nCol++] = i;
238761      }else{
238762        iOld++;
238763      }
238764    }
238765  }
238766
238767  sqlite3_free(p);
238768  return pRet;
238769}
238770
238771static Fts5Colset *sqlite3Fts5ParseColset(
238772  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
238773  Fts5Colset *pColset,            /* Existing colset object */
238774  Fts5Token *p
238775){
238776  Fts5Colset *pRet = 0;
238777  int iCol;
238778  char *z;                        /* Dequoted copy of token p */
238779
238780  z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
238781  if( pParse->rc==SQLITE_OK ){
238782    Fts5Config *pConfig = pParse->pConfig;
238783    sqlite3Fts5Dequote(z);
238784    for(iCol=0; iCol<pConfig->nCol; iCol++){
238785      if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
238786    }
238787    if( iCol==pConfig->nCol ){
238788      sqlite3Fts5ParseError(pParse, "no such column: %s", z);
238789    }else{
238790      pRet = fts5ParseColset(pParse, pColset, iCol);
238791    }
238792    sqlite3_free(z);
238793  }
238794
238795  if( pRet==0 ){
238796    assert( pParse->rc!=SQLITE_OK );
238797    sqlite3_free(pColset);
238798  }
238799
238800  return pRet;
238801}
238802
238803/*
238804** If argument pOrig is NULL, or if (*pRc) is set to anything other than
238805** SQLITE_OK when this function is called, NULL is returned.
238806**
238807** Otherwise, a copy of (*pOrig) is made into memory obtained from
238808** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
238809** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
238810*/
238811static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
238812  Fts5Colset *pRet;
238813  if( pOrig ){
238814    sqlite3_int64 nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
238815    pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
238816    if( pRet ){
238817      memcpy(pRet, pOrig, (size_t)nByte);
238818    }
238819  }else{
238820    pRet = 0;
238821  }
238822  return pRet;
238823}
238824
238825/*
238826** Remove from colset pColset any columns that are not also in colset pMerge.
238827*/
238828static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
238829  int iIn = 0;          /* Next input in pColset */
238830  int iMerge = 0;       /* Next input in pMerge */
238831  int iOut = 0;         /* Next output slot in pColset */
238832
238833  while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
238834    int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
238835    if( iDiff==0 ){
238836      pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
238837      iMerge++;
238838      iIn++;
238839    }else if( iDiff>0 ){
238840      iMerge++;
238841    }else{
238842      iIn++;
238843    }
238844  }
238845  pColset->nCol = iOut;
238846}
238847
238848/*
238849** Recursively apply colset pColset to expression node pNode and all of
238850** its decendents. If (*ppFree) is not NULL, it contains a spare copy
238851** of pColset. This function may use the spare copy and set (*ppFree) to
238852** zero, or it may create copies of pColset using fts5CloneColset().
238853*/
238854static void fts5ParseSetColset(
238855  Fts5Parse *pParse,
238856  Fts5ExprNode *pNode,
238857  Fts5Colset *pColset,
238858  Fts5Colset **ppFree
238859){
238860  if( pParse->rc==SQLITE_OK ){
238861    assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
238862         || pNode->eType==FTS5_AND  || pNode->eType==FTS5_OR
238863         || pNode->eType==FTS5_NOT  || pNode->eType==FTS5_EOF
238864    );
238865    if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
238866      Fts5ExprNearset *pNear = pNode->pNear;
238867      if( pNear->pColset ){
238868        fts5MergeColset(pNear->pColset, pColset);
238869        if( pNear->pColset->nCol==0 ){
238870          pNode->eType = FTS5_EOF;
238871          pNode->xNext = 0;
238872        }
238873      }else if( *ppFree ){
238874        pNear->pColset = pColset;
238875        *ppFree = 0;
238876      }else{
238877        pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
238878      }
238879    }else{
238880      int i;
238881      assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
238882      for(i=0; i<pNode->nChild; i++){
238883        fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
238884      }
238885    }
238886  }
238887}
238888
238889/*
238890** Apply colset pColset to expression node pExpr and all of its descendents.
238891*/
238892static void sqlite3Fts5ParseSetColset(
238893  Fts5Parse *pParse,
238894  Fts5ExprNode *pExpr,
238895  Fts5Colset *pColset
238896){
238897  Fts5Colset *pFree = pColset;
238898  if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
238899    sqlite3Fts5ParseError(pParse,
238900        "fts5: column queries are not supported (detail=none)"
238901    );
238902  }else{
238903    fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
238904  }
238905  sqlite3_free(pFree);
238906}
238907
238908static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
238909  switch( pNode->eType ){
238910    case FTS5_STRING: {
238911      Fts5ExprNearset *pNear = pNode->pNear;
238912      if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
238913       && pNear->apPhrase[0]->aTerm[0].pSynonym==0
238914       && pNear->apPhrase[0]->aTerm[0].bFirst==0
238915      ){
238916        pNode->eType = FTS5_TERM;
238917        pNode->xNext = fts5ExprNodeNext_TERM;
238918      }else{
238919        pNode->xNext = fts5ExprNodeNext_STRING;
238920      }
238921      break;
238922    };
238923
238924    case FTS5_OR: {
238925      pNode->xNext = fts5ExprNodeNext_OR;
238926      break;
238927    };
238928
238929    case FTS5_AND: {
238930      pNode->xNext = fts5ExprNodeNext_AND;
238931      break;
238932    };
238933
238934    default: assert( pNode->eType==FTS5_NOT ); {
238935      pNode->xNext = fts5ExprNodeNext_NOT;
238936      break;
238937    };
238938  }
238939}
238940
238941static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
238942  int ii = p->nChild;
238943  if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
238944    int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
238945    memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
238946    p->nChild += pSub->nChild;
238947    sqlite3_free(pSub);
238948  }else{
238949    p->apChild[p->nChild++] = pSub;
238950  }
238951  for( ; ii<p->nChild; ii++){
238952    p->iHeight = MAX(p->iHeight, p->apChild[ii]->iHeight + 1);
238953  }
238954}
238955
238956/*
238957** This function is used when parsing LIKE or GLOB patterns against
238958** trigram indexes that specify either detail=column or detail=none.
238959** It converts a phrase:
238960**
238961**     abc + def + ghi
238962**
238963** into an AND tree:
238964**
238965**     abc AND def AND ghi
238966*/
238967static Fts5ExprNode *fts5ParsePhraseToAnd(
238968  Fts5Parse *pParse,
238969  Fts5ExprNearset *pNear
238970){
238971  int nTerm = pNear->apPhrase[0]->nTerm;
238972  int ii;
238973  int nByte;
238974  Fts5ExprNode *pRet;
238975
238976  assert( pNear->nPhrase==1 );
238977  assert( pParse->bPhraseToAnd );
238978
238979  nByte = sizeof(Fts5ExprNode) + nTerm*sizeof(Fts5ExprNode*);
238980  pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
238981  if( pRet ){
238982    pRet->eType = FTS5_AND;
238983    pRet->nChild = nTerm;
238984    pRet->iHeight = 1;
238985    fts5ExprAssignXNext(pRet);
238986    pParse->nPhrase--;
238987    for(ii=0; ii<nTerm; ii++){
238988      Fts5ExprPhrase *pPhrase = (Fts5ExprPhrase*)sqlite3Fts5MallocZero(
238989          &pParse->rc, sizeof(Fts5ExprPhrase)
238990      );
238991      if( pPhrase ){
238992        if( parseGrowPhraseArray(pParse) ){
238993          fts5ExprPhraseFree(pPhrase);
238994        }else{
238995          Fts5ExprTerm *p = &pNear->apPhrase[0]->aTerm[ii];
238996          Fts5ExprTerm *pTo = &pPhrase->aTerm[0];
238997          pParse->apPhrase[pParse->nPhrase++] = pPhrase;
238998          pPhrase->nTerm = 1;
238999          pTo->pTerm = sqlite3Fts5Strndup(&pParse->rc, p->pTerm, p->nFullTerm);
239000          pTo->nQueryTerm = p->nQueryTerm;
239001          pTo->nFullTerm = p->nFullTerm;
239002          pRet->apChild[ii] = sqlite3Fts5ParseNode(pParse, FTS5_STRING,
239003              0, 0, sqlite3Fts5ParseNearset(pParse, 0, pPhrase)
239004          );
239005        }
239006      }
239007    }
239008
239009    if( pParse->rc ){
239010      sqlite3Fts5ParseNodeFree(pRet);
239011      pRet = 0;
239012    }else{
239013      sqlite3Fts5ParseNearsetFree(pNear);
239014    }
239015  }
239016
239017  return pRet;
239018}
239019
239020/*
239021** Allocate and return a new expression object. If anything goes wrong (i.e.
239022** OOM error), leave an error code in pParse and return NULL.
239023*/
239024static Fts5ExprNode *sqlite3Fts5ParseNode(
239025  Fts5Parse *pParse,              /* Parse context */
239026  int eType,                      /* FTS5_STRING, AND, OR or NOT */
239027  Fts5ExprNode *pLeft,            /* Left hand child expression */
239028  Fts5ExprNode *pRight,           /* Right hand child expression */
239029  Fts5ExprNearset *pNear          /* For STRING expressions, the near cluster */
239030){
239031  Fts5ExprNode *pRet = 0;
239032
239033  if( pParse->rc==SQLITE_OK ){
239034    int nChild = 0;               /* Number of children of returned node */
239035    sqlite3_int64 nByte;          /* Bytes of space to allocate for this node */
239036
239037    assert( (eType!=FTS5_STRING && !pNear)
239038         || (eType==FTS5_STRING && !pLeft && !pRight)
239039    );
239040    if( eType==FTS5_STRING && pNear==0 ) return 0;
239041    if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
239042    if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
239043
239044    if( eType==FTS5_STRING
239045     && pParse->bPhraseToAnd
239046     && pNear->apPhrase[0]->nTerm>1
239047    ){
239048      pRet = fts5ParsePhraseToAnd(pParse, pNear);
239049    }else{
239050      if( eType==FTS5_NOT ){
239051        nChild = 2;
239052      }else if( eType==FTS5_AND || eType==FTS5_OR ){
239053        nChild = 2;
239054        if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
239055        if( pRight->eType==eType ) nChild += pRight->nChild-1;
239056      }
239057
239058      nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
239059      pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
239060
239061      if( pRet ){
239062        pRet->eType = eType;
239063        pRet->pNear = pNear;
239064        fts5ExprAssignXNext(pRet);
239065        if( eType==FTS5_STRING ){
239066          int iPhrase;
239067          for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
239068            pNear->apPhrase[iPhrase]->pNode = pRet;
239069            if( pNear->apPhrase[iPhrase]->nTerm==0 ){
239070              pRet->xNext = 0;
239071              pRet->eType = FTS5_EOF;
239072            }
239073          }
239074
239075          if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){
239076            Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
239077            if( pNear->nPhrase!=1
239078                || pPhrase->nTerm>1
239079                || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
239080              ){
239081              sqlite3Fts5ParseError(pParse,
239082                  "fts5: %s queries are not supported (detail!=full)",
239083                  pNear->nPhrase==1 ? "phrase": "NEAR"
239084              );
239085              sqlite3_free(pRet);
239086              pRet = 0;
239087            }
239088          }
239089        }else{
239090          fts5ExprAddChildren(pRet, pLeft);
239091          fts5ExprAddChildren(pRet, pRight);
239092          if( pRet->iHeight>SQLITE_FTS5_MAX_EXPR_DEPTH ){
239093            sqlite3Fts5ParseError(pParse,
239094                "fts5 expression tree is too large (maximum depth %d)",
239095                SQLITE_FTS5_MAX_EXPR_DEPTH
239096            );
239097            sqlite3_free(pRet);
239098            pRet = 0;
239099          }
239100        }
239101      }
239102    }
239103  }
239104
239105  if( pRet==0 ){
239106    assert( pParse->rc!=SQLITE_OK );
239107    sqlite3Fts5ParseNodeFree(pLeft);
239108    sqlite3Fts5ParseNodeFree(pRight);
239109    sqlite3Fts5ParseNearsetFree(pNear);
239110  }
239111  return pRet;
239112}
239113
239114static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
239115  Fts5Parse *pParse,              /* Parse context */
239116  Fts5ExprNode *pLeft,            /* Left hand child expression */
239117  Fts5ExprNode *pRight            /* Right hand child expression */
239118){
239119  Fts5ExprNode *pRet = 0;
239120  Fts5ExprNode *pPrev;
239121
239122  if( pParse->rc ){
239123    sqlite3Fts5ParseNodeFree(pLeft);
239124    sqlite3Fts5ParseNodeFree(pRight);
239125  }else{
239126
239127    assert( pLeft->eType==FTS5_STRING
239128        || pLeft->eType==FTS5_TERM
239129        || pLeft->eType==FTS5_EOF
239130        || pLeft->eType==FTS5_AND
239131    );
239132    assert( pRight->eType==FTS5_STRING
239133        || pRight->eType==FTS5_TERM
239134        || pRight->eType==FTS5_EOF
239135    );
239136
239137    if( pLeft->eType==FTS5_AND ){
239138      pPrev = pLeft->apChild[pLeft->nChild-1];
239139    }else{
239140      pPrev = pLeft;
239141    }
239142    assert( pPrev->eType==FTS5_STRING
239143        || pPrev->eType==FTS5_TERM
239144        || pPrev->eType==FTS5_EOF
239145        );
239146
239147    if( pRight->eType==FTS5_EOF ){
239148      assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
239149      sqlite3Fts5ParseNodeFree(pRight);
239150      pRet = pLeft;
239151      pParse->nPhrase--;
239152    }
239153    else if( pPrev->eType==FTS5_EOF ){
239154      Fts5ExprPhrase **ap;
239155
239156      if( pPrev==pLeft ){
239157        pRet = pRight;
239158      }else{
239159        pLeft->apChild[pLeft->nChild-1] = pRight;
239160        pRet = pLeft;
239161      }
239162
239163      ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
239164      assert( ap[0]==pPrev->pNear->apPhrase[0] );
239165      memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
239166      pParse->nPhrase--;
239167
239168      sqlite3Fts5ParseNodeFree(pPrev);
239169    }
239170    else{
239171      pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
239172    }
239173  }
239174
239175  return pRet;
239176}
239177
239178#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
239179static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
239180  sqlite3_int64 nByte = 0;
239181  Fts5ExprTerm *p;
239182  char *zQuoted;
239183
239184  /* Determine the maximum amount of space required. */
239185  for(p=pTerm; p; p=p->pSynonym){
239186    nByte += pTerm->nQueryTerm * 2 + 3 + 2;
239187  }
239188  zQuoted = sqlite3_malloc64(nByte);
239189
239190  if( zQuoted ){
239191    int i = 0;
239192    for(p=pTerm; p; p=p->pSynonym){
239193      char *zIn = p->pTerm;
239194      char *zEnd = &zIn[p->nQueryTerm];
239195      zQuoted[i++] = '"';
239196      while( zIn<zEnd ){
239197        if( *zIn=='"' ) zQuoted[i++] = '"';
239198        zQuoted[i++] = *zIn++;
239199      }
239200      zQuoted[i++] = '"';
239201      if( p->pSynonym ) zQuoted[i++] = '|';
239202    }
239203    if( pTerm->bPrefix ){
239204      zQuoted[i++] = ' ';
239205      zQuoted[i++] = '*';
239206    }
239207    zQuoted[i++] = '\0';
239208  }
239209  return zQuoted;
239210}
239211
239212static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
239213  char *zNew;
239214  va_list ap;
239215  va_start(ap, zFmt);
239216  zNew = sqlite3_vmprintf(zFmt, ap);
239217  va_end(ap);
239218  if( zApp && zNew ){
239219    char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
239220    sqlite3_free(zNew);
239221    zNew = zNew2;
239222  }
239223  sqlite3_free(zApp);
239224  return zNew;
239225}
239226
239227/*
239228** Compose a tcl-readable representation of expression pExpr. Return a
239229** pointer to a buffer containing that representation. It is the
239230** responsibility of the caller to at some point free the buffer using
239231** sqlite3_free().
239232*/
239233static char *fts5ExprPrintTcl(
239234  Fts5Config *pConfig,
239235  const char *zNearsetCmd,
239236  Fts5ExprNode *pExpr
239237){
239238  char *zRet = 0;
239239  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
239240    Fts5ExprNearset *pNear = pExpr->pNear;
239241    int i;
239242    int iTerm;
239243
239244    zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
239245    if( zRet==0 ) return 0;
239246    if( pNear->pColset ){
239247      int *aiCol = pNear->pColset->aiCol;
239248      int nCol = pNear->pColset->nCol;
239249      if( nCol==1 ){
239250        zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
239251      }else{
239252        zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
239253        for(i=1; i<pNear->pColset->nCol; i++){
239254          zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
239255        }
239256        zRet = fts5PrintfAppend(zRet, "} ");
239257      }
239258      if( zRet==0 ) return 0;
239259    }
239260
239261    if( pNear->nPhrase>1 ){
239262      zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
239263      if( zRet==0 ) return 0;
239264    }
239265
239266    zRet = fts5PrintfAppend(zRet, "--");
239267    if( zRet==0 ) return 0;
239268
239269    for(i=0; i<pNear->nPhrase; i++){
239270      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
239271
239272      zRet = fts5PrintfAppend(zRet, " {");
239273      for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
239274        Fts5ExprTerm *p = &pPhrase->aTerm[iTerm];
239275        zRet = fts5PrintfAppend(zRet, "%s%.*s", iTerm==0?"":" ",
239276            p->nQueryTerm, p->pTerm
239277        );
239278        if( pPhrase->aTerm[iTerm].bPrefix ){
239279          zRet = fts5PrintfAppend(zRet, "*");
239280        }
239281      }
239282
239283      if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
239284      if( zRet==0 ) return 0;
239285    }
239286
239287  }else if( pExpr->eType==0 ){
239288    zRet = sqlite3_mprintf("{}");
239289  }else{
239290    char const *zOp = 0;
239291    int i;
239292    switch( pExpr->eType ){
239293      case FTS5_AND: zOp = "AND"; break;
239294      case FTS5_NOT: zOp = "NOT"; break;
239295      default:
239296        assert( pExpr->eType==FTS5_OR );
239297        zOp = "OR";
239298        break;
239299    }
239300
239301    zRet = sqlite3_mprintf("%s", zOp);
239302    for(i=0; zRet && i<pExpr->nChild; i++){
239303      char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
239304      if( !z ){
239305        sqlite3_free(zRet);
239306        zRet = 0;
239307      }else{
239308        zRet = fts5PrintfAppend(zRet, " [%z]", z);
239309      }
239310    }
239311  }
239312
239313  return zRet;
239314}
239315
239316static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
239317  char *zRet = 0;
239318  if( pExpr->eType==0 ){
239319    return sqlite3_mprintf("\"\"");
239320  }else
239321  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
239322    Fts5ExprNearset *pNear = pExpr->pNear;
239323    int i;
239324    int iTerm;
239325
239326    if( pNear->pColset ){
239327      int ii;
239328      Fts5Colset *pColset = pNear->pColset;
239329      if( pColset->nCol>1 ) zRet = fts5PrintfAppend(zRet, "{");
239330      for(ii=0; ii<pColset->nCol; ii++){
239331        zRet = fts5PrintfAppend(zRet, "%s%s",
239332            pConfig->azCol[pColset->aiCol[ii]], ii==pColset->nCol-1 ? "" : " "
239333        );
239334      }
239335      if( zRet ){
239336        zRet = fts5PrintfAppend(zRet, "%s : ", pColset->nCol>1 ? "}" : "");
239337      }
239338      if( zRet==0 ) return 0;
239339    }
239340
239341    if( pNear->nPhrase>1 ){
239342      zRet = fts5PrintfAppend(zRet, "NEAR(");
239343      if( zRet==0 ) return 0;
239344    }
239345
239346    for(i=0; i<pNear->nPhrase; i++){
239347      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
239348      if( i!=0 ){
239349        zRet = fts5PrintfAppend(zRet, " ");
239350        if( zRet==0 ) return 0;
239351      }
239352      for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
239353        char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
239354        if( zTerm ){
239355          zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
239356          sqlite3_free(zTerm);
239357        }
239358        if( zTerm==0 || zRet==0 ){
239359          sqlite3_free(zRet);
239360          return 0;
239361        }
239362      }
239363    }
239364
239365    if( pNear->nPhrase>1 ){
239366      zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
239367      if( zRet==0 ) return 0;
239368    }
239369
239370  }else{
239371    char const *zOp = 0;
239372    int i;
239373
239374    switch( pExpr->eType ){
239375      case FTS5_AND: zOp = " AND "; break;
239376      case FTS5_NOT: zOp = " NOT "; break;
239377      default:
239378        assert( pExpr->eType==FTS5_OR );
239379        zOp = " OR ";
239380        break;
239381    }
239382
239383    for(i=0; i<pExpr->nChild; i++){
239384      char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
239385      if( z==0 ){
239386        sqlite3_free(zRet);
239387        zRet = 0;
239388      }else{
239389        int e = pExpr->apChild[i]->eType;
239390        int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
239391        zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
239392            (i==0 ? "" : zOp),
239393            (b?"(":""), z, (b?")":"")
239394        );
239395      }
239396      if( zRet==0 ) break;
239397    }
239398  }
239399
239400  return zRet;
239401}
239402
239403/*
239404** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
239405** and fts5_expr_tcl() (bTcl!=0).
239406*/
239407static void fts5ExprFunction(
239408  sqlite3_context *pCtx,          /* Function call context */
239409  int nArg,                       /* Number of args */
239410  sqlite3_value **apVal,          /* Function arguments */
239411  int bTcl
239412){
239413  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
239414  sqlite3 *db = sqlite3_context_db_handle(pCtx);
239415  const char *zExpr = 0;
239416  char *zErr = 0;
239417  Fts5Expr *pExpr = 0;
239418  int rc;
239419  int i;
239420
239421  const char **azConfig;          /* Array of arguments for Fts5Config */
239422  const char *zNearsetCmd = "nearset";
239423  int nConfig;                    /* Size of azConfig[] */
239424  Fts5Config *pConfig = 0;
239425  int iArg = 1;
239426
239427  if( nArg<1 ){
239428    zErr = sqlite3_mprintf("wrong number of arguments to function %s",
239429        bTcl ? "fts5_expr_tcl" : "fts5_expr"
239430    );
239431    sqlite3_result_error(pCtx, zErr, -1);
239432    sqlite3_free(zErr);
239433    return;
239434  }
239435
239436  if( bTcl && nArg>1 ){
239437    zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
239438    iArg = 2;
239439  }
239440
239441  nConfig = 3 + (nArg-iArg);
239442  azConfig = (const char**)sqlite3_malloc64(sizeof(char*) * nConfig);
239443  if( azConfig==0 ){
239444    sqlite3_result_error_nomem(pCtx);
239445    return;
239446  }
239447  azConfig[0] = 0;
239448  azConfig[1] = "main";
239449  azConfig[2] = "tbl";
239450  for(i=3; iArg<nArg; iArg++){
239451    const char *z = (const char*)sqlite3_value_text(apVal[iArg]);
239452    azConfig[i++] = (z ? z : "");
239453  }
239454
239455  zExpr = (const char*)sqlite3_value_text(apVal[0]);
239456  if( zExpr==0 ) zExpr = "";
239457
239458  rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
239459  if( rc==SQLITE_OK ){
239460    rc = sqlite3Fts5ExprNew(pConfig, 0, pConfig->nCol, zExpr, &pExpr, &zErr);
239461  }
239462  if( rc==SQLITE_OK ){
239463    char *zText;
239464    if( pExpr->pRoot->xNext==0 ){
239465      zText = sqlite3_mprintf("");
239466    }else if( bTcl ){
239467      zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
239468    }else{
239469      zText = fts5ExprPrint(pConfig, pExpr->pRoot);
239470    }
239471    if( zText==0 ){
239472      rc = SQLITE_NOMEM;
239473    }else{
239474      sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
239475      sqlite3_free(zText);
239476    }
239477  }
239478
239479  if( rc!=SQLITE_OK ){
239480    if( zErr ){
239481      sqlite3_result_error(pCtx, zErr, -1);
239482      sqlite3_free(zErr);
239483    }else{
239484      sqlite3_result_error_code(pCtx, rc);
239485    }
239486  }
239487  sqlite3_free((void *)azConfig);
239488  sqlite3Fts5ConfigFree(pConfig);
239489  sqlite3Fts5ExprFree(pExpr);
239490}
239491
239492static void fts5ExprFunctionHr(
239493  sqlite3_context *pCtx,          /* Function call context */
239494  int nArg,                       /* Number of args */
239495  sqlite3_value **apVal           /* Function arguments */
239496){
239497  fts5ExprFunction(pCtx, nArg, apVal, 0);
239498}
239499static void fts5ExprFunctionTcl(
239500  sqlite3_context *pCtx,          /* Function call context */
239501  int nArg,                       /* Number of args */
239502  sqlite3_value **apVal           /* Function arguments */
239503){
239504  fts5ExprFunction(pCtx, nArg, apVal, 1);
239505}
239506
239507/*
239508** The implementation of an SQLite user-defined-function that accepts a
239509** single integer as an argument. If the integer is an alpha-numeric
239510** unicode code point, 1 is returned. Otherwise 0.
239511*/
239512static void fts5ExprIsAlnum(
239513  sqlite3_context *pCtx,          /* Function call context */
239514  int nArg,                       /* Number of args */
239515  sqlite3_value **apVal           /* Function arguments */
239516){
239517  int iCode;
239518  u8 aArr[32];
239519  if( nArg!=1 ){
239520    sqlite3_result_error(pCtx,
239521        "wrong number of arguments to function fts5_isalnum", -1
239522    );
239523    return;
239524  }
239525  memset(aArr, 0, sizeof(aArr));
239526  sqlite3Fts5UnicodeCatParse("L*", aArr);
239527  sqlite3Fts5UnicodeCatParse("N*", aArr);
239528  sqlite3Fts5UnicodeCatParse("Co", aArr);
239529  iCode = sqlite3_value_int(apVal[0]);
239530  sqlite3_result_int(pCtx, aArr[sqlite3Fts5UnicodeCategory((u32)iCode)]);
239531}
239532
239533static void fts5ExprFold(
239534  sqlite3_context *pCtx,          /* Function call context */
239535  int nArg,                       /* Number of args */
239536  sqlite3_value **apVal           /* Function arguments */
239537){
239538  if( nArg!=1 && nArg!=2 ){
239539    sqlite3_result_error(pCtx,
239540        "wrong number of arguments to function fts5_fold", -1
239541    );
239542  }else{
239543    int iCode;
239544    int bRemoveDiacritics = 0;
239545    iCode = sqlite3_value_int(apVal[0]);
239546    if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
239547    sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
239548  }
239549}
239550#endif /* if SQLITE_TEST || SQLITE_FTS5_DEBUG */
239551
239552/*
239553** This is called during initialization to register the fts5_expr() scalar
239554** UDF with the SQLite handle passed as the only argument.
239555*/
239556static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
239557#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
239558  struct Fts5ExprFunc {
239559    const char *z;
239560    void (*x)(sqlite3_context*,int,sqlite3_value**);
239561  } aFunc[] = {
239562    { "fts5_expr",     fts5ExprFunctionHr },
239563    { "fts5_expr_tcl", fts5ExprFunctionTcl },
239564    { "fts5_isalnum",  fts5ExprIsAlnum },
239565    { "fts5_fold",     fts5ExprFold },
239566  };
239567  int i;
239568  int rc = SQLITE_OK;
239569  void *pCtx = (void*)pGlobal;
239570
239571  for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
239572    struct Fts5ExprFunc *p = &aFunc[i];
239573    rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
239574  }
239575#else
239576  int rc = SQLITE_OK;
239577  UNUSED_PARAM2(pGlobal,db);
239578#endif
239579
239580  /* Avoid warnings indicating that sqlite3Fts5ParserTrace() and
239581  ** sqlite3Fts5ParserFallback() are unused */
239582#ifndef NDEBUG
239583  (void)sqlite3Fts5ParserTrace;
239584#endif
239585  (void)sqlite3Fts5ParserFallback;
239586
239587  return rc;
239588}
239589
239590/*
239591** Return the number of phrases in expression pExpr.
239592*/
239593static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
239594  return (pExpr ? pExpr->nPhrase : 0);
239595}
239596
239597/*
239598** Return the number of terms in the iPhrase'th phrase in pExpr.
239599*/
239600static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
239601  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
239602  return pExpr->apExprPhrase[iPhrase]->nTerm;
239603}
239604
239605/*
239606** This function is used to access the current position list for phrase
239607** iPhrase.
239608*/
239609static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
239610  int nRet;
239611  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
239612  Fts5ExprNode *pNode = pPhrase->pNode;
239613  if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
239614    *pa = pPhrase->poslist.p;
239615    nRet = pPhrase->poslist.n;
239616  }else{
239617    *pa = 0;
239618    nRet = 0;
239619  }
239620  return nRet;
239621}
239622
239623struct Fts5PoslistPopulator {
239624  Fts5PoslistWriter writer;
239625  int bOk;                        /* True if ok to populate */
239626  int bMiss;
239627};
239628
239629/*
239630** Clear the position lists associated with all phrases in the expression
239631** passed as the first argument. Argument bLive is true if the expression
239632** might be pointing to a real entry, otherwise it has just been reset.
239633**
239634** At present this function is only used for detail=col and detail=none
239635** fts5 tables. This implies that all phrases must be at most 1 token
239636** in size, as phrase matches are not supported without detail=full.
239637*/
239638static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
239639  Fts5PoslistPopulator *pRet;
239640  pRet = sqlite3_malloc64(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
239641  if( pRet ){
239642    int i;
239643    memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
239644    for(i=0; i<pExpr->nPhrase; i++){
239645      Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
239646      Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
239647      assert( pExpr->apExprPhrase[i]->nTerm<=1 );
239648      if( bLive &&
239649          (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
239650      ){
239651        pRet[i].bMiss = 1;
239652      }else{
239653        pBuf->n = 0;
239654      }
239655    }
239656  }
239657  return pRet;
239658}
239659
239660struct Fts5ExprCtx {
239661  Fts5Expr *pExpr;
239662  Fts5PoslistPopulator *aPopulator;
239663  i64 iOff;
239664};
239665typedef struct Fts5ExprCtx Fts5ExprCtx;
239666
239667/*
239668** TODO: Make this more efficient!
239669*/
239670static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
239671  int i;
239672  for(i=0; i<pColset->nCol; i++){
239673    if( pColset->aiCol[i]==iCol ) return 1;
239674  }
239675  return 0;
239676}
239677
239678/*
239679** pToken is a buffer nToken bytes in size that may or may not contain
239680** an embedded 0x00 byte. If it does, return the number of bytes in
239681** the buffer before the 0x00. If it does not, return nToken.
239682*/
239683static int fts5QueryTerm(const char *pToken, int nToken){
239684  int ii;
239685  for(ii=0; ii<nToken && pToken[ii]; ii++){}
239686  return ii;
239687}
239688
239689static int fts5ExprPopulatePoslistsCb(
239690  void *pCtx,                /* Copy of 2nd argument to xTokenize() */
239691  int tflags,                /* Mask of FTS5_TOKEN_* flags */
239692  const char *pToken,        /* Pointer to buffer containing token */
239693  int nToken,                /* Size of token in bytes */
239694  int iUnused1,              /* Byte offset of token within input text */
239695  int iUnused2               /* Byte offset of end of token within input text */
239696){
239697  Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
239698  Fts5Expr *pExpr = p->pExpr;
239699  int i;
239700  int nQuery = nToken;
239701  i64 iRowid = pExpr->pRoot->iRowid;
239702
239703  UNUSED_PARAM2(iUnused1, iUnused2);
239704
239705  if( nQuery>FTS5_MAX_TOKEN_SIZE ) nQuery = FTS5_MAX_TOKEN_SIZE;
239706  if( pExpr->pConfig->bTokendata ){
239707    nQuery = fts5QueryTerm(pToken, nQuery);
239708  }
239709  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
239710  for(i=0; i<pExpr->nPhrase; i++){
239711    Fts5ExprTerm *pT;
239712    if( p->aPopulator[i].bOk==0 ) continue;
239713    for(pT=&pExpr->apExprPhrase[i]->aTerm[0]; pT; pT=pT->pSynonym){
239714      if( (pT->nQueryTerm==nQuery || (pT->nQueryTerm<nQuery && pT->bPrefix))
239715       && memcmp(pT->pTerm, pToken, pT->nQueryTerm)==0
239716      ){
239717        int rc = sqlite3Fts5PoslistWriterAppend(
239718            &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
239719        );
239720        if( rc==SQLITE_OK && pExpr->pConfig->bTokendata && !pT->bPrefix ){
239721          int iCol = p->iOff>>32;
239722          int iTokOff = p->iOff & 0x7FFFFFFF;
239723          rc = sqlite3Fts5IndexIterWriteTokendata(
239724              pT->pIter, pToken, nToken, iRowid, iCol, iTokOff
239725          );
239726        }
239727        if( rc ) return rc;
239728        break;
239729      }
239730    }
239731  }
239732  return SQLITE_OK;
239733}
239734
239735static int sqlite3Fts5ExprPopulatePoslists(
239736  Fts5Config *pConfig,
239737  Fts5Expr *pExpr,
239738  Fts5PoslistPopulator *aPopulator,
239739  int iCol,
239740  const char *z, int n
239741){
239742  int i;
239743  Fts5ExprCtx sCtx;
239744  sCtx.pExpr = pExpr;
239745  sCtx.aPopulator = aPopulator;
239746  sCtx.iOff = (((i64)iCol) << 32) - 1;
239747
239748  for(i=0; i<pExpr->nPhrase; i++){
239749    Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
239750    Fts5Colset *pColset = pNode->pNear->pColset;
239751    if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
239752     || aPopulator[i].bMiss
239753    ){
239754      aPopulator[i].bOk = 0;
239755    }else{
239756      aPopulator[i].bOk = 1;
239757    }
239758  }
239759
239760  return sqlite3Fts5Tokenize(pConfig,
239761      FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
239762  );
239763}
239764
239765static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
239766  if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
239767    pNode->pNear->apPhrase[0]->poslist.n = 0;
239768  }else{
239769    int i;
239770    for(i=0; i<pNode->nChild; i++){
239771      fts5ExprClearPoslists(pNode->apChild[i]);
239772    }
239773  }
239774}
239775
239776static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
239777  pNode->iRowid = iRowid;
239778  pNode->bEof = 0;
239779  switch( pNode->eType ){
239780    case FTS5_TERM:
239781    case FTS5_STRING:
239782      return (pNode->pNear->apPhrase[0]->poslist.n>0);
239783
239784    case FTS5_AND: {
239785      int i;
239786      for(i=0; i<pNode->nChild; i++){
239787        if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
239788          fts5ExprClearPoslists(pNode);
239789          return 0;
239790        }
239791      }
239792      break;
239793    }
239794
239795    case FTS5_OR: {
239796      int i;
239797      int bRet = 0;
239798      for(i=0; i<pNode->nChild; i++){
239799        if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
239800          bRet = 1;
239801        }
239802      }
239803      return bRet;
239804    }
239805
239806    default: {
239807      assert( pNode->eType==FTS5_NOT );
239808      if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
239809          || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
239810        ){
239811        fts5ExprClearPoslists(pNode);
239812        return 0;
239813      }
239814      break;
239815    }
239816  }
239817  return 1;
239818}
239819
239820static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
239821  fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
239822}
239823
239824/*
239825** This function is only called for detail=columns tables.
239826*/
239827static int sqlite3Fts5ExprPhraseCollist(
239828  Fts5Expr *pExpr,
239829  int iPhrase,
239830  const u8 **ppCollist,
239831  int *pnCollist
239832){
239833  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
239834  Fts5ExprNode *pNode = pPhrase->pNode;
239835  int rc = SQLITE_OK;
239836
239837  assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
239838  assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
239839
239840  if( pNode->bEof==0
239841   && pNode->iRowid==pExpr->pRoot->iRowid
239842   && pPhrase->poslist.n>0
239843  ){
239844    Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
239845    if( pTerm->pSynonym ){
239846      Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
239847      rc = fts5ExprSynonymList(
239848          pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
239849      );
239850    }else{
239851      *ppCollist = pPhrase->aTerm[0].pIter->pData;
239852      *pnCollist = pPhrase->aTerm[0].pIter->nData;
239853    }
239854  }else{
239855    *ppCollist = 0;
239856    *pnCollist = 0;
239857  }
239858
239859  return rc;
239860}
239861
239862/*
239863** Does the work of the fts5_api.xQueryToken() API method.
239864*/
239865static int sqlite3Fts5ExprQueryToken(
239866  Fts5Expr *pExpr,
239867  int iPhrase,
239868  int iToken,
239869  const char **ppOut,
239870  int *pnOut
239871){
239872  Fts5ExprPhrase *pPhrase = 0;
239873
239874  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ){
239875    return SQLITE_RANGE;
239876  }
239877  pPhrase = pExpr->apExprPhrase[iPhrase];
239878  if( iToken<0 || iToken>=pPhrase->nTerm ){
239879    return SQLITE_RANGE;
239880  }
239881
239882  *ppOut = pPhrase->aTerm[iToken].pTerm;
239883  *pnOut = pPhrase->aTerm[iToken].nFullTerm;
239884  return SQLITE_OK;
239885}
239886
239887/*
239888** Does the work of the fts5_api.xInstToken() API method.
239889*/
239890static int sqlite3Fts5ExprInstToken(
239891  Fts5Expr *pExpr,
239892  i64 iRowid,
239893  int iPhrase,
239894  int iCol,
239895  int iOff,
239896  int iToken,
239897  const char **ppOut,
239898  int *pnOut
239899){
239900  Fts5ExprPhrase *pPhrase = 0;
239901  Fts5ExprTerm *pTerm = 0;
239902  int rc = SQLITE_OK;
239903
239904  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ){
239905    return SQLITE_RANGE;
239906  }
239907  pPhrase = pExpr->apExprPhrase[iPhrase];
239908  if( iToken<0 || iToken>=pPhrase->nTerm ){
239909    return SQLITE_RANGE;
239910  }
239911  pTerm = &pPhrase->aTerm[iToken];
239912  if( pTerm->bPrefix==0 ){
239913    if( pExpr->pConfig->bTokendata ){
239914      rc = sqlite3Fts5IterToken(
239915          pTerm->pIter, iRowid, iCol, iOff+iToken, ppOut, pnOut
239916      );
239917    }else{
239918      *ppOut = pTerm->pTerm;
239919      *pnOut = pTerm->nFullTerm;
239920    }
239921  }
239922  return rc;
239923}
239924
239925/*
239926** Clear the token mappings for all Fts5IndexIter objects mannaged by
239927** the expression passed as the only argument.
239928*/
239929static void sqlite3Fts5ExprClearTokens(Fts5Expr *pExpr){
239930  int ii;
239931  for(ii=0; ii<pExpr->nPhrase; ii++){
239932    Fts5ExprTerm *pT;
239933    for(pT=&pExpr->apExprPhrase[ii]->aTerm[0]; pT; pT=pT->pSynonym){
239934      sqlite3Fts5IndexIterClearTokendata(pT->pIter);
239935    }
239936  }
239937}
239938
239939/*
239940** 2014 August 11
239941**
239942** The author disclaims copyright to this source code.  In place of
239943** a legal notice, here is a blessing:
239944**
239945**    May you do good and not evil.
239946**    May you find forgiveness for yourself and forgive others.
239947**    May you share freely, never taking more than you give.
239948**
239949******************************************************************************
239950**
239951*/
239952
239953
239954
239955/* #include "fts5Int.h" */
239956
239957typedef struct Fts5HashEntry Fts5HashEntry;
239958
239959/*
239960** This file contains the implementation of an in-memory hash table used
239961** to accumuluate "term -> doclist" content before it is flused to a level-0
239962** segment.
239963*/
239964
239965
239966struct Fts5Hash {
239967  int eDetail;                    /* Copy of Fts5Config.eDetail */
239968  int *pnByte;                    /* Pointer to bytes counter */
239969  int nEntry;                     /* Number of entries currently in hash */
239970  int nSlot;                      /* Size of aSlot[] array */
239971  Fts5HashEntry *pScan;           /* Current ordered scan item */
239972  Fts5HashEntry **aSlot;          /* Array of hash slots */
239973};
239974
239975/*
239976** Each entry in the hash table is represented by an object of the
239977** following type. Each object, its key, and its current data are stored
239978** in a single memory allocation. The key immediately follows the object
239979** in memory. The position list data immediately follows the key data
239980** in memory.
239981**
239982** The key is Fts5HashEntry.nKey bytes in size. It consists of a single
239983** byte identifying the index (either the main term index or a prefix-index),
239984** followed by the term data. For example: "0token". There is no
239985** nul-terminator - in this case nKey=6.
239986**
239987** The data that follows the key is in a similar, but not identical format
239988** to the doclist data stored in the database. It is:
239989**
239990**   * Rowid, as a varint
239991**   * Position list, without 0x00 terminator.
239992**   * Size of previous position list and rowid, as a 4 byte
239993**     big-endian integer.
239994**
239995** iRowidOff:
239996**   Offset of last rowid written to data area. Relative to first byte of
239997**   structure.
239998**
239999** nData:
240000**   Bytes of data written since iRowidOff.
240001*/
240002struct Fts5HashEntry {
240003  Fts5HashEntry *pHashNext;       /* Next hash entry with same hash-key */
240004  Fts5HashEntry *pScanNext;       /* Next entry in sorted order */
240005
240006  int nAlloc;                     /* Total size of allocation */
240007  int iSzPoslist;                 /* Offset of space for 4-byte poslist size */
240008  int nData;                      /* Total bytes of data (incl. structure) */
240009  int nKey;                       /* Length of key in bytes */
240010  u8 bDel;                        /* Set delete-flag @ iSzPoslist */
240011  u8 bContent;                    /* Set content-flag (detail=none mode) */
240012  i16 iCol;                       /* Column of last value written */
240013  int iPos;                       /* Position of last value written */
240014  i64 iRowid;                     /* Rowid of last value written */
240015};
240016
240017/*
240018** Eqivalent to:
240019**
240020**   char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
240021*/
240022#define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
240023
240024
240025/*
240026** Allocate a new hash table.
240027*/
240028static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
240029  int rc = SQLITE_OK;
240030  Fts5Hash *pNew;
240031
240032  *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
240033  if( pNew==0 ){
240034    rc = SQLITE_NOMEM;
240035  }else{
240036    sqlite3_int64 nByte;
240037    memset(pNew, 0, sizeof(Fts5Hash));
240038    pNew->pnByte = pnByte;
240039    pNew->eDetail = pConfig->eDetail;
240040
240041    pNew->nSlot = 1024;
240042    nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
240043    pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc64(nByte);
240044    if( pNew->aSlot==0 ){
240045      sqlite3_free(pNew);
240046      *ppNew = 0;
240047      rc = SQLITE_NOMEM;
240048    }else{
240049      memset(pNew->aSlot, 0, (size_t)nByte);
240050    }
240051  }
240052  return rc;
240053}
240054
240055/*
240056** Free a hash table object.
240057*/
240058static void sqlite3Fts5HashFree(Fts5Hash *pHash){
240059  if( pHash ){
240060    sqlite3Fts5HashClear(pHash);
240061    sqlite3_free(pHash->aSlot);
240062    sqlite3_free(pHash);
240063  }
240064}
240065
240066/*
240067** Empty (but do not delete) a hash table.
240068*/
240069static void sqlite3Fts5HashClear(Fts5Hash *pHash){
240070  int i;
240071  for(i=0; i<pHash->nSlot; i++){
240072    Fts5HashEntry *pNext;
240073    Fts5HashEntry *pSlot;
240074    for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
240075      pNext = pSlot->pHashNext;
240076      sqlite3_free(pSlot);
240077    }
240078  }
240079  memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
240080  pHash->nEntry = 0;
240081}
240082
240083static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
240084  int i;
240085  unsigned int h = 13;
240086  for(i=n-1; i>=0; i--){
240087    h = (h << 3) ^ h ^ p[i];
240088  }
240089  return (h % nSlot);
240090}
240091
240092static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
240093  int i;
240094  unsigned int h = 13;
240095  for(i=n-1; i>=0; i--){
240096    h = (h << 3) ^ h ^ p[i];
240097  }
240098  h = (h << 3) ^ h ^ b;
240099  return (h % nSlot);
240100}
240101
240102/*
240103** Resize the hash table by doubling the number of slots.
240104*/
240105static int fts5HashResize(Fts5Hash *pHash){
240106  int nNew = pHash->nSlot*2;
240107  int i;
240108  Fts5HashEntry **apNew;
240109  Fts5HashEntry **apOld = pHash->aSlot;
240110
240111  apNew = (Fts5HashEntry**)sqlite3_malloc64(nNew*sizeof(Fts5HashEntry*));
240112  if( !apNew ) return SQLITE_NOMEM;
240113  memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
240114
240115  for(i=0; i<pHash->nSlot; i++){
240116    while( apOld[i] ){
240117      unsigned int iHash;
240118      Fts5HashEntry *p = apOld[i];
240119      apOld[i] = p->pHashNext;
240120      iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p), p->nKey);
240121      p->pHashNext = apNew[iHash];
240122      apNew[iHash] = p;
240123    }
240124  }
240125
240126  sqlite3_free(apOld);
240127  pHash->nSlot = nNew;
240128  pHash->aSlot = apNew;
240129  return SQLITE_OK;
240130}
240131
240132static int fts5HashAddPoslistSize(
240133  Fts5Hash *pHash,
240134  Fts5HashEntry *p,
240135  Fts5HashEntry *p2
240136){
240137  int nRet = 0;
240138  if( p->iSzPoslist ){
240139    u8 *pPtr = p2 ? (u8*)p2 : (u8*)p;
240140    int nData = p->nData;
240141    if( pHash->eDetail==FTS5_DETAIL_NONE ){
240142      assert( nData==p->iSzPoslist );
240143      if( p->bDel ){
240144        pPtr[nData++] = 0x00;
240145        if( p->bContent ){
240146          pPtr[nData++] = 0x00;
240147        }
240148      }
240149    }else{
240150      int nSz = (nData - p->iSzPoslist - 1);       /* Size in bytes */
240151      int nPos = nSz*2 + p->bDel;                     /* Value of nPos field */
240152
240153      assert( p->bDel==0 || p->bDel==1 );
240154      if( nPos<=127 ){
240155        pPtr[p->iSzPoslist] = (u8)nPos;
240156      }else{
240157        int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
240158        memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
240159        sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
240160        nData += (nByte-1);
240161      }
240162    }
240163
240164    nRet = nData - p->nData;
240165    if( p2==0 ){
240166      p->iSzPoslist = 0;
240167      p->bDel = 0;
240168      p->bContent = 0;
240169      p->nData = nData;
240170    }
240171  }
240172  return nRet;
240173}
240174
240175/*
240176** Add an entry to the in-memory hash table. The key is the concatenation
240177** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
240178**
240179**     (bByte || pToken) -> (iRowid,iCol,iPos)
240180**
240181** Or, if iCol is negative, then the value is a delete marker.
240182*/
240183static int sqlite3Fts5HashWrite(
240184  Fts5Hash *pHash,
240185  i64 iRowid,                     /* Rowid for this entry */
240186  int iCol,                       /* Column token appears in (-ve -> delete) */
240187  int iPos,                       /* Position of token within column */
240188  char bByte,                     /* First byte of token */
240189  const char *pToken, int nToken  /* Token to add or remove to or from index */
240190){
240191  unsigned int iHash;
240192  Fts5HashEntry *p;
240193  u8 *pPtr;
240194  int nIncr = 0;                  /* Amount to increment (*pHash->pnByte) by */
240195  int bNew;                       /* If non-delete entry should be written */
240196
240197  bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
240198
240199  /* Attempt to locate an existing hash entry */
240200  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
240201  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
240202    char *zKey = fts5EntryKey(p);
240203    if( zKey[0]==bByte
240204     && p->nKey==nToken+1
240205     && memcmp(&zKey[1], pToken, nToken)==0
240206    ){
240207      break;
240208    }
240209  }
240210
240211  /* If an existing hash entry cannot be found, create a new one. */
240212  if( p==0 ){
240213    /* Figure out how much space to allocate */
240214    char *zKey;
240215    sqlite3_int64 nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
240216    if( nByte<128 ) nByte = 128;
240217
240218    /* Grow the Fts5Hash.aSlot[] array if necessary. */
240219    if( (pHash->nEntry*2)>=pHash->nSlot ){
240220      int rc = fts5HashResize(pHash);
240221      if( rc!=SQLITE_OK ) return rc;
240222      iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
240223    }
240224
240225    /* Allocate new Fts5HashEntry and add it to the hash table. */
240226    p = (Fts5HashEntry*)sqlite3_malloc64(nByte);
240227    if( !p ) return SQLITE_NOMEM;
240228    memset(p, 0, sizeof(Fts5HashEntry));
240229    p->nAlloc = (int)nByte;
240230    zKey = fts5EntryKey(p);
240231    zKey[0] = bByte;
240232    memcpy(&zKey[1], pToken, nToken);
240233    assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
240234    p->nKey = nToken+1;
240235    zKey[nToken+1] = '\0';
240236    p->nData = nToken+1 + sizeof(Fts5HashEntry);
240237    p->pHashNext = pHash->aSlot[iHash];
240238    pHash->aSlot[iHash] = p;
240239    pHash->nEntry++;
240240
240241    /* Add the first rowid field to the hash-entry */
240242    p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
240243    p->iRowid = iRowid;
240244
240245    p->iSzPoslist = p->nData;
240246    if( pHash->eDetail!=FTS5_DETAIL_NONE ){
240247      p->nData += 1;
240248      p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
240249    }
240250
240251  }else{
240252
240253    /* Appending to an existing hash-entry. Check that there is enough
240254    ** space to append the largest possible new entry. Worst case scenario
240255    ** is:
240256    **
240257    **     + 9 bytes for a new rowid,
240258    **     + 4 byte reserved for the "poslist size" varint.
240259    **     + 1 byte for a "new column" byte,
240260    **     + 3 bytes for a new column number (16-bit max) as a varint,
240261    **     + 5 bytes for the new position offset (32-bit max).
240262    */
240263    if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
240264      sqlite3_int64 nNew = p->nAlloc * 2;
240265      Fts5HashEntry *pNew;
240266      Fts5HashEntry **pp;
240267      pNew = (Fts5HashEntry*)sqlite3_realloc64(p, nNew);
240268      if( pNew==0 ) return SQLITE_NOMEM;
240269      pNew->nAlloc = (int)nNew;
240270      for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
240271      *pp = pNew;
240272      p = pNew;
240273    }
240274    nIncr -= p->nData;
240275  }
240276  assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
240277
240278  pPtr = (u8*)p;
240279
240280  /* If this is a new rowid, append the 4-byte size field for the previous
240281  ** entry, and the new rowid for this entry.  */
240282  if( iRowid!=p->iRowid ){
240283    u64 iDiff = (u64)iRowid - (u64)p->iRowid;
240284    fts5HashAddPoslistSize(pHash, p, 0);
240285    p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iDiff);
240286    p->iRowid = iRowid;
240287    bNew = 1;
240288    p->iSzPoslist = p->nData;
240289    if( pHash->eDetail!=FTS5_DETAIL_NONE ){
240290      p->nData += 1;
240291      p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
240292      p->iPos = 0;
240293    }
240294  }
240295
240296  if( iCol>=0 ){
240297    if( pHash->eDetail==FTS5_DETAIL_NONE ){
240298      p->bContent = 1;
240299    }else{
240300      /* Append a new column value, if necessary */
240301      assert_nc( iCol>=p->iCol );
240302      if( iCol!=p->iCol ){
240303        if( pHash->eDetail==FTS5_DETAIL_FULL ){
240304          pPtr[p->nData++] = 0x01;
240305          p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
240306          p->iCol = (i16)iCol;
240307          p->iPos = 0;
240308        }else{
240309          bNew = 1;
240310          p->iCol = (i16)(iPos = iCol);
240311        }
240312      }
240313
240314      /* Append the new position offset, if necessary */
240315      if( bNew ){
240316        p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
240317        p->iPos = iPos;
240318      }
240319    }
240320  }else{
240321    /* This is a delete. Set the delete flag. */
240322    p->bDel = 1;
240323  }
240324
240325  nIncr += p->nData;
240326  *pHash->pnByte += nIncr;
240327  return SQLITE_OK;
240328}
240329
240330
240331/*
240332** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
240333** each sorted in key order. This function merges the two lists into a
240334** single list and returns a pointer to its first element.
240335*/
240336static Fts5HashEntry *fts5HashEntryMerge(
240337  Fts5HashEntry *pLeft,
240338  Fts5HashEntry *pRight
240339){
240340  Fts5HashEntry *p1 = pLeft;
240341  Fts5HashEntry *p2 = pRight;
240342  Fts5HashEntry *pRet = 0;
240343  Fts5HashEntry **ppOut = &pRet;
240344
240345  while( p1 || p2 ){
240346    if( p1==0 ){
240347      *ppOut = p2;
240348      p2 = 0;
240349    }else if( p2==0 ){
240350      *ppOut = p1;
240351      p1 = 0;
240352    }else{
240353      char *zKey1 = fts5EntryKey(p1);
240354      char *zKey2 = fts5EntryKey(p2);
240355      int nMin = MIN(p1->nKey, p2->nKey);
240356
240357      int cmp = memcmp(zKey1, zKey2, nMin);
240358      if( cmp==0 ){
240359        cmp = p1->nKey - p2->nKey;
240360      }
240361      assert( cmp!=0 );
240362
240363      if( cmp>0 ){
240364        /* p2 is smaller */
240365        *ppOut = p2;
240366        ppOut = &p2->pScanNext;
240367        p2 = p2->pScanNext;
240368      }else{
240369        /* p1 is smaller */
240370        *ppOut = p1;
240371        ppOut = &p1->pScanNext;
240372        p1 = p1->pScanNext;
240373      }
240374      *ppOut = 0;
240375    }
240376  }
240377
240378  return pRet;
240379}
240380
240381/*
240382** Link all tokens from hash table iHash into a list in sorted order. The
240383** tokens are not removed from the hash table.
240384*/
240385static int fts5HashEntrySort(
240386  Fts5Hash *pHash,
240387  const char *pTerm, int nTerm,   /* Query prefix, if any */
240388  Fts5HashEntry **ppSorted
240389){
240390  const int nMergeSlot = 32;
240391  Fts5HashEntry **ap;
240392  Fts5HashEntry *pList;
240393  int iSlot;
240394  int i;
240395
240396  *ppSorted = 0;
240397  ap = sqlite3_malloc64(sizeof(Fts5HashEntry*) * nMergeSlot);
240398  if( !ap ) return SQLITE_NOMEM;
240399  memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
240400
240401  for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
240402    Fts5HashEntry *pIter;
240403    for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
240404      if( pTerm==0
240405       || (pIter->nKey>=nTerm && 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm))
240406      ){
240407        Fts5HashEntry *pEntry = pIter;
240408        pEntry->pScanNext = 0;
240409        for(i=0; ap[i]; i++){
240410          pEntry = fts5HashEntryMerge(pEntry, ap[i]);
240411          ap[i] = 0;
240412        }
240413        ap[i] = pEntry;
240414      }
240415    }
240416  }
240417
240418  pList = 0;
240419  for(i=0; i<nMergeSlot; i++){
240420    pList = fts5HashEntryMerge(pList, ap[i]);
240421  }
240422
240423  sqlite3_free(ap);
240424  *ppSorted = pList;
240425  return SQLITE_OK;
240426}
240427
240428/*
240429** Query the hash table for a doclist associated with term pTerm/nTerm.
240430*/
240431static int sqlite3Fts5HashQuery(
240432  Fts5Hash *pHash,                /* Hash table to query */
240433  int nPre,
240434  const char *pTerm, int nTerm,   /* Query term */
240435  void **ppOut,                   /* OUT: Pointer to new object */
240436  int *pnDoclist                  /* OUT: Size of doclist in bytes */
240437){
240438  unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
240439  char *zKey = 0;
240440  Fts5HashEntry *p;
240441
240442  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
240443    zKey = fts5EntryKey(p);
240444    if( nTerm==p->nKey && memcmp(zKey, pTerm, nTerm)==0 ) break;
240445  }
240446
240447  if( p ){
240448    int nHashPre = sizeof(Fts5HashEntry) + nTerm;
240449    int nList = p->nData - nHashPre;
240450    u8 *pRet = (u8*)(*ppOut = sqlite3_malloc64(nPre + nList + 10));
240451    if( pRet ){
240452      Fts5HashEntry *pFaux = (Fts5HashEntry*)&pRet[nPre-nHashPre];
240453      memcpy(&pRet[nPre], &((u8*)p)[nHashPre], nList);
240454      nList += fts5HashAddPoslistSize(pHash, p, pFaux);
240455      *pnDoclist = nList;
240456    }else{
240457      *pnDoclist = 0;
240458      return SQLITE_NOMEM;
240459    }
240460  }else{
240461    *ppOut = 0;
240462    *pnDoclist = 0;
240463  }
240464
240465  return SQLITE_OK;
240466}
240467
240468static int sqlite3Fts5HashScanInit(
240469  Fts5Hash *p,                    /* Hash table to query */
240470  const char *pTerm, int nTerm    /* Query prefix */
240471){
240472  return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
240473}
240474
240475#ifdef SQLITE_DEBUG
240476static int fts5HashCount(Fts5Hash *pHash){
240477  int nEntry = 0;
240478  int ii;
240479  for(ii=0; ii<pHash->nSlot; ii++){
240480    Fts5HashEntry *p = 0;
240481    for(p=pHash->aSlot[ii]; p; p=p->pHashNext){
240482      nEntry++;
240483    }
240484  }
240485  return nEntry;
240486}
240487#endif
240488
240489/*
240490** Return true if the hash table is empty, false otherwise.
240491*/
240492static int sqlite3Fts5HashIsEmpty(Fts5Hash *pHash){
240493  assert( pHash->nEntry==fts5HashCount(pHash) );
240494  return pHash->nEntry==0;
240495}
240496
240497static void sqlite3Fts5HashScanNext(Fts5Hash *p){
240498  assert( !sqlite3Fts5HashScanEof(p) );
240499  p->pScan = p->pScan->pScanNext;
240500}
240501
240502static int sqlite3Fts5HashScanEof(Fts5Hash *p){
240503  return (p->pScan==0);
240504}
240505
240506static void sqlite3Fts5HashScanEntry(
240507  Fts5Hash *pHash,
240508  const char **pzTerm,            /* OUT: term (nul-terminated) */
240509  int *pnTerm,                    /* OUT: Size of term in bytes */
240510  const u8 **ppDoclist,           /* OUT: pointer to doclist */
240511  int *pnDoclist                  /* OUT: size of doclist in bytes */
240512){
240513  Fts5HashEntry *p;
240514  if( (p = pHash->pScan) ){
240515    char *zKey = fts5EntryKey(p);
240516    int nTerm = p->nKey;
240517    fts5HashAddPoslistSize(pHash, p, 0);
240518    *pzTerm = zKey;
240519    *pnTerm = nTerm;
240520    *ppDoclist = (const u8*)&zKey[nTerm];
240521    *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm);
240522  }else{
240523    *pzTerm = 0;
240524    *pnTerm = 0;
240525    *ppDoclist = 0;
240526    *pnDoclist = 0;
240527  }
240528}
240529
240530/*
240531** 2014 May 31
240532**
240533** The author disclaims copyright to this source code.  In place of
240534** a legal notice, here is a blessing:
240535**
240536**    May you do good and not evil.
240537**    May you find forgiveness for yourself and forgive others.
240538**    May you share freely, never taking more than you give.
240539**
240540******************************************************************************
240541**
240542** Low level access to the FTS index stored in the database file. The
240543** routines in this file file implement all read and write access to the
240544** %_data table. Other parts of the system access this functionality via
240545** the interface defined in fts5Int.h.
240546*/
240547
240548
240549/* #include "fts5Int.h" */
240550
240551/*
240552** Overview:
240553**
240554** The %_data table contains all the FTS indexes for an FTS5 virtual table.
240555** As well as the main term index, there may be up to 31 prefix indexes.
240556** The format is similar to FTS3/4, except that:
240557**
240558**   * all segment b-tree leaf data is stored in fixed size page records
240559**     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
240560**     taken to ensure it is possible to iterate in either direction through
240561**     the entries in a doclist, or to seek to a specific entry within a
240562**     doclist, without loading it into memory.
240563**
240564**   * large doclists that span many pages have associated "doclist index"
240565**     records that contain a copy of the first rowid on each page spanned by
240566**     the doclist. This is used to speed up seek operations, and merges of
240567**     large doclists with very small doclists.
240568**
240569**   * extra fields in the "structure record" record the state of ongoing
240570**     incremental merge operations.
240571**
240572*/
240573
240574
240575#define FTS5_OPT_WORK_UNIT  1000  /* Number of leaf pages per optimize step */
240576#define FTS5_WORK_UNIT      64    /* Number of leaf pages in unit of work */
240577
240578#define FTS5_MIN_DLIDX_SIZE 4     /* Add dlidx if this many empty pages */
240579
240580#define FTS5_MAIN_PREFIX '0'
240581
240582#if FTS5_MAX_PREFIX_INDEXES > 31
240583# error "FTS5_MAX_PREFIX_INDEXES is too large"
240584#endif
240585
240586#define FTS5_MAX_LEVEL 64
240587
240588/*
240589** There are two versions of the format used for the structure record:
240590**
240591**   1. the legacy format, that may be read by all fts5 versions, and
240592**
240593**   2. the V2 format, which is used by contentless_delete=1 databases.
240594**
240595** Both begin with a 4-byte "configuration cookie" value. Then, a legacy
240596** format structure record contains a varint - the number of levels in
240597** the structure. Whereas a V2 structure record contains the constant
240598** 4 bytes [0xff 0x00 0x00 0x01]. This is unambiguous as the value of a
240599** varint has to be at least 16256 to begin with "0xFF". And the default
240600** maximum number of levels is 64.
240601**
240602** See below for more on structure record formats.
240603*/
240604#define FTS5_STRUCTURE_V2 "\xFF\x00\x00\x01"
240605
240606/*
240607** Details:
240608**
240609** The %_data table managed by this module,
240610**
240611**     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
240612**
240613** , contains the following 6 types of records. See the comments surrounding
240614** the FTS5_*_ROWID macros below for a description of how %_data rowids are
240615** assigned to each fo them.
240616**
240617** 1. Structure Records:
240618**
240619**   The set of segments that make up an index - the index structure - are
240620**   recorded in a single record within the %_data table. The record consists
240621**   of a single 32-bit configuration cookie value followed by a list of
240622**   SQLite varints.
240623**
240624**   If the structure record is a V2 record, the configuration cookie is
240625**   followed by the following 4 bytes: [0xFF 0x00 0x00 0x01].
240626**
240627**   Next, the record continues with three varints:
240628**
240629**     + number of levels,
240630**     + total number of segments on all levels,
240631**     + value of write counter.
240632**
240633**   Then, for each level from 0 to nMax:
240634**
240635**     + number of input segments in ongoing merge.
240636**     + total number of segments in level.
240637**     + for each segment from oldest to newest:
240638**         + segment id (always > 0)
240639**         + first leaf page number (often 1, always greater than 0)
240640**         + final leaf page number
240641**
240642**      Then, for V2 structures only:
240643**
240644**         + lower origin counter value,
240645**         + upper origin counter value,
240646**         + the number of tombstone hash pages.
240647**
240648** 2. The Averages Record:
240649**
240650**   A single record within the %_data table. The data is a list of varints.
240651**   The first value is the number of rows in the index. Then, for each column
240652**   from left to right, the total number of tokens in the column for all
240653**   rows of the table.
240654**
240655** 3. Segment leaves:
240656**
240657**   TERM/DOCLIST FORMAT:
240658**
240659**     Most of each segment leaf is taken up by term/doclist data. The
240660**     general format of term/doclist, starting with the first term
240661**     on the leaf page, is:
240662**
240663**         varint : size of first term
240664**         blob:    first term data
240665**         doclist: first doclist
240666**         zero-or-more {
240667**           varint:  number of bytes in common with previous term
240668**           varint:  number of bytes of new term data (nNew)
240669**           blob:    nNew bytes of new term data
240670**           doclist: next doclist
240671**         }
240672**
240673**     doclist format:
240674**
240675**         varint:  first rowid
240676**         poslist: first poslist
240677**         zero-or-more {
240678**           varint:  rowid delta (always > 0)
240679**           poslist: next poslist
240680**         }
240681**
240682**     poslist format:
240683**
240684**         varint: size of poslist in bytes multiplied by 2, not including
240685**                 this field. Plus 1 if this entry carries the "delete" flag.
240686**         collist: collist for column 0
240687**         zero-or-more {
240688**           0x01 byte
240689**           varint: column number (I)
240690**           collist: collist for column I
240691**         }
240692**
240693**     collist format:
240694**
240695**         varint: first offset + 2
240696**         zero-or-more {
240697**           varint: offset delta + 2
240698**         }
240699**
240700**   PAGE FORMAT
240701**
240702**     Each leaf page begins with a 4-byte header containing 2 16-bit
240703**     unsigned integer fields in big-endian format. They are:
240704**
240705**       * The byte offset of the first rowid on the page, if it exists
240706**         and occurs before the first term (otherwise 0).
240707**
240708**       * The byte offset of the start of the page footer. If the page
240709**         footer is 0 bytes in size, then this field is the same as the
240710**         size of the leaf page in bytes.
240711**
240712**     The page footer consists of a single varint for each term located
240713**     on the page. Each varint is the byte offset of the current term
240714**     within the page, delta-compressed against the previous value. In
240715**     other words, the first varint in the footer is the byte offset of
240716**     the first term, the second is the byte offset of the second less that
240717**     of the first, and so on.
240718**
240719**     The term/doclist format described above is accurate if the entire
240720**     term/doclist data fits on a single leaf page. If this is not the case,
240721**     the format is changed in two ways:
240722**
240723**       + if the first rowid on a page occurs before the first term, it
240724**         is stored as a literal value:
240725**
240726**             varint:  first rowid
240727**
240728**       + the first term on each page is stored in the same way as the
240729**         very first term of the segment:
240730**
240731**             varint : size of first term
240732**             blob:    first term data
240733**
240734** 5. Segment doclist indexes:
240735**
240736**   Doclist indexes are themselves b-trees, however they usually consist of
240737**   a single leaf record only. The format of each doclist index leaf page
240738**   is:
240739**
240740**     * Flags byte. Bits are:
240741**         0x01: Clear if leaf is also the root page, otherwise set.
240742**
240743**     * Page number of fts index leaf page. As a varint.
240744**
240745**     * First rowid on page indicated by previous field. As a varint.
240746**
240747**     * A list of varints, one for each subsequent termless page. A
240748**       positive delta if the termless page contains at least one rowid,
240749**       or an 0x00 byte otherwise.
240750**
240751**   Internal doclist index nodes are:
240752**
240753**     * Flags byte. Bits are:
240754**         0x01: Clear for root page, otherwise set.
240755**
240756**     * Page number of first child page. As a varint.
240757**
240758**     * Copy of first rowid on page indicated by previous field. As a varint.
240759**
240760**     * A list of delta-encoded varints - the first rowid on each subsequent
240761**       child page.
240762**
240763** 6. Tombstone Hash Page
240764**
240765**   These records are only ever present in contentless_delete=1 tables.
240766**   There are zero or more of these associated with each segment. They
240767**   are used to store the tombstone rowids for rows contained in the
240768**   associated segments.
240769**
240770**   The set of nHashPg tombstone hash pages associated with a single
240771**   segment together form a single hash table containing tombstone rowids.
240772**   To find the page of the hash on which a key might be stored:
240773**
240774**       iPg = (rowid % nHashPg)
240775**
240776**   Then, within page iPg, which has nSlot slots:
240777**
240778**       iSlot = (rowid / nHashPg) % nSlot
240779**
240780**   Each tombstone hash page begins with an 8 byte header:
240781**
240782**     1-byte:  Key-size (the size in bytes of each slot). Either 4 or 8.
240783**     1-byte:  rowid-0-tombstone flag. This flag is only valid on the
240784**              first tombstone hash page for each segment (iPg=0). If set,
240785**              the hash table contains rowid 0. If clear, it does not.
240786**              Rowid 0 is handled specially.
240787**     2-bytes: unused.
240788**     4-bytes: Big-endian integer containing number of entries on page.
240789**
240790**   Following this are nSlot 4 or 8 byte slots (depending on the key-size
240791**   in the first byte of the page header). The number of slots may be
240792**   determined based on the size of the page record and the key-size:
240793**
240794**     nSlot = (nByte - 8) / key-size
240795*/
240796
240797/*
240798** Rowids for the averages and structure records in the %_data table.
240799*/
240800#define FTS5_AVERAGES_ROWID     1    /* Rowid used for the averages record */
240801#define FTS5_STRUCTURE_ROWID   10    /* The structure record */
240802
240803/*
240804** Macros determining the rowids used by segment leaves and dlidx leaves
240805** and nodes. All nodes and leaves are stored in the %_data table with large
240806** positive rowids.
240807**
240808** Each segment has a unique non-zero 16-bit id.
240809**
240810** The rowid for each segment leaf is found by passing the segment id and
240811** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
240812** sequentially starting from 1.
240813*/
240814#define FTS5_DATA_ID_B     16     /* Max seg id number 65535 */
240815#define FTS5_DATA_DLI_B     1     /* Doclist-index flag (1 bit) */
240816#define FTS5_DATA_HEIGHT_B  5     /* Max dlidx tree height of 32 */
240817#define FTS5_DATA_PAGE_B   31     /* Max page number of 2147483648 */
240818
240819#define fts5_dri(segid, dlidx, height, pgno) (                                 \
240820 ((i64)(segid)  << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) +    \
240821 ((i64)(dlidx)  << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) +                  \
240822 ((i64)(height) << (FTS5_DATA_PAGE_B)) +                                       \
240823 ((i64)(pgno))                                                                 \
240824)
240825
240826#define FTS5_SEGMENT_ROWID(segid, pgno)       fts5_dri(segid, 0, 0, pgno)
240827#define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
240828#define FTS5_TOMBSTONE_ROWID(segid,ipg)       fts5_dri(segid+(1<<16), 0, 0, ipg)
240829
240830#ifdef SQLITE_DEBUG
240831static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
240832#endif
240833
240834
240835/*
240836** Each time a blob is read from the %_data table, it is padded with this
240837** many zero bytes. This makes it easier to decode the various record formats
240838** without overreading if the records are corrupt.
240839*/
240840#define FTS5_DATA_ZERO_PADDING 8
240841#define FTS5_DATA_PADDING 20
240842
240843typedef struct Fts5Data Fts5Data;
240844typedef struct Fts5DlidxIter Fts5DlidxIter;
240845typedef struct Fts5DlidxLvl Fts5DlidxLvl;
240846typedef struct Fts5DlidxWriter Fts5DlidxWriter;
240847typedef struct Fts5Iter Fts5Iter;
240848typedef struct Fts5PageWriter Fts5PageWriter;
240849typedef struct Fts5SegIter Fts5SegIter;
240850typedef struct Fts5DoclistIter Fts5DoclistIter;
240851typedef struct Fts5SegWriter Fts5SegWriter;
240852typedef struct Fts5Structure Fts5Structure;
240853typedef struct Fts5StructureLevel Fts5StructureLevel;
240854typedef struct Fts5StructureSegment Fts5StructureSegment;
240855typedef struct Fts5TokenDataIter Fts5TokenDataIter;
240856typedef struct Fts5TokenDataMap Fts5TokenDataMap;
240857typedef struct Fts5TombstoneArray Fts5TombstoneArray;
240858
240859struct Fts5Data {
240860  u8 *p;                          /* Pointer to buffer containing record */
240861  int nn;                         /* Size of record in bytes */
240862  int szLeaf;                     /* Size of leaf without page-index */
240863};
240864
240865/*
240866** One object per %_data table.
240867**
240868** nContentlessDelete:
240869**   The number of contentless delete operations since the most recent
240870**   call to fts5IndexFlush() or fts5IndexDiscardData(). This is tracked
240871**   so that extra auto-merge work can be done by fts5IndexFlush() to
240872**   account for the delete operations.
240873*/
240874struct Fts5Index {
240875  Fts5Config *pConfig;            /* Virtual table configuration */
240876  char *zDataTbl;                 /* Name of %_data table */
240877  int nWorkUnit;                  /* Leaf pages in a "unit" of work */
240878
240879  /*
240880  ** Variables related to the accumulation of tokens and doclists within the
240881  ** in-memory hash tables before they are flushed to disk.
240882  */
240883  Fts5Hash *pHash;                /* Hash table for in-memory data */
240884  int nPendingData;               /* Current bytes of pending data */
240885  i64 iWriteRowid;                /* Rowid for current doc being written */
240886  int bDelete;                    /* Current write is a delete */
240887  int nContentlessDelete;         /* Number of contentless delete ops */
240888  int nPendingRow;                /* Number of INSERT in hash table */
240889
240890  /* Error state. */
240891  int rc;                         /* Current error code */
240892  int flushRc;
240893
240894  /* State used by the fts5DataXXX() functions. */
240895  sqlite3_blob *pReader;          /* RO incr-blob open on %_data table */
240896  sqlite3_stmt *pWriter;          /* "INSERT ... %_data VALUES(?,?)" */
240897  sqlite3_stmt *pDeleter;         /* "DELETE FROM %_data ... id>=? AND id<=?" */
240898  sqlite3_stmt *pIdxWriter;       /* "INSERT ... %_idx VALUES(?,?,?,?)" */
240899  sqlite3_stmt *pIdxDeleter;      /* "DELETE FROM %_idx WHERE segid=?" */
240900  sqlite3_stmt *pIdxSelect;
240901  sqlite3_stmt *pIdxNextSelect;
240902  int nRead;                      /* Total number of blocks read */
240903
240904  sqlite3_stmt *pDeleteFromIdx;
240905
240906  sqlite3_stmt *pDataVersion;
240907  i64 iStructVersion;             /* data_version when pStruct read */
240908  Fts5Structure *pStruct;         /* Current db structure (or NULL) */
240909};
240910
240911struct Fts5DoclistIter {
240912  u8 *aEof;                       /* Pointer to 1 byte past end of doclist */
240913
240914  /* Output variables. aPoslist==0 at EOF */
240915  i64 iRowid;
240916  u8 *aPoslist;
240917  int nPoslist;
240918  int nSize;
240919};
240920
240921/*
240922** The contents of the "structure" record for each index are represented
240923** using an Fts5Structure record in memory. Which uses instances of the
240924** other Fts5StructureXXX types as components.
240925**
240926** nOriginCntr:
240927**   This value is set to non-zero for structure records created for
240928**   contentlessdelete=1 tables only. In that case it represents the
240929**   origin value to apply to the next top-level segment created.
240930*/
240931struct Fts5StructureSegment {
240932  int iSegid;                     /* Segment id */
240933  int pgnoFirst;                  /* First leaf page number in segment */
240934  int pgnoLast;                   /* Last leaf page number in segment */
240935
240936  /* contentlessdelete=1 tables only: */
240937  u64 iOrigin1;
240938  u64 iOrigin2;
240939  int nPgTombstone;               /* Number of tombstone hash table pages */
240940  u64 nEntryTombstone;            /* Number of tombstone entries that "count" */
240941  u64 nEntry;                     /* Number of rows in this segment */
240942};
240943struct Fts5StructureLevel {
240944  int nMerge;                     /* Number of segments in incr-merge */
240945  int nSeg;                       /* Total number of segments on level */
240946  Fts5StructureSegment *aSeg;     /* Array of segments. aSeg[0] is oldest. */
240947};
240948struct Fts5Structure {
240949  int nRef;                       /* Object reference count */
240950  u64 nWriteCounter;              /* Total leaves written to level 0 */
240951  u64 nOriginCntr;                /* Origin value for next top-level segment */
240952  int nSegment;                   /* Total segments in this structure */
240953  int nLevel;                     /* Number of levels in this index */
240954  Fts5StructureLevel aLevel[1];   /* Array of nLevel level objects */
240955};
240956
240957/*
240958** An object of type Fts5SegWriter is used to write to segments.
240959*/
240960struct Fts5PageWriter {
240961  int pgno;                       /* Page number for this page */
240962  int iPrevPgidx;                 /* Previous value written into pgidx */
240963  Fts5Buffer buf;                 /* Buffer containing leaf data */
240964  Fts5Buffer pgidx;               /* Buffer containing page-index */
240965  Fts5Buffer term;                /* Buffer containing previous term on page */
240966};
240967struct Fts5DlidxWriter {
240968  int pgno;                       /* Page number for this page */
240969  int bPrevValid;                 /* True if iPrev is valid */
240970  i64 iPrev;                      /* Previous rowid value written to page */
240971  Fts5Buffer buf;                 /* Buffer containing page data */
240972};
240973struct Fts5SegWriter {
240974  int iSegid;                     /* Segid to write to */
240975  Fts5PageWriter writer;          /* PageWriter object */
240976  i64 iPrevRowid;                 /* Previous rowid written to current leaf */
240977  u8 bFirstRowidInDoclist;        /* True if next rowid is first in doclist */
240978  u8 bFirstRowidInPage;           /* True if next rowid is first in page */
240979  /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
240980  u8 bFirstTermInPage;            /* True if next term will be first in leaf */
240981  int nLeafWritten;               /* Number of leaf pages written */
240982  int nEmpty;                     /* Number of contiguous term-less nodes */
240983
240984  int nDlidx;                     /* Allocated size of aDlidx[] array */
240985  Fts5DlidxWriter *aDlidx;        /* Array of Fts5DlidxWriter objects */
240986
240987  /* Values to insert into the %_idx table */
240988  Fts5Buffer btterm;              /* Next term to insert into %_idx table */
240989  int iBtPage;                    /* Page number corresponding to btterm */
240990};
240991
240992typedef struct Fts5CResult Fts5CResult;
240993struct Fts5CResult {
240994  u16 iFirst;                     /* aSeg[] index of firstest iterator */
240995  u8 bTermEq;                     /* True if the terms are equal */
240996};
240997
240998/*
240999** Object for iterating through a single segment, visiting each term/rowid
241000** pair in the segment.
241001**
241002** pSeg:
241003**   The segment to iterate through.
241004**
241005** iLeafPgno:
241006**   Current leaf page number within segment.
241007**
241008** iLeafOffset:
241009**   Byte offset within the current leaf that is the first byte of the
241010**   position list data (one byte passed the position-list size field).
241011**
241012** pLeaf:
241013**   Buffer containing current leaf page data. Set to NULL at EOF.
241014**
241015** iTermLeafPgno, iTermLeafOffset:
241016**   Leaf page number containing the last term read from the segment. And
241017**   the offset immediately following the term data.
241018**
241019** flags:
241020**   Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
241021**
241022**   FTS5_SEGITER_ONETERM:
241023**     If set, set the iterator to point to EOF after the current doclist
241024**     has been exhausted. Do not proceed to the next term in the segment.
241025**
241026**   FTS5_SEGITER_REVERSE:
241027**     This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
241028**     it is set, iterate through rowid in descending order instead of the
241029**     default ascending order.
241030**
241031** iRowidOffset/nRowidOffset/aRowidOffset:
241032**     These are used if the FTS5_SEGITER_REVERSE flag is set.
241033**
241034**     For each rowid on the page corresponding to the current term, the
241035**     corresponding aRowidOffset[] entry is set to the byte offset of the
241036**     start of the "position-list-size" field within the page.
241037**
241038** iTermIdx:
241039**     Index of current term on iTermLeafPgno.
241040**
241041** apTombstone/nTombstone:
241042**     These are used for contentless_delete=1 tables only. When the cursor
241043**     is first allocated, the apTombstone[] array is allocated so that it
241044**     is large enough for all tombstones hash pages associated with the
241045**     segment. The pages themselves are loaded lazily from the database as
241046**     they are required.
241047*/
241048struct Fts5SegIter {
241049  Fts5StructureSegment *pSeg;     /* Segment to iterate through */
241050  int flags;                      /* Mask of configuration flags */
241051  int iLeafPgno;                  /* Current leaf page number */
241052  Fts5Data *pLeaf;                /* Current leaf data */
241053  Fts5Data *pNextLeaf;            /* Leaf page (iLeafPgno+1) */
241054  i64 iLeafOffset;                /* Byte offset within current leaf */
241055  Fts5TombstoneArray *pTombArray; /* Array of tombstone pages */
241056
241057  /* Next method */
241058  void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
241059
241060  /* The page and offset from which the current term was read. The offset
241061  ** is the offset of the first rowid in the current doclist.  */
241062  int iTermLeafPgno;
241063  int iTermLeafOffset;
241064
241065  int iPgidxOff;                  /* Next offset in pgidx */
241066  int iEndofDoclist;
241067
241068  /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
241069  int iRowidOffset;               /* Current entry in aRowidOffset[] */
241070  int nRowidOffset;               /* Allocated size of aRowidOffset[] array */
241071  int *aRowidOffset;              /* Array of offset to rowid fields */
241072
241073  Fts5DlidxIter *pDlidx;          /* If there is a doclist-index */
241074
241075  /* Variables populated based on current entry. */
241076  Fts5Buffer term;                /* Current term */
241077  i64 iRowid;                     /* Current rowid */
241078  int nPos;                       /* Number of bytes in current position list */
241079  u8 bDel;                        /* True if the delete flag is set */
241080};
241081
241082/*
241083** Array of tombstone pages. Reference counted.
241084*/
241085struct Fts5TombstoneArray {
241086  int nRef;                       /* Number of pointers to this object */
241087  int nTombstone;
241088  Fts5Data *apTombstone[1];       /* Array of tombstone pages */
241089};
241090
241091/*
241092** Argument is a pointer to an Fts5Data structure that contains a
241093** leaf page.
241094*/
241095#define ASSERT_SZLEAF_OK(x) assert( \
241096    (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
241097)
241098
241099#define FTS5_SEGITER_ONETERM 0x01
241100#define FTS5_SEGITER_REVERSE 0x02
241101
241102/*
241103** Argument is a pointer to an Fts5Data structure that contains a leaf
241104** page. This macro evaluates to true if the leaf contains no terms, or
241105** false if it contains at least one term.
241106*/
241107#define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
241108
241109#define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
241110
241111#define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
241112
241113/*
241114** Object for iterating through the merged results of one or more segments,
241115** visiting each term/rowid pair in the merged data.
241116**
241117** nSeg is always a power of two greater than or equal to the number of
241118** segments that this object is merging data from. Both the aSeg[] and
241119** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
241120** with zeroed objects - these are handled as if they were iterators opened
241121** on empty segments.
241122**
241123** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
241124** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
241125** comparison in this context is the index of the iterator that currently
241126** points to the smaller term/rowid combination. Iterators at EOF are
241127** considered to be greater than all other iterators.
241128**
241129** aFirst[1] contains the index in aSeg[] of the iterator that points to
241130** the smallest key overall. aFirst[0] is unused.
241131**
241132** poslist:
241133**   Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
241134**   There is no way to tell if this is populated or not.
241135**
241136** pColset:
241137**   If not NULL, points to an object containing a set of column indices.
241138**   Only matches that occur in one of these columns will be returned.
241139**   The Fts5Iter does not own the Fts5Colset object, and so it is not
241140**   freed when the iterator is closed - it is owned by the upper layer.
241141*/
241142struct Fts5Iter {
241143  Fts5IndexIter base;             /* Base class containing output vars */
241144  Fts5TokenDataIter *pTokenDataIter;
241145
241146  Fts5Index *pIndex;              /* Index that owns this iterator */
241147  Fts5Buffer poslist;             /* Buffer containing current poslist */
241148  Fts5Colset *pColset;            /* Restrict matches to these columns */
241149
241150  /* Invoked to set output variables. */
241151  void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
241152
241153  int nSeg;                       /* Size of aSeg[] array */
241154  int bRev;                       /* True to iterate in reverse order */
241155  u8 bSkipEmpty;                  /* True to skip deleted entries */
241156
241157  i64 iSwitchRowid;               /* Firstest rowid of other than aFirst[1] */
241158  Fts5CResult *aFirst;            /* Current merge state (see above) */
241159  Fts5SegIter aSeg[1];            /* Array of segment iterators */
241160};
241161
241162/*
241163** An instance of the following type is used to iterate through the contents
241164** of a doclist-index record.
241165**
241166** pData:
241167**   Record containing the doclist-index data.
241168**
241169** bEof:
241170**   Set to true once iterator has reached EOF.
241171**
241172** iOff:
241173**   Set to the current offset within record pData.
241174*/
241175struct Fts5DlidxLvl {
241176  Fts5Data *pData;              /* Data for current page of this level */
241177  int iOff;                     /* Current offset into pData */
241178  int bEof;                     /* At EOF already */
241179  int iFirstOff;                /* Used by reverse iterators */
241180
241181  /* Output variables */
241182  int iLeafPgno;                /* Page number of current leaf page */
241183  i64 iRowid;                   /* First rowid on leaf iLeafPgno */
241184};
241185struct Fts5DlidxIter {
241186  int nLvl;
241187  int iSegid;
241188  Fts5DlidxLvl aLvl[1];
241189};
241190
241191static void fts5PutU16(u8 *aOut, u16 iVal){
241192  aOut[0] = (iVal>>8);
241193  aOut[1] = (iVal&0xFF);
241194}
241195
241196static u16 fts5GetU16(const u8 *aIn){
241197  return ((u16)aIn[0] << 8) + aIn[1];
241198}
241199
241200/*
241201** The only argument points to a buffer at least 8 bytes in size. This
241202** function interprets the first 8 bytes of the buffer as a 64-bit big-endian
241203** unsigned integer and returns the result.
241204*/
241205static u64 fts5GetU64(u8 *a){
241206  return ((u64)a[0] << 56)
241207       + ((u64)a[1] << 48)
241208       + ((u64)a[2] << 40)
241209       + ((u64)a[3] << 32)
241210       + ((u64)a[4] << 24)
241211       + ((u64)a[5] << 16)
241212       + ((u64)a[6] << 8)
241213       + ((u64)a[7] << 0);
241214}
241215
241216/*
241217** The only argument points to a buffer at least 4 bytes in size. This
241218** function interprets the first 4 bytes of the buffer as a 32-bit big-endian
241219** unsigned integer and returns the result.
241220*/
241221static u32 fts5GetU32(const u8 *a){
241222  return ((u32)a[0] << 24)
241223       + ((u32)a[1] << 16)
241224       + ((u32)a[2] << 8)
241225       + ((u32)a[3] << 0);
241226}
241227
241228/*
241229** Write iVal, formated as a 64-bit big-endian unsigned integer, to the
241230** buffer indicated by the first argument.
241231*/
241232static void fts5PutU64(u8 *a, u64 iVal){
241233  a[0] = ((iVal >> 56) & 0xFF);
241234  a[1] = ((iVal >> 48) & 0xFF);
241235  a[2] = ((iVal >> 40) & 0xFF);
241236  a[3] = ((iVal >> 32) & 0xFF);
241237  a[4] = ((iVal >> 24) & 0xFF);
241238  a[5] = ((iVal >> 16) & 0xFF);
241239  a[6] = ((iVal >>  8) & 0xFF);
241240  a[7] = ((iVal >>  0) & 0xFF);
241241}
241242
241243/*
241244** Write iVal, formated as a 32-bit big-endian unsigned integer, to the
241245** buffer indicated by the first argument.
241246*/
241247static void fts5PutU32(u8 *a, u32 iVal){
241248  a[0] = ((iVal >> 24) & 0xFF);
241249  a[1] = ((iVal >> 16) & 0xFF);
241250  a[2] = ((iVal >>  8) & 0xFF);
241251  a[3] = ((iVal >>  0) & 0xFF);
241252}
241253
241254/*
241255** Allocate and return a buffer at least nByte bytes in size.
241256**
241257** If an OOM error is encountered, return NULL and set the error code in
241258** the Fts5Index handle passed as the first argument.
241259*/
241260static void *fts5IdxMalloc(Fts5Index *p, sqlite3_int64 nByte){
241261  return sqlite3Fts5MallocZero(&p->rc, nByte);
241262}
241263
241264/*
241265** Compare the contents of the pLeft buffer with the pRight/nRight blob.
241266**
241267** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
241268** +ve if pRight is smaller than pLeft. In other words:
241269**
241270**     res = *pLeft - *pRight
241271*/
241272#ifdef SQLITE_DEBUG
241273static int fts5BufferCompareBlob(
241274  Fts5Buffer *pLeft,              /* Left hand side of comparison */
241275  const u8 *pRight, int nRight    /* Right hand side of comparison */
241276){
241277  int nCmp = MIN(pLeft->n, nRight);
241278  int res = memcmp(pLeft->p, pRight, nCmp);
241279  return (res==0 ? (pLeft->n - nRight) : res);
241280}
241281#endif
241282
241283/*
241284** Compare the contents of the two buffers using memcmp(). If one buffer
241285** is a prefix of the other, it is considered the lesser.
241286**
241287** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
241288** +ve if pRight is smaller than pLeft. In other words:
241289**
241290**     res = *pLeft - *pRight
241291*/
241292static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
241293  int nCmp, res;
241294  nCmp = MIN(pLeft->n, pRight->n);
241295  assert( nCmp<=0 || pLeft->p!=0 );
241296  assert( nCmp<=0 || pRight->p!=0 );
241297  res = fts5Memcmp(pLeft->p, pRight->p, nCmp);
241298  return (res==0 ? (pLeft->n - pRight->n) : res);
241299}
241300
241301static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
241302  int ret;
241303  fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
241304  return ret;
241305}
241306
241307/*
241308** Close the read-only blob handle, if it is open.
241309*/
241310static void sqlite3Fts5IndexCloseReader(Fts5Index *p){
241311  if( p->pReader ){
241312    sqlite3_blob *pReader = p->pReader;
241313    p->pReader = 0;
241314    sqlite3_blob_close(pReader);
241315  }
241316}
241317
241318/*
241319** Retrieve a record from the %_data table.
241320**
241321** If an error occurs, NULL is returned and an error left in the
241322** Fts5Index object.
241323*/
241324static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
241325  Fts5Data *pRet = 0;
241326  if( p->rc==SQLITE_OK ){
241327    int rc = SQLITE_OK;
241328
241329    if( p->pReader ){
241330      /* This call may return SQLITE_ABORT if there has been a savepoint
241331      ** rollback since it was last used. In this case a new blob handle
241332      ** is required.  */
241333      sqlite3_blob *pBlob = p->pReader;
241334      p->pReader = 0;
241335      rc = sqlite3_blob_reopen(pBlob, iRowid);
241336      assert( p->pReader==0 );
241337      p->pReader = pBlob;
241338      if( rc!=SQLITE_OK ){
241339        sqlite3Fts5IndexCloseReader(p);
241340      }
241341      if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
241342    }
241343
241344    /* If the blob handle is not open at this point, open it and seek
241345    ** to the requested entry.  */
241346    if( p->pReader==0 && rc==SQLITE_OK ){
241347      Fts5Config *pConfig = p->pConfig;
241348      rc = sqlite3_blob_open(pConfig->db,
241349          pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
241350      );
241351    }
241352
241353    /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
241354    ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
241355    ** All the reasons those functions might return SQLITE_ERROR - missing
241356    ** table, missing row, non-blob/text in block column - indicate
241357    ** backing store corruption.  */
241358    if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
241359
241360    if( rc==SQLITE_OK ){
241361      u8 *aOut = 0;               /* Read blob data into this buffer */
241362      int nByte = sqlite3_blob_bytes(p->pReader);
241363      sqlite3_int64 nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
241364      pRet = (Fts5Data*)sqlite3_malloc64(nAlloc);
241365      if( pRet ){
241366        pRet->nn = nByte;
241367        aOut = pRet->p = (u8*)&pRet[1];
241368      }else{
241369        rc = SQLITE_NOMEM;
241370      }
241371
241372      if( rc==SQLITE_OK ){
241373        rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
241374      }
241375      if( rc!=SQLITE_OK ){
241376        sqlite3_free(pRet);
241377        pRet = 0;
241378      }else{
241379        /* TODO1: Fix this */
241380        pRet->p[nByte] = 0x00;
241381        pRet->p[nByte+1] = 0x00;
241382        pRet->szLeaf = fts5GetU16(&pRet->p[2]);
241383      }
241384    }
241385    p->rc = rc;
241386    p->nRead++;
241387  }
241388
241389  assert( (pRet==0)==(p->rc!=SQLITE_OK) );
241390  return pRet;
241391}
241392
241393
241394/*
241395** Release a reference to data record returned by an earlier call to
241396** fts5DataRead().
241397*/
241398static void fts5DataRelease(Fts5Data *pData){
241399  sqlite3_free(pData);
241400}
241401
241402static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
241403  Fts5Data *pRet = fts5DataRead(p, iRowid);
241404  if( pRet ){
241405    if( pRet->nn<4 || pRet->szLeaf>pRet->nn ){
241406      p->rc = FTS5_CORRUPT;
241407      fts5DataRelease(pRet);
241408      pRet = 0;
241409    }
241410  }
241411  return pRet;
241412}
241413
241414static int fts5IndexPrepareStmt(
241415  Fts5Index *p,
241416  sqlite3_stmt **ppStmt,
241417  char *zSql
241418){
241419  if( p->rc==SQLITE_OK ){
241420    if( zSql ){
241421      p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
241422          SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB,
241423          ppStmt, 0);
241424    }else{
241425      p->rc = SQLITE_NOMEM;
241426    }
241427  }
241428  sqlite3_free(zSql);
241429  return p->rc;
241430}
241431
241432
241433/*
241434** INSERT OR REPLACE a record into the %_data table.
241435*/
241436static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
241437  if( p->rc!=SQLITE_OK ) return;
241438
241439  if( p->pWriter==0 ){
241440    Fts5Config *pConfig = p->pConfig;
241441    fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
241442          "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
241443          pConfig->zDb, pConfig->zName
241444    ));
241445    if( p->rc ) return;
241446  }
241447
241448  sqlite3_bind_int64(p->pWriter, 1, iRowid);
241449  sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
241450  sqlite3_step(p->pWriter);
241451  p->rc = sqlite3_reset(p->pWriter);
241452  sqlite3_bind_null(p->pWriter, 2);
241453}
241454
241455/*
241456** Execute the following SQL:
241457**
241458**     DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
241459*/
241460static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
241461  if( p->rc!=SQLITE_OK ) return;
241462
241463  if( p->pDeleter==0 ){
241464    Fts5Config *pConfig = p->pConfig;
241465    char *zSql = sqlite3_mprintf(
241466        "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
241467          pConfig->zDb, pConfig->zName
241468    );
241469    if( fts5IndexPrepareStmt(p, &p->pDeleter, zSql) ) return;
241470  }
241471
241472  sqlite3_bind_int64(p->pDeleter, 1, iFirst);
241473  sqlite3_bind_int64(p->pDeleter, 2, iLast);
241474  sqlite3_step(p->pDeleter);
241475  p->rc = sqlite3_reset(p->pDeleter);
241476}
241477
241478/*
241479** Remove all records associated with segment iSegid.
241480*/
241481static void fts5DataRemoveSegment(Fts5Index *p, Fts5StructureSegment *pSeg){
241482  int iSegid = pSeg->iSegid;
241483  i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
241484  i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
241485  fts5DataDelete(p, iFirst, iLast);
241486
241487  if( pSeg->nPgTombstone ){
241488    i64 iTomb1 = FTS5_TOMBSTONE_ROWID(iSegid, 0);
241489    i64 iTomb2 = FTS5_TOMBSTONE_ROWID(iSegid, pSeg->nPgTombstone-1);
241490    fts5DataDelete(p, iTomb1, iTomb2);
241491  }
241492  if( p->pIdxDeleter==0 ){
241493    Fts5Config *pConfig = p->pConfig;
241494    fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
241495          "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
241496          pConfig->zDb, pConfig->zName
241497    ));
241498  }
241499  if( p->rc==SQLITE_OK ){
241500    sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
241501    sqlite3_step(p->pIdxDeleter);
241502    p->rc = sqlite3_reset(p->pIdxDeleter);
241503  }
241504}
241505
241506/*
241507** Release a reference to an Fts5Structure object returned by an earlier
241508** call to fts5StructureRead() or fts5StructureDecode().
241509*/
241510static void fts5StructureRelease(Fts5Structure *pStruct){
241511  if( pStruct && 0>=(--pStruct->nRef) ){
241512    int i;
241513    assert( pStruct->nRef==0 );
241514    for(i=0; i<pStruct->nLevel; i++){
241515      sqlite3_free(pStruct->aLevel[i].aSeg);
241516    }
241517    sqlite3_free(pStruct);
241518  }
241519}
241520
241521static void fts5StructureRef(Fts5Structure *pStruct){
241522  pStruct->nRef++;
241523}
241524
241525static void *sqlite3Fts5StructureRef(Fts5Index *p){
241526  fts5StructureRef(p->pStruct);
241527  return (void*)p->pStruct;
241528}
241529static void sqlite3Fts5StructureRelease(void *p){
241530  if( p ){
241531    fts5StructureRelease((Fts5Structure*)p);
241532  }
241533}
241534static int sqlite3Fts5StructureTest(Fts5Index *p, void *pStruct){
241535  if( p->pStruct!=(Fts5Structure*)pStruct ){
241536    return SQLITE_ABORT;
241537  }
241538  return SQLITE_OK;
241539}
241540
241541/*
241542** Ensure that structure object (*pp) is writable.
241543**
241544** This function is a no-op if (*pRc) is not SQLITE_OK when it is called. If
241545** an error occurs, (*pRc) is set to an SQLite error code before returning.
241546*/
241547static void fts5StructureMakeWritable(int *pRc, Fts5Structure **pp){
241548  Fts5Structure *p = *pp;
241549  if( *pRc==SQLITE_OK && p->nRef>1 ){
241550    i64 nByte = sizeof(Fts5Structure)+(p->nLevel-1)*sizeof(Fts5StructureLevel);
241551    Fts5Structure *pNew;
241552    pNew = (Fts5Structure*)sqlite3Fts5MallocZero(pRc, nByte);
241553    if( pNew ){
241554      int i;
241555      memcpy(pNew, p, nByte);
241556      for(i=0; i<p->nLevel; i++) pNew->aLevel[i].aSeg = 0;
241557      for(i=0; i<p->nLevel; i++){
241558        Fts5StructureLevel *pLvl = &pNew->aLevel[i];
241559        nByte = sizeof(Fts5StructureSegment) * pNew->aLevel[i].nSeg;
241560        pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(pRc, nByte);
241561        if( pLvl->aSeg==0 ){
241562          for(i=0; i<p->nLevel; i++){
241563            sqlite3_free(pNew->aLevel[i].aSeg);
241564          }
241565          sqlite3_free(pNew);
241566          return;
241567        }
241568        memcpy(pLvl->aSeg, p->aLevel[i].aSeg, nByte);
241569      }
241570      p->nRef--;
241571      pNew->nRef = 1;
241572    }
241573    *pp = pNew;
241574  }
241575}
241576
241577/*
241578** Deserialize and return the structure record currently stored in serialized
241579** form within buffer pData/nData.
241580**
241581** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
241582** are over-allocated by one slot. This allows the structure contents
241583** to be more easily edited.
241584**
241585** If an error occurs, *ppOut is set to NULL and an SQLite error code
241586** returned. Otherwise, *ppOut is set to point to the new object and
241587** SQLITE_OK returned.
241588*/
241589static int fts5StructureDecode(
241590  const u8 *pData,                /* Buffer containing serialized structure */
241591  int nData,                      /* Size of buffer pData in bytes */
241592  int *piCookie,                  /* Configuration cookie value */
241593  Fts5Structure **ppOut           /* OUT: Deserialized object */
241594){
241595  int rc = SQLITE_OK;
241596  int i = 0;
241597  int iLvl;
241598  int nLevel = 0;
241599  int nSegment = 0;
241600  sqlite3_int64 nByte;            /* Bytes of space to allocate at pRet */
241601  Fts5Structure *pRet = 0;        /* Structure object to return */
241602  int bStructureV2 = 0;           /* True for FTS5_STRUCTURE_V2 */
241603  u64 nOriginCntr = 0;            /* Largest origin value seen so far */
241604
241605  /* Grab the cookie value */
241606  if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
241607  i = 4;
241608
241609  /* Check if this is a V2 structure record. Set bStructureV2 if it is. */
241610  if( 0==memcmp(&pData[i], FTS5_STRUCTURE_V2, 4) ){
241611    i += 4;
241612    bStructureV2 = 1;
241613  }
241614
241615  /* Read the total number of levels and segments from the start of the
241616  ** structure record.  */
241617  i += fts5GetVarint32(&pData[i], nLevel);
241618  i += fts5GetVarint32(&pData[i], nSegment);
241619  if( nLevel>FTS5_MAX_SEGMENT   || nLevel<0
241620   || nSegment>FTS5_MAX_SEGMENT || nSegment<0
241621  ){
241622    return FTS5_CORRUPT;
241623  }
241624  nByte = (
241625      sizeof(Fts5Structure) +                    /* Main structure */
241626      sizeof(Fts5StructureLevel) * (nLevel-1)    /* aLevel[] array */
241627  );
241628  pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
241629
241630  if( pRet ){
241631    pRet->nRef = 1;
241632    pRet->nLevel = nLevel;
241633    pRet->nSegment = nSegment;
241634    i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
241635
241636    for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
241637      Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
241638      int nTotal = 0;
241639      int iSeg;
241640
241641      if( i>=nData ){
241642        rc = FTS5_CORRUPT;
241643      }else{
241644        i += fts5GetVarint32(&pData[i], pLvl->nMerge);
241645        i += fts5GetVarint32(&pData[i], nTotal);
241646        if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT;
241647        pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
241648            nTotal * sizeof(Fts5StructureSegment)
241649        );
241650        nSegment -= nTotal;
241651      }
241652
241653      if( rc==SQLITE_OK ){
241654        pLvl->nSeg = nTotal;
241655        for(iSeg=0; iSeg<nTotal; iSeg++){
241656          Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
241657          if( i>=nData ){
241658            rc = FTS5_CORRUPT;
241659            break;
241660          }
241661          assert( pSeg!=0 );
241662          i += fts5GetVarint32(&pData[i], pSeg->iSegid);
241663          i += fts5GetVarint32(&pData[i], pSeg->pgnoFirst);
241664          i += fts5GetVarint32(&pData[i], pSeg->pgnoLast);
241665          if( bStructureV2 ){
241666            i += fts5GetVarint(&pData[i], &pSeg->iOrigin1);
241667            i += fts5GetVarint(&pData[i], &pSeg->iOrigin2);
241668            i += fts5GetVarint32(&pData[i], pSeg->nPgTombstone);
241669            i += fts5GetVarint(&pData[i], &pSeg->nEntryTombstone);
241670            i += fts5GetVarint(&pData[i], &pSeg->nEntry);
241671            nOriginCntr = MAX(nOriginCntr, pSeg->iOrigin2);
241672          }
241673          if( pSeg->pgnoLast<pSeg->pgnoFirst ){
241674            rc = FTS5_CORRUPT;
241675            break;
241676          }
241677        }
241678        if( iLvl>0 && pLvl[-1].nMerge && nTotal==0 ) rc = FTS5_CORRUPT;
241679        if( iLvl==nLevel-1 && pLvl->nMerge ) rc = FTS5_CORRUPT;
241680      }
241681    }
241682    if( nSegment!=0 && rc==SQLITE_OK ) rc = FTS5_CORRUPT;
241683    if( bStructureV2 ){
241684      pRet->nOriginCntr = nOriginCntr+1;
241685    }
241686
241687    if( rc!=SQLITE_OK ){
241688      fts5StructureRelease(pRet);
241689      pRet = 0;
241690    }
241691  }
241692
241693  *ppOut = pRet;
241694  return rc;
241695}
241696
241697/*
241698** Add a level to the Fts5Structure.aLevel[] array of structure object
241699** (*ppStruct).
241700*/
241701static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
241702  fts5StructureMakeWritable(pRc, ppStruct);
241703  assert( (ppStruct!=0 && (*ppStruct)!=0) || (*pRc)!=SQLITE_OK );
241704  if( *pRc==SQLITE_OK ){
241705    Fts5Structure *pStruct = *ppStruct;
241706    int nLevel = pStruct->nLevel;
241707    sqlite3_int64 nByte = (
241708        sizeof(Fts5Structure) +                  /* Main structure */
241709        sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */
241710    );
241711
241712    pStruct = sqlite3_realloc64(pStruct, nByte);
241713    if( pStruct ){
241714      memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
241715      pStruct->nLevel++;
241716      *ppStruct = pStruct;
241717    }else{
241718      *pRc = SQLITE_NOMEM;
241719    }
241720  }
241721}
241722
241723/*
241724** Extend level iLvl so that there is room for at least nExtra more
241725** segments.
241726*/
241727static void fts5StructureExtendLevel(
241728  int *pRc,
241729  Fts5Structure *pStruct,
241730  int iLvl,
241731  int nExtra,
241732  int bInsert
241733){
241734  if( *pRc==SQLITE_OK ){
241735    Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
241736    Fts5StructureSegment *aNew;
241737    sqlite3_int64 nByte;
241738
241739    nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
241740    aNew = sqlite3_realloc64(pLvl->aSeg, nByte);
241741    if( aNew ){
241742      if( bInsert==0 ){
241743        memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
241744      }else{
241745        int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
241746        memmove(&aNew[nExtra], aNew, nMove);
241747        memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
241748      }
241749      pLvl->aSeg = aNew;
241750    }else{
241751      *pRc = SQLITE_NOMEM;
241752    }
241753  }
241754}
241755
241756static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
241757  Fts5Structure *pRet = 0;
241758  Fts5Config *pConfig = p->pConfig;
241759  int iCookie;                    /* Configuration cookie */
241760  Fts5Data *pData;
241761
241762  pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
241763  if( p->rc==SQLITE_OK ){
241764    /* TODO: Do we need this if the leaf-index is appended? Probably... */
241765    memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
241766    p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
241767    if( p->rc==SQLITE_OK && (pConfig->pgsz==0 || pConfig->iCookie!=iCookie) ){
241768      p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
241769    }
241770    fts5DataRelease(pData);
241771    if( p->rc!=SQLITE_OK ){
241772      fts5StructureRelease(pRet);
241773      pRet = 0;
241774    }
241775  }
241776
241777  return pRet;
241778}
241779
241780static i64 fts5IndexDataVersion(Fts5Index *p){
241781  i64 iVersion = 0;
241782
241783  if( p->rc==SQLITE_OK ){
241784    if( p->pDataVersion==0 ){
241785      p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
241786          sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
241787          );
241788      if( p->rc ) return 0;
241789    }
241790
241791    if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
241792      iVersion = sqlite3_column_int64(p->pDataVersion, 0);
241793    }
241794    p->rc = sqlite3_reset(p->pDataVersion);
241795  }
241796
241797  return iVersion;
241798}
241799
241800/*
241801** Read, deserialize and return the structure record.
241802**
241803** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
241804** are over-allocated as described for function fts5StructureDecode()
241805** above.
241806**
241807** If an error occurs, NULL is returned and an error code left in the
241808** Fts5Index handle. If an error has already occurred when this function
241809** is called, it is a no-op.
241810*/
241811static Fts5Structure *fts5StructureRead(Fts5Index *p){
241812
241813  if( p->pStruct==0 ){
241814    p->iStructVersion = fts5IndexDataVersion(p);
241815    if( p->rc==SQLITE_OK ){
241816      p->pStruct = fts5StructureReadUncached(p);
241817    }
241818  }
241819
241820#if 0
241821  else{
241822    Fts5Structure *pTest = fts5StructureReadUncached(p);
241823    if( pTest ){
241824      int i, j;
241825      assert_nc( p->pStruct->nSegment==pTest->nSegment );
241826      assert_nc( p->pStruct->nLevel==pTest->nLevel );
241827      for(i=0; i<pTest->nLevel; i++){
241828        assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
241829        assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
241830        for(j=0; j<pTest->aLevel[i].nSeg; j++){
241831          Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
241832          Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
241833          assert_nc( p1->iSegid==p2->iSegid );
241834          assert_nc( p1->pgnoFirst==p2->pgnoFirst );
241835          assert_nc( p1->pgnoLast==p2->pgnoLast );
241836        }
241837      }
241838      fts5StructureRelease(pTest);
241839    }
241840  }
241841#endif
241842
241843  if( p->rc!=SQLITE_OK ) return 0;
241844  assert( p->iStructVersion!=0 );
241845  assert( p->pStruct!=0 );
241846  fts5StructureRef(p->pStruct);
241847  return p->pStruct;
241848}
241849
241850static void fts5StructureInvalidate(Fts5Index *p){
241851  if( p->pStruct ){
241852    fts5StructureRelease(p->pStruct);
241853    p->pStruct = 0;
241854  }
241855}
241856
241857/*
241858** Return the total number of segments in index structure pStruct. This
241859** function is only ever used as part of assert() conditions.
241860*/
241861#ifdef SQLITE_DEBUG
241862static int fts5StructureCountSegments(Fts5Structure *pStruct){
241863  int nSegment = 0;               /* Total number of segments */
241864  if( pStruct ){
241865    int iLvl;                     /* Used to iterate through levels */
241866    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
241867      nSegment += pStruct->aLevel[iLvl].nSeg;
241868    }
241869  }
241870
241871  return nSegment;
241872}
241873#endif
241874
241875#define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) {     \
241876  assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) );             \
241877  memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob);             \
241878  (pBuf)->n += nBlob;                                      \
241879}
241880
241881#define fts5BufferSafeAppendVarint(pBuf, iVal) {                \
241882  (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal));  \
241883  assert( (pBuf)->nSpace>=(pBuf)->n );                          \
241884}
241885
241886
241887/*
241888** Serialize and store the "structure" record.
241889**
241890** If an error occurs, leave an error code in the Fts5Index object. If an
241891** error has already occurred, this function is a no-op.
241892*/
241893static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
241894  if( p->rc==SQLITE_OK ){
241895    Fts5Buffer buf;               /* Buffer to serialize record into */
241896    int iLvl;                     /* Used to iterate through levels */
241897    int iCookie;                  /* Cookie value to store */
241898    int nHdr = (pStruct->nOriginCntr>0 ? (4+4+9+9+9) : (4+9+9));
241899
241900    assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
241901    memset(&buf, 0, sizeof(Fts5Buffer));
241902
241903    /* Append the current configuration cookie */
241904    iCookie = p->pConfig->iCookie;
241905    if( iCookie<0 ) iCookie = 0;
241906
241907    if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, nHdr) ){
241908      sqlite3Fts5Put32(buf.p, iCookie);
241909      buf.n = 4;
241910      if( pStruct->nOriginCntr>0 ){
241911        fts5BufferSafeAppendBlob(&buf, FTS5_STRUCTURE_V2, 4);
241912      }
241913      fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
241914      fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
241915      fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
241916    }
241917
241918    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
241919      int iSeg;                     /* Used to iterate through segments */
241920      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
241921      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
241922      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
241923      assert( pLvl->nMerge<=pLvl->nSeg );
241924
241925      for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
241926        Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
241927        fts5BufferAppendVarint(&p->rc, &buf, pSeg->iSegid);
241928        fts5BufferAppendVarint(&p->rc, &buf, pSeg->pgnoFirst);
241929        fts5BufferAppendVarint(&p->rc, &buf, pSeg->pgnoLast);
241930        if( pStruct->nOriginCntr>0 ){
241931          fts5BufferAppendVarint(&p->rc, &buf, pSeg->iOrigin1);
241932          fts5BufferAppendVarint(&p->rc, &buf, pSeg->iOrigin2);
241933          fts5BufferAppendVarint(&p->rc, &buf, pSeg->nPgTombstone);
241934          fts5BufferAppendVarint(&p->rc, &buf, pSeg->nEntryTombstone);
241935          fts5BufferAppendVarint(&p->rc, &buf, pSeg->nEntry);
241936        }
241937      }
241938    }
241939
241940    fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
241941    fts5BufferFree(&buf);
241942  }
241943}
241944
241945#if 0
241946static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
241947static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
241948  int rc = SQLITE_OK;
241949  Fts5Buffer buf;
241950  memset(&buf, 0, sizeof(buf));
241951  fts5DebugStructure(&rc, &buf, pStruct);
241952  fprintf(stdout, "%s: %s\n", zCaption, buf.p);
241953  fflush(stdout);
241954  fts5BufferFree(&buf);
241955}
241956#else
241957# define fts5PrintStructure(x,y)
241958#endif
241959
241960static int fts5SegmentSize(Fts5StructureSegment *pSeg){
241961  return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
241962}
241963
241964/*
241965** Return a copy of index structure pStruct. Except, promote as many
241966** segments as possible to level iPromote. If an OOM occurs, NULL is
241967** returned.
241968*/
241969static void fts5StructurePromoteTo(
241970  Fts5Index *p,
241971  int iPromote,
241972  int szPromote,
241973  Fts5Structure *pStruct
241974){
241975  int il, is;
241976  Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
241977
241978  if( pOut->nMerge==0 ){
241979    for(il=iPromote+1; il<pStruct->nLevel; il++){
241980      Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
241981      if( pLvl->nMerge ) return;
241982      for(is=pLvl->nSeg-1; is>=0; is--){
241983        int sz = fts5SegmentSize(&pLvl->aSeg[is]);
241984        if( sz>szPromote ) return;
241985        fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
241986        if( p->rc ) return;
241987        memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
241988        pOut->nSeg++;
241989        pLvl->nSeg--;
241990      }
241991    }
241992  }
241993}
241994
241995/*
241996** A new segment has just been written to level iLvl of index structure
241997** pStruct. This function determines if any segments should be promoted
241998** as a result. Segments are promoted in two scenarios:
241999**
242000**   a) If the segment just written is smaller than one or more segments
242001**      within the previous populated level, it is promoted to the previous
242002**      populated level.
242003**
242004**   b) If the segment just written is larger than the newest segment on
242005**      the next populated level, then that segment, and any other adjacent
242006**      segments that are also smaller than the one just written, are
242007**      promoted.
242008**
242009** If one or more segments are promoted, the structure object is updated
242010** to reflect this.
242011*/
242012static void fts5StructurePromote(
242013  Fts5Index *p,                   /* FTS5 backend object */
242014  int iLvl,                       /* Index level just updated */
242015  Fts5Structure *pStruct          /* Index structure */
242016){
242017  if( p->rc==SQLITE_OK ){
242018    int iTst;
242019    int iPromote = -1;
242020    int szPromote = 0;            /* Promote anything this size or smaller */
242021    Fts5StructureSegment *pSeg;   /* Segment just written */
242022    int szSeg;                    /* Size of segment just written */
242023    int nSeg = pStruct->aLevel[iLvl].nSeg;
242024
242025    if( nSeg==0 ) return;
242026    pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
242027    szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
242028
242029    /* Check for condition (a) */
242030    for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
242031    if( iTst>=0 ){
242032      int i;
242033      int szMax = 0;
242034      Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
242035      assert( pTst->nMerge==0 );
242036      for(i=0; i<pTst->nSeg; i++){
242037        int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
242038        if( sz>szMax ) szMax = sz;
242039      }
242040      if( szMax>=szSeg ){
242041        /* Condition (a) is true. Promote the newest segment on level
242042        ** iLvl to level iTst.  */
242043        iPromote = iTst;
242044        szPromote = szMax;
242045      }
242046    }
242047
242048    /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
242049    ** is a no-op if it is not.  */
242050    if( iPromote<0 ){
242051      iPromote = iLvl;
242052      szPromote = szSeg;
242053    }
242054    fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
242055  }
242056}
242057
242058
242059/*
242060** Advance the iterator passed as the only argument. If the end of the
242061** doclist-index page is reached, return non-zero.
242062*/
242063static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
242064  Fts5Data *pData = pLvl->pData;
242065
242066  if( pLvl->iOff==0 ){
242067    assert( pLvl->bEof==0 );
242068    pLvl->iOff = 1;
242069    pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
242070    pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
242071    pLvl->iFirstOff = pLvl->iOff;
242072  }else{
242073    int iOff;
242074    for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
242075      if( pData->p[iOff] ) break;
242076    }
242077
242078    if( iOff<pData->nn ){
242079      u64 iVal;
242080      pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
242081      iOff += fts5GetVarint(&pData->p[iOff], &iVal);
242082      pLvl->iRowid += iVal;
242083      pLvl->iOff = iOff;
242084    }else{
242085      pLvl->bEof = 1;
242086    }
242087  }
242088
242089  return pLvl->bEof;
242090}
242091
242092/*
242093** Advance the iterator passed as the only argument.
242094*/
242095static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
242096  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
242097
242098  assert( iLvl<pIter->nLvl );
242099  if( fts5DlidxLvlNext(pLvl) ){
242100    if( (iLvl+1) < pIter->nLvl ){
242101      fts5DlidxIterNextR(p, pIter, iLvl+1);
242102      if( pLvl[1].bEof==0 ){
242103        fts5DataRelease(pLvl->pData);
242104        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
242105        pLvl->pData = fts5DataRead(p,
242106            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
242107        );
242108        if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
242109      }
242110    }
242111  }
242112
242113  return pIter->aLvl[0].bEof;
242114}
242115static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
242116  return fts5DlidxIterNextR(p, pIter, 0);
242117}
242118
242119/*
242120** The iterator passed as the first argument has the following fields set
242121** as follows. This function sets up the rest of the iterator so that it
242122** points to the first rowid in the doclist-index.
242123**
242124**   pData:
242125**     pointer to doclist-index record,
242126**
242127** When this function is called pIter->iLeafPgno is the page number the
242128** doclist is associated with (the one featuring the term).
242129*/
242130static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
242131  int i;
242132  for(i=0; i<pIter->nLvl; i++){
242133    fts5DlidxLvlNext(&pIter->aLvl[i]);
242134  }
242135  return pIter->aLvl[0].bEof;
242136}
242137
242138
242139static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
242140  return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
242141}
242142
242143static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
242144  int i;
242145
242146  /* Advance each level to the last entry on the last page */
242147  for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
242148    Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
242149    while( fts5DlidxLvlNext(pLvl)==0 );
242150    pLvl->bEof = 0;
242151
242152    if( i>0 ){
242153      Fts5DlidxLvl *pChild = &pLvl[-1];
242154      fts5DataRelease(pChild->pData);
242155      memset(pChild, 0, sizeof(Fts5DlidxLvl));
242156      pChild->pData = fts5DataRead(p,
242157          FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
242158      );
242159    }
242160  }
242161}
242162
242163/*
242164** Move the iterator passed as the only argument to the previous entry.
242165*/
242166static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
242167  int iOff = pLvl->iOff;
242168
242169  assert( pLvl->bEof==0 );
242170  if( iOff<=pLvl->iFirstOff ){
242171    pLvl->bEof = 1;
242172  }else{
242173    u8 *a = pLvl->pData->p;
242174
242175    pLvl->iOff = 0;
242176    fts5DlidxLvlNext(pLvl);
242177    while( 1 ){
242178      int nZero = 0;
242179      int ii = pLvl->iOff;
242180      u64 delta = 0;
242181
242182      while( a[ii]==0 ){
242183        nZero++;
242184        ii++;
242185      }
242186      ii += sqlite3Fts5GetVarint(&a[ii], &delta);
242187
242188      if( ii>=iOff ) break;
242189      pLvl->iLeafPgno += nZero+1;
242190      pLvl->iRowid += delta;
242191      pLvl->iOff = ii;
242192    }
242193  }
242194
242195  return pLvl->bEof;
242196}
242197
242198static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
242199  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
242200
242201  assert( iLvl<pIter->nLvl );
242202  if( fts5DlidxLvlPrev(pLvl) ){
242203    if( (iLvl+1) < pIter->nLvl ){
242204      fts5DlidxIterPrevR(p, pIter, iLvl+1);
242205      if( pLvl[1].bEof==0 ){
242206        fts5DataRelease(pLvl->pData);
242207        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
242208        pLvl->pData = fts5DataRead(p,
242209            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
242210        );
242211        if( pLvl->pData ){
242212          while( fts5DlidxLvlNext(pLvl)==0 );
242213          pLvl->bEof = 0;
242214        }
242215      }
242216    }
242217  }
242218
242219  return pIter->aLvl[0].bEof;
242220}
242221static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
242222  return fts5DlidxIterPrevR(p, pIter, 0);
242223}
242224
242225/*
242226** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
242227*/
242228static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
242229  if( pIter ){
242230    int i;
242231    for(i=0; i<pIter->nLvl; i++){
242232      fts5DataRelease(pIter->aLvl[i].pData);
242233    }
242234    sqlite3_free(pIter);
242235  }
242236}
242237
242238static Fts5DlidxIter *fts5DlidxIterInit(
242239  Fts5Index *p,                   /* Fts5 Backend to iterate within */
242240  int bRev,                       /* True for ORDER BY ASC */
242241  int iSegid,                     /* Segment id */
242242  int iLeafPg                     /* Leaf page number to load dlidx for */
242243){
242244  Fts5DlidxIter *pIter = 0;
242245  int i;
242246  int bDone = 0;
242247
242248  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
242249    sqlite3_int64 nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
242250    Fts5DlidxIter *pNew;
242251
242252    pNew = (Fts5DlidxIter*)sqlite3_realloc64(pIter, nByte);
242253    if( pNew==0 ){
242254      p->rc = SQLITE_NOMEM;
242255    }else{
242256      i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
242257      Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
242258      pIter = pNew;
242259      memset(pLvl, 0, sizeof(Fts5DlidxLvl));
242260      pLvl->pData = fts5DataRead(p, iRowid);
242261      if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
242262        bDone = 1;
242263      }
242264      pIter->nLvl = i+1;
242265    }
242266  }
242267
242268  if( p->rc==SQLITE_OK ){
242269    pIter->iSegid = iSegid;
242270    if( bRev==0 ){
242271      fts5DlidxIterFirst(pIter);
242272    }else{
242273      fts5DlidxIterLast(p, pIter);
242274    }
242275  }
242276
242277  if( p->rc!=SQLITE_OK ){
242278    fts5DlidxIterFree(pIter);
242279    pIter = 0;
242280  }
242281
242282  return pIter;
242283}
242284
242285static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
242286  return pIter->aLvl[0].iRowid;
242287}
242288static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
242289  return pIter->aLvl[0].iLeafPgno;
242290}
242291
242292/*
242293** Load the next leaf page into the segment iterator.
242294*/
242295static void fts5SegIterNextPage(
242296  Fts5Index *p,                   /* FTS5 backend object */
242297  Fts5SegIter *pIter              /* Iterator to advance to next page */
242298){
242299  Fts5Data *pLeaf;
242300  Fts5StructureSegment *pSeg = pIter->pSeg;
242301  fts5DataRelease(pIter->pLeaf);
242302  pIter->iLeafPgno++;
242303  if( pIter->pNextLeaf ){
242304    pIter->pLeaf = pIter->pNextLeaf;
242305    pIter->pNextLeaf = 0;
242306  }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
242307    pIter->pLeaf = fts5LeafRead(p,
242308        FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
242309    );
242310  }else{
242311    pIter->pLeaf = 0;
242312  }
242313  pLeaf = pIter->pLeaf;
242314
242315  if( pLeaf ){
242316    pIter->iPgidxOff = pLeaf->szLeaf;
242317    if( fts5LeafIsTermless(pLeaf) ){
242318      pIter->iEndofDoclist = pLeaf->nn+1;
242319    }else{
242320      pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
242321          pIter->iEndofDoclist
242322      );
242323    }
242324  }
242325}
242326
242327/*
242328** Argument p points to a buffer containing a varint to be interpreted as a
242329** position list size field. Read the varint and return the number of bytes
242330** read. Before returning, set *pnSz to the number of bytes in the position
242331** list, and *pbDel to true if the delete flag is set, or false otherwise.
242332*/
242333static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
242334  int nSz;
242335  int n = 0;
242336  fts5FastGetVarint32(p, n, nSz);
242337  assert_nc( nSz>=0 );
242338  *pnSz = nSz/2;
242339  *pbDel = nSz & 0x0001;
242340  return n;
242341}
242342
242343/*
242344** Fts5SegIter.iLeafOffset currently points to the first byte of a
242345** position-list size field. Read the value of the field and store it
242346** in the following variables:
242347**
242348**   Fts5SegIter.nPos
242349**   Fts5SegIter.bDel
242350**
242351** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
242352** position list content (if any).
242353*/
242354static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
242355  if( p->rc==SQLITE_OK ){
242356    int iOff = pIter->iLeafOffset;  /* Offset to read at */
242357    ASSERT_SZLEAF_OK(pIter->pLeaf);
242358    if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
242359      int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
242360      pIter->bDel = 0;
242361      pIter->nPos = 1;
242362      if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
242363        pIter->bDel = 1;
242364        iOff++;
242365        if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
242366          pIter->nPos = 1;
242367          iOff++;
242368        }else{
242369          pIter->nPos = 0;
242370        }
242371      }
242372    }else{
242373      int nSz;
242374      fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
242375      pIter->bDel = (nSz & 0x0001);
242376      pIter->nPos = nSz>>1;
242377      assert_nc( pIter->nPos>=0 );
242378    }
242379    pIter->iLeafOffset = iOff;
242380  }
242381}
242382
242383static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
242384  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
242385  i64 iOff = pIter->iLeafOffset;
242386
242387  ASSERT_SZLEAF_OK(pIter->pLeaf);
242388  while( iOff>=pIter->pLeaf->szLeaf ){
242389    fts5SegIterNextPage(p, pIter);
242390    if( pIter->pLeaf==0 ){
242391      if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
242392      return;
242393    }
242394    iOff = 4;
242395    a = pIter->pLeaf->p;
242396  }
242397  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
242398  pIter->iLeafOffset = iOff;
242399}
242400
242401/*
242402** Fts5SegIter.iLeafOffset currently points to the first byte of the
242403** "nSuffix" field of a term. Function parameter nKeep contains the value
242404** of the "nPrefix" field (if there was one - it is passed 0 if this is
242405** the first term in the segment).
242406**
242407** This function populates:
242408**
242409**   Fts5SegIter.term
242410**   Fts5SegIter.rowid
242411**
242412** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
242413** the first position list. The position list belonging to document
242414** (Fts5SegIter.iRowid).
242415*/
242416static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
242417  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
242418  i64 iOff = pIter->iLeafOffset;  /* Offset to read at */
242419  int nNew;                       /* Bytes of new data */
242420
242421  iOff += fts5GetVarint32(&a[iOff], nNew);
242422  if( iOff+nNew>pIter->pLeaf->szLeaf || nKeep>pIter->term.n || nNew==0 ){
242423    p->rc = FTS5_CORRUPT;
242424    return;
242425  }
242426  pIter->term.n = nKeep;
242427  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
242428  assert( pIter->term.n<=pIter->term.nSpace );
242429  iOff += nNew;
242430  pIter->iTermLeafOffset = iOff;
242431  pIter->iTermLeafPgno = pIter->iLeafPgno;
242432  pIter->iLeafOffset = iOff;
242433
242434  if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
242435    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
242436  }else{
242437    int nExtra;
242438    pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
242439    pIter->iEndofDoclist += nExtra;
242440  }
242441
242442  fts5SegIterLoadRowid(p, pIter);
242443}
242444
242445static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
242446static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
242447static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
242448
242449static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
242450  if( pIter->flags & FTS5_SEGITER_REVERSE ){
242451    pIter->xNext = fts5SegIterNext_Reverse;
242452  }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
242453    pIter->xNext = fts5SegIterNext_None;
242454  }else{
242455    pIter->xNext = fts5SegIterNext;
242456  }
242457}
242458
242459/*
242460** Allocate a tombstone hash page array object (pIter->pTombArray) for
242461** the iterator passed as the second argument. If an OOM error occurs,
242462** leave an error in the Fts5Index object.
242463*/
242464static void fts5SegIterAllocTombstone(Fts5Index *p, Fts5SegIter *pIter){
242465  const int nTomb = pIter->pSeg->nPgTombstone;
242466  if( nTomb>0 ){
242467    int nByte = nTomb * sizeof(Fts5Data*) + sizeof(Fts5TombstoneArray);
242468    Fts5TombstoneArray *pNew;
242469    pNew = (Fts5TombstoneArray*)sqlite3Fts5MallocZero(&p->rc, nByte);
242470    if( pNew ){
242471      pNew->nTombstone = nTomb;
242472      pNew->nRef = 1;
242473      pIter->pTombArray = pNew;
242474    }
242475  }
242476}
242477
242478/*
242479** Initialize the iterator object pIter to iterate through the entries in
242480** segment pSeg. The iterator is left pointing to the first entry when
242481** this function returns.
242482**
242483** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
242484** an error has already occurred when this function is called, it is a no-op.
242485*/
242486static void fts5SegIterInit(
242487  Fts5Index *p,                   /* FTS index object */
242488  Fts5StructureSegment *pSeg,     /* Description of segment */
242489  Fts5SegIter *pIter              /* Object to populate */
242490){
242491  if( pSeg->pgnoFirst==0 ){
242492    /* This happens if the segment is being used as an input to an incremental
242493    ** merge and all data has already been "trimmed". See function
242494    ** fts5TrimSegments() for details. In this case leave the iterator empty.
242495    ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
242496    ** at EOF already. */
242497    assert( pIter->pLeaf==0 );
242498    return;
242499  }
242500
242501  if( p->rc==SQLITE_OK ){
242502    memset(pIter, 0, sizeof(*pIter));
242503    fts5SegIterSetNext(p, pIter);
242504    pIter->pSeg = pSeg;
242505    pIter->iLeafPgno = pSeg->pgnoFirst-1;
242506    do {
242507      fts5SegIterNextPage(p, pIter);
242508    }while( p->rc==SQLITE_OK && pIter->pLeaf && pIter->pLeaf->nn==4 );
242509  }
242510
242511  if( p->rc==SQLITE_OK && pIter->pLeaf ){
242512    pIter->iLeafOffset = 4;
242513    assert( pIter->pLeaf!=0 );
242514    assert_nc( pIter->pLeaf->nn>4 );
242515    assert_nc( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
242516    pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
242517    fts5SegIterLoadTerm(p, pIter, 0);
242518    fts5SegIterLoadNPos(p, pIter);
242519    fts5SegIterAllocTombstone(p, pIter);
242520  }
242521}
242522
242523/*
242524** This function is only ever called on iterators created by calls to
242525** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
242526**
242527** The iterator is in an unusual state when this function is called: the
242528** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
242529** the position-list size field for the first relevant rowid on the page.
242530** Fts5SegIter.rowid is set, but nPos and bDel are not.
242531**
242532** This function advances the iterator so that it points to the last
242533** relevant rowid on the page and, if necessary, initializes the
242534** aRowidOffset[] and iRowidOffset variables. At this point the iterator
242535** is in its regular state - Fts5SegIter.iLeafOffset points to the first
242536** byte of the position list content associated with said rowid.
242537*/
242538static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
242539  int eDetail = p->pConfig->eDetail;
242540  int n = pIter->pLeaf->szLeaf;
242541  int i = pIter->iLeafOffset;
242542  u8 *a = pIter->pLeaf->p;
242543  int iRowidOffset = 0;
242544
242545  if( n>pIter->iEndofDoclist ){
242546    n = pIter->iEndofDoclist;
242547  }
242548
242549  ASSERT_SZLEAF_OK(pIter->pLeaf);
242550  while( 1 ){
242551    u64 iDelta = 0;
242552
242553    if( eDetail==FTS5_DETAIL_NONE ){
242554      /* todo */
242555      if( i<n && a[i]==0 ){
242556        i++;
242557        if( i<n && a[i]==0 ) i++;
242558      }
242559    }else{
242560      int nPos;
242561      int bDummy;
242562      i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
242563      i += nPos;
242564    }
242565    if( i>=n ) break;
242566    i += fts5GetVarint(&a[i], &iDelta);
242567    pIter->iRowid += iDelta;
242568
242569    /* If necessary, grow the pIter->aRowidOffset[] array. */
242570    if( iRowidOffset>=pIter->nRowidOffset ){
242571      int nNew = pIter->nRowidOffset + 8;
242572      int *aNew = (int*)sqlite3_realloc64(pIter->aRowidOffset,nNew*sizeof(int));
242573      if( aNew==0 ){
242574        p->rc = SQLITE_NOMEM;
242575        break;
242576      }
242577      pIter->aRowidOffset = aNew;
242578      pIter->nRowidOffset = nNew;
242579    }
242580
242581    pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
242582    pIter->iLeafOffset = i;
242583  }
242584  pIter->iRowidOffset = iRowidOffset;
242585  fts5SegIterLoadNPos(p, pIter);
242586}
242587
242588/*
242589**
242590*/
242591static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
242592  assert( pIter->flags & FTS5_SEGITER_REVERSE );
242593  assert( pIter->flags & FTS5_SEGITER_ONETERM );
242594
242595  fts5DataRelease(pIter->pLeaf);
242596  pIter->pLeaf = 0;
242597  while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
242598    Fts5Data *pNew;
242599    pIter->iLeafPgno--;
242600    pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
242601          pIter->pSeg->iSegid, pIter->iLeafPgno
242602    ));
242603    if( pNew ){
242604      /* iTermLeafOffset may be equal to szLeaf if the term is the last
242605      ** thing on the page - i.e. the first rowid is on the following page.
242606      ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
242607      if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
242608        assert( pIter->pLeaf==0 );
242609        if( pIter->iTermLeafOffset<pNew->szLeaf ){
242610          pIter->pLeaf = pNew;
242611          pIter->iLeafOffset = pIter->iTermLeafOffset;
242612        }
242613      }else{
242614        int iRowidOff;
242615        iRowidOff = fts5LeafFirstRowidOff(pNew);
242616        if( iRowidOff ){
242617          if( iRowidOff>=pNew->szLeaf ){
242618            p->rc = FTS5_CORRUPT;
242619          }else{
242620            pIter->pLeaf = pNew;
242621            pIter->iLeafOffset = iRowidOff;
242622          }
242623        }
242624      }
242625
242626      if( pIter->pLeaf ){
242627        u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
242628        pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
242629        break;
242630      }else{
242631        fts5DataRelease(pNew);
242632      }
242633    }
242634  }
242635
242636  if( pIter->pLeaf ){
242637    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
242638    fts5SegIterReverseInitPage(p, pIter);
242639  }
242640}
242641
242642/*
242643** Return true if the iterator passed as the second argument currently
242644** points to a delete marker. A delete marker is an entry with a 0 byte
242645** position-list.
242646*/
242647static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
242648  Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
242649  return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
242650}
242651
242652/*
242653** Advance iterator pIter to the next entry.
242654**
242655** This version of fts5SegIterNext() is only used by reverse iterators.
242656*/
242657static void fts5SegIterNext_Reverse(
242658  Fts5Index *p,                   /* FTS5 backend object */
242659  Fts5SegIter *pIter,             /* Iterator to advance */
242660  int *pbUnused                   /* Unused */
242661){
242662  assert( pIter->flags & FTS5_SEGITER_REVERSE );
242663  assert( pIter->pNextLeaf==0 );
242664  UNUSED_PARAM(pbUnused);
242665
242666  if( pIter->iRowidOffset>0 ){
242667    u8 *a = pIter->pLeaf->p;
242668    int iOff;
242669    u64 iDelta;
242670
242671    pIter->iRowidOffset--;
242672    pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
242673    fts5SegIterLoadNPos(p, pIter);
242674    iOff = pIter->iLeafOffset;
242675    if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
242676      iOff += pIter->nPos;
242677    }
242678    fts5GetVarint(&a[iOff], &iDelta);
242679    pIter->iRowid -= iDelta;
242680  }else{
242681    fts5SegIterReverseNewPage(p, pIter);
242682  }
242683}
242684
242685/*
242686** Advance iterator pIter to the next entry.
242687**
242688** This version of fts5SegIterNext() is only used if detail=none and the
242689** iterator is not a reverse direction iterator.
242690*/
242691static void fts5SegIterNext_None(
242692  Fts5Index *p,                   /* FTS5 backend object */
242693  Fts5SegIter *pIter,             /* Iterator to advance */
242694  int *pbNewTerm                  /* OUT: Set for new term */
242695){
242696  int iOff;
242697
242698  assert( p->rc==SQLITE_OK );
242699  assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
242700  assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
242701
242702  ASSERT_SZLEAF_OK(pIter->pLeaf);
242703  iOff = pIter->iLeafOffset;
242704
242705  /* Next entry is on the next page */
242706  while( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
242707    fts5SegIterNextPage(p, pIter);
242708    if( p->rc || pIter->pLeaf==0 ) return;
242709    pIter->iRowid = 0;
242710    iOff = 4;
242711  }
242712
242713  if( iOff<pIter->iEndofDoclist ){
242714    /* Next entry is on the current page */
242715    i64 iDelta;
242716    iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
242717    pIter->iLeafOffset = iOff;
242718    pIter->iRowid += iDelta;
242719  }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
242720    if( pIter->pSeg ){
242721      int nKeep = 0;
242722      if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
242723        iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
242724      }
242725      pIter->iLeafOffset = iOff;
242726      fts5SegIterLoadTerm(p, pIter, nKeep);
242727    }else{
242728      const u8 *pList = 0;
242729      const char *zTerm = 0;
242730      int nTerm = 0;
242731      int nList;
242732      sqlite3Fts5HashScanNext(p->pHash);
242733      sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &nTerm, &pList, &nList);
242734      if( pList==0 ) goto next_none_eof;
242735      pIter->pLeaf->p = (u8*)pList;
242736      pIter->pLeaf->nn = nList;
242737      pIter->pLeaf->szLeaf = nList;
242738      pIter->iEndofDoclist = nList;
242739      sqlite3Fts5BufferSet(&p->rc,&pIter->term, nTerm, (u8*)zTerm);
242740      pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
242741    }
242742
242743    if( pbNewTerm ) *pbNewTerm = 1;
242744  }else{
242745    goto next_none_eof;
242746  }
242747
242748  fts5SegIterLoadNPos(p, pIter);
242749
242750  return;
242751 next_none_eof:
242752  fts5DataRelease(pIter->pLeaf);
242753  pIter->pLeaf = 0;
242754}
242755
242756
242757/*
242758** Advance iterator pIter to the next entry.
242759**
242760** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
242761** is not considered an error if the iterator reaches EOF. If an error has
242762** already occurred when this function is called, it is a no-op.
242763*/
242764static void fts5SegIterNext(
242765  Fts5Index *p,                   /* FTS5 backend object */
242766  Fts5SegIter *pIter,             /* Iterator to advance */
242767  int *pbNewTerm                  /* OUT: Set for new term */
242768){
242769  Fts5Data *pLeaf = pIter->pLeaf;
242770  int iOff;
242771  int bNewTerm = 0;
242772  int nKeep = 0;
242773  u8 *a;
242774  int n;
242775
242776  assert( pbNewTerm==0 || *pbNewTerm==0 );
242777  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
242778
242779  /* Search for the end of the position list within the current page. */
242780  a = pLeaf->p;
242781  n = pLeaf->szLeaf;
242782
242783  ASSERT_SZLEAF_OK(pLeaf);
242784  iOff = pIter->iLeafOffset + pIter->nPos;
242785
242786  if( iOff<n ){
242787    /* The next entry is on the current page. */
242788    assert_nc( iOff<=pIter->iEndofDoclist );
242789    if( iOff>=pIter->iEndofDoclist ){
242790      bNewTerm = 1;
242791      if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
242792        iOff += fts5GetVarint32(&a[iOff], nKeep);
242793      }
242794    }else{
242795      u64 iDelta;
242796      iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
242797      pIter->iRowid += iDelta;
242798      assert_nc( iDelta>0 );
242799    }
242800    pIter->iLeafOffset = iOff;
242801
242802  }else if( pIter->pSeg==0 ){
242803    const u8 *pList = 0;
242804    const char *zTerm = 0;
242805    int nTerm = 0;
242806    int nList = 0;
242807    assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
242808    if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
242809      sqlite3Fts5HashScanNext(p->pHash);
242810      sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &nTerm, &pList, &nList);
242811    }
242812    if( pList==0 ){
242813      fts5DataRelease(pIter->pLeaf);
242814      pIter->pLeaf = 0;
242815    }else{
242816      pIter->pLeaf->p = (u8*)pList;
242817      pIter->pLeaf->nn = nList;
242818      pIter->pLeaf->szLeaf = nList;
242819      pIter->iEndofDoclist = nList+1;
242820      sqlite3Fts5BufferSet(&p->rc, &pIter->term, nTerm, (u8*)zTerm);
242821      pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
242822      *pbNewTerm = 1;
242823    }
242824  }else{
242825    iOff = 0;
242826    /* Next entry is not on the current page */
242827    while( iOff==0 ){
242828      fts5SegIterNextPage(p, pIter);
242829      pLeaf = pIter->pLeaf;
242830      if( pLeaf==0 ) break;
242831      ASSERT_SZLEAF_OK(pLeaf);
242832      if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
242833        iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
242834        pIter->iLeafOffset = iOff;
242835
242836        if( pLeaf->nn>pLeaf->szLeaf ){
242837          pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
242838              &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
242839          );
242840        }
242841      }
242842      else if( pLeaf->nn>pLeaf->szLeaf ){
242843        pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
242844            &pLeaf->p[pLeaf->szLeaf], iOff
242845        );
242846        pIter->iLeafOffset = iOff;
242847        pIter->iEndofDoclist = iOff;
242848        bNewTerm = 1;
242849      }
242850      assert_nc( iOff<pLeaf->szLeaf );
242851      if( iOff>pLeaf->szLeaf ){
242852        p->rc = FTS5_CORRUPT;
242853        return;
242854      }
242855    }
242856  }
242857
242858  /* Check if the iterator is now at EOF. If so, return early. */
242859  if( pIter->pLeaf ){
242860    if( bNewTerm ){
242861      if( pIter->flags & FTS5_SEGITER_ONETERM ){
242862        fts5DataRelease(pIter->pLeaf);
242863        pIter->pLeaf = 0;
242864      }else{
242865        fts5SegIterLoadTerm(p, pIter, nKeep);
242866        fts5SegIterLoadNPos(p, pIter);
242867        if( pbNewTerm ) *pbNewTerm = 1;
242868      }
242869    }else{
242870      /* The following could be done by calling fts5SegIterLoadNPos(). But
242871      ** this block is particularly performance critical, so equivalent
242872      ** code is inlined.  */
242873      int nSz;
242874      assert_nc( pIter->iLeafOffset<=pIter->pLeaf->nn );
242875      fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
242876      pIter->bDel = (nSz & 0x0001);
242877      pIter->nPos = nSz>>1;
242878      assert_nc( pIter->nPos>=0 );
242879    }
242880  }
242881}
242882
242883#define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
242884
242885#define fts5IndexSkipVarint(a, iOff) {            \
242886  int iEnd = iOff+9;                              \
242887  while( (a[iOff++] & 0x80) && iOff<iEnd );       \
242888}
242889
242890/*
242891** Iterator pIter currently points to the first rowid in a doclist. This
242892** function sets the iterator up so that iterates in reverse order through
242893** the doclist.
242894*/
242895static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
242896  Fts5DlidxIter *pDlidx = pIter->pDlidx;
242897  Fts5Data *pLast = 0;
242898  int pgnoLast = 0;
242899
242900  if( pDlidx && p->pConfig->iVersion==FTS5_CURRENT_VERSION ){
242901    int iSegid = pIter->pSeg->iSegid;
242902    pgnoLast = fts5DlidxIterPgno(pDlidx);
242903    pLast = fts5LeafRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
242904  }else{
242905    Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */
242906
242907    /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
242908    ** position-list content for the current rowid. Back it up so that it
242909    ** points to the start of the position-list size field. */
242910    int iPoslist;
242911    if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
242912      iPoslist = pIter->iTermLeafOffset;
242913    }else{
242914      iPoslist = 4;
242915    }
242916    fts5IndexSkipVarint(pLeaf->p, iPoslist);
242917    pIter->iLeafOffset = iPoslist;
242918
242919    /* If this condition is true then the largest rowid for the current
242920    ** term may not be stored on the current page. So search forward to
242921    ** see where said rowid really is.  */
242922    if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
242923      int pgno;
242924      Fts5StructureSegment *pSeg = pIter->pSeg;
242925
242926      /* The last rowid in the doclist may not be on the current page. Search
242927      ** forward to find the page containing the last rowid.  */
242928      for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
242929        i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
242930        Fts5Data *pNew = fts5LeafRead(p, iAbs);
242931        if( pNew ){
242932          int iRowid, bTermless;
242933          iRowid = fts5LeafFirstRowidOff(pNew);
242934          bTermless = fts5LeafIsTermless(pNew);
242935          if( iRowid ){
242936            SWAPVAL(Fts5Data*, pNew, pLast);
242937            pgnoLast = pgno;
242938          }
242939          fts5DataRelease(pNew);
242940          if( bTermless==0 ) break;
242941        }
242942      }
242943    }
242944  }
242945
242946  /* If pLast is NULL at this point, then the last rowid for this doclist
242947  ** lies on the page currently indicated by the iterator. In this case
242948  ** pIter->iLeafOffset is already set to point to the position-list size
242949  ** field associated with the first relevant rowid on the page.
242950  **
242951  ** Or, if pLast is non-NULL, then it is the page that contains the last
242952  ** rowid. In this case configure the iterator so that it points to the
242953  ** first rowid on this page.
242954  */
242955  if( pLast ){
242956    int iOff;
242957    fts5DataRelease(pIter->pLeaf);
242958    pIter->pLeaf = pLast;
242959    pIter->iLeafPgno = pgnoLast;
242960    iOff = fts5LeafFirstRowidOff(pLast);
242961    if( iOff>pLast->szLeaf ){
242962      p->rc = FTS5_CORRUPT;
242963      return;
242964    }
242965    iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
242966    pIter->iLeafOffset = iOff;
242967
242968    if( fts5LeafIsTermless(pLast) ){
242969      pIter->iEndofDoclist = pLast->nn+1;
242970    }else{
242971      pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
242972    }
242973  }
242974
242975  fts5SegIterReverseInitPage(p, pIter);
242976}
242977
242978/*
242979** Iterator pIter currently points to the first rowid of a doclist.
242980** There is a doclist-index associated with the final term on the current
242981** page. If the current term is the last term on the page, load the
242982** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
242983*/
242984static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
242985  int iSeg = pIter->pSeg->iSegid;
242986  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
242987  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
242988
242989  assert( pIter->flags & FTS5_SEGITER_ONETERM );
242990  assert( pIter->pDlidx==0 );
242991
242992  /* Check if the current doclist ends on this page. If it does, return
242993  ** early without loading the doclist-index (as it belongs to a different
242994  ** term. */
242995  if( pIter->iTermLeafPgno==pIter->iLeafPgno
242996   && pIter->iEndofDoclist<pLeaf->szLeaf
242997  ){
242998    return;
242999  }
243000
243001  pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
243002}
243003
243004/*
243005** The iterator object passed as the second argument currently contains
243006** no valid values except for the Fts5SegIter.pLeaf member variable. This
243007** function searches the leaf page for a term matching (pTerm/nTerm).
243008**
243009** If the specified term is found on the page, then the iterator is left
243010** pointing to it. If argument bGe is zero and the term is not found,
243011** the iterator is left pointing at EOF.
243012**
243013** If bGe is non-zero and the specified term is not found, then the
243014** iterator is left pointing to the smallest term in the segment that
243015** is larger than the specified term, even if this term is not on the
243016** current page.
243017*/
243018static void fts5LeafSeek(
243019  Fts5Index *p,                   /* Leave any error code here */
243020  int bGe,                        /* True for a >= search */
243021  Fts5SegIter *pIter,             /* Iterator to seek */
243022  const u8 *pTerm, int nTerm      /* Term to search for */
243023){
243024  u32 iOff;
243025  const u8 *a = pIter->pLeaf->p;
243026  u32 n = (u32)pIter->pLeaf->nn;
243027
243028  u32 nMatch = 0;
243029  u32 nKeep = 0;
243030  u32 nNew = 0;
243031  u32 iTermOff;
243032  u32 iPgidx;                     /* Current offset in pgidx */
243033  int bEndOfPage = 0;
243034
243035  assert( p->rc==SQLITE_OK );
243036
243037  iPgidx = (u32)pIter->pLeaf->szLeaf;
243038  iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
243039  iOff = iTermOff;
243040  if( iOff>n ){
243041    p->rc = FTS5_CORRUPT;
243042    return;
243043  }
243044
243045  while( 1 ){
243046
243047    /* Figure out how many new bytes are in this term */
243048    fts5FastGetVarint32(a, iOff, nNew);
243049    if( nKeep<nMatch ){
243050      goto search_failed;
243051    }
243052
243053    assert( nKeep>=nMatch );
243054    if( nKeep==nMatch ){
243055      u32 nCmp;
243056      u32 i;
243057      nCmp = (u32)MIN(nNew, nTerm-nMatch);
243058      for(i=0; i<nCmp; i++){
243059        if( a[iOff+i]!=pTerm[nMatch+i] ) break;
243060      }
243061      nMatch += i;
243062
243063      if( (u32)nTerm==nMatch ){
243064        if( i==nNew ){
243065          goto search_success;
243066        }else{
243067          goto search_failed;
243068        }
243069      }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
243070        goto search_failed;
243071      }
243072    }
243073
243074    if( iPgidx>=n ){
243075      bEndOfPage = 1;
243076      break;
243077    }
243078
243079    iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
243080    iTermOff += nKeep;
243081    iOff = iTermOff;
243082
243083    if( iOff>=n ){
243084      p->rc = FTS5_CORRUPT;
243085      return;
243086    }
243087
243088    /* Read the nKeep field of the next term. */
243089    fts5FastGetVarint32(a, iOff, nKeep);
243090  }
243091
243092 search_failed:
243093  if( bGe==0 ){
243094    fts5DataRelease(pIter->pLeaf);
243095    pIter->pLeaf = 0;
243096    return;
243097  }else if( bEndOfPage ){
243098    do {
243099      fts5SegIterNextPage(p, pIter);
243100      if( pIter->pLeaf==0 ) return;
243101      a = pIter->pLeaf->p;
243102      if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
243103        iPgidx = (u32)pIter->pLeaf->szLeaf;
243104        iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
243105        if( iOff<4 || (i64)iOff>=pIter->pLeaf->szLeaf ){
243106          p->rc = FTS5_CORRUPT;
243107          return;
243108        }else{
243109          nKeep = 0;
243110          iTermOff = iOff;
243111          n = (u32)pIter->pLeaf->nn;
243112          iOff += fts5GetVarint32(&a[iOff], nNew);
243113          break;
243114        }
243115      }
243116    }while( 1 );
243117  }
243118
243119 search_success:
243120  if( (i64)iOff+nNew>n || nNew<1 ){
243121    p->rc = FTS5_CORRUPT;
243122    return;
243123  }
243124  pIter->iLeafOffset = iOff + nNew;
243125  pIter->iTermLeafOffset = pIter->iLeafOffset;
243126  pIter->iTermLeafPgno = pIter->iLeafPgno;
243127
243128  fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
243129  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
243130
243131  if( iPgidx>=n ){
243132    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
243133  }else{
243134    int nExtra;
243135    iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
243136    pIter->iEndofDoclist = iTermOff + nExtra;
243137  }
243138  pIter->iPgidxOff = iPgidx;
243139
243140  fts5SegIterLoadRowid(p, pIter);
243141  fts5SegIterLoadNPos(p, pIter);
243142}
243143
243144static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
243145  if( p->pIdxSelect==0 ){
243146    Fts5Config *pConfig = p->pConfig;
243147    fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
243148          "SELECT pgno FROM '%q'.'%q_idx' WHERE "
243149          "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
243150          pConfig->zDb, pConfig->zName
243151    ));
243152  }
243153  return p->pIdxSelect;
243154}
243155
243156/*
243157** Initialize the object pIter to point to term pTerm/nTerm within segment
243158** pSeg. If there is no such term in the index, the iterator is set to EOF.
243159**
243160** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
243161** an error has already occurred when this function is called, it is a no-op.
243162*/
243163static void fts5SegIterSeekInit(
243164  Fts5Index *p,                   /* FTS5 backend */
243165  const u8 *pTerm, int nTerm,     /* Term to seek to */
243166  int flags,                      /* Mask of FTS5INDEX_XXX flags */
243167  Fts5StructureSegment *pSeg,     /* Description of segment */
243168  Fts5SegIter *pIter              /* Object to populate */
243169){
243170  int iPg = 1;
243171  int bGe = (flags & FTS5INDEX_QUERY_SCAN);
243172  int bDlidx = 0;                 /* True if there is a doclist-index */
243173  sqlite3_stmt *pIdxSelect = 0;
243174
243175  assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
243176  assert( pTerm && nTerm );
243177  memset(pIter, 0, sizeof(*pIter));
243178  pIter->pSeg = pSeg;
243179
243180  /* This block sets stack variable iPg to the leaf page number that may
243181  ** contain term (pTerm/nTerm), if it is present in the segment. */
243182  pIdxSelect = fts5IdxSelectStmt(p);
243183  if( p->rc ) return;
243184  sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
243185  sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
243186  if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
243187    i64 val = sqlite3_column_int(pIdxSelect, 0);
243188    iPg = (int)(val>>1);
243189    bDlidx = (val & 0x0001);
243190  }
243191  p->rc = sqlite3_reset(pIdxSelect);
243192  sqlite3_bind_null(pIdxSelect, 2);
243193
243194  if( iPg<pSeg->pgnoFirst ){
243195    iPg = pSeg->pgnoFirst;
243196    bDlidx = 0;
243197  }
243198
243199  pIter->iLeafPgno = iPg - 1;
243200  fts5SegIterNextPage(p, pIter);
243201
243202  if( pIter->pLeaf ){
243203    fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
243204  }
243205
243206  if( p->rc==SQLITE_OK && (bGe==0 || (flags & FTS5INDEX_QUERY_SCANONETERM)) ){
243207    pIter->flags |= FTS5_SEGITER_ONETERM;
243208    if( pIter->pLeaf ){
243209      if( flags & FTS5INDEX_QUERY_DESC ){
243210        pIter->flags |= FTS5_SEGITER_REVERSE;
243211      }
243212      if( bDlidx ){
243213        fts5SegIterLoadDlidx(p, pIter);
243214      }
243215      if( flags & FTS5INDEX_QUERY_DESC ){
243216        fts5SegIterReverse(p, pIter);
243217      }
243218    }
243219  }
243220
243221  fts5SegIterSetNext(p, pIter);
243222  if( 0==(flags & FTS5INDEX_QUERY_SCANONETERM) ){
243223    fts5SegIterAllocTombstone(p, pIter);
243224  }
243225
243226  /* Either:
243227  **
243228  **   1) an error has occurred, or
243229  **   2) the iterator points to EOF, or
243230  **   3) the iterator points to an entry with term (pTerm/nTerm), or
243231  **   4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
243232  **      to an entry with a term greater than or equal to (pTerm/nTerm).
243233  */
243234  assert_nc( p->rc!=SQLITE_OK                                       /* 1 */
243235   || pIter->pLeaf==0                                               /* 2 */
243236   || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0          /* 3 */
243237   || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0)  /* 4 */
243238  );
243239}
243240
243241
243242/*
243243** SQL used by fts5SegIterNextInit() to find the page to open.
243244*/
243245static sqlite3_stmt *fts5IdxNextStmt(Fts5Index *p){
243246  if( p->pIdxNextSelect==0 ){
243247    Fts5Config *pConfig = p->pConfig;
243248    fts5IndexPrepareStmt(p, &p->pIdxNextSelect, sqlite3_mprintf(
243249          "SELECT pgno FROM '%q'.'%q_idx' WHERE "
243250          "segid=? AND term>? ORDER BY term ASC LIMIT 1",
243251          pConfig->zDb, pConfig->zName
243252    ));
243253
243254  }
243255  return p->pIdxNextSelect;
243256}
243257
243258/*
243259** This is similar to fts5SegIterSeekInit(), except that it initializes
243260** the segment iterator to point to the first term following the page
243261** with pToken/nToken on it.
243262*/
243263static void fts5SegIterNextInit(
243264  Fts5Index *p,
243265  const char *pTerm, int nTerm,
243266  Fts5StructureSegment *pSeg,     /* Description of segment */
243267  Fts5SegIter *pIter              /* Object to populate */
243268){
243269  int iPg = -1;                   /* Page of segment to open */
243270  int bDlidx = 0;
243271  sqlite3_stmt *pSel = 0;         /* SELECT to find iPg */
243272
243273  pSel = fts5IdxNextStmt(p);
243274  if( pSel ){
243275    assert( p->rc==SQLITE_OK );
243276    sqlite3_bind_int(pSel, 1, pSeg->iSegid);
243277    sqlite3_bind_blob(pSel, 2, pTerm, nTerm, SQLITE_STATIC);
243278
243279    if( sqlite3_step(pSel)==SQLITE_ROW ){
243280      i64 val = sqlite3_column_int64(pSel, 0);
243281      iPg = (int)(val>>1);
243282      bDlidx = (val & 0x0001);
243283    }
243284    p->rc = sqlite3_reset(pSel);
243285    sqlite3_bind_null(pSel, 2);
243286    if( p->rc ) return;
243287  }
243288
243289  memset(pIter, 0, sizeof(*pIter));
243290  pIter->pSeg = pSeg;
243291  pIter->flags |= FTS5_SEGITER_ONETERM;
243292  if( iPg>=0 ){
243293    pIter->iLeafPgno = iPg - 1;
243294    fts5SegIterNextPage(p, pIter);
243295    fts5SegIterSetNext(p, pIter);
243296  }
243297  if( pIter->pLeaf ){
243298    const u8 *a = pIter->pLeaf->p;
243299    int iTermOff = 0;
243300
243301    pIter->iPgidxOff = pIter->pLeaf->szLeaf;
243302    pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], iTermOff);
243303    pIter->iLeafOffset = iTermOff;
243304    fts5SegIterLoadTerm(p, pIter, 0);
243305    fts5SegIterLoadNPos(p, pIter);
243306    if( bDlidx ) fts5SegIterLoadDlidx(p, pIter);
243307
243308    assert( p->rc!=SQLITE_OK ||
243309        fts5BufferCompareBlob(&pIter->term, (const u8*)pTerm, nTerm)>0
243310    );
243311  }
243312}
243313
243314/*
243315** Initialize the object pIter to point to term pTerm/nTerm within the
243316** in-memory hash table. If there is no such term in the hash-table, the
243317** iterator is set to EOF.
243318**
243319** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
243320** an error has already occurred when this function is called, it is a no-op.
243321*/
243322static void fts5SegIterHashInit(
243323  Fts5Index *p,                   /* FTS5 backend */
243324  const u8 *pTerm, int nTerm,     /* Term to seek to */
243325  int flags,                      /* Mask of FTS5INDEX_XXX flags */
243326  Fts5SegIter *pIter              /* Object to populate */
243327){
243328  int nList = 0;
243329  const u8 *z = 0;
243330  int n = 0;
243331  Fts5Data *pLeaf = 0;
243332
243333  assert( p->pHash );
243334  assert( p->rc==SQLITE_OK );
243335
243336  if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
243337    const u8 *pList = 0;
243338
243339    p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
243340    sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &n, &pList, &nList);
243341    if( pList ){
243342      pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
243343      if( pLeaf ){
243344        pLeaf->p = (u8*)pList;
243345      }
243346    }
243347
243348    /* The call to sqlite3Fts5HashScanInit() causes the hash table to
243349    ** fill the size field of all existing position lists. This means they
243350    ** can no longer be appended to. Since the only scenario in which they
243351    ** can be appended to is if the previous operation on this table was
243352    ** a DELETE, by clearing the Fts5Index.bDelete flag we can avoid this
243353    ** possibility altogether.  */
243354    p->bDelete = 0;
243355  }else{
243356    p->rc = sqlite3Fts5HashQuery(p->pHash, sizeof(Fts5Data),
243357        (const char*)pTerm, nTerm, (void**)&pLeaf, &nList
243358    );
243359    if( pLeaf ){
243360      pLeaf->p = (u8*)&pLeaf[1];
243361    }
243362    z = pTerm;
243363    n = nTerm;
243364    pIter->flags |= FTS5_SEGITER_ONETERM;
243365  }
243366
243367  if( pLeaf ){
243368    sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
243369    pLeaf->nn = pLeaf->szLeaf = nList;
243370    pIter->pLeaf = pLeaf;
243371    pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
243372    pIter->iEndofDoclist = pLeaf->nn;
243373
243374    if( flags & FTS5INDEX_QUERY_DESC ){
243375      pIter->flags |= FTS5_SEGITER_REVERSE;
243376      fts5SegIterReverseInitPage(p, pIter);
243377    }else{
243378      fts5SegIterLoadNPos(p, pIter);
243379    }
243380  }
243381
243382  fts5SegIterSetNext(p, pIter);
243383}
243384
243385/*
243386** Array ap[] contains n elements. Release each of these elements using
243387** fts5DataRelease(). Then free the array itself using sqlite3_free().
243388*/
243389static void fts5IndexFreeArray(Fts5Data **ap, int n){
243390  if( ap ){
243391    int ii;
243392    for(ii=0; ii<n; ii++){
243393      fts5DataRelease(ap[ii]);
243394    }
243395    sqlite3_free(ap);
243396  }
243397}
243398
243399/*
243400** Decrement the ref-count of the object passed as the only argument. If it
243401** reaches 0, free it and its contents.
243402*/
243403static void fts5TombstoneArrayDelete(Fts5TombstoneArray *p){
243404  if( p ){
243405    p->nRef--;
243406    if( p->nRef<=0 ){
243407      int ii;
243408      for(ii=0; ii<p->nTombstone; ii++){
243409        fts5DataRelease(p->apTombstone[ii]);
243410      }
243411      sqlite3_free(p);
243412    }
243413  }
243414}
243415
243416/*
243417** Zero the iterator passed as the only argument.
243418*/
243419static void fts5SegIterClear(Fts5SegIter *pIter){
243420  fts5BufferFree(&pIter->term);
243421  fts5DataRelease(pIter->pLeaf);
243422  fts5DataRelease(pIter->pNextLeaf);
243423  fts5TombstoneArrayDelete(pIter->pTombArray);
243424  fts5DlidxIterFree(pIter->pDlidx);
243425  sqlite3_free(pIter->aRowidOffset);
243426  memset(pIter, 0, sizeof(Fts5SegIter));
243427}
243428
243429#ifdef SQLITE_DEBUG
243430
243431/*
243432** This function is used as part of the big assert() procedure implemented by
243433** fts5AssertMultiIterSetup(). It ensures that the result currently stored
243434** in *pRes is the correct result of comparing the current positions of the
243435** two iterators.
243436*/
243437static void fts5AssertComparisonResult(
243438  Fts5Iter *pIter,
243439  Fts5SegIter *p1,
243440  Fts5SegIter *p2,
243441  Fts5CResult *pRes
243442){
243443  int i1 = p1 - pIter->aSeg;
243444  int i2 = p2 - pIter->aSeg;
243445
243446  if( p1->pLeaf || p2->pLeaf ){
243447    if( p1->pLeaf==0 ){
243448      assert( pRes->iFirst==i2 );
243449    }else if( p2->pLeaf==0 ){
243450      assert( pRes->iFirst==i1 );
243451    }else{
243452      int nMin = MIN(p1->term.n, p2->term.n);
243453      int res = fts5Memcmp(p1->term.p, p2->term.p, nMin);
243454      if( res==0 ) res = p1->term.n - p2->term.n;
243455
243456      if( res==0 ){
243457        assert( pRes->bTermEq==1 );
243458        assert( p1->iRowid!=p2->iRowid );
243459        res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
243460      }else{
243461        assert( pRes->bTermEq==0 );
243462      }
243463
243464      if( res<0 ){
243465        assert( pRes->iFirst==i1 );
243466      }else{
243467        assert( pRes->iFirst==i2 );
243468      }
243469    }
243470  }
243471}
243472
243473/*
243474** This function is a no-op unless SQLITE_DEBUG is defined when this module
243475** is compiled. In that case, this function is essentially an assert()
243476** statement used to verify that the contents of the pIter->aFirst[] array
243477** are correct.
243478*/
243479static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
243480  if( p->rc==SQLITE_OK ){
243481    Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
243482    int i;
243483
243484    assert( (pFirst->pLeaf==0)==pIter->base.bEof );
243485
243486    /* Check that pIter->iSwitchRowid is set correctly. */
243487    for(i=0; i<pIter->nSeg; i++){
243488      Fts5SegIter *p1 = &pIter->aSeg[i];
243489      assert( p1==pFirst
243490           || p1->pLeaf==0
243491           || fts5BufferCompare(&pFirst->term, &p1->term)
243492           || p1->iRowid==pIter->iSwitchRowid
243493           || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
243494      );
243495    }
243496
243497    for(i=0; i<pIter->nSeg; i+=2){
243498      Fts5SegIter *p1 = &pIter->aSeg[i];
243499      Fts5SegIter *p2 = &pIter->aSeg[i+1];
243500      Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
243501      fts5AssertComparisonResult(pIter, p1, p2, pRes);
243502    }
243503
243504    for(i=1; i<(pIter->nSeg / 2); i+=2){
243505      Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
243506      Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
243507      Fts5CResult *pRes = &pIter->aFirst[i];
243508      fts5AssertComparisonResult(pIter, p1, p2, pRes);
243509    }
243510  }
243511}
243512#else
243513# define fts5AssertMultiIterSetup(x,y)
243514#endif
243515
243516/*
243517** Do the comparison necessary to populate pIter->aFirst[iOut].
243518**
243519** If the returned value is non-zero, then it is the index of an entry
243520** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
243521** to a key that is a duplicate of another, higher priority,
243522** segment-iterator in the pSeg->aSeg[] array.
243523*/
243524static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
243525  int i1;                         /* Index of left-hand Fts5SegIter */
243526  int i2;                         /* Index of right-hand Fts5SegIter */
243527  int iRes;
243528  Fts5SegIter *p1;                /* Left-hand Fts5SegIter */
243529  Fts5SegIter *p2;                /* Right-hand Fts5SegIter */
243530  Fts5CResult *pRes = &pIter->aFirst[iOut];
243531
243532  assert( iOut<pIter->nSeg && iOut>0 );
243533  assert( pIter->bRev==0 || pIter->bRev==1 );
243534
243535  if( iOut>=(pIter->nSeg/2) ){
243536    i1 = (iOut - pIter->nSeg/2) * 2;
243537    i2 = i1 + 1;
243538  }else{
243539    i1 = pIter->aFirst[iOut*2].iFirst;
243540    i2 = pIter->aFirst[iOut*2+1].iFirst;
243541  }
243542  p1 = &pIter->aSeg[i1];
243543  p2 = &pIter->aSeg[i2];
243544
243545  pRes->bTermEq = 0;
243546  if( p1->pLeaf==0 ){           /* If p1 is at EOF */
243547    iRes = i2;
243548  }else if( p2->pLeaf==0 ){     /* If p2 is at EOF */
243549    iRes = i1;
243550  }else{
243551    int res = fts5BufferCompare(&p1->term, &p2->term);
243552    if( res==0 ){
243553      assert_nc( i2>i1 );
243554      assert_nc( i2!=0 );
243555      pRes->bTermEq = 1;
243556      if( p1->iRowid==p2->iRowid ){
243557        return i2;
243558      }
243559      res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
243560    }
243561    assert( res!=0 );
243562    if( res<0 ){
243563      iRes = i1;
243564    }else{
243565      iRes = i2;
243566    }
243567  }
243568
243569  pRes->iFirst = (u16)iRes;
243570  return 0;
243571}
243572
243573/*
243574** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
243575** It is an error if leaf iLeafPgno does not exist. Unless the db is
243576** a 'secure-delete' db, if it contains no rowids then this is also an error.
243577*/
243578static void fts5SegIterGotoPage(
243579  Fts5Index *p,                   /* FTS5 backend object */
243580  Fts5SegIter *pIter,             /* Iterator to advance */
243581  int iLeafPgno
243582){
243583  assert( iLeafPgno>pIter->iLeafPgno );
243584
243585  if( iLeafPgno>pIter->pSeg->pgnoLast ){
243586    p->rc = FTS5_CORRUPT;
243587  }else{
243588    fts5DataRelease(pIter->pNextLeaf);
243589    pIter->pNextLeaf = 0;
243590    pIter->iLeafPgno = iLeafPgno-1;
243591
243592    while( p->rc==SQLITE_OK ){
243593      int iOff;
243594      fts5SegIterNextPage(p, pIter);
243595      if( pIter->pLeaf==0 ) break;
243596      iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
243597      if( iOff>0 ){
243598        u8 *a = pIter->pLeaf->p;
243599        int n = pIter->pLeaf->szLeaf;
243600        if( iOff<4 || iOff>=n ){
243601          p->rc = FTS5_CORRUPT;
243602        }else{
243603          iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
243604          pIter->iLeafOffset = iOff;
243605          fts5SegIterLoadNPos(p, pIter);
243606        }
243607        break;
243608      }
243609    }
243610  }
243611}
243612
243613/*
243614** Advance the iterator passed as the second argument until it is at or
243615** past rowid iFrom. Regardless of the value of iFrom, the iterator is
243616** always advanced at least once.
243617*/
243618static void fts5SegIterNextFrom(
243619  Fts5Index *p,                   /* FTS5 backend object */
243620  Fts5SegIter *pIter,             /* Iterator to advance */
243621  i64 iMatch                      /* Advance iterator at least this far */
243622){
243623  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
243624  Fts5DlidxIter *pDlidx = pIter->pDlidx;
243625  int iLeafPgno = pIter->iLeafPgno;
243626  int bMove = 1;
243627
243628  assert( pIter->flags & FTS5_SEGITER_ONETERM );
243629  assert( pIter->pDlidx );
243630  assert( pIter->pLeaf );
243631
243632  if( bRev==0 ){
243633    while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
243634      iLeafPgno = fts5DlidxIterPgno(pDlidx);
243635      fts5DlidxIterNext(p, pDlidx);
243636    }
243637    assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
243638    if( iLeafPgno>pIter->iLeafPgno ){
243639      fts5SegIterGotoPage(p, pIter, iLeafPgno);
243640      bMove = 0;
243641    }
243642  }else{
243643    assert( pIter->pNextLeaf==0 );
243644    assert( iMatch<pIter->iRowid );
243645    while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
243646      fts5DlidxIterPrev(p, pDlidx);
243647    }
243648    iLeafPgno = fts5DlidxIterPgno(pDlidx);
243649
243650    assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
243651
243652    if( iLeafPgno<pIter->iLeafPgno ){
243653      pIter->iLeafPgno = iLeafPgno+1;
243654      fts5SegIterReverseNewPage(p, pIter);
243655      bMove = 0;
243656    }
243657  }
243658
243659  do{
243660    if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
243661    if( pIter->pLeaf==0 ) break;
243662    if( bRev==0 && pIter->iRowid>=iMatch ) break;
243663    if( bRev!=0 && pIter->iRowid<=iMatch ) break;
243664    bMove = 1;
243665  }while( p->rc==SQLITE_OK );
243666}
243667
243668/*
243669** Free the iterator object passed as the second argument.
243670*/
243671static void fts5MultiIterFree(Fts5Iter *pIter){
243672  if( pIter ){
243673    int i;
243674    for(i=0; i<pIter->nSeg; i++){
243675      fts5SegIterClear(&pIter->aSeg[i]);
243676    }
243677    fts5BufferFree(&pIter->poslist);
243678    sqlite3_free(pIter);
243679  }
243680}
243681
243682static void fts5MultiIterAdvanced(
243683  Fts5Index *p,                   /* FTS5 backend to iterate within */
243684  Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
243685  int iChanged,                   /* Index of sub-iterator just advanced */
243686  int iMinset                     /* Minimum entry in aFirst[] to set */
243687){
243688  int i;
243689  for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
243690    int iEq;
243691    if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
243692      Fts5SegIter *pSeg = &pIter->aSeg[iEq];
243693      assert( p->rc==SQLITE_OK );
243694      pSeg->xNext(p, pSeg, 0);
243695      i = pIter->nSeg + iEq;
243696    }
243697  }
243698}
243699
243700/*
243701** Sub-iterator iChanged of iterator pIter has just been advanced. It still
243702** points to the same term though - just a different rowid. This function
243703** attempts to update the contents of the pIter->aFirst[] accordingly.
243704** If it does so successfully, 0 is returned. Otherwise 1.
243705**
243706** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
243707** on the iterator instead. That function does the same as this one, except
243708** that it deals with more complicated cases as well.
243709*/
243710static int fts5MultiIterAdvanceRowid(
243711  Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
243712  int iChanged,                   /* Index of sub-iterator just advanced */
243713  Fts5SegIter **ppFirst
243714){
243715  Fts5SegIter *pNew = &pIter->aSeg[iChanged];
243716
243717  if( pNew->iRowid==pIter->iSwitchRowid
243718   || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
243719  ){
243720    int i;
243721    Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
243722    pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
243723    for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
243724      Fts5CResult *pRes = &pIter->aFirst[i];
243725
243726      assert( pNew->pLeaf );
243727      assert( pRes->bTermEq==0 || pOther->pLeaf );
243728
243729      if( pRes->bTermEq ){
243730        if( pNew->iRowid==pOther->iRowid ){
243731          return 1;
243732        }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
243733          pIter->iSwitchRowid = pOther->iRowid;
243734          pNew = pOther;
243735        }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
243736          pIter->iSwitchRowid = pOther->iRowid;
243737        }
243738      }
243739      pRes->iFirst = (u16)(pNew - pIter->aSeg);
243740      if( i==1 ) break;
243741
243742      pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
243743    }
243744  }
243745
243746  *ppFirst = pNew;
243747  return 0;
243748}
243749
243750/*
243751** Set the pIter->bEof variable based on the state of the sub-iterators.
243752*/
243753static void fts5MultiIterSetEof(Fts5Iter *pIter){
243754  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
243755  pIter->base.bEof = pSeg->pLeaf==0;
243756  pIter->iSwitchRowid = pSeg->iRowid;
243757}
243758
243759/*
243760** The argument to this macro must be an Fts5Data structure containing a
243761** tombstone hash page. This macro returns the key-size of the hash-page.
243762*/
243763#define TOMBSTONE_KEYSIZE(pPg) (pPg->p[0]==4 ? 4 : 8)
243764
243765#define TOMBSTONE_NSLOT(pPg)   \
243766  ((pPg->nn > 16) ? ((pPg->nn-8) / TOMBSTONE_KEYSIZE(pPg)) : 1)
243767
243768/*
243769** Query a single tombstone hash table for rowid iRowid. Return true if
243770** it is found or false otherwise. The tombstone hash table is one of
243771** nHashTable tables.
243772*/
243773static int fts5IndexTombstoneQuery(
243774  Fts5Data *pHash,                /* Hash table page to query */
243775  int nHashTable,                 /* Number of pages attached to segment */
243776  u64 iRowid                      /* Rowid to query hash for */
243777){
243778  const int szKey = TOMBSTONE_KEYSIZE(pHash);
243779  const int nSlot = TOMBSTONE_NSLOT(pHash);
243780  int iSlot = (iRowid / nHashTable) % nSlot;
243781  int nCollide = nSlot;
243782
243783  if( iRowid==0 ){
243784    return pHash->p[1];
243785  }else if( szKey==4 ){
243786    u32 *aSlot = (u32*)&pHash->p[8];
243787    while( aSlot[iSlot] ){
243788      if( fts5GetU32((u8*)&aSlot[iSlot])==iRowid ) return 1;
243789      if( nCollide--==0 ) break;
243790      iSlot = (iSlot+1)%nSlot;
243791    }
243792  }else{
243793    u64 *aSlot = (u64*)&pHash->p[8];
243794    while( aSlot[iSlot] ){
243795      if( fts5GetU64((u8*)&aSlot[iSlot])==iRowid ) return 1;
243796      if( nCollide--==0 ) break;
243797      iSlot = (iSlot+1)%nSlot;
243798    }
243799  }
243800
243801  return 0;
243802}
243803
243804/*
243805** Return true if the iterator passed as the only argument points
243806** to an segment entry for which there is a tombstone. Return false
243807** if there is no tombstone or if the iterator is already at EOF.
243808*/
243809static int fts5MultiIterIsDeleted(Fts5Iter *pIter){
243810  int iFirst = pIter->aFirst[1].iFirst;
243811  Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
243812  Fts5TombstoneArray *pArray = pSeg->pTombArray;
243813
243814  if( pSeg->pLeaf && pArray ){
243815    /* Figure out which page the rowid might be present on. */
243816    int iPg = ((u64)pSeg->iRowid) % pArray->nTombstone;
243817    assert( iPg>=0 );
243818
243819    /* If tombstone hash page iPg has not yet been loaded from the
243820    ** database, load it now. */
243821    if( pArray->apTombstone[iPg]==0 ){
243822      pArray->apTombstone[iPg] = fts5DataRead(pIter->pIndex,
243823          FTS5_TOMBSTONE_ROWID(pSeg->pSeg->iSegid, iPg)
243824      );
243825      if( pArray->apTombstone[iPg]==0 ) return 0;
243826    }
243827
243828    return fts5IndexTombstoneQuery(
243829        pArray->apTombstone[iPg],
243830        pArray->nTombstone,
243831        pSeg->iRowid
243832    );
243833  }
243834
243835  return 0;
243836}
243837
243838/*
243839** Move the iterator to the next entry.
243840**
243841** If an error occurs, an error code is left in Fts5Index.rc. It is not
243842** considered an error if the iterator reaches EOF, or if it is already at
243843** EOF when this function is called.
243844*/
243845static void fts5MultiIterNext(
243846  Fts5Index *p,
243847  Fts5Iter *pIter,
243848  int bFrom,                      /* True if argument iFrom is valid */
243849  i64 iFrom                       /* Advance at least as far as this */
243850){
243851  int bUseFrom = bFrom;
243852  assert( pIter->base.bEof==0 );
243853  while( p->rc==SQLITE_OK ){
243854    int iFirst = pIter->aFirst[1].iFirst;
243855    int bNewTerm = 0;
243856    Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
243857    assert( p->rc==SQLITE_OK );
243858    if( bUseFrom && pSeg->pDlidx ){
243859      fts5SegIterNextFrom(p, pSeg, iFrom);
243860    }else{
243861      pSeg->xNext(p, pSeg, &bNewTerm);
243862    }
243863
243864    if( pSeg->pLeaf==0 || bNewTerm
243865     || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
243866    ){
243867      fts5MultiIterAdvanced(p, pIter, iFirst, 1);
243868      fts5MultiIterSetEof(pIter);
243869      pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
243870      if( pSeg->pLeaf==0 ) return;
243871    }
243872
243873    fts5AssertMultiIterSetup(p, pIter);
243874    assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
243875    if( (pIter->bSkipEmpty==0 || pSeg->nPos)
243876      && 0==fts5MultiIterIsDeleted(pIter)
243877    ){
243878      pIter->xSetOutputs(pIter, pSeg);
243879      return;
243880    }
243881    bUseFrom = 0;
243882  }
243883}
243884
243885static void fts5MultiIterNext2(
243886  Fts5Index *p,
243887  Fts5Iter *pIter,
243888  int *pbNewTerm                  /* OUT: True if *might* be new term */
243889){
243890  assert( pIter->bSkipEmpty );
243891  if( p->rc==SQLITE_OK ){
243892    *pbNewTerm = 0;
243893    do{
243894      int iFirst = pIter->aFirst[1].iFirst;
243895      Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
243896      int bNewTerm = 0;
243897
243898      assert( p->rc==SQLITE_OK );
243899      pSeg->xNext(p, pSeg, &bNewTerm);
243900      if( pSeg->pLeaf==0 || bNewTerm
243901       || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
243902      ){
243903        fts5MultiIterAdvanced(p, pIter, iFirst, 1);
243904        fts5MultiIterSetEof(pIter);
243905        *pbNewTerm = 1;
243906      }
243907      fts5AssertMultiIterSetup(p, pIter);
243908
243909    }while( (fts5MultiIterIsEmpty(p, pIter) || fts5MultiIterIsDeleted(pIter))
243910         && (p->rc==SQLITE_OK)
243911    );
243912  }
243913}
243914
243915static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
243916  UNUSED_PARAM2(pUnused1, pUnused2);
243917}
243918
243919static Fts5Iter *fts5MultiIterAlloc(
243920  Fts5Index *p,                   /* FTS5 backend to iterate within */
243921  int nSeg
243922){
243923  Fts5Iter *pNew;
243924  i64 nSlot;                      /* Power of two >= nSeg */
243925
243926  for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
243927  pNew = fts5IdxMalloc(p,
243928      sizeof(Fts5Iter) +                  /* pNew */
243929      sizeof(Fts5SegIter) * (nSlot-1) +   /* pNew->aSeg[] */
243930      sizeof(Fts5CResult) * nSlot         /* pNew->aFirst[] */
243931  );
243932  if( pNew ){
243933    pNew->nSeg = nSlot;
243934    pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
243935    pNew->pIndex = p;
243936    pNew->xSetOutputs = fts5IterSetOutputs_Noop;
243937  }
243938  return pNew;
243939}
243940
243941static void fts5PoslistCallback(
243942  Fts5Index *pUnused,
243943  void *pContext,
243944  const u8 *pChunk, int nChunk
243945){
243946  UNUSED_PARAM(pUnused);
243947  assert_nc( nChunk>=0 );
243948  if( nChunk>0 ){
243949    fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
243950  }
243951}
243952
243953typedef struct PoslistCallbackCtx PoslistCallbackCtx;
243954struct PoslistCallbackCtx {
243955  Fts5Buffer *pBuf;               /* Append to this buffer */
243956  Fts5Colset *pColset;            /* Restrict matches to this column */
243957  int eState;                     /* See above */
243958};
243959
243960typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
243961struct PoslistOffsetsCtx {
243962  Fts5Buffer *pBuf;               /* Append to this buffer */
243963  Fts5Colset *pColset;            /* Restrict matches to this column */
243964  int iRead;
243965  int iWrite;
243966};
243967
243968/*
243969** TODO: Make this more efficient!
243970*/
243971static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
243972  int i;
243973  for(i=0; i<pColset->nCol; i++){
243974    if( pColset->aiCol[i]==iCol ) return 1;
243975  }
243976  return 0;
243977}
243978
243979static void fts5PoslistOffsetsCallback(
243980  Fts5Index *pUnused,
243981  void *pContext,
243982  const u8 *pChunk, int nChunk
243983){
243984  PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
243985  UNUSED_PARAM(pUnused);
243986  assert_nc( nChunk>=0 );
243987  if( nChunk>0 ){
243988    int i = 0;
243989    while( i<nChunk ){
243990      int iVal;
243991      i += fts5GetVarint32(&pChunk[i], iVal);
243992      iVal += pCtx->iRead - 2;
243993      pCtx->iRead = iVal;
243994      if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
243995        fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
243996        pCtx->iWrite = iVal;
243997      }
243998    }
243999  }
244000}
244001
244002static void fts5PoslistFilterCallback(
244003  Fts5Index *pUnused,
244004  void *pContext,
244005  const u8 *pChunk, int nChunk
244006){
244007  PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
244008  UNUSED_PARAM(pUnused);
244009  assert_nc( nChunk>=0 );
244010  if( nChunk>0 ){
244011    /* Search through to find the first varint with value 1. This is the
244012    ** start of the next columns hits. */
244013    int i = 0;
244014    int iStart = 0;
244015
244016    if( pCtx->eState==2 ){
244017      int iCol;
244018      fts5FastGetVarint32(pChunk, i, iCol);
244019      if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
244020        pCtx->eState = 1;
244021        fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
244022      }else{
244023        pCtx->eState = 0;
244024      }
244025    }
244026
244027    do {
244028      while( i<nChunk && pChunk[i]!=0x01 ){
244029        while( pChunk[i] & 0x80 ) i++;
244030        i++;
244031      }
244032      if( pCtx->eState ){
244033        fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
244034      }
244035      if( i<nChunk ){
244036        int iCol;
244037        iStart = i;
244038        i++;
244039        if( i>=nChunk ){
244040          pCtx->eState = 2;
244041        }else{
244042          fts5FastGetVarint32(pChunk, i, iCol);
244043          pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
244044          if( pCtx->eState ){
244045            fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
244046            iStart = i;
244047          }
244048        }
244049      }
244050    }while( i<nChunk );
244051  }
244052}
244053
244054static void fts5ChunkIterate(
244055  Fts5Index *p,                   /* Index object */
244056  Fts5SegIter *pSeg,              /* Poslist of this iterator */
244057  void *pCtx,                     /* Context pointer for xChunk callback */
244058  void (*xChunk)(Fts5Index*, void*, const u8*, int)
244059){
244060  int nRem = pSeg->nPos;          /* Number of bytes still to come */
244061  Fts5Data *pData = 0;
244062  u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
244063  int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
244064  int pgno = pSeg->iLeafPgno;
244065  int pgnoSave = 0;
244066
244067  /* This function does not work with detail=none databases. */
244068  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
244069
244070  if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
244071    pgnoSave = pgno+1;
244072  }
244073
244074  while( 1 ){
244075    xChunk(p, pCtx, pChunk, nChunk);
244076    nRem -= nChunk;
244077    fts5DataRelease(pData);
244078    if( nRem<=0 ){
244079      break;
244080    }else if( pSeg->pSeg==0 ){
244081      p->rc = FTS5_CORRUPT;
244082      return;
244083    }else{
244084      pgno++;
244085      pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
244086      if( pData==0 ) break;
244087      pChunk = &pData->p[4];
244088      nChunk = MIN(nRem, pData->szLeaf - 4);
244089      if( pgno==pgnoSave ){
244090        assert( pSeg->pNextLeaf==0 );
244091        pSeg->pNextLeaf = pData;
244092        pData = 0;
244093      }
244094    }
244095  }
244096}
244097
244098/*
244099** Iterator pIter currently points to a valid entry (not EOF). This
244100** function appends the position list data for the current entry to
244101** buffer pBuf. It does not make a copy of the position-list size
244102** field.
244103*/
244104static void fts5SegiterPoslist(
244105  Fts5Index *p,
244106  Fts5SegIter *pSeg,
244107  Fts5Colset *pColset,
244108  Fts5Buffer *pBuf
244109){
244110  assert( pBuf!=0 );
244111  assert( pSeg!=0 );
244112  if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+FTS5_DATA_ZERO_PADDING) ){
244113    assert( pBuf->p!=0 );
244114    assert( pBuf->nSpace >= pBuf->n+pSeg->nPos+FTS5_DATA_ZERO_PADDING );
244115    memset(&pBuf->p[pBuf->n+pSeg->nPos], 0, FTS5_DATA_ZERO_PADDING);
244116    if( pColset==0 ){
244117      fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
244118    }else{
244119      if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
244120        PoslistCallbackCtx sCtx;
244121        sCtx.pBuf = pBuf;
244122        sCtx.pColset = pColset;
244123        sCtx.eState = fts5IndexColsetTest(pColset, 0);
244124        assert( sCtx.eState==0 || sCtx.eState==1 );
244125        fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
244126      }else{
244127        PoslistOffsetsCtx sCtx;
244128        memset(&sCtx, 0, sizeof(sCtx));
244129        sCtx.pBuf = pBuf;
244130        sCtx.pColset = pColset;
244131        fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
244132      }
244133    }
244134  }
244135}
244136
244137/*
244138** Parameter pPos points to a buffer containing a position list, size nPos.
244139** This function filters it according to pColset (which must be non-NULL)
244140** and sets pIter->base.pData/nData to point to the new position list.
244141** If memory is required for the new position list, use buffer pIter->poslist.
244142** Or, if the new position list is a contiguous subset of the input, set
244143** pIter->base.pData/nData to point directly to it.
244144**
244145** This function is a no-op if *pRc is other than SQLITE_OK when it is
244146** called. If an OOM error is encountered, *pRc is set to SQLITE_NOMEM
244147** before returning.
244148*/
244149static void fts5IndexExtractColset(
244150  int *pRc,
244151  Fts5Colset *pColset,            /* Colset to filter on */
244152  const u8 *pPos, int nPos,       /* Position list */
244153  Fts5Iter *pIter
244154){
244155  if( *pRc==SQLITE_OK ){
244156    const u8 *p = pPos;
244157    const u8 *aCopy = p;
244158    const u8 *pEnd = &p[nPos];    /* One byte past end of position list */
244159    int i = 0;
244160    int iCurrent = 0;
244161
244162    if( pColset->nCol>1 && sqlite3Fts5BufferSize(pRc, &pIter->poslist, nPos) ){
244163      return;
244164    }
244165
244166    while( 1 ){
244167      while( pColset->aiCol[i]<iCurrent ){
244168        i++;
244169        if( i==pColset->nCol ){
244170          pIter->base.pData = pIter->poslist.p;
244171          pIter->base.nData = pIter->poslist.n;
244172          return;
244173        }
244174      }
244175
244176      /* Advance pointer p until it points to pEnd or an 0x01 byte that is
244177      ** not part of a varint */
244178      while( p<pEnd && *p!=0x01 ){
244179        while( *p++ & 0x80 );
244180      }
244181
244182      if( pColset->aiCol[i]==iCurrent ){
244183        if( pColset->nCol==1 ){
244184          pIter->base.pData = aCopy;
244185          pIter->base.nData = p-aCopy;
244186          return;
244187        }
244188        fts5BufferSafeAppendBlob(&pIter->poslist, aCopy, p-aCopy);
244189      }
244190      if( p>=pEnd ){
244191        pIter->base.pData = pIter->poslist.p;
244192        pIter->base.nData = pIter->poslist.n;
244193        return;
244194      }
244195      aCopy = p++;
244196      iCurrent = *p++;
244197      if( iCurrent & 0x80 ){
244198        p--;
244199        p += fts5GetVarint32(p, iCurrent);
244200      }
244201    }
244202  }
244203
244204}
244205
244206/*
244207** xSetOutputs callback used by detail=none tables.
244208*/
244209static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
244210  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
244211  pIter->base.iRowid = pSeg->iRowid;
244212  pIter->base.nData = pSeg->nPos;
244213}
244214
244215/*
244216** xSetOutputs callback used by detail=full and detail=col tables when no
244217** column filters are specified.
244218*/
244219static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
244220  pIter->base.iRowid = pSeg->iRowid;
244221  pIter->base.nData = pSeg->nPos;
244222
244223  assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
244224  assert( pIter->pColset==0 );
244225
244226  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
244227    /* All data is stored on the current page. Populate the output
244228    ** variables to point into the body of the page object. */
244229    pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
244230  }else{
244231    /* The data is distributed over two or more pages. Copy it into the
244232    ** Fts5Iter.poslist buffer and then set the output pointer to point
244233    ** to this buffer.  */
244234    fts5BufferZero(&pIter->poslist);
244235    fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
244236    pIter->base.pData = pIter->poslist.p;
244237  }
244238}
244239
244240/*
244241** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
244242** against no columns at all).
244243*/
244244static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
244245  UNUSED_PARAM(pSeg);
244246  pIter->base.nData = 0;
244247}
244248
244249/*
244250** xSetOutputs callback used by detail=col when there is a column filter
244251** and there are 100 or more columns. Also called as a fallback from
244252** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
244253*/
244254static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
244255  fts5BufferZero(&pIter->poslist);
244256  fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
244257  pIter->base.iRowid = pSeg->iRowid;
244258  pIter->base.pData = pIter->poslist.p;
244259  pIter->base.nData = pIter->poslist.n;
244260}
244261
244262/*
244263** xSetOutputs callback used when:
244264**
244265**   * detail=col,
244266**   * there is a column filter, and
244267**   * the table contains 100 or fewer columns.
244268**
244269** The last point is to ensure all column numbers are stored as
244270** single-byte varints.
244271*/
244272static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
244273
244274  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
244275  assert( pIter->pColset );
244276
244277  if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
244278    fts5IterSetOutputs_Col(pIter, pSeg);
244279  }else{
244280    u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
244281    u8 *pEnd = (u8*)&a[pSeg->nPos];
244282    int iPrev = 0;
244283    int *aiCol = pIter->pColset->aiCol;
244284    int *aiColEnd = &aiCol[pIter->pColset->nCol];
244285
244286    u8 *aOut = pIter->poslist.p;
244287    int iPrevOut = 0;
244288
244289    pIter->base.iRowid = pSeg->iRowid;
244290
244291    while( a<pEnd ){
244292      iPrev += (int)a++[0] - 2;
244293      while( *aiCol<iPrev ){
244294        aiCol++;
244295        if( aiCol==aiColEnd ) goto setoutputs_col_out;
244296      }
244297      if( *aiCol==iPrev ){
244298        *aOut++ = (u8)((iPrev - iPrevOut) + 2);
244299        iPrevOut = iPrev;
244300      }
244301    }
244302
244303setoutputs_col_out:
244304    pIter->base.pData = pIter->poslist.p;
244305    pIter->base.nData = aOut - pIter->poslist.p;
244306  }
244307}
244308
244309/*
244310** xSetOutputs callback used by detail=full when there is a column filter.
244311*/
244312static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
244313  Fts5Colset *pColset = pIter->pColset;
244314  pIter->base.iRowid = pSeg->iRowid;
244315
244316  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
244317  assert( pColset );
244318
244319  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
244320    /* All data is stored on the current page. Populate the output
244321    ** variables to point into the body of the page object. */
244322    const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
244323    int *pRc = &pIter->pIndex->rc;
244324    fts5BufferZero(&pIter->poslist);
244325    fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, pIter);
244326  }else{
244327    /* The data is distributed over two or more pages. Copy it into the
244328    ** Fts5Iter.poslist buffer and then set the output pointer to point
244329    ** to this buffer.  */
244330    fts5BufferZero(&pIter->poslist);
244331    fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
244332    pIter->base.pData = pIter->poslist.p;
244333    pIter->base.nData = pIter->poslist.n;
244334  }
244335}
244336
244337static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
244338  assert( pIter!=0 || (*pRc)!=SQLITE_OK );
244339  if( *pRc==SQLITE_OK ){
244340    Fts5Config *pConfig = pIter->pIndex->pConfig;
244341    if( pConfig->eDetail==FTS5_DETAIL_NONE ){
244342      pIter->xSetOutputs = fts5IterSetOutputs_None;
244343    }
244344
244345    else if( pIter->pColset==0 ){
244346      pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
244347    }
244348
244349    else if( pIter->pColset->nCol==0 ){
244350      pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
244351    }
244352
244353    else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
244354      pIter->xSetOutputs = fts5IterSetOutputs_Full;
244355    }
244356
244357    else{
244358      assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
244359      if( pConfig->nCol<=100 ){
244360        pIter->xSetOutputs = fts5IterSetOutputs_Col100;
244361        sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
244362      }else{
244363        pIter->xSetOutputs = fts5IterSetOutputs_Col;
244364      }
244365    }
244366  }
244367}
244368
244369/*
244370** All the component segment-iterators of pIter have been set up. This
244371** functions finishes setup for iterator pIter itself.
244372*/
244373static void fts5MultiIterFinishSetup(Fts5Index *p, Fts5Iter *pIter){
244374  int iIter;
244375  for(iIter=pIter->nSeg-1; iIter>0; iIter--){
244376    int iEq;
244377    if( (iEq = fts5MultiIterDoCompare(pIter, iIter)) ){
244378      Fts5SegIter *pSeg = &pIter->aSeg[iEq];
244379      if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
244380      fts5MultiIterAdvanced(p, pIter, iEq, iIter);
244381    }
244382  }
244383  fts5MultiIterSetEof(pIter);
244384  fts5AssertMultiIterSetup(p, pIter);
244385
244386  if( (pIter->bSkipEmpty && fts5MultiIterIsEmpty(p, pIter))
244387   || fts5MultiIterIsDeleted(pIter)
244388  ){
244389    fts5MultiIterNext(p, pIter, 0, 0);
244390  }else if( pIter->base.bEof==0 ){
244391    Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
244392    pIter->xSetOutputs(pIter, pSeg);
244393  }
244394}
244395
244396/*
244397** Allocate a new Fts5Iter object.
244398**
244399** The new object will be used to iterate through data in structure pStruct.
244400** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
244401** is zero or greater, data from the first nSegment segments on level iLevel
244402** is merged.
244403**
244404** The iterator initially points to the first term/rowid entry in the
244405** iterated data.
244406*/
244407static void fts5MultiIterNew(
244408  Fts5Index *p,                   /* FTS5 backend to iterate within */
244409  Fts5Structure *pStruct,         /* Structure of specific index */
244410  int flags,                      /* FTS5INDEX_QUERY_XXX flags */
244411  Fts5Colset *pColset,            /* Colset to filter on (or NULL) */
244412  const u8 *pTerm, int nTerm,     /* Term to seek to (or NULL/0) */
244413  int iLevel,                     /* Level to iterate (-1 for all) */
244414  int nSegment,                   /* Number of segments to merge (iLevel>=0) */
244415  Fts5Iter **ppOut                /* New object */
244416){
244417  int nSeg = 0;                   /* Number of segment-iters in use */
244418  int iIter = 0;                  /* */
244419  int iSeg;                       /* Used to iterate through segments */
244420  Fts5StructureLevel *pLvl;
244421  Fts5Iter *pNew;
244422
244423  assert( (pTerm==0 && nTerm==0) || iLevel<0 );
244424
244425  /* Allocate space for the new multi-seg-iterator. */
244426  if( p->rc==SQLITE_OK ){
244427    if( iLevel<0 ){
244428      assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
244429      nSeg = pStruct->nSegment;
244430      nSeg += (p->pHash && 0==(flags & FTS5INDEX_QUERY_SKIPHASH));
244431    }else{
244432      nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
244433    }
244434  }
244435  *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
244436  if( pNew==0 ){
244437    assert( p->rc!=SQLITE_OK );
244438    goto fts5MultiIterNew_post_check;
244439  }
244440  pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
244441  pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
244442  pNew->pColset = pColset;
244443  if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
244444    fts5IterSetOutputCb(&p->rc, pNew);
244445  }
244446
244447  /* Initialize each of the component segment iterators. */
244448  if( p->rc==SQLITE_OK ){
244449    if( iLevel<0 ){
244450      Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
244451      if( p->pHash && 0==(flags & FTS5INDEX_QUERY_SKIPHASH) ){
244452        /* Add a segment iterator for the current contents of the hash table. */
244453        Fts5SegIter *pIter = &pNew->aSeg[iIter++];
244454        fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
244455      }
244456      for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
244457        for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
244458          Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
244459          Fts5SegIter *pIter = &pNew->aSeg[iIter++];
244460          if( pTerm==0 ){
244461            fts5SegIterInit(p, pSeg, pIter);
244462          }else{
244463            fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
244464          }
244465        }
244466      }
244467    }else{
244468      pLvl = &pStruct->aLevel[iLevel];
244469      for(iSeg=nSeg-1; iSeg>=0; iSeg--){
244470        fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
244471      }
244472    }
244473    assert( iIter==nSeg );
244474  }
244475
244476  /* If the above was successful, each component iterator now points
244477  ** to the first entry in its segment. In this case initialize the
244478  ** aFirst[] array. Or, if an error has occurred, free the iterator
244479  ** object and set the output variable to NULL.  */
244480  if( p->rc==SQLITE_OK ){
244481    fts5MultiIterFinishSetup(p, pNew);
244482  }else{
244483    fts5MultiIterFree(pNew);
244484    *ppOut = 0;
244485  }
244486
244487fts5MultiIterNew_post_check:
244488  assert( (*ppOut)!=0 || p->rc!=SQLITE_OK );
244489  return;
244490}
244491
244492/*
244493** Create an Fts5Iter that iterates through the doclist provided
244494** as the second argument.
244495*/
244496static void fts5MultiIterNew2(
244497  Fts5Index *p,                   /* FTS5 backend to iterate within */
244498  Fts5Data *pData,                /* Doclist to iterate through */
244499  int bDesc,                      /* True for descending rowid order */
244500  Fts5Iter **ppOut                /* New object */
244501){
244502  Fts5Iter *pNew;
244503  pNew = fts5MultiIterAlloc(p, 2);
244504  if( pNew ){
244505    Fts5SegIter *pIter = &pNew->aSeg[1];
244506    pIter->flags = FTS5_SEGITER_ONETERM;
244507    if( pData->szLeaf>0 ){
244508      pIter->pLeaf = pData;
244509      pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
244510      pIter->iEndofDoclist = pData->nn;
244511      pNew->aFirst[1].iFirst = 1;
244512      if( bDesc ){
244513        pNew->bRev = 1;
244514        pIter->flags |= FTS5_SEGITER_REVERSE;
244515        fts5SegIterReverseInitPage(p, pIter);
244516      }else{
244517        fts5SegIterLoadNPos(p, pIter);
244518      }
244519      pData = 0;
244520    }else{
244521      pNew->base.bEof = 1;
244522    }
244523    fts5SegIterSetNext(p, pIter);
244524
244525    *ppOut = pNew;
244526  }
244527
244528  fts5DataRelease(pData);
244529}
244530
244531/*
244532** Return true if the iterator is at EOF or if an error has occurred.
244533** False otherwise.
244534*/
244535static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
244536  assert( pIter!=0 || p->rc!=SQLITE_OK );
244537  assert( p->rc!=SQLITE_OK
244538      || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
244539  );
244540  return (p->rc || pIter->base.bEof);
244541}
244542
244543/*
244544** Return the rowid of the entry that the iterator currently points
244545** to. If the iterator points to EOF when this function is called the
244546** results are undefined.
244547*/
244548static i64 fts5MultiIterRowid(Fts5Iter *pIter){
244549  assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
244550  return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
244551}
244552
244553/*
244554** Move the iterator to the next entry at or following iMatch.
244555*/
244556static void fts5MultiIterNextFrom(
244557  Fts5Index *p,
244558  Fts5Iter *pIter,
244559  i64 iMatch
244560){
244561  while( 1 ){
244562    i64 iRowid;
244563    fts5MultiIterNext(p, pIter, 1, iMatch);
244564    if( fts5MultiIterEof(p, pIter) ) break;
244565    iRowid = fts5MultiIterRowid(pIter);
244566    if( pIter->bRev==0 && iRowid>=iMatch ) break;
244567    if( pIter->bRev!=0 && iRowid<=iMatch ) break;
244568  }
244569}
244570
244571/*
244572** Return a pointer to a buffer containing the term associated with the
244573** entry that the iterator currently points to.
244574*/
244575static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
244576  Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
244577  *pn = p->term.n;
244578  return p->term.p;
244579}
244580
244581/*
244582** Allocate a new segment-id for the structure pStruct. The new segment
244583** id must be between 1 and 65335 inclusive, and must not be used by
244584** any currently existing segment. If a free segment id cannot be found,
244585** SQLITE_FULL is returned.
244586**
244587** If an error has already occurred, this function is a no-op. 0 is
244588** returned in this case.
244589*/
244590static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
244591  int iSegid = 0;
244592
244593  if( p->rc==SQLITE_OK ){
244594    if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
244595      p->rc = SQLITE_FULL;
244596    }else{
244597      /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
244598      ** array is 63 elements, or 252 bytes, in size.  */
244599      u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
244600      int iLvl, iSeg;
244601      int i;
244602      u32 mask;
244603      memset(aUsed, 0, sizeof(aUsed));
244604      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
244605        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
244606          int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
244607          if( iId<=FTS5_MAX_SEGMENT && iId>0 ){
244608            aUsed[(iId-1) / 32] |= (u32)1 << ((iId-1) % 32);
244609          }
244610        }
244611      }
244612
244613      for(i=0; aUsed[i]==0xFFFFFFFF; i++);
244614      mask = aUsed[i];
244615      for(iSegid=0; mask & ((u32)1 << iSegid); iSegid++);
244616      iSegid += 1 + i*32;
244617
244618#ifdef SQLITE_DEBUG
244619      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
244620        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
244621          assert_nc( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
244622        }
244623      }
244624      assert_nc( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
244625
244626      {
244627        sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
244628        if( p->rc==SQLITE_OK ){
244629          u8 aBlob[2] = {0xff, 0xff};
244630          sqlite3_bind_int(pIdxSelect, 1, iSegid);
244631          sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
244632          assert_nc( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
244633          p->rc = sqlite3_reset(pIdxSelect);
244634          sqlite3_bind_null(pIdxSelect, 2);
244635        }
244636      }
244637#endif
244638    }
244639  }
244640
244641  return iSegid;
244642}
244643
244644/*
244645** Discard all data currently cached in the hash-tables.
244646*/
244647static void fts5IndexDiscardData(Fts5Index *p){
244648  assert( p->pHash || p->nPendingData==0 );
244649  if( p->pHash ){
244650    sqlite3Fts5HashClear(p->pHash);
244651    p->nPendingData = 0;
244652    p->nPendingRow = 0;
244653    p->flushRc = SQLITE_OK;
244654  }
244655  p->nContentlessDelete = 0;
244656}
244657
244658/*
244659** Return the size of the prefix, in bytes, that buffer
244660** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
244661**
244662** Buffer (pNew/<length-unknown>) is guaranteed to be greater
244663** than buffer (pOld/nOld).
244664*/
244665static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
244666  int i;
244667  for(i=0; i<nOld; i++){
244668    if( pOld[i]!=pNew[i] ) break;
244669  }
244670  return i;
244671}
244672
244673static void fts5WriteDlidxClear(
244674  Fts5Index *p,
244675  Fts5SegWriter *pWriter,
244676  int bFlush                      /* If true, write dlidx to disk */
244677){
244678  int i;
244679  assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
244680  for(i=0; i<pWriter->nDlidx; i++){
244681    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
244682    if( pDlidx->buf.n==0 ) break;
244683    if( bFlush ){
244684      assert( pDlidx->pgno!=0 );
244685      fts5DataWrite(p,
244686          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
244687          pDlidx->buf.p, pDlidx->buf.n
244688      );
244689    }
244690    sqlite3Fts5BufferZero(&pDlidx->buf);
244691    pDlidx->bPrevValid = 0;
244692  }
244693}
244694
244695/*
244696** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
244697** Any new array elements are zeroed before returning.
244698*/
244699static int fts5WriteDlidxGrow(
244700  Fts5Index *p,
244701  Fts5SegWriter *pWriter,
244702  int nLvl
244703){
244704  if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
244705    Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc64(
244706        pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
244707    );
244708    if( aDlidx==0 ){
244709      p->rc = SQLITE_NOMEM;
244710    }else{
244711      size_t nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
244712      memset(&aDlidx[pWriter->nDlidx], 0, nByte);
244713      pWriter->aDlidx = aDlidx;
244714      pWriter->nDlidx = nLvl;
244715    }
244716  }
244717  return p->rc;
244718}
244719
244720/*
244721** If the current doclist-index accumulating in pWriter->aDlidx[] is large
244722** enough, flush it to disk and return 1. Otherwise discard it and return
244723** zero.
244724*/
244725static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
244726  int bFlag = 0;
244727
244728  /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
244729  ** to the database, also write the doclist-index to disk.  */
244730  if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
244731    bFlag = 1;
244732  }
244733  fts5WriteDlidxClear(p, pWriter, bFlag);
244734  pWriter->nEmpty = 0;
244735  return bFlag;
244736}
244737
244738/*
244739** This function is called whenever processing of the doclist for the
244740** last term on leaf page (pWriter->iBtPage) is completed.
244741**
244742** The doclist-index for that term is currently stored in-memory within the
244743** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
244744** writes it out to disk. Or, if it is too small to bother with, discards
244745** it.
244746**
244747** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
244748*/
244749static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
244750  int bFlag;
244751
244752  assert( pWriter->iBtPage || pWriter->nEmpty==0 );
244753  if( pWriter->iBtPage==0 ) return;
244754  bFlag = fts5WriteFlushDlidx(p, pWriter);
244755
244756  if( p->rc==SQLITE_OK ){
244757    const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
244758    /* The following was already done in fts5WriteInit(): */
244759    /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
244760    sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
244761    sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
244762    sqlite3_step(p->pIdxWriter);
244763    p->rc = sqlite3_reset(p->pIdxWriter);
244764    sqlite3_bind_null(p->pIdxWriter, 2);
244765  }
244766  pWriter->iBtPage = 0;
244767}
244768
244769/*
244770** This is called once for each leaf page except the first that contains
244771** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
244772** is larger than all terms written to earlier leaves, and equal to or
244773** smaller than the first term on the new leaf.
244774**
244775** If an error occurs, an error code is left in Fts5Index.rc. If an error
244776** has already occurred when this function is called, it is a no-op.
244777*/
244778static void fts5WriteBtreeTerm(
244779  Fts5Index *p,                   /* FTS5 backend object */
244780  Fts5SegWriter *pWriter,         /* Writer object */
244781  int nTerm, const u8 *pTerm      /* First term on new page */
244782){
244783  fts5WriteFlushBtree(p, pWriter);
244784  if( p->rc==SQLITE_OK ){
244785    fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
244786    pWriter->iBtPage = pWriter->writer.pgno;
244787  }
244788}
244789
244790/*
244791** This function is called when flushing a leaf page that contains no
244792** terms at all to disk.
244793*/
244794static void fts5WriteBtreeNoTerm(
244795  Fts5Index *p,                   /* FTS5 backend object */
244796  Fts5SegWriter *pWriter          /* Writer object */
244797){
244798  /* If there were no rowids on the leaf page either and the doclist-index
244799  ** has already been started, append an 0x00 byte to it.  */
244800  if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
244801    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
244802    assert( pDlidx->bPrevValid );
244803    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
244804  }
244805
244806  /* Increment the "number of sequential leaves without a term" counter. */
244807  pWriter->nEmpty++;
244808}
244809
244810static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
244811  i64 iRowid;
244812  int iOff;
244813
244814  iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
244815  fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
244816  return iRowid;
244817}
244818
244819/*
244820** Rowid iRowid has just been appended to the current leaf page. It is the
244821** first on the page. This function appends an appropriate entry to the current
244822** doclist-index.
244823*/
244824static void fts5WriteDlidxAppend(
244825  Fts5Index *p,
244826  Fts5SegWriter *pWriter,
244827  i64 iRowid
244828){
244829  int i;
244830  int bDone = 0;
244831
244832  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
244833    i64 iVal;
244834    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
244835
244836    if( pDlidx->buf.n>=p->pConfig->pgsz ){
244837      /* The current doclist-index page is full. Write it to disk and push
244838      ** a copy of iRowid (which will become the first rowid on the next
244839      ** doclist-index leaf page) up into the next level of the b-tree
244840      ** hierarchy. If the node being flushed is currently the root node,
244841      ** also push its first rowid upwards. */
244842      pDlidx->buf.p[0] = 0x01;    /* Not the root node */
244843      fts5DataWrite(p,
244844          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
244845          pDlidx->buf.p, pDlidx->buf.n
244846      );
244847      fts5WriteDlidxGrow(p, pWriter, i+2);
244848      pDlidx = &pWriter->aDlidx[i];
244849      if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
244850        i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
244851
244852        /* This was the root node. Push its first rowid up to the new root. */
244853        pDlidx[1].pgno = pDlidx->pgno;
244854        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
244855        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
244856        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
244857        pDlidx[1].bPrevValid = 1;
244858        pDlidx[1].iPrev = iFirst;
244859      }
244860
244861      sqlite3Fts5BufferZero(&pDlidx->buf);
244862      pDlidx->bPrevValid = 0;
244863      pDlidx->pgno++;
244864    }else{
244865      bDone = 1;
244866    }
244867
244868    if( pDlidx->bPrevValid ){
244869      iVal = (u64)iRowid - (u64)pDlidx->iPrev;
244870    }else{
244871      i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
244872      assert( pDlidx->buf.n==0 );
244873      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
244874      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
244875      iVal = iRowid;
244876    }
244877
244878    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
244879    pDlidx->bPrevValid = 1;
244880    pDlidx->iPrev = iRowid;
244881  }
244882}
244883
244884static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
244885  static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
244886  Fts5PageWriter *pPage = &pWriter->writer;
244887  i64 iRowid;
244888
244889  assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
244890
244891  /* Set the szLeaf header field. */
244892  assert( 0==fts5GetU16(&pPage->buf.p[2]) );
244893  fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
244894
244895  if( pWriter->bFirstTermInPage ){
244896    /* No term was written to this page. */
244897    assert( pPage->pgidx.n==0 );
244898    fts5WriteBtreeNoTerm(p, pWriter);
244899  }else{
244900    /* Append the pgidx to the page buffer. Set the szLeaf header field. */
244901    fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
244902  }
244903
244904  /* Write the page out to disk */
244905  iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
244906  fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
244907
244908  /* Initialize the next page. */
244909  fts5BufferZero(&pPage->buf);
244910  fts5BufferZero(&pPage->pgidx);
244911  fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
244912  pPage->iPrevPgidx = 0;
244913  pPage->pgno++;
244914
244915  /* Increase the leaves written counter */
244916  pWriter->nLeafWritten++;
244917
244918  /* The new leaf holds no terms or rowids */
244919  pWriter->bFirstTermInPage = 1;
244920  pWriter->bFirstRowidInPage = 1;
244921}
244922
244923/*
244924** Append term pTerm/nTerm to the segment being written by the writer passed
244925** as the second argument.
244926**
244927** If an error occurs, set the Fts5Index.rc error code. If an error has
244928** already occurred, this function is a no-op.
244929*/
244930static void fts5WriteAppendTerm(
244931  Fts5Index *p,
244932  Fts5SegWriter *pWriter,
244933  int nTerm, const u8 *pTerm
244934){
244935  int nPrefix;                    /* Bytes of prefix compression for term */
244936  Fts5PageWriter *pPage = &pWriter->writer;
244937  Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
244938  int nMin = MIN(pPage->term.n, nTerm);
244939
244940  assert( p->rc==SQLITE_OK );
244941  assert( pPage->buf.n>=4 );
244942  assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
244943
244944  /* If the current leaf page is full, flush it to disk. */
244945  if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
244946    if( pPage->buf.n>4 ){
244947      fts5WriteFlushLeaf(p, pWriter);
244948      if( p->rc!=SQLITE_OK ) return;
244949    }
244950    fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
244951  }
244952
244953  /* TODO1: Updating pgidx here. */
244954  pPgidx->n += sqlite3Fts5PutVarint(
244955      &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
244956  );
244957  pPage->iPrevPgidx = pPage->buf.n;
244958#if 0
244959  fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
244960  pPgidx->n += 2;
244961#endif
244962
244963  if( pWriter->bFirstTermInPage ){
244964    nPrefix = 0;
244965    if( pPage->pgno!=1 ){
244966      /* This is the first term on a leaf that is not the leftmost leaf in
244967      ** the segment b-tree. In this case it is necessary to add a term to
244968      ** the b-tree hierarchy that is (a) larger than the largest term
244969      ** already written to the segment and (b) smaller than or equal to
244970      ** this term. In other words, a prefix of (pTerm/nTerm) that is one
244971      ** byte longer than the longest prefix (pTerm/nTerm) shares with the
244972      ** previous term.
244973      **
244974      ** Usually, the previous term is available in pPage->term. The exception
244975      ** is if this is the first term written in an incremental-merge step.
244976      ** In this case the previous term is not available, so just write a
244977      ** copy of (pTerm/nTerm) into the parent node. This is slightly
244978      ** inefficient, but still correct.  */
244979      int n = nTerm;
244980      if( pPage->term.n ){
244981        n = 1 + fts5PrefixCompress(nMin, pPage->term.p, pTerm);
244982      }
244983      fts5WriteBtreeTerm(p, pWriter, n, pTerm);
244984      if( p->rc!=SQLITE_OK ) return;
244985      pPage = &pWriter->writer;
244986    }
244987  }else{
244988    nPrefix = fts5PrefixCompress(nMin, pPage->term.p, pTerm);
244989    fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
244990  }
244991
244992  /* Append the number of bytes of new data, then the term data itself
244993  ** to the page. */
244994  fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
244995  fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
244996
244997  /* Update the Fts5PageWriter.term field. */
244998  fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
244999  pWriter->bFirstTermInPage = 0;
245000
245001  pWriter->bFirstRowidInPage = 0;
245002  pWriter->bFirstRowidInDoclist = 1;
245003
245004  assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
245005  pWriter->aDlidx[0].pgno = pPage->pgno;
245006}
245007
245008/*
245009** Append a rowid and position-list size field to the writers output.
245010*/
245011static void fts5WriteAppendRowid(
245012  Fts5Index *p,
245013  Fts5SegWriter *pWriter,
245014  i64 iRowid
245015){
245016  if( p->rc==SQLITE_OK ){
245017    Fts5PageWriter *pPage = &pWriter->writer;
245018
245019    if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
245020      fts5WriteFlushLeaf(p, pWriter);
245021    }
245022
245023    /* If this is to be the first rowid written to the page, set the
245024    ** rowid-pointer in the page-header. Also append a value to the dlidx
245025    ** buffer, in case a doclist-index is required.  */
245026    if( pWriter->bFirstRowidInPage ){
245027      fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
245028      fts5WriteDlidxAppend(p, pWriter, iRowid);
245029    }
245030
245031    /* Write the rowid. */
245032    if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
245033      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
245034    }else{
245035      assert_nc( p->rc || iRowid>pWriter->iPrevRowid );
245036      fts5BufferAppendVarint(&p->rc, &pPage->buf,
245037          (u64)iRowid - (u64)pWriter->iPrevRowid
245038      );
245039    }
245040    pWriter->iPrevRowid = iRowid;
245041    pWriter->bFirstRowidInDoclist = 0;
245042    pWriter->bFirstRowidInPage = 0;
245043  }
245044}
245045
245046static void fts5WriteAppendPoslistData(
245047  Fts5Index *p,
245048  Fts5SegWriter *pWriter,
245049  const u8 *aData,
245050  int nData
245051){
245052  Fts5PageWriter *pPage = &pWriter->writer;
245053  const u8 *a = aData;
245054  int n = nData;
245055
245056  assert( p->pConfig->pgsz>0 || p->rc!=SQLITE_OK );
245057  while( p->rc==SQLITE_OK
245058     && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
245059  ){
245060    int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
245061    int nCopy = 0;
245062    while( nCopy<nReq ){
245063      i64 dummy;
245064      nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
245065    }
245066    fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
245067    a += nCopy;
245068    n -= nCopy;
245069    fts5WriteFlushLeaf(p, pWriter);
245070  }
245071  if( n>0 ){
245072    fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
245073  }
245074}
245075
245076/*
245077** Flush any data cached by the writer object to the database. Free any
245078** allocations associated with the writer.
245079*/
245080static void fts5WriteFinish(
245081  Fts5Index *p,
245082  Fts5SegWriter *pWriter,         /* Writer object */
245083  int *pnLeaf                     /* OUT: Number of leaf pages in b-tree */
245084){
245085  int i;
245086  Fts5PageWriter *pLeaf = &pWriter->writer;
245087  if( p->rc==SQLITE_OK ){
245088    assert( pLeaf->pgno>=1 );
245089    if( pLeaf->buf.n>4 ){
245090      fts5WriteFlushLeaf(p, pWriter);
245091    }
245092    *pnLeaf = pLeaf->pgno-1;
245093    if( pLeaf->pgno>1 ){
245094      fts5WriteFlushBtree(p, pWriter);
245095    }
245096  }
245097  fts5BufferFree(&pLeaf->term);
245098  fts5BufferFree(&pLeaf->buf);
245099  fts5BufferFree(&pLeaf->pgidx);
245100  fts5BufferFree(&pWriter->btterm);
245101
245102  for(i=0; i<pWriter->nDlidx; i++){
245103    sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
245104  }
245105  sqlite3_free(pWriter->aDlidx);
245106}
245107
245108static void fts5WriteInit(
245109  Fts5Index *p,
245110  Fts5SegWriter *pWriter,
245111  int iSegid
245112){
245113  const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
245114
245115  memset(pWriter, 0, sizeof(Fts5SegWriter));
245116  pWriter->iSegid = iSegid;
245117
245118  fts5WriteDlidxGrow(p, pWriter, 1);
245119  pWriter->writer.pgno = 1;
245120  pWriter->bFirstTermInPage = 1;
245121  pWriter->iBtPage = 1;
245122
245123  assert( pWriter->writer.buf.n==0 );
245124  assert( pWriter->writer.pgidx.n==0 );
245125
245126  /* Grow the two buffers to pgsz + padding bytes in size. */
245127  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
245128  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
245129
245130  if( p->pIdxWriter==0 ){
245131    Fts5Config *pConfig = p->pConfig;
245132    fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
245133          "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
245134          pConfig->zDb, pConfig->zName
245135    ));
245136  }
245137
245138  if( p->rc==SQLITE_OK ){
245139    /* Initialize the 4-byte leaf-page header to 0x00. */
245140    memset(pWriter->writer.buf.p, 0, 4);
245141    pWriter->writer.buf.n = 4;
245142
245143    /* Bind the current output segment id to the index-writer. This is an
245144    ** optimization over binding the same value over and over as rows are
245145    ** inserted into %_idx by the current writer.  */
245146    sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
245147  }
245148}
245149
245150/*
245151** Iterator pIter was used to iterate through the input segments of on an
245152** incremental merge operation. This function is called if the incremental
245153** merge step has finished but the input has not been completely exhausted.
245154*/
245155static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
245156  int i;
245157  Fts5Buffer buf;
245158  memset(&buf, 0, sizeof(Fts5Buffer));
245159  for(i=0; i<pIter->nSeg && p->rc==SQLITE_OK; i++){
245160    Fts5SegIter *pSeg = &pIter->aSeg[i];
245161    if( pSeg->pSeg==0 ){
245162      /* no-op */
245163    }else if( pSeg->pLeaf==0 ){
245164      /* All keys from this input segment have been transfered to the output.
245165      ** Set both the first and last page-numbers to 0 to indicate that the
245166      ** segment is now empty. */
245167      pSeg->pSeg->pgnoLast = 0;
245168      pSeg->pSeg->pgnoFirst = 0;
245169    }else{
245170      int iOff = pSeg->iTermLeafOffset;     /* Offset on new first leaf page */
245171      i64 iLeafRowid;
245172      Fts5Data *pData;
245173      int iId = pSeg->pSeg->iSegid;
245174      u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
245175
245176      iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
245177      pData = fts5LeafRead(p, iLeafRowid);
245178      if( pData ){
245179        if( iOff>pData->szLeaf ){
245180          /* This can occur if the pages that the segments occupy overlap - if
245181          ** a single page has been assigned to more than one segment. In
245182          ** this case a prior iteration of this loop may have corrupted the
245183          ** segment currently being trimmed.  */
245184          p->rc = FTS5_CORRUPT;
245185        }else{
245186          fts5BufferZero(&buf);
245187          fts5BufferGrow(&p->rc, &buf, pData->nn);
245188          fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
245189          fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
245190          fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
245191          fts5BufferAppendBlob(&p->rc, &buf,pData->szLeaf-iOff,&pData->p[iOff]);
245192          if( p->rc==SQLITE_OK ){
245193            /* Set the szLeaf field */
245194            fts5PutU16(&buf.p[2], (u16)buf.n);
245195          }
245196
245197          /* Set up the new page-index array */
245198          fts5BufferAppendVarint(&p->rc, &buf, 4);
245199          if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
245200           && pSeg->iEndofDoclist<pData->szLeaf
245201           && pSeg->iPgidxOff<=pData->nn
245202          ){
245203            int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
245204            fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
245205            fts5BufferAppendBlob(&p->rc, &buf,
245206                pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
245207            );
245208          }
245209
245210          pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
245211          fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
245212          fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
245213        }
245214        fts5DataRelease(pData);
245215      }
245216    }
245217  }
245218  fts5BufferFree(&buf);
245219}
245220
245221static void fts5MergeChunkCallback(
245222  Fts5Index *p,
245223  void *pCtx,
245224  const u8 *pChunk, int nChunk
245225){
245226  Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
245227  fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
245228}
245229
245230/*
245231**
245232*/
245233static void fts5IndexMergeLevel(
245234  Fts5Index *p,                   /* FTS5 backend object */
245235  Fts5Structure **ppStruct,       /* IN/OUT: Stucture of index */
245236  int iLvl,                       /* Level to read input from */
245237  int *pnRem                      /* Write up to this many output leaves */
245238){
245239  Fts5Structure *pStruct = *ppStruct;
245240  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
245241  Fts5StructureLevel *pLvlOut;
245242  Fts5Iter *pIter = 0;       /* Iterator to read input data */
245243  int nRem = pnRem ? *pnRem : 0;  /* Output leaf pages left to write */
245244  int nInput;                     /* Number of input segments */
245245  Fts5SegWriter writer;           /* Writer object */
245246  Fts5StructureSegment *pSeg;     /* Output segment */
245247  Fts5Buffer term;
245248  int bOldest;                    /* True if the output segment is the oldest */
245249  int eDetail = p->pConfig->eDetail;
245250  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
245251  int bTermWritten = 0;           /* True if current term already output */
245252
245253  assert( iLvl<pStruct->nLevel );
245254  assert( pLvl->nMerge<=pLvl->nSeg );
245255
245256  memset(&writer, 0, sizeof(Fts5SegWriter));
245257  memset(&term, 0, sizeof(Fts5Buffer));
245258  if( pLvl->nMerge ){
245259    pLvlOut = &pStruct->aLevel[iLvl+1];
245260    assert( pLvlOut->nSeg>0 );
245261    nInput = pLvl->nMerge;
245262    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
245263
245264    fts5WriteInit(p, &writer, pSeg->iSegid);
245265    writer.writer.pgno = pSeg->pgnoLast+1;
245266    writer.iBtPage = 0;
245267  }else{
245268    int iSegid = fts5AllocateSegid(p, pStruct);
245269
245270    /* Extend the Fts5Structure object as required to ensure the output
245271    ** segment exists. */
245272    if( iLvl==pStruct->nLevel-1 ){
245273      fts5StructureAddLevel(&p->rc, ppStruct);
245274      pStruct = *ppStruct;
245275    }
245276    fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
245277    if( p->rc ) return;
245278    pLvl = &pStruct->aLevel[iLvl];
245279    pLvlOut = &pStruct->aLevel[iLvl+1];
245280
245281    fts5WriteInit(p, &writer, iSegid);
245282
245283    /* Add the new segment to the output level */
245284    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
245285    pLvlOut->nSeg++;
245286    pSeg->pgnoFirst = 1;
245287    pSeg->iSegid = iSegid;
245288    pStruct->nSegment++;
245289
245290    /* Read input from all segments in the input level */
245291    nInput = pLvl->nSeg;
245292
245293    /* Set the range of origins that will go into the output segment. */
245294    if( pStruct->nOriginCntr>0 ){
245295      pSeg->iOrigin1 = pLvl->aSeg[0].iOrigin1;
245296      pSeg->iOrigin2 = pLvl->aSeg[pLvl->nSeg-1].iOrigin2;
245297    }
245298  }
245299  bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
245300
245301  assert( iLvl>=0 );
245302  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
245303      fts5MultiIterEof(p, pIter)==0;
245304      fts5MultiIterNext(p, pIter, 0, 0)
245305  ){
245306    Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
245307    int nPos;                     /* position-list size field value */
245308    int nTerm;
245309    const u8 *pTerm;
245310
245311    pTerm = fts5MultiIterTerm(pIter, &nTerm);
245312    if( nTerm!=term.n || fts5Memcmp(pTerm, term.p, nTerm) ){
245313      if( pnRem && writer.nLeafWritten>nRem ){
245314        break;
245315      }
245316      fts5BufferSet(&p->rc, &term, nTerm, pTerm);
245317      bTermWritten =0;
245318    }
245319
245320    /* Check for key annihilation. */
245321    if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
245322
245323    if( p->rc==SQLITE_OK && bTermWritten==0 ){
245324      /* This is a new term. Append a term to the output segment. */
245325      fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
245326      bTermWritten = 1;
245327    }
245328
245329    /* Append the rowid to the output */
245330    /* WRITEPOSLISTSIZE */
245331    fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
245332
245333    if( eDetail==FTS5_DETAIL_NONE ){
245334      if( pSegIter->bDel ){
245335        fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
245336        if( pSegIter->nPos>0 ){
245337          fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
245338        }
245339      }
245340    }else{
245341      /* Append the position-list data to the output */
245342      nPos = pSegIter->nPos*2 + pSegIter->bDel;
245343      fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
245344      fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
245345    }
245346  }
245347
245348  /* Flush the last leaf page to disk. Set the output segment b-tree height
245349  ** and last leaf page number at the same time.  */
245350  fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
245351
245352  assert( pIter!=0 || p->rc!=SQLITE_OK );
245353  if( fts5MultiIterEof(p, pIter) ){
245354    int i;
245355
245356    /* Remove the redundant segments from the %_data table */
245357    assert( pSeg->nEntry==0 );
245358    for(i=0; i<nInput; i++){
245359      Fts5StructureSegment *pOld = &pLvl->aSeg[i];
245360      pSeg->nEntry += (pOld->nEntry - pOld->nEntryTombstone);
245361      fts5DataRemoveSegment(p, pOld);
245362    }
245363
245364    /* Remove the redundant segments from the input level */
245365    if( pLvl->nSeg!=nInput ){
245366      int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
245367      memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
245368    }
245369    pStruct->nSegment -= nInput;
245370    pLvl->nSeg -= nInput;
245371    pLvl->nMerge = 0;
245372    if( pSeg->pgnoLast==0 ){
245373      pLvlOut->nSeg--;
245374      pStruct->nSegment--;
245375    }
245376  }else{
245377    assert( pSeg->pgnoLast>0 );
245378    fts5TrimSegments(p, pIter);
245379    pLvl->nMerge = nInput;
245380  }
245381
245382  fts5MultiIterFree(pIter);
245383  fts5BufferFree(&term);
245384  if( pnRem ) *pnRem -= writer.nLeafWritten;
245385}
245386
245387/*
245388** If this is not a contentless_delete=1 table, or if the 'deletemerge'
245389** configuration option is set to 0, then this function always returns -1.
245390** Otherwise, it searches the structure object passed as the second argument
245391** for a level suitable for merging due to having a large number of
245392** tombstones in the tombstone hash. If one is found, its index is returned.
245393** Otherwise, if there is no suitable level, -1.
245394*/
245395static int fts5IndexFindDeleteMerge(Fts5Index *p, Fts5Structure *pStruct){
245396  Fts5Config *pConfig = p->pConfig;
245397  int iRet = -1;
245398  if( pConfig->bContentlessDelete && pConfig->nDeleteMerge>0 ){
245399    int ii;
245400    int nBest = 0;
245401
245402    for(ii=0; ii<pStruct->nLevel; ii++){
245403      Fts5StructureLevel *pLvl = &pStruct->aLevel[ii];
245404      i64 nEntry = 0;
245405      i64 nTomb = 0;
245406      int iSeg;
245407      for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
245408        nEntry += pLvl->aSeg[iSeg].nEntry;
245409        nTomb += pLvl->aSeg[iSeg].nEntryTombstone;
245410      }
245411      assert_nc( nEntry>0 || pLvl->nSeg==0 );
245412      if( nEntry>0 ){
245413        int nPercent = (nTomb * 100) / nEntry;
245414        if( nPercent>=pConfig->nDeleteMerge && nPercent>nBest ){
245415          iRet = ii;
245416          nBest = nPercent;
245417        }
245418      }
245419    }
245420  }
245421  return iRet;
245422}
245423
245424/*
245425** Do up to nPg pages of automerge work on the index.
245426**
245427** Return true if any changes were actually made, or false otherwise.
245428*/
245429static int fts5IndexMerge(
245430  Fts5Index *p,                   /* FTS5 backend object */
245431  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
245432  int nPg,                        /* Pages of work to do */
245433  int nMin                        /* Minimum number of segments to merge */
245434){
245435  int nRem = nPg;
245436  int bRet = 0;
245437  Fts5Structure *pStruct = *ppStruct;
245438  while( nRem>0 && p->rc==SQLITE_OK ){
245439    int iLvl;                   /* To iterate through levels */
245440    int iBestLvl = 0;           /* Level offering the most input segments */
245441    int nBest = 0;              /* Number of input segments on best level */
245442
245443    /* Set iBestLvl to the level to read input segments from. Or to -1 if
245444    ** there is no level suitable to merge segments from.  */
245445    assert( pStruct->nLevel>0 );
245446    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
245447      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
245448      if( pLvl->nMerge ){
245449        if( pLvl->nMerge>nBest ){
245450          iBestLvl = iLvl;
245451          nBest = nMin;
245452        }
245453        break;
245454      }
245455      if( pLvl->nSeg>nBest ){
245456        nBest = pLvl->nSeg;
245457        iBestLvl = iLvl;
245458      }
245459    }
245460    if( nBest<nMin ){
245461      iBestLvl = fts5IndexFindDeleteMerge(p, pStruct);
245462    }
245463
245464    if( iBestLvl<0 ) break;
245465    bRet = 1;
245466    fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
245467    if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
245468      fts5StructurePromote(p, iBestLvl+1, pStruct);
245469    }
245470
245471    if( nMin==1 ) nMin = 2;
245472  }
245473  *ppStruct = pStruct;
245474  return bRet;
245475}
245476
245477/*
245478** A total of nLeaf leaf pages of data has just been flushed to a level-0
245479** segment. This function updates the write-counter accordingly and, if
245480** necessary, performs incremental merge work.
245481**
245482** If an error occurs, set the Fts5Index.rc error code. If an error has
245483** already occurred, this function is a no-op.
245484*/
245485static void fts5IndexAutomerge(
245486  Fts5Index *p,                   /* FTS5 backend object */
245487  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
245488  int nLeaf                       /* Number of output leaves just written */
245489){
245490  if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 && ALWAYS((*ppStruct)!=0) ){
245491    Fts5Structure *pStruct = *ppStruct;
245492    u64 nWrite;                   /* Initial value of write-counter */
245493    int nWork;                    /* Number of work-quanta to perform */
245494    int nRem;                     /* Number of leaf pages left to write */
245495
245496    /* Update the write-counter. While doing so, set nWork. */
245497    nWrite = pStruct->nWriteCounter;
245498    nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
245499    pStruct->nWriteCounter += nLeaf;
245500    nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
245501
245502    fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
245503  }
245504}
245505
245506static void fts5IndexCrisismerge(
245507  Fts5Index *p,                   /* FTS5 backend object */
245508  Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */
245509){
245510  const int nCrisis = p->pConfig->nCrisisMerge;
245511  Fts5Structure *pStruct = *ppStruct;
245512  if( pStruct && pStruct->nLevel>0 ){
245513    int iLvl = 0;
245514    while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
245515      fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
245516      assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
245517      fts5StructurePromote(p, iLvl+1, pStruct);
245518      iLvl++;
245519    }
245520    *ppStruct = pStruct;
245521  }
245522}
245523
245524static int fts5IndexReturn(Fts5Index *p){
245525  int rc = p->rc;
245526  p->rc = SQLITE_OK;
245527  return rc;
245528}
245529
245530typedef struct Fts5FlushCtx Fts5FlushCtx;
245531struct Fts5FlushCtx {
245532  Fts5Index *pIdx;
245533  Fts5SegWriter writer;
245534};
245535
245536/*
245537** Buffer aBuf[] contains a list of varints, all small enough to fit
245538** in a 32-bit integer. Return the size of the largest prefix of this
245539** list nMax bytes or less in size.
245540*/
245541static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
245542  int ret;
245543  u32 dummy;
245544  ret = fts5GetVarint32(aBuf, dummy);
245545  if( ret<nMax ){
245546    while( 1 ){
245547      int i = fts5GetVarint32(&aBuf[ret], dummy);
245548      if( (ret + i) > nMax ) break;
245549      ret += i;
245550    }
245551  }
245552  return ret;
245553}
245554
245555/*
245556** Execute the SQL statement:
245557**
245558**    DELETE FROM %_idx WHERE (segid, (pgno/2)) = ($iSegid, $iPgno);
245559**
245560** This is used when a secure-delete operation removes the last term
245561** from a segment leaf page. In that case the %_idx entry is removed
245562** too. This is done to ensure that if all instances of a token are
245563** removed from an fts5 database in secure-delete mode, no trace of
245564** the token itself remains in the database.
245565*/
245566static void fts5SecureDeleteIdxEntry(
245567  Fts5Index *p,                   /* FTS5 backend object */
245568  int iSegid,                     /* Id of segment to delete entry for */
245569  int iPgno                       /* Page number within segment */
245570){
245571  if( iPgno!=1 ){
245572    assert( p->pConfig->iVersion==FTS5_CURRENT_VERSION_SECUREDELETE );
245573    if( p->pDeleteFromIdx==0 ){
245574      fts5IndexPrepareStmt(p, &p->pDeleteFromIdx, sqlite3_mprintf(
245575          "DELETE FROM '%q'.'%q_idx' WHERE (segid, (pgno/2)) = (?1, ?2)",
245576          p->pConfig->zDb, p->pConfig->zName
245577      ));
245578    }
245579    if( p->rc==SQLITE_OK ){
245580      sqlite3_bind_int(p->pDeleteFromIdx, 1, iSegid);
245581      sqlite3_bind_int(p->pDeleteFromIdx, 2, iPgno);
245582      sqlite3_step(p->pDeleteFromIdx);
245583      p->rc = sqlite3_reset(p->pDeleteFromIdx);
245584    }
245585  }
245586}
245587
245588/*
245589** This is called when a secure-delete operation removes a position-list
245590** that overflows onto segment page iPgno of segment pSeg. This function
245591** rewrites node iPgno, and possibly one or more of its right-hand peers,
245592** to remove this portion of the position list.
245593**
245594** Output variable (*pbLastInDoclist) is set to true if the position-list
245595** removed is followed by a new term or the end-of-segment, or false if
245596** it is followed by another rowid/position list.
245597*/
245598static void fts5SecureDeleteOverflow(
245599  Fts5Index *p,
245600  Fts5StructureSegment *pSeg,
245601  int iPgno,
245602  int *pbLastInDoclist
245603){
245604  const int bDetailNone = (p->pConfig->eDetail==FTS5_DETAIL_NONE);
245605  int pgno;
245606  Fts5Data *pLeaf = 0;
245607  assert( iPgno!=1 );
245608
245609  *pbLastInDoclist = 1;
245610  for(pgno=iPgno; p->rc==SQLITE_OK && pgno<=pSeg->pgnoLast; pgno++){
245611    i64 iRowid = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
245612    int iNext = 0;
245613    u8 *aPg = 0;
245614
245615    pLeaf = fts5DataRead(p, iRowid);
245616    if( pLeaf==0 ) break;
245617    aPg = pLeaf->p;
245618
245619    iNext = fts5GetU16(&aPg[0]);
245620    if( iNext!=0 ){
245621      *pbLastInDoclist = 0;
245622    }
245623    if( iNext==0 && pLeaf->szLeaf!=pLeaf->nn ){
245624      fts5GetVarint32(&aPg[pLeaf->szLeaf], iNext);
245625    }
245626
245627    if( iNext==0 ){
245628      /* The page contains no terms or rowids. Replace it with an empty
245629      ** page and move on to the right-hand peer.  */
245630      const u8 aEmpty[] = {0x00, 0x00, 0x00, 0x04};
245631      assert_nc( bDetailNone==0 || pLeaf->nn==4 );
245632      if( bDetailNone==0 ) fts5DataWrite(p, iRowid, aEmpty, sizeof(aEmpty));
245633      fts5DataRelease(pLeaf);
245634      pLeaf = 0;
245635    }else if( bDetailNone ){
245636      break;
245637    }else if( iNext>=pLeaf->szLeaf || pLeaf->nn<pLeaf->szLeaf || iNext<4 ){
245638      p->rc = FTS5_CORRUPT;
245639      break;
245640    }else{
245641      int nShift = iNext - 4;
245642      int nPg;
245643
245644      int nIdx = 0;
245645      u8 *aIdx = 0;
245646
245647      /* Unless the current page footer is 0 bytes in size (in which case
245648      ** the new page footer will be as well), allocate and populate a
245649      ** buffer containing the new page footer. Set stack variables aIdx
245650      ** and nIdx accordingly.  */
245651      if( pLeaf->nn>pLeaf->szLeaf ){
245652        int iFirst = 0;
245653        int i1 = pLeaf->szLeaf;
245654        int i2 = 0;
245655
245656        i1 += fts5GetVarint32(&aPg[i1], iFirst);
245657        if( iFirst<iNext ){
245658          p->rc = FTS5_CORRUPT;
245659          break;
245660        }
245661        aIdx = sqlite3Fts5MallocZero(&p->rc, (pLeaf->nn-pLeaf->szLeaf)+2);
245662        if( aIdx==0 ) break;
245663        i2 = sqlite3Fts5PutVarint(aIdx, iFirst-nShift);
245664        if( i1<pLeaf->nn ){
245665          memcpy(&aIdx[i2], &aPg[i1], pLeaf->nn-i1);
245666          i2 += (pLeaf->nn-i1);
245667        }
245668        nIdx = i2;
245669      }
245670
245671      /* Modify the contents of buffer aPg[]. Set nPg to the new size
245672      ** in bytes. The new page is always smaller than the old.  */
245673      nPg = pLeaf->szLeaf - nShift;
245674      memmove(&aPg[4], &aPg[4+nShift], nPg-4);
245675      fts5PutU16(&aPg[2], nPg);
245676      if( fts5GetU16(&aPg[0]) ) fts5PutU16(&aPg[0], 4);
245677      if( nIdx>0 ){
245678        memcpy(&aPg[nPg], aIdx, nIdx);
245679        nPg += nIdx;
245680      }
245681      sqlite3_free(aIdx);
245682
245683      /* Write the new page to disk and exit the loop */
245684      assert( nPg>4 || fts5GetU16(aPg)==0 );
245685      fts5DataWrite(p, iRowid, aPg, nPg);
245686      break;
245687    }
245688  }
245689  fts5DataRelease(pLeaf);
245690}
245691
245692/*
245693** Completely remove the entry that pSeg currently points to from
245694** the database.
245695*/
245696static void fts5DoSecureDelete(
245697  Fts5Index *p,
245698  Fts5SegIter *pSeg
245699){
245700  const int bDetailNone = (p->pConfig->eDetail==FTS5_DETAIL_NONE);
245701  int iSegid = pSeg->pSeg->iSegid;
245702  u8 *aPg = pSeg->pLeaf->p;
245703  int nPg = pSeg->pLeaf->nn;
245704  int iPgIdx = pSeg->pLeaf->szLeaf;
245705
245706  u64 iDelta = 0;
245707  int iNextOff = 0;
245708  int iOff = 0;
245709  int nIdx = 0;
245710  u8 *aIdx = 0;
245711  int bLastInDoclist = 0;
245712  int iIdx = 0;
245713  int iStart = 0;
245714  int iDelKeyOff = 0;       /* Offset of deleted key, if any */
245715
245716  nIdx = nPg-iPgIdx;
245717  aIdx = sqlite3Fts5MallocZero(&p->rc, nIdx+16);
245718  if( p->rc ) return;
245719  memcpy(aIdx, &aPg[iPgIdx], nIdx);
245720
245721  /* At this point segment iterator pSeg points to the entry
245722  ** this function should remove from the b-tree segment.
245723  **
245724  ** In detail=full or detail=column mode, pSeg->iLeafOffset is the
245725  ** offset of the first byte in the position-list for the entry to
245726  ** remove. Immediately before this comes two varints that will also
245727  ** need to be removed:
245728  **
245729  **     + the rowid or delta rowid value for the entry, and
245730  **     + the size of the position list in bytes.
245731  **
245732  ** Or, in detail=none mode, there is a single varint prior to
245733  ** pSeg->iLeafOffset - the rowid or delta rowid value.
245734  **
245735  ** This block sets the following variables:
245736  **
245737  **   iStart:
245738  **     The offset of the first byte of the rowid or delta-rowid
245739  **     value for the doclist entry being removed.
245740  **
245741  **   iDelta:
245742  **     The value of the rowid or delta-rowid value for the doclist
245743  **     entry being removed.
245744  **
245745  **   iNextOff:
245746  **     The offset of the next entry following the position list
245747  **     for the one being removed. If the position list for this
245748  **     entry overflows onto the next leaf page, this value will be
245749  **     greater than pLeaf->szLeaf.
245750  */
245751  {
245752    int iSOP;                     /* Start-Of-Position-list */
245753    if( pSeg->iLeafPgno==pSeg->iTermLeafPgno ){
245754      iStart = pSeg->iTermLeafOffset;
245755    }else{
245756      iStart = fts5GetU16(&aPg[0]);
245757    }
245758
245759    iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
245760    assert_nc( iSOP<=pSeg->iLeafOffset );
245761
245762    if( bDetailNone ){
245763      while( iSOP<pSeg->iLeafOffset ){
245764        if( aPg[iSOP]==0x00 ) iSOP++;
245765        if( aPg[iSOP]==0x00 ) iSOP++;
245766        iStart = iSOP;
245767        iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
245768      }
245769
245770      iNextOff = iSOP;
245771      if( iNextOff<pSeg->iEndofDoclist && aPg[iNextOff]==0x00 ) iNextOff++;
245772      if( iNextOff<pSeg->iEndofDoclist && aPg[iNextOff]==0x00 ) iNextOff++;
245773
245774    }else{
245775      int nPos = 0;
245776      iSOP += fts5GetVarint32(&aPg[iSOP], nPos);
245777      while( iSOP<pSeg->iLeafOffset ){
245778        iStart = iSOP + (nPos/2);
245779        iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
245780        iSOP += fts5GetVarint32(&aPg[iSOP], nPos);
245781      }
245782      assert_nc( iSOP==pSeg->iLeafOffset );
245783      iNextOff = pSeg->iLeafOffset + pSeg->nPos;
245784    }
245785  }
245786
245787  iOff = iStart;
245788
245789  /* If the position-list for the entry being removed flows over past
245790  ** the end of this page, delete the portion of the position-list on the
245791  ** next page and beyond.
245792  **
245793  ** Set variable bLastInDoclist to true if this entry happens
245794  ** to be the last rowid in the doclist for its term.  */
245795  if( iNextOff>=iPgIdx ){
245796    int pgno = pSeg->iLeafPgno+1;
245797    fts5SecureDeleteOverflow(p, pSeg->pSeg, pgno, &bLastInDoclist);
245798    iNextOff = iPgIdx;
245799  }
245800
245801  if( pSeg->bDel==0 ){
245802    if( iNextOff!=iPgIdx ){
245803      /* Loop through the page-footer. If iNextOff (offset of the
245804      ** entry following the one we are removing) is equal to the
245805      ** offset of a key on this page, then the entry is the last
245806      ** in its doclist. */
245807      int iKeyOff = 0;
245808      for(iIdx=0; iIdx<nIdx; /* no-op */){
245809        u32 iVal = 0;
245810        iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
245811        iKeyOff += iVal;
245812        if( iKeyOff==iNextOff ){
245813          bLastInDoclist = 1;
245814        }
245815      }
245816    }
245817
245818    /* If this is (a) the first rowid on a page and (b) is not followed by
245819    ** another position list on the same page, set the "first-rowid" field
245820    ** of the header to 0.  */
245821    if( fts5GetU16(&aPg[0])==iStart && (bLastInDoclist || iNextOff==iPgIdx) ){
245822      fts5PutU16(&aPg[0], 0);
245823    }
245824  }
245825
245826  if( pSeg->bDel ){
245827    iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta);
245828    aPg[iOff++] = 0x01;
245829  }else if( bLastInDoclist==0 ){
245830    if( iNextOff!=iPgIdx ){
245831      u64 iNextDelta = 0;
245832      iNextOff += fts5GetVarint(&aPg[iNextOff], &iNextDelta);
245833      iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta + iNextDelta);
245834    }
245835  }else if(
245836      pSeg->iLeafPgno==pSeg->iTermLeafPgno
245837   && iStart==pSeg->iTermLeafOffset
245838  ){
245839    /* The entry being removed was the only position list in its
245840    ** doclist. Therefore the term needs to be removed as well. */
245841    int iKey = 0;
245842    int iKeyOff = 0;
245843
245844    /* Set iKeyOff to the offset of the term that will be removed - the
245845    ** last offset in the footer that is not greater than iStart. */
245846    for(iIdx=0; iIdx<nIdx; iKey++){
245847      u32 iVal = 0;
245848      iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
245849      if( (iKeyOff+iVal)>(u32)iStart ) break;
245850      iKeyOff += iVal;
245851    }
245852    assert_nc( iKey>=1 );
245853
245854    /* Set iDelKeyOff to the value of the footer entry to remove from
245855    ** the page. */
245856    iDelKeyOff = iOff = iKeyOff;
245857
245858    if( iNextOff!=iPgIdx ){
245859      /* This is the only position-list associated with the term, and there
245860      ** is another term following it on this page. So the subsequent term
245861      ** needs to be moved to replace the term associated with the entry
245862      ** being removed. */
245863      int nPrefix = 0;
245864      int nSuffix = 0;
245865      int nPrefix2 = 0;
245866      int nSuffix2 = 0;
245867
245868      iDelKeyOff = iNextOff;
245869      iNextOff += fts5GetVarint32(&aPg[iNextOff], nPrefix2);
245870      iNextOff += fts5GetVarint32(&aPg[iNextOff], nSuffix2);
245871
245872      if( iKey!=1 ){
245873        iKeyOff += fts5GetVarint32(&aPg[iKeyOff], nPrefix);
245874      }
245875      iKeyOff += fts5GetVarint32(&aPg[iKeyOff], nSuffix);
245876
245877      nPrefix = MIN(nPrefix, nPrefix2);
245878      nSuffix = (nPrefix2 + nSuffix2) - nPrefix;
245879
245880      if( (iKeyOff+nSuffix)>iPgIdx || (iNextOff+nSuffix2)>iPgIdx ){
245881        p->rc = FTS5_CORRUPT;
245882      }else{
245883        if( iKey!=1 ){
245884          iOff += sqlite3Fts5PutVarint(&aPg[iOff], nPrefix);
245885        }
245886        iOff += sqlite3Fts5PutVarint(&aPg[iOff], nSuffix);
245887        if( nPrefix2>pSeg->term.n ){
245888          p->rc = FTS5_CORRUPT;
245889        }else if( nPrefix2>nPrefix ){
245890          memcpy(&aPg[iOff], &pSeg->term.p[nPrefix], nPrefix2-nPrefix);
245891          iOff += (nPrefix2-nPrefix);
245892        }
245893        memmove(&aPg[iOff], &aPg[iNextOff], nSuffix2);
245894        iOff += nSuffix2;
245895        iNextOff += nSuffix2;
245896      }
245897    }
245898  }else if( iStart==4 ){
245899    int iPgno;
245900
245901    assert_nc( pSeg->iLeafPgno>pSeg->iTermLeafPgno );
245902    /* The entry being removed may be the only position list in
245903    ** its doclist. */
245904    for(iPgno=pSeg->iLeafPgno-1; iPgno>pSeg->iTermLeafPgno; iPgno-- ){
245905      Fts5Data *pPg = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, iPgno));
245906      int bEmpty = (pPg && pPg->nn==4);
245907      fts5DataRelease(pPg);
245908      if( bEmpty==0 ) break;
245909    }
245910
245911    if( iPgno==pSeg->iTermLeafPgno ){
245912      i64 iId = FTS5_SEGMENT_ROWID(iSegid, pSeg->iTermLeafPgno);
245913      Fts5Data *pTerm = fts5DataRead(p, iId);
245914      if( pTerm && pTerm->szLeaf==pSeg->iTermLeafOffset ){
245915        u8 *aTermIdx = &pTerm->p[pTerm->szLeaf];
245916        int nTermIdx = pTerm->nn - pTerm->szLeaf;
245917        int iTermIdx = 0;
245918        int iTermOff = 0;
245919
245920        while( 1 ){
245921          u32 iVal = 0;
245922          int nByte = fts5GetVarint32(&aTermIdx[iTermIdx], iVal);
245923          iTermOff += iVal;
245924          if( (iTermIdx+nByte)>=nTermIdx ) break;
245925          iTermIdx += nByte;
245926        }
245927        nTermIdx = iTermIdx;
245928
245929        memmove(&pTerm->p[iTermOff], &pTerm->p[pTerm->szLeaf], nTermIdx);
245930        fts5PutU16(&pTerm->p[2], iTermOff);
245931
245932        fts5DataWrite(p, iId, pTerm->p, iTermOff+nTermIdx);
245933        if( nTermIdx==0 ){
245934          fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iTermLeafPgno);
245935        }
245936      }
245937      fts5DataRelease(pTerm);
245938    }
245939  }
245940
245941  /* Assuming no error has occurred, this block does final edits to the
245942  ** leaf page before writing it back to disk. Input variables are:
245943  **
245944  **   nPg: Total initial size of leaf page.
245945  **   iPgIdx: Initial offset of page footer.
245946  **
245947  **   iOff: Offset to move data to
245948  **   iNextOff: Offset to move data from
245949  */
245950  if( p->rc==SQLITE_OK ){
245951    const int nMove = nPg - iNextOff;     /* Number of bytes to move */
245952    int nShift = iNextOff - iOff;         /* Distance to move them */
245953
245954    int iPrevKeyOut = 0;
245955    int iKeyIn = 0;
245956
245957    memmove(&aPg[iOff], &aPg[iNextOff], nMove);
245958    iPgIdx -= nShift;
245959    nPg = iPgIdx;
245960    fts5PutU16(&aPg[2], iPgIdx);
245961
245962    for(iIdx=0; iIdx<nIdx; /* no-op */){
245963      u32 iVal = 0;
245964      iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
245965      iKeyIn += iVal;
245966      if( iKeyIn!=iDelKeyOff ){
245967        int iKeyOut = (iKeyIn - (iKeyIn>iOff ? nShift : 0));
245968        nPg += sqlite3Fts5PutVarint(&aPg[nPg], iKeyOut - iPrevKeyOut);
245969        iPrevKeyOut = iKeyOut;
245970      }
245971    }
245972
245973    if( iPgIdx==nPg && nIdx>0 && pSeg->iLeafPgno!=1 ){
245974      fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iLeafPgno);
245975    }
245976
245977    assert_nc( nPg>4 || fts5GetU16(aPg)==0 );
245978    fts5DataWrite(p, FTS5_SEGMENT_ROWID(iSegid,pSeg->iLeafPgno), aPg, nPg);
245979  }
245980  sqlite3_free(aIdx);
245981}
245982
245983/*
245984** This is called as part of flushing a delete to disk in 'secure-delete'
245985** mode. It edits the segments within the database described by argument
245986** pStruct to remove the entries for term zTerm, rowid iRowid.
245987*/
245988static void fts5FlushSecureDelete(
245989  Fts5Index *p,
245990  Fts5Structure *pStruct,
245991  const char *zTerm,
245992  int nTerm,
245993  i64 iRowid
245994){
245995  const int f = FTS5INDEX_QUERY_SKIPHASH;
245996  Fts5Iter *pIter = 0;            /* Used to find term instance */
245997
245998  fts5MultiIterNew(p, pStruct, f, 0, (const u8*)zTerm, nTerm, -1, 0, &pIter);
245999  if( fts5MultiIterEof(p, pIter)==0 ){
246000    i64 iThis = fts5MultiIterRowid(pIter);
246001    if( iThis<iRowid ){
246002      fts5MultiIterNextFrom(p, pIter, iRowid);
246003    }
246004
246005    if( p->rc==SQLITE_OK
246006     && fts5MultiIterEof(p, pIter)==0
246007     && iRowid==fts5MultiIterRowid(pIter)
246008    ){
246009      Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
246010      fts5DoSecureDelete(p, pSeg);
246011    }
246012  }
246013
246014  fts5MultiIterFree(pIter);
246015}
246016
246017
246018/*
246019** Flush the contents of in-memory hash table iHash to a new level-0
246020** segment on disk. Also update the corresponding structure record.
246021**
246022** If an error occurs, set the Fts5Index.rc error code. If an error has
246023** already occurred, this function is a no-op.
246024*/
246025static void fts5FlushOneHash(Fts5Index *p){
246026  Fts5Hash *pHash = p->pHash;
246027  Fts5Structure *pStruct;
246028  int iSegid;
246029  int pgnoLast = 0;                 /* Last leaf page number in segment */
246030
246031  /* Obtain a reference to the index structure and allocate a new segment-id
246032  ** for the new level-0 segment.  */
246033  pStruct = fts5StructureRead(p);
246034  fts5StructureInvalidate(p);
246035
246036  if( sqlite3Fts5HashIsEmpty(pHash)==0 ){
246037    iSegid = fts5AllocateSegid(p, pStruct);
246038    if( iSegid ){
246039      const int pgsz = p->pConfig->pgsz;
246040      int eDetail = p->pConfig->eDetail;
246041      int bSecureDelete = p->pConfig->bSecureDelete;
246042      Fts5StructureSegment *pSeg; /* New segment within pStruct */
246043      Fts5Buffer *pBuf;           /* Buffer in which to assemble leaf page */
246044      Fts5Buffer *pPgidx;         /* Buffer in which to assemble pgidx */
246045
246046      Fts5SegWriter writer;
246047      fts5WriteInit(p, &writer, iSegid);
246048
246049      pBuf = &writer.writer.buf;
246050      pPgidx = &writer.writer.pgidx;
246051
246052      /* fts5WriteInit() should have initialized the buffers to (most likely)
246053      ** the maximum space required. */
246054      assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
246055      assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
246056
246057      /* Begin scanning through hash table entries. This loop runs once for each
246058      ** term/doclist currently stored within the hash table. */
246059      if( p->rc==SQLITE_OK ){
246060        p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
246061      }
246062      while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
246063        const char *zTerm;        /* Buffer containing term */
246064        int nTerm;                /* Size of zTerm in bytes */
246065        const u8 *pDoclist;       /* Pointer to doclist for this term */
246066        int nDoclist;             /* Size of doclist in bytes */
246067
246068        /* Get the term and doclist for this entry. */
246069        sqlite3Fts5HashScanEntry(pHash, &zTerm, &nTerm, &pDoclist, &nDoclist);
246070        if( bSecureDelete==0 ){
246071          fts5WriteAppendTerm(p, &writer, nTerm, (const u8*)zTerm);
246072          if( p->rc!=SQLITE_OK ) break;
246073          assert( writer.bFirstRowidInPage==0 );
246074        }
246075
246076        if( !bSecureDelete && pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
246077          /* The entire doclist will fit on the current leaf. */
246078          fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
246079        }else{
246080          int bTermWritten = !bSecureDelete;
246081          i64 iRowid = 0;
246082          i64 iPrev = 0;
246083          int iOff = 0;
246084
246085          /* The entire doclist will not fit on this leaf. The following
246086          ** loop iterates through the poslists that make up the current
246087          ** doclist.  */
246088          while( p->rc==SQLITE_OK && iOff<nDoclist ){
246089            u64 iDelta = 0;
246090            iOff += fts5GetVarint(&pDoclist[iOff], &iDelta);
246091            iRowid += iDelta;
246092
246093            /* If in secure delete mode, and if this entry in the poslist is
246094            ** in fact a delete, then edit the existing segments directly
246095            ** using fts5FlushSecureDelete().  */
246096            if( bSecureDelete ){
246097              if( eDetail==FTS5_DETAIL_NONE ){
246098                if( iOff<nDoclist && pDoclist[iOff]==0x00 ){
246099                  fts5FlushSecureDelete(p, pStruct, zTerm, nTerm, iRowid);
246100                  iOff++;
246101                  if( iOff<nDoclist && pDoclist[iOff]==0x00 ){
246102                    iOff++;
246103                    nDoclist = 0;
246104                  }else{
246105                    continue;
246106                  }
246107                }
246108              }else if( (pDoclist[iOff] & 0x01) ){
246109                fts5FlushSecureDelete(p, pStruct, zTerm, nTerm, iRowid);
246110                if( p->rc!=SQLITE_OK || pDoclist[iOff]==0x01 ){
246111                  iOff++;
246112                  continue;
246113                }
246114              }
246115            }
246116
246117            if( p->rc==SQLITE_OK && bTermWritten==0 ){
246118              fts5WriteAppendTerm(p, &writer, nTerm, (const u8*)zTerm);
246119              bTermWritten = 1;
246120              assert( p->rc!=SQLITE_OK || writer.bFirstRowidInPage==0 );
246121            }
246122
246123            if( writer.bFirstRowidInPage ){
246124              fts5PutU16(&pBuf->p[0], (u16)pBuf->n);   /* first rowid on page */
246125              pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
246126              writer.bFirstRowidInPage = 0;
246127              fts5WriteDlidxAppend(p, &writer, iRowid);
246128            }else{
246129              u64 iRowidDelta = (u64)iRowid - (u64)iPrev;
246130              pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowidDelta);
246131            }
246132            if( p->rc!=SQLITE_OK ) break;
246133            assert( pBuf->n<=pBuf->nSpace );
246134            iPrev = iRowid;
246135
246136            if( eDetail==FTS5_DETAIL_NONE ){
246137              if( iOff<nDoclist && pDoclist[iOff]==0 ){
246138                pBuf->p[pBuf->n++] = 0;
246139                iOff++;
246140                if( iOff<nDoclist && pDoclist[iOff]==0 ){
246141                  pBuf->p[pBuf->n++] = 0;
246142                  iOff++;
246143                }
246144              }
246145              if( (pBuf->n + pPgidx->n)>=pgsz ){
246146                fts5WriteFlushLeaf(p, &writer);
246147              }
246148            }else{
246149              int bDel = 0;
246150              int nPos = 0;
246151              int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDel);
246152              if( bDel && bSecureDelete ){
246153                fts5BufferAppendVarint(&p->rc, pBuf, nPos*2);
246154                iOff += nCopy;
246155                nCopy = nPos;
246156              }else{
246157                nCopy += nPos;
246158              }
246159              if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
246160                /* The entire poslist will fit on the current leaf. So copy
246161                ** it in one go. */
246162                fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
246163              }else{
246164                /* The entire poslist will not fit on this leaf. So it needs
246165                ** to be broken into sections. The only qualification being
246166                ** that each varint must be stored contiguously.  */
246167                const u8 *pPoslist = &pDoclist[iOff];
246168                int iPos = 0;
246169                while( p->rc==SQLITE_OK ){
246170                  int nSpace = pgsz - pBuf->n - pPgidx->n;
246171                  int n = 0;
246172                  if( (nCopy - iPos)<=nSpace ){
246173                    n = nCopy - iPos;
246174                  }else{
246175                    n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
246176                  }
246177                  assert( n>0 );
246178                  fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
246179                  iPos += n;
246180                  if( (pBuf->n + pPgidx->n)>=pgsz ){
246181                    fts5WriteFlushLeaf(p, &writer);
246182                  }
246183                  if( iPos>=nCopy ) break;
246184                }
246185              }
246186              iOff += nCopy;
246187            }
246188          }
246189        }
246190
246191        /* TODO2: Doclist terminator written here. */
246192        /* pBuf->p[pBuf->n++] = '\0'; */
246193        assert( pBuf->n<=pBuf->nSpace );
246194        if( p->rc==SQLITE_OK ) sqlite3Fts5HashScanNext(pHash);
246195      }
246196      fts5WriteFinish(p, &writer, &pgnoLast);
246197
246198      assert( p->rc!=SQLITE_OK || bSecureDelete || pgnoLast>0 );
246199      if( pgnoLast>0 ){
246200        /* Update the Fts5Structure. It is written back to the database by the
246201        ** fts5StructureRelease() call below.  */
246202        if( pStruct->nLevel==0 ){
246203          fts5StructureAddLevel(&p->rc, &pStruct);
246204        }
246205        fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
246206        if( p->rc==SQLITE_OK ){
246207          pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
246208          pSeg->iSegid = iSegid;
246209          pSeg->pgnoFirst = 1;
246210          pSeg->pgnoLast = pgnoLast;
246211          if( pStruct->nOriginCntr>0 ){
246212            pSeg->iOrigin1 = pStruct->nOriginCntr;
246213            pSeg->iOrigin2 = pStruct->nOriginCntr;
246214            pSeg->nEntry = p->nPendingRow;
246215            pStruct->nOriginCntr++;
246216          }
246217          pStruct->nSegment++;
246218        }
246219        fts5StructurePromote(p, 0, pStruct);
246220      }
246221    }
246222  }
246223
246224  fts5IndexAutomerge(p, &pStruct, pgnoLast + p->nContentlessDelete);
246225  fts5IndexCrisismerge(p, &pStruct);
246226  fts5StructureWrite(p, pStruct);
246227  fts5StructureRelease(pStruct);
246228}
246229
246230/*
246231** Flush any data stored in the in-memory hash tables to the database.
246232*/
246233static void fts5IndexFlush(Fts5Index *p){
246234  /* Unless it is empty, flush the hash table to disk */
246235  if( p->flushRc ){
246236    p->rc = p->flushRc;
246237    return;
246238  }
246239  if( p->nPendingData || p->nContentlessDelete ){
246240    assert( p->pHash );
246241    fts5FlushOneHash(p);
246242    if( p->rc==SQLITE_OK ){
246243      sqlite3Fts5HashClear(p->pHash);
246244      p->nPendingData = 0;
246245      p->nPendingRow = 0;
246246      p->nContentlessDelete = 0;
246247    }else if( p->nPendingData || p->nContentlessDelete ){
246248      p->flushRc = p->rc;
246249    }
246250  }
246251}
246252
246253static Fts5Structure *fts5IndexOptimizeStruct(
246254  Fts5Index *p,
246255  Fts5Structure *pStruct
246256){
246257  Fts5Structure *pNew = 0;
246258  sqlite3_int64 nByte = sizeof(Fts5Structure);
246259  int nSeg = pStruct->nSegment;
246260  int i;
246261
246262  /* Figure out if this structure requires optimization. A structure does
246263  ** not require optimization if either:
246264  **
246265  **  1. it consists of fewer than two segments, or
246266  **  2. all segments are on the same level, or
246267  **  3. all segments except one are currently inputs to a merge operation.
246268  **
246269  ** In the first case, if there are no tombstone hash pages, return NULL. In
246270  ** the second, increment the ref-count on *pStruct and return a copy of the
246271  ** pointer to it.
246272  */
246273  if( nSeg==0 ) return 0;
246274  for(i=0; i<pStruct->nLevel; i++){
246275    int nThis = pStruct->aLevel[i].nSeg;
246276    int nMerge = pStruct->aLevel[i].nMerge;
246277    if( nThis>0 && (nThis==nSeg || (nThis==nSeg-1 && nMerge==nThis)) ){
246278      if( nSeg==1 && nThis==1 && pStruct->aLevel[i].aSeg[0].nPgTombstone==0 ){
246279        return 0;
246280      }
246281      fts5StructureRef(pStruct);
246282      return pStruct;
246283    }
246284    assert( pStruct->aLevel[i].nMerge<=nThis );
246285  }
246286
246287  nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
246288  pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
246289
246290  if( pNew ){
246291    Fts5StructureLevel *pLvl;
246292    nByte = nSeg * sizeof(Fts5StructureSegment);
246293    pNew->nLevel = MIN(pStruct->nLevel+1, FTS5_MAX_LEVEL);
246294    pNew->nRef = 1;
246295    pNew->nWriteCounter = pStruct->nWriteCounter;
246296    pNew->nOriginCntr = pStruct->nOriginCntr;
246297    pLvl = &pNew->aLevel[pNew->nLevel-1];
246298    pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
246299    if( pLvl->aSeg ){
246300      int iLvl, iSeg;
246301      int iSegOut = 0;
246302      /* Iterate through all segments, from oldest to newest. Add them to
246303      ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
246304      ** segment in the data structure.  */
246305      for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
246306        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
246307          pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
246308          iSegOut++;
246309        }
246310      }
246311      pNew->nSegment = pLvl->nSeg = nSeg;
246312    }else{
246313      sqlite3_free(pNew);
246314      pNew = 0;
246315    }
246316  }
246317
246318  return pNew;
246319}
246320
246321static int sqlite3Fts5IndexOptimize(Fts5Index *p){
246322  Fts5Structure *pStruct;
246323  Fts5Structure *pNew = 0;
246324
246325  assert( p->rc==SQLITE_OK );
246326  fts5IndexFlush(p);
246327  assert( p->rc!=SQLITE_OK || p->nContentlessDelete==0 );
246328  pStruct = fts5StructureRead(p);
246329  assert( p->rc!=SQLITE_OK || pStruct!=0 );
246330  fts5StructureInvalidate(p);
246331
246332  if( pStruct ){
246333    pNew = fts5IndexOptimizeStruct(p, pStruct);
246334  }
246335  fts5StructureRelease(pStruct);
246336
246337  assert( pNew==0 || pNew->nSegment>0 );
246338  if( pNew ){
246339    int iLvl;
246340    for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
246341    while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
246342      int nRem = FTS5_OPT_WORK_UNIT;
246343      fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
246344    }
246345
246346    fts5StructureWrite(p, pNew);
246347    fts5StructureRelease(pNew);
246348  }
246349
246350  return fts5IndexReturn(p);
246351}
246352
246353/*
246354** This is called to implement the special "VALUES('merge', $nMerge)"
246355** INSERT command.
246356*/
246357static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
246358  Fts5Structure *pStruct = 0;
246359
246360  fts5IndexFlush(p);
246361  pStruct = fts5StructureRead(p);
246362  if( pStruct ){
246363    int nMin = p->pConfig->nUsermerge;
246364    fts5StructureInvalidate(p);
246365    if( nMerge<0 ){
246366      Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
246367      fts5StructureRelease(pStruct);
246368      pStruct = pNew;
246369      nMin = 1;
246370      nMerge = nMerge*-1;
246371    }
246372    if( pStruct && pStruct->nLevel ){
246373      if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
246374        fts5StructureWrite(p, pStruct);
246375      }
246376    }
246377    fts5StructureRelease(pStruct);
246378  }
246379  return fts5IndexReturn(p);
246380}
246381
246382static void fts5AppendRowid(
246383  Fts5Index *p,
246384  u64 iDelta,
246385  Fts5Iter *pUnused,
246386  Fts5Buffer *pBuf
246387){
246388  UNUSED_PARAM(pUnused);
246389  fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
246390}
246391
246392static void fts5AppendPoslist(
246393  Fts5Index *p,
246394  u64 iDelta,
246395  Fts5Iter *pMulti,
246396  Fts5Buffer *pBuf
246397){
246398  int nData = pMulti->base.nData;
246399  int nByte = nData + 9 + 9 + FTS5_DATA_ZERO_PADDING;
246400  assert( nData>0 );
246401  if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nByte) ){
246402    fts5BufferSafeAppendVarint(pBuf, iDelta);
246403    fts5BufferSafeAppendVarint(pBuf, nData*2);
246404    fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
246405    memset(&pBuf->p[pBuf->n], 0, FTS5_DATA_ZERO_PADDING);
246406  }
246407}
246408
246409
246410static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
246411  u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
246412
246413  assert( pIter->aPoslist || (p==0 && pIter->aPoslist==0) );
246414  if( p>=pIter->aEof ){
246415    pIter->aPoslist = 0;
246416  }else{
246417    i64 iDelta;
246418
246419    p += fts5GetVarint(p, (u64*)&iDelta);
246420    pIter->iRowid += iDelta;
246421
246422    /* Read position list size */
246423    if( p[0] & 0x80 ){
246424      int nPos;
246425      pIter->nSize = fts5GetVarint32(p, nPos);
246426      pIter->nPoslist = (nPos>>1);
246427    }else{
246428      pIter->nPoslist = ((int)(p[0])) >> 1;
246429      pIter->nSize = 1;
246430    }
246431
246432    pIter->aPoslist = p;
246433    if( &pIter->aPoslist[pIter->nPoslist]>pIter->aEof ){
246434      pIter->aPoslist = 0;
246435    }
246436  }
246437}
246438
246439static void fts5DoclistIterInit(
246440  Fts5Buffer *pBuf,
246441  Fts5DoclistIter *pIter
246442){
246443  memset(pIter, 0, sizeof(*pIter));
246444  if( pBuf->n>0 ){
246445    pIter->aPoslist = pBuf->p;
246446    pIter->aEof = &pBuf->p[pBuf->n];
246447    fts5DoclistIterNext(pIter);
246448  }
246449}
246450
246451#if 0
246452/*
246453** Append a doclist to buffer pBuf.
246454**
246455** This function assumes that space within the buffer has already been
246456** allocated.
246457*/
246458static void fts5MergeAppendDocid(
246459  Fts5Buffer *pBuf,               /* Buffer to write to */
246460  i64 *piLastRowid,               /* IN/OUT: Previous rowid written (if any) */
246461  i64 iRowid                      /* Rowid to append */
246462){
246463  assert( pBuf->n!=0 || (*piLastRowid)==0 );
246464  fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
246465  *piLastRowid = iRowid;
246466}
246467#endif
246468
246469#define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) {                 \
246470  assert( (pBuf)->n!=0 || (iLastRowid)==0 );                             \
246471  fts5BufferSafeAppendVarint((pBuf), (u64)(iRowid) - (u64)(iLastRowid)); \
246472  (iLastRowid) = (iRowid);                                               \
246473}
246474
246475/*
246476** Swap the contents of buffer *p1 with that of *p2.
246477*/
246478static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
246479  Fts5Buffer tmp = *p1;
246480  *p1 = *p2;
246481  *p2 = tmp;
246482}
246483
246484static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
246485  int i = *piOff;
246486  if( i>=pBuf->n ){
246487    *piOff = -1;
246488  }else{
246489    u64 iVal;
246490    *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
246491    *piRowid += iVal;
246492  }
246493}
246494
246495/*
246496** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
246497** In this case the buffers consist of a delta-encoded list of rowids only.
246498*/
246499static void fts5MergeRowidLists(
246500  Fts5Index *p,                   /* FTS5 backend object */
246501  Fts5Buffer *p1,                 /* First list to merge */
246502  int nBuf,                       /* Number of entries in apBuf[] */
246503  Fts5Buffer *aBuf                /* Array of other lists to merge into p1 */
246504){
246505  int i1 = 0;
246506  int i2 = 0;
246507  i64 iRowid1 = 0;
246508  i64 iRowid2 = 0;
246509  i64 iOut = 0;
246510  Fts5Buffer *p2 = &aBuf[0];
246511  Fts5Buffer out;
246512
246513  (void)nBuf;
246514  memset(&out, 0, sizeof(out));
246515  assert( nBuf==1 );
246516  sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
246517  if( p->rc ) return;
246518
246519  fts5NextRowid(p1, &i1, &iRowid1);
246520  fts5NextRowid(p2, &i2, &iRowid2);
246521  while( i1>=0 || i2>=0 ){
246522    if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
246523      assert( iOut==0 || iRowid1>iOut );
246524      fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
246525      iOut = iRowid1;
246526      fts5NextRowid(p1, &i1, &iRowid1);
246527    }else{
246528      assert( iOut==0 || iRowid2>iOut );
246529      fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
246530      iOut = iRowid2;
246531      if( i1>=0 && iRowid1==iRowid2 ){
246532        fts5NextRowid(p1, &i1, &iRowid1);
246533      }
246534      fts5NextRowid(p2, &i2, &iRowid2);
246535    }
246536  }
246537
246538  fts5BufferSwap(&out, p1);
246539  fts5BufferFree(&out);
246540}
246541
246542typedef struct PrefixMerger PrefixMerger;
246543struct PrefixMerger {
246544  Fts5DoclistIter iter;           /* Doclist iterator */
246545  i64 iPos;                       /* For iterating through a position list */
246546  int iOff;
246547  u8 *aPos;
246548  PrefixMerger *pNext;            /* Next in docid/poslist order */
246549};
246550
246551static void fts5PrefixMergerInsertByRowid(
246552  PrefixMerger **ppHead,
246553  PrefixMerger *p
246554){
246555  if( p->iter.aPoslist ){
246556    PrefixMerger **pp = ppHead;
246557    while( *pp && p->iter.iRowid>(*pp)->iter.iRowid ){
246558      pp = &(*pp)->pNext;
246559    }
246560    p->pNext = *pp;
246561    *pp = p;
246562  }
246563}
246564
246565static void fts5PrefixMergerInsertByPosition(
246566  PrefixMerger **ppHead,
246567  PrefixMerger *p
246568){
246569  if( p->iPos>=0 ){
246570    PrefixMerger **pp = ppHead;
246571    while( *pp && p->iPos>(*pp)->iPos ){
246572      pp = &(*pp)->pNext;
246573    }
246574    p->pNext = *pp;
246575    *pp = p;
246576  }
246577}
246578
246579
246580/*
246581** Array aBuf[] contains nBuf doclists. These are all merged in with the
246582** doclist in buffer p1.
246583*/
246584static void fts5MergePrefixLists(
246585  Fts5Index *p,                   /* FTS5 backend object */
246586  Fts5Buffer *p1,                 /* First list to merge */
246587  int nBuf,                       /* Number of buffers in array aBuf[] */
246588  Fts5Buffer *aBuf                /* Other lists to merge in */
246589){
246590#define fts5PrefixMergerNextPosition(p) \
246591  sqlite3Fts5PoslistNext64((p)->aPos,(p)->iter.nPoslist,&(p)->iOff,&(p)->iPos)
246592#define FTS5_MERGE_NLIST 16
246593  PrefixMerger aMerger[FTS5_MERGE_NLIST];
246594  PrefixMerger *pHead = 0;
246595  int i;
246596  int nOut = 0;
246597  Fts5Buffer out = {0, 0, 0};
246598  Fts5Buffer tmp = {0, 0, 0};
246599  i64 iLastRowid = 0;
246600
246601  /* Initialize a doclist-iterator for each input buffer. Arrange them in
246602  ** a linked-list starting at pHead in ascending order of rowid. Avoid
246603  ** linking any iterators already at EOF into the linked list at all. */
246604  assert( nBuf+1<=(int)(sizeof(aMerger)/sizeof(aMerger[0])) );
246605  memset(aMerger, 0, sizeof(PrefixMerger)*(nBuf+1));
246606  pHead = &aMerger[nBuf];
246607  fts5DoclistIterInit(p1, &pHead->iter);
246608  for(i=0; i<nBuf; i++){
246609    fts5DoclistIterInit(&aBuf[i], &aMerger[i].iter);
246610    fts5PrefixMergerInsertByRowid(&pHead, &aMerger[i]);
246611    nOut += aBuf[i].n;
246612  }
246613  if( nOut==0 ) return;
246614  nOut += p1->n + 9 + 10*nBuf;
246615
246616  /* The maximum size of the output is equal to the sum of the
246617  ** input sizes + 1 varint (9 bytes). The extra varint is because if the
246618  ** first rowid in one input is a large negative number, and the first in
246619  ** the other a non-negative number, the delta for the non-negative
246620  ** number will be larger on disk than the literal integer value
246621  ** was.
246622  **
246623  ** Or, if the input position-lists are corrupt, then the output might
246624  ** include up to (nBuf+1) extra 10-byte positions created by interpreting -1
246625  ** (the value PoslistNext64() uses for EOF) as a position and appending
246626  ** it to the output. This can happen at most once for each input
246627  ** position-list, hence (nBuf+1) 10 byte paddings.  */
246628  if( sqlite3Fts5BufferSize(&p->rc, &out, nOut) ) return;
246629
246630  while( pHead ){
246631    fts5MergeAppendDocid(&out, iLastRowid, pHead->iter.iRowid);
246632
246633    if( pHead->pNext && iLastRowid==pHead->pNext->iter.iRowid ){
246634      /* Merge data from two or more poslists */
246635      i64 iPrev = 0;
246636      int nTmp = FTS5_DATA_ZERO_PADDING;
246637      int nMerge = 0;
246638      PrefixMerger *pSave = pHead;
246639      PrefixMerger *pThis = 0;
246640      int nTail = 0;
246641
246642      pHead = 0;
246643      while( pSave && pSave->iter.iRowid==iLastRowid ){
246644        PrefixMerger *pNext = pSave->pNext;
246645        pSave->iOff = 0;
246646        pSave->iPos = 0;
246647        pSave->aPos = &pSave->iter.aPoslist[pSave->iter.nSize];
246648        fts5PrefixMergerNextPosition(pSave);
246649        nTmp += pSave->iter.nPoslist + 10;
246650        nMerge++;
246651        fts5PrefixMergerInsertByPosition(&pHead, pSave);
246652        pSave = pNext;
246653      }
246654
246655      if( pHead==0 || pHead->pNext==0 ){
246656        p->rc = FTS5_CORRUPT;
246657        break;
246658      }
246659
246660      /* See the earlier comment in this function for an explanation of why
246661      ** corrupt input position lists might cause the output to consume
246662      ** at most nMerge*10 bytes of unexpected space. */
246663      if( sqlite3Fts5BufferSize(&p->rc, &tmp, nTmp+nMerge*10) ){
246664        break;
246665      }
246666      fts5BufferZero(&tmp);
246667
246668      pThis = pHead;
246669      pHead = pThis->pNext;
246670      sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, pThis->iPos);
246671      fts5PrefixMergerNextPosition(pThis);
246672      fts5PrefixMergerInsertByPosition(&pHead, pThis);
246673
246674      while( pHead->pNext ){
246675        pThis = pHead;
246676        if( pThis->iPos!=iPrev ){
246677          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, pThis->iPos);
246678        }
246679        fts5PrefixMergerNextPosition(pThis);
246680        pHead = pThis->pNext;
246681        fts5PrefixMergerInsertByPosition(&pHead, pThis);
246682      }
246683
246684      if( pHead->iPos!=iPrev ){
246685        sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, pHead->iPos);
246686      }
246687      nTail = pHead->iter.nPoslist - pHead->iOff;
246688
246689      /* WRITEPOSLISTSIZE */
246690      assert_nc( tmp.n+nTail<=nTmp );
246691      assert( tmp.n+nTail<=nTmp+nMerge*10 );
246692      if( tmp.n+nTail>nTmp-FTS5_DATA_ZERO_PADDING ){
246693        if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
246694        break;
246695      }
246696      fts5BufferSafeAppendVarint(&out, (tmp.n+nTail) * 2);
246697      fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
246698      if( nTail>0 ){
246699        fts5BufferSafeAppendBlob(&out, &pHead->aPos[pHead->iOff], nTail);
246700      }
246701
246702      pHead = pSave;
246703      for(i=0; i<nBuf+1; i++){
246704        PrefixMerger *pX = &aMerger[i];
246705        if( pX->iter.aPoslist && pX->iter.iRowid==iLastRowid ){
246706          fts5DoclistIterNext(&pX->iter);
246707          fts5PrefixMergerInsertByRowid(&pHead, pX);
246708        }
246709      }
246710
246711    }else{
246712      /* Copy poslist from pHead to output */
246713      PrefixMerger *pThis = pHead;
246714      Fts5DoclistIter *pI = &pThis->iter;
246715      fts5BufferSafeAppendBlob(&out, pI->aPoslist, pI->nPoslist+pI->nSize);
246716      fts5DoclistIterNext(pI);
246717      pHead = pThis->pNext;
246718      fts5PrefixMergerInsertByRowid(&pHead, pThis);
246719    }
246720  }
246721
246722  fts5BufferFree(p1);
246723  fts5BufferFree(&tmp);
246724  memset(&out.p[out.n], 0, FTS5_DATA_ZERO_PADDING);
246725  *p1 = out;
246726}
246727
246728static void fts5SetupPrefixIter(
246729  Fts5Index *p,                   /* Index to read from */
246730  int bDesc,                      /* True for "ORDER BY rowid DESC" */
246731  int iIdx,                       /* Index to scan for data */
246732  u8 *pToken,                     /* Buffer containing prefix to match */
246733  int nToken,                     /* Size of buffer pToken in bytes */
246734  Fts5Colset *pColset,            /* Restrict matches to these columns */
246735  Fts5Iter **ppIter               /* OUT: New iterator */
246736){
246737  Fts5Structure *pStruct;
246738  Fts5Buffer *aBuf;
246739  int nBuf = 32;
246740  int nMerge = 1;
246741
246742  void (*xMerge)(Fts5Index*, Fts5Buffer*, int, Fts5Buffer*);
246743  void (*xAppend)(Fts5Index*, u64, Fts5Iter*, Fts5Buffer*);
246744  if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
246745    xMerge = fts5MergeRowidLists;
246746    xAppend = fts5AppendRowid;
246747  }else{
246748    nMerge = FTS5_MERGE_NLIST-1;
246749    nBuf = nMerge*8;   /* Sufficient to merge (16^8)==(2^32) lists */
246750    xMerge = fts5MergePrefixLists;
246751    xAppend = fts5AppendPoslist;
246752  }
246753
246754  aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
246755  pStruct = fts5StructureRead(p);
246756  assert( p->rc!=SQLITE_OK || (aBuf && pStruct) );
246757
246758  if( p->rc==SQLITE_OK ){
246759    const int flags = FTS5INDEX_QUERY_SCAN
246760                    | FTS5INDEX_QUERY_SKIPEMPTY
246761                    | FTS5INDEX_QUERY_NOOUTPUT;
246762    int i;
246763    i64 iLastRowid = 0;
246764    Fts5Iter *p1 = 0;     /* Iterator used to gather data from index */
246765    Fts5Data *pData;
246766    Fts5Buffer doclist;
246767    int bNewTerm = 1;
246768
246769    memset(&doclist, 0, sizeof(doclist));
246770
246771    /* If iIdx is non-zero, then it is the number of a prefix-index for
246772    ** prefixes 1 character longer than the prefix being queried for. That
246773    ** index contains all the doclists required, except for the one
246774    ** corresponding to the prefix itself. That one is extracted from the
246775    ** main term index here.  */
246776    if( iIdx!=0 ){
246777      int dummy = 0;
246778      const int f2 = FTS5INDEX_QUERY_SKIPEMPTY|FTS5INDEX_QUERY_NOOUTPUT;
246779      pToken[0] = FTS5_MAIN_PREFIX;
246780      fts5MultiIterNew(p, pStruct, f2, pColset, pToken, nToken, -1, 0, &p1);
246781      fts5IterSetOutputCb(&p->rc, p1);
246782      for(;
246783        fts5MultiIterEof(p, p1)==0;
246784        fts5MultiIterNext2(p, p1, &dummy)
246785      ){
246786        Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
246787        p1->xSetOutputs(p1, pSeg);
246788        if( p1->base.nData ){
246789          xAppend(p, (u64)p1->base.iRowid-(u64)iLastRowid, p1, &doclist);
246790          iLastRowid = p1->base.iRowid;
246791        }
246792      }
246793      fts5MultiIterFree(p1);
246794    }
246795
246796    pToken[0] = FTS5_MAIN_PREFIX + iIdx;
246797    fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
246798    fts5IterSetOutputCb(&p->rc, p1);
246799
246800    for( /* no-op */ ;
246801        fts5MultiIterEof(p, p1)==0;
246802        fts5MultiIterNext2(p, p1, &bNewTerm)
246803    ){
246804      Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
246805      int nTerm = pSeg->term.n;
246806      const u8 *pTerm = pSeg->term.p;
246807      p1->xSetOutputs(p1, pSeg);
246808
246809      assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
246810      if( bNewTerm ){
246811        if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
246812      }
246813
246814      if( p1->base.nData==0 ) continue;
246815      if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
246816        for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
246817          int i1 = i*nMerge;
246818          int iStore;
246819          assert( i1+nMerge<=nBuf );
246820          for(iStore=i1; iStore<i1+nMerge; iStore++){
246821            if( aBuf[iStore].n==0 ){
246822              fts5BufferSwap(&doclist, &aBuf[iStore]);
246823              fts5BufferZero(&doclist);
246824              break;
246825            }
246826          }
246827          if( iStore==i1+nMerge ){
246828            xMerge(p, &doclist, nMerge, &aBuf[i1]);
246829            for(iStore=i1; iStore<i1+nMerge; iStore++){
246830              fts5BufferZero(&aBuf[iStore]);
246831            }
246832          }
246833        }
246834        iLastRowid = 0;
246835      }
246836
246837      xAppend(p, (u64)p1->base.iRowid-(u64)iLastRowid, p1, &doclist);
246838      iLastRowid = p1->base.iRowid;
246839    }
246840
246841    assert( (nBuf%nMerge)==0 );
246842    for(i=0; i<nBuf; i+=nMerge){
246843      int iFree;
246844      if( p->rc==SQLITE_OK ){
246845        xMerge(p, &doclist, nMerge, &aBuf[i]);
246846      }
246847      for(iFree=i; iFree<i+nMerge; iFree++){
246848        fts5BufferFree(&aBuf[iFree]);
246849      }
246850    }
246851    fts5MultiIterFree(p1);
246852
246853    pData = fts5IdxMalloc(p, sizeof(*pData)+doclist.n+FTS5_DATA_ZERO_PADDING);
246854    if( pData ){
246855      pData->p = (u8*)&pData[1];
246856      pData->nn = pData->szLeaf = doclist.n;
246857      if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
246858      fts5MultiIterNew2(p, pData, bDesc, ppIter);
246859    }
246860    fts5BufferFree(&doclist);
246861  }
246862
246863  fts5StructureRelease(pStruct);
246864  sqlite3_free(aBuf);
246865}
246866
246867
246868/*
246869** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
246870** to the document with rowid iRowid.
246871*/
246872static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
246873  assert( p->rc==SQLITE_OK );
246874
246875  /* Allocate the hash table if it has not already been allocated */
246876  if( p->pHash==0 ){
246877    p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
246878  }
246879
246880  /* Flush the hash table to disk if required */
246881  if( iRowid<p->iWriteRowid
246882   || (iRowid==p->iWriteRowid && p->bDelete==0)
246883   || (p->nPendingData > p->pConfig->nHashSize)
246884  ){
246885    fts5IndexFlush(p);
246886  }
246887
246888  p->iWriteRowid = iRowid;
246889  p->bDelete = bDelete;
246890  if( bDelete==0 ){
246891    p->nPendingRow++;
246892  }
246893  return fts5IndexReturn(p);
246894}
246895
246896/*
246897** Commit data to disk.
246898*/
246899static int sqlite3Fts5IndexSync(Fts5Index *p){
246900  assert( p->rc==SQLITE_OK );
246901  fts5IndexFlush(p);
246902  sqlite3Fts5IndexCloseReader(p);
246903  return fts5IndexReturn(p);
246904}
246905
246906/*
246907** Discard any data stored in the in-memory hash tables. Do not write it
246908** to the database. Additionally, assume that the contents of the %_data
246909** table may have changed on disk. So any in-memory caches of %_data
246910** records must be invalidated.
246911*/
246912static int sqlite3Fts5IndexRollback(Fts5Index *p){
246913  sqlite3Fts5IndexCloseReader(p);
246914  fts5IndexDiscardData(p);
246915  fts5StructureInvalidate(p);
246916  /* assert( p->rc==SQLITE_OK ); */
246917  return SQLITE_OK;
246918}
246919
246920/*
246921** The %_data table is completely empty when this function is called. This
246922** function populates it with the initial structure objects for each index,
246923** and the initial version of the "averages" record (a zero-byte blob).
246924*/
246925static int sqlite3Fts5IndexReinit(Fts5Index *p){
246926  Fts5Structure s;
246927  fts5StructureInvalidate(p);
246928  fts5IndexDiscardData(p);
246929  memset(&s, 0, sizeof(Fts5Structure));
246930  if( p->pConfig->bContentlessDelete ){
246931    s.nOriginCntr = 1;
246932  }
246933  fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
246934  fts5StructureWrite(p, &s);
246935  return fts5IndexReturn(p);
246936}
246937
246938/*
246939** Open a new Fts5Index handle. If the bCreate argument is true, create
246940** and initialize the underlying %_data table.
246941**
246942** If successful, set *pp to point to the new object and return SQLITE_OK.
246943** Otherwise, set *pp to NULL and return an SQLite error code.
246944*/
246945static int sqlite3Fts5IndexOpen(
246946  Fts5Config *pConfig,
246947  int bCreate,
246948  Fts5Index **pp,
246949  char **pzErr
246950){
246951  int rc = SQLITE_OK;
246952  Fts5Index *p;                   /* New object */
246953
246954  *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
246955  if( rc==SQLITE_OK ){
246956    p->pConfig = pConfig;
246957    p->nWorkUnit = FTS5_WORK_UNIT;
246958    p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
246959    if( p->zDataTbl && bCreate ){
246960      rc = sqlite3Fts5CreateTable(
246961          pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
246962      );
246963      if( rc==SQLITE_OK ){
246964        rc = sqlite3Fts5CreateTable(pConfig, "idx",
246965            "segid, term, pgno, PRIMARY KEY(segid, term)",
246966            1, pzErr
246967        );
246968      }
246969      if( rc==SQLITE_OK ){
246970        rc = sqlite3Fts5IndexReinit(p);
246971      }
246972    }
246973  }
246974
246975  assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
246976  if( rc ){
246977    sqlite3Fts5IndexClose(p);
246978    *pp = 0;
246979  }
246980  return rc;
246981}
246982
246983/*
246984** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
246985*/
246986static int sqlite3Fts5IndexClose(Fts5Index *p){
246987  int rc = SQLITE_OK;
246988  if( p ){
246989    assert( p->pReader==0 );
246990    fts5StructureInvalidate(p);
246991    sqlite3_finalize(p->pWriter);
246992    sqlite3_finalize(p->pDeleter);
246993    sqlite3_finalize(p->pIdxWriter);
246994    sqlite3_finalize(p->pIdxDeleter);
246995    sqlite3_finalize(p->pIdxSelect);
246996    sqlite3_finalize(p->pIdxNextSelect);
246997    sqlite3_finalize(p->pDataVersion);
246998    sqlite3_finalize(p->pDeleteFromIdx);
246999    sqlite3Fts5HashFree(p->pHash);
247000    sqlite3_free(p->zDataTbl);
247001    sqlite3_free(p);
247002  }
247003  return rc;
247004}
247005
247006/*
247007** Argument p points to a buffer containing utf-8 text that is n bytes in
247008** size. Return the number of bytes in the nChar character prefix of the
247009** buffer, or 0 if there are less than nChar characters in total.
247010*/
247011static int sqlite3Fts5IndexCharlenToBytelen(
247012  const char *p,
247013  int nByte,
247014  int nChar
247015){
247016  int n = 0;
247017  int i;
247018  for(i=0; i<nChar; i++){
247019    if( n>=nByte ) return 0;      /* Input contains fewer than nChar chars */
247020    if( (unsigned char)p[n++]>=0xc0 ){
247021      if( n>=nByte ) return 0;
247022      while( (p[n] & 0xc0)==0x80 ){
247023        n++;
247024        if( n>=nByte ){
247025          if( i+1==nChar ) break;
247026          return 0;
247027        }
247028      }
247029    }
247030  }
247031  return n;
247032}
247033
247034/*
247035** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
247036** unicode characters in the string.
247037*/
247038static int fts5IndexCharlen(const char *pIn, int nIn){
247039  int nChar = 0;
247040  int i = 0;
247041  while( i<nIn ){
247042    if( (unsigned char)pIn[i++]>=0xc0 ){
247043      while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
247044    }
247045    nChar++;
247046  }
247047  return nChar;
247048}
247049
247050/*
247051** Insert or remove data to or from the index. Each time a document is
247052** added to or removed from the index, this function is called one or more
247053** times.
247054**
247055** For an insert, it must be called once for each token in the new document.
247056** If the operation is a delete, it must be called (at least) once for each
247057** unique token in the document with an iCol value less than zero. The iPos
247058** argument is ignored for a delete.
247059*/
247060static int sqlite3Fts5IndexWrite(
247061  Fts5Index *p,                   /* Index to write to */
247062  int iCol,                       /* Column token appears in (-ve -> delete) */
247063  int iPos,                       /* Position of token within column */
247064  const char *pToken, int nToken  /* Token to add or remove to or from index */
247065){
247066  int i;                          /* Used to iterate through indexes */
247067  int rc = SQLITE_OK;             /* Return code */
247068  Fts5Config *pConfig = p->pConfig;
247069
247070  assert( p->rc==SQLITE_OK );
247071  assert( (iCol<0)==p->bDelete );
247072
247073  /* Add the entry to the main terms index. */
247074  rc = sqlite3Fts5HashWrite(
247075      p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
247076  );
247077
247078  for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
247079    const int nChar = pConfig->aPrefix[i];
247080    int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
247081    if( nByte ){
247082      rc = sqlite3Fts5HashWrite(p->pHash,
247083          p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
247084          nByte
247085      );
247086    }
247087  }
247088
247089  return rc;
247090}
247091
247092/*
247093** pToken points to a buffer of size nToken bytes containing a search
247094** term, including the index number at the start, used on a tokendata=1
247095** table. This function returns true if the term in buffer pBuf matches
247096** token pToken/nToken.
247097*/
247098static int fts5IsTokendataPrefix(
247099  Fts5Buffer *pBuf,
247100  const u8 *pToken,
247101  int nToken
247102){
247103  return (
247104      pBuf->n>=nToken
247105   && 0==memcmp(pBuf->p, pToken, nToken)
247106   && (pBuf->n==nToken || pBuf->p[nToken]==0x00)
247107  );
247108}
247109
247110/*
247111** Ensure the segment-iterator passed as the only argument points to EOF.
247112*/
247113static void fts5SegIterSetEOF(Fts5SegIter *pSeg){
247114  fts5DataRelease(pSeg->pLeaf);
247115  pSeg->pLeaf = 0;
247116}
247117
247118/*
247119** Usually, a tokendata=1 iterator (struct Fts5TokenDataIter) accumulates an
247120** array of these for each row it visits. Or, for an iterator used by an
247121** "ORDER BY rank" query, it accumulates an array of these for the entire
247122** query.
247123**
247124** Each instance in the array indicates the iterator (and therefore term)
247125** associated with position iPos of rowid iRowid. This is used by the
247126** xInstToken() API.
247127*/
247128struct Fts5TokenDataMap {
247129  i64 iRowid;                     /* Row this token is located in */
247130  i64 iPos;                       /* Position of token */
247131  int iIter;                      /* Iterator token was read from */
247132};
247133
247134/*
247135** An object used to supplement Fts5Iter for tokendata=1 iterators.
247136*/
247137struct Fts5TokenDataIter {
247138  int nIter;
247139  int nIterAlloc;
247140
247141  int nMap;
247142  int nMapAlloc;
247143  Fts5TokenDataMap *aMap;
247144
247145  Fts5PoslistReader *aPoslistReader;
247146  int *aPoslistToIter;
247147  Fts5Iter *apIter[1];
247148};
247149
247150/*
247151** This function appends iterator pAppend to Fts5TokenDataIter pIn and
247152** returns the result.
247153*/
247154static Fts5TokenDataIter *fts5AppendTokendataIter(
247155  Fts5Index *p,                   /* Index object (for error code) */
247156  Fts5TokenDataIter *pIn,         /* Current Fts5TokenDataIter struct */
247157  Fts5Iter *pAppend               /* Append this iterator */
247158){
247159  Fts5TokenDataIter *pRet = pIn;
247160
247161  if( p->rc==SQLITE_OK ){
247162    if( pIn==0 || pIn->nIter==pIn->nIterAlloc ){
247163      int nAlloc = pIn ? pIn->nIterAlloc*2 : 16;
247164      int nByte = nAlloc * sizeof(Fts5Iter*) + sizeof(Fts5TokenDataIter);
247165      Fts5TokenDataIter *pNew = (Fts5TokenDataIter*)sqlite3_realloc(pIn, nByte);
247166
247167      if( pNew==0 ){
247168        p->rc = SQLITE_NOMEM;
247169      }else{
247170        if( pIn==0 ) memset(pNew, 0, nByte);
247171        pRet = pNew;
247172        pNew->nIterAlloc = nAlloc;
247173      }
247174    }
247175  }
247176  if( p->rc ){
247177    sqlite3Fts5IterClose((Fts5IndexIter*)pAppend);
247178  }else{
247179    pRet->apIter[pRet->nIter++] = pAppend;
247180  }
247181  assert( pRet==0 || pRet->nIter<=pRet->nIterAlloc );
247182
247183  return pRet;
247184}
247185
247186/*
247187** Delete an Fts5TokenDataIter structure and its contents.
247188*/
247189static void fts5TokendataIterDelete(Fts5TokenDataIter *pSet){
247190  if( pSet ){
247191    int ii;
247192    for(ii=0; ii<pSet->nIter; ii++){
247193      fts5MultiIterFree(pSet->apIter[ii]);
247194    }
247195    sqlite3_free(pSet->aPoslistReader);
247196    sqlite3_free(pSet->aMap);
247197    sqlite3_free(pSet);
247198  }
247199}
247200
247201/*
247202** Append a mapping to the token-map belonging to object pT.
247203*/
247204static void fts5TokendataIterAppendMap(
247205  Fts5Index *p,
247206  Fts5TokenDataIter *pT,
247207  int iIter,
247208  i64 iRowid,
247209  i64 iPos
247210){
247211  if( p->rc==SQLITE_OK ){
247212    if( pT->nMap==pT->nMapAlloc ){
247213      int nNew = pT->nMapAlloc ? pT->nMapAlloc*2 : 64;
247214      int nByte = nNew * sizeof(Fts5TokenDataMap);
247215      Fts5TokenDataMap *aNew;
247216
247217      aNew = (Fts5TokenDataMap*)sqlite3_realloc(pT->aMap, nByte);
247218      if( aNew==0 ){
247219        p->rc = SQLITE_NOMEM;
247220        return;
247221      }
247222
247223      pT->aMap = aNew;
247224      pT->nMapAlloc = nNew;
247225    }
247226
247227    pT->aMap[pT->nMap].iRowid = iRowid;
247228    pT->aMap[pT->nMap].iPos = iPos;
247229    pT->aMap[pT->nMap].iIter = iIter;
247230    pT->nMap++;
247231  }
247232}
247233
247234/*
247235** The iterator passed as the only argument must be a tokendata=1 iterator
247236** (pIter->pTokenDataIter!=0). This function sets the iterator output
247237** variables (pIter->base.*) according to the contents of the current
247238** row.
247239*/
247240static void fts5IterSetOutputsTokendata(Fts5Iter *pIter){
247241  int ii;
247242  int nHit = 0;
247243  i64 iRowid = SMALLEST_INT64;
247244  int iMin = 0;
247245
247246  Fts5TokenDataIter *pT = pIter->pTokenDataIter;
247247
247248  pIter->base.nData = 0;
247249  pIter->base.pData = 0;
247250
247251  for(ii=0; ii<pT->nIter; ii++){
247252    Fts5Iter *p = pT->apIter[ii];
247253    if( p->base.bEof==0 ){
247254      if( nHit==0 || p->base.iRowid<iRowid ){
247255        iRowid = p->base.iRowid;
247256        nHit = 1;
247257        pIter->base.pData = p->base.pData;
247258        pIter->base.nData = p->base.nData;
247259        iMin = ii;
247260      }else if( p->base.iRowid==iRowid ){
247261        nHit++;
247262      }
247263    }
247264  }
247265
247266  if( nHit==0 ){
247267    pIter->base.bEof = 1;
247268  }else{
247269    int eDetail = pIter->pIndex->pConfig->eDetail;
247270    pIter->base.bEof = 0;
247271    pIter->base.iRowid = iRowid;
247272
247273    if( nHit==1 && eDetail==FTS5_DETAIL_FULL ){
247274      fts5TokendataIterAppendMap(pIter->pIndex, pT, iMin, iRowid, -1);
247275    }else
247276    if( nHit>1 && eDetail!=FTS5_DETAIL_NONE ){
247277      int nReader = 0;
247278      int nByte = 0;
247279      i64 iPrev = 0;
247280
247281      /* Allocate array of iterators if they are not already allocated. */
247282      if( pT->aPoslistReader==0 ){
247283        pT->aPoslistReader = (Fts5PoslistReader*)sqlite3Fts5MallocZero(
247284            &pIter->pIndex->rc,
247285            pT->nIter * (sizeof(Fts5PoslistReader) + sizeof(int))
247286        );
247287        if( pT->aPoslistReader==0 ) return;
247288        pT->aPoslistToIter = (int*)&pT->aPoslistReader[pT->nIter];
247289      }
247290
247291      /* Populate an iterator for each poslist that will be merged */
247292      for(ii=0; ii<pT->nIter; ii++){
247293        Fts5Iter *p = pT->apIter[ii];
247294        if( iRowid==p->base.iRowid ){
247295          pT->aPoslistToIter[nReader] = ii;
247296          sqlite3Fts5PoslistReaderInit(
247297              p->base.pData, p->base.nData, &pT->aPoslistReader[nReader++]
247298          );
247299          nByte += p->base.nData;
247300        }
247301      }
247302
247303      /* Ensure the output buffer is large enough */
247304      if( fts5BufferGrow(&pIter->pIndex->rc, &pIter->poslist, nByte+nHit*10) ){
247305        return;
247306      }
247307
247308      /* Ensure the token-mapping is large enough */
247309      if( eDetail==FTS5_DETAIL_FULL && pT->nMapAlloc<(pT->nMap + nByte) ){
247310        int nNew = (pT->nMapAlloc + nByte) * 2;
247311        Fts5TokenDataMap *aNew = (Fts5TokenDataMap*)sqlite3_realloc(
247312            pT->aMap, nNew*sizeof(Fts5TokenDataMap)
247313        );
247314        if( aNew==0 ){
247315          pIter->pIndex->rc = SQLITE_NOMEM;
247316          return;
247317        }
247318        pT->aMap = aNew;
247319        pT->nMapAlloc = nNew;
247320      }
247321
247322      pIter->poslist.n = 0;
247323
247324      while( 1 ){
247325        i64 iMinPos = LARGEST_INT64;
247326
247327        /* Find smallest position */
247328        iMin = 0;
247329        for(ii=0; ii<nReader; ii++){
247330          Fts5PoslistReader *pReader = &pT->aPoslistReader[ii];
247331          if( pReader->bEof==0 ){
247332            if( pReader->iPos<iMinPos ){
247333              iMinPos = pReader->iPos;
247334              iMin = ii;
247335            }
247336          }
247337        }
247338
247339        /* If all readers were at EOF, break out of the loop. */
247340        if( iMinPos==LARGEST_INT64 ) break;
247341
247342        sqlite3Fts5PoslistSafeAppend(&pIter->poslist, &iPrev, iMinPos);
247343        sqlite3Fts5PoslistReaderNext(&pT->aPoslistReader[iMin]);
247344
247345        if( eDetail==FTS5_DETAIL_FULL ){
247346          pT->aMap[pT->nMap].iPos = iMinPos;
247347          pT->aMap[pT->nMap].iIter = pT->aPoslistToIter[iMin];
247348          pT->aMap[pT->nMap].iRowid = iRowid;
247349          pT->nMap++;
247350        }
247351      }
247352
247353      pIter->base.pData = pIter->poslist.p;
247354      pIter->base.nData = pIter->poslist.n;
247355    }
247356  }
247357}
247358
247359/*
247360** The iterator passed as the only argument must be a tokendata=1 iterator
247361** (pIter->pTokenDataIter!=0). This function advances the iterator. If
247362** argument bFrom is false, then the iterator is advanced to the next
247363** entry. Or, if bFrom is true, it is advanced to the first entry with
247364** a rowid of iFrom or greater.
247365*/
247366static void fts5TokendataIterNext(Fts5Iter *pIter, int bFrom, i64 iFrom){
247367  int ii;
247368  Fts5TokenDataIter *pT = pIter->pTokenDataIter;
247369  Fts5Index *pIndex = pIter->pIndex;
247370
247371  for(ii=0; ii<pT->nIter; ii++){
247372    Fts5Iter *p = pT->apIter[ii];
247373    if( p->base.bEof==0
247374     && (p->base.iRowid==pIter->base.iRowid || (bFrom && p->base.iRowid<iFrom))
247375    ){
247376      fts5MultiIterNext(pIndex, p, bFrom, iFrom);
247377      while( bFrom && p->base.bEof==0
247378          && p->base.iRowid<iFrom
247379          && pIndex->rc==SQLITE_OK
247380      ){
247381        fts5MultiIterNext(pIndex, p, 0, 0);
247382      }
247383    }
247384  }
247385
247386  if( pIndex->rc==SQLITE_OK ){
247387    fts5IterSetOutputsTokendata(pIter);
247388  }
247389}
247390
247391/*
247392** If the segment-iterator passed as the first argument is at EOF, then
247393** set pIter->term to a copy of buffer pTerm.
247394*/
247395static void fts5TokendataSetTermIfEof(Fts5Iter *pIter, Fts5Buffer *pTerm){
247396  if( pIter && pIter->aSeg[0].pLeaf==0 ){
247397    fts5BufferSet(&pIter->pIndex->rc, &pIter->aSeg[0].term, pTerm->n, pTerm->p);
247398  }
247399}
247400
247401/*
247402** This function sets up an iterator to use for a non-prefix query on a
247403** tokendata=1 table.
247404*/
247405static Fts5Iter *fts5SetupTokendataIter(
247406  Fts5Index *p,                   /* FTS index to query */
247407  const u8 *pToken,               /* Buffer containing query term */
247408  int nToken,                     /* Size of buffer pToken in bytes */
247409  Fts5Colset *pColset             /* Colset to filter on */
247410){
247411  Fts5Iter *pRet = 0;
247412  Fts5TokenDataIter *pSet = 0;
247413  Fts5Structure *pStruct = 0;
247414  const int flags = FTS5INDEX_QUERY_SCANONETERM | FTS5INDEX_QUERY_SCAN;
247415
247416  Fts5Buffer bSeek = {0, 0, 0};
247417  Fts5Buffer *pSmall = 0;
247418
247419  fts5IndexFlush(p);
247420  pStruct = fts5StructureRead(p);
247421
247422  while( p->rc==SQLITE_OK ){
247423    Fts5Iter *pPrev = pSet ? pSet->apIter[pSet->nIter-1] : 0;
247424    Fts5Iter *pNew = 0;
247425    Fts5SegIter *pNewIter = 0;
247426    Fts5SegIter *pPrevIter = 0;
247427
247428    int iLvl, iSeg, ii;
247429
247430    pNew = fts5MultiIterAlloc(p, pStruct->nSegment);
247431    if( pSmall ){
247432      fts5BufferSet(&p->rc, &bSeek, pSmall->n, pSmall->p);
247433      fts5BufferAppendBlob(&p->rc, &bSeek, 1, (const u8*)"\0");
247434    }else{
247435      fts5BufferSet(&p->rc, &bSeek, nToken, pToken);
247436    }
247437    if( p->rc ){
247438      sqlite3Fts5IterClose((Fts5IndexIter*)pNew);
247439      break;
247440    }
247441
247442    pNewIter = &pNew->aSeg[0];
247443    pPrevIter = (pPrev ? &pPrev->aSeg[0] : 0);
247444    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
247445      for(iSeg=pStruct->aLevel[iLvl].nSeg-1; iSeg>=0; iSeg--){
247446        Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
247447        int bDone = 0;
247448
247449        if( pPrevIter ){
247450          if( fts5BufferCompare(pSmall, &pPrevIter->term) ){
247451            memcpy(pNewIter, pPrevIter, sizeof(Fts5SegIter));
247452            memset(pPrevIter, 0, sizeof(Fts5SegIter));
247453            bDone = 1;
247454          }else if( pPrevIter->iEndofDoclist>pPrevIter->pLeaf->szLeaf ){
247455            fts5SegIterNextInit(p,(const char*)bSeek.p,bSeek.n-1,pSeg,pNewIter);
247456            bDone = 1;
247457          }
247458        }
247459
247460        if( bDone==0 ){
247461          fts5SegIterSeekInit(p, bSeek.p, bSeek.n, flags, pSeg, pNewIter);
247462        }
247463
247464        if( pPrevIter ){
247465          if( pPrevIter->pTombArray ){
247466            pNewIter->pTombArray = pPrevIter->pTombArray;
247467            pNewIter->pTombArray->nRef++;
247468          }
247469        }else{
247470          fts5SegIterAllocTombstone(p, pNewIter);
247471        }
247472
247473        pNewIter++;
247474        if( pPrevIter ) pPrevIter++;
247475        if( p->rc ) break;
247476      }
247477    }
247478    fts5TokendataSetTermIfEof(pPrev, pSmall);
247479
247480    pNew->bSkipEmpty = 1;
247481    pNew->pColset = pColset;
247482    fts5IterSetOutputCb(&p->rc, pNew);
247483
247484    /* Loop through all segments in the new iterator. Find the smallest
247485    ** term that any segment-iterator points to. Iterator pNew will be
247486    ** used for this term. Also, set any iterator that points to a term that
247487    ** does not match pToken/nToken to point to EOF */
247488    pSmall = 0;
247489    for(ii=0; ii<pNew->nSeg; ii++){
247490      Fts5SegIter *pII = &pNew->aSeg[ii];
247491      if( 0==fts5IsTokendataPrefix(&pII->term, pToken, nToken) ){
247492        fts5SegIterSetEOF(pII);
247493      }
247494      if( pII->pLeaf && (!pSmall || fts5BufferCompare(pSmall, &pII->term)>0) ){
247495        pSmall = &pII->term;
247496      }
247497    }
247498
247499    /* If pSmall is still NULL at this point, then the new iterator does
247500    ** not point to any terms that match the query. So delete it and break
247501    ** out of the loop - all required iterators have been collected.  */
247502    if( pSmall==0 ){
247503      sqlite3Fts5IterClose((Fts5IndexIter*)pNew);
247504      break;
247505    }
247506
247507    /* Append this iterator to the set and continue. */
247508    pSet = fts5AppendTokendataIter(p, pSet, pNew);
247509  }
247510
247511  if( p->rc==SQLITE_OK && pSet ){
247512    int ii;
247513    for(ii=0; ii<pSet->nIter; ii++){
247514      Fts5Iter *pIter = pSet->apIter[ii];
247515      int iSeg;
247516      for(iSeg=0; iSeg<pIter->nSeg; iSeg++){
247517        pIter->aSeg[iSeg].flags |= FTS5_SEGITER_ONETERM;
247518      }
247519      fts5MultiIterFinishSetup(p, pIter);
247520    }
247521  }
247522
247523  if( p->rc==SQLITE_OK ){
247524    pRet = fts5MultiIterAlloc(p, 0);
247525  }
247526  if( pRet ){
247527    pRet->pTokenDataIter = pSet;
247528    if( pSet ){
247529      fts5IterSetOutputsTokendata(pRet);
247530    }else{
247531      pRet->base.bEof = 1;
247532    }
247533  }else{
247534    fts5TokendataIterDelete(pSet);
247535  }
247536
247537  fts5StructureRelease(pStruct);
247538  fts5BufferFree(&bSeek);
247539  return pRet;
247540}
247541
247542
247543/*
247544** Open a new iterator to iterate though all rowid that match the
247545** specified token or token prefix.
247546*/
247547static int sqlite3Fts5IndexQuery(
247548  Fts5Index *p,                   /* FTS index to query */
247549  const char *pToken, int nToken, /* Token (or prefix) to query for */
247550  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
247551  Fts5Colset *pColset,            /* Match these columns only */
247552  Fts5IndexIter **ppIter          /* OUT: New iterator object */
247553){
247554  Fts5Config *pConfig = p->pConfig;
247555  Fts5Iter *pRet = 0;
247556  Fts5Buffer buf = {0, 0, 0};
247557
247558  /* If the QUERY_SCAN flag is set, all other flags must be clear. */
247559  assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
247560
247561  if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
247562    int iIdx = 0;                 /* Index to search */
247563    int iPrefixIdx = 0;           /* +1 prefix index */
247564    int bTokendata = pConfig->bTokendata;
247565    if( nToken>0 ) memcpy(&buf.p[1], pToken, nToken);
247566
247567    if( flags & (FTS5INDEX_QUERY_NOTOKENDATA|FTS5INDEX_QUERY_SCAN) ){
247568      bTokendata = 0;
247569    }
247570
247571    /* Figure out which index to search and set iIdx accordingly. If this
247572    ** is a prefix query for which there is no prefix index, set iIdx to
247573    ** greater than pConfig->nPrefix to indicate that the query will be
247574    ** satisfied by scanning multiple terms in the main index.
247575    **
247576    ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
247577    ** prefix-query. Instead of using a prefix-index (if one exists),
247578    ** evaluate the prefix query using the main FTS index. This is used
247579    ** for internal sanity checking by the integrity-check in debug
247580    ** mode only.  */
247581#ifdef SQLITE_DEBUG
247582    if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
247583      assert( flags & FTS5INDEX_QUERY_PREFIX );
247584      iIdx = 1+pConfig->nPrefix;
247585    }else
247586#endif
247587    if( flags & FTS5INDEX_QUERY_PREFIX ){
247588      int nChar = fts5IndexCharlen(pToken, nToken);
247589      for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
247590        int nIdxChar = pConfig->aPrefix[iIdx-1];
247591        if( nIdxChar==nChar ) break;
247592        if( nIdxChar==nChar+1 ) iPrefixIdx = iIdx;
247593      }
247594    }
247595
247596    if( bTokendata && iIdx==0 ){
247597      buf.p[0] = '0';
247598      pRet = fts5SetupTokendataIter(p, buf.p, nToken+1, pColset);
247599    }else if( iIdx<=pConfig->nPrefix ){
247600      /* Straight index lookup */
247601      Fts5Structure *pStruct = fts5StructureRead(p);
247602      buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
247603      if( pStruct ){
247604        fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
247605            pColset, buf.p, nToken+1, -1, 0, &pRet
247606        );
247607        fts5StructureRelease(pStruct);
247608      }
247609    }else{
247610      /* Scan multiple terms in the main index */
247611      int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
247612      fts5SetupPrefixIter(p, bDesc, iPrefixIdx, buf.p, nToken+1, pColset,&pRet);
247613      if( pRet==0 ){
247614        assert( p->rc!=SQLITE_OK );
247615      }else{
247616        assert( pRet->pColset==0 );
247617        fts5IterSetOutputCb(&p->rc, pRet);
247618        if( p->rc==SQLITE_OK ){
247619          Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
247620          if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
247621        }
247622      }
247623    }
247624
247625    if( p->rc ){
247626      sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
247627      pRet = 0;
247628      sqlite3Fts5IndexCloseReader(p);
247629    }
247630
247631    *ppIter = (Fts5IndexIter*)pRet;
247632    sqlite3Fts5BufferFree(&buf);
247633  }
247634  return fts5IndexReturn(p);
247635}
247636
247637/*
247638** Return true if the iterator passed as the only argument is at EOF.
247639*/
247640/*
247641** Move to the next matching rowid.
247642*/
247643static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
247644  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
247645  assert( pIter->pIndex->rc==SQLITE_OK );
247646  if( pIter->pTokenDataIter ){
247647    fts5TokendataIterNext(pIter, 0, 0);
247648  }else{
247649    fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
247650  }
247651  return fts5IndexReturn(pIter->pIndex);
247652}
247653
247654/*
247655** Move to the next matching term/rowid. Used by the fts5vocab module.
247656*/
247657static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
247658  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
247659  Fts5Index *p = pIter->pIndex;
247660
247661  assert( pIter->pIndex->rc==SQLITE_OK );
247662
247663  fts5MultiIterNext(p, pIter, 0, 0);
247664  if( p->rc==SQLITE_OK ){
247665    Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
247666    if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
247667      fts5DataRelease(pSeg->pLeaf);
247668      pSeg->pLeaf = 0;
247669      pIter->base.bEof = 1;
247670    }
247671  }
247672
247673  return fts5IndexReturn(pIter->pIndex);
247674}
247675
247676/*
247677** Move to the next matching rowid that occurs at or after iMatch. The
247678** definition of "at or after" depends on whether this iterator iterates
247679** in ascending or descending rowid order.
247680*/
247681static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
247682  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
247683  if( pIter->pTokenDataIter ){
247684    fts5TokendataIterNext(pIter, 1, iMatch);
247685  }else{
247686    fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
247687  }
247688  return fts5IndexReturn(pIter->pIndex);
247689}
247690
247691/*
247692** Return the current term.
247693*/
247694static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
247695  int n;
247696  const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
247697  assert_nc( z || n<=1 );
247698  *pn = n-1;
247699  return (z ? &z[1] : 0);
247700}
247701
247702/*
247703** This is used by xInstToken() to access the token at offset iOff, column
247704** iCol of row iRowid. The token is returned via output variables *ppOut
247705** and *pnOut. The iterator passed as the first argument must be a tokendata=1
247706** iterator (pIter->pTokenDataIter!=0).
247707*/
247708static int sqlite3Fts5IterToken(
247709  Fts5IndexIter *pIndexIter,
247710  i64 iRowid,
247711  int iCol,
247712  int iOff,
247713  const char **ppOut, int *pnOut
247714){
247715  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
247716  Fts5TokenDataIter *pT = pIter->pTokenDataIter;
247717  Fts5TokenDataMap *aMap = pT->aMap;
247718  i64 iPos = (((i64)iCol)<<32) + iOff;
247719
247720  int i1 = 0;
247721  int i2 = pT->nMap;
247722  int iTest = 0;
247723
247724  while( i2>i1 ){
247725    iTest = (i1 + i2) / 2;
247726
247727    if( aMap[iTest].iRowid<iRowid ){
247728      i1 = iTest+1;
247729    }else if( aMap[iTest].iRowid>iRowid ){
247730      i2 = iTest;
247731    }else{
247732      if( aMap[iTest].iPos<iPos ){
247733        if( aMap[iTest].iPos<0 ){
247734          break;
247735        }
247736        i1 = iTest+1;
247737      }else if( aMap[iTest].iPos>iPos ){
247738        i2 = iTest;
247739      }else{
247740        break;
247741      }
247742    }
247743  }
247744
247745  if( i2>i1 ){
247746    Fts5Iter *pMap = pT->apIter[aMap[iTest].iIter];
247747    *ppOut = (const char*)pMap->aSeg[0].term.p+1;
247748    *pnOut = pMap->aSeg[0].term.n-1;
247749  }
247750
247751  return SQLITE_OK;
247752}
247753
247754/*
247755** Clear any existing entries from the token-map associated with the
247756** iterator passed as the only argument.
247757*/
247758static void sqlite3Fts5IndexIterClearTokendata(Fts5IndexIter *pIndexIter){
247759  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
247760  if( pIter && pIter->pTokenDataIter ){
247761    pIter->pTokenDataIter->nMap = 0;
247762  }
247763}
247764
247765/*
247766** Set a token-mapping for the iterator passed as the first argument. This
247767** is used in detail=column or detail=none mode when a token is requested
247768** using the xInstToken() API. In this case the caller tokenizers the
247769** current row and configures the token-mapping via multiple calls to this
247770** function.
247771*/
247772static int sqlite3Fts5IndexIterWriteTokendata(
247773  Fts5IndexIter *pIndexIter,
247774  const char *pToken, int nToken,
247775  i64 iRowid, int iCol, int iOff
247776){
247777  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
247778  Fts5TokenDataIter *pT = pIter->pTokenDataIter;
247779  Fts5Index *p = pIter->pIndex;
247780  int ii;
247781
247782  assert( p->pConfig->eDetail!=FTS5_DETAIL_FULL );
247783  assert( pIter->pTokenDataIter );
247784
247785  for(ii=0; ii<pT->nIter; ii++){
247786    Fts5Buffer *pTerm = &pT->apIter[ii]->aSeg[0].term;
247787    if( nToken==pTerm->n-1 && memcmp(pToken, pTerm->p+1, nToken)==0 ) break;
247788  }
247789  if( ii<pT->nIter ){
247790    fts5TokendataIterAppendMap(p, pT, ii, iRowid, (((i64)iCol)<<32) + iOff);
247791  }
247792  return fts5IndexReturn(p);
247793}
247794
247795/*
247796** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
247797*/
247798static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
247799  if( pIndexIter ){
247800    Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
247801    Fts5Index *pIndex = pIter->pIndex;
247802    fts5TokendataIterDelete(pIter->pTokenDataIter);
247803    fts5MultiIterFree(pIter);
247804    sqlite3Fts5IndexCloseReader(pIndex);
247805  }
247806}
247807
247808/*
247809** Read and decode the "averages" record from the database.
247810**
247811** Parameter anSize must point to an array of size nCol, where nCol is
247812** the number of user defined columns in the FTS table.
247813*/
247814static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
247815  int nCol = p->pConfig->nCol;
247816  Fts5Data *pData;
247817
247818  *pnRow = 0;
247819  memset(anSize, 0, sizeof(i64) * nCol);
247820  pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
247821  if( p->rc==SQLITE_OK && pData->nn ){
247822    int i = 0;
247823    int iCol;
247824    i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
247825    for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
247826      i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
247827    }
247828  }
247829
247830  fts5DataRelease(pData);
247831  return fts5IndexReturn(p);
247832}
247833
247834/*
247835** Replace the current "averages" record with the contents of the buffer
247836** supplied as the second argument.
247837*/
247838static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
247839  assert( p->rc==SQLITE_OK );
247840  fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
247841  return fts5IndexReturn(p);
247842}
247843
247844/*
247845** Return the total number of blocks this module has read from the %_data
247846** table since it was created.
247847*/
247848static int sqlite3Fts5IndexReads(Fts5Index *p){
247849  return p->nRead;
247850}
247851
247852/*
247853** Set the 32-bit cookie value stored at the start of all structure
247854** records to the value passed as the second argument.
247855**
247856** Return SQLITE_OK if successful, or an SQLite error code if an error
247857** occurs.
247858*/
247859static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
247860  int rc;                              /* Return code */
247861  Fts5Config *pConfig = p->pConfig;    /* Configuration object */
247862  u8 aCookie[4];                       /* Binary representation of iNew */
247863  sqlite3_blob *pBlob = 0;
247864
247865  assert( p->rc==SQLITE_OK );
247866  sqlite3Fts5Put32(aCookie, iNew);
247867
247868  rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
247869      "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
247870  );
247871  if( rc==SQLITE_OK ){
247872    sqlite3_blob_write(pBlob, aCookie, 4, 0);
247873    rc = sqlite3_blob_close(pBlob);
247874  }
247875
247876  return rc;
247877}
247878
247879static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
247880  Fts5Structure *pStruct;
247881  pStruct = fts5StructureRead(p);
247882  fts5StructureRelease(pStruct);
247883  return fts5IndexReturn(p);
247884}
247885
247886/*
247887** Retrieve the origin value that will be used for the segment currently
247888** being accumulated in the in-memory hash table when it is flushed to
247889** disk. If successful, SQLITE_OK is returned and (*piOrigin) set to
247890** the queried value. Or, if an error occurs, an error code is returned
247891** and the final value of (*piOrigin) is undefined.
247892*/
247893static int sqlite3Fts5IndexGetOrigin(Fts5Index *p, i64 *piOrigin){
247894  Fts5Structure *pStruct;
247895  pStruct = fts5StructureRead(p);
247896  if( pStruct ){
247897    *piOrigin = pStruct->nOriginCntr;
247898    fts5StructureRelease(pStruct);
247899  }
247900  return fts5IndexReturn(p);
247901}
247902
247903/*
247904** Buffer pPg contains a page of a tombstone hash table - one of nPg pages
247905** associated with the same segment. This function adds rowid iRowid to
247906** the hash table. The caller is required to guarantee that there is at
247907** least one free slot on the page.
247908**
247909** If parameter bForce is false and the hash table is deemed to be full
247910** (more than half of the slots are occupied), then non-zero is returned
247911** and iRowid not inserted. Or, if bForce is true or if the hash table page
247912** is not full, iRowid is inserted and zero returned.
247913*/
247914static int fts5IndexTombstoneAddToPage(
247915  Fts5Data *pPg,
247916  int bForce,
247917  int nPg,
247918  u64 iRowid
247919){
247920  const int szKey = TOMBSTONE_KEYSIZE(pPg);
247921  const int nSlot = TOMBSTONE_NSLOT(pPg);
247922  const int nElem = fts5GetU32(&pPg->p[4]);
247923  int iSlot = (iRowid / nPg) % nSlot;
247924  int nCollide = nSlot;
247925
247926  if( szKey==4 && iRowid>0xFFFFFFFF ) return 2;
247927  if( iRowid==0 ){
247928    pPg->p[1] = 0x01;
247929    return 0;
247930  }
247931
247932  if( bForce==0 && nElem>=(nSlot/2) ){
247933    return 1;
247934  }
247935
247936  fts5PutU32(&pPg->p[4], nElem+1);
247937  if( szKey==4 ){
247938    u32 *aSlot = (u32*)&pPg->p[8];
247939    while( aSlot[iSlot] ){
247940      iSlot = (iSlot + 1) % nSlot;
247941      if( nCollide--==0 ) return 0;
247942    }
247943    fts5PutU32((u8*)&aSlot[iSlot], (u32)iRowid);
247944  }else{
247945    u64 *aSlot = (u64*)&pPg->p[8];
247946    while( aSlot[iSlot] ){
247947      iSlot = (iSlot + 1) % nSlot;
247948      if( nCollide--==0 ) return 0;
247949    }
247950    fts5PutU64((u8*)&aSlot[iSlot], iRowid);
247951  }
247952
247953  return 0;
247954}
247955
247956/*
247957** This function attempts to build a new hash containing all the keys
247958** currently in the tombstone hash table for segment pSeg. The new
247959** hash will be stored in the nOut buffers passed in array apOut[].
247960** All pages of the new hash use key-size szKey (4 or 8).
247961**
247962** Return 0 if the hash is successfully rebuilt into the nOut pages.
247963** Or non-zero if it is not (because one page became overfull). In this
247964** case the caller should retry with a larger nOut parameter.
247965**
247966** Parameter pData1 is page iPg1 of the hash table being rebuilt.
247967*/
247968static int fts5IndexTombstoneRehash(
247969  Fts5Index *p,
247970  Fts5StructureSegment *pSeg,     /* Segment to rebuild hash of */
247971  Fts5Data *pData1,               /* One page of current hash - or NULL */
247972  int iPg1,                       /* Which page of the current hash is pData1 */
247973  int szKey,                      /* 4 or 8, the keysize */
247974  int nOut,                       /* Number of output pages */
247975  Fts5Data **apOut                /* Array of output hash pages */
247976){
247977  int ii;
247978  int res = 0;
247979
247980  /* Initialize the headers of all the output pages */
247981  for(ii=0; ii<nOut; ii++){
247982    apOut[ii]->p[0] = szKey;
247983    fts5PutU32(&apOut[ii]->p[4], 0);
247984  }
247985
247986  /* Loop through the current pages of the hash table. */
247987  for(ii=0; res==0 && ii<pSeg->nPgTombstone; ii++){
247988    Fts5Data *pData = 0;          /* Page ii of the current hash table */
247989    Fts5Data *pFree = 0;          /* Free this at the end of the loop */
247990
247991    if( iPg1==ii ){
247992      pData = pData1;
247993    }else{
247994      pFree = pData = fts5DataRead(p, FTS5_TOMBSTONE_ROWID(pSeg->iSegid, ii));
247995    }
247996
247997    if( pData ){
247998      int szKeyIn = TOMBSTONE_KEYSIZE(pData);
247999      int nSlotIn = (pData->nn - 8) / szKeyIn;
248000      int iIn;
248001      for(iIn=0; iIn<nSlotIn; iIn++){
248002        u64 iVal = 0;
248003
248004        /* Read the value from slot iIn of the input page into iVal. */
248005        if( szKeyIn==4 ){
248006          u32 *aSlot = (u32*)&pData->p[8];
248007          if( aSlot[iIn] ) iVal = fts5GetU32((u8*)&aSlot[iIn]);
248008        }else{
248009          u64 *aSlot = (u64*)&pData->p[8];
248010          if( aSlot[iIn] ) iVal = fts5GetU64((u8*)&aSlot[iIn]);
248011        }
248012
248013        /* If iVal is not 0 at this point, insert it into the new hash table */
248014        if( iVal ){
248015          Fts5Data *pPg = apOut[(iVal % nOut)];
248016          res = fts5IndexTombstoneAddToPage(pPg, 0, nOut, iVal);
248017          if( res ) break;
248018        }
248019      }
248020
248021      /* If this is page 0 of the old hash, copy the rowid-0-flag from the
248022      ** old hash to the new.  */
248023      if( ii==0 ){
248024        apOut[0]->p[1] = pData->p[1];
248025      }
248026    }
248027    fts5DataRelease(pFree);
248028  }
248029
248030  return res;
248031}
248032
248033/*
248034** This is called to rebuild the hash table belonging to segment pSeg.
248035** If parameter pData1 is not NULL, then one page of the existing hash table
248036** has already been loaded - pData1, which is page iPg1. The key-size for
248037** the new hash table is szKey (4 or 8).
248038**
248039** If successful, the new hash table is not written to disk. Instead,
248040** output parameter (*pnOut) is set to the number of pages in the new
248041** hash table, and (*papOut) to point to an array of buffers containing
248042** the new page data.
248043**
248044** If an error occurs, an error code is left in the Fts5Index object and
248045** both output parameters set to 0 before returning.
248046*/
248047static void fts5IndexTombstoneRebuild(
248048  Fts5Index *p,
248049  Fts5StructureSegment *pSeg,     /* Segment to rebuild hash of */
248050  Fts5Data *pData1,               /* One page of current hash - or NULL */
248051  int iPg1,                       /* Which page of the current hash is pData1 */
248052  int szKey,                      /* 4 or 8, the keysize */
248053  int *pnOut,                     /* OUT: Number of output pages */
248054  Fts5Data ***papOut              /* OUT: Output hash pages */
248055){
248056  const int MINSLOT = 32;
248057  int nSlotPerPage = MAX(MINSLOT, (p->pConfig->pgsz - 8) / szKey);
248058  int nSlot = 0;                  /* Number of slots in each output page */
248059  int nOut = 0;
248060
248061  /* Figure out how many output pages (nOut) and how many slots per
248062  ** page (nSlot).  There are three possibilities:
248063  **
248064  **   1. The hash table does not yet exist. In this case the new hash
248065  **      table will consist of a single page with MINSLOT slots.
248066  **
248067  **   2. The hash table exists but is currently a single page. In this
248068  **      case an attempt is made to grow the page to accommodate the new
248069  **      entry. The page is allowed to grow up to nSlotPerPage (see above)
248070  **      slots.
248071  **
248072  **   3. The hash table already consists of more than one page, or of
248073  **      a single page already so large that it cannot be grown. In this
248074  **      case the new hash consists of (nPg*2+1) pages of nSlotPerPage
248075  **      slots each, where nPg is the current number of pages in the
248076  **      hash table.
248077  */
248078  if( pSeg->nPgTombstone==0 ){
248079    /* Case 1. */
248080    nOut = 1;
248081    nSlot = MINSLOT;
248082  }else if( pSeg->nPgTombstone==1 ){
248083    /* Case 2. */
248084    int nElem = (int)fts5GetU32(&pData1->p[4]);
248085    assert( pData1 && iPg1==0 );
248086    nOut = 1;
248087    nSlot = MAX(nElem*4, MINSLOT);
248088    if( nSlot>nSlotPerPage ) nOut = 0;
248089  }
248090  if( nOut==0 ){
248091    /* Case 3. */
248092    nOut = (pSeg->nPgTombstone * 2 + 1);
248093    nSlot = nSlotPerPage;
248094  }
248095
248096  /* Allocate the required array and output pages */
248097  while( 1 ){
248098    int res = 0;
248099    int ii = 0;
248100    int szPage = 0;
248101    Fts5Data **apOut = 0;
248102
248103    /* Allocate space for the new hash table */
248104    assert( nSlot>=MINSLOT );
248105    apOut = (Fts5Data**)sqlite3Fts5MallocZero(&p->rc, sizeof(Fts5Data*) * nOut);
248106    szPage = 8 + nSlot*szKey;
248107    for(ii=0; ii<nOut; ii++){
248108      Fts5Data *pNew = (Fts5Data*)sqlite3Fts5MallocZero(&p->rc,
248109          sizeof(Fts5Data)+szPage
248110      );
248111      if( pNew ){
248112        pNew->nn = szPage;
248113        pNew->p = (u8*)&pNew[1];
248114        apOut[ii] = pNew;
248115      }
248116    }
248117
248118    /* Rebuild the hash table. */
248119    if( p->rc==SQLITE_OK ){
248120      res = fts5IndexTombstoneRehash(p, pSeg, pData1, iPg1, szKey, nOut, apOut);
248121    }
248122    if( res==0 ){
248123      if( p->rc ){
248124        fts5IndexFreeArray(apOut, nOut);
248125        apOut = 0;
248126        nOut = 0;
248127      }
248128      *pnOut = nOut;
248129      *papOut = apOut;
248130      break;
248131    }
248132
248133    /* If control flows to here, it was not possible to rebuild the hash
248134    ** table. Free all buffers and then try again with more pages. */
248135    assert( p->rc==SQLITE_OK );
248136    fts5IndexFreeArray(apOut, nOut);
248137    nSlot = nSlotPerPage;
248138    nOut = nOut*2 + 1;
248139  }
248140}
248141
248142
248143/*
248144** Add a tombstone for rowid iRowid to segment pSeg.
248145*/
248146static void fts5IndexTombstoneAdd(
248147  Fts5Index *p,
248148  Fts5StructureSegment *pSeg,
248149  u64 iRowid
248150){
248151  Fts5Data *pPg = 0;
248152  int iPg = -1;
248153  int szKey = 0;
248154  int nHash = 0;
248155  Fts5Data **apHash = 0;
248156
248157  p->nContentlessDelete++;
248158
248159  if( pSeg->nPgTombstone>0 ){
248160    iPg = iRowid % pSeg->nPgTombstone;
248161    pPg = fts5DataRead(p, FTS5_TOMBSTONE_ROWID(pSeg->iSegid,iPg));
248162    if( pPg==0 ){
248163      assert( p->rc!=SQLITE_OK );
248164      return;
248165    }
248166
248167    if( 0==fts5IndexTombstoneAddToPage(pPg, 0, pSeg->nPgTombstone, iRowid) ){
248168      fts5DataWrite(p, FTS5_TOMBSTONE_ROWID(pSeg->iSegid,iPg), pPg->p, pPg->nn);
248169      fts5DataRelease(pPg);
248170      return;
248171    }
248172  }
248173
248174  /* Have to rebuild the hash table. First figure out the key-size (4 or 8). */
248175  szKey = pPg ? TOMBSTONE_KEYSIZE(pPg) : 4;
248176  if( iRowid>0xFFFFFFFF ) szKey = 8;
248177
248178  /* Rebuild the hash table */
248179  fts5IndexTombstoneRebuild(p, pSeg, pPg, iPg, szKey, &nHash, &apHash);
248180  assert( p->rc==SQLITE_OK || (nHash==0 && apHash==0) );
248181
248182  /* If all has succeeded, write the new rowid into one of the new hash
248183  ** table pages, then write them all out to disk. */
248184  if( nHash ){
248185    int ii = 0;
248186    fts5IndexTombstoneAddToPage(apHash[iRowid % nHash], 1, nHash, iRowid);
248187    for(ii=0; ii<nHash; ii++){
248188      i64 iTombstoneRowid = FTS5_TOMBSTONE_ROWID(pSeg->iSegid, ii);
248189      fts5DataWrite(p, iTombstoneRowid, apHash[ii]->p, apHash[ii]->nn);
248190    }
248191    pSeg->nPgTombstone = nHash;
248192    fts5StructureWrite(p, p->pStruct);
248193  }
248194
248195  fts5DataRelease(pPg);
248196  fts5IndexFreeArray(apHash, nHash);
248197}
248198
248199/*
248200** Add iRowid to the tombstone list of the segment or segments that contain
248201** rows from origin iOrigin. Return SQLITE_OK if successful, or an SQLite
248202** error code otherwise.
248203*/
248204static int sqlite3Fts5IndexContentlessDelete(Fts5Index *p, i64 iOrigin, i64 iRowid){
248205  Fts5Structure *pStruct;
248206  pStruct = fts5StructureRead(p);
248207  if( pStruct ){
248208    int bFound = 0;               /* True after pSeg->nEntryTombstone incr. */
248209    int iLvl;
248210    for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
248211      int iSeg;
248212      for(iSeg=pStruct->aLevel[iLvl].nSeg-1; iSeg>=0; iSeg--){
248213        Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
248214        if( pSeg->iOrigin1<=(u64)iOrigin && pSeg->iOrigin2>=(u64)iOrigin ){
248215          if( bFound==0 ){
248216            pSeg->nEntryTombstone++;
248217            bFound = 1;
248218          }
248219          fts5IndexTombstoneAdd(p, pSeg, iRowid);
248220        }
248221      }
248222    }
248223    fts5StructureRelease(pStruct);
248224  }
248225  return fts5IndexReturn(p);
248226}
248227
248228/*************************************************************************
248229**************************************************************************
248230** Below this point is the implementation of the integrity-check
248231** functionality.
248232*/
248233
248234/*
248235** Return a simple checksum value based on the arguments.
248236*/
248237static u64 sqlite3Fts5IndexEntryCksum(
248238  i64 iRowid,
248239  int iCol,
248240  int iPos,
248241  int iIdx,
248242  const char *pTerm,
248243  int nTerm
248244){
248245  int i;
248246  u64 ret = iRowid;
248247  ret += (ret<<3) + iCol;
248248  ret += (ret<<3) + iPos;
248249  if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
248250  for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
248251  return ret;
248252}
248253
248254#ifdef SQLITE_DEBUG
248255/*
248256** This function is purely an internal test. It does not contribute to
248257** FTS functionality, or even the integrity-check, in any way.
248258**
248259** Instead, it tests that the same set of pgno/rowid combinations are
248260** visited regardless of whether the doclist-index identified by parameters
248261** iSegid/iLeaf is iterated in forwards or reverse order.
248262*/
248263static void fts5TestDlidxReverse(
248264  Fts5Index *p,
248265  int iSegid,                     /* Segment id to load from */
248266  int iLeaf                       /* Load doclist-index for this leaf */
248267){
248268  Fts5DlidxIter *pDlidx = 0;
248269  u64 cksum1 = 13;
248270  u64 cksum2 = 13;
248271
248272  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
248273      fts5DlidxIterEof(p, pDlidx)==0;
248274      fts5DlidxIterNext(p, pDlidx)
248275  ){
248276    i64 iRowid = fts5DlidxIterRowid(pDlidx);
248277    int pgno = fts5DlidxIterPgno(pDlidx);
248278    assert( pgno>iLeaf );
248279    cksum1 += iRowid + ((i64)pgno<<32);
248280  }
248281  fts5DlidxIterFree(pDlidx);
248282  pDlidx = 0;
248283
248284  for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
248285      fts5DlidxIterEof(p, pDlidx)==0;
248286      fts5DlidxIterPrev(p, pDlidx)
248287  ){
248288    i64 iRowid = fts5DlidxIterRowid(pDlidx);
248289    int pgno = fts5DlidxIterPgno(pDlidx);
248290    assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
248291    cksum2 += iRowid + ((i64)pgno<<32);
248292  }
248293  fts5DlidxIterFree(pDlidx);
248294  pDlidx = 0;
248295
248296  if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
248297}
248298
248299static int fts5QueryCksum(
248300  Fts5Index *p,                   /* Fts5 index object */
248301  int iIdx,
248302  const char *z,                  /* Index key to query for */
248303  int n,                          /* Size of index key in bytes */
248304  int flags,                      /* Flags for Fts5IndexQuery */
248305  u64 *pCksum                     /* IN/OUT: Checksum value */
248306){
248307  int eDetail = p->pConfig->eDetail;
248308  u64 cksum = *pCksum;
248309  Fts5IndexIter *pIter = 0;
248310  int rc = sqlite3Fts5IndexQuery(
248311      p, z, n, (flags | FTS5INDEX_QUERY_NOTOKENDATA), 0, &pIter
248312  );
248313
248314  while( rc==SQLITE_OK && ALWAYS(pIter!=0) && 0==sqlite3Fts5IterEof(pIter) ){
248315    i64 rowid = pIter->iRowid;
248316
248317    if( eDetail==FTS5_DETAIL_NONE ){
248318      cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
248319    }else{
248320      Fts5PoslistReader sReader;
248321      for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
248322          sReader.bEof==0;
248323          sqlite3Fts5PoslistReaderNext(&sReader)
248324      ){
248325        int iCol = FTS5_POS2COLUMN(sReader.iPos);
248326        int iOff = FTS5_POS2OFFSET(sReader.iPos);
248327        cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
248328      }
248329    }
248330    if( rc==SQLITE_OK ){
248331      rc = sqlite3Fts5IterNext(pIter);
248332    }
248333  }
248334  sqlite3Fts5IterClose(pIter);
248335
248336  *pCksum = cksum;
248337  return rc;
248338}
248339
248340/*
248341** Check if buffer z[], size n bytes, contains as series of valid utf-8
248342** encoded codepoints. If so, return 0. Otherwise, if the buffer does not
248343** contain valid utf-8, return non-zero.
248344*/
248345static int fts5TestUtf8(const char *z, int n){
248346  int i = 0;
248347  assert_nc( n>0 );
248348  while( i<n ){
248349    if( (z[i] & 0x80)==0x00 ){
248350      i++;
248351    }else
248352    if( (z[i] & 0xE0)==0xC0 ){
248353      if( i+1>=n || (z[i+1] & 0xC0)!=0x80 ) return 1;
248354      i += 2;
248355    }else
248356    if( (z[i] & 0xF0)==0xE0 ){
248357      if( i+2>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;
248358      i += 3;
248359    }else
248360    if( (z[i] & 0xF8)==0xF0 ){
248361      if( i+3>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;
248362      if( (z[i+2] & 0xC0)!=0x80 ) return 1;
248363      i += 3;
248364    }else{
248365      return 1;
248366    }
248367  }
248368
248369  return 0;
248370}
248371
248372/*
248373** This function is also purely an internal test. It does not contribute to
248374** FTS functionality, or even the integrity-check, in any way.
248375*/
248376static void fts5TestTerm(
248377  Fts5Index *p,
248378  Fts5Buffer *pPrev,              /* Previous term */
248379  const char *z, int n,           /* Possibly new term to test */
248380  u64 expected,
248381  u64 *pCksum
248382){
248383  int rc = p->rc;
248384  if( pPrev->n==0 ){
248385    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
248386  }else
248387  if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
248388    u64 cksum3 = *pCksum;
248389    const char *zTerm = (const char*)&pPrev->p[1];  /* term sans prefix-byte */
248390    int nTerm = pPrev->n-1;            /* Size of zTerm in bytes */
248391    int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
248392    int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
248393    u64 ck1 = 0;
248394    u64 ck2 = 0;
248395
248396    /* Check that the results returned for ASC and DESC queries are
248397    ** the same. If not, call this corruption.  */
248398    rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
248399    if( rc==SQLITE_OK ){
248400      int f = flags|FTS5INDEX_QUERY_DESC;
248401      rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
248402    }
248403    if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
248404
248405    /* If this is a prefix query, check that the results returned if the
248406    ** the index is disabled are the same. In both ASC and DESC order.
248407    **
248408    ** This check may only be performed if the hash table is empty. This
248409    ** is because the hash table only supports a single scan query at
248410    ** a time, and the multi-iter loop from which this function is called
248411    ** is already performing such a scan.
248412    **
248413    ** Also only do this if buffer zTerm contains nTerm bytes of valid
248414    ** utf-8. Otherwise, the last part of the buffer contents might contain
248415    ** a non-utf-8 sequence that happens to be a prefix of a valid utf-8
248416    ** character stored in the main fts index, which will cause the
248417    ** test to fail.  */
248418    if( p->nPendingData==0 && 0==fts5TestUtf8(zTerm, nTerm) ){
248419      if( iIdx>0 && rc==SQLITE_OK ){
248420        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
248421        ck2 = 0;
248422        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
248423        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
248424      }
248425      if( iIdx>0 && rc==SQLITE_OK ){
248426        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
248427        ck2 = 0;
248428        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
248429        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
248430      }
248431    }
248432
248433    cksum3 ^= ck1;
248434    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
248435
248436    if( rc==SQLITE_OK && cksum3!=expected ){
248437      rc = FTS5_CORRUPT;
248438    }
248439    *pCksum = cksum3;
248440  }
248441  p->rc = rc;
248442}
248443
248444#else
248445# define fts5TestDlidxReverse(x,y,z)
248446# define fts5TestTerm(u,v,w,x,y,z)
248447#endif
248448
248449/*
248450** Check that:
248451**
248452**   1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
248453**      contain zero terms.
248454**   2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
248455**      contain zero rowids.
248456*/
248457static void fts5IndexIntegrityCheckEmpty(
248458  Fts5Index *p,
248459  Fts5StructureSegment *pSeg,     /* Segment to check internal consistency */
248460  int iFirst,
248461  int iNoRowid,
248462  int iLast
248463){
248464  int i;
248465
248466  /* Now check that the iter.nEmpty leaves following the current leaf
248467  ** (a) exist and (b) contain no terms. */
248468  for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
248469    Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
248470    if( pLeaf ){
248471      if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
248472      if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
248473    }
248474    fts5DataRelease(pLeaf);
248475  }
248476}
248477
248478static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
248479  i64 iTermOff = 0;
248480  int ii;
248481
248482  Fts5Buffer buf1 = {0,0,0};
248483  Fts5Buffer buf2 = {0,0,0};
248484
248485  ii = pLeaf->szLeaf;
248486  while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
248487    int res;
248488    i64 iOff;
248489    int nIncr;
248490
248491    ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
248492    iTermOff += nIncr;
248493    iOff = iTermOff;
248494
248495    if( iOff>=pLeaf->szLeaf ){
248496      p->rc = FTS5_CORRUPT;
248497    }else if( iTermOff==nIncr ){
248498      int nByte;
248499      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
248500      if( (iOff+nByte)>pLeaf->szLeaf ){
248501        p->rc = FTS5_CORRUPT;
248502      }else{
248503        fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
248504      }
248505    }else{
248506      int nKeep, nByte;
248507      iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
248508      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
248509      if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
248510        p->rc = FTS5_CORRUPT;
248511      }else{
248512        buf1.n = nKeep;
248513        fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
248514      }
248515
248516      if( p->rc==SQLITE_OK ){
248517        res = fts5BufferCompare(&buf1, &buf2);
248518        if( res<=0 ) p->rc = FTS5_CORRUPT;
248519      }
248520    }
248521    fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
248522  }
248523
248524  fts5BufferFree(&buf1);
248525  fts5BufferFree(&buf2);
248526}
248527
248528static void fts5IndexIntegrityCheckSegment(
248529  Fts5Index *p,                   /* FTS5 backend object */
248530  Fts5StructureSegment *pSeg      /* Segment to check internal consistency */
248531){
248532  Fts5Config *pConfig = p->pConfig;
248533  int bSecureDelete = (pConfig->iVersion==FTS5_CURRENT_VERSION_SECUREDELETE);
248534  sqlite3_stmt *pStmt = 0;
248535  int rc2;
248536  int iIdxPrevLeaf = pSeg->pgnoFirst-1;
248537  int iDlidxPrevLeaf = pSeg->pgnoLast;
248538
248539  if( pSeg->pgnoFirst==0 ) return;
248540
248541  fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
248542      "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d "
248543      "ORDER BY 1, 2",
248544      pConfig->zDb, pConfig->zName, pSeg->iSegid
248545  ));
248546
248547  /* Iterate through the b-tree hierarchy.  */
248548  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
248549    i64 iRow;                     /* Rowid for this leaf */
248550    Fts5Data *pLeaf;              /* Data for this leaf */
248551
248552    const char *zIdxTerm = (const char*)sqlite3_column_blob(pStmt, 1);
248553    int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
248554    int iIdxLeaf = sqlite3_column_int(pStmt, 2);
248555    int bIdxDlidx = sqlite3_column_int(pStmt, 3);
248556
248557    /* If the leaf in question has already been trimmed from the segment,
248558    ** ignore this b-tree entry. Otherwise, load it into memory. */
248559    if( iIdxLeaf<pSeg->pgnoFirst ) continue;
248560    iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
248561    pLeaf = fts5LeafRead(p, iRow);
248562    if( pLeaf==0 ) break;
248563
248564    /* Check that the leaf contains at least one term, and that it is equal
248565    ** to or larger than the split-key in zIdxTerm.  Also check that if there
248566    ** is also a rowid pointer within the leaf page header, it points to a
248567    ** location before the term.  */
248568    if( pLeaf->nn<=pLeaf->szLeaf ){
248569
248570      if( nIdxTerm==0
248571       && pConfig->iVersion==FTS5_CURRENT_VERSION_SECUREDELETE
248572       && pLeaf->nn==pLeaf->szLeaf
248573       && pLeaf->nn==4
248574      ){
248575        /* special case - the very first page in a segment keeps its %_idx
248576        ** entry even if all the terms are removed from it by secure-delete
248577        ** operations. */
248578      }else{
248579        p->rc = FTS5_CORRUPT;
248580      }
248581
248582    }else{
248583      int iOff;                   /* Offset of first term on leaf */
248584      int iRowidOff;              /* Offset of first rowid on leaf */
248585      int nTerm;                  /* Size of term on leaf in bytes */
248586      int res;                    /* Comparison of term and split-key */
248587
248588      iOff = fts5LeafFirstTermOff(pLeaf);
248589      iRowidOff = fts5LeafFirstRowidOff(pLeaf);
248590      if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){
248591        p->rc = FTS5_CORRUPT;
248592      }else{
248593        iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
248594        res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
248595        if( res==0 ) res = nTerm - nIdxTerm;
248596        if( res<0 ) p->rc = FTS5_CORRUPT;
248597      }
248598
248599      fts5IntegrityCheckPgidx(p, pLeaf);
248600    }
248601    fts5DataRelease(pLeaf);
248602    if( p->rc ) break;
248603
248604    /* Now check that the iter.nEmpty leaves following the current leaf
248605    ** (a) exist and (b) contain no terms. */
248606    fts5IndexIntegrityCheckEmpty(
248607        p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
248608    );
248609    if( p->rc ) break;
248610
248611    /* If there is a doclist-index, check that it looks right. */
248612    if( bIdxDlidx ){
248613      Fts5DlidxIter *pDlidx = 0;  /* For iterating through doclist index */
248614      int iPrevLeaf = iIdxLeaf;
248615      int iSegid = pSeg->iSegid;
248616      int iPg = 0;
248617      i64 iKey;
248618
248619      for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
248620          fts5DlidxIterEof(p, pDlidx)==0;
248621          fts5DlidxIterNext(p, pDlidx)
248622      ){
248623
248624        /* Check any rowid-less pages that occur before the current leaf. */
248625        for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
248626          iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
248627          pLeaf = fts5DataRead(p, iKey);
248628          if( pLeaf ){
248629            if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
248630            fts5DataRelease(pLeaf);
248631          }
248632        }
248633        iPrevLeaf = fts5DlidxIterPgno(pDlidx);
248634
248635        /* Check that the leaf page indicated by the iterator really does
248636        ** contain the rowid suggested by the same. */
248637        iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
248638        pLeaf = fts5DataRead(p, iKey);
248639        if( pLeaf ){
248640          i64 iRowid;
248641          int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
248642          ASSERT_SZLEAF_OK(pLeaf);
248643          if( iRowidOff>=pLeaf->szLeaf ){
248644            p->rc = FTS5_CORRUPT;
248645          }else if( bSecureDelete==0 || iRowidOff>0 ){
248646            i64 iDlRowid = fts5DlidxIterRowid(pDlidx);
248647            fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
248648            if( iRowid<iDlRowid || (bSecureDelete==0 && iRowid!=iDlRowid) ){
248649              p->rc = FTS5_CORRUPT;
248650            }
248651          }
248652          fts5DataRelease(pLeaf);
248653        }
248654      }
248655
248656      iDlidxPrevLeaf = iPg;
248657      fts5DlidxIterFree(pDlidx);
248658      fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
248659    }else{
248660      iDlidxPrevLeaf = pSeg->pgnoLast;
248661      /* TODO: Check there is no doclist index */
248662    }
248663
248664    iIdxPrevLeaf = iIdxLeaf;
248665  }
248666
248667  rc2 = sqlite3_finalize(pStmt);
248668  if( p->rc==SQLITE_OK ) p->rc = rc2;
248669
248670  /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
248671#if 0
248672  if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
248673    p->rc = FTS5_CORRUPT;
248674  }
248675#endif
248676}
248677
248678
248679/*
248680** Run internal checks to ensure that the FTS index (a) is internally
248681** consistent and (b) contains entries for which the XOR of the checksums
248682** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
248683**
248684** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
248685** checksum does not match. Return SQLITE_OK if all checks pass without
248686** error, or some other SQLite error code if another error (e.g. OOM)
248687** occurs.
248688*/
248689static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum){
248690  int eDetail = p->pConfig->eDetail;
248691  u64 cksum2 = 0;                 /* Checksum based on contents of indexes */
248692  Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */
248693  Fts5Iter *pIter;                /* Used to iterate through entire index */
248694  Fts5Structure *pStruct;         /* Index structure */
248695  int iLvl, iSeg;
248696
248697#ifdef SQLITE_DEBUG
248698  /* Used by extra internal tests only run if NDEBUG is not defined */
248699  u64 cksum3 = 0;                 /* Checksum based on contents of indexes */
248700  Fts5Buffer term = {0,0,0};      /* Buffer used to hold most recent term */
248701#endif
248702  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
248703
248704  /* Load the FTS index structure */
248705  pStruct = fts5StructureRead(p);
248706  if( pStruct==0 ){
248707    assert( p->rc!=SQLITE_OK );
248708    return fts5IndexReturn(p);
248709  }
248710
248711  /* Check that the internal nodes of each segment match the leaves */
248712  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
248713    for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
248714      Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
248715      fts5IndexIntegrityCheckSegment(p, pSeg);
248716    }
248717  }
248718
248719  /* The cksum argument passed to this function is a checksum calculated
248720  ** based on all expected entries in the FTS index (including prefix index
248721  ** entries). This block checks that a checksum calculated based on the
248722  ** actual contents of FTS index is identical.
248723  **
248724  ** Two versions of the same checksum are calculated. The first (stack
248725  ** variable cksum2) based on entries extracted from the full-text index
248726  ** while doing a linear scan of each individual index in turn.
248727  **
248728  ** As each term visited by the linear scans, a separate query for the
248729  ** same term is performed. cksum3 is calculated based on the entries
248730  ** extracted by these queries.
248731  */
248732  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
248733      fts5MultiIterEof(p, pIter)==0;
248734      fts5MultiIterNext(p, pIter, 0, 0)
248735  ){
248736    int n;                      /* Size of term in bytes */
248737    i64 iPos = 0;               /* Position read from poslist */
248738    int iOff = 0;               /* Offset within poslist */
248739    i64 iRowid = fts5MultiIterRowid(pIter);
248740    char *z = (char*)fts5MultiIterTerm(pIter, &n);
248741
248742    /* If this is a new term, query for it. Update cksum3 with the results. */
248743    fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
248744    if( p->rc ) break;
248745
248746    if( eDetail==FTS5_DETAIL_NONE ){
248747      if( 0==fts5MultiIterIsEmpty(p, pIter) ){
248748        cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
248749      }
248750    }else{
248751      poslist.n = 0;
248752      fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
248753      fts5BufferAppendBlob(&p->rc, &poslist, 4, (const u8*)"\0\0\0\0");
248754      while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
248755        int iCol = FTS5_POS2COLUMN(iPos);
248756        int iTokOff = FTS5_POS2OFFSET(iPos);
248757        cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
248758      }
248759    }
248760  }
248761  fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
248762
248763  fts5MultiIterFree(pIter);
248764  if( p->rc==SQLITE_OK && bUseCksum && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
248765
248766  fts5StructureRelease(pStruct);
248767#ifdef SQLITE_DEBUG
248768  fts5BufferFree(&term);
248769#endif
248770  fts5BufferFree(&poslist);
248771  return fts5IndexReturn(p);
248772}
248773
248774/*************************************************************************
248775**************************************************************************
248776** Below this point is the implementation of the fts5_decode() scalar
248777** function only.
248778*/
248779
248780#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
248781/*
248782** Decode a segment-data rowid from the %_data table. This function is
248783** the opposite of macro FTS5_SEGMENT_ROWID().
248784*/
248785static void fts5DecodeRowid(
248786  i64 iRowid,                     /* Rowid from %_data table */
248787  int *pbTombstone,               /* OUT: Tombstone hash flag */
248788  int *piSegid,                   /* OUT: Segment id */
248789  int *pbDlidx,                   /* OUT: Dlidx flag */
248790  int *piHeight,                  /* OUT: Height */
248791  int *piPgno                     /* OUT: Page number */
248792){
248793  *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
248794  iRowid >>= FTS5_DATA_PAGE_B;
248795
248796  *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
248797  iRowid >>= FTS5_DATA_HEIGHT_B;
248798
248799  *pbDlidx = (int)(iRowid & 0x0001);
248800  iRowid >>= FTS5_DATA_DLI_B;
248801
248802  *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
248803  iRowid >>= FTS5_DATA_ID_B;
248804
248805  *pbTombstone = (int)(iRowid & 0x0001);
248806}
248807#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
248808
248809#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
248810static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
248811  int iSegid, iHeight, iPgno, bDlidx, bTomb;     /* Rowid compenents */
248812  fts5DecodeRowid(iKey, &bTomb, &iSegid, &bDlidx, &iHeight, &iPgno);
248813
248814  if( iSegid==0 ){
248815    if( iKey==FTS5_AVERAGES_ROWID ){
248816      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
248817    }else{
248818      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
248819    }
248820  }
248821  else{
248822    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%s%ssegid=%d h=%d pgno=%d}",
248823        bDlidx ? "dlidx " : "",
248824        bTomb ? "tombstone " : "",
248825        iSegid, iHeight, iPgno
248826    );
248827  }
248828}
248829#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
248830
248831#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
248832static void fts5DebugStructure(
248833  int *pRc,                       /* IN/OUT: error code */
248834  Fts5Buffer *pBuf,
248835  Fts5Structure *p
248836){
248837  int iLvl, iSeg;                 /* Iterate through levels, segments */
248838
248839  for(iLvl=0; iLvl<p->nLevel; iLvl++){
248840    Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
248841    sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
248842        " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
248843    );
248844    for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
248845      Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
248846      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d",
248847          pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
248848      );
248849      if( pSeg->iOrigin1>0 ){
248850        sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " origin=%lld..%lld",
248851            pSeg->iOrigin1, pSeg->iOrigin2
248852        );
248853      }
248854      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
248855    }
248856    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
248857  }
248858}
248859#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
248860
248861#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
248862/*
248863** This is part of the fts5_decode() debugging aid.
248864**
248865** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
248866** function appends a human-readable representation of the same object
248867** to the buffer passed as the second argument.
248868*/
248869static void fts5DecodeStructure(
248870  int *pRc,                       /* IN/OUT: error code */
248871  Fts5Buffer *pBuf,
248872  const u8 *pBlob, int nBlob
248873){
248874  int rc;                         /* Return code */
248875  Fts5Structure *p = 0;           /* Decoded structure object */
248876
248877  rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
248878  if( rc!=SQLITE_OK ){
248879    *pRc = rc;
248880    return;
248881  }
248882
248883  fts5DebugStructure(pRc, pBuf, p);
248884  fts5StructureRelease(p);
248885}
248886#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
248887
248888#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
248889/*
248890** This is part of the fts5_decode() debugging aid.
248891**
248892** Arguments pBlob/nBlob contain an "averages" record. This function
248893** appends a human-readable representation of record to the buffer passed
248894** as the second argument.
248895*/
248896static void fts5DecodeAverages(
248897  int *pRc,                       /* IN/OUT: error code */
248898  Fts5Buffer *pBuf,
248899  const u8 *pBlob, int nBlob
248900){
248901  int i = 0;
248902  const char *zSpace = "";
248903
248904  while( i<nBlob ){
248905    u64 iVal;
248906    i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
248907    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
248908    zSpace = " ";
248909  }
248910}
248911#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
248912
248913#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
248914/*
248915** Buffer (a/n) is assumed to contain a list of serialized varints. Read
248916** each varint and append its string representation to buffer pBuf. Return
248917** after either the input buffer is exhausted or a 0 value is read.
248918**
248919** The return value is the number of bytes read from the input buffer.
248920*/
248921static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
248922  int iOff = 0;
248923  while( iOff<n ){
248924    int iVal;
248925    iOff += fts5GetVarint32(&a[iOff], iVal);
248926    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
248927  }
248928  return iOff;
248929}
248930#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
248931
248932#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
248933/*
248934** The start of buffer (a/n) contains the start of a doclist. The doclist
248935** may or may not finish within the buffer. This function appends a text
248936** representation of the part of the doclist that is present to buffer
248937** pBuf.
248938**
248939** The return value is the number of bytes read from the input buffer.
248940*/
248941static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
248942  i64 iDocid = 0;
248943  int iOff = 0;
248944
248945  if( n>0 ){
248946    iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
248947    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
248948  }
248949  while( iOff<n ){
248950    int nPos;
248951    int bDel;
248952    iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
248953    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
248954    iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
248955    if( iOff<n ){
248956      i64 iDelta;
248957      iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
248958      iDocid += iDelta;
248959      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
248960    }
248961  }
248962
248963  return iOff;
248964}
248965#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
248966
248967#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
248968/*
248969** This function is part of the fts5_decode() debugging function. It is
248970** only ever used with detail=none tables.
248971**
248972** Buffer (pData/nData) contains a doclist in the format used by detail=none
248973** tables. This function appends a human-readable version of that list to
248974** buffer pBuf.
248975**
248976** If *pRc is other than SQLITE_OK when this function is called, it is a
248977** no-op. If an OOM or other error occurs within this function, *pRc is
248978** set to an SQLite error code before returning. The final state of buffer
248979** pBuf is undefined in this case.
248980*/
248981static void fts5DecodeRowidList(
248982  int *pRc,                       /* IN/OUT: Error code */
248983  Fts5Buffer *pBuf,               /* Buffer to append text to */
248984  const u8 *pData, int nData      /* Data to decode list-of-rowids from */
248985){
248986  int i = 0;
248987  i64 iRowid = 0;
248988
248989  while( i<nData ){
248990    const char *zApp = "";
248991    u64 iVal;
248992    i += sqlite3Fts5GetVarint(&pData[i], &iVal);
248993    iRowid += iVal;
248994
248995    if( i<nData && pData[i]==0x00 ){
248996      i++;
248997      if( i<nData && pData[i]==0x00 ){
248998        i++;
248999        zApp = "+";
249000      }else{
249001        zApp = "*";
249002      }
249003    }
249004
249005    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
249006  }
249007}
249008#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
249009
249010#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
249011static void fts5BufferAppendTerm(int *pRc, Fts5Buffer *pBuf, Fts5Buffer *pTerm){
249012  int ii;
249013  fts5BufferGrow(pRc, pBuf, pTerm->n*2 + 1);
249014  if( *pRc==SQLITE_OK ){
249015    for(ii=0; ii<pTerm->n; ii++){
249016      if( pTerm->p[ii]==0x00 ){
249017        pBuf->p[pBuf->n++] = '\\';
249018        pBuf->p[pBuf->n++] = '0';
249019      }else{
249020        pBuf->p[pBuf->n++] = pTerm->p[ii];
249021      }
249022    }
249023    pBuf->p[pBuf->n] = 0x00;
249024  }
249025}
249026#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
249027
249028#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
249029/*
249030** The implementation of user-defined scalar function fts5_decode().
249031*/
249032static void fts5DecodeFunction(
249033  sqlite3_context *pCtx,          /* Function call context */
249034  int nArg,                       /* Number of args (always 2) */
249035  sqlite3_value **apVal           /* Function arguments */
249036){
249037  i64 iRowid;                     /* Rowid for record being decoded */
249038  int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
249039  int bTomb;
249040  const u8 *aBlob; int n;         /* Record to decode */
249041  u8 *a = 0;
249042  Fts5Buffer s;                   /* Build up text to return here */
249043  int rc = SQLITE_OK;             /* Return code */
249044  sqlite3_int64 nSpace = 0;
249045  int eDetailNone = (sqlite3_user_data(pCtx)!=0);
249046
249047  assert( nArg==2 );
249048  UNUSED_PARAM(nArg);
249049  memset(&s, 0, sizeof(Fts5Buffer));
249050  iRowid = sqlite3_value_int64(apVal[0]);
249051
249052  /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
249053  ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
249054  ** buffer overreads even if the record is corrupt.  */
249055  n = sqlite3_value_bytes(apVal[1]);
249056  aBlob = sqlite3_value_blob(apVal[1]);
249057  nSpace = n + FTS5_DATA_ZERO_PADDING;
249058  a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
249059  if( a==0 ) goto decode_out;
249060  if( n>0 ) memcpy(a, aBlob, n);
249061
249062  fts5DecodeRowid(iRowid, &bTomb, &iSegid, &bDlidx, &iHeight, &iPgno);
249063
249064  fts5DebugRowid(&rc, &s, iRowid);
249065  if( bDlidx ){
249066    Fts5Data dlidx;
249067    Fts5DlidxLvl lvl;
249068
249069    dlidx.p = a;
249070    dlidx.nn = n;
249071
249072    memset(&lvl, 0, sizeof(Fts5DlidxLvl));
249073    lvl.pData = &dlidx;
249074    lvl.iLeafPgno = iPgno;
249075
249076    for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
249077      sqlite3Fts5BufferAppendPrintf(&rc, &s,
249078          " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
249079      );
249080    }
249081  }else if( bTomb ){
249082    u32 nElem  = fts5GetU32(&a[4]);
249083    int szKey = (aBlob[0]==4 || aBlob[0]==8) ? aBlob[0] : 8;
249084    int nSlot = (n - 8) / szKey;
249085    int ii;
249086    sqlite3Fts5BufferAppendPrintf(&rc, &s, " nElem=%d", (int)nElem);
249087    if( aBlob[1] ){
249088      sqlite3Fts5BufferAppendPrintf(&rc, &s, " 0");
249089    }
249090    for(ii=0; ii<nSlot; ii++){
249091      u64 iVal = 0;
249092      if( szKey==4 ){
249093        u32 *aSlot = (u32*)&aBlob[8];
249094        if( aSlot[ii] ) iVal = fts5GetU32((u8*)&aSlot[ii]);
249095      }else{
249096        u64 *aSlot = (u64*)&aBlob[8];
249097        if( aSlot[ii] ) iVal = fts5GetU64((u8*)&aSlot[ii]);
249098      }
249099      if( iVal!=0 ){
249100        sqlite3Fts5BufferAppendPrintf(&rc, &s, " %lld", (i64)iVal);
249101      }
249102    }
249103  }else if( iSegid==0 ){
249104    if( iRowid==FTS5_AVERAGES_ROWID ){
249105      fts5DecodeAverages(&rc, &s, a, n);
249106    }else{
249107      fts5DecodeStructure(&rc, &s, a, n);
249108    }
249109  }else if( eDetailNone ){
249110    Fts5Buffer term;              /* Current term read from page */
249111    int szLeaf;
249112    int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
249113    int iTermOff;
249114    int nKeep = 0;
249115    int iOff;
249116
249117    memset(&term, 0, sizeof(Fts5Buffer));
249118
249119    /* Decode any entries that occur before the first term. */
249120    if( szLeaf<n ){
249121      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
249122    }else{
249123      iTermOff = szLeaf;
249124    }
249125    fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
249126
249127    iOff = iTermOff;
249128    while( iOff<szLeaf && rc==SQLITE_OK ){
249129      int nAppend;
249130
249131      /* Read the term data for the next term*/
249132      iOff += fts5GetVarint32(&a[iOff], nAppend);
249133      term.n = nKeep;
249134      fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
249135      sqlite3Fts5BufferAppendPrintf(&rc, &s, " term=");
249136      fts5BufferAppendTerm(&rc, &s, &term);
249137      iOff += nAppend;
249138
249139      /* Figure out where the doclist for this term ends */
249140      if( iPgidxOff<n ){
249141        int nIncr;
249142        iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
249143        iTermOff += nIncr;
249144      }else{
249145        iTermOff = szLeaf;
249146      }
249147      if( iTermOff>szLeaf ){
249148        rc = FTS5_CORRUPT;
249149      }else{
249150        fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
249151      }
249152      iOff = iTermOff;
249153      if( iOff<szLeaf ){
249154        iOff += fts5GetVarint32(&a[iOff], nKeep);
249155      }
249156    }
249157
249158    fts5BufferFree(&term);
249159  }else{
249160    Fts5Buffer term;              /* Current term read from page */
249161    int szLeaf;                   /* Offset of pgidx in a[] */
249162    int iPgidxOff;
249163    int iPgidxPrev = 0;           /* Previous value read from pgidx */
249164    int iTermOff = 0;
249165    int iRowidOff = 0;
249166    int iOff;
249167    int nDoclist;
249168
249169    memset(&term, 0, sizeof(Fts5Buffer));
249170
249171    if( n<4 ){
249172      sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
249173      goto decode_out;
249174    }else{
249175      iRowidOff = fts5GetU16(&a[0]);
249176      iPgidxOff = szLeaf = fts5GetU16(&a[2]);
249177      if( iPgidxOff<n ){
249178        fts5GetVarint32(&a[iPgidxOff], iTermOff);
249179      }else if( iPgidxOff>n ){
249180        rc = FTS5_CORRUPT;
249181        goto decode_out;
249182      }
249183    }
249184
249185    /* Decode the position list tail at the start of the page */
249186    if( iRowidOff!=0 ){
249187      iOff = iRowidOff;
249188    }else if( iTermOff!=0 ){
249189      iOff = iTermOff;
249190    }else{
249191      iOff = szLeaf;
249192    }
249193    if( iOff>n ){
249194      rc = FTS5_CORRUPT;
249195      goto decode_out;
249196    }
249197    fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
249198
249199    /* Decode any more doclist data that appears on the page before the
249200    ** first term. */
249201    nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
249202    if( nDoclist+iOff>n ){
249203      rc = FTS5_CORRUPT;
249204      goto decode_out;
249205    }
249206    fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
249207
249208    while( iPgidxOff<n && rc==SQLITE_OK ){
249209      int bFirst = (iPgidxOff==szLeaf);     /* True for first term on page */
249210      int nByte;                            /* Bytes of data */
249211      int iEnd;
249212
249213      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
249214      iPgidxPrev += nByte;
249215      iOff = iPgidxPrev;
249216
249217      if( iPgidxOff<n ){
249218        fts5GetVarint32(&a[iPgidxOff], nByte);
249219        iEnd = iPgidxPrev + nByte;
249220      }else{
249221        iEnd = szLeaf;
249222      }
249223      if( iEnd>szLeaf ){
249224        rc = FTS5_CORRUPT;
249225        break;
249226      }
249227
249228      if( bFirst==0 ){
249229        iOff += fts5GetVarint32(&a[iOff], nByte);
249230        if( nByte>term.n ){
249231          rc = FTS5_CORRUPT;
249232          break;
249233        }
249234        term.n = nByte;
249235      }
249236      iOff += fts5GetVarint32(&a[iOff], nByte);
249237      if( iOff+nByte>n ){
249238        rc = FTS5_CORRUPT;
249239        break;
249240      }
249241      fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
249242      iOff += nByte;
249243
249244      sqlite3Fts5BufferAppendPrintf(&rc, &s, " term=");
249245      fts5BufferAppendTerm(&rc, &s, &term);
249246      iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
249247    }
249248
249249    fts5BufferFree(&term);
249250  }
249251
249252 decode_out:
249253  sqlite3_free(a);
249254  if( rc==SQLITE_OK ){
249255    sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
249256  }else{
249257    sqlite3_result_error_code(pCtx, rc);
249258  }
249259  fts5BufferFree(&s);
249260}
249261#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
249262
249263#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
249264/*
249265** The implementation of user-defined scalar function fts5_rowid().
249266*/
249267static void fts5RowidFunction(
249268  sqlite3_context *pCtx,          /* Function call context */
249269  int nArg,                       /* Number of args (always 2) */
249270  sqlite3_value **apVal           /* Function arguments */
249271){
249272  const char *zArg;
249273  if( nArg==0 ){
249274    sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
249275  }else{
249276    zArg = (const char*)sqlite3_value_text(apVal[0]);
249277    if( 0==sqlite3_stricmp(zArg, "segment") ){
249278      i64 iRowid;
249279      int segid, pgno;
249280      if( nArg!=3 ){
249281        sqlite3_result_error(pCtx,
249282            "should be: fts5_rowid('segment', segid, pgno))", -1
249283        );
249284      }else{
249285        segid = sqlite3_value_int(apVal[1]);
249286        pgno = sqlite3_value_int(apVal[2]);
249287        iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
249288        sqlite3_result_int64(pCtx, iRowid);
249289      }
249290    }else{
249291      sqlite3_result_error(pCtx,
249292        "first arg to fts5_rowid() must be 'segment'" , -1
249293      );
249294    }
249295  }
249296}
249297#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
249298
249299#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
249300
249301typedef struct Fts5StructVtab Fts5StructVtab;
249302struct Fts5StructVtab {
249303  sqlite3_vtab base;
249304};
249305
249306typedef struct Fts5StructVcsr Fts5StructVcsr;
249307struct Fts5StructVcsr {
249308  sqlite3_vtab_cursor base;
249309  Fts5Structure *pStruct;
249310  int iLevel;
249311  int iSeg;
249312  int iRowid;
249313};
249314
249315/*
249316** Create a new fts5_structure() table-valued function.
249317*/
249318static int fts5structConnectMethod(
249319  sqlite3 *db,
249320  void *pAux,
249321  int argc, const char *const*argv,
249322  sqlite3_vtab **ppVtab,
249323  char **pzErr
249324){
249325  Fts5StructVtab *pNew = 0;
249326  int rc = SQLITE_OK;
249327
249328  rc = sqlite3_declare_vtab(db,
249329      "CREATE TABLE xyz("
249330          "level, segment, merge, segid, leaf1, leaf2, loc1, loc2, "
249331          "npgtombstone, nentrytombstone, nentry, struct HIDDEN);"
249332  );
249333  if( rc==SQLITE_OK ){
249334    pNew = sqlite3Fts5MallocZero(&rc, sizeof(*pNew));
249335  }
249336
249337  *ppVtab = (sqlite3_vtab*)pNew;
249338  return rc;
249339}
249340
249341/*
249342** We must have a single struct=? constraint that will be passed through
249343** into the xFilter method.  If there is no valid stmt=? constraint,
249344** then return an SQLITE_CONSTRAINT error.
249345*/
249346static int fts5structBestIndexMethod(
249347  sqlite3_vtab *tab,
249348  sqlite3_index_info *pIdxInfo
249349){
249350  int i;
249351  int rc = SQLITE_CONSTRAINT;
249352  struct sqlite3_index_constraint *p;
249353  pIdxInfo->estimatedCost = (double)100;
249354  pIdxInfo->estimatedRows = 100;
249355  pIdxInfo->idxNum = 0;
249356  for(i=0, p=pIdxInfo->aConstraint; i<pIdxInfo->nConstraint; i++, p++){
249357    if( p->usable==0 ) continue;
249358    if( p->op==SQLITE_INDEX_CONSTRAINT_EQ && p->iColumn==11 ){
249359      rc = SQLITE_OK;
249360      pIdxInfo->aConstraintUsage[i].omit = 1;
249361      pIdxInfo->aConstraintUsage[i].argvIndex = 1;
249362      break;
249363    }
249364  }
249365  return rc;
249366}
249367
249368/*
249369** This method is the destructor for bytecodevtab objects.
249370*/
249371static int fts5structDisconnectMethod(sqlite3_vtab *pVtab){
249372  Fts5StructVtab *p = (Fts5StructVtab*)pVtab;
249373  sqlite3_free(p);
249374  return SQLITE_OK;
249375}
249376
249377/*
249378** Constructor for a new bytecodevtab_cursor object.
249379*/
249380static int fts5structOpenMethod(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
249381  int rc = SQLITE_OK;
249382  Fts5StructVcsr *pNew = 0;
249383
249384  pNew = sqlite3Fts5MallocZero(&rc, sizeof(*pNew));
249385  *ppCsr = (sqlite3_vtab_cursor*)pNew;
249386
249387  return SQLITE_OK;
249388}
249389
249390/*
249391** Destructor for a bytecodevtab_cursor.
249392*/
249393static int fts5structCloseMethod(sqlite3_vtab_cursor *cur){
249394  Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
249395  fts5StructureRelease(pCsr->pStruct);
249396  sqlite3_free(pCsr);
249397  return SQLITE_OK;
249398}
249399
249400
249401/*
249402** Advance a bytecodevtab_cursor to its next row of output.
249403*/
249404static int fts5structNextMethod(sqlite3_vtab_cursor *cur){
249405  Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
249406  Fts5Structure *p = pCsr->pStruct;
249407
249408  assert( pCsr->pStruct );
249409  pCsr->iSeg++;
249410  pCsr->iRowid++;
249411  while( pCsr->iLevel<p->nLevel && pCsr->iSeg>=p->aLevel[pCsr->iLevel].nSeg ){
249412    pCsr->iLevel++;
249413    pCsr->iSeg = 0;
249414  }
249415  if( pCsr->iLevel>=p->nLevel ){
249416    fts5StructureRelease(pCsr->pStruct);
249417    pCsr->pStruct = 0;
249418  }
249419  return SQLITE_OK;
249420}
249421
249422/*
249423** Return TRUE if the cursor has been moved off of the last
249424** row of output.
249425*/
249426static int fts5structEofMethod(sqlite3_vtab_cursor *cur){
249427  Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
249428  return pCsr->pStruct==0;
249429}
249430
249431static int fts5structRowidMethod(
249432  sqlite3_vtab_cursor *cur,
249433  sqlite_int64 *piRowid
249434){
249435  Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
249436  *piRowid = pCsr->iRowid;
249437  return SQLITE_OK;
249438}
249439
249440/*
249441** Return values of columns for the row at which the bytecodevtab_cursor
249442** is currently pointing.
249443*/
249444static int fts5structColumnMethod(
249445  sqlite3_vtab_cursor *cur,   /* The cursor */
249446  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
249447  int i                       /* Which column to return */
249448){
249449  Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
249450  Fts5Structure *p = pCsr->pStruct;
249451  Fts5StructureSegment *pSeg = &p->aLevel[pCsr->iLevel].aSeg[pCsr->iSeg];
249452
249453  switch( i ){
249454    case 0: /* level */
249455      sqlite3_result_int(ctx, pCsr->iLevel);
249456      break;
249457    case 1: /* segment */
249458      sqlite3_result_int(ctx, pCsr->iSeg);
249459      break;
249460    case 2: /* merge */
249461      sqlite3_result_int(ctx, pCsr->iSeg < p->aLevel[pCsr->iLevel].nMerge);
249462      break;
249463    case 3: /* segid */
249464      sqlite3_result_int(ctx, pSeg->iSegid);
249465      break;
249466    case 4: /* leaf1 */
249467      sqlite3_result_int(ctx, pSeg->pgnoFirst);
249468      break;
249469    case 5: /* leaf2 */
249470      sqlite3_result_int(ctx, pSeg->pgnoLast);
249471      break;
249472    case 6: /* origin1 */
249473      sqlite3_result_int64(ctx, pSeg->iOrigin1);
249474      break;
249475    case 7: /* origin2 */
249476      sqlite3_result_int64(ctx, pSeg->iOrigin2);
249477      break;
249478    case 8: /* npgtombstone */
249479      sqlite3_result_int(ctx, pSeg->nPgTombstone);
249480      break;
249481    case 9: /* nentrytombstone */
249482      sqlite3_result_int64(ctx, pSeg->nEntryTombstone);
249483      break;
249484    case 10: /* nentry */
249485      sqlite3_result_int64(ctx, pSeg->nEntry);
249486      break;
249487  }
249488  return SQLITE_OK;
249489}
249490
249491/*
249492** Initialize a cursor.
249493**
249494**    idxNum==0     means show all subprograms
249495**    idxNum==1     means show only the main bytecode and omit subprograms.
249496*/
249497static int fts5structFilterMethod(
249498  sqlite3_vtab_cursor *pVtabCursor,
249499  int idxNum, const char *idxStr,
249500  int argc, sqlite3_value **argv
249501){
249502  Fts5StructVcsr *pCsr = (Fts5StructVcsr *)pVtabCursor;
249503  int rc = SQLITE_OK;
249504
249505  const u8 *aBlob = 0;
249506  int nBlob = 0;
249507
249508  assert( argc==1 );
249509  fts5StructureRelease(pCsr->pStruct);
249510  pCsr->pStruct = 0;
249511
249512  nBlob = sqlite3_value_bytes(argv[0]);
249513  aBlob = (const u8*)sqlite3_value_blob(argv[0]);
249514  rc = fts5StructureDecode(aBlob, nBlob, 0, &pCsr->pStruct);
249515  if( rc==SQLITE_OK ){
249516    pCsr->iLevel = 0;
249517    pCsr->iRowid = 0;
249518    pCsr->iSeg = -1;
249519    rc = fts5structNextMethod(pVtabCursor);
249520  }
249521
249522  return rc;
249523}
249524
249525#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
249526
249527/*
249528** This is called as part of registering the FTS5 module with database
249529** connection db. It registers several user-defined scalar functions useful
249530** with FTS5.
249531**
249532** If successful, SQLITE_OK is returned. If an error occurs, some other
249533** SQLite error code is returned instead.
249534*/
249535static int sqlite3Fts5IndexInit(sqlite3 *db){
249536#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
249537  int rc = sqlite3_create_function(
249538      db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
249539  );
249540
249541  if( rc==SQLITE_OK ){
249542    rc = sqlite3_create_function(
249543        db, "fts5_decode_none", 2,
249544        SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
249545    );
249546  }
249547
249548  if( rc==SQLITE_OK ){
249549    rc = sqlite3_create_function(
249550        db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
249551    );
249552  }
249553
249554  if( rc==SQLITE_OK ){
249555    static const sqlite3_module fts5structure_module = {
249556      0,                           /* iVersion      */
249557      0,                           /* xCreate       */
249558      fts5structConnectMethod,     /* xConnect      */
249559      fts5structBestIndexMethod,   /* xBestIndex    */
249560      fts5structDisconnectMethod,  /* xDisconnect   */
249561      0,                           /* xDestroy      */
249562      fts5structOpenMethod,        /* xOpen         */
249563      fts5structCloseMethod,       /* xClose        */
249564      fts5structFilterMethod,      /* xFilter       */
249565      fts5structNextMethod,        /* xNext         */
249566      fts5structEofMethod,         /* xEof          */
249567      fts5structColumnMethod,      /* xColumn       */
249568      fts5structRowidMethod,       /* xRowid        */
249569      0,                           /* xUpdate       */
249570      0,                           /* xBegin        */
249571      0,                           /* xSync         */
249572      0,                           /* xCommit       */
249573      0,                           /* xRollback     */
249574      0,                           /* xFindFunction */
249575      0,                           /* xRename       */
249576      0,                           /* xSavepoint    */
249577      0,                           /* xRelease      */
249578      0,                           /* xRollbackTo   */
249579      0,                           /* xShadowName   */
249580      0                            /* xIntegrity    */
249581    };
249582    rc = sqlite3_create_module(db, "fts5_structure", &fts5structure_module, 0);
249583  }
249584  return rc;
249585#else
249586  return SQLITE_OK;
249587  UNUSED_PARAM(db);
249588#endif
249589}
249590
249591
249592static int sqlite3Fts5IndexReset(Fts5Index *p){
249593  assert( p->pStruct==0 || p->iStructVersion!=0 );
249594  if( fts5IndexDataVersion(p)!=p->iStructVersion ){
249595    fts5StructureInvalidate(p);
249596  }
249597  return fts5IndexReturn(p);
249598}
249599
249600/*
249601** 2014 Jun 09
249602**
249603** The author disclaims copyright to this source code.  In place of
249604** a legal notice, here is a blessing:
249605**
249606**    May you do good and not evil.
249607**    May you find forgiveness for yourself and forgive others.
249608**    May you share freely, never taking more than you give.
249609**
249610******************************************************************************
249611**
249612** This is an SQLite module implementing full-text search.
249613*/
249614
249615
249616/* #include "fts5Int.h" */
249617
249618/*
249619** This variable is set to false when running tests for which the on disk
249620** structures should not be corrupt. Otherwise, true. If it is false, extra
249621** assert() conditions in the fts5 code are activated - conditions that are
249622** only true if it is guaranteed that the fts5 database is not corrupt.
249623*/
249624#ifdef SQLITE_DEBUG
249625SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
249626#endif
249627
249628
249629typedef struct Fts5Auxdata Fts5Auxdata;
249630typedef struct Fts5Auxiliary Fts5Auxiliary;
249631typedef struct Fts5Cursor Fts5Cursor;
249632typedef struct Fts5FullTable Fts5FullTable;
249633typedef struct Fts5Sorter Fts5Sorter;
249634typedef struct Fts5TokenizerModule Fts5TokenizerModule;
249635
249636/*
249637** NOTES ON TRANSACTIONS:
249638**
249639** SQLite invokes the following virtual table methods as transactions are
249640** opened and closed by the user:
249641**
249642**     xBegin():    Start of a new transaction.
249643**     xSync():     Initial part of two-phase commit.
249644**     xCommit():   Final part of two-phase commit.
249645**     xRollback(): Rollback the transaction.
249646**
249647** Anything that is required as part of a commit that may fail is performed
249648** in the xSync() callback. Current versions of SQLite ignore any errors
249649** returned by xCommit().
249650**
249651** And as sub-transactions are opened/closed:
249652**
249653**     xSavepoint(int S):  Open savepoint S.
249654**     xRelease(int S):    Commit and close savepoint S.
249655**     xRollbackTo(int S): Rollback to start of savepoint S.
249656**
249657** During a write-transaction the fts5_index.c module may cache some data
249658** in-memory. It is flushed to disk whenever xSync(), xRelease() or
249659** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
249660** is called.
249661**
249662** Additionally, if SQLITE_DEBUG is defined, an instance of the following
249663** structure is used to record the current transaction state. This information
249664** is not required, but it is used in the assert() statements executed by
249665** function fts5CheckTransactionState() (see below).
249666*/
249667struct Fts5TransactionState {
249668  int eState;                     /* 0==closed, 1==open, 2==synced */
249669  int iSavepoint;                 /* Number of open savepoints (0 -> none) */
249670};
249671
249672/*
249673** A single object of this type is allocated when the FTS5 module is
249674** registered with a database handle. It is used to store pointers to
249675** all registered FTS5 extensions - tokenizers and auxiliary functions.
249676*/
249677struct Fts5Global {
249678  fts5_api api;                   /* User visible part of object (see fts5.h) */
249679  sqlite3 *db;                    /* Associated database connection */
249680  i64 iNextId;                    /* Used to allocate unique cursor ids */
249681  Fts5Auxiliary *pAux;            /* First in list of all aux. functions */
249682  Fts5TokenizerModule *pTok;      /* First in list of all tokenizer modules */
249683  Fts5TokenizerModule *pDfltTok;  /* Default tokenizer module */
249684  Fts5Cursor *pCsr;               /* First in list of all open cursors */
249685};
249686
249687/*
249688** Each auxiliary function registered with the FTS5 module is represented
249689** by an object of the following type. All such objects are stored as part
249690** of the Fts5Global.pAux list.
249691*/
249692struct Fts5Auxiliary {
249693  Fts5Global *pGlobal;            /* Global context for this function */
249694  char *zFunc;                    /* Function name (nul-terminated) */
249695  void *pUserData;                /* User-data pointer */
249696  fts5_extension_function xFunc;  /* Callback function */
249697  void (*xDestroy)(void*);        /* Destructor function */
249698  Fts5Auxiliary *pNext;           /* Next registered auxiliary function */
249699};
249700
249701/*
249702** Each tokenizer module registered with the FTS5 module is represented
249703** by an object of the following type. All such objects are stored as part
249704** of the Fts5Global.pTok list.
249705*/
249706struct Fts5TokenizerModule {
249707  char *zName;                    /* Name of tokenizer */
249708  void *pUserData;                /* User pointer passed to xCreate() */
249709  fts5_tokenizer x;               /* Tokenizer functions */
249710  void (*xDestroy)(void*);        /* Destructor function */
249711  Fts5TokenizerModule *pNext;     /* Next registered tokenizer module */
249712};
249713
249714struct Fts5FullTable {
249715  Fts5Table p;                    /* Public class members from fts5Int.h */
249716  Fts5Storage *pStorage;          /* Document store */
249717  Fts5Global *pGlobal;            /* Global (connection wide) data */
249718  Fts5Cursor *pSortCsr;           /* Sort data from this cursor */
249719  int iSavepoint;                 /* Successful xSavepoint()+1 */
249720
249721#ifdef SQLITE_DEBUG
249722  struct Fts5TransactionState ts;
249723#endif
249724};
249725
249726struct Fts5MatchPhrase {
249727  Fts5Buffer *pPoslist;           /* Pointer to current poslist */
249728  int nTerm;                      /* Size of phrase in terms */
249729};
249730
249731/*
249732** pStmt:
249733**   SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
249734**
249735** aIdx[]:
249736**   There is one entry in the aIdx[] array for each phrase in the query,
249737**   the value of which is the offset within aPoslist[] following the last
249738**   byte of the position list for the corresponding phrase.
249739*/
249740struct Fts5Sorter {
249741  sqlite3_stmt *pStmt;
249742  i64 iRowid;                     /* Current rowid */
249743  const u8 *aPoslist;             /* Position lists for current row */
249744  int nIdx;                       /* Number of entries in aIdx[] */
249745  int aIdx[1];                    /* Offsets into aPoslist for current row */
249746};
249747
249748
249749/*
249750** Virtual-table cursor object.
249751**
249752** iSpecial:
249753**   If this is a 'special' query (refer to function fts5SpecialMatch()),
249754**   then this variable contains the result of the query.
249755**
249756** iFirstRowid, iLastRowid:
249757**   These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
249758**   cursor iterates in ascending order of rowids, iFirstRowid is the lower
249759**   limit of rowids to return, and iLastRowid the upper. In other words, the
249760**   WHERE clause in the user's query might have been:
249761**
249762**       <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
249763**
249764**   If the cursor iterates in descending order of rowid, iFirstRowid
249765**   is the upper limit (i.e. the "first" rowid visited) and iLastRowid
249766**   the lower.
249767*/
249768struct Fts5Cursor {
249769  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
249770  Fts5Cursor *pNext;              /* Next cursor in Fts5Cursor.pCsr list */
249771  int *aColumnSize;               /* Values for xColumnSize() */
249772  i64 iCsrId;                     /* Cursor id */
249773
249774  /* Zero from this point onwards on cursor reset */
249775  int ePlan;                      /* FTS5_PLAN_XXX value */
249776  int bDesc;                      /* True for "ORDER BY rowid DESC" queries */
249777  i64 iFirstRowid;                /* Return no rowids earlier than this */
249778  i64 iLastRowid;                 /* Return no rowids later than this */
249779  sqlite3_stmt *pStmt;            /* Statement used to read %_content */
249780  Fts5Expr *pExpr;                /* Expression for MATCH queries */
249781  Fts5Sorter *pSorter;            /* Sorter for "ORDER BY rank" queries */
249782  int csrflags;                   /* Mask of cursor flags (see below) */
249783  i64 iSpecial;                   /* Result of special query */
249784
249785  /* "rank" function. Populated on demand from vtab.xColumn(). */
249786  char *zRank;                    /* Custom rank function */
249787  char *zRankArgs;                /* Custom rank function args */
249788  Fts5Auxiliary *pRank;           /* Rank callback (or NULL) */
249789  int nRankArg;                   /* Number of trailing arguments for rank() */
249790  sqlite3_value **apRankArg;      /* Array of trailing arguments */
249791  sqlite3_stmt *pRankArgStmt;     /* Origin of objects in apRankArg[] */
249792
249793  /* Auxiliary data storage */
249794  Fts5Auxiliary *pAux;            /* Currently executing extension function */
249795  Fts5Auxdata *pAuxdata;          /* First in linked list of saved aux-data */
249796
249797  /* Cache used by auxiliary functions xInst() and xInstCount() */
249798  Fts5PoslistReader *aInstIter;   /* One for each phrase */
249799  int nInstAlloc;                 /* Size of aInst[] array (entries / 3) */
249800  int nInstCount;                 /* Number of phrase instances */
249801  int *aInst;                     /* 3 integers per phrase instance */
249802};
249803
249804/*
249805** Bits that make up the "idxNum" parameter passed indirectly by
249806** xBestIndex() to xFilter().
249807*/
249808#define FTS5_BI_MATCH        0x0001         /* <tbl> MATCH ? */
249809#define FTS5_BI_RANK         0x0002         /* rank MATCH ? */
249810#define FTS5_BI_ROWID_EQ     0x0004         /* rowid == ? */
249811#define FTS5_BI_ROWID_LE     0x0008         /* rowid <= ? */
249812#define FTS5_BI_ROWID_GE     0x0010         /* rowid >= ? */
249813
249814#define FTS5_BI_ORDER_RANK   0x0020
249815#define FTS5_BI_ORDER_ROWID  0x0040
249816#define FTS5_BI_ORDER_DESC   0x0080
249817
249818/*
249819** Values for Fts5Cursor.csrflags
249820*/
249821#define FTS5CSR_EOF               0x01
249822#define FTS5CSR_REQUIRE_CONTENT   0x02
249823#define FTS5CSR_REQUIRE_DOCSIZE   0x04
249824#define FTS5CSR_REQUIRE_INST      0x08
249825#define FTS5CSR_FREE_ZRANK        0x10
249826#define FTS5CSR_REQUIRE_RESEEK    0x20
249827#define FTS5CSR_REQUIRE_POSLIST   0x40
249828
249829#define BitFlagAllTest(x,y) (((x) & (y))==(y))
249830#define BitFlagTest(x,y)    (((x) & (y))!=0)
249831
249832
249833/*
249834** Macros to Set(), Clear() and Test() cursor flags.
249835*/
249836#define CsrFlagSet(pCsr, flag)   ((pCsr)->csrflags |= (flag))
249837#define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
249838#define CsrFlagTest(pCsr, flag)  ((pCsr)->csrflags & (flag))
249839
249840struct Fts5Auxdata {
249841  Fts5Auxiliary *pAux;            /* Extension to which this belongs */
249842  void *pPtr;                     /* Pointer value */
249843  void(*xDelete)(void*);          /* Destructor */
249844  Fts5Auxdata *pNext;             /* Next object in linked list */
249845};
249846
249847#ifdef SQLITE_DEBUG
249848#define FTS5_BEGIN      1
249849#define FTS5_SYNC       2
249850#define FTS5_COMMIT     3
249851#define FTS5_ROLLBACK   4
249852#define FTS5_SAVEPOINT  5
249853#define FTS5_RELEASE    6
249854#define FTS5_ROLLBACKTO 7
249855static void fts5CheckTransactionState(Fts5FullTable *p, int op, int iSavepoint){
249856  switch( op ){
249857    case FTS5_BEGIN:
249858      assert( p->ts.eState==0 );
249859      p->ts.eState = 1;
249860      p->ts.iSavepoint = -1;
249861      break;
249862
249863    case FTS5_SYNC:
249864      assert( p->ts.eState==1 || p->ts.eState==2 );
249865      p->ts.eState = 2;
249866      break;
249867
249868    case FTS5_COMMIT:
249869      assert( p->ts.eState==2 );
249870      p->ts.eState = 0;
249871      break;
249872
249873    case FTS5_ROLLBACK:
249874      assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
249875      p->ts.eState = 0;
249876      break;
249877
249878    case FTS5_SAVEPOINT:
249879      assert( p->ts.eState>=1 );
249880      assert( iSavepoint>=0 );
249881      assert( iSavepoint>=p->ts.iSavepoint );
249882      p->ts.iSavepoint = iSavepoint;
249883      break;
249884
249885    case FTS5_RELEASE:
249886      assert( p->ts.eState>=1 );
249887      assert( iSavepoint>=0 );
249888      assert( iSavepoint<=p->ts.iSavepoint );
249889      p->ts.iSavepoint = iSavepoint-1;
249890      break;
249891
249892    case FTS5_ROLLBACKTO:
249893      assert( p->ts.eState>=1 );
249894      assert( iSavepoint>=-1 );
249895      /* The following assert() can fail if another vtab strikes an error
249896      ** within an xSavepoint() call then SQLite calls xRollbackTo() - without
249897      ** having called xSavepoint() on this vtab.  */
249898      /* assert( iSavepoint<=p->ts.iSavepoint ); */
249899      p->ts.iSavepoint = iSavepoint;
249900      break;
249901  }
249902}
249903#else
249904# define fts5CheckTransactionState(x,y,z)
249905#endif
249906
249907/*
249908** Return true if pTab is a contentless table.
249909*/
249910static int fts5IsContentless(Fts5FullTable *pTab){
249911  return pTab->p.pConfig->eContent==FTS5_CONTENT_NONE;
249912}
249913
249914/*
249915** Delete a virtual table handle allocated by fts5InitVtab().
249916*/
249917static void fts5FreeVtab(Fts5FullTable *pTab){
249918  if( pTab ){
249919    sqlite3Fts5IndexClose(pTab->p.pIndex);
249920    sqlite3Fts5StorageClose(pTab->pStorage);
249921    sqlite3Fts5ConfigFree(pTab->p.pConfig);
249922    sqlite3_free(pTab);
249923  }
249924}
249925
249926/*
249927** The xDisconnect() virtual table method.
249928*/
249929static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
249930  fts5FreeVtab((Fts5FullTable*)pVtab);
249931  return SQLITE_OK;
249932}
249933
249934/*
249935** The xDestroy() virtual table method.
249936*/
249937static int fts5DestroyMethod(sqlite3_vtab *pVtab){
249938  Fts5Table *pTab = (Fts5Table*)pVtab;
249939  int rc = sqlite3Fts5DropAll(pTab->pConfig);
249940  if( rc==SQLITE_OK ){
249941    fts5FreeVtab((Fts5FullTable*)pVtab);
249942  }
249943  return rc;
249944}
249945
249946/*
249947** This function is the implementation of both the xConnect and xCreate
249948** methods of the FTS3 virtual table.
249949**
249950** The argv[] array contains the following:
249951**
249952**   argv[0]   -> module name  ("fts5")
249953**   argv[1]   -> database name
249954**   argv[2]   -> table name
249955**   argv[...] -> "column name" and other module argument fields.
249956*/
249957static int fts5InitVtab(
249958  int bCreate,                    /* True for xCreate, false for xConnect */
249959  sqlite3 *db,                    /* The SQLite database connection */
249960  void *pAux,                     /* Hash table containing tokenizers */
249961  int argc,                       /* Number of elements in argv array */
249962  const char * const *argv,       /* xCreate/xConnect argument array */
249963  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
249964  char **pzErr                    /* Write any error message here */
249965){
249966  Fts5Global *pGlobal = (Fts5Global*)pAux;
249967  const char **azConfig = (const char**)argv;
249968  int rc = SQLITE_OK;             /* Return code */
249969  Fts5Config *pConfig = 0;        /* Results of parsing argc/argv */
249970  Fts5FullTable *pTab = 0;        /* New virtual table object */
249971
249972  /* Allocate the new vtab object and parse the configuration */
249973  pTab = (Fts5FullTable*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5FullTable));
249974  if( rc==SQLITE_OK ){
249975    rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
249976    assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
249977  }
249978  if( rc==SQLITE_OK ){
249979    pTab->p.pConfig = pConfig;
249980    pTab->pGlobal = pGlobal;
249981  }
249982
249983  /* Open the index sub-system */
249984  if( rc==SQLITE_OK ){
249985    rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->p.pIndex, pzErr);
249986  }
249987
249988  /* Open the storage sub-system */
249989  if( rc==SQLITE_OK ){
249990    rc = sqlite3Fts5StorageOpen(
249991        pConfig, pTab->p.pIndex, bCreate, &pTab->pStorage, pzErr
249992    );
249993  }
249994
249995  /* Call sqlite3_declare_vtab() */
249996  if( rc==SQLITE_OK ){
249997    rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
249998  }
249999
250000  /* Load the initial configuration */
250001  if( rc==SQLITE_OK ){
250002    assert( pConfig->pzErrmsg==0 );
250003    pConfig->pzErrmsg = pzErr;
250004    rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
250005    sqlite3Fts5IndexRollback(pTab->p.pIndex);
250006    pConfig->pzErrmsg = 0;
250007  }
250008
250009  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
250010    rc = sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, (int)1);
250011  }
250012  if( rc==SQLITE_OK ){
250013    rc = sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
250014  }
250015
250016  if( rc!=SQLITE_OK ){
250017    fts5FreeVtab(pTab);
250018    pTab = 0;
250019  }else if( bCreate ){
250020    fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
250021  }
250022  *ppVTab = (sqlite3_vtab*)pTab;
250023  return rc;
250024}
250025
250026/*
250027** The xConnect() and xCreate() methods for the virtual table. All the
250028** work is done in function fts5InitVtab().
250029*/
250030static int fts5ConnectMethod(
250031  sqlite3 *db,                    /* Database connection */
250032  void *pAux,                     /* Pointer to tokenizer hash table */
250033  int argc,                       /* Number of elements in argv array */
250034  const char * const *argv,       /* xCreate/xConnect argument array */
250035  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
250036  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
250037){
250038  return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
250039}
250040static int fts5CreateMethod(
250041  sqlite3 *db,                    /* Database connection */
250042  void *pAux,                     /* Pointer to tokenizer hash table */
250043  int argc,                       /* Number of elements in argv array */
250044  const char * const *argv,       /* xCreate/xConnect argument array */
250045  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
250046  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
250047){
250048  return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
250049}
250050
250051/*
250052** The different query plans.
250053*/
250054#define FTS5_PLAN_MATCH          1       /* (<tbl> MATCH ?) */
250055#define FTS5_PLAN_SOURCE         2       /* A source cursor for SORTED_MATCH */
250056#define FTS5_PLAN_SPECIAL        3       /* An internal query */
250057#define FTS5_PLAN_SORTED_MATCH   4       /* (<tbl> MATCH ? ORDER BY rank) */
250058#define FTS5_PLAN_SCAN           5       /* No usable constraint */
250059#define FTS5_PLAN_ROWID          6       /* (rowid = ?) */
250060
250061/*
250062** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
250063** extension is currently being used by a version of SQLite too old to
250064** support index-info flags. In that case this function is a no-op.
250065*/
250066static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
250067#if SQLITE_VERSION_NUMBER>=3008012
250068#ifndef SQLITE_CORE
250069  if( sqlite3_libversion_number()>=3008012 )
250070#endif
250071  {
250072    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
250073  }
250074#endif
250075}
250076
250077static int fts5UsePatternMatch(
250078  Fts5Config *pConfig,
250079  struct sqlite3_index_constraint *p
250080){
250081  assert( FTS5_PATTERN_GLOB==SQLITE_INDEX_CONSTRAINT_GLOB );
250082  assert( FTS5_PATTERN_LIKE==SQLITE_INDEX_CONSTRAINT_LIKE );
250083  if( pConfig->ePattern==FTS5_PATTERN_GLOB && p->op==FTS5_PATTERN_GLOB ){
250084    return 1;
250085  }
250086  if( pConfig->ePattern==FTS5_PATTERN_LIKE
250087   && (p->op==FTS5_PATTERN_LIKE || p->op==FTS5_PATTERN_GLOB)
250088  ){
250089    return 1;
250090  }
250091  return 0;
250092}
250093
250094/*
250095** Implementation of the xBestIndex method for FTS5 tables. Within the
250096** WHERE constraint, it searches for the following:
250097**
250098**   1. A MATCH constraint against the table column.
250099**   2. A MATCH constraint against the "rank" column.
250100**   3. A MATCH constraint against some other column.
250101**   4. An == constraint against the rowid column.
250102**   5. A < or <= constraint against the rowid column.
250103**   6. A > or >= constraint against the rowid column.
250104**
250105** Within the ORDER BY, the following are supported:
250106**
250107**   5. ORDER BY rank [ASC|DESC]
250108**   6. ORDER BY rowid [ASC|DESC]
250109**
250110** Information for the xFilter call is passed via both the idxNum and
250111** idxStr variables. Specifically, idxNum is a bitmask of the following
250112** flags used to encode the ORDER BY clause:
250113**
250114**     FTS5_BI_ORDER_RANK
250115**     FTS5_BI_ORDER_ROWID
250116**     FTS5_BI_ORDER_DESC
250117**
250118** idxStr is used to encode data from the WHERE clause. For each argument
250119** passed to the xFilter method, the following is appended to idxStr:
250120**
250121**   Match against table column:            "m"
250122**   Match against rank column:             "r"
250123**   Match against other column:            "M<column-number>"
250124**   LIKE  against other column:            "L<column-number>"
250125**   GLOB  against other column:            "G<column-number>"
250126**   Equality constraint against the rowid: "="
250127**   A < or <= against the rowid:           "<"
250128**   A > or >= against the rowid:           ">"
250129**
250130** This function ensures that there is at most one "r" or "=". And that if
250131** there exists an "=" then there is no "<" or ">".
250132**
250133** Costs are assigned as follows:
250134**
250135**  a) If an unusable MATCH operator is present in the WHERE clause, the
250136**     cost is unconditionally set to 1e50 (a really big number).
250137**
250138**  a) If a MATCH operator is present, the cost depends on the other
250139**     constraints also present. As follows:
250140**
250141**       * No other constraints:         cost=1000.0
250142**       * One rowid range constraint:   cost=750.0
250143**       * Both rowid range constraints: cost=500.0
250144**       * An == rowid constraint:       cost=100.0
250145**
250146**  b) Otherwise, if there is no MATCH:
250147**
250148**       * No other constraints:         cost=1000000.0
250149**       * One rowid range constraint:   cost=750000.0
250150**       * Both rowid range constraints: cost=250000.0
250151**       * An == rowid constraint:       cost=10.0
250152**
250153** Costs are not modified by the ORDER BY clause.
250154*/
250155static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
250156  Fts5Table *pTab = (Fts5Table*)pVTab;
250157  Fts5Config *pConfig = pTab->pConfig;
250158  const int nCol = pConfig->nCol;
250159  int idxFlags = 0;               /* Parameter passed through to xFilter() */
250160  int i;
250161
250162  char *idxStr;
250163  int iIdxStr = 0;
250164  int iCons = 0;
250165
250166  int bSeenEq = 0;
250167  int bSeenGt = 0;
250168  int bSeenLt = 0;
250169  int bSeenMatch = 0;
250170  int bSeenRank = 0;
250171
250172
250173  assert( SQLITE_INDEX_CONSTRAINT_EQ<SQLITE_INDEX_CONSTRAINT_MATCH );
250174  assert( SQLITE_INDEX_CONSTRAINT_GT<SQLITE_INDEX_CONSTRAINT_MATCH );
250175  assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
250176  assert( SQLITE_INDEX_CONSTRAINT_GE<SQLITE_INDEX_CONSTRAINT_MATCH );
250177  assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
250178
250179  if( pConfig->bLock ){
250180    pTab->base.zErrMsg = sqlite3_mprintf(
250181        "recursively defined fts5 content table"
250182    );
250183    return SQLITE_ERROR;
250184  }
250185
250186  idxStr = (char*)sqlite3_malloc(pInfo->nConstraint * 8 + 1);
250187  if( idxStr==0 ) return SQLITE_NOMEM;
250188  pInfo->idxStr = idxStr;
250189  pInfo->needToFreeIdxStr = 1;
250190
250191  for(i=0; i<pInfo->nConstraint; i++){
250192    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
250193    int iCol = p->iColumn;
250194    if( p->op==SQLITE_INDEX_CONSTRAINT_MATCH
250195     || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol>=nCol)
250196    ){
250197      /* A MATCH operator or equivalent */
250198      if( p->usable==0 || iCol<0 ){
250199        /* As there exists an unusable MATCH constraint this is an
250200        ** unusable plan. Set a prohibitively high cost. */
250201        pInfo->estimatedCost = 1e50;
250202        assert( iIdxStr < pInfo->nConstraint*6 + 1 );
250203        idxStr[iIdxStr] = 0;
250204        return SQLITE_OK;
250205      }else{
250206        if( iCol==nCol+1 ){
250207          if( bSeenRank ) continue;
250208          idxStr[iIdxStr++] = 'r';
250209          bSeenRank = 1;
250210        }else if( iCol>=0 ){
250211          bSeenMatch = 1;
250212          idxStr[iIdxStr++] = 'M';
250213          sqlite3_snprintf(6, &idxStr[iIdxStr], "%d", iCol);
250214          idxStr += strlen(&idxStr[iIdxStr]);
250215          assert( idxStr[iIdxStr]=='\0' );
250216        }
250217        pInfo->aConstraintUsage[i].argvIndex = ++iCons;
250218        pInfo->aConstraintUsage[i].omit = 1;
250219      }
250220    }else if( p->usable ){
250221      if( iCol>=0 && iCol<nCol && fts5UsePatternMatch(pConfig, p) ){
250222        assert( p->op==FTS5_PATTERN_LIKE || p->op==FTS5_PATTERN_GLOB );
250223        idxStr[iIdxStr++] = p->op==FTS5_PATTERN_LIKE ? 'L' : 'G';
250224        sqlite3_snprintf(6, &idxStr[iIdxStr], "%d", iCol);
250225        idxStr += strlen(&idxStr[iIdxStr]);
250226        pInfo->aConstraintUsage[i].argvIndex = ++iCons;
250227        assert( idxStr[iIdxStr]=='\0' );
250228      }else if( bSeenEq==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol<0 ){
250229        idxStr[iIdxStr++] = '=';
250230        bSeenEq = 1;
250231        pInfo->aConstraintUsage[i].argvIndex = ++iCons;
250232      }
250233    }
250234  }
250235
250236  if( bSeenEq==0 ){
250237    for(i=0; i<pInfo->nConstraint; i++){
250238      struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
250239      if( p->iColumn<0 && p->usable ){
250240        int op = p->op;
250241        if( op==SQLITE_INDEX_CONSTRAINT_LT || op==SQLITE_INDEX_CONSTRAINT_LE ){
250242          if( bSeenLt ) continue;
250243          idxStr[iIdxStr++] = '<';
250244          pInfo->aConstraintUsage[i].argvIndex = ++iCons;
250245          bSeenLt = 1;
250246        }else
250247        if( op==SQLITE_INDEX_CONSTRAINT_GT || op==SQLITE_INDEX_CONSTRAINT_GE ){
250248          if( bSeenGt ) continue;
250249          idxStr[iIdxStr++] = '>';
250250          pInfo->aConstraintUsage[i].argvIndex = ++iCons;
250251          bSeenGt = 1;
250252        }
250253      }
250254    }
250255  }
250256  idxStr[iIdxStr] = '\0';
250257
250258  /* Set idxFlags flags for the ORDER BY clause
250259  **
250260  ** Note that tokendata=1 tables cannot currently handle "ORDER BY rowid DESC".
250261  */
250262  if( pInfo->nOrderBy==1 ){
250263    int iSort = pInfo->aOrderBy[0].iColumn;
250264    if( iSort==(pConfig->nCol+1) && bSeenMatch ){
250265      idxFlags |= FTS5_BI_ORDER_RANK;
250266    }else if( iSort==-1 && (!pInfo->aOrderBy[0].desc || !pConfig->bTokendata) ){
250267      idxFlags |= FTS5_BI_ORDER_ROWID;
250268    }
250269    if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
250270      pInfo->orderByConsumed = 1;
250271      if( pInfo->aOrderBy[0].desc ){
250272        idxFlags |= FTS5_BI_ORDER_DESC;
250273      }
250274    }
250275  }
250276
250277  /* Calculate the estimated cost based on the flags set in idxFlags. */
250278  if( bSeenEq ){
250279    pInfo->estimatedCost = bSeenMatch ? 100.0 : 10.0;
250280    if( bSeenMatch==0 ) fts5SetUniqueFlag(pInfo);
250281  }else if( bSeenLt && bSeenGt ){
250282    pInfo->estimatedCost = bSeenMatch ? 500.0 : 250000.0;
250283  }else if( bSeenLt || bSeenGt ){
250284    pInfo->estimatedCost = bSeenMatch ? 750.0 : 750000.0;
250285  }else{
250286    pInfo->estimatedCost = bSeenMatch ? 1000.0 : 1000000.0;
250287  }
250288
250289  pInfo->idxNum = idxFlags;
250290  return SQLITE_OK;
250291}
250292
250293static int fts5NewTransaction(Fts5FullTable *pTab){
250294  Fts5Cursor *pCsr;
250295  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
250296    if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
250297  }
250298  return sqlite3Fts5StorageReset(pTab->pStorage);
250299}
250300
250301/*
250302** Implementation of xOpen method.
250303*/
250304static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
250305  Fts5FullTable *pTab = (Fts5FullTable*)pVTab;
250306  Fts5Config *pConfig = pTab->p.pConfig;
250307  Fts5Cursor *pCsr = 0;           /* New cursor object */
250308  sqlite3_int64 nByte;            /* Bytes of space to allocate */
250309  int rc;                         /* Return code */
250310
250311  rc = fts5NewTransaction(pTab);
250312  if( rc==SQLITE_OK ){
250313    nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
250314    pCsr = (Fts5Cursor*)sqlite3_malloc64(nByte);
250315    if( pCsr ){
250316      Fts5Global *pGlobal = pTab->pGlobal;
250317      memset(pCsr, 0, (size_t)nByte);
250318      pCsr->aColumnSize = (int*)&pCsr[1];
250319      pCsr->pNext = pGlobal->pCsr;
250320      pGlobal->pCsr = pCsr;
250321      pCsr->iCsrId = ++pGlobal->iNextId;
250322    }else{
250323      rc = SQLITE_NOMEM;
250324    }
250325  }
250326  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
250327  return rc;
250328}
250329
250330static int fts5StmtType(Fts5Cursor *pCsr){
250331  if( pCsr->ePlan==FTS5_PLAN_SCAN ){
250332    return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
250333  }
250334  return FTS5_STMT_LOOKUP;
250335}
250336
250337/*
250338** This function is called after the cursor passed as the only argument
250339** is moved to point at a different row. It clears all cached data
250340** specific to the previous row stored by the cursor object.
250341*/
250342static void fts5CsrNewrow(Fts5Cursor *pCsr){
250343  CsrFlagSet(pCsr,
250344      FTS5CSR_REQUIRE_CONTENT
250345    | FTS5CSR_REQUIRE_DOCSIZE
250346    | FTS5CSR_REQUIRE_INST
250347    | FTS5CSR_REQUIRE_POSLIST
250348  );
250349}
250350
250351static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
250352  Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
250353  Fts5Auxdata *pData;
250354  Fts5Auxdata *pNext;
250355
250356  sqlite3_free(pCsr->aInstIter);
250357  sqlite3_free(pCsr->aInst);
250358  if( pCsr->pStmt ){
250359    int eStmt = fts5StmtType(pCsr);
250360    sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
250361  }
250362  if( pCsr->pSorter ){
250363    Fts5Sorter *pSorter = pCsr->pSorter;
250364    sqlite3_finalize(pSorter->pStmt);
250365    sqlite3_free(pSorter);
250366  }
250367
250368  if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
250369    sqlite3Fts5ExprFree(pCsr->pExpr);
250370  }
250371
250372  for(pData=pCsr->pAuxdata; pData; pData=pNext){
250373    pNext = pData->pNext;
250374    if( pData->xDelete ) pData->xDelete(pData->pPtr);
250375    sqlite3_free(pData);
250376  }
250377
250378  sqlite3_finalize(pCsr->pRankArgStmt);
250379  sqlite3_free(pCsr->apRankArg);
250380
250381  if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
250382    sqlite3_free(pCsr->zRank);
250383    sqlite3_free(pCsr->zRankArgs);
250384  }
250385
250386  sqlite3Fts5IndexCloseReader(pTab->p.pIndex);
250387  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
250388}
250389
250390
250391/*
250392** Close the cursor.  For additional information see the documentation
250393** on the xClose method of the virtual table interface.
250394*/
250395static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
250396  if( pCursor ){
250397    Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
250398    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
250399    Fts5Cursor **pp;
250400
250401    fts5FreeCursorComponents(pCsr);
250402    /* Remove the cursor from the Fts5Global.pCsr list */
250403    for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
250404    *pp = pCsr->pNext;
250405
250406    sqlite3_free(pCsr);
250407  }
250408  return SQLITE_OK;
250409}
250410
250411static int fts5SorterNext(Fts5Cursor *pCsr){
250412  Fts5Sorter *pSorter = pCsr->pSorter;
250413  int rc;
250414
250415  rc = sqlite3_step(pSorter->pStmt);
250416  if( rc==SQLITE_DONE ){
250417    rc = SQLITE_OK;
250418    CsrFlagSet(pCsr, FTS5CSR_EOF|FTS5CSR_REQUIRE_CONTENT);
250419  }else if( rc==SQLITE_ROW ){
250420    const u8 *a;
250421    const u8 *aBlob;
250422    int nBlob;
250423    int i;
250424    int iOff = 0;
250425    rc = SQLITE_OK;
250426
250427    pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
250428    nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
250429    aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
250430
250431    /* nBlob==0 in detail=none mode. */
250432    if( nBlob>0 ){
250433      for(i=0; i<(pSorter->nIdx-1); i++){
250434        int iVal;
250435        a += fts5GetVarint32(a, iVal);
250436        iOff += iVal;
250437        pSorter->aIdx[i] = iOff;
250438      }
250439      pSorter->aIdx[i] = &aBlob[nBlob] - a;
250440      pSorter->aPoslist = a;
250441    }
250442
250443    fts5CsrNewrow(pCsr);
250444  }
250445
250446  return rc;
250447}
250448
250449
250450/*
250451** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
250452** open on table pTab.
250453*/
250454static void fts5TripCursors(Fts5FullTable *pTab){
250455  Fts5Cursor *pCsr;
250456  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
250457    if( pCsr->ePlan==FTS5_PLAN_MATCH
250458     && pCsr->base.pVtab==(sqlite3_vtab*)pTab
250459    ){
250460      CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
250461    }
250462  }
250463}
250464
250465/*
250466** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
250467** argument, close and reopen all Fts5IndexIter iterators that the cursor
250468** is using. Then attempt to move the cursor to a rowid equal to or laster
250469** (in the cursors sort order - ASC or DESC) than the current rowid.
250470**
250471** If the new rowid is not equal to the old, set output parameter *pbSkip
250472** to 1 before returning. Otherwise, leave it unchanged.
250473**
250474** Return SQLITE_OK if successful or if no reseek was required, or an
250475** error code if an error occurred.
250476*/
250477static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
250478  int rc = SQLITE_OK;
250479  assert( *pbSkip==0 );
250480  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
250481    Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
250482    int bDesc = pCsr->bDesc;
250483    i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
250484
250485    rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->p.pIndex, iRowid, bDesc);
250486    if( rc==SQLITE_OK &&  iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
250487      *pbSkip = 1;
250488    }
250489
250490    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
250491    fts5CsrNewrow(pCsr);
250492    if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
250493      CsrFlagSet(pCsr, FTS5CSR_EOF);
250494      *pbSkip = 1;
250495    }
250496  }
250497  return rc;
250498}
250499
250500
250501/*
250502** Advance the cursor to the next row in the table that matches the
250503** search criteria.
250504**
250505** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
250506** even if we reach end-of-file.  The fts5EofMethod() will be called
250507** subsequently to determine whether or not an EOF was hit.
250508*/
250509static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
250510  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
250511  int rc;
250512
250513  assert( (pCsr->ePlan<3)==
250514          (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
250515  );
250516  assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
250517
250518  /* If this cursor uses FTS5_PLAN_MATCH and this is a tokendata=1 table,
250519  ** clear any token mappings accumulated at the fts5_index.c level. In
250520  ** other cases, specifically FTS5_PLAN_SOURCE and FTS5_PLAN_SORTED_MATCH,
250521  ** we need to retain the mappings for the entire query.  */
250522  if( pCsr->ePlan==FTS5_PLAN_MATCH
250523   && ((Fts5Table*)pCursor->pVtab)->pConfig->bTokendata
250524  ){
250525    sqlite3Fts5ExprClearTokens(pCsr->pExpr);
250526  }
250527
250528  if( pCsr->ePlan<3 ){
250529    int bSkip = 0;
250530    if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
250531    rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
250532    CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
250533    fts5CsrNewrow(pCsr);
250534  }else{
250535    switch( pCsr->ePlan ){
250536      case FTS5_PLAN_SPECIAL: {
250537        CsrFlagSet(pCsr, FTS5CSR_EOF);
250538        rc = SQLITE_OK;
250539        break;
250540      }
250541
250542      case FTS5_PLAN_SORTED_MATCH: {
250543        rc = fts5SorterNext(pCsr);
250544        break;
250545      }
250546
250547      default: {
250548        Fts5Config *pConfig = ((Fts5Table*)pCursor->pVtab)->pConfig;
250549        pConfig->bLock++;
250550        rc = sqlite3_step(pCsr->pStmt);
250551        pConfig->bLock--;
250552        if( rc!=SQLITE_ROW ){
250553          CsrFlagSet(pCsr, FTS5CSR_EOF);
250554          rc = sqlite3_reset(pCsr->pStmt);
250555          if( rc!=SQLITE_OK ){
250556            pCursor->pVtab->zErrMsg = sqlite3_mprintf(
250557                "%s", sqlite3_errmsg(pConfig->db)
250558            );
250559          }
250560        }else{
250561          rc = SQLITE_OK;
250562        }
250563        break;
250564      }
250565    }
250566  }
250567
250568  return rc;
250569}
250570
250571
250572static int fts5PrepareStatement(
250573  sqlite3_stmt **ppStmt,
250574  Fts5Config *pConfig,
250575  const char *zFmt,
250576  ...
250577){
250578  sqlite3_stmt *pRet = 0;
250579  int rc;
250580  char *zSql;
250581  va_list ap;
250582
250583  va_start(ap, zFmt);
250584  zSql = sqlite3_vmprintf(zFmt, ap);
250585  if( zSql==0 ){
250586    rc = SQLITE_NOMEM;
250587  }else{
250588    rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
250589                            SQLITE_PREPARE_PERSISTENT, &pRet, 0);
250590    if( rc!=SQLITE_OK ){
250591      *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
250592    }
250593    sqlite3_free(zSql);
250594  }
250595
250596  va_end(ap);
250597  *ppStmt = pRet;
250598  return rc;
250599}
250600
250601static int fts5CursorFirstSorted(
250602  Fts5FullTable *pTab,
250603  Fts5Cursor *pCsr,
250604  int bDesc
250605){
250606  Fts5Config *pConfig = pTab->p.pConfig;
250607  Fts5Sorter *pSorter;
250608  int nPhrase;
250609  sqlite3_int64 nByte;
250610  int rc;
250611  const char *zRank = pCsr->zRank;
250612  const char *zRankArgs = pCsr->zRankArgs;
250613
250614  nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
250615  nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
250616  pSorter = (Fts5Sorter*)sqlite3_malloc64(nByte);
250617  if( pSorter==0 ) return SQLITE_NOMEM;
250618  memset(pSorter, 0, (size_t)nByte);
250619  pSorter->nIdx = nPhrase;
250620
250621  /* TODO: It would be better to have some system for reusing statement
250622  ** handles here, rather than preparing a new one for each query. But that
250623  ** is not possible as SQLite reference counts the virtual table objects.
250624  ** And since the statement required here reads from this very virtual
250625  ** table, saving it creates a circular reference.
250626  **
250627  ** If SQLite a built-in statement cache, this wouldn't be a problem. */
250628  rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
250629      "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(\"%w\"%s%s) %s",
250630      pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
250631      (zRankArgs ? ", " : ""),
250632      (zRankArgs ? zRankArgs : ""),
250633      bDesc ? "DESC" : "ASC"
250634  );
250635
250636  pCsr->pSorter = pSorter;
250637  if( rc==SQLITE_OK ){
250638    assert( pTab->pSortCsr==0 );
250639    pTab->pSortCsr = pCsr;
250640    rc = fts5SorterNext(pCsr);
250641    pTab->pSortCsr = 0;
250642  }
250643
250644  if( rc!=SQLITE_OK ){
250645    sqlite3_finalize(pSorter->pStmt);
250646    sqlite3_free(pSorter);
250647    pCsr->pSorter = 0;
250648  }
250649
250650  return rc;
250651}
250652
250653static int fts5CursorFirst(Fts5FullTable *pTab, Fts5Cursor *pCsr, int bDesc){
250654  int rc;
250655  Fts5Expr *pExpr = pCsr->pExpr;
250656  rc = sqlite3Fts5ExprFirst(pExpr, pTab->p.pIndex, pCsr->iFirstRowid, bDesc);
250657  if( sqlite3Fts5ExprEof(pExpr) ){
250658    CsrFlagSet(pCsr, FTS5CSR_EOF);
250659  }
250660  fts5CsrNewrow(pCsr);
250661  return rc;
250662}
250663
250664/*
250665** Process a "special" query. A special query is identified as one with a
250666** MATCH expression that begins with a '*' character. The remainder of
250667** the text passed to the MATCH operator are used as  the special query
250668** parameters.
250669*/
250670static int fts5SpecialMatch(
250671  Fts5FullTable *pTab,
250672  Fts5Cursor *pCsr,
250673  const char *zQuery
250674){
250675  int rc = SQLITE_OK;             /* Return code */
250676  const char *z = zQuery;         /* Special query text */
250677  int n;                          /* Number of bytes in text at z */
250678
250679  while( z[0]==' ' ) z++;
250680  for(n=0; z[n] && z[n]!=' '; n++);
250681
250682  assert( pTab->p.base.zErrMsg==0 );
250683  pCsr->ePlan = FTS5_PLAN_SPECIAL;
250684
250685  if( n==5 && 0==sqlite3_strnicmp("reads", z, n) ){
250686    pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->p.pIndex);
250687  }
250688  else if( n==2 && 0==sqlite3_strnicmp("id", z, n) ){
250689    pCsr->iSpecial = pCsr->iCsrId;
250690  }
250691  else{
250692    /* An unrecognized directive. Return an error message. */
250693    pTab->p.base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
250694    rc = SQLITE_ERROR;
250695  }
250696
250697  return rc;
250698}
250699
250700/*
250701** Search for an auxiliary function named zName that can be used with table
250702** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
250703** structure. Otherwise, if no such function exists, return NULL.
250704*/
250705static Fts5Auxiliary *fts5FindAuxiliary(Fts5FullTable *pTab, const char *zName){
250706  Fts5Auxiliary *pAux;
250707
250708  for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
250709    if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
250710  }
250711
250712  /* No function of the specified name was found. Return 0. */
250713  return 0;
250714}
250715
250716
250717static int fts5FindRankFunction(Fts5Cursor *pCsr){
250718  Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
250719  Fts5Config *pConfig = pTab->p.pConfig;
250720  int rc = SQLITE_OK;
250721  Fts5Auxiliary *pAux = 0;
250722  const char *zRank = pCsr->zRank;
250723  const char *zRankArgs = pCsr->zRankArgs;
250724
250725  if( zRankArgs ){
250726    char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
250727    if( zSql ){
250728      sqlite3_stmt *pStmt = 0;
250729      rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
250730                              SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
250731      sqlite3_free(zSql);
250732      assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
250733      if( rc==SQLITE_OK ){
250734        if( SQLITE_ROW==sqlite3_step(pStmt) ){
250735          sqlite3_int64 nByte;
250736          pCsr->nRankArg = sqlite3_column_count(pStmt);
250737          nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
250738          pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
250739          if( rc==SQLITE_OK ){
250740            int i;
250741            for(i=0; i<pCsr->nRankArg; i++){
250742              pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
250743            }
250744          }
250745          pCsr->pRankArgStmt = pStmt;
250746        }else{
250747          rc = sqlite3_finalize(pStmt);
250748          assert( rc!=SQLITE_OK );
250749        }
250750      }
250751    }
250752  }
250753
250754  if( rc==SQLITE_OK ){
250755    pAux = fts5FindAuxiliary(pTab, zRank);
250756    if( pAux==0 ){
250757      assert( pTab->p.base.zErrMsg==0 );
250758      pTab->p.base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
250759      rc = SQLITE_ERROR;
250760    }
250761  }
250762
250763  pCsr->pRank = pAux;
250764  return rc;
250765}
250766
250767
250768static int fts5CursorParseRank(
250769  Fts5Config *pConfig,
250770  Fts5Cursor *pCsr,
250771  sqlite3_value *pRank
250772){
250773  int rc = SQLITE_OK;
250774  if( pRank ){
250775    const char *z = (const char*)sqlite3_value_text(pRank);
250776    char *zRank = 0;
250777    char *zRankArgs = 0;
250778
250779    if( z==0 ){
250780      if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
250781    }else{
250782      rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
250783    }
250784    if( rc==SQLITE_OK ){
250785      pCsr->zRank = zRank;
250786      pCsr->zRankArgs = zRankArgs;
250787      CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
250788    }else if( rc==SQLITE_ERROR ){
250789      pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
250790          "parse error in rank function: %s", z
250791      );
250792    }
250793  }else{
250794    if( pConfig->zRank ){
250795      pCsr->zRank = (char*)pConfig->zRank;
250796      pCsr->zRankArgs = (char*)pConfig->zRankArgs;
250797    }else{
250798      pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
250799      pCsr->zRankArgs = 0;
250800    }
250801  }
250802  return rc;
250803}
250804
250805static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
250806  if( pVal ){
250807    int eType = sqlite3_value_numeric_type(pVal);
250808    if( eType==SQLITE_INTEGER ){
250809      return sqlite3_value_int64(pVal);
250810    }
250811  }
250812  return iDefault;
250813}
250814
250815/*
250816** This is the xFilter interface for the virtual table.  See
250817** the virtual table xFilter method documentation for additional
250818** information.
250819**
250820** There are three possible query strategies:
250821**
250822**   1. Full-text search using a MATCH operator.
250823**   2. A by-rowid lookup.
250824**   3. A full-table scan.
250825*/
250826static int fts5FilterMethod(
250827  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
250828  int idxNum,                     /* Strategy index */
250829  const char *idxStr,             /* Unused */
250830  int nVal,                       /* Number of elements in apVal */
250831  sqlite3_value **apVal           /* Arguments for the indexing scheme */
250832){
250833  Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
250834  Fts5Config *pConfig = pTab->p.pConfig;
250835  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
250836  int rc = SQLITE_OK;             /* Error code */
250837  int bDesc;                      /* True if ORDER BY [rank|rowid] DESC */
250838  int bOrderByRank;               /* True if ORDER BY rank */
250839  sqlite3_value *pRank = 0;       /* rank MATCH ? expression (or NULL) */
250840  sqlite3_value *pRowidEq = 0;    /* rowid = ? expression (or NULL) */
250841  sqlite3_value *pRowidLe = 0;    /* rowid <= ? expression (or NULL) */
250842  sqlite3_value *pRowidGe = 0;    /* rowid >= ? expression (or NULL) */
250843  int iCol;                       /* Column on LHS of MATCH operator */
250844  char **pzErrmsg = pConfig->pzErrmsg;
250845  int i;
250846  int iIdxStr = 0;
250847  Fts5Expr *pExpr = 0;
250848
250849  if( pConfig->bLock ){
250850    pTab->p.base.zErrMsg = sqlite3_mprintf(
250851        "recursively defined fts5 content table"
250852    );
250853    return SQLITE_ERROR;
250854  }
250855
250856  if( pCsr->ePlan ){
250857    fts5FreeCursorComponents(pCsr);
250858    memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
250859  }
250860
250861  assert( pCsr->pStmt==0 );
250862  assert( pCsr->pExpr==0 );
250863  assert( pCsr->csrflags==0 );
250864  assert( pCsr->pRank==0 );
250865  assert( pCsr->zRank==0 );
250866  assert( pCsr->zRankArgs==0 );
250867  assert( pTab->pSortCsr==0 || nVal==0 );
250868
250869  assert( pzErrmsg==0 || pzErrmsg==&pTab->p.base.zErrMsg );
250870  pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
250871
250872  /* Decode the arguments passed through to this function. */
250873  for(i=0; i<nVal; i++){
250874    switch( idxStr[iIdxStr++] ){
250875      case 'r':
250876        pRank = apVal[i];
250877        break;
250878      case 'M': {
250879        const char *zText = (const char*)sqlite3_value_text(apVal[i]);
250880        if( zText==0 ) zText = "";
250881        iCol = 0;
250882        do{
250883          iCol = iCol*10 + (idxStr[iIdxStr]-'0');
250884          iIdxStr++;
250885        }while( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' );
250886
250887        if( zText[0]=='*' ){
250888          /* The user has issued a query of the form "MATCH '*...'". This
250889          ** indicates that the MATCH expression is not a full text query,
250890          ** but a request for an internal parameter.  */
250891          rc = fts5SpecialMatch(pTab, pCsr, &zText[1]);
250892          goto filter_out;
250893        }else{
250894          char **pzErr = &pTab->p.base.zErrMsg;
250895          rc = sqlite3Fts5ExprNew(pConfig, 0, iCol, zText, &pExpr, pzErr);
250896          if( rc==SQLITE_OK ){
250897            rc = sqlite3Fts5ExprAnd(&pCsr->pExpr, pExpr);
250898            pExpr = 0;
250899          }
250900          if( rc!=SQLITE_OK ) goto filter_out;
250901        }
250902
250903        break;
250904      }
250905      case 'L':
250906      case 'G': {
250907        int bGlob = (idxStr[iIdxStr-1]=='G');
250908        const char *zText = (const char*)sqlite3_value_text(apVal[i]);
250909        iCol = 0;
250910        do{
250911          iCol = iCol*10 + (idxStr[iIdxStr]-'0');
250912          iIdxStr++;
250913        }while( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' );
250914        if( zText ){
250915          rc = sqlite3Fts5ExprPattern(pConfig, bGlob, iCol, zText, &pExpr);
250916        }
250917        if( rc==SQLITE_OK ){
250918          rc = sqlite3Fts5ExprAnd(&pCsr->pExpr, pExpr);
250919          pExpr = 0;
250920        }
250921        if( rc!=SQLITE_OK ) goto filter_out;
250922        break;
250923      }
250924      case '=':
250925        pRowidEq = apVal[i];
250926        break;
250927      case '<':
250928        pRowidLe = apVal[i];
250929        break;
250930      default: assert( idxStr[iIdxStr-1]=='>' );
250931        pRowidGe = apVal[i];
250932        break;
250933    }
250934  }
250935  bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
250936  pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
250937
250938  /* Set the cursor upper and lower rowid limits. Only some strategies
250939  ** actually use them. This is ok, as the xBestIndex() method leaves the
250940  ** sqlite3_index_constraint.omit flag clear for range constraints
250941  ** on the rowid field.  */
250942  if( pRowidEq ){
250943    pRowidLe = pRowidGe = pRowidEq;
250944  }
250945  if( bDesc ){
250946    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
250947    pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
250948  }else{
250949    pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
250950    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
250951  }
250952
250953  rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
250954  if( rc!=SQLITE_OK ) goto filter_out;
250955
250956  if( pTab->pSortCsr ){
250957    /* If pSortCsr is non-NULL, then this call is being made as part of
250958    ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
250959    ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
250960    ** return results to the user for this query. The current cursor
250961    ** (pCursor) is used to execute the query issued by function
250962    ** fts5CursorFirstSorted() above.  */
250963    assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
250964    assert( nVal==0 && bOrderByRank==0 && bDesc==0 );
250965    assert( pCsr->iLastRowid==LARGEST_INT64 );
250966    assert( pCsr->iFirstRowid==SMALLEST_INT64 );
250967    if( pTab->pSortCsr->bDesc ){
250968      pCsr->iLastRowid = pTab->pSortCsr->iFirstRowid;
250969      pCsr->iFirstRowid = pTab->pSortCsr->iLastRowid;
250970    }else{
250971      pCsr->iLastRowid = pTab->pSortCsr->iLastRowid;
250972      pCsr->iFirstRowid = pTab->pSortCsr->iFirstRowid;
250973    }
250974    pCsr->ePlan = FTS5_PLAN_SOURCE;
250975    pCsr->pExpr = pTab->pSortCsr->pExpr;
250976    rc = fts5CursorFirst(pTab, pCsr, bDesc);
250977  }else if( pCsr->pExpr ){
250978    assert( rc==SQLITE_OK );
250979    rc = fts5CursorParseRank(pConfig, pCsr, pRank);
250980    if( rc==SQLITE_OK ){
250981      if( bOrderByRank ){
250982        pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
250983        rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
250984      }else{
250985        pCsr->ePlan = FTS5_PLAN_MATCH;
250986        rc = fts5CursorFirst(pTab, pCsr, bDesc);
250987      }
250988    }
250989  }else if( pConfig->zContent==0 ){
250990    *pConfig->pzErrmsg = sqlite3_mprintf(
250991        "%s: table does not support scanning", pConfig->zName
250992    );
250993    rc = SQLITE_ERROR;
250994  }else{
250995    /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
250996    ** by rowid (ePlan==FTS5_PLAN_ROWID).  */
250997    pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
250998    rc = sqlite3Fts5StorageStmt(
250999        pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->p.base.zErrMsg
251000    );
251001    if( rc==SQLITE_OK ){
251002      if( pRowidEq!=0 ){
251003        assert( pCsr->ePlan==FTS5_PLAN_ROWID );
251004        sqlite3_bind_value(pCsr->pStmt, 1, pRowidEq);
251005      }else{
251006        sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
251007        sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
251008      }
251009      rc = fts5NextMethod(pCursor);
251010    }
251011  }
251012
251013 filter_out:
251014  sqlite3Fts5ExprFree(pExpr);
251015  pConfig->pzErrmsg = pzErrmsg;
251016  return rc;
251017}
251018
251019/*
251020** This is the xEof method of the virtual table. SQLite calls this
251021** routine to find out if it has reached the end of a result set.
251022*/
251023static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
251024  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
251025  return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
251026}
251027
251028/*
251029** Return the rowid that the cursor currently points to.
251030*/
251031static i64 fts5CursorRowid(Fts5Cursor *pCsr){
251032  assert( pCsr->ePlan==FTS5_PLAN_MATCH
251033       || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
251034       || pCsr->ePlan==FTS5_PLAN_SOURCE
251035  );
251036  if( pCsr->pSorter ){
251037    return pCsr->pSorter->iRowid;
251038  }else{
251039    return sqlite3Fts5ExprRowid(pCsr->pExpr);
251040  }
251041}
251042
251043/*
251044** This is the xRowid method. The SQLite core calls this routine to
251045** retrieve the rowid for the current row of the result set. fts5
251046** exposes %_content.rowid as the rowid for the virtual table. The
251047** rowid should be written to *pRowid.
251048*/
251049static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
251050  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
251051  int ePlan = pCsr->ePlan;
251052
251053  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
251054  switch( ePlan ){
251055    case FTS5_PLAN_SPECIAL:
251056      *pRowid = 0;
251057      break;
251058
251059    case FTS5_PLAN_SOURCE:
251060    case FTS5_PLAN_MATCH:
251061    case FTS5_PLAN_SORTED_MATCH:
251062      *pRowid = fts5CursorRowid(pCsr);
251063      break;
251064
251065    default:
251066      *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
251067      break;
251068  }
251069
251070  return SQLITE_OK;
251071}
251072
251073/*
251074** If the cursor requires seeking (bSeekRequired flag is set), seek it.
251075** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
251076**
251077** If argument bErrormsg is true and an error occurs, an error message may
251078** be left in sqlite3_vtab.zErrMsg.
251079*/
251080static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
251081  int rc = SQLITE_OK;
251082
251083  /* If the cursor does not yet have a statement handle, obtain one now. */
251084  if( pCsr->pStmt==0 ){
251085    Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
251086    int eStmt = fts5StmtType(pCsr);
251087    rc = sqlite3Fts5StorageStmt(
251088        pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->p.base.zErrMsg:0)
251089    );
251090    assert( rc!=SQLITE_OK || pTab->p.base.zErrMsg==0 );
251091    assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
251092  }
251093
251094  if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
251095    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
251096    assert( pCsr->pExpr );
251097    sqlite3_reset(pCsr->pStmt);
251098    sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
251099    pTab->pConfig->bLock++;
251100    rc = sqlite3_step(pCsr->pStmt);
251101    pTab->pConfig->bLock--;
251102    if( rc==SQLITE_ROW ){
251103      rc = SQLITE_OK;
251104      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
251105    }else{
251106      rc = sqlite3_reset(pCsr->pStmt);
251107      if( rc==SQLITE_OK ){
251108        rc = FTS5_CORRUPT;
251109      }else if( pTab->pConfig->pzErrmsg ){
251110        *pTab->pConfig->pzErrmsg = sqlite3_mprintf(
251111            "%s", sqlite3_errmsg(pTab->pConfig->db)
251112        );
251113      }
251114    }
251115  }
251116  return rc;
251117}
251118
251119static void fts5SetVtabError(Fts5FullTable *p, const char *zFormat, ...){
251120  va_list ap;                     /* ... printf arguments */
251121  va_start(ap, zFormat);
251122  assert( p->p.base.zErrMsg==0 );
251123  p->p.base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
251124  va_end(ap);
251125}
251126
251127/*
251128** This function is called to handle an FTS INSERT command. In other words,
251129** an INSERT statement of the form:
251130**
251131**     INSERT INTO fts(fts) VALUES($pCmd)
251132**     INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
251133**
251134** Argument pVal is the value assigned to column "fts" by the INSERT
251135** statement. This function returns SQLITE_OK if successful, or an SQLite
251136** error code if an error occurs.
251137**
251138** The commands implemented by this function are documented in the "Special
251139** INSERT Directives" section of the documentation. It should be updated if
251140** more commands are added to this function.
251141*/
251142static int fts5SpecialInsert(
251143  Fts5FullTable *pTab,            /* Fts5 table object */
251144  const char *zCmd,               /* Text inserted into table-name column */
251145  sqlite3_value *pVal             /* Value inserted into rank column */
251146){
251147  Fts5Config *pConfig = pTab->p.pConfig;
251148  int rc = SQLITE_OK;
251149  int bError = 0;
251150  int bLoadConfig = 0;
251151
251152  if( 0==sqlite3_stricmp("delete-all", zCmd) ){
251153    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
251154      fts5SetVtabError(pTab,
251155          "'delete-all' may only be used with a "
251156          "contentless or external content fts5 table"
251157      );
251158      rc = SQLITE_ERROR;
251159    }else{
251160      rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
251161    }
251162    bLoadConfig = 1;
251163  }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
251164    if( pConfig->eContent==FTS5_CONTENT_NONE ){
251165      fts5SetVtabError(pTab,
251166          "'rebuild' may not be used with a contentless fts5 table"
251167      );
251168      rc = SQLITE_ERROR;
251169    }else{
251170      rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
251171    }
251172    bLoadConfig = 1;
251173  }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
251174    rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
251175  }else if( 0==sqlite3_stricmp("merge", zCmd) ){
251176    int nMerge = sqlite3_value_int(pVal);
251177    rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
251178  }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
251179    int iArg = sqlite3_value_int(pVal);
251180    rc = sqlite3Fts5StorageIntegrity(pTab->pStorage, iArg);
251181#ifdef SQLITE_DEBUG
251182  }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
251183    pConfig->bPrefixIndex = sqlite3_value_int(pVal);
251184#endif
251185  }else if( 0==sqlite3_stricmp("flush", zCmd) ){
251186    rc = sqlite3Fts5FlushToDisk(&pTab->p);
251187  }else{
251188    rc = sqlite3Fts5FlushToDisk(&pTab->p);
251189    if( rc==SQLITE_OK ){
251190      rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
251191    }
251192    if( rc==SQLITE_OK ){
251193      rc = sqlite3Fts5ConfigSetValue(pTab->p.pConfig, zCmd, pVal, &bError);
251194    }
251195    if( rc==SQLITE_OK ){
251196      if( bError ){
251197        rc = SQLITE_ERROR;
251198      }else{
251199        rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
251200      }
251201    }
251202  }
251203
251204  if( rc==SQLITE_OK && bLoadConfig ){
251205    pTab->p.pConfig->iCookie--;
251206    rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
251207  }
251208
251209  return rc;
251210}
251211
251212static int fts5SpecialDelete(
251213  Fts5FullTable *pTab,
251214  sqlite3_value **apVal
251215){
251216  int rc = SQLITE_OK;
251217  int eType1 = sqlite3_value_type(apVal[1]);
251218  if( eType1==SQLITE_INTEGER ){
251219    sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
251220    rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
251221  }
251222  return rc;
251223}
251224
251225static void fts5StorageInsert(
251226  int *pRc,
251227  Fts5FullTable *pTab,
251228  sqlite3_value **apVal,
251229  i64 *piRowid
251230){
251231  int rc = *pRc;
251232  if( rc==SQLITE_OK ){
251233    rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
251234  }
251235  if( rc==SQLITE_OK ){
251236    rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
251237  }
251238  *pRc = rc;
251239}
251240
251241/*
251242** This function is the implementation of the xUpdate callback used by
251243** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
251244** inserted, updated or deleted.
251245**
251246** A delete specifies a single argument - the rowid of the row to remove.
251247**
251248** Update and insert operations pass:
251249**
251250**   1. The "old" rowid, or NULL.
251251**   2. The "new" rowid.
251252**   3. Values for each of the nCol matchable columns.
251253**   4. Values for the two hidden columns (<tablename> and "rank").
251254*/
251255static int fts5UpdateMethod(
251256  sqlite3_vtab *pVtab,            /* Virtual table handle */
251257  int nArg,                       /* Size of argument array */
251258  sqlite3_value **apVal,          /* Array of arguments */
251259  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
251260){
251261  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
251262  Fts5Config *pConfig = pTab->p.pConfig;
251263  int eType0;                     /* value_type() of apVal[0] */
251264  int rc = SQLITE_OK;             /* Return code */
251265  int bUpdateOrDelete = 0;
251266
251267  /* A transaction must be open when this is called. */
251268  assert( pTab->ts.eState==1 || pTab->ts.eState==2 );
251269
251270  assert( pVtab->zErrMsg==0 );
251271  assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
251272  assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER
251273       || sqlite3_value_type(apVal[0])==SQLITE_NULL
251274  );
251275  assert( pTab->p.pConfig->pzErrmsg==0 );
251276  if( pConfig->pgsz==0 ){
251277    rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
251278    if( rc!=SQLITE_OK ) return rc;
251279  }
251280
251281  pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
251282
251283  /* Put any active cursors into REQUIRE_SEEK state. */
251284  fts5TripCursors(pTab);
251285
251286  eType0 = sqlite3_value_type(apVal[0]);
251287  if( eType0==SQLITE_NULL
251288   && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
251289  ){
251290    /* A "special" INSERT op. These are handled separately. */
251291    const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
251292    if( pConfig->eContent!=FTS5_CONTENT_NORMAL
251293      && 0==sqlite3_stricmp("delete", z)
251294    ){
251295      if( pConfig->bContentlessDelete ){
251296        fts5SetVtabError(pTab,
251297            "'delete' may not be used with a contentless_delete=1 table"
251298        );
251299        rc = SQLITE_ERROR;
251300      }else{
251301        rc = fts5SpecialDelete(pTab, apVal);
251302      }
251303    }else{
251304      rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
251305    }
251306  }else{
251307    /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
251308    ** any conflict on the rowid value must be detected before any
251309    ** modifications are made to the database file. There are 4 cases:
251310    **
251311    **   1) DELETE
251312    **   2) UPDATE (rowid not modified)
251313    **   3) UPDATE (rowid modified)
251314    **   4) INSERT
251315    **
251316    ** Cases 3 and 4 may violate the rowid constraint.
251317    */
251318    int eConflict = SQLITE_ABORT;
251319    if( pConfig->eContent==FTS5_CONTENT_NORMAL || pConfig->bContentlessDelete ){
251320      eConflict = sqlite3_vtab_on_conflict(pConfig->db);
251321    }
251322
251323    assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
251324    assert( nArg!=1 || eType0==SQLITE_INTEGER );
251325
251326    /* Filter out attempts to run UPDATE or DELETE on contentless tables.
251327    ** This is not suported. Except - they are both supported if the CREATE
251328    ** VIRTUAL TABLE statement contained "contentless_delete=1". */
251329    if( eType0==SQLITE_INTEGER
251330     && pConfig->eContent==FTS5_CONTENT_NONE
251331     && pConfig->bContentlessDelete==0
251332    ){
251333      pTab->p.base.zErrMsg = sqlite3_mprintf(
251334          "cannot %s contentless fts5 table: %s",
251335          (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
251336      );
251337      rc = SQLITE_ERROR;
251338    }
251339
251340    /* DELETE */
251341    else if( nArg==1 ){
251342      i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */
251343      rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
251344      bUpdateOrDelete = 1;
251345    }
251346
251347    /* INSERT or UPDATE */
251348    else{
251349      int eType1 = sqlite3_value_numeric_type(apVal[1]);
251350
251351      if( eType1!=SQLITE_INTEGER && eType1!=SQLITE_NULL ){
251352        rc = SQLITE_MISMATCH;
251353      }
251354
251355      else if( eType0!=SQLITE_INTEGER ){
251356        /* An INSERT statement. If the conflict-mode is REPLACE, first remove
251357        ** the current entry (if any). */
251358        if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){
251359          i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
251360          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
251361          bUpdateOrDelete = 1;
251362        }
251363        fts5StorageInsert(&rc, pTab, apVal, pRowid);
251364      }
251365
251366      /* UPDATE */
251367      else{
251368        i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
251369        i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */
251370        if( eType1==SQLITE_INTEGER && iOld!=iNew ){
251371          if( eConflict==SQLITE_REPLACE ){
251372            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
251373            if( rc==SQLITE_OK ){
251374              rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
251375            }
251376            fts5StorageInsert(&rc, pTab, apVal, pRowid);
251377          }else{
251378            rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
251379            if( rc==SQLITE_OK ){
251380              rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
251381            }
251382            if( rc==SQLITE_OK ){
251383              rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal,*pRowid);
251384            }
251385          }
251386        }else{
251387          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
251388          fts5StorageInsert(&rc, pTab, apVal, pRowid);
251389        }
251390        bUpdateOrDelete = 1;
251391      }
251392    }
251393  }
251394
251395  if( rc==SQLITE_OK
251396   && bUpdateOrDelete
251397   && pConfig->bSecureDelete
251398   && pConfig->iVersion==FTS5_CURRENT_VERSION
251399  ){
251400    rc = sqlite3Fts5StorageConfigValue(
251401        pTab->pStorage, "version", 0, FTS5_CURRENT_VERSION_SECUREDELETE
251402    );
251403    if( rc==SQLITE_OK ){
251404      pConfig->iVersion = FTS5_CURRENT_VERSION_SECUREDELETE;
251405    }
251406  }
251407
251408  pTab->p.pConfig->pzErrmsg = 0;
251409  return rc;
251410}
251411
251412/*
251413** Implementation of xSync() method.
251414*/
251415static int fts5SyncMethod(sqlite3_vtab *pVtab){
251416  int rc;
251417  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
251418  fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
251419  pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
251420  rc = sqlite3Fts5FlushToDisk(&pTab->p);
251421  pTab->p.pConfig->pzErrmsg = 0;
251422  return rc;
251423}
251424
251425/*
251426** Implementation of xBegin() method.
251427*/
251428static int fts5BeginMethod(sqlite3_vtab *pVtab){
251429  fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_BEGIN, 0);
251430  fts5NewTransaction((Fts5FullTable*)pVtab);
251431  return SQLITE_OK;
251432}
251433
251434/*
251435** Implementation of xCommit() method. This is a no-op. The contents of
251436** the pending-terms hash-table have already been flushed into the database
251437** by fts5SyncMethod().
251438*/
251439static int fts5CommitMethod(sqlite3_vtab *pVtab){
251440  UNUSED_PARAM(pVtab);  /* Call below is a no-op for NDEBUG builds */
251441  fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_COMMIT, 0);
251442  return SQLITE_OK;
251443}
251444
251445/*
251446** Implementation of xRollback(). Discard the contents of the pending-terms
251447** hash-table. Any changes made to the database are reverted by SQLite.
251448*/
251449static int fts5RollbackMethod(sqlite3_vtab *pVtab){
251450  int rc;
251451  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
251452  fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
251453  rc = sqlite3Fts5StorageRollback(pTab->pStorage);
251454  return rc;
251455}
251456
251457static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
251458
251459static void *fts5ApiUserData(Fts5Context *pCtx){
251460  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251461  return pCsr->pAux->pUserData;
251462}
251463
251464static int fts5ApiColumnCount(Fts5Context *pCtx){
251465  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251466  return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
251467}
251468
251469static int fts5ApiColumnTotalSize(
251470  Fts5Context *pCtx,
251471  int iCol,
251472  sqlite3_int64 *pnToken
251473){
251474  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251475  Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
251476  return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
251477}
251478
251479static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
251480  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251481  Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
251482  return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
251483}
251484
251485static int fts5ApiTokenize(
251486  Fts5Context *pCtx,
251487  const char *pText, int nText,
251488  void *pUserData,
251489  int (*xToken)(void*, int, const char*, int, int, int)
251490){
251491  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251492  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
251493  return sqlite3Fts5Tokenize(
251494      pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
251495  );
251496}
251497
251498static int fts5ApiPhraseCount(Fts5Context *pCtx){
251499  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251500  return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
251501}
251502
251503static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
251504  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251505  return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
251506}
251507
251508static int fts5ApiColumnText(
251509  Fts5Context *pCtx,
251510  int iCol,
251511  const char **pz,
251512  int *pn
251513){
251514  int rc = SQLITE_OK;
251515  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251516  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
251517  if( iCol<0 || iCol>=pTab->pConfig->nCol ){
251518    rc = SQLITE_RANGE;
251519  }else if( fts5IsContentless((Fts5FullTable*)(pCsr->base.pVtab))
251520   || pCsr->ePlan==FTS5_PLAN_SPECIAL
251521  ){
251522    *pz = 0;
251523    *pn = 0;
251524  }else{
251525    rc = fts5SeekCursor(pCsr, 0);
251526    if( rc==SQLITE_OK ){
251527      *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
251528      *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
251529    }
251530  }
251531  return rc;
251532}
251533
251534static int fts5CsrPoslist(
251535  Fts5Cursor *pCsr,
251536  int iPhrase,
251537  const u8 **pa,
251538  int *pn
251539){
251540  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
251541  int rc = SQLITE_OK;
251542  int bLive = (pCsr->pSorter==0);
251543
251544  if( iPhrase<0 || iPhrase>=sqlite3Fts5ExprPhraseCount(pCsr->pExpr) ){
251545    rc = SQLITE_RANGE;
251546  }else if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
251547    if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
251548      Fts5PoslistPopulator *aPopulator;
251549      int i;
251550      aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
251551      if( aPopulator==0 ) rc = SQLITE_NOMEM;
251552      for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
251553        int n; const char *z;
251554        rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
251555        if( rc==SQLITE_OK ){
251556          rc = sqlite3Fts5ExprPopulatePoslists(
251557              pConfig, pCsr->pExpr, aPopulator, i, z, n
251558          );
251559        }
251560      }
251561      sqlite3_free(aPopulator);
251562
251563      if( pCsr->pSorter ){
251564        sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
251565      }
251566    }
251567    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
251568  }
251569
251570  if( rc==SQLITE_OK ){
251571    if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
251572      Fts5Sorter *pSorter = pCsr->pSorter;
251573      int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
251574      *pn = pSorter->aIdx[iPhrase] - i1;
251575      *pa = &pSorter->aPoslist[i1];
251576    }else{
251577      *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
251578    }
251579  }else{
251580    *pa = 0;
251581    *pn = 0;
251582  }
251583
251584
251585  return rc;
251586}
251587
251588/*
251589** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
251590** correctly for the current view. Return SQLITE_OK if successful, or an
251591** SQLite error code otherwise.
251592*/
251593static int fts5CacheInstArray(Fts5Cursor *pCsr){
251594  int rc = SQLITE_OK;
251595  Fts5PoslistReader *aIter;       /* One iterator for each phrase */
251596  int nIter;                      /* Number of iterators/phrases */
251597  int nCol = ((Fts5Table*)pCsr->base.pVtab)->pConfig->nCol;
251598
251599  nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
251600  if( pCsr->aInstIter==0 ){
251601    sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nIter;
251602    pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
251603  }
251604  aIter = pCsr->aInstIter;
251605
251606  if( aIter ){
251607    int nInst = 0;                /* Number instances seen so far */
251608    int i;
251609
251610    /* Initialize all iterators */
251611    for(i=0; i<nIter && rc==SQLITE_OK; i++){
251612      const u8 *a;
251613      int n;
251614      rc = fts5CsrPoslist(pCsr, i, &a, &n);
251615      if( rc==SQLITE_OK ){
251616        sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
251617      }
251618    }
251619
251620    if( rc==SQLITE_OK ){
251621      while( 1 ){
251622        int *aInst;
251623        int iBest = -1;
251624        for(i=0; i<nIter; i++){
251625          if( (aIter[i].bEof==0)
251626              && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
251627            ){
251628            iBest = i;
251629          }
251630        }
251631        if( iBest<0 ) break;
251632
251633        nInst++;
251634        if( nInst>=pCsr->nInstAlloc ){
251635          int nNewSize = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
251636          aInst = (int*)sqlite3_realloc64(
251637              pCsr->aInst, nNewSize*sizeof(int)*3
251638              );
251639          if( aInst ){
251640            pCsr->aInst = aInst;
251641            pCsr->nInstAlloc = nNewSize;
251642          }else{
251643            nInst--;
251644            rc = SQLITE_NOMEM;
251645            break;
251646          }
251647        }
251648
251649        aInst = &pCsr->aInst[3 * (nInst-1)];
251650        aInst[0] = iBest;
251651        aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
251652        aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
251653        if( aInst[1]<0 || aInst[1]>=nCol ){
251654          rc = FTS5_CORRUPT;
251655          break;
251656        }
251657        sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
251658      }
251659    }
251660
251661    pCsr->nInstCount = nInst;
251662    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
251663  }
251664  return rc;
251665}
251666
251667static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
251668  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251669  int rc = SQLITE_OK;
251670  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
251671   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
251672    *pnInst = pCsr->nInstCount;
251673  }
251674  return rc;
251675}
251676
251677static int fts5ApiInst(
251678  Fts5Context *pCtx,
251679  int iIdx,
251680  int *piPhrase,
251681  int *piCol,
251682  int *piOff
251683){
251684  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251685  int rc = SQLITE_OK;
251686  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
251687   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
251688  ){
251689    if( iIdx<0 || iIdx>=pCsr->nInstCount ){
251690      rc = SQLITE_RANGE;
251691    }else{
251692      *piPhrase = pCsr->aInst[iIdx*3];
251693      *piCol = pCsr->aInst[iIdx*3 + 1];
251694      *piOff = pCsr->aInst[iIdx*3 + 2];
251695    }
251696  }
251697  return rc;
251698}
251699
251700static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
251701  return fts5CursorRowid((Fts5Cursor*)pCtx);
251702}
251703
251704static int fts5ColumnSizeCb(
251705  void *pContext,                 /* Pointer to int */
251706  int tflags,
251707  const char *pUnused,            /* Buffer containing token */
251708  int nUnused,                    /* Size of token in bytes */
251709  int iUnused1,                   /* Start offset of token */
251710  int iUnused2                    /* End offset of token */
251711){
251712  int *pCnt = (int*)pContext;
251713  UNUSED_PARAM2(pUnused, nUnused);
251714  UNUSED_PARAM2(iUnused1, iUnused2);
251715  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
251716    (*pCnt)++;
251717  }
251718  return SQLITE_OK;
251719}
251720
251721static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
251722  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251723  Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
251724  Fts5Config *pConfig = pTab->p.pConfig;
251725  int rc = SQLITE_OK;
251726
251727  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
251728    if( pConfig->bColumnsize ){
251729      i64 iRowid = fts5CursorRowid(pCsr);
251730      rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
251731    }else if( pConfig->zContent==0 ){
251732      int i;
251733      for(i=0; i<pConfig->nCol; i++){
251734        if( pConfig->abUnindexed[i]==0 ){
251735          pCsr->aColumnSize[i] = -1;
251736        }
251737      }
251738    }else{
251739      int i;
251740      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
251741        if( pConfig->abUnindexed[i]==0 ){
251742          const char *z; int n;
251743          void *p = (void*)(&pCsr->aColumnSize[i]);
251744          pCsr->aColumnSize[i] = 0;
251745          rc = fts5ApiColumnText(pCtx, i, &z, &n);
251746          if( rc==SQLITE_OK ){
251747            rc = sqlite3Fts5Tokenize(
251748                pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
251749            );
251750          }
251751        }
251752      }
251753    }
251754    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
251755  }
251756  if( iCol<0 ){
251757    int i;
251758    *pnToken = 0;
251759    for(i=0; i<pConfig->nCol; i++){
251760      *pnToken += pCsr->aColumnSize[i];
251761    }
251762  }else if( iCol<pConfig->nCol ){
251763    *pnToken = pCsr->aColumnSize[iCol];
251764  }else{
251765    *pnToken = 0;
251766    rc = SQLITE_RANGE;
251767  }
251768  return rc;
251769}
251770
251771/*
251772** Implementation of the xSetAuxdata() method.
251773*/
251774static int fts5ApiSetAuxdata(
251775  Fts5Context *pCtx,              /* Fts5 context */
251776  void *pPtr,                     /* Pointer to save as auxdata */
251777  void(*xDelete)(void*)           /* Destructor for pPtr (or NULL) */
251778){
251779  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251780  Fts5Auxdata *pData;
251781
251782  /* Search through the cursors list of Fts5Auxdata objects for one that
251783  ** corresponds to the currently executing auxiliary function.  */
251784  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
251785    if( pData->pAux==pCsr->pAux ) break;
251786  }
251787
251788  if( pData ){
251789    if( pData->xDelete ){
251790      pData->xDelete(pData->pPtr);
251791    }
251792  }else{
251793    int rc = SQLITE_OK;
251794    pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
251795    if( pData==0 ){
251796      if( xDelete ) xDelete(pPtr);
251797      return rc;
251798    }
251799    pData->pAux = pCsr->pAux;
251800    pData->pNext = pCsr->pAuxdata;
251801    pCsr->pAuxdata = pData;
251802  }
251803
251804  pData->xDelete = xDelete;
251805  pData->pPtr = pPtr;
251806  return SQLITE_OK;
251807}
251808
251809static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
251810  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251811  Fts5Auxdata *pData;
251812  void *pRet = 0;
251813
251814  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
251815    if( pData->pAux==pCsr->pAux ) break;
251816  }
251817
251818  if( pData ){
251819    pRet = pData->pPtr;
251820    if( bClear ){
251821      pData->pPtr = 0;
251822      pData->xDelete = 0;
251823    }
251824  }
251825
251826  return pRet;
251827}
251828
251829static void fts5ApiPhraseNext(
251830  Fts5Context *pUnused,
251831  Fts5PhraseIter *pIter,
251832  int *piCol, int *piOff
251833){
251834  UNUSED_PARAM(pUnused);
251835  if( pIter->a>=pIter->b ){
251836    *piCol = -1;
251837    *piOff = -1;
251838  }else{
251839    int iVal;
251840    pIter->a += fts5GetVarint32(pIter->a, iVal);
251841    if( iVal==1 ){
251842      pIter->a += fts5GetVarint32(pIter->a, iVal);
251843      *piCol = iVal;
251844      *piOff = 0;
251845      pIter->a += fts5GetVarint32(pIter->a, iVal);
251846    }
251847    *piOff += (iVal-2);
251848  }
251849}
251850
251851static int fts5ApiPhraseFirst(
251852  Fts5Context *pCtx,
251853  int iPhrase,
251854  Fts5PhraseIter *pIter,
251855  int *piCol, int *piOff
251856){
251857  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251858  int n;
251859  int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
251860  if( rc==SQLITE_OK ){
251861    assert( pIter->a || n==0 );
251862    pIter->b = (pIter->a ? &pIter->a[n] : 0);
251863    *piCol = 0;
251864    *piOff = 0;
251865    fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
251866  }
251867  return rc;
251868}
251869
251870static void fts5ApiPhraseNextColumn(
251871  Fts5Context *pCtx,
251872  Fts5PhraseIter *pIter,
251873  int *piCol
251874){
251875  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251876  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
251877
251878  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
251879    if( pIter->a>=pIter->b ){
251880      *piCol = -1;
251881    }else{
251882      int iIncr;
251883      pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
251884      *piCol += (iIncr-2);
251885    }
251886  }else{
251887    while( 1 ){
251888      int dummy;
251889      if( pIter->a>=pIter->b ){
251890        *piCol = -1;
251891        return;
251892      }
251893      if( pIter->a[0]==0x01 ) break;
251894      pIter->a += fts5GetVarint32(pIter->a, dummy);
251895    }
251896    pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
251897  }
251898}
251899
251900static int fts5ApiPhraseFirstColumn(
251901  Fts5Context *pCtx,
251902  int iPhrase,
251903  Fts5PhraseIter *pIter,
251904  int *piCol
251905){
251906  int rc = SQLITE_OK;
251907  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251908  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
251909
251910  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
251911    Fts5Sorter *pSorter = pCsr->pSorter;
251912    int n;
251913    if( pSorter ){
251914      int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
251915      n = pSorter->aIdx[iPhrase] - i1;
251916      pIter->a = &pSorter->aPoslist[i1];
251917    }else{
251918      rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
251919    }
251920    if( rc==SQLITE_OK ){
251921      assert( pIter->a || n==0 );
251922      pIter->b = (pIter->a ? &pIter->a[n] : 0);
251923      *piCol = 0;
251924      fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
251925    }
251926  }else{
251927    int n;
251928    rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
251929    if( rc==SQLITE_OK ){
251930      assert( pIter->a || n==0 );
251931      pIter->b = (pIter->a ? &pIter->a[n] : 0);
251932      if( n<=0 ){
251933        *piCol = -1;
251934      }else if( pIter->a[0]==0x01 ){
251935        pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
251936      }else{
251937        *piCol = 0;
251938      }
251939    }
251940  }
251941
251942  return rc;
251943}
251944
251945/*
251946** xQueryToken() API implemenetation.
251947*/
251948static int fts5ApiQueryToken(
251949  Fts5Context* pCtx,
251950  int iPhrase,
251951  int iToken,
251952  const char **ppOut,
251953  int *pnOut
251954){
251955  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251956  return sqlite3Fts5ExprQueryToken(pCsr->pExpr, iPhrase, iToken, ppOut, pnOut);
251957}
251958
251959/*
251960** xInstToken() API implemenetation.
251961*/
251962static int fts5ApiInstToken(
251963  Fts5Context *pCtx,
251964  int iIdx,
251965  int iToken,
251966  const char **ppOut, int *pnOut
251967){
251968  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
251969  int rc = SQLITE_OK;
251970  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
251971   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
251972  ){
251973    if( iIdx<0 || iIdx>=pCsr->nInstCount ){
251974      rc = SQLITE_RANGE;
251975    }else{
251976      int iPhrase = pCsr->aInst[iIdx*3];
251977      int iCol = pCsr->aInst[iIdx*3 + 1];
251978      int iOff = pCsr->aInst[iIdx*3 + 2];
251979      i64 iRowid = fts5CursorRowid(pCsr);
251980      rc = sqlite3Fts5ExprInstToken(
251981          pCsr->pExpr, iRowid, iPhrase, iCol, iOff, iToken, ppOut, pnOut
251982      );
251983    }
251984  }
251985  return rc;
251986}
251987
251988
251989static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
251990    int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
251991);
251992
251993static const Fts5ExtensionApi sFts5Api = {
251994  3,                            /* iVersion */
251995  fts5ApiUserData,
251996  fts5ApiColumnCount,
251997  fts5ApiRowCount,
251998  fts5ApiColumnTotalSize,
251999  fts5ApiTokenize,
252000  fts5ApiPhraseCount,
252001  fts5ApiPhraseSize,
252002  fts5ApiInstCount,
252003  fts5ApiInst,
252004  fts5ApiRowid,
252005  fts5ApiColumnText,
252006  fts5ApiColumnSize,
252007  fts5ApiQueryPhrase,
252008  fts5ApiSetAuxdata,
252009  fts5ApiGetAuxdata,
252010  fts5ApiPhraseFirst,
252011  fts5ApiPhraseNext,
252012  fts5ApiPhraseFirstColumn,
252013  fts5ApiPhraseNextColumn,
252014  fts5ApiQueryToken,
252015  fts5ApiInstToken
252016};
252017
252018/*
252019** Implementation of API function xQueryPhrase().
252020*/
252021static int fts5ApiQueryPhrase(
252022  Fts5Context *pCtx,
252023  int iPhrase,
252024  void *pUserData,
252025  int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
252026){
252027  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
252028  Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
252029  int rc;
252030  Fts5Cursor *pNew = 0;
252031
252032  rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
252033  if( rc==SQLITE_OK ){
252034    pNew->ePlan = FTS5_PLAN_MATCH;
252035    pNew->iFirstRowid = SMALLEST_INT64;
252036    pNew->iLastRowid = LARGEST_INT64;
252037    pNew->base.pVtab = (sqlite3_vtab*)pTab;
252038    rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
252039  }
252040
252041  if( rc==SQLITE_OK ){
252042    for(rc = fts5CursorFirst(pTab, pNew, 0);
252043        rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
252044        rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
252045    ){
252046      rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
252047      if( rc!=SQLITE_OK ){
252048        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
252049        break;
252050      }
252051    }
252052  }
252053
252054  fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
252055  return rc;
252056}
252057
252058static void fts5ApiInvoke(
252059  Fts5Auxiliary *pAux,
252060  Fts5Cursor *pCsr,
252061  sqlite3_context *context,
252062  int argc,
252063  sqlite3_value **argv
252064){
252065  assert( pCsr->pAux==0 );
252066  pCsr->pAux = pAux;
252067  pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
252068  pCsr->pAux = 0;
252069}
252070
252071static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
252072  Fts5Cursor *pCsr;
252073  for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
252074    if( pCsr->iCsrId==iCsrId ) break;
252075  }
252076  return pCsr;
252077}
252078
252079static void fts5ApiCallback(
252080  sqlite3_context *context,
252081  int argc,
252082  sqlite3_value **argv
252083){
252084
252085  Fts5Auxiliary *pAux;
252086  Fts5Cursor *pCsr;
252087  i64 iCsrId;
252088
252089  assert( argc>=1 );
252090  pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
252091  iCsrId = sqlite3_value_int64(argv[0]);
252092
252093  pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
252094  if( pCsr==0 || pCsr->ePlan==0 ){
252095    char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
252096    sqlite3_result_error(context, zErr, -1);
252097    sqlite3_free(zErr);
252098  }else{
252099    fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
252100  }
252101}
252102
252103
252104/*
252105** Given cursor id iId, return a pointer to the corresponding Fts5Table
252106** object. Or NULL If the cursor id does not exist.
252107*/
252108static Fts5Table *sqlite3Fts5TableFromCsrid(
252109  Fts5Global *pGlobal,            /* FTS5 global context for db handle */
252110  i64 iCsrId                      /* Id of cursor to find */
252111){
252112  Fts5Cursor *pCsr;
252113  pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
252114  if( pCsr ){
252115    return (Fts5Table*)pCsr->base.pVtab;
252116  }
252117  return 0;
252118}
252119
252120/*
252121** Return a "position-list blob" corresponding to the current position of
252122** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
252123** the current position-list for each phrase in the query associated with
252124** cursor pCsr.
252125**
252126** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
252127** the number of phrases in the query. Following the varints are the
252128** concatenated position lists for each phrase, in order.
252129**
252130** The first varint (if it exists) contains the size of the position list
252131** for phrase 0. The second (same disclaimer) contains the size of position
252132** list 1. And so on. There is no size field for the final position list,
252133** as it can be derived from the total size of the blob.
252134*/
252135static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
252136  int i;
252137  int rc = SQLITE_OK;
252138  int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
252139  Fts5Buffer val;
252140
252141  memset(&val, 0, sizeof(Fts5Buffer));
252142  switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
252143    case FTS5_DETAIL_FULL:
252144
252145      /* Append the varints */
252146      for(i=0; i<(nPhrase-1); i++){
252147        const u8 *dummy;
252148        int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
252149        sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
252150      }
252151
252152      /* Append the position lists */
252153      for(i=0; i<nPhrase; i++){
252154        const u8 *pPoslist;
252155        int nPoslist;
252156        nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
252157        sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
252158      }
252159      break;
252160
252161    case FTS5_DETAIL_COLUMNS:
252162
252163      /* Append the varints */
252164      for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
252165        const u8 *dummy;
252166        int nByte;
252167        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
252168        sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
252169      }
252170
252171      /* Append the position lists */
252172      for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
252173        const u8 *pPoslist;
252174        int nPoslist;
252175        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
252176        sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
252177      }
252178      break;
252179
252180    default:
252181      break;
252182  }
252183
252184  sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
252185  return rc;
252186}
252187
252188/*
252189** This is the xColumn method, called by SQLite to request a value from
252190** the row that the supplied cursor currently points to.
252191*/
252192static int fts5ColumnMethod(
252193  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
252194  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
252195  int iCol                        /* Index of column to read value from */
252196){
252197  Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
252198  Fts5Config *pConfig = pTab->p.pConfig;
252199  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
252200  int rc = SQLITE_OK;
252201
252202  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
252203
252204  if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
252205    if( iCol==pConfig->nCol ){
252206      sqlite3_result_int64(pCtx, pCsr->iSpecial);
252207    }
252208  }else
252209
252210  if( iCol==pConfig->nCol ){
252211    /* User is requesting the value of the special column with the same name
252212    ** as the table. Return the cursor integer id number. This value is only
252213    ** useful in that it may be passed as the first argument to an FTS5
252214    ** auxiliary function.  */
252215    sqlite3_result_int64(pCtx, pCsr->iCsrId);
252216  }else if( iCol==pConfig->nCol+1 ){
252217
252218    /* The value of the "rank" column. */
252219    if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
252220      fts5PoslistBlob(pCtx, pCsr);
252221    }else if(
252222        pCsr->ePlan==FTS5_PLAN_MATCH
252223     || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
252224    ){
252225      if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
252226        fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
252227      }
252228    }
252229  }else if( !fts5IsContentless(pTab) ){
252230    pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
252231    rc = fts5SeekCursor(pCsr, 1);
252232    if( rc==SQLITE_OK ){
252233      sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
252234    }
252235    pConfig->pzErrmsg = 0;
252236  }else if( pConfig->bContentlessDelete && sqlite3_vtab_nochange(pCtx) ){
252237    char *zErr = sqlite3_mprintf("cannot UPDATE a subset of "
252238        "columns on fts5 contentless-delete table: %s", pConfig->zName
252239    );
252240    sqlite3_result_error(pCtx, zErr, -1);
252241    sqlite3_free(zErr);
252242  }
252243  return rc;
252244}
252245
252246
252247/*
252248** This routine implements the xFindFunction method for the FTS3
252249** virtual table.
252250*/
252251static int fts5FindFunctionMethod(
252252  sqlite3_vtab *pVtab,            /* Virtual table handle */
252253  int nUnused,                    /* Number of SQL function arguments */
252254  const char *zName,              /* Name of SQL function */
252255  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
252256  void **ppArg                    /* OUT: User data for *pxFunc */
252257){
252258  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
252259  Fts5Auxiliary *pAux;
252260
252261  UNUSED_PARAM(nUnused);
252262  pAux = fts5FindAuxiliary(pTab, zName);
252263  if( pAux ){
252264    *pxFunc = fts5ApiCallback;
252265    *ppArg = (void*)pAux;
252266    return 1;
252267  }
252268
252269  /* No function of the specified name was found. Return 0. */
252270  return 0;
252271}
252272
252273/*
252274** Implementation of FTS5 xRename method. Rename an fts5 table.
252275*/
252276static int fts5RenameMethod(
252277  sqlite3_vtab *pVtab,            /* Virtual table handle */
252278  const char *zName               /* New name of table */
252279){
252280  int rc;
252281  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
252282  rc = sqlite3Fts5StorageRename(pTab->pStorage, zName);
252283  return rc;
252284}
252285
252286static int sqlite3Fts5FlushToDisk(Fts5Table *pTab){
252287  fts5TripCursors((Fts5FullTable*)pTab);
252288  return sqlite3Fts5StorageSync(((Fts5FullTable*)pTab)->pStorage);
252289}
252290
252291/*
252292** The xSavepoint() method.
252293**
252294** Flush the contents of the pending-terms table to disk.
252295*/
252296static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
252297  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
252298  int rc = SQLITE_OK;
252299
252300  fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
252301  rc = sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
252302  if( rc==SQLITE_OK ){
252303    pTab->iSavepoint = iSavepoint+1;
252304  }
252305  return rc;
252306}
252307
252308/*
252309** The xRelease() method.
252310**
252311** This is a no-op.
252312*/
252313static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
252314  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
252315  int rc = SQLITE_OK;
252316  fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
252317  if( (iSavepoint+1)<pTab->iSavepoint ){
252318    rc = sqlite3Fts5FlushToDisk(&pTab->p);
252319    if( rc==SQLITE_OK ){
252320      pTab->iSavepoint = iSavepoint;
252321    }
252322  }
252323  return rc;
252324}
252325
252326/*
252327** The xRollbackTo() method.
252328**
252329** Discard the contents of the pending terms table.
252330*/
252331static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
252332  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
252333  int rc = SQLITE_OK;
252334  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
252335  fts5TripCursors(pTab);
252336  if( (iSavepoint+1)<=pTab->iSavepoint ){
252337    pTab->p.pConfig->pgsz = 0;
252338    rc = sqlite3Fts5StorageRollback(pTab->pStorage);
252339  }
252340  return rc;
252341}
252342
252343/*
252344** Register a new auxiliary function with global context pGlobal.
252345*/
252346static int fts5CreateAux(
252347  fts5_api *pApi,                 /* Global context (one per db handle) */
252348  const char *zName,              /* Name of new function */
252349  void *pUserData,                /* User data for aux. function */
252350  fts5_extension_function xFunc,  /* Aux. function implementation */
252351  void(*xDestroy)(void*)          /* Destructor for pUserData */
252352){
252353  Fts5Global *pGlobal = (Fts5Global*)pApi;
252354  int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
252355  if( rc==SQLITE_OK ){
252356    Fts5Auxiliary *pAux;
252357    sqlite3_int64 nName;            /* Size of zName in bytes, including \0 */
252358    sqlite3_int64 nByte;            /* Bytes of space to allocate */
252359
252360    nName = strlen(zName) + 1;
252361    nByte = sizeof(Fts5Auxiliary) + nName;
252362    pAux = (Fts5Auxiliary*)sqlite3_malloc64(nByte);
252363    if( pAux ){
252364      memset(pAux, 0, (size_t)nByte);
252365      pAux->zFunc = (char*)&pAux[1];
252366      memcpy(pAux->zFunc, zName, nName);
252367      pAux->pGlobal = pGlobal;
252368      pAux->pUserData = pUserData;
252369      pAux->xFunc = xFunc;
252370      pAux->xDestroy = xDestroy;
252371      pAux->pNext = pGlobal->pAux;
252372      pGlobal->pAux = pAux;
252373    }else{
252374      rc = SQLITE_NOMEM;
252375    }
252376  }
252377
252378  return rc;
252379}
252380
252381/*
252382** Register a new tokenizer. This is the implementation of the
252383** fts5_api.xCreateTokenizer() method.
252384*/
252385static int fts5CreateTokenizer(
252386  fts5_api *pApi,                 /* Global context (one per db handle) */
252387  const char *zName,              /* Name of new function */
252388  void *pUserData,                /* User data for aux. function */
252389  fts5_tokenizer *pTokenizer,     /* Tokenizer implementation */
252390  void(*xDestroy)(void*)          /* Destructor for pUserData */
252391){
252392  Fts5Global *pGlobal = (Fts5Global*)pApi;
252393  Fts5TokenizerModule *pNew;
252394  sqlite3_int64 nName;            /* Size of zName and its \0 terminator */
252395  sqlite3_int64 nByte;            /* Bytes of space to allocate */
252396  int rc = SQLITE_OK;
252397
252398  nName = strlen(zName) + 1;
252399  nByte = sizeof(Fts5TokenizerModule) + nName;
252400  pNew = (Fts5TokenizerModule*)sqlite3_malloc64(nByte);
252401  if( pNew ){
252402    memset(pNew, 0, (size_t)nByte);
252403    pNew->zName = (char*)&pNew[1];
252404    memcpy(pNew->zName, zName, nName);
252405    pNew->pUserData = pUserData;
252406    pNew->x = *pTokenizer;
252407    pNew->xDestroy = xDestroy;
252408    pNew->pNext = pGlobal->pTok;
252409    pGlobal->pTok = pNew;
252410    if( pNew->pNext==0 ){
252411      pGlobal->pDfltTok = pNew;
252412    }
252413  }else{
252414    rc = SQLITE_NOMEM;
252415  }
252416
252417  return rc;
252418}
252419
252420static Fts5TokenizerModule *fts5LocateTokenizer(
252421  Fts5Global *pGlobal,
252422  const char *zName
252423){
252424  Fts5TokenizerModule *pMod = 0;
252425
252426  if( zName==0 ){
252427    pMod = pGlobal->pDfltTok;
252428  }else{
252429    for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
252430      if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
252431    }
252432  }
252433
252434  return pMod;
252435}
252436
252437/*
252438** Find a tokenizer. This is the implementation of the
252439** fts5_api.xFindTokenizer() method.
252440*/
252441static int fts5FindTokenizer(
252442  fts5_api *pApi,                 /* Global context (one per db handle) */
252443  const char *zName,              /* Name of new function */
252444  void **ppUserData,
252445  fts5_tokenizer *pTokenizer      /* Populate this object */
252446){
252447  int rc = SQLITE_OK;
252448  Fts5TokenizerModule *pMod;
252449
252450  pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
252451  if( pMod ){
252452    *pTokenizer = pMod->x;
252453    *ppUserData = pMod->pUserData;
252454  }else{
252455    memset(pTokenizer, 0, sizeof(fts5_tokenizer));
252456    rc = SQLITE_ERROR;
252457  }
252458
252459  return rc;
252460}
252461
252462static int sqlite3Fts5GetTokenizer(
252463  Fts5Global *pGlobal,
252464  const char **azArg,
252465  int nArg,
252466  Fts5Config *pConfig,
252467  char **pzErr
252468){
252469  Fts5TokenizerModule *pMod;
252470  int rc = SQLITE_OK;
252471
252472  pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
252473  if( pMod==0 ){
252474    assert( nArg>0 );
252475    rc = SQLITE_ERROR;
252476    *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
252477  }else{
252478    rc = pMod->x.xCreate(
252479        pMod->pUserData, (azArg?&azArg[1]:0), (nArg?nArg-1:0), &pConfig->pTok
252480    );
252481    pConfig->pTokApi = &pMod->x;
252482    if( rc!=SQLITE_OK ){
252483      if( pzErr ) *pzErr = sqlite3_mprintf("error in tokenizer constructor");
252484    }else{
252485      pConfig->ePattern = sqlite3Fts5TokenizerPattern(
252486          pMod->x.xCreate, pConfig->pTok
252487      );
252488    }
252489  }
252490
252491  if( rc!=SQLITE_OK ){
252492    pConfig->pTokApi = 0;
252493    pConfig->pTok = 0;
252494  }
252495
252496  return rc;
252497}
252498
252499static void fts5ModuleDestroy(void *pCtx){
252500  Fts5TokenizerModule *pTok, *pNextTok;
252501  Fts5Auxiliary *pAux, *pNextAux;
252502  Fts5Global *pGlobal = (Fts5Global*)pCtx;
252503
252504  for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
252505    pNextAux = pAux->pNext;
252506    if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
252507    sqlite3_free(pAux);
252508  }
252509
252510  for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
252511    pNextTok = pTok->pNext;
252512    if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
252513    sqlite3_free(pTok);
252514  }
252515
252516  sqlite3_free(pGlobal);
252517}
252518
252519static void fts5Fts5Func(
252520  sqlite3_context *pCtx,          /* Function call context */
252521  int nArg,                       /* Number of args */
252522  sqlite3_value **apArg           /* Function arguments */
252523){
252524  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
252525  fts5_api **ppApi;
252526  UNUSED_PARAM(nArg);
252527  assert( nArg==1 );
252528  ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
252529  if( ppApi ) *ppApi = &pGlobal->api;
252530}
252531
252532/*
252533** Implementation of fts5_source_id() function.
252534*/
252535static void fts5SourceIdFunc(
252536  sqlite3_context *pCtx,          /* Function call context */
252537  int nArg,                       /* Number of args */
252538  sqlite3_value **apUnused        /* Function arguments */
252539){
252540  assert( nArg==0 );
252541  UNUSED_PARAM2(nArg, apUnused);
252542  sqlite3_result_text(pCtx, "fts5: 2024-05-23 13:25:27 96c92aba00c8375bc32fafcdf12429c58bd8aabfcadab6683e35bbb9cdebf19e", -1, SQLITE_TRANSIENT);
252543}
252544
252545/*
252546** Return true if zName is the extension on one of the shadow tables used
252547** by this module.
252548*/
252549static int fts5ShadowName(const char *zName){
252550  static const char *azName[] = {
252551    "config", "content", "data", "docsize", "idx"
252552  };
252553  unsigned int i;
252554  for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
252555    if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
252556  }
252557  return 0;
252558}
252559
252560/*
252561** Run an integrity check on the FTS5 data structures.  Return a string
252562** if anything is found amiss.  Return a NULL pointer if everything is
252563** OK.
252564*/
252565static int fts5IntegrityMethod(
252566  sqlite3_vtab *pVtab,    /* the FTS5 virtual table to check */
252567  const char *zSchema,    /* Name of schema in which this table lives */
252568  const char *zTabname,   /* Name of the table itself */
252569  int isQuick,            /* True if this is a quick-check */
252570  char **pzErr            /* Write error message here */
252571){
252572  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
252573  int rc;
252574
252575  assert( pzErr!=0 && *pzErr==0 );
252576  UNUSED_PARAM(isQuick);
252577  rc = sqlite3Fts5StorageIntegrity(pTab->pStorage, 0);
252578  if( (rc&0xff)==SQLITE_CORRUPT ){
252579    *pzErr = sqlite3_mprintf("malformed inverted index for FTS5 table %s.%s",
252580                zSchema, zTabname);
252581     rc = (*pzErr) ? SQLITE_OK : SQLITE_NOMEM;
252582  }else if( rc!=SQLITE_OK ){
252583    *pzErr = sqlite3_mprintf("unable to validate the inverted index for"
252584                             " FTS5 table %s.%s: %s",
252585                zSchema, zTabname, sqlite3_errstr(rc));
252586  }
252587  sqlite3Fts5IndexCloseReader(pTab->p.pIndex);
252588
252589  return rc;
252590}
252591
252592static int fts5Init(sqlite3 *db){
252593  static const sqlite3_module fts5Mod = {
252594    /* iVersion      */ 4,
252595    /* xCreate       */ fts5CreateMethod,
252596    /* xConnect      */ fts5ConnectMethod,
252597    /* xBestIndex    */ fts5BestIndexMethod,
252598    /* xDisconnect   */ fts5DisconnectMethod,
252599    /* xDestroy      */ fts5DestroyMethod,
252600    /* xOpen         */ fts5OpenMethod,
252601    /* xClose        */ fts5CloseMethod,
252602    /* xFilter       */ fts5FilterMethod,
252603    /* xNext         */ fts5NextMethod,
252604    /* xEof          */ fts5EofMethod,
252605    /* xColumn       */ fts5ColumnMethod,
252606    /* xRowid        */ fts5RowidMethod,
252607    /* xUpdate       */ fts5UpdateMethod,
252608    /* xBegin        */ fts5BeginMethod,
252609    /* xSync         */ fts5SyncMethod,
252610    /* xCommit       */ fts5CommitMethod,
252611    /* xRollback     */ fts5RollbackMethod,
252612    /* xFindFunction */ fts5FindFunctionMethod,
252613    /* xRename       */ fts5RenameMethod,
252614    /* xSavepoint    */ fts5SavepointMethod,
252615    /* xRelease      */ fts5ReleaseMethod,
252616    /* xRollbackTo   */ fts5RollbackToMethod,
252617    /* xShadowName   */ fts5ShadowName,
252618    /* xIntegrity    */ fts5IntegrityMethod
252619  };
252620
252621  int rc;
252622  Fts5Global *pGlobal = 0;
252623
252624  pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
252625  if( pGlobal==0 ){
252626    rc = SQLITE_NOMEM;
252627  }else{
252628    void *p = (void*)pGlobal;
252629    memset(pGlobal, 0, sizeof(Fts5Global));
252630    pGlobal->db = db;
252631    pGlobal->api.iVersion = 2;
252632    pGlobal->api.xCreateFunction = fts5CreateAux;
252633    pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
252634    pGlobal->api.xFindTokenizer = fts5FindTokenizer;
252635    rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
252636    if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
252637    if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
252638    if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
252639    if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
252640    if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
252641    if( rc==SQLITE_OK ){
252642      rc = sqlite3_create_function(
252643          db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
252644      );
252645    }
252646    if( rc==SQLITE_OK ){
252647      rc = sqlite3_create_function(
252648          db, "fts5_source_id", 0,
252649          SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS,
252650          p, fts5SourceIdFunc, 0, 0
252651      );
252652    }
252653  }
252654
252655  /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
252656  ** fts5_test_mi.c is compiled and linked into the executable. And call
252657  ** its entry point to enable the matchinfo() demo.  */
252658#ifdef SQLITE_FTS5_ENABLE_TEST_MI
252659  if( rc==SQLITE_OK ){
252660    extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
252661    rc = sqlite3Fts5TestRegisterMatchinfo(db);
252662  }
252663#endif
252664
252665  return rc;
252666}
252667
252668/*
252669** The following functions are used to register the module with SQLite. If
252670** this module is being built as part of the SQLite core (SQLITE_CORE is
252671** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
252672**
252673** Or, if this module is being built as a loadable extension,
252674** sqlite3Fts5Init() is omitted and the two standard entry points
252675** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
252676*/
252677#ifndef SQLITE_CORE
252678#ifdef _WIN32
252679__declspec(dllexport)
252680#endif
252681SQLITE_API int sqlite3_fts_init(
252682  sqlite3 *db,
252683  char **pzErrMsg,
252684  const sqlite3_api_routines *pApi
252685){
252686  SQLITE_EXTENSION_INIT2(pApi);
252687  (void)pzErrMsg;  /* Unused parameter */
252688  return fts5Init(db);
252689}
252690
252691#ifdef _WIN32
252692__declspec(dllexport)
252693#endif
252694SQLITE_API int sqlite3_fts5_init(
252695  sqlite3 *db,
252696  char **pzErrMsg,
252697  const sqlite3_api_routines *pApi
252698){
252699  SQLITE_EXTENSION_INIT2(pApi);
252700  (void)pzErrMsg;  /* Unused parameter */
252701  return fts5Init(db);
252702}
252703#else
252704SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
252705  return fts5Init(db);
252706}
252707#endif
252708
252709/*
252710** 2014 May 31
252711**
252712** The author disclaims copyright to this source code.  In place of
252713** a legal notice, here is a blessing:
252714**
252715**    May you do good and not evil.
252716**    May you find forgiveness for yourself and forgive others.
252717**    May you share freely, never taking more than you give.
252718**
252719******************************************************************************
252720**
252721*/
252722
252723
252724
252725/* #include "fts5Int.h" */
252726
252727struct Fts5Storage {
252728  Fts5Config *pConfig;
252729  Fts5Index *pIndex;
252730  int bTotalsValid;               /* True if nTotalRow/aTotalSize[] are valid */
252731  i64 nTotalRow;                  /* Total number of rows in FTS table */
252732  i64 *aTotalSize;                /* Total sizes of each column */
252733  sqlite3_stmt *aStmt[11];
252734};
252735
252736
252737#if FTS5_STMT_SCAN_ASC!=0
252738# error "FTS5_STMT_SCAN_ASC mismatch"
252739#endif
252740#if FTS5_STMT_SCAN_DESC!=1
252741# error "FTS5_STMT_SCAN_DESC mismatch"
252742#endif
252743#if FTS5_STMT_LOOKUP!=2
252744# error "FTS5_STMT_LOOKUP mismatch"
252745#endif
252746
252747#define FTS5_STMT_INSERT_CONTENT  3
252748#define FTS5_STMT_REPLACE_CONTENT 4
252749#define FTS5_STMT_DELETE_CONTENT  5
252750#define FTS5_STMT_REPLACE_DOCSIZE  6
252751#define FTS5_STMT_DELETE_DOCSIZE  7
252752#define FTS5_STMT_LOOKUP_DOCSIZE  8
252753#define FTS5_STMT_REPLACE_CONFIG 9
252754#define FTS5_STMT_SCAN 10
252755
252756/*
252757** Prepare the two insert statements - Fts5Storage.pInsertContent and
252758** Fts5Storage.pInsertDocsize - if they have not already been prepared.
252759** Return SQLITE_OK if successful, or an SQLite error code if an error
252760** occurs.
252761*/
252762static int fts5StorageGetStmt(
252763  Fts5Storage *p,                 /* Storage handle */
252764  int eStmt,                      /* FTS5_STMT_XXX constant */
252765  sqlite3_stmt **ppStmt,          /* OUT: Prepared statement handle */
252766  char **pzErrMsg                 /* OUT: Error message (if any) */
252767){
252768  int rc = SQLITE_OK;
252769
252770  /* If there is no %_docsize table, there should be no requests for
252771  ** statements to operate on it.  */
252772  assert( p->pConfig->bColumnsize || (
252773        eStmt!=FTS5_STMT_REPLACE_DOCSIZE
252774     && eStmt!=FTS5_STMT_DELETE_DOCSIZE
252775     && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
252776  ));
252777
252778  assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
252779  if( p->aStmt[eStmt]==0 ){
252780    const char *azStmt[] = {
252781      "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
252782      "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
252783      "SELECT %s FROM %s T WHERE T.%Q=?",               /* LOOKUP  */
252784
252785      "INSERT INTO %Q.'%q_content' VALUES(%s)",         /* INSERT_CONTENT  */
252786      "REPLACE INTO %Q.'%q_content' VALUES(%s)",        /* REPLACE_CONTENT */
252787      "DELETE FROM %Q.'%q_content' WHERE id=?",         /* DELETE_CONTENT  */
252788      "REPLACE INTO %Q.'%q_docsize' VALUES(?,?%s)",     /* REPLACE_DOCSIZE  */
252789      "DELETE FROM %Q.'%q_docsize' WHERE id=?",         /* DELETE_DOCSIZE  */
252790
252791      "SELECT sz%s FROM %Q.'%q_docsize' WHERE id=?",    /* LOOKUP_DOCSIZE  */
252792
252793      "REPLACE INTO %Q.'%q_config' VALUES(?,?)",        /* REPLACE_CONFIG */
252794      "SELECT %s FROM %s AS T",                         /* SCAN */
252795    };
252796    Fts5Config *pC = p->pConfig;
252797    char *zSql = 0;
252798
252799    switch( eStmt ){
252800      case FTS5_STMT_SCAN:
252801        zSql = sqlite3_mprintf(azStmt[eStmt],
252802            pC->zContentExprlist, pC->zContent
252803        );
252804        break;
252805
252806      case FTS5_STMT_SCAN_ASC:
252807      case FTS5_STMT_SCAN_DESC:
252808        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
252809            pC->zContent, pC->zContentRowid, pC->zContentRowid,
252810            pC->zContentRowid
252811        );
252812        break;
252813
252814      case FTS5_STMT_LOOKUP:
252815        zSql = sqlite3_mprintf(azStmt[eStmt],
252816            pC->zContentExprlist, pC->zContent, pC->zContentRowid
252817        );
252818        break;
252819
252820      case FTS5_STMT_INSERT_CONTENT:
252821      case FTS5_STMT_REPLACE_CONTENT: {
252822        int nCol = pC->nCol + 1;
252823        char *zBind;
252824        int i;
252825
252826        zBind = sqlite3_malloc64(1 + nCol*2);
252827        if( zBind ){
252828          for(i=0; i<nCol; i++){
252829            zBind[i*2] = '?';
252830            zBind[i*2 + 1] = ',';
252831          }
252832          zBind[i*2-1] = '\0';
252833          zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
252834          sqlite3_free(zBind);
252835        }
252836        break;
252837      }
252838
252839      case FTS5_STMT_REPLACE_DOCSIZE:
252840        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName,
252841          (pC->bContentlessDelete ? ",?" : "")
252842        );
252843        break;
252844
252845      case FTS5_STMT_LOOKUP_DOCSIZE:
252846        zSql = sqlite3_mprintf(azStmt[eStmt],
252847            (pC->bContentlessDelete ? ",origin" : ""),
252848            pC->zDb, pC->zName
252849        );
252850        break;
252851
252852      default:
252853        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
252854        break;
252855    }
252856
252857    if( zSql==0 ){
252858      rc = SQLITE_NOMEM;
252859    }else{
252860      int f = SQLITE_PREPARE_PERSISTENT;
252861      if( eStmt>FTS5_STMT_LOOKUP ) f |= SQLITE_PREPARE_NO_VTAB;
252862      p->pConfig->bLock++;
252863      rc = sqlite3_prepare_v3(pC->db, zSql, -1, f, &p->aStmt[eStmt], 0);
252864      p->pConfig->bLock--;
252865      sqlite3_free(zSql);
252866      if( rc!=SQLITE_OK && pzErrMsg ){
252867        *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
252868      }
252869    }
252870  }
252871
252872  *ppStmt = p->aStmt[eStmt];
252873  sqlite3_reset(*ppStmt);
252874  return rc;
252875}
252876
252877
252878static int fts5ExecPrintf(
252879  sqlite3 *db,
252880  char **pzErr,
252881  const char *zFormat,
252882  ...
252883){
252884  int rc;
252885  va_list ap;                     /* ... printf arguments */
252886  char *zSql;
252887
252888  va_start(ap, zFormat);
252889  zSql = sqlite3_vmprintf(zFormat, ap);
252890
252891  if( zSql==0 ){
252892    rc = SQLITE_NOMEM;
252893  }else{
252894    rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
252895    sqlite3_free(zSql);
252896  }
252897
252898  va_end(ap);
252899  return rc;
252900}
252901
252902/*
252903** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
252904** code otherwise.
252905*/
252906static int sqlite3Fts5DropAll(Fts5Config *pConfig){
252907  int rc = fts5ExecPrintf(pConfig->db, 0,
252908      "DROP TABLE IF EXISTS %Q.'%q_data';"
252909      "DROP TABLE IF EXISTS %Q.'%q_idx';"
252910      "DROP TABLE IF EXISTS %Q.'%q_config';",
252911      pConfig->zDb, pConfig->zName,
252912      pConfig->zDb, pConfig->zName,
252913      pConfig->zDb, pConfig->zName
252914  );
252915  if( rc==SQLITE_OK && pConfig->bColumnsize ){
252916    rc = fts5ExecPrintf(pConfig->db, 0,
252917        "DROP TABLE IF EXISTS %Q.'%q_docsize';",
252918        pConfig->zDb, pConfig->zName
252919    );
252920  }
252921  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
252922    rc = fts5ExecPrintf(pConfig->db, 0,
252923        "DROP TABLE IF EXISTS %Q.'%q_content';",
252924        pConfig->zDb, pConfig->zName
252925    );
252926  }
252927  return rc;
252928}
252929
252930static void fts5StorageRenameOne(
252931  Fts5Config *pConfig,            /* Current FTS5 configuration */
252932  int *pRc,                       /* IN/OUT: Error code */
252933  const char *zTail,              /* Tail of table name e.g. "data", "config" */
252934  const char *zName               /* New name of FTS5 table */
252935){
252936  if( *pRc==SQLITE_OK ){
252937    *pRc = fts5ExecPrintf(pConfig->db, 0,
252938        "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
252939        pConfig->zDb, pConfig->zName, zTail, zName, zTail
252940    );
252941  }
252942}
252943
252944static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
252945  Fts5Config *pConfig = pStorage->pConfig;
252946  int rc = sqlite3Fts5StorageSync(pStorage);
252947
252948  fts5StorageRenameOne(pConfig, &rc, "data", zName);
252949  fts5StorageRenameOne(pConfig, &rc, "idx", zName);
252950  fts5StorageRenameOne(pConfig, &rc, "config", zName);
252951  if( pConfig->bColumnsize ){
252952    fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
252953  }
252954  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
252955    fts5StorageRenameOne(pConfig, &rc, "content", zName);
252956  }
252957  return rc;
252958}
252959
252960/*
252961** Create the shadow table named zPost, with definition zDefn. Return
252962** SQLITE_OK if successful, or an SQLite error code otherwise.
252963*/
252964static int sqlite3Fts5CreateTable(
252965  Fts5Config *pConfig,            /* FTS5 configuration */
252966  const char *zPost,              /* Shadow table to create (e.g. "content") */
252967  const char *zDefn,              /* Columns etc. for shadow table */
252968  int bWithout,                   /* True for without rowid */
252969  char **pzErr                    /* OUT: Error message */
252970){
252971  int rc;
252972  char *zErr = 0;
252973
252974  rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
252975      pConfig->zDb, pConfig->zName, zPost, zDefn,
252976#ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
252977      bWithout?" WITHOUT ROWID":
252978#endif
252979      ""
252980  );
252981  if( zErr ){
252982    *pzErr = sqlite3_mprintf(
252983        "fts5: error creating shadow table %q_%s: %s",
252984        pConfig->zName, zPost, zErr
252985    );
252986    sqlite3_free(zErr);
252987  }
252988
252989  return rc;
252990}
252991
252992/*
252993** Open a new Fts5Index handle. If the bCreate argument is true, create
252994** and initialize the underlying tables
252995**
252996** If successful, set *pp to point to the new object and return SQLITE_OK.
252997** Otherwise, set *pp to NULL and return an SQLite error code.
252998*/
252999static int sqlite3Fts5StorageOpen(
253000  Fts5Config *pConfig,
253001  Fts5Index *pIndex,
253002  int bCreate,
253003  Fts5Storage **pp,
253004  char **pzErr                    /* OUT: Error message */
253005){
253006  int rc = SQLITE_OK;
253007  Fts5Storage *p;                 /* New object */
253008  sqlite3_int64 nByte;            /* Bytes of space to allocate */
253009
253010  nByte = sizeof(Fts5Storage)               /* Fts5Storage object */
253011        + pConfig->nCol * sizeof(i64);      /* Fts5Storage.aTotalSize[] */
253012  *pp = p = (Fts5Storage*)sqlite3_malloc64(nByte);
253013  if( !p ) return SQLITE_NOMEM;
253014
253015  memset(p, 0, (size_t)nByte);
253016  p->aTotalSize = (i64*)&p[1];
253017  p->pConfig = pConfig;
253018  p->pIndex = pIndex;
253019
253020  if( bCreate ){
253021    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
253022      int nDefn = 32 + pConfig->nCol*10;
253023      char *zDefn = sqlite3_malloc64(32 + (sqlite3_int64)pConfig->nCol * 10);
253024      if( zDefn==0 ){
253025        rc = SQLITE_NOMEM;
253026      }else{
253027        int i;
253028        int iOff;
253029        sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
253030        iOff = (int)strlen(zDefn);
253031        for(i=0; i<pConfig->nCol; i++){
253032          sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
253033          iOff += (int)strlen(&zDefn[iOff]);
253034        }
253035        rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
253036      }
253037      sqlite3_free(zDefn);
253038    }
253039
253040    if( rc==SQLITE_OK && pConfig->bColumnsize ){
253041      const char *zCols = "id INTEGER PRIMARY KEY, sz BLOB";
253042      if( pConfig->bContentlessDelete ){
253043        zCols = "id INTEGER PRIMARY KEY, sz BLOB, origin INTEGER";
253044      }
253045      rc = sqlite3Fts5CreateTable(pConfig, "docsize", zCols, 0, pzErr);
253046    }
253047    if( rc==SQLITE_OK ){
253048      rc = sqlite3Fts5CreateTable(
253049          pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
253050      );
253051    }
253052    if( rc==SQLITE_OK ){
253053      rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
253054    }
253055  }
253056
253057  if( rc ){
253058    sqlite3Fts5StorageClose(p);
253059    *pp = 0;
253060  }
253061  return rc;
253062}
253063
253064/*
253065** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
253066*/
253067static int sqlite3Fts5StorageClose(Fts5Storage *p){
253068  int rc = SQLITE_OK;
253069  if( p ){
253070    int i;
253071
253072    /* Finalize all SQL statements */
253073    for(i=0; i<ArraySize(p->aStmt); i++){
253074      sqlite3_finalize(p->aStmt[i]);
253075    }
253076
253077    sqlite3_free(p);
253078  }
253079  return rc;
253080}
253081
253082typedef struct Fts5InsertCtx Fts5InsertCtx;
253083struct Fts5InsertCtx {
253084  Fts5Storage *pStorage;
253085  int iCol;
253086  int szCol;                      /* Size of column value in tokens */
253087};
253088
253089/*
253090** Tokenization callback used when inserting tokens into the FTS index.
253091*/
253092static int fts5StorageInsertCallback(
253093  void *pContext,                 /* Pointer to Fts5InsertCtx object */
253094  int tflags,
253095  const char *pToken,             /* Buffer containing token */
253096  int nToken,                     /* Size of token in bytes */
253097  int iUnused1,                   /* Start offset of token */
253098  int iUnused2                    /* End offset of token */
253099){
253100  Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
253101  Fts5Index *pIdx = pCtx->pStorage->pIndex;
253102  UNUSED_PARAM2(iUnused1, iUnused2);
253103  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
253104  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
253105    pCtx->szCol++;
253106  }
253107  return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
253108}
253109
253110/*
253111** If a row with rowid iDel is present in the %_content table, add the
253112** delete-markers to the FTS index necessary to delete it. Do not actually
253113** remove the %_content row at this time though.
253114*/
253115static int fts5StorageDeleteFromIndex(
253116  Fts5Storage *p,
253117  i64 iDel,
253118  sqlite3_value **apVal
253119){
253120  Fts5Config *pConfig = p->pConfig;
253121  sqlite3_stmt *pSeek = 0;        /* SELECT to read row iDel from %_data */
253122  int rc = SQLITE_OK;             /* Return code */
253123  int rc2;                        /* sqlite3_reset() return code */
253124  int iCol;
253125  Fts5InsertCtx ctx;
253126
253127  if( apVal==0 ){
253128    rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
253129    if( rc!=SQLITE_OK ) return rc;
253130    sqlite3_bind_int64(pSeek, 1, iDel);
253131    if( sqlite3_step(pSeek)!=SQLITE_ROW ){
253132      return sqlite3_reset(pSeek);
253133    }
253134  }
253135
253136  ctx.pStorage = p;
253137  ctx.iCol = -1;
253138  for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
253139    if( pConfig->abUnindexed[iCol-1]==0 ){
253140      const char *zText;
253141      int nText;
253142      assert( pSeek==0 || apVal==0 );
253143      assert( pSeek!=0 || apVal!=0 );
253144      if( pSeek ){
253145        zText = (const char*)sqlite3_column_text(pSeek, iCol);
253146        nText = sqlite3_column_bytes(pSeek, iCol);
253147      }else if( ALWAYS(apVal) ){
253148        zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
253149        nText = sqlite3_value_bytes(apVal[iCol-1]);
253150      }else{
253151        continue;
253152      }
253153      ctx.szCol = 0;
253154      rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
253155          zText, nText, (void*)&ctx, fts5StorageInsertCallback
253156      );
253157      p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
253158      if( p->aTotalSize[iCol-1]<0 ){
253159        rc = FTS5_CORRUPT;
253160      }
253161    }
253162  }
253163  if( rc==SQLITE_OK && p->nTotalRow<1 ){
253164    rc = FTS5_CORRUPT;
253165  }else{
253166    p->nTotalRow--;
253167  }
253168
253169  rc2 = sqlite3_reset(pSeek);
253170  if( rc==SQLITE_OK ) rc = rc2;
253171  return rc;
253172}
253173
253174/*
253175** This function is called to process a DELETE on a contentless_delete=1
253176** table. It adds the tombstone required to delete the entry with rowid
253177** iDel. If successful, SQLITE_OK is returned. Or, if an error occurs,
253178** an SQLite error code.
253179*/
253180static int fts5StorageContentlessDelete(Fts5Storage *p, i64 iDel){
253181  i64 iOrigin = 0;
253182  sqlite3_stmt *pLookup = 0;
253183  int rc = SQLITE_OK;
253184
253185  assert( p->pConfig->bContentlessDelete );
253186  assert( p->pConfig->eContent==FTS5_CONTENT_NONE );
253187
253188  /* Look up the origin of the document in the %_docsize table. Store
253189  ** this in stack variable iOrigin.  */
253190  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
253191  if( rc==SQLITE_OK ){
253192    sqlite3_bind_int64(pLookup, 1, iDel);
253193    if( SQLITE_ROW==sqlite3_step(pLookup) ){
253194      iOrigin = sqlite3_column_int64(pLookup, 1);
253195    }
253196    rc = sqlite3_reset(pLookup);
253197  }
253198
253199  if( rc==SQLITE_OK && iOrigin!=0 ){
253200    rc = sqlite3Fts5IndexContentlessDelete(p->pIndex, iOrigin, iDel);
253201  }
253202
253203  return rc;
253204}
253205
253206/*
253207** Insert a record into the %_docsize table. Specifically, do:
253208**
253209**   INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
253210**
253211** If there is no %_docsize table (as happens if the columnsize=0 option
253212** is specified when the FTS5 table is created), this function is a no-op.
253213*/
253214static int fts5StorageInsertDocsize(
253215  Fts5Storage *p,                 /* Storage module to write to */
253216  i64 iRowid,                     /* id value */
253217  Fts5Buffer *pBuf                /* sz value */
253218){
253219  int rc = SQLITE_OK;
253220  if( p->pConfig->bColumnsize ){
253221    sqlite3_stmt *pReplace = 0;
253222    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
253223    if( rc==SQLITE_OK ){
253224      sqlite3_bind_int64(pReplace, 1, iRowid);
253225      if( p->pConfig->bContentlessDelete ){
253226        i64 iOrigin = 0;
253227        rc = sqlite3Fts5IndexGetOrigin(p->pIndex, &iOrigin);
253228        sqlite3_bind_int64(pReplace, 3, iOrigin);
253229      }
253230      if( rc==SQLITE_OK ){
253231        sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
253232        sqlite3_step(pReplace);
253233        rc = sqlite3_reset(pReplace);
253234        sqlite3_bind_null(pReplace, 2);
253235      }
253236    }
253237  }
253238  return rc;
253239}
253240
253241/*
253242** Load the contents of the "averages" record from disk into the
253243** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
253244** argument bCache is true, set the p->bTotalsValid flag to indicate
253245** that the contents of aTotalSize[] and nTotalRow are valid until
253246** further notice.
253247**
253248** Return SQLITE_OK if successful, or an SQLite error code if an error
253249** occurs.
253250*/
253251static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
253252  int rc = SQLITE_OK;
253253  if( p->bTotalsValid==0 ){
253254    rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
253255    p->bTotalsValid = bCache;
253256  }
253257  return rc;
253258}
253259
253260/*
253261** Store the current contents of the p->nTotalRow and p->aTotalSize[]
253262** variables in the "averages" record on disk.
253263**
253264** Return SQLITE_OK if successful, or an SQLite error code if an error
253265** occurs.
253266*/
253267static int fts5StorageSaveTotals(Fts5Storage *p){
253268  int nCol = p->pConfig->nCol;
253269  int i;
253270  Fts5Buffer buf;
253271  int rc = SQLITE_OK;
253272  memset(&buf, 0, sizeof(buf));
253273
253274  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
253275  for(i=0; i<nCol; i++){
253276    sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
253277  }
253278  if( rc==SQLITE_OK ){
253279    rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
253280  }
253281  sqlite3_free(buf.p);
253282
253283  return rc;
253284}
253285
253286/*
253287** Remove a row from the FTS table.
253288*/
253289static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
253290  Fts5Config *pConfig = p->pConfig;
253291  int rc;
253292  sqlite3_stmt *pDel = 0;
253293
253294  assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
253295  rc = fts5StorageLoadTotals(p, 1);
253296
253297  /* Delete the index records */
253298  if( rc==SQLITE_OK ){
253299    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
253300  }
253301
253302  if( rc==SQLITE_OK ){
253303    if( p->pConfig->bContentlessDelete ){
253304      rc = fts5StorageContentlessDelete(p, iDel);
253305    }else{
253306      rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
253307    }
253308  }
253309
253310  /* Delete the %_docsize record */
253311  if( rc==SQLITE_OK && pConfig->bColumnsize ){
253312    rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
253313    if( rc==SQLITE_OK ){
253314      sqlite3_bind_int64(pDel, 1, iDel);
253315      sqlite3_step(pDel);
253316      rc = sqlite3_reset(pDel);
253317    }
253318  }
253319
253320  /* Delete the %_content record */
253321  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
253322    if( rc==SQLITE_OK ){
253323      rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
253324    }
253325    if( rc==SQLITE_OK ){
253326      sqlite3_bind_int64(pDel, 1, iDel);
253327      sqlite3_step(pDel);
253328      rc = sqlite3_reset(pDel);
253329    }
253330  }
253331
253332  return rc;
253333}
253334
253335/*
253336** Delete all entries in the FTS5 index.
253337*/
253338static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
253339  Fts5Config *pConfig = p->pConfig;
253340  int rc;
253341
253342  p->bTotalsValid = 0;
253343
253344  /* Delete the contents of the %_data and %_docsize tables. */
253345  rc = fts5ExecPrintf(pConfig->db, 0,
253346      "DELETE FROM %Q.'%q_data';"
253347      "DELETE FROM %Q.'%q_idx';",
253348      pConfig->zDb, pConfig->zName,
253349      pConfig->zDb, pConfig->zName
253350  );
253351  if( rc==SQLITE_OK && pConfig->bColumnsize ){
253352    rc = fts5ExecPrintf(pConfig->db, 0,
253353        "DELETE FROM %Q.'%q_docsize';",
253354        pConfig->zDb, pConfig->zName
253355    );
253356  }
253357
253358  /* Reinitialize the %_data table. This call creates the initial structure
253359  ** and averages records.  */
253360  if( rc==SQLITE_OK ){
253361    rc = sqlite3Fts5IndexReinit(p->pIndex);
253362  }
253363  if( rc==SQLITE_OK ){
253364    rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
253365  }
253366  return rc;
253367}
253368
253369static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
253370  Fts5Buffer buf = {0,0,0};
253371  Fts5Config *pConfig = p->pConfig;
253372  sqlite3_stmt *pScan = 0;
253373  Fts5InsertCtx ctx;
253374  int rc, rc2;
253375
253376  memset(&ctx, 0, sizeof(Fts5InsertCtx));
253377  ctx.pStorage = p;
253378  rc = sqlite3Fts5StorageDeleteAll(p);
253379  if( rc==SQLITE_OK ){
253380    rc = fts5StorageLoadTotals(p, 1);
253381  }
253382
253383  if( rc==SQLITE_OK ){
253384    rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, pConfig->pzErrmsg);
253385  }
253386
253387  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
253388    i64 iRowid = sqlite3_column_int64(pScan, 0);
253389
253390    sqlite3Fts5BufferZero(&buf);
253391    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
253392    for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
253393      ctx.szCol = 0;
253394      if( pConfig->abUnindexed[ctx.iCol]==0 ){
253395        const char *zText = (const char*)sqlite3_column_text(pScan, ctx.iCol+1);
253396        int nText = sqlite3_column_bytes(pScan, ctx.iCol+1);
253397        rc = sqlite3Fts5Tokenize(pConfig,
253398            FTS5_TOKENIZE_DOCUMENT,
253399            zText, nText,
253400            (void*)&ctx,
253401            fts5StorageInsertCallback
253402        );
253403      }
253404      sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
253405      p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
253406    }
253407    p->nTotalRow++;
253408
253409    if( rc==SQLITE_OK ){
253410      rc = fts5StorageInsertDocsize(p, iRowid, &buf);
253411    }
253412  }
253413  sqlite3_free(buf.p);
253414  rc2 = sqlite3_reset(pScan);
253415  if( rc==SQLITE_OK ) rc = rc2;
253416
253417  /* Write the averages record */
253418  if( rc==SQLITE_OK ){
253419    rc = fts5StorageSaveTotals(p);
253420  }
253421  return rc;
253422}
253423
253424static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
253425  return sqlite3Fts5IndexOptimize(p->pIndex);
253426}
253427
253428static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
253429  return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
253430}
253431
253432static int sqlite3Fts5StorageReset(Fts5Storage *p){
253433  return sqlite3Fts5IndexReset(p->pIndex);
253434}
253435
253436/*
253437** Allocate a new rowid. This is used for "external content" tables when
253438** a NULL value is inserted into the rowid column. The new rowid is allocated
253439** by inserting a dummy row into the %_docsize table. The dummy will be
253440** overwritten later.
253441**
253442** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
253443** this case the user is required to provide a rowid explicitly.
253444*/
253445static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
253446  int rc = SQLITE_MISMATCH;
253447  if( p->pConfig->bColumnsize ){
253448    sqlite3_stmt *pReplace = 0;
253449    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
253450    if( rc==SQLITE_OK ){
253451      sqlite3_bind_null(pReplace, 1);
253452      sqlite3_bind_null(pReplace, 2);
253453      sqlite3_step(pReplace);
253454      rc = sqlite3_reset(pReplace);
253455    }
253456    if( rc==SQLITE_OK ){
253457      *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
253458    }
253459  }
253460  return rc;
253461}
253462
253463/*
253464** Insert a new row into the FTS content table.
253465*/
253466static int sqlite3Fts5StorageContentInsert(
253467  Fts5Storage *p,
253468  sqlite3_value **apVal,
253469  i64 *piRowid
253470){
253471  Fts5Config *pConfig = p->pConfig;
253472  int rc = SQLITE_OK;
253473
253474  /* Insert the new row into the %_content table. */
253475  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
253476    if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
253477      *piRowid = sqlite3_value_int64(apVal[1]);
253478    }else{
253479      rc = fts5StorageNewRowid(p, piRowid);
253480    }
253481  }else{
253482    sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */
253483    int i;                        /* Counter variable */
253484    rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
253485    for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
253486      rc = sqlite3_bind_value(pInsert, i, apVal[i]);
253487    }
253488    if( rc==SQLITE_OK ){
253489      sqlite3_step(pInsert);
253490      rc = sqlite3_reset(pInsert);
253491    }
253492    *piRowid = sqlite3_last_insert_rowid(pConfig->db);
253493  }
253494
253495  return rc;
253496}
253497
253498/*
253499** Insert new entries into the FTS index and %_docsize table.
253500*/
253501static int sqlite3Fts5StorageIndexInsert(
253502  Fts5Storage *p,
253503  sqlite3_value **apVal,
253504  i64 iRowid
253505){
253506  Fts5Config *pConfig = p->pConfig;
253507  int rc = SQLITE_OK;             /* Return code */
253508  Fts5InsertCtx ctx;              /* Tokenization callback context object */
253509  Fts5Buffer buf;                 /* Buffer used to build up %_docsize blob */
253510
253511  memset(&buf, 0, sizeof(Fts5Buffer));
253512  ctx.pStorage = p;
253513  rc = fts5StorageLoadTotals(p, 1);
253514
253515  if( rc==SQLITE_OK ){
253516    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
253517  }
253518  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
253519    ctx.szCol = 0;
253520    if( pConfig->abUnindexed[ctx.iCol]==0 ){
253521      const char *zText = (const char*)sqlite3_value_text(apVal[ctx.iCol+2]);
253522      int nText = sqlite3_value_bytes(apVal[ctx.iCol+2]);
253523      rc = sqlite3Fts5Tokenize(pConfig,
253524          FTS5_TOKENIZE_DOCUMENT,
253525          zText, nText,
253526          (void*)&ctx,
253527          fts5StorageInsertCallback
253528      );
253529    }
253530    sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
253531    p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
253532  }
253533  p->nTotalRow++;
253534
253535  /* Write the %_docsize record */
253536  if( rc==SQLITE_OK ){
253537    rc = fts5StorageInsertDocsize(p, iRowid, &buf);
253538  }
253539  sqlite3_free(buf.p);
253540
253541  return rc;
253542}
253543
253544static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
253545  Fts5Config *pConfig = p->pConfig;
253546  char *zSql;
253547  int rc;
253548
253549  zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
253550      pConfig->zDb, pConfig->zName, zSuffix
253551  );
253552  if( zSql==0 ){
253553    rc = SQLITE_NOMEM;
253554  }else{
253555    sqlite3_stmt *pCnt = 0;
253556    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
253557    if( rc==SQLITE_OK ){
253558      if( SQLITE_ROW==sqlite3_step(pCnt) ){
253559        *pnRow = sqlite3_column_int64(pCnt, 0);
253560      }
253561      rc = sqlite3_finalize(pCnt);
253562    }
253563  }
253564
253565  sqlite3_free(zSql);
253566  return rc;
253567}
253568
253569/*
253570** Context object used by sqlite3Fts5StorageIntegrity().
253571*/
253572typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
253573struct Fts5IntegrityCtx {
253574  i64 iRowid;
253575  int iCol;
253576  int szCol;
253577  u64 cksum;
253578  Fts5Termset *pTermset;
253579  Fts5Config *pConfig;
253580};
253581
253582
253583/*
253584** Tokenization callback used by integrity check.
253585*/
253586static int fts5StorageIntegrityCallback(
253587  void *pContext,                 /* Pointer to Fts5IntegrityCtx object */
253588  int tflags,
253589  const char *pToken,             /* Buffer containing token */
253590  int nToken,                     /* Size of token in bytes */
253591  int iUnused1,                   /* Start offset of token */
253592  int iUnused2                    /* End offset of token */
253593){
253594  Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
253595  Fts5Termset *pTermset = pCtx->pTermset;
253596  int bPresent;
253597  int ii;
253598  int rc = SQLITE_OK;
253599  int iPos;
253600  int iCol;
253601
253602  UNUSED_PARAM2(iUnused1, iUnused2);
253603  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
253604
253605  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
253606    pCtx->szCol++;
253607  }
253608
253609  switch( pCtx->pConfig->eDetail ){
253610    case FTS5_DETAIL_FULL:
253611      iPos = pCtx->szCol-1;
253612      iCol = pCtx->iCol;
253613      break;
253614
253615    case FTS5_DETAIL_COLUMNS:
253616      iPos = pCtx->iCol;
253617      iCol = 0;
253618      break;
253619
253620    default:
253621      assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
253622      iPos = 0;
253623      iCol = 0;
253624      break;
253625  }
253626
253627  rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
253628  if( rc==SQLITE_OK && bPresent==0 ){
253629    pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
253630        pCtx->iRowid, iCol, iPos, 0, pToken, nToken
253631    );
253632  }
253633
253634  for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
253635    const int nChar = pCtx->pConfig->aPrefix[ii];
253636    int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
253637    if( nByte ){
253638      rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
253639      if( bPresent==0 ){
253640        pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
253641            pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
253642        );
253643      }
253644    }
253645  }
253646
253647  return rc;
253648}
253649
253650/*
253651** Check that the contents of the FTS index match that of the %_content
253652** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
253653** some other SQLite error code if an error occurs while attempting to
253654** determine this.
253655*/
253656static int sqlite3Fts5StorageIntegrity(Fts5Storage *p, int iArg){
253657  Fts5Config *pConfig = p->pConfig;
253658  int rc = SQLITE_OK;             /* Return code */
253659  int *aColSize;                  /* Array of size pConfig->nCol */
253660  i64 *aTotalSize;                /* Array of size pConfig->nCol */
253661  Fts5IntegrityCtx ctx;
253662  sqlite3_stmt *pScan;
253663  int bUseCksum;
253664
253665  memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
253666  ctx.pConfig = p->pConfig;
253667  aTotalSize = (i64*)sqlite3_malloc64(pConfig->nCol*(sizeof(int)+sizeof(i64)));
253668  if( !aTotalSize ) return SQLITE_NOMEM;
253669  aColSize = (int*)&aTotalSize[pConfig->nCol];
253670  memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
253671
253672  bUseCksum = (pConfig->eContent==FTS5_CONTENT_NORMAL
253673           || (pConfig->eContent==FTS5_CONTENT_EXTERNAL && iArg)
253674  );
253675  if( bUseCksum ){
253676    /* Generate the expected index checksum based on the contents of the
253677    ** %_content table. This block stores the checksum in ctx.cksum. */
253678    rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
253679    if( rc==SQLITE_OK ){
253680      int rc2;
253681      while( SQLITE_ROW==sqlite3_step(pScan) ){
253682        int i;
253683        ctx.iRowid = sqlite3_column_int64(pScan, 0);
253684        ctx.szCol = 0;
253685        if( pConfig->bColumnsize ){
253686          rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
253687        }
253688        if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
253689          rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
253690        }
253691        for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
253692          if( pConfig->abUnindexed[i] ) continue;
253693          ctx.iCol = i;
253694          ctx.szCol = 0;
253695          if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
253696            rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
253697          }
253698          if( rc==SQLITE_OK ){
253699            const char *zText = (const char*)sqlite3_column_text(pScan, i+1);
253700            int nText = sqlite3_column_bytes(pScan, i+1);
253701            rc = sqlite3Fts5Tokenize(pConfig,
253702                FTS5_TOKENIZE_DOCUMENT,
253703                zText, nText,
253704                (void*)&ctx,
253705                fts5StorageIntegrityCallback
253706            );
253707          }
253708          if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
253709            rc = FTS5_CORRUPT;
253710          }
253711          aTotalSize[i] += ctx.szCol;
253712          if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
253713            sqlite3Fts5TermsetFree(ctx.pTermset);
253714            ctx.pTermset = 0;
253715          }
253716        }
253717        sqlite3Fts5TermsetFree(ctx.pTermset);
253718        ctx.pTermset = 0;
253719
253720        if( rc!=SQLITE_OK ) break;
253721      }
253722      rc2 = sqlite3_reset(pScan);
253723      if( rc==SQLITE_OK ) rc = rc2;
253724    }
253725
253726    /* Test that the "totals" (sometimes called "averages") record looks Ok */
253727    if( rc==SQLITE_OK ){
253728      int i;
253729      rc = fts5StorageLoadTotals(p, 0);
253730      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
253731        if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
253732      }
253733    }
253734
253735    /* Check that the %_docsize and %_content tables contain the expected
253736    ** number of rows.  */
253737    if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
253738      i64 nRow = 0;
253739      rc = fts5StorageCount(p, "content", &nRow);
253740      if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
253741    }
253742    if( rc==SQLITE_OK && pConfig->bColumnsize ){
253743      i64 nRow = 0;
253744      rc = fts5StorageCount(p, "docsize", &nRow);
253745      if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
253746    }
253747  }
253748
253749  /* Pass the expected checksum down to the FTS index module. It will
253750  ** verify, amongst other things, that it matches the checksum generated by
253751  ** inspecting the index itself.  */
253752  if( rc==SQLITE_OK ){
253753    rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum, bUseCksum);
253754  }
253755
253756  sqlite3_free(aTotalSize);
253757  return rc;
253758}
253759
253760/*
253761** Obtain an SQLite statement handle that may be used to read data from the
253762** %_content table.
253763*/
253764static int sqlite3Fts5StorageStmt(
253765  Fts5Storage *p,
253766  int eStmt,
253767  sqlite3_stmt **pp,
253768  char **pzErrMsg
253769){
253770  int rc;
253771  assert( eStmt==FTS5_STMT_SCAN_ASC
253772       || eStmt==FTS5_STMT_SCAN_DESC
253773       || eStmt==FTS5_STMT_LOOKUP
253774  );
253775  rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
253776  if( rc==SQLITE_OK ){
253777    assert( p->aStmt[eStmt]==*pp );
253778    p->aStmt[eStmt] = 0;
253779  }
253780  return rc;
253781}
253782
253783/*
253784** Release an SQLite statement handle obtained via an earlier call to
253785** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
253786** must match that passed to the sqlite3Fts5StorageStmt() call.
253787*/
253788static void sqlite3Fts5StorageStmtRelease(
253789  Fts5Storage *p,
253790  int eStmt,
253791  sqlite3_stmt *pStmt
253792){
253793  assert( eStmt==FTS5_STMT_SCAN_ASC
253794       || eStmt==FTS5_STMT_SCAN_DESC
253795       || eStmt==FTS5_STMT_LOOKUP
253796  );
253797  if( p->aStmt[eStmt]==0 ){
253798    sqlite3_reset(pStmt);
253799    p->aStmt[eStmt] = pStmt;
253800  }else{
253801    sqlite3_finalize(pStmt);
253802  }
253803}
253804
253805static int fts5StorageDecodeSizeArray(
253806  int *aCol, int nCol,            /* Array to populate */
253807  const u8 *aBlob, int nBlob      /* Record to read varints from */
253808){
253809  int i;
253810  int iOff = 0;
253811  for(i=0; i<nCol; i++){
253812    if( iOff>=nBlob ) return 1;
253813    iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
253814  }
253815  return (iOff!=nBlob);
253816}
253817
253818/*
253819** Argument aCol points to an array of integers containing one entry for
253820** each table column. This function reads the %_docsize record for the
253821** specified rowid and populates aCol[] with the results.
253822**
253823** An SQLite error code is returned if an error occurs, or SQLITE_OK
253824** otherwise.
253825*/
253826static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
253827  int nCol = p->pConfig->nCol;    /* Number of user columns in table */
253828  sqlite3_stmt *pLookup = 0;      /* Statement to query %_docsize */
253829  int rc;                         /* Return Code */
253830
253831  assert( p->pConfig->bColumnsize );
253832  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
253833  if( pLookup ){
253834    int bCorrupt = 1;
253835    assert( rc==SQLITE_OK );
253836    sqlite3_bind_int64(pLookup, 1, iRowid);
253837    if( SQLITE_ROW==sqlite3_step(pLookup) ){
253838      const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
253839      int nBlob = sqlite3_column_bytes(pLookup, 0);
253840      if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
253841        bCorrupt = 0;
253842      }
253843    }
253844    rc = sqlite3_reset(pLookup);
253845    if( bCorrupt && rc==SQLITE_OK ){
253846      rc = FTS5_CORRUPT;
253847    }
253848  }else{
253849    assert( rc!=SQLITE_OK );
253850  }
253851
253852  return rc;
253853}
253854
253855static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
253856  int rc = fts5StorageLoadTotals(p, 0);
253857  if( rc==SQLITE_OK ){
253858    *pnToken = 0;
253859    if( iCol<0 ){
253860      int i;
253861      for(i=0; i<p->pConfig->nCol; i++){
253862        *pnToken += p->aTotalSize[i];
253863      }
253864    }else if( iCol<p->pConfig->nCol ){
253865      *pnToken = p->aTotalSize[iCol];
253866    }else{
253867      rc = SQLITE_RANGE;
253868    }
253869  }
253870  return rc;
253871}
253872
253873static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
253874  int rc = fts5StorageLoadTotals(p, 0);
253875  if( rc==SQLITE_OK ){
253876    /* nTotalRow being zero does not necessarily indicate a corrupt
253877    ** database - it might be that the FTS5 table really does contain zero
253878    ** rows. However this function is only called from the xRowCount() API,
253879    ** and there is no way for that API to be invoked if the table contains
253880    ** no rows. Hence the FTS5_CORRUPT return.  */
253881    *pnRow = p->nTotalRow;
253882    if( p->nTotalRow<=0 ) rc = FTS5_CORRUPT;
253883  }
253884  return rc;
253885}
253886
253887/*
253888** Flush any data currently held in-memory to disk.
253889*/
253890static int sqlite3Fts5StorageSync(Fts5Storage *p){
253891  int rc = SQLITE_OK;
253892  i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
253893  if( p->bTotalsValid ){
253894    rc = fts5StorageSaveTotals(p);
253895    if( rc==SQLITE_OK ){
253896      p->bTotalsValid = 0;
253897    }
253898  }
253899  if( rc==SQLITE_OK ){
253900    rc = sqlite3Fts5IndexSync(p->pIndex);
253901  }
253902  sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
253903  return rc;
253904}
253905
253906static int sqlite3Fts5StorageRollback(Fts5Storage *p){
253907  p->bTotalsValid = 0;
253908  return sqlite3Fts5IndexRollback(p->pIndex);
253909}
253910
253911static int sqlite3Fts5StorageConfigValue(
253912  Fts5Storage *p,
253913  const char *z,
253914  sqlite3_value *pVal,
253915  int iVal
253916){
253917  sqlite3_stmt *pReplace = 0;
253918  int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
253919  if( rc==SQLITE_OK ){
253920    sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
253921    if( pVal ){
253922      sqlite3_bind_value(pReplace, 2, pVal);
253923    }else{
253924      sqlite3_bind_int(pReplace, 2, iVal);
253925    }
253926    sqlite3_step(pReplace);
253927    rc = sqlite3_reset(pReplace);
253928    sqlite3_bind_null(pReplace, 1);
253929  }
253930  if( rc==SQLITE_OK && pVal ){
253931    int iNew = p->pConfig->iCookie + 1;
253932    rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
253933    if( rc==SQLITE_OK ){
253934      p->pConfig->iCookie = iNew;
253935    }
253936  }
253937  return rc;
253938}
253939
253940/*
253941** 2014 May 31
253942**
253943** The author disclaims copyright to this source code.  In place of
253944** a legal notice, here is a blessing:
253945**
253946**    May you do good and not evil.
253947**    May you find forgiveness for yourself and forgive others.
253948**    May you share freely, never taking more than you give.
253949**
253950******************************************************************************
253951*/
253952
253953
253954/* #include "fts5Int.h" */
253955
253956/**************************************************************************
253957** Start of ascii tokenizer implementation.
253958*/
253959
253960/*
253961** For tokenizers with no "unicode" modifier, the set of token characters
253962** is the same as the set of ASCII range alphanumeric characters.
253963*/
253964static unsigned char aAsciiTokenChar[128] = {
253965  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00..0x0F */
253966  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x10..0x1F */
253967  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20..0x2F */
253968  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30..0x3F */
253969  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40..0x4F */
253970  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x50..0x5F */
253971  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60..0x6F */
253972  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x70..0x7F */
253973};
253974
253975typedef struct AsciiTokenizer AsciiTokenizer;
253976struct AsciiTokenizer {
253977  unsigned char aTokenChar[128];
253978};
253979
253980static void fts5AsciiAddExceptions(
253981  AsciiTokenizer *p,
253982  const char *zArg,
253983  int bTokenChars
253984){
253985  int i;
253986  for(i=0; zArg[i]; i++){
253987    if( (zArg[i] & 0x80)==0 ){
253988      p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
253989    }
253990  }
253991}
253992
253993/*
253994** Delete a "ascii" tokenizer.
253995*/
253996static void fts5AsciiDelete(Fts5Tokenizer *p){
253997  sqlite3_free(p);
253998}
253999
254000/*
254001** Create an "ascii" tokenizer.
254002*/
254003static int fts5AsciiCreate(
254004  void *pUnused,
254005  const char **azArg, int nArg,
254006  Fts5Tokenizer **ppOut
254007){
254008  int rc = SQLITE_OK;
254009  AsciiTokenizer *p = 0;
254010  UNUSED_PARAM(pUnused);
254011  if( nArg%2 ){
254012    rc = SQLITE_ERROR;
254013  }else{
254014    p = sqlite3_malloc(sizeof(AsciiTokenizer));
254015    if( p==0 ){
254016      rc = SQLITE_NOMEM;
254017    }else{
254018      int i;
254019      memset(p, 0, sizeof(AsciiTokenizer));
254020      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
254021      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
254022        const char *zArg = azArg[i+1];
254023        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
254024          fts5AsciiAddExceptions(p, zArg, 1);
254025        }else
254026        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
254027          fts5AsciiAddExceptions(p, zArg, 0);
254028        }else{
254029          rc = SQLITE_ERROR;
254030        }
254031      }
254032      if( rc!=SQLITE_OK ){
254033        fts5AsciiDelete((Fts5Tokenizer*)p);
254034        p = 0;
254035      }
254036    }
254037  }
254038
254039  *ppOut = (Fts5Tokenizer*)p;
254040  return rc;
254041}
254042
254043
254044static void asciiFold(char *aOut, const char *aIn, int nByte){
254045  int i;
254046  for(i=0; i<nByte; i++){
254047    char c = aIn[i];
254048    if( c>='A' && c<='Z' ) c += 32;
254049    aOut[i] = c;
254050  }
254051}
254052
254053/*
254054** Tokenize some text using the ascii tokenizer.
254055*/
254056static int fts5AsciiTokenize(
254057  Fts5Tokenizer *pTokenizer,
254058  void *pCtx,
254059  int iUnused,
254060  const char *pText, int nText,
254061  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
254062){
254063  AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
254064  int rc = SQLITE_OK;
254065  int ie;
254066  int is = 0;
254067
254068  char aFold[64];
254069  int nFold = sizeof(aFold);
254070  char *pFold = aFold;
254071  unsigned char *a = p->aTokenChar;
254072
254073  UNUSED_PARAM(iUnused);
254074
254075  while( is<nText && rc==SQLITE_OK ){
254076    int nByte;
254077
254078    /* Skip any leading divider characters. */
254079    while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
254080      is++;
254081    }
254082    if( is==nText ) break;
254083
254084    /* Count the token characters */
254085    ie = is+1;
254086    while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
254087      ie++;
254088    }
254089
254090    /* Fold to lower case */
254091    nByte = ie-is;
254092    if( nByte>nFold ){
254093      if( pFold!=aFold ) sqlite3_free(pFold);
254094      pFold = sqlite3_malloc64((sqlite3_int64)nByte*2);
254095      if( pFold==0 ){
254096        rc = SQLITE_NOMEM;
254097        break;
254098      }
254099      nFold = nByte*2;
254100    }
254101    asciiFold(pFold, &pText[is], nByte);
254102
254103    /* Invoke the token callback */
254104    rc = xToken(pCtx, 0, pFold, nByte, is, ie);
254105    is = ie+1;
254106  }
254107
254108  if( pFold!=aFold ) sqlite3_free(pFold);
254109  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
254110  return rc;
254111}
254112
254113/**************************************************************************
254114** Start of unicode61 tokenizer implementation.
254115*/
254116
254117
254118/*
254119** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
254120** from the sqlite3 source file utf.c. If this file is compiled as part
254121** of the amalgamation, they are not required.
254122*/
254123#ifndef SQLITE_AMALGAMATION
254124
254125static const unsigned char sqlite3Utf8Trans1[] = {
254126  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
254127  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
254128  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
254129  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
254130  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
254131  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
254132  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
254133  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
254134};
254135
254136#define READ_UTF8(zIn, zTerm, c)                           \
254137  c = *(zIn++);                                            \
254138  if( c>=0xc0 ){                                           \
254139    c = sqlite3Utf8Trans1[c-0xc0];                         \
254140    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
254141      c = (c<<6) + (0x3f & *(zIn++));                      \
254142    }                                                      \
254143    if( c<0x80                                             \
254144        || (c&0xFFFFF800)==0xD800                          \
254145        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
254146  }
254147
254148
254149#define WRITE_UTF8(zOut, c) {                          \
254150  if( c<0x00080 ){                                     \
254151    *zOut++ = (unsigned char)(c&0xFF);                 \
254152  }                                                    \
254153  else if( c<0x00800 ){                                \
254154    *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F);     \
254155    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
254156  }                                                    \
254157  else if( c<0x10000 ){                                \
254158    *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F);    \
254159    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
254160    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
254161  }else{                                               \
254162    *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07);  \
254163    *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F);  \
254164    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
254165    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
254166  }                                                    \
254167}
254168
254169#endif /* ifndef SQLITE_AMALGAMATION */
254170
254171#define FTS5_SKIP_UTF8(zIn) {                               \
254172  if( ((unsigned char)(*(zIn++)))>=0xc0 ){                              \
254173    while( (((unsigned char)*zIn) & 0xc0)==0x80 ){ zIn++; }             \
254174  }                                                    \
254175}
254176
254177typedef struct Unicode61Tokenizer Unicode61Tokenizer;
254178struct Unicode61Tokenizer {
254179  unsigned char aTokenChar[128];  /* ASCII range token characters */
254180  char *aFold;                    /* Buffer to fold text into */
254181  int nFold;                      /* Size of aFold[] in bytes */
254182  int eRemoveDiacritic;           /* True if remove_diacritics=1 is set */
254183  int nException;
254184  int *aiException;
254185
254186  unsigned char aCategory[32];    /* True for token char categories */
254187};
254188
254189/* Values for eRemoveDiacritic (must match internals of fts5_unicode2.c) */
254190#define FTS5_REMOVE_DIACRITICS_NONE    0
254191#define FTS5_REMOVE_DIACRITICS_SIMPLE  1
254192#define FTS5_REMOVE_DIACRITICS_COMPLEX 2
254193
254194static int fts5UnicodeAddExceptions(
254195  Unicode61Tokenizer *p,          /* Tokenizer object */
254196  const char *z,                  /* Characters to treat as exceptions */
254197  int bTokenChars                 /* 1 for 'tokenchars', 0 for 'separators' */
254198){
254199  int rc = SQLITE_OK;
254200  int n = (int)strlen(z);
254201  int *aNew;
254202
254203  if( n>0 ){
254204    aNew = (int*)sqlite3_realloc64(p->aiException,
254205                                   (n+p->nException)*sizeof(int));
254206    if( aNew ){
254207      int nNew = p->nException;
254208      const unsigned char *zCsr = (const unsigned char*)z;
254209      const unsigned char *zTerm = (const unsigned char*)&z[n];
254210      while( zCsr<zTerm ){
254211        u32 iCode;
254212        int bToken;
254213        READ_UTF8(zCsr, zTerm, iCode);
254214        if( iCode<128 ){
254215          p->aTokenChar[iCode] = (unsigned char)bTokenChars;
254216        }else{
254217          bToken = p->aCategory[sqlite3Fts5UnicodeCategory(iCode)];
254218          assert( (bToken==0 || bToken==1) );
254219          assert( (bTokenChars==0 || bTokenChars==1) );
254220          if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
254221            int i;
254222            for(i=0; i<nNew; i++){
254223              if( (u32)aNew[i]>iCode ) break;
254224            }
254225            memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
254226            aNew[i] = iCode;
254227            nNew++;
254228          }
254229        }
254230      }
254231      p->aiException = aNew;
254232      p->nException = nNew;
254233    }else{
254234      rc = SQLITE_NOMEM;
254235    }
254236  }
254237
254238  return rc;
254239}
254240
254241/*
254242** Return true if the p->aiException[] array contains the value iCode.
254243*/
254244static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
254245  if( p->nException>0 ){
254246    int *a = p->aiException;
254247    int iLo = 0;
254248    int iHi = p->nException-1;
254249
254250    while( iHi>=iLo ){
254251      int iTest = (iHi + iLo) / 2;
254252      if( iCode==a[iTest] ){
254253        return 1;
254254      }else if( iCode>a[iTest] ){
254255        iLo = iTest+1;
254256      }else{
254257        iHi = iTest-1;
254258      }
254259    }
254260  }
254261
254262  return 0;
254263}
254264
254265/*
254266** Delete a "unicode61" tokenizer.
254267*/
254268static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
254269  if( pTok ){
254270    Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
254271    sqlite3_free(p->aiException);
254272    sqlite3_free(p->aFold);
254273    sqlite3_free(p);
254274  }
254275  return;
254276}
254277
254278static int unicodeSetCategories(Unicode61Tokenizer *p, const char *zCat){
254279  const char *z = zCat;
254280
254281  while( *z ){
254282    while( *z==' ' || *z=='\t' ) z++;
254283    if( *z && sqlite3Fts5UnicodeCatParse(z, p->aCategory) ){
254284      return SQLITE_ERROR;
254285    }
254286    while( *z!=' ' && *z!='\t' && *z!='\0' ) z++;
254287  }
254288
254289  sqlite3Fts5UnicodeAscii(p->aCategory, p->aTokenChar);
254290  return SQLITE_OK;
254291}
254292
254293/*
254294** Create a "unicode61" tokenizer.
254295*/
254296static int fts5UnicodeCreate(
254297  void *pUnused,
254298  const char **azArg, int nArg,
254299  Fts5Tokenizer **ppOut
254300){
254301  int rc = SQLITE_OK;             /* Return code */
254302  Unicode61Tokenizer *p = 0;      /* New tokenizer object */
254303
254304  UNUSED_PARAM(pUnused);
254305
254306  if( nArg%2 ){
254307    rc = SQLITE_ERROR;
254308  }else{
254309    p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
254310    if( p ){
254311      const char *zCat = "L* N* Co";
254312      int i;
254313      memset(p, 0, sizeof(Unicode61Tokenizer));
254314
254315      p->eRemoveDiacritic = FTS5_REMOVE_DIACRITICS_SIMPLE;
254316      p->nFold = 64;
254317      p->aFold = sqlite3_malloc64(p->nFold * sizeof(char));
254318      if( p->aFold==0 ){
254319        rc = SQLITE_NOMEM;
254320      }
254321
254322      /* Search for a "categories" argument */
254323      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
254324        if( 0==sqlite3_stricmp(azArg[i], "categories") ){
254325          zCat = azArg[i+1];
254326        }
254327      }
254328
254329      if( rc==SQLITE_OK ){
254330        rc = unicodeSetCategories(p, zCat);
254331      }
254332
254333      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
254334        const char *zArg = azArg[i+1];
254335        if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
254336          if( (zArg[0]!='0' && zArg[0]!='1' && zArg[0]!='2') || zArg[1] ){
254337            rc = SQLITE_ERROR;
254338          }else{
254339            p->eRemoveDiacritic = (zArg[0] - '0');
254340            assert( p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_NONE
254341                 || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_SIMPLE
254342                 || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_COMPLEX
254343            );
254344          }
254345        }else
254346        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
254347          rc = fts5UnicodeAddExceptions(p, zArg, 1);
254348        }else
254349        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
254350          rc = fts5UnicodeAddExceptions(p, zArg, 0);
254351        }else
254352        if( 0==sqlite3_stricmp(azArg[i], "categories") ){
254353          /* no-op */
254354        }else{
254355          rc = SQLITE_ERROR;
254356        }
254357      }
254358
254359    }else{
254360      rc = SQLITE_NOMEM;
254361    }
254362    if( rc!=SQLITE_OK ){
254363      fts5UnicodeDelete((Fts5Tokenizer*)p);
254364      p = 0;
254365    }
254366    *ppOut = (Fts5Tokenizer*)p;
254367  }
254368  return rc;
254369}
254370
254371/*
254372** Return true if, for the purposes of tokenizing with the tokenizer
254373** passed as the first argument, codepoint iCode is considered a token
254374** character (not a separator).
254375*/
254376static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
254377  return (
254378    p->aCategory[sqlite3Fts5UnicodeCategory((u32)iCode)]
254379    ^ fts5UnicodeIsException(p, iCode)
254380  );
254381}
254382
254383static int fts5UnicodeTokenize(
254384  Fts5Tokenizer *pTokenizer,
254385  void *pCtx,
254386  int iUnused,
254387  const char *pText, int nText,
254388  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
254389){
254390  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
254391  int rc = SQLITE_OK;
254392  unsigned char *a = p->aTokenChar;
254393
254394  unsigned char *zTerm = (unsigned char*)&pText[nText];
254395  unsigned char *zCsr = (unsigned char *)pText;
254396
254397  /* Output buffer */
254398  char *aFold = p->aFold;
254399  int nFold = p->nFold;
254400  const char *pEnd = &aFold[nFold-6];
254401
254402  UNUSED_PARAM(iUnused);
254403
254404  /* Each iteration of this loop gobbles up a contiguous run of separators,
254405  ** then the next token.  */
254406  while( rc==SQLITE_OK ){
254407    u32 iCode;                    /* non-ASCII codepoint read from input */
254408    char *zOut = aFold;
254409    int is;
254410    int ie;
254411
254412    /* Skip any separator characters. */
254413    while( 1 ){
254414      if( zCsr>=zTerm ) goto tokenize_done;
254415      if( *zCsr & 0x80 ) {
254416        /* A character outside of the ascii range. Skip past it if it is
254417        ** a separator character. Or break out of the loop if it is not. */
254418        is = zCsr - (unsigned char*)pText;
254419        READ_UTF8(zCsr, zTerm, iCode);
254420        if( fts5UnicodeIsAlnum(p, iCode) ){
254421          goto non_ascii_tokenchar;
254422        }
254423      }else{
254424        if( a[*zCsr] ){
254425          is = zCsr - (unsigned char*)pText;
254426          goto ascii_tokenchar;
254427        }
254428        zCsr++;
254429      }
254430    }
254431
254432    /* Run through the tokenchars. Fold them into the output buffer along
254433    ** the way.  */
254434    while( zCsr<zTerm ){
254435
254436      /* Grow the output buffer so that there is sufficient space to fit the
254437      ** largest possible utf-8 character.  */
254438      if( zOut>pEnd ){
254439        aFold = sqlite3_malloc64((sqlite3_int64)nFold*2);
254440        if( aFold==0 ){
254441          rc = SQLITE_NOMEM;
254442          goto tokenize_done;
254443        }
254444        zOut = &aFold[zOut - p->aFold];
254445        memcpy(aFold, p->aFold, nFold);
254446        sqlite3_free(p->aFold);
254447        p->aFold = aFold;
254448        p->nFold = nFold = nFold*2;
254449        pEnd = &aFold[nFold-6];
254450      }
254451
254452      if( *zCsr & 0x80 ){
254453        /* An non-ascii-range character. Fold it into the output buffer if
254454        ** it is a token character, or break out of the loop if it is not. */
254455        READ_UTF8(zCsr, zTerm, iCode);
254456        if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
254457 non_ascii_tokenchar:
254458          iCode = sqlite3Fts5UnicodeFold(iCode, p->eRemoveDiacritic);
254459          if( iCode ) WRITE_UTF8(zOut, iCode);
254460        }else{
254461          break;
254462        }
254463      }else if( a[*zCsr]==0 ){
254464        /* An ascii-range separator character. End of token. */
254465        break;
254466      }else{
254467 ascii_tokenchar:
254468        if( *zCsr>='A' && *zCsr<='Z' ){
254469          *zOut++ = *zCsr + 32;
254470        }else{
254471          *zOut++ = *zCsr;
254472        }
254473        zCsr++;
254474      }
254475      ie = zCsr - (unsigned char*)pText;
254476    }
254477
254478    /* Invoke the token callback */
254479    rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
254480  }
254481
254482 tokenize_done:
254483  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
254484  return rc;
254485}
254486
254487/**************************************************************************
254488** Start of porter stemmer implementation.
254489*/
254490
254491/* Any tokens larger than this (in bytes) are passed through without
254492** stemming. */
254493#define FTS5_PORTER_MAX_TOKEN 64
254494
254495typedef struct PorterTokenizer PorterTokenizer;
254496struct PorterTokenizer {
254497  fts5_tokenizer tokenizer;       /* Parent tokenizer module */
254498  Fts5Tokenizer *pTokenizer;      /* Parent tokenizer instance */
254499  char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
254500};
254501
254502/*
254503** Delete a "porter" tokenizer.
254504*/
254505static void fts5PorterDelete(Fts5Tokenizer *pTok){
254506  if( pTok ){
254507    PorterTokenizer *p = (PorterTokenizer*)pTok;
254508    if( p->pTokenizer ){
254509      p->tokenizer.xDelete(p->pTokenizer);
254510    }
254511    sqlite3_free(p);
254512  }
254513}
254514
254515/*
254516** Create a "porter" tokenizer.
254517*/
254518static int fts5PorterCreate(
254519  void *pCtx,
254520  const char **azArg, int nArg,
254521  Fts5Tokenizer **ppOut
254522){
254523  fts5_api *pApi = (fts5_api*)pCtx;
254524  int rc = SQLITE_OK;
254525  PorterTokenizer *pRet;
254526  void *pUserdata = 0;
254527  const char *zBase = "unicode61";
254528
254529  if( nArg>0 ){
254530    zBase = azArg[0];
254531  }
254532
254533  pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
254534  if( pRet ){
254535    memset(pRet, 0, sizeof(PorterTokenizer));
254536    rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
254537  }else{
254538    rc = SQLITE_NOMEM;
254539  }
254540  if( rc==SQLITE_OK ){
254541    int nArg2 = (nArg>0 ? nArg-1 : 0);
254542    const char **azArg2 = (nArg2 ? &azArg[1] : 0);
254543    rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
254544  }
254545
254546  if( rc!=SQLITE_OK ){
254547    fts5PorterDelete((Fts5Tokenizer*)pRet);
254548    pRet = 0;
254549  }
254550  *ppOut = (Fts5Tokenizer*)pRet;
254551  return rc;
254552}
254553
254554typedef struct PorterContext PorterContext;
254555struct PorterContext {
254556  void *pCtx;
254557  int (*xToken)(void*, int, const char*, int, int, int);
254558  char *aBuf;
254559};
254560
254561typedef struct PorterRule PorterRule;
254562struct PorterRule {
254563  const char *zSuffix;
254564  int nSuffix;
254565  int (*xCond)(char *zStem, int nStem);
254566  const char *zOutput;
254567  int nOutput;
254568};
254569
254570#if 0
254571static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
254572  int ret = -1;
254573  int nBuf = *pnBuf;
254574  PorterRule *p;
254575
254576  for(p=aRule; p->zSuffix; p++){
254577    assert( strlen(p->zSuffix)==p->nSuffix );
254578    assert( strlen(p->zOutput)==p->nOutput );
254579    if( nBuf<p->nSuffix ) continue;
254580    if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
254581  }
254582
254583  if( p->zSuffix ){
254584    int nStem = nBuf - p->nSuffix;
254585    if( p->xCond==0 || p->xCond(aBuf, nStem) ){
254586      memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
254587      *pnBuf = nStem + p->nOutput;
254588      ret = p - aRule;
254589    }
254590  }
254591
254592  return ret;
254593}
254594#endif
254595
254596static int fts5PorterIsVowel(char c, int bYIsVowel){
254597  return (
254598      c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
254599  );
254600}
254601
254602static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
254603  int i;
254604  int bCons = bPrevCons;
254605
254606  /* Scan for a vowel */
254607  for(i=0; i<nStem; i++){
254608    if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
254609  }
254610
254611  /* Scan for a consonent */
254612  for(i++; i<nStem; i++){
254613    if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
254614  }
254615  return 0;
254616}
254617
254618/* porter rule condition: (m > 0) */
254619static int fts5Porter_MGt0(char *zStem, int nStem){
254620  return !!fts5PorterGobbleVC(zStem, nStem, 0);
254621}
254622
254623/* porter rule condition: (m > 1) */
254624static int fts5Porter_MGt1(char *zStem, int nStem){
254625  int n;
254626  n = fts5PorterGobbleVC(zStem, nStem, 0);
254627  if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
254628    return 1;
254629  }
254630  return 0;
254631}
254632
254633/* porter rule condition: (m = 1) */
254634static int fts5Porter_MEq1(char *zStem, int nStem){
254635  int n;
254636  n = fts5PorterGobbleVC(zStem, nStem, 0);
254637  if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
254638    return 1;
254639  }
254640  return 0;
254641}
254642
254643/* porter rule condition: (*o) */
254644static int fts5Porter_Ostar(char *zStem, int nStem){
254645  if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
254646    return 0;
254647  }else{
254648    int i;
254649    int mask = 0;
254650    int bCons = 0;
254651    for(i=0; i<nStem; i++){
254652      bCons = !fts5PorterIsVowel(zStem[i], bCons);
254653      assert( bCons==0 || bCons==1 );
254654      mask = (mask << 1) + bCons;
254655    }
254656    return ((mask & 0x0007)==0x0005);
254657  }
254658}
254659
254660/* porter rule condition: (m > 1 and (*S or *T)) */
254661static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
254662  assert( nStem>0 );
254663  return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
254664      && fts5Porter_MGt1(zStem, nStem);
254665}
254666
254667/* porter rule condition: (*v*) */
254668static int fts5Porter_Vowel(char *zStem, int nStem){
254669  int i;
254670  for(i=0; i<nStem; i++){
254671    if( fts5PorterIsVowel(zStem[i], i>0) ){
254672      return 1;
254673    }
254674  }
254675  return 0;
254676}
254677
254678
254679/**************************************************************************
254680***************************************************************************
254681** GENERATED CODE STARTS HERE (mkportersteps.tcl)
254682*/
254683
254684static int fts5PorterStep4(char *aBuf, int *pnBuf){
254685  int ret = 0;
254686  int nBuf = *pnBuf;
254687  switch( aBuf[nBuf-2] ){
254688
254689    case 'a':
254690      if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
254691        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
254692          *pnBuf = nBuf - 2;
254693        }
254694      }
254695      break;
254696
254697    case 'c':
254698      if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
254699        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
254700          *pnBuf = nBuf - 4;
254701        }
254702      }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
254703        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
254704          *pnBuf = nBuf - 4;
254705        }
254706      }
254707      break;
254708
254709    case 'e':
254710      if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
254711        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
254712          *pnBuf = nBuf - 2;
254713        }
254714      }
254715      break;
254716
254717    case 'i':
254718      if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
254719        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
254720          *pnBuf = nBuf - 2;
254721        }
254722      }
254723      break;
254724
254725    case 'l':
254726      if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
254727        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
254728          *pnBuf = nBuf - 4;
254729        }
254730      }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
254731        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
254732          *pnBuf = nBuf - 4;
254733        }
254734      }
254735      break;
254736
254737    case 'n':
254738      if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
254739        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
254740          *pnBuf = nBuf - 3;
254741        }
254742      }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
254743        if( fts5Porter_MGt1(aBuf, nBuf-5) ){
254744          *pnBuf = nBuf - 5;
254745        }
254746      }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
254747        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
254748          *pnBuf = nBuf - 4;
254749        }
254750      }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
254751        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
254752          *pnBuf = nBuf - 3;
254753        }
254754      }
254755      break;
254756
254757    case 'o':
254758      if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
254759        if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
254760          *pnBuf = nBuf - 3;
254761        }
254762      }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
254763        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
254764          *pnBuf = nBuf - 2;
254765        }
254766      }
254767      break;
254768
254769    case 's':
254770      if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
254771        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
254772          *pnBuf = nBuf - 3;
254773        }
254774      }
254775      break;
254776
254777    case 't':
254778      if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
254779        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
254780          *pnBuf = nBuf - 3;
254781        }
254782      }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
254783        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
254784          *pnBuf = nBuf - 3;
254785        }
254786      }
254787      break;
254788
254789    case 'u':
254790      if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
254791        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
254792          *pnBuf = nBuf - 3;
254793        }
254794      }
254795      break;
254796
254797    case 'v':
254798      if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
254799        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
254800          *pnBuf = nBuf - 3;
254801        }
254802      }
254803      break;
254804
254805    case 'z':
254806      if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
254807        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
254808          *pnBuf = nBuf - 3;
254809        }
254810      }
254811      break;
254812
254813  }
254814  return ret;
254815}
254816
254817
254818static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
254819  int ret = 0;
254820  int nBuf = *pnBuf;
254821  switch( aBuf[nBuf-2] ){
254822
254823    case 'a':
254824      if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
254825        memcpy(&aBuf[nBuf-2], "ate", 3);
254826        *pnBuf = nBuf - 2 + 3;
254827        ret = 1;
254828      }
254829      break;
254830
254831    case 'b':
254832      if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
254833        memcpy(&aBuf[nBuf-2], "ble", 3);
254834        *pnBuf = nBuf - 2 + 3;
254835        ret = 1;
254836      }
254837      break;
254838
254839    case 'i':
254840      if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
254841        memcpy(&aBuf[nBuf-2], "ize", 3);
254842        *pnBuf = nBuf - 2 + 3;
254843        ret = 1;
254844      }
254845      break;
254846
254847  }
254848  return ret;
254849}
254850
254851
254852static int fts5PorterStep2(char *aBuf, int *pnBuf){
254853  int ret = 0;
254854  int nBuf = *pnBuf;
254855  switch( aBuf[nBuf-2] ){
254856
254857    case 'a':
254858      if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
254859        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
254860          memcpy(&aBuf[nBuf-7], "ate", 3);
254861          *pnBuf = nBuf - 7 + 3;
254862        }
254863      }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
254864        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
254865          memcpy(&aBuf[nBuf-6], "tion", 4);
254866          *pnBuf = nBuf - 6 + 4;
254867        }
254868      }
254869      break;
254870
254871    case 'c':
254872      if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
254873        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
254874          memcpy(&aBuf[nBuf-4], "ence", 4);
254875          *pnBuf = nBuf - 4 + 4;
254876        }
254877      }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
254878        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
254879          memcpy(&aBuf[nBuf-4], "ance", 4);
254880          *pnBuf = nBuf - 4 + 4;
254881        }
254882      }
254883      break;
254884
254885    case 'e':
254886      if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
254887        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
254888          memcpy(&aBuf[nBuf-4], "ize", 3);
254889          *pnBuf = nBuf - 4 + 3;
254890        }
254891      }
254892      break;
254893
254894    case 'g':
254895      if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
254896        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
254897          memcpy(&aBuf[nBuf-4], "log", 3);
254898          *pnBuf = nBuf - 4 + 3;
254899        }
254900      }
254901      break;
254902
254903    case 'l':
254904      if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
254905        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
254906          memcpy(&aBuf[nBuf-3], "ble", 3);
254907          *pnBuf = nBuf - 3 + 3;
254908        }
254909      }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
254910        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
254911          memcpy(&aBuf[nBuf-4], "al", 2);
254912          *pnBuf = nBuf - 4 + 2;
254913        }
254914      }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
254915        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
254916          memcpy(&aBuf[nBuf-5], "ent", 3);
254917          *pnBuf = nBuf - 5 + 3;
254918        }
254919      }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
254920        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
254921          memcpy(&aBuf[nBuf-3], "e", 1);
254922          *pnBuf = nBuf - 3 + 1;
254923        }
254924      }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
254925        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
254926          memcpy(&aBuf[nBuf-5], "ous", 3);
254927          *pnBuf = nBuf - 5 + 3;
254928        }
254929      }
254930      break;
254931
254932    case 'o':
254933      if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
254934        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
254935          memcpy(&aBuf[nBuf-7], "ize", 3);
254936          *pnBuf = nBuf - 7 + 3;
254937        }
254938      }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
254939        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
254940          memcpy(&aBuf[nBuf-5], "ate", 3);
254941          *pnBuf = nBuf - 5 + 3;
254942        }
254943      }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
254944        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
254945          memcpy(&aBuf[nBuf-4], "ate", 3);
254946          *pnBuf = nBuf - 4 + 3;
254947        }
254948      }
254949      break;
254950
254951    case 's':
254952      if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
254953        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
254954          memcpy(&aBuf[nBuf-5], "al", 2);
254955          *pnBuf = nBuf - 5 + 2;
254956        }
254957      }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
254958        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
254959          memcpy(&aBuf[nBuf-7], "ive", 3);
254960          *pnBuf = nBuf - 7 + 3;
254961        }
254962      }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
254963        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
254964          memcpy(&aBuf[nBuf-7], "ful", 3);
254965          *pnBuf = nBuf - 7 + 3;
254966        }
254967      }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
254968        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
254969          memcpy(&aBuf[nBuf-7], "ous", 3);
254970          *pnBuf = nBuf - 7 + 3;
254971        }
254972      }
254973      break;
254974
254975    case 't':
254976      if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
254977        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
254978          memcpy(&aBuf[nBuf-5], "al", 2);
254979          *pnBuf = nBuf - 5 + 2;
254980        }
254981      }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
254982        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
254983          memcpy(&aBuf[nBuf-5], "ive", 3);
254984          *pnBuf = nBuf - 5 + 3;
254985        }
254986      }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
254987        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
254988          memcpy(&aBuf[nBuf-6], "ble", 3);
254989          *pnBuf = nBuf - 6 + 3;
254990        }
254991      }
254992      break;
254993
254994  }
254995  return ret;
254996}
254997
254998
254999static int fts5PorterStep3(char *aBuf, int *pnBuf){
255000  int ret = 0;
255001  int nBuf = *pnBuf;
255002  switch( aBuf[nBuf-2] ){
255003
255004    case 'a':
255005      if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
255006        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
255007          memcpy(&aBuf[nBuf-4], "ic", 2);
255008          *pnBuf = nBuf - 4 + 2;
255009        }
255010      }
255011      break;
255012
255013    case 's':
255014      if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
255015        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
255016          *pnBuf = nBuf - 4;
255017        }
255018      }
255019      break;
255020
255021    case 't':
255022      if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
255023        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
255024          memcpy(&aBuf[nBuf-5], "ic", 2);
255025          *pnBuf = nBuf - 5 + 2;
255026        }
255027      }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
255028        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
255029          memcpy(&aBuf[nBuf-5], "ic", 2);
255030          *pnBuf = nBuf - 5 + 2;
255031        }
255032      }
255033      break;
255034
255035    case 'u':
255036      if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
255037        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
255038          *pnBuf = nBuf - 3;
255039        }
255040      }
255041      break;
255042
255043    case 'v':
255044      if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
255045        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
255046          *pnBuf = nBuf - 5;
255047        }
255048      }
255049      break;
255050
255051    case 'z':
255052      if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
255053        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
255054          memcpy(&aBuf[nBuf-5], "al", 2);
255055          *pnBuf = nBuf - 5 + 2;
255056        }
255057      }
255058      break;
255059
255060  }
255061  return ret;
255062}
255063
255064
255065static int fts5PorterStep1B(char *aBuf, int *pnBuf){
255066  int ret = 0;
255067  int nBuf = *pnBuf;
255068  switch( aBuf[nBuf-2] ){
255069
255070    case 'e':
255071      if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
255072        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
255073          memcpy(&aBuf[nBuf-3], "ee", 2);
255074          *pnBuf = nBuf - 3 + 2;
255075        }
255076      }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
255077        if( fts5Porter_Vowel(aBuf, nBuf-2) ){
255078          *pnBuf = nBuf - 2;
255079          ret = 1;
255080        }
255081      }
255082      break;
255083
255084    case 'n':
255085      if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
255086        if( fts5Porter_Vowel(aBuf, nBuf-3) ){
255087          *pnBuf = nBuf - 3;
255088          ret = 1;
255089        }
255090      }
255091      break;
255092
255093  }
255094  return ret;
255095}
255096
255097/*
255098** GENERATED CODE ENDS HERE (mkportersteps.tcl)
255099***************************************************************************
255100**************************************************************************/
255101
255102static void fts5PorterStep1A(char *aBuf, int *pnBuf){
255103  int nBuf = *pnBuf;
255104  if( aBuf[nBuf-1]=='s' ){
255105    if( aBuf[nBuf-2]=='e' ){
255106      if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
255107       || (nBuf>3 && aBuf[nBuf-3]=='i' )
255108      ){
255109        *pnBuf = nBuf-2;
255110      }else{
255111        *pnBuf = nBuf-1;
255112      }
255113    }
255114    else if( aBuf[nBuf-2]!='s' ){
255115      *pnBuf = nBuf-1;
255116    }
255117  }
255118}
255119
255120static int fts5PorterCb(
255121  void *pCtx,
255122  int tflags,
255123  const char *pToken,
255124  int nToken,
255125  int iStart,
255126  int iEnd
255127){
255128  PorterContext *p = (PorterContext*)pCtx;
255129
255130  char *aBuf;
255131  int nBuf;
255132
255133  if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
255134  aBuf = p->aBuf;
255135  nBuf = nToken;
255136  memcpy(aBuf, pToken, nBuf);
255137
255138  /* Step 1. */
255139  fts5PorterStep1A(aBuf, &nBuf);
255140  if( fts5PorterStep1B(aBuf, &nBuf) ){
255141    if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
255142      char c = aBuf[nBuf-1];
255143      if( fts5PorterIsVowel(c, 0)==0
255144       && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
255145      ){
255146        nBuf--;
255147      }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
255148        aBuf[nBuf++] = 'e';
255149      }
255150    }
255151  }
255152
255153  /* Step 1C. */
255154  if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
255155    aBuf[nBuf-1] = 'i';
255156  }
255157
255158  /* Steps 2 through 4. */
255159  fts5PorterStep2(aBuf, &nBuf);
255160  fts5PorterStep3(aBuf, &nBuf);
255161  fts5PorterStep4(aBuf, &nBuf);
255162
255163  /* Step 5a. */
255164  assert( nBuf>0 );
255165  if( aBuf[nBuf-1]=='e' ){
255166    if( fts5Porter_MGt1(aBuf, nBuf-1)
255167     || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
255168    ){
255169      nBuf--;
255170    }
255171  }
255172
255173  /* Step 5b. */
255174  if( nBuf>1 && aBuf[nBuf-1]=='l'
255175   && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
255176  ){
255177    nBuf--;
255178  }
255179
255180  return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
255181
255182 pass_through:
255183  return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
255184}
255185
255186/*
255187** Tokenize using the porter tokenizer.
255188*/
255189static int fts5PorterTokenize(
255190  Fts5Tokenizer *pTokenizer,
255191  void *pCtx,
255192  int flags,
255193  const char *pText, int nText,
255194  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
255195){
255196  PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
255197  PorterContext sCtx;
255198  sCtx.xToken = xToken;
255199  sCtx.pCtx = pCtx;
255200  sCtx.aBuf = p->aBuf;
255201  return p->tokenizer.xTokenize(
255202      p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
255203  );
255204}
255205
255206/**************************************************************************
255207** Start of trigram implementation.
255208*/
255209typedef struct TrigramTokenizer TrigramTokenizer;
255210struct TrigramTokenizer {
255211  int bFold;                      /* True to fold to lower-case */
255212  int iFoldParam;                 /* Parameter to pass to Fts5UnicodeFold() */
255213};
255214
255215/*
255216** Free a trigram tokenizer.
255217*/
255218static void fts5TriDelete(Fts5Tokenizer *p){
255219  sqlite3_free(p);
255220}
255221
255222/*
255223** Allocate a trigram tokenizer.
255224*/
255225static int fts5TriCreate(
255226  void *pUnused,
255227  const char **azArg,
255228  int nArg,
255229  Fts5Tokenizer **ppOut
255230){
255231  int rc = SQLITE_OK;
255232  TrigramTokenizer *pNew = (TrigramTokenizer*)sqlite3_malloc(sizeof(*pNew));
255233  UNUSED_PARAM(pUnused);
255234  if( pNew==0 ){
255235    rc = SQLITE_NOMEM;
255236  }else{
255237    int i;
255238    pNew->bFold = 1;
255239    pNew->iFoldParam = 0;
255240    for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
255241      const char *zArg = azArg[i+1];
255242      if( 0==sqlite3_stricmp(azArg[i], "case_sensitive") ){
255243        if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
255244          rc = SQLITE_ERROR;
255245        }else{
255246          pNew->bFold = (zArg[0]=='0');
255247        }
255248      }else if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
255249        if( (zArg[0]!='0' && zArg[0]!='1' && zArg[0]!='2') || zArg[1] ){
255250          rc = SQLITE_ERROR;
255251        }else{
255252          pNew->iFoldParam = (zArg[0]!='0') ? 2 : 0;
255253        }
255254      }else{
255255        rc = SQLITE_ERROR;
255256      }
255257    }
255258
255259    if( pNew->iFoldParam!=0 && pNew->bFold==0 ){
255260      rc = SQLITE_ERROR;
255261    }
255262
255263    if( rc!=SQLITE_OK ){
255264      fts5TriDelete((Fts5Tokenizer*)pNew);
255265      pNew = 0;
255266    }
255267  }
255268  *ppOut = (Fts5Tokenizer*)pNew;
255269  return rc;
255270}
255271
255272/*
255273** Trigram tokenizer tokenize routine.
255274*/
255275static int fts5TriTokenize(
255276  Fts5Tokenizer *pTok,
255277  void *pCtx,
255278  int unusedFlags,
255279  const char *pText, int nText,
255280  int (*xToken)(void*, int, const char*, int, int, int)
255281){
255282  TrigramTokenizer *p = (TrigramTokenizer*)pTok;
255283  int rc = SQLITE_OK;
255284  char aBuf[32];
255285  char *zOut = aBuf;
255286  int ii;
255287  const unsigned char *zIn = (const unsigned char*)pText;
255288  const unsigned char *zEof = &zIn[nText];
255289  u32 iCode;
255290  int aStart[3];                  /* Input offset of each character in aBuf[] */
255291
255292  UNUSED_PARAM(unusedFlags);
255293
255294  /* Populate aBuf[] with the characters for the first trigram. */
255295  for(ii=0; ii<3; ii++){
255296    do {
255297      aStart[ii] = zIn - (const unsigned char*)pText;
255298      READ_UTF8(zIn, zEof, iCode);
255299      if( iCode==0 ) return SQLITE_OK;
255300      if( p->bFold ) iCode = sqlite3Fts5UnicodeFold(iCode, p->iFoldParam);
255301    }while( iCode==0 );
255302    WRITE_UTF8(zOut, iCode);
255303  }
255304
255305  /* At the start of each iteration of this loop:
255306  **
255307  **  aBuf:      Contains 3 characters. The 3 characters of the next trigram.
255308  **  zOut:      Points to the byte following the last character in aBuf.
255309  **  aStart[3]: Contains the byte offset in the input text corresponding
255310  **             to the start of each of the three characters in the buffer.
255311  */
255312  assert( zIn<=zEof );
255313  while( 1 ){
255314    int iNext;                    /* Start of character following current tri */
255315    const char *z1;
255316
255317    /* Read characters from the input up until the first non-diacritic */
255318    do {
255319      iNext = zIn - (const unsigned char*)pText;
255320      READ_UTF8(zIn, zEof, iCode);
255321      if( iCode==0 ) break;
255322      if( p->bFold ) iCode = sqlite3Fts5UnicodeFold(iCode, p->iFoldParam);
255323    }while( iCode==0 );
255324
255325    /* Pass the current trigram back to fts5 */
255326    rc = xToken(pCtx, 0, aBuf, zOut-aBuf, aStart[0], iNext);
255327    if( iCode==0 || rc!=SQLITE_OK ) break;
255328
255329    /* Remove the first character from buffer aBuf[]. Append the character
255330    ** with codepoint iCode.  */
255331    z1 = aBuf;
255332    FTS5_SKIP_UTF8(z1);
255333    memmove(aBuf, z1, zOut - z1);
255334    zOut -= (z1 - aBuf);
255335    WRITE_UTF8(zOut, iCode);
255336
255337    /* Update the aStart[] array */
255338    aStart[0] = aStart[1];
255339    aStart[1] = aStart[2];
255340    aStart[2] = iNext;
255341  }
255342
255343  return rc;
255344}
255345
255346/*
255347** Argument xCreate is a pointer to a constructor function for a tokenizer.
255348** pTok is a tokenizer previously created using the same method. This function
255349** returns one of FTS5_PATTERN_NONE, FTS5_PATTERN_LIKE or FTS5_PATTERN_GLOB
255350** indicating the style of pattern matching that the tokenizer can support.
255351** In practice, this is:
255352**
255353**     "trigram" tokenizer, case_sensitive=1 - FTS5_PATTERN_GLOB
255354**     "trigram" tokenizer, case_sensitive=0 (the default) - FTS5_PATTERN_LIKE
255355**     all other tokenizers - FTS5_PATTERN_NONE
255356*/
255357static int sqlite3Fts5TokenizerPattern(
255358    int (*xCreate)(void*, const char**, int, Fts5Tokenizer**),
255359    Fts5Tokenizer *pTok
255360){
255361  if( xCreate==fts5TriCreate ){
255362    TrigramTokenizer *p = (TrigramTokenizer*)pTok;
255363    if( p->iFoldParam==0 ){
255364      return p->bFold ? FTS5_PATTERN_LIKE : FTS5_PATTERN_GLOB;
255365    }
255366  }
255367  return FTS5_PATTERN_NONE;
255368}
255369
255370/*
255371** Register all built-in tokenizers with FTS5.
255372*/
255373static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
255374  struct BuiltinTokenizer {
255375    const char *zName;
255376    fts5_tokenizer x;
255377  } aBuiltin[] = {
255378    { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
255379    { "ascii",     {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
255380    { "porter",    {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
255381    { "trigram",   {fts5TriCreate, fts5TriDelete, fts5TriTokenize}},
255382  };
255383
255384  int rc = SQLITE_OK;             /* Return code */
255385  int i;                          /* To iterate through builtin functions */
255386
255387  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
255388    rc = pApi->xCreateTokenizer(pApi,
255389        aBuiltin[i].zName,
255390        (void*)pApi,
255391        &aBuiltin[i].x,
255392        0
255393    );
255394  }
255395
255396  return rc;
255397}
255398
255399/*
255400** 2012-05-25
255401**
255402** The author disclaims copyright to this source code.  In place of
255403** a legal notice, here is a blessing:
255404**
255405**    May you do good and not evil.
255406**    May you find forgiveness for yourself and forgive others.
255407**    May you share freely, never taking more than you give.
255408**
255409******************************************************************************
255410*/
255411
255412/*
255413** DO NOT EDIT THIS MACHINE GENERATED FILE.
255414*/
255415
255416
255417/* #include <assert.h> */
255418
255419
255420
255421/*
255422** If the argument is a codepoint corresponding to a lowercase letter
255423** in the ASCII range with a diacritic added, return the codepoint
255424** of the ASCII letter only. For example, if passed 235 - "LATIN
255425** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
255426** E"). The resuls of passing a codepoint that corresponds to an
255427** uppercase letter are undefined.
255428*/
255429static int fts5_remove_diacritic(int c, int bComplex){
255430  unsigned short aDia[] = {
255431        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
255432     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
255433     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
255434     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
255435     3456,  3696,  3712,  3728,  3744,  3766,  3832,  3896,
255436     3912,  3928,  3944,  3968,  4008,  4040,  4056,  4106,
255437     4138,  4170,  4202,  4234,  4266,  4296,  4312,  4344,
255438     4408,  4424,  4442,  4472,  4488,  4504,  6148,  6198,
255439     6264,  6280,  6360,  6429,  6505,  6529, 61448, 61468,
255440    61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704,
255441    61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914,
255442    61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218,
255443    62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554,
255444    62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766,
255445    62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118,
255446    63182, 63242, 63274, 63310, 63368, 63390,
255447  };
255448#define HIBIT ((unsigned char)0x80)
255449  unsigned char aChar[] = {
255450    '\0',      'a',       'c',       'e',       'i',       'n',
255451    'o',       'u',       'y',       'y',       'a',       'c',
255452    'd',       'e',       'e',       'g',       'h',       'i',
255453    'j',       'k',       'l',       'n',       'o',       'r',
255454    's',       't',       'u',       'u',       'w',       'y',
255455    'z',       'o',       'u',       'a',       'i',       'o',
255456    'u',       'u'|HIBIT, 'a'|HIBIT, 'g',       'k',       'o',
255457    'o'|HIBIT, 'j',       'g',       'n',       'a'|HIBIT, 'a',
255458    'e',       'i',       'o',       'r',       'u',       's',
255459    't',       'h',       'a',       'e',       'o'|HIBIT, 'o',
255460    'o'|HIBIT, 'y',       '\0',      '\0',      '\0',      '\0',
255461    '\0',      '\0',      '\0',      '\0',      'a',       'b',
255462    'c'|HIBIT, 'd',       'd',       'e'|HIBIT, 'e',       'e'|HIBIT,
255463    'f',       'g',       'h',       'h',       'i',       'i'|HIBIT,
255464    'k',       'l',       'l'|HIBIT, 'l',       'm',       'n',
255465    'o'|HIBIT, 'p',       'r',       'r'|HIBIT, 'r',       's',
255466    's'|HIBIT, 't',       'u',       'u'|HIBIT, 'v',       'w',
255467    'w',       'x',       'y',       'z',       'h',       't',
255468    'w',       'y',       'a',       'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT,
255469    'e',       'e'|HIBIT, 'e'|HIBIT, 'i',       'o',       'o'|HIBIT,
255470    'o'|HIBIT, 'o'|HIBIT, 'u',       'u'|HIBIT, 'u'|HIBIT, 'y',
255471  };
255472
255473  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
255474  int iRes = 0;
255475  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
255476  int iLo = 0;
255477  while( iHi>=iLo ){
255478    int iTest = (iHi + iLo) / 2;
255479    if( key >= aDia[iTest] ){
255480      iRes = iTest;
255481      iLo = iTest+1;
255482    }else{
255483      iHi = iTest-1;
255484    }
255485  }
255486  assert( key>=aDia[iRes] );
255487  if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;
255488  return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);
255489}
255490
255491
255492/*
255493** Return true if the argument interpreted as a unicode codepoint
255494** is a diacritical modifier character.
255495*/
255496static int sqlite3Fts5UnicodeIsdiacritic(int c){
255497  unsigned int mask0 = 0x08029FDF;
255498  unsigned int mask1 = 0x000361F8;
255499  if( c<768 || c>817 ) return 0;
255500  return (c < 768+32) ?
255501      (mask0 & ((unsigned int)1 << (c-768))) :
255502      (mask1 & ((unsigned int)1 << (c-768-32)));
255503}
255504
255505
255506/*
255507** Interpret the argument as a unicode codepoint. If the codepoint
255508** is an upper case character that has a lower case equivalent,
255509** return the codepoint corresponding to the lower case version.
255510** Otherwise, return a copy of the argument.
255511**
255512** The results are undefined if the value passed to this function
255513** is less than zero.
255514*/
255515static int sqlite3Fts5UnicodeFold(int c, int eRemoveDiacritic){
255516  /* Each entry in the following array defines a rule for folding a range
255517  ** of codepoints to lower case. The rule applies to a range of nRange
255518  ** codepoints starting at codepoint iCode.
255519  **
255520  ** If the least significant bit in flags is clear, then the rule applies
255521  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
255522  ** need to be folded). Or, if it is set, then the rule only applies to
255523  ** every second codepoint in the range, starting with codepoint C.
255524  **
255525  ** The 7 most significant bits in flags are an index into the aiOff[]
255526  ** array. If a specific codepoint C does require folding, then its lower
255527  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
255528  **
255529  ** The contents of this array are generated by parsing the CaseFolding.txt
255530  ** file distributed as part of the "Unicode Character Database". See
255531  ** http://www.unicode.org for details.
255532  */
255533  static const struct TableEntry {
255534    unsigned short iCode;
255535    unsigned char flags;
255536    unsigned char nRange;
255537  } aEntry[] = {
255538    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
255539    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
255540    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
255541    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
255542    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
255543    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
255544    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
255545    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
255546    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
255547    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
255548    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
255549    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
255550    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
255551    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
255552    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
255553    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
255554    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
255555    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
255556    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
255557    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
255558    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
255559    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
255560    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
255561    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
255562    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
255563    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
255564    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
255565    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
255566    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
255567    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
255568    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
255569    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
255570    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
255571    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
255572    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
255573    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
255574    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
255575    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
255576    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
255577    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
255578    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
255579    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
255580    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
255581    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
255582    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
255583    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
255584    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
255585    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
255586    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
255587    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
255588    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
255589    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
255590    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
255591    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
255592    {65313, 14, 26},
255593  };
255594  static const unsigned short aiOff[] = {
255595   1,     2,     8,     15,    16,    26,    28,    32,
255596   37,    38,    40,    48,    63,    64,    69,    71,
255597   79,    80,    116,   202,   203,   205,   206,   207,
255598   209,   210,   211,   213,   214,   217,   218,   219,
255599   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
255600   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
255601   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
255602   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
255603   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
255604   65514, 65521, 65527, 65528, 65529,
255605  };
255606
255607  int ret = c;
255608
255609  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
255610
255611  if( c<128 ){
255612    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
255613  }else if( c<65536 ){
255614    const struct TableEntry *p;
255615    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
255616    int iLo = 0;
255617    int iRes = -1;
255618
255619    assert( c>aEntry[0].iCode );
255620    while( iHi>=iLo ){
255621      int iTest = (iHi + iLo) / 2;
255622      int cmp = (c - aEntry[iTest].iCode);
255623      if( cmp>=0 ){
255624        iRes = iTest;
255625        iLo = iTest+1;
255626      }else{
255627        iHi = iTest-1;
255628      }
255629    }
255630
255631    assert( iRes>=0 && c>=aEntry[iRes].iCode );
255632    p = &aEntry[iRes];
255633    if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
255634      ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
255635      assert( ret>0 );
255636    }
255637
255638    if( eRemoveDiacritic ){
255639      ret = fts5_remove_diacritic(ret, eRemoveDiacritic==2);
255640    }
255641  }
255642
255643  else if( c>=66560 && c<66600 ){
255644    ret = c + 40;
255645  }
255646
255647  return ret;
255648}
255649
255650
255651static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
255652  aArray[0] = 1;
255653  switch( zCat[0] ){
255654    case 'C':
255655          switch( zCat[1] ){
255656            case 'c': aArray[1] = 1; break;
255657            case 'f': aArray[2] = 1; break;
255658            case 'n': aArray[3] = 1; break;
255659            case 's': aArray[4] = 1; break;
255660            case 'o': aArray[31] = 1; break;
255661            case '*':
255662              aArray[1] = 1;
255663              aArray[2] = 1;
255664              aArray[3] = 1;
255665              aArray[4] = 1;
255666              aArray[31] = 1;
255667              break;
255668            default: return 1;          }
255669          break;
255670
255671    case 'L':
255672          switch( zCat[1] ){
255673            case 'l': aArray[5] = 1; break;
255674            case 'm': aArray[6] = 1; break;
255675            case 'o': aArray[7] = 1; break;
255676            case 't': aArray[8] = 1; break;
255677            case 'u': aArray[9] = 1; break;
255678            case 'C': aArray[30] = 1; break;
255679            case '*':
255680              aArray[5] = 1;
255681              aArray[6] = 1;
255682              aArray[7] = 1;
255683              aArray[8] = 1;
255684              aArray[9] = 1;
255685              aArray[30] = 1;
255686              break;
255687            default: return 1;          }
255688          break;
255689
255690    case 'M':
255691          switch( zCat[1] ){
255692            case 'c': aArray[10] = 1; break;
255693            case 'e': aArray[11] = 1; break;
255694            case 'n': aArray[12] = 1; break;
255695            case '*':
255696              aArray[10] = 1;
255697              aArray[11] = 1;
255698              aArray[12] = 1;
255699              break;
255700            default: return 1;          }
255701          break;
255702
255703    case 'N':
255704          switch( zCat[1] ){
255705            case 'd': aArray[13] = 1; break;
255706            case 'l': aArray[14] = 1; break;
255707            case 'o': aArray[15] = 1; break;
255708            case '*':
255709              aArray[13] = 1;
255710              aArray[14] = 1;
255711              aArray[15] = 1;
255712              break;
255713            default: return 1;          }
255714          break;
255715
255716    case 'P':
255717          switch( zCat[1] ){
255718            case 'c': aArray[16] = 1; break;
255719            case 'd': aArray[17] = 1; break;
255720            case 'e': aArray[18] = 1; break;
255721            case 'f': aArray[19] = 1; break;
255722            case 'i': aArray[20] = 1; break;
255723            case 'o': aArray[21] = 1; break;
255724            case 's': aArray[22] = 1; break;
255725            case '*':
255726              aArray[16] = 1;
255727              aArray[17] = 1;
255728              aArray[18] = 1;
255729              aArray[19] = 1;
255730              aArray[20] = 1;
255731              aArray[21] = 1;
255732              aArray[22] = 1;
255733              break;
255734            default: return 1;          }
255735          break;
255736
255737    case 'S':
255738          switch( zCat[1] ){
255739            case 'c': aArray[23] = 1; break;
255740            case 'k': aArray[24] = 1; break;
255741            case 'm': aArray[25] = 1; break;
255742            case 'o': aArray[26] = 1; break;
255743            case '*':
255744              aArray[23] = 1;
255745              aArray[24] = 1;
255746              aArray[25] = 1;
255747              aArray[26] = 1;
255748              break;
255749            default: return 1;          }
255750          break;
255751
255752    case 'Z':
255753          switch( zCat[1] ){
255754            case 'l': aArray[27] = 1; break;
255755            case 'p': aArray[28] = 1; break;
255756            case 's': aArray[29] = 1; break;
255757            case '*':
255758              aArray[27] = 1;
255759              aArray[28] = 1;
255760              aArray[29] = 1;
255761              break;
255762            default: return 1;          }
255763          break;
255764
255765  }
255766  return 0;
255767}
255768
255769static u16 aFts5UnicodeBlock[] = {
255770    0,     1471,  1753,  1760,  1760,  1760,  1760,  1760,  1760,  1760,
255771    1760,  1760,  1760,  1760,  1760,  1763,  1765,
255772  };
255773static u16 aFts5UnicodeMap[] = {
255774    0,     32,    33,    36,    37,    40,    41,    42,    43,    44,
255775    45,    46,    48,    58,    60,    63,    65,    91,    92,    93,
255776    94,    95,    96,    97,    123,   124,   125,   126,   127,   160,
255777    161,   162,   166,   167,   168,   169,   170,   171,   172,   173,
255778    174,   175,   176,   177,   178,   180,   181,   182,   184,   185,
255779    186,   187,   188,   191,   192,   215,   216,   223,   247,   248,
255780    256,   312,   313,   329,   330,   377,   383,   385,   387,   388,
255781    391,   394,   396,   398,   402,   403,   405,   406,   409,   412,
255782    414,   415,   417,   418,   423,   427,   428,   431,   434,   436,
255783    437,   440,   442,   443,   444,   446,   448,   452,   453,   454,
255784    455,   456,   457,   458,   459,   460,   461,   477,   478,   496,
255785    497,   498,   499,   500,   503,   505,   506,   564,   570,   572,
255786    573,   575,   577,   580,   583,   584,   592,   660,   661,   688,
255787    706,   710,   722,   736,   741,   748,   749,   750,   751,   768,
255788    880,   884,   885,   886,   890,   891,   894,   900,   902,   903,
255789    904,   908,   910,   912,   913,   931,   940,   975,   977,   978,
255790    981,   984,   1008,  1012,  1014,  1015,  1018,  1020,  1021,  1072,
255791    1120,  1154,  1155,  1160,  1162,  1217,  1231,  1232,  1329,  1369,
255792    1370,  1377,  1417,  1418,  1423,  1425,  1470,  1471,  1472,  1473,
255793    1475,  1476,  1478,  1479,  1488,  1520,  1523,  1536,  1542,  1545,
255794    1547,  1548,  1550,  1552,  1563,  1566,  1568,  1600,  1601,  1611,
255795    1632,  1642,  1646,  1648,  1649,  1748,  1749,  1750,  1757,  1758,
255796    1759,  1765,  1767,  1769,  1770,  1774,  1776,  1786,  1789,  1791,
255797    1792,  1807,  1808,  1809,  1810,  1840,  1869,  1958,  1969,  1984,
255798    1994,  2027,  2036,  2038,  2039,  2042,  2048,  2070,  2074,  2075,
255799    2084,  2085,  2088,  2089,  2096,  2112,  2137,  2142,  2208,  2210,
255800    2276,  2304,  2307,  2308,  2362,  2363,  2364,  2365,  2366,  2369,
255801    2377,  2381,  2382,  2384,  2385,  2392,  2402,  2404,  2406,  2416,
255802    2417,  2418,  2425,  2433,  2434,  2437,  2447,  2451,  2474,  2482,
255803    2486,  2492,  2493,  2494,  2497,  2503,  2507,  2509,  2510,  2519,
255804    2524,  2527,  2530,  2534,  2544,  2546,  2548,  2554,  2555,  2561,
255805    2563,  2565,  2575,  2579,  2602,  2610,  2613,  2616,  2620,  2622,
255806    2625,  2631,  2635,  2641,  2649,  2654,  2662,  2672,  2674,  2677,
255807    2689,  2691,  2693,  2703,  2707,  2730,  2738,  2741,  2748,  2749,
255808    2750,  2753,  2759,  2761,  2763,  2765,  2768,  2784,  2786,  2790,
255809    2800,  2801,  2817,  2818,  2821,  2831,  2835,  2858,  2866,  2869,
255810    2876,  2877,  2878,  2879,  2880,  2881,  2887,  2891,  2893,  2902,
255811    2903,  2908,  2911,  2914,  2918,  2928,  2929,  2930,  2946,  2947,
255812    2949,  2958,  2962,  2969,  2972,  2974,  2979,  2984,  2990,  3006,
255813    3008,  3009,  3014,  3018,  3021,  3024,  3031,  3046,  3056,  3059,
255814    3065,  3066,  3073,  3077,  3086,  3090,  3114,  3125,  3133,  3134,
255815    3137,  3142,  3146,  3157,  3160,  3168,  3170,  3174,  3192,  3199,
255816    3202,  3205,  3214,  3218,  3242,  3253,  3260,  3261,  3262,  3263,
255817    3264,  3270,  3271,  3274,  3276,  3285,  3294,  3296,  3298,  3302,
255818    3313,  3330,  3333,  3342,  3346,  3389,  3390,  3393,  3398,  3402,
255819    3405,  3406,  3415,  3424,  3426,  3430,  3440,  3449,  3450,  3458,
255820    3461,  3482,  3507,  3517,  3520,  3530,  3535,  3538,  3542,  3544,
255821    3570,  3572,  3585,  3633,  3634,  3636,  3647,  3648,  3654,  3655,
255822    3663,  3664,  3674,  3713,  3716,  3719,  3722,  3725,  3732,  3737,
255823    3745,  3749,  3751,  3754,  3757,  3761,  3762,  3764,  3771,  3773,
255824    3776,  3782,  3784,  3792,  3804,  3840,  3841,  3844,  3859,  3860,
255825    3861,  3864,  3866,  3872,  3882,  3892,  3893,  3894,  3895,  3896,
255826    3897,  3898,  3899,  3900,  3901,  3902,  3904,  3913,  3953,  3967,
255827    3968,  3973,  3974,  3976,  3981,  3993,  4030,  4038,  4039,  4046,
255828    4048,  4053,  4057,  4096,  4139,  4141,  4145,  4146,  4152,  4153,
255829    4155,  4157,  4159,  4160,  4170,  4176,  4182,  4184,  4186,  4190,
255830    4193,  4194,  4197,  4199,  4206,  4209,  4213,  4226,  4227,  4229,
255831    4231,  4237,  4238,  4239,  4240,  4250,  4253,  4254,  4256,  4295,
255832    4301,  4304,  4347,  4348,  4349,  4682,  4688,  4696,  4698,  4704,
255833    4746,  4752,  4786,  4792,  4800,  4802,  4808,  4824,  4882,  4888,
255834    4957,  4960,  4969,  4992,  5008,  5024,  5120,  5121,  5741,  5743,
255835    5760,  5761,  5787,  5788,  5792,  5867,  5870,  5888,  5902,  5906,
255836    5920,  5938,  5941,  5952,  5970,  5984,  5998,  6002,  6016,  6068,
255837    6070,  6071,  6078,  6086,  6087,  6089,  6100,  6103,  6104,  6107,
255838    6108,  6109,  6112,  6128,  6144,  6150,  6151,  6155,  6158,  6160,
255839    6176,  6211,  6212,  6272,  6313,  6314,  6320,  6400,  6432,  6435,
255840    6439,  6441,  6448,  6450,  6451,  6457,  6464,  6468,  6470,  6480,
255841    6512,  6528,  6576,  6593,  6600,  6608,  6618,  6622,  6656,  6679,
255842    6681,  6686,  6688,  6741,  6742,  6743,  6744,  6752,  6753,  6754,
255843    6755,  6757,  6765,  6771,  6783,  6784,  6800,  6816,  6823,  6824,
255844    6912,  6916,  6917,  6964,  6965,  6966,  6971,  6972,  6973,  6978,
255845    6979,  6981,  6992,  7002,  7009,  7019,  7028,  7040,  7042,  7043,
255846    7073,  7074,  7078,  7080,  7082,  7083,  7084,  7086,  7088,  7098,
255847    7142,  7143,  7144,  7146,  7149,  7150,  7151,  7154,  7164,  7168,
255848    7204,  7212,  7220,  7222,  7227,  7232,  7245,  7248,  7258,  7288,
255849    7294,  7360,  7376,  7379,  7380,  7393,  7394,  7401,  7405,  7406,
255850    7410,  7412,  7413,  7424,  7468,  7531,  7544,  7545,  7579,  7616,
255851    7676,  7680,  7830,  7838,  7936,  7944,  7952,  7960,  7968,  7976,
255852    7984,  7992,  8000,  8008,  8016,  8025,  8027,  8029,  8031,  8033,
255853    8040,  8048,  8064,  8072,  8080,  8088,  8096,  8104,  8112,  8118,
255854    8120,  8124,  8125,  8126,  8127,  8130,  8134,  8136,  8140,  8141,
255855    8144,  8150,  8152,  8157,  8160,  8168,  8173,  8178,  8182,  8184,
255856    8188,  8189,  8192,  8203,  8208,  8214,  8216,  8217,  8218,  8219,
255857    8221,  8222,  8223,  8224,  8232,  8233,  8234,  8239,  8240,  8249,
255858    8250,  8251,  8255,  8257,  8260,  8261,  8262,  8263,  8274,  8275,
255859    8276,  8277,  8287,  8288,  8298,  8304,  8305,  8308,  8314,  8317,
255860    8318,  8319,  8320,  8330,  8333,  8334,  8336,  8352,  8400,  8413,
255861    8417,  8418,  8421,  8448,  8450,  8451,  8455,  8456,  8458,  8459,
255862    8462,  8464,  8467,  8468,  8469,  8470,  8472,  8473,  8478,  8484,
255863    8485,  8486,  8487,  8488,  8489,  8490,  8494,  8495,  8496,  8500,
255864    8501,  8505,  8506,  8508,  8510,  8512,  8517,  8519,  8522,  8523,
255865    8524,  8526,  8527,  8528,  8544,  8579,  8581,  8585,  8592,  8597,
255866    8602,  8604,  8608,  8609,  8611,  8612,  8614,  8615,  8622,  8623,
255867    8654,  8656,  8658,  8659,  8660,  8661,  8692,  8960,  8968,  8972,
255868    8992,  8994,  9001,  9002,  9003,  9084,  9085,  9115,  9140,  9180,
255869    9186,  9216,  9280,  9312,  9372,  9450,  9472,  9655,  9656,  9665,
255870    9666,  9720,  9728,  9839,  9840,  9985,  10088, 10089, 10090, 10091,
255871    10092, 10093, 10094, 10095, 10096, 10097, 10098, 10099, 10100, 10101,
255872    10102, 10132, 10176, 10181, 10182, 10183, 10214, 10215, 10216, 10217,
255873    10218, 10219, 10220, 10221, 10222, 10223, 10224, 10240, 10496, 10627,
255874    10628, 10629, 10630, 10631, 10632, 10633, 10634, 10635, 10636, 10637,
255875    10638, 10639, 10640, 10641, 10642, 10643, 10644, 10645, 10646, 10647,
255876    10648, 10649, 10712, 10713, 10714, 10715, 10716, 10748, 10749, 10750,
255877    11008, 11056, 11077, 11079, 11088, 11264, 11312, 11360, 11363, 11365,
255878    11367, 11374, 11377, 11378, 11380, 11381, 11383, 11388, 11390, 11393,
255879    11394, 11492, 11493, 11499, 11503, 11506, 11513, 11517, 11518, 11520,
255880    11559, 11565, 11568, 11631, 11632, 11647, 11648, 11680, 11688, 11696,
255881    11704, 11712, 11720, 11728, 11736, 11744, 11776, 11778, 11779, 11780,
255882    11781, 11782, 11785, 11786, 11787, 11788, 11789, 11790, 11799, 11800,
255883    11802, 11803, 11804, 11805, 11806, 11808, 11809, 11810, 11811, 11812,
255884    11813, 11814, 11815, 11816, 11817, 11818, 11823, 11824, 11834, 11904,
255885    11931, 12032, 12272, 12288, 12289, 12292, 12293, 12294, 12295, 12296,
255886    12297, 12298, 12299, 12300, 12301, 12302, 12303, 12304, 12305, 12306,
255887    12308, 12309, 12310, 12311, 12312, 12313, 12314, 12315, 12316, 12317,
255888    12318, 12320, 12321, 12330, 12334, 12336, 12337, 12342, 12344, 12347,
255889    12348, 12349, 12350, 12353, 12441, 12443, 12445, 12447, 12448, 12449,
255890    12539, 12540, 12543, 12549, 12593, 12688, 12690, 12694, 12704, 12736,
255891    12784, 12800, 12832, 12842, 12872, 12880, 12881, 12896, 12928, 12938,
255892    12977, 12992, 13056, 13312, 19893, 19904, 19968, 40908, 40960, 40981,
255893    40982, 42128, 42192, 42232, 42238, 42240, 42508, 42509, 42512, 42528,
255894    42538, 42560, 42606, 42607, 42608, 42611, 42612, 42622, 42623, 42624,
255895    42655, 42656, 42726, 42736, 42738, 42752, 42775, 42784, 42786, 42800,
255896    42802, 42864, 42865, 42873, 42878, 42888, 42889, 42891, 42896, 42912,
255897    43000, 43002, 43003, 43010, 43011, 43014, 43015, 43019, 43020, 43043,
255898    43045, 43047, 43048, 43056, 43062, 43064, 43065, 43072, 43124, 43136,
255899    43138, 43188, 43204, 43214, 43216, 43232, 43250, 43256, 43259, 43264,
255900    43274, 43302, 43310, 43312, 43335, 43346, 43359, 43360, 43392, 43395,
255901    43396, 43443, 43444, 43446, 43450, 43452, 43453, 43457, 43471, 43472,
255902    43486, 43520, 43561, 43567, 43569, 43571, 43573, 43584, 43587, 43588,
255903    43596, 43597, 43600, 43612, 43616, 43632, 43633, 43639, 43642, 43643,
255904    43648, 43696, 43697, 43698, 43701, 43703, 43705, 43710, 43712, 43713,
255905    43714, 43739, 43741, 43742, 43744, 43755, 43756, 43758, 43760, 43762,
255906    43763, 43765, 43766, 43777, 43785, 43793, 43808, 43816, 43968, 44003,
255907    44005, 44006, 44008, 44009, 44011, 44012, 44013, 44016, 44032, 55203,
255908    55216, 55243, 55296, 56191, 56319, 57343, 57344, 63743, 63744, 64112,
255909    64256, 64275, 64285, 64286, 64287, 64297, 64298, 64312, 64318, 64320,
255910    64323, 64326, 64434, 64467, 64830, 64831, 64848, 64914, 65008, 65020,
255911    65021, 65024, 65040, 65047, 65048, 65049, 65056, 65072, 65073, 65075,
255912    65077, 65078, 65079, 65080, 65081, 65082, 65083, 65084, 65085, 65086,
255913    65087, 65088, 65089, 65090, 65091, 65092, 65093, 65095, 65096, 65097,
255914    65101, 65104, 65108, 65112, 65113, 65114, 65115, 65116, 65117, 65118,
255915    65119, 65122, 65123, 65124, 65128, 65129, 65130, 65136, 65142, 65279,
255916    65281, 65284, 65285, 65288, 65289, 65290, 65291, 65292, 65293, 65294,
255917    65296, 65306, 65308, 65311, 65313, 65339, 65340, 65341, 65342, 65343,
255918    65344, 65345, 65371, 65372, 65373, 65374, 65375, 65376, 65377, 65378,
255919    65379, 65380, 65382, 65392, 65393, 65438, 65440, 65474, 65482, 65490,
255920    65498, 65504, 65506, 65507, 65508, 65509, 65512, 65513, 65517, 65529,
255921    65532, 0,     13,    40,    60,    63,    80,    128,   256,   263,
255922    311,   320,   373,   377,   394,   400,   464,   509,   640,   672,
255923    768,   800,   816,   833,   834,   842,   896,   927,   928,   968,
255924    976,   977,   1024,  1064,  1104,  1184,  2048,  2056,  2058,  2103,
255925    2108,  2111,  2135,  2136,  2304,  2326,  2335,  2336,  2367,  2432,
255926    2494,  2560,  2561,  2565,  2572,  2576,  2581,  2585,  2616,  2623,
255927    2624,  2640,  2656,  2685,  2687,  2816,  2873,  2880,  2904,  2912,
255928    2936,  3072,  3680,  4096,  4097,  4098,  4099,  4152,  4167,  4178,
255929    4198,  4224,  4226,  4227,  4272,  4275,  4279,  4281,  4283,  4285,
255930    4286,  4304,  4336,  4352,  4355,  4391,  4396,  4397,  4406,  4416,
255931    4480,  4482,  4483,  4531,  4534,  4543,  4545,  4549,  4560,  5760,
255932    5803,  5804,  5805,  5806,  5808,  5814,  5815,  5824,  8192,  9216,
255933    9328,  12288, 26624, 28416, 28496, 28497, 28559, 28563, 45056, 53248,
255934    53504, 53545, 53605, 53607, 53610, 53613, 53619, 53627, 53635, 53637,
255935    53644, 53674, 53678, 53760, 53826, 53829, 54016, 54112, 54272, 54298,
255936    54324, 54350, 54358, 54376, 54402, 54428, 54430, 54434, 54437, 54441,
255937    54446, 54454, 54459, 54461, 54469, 54480, 54506, 54532, 54535, 54541,
255938    54550, 54558, 54584, 54587, 54592, 54598, 54602, 54610, 54636, 54662,
255939    54688, 54714, 54740, 54766, 54792, 54818, 54844, 54870, 54896, 54922,
255940    54952, 54977, 54978, 55003, 55004, 55010, 55035, 55036, 55061, 55062,
255941    55068, 55093, 55094, 55119, 55120, 55126, 55151, 55152, 55177, 55178,
255942    55184, 55209, 55210, 55235, 55236, 55242, 55246, 60928, 60933, 60961,
255943    60964, 60967, 60969, 60980, 60985, 60987, 60994, 60999, 61001, 61003,
255944    61005, 61009, 61012, 61015, 61017, 61019, 61021, 61023, 61025, 61028,
255945    61031, 61036, 61044, 61049, 61054, 61056, 61067, 61089, 61093, 61099,
255946    61168, 61440, 61488, 61600, 61617, 61633, 61649, 61696, 61712, 61744,
255947    61808, 61926, 61968, 62016, 62032, 62208, 62256, 62263, 62336, 62368,
255948    62406, 62432, 62464, 62528, 62530, 62713, 62720, 62784, 62800, 62971,
255949    63045, 63104, 63232, 0,     42710, 42752, 46900, 46912, 47133, 63488,
255950    1,     32,    256,   0,     65533,
255951  };
255952static u16 aFts5UnicodeData[] = {
255953    1025,  61,    117,   55,    117,   54,    50,    53,    57,    53,
255954    49,    85,    333,   85,    121,   85,    841,   54,    53,    50,
255955    56,    48,    56,    837,   54,    57,    50,    57,    1057,  61,
255956    53,    151,   58,    53,    56,    58,    39,    52,    57,    34,
255957    58,    56,    58,    57,    79,    56,    37,    85,    56,    47,
255958    39,    51,    111,   53,    745,   57,    233,   773,   57,    261,
255959    1822,  37,    542,   37,    1534,  222,   69,    73,    37,    126,
255960    126,   73,    69,    137,   37,    73,    37,    105,   101,   73,
255961    37,    73,    37,    190,   158,   37,    126,   126,   73,    37,
255962    126,   94,    37,    39,    94,    69,    135,   41,    40,    37,
255963    41,    40,    37,    41,    40,    37,    542,   37,    606,   37,
255964    41,    40,    37,    126,   73,    37,    1886,  197,   73,    37,
255965    73,    69,    126,   105,   37,    286,   2181,  39,    869,   582,
255966    152,   390,   472,   166,   248,   38,    56,    38,    568,   3596,
255967    158,   38,    56,    94,    38,    101,   53,    88,    41,    53,
255968    105,   41,    73,    37,    553,   297,   1125,  94,    37,    105,
255969    101,   798,   133,   94,    57,    126,   94,    37,    1641,  1541,
255970    1118,  58,    172,   75,    1790,  478,   37,    2846,  1225,  38,
255971    213,   1253,  53,    49,    55,    1452,  49,    44,    53,    76,
255972    53,    76,    53,    44,    871,   103,   85,    162,   121,   85,
255973    55,    85,    90,    364,   53,    85,    1031,  38,    327,   684,
255974    333,   149,   71,    44,    3175,  53,    39,    236,   34,    58,
255975    204,   70,    76,    58,    140,   71,    333,   103,   90,    39,
255976    469,   34,    39,    44,    967,   876,   2855,  364,   39,    333,
255977    1063,  300,   70,    58,    117,   38,    711,   140,   38,    300,
255978    38,    108,   38,    172,   501,   807,   108,   53,    39,    359,
255979    876,   108,   42,    1735,  44,    42,    44,    39,    106,   268,
255980    138,   44,    74,    39,    236,   327,   76,    85,    333,   53,
255981    38,    199,   231,   44,    74,    263,   71,    711,   231,   39,
255982    135,   44,    39,    106,   140,   74,    74,    44,    39,    42,
255983    71,    103,   76,    333,   71,    87,    207,   58,    55,    76,
255984    42,    199,   71,    711,   231,   71,    71,    71,    44,    106,
255985    76,    76,    108,   44,    135,   39,    333,   76,    103,   44,
255986    76,    42,    295,   103,   711,   231,   71,    167,   44,    39,
255987    106,   172,   76,    42,    74,    44,    39,    71,    76,    333,
255988    53,    55,    44,    74,    263,   71,    711,   231,   71,    167,
255989    44,    39,    42,    44,    42,    140,   74,    74,    44,    44,
255990    42,    71,    103,   76,    333,   58,    39,    207,   44,    39,
255991    199,   103,   135,   71,    39,    71,    71,    103,   391,   74,
255992    44,    74,    106,   106,   44,    39,    42,    333,   111,   218,
255993    55,    58,    106,   263,   103,   743,   327,   167,   39,    108,
255994    138,   108,   140,   76,    71,    71,    76,    333,   239,   58,
255995    74,    263,   103,   743,   327,   167,   44,    39,    42,    44,
255996    170,   44,    74,    74,    76,    74,    39,    71,    76,    333,
255997    71,    74,    263,   103,   1319,  39,    106,   140,   106,   106,
255998    44,    39,    42,    71,    76,    333,   207,   58,    199,   74,
255999    583,   775,   295,   39,    231,   44,    106,   108,   44,    266,
256000    74,    53,    1543,  44,    71,    236,   55,    199,   38,    268,
256001    53,    333,   85,    71,    39,    71,    39,    39,    135,   231,
256002    103,   39,    39,    71,    135,   44,    71,    204,   76,    39,
256003    167,   38,    204,   333,   135,   39,    122,   501,   58,    53,
256004    122,   76,    218,   333,   335,   58,    44,    58,    44,    58,
256005    44,    54,    50,    54,    50,    74,    263,   1159,  460,   42,
256006    172,   53,    76,    167,   364,   1164,  282,   44,    218,   90,
256007    181,   154,   85,    1383,  74,    140,   42,    204,   42,    76,
256008    74,    76,    39,    333,   213,   199,   74,    76,    135,   108,
256009    39,    106,   71,    234,   103,   140,   423,   44,    74,    76,
256010    202,   44,    39,    42,    333,   106,   44,    90,    1225,  41,
256011    41,    1383,  53,    38,    10631, 135,   231,   39,    135,   1319,
256012    135,   1063,  135,   231,   39,    135,   487,   1831,  135,   2151,
256013    108,   309,   655,   519,   346,   2727,  49,    19847, 85,    551,
256014    61,    839,   54,    50,    2407,  117,   110,   423,   135,   108,
256015    583,   108,   85,    583,   76,    423,   103,   76,    1671,  76,
256016    42,    236,   266,   44,    74,    364,   117,   38,    117,   55,
256017    39,    44,    333,   335,   213,   49,    149,   108,   61,    333,
256018    1127,  38,    1671,  1319,  44,    39,    2247,  935,   108,   138,
256019    76,    106,   74,    44,    202,   108,   58,    85,    333,   967,
256020    167,   1415,  554,   231,   74,    333,   47,    1114,  743,   76,
256021    106,   85,    1703,  42,    44,    42,    236,   44,    42,    44,
256022    74,    268,   202,   332,   44,    333,   333,   245,   38,    213,
256023    140,   42,    1511,  44,    42,    172,   42,    44,    170,   44,
256024    74,    231,   333,   245,   346,   300,   314,   76,    42,    967,
256025    42,    140,   74,    76,    42,    44,    74,    71,    333,   1415,
256026    44,    42,    76,    106,   44,    42,    108,   74,    149,   1159,
256027    266,   268,   74,    76,    181,   333,   103,   333,   967,   198,
256028    85,    277,   108,   53,    428,   42,    236,   135,   44,    135,
256029    74,    44,    71,    1413,  2022,  421,   38,    1093,  1190,  1260,
256030    140,   4830,  261,   3166,  261,   265,   197,   201,   261,   265,
256031    261,   265,   197,   201,   261,   41,    41,    41,    94,    229,
256032    265,   453,   261,   264,   261,   264,   261,   264,   165,   69,
256033    137,   40,    56,    37,    120,   101,   69,    137,   40,    120,
256034    133,   69,    137,   120,   261,   169,   120,   101,   69,    137,
256035    40,    88,    381,   162,   209,   85,    52,    51,    54,    84,
256036    51,    54,    52,    277,   59,    60,    162,   61,    309,   52,
256037    51,    149,   80,    117,   57,    54,    50,    373,   57,    53,
256038    48,    341,   61,    162,   194,   47,    38,    207,   121,   54,
256039    50,    38,    335,   121,   54,    50,    422,   855,   428,   139,
256040    44,    107,   396,   90,    41,    154,   41,    90,    37,    105,
256041    69,    105,   37,    58,    41,    90,    57,    169,   218,   41,
256042    58,    41,    58,    41,    58,    137,   58,    37,    137,   37,
256043    135,   37,    90,    69,    73,    185,   94,    101,   58,    57,
256044    90,    37,    58,    527,   1134,  94,    142,   47,    185,   186,
256045    89,    154,   57,    90,    57,    90,    57,    250,   57,    1018,
256046    89,    90,    57,    58,    57,    1018,  8601,  282,   153,   666,
256047    89,    250,   54,    50,    2618,  57,    986,   825,   1306,  217,
256048    602,   1274,  378,   1935,  2522,  719,   5882,  57,    314,   57,
256049    1754,  281,   3578,  57,    4634,  3322,  54,    50,    54,    50,
256050    54,    50,    54,    50,    54,    50,    54,    50,    54,    50,
256051    975,   1434,  185,   54,    50,    1017,  54,    50,    54,    50,
256052    54,    50,    54,    50,    54,    50,    537,   8218,  4217,  54,
256053    50,    54,    50,    54,    50,    54,    50,    54,    50,    54,
256054    50,    54,    50,    54,    50,    54,    50,    54,    50,    54,
256055    50,    2041,  54,    50,    54,    50,    1049,  54,    50,    8281,
256056    1562,  697,   90,    217,   346,   1513,  1509,  126,   73,    69,
256057    254,   105,   37,    94,    37,    94,    165,   70,    105,   37,
256058    3166,  37,    218,   158,   108,   94,    149,   47,    85,    1221,
256059    37,    37,    1799,  38,    53,    44,    743,   231,   231,   231,
256060    231,   231,   231,   231,   231,   1036,  85,    52,    51,    52,
256061    51,    117,   52,    51,    53,    52,    51,    309,   49,    85,
256062    49,    53,    52,    51,    85,    52,    51,    54,    50,    54,
256063    50,    54,    50,    54,    50,    181,   38,    341,   81,    858,
256064    2874,  6874,  410,   61,    117,   58,    38,    39,    46,    54,
256065    50,    54,    50,    54,    50,    54,    50,    54,    50,    90,
256066    54,    50,    54,    50,    54,    50,    54,    50,    49,    54,
256067    82,    58,    302,   140,   74,    49,    166,   90,    110,   38,
256068    39,    53,    90,    2759,  76,    88,    70,    39,    49,    2887,
256069    53,    102,   39,    1319,  3015,  90,    143,   346,   871,   1178,
256070    519,   1018,  335,   986,   271,   58,    495,   1050,  335,   1274,
256071    495,   2042,  8218,  39,    39,    2074,  39,    39,    679,   38,
256072    36583, 1786,  1287,  198,   85,    8583,  38,    117,   519,   333,
256073    71,    1502,  39,    44,    107,   53,    332,   53,    38,    798,
256074    44,    2247,  334,   76,    213,   760,   294,   88,    478,   69,
256075    2014,  38,    261,   190,   350,   38,    88,    158,   158,   382,
256076    70,    37,    231,   44,    103,   44,    135,   44,    743,   74,
256077    76,    42,    154,   207,   90,    55,    58,    1671,  149,   74,
256078    1607,  522,   44,    85,    333,   588,   199,   117,   39,    333,
256079    903,   268,   85,    743,   364,   74,    53,    935,   108,   42,
256080    1511,  44,    74,    140,   74,    44,    138,   437,   38,    333,
256081    85,    1319,  204,   74,    76,    74,    76,    103,   44,    263,
256082    44,    42,    333,   149,   519,   38,    199,   122,   39,    42,
256083    1543,  44,    39,    108,   71,    76,    167,   76,    39,    44,
256084    39,    71,    38,    85,    359,   42,    76,    74,    85,    39,
256085    70,    42,    44,    199,   199,   199,   231,   231,   1127,  74,
256086    44,    74,    44,    74,    53,    42,    44,    333,   39,    39,
256087    743,   1575,  36,    68,    68,    36,    63,    63,    11719, 3399,
256088    229,   165,   39,    44,    327,   57,    423,   167,   39,    71,
256089    71,    3463,  536,   11623, 54,    50,    2055,  1735,  391,   55,
256090    58,    524,   245,   54,    50,    53,    236,   53,    81,    80,
256091    54,    50,    54,    50,    54,    50,    54,    50,    54,    50,
256092    54,    50,    54,    50,    54,    50,    85,    54,    50,    149,
256093    112,   117,   149,   49,    54,    50,    54,    50,    54,    50,
256094    117,   57,    49,    121,   53,    55,    85,    167,   4327,  34,
256095    117,   55,    117,   54,    50,    53,    57,    53,    49,    85,
256096    333,   85,    121,   85,    841,   54,    53,    50,    56,    48,
256097    56,    837,   54,    57,    50,    57,    54,    50,    53,    54,
256098    50,    85,    327,   38,    1447,  70,    999,   199,   199,   199,
256099    103,   87,    57,    56,    58,    87,    58,    153,   90,    98,
256100    90,    391,   839,   615,   71,    487,   455,   3943,  117,   1455,
256101    314,   1710,  143,   570,   47,    410,   1466,  44,    935,   1575,
256102    999,   143,   551,   46,    263,   46,    967,   53,    1159,  263,
256103    53,    174,   1289,  1285,  2503,  333,   199,   39,    1415,  71,
256104    39,    743,   53,    271,   711,   207,   53,    839,   53,    1799,
256105    71,    39,    108,   76,    140,   135,   103,   871,   108,   44,
256106    271,   309,   935,   79,    53,    1735,  245,   711,   271,   615,
256107    271,   2343,  1007,  42,    44,    42,    1703,  492,   245,   655,
256108    333,   76,    42,    1447,  106,   140,   74,    76,    85,    34,
256109    149,   807,   333,   108,   1159,  172,   42,    268,   333,   149,
256110    76,    42,    1543,  106,   300,   74,    135,   149,   333,   1383,
256111    44,    42,    44,    74,    204,   42,    44,    333,   28135, 3182,
256112    149,   34279, 18215, 2215,  39,    1482,  140,   422,   71,    7898,
256113    1274,  1946,  74,    108,   122,   202,   258,   268,   90,    236,
256114    986,   140,   1562,  2138,  108,   58,    2810,  591,   841,   837,
256115    841,   229,   581,   841,   837,   41,    73,    41,    73,    137,
256116    265,   133,   37,    229,   357,   841,   837,   73,    137,   265,
256117    233,   837,   73,    137,   169,   41,    233,   837,   841,   837,
256118    841,   837,   841,   837,   841,   837,   841,   837,   841,   901,
256119    809,   57,    805,   57,    197,   809,   57,    805,   57,    197,
256120    809,   57,    805,   57,    197,   809,   57,    805,   57,    197,
256121    809,   57,    805,   57,    197,   94,    1613,  135,   871,   71,
256122    39,    39,    327,   135,   39,    39,    39,    39,    39,    39,
256123    103,   71,    39,    39,    39,    39,    39,    39,    71,    39,
256124    135,   231,   135,   135,   39,    327,   551,   103,   167,   551,
256125    89,    1434,  3226,  506,   474,   506,   506,   367,   1018,  1946,
256126    1402,  954,   1402,  314,   90,    1082,  218,   2266,  666,   1210,
256127    186,   570,   2042,  58,    5850,  154,   2010,  154,   794,   2266,
256128    378,   2266,  3738,  39,    39,    39,    39,    39,    39,    17351,
256129    34,    3074,  7692,  63,    63,
256130  };
256131
256132static int sqlite3Fts5UnicodeCategory(u32 iCode) {
256133  int iRes = -1;
256134  int iHi;
256135  int iLo;
256136  int ret;
256137  u16 iKey;
256138
256139  if( iCode>=(1<<20) ){
256140    return 0;
256141  }
256142  iLo = aFts5UnicodeBlock[(iCode>>16)];
256143  iHi = aFts5UnicodeBlock[1+(iCode>>16)];
256144  iKey = (iCode & 0xFFFF);
256145  while( iHi>iLo ){
256146    int iTest = (iHi + iLo) / 2;
256147    assert( iTest>=iLo && iTest<iHi );
256148    if( iKey>=aFts5UnicodeMap[iTest] ){
256149      iRes = iTest;
256150      iLo = iTest+1;
256151    }else{
256152      iHi = iTest;
256153    }
256154  }
256155
256156  if( iRes<0 ) return 0;
256157  if( iKey>=(aFts5UnicodeMap[iRes]+(aFts5UnicodeData[iRes]>>5)) ) return 0;
256158  ret = aFts5UnicodeData[iRes] & 0x1F;
256159  if( ret!=30 ) return ret;
256160  return ((iKey - aFts5UnicodeMap[iRes]) & 0x01) ? 5 : 9;
256161}
256162
256163static void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){
256164  int i = 0;
256165  int iTbl = 0;
256166  while( i<128 ){
256167    int bToken = aArray[ aFts5UnicodeData[iTbl] & 0x1F ];
256168    int n = (aFts5UnicodeData[iTbl] >> 5) + i;
256169    for(; i<128 && i<n; i++){
256170      aAscii[i] = (u8)bToken;
256171    }
256172    iTbl++;
256173  }
256174  aAscii[0] = 0;                  /* 0x00 is never a token character */
256175}
256176
256177
256178/*
256179** 2015 May 30
256180**
256181** The author disclaims copyright to this source code.  In place of
256182** a legal notice, here is a blessing:
256183**
256184**    May you do good and not evil.
256185**    May you find forgiveness for yourself and forgive others.
256186**    May you share freely, never taking more than you give.
256187**
256188******************************************************************************
256189**
256190** Routines for varint serialization and deserialization.
256191*/
256192
256193
256194/* #include "fts5Int.h" */
256195
256196/*
256197** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
256198** Except, this version does handle the single byte case that the core
256199** version depends on being handled before its function is called.
256200*/
256201static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
256202  u32 a,b;
256203
256204  /* The 1-byte case. Overwhelmingly the most common. */
256205  a = *p;
256206  /* a: p0 (unmasked) */
256207  if (!(a&0x80))
256208  {
256209    /* Values between 0 and 127 */
256210    *v = a;
256211    return 1;
256212  }
256213
256214  /* The 2-byte case */
256215  p++;
256216  b = *p;
256217  /* b: p1 (unmasked) */
256218  if (!(b&0x80))
256219  {
256220    /* Values between 128 and 16383 */
256221    a &= 0x7f;
256222    a = a<<7;
256223    *v = a | b;
256224    return 2;
256225  }
256226
256227  /* The 3-byte case */
256228  p++;
256229  a = a<<14;
256230  a |= *p;
256231  /* a: p0<<14 | p2 (unmasked) */
256232  if (!(a&0x80))
256233  {
256234    /* Values between 16384 and 2097151 */
256235    a &= (0x7f<<14)|(0x7f);
256236    b &= 0x7f;
256237    b = b<<7;
256238    *v = a | b;
256239    return 3;
256240  }
256241
256242  /* A 32-bit varint is used to store size information in btrees.
256243  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
256244  ** A 3-byte varint is sufficient, for example, to record the size
256245  ** of a 1048569-byte BLOB or string.
256246  **
256247  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
256248  ** rare larger cases can be handled by the slower 64-bit varint
256249  ** routine.
256250  */
256251  {
256252    u64 v64;
256253    u8 n;
256254    p -= 2;
256255    n = sqlite3Fts5GetVarint(p, &v64);
256256    *v = ((u32)v64) & 0x7FFFFFFF;
256257    assert( n>3 && n<=9 );
256258    return n;
256259  }
256260}
256261
256262
256263/*
256264** Bitmasks used by sqlite3GetVarint().  These precomputed constants
256265** are defined here rather than simply putting the constant expressions
256266** inline in order to work around bugs in the RVT compiler.
256267**
256268** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
256269**
256270** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
256271*/
256272#define SLOT_2_0     0x001fc07f
256273#define SLOT_4_2_0   0xf01fc07f
256274
256275/*
256276** Read a 64-bit variable-length integer from memory starting at p[0].
256277** Return the number of bytes read.  The value is stored in *v.
256278*/
256279static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
256280  u32 a,b,s;
256281
256282  a = *p;
256283  /* a: p0 (unmasked) */
256284  if (!(a&0x80))
256285  {
256286    *v = a;
256287    return 1;
256288  }
256289
256290  p++;
256291  b = *p;
256292  /* b: p1 (unmasked) */
256293  if (!(b&0x80))
256294  {
256295    a &= 0x7f;
256296    a = a<<7;
256297    a |= b;
256298    *v = a;
256299    return 2;
256300  }
256301
256302  /* Verify that constants are precomputed correctly */
256303  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
256304  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
256305
256306  p++;
256307  a = a<<14;
256308  a |= *p;
256309  /* a: p0<<14 | p2 (unmasked) */
256310  if (!(a&0x80))
256311  {
256312    a &= SLOT_2_0;
256313    b &= 0x7f;
256314    b = b<<7;
256315    a |= b;
256316    *v = a;
256317    return 3;
256318  }
256319
256320  /* CSE1 from below */
256321  a &= SLOT_2_0;
256322  p++;
256323  b = b<<14;
256324  b |= *p;
256325  /* b: p1<<14 | p3 (unmasked) */
256326  if (!(b&0x80))
256327  {
256328    b &= SLOT_2_0;
256329    /* moved CSE1 up */
256330    /* a &= (0x7f<<14)|(0x7f); */
256331    a = a<<7;
256332    a |= b;
256333    *v = a;
256334    return 4;
256335  }
256336
256337  /* a: p0<<14 | p2 (masked) */
256338  /* b: p1<<14 | p3 (unmasked) */
256339  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
256340  /* moved CSE1 up */
256341  /* a &= (0x7f<<14)|(0x7f); */
256342  b &= SLOT_2_0;
256343  s = a;
256344  /* s: p0<<14 | p2 (masked) */
256345
256346  p++;
256347  a = a<<14;
256348  a |= *p;
256349  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
256350  if (!(a&0x80))
256351  {
256352    /* we can skip these cause they were (effectively) done above in calc'ing s */
256353    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
256354    /* b &= (0x7f<<14)|(0x7f); */
256355    b = b<<7;
256356    a |= b;
256357    s = s>>18;
256358    *v = ((u64)s)<<32 | a;
256359    return 5;
256360  }
256361
256362  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
256363  s = s<<7;
256364  s |= b;
256365  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
256366
256367  p++;
256368  b = b<<14;
256369  b |= *p;
256370  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
256371  if (!(b&0x80))
256372  {
256373    /* we can skip this cause it was (effectively) done above in calc'ing s */
256374    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
256375    a &= SLOT_2_0;
256376    a = a<<7;
256377    a |= b;
256378    s = s>>18;
256379    *v = ((u64)s)<<32 | a;
256380    return 6;
256381  }
256382
256383  p++;
256384  a = a<<14;
256385  a |= *p;
256386  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
256387  if (!(a&0x80))
256388  {
256389    a &= SLOT_4_2_0;
256390    b &= SLOT_2_0;
256391    b = b<<7;
256392    a |= b;
256393    s = s>>11;
256394    *v = ((u64)s)<<32 | a;
256395    return 7;
256396  }
256397
256398  /* CSE2 from below */
256399  a &= SLOT_2_0;
256400  p++;
256401  b = b<<14;
256402  b |= *p;
256403  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
256404  if (!(b&0x80))
256405  {
256406    b &= SLOT_4_2_0;
256407    /* moved CSE2 up */
256408    /* a &= (0x7f<<14)|(0x7f); */
256409    a = a<<7;
256410    a |= b;
256411    s = s>>4;
256412    *v = ((u64)s)<<32 | a;
256413    return 8;
256414  }
256415
256416  p++;
256417  a = a<<15;
256418  a |= *p;
256419  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
256420
256421  /* moved CSE2 up */
256422  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
256423  b &= SLOT_2_0;
256424  b = b<<8;
256425  a |= b;
256426
256427  s = s<<4;
256428  b = p[-4];
256429  b &= 0x7f;
256430  b = b>>3;
256431  s |= b;
256432
256433  *v = ((u64)s)<<32 | a;
256434
256435  return 9;
256436}
256437
256438/*
256439** The variable-length integer encoding is as follows:
256440**
256441** KEY:
256442**         A = 0xxxxxxx    7 bits of data and one flag bit
256443**         B = 1xxxxxxx    7 bits of data and one flag bit
256444**         C = xxxxxxxx    8 bits of data
256445**
256446**  7 bits - A
256447** 14 bits - BA
256448** 21 bits - BBA
256449** 28 bits - BBBA
256450** 35 bits - BBBBA
256451** 42 bits - BBBBBA
256452** 49 bits - BBBBBBA
256453** 56 bits - BBBBBBBA
256454** 64 bits - BBBBBBBBC
256455*/
256456
256457#ifdef SQLITE_NOINLINE
256458# define FTS5_NOINLINE SQLITE_NOINLINE
256459#else
256460# define FTS5_NOINLINE
256461#endif
256462
256463/*
256464** Write a 64-bit variable-length integer to memory starting at p[0].
256465** The length of data write will be between 1 and 9 bytes.  The number
256466** of bytes written is returned.
256467**
256468** A variable-length integer consists of the lower 7 bits of each byte
256469** for all bytes that have the 8th bit set and one byte with the 8th
256470** bit clear.  Except, if we get to the 9th byte, it stores the full
256471** 8 bits and is the last byte.
256472*/
256473static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
256474  int i, j, n;
256475  u8 buf[10];
256476  if( v & (((u64)0xff000000)<<32) ){
256477    p[8] = (u8)v;
256478    v >>= 8;
256479    for(i=7; i>=0; i--){
256480      p[i] = (u8)((v & 0x7f) | 0x80);
256481      v >>= 7;
256482    }
256483    return 9;
256484  }
256485  n = 0;
256486  do{
256487    buf[n++] = (u8)((v & 0x7f) | 0x80);
256488    v >>= 7;
256489  }while( v!=0 );
256490  buf[0] &= 0x7f;
256491  assert( n<=9 );
256492  for(i=0, j=n-1; j>=0; j--, i++){
256493    p[i] = buf[j];
256494  }
256495  return n;
256496}
256497
256498static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
256499  if( v<=0x7f ){
256500    p[0] = v&0x7f;
256501    return 1;
256502  }
256503  if( v<=0x3fff ){
256504    p[0] = ((v>>7)&0x7f)|0x80;
256505    p[1] = v&0x7f;
256506    return 2;
256507  }
256508  return fts5PutVarint64(p,v);
256509}
256510
256511
256512static int sqlite3Fts5GetVarintLen(u32 iVal){
256513#if 0
256514  if( iVal<(1 << 7 ) ) return 1;
256515#endif
256516  assert( iVal>=(1 << 7) );
256517  if( iVal<(1 << 14) ) return 2;
256518  if( iVal<(1 << 21) ) return 3;
256519  if( iVal<(1 << 28) ) return 4;
256520  return 5;
256521}
256522
256523/*
256524** 2015 May 08
256525**
256526** The author disclaims copyright to this source code.  In place of
256527** a legal notice, here is a blessing:
256528**
256529**    May you do good and not evil.
256530**    May you find forgiveness for yourself and forgive others.
256531**    May you share freely, never taking more than you give.
256532**
256533******************************************************************************
256534**
256535** This is an SQLite virtual table module implementing direct access to an
256536** existing FTS5 index. The module may create several different types of
256537** tables:
256538**
256539** col:
256540**     CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
256541**
256542**   One row for each term/column combination. The value of $doc is set to
256543**   the number of fts5 rows that contain at least one instance of term
256544**   $term within column $col. Field $cnt is set to the total number of
256545**   instances of term $term in column $col (in any row of the fts5 table).
256546**
256547** row:
256548**     CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
256549**
256550**   One row for each term in the database. The value of $doc is set to
256551**   the number of fts5 rows that contain at least one instance of term
256552**   $term. Field $cnt is set to the total number of instances of term
256553**   $term in the database.
256554**
256555** instance:
256556**     CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
256557**
256558**   One row for each term instance in the database.
256559*/
256560
256561
256562/* #include "fts5Int.h" */
256563
256564
256565typedef struct Fts5VocabTable Fts5VocabTable;
256566typedef struct Fts5VocabCursor Fts5VocabCursor;
256567
256568struct Fts5VocabTable {
256569  sqlite3_vtab base;
256570  char *zFts5Tbl;                 /* Name of fts5 table */
256571  char *zFts5Db;                  /* Db containing fts5 table */
256572  sqlite3 *db;                    /* Database handle */
256573  Fts5Global *pGlobal;            /* FTS5 global object for this database */
256574  int eType;                      /* FTS5_VOCAB_COL, ROW or INSTANCE */
256575  unsigned bBusy;                 /* True if busy */
256576};
256577
256578struct Fts5VocabCursor {
256579  sqlite3_vtab_cursor base;
256580  sqlite3_stmt *pStmt;            /* Statement holding lock on pIndex */
256581  Fts5Table *pFts5;               /* Associated FTS5 table */
256582
256583  int bEof;                       /* True if this cursor is at EOF */
256584  Fts5IndexIter *pIter;           /* Term/rowid iterator object */
256585  void *pStruct;                  /* From sqlite3Fts5StructureRef() */
256586
256587  int nLeTerm;                    /* Size of zLeTerm in bytes */
256588  char *zLeTerm;                  /* (term <= $zLeTerm) paramater, or NULL */
256589
256590  /* These are used by 'col' tables only */
256591  int iCol;
256592  i64 *aCnt;
256593  i64 *aDoc;
256594
256595  /* Output values used by all tables. */
256596  i64 rowid;                      /* This table's current rowid value */
256597  Fts5Buffer term;                /* Current value of 'term' column */
256598
256599  /* Output values Used by 'instance' tables only */
256600  i64 iInstPos;
256601  int iInstOff;
256602};
256603
256604#define FTS5_VOCAB_COL      0
256605#define FTS5_VOCAB_ROW      1
256606#define FTS5_VOCAB_INSTANCE 2
256607
256608#define FTS5_VOCAB_COL_SCHEMA  "term, col, doc, cnt"
256609#define FTS5_VOCAB_ROW_SCHEMA  "term, doc, cnt"
256610#define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset"
256611
256612/*
256613** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
256614*/
256615#define FTS5_VOCAB_TERM_EQ 0x01
256616#define FTS5_VOCAB_TERM_GE 0x02
256617#define FTS5_VOCAB_TERM_LE 0x04
256618
256619
256620/*
256621** Translate a string containing an fts5vocab table type to an
256622** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
256623** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
256624** and return SQLITE_ERROR.
256625*/
256626static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
256627  int rc = SQLITE_OK;
256628  char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
256629  if( rc==SQLITE_OK ){
256630    sqlite3Fts5Dequote(zCopy);
256631    if( sqlite3_stricmp(zCopy, "col")==0 ){
256632      *peType = FTS5_VOCAB_COL;
256633    }else
256634
256635    if( sqlite3_stricmp(zCopy, "row")==0 ){
256636      *peType = FTS5_VOCAB_ROW;
256637    }else
256638    if( sqlite3_stricmp(zCopy, "instance")==0 ){
256639      *peType = FTS5_VOCAB_INSTANCE;
256640    }else
256641    {
256642      *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
256643      rc = SQLITE_ERROR;
256644    }
256645    sqlite3_free(zCopy);
256646  }
256647
256648  return rc;
256649}
256650
256651
256652/*
256653** The xDisconnect() virtual table method.
256654*/
256655static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
256656  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
256657  sqlite3_free(pTab);
256658  return SQLITE_OK;
256659}
256660
256661/*
256662** The xDestroy() virtual table method.
256663*/
256664static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
256665  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
256666  sqlite3_free(pTab);
256667  return SQLITE_OK;
256668}
256669
256670/*
256671** This function is the implementation of both the xConnect and xCreate
256672** methods of the FTS3 virtual table.
256673**
256674** The argv[] array contains the following:
256675**
256676**   argv[0]   -> module name  ("fts5vocab")
256677**   argv[1]   -> database name
256678**   argv[2]   -> table name
256679**
256680** then:
256681**
256682**   argv[3]   -> name of fts5 table
256683**   argv[4]   -> type of fts5vocab table
256684**
256685** or, for tables in the TEMP schema only.
256686**
256687**   argv[3]   -> name of fts5 tables database
256688**   argv[4]   -> name of fts5 table
256689**   argv[5]   -> type of fts5vocab table
256690*/
256691static int fts5VocabInitVtab(
256692  sqlite3 *db,                    /* The SQLite database connection */
256693  void *pAux,                     /* Pointer to Fts5Global object */
256694  int argc,                       /* Number of elements in argv array */
256695  const char * const *argv,       /* xCreate/xConnect argument array */
256696  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
256697  char **pzErr                    /* Write any error message here */
256698){
256699  const char *azSchema[] = {
256700    "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA  ")",
256701    "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA  ")",
256702    "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
256703  };
256704
256705  Fts5VocabTable *pRet = 0;
256706  int rc = SQLITE_OK;             /* Return code */
256707  int bDb;
256708
256709  bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
256710
256711  if( argc!=5 && bDb==0 ){
256712    *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
256713    rc = SQLITE_ERROR;
256714  }else{
256715    int nByte;                      /* Bytes of space to allocate */
256716    const char *zDb = bDb ? argv[3] : argv[1];
256717    const char *zTab = bDb ? argv[4] : argv[3];
256718    const char *zType = bDb ? argv[5] : argv[4];
256719    int nDb = (int)strlen(zDb)+1;
256720    int nTab = (int)strlen(zTab)+1;
256721    int eType = 0;
256722
256723    rc = fts5VocabTableType(zType, pzErr, &eType);
256724    if( rc==SQLITE_OK ){
256725      assert( eType>=0 && eType<ArraySize(azSchema) );
256726      rc = sqlite3_declare_vtab(db, azSchema[eType]);
256727    }
256728
256729    nByte = sizeof(Fts5VocabTable) + nDb + nTab;
256730    pRet = sqlite3Fts5MallocZero(&rc, nByte);
256731    if( pRet ){
256732      pRet->pGlobal = (Fts5Global*)pAux;
256733      pRet->eType = eType;
256734      pRet->db = db;
256735      pRet->zFts5Tbl = (char*)&pRet[1];
256736      pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
256737      memcpy(pRet->zFts5Tbl, zTab, nTab);
256738      memcpy(pRet->zFts5Db, zDb, nDb);
256739      sqlite3Fts5Dequote(pRet->zFts5Tbl);
256740      sqlite3Fts5Dequote(pRet->zFts5Db);
256741    }
256742  }
256743
256744  *ppVTab = (sqlite3_vtab*)pRet;
256745  return rc;
256746}
256747
256748
256749/*
256750** The xConnect() and xCreate() methods for the virtual table. All the
256751** work is done in function fts5VocabInitVtab().
256752*/
256753static int fts5VocabConnectMethod(
256754  sqlite3 *db,                    /* Database connection */
256755  void *pAux,                     /* Pointer to tokenizer hash table */
256756  int argc,                       /* Number of elements in argv array */
256757  const char * const *argv,       /* xCreate/xConnect argument array */
256758  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
256759  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
256760){
256761  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
256762}
256763static int fts5VocabCreateMethod(
256764  sqlite3 *db,                    /* Database connection */
256765  void *pAux,                     /* Pointer to tokenizer hash table */
256766  int argc,                       /* Number of elements in argv array */
256767  const char * const *argv,       /* xCreate/xConnect argument array */
256768  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
256769  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
256770){
256771  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
256772}
256773
256774/*
256775** Implementation of the xBestIndex method.
256776**
256777** Only constraints of the form:
256778**
256779**     term <= ?
256780**     term == ?
256781**     term >= ?
256782**
256783** are interpreted. Less-than and less-than-or-equal are treated
256784** identically, as are greater-than and greater-than-or-equal.
256785*/
256786static int fts5VocabBestIndexMethod(
256787  sqlite3_vtab *pUnused,
256788  sqlite3_index_info *pInfo
256789){
256790  int i;
256791  int iTermEq = -1;
256792  int iTermGe = -1;
256793  int iTermLe = -1;
256794  int idxNum = 0;
256795  int nArg = 0;
256796
256797  UNUSED_PARAM(pUnused);
256798
256799  for(i=0; i<pInfo->nConstraint; i++){
256800    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
256801    if( p->usable==0 ) continue;
256802    if( p->iColumn==0 ){          /* term column */
256803      if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
256804      if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
256805      if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
256806      if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
256807      if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
256808    }
256809  }
256810
256811  if( iTermEq>=0 ){
256812    idxNum |= FTS5_VOCAB_TERM_EQ;
256813    pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
256814    pInfo->estimatedCost = 100;
256815  }else{
256816    pInfo->estimatedCost = 1000000;
256817    if( iTermGe>=0 ){
256818      idxNum |= FTS5_VOCAB_TERM_GE;
256819      pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
256820      pInfo->estimatedCost = pInfo->estimatedCost / 2;
256821    }
256822    if( iTermLe>=0 ){
256823      idxNum |= FTS5_VOCAB_TERM_LE;
256824      pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
256825      pInfo->estimatedCost = pInfo->estimatedCost / 2;
256826    }
256827  }
256828
256829  /* This virtual table always delivers results in ascending order of
256830  ** the "term" column (column 0). So if the user has requested this
256831  ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
256832  ** sqlite3_index_info.orderByConsumed flag to tell the core the results
256833  ** are already in sorted order.  */
256834  if( pInfo->nOrderBy==1
256835   && pInfo->aOrderBy[0].iColumn==0
256836   && pInfo->aOrderBy[0].desc==0
256837  ){
256838    pInfo->orderByConsumed = 1;
256839  }
256840
256841  pInfo->idxNum = idxNum;
256842  return SQLITE_OK;
256843}
256844
256845/*
256846** Implementation of xOpen method.
256847*/
256848static int fts5VocabOpenMethod(
256849  sqlite3_vtab *pVTab,
256850  sqlite3_vtab_cursor **ppCsr
256851){
256852  Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
256853  Fts5Table *pFts5 = 0;
256854  Fts5VocabCursor *pCsr = 0;
256855  int rc = SQLITE_OK;
256856  sqlite3_stmt *pStmt = 0;
256857  char *zSql = 0;
256858
256859  if( pTab->bBusy ){
256860    pVTab->zErrMsg = sqlite3_mprintf(
256861       "recursive definition for %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
256862    );
256863    return SQLITE_ERROR;
256864  }
256865  zSql = sqlite3Fts5Mprintf(&rc,
256866      "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
256867      pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
256868  );
256869  if( zSql ){
256870    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
256871  }
256872  sqlite3_free(zSql);
256873  assert( rc==SQLITE_OK || pStmt==0 );
256874  if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
256875
256876  pTab->bBusy = 1;
256877  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
256878    i64 iId = sqlite3_column_int64(pStmt, 0);
256879    pFts5 = sqlite3Fts5TableFromCsrid(pTab->pGlobal, iId);
256880  }
256881  pTab->bBusy = 0;
256882
256883  if( rc==SQLITE_OK ){
256884    if( pFts5==0 ){
256885      rc = sqlite3_finalize(pStmt);
256886      pStmt = 0;
256887      if( rc==SQLITE_OK ){
256888        pVTab->zErrMsg = sqlite3_mprintf(
256889            "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
256890            );
256891        rc = SQLITE_ERROR;
256892      }
256893    }else{
256894      rc = sqlite3Fts5FlushToDisk(pFts5);
256895    }
256896  }
256897
256898  if( rc==SQLITE_OK ){
256899    i64 nByte = pFts5->pConfig->nCol * sizeof(i64)*2 + sizeof(Fts5VocabCursor);
256900    pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
256901  }
256902
256903  if( pCsr ){
256904    pCsr->pFts5 = pFts5;
256905    pCsr->pStmt = pStmt;
256906    pCsr->aCnt = (i64*)&pCsr[1];
256907    pCsr->aDoc = &pCsr->aCnt[pFts5->pConfig->nCol];
256908  }else{
256909    sqlite3_finalize(pStmt);
256910  }
256911
256912  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
256913  return rc;
256914}
256915
256916static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
256917  pCsr->rowid = 0;
256918  sqlite3Fts5IterClose(pCsr->pIter);
256919  sqlite3Fts5StructureRelease(pCsr->pStruct);
256920  pCsr->pStruct = 0;
256921  pCsr->pIter = 0;
256922  sqlite3_free(pCsr->zLeTerm);
256923  pCsr->nLeTerm = -1;
256924  pCsr->zLeTerm = 0;
256925  pCsr->bEof = 0;
256926}
256927
256928/*
256929** Close the cursor.  For additional information see the documentation
256930** on the xClose method of the virtual table interface.
256931*/
256932static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
256933  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
256934  fts5VocabResetCursor(pCsr);
256935  sqlite3Fts5BufferFree(&pCsr->term);
256936  sqlite3_finalize(pCsr->pStmt);
256937  sqlite3_free(pCsr);
256938  return SQLITE_OK;
256939}
256940
256941static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
256942  int rc = SQLITE_OK;
256943
256944  if( sqlite3Fts5IterEof(pCsr->pIter) ){
256945    pCsr->bEof = 1;
256946  }else{
256947    const char *zTerm;
256948    int nTerm;
256949    zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
256950    if( pCsr->nLeTerm>=0 ){
256951      int nCmp = MIN(nTerm, pCsr->nLeTerm);
256952      int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
256953      if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
256954        pCsr->bEof = 1;
256955      }
256956    }
256957
256958    sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
256959  }
256960  return rc;
256961}
256962
256963static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
256964  int eDetail = pCsr->pFts5->pConfig->eDetail;
256965  int rc = SQLITE_OK;
256966  Fts5IndexIter *pIter = pCsr->pIter;
256967  i64 *pp = &pCsr->iInstPos;
256968  int *po = &pCsr->iInstOff;
256969
256970  assert( sqlite3Fts5IterEof(pIter)==0 );
256971  assert( pCsr->bEof==0 );
256972  while( eDetail==FTS5_DETAIL_NONE
256973      || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp)
256974  ){
256975    pCsr->iInstPos = 0;
256976    pCsr->iInstOff = 0;
256977
256978    rc = sqlite3Fts5IterNextScan(pCsr->pIter);
256979    if( rc==SQLITE_OK ){
256980      rc = fts5VocabInstanceNewTerm(pCsr);
256981      if( pCsr->bEof || eDetail==FTS5_DETAIL_NONE ) break;
256982    }
256983    if( rc ){
256984      pCsr->bEof = 1;
256985      break;
256986    }
256987  }
256988
256989  return rc;
256990}
256991
256992/*
256993** Advance the cursor to the next row in the table.
256994*/
256995static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
256996  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
256997  Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
256998  int nCol = pCsr->pFts5->pConfig->nCol;
256999  int rc;
257000
257001  rc = sqlite3Fts5StructureTest(pCsr->pFts5->pIndex, pCsr->pStruct);
257002  if( rc!=SQLITE_OK ) return rc;
257003  pCsr->rowid++;
257004
257005  if( pTab->eType==FTS5_VOCAB_INSTANCE ){
257006    return fts5VocabInstanceNext(pCsr);
257007  }
257008
257009  if( pTab->eType==FTS5_VOCAB_COL ){
257010    for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
257011      if( pCsr->aDoc[pCsr->iCol] ) break;
257012    }
257013  }
257014
257015  if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){
257016    if( sqlite3Fts5IterEof(pCsr->pIter) ){
257017      pCsr->bEof = 1;
257018    }else{
257019      const char *zTerm;
257020      int nTerm;
257021
257022      zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
257023      assert( nTerm>=0 );
257024      if( pCsr->nLeTerm>=0 ){
257025        int nCmp = MIN(nTerm, pCsr->nLeTerm);
257026        int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
257027        if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
257028          pCsr->bEof = 1;
257029          return SQLITE_OK;
257030        }
257031      }
257032
257033      sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
257034      memset(pCsr->aCnt, 0, nCol * sizeof(i64));
257035      memset(pCsr->aDoc, 0, nCol * sizeof(i64));
257036      pCsr->iCol = 0;
257037
257038      assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
257039      while( rc==SQLITE_OK ){
257040        int eDetail = pCsr->pFts5->pConfig->eDetail;
257041        const u8 *pPos; int nPos;   /* Position list */
257042        i64 iPos = 0;               /* 64-bit position read from poslist */
257043        int iOff = 0;               /* Current offset within position list */
257044
257045        pPos = pCsr->pIter->pData;
257046        nPos = pCsr->pIter->nData;
257047
257048        switch( pTab->eType ){
257049          case FTS5_VOCAB_ROW:
257050            if( eDetail==FTS5_DETAIL_FULL ){
257051              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
257052                pCsr->aCnt[0]++;
257053              }
257054            }
257055            pCsr->aDoc[0]++;
257056            break;
257057
257058          case FTS5_VOCAB_COL:
257059            if( eDetail==FTS5_DETAIL_FULL ){
257060              int iCol = -1;
257061              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
257062                int ii = FTS5_POS2COLUMN(iPos);
257063                if( iCol!=ii ){
257064                  if( ii>=nCol ){
257065                    rc = FTS5_CORRUPT;
257066                    break;
257067                  }
257068                  pCsr->aDoc[ii]++;
257069                  iCol = ii;
257070                }
257071                pCsr->aCnt[ii]++;
257072              }
257073            }else if( eDetail==FTS5_DETAIL_COLUMNS ){
257074              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
257075                assert_nc( iPos>=0 && iPos<nCol );
257076                if( iPos>=nCol ){
257077                  rc = FTS5_CORRUPT;
257078                  break;
257079                }
257080                pCsr->aDoc[iPos]++;
257081              }
257082            }else{
257083              assert( eDetail==FTS5_DETAIL_NONE );
257084              pCsr->aDoc[0]++;
257085            }
257086            break;
257087
257088          default:
257089            assert( pTab->eType==FTS5_VOCAB_INSTANCE );
257090            break;
257091        }
257092
257093        if( rc==SQLITE_OK ){
257094          rc = sqlite3Fts5IterNextScan(pCsr->pIter);
257095        }
257096        if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;
257097
257098        if( rc==SQLITE_OK ){
257099          zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
257100          if( nTerm!=pCsr->term.n
257101          || (nTerm>0 && memcmp(zTerm, pCsr->term.p, nTerm))
257102          ){
257103            break;
257104          }
257105          if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
257106        }
257107      }
257108    }
257109  }
257110
257111  if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
257112    for(/* noop */; pCsr->iCol<nCol && pCsr->aDoc[pCsr->iCol]==0; pCsr->iCol++);
257113    if( pCsr->iCol==nCol ){
257114      rc = FTS5_CORRUPT;
257115    }
257116  }
257117  return rc;
257118}
257119
257120/*
257121** This is the xFilter implementation for the virtual table.
257122*/
257123static int fts5VocabFilterMethod(
257124  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
257125  int idxNum,                     /* Strategy index */
257126  const char *zUnused,            /* Unused */
257127  int nUnused,                    /* Number of elements in apVal */
257128  sqlite3_value **apVal           /* Arguments for the indexing scheme */
257129){
257130  Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
257131  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
257132  int eType = pTab->eType;
257133  int rc = SQLITE_OK;
257134
257135  int iVal = 0;
257136  int f = FTS5INDEX_QUERY_SCAN;
257137  const char *zTerm = 0;
257138  int nTerm = 0;
257139
257140  sqlite3_value *pEq = 0;
257141  sqlite3_value *pGe = 0;
257142  sqlite3_value *pLe = 0;
257143
257144  UNUSED_PARAM2(zUnused, nUnused);
257145
257146  fts5VocabResetCursor(pCsr);
257147  if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
257148  if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
257149  if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
257150
257151  if( pEq ){
257152    zTerm = (const char *)sqlite3_value_text(pEq);
257153    nTerm = sqlite3_value_bytes(pEq);
257154    f = FTS5INDEX_QUERY_NOTOKENDATA;
257155  }else{
257156    if( pGe ){
257157      zTerm = (const char *)sqlite3_value_text(pGe);
257158      nTerm = sqlite3_value_bytes(pGe);
257159    }
257160    if( pLe ){
257161      const char *zCopy = (const char *)sqlite3_value_text(pLe);
257162      if( zCopy==0 ) zCopy = "";
257163      pCsr->nLeTerm = sqlite3_value_bytes(pLe);
257164      pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
257165      if( pCsr->zLeTerm==0 ){
257166        rc = SQLITE_NOMEM;
257167      }else{
257168        memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
257169      }
257170    }
257171  }
257172
257173  if( rc==SQLITE_OK ){
257174    Fts5Index *pIndex = pCsr->pFts5->pIndex;
257175    rc = sqlite3Fts5IndexQuery(pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
257176    if( rc==SQLITE_OK ){
257177      pCsr->pStruct = sqlite3Fts5StructureRef(pIndex);
257178    }
257179  }
257180  if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
257181    rc = fts5VocabInstanceNewTerm(pCsr);
257182  }
257183  if( rc==SQLITE_OK && !pCsr->bEof
257184   && (eType!=FTS5_VOCAB_INSTANCE
257185    || pCsr->pFts5->pConfig->eDetail!=FTS5_DETAIL_NONE)
257186  ){
257187    rc = fts5VocabNextMethod(pCursor);
257188  }
257189
257190  return rc;
257191}
257192
257193/*
257194** This is the xEof method of the virtual table. SQLite calls this
257195** routine to find out if it has reached the end of a result set.
257196*/
257197static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
257198  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
257199  return pCsr->bEof;
257200}
257201
257202static int fts5VocabColumnMethod(
257203  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
257204  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
257205  int iCol                        /* Index of column to read value from */
257206){
257207  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
257208  int eDetail = pCsr->pFts5->pConfig->eDetail;
257209  int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
257210  i64 iVal = 0;
257211
257212  if( iCol==0 ){
257213    sqlite3_result_text(
257214        pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
257215    );
257216  }else if( eType==FTS5_VOCAB_COL ){
257217    assert( iCol==1 || iCol==2 || iCol==3 );
257218    if( iCol==1 ){
257219      if( eDetail!=FTS5_DETAIL_NONE ){
257220        const char *z = pCsr->pFts5->pConfig->azCol[pCsr->iCol];
257221        sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
257222      }
257223    }else if( iCol==2 ){
257224      iVal = pCsr->aDoc[pCsr->iCol];
257225    }else{
257226      iVal = pCsr->aCnt[pCsr->iCol];
257227    }
257228  }else if( eType==FTS5_VOCAB_ROW ){
257229    assert( iCol==1 || iCol==2 );
257230    if( iCol==1 ){
257231      iVal = pCsr->aDoc[0];
257232    }else{
257233      iVal = pCsr->aCnt[0];
257234    }
257235  }else{
257236    assert( eType==FTS5_VOCAB_INSTANCE );
257237    switch( iCol ){
257238      case 1:
257239        sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);
257240        break;
257241      case 2: {
257242        int ii = -1;
257243        if( eDetail==FTS5_DETAIL_FULL ){
257244          ii = FTS5_POS2COLUMN(pCsr->iInstPos);
257245        }else if( eDetail==FTS5_DETAIL_COLUMNS ){
257246          ii = (int)pCsr->iInstPos;
257247        }
257248        if( ii>=0 && ii<pCsr->pFts5->pConfig->nCol ){
257249          const char *z = pCsr->pFts5->pConfig->azCol[ii];
257250          sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
257251        }
257252        break;
257253      }
257254      default: {
257255        assert( iCol==3 );
257256        if( eDetail==FTS5_DETAIL_FULL ){
257257          int ii = FTS5_POS2OFFSET(pCsr->iInstPos);
257258          sqlite3_result_int(pCtx, ii);
257259        }
257260        break;
257261      }
257262    }
257263  }
257264
257265  if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
257266  return SQLITE_OK;
257267}
257268
257269/*
257270** This is the xRowid method. The SQLite core calls this routine to
257271** retrieve the rowid for the current row of the result set. The
257272** rowid should be written to *pRowid.
257273*/
257274static int fts5VocabRowidMethod(
257275  sqlite3_vtab_cursor *pCursor,
257276  sqlite_int64 *pRowid
257277){
257278  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
257279  *pRowid = pCsr->rowid;
257280  return SQLITE_OK;
257281}
257282
257283static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
257284  static const sqlite3_module fts5Vocab = {
257285    /* iVersion      */ 2,
257286    /* xCreate       */ fts5VocabCreateMethod,
257287    /* xConnect      */ fts5VocabConnectMethod,
257288    /* xBestIndex    */ fts5VocabBestIndexMethod,
257289    /* xDisconnect   */ fts5VocabDisconnectMethod,
257290    /* xDestroy      */ fts5VocabDestroyMethod,
257291    /* xOpen         */ fts5VocabOpenMethod,
257292    /* xClose        */ fts5VocabCloseMethod,
257293    /* xFilter       */ fts5VocabFilterMethod,
257294    /* xNext         */ fts5VocabNextMethod,
257295    /* xEof          */ fts5VocabEofMethod,
257296    /* xColumn       */ fts5VocabColumnMethod,
257297    /* xRowid        */ fts5VocabRowidMethod,
257298    /* xUpdate       */ 0,
257299    /* xBegin        */ 0,
257300    /* xSync         */ 0,
257301    /* xCommit       */ 0,
257302    /* xRollback     */ 0,
257303    /* xFindFunction */ 0,
257304    /* xRename       */ 0,
257305    /* xSavepoint    */ 0,
257306    /* xRelease      */ 0,
257307    /* xRollbackTo   */ 0,
257308    /* xShadowName   */ 0,
257309    /* xIntegrity    */ 0
257310  };
257311  void *p = (void*)pGlobal;
257312
257313  return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
257314}
257315
257316
257317
257318#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
257319
257320/************** End of fts5.c ************************************************/
257321/************** Begin file stmt.c ********************************************/
257322/*
257323** 2017-05-31
257324**
257325** The author disclaims copyright to this source code.  In place of
257326** a legal notice, here is a blessing:
257327**
257328**    May you do good and not evil.
257329**    May you find forgiveness for yourself and forgive others.
257330**    May you share freely, never taking more than you give.
257331**
257332*************************************************************************
257333**
257334** This file demonstrates an eponymous virtual table that returns information
257335** about all prepared statements for the database connection.
257336**
257337** Usage example:
257338**
257339**     .load ./stmt
257340**     .mode line
257341**     .header on
257342**     SELECT * FROM stmt;
257343*/
257344#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
257345#if !defined(SQLITEINT_H)
257346/* #include "sqlite3ext.h" */
257347#endif
257348SQLITE_EXTENSION_INIT1
257349/* #include <assert.h> */
257350/* #include <string.h> */
257351
257352#ifndef SQLITE_OMIT_VIRTUALTABLE
257353
257354
257355#define STMT_NUM_INTEGER_COLUMN 10
257356typedef struct StmtRow StmtRow;
257357struct StmtRow {
257358  sqlite3_int64 iRowid;                /* Rowid value */
257359  char *zSql;                          /* column "sql" */
257360  int aCol[STMT_NUM_INTEGER_COLUMN+1]; /* all other column values */
257361  StmtRow *pNext;                      /* Next row to return */
257362};
257363
257364/* stmt_vtab is a subclass of sqlite3_vtab which will
257365** serve as the underlying representation of a stmt virtual table
257366*/
257367typedef struct stmt_vtab stmt_vtab;
257368struct stmt_vtab {
257369  sqlite3_vtab base;  /* Base class - must be first */
257370  sqlite3 *db;        /* Database connection for this stmt vtab */
257371};
257372
257373/* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
257374** serve as the underlying representation of a cursor that scans
257375** over rows of the result
257376*/
257377typedef struct stmt_cursor stmt_cursor;
257378struct stmt_cursor {
257379  sqlite3_vtab_cursor base;  /* Base class - must be first */
257380  sqlite3 *db;               /* Database connection for this cursor */
257381  StmtRow *pRow;             /* Current row */
257382};
257383
257384/*
257385** The stmtConnect() method is invoked to create a new
257386** stmt_vtab that describes the stmt virtual table.
257387**
257388** Think of this routine as the constructor for stmt_vtab objects.
257389**
257390** All this routine needs to do is:
257391**
257392**    (1) Allocate the stmt_vtab object and initialize all fields.
257393**
257394**    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
257395**        result set of queries against stmt will look like.
257396*/
257397static int stmtConnect(
257398  sqlite3 *db,
257399  void *pAux,
257400  int argc, const char *const*argv,
257401  sqlite3_vtab **ppVtab,
257402  char **pzErr
257403){
257404  stmt_vtab *pNew;
257405  int rc;
257406
257407/* Column numbers */
257408#define STMT_COLUMN_SQL     0   /* SQL for the statement */
257409#define STMT_COLUMN_NCOL    1   /* Number of result columns */
257410#define STMT_COLUMN_RO      2   /* True if read-only */
257411#define STMT_COLUMN_BUSY    3   /* True if currently busy */
257412#define STMT_COLUMN_NSCAN   4   /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
257413#define STMT_COLUMN_NSORT   5   /* SQLITE_STMTSTATUS_SORT */
257414#define STMT_COLUMN_NAIDX   6   /* SQLITE_STMTSTATUS_AUTOINDEX */
257415#define STMT_COLUMN_NSTEP   7   /* SQLITE_STMTSTATUS_VM_STEP */
257416#define STMT_COLUMN_REPREP  8   /* SQLITE_STMTSTATUS_REPREPARE */
257417#define STMT_COLUMN_RUN     9   /* SQLITE_STMTSTATUS_RUN */
257418#define STMT_COLUMN_MEM    10   /* SQLITE_STMTSTATUS_MEMUSED */
257419
257420
257421  (void)pAux;
257422  (void)argc;
257423  (void)argv;
257424  (void)pzErr;
257425  rc = sqlite3_declare_vtab(db,
257426     "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
257427                    "reprep,run,mem)");
257428  if( rc==SQLITE_OK ){
257429    pNew = sqlite3_malloc64( sizeof(*pNew) );
257430    *ppVtab = (sqlite3_vtab*)pNew;
257431    if( pNew==0 ) return SQLITE_NOMEM;
257432    memset(pNew, 0, sizeof(*pNew));
257433    pNew->db = db;
257434  }
257435  return rc;
257436}
257437
257438/*
257439** This method is the destructor for stmt_cursor objects.
257440*/
257441static int stmtDisconnect(sqlite3_vtab *pVtab){
257442  sqlite3_free(pVtab);
257443  return SQLITE_OK;
257444}
257445
257446/*
257447** Constructor for a new stmt_cursor object.
257448*/
257449static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
257450  stmt_cursor *pCur;
257451  pCur = sqlite3_malloc64( sizeof(*pCur) );
257452  if( pCur==0 ) return SQLITE_NOMEM;
257453  memset(pCur, 0, sizeof(*pCur));
257454  pCur->db = ((stmt_vtab*)p)->db;
257455  *ppCursor = &pCur->base;
257456  return SQLITE_OK;
257457}
257458
257459static void stmtCsrReset(stmt_cursor *pCur){
257460  StmtRow *pRow = 0;
257461  StmtRow *pNext = 0;
257462  for(pRow=pCur->pRow; pRow; pRow=pNext){
257463    pNext = pRow->pNext;
257464    sqlite3_free(pRow);
257465  }
257466  pCur->pRow = 0;
257467}
257468
257469/*
257470** Destructor for a stmt_cursor.
257471*/
257472static int stmtClose(sqlite3_vtab_cursor *cur){
257473  stmtCsrReset((stmt_cursor*)cur);
257474  sqlite3_free(cur);
257475  return SQLITE_OK;
257476}
257477
257478
257479/*
257480** Advance a stmt_cursor to its next row of output.
257481*/
257482static int stmtNext(sqlite3_vtab_cursor *cur){
257483  stmt_cursor *pCur = (stmt_cursor*)cur;
257484  StmtRow *pNext = pCur->pRow->pNext;
257485  sqlite3_free(pCur->pRow);
257486  pCur->pRow = pNext;
257487  return SQLITE_OK;
257488}
257489
257490/*
257491** Return values of columns for the row at which the stmt_cursor
257492** is currently pointing.
257493*/
257494static int stmtColumn(
257495  sqlite3_vtab_cursor *cur,   /* The cursor */
257496  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
257497  int i                       /* Which column to return */
257498){
257499  stmt_cursor *pCur = (stmt_cursor*)cur;
257500  StmtRow *pRow = pCur->pRow;
257501  if( i==STMT_COLUMN_SQL ){
257502    sqlite3_result_text(ctx, pRow->zSql, -1, SQLITE_TRANSIENT);
257503  }else{
257504    sqlite3_result_int(ctx, pRow->aCol[i]);
257505  }
257506  return SQLITE_OK;
257507}
257508
257509/*
257510** Return the rowid for the current row.  In this implementation, the
257511** rowid is the same as the output value.
257512*/
257513static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
257514  stmt_cursor *pCur = (stmt_cursor*)cur;
257515  *pRowid = pCur->pRow->iRowid;
257516  return SQLITE_OK;
257517}
257518
257519/*
257520** Return TRUE if the cursor has been moved off of the last
257521** row of output.
257522*/
257523static int stmtEof(sqlite3_vtab_cursor *cur){
257524  stmt_cursor *pCur = (stmt_cursor*)cur;
257525  return pCur->pRow==0;
257526}
257527
257528/*
257529** This method is called to "rewind" the stmt_cursor object back
257530** to the first row of output.  This method is always called at least
257531** once prior to any call to stmtColumn() or stmtRowid() or
257532** stmtEof().
257533*/
257534static int stmtFilter(
257535  sqlite3_vtab_cursor *pVtabCursor,
257536  int idxNum, const char *idxStr,
257537  int argc, sqlite3_value **argv
257538){
257539  stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
257540  sqlite3_stmt *p = 0;
257541  sqlite3_int64 iRowid = 1;
257542  StmtRow **ppRow = 0;
257543
257544  (void)idxNum;
257545  (void)idxStr;
257546  (void)argc;
257547  (void)argv;
257548  stmtCsrReset(pCur);
257549  ppRow = &pCur->pRow;
257550  for(p=sqlite3_next_stmt(pCur->db, 0); p; p=sqlite3_next_stmt(pCur->db, p)){
257551    const char *zSql = sqlite3_sql(p);
257552    sqlite3_int64 nSql = zSql ? strlen(zSql)+1 : 0;
257553    StmtRow *pNew = (StmtRow*)sqlite3_malloc64(sizeof(StmtRow) + nSql);
257554
257555    if( pNew==0 ) return SQLITE_NOMEM;
257556    memset(pNew, 0, sizeof(StmtRow));
257557    if( zSql ){
257558      pNew->zSql = (char*)&pNew[1];
257559      memcpy(pNew->zSql, zSql, nSql);
257560    }
257561    pNew->aCol[STMT_COLUMN_NCOL] = sqlite3_column_count(p);
257562    pNew->aCol[STMT_COLUMN_RO] = sqlite3_stmt_readonly(p);
257563    pNew->aCol[STMT_COLUMN_BUSY] = sqlite3_stmt_busy(p);
257564    pNew->aCol[STMT_COLUMN_NSCAN] = sqlite3_stmt_status(
257565        p, SQLITE_STMTSTATUS_FULLSCAN_STEP, 0
257566    );
257567    pNew->aCol[STMT_COLUMN_NSORT] = sqlite3_stmt_status(
257568        p, SQLITE_STMTSTATUS_SORT, 0
257569    );
257570    pNew->aCol[STMT_COLUMN_NAIDX] = sqlite3_stmt_status(
257571        p, SQLITE_STMTSTATUS_AUTOINDEX, 0
257572    );
257573    pNew->aCol[STMT_COLUMN_NSTEP] = sqlite3_stmt_status(
257574        p, SQLITE_STMTSTATUS_VM_STEP, 0
257575    );
257576    pNew->aCol[STMT_COLUMN_REPREP] = sqlite3_stmt_status(
257577        p, SQLITE_STMTSTATUS_REPREPARE, 0
257578    );
257579    pNew->aCol[STMT_COLUMN_RUN] = sqlite3_stmt_status(
257580        p, SQLITE_STMTSTATUS_RUN, 0
257581    );
257582    pNew->aCol[STMT_COLUMN_MEM] = sqlite3_stmt_status(
257583        p, SQLITE_STMTSTATUS_MEMUSED, 0
257584    );
257585    pNew->iRowid = iRowid++;
257586    *ppRow = pNew;
257587    ppRow = &pNew->pNext;
257588  }
257589
257590  return SQLITE_OK;
257591}
257592
257593/*
257594** SQLite will invoke this method one or more times while planning a query
257595** that uses the stmt virtual table.  This routine needs to create
257596** a query plan for each invocation and compute an estimated cost for that
257597** plan.
257598*/
257599static int stmtBestIndex(
257600  sqlite3_vtab *tab,
257601  sqlite3_index_info *pIdxInfo
257602){
257603  (void)tab;
257604  pIdxInfo->estimatedCost = (double)500;
257605  pIdxInfo->estimatedRows = 500;
257606  return SQLITE_OK;
257607}
257608
257609/*
257610** This following structure defines all the methods for the
257611** stmt virtual table.
257612*/
257613static sqlite3_module stmtModule = {
257614  0,                         /* iVersion */
257615  0,                         /* xCreate */
257616  stmtConnect,               /* xConnect */
257617  stmtBestIndex,             /* xBestIndex */
257618  stmtDisconnect,            /* xDisconnect */
257619  0,                         /* xDestroy */
257620  stmtOpen,                  /* xOpen - open a cursor */
257621  stmtClose,                 /* xClose - close a cursor */
257622  stmtFilter,                /* xFilter - configure scan constraints */
257623  stmtNext,                  /* xNext - advance a cursor */
257624  stmtEof,                   /* xEof - check for end of scan */
257625  stmtColumn,                /* xColumn - read data */
257626  stmtRowid,                 /* xRowid - read data */
257627  0,                         /* xUpdate */
257628  0,                         /* xBegin */
257629  0,                         /* xSync */
257630  0,                         /* xCommit */
257631  0,                         /* xRollback */
257632  0,                         /* xFindMethod */
257633  0,                         /* xRename */
257634  0,                         /* xSavepoint */
257635  0,                         /* xRelease */
257636  0,                         /* xRollbackTo */
257637  0,                         /* xShadowName */
257638  0                          /* xIntegrity */
257639};
257640
257641#endif /* SQLITE_OMIT_VIRTUALTABLE */
257642
257643SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
257644  int rc = SQLITE_OK;
257645#ifndef SQLITE_OMIT_VIRTUALTABLE
257646  rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
257647#endif
257648  return rc;
257649}
257650
257651#ifndef SQLITE_CORE
257652#ifdef _WIN32
257653__declspec(dllexport)
257654#endif
257655SQLITE_API int sqlite3_stmt_init(
257656  sqlite3 *db,
257657  char **pzErrMsg,
257658  const sqlite3_api_routines *pApi
257659){
257660  int rc = SQLITE_OK;
257661  SQLITE_EXTENSION_INIT2(pApi);
257662#ifndef SQLITE_OMIT_VIRTUALTABLE
257663  rc = sqlite3StmtVtabInit(db);
257664#endif
257665  return rc;
257666}
257667#endif /* SQLITE_CORE */
257668#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
257669
257670/************** End of stmt.c ************************************************/
257671/* Return the source-id for this library */
257672SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
257673/************************** End of sqlite3.c ******************************/
257674